@girardelli/architect 2.2.0 → 5.0.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 (212) hide show
  1. package/README.md +105 -116
  2. package/architect-run.sh +431 -0
  3. package/assets/banner-v3.html +561 -0
  4. package/dist/agent-generator/context-enricher.d.ts +58 -0
  5. package/dist/agent-generator/context-enricher.d.ts.map +1 -0
  6. package/dist/agent-generator/context-enricher.js +613 -0
  7. package/dist/agent-generator/context-enricher.js.map +1 -0
  8. package/dist/agent-generator/domain-inferrer.d.ts +52 -0
  9. package/dist/agent-generator/domain-inferrer.d.ts.map +1 -0
  10. package/dist/agent-generator/domain-inferrer.js +585 -0
  11. package/dist/agent-generator/domain-inferrer.js.map +1 -0
  12. package/dist/agent-generator/framework-detector.d.ts +40 -0
  13. package/dist/agent-generator/framework-detector.d.ts.map +1 -0
  14. package/dist/agent-generator/framework-detector.js +611 -0
  15. package/dist/agent-generator/framework-detector.js.map +1 -0
  16. package/dist/agent-generator/index.d.ts +47 -0
  17. package/dist/agent-generator/index.d.ts.map +1 -0
  18. package/dist/agent-generator/index.js +545 -0
  19. package/dist/agent-generator/index.js.map +1 -0
  20. package/dist/agent-generator/stack-detector.d.ts +14 -0
  21. package/dist/agent-generator/stack-detector.d.ts.map +1 -0
  22. package/dist/agent-generator/stack-detector.js +124 -0
  23. package/dist/agent-generator/stack-detector.js.map +1 -0
  24. package/dist/agent-generator/templates/core/agents.d.ts +17 -0
  25. package/dist/agent-generator/templates/core/agents.d.ts.map +1 -0
  26. package/dist/agent-generator/templates/core/agents.js +1256 -0
  27. package/dist/agent-generator/templates/core/agents.js.map +1 -0
  28. package/dist/agent-generator/templates/core/architecture-rules.d.ts +7 -0
  29. package/dist/agent-generator/templates/core/architecture-rules.d.ts.map +1 -0
  30. package/dist/agent-generator/templates/core/architecture-rules.js +274 -0
  31. package/dist/agent-generator/templates/core/architecture-rules.js.map +1 -0
  32. package/dist/agent-generator/templates/core/general-rules.d.ts +8 -0
  33. package/dist/agent-generator/templates/core/general-rules.d.ts.map +1 -0
  34. package/dist/agent-generator/templates/core/general-rules.js +301 -0
  35. package/dist/agent-generator/templates/core/general-rules.js.map +1 -0
  36. package/dist/agent-generator/templates/core/hooks-generator.d.ts +21 -0
  37. package/dist/agent-generator/templates/core/hooks-generator.d.ts.map +1 -0
  38. package/dist/agent-generator/templates/core/hooks-generator.js +233 -0
  39. package/dist/agent-generator/templates/core/hooks-generator.js.map +1 -0
  40. package/dist/agent-generator/templates/core/index-md.d.ts +7 -0
  41. package/dist/agent-generator/templates/core/index-md.d.ts.map +1 -0
  42. package/dist/agent-generator/templates/core/index-md.js +246 -0
  43. package/dist/agent-generator/templates/core/index-md.js.map +1 -0
  44. package/dist/agent-generator/templates/core/orchestrator.d.ts +8 -0
  45. package/dist/agent-generator/templates/core/orchestrator.d.ts.map +1 -0
  46. package/dist/agent-generator/templates/core/orchestrator.js +422 -0
  47. package/dist/agent-generator/templates/core/orchestrator.js.map +1 -0
  48. package/dist/agent-generator/templates/core/preflight.d.ts +8 -0
  49. package/dist/agent-generator/templates/core/preflight.d.ts.map +1 -0
  50. package/dist/agent-generator/templates/core/preflight.js +213 -0
  51. package/dist/agent-generator/templates/core/preflight.js.map +1 -0
  52. package/dist/agent-generator/templates/core/quality-gates.d.ts +11 -0
  53. package/dist/agent-generator/templates/core/quality-gates.d.ts.map +1 -0
  54. package/dist/agent-generator/templates/core/quality-gates.js +254 -0
  55. package/dist/agent-generator/templates/core/quality-gates.js.map +1 -0
  56. package/dist/agent-generator/templates/core/security-rules.d.ts +7 -0
  57. package/dist/agent-generator/templates/core/security-rules.d.ts.map +1 -0
  58. package/dist/agent-generator/templates/core/security-rules.js +528 -0
  59. package/dist/agent-generator/templates/core/security-rules.js.map +1 -0
  60. package/dist/agent-generator/templates/core/skills-generator.d.ts +19 -0
  61. package/dist/agent-generator/templates/core/skills-generator.d.ts.map +1 -0
  62. package/dist/agent-generator/templates/core/skills-generator.js +546 -0
  63. package/dist/agent-generator/templates/core/skills-generator.js.map +1 -0
  64. package/dist/agent-generator/templates/core/workflow-fix-bug.d.ts +7 -0
  65. package/dist/agent-generator/templates/core/workflow-fix-bug.d.ts.map +1 -0
  66. package/dist/agent-generator/templates/core/workflow-fix-bug.js +237 -0
  67. package/dist/agent-generator/templates/core/workflow-fix-bug.js.map +1 -0
  68. package/dist/agent-generator/templates/core/workflow-new-feature.d.ts +8 -0
  69. package/dist/agent-generator/templates/core/workflow-new-feature.d.ts.map +1 -0
  70. package/dist/agent-generator/templates/core/workflow-new-feature.js +321 -0
  71. package/dist/agent-generator/templates/core/workflow-new-feature.js.map +1 -0
  72. package/dist/agent-generator/templates/core/workflow-review.d.ts +7 -0
  73. package/dist/agent-generator/templates/core/workflow-review.d.ts.map +1 -0
  74. package/dist/agent-generator/templates/core/workflow-review.js +104 -0
  75. package/dist/agent-generator/templates/core/workflow-review.js.map +1 -0
  76. package/dist/agent-generator/templates/domain/index.d.ts +22 -0
  77. package/dist/agent-generator/templates/domain/index.d.ts.map +1 -0
  78. package/dist/agent-generator/templates/domain/index.js +1176 -0
  79. package/dist/agent-generator/templates/domain/index.js.map +1 -0
  80. package/dist/agent-generator/templates/stack/index.d.ts +8 -0
  81. package/dist/agent-generator/templates/stack/index.d.ts.map +1 -0
  82. package/dist/agent-generator/templates/stack/index.js +695 -0
  83. package/dist/agent-generator/templates/stack/index.js.map +1 -0
  84. package/dist/agent-generator/templates/template-helpers.d.ts +75 -0
  85. package/dist/agent-generator/templates/template-helpers.d.ts.map +1 -0
  86. package/dist/agent-generator/templates/template-helpers.js +726 -0
  87. package/dist/agent-generator/templates/template-helpers.js.map +1 -0
  88. package/dist/agent-generator/types.d.ts +196 -0
  89. package/dist/agent-generator/types.d.ts.map +1 -0
  90. package/dist/agent-generator/types.js +27 -0
  91. package/dist/agent-generator/types.js.map +1 -0
  92. package/dist/analyzer.d.ts +5 -0
  93. package/dist/analyzer.d.ts.map +1 -1
  94. package/dist/analyzer.js +46 -5
  95. package/dist/analyzer.js.map +1 -1
  96. package/dist/analyzers/forecast.d.ts +85 -0
  97. package/dist/analyzers/forecast.d.ts.map +1 -0
  98. package/dist/analyzers/forecast.js +337 -0
  99. package/dist/analyzers/forecast.js.map +1 -0
  100. package/dist/analyzers/git-cache.d.ts +7 -0
  101. package/dist/analyzers/git-cache.d.ts.map +1 -0
  102. package/dist/analyzers/git-cache.js +41 -0
  103. package/dist/analyzers/git-cache.js.map +1 -0
  104. package/dist/analyzers/git-history.d.ts +113 -0
  105. package/dist/analyzers/git-history.d.ts.map +1 -0
  106. package/dist/analyzers/git-history.js +333 -0
  107. package/dist/analyzers/git-history.js.map +1 -0
  108. package/dist/analyzers/index.d.ts +10 -0
  109. package/dist/analyzers/index.d.ts.map +1 -0
  110. package/dist/analyzers/index.js +7 -0
  111. package/dist/analyzers/index.js.map +1 -0
  112. package/dist/analyzers/temporal-scorer.d.ts +72 -0
  113. package/dist/analyzers/temporal-scorer.d.ts.map +1 -0
  114. package/dist/analyzers/temporal-scorer.js +140 -0
  115. package/dist/analyzers/temporal-scorer.js.map +1 -0
  116. package/dist/anti-patterns.d.ts +7 -0
  117. package/dist/anti-patterns.d.ts.map +1 -1
  118. package/dist/anti-patterns.js +25 -6
  119. package/dist/anti-patterns.js.map +1 -1
  120. package/dist/cli.d.ts +2 -3
  121. package/dist/cli.d.ts.map +1 -1
  122. package/dist/cli.js +275 -113
  123. package/dist/cli.js.map +1 -1
  124. package/dist/config.d.ts +6 -0
  125. package/dist/config.d.ts.map +1 -1
  126. package/dist/config.js +48 -11
  127. package/dist/config.js.map +1 -1
  128. package/dist/html-reporter.d.ts +3 -1
  129. package/dist/html-reporter.d.ts.map +1 -1
  130. package/dist/html-reporter.js +248 -12
  131. package/dist/html-reporter.js.map +1 -1
  132. package/dist/index.d.ts +16 -3
  133. package/dist/index.d.ts.map +1 -1
  134. package/dist/index.js +63 -4
  135. package/dist/index.js.map +1 -1
  136. package/dist/project-summarizer.d.ts +38 -0
  137. package/dist/project-summarizer.d.ts.map +1 -0
  138. package/dist/project-summarizer.js +463 -0
  139. package/dist/project-summarizer.js.map +1 -0
  140. package/dist/refactor-reporter.js +1 -1
  141. package/dist/scanner.d.ts +8 -2
  142. package/dist/scanner.d.ts.map +1 -1
  143. package/dist/scanner.js +153 -113
  144. package/dist/scanner.js.map +1 -1
  145. package/dist/scorer.d.ts.map +1 -1
  146. package/dist/scorer.js +24 -11
  147. package/dist/scorer.js.map +1 -1
  148. package/dist/types.d.ts +29 -0
  149. package/dist/types.d.ts.map +1 -1
  150. package/package.json +12 -3
  151. package/src/agent-generator/context-enricher.ts +672 -0
  152. package/src/agent-generator/domain-inferrer.ts +635 -0
  153. package/src/agent-generator/framework-detector.ts +669 -0
  154. package/src/agent-generator/index.ts +634 -0
  155. package/src/agent-generator/stack-detector.ts +115 -0
  156. package/src/agent-generator/templates/core/agents.ts +1296 -0
  157. package/src/agent-generator/templates/core/architecture-rules.ts +287 -0
  158. package/src/agent-generator/templates/core/general-rules.ts +306 -0
  159. package/src/agent-generator/templates/core/hooks-generator.ts +242 -0
  160. package/src/agent-generator/templates/core/index-md.ts +260 -0
  161. package/src/agent-generator/templates/core/orchestrator.ts +459 -0
  162. package/src/agent-generator/templates/core/preflight.ts +215 -0
  163. package/src/agent-generator/templates/core/quality-gates.ts +256 -0
  164. package/src/agent-generator/templates/core/security-rules.ts +543 -0
  165. package/src/agent-generator/templates/core/skills-generator.ts +585 -0
  166. package/src/agent-generator/templates/core/workflow-fix-bug.ts +239 -0
  167. package/src/agent-generator/templates/core/workflow-new-feature.ts +323 -0
  168. package/src/agent-generator/templates/core/workflow-review.ts +106 -0
  169. package/src/agent-generator/templates/domain/index.ts +1201 -0
  170. package/src/agent-generator/templates/stack/index.ts +705 -0
  171. package/src/agent-generator/templates/template-helpers.ts +776 -0
  172. package/src/agent-generator/types.ts +232 -0
  173. package/src/analyzer.ts +51 -5
  174. package/src/analyzers/forecast.ts +496 -0
  175. package/src/analyzers/git-cache.ts +52 -0
  176. package/src/analyzers/git-history.ts +488 -0
  177. package/src/analyzers/index.ts +33 -0
  178. package/src/analyzers/temporal-scorer.ts +227 -0
  179. package/src/anti-patterns.ts +29 -6
  180. package/src/cli.ts +316 -117
  181. package/src/config.ts +52 -11
  182. package/src/html-reporter.ts +263 -13
  183. package/src/index.ts +93 -10
  184. package/src/project-summarizer.ts +521 -0
  185. package/src/refactor-reporter.ts +1 -1
  186. package/src/scanner.ts +136 -90
  187. package/src/scorer.ts +26 -11
  188. package/src/types.ts +27 -0
  189. package/tests/agent-generator.test.ts +427 -0
  190. package/tests/analyzers-integration.test.ts +174 -0
  191. package/tests/architect-adapter-enrichment.test.ts +9 -0
  192. package/tests/context-enricher.test.ts +971 -0
  193. package/tests/fixtures/monorepo/package.json +6 -0
  194. package/tests/fixtures/monorepo/packages/app/package.json +12 -0
  195. package/tests/fixtures/monorepo/packages/app/src/index.ts +6 -0
  196. package/tests/fixtures/monorepo/packages/core/package.json +7 -0
  197. package/tests/fixtures/monorepo/packages/core/src/index.ts +7 -0
  198. package/tests/forecast.test.ts +509 -0
  199. package/tests/framework-detector.test.ts +1172 -0
  200. package/tests/git-history.test.ts +254 -0
  201. package/tests/monorepo-scan.test.ts +170 -0
  202. package/tests/scanner.test.ts +7 -8
  203. package/tests/scorer.test.ts +594 -0
  204. package/tests/stack-detector.test.ts +241 -0
  205. package/tests/template-generation.test.ts +706 -0
  206. package/tests/template-helpers.test.ts +1152 -0
  207. package/tests/temporal-scorer.test.ts +307 -0
  208. package/dist/agent-generator.d.ts +0 -106
  209. package/dist/agent-generator.d.ts.map +0 -1
  210. package/dist/agent-generator.js +0 -1398
  211. package/dist/agent-generator.js.map +0 -1
  212. package/src/agent-generator.ts +0 -1526
@@ -0,0 +1,1296 @@
1
+ import { TemplateContext, EnrichedTemplateContext } from '../../types.js';
2
+ import { crossRef, depthIndicator, depthAtLeast, getEnriched, frameworkBadge, frameworkModuleStructure, frameworkSecurityChecklist, toolchainCommands, projectStructureBadge } from '../template-helpers.js';
3
+
4
+ /**
5
+ * Generates all specialist agent cards.
6
+ * Each is stack-aware and enterprise-grade detailed.
7
+ *
8
+ * All functions support both TemplateContext (backward compat) and EnrichedTemplateContext.
9
+ * Use getEnriched() to safely extract enriched fields when available.
10
+ */
11
+
12
+ export function generateBackendAgent(ctx: TemplateContext | EnrichedTemplateContext): string {
13
+ const { stack, projectName, config, report } = ctx;
14
+ const enriched = getEnriched(ctx);
15
+ const lang = stack.primary;
16
+ // v3.1: Use detected primary framework instead of generic stack.frameworks
17
+ const primaryFw = enriched.primaryFramework;
18
+ const fw = primaryFw ? primaryFw.name : (stack.frameworks.filter(f =>
19
+ ['Django', 'Flask', 'FastAPI', 'NestJS', 'Spring', 'Express', 'Fastify', 'Rails', 'Laravel'].includes(f)
20
+ ).join(', ') || lang);
21
+
22
+ // Build module structure section if enriched data available
23
+ const modulesSection = enriched.modules && enriched.modules.length > 0
24
+ ? `
25
+ ## Módulos do Projeto
26
+
27
+ ${enriched.modules.map(m => `### ${m.name}
28
+ - **Path:** \`${m.path}\`
29
+ - **Arquivos:** ${m.fileCount}${m.lineCount > 0 ? ` · **Linhas:** ${m.lineCount.toLocaleString()}` : ''}
30
+ - **Descrição:** ${m.description}
31
+ - **Testes:** ${m.hasTests ? '✅ Sim' : '❌ Não'}
32
+ ${m.entities.length > 0 ? `- **Entidades:** ${m.entities.join(', ')}` : ''}
33
+ `).join('\n')}
34
+ `
35
+ : '';
36
+
37
+ // Build endpoints section if enriched data available
38
+ const endpointsSection = enriched.endpoints && enriched.endpoints.length > 0
39
+ ? `
40
+ ## Endpoints Mapeados
41
+
42
+ ${enriched.endpoints.map(e => `- \`${e.method}\` \`${e.path}\` — ${e.handler} (Auth: ${e.hasAuth ? 'sim' : 'não'}, Validação: ${e.hasValidation ? 'sim' : 'não'})`).join('\n')}
43
+ `
44
+ : '';
45
+
46
+ // Build domain section if enriched data available
47
+ const domainSection = enriched.domain
48
+ ? `
49
+ ## Domínio & Contexto de Negócio
50
+
51
+ - **Domínio:** ${enriched.domain.domain}
52
+ - **Sub-domínio:** ${enriched.domain.subDomain}
53
+ - **Descrição:** ${enriched.domain.description}
54
+ - **Confiança na Inferência:** ${Math.round(enriched.domain.confidence * 100)}%
55
+ ${enriched.domain.businessEntities && enriched.domain.businessEntities.length > 0
56
+ ? `
57
+ ### Entidades de Negócio Detectadas
58
+
59
+ ${enriched.domain.businessEntities.map(e => `- **${e.name}** (${e.layer}) — de \`${e.source}\`
60
+ - Campos: ${e.fields.join(', ')}
61
+ - Relacionamentos: ${e.relationships.length > 0 ? e.relationships.join(', ') : 'nenhum'}`).join('\n')}
62
+ `
63
+ : ''}
64
+ `
65
+ : '';
66
+
67
+ return `---
68
+ antigravity:
69
+ trigger: 'on_demand'
70
+ globs: ['**/*.${lang === 'Python' ? 'py' : lang === 'Dart' ? 'dart' : lang === 'Go' ? 'go' : 'ts'}']
71
+ description: '${lang} Backend Developer — APIs, serviços, lógica de negócio'
72
+ agent_card:
73
+ id: '${lang.toLowerCase()}-backend'
74
+ name: '${lang} Backend Developer'
75
+ role: 'development'
76
+ capabilities: [api-design, service-architecture, business-logic, data-modeling, testing]
77
+ inputs: [user-story, api-contracts, business-rules, integration-doc]
78
+ outputs: [controllers, services, entities, migrations, tests, integration-doc]
79
+ depends_on: [${stack.hasDatabase ? 'database-engineer' : ''}]
80
+ version: 3.1.0
81
+ ---
82
+
83
+ # 🔧 ${lang.toUpperCase()} BACKEND DEVELOPER
84
+
85
+ ${depthIndicator(ctx)}
86
+
87
+ > Especialista em backend ${fw} para ${projectName}
88
+
89
+ ## Stack
90
+
91
+ - **Linguagem:** ${lang}
92
+ - **Framework:** ${fw}${primaryFw?.version ? ` v${primaryFw.version}` : ''}
93
+ - **Arquitetura:** ${projectStructureBadge(ctx)}
94
+ - **Teste:** ${stack.testFramework}
95
+ - **Package Manager:** ${stack.packageManager}
96
+ - **Score Atual:** ${report.score.overall}/100
97
+
98
+ ${frameworkBadge(ctx)}
99
+ ${domainSection}
100
+
101
+ ## Princípios (SOLID + Clean Architecture)
102
+
103
+ 1. **S** — Single Responsibility: Uma classe, uma responsabilidade
104
+ 2. **O** — Open/Closed: Aberto para extensão, fechado para modificação
105
+ 3. **L** — Liskov Substitution: Subtipos devem ser substituíveis
106
+ 4. **I** — Interface Segregation: Interfaces específicas > interfaces gordas
107
+ 5. **D** — Dependency Inversion: Depender de abstrações, não de concretos
108
+ ${modulesSection}
109
+
110
+ ## Estrutura do Projeto (Detectada)
111
+
112
+ ${frameworkModuleStructure(ctx)}
113
+ ${endpointsSection}
114
+
115
+ ## Regras de Implementação
116
+
117
+ \`\`\`
118
+ □ Controller NUNCA contém lógica de negócio (apenas routing)
119
+ □ Service NUNCA acessa Request/Response diretamente
120
+ □ Entity NUNCA é exposta diretamente na API (usar DTO)
121
+ □ Validação de input no DTO / Guard / Pipe
122
+ □ Erros com mensagens claras e códigos HTTP corretos
123
+ □ Logging estruturado (não console.log)
124
+ □ Testes unitários para cada service method
125
+ □ Testes de integração para cada endpoint
126
+ □ Cobertura ≥ ${config.coverageMinimum}%
127
+ \`\`\`
128
+
129
+ ## Após Implementação Backend
130
+
131
+ > **OBRIGATÓRIO: Gerar Documento de Integração antes de qualquer frontend/app.**
132
+
133
+ O documento deve conter:
134
+ - Todos os endpoints criados/modificados
135
+ - Payloads de request e response (com exemplos)
136
+ - Códigos de erro e mensagens
137
+ - Regras de negócio aplicadas
138
+ - Headers necessários (auth, pagination, etc.)
139
+
140
+ ${crossRef('backend', ctx)}
141
+
142
+ ---
143
+
144
+ **Gerado por Architect v3.1**
145
+ `;
146
+ }
147
+
148
+ export function generateFrontendAgent(ctx: TemplateContext | EnrichedTemplateContext): string {
149
+ const { stack, projectName, config, report } = ctx;
150
+ const enriched = getEnriched(ctx);
151
+ // v5.1: Use enriched primaryFramework or detect from all frameworks
152
+ const FRONTEND_FWS = ['Angular', 'Vue', 'Vue.js', 'Next.js', 'React', 'Nuxt', 'Svelte', 'Remix'];
153
+ const detectedFw = enriched.detectedFrameworks?.find(f => FRONTEND_FWS.includes(f.name));
154
+ const fw = detectedFw?.name ||
155
+ stack.frameworks.find(f => FRONTEND_FWS.includes(f)) || 'Frontend';
156
+
157
+ // Build endpoints integration guide if available
158
+ const endpointsGuide = enriched.endpoints && enriched.endpoints.length > 0
159
+ ? `
160
+ ## Endpoints para Integração
161
+
162
+ ${enriched.endpoints.filter(e => ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'].includes(e.method))
163
+ .slice(0, 15) // limit to 15 most important
164
+ .map(e => `- \`${e.method}\` \`${e.path}\` (${e.handler})`)
165
+ .join('\n')}
166
+ ${enriched.endpoints.length > 15 ? `
167
+ ... e mais ${enriched.endpoints.length - 15} endpoints. Ver documento de integração completo.` : ''}
168
+ `
169
+ : '';
170
+
171
+ // Build modules structure if available
172
+ const modulesGuide = enriched.modules && enriched.modules.length > 0
173
+ ? `
174
+ ## Estrutura de Módulos Disponíveis
175
+
176
+ ${enriched.modules.map(m => `- \`${m.path}\` — ${m.description}`).join('\n')}
177
+ `
178
+ : '';
179
+
180
+ return `---
181
+ antigravity:
182
+ trigger: 'on_demand'
183
+ globs: ['**/*.{ts,tsx,vue,jsx,html,css,scss}']
184
+ description: '${fw} Frontend Developer — Componentes, UX, state management'
185
+ agent_card:
186
+ id: '${fw.toLowerCase().replace('.', '')}-frontend'
187
+ name: '${fw} Frontend Developer'
188
+ role: 'development'
189
+ capabilities: [component-development, state-management, responsive-design, form-handling, api-integration]
190
+ inputs: [mockup, integration-doc, user-story, design-system]
191
+ outputs: [components, pages, services, tests]
192
+ depends_on: [orchestrator]
193
+ version: 3.1.0
194
+ ---
195
+
196
+ # 🎨 ${fw.toUpperCase().replace('.', '')} FRONTEND DEVELOPER
197
+
198
+ ${depthIndicator(ctx)}
199
+
200
+ > Especialista em frontend ${fw} para ${projectName}
201
+
202
+ ## Stack Frontend
203
+
204
+ - **Framework:** ${fw}
205
+ - **Linguagens:** ${stack.languages.join(', ')}
206
+ - **Teste:** ${stack.testFramework}
207
+ - **Score Atual:** ${report.score.overall}/100
208
+
209
+ ## Pré-Requisitos para Implementar
210
+
211
+ \`\`\`
212
+ ╔══════════════════════════════════════════════╗
213
+ ║ ANTES de escrever qualquer componente: ║
214
+ ║ ║
215
+ ║ □ MOCKUP aprovado pelo humano ║
216
+ ║ □ Documento de Integração disponível ║
217
+ ║ □ User stories com critérios de aceite ║
218
+ ║ □ BDD scenarios escritos ║
219
+ ╚══════════════════════════════════════════════╝
220
+ \`\`\`
221
+ ${modulesGuide}${endpointsGuide}
222
+
223
+ ## Regras de Implementação
224
+
225
+ \`\`\`
226
+ □ Componente segue MOCKUP aprovado (não inventar UI)
227
+ □ TODOS os estados implementados:
228
+ - ✅ Com dados (estado normal)
229
+ - 📭 Vazio (empty state)
230
+ - ⏳ Carregando (loading state / skeleton)
231
+ - ❌ Erro (error state com mensagem clara)
232
+ □ Lógica de negócio em services (NUNCA no componente)
233
+ □ State management adequado (sem prop drilling)
234
+ □ Formulários com validação client-side
235
+ □ Responsivo (testar mobile + desktop)
236
+ □ Acessibilidade básica (labels, aria, contraste)
237
+ □ Lazy loading onde aplicável
238
+ □ Cobertura ≥ ${config.coverageMinimum}%
239
+ \`\`\`
240
+
241
+ ${crossRef('frontend', ctx)}
242
+
243
+ ---
244
+
245
+ **Gerado por Architect v3.1**
246
+ `;
247
+ }
248
+
249
+ export function generateSecurityAgent(ctx: TemplateContext | EnrichedTemplateContext): string {
250
+ const { projectName, config, stack } = ctx;
251
+ const enriched = getEnriched(ctx);
252
+
253
+ // Build compliance section if available
254
+ const complianceSection = enriched.domain && enriched.domain.compliance && enriched.domain.compliance.length > 0
255
+ ? `
256
+ ## Requisitos de Compliance Detectados
257
+
258
+ ${enriched.domain.compliance.map(c => `### ${c.name}
259
+ **Motivo:** ${c.reason}
260
+
261
+ **Verificações Obrigatórias:**
262
+ ${c.mandatoryChecks.map(check => `- □ ${check}`).join('\n')}
263
+ `).join('\n')}
264
+ `
265
+ : '';
266
+
267
+ // Build integrations security section if available
268
+ const integrationsSection = enriched.domain && enriched.domain.integrations && enriched.domain.integrations.length > 0
269
+ ? `
270
+ ## Segurança em Integrações
271
+
272
+ ${enriched.domain.integrations.map(i => {
273
+ let threat = '';
274
+ if (i.type === 'payment') threat = 'PCI-DSS, criptografia de dados sensíveis, tokenização';
275
+ else if (i.type === 'auth') threat = 'MFA, session hijacking, credential stuffing';
276
+ else if (i.type === 'api') threat = 'Rate limiting, API key rotation, HTTPS obrigatório';
277
+ else if (i.type === 'database') threat = 'SQL Injection, Encryption at rest, Backups';
278
+ else if (i.type === 'government') threat = 'Compliance regulatório, audit trails, data retention';
279
+ else threat = 'Validação de entrada/saída, rate limiting';
280
+
281
+ return `- **${i.name}** (${i.type}) — Ameaças: ${threat}`;
282
+ }).join('\n')}
283
+ `
284
+ : '';
285
+
286
+ // Domain-specific threats
287
+ const domainThreatsSection = enriched.domain
288
+ ? `
289
+ ## Ameaças Específicas do Domínio: ${enriched.domain.domain}
290
+
291
+ ${enriched.domain.domain === 'fintech' || enriched.domain.domain === 'payments'
292
+ ? `- **Manipulação de dados:** Auditoria de transações, checksums, criptografia
293
+ - **Acesso não autorizado:** MFA em contas privilégiadas, IP whitelist
294
+ - **Conformidade:** PCI-DSS, LGPD, SOX
295
+ - **Fraude:** Detecção de anomalias, rate limiting`
296
+ : enriched.domain.domain === 'healthtech'
297
+ ? `- **Vazamento de dados:** Criptografia end-to-end, anonimização
298
+ - **HIPAA/LGPD:** Audit trails, consentimento explícito
299
+ - **Integridade:** Assinatura digital, blockchain se aplicável
300
+ - **Acesso:** RBAC granular, 2FA para dados sensíveis`
301
+ : enriched.domain.domain === 'e-commerce'
302
+ ? `- **Fraude de pagamento:** CVV validation, 3D Secure
303
+ - **Roubo de dados:** SSL/TLS, PCI-DSS, criptografia em repouso
304
+ - **DoS:** Rate limiting, CAPTCHA, WAF
305
+ - **Autenticação:** MFA, session timeout`
306
+ : `- **Confidencialidade:** Dados em trânsito e repouso criptografados
307
+ - **Integridade:** Validação de entrada, checksums
308
+ - **Disponibilidade:** Backup, disaster recovery, monitoring
309
+ - **Auditoria:** Logging de ações sensíveis, retention policy`}
310
+ `
311
+ : '';
312
+
313
+ // v3.1: Framework-specific security checklist
314
+ const stackSecuritySection = frameworkSecurityChecklist(ctx);
315
+
316
+ return `---
317
+ antigravity:
318
+ trigger: 'on_demand'
319
+ description: 'Security Auditor — Análise de ameaças, compliance, vulnerabilidades'
320
+ agent_card:
321
+ id: 'security-auditor'
322
+ name: 'Security Auditor'
323
+ role: 'quality'
324
+ capabilities: [threat-modeling, owasp-analysis, compliance-check, vulnerability-detection]
325
+ inputs: [architecture-doc, source-code, api-contracts]
326
+ outputs: [threat-model, security-findings, compliance-report]
327
+ depends_on: []
328
+ version: 3.1.0
329
+ ---
330
+
331
+ # 🛡️ SECURITY AUDITOR
332
+
333
+ ${depthIndicator(ctx)}
334
+
335
+ > Análise de segurança para ${projectName}
336
+
337
+ ## Checklist OWASP Top 10
338
+
339
+ \`\`\`
340
+ □ A01: Broken Access Control — RBAC implementado?
341
+ □ A02: Cryptographic Failures — Dados sensíveis criptografados?
342
+ □ A03: Injection — Inputs sanitizados? Queries parametrizadas?
343
+ □ A04: Insecure Design — Threat model feito?
344
+ □ A05: Security Misconfiguration — Headers, CORS, defaults?
345
+ □ A06: Vulnerable Components — Deps atualizadas?
346
+ □ A07: Auth Failures — Brute force protegido? Session management?
347
+ □ A08: Software Integrity — Supply chain verificado?
348
+ □ A09: Logging Failures — Audit log para ações sensíveis?
349
+ □ A10: SSRF — Server-side requests validados?
350
+ \`\`\`
351
+ ${stackSecuritySection}
352
+ ${complianceSection}${integrationsSection}${domainThreatsSection}
353
+
354
+ ## Quando Ativar
355
+
356
+ - Qualquer feature que lida com: autenticação, autorização, dados pessoais, pagamentos
357
+ - Novas APIs públicas
358
+ - Integrações com sistemas externos
359
+ - Mudanças em infra/deploy
360
+
361
+ ## Output Esperado
362
+
363
+ 1. Lista de findings com severidade (CRITICAL/HIGH/MEDIUM/LOW)
364
+ 2. Recomendações de mitigação
365
+ 3. Threat model (se aplicável)
366
+
367
+ ${crossRef('security-auditor', ctx)}
368
+
369
+ ---
370
+
371
+ **Gerado por Architect v3.1**
372
+ `;
373
+ }
374
+
375
+ export function generateQAAgent(ctx: TemplateContext | EnrichedTemplateContext): string {
376
+ const { projectName, config, stack, plan } = ctx;
377
+ const enriched = getEnriched(ctx);
378
+
379
+ // Build untested modules warning (reference canonical source)
380
+ const untestedCount = enriched.untestedModules?.length || 0;
381
+ const unterstedWarning = untestedCount > 0
382
+ ? `
383
+ ## ⚠️ MÓDULOS SEM COBERTURA DE TESTE
384
+
385
+ **${untestedCount} módulos sem testes detectados.**
386
+
387
+ > 📋 Lista completa e priorização: ver [QUALITY-GATES.md](../guards/QUALITY-GATES.md) e [TECH-DEBT-CONTROLLER.md](./TECH-DEBT-CONTROLLER.md)
388
+
389
+ **Ação:** Implementar testes para cada módulo listado, seguindo o workflow TDD.
390
+ `
391
+ : '';
392
+
393
+ // Build test scenarios from endpoints
394
+ const testScenariosSection = enriched.endpoints && enriched.endpoints.length > 0
395
+ ? `
396
+ ## Cenários de Teste por Endpoint
397
+
398
+ ${enriched.endpoints.slice(0, 10).map(e => `### \`${e.method}\` \`${e.path}\`
399
+
400
+ **Casos de teste:**
401
+ - ✅ Sucesso com dados válidos
402
+ - ⚠️ Validação: entrada inválida
403
+ ${e.hasAuth ? `- 🔒 Autenticação: sem token, token inválido
404
+ - 🔒 Autorização: usuário sem permissão` : ''}
405
+ - ❌ Erro: recurso não encontrado (404)
406
+ - ❌ Erro: conflito (409)
407
+ `).join('\n')}
408
+
409
+ ${enriched.endpoints.length > 10 ? `... e mais ${enriched.endpoints.length - 10} endpoints para testar.` : ''}
410
+ `
411
+ : '';
412
+
413
+ // Build domain-specific test scenarios
414
+ const domainTestsSection = enriched.domain
415
+ ? `
416
+ ## Cenários de Teste Específicos do Domínio: ${enriched.domain.domain}
417
+
418
+ ${enriched.domain.domain === 'fintech' || enriched.domain.domain === 'payments'
419
+ ? `### Testes de Negócio
420
+ - Criar transação com valores válidos
421
+ - Rejeitar transação acima do limite
422
+ - Processar reembolso corretamente
423
+ - Auditoria de todas as transações
424
+ - Validar saldo após múltiplas operações
425
+
426
+ ### Testes de Segurança
427
+ - Não expor dados de cartão em logs
428
+ - Validar PCI-DSS compliance
429
+ - Testar detecção de fraude`
430
+ : enriched.domain.domain === 'healthtech'
431
+ ? `### Testes de Negócio
432
+ - Criar registro de paciente com LGPD compliance
433
+ - Validar consentimento antes de compartilhar dados
434
+ - Anonimizar dados corretamente
435
+ - Respeitar direito ao esquecimento
436
+ - Auditoria de acesso a dados sensíveis
437
+
438
+ ### Testes de Segurança
439
+ - Criptografia end-to-end em repouso
440
+ - Validar 2FA para dados críticos
441
+ - Testar retenção de dados`
442
+ : enriched.domain.domain === 'e-commerce'
443
+ ? `### Testes de Negócio
444
+ - Criar carrinho com múltiplos produtos
445
+ - Aplicar desconto/cupom corretamente
446
+ - Processar pagamento com validação 3DS
447
+ - Atualizar inventário após venda
448
+ - Gerar pedido com status correto
449
+
450
+ ### Testes de Segurança
451
+ - Não expor dados de cartão
452
+ - Validar rate limiting em checkout
453
+ - Testar proteção contra fraud`
454
+ : `### Testes de Negócio
455
+ - Fluxo principal (happy path)
456
+ - Edge cases e limites
457
+ - Concorrência (race conditions)
458
+ - Rollback após erro
459
+ - Idempotência
460
+
461
+ ### Testes de Segurança
462
+ - Inputs inválidos/maliciosos
463
+ - Acesso não autorizado
464
+ - Rate limiting
465
+ - Logging correto`}
466
+ `
467
+ : '';
468
+
469
+ return `---
470
+ antigravity:
471
+ trigger: 'on_demand'
472
+ description: 'QA Test Engineer — Planos de teste, BDD/TDD, cobertura'
473
+ agent_card:
474
+ id: 'qa-test-engineer'
475
+ name: 'QA Test Engineer'
476
+ role: 'quality'
477
+ capabilities: [test-planning, bdd-scenarios, tdd-implementation, coverage-analysis, regression-testing]
478
+ inputs: [user-story, bdd-scenarios, source-code]
479
+ outputs: [test-plan, test-cases, coverage-report]
480
+ depends_on: []
481
+ version: 3.1.0
482
+ ---
483
+
484
+ # 🧪 QA TEST ENGINEER
485
+
486
+ ${depthIndicator(ctx)}
487
+
488
+ > Qualidade de testes para ${projectName}
489
+
490
+ ## Metas Inegociáveis
491
+
492
+ \`\`\`
493
+ ╔══════════════════════════════════════════╗
494
+ ║ Cobertura mínima: ${config.coverageMinimum}% ║
495
+ ║ Sem testes, sem entrega, sem finalizar ║
496
+ ║ INEGOCIÁVEL. ║
497
+ ╚══════════════════════════════════════════╝
498
+ \`\`\`
499
+ ${unterstedWarning}
500
+
501
+ ## Pirâmide de Testes
502
+
503
+ \`\`\`
504
+ ╱╲
505
+ ╱ E2E╲ → Poucos, lentos, alto valor
506
+ ╱──────╲
507
+ ╱Integration╲ → Médio, validam integração
508
+ ╱──────────────╲
509
+ ╱ Unit Tests ╲ → Muitos, rápidos, baratos
510
+ ╱════════════════════╲
511
+ \`\`\`
512
+
513
+ ## Processo
514
+
515
+ 1. **BDD primeiro** — cenários Gherkin antes de código
516
+ 2. **TDD** — RED → GREEN → REFACTOR
517
+ 3. **Coverage** — verificar após cada implementação
518
+ 4. **Regressão** — TODOS os testes antigos devem continuar passando
519
+ 5. **Review** — testes são revisados junto com código
520
+
521
+ ## Framework: ${stack.testFramework}
522
+ ${testScenariosSection}${domainTestsSection}
523
+
524
+ ## Refactoring Roadmap
525
+
526
+ ${plan.steps.slice(0, 5).map((step, idx) => `${idx + 1}. ${step.description} (${step.priority || 'MEDIUM'})`).join('\n')}
527
+ ${plan.steps.length > 5 ? `\n... e mais ${plan.steps.length - 5} steps.` : ''}
528
+
529
+ ${crossRef('qa-test', ctx)}
530
+
531
+ ---
532
+
533
+ **Gerado por Architect v3.1**
534
+ `;
535
+ }
536
+
537
+ export function generateTechDebtAgent(ctx: TemplateContext | EnrichedTemplateContext): string {
538
+ const { projectName, report, plan, config } = ctx;
539
+ const enriched = getEnriched(ctx);
540
+
541
+ // Group anti-patterns by severity
542
+ const criticalPatterns = report.antiPatterns.filter(a => a.severity === 'CRITICAL');
543
+ const highPatterns = report.antiPatterns.filter(a => a.severity === 'HIGH');
544
+ const mediumPatterns = report.antiPatterns.filter(a => a.severity === 'MEDIUM');
545
+ const lowPatterns = report.antiPatterns.filter(a => a.severity === 'LOW');
546
+
547
+ const antiPatternsSection = `
548
+ ## Anti-Patterns Detectados (Agrupados por Severidade)
549
+
550
+ ${criticalPatterns.length > 0 ? `
551
+ ### 🔴 CRÍTICOS (${criticalPatterns.length})
552
+ ${criticalPatterns.map(a => `- **${a.name}** — \`${a.location}\`
553
+ Ação: Resolver no próximo sprint`).join('\n')}
554
+ ` : ''}
555
+
556
+ ${highPatterns.length > 0 ? `
557
+ ### 🟠 ALTOS (${highPatterns.length})
558
+ ${highPatterns.map(a => `- **${a.name}** — \`${a.location}\`
559
+ Ação: Planejar correção para próximas 2 semanas`).join('\n')}
560
+ ` : ''}
561
+
562
+ ${mediumPatterns.length > 0 ? `
563
+ ### 🟡 MÉDIOS (${mediumPatterns.length})
564
+ ${mediumPatterns.map(a => `- **${a.name}** — \`${a.location}\`
565
+ Ação: Adicionar ao backlog de técnico`).join('\n')}
566
+ ` : ''}
567
+
568
+ ${lowPatterns.length > 0 ? `
569
+ ### 🟢 BAIXOS (${lowPatterns.length})
570
+ ${lowPatterns.map(a => `- **${a.name}** — \`${a.location}\`
571
+ Ação: Considerar em refatorações futuras`).join('\n')}
572
+ ` : ''}
573
+
574
+ ${report.antiPatterns.length === 0 ? '✅ Nenhum anti-pattern detectado.' : ''}
575
+ `;
576
+
577
+ // Critical coupling hotspots
578
+ const couplingSection = enriched.criticalPaths && enriched.criticalPaths.length > 0
579
+ ? `
580
+ ## Hotspots de Acoplamento (Tech Debt)
581
+
582
+ Arquivos com alta complexidade de acoplamento — priorizar refatoração:
583
+
584
+ ${enriched.criticalPaths.slice(0, 10).map(p => `- \`${p}\` — Alto acoplamento detectado`).join('\n')}
585
+ ${enriched.criticalPaths.length > 10 ? `\n... e mais ${enriched.criticalPaths.length - 10} caminhos críticos.` : ''}
586
+ `
587
+ : '';
588
+
589
+ // Untested modules as debt (reference canonical source)
590
+ const untestedDebtCount = enriched.untestedModules?.length || 0;
591
+ const unterstedDebtSection = untestedDebtCount > 0
592
+ ? `
593
+ ## Débito em Cobertura de Teste
594
+
595
+ **${untestedDebtCount} módulos sem testes adequados detectados.**
596
+
597
+ > 📋 Lista canônica e gates de cobertura: ver [QUALITY-GATES.md](../guards/QUALITY-GATES.md#módulos-sem-testes)
598
+
599
+ **Plano de ação:**
600
+ 1. Priorizar módulos com mais dependências
601
+ 2. Seguir workflow TDD para cada módulo
602
+ 3. Meta: reduzir lista a zero em ${Math.ceil(untestedDebtCount / 3)} sprints
603
+ `
604
+ : '';
605
+
606
+ return `---
607
+ antigravity:
608
+ trigger: 'on_demand'
609
+ description: 'Tech Debt Controller — Controle de débito técnico e metas de score'
610
+ agent_card:
611
+ id: 'tech-debt-controller'
612
+ name: 'Tech Debt Controller'
613
+ role: 'governance'
614
+ capabilities: [debt-tracking, score-monitoring, refactoring-prioritization]
615
+ inputs: [architecture-report, anti-patterns, score-history]
616
+ outputs: [debt-backlog, refactoring-plan, score-targets]
617
+ depends_on: []
618
+ version: 3.1.0
619
+ ---
620
+
621
+ # 📊 TECH DEBT CONTROLLER
622
+
623
+ ${depthIndicator(ctx)}
624
+
625
+ > Controle de débito técnico para ${projectName}
626
+
627
+ ## Estado Atual
628
+
629
+ | Métrica | Valor |
630
+ |---------|-------|
631
+ | Score | ${report.score.overall}/100 |
632
+ | Meta | ${Math.min(100, report.score.overall + 10)}/100 |
633
+ | Anti-patterns | ${report.antiPatterns.length} |
634
+ | Refatorações pendentes | ${plan.steps.length} |
635
+ | Estimativa de Melhora | +${plan.estimatedScoreAfter.overall - report.score.overall} pontos |
636
+ ${antiPatternsSection}${couplingSection}${unterstedDebtSection}
637
+
638
+ ## Roadmap de Refatoração
639
+
640
+ Prioridade por impacto:
641
+
642
+ ${plan.steps.slice(0, 8).map((step, idx) => `
643
+ ${idx + 1}. **${step.title}** — ${step.description}
644
+ - Tier: ${step.tier === 1 ? 'Crítico' : 'Importante'}
645
+ - Prioridade: ${step.priority}
646
+ `).join('\n')}
647
+
648
+ ${plan.steps.length > 8 ? `
649
+ ... e mais ${plan.steps.length - 8} steps no plano completo.
650
+ ` : ''}
651
+
652
+ ## Metas de Score
653
+
654
+ \`\`\`
655
+ Score Atual: ${report.score.overall}/100
656
+ Meta Curto Prazo: ${Math.min(100, report.score.overall + 5)}/100
657
+ Meta Médio Prazo: ${Math.min(100, report.score.overall + 10)}/100
658
+ Mínimo Aceitável: ${config.scoreThreshold}/100
659
+ \`\`\`
660
+
661
+ ## Regras
662
+
663
+ \`\`\`
664
+ □ Score NUNCA pode regredir após um PR
665
+ □ Mínimo: ${config.scoreThreshold}/100
666
+ □ Críticos: resolver dentro de 1 sprint
667
+ □ Altos: resolver dentro de 2 sprints
668
+ □ Médios: adicionar ao backlog técnico
669
+ □ Verificar com: architect score ./src
670
+ \`\`\`
671
+
672
+ ${crossRef('tech-debt', ctx)}
673
+
674
+ ---
675
+
676
+ **Gerado por Architect v3.1**
677
+ `;
678
+ }
679
+
680
+ export function generateCodeReviewChecklist(ctx: TemplateContext | EnrichedTemplateContext): string {
681
+ const { projectName, config, stack } = ctx;
682
+ const enriched = getEnriched(ctx);
683
+
684
+ // Domain-specific review items
685
+ const domainReviewItems = enriched.domain
686
+ ? `
687
+ ## Itens de Revisão Específicos do Domínio: ${enriched.domain.domain}
688
+
689
+ ${enriched.domain.domain === 'fintech' || enriched.domain.domain === 'payments'
690
+ ? `□ Transações são idempotentes?
691
+ □ Auditoria completa de todas as operações?
692
+ □ Sem exposição de dados sensíveis em logs?
693
+ □ Valores monetários não usam float (usar Decimal)?
694
+ □ PCI-DSS compliance verificado?`
695
+ : enriched.domain.domain === 'healthtech'
696
+ ? `□ LGPD compliance verificado (consentimento, retenção)?
697
+ □ Dados sensíveis criptografados em repouso?
698
+ □ Acesso auditado e logado?
699
+ □ Anonimização implementada corretamente?
700
+ □ 2FA em operações sensíveis?`
701
+ : enriched.domain.domain === 'e-commerce'
702
+ ? `□ Carrinho é idempotente?
703
+ □ Inventário é atualizado corretamente (race conditions)?
704
+ □ Preços são validados (sem manipulação client-side)?
705
+ □ Cupons/descontos aplicados corretamente?
706
+ □ Fraude detection implementado?`
707
+ : `□ Fluxo crítico de negócio não quebrou?
708
+ □ Rollback é seguro?
709
+ □ Concorrência tratada?
710
+ □ State final é consistente?`}
711
+ `
712
+ : '';
713
+
714
+ // Stack-specific review items
715
+ const stackReviewItems = `
716
+ ## Checklist Específico para ${stack.primary}
717
+
718
+ ${stack.primary === 'TypeScript' || stack.primary === 'JavaScript'
719
+ ? `□ \`strict: true\` em tsconfig (sem any sem justificativa)?
720
+ □ Imports circulares?
721
+ □ Async/await tratado (sem unhandled promises)?
722
+ □ Memory leaks (EventListeners desinscritos)?
723
+ □ Console.log/debugger removidos?`
724
+ : stack.primary === 'Python'
725
+ ? `□ Type hints em todas as funções públicas?
726
+ □ Docstrings formatadas (Google ou NumPy style)?
727
+ □ Sem mutable default arguments?
728
+ □ Context managers usados para resources?
729
+ □ F-strings em vez de % ou .format()?
730
+ □ Sem \`eval()\` ou \`exec()\`?`
731
+ : stack.primary === 'Go'
732
+ ? `□ Erros tratados (não ignorados com _)?
733
+ □ Defer para cleanup?
734
+ □ Goroutines com contexto?
735
+ □ Race conditions testadas?
736
+ □ Timeouts implementados?`
737
+ : stack.primary === 'Dart'
738
+ ? `□ Null-safety (! evitado)?
739
+ □ Widgets têm keys quando em listas?
740
+ □ BuildContext acessado apenas em build?
741
+ □ Listeners desinscritos?
742
+ □ Imagens/assets fazem lazy-load?`
743
+ : `□ Código segue padrões do projeto?
744
+ □ Dependencies atualizadas?
745
+ □ Sem warnings do compilador/linter?`}
746
+ `;
747
+
748
+ // Integration/endpoint specific items
749
+ const integrationReviewItems = enriched.endpoints && enriched.endpoints.length > 0
750
+ ? `
751
+ ## Itens de Revisão de Integração
752
+
753
+ □ Endpoint trata todos os status codes esperados?
754
+ □ Validação do payload de entrada?
755
+ ${enriched.endpoints.some(e => e.hasAuth) ? '□ Autenticação/autorização verificadas?' : ''}
756
+ ${enriched.endpoints.some(e => e.hasValidation) ? '□ Validação de input implementada?' : ''}
757
+ □ Resposta segue o contrato documentado?
758
+ □ Erros retornam mensagens claras?
759
+ □ Rate limiting aplicado?
760
+ □ Logging estruturado?
761
+ `
762
+ : '';
763
+
764
+ return `---
765
+ antigravity:
766
+ trigger: 'on_demand'
767
+ description: 'Code Review Checklist — Pontos obrigatórios de revisão'
768
+ ---
769
+
770
+ # 🔍 CODE REVIEW CHECKLIST — ${projectName}
771
+
772
+ ${depthIndicator(ctx)}
773
+
774
+ > **Todo PR deve ser verificado contra este checklist.**
775
+
776
+ ## Obrigatório
777
+
778
+ \`\`\`
779
+ □ Código compila sem erros
780
+ □ Todos os testes passam
781
+ □ Cobertura ≥ ${config.coverageMinimum}%
782
+ □ Lint sem errors
783
+ □ Nenhum secret hardcoded
784
+ □ Score não regrediu
785
+ \`\`\`
786
+
787
+ ## Funcional
788
+
789
+ \`\`\`
790
+ □ Atende aos critérios de aceite
791
+ □ Edge cases tratados
792
+ □ Erros tratados adequadamente
793
+ □ Não quebra features existentes
794
+ \`\`\`
795
+
796
+ ## Qualidade
797
+
798
+ \`\`\`
799
+ □ Código legível sem comentários explicativos
800
+ □ Naming descritivo e consistente
801
+ □ Sem duplicação (DRY)
802
+ □ Sem magic numbers
803
+ □ Sem any / type: ignore injustificado
804
+ □ Arquivos < 500 linhas
805
+ \`\`\`
806
+
807
+ ## Segurança
808
+
809
+ \`\`\`
810
+ □ Inputs validados
811
+ □ Queries parametrizadas
812
+ □ Auth/authz verificados
813
+ □ Dados sensíveis protegidos
814
+ \`\`\`
815
+ ${stackReviewItems}${domainReviewItems}${integrationReviewItems}
816
+
817
+ ${crossRef('code-review', ctx)}
818
+
819
+ ---
820
+
821
+ **Gerado por Architect v3.1**
822
+ `;
823
+ }
824
+
825
+ export function generateDatabaseAgent(ctx: TemplateContext | EnrichedTemplateContext): string {
826
+ const { projectName, config, stack } = ctx;
827
+ const enriched = getEnriched(ctx);
828
+
829
+ // Detect ORM/database framework
830
+ const dbFramework = stack.frameworks.filter(f =>
831
+ ['TypeORM', 'Prisma', 'SQLAlchemy', 'Django ORM', 'Sequelize', 'Knex'].includes(f)
832
+ ).join(', ') || 'SQL';
833
+
834
+ // Build business entities section
835
+ const entitiesSection = enriched.domain && enriched.domain.businessEntities && enriched.domain.businessEntities.length > 0
836
+ ? `
837
+ ## Entidades de Negócio (Entity Relationship)
838
+
839
+ ${enriched.domain.businessEntities.map(e => `
840
+ ### ${e.name}
841
+ **Camada:** ${e.layer} | **Fonte:** \`${e.source}\`
842
+
843
+ **Campos:**
844
+ ${e.fields.map(f => `- ${f}`).join('\n')}
845
+
846
+ **Relacionamentos:**
847
+ ${e.relationships.length > 0 ? e.relationships.map(r => `- ${r}`).join('\n') : '- Nenhum'}
848
+ `).join('\n')}
849
+ `
850
+ : '';
851
+
852
+ // Migration strategy based on framework
853
+ const migrationStrategy = `
854
+ ## Estratégia de Migrations
855
+
856
+ ### Framework: ${dbFramework}
857
+
858
+ ${dbFramework.includes('TypeORM')
859
+ ? `\`\`\`bash
860
+ # Criar migration
861
+ npm run typeorm migration:generate -- -n DescricaoDaMigracao
862
+
863
+ # Executar
864
+ npm run typeorm migration:run
865
+
866
+ # Reverter
867
+ npm run typeorm migration:revert
868
+ \`\`\`
869
+
870
+ **Padrão:**
871
+ - Uma migration por feature
872
+ - Naming: \`YYYY-MM-DD-HH-mm-ss-description.ts\`
873
+ - Ambos up() e down() implementados
874
+ - Testar reverter em staging antes de produção`
875
+ : dbFramework.includes('Prisma')
876
+ ? `\`\`\`bash
877
+ # Criar migration
878
+ npx prisma migrate dev --name DescricaoDaMigracao
879
+
880
+ # Produção
881
+ npx prisma migrate deploy
882
+ \`\`\`
883
+
884
+ **Padrão:**
885
+ - Schema.prisma é source of truth
886
+ - Migrations em \`prisma/migrations/\`
887
+ - Sempre testar \`prisma migrate resolve\` se houver problema
888
+ - Usar \`@relation\` para relacionamentos`
889
+ : dbFramework.includes('SQLAlchemy')
890
+ ? `\`\`\`bash
891
+ # Criar migration
892
+ alembic revision --autogenerate -m "description"
893
+
894
+ # Executar
895
+ alembic upgrade head
896
+
897
+ # Reverter
898
+ alembic downgrade -1
899
+ \`\`\`
900
+
901
+ **Padrão:**
902
+ - Alembic em \`alembic/versions/\`
903
+ - Sempre revisar .py autogenerado
904
+ - Testar em staging antes de produção`
905
+ : `\`\`\`bash
906
+ # Criar arquivos .sql com:
907
+ -- migrations/001-create-table.up.sql
908
+ -- migrations/001-create-table.down.sql
909
+ \`\`\`
910
+
911
+ **Padrão:**
912
+ - Um arquivo up/down por migration
913
+ - Idempotent (IF NOT EXISTS, etc.)
914
+ - Testar reverter`}
915
+ `;
916
+
917
+ // Indexing strategy
918
+ const indexingStrategy = `
919
+ ## Estratégia de Indexing
920
+
921
+ ### Índices Obrigatórios:
922
+
923
+ \`\`\`
924
+ □ PRIMARY KEY em toda tabela
925
+ □ FOREIGN KEYS entre entidades relacionadas
926
+ □ Índice em campos usados em WHERE frequente
927
+ □ Índice em campos de JOIN
928
+ □ Índice em campos de ORDER BY
929
+ \`\`\`
930
+
931
+ ### Exemplo:
932
+
933
+ \`\`\`sql
934
+ -- Por frequência de query
935
+ CREATE INDEX idx_user_email ON users(email);
936
+ CREATE INDEX idx_order_user_id ON orders(user_id);
937
+ CREATE INDEX idx_order_status_created ON orders(status, created_at);
938
+
939
+ -- Composto para filtros múltiplos
940
+ CREATE INDEX idx_order_user_status ON orders(user_id, status);
941
+ \`\`\`
942
+
943
+ ### Cuidado:
944
+
945
+ \`\`\`
946
+ □ Não criar índice para CADA coluna (overhead)
947
+ □ Medir com EXPLAIN PLAN antes/depois
948
+ □ Índices consomem storage e memória
949
+ □ Atualizar índices em ALTER TABLE é lento
950
+ \`\`\`
951
+ `;
952
+
953
+ // Build domain patterns section with conditional content
954
+ let domainPatternsContent = '';
955
+ if (enriched.domain) {
956
+ if (enriched.domain.domain === 'fintech' || enriched.domain.domain === 'payments') {
957
+ domainPatternsContent = `### Requisitos:
958
+ - **Audit Trail:** TODA transação registrada com timestamp/user
959
+ - **Soft Deletes:** Nunca deletar, marcar como inativo
960
+ - **Idempotência:** Transação com mesmo ID é processada 1x
961
+ - **Timestamps:** created_at, updated_at, deleted_at em todas as tabelas
962
+ - **Denormalização:** Guardar valor em repouso na transação
963
+
964
+ ### Exemplo Schema:
965
+ \`\`\`sql
966
+ CREATE TABLE transactions (
967
+ id UUID PRIMARY KEY,
968
+ user_id UUID NOT NULL REFERENCES users(id),
969
+ amount DECIMAL(19,2) NOT NULL,
970
+ status VARCHAR(20) NOT NULL, -- PENDING, COMPLETED, FAILED
971
+ idempotency_key VARCHAR(255) UNIQUE, -- para replay-safety
972
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
973
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
974
+ deleted_at TIMESTAMP NULL
975
+ );
976
+
977
+ CREATE TABLE transaction_audit (
978
+ id UUID PRIMARY KEY,
979
+ transaction_id UUID REFERENCES transactions(id),
980
+ action VARCHAR(50),
981
+ user_id UUID,
982
+ old_value JSONB,
983
+ new_value JSONB,
984
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
985
+ );
986
+ \`\`\``;
987
+ } else if (enriched.domain.domain === 'healthtech') {
988
+ domainPatternsContent = `### Requisitos:
989
+ - **Criptografia:** Dados sensíveis criptografados em repouso
990
+ - **Anonimização:** Poder remover PII mantendo histórico
991
+ - **Retention:** Política de retenção de dados
992
+ - **Access Logs:** Quem acessou o que, quando
993
+ - **Consentimento:** Rastrear consentimento de paciente
994
+
995
+ ### Exemplo Schema:
996
+ \`\`\`sql
997
+ CREATE TABLE patients (
998
+ id UUID PRIMARY KEY,
999
+ name_encrypted BYTEA NOT NULL, -- criptografado
1000
+ ssn_encrypted BYTEA NOT NULL,
1001
+ created_at TIMESTAMP,
1002
+ deleted_at TIMESTAMP NULL
1003
+ );
1004
+
1005
+ CREATE TABLE access_logs (
1006
+ id UUID PRIMARY KEY,
1007
+ patient_id UUID REFERENCES patients(id),
1008
+ accessed_by UUID REFERENCES users(id),
1009
+ accessed_at TIMESTAMP,
1010
+ data_type VARCHAR(50),
1011
+ purpose VARCHAR(100)
1012
+ );
1013
+
1014
+ CREATE TABLE consents (
1015
+ id UUID PRIMARY KEY,
1016
+ patient_id UUID REFERENCES patients(id),
1017
+ type VARCHAR(50),
1018
+ granted_at TIMESTAMP,
1019
+ expires_at TIMESTAMP
1020
+ );
1021
+ \`\`\``;
1022
+ } else if (enriched.domain.domain === 'e-commerce') {
1023
+ domainPatternsContent = `### Requisitos:
1024
+ - **Inventário:** Stock é crítico (race condition)
1025
+ - **Preços:** Histórico de preço por produto
1026
+ - **Pedidos:** Snapshot do preço no momento da venda
1027
+ - **Cupons:** Validação e uso limitado
1028
+ - **Pagamento:** Separado de pedido (pode estar pendente)
1029
+
1030
+ ### Exemplo Schema:
1031
+ \`\`\`sql
1032
+ CREATE TABLE products (
1033
+ id UUID PRIMARY KEY,
1034
+ name VARCHAR(255),
1035
+ price DECIMAL(19,2), -- preço atual
1036
+ stock INT DEFAULT 0
1037
+ );
1038
+
1039
+ CREATE TABLE product_prices (
1040
+ id UUID PRIMARY KEY,
1041
+ product_id UUID REFERENCES products(id),
1042
+ price DECIMAL(19,2),
1043
+ effective_from TIMESTAMP,
1044
+ effective_to TIMESTAMP NULL
1045
+ );
1046
+
1047
+ CREATE TABLE orders (
1048
+ id UUID PRIMARY KEY,
1049
+ user_id UUID REFERENCES users(id),
1050
+ total DECIMAL(19,2),
1051
+ status VARCHAR(20),
1052
+ created_at TIMESTAMP
1053
+ );
1054
+
1055
+ CREATE TABLE order_items (
1056
+ id UUID PRIMARY KEY,
1057
+ order_id UUID REFERENCES orders(id),
1058
+ product_id UUID REFERENCES products(id),
1059
+ quantity INT,
1060
+ price_at_purchase DECIMAL(19,2) -- snapshot
1061
+ );
1062
+ \`\`\``;
1063
+ } else {
1064
+ domainPatternsContent = `### Requisitos Genéricos:
1065
+ - Timestamps: created_at, updated_at
1066
+ - Soft deletes: deleted_at (se aplicável)
1067
+ - Índices em ForeignKeys
1068
+ - Constraints em integridade`;
1069
+ }
1070
+ }
1071
+
1072
+ const domainPatternsSection = enriched.domain
1073
+ ? `
1074
+ ## Padrões de Dados Específicos do Domínio: ${enriched.domain.domain}
1075
+
1076
+ ${domainPatternsContent}
1077
+ `
1078
+ : '';
1079
+
1080
+ // Compliance section
1081
+ const complianceSection = enriched.domain && enriched.domain.compliance && enriched.domain.compliance.length > 0
1082
+ ? `
1083
+ ## Compliance & Dados
1084
+
1085
+ ${enriched.domain.compliance.map(c => `### ${c.name}
1086
+ ${c.mandatoryChecks.map(check => `- □ ${check}`).join('\n')}
1087
+ `).join('\n')}
1088
+ `
1089
+ : '';
1090
+
1091
+ return `---
1092
+ antigravity:
1093
+ trigger: 'on_demand'
1094
+ description: 'Database Engineer — Schema, migrations, performance'
1095
+ agent_card:
1096
+ id: 'database-engineer'
1097
+ name: 'Database Engineer'
1098
+ role: 'development'
1099
+ capabilities: [schema-design, migration-management, indexing, query-optimization]
1100
+ inputs: [entity-model, business-rules, performance-requirements]
1101
+ outputs: [migrations, indexes, seeds, query-optimization]
1102
+ depends_on: []
1103
+ version: 3.1.0
1104
+ ---
1105
+
1106
+ # 🗄️ DATABASE ENGINEER
1107
+
1108
+ ${depthIndicator(ctx)}
1109
+
1110
+ > Schema design, migrations, e performance para ${projectName}
1111
+ ${entitiesSection}${migrationStrategy}${indexingStrategy}${domainPatternsSection}${complianceSection}
1112
+
1113
+ ## Regras Gerais
1114
+
1115
+ \`\`\`
1116
+ □ TODA migration deve ser reversível (up + down)
1117
+ □ Índices para queries frequentes (validar com EXPLAIN)
1118
+ □ Foreign keys onde há relacionamento
1119
+ □ Constraints (NOT NULL, UNIQUE, CHECK) por negócio
1120
+ □ Sem ALTER TABLE em tabelas grandes sem plano
1121
+ □ Seed data atualizado para dev/test
1122
+ □ Queries otimizadas (sem N+1, sem full scan)
1123
+ □ Performance de migrations testada em staging
1124
+ \`\`\`
1125
+
1126
+ ${crossRef('database-engineer', ctx)}
1127
+
1128
+ ---
1129
+
1130
+ **Gerado por Architect v3.1**
1131
+ `;
1132
+ }
1133
+
1134
+ export function generateMobileAgent(ctx: TemplateContext | EnrichedTemplateContext): string {
1135
+ const { projectName, config, stack } = ctx;
1136
+ const enriched = getEnriched(ctx);
1137
+
1138
+ // Build endpoints for mobile integration
1139
+ const endpointsSection = enriched.endpoints && enriched.endpoints.length > 0
1140
+ ? `
1141
+ ## Endpoints para Integração Mobile
1142
+
1143
+ ${enriched.endpoints.slice(0, 12).map(e => `- \`${e.method}\` \`${e.path}\` — ${e.handler}`).join('\n')}
1144
+ ${enriched.endpoints.length > 12 ? `\n... e mais ${enriched.endpoints.length - 12} endpoints. Ver documento de integração.` : ''}
1145
+ `
1146
+ : '';
1147
+
1148
+ // Build modules structure
1149
+ const modulesSection = enriched.modules && enriched.modules.length > 0
1150
+ ? `
1151
+ ## Estrutura de Módulos
1152
+
1153
+ ${enriched.modules.map(m => `- \`${m.path}\` — ${m.description}`).join('\n')}
1154
+ `
1155
+ : '';
1156
+
1157
+ // Build domain-specific mobile considerations
1158
+ let domainMobileContent = '';
1159
+ if (enriched.domain) {
1160
+ if (enriched.domain.domain === 'fintech' || enriched.domain.domain === 'payments') {
1161
+ domainMobileContent = `### Screens Críticas:
1162
+ - **Carteira:** Saldo disponível, histórico de transações
1163
+ - **Enviar Dinheiro:** Validação de conta destino, confirmação
1164
+ - **Pagamentos:** 2FA, biometria, confirmação final
1165
+ - **Segurança:** Definir PIN, mudar senha, 2FA setup
1166
+
1167
+ ### Estados Especiais:
1168
+ - Offline: Mostrar saldo em cache, desabilitar transações
1169
+ - Sincronizando: Indicator de atualização
1170
+ - Erro de rede: Retry com backoff exponencial
1171
+ - Transação pendente: Status em tempo real`;
1172
+ } else if (enriched.domain.domain === 'healthtech') {
1173
+ domainMobileContent = `### Screens Críticas:
1174
+ - **Prontuário:** Histórico médico, medicações
1175
+ - **Agendamento:** Calendário, confirmação SMS
1176
+ - **Consulta:** Receitas, encaminhamentos
1177
+ - **Privacidade:** Consentimento, biometria
1178
+
1179
+ ### Estados Especiais:
1180
+ - Offline: Dados sincronizam quando online
1181
+ - Dados sensíveis: Sempre requer biometria
1182
+ - Consulta em andamento: Status em tempo real
1183
+ - Privacidade: Diálogos de consentimento antes de acessar`;
1184
+ } else if (enriched.domain.domain === 'e-commerce') {
1185
+ domainMobileContent = `### Screens Críticas:
1186
+ - **Catálogo:** Filtros, busca, avaliações
1187
+ - **Carrinho:** Quantidade, preço atualizado, cupom
1188
+ - **Checkout:** Endereço, cartão, 3D Secure
1189
+ - **Pedidos:** Status, rastreamento, devolução
1190
+
1191
+ ### Estados Especiais:
1192
+ - Offline: Carrinho em cache, sincroniza depois
1193
+ - Estoque zerado: Mostrar de forma clara
1194
+ - Frete: Calcular por CEP em tempo real
1195
+ - Promoção: Aplicar cupom com feedback imediato`;
1196
+ } else {
1197
+ domainMobileContent = `### Screens Padrão:
1198
+ - Lista: Com busca, filtro, paginação
1199
+ - Detalhe: Completo com ações
1200
+ - Formulário: Validação em tempo real
1201
+ - Confirmação: Antes de ação crítica
1202
+
1203
+ ### Estados Especiais:
1204
+ - Loading: Skeleton ou spinner
1205
+ - Empty: Mensagem clara
1206
+ - Error: Com retry
1207
+ - Offline: Modo read-only`;
1208
+ }
1209
+ }
1210
+
1211
+ const domainSection = enriched.domain
1212
+ ? `
1213
+ ## Considerações de UX por Domínio: ${enriched.domain.domain}
1214
+
1215
+ ${domainMobileContent}
1216
+ `
1217
+ : '';
1218
+
1219
+ return `---
1220
+ antigravity:
1221
+ trigger: 'on_demand'
1222
+ globs: ['**/*.dart']
1223
+ description: 'Flutter UI Developer — Screens, widgets, navegação'
1224
+ agent_card:
1225
+ id: 'flutter-ui-developer'
1226
+ name: 'Flutter UI Developer'
1227
+ role: 'development'
1228
+ capabilities: [screen-development, widget-composition, navigation, api-integration, state-management]
1229
+ inputs: [mockup, integration-doc, user-story]
1230
+ outputs: [screens, widgets, services, tests]
1231
+ depends_on: [orchestrator]
1232
+ version: 3.1.0
1233
+ ---
1234
+
1235
+ # 📱 FLUTTER UI DEVELOPER
1236
+
1237
+ ${depthIndicator(ctx)}
1238
+
1239
+ > Screens mobile, widgets, navegação para ${projectName}
1240
+
1241
+ ## Stack
1242
+
1243
+ - **Framework:** Flutter / Dart
1244
+ - **Package Manager:** ${stack.packageManager}
1245
+ - **Teste:** ${stack.testFramework}
1246
+
1247
+ ## Pré-Requisitos
1248
+
1249
+ \`\`\`
1250
+ □ MOCKUP do app aprovado (com todos os estados e fluxos)
1251
+ □ Documento de Integração disponível
1252
+ □ User stories com critérios de aceite
1253
+ □ Design system aprovado (cores, tipografia, componentes)
1254
+ \`\`\`
1255
+ ${modulesSection}${endpointsSection}${domainSection}
1256
+
1257
+ ## Regras
1258
+
1259
+ \`\`\`
1260
+ □ TODOS os estados: normal, loading, error, empty
1261
+ □ Padrão visual do app (cores, fontes, espaçamentos) consistente
1262
+ □ Navegação consistente (back button, deep link funcionando)
1263
+ □ Sem lógica de negócio em widgets (usar ChangeNotifier/Bloc)
1264
+ □ ListView.builder para listas longas (NUNCA Column com itens dinâmicos)
1265
+ □ Offline graceful quando aplicável (cache local)
1266
+ □ Imagens com lazy-load e placeholder
1267
+ □ Screens responsivas (testar orientação portrait + landscape)
1268
+ □ Acessibilidade (Semantics, labels)
1269
+ □ Cobertura ≥ ${config.coverageMinimum}%
1270
+ \`\`\`
1271
+
1272
+ ## Estrutura de Projeto
1273
+
1274
+ \`\`\`
1275
+ lib/
1276
+ ├── main.dart
1277
+ ├── models/
1278
+ │ └── [domain].dart
1279
+ ├── screens/
1280
+ │ └── [feature]/
1281
+ │ ├── [feature]_screen.dart
1282
+ │ └── widgets/
1283
+ │ └── [component].dart
1284
+ ├── services/
1285
+ │ └── api_service.dart
1286
+ └── __tests__/
1287
+ └── [feature]_test.dart
1288
+ \`\`\`
1289
+
1290
+ ${crossRef('flutter', ctx)}
1291
+
1292
+ ---
1293
+
1294
+ **Gerado por Architect v3.1**
1295
+ `;
1296
+ }