@onion-ai/cli 1.0.0-beta.1

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 (220) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +529 -0
  3. package/bin/onion.js +6 -0
  4. package/framework/CLAUDE.md +45 -0
  5. package/framework/VERSION +1 -0
  6. package/framework/agents/compliance/iso-22301-specialist.md +985 -0
  7. package/framework/agents/compliance/iso-27001-specialist.md +713 -0
  8. package/framework/agents/compliance/pmbok-specialist.md +739 -0
  9. package/framework/agents/compliance/security-information-master.md +907 -0
  10. package/framework/agents/compliance/soc2-specialist.md +889 -0
  11. package/framework/agents/deployment/docker-specialist.md +1192 -0
  12. package/framework/agents/development/c4-architecture-specialist.md +745 -0
  13. package/framework/agents/development/c4-documentation-specialist.md +695 -0
  14. package/framework/agents/development/clickup-specialist.md +396 -0
  15. package/framework/agents/development/cursor-specialist.md +277 -0
  16. package/framework/agents/development/docs-reverse-engineer.md +417 -0
  17. package/framework/agents/development/gamma-api-specialist.md +1168 -0
  18. package/framework/agents/development/gitflow-specialist.md +1206 -0
  19. package/framework/agents/development/linux-security-specialist.md +675 -0
  20. package/framework/agents/development/mermaid-specialist.md +515 -0
  21. package/framework/agents/development/nodejs-specialist.md +672 -0
  22. package/framework/agents/development/nx-migration-specialist.md +866 -0
  23. package/framework/agents/development/nx-monorepo-specialist.md +618 -0
  24. package/framework/agents/development/postgres-specialist.md +1123 -0
  25. package/framework/agents/development/react-developer.md +131 -0
  26. package/framework/agents/development/runflow-specialist.md +277 -0
  27. package/framework/agents/development/system-documentation-orchestrator.md +1387 -0
  28. package/framework/agents/development/task-specialist.md +677 -0
  29. package/framework/agents/git/branch-code-reviewer.md +225 -0
  30. package/framework/agents/git/branch-documentation-writer.md +161 -0
  31. package/framework/agents/git/branch-metaspec-checker.md +67 -0
  32. package/framework/agents/git/branch-test-planner.md +176 -0
  33. package/framework/agents/meta/agent-creator-specialist.md +1266 -0
  34. package/framework/agents/meta/command-creator-specialist.md +1676 -0
  35. package/framework/agents/meta/metaspec-gate-keeper.md +240 -0
  36. package/framework/agents/meta/onion.md +824 -0
  37. package/framework/agents/product/branding-positioning-specialist.md +1029 -0
  38. package/framework/agents/product/extract-meeting-specialist.md +394 -0
  39. package/framework/agents/product/meeting-consolidator.md +482 -0
  40. package/framework/agents/product/pain-price-specialist.md +508 -0
  41. package/framework/agents/product/presentation-orchestrator.md +1190 -0
  42. package/framework/agents/product/product-agent.md +201 -0
  43. package/framework/agents/product/story-points-framework-specialist.md +538 -0
  44. package/framework/agents/product/storytelling-business-specialist.md +890 -0
  45. package/framework/agents/research/research-agent.md +292 -0
  46. package/framework/agents/review/code-reviewer.md +154 -0
  47. package/framework/agents/review/corporate-compliance-specialist.md +370 -0
  48. package/framework/agents/testing/test-agent.md +424 -0
  49. package/framework/agents/testing/test-engineer.md +294 -0
  50. package/framework/agents/testing/test-planner.md +117 -0
  51. package/framework/commands/common/prompts/README.md +208 -0
  52. package/framework/commands/common/prompts/clickup-patterns.md +144 -0
  53. package/framework/commands/common/prompts/code-review-checklist.md +168 -0
  54. package/framework/commands/common/prompts/git-workflow-patterns.md +235 -0
  55. package/framework/commands/common/prompts/output-formats.md +240 -0
  56. package/framework/commands/common/prompts/technical.md +194 -0
  57. package/framework/commands/common/templates/abstraction-template.md +399 -0
  58. package/framework/commands/common/templates/agent-template.md +353 -0
  59. package/framework/commands/common/templates/business_context_template.md +748 -0
  60. package/framework/commands/common/templates/command-template.md +273 -0
  61. package/framework/commands/common/templates/technical_context_template.md +526 -0
  62. package/framework/commands/design/screen-spec.md +505 -0
  63. package/framework/commands/development/runflow-dev.md +465 -0
  64. package/framework/commands/docs/build-business-docs.md +299 -0
  65. package/framework/commands/docs/build-compliance-docs.md +143 -0
  66. package/framework/commands/docs/build-index.md +119 -0
  67. package/framework/commands/docs/build-tech-docs.md +221 -0
  68. package/framework/commands/docs/docs-health.md +141 -0
  69. package/framework/commands/docs/help.md +278 -0
  70. package/framework/commands/docs/refine-vision.md +25 -0
  71. package/framework/commands/docs/reverse-consolidate.md +158 -0
  72. package/framework/commands/docs/sync-sessions.md +354 -0
  73. package/framework/commands/docs/validate-docs.md +157 -0
  74. package/framework/commands/engineer/bump.md +29 -0
  75. package/framework/commands/engineer/docs.md +11 -0
  76. package/framework/commands/engineer/hotfix.md +183 -0
  77. package/framework/commands/engineer/plan.md +85 -0
  78. package/framework/commands/engineer/pr-update.md +219 -0
  79. package/framework/commands/engineer/pr.md +117 -0
  80. package/framework/commands/engineer/pre-pr.md +81 -0
  81. package/framework/commands/engineer/start.md +254 -0
  82. package/framework/commands/engineer/validate-phase-sync.md +134 -0
  83. package/framework/commands/engineer/warm-up.md +20 -0
  84. package/framework/commands/engineer/work.md +155 -0
  85. package/framework/commands/f/company-context-extractor.md +93 -0
  86. package/framework/commands/f/process-meetings.md +103 -0
  87. package/framework/commands/git/README.md +682 -0
  88. package/framework/commands/git/code-review.md +213 -0
  89. package/framework/commands/git/fast-commit.md +43 -0
  90. package/framework/commands/git/feature/finish.md +88 -0
  91. package/framework/commands/git/feature/publish.md +89 -0
  92. package/framework/commands/git/feature/start.md +172 -0
  93. package/framework/commands/git/help.md +100 -0
  94. package/framework/commands/git/hotfix/finish.md +96 -0
  95. package/framework/commands/git/hotfix/start.md +92 -0
  96. package/framework/commands/git/init.md +111 -0
  97. package/framework/commands/git/release/finish.md +96 -0
  98. package/framework/commands/git/release/start.md +93 -0
  99. package/framework/commands/git/sync.md +199 -0
  100. package/framework/commands/meta/all-tools.md +58 -0
  101. package/framework/commands/meta/analyze-complex-problem.md +186 -0
  102. package/framework/commands/meta/create-abstraction.md +882 -0
  103. package/framework/commands/meta/create-agent-express.md +98 -0
  104. package/framework/commands/meta/create-agent.md +210 -0
  105. package/framework/commands/meta/create-command.md +203 -0
  106. package/framework/commands/meta/create-knowledge-base.md +143 -0
  107. package/framework/commands/meta/create-task-structure.md +150 -0
  108. package/framework/commands/meta/setup-integration.md +274 -0
  109. package/framework/commands/onion.md +169 -0
  110. package/framework/commands/product/README.md +249 -0
  111. package/framework/commands/product/analyze-pain-price.md +694 -0
  112. package/framework/commands/product/branding.md +458 -0
  113. package/framework/commands/product/check.md +46 -0
  114. package/framework/commands/product/checklist-sync.md +239 -0
  115. package/framework/commands/product/collect.md +95 -0
  116. package/framework/commands/product/consolidate-meetings.md +291 -0
  117. package/framework/commands/product/estimate.md +511 -0
  118. package/framework/commands/product/extract-meeting.md +226 -0
  119. package/framework/commands/product/feature.md +416 -0
  120. package/framework/commands/product/light-arch.md +82 -0
  121. package/framework/commands/product/presentation.md +174 -0
  122. package/framework/commands/product/refine.md +161 -0
  123. package/framework/commands/product/spec.md +79 -0
  124. package/framework/commands/product/task-check.md +378 -0
  125. package/framework/commands/product/task.md +603 -0
  126. package/framework/commands/product/validate-task.md +325 -0
  127. package/framework/commands/product/warm-up.md +24 -0
  128. package/framework/commands/quick/analisys.md +17 -0
  129. package/framework/commands/test/e2e.md +377 -0
  130. package/framework/commands/test/integration.md +508 -0
  131. package/framework/commands/test/unit.md +381 -0
  132. package/framework/commands/validate/collab/pair-testing.md +657 -0
  133. package/framework/commands/validate/collab/three-amigos.md +534 -0
  134. package/framework/commands/validate/qa-points/estimate.md +660 -0
  135. package/framework/commands/validate/test-strategy/analyze.md +1201 -0
  136. package/framework/commands/validate/test-strategy/create.md +411 -0
  137. package/framework/commands/validate/workflow.md +370 -0
  138. package/framework/commands/warm-up.md +20 -0
  139. package/framework/docs/architecture/acoplamento-clickup-problema-analise.md +468 -0
  140. package/framework/docs/architecture/desacoplamento-roadmap.md +364 -0
  141. package/framework/docs/architecture/validacao-fase-1.md +235 -0
  142. package/framework/docs/c4/c4-detection-rules.md +395 -0
  143. package/framework/docs/c4/c4-documentation-templates.md +579 -0
  144. package/framework/docs/c4/c4-mermaid-patterns.md +331 -0
  145. package/framework/docs/c4/c4-templates.md +256 -0
  146. package/framework/docs/clickup/clickup-acceptance-criteria-strategy.md +329 -0
  147. package/framework/docs/clickup/clickup-auto-update-strategy.md +340 -0
  148. package/framework/docs/clickup/clickup-comment-formatter.md +239 -0
  149. package/framework/docs/clickup/clickup-description-fix.md +384 -0
  150. package/framework/docs/clickup/clickup-dual-comment-strategy.md +528 -0
  151. package/framework/docs/clickup/clickup-formatting.md +302 -0
  152. package/framework/docs/clickup/separador-tamanho-otimizado.md +258 -0
  153. package/framework/docs/engineer/pre-pr-acceptance-validation.md +256 -0
  154. package/framework/docs/onion/ESPERANTO.md +293 -0
  155. package/framework/docs/onion/agents-reference.md +832 -0
  156. package/framework/docs/onion/clickup-integration.md +780 -0
  157. package/framework/docs/onion/commands-guide.md +924 -0
  158. package/framework/docs/onion/engineering-flows.md +900 -0
  159. package/framework/docs/onion/getting-started.md +803 -0
  160. package/framework/docs/onion/maintenance-checklist.md +421 -0
  161. package/framework/docs/onion/naming-conventions.md +286 -0
  162. package/framework/docs/onion/practical-examples.md +854 -0
  163. package/framework/docs/product/story-points-integration.md +269 -0
  164. package/framework/docs/product/story-points-validation.md +237 -0
  165. package/framework/docs/reviews/task-manager-docs-review-2025-11-24.md +184 -0
  166. package/framework/docs/strategies/clickup-comment-patterns.md +766 -0
  167. package/framework/docs/strategies/clickup-integration-tests.md +602 -0
  168. package/framework/docs/strategies/clickup-mcp-wrappers-tests.md +888 -0
  169. package/framework/docs/strategies/clickup-regression-tests.md +587 -0
  170. package/framework/docs/strategies/visual-patterns.md +315 -0
  171. package/framework/docs/templates/README.md +649 -0
  172. package/framework/docs/templates/adr-template.md +226 -0
  173. package/framework/docs/templates/analysis-template.md +280 -0
  174. package/framework/docs/templates/execution-plan-template.md +430 -0
  175. package/framework/docs/templates/guide-template.md +367 -0
  176. package/framework/docs/templates/phase-execution-prompt-template.md +504 -0
  177. package/framework/docs/templates/reference-template.md +522 -0
  178. package/framework/docs/templates/solution-template.md +390 -0
  179. package/framework/docs/tools/README.md +356 -0
  180. package/framework/docs/tools/agents.md +365 -0
  181. package/framework/docs/tools/commands.md +669 -0
  182. package/framework/docs/tools/cursor.md +539 -0
  183. package/framework/docs/tools/mcps.md +937 -0
  184. package/framework/docs/tools/rules.md +461 -0
  185. package/framework/rules/language-and-documentation.mdc +371 -0
  186. package/framework/rules/nestjs-controllers.md +83 -0
  187. package/framework/rules/nestjs-dtos.md +255 -0
  188. package/framework/rules/nestjs-modules.md +141 -0
  189. package/framework/rules/nestjs-services.md +230 -0
  190. package/framework/rules/nx-rules.mdc +41 -0
  191. package/framework/rules/onion-patterns.mdc +197 -0
  192. package/framework/skills/codebase-visualizer/SKILL.md +26 -0
  193. package/framework/skills/codebase-visualizer/scripts/visualize.py +131 -0
  194. package/framework/skills/collect/SKILL.md +84 -0
  195. package/framework/skills/create-rule/SKILL.md +152 -0
  196. package/framework/skills/db-schema-visualizer/SKILL.md +49 -0
  197. package/framework/skills/db-schema-visualizer/scripts/visualize.py +1191 -0
  198. package/framework/skills/sync-meetings/SKILL.md +239 -0
  199. package/framework/utils/clickup-mcp-wrappers.md +744 -0
  200. package/framework/utils/date-time-standards.md +200 -0
  201. package/framework/utils/task-manager/README.md +94 -0
  202. package/framework/utils/task-manager/adapters/asana.md +377 -0
  203. package/framework/utils/task-manager/adapters/clickup.md +467 -0
  204. package/framework/utils/task-manager/adapters/linear.md +421 -0
  205. package/framework/utils/task-manager/detector.md +299 -0
  206. package/framework/utils/task-manager/factory.md +363 -0
  207. package/framework/utils/task-manager/interface.md +248 -0
  208. package/framework/utils/task-manager/types.md +409 -0
  209. package/package.json +41 -0
  210. package/src/cli.js +73 -0
  211. package/src/commands/doctor.js +191 -0
  212. package/src/commands/init.js +287 -0
  213. package/src/commands/install.js +261 -0
  214. package/src/commands/list.js +152 -0
  215. package/src/commands/uninstall.js +90 -0
  216. package/src/commands/update.js +26 -0
  217. package/src/utils/fs.js +89 -0
  218. package/src/utils/log.js +35 -0
  219. package/src/utils/paths.js +32 -0
  220. package/src/utils/prompt.js +76 -0
@@ -0,0 +1,508 @@
1
+ ---
2
+ name: integration
3
+ description: |
4
+ Gera e executa testes de integração automaticamente com detecção de framework.
5
+ Use para criar testes de integração (Grey-box) seguindo padrões do projeto, incluindo API contract testing, boundary testing e fuzzing.
6
+ model: sonnet
7
+
8
+ parameters:
9
+ - name: api-endpoint
10
+ description: Endpoint da API ou serviço para testar (ex: "/api/users", "UserService")
11
+ required: true
12
+ - name: --generate
13
+ description: Gera arquivo de teste se não existir
14
+ required: false
15
+ - name: --run
16
+ description: Executa os testes após gerar/validar
17
+ required: false
18
+ - name: --contract
19
+ description: Foca em contract testing (valida schemas e contratos)
20
+ required: false
21
+ - name: --boundary
22
+ description: Foca em boundary testing (timeouts, erros, limites)
23
+ required: false
24
+ - name: --fuzz
25
+ description: Inclui fuzzing de API (testes com dados malformados)
26
+ required: false
27
+ - name: --framework
28
+ description: Framework específico (sobrescreve auto-detecção: supertest|pact|postman|wiremock|jest|vitest)
29
+ required: false
30
+ - name: --mock-external
31
+ description: Mocka serviços externos (default: true para testes isolados)
32
+ required: false
33
+
34
+ category: test
35
+ tags:
36
+ - testing
37
+ - integration-tests
38
+ - grey-box-testing
39
+ - api-testing
40
+ - contract-testing
41
+ - test-generation
42
+ - automation
43
+
44
+ version: "3.0.0"
45
+ updated: "2025-12-03"
46
+
47
+ related_commands:
48
+ - /test/unit
49
+ - /test/e2e
50
+ - /validate/test-strategy/create
51
+ - /engineer/work
52
+
53
+ related_agents:
54
+ - test-engineer
55
+ - test-planner
56
+ - test-agent
57
+ ---
58
+
59
+ # 🔗 Test Integration
60
+
61
+ Gera e executa testes de integração automaticamente com detecção inteligente de framework, foco em Grey-box testing (API contract testing, boundary testing, fuzzing) seguindo o Framework de Testes.
62
+
63
+ ## 🎯 Objetivo
64
+
65
+ Automatizar o ciclo completo de testes de integração (Grey-box perspective):
66
+ - **Auto-detecção** de framework de integração (Supertest, Pact, Postman, Wiremock)
67
+ - **Análise de API/service** para identificar endpoints e contratos
68
+ - **Geração automática** de testes de integração seguindo padrões do projeto
69
+ - **Suporte a contract testing** (validação de schemas e contratos)
70
+ - **Suporte a boundary testing** (timeouts, erros, limites)
71
+ - **Suporte a fuzzing** (dados malformados e edge cases)
72
+ - **Execução inteligente** com mocks de serviços externos
73
+
74
+ ## ⚡ Fluxo de Execução
75
+
76
+ ### Passo 1: Validar Endpoint/Service
77
+
78
+ ```bash
79
+ # Validar formato
80
+ if [[ -z "{{api-endpoint}}" ]]; then
81
+ echo "❌ ERRO: Endpoint ou serviço é obrigatório"
82
+ exit 1
83
+ fi
84
+ ```
85
+
86
+ **Validações:**
87
+ ```markdown
88
+ SE api-endpoint vazio:
89
+ ❌ ERRO: Endpoint ou serviço é obrigatório
90
+ 💡 Exemplos: "/api/users", "UserService", "payment-gateway"
91
+
92
+ SE formato inválido:
93
+ ⚠️ AVISO: Endpoint deve ser caminho de API ou nome de serviço
94
+ ```
95
+
96
+ ### Passo 2: Detectar Framework de Integração
97
+
98
+ **Estratégia de Detecção (em ordem de prioridade):**
99
+
100
+ 1. **Verificar configurações:**
101
+ - `pact.config.{js,ts}` → Pact detectado
102
+ - `postman.json` ou `postman/` → Postman detectado
103
+ - `wiremock/` ou `mocks/` → Wiremock detectado
104
+ - `package.json` → `supertest`, `@pact-foundation/pact`, `postman`, `wiremock` em dependencies
105
+ - `jest.config.{js,ts}` ou `vitest.config.{js,ts}` → Jest/Vitest com Supertest
106
+
107
+ 2. **Buscar arquivos de teste existentes:**
108
+ - `**/*.integration.{js,ts}`
109
+ - `**/integration/**/*.spec.{js,ts}`
110
+ - `**/tests/integration/**/*.{js,ts}`
111
+ - `**/contracts/**/*.{js,ts}` (Pact)
112
+ - `**/pacts/**/*.json` (Pact)
113
+
114
+ 3. **Inferir por estrutura:**
115
+ - Diretório `contracts/` ou `pacts/` → Pact
116
+ - Diretório `mocks/` ou `wiremock/` → Wiremock
117
+ - Arquivos `*.postman_collection.json` → Postman
118
+ - Uso de `supertest` em testes → Supertest
119
+
120
+ **Output:**
121
+ ```markdown
122
+ ✅ Framework detectado: [supertest|pact|postman|wiremock|jest|vitest]
123
+ 📁 Config: [caminho do arquivo de config]
124
+ 🔧 Test runner: [jest|vitest|mocha]
125
+ 🌐 Mock strategy: [wiremock|nock|msw]
126
+ ```
127
+
128
+ **Se `--framework` fornecido:** Sobrescreve detecção automática
129
+
130
+ ### Passo 3: Analisar API/Service
131
+
132
+ **Objetivo:** Identificar endpoints, contratos e dependências externas.
133
+
134
+ #### 3.1 Detectar Tipo de Endpoint
135
+
136
+ **Buscar no código:**
137
+ - Rotas de API: `app.get()`, `router.post()`, `@Get()`, `@Post()`
138
+ - Serviços: Classes com métodos públicos, interfaces
139
+ - GraphQL: `schema.graphql`, resolvers
140
+
141
+ #### 3.2 Extrair Contratos
142
+
143
+ **Buscar schemas e contratos:**
144
+ - OpenAPI/Swagger: `openapi.yaml`, `swagger.json`
145
+ - JSON Schema: `schema.json`, `*.schema.json`
146
+ - Pact contracts: `pacts/*.json`
147
+ - TypeScript types/interfaces
148
+ - GraphQL schema
149
+
150
+ #### 3.3 Identificar Dependências Externas
151
+
152
+ - APIs externas (HTTP calls)
153
+ - Serviços de terceiros
154
+ - Bancos de dados
155
+ - Message queues
156
+ - Cache services
157
+
158
+ **Output da Análise:**
159
+ ```markdown
160
+ 📊 Análise de API/Service:
161
+ ∟ Tipo: [REST API|GraphQL|Service|Microservice]
162
+ ∟ Endpoints encontrados: [N]
163
+ ∟ Contratos encontrados: [Sim/Não]
164
+ ∟ Dependências externas: [lista]
165
+ ∟ Mock strategy: [wiremock|nock|msw|manual]
166
+ ```
167
+
168
+ ### Passo 4: Verificar Arquivo de Teste Existente
169
+
170
+ **Padrões de nomenclatura:**
171
+ - **Supertest:** `{{endpoint}}.integration.test.{js,ts}`
172
+ - **Pact:** `{{consumer}}-{{provider}}.spec.{js,ts}` ou `contracts/{{name}}.spec.{js,ts}`
173
+ - **Postman:** `{{collection}}.postman_collection.json`
174
+ - **Jest/Vitest:** `{{endpoint}}.integration.{js,ts}` ou `integration/{{endpoint}}.spec.{js,ts}`
175
+
176
+ **Decisão:**
177
+ ```markdown
178
+ SE arquivo existe:
179
+ ✅ Encontrado: [caminho]
180
+ SE --generate: ⚠️ Pula geração, continua execução
181
+ SENÃO: Continua execução
182
+
183
+ SE não existe:
184
+ SE --generate: → Gerar (Passo 5)
185
+ SENÃO: ❌ ERRO: Use --generate para criar
186
+ ```
187
+
188
+ ### Passo 5: Gerar Arquivo de Teste (SE --generate)
189
+
190
+ **Estratégia:**
191
+ 1. **Ler padrões existentes:** Buscar `**/*.integration.{js,ts}`, `**/contracts/**/*.{js,ts}` para extrair estrutura
192
+ 2. **Gerar testes base:** Padrão AAA (Arrange, Act, Assert) para cada endpoint:
193
+ - **Contract tests:** Validação de schema, tipos, estruturas
194
+ - **Boundary tests:** Timeouts, erros, limites, edge cases
195
+ - **Fuzzing tests:** Dados malformados, tipos incorretos, valores extremos
196
+ 3. **Configurar mocks:** Para dependências externas (Wiremock, Nock, MSW)
197
+ 4. **Criar arquivo:** `write {{test-file-path}}`
198
+
199
+ **Exemplo estrutura (Supertest + Jest):**
200
+ ```typescript
201
+ import request from 'supertest';
202
+ import app from '../src/app';
203
+
204
+ describe('API Integration: {{api-endpoint}}', () => {
205
+ beforeEach(() => {
206
+ // Setup mocks para serviços externos
207
+ });
208
+
209
+ describe('Contract Testing', () => {
210
+ test('should return valid schema for GET /api/users', async () => {
211
+ const response = await request(app)
212
+ .get('/api/users')
213
+ .expect(200);
214
+
215
+ expect(response.body).toMatchSchema({
216
+ users: expect.arrayContaining([
217
+ expect.objectContaining({
218
+ id: expect.any(String),
219
+ name: expect.any(String),
220
+ email: expect.any(String)
221
+ })
222
+ ])
223
+ });
224
+ });
225
+ });
226
+
227
+ describe('Boundary Testing', () => {
228
+ test('should handle timeout from external service', async () => {
229
+ // Mock timeout
230
+ mockExternalService.timeout();
231
+
232
+ const response = await request(app)
233
+ .get('/api/users')
234
+ .expect(500);
235
+
236
+ expect(response.body.error).toBe('Service timeout');
237
+ });
238
+
239
+ test('should handle invalid response from external service', async () => {
240
+ mockExternalService.returnsInvalidData();
241
+
242
+ const response = await request(app)
243
+ .get('/api/users')
244
+ .expect(500);
245
+ });
246
+ });
247
+
248
+ describe('Fuzzing Tests', () => {
249
+ test('should handle malformed JSON gracefully', async () => {
250
+ const malformedInputs = [
251
+ '{"name": incomplete',
252
+ '{"name": null, "email": ""}',
253
+ '{"name": "' + 'x'.repeat(10000) + '"}',
254
+ ];
255
+
256
+ for (const input of malformedInputs) {
257
+ const response = await request(app)
258
+ .post('/api/users')
259
+ .send(input)
260
+ .expect(400);
261
+
262
+ expect(response.body.error).toBeDefined();
263
+ }
264
+ });
265
+ });
266
+ });
267
+ ```
268
+
269
+ **Exemplo estrutura (Pact):**
270
+ ```typescript
271
+ import { Pact } from '@pact-foundation/pact';
272
+
273
+ describe('Pact Contract: UserService', () => {
274
+ const provider = new Pact({
275
+ consumer: 'Frontend',
276
+ provider: 'UserService',
277
+ });
278
+
279
+ beforeAll(() => provider.setup());
280
+ afterAll(() => provider.finalize());
281
+
282
+ test('should return user list', async () => {
283
+ await provider.addInteraction({
284
+ state: 'users exist',
285
+ uponReceiving: 'a request for users',
286
+ withRequest: {
287
+ method: 'GET',
288
+ path: '/api/users',
289
+ },
290
+ willRespondWith: {
291
+ status: 200,
292
+ body: {
293
+ users: Matchers.arrayContaining([
294
+ Matchers.like({
295
+ id: Matchers.string('123'),
296
+ name: Matchers.string('John'),
297
+ }),
298
+ ]),
299
+ },
300
+ },
301
+ });
302
+
303
+ // Execute test
304
+ const response = await fetch('/api/users');
305
+ expect(response.status).toBe(200);
306
+ });
307
+ });
308
+ ```
309
+
310
+ **Validação:** ✅ Arquivo gerado: {{test-file-path}}, [N] testes (contract: X, boundary: Y, fuzzing: Z)
311
+
312
+ ### Passo 6: Executar Testes (SE --run)
313
+
314
+ **Comandos por framework:**
315
+
316
+ - **Supertest + Jest:** `npx jest {{test-file}} [--coverage]` ou `pnpm jest`
317
+ - **Supertest + Vitest:** `npx vitest [run] {{test-file}}` ou `pnpm vitest`
318
+ - **Pact:** `npx pact-provider-verifier` ou `pnpm pact:verify`
319
+ - **Postman:** `npx newman run {{collection}}.json` ou `pnpm postman:test`
320
+ - **Wiremock:** `java -jar wiremock.jar --port 8080` (setup) + testes
321
+
322
+ **Construir comando:** Base + flags específicas + execução
323
+
324
+ **Executar:** `run_terminal_cmd [comando]` e capturar: resultados (pass/fail), contratos validados, erros, tempo
325
+
326
+ ### Passo 7: Apresentar Resultados
327
+
328
+ ## 📤 Output Esperado
329
+
330
+ ```
331
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
332
+ ✅ TESTES DE INTEGRAÇÃO - {{api-endpoint}}
333
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
334
+
335
+ 🔍 Detecção:
336
+ ∟ Framework: [supertest|pact|postman|wiremock|jest|vitest]
337
+ ∟ Config: [caminho do arquivo de config]
338
+ ∟ Test runner: [jest|vitest|mocha]
339
+ ∟ Mock strategy: [wiremock|nock|msw|manual]
340
+
341
+ 📊 Análise de API/Service:
342
+ ∟ Endpoint/Service: {{api-endpoint}}
343
+ ∟ Tipo: [REST API|GraphQL|Service|Microservice]
344
+ ∟ Endpoints encontrados: [N]
345
+ ∟ Contratos encontrados: [Sim/Não]
346
+ ∟ Dependências externas: [lista]
347
+ ∟ Mock strategy recomendada: [wiremock|nock|msw]
348
+
349
+ 📝 Arquivo de Teste:
350
+ ∟ Status: [✅ Existente | ✅ Gerado | ❌ Não encontrado]
351
+ ∟ Caminho: {{test-file-path}}
352
+ ∟ Testes: [N] casos de teste
353
+ ├─ Contract tests: [N]
354
+ ├─ Boundary tests: [N]
355
+ └─ Fuzzing tests: [N]
356
+
357
+ 🧪 Execução:
358
+ ∟ Comando: [comando executado]
359
+ ∟ Status: [✅ Passou | ❌ Falhou | ⚠️ Parcial]
360
+ ∟ Testes executados: [X/Y] passaram
361
+ ∟ Contratos validados: [X/Y]
362
+ ∟ Tempo: [X]s
363
+
364
+ 📊 Resultados Detalhados:
365
+ ∟ Contract Tests: [X/Y] ✅
366
+ └─ Schemas validados: [lista]
367
+ └─ Contratos verificados: [lista]
368
+ ∟ Boundary Tests: [X/Y] ✅
369
+ └─ Timeouts testados: [N]
370
+ └─ Erros tratados: [N]
371
+ ∟ Fuzzing Tests: [X/Y] ✅
372
+ └─ Inputs malformados: [N]
373
+ └─ Edge cases: [N]
374
+
375
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
376
+
377
+ 🚀 Próximos Passos:
378
+ 1. Revisar testes gerados e adicionar casos específicos
379
+ 2. Executar novamente: /test/integration {{api-endpoint}} --run
380
+ 3. Adicionar contract tests: /test/integration {{api-endpoint}} --contract
381
+ 4. Integrar no pipeline: /validate/test-strategy/create
382
+
383
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
384
+ ```
385
+
386
+ ## 📋 Exemplos de Uso
387
+
388
+ **1. Gerar e executar com contract testing:**
389
+ ```bash
390
+ /test/integration /api/users --generate --run --contract
391
+ ```
392
+ → Detecta framework, analisa API, gera `users.integration.test.js` com contract tests, executa
393
+
394
+ **2. Apenas gerar testes de boundary:**
395
+ ```bash
396
+ /test/integration payment-service --generate --boundary --framework supertest
397
+ ```
398
+ → Força Supertest, gera testes de boundary (timeouts, erros), não executa
399
+
400
+ **3. Executar com fuzzing:**
401
+ ```bash
402
+ /test/integration /api/orders --run --fuzz
403
+ ```
404
+ → Executa `orders.integration.test.js` existente com fuzzing habilitado
405
+
406
+ **4. Gerar testes completos (contract + boundary + fuzzing):**
407
+ ```bash
408
+ /test/integration user-service --generate --contract --boundary --fuzz
409
+ ```
410
+ → Gera suite completa de testes de integração
411
+
412
+ **5. Executar teste existente sem mockar externos:**
413
+ ```bash
414
+ /test/integration /api/products --run --mock-external false
415
+ ```
416
+ → Executa contra serviços reais (útil para staging)
417
+
418
+ ## ⚙️ Parâmetros Detalhados
419
+
420
+ | Parâmetro | Tipo | Obrigatório | Descrição |
421
+ |-----------|------|-------------|-----------|
422
+ | `api-endpoint` | string | ✅ | Endpoint da API ou nome do serviço |
423
+ | `--generate` | flag | ❌ | Gera arquivo de teste se não existir |
424
+ | `--run` | flag | ❌ | Executa os testes após gerar/validar |
425
+ | `--contract` | flag | ❌ | Foca em contract testing (schemas) |
426
+ | `--boundary` | flag | ❌ | Foca em boundary testing (timeouts, erros) |
427
+ | `--fuzz` | flag | ❌ | Inclui fuzzing de API (dados malformados) |
428
+ | `--framework` | string | ❌ | Framework específico (sobrescreve auto-detecção) |
429
+ | `--mock-external` | boolean | ❌ | Mocka serviços externos (default: true) |
430
+
431
+ ## 🔗 Comandos Relacionados
432
+
433
+ - `/test/unit` - Testes unitários (White-box)
434
+ - `/test/e2e` - Testes end-to-end (Black-box)
435
+ - `/validate/test-strategy/create` - Criar estratégia completa de testes
436
+ - `/engineer/work` - Continuar desenvolvimento com testes
437
+
438
+ ## ⚠️ Validações e Regras
439
+
440
+ ### Validações Obrigatórias
441
+
442
+ 1. **Endpoint/Service deve ser fornecido:**
443
+ ```markdown
444
+ SE api-endpoint vazio:
445
+ ❌ ERRO: Endpoint ou serviço é obrigatório
446
+ ```
447
+
448
+ 2. **Framework deve ser detectável ou fornecido:**
449
+ ```markdown
450
+ SE nenhum framework detectado E --framework não fornecido:
451
+ ❌ ERRO: Não foi possível detectar framework de integração
452
+ 💡 Instale um framework ou use --framework [nome]
453
+ ```
454
+
455
+ 3. **Arquivo de teste deve existir para execução:**
456
+ ```markdown
457
+ SE --run fornecido E arquivo de teste não existe E --generate não fornecido:
458
+ ❌ ERRO: Arquivo de teste não encontrado
459
+ 💡 Use --generate para criar automaticamente
460
+ ```
461
+
462
+ ### Regras de Negócio
463
+
464
+ 1. **Auto-detecção tem prioridade** sobre --framework, exceto se --framework fornecido
465
+ 2. **Geração segue padrões** do projeto (analisa testes existentes)
466
+ 3. **Contract testing** valida schemas, tipos e estruturas de resposta
467
+ 4. **Boundary testing** foca em timeouts, erros e limites de integração
468
+ 5. **Fuzzing** testa robustez com dados malformados e edge cases
469
+ 6. **Mock externo é default** (true) para isolamento, use `--mock-external false` para testes reais
470
+ 7. **Testes gerados** seguem perspectiva Grey-box (dev testando outro dev)
471
+
472
+ ## 🔧 Suporte por Framework
473
+
474
+ | Framework | Contract | Boundary | Fuzzing | Mock Strategy |
475
+ |-----------|----------|----------|---------|---------------|
476
+ | Supertest | ✅ | ✅ | ✅ | Nock, MSW |
477
+ | Pact | ✅ | ⚠️ | ❌ | Pact Mock Service |
478
+ | Postman | ✅ | ✅ | ⚠️ | Postman Mock Server |
479
+ | Wiremock | ⚠️ | ✅ | ⚠️ | Wiremock |
480
+ | Jest/Vitest | ✅ | ✅ | ✅ | Jest/Vitest mocks |
481
+
482
+ ## 📚 Referências
483
+
484
+ - **Agente de Testes:** @test-engineer, @test-agent
485
+ - **Framework de Testes:** `docs/knowbase/frameworks/framework_testes.md`
486
+ - **Grey-box Testing:** Seção "Padrões Grey-box" do framework
487
+ - **API Contract Testing:** Seção "Teste de Contrato de API"
488
+ - **Supertest Docs:** https://github.com/visionmedia/supertest
489
+ - **Pact Docs:** https://docs.pact.io
490
+ - **Wiremock Docs:** https://wiremock.org
491
+
492
+ ## ⚠️ Notas Importantes
493
+
494
+ - **Auto-detecção inteligente:** Analisa configurações e padrões do projeto
495
+ - **Geração conservadora:** Cria testes básicos, desenvolvedor deve expandir
496
+ - **Perspectiva Grey-box:** Foco em integração entre componentes (dev testando outro dev)
497
+ - **Contract testing:** Valida contratos entre serviços (100% coverage conforme framework)
498
+ - **Boundary testing:** Testa fronteiras de integração (timeouts, erros, limites)
499
+ - **Fuzzing opcional:** Use `--fuzz` para testes de robustez
500
+ - **Mock por padrão:** Isola testes de serviços externos, use `--mock-external false` para testes reais
501
+ - **Integração com pipeline:** Testes gerados seguem padrões do projeto
502
+
503
+ ---
504
+
505
+ **Versão:** 3.0.0
506
+ **Última atualização:** 2025-12-03
507
+ **Mantido por:** Sistema Onion
508
+