Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

@sysmanager/sys-skills

Package Overview
Dependencies
Maintainers
1
Versions
20
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@sysmanager/sys-skills - npm Package Compare versions

Package was removed
Sorry, it seems this package was removed from the registry
Comparing version
1.0.12
to
1.0.13
+175
skills/implement/architecture-review/SKILL.md
---
id: architecture-review
name: Architecture Review
description: "Skill para revisão arquitetural no Dual Code Review da Etapa 4 da fase Implement — componente de arquitetura do par (Opus arch + Correctness Codex). Usa CodiumAI PR-Agent (~20k★, Apache-2.0, ADO-nativo) + obra/superpowers/requesting-code-review + TLC stack (coding-guidelines + react-best-practices + modular-design-principles + security-best-practices). Atende o slot Implement E4 (code-reviewer — architecture) do framework AI-SDLC. Emite [VEREDITO] via comentário no WI ADO — nunca seta estado diretamente."
argument-hint: "review | arch | security | patterns"
metadata:
version: '1.0.0'
category: sdlc
dependencies: [harness-core]
requires: {}
tags: [architecture-review, dual-cr, code-review, codiumai, pr-agent, security, patterns, e4, implement-phase]
---
# Architecture Review — Implement E4 (Dual CR)
## Objetivo
Executar a **revisão arquitetural por PR** no Dual Code Review — verificar conformidade com Design Doc, padrões arquiteturais, segurança e manutenibilidade. O par complementar (`syscoe-correctness-codex`) cobre corretude funcional e BDD/DDD.
Slot atendido: **Implement E4 — code-reviewer (Architecture) — Dual CR**
**Winner v3:** CodiumAI PR-Agent (~20k★, Apache-2.0, ADO-nativo) + obra/superpowers `requesting-code-review` + TLC: `coding-guidelines` + `react-best-practices` + `react-composition-patterns` + `modular-design-principles` + `security-best-practices`
> **Dual CR = dois revisores em paralelo:** este agente (arquitetura) + `syscoe-correctness-codex` (corretude). Rodam sobre o mesmo PR, em janelas separadas. O orquestrador consolida os dois vereditos.
> **Regra inviolável:** nunca seta estado diretamente — emite `[VEREDITO]` como comentário no WI ADO; orquestrador transita.
---
## Quando Usar Esta Skill
- BUILD Gate (E3) verde: PR aberto, WIT em `Ready for Review` → `In Review`
- Roda em **paralelo com `syscoe-correctness-codex`**
- Foco: arquitetura, padrões, segurança, manutenibilidade (não corretude funcional BDD)
---
## Passo 1 — Descoberta de Contexto
Ler antes de revisar:
1. **Design Doc Enriquecido** — `design-doc-enriquecido.md`: padrões arquiteturais decididos nos Pilares 1-6
2. **ADRs do projeto** — `docs/adr/`: decisões arquiteturais que o código deve seguir
3. **CLAUDE.md** — stack, convenções, padrões de código
4. **Arquivos modificados** — `git diff` vs branch base
---
## Passo 2 — Checklist Arquitetural
### Conformidade com Design Doc
- [ ] Stack usada é a decidida no `design-doc-enriquecido.md` (Pilares 1-4)?
- [ ] Padrão de logging segue o definido (biblioteca + formato)?
- [ ] Padrão de tratamento de erros segue o definido?
- [ ] Boundaries de módulo respeitados (via `modular-design-principles`)?
- [ ] Granularidade arquitetural (F1/F2/F3/F4) mantida conforme Pilar 6?
### Qualidade do Código (via TLC `coding-guidelines`)
- [ ] Funções com responsabilidade única (SRP)?
- [ ] Nomes expressivos e consistentes com a UL?
- [ ] Sem god objects ou módulos com responsabilidade excessiva?
- [ ] Dependências declaradas explicitamente (sem acoplamento implícito)?
- [ ] Ausência de magic numbers e strings hardcoded?
### Segurança (via TLC `security-best-practices`)
- [ ] Input validation em todas as entradas externas (API, forms, CLI)?
- [ ] Sem secrets ou credenciais no código (`grep -r "password\|secret\|token" --include="*.ts"`)?
- [ ] Autorização verificada nos endpoints protegidos?
- [ ] Proteção contra injeção (SQL, XSS, command injection)?
- [ ] Comunicação via HTTPS/TLS onde necessário?
### Frontend (se aplicável — via TLC `react-best-practices` + `react-composition-patterns`)
- [ ] Componentes com responsabilidade única?
- [ ] State management conforme o padrão decidido (Zustand/Redux/Context)?
- [ ] Sem prop drilling excessivo (>3 níveis)?
- [ ] Composição preferida a herança?
- [ ] Performance: sem re-renders desnecessários (useCallback, useMemo quando justificado)?
---
## Passo 3 — Verificação de ADRs
Para cada ADR aprovado em `docs/adr/`, verificar se o código respeita a decisão:
```markdown
## Conformidade com ADRs
| ADR | Decisão | Código Respeita? |
|---|---|---|
| ADR-001 — PostgreSQL + Prisma | Usar Prisma como ORM | ✅ / ❌ `{arquivo:linha}` usa outro ORM |
| ADR-003 — JWT RS256 | Autenticação via JWT RS256 | ✅ / ❌ |
```
ADR violada = apontamento CRÍTICO.
---
## Passo 4 — CodiumAI PR-Agent (ADO-nativo)
Se CodiumAI PR-Agent está configurado no projeto ADO, invocar para análise complementar:
```bash
# CodiumAI analisa o PR e sugere melhorias
# Integração nativa com Azure DevOps Pull Requests
```
Incorporar sugestões relevantes do PR-Agent ao relatório de review.
---
## Passo 5 — Veredito Arquitetural
Emitir como comentário no WI ADO via `wit_add_work_item_comment`:
```markdown
## Architecture Review — {data}
**PR:** #{id}
**Work Item:** #{id ADO}
**Revisor:** Architecture Review (Opus)
### Conformidade com Design Doc: ✅ / ⚠️ / ❌
### Checklist Arquitetural: {N}/{total} itens OK
### Segurança: ✅ / ❌ ({N} vulnerabilidades)
### ADRs respeitadas: {N}/{total}
### Apontamentos Arquiteturais
#### Críticos (bloqueiam merge)
1. `{arquivo}:{linha}` — {problema arquitetural crítico}
#### Importantes (devem corrigir)
1. `{arquivo}:{linha}` — {problema de qualidade}
#### Informativos
1. {sugestão de melhoria sem bloqueio}
---
**[VEREDITO: APPROVED]**
— arquitetura conforme Design Doc, ADRs respeitadas, sem vulnerabilidades
**[VEREDITO: NEEDS REVISION — {lista}]**
— {N} problema(s) arquiteturais
**[VEREDITO: REJECTED — {motivo estrutural}]**
— violação grave de ADR ou segurança
```
---
## Passo 6 — Mapeamento Veredito → Transição (pelo orquestrador)
| Veredito (este) | Veredito (`syscoe-correctness-codex`) | Transição |
|---|---|---|
| APPROVED | APPROVED | WIT → `In Testing` |
| APPROVED | NEEDS REVISION | WIT → `Needs Revision` |
| NEEDS REVISION | qualquer | WIT → `Needs Revision` |
| REJECTED | qualquer | WIT → `Rejected` (após HITL) |
O orquestrador consolida os dois vereditos e executa a transição.
---
## Regras Invioláveis
- **NUNCA setar estado** — emitir veredito; orquestrador transita
- **ADR violada = CRÍTICO** — não negociável
- **Citar arquivo:linha** em todo apontamento — reviewer deve ser acionável
- **Não reduplica `syscoe-correctness-codex`** — este agente foca em arquitetura; BDD/DDD é papel do Codex
- **Modelo: Opus** — revisão arquitetural exige raciocínio profundo de trade-offs
---
id: build-gate
name: Build Gate
description: "Skill para execução do BUILD Gate na Etapa 3 da fase Implement — verifica sensores mecânicos, faz commit com Conventional Commits, atualiza progress.md e transita o WIT SDLC para Ready for Review. Usa obra/superpowers/execute-plan (121k★). Atende o slot Implement E3 (sonnet-builder BUILD Gate) do framework AI-SDLC. Delega operações git ao git-cli-manager via workflow canônico (7 steps). Builder NUNCA executa git diretamente."
argument-hint: "gate | commit | push | status"
metadata:
version: '1.0.0'
category: sdlc
dependencies: [harness-core, git-cli]
requires: {}
tags: [build-gate, commit, push, sensors, conventional-commits, progress, e3, implement-phase]
---
# Build Gate — Implement E3
## Objetivo
Garantir que o código de uma task está mecanicamente correto antes de subir para review — sensores verdes, commit canônico, `progress.md` atualizado e WIT SDLC transitado para `Ready for Review`.
Slot atendido: **Implement E3 — sonnet-builder (BUILD Gate)**
**Winner v3:** obra/superpowers `execute-plan` (121k★)
> **Regra inviolável:** o builder **NUNCA** executa `git` diretamente. Toda operação git é delegada ao workflow `git-cli-manager-build-gate` (7 steps). Isso evita bypasses de hooks, force-pushes acidentais e commits sem mensagem canônica.
---
## Quando Usar Esta Skill
- Ciclo TDD (E2) concluído: RED ✅ GREEN ✅ REFACTOR ✅
- Todos os sensores passando localmente
- Pronto para submeter a task para o Dual Code Review (E4)
---
## Passo 1 — Verificar Sensores Mecânicos
Antes de qualquer operação git, executar os sensores do projeto:
| Stack | Comandos |
|---|---|
| Node.js / TypeScript | `npm run lint && npm run typecheck && npm test -- --coverage` |
| Python | `ruff check . && mypy . && pytest --cov` |
| Go | `go vet ./... && go test -cover ./...` |
```markdown
## Verificação de Sensores
| Sensor | Status | Detalhes |
|---|---|---|
| Lint | ✅ / ❌ | {N} warnings / errors |
| Typecheck | ✅ / ❌ | {N} erros |
| Testes | ✅ / ❌ | {N} passing, {N} failing |
| Cobertura | ✅ / ❌ | {%}% (threshold: {%}%) |
```
Se qualquer sensor ❌ → **não invocar o workflow git**. Corrigir primeiro.
---
## Passo 2 — Invocar Workflow `git-cli-manager-build-gate`
Com sensores todos ✅, invocar o workflow canônico com os inputs:
```json
{
"epic_id": "{id do épico}",
"task_paths": ["{arquivo1}", "{arquivo2}"],
"task_summary": "{título da task — imperativo}",
"task_body": "Implementa {descrição}. Spec §{N}. BDD cenário {id}.",
"wit_sdlc_id": "{ID do WIT SDLC Implement no ADO}"
}
```
O workflow executa os 7 steps automaticamente:
| Step | Ação |
|---|---|
| 01 `verify-sensors` | Re-verifica linter + typecheck + testes |
| 02 `validate-working-tree` | Confirma que só os `task_paths` estão modificados |
| 03 `commit-task` | Commit com Conventional Commits + co-author trailer + scan de segredos |
| 04 `update-progress` | Append da entry da task em `progress.md` com SHA do step 03 |
| 05 `commit-progress` | Commit separado de `progress.md` (auditoria limpa) |
| 06 `push` | Push para origin (sem `--no-verify`, sem force) |
| 07 `transition-ado` | WIT SDLC `In Progress` → `Ready for Review` via `ado-board-manager` |
---
## Passo 3 — Formato do Commit (Conventional Commits)
O step 03 do workflow gera automaticamente, mas confirmar formato:
```
{type}({scope}): {descrição imperativa em inglês}
{body em pt-BR se necessário}
Spec §{N} — BDD {cenário-id}
Co-Authored-By: {modelo} <noreply@anthropic.com>
```
**Types válidos:** `feat`, `fix`, `test`, `refactor`, `docs`, `chore`, `perf`
Exemplos:
```
feat(payments): add PaymentOrder aggregate with balance validation
test(payments): add RED test for insufficient balance invariant
refactor(payments): extract balance check to domain service
```
---
## Passo 4 — Confirmar Output do Workflow
Após o workflow completar:
```markdown
## Build Gate — {task id} — {YYYY-MM-DD}
Step 01 verify-sensors: ✅
Step 02 validate-working-tree: ✅ ({N} arquivos)
Step 03 commit-task: ✅ SHA {hash}
Step 04 update-progress: ✅
Step 05 commit-progress: ✅ SHA {hash}
Step 06 push: ✅ origin/{branch}
Step 07 transition-ado: ✅ WIT #{id} → Ready for Review
Próximo: aguardar Dual Code Review (E4)
```
---
## Regras Invioláveis
- **NUNCA `git` direto** — sempre via workflow `git-cli-manager-build-gate`
- **NUNCA `--no-verify`** — hooks não podem ser bypassados
- **NUNCA `git add -A` ou `git add .`** — sempre paths explícitos em `task_paths`
- **NUNCA force-push em `main`/`master`** — erro crítico bloqueado pelo workflow
- **Sensores verdes antes do workflow** — se um sensor falha, corrigir; nunca commitar código com sensor vermelho
- **SHA do commit no `progress.md`** — rastreabilidade da task para o Dual CR
---
id: syscoe-acceptance-review-macro
name: SysCOE Acceptance Review Macro
description: "Skill composta SysManager para varredura sistêmica do delta completo de uma feature antes do merge, rodando na sub-etapa E6.A (Bridge to Production) da fase Implement com janela de 1M tokens. Atende o slot I-E5 acceptance-reviewer (GAP shrink) do framework AI-SDLC. Use quando o orquestrador da fase Implement ativa a sub-etapa 6.A após UAT (Etapa 5) aprovado — o agente lê TODOS os arquivos alterados pela feature em conjunto para detectar inconsistências entre tasks que o Dual CR por PR não alcança. Emite veredito Go/No-Go/Aceitar Debit. Composta de: TLC tlc-spec-driven (validate.md) + security-threat-model com wrapper SysManager (hidden-eval Gherkin, UL diff report, anti-collusion macro, varredura 1M tokens)."
argument-hint: "review | go | no-go | debit"
metadata:
version: '2.0.0'
category: sdlc
dependencies: [harness-core]
requires: {}
tags: [acceptance, macro-review, feature-delta, hidden-eval, ul-diff, anti-collusion, e6a, 1m-context, syscoe]
---
# SysCOE Acceptance Review Macro — Implement E6.A
## Objetivo
Fazer **varredura sistêmica única** do delta completo de uma feature — todos os arquivos novos e modificados pelas tasks, vistos em conjunto com 1M tokens de contexto — detectando problemas que nenhuma revisão isolada por PR consegue alcançar antes do merge para produção.
Slot atendido: **I-E5/E6.A acceptance-reviewer — sub-etapa Bridge to Production**
> **Posicionamento correto no ciclo:** esta skill roda em **E6.A**, após E5 (UAT behavioral + visual) já aprovado pelo Gate 5 humano. Não substitui o Dual CR (E4) nem o UAT (E5) — os complementa com visão macro da feature inteira.
---
## Por que este agente existe
O Dual CR (Etapa 4) avalia cada PR isolado. O UAT (Etapa 5) avalia comportamento por feature. Mas existe um gap crítico: **nenhum revisor viu o delta completo em conjunto**. Após fatiamento em sprints/tasks com sessões isoladas (<30% contexto por sessão), é possível que o conjunto integrado tenha:
- Task 3 quebrando silenciosamente contrato definido pela Task 1
- Padrões arquiteturais violados em pontos esparsos do delta
- Escopo negativo do PRD/Spec violado em algum lugar
- Lógica duplicada entre tasks que deveriam compartilhar helper
- Feature do PRD/Spec esquecida no conjunto
---
## Quando Usar Esta Skill
- Orquestrador ativa E6.A após Gate 5 (UAT) aprovado
- Work item Implement está em `In Validate`
- Todos os PRs da feature já passaram pelo Dual CR (E4) e UAT (E5)
- O delta completo da feature está disponível (arquivos no branch)
Não usar para:
- Revisar PR individual → usar `syscoe-correctness-codex` (E4 Dual CR)
- Fazer UAT por cenário → etapa E5 (behavioral + visual)
- Enriquecer spec → usar `syscoe-spec-enrich-adversarial` (Plan E3)
---
## Passo 1 — Coletar Entradas (janela limpa, 1M tokens)
Ler do zero, sem herdar contexto de sessões anteriores:
| Artefato | Localização | Propósito |
|---|---|---|
| `spec.md` (Spec Enriquecida) | `.specs/{epic-id}/spec.md` | Referência primária de comportamento esperado |
| `design-doc-enriquecido.md` | `.specs/research/design-doc-enriquecido.md` | Padrões arquiteturais a verificar |
| `prd.md` | `.specs/research/prd.md` | Escopo negativo + User Stories |
| `progress.md` | Raiz do repo | Decisões em tempo real durante Implement |
| `tasks.md` | `.specs/{epic-id}/tasks.md` | Tasks com DoD por cenário BDD |
| **Delta completo** | Todos arquivos novos/modificados pela feature | 50-200k tokens — ler tudo |
| Relatórios Dual CR | `review-arch.md` + `review-codex.md` por PR | Contexto dos problemas já tratados por PR |
| Relatórios UAT | `uat-behavioral.md` + `uat-visual.md` | Confirmação de comportamento por feature |
> **Usar a janela de 1M tokens integralmente.** Não economizar contexto — esse é o motivo deste agente existir.
---
## Passo 2 — Varredura Sistêmica (9 verificações)
### 2.1 — Cobertura Macro: PRD → Arquivos do Delta
Para cada feature/US do PRD, mapear quais arquivos do delta a implementam. Detectar:
- Feature do PRD com zero arquivos correspondentes no delta → **omissão crítica**
- Feature do PRD com implementação parcial → **cobertura incompleta**
### 2.2 — Inconsistências Entre Tasks
Verificar contratos definidos em uma task sendo violados por outra:
- Tipos exportados na Task X consumidos com assinatura errada na Task Y
- Constantes/enums definidos na Task A usados com valor diferente na Task B
- Decisões de design tomadas implicitamente em Task X conflitando com Task Y
### 2.3 — Auditoria de Escopo Negativo
O escopo negativo do PRD (§10 do Design Doc + seções `NOT` do PRD) foi respeitado em todo o delta?
- Endpoint criado que não deveria existir no MVP?
- Schema com coluna fora do escopo?
- Integração com terceiro não prevista?
### 2.4 — Lógica Duplicada
Funções/blocos similares em tasks diferentes que deveriam ser helper compartilhado. Indicador: blocos >5 linhas com lógica idêntica ou quase-idêntica em arquivos de tasks distintas.
### 2.5 — Conformidade com Padrões Arquiteturais
Decisões do `design-doc-enriquecido.md` (Tech Decisions Pilares 1-6) foram seguidas em **todos** os arquivos do delta?
- Padrão de logging diferente do definido?
- ORM diferente do escolhido?
- Fronteira de Bounded Context cruzada sem ACL?
### 2.6 — Cross-check com `progress.md`
Decisões tomadas em tempo real durante Implement (registradas em `progress.md`) que afetam a feature foram propagadas para todas as tasks dependentes?
### 2.7 — `hidden-eval/` (features Large+ e Complex)
Carregar cenários `.feature` de `.wiki-maintenance/hidden-eval/<bounded-context-da-feature>/`.
> **Regra de confidencialidade:** apenas este agente lê a pasta `hidden-eval/`. Builder e Dual CR não acessam. Se outro agente pediu o conteúdo → recusar e marcar cenário como `BURNED`.
Para cada cenário aplicável, confrontar com comportamento esperado do delta:
| Resultado | Ação |
|---|---|
| BC sem subpasta em `hidden-eval/` | Registrar `hidden-eval-status: skip-empty-bc`. Não bloqueia. |
| Subpasta sem cenário aplicável | Registrar `hidden-eval-status: skip-no-applicable-scenarios` + listar consultados. Não bloqueia. |
| Cenário aplicável e todos passam | Critério satisfeito. |
| Cenário aplicável e algum falha | **No-Go automático** — devolver para Etapa 4 (Dual CR). |
> Sem confronto OU registro explícito do motivo (`skip-*`) → degradação para LLM-as-judge regular sujeito a circular evaluation (Stanford CodeX 2026). Empty state é OK quando registrado; ausência silenciosa é anti-padrão.
### 2.8 — UL Diff Report: Spec → Implementação (features Medium+)
Comparar termos usados no delta com o glossário UL declarado em `spec.md §14`:
```markdown
## [UL DIFF REPORT — Spec → Implementação]
| Termo no Código | Equivalente na UL | Status |
|---|---|---|
| `paymentRecord` | `PaymentOrder` | ⚠️ Divergência léxica — usar termo canônico |
| `processPayment()` | `PaymentProcessed` (evento) | ❌ Tipo errado — evento, não método |
| `PaymentOrder` | `PaymentOrder` | ✅ Conforme |
```
Termo novo no código sem registro na UL = bloqueio (anti-padrão A7).
### 2.9 — Anti-Collusion Macro
Verificação macro complementar à do `code-reviewer` por PR:
- Autor dos cenários Gherkin (fase Plan) ≠ autor das implementações (fase Implement)?
- Mesma identidade em ambos os papéis = escalar para HITL para re-implementação por outro agente
---
## Passo 3 — Veredito Formal
```markdown
# Acceptance Review — [Feature/Epic]
**Data:** YYYY-MM-DD
**Work Item:** #{id ADO}
**Modelo:** Claude Opus 4.6 (1M context, janela limpa)
**Delta lido:** {N} arquivos, ~{N} tokens
## Verificações
| Verificação | Resultado | Severidade |
|---|---|---|
| 2.1 Cobertura PRD → Delta | ✅ / ❌ | Crítica / Não-crítica |
| 2.2 Inconsistências entre tasks | ✅ / ❌ | Crítica / Não-crítica |
| 2.3 Escopo negativo | ✅ / ❌ | Crítica / Não-crítica |
| 2.4 Lógica duplicada | ✅ / ⚠️ | Não-crítica / Informativa |
| 2.5 Padrões arquiteturais | ✅ / ❌ | Crítica / Não-crítica |
| 2.6 Cross-check progress.md | ✅ / ⚠️ | Não-crítica |
| 2.7 hidden-eval | ✅ / ❌ / skip-* | Crítica se falha |
| 2.8 UL diff report | ✅ / ⚠️ | Não-crítica |
| 2.9 Anti-collusion macro | ✅ / ❌ | Crítica |
## Apontamentos Detalhados
### Críticos (bloqueiam merge)
1. **[categoria]** {arquivo:linha} — {descrição} — {sugestão de fix}
### Não-críticos (aceitar como debit)
1. **[categoria]** {arquivo:linha} — {descrição}
## Veredito
**✅ Go** — feature integrada saudável. Autorizar merge.
**❌ No-Go** — {N} problema(s) crítico(s): {lista resumida}. Devolver para Etapa 4 (Dual CR).
**⚠️ Aceitar Debit** — sem bloqueadores críticos. Autorizar merge; registrar {N} débito(s) em `progress.md`.
```
---
## Passo 4 — Estados ADO — WIT SDLC Implement
| Momento | Estado ADO |
|---|---|
| E6.A inicia (work item em `In Validate`) | Mantém `In Validate` (categoria `InProgress`) |
| Veredito **Go** | Pipeline DoD promove para `Approved` (categoria `Resolved`) |
| Veredito **Aceitar Debit** | Mesmo caminho que Go; débitos registrados em `progress.md` |
| Veredito **No-Go** | Transita para `Needs Revision` → devolve para E4 (Dual CR) |
| Owner fecha | `Approved` → `Done` (categoria `Completed`) |
> **Anti-padrão:** este agente nunca seta `Done`, `Approved`, `In Testing` ou `In Progress` diretamente.
> **Frequência:** **uma vez por feature**. Se No-Go, esperar Dual CR aprovar novamente + UAT re-passar antes de re-rodar.
---
## Regras Invioláveis
- **Janela limpa obrigatória** — nunca herdar contexto do builder, Dual CR ou UAT
- **Ler delta inteiro** — a janela de 1M tokens existe para isso; não economizar contexto
- **`hidden-eval/` confidencial** — nunca expor conteúdo dos cenários a outros agentes; queimar cenário exposto
- **Veredito com 3 categorias** — sempre Go, No-Go ou Aceitar Debit; nunca veredito binário aprovado/rejeitado
- **Uma vez por feature** — não re-auditar delta corrigido sem Dual CR + UAT passarem primeiro
- **UL diff obrigatório para Medium+** — termo novo sem UL é bloqueio
- **Citar arquivo:linha** em todo apontamento — reviewer deve ser acionável
- **Idioma** — gerar no idioma da solicitação; termos técnicos e nomes de artefatos permanecem em inglês
---
id: syscoe-correctness-codex
name: SysCOE Correctness Codex
description: "Skill composta SysManager para code review de corretude na Etapa 4 do Implement (Dual Code Review), rodando por PR com foco em conformidade funcional com a Spec, anti-padrões BDD/DDD e UL diff report. Atende o slot I-E4 codex-correctness (GAP shrink) do framework AI-SDLC. Emite [VEREDITO: APPROVED/NEEDS REVISION/REJECTED] via comentário no WI ADO — nunca seta estado diretamente. Composta de: TLC coding-guidelines + the-fool com wrapper SysManager (A1 anti-collusion, A2 Gherkin imutável, A7 UL literal, UL diff report, trajectory metrics)."
argument-hint: "review | rescue | veredito"
metadata:
version: '2.0.0'
category: sdlc
dependencies: [harness-core]
requires: {}
tags: [code-review, dual-cr, correctness, bdd, ddd, anti-collusion, ul-diff, veredito, e4, syscoe]
---
# SysCOE Correctness Codex — Implement E4 (Dual CR)
## Objetivo
Executar o **Dual Code Review por PR** na Etapa 4 do Implement — revisar corretude funcional do código em relação à Spec e aos critérios de aceite BDD, com foco em anti-padrões que o CI não detecta (collusion, UL drift, Gherkin editado durante GREEN).
Slot atendido: **I-E4 codex-correctness — componente de corretude do Dual Code Review**
> **Dual CR = dois revisores em paralelo:** Opus (revisão arquitetural) + este agente (corretude funcional + BDD/DDD). Rodam sobre o mesmo PR, em janelas separadas, com vereditos independentes que o orquestrador consolida.
> **Regra inviolável:** este agente **emite veredito** como comentário no WI ADO. Nunca seta estado diretamente — o orquestrador (ou `syscoe-board-ado-pro` sob comando do orquestrador) executa a transição após receber o veredito.
---
## Quando Usar Esta Skill
- Orquestrador da fase Implement ativa a Etapa 4 (Dual CR) após BUILD Gate verde
- Work item Implement em `In Review` (após `Ready for Review` via BUILD Gate)
- Roda **uma vez por PR** — não uma vez por feature
Não usar para:
- Varredura macro do delta completo da feature → usar `syscoe-acceptance-review-macro` (E6.A)
- Revisar spec antes de implementar → usar `syscoe-spec-enrich-adversarial` (Plan E3)
- Código quebrado sem PR → ver modo `rescue`
---
## Passo 1 — Descoberta de Contexto
Antes de aplicar qualquer checklist, ler:
1. **Stack do projeto** — `README.md` + `package.json` / `pyproject.toml` / `go.mod`
2. **Code style** — `CLAUDE.md` do repo + config de lint (`.eslintrc`, `ruff.toml`)
3. **Spec/design/tasks** — `.specs/{work-item-id}/spec.md`, `design-doc-enriquecido.md`, `tasks.md`
4. **Arquivos modificados** — git diff vs branch base ou lista de arquivos no PR
5. **Relatório do revisor arquitetural** (Opus) — se disponível, não reduplique apontamentos já cobertos
---
## Passo 2 — Checklist Funcional (DoD)
- [ ] Todos os critérios de aceite do work item foram atendidos
- [ ] A funcionalidade descrita funciona conforme `spec.md`
- [ ] Não introduz regressões em funcionalidades existentes (rodar suite de testes)
- [ ] Funciona em todos os ambientes suportados (temas, breakpoints, locales quando aplicável)
- [ ] Dados consistentes com modelo de dados do `design-doc-enriquecido.md`
- [ ] Inputs, outputs, filtros e interações funcionam conforme Spec
---
## Passo 3 — Checklist Técnico (DoR)
- [ ] Código segue code style do projeto (lint, formatter, docstrings onde requerido)
- [ ] Sem código morto, `console.log`/`print` ou TODOs esquecidos
- [ ] Sem vulnerabilidades evidentes (XSS, injection, secrets hardcoded)
- [ ] Responsividade e acessibilidade preservadas (roles ARIA, labels, navegação por teclado, contrast ratio)
- [ ] Funções/classes reutilizáveis e bem nomeadas (convenção do repo)
- [ ] Performance razoável (sem loops O(n²) desnecessários, sem DOM thrashing)
- [ ] Cobertura de testes mantida ou aumentada (verificar via `coverage`)
---
## Passo 4 — Checklist BDD/DDD (features Medium+)
Este checklist é **obrigatório** para features Medium+. Cada item com ❌ bloqueia automaticamente.
### A1 — Anti-Collusion
> "Autor do cenário (Plan) ≠ autor da implementação (Implement)"
- [ ] Verificar: quem escreveu os cenários Gherkin em `.specs/{work-item-id}/spec.md §11`?
- [ ] Verificar: quem fez os commits da implementação?
- [ ] Mesma identidade em ambos → `[VEREDITO: NEEDS REVISION]` automático + pedido de re-implementação por outro agente
### A2 — Gherkin Imutável Durante GREEN
> "Cenário Gherkin não pode ser editado entre o commit RED e o commit GREEN"
- [ ] Verificar via `git log --follow .specs/{work-item-id}/spec.md` (ou local equivalente do `.feature`)
- [ ] Diff do cenário entre commit RED e commit GREEN deve ser **zero**
- [ ] Mudança no cenário durante a implementação = test-fit → `[VEREDITO: NEEDS REVISION]` automático com motivo explícito
### A7 — UL Literal no Código
> "Identificadores no código usam termos do glossário UL literalmente, não sinônimos"
- [ ] Verificar: file names, function names, variable names, error messages usam termos de `spec.md §14` literalmente?
- [ ] Identificador semanticamente equivalente mas léxicamente divergente = bloqueio
- Ex: glossário UL tem `PaymentOrder` → código usa `paymentRecord` → bloqueio
- Ex: glossário UL tem `PaymentProcessed` (evento) → código tem `processPayment()` (método) → bloqueio
### Cobertura Cenário-a-Cenário
- [ ] Cada cenário Gherkin de `spec.md §11` tem ≥1 teste executável que:
- **Falha** sem o código sob review
- **Passa** com o código sob review
### Aggregate Respeitado (features Large+)
- [ ] Código não cruza fronteira de Bounded Context sem ACL declarada em `context-map.md`
---
## Passo 5 — Validações Automatizadas
Executar **antes** de emitir veredito:
| Stack | Comando |
|---|---|
| Node.js / TypeScript | `npm run lint && npm run type-check && npm test -- --coverage` |
| Python | `ruff check . && mypy . && pytest --cov` |
| Go | `go vet ./... && go test -cover ./...` |
Se testes falham → `[VEREDITO: NEEDS REVISION]` com saída completa dos testes.
---
## Passo 6 — UL Diff Report (obrigatório para Medium+)
```markdown
## [UL DIFF REPORT — Spec → Código]
| Identificador no Código | Termo na UL (spec.md §14) | Status |
|---|---|---|
| `PaymentOrder` | `PaymentOrder` | ✅ Conforme |
| `paymentRecord` | `PaymentOrder` | ❌ Divergência léxica — usar `PaymentOrder` |
| `processPayment()` | `PaymentProcessed` (evento) | ❌ Tipo errado — evento, não método |
| `UserAccount` | (ausente na UL) | ⚠️ Termo novo — adicionar à UL ou renomear |
```
Termo novo no código sem registro na UL = bloqueio (A7).
---
## Passo 7 — Veredito Formal
Emitir como comentário no WI ADO via `wit_add_work_item_comment`. Formato obrigatório:
```markdown
## Code Review — Correctness Codex
**Data:** YYYY-MM-DD
**PR:** #{id}
**Work Item:** #{id ADO}
**Testes executados:** ✅ lint + typecheck + {N} testes passando
### Checklist Funcional: ✅ / ❌ ({N} itens com problema)
### Checklist Técnico: ✅ / ❌ ({N} itens com problema)
### Checklist BDD/DDD: ✅ / ❌ ({N} bloqueios — apenas Medium+)
### UL Diff Report: ✅ / ⚠️ ({N} divergências)
### Problemas Encontrados
#### Críticos (bloqueiam merge)
1. `{arquivo}:{linha}` — **[A2]** Cenário Gherkin editado entre RED e GREEN. {descrição}
2. `{arquivo}:{linha}` — **[A7]** Divergência UL: código usa `paymentRecord`, UL define `PaymentOrder`
#### Não-críticos (recomendações)
1. `{arquivo}:{linha}` — {descrição}
### Trajectory Metrics (Galileo 2026)
- Commits descartados detectados: {N}
- Retries via Codex Rescue: {N}
- Decisões intermediárias em `progress.md`: {N}
---
**[VEREDITO: APPROVED]**
— todos os checklists passaram; testes verdes; sem bloqueios
**[VEREDITO: NEEDS REVISION — {lista sucinta dos itens}]**
— problema(s) pontuais; corrigir e re-submeter (loop max 2 — Gate 4.5)
**[VEREDITO: REJECTED — {motivo estrutural}]**
— abordagem viola design.md / escopo errado / mudança fora da Spec
```
---
## Passo 8 — Mapeamento Veredito → Transição (executada pelo orquestrador)
| Veredito | Transição executada pelo orquestrador |
|---|---|
| `[VEREDITO: APPROVED]` | WIT → `In Testing` + `Custom.QualityGate=Pending` → Etapa 5 (UAT) |
| `[VEREDITO: NEEDS REVISION]` | WIT → `Needs Revision` + `Custom.QualityGate=Needs Revision` (loop max 2) |
| `[VEREDITO: REJECTED]` | WIT → `Rejected` + `Custom.QualityGate=Rejected` (após HITL confirmar) |
> **Este agente nunca executa transições.** Emite o veredito; o orquestrador lê e aciona o `syscoe-board-ado-pro`.
---
## Modo Rescue (código quebrado sem PR)
Se invocado com argumento `rescue`:
1. Identificar o erro exato (stacktrace ou comportamento observado vs esperado)
2. Isolar o trecho problemático com localização `{arquivo}:{linha}`
3. Classificar causa raiz: lógica incorreta / null pointer / race condition / missing AC / etc.
4. Propor correção **mínima** (não refatorar além do escopo do bug)
5. Verificar que a correção não quebra nenhum outro cenário BDD
> Rescue não substitui spec — se o código quebrado porque a Spec está errada → escalar para `syscoe-spec-enrich-adversarial`.
---
## Regras Invioláveis
- **NUNCA setar estado diretamente** — emitir veredito via comentário ADO; orquestrador transita
- **NUNCA aprovar sem rodar testes** — auto-failure de code review
- **A2 é bloqueio automático** — cenário Gherkin editado durante GREEN = `NEEDS REVISION` sem exceção
- **A1 é bloqueio automático** — mesma identidade em Plan (cenários) e Implement (código) = `NEEDS REVISION`
- **UL DIFF REPORT obrigatório para Medium+** — sem o relatório, o veredito é inválido
- **Citar arquivo:linha** em todo problema — reviewer deve ser acionável
- **Roda por PR, não por feature** — a varredura macro da feature é responsabilidade do `syscoe-acceptance-review-macro` (E6.A)
- **Idioma** — gerar no idioma da solicitação; nomes de anti-padrões (A1, A2, A7) e estados ADO permanecem em inglês
---
id: syscoe-deploy-multi-target
name: SysCOE Deploy Multi-Target
description: "Skill composta SysManager para bridge de deploy na Etapa 6 da fase Implement — valida pré-condições, dispara pipeline canônico (Vercel ou Cloudflare), cria Agent Deployment WIT, executa smoke test pós-deploy e coleta Eval Run com métricas primárias em t+15min. Atende o slot I-E6 deploy-bridge do framework AI-SDLC. Use quando o orquestrador da fase Implement ativa a Etapa 6 (Bridge to Production) após Gate 5 (UAT) e Acceptance Review macro (E6.A) aprovados. Modelo recomendado: Sonnet (orquestração com tooling pesado). Composta de: Vercel MCP oficial + Cloudflare MCP oficial + TLC sentry (post-deploy)."
argument-hint: "deploy | vercel | cloudflare | rollback | status"
metadata:
version: '2.0.0'
category: sdlc
dependencies: [harness-core]
requires: {}
tags: [deploy, vercel, cloudflare, sentry, agent-deployment-wit, eval-run, smoke-test, e6, syscoe]
---
# SysCOE Deploy Multi-Target — Implement E6
## Objetivo
Executar o **Bridge to Production** da fase Implement: validar pré-condições, disparar pipeline de deploy governado, criar o Agent Deployment WIT, fazer smoke test com evidência e coletar métricas primárias de produção em t+15min antes de liberar o Gate 6.
Slot atendido: **I-E6 deploy-bridge (Etapa 6 — Implement)**
> **Modelo recomendado: Claude Sonnet** — orquestração de tooling pesado (Vercel MCP, Cloudflare MCP, healthchecks, ADO API). Não exige raciocínio profundo; Haiku é insuficiente para orquestração complexa, Opus é desnecessário.
> **Pattern HITL:** SRE + Owner aprovam intenção → este agente executa pipeline. Não decide unilateralmente sobre ir para produção.
---
## Quando Usar Esta Skill
- Orquestrador ativa Etapa 6 após:
- Gate 5 (UAT behavioral + visual) ✅ aprovado
- Acceptance Review macro (E6.A) com veredito **Go** ou **Aceitar Debit** ✅
- Pipeline DoD em `In Validate` ✅ verde
- Work item Implement em `In Validate` → `Approved` (após pipeline DoD)
Não usar para:
- Revisão de código antes do deploy → `syscoe-correctness-codex` (E4)
- Varredura macro da feature → `syscoe-acceptance-review-macro` (E6.A)
- Atualizar board ADO → delegar ao `syscoe-board-ado-pro`
---
## Passo 1 — Checklist de Pré-Deploy (Gate de Entrada)
Verificar **obrigatoriamente** antes de qualquer ação de deploy:
```markdown
## Checklist de Pré-Deploy
| Item | Status |
|---|---|
| Gate 5 (UAT) aprovado pelo HITL humano | ✅ / ❌ |
| Acceptance Review macro (E6.A) — veredito Go/Debit | ✅ / ❌ |
| Pipeline DoD (`In Validate`) verde | ✅ / ❌ |
| Smoke test em staging passou | ✅ / ❌ |
| Observabilidade habilitada (dashboards/alertas prontos) | ✅ / ❌ |
| Runbook atualizado para esta feature | ✅ / ❌ |
| `progress.md` atualizado com decisões finais | ✅ / ❌ |
| Secrets/variáveis de ambiente configurados no target | ✅ / ❌ |
```
Se qualquer item ❌ → **bloquear deploy** e informar ao orquestrador qual item pendente.
---
## Passo 2 — HITL de Intenção (SRE + Owner)
Apresentar resumo ao SRE e Owner antes de executar:
```
Intenção de deploy:
Feature: #{id ADO} — {título}
Target: {Vercel / Cloudflare / Ambos}
Ambiente: {staging / production}
Branch: {nome da branch}
Checklist de pré-deploy: ✅ Todos verdes
Confirmar deploy para produção? [s/n]
```
Só prosseguir após confirmação explícita.
---
## Passo 3 — Roteamento de Deploy
| Tipo de Projeto | Target |
|---|---|
| Next.js / React / Vue / Node API com SSR | **Vercel** |
| Workers / Edge Functions / D1 / R2 / Pages estáticas | **Cloudflare** |
| APIs de borda com latência < 50ms necessária | **Cloudflare Workers** |
Se não detectável automaticamente → perguntar ao orquestrador.
---
## Passo 4 — Execução do Deploy
### Deploy Vercel (via Vercel MCP)
1. `vercel projects list` — confirmar projeto correto
2. Executar deploy com variáveis de ambiente do ambiente-alvo
3. Aguardar URL de deploy
4. Registrar URL gerada
### Deploy Cloudflare (via Cloudflare MCP)
1. Verificar `wrangler.toml` — account_id, zone_id, name corretos
2. Executar D1 migrations se existirem (antes do código)
3. Publicar Worker/Pages com secrets do vault CF
4. Confirmar que rota está ativa
---
## Passo 5 — Smoke Test Pós-Deploy (com evidência obrigatória)
Executar verificações básicas e registrar evidência (log + status HTTP):
```markdown
## Smoke Test Pós-Deploy
| Verificação | Resultado | Evidência |
|---|---|---|
| Healthcheck endpoint (`/health` ou equivalente) | ✅ HTTP 200 | `curl -s {url}/health → {"status":"ok"}` |
| Endpoint principal da feature | ✅ HTTP 200 | `curl -s {url}/{rota} → {resposta esperada}` |
| Autenticação não quebrada | ✅ HTTP 401 para req sem token | `curl -s {url}/{rota-protegida} → 401` |
| Sem erros 5xx no log de deploy | ✅ 0 erros | Log: `{trecho do log confirmando}` |
```
Se qualquer verificação falha → acionar Rollback (Passo 8) imediatamente.
---
## Passo 6 — Agent Deployment WIT (RFC v0.3.1)
Criar ou atualizar o **Agent Deployment WIT** no ADO, associado ao deploy:
```
Tipo: Agent Deployment
Título: Deploy — {feature} — {ambiente} — {data}
Estado: Active
Campos:
- Feature vinculada: #{id Feature ADO}
- Work Item Implement: #{id WIT SDLC Implement}
- URL de deploy: {url}
- Ambiente: {staging / production}
- SHA do commit: {git sha}
- Data de deploy: {ISO timestamp}
```
> **Nota sobre `sys-ai-augmented`:** o Agent Deployment WIT faz parte do process `sys-ai-augmented` (RFC v0.3.1). Se o projeto usa apenas `gov-sys-manager` (sem `sys-ai-augmented` provisionado), registrar as informações como comentário no WIT SDLC Implement e marcar como `[PLANNED — Agent Deployment WIT não provisionado]`.
Delegar criação ao `syscoe-board-ado-pro` (Haiku).
---
## Passo 7 — Eval Run: Métricas em t+15min
Após deploy estável por 15 minutos (Gate SRE), coletar métricas primárias:
```markdown
## Eval Run — t+15min
**Feature:** #{id ADO} — {título}
**Deploy timestamp:** {ISO}
**Eval timestamp:** {ISO} (t+15min)
| Métrica | Valor Observado | SLO Definido | Status |
|---|---|---|---|
| Error rate (5xx) | {N}% | < 1% | ✅ / ❌ |
| P95 latência endpoint principal | {N}ms | < {N}ms | ✅ / ❌ |
| Throughput | {N} req/min | > {N} req/min | ✅ / ❌ |
| Alertas ativos (Sentry/OTel) | {N} alertas | 0 | ✅ / ❌ |
**Status:** ✅ Estável — Gate 6 liberado / ❌ Instável — acionar Rollback
```
Se métricas fora do SLO → acionar Rollback (Passo 8).
---
## Passo 8 — Rollback
Se smoke test falhar ou métricas de t+15min fora do SLO:
### Rollback Vercel
```
vercel rollback --prod {deployment-url-anterior}
```
Confirmar retorno ao estado anterior + smoke test de confirmação.
### Rollback Cloudflare
1. Identificar versão anterior no dashboard Workers
2. `wrangler rollback` para versão estável
3. Executar rollback de D1 migrations (se afetado)
4. Smoke test de confirmação
**SLA de Rollback:** ≤ 15 minutos da decisão.
Após rollback:
- Transitar WIT SDLC Implement para `Needs Revision`
- Registrar motivo do rollback em `progress.md`
- Notificar orquestrador e Owner
---
## Passo 9 — Atualização de `progress.md`
Registrar o deploy em `progress.md`:
```markdown
## Deploy — {data}
- Ambiente: {staging / production}
- Target: {Vercel / Cloudflare}
- URL: {url}
- SHA: {git sha}
- Smoke test: ✅ passou
- Eval Run t+15min: ✅ estável
- Agent Deployment WIT: #{id} (Active)
- Status: ✅ SUCESSO / ❌ ROLLBACK ({motivo})
```
---
## Passo 10 — Release Tag (Etapa 6 — Bridge to Production)
Ao confirmar deploy estável, criar tag semver via `git-cli-manager`:
```json
{
"name": "v{MAJOR}.{MINOR}.{PATCH}",
"message": "Release {descrição} — Epic #{epic-id}",
"ref": "HEAD"
}
```
Em seguida: `git-cli-manager push` com `{ remote: "origin", tags: true }`.
---
## Passo 11 — Estados ADO — WIT SDLC Implement
| Momento | Estado ADO |
|---|---|
| Pipeline DoD verde (após Gate 5 + E6.A Go) | `In Validate` → `Approved` (pipeline DoD) |
| Deploy + smoke test + t+15min ✅ | Mantém `Approved` |
| Owner fecha | `Approved` → `Done` (Owner — manual) |
| Rollback necessário | `Approved` → `Needs Revision` |
> **Anti-padrão:** pipeline DoD nunca seta `Done`; Owner sempre finaliza manualmente.
---
## Regras Invioláveis
- **Gate de intenção obrigatório** — SRE + Owner confirmam antes do deploy em produção
- **Smoke test com evidência** — log + status HTTP; sem evidência, o deploy não é considerado verificado
- **Eval Run t+15min antes de liberar Gate 6** — métricas fora do SLO acionam rollback automático
- **SLA de rollback ≤ 15min** — nenhuma instabilidade fica mais de 15 minutos sem rollback iniciado
- **`progress.md` atualizado** — o deploy deve estar registrado antes do Owner fechar o WIT
- **Modelo: Sonnet** — orquestração de tooling; Opus é desnecessário, Haiku é insuficiente
- **Idioma** — gerar no idioma da solicitação; nomes de campos ADO e termos técnicos de deploy em inglês
---
id: task-pickup-clean-session
name: Task Pickup — Clean Session
description: "Skill para inicialização de sessão limpa de Implement na Etapa 1 — carrega apenas o contexto mínimo necessário (<30% da janela) para executar uma task específica sem saturação de contexto. Usa TLC codenavi para navegação de codebase. Atende o slot Implement E1 (task-pickup) do framework AI-SDLC. Use no início de cada sessão de implementação para garantir foco e evitar alucinação por contexto poluído."
argument-hint: "pickup | next | resume"
metadata:
version: '1.0.0'
category: sdlc
dependencies: [harness-core]
requires: {}
tags: [task-pickup, clean-session, context-engineering, codenavi, e1, implement-phase]
---
# Task Pickup — Clean Session — Implement E1
## Objetivo
Iniciar cada sessão de implementação com **contexto mínimo e cirúrgico** — apenas o que o builder precisa para executar a task atual sem saturar a janela de contexto com artefatos desnecessários.
Slot atendido: **Implement E1 — task-pickup / sonnet-builder (sessão limpa)**
**Winner v3:** TLC: `codenavi` + Claude `/init` built-in
> **Regra de contexto:** usar <30% da janela disponível no início da sessão. Se o contexto passar de 30% durante a task, fechar e abrir nova sessão com apenas os arquivos relevantes ao próximo passo.
---
## Quando Usar Esta Skill
- No início de cada nova sessão de Implement (por task ou por grupo de tasks relacionadas)
- Ao retomar trabalho interrompido (resumir estado via `progress.md`)
- Após reset de contexto (sessão saturou os 30%)
---
## Passo 1 — Ler `bridge-handshake.md`
O `bridge-handshake.md` (gerado em Plan E6) define o contexto mínimo da sessão:
```markdown
## Carregamento de Sessão (de bridge-handshake.md)
Próxima Task: {id} — {título}
Bloco Spec: §{N} — "{âncora}"
Cenário BDD: Spec §11 — cenário {id}
DoD: {critério mecânico}
Estimativa: {N} SP
```
Se `bridge-handshake.md` não existe → bloquear e invocar `bridge-handshake` (Plan E6) primeiro.
---
## Passo 2 — Carregar Contexto Mínimo
Carregar **apenas** os seguintes arquivos, nesta ordem de prioridade:
```
1. CLAUDE.md (Rules — obrigatório)
2. .specs/{epic-id}/tasks.md (task atual + suas dependências diretas)
3. .specs/{epic-id}/spec.md (apenas §§ relevantes para a task)
4. progress.md (últimas 5 entradas — estado atual)
5. [arquivos de código relevantes] (via codenavi — descoberta cirúrgica)
```
**NÃO carregar no início da sessão:**
- PRD completo (2.000+ linhas)
- Spec completa (600-1500 linhas inteiras)
- Histórico completo de sessões anteriores
- Design Doc completo
---
## Passo 3 — Navegação do Codebase (via TLC codenavi)
Usar `codenavi` para descobrir o código relevante sem ler o repositório inteiro:
```bash
# Exemplos de uso do codenavi
codenavi find "PaymentOrder" # encontra onde a entidade está definida
codenavi deps "src/orders/order.ts" # lista dependências do arquivo
codenavi test "PaymentOrder" # encontra testes relacionados
```
Carregar apenas os arquivos retornados pelo codenavi que são relevantes para a task.
---
## Passo 4 — Verificar Estado Atual (progress.md)
Ler as últimas 5 entradas do `progress.md` para entender o estado:
```markdown
## Estado da Sessão (de progress.md)
Última task concluída: {id} — {título} (SHA: {hash})
Sensores: {verde/vermelho}
Próxima task: {id} — {título}
Bloqueios ativos: {nenhum / descrição}
```
Se houver bloqueio ativo → reportar ao orquestrador antes de iniciar nova task.
---
## Passo 5 — Confirmar Contexto e Iniciar
Apresentar resumo da sessão ao builder antes de iniciar:
```
Sessão de Implement — {data}
Épico: {nome} | Sprint: {N}
Task atual: {id} — {título}
Âncora na Spec: §{N} — "{trecho}"
Cenário BDD alvo: {id} — "{nome}"
DoD: {critério mecânico}
Arquivos carregados: {N} ({%}% da janela)
Status: ✅ Pronto para iniciar TDD Loop (E2)
```
---
## Regras Invioláveis
- **<30% de contexto** no início da sessão — sempre
- **`bridge-handshake.md` obrigatório** — sem ele, o builder não sabe qual task executar
- **codenavi antes de ler código** — nunca ler arquivos de código sem descoberta prévia via codenavi
- **progress.md atualizado** — verificar estado antes de iniciar; nunca assumir que o estado da sessão anterior está correto
- **Reset a 30%** — se o contexto saturar durante a task, fechar sessão e abrir nova com contexto mínimo para o próximo passo
---
id: tdd-loop
name: TDD Loop
description: "Skill para execução do ciclo TDD (RED → GREEN → REFACTOR) na Etapa 2 da fase Implement. Usa obra/superpowers/test-driven-development (121k★, MIT). Atende o slot Implement E2 (sonnet-builder) do framework AI-SDLC. Use para cada task atômica: escrever teste que falha (RED), implementar código mínimo para passar (GREEN), refatorar sem quebrar (REFACTOR). Aciona tdd-rescue se travar por >2 tentativas."
argument-hint: "red | green | refactor | rescue"
metadata:
version: '1.0.0'
category: sdlc
dependencies: []
requires: {}
tags: [tdd, test-driven, red-green-refactor, unit-test, implementation, e2, implement-phase]
---
# TDD Loop — Implement E2
## Objetivo
Executar o ciclo **RED → GREEN → REFACTOR** para cada task atômica — com o cenário BDD da Spec como guia, não o treinamento genérico do modelo.
Slot atendido: **Implement E2 — sonnet-builder (TDD Loop)**
**Winner v3:** obra/superpowers `test-driven-development` (121k★, MIT)
> **Regra inviolável:** o cenário Gherkin da Spec (§11) é a especificação do teste. **Nunca modificar o cenário** durante o ciclo GREEN — isso é o anti-padrão A2 (test-fit). Se o cenário parecer errado, parar e escalar.
---
## Quando Usar Esta Skill
- Sessão iniciada via `task-pickup-clean-session` (E1)
- Task atual definida, cenário BDD ID referenciado, DoD mecânico conhecido
- Sensores mecânicos do projeto acessíveis (lint, typecheck, testes)
---
## Passo 1 — RED: Escrever o Teste Que Falha
1. Ler o cenário BDD referenciado na task (Spec §11)
2. Traduzir o cenário para um teste executável no framework do projeto:
```typescript
// Exemplo: cenário "Pagamento rejeitado por saldo insuficiente"
describe('PaymentOrder', () => {
it('SHALL rejeitar pagamento quando saldo for insuficiente', () => {
// Given
const account = new Account({ balance: 50 })
const order = new PaymentOrder({ amount: 100 })
// When / Then
expect(() => account.process(order)).toThrow('Saldo insuficiente')
})
})
```
3. Executar o teste e confirmar que **falha** com o erro esperado (não por syntax error)
4. Commitar o teste RED: `test(scope): add failing test for {cenário BDD id}`
> **Anti-padrão A2:** nunca modificar o cenário Gherkin durante esta fase. Modificar o cenário para fazer o teste passar é test-fit — bloqueio automático no Dual CR.
---
## Passo 2 — GREEN: Implementar o Código Mínimo
Escrever o **mínimo de código** necessário para o teste passar:
1. Não antecipar features futuras
2. Não refatorar ainda — só fazer o teste ficar verde
3. Executar o teste e confirmar que **passa**
4. Verificar que testes existentes ainda passam (sem regressão)
> Se o teste não passa após 2 tentativas → acionar `tdd-rescue` (argumento `rescue`)
---
## Passo 3 — REFACTOR: Melhorar Sem Quebrar
Com o teste verde, refatorar o código para qualidade:
1. Eliminar duplicação (DRY)
2. Melhorar nomes (conforme Ubiquitous Language do glossário UL)
3. Extrair funções se necessário (SRP)
4. Verificar que todos os testes ainda passam após refatoração
> **UL literal:** identificadores no código devem usar termos do glossário UL (`spec.md §14`) literalmente. `paymentRecord` quando a UL define `PaymentOrder` = anti-padrão A7.
---
## Passo 4 — Completar o Ciclo
Ao completar RED → GREEN → REFACTOR para a task:
1. Executar sensores completos: `npm run lint && npm run typecheck && npm test`
2. Se todos passam → registrar em `progress.md`:
```markdown
## Task {id} — {título} — {YYYY-MM-DD}
Ciclos TDD: {N} (RED: {hash} | GREEN: {hash} | REFACTOR: {hash})
Cenário BDD: {id} — {status: PASS}
DoD: {checklist mecânico executado}
Sensores: lint ✅ typecheck ✅ tests ✅ coverage {N}%
Próxima task: {id}
```
3. Invocar `build-gate` (E3) para commit + push via workflow canônico
---
## Passo 5 — Quando Acionar `tdd-rescue`
Acionar `tdd-rescue` quando:
- Teste não passa após 2 implementações distintas
- Erro de compilação/typecheck que não consegue resolver
- Comportamento inesperado que não faz sentido com a Spec
```
Situação que requer rescue:
- Task: {id}
- Erro: {mensagem de erro}
- Tentativas: {N}
- Descrição: {o que foi tentado}
```
---
## Regras Invioláveis
- **Cenário BDD é a especificação** — nunca modificar o cenário para fazer o teste passar (A2)
- **UL literal nos identificadores** — código usa termos do glossário (A7)
- **Mínimo no GREEN** — não antecipar features no ciclo GREEN
- **Sensores antes do build-gate** — todos os sensores devem passar antes de invocar E3
- **Rescue após 2 falhas** — não persistir em ciclos de tentativa/erro; acionar tdd-rescue
---
id: tdd-rescue
name: TDD Rescue
description: "Skill para recuperação de TDD travado na Etapa 2 da fase Implement via diagnóstico heterogêneo Codex+GPT. Usa plugin local codex:rescue + codex:gpt-5-prompting. Atende o slot Implement E2 (codex-rescue) do framework AI-SDLC. Use quando o builder está travado por >2 tentativas no ciclo RED→GREEN — o Codex diagnostica a causa raiz e propõe uma abordagem alternativa com perspectiva diferente da família Claude."
argument-hint: "rescue | debug | diagnose"
metadata:
version: '1.0.0'
category: sdlc
dependencies: []
requires: {}
tags: [rescue, debugging, tdd-rescue, codex, heterogeneous, e2, implement-phase]
---
# TDD Rescue — Implement E2
## Objetivo
Desbloquear o builder quando o ciclo TDD está travado — usando **perspectiva heterogênea** (Codex GPT, família diferente de Claude) para diagnosticar a causa raiz e propor uma abordagem alternativa que o builder não identificou.
Slot atendido: **Implement E2 — codex-rescue (TDD Rescue)**
**Winner v3:** Plugin local `codex:rescue` + `codex:gpt-5-prompting`
> **Heterogeneidade deliberada:** se o builder é Claude (Sonnet), o rescue usa Codex (família diferente). Perspectivas distintas evitam o ciclo de "mesma família, mesmo erro" — o Codex não herda os vieses da tentativa anterior do Claude.
---
## Quando Usar Esta Skill
- Builder travado após ≥2 tentativas distintas no ciclo GREEN
- Erro de compilação, typecheck ou teste que não consegue resolver
- Comportamento inesperado que contradiz a Spec mas o código parece correto
**Acionar via:** `tdd-loop rescue` ou diretamente com argumento `rescue`
---
## Passo 1 — Coletar Contexto do Travamento
O builder deve fornecer:
```markdown
## Contexto para Rescue
**Task:** {id} — {título}
**Cenário BDD alvo:** {id} — "{nome do cenário}"
**Erro observado:**
```
{stacktrace ou mensagem de erro completa}
```
**O que foi tentado:**
1. Tentativa 1: {descrição da abordagem}
Resultado: {o que aconteceu}
2. Tentativa 2: {descrição da abordagem alternativa}
Resultado: {o que aconteceu}
**Código atual:**
```{linguagem}
{trecho relevante do código — função/classe problemática}
```
**Teste atual:**
```{linguagem}
{teste que deveria passar mas não passa}
```
```
---
## Passo 2 — Diagnóstico Heterogêneo (Codex GPT)
O Codex analisa o contexto com perspectiva nova:
```markdown
## Diagnóstico Codex
**Causa raiz identificada:** {análise da causa raiz}
**Por que as tentativas anteriores falharam:** {explicação}
**Abordagem alternativa:**
```{linguagem}
{código alternativo proposto}
```
**Por que esta abordagem deve funcionar:** {justificativa técnica}
**Riscos da abordagem:** {o que pode dar errado com esta solução}
```
---
## Passo 3 — Validar Proposta Contra Spec
Antes de aplicar a solução proposta pelo Codex, verificar:
1. A solução respeita o cenário BDD da Spec? (não modifica comportamento esperado)
2. A solução usa termos do glossário UL? (anti-padrão A7)
3. A solução não viola invariantes de domínio identificadas pelo Spec Enricher?
4. A solução é mínima? (não antecipa features fora do escopo da task)
Se alguma verificação falha → reportar ao orquestrador antes de aplicar.
---
## Passo 4 — Aplicar e Verificar
1. Aplicar a solução proposta
2. Executar o teste: deve passar agora
3. Executar sensores: lint + typecheck + todos os testes
4. Registrar em `progress.md`:
```markdown
## Rescue — Task {id} — {YYYY-MM-DD}
Causa raiz: {diagnóstico Codex}
Abordagem aplicada: {descrição}
Resultado: ✅ Teste verde | Sensores: lint ✅ typecheck ✅ tests ✅
Continuar com: tdd-loop (REFACTOR)
```
---
## Passo 5 — Escalar se Rescue Falhar
Se o rescue também não resolver:
```
Rescue sem sucesso após 1 ciclo.
Causa provável: a Spec pode estar incorreta ou incompleta para esta task.
Opções:
1. Escalar para plan-spec-enricher — a Spec precisa de revisão
2. Escalar para HITL — humano decide a abordagem
3. Registrar como bloqueio em progress.md e avançar para próxima task
```
Registrar o bloqueio no WIT SDLC Implement via `syscoe-board-ado-pro` (estado `Blocked`).
---
## Regras Invioláveis
- **Máximo 1 ciclo de rescue por task** — se o rescue falhar, escalar para humano
- **Heterogeneidade obrigatória** — rescue deve usar modelo de família diferente do builder
- **Não modificar o cenário BDD** — mesmo no rescue, o cenário é imutável (A2)
- **Validar contra Spec antes de aplicar** — solução do Codex pode ser correta tecnicamente mas incorreta para o domínio
- **Registrar causa raiz** — o diagnóstico deve ir para `progress.md` para o Dual CR ter contexto
---
id: visual-regression
name: Visual Regression
description: "Skill para UAT visual e testes de regressão visual na Etapa 5 da fase Implement. Usa Microsoft playwright-mcp oficial + TLC playwright-skill + TLC chrome-devtools (wrapper). Atende o slot Implement E5 (gemini-uat-visual) do framework AI-SDLC. Use quando o Dual CR (E4) aprova o PR e o orquestrador aciona o UAT visual — detecta regressões em UI, verifica acessibilidade e captura evidência (screenshots) para a Acceptance Review macro (E6.A)."
argument-hint: "test | regression | accessibility | capture | report"
metadata:
version: '1.0.0'
category: sdlc
dependencies: []
requires: {}
tags: [visual-regression, playwright, uat, accessibility, e2e, screenshots, e5, implement-phase]
---
# Visual Regression — Implement E5
## Objetivo
Detectar **regressões visuais e de acessibilidade** na UI após a implementação das tasks — usando Playwright para testes E2E e captura de screenshots como evidência para a Acceptance Review macro (E6.A).
Slot atendido: **Implement E5 — gemini-uat-visual (UAT Visual)**
**Winner v3:** Microsoft `playwright-mcp` oficial + TLC: `playwright-skill` + TLC: `chrome-devtools` (wrapper)
> **Nota sobre o modelo:** UAT visual pode usar Gemini Flash (visão rápida) ou Claude Sonnet para análise das screenshots. O MCP Playwright executa os testes; o modelo analisa os resultados visuais.
---
## Quando Usar Esta Skill
- Dual CR (E4) emitiu `[VEREDITO: APPROVED]`
- WIT Implement em `In Testing`
- Feature tem componentes de UI que podem ter regressão visual
- Roda em paralelo com UAT behavioral (testes funcionais)
Não usar para:
- Features sem UI (backend puro, workers, etc.) → marcar UAT visual como `N/A`
- Substituir testes unitários de componentes → visual regression é complementar
---
## Passo 1 — Identificar Cenários de Regressão
A partir do `tasks.md` e da Spec, identificar:
1. **Flows com UI modificada** — quais telas/componentes foram alterados pelas tasks desta feature?
2. **Flows críticos adjacentes** — quais flows existentes podem ter sido afetados por mudanças de CSS/layout compartilhado?
3. **Componentes novos** — quais componentes novos precisam de baseline visual?
---
## Passo 2 — Executar Testes Playwright (via playwright-mcp)
Para cada flow identificado:
```typescript
// Exemplo de teste Playwright (via playwright-skill TLC)
test('Visual — Dashboard após implementação de Pagamentos', async ({ page }) => {
await page.goto('/dashboard')
await expect(page).toHaveScreenshot('dashboard-baseline.png', {
threshold: 0.01 // 1% de diferença máxima aceita
})
})
test('Visual — Formulário de Pagamento', async ({ page }) => {
await page.goto('/payments/new')
await expect(page.locator('[data-testid="payment-form"]')).toHaveScreenshot('payment-form.png')
})
```
Executar via `playwright-mcp` com captura de screenshots comparativas:
- Screenshot atual vs baseline (se existir)
- Screenshot de estados: vazio, preenchido, erro, sucesso
---
## Passo 3 — Verificação de Acessibilidade (via chrome-devtools)
Para cada tela com UI nova ou modificada:
```markdown
## Auditoria de Acessibilidade — {tela/componente}
| Critério WCAG 2.1 AA | Status | Detalhes |
|---|---|---|
| Contraste de cores ≥ 4.5:1 | ✅ / ❌ | {elemento com problema} |
| Texto alternativo em imagens | ✅ / ❌ | {imagem sem alt} |
| Labels em inputs | ✅ / ❌ | {input sem label} |
| Navegação por teclado | ✅ / ❌ | {elemento não focável} |
| Hierarquia de headings | ✅ / ❌ | {H1 ausente / duplicado} |
| ARIA roles corretos | ✅ / ❌ | {role incorreto} |
```
**Severidade:**
- CRÍTICO: bloqueia UAT (ex: sem contraste, sem label em input obrigatório)
- IMPORTANTE: deve corrigir antes do merge
- MENOR: recomendação para próximo sprint
---
## Passo 4 — Relatório de Regressão Visual
```markdown
# Visual Regression Report — {feature}
**Data:** YYYY-MM-DD
**Work Item:** #{id ADO}
**Flows testados:** {N}
## Screenshots Comparativas
| Flow | Baseline | Atual | Delta | Status |
|---|---|---|---|---|
| Dashboard | {hash} | {hash} | {%}% | ✅ / ❌ |
| Payment Form | Novo | — | — | ✅ baseline criado |
| Checkout Flow | {hash} | {hash} | {%}% | ❌ regressão detectada |
## Regressões Visuais Detectadas
1. **{flow}** — {descrição da diferença visual}
- Screenshot: `{path/screenshot-diff.png}`
- Componente afetado: `{componente}`
- Causa provável: {diagnóstico}
## Auditoria de Acessibilidade
[resultado por tela — conforme Passo 3]
## Evidências
- Screenshots em: `.specs/{epic-id}/uat-visual/screenshots/`
## Recomendação
✅ UAT Visual APROVADO — sem regressões, acessibilidade OK
❌ UAT Visual REPROVADO — {N} regressão(ões) / {N} bloqueador(es) de acessibilidade
```
---
## Passo 5 — Estados ADO
| Momento | Estado |
|---|---|
| UAT Visual inicia (Dual CR aprovado) | WIT em `In Testing` |
| Testes executados, relatório gerado | `In Testing` |
| Gate 5 humano aprova UAT (behavioral + visual) | `In Testing` → `In Validate` |
| Regressão crítica detectada | `In Testing` → `Needs Revision` (volta E4) |
---
## Regras Invioláveis
- **Screenshots como evidência** — UAT visual sem screenshots não tem evidência; não aceito
- **CRÍTICO de acessibilidade = bloqueio** — WCAG AA não é opcional (padrão SysManager)
- **Baseline salvo** — screenshots de componentes novos devem ser salvos como baseline para futuros runs
- **N/A registrado explicitamente** — features sem UI devem registrar `visual-regression: N/A` no relatório; ausência silenciosa é anti-padrão
- **Threshold de 1%** — delta visual > 1% é regressão detectada (usar threshold menor para componentes críticos)
---
id: bridge-handshake-plan
name: Bridge Handshake — Plan to Implement
description: "Skill para transição da fase Plan para a fase Implement via handshake canônico — verifica sensores mecânicos, gera bridge-handshake.md com session-handoff STATE.md, committa progress.md e prepara worktrees. Atende o slot Plan E6 (plan-bridge-implementer) do framework AI-SDLC. Diferente do bridge-handshake (Research E6), este adiciona TLC tlc-spec-driven session-handoff e STATE.md complementar, além de verificação obrigatória dos sensores mecânicos do projeto antes de liberar Implement. Use quando o Sprint Validator (Plan E5) aprova o sprint plan e a fase Plan pode ser encerrada."
argument-hint: "check | generate | verify | finalize"
metadata:
version: '1.0.0'
category: sdlc
dependencies: [harness-core, git-cli]
requires: {}
tags: [bridge, handshake, plan-to-implement, session-handoff, state-md, sensors, worktrees, e6, plan-phase]
---
# Bridge Handshake — Plan to Implement — Plan E6
## Objetivo
Encerrar formalmente a fase Plan e preparar tudo que o builder precisa para iniciar a fase Implement com contexto mínimo e preciso — bridge-handshake.md como contrato verificável, STATE.md de session-handoff, sensores mecânicos verdes e worktrees prontos.
Slot atendido: **Plan E6 — plan-bridge-implementer**
**Winner v3:** gotalab/cc-sdd `phase-gate handoff` + TLC: `tlc-spec-driven session-handoff` (+ STATE.md complementar)
> **Diferença do `bridge-handshake` (Research E6):** este skill adiciona verificação obrigatória de sensores mecânicos, geração de STATE.md para session-handoff e configuração de worktrees por épico — elementos específicos da transição Plan → Implement que não existem na transição Research → Plan.
---
## Quando Usar Esta Skill
- Gate 5 (Sprint Validator — Plan E5) aprovado
- Sprint plan confirmado pelo PM/PO
- `tasks.md` com todas as tasks e DoD mecânico pronto
- Work item Plan em `In Validate` (pré-aprovação da Bridge)
---
## Passo 1 — Checklist de Completude Plan (obrigatório)
```markdown
## Checklist Bridge Plan → Implement
### Artefatos de Spec
- [ ] `spec.md` (Spec Enriquecida) aprovada no Gate 2.5 e commitada (SHA: {hash})
- [ ] `tasks.md` com tasks atômicas, DoD YAML mecânico, estimativas Fibonacci, tags [P]
- [ ] `tech-decisions-log.md` com todas as decisões dos Pilares 1-6
- [ ] `context-map.md` presente e commitado (features Large+)
- [ ] ADR drafts em `docs/adr/` commitados
### Work Items ADO
- [ ] PBIs criados no ADO (aprovados no Gate 4)
- [ ] Tasks criadas no ADO (aprovadas no Gate 4)
- [ ] Sprint plan configurado no ADO (iterações com tasks alocadas)
### Sprint Plan
- [ ] `sprint-capacity-report.md` aprovado no Gate 5
- [ ] Over-commitment resolvido (nenhum perfil > 115%)
- [ ] Pre-mortem executado com riscos registrados
### Infraestrutura
- [ ] Sensores mecânicos verdes (lint + typecheck + CI)
- [ ] Worktrees preparados (1 por épico com tag [P])
- [ ] Codex CLI acessível (para Rescue E2 e CR correctness E4)
- [ ] Observabilidade configurada (dashboards/alertas prontos)
```
Se qualquer item ❌ → bloquear Bridge e reportar ao orquestrador o item pendente.
---
## Passo 2 — Verificar Sensores Mecânicos
```bash
# Executar sensores do projeto
npm run lint # ou equivalente
npm run typecheck
gh run list --limit 3 --status completed # CI status
# Verificar cobertura mínima
npm test -- --coverage
```
```markdown
## Status dos Sensores
| Sensor | Status | Detalhes |
|---|---|---|
| Lint | ✅ / ❌ | {N} warnings |
| Typecheck | ✅ / ❌ | {N} erros |
| CI (último run) | ✅ / ❌ | {status + SHA} |
| Cobertura | ✅ / ❌ | {%}% |
```
**Sensor vermelho = Bridge bloqueada.** Não avançar com sensores falhando.
---
## Passo 3 — Gerar STATE.md (via TLC tlc-spec-driven session-handoff)
O STATE.md é o **ponto de reentrada de sessão** — o builder abre uma nova sessão de Implement, lê o STATE.md e sabe exatamente onde parou e o que fazer a seguir.
Gerar `_sys/core/STATE.md` (ou `.specs/{epic-id}/STATE.md`):
```markdown
# STATE — {épico/feature}
**Última atualização:** {ISO timestamp}
**Fase:** Plan → Implement (Bridge concluída)
**Sprint ativo:** {nome do sprint}
## Próxima Ação
**Task:** {id} — {título da primeira task do sprint}
**Âncora Spec:** §{N} — "{trecho âncora}"
**Cenário BDD:** Spec §11 — cenário {id} — "{nome}"
**DoD:** `{critério mecânico}`
**Estimativa:** {N} SP
**Worktree:** `.worktrees/{epic-id}/`
## Contexto Mínimo para Sessão (<30% da janela)
Carregar nesta ordem:
1. `CLAUDE.md` (Rules)
2. `.specs/{epic-id}/tasks.md` (task atual + deps diretas)
3. `.specs/{epic-id}/spec.md` §{seções relevantes}
4. `progress.md` (últimas 5 entradas)
NÃO carregar: PRD, Design Doc, histórico de sessões anteriores.
## Sprint Backlog
| Task | SP | [P]? | Status |
|---|---|---|---|
| {id} — {título} | {N} | ✅/❌ | Próxima |
| {id} — {título} | {N} | ✅ | Pendente |
## Bloqueios Ativos
{nenhum / descrição}
## Riscos do Pre-mortem
1. {risco 1} — Mitigação: {ação}
2. {risco 2} — Mitigação: {ação}
```
---
## Passo 4 — Gerar `bridge-handshake.md`
O contrato verificável mecanicamente pelo `harness-implement` ao iniciar:
```markdown
# Bridge Handshake — Plan → Implement
**Status:** ✅ Plan aprovado — Implement pode iniciar
**Data:** {YYYY-MM-DD}
**Aprovado por:** Gate 5 ({nome do PM/PO}) + Bridge E6
## Artefatos (com SHA para verificação)
| Artefato | Path | SHA | Status |
|---|---|---|---|
| Spec Enriquecida | `.specs/{epic-id}/spec.md` | {hash} | ✅ commitado |
| Tasks | `.specs/{epic-id}/tasks.md` | {hash} | ✅ commitado |
| Progress | `progress.md` | {hash} | ✅ commitado |
| STATE.md | `_sys/core/STATE.md` | {hash} | ✅ commitado |
| Sprint Plan ADO | Sprint {nome} | — | ✅ configurado |
## Sensores no Momento da Bridge
| Sensor | Status | SHA/Run |
|---|---|---|
| Lint | ✅ | — |
| Typecheck | ✅ | — |
| CI | ✅ | {run-id} |
| Cobertura | ✅ | {%}% |
## Worktrees Preparados
| Épico | Worktree Path | Branch | Tag [P]? |
|---|---|---|---|
| {épico 1} | `.worktrees/{id}/` | `feature/{id}` | ✅ |
| {épico 2} | `.worktrees/{id}/` | `feature/{id}` | ❌ |
## Instruções para o Builder
1. Ler `bridge-handshake.md` (este arquivo) ao iniciar
2. Ler `_sys/core/STATE.md` para identificar primeira task
3. Usar `task-pickup-clean-session` (E1) para iniciar sessão com <30% contexto
4. NUNCA executar `git` diretamente — sempre via `build-gate` (E3)
```
---
## Passo 5 — Commitar Artefatos de Bridge
Via `git-cli-manager`:
```
Commit: "chore(plan): bridge Plan→Implement — epic {id}"
Arquivos:
- bridge-handshake.md
- _sys/core/STATE.md
- progress.md (atualizado com entrada de Bridge)
```
---
## Passo 6 — Transitar WIT SDLC Plan
Via `syscoe-board-ado-pro` (Haiku):
```
WIT SDLC Plan #{id} → Approved
Comentário: "Bridge Plan→Implement concluída. Sensores verdes. Artefatos commitados (SHA: {hash}). Implement pode iniciar."
```
Owner fecha: `Approved` → `Done`.
---
## Estados ADO — WIT SDLC Plan
| Momento | Estado |
|---|---|
| Bridge E6 inicia | `In Validate` (mantém) |
| Checklist verde + sensores verdes + artefatos gerados | `In Validate` → `Approved` |
| Owner fecha | `Approved` → `Done` |
---
## Regras Invioláveis
- **Sensores mecânicos obrigatoriamente verdes** — Bridge não fecha com sensor vermelho; Implement herda o estado do repositório
- **STATE.md obrigatório** — sem ele, o builder não tem session-handoff e vai saturar contexto na primeira sessão
- **SHAs no bridge-handshake.md** — contrato sem SHA não é verificável mecanicamente pelo `harness-implement`
- **Worktree por épico [P]** — épicos paralelos precisam de worktrees isolados; sem worktree, não há paralelismo seguro
- **Rebote máximo 1x** — se durante esta Bridge se descobre que um BC está errado, pode rebotar para Research (1 rebote por épico); registrar como debt
---
id: create-adr
name: ADR Creator
description: Creates Architecture Decision Records (ADRs) to document significant architectural choices and their rationale for future team members. Use when the user says "write an ADR", "document this decision", "record why we chose X", "add an architecture decision record", "create an ADR for", or wants to capture the reasoning behind a technical choice so the team understands it later. Do NOT use when the decision hasn't been made yet (use create-rfc instead), for implementation planning (use technical-design-doc-creator), or for general documentation.
metadata:
version: '1.0.0'
category: documentation
dependencies: []
requires: {}
tags: [adr, architecture, decision-record, documentation]
---
# ADR Creator
You are an expert in creating Architecture Decision Records (ADRs) — concise, durable documents that capture the context, decision, and consequences of significant architectural choices so future team members understand *why* things are the way they are.
## When to Use This Skill
Use this skill when:
- User asks to "write an ADR", "create an ADR", "add an architecture decision record"
- User wants to "document why we chose X", "record this decision", "capture this architectural choice"
- A significant technical decision has been made (or is being finalized) and needs to be recorded
- The team wants to preserve the reasoning behind a choice for future engineers
- User asks "why did we choose X" and the answer should be written down permanently
Do NOT use for:
- Decisions not yet made — use `create-rfc` to drive the decision process first
- Implementation planning after the decision — use `technical-design-doc-creator`
- Simple configuration choices or trivial code decisions
- Meeting notes or general documentation
## ADR vs RFC — Critical Distinction
| Aspect | ADR | RFC |
|--------|-----|-----|
| **Timing** | Decision already made (or being finalized) | Before the decision (seeking input) |
| **Purpose** | Record for future team members | Proposal seeking approval |
| **Audience** | Engineers joining months or years later | Current stakeholders |
| **Length** | Short — 200–500 words | Long — thorough comparison |
| **Mutability** | Immutable — superseded, never edited | Iterative — evolves during review |
| **Tone** | Historical record | Deliberative proposal |
If the user says "I need to decide whether to do X" → use `create-rfc`.
If the user says "We decided to do X, let me document it" → use this skill.
## Language Adaptation
**CRITICAL**: Always generate the ADR in the **same language as the user's request**. Detect the language automatically.
- Keep technical terms in English when appropriate (e.g., "ADR", "API", "microservices")
- All section headers and content should be in the user's language
- Company/product names remain in original form
## ADR Format Selection
Three formats are widely used. Detect the right one from context, or ask:
| Format | Best For | Length |
|--------|----------|--------|
| **MADR** (Markdown ADR) | Teams that want structured options comparison | Medium |
| **Nygard** (original) | Minimal, fast recording; obvious decisions | Short |
| **Y-Statement** | Inline documentation, very compact contexts | One paragraph |
Default to **MADR** unless the user specifies otherwise or the decision is very simple.
---
## Interactive Workflow
### Step 1: Gather Context (if not provided)
If the user provides minimal context, use **AskQuestion** to collect essential information:
```json
{
"title": "ADR Information",
"questions": [
{
"id": "adr_decision",
"prompt": "What was the decision made? (e.g., 'Use PostgreSQL for primary storage')",
"options": [
{ "id": "free_text", "label": "I'll describe it in my next message" }
]
},
{
"id": "adr_format",
"prompt": "Which ADR format would you like to use?",
"options": [
{ "id": "madr", "label": "MADR — structured, with options comparison (recommended)" },
{ "id": "nygard", "label": "Nygard — minimal: Context / Decision / Consequences" },
{ "id": "y_statement", "label": "Y-Statement — single paragraph, very compact" }
]
},
{
"id": "adr_status",
"prompt": "What is the current status of this decision?",
"options": [
{ "id": "accepted", "label": "Accepted — decision is final" },
{ "id": "proposed", "label": "Proposed — decision is being finalized" },
{ "id": "deprecated", "label": "Deprecated — this approach is no longer recommended" },
{ "id": "superseded", "label": "Superseded — replaced by a newer decision" }
]
},
{
"id": "adr_supersedes",
"prompt": "Does this ADR supersede a previous decision?",
"options": [
{ "id": "yes", "label": "Yes — I'll provide the ADR number/title" },
{ "id": "no", "label": "No — this is a new decision" }
]
}
]
}
```
### Step 2: Validate Mandatory Fields
**MANDATORY fields — ask if missing**:
- **Decision title** (noun phrase, not a question — e.g., "Use Redis for session storage")
- **Date** of the decision (or today's date)
- **Status** (Accepted / Proposed / Deprecated / Superseded)
- **Context** — the forces, constraints, and situation that made this decision necessary
- **The decision itself** — what was chosen and why
- **Consequences** — what becomes easier, harder, or different as a result
**RECOMMENDED fields**:
- **Decision drivers** — the key criteria or constraints
- **Options considered** — what alternatives were evaluated
- **Pros/cons per option** — honest trade-off assessment
- **Decision outcome rationale** — why this option over the others
- **Links** — related ADRs, RFCs, tickets, or documentation
If any mandatory fields are missing, ask IN THE USER'S LANGUAGE before generating the document.
### Step 3: Assign ADR Number
Scan the existing ADR directory for the next sequential number:
1. Check if an ADR directory exists (`docs/adr/`, `docs/decisions/`, `.adr/`, or `adr/`)
2. Find the highest existing number
3. Assign the next number (e.g., if ADR-007 exists, this becomes ADR-008)
4. If no directory exists, start at ADR-001 and suggest creating the directory
### Step 4: Generate the ADR
Generate the ADR following the format selected in Step 1.
### Step 5: Offer File Placement
After generating, ask where to save it:
```
ADR Created: "ADR-{NNN}: {Title}"
Suggested file path: docs/adr/{NNN}-{kebab-case-title}.md
Would you like me to:
1. Save it to docs/adr/ (recommended convention)
2. Save it to a different location
3. Just show the content (I'll place it manually)
```
---
## Document Templates
### MADR Format (Default)
```markdown
# ADR-{NNN}: {Title}
- **Date**: YYYY-MM-DD
- **Status**: Accepted | Proposed | Deprecated | Superseded by [ADR-NNN]({link})
- **Deciders**: {who was involved in the decision}
- **Tags**: {optional: architecture, security, performance, database, etc.}
## Context and Problem Statement
{Describe the context and the problem or question that led to this decision.
2–4 sentences. What situation forced this choice?}
## Decision Drivers
- {Driver 1 — e.g., "Must support 10k concurrent users"}
- {Driver 2 — e.g., "Team has no Go experience"}
- {Driver 3 — e.g., "Must be deployable on-premise"}
## Considered Options
- {Option A}
- {Option B}
- {Option C — "Do nothing / status quo" when relevant}
## Decision Outcome
Chosen option: **"{Option A}"**, because {concise rationale tied to decision drivers}.
### Positive Consequences
- {Benefit 1}
- {Benefit 2}
### Negative Consequences
- {Trade-off 1 — be honest}
- {Trade-off 2}
## Pros and Cons of the Options
### {Option A} ✅ Chosen
- ✅ {Pro 1}
- ✅ {Pro 2}
- ❌ {Con 1}
### {Option B}
- ✅ {Pro 1}
- ❌ {Con 1}
- ❌ {Con 2}
### {Option C}
- ✅ {Pro 1}
- ❌ {Con 1}
## Links
- {Related ADR, RFC, ticket, or documentation}
- Supersedes: [ADR-{NNN}: {Title}]({link}) (if applicable)
- Superseded by: [ADR-{NNN}: {Title}]({link}) (if applicable)
```
---
### Nygard Format (Minimal)
```markdown
# ADR-{NNN}: {Title}
## Status
Accepted | Proposed | Deprecated | Superseded by ADR-{NNN}
## Context
{What is the situation that led to this decision?
What forces are at play — technical, business, organizational?
What constraints exist? 2–5 sentences.}
## Decision
{What did we decide to do?
State it directly, in active voice: "We will use X" or "We decided to adopt Y."
Include a brief rationale — why this option over the alternatives.}
## Consequences
{What becomes easier or better as a result?}
{What becomes harder or worse? Be honest about trade-offs.}
{What new concerns or constraints does this introduce?}
```
---
### Y-Statement Format (Compact)
```markdown
# ADR-{NNN}: {Title}
**Date**: YYYY-MM-DD | **Status**: Accepted
In the context of **{situation/use case}**,
facing **{concern or constraint}**,
we decided **{the option chosen}**,
to achieve **{quality attribute or goal}**,
accepting **{the downside or trade-off}**.
**Deciders**: {names or roles}
**Links**: {related ADRs, tickets}
```
---
## ADR Quality Checklist
Before finalizing, verify:
- [ ] **Title** is a noun phrase describing the decision (not a question, not a vague label)
- [ ] **Date** is included (decisions without dates lose context quickly)
- [ ] **Status** is set correctly — Accepted, Proposed, Deprecated, or Superseded
- [ ] **Context** explains the *forces* that made this decision necessary, not just what was done
- [ ] **Decision** is stated directly and tied to the context
- [ ] **Consequences** include honest trade-offs — not just positives
- [ ] **Options** (MADR format) include at least 2 alternatives actually considered
- [ ] **Supersedes / superseded by** links are included when applicable
- [ ] **File** follows naming convention: `NNN-kebab-case-title.md`
- [ ] **Number** is sequential in the ADR directory
---
## ADR File Naming Convention
```
docs/adr/
├── 001-use-postgresql-for-primary-storage.md
├── 002-adopt-event-driven-architecture.md
├── 003-replace-jenkins-with-github-actions.md ← supersedes ADR-001 if relevant
└── README.md ← optional index
```
- Zero-padded numbers: `001`, `002`, ... `099`, `100`
- Kebab-case title
- `.md` extension
- Common directories: `docs/adr/`, `docs/decisions/`, `adr/`, `.adr/`
---
## Common Anti-Patterns to Avoid
### Title as a Question
**BAD**: `# ADR-001: Should we use PostgreSQL?`
**GOOD**: `# ADR-001: Use PostgreSQL for Primary Storage`
Titles should record the decision, not the question. Future readers need to know *what was decided*, not what was considered.
---
### Vague Context
**BAD**:
```
We needed a database and chose PostgreSQL.
```
**GOOD**:
```
Our application requires a relational database with strong ACID guarantees.
The team has deep PostgreSQL experience. MySQL was evaluated but lacks
native support for JSONB columns, which our schema design requires.
Our cloud provider (AWS) offers managed PostgreSQL via RDS at acceptable cost.
```
Context should explain the *forces* — why wasn't the alternative obviously better?
---
### Consequences Without Trade-offs
**BAD**:
```
## Consequences
PostgreSQL is fast and reliable.
```
**GOOD**:
```
## Consequences
- Enables JSONB columns and advanced indexing for our query patterns
- Team expertise means fast onboarding and fewer operational surprises
- Adds operational burden compared to a managed NoSQL service
- Schema migrations require careful planning in a relational model
```
Honest trade-offs are what make ADRs valuable years later.
---
### Editing Instead of Superseding
**BAD**: Editing an old ADR to change the decision after the fact.
**GOOD**: Creating a new ADR with `Status: Superseded by ADR-{NNN}` on the old one and linking back.
ADRs are historical records. The old decision was correct *given what was known at the time*. Superseding preserves that context.
---
### Missing the "Why Not" Rationale
**BAD**:
```
## Decision
We will use Redis for session storage.
```
**GOOD**:
```
## Decision
We will use Redis for session storage. We considered storing sessions in PostgreSQL
(already in our stack) but Redis's built-in TTL support and in-memory performance
make it significantly better suited for high-frequency session reads. The operational
cost of an additional service is justified by the simplified session expiry logic.
```
The rationale is *why this option and not the others* — not just what was chosen.
---
## Important Notes
- **ADRs are immutable** — never edit the decision. Supersede with a new ADR.
- **Short is better** — 200–500 words is ideal. If it needs to be longer, move detail to a linked TDD or RFC.
- **Context ages** — always date the ADR; what seems obvious now won't be in 3 years.
- **Honest consequences** — a one-sided ADR loses credibility. Future engineers will hit the downsides regardless.
- **Link everything** — related ADRs, the RFC that drove the decision, tickets, PR references.
- **Language adaptation** — always write in the user's language.
- **Number sequentially** — check the directory before assigning a number.
## Example Prompts that Trigger This Skill
### English
- "Write an ADR for using PostgreSQL as our primary database"
- "Document our decision to adopt GraphQL"
- "Create an ADR for moving our frontend to Next.js"
- "I need to record why we chose Kafka over RabbitMQ"
- "Add an architecture decision record for our authentication approach"
### Portuguese
- "Escreva um ADR sobre a decisão de usar PostgreSQL"
- "Documente a decisão de adotar GraphQL no projeto"
- "Crie um ADR explicando por que escolhemos Kafka"
### Spanish
- "Escribe un ADR sobre la decisión de usar PostgreSQL"
- "Documenta la decisión de adoptar microservicios"
- "Crea un ADR explicando por qué elegimos Next.js"
---
id: create-prd
name: PRD Creator
description: |
Generates a detailed Product Requirements Document (PRD) in Markdown from an initial user prompt, using a clarifying-questions workflow suitable for a junior developer to implement.
**Use this skill when:**
- The user says "write a PRD", "create a PRD", "draft a PRD for feature X"
- The user says "escreva um PRD", "crie um PRD", "documento de requisitos do produto"
- A new feature needs scope, user stories, functional requirements, and success metrics captured *before* implementation
- The user wants a product-requirements artifact as input for task decomposition
**After the PRD is generated, the natural follow-up is `generate-tasks`**, which decomposes the PRD into actionable work items.
**Do NOT use for:**
- Architectural decisions already made — use `create-adr`
- Change proposals seeking stakeholder alignment — use `create-rfc`
- Implementation planning after scope is fixed — use `create-technical-design-doc`
metadata:
version: '1.0.0'
category: documentation
dependencies: []
requires: {}
tags: [prd, product, requirements, documentation]
---
# Rule: Generating a Product Requirements Document (PRD)
## Goal
Guide an AI assistant in creating a detailed Product Requirements Document (PRD) in Markdown format, based on an initial user prompt. The PRD should be clear, actionable, and suitable for a junior developer to understand and implement the feature.
## Process
1. **Receive Initial Prompt**: The user provides a brief description or request for a new feature.
2. **Ask Clarifying Questions**: Before writing the PRD, the AI must ask clarifying questions to gather enough detail. The goal is to understand the "what" and "why" of the feature, not necessarily the "how" (which the developer will figure out). Make sure to provide options in lists with letters/numbers so the user can reply easily with their selections.
3. **Generate PRD**: Based on the initial prompt and the user's answers to the clarifying questions, generate a PRD using the structure described below.
4. **Save PRD**: Save the generated document as `prd-[feature-name].md` inside the `/tasks` directory.
## Clarifying Questions (Examples)
The AI should adapt its questions based on the prompt, but here are some common areas to explore:
- **Problem/Goal**: "What problem does this feature solve for the user?" or "What is the main goal we want to achieve with this feature?"
- **Target User**: "Who is the primary user of this feature?"
- **Core Functionality**: "Can you describe the key actions a user should be able to perform with this feature?"
- **User Stories**: "Could you provide a few user stories? (e.g., As a [type of user], I want to [perform an action] so that [benefit].)"
- **Acceptance Criteria**: "How will we know when this feature has been successfully implemented? What are the main success criteria?"
- **Scope/Boundaries**: "Are there specific things this feature should *not* do (non-goals)?"
- **Data Requirements**: "What kind of data does this feature need to display or manipulate?"
- **Design/UI**: "Are there any design mockups or UI guidelines to follow?" or "Can you describe the desired look and feel?"
- **Edge Cases**: "Are there any edge cases or error conditions we should consider?"
## PRD Structure
The generated PRD should include the following sections:
1. **Introduction/Overview**: Briefly describe the feature and the problem it solves. State the goal.
2. **Goals**: List the specific, measurable goals for this feature.
3. **User Stories**: Detail the user narratives describing how the feature is used and the benefits.
4. **Functional Requirements**: List the specific behaviors the feature must have. Use clear, concise language (e.g., "The system must allow users to upload a profile picture."). Number these requirements.
5. **Non-Goals (Out of Scope)**: Clearly state what this feature will *not* include in order to manage scope.
6. **Design Considerations (Optional)**: Link to mockups, describe UI/UX requirements, or mention relevant components/styles if applicable.
7. **Technical Considerations (Optional)**: Mention known technical constraints, dependencies, or suggestions (e.g., "Should integrate with the existing Auth module").
8. **Success Metrics**: How will the success of this feature be measured? (e.g., "Increase user engagement by 10%", "Reduce support tickets related to X").
9. **Open Questions**: List remaining questions or areas that need further clarification.
## Target Audience
Assume the primary reader of the PRD is a **junior developer**. Therefore, requirements should be explicit, unambiguous, and avoid jargon where possible. Provide enough detail for them to understand the feature's purpose and the core logic.
## Output
- **Format**: Markdown (`.md`)
- **Location**: `/tasks/`
- **Filename**: `prd-[feature-name].md`
## Final Instructions
1. Do NOT start implementing the PRD
2. Make sure to ask the user clarifying questions
3. Take the user's answers to the clarifying questions and improve the PRD
## Next Steps
Once the PRD is generated and approved, the natural follow-up is to decompose it into a task list. Invoke the `generate-tasks` skill with this PRD as input — it will produce actionable work items derived directly from the functional requirements and user stories captured here.
# RFC Section Templates
Complete Markdown templates for each RFC section. Read this file when generating an RFC document.
---
## 1. Header & Metadata (MANDATORY)
```markdown
# RFC: [Clear, Action-Oriented Title]
| Field | Value |
|--------------|------------------------------------|
| **Impact** | HIGH / MEDIUM / LOW |
| **Status** | NOT STARTED / IN PROGRESS / COMPLETE |
| **Driver** | @Name — responsible for the proposal |
| **Approver** | @Name1, @Name2 — must approve before action |
| **Contributors** | @Name3, @Name4 — provide input |
| **Informed** | @Team, @Stakeholder — kept in the loop |
| **Due Date** | YYYY-MM-DD (or "TBD") |
| **Resources** | [Link to Jira], [Link to design], [Related RFC] |
| **Created** | YYYY-MM-DD |
| **Last Updated** | YYYY-MM-DD |
```
**RACI Guidance**:
- **Driver**: Owns the proposal, drives the process, implements the outcome
- **Approver**: Decision-maker(s) — must explicitly approve or reject
- **Contributors**: Provide expertise, review options, raise concerns
- **Informed**: Notified of the decision but don't need to act
**If missing**: Ask "Who is driving this proposal? Who needs to approve the final decision? Who should be consulted?"
---
## 2. Background (MANDATORY)
```markdown
## Background
[2-4 paragraphs describing the current state and why a decision is needed]
**Current State**:
What exists today? What system, process, or situation does this RFC address?
**Problem or Opportunity**:
What is the specific pain point, risk, or opportunity driving this RFC?
Include data or evidence where possible (e.g., "we're spending 10h/week on X" or "incident rate has doubled").
**Why Now**:
What makes this decision urgent or timely?
- Business driver (deadline, market change, regulatory requirement)
- Technical driver (scaling limit, security risk, accumulating debt)
- Team driver (onboarding friction, process inefficiency)
**What Happens If We Don't Decide**:
- [Consequence 1 — e.g., continued cost, growing risk]
- [Consequence 2 — e.g., missed opportunity]
```
**If unclear**: Ask "What is the current situation? Why is this decision needed now? What happens if we do nothing?"
---
## 3. Assumptions (MANDATORY)
```markdown
## Assumptions
[Explicit statements taken as true for this proposal to hold. If any assumption proves false, this RFC should be revisited.]
| # | Assumption | Owner | Confidence | Invalidation Trigger |
|---|------------|-------|------------|----------------------|
| 1 | [e.g., "Current traffic will not exceed 10k req/s in the next 12 months"] | @Name | High | If traffic projections change |
| 2 | [e.g., "The team has capacity to implement this in Q2"] | @Name | Medium | If Q2 roadmap changes |
| 3 | [e.g., "Vendor X's pricing remains stable"] | @Name | Low | If pricing changes >20% |
**Confidence levels**:
- **High** — backed by data or contractual guarantees
- **Medium** — reasonable expectation, but not verified
- **Low** — uncertain; decision may need revisiting if this assumption shifts
**If any assumption is invalidated**: The Driver is responsible for reassessing the RFC outcome and communicating changes to Approvers and Informed parties.
```
**If missing**: Ask "What are you taking for granted for this proposal to work? What would need to be true for the recommended option to succeed?"
---
## 4. Decision Criteria (MANDATORY)
```markdown
## Decision Criteria
[State how the decision will be made — before listing options. This prevents criteria from being chosen retroactively to justify a preferred option.]
The option chosen must best satisfy the following criteria, listed in order of priority:
| Priority | Criterion | Description | Weight |
|----------|-----------|-------------|--------|
| 1 | [e.g., Security compliance] | Must meet SOC 2 / GDPR requirements | Must-have |
| 2 | [e.g., Time to production] | Decision should enable delivery within Q2 | High |
| 3 | [e.g., Total cost of ownership] | Prefer lower long-term cost over short-term savings | High |
| 4 | [e.g., Team expertise] | Prefer technologies the team already knows | Medium |
| 5 | [e.g., Reversibility] | Prefer options that are easier to undo if wrong | Medium |
| 6 | [e.g., Vendor lock-in] | Avoid deep dependence on a single vendor | Low |
**Weight guidance**:
- **Must-have**: Non-negotiable. An option that fails this criterion is disqualified.
- **High**: Strong influence on the decision.
- **Medium**: Considered, but can be traded off.
- **Low**: Nice to have; tiebreaker only.
**Decision rule**: The recommended option is the one that satisfies all Must-haves and scores highest across High and Medium criteria. Explicitly call out trade-offs when no option wins on all criteria.
```
**If missing**: Ask "What matters most when choosing between options? Are there any hard requirements that would disqualify an option? How will you weigh speed vs cost vs risk?"
---
## 5. Relevant Data (RECOMMENDED)
```markdown
## Relevant Data
[Evidence, metrics, or research that informs the decision]
**Quantitative Data**:
- Current cost/time: [e.g., "$X/month", "Y hours/week"]
- Usage/adoption: [e.g., "Z% of users affected"]
- Frequency: [e.g., "N incidents per quarter"]
**Qualitative Data**:
- User/team feedback: [summary of pain points or requests]
- Prior attempts: [what was tried before, why it didn't work]
**External References**:
- Industry benchmarks or standards
- Vendor documentation or case studies
- Research papers or technical articles
```
---
## 6. Options Considered (MANDATORY — minimum 2)
For each option, use this template. Evaluate against the **Decision Criteria** defined above.
```markdown
## Options Considered
### Option 1: [Option Name] ⭐ (Recommended)
**Description**:
[Clear description of this approach in 1-3 paragraphs]
**How It Works**:
1. Step or component A
2. Step or component B
3. Step or component C
**Pros**:
- [Advantage 1 — be specific]
- [Advantage 2]
- [Advantage 3]
**Cons**:
- [Disadvantage 1 — be honest]
- [Disadvantage 2]
**Estimated Cost**: LARGE / MEDIUM / SMALL
- Effort: [X weeks / person-days]
- Financial: [$X/month] (if applicable)
- Risk: HIGH / MEDIUM / LOW
---
### Option 2: [Option Name]
**Description**:
[Clear description of this approach]
**How It Works**:
1. Step or component A
2. Step or component B
**Pros**:
- [Advantage 1]
- [Advantage 2]
**Cons**:
- [Disadvantage 1]
- [Disadvantage 2]
**Estimated Cost**: LARGE / MEDIUM / SMALL
- Effort: [X weeks / person-days]
- Financial: [$X/month] (if applicable)
- Risk: HIGH / MEDIUM / LOW
---
### Option 3: Do Nothing (always consider)
**Description**:
Maintain the status quo and accept the current situation.
**Pros**:
- No immediate cost or disruption
- No migration risk
**Cons**:
- [Consequence of inaction 1]
- [Consequence of inaction 2]
**Estimated Cost**: SMALL (upfront) / potentially LARGE (long-term)
```
**Option Comparison Matrix** (for 3+ options):
```markdown
## Options Comparison
| Criterion | Option 1 | Option 2 | Option 3 |
|------------------------|----------|----------|----------|
| Implementation effort | Medium | Low | None |
| Cost | $X/mo | $Y/mo | $Z/mo |
| Time to value | 4 weeks | 1 week | N/A |
| Risk | Low | Medium | High |
| Reversibility | Easy | Hard | N/A |
| Team impact | Minimal | Moderate | None |
**Recommended**: Option 1 because [brief rationale]
```
---
## 7. Action Items (MANDATORY)
```markdown
## Action Items
[What happens after the decision is made — tasks required to implement the chosen option]
| Action | Owner | Due Date | Status |
|--------|-------|----------|--------|
| [Task 1 — e.g., "Evaluate vendor X with a PoC"] | @Name | YYYY-MM-DD | NOT STARTED |
| [Task 2 — e.g., "Update runbook for new process"] | @Name | YYYY-MM-DD | NOT STARTED |
| [Task 3 — e.g., "Communicate decision to affected teams"] | @Name | YYYY-MM-DD | NOT STARTED |
| [Task 4 — e.g., "Create follow-up TDD for implementation"] | @Name | YYYY-MM-DD | NOT STARTED |
**Note**: If this RFC is approved, a Technical Design Document (TDD) may be needed to plan the implementation in detail.
```
---
## 8. Outcome (MANDATORY — filled after decision)
```markdown
## Outcome
**Decision**: [Option X was chosen / RFC was rejected / deferred]
**Decision Date**: YYYY-MM-DD
**Decided By**: @Approver1, @Approver2
**Rationale**:
[Why this option was chosen over the alternatives. Be specific — future readers need to understand the reasoning, especially if circumstances change.]
**Key Factors**:
- [Factor 1 that drove the decision]
- [Factor 2]
- [Factor 3]
**Conditions / Caveats** (if any):
- [e.g., "Approved for Q1 only, will be revisited in Q2"]
- [e.g., "Requires security review before implementation"]
**Follow-up**:
- [ ] Create TDD for implementation (if applicable)
- [ ] Update affected documentation
- [ ] Notify informed stakeholders of decision
- [ ] Schedule retrospective in [X months] to evaluate outcome
```
---
id: create-rfc
name: RFC Creator
description: Creates structured Request for Comments (RFC) documents for proposing and deciding on significant changes. Use when the user says "write an RFC", "create a proposal", "I need to propose a change", "draft an RFC", "document a decision", or needs stakeholder alignment before making a major technical or process decision. Do NOT use for TDDs/implementation docs (use technical-design-doc-creator instead), README files, or general documentation.
metadata:
version: '1.0.0'
category: documentation
dependencies: []
requires: {}
tags: [rfc, proposal, decision-making, stakeholder-alignment, documentation]
---
# RFC Creator
You are an expert in creating Request for Comments (RFC) documents that clearly communicate proposals, capture alternatives considered, and drive structured decision-making across teams.
## When to Use This Skill
Use this skill when:
- User asks to "write an RFC", "create an RFC", "draft a proposal", or "write a request for comments"
- User needs to propose a significant change and gather stakeholder feedback
- A major architectural, process, or product decision needs to be documented before acting
- User wants to align multiple teams or approvers before committing to a direction
- User asks to "document a decision" or "get buy-in" on a proposal
- User needs to compare options and record the chosen direction with rationale
Do NOT use for:
- Technical Design Documents focused on implementation (use `technical-design-doc-creator`)
- Simple meeting notes or summaries
- README files or API documentation
## Language Adaptation
**CRITICAL**: Always generate the RFC in the **same language as the user's request**. Detect the language automatically and generate all content in that language.
- Keep technical terms in English when appropriate (e.g., "API", "RFC", "rollback", "stakeholder")
- Company/product names remain in original language
- Use natural, professional language for the target language
## RFC vs TDD
| Aspect | RFC | TDD |
|--------|-----|-----|
| **Purpose** | Propose + decide | Design + plan implementation |
| **Audience** | Broad stakeholders, leadership | Engineering team |
| **Focus** | Should we do X? Which option? | How do we build X? |
| **Output** | Decision + rationale | Architecture + implementation plan |
| **Timing** | Before committing to a direction | After direction is decided |
Use RFC when the **decision itself** needs alignment. Use TDD when the decision is made and you need to document the **implementation approach**.
## Interactive Workflow
### Step 1: Gather Context (if not provided)
If the user provides no context, use **AskQuestion** to collect basic information:
```json
{
"title": "RFC Information",
"questions": [
{
"id": "rfc_topic",
"prompt": "What is the topic or change you want to propose?",
"options": [
{ "id": "free_text", "label": "I'll describe it below" }
]
},
{
"id": "rfc_impact",
"prompt": "What is the estimated impact of this change?",
"options": [
{ "id": "high", "label": "HIGH - affects multiple teams, systems, or users" },
{ "id": "medium", "label": "MEDIUM - affects one team or system" },
{ "id": "low", "label": "LOW - limited scope, easily reversible" }
]
},
{
"id": "rfc_urgency",
"prompt": "Is there a due date or urgency?",
"options": [
{ "id": "urgent", "label": "Yes, we need a decision soon" },
{ "id": "planned", "label": "Part of planned roadmap" },
{ "id": "open", "label": "No fixed deadline" }
]
},
{
"id": "rfc_options",
"prompt": "Do you have options/alternatives in mind?",
"options": [
{ "id": "yes", "label": "Yes, I have 2+ options to compare" },
{ "id": "one", "label": "I have a preferred option, need to document alternatives" },
{ "id": "no", "label": "No, need help structuring options" }
]
}
]
}
```
### Step 2: Validate Mandatory Fields
**MANDATORY fields — ask if missing**:
- RFC title (clear, action-oriented)
- Background / context (what is the current state and why this matters)
- Driver (who is proposing / responsible for the decision)
- Approver(s) (who needs to approve)
- Impact level (HIGH / MEDIUM / LOW)
- At least 1 explicit assumption (with confidence level)
- At least 2 decision criteria (with weights), stated before options
- At least 2 options considered (including "do nothing" when relevant)
- Recommended option with rationale tied back to the decision criteria
If any of these are missing, ask IN THE USER'S LANGUAGE before generating the document.
### Step 3: Detect RFC Type and Tailor Sections
| RFC Type | Additional Focus Areas |
|----------|----------------------|
| **Technical/Architecture** | System impact, migration path, technical risks |
| **Process/Workflow** | Team impact, adoption plan, rollback if process fails |
| **Product/Feature** | User impact, metrics, go/no-go criteria |
| **Vendor/Tool Selection** | Cost comparison, lock-in risk, evaluation criteria |
| **Policy/Compliance** | Regulatory requirements, audit trail, enforcement |
### Step 4: Generate RFC Document
Generate the RFC in Markdown following the templates below.
### Step 5: Offer Next Steps
After generating, offer:
```
RFC Created: "[Title]"
Sections included:
- Mandatory: Header & Metadata, Background, Assumptions, Decision Criteria, Options Considered, Action Items, Outcome
- Recommended: Relevant Data, Pros/Cons comparison, Cost estimate, Resources
Suggested next steps:
- Share with Contributors for feedback
- Set a decision deadline
- Schedule a review meeting with Approvers
- Link related Jira/Linear tickets
Would you like me to:
1. Add more options to compare?
2. Create a follow-up technical design doc (TDD) for implementation details?
3. Publish this to Confluence?
```
## Document Structure
### Mandatory Sections
1. **Header & Metadata**
2. **Background**
3. **Assumptions**
4. **Decision Criteria**
5. **Options Considered** (minimum 2)
6. **Action Items**
7. **Outcome**
### Recommended Sections
8. **Relevant Data** — metrics, research, evidence
9. **Pros and Cons** (per option)
10. **Estimated Cost** (effort/complexity/monetary)
11. **Resources** — links, references, prior art
---
## Section Templates
Read `references/section-templates.md` when generating an RFC document. It contains complete Markdown templates for all 11 sections (7 mandatory + 4 recommended) with examples and "if missing" prompts for each field.
---
## RFC Quality Checklist
Before finalizing, verify:
- [ ] **Title**: Clear, action-oriented, specific (not "RFC about the database")
- [ ] **Impact**: Assessed as HIGH / MEDIUM / LOW with justification
- [ ] **Background**: Current state + problem + why now + cost of inaction
- [ ] **Assumptions**: Explicit, with confidence levels and invalidation triggers
- [ ] **Decision Criteria**: Defined *before* options, with weights; Must-haves identified
- [ ] **Data**: At least some evidence supporting the need for change
- [ ] **Options**: Minimum 2 options (including "do nothing" for significant changes)
- [ ] **Options evaluated against criteria**: Not just pros/cons in isolation
- [ ] **Pros/Cons**: Honest assessment, not just selling one option
- [ ] **Cost**: Effort estimate for each option (even if rough)
- [ ] **RACI**: Driver, Approver(s), Contributors, Informed all identified
- [ ] **Action Items**: Concrete next steps after the decision
- [ ] **Outcome**: Left as placeholder to be filled when decision is made
---
## Common Anti-Patterns to Avoid
### Predetermined Conclusion Disguised as RFC
**BAD**:
```
We should use Kubernetes. Here are some reasons. Option 2 is to not use Kubernetes (obviously wrong).
```
**GOOD**:
```
Option 1: Adopt Kubernetes — [genuine pros and cons]
Option 2: Stick with Docker Compose — [genuine pros and cons]
Option 3: Move to managed container platform (ECS/Cloud Run) — [genuine pros and cons]
```
### Vague Background
**BAD**:
```
Our current deployment process has some issues.
```
**GOOD**:
```
Our current deployment process requires 45 minutes of manual steps and has caused 3 production incidents in the past quarter due to human error. The team spends ~8 hours/week on deployment-related tasks.
```
### Missing "Do Nothing" Option
Always include the status quo as an option for significant changes — it forces honest evaluation of whether action is truly needed.
### No Decision Criteria (or criteria defined after options)
**BAD**: Presenting options first, then listing criteria — which looks like the criteria were chosen to justify a preferred option.
**GOOD**: Define criteria with weights *before* listing options. Then evaluate each option against them explicitly. The recommendation section should reference which criteria drove the decision.
### Hidden or Unstated Assumptions
**BAD**:
```
We'll migrate to the new system over 6 months.
```
**GOOD**:
```
Assumption: The team has 2 engineers available for migration work in Q3.
Confidence: Medium. Invalidated if Q3 headcount changes.
```
Unstated assumptions become invisible time bombs. When the RFC outcome stops working six months later, no one can tell whether the decision was wrong or whether a hidden assumption was invalidated.
---
## Output Summary Format
After generating the RFC:
```
RFC Created: "[Title]"
Impact: HIGH / MEDIUM / LOW
Status: NOT STARTED
Sections included:
- Header & Metadata (Driver, Approver, Due Date)
- Background (current state, problem, why now)
- N options compared with pros/cons and cost estimates
- Action Items (M tasks identified)
- Outcome (placeholder — to be filled after decision)
Suggested next steps:
- Share with Contributors listed for feedback
- Set the decision meeting for [Due Date]
- Update Status to IN PROGRESS
Would you like me to add anything else?
```
---
## Important Notes
- **RFC is for decisions, not implementation** — once the RFC is decided, create a TDD for the implementation plan
- **Honest options are critical** — a one-sided RFC undermines trust and produces bad decisions
- **"Do nothing" is always an option** — helps assess whether change is truly worth it
- **Outcome section is filled after the fact** — leave as placeholder during drafting
- **Language adaptation** — always write in the user's language
- **Respect user's context** — if the user provides rich context, use it; don't ask for what's already given
- **Be concise in options** — focus on the decision factors, not implementation details
- **RFCs age** — date everything; decisions made without context become confusing later
## Example Prompts that Trigger This Skill
### English
- "Write an RFC for migrating our database from MySQL to PostgreSQL"
- "I need an RFC to propose moving from monolith to microservices"
- "Create a request for comments on our on-call rotation policy"
- "Draft an RFC comparing self-hosted vs managed Kafka"
- "I need to get approval to adopt a new design system"
### Portuguese
- "Escreva um RFC para migrar nosso banco de dados"
- "Preciso de um RFC para propor a adoção de uma nova ferramenta"
- "Crie um Request for Comments sobre nossa política de on-call"
- "Quero documentar a decisão de trocar de provedor de cloud"
### Spanish
- "Escribe un RFC para migrar nuestra infraestructura a la nube"
- "Necesito un RFC para proponer un cambio en el proceso de deploy"
- "Crea un Request for Comments sobre la adopción de un nuevo framework"
---
id: create-technical-design-doc
name: Technical Design Doc Creator
description: Creates comprehensive Technical Design Documents (TDD) with mandatory and optional sections through interactive discovery. Use when user asks to "write a design doc", "create a TDD", "technical spec", "architecture document", "RFC", "design proposal", or needs to document a technical decision before implementation. Do NOT use for README files, API docs, or general documentation (use docs-writer instead).
metadata:
version: '1.0.0'
category: documentation
dependencies: []
requires: {}
tags: [tdd, technical-design, architecture, documentation]
---
# Technical Design Doc Creator
You are an expert in creating Technical Design Documents (TDDs) that clearly communicate software architecture decisions, implementation plans, and risk assessments following industry best practices.
## When to Use This Skill
Use this skill when:
- User asks to "create a TDD", "write a design doc", or "document technical design"
- User asks to "criar um TDD", "escrever um design doc", or "documentar design técnico"
- Starting a new feature or integration project
- Designing a system that requires team alignment
- Planning a migration or replacement of existing systems
- User mentions needing documentation for stakeholder approval
- Before implementing significant technical changes
## Language Adaptation
**CRITICAL**: Always generate the TDD in the **same language as the user's request**. Detect the language automatically from the user's input and generate all content (headers, prose, explanations) in that language.
**Translation Guidelines**:
- Translate all section headers, prose, and explanations to match user's language
- Keep technical terms in English when appropriate (e.g., "API", "webhook", "JSON", "rollback", "feature flag")
- Keep code examples and schemas language-agnostic (JSON, diagrams, code)
- Company/product names remain in original language
- Use natural, professional language for the target language
- Maintain consistency in terminology throughout the document
**Common Section Header Translations**:
| English | Portuguese | Spanish |
| -------------------------- | ------------------------------- | ---------------------------- |
| Context | Contexto | Contexto |
| Problem Statement | Definição do Problema | Definición del Problema |
| Scope | Escopo | Alcance |
| Technical Solution | Solução Técnica | Solución Técnica |
| Risks | Riscos | Riesgos |
| Implementation Plan | Plano de Implementação | Plan de Implementación |
| Security Considerations | Considerações de Segurança | Consideraciones de Seguridad |
| Testing Strategy | Estratégia de Testes | Estrategia de Pruebas |
| Monitoring & Observability | Monitoramento e Observabilidade | Monitoreo y Observabilidad |
| Rollback Plan | Plano de Rollback | Plan de Reversión |
## Industry Standards Reference
This skill follows established patterns from:
- **Google Design Docs**: Context, Goals, Non-Goals, Design, Alternatives, Security, Testing
- **Amazon PR-FAQ**: Working Backwards - start with customer problem
- **RFC Pattern**: Summary, Motivation, Explanation, Alternatives, Drawbacks
- **ADR (Architecture Decision Records)**: Context, Decision, Consequences
- **SRE Book**: Monitoring, Rollback, SLOs, Observability
- **PCI DSS**: Security requirements for payment systems
- **OWASP**: Security best practices
## High-Level vs Implementation Details
**CRITICAL PRINCIPLE**: TDDs document **architectural decisions and contracts**, NOT implementation code.
### ✅ What to Include (High-Level)
| Category | Include | Example |
| ----------------- | ----------------------------- | --------------------------------------------------------------- |
| **API Contracts** | Request/Response schemas | `POST /subscriptions` with JSON body structure |
| **Data Schemas** | Table structures, field types | `BillingCustomer` table with fields: id, email, stripeId |
| **Architecture** | Components, data flow | "Frontend → API → Service → Stripe → Database" |
| **Decisions** | What technology, why chosen | "Use Stripe because: global support, PCI compliance, best docs" |
| **Diagrams** | Sequence, architecture, flow | Mermaid/PlantUML diagrams showing interactions |
| **Structures** | Log format, event schemas | JSON structure for structured logging |
| **Strategies** | Approach, not commands | "Rollback via feature flag" (not the curl command) |
### ❌ What to Avoid (Implementation Code)
| Category | Avoid | Why |
| ------------------------ | ---------------------------------------- | ------------------------------------------------- |
| **CLI Commands** | `nx db:generate`, `kubectl rollout undo` | Too specific, may change with tooling |
| **Code Snippets** | TypeScript/JavaScript implementation | Belongs in code, not docs |
| **Framework Specifics** | `@Injectable()`, `extends Repository` | Framework may change, decision is what matters |
| **File Paths** | `scripts/backfill-feature.ts` | Implementation detail, not architectural decision |
| **Tool-Specific Syntax** | NestJS decorators, TypeORM entities | Document pattern, not implementation |
### Examples: High-Level vs Implementation
#### ❌ BAD (Too Implementation-Specific)
````markdown
**Rollback Steps**:
```bash
curl -X PATCH https://api.launchdarkly.com/flags/FEATURE_X \
-H "Authorization: Bearer $API_KEY" \
-d '{"enabled": false}'
nx db:rollback billing
```
````
````
#### ✅ GOOD (High-Level Decision)
```markdown
**Rollback Steps**:
1. Disable feature flag via feature flag service dashboard
2. Revert database schema using down migration
3. Verify system returns to previous state
4. Monitor error rates to confirm rollback success
````
#### ❌ BAD (Implementation Code)
````markdown
**Service Implementation**:
```typescript
@Injectable()
export class CustomerService {
@Transactional({ connectionName: 'billing' })
async create(data: CreateCustomerDto) {
const customer = new Customer()
customer.email = data.email
return this.repository.save(customer)
}
}
```
````
````
#### ✅ GOOD (High-Level Structure)
```markdown
**Service Layer**:
- `CustomerService`: Manages customer lifecycle
- `create()`: Creates customer, validates email uniqueness
- `getById()`: Retrieves customer by ID
- `updatePaymentMethod()`: Updates default payment method
- All write operations use transactions to ensure data consistency
- Services call external Stripe API and cache results locally
````
### Guideline: Ask "Will This Change?"
Before adding detail to TDD, ask:
- **"If we change frameworks, does this detail still apply?"**
- YES → Include (it's an architectural decision)
- NO → Exclude (it's implementation detail)
- **"Can someone implement this differently and still meet the requirement?"**
- YES → Focus on the requirement, not the implementation
- NO → You might be too specific
**Goal**: TDD should survive implementation changes. If you migrate from NestJS to Express, or TypeORM to Prisma, the TDD should still be valid.
## Document Structure
### Mandatory Sections (Must Have)
These sections are **required**. If the user doesn't provide information, you **must ask** using AskQuestion tool:
1. **Header & Metadata**
2. **Context**
3. **Problem Statement & Motivation**
4. **Scope** (In Scope / Out of Scope)
5. **Technical Solution**
6. **Risks**
7. **Implementation Plan**
### Critical Sections (Ask if Missing)
These are **highly recommended** especially for:
- Payment integrations (Security is MANDATORY)
- Production systems (Monitoring, Rollback are MANDATORY)
- External integrations (Dependencies, Security)
8. **Security Considerations** (MANDATORY for payments/auth/PII)
9. **Testing Strategy**
10. **Monitoring & Observability**
11. **Rollback Plan**
### Suggested Sections (Offer to User)
Ask user: "Would you like to add these sections now or later?"
12. **Success Metrics**
13. **Glossary & Domain Terms**
14. **Alternatives Considered**
15. **Dependencies**
16. **Performance Requirements**
17. **Migration Plan** (if applicable)
18. **Open Questions**
19. **Roadmap / Timeline**
20. **Approval & Sign-off**
## Project Size Adaptation
Use this heuristic to determine project complexity:
### Small Project (< 1 week)
**Use sections**: 1, 2, 3, 4, 5, 6, 7, 9
**Skip**: Alternatives, Migration Plan, Approval
### Medium Project (1-4 weeks)
**Use sections**: 1-11, 15, 18
**Offer**: Success Metrics, Glossary, Alternatives, Performance
### Large Project (> 1 month)
**Use all sections** (1-20)
**Critical**: All mandatory + critical sections must be detailed
## Interactive Workflow
### Step 1: Initial Gathering
Use **AskQuestion** tool to collect basic information:
```json
{
"title": "TDD Project Information",
"questions": [
{
"id": "project_name",
"prompt": "What is the name of the feature/integration/project?",
"options": [] // Free text
},
{
"id": "project_size",
"prompt": "What is the expected project size?",
"options": [
{ "id": "small", "label": "Small (< 1 week)" },
{ "id": "medium", "label": "Medium (1-4 weeks)" },
{ "id": "large", "label": "Large (> 1 month)" }
]
},
{
"id": "project_type",
"prompt": "What type of project is this?",
"allow_multiple": true,
"options": [
{ "id": "integration", "label": "External integration (API, service)" },
{ "id": "feature", "label": "New feature" },
{ "id": "refactor", "label": "Refactoring/migration" },
{ "id": "infrastructure", "label": "Infrastructure/platform" },
{ "id": "payment", "label": "Payment/billing system" },
{ "id": "auth", "label": "Authentication/authorization" },
{ "id": "data", "label": "Data migration/processing" }
]
},
{
"id": "has_context",
"prompt": "Do you have a clear problem statement and context?",
"options": [
{ "id": "yes", "label": "Yes, I can provide it now" },
{ "id": "partial", "label": "Partially, need help clarifying" },
{ "id": "no", "label": "No, need help defining it" }
]
}
]
}
```
### Step 2: Validate Mandatory Information
Based on answers, check if user can provide:
**MANDATORY fields to ask if missing**:
- Tech Lead / Owner
- Team members
- Problem description (what/why/impact)
- What is in scope
- What is out of scope
- High-level solution approach
- At least 3 risks
- Implementation tasks breakdown
**Ask using AskQuestion or natural conversation IN THE USER'S LANGUAGE**:
**English Example**:
```
I need the following information to create the TDD:
1. **Problem Statement**:
- What problem are we solving?
- Why is this important now?
- What happens if we don't solve it?
2. **Scope**:
- What WILL be delivered in this project?
- What will NOT be included (out of scope)?
3. **Technical Approach**:
- High-level description of the solution
- Main components involved
- Integration points
Can you provide this information?
```
**Portuguese Example**:
```
Preciso das seguintes informações para criar o TDD:
1. **Definição do Problema**:
- Que problema estamos resolvendo?
- Por que isso é importante agora?
- O que acontece se não resolvermos?
2. **Escopo**:
- O que SERÁ entregue neste projeto?
- O que NÃO será incluído (fora do escopo)?
3. **Abordagem Técnica**:
- Descrição de alto nível da solução
- Principais componentes envolvidos
- Pontos de integração
Você pode fornecer essas informações?
```
### Step 3: Check for Critical Sections
Based on `project_type`, determine if critical sections are mandatory:
| Project Type | Critical Sections Required |
| ----------------- | ------------------------------------------ |
| `payment`, `auth` | **Security Considerations** (MANDATORY) |
| All production | **Monitoring & Observability** (MANDATORY) |
| All production | **Rollback Plan** (MANDATORY) |
| `integration` | **Dependencies**, **Security** |
| All | **Testing Strategy** (highly recommended) |
**If critical sections are missing, ASK IN THE USER'S LANGUAGE**:
**English**:
```
This is a [payment/auth/production] system. These sections are CRITICAL:
❗ **Security Considerations** - Required for compliance (PCI DSS, OWASP)
❗ **Monitoring & Observability** - Required to detect issues in production
❗ **Rollback Plan** - Required to revert if something fails
Can you provide:
1. Security requirements (auth, encryption, PII handling)?
2. What metrics will you monitor?
3. How will you rollback if something goes wrong?
```
**Portuguese**:
```
Este é um sistema de [pagamento/autenticação/produção]. Estas seções são CRÍTICAS:
❗ **Considerações de Segurança** - Obrigatório para compliance (PCI DSS, OWASP)
❗ **Monitoramento e Observabilidade** - Obrigatório para detectar problemas em produção
❗ **Plano de Rollback** - Obrigatório para reverter se algo falhar
Você pode fornecer:
1. Requisitos de segurança (autenticação, encriptação, tratamento de PII)?
2. Quais métricas você vai monitorar?
3. Como você fará rollback se algo der errado?
```
### Step 4: Offer Suggested Sections
After mandatory sections are covered, **offer optional sections IN THE USER'S LANGUAGE**:
**English**:
```
I can also add these sections to make the TDD more complete:
📊 **Success Metrics** - How will you measure success?
📚 **Glossary** - Define domain-specific terms
⚖️ **Alternatives Considered** - Why this approach over others?
🔗 **Dependencies** - External services/teams needed
⚡ **Performance Requirements** - Latency, throughput, availability targets
📋 **Open Questions** - Track pending decisions
Would you like me to add any of these now? (You can add them later)
```
**Portuguese**:
```
Também posso adicionar estas seções para tornar o TDD mais completo:
📊 **Métricas de Sucesso** - Como você vai medir o sucesso?
📚 **Glossário** - Definir termos específicos do domínio
⚖️ **Alternativas Consideradas** - Por que esta abordagem ao invés de outras?
🔗 **Dependências** - Serviços/times externos necessários
⚡ **Requisitos de Performance** - Latência, throughput, disponibilidade
📋 **Questões em Aberto** - Rastrear decisões pendentes
Gostaria que eu adicionasse alguma dessas agora? (Você pode adicionar depois)
```
### Step 5: Generate Document
Generate the TDD in Markdown format following the templates below.
### Step 6: Offer Confluence Integration
If user has Confluence Assistant skill available, **ask in their language**:
**English**:
```
Would you like me to publish this TDD to Confluence?
- I can create a new page in your space
- Or update an existing page
```
**Portuguese**:
```
Gostaria que eu publicasse este TDD no Confluence?
- Posso criar uma nova página no seu espaço
- Ou atualizar uma página existente
```
## Section Templates
### 1. Header & Metadata (MANDATORY)
```markdown
# TDD - [Project/Feature Name]
| Field | Value |
| --------------- | ---------------------------- |
| Tech Lead | @Name |
| Product Manager | @Name (if applicable) |
| Team | Name1, Name2, Name3 |
| Epic/Ticket | [Link to Jira/Linear] |
| Figma/Design | [Link if applicable] |
| Status | Draft / In Review / Approved |
| Created | YYYY-MM-DD |
| Last Updated | YYYY-MM-DD |
```
**If user doesn't provide**: Ask for Tech Lead, Team members, and Epic link.
---
### 2. Context (MANDATORY)
```markdown
## Context
[2-4 paragraph description of the project]
**Background**:
What is the current state? What system/feature does this relate to?
**Domain**:
What business domain is this part of? (e.g., billing, authentication, content delivery)
**Stakeholders**:
Who cares about this project? (users, business, compliance, etc.)
```
**If unclear**: Ask "Can you describe the current situation and what business domain this relates to?"
---
### 3. Problem Statement & Motivation (MANDATORY)
```markdown
## Problem Statement & Motivation
### Problems We're Solving
- **Problem 1**: [Specific pain point with impact]
- Impact: [quantify if possible - time wasted, cost, user friction]
- **Problem 2**: [Another pain point]
- Impact: [quantify if possible]
### Why Now?
- [Business driver - market expansion, competitor pressure, regulatory requirement]
- [Technical driver - technical debt, scalability limits]
- [User driver - customer feedback, usage patterns]
### Impact of NOT Solving
- **Business**: [revenue loss, competitive disadvantage]
- **Technical**: [technical debt accumulation, system degradation]
- **Users**: [poor experience, churn risk]
```
**If user says "to integrate with X"**: Ask "What specific problems will this integration solve? Why is it important now? What happens if we don't do it?"
---
### 4. Scope (MANDATORY)
```markdown
## Scope
### ✅ In Scope (V1 - MVP)
Explicit list of what WILL be delivered:
- Feature/capability 1
- Feature/capability 2
- Feature/capability 3
- Integration point A
- Data migration for X
### ❌ Out of Scope (V1)
Explicit list of what will NOT be included in this phase:
- Feature X (deferred to V2)
- Integration Y (not needed for MVP)
- Advanced analytics (future enhancement)
- Multi-region support (V2)
### 🔮 Future Considerations (V2+)
What might come later:
- Feature A (user demand dependent)
- Feature B (after V1 validation)
```
**If user doesn't define**: Ask "What are the must-haves for V1? What can wait for later versions?"
---
### 5. Technical Solution (MANDATORY)
````markdown
## Technical Solution
### Architecture Overview
[High-level description of the solution]
**Key Components**:
- Component A: [responsibility]
- Component B: [responsibility]
- Component C: [responsibility]
**Architecture Diagram**:
[Include Mermaid diagram, PlantUML, or link to diagram]
```mermaid
graph LR
A[Frontend] -->|HTTP| B[API Gateway]
B -->|GraphQL| C[Backend Service]
C -->|REST| D[External API]
C -->|Write| E[(Database)]
```
````
### Data Flow
1. **Step 1**: User action → Frontend
2. **Step 2**: Frontend → API Gateway (POST /resource)
3. **Step 3**: API Gateway → Service Layer
4. **Step 4**: Service → External API (if applicable)
5. **Step 5**: Service → Database (persist)
6. **Step 6**: Response → Frontend
### APIs & Endpoints
| Endpoint | Method | Description | Request | Response |
| ---------------------- | ------ | ---------------- | ----------- | ---------------- |
| `/api/v1/resource` | POST | Creates resource | `CreateDto` | `ResourceDto` |
| `/api/v1/resource/:id` | GET | Get by ID | - | `ResourceDto` |
| `/api/v1/resource/:id` | DELETE | Delete resource | - | `204 No Content` |
**Example Request/Response**:
```json
// POST /api/v1/resource
{
"name": "Example",
"type": "standard"
}
// Response 201 Created
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "Example",
"type": "standard",
"status": "active",
"createdAt": "2026-02-04T10:00:00Z"
}
```
### Database Changes
**New Tables**:
- `{ModuleName}{EntityName}` - [description]
- Primary fields: id, userId, name, status
- Timestamps: createdAt, updatedAt
- Indexes: userId, status (for query performance)
**Schema Changes** (if modifying existing):
- Add column `newField` to `ExistingTable`
- Type: [varchar/integer/jsonb/etc.]
- Constraints: [nullable/unique/foreign key]
**Migration Strategy**:
- Generate migration from schema changes
- Test migration on staging environment first
- Run during low-traffic window
- Have rollback migration ready
**Data Backfill** (if needed):
- Affected records: Estimate quantity
- Processing time: Estimate duration for data migration
- Validation: How to verify data integrity after backfill
````
**If user provides vague description**: Ask "What are the main components? How does data flow through the system? What APIs will be created/modified?"
---
### 6. Risks (MANDATORY)
```markdown
## Risks
| Risk | Impact | Probability | Mitigation |
|------|--------|-------------|------------|
| External API downtime | High | Medium | Implement circuit breaker, cache responses, fallback to degraded mode |
| Data migration failure | High | Low | Test on staging copy, run dry-run first, have rollback script ready |
| Performance degradation | Medium | Medium | Load test before deployment, implement caching, monitor latency |
| Security vulnerability | High | Low | Security review, penetration testing, follow OWASP guidelines |
| Scope creep | Medium | High | Strict scope definition, change request process, regular stakeholder alignment |
**Risk Scoring**:
- **Impact**: High (system down, data loss) / Medium (degraded UX) / Low (minor inconvenience)
- **Probability**: High (>50%) / Medium (20-50%) / Low (<20%)
````
**If user provides < 3 risks**: Ask "What could go wrong? Consider: external dependencies, data integrity, performance, security, scope changes."
---
### 7. Implementation Plan (MANDATORY)
```markdown
## Implementation Plan
| Phase | Task | Description | Owner | Status | Estimate |
| --------------------- | ----------------- | -------------------------------------- | ------- | ------ | -------- |
| **Phase 1 - Setup** | Setup credentials | Obtain API keys, configure environment | @Dev1 | TODO | 1d |
| | Database setup | Create schema, configure datasource | @Dev1 | TODO | 1d |
| **Phase 2 - Core** | Entities & repos | Create TypeORM entities, repositories | @Dev2 | TODO | 3d |
| | Services | Implement business logic services | @Dev2 | TODO | 4d |
| **Phase 3 - APIs** | REST endpoints | Create controllers, DTOs | @Dev3 | TODO | 3d |
| | Integration | Integrate with external API | @Dev1 | TODO | 3d |
| **Phase 4 - Testing** | Unit tests | Test services and repositories | @Team | TODO | 2d |
| | E2E tests | Test full flow | @Team | TODO | 3d |
| **Phase 5 - Deploy** | Staging deploy | Deploy to staging, smoke test | @DevOps | TODO | 1d |
| | Production deploy | Phased rollout to production | @DevOps | TODO | 1d |
**Total Estimate**: ~20 days (4 weeks)
**Dependencies**:
- Must complete Phase N before Phase N+1
- External API access required before Phase 3
- Security review required before Phase 5
```
**If user provides vague plan**: Ask "Can you break this down into phases with specific tasks? Who will work on each part? What's the estimated timeline?"
---
### 8. Security Considerations (CRITICAL for payments/auth/PII)
```markdown
## Security Considerations
### Authentication & Authorization
- **Authentication**: How users prove identity
- Example: JWT tokens, OAuth 2.0, session-based
- **Authorization**: What authenticated users can access
- Example: Role-based (RBAC), Attribute-based (ABAC)
- Ensure users can only access their own resources
### Data Protection
**Encryption**:
- **At Rest**: Database encryption enabled (AES-256)
- **In Transit**: TLS 1.3 for all API communication
- **Secrets**: Store API keys in environment variables / secret manager (AWS Secrets Manager, HashiCorp Vault)
**PII Handling**:
- What PII is collected: [email, name, payment info]
- Legal basis: [consent, contract, legitimate interest]
- Retention: [how long data is kept]
- Deletion: [GDPR right to be forgotten implementation]
### Compliance Requirements
| Regulation | Requirement | Implementation |
| ----------- | ---------------------------------- | ------------------------------------------------- |
| **GDPR** | Data protection, right to deletion | Implement data export/deletion endpoints |
| **PCI DSS** | No storage of card data | Use Stripe tokenization, never store CVV/full PAN |
| **LGPD** | Brazil data protection | Same as GDPR compliance |
### Security Best Practices
- ✅ Input validation on all endpoints
- ✅ SQL injection prevention (parameterized queries)
- ✅ XSS prevention (sanitize user input, CSP headers)
- ✅ CSRF protection (tokens for state-changing operations)
- ✅ Rate limiting (e.g., 10 req/min per user, 100 req/min per IP)
- ✅ Audit logging (log all sensitive operations)
### Secrets Management
**API Keys**:
- Storage: Environment variables or secret management service
- Rotation: Define rotation policy (e.g., every 90 days)
- Access: Backend services only, never exposed to frontend
- Examples: Stripe keys, database credentials, API tokens
**Webhook Signatures**:
- Validate webhook signatures from external services
- Reject requests without valid signature headers
- Log invalid signature attempts for security monitoring
```
**If missing and project involves payments/auth**: Ask "This is a [payment/auth] system. I need security details: How will you handle authentication? What encryption will be used? What PII is collected? Any compliance requirements (GDPR, PCI DSS)?"
---
### 9. Testing Strategy (CRITICAL)
```markdown
## Testing Strategy
| Test Type | Scope | Coverage Target | Approach |
| --------------------- | ------------------------ | ------------------------ | -------------------- |
| **Unit Tests** | Services, repositories | > 80% | Jest with mocks |
| **Integration Tests** | API endpoints + database | Critical paths | Supertest + test DB |
| **E2E Tests** | Full user flows | Happy path + error cases | Playwright |
| **Contract Tests** | External API integration | API contract validation | Pact or manual mocks |
| **Load Tests** | Performance under load | Baseline performance | k6 or Artillery |
### Test Scenarios
**Unit Tests**:
- ✅ Service business logic (create, update, delete)
- ✅ Repository query methods
- ✅ Error handling (throw correct exceptions)
- ✅ Edge cases (null inputs, invalid data)
**Integration Tests**:
- ✅ POST `/api/v1/resource` → creates in DB
- ✅ GET `/api/v1/resource/:id` → returns correct data
- ✅ DELETE `/api/v1/resource/:id` → removes from DB
- ✅ Invalid input → returns 400 Bad Request
- ✅ Unauthorized access → returns 401/403
**E2E Tests**:
- ✅ User creates resource → success flow
- ✅ User tries to access another user's resource → denied
- ✅ External API fails → graceful degradation
- ✅ Database connection lost → proper error handling
**Load Tests**:
- Target: 100 req/s sustained, 500 req/s peak
- Monitor: Latency (p50, p95, p99), error rate, throughput
- Pass criteria: p95 < 500ms, error rate < 1%
### Test Data Management
- Use factories for test data (e.g., `@faker-js/faker`)
- Seed test database with realistic data
- Clean up test data after each test
- Use separate test database (never use production)
```
**If missing**: Ask "How will you test this? What test types are needed (unit, integration, e2e)? What are critical test scenarios?"
---
### 10. Monitoring & Observability (CRITICAL for production)
````markdown
## Monitoring & Observability
### Metrics to Track
| Metric | Type | Alert Threshold | Dashboard |
| ------------------------- | ---------- | ----------------- | ------------------ |
| `api.latency` | Latency | p95 > 1s for 5min | DataDog / Grafana |
| `api.error_rate` | Error rate | > 1% for 5min | DataDog / Grafana |
| `external_api.latency` | Latency | p95 > 2s for 5min | DataDog |
| `external_api.errors` | Counter | > 5 in 1min | PagerDuty |
| `database.query_time` | Duration | p95 > 100ms | DataDog |
| `webhook.processing_time` | Duration | > 5s | Internal Dashboard |
### Structured Logging
**Log Format** (JSON):
```json
{
"level": "info",
"timestamp": "2026-02-04T10:00:00Z",
"message": "Resource created",
"context": {
"userId": "user-123",
"resourceId": "res-456",
"action": "create",
"duration_ms": 45
}
}
```
````
**What to Log**:
- ✅ All API requests (method, path, status, duration)
- ✅ External API calls (endpoint, status, duration)
- ✅ Database queries (slow queries > 100ms)
- ✅ Errors and exceptions (stack trace, context)
- ✅ Business events (resource created, payment processed)
**What NOT to Log**:
- ❌ Passwords, API keys, secrets
- ❌ Full credit card numbers
- ❌ Sensitive PII (redact or hash)
### Alerts
| Alert | Severity | Channel | On-Call Action |
| ---------------------------------- | ------------- | ------------------ | ------------------------------------------- |
| Error rate > 5% | P1 (Critical) | PagerDuty | Immediate investigation, rollback if needed |
| External API down | P1 (Critical) | PagerDuty | Enable fallback mode, notify stakeholders |
| Latency > 2s (p95) | P2 (High) | Slack #engineering | Investigate performance degradation |
| Webhook failures > 20 | P2 (High) | Slack #engineering | Check webhook endpoint, Stripe status |
| Database connection pool exhausted | P1 (Critical) | PagerDuty | Scale up connections or investigate leak |
### Dashboards
**Operational Dashboard**:
- Request rate (per endpoint)
- Error rate (overall and per endpoint)
- Latency (p50, p95, p99)
- External API health
- Database performance
**Business Dashboard**:
- Resources created (count per day)
- Active users
- Conversion metrics (if applicable)
````
**If missing for production system**: Ask "How will you monitor this in production? What metrics matter? What alerts do you need?"
---
### 11. Rollback Plan (CRITICAL for production)
```markdown
## Rollback Plan
### Deployment Strategy
- **Feature Flag**: `FEATURE_X_ENABLED` (LaunchDarkly / custom)
- **Phased Rollout**:
- Phase 1: 5% of traffic (1 day)
- Phase 2: 25% of traffic (1 day)
- Phase 3: 50% of traffic (1 day)
- Phase 4: 100% of traffic
- **Canary Deployment**: Deploy to 1 instance first, monitor for 1h before full rollout
### Rollback Triggers
| Trigger | Action |
|---------|--------|
| Error rate > 5% for 5 minutes | **Immediate rollback** - disable feature flag |
| Latency > 3s (p95) for 10 minutes | **Investigate** - rollback if no quick fix |
| External API integration failing > 50% | **Rollback** - revert to previous version |
| Database migration fails | **STOP** - do not proceed, investigate |
| Customer reports of data loss | **Immediate rollback** + incident response |
### Rollback Steps
**1. Immediate Rollback (< 5 minutes)**:
- **Feature Flag**: Disable via feature flag dashboard (instant)
- **Deployment**: Revert to previous version via deployment tool (2-3 minutes)
**2. Database Rollback** (if schema changed):
- Run down migration using migration tool
- Verify schema integrity
- Confirm data consistency
**3. Communication**:
- Notify #engineering Slack channel
- Update status page (if customer-facing)
- Create incident ticket
- Schedule post-mortem within 24h
### Post-Rollback
- **Root Cause Analysis**: Within 24 hours
- **Fix**: Implement fix in development environment
- **Re-test**: Full test suite + additional tests for root cause
- **Re-deploy**: Following same phased rollout strategy
### Database Rollback Considerations
- **Migrations**: Always create reversible migrations (down migration)
- **Data Backfill**: If data was modified, have script to restore previous state
- **Backup**: Take database snapshot before running migrations
- **Testing**: Test rollback procedure on staging before production
````
**If missing for production**: Ask "What happens if the deploy goes wrong? How will you rollback? What are the triggers for rollback?"
---
### 12. Success Metrics (SUGGESTED)
```markdown
## Success Metrics
| Metric | Baseline | Target | Measurement |
| ----------------------- | ------------- | ------- | ------------------ |
| API latency (p95) | N/A (new API) | < 200ms | DataDog APM |
| Error rate | N/A | < 0.1% | Sentry / logs |
| Conversion rate | N/A | > 70% | Analytics |
| User satisfaction | N/A | NPS > 8 | User survey |
| Time to complete action | N/A | < 30s | Frontend analytics |
**Business Metrics**:
- Increase in [metric] by [X%]
- Reduction in [cost/time] by [Y%]
- User adoption: [Z%] of users using new feature within 30 days
**Technical Metrics**:
- Zero production incidents in first 30 days
- Test coverage > 80%
- Documentation completeness: 100% of public APIs documented
```
---
### 13. Glossary & Domain Terms (SUGGESTED)
```markdown
## Glossary
| Term | Description |
| ------------------- | --------------------------------------------------------------------- |
| **Customer** | A user who has an active subscription or has made a purchase |
| **Subscription** | Recurring payment arrangement with defined interval (monthly, annual) |
| **Trial** | Free period for users to test service before payment required |
| **Webhook** | HTTP callback from external service to notify of events |
| **Idempotency** | Operation can be applied multiple times with same result |
| **Circuit Breaker** | Pattern to prevent cascading failures when external service is down |
**Acronyms**:
- **API**: Application Programming Interface
- **SLA**: Service Level Agreement
- **PII**: Personally Identifiable Information
- **GDPR**: General Data Protection Regulation
- **PCI DSS**: Payment Card Industry Data Security Standard
```
---
### 14. Alternatives Considered (SUGGESTED)
```markdown
## Alternatives Considered
| Option | Pros | Cons | Why Not Chosen |
| --------------------- | -------------------------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------- |
| **Option A** (Chosen) | + Best documentation<br>+ Global support<br>+ Mature SDK | - Cost: 2.9% + $0.30<br>- Vendor lock-in | ✅ **Chosen** - Best balance of features and cost |
| Option B | + Lower fees (2.5%)<br>+ Brand recognition | - Poor developer experience<br>- Limited international support | Developer experience inferior, harder to maintain |
| Option C | + Full control<br>+ No transaction fees | - High maintenance cost<br>- Compliance burden (PCI DSS)<br>- Security risk | Too risky and expensive to maintain in-house |
| Option D | + Cheapest option | - No support<br>- Limited features<br>- Unknown reliability | Too risky for production payment processing |
**Decision Criteria**:
1. Developer experience and documentation quality (weight: 40%)
2. Total cost of ownership (weight: 30%)
3. International support and compliance (weight: 20%)
4. Reliability and uptime (weight: 10%)
**Why Option A Won**:
- Scored highest on developer experience (critical for fast iteration)
- Industry-standard for startups (easier to hire developers with experience)
- Built-in compliance (PCI DSS, SCA, 3D Secure) reduces risk
```
---
### 15. Dependencies (SUGGESTED)
```markdown
## Dependencies
| Dependency | Type | Owner | Status | Risk |
| --------------------- | -------------- | ----------- | ---------------- | ------------------- |
| Stripe API | External | Stripe Inc. | Production-ready | Low (99.99% uptime) |
| Identity Module | Internal | Team Auth | Production-ready | Low |
| Database (PostgreSQL) | Infrastructure | DevOps | Ready | Low |
| Redis (caching) | Infrastructure | DevOps | Needs setup | Medium |
| Feature flag service | Internal | Platform | Ready | Low |
**Approval Requirements**:
- [ ] Security team review (for payment/auth projects)
- [ ] Compliance sign-off (for PII/payment data)
- [ ] Ops team ready for monitoring setup
- [ ] Product sign-off on scope
**Blockers**:
- Waiting for Stripe production keys (ETA: 2026-02-10)
- Need Redis setup in staging (ETA: 2026-02-08)
```
---
### 16. Performance Requirements (SUGGESTED)
```markdown
## Performance Requirements
| Metric | Requirement | Measurement Method |
| ------------------- | ----------------------------- | ------------------ |
| API Latency (p50) | < 100ms | DataDog APM |
| API Latency (p95) | < 500ms | DataDog APM |
| API Latency (p99) | < 1s | DataDog APM |
| Throughput | 1000 req/s sustained | Load testing (k6) |
| Availability | 99.9% (< 8.76h downtime/year) | Uptime monitoring |
| Database query time | < 50ms (p95) | Slow query log |
**Load Testing Plan**:
- Baseline: 100 req/s for 10 minutes
- Peak: 500 req/s for 5 minutes
- Spike: 1000 req/s for 1 minute
**Scalability**:
- Horizontal scaling: Add more instances (Kubernetes autoscaling)
- Database: Read replicas if needed (after 10k req/s)
- Caching: Redis for frequently accessed data (> 100 req/s per resource)
```
---
### 17. Migration Plan (SUGGESTED - if applicable)
```markdown
## Migration Plan
### Migration Strategy
**Type**: [Blue-Green / Rolling / Big Bang / Phased]
**Phases**:
| Phase | Description | Users Affected | Duration | Rollback |
| ----------------- | -------------------------------------- | -------------- | -------- | ------------------- |
| 1. Preparation | Set up new system, run in parallel | 0% | 1 week | N/A |
| 2. Shadow Mode | New system processes but doesn't serve | 0% | 1 week | Instant |
| 3. Pilot | 5% of users on new system | 5% | 1 week | < 5min |
| 4. Ramp Up | 50% of users on new system | 50% | 1 week | < 5min |
| 5. Full Migration | 100% of users on new system | 100% | 1 day | < 5min |
| 6. Decommission | Turn off old system | 0% | 1 week | Restore from backup |
### Data Migration
**Source**: Old system database
**Destination**: New system database
**Volume**: [X million records]
**Method**: [ETL script / database replication / API sync]
**Steps**:
1. Export data from old system (script: `scripts/export-old-data.ts`)
2. Transform data to new schema (script: `scripts/transform-data.ts`)
3. Validate data integrity (checksums, row counts)
4. Load into new system (script: `scripts/load-new-data.ts`)
5. Verify: Run parallel reads, compare results
**Timeline**:
- Dry run on staging: 2026-02-10
- Production migration window: 2026-02-15 02:00-06:00 UTC (low traffic)
### Backward Compatibility
- Old API endpoints will remain active for 90 days
- Deprecation warnings added to responses
- Client libraries updated with migration guide
```
---
### 18. Open Questions (SUGGESTED)
```markdown
## Open Questions
| # | Question | Context | Owner | Status | Decision Date |
| --- | ------------------------------------------------------ | ---------------------------------------------- | --------- | ---------------- | ------------- |
| 1 | How to handle trial expiration without payment method? | User loses access immediately or grace period? | @Product | 🟡 In Discussion | TBD |
| 2 | Allow multiple trials for same email? | Prevent abuse vs. legitimate use cases | @TechLead | 🔴 Open | TBD |
| 3 | SLA for webhook processing? | Stripe retries for 72h, what's our target? | @Backend | 🔴 Open | TBD |
| 4 | Support for promo codes in V1? | Marketing requested, is it in scope? | @Product | ✅ Resolved: V2 | 2026-02-01 |
| 5 | Fallback if Identity Module fails? | Can we create subscription without user data? | @TechLead | 🔴 Open | TBD |
**Status Legend**:
- 🔴 Open - needs decision
- 🟡 In Discussion - actively being discussed
- ✅ Resolved - decision made
```
---
### 19. Roadmap / Timeline (SUGGESTED)
```markdown
## Roadmap / Timeline
| Phase | Deliverables | Duration | Target Date | Status |
| ------------------------ | --------------------------------------------------------------------------------- | -------- | ----------- | -------------- |
| **Phase 0: Setup** | - Stripe credentials<br>- Staging environment<br>- SDK installed | 2 days | 2026-02-05 | ✅ Complete |
| **Phase 1: Persistence** | - Entities created<br>- Repositories implemented<br>- Migrations generated | 3 days | 2026-02-08 | 🟡 In Progress |
| **Phase 2: Services** | - CustomerService<br>- SubscriptionService<br>- Identity integration | 5 days | 2026-02-15 | ⏳ Pending |
| **Phase 3: APIs** | - POST /subscriptions<br>- DELETE /subscriptions/:id<br>- GET /subscriptions | 3 days | 2026-02-18 | ⏳ Pending |
| **Phase 4: Webhooks** | - Webhook endpoint<br>- Signature validation<br>- Event handlers | 4 days | 2026-02-22 | ⏳ Pending |
| **Phase 5: Testing** | - Unit tests (80% coverage)<br>- Integration tests<br>- E2E tests | 5 days | 2026-02-27 | ⏳ Pending |
| **Phase 6: Deploy** | - Documentation<br>- Monitoring setup<br>- Staging deploy<br>- Production rollout | 3 days | 2026-03-02 | ⏳ Pending |
**Total Duration**: ~25 days (5 weeks)
**Milestones**:
- 🎯 M1: MVP ready for staging (2026-02-22)
- 🎯 M2: Production deployment (2026-03-02)
- 🎯 M3: 100% rollout complete (2026-03-09)
**Critical Path**:
Phase 0 → Phase 1 → Phase 2 → Phase 3 → Phase 4 → Phase 5 → Phase 6
```
---
### 20. Approval & Sign-off (SUGGESTED)
```markdown
## Approval & Sign-off
| Role | Name | Status | Date | Comments |
| ------------------------ | ----- | -------------- | ---------- | --------------------------------- |
| Tech Lead | @Name | ✅ Approved | 2026-02-04 | LGTM, proceed with implementation |
| Staff/Principal Engineer | @Name | ⏳ Pending | - | Requested security review first |
| Product Manager | @Name | ✅ Approved | 2026-02-03 | Scope aligned with roadmap |
| Engineering Manager | @Name | ⏳ Pending | - | - |
| Security Team | @Name | 🔴 Not Started | - | Required for payment integration |
| Compliance/Legal | @Name | N/A | - | Not required for this project |
**Approval Criteria**:
- ✅ All mandatory sections complete
- ✅ Security review passed (if applicable)
- ✅ Risks identified and mitigated
- ✅ Timeline realistic and agreed upon
- ⏳ Test strategy approved by QA
- ⏳ Monitoring plan reviewed by SRE
**Next Steps After Approval**:
1. Create Epic in Jira (link in metadata)
2. Break down into User Stories
3. Begin Phase 1 implementation
4. Schedule kickoff meeting with team
```
---
## Validation Rules
### Mandatory Section Checklist
Before finalizing TDD, ensure:
- [ ] **Header**: Tech Lead, Team, Epic link present
- [ ] **Context**: 2+ paragraphs describing background and domain
- [ ] **Problem**: At least 2 specific problems identified with impact
- [ ] **Scope**: Clear in-scope and out-of-scope items (min 3 each)
- [ ] **Technical Solution**: Architecture diagram or description
- [ ] **Technical Solution**: At least 1 API endpoint defined
- [ ] **Risks**: At least 3 risks with impact/probability/mitigation
- [ ] **Implementation Plan**: Broken into phases with estimates
### Critical Section Checklist (by project type)
**If Payment/Auth project**:
- [ ] **Security**: Authentication method defined
- [ ] **Security**: Encryption (at rest, in transit) specified
- [ ] **Security**: PII handling approach documented
- [ ] **Security**: Compliance requirements identified
**If Production system**:
- [ ] **Monitoring**: At least 3 metrics defined with thresholds
- [ ] **Monitoring**: Alerts configured
- [ ] **Rollback**: Rollback triggers defined
- [ ] **Rollback**: Rollback steps documented
**All projects**:
- [ ] **Testing**: At least 2 test types defined (unit, integration, e2e)
- [ ] **Testing**: Critical test scenarios listed
## Output Format
### When Creating TDD
1. **Generate Markdown document**
2. **Validate against checklists above**
3. **Highlight any missing critical sections**
4. **Provide summary to user**:
```
✅ TDD Created: "[Project Name]"
**Sections Included**:
✅ Mandatory (7/7): All present
✅ Critical (3/4): Security, Testing, Monitoring
⚠️ Missing: Rollback Plan (recommended for production)
**Suggested Next Steps**:
- Add Rollback Plan section (critical for production)
- Review Security section with InfoSec team
- Create Epic in Jira and link in metadata
- Schedule TDD review meeting with stakeholders
Would you like me to:
1. Add the missing Rollback Plan section?
2. Publish this TDD to Confluence?
3. Create a Jira Epic for this project?
```
### Confluence Integration
If user wants to publish to Confluence:
```
I'll publish this TDD to Confluence.
Which space should I use?
- Personal space (~557058...)
- Team space (provide space key)
Should I:
- Create a new page
- Update existing page (provide page ID or URL)
```
Then use Confluence Assistant skill to publish.
## Common Anti-Patterns to Avoid
### ❌ Vague Problem Statements
**BAD**:
```
We need to integrate with Stripe.
```
**GOOD**:
```
### Problems We're Solving
- **Manual payment processing takes 2 hours/day**: Currently processing payments manually, costing $500/month in labor
- **Cannot expand internationally**: Current payment processor only supports USD
- **High cart abandonment (45%)**: Poor checkout UX causing revenue loss of $10k/month
```
### ❌ Undefined Scope
**BAD**:
```
Build payment integration with all features.
```
**GOOD**:
```
### ✅ In Scope (V1)
- Trial subscriptions (14 days)
- Single payment method per user
- USD only
- Cancel subscription
### ❌ Out of Scope (V1)
- Multiple payment methods
- Multi-currency
- Promo codes
- Usage-based billing
```
### ❌ Missing Security for Payment Systems
**BAD**:
```
No security section for payment integration.
```
**GOOD**:
```
### Security Considerations (MANDATORY)
**PCI DSS Compliance**:
- Never store full card numbers (use Stripe tokens)
- Never log CVV or full PAN
- Use Stripe Elements for card input (PCI SAQ A)
**Secrets Management**:
- Store `STRIPE_SECRET_KEY` in environment variables
- Rotate keys every 90 days
- Never commit keys to git
```
### ❌ No Rollback Plan
**BAD**:
```
We'll deploy and hope it works.
```
**GOOD**:
```
### Rollback Plan
**Triggers**:
- Error rate > 5% → immediate rollback
- Payment processing failures > 10% → immediate rollback
**Steps**:
1. Disable feature flag `STRIPE_INTEGRATION_ENABLED`
2. Verify old payment processor is active
3. Notify #engineering and #product
4. Schedule post-mortem within 24h
```
## Important Notes
- **Respect user's language** - Automatically detect and generate TDD in the same language as user's request
- **Focus on architecture, not implementation** - Document decisions and contracts, not code
- **High-level examples only** - Show API contracts, data schemas, diagrams (not CLI commands or code snippets)
- **Always validate mandatory sections** - Don't let user skip them
- **For payments/auth** - Security section is MANDATORY
- **For production** - Monitoring and Rollback are MANDATORY
- **Ask clarifying questions** - Don't guess missing information (ask in user's language)
- **Be thorough but pragmatic** - Small projects don't need all 20 sections
- **Update the document** - TDDs should evolve as the project progresses
- **Use industry standards** - Reference Google, Amazon, RFC patterns
- **Think about compliance** - GDPR, PCI DSS, HIPAA where applicable
- **Test for longevity** - If implementation framework changes, TDD should still be valid
## Example Prompts that Trigger This Skill
### English
- "Create a TDD for Stripe integration"
- "I need a technical design document for the new auth system"
- "Write a design doc for the API redesign"
- "Help me document the payment integration architecture"
- "Create a tech spec for migrating to microservices"
### Portuguese
- "Crie um TDD para integração com Stripe"
- "Preciso de um documento de design técnico para o novo sistema de autenticação"
- "Escreva um design doc para o redesign da API"
- "Me ajude a documentar a arquitetura de integração de pagamento"
- "Crie uma especificação técnica para migração para microserviços"
### Spanish
- "Crea un TDD para integración con Stripe"
- "Necesito un documento de diseño técnico para el nuevo sistema de autenticación"
- "Escribe un design doc para el rediseño de la API"
- "Ayúdame a documentar la arquitectura de integración de pagos"
- "Crea una especificación técnica para migración a microservicios"
## References
### Industry Standards
- [Google Engineering Practices](https://google.github.io/eng-practices/)
- [Google SRE Book](https://sre.google/sre-book/table-of-contents/)
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
- [Architecture Decision Records](https://adr.github.io/)
```
```
---
id: generate-tasks
name: Task List Generator
description: |
Generates a detailed, step-by-step task list in Markdown from a PRD or any feature requirements, using a two-phase (parent tasks → sub-tasks) workflow and producing each task in the SYS Manager template (O que fazer, Dependências, Execução, Definition of Done, Sugestão de Esforço, Notas Técnicas).
**Use this skill when:**
- The user says "generate tasks from this PRD", "create a task list", "break this down into tasks"
- The user says "gerar tarefas", "criar lista de tarefas", "decompor o PRD em tasks"
- A PRD (from `create-prd`) or a feature description exists and needs to be decomposed into implementable work items following the SYS Manager template
**This skill is the natural successor to `create-prd`** — the PRD it produces is the canonical input here.
**Do NOT use for:**
- Writing the requirements themselves — use `create-prd`
- Architectural decisions — use `create-adr`
- Change proposals seeking stakeholder alignment — use `create-rfc`
- Implementation design after scope is set — use `create-technical-design-doc`
metadata:
version: '1.0.0'
category: documentation
dependencies: [create-prd]
requires: {}
tags: [tasks, task-list, decomposition, sys-manager, documentation]
---
# Rule: Generating a Task List from a PRD or Feature Requirements
## Goal
Guide an AI assistant in creating a detailed, step-by-step task list in Markdown format, based on a Product Requirements Document (PRD) or a feature description. The task list guides a developer through implementation, and **each task follows the SYS Manager task template**.
## Output
- **Format**: Markdown (`.md`)
- **Location**: `/tasks/`
- **Filename**:
- When generated from a PRD: `tasks-[prd-filename].md` (e.g., `tasks-prd-user-profile-editing.md`)
- When generated from free-form requirements: `tasks-[feature-name].md`
## Process
1. **Receive Input**: The user points to a PRD file, provides a feature description, or references existing documentation.
2. **Analyze Input**: Read and analyze functional requirements, user stories, non-goals, and any other sections of the PRD or requirements document.
3. **Phase 1 — Generate Parent Tasks**: Based on the analysis, create the file and generate the main, high-level tasks required to implement the feature. **IMPORTANT: Always include task `0.0 Create feature branch` as the first parent task, unless the user explicitly requests not to.** Use your judgement on how many additional high-level tasks to use — typically around 5. Present these tasks to the user **without sub-tasks yet**. Inform the user: "I have generated the high-level tasks based on the input. Ready to generate the sub-tasks? Respond with 'Go' to proceed."
4. **Wait for Confirmation**: Pause and wait for the user to respond with "Go".
5. **Phase 2 — Generate Sub-Tasks**: Once confirmed, break each parent task into smaller, actionable sub-tasks. Ensure sub-tasks logically follow from the parent and cover the implementation details implied by the PRD or requirements. **Each sub-task must be written in the SYS Manager task template (see below).**
6. **Identify Relevant Files**: Based on the tasks and input, list potential files to be created or modified under a `Relevant Files` section, including corresponding test files when applicable.
7. **Generate Final Output**: Combine parent tasks, sub-tasks (in the SYS Manager template), relevant files, and notes into the final Markdown structure.
8. **Save Task List**: Save to `/tasks/` with the filename derived in the **Output** section above.
## SYS Manager Task Template
Every sub-task **must** include the following fields. Field names stay in Portuguese to preserve the SYS Manager convention; content can be in the language the user is working in.
```markdown
#### [Sub-task Title]
**O que fazer**
<One-paragraph description of what must be done.>
**Dependências**
<Other tasks, artifacts, or conditions this task depends on. Write "Sem pré-requisitos." if none.>
**Execução**
1. Step 1
2. Step 2
3. ...
**Definition of Done**
- [ ] Criterion 1
- [ ] Criterion 2
- [ ] ...
**Sugestão de Esforço**
<e.g., 2h>
**Notas Técnicas**
<Optional: implementation hints, references, constraints, edge cases. Omit the section if nothing applies.>
```
## Output Format
The generated task list _must_ follow this structure:
````markdown
# Task List: [Feature Name]
## Relevant Files
- `path/to/file1.ts` — Brief description of why this file is relevant (e.g., contains the main component for this feature).
- `path/to/file1.test.ts` — Unit tests for `file1.ts`.
- `path/to/another/file.tsx` — Brief description (e.g., API route handler for data submission).
- `path/to/another/file.test.tsx` — Unit tests for `another/file.tsx`.
- `lib/utils/helpers.ts` — Brief description (e.g., utility functions needed for calculations).
- `lib/utils/helpers.test.ts` — Unit tests for `helpers.ts`.
### Notes
- Unit tests should typically be placed alongside the code files they test (e.g., `MyComponent.tsx` and `MyComponent.test.tsx` in the same directory).
- Use `npx jest [optional/path/to/test/file]` to run tests. Running without a path executes all tests found by the Jest configuration.
## Instructions for Completing Tasks
**IMPORTANT:** As you complete each task, check it off in this markdown file by changing `- [ ]` to `- [x]`. This helps track progress and ensures no steps are skipped.
Example:
- `- [ ] 1.1 Read file` → `- [x] 1.1 Read file` (after completing)
Update the file after completing each sub-task, not only after finishing an entire parent task.
## Tasks
- [ ] 0.0 Create feature branch
- [ ] 0.1 Create and checkout a new branch for this feature
**O que fazer**
Criar uma branch de feature isolada para implementar a funcionalidade sem afetar `main`.
**Dependências**
Sem pré-requisitos.
**Execução**
1. Abrir o terminal na raiz do repositório
2. Rodar `git checkout main && git pull`
3. Rodar `git checkout -b feature/[feature-name]`
**Definition of Done**
- [ ] Branch criada a partir de `main` atualizada
- [ ] Branch ativa no diretório de trabalho
**Sugestão de Esforço**
15min
**Notas Técnicas**
Seguir a convenção de nomenclatura de branches adotada pelo projeto.
- [ ] 1.0 Parent Task Title
- [ ] 1.1 Sub-task title
**O que fazer**
...
**Dependências**
...
**Execução**
1. ...
**Definition of Done**
- [ ] ...
**Sugestão de Esforço**
...
**Notas Técnicas**
...
- [ ] 1.2 Sub-task title
(same structure)
- [ ] 2.0 Parent Task Title
- [ ] 2.1 Sub-task title
...
- [ ] 3.0 Parent Task Title (may not require sub-tasks if purely structural or configuration)
````
## Interaction Model
The process explicitly requires a pause after generating parent tasks to get user confirmation ("Go") before proceeding to generate the detailed sub-tasks. This ensures the high-level plan aligns with user expectations before diving into details.
## Target Audience
Assume the primary reader of the task list is a **junior developer** who will implement the feature. Each SYS Manager field should be explicit, unambiguous, and avoid jargon where possible.
## Next Steps
Once the task list is generated and approved, the developer implements tasks sequentially, checking them off as they go. If during implementation:
- A significant architectural choice emerges → invoke `create-adr` to record it
- A complex implementation plan is needed → invoke `create-technical-design-doc`
- A proposal requiring stakeholder alignment comes up → invoke `create-rfc`
---
id: process-task-list
name: Task List Processor
description: |
Guides an AI assistant through the execution of a Markdown task list (typically produced by `generate-tasks`), enforcing a one-sub-task-at-a-time protocol with user approval between steps, test-gated commits after each parent task, and continuous maintenance of the "Relevant Files" section.
**Use this skill when:**
- The user says "process this task list", "let's work through the tasks", "execute the task list"
- The user says "vamos executar as tasks", "processar a lista de tarefas", "trabalhar na próxima tarefa"
- A task list file (e.g., `tasks/tasks-prd-*.md`) exists and the user wants to start/continue implementing its items sequentially
**This skill is the natural successor to `generate-tasks`.**
**Do NOT use for:**
- Writing the requirements themselves — use `create-prd`
- Generating the task list — use `generate-tasks`
- Recording architectural decisions — use `create-adr`
- Drafting change proposals — use `create-rfc`
metadata:
version: '1.0.0'
category: documentation
dependencies: [generate-tasks]
requires: {}
tags: [task-list, execution, workflow, sys-manager, documentation]
---
# Task List Management
Guidelines for managing task lists in Markdown files to track progress while implementing a PRD-derived feature.
## Task Implementation
- **One sub-task at a time:** Do **NOT** start the next sub-task until you ask the user for permission and they reply with any affirmative in their working language (e.g., `yes`, `y`, `ok`, `sim`, `s`, `vai`, `go`).
- **Completion protocol:**
1. When you finish a **sub-task**, immediately mark it as completed by changing `[ ]` to `[x]`.
2. If the sub-task was written in the **SYS Manager template** (from `generate-tasks`), also tick every satisfied item inside its **Definition of Done** checklist (`- [ ]` → `- [x]`). A sub-task is only complete when its top-level checkbox *and* all its DoD items are `[x]`.
3. If **all** sub-tasks under a parent task are now `[x]`, follow this sequence:
- **First**: Run the full test suite (`pytest`, `npm test`, `bin/rails test`, etc.)
- **Only if all tests pass**: Stage changes (`git add .`)
- **Clean up**: Remove any temporary files and temporary code before committing
- **Commit**: Use a descriptive commit message that:
- Uses conventional commit format (`feat:`, `fix:`, `refactor:`, etc.)
- Summarizes what was accomplished in the parent task
- Lists key changes and additions
- References the task number and the PRD (or ADO work item) context
- **Formats the message as a single-line command using `-m` flags**, e.g.:
```
git commit -m "feat: adds payment validation logic" -m "- Validates card type and expiry" -m "- Adds unit tests for edge cases" -m "Related to T123 in PRD"
```
4. Once all the sub-tasks are marked completed and changes have been committed, mark the **parent task** as completed.
- **Stop after each sub-task and wait for the user's go-ahead.**
## Task List Maintenance
1. **Update the task list as you work:**
- Mark tasks and sub-tasks as completed (`[x]`) per the protocol above.
- Add newly discovered tasks as they emerge (preserving the parent/sub-task numbering scheme).
2. **Maintain the `Relevant Files` section:**
- List every file created or modified.
- Give each file a one-line description of its purpose.
- Add corresponding test files when new code files appear.
## AI Instructions
When working with task lists, the AI must:
1. Regularly update the task list file after finishing any significant work.
2. Follow the completion protocol:
- Mark each finished **sub-task** `[x]`.
- When the sub-task uses the SYS Manager template, tick each satisfied DoD item `[x]` as well.
- Mark the **parent task** `[x]` once **all** its sub-tasks are `[x]`.
3. Add newly discovered tasks.
4. Keep `Relevant Files` accurate and up to date.
5. Before starting work, check which sub-task is next (lowest-numbered unchecked sub-task under the current parent).
6. After implementing a sub-task, update the file and then **pause for user approval** before continuing.
## Interaction Model
The process is deliberately incremental. The pause-after-each-sub-task rule ensures the user can:
- Review the diff before approving the next step
- Catch drift early (e.g., sub-task misunderstood, scope creep)
- Re-plan mid-execution if a blocker or surprise emerges
Do not batch multiple sub-tasks into a single turn, even if they look trivial.
## Next Steps
Once all parent tasks are `[x]` and the final commit is in place:
- If the feature requires stakeholder sign-off → draft an RFC via `create-rfc`
- If an architectural decision was made during implementation → record it via `create-adr`
- If the task list revealed a larger design worth documenting → create a TDD via `create-technical-design-doc`
---
id: spec-from-prd
name: Spec from PRD
description: "Skill para geração da Spec técnica executável na Etapa 2 da fase Plan a partir do PRD e Design Doc Enriquecido. Usa gotalab/cc-sdd spec-writer (3k★) + TLC tlc-spec-driven (Specify). Atende o slot Plan E2 (plan-spec-writer) do framework AI-SDLC. Produz spec.md com 10 seções obrigatórias (600-1500 linhas) em loop automático com cobertura ≥95% dos requisitos do PRD, antes de ser auditada pelo Spec Validator e Enricher na Etapa 3."
argument-hint: "generate | iterate | section"
metadata:
version: '1.0.0'
category: sdlc
dependencies: []
requires: {}
tags: [spec, specification, plan, e2, spec-writer, coverage, gherkin, state-machine, plan-phase]
---
# Spec from PRD — Plan E2
## Objetivo
Transformar o PRD + Design Doc Enriquecido em **Spec técnica executável** — o artefato que o builder em Implement lê sessão a sessão, com modelos de dados, rotas, state machines, RNFs medidos e cenários BDD formais.
Slot atendido: **Plan E2 — plan-spec-writer**
**Winner v3:** gotalab/cc-sdd `spec-writer` (3k★) + TLC: `tlc-spec-driven` (Specify)
> **Loop automático** até cobertura ≥95% dos requisitos do PRD. Não avança para Etapa 3 com cobertura menor.
---
## Quando Usar Esta Skill
- Etapa 1 (Tech Decisions) concluída, `design-doc-enriquecido.md` disponível
- `bridge-to-plan.md` aprovado (Research E6)
- Work item Plan em `In Planning` (Etapa 2 inicia)
---
## Passo 1 — Leitura de Inputs
| Arquivo | O que extrair |
|---|---|
| `.specs/research/design-doc-enriquecido.md` | Decisões de stack (Pilares 1-6) |
| `.specs/research/prd.md` | Todos os requisitos funcionais e não-funcionais |
| `tech-decisions-log.md` | Decisões registradas na Etapa 1 |
| `context-map.md` (se Large+) | Bounded Contexts e ACLs |
| `CLAUDE.md` | Padrões de código e convenções |
---
## Passo 2 — Estrutura Canônica da Spec (10 seções obrigatórias)
```markdown
# Spec — {nome do épico/feature}
## §1. Modelos de Dados
[Schema completo: campos, tipos, constraints, índices, migrations]
## §2. APIs e Contratos
[Rotas HTTP/gRPC: verbo, path, request, response, auth, status codes]
## §3. State Machines
[Máquinas de estado para entidades com estados mutáveis]
## §4. Requisitos Não-Funcionais (com valores concretos)
[Performance, disponibilidade, segurança, LGPD — sempre com número]
## §5. Edge Cases e Casos de Erro
[Comportamento esperado para inputs inválidos e falhas externas]
## §6. Escopo Negativo
[O que esta spec explicitamente NÃO implementa]
## §7. Definition of Done (por critério mecânico)
[Sensores que devem passar para considerar spec implementada]
## §8. Dependências Técnicas
[Libs, SDKs, MCPs, serviços externos que esta spec usa]
## §9. Diagrama de Componentes
[Mermaid: quais componentes interagem e como]
## §10. Restrições de Implementação
[Constraints que o builder DEVE respeitar]
## §11. Cenários Gherkin Formais (features Medium+)
[Cenários expandidos das 3 categorias mandatórias por US]
## §12. Rastreabilidade PRD → Spec
[Mapeamento: cada US do PRD → seção da Spec que a implementa]
## §13. Glossário — Ubiquitous Language (espelho do PRD §14)
[Termos canônicos que aparecerão no código]
## §14. Glossário UL — Técnico (espelho do Design Doc §11)
[Aggregates, Entities, Value Objects, Domain Events]
```
---
## Passo 3 — Loop de Cobertura (≥95%)
Após gerar o draft, verificar automaticamente a cobertura:
1. Para cada User Story do PRD §6 → verificar se há seção correspondente na Spec
2. Para cada RNF do PRD §7 → verificar se há critério mecânico na Spec §4 e §7
3. Para cada feature Must Have do canvas → verificar implementação na Spec
```markdown
## Relatório de Cobertura
| Requisito PRD | Coberto na Spec? | Seção |
|---|---|---|
| US-01: {título} | ✅ / ❌ | Spec §{N} |
| RNF-02: {título} | ✅ / ❌ | Spec §4.{N} |
**Cobertura total:** {N}% ({cobertos}/{total} requisitos)
Status: ✅ ≥95% — pronto para Etapa 3 / ❌ {N}% — nova iteração necessária
```
Iterar até ≥95% antes de submeter para a Etapa 3.
---
## Passo 4 — Cenários Gherkin Formais (§11, features Medium+)
Expandir os cenários BDD seed do PRD §15 para as 3 categorias mandatórias:
```gherkin
Feature: {título da US}
Background:
Given {pré-condição comum}
Scenario: Happy path — {nome}
Given {estado inicial}
When {ação principal}
Then {resultado esperado}
Scenario: Edge case — {nome}
Given {estado com entrada de borda}
When {ação no limite}
Then sistema SHALL {comportamento esperado no limite}
Scenario: Invariante violada — {nome}
Given {tentativa de violar regra de domínio}
When {ação proibida}
Then sistema SHALL recusar com {mensagem/comportamento específico}
```
---
## Passo 5 — Rastreabilidade PRD → Spec (§12)
```markdown
## §12. Rastreabilidade PRD → Spec
| PRD | Spec | Status |
|---|---|---|
| US-01 {título} | §2 Rota POST /orders + §1 Modelo Order | ✅ Coberto |
| RNF-P95 < 300ms | §4.1 Performance + §7 DoD sensor `k6 run` | ✅ Coberto |
| Escopo neg. §10 | §6 Escopo negativo da Spec | ✅ Espelhado |
```
---
## Output
- `.specs/{epic-id}/spec.md` — Spec técnica completa (600-1500 linhas)
---
## Estados ADO
| Momento | Estado |
|---|---|
| Etapa 2 inicia (Tech Decisions concluídas) | `In Planning` (mantém) |
| Spec draft gerada com ≥95% cobertura | `In Planning` → `Ready for Review` |
| Etapa 3 (Validator + Enricher) inicia | `Ready for Review` |
---
## Regras Invioláveis
- **≥95% cobertura antes de submeter para Etapa 3** — spec com cobertura menor é rejeitada pelo Spec Validator
- **§6 Escopo Negativo obrigatório** — espelhar e expandir o escopo negativo do PRD §10
- **RNFs com valores concretos** — "deve ser rápido" não é RNF; "P95 < 300ms sob 500 req/s" é
- **State machines para entidades mutáveis** — toda entidade que muda de estado precisa de diagrama
- **§12 Rastreabilidade obrigatória** — permite ao Spec Validator verificar cobertura mecanicamente
- **Idioma** — spec em pt-BR; identificadores técnicos (nomes de campos, rotas, eventos) em inglês
---
id: spec-review
name: Spec Review
description: "Skill para auditoria formal de cobertura da Spec na Etapa 3 da fase Plan, rodando em janela limpa paralela ao Spec Enricher. Usa gotalab/cc-sdd approval-gates + TLC the-fool + TLC technical-design-doc-creator (review mode). Atende o slot Plan E3 (plan-spec-validator) do framework AI-SDLC. Verifica cobertura ≥95% do PRD, consistência com Design Doc e aprovação formal nos Gates de qualidade — gera spec-review-report.md para Gate 2.5 (HITL micro)."
argument-hint: "review | coverage | gate"
metadata:
version: '1.0.0'
category: sdlc
dependencies: []
requires: {}
tags: [spec-review, spec-validator, coverage, approval-gates, the-fool, e3, plan-phase]
---
# Spec Review — Plan E3
## Objetivo
Auditar **cobertura formal** da Spec em relação ao PRD — verificar se ≥95% dos requisitos foram especificados, se há inconsistências com o Design Doc e se a Spec está pronta para decomposição em tasks.
Slot atendido: **Plan E3 — plan-spec-validator**
**Winner v3:** gotalab/cc-sdd `approval-gates` + TLC: `the-fool` + `technical-design-doc-creator` (review mode)
> **Diferença crítica do Spec Enricher:** este agente verifica *cobertura e consistência formal*. O Enricher (`syscoe-spec-enrich-adversarial`) verifica *fragilidade e edge cases*. Rodam em paralelo, ambos em janela limpa.
---
## Quando Usar Esta Skill
- Spec draft (Etapa 2) disponível com ≥95% de cobertura declarada
- Work item Plan em `Ready for Review`
- Roda em **paralelo com o Spec Enricher** — ambos em janelas limpas separadas do Writer
---
## Passo 1 — Leitura de Inputs (janela limpa)
| Arquivo | Propósito |
|---|---|
| `.specs/{epic-id}/spec.md` (draft) | Alvo da auditoria |
| `.specs/research/prd.md` | Referência de todos os requisitos |
| `.specs/research/design-doc-enriquecido.md` | Referência arquitetural |
| `tech-decisions-log.md` | Decisões que devem estar refletidas na Spec |
---
## Passo 2 — Auditoria de Cobertura (via cc-sdd approval-gates)
Para cada requisito do PRD, verificar presença na Spec:
```markdown
## Verificação de Cobertura PRD → Spec
### Requisitos Funcionais (User Stories)
| US | Título | Cobertura na Spec | Seção |
|---|---|---|---|
| US-01 | {título} | ✅ / ❌ / ⚠️ Parcial | Spec §{N} |
...
### Requisitos Não-Funcionais
| RNF | Categoria | Cobertura | Valor concreto? |
|---|---|---|---|
| RNF-01 | Performance | ✅ / ❌ | P95 < 300ms ✅ / genérico ❌ |
...
### Escopo Negativo
| Item PRD §10 | Espelhado na Spec §6? |
|---|---|
| {item} | ✅ / ❌ |
**Cobertura calculada:** {N}/{total} = {%}%
**Status:** ✅ ≥95% — aprovado / ❌ {%}% — bloqueado
```
---
## Passo 3 — Consistência com Design Doc (via technical-design-doc-creator review mode)
Verificar que a Spec não contradiz o Design Doc Enriquecido:
```markdown
## Consistência Spec ↔ Design Doc
| Aspecto | Spec | Design Doc | Status |
|---|---|---|---|
| Schema da tabela `{X}` | {definição na Spec} | {definição no Design Doc} | ✅ / ❌ |
| Stack backend | {mencionado na Spec?} | {decisão no Design Doc} | ✅ / ❌ |
| Padrão de logging | {Spec §4} | {Design Doc §6} | ✅ / ❌ |
| Bounded Context | {Spec respeita BC?} | {context-map.md} | ✅ / ❌ |
```
---
## Passo 4 — Red Team (via `the-fool`)
Aplicar postura adversarial sobre a Spec como um todo:
Perguntas obrigatórias:
- "Esta Spec tem todos os dados que um builder precisa para trabalhar em sessão isolada sem perguntar ao PM?"
- "É possível completar cada task do decomposer sem interpretar ambiguidades?"
- "O escopo negativo é suficientemente explícito para evitar scope creep em Implement?"
- "Há alguma suposição implícita que o builder vai resolver com treinamento genérico?"
---
## Passo 5 — Checklist BDD/DDD (features Medium+)
```markdown
## Checklist BDD/DDD
- [ ] Todas as US Medium+ têm cenários Gherkin nas 3 categorias (happy + edge + invariante)
- [ ] Glossário UL §13 espelha PRD §14 sem termos divergentes
- [ ] Glossário UL técnico §14 espelha Design Doc §11 sem conflitos
- [ ] Aggregates identificados têm invariante transacional explícita
- [ ] Tasks que cruzam BC têm ACL referenciada
```
---
## Passo 6 — Output: `spec-review-report.md`
```markdown
# Spec Review Report — {épico/feature}
**Agente:** Spec Validator (plan-spec-validator)
**Data:** YYYY-MM-DD
**Ciclo:** {1/2/3}
## Cobertura: {%}% ({cobertos}/{total} requisitos)
**Status:** ✅ ≥95% aprovado / ❌ {%}% bloqueado
## Inconsistências Críticas (bloqueiam Gate 2.5)
1. Spec §{N} contradiz Design Doc §{M}: {descrição}
## Problemas Formais (devem ser corrigidos)
1. US-{N}: sem cobertura na Spec
2. RNF-{N}: sem valor concreto (genérico)
## Checklist BDD/DDD
[resultados do Passo 5]
## Observações do Red Team
[resultado do Passo 4]
## Recomendação para Gate 2.5
✅ Spec aprovada para Etapa 4 (junto com relatório do Enricher)
❌ Spec precisa de revisão: {N} bloqueadores
```
---
## Passo 7 — Gate 2.5 (HITL Micro)
Consolidar relatórios do Spec Validator (este) + Spec Enricher (paralelo):
```
Gate 2.5 — Aprovação da Spec
Spec Validator: cobertura {%}%, {N} bloqueadores
Spec Enricher: {N} questões por categoria
Questões para decisão humana:
1. [Bloqueador] {questão do Validator}
2. [Enriquecimento] {questão do Enricher}
[Aprovar spec para Etapa 4 / Solicitar revisão]
```
---
## Estados ADO
| Momento | Estado |
|---|---|
| Etapa 3 inicia (em paralelo com Enricher) | `Ready for Review` → `In Review` |
| Relatório entregue para Gate 2.5 | `In Review` |
| Writer incorpora correções | `In Review` → `Needs Revision` → `In Review` |
| Gate 2.5 aprovado | `In Review` → `In Planning` (Etapa 4) |
---
## Regras Invioláveis
- **Janela limpa** — nunca herdar contexto do Spec Writer
- **Cobertura <95% = bloqueio** — não negociável; Etapa 3 devolve para Etapa 2
- **Inconsistência Spec↔Design Doc = CRÍTICO** — arquitetura e spec não podem contradizer
- **Não substituir o Spec Enricher** — este agente cobre cobertura formal; fragilidade e edge cases são papel do Enricher
- **Máximo 3 ciclos** — após 3 ciclos com bloqueadores → escalar para HITL humano
---
id: syscoe-spec-enrich-adversarial
name: SysCOE Spec Enricher Adversarial
description: "Skill composta SysManager para caça adversarial de edge cases, contradições e invariantes violadas na Spec durante a Etapa 3 da fase Plan, rodando em janela limpa paralela ao Spec Validator. Atende o slot P-E3 spec-enricher (GAP shrink) do framework AI-SDLC. Use quando o orquestrador da fase Plan ativa a Etapa 3 — o agente lê spec.md em janela limpa, caca problemas em 5 categorias e expande cenários BDD para 3 categorias mandatórias por US, gerando spec-enrichment-report.md para o Gate 2.5 (HITL micro). NÃO reescreve a spec — gera relatório de questões. Composta de: TLC tlc-spec-driven (discuss.md) + domain-analysis + tactical-ddd + coupling-analysis + the-fool."
argument-hint: "enrich | bdd | report | gate"
metadata:
version: '2.0.0'
category: sdlc
dependencies: [harness-core]
requires: {}
tags: [spec, enrichment, adversarial, edge-cases, bdd, gherkin, ddd, invariants, gate-2.5, syscoe]
---
# SysCOE Spec Enricher — Plan E3
## Objetivo
Ser o **cético dedicado** da Spec — caçar o que pode quebrar em produção, não o que está faltando formalmente (isso é papel do Spec Validator). Filosofia: "se não houver edge case mapeado, o agente de Implement vai inventar comportamento — geralmente errado".
Slot atendido: **P-E3 spec-enricher (Etapa 3 — Plan)**
> **Diferença crítica do Spec Validator:** o Validator audita *cobertura* (≥95% dos requisitos do PRD cobertos). Este agente audita *fragilidade* (o que pode quebrar). Rodam em paralelo, ambos em janela limpa separada do Spec Writer.
> **Output:** `spec-enrichment-report.md` com questões para o Gate 2.5 (HITL micro). Este agente **não reescreve a spec** — o humano decide como resolver cada questão levantada; o Spec Writer então incorpora as resoluções.
---
## Quando Usar Esta Skill
- Orquestrador da fase Plan ativa a Etapa 3 (Spec Validator e Spec Enricher rodando em paralelo)
- Work item Plan em `Ready for Review` (Spec draft submetida pelo Writer)
- Janela de contexto limpa — sem histórico do Spec Writer
Não usar para:
- Auditar cobertura formal da Spec → papel do Spec Validator
- Criar spec → Plan E2 (`plan-spec-writer`)
- Decompor tasks → Plan E4 (`syscoe-task-decomposer-pro`)
---
## Passo 1 — Leitura de Inputs (janela limpa, paralela ao Validator)
Ler do zero, sem herdar contexto do Spec Writer:
| Arquivo | Propósito |
|---|---|
| `.specs/research/prd.md` | User Stories, escopo negativo, cenários BDD seed |
| `.specs/research/design-doc-enriquecido.md` | Decisões de stack, padrões arquiteturais, RNF |
| `.specs/{epic-id}/spec.md` (draft) | Spec gerada pelo Writer — alvo da caça |
---
## Passo 2 — Caça Adversarial: 5 Categorias Obrigatórias
Nenhuma categoria pode ser pulada. Cada apontamento deve referenciar seção específica da Spec ou do PRD.
### Categoria 1 — Edge Cases de Input
> "O que quebra quando a entrada está no limite ou está fora dele?"
Caçar:
- Login inválido, payload malformado, upload incompleto
- Retry idempotente (o que acontece se o usuário submete duas vezes?)
- Limites de dados não especificados (tamanho máximo de campo, quantidade máxima de itens)
- Pré-condições implícitas não documentadas (o que precisa existir antes desta ação ser possível?)
- Valores de borda (0, -1, null, string vazia, array vazio)
### Categoria 2 — Falhas de Dependências
> "O que acontece quando o mundo externo não coopera?"
Caçar:
- API de terceiro fora do ar ou retornando 503
- Timeout em chamadas externas (qual é o comportamento após N segundos?)
- Rate limit estourado em API externa
- Secrets ausentes ou expirados
- Banco de dados indisponível durante operação de escrita
- Fila de mensagens cheia ou indisponível
### Categoria 3 — Contradições entre PRD e Spec
> "O que a Spec diz que conflita com o PRD?"
Caçar:
- Campo definido com tipo X no PRD §14 (UL), com tipo Y na Spec
- Constraint divergente entre PRD e Spec (ex: PRD diz "máx 100 itens", Spec não limita)
- Regra de negócio descrita de forma diferente nos dois artefatos
- Escopo negativo do PRD violado silenciosamente na Spec (feature implementada que o PRD diz "NÃO")
### Categoria 4 — Race Conditions e Concorrência
> "O que pode dar errado quando dois processos atuam simultaneamente?"
Caçar (via análise de acoplamento — `coupling-analysis`):
- Updates concorrentes no mesmo Aggregate sem controle de concorrência (otimistic/pessimistic lock?)
- Fluxo que assume ordenação de eventos não garantida
- Timeouts não tratados em chamadas externas durante transações
- Estado transitório não descrito (o que o sistema exibe enquanto a operação está em andamento?)
- Dois usuários tentando reservar o mesmo recurso simultaneamente
### Categoria 5 — Invariantes Violadas (DDD Tactical, features Large+)
> "Que regra de domínio o sistema deve recusar mesmo se o usuário pedir?"
Esta é a categoria mais crítica para features com Aggregates identificados. Caçar toda regra de negócio que:
- O sistema deve recusar mesmo que a requisição seja tecnicamente válida
- Define o "não pode acontecer" do domínio (idempotência, autorização, concorrência, reversão, temporalidade, consistência eventual)
Exemplos de invariantes que precisam estar explícitas na Spec:
- "Um pedido cancelado não pode ser reaberto"
- "Transferência não pode exceder saldo disponível"
- "Apenas o criador do recurso pode deletá-lo"
- "O estado X não pode transitar para Y diretamente"
Cada invariante identificada que **não está na Spec** vira questão com sugestão de cenário BDD:
```gherkin
# Invariante violada — cenário mandatório a adicionar
WHEN usuário tenta reabrir pedido cancelado
THEN sistema SHALL recusar com erro "Pedido não pode ser reaberto após cancelamento"
```
---
## Passo 3 — Expansão dos Cenários BDD (3 Categorias Mandatórias por US)
Para cada User Story Medium+ que tenha cenários seed no PRD §15, expandir para **3 categorias mandatórias**:
| Categoria | Pergunta-guia | Sintaxe |
|---|---|---|
| **Happy path** | "O usuário típico, no caminho mais comum, vê o quê?" | `WHEN/THEN/SHALL` — fluxo principal |
| **Edge case** | "O que quebra quando a entrada está no limite?" | `WHEN/THEN/SHALL` — entrada de borda |
| **Invariante violada** | "Que regra de domínio o sistema recusa mesmo se o usuário pedir?" | `WHEN/THEN/SHALL` — sistema SHALL recusar |
US sem cobertura das 3 categorias = bloqueio no Spec Validator (anti-padrão A3).
**Formato dos cenários propostos** (para inclusão na Spec após resolução HITL):
```gherkin
# US-{id} — {título da US}
# Categoria: Happy path
WHEN {ação principal do usuário}
THEN sistema SHALL {resultado esperado no caminho feliz}
# Categoria: Edge case
WHEN {ação com entrada de borda ou limite}
THEN sistema SHALL {comportamento esperado no limite}
# Categoria: Invariante violada
WHEN {tentativa de violar regra de domínio}
THEN sistema SHALL recusar com {mensagem/comportamento específico}
```
---
## Passo 4 — Output: `spec-enrichment-report.md`
O output é um **relatório de questões para HITL**, não uma spec reescrita:
```markdown
# Spec Enrichment Report — {título do épico/feature}
**Agente:** Patrícia Enricher (plan-spec-enricher)
**Data:** YYYY-MM-DD
**Spec analisada:** `.specs/{epic-id}/spec.md` (draft)
## Resumo
- Categoria 1 (Edge cases): {N} questões
- Categoria 2 (Falhas dependências): {N} questões
- Categoria 3 (Contradições PRD↔Spec): {N} questões
- Categoria 4 (Race conditions): {N} questões
- Categoria 5 (Invariantes violadas): {N} questões
- Cenários BDD a adicionar: {N}
---
## Categoria 1 — Edge Cases de Input
### Q1.1 — {título curto}
- **Referência:** Spec §{seção} + PRD US-{id}
- **Comportamento ambíguo:** {descrição do problema}
- **Sugestão A:** {solução proposta A}
- **Sugestão B:** {solução proposta B}
- **Cenário BDD sugerido:**
```gherkin
WHEN {condição de borda}
THEN sistema SHALL {comportamento esperado}
```
[repetir para cada questão por categoria]
---
## Cenários BDD Mandatórios a Adicionar
### US-{id} — {título}
[cenários das 3 categorias conforme Passo 3]
---
## Checklist Gate 2.5
- [ ] Todas as questões de Categoria 3 (Contradições) resolvidas ou aceitas como risco documentado
- [ ] Todas as invariantes de Categoria 5 adicionadas à Spec como cenários BDD mandatórios
- [ ] Todas as race conditions com estratégia de mitigação definida
- [ ] Todas as US Medium+ com 3 categorias BDD cobertas
```
---
## Passo 5 — Estados ADO — WIT SDLC Plan
| Momento | Estado ADO |
|---|---|
| Etapa 3 inicia (em paralelo com Validator) | `Ready for Review` → `In Review` |
| Questões enviadas para Gate 2.5 | Mantém `In Review` |
| Gate 2.5 aprova resolução | `In Review` → `Needs Revision` (Writer incorpora) |
| Writer revisou e resubmeteu | `Needs Revision` → `In Review` |
| Convergência (max 3 ciclos) | `In Review` → `In Planning` (Etapa 4 inicia) |
> Anti-padrão: nunca setar `Approved`, `In Validate` ou `Done` — este agente é Validador-Juiz lateral, não fecha gates terminais.
---
## Regras Invioláveis
- **Janela limpa obrigatória** — nunca herdar contexto do Spec Writer
- **5 categorias obrigatórias** — pular qualquer uma invalida o relatório
- **Output é relatório, não spec reescrita** — o humano decide como resolver cada questão; o Writer incorpora
- **Toda questão âncora na Spec ou PRD** — questão sem referência específica não é aceita
- **Invariante sem cenário BDD** não está resolvida — toda invariante vira cenário `SHALL recusar`
- **Generalização proibida** — em vez de "tratar erros", escrever "se Stripe retorna 503, retry 3x com backoff exponencial; após retries, registrar evento `payment.degraded` e retornar 503 ao cliente"
- **Idioma** — gerar no idioma da solicitação; termos de domínio e Gherkin em inglês quando estabelecidos no glossário UL
---
id: syscoe-sprint-capacity
name: SysCOE Sprint Capacity
description: "Skill custom 100% SysManager para validação de sprint plan e capacidade dos times na Etapa 5 da fase Plan — único slot sem equivalente externo adequado. Usa ADO work_get_team_capacity + TLC the-fool + phuryn/pm-skills/pre-mortem. Atende o slot Plan E5 (plan-sprint-validator) do framework AI-SDLC. Verifica se as tasks decompostas cabem na capacidade real dos times, detecta over-commitment e aplica pre-mortem para antecipar riscos de entrega."
argument-hint: "validate | capacity | premortem | report"
metadata:
version: '1.0.0'
category: sdlc
dependencies: [harness-core]
requires: {}
tags: [sprint, capacity, planning, pre-mortem, over-commitment, velocity, e5, plan-phase, syscoe]
---
# SysCOE Sprint Capacity — Plan E5
## Objetivo
Validar que as tasks decompostas na Etapa 4 **cabem na capacidade real dos times** e antecipar riscos de entrega com pre-mortem antes de comprometer o sprint plan.
Slot atendido: **Plan E5 — plan-sprint-validator (único GAP sem equivalente externo adequado)**
**Winner v3:** Custom 100% SysManager — `work_get_team_capacity` (ADO MCP) + TLC: `the-fool` + phuryn/pm-skills: `pre-mortem`
---
## Quando Usar Esta Skill
- Etapa 4 (Task Decomposer) concluída, `tasks.md` disponível com sprint plan inicial
- Work item Plan em `Ready for Review` (Etapa 5 inicia)
- Equipe e iterações configuradas no ADO
---
## Passo 1 — Leitura de Capacidade Real (ADO)
Via `work_get_team_capacity` (MCP ADO):
```markdown
## Capacidade Real — Sprint {nome}
| Membro | Time | Dias disponíveis | Horas/dia | Capacidade bruta |
|---|---|---|---|---|
| {nome} | Backend | {N} dias | {N}h | {N}h |
| {nome} | Frontend | {N} dias | {N}h | {N}h |
| {nome} | QA | {N} dias | {N}h | {N}h |
**Capacidade bruta total:** {N}h
**Fator de cerimônias** (daily, planning, retro, refinamento): -{N}h
**Capacidade líquida:** {N}h ≈ {N} SP (velocity média: {N} SP/sprint)
```
---
## Passo 2 — Comparar Tasks × Capacidade
Do `tasks.md` (Etapa 4), extrair total planejado por sprint:
```markdown
## Comparativo Sprint {N}
| Perfil | SP Planejados | Capacidade Líquida | Status |
|---|---|---|---|
| Backend | {N} SP | {N} SP | ✅ OK / ⚠️ +{N}% / ❌ Over |
| Frontend | {N} SP | {N} SP | ✅ / ⚠️ / ❌ |
| QA | {N} SP | {N} SP | ✅ / ⚠️ / ❌ |
| **Total** | **{N} SP** | **{N} SP** | ✅ / ⚠️ / ❌ |
**Over-commitment:** {%}% acima da capacidade
```
**Limiares:**
- ≤ 100% capacidade → ✅ OK
- 100-115% → ⚠️ Atenção (buffer de risco consumido)
- > 115% → ❌ Over-commitment — tasks devem ser movidas para próximo sprint
---
## Passo 3 — Rebalanceamento (se necessário)
Se over-commitment detectado, propor rebalanceamento:
```markdown
## Proposta de Rebalanceamento
### Tasks a mover para Sprint {N+1}
| Task | SP | Justificativa |
|---|---|---|
| {task com menor prioridade} | {N} SP | {motivo de ser adiada} |
### Sprint {N} após rebalanceamento
SP planejados: {N} ({%}% da capacidade) → ✅ Viável
```
Apresentar proposta ao PM/PO via Gate 5 antes de confirmar.
---
## Passo 4 — Pre-mortem (via phuryn/pm-skills)
Aplicar pre-mortem no sprint plan:
> "Imaginem que estamos no final do Sprint {N} e ele falhou. O que aconteceu?"
Identificar os 3-5 riscos mais prováveis:
```markdown
## Pre-mortem — Sprint {N}
| Risco | Probabilidade | Impacto | Mitigação |
|---|---|---|---|
| Task X bloqueada por dependência externa Y | Alta | Alto | Acionar fornecedor Y na semana 1 |
| Estimativa de Task Z muito otimista (8 SP) | Média | Médio | Dividir Z em Z1+Z2 antes do sprint |
| Membro do time X em férias na semana 2 | Confirmado | Alto | Redistribuir tasks de X para semana 1 |
```
---
## Passo 5 — Red Team (via `the-fool`)
Questionar o sprint plan:
- "Qual task vai atrasar e por quê?"
- "Qual dependência técnica não foi mapeada?"
- "O que acontece se a task de QA precisar de mais 2 dias?"
- "Qual task tem estimativa claramente otimista?"
---
## Passo 6 — Gate 5 (HITL)
```
Gate 5 — Aprovação do Sprint Plan
Sprint {N}: {N} SP planejados / {N} SP disponíveis ({%}%)
Pre-mortem: {N} riscos identificados, {N} mitigados
O sprint plan está aprovado?
[Aprovar / Rebalancear {tasks específicas} / Ajustar capacidade]
```
---
## Output
Gerar `sprint-capacity-report.md` com:
- Comparativo tasks × capacidade por perfil
- Proposta de rebalanceamento (se necessário)
- Pre-mortem com riscos e mitigações
- Sprint plan aprovado (após Gate 5)
---
## Estados ADO
| Momento | Estado |
|---|---|
| Etapa 5 inicia | `Ready for Review` (mantém) |
| Análise e pre-mortem em andamento | `Ready for Review` |
| Gate 5 aprovado | `Ready for Review` → `In Validate` (Bridge E6) |
---
## Regras Invioláveis
- **Capacidade via ADO** — nunca usar estimativa manual de capacidade; buscar via `work_get_team_capacity`
- **> 115% = over-commitment** — bloquear sprint plan e exigir rebalanceamento
- **Pre-mortem antes do Gate 5** — sprint sem pre-mortem não é validado
- **Gate 5 é humano** — PM/PO devem confirmar o sprint plan; agente não auto-aprova
- **Velocity histórica** — se disponível no ADO, usar velocity média dos últimos 3 sprints; não usar estimativa estática
---
id: syscoe-task-decomposer-pro
name: SysCOE Task Decomposer Pro
description: "Skill composta SysManager para decomposição da Spec Enriquecida em PBIs e tasks atômicas com DoD verificável mecanicamente, tags [P] de paralelismo, estimativas Fibonacci, BDD Scenario ID por task e criação de WIs ADO após Gate 4 humano. Atende o slot P-E4 task-decomposer do framework AI-SDLC. Use quando o orquestrador da fase Plan ativa a Etapa 4 após Gate 3 (Spec Enriquecida aprovada). Modelo recomendado: Sonnet (custo/benefício para decomposição estruturada). Composta de: gotalab cc-sdd (tasks phase) + TLC decomposition-planning-roadmap + component-identification-sizing + modular-decomposition com bridge de rastreabilidade spec-block↔BDD-scenario↔task↔WI ADO."
argument-hint: "decompose | sprint | ado | review"
metadata:
version: '2.0.0'
category: sdlc
dependencies: [harness-core]
requires: {}
tags: [task-decomposition, pbi, work-items, ado, bdd, dod, fibonacci, parallelism, bc-boundary, syscoe]
---
# SysCOE Task Decomposer Pro — Plan E4
## Objetivo
Transformar a Spec Enriquecida em **PBIs (fatias verticais de valor) + tasks atômicas com DoD verificável mecanicamente** — tarefas que cabem em uma sessão com <30% contexto, com critério de done checável por sensor externo, com rastreabilidade bidirecional spec-block ↔ cenário BDD ↔ WI ADO.
Slot atendido: **P-E4 task-decomposer (Etapa 4 — Plan)**
> **Modelo recomendado: Claude Sonnet** — decomposição estruturada não exige raciocínio profundo de trade-offs. Usar Opus aqui é anti-padrão de custo.
---
## Quando Usar Esta Skill
- Orquestrador da fase Plan ativa a Etapa 4 após Gate 3 (Spec Enriquecida aprovada)
- Work item Plan em `In Planning` (Spec Enriquecida liberada pelo Gate 2.5)
- `parallelism-map.md` da Research disponível (para respeitar épicos paralelos)
Não usar para:
- Enriquecer spec → Plan E3 (`syscoe-spec-enrich-adversarial`)
- Criar WIs ADO sem Gate 4 humano aprovado → nunca criar antes da aprovação
- Estimar capacidade → Plan E5 (sprint-validator)
---
## Passo 1 — Leitura de Inputs
| Arquivo | Propósito |
|---|---|
| `.specs/{epic-id}/spec.md` (Spec Enriquecida, após Gate 3) | Fonte dos blocos de spec e cenários BDD |
| `.specs/research/parallelism-map.md` | Épicos identificados e tags `[P]` da Bridge to Plan |
| Capacidade declarada | pts/sprint e número de devs (fornecido pelo orquestrador) |
---
## Passo 2 — Agrupamento em PBIs por Fatia Vertical
Agrupar a Spec em **PBIs vinculados a Features ADO** (criadas pela Bridge to Plan da Research). Cada PBI é uma fatia vertical de valor entregável — não um componente técnico horizontal.
> Anti-padrão: PBI "Criar camada de banco de dados" é horizontal. Correto: PBI "Usuário pode criar conta e fazer login" é vertical.
---
## Passo 3 — Decomposição em Tasks Atômicas
Para cada PBI, decompor em tasks com os campos obrigatórios:
```markdown
### Task: {título acionável — verbo no infinitivo + substantivo concreto}
| Campo | Valor |
|---|---|
| **Bloco da Spec** | Spec §{seção} — "{trecho âncora}" |
| **Cenário BDD ID** | Spec §11 — cenário `{id}` ("{nome do cenário Gherkin}") |
| **Tipo** | Backend / Frontend / Infra / QA / Dados |
| **Estimativa** | {1/2/3/5/8} SP |
| **Tag [P]** | ✅ Paralelizável / ❌ Sequencial |
| **Dependências** | [Task-X, Task-Y] ou nenhuma |
| **Aggregate alvo** | `{NomeAggregate}` (features Large+) ou N/A |
**Definition of Done (verificável mecanicamente):**
```yaml
definition-of-done:
static-checks: [lint, typecheck]
unit-tests: ["coverage >= {N}% no módulo {X}"]
contract-tests: ["openapi-validator passa para rota {Y}"]
integration-tests: ["cenário BDD {id} passa end-to-end"]
manual-checks: ["[apenas se não automatizável] {critério específico}"]
```
```
### Regras de Atomicidade
- Uma task = um artefato testável entregável em uma sessão (<30% contexto)
- Máximo de **um tipo** por task — se exige Backend + Frontend → dividir em duas tasks
- Tasks de QA são criadas automaticamente para toda task de implementação com AC Gherkin
- **Nenhuma task sem DoD mecânico** — "funciona bem" não é DoD
- **Toda task âncora na Spec** — task sem `Bloco da Spec` referenciado é anti-padrão
- **Toda task Medium+ aponta para ≥1 Cenário BDD ID** — o DoD valida o cenário executável
### Anti-Padrões de Granularidade
| Anti-padrão | Por quê é problema | Correto |
|---|---|---|
| `Task: Criar variável de ambiente X` | Granulação excessiva — não é artefato testável | Agrupar em `Task: Setup do épico — env vars + configs` |
| `Task: Criar db.ts` + `Task: Criar db.test.ts` | Split por arquivo — mesmo artefato | `Task: Implementar persistência para transactions (db.ts + testes)` |
| Task sem DoD | Critério subjetivo de done | Sempre DoD mecânico via sensor |
| Task sem âncora na Spec | Scope creep silencioso | Toda task referencia seção da Spec |
---
## Passo 4 — Estimativas Fibonacci
Usar escala Fibonacci: **1 / 2 / 3 / 5 / 8** Story Points.
| SP | Complexidade | Indicadores |
|---|---|---|
| 1 | Trivial | CRUD simples, padrão idêntico já existe no projeto |
| 2 | Baixa | Lógica simples, sem integrações, teste direto |
| 3 | Média | Lógica de negócio moderada ou 1 integração |
| 5 | Alta | Lógica complexa, múltiplas integrações ou padrão novo |
| 8 | Muito alta | Nova área técnica, risco elevado — considerar dividir |
> Task com estimativa 8 é sinal de quebra necessária: se pode ser dividida em 2 tasks de 3-5, dividir.
---
## Passo 5 — Tags `[P]` de Paralelismo
Herdar tags `[P]` do `parallelism-map.md` da Research. Para cada task, marcar:
- `[P]` — pode ser executada em paralelo com outras tasks do mesmo PBI (sem dependência de dados ou contrato)
- Sem tag — deve ser executada em sequência (depende de output de task anterior)
Gerar grafo de dependências em Mermaid:
```mermaid
graph TD
T1[Task 1: Setup do schema] --> T3[Task 3: Implementar persistência]
T2[Task 2: Setup de autenticação] --> T3
T3 --> T4[Task 4: Implementar rota POST /orders]
T4 --> T5[Task 5: QA — cenário BDD US-03]
```
---
## Passo 6 — Fronteiras de Bounded Context (features Large+)
Para cada task que envolve múltiplos BCs:
1. Verificar se a task cruza fronteira de Bounded Context
2. Se cruza: verificar se há ACL declarada em `context-map.md`
3. Se não há ACL → **bloquear task** e exigir declaração de ACL antes de prosseguir
4. Se ACL existe → referenciar na task: `Requer ACL: {nome da ACL} em context-map.md §{seção}`
---
## Passo 7 — Sprint Plan Inicial
Organizar tasks em sprints baseado em dependências e capacidade declarada:
```markdown
## Sprint Plan — {épico/feature}
| Sprint | Tasks | SP Planejados | SP Disponíveis | Entregável |
|---|---|---|---|---|
| Sprint N | [T1, T2 (P)] | {N} | {N} | {o que fica pronto} |
| Sprint N+1 | [T3, T4] | {N} | {N} | {entregável} |
| Sprint N+2 | [T5-QA, T6] | {N} | {N} | {entregável final} |
```
Alertar se tasks planejadas > capacidade + 15% (over-commitment).
---
## Passo 8 — Saída Canônica
Gerar `tasks.md` por épico:
```markdown
# Tasks — {título do épico}
**Epic:** #{id ADO}
**Spec:** `.specs/{epic-id}/spec.md` (Enriquecida, Gate 3 aprovado)
**Total de tasks:** {N} | **Total estimado:** {N} SP | **Sprints:** {N}
## PBI-01: {título da fatia vertical}
### Task T01 — {título}
[campos obrigatórios conforme Passo 3]
### Task T02 — {título} [P]
[campos obrigatórios]
## PBI-02: {título}
...
## Grafo de Dependências
[diagrama Mermaid]
## Sprint Plan
[tabela conforme Passo 7]
```
---
## Passo 9 — Criação de WIs ADO (somente após Gate 4 humano)
**Apresentar tasks ao orquestrador para revisão humana (Gate 4) antes de criar qualquer WI ADO.**
```
Vou criar {N} Work Items no ADO vinculados ao Epic #{id}:
- {N} PBIs como filhos da Feature #{id}
- {N} Tasks como filhos de cada PBI
Confirma? [s/n]
```
Após confirmação, delegar ao `syscoe-board-ado-pro` (Haiku):
- `wit_add_child_work_items` para criar a hierarquia
- Preencher: título, descrição com spec-block + cenário BDD + DoD, estimativa, iteração
---
## Passo 10 — Estados ADO — WIT SDLC Plan
| Momento | Estado ADO |
|---|---|
| Etapa 4 inicia (Spec Enriquecida aprovada) | Mantém `In Planning` |
| `tasks.md` + sprint plan gerados | `In Planning` → `Ready for Review` |
| Sprint Validator (E5) aponta ajustes | `Ready for Review` → `In Planning` |
| Sprint Validator aprova | Mantém `Ready for Review` (E5 continua) |
> Anti-padrão: criar PBIs/Tasks no ADO antes do Gate 4 humano aprovar — o board não pode ter tasks que ainda podem mudar.
---
## Regras Invioláveis
- **Toda task âncora na Spec** — sem referência ao bloco da Spec, a task não existe
- **DoD mecânico obrigatório** — sensor externo verificável; sem DoD subjetivo
- **BDD Scenario ID obrigatório para Medium+** — todo cenário BDD da Spec deve ter ≥1 task que o executa
- **Fronteira de BC** — task que cruza BC sem ACL é bloqueada automaticamente
- **Gate 4 antes do ADO** — nunca criar WIs antes da aprovação humana
- **Modelo: Sonnet** — decomposição estruturada; Opus é anti-padrão de custo aqui
- **Idioma** — gerar no idioma da solicitação; termos de domínio e campos ADO em inglês
---
id: syscoe-tech-decider-7pillars
name: SysCOE Tech Decider — 6 Pilares
description: "Skill composta SysManager para conduzir decisões tecnológicas na Etapa 1 da fase Plan via conversa estruturada HITL em 6 pilares (BD / Backend / Frontend / Segurança / DDD Strategic / Granularidade F1-F4). Atende o slot P-E1 tech-decider do framework AI-SDLC. Use quando o orquestrador da fase Plan ativa a Etapa 1 para tomar decisões de stack antes da geração da Spec. Nunca decide sozinho — apresenta 2-3 opções com trade-offs e espera arbitragem humana. Composta de: TLC create-adr + tactical-ddd + modular-design-principles + coupling-analysis com wrapper SysManager (6-criteria test de granularidade, fallback via Rules, ADR draft obrigatório por decisão significativa)."
argument-hint: "start | pilar1 | pilar2 | pilar3 | pilar4 | pilar5 | pilar6 | finalize"
metadata:
version: '2.0.0'
category: sdlc
dependencies: [create-adr]
requires: {}
tags: [tech-decision, architecture, ddd, granularity, f1-f4, coupling, plan, e1, hitl, syscoe]
---
# SysCOE Tech Decider — Plan E1
## Objetivo
Forçar decisões tecnológicas concretas em **conversa estruturada com humano** antes da Spec ser gerada. O Spec Writer recebe o `design-doc-enriquecido.md` como input — se ele receber o Design Doc da Research direto, sem as Tech Decisions, chutará stack, ORM, framework de testes e padrão de autenticação com base em treinamento genérico.
Slot atendido: **P-E1 tech-decider (Etapa 1 — Plan)**
> **Princípio fundamental:** este agente nunca decide sozinho. Para cada pilar: apresenta 2-3 opções com trade-offs → espera decisão do Tech Lead/SRE/SecEng → registra escolha + justificativa.
---
## Quando Usar Esta Skill
- Orquestrador da fase Plan ativa a Etapa 1
- Antes de qualquer geração de Spec (Etapa 2)
- Há decisões de stack, DDD ou granularidade não cobertas pelas Rules do projeto
Não usar para:
- Criar Design Doc → slot Research E5B (`syscoe-design-doc-suite`)
- Gerar Spec → slot Plan E2 (`plan-spec-writer`)
- Decompor tasks → slot Plan E4 (`syscoe-task-decomposer-pro`)
---
## Passo 1 — Leitura de Inputs
Ao iniciar, ler:
| Arquivo | Propósito |
|---|---|
| `.specs/research/design-doc.md` (ou `design-doc-enriquecido.md` se já parcial) | Arquitetura macro da Research |
| `.specs/research/prd.md` | User Stories, escopo, features priorizadas |
| `CLAUDE.md` / `AGENTS.md` (Rules) | Decisões de stack já tomadas → auto-resolver sem escalar |
| `viability-report.md` + `parallelism-map.md` | Épicos aprovados na Bridge to Plan |
### Fallback automático via Rules
Se Rules (`CLAUDE.md`/`AGENTS.md`) já documenta uma decisão (ex: "todo backend novo em Node.js + Fastify"), preencher automaticamente e marcar como `auto-resolvido (rules)`. **Não escalar para HITL o que já está decidido.** Apenas pilares sem cobertura geram conversa.
---
## Passo 2 — Os 6 Pilares (sequência obrigatória)
Conduzir um pilar de cada vez, nesta ordem. Não misturar pilares.
### Pilar 1 — Banco de Dados
Perguntas a decidir com Tech Lead/SRE:
- Engine: relacional (PostgreSQL, MySQL) vs NoSQL (MongoDB, DynamoDB) vs híbrido?
- Schema concreto: quais entidades principais, tipos de dados, constraints?
- Migrations: estratégia (Flyway, Prisma, Alembic, custom)?
- Índices críticos: quais colunas serão filtradas/ordenadas em produção?
- Particionamento: necessário no MVP? Se sim, por qual chave?
Apresentar 2-3 opções com trade-offs. Registrar decisão + justificativa.
### Pilar 2 — Backend
Perguntas a decidir:
- Linguagem + framework (ex: Node.js + Fastify, Python + FastAPI, Go + Gin)?
- Organização de módulos (feature-based, layer-based, ports-and-adapters)?
- Runtime de testes (Jest, Pytest, Go test)?
- Padrão de tratamento de erros?
- Padrão de logging (biblioteca + formato)?
Apresentar 2-3 opções. Registrar.
### Pilar 3 — Frontend (se aplicável)
Perguntas a decidir:
- Framework (Next.js, React SPA, Vue, sem frontend)?
- State management (Zustand, Redux, React Query, Context)?
- Design system (Shadcn, MUI, Tailwind puro, custom)?
- Build tool (Vite, Turbopack, webpack)?
Apresentar 2-3 opções. Registrar. Se não há frontend → marcar `N/A` e prosseguir.
### Pilar 4 — Segurança
Perguntas a decidir com SecEng:
- Autenticação: JWT, OAuth2/OIDC, session-based, API keys?
- Autorização: RBAC, ABAC, policy-based?
- Secrets: onde armazenar (vault, env vars, secrets manager)?
- Rate limiting: por IP, por usuário, por API key? Biblioteca?
- Compliance: LGPD aplicável? DPIA necessário? Dados pessoais processados?
Apresentar 2-3 opções. Registrar.
### Pilar 5 — DDD Strategic Refinement (features Large+ apenas)
> Pular em features Quick/Medium. Para Large+: conduzir obrigatoriamente.
1. **Confirmar Bounded Contexts do PRD §14:** as relações entre BCs estão claras? Há BC esquecido descoberto durante Tech Decisions?
2. **Tactical Patterns por Aggregate:** para cada Aggregate candidato, validar com Tech Lead/Owner que existe **invariante transacional explícita** que justifica o Aggregate. Sem invariante → é Entity ou agrupamento simples.
- Anti-padrão A4 vetado: sufixos `-Manager`/`-Helper`/`-Service` escondendo aggregate root
3. **Anti-Corruption Layer (ACL):** integração com BCs externos com vocabulário diferente exige ACL. Documentar tradução.
Output deste pilar: `context-map.md` com relações entre BCs (`Customer-Supplier`, `Conformist`, `Anti-Corruption Layer`, `Shared Kernel`, `Open Host Service`, `Published Language`).
### Pilar 6 — Granularidade Arquitetural (F1-F4)
> Aplicável a features Large+ ou quando o Service afetado existe no `sys-ai-augmented`. Em Quick/Medium → default F1 sem discussão.
#### As 4 Fases de Granularidade
| Fase | Nome | Prática |
|---|---|---|
| **F1** | Monólito Modular | Default. Uma app única; módulos coesos com fronteiras lógicas; deploy unificado |
| **F2** | Modular com Fronteiras Claras | Mesmo monólito + governance forte (enforce-module-boundaries, observabilidade por módulo) |
| **F3** | Apps Dedicadas | Módulos críticos em apps próprias; deploy/escala independentes |
| **F4** | Microservices | Comunicação exclusivamente via rede; cada serviço unidade independente de release |
#### 6-Criteria Test para Decidir a Fase
Aplicar os 6 critérios abaixo. Cada critério verdadeiro = 1 ponto:
| Critério | Pergunta |
|---|---|
| **Language** | O módulo precisa de linguagem diferente da app principal? |
| **Rate of change** | O módulo tem cadência de deploy significativamente diferente? |
| **Scale / SLO** | O módulo tem requisito de escala ou SLO incompatível com o monólito? |
| **Consistency** | O módulo precisa de modelo de consistência diferente (ex: eventual vs. forte)? |
| **Ownership** | O módulo é de propriedade de equipe diferente com autonomia de deploy? |
| **Pain signal** | Há evidência concreta de dor operacional (incidentes, deploys acoplados)? |
**Interpretação dos pontos:**
- **0-1 critérios** → F1 (default). Não discutir.
- **2 critérios** → F1 + nota "monitorar" no `tech-decisions-log.md`; revisar em 1-2 sprints.
- **3+ critérios** → propor F2 ou F3 com justificativa explícita do critério dominante.
- **F3 → F4** exige 3+ critérios **mais** maturidade operacional (observabilidade distribuída, SRE, runbooks prontos).
> **Anti-cargo-cult:** "os arquivos ficaram grandes" e "quero microservices" **não são** critérios. Se o único motivo é estético ou hype, mantém F1.
> **Reversibilidade:** registrar no `tech-decisions-log.md` que **descer de fase é prática esperada** quando overhead não se paga (F4 → F3, F3 → F2). Isso diferencia o framework de arquiteturas microservices clássicas.
---
## Passo 3 — Outputs Obrigatórios
Ao concluir os 6 pilares, gerar:
### 3.1 — `design-doc-enriquecido.md`
Design Doc da Research com **camada de Tech Decisions adicionada**. Não sobrescrever — adicionar seção nova:
```markdown
## Tech Decisions — Etapa 1 Plan
### Pilar 1 — Banco de Dados
**Decisão:** PostgreSQL 16 com Prisma ORM
**Alternativas consideradas:** MySQL 8, MongoDB
**Justificativa:** ...
**Auto-resolvido via Rules:** não (nova decisão)
### Pilar 2 — Backend
...
```
### 3.2 — `tech-decisions-log.md`
Registro auditável de cada escolha:
```markdown
# Tech Decisions Log — [Epic/Feature]
| Data | Pilar | Decisão | Alternativas | Justificativa | Decidido por |
|---|---|---|---|---|---|
| YYYY-MM-DD | BD | PostgreSQL + Prisma | MySQL, MongoDB | ... | Tech Lead João |
| YYYY-MM-DD | Backend | Node.js + Fastify | Go, Python | auto-resolvido (rules) | — |
```
### 3.3 — ADR Drafts em `docs/adr/ADR-XXXX-<slug>.md`
**Toda decisão tecnológica significativa** (escolha que persistirá além desta feature, cria lock-in ou afeta repos vizinhos) gera um ADR draft com `Status: ⏳ Proposed`.
- Decisões cobertas por Rules (`auto-resolvido (rules)`) → **não geram ADR**
- Decisões locais triviais (lib de utilidade, escolha estética) → **não geram ADR**
- Numeração `XXXX` literal até o merge para evitar colisão em PRs paralelos
```markdown
# ADR-XXXX — [Título da Decisão]
**Status:** ⏳ Proposed
**Data:** YYYY-MM-DD
**Contexto:** [o que levou a esta decisão]
**Decisão:** [o que foi decidido]
**Alternativas consideradas:** [opção B, opção C e por que foram descartadas]
**Consequências:** [o que muda com esta decisão; trade-offs aceitos]
**Aprovadores:** [Tech Lead, SRE, SecEng — conforme categoria do ADR]
```
> Doutrina canônica + matriz de aprovação por categoria: `ADR-Pattern.md` em Governança-e-Harness.
### 3.4 — `context-map.md` (features Large+ — Pilar 5)
Mapa de relações entre Bounded Contexts:
```markdown
# Context Map — [Feature/Epic]
## Bounded Contexts
| BC | Subdomain | Owner |
|---|---|---|
| Payments | Core | Time Backend |
| Notifications | Supporting | Time Platform |
## Relações
| De | Para | Padrão | Descrição |
|---|---|---|---|
| Payments | Notifications | Customer-Supplier | Payments publica eventos; Notifications consome |
| Payments | ExternalGateway | Anti-Corruption Layer | ACL traduz API Stripe → modelo interno |
```
---
## Passo 4 — Estados ADO — WIT SDLC Plan
| Momento | Estado ADO |
|---|---|
| Etapa 1 inicia | `Todo` → `In Planning` |
| Tech Decisions em curso (conversas nos pilares) | `In Planning` |
| Bloqueio externo (decisão pendente de stakeholder) | `Blocked` |
| Etapa 1 concluída (Etapa 2 Spec Writer começa) | Mantém `In Planning` |
> Anti-padrão: nunca setar `Approved` ou `Done` (conquistados pela Bridge Etapa 6 + Owner — Constitution Art. 4).
---
## Anti-Padrões
- **Decidir sozinho** quando Rules não cobre — sempre HITL com opções e trade-offs
- **Apresentar 1 opção** — sempre 2-3 com trade-offs explícitos
- **Pular pilares** — todos os 4 pilares base são obrigatórios mesmo com resposta trivial
- **Misturar pilares** — BD não se mistura com Frontend; uma conversa de cada vez
- **Aggregate inflado** (A4) — toda entidade virando Aggregate; sufixos `-Manager`/`-Helper` escondendo aggregate root; Aggregate **só** com invariante transacional explícita
- **Subir para F3/F4 sem 3+ critérios** do 6-criteria test — viola Constitution Art. 13c
- **Decisão sem ADR draft** — toda escolha que cria lock-in ou afeta repos vizinhos precisa de ADR; sem ADR a decisão some quando o épico fecha
- **Modelo errado** — Tech Decisions exigem raciocínio profundo de trade-offs; usar Opus 4.6 ou equivalente
- **Idioma** — gerar no idioma da solicitação; nomes de padrões DDD e fases F1-F4 permanecem em inglês
---
id: bridge-handshake
name: Bridge Handshake
description: "Skill para transição de fase via handshake canônico — gera viability-report, parallelism-map (Mermaid DAG) e bridge-handshake.md para transferência segura entre Research→Plan ou Plan→Implement. Usa gotalab/cc-sdd phase-gate handoff + TLC tlc-spec-driven session-handoff. Atende os slots Research E6 (research-bridge-planner) e Plan E6 (plan-bridge-implementer) do framework AI-SDLC."
argument-hint: "research-to-plan | plan-to-implement | check"
metadata:
version: '1.0.0'
category: sdlc
dependencies: [harness-core]
requires: {}
tags: [bridge, handshake, phase-gate, viability, parallelism-map, session-handoff, e6, research-phase, plan-phase]
---
# Bridge Handshake — Research E6 / Plan E6
## Objetivo
Garantir que a transição entre fases seja **explícita, auditável e reversível** — com mapa de paralelismo para a fase seguinte, checklist de completude e contrato de handoff que o próximo agente pode verificar mecanicamente.
Slots atendidos:
- **Research E6 — research-bridge-planner** (Bridge Research → Plan)
- **Plan E6 — plan-bridge-implementer** (Bridge Plan → Implement)
**Winner v3:** gotalab/cc-sdd `phase-gate handoff` + TLC: `tlc-spec-driven session-handoff`
---
## Quando Usar Esta Skill
### Research E6 (Bridge Research → Plan)
- Gate Bridge do orquestrador Research ativado após HITL Final (Gate 5) aprovado
- PRD e Design Doc aprovados e commitados
- Argumento: `research-to-plan`
### Plan E6 (Bridge Plan → Implement)
- Gate Bridge do orquestrador Plan ativado após Gate 5 (Sprint Validator) aprovado
- Spec Enriquecida, Tasks e progress.md aprovados e commitados
- Argumento: `plan-to-implement`
---
## Modo: `research-to-plan`
### Passo 1 — Checklist de Completude Research
```markdown
## Checklist Bridge Research → Plan
- [ ] `prd.md` aprovado pelo HITL Final e commitado
- [ ] `design-doc.md` aprovado pelo HITL Final e commitado
- [ ] `prd-audit-report.md` com 0 CRÍTICOs pendentes
- [ ] Cenários BDD seed presentes em todas as US Medium+
- [ ] Ubiquitous Language §14 com termos [CONFIRMED]
- [ ] Épicos identificados (mínimo 1, máximo 15)
- [ ] Features ADO criadas no board (1 por épico)
```
### Passo 2 — Viability Report
Auditar o Design Doc contra as Rules e restrições conhecidas:
```markdown
# Viability Report — {projeto}
## Viabilidade Técnica por Épico
| Épico | Viabilidade | Dependências | Riscos |
|---|---|---|---|
| {épico 1} | ✅ Viável / ⚠️ Condicionado / ❌ Bloqueado | {deps} | {riscos} |
## Lacunas Técnicas Identificadas
{o que o Design Doc não cobre e precisa ser resolvido em Plan E1}
## Decisão
✅ Viável para Plan — avançar
⚠️ Condicionado — resolver {lacunas} antes de Plan E1
```
### Passo 3 — Parallelism Map (Mermaid DAG)
Mapear quais épicos podem ser desenvolvidos em paralelo:
```mermaid
graph TD
PRD[PRD Aprovado] --> E1[Épico 1: Auth]
PRD --> E2[Épico 2: Dashboard]
E1 --> E3[Épico 3: Permissões]
E2 --> E4[Épico 4: Relatórios]
E3 --> E4
```
Tags `[P]` nos épicos que podem rodar em paralelo.
### Passo 4 — Bridge to Plan Document
Gerar `.specs/research/bridge-to-plan.md`:
```markdown
# Bridge to Plan — {projeto}
**Status:** Aprovado pelo HITL Final em {data}
**PRD:** `.specs/research/prd.md` (SHA: {hash})
**Design Doc:** `.specs/research/design-doc.md` (SHA: {hash})
## Épicos para Plan
| Épico | Feature ADO | Paralelo? | Priority |
|---|---|---|---|
| {épico} | #{id} | [P] / Sequencial | P1/P2/P3 |
## Artefatos de Handoff
- `viability-report.md` — {N} lacunas técnicas para Plan E1
- `parallelism-map.md` — {N} épicos, {N} paralelos
- Features ADO: #{ids}
## Contrato para Plan
O agente `plan-tech-decider` deve resolver as lacunas técnicas listadas no viability-report antes de iniciar o Spec Writer.
```
---
## Modo: `plan-to-implement`
### Passo 1 — Checklist de Completude Plan
```markdown
## Checklist Bridge Plan → Implement
- [ ] `spec.md` (Spec Enriquecida) aprovada e commitada
- [ ] `tasks.md` com tasks atômicas, DoD mecânico e estimativas Fibonacci
- [ ] `progress.md` criado com estado inicial do épico
- [ ] PBIs e Tasks criados no ADO (após Gate 4 humano)
- [ ] Sprint plan aprovado pelo Sprint Validator (Gate 5)
- [ ] Sensores mecânicos verdes (lint + typecheck + CI)
- [ ] Worktrees preparados (1 por épico com tag [P])
```
### Passo 2 — Session Handoff (via `tlc-spec-driven`)
Gerar `bridge-handshake.md` — contrato que o builder lê ao iniciar cada sessão:
```markdown
# Bridge Handshake — {épico}
**Status:** Plan aprovado → Implement pode iniciar
**Spec:** `.specs/{epic-id}/spec.md` (SHA: {hash})
**Tasks:** `.specs/{epic-id}/tasks.md` (SHA: {hash})
**Progress:** `progress.md` (SHA: {hash})
## Próxima Task a Executar
**Task:** {id} — {título}
**Bloco Spec:** §{N} — "{âncora}"
**Cenário BDD:** Spec §11 — cenário {id}
**DoD:** {critério mecânico}
**Estimativa:** {N} SP
## Contexto da Sessão (<30% contexto)
Carregar apenas:
1. `CLAUDE.md` (Rules)
2. `.specs/{epic-id}/spec.md` §{seções relevantes para esta task}
3. `.specs/{epic-id}/tasks.md` (task atual + dependências)
4. `progress.md` (últimas 5 entradas)
```
### Passo 3 — Verificação de Sensores
```bash
# Sensores que devem estar verdes antes de Implement iniciar
npm run lint # ou equivalente
npm run typecheck
gh run list --limit 1 --status completed
```
Se qualquer sensor vermelho → bloquear Bridge e registrar como falha de Plan E6.
---
## Estados ADO
| Momento | Estado (Research E6) | Estado (Plan E6) |
|---|---|---|
| Bridge inicia | `In Validate` | `In Validate` |
| Checklist verde + artefatos gerados | `In Validate` → `Approved` | `In Validate` → `Approved` |
| Owner fecha | `Approved` → `Done` | `Approved` → `Done` |
---
## Regras Invioláveis
- **Bridge é contrato** — qualquer fase seguinte pode verificar mecanicamente se a bridge está aprovada
- **Sensores mecânicos** (Plan→Implement) — Bridge não fecha com sensor vermelho
- **SHA dos artefatos** — bridge-handshake.md deve ter SHA dos artefatos principais para detectar adulteração
- **Rebote máximo 1x** — se Plan E6 descobre BC errado, pode rebotar para Research (1 rebote por épico)
- **Épicos identificados** (Research→Plan) — mínimo 1, máximo 15 por PRD
---
id: divergent-ideation
name: Divergent Ideation
description: "Skill para ideação divergente e lean design na Etapa 3 da fase Research — gera personas, jornadas, storyboards e Feature Canvas (MoSCoW) usando obra/superpowers/brainstorming + TLC excalidraw-studio + the-fool. Atende o slot Research E3 (research-ideator) do framework AI-SDLC. Use quando o agente research-ideator precisa transformar o Problem Statement validado em direções de design concretas com critério adversarial embutido."
argument-hint: "ideate | personas | journey | canvas | fool"
metadata:
version: '1.0.0'
category: sdlc
dependencies: []
requires: {}
tags: [ideation, brainstorming, personas, user-journey, feature-canvas, moscow, excalidraw, e3, research-phase]
---
# Divergent Ideation — Research E3
## Objetivo
Transformar o Problem Statement validado (Etapa 2) em **múltiplas direções de design** com personas reais, jornadas detalhadas, storyboards e Feature Canvas priorizado — com postura adversarial embutida via `the-fool` para testar as ideias antes de prototipar.
Slot atendido: **Research E3 — research-ideator**
**Winner v3:** obra/superpowers `brainstorming` (121k★) + TLC: `excalidraw-studio` + `the-fool`
---
## Quando Usar Esta Skill
- Gate 2 (Research E2) aprovado, `problem-statement.md` disponível
- Orquestrador ativa a Etapa 3 da fase Research
- Work item Research em `Ready for Review` (estado `Design`)
---
## Passo 1 — Leitura de Inputs
| Arquivo | O que extrair |
|---|---|
| `.specs/research/problem-statement.md` | JTBDs, OST, MVP candidato |
| `.specs/research/discovery.md` | Bloco 2 (concorrentes) para diferenciação |
| `CLAUDE.md` / `AGENTS.md` | Constraints de stack e produto |
---
## Passo 2 — Personas (2-3 personas primárias)
Para cada persona identificada nos JTBDs:
```markdown
## Persona: {Nome}
| Campo | Descrição |
|---|---|
| **Perfil** | {cargo, empresa, contexto} |
| **JTBD principal** | {job statement desta persona} |
| **Frustrações atuais** | {dores com as soluções atuais} |
| **Comportamentos** | {como age hoje para resolver o problema} |
| **Critério de sucesso** | {o que precisa acontecer para considerar o produto bom} |
| **Citação representativa** | "{frase que esta persona diria}" |
```
---
## Passo 3 — Jornadas (User Journeys)
Para a persona principal, mapear a jornada completa:
```markdown
## Jornada: {Persona} × {JTBD principal}
| Etapa | Ação | Pensamento | Emoção | Oportunidade |
|---|---|---|---|---|
| Descoberta | {o que faz} | {o que pensa} | 😤/😊/😕 | {o que podemos melhorar} |
| Avaliação | ... | ... | ... | ... |
| Uso | ... | ... | ... | ... |
| Resultado | ... | ... | ... | ... |
```
---
## Passo 4 — Brainstorming Divergente (obra/superpowers)
Gerar **mínimo 3 direções de design** distintas para o MVP candidato:
```markdown
## Direção A: {título provocativo}
{descrição em 3-5 linhas da abordagem}
- Diferenciação: {o que torna único}
- Risco principal: {o que pode falhar}
## Direção B: {título provocativo}
...
## Direção C: {título provocativo}
...
```
---
## Passo 5 — Storyboards (via `excalidraw-studio`)
Para a direção mais promissora, gerar storyboard visual das telas/fluxos principais em Excalidraw ou Mermaid:
```mermaid
flowchart LR
A[Usuário abre app] --> B{Primeiro acesso?}
B -->|Sim| C[Onboarding]
B -->|Não| D[Dashboard]
C --> D
D --> E[Ação principal do JTBD]
```
---
## Passo 6 — Feature Canvas com MoSCoW (8-10 features)
Priorizar as features do MVP com critério MoSCoW:
```markdown
## Feature Canvas — {nome do MVP}
### Must Have (sem isso não é MVP)
- F1: {feature} — {justificativa baseada no JTBD}
- F2: {feature} — ...
### Should Have (importante mas não bloqueante)
- F3: {feature} — ...
### Could Have (desejável se houver tempo)
- F4: {feature} — ...
### Won't Have (explicitamente fora do MVP)
- F5: {feature} — {por que fica para depois}
```
Total de features Must Have + Should Have: **8-10 features** (limite do MVP candidato).
---
## Passo 7 — Revisão Adversarial (via `the-fool`)
Aplicar postura adversarial nas 3 direções de design:
Para cada direção, responder:
- "Por que isso vai falhar?" — identificar os 3 maiores riscos
- "Que usuário odiaria isso e por quê?"
- "Qual concorrente já faz isso melhor?"
- "Qual suposição estamos fazendo sem validar?"
Usar as respostas para refinar o Feature Canvas antes do Gate 3.
---
## Passo 8 — Gate 3 (HITL)
Apresentar ao PO + Designer + BA:
```
Gate 3 — Escolha de Direção de Design
Três direções foram geradas. Qual seguir para prototipação?
Direção A: {resumo de 1 linha}
Direção B: {resumo de 1 linha}
Direção C: {resumo de 1 linha}
[Escolher direção / Hibridizar A+B / Solicitar nova direção]
```
---
## Output
Gerar `.specs/research/personas.md`, `journeys.md`, `feature-canvas.md` com a direção aprovada.
---
## Estados ADO
| Momento | Estado |
|---|---|
| Etapa 3 inicia | `Ready for Review` → `Design` |
| Brainstorming e canvas em andamento | `Design` |
| Gate 3 aprovado | Mantém `Design` (Etapa 4 inicia) |
---
## Regras Invioláveis
- **Mínimo 3 direções** — uma única opção não é ideação divergente
- **Feature Canvas com escopo negativo** — "Won't Have" é obrigatório
- **The-fool antes do Gate 3** — direção sem revisão adversarial não está pronta para prototipar
- **8-10 features Must+Should** — MVP com >10 features é escopo inflado
---
id: jtbd-extract
name: JTBD Extract
description: "Skill para síntese de Jobs-to-be-Done e definição do Problem Statement a partir da pesquisa de mercado na Etapa 2 da fase Research. Usa pmprompt/jobs-to-be-done (framework Christensen) com exigência de DPA para dados de usuários. Atende o slot Research E2 (research-synthesizer) do framework AI-SDLC. Use quando o agente research-synthesizer precisa sintetizar discovery.md em JTBD, OST (Opportunity Solution Tree), problem statement e MVP candidato refinado."
argument-hint: "jtbd | ost | problem | mvp"
metadata:
version: '1.0.0'
category: sdlc
dependencies: []
requires: {}
tags: [jtbd, jobs-to-be-done, ost, problem-statement, mvp, e2, research-phase]
---
# JTBD Extract — Research E2
## Objetivo
Sintetizar os dados brutos da pesquisa de mercado (Etapa 1) em **Jobs-to-be-Done estruturados**, Opportunity Solution Tree e Problem Statement claro — os insumos que validam se o problema tem ROI suficiente para avançar.
Slot atendido: **Research E2 — research-synthesizer**
**Winner v3:** pmprompt/jobs-to-be-done (framework Christensen) + phuryn/pm-skills/summarize-interview
> **DPA obrigatório:** se entrevistas com usuários ou dados pessoais forem usados como input, exigir Data Processing Agreement antes de processar.
---
## Quando Usar Esta Skill
- Gate 1 (Research E1) aprovado, `discovery.md` disponível
- Orquestrador ativa a Etapa 2 da fase Research
- Work item Research em `Draft` → transitar para `Ready for Review`
---
## Passo 1 — Leitura de Inputs
| Arquivo | O que extrair |
|---|---|
| `.specs/research/discovery.md` | Blocos 1-5 da pesquisa |
| `entry/briefing.md` | Contexto original do problema |
| Entrevistas/feedbacks de usuários (se disponíveis) | Citações diretas — verificar DPA |
---
## Passo 2 — Extração de Jobs-to-be-Done
Usando o framework Christensen, mapear os JTBDs do público-alvo:
```markdown
## Jobs-to-be-Done
### JTBD Principal
**Job statement:** "Quando {situação}, quero {motivação}, para que {resultado esperado}"
**Dimensões:**
- Funcional: {o que o usuário quer fazer concretamente}
- Social: {como o usuário quer ser percebido}
- Emocional: {como o usuário quer se sentir}
**Evidências do discovery:** {referências ao Bloco 3 do discovery.md}
### JTBDs Secundários
[repetir estrutura para cada JTBD identificado — máx. 3-5]
```
---
## Passo 3 — Opportunity Solution Tree (OST)
Construir o OST mapeando: Objetivo de negócio → Oportunidades (JTBDs) → Soluções candidatas:
```markdown
## Opportunity Solution Tree
**Objetivo de negócio:** {métrica de sucesso mensurável}
**Oportunidade 1:** {JTBD principal não atendido}
└── Solução A: {ideia de solução}
└── Solução B: {ideia de solução alternativa}
**Oportunidade 2:** {JTBD secundário}
└── Solução C: {ideia de solução}
```
---
## Passo 4 — Problem Statement
Redigir o Problem Statement no formato canônico:
```markdown
## Problem Statement
**Para:** {público-alvo específico}
**Que:** {problema concreto que enfrentam}
**O produto:** {nome/descrição}
**É um:** {categoria de produto}
**Que:** {benefício principal / proposta de valor}
**Diferente de:** {alternativa atual que eles usam}
**Nossa solução:** {diferenciação específica}
**Critério de sucesso mensurável:** {como saberemos que resolvemos o problema}
```
---
## Passo 5 — MVP Candidato Refinado
Com base nos JTBDs e OST, refinar o MVP candidato do briefing:
```markdown
## MVP Candidato
**Escopo:** {o que o MVP inclui}
**Fora do escopo:** {o que explicitamente fica para depois}
**JTBD endereçados:** {quais JTBDs o MVP resolve}
**Hipótese principal:** {a hipótese que o MVP testa}
**Critério de validação:** {como validar a hipótese com usuários reais}
**Estimativa de esforço:** {ordem de grandeza: dias/semanas/meses}
```
---
## Passo 6 — Gate 2 (HITL)
Apresentar ao PO + Stakeholders:
```
Gate 2 — Validação do Problema e ROI
O JTBD principal está correto?
O Problem Statement captura o problema real?
O MVP candidato tem ROI suficiente para avançar?
[Aprovar para Etapa 3 / Solicitar revisão de {elemento}]
```
---
## Output
Gerar `.specs/research/problem-statement.md` com JTBDs + OST + Problem Statement + MVP candidato.
---
## Estados ADO
| Momento | Estado |
|---|---|
| Etapa 2 inicia | `Draft` → `Ready for Review` |
| Síntese em andamento | `Ready for Review` |
| Gate 2 aprovado | Mantém `Ready for Review` (Etapa 3 inicia) |
---
## Regras Invioláveis
- **DPA antes de dados de usuários** — nunca processar entrevistas ou PII sem DPA aprovado (gate §6 item 6)
- **JTBD com evidências** — todo JTBD precisa de evidência do `discovery.md`; JTBD sem evidência é hipótese, não dado
- **Problem Statement mensurável** — critério de sucesso vago ("melhorar experiência") é anti-padrão
- **MVP com escopo negativo** — "fora do escopo" é obrigatório no MVP candidato
---
id: market-research
name: Market Research
description: "Skill para pesquisa de mercado estruturada na Etapa 1 da fase Research — coleta insights de mercado, concorrentes, tendências e dados técnicos usando phuryn/pm-skills/market-research + TLC firecrawl-search/firecrawl-scrape (wrapper CC-BY-4.0 sobre Firecrawl AGPL). Atende o slot Research E1 (research-researcher) do framework AI-SDLC. Use quando o agente research-researcher precisa executar a descoberta automatizada de oportunidade. Modelo recomendado: Gemini 3.1 Pro (superior em pesquisa web)."
argument-hint: "research | competitors | trends | technical"
metadata:
version: '1.0.0'
category: sdlc
dependencies: []
requires: {}
tags: [market-research, research, discovery, firecrawl, jtbd, e1, research-phase]
---
# Market Research — Research E1
## Objetivo
Executar pesquisa de mercado profunda e estruturada para alimentar a fase Research com dados reais — concorrentes, tendências, benchmarks técnicos e oportunidades — antes de qualquer ideação ou definição de produto.
Slot atendido: **Research E1 — research-researcher**
**Winner v3:** phuryn/pm-skills `market-research` (900★) + TLC: `firecrawl-search` + `firecrawl-scrape` (wrapper CC-BY-4.0)
> **Modelo recomendado:** Gemini 3.1 Pro — superior em pesquisa web e síntese de múltiplas fontes.
> **Firecrawl:** usar apenas via wrapper TLC CC-BY-4.0. Firecrawl raw (AGPL) está bloqueado pelo gate §6 (risco de contaminação copyleft).
---
## Quando Usar Esta Skill
- Orquestrador da fase Research ativa a Etapa 1 após Setup do Harness (E0) aprovado
- Briefing inicial do produto disponível em `entry/briefing.md`
- Pesquisa de mercado ainda não foi realizada para este épico/feature
---
## Passo 1 — Leitura do Briefing
Ler `entry/briefing.md` para extrair:
- Problema que o produto/feature resolve
- Público-alvo e segmento de mercado
- Constraints conhecidas (tecnologia, prazo, budget)
- Perguntas específicas a responder com a pesquisa
---
## Passo 2 — Execução da Pesquisa (5 blocos obrigatórios)
Usando `firecrawl-search` (TLC wrapper) + `firecrawl-scrape` para fontes primárias:
### Bloco 1 — Análise de Mercado
- Tamanho do mercado e crescimento (TAM/SAM/SOM se disponível)
- Tendências relevantes (últimos 12-24 meses)
- Players principais e seus posicionamentos
- Jobs-to-be-done dominantes neste mercado
### Bloco 2 — Análise de Concorrentes (diretos e indiretos)
- Top 3-5 concorrentes com features comparadas
- Pontos fortes e fracos de cada um
- Gaps não atendidos pelo mercado atual
- Feedback de usuários em reviews públicos
### Bloco 3 — Validação do Problema
- Evidências de que o problema é real (fóruns, reviews, posts, estudos)
- Frequência e intensidade do problema relatado
- Soluções alternativas que os usuários usam hoje (workarounds)
### Bloco 4 — Contexto Técnico
- Stack constraints identificadas na pesquisa
- Integrações de terceiros relevantes (APIs, SDKs disponíveis)
- Padrões técnicos do setor
- Limitações técnicas conhecidas
### Bloco 5 — Oportunidade e Diferenciação
- O que nenhum concorrente faz bem
- Qual diferenciação é tecnicamente viável
- Qual seria o MVP mínimo para entrar no mercado
---
## Passo 3 — Output: `discovery.md`
Gerar `.specs/research/discovery.md` com estrutura canônica:
```markdown
# Discovery — {nome do produto/feature}
**Data:** YYYY-MM-DD
**Pesquisador:** research-researcher (Gemini 3.1 Pro)
**Fontes consultadas:** {N} fontes
## Bloco 1 — Análise de Mercado
{síntese dos dados de mercado}
## Bloco 2 — Análise de Concorrentes
| Concorrente | Posicionamento | Pontos Fortes | Gaps |
|---|---|---|---|
## Bloco 3 — Validação do Problema
{evidências do problema com referências}
## Bloco 4 — Contexto Técnico
{stack constraints, integrações disponíveis, padrões}
## Bloco 5 — Oportunidade e Diferenciação
{o que está em aberto + MVP candidato inicial}
## Fontes
{lista de URLs consultadas via firecrawl}
```
---
## Passo 4 — Gate 1 (HITL)
Apresentar `discovery.md` ao PM/PO para validação:
```
Gate 1 — Validação de Insights de Pesquisa
Os insights coletados são relevantes para o problema declarado no briefing?
Os concorrentes mapeados são os corretos?
O contexto técnico reflete a realidade do projeto?
[Aprovar / Solicitar aprofundamento em {bloco}]
```
Só avançar para Etapa 2 após aprovação do Gate 1.
---
## Estados ADO — WIT SDLC Research
| Momento | Estado |
|---|---|
| Etapa 1 inicia | `Todo` → `In Progress` |
| Pesquisa em andamento | `In Progress` |
| `discovery.md` pronto para Gate 1 | `In Progress` → `Draft` |
| Gate 1 aprovado | Mantém `Draft` (Etapa 2 inicia) |
---
## Regras Invioláveis
- **Firecrawl raw bloqueado** — usar apenas via wrapper TLC CC-BY-4.0 (gate §6)
- **5 blocos obrigatórios** — pesquisa sem os 5 blocos é incompleta para alimentar a Etapa 2
- **Fontes citadas** — toda afirmação factual precisa de URL fonte no `discovery.md`
- **Modelo: Gemini 3.1 Pro** — melhor para síntese de múltiplas fontes web
- **DPA prévio** — se a pesquisa envolve dados de usuários identificáveis, exigir DPA antes de processar
---
id: multi-llm-plan-validation
name: Multi-LLM Plan Validation
description: "Skill local para validação heterogênea do PRD e Design Doc usando Codex GPT e Gemini em paralelo como Validador-Juiz da Etapa 5C da fase Research. Substitui o custom syscoe-prd-dual-validator como skill local reutilizável. Atende o slot Research E5 (research-prd-validator) do framework AI-SDLC. Use quando o orquestrador aciona a auditoria do PRD e Design Doc em janela limpa, paralela aos Writers."
argument-hint: "validate | audit | report"
metadata:
version: '1.0.0'
category: sdlc
dependencies: []
requires: {}
tags: [validation, multi-llm, prd-audit, design-doc-audit, validador-juiz, e5c, research-phase]
---
# Multi-LLM Plan Validation — Research E5C
## Objetivo
Auditar o PRD e o Design Doc com **perspectiva heterogênea** — dois modelos de famílias diferentes (Codex GPT-5.5 + Gemini 3.1 Pro) em janela limpa separada dos Writers — detectando problemas que um único revisor da mesma família pode não ver.
Slot atendido: **Research E5 — research-prd-validator (Etapa 5C)**
**Winner v3:** `multi-llm-plan-validation` (skill local) — substitui o custom `syscoe-prd-dual-validator` (vira opcional apenas para BDD-DDD avançado)
> **Janela limpa obrigatória** — nunca herdar contexto dos Writers (5A PRD e 5B Design Doc). Ler apenas os artefatos finalizados + PRD/Design Doc drafts.
---
## Quando Usar Esta Skill
- PRD draft (5A) e Design Doc draft (5B) disponíveis simultaneamente
- Orquestrador ativa a Etapa 5C em paralelo à geração dos drafts
- Gate 4.5 (HITL micro) precisa ser preparado com relatório de auditoria
---
## Passo 1 — Leitura de Inputs (janela limpa)
| Arquivo | Propósito |
|---|---|
| `.specs/research/prd.md` (draft) | Alvo principal da auditoria |
| `.specs/research/design-doc.md` (draft) | Alvo secundário (consistência com PRD) |
| `.specs/research/discovery.md` | Referência de dados de mercado |
| `.specs/research/problem-statement.md` | Referência do problema validado |
---
## Passo 2 — Auditoria Paralela (Codex + Gemini)
Executar dois passes de auditoria com perspectivas diferentes:
### Revisor 1 — Codex GPT (foco: governança e completude)
Verificar:
- Todos os requisitos funcionais cobrem as features Must Have do canvas?
- Escopo negativo (§10) está explícito e abrangente?
- RNFs (§7) têm valores concretos (não genéricos)?
- User Stories têm critérios de aceite verificáveis?
- Há contradições internas no PRD?
### Revisor 2 — Gemini 3.1 Pro (foco: mercado e BDD-DDD)
Verificar:
- O PRD reflete os dados de mercado do `discovery.md`?
- Os cenários BDD seed (§15) são realistas e suficientes?
- A Ubiquitous Language (§14) é consistente com o Design Doc §11?
- Há termos divergentes entre PRD e Design Doc?
- O escopo do MVP é realista dado o contexto técnico do Design Doc?
---
## Passo 3 — Output: `prd-audit-report.md`
```markdown
# PRD Audit Report — {feature}
**Data:** YYYY-MM-DD
**Ciclo:** {1/2/3}
## Revisor 1 — Codex GPT (Governança e Completude)
### CRÍTICOs (bloqueiam aprovação)
1. **[CRÍTICO]** PRD §{N}: {problema} — {sugestão concreta de correção}
### MODERADOs (devem ser resolvidos, mas não bloqueiam)
1. **[MODERADO]** PRD §{N}: {problema} — {sugestão}
### SUGESTÕEs (melhorias opcionais)
1. **[SUGESTÃO]** PRD §{N}: {melhoria}
## Revisor 2 — Gemini 3.1 Pro (Mercado e BDD-DDD)
### CRÍTICOs
1. **[CRÍTICO]** Design Doc §{N}: inconsistência com PRD §{M} — {descrição}
### UL Diff Report (PRD §14 vs Design Doc §11)
| Termo PRD | Termo Design Doc | Status |
|---|---|---|
| `{termo}` | `{termo}` | ✅ Consistente / ❌ Divergência |
### MODERADOs e SUGESTÕEs
...
## Consenso (apontamentos em ambos os revisores)
{lista de problemas identificados pelos dois modelos — prioridade máxima}
## Recomendação
- CRÍTICOs: {N} → **Bloqueia aprovação**
- MODERADOs: {N} → Writer deve resolver no próximo ciclo
- SUGESTÕEs: {N} → Opcional
```
---
## Passo 4 — Gate 4.5 (HITL Micro)
Se há apontamentos CRÍTICOS ou MODERADOS de interpretação ambígua:
```
Gate 4.5 — Arbitragem de Apontamentos
O Validador-Juiz identificou {N} pontos para decisão:
1. [CRÍTICO] §{seção}: {ambiguidade} — Opção A vs Opção B
→ Sua decisão: ___
2. [MODERADO] §{seção}: {conflito}
→ Aceitar correção sugerida? [s/n]
[Aprovar resoluções / Solicitar nova rodada]
```
**Máximo 3 ciclos.** Após 3 ciclos com CRÍTICOs → escalar para HITL Final (Gate 5).
---
## Passo 5 — HITL Final (Gate 5)
Após convergência do loop:
```
Gate 5 — Aprovação Final do PRD e Design Doc
PRD e Design Doc passaram por {N} ciclos de revisão.
CRÍTICOs pendentes: {0}
MODERADOs pendentes: {N} (aceitos como dívida documentada)
PRD e Design Doc estão aprovados para Bridge to Plan?
[Aprovar / Rejeitar / Solicitar revisão em {seção}]
```
---
## Estados ADO
| Momento | Estado |
|---|---|
| Auditoria inicia | `Ready for Review` → `In Review` |
| Loop com Writers (ciclos) | `In Review` ↔ `Needs Revision` |
| HITL Final aprova | `In Review` → `In Validate` |
| Bridge to Plan aprovada | `In Validate` → `Approved` |
---
## Regras Invioláveis
- **Janela limpa** — nunca herdar contexto dos Writers
- **Dois revisores heterogêneos** — um único modelo auditando seu próprio output é circular evaluation
- **UL Diff Report obrigatório** — inconsistência entre PRD §14 e Design Doc §11 é CRÍTICO automático
- **CRÍTICOs bloqueiam Gate 5** — sem exceção; resolvê-los ou registrar como risco documentado
- **Máximo 3 ciclos** — se após 3 ciclos ainda há CRÍTICOs → escalar para HITL humano
---
id: prd-from-discovery
name: PRD from Discovery
description: "Skill para produção do PRD na Etapa 5A da fase Research, rodando em janela paralela ao Design Doc Writer. Usa gotalab/cc-sdd PRD harness (3k★) com sanitização de payload obrigatória. Atende o slot Research E5 (research-prd-writer) do framework AI-SDLC. Produz PRD com 14 seções canônicas (600-1000 linhas) incluindo User Stories com cenários BDD seed e glossário de Ubiquitous Language §14. Roda em loop com research-prd-validator (max 3 ciclos)."
argument-hint: "draft | iterate | finalize"
metadata:
version: '1.0.0'
category: sdlc
dependencies: []
requires: {}
tags: [prd, product-requirements, user-stories, bdd-seed, ubiquitous-language, e5a, research-phase]
---
# PRD from Discovery — Research E5A
## Objetivo
Produzir o **Product Requirements Document (PRD)** — artefato canônico de produto com User Stories, critérios de aceite BDD seed e Ubiquitous Language — em janela de contexto separada e paralela ao Design Doc Writer.
Slot atendido: **Research E5 — research-prd-writer (Etapa 5A)**
**Winner v3:** gotalab/cc-sdd PRD harness (3k★) + sanitização de payload obrigatória
> **Janela paralela ao Design Doc Writer:** ambos consomem os mesmos inputs das Etapas 1-4 independentemente, sem contaminar a prosa um do outro.
> **Sanitização de payload obrigatória** (gate §6 item 6) para skills que enviam dados a terceiros.
---
## Quando Usar Esta Skill
- Gate 4 (Research E4) aprovado, `prototype-feedback.md` disponível
- Orquestrador ativa a Etapa 5 da fase Research (5A e 5B em paralelo)
- Roda em loop com `research-prd-validator` (Validador-Juiz), max 3 ciclos
---
## Passo 1 — Leitura de Inputs (janela limpa)
| Arquivo | O que extrair |
|---|---|
| `.specs/research/discovery.md` | Contexto de mercado e dados técnicos |
| `.specs/research/problem-statement.md` | JTBDs, OST, Problem Statement |
| `.specs/research/personas.md` + `journeys.md` | Audiências e fluxos validados |
| `.specs/research/feature-canvas.md` | Features Must/Should/Could/Won't |
| `.specs/research/prototype-feedback.md` | Ajustes confirmados com usuários |
---
## Passo 2 — Estrutura Canônica do PRD (14 seções)
```markdown
# PRD — {nome do produto/feature}
## §1. Resumo Executivo
[Problema, solução, valor esperado, timeline — 1 página]
## §2. Contexto e Motivação
[Por que agora, evidências de mercado, urgência]
## §3. Objetivos e Métricas de Sucesso (OKRs/KPIs)
[Métricas mensuráveis com baseline atual e target]
## §4. Público-Alvo e Personas
[Personas com perfis e JTBDs — referenciar personas.md]
## §5. Jornadas do Usuário
[Fluxos principais — referenciar journeys.md]
## §6. Requisitos Funcionais (User Stories)
[US organizadas por épico com ACs e cenários BDD seed]
## §7. Requisitos Não-Funcionais
[Performance, disponibilidade, segurança, LGPD/compliance]
## §8. Integrações e Dependências
[Sistemas externos, APIs, serviços de terceiros]
## §9. Restrições e Premissas
[Tecnológicas, orçamentárias, regulatórias]
## §10. Escopo Negativo
[O que este MVP explicitamente NÃO inclui — obrigatório]
## §11. Critérios de Aceitação Gerais
[Condições para considerar o produto "pronto para lançar"]
## §12. Roadmap e Faseamento
[O que é MVP, o que é V2, o que é V3]
## §13. Riscos e Mitigações
[Top 5 riscos com probabilidade e plano de mitigação]
## §14. Glossário — Ubiquitous Language
[Termos de domínio com definições canônicas e tags]
## §15. Cenários BDD Seed (features Medium+)
[1-2 cenários WHEN/THEN/SHALL por User Story Medium+]
```
---
## Passo 3 — User Stories com BDD Seed (§6 e §15)
Para cada User Story, formato obrigatório:
```markdown
### US-{N}: {título}
**Como** {persona}, **quero** {ação}, **para que** {resultado}.
**Critérios de Aceite:**
- AC1: {critério verificável}
- AC2: {critério verificável}
**Cenários BDD Seed (features Medium+):**
```gherkin
# Seed — Happy Path
WHEN {ação principal do usuário}
THEN sistema SHALL {resultado esperado}
# Seed — Edge Case (se identificado no protótipo)
WHEN {condição de borda conhecida}
THEN sistema SHALL {comportamento esperado}
```
**Estimativa:** Quick / Medium / Large
**Épico:** {nome do épico}
```
---
## Passo 4 — Glossário de Ubiquitous Language (§14)
Construir vocabulário canônico do domínio:
```markdown
## §14. Glossário — Ubiquitous Language
| Termo | Definição | Tag |
|---|---|---|
| `{Termo}` | {definição no contexto do domínio} | [CONFIRMED by Owner] |
| `{Termo}` | {definição inferida} | [INFERRED, needs validation] |
```
- Todo termo que aparecerá em código, banco, APIs ou eventos de domínio deve estar aqui
- Tags obrigatórias: `[CONFIRMED by Owner/TL]` ou `[INFERRED, needs validation]`
- Inconsistência com Design Doc §11 = bloqueio pelo `research-prd-validator`
---
## Passo 5 — Loop com Validador-Juiz
O `research-prd-validator` (multi-llm-plan-validation ou Codex+Gemini) audita em janela limpa. Ao receber apontamentos:
1. Ler `prd-audit-report.md`
2. Identificar apontamentos CRÍTICO / MODERADO / SUGESTÃO
3. Resolver CRÍTICOs obrigatoriamente; MODERADOS conforme julgamento do PM
4. Atualizar PRD e informar ao orquestrador para novo ciclo
> **Máximo 3 ciclos.** Após 3 ciclos com CRÍTICOs pendentes → Gate 4.5 HITL micro para arbitragem.
---
## Output
- `.specs/research/prd.md` — PRD completo (600-1000 linhas)
---
## Estados ADO
| Momento | Estado |
|---|---|
| Etapa 5A inicia | `In Testing` → `Ready for Review` |
| Loop Writer↔Validator | `Ready for Review` ↔ `Needs Revision` |
| HITL Final aprova | `Ready for Review` → `In Validate` |
---
## Regras Invioláveis
- **§10 Escopo Negativo obrigatório** — PRD sem escopo negativo é rejeitado pelo Validador-Juiz
- **§14 Ubiquitous Language obrigatório** — mínimo 5 termos com tags; inconsistência com Design Doc = bloqueio
- **Cenários BDD seed para features Medium+** — US Medium+ sem seed é anti-padrão
- **Sanitização de payload** — se o cc-sdd PRD harness enviar dados para terceiros, sanitizar PII antes
- **Janela limpa** — não herdar contexto do Design Doc Writer (5B paralelo)
- **600-1000 linhas** — PRD muito curto indica cobertura insuficiente; muito longo indica escopo inflado
---
id: syscoe-design-doc-suite
name: SysCOE Design Doc Suite
description: "Skill composta SysManager para produção do Design Doc técnico na Etapa 5B da fase Research, rodando em janela de contexto separada e paralela ao PRD Writer. Atende o slot R-E5 design-doc-writer do framework AI-SDLC. Use quando o orquestrador da fase Research aciona a Etapa 5B para produzir o artefato técnico complementar ao PRD — arquitetura, APIs, modelo de dados, RNF operacionais e Domain Language técnica. Não usar para ADR (Plan E1) nem RFC (Plan E2). Composta de: TLC technical-design-doc-creator + mermaid-studio com wrapper SysManager (11 seções canônicas, Domain Language técnica §11, loop Validador-Juiz max 3 ciclos)."
argument-hint: "draft | iterate | finalize"
metadata:
version: '2.0.0'
category: sdlc
dependencies: []
requires: {}
tags: [design-doc, architecture, rfc, domain-language, research, e5b, validador-juiz, syscoe]
---
# SysCOE Design Doc Suite — Research E5B
## Objetivo
Produzir o **Design Doc** — artefato canônico técnico complementar ao PRD — na Etapa 5B da fase Research. PMs leem PRD com personas e jornadas; Tech Leads e SREs precisam de arquitetura, contratos de API, modelo de dados e RNF operacionais com exemplos concretos. Este skill entrega exatamente isso.
Slot atendido: **R-E5 design-doc-writer (Etapa 5B — Research)**
> **Regra de escopo:** esta skill NÃO cria ADRs (slot Plan E1 — `syscoe-tech-decider-7pillars`) nem RFCs (slot Plan E1/E2). O Design Doc é um artefato de Research; ADRs e RFCs são artefatos de Plan.
---
## Quando Usar Esta Skill
- Orquestrador da fase Research ativa a Etapa 5 (PRD + Design Doc em paralelo)
- Esta skill roda **em janela de contexto separada** do PRD Writer — mecanismo deliberado para evitar contaminação de prosa entre audiências
- O Design Doc **não é derivado do PRD** — ambos consomem os mesmos inputs das Etapas 1-4 independentemente
- Roda em loop com o `research-prd-validator` (Validador-Juiz), max 3 ciclos
Não usar para:
- Criar ADRs → slot Plan E1 (`syscoe-tech-decider-7pillars`)
- Criar RFCs → slot Plan E1/E2
- Criar diagramas Mermaid isolados → usar mermaid-studio diretamente
- Enriquecer spec de Plan → usar `syscoe-spec-enrich-adversarial`
---
## Passo 1 — Leitura de Inputs (janela limpa)
Ao iniciar, ler **somente** os artefatos das Etapas 1-4 da pasta `.specs/research/`:
| Arquivo | O que extrair |
|---|---|
| `discovery.md` | Bloco 4 (Parte Técnica): stack constraints, integrações 3rd party, APIs identificadas |
| `problem-statement.md` | Escopo do problema e MVP candidato |
| `personas.md` + `journeys.md` | Apenas contratos de UX que afetam APIs (não narrativa de produto) |
| `feature-canvas.md` | Features priorizadas (MoSCoW) que precisam virar componentes |
| Feedback do protótipo (Etapa 4) | Pistas de gargalo técnico identificadas em testes |
| `CLAUDE.md` / `AGENTS.md` (Rules do projeto) | Padrões de stack, logging, segurança já estabelecidos |
> **Não ler** o PRD draft em produção paralela — cada writer foca em sua audiência sem contaminação cruzada.
---
## Passo 2 — Estrutura Canônica do Design Doc (11 seções)
Produzir o Design Doc seguindo as 11 seções obrigatórias:
```markdown
# Design Doc — [Nome do Produto/Feature]
## 1. Resumo da Arquitetura
[Diagrama de blocos Mermaid + 3-5 linhas: estilo arquitetural, componentes principais]
## 2. Modelo de Dados / Schema
[Entidades, relacionamentos, índices críticos, constraints, migrations necessárias]
## 3. APIs Públicas
[Rotas, contratos request/response, autenticação, versionamento, exemplos concretos]
## 4. Integrações com Sistemas Existentes
[Sistemas legados, MCPs, filas, webhooks — protocolo + autenticação por integração]
## 5. MVP Técnico
[Versão mínima construível em N dias que entrega o valor do MVP candidato do PRD]
## 6. Requisitos Não-Funcionais Operacionais (com exemplos concretos)
[Performance, segurança, observabilidade, compliance — sempre com número ou biblioteca]
## 7. Tradeoffs e Alternativas Consideradas
[Decisões arquiteturais com justificativa: por que X e não Y]
## 8. Riscos Técnicos
[Lista priorizada com plano de mitigação por risco]
## 9. Estimativa de Esforço (ordem de grandeza)
[Por componente, em dias-pessoa — sem virar PBI, isso é papel do Plan]
## 10. Escopo Negativo Técnico
[O que este MVP explicitamente NÃO implementa — obrigatório]
## 11. Domain Language Técnica (features Medium+)
[Termos técnicos canônicos: Aggregates, Entities, Value Objects, Domain Events
que aparecerão no código de Implement. Cada termo com tag de origem.]
```
---
## Passo 3 — Regras por Seção
### Seção 6 — RNF Operacionais: sempre com exemplo concreto
RNF genérico é anti-padrão. Escrever **sempre** com número ou biblioteca:
| Anti-padrão | Correto |
|---|---|
| "Sistema deve ser seguro." | "Comunicação via HTTPS, TLS 1.3. Rate limit: 100 req/min por API key (HTTP 429 com `Retry-After`)." |
| "Sistema deve ser rápido." | "P95 latência < 300ms para endpoints de leitura sob carga de 500 req/s." |
| "Sistema deve logar." | "Logs estruturados JSON, OpenTelemetry, retenção 90 dias hot / 1 ano cold." |
### Seção 7 — Tradeoffs: toda decisão significativa documentada
Toda decisão arquitetural que persistirá além desta feature ou cria lock-in tecnológico deve ter justificativa. Formato:
```
**Decisão:** [o que foi decidido]
**Alternativas consideradas:** [opção B, opção C]
**Justificativa:** [por que A ganhou sobre B e C]
**Trade-off aceito:** [o que se abre mão ao escolher A]
```
Se Rules (`CLAUDE.md`/`AGENTS.md`) já cobre o padrão → referenciar e seguir, nunca reinventar.
### Seção 9 — Estimativa: ordem de grandeza, não PBI
Estimativa em dias-pessoa por componente (3 dias / 2 semanas / 1 mês). Transformar em PBIs é responsabilidade do Plan (Etapa 4 — `syscoe-task-decomposer-pro`).
### Seção 10 — Escopo Negativo Técnico: obrigatório
Sem esta seção, o agente de Implement preenche lacunas com treinamento genérico ("um sistema assim normalmente tem cache distribuído também..."). Sempre explicitar o que o MVP **não** implementa.
### Seção 11 — Domain Language Técnica (features Medium+)
Espelha o glossário UL do PRD §14, mas focado nos termos técnicos canônicos. Formato obrigatório:
```markdown
## 11. Domain Language Técnica
| Termo | Tipo DDD | Definição Técnica | Tag de Origem |
|---|---|---|---|
| `PaymentOrder` | Aggregate | Raiz de agregado para ordens de pagamento | [CONFIRMED by TL] |
| `PaymentMethod` | Value Object | Enum imutável: CREDIT/PIX/BOLETO | [INFERRED, needs validation] |
| `PaymentProcessed` | Domain Event | Emitido após cobrança confirmada no gateway | [CONFIRMED by Owner] |
```
- `[CONFIRMED by Owner/TL]` — validado com humano responsável
- `[INFERRED, needs validation]` — inferido dos artefatos; precisa confirmação
- Inconsistência entre §11 (Design Doc) e §14 (PRD) = bloqueio do `research-prd-validator`
---
## Passo 4 — Integração com PRD Writer e Validador-Juiz
### Relação com o PRD Writer (paralelo)
| Aspecto | PRD Writer | Design Doc Writer (esta skill) |
|---|---|---|
| Audiência | PM, PO, Stakeholders | Tech Lead, SRE, Arquiteto |
| Foco | Produto, personas, jornadas, User Stories | Arquitetura, APIs, modelo de dados, RNF |
| Referência cruzada | PRD referencia Design Doc em seções técnicas | Design Doc referencia features do PRD |
### Loop com Validador-Juiz (max 3 ciclos)
O `research-prd-validator` audita ambos os artefatos em janela limpa separada. Ao receber apontamentos:
1. Ler o relatório de auditoria (`prd-audit-report.md`)
2. Identificar apontamentos direcionados ao Design Doc (RNF ausentes, tradeoffs não justificados, escopo técnico inflado, inconsistências de Domain Language)
3. Revisar as seções apontadas
4. Informar ao orquestrador que o Design Doc foi atualizado para novo ciclo de auditoria
> **Máximo 3 ciclos.** Se após 3 ciclos ainda há apontamentos CRÍTICOS → escalar para HITL Final (Gate 5) para arbitragem humana.
---
## Passo 5 — Output e Estados ADO
### Saída
- `.specs/research/design-doc.md` — Design Doc completo (commitar após aprovação do HITL Final)
### Estados ADO — WIT SDLC Research
| Momento | Estado ADO | Quem transita |
|---|---|---|
| Etapa 5 inicia (artefatos E1-E4 prontos) | `Ready for Review` → `In Review` | Orquestrador |
| Apontamentos do Validator | `In Review` → `Needs Revision` | Orquestrador (após Gate 4.5 HITL) |
| Revisão entregue | `Needs Revision` → `In Review` | Orquestrador |
| HITL Final aprova | `In Review` → `In Validate` | Orquestrador |
| Bridge to Plan aprovada | `In Validate` → `Approved` | `research-bridge-planner` |
| Owner fecha | `Approved` → `Done` | Owner (manual) |
> **Anti-padrão:** nunca setar `Approved` ou `Done` diretamente — esses estados são conquistados pela Bridge to Plan + Owner (Constitution Art. 4).
---
## Regras Invioláveis
- **Janela limpa obrigatória** — nunca herdar contexto do PRD Writer ou de etapas anteriores da mesma sessão
- **Seção 10 (Escopo Negativo Técnico) é obrigatória** — sem ela, o artefato é rejeitado pelo Validador-Juiz
- **Seção 11 com tags** é obrigatória para features Medium+ — termo sem tag `[CONFIRMED]` ou `[INFERRED]` é bloqueio
- **RNF com exemplo concreto** — RNF genérico ("deve ser seguro") é anti-padrão rejeitado na auditoria
- **Estimativa ≠ PBI** — nunca decompor em tasks aqui; isso é papel do Plan
- **Nunca criar ADR ou RFC nesta skill** — pertencem ao Plan E1
- **Idioma** — gerar no idioma da solicitação; termos técnicos canônicos permanecem em inglês quando estabelecidos no glossário UL
---
id: ui-from-spec
name: UI from Spec
description: "Skill para prototipação rápida de UI na Etapa 4 da fase Research — gera mockups e protótipos navegáveis usando Figma Specs Plugin oficial + TLC frontend-blueprint para descoberta de componentes. Atende o slot Research E4 (research-prototyper) do framework AI-SDLC. Use quando o agente research-prototyper precisa materializar a direção de design aprovada em protótipo testável com usuários. Roda em worktree isolado para não contaminar a branch principal."
argument-hint: "prototype | mockup | figma | test"
metadata:
version: '1.0.0'
category: sdlc
dependencies: []
requires: {}
tags: [prototype, figma, ui, mockup, user-testing, frontend-blueprint, e4, research-phase]
---
# UI from Spec — Research E4
## Objetivo
Materializar a direção de design aprovada (Etapa 3) em **protótipo navegável testável com usuários reais** — não código de produção, mas interface suficientemente fiel para validar a hipótese do MVP antes de escrever uma linha de código.
Slot atendido: **Research E4 — research-prototyper**
**Winner v3:** Figma Specs Plugin oficial + TLC: `frontend-blueprint` (para discovery de componentes)
> **Roda em worktree isolado** — protótipos não devem contaminar a branch principal do projeto.
---
## Quando Usar Esta Skill
- Gate 3 (Research E3) aprovado, `feature-canvas.md` e `personas.md` disponíveis
- Orquestrador ativa a Etapa 4 da fase Research
- Work item Research em `Design` → transitar para `In Testing`
---
## Passo 1 — Leitura de Inputs
| Arquivo | O que extrair |
|---|---|
| `.specs/research/feature-canvas.md` | Features Must Have a prototipar |
| `.specs/research/personas.md` | Persona principal para guiar fluxo |
| `.specs/research/journeys.md` | Jornada aprovada no Gate 3 |
| `CLAUDE.md` | Design system existente (se houver) |
---
## Passo 2 — Discovery de Componentes (via `frontend-blueprint`)
Antes de criar mockups, descobrir componentes disponíveis:
1. Há design system existente no projeto? (Figma library, Shadcn, MUI, etc.)
2. Quais componentes reutilizáveis cobrem as features Must Have?
3. Quais precisam ser criados do zero?
Output: lista de componentes existentes vs. a criar.
---
## Passo 3 — Protótipo no Figma (via Figma Specs Plugin)
Criar prótótipo navegável no Figma cobrindo os fluxos principais das features Must Have:
**Telas obrigatórias:**
1. Tela de entrada / onboarding (primeiro acesso)
2. Fluxo principal do JTBD (happy path completo)
3. Tela de erro / estado vazio (ao menos 1)
4. Tela de sucesso / confirmação
**Fidelidade:** mid-fidelity (sem conteúdo final, mas com layout e interações navegáveis).
**Conectar frames** para criar protótipo clicável testável com usuários.
---
## Passo 4 — Script de Teste com Usuários
Gerar roteiro de teste para validação com 3-5 usuários da persona principal:
```markdown
## Script de Teste — {nome do MVP}
**Persona alvo:** {nome da persona}
**Objetivo:** validar se o protótipo resolve o JTBD "{job statement}"
**Duração:** 30-45 minutos por sessão
### Tarefas a completar (sem instrução direta)
1. "{tarefa que cobre fluxo principal}"
2. "{tarefa que cobre fluxo secundário}"
3. "{tarefa adversarial — o que acontece se errar?"
### Perguntas pós-teste
- O que foi confuso?
- Qual parte faria diferente?
- Usaria esse produto? Por quê sim/não?
### Critério de aprovação
- ≥ 3/5 usuários completam Tarefa 1 sem ajuda
- ≥ 4/5 usuários entendem a proposta de valor
```
---
## Passo 5 — Registro de Feedback do Protótipo
Após testes com usuários, registrar em `.specs/research/prototype-feedback.md`:
```markdown
## Feedback do Protótipo
**Usuários testados:** {N}
**Data:** YYYY-MM-DD
### Pontos positivos (recorrentes)
- {feedback recorrente positivo}
### Fricções identificadas
- {fricção 1}: {N}/{total} usuários reportaram
- {fricção 2}: {N}/{total} usuários reportaram
### Implicações para o Design Doc e PRD
- {ajuste necessário na feature X}
- {escopo negativo confirmado: feature Y não será necessária}
### MVP validado?
✅ Sim — critério de aprovação atingido. Avançar para Etapa 5.
❌ Não — {N} fricções críticas. Iterar no protótipo antes de avançar.
```
---
## Passo 6 — Gate 4 (HITL)
```
Gate 4 — Validação do Protótipo
O protótipo foi testado com {N} usuários da persona {nome}.
Resultado: {N}/{total} completaram a tarefa principal.
O MVP candidato está validado?
[Aprovar para Etapa 5 / Solicitar iteração no protótipo]
```
---
## Estados ADO
| Momento | Estado |
|---|---|
| Etapa 4 inicia | `Design` → `In Testing` |
| Protótipo sendo criado | `In Testing` |
| Testes com usuários em andamento | `In Testing` |
| Gate 4 aprovado | Mantém `In Testing` (Etapa 5 inicia) |
---
## Regras Invioláveis
- **Worktree isolado** — protótipos nunca na branch principal
- **Mid-fidelity mínimo** — wireframes de baixa fidelidade não são suficientes para teste real com usuários
- **Script de teste antes de testar** — nunca teste não estruturado
- **Feedback registrado antes do Gate 4** — Gate 4 não pode ser ativado sem `prototype-feedback.md`
- **Não é código de produção** — protótipo serve para validar, não para evoluir para produção
---
id: syscoe-board-ado-pro
name: SysCOE Board ADO Pro
description: "Skill composta SysManager para gestão mecânica do board Azure DevOps — atualização de estados, registro de métricas (tokens/custo/duração) e criação de work items hierárquicos. Atende o slot Transversal board-manager do framework AI-SDLC. Use quando o orquestrador de qualquer fase (Research/Plan/Implement) precisa transitar estados do WIT SDLC, registrar métricas de execução ou criar hierarquia Epic→Feature→WIT SDLC. Agente deliberadamente leve (Haiku) — executa apenas operações mecânicas, nunca decide autonomamente. Composta de: Microsoft azure-devops-mcp oficial com wrapper SysManager (process-target verification, 15-state flow, métricas por modelo)."
argument-hint: "transition | metrics | create | link | status"
metadata:
version: '2.0.0'
category: sdlc
dependencies: [harness-core]
requires: {}
tags: [ado, board, work-items, wit-sdlc, metrics, state-transition, gov-sys-manager, haiku, syscoe]
---
# SysCOE Board ADO Pro — Transversal
## Objetivo
Manter o Azure DevOps atualizado com estados corretos, métricas de execução e hierarquia de work items durante todas as fases do AI-SDLC. É um agente **mecânico e leve** — o trabalho intelectual fica com os agentes de fase (Opus/Sonnet); este executa as operações de board resultantes.
Slot atendido: **Transversal board-manager**
> **Model routing:** usar **Haiku 4.5** para todas as operações deste agente. Atualizar board é trabalho mecânico — Haiku custa ~20x menos que Opus e executa em segundos. Usar Opus/Sonnet aqui é desperdício de custo.
---
## Quando Usar Esta Skill
- Orquestrador de qualquer fase precisa transitar estado de um WIT SDLC
- Após veredito de agente revisor (emitido via comentário — nunca o próprio revisor transita)
- Ao final de etapa com sensores verdes (BUILD Gate → `Ready for Review`)
- Para registrar métricas de execução ao concluir etapas
- Para criar Epic → Feature → WIT SDLC a partir de PRD aprovado
Não usar para:
- Emitir vereditos de review → usar `syscoe-correctness-codex` ou `syscoe-acceptance-review-macro`
- Decidir qual estado é correto → receber instrução explícita do orquestrador
- Criar PBIs/Tasks → aguardar Gate 4 humano (`syscoe-task-decomposer-pro`)
---
## Passo 1 — Verificar Process Target (obrigatório antes de qualquer operação)
Dois processes ADO coexistem na org `sysmanagerdevops`:
| Process | Status | WITs Disponíveis |
|---|---|---|
| `gov-sys-manager` | ✅ **Ativo** — default em 35 projetos | WIT custom `SDLC` com 15 estados |
| `sys-ai-augmented` | 🔄 Em provisioning (Wave 7) | Herda SDLC + novos WITs `[PLANNED]` |
**Antes de qualquer transição:**
1. Identificar o process do projeto-alvo via `mcp__azure-devops__core_get_project` ou `az boards project list`
2. Se `gov-sys-manager` → usar catálogo completo dos 15 estados
3. Se `sys-ai-augmented` → usar apenas topologia herdada do SDLC (15 estados) + WITs Agile herdados. **Não tentar criar ou usar estados/WITs dos novos 5 tipos** (não provisionados)
---
## Passo 2 — Catálogo de Estados — WIT Custom SDLC (15 estados, 5 categorias)
### Fluxo Implement (UAT mandatório na Etapa 5)
```
Todo (Proposed)
→ In Progress (InProgress)
→ Ready for Review (InProgress)
→ In Review (InProgress)
→ In Testing (InProgress) ← gate obrigatório após Dual CR
→ In Validate (InProgress) ← pipeline DoD
→ Approved (Resolved) ← gate técnico DoD + Acceptance Review macro
→ Done (Completed) ← Owner fecha (manual)
```
### Fluxo Research
```
Todo (Proposed)
→ In Progress (InProgress)
→ Draft (Proposed)
→ Design (Proposed)
→ In Testing (InProgress) ← protótipo com usuários
→ Ready for Review (InProgress)
→ In Review (InProgress) ← loop Writer↔Validator
→ In Validate (InProgress) ← HITL Final aprovou
→ Approved (Resolved)
→ Done (Completed)
```
### Fluxo Plan
```
Todo (Proposed)
→ In Planning (InProgress)
→ Ready for Review (InProgress)
→ In Review (InProgress) ← loop Writer↔Validator
→ In Validate (InProgress)
→ Approved (Resolved)
→ Done (Completed)
```
### Loops e Desvios (qualquer estado)
| Transição | Uso |
|---|---|
| Qualquer → `Needs Revision` (InProgress) | Loop de correção (máx. 2-3 ciclos conforme gate) |
| Qualquer → `Blocked` (InProgress) | Dependência externa pendente |
| Qualquer → `Removed` (Removed) | Descartado |
| Qualquer → `Rejected` (Removed) | Rejeitado estruturalmente (após HITL confirmar) |
### Invariantes (Constitution Art. 4 + Fases/Implement.md)
- `Done` **sempre** passa por `In Review → In Validate → Approved` antes
- Em Implement, `In Testing` é gate mandatório entre `In Review` e `In Validate`
- Revisor da Etapa 4 (Dual CR) **NUNCA** seta `Done`, `Approved`, `In Validate` ou `In Testing` diretamente — emite veredito; este agente transita sob comando do orquestrador
- `Approved` é conquistado pela pipeline DoD + Acceptance Review macro (E6.A)
- `Done` é finalizado pelo Owner; pipeline DoD **nunca** seta `Done`
---
## Passo 3 — Operações Disponíveis
### 3.1 — Transitar Estado
Receber instrução do orquestrador: `{ work_item_id, from_state, to_state, comment }`.
Antes de executar:
1. Verificar estado atual via `wit_get_work_item` — confirmar que `from_state` é o estado real
2. Verificar que a transição é válida no catálogo acima
3. Executar `wit_update_work_item` com novo estado
4. Adicionar comentário de rastreabilidade via `wit_add_work_item_comment`
> **NUNCA** mudar estado sem instrução explícita do orquestrador. Se o estado atual divergir do esperado, reportar divergência ao orquestrador e aguardar decisão.
### 3.2 — Registrar Métricas
Ao transitar para `Done` ou `Approved`, registrar nos campos customizados:
| Campo ADO | Valor | Cálculo |
|---|---|---|
| `Custom.TokensUsed` | Total de tokens consumidos na fase | Somar tokens de todas as etapas |
| `Custom.EstAICost` | Custo estimado em USD | Usar tabela de custo por modelo abaixo |
| `Custom.Duration` | Duração em minutos | `completed_at - started_at` |
| `Custom.StartedAt` | ISO timestamp de início | Quando a fase entrou em `In Progress` |
| `Custom.CompletedAt` | ISO timestamp de conclusão | Momento atual |
**Tabela de custo por modelo (referência):**
| Modelo | Custo/token |
|---|---|
| Claude Opus 4.6/4.7 | $0.00004 |
| Claude Sonnet 4.6 | $0.000008 |
| Claude Haiku 4.5 | $0.000003 |
| Gemini 3.1 Pro | $0.000003 |
### 3.3 — Criar Hierarquia de Work Items
A partir de PRD aprovado, criar a hierarquia:
```
Epic (uma por iniciativa do PRD)
└── Feature (uma por épico do parallelism-map da Research)
└── WIT SDLC Research — [nome do épico] (estado inicial: Todo)
└── WIT SDLC Plan — [nome do épico] (criado quando Research → Done)
└── WIT SDLC Implement — [nome do épico] (criado quando Plan → Done)
```
> PBIs e Tasks são criados pelo `syscoe-task-decomposer-pro` somente após Gate 4 humano aprovar — **não criar aqui**.
Usar `wit_add_child_work_items` para vincular parent-child automaticamente.
### 3.4 — Linkar PR → WIT
Quando PR é aberto na branch de uma feature:
1. Extrair epic-id / feature-id da convenção de branch (ex: `feature/EPIC-42-payment`)
2. Buscar WIT SDLC Implement correspondente
3. Criar link `Pull Request` via `wit_link_work_item_to_pull_request`
4. Adicionar comentário: "PR #{pr_id} vinculado — {título do PR}"
### 3.5 — Consultar Status (modo `status`)
Gerar snapshot rápido de um work item ou iteração:
```markdown
## Status do WIT #{id}
| Campo | Valor |
|---|---|
| Título | {título} |
| Estado | {estado atual} |
| Fase | Research / Plan / Implement |
| Iteração | {sprint} |
| Última atualização | {data} |
| Métricas | Tokens: {N} · Custo: ${N} · Duração: {N}min |
```
---
## Passo 4 — Regras Invioláveis
- **NUNCA** mudar estado sem instrução explícita do orquestrador
- **SEMPRE** registrar métricas ao transitar para `Done` ou `Approved`
- **SEMPRE** verificar process target (gov-sys-manager vs sys-ai-augmented) antes de qualquer transição
- **NUNCA** criar PBIs/Tasks — isso é responsabilidade do `syscoe-task-decomposer-pro` após Gate 4
- **NUNCA** setar `Done` por conta própria — sempre responsabilidade do Owner
- **Se transição falhar** → reportar erro ao orquestrador; não tentar corrigir sozinho
- **Modelo: Haiku 4.5** — este é um agente mecânico; usar Opus/Sonnet é anti-padrão de custo
- **Idioma** — campos de texto em pt-BR; nomes de estado e tipo em inglês (padrão ADO)
---
id: syscoe-setup-harness
name: SysCOE Setup Harness
description: "Skill custom SysManager para bootstrap completo do harness AI-SDLC em um novo projeto ou nova feature — cria estrutura _sys/core/, gera config.yaml, CLAUDE.md/AGENTS.md, configura MCPs, instala skills locais e prepara o ADO board. Atende o slot Transversal E0 (harness-bot) do framework AI-SDLC. Use quando um projeto ainda não tem o harness configurado ou quando uma nova feature precisa de scaffold isolado. Composta de: TLC skill-architect + subagent-creator + local harness-research init."
argument-hint: "new-project | new-feature | new-env | migrate | check"
metadata:
version: '1.0.0'
category: sdlc
dependencies: [harness-core, harness-research]
requires: {}
tags: [setup, harness, bootstrap, scaffold, config-yaml, claude-md, mcp, e0, syscoe]
---
# SysCOE Setup Harness — Transversal E0
## Objetivo
Preparar toda a infraestrutura do harness AI-SDLC antes que qualquer fase (Research/Plan/Implement) possa iniciar. É a **Etapa 0** do framework — não iterativa, sem Gate próprio, mas pré-requisito de plataforma sem o qual as 6 etapas das fases produzem output instável.
Slot atendido: **Transversal E0 — harness-bot**
> **Regra:** se o checklist desta skill não está 100% verde, as fases não iniciam. Pular o Setup é a causa #1 de alucinação em projetos AI-SDLC.
---
## Quando Usar Esta Skill
- Novo projeto sendo iniciado no framework AI-SDLC
- Nova feature em projeto existente que precisa de scaffold isolado
- Migração de projeto legado (sem `_sys/core/`) para a estrutura canônica
- Verificação de saúde do harness de um projeto existente
---
## Passo 1 — Identificar Modo
| Argumento | Ação |
|---|---|
| `new-project` | Bootstrap completo: `_sys/core/` + config.yaml + Rules + MCPs + ADO board |
| `new-feature` | Scaffold de feature: worktree + sub-collection wiki + WIT SDLC |
| `new-env` | Configurar novo ambiente (staging, sandbox) em projeto existente |
| `migrate` | Migrar projeto legado (pre-`_sys/core/`) para estrutura canônica |
| `check` | Verificar saúde do harness existente sem criar nada |
---
## Passo 2 — Checklist de Pré-Requisitos de Plataforma
Verificar e instalar o que estiver faltando:
```markdown
## Checklist E0 — Setup do Harness
### Tools & CLIs
- [ ] `claude-code` instalado e autenticado
- [ ] `az` CLI instalado (`az --version`)
- [ ] `gh` CLI instalado e autenticado (`gh auth status`)
- [ ] `mmdc` (Mermaid CLI) instalado (`mmdc --version`)
- [ ] Node.js ≥ 20 + npm instalados
### MCPs Configurados (`.mcp.json` ou `~/.claude/settings.json`)
- [ ] Azure DevOps MCP (`azure-devops-mcp` Microsoft oficial)
- [ ] Outline wiki MCP (`outline`)
- [ ] Context7 MCP (`context7`)
- [ ] Figma MCP (se projeto tem UI)
- [ ] Langfuse MCP (se projeto tem features de IA)
### Arquivos Imperativos no Repo
- [ ] `CLAUDE.md` (Rules do projeto para Claude Code)
- [ ] `AGENTS.md` (catálogo de agentes disponíveis)
- [ ] `.gitignore` inclui `_sys/core/.lock` e `.env`
### ADO Board
- [ ] Process `gov-sys-manager` ativo no projeto ADO
- [ ] Campos customizados provisionados (TokensUsed, EstAICost, Duration, StartedAt, CompletedAt)
- [ ] Epic criado para o projeto/feature
```
---
## Passo 3 — Gerar `_sys/core/config.yaml`
Criar a **fonte da verdade** do projeto:
```yaml
# _sys/core/config.yaml
project:
id: "{slug-do-projeto}"
name: "{nome completo}"
ado_org: "https://dev.azure.com/sysmanagerdevops"
ado_project: "{nome-projeto-ADO}"
ado_epic_id: {id}
outline_collection_id: "{id}"
target:
llm: "claude" # claude | codex | gemini | copilot
model: "sonnet" # opus | sonnet | haiku
phase:
current: "none" # none | research | plan | implement
step: 0
status: "setup" # setup | in-progress | validating | done | blocked
history: []
skills:
installed: [] # preenchido após instalação
agents:
research: []
plan: []
implement: []
```
---
## Passo 4 — Gerar `CLAUDE.md` (Rules)
Criar o arquivo de Rules com o template SysManager:
```markdown
# CLAUDE.md — Rules do Projeto {nome}
## Contexto
{descrição do projeto, stack, objetivos}
## Stack
- Backend: {linguagem + framework}
- Frontend: {framework ou N/A}
- Banco: {engine}
- Infra: {cloud/plataforma}
## Padrões Estabelecidos
- Logging: {biblioteca + formato}
- Testes: {framework + cobertura mínima}
- Linting: {ferramenta + config}
- Commits: Conventional Commits obrigatório
## Constraints
- ADO-only: sem GitHub, sem Jira, sem Confluence
- LLM target: Claude Code (Sonnet para builder, Opus para revisores)
## Skills Instaladas
Ver `_sys/core/config.yaml → skills.installed`
## Agentes Disponíveis
Ver `_sys/core/agents/` e `AGENTS.md`
```
---
## Passo 5 — Instalar Skills Locais
Instalar as skills obrigatórias via `@sysmanager/sys-skills`:
```bash
# Skills transversais (sempre)
npx @sysmanager/sys-skills install --skill harness-core --target claude
npx @sysmanager/sys-skills install --skill harness-research --target claude
npx @sysmanager/sys-skills install --skill harness-plan --target claude
npx @sysmanager/sys-skills install --skill harness-implement --target claude
npx @sysmanager/sys-skills install --skill ado-workflow --target claude
npx @sysmanager/sys-skills install --skill git-cli --target claude
npx @sysmanager/sys-skills install --skill outline-wiki-manager --target claude
# Skills de fase (conforme roadmap do projeto)
npx @sysmanager/sys-skills install --skill market-research --target claude
npx @sysmanager/sys-skills install --skill prd-from-discovery --target claude
npx @sysmanager/sys-skills install --skill spec-from-prd --target claude
npx @sysmanager/sys-skills install --skill syscoe-task-decomposer-pro --target claude
npx @sysmanager/sys-skills install --skill syscoe-correctness-codex --target claude
npx @sysmanager/sys-skills install --skill syscoe-acceptance-review-macro --target claude
npx @sysmanager/sys-skills install --skill syscoe-deploy-multi-target --target claude
```
Atualizar `_sys/core/config.yaml → skills.installed` com cada skill instalada.
---
## Passo 6 — Preparar ADO Board
1. Verificar que Epic existe → se não, criar via `syscoe-board-ado-pro`
2. Criar WIT SDLC Research com estado `Todo` (será criado automaticamente quando Research iniciar)
3. Configurar iterações (sprints) no projeto ADO
---
## Passo 7 — Preparar Sub-collection Outline
1. Verificar que a coleção do projeto existe no Outline
2. Criar sub-collection de Research (E0-E6) via `outline-wiki-manager`
3. Registrar IDs no `_sys/core/.outline-sync.json`
---
## Passo 8 — Verificação Final (modo `check`)
```markdown
## Health Check do Harness
| Item | Status |
|---|---|
| `_sys/core/config.yaml` existe e é válido | ✅ / ❌ |
| `CLAUDE.md` com stack e constraints | ✅ / ❌ |
| `AGENTS.md` com agentes cadastrados | ✅ / ❌ |
| MCPs configurados e respondendo | ✅ / ❌ |
| Skills obrigatórias instaladas | ✅ / ❌ |
| ADO Epic e WITs SDLC criados | ✅ / ❌ |
| Outline sub-collection preparada | ✅ / ❌ |
**Status geral:** ✅ Pronto para Research / ❌ {N} itens pendentes
```
---
## Regras Invioláveis
- **Checklist 100% verde antes de iniciar Research** — sem exceções
- **`config.yaml` é a fonte da verdade** — nunca duplicar metadados do projeto em outros arquivos
- **Lock de `config.yaml`** — adquirir `_sys/core/.lock` antes de escrever (ver `harness-core`)
- **MCPs antes das skills** — configurar MCPs primeiro; skills dependem deles para operar
- **Idioma** — `config.yaml` em inglês; `CLAUDE.md` no idioma do projeto (pt-BR por padrão SysManager)
+18
-4

@@ -16,6 +16,20 @@ import fs from "fs-extra";

const stat = await fs.stat(full);
if (stat.isDirectory()) {
const skillFile = path.join(full, "SKILL.md");
if (await fs.pathExists(skillFile)) {
results.push(skillFile);
if (!stat.isDirectory())
continue;
// Flat: skills/<id>/SKILL.md
const skillFile = path.join(full, "SKILL.md");
if (await fs.pathExists(skillFile)) {
results.push(skillFile);
continue;
}
// Nested: skills/<phase>/<id>/SKILL.md
const subEntries = await fs.readdir(full);
for (const subEntry of subEntries) {
const subFull = path.join(full, subEntry);
const subStat = await fs.stat(subFull);
if (subStat.isDirectory()) {
const nestedSkillFile = path.join(subFull, "SKILL.md");
if (await fs.pathExists(nestedSkillFile)) {
results.push(nestedSkillFile);
}
}

@@ -22,0 +36,0 @@ }

+1
-1
{
"name": "@sysmanager/sys-skills",
"version": "1.0.12",
"version": "1.0.13",
"description": "Agent Skills Framework - Easy setup for AI agent capabilities and integrations (Claude, Gemini, Codex, GitHub Copilot)",

@@ -5,0 +5,0 @@ "type": "module",

---
id: create-adr
name: ADR Creator
description: Creates Architecture Decision Records (ADRs) to document significant architectural choices and their rationale for future team members. Use when the user says "write an ADR", "document this decision", "record why we chose X", "add an architecture decision record", "create an ADR for", or wants to capture the reasoning behind a technical choice so the team understands it later. Do NOT use when the decision hasn't been made yet (use create-rfc instead), for implementation planning (use technical-design-doc-creator), or for general documentation.
metadata:
version: '1.0.0'
category: documentation
dependencies: []
requires: {}
tags: [adr, architecture, decision-record, documentation]
---
# ADR Creator
You are an expert in creating Architecture Decision Records (ADRs) — concise, durable documents that capture the context, decision, and consequences of significant architectural choices so future team members understand *why* things are the way they are.
## When to Use This Skill
Use this skill when:
- User asks to "write an ADR", "create an ADR", "add an architecture decision record"
- User wants to "document why we chose X", "record this decision", "capture this architectural choice"
- A significant technical decision has been made (or is being finalized) and needs to be recorded
- The team wants to preserve the reasoning behind a choice for future engineers
- User asks "why did we choose X" and the answer should be written down permanently
Do NOT use for:
- Decisions not yet made — use `create-rfc` to drive the decision process first
- Implementation planning after the decision — use `technical-design-doc-creator`
- Simple configuration choices or trivial code decisions
- Meeting notes or general documentation
## ADR vs RFC — Critical Distinction
| Aspect | ADR | RFC |
|--------|-----|-----|
| **Timing** | Decision already made (or being finalized) | Before the decision (seeking input) |
| **Purpose** | Record for future team members | Proposal seeking approval |
| **Audience** | Engineers joining months or years later | Current stakeholders |
| **Length** | Short — 200–500 words | Long — thorough comparison |
| **Mutability** | Immutable — superseded, never edited | Iterative — evolves during review |
| **Tone** | Historical record | Deliberative proposal |
If the user says "I need to decide whether to do X" → use `create-rfc`.
If the user says "We decided to do X, let me document it" → use this skill.
## Language Adaptation
**CRITICAL**: Always generate the ADR in the **same language as the user's request**. Detect the language automatically.
- Keep technical terms in English when appropriate (e.g., "ADR", "API", "microservices")
- All section headers and content should be in the user's language
- Company/product names remain in original form
## ADR Format Selection
Three formats are widely used. Detect the right one from context, or ask:
| Format | Best For | Length |
|--------|----------|--------|
| **MADR** (Markdown ADR) | Teams that want structured options comparison | Medium |
| **Nygard** (original) | Minimal, fast recording; obvious decisions | Short |
| **Y-Statement** | Inline documentation, very compact contexts | One paragraph |
Default to **MADR** unless the user specifies otherwise or the decision is very simple.
---
## Interactive Workflow
### Step 1: Gather Context (if not provided)
If the user provides minimal context, use **AskQuestion** to collect essential information:
```json
{
"title": "ADR Information",
"questions": [
{
"id": "adr_decision",
"prompt": "What was the decision made? (e.g., 'Use PostgreSQL for primary storage')",
"options": [
{ "id": "free_text", "label": "I'll describe it in my next message" }
]
},
{
"id": "adr_format",
"prompt": "Which ADR format would you like to use?",
"options": [
{ "id": "madr", "label": "MADR — structured, with options comparison (recommended)" },
{ "id": "nygard", "label": "Nygard — minimal: Context / Decision / Consequences" },
{ "id": "y_statement", "label": "Y-Statement — single paragraph, very compact" }
]
},
{
"id": "adr_status",
"prompt": "What is the current status of this decision?",
"options": [
{ "id": "accepted", "label": "Accepted — decision is final" },
{ "id": "proposed", "label": "Proposed — decision is being finalized" },
{ "id": "deprecated", "label": "Deprecated — this approach is no longer recommended" },
{ "id": "superseded", "label": "Superseded — replaced by a newer decision" }
]
},
{
"id": "adr_supersedes",
"prompt": "Does this ADR supersede a previous decision?",
"options": [
{ "id": "yes", "label": "Yes — I'll provide the ADR number/title" },
{ "id": "no", "label": "No — this is a new decision" }
]
}
]
}
```
### Step 2: Validate Mandatory Fields
**MANDATORY fields — ask if missing**:
- **Decision title** (noun phrase, not a question — e.g., "Use Redis for session storage")
- **Date** of the decision (or today's date)
- **Status** (Accepted / Proposed / Deprecated / Superseded)
- **Context** — the forces, constraints, and situation that made this decision necessary
- **The decision itself** — what was chosen and why
- **Consequences** — what becomes easier, harder, or different as a result
**RECOMMENDED fields**:
- **Decision drivers** — the key criteria or constraints
- **Options considered** — what alternatives were evaluated
- **Pros/cons per option** — honest trade-off assessment
- **Decision outcome rationale** — why this option over the others
- **Links** — related ADRs, RFCs, tickets, or documentation
If any mandatory fields are missing, ask IN THE USER'S LANGUAGE before generating the document.
### Step 3: Assign ADR Number
Scan the existing ADR directory for the next sequential number:
1. Check if an ADR directory exists (`docs/adr/`, `docs/decisions/`, `.adr/`, or `adr/`)
2. Find the highest existing number
3. Assign the next number (e.g., if ADR-007 exists, this becomes ADR-008)
4. If no directory exists, start at ADR-001 and suggest creating the directory
### Step 4: Generate the ADR
Generate the ADR following the format selected in Step 1.
### Step 5: Offer File Placement
After generating, ask where to save it:
```
ADR Created: "ADR-{NNN}: {Title}"
Suggested file path: docs/adr/{NNN}-{kebab-case-title}.md
Would you like me to:
1. Save it to docs/adr/ (recommended convention)
2. Save it to a different location
3. Just show the content (I'll place it manually)
```
---
## Document Templates
### MADR Format (Default)
```markdown
# ADR-{NNN}: {Title}
- **Date**: YYYY-MM-DD
- **Status**: Accepted | Proposed | Deprecated | Superseded by [ADR-NNN]({link})
- **Deciders**: {who was involved in the decision}
- **Tags**: {optional: architecture, security, performance, database, etc.}
## Context and Problem Statement
{Describe the context and the problem or question that led to this decision.
2–4 sentences. What situation forced this choice?}
## Decision Drivers
- {Driver 1 — e.g., "Must support 10k concurrent users"}
- {Driver 2 — e.g., "Team has no Go experience"}
- {Driver 3 — e.g., "Must be deployable on-premise"}
## Considered Options
- {Option A}
- {Option B}
- {Option C — "Do nothing / status quo" when relevant}
## Decision Outcome
Chosen option: **"{Option A}"**, because {concise rationale tied to decision drivers}.
### Positive Consequences
- {Benefit 1}
- {Benefit 2}
### Negative Consequences
- {Trade-off 1 — be honest}
- {Trade-off 2}
## Pros and Cons of the Options
### {Option A} ✅ Chosen
- ✅ {Pro 1}
- ✅ {Pro 2}
- ❌ {Con 1}
### {Option B}
- ✅ {Pro 1}
- ❌ {Con 1}
- ❌ {Con 2}
### {Option C}
- ✅ {Pro 1}
- ❌ {Con 1}
## Links
- {Related ADR, RFC, ticket, or documentation}
- Supersedes: [ADR-{NNN}: {Title}]({link}) (if applicable)
- Superseded by: [ADR-{NNN}: {Title}]({link}) (if applicable)
```
---
### Nygard Format (Minimal)
```markdown
# ADR-{NNN}: {Title}
## Status
Accepted | Proposed | Deprecated | Superseded by ADR-{NNN}
## Context
{What is the situation that led to this decision?
What forces are at play — technical, business, organizational?
What constraints exist? 2–5 sentences.}
## Decision
{What did we decide to do?
State it directly, in active voice: "We will use X" or "We decided to adopt Y."
Include a brief rationale — why this option over the alternatives.}
## Consequences
{What becomes easier or better as a result?}
{What becomes harder or worse? Be honest about trade-offs.}
{What new concerns or constraints does this introduce?}
```
---
### Y-Statement Format (Compact)
```markdown
# ADR-{NNN}: {Title}
**Date**: YYYY-MM-DD | **Status**: Accepted
In the context of **{situation/use case}**,
facing **{concern or constraint}**,
we decided **{the option chosen}**,
to achieve **{quality attribute or goal}**,
accepting **{the downside or trade-off}**.
**Deciders**: {names or roles}
**Links**: {related ADRs, tickets}
```
---
## ADR Quality Checklist
Before finalizing, verify:
- [ ] **Title** is a noun phrase describing the decision (not a question, not a vague label)
- [ ] **Date** is included (decisions without dates lose context quickly)
- [ ] **Status** is set correctly — Accepted, Proposed, Deprecated, or Superseded
- [ ] **Context** explains the *forces* that made this decision necessary, not just what was done
- [ ] **Decision** is stated directly and tied to the context
- [ ] **Consequences** include honest trade-offs — not just positives
- [ ] **Options** (MADR format) include at least 2 alternatives actually considered
- [ ] **Supersedes / superseded by** links are included when applicable
- [ ] **File** follows naming convention: `NNN-kebab-case-title.md`
- [ ] **Number** is sequential in the ADR directory
---
## ADR File Naming Convention
```
docs/adr/
├── 001-use-postgresql-for-primary-storage.md
├── 002-adopt-event-driven-architecture.md
├── 003-replace-jenkins-with-github-actions.md ← supersedes ADR-001 if relevant
└── README.md ← optional index
```
- Zero-padded numbers: `001`, `002`, ... `099`, `100`
- Kebab-case title
- `.md` extension
- Common directories: `docs/adr/`, `docs/decisions/`, `adr/`, `.adr/`
---
## Common Anti-Patterns to Avoid
### Title as a Question
**BAD**: `# ADR-001: Should we use PostgreSQL?`
**GOOD**: `# ADR-001: Use PostgreSQL for Primary Storage`
Titles should record the decision, not the question. Future readers need to know *what was decided*, not what was considered.
---
### Vague Context
**BAD**:
```
We needed a database and chose PostgreSQL.
```
**GOOD**:
```
Our application requires a relational database with strong ACID guarantees.
The team has deep PostgreSQL experience. MySQL was evaluated but lacks
native support for JSONB columns, which our schema design requires.
Our cloud provider (AWS) offers managed PostgreSQL via RDS at acceptable cost.
```
Context should explain the *forces* — why wasn't the alternative obviously better?
---
### Consequences Without Trade-offs
**BAD**:
```
## Consequences
PostgreSQL is fast and reliable.
```
**GOOD**:
```
## Consequences
- Enables JSONB columns and advanced indexing for our query patterns
- Team expertise means fast onboarding and fewer operational surprises
- Adds operational burden compared to a managed NoSQL service
- Schema migrations require careful planning in a relational model
```
Honest trade-offs are what make ADRs valuable years later.
---
### Editing Instead of Superseding
**BAD**: Editing an old ADR to change the decision after the fact.
**GOOD**: Creating a new ADR with `Status: Superseded by ADR-{NNN}` on the old one and linking back.
ADRs are historical records. The old decision was correct *given what was known at the time*. Superseding preserves that context.
---
### Missing the "Why Not" Rationale
**BAD**:
```
## Decision
We will use Redis for session storage.
```
**GOOD**:
```
## Decision
We will use Redis for session storage. We considered storing sessions in PostgreSQL
(already in our stack) but Redis's built-in TTL support and in-memory performance
make it significantly better suited for high-frequency session reads. The operational
cost of an additional service is justified by the simplified session expiry logic.
```
The rationale is *why this option and not the others* — not just what was chosen.
---
## Important Notes
- **ADRs are immutable** — never edit the decision. Supersede with a new ADR.
- **Short is better** — 200–500 words is ideal. If it needs to be longer, move detail to a linked TDD or RFC.
- **Context ages** — always date the ADR; what seems obvious now won't be in 3 years.
- **Honest consequences** — a one-sided ADR loses credibility. Future engineers will hit the downsides regardless.
- **Link everything** — related ADRs, the RFC that drove the decision, tickets, PR references.
- **Language adaptation** — always write in the user's language.
- **Number sequentially** — check the directory before assigning a number.
## Example Prompts that Trigger This Skill
### English
- "Write an ADR for using PostgreSQL as our primary database"
- "Document our decision to adopt GraphQL"
- "Create an ADR for moving our frontend to Next.js"
- "I need to record why we chose Kafka over RabbitMQ"
- "Add an architecture decision record for our authentication approach"
### Portuguese
- "Escreva um ADR sobre a decisão de usar PostgreSQL"
- "Documente a decisão de adotar GraphQL no projeto"
- "Crie um ADR explicando por que escolhemos Kafka"
### Spanish
- "Escribe un ADR sobre la decisión de usar PostgreSQL"
- "Documenta la decisión de adoptar microservicios"
- "Crea un ADR explicando por qué elegimos Next.js"
---
id: create-prd
name: PRD Creator
description: |
Generates a detailed Product Requirements Document (PRD) in Markdown from an initial user prompt, using a clarifying-questions workflow suitable for a junior developer to implement.
**Use this skill when:**
- The user says "write a PRD", "create a PRD", "draft a PRD for feature X"
- The user says "escreva um PRD", "crie um PRD", "documento de requisitos do produto"
- A new feature needs scope, user stories, functional requirements, and success metrics captured *before* implementation
- The user wants a product-requirements artifact as input for task decomposition
**After the PRD is generated, the natural follow-up is `generate-tasks`**, which decomposes the PRD into actionable work items.
**Do NOT use for:**
- Architectural decisions already made — use `create-adr`
- Change proposals seeking stakeholder alignment — use `create-rfc`
- Implementation planning after scope is fixed — use `create-technical-design-doc`
metadata:
version: '1.0.0'
category: documentation
dependencies: []
requires: {}
tags: [prd, product, requirements, documentation]
---
# Rule: Generating a Product Requirements Document (PRD)
## Goal
Guide an AI assistant in creating a detailed Product Requirements Document (PRD) in Markdown format, based on an initial user prompt. The PRD should be clear, actionable, and suitable for a junior developer to understand and implement the feature.
## Process
1. **Receive Initial Prompt**: The user provides a brief description or request for a new feature.
2. **Ask Clarifying Questions**: Before writing the PRD, the AI must ask clarifying questions to gather enough detail. The goal is to understand the "what" and "why" of the feature, not necessarily the "how" (which the developer will figure out). Make sure to provide options in lists with letters/numbers so the user can reply easily with their selections.
3. **Generate PRD**: Based on the initial prompt and the user's answers to the clarifying questions, generate a PRD using the structure described below.
4. **Save PRD**: Save the generated document as `prd-[feature-name].md` inside the `/tasks` directory.
## Clarifying Questions (Examples)
The AI should adapt its questions based on the prompt, but here are some common areas to explore:
- **Problem/Goal**: "What problem does this feature solve for the user?" or "What is the main goal we want to achieve with this feature?"
- **Target User**: "Who is the primary user of this feature?"
- **Core Functionality**: "Can you describe the key actions a user should be able to perform with this feature?"
- **User Stories**: "Could you provide a few user stories? (e.g., As a [type of user], I want to [perform an action] so that [benefit].)"
- **Acceptance Criteria**: "How will we know when this feature has been successfully implemented? What are the main success criteria?"
- **Scope/Boundaries**: "Are there specific things this feature should *not* do (non-goals)?"
- **Data Requirements**: "What kind of data does this feature need to display or manipulate?"
- **Design/UI**: "Are there any design mockups or UI guidelines to follow?" or "Can you describe the desired look and feel?"
- **Edge Cases**: "Are there any edge cases or error conditions we should consider?"
## PRD Structure
The generated PRD should include the following sections:
1. **Introduction/Overview**: Briefly describe the feature and the problem it solves. State the goal.
2. **Goals**: List the specific, measurable goals for this feature.
3. **User Stories**: Detail the user narratives describing how the feature is used and the benefits.
4. **Functional Requirements**: List the specific behaviors the feature must have. Use clear, concise language (e.g., "The system must allow users to upload a profile picture."). Number these requirements.
5. **Non-Goals (Out of Scope)**: Clearly state what this feature will *not* include in order to manage scope.
6. **Design Considerations (Optional)**: Link to mockups, describe UI/UX requirements, or mention relevant components/styles if applicable.
7. **Technical Considerations (Optional)**: Mention known technical constraints, dependencies, or suggestions (e.g., "Should integrate with the existing Auth module").
8. **Success Metrics**: How will the success of this feature be measured? (e.g., "Increase user engagement by 10%", "Reduce support tickets related to X").
9. **Open Questions**: List remaining questions or areas that need further clarification.
## Target Audience
Assume the primary reader of the PRD is a **junior developer**. Therefore, requirements should be explicit, unambiguous, and avoid jargon where possible. Provide enough detail for them to understand the feature's purpose and the core logic.
## Output
- **Format**: Markdown (`.md`)
- **Location**: `/tasks/`
- **Filename**: `prd-[feature-name].md`
## Final Instructions
1. Do NOT start implementing the PRD
2. Make sure to ask the user clarifying questions
3. Take the user's answers to the clarifying questions and improve the PRD
## Next Steps
Once the PRD is generated and approved, the natural follow-up is to decompose it into a task list. Invoke the `generate-tasks` skill with this PRD as input — it will produce actionable work items derived directly from the functional requirements and user stories captured here.
# RFC Section Templates
Complete Markdown templates for each RFC section. Read this file when generating an RFC document.
---
## 1. Header & Metadata (MANDATORY)
```markdown
# RFC: [Clear, Action-Oriented Title]
| Field | Value |
|--------------|------------------------------------|
| **Impact** | HIGH / MEDIUM / LOW |
| **Status** | NOT STARTED / IN PROGRESS / COMPLETE |
| **Driver** | @Name — responsible for the proposal |
| **Approver** | @Name1, @Name2 — must approve before action |
| **Contributors** | @Name3, @Name4 — provide input |
| **Informed** | @Team, @Stakeholder — kept in the loop |
| **Due Date** | YYYY-MM-DD (or "TBD") |
| **Resources** | [Link to Jira], [Link to design], [Related RFC] |
| **Created** | YYYY-MM-DD |
| **Last Updated** | YYYY-MM-DD |
```
**RACI Guidance**:
- **Driver**: Owns the proposal, drives the process, implements the outcome
- **Approver**: Decision-maker(s) — must explicitly approve or reject
- **Contributors**: Provide expertise, review options, raise concerns
- **Informed**: Notified of the decision but don't need to act
**If missing**: Ask "Who is driving this proposal? Who needs to approve the final decision? Who should be consulted?"
---
## 2. Background (MANDATORY)
```markdown
## Background
[2-4 paragraphs describing the current state and why a decision is needed]
**Current State**:
What exists today? What system, process, or situation does this RFC address?
**Problem or Opportunity**:
What is the specific pain point, risk, or opportunity driving this RFC?
Include data or evidence where possible (e.g., "we're spending 10h/week on X" or "incident rate has doubled").
**Why Now**:
What makes this decision urgent or timely?
- Business driver (deadline, market change, regulatory requirement)
- Technical driver (scaling limit, security risk, accumulating debt)
- Team driver (onboarding friction, process inefficiency)
**What Happens If We Don't Decide**:
- [Consequence 1 — e.g., continued cost, growing risk]
- [Consequence 2 — e.g., missed opportunity]
```
**If unclear**: Ask "What is the current situation? Why is this decision needed now? What happens if we do nothing?"
---
## 3. Assumptions (MANDATORY)
```markdown
## Assumptions
[Explicit statements taken as true for this proposal to hold. If any assumption proves false, this RFC should be revisited.]
| # | Assumption | Owner | Confidence | Invalidation Trigger |
|---|------------|-------|------------|----------------------|
| 1 | [e.g., "Current traffic will not exceed 10k req/s in the next 12 months"] | @Name | High | If traffic projections change |
| 2 | [e.g., "The team has capacity to implement this in Q2"] | @Name | Medium | If Q2 roadmap changes |
| 3 | [e.g., "Vendor X's pricing remains stable"] | @Name | Low | If pricing changes >20% |
**Confidence levels**:
- **High** — backed by data or contractual guarantees
- **Medium** — reasonable expectation, but not verified
- **Low** — uncertain; decision may need revisiting if this assumption shifts
**If any assumption is invalidated**: The Driver is responsible for reassessing the RFC outcome and communicating changes to Approvers and Informed parties.
```
**If missing**: Ask "What are you taking for granted for this proposal to work? What would need to be true for the recommended option to succeed?"
---
## 4. Decision Criteria (MANDATORY)
```markdown
## Decision Criteria
[State how the decision will be made — before listing options. This prevents criteria from being chosen retroactively to justify a preferred option.]
The option chosen must best satisfy the following criteria, listed in order of priority:
| Priority | Criterion | Description | Weight |
|----------|-----------|-------------|--------|
| 1 | [e.g., Security compliance] | Must meet SOC 2 / GDPR requirements | Must-have |
| 2 | [e.g., Time to production] | Decision should enable delivery within Q2 | High |
| 3 | [e.g., Total cost of ownership] | Prefer lower long-term cost over short-term savings | High |
| 4 | [e.g., Team expertise] | Prefer technologies the team already knows | Medium |
| 5 | [e.g., Reversibility] | Prefer options that are easier to undo if wrong | Medium |
| 6 | [e.g., Vendor lock-in] | Avoid deep dependence on a single vendor | Low |
**Weight guidance**:
- **Must-have**: Non-negotiable. An option that fails this criterion is disqualified.
- **High**: Strong influence on the decision.
- **Medium**: Considered, but can be traded off.
- **Low**: Nice to have; tiebreaker only.
**Decision rule**: The recommended option is the one that satisfies all Must-haves and scores highest across High and Medium criteria. Explicitly call out trade-offs when no option wins on all criteria.
```
**If missing**: Ask "What matters most when choosing between options? Are there any hard requirements that would disqualify an option? How will you weigh speed vs cost vs risk?"
---
## 5. Relevant Data (RECOMMENDED)
```markdown
## Relevant Data
[Evidence, metrics, or research that informs the decision]
**Quantitative Data**:
- Current cost/time: [e.g., "$X/month", "Y hours/week"]
- Usage/adoption: [e.g., "Z% of users affected"]
- Frequency: [e.g., "N incidents per quarter"]
**Qualitative Data**:
- User/team feedback: [summary of pain points or requests]
- Prior attempts: [what was tried before, why it didn't work]
**External References**:
- Industry benchmarks or standards
- Vendor documentation or case studies
- Research papers or technical articles
```
---
## 6. Options Considered (MANDATORY — minimum 2)
For each option, use this template. Evaluate against the **Decision Criteria** defined above.
```markdown
## Options Considered
### Option 1: [Option Name] ⭐ (Recommended)
**Description**:
[Clear description of this approach in 1-3 paragraphs]
**How It Works**:
1. Step or component A
2. Step or component B
3. Step or component C
**Pros**:
- [Advantage 1 — be specific]
- [Advantage 2]
- [Advantage 3]
**Cons**:
- [Disadvantage 1 — be honest]
- [Disadvantage 2]
**Estimated Cost**: LARGE / MEDIUM / SMALL
- Effort: [X weeks / person-days]
- Financial: [$X/month] (if applicable)
- Risk: HIGH / MEDIUM / LOW
---
### Option 2: [Option Name]
**Description**:
[Clear description of this approach]
**How It Works**:
1. Step or component A
2. Step or component B
**Pros**:
- [Advantage 1]
- [Advantage 2]
**Cons**:
- [Disadvantage 1]
- [Disadvantage 2]
**Estimated Cost**: LARGE / MEDIUM / SMALL
- Effort: [X weeks / person-days]
- Financial: [$X/month] (if applicable)
- Risk: HIGH / MEDIUM / LOW
---
### Option 3: Do Nothing (always consider)
**Description**:
Maintain the status quo and accept the current situation.
**Pros**:
- No immediate cost or disruption
- No migration risk
**Cons**:
- [Consequence of inaction 1]
- [Consequence of inaction 2]
**Estimated Cost**: SMALL (upfront) / potentially LARGE (long-term)
```
**Option Comparison Matrix** (for 3+ options):
```markdown
## Options Comparison
| Criterion | Option 1 | Option 2 | Option 3 |
|------------------------|----------|----------|----------|
| Implementation effort | Medium | Low | None |
| Cost | $X/mo | $Y/mo | $Z/mo |
| Time to value | 4 weeks | 1 week | N/A |
| Risk | Low | Medium | High |
| Reversibility | Easy | Hard | N/A |
| Team impact | Minimal | Moderate | None |
**Recommended**: Option 1 because [brief rationale]
```
---
## 7. Action Items (MANDATORY)
```markdown
## Action Items
[What happens after the decision is made — tasks required to implement the chosen option]
| Action | Owner | Due Date | Status |
|--------|-------|----------|--------|
| [Task 1 — e.g., "Evaluate vendor X with a PoC"] | @Name | YYYY-MM-DD | NOT STARTED |
| [Task 2 — e.g., "Update runbook for new process"] | @Name | YYYY-MM-DD | NOT STARTED |
| [Task 3 — e.g., "Communicate decision to affected teams"] | @Name | YYYY-MM-DD | NOT STARTED |
| [Task 4 — e.g., "Create follow-up TDD for implementation"] | @Name | YYYY-MM-DD | NOT STARTED |
**Note**: If this RFC is approved, a Technical Design Document (TDD) may be needed to plan the implementation in detail.
```
---
## 8. Outcome (MANDATORY — filled after decision)
```markdown
## Outcome
**Decision**: [Option X was chosen / RFC was rejected / deferred]
**Decision Date**: YYYY-MM-DD
**Decided By**: @Approver1, @Approver2
**Rationale**:
[Why this option was chosen over the alternatives. Be specific — future readers need to understand the reasoning, especially if circumstances change.]
**Key Factors**:
- [Factor 1 that drove the decision]
- [Factor 2]
- [Factor 3]
**Conditions / Caveats** (if any):
- [e.g., "Approved for Q1 only, will be revisited in Q2"]
- [e.g., "Requires security review before implementation"]
**Follow-up**:
- [ ] Create TDD for implementation (if applicable)
- [ ] Update affected documentation
- [ ] Notify informed stakeholders of decision
- [ ] Schedule retrospective in [X months] to evaluate outcome
```
---
id: create-rfc
name: RFC Creator
description: Creates structured Request for Comments (RFC) documents for proposing and deciding on significant changes. Use when the user says "write an RFC", "create a proposal", "I need to propose a change", "draft an RFC", "document a decision", or needs stakeholder alignment before making a major technical or process decision. Do NOT use for TDDs/implementation docs (use technical-design-doc-creator instead), README files, or general documentation.
metadata:
version: '1.0.0'
category: documentation
dependencies: []
requires: {}
tags: [rfc, proposal, decision-making, stakeholder-alignment, documentation]
---
# RFC Creator
You are an expert in creating Request for Comments (RFC) documents that clearly communicate proposals, capture alternatives considered, and drive structured decision-making across teams.
## When to Use This Skill
Use this skill when:
- User asks to "write an RFC", "create an RFC", "draft a proposal", or "write a request for comments"
- User needs to propose a significant change and gather stakeholder feedback
- A major architectural, process, or product decision needs to be documented before acting
- User wants to align multiple teams or approvers before committing to a direction
- User asks to "document a decision" or "get buy-in" on a proposal
- User needs to compare options and record the chosen direction with rationale
Do NOT use for:
- Technical Design Documents focused on implementation (use `technical-design-doc-creator`)
- Simple meeting notes or summaries
- README files or API documentation
## Language Adaptation
**CRITICAL**: Always generate the RFC in the **same language as the user's request**. Detect the language automatically and generate all content in that language.
- Keep technical terms in English when appropriate (e.g., "API", "RFC", "rollback", "stakeholder")
- Company/product names remain in original language
- Use natural, professional language for the target language
## RFC vs TDD
| Aspect | RFC | TDD |
|--------|-----|-----|
| **Purpose** | Propose + decide | Design + plan implementation |
| **Audience** | Broad stakeholders, leadership | Engineering team |
| **Focus** | Should we do X? Which option? | How do we build X? |
| **Output** | Decision + rationale | Architecture + implementation plan |
| **Timing** | Before committing to a direction | After direction is decided |
Use RFC when the **decision itself** needs alignment. Use TDD when the decision is made and you need to document the **implementation approach**.
## Interactive Workflow
### Step 1: Gather Context (if not provided)
If the user provides no context, use **AskQuestion** to collect basic information:
```json
{
"title": "RFC Information",
"questions": [
{
"id": "rfc_topic",
"prompt": "What is the topic or change you want to propose?",
"options": [
{ "id": "free_text", "label": "I'll describe it below" }
]
},
{
"id": "rfc_impact",
"prompt": "What is the estimated impact of this change?",
"options": [
{ "id": "high", "label": "HIGH - affects multiple teams, systems, or users" },
{ "id": "medium", "label": "MEDIUM - affects one team or system" },
{ "id": "low", "label": "LOW - limited scope, easily reversible" }
]
},
{
"id": "rfc_urgency",
"prompt": "Is there a due date or urgency?",
"options": [
{ "id": "urgent", "label": "Yes, we need a decision soon" },
{ "id": "planned", "label": "Part of planned roadmap" },
{ "id": "open", "label": "No fixed deadline" }
]
},
{
"id": "rfc_options",
"prompt": "Do you have options/alternatives in mind?",
"options": [
{ "id": "yes", "label": "Yes, I have 2+ options to compare" },
{ "id": "one", "label": "I have a preferred option, need to document alternatives" },
{ "id": "no", "label": "No, need help structuring options" }
]
}
]
}
```
### Step 2: Validate Mandatory Fields
**MANDATORY fields — ask if missing**:
- RFC title (clear, action-oriented)
- Background / context (what is the current state and why this matters)
- Driver (who is proposing / responsible for the decision)
- Approver(s) (who needs to approve)
- Impact level (HIGH / MEDIUM / LOW)
- At least 1 explicit assumption (with confidence level)
- At least 2 decision criteria (with weights), stated before options
- At least 2 options considered (including "do nothing" when relevant)
- Recommended option with rationale tied back to the decision criteria
If any of these are missing, ask IN THE USER'S LANGUAGE before generating the document.
### Step 3: Detect RFC Type and Tailor Sections
| RFC Type | Additional Focus Areas |
|----------|----------------------|
| **Technical/Architecture** | System impact, migration path, technical risks |
| **Process/Workflow** | Team impact, adoption plan, rollback if process fails |
| **Product/Feature** | User impact, metrics, go/no-go criteria |
| **Vendor/Tool Selection** | Cost comparison, lock-in risk, evaluation criteria |
| **Policy/Compliance** | Regulatory requirements, audit trail, enforcement |
### Step 4: Generate RFC Document
Generate the RFC in Markdown following the templates below.
### Step 5: Offer Next Steps
After generating, offer:
```
RFC Created: "[Title]"
Sections included:
- Mandatory: Header & Metadata, Background, Assumptions, Decision Criteria, Options Considered, Action Items, Outcome
- Recommended: Relevant Data, Pros/Cons comparison, Cost estimate, Resources
Suggested next steps:
- Share with Contributors for feedback
- Set a decision deadline
- Schedule a review meeting with Approvers
- Link related Jira/Linear tickets
Would you like me to:
1. Add more options to compare?
2. Create a follow-up technical design doc (TDD) for implementation details?
3. Publish this to Confluence?
```
## Document Structure
### Mandatory Sections
1. **Header & Metadata**
2. **Background**
3. **Assumptions**
4. **Decision Criteria**
5. **Options Considered** (minimum 2)
6. **Action Items**
7. **Outcome**
### Recommended Sections
8. **Relevant Data** — metrics, research, evidence
9. **Pros and Cons** (per option)
10. **Estimated Cost** (effort/complexity/monetary)
11. **Resources** — links, references, prior art
---
## Section Templates
Read `references/section-templates.md` when generating an RFC document. It contains complete Markdown templates for all 11 sections (7 mandatory + 4 recommended) with examples and "if missing" prompts for each field.
---
## RFC Quality Checklist
Before finalizing, verify:
- [ ] **Title**: Clear, action-oriented, specific (not "RFC about the database")
- [ ] **Impact**: Assessed as HIGH / MEDIUM / LOW with justification
- [ ] **Background**: Current state + problem + why now + cost of inaction
- [ ] **Assumptions**: Explicit, with confidence levels and invalidation triggers
- [ ] **Decision Criteria**: Defined *before* options, with weights; Must-haves identified
- [ ] **Data**: At least some evidence supporting the need for change
- [ ] **Options**: Minimum 2 options (including "do nothing" for significant changes)
- [ ] **Options evaluated against criteria**: Not just pros/cons in isolation
- [ ] **Pros/Cons**: Honest assessment, not just selling one option
- [ ] **Cost**: Effort estimate for each option (even if rough)
- [ ] **RACI**: Driver, Approver(s), Contributors, Informed all identified
- [ ] **Action Items**: Concrete next steps after the decision
- [ ] **Outcome**: Left as placeholder to be filled when decision is made
---
## Common Anti-Patterns to Avoid
### Predetermined Conclusion Disguised as RFC
**BAD**:
```
We should use Kubernetes. Here are some reasons. Option 2 is to not use Kubernetes (obviously wrong).
```
**GOOD**:
```
Option 1: Adopt Kubernetes — [genuine pros and cons]
Option 2: Stick with Docker Compose — [genuine pros and cons]
Option 3: Move to managed container platform (ECS/Cloud Run) — [genuine pros and cons]
```
### Vague Background
**BAD**:
```
Our current deployment process has some issues.
```
**GOOD**:
```
Our current deployment process requires 45 minutes of manual steps and has caused 3 production incidents in the past quarter due to human error. The team spends ~8 hours/week on deployment-related tasks.
```
### Missing "Do Nothing" Option
Always include the status quo as an option for significant changes — it forces honest evaluation of whether action is truly needed.
### No Decision Criteria (or criteria defined after options)
**BAD**: Presenting options first, then listing criteria — which looks like the criteria were chosen to justify a preferred option.
**GOOD**: Define criteria with weights *before* listing options. Then evaluate each option against them explicitly. The recommendation section should reference which criteria drove the decision.
### Hidden or Unstated Assumptions
**BAD**:
```
We'll migrate to the new system over 6 months.
```
**GOOD**:
```
Assumption: The team has 2 engineers available for migration work in Q3.
Confidence: Medium. Invalidated if Q3 headcount changes.
```
Unstated assumptions become invisible time bombs. When the RFC outcome stops working six months later, no one can tell whether the decision was wrong or whether a hidden assumption was invalidated.
---
## Output Summary Format
After generating the RFC:
```
RFC Created: "[Title]"
Impact: HIGH / MEDIUM / LOW
Status: NOT STARTED
Sections included:
- Header & Metadata (Driver, Approver, Due Date)
- Background (current state, problem, why now)
- N options compared with pros/cons and cost estimates
- Action Items (M tasks identified)
- Outcome (placeholder — to be filled after decision)
Suggested next steps:
- Share with Contributors listed for feedback
- Set the decision meeting for [Due Date]
- Update Status to IN PROGRESS
Would you like me to add anything else?
```
---
## Important Notes
- **RFC is for decisions, not implementation** — once the RFC is decided, create a TDD for the implementation plan
- **Honest options are critical** — a one-sided RFC undermines trust and produces bad decisions
- **"Do nothing" is always an option** — helps assess whether change is truly worth it
- **Outcome section is filled after the fact** — leave as placeholder during drafting
- **Language adaptation** — always write in the user's language
- **Respect user's context** — if the user provides rich context, use it; don't ask for what's already given
- **Be concise in options** — focus on the decision factors, not implementation details
- **RFCs age** — date everything; decisions made without context become confusing later
## Example Prompts that Trigger This Skill
### English
- "Write an RFC for migrating our database from MySQL to PostgreSQL"
- "I need an RFC to propose moving from monolith to microservices"
- "Create a request for comments on our on-call rotation policy"
- "Draft an RFC comparing self-hosted vs managed Kafka"
- "I need to get approval to adopt a new design system"
### Portuguese
- "Escreva um RFC para migrar nosso banco de dados"
- "Preciso de um RFC para propor a adoção de uma nova ferramenta"
- "Crie um Request for Comments sobre nossa política de on-call"
- "Quero documentar a decisão de trocar de provedor de cloud"
### Spanish
- "Escribe un RFC para migrar nuestra infraestructura a la nube"
- "Necesito un RFC para proponer un cambio en el proceso de deploy"
- "Crea un Request for Comments sobre la adopción de un nuevo framework"
---
id: create-technical-design-doc
name: Technical Design Doc Creator
description: Creates comprehensive Technical Design Documents (TDD) with mandatory and optional sections through interactive discovery. Use when user asks to "write a design doc", "create a TDD", "technical spec", "architecture document", "RFC", "design proposal", or needs to document a technical decision before implementation. Do NOT use for README files, API docs, or general documentation (use docs-writer instead).
metadata:
version: '1.0.0'
category: documentation
dependencies: []
requires: {}
tags: [tdd, technical-design, architecture, documentation]
---
# Technical Design Doc Creator
You are an expert in creating Technical Design Documents (TDDs) that clearly communicate software architecture decisions, implementation plans, and risk assessments following industry best practices.
## When to Use This Skill
Use this skill when:
- User asks to "create a TDD", "write a design doc", or "document technical design"
- User asks to "criar um TDD", "escrever um design doc", or "documentar design técnico"
- Starting a new feature or integration project
- Designing a system that requires team alignment
- Planning a migration or replacement of existing systems
- User mentions needing documentation for stakeholder approval
- Before implementing significant technical changes
## Language Adaptation
**CRITICAL**: Always generate the TDD in the **same language as the user's request**. Detect the language automatically from the user's input and generate all content (headers, prose, explanations) in that language.
**Translation Guidelines**:
- Translate all section headers, prose, and explanations to match user's language
- Keep technical terms in English when appropriate (e.g., "API", "webhook", "JSON", "rollback", "feature flag")
- Keep code examples and schemas language-agnostic (JSON, diagrams, code)
- Company/product names remain in original language
- Use natural, professional language for the target language
- Maintain consistency in terminology throughout the document
**Common Section Header Translations**:
| English | Portuguese | Spanish |
| -------------------------- | ------------------------------- | ---------------------------- |
| Context | Contexto | Contexto |
| Problem Statement | Definição do Problema | Definición del Problema |
| Scope | Escopo | Alcance |
| Technical Solution | Solução Técnica | Solución Técnica |
| Risks | Riscos | Riesgos |
| Implementation Plan | Plano de Implementação | Plan de Implementación |
| Security Considerations | Considerações de Segurança | Consideraciones de Seguridad |
| Testing Strategy | Estratégia de Testes | Estrategia de Pruebas |
| Monitoring & Observability | Monitoramento e Observabilidade | Monitoreo y Observabilidad |
| Rollback Plan | Plano de Rollback | Plan de Reversión |
## Industry Standards Reference
This skill follows established patterns from:
- **Google Design Docs**: Context, Goals, Non-Goals, Design, Alternatives, Security, Testing
- **Amazon PR-FAQ**: Working Backwards - start with customer problem
- **RFC Pattern**: Summary, Motivation, Explanation, Alternatives, Drawbacks
- **ADR (Architecture Decision Records)**: Context, Decision, Consequences
- **SRE Book**: Monitoring, Rollback, SLOs, Observability
- **PCI DSS**: Security requirements for payment systems
- **OWASP**: Security best practices
## High-Level vs Implementation Details
**CRITICAL PRINCIPLE**: TDDs document **architectural decisions and contracts**, NOT implementation code.
### ✅ What to Include (High-Level)
| Category | Include | Example |
| ----------------- | ----------------------------- | --------------------------------------------------------------- |
| **API Contracts** | Request/Response schemas | `POST /subscriptions` with JSON body structure |
| **Data Schemas** | Table structures, field types | `BillingCustomer` table with fields: id, email, stripeId |
| **Architecture** | Components, data flow | "Frontend → API → Service → Stripe → Database" |
| **Decisions** | What technology, why chosen | "Use Stripe because: global support, PCI compliance, best docs" |
| **Diagrams** | Sequence, architecture, flow | Mermaid/PlantUML diagrams showing interactions |
| **Structures** | Log format, event schemas | JSON structure for structured logging |
| **Strategies** | Approach, not commands | "Rollback via feature flag" (not the curl command) |
### ❌ What to Avoid (Implementation Code)
| Category | Avoid | Why |
| ------------------------ | ---------------------------------------- | ------------------------------------------------- |
| **CLI Commands** | `nx db:generate`, `kubectl rollout undo` | Too specific, may change with tooling |
| **Code Snippets** | TypeScript/JavaScript implementation | Belongs in code, not docs |
| **Framework Specifics** | `@Injectable()`, `extends Repository` | Framework may change, decision is what matters |
| **File Paths** | `scripts/backfill-feature.ts` | Implementation detail, not architectural decision |
| **Tool-Specific Syntax** | NestJS decorators, TypeORM entities | Document pattern, not implementation |
### Examples: High-Level vs Implementation
#### ❌ BAD (Too Implementation-Specific)
````markdown
**Rollback Steps**:
```bash
curl -X PATCH https://api.launchdarkly.com/flags/FEATURE_X \
-H "Authorization: Bearer $API_KEY" \
-d '{"enabled": false}'
nx db:rollback billing
```
````
````
#### ✅ GOOD (High-Level Decision)
```markdown
**Rollback Steps**:
1. Disable feature flag via feature flag service dashboard
2. Revert database schema using down migration
3. Verify system returns to previous state
4. Monitor error rates to confirm rollback success
````
#### ❌ BAD (Implementation Code)
````markdown
**Service Implementation**:
```typescript
@Injectable()
export class CustomerService {
@Transactional({ connectionName: 'billing' })
async create(data: CreateCustomerDto) {
const customer = new Customer()
customer.email = data.email
return this.repository.save(customer)
}
}
```
````
````
#### ✅ GOOD (High-Level Structure)
```markdown
**Service Layer**:
- `CustomerService`: Manages customer lifecycle
- `create()`: Creates customer, validates email uniqueness
- `getById()`: Retrieves customer by ID
- `updatePaymentMethod()`: Updates default payment method
- All write operations use transactions to ensure data consistency
- Services call external Stripe API and cache results locally
````
### Guideline: Ask "Will This Change?"
Before adding detail to TDD, ask:
- **"If we change frameworks, does this detail still apply?"**
- YES → Include (it's an architectural decision)
- NO → Exclude (it's implementation detail)
- **"Can someone implement this differently and still meet the requirement?"**
- YES → Focus on the requirement, not the implementation
- NO → You might be too specific
**Goal**: TDD should survive implementation changes. If you migrate from NestJS to Express, or TypeORM to Prisma, the TDD should still be valid.
## Document Structure
### Mandatory Sections (Must Have)
These sections are **required**. If the user doesn't provide information, you **must ask** using AskQuestion tool:
1. **Header & Metadata**
2. **Context**
3. **Problem Statement & Motivation**
4. **Scope** (In Scope / Out of Scope)
5. **Technical Solution**
6. **Risks**
7. **Implementation Plan**
### Critical Sections (Ask if Missing)
These are **highly recommended** especially for:
- Payment integrations (Security is MANDATORY)
- Production systems (Monitoring, Rollback are MANDATORY)
- External integrations (Dependencies, Security)
8. **Security Considerations** (MANDATORY for payments/auth/PII)
9. **Testing Strategy**
10. **Monitoring & Observability**
11. **Rollback Plan**
### Suggested Sections (Offer to User)
Ask user: "Would you like to add these sections now or later?"
12. **Success Metrics**
13. **Glossary & Domain Terms**
14. **Alternatives Considered**
15. **Dependencies**
16. **Performance Requirements**
17. **Migration Plan** (if applicable)
18. **Open Questions**
19. **Roadmap / Timeline**
20. **Approval & Sign-off**
## Project Size Adaptation
Use this heuristic to determine project complexity:
### Small Project (< 1 week)
**Use sections**: 1, 2, 3, 4, 5, 6, 7, 9
**Skip**: Alternatives, Migration Plan, Approval
### Medium Project (1-4 weeks)
**Use sections**: 1-11, 15, 18
**Offer**: Success Metrics, Glossary, Alternatives, Performance
### Large Project (> 1 month)
**Use all sections** (1-20)
**Critical**: All mandatory + critical sections must be detailed
## Interactive Workflow
### Step 1: Initial Gathering
Use **AskQuestion** tool to collect basic information:
```json
{
"title": "TDD Project Information",
"questions": [
{
"id": "project_name",
"prompt": "What is the name of the feature/integration/project?",
"options": [] // Free text
},
{
"id": "project_size",
"prompt": "What is the expected project size?",
"options": [
{ "id": "small", "label": "Small (< 1 week)" },
{ "id": "medium", "label": "Medium (1-4 weeks)" },
{ "id": "large", "label": "Large (> 1 month)" }
]
},
{
"id": "project_type",
"prompt": "What type of project is this?",
"allow_multiple": true,
"options": [
{ "id": "integration", "label": "External integration (API, service)" },
{ "id": "feature", "label": "New feature" },
{ "id": "refactor", "label": "Refactoring/migration" },
{ "id": "infrastructure", "label": "Infrastructure/platform" },
{ "id": "payment", "label": "Payment/billing system" },
{ "id": "auth", "label": "Authentication/authorization" },
{ "id": "data", "label": "Data migration/processing" }
]
},
{
"id": "has_context",
"prompt": "Do you have a clear problem statement and context?",
"options": [
{ "id": "yes", "label": "Yes, I can provide it now" },
{ "id": "partial", "label": "Partially, need help clarifying" },
{ "id": "no", "label": "No, need help defining it" }
]
}
]
}
```
### Step 2: Validate Mandatory Information
Based on answers, check if user can provide:
**MANDATORY fields to ask if missing**:
- Tech Lead / Owner
- Team members
- Problem description (what/why/impact)
- What is in scope
- What is out of scope
- High-level solution approach
- At least 3 risks
- Implementation tasks breakdown
**Ask using AskQuestion or natural conversation IN THE USER'S LANGUAGE**:
**English Example**:
```
I need the following information to create the TDD:
1. **Problem Statement**:
- What problem are we solving?
- Why is this important now?
- What happens if we don't solve it?
2. **Scope**:
- What WILL be delivered in this project?
- What will NOT be included (out of scope)?
3. **Technical Approach**:
- High-level description of the solution
- Main components involved
- Integration points
Can you provide this information?
```
**Portuguese Example**:
```
Preciso das seguintes informações para criar o TDD:
1. **Definição do Problema**:
- Que problema estamos resolvendo?
- Por que isso é importante agora?
- O que acontece se não resolvermos?
2. **Escopo**:
- O que SERÁ entregue neste projeto?
- O que NÃO será incluído (fora do escopo)?
3. **Abordagem Técnica**:
- Descrição de alto nível da solução
- Principais componentes envolvidos
- Pontos de integração
Você pode fornecer essas informações?
```
### Step 3: Check for Critical Sections
Based on `project_type`, determine if critical sections are mandatory:
| Project Type | Critical Sections Required |
| ----------------- | ------------------------------------------ |
| `payment`, `auth` | **Security Considerations** (MANDATORY) |
| All production | **Monitoring & Observability** (MANDATORY) |
| All production | **Rollback Plan** (MANDATORY) |
| `integration` | **Dependencies**, **Security** |
| All | **Testing Strategy** (highly recommended) |
**If critical sections are missing, ASK IN THE USER'S LANGUAGE**:
**English**:
```
This is a [payment/auth/production] system. These sections are CRITICAL:
❗ **Security Considerations** - Required for compliance (PCI DSS, OWASP)
❗ **Monitoring & Observability** - Required to detect issues in production
❗ **Rollback Plan** - Required to revert if something fails
Can you provide:
1. Security requirements (auth, encryption, PII handling)?
2. What metrics will you monitor?
3. How will you rollback if something goes wrong?
```
**Portuguese**:
```
Este é um sistema de [pagamento/autenticação/produção]. Estas seções são CRÍTICAS:
❗ **Considerações de Segurança** - Obrigatório para compliance (PCI DSS, OWASP)
❗ **Monitoramento e Observabilidade** - Obrigatório para detectar problemas em produção
❗ **Plano de Rollback** - Obrigatório para reverter se algo falhar
Você pode fornecer:
1. Requisitos de segurança (autenticação, encriptação, tratamento de PII)?
2. Quais métricas você vai monitorar?
3. Como você fará rollback se algo der errado?
```
### Step 4: Offer Suggested Sections
After mandatory sections are covered, **offer optional sections IN THE USER'S LANGUAGE**:
**English**:
```
I can also add these sections to make the TDD more complete:
📊 **Success Metrics** - How will you measure success?
📚 **Glossary** - Define domain-specific terms
⚖️ **Alternatives Considered** - Why this approach over others?
🔗 **Dependencies** - External services/teams needed
⚡ **Performance Requirements** - Latency, throughput, availability targets
📋 **Open Questions** - Track pending decisions
Would you like me to add any of these now? (You can add them later)
```
**Portuguese**:
```
Também posso adicionar estas seções para tornar o TDD mais completo:
📊 **Métricas de Sucesso** - Como você vai medir o sucesso?
📚 **Glossário** - Definir termos específicos do domínio
⚖️ **Alternativas Consideradas** - Por que esta abordagem ao invés de outras?
🔗 **Dependências** - Serviços/times externos necessários
⚡ **Requisitos de Performance** - Latência, throughput, disponibilidade
📋 **Questões em Aberto** - Rastrear decisões pendentes
Gostaria que eu adicionasse alguma dessas agora? (Você pode adicionar depois)
```
### Step 5: Generate Document
Generate the TDD in Markdown format following the templates below.
### Step 6: Offer Confluence Integration
If user has Confluence Assistant skill available, **ask in their language**:
**English**:
```
Would you like me to publish this TDD to Confluence?
- I can create a new page in your space
- Or update an existing page
```
**Portuguese**:
```
Gostaria que eu publicasse este TDD no Confluence?
- Posso criar uma nova página no seu espaço
- Ou atualizar uma página existente
```
## Section Templates
### 1. Header & Metadata (MANDATORY)
```markdown
# TDD - [Project/Feature Name]
| Field | Value |
| --------------- | ---------------------------- |
| Tech Lead | @Name |
| Product Manager | @Name (if applicable) |
| Team | Name1, Name2, Name3 |
| Epic/Ticket | [Link to Jira/Linear] |
| Figma/Design | [Link if applicable] |
| Status | Draft / In Review / Approved |
| Created | YYYY-MM-DD |
| Last Updated | YYYY-MM-DD |
```
**If user doesn't provide**: Ask for Tech Lead, Team members, and Epic link.
---
### 2. Context (MANDATORY)
```markdown
## Context
[2-4 paragraph description of the project]
**Background**:
What is the current state? What system/feature does this relate to?
**Domain**:
What business domain is this part of? (e.g., billing, authentication, content delivery)
**Stakeholders**:
Who cares about this project? (users, business, compliance, etc.)
```
**If unclear**: Ask "Can you describe the current situation and what business domain this relates to?"
---
### 3. Problem Statement & Motivation (MANDATORY)
```markdown
## Problem Statement & Motivation
### Problems We're Solving
- **Problem 1**: [Specific pain point with impact]
- Impact: [quantify if possible - time wasted, cost, user friction]
- **Problem 2**: [Another pain point]
- Impact: [quantify if possible]
### Why Now?
- [Business driver - market expansion, competitor pressure, regulatory requirement]
- [Technical driver - technical debt, scalability limits]
- [User driver - customer feedback, usage patterns]
### Impact of NOT Solving
- **Business**: [revenue loss, competitive disadvantage]
- **Technical**: [technical debt accumulation, system degradation]
- **Users**: [poor experience, churn risk]
```
**If user says "to integrate with X"**: Ask "What specific problems will this integration solve? Why is it important now? What happens if we don't do it?"
---
### 4. Scope (MANDATORY)
```markdown
## Scope
### ✅ In Scope (V1 - MVP)
Explicit list of what WILL be delivered:
- Feature/capability 1
- Feature/capability 2
- Feature/capability 3
- Integration point A
- Data migration for X
### ❌ Out of Scope (V1)
Explicit list of what will NOT be included in this phase:
- Feature X (deferred to V2)
- Integration Y (not needed for MVP)
- Advanced analytics (future enhancement)
- Multi-region support (V2)
### 🔮 Future Considerations (V2+)
What might come later:
- Feature A (user demand dependent)
- Feature B (after V1 validation)
```
**If user doesn't define**: Ask "What are the must-haves for V1? What can wait for later versions?"
---
### 5. Technical Solution (MANDATORY)
````markdown
## Technical Solution
### Architecture Overview
[High-level description of the solution]
**Key Components**:
- Component A: [responsibility]
- Component B: [responsibility]
- Component C: [responsibility]
**Architecture Diagram**:
[Include Mermaid diagram, PlantUML, or link to diagram]
```mermaid
graph LR
A[Frontend] -->|HTTP| B[API Gateway]
B -->|GraphQL| C[Backend Service]
C -->|REST| D[External API]
C -->|Write| E[(Database)]
```
````
### Data Flow
1. **Step 1**: User action → Frontend
2. **Step 2**: Frontend → API Gateway (POST /resource)
3. **Step 3**: API Gateway → Service Layer
4. **Step 4**: Service → External API (if applicable)
5. **Step 5**: Service → Database (persist)
6. **Step 6**: Response → Frontend
### APIs & Endpoints
| Endpoint | Method | Description | Request | Response |
| ---------------------- | ------ | ---------------- | ----------- | ---------------- |
| `/api/v1/resource` | POST | Creates resource | `CreateDto` | `ResourceDto` |
| `/api/v1/resource/:id` | GET | Get by ID | - | `ResourceDto` |
| `/api/v1/resource/:id` | DELETE | Delete resource | - | `204 No Content` |
**Example Request/Response**:
```json
// POST /api/v1/resource
{
"name": "Example",
"type": "standard"
}
// Response 201 Created
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "Example",
"type": "standard",
"status": "active",
"createdAt": "2026-02-04T10:00:00Z"
}
```
### Database Changes
**New Tables**:
- `{ModuleName}{EntityName}` - [description]
- Primary fields: id, userId, name, status
- Timestamps: createdAt, updatedAt
- Indexes: userId, status (for query performance)
**Schema Changes** (if modifying existing):
- Add column `newField` to `ExistingTable`
- Type: [varchar/integer/jsonb/etc.]
- Constraints: [nullable/unique/foreign key]
**Migration Strategy**:
- Generate migration from schema changes
- Test migration on staging environment first
- Run during low-traffic window
- Have rollback migration ready
**Data Backfill** (if needed):
- Affected records: Estimate quantity
- Processing time: Estimate duration for data migration
- Validation: How to verify data integrity after backfill
````
**If user provides vague description**: Ask "What are the main components? How does data flow through the system? What APIs will be created/modified?"
---
### 6. Risks (MANDATORY)
```markdown
## Risks
| Risk | Impact | Probability | Mitigation |
|------|--------|-------------|------------|
| External API downtime | High | Medium | Implement circuit breaker, cache responses, fallback to degraded mode |
| Data migration failure | High | Low | Test on staging copy, run dry-run first, have rollback script ready |
| Performance degradation | Medium | Medium | Load test before deployment, implement caching, monitor latency |
| Security vulnerability | High | Low | Security review, penetration testing, follow OWASP guidelines |
| Scope creep | Medium | High | Strict scope definition, change request process, regular stakeholder alignment |
**Risk Scoring**:
- **Impact**: High (system down, data loss) / Medium (degraded UX) / Low (minor inconvenience)
- **Probability**: High (>50%) / Medium (20-50%) / Low (<20%)
````
**If user provides < 3 risks**: Ask "What could go wrong? Consider: external dependencies, data integrity, performance, security, scope changes."
---
### 7. Implementation Plan (MANDATORY)
```markdown
## Implementation Plan
| Phase | Task | Description | Owner | Status | Estimate |
| --------------------- | ----------------- | -------------------------------------- | ------- | ------ | -------- |
| **Phase 1 - Setup** | Setup credentials | Obtain API keys, configure environment | @Dev1 | TODO | 1d |
| | Database setup | Create schema, configure datasource | @Dev1 | TODO | 1d |
| **Phase 2 - Core** | Entities & repos | Create TypeORM entities, repositories | @Dev2 | TODO | 3d |
| | Services | Implement business logic services | @Dev2 | TODO | 4d |
| **Phase 3 - APIs** | REST endpoints | Create controllers, DTOs | @Dev3 | TODO | 3d |
| | Integration | Integrate with external API | @Dev1 | TODO | 3d |
| **Phase 4 - Testing** | Unit tests | Test services and repositories | @Team | TODO | 2d |
| | E2E tests | Test full flow | @Team | TODO | 3d |
| **Phase 5 - Deploy** | Staging deploy | Deploy to staging, smoke test | @DevOps | TODO | 1d |
| | Production deploy | Phased rollout to production | @DevOps | TODO | 1d |
**Total Estimate**: ~20 days (4 weeks)
**Dependencies**:
- Must complete Phase N before Phase N+1
- External API access required before Phase 3
- Security review required before Phase 5
```
**If user provides vague plan**: Ask "Can you break this down into phases with specific tasks? Who will work on each part? What's the estimated timeline?"
---
### 8. Security Considerations (CRITICAL for payments/auth/PII)
```markdown
## Security Considerations
### Authentication & Authorization
- **Authentication**: How users prove identity
- Example: JWT tokens, OAuth 2.0, session-based
- **Authorization**: What authenticated users can access
- Example: Role-based (RBAC), Attribute-based (ABAC)
- Ensure users can only access their own resources
### Data Protection
**Encryption**:
- **At Rest**: Database encryption enabled (AES-256)
- **In Transit**: TLS 1.3 for all API communication
- **Secrets**: Store API keys in environment variables / secret manager (AWS Secrets Manager, HashiCorp Vault)
**PII Handling**:
- What PII is collected: [email, name, payment info]
- Legal basis: [consent, contract, legitimate interest]
- Retention: [how long data is kept]
- Deletion: [GDPR right to be forgotten implementation]
### Compliance Requirements
| Regulation | Requirement | Implementation |
| ----------- | ---------------------------------- | ------------------------------------------------- |
| **GDPR** | Data protection, right to deletion | Implement data export/deletion endpoints |
| **PCI DSS** | No storage of card data | Use Stripe tokenization, never store CVV/full PAN |
| **LGPD** | Brazil data protection | Same as GDPR compliance |
### Security Best Practices
- ✅ Input validation on all endpoints
- ✅ SQL injection prevention (parameterized queries)
- ✅ XSS prevention (sanitize user input, CSP headers)
- ✅ CSRF protection (tokens for state-changing operations)
- ✅ Rate limiting (e.g., 10 req/min per user, 100 req/min per IP)
- ✅ Audit logging (log all sensitive operations)
### Secrets Management
**API Keys**:
- Storage: Environment variables or secret management service
- Rotation: Define rotation policy (e.g., every 90 days)
- Access: Backend services only, never exposed to frontend
- Examples: Stripe keys, database credentials, API tokens
**Webhook Signatures**:
- Validate webhook signatures from external services
- Reject requests without valid signature headers
- Log invalid signature attempts for security monitoring
```
**If missing and project involves payments/auth**: Ask "This is a [payment/auth] system. I need security details: How will you handle authentication? What encryption will be used? What PII is collected? Any compliance requirements (GDPR, PCI DSS)?"
---
### 9. Testing Strategy (CRITICAL)
```markdown
## Testing Strategy
| Test Type | Scope | Coverage Target | Approach |
| --------------------- | ------------------------ | ------------------------ | -------------------- |
| **Unit Tests** | Services, repositories | > 80% | Jest with mocks |
| **Integration Tests** | API endpoints + database | Critical paths | Supertest + test DB |
| **E2E Tests** | Full user flows | Happy path + error cases | Playwright |
| **Contract Tests** | External API integration | API contract validation | Pact or manual mocks |
| **Load Tests** | Performance under load | Baseline performance | k6 or Artillery |
### Test Scenarios
**Unit Tests**:
- ✅ Service business logic (create, update, delete)
- ✅ Repository query methods
- ✅ Error handling (throw correct exceptions)
- ✅ Edge cases (null inputs, invalid data)
**Integration Tests**:
- ✅ POST `/api/v1/resource` → creates in DB
- ✅ GET `/api/v1/resource/:id` → returns correct data
- ✅ DELETE `/api/v1/resource/:id` → removes from DB
- ✅ Invalid input → returns 400 Bad Request
- ✅ Unauthorized access → returns 401/403
**E2E Tests**:
- ✅ User creates resource → success flow
- ✅ User tries to access another user's resource → denied
- ✅ External API fails → graceful degradation
- ✅ Database connection lost → proper error handling
**Load Tests**:
- Target: 100 req/s sustained, 500 req/s peak
- Monitor: Latency (p50, p95, p99), error rate, throughput
- Pass criteria: p95 < 500ms, error rate < 1%
### Test Data Management
- Use factories for test data (e.g., `@faker-js/faker`)
- Seed test database with realistic data
- Clean up test data after each test
- Use separate test database (never use production)
```
**If missing**: Ask "How will you test this? What test types are needed (unit, integration, e2e)? What are critical test scenarios?"
---
### 10. Monitoring & Observability (CRITICAL for production)
````markdown
## Monitoring & Observability
### Metrics to Track
| Metric | Type | Alert Threshold | Dashboard |
| ------------------------- | ---------- | ----------------- | ------------------ |
| `api.latency` | Latency | p95 > 1s for 5min | DataDog / Grafana |
| `api.error_rate` | Error rate | > 1% for 5min | DataDog / Grafana |
| `external_api.latency` | Latency | p95 > 2s for 5min | DataDog |
| `external_api.errors` | Counter | > 5 in 1min | PagerDuty |
| `database.query_time` | Duration | p95 > 100ms | DataDog |
| `webhook.processing_time` | Duration | > 5s | Internal Dashboard |
### Structured Logging
**Log Format** (JSON):
```json
{
"level": "info",
"timestamp": "2026-02-04T10:00:00Z",
"message": "Resource created",
"context": {
"userId": "user-123",
"resourceId": "res-456",
"action": "create",
"duration_ms": 45
}
}
```
````
**What to Log**:
- ✅ All API requests (method, path, status, duration)
- ✅ External API calls (endpoint, status, duration)
- ✅ Database queries (slow queries > 100ms)
- ✅ Errors and exceptions (stack trace, context)
- ✅ Business events (resource created, payment processed)
**What NOT to Log**:
- ❌ Passwords, API keys, secrets
- ❌ Full credit card numbers
- ❌ Sensitive PII (redact or hash)
### Alerts
| Alert | Severity | Channel | On-Call Action |
| ---------------------------------- | ------------- | ------------------ | ------------------------------------------- |
| Error rate > 5% | P1 (Critical) | PagerDuty | Immediate investigation, rollback if needed |
| External API down | P1 (Critical) | PagerDuty | Enable fallback mode, notify stakeholders |
| Latency > 2s (p95) | P2 (High) | Slack #engineering | Investigate performance degradation |
| Webhook failures > 20 | P2 (High) | Slack #engineering | Check webhook endpoint, Stripe status |
| Database connection pool exhausted | P1 (Critical) | PagerDuty | Scale up connections or investigate leak |
### Dashboards
**Operational Dashboard**:
- Request rate (per endpoint)
- Error rate (overall and per endpoint)
- Latency (p50, p95, p99)
- External API health
- Database performance
**Business Dashboard**:
- Resources created (count per day)
- Active users
- Conversion metrics (if applicable)
````
**If missing for production system**: Ask "How will you monitor this in production? What metrics matter? What alerts do you need?"
---
### 11. Rollback Plan (CRITICAL for production)
```markdown
## Rollback Plan
### Deployment Strategy
- **Feature Flag**: `FEATURE_X_ENABLED` (LaunchDarkly / custom)
- **Phased Rollout**:
- Phase 1: 5% of traffic (1 day)
- Phase 2: 25% of traffic (1 day)
- Phase 3: 50% of traffic (1 day)
- Phase 4: 100% of traffic
- **Canary Deployment**: Deploy to 1 instance first, monitor for 1h before full rollout
### Rollback Triggers
| Trigger | Action |
|---------|--------|
| Error rate > 5% for 5 minutes | **Immediate rollback** - disable feature flag |
| Latency > 3s (p95) for 10 minutes | **Investigate** - rollback if no quick fix |
| External API integration failing > 50% | **Rollback** - revert to previous version |
| Database migration fails | **STOP** - do not proceed, investigate |
| Customer reports of data loss | **Immediate rollback** + incident response |
### Rollback Steps
**1. Immediate Rollback (< 5 minutes)**:
- **Feature Flag**: Disable via feature flag dashboard (instant)
- **Deployment**: Revert to previous version via deployment tool (2-3 minutes)
**2. Database Rollback** (if schema changed):
- Run down migration using migration tool
- Verify schema integrity
- Confirm data consistency
**3. Communication**:
- Notify #engineering Slack channel
- Update status page (if customer-facing)
- Create incident ticket
- Schedule post-mortem within 24h
### Post-Rollback
- **Root Cause Analysis**: Within 24 hours
- **Fix**: Implement fix in development environment
- **Re-test**: Full test suite + additional tests for root cause
- **Re-deploy**: Following same phased rollout strategy
### Database Rollback Considerations
- **Migrations**: Always create reversible migrations (down migration)
- **Data Backfill**: If data was modified, have script to restore previous state
- **Backup**: Take database snapshot before running migrations
- **Testing**: Test rollback procedure on staging before production
````
**If missing for production**: Ask "What happens if the deploy goes wrong? How will you rollback? What are the triggers for rollback?"
---
### 12. Success Metrics (SUGGESTED)
```markdown
## Success Metrics
| Metric | Baseline | Target | Measurement |
| ----------------------- | ------------- | ------- | ------------------ |
| API latency (p95) | N/A (new API) | < 200ms | DataDog APM |
| Error rate | N/A | < 0.1% | Sentry / logs |
| Conversion rate | N/A | > 70% | Analytics |
| User satisfaction | N/A | NPS > 8 | User survey |
| Time to complete action | N/A | < 30s | Frontend analytics |
**Business Metrics**:
- Increase in [metric] by [X%]
- Reduction in [cost/time] by [Y%]
- User adoption: [Z%] of users using new feature within 30 days
**Technical Metrics**:
- Zero production incidents in first 30 days
- Test coverage > 80%
- Documentation completeness: 100% of public APIs documented
```
---
### 13. Glossary & Domain Terms (SUGGESTED)
```markdown
## Glossary
| Term | Description |
| ------------------- | --------------------------------------------------------------------- |
| **Customer** | A user who has an active subscription or has made a purchase |
| **Subscription** | Recurring payment arrangement with defined interval (monthly, annual) |
| **Trial** | Free period for users to test service before payment required |
| **Webhook** | HTTP callback from external service to notify of events |
| **Idempotency** | Operation can be applied multiple times with same result |
| **Circuit Breaker** | Pattern to prevent cascading failures when external service is down |
**Acronyms**:
- **API**: Application Programming Interface
- **SLA**: Service Level Agreement
- **PII**: Personally Identifiable Information
- **GDPR**: General Data Protection Regulation
- **PCI DSS**: Payment Card Industry Data Security Standard
```
---
### 14. Alternatives Considered (SUGGESTED)
```markdown
## Alternatives Considered
| Option | Pros | Cons | Why Not Chosen |
| --------------------- | -------------------------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------- |
| **Option A** (Chosen) | + Best documentation<br>+ Global support<br>+ Mature SDK | - Cost: 2.9% + $0.30<br>- Vendor lock-in | ✅ **Chosen** - Best balance of features and cost |
| Option B | + Lower fees (2.5%)<br>+ Brand recognition | - Poor developer experience<br>- Limited international support | Developer experience inferior, harder to maintain |
| Option C | + Full control<br>+ No transaction fees | - High maintenance cost<br>- Compliance burden (PCI DSS)<br>- Security risk | Too risky and expensive to maintain in-house |
| Option D | + Cheapest option | - No support<br>- Limited features<br>- Unknown reliability | Too risky for production payment processing |
**Decision Criteria**:
1. Developer experience and documentation quality (weight: 40%)
2. Total cost of ownership (weight: 30%)
3. International support and compliance (weight: 20%)
4. Reliability and uptime (weight: 10%)
**Why Option A Won**:
- Scored highest on developer experience (critical for fast iteration)
- Industry-standard for startups (easier to hire developers with experience)
- Built-in compliance (PCI DSS, SCA, 3D Secure) reduces risk
```
---
### 15. Dependencies (SUGGESTED)
```markdown
## Dependencies
| Dependency | Type | Owner | Status | Risk |
| --------------------- | -------------- | ----------- | ---------------- | ------------------- |
| Stripe API | External | Stripe Inc. | Production-ready | Low (99.99% uptime) |
| Identity Module | Internal | Team Auth | Production-ready | Low |
| Database (PostgreSQL) | Infrastructure | DevOps | Ready | Low |
| Redis (caching) | Infrastructure | DevOps | Needs setup | Medium |
| Feature flag service | Internal | Platform | Ready | Low |
**Approval Requirements**:
- [ ] Security team review (for payment/auth projects)
- [ ] Compliance sign-off (for PII/payment data)
- [ ] Ops team ready for monitoring setup
- [ ] Product sign-off on scope
**Blockers**:
- Waiting for Stripe production keys (ETA: 2026-02-10)
- Need Redis setup in staging (ETA: 2026-02-08)
```
---
### 16. Performance Requirements (SUGGESTED)
```markdown
## Performance Requirements
| Metric | Requirement | Measurement Method |
| ------------------- | ----------------------------- | ------------------ |
| API Latency (p50) | < 100ms | DataDog APM |
| API Latency (p95) | < 500ms | DataDog APM |
| API Latency (p99) | < 1s | DataDog APM |
| Throughput | 1000 req/s sustained | Load testing (k6) |
| Availability | 99.9% (< 8.76h downtime/year) | Uptime monitoring |
| Database query time | < 50ms (p95) | Slow query log |
**Load Testing Plan**:
- Baseline: 100 req/s for 10 minutes
- Peak: 500 req/s for 5 minutes
- Spike: 1000 req/s for 1 minute
**Scalability**:
- Horizontal scaling: Add more instances (Kubernetes autoscaling)
- Database: Read replicas if needed (after 10k req/s)
- Caching: Redis for frequently accessed data (> 100 req/s per resource)
```
---
### 17. Migration Plan (SUGGESTED - if applicable)
```markdown
## Migration Plan
### Migration Strategy
**Type**: [Blue-Green / Rolling / Big Bang / Phased]
**Phases**:
| Phase | Description | Users Affected | Duration | Rollback |
| ----------------- | -------------------------------------- | -------------- | -------- | ------------------- |
| 1. Preparation | Set up new system, run in parallel | 0% | 1 week | N/A |
| 2. Shadow Mode | New system processes but doesn't serve | 0% | 1 week | Instant |
| 3. Pilot | 5% of users on new system | 5% | 1 week | < 5min |
| 4. Ramp Up | 50% of users on new system | 50% | 1 week | < 5min |
| 5. Full Migration | 100% of users on new system | 100% | 1 day | < 5min |
| 6. Decommission | Turn off old system | 0% | 1 week | Restore from backup |
### Data Migration
**Source**: Old system database
**Destination**: New system database
**Volume**: [X million records]
**Method**: [ETL script / database replication / API sync]
**Steps**:
1. Export data from old system (script: `scripts/export-old-data.ts`)
2. Transform data to new schema (script: `scripts/transform-data.ts`)
3. Validate data integrity (checksums, row counts)
4. Load into new system (script: `scripts/load-new-data.ts`)
5. Verify: Run parallel reads, compare results
**Timeline**:
- Dry run on staging: 2026-02-10
- Production migration window: 2026-02-15 02:00-06:00 UTC (low traffic)
### Backward Compatibility
- Old API endpoints will remain active for 90 days
- Deprecation warnings added to responses
- Client libraries updated with migration guide
```
---
### 18. Open Questions (SUGGESTED)
```markdown
## Open Questions
| # | Question | Context | Owner | Status | Decision Date |
| --- | ------------------------------------------------------ | ---------------------------------------------- | --------- | ---------------- | ------------- |
| 1 | How to handle trial expiration without payment method? | User loses access immediately or grace period? | @Product | 🟡 In Discussion | TBD |
| 2 | Allow multiple trials for same email? | Prevent abuse vs. legitimate use cases | @TechLead | 🔴 Open | TBD |
| 3 | SLA for webhook processing? | Stripe retries for 72h, what's our target? | @Backend | 🔴 Open | TBD |
| 4 | Support for promo codes in V1? | Marketing requested, is it in scope? | @Product | ✅ Resolved: V2 | 2026-02-01 |
| 5 | Fallback if Identity Module fails? | Can we create subscription without user data? | @TechLead | 🔴 Open | TBD |
**Status Legend**:
- 🔴 Open - needs decision
- 🟡 In Discussion - actively being discussed
- ✅ Resolved - decision made
```
---
### 19. Roadmap / Timeline (SUGGESTED)
```markdown
## Roadmap / Timeline
| Phase | Deliverables | Duration | Target Date | Status |
| ------------------------ | --------------------------------------------------------------------------------- | -------- | ----------- | -------------- |
| **Phase 0: Setup** | - Stripe credentials<br>- Staging environment<br>- SDK installed | 2 days | 2026-02-05 | ✅ Complete |
| **Phase 1: Persistence** | - Entities created<br>- Repositories implemented<br>- Migrations generated | 3 days | 2026-02-08 | 🟡 In Progress |
| **Phase 2: Services** | - CustomerService<br>- SubscriptionService<br>- Identity integration | 5 days | 2026-02-15 | ⏳ Pending |
| **Phase 3: APIs** | - POST /subscriptions<br>- DELETE /subscriptions/:id<br>- GET /subscriptions | 3 days | 2026-02-18 | ⏳ Pending |
| **Phase 4: Webhooks** | - Webhook endpoint<br>- Signature validation<br>- Event handlers | 4 days | 2026-02-22 | ⏳ Pending |
| **Phase 5: Testing** | - Unit tests (80% coverage)<br>- Integration tests<br>- E2E tests | 5 days | 2026-02-27 | ⏳ Pending |
| **Phase 6: Deploy** | - Documentation<br>- Monitoring setup<br>- Staging deploy<br>- Production rollout | 3 days | 2026-03-02 | ⏳ Pending |
**Total Duration**: ~25 days (5 weeks)
**Milestones**:
- 🎯 M1: MVP ready for staging (2026-02-22)
- 🎯 M2: Production deployment (2026-03-02)
- 🎯 M3: 100% rollout complete (2026-03-09)
**Critical Path**:
Phase 0 → Phase 1 → Phase 2 → Phase 3 → Phase 4 → Phase 5 → Phase 6
```
---
### 20. Approval & Sign-off (SUGGESTED)
```markdown
## Approval & Sign-off
| Role | Name | Status | Date | Comments |
| ------------------------ | ----- | -------------- | ---------- | --------------------------------- |
| Tech Lead | @Name | ✅ Approved | 2026-02-04 | LGTM, proceed with implementation |
| Staff/Principal Engineer | @Name | ⏳ Pending | - | Requested security review first |
| Product Manager | @Name | ✅ Approved | 2026-02-03 | Scope aligned with roadmap |
| Engineering Manager | @Name | ⏳ Pending | - | - |
| Security Team | @Name | 🔴 Not Started | - | Required for payment integration |
| Compliance/Legal | @Name | N/A | - | Not required for this project |
**Approval Criteria**:
- ✅ All mandatory sections complete
- ✅ Security review passed (if applicable)
- ✅ Risks identified and mitigated
- ✅ Timeline realistic and agreed upon
- ⏳ Test strategy approved by QA
- ⏳ Monitoring plan reviewed by SRE
**Next Steps After Approval**:
1. Create Epic in Jira (link in metadata)
2. Break down into User Stories
3. Begin Phase 1 implementation
4. Schedule kickoff meeting with team
```
---
## Validation Rules
### Mandatory Section Checklist
Before finalizing TDD, ensure:
- [ ] **Header**: Tech Lead, Team, Epic link present
- [ ] **Context**: 2+ paragraphs describing background and domain
- [ ] **Problem**: At least 2 specific problems identified with impact
- [ ] **Scope**: Clear in-scope and out-of-scope items (min 3 each)
- [ ] **Technical Solution**: Architecture diagram or description
- [ ] **Technical Solution**: At least 1 API endpoint defined
- [ ] **Risks**: At least 3 risks with impact/probability/mitigation
- [ ] **Implementation Plan**: Broken into phases with estimates
### Critical Section Checklist (by project type)
**If Payment/Auth project**:
- [ ] **Security**: Authentication method defined
- [ ] **Security**: Encryption (at rest, in transit) specified
- [ ] **Security**: PII handling approach documented
- [ ] **Security**: Compliance requirements identified
**If Production system**:
- [ ] **Monitoring**: At least 3 metrics defined with thresholds
- [ ] **Monitoring**: Alerts configured
- [ ] **Rollback**: Rollback triggers defined
- [ ] **Rollback**: Rollback steps documented
**All projects**:
- [ ] **Testing**: At least 2 test types defined (unit, integration, e2e)
- [ ] **Testing**: Critical test scenarios listed
## Output Format
### When Creating TDD
1. **Generate Markdown document**
2. **Validate against checklists above**
3. **Highlight any missing critical sections**
4. **Provide summary to user**:
```
✅ TDD Created: "[Project Name]"
**Sections Included**:
✅ Mandatory (7/7): All present
✅ Critical (3/4): Security, Testing, Monitoring
⚠️ Missing: Rollback Plan (recommended for production)
**Suggested Next Steps**:
- Add Rollback Plan section (critical for production)
- Review Security section with InfoSec team
- Create Epic in Jira and link in metadata
- Schedule TDD review meeting with stakeholders
Would you like me to:
1. Add the missing Rollback Plan section?
2. Publish this TDD to Confluence?
3. Create a Jira Epic for this project?
```
### Confluence Integration
If user wants to publish to Confluence:
```
I'll publish this TDD to Confluence.
Which space should I use?
- Personal space (~557058...)
- Team space (provide space key)
Should I:
- Create a new page
- Update existing page (provide page ID or URL)
```
Then use Confluence Assistant skill to publish.
## Common Anti-Patterns to Avoid
### ❌ Vague Problem Statements
**BAD**:
```
We need to integrate with Stripe.
```
**GOOD**:
```
### Problems We're Solving
- **Manual payment processing takes 2 hours/day**: Currently processing payments manually, costing $500/month in labor
- **Cannot expand internationally**: Current payment processor only supports USD
- **High cart abandonment (45%)**: Poor checkout UX causing revenue loss of $10k/month
```
### ❌ Undefined Scope
**BAD**:
```
Build payment integration with all features.
```
**GOOD**:
```
### ✅ In Scope (V1)
- Trial subscriptions (14 days)
- Single payment method per user
- USD only
- Cancel subscription
### ❌ Out of Scope (V1)
- Multiple payment methods
- Multi-currency
- Promo codes
- Usage-based billing
```
### ❌ Missing Security for Payment Systems
**BAD**:
```
No security section for payment integration.
```
**GOOD**:
```
### Security Considerations (MANDATORY)
**PCI DSS Compliance**:
- Never store full card numbers (use Stripe tokens)
- Never log CVV or full PAN
- Use Stripe Elements for card input (PCI SAQ A)
**Secrets Management**:
- Store `STRIPE_SECRET_KEY` in environment variables
- Rotate keys every 90 days
- Never commit keys to git
```
### ❌ No Rollback Plan
**BAD**:
```
We'll deploy and hope it works.
```
**GOOD**:
```
### Rollback Plan
**Triggers**:
- Error rate > 5% → immediate rollback
- Payment processing failures > 10% → immediate rollback
**Steps**:
1. Disable feature flag `STRIPE_INTEGRATION_ENABLED`
2. Verify old payment processor is active
3. Notify #engineering and #product
4. Schedule post-mortem within 24h
```
## Important Notes
- **Respect user's language** - Automatically detect and generate TDD in the same language as user's request
- **Focus on architecture, not implementation** - Document decisions and contracts, not code
- **High-level examples only** - Show API contracts, data schemas, diagrams (not CLI commands or code snippets)
- **Always validate mandatory sections** - Don't let user skip them
- **For payments/auth** - Security section is MANDATORY
- **For production** - Monitoring and Rollback are MANDATORY
- **Ask clarifying questions** - Don't guess missing information (ask in user's language)
- **Be thorough but pragmatic** - Small projects don't need all 20 sections
- **Update the document** - TDDs should evolve as the project progresses
- **Use industry standards** - Reference Google, Amazon, RFC patterns
- **Think about compliance** - GDPR, PCI DSS, HIPAA where applicable
- **Test for longevity** - If implementation framework changes, TDD should still be valid
## Example Prompts that Trigger This Skill
### English
- "Create a TDD for Stripe integration"
- "I need a technical design document for the new auth system"
- "Write a design doc for the API redesign"
- "Help me document the payment integration architecture"
- "Create a tech spec for migrating to microservices"
### Portuguese
- "Crie um TDD para integração com Stripe"
- "Preciso de um documento de design técnico para o novo sistema de autenticação"
- "Escreva um design doc para o redesign da API"
- "Me ajude a documentar a arquitetura de integração de pagamento"
- "Crie uma especificação técnica para migração para microserviços"
### Spanish
- "Crea un TDD para integración con Stripe"
- "Necesito un documento de diseño técnico para el nuevo sistema de autenticación"
- "Escribe un design doc para el rediseño de la API"
- "Ayúdame a documentar la arquitectura de integración de pagos"
- "Crea una especificación técnica para migración a microservicios"
## References
### Industry Standards
- [Google Engineering Practices](https://google.github.io/eng-practices/)
- [Google SRE Book](https://sre.google/sre-book/table-of-contents/)
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
- [Architecture Decision Records](https://adr.github.io/)
```
```
---
id: generate-tasks
name: Task List Generator
description: |
Generates a detailed, step-by-step task list in Markdown from a PRD or any feature requirements, using a two-phase (parent tasks → sub-tasks) workflow and producing each task in the SYS Manager template (O que fazer, Dependências, Execução, Definition of Done, Sugestão de Esforço, Notas Técnicas).
**Use this skill when:**
- The user says "generate tasks from this PRD", "create a task list", "break this down into tasks"
- The user says "gerar tarefas", "criar lista de tarefas", "decompor o PRD em tasks"
- A PRD (from `create-prd`) or a feature description exists and needs to be decomposed into implementable work items following the SYS Manager template
**This skill is the natural successor to `create-prd`** — the PRD it produces is the canonical input here.
**Do NOT use for:**
- Writing the requirements themselves — use `create-prd`
- Architectural decisions — use `create-adr`
- Change proposals seeking stakeholder alignment — use `create-rfc`
- Implementation design after scope is set — use `create-technical-design-doc`
metadata:
version: '1.0.0'
category: documentation
dependencies: [create-prd]
requires: {}
tags: [tasks, task-list, decomposition, sys-manager, documentation]
---
# Rule: Generating a Task List from a PRD or Feature Requirements
## Goal
Guide an AI assistant in creating a detailed, step-by-step task list in Markdown format, based on a Product Requirements Document (PRD) or a feature description. The task list guides a developer through implementation, and **each task follows the SYS Manager task template**.
## Output
- **Format**: Markdown (`.md`)
- **Location**: `/tasks/`
- **Filename**:
- When generated from a PRD: `tasks-[prd-filename].md` (e.g., `tasks-prd-user-profile-editing.md`)
- When generated from free-form requirements: `tasks-[feature-name].md`
## Process
1. **Receive Input**: The user points to a PRD file, provides a feature description, or references existing documentation.
2. **Analyze Input**: Read and analyze functional requirements, user stories, non-goals, and any other sections of the PRD or requirements document.
3. **Phase 1 — Generate Parent Tasks**: Based on the analysis, create the file and generate the main, high-level tasks required to implement the feature. **IMPORTANT: Always include task `0.0 Create feature branch` as the first parent task, unless the user explicitly requests not to.** Use your judgement on how many additional high-level tasks to use — typically around 5. Present these tasks to the user **without sub-tasks yet**. Inform the user: "I have generated the high-level tasks based on the input. Ready to generate the sub-tasks? Respond with 'Go' to proceed."
4. **Wait for Confirmation**: Pause and wait for the user to respond with "Go".
5. **Phase 2 — Generate Sub-Tasks**: Once confirmed, break each parent task into smaller, actionable sub-tasks. Ensure sub-tasks logically follow from the parent and cover the implementation details implied by the PRD or requirements. **Each sub-task must be written in the SYS Manager task template (see below).**
6. **Identify Relevant Files**: Based on the tasks and input, list potential files to be created or modified under a `Relevant Files` section, including corresponding test files when applicable.
7. **Generate Final Output**: Combine parent tasks, sub-tasks (in the SYS Manager template), relevant files, and notes into the final Markdown structure.
8. **Save Task List**: Save to `/tasks/` with the filename derived in the **Output** section above.
## SYS Manager Task Template
Every sub-task **must** include the following fields. Field names stay in Portuguese to preserve the SYS Manager convention; content can be in the language the user is working in.
```markdown
#### [Sub-task Title]
**O que fazer**
<One-paragraph description of what must be done.>
**Dependências**
<Other tasks, artifacts, or conditions this task depends on. Write "Sem pré-requisitos." if none.>
**Execução**
1. Step 1
2. Step 2
3. ...
**Definition of Done**
- [ ] Criterion 1
- [ ] Criterion 2
- [ ] ...
**Sugestão de Esforço**
<e.g., 2h>
**Notas Técnicas**
<Optional: implementation hints, references, constraints, edge cases. Omit the section if nothing applies.>
```
## Output Format
The generated task list _must_ follow this structure:
````markdown
# Task List: [Feature Name]
## Relevant Files
- `path/to/file1.ts` — Brief description of why this file is relevant (e.g., contains the main component for this feature).
- `path/to/file1.test.ts` — Unit tests for `file1.ts`.
- `path/to/another/file.tsx` — Brief description (e.g., API route handler for data submission).
- `path/to/another/file.test.tsx` — Unit tests for `another/file.tsx`.
- `lib/utils/helpers.ts` — Brief description (e.g., utility functions needed for calculations).
- `lib/utils/helpers.test.ts` — Unit tests for `helpers.ts`.
### Notes
- Unit tests should typically be placed alongside the code files they test (e.g., `MyComponent.tsx` and `MyComponent.test.tsx` in the same directory).
- Use `npx jest [optional/path/to/test/file]` to run tests. Running without a path executes all tests found by the Jest configuration.
## Instructions for Completing Tasks
**IMPORTANT:** As you complete each task, check it off in this markdown file by changing `- [ ]` to `- [x]`. This helps track progress and ensures no steps are skipped.
Example:
- `- [ ] 1.1 Read file` → `- [x] 1.1 Read file` (after completing)
Update the file after completing each sub-task, not only after finishing an entire parent task.
## Tasks
- [ ] 0.0 Create feature branch
- [ ] 0.1 Create and checkout a new branch for this feature
**O que fazer**
Criar uma branch de feature isolada para implementar a funcionalidade sem afetar `main`.
**Dependências**
Sem pré-requisitos.
**Execução**
1. Abrir o terminal na raiz do repositório
2. Rodar `git checkout main && git pull`
3. Rodar `git checkout -b feature/[feature-name]`
**Definition of Done**
- [ ] Branch criada a partir de `main` atualizada
- [ ] Branch ativa no diretório de trabalho
**Sugestão de Esforço**
15min
**Notas Técnicas**
Seguir a convenção de nomenclatura de branches adotada pelo projeto.
- [ ] 1.0 Parent Task Title
- [ ] 1.1 Sub-task title
**O que fazer**
...
**Dependências**
...
**Execução**
1. ...
**Definition of Done**
- [ ] ...
**Sugestão de Esforço**
...
**Notas Técnicas**
...
- [ ] 1.2 Sub-task title
(same structure)
- [ ] 2.0 Parent Task Title
- [ ] 2.1 Sub-task title
...
- [ ] 3.0 Parent Task Title (may not require sub-tasks if purely structural or configuration)
````
## Interaction Model
The process explicitly requires a pause after generating parent tasks to get user confirmation ("Go") before proceeding to generate the detailed sub-tasks. This ensures the high-level plan aligns with user expectations before diving into details.
## Target Audience
Assume the primary reader of the task list is a **junior developer** who will implement the feature. Each SYS Manager field should be explicit, unambiguous, and avoid jargon where possible.
## Next Steps
Once the task list is generated and approved, the developer implements tasks sequentially, checking them off as they go. If during implementation:
- A significant architectural choice emerges → invoke `create-adr` to record it
- A complex implementation plan is needed → invoke `create-technical-design-doc`
- A proposal requiring stakeholder alignment comes up → invoke `create-rfc`
---
id: process-task-list
name: Task List Processor
description: |
Guides an AI assistant through the execution of a Markdown task list (typically produced by `generate-tasks`), enforcing a one-sub-task-at-a-time protocol with user approval between steps, test-gated commits after each parent task, and continuous maintenance of the "Relevant Files" section.
**Use this skill when:**
- The user says "process this task list", "let's work through the tasks", "execute the task list"
- The user says "vamos executar as tasks", "processar a lista de tarefas", "trabalhar na próxima tarefa"
- A task list file (e.g., `tasks/tasks-prd-*.md`) exists and the user wants to start/continue implementing its items sequentially
**This skill is the natural successor to `generate-tasks`.**
**Do NOT use for:**
- Writing the requirements themselves — use `create-prd`
- Generating the task list — use `generate-tasks`
- Recording architectural decisions — use `create-adr`
- Drafting change proposals — use `create-rfc`
metadata:
version: '1.0.0'
category: documentation
dependencies: [generate-tasks]
requires: {}
tags: [task-list, execution, workflow, sys-manager, documentation]
---
# Task List Management
Guidelines for managing task lists in Markdown files to track progress while implementing a PRD-derived feature.
## Task Implementation
- **One sub-task at a time:** Do **NOT** start the next sub-task until you ask the user for permission and they reply with any affirmative in their working language (e.g., `yes`, `y`, `ok`, `sim`, `s`, `vai`, `go`).
- **Completion protocol:**
1. When you finish a **sub-task**, immediately mark it as completed by changing `[ ]` to `[x]`.
2. If the sub-task was written in the **SYS Manager template** (from `generate-tasks`), also tick every satisfied item inside its **Definition of Done** checklist (`- [ ]` → `- [x]`). A sub-task is only complete when its top-level checkbox *and* all its DoD items are `[x]`.
3. If **all** sub-tasks under a parent task are now `[x]`, follow this sequence:
- **First**: Run the full test suite (`pytest`, `npm test`, `bin/rails test`, etc.)
- **Only if all tests pass**: Stage changes (`git add .`)
- **Clean up**: Remove any temporary files and temporary code before committing
- **Commit**: Use a descriptive commit message that:
- Uses conventional commit format (`feat:`, `fix:`, `refactor:`, etc.)
- Summarizes what was accomplished in the parent task
- Lists key changes and additions
- References the task number and the PRD (or ADO work item) context
- **Formats the message as a single-line command using `-m` flags**, e.g.:
```
git commit -m "feat: adds payment validation logic" -m "- Validates card type and expiry" -m "- Adds unit tests for edge cases" -m "Related to T123 in PRD"
```
4. Once all the sub-tasks are marked completed and changes have been committed, mark the **parent task** as completed.
- **Stop after each sub-task and wait for the user's go-ahead.**
## Task List Maintenance
1. **Update the task list as you work:**
- Mark tasks and sub-tasks as completed (`[x]`) per the protocol above.
- Add newly discovered tasks as they emerge (preserving the parent/sub-task numbering scheme).
2. **Maintain the `Relevant Files` section:**
- List every file created or modified.
- Give each file a one-line description of its purpose.
- Add corresponding test files when new code files appear.
## AI Instructions
When working with task lists, the AI must:
1. Regularly update the task list file after finishing any significant work.
2. Follow the completion protocol:
- Mark each finished **sub-task** `[x]`.
- When the sub-task uses the SYS Manager template, tick each satisfied DoD item `[x]` as well.
- Mark the **parent task** `[x]` once **all** its sub-tasks are `[x]`.
3. Add newly discovered tasks.
4. Keep `Relevant Files` accurate and up to date.
5. Before starting work, check which sub-task is next (lowest-numbered unchecked sub-task under the current parent).
6. After implementing a sub-task, update the file and then **pause for user approval** before continuing.
## Interaction Model
The process is deliberately incremental. The pause-after-each-sub-task rule ensures the user can:
- Review the diff before approving the next step
- Catch drift early (e.g., sub-task misunderstood, scope creep)
- Re-plan mid-execution if a blocker or surprise emerges
Do not batch multiple sub-tasks into a single turn, even if they look trivial.
## Next Steps
Once all parent tasks are `[x]` and the final commit is in place:
- If the feature requires stakeholder sign-off → draft an RFC via `create-rfc`
- If an architectural decision was made during implementation → record it via `create-adr`
- If the task list revealed a larger design worth documenting → create a TDD via `create-technical-design-doc`