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