specifica-br 1.2.2 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +114 -44
  2. package/dist/boilerplate/commands/executar-task.md +133 -0
  3. package/dist/boilerplate/commands/gerar-contexto.md +1462 -0
  4. package/dist/boilerplate/commands/gerar-prd.md +289 -0
  5. package/dist/boilerplate/commands/gerar-tasks.md +168 -0
  6. package/dist/boilerplate/commands/gerar-techspec.md +1467 -0
  7. package/dist/boilerplate/commands/gerar-visao.md +731 -0
  8. package/dist/boilerplate/commands/realizar-codereview.md +288 -0
  9. package/dist/boilerplate/opencode-commands/executar-task.md +55 -48
  10. package/dist/boilerplate/opencode-commands/gerar-contexto.md +1462 -0
  11. package/dist/boilerplate/opencode-commands/gerar-prd.md +232 -40
  12. package/dist/boilerplate/opencode-commands/gerar-tasks.md +112 -31
  13. package/dist/boilerplate/opencode-commands/gerar-techspec.md +1464 -80
  14. package/dist/boilerplate/opencode-commands/gerar-visao.md +731 -0
  15. package/dist/boilerplate/opencode-commands/realizar-codereview.md +288 -0
  16. package/dist/boilerplate/skills/product-manager/SKILL.md +32 -0
  17. package/dist/boilerplate/skills/techspec-generator/SKILL.md +489 -0
  18. package/dist/boilerplate/skills/techspec-generator/references/api-contracts.md +421 -0
  19. package/dist/boilerplate/skills/techspec-generator/references/architecture-patterns.md +316 -0
  20. package/dist/boilerplate/skills/techspec-generator/references/database-modeling.md +436 -0
  21. package/dist/boilerplate/skills/techspec-generator/references/observability-testing.md +436 -0
  22. package/dist/boilerplate/skills/techspec-generator/references/security-hardening.md +238 -0
  23. package/dist/boilerplate/skills/techspec-generator/references/ux-ui-accessibility.md +511 -0
  24. package/dist/boilerplate/specs-templates/architecture-template.md +736 -0
  25. package/dist/boilerplate/specs-templates/codereview-template.md +95 -0
  26. package/dist/boilerplate/specs-templates/prd-template.md +101 -19
  27. package/dist/boilerplate/specs-templates/product_vision-template.md +284 -0
  28. package/dist/boilerplate/specs-templates/task-template.md +64 -18
  29. package/dist/boilerplate/specs-templates/tasks-template.md +12 -4
  30. package/dist/boilerplate/specs-templates/techspec-template.md +1227 -89
  31. package/dist/boilerplate/templates/architecture-template.md +736 -0
  32. package/dist/boilerplate/templates/codereview-template.md +95 -0
  33. package/dist/boilerplate/templates/prd-template.md +167 -0
  34. package/dist/boilerplate/templates/product_vision-template.md +284 -0
  35. package/dist/boilerplate/templates/task-template.md +169 -0
  36. package/dist/boilerplate/templates/tasks-template.md +15 -0
  37. package/dist/boilerplate/templates/techspec-template.md +1306 -0
  38. package/dist/commands/help.js +33 -11
  39. package/dist/commands/init.js +39 -43
  40. package/dist/tools-mapping.json +32 -0
  41. package/dist/types/init.d.ts +14 -17
  42. package/dist/utils/file-service.d.ts +5 -3
  43. package/dist/utils/file-service.js +168 -56
  44. package/dist/utils/message-formatter.d.ts +2 -1
  45. package/dist/utils/message-formatter.js +39 -22
  46. package/package.json +1 -1
@@ -0,0 +1,1306 @@
1
+ # Technical Specification: {{FEATURE_NAME}}
2
+
3
+ **Scope:** Esta especificação cobre APENAS a feature {{FEATURE_NAME}} conforme descrita no PRD.
4
+ Qualquer comportamento fora deste escopo deve ser explicitamente rejeitado.
5
+
6
+ | Metadata | Details |
7
+ | :--- | :--- |
8
+ | **Status** | Draft |
9
+ | **Data** | {{DATA_ATUAL}} |
10
+ | **Referência PRD** | [Link PRD](./prd.md) |
11
+ <!-- Status: DRAFT → IN_PROGRESS → APPROVED -->
12
+
13
+ ---
14
+
15
+ ## 1. Introdução e contexto
16
+
17
+ <!-- INSTRUÇÕES DE PREENCHIMENTO:
18
+ OBJETIVO: Dar visão geral técnica da feature em 1-2 parágrafos
19
+ FORMATO: Texto conciso (máx 150 palavras)
20
+ CONTEÚDO OBRIGATÓRIO:
21
+ - Padrão arquitetural usado (ex: "Clean Architecture com CQRS")
22
+ - Tecnologias principais (ex: "PostgreSQL, RabbitMQ, Redis")
23
+ - Padrões de design aplicados (ex: "Saga pattern", "Repository pattern")
24
+
25
+ EXEMPLO BOM:
26
+ "Esta feature implementará o fluxo de checkout utilizando o padrão Saga para orquestração.
27
+ Usaremos RabbitMQ para processamento assíncrono de pagamentos (conforme padrão em PaymentService).
28
+ O estado do pedido será persistido no PostgreSQL seguindo estrutura estabelecida em OrderEntity."
29
+
30
+ ANTI-PATTERN:
31
+ "Esta feature é para checkout e vai usar banco de dados." (Muito vago, sem tecnologias específicas)
32
+
33
+ REGRA: Citar AGENTS.md ou Features similares quando aplicável
34
+ -->
35
+
36
+ {{INTRODUCTION_CONTENT}}
37
+
38
+ **Objetivo de Negócio:** ...
39
+ **Impacto no Usuário:** ...
40
+ **Non Goals:** ...
41
+ **Pressupostos:** ...
42
+
43
+ ---
44
+
45
+ ## 2. High-Level Architecture [Obrigatório]
46
+
47
+ ### 2.1 Context Diagram
48
+
49
+ <!-- INSTRUÇÕES DE PREENCHIMENTO:
50
+ OBJETIVO: Mostrar componentes envolvidos nesta feature APENAS
51
+ FORMATO: Diagrama Mermaid (graph LR ou TD)
52
+ REGRAS:
53
+ - Refletir APENAS componentes mencionados no PRD
54
+ - Serviços especulativos são PROIBIDOS
55
+ - Prefira menos nós à completude
56
+ - Use rótulos nas arestas para indicar comunicação
57
+
58
+ EXEMPLO BOM:
59
+ graph LR
60
+ User -->|HTTP POST /orders| API
61
+ API -->|Publish OrderCreated| MessageBroker
62
+ PaymentWorker -->|Consume OrderCreated| MessageBroker
63
+ PaymentWorker -->|Update status| Database
64
+
65
+ EXEMPLO RUIM:
66
+ graph LR
67
+ User --> API --> Cache --> MessageBroker --> Worker --> Database --> Analytics
68
+ (Cache e Analytics não estão no PRD - isso é especulação)
69
+
70
+ TIPOS DE NÓS COMUNS:
71
+ - User, Client, Frontend
72
+ - API, Gateway, Controller
73
+ - Service, Worker, Processor
74
+ - Database, Cache, Queue
75
+ - ExternalService, ThirdPartyAPI
76
+ -->
77
+
78
+ :::mermaid
79
+ {{CONTEXT_DIAGRAM_CONTENT}}
80
+ :::
81
+
82
+ <!-- NOTA: Substituir o placeholder acima pelo diagrama real -->
83
+
84
+ ### 2.2 Design de Componentes (Alinhado com a Arquitetura da Aplicação) [Obrigatório]
85
+
86
+ <!-- INSTRUÇÕES DE PREENCHIMENTO:
87
+ OBJETIVO: Listar componentes que serão criados/modificados
88
+ FORMATO: Tabela com colunas obrigatórias
89
+ REGRAS:
90
+ - Todo componente DEVE estar em conformidade com a arquitetura declarada
91
+ - Todo componente DEVE pertencer a exatamente UMA camada arquitetural
92
+ - Nenhum componente PODE violar direção de dependências
93
+
94
+ CAMADAS ARQUITETURAIS COMUNS:
95
+ - Domain: Entidades, Value Objects, Domain Services
96
+ - Application: Use Cases, Commands, Queries, Handlers, DTOs
97
+ - Infrastructure: Repositories, External Services, Adapters
98
+ - Interface: Controllers, Presenters, Gateways
99
+
100
+ TIPOS DE COMPONENTES:
101
+ - Controller, Handler, Service, Repository, Entity, Adapter, Worker
102
+
103
+ EXEMPLO BOM:
104
+ | Nome | Camada | Tipo | Responsabilidade | Dependências Permitidas |
105
+ |:---|:---|:---|:---|:---|
106
+ | CreateOrderHandler | Application | Handler | Processa comando de criação de pedido | IOrderRepository, IEventBus |
107
+ | OrderRepository | Infrastructure | Repository | Persiste e busca ordens no DB | DbContext (Dapper) |
108
+ | Order | Domain | Entity | Entidade de domínio Order | Nenhuma (entidade) |
109
+
110
+ EXEMPLO RUIM:
111
+ | Nome | Camada | Tipo | Descrição |
112
+ |:---|:---|:---|:---|
113
+ | OrderService | Application | Service | Gerencia pedidos |
114
+ (Faltou: responsabilidade específica, dependências)
115
+
116
+ ANTI-PATTERN:
117
+ - Componentes que dependem de camadas "superiores" (Domain dependendo de Application)
118
+ - Misturar responsabilidades (Handler que acessa DB diretamente)
119
+ -->
120
+
121
+ | Nome | Camada | Tipo | Responsabilidade | Dependências (Apenas Permitidas) |
122
+ |:---|:---|:---|:---|:---|
123
+ {{COMPONENT_DESIGN_CONTENT}}
124
+ <!-- ADICIONAR LINHAS CONFORME NECESSÁRIO -->
125
+
126
+ ---
127
+
128
+ ## 3. Design e Persistência de Dados [Se aplicável]
129
+
130
+ ### 3.1 Modelos de dados / Schema [Se aplicável]
131
+
132
+ <!-- INSTRUÇÕES DE PREENCHIMENTO:
133
+ OBJETIVO: Definir estrutura de dados EXATA
134
+ FORMATO: Lista de Entities ou Tables com campos especificados
135
+ REGRAS:
136
+ - Tipos de dados ESPECÍFICOS (VARCHAR(255), não "string")
137
+ - Constraints explícitas (PK, FK, Unique, Not Null)
138
+ - Índices quando aplicável
139
+ - Relacionamentos documentados
140
+
141
+ EXEMPLO BOM:
142
+ Entity: Order
143
+ - id (UUID, PK): Identificador único
144
+ - customer_id (UUID, FK -> User.id, Not Null, Indexed): Cliente
145
+ - total_amount (DECIMAL(10,2), Not Null): Valor total
146
+ - status (VARCHAR(50), Not Null): [PENDING, PAID, FAILED, CANCELLED]
147
+ - created_at (TIMESTAMP, Default: NOW): Data criação
148
+
149
+ Constraints:
150
+ - CHECK (total_amount >= 0)
151
+ - INDEX idx_customer_id ON customer_id
152
+ - INDEX idx_status ON status
153
+
154
+ EXEMPLO RUIM:
155
+ Entity: Order
156
+ - id: int
157
+ - customer: reference to user
158
+ - amount: decimal
159
+ - status: enum
160
+ (Tipos genéricos, sem tamanhos, sem constraints)
161
+
162
+ ANTI-PATTERNS:
163
+ - "string" em vez de "VARCHAR(255)"
164
+ - "number" em vez de "DECIMAL(10,2)"
165
+ - Não especificar nullable/not null
166
+ - Não documentar índices
167
+ -->
168
+
169
+ {{DATA_MODELS_CONTENT}}
170
+ <!-- ADICIONAR ENTITIES/TABLES CONFORME NECESSÁRIO -->
171
+
172
+ ### 3.2 Estratégia de armazenamento [Se aplicável]
173
+
174
+ <!-- INSTRUÇÕES DE PREENCHIMENTO:
175
+ OBJETIVO: Explicar COMO os dados serão armazenados
176
+ FORMATO: Texto curto ou bullet points
177
+ CONTEÚDO:
178
+ - Tipo de banco (relacional, document, key-value)
179
+ - Estratégias de particionamento (se aplicável)
180
+ - Políticas de retenção
181
+ - Backup/restore considerations
182
+
183
+ EXEMPLO BOM:
184
+ "Orders serão armazenados em PostgreSQL (conforme padrão do projeto).
185
+ Dados de auditoria (OrderEvents) serão particionados por mês (partitioning table).
186
+ Retenção: 5 anos em produção, conforme compliance."
187
+
188
+ -->
189
+
190
+ {{STORAGE_STRATEGY_CONTENT}}
191
+
192
+ ### 3.3 Banco de Dados e Infraestrutura [Se aplicável]
193
+
194
+ <!-- INSTRUÇÕES DE PREENCHIMENTO:
195
+ OBJETIVO: Documentar stack de banco e infraestrutura EXATA
196
+ FORMATO: Tabela ou lista estruturada
197
+ CONTEÚDO OBRIGATÓRIO:
198
+ - Tipo de banco de dados (com versão)
199
+ - ORM/Query Builder usado
200
+ - Ferramenta de migrations
201
+ - Serviços de infraestrutura (Docker, mensageria, cache, storage)
202
+ - Padrões de nomenclatura de tabelas/colunas
203
+
204
+ EXEMPLO BOM:
205
+ **Database Stack:**
206
+ - Type: PostgreSQL 15+
207
+ - ORM: Prisma (conforme padrão do projeto)
208
+ - Migrations: Prisma Migrate (/prisma/migrations)
209
+ - Naming: snake_case for tables/columns
210
+ - FK Pattern: {table}_id (user_id, order_id)
211
+ - PK Pattern: UUID with gen_random_uuid()
212
+
213
+ **Infrastructure Stack:**
214
+ - Containerization: Docker Compose (docker-compose.yml)
215
+ - Services: postgres, redis, rabbitmq
216
+ - Messaging: RabbitMQ with amqplib
217
+ - Cache: Redis with ioredis (TTL: 5min default)
218
+ - Storage: S3 with CloudFront CDN
219
+ - CI/CD: GitHub Actions (test, lint, deploy)
220
+
221
+ EXEMPLO RUIM:
222
+ - Banco SQL
223
+ - ORM padrão
224
+ - Docker com alguns serviços
225
+ (Faltam: versões, nomes específicos, tecnologias exatas)
226
+
227
+ ANTI-PATTERNS:
228
+ - "banco de dados relacional" (qual? PostgreSQL? MySQL?)
229
+ - "ORM moderno" (Prisma? TypeORM? Sequelize?)
230
+ - Não especificar versões
231
+ - Não documentar serviços de docker-compose
232
+ -->
233
+
234
+ {{DATABASE_INFRASTRUCTURE_CONTENT}}
235
+
236
+ ---
237
+
238
+ ## 4. Contratos de Integracao (Boundaries) [Obrigatorio]
239
+
240
+ <!-- INSTRUÇÕES DE PREENCHIMENTO GERAL:
241
+ OBJETIVO: Documentar TODOS os contratos entre fronteiras do sistema
242
+ REGRA PRINCIPAL: Toda fronteira que a feature toca DEVE ter seu contrato definido aqui.
243
+ Não importa se o outro lado está no mesmo repositório ou é um serviço de terceiros.
244
+
245
+ CLASSIFICAÇÃO DE ORIGEM (como o contrato foi obtido):
246
+ - DESCOBERTO: LLM encontrou definição existente no código/docs (OpenAPI, proto, migrations, etc.)
247
+ - SOLICITADO: LLM não encontrou, usuário forneceu a definição
248
+ - PROPOSTO: LLM propôs com base no PRD e padrões do projeto
249
+
250
+ CADA contrato DEVE conter:
251
+ - Metadata com ID único (CT-XXX), fronteira, protocolo e origem
252
+ - Schema de entrada completo com tipos
253
+ - Schema de saida completo com tipos
254
+ - Schema de erro com codigos
255
+ - Headers/Metadata quando aplicável
256
+
257
+ ANTI-PATTERNS GERAIS:
258
+ - "Enviar dados para o backend" (qual schema? qual protocolo?)
259
+ - "Salvar no banco" (qual tabela? quais campos? quais tipos?)
260
+ - "Publicar evento" (qual tópico? qual payload? quais headers?)
261
+ - Contrato sem ID de rastreamento (impossível vincular a tasks)
262
+ - Omitir contratos de terceiros (Stripe, SendGrid, etc.)
263
+ -->
264
+
265
+ ### Tabela Resumo de Contratos
266
+
267
+ <!-- INSTRUÇÕES:
268
+ Listar TODOS os contratos da feature com resumo. Preencher conforme cada subseção abaixo.
269
+ -->
270
+
271
+ | ID | Fronteira | Contrato | Protocolo | Origem | Secao Detalhe |
272
+ |:---|:---|:---|:---|:---|:---|
273
+ | CT-001 | Client-Backend | {{CONTRATO_001_NOME}} | {{PROTOCOL}} | {{DESCOBERTO/SOLICITADO/PROPOSTO}} | 4.1 |
274
+ | CT-002 | Backend-Database | {{CONTRATO_002_NOME}} | {{PROTOCOL}} | {{DESCOBERTO/SOLICITADO/PROPOSTO}} | 4.2 |
275
+ <!-- ADICIONAR LINHAS CONFORME NECESSÁRIO -->
276
+
277
+ ---
278
+
279
+ ### 4.1 Contrato Client-Backend [Se aplicavel]
280
+
281
+ <!-- INSTRUÇÕES DE PREENCHIMENTO:
282
+ OBJETIVO: Definir contratos entre clientes (frontend, app, terceiros) e o backend
283
+ APLICABILIDADE: HTTP REST, gRPC, WebSocket, GraphQL, SSE, ou qualquer protocolo de comunicação cliente-servidor
284
+ REGRAS:
285
+ - Metodo/operacao e rota completos
286
+ - Request payload com tipos
287
+ - Response para TODOS os status codes possiveis
288
+ - Error responses formatados
289
+ - Headers obrigatorios (auth, content-type, correlation-id)
290
+ - Politicas de comunicacao cross-origin (CORS) quando aplicavel
291
+
292
+ FORMATO POR ENDPOINT/OPERACAO:
293
+
294
+ #### [CT-XXX] NOME_DO_ENDPOINT
295
+
296
+ | Metadata | Details |
297
+ |:---|:---|
298
+ | **ID** | CT-XXX |
299
+ | **Fronteira** | Client -> Backend |
300
+ | **Protocolo** | [HTTP REST / gRPC / WebSocket / GraphQL / SSE] |
301
+ | **Operacao** | [POST /api/v1/orders] |
302
+ | **Como Obtido** | [DESCOBERTO / SOLICITADO / PROPOSTO] |
303
+ | **Auth** | [Bearer JWT / API Key / None] |
304
+
305
+ Request:
306
+ ```json
307
+ {{REQUEST_SCHEMA}}
308
+ ```
309
+
310
+ Response [STATUS_CODE]:
311
+ ```json
312
+ {{SUCCESS_RESPONSE_SCHEMA}}
313
+ ```
314
+
315
+ Error [STATUS_CODE]:
316
+ ```json
317
+ {{ERROR_RESPONSE_SCHEMA}}
318
+ ```
319
+
320
+ EXEMPLO BOM:
321
+ #### CT-001 Create Order
322
+
323
+ | Metadata | Details |
324
+ |:---|:---|
325
+ | **ID** | CT-001 |
326
+ | **Fronteira** | Client -> Backend |
327
+ | **Protocolo** | HTTP REST |
328
+ | **Operacao** | POST /api/v1/orders |
329
+ | **Como Obtido** | PROPOSTO |
330
+ | **Auth** | Bearer JWT (role: customer, admin) |
331
+
332
+ Headers:
333
+ - Content-Type: application/json
334
+ - Authorization: Bearer {token}
335
+ - X-Correlation-Id: {uuid}
336
+
337
+ Request:
338
+ ```json
339
+ {
340
+ "items": [
341
+ {
342
+ "productId": "uuid-v4",
343
+ "quantity": 1
344
+ }
345
+ ]
346
+ }
347
+ ```
348
+
349
+ Response 201 Created:
350
+ ```json
351
+ {
352
+ "orderId": "uuid-v4",
353
+ "status": "PENDING",
354
+ "totalAmount": 99.99,
355
+ "createdAt": "2024-03-01T10:00:00Z"
356
+ }
357
+ ```
358
+
359
+ Response 400 Bad Request:
360
+ ```json
361
+ {
362
+ "code": "VALIDATION_ERROR",
363
+ "message": "Invalid request payload",
364
+ "details": [
365
+ { "field": "items[0].quantity", "error": "Must be greater than 0" }
366
+ ]
367
+ }
368
+ ```
369
+
370
+ Response 422 Unprocessable Entity:
371
+ ```json
372
+ {
373
+ "code": "INSUFFICIENT_STOCK",
374
+ "message": "Item xyz out of stock",
375
+ "details": {
376
+ "itemId": "xyz",
377
+ "requested": 5,
378
+ "available": 2
379
+ }
380
+ }
381
+ ```
382
+
383
+ Response 500 Internal Server Error:
384
+ ```json
385
+ {
386
+ "code": "INTERNAL_ERROR",
387
+ "message": "Unexpected error occurred",
388
+ "requestId": "correlation-id-here"
389
+ }
390
+ ```
391
+
392
+ EXEMPLO RUIM:
393
+ POST /orders
394
+ Request: { order data }
395
+ Response: { order }
396
+ (Faltam: ID do contrato, versao da API, tipos, status codes, error cases, headers)
397
+
398
+ ANTI-PATTERNS:
399
+ - Nao documentar error cases
400
+ - Nao especificar content-type
401
+ - Status codes genericos (sem 422, 400, 404)
402
+ - Request sem tipos de dados
403
+ - Omitir headers obrigatorios
404
+ - Nao classificar origem (DESCOBERTO/SOLICITADO/PROPOSTO)
405
+ -->
406
+
407
+ {{CLIENT_BACKEND_CONTRACTS}}
408
+ <!-- ADICIONAR ENDPOINTS/OPERACOES CONFORME NECESSARIO -->
409
+
410
+ #### 4.1.1 Politicas de Comunicacao Cross-Origin (CORS) [Se aplicavel]
411
+
412
+ <!-- INSTRUÇÕES DE PREENCHIMENTO:
413
+ OBJETIVO: Definir politicas de CORS quando frontend e backend estao em dominios/ports diferentes
414
+ APLICABILIDADE: Aplicar sempre que a comunicacao Client-Backend for HTTP e houver
415
+ possibilidade de cross-origin (diferentes dominios, subdominios, ports ou protocolos)
416
+ REGRA: Mesmo em monorepo com SSR, pode haver chamadas cross-origin em ambiente de desenvolvimento.
417
+
418
+ FORMATO:
419
+
420
+ | Politica | Valor | Justificativa |
421
+ |:---|:---|:---|
422
+ | **Allowed Origins** | [lista de origens ou *] | [quais dominios podem acessar] |
423
+ | **Allowed Methods** | [GET, POST, PUT, DELETE, PATCH, OPTIONS] | [quais metodos sao permitidos] |
424
+ | **Allowed Headers** | [Content-Type, Authorization, X-Correlation-Id] | [quais headers o cliente pode enviar] |
425
+ | **Exposed Headers** | [X-Request-Id, X-Total-Count] | [quais headers o cliente pode ler] |
426
+ | **Allow Credentials** | [true / false] | [cookies, authorization headers] |
427
+ | **Max Age** | [segundos] | [cache do preflight] |
428
+ | **Como Obtido** | [DESCOBERTO / SOLICITADO / PROPOSTO] | |
429
+
430
+ EXEMPLO BOM:
431
+
432
+ | Politica | Valor | Justificativa |
433
+ |:---|:---|:---|
434
+ | **Allowed Origins** | https://app.example.com, http://localhost:3000 (dev) | Frontend em dominio diferente do backend |
435
+ | **Allowed Methods** | GET, POST, PUT, DELETE, OPTIONS | CRUD completo + preflight |
436
+ | **Allowed Headers** | Content-Type, Authorization, X-Correlation-Id | Headers obrigatorios dos contratos |
437
+ | **Exposed Headers** | X-Request-Id, X-Total-Count | Cliente precisa ler para UI |
438
+ | **Allow Credentials** | true | Autenticacao via cookie/JWT |
439
+ | **Max Age** | 3600 | Preflight cache de 1h |
440
+ | **Como Obtido** | DESCOBERTO (cors.ts com configuracao existente) |
441
+
442
+ EXEMPLO RUIM:
443
+ "CORS configurado"
444
+ (Faltam: origins especificos, metodos, headers, credentials)
445
+
446
+ ANTI-PATTERNS:
447
+ - Allowed Origins: * em producao (risco de seguranca)
448
+ - Nao documentar CORS quando frontend e backend estao separados
449
+ - Omitir Allow Credentials quando usa cookies/auth
450
+ - Nao alinhar Allowed Headers com os headers dos contratos
451
+ -->
452
+
453
+ | Politica | Valor | Justificativa |
454
+ |:---|:---|:---|
455
+ | **Allowed Origins** | {{CORS_ORIGINS}} | {{CORS_ORIGINS_JUSTIFICATION}} |
456
+ | **Allowed Methods** | {{CORS_METHODS}} | {{CORS_METHODS_JUSTIFICATION}} |
457
+ | **Allowed Headers** | {{CORS_HEADERS}} | {{CORS_HEADERS_JUSTIFICATION}} |
458
+ | **Exposed Headers** | {{CORS_EXPOSED_HEADERS}} | {{CORS_EXPOSED_JUSTIFICATION}} |
459
+ | **Allow Credentials** | {{CORS_CREDENTIALS}} | {{CORS_CREDENTIALS_JUSTIFICATION}} |
460
+ | **Max Age** | {{CORS_MAX_AGE}} | {{CORS_MAX_AGE_JUSTIFICATION}} |
461
+ | **Como Obtido** | {{DESCOBERTO/SOLICITADO/PROPOSTO}} | |
462
+
463
+ ---
464
+
465
+ ### 4.2 Contrato Backend-Database [Se aplicavel]
466
+
467
+ <!-- INSTRUÇÕES DE PREENCHIMENTO:
468
+ OBJETIVO: Definir contratos entre o backend e o banco de dados
469
+ APLICABILIDADE: Qualquer mecanismo de persistencia (SQL, NoSQL, ORM, query builder, stored procedures)
470
+ REGRAS:
471
+ - Operacao claramente definida (query, command, procedure)
472
+ - Input: parametros, entidades, filtros
473
+ - Output: result sets, affected rows, generated keys
474
+ - Constraints e erros esperados (violation, timeout, deadlock)
475
+ - Transacoes quando aplicavel
476
+
477
+ FORMATO POR OPERACAO:
478
+
479
+ #### [CT-XXX] NOME_DA_OPERACAO
480
+
481
+ | Metadata | Details |
482
+ |:---|:---|
483
+ | **ID** | CT-XXX |
484
+ | **Fronteira** | Backend -> Database |
485
+ | **Protocolo** | [SQL / NoSQL Query / ORM / Stored Procedure] |
486
+ | **Operacao** | [INSERT / SELECT / UPDATE / DELETE / PROC] |
487
+ | **Como Obtido** | [DESCOBERTO / SOLICITADO / PROPOSTO] |
488
+ | **Tabela/Collection** | [nome] |
489
+
490
+ Input:
491
+ ```json
492
+ {{INPUT_SCHEMA}}
493
+ ```
494
+
495
+ Output:
496
+ ```json
497
+ {{OUTPUT_SCHEMA}}
498
+ ```
499
+
500
+ Erros Esperados:
501
+ - CONSTRAINT_VIOLATION: {{descricao}}
502
+ - TIMEOUT: {{descricao}}
503
+
504
+ EXEMPLO BOM:
505
+ #### CT-005 Insert Order
506
+
507
+ | Metadata | Details |
508
+ |:---|:---|
509
+ | **ID** | CT-005 |
510
+ | **Fronteira** | Backend -> Database |
511
+ | **Protocolo** | SQL (via ORM/Query Builder) |
512
+ | **Operacao** | INSERT |
513
+ | **Como Obtido** | DESCOBERTO (migration 20240301_create_orders.sql) |
514
+ | **Tabela** | orders |
515
+
516
+ Input:
517
+ ```json
518
+ {
519
+ "id": "uuid-v4",
520
+ "customer_id": "uuid-v4",
521
+ "status": "PENDING",
522
+ "total_amount": 99.99,
523
+ "created_at": "2024-03-01T10:00:00Z"
524
+ }
525
+ ```
526
+
527
+ Output:
528
+ ```json
529
+ {
530
+ "affected_rows": 1,
531
+ "generated_keys": ["uuid-v4"]
532
+ }
533
+ ```
534
+
535
+ Erros Esperados:
536
+ - FK_VIOLATION: customer_id nao existe na tabela users
537
+ - CHECK_VIOLATION: total_amount negativo
538
+
539
+ EXEMPLO RUIM:
540
+ "Salvar pedido no banco"
541
+ (Faltam: ID, tabela, campos, tipos, constraints, erros)
542
+
543
+ ANTI-PATTERNS:
544
+ - "Salvar no banco" (qual tabela? quais campos?)
545
+ - Nao documentar constraints e erros esperados
546
+ - Omitir tipo de operacao (INSERT vs UPDATE)
547
+ -->
548
+
549
+ {{BACKEND_DATABASE_CONTRACTS}}
550
+ <!-- ADICIONAR OPERACOES CONFORME NECESSARIO -->
551
+
552
+ ---
553
+
554
+ ### 4.3 Contrato Backend-Message Broker [Se aplicavel]
555
+
556
+ <!-- INSTRUÇÕES DE PREENCHIMENTO:
557
+ OBJETIVO: Definir contratos de mensageria (publicacao e consumo)
558
+ APLICABILIDADE: Kafka, RabbitMQ, SQS, gRPC streaming, ou qualquer mecanismo de mensageria
559
+ REGRAS:
560
+ - Nome do evento (Passado: OrderCreated, PaymentFailed)
561
+ - Source (quem publica) e Target (quem consome)
562
+ - Topic/Queue/Channel
563
+ - Payload com tipos
564
+ - Correlation ID (sempre)
565
+ - Estrategia de error (dead letter, retry)
566
+ - Ordenacao (FIFO, particoes)
567
+
568
+ FORMATO POR EVENTO/MENSAGEM:
569
+
570
+ #### [CT-XXX] NOME_DO_EVENTO (Publish)
571
+
572
+ | Metadata | Details |
573
+ |:---|:---|
574
+ | **ID** | CT-XXX |
575
+ | **Fronteira** | Backend -> Message Broker |
576
+ | **Direcao** | [Publish / Subscribe] |
577
+ | **Topic/Queue** | [nome] |
578
+ | **Como Obtido** | [DESCOBERTO / SOLICITADO / PROPOSTO] |
579
+ | **Source** | [Componente que publica] |
580
+ | **Target** | [Componente que consome] |
581
+
582
+ Payload:
583
+ ```json
584
+ {{EVENT_PAYLOAD}}
585
+ ```
586
+
587
+ Headers/Metadata:
588
+ ```json
589
+ {{EVENT_HEADERS}}
590
+ ```
591
+
592
+ Error Handling:
593
+ - Retry: {{policy}}
594
+ - Dead Letter: {{topic}}
595
+
596
+ EXEMPLO BOM:
597
+ #### CT-010 OrderCreated (Publish)
598
+
599
+ | Metadata | Details |
600
+ |:---|:---|
601
+ | **ID** | CT-010 |
602
+ | **Fronteira** | Backend -> Message Broker |
603
+ | **Direcao** | Publish |
604
+ | **Topic/Queue** | orders.events |
605
+ | **Como Obtido** | PROPOSTO |
606
+ | **Source** | CreateOrderHandler (Application Layer) |
607
+ | **Target** | PaymentWorker, InventoryWorker |
608
+
609
+ Payload:
610
+ ```json
611
+ {
612
+ "eventId": "uuid-v4",
613
+ "eventType": "OrderCreated",
614
+ "timestamp": "2024-03-01T10:00:00Z",
615
+ "data": {
616
+ "orderId": "uuid-v4",
617
+ "customerId": "uuid-v4",
618
+ "totalAmount": 99.99,
619
+ "items": [
620
+ {
621
+ "productId": "uuid-v4",
622
+ "quantity": 1,
623
+ "unitPrice": 99.99
624
+ }
625
+ ]
626
+ },
627
+ "metadata": {
628
+ "correlationId": "uuid-v4",
629
+ "causationId": "uuid-v4"
630
+ }
631
+ }
632
+ ```
633
+
634
+ Error Handling:
635
+ - Retry: 3 tentativas com backoff exponencial (1s, 2s, 4s)
636
+ - Dead Letter: orders.events.dlq
637
+
638
+ EXEMPLO RUIM:
639
+ Event: OrderCreated
640
+ Payload: { order data }
641
+ (Faltam: ID, source, tipos especificos, correlationId, error handling)
642
+
643
+ ANTI-PATTERNS:
644
+ - Eventos sem correlation ID (impossivel tracing)
645
+ - Payloads nao estruturados
646
+ - Nao definir estrategia de retry/dead letter
647
+ - Omitir consumer esperado
648
+ -->
649
+
650
+ {{BACKEND_MESSAGE_BROKER_CONTRACTS}}
651
+ <!-- ADICIONAR EVENTOS/MESSAGES CONFORME NECESSARIO -->
652
+
653
+ ---
654
+
655
+ ### 4.4 Contrato Backend-Cache [Se aplicavel]
656
+
657
+ <!-- INSTRUÇÕES DE PREENCHIMENTO:
658
+ OBJETIVO: Definir contratos de cache (leitura, escrita, invalidacao)
659
+ APLICABILIDADE: Redis, Memcached, cache em memoria, CDN cache, ou qualquer camada de cache
660
+ REGRAS:
661
+ - Key pattern (como a chave e formada)
662
+ - TTL (tempo de vida)
663
+ - Schema do valor cacheado
664
+ - Estrategia de invalidacao
665
+
666
+ FORMATO POR OPERACAO DE CACHE:
667
+
668
+ #### [CT-XXX] NOME_DO_CACHE
669
+
670
+ | Metadata | Details |
671
+ |:---|:---|
672
+ | **ID** | CT-XXX |
673
+ | **Fronteira** | Backend -> Cache |
674
+ | **Operacao** | [Get / Set / Invalidate] |
675
+ | **Key Pattern** | [padrao] |
676
+ | **TTL** | [tempo] |
677
+ | **Como Obtido** | [DESCOBERTO / SOLICITADO / PROPOSTO] |
678
+
679
+ Value Schema:
680
+ ```json
681
+ {{CACHED_VALUE_SCHEMA}}
682
+ ```
683
+
684
+ Invalidacao:
685
+ - Trigger: {{quando invalidar}}
686
+ - Pattern: {{quais chaves}}
687
+
688
+ EXEMPLO BOM:
689
+ #### CT-015 Product Catalog Cache
690
+
691
+ | Metadata | Details |
692
+ |:---|:---|
693
+ | **ID** | CT-015 |
694
+ | **Fronteira** | Backend -> Cache |
695
+ | **Operacao** | Get/Set/Invalidate |
696
+ | **Key Pattern** | product:catalog:{categoryId} |
697
+ | **TTL** | 5 minutos |
698
+ | **Como Obtido** | DESCOBERTO (Redis config em cache.ts) |
699
+
700
+ Value Schema:
701
+ ```json
702
+ {
703
+ "products": [
704
+ {
705
+ "id": "uuid-v4",
706
+ "name": "string",
707
+ "price": 99.99,
708
+ "stock": 10
709
+ }
710
+ ],
711
+ "cachedAt": "2024-03-01T10:00:00Z"
712
+ }
713
+ ```
714
+
715
+ Invalidacao:
716
+ - Trigger: ProductUpdated, ProductDeleted events
717
+ - Pattern: product:catalog:*
718
+
719
+ EXEMPLO RUIM:
720
+ "Usar cache para produtos"
721
+ (Faltam: key pattern, TTL, schema, invalidacao)
722
+
723
+ ANTI-PATTERNS:
724
+ - Cache sem TTL (dados obsoletos indefinidamente)
725
+ - Cache sem estrategia de invalidacao
726
+ - Keys sem padrao documentado
727
+ -->
728
+
729
+ {{BACKEND_CACHE_CONTRACTS}}
730
+ <!-- ADICIONAR ENTRADAS DE CACHE CONFORME NECESSARIO -->
731
+
732
+ ---
733
+
734
+ ### 4.5 Contrato Backend-External Services [Se aplicavel]
735
+
736
+ <!-- INSTRUÇÕES DE PREENCHIMENTO:
737
+ OBJETIVO: Definir contratos com servicos externos (terceiros, outras equipes, APIs publicas)
738
+ APLICABILIDADE: HTTP REST, SOAP, gRPC, SDKs, webhooks, ou qualquer integracao externa
739
+ REGRAS:
740
+ - Servico de terceiros DEVE ter contrato definido (mesmo que não haja doc interna)
741
+ - Distinguir OUTBOUND (backend chama terceiro) de INBOUND (terceiro chama backend/webhook)
742
+ - Autenticacao com terceiro
743
+ - Rate limits, retries, circuit breaker
744
+ - NUNCA documentar valores reais de API keys ou secrets
745
+
746
+ FORMATO POR INTEGRACAO:
747
+
748
+ #### [CT-XXX] NOME_DO_SERVICO - Outbound (Backend -> Terceiro)
749
+
750
+ | Metadata | Details |
751
+ |:---|:---|
752
+ | **ID** | CT-XXX |
753
+ | **Fronteira** | Backend -> [Nome do Servico] |
754
+ | **Direcao** | Outbound |
755
+ | **Protocolo** | [HTTP REST / gRPC / SDK] |
756
+ | **Operacao** | [POST /v1/payment-intents] |
757
+ | **Como Obtido** | [DESCOBERTO / SOLICITADO / PROPOSTO] |
758
+ | **Auth** | [API Key / OAuth / Bearer] |
759
+ | **Rate Limit** | [X req/min] |
760
+ | **Timeout** | [Xs] |
761
+
762
+ Request:
763
+ ```json
764
+ {{OUTBOUND_REQUEST}}
765
+ ```
766
+
767
+ Response Success:
768
+ ```json
769
+ {{OUTBOUND_SUCCESS_RESPONSE}}
770
+ ```
771
+
772
+ Response Error:
773
+ ```json
774
+ {{OUTBOUND_ERROR_RESPONSE}}
775
+ ```
776
+
777
+ Error Handling:
778
+ - Retry: {{policy}}
779
+ - Circuit Breaker: {{config}}
780
+ - Fallback: {{acao alternativa}}
781
+
782
+ #### [CT-XXX] NOME_DO_SERVICO - Inbound (Webhook)
783
+
784
+ | Metadata | Details |
785
+ |:---|:---|
786
+ | **ID** | CT-XXX |
787
+ | **Fronteira** | [Nome do Servico] -> Backend |
788
+ | **Direcao** | Inbound (Webhook) |
789
+ | **Endpoint** | [POST /api/webhooks/servico] |
790
+ | **Como Obtido** | [DESCOBERTO / SOLICITADO / PROPOSTO] |
791
+ | **Verificacao** | [HMAC SHA256 / Signature Header] |
792
+
793
+ Payload:
794
+ ```json
795
+ {{WEBHOOK_PAYLOAD}}
796
+ ```
797
+
798
+ Expected Response:
799
+ ```json
800
+ {{WEBHOOK_ACK}}
801
+ ```
802
+
803
+ EXEMPLO BOM:
804
+ #### CT-020 Stripe Payment Intent - Outbound
805
+
806
+ | Metadata | Details |
807
+ |:---|:---|
808
+ | **ID** | CT-020 |
809
+ | **Fronteira** | Backend -> Stripe API |
810
+ | **Direcao** | Outbound |
811
+ | **Protocolo** | HTTP REST (via SDK) |
812
+ | **Operacao** | POST /v1/payment_intents |
813
+ | **Como Obtido** | SOLICITADO (usuario confirmou) |
814
+ | **Auth** | Stripe Secret Key |
815
+ | **Rate Limit** | 100 req/min |
816
+ | **Timeout** | 10s |
817
+
818
+ Request:
819
+ ```json
820
+ {
821
+ "amount": 9999,
822
+ "currency": "usd",
823
+ "metadata": {
824
+ "orderId": "uuid-v4"
825
+ }
826
+ }
827
+ ```
828
+
829
+ Response 200 OK:
830
+ ```json
831
+ {
832
+ "id": "pi_xxx",
833
+ "status": "requires_payment_method",
834
+ "amount": 9999,
835
+ "currency": "usd"
836
+ }
837
+ ```
838
+
839
+ Error 401:
840
+ ```json
841
+ {
842
+ "error": {
843
+ "type": "authentication_error",
844
+ "message": "Invalid API Key"
845
+ }
846
+ }
847
+ ```
848
+
849
+ Error Handling:
850
+ - Retry: 3 tentativas com backoff exponencial
851
+ - Circuit Breaker: abrir apos 5 falhas consecutivas
852
+ - Fallback: marcar pedido como PAYMENT_PENDING e processar manualmente
853
+
854
+ #### CT-021 Stripe Webhook - Inbound
855
+
856
+ | Metadata | Details |
857
+ |:---|:---|
858
+ | **ID** | CT-021 |
859
+ | **Fronteira** | Stripe -> Backend |
860
+ | **Direcao** | Inbound (Webhook) |
861
+ | **Endpoint** | POST /api/webhooks/stripe |
862
+ | **Como Obtido** | SOLICITADO (usuario confirmou) |
863
+ | **Verificacao** | Stripe-Signature header (HMAC SHA256) |
864
+
865
+ Payload (payment_intent.succeeded):
866
+ ```json
867
+ {
868
+ "type": "payment_intent.succeeded",
869
+ "data": {
870
+ "object": {
871
+ "id": "pi_xxx",
872
+ "status": "succeeded",
873
+ "amount": 9999,
874
+ "metadata": {
875
+ "orderId": "uuid-v4"
876
+ }
877
+ }
878
+ }
879
+ }
880
+ ```
881
+
882
+ Expected Response: 200 OK (empty body)
883
+
884
+ EXEMPLO RUIM:
885
+ "Integrar com Stripe para pagamento"
886
+ (Faltam: endpoint, payload, erros, auth, rate limit, timeout, webhooks)
887
+
888
+ ANTI-PATTERNS:
889
+ - Omitir contrato de servico de terceiro
890
+ - Nao documentar webhooks recebidos
891
+ - Nao definir retry/circuit breaker
892
+ - Documentar valores reais de API keys
893
+ -->
894
+
895
+ {{BACKEND_EXTERNAL_CONTRACTS}}
896
+ <!-- ADICIONAR INTEGRACOES CONFORME NECESSARIO -->
897
+
898
+ ---
899
+
900
+ ### 4.6 Contrato Backend-Storage [Se aplicavel]
901
+
902
+ <!-- INSTRUÇÕES DE PREENCHIMENTO:
903
+ OBJETIVO: Definir contratos de armazenamento de arquivos
904
+ APLICABILIDADE: S3, Blob Storage, filesystem local, CDN, ou qualquer mecanismo de storage
905
+ REGRAS:
906
+ - Tipo de operacao (upload, download, delete)
907
+ - Formatos aceitos, tamanho maximo
908
+ - Path pattern (como o caminho e formado)
909
+ - Controle de acesso (publico, privado, presigned URL)
910
+
911
+ FORMATO POR OPERACAO:
912
+
913
+ #### [CT-XXX] NOME_DA_OPERACAO
914
+
915
+ | Metadata | Details |
916
+ |:---|:---|
917
+ | **ID** | CT-XXX |
918
+ | **Fronteira** | Backend -> Storage |
919
+ | **Operacao** | [Upload / Download / Delete] |
920
+ | **Path Pattern** | [padrao] |
921
+ | **Formatos Aceitos** | [mime types] |
922
+ | **Tamanho Maximo** | [valor] |
923
+ | **Acesso** | [Publico / Privado / Presigned URL] |
924
+ | **Como Obtido** | [DESCOBERTO / SOLICITADO / PROPOSTO] |
925
+
926
+ Input/Output Schema:
927
+ ```json
928
+ {{STORAGE_SCHEMA}}
929
+ ```
930
+
931
+ EXEMPLO BOM:
932
+ #### CT-025 Upload Profile Image
933
+
934
+ | Metadata | Details |
935
+ |:---|:---|
936
+ | **ID** | CT-025 |
937
+ | **Fronteira** | Backend -> S3 Storage |
938
+ | **Operacao** | Upload |
939
+ | **Path Pattern** | /profiles/{userId}/avatar.{ext} |
940
+ | **Formatos Aceitos** | image/jpeg, image/png, image/webp |
941
+ | **Tamanho Maximo** | 2MB |
942
+ | **Acesso** | Presigned URL (expira em 1h) |
943
+ | **Como Obtido** | DESCOBERTO (storage.ts com S3 config) |
944
+
945
+ EXEMPLO RUIM:
946
+ "Fazer upload de imagem"
947
+ (Faltam: path, formatos, tamanho, acesso)
948
+ -->
949
+
950
+ {{BACKEND_STORAGE_CONTRACTS}}
951
+ <!-- ADICIONAR OPERACOES DE STORAGE CONFORME NECESSARIO -->
952
+
953
+ ---
954
+
955
+ ### 4.7 Contrato Backend-Search Engine [Se aplicavel]
956
+
957
+ <!-- INSTRUÇÕES DE PREENCHIMENTO:
958
+ OBJETIVO: Definir contratos com mecanismos de busca
959
+ APLICABILIDADE: Elasticsearch, Meilisearch, Algolia, ou qualquer search engine
960
+ REGRAS:
961
+ - Schema do documento indexado
962
+ - Query parameters aceitos
963
+ - Schema da resposta (paginacao, scoring)
964
+
965
+ FORMATO POR OPERACAO:
966
+
967
+ #### [CT-XXX] NOME_DO_INDICE
968
+
969
+ | Metadata | Details |
970
+ |:---|:---|
971
+ | **ID** | CT-XXX |
972
+ | **Fronteira** | Backend -> Search Engine |
973
+ | **Operacao** | [Index / Search / Delete] |
974
+ | **Indice/Collection** | [nome] |
975
+ | **Como Obtido** | [DESCOBERTO / SOLICITADO / PROPOSTO] |
976
+
977
+ Document/Query Schema:
978
+ ```json
979
+ {{SEARCH_SCHEMA}}
980
+ ```
981
+
982
+ Response Schema:
983
+ ```json
984
+ {{SEARCH_RESPONSE}}
985
+ ```
986
+ -->
987
+
988
+ {{BACKEND_SEARCH_CONTRACTS}}
989
+ <!-- ADICIONAR OPERACOES DE SEARCH CONFORME NECESSARIO -->
990
+
991
+ ---
992
+
993
+ ### 4.8 Contrato Application-Environment [Obrigatorio]
994
+
995
+ <!-- INSTRUÇÕES DE PREENCHIMENTO:
996
+ OBJETIVO: Documentar variaveis de ambiente necessarias para a feature
997
+ APLICABILIDADE: Toda feature que requer nova configuracao de ambiente
998
+ REGRAS:
999
+ - Listar TODAS as variaveis de ambiente que a feature precisa
1000
+ - Classificar: obrigatoria vs opcional
1001
+ - Documentar formato esperado
1002
+ - NUNCA documentar valores reais de secrets
1003
+ - Distinguir Backend, Frontend e Secrets
1004
+
1005
+ FORMATO:
1006
+
1007
+ #### Backend
1008
+
1009
+ | ID | Nome | Tipo | Obrigatoria | Default | Descricao | Exemplo |
1010
+ |:---|:---|:---|:---|:---|:---|:---|
1011
+ | ENV-001 | {{VAR_NAME}} | [string/int/bool/url] | [Sim/Nao] | [valor ou N/A] | {{descricao}} | {{exemplo}} |
1012
+
1013
+ #### Frontend
1014
+
1015
+ | ID | Nome | Tipo | Obrigatoria | Default | Descricao | Exemplo |
1016
+ |:---|:---|:---|:---|:---|:---|:---|
1017
+ | ENV-010 | {{VAR_NAME}} | [string/url] | [Sim/Nao] | [valor ou N/A] | {{descricao}} | {{exemplo}} |
1018
+
1019
+ #### Secrets (referencia SOMENTE, nunca valores)
1020
+
1021
+ | ID | Nome | Formato | Obrigatoria | Descricao |
1022
+ |:---|:---|:---|:---|:---|
1023
+ | SEC-001 | {{SECRET_NAME}} | [min 32 chars / path / etc] | [Sim/Nao] | {{para que serve}} |
1024
+
1025
+ EXEMPLO BOM:
1026
+ #### Backend
1027
+
1028
+ | ID | Nome | Tipo | Obrigatoria | Default | Descricao | Exemplo |
1029
+ |:---|:---|:---|:---|:---|:---|:---|
1030
+ | ENV-001 | ORDERS_MAX_VALUE | int | Nao | 10000 | Valor maximo sem aprovacao manual | 10000 |
1031
+ | ENV-002 | ORDERS_CACHE_TTL | int | Nao | 300 | TTL do cache de pedidos (segundos) | 300 |
1032
+
1033
+ #### Frontend
1034
+
1035
+ | ID | Nome | Tipo | Obrigatoria | Default | Descricao | Exemplo |
1036
+ |:---|:---|:---|:---|:---|:---|:---|
1037
+ | ENV-010 | NEXT_PUBLIC_API_URL | url | Sim | N/A | URL base da API | https://api.example.com |
1038
+
1039
+ #### Secrets
1040
+
1041
+ | ID | Nome | Formato | Obrigatoria | Descricao |
1042
+ |:---|:---|:---|:---|:---|
1043
+ | SEC-001 | STRIPE_SECRET_KEY | sk_live_* (min 32 chars) | Sim | Chave secreta do Stripe |
1044
+ | SEC-002 | JWT_SECRET | min 32 chars | Sim | Secret para assinatura de JWT |
1045
+
1046
+ EXEMPLO RUIM:
1047
+ "Configurar variaveis de ambiente necessarias"
1048
+ (Faltam: nomes, tipos, defaults, exemplos, secrets)
1049
+
1050
+ ANTI-PATTERNS:
1051
+ - Documentar valor real de secrets/API keys
1052
+ - Variavel sem descricao
1053
+ - Nao distinguir backend de frontend
1054
+ - Nao documentar formato esperado de secrets
1055
+ -->
1056
+
1057
+ #### Backend
1058
+
1059
+ | ID | Nome | Tipo | Obrigatoria | Default | Descricao | Exemplo |
1060
+ |:---|:---|:---|:---|:---|:---|:---|
1061
+ {{BACKEND_ENV_VARS}}
1062
+ <!-- ADICIONAR LINHAS CONFORME NECESSARIO -->
1063
+
1064
+ #### Frontend
1065
+
1066
+ | ID | Nome | Tipo | Obrigatoria | Default | Descricao | Exemplo |
1067
+ |:---|:---|:---|:---|:---|:---|:---|
1068
+ {{FRONTEND_ENV_VARS}}
1069
+ <!-- ADICIONAR LINHAS CONFORME NECESSARIO -->
1070
+
1071
+ #### Secrets (referencia SOMENTE, nunca valores)
1072
+
1073
+ | ID | Nome | Formato | Obrigatoria | Descricao |
1074
+ |:---|:---|:---|:---|:---|
1075
+ {{SECRETS_REF}}
1076
+ <!-- ADICIONAR LINHAS CONFORME NECESSARIO -->
1077
+
1078
+ ---
1079
+
1080
+ ## 5. Lógica de negócio e algoritmos principais [Obrigatório]
1081
+
1082
+ ### 5.1 Fluxo principal [Obrigatório]
1083
+
1084
+ <!-- INSTRUÇÕES DE PREENCHIMENTO:
1085
+ OBJETIVO: Descrever passo a passo do "caminho feliz"
1086
+ FORMATO: Lista numerada de passos
1087
+ REGRAS:
1088
+ - Passos observáveis e testáveis
1089
+ - Decisões binárias claras (se X então Y)
1090
+ - Validações explicitadas
1091
+ - Ordem lógica preservada
1092
+
1093
+ EXEMPLO BOM:
1094
+ 1. Receber requisição de criação de pedido.
1095
+ 2. **Validação:** Verificar se todos os produtos existem no catálogo (via ProductService).
1096
+ - *Se algum produto não existir:* Retornar Erro `ProductNotFound`.
1097
+ 3. **Validação:** Verificar disponibilidade de estoque para cada item (via InventoryService).
1098
+ - *Se estoque insuficiente:* Retornar Erro `InsufficientStock`.
1099
+ 4. Calcular valor total do pedido (soma de quantity * unitPrice).
1100
+ 5. **Validação:** Se total > 10.000, exigir aprovação manual.
1101
+ - *Se sem aprovação:* Status = `REVIEW_PENDING`.
1102
+ - *Se aprovado ou total < 10.000:* Status = `PENDING_PAYMENT`.
1103
+ 6. Salvar pedido no banco (via OrderRepository).
1104
+ 7. Publicar evento `OrderCreated` no message broker.
1105
+ 8. Retornar 201 Created com orderId e status.
1106
+
1107
+ EXEMPLO RUIM:
1108
+ 1. Criar pedido
1109
+ 2. Validar
1110
+ 3. Salvar no banco
1111
+ 4. Publicar evento
1112
+ (Passos genéricos, sem decisões, sem validações específicas)
1113
+
1114
+ ANTI-PATTERNS:
1115
+ - "Processar pedido" (muito vago)
1116
+ - "Fazer validações" (quais validações?)
1117
+ - Não documentar tratamentos de erro
1118
+ -->
1119
+
1120
+ {{MAIN_FLOW_CONTENT}}
1121
+
1122
+ ### 5.2 Casos extremos [Obrigatório]
1123
+
1124
+ <!-- INSTRUÇÕES DE PREENCHIMENTO:
1125
+ OBJETIVO: Documentar edge cases e exceções
1126
+ FORMATO: Lista de regras com condições e ações
1127
+ REGRAS:
1128
+ - Regras de negócio específicas
1129
+ - Tratamento de falhas
1130
+ - Retry policies
1131
+ - Timeout strategies
1132
+
1133
+ EXEMPLO BOM:
1134
+ - **Regra de Negócio:** Se valor total > 10.000, status = `REVIEW_PENDING` e requer aprovação manual.
1135
+ - **Concorrência:** Se múltiplas requisições para mesmo produto simultaneamente, usar optimistic locking (version field).
1136
+ - **Retry:** Se PaymentService falhar (5xx), tentar 3 vezes com backoff exponencial (1s, 2s, 4s).
1137
+ - **Timeout:** Se InventoryService não responder em 3s, falhar com `InventoryTimeout` error.
1138
+ - **Data Consistency:** Se pagamento falhar após pedido criado, publicar `OrderFailed` e reverter estoque (compensating transaction).
1139
+
1140
+ EXEMPLO RUIM:
1141
+ - Tratar erros
1142
+ - Tentar novamente se falhar
1143
+ - Validar inputs
1144
+ (Genérico, sem números, sem ações específicas)
1145
+
1146
+ ANTI-PATTERNS:
1147
+ - "Tratar gracefulmente" (o que isso significa?)
1148
+ - "Fazer retry" (quantas vezes? com que backoff?)
1149
+ - Não documentar compensating transactions
1150
+ -->
1151
+
1152
+ {{EDGE_CASES_CONTENT}}
1153
+ <!-- ADICIONAR CASOS EXTREMOS CONFORME NECESSÁRIO -->
1154
+
1155
+ ---
1156
+
1157
+ ## 6. Observability & Operational Readiness [Se aplicável]
1158
+
1159
+ ### 6.1 Logging & Tracing
1160
+
1161
+ <!-- INSTRUÇÕES DE PREENCHIMENTO:
1162
+ OBJETIVO: Definir o que deve ser logado
1163
+ FORMATO: Lista de eventos de log com nível e contexto
1164
+ REGRAS:
1165
+ - Níveis apropriados (ERROR, WARN, INFO, DEBUG)
1166
+ - Contexto relevante (quais dados incluir)
1167
+ - NUNCA logar dados sensíveis (senha, token, cartão)
1168
+ - Sempre incluir correlationId
1169
+
1170
+ EXEMPLO BOM:
1171
+ - **Level:** INFO | **When:** Pedido criado com sucesso | **Context:** orderId, customerId, totalAmount, correlationId
1172
+ - **Level:** ERROR | **When:** Falha no pagamento | **Context:** orderId, errorCode, errorMessage, correlationId (NUNCA logar detalhes do cartão)
1173
+ - **Level:** WARN | **When:** Estoque baixo (< 10 unidades) | **Context:** productId, currentStock, correlationId
1174
+ - **Level:** DEBUG | **When:** Início do processamento | **Context:** orderId, step, correlationId
1175
+
1176
+ EXEMPLO RUIM:
1177
+ - Logar erros
1178
+ - Logar quando pedido for criado
1179
+ (Faltam: nível, contexto, o que especificamente logar)
1180
+
1181
+ ANTI-PATTERNS:
1182
+ - Logar dados sensíveis (password, token, credit card)
1183
+ - Logar sem contexto (qual orderId?)
1184
+ - Usar nivel errado (ERROR para algo esperado)
1185
+ -->
1186
+
1187
+ {{LOGGING_CONTENT}}
1188
+
1189
+ ### 6.2 Métricas (KPIs) [Se aplicável]
1190
+
1191
+ <!-- INSTRUÇÕES DE PREENCHIMENTO:
1192
+ OBJETIVO: Definir métricas a serem emitidas
1193
+ FORMATO: Lista de métricas com tipo e descrição
1194
+ REGRAS:
1195
+ - Tipos: Counter (incrementos), Gauge (valor atual), Histogram (distribuição)
1196
+ - Nomes descritivos
1197
+ - Units quando aplicável
1198
+
1199
+ EXEMPLO BOM:
1200
+ - `orders_created_total` (Counter): Total de pedidos criados
1201
+ - `order_amount_histogram` (Histogram): Distribuição de valores de pedidos (em USD)
1202
+ - `payment_processing_duration_seconds` (Histogram): Tempo de processamento de pagamento
1203
+ - `inventory_check_failures_total` (Counter): Total de falhas em checagem de estoque
1204
+
1205
+ EXEMPLO RUIM:
1206
+ - Métricas de pedidos
1207
+ - Tempo de processamento
1208
+ (Faltam: tipo, nome específico, unidade)
1209
+
1210
+ ANTI-PATTERNS:
1211
+ - Métricas sem tipo
1212
+ - Nomes genéricos ("metrics", "data")
1213
+ - Não especificar unidade (seconds vs milliseconds)
1214
+ -->
1215
+
1216
+ {{METRICS_CONTENT}}
1217
+
1218
+ ---
1219
+
1220
+ ## 7. Segurança & Compliance [Se aplicável]
1221
+
1222
+ <!-- INSTRUÇÕES DE PREENCHIMENTO:
1223
+ OBJETIVO: Documentar requisitos de segurança
1224
+ FORMATO: Lista de requisitos ou tabela
1225
+ REGRAS:
1226
+ - Autenticação/autorização necessária
1227
+ - Dados sensíveis identificados
1228
+ - Criptografia aplicada onde necessário
1229
+ - Input sanitization
1230
+
1231
+ EXEMPLO BOM:
1232
+ - **Authentication:** Endpoints requerem JWT Bearer token com role `customer` ou `admin`.
1233
+ - **Authorization:** DELETE /orders/{id} requer role `admin` ou ser o dono do pedido (customerId == userId).
1234
+ - **Data Privacy:** Campos `cpf` e `creditCardNumber` devem ser criptografados em repouso (AES-256).
1235
+ - **Input Sanitization:** Todos os campos de texto devem ser sanitizados contra XSS e SQL Injection.
1236
+ - **Criticidade:** Alta (envolve dados financeiros).
1237
+ - **Recomendação:** Rate limiting de 10 req/min por IP para criação de pedidos.
1238
+
1239
+ EXEMPLO RUIM:
1240
+ - Requer autenticação
1241
+ - Criptografar dados sensíveis
1242
+ - Sanitizar inputs
1243
+ (Faltam: qual tipo de auth? quais dados? como sanitizar?)
1244
+
1245
+ ANTI-PATTERNS:
1246
+ - "Segurança necessária" (o quê?)
1247
+ - "Criptografar tudo" (o que é criptografável?)
1248
+ - Não especificar roles ou permissions
1249
+ -->
1250
+
1251
+ {{SECURITY_CONTENT}}
1252
+
1253
+ ---
1254
+
1255
+ ## 8. Plano de Implementação [Obrigatório]
1256
+
1257
+ <!-- INSTRUÇÕES DE PREENCHIMENTO:
1258
+ OBJETIVO: Lista de passos técnicos implementáveis
1259
+ FORMATO: Lista numerada de passos específicos
1260
+ REGRAS:
1261
+ - Máximo 10 passos
1262
+ - Cada passo deve ser INDEPENDENTE (pode virar uma task)
1263
+ - Passos devem ser MODULARES (não misturar camadas)
1264
+ - Ordem lógica de execução
1265
+ - Dependências entre passos explícitas
1266
+
1267
+ EXEMPLO BOM:
1268
+ 1. Create migration `20240301_create_orders_table.sql` with schema defined (section 3.1).
1269
+ 2. Create entity `Order.cs` in `/src/Domain/Orders/` following pattern from `User` entity.
1270
+ 3. Create interface `IOrderRepository.cs` in `/src/Infrastructure/Orders/`.
1271
+ 4. Implement `OrderRepository.cs` with Dapper (following pattern from `UserRepository`).
1272
+ 5. Create `CreateOrderCommand.cs` and `CreateOrderHandler.cs` using MediatR pattern (like `CreateUserHandler`).
1273
+ 6. Add FluentValidation validator `CreateOrderCommandValidator.cs`.
1274
+ 7. Create `OrdersController.cs` with POST /api/v1/orders endpoint.
1275
+ 8. Configure Serilog logging for Order flow (INFO on success, ERROR on failure).
1276
+ 9. Write integration tests for `OrderRepository` (following pattern from `UserRepositoryTests`).
1277
+ 10. Write unit tests for `CreateOrderHandler`.
1278
+
1279
+ EXEMPLO RUIM:
1280
+ 1. Criar models e repository
1281
+ 2. Criar endpoint
1282
+ 3. Adicionar validação
1283
+ 4. Escrever testes
1284
+ (Passos genéricos, não modulares, misturam coisas)
1285
+
1286
+ ANTI-PATTERNS:
1287
+ - "Implementar feature X" (muito vago)
1288
+ - Misturar Database + Backend no mesmo passo (viola atomicidade)
1289
+ - Não mencionar arquivos ou caminhos
1290
+ - Passos dependentes não ordenados
1291
+ - Mais de 10 passos (quebrar em sub-passos)
1292
+
1293
+ REGRAS DE ATOMICIDADE:
1294
+ - Cada passo = UMA camada tecnológica
1295
+ - Database (migrations, entities)
1296
+ - Application (commands, handlers, validators)
1297
+ - Infrastructure (repositories, external services)
1298
+ - Interface (controllers, endpoints)
1299
+ - Tests (unit, integration)
1300
+ -->
1301
+
1302
+ {{IMPLEMENTATION_PLAN_CONTENT}}
1303
+
1304
+ ---
1305
+
1306
+ **Template Version:** 0.3.0