@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,634 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, statSync } from 'fs';
2
+ import { join } from 'path';
3
+ import { AnalysisReport, RefactoringPlan } from '../types.js';
4
+ import {
5
+ StackInfo,
6
+ AgentAuditFinding,
7
+ AgentItem,
8
+ AgentItemStatus,
9
+ AgentSuggestion,
10
+ TemplateContext,
11
+ EnrichedTemplateContext,
12
+ DomainInsights,
13
+ ModuleDetail,
14
+ DetectedEndpoint,
15
+ FrameworkInfo,
16
+ DetectedToolchain,
17
+ AgentGeneratorConfig,
18
+ DEFAULT_AGENT_CONFIG,
19
+ } from './types.js';
20
+ import { StackDetector } from './stack-detector.js';
21
+ import { ContextEnricher } from './context-enricher.js';
22
+
23
+ // ── Core Templates (Enterprise-Grade) ──
24
+ import { generateIndexMd } from './templates/core/index-md.js';
25
+ import { generateOrchestrator } from './templates/core/orchestrator.js';
26
+ import { generatePreflight } from './templates/core/preflight.js';
27
+ import { generateQualityGates } from './templates/core/quality-gates.js';
28
+ import { generateGeneralRules } from './templates/core/general-rules.js';
29
+ import { generateArchitectureRules } from './templates/core/architecture-rules.js';
30
+ import { generateSecurityRules } from './templates/core/security-rules.js';
31
+ import { generateNewFeatureWorkflow } from './templates/core/workflow-new-feature.js';
32
+ import { generateFixBugWorkflow } from './templates/core/workflow-fix-bug.js';
33
+ import { generateReviewWorkflow } from './templates/core/workflow-review.js';
34
+ import {
35
+ generateBackendAgent,
36
+ generateFrontendAgent,
37
+ generateSecurityAgent,
38
+ generateQAAgent,
39
+ generateTechDebtAgent,
40
+ generateCodeReviewChecklist,
41
+ generateDatabaseAgent,
42
+ generateMobileAgent,
43
+ } from './templates/core/agents.js';
44
+
45
+ // ── Stack-Specific Templates ──
46
+ import { generateStackRules, getStackRuleFileName } from './templates/stack/index.js';
47
+
48
+ // ── Domain Templates ──
49
+ import {
50
+ generateC4Template,
51
+ generateBddTemplate,
52
+ generateTddTemplate,
53
+ generateAdrTemplate,
54
+ generateThreatModelTemplate,
55
+ } from './templates/domain/index.js';
56
+
57
+ // ── Skills Generator ──
58
+ import { generateProjectSkills, generateArchitectIntegrationSkill, generateCIPipelineSkill, generateMonorepoGuideSkill } from './templates/core/skills-generator.js';
59
+
60
+ // ── Hooks Generator ──
61
+ import { generatePreCommitHook, generatePrePushHook, generatePostAnalysisHook } from './templates/core/hooks-generator.js';
62
+
63
+ // Re-export types for backward compatibility
64
+ export type { StackInfo, AgentAuditFinding, AgentItem, AgentItemStatus, AgentSuggestion, EnrichedTemplateContext, DomainInsights, ModuleDetail, DetectedEndpoint, FrameworkInfo, DetectedToolchain };
65
+
66
+ /**
67
+ * Agent Generator v3.1 — Enterprise-Grade
68
+ *
69
+ * Generates or audits .agent/ directories with enterprise-grade
70
+ * agent frameworks: detailed workflows, approval gates, quality enforcement,
71
+ * stack-specific agents, and domain templates.
72
+ */
73
+ export class AgentGenerator {
74
+ private stackDetector = new StackDetector();
75
+ private contextEnricher = new ContextEnricher();
76
+
77
+ /** Max lines for any single generated .agent file */
78
+ private static readonly MAX_FILE_LINES = 500;
79
+
80
+ /** Paths that indicate third-party code — filter from agent context */
81
+ private static readonly EXCLUDED_SEGMENTS = [
82
+ 'node_modules', '/dist/', '/build/', '/coverage/',
83
+ '/.next/', '/venv/', '/__pycache__/', '/target/',
84
+ ];
85
+
86
+ /**
87
+ * Sanitize the report before passing to agent generation.
88
+ * Removes anti-patterns, dependency nodes, and suggestions
89
+ * that reference node_modules or build artifacts.
90
+ */
91
+ private sanitizeReport(report: AnalysisReport): AnalysisReport {
92
+ const isProjectPath = (path: string): boolean => {
93
+ const normalized = path.replace(/\\/g, '/');
94
+ return !AgentGenerator.EXCLUDED_SEGMENTS.some(seg => normalized.includes(seg));
95
+ };
96
+
97
+ return {
98
+ ...report,
99
+ antiPatterns: report.antiPatterns.filter(ap => {
100
+ if (!isProjectPath(ap.location)) return false;
101
+ if (ap.affectedFiles?.some(f => !isProjectPath(f))) {
102
+ // Keep the pattern but clean affected files
103
+ ap.affectedFiles = ap.affectedFiles.filter(f => isProjectPath(f));
104
+ }
105
+ return true;
106
+ }),
107
+ dependencyGraph: {
108
+ nodes: report.dependencyGraph.nodes.filter(n => isProjectPath(n)),
109
+ edges: report.dependencyGraph.edges.filter(
110
+ e => isProjectPath(e.from) && isProjectPath(e.to)
111
+ ),
112
+ },
113
+ suggestions: report.suggestions.filter(
114
+ s => !s.description.includes('node_modules')
115
+ ),
116
+ };
117
+ }
118
+
119
+ /**
120
+ * Cap content to max lines to prevent oversized agent files.
121
+ */
122
+ private capContent(content: string): string {
123
+ const lines = content.split('\n');
124
+ if (lines.length <= AgentGenerator.MAX_FILE_LINES) return content;
125
+
126
+ const truncated = lines.slice(0, AgentGenerator.MAX_FILE_LINES);
127
+ truncated.push('');
128
+ truncated.push('<!-- Content truncated at ' + AgentGenerator.MAX_FILE_LINES + ' lines. Run `architect agents` to regenerate. -->');
129
+ return truncated.join('\n');
130
+ }
131
+
132
+ /**
133
+ * Suggest agents without writing files — for unified report.
134
+ */
135
+ suggest(
136
+ report: AnalysisReport,
137
+ plan: RefactoringPlan,
138
+ projectPath: string,
139
+ ): AgentSuggestion {
140
+ const cleanReport = this.sanitizeReport(report);
141
+ const stack = this.stackDetector.detect(cleanReport);
142
+ const agentDir = join(projectPath, '.agent');
143
+ const isExisting = existsSync(agentDir);
144
+
145
+ const existingFiles = (subdir: string): Set<string> => {
146
+ const dir = join(agentDir, subdir);
147
+ if (!existsSync(dir)) return new Set();
148
+ return new Set(readdirSync(dir).map(f => f.replace(/\.md$/, '')));
149
+ };
150
+
151
+ let audit: AgentAuditFinding[] = [];
152
+ if (isExisting) {
153
+ audit = this.auditExisting(agentDir, stack, report, plan);
154
+ }
155
+
156
+ const ctx = this.buildContext(cleanReport, plan, stack, projectPath);
157
+
158
+ const existingAgents = existingFiles('agents');
159
+ const existingRules = existingFiles('rules');
160
+ const existingGuards = existingFiles('guards');
161
+ const existingWorkflows = existingFiles('workflows');
162
+ const existingSkillsDir = join(agentDir, 'skills');
163
+ const existingSkillNames = existsSync(existingSkillsDir)
164
+ ? new Set(readdirSync(existingSkillsDir).filter(f => {
165
+ try { return statSync(join(existingSkillsDir, f)).isDirectory(); } catch { return false; }
166
+ }))
167
+ : new Set<string>();
168
+
169
+ const itemStatus = (name: string, existing: Set<string>): AgentItemStatus => {
170
+ const found = [...existing].some(e => e.toLowerCase() === name.toLowerCase());
171
+ if (!found) return 'CREATE';
172
+ const hasImprovement = audit.some(
173
+ f => f.file.toLowerCase().includes(name.toLowerCase()) && (f.type === 'IMPROVEMENT' || f.type === 'OUTDATED')
174
+ );
175
+ return hasImprovement ? 'MODIFY' : 'KEEP';
176
+ };
177
+
178
+ // ── Agent definitions ──
179
+ const agentDefs: { name: string; desc: string }[] = [
180
+ { name: 'AGENT-ORCHESTRATOR', desc: 'Centro de comando — decompõe requisições, enforça gates, coordena agentes' },
181
+ ];
182
+ if (stack.hasBackend) agentDefs.push({
183
+ name: `${stack.primary.toUpperCase()}-BACKEND-DEVELOPER`,
184
+ desc: `Especialista em ${stack.primary} — APIs, serviços, lógica de negócio, integration docs`,
185
+ });
186
+ if (stack.hasFrontend) {
187
+ const FRONTEND_FWS = ['Angular', 'Vue', 'Vue.js', 'Next.js', 'React', 'Nuxt', 'Svelte', 'Remix'];
188
+ const detectedFw = ctx.detectedFrameworks?.find(f => FRONTEND_FWS.includes(f.name));
189
+ const fw = detectedFw?.name ||
190
+ stack.frameworks.find(f => FRONTEND_FWS.includes(f)) || 'FRONTEND';
191
+ agentDefs.push({
192
+ name: `${fw.toUpperCase().replace('.', '').replace(/\s/g, '-')}-FRONTEND-DEVELOPER`,
193
+ desc: `Componentes ${fw}, state management, UX responsiva, todos os estados UI`,
194
+ });
195
+ }
196
+ if (stack.hasMobile) agentDefs.push({
197
+ name: 'FLUTTER-UI-DEVELOPER',
198
+ desc: 'Screens mobile, widgets, navegação, integração API, padrão visual do app',
199
+ });
200
+ if (stack.hasDatabase) agentDefs.push({
201
+ name: 'DATABASE-ENGINEER',
202
+ desc: 'Schema design, migrations reversíveis, indexação, performance de queries',
203
+ });
204
+ agentDefs.push(
205
+ { name: 'SECURITY-AUDITOR', desc: 'OWASP Top 10, STRIDE threat model, compliance, vulnerabilidades' },
206
+ { name: 'QA-TEST-ENGINEER', desc: 'BDD/TDD, cobertura mínima, planos de teste, regressão' },
207
+ { name: 'TECH-DEBT-CONTROLLER', desc: 'Score tracking, anti-patterns, refatorações, metas de qualidade' },
208
+ );
209
+
210
+ const ruleDefs: { name: string; desc: string }[] = [
211
+ { name: '00-general', desc: '9 Regras de Ouro, Git Flow, naming conventions, ações proibidas' },
212
+ { name: '01-architecture', desc: 'Separação de camadas, dependency rules, padrões de módulo' },
213
+ { name: '02-security', desc: 'Sanitização, secrets management, validação, OWASP' },
214
+ ];
215
+ const stackRuleName = getStackRuleFileName(ctx);
216
+ if (stackRuleName) {
217
+ const fwLabel = stack.frameworks[0] || stack.primary;
218
+ ruleDefs.push({ name: stackRuleName, desc: `Regras específicas ${fwLabel} — patterns, anti-patterns, checklist` });
219
+ }
220
+
221
+ const guardDefs = [
222
+ { name: 'PREFLIGHT', desc: '6-phase checklist pré-ação: ambiente → leitura → negócio → camada → commit → done' },
223
+ { name: 'QUALITY-GATES', desc: '3 níveis (CRITICAL/IMPORTANT/DESIRABLE), métricas, blockers, verificação em 4 estágios' },
224
+ { name: 'CODE-REVIEW-CHECKLIST', desc: 'Review em 6 dimensões: funcional, qualidade, testes, segurança, performance, arquitetura' },
225
+ ];
226
+
227
+ const workflowDefs = [
228
+ { name: 'new-feature', desc: '10 steps com 6 approval gates, mockup-first, backend-first, integration doc' },
229
+ { name: 'fix-bug', desc: '10 steps: diagnóstico → root cause → RED test → fix mínimo → regressão → docs' },
230
+ { name: 'review', desc: 'Code review em 6 dimensões com checklist estruturado' },
231
+ ];
232
+
233
+ // Build items
234
+ const suggestedAgents: AgentItem[] = agentDefs.map(({ name, desc }) => ({
235
+ name, status: itemStatus(name, existingAgents), description: desc,
236
+ }));
237
+ for (const existing of existingAgents) {
238
+ if (!agentDefs.some(d => d.name.toLowerCase() === existing.toLowerCase())) {
239
+ suggestedAgents.push({ name: existing, status: 'KEEP', reason: 'Custom agent', description: 'Agente customizado do projeto' });
240
+ }
241
+ }
242
+
243
+ const suggestedRules: AgentItem[] = ruleDefs.map(({ name, desc }) => ({
244
+ name, status: itemStatus(name, existingRules), description: desc,
245
+ }));
246
+ for (const existing of existingRules) {
247
+ if (!ruleDefs.some(d => d.name.toLowerCase() === existing.toLowerCase())) {
248
+ suggestedRules.push({ name: existing, status: 'KEEP', reason: 'Custom rule' });
249
+ }
250
+ }
251
+
252
+ const suggestedGuards: AgentItem[] = guardDefs.map(({ name, desc }) => ({
253
+ name, status: itemStatus(name, existingGuards), description: desc,
254
+ }));
255
+
256
+ const suggestedWorkflows: AgentItem[] = workflowDefs.map(({ name, desc }) => ({
257
+ name, status: itemStatus(name, existingWorkflows), description: desc,
258
+ }));
259
+ for (const existing of existingWorkflows) {
260
+ if (!workflowDefs.some(d => d.name.toLowerCase() === existing.toLowerCase())) {
261
+ suggestedWorkflows.push({ name: existing, status: 'KEEP', reason: 'Custom workflow' });
262
+ }
263
+ }
264
+
265
+ // Skills
266
+ const skillEntries = this.buildSkillEntries(stack, existingSkillNames);
267
+
268
+ return {
269
+ stack,
270
+ hasExistingAgents: isExisting,
271
+ suggestedAgents,
272
+ suggestedRules,
273
+ suggestedGuards,
274
+ suggestedWorkflows,
275
+ suggestedSkills: skillEntries,
276
+ audit,
277
+ command: `architect agents ${projectPath}`,
278
+ };
279
+ }
280
+
281
+ /**
282
+ * Generate or audit .agent/ directory for a project.
283
+ */
284
+ generate(
285
+ report: AnalysisReport,
286
+ plan: RefactoringPlan,
287
+ projectPath: string,
288
+ outputDir?: string
289
+ ): { generated: string[]; audit: AgentAuditFinding[] } {
290
+ const cleanReport = this.sanitizeReport(report);
291
+ const stack = this.stackDetector.detect(cleanReport);
292
+ const agentDir = outputDir || join(projectPath, '.agent');
293
+ const isExisting = existsSync(agentDir);
294
+
295
+ if (isExisting) {
296
+ const audit = this.auditExisting(agentDir, stack, cleanReport, plan);
297
+ const generated = this.generateMissing(agentDir, audit, cleanReport, plan, stack, projectPath);
298
+ return { generated, audit };
299
+ }
300
+
301
+ const generated = this.generateFull(agentDir, cleanReport, plan, stack, projectPath);
302
+ return { generated, audit: [] };
303
+ }
304
+
305
+ // ── Private: Build Template Context ──
306
+
307
+ private buildContext(report: AnalysisReport, plan: RefactoringPlan, stack: StackInfo, projectPath?: string): EnrichedTemplateContext {
308
+ if (projectPath) {
309
+ return this.contextEnricher.enrich(report, plan, stack, projectPath);
310
+ }
311
+ // Fallback to basic enriched context for backward compatibility
312
+ return {
313
+ report,
314
+ plan,
315
+ stack,
316
+ projectName: report.projectInfo.name || 'Project',
317
+ stackLabel: [...stack.languages, ...stack.frameworks].join(' + '),
318
+ config: DEFAULT_AGENT_CONFIG,
319
+ domain: {
320
+ domain: 'general',
321
+ subDomain: 'general',
322
+ description: '',
323
+ businessEntities: [],
324
+ compliance: [],
325
+ integrations: [],
326
+ keywords: [],
327
+ confidence: 0,
328
+ },
329
+ modules: [],
330
+ endpoints: [],
331
+ untestedModules: [],
332
+ criticalPaths: [],
333
+ projectDepth: 'small',
334
+ detectedFrameworks: [],
335
+ primaryFramework: null,
336
+ toolchain: {
337
+ buildCmd: 'echo "No build command detected"',
338
+ testCmd: 'echo "No test command detected"',
339
+ lintCmd: 'echo "No lint command detected"',
340
+ runCmd: 'echo "No run command detected"',
341
+ coverageCmd: 'echo "No coverage command detected"',
342
+ installCmd: 'echo "No install command detected"',
343
+ migrateCmd: null,
344
+ depsFile: 'unknown',
345
+ },
346
+ projectStructure: 'unknown',
347
+ };
348
+ }
349
+
350
+ // ── Private: Full Generation ──
351
+
352
+ private generateFull(agentDir: string, report: AnalysisReport, plan: RefactoringPlan, stack: StackInfo, projectPath: string): string[] {
353
+ const generated: string[] = [];
354
+ const ctx = this.buildContext(report, plan, stack, projectPath);
355
+
356
+ // Create directories
357
+ const dirs = ['agents', 'rules', 'guards', 'workflows', 'templates', 'skills', 'hooks'];
358
+ for (const d of dirs) mkdirSync(join(agentDir, d), { recursive: true });
359
+
360
+ // ── Core files (Enterprise-Grade) ──
361
+ const coreFiles: Record<string, string> = {
362
+ 'INDEX.md': generateIndexMd(ctx),
363
+ 'agents/AGENT-ORCHESTRATOR.md': generateOrchestrator(ctx),
364
+ 'guards/PREFLIGHT.md': generatePreflight(ctx),
365
+ 'guards/QUALITY-GATES.md': generateQualityGates(ctx),
366
+ 'guards/CODE-REVIEW-CHECKLIST.md': generateCodeReviewChecklist(ctx),
367
+ 'rules/00-general.md': generateGeneralRules(ctx),
368
+ 'rules/01-architecture.md': generateArchitectureRules(ctx),
369
+ 'rules/02-security.md': generateSecurityRules(ctx),
370
+ 'workflows/new-feature.md': generateNewFeatureWorkflow(ctx),
371
+ 'workflows/fix-bug.md': generateFixBugWorkflow(ctx),
372
+ 'workflows/review.md': generateReviewWorkflow(ctx),
373
+ };
374
+
375
+ // ── Stack-specific agents ──
376
+ if (stack.hasBackend) {
377
+ coreFiles[`agents/${stack.primary.toUpperCase()}-BACKEND-DEVELOPER.md`] = generateBackendAgent(ctx);
378
+ }
379
+ if (stack.hasFrontend) {
380
+ const FRONTEND_FWS = ['Angular', 'Vue', 'Vue.js', 'Next.js', 'React', 'Nuxt', 'Svelte', 'Remix'];
381
+ const detectedFw = ctx.detectedFrameworks?.find(f => FRONTEND_FWS.includes(f.name));
382
+ const fwName = detectedFw?.name ||
383
+ stack.frameworks.find(f => FRONTEND_FWS.includes(f)) || 'Frontend';
384
+ coreFiles[`agents/${fwName.toUpperCase().replace('.', '').replace(/\s/g, '-')}-FRONTEND-DEVELOPER.md`] = generateFrontendAgent(ctx);
385
+ }
386
+ if (stack.hasMobile) {
387
+ coreFiles['agents/FLUTTER-UI-DEVELOPER.md'] = generateMobileAgent(ctx);
388
+ }
389
+ if (stack.hasDatabase) {
390
+ coreFiles['agents/DATABASE-ENGINEER.md'] = generateDatabaseAgent(ctx);
391
+ }
392
+ coreFiles['agents/SECURITY-AUDITOR.md'] = generateSecurityAgent(ctx);
393
+ coreFiles['agents/QA-TEST-ENGINEER.md'] = generateQAAgent(ctx);
394
+ coreFiles['agents/TECH-DEBT-CONTROLLER.md'] = generateTechDebtAgent(ctx);
395
+
396
+ // ── Stack-specific rules ──
397
+ const stackRuleContent = generateStackRules(ctx);
398
+ const stackRuleFile = getStackRuleFileName(ctx);
399
+ if (stackRuleContent && stackRuleFile) {
400
+ coreFiles[`rules/${stackRuleFile}.md`] = stackRuleContent;
401
+ }
402
+
403
+ // ── Domain templates ──
404
+ coreFiles['templates/C4.md'] = generateC4Template(ctx);
405
+ coreFiles['templates/BDD.md'] = generateBddTemplate(ctx);
406
+ coreFiles['templates/TDD.md'] = generateTddTemplate(ctx);
407
+ coreFiles['templates/ADR.md'] = generateAdrTemplate(ctx);
408
+ coreFiles['templates/THREAT-MODEL.md'] = generateThreatModelTemplate(ctx);
409
+
410
+ // ── Project Skills (padrões detectados) ──
411
+ const skillsContent = generateProjectSkills(ctx);
412
+ if (skillsContent) {
413
+ coreFiles['skills/PROJECT-PATTERNS.md'] = skillsContent;
414
+ }
415
+
416
+ // ── Data-driven Skills (real project data) ──
417
+ coreFiles['skills/ARCHITECT-INTEGRATION.md'] = generateArchitectIntegrationSkill(ctx);
418
+ coreFiles['skills/CI-PIPELINE.md'] = generateCIPipelineSkill(ctx);
419
+
420
+ const monorepoGuide = generateMonorepoGuideSkill(ctx);
421
+ if (monorepoGuide) {
422
+ coreFiles['skills/MONOREPO-GUIDE.md'] = monorepoGuide;
423
+ }
424
+
425
+ // ── Executable Hooks ──
426
+ coreFiles['hooks/pre-commit.sh'] = generatePreCommitHook(ctx);
427
+ coreFiles['hooks/pre-push.sh'] = generatePrePushHook(ctx);
428
+ coreFiles['hooks/post-analysis.sh'] = generatePostAnalysisHook(ctx);
429
+
430
+ // ── Write all files (with size cap) ──
431
+ for (const [path, content] of Object.entries(coreFiles)) {
432
+ const fullPath = join(agentDir, path);
433
+ const dir = join(fullPath, '..');
434
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
435
+ writeFileSync(fullPath, this.capContent(content));
436
+ generated.push(path);
437
+ }
438
+
439
+ return generated;
440
+ }
441
+
442
+ // ── Private: Generate Missing (for existing .agent/) ──
443
+
444
+ private generateMissing(
445
+ agentDir: string,
446
+ audit: AgentAuditFinding[],
447
+ report: AnalysisReport,
448
+ plan: RefactoringPlan,
449
+ stack: StackInfo,
450
+ projectPath: string,
451
+ ): string[] {
452
+ const generated: string[] = [];
453
+ const missing = audit.filter(f => f.type === 'MISSING');
454
+ const ctx = this.buildContext(report, plan, stack, projectPath);
455
+
456
+ for (const finding of missing) {
457
+ const fullPath = join(agentDir, finding.file);
458
+ const dir = join(fullPath, '..');
459
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
460
+
461
+ const content = this.getTemplateFor(finding.file, ctx);
462
+ if (content) {
463
+ writeFileSync(fullPath, content);
464
+ generated.push(finding.file);
465
+ }
466
+ }
467
+
468
+ return generated;
469
+ }
470
+
471
+ private getTemplateFor(file: string, ctx: EnrichedTemplateContext): string | null {
472
+ if (file.includes('INDEX')) return generateIndexMd(ctx);
473
+ if (file.includes('ORCHESTRATOR')) return generateOrchestrator(ctx);
474
+ if (file.includes('PREFLIGHT')) return generatePreflight(ctx);
475
+ if (file.includes('QUALITY-GATES')) return generateQualityGates(ctx);
476
+ if (file.includes('CODE-REVIEW')) return generateCodeReviewChecklist(ctx);
477
+ if (file.includes('SECURITY')) return generateSecurityAgent(ctx);
478
+ if (file.includes('QA')) return generateQAAgent(ctx);
479
+ if (file.includes('TECH-DEBT')) return generateTechDebtAgent(ctx);
480
+ if (file.includes('BACKEND')) return generateBackendAgent(ctx);
481
+ if (file.includes('FRONTEND')) return generateFrontendAgent(ctx);
482
+ if (file.includes('FLUTTER')) return generateMobileAgent(ctx);
483
+ if (file.includes('DATABASE')) return generateDatabaseAgent(ctx);
484
+ if (file.includes('00-general')) return generateGeneralRules(ctx);
485
+ if (file.includes('01-architecture')) return generateArchitectureRules(ctx);
486
+ if (file.includes('02-security')) return generateSecurityRules(ctx);
487
+ if (file.includes('03-')) return generateStackRules(ctx);
488
+ if (file.includes('new-feature') || file.includes('develop')) return generateNewFeatureWorkflow(ctx);
489
+ if (file.includes('fix-bug')) return generateFixBugWorkflow(ctx);
490
+ if (file.includes('review')) return generateReviewWorkflow(ctx);
491
+ if (file.includes('C4')) return generateC4Template(ctx);
492
+ if (file.includes('BDD')) return generateBddTemplate(ctx);
493
+ if (file.includes('TDD')) return generateTddTemplate(ctx);
494
+ if (file.includes('ADR')) return generateAdrTemplate(ctx);
495
+ if (file.includes('THREAT')) return generateThreatModelTemplate(ctx);
496
+ return null;
497
+ }
498
+
499
+ // ── Private: Audit ──
500
+
501
+ private auditExisting(
502
+ agentDir: string,
503
+ stack: StackInfo,
504
+ report: AnalysisReport,
505
+ plan: RefactoringPlan,
506
+ ): AgentAuditFinding[] {
507
+ const findings: AgentAuditFinding[] = [];
508
+
509
+ const checkExists = (subpath: string, category: string, desc: string): void => {
510
+ const full = join(agentDir, subpath);
511
+ if (!existsSync(full)) {
512
+ findings.push({ type: 'MISSING', category, file: subpath, description: desc });
513
+ } else {
514
+ findings.push({ type: 'OK', category, file: subpath, description: `${subpath} exists` });
515
+ }
516
+ };
517
+
518
+ // Core structure
519
+ checkExists('INDEX.md', 'core', 'Master navigation guide');
520
+ checkExists('agents/AGENT-ORCHESTRATOR.md', 'agents', 'Orchestrator agent with approval gates');
521
+ checkExists('rules/00-general.md', 'rules', 'Golden rules and conventions');
522
+ checkExists('rules/01-architecture.md', 'rules', 'Layer rules, dependency direction, module patterns');
523
+ checkExists('rules/02-security.md', 'rules', 'OWASP, input validation, secrets management');
524
+ checkExists('guards/PREFLIGHT.md', 'guards', '6-phase preflight checklist');
525
+ checkExists('guards/QUALITY-GATES.md', 'guards', '3-level quality gates');
526
+ checkExists('guards/CODE-REVIEW-CHECKLIST.md', 'guards', 'Structured code review checklist');
527
+ checkExists('workflows/new-feature.md', 'workflows', '10-step feature workflow with approval gates');
528
+ checkExists('workflows/fix-bug.md', 'workflows', 'Diagnostic bug fix workflow');
529
+
530
+ // Domain templates
531
+ checkExists('templates/C4.md', 'templates', 'C4 architecture template');
532
+ checkExists('templates/BDD.md', 'templates', 'BDD scenario template');
533
+ checkExists('templates/TDD.md', 'templates', 'TDD test template');
534
+ checkExists('templates/ADR.md', 'templates', 'ADR decision record template');
535
+ checkExists('templates/THREAT-MODEL.md', 'templates', 'STRIDE threat model template');
536
+
537
+ // Stack-specific agents
538
+ if (stack.hasBackend) {
539
+ const found = this.findAgentByRole(agentDir, 'backend');
540
+ if (!found) {
541
+ findings.push({
542
+ type: 'MISSING', category: 'agents',
543
+ file: `agents/${stack.primary.toUpperCase()}-BACKEND-DEVELOPER.md`,
544
+ description: `No backend developer agent for ${stack.primary}`,
545
+ });
546
+ }
547
+ }
548
+ if (stack.hasFrontend) {
549
+ const found = this.findAgentByRole(agentDir, 'frontend');
550
+ if (!found) {
551
+ findings.push({
552
+ type: 'MISSING', category: 'agents',
553
+ file: 'agents/FRONTEND-DEVELOPER.md',
554
+ description: 'No frontend developer agent',
555
+ });
556
+ }
557
+ }
558
+
559
+ // Quality improvements
560
+ if (plan.steps.length > 0) {
561
+ const found = this.findAgentByRole(agentDir, 'tech-debt');
562
+ if (!found) {
563
+ findings.push({
564
+ type: 'IMPROVEMENT', category: 'agents',
565
+ file: 'agents/TECH-DEBT-CONTROLLER.md',
566
+ description: `${plan.steps.length} refactoring steps found but no Tech Debt agent`,
567
+ suggestion: 'Create a Tech Debt Controller to track and prioritize refactoring',
568
+ });
569
+ }
570
+ }
571
+
572
+ if (report.score.overall < 80) {
573
+ findings.push({
574
+ type: 'IMPROVEMENT', category: 'guards',
575
+ file: 'guards/QUALITY-GATES.md',
576
+ description: `Score is ${report.score.overall}/100 — quality gates should enforce improvement`,
577
+ suggestion: `Set minimum score threshold to ${report.score.overall + 5} and add regression guards`,
578
+ });
579
+ }
580
+
581
+ return findings;
582
+ }
583
+
584
+ private findAgentByRole(agentDir: string, role: string): string | null {
585
+ const dir = join(agentDir, 'agents');
586
+ if (!existsSync(dir)) return null;
587
+ const files = readdirSync(dir);
588
+ for (const file of files) {
589
+ const content = readFileSync(join(dir, file), 'utf-8').toLowerCase();
590
+ if (content.includes(role)) return file;
591
+ }
592
+ return null;
593
+ }
594
+
595
+ // ── Private: Skills ──
596
+
597
+ private buildSkillEntries(stack: StackInfo, existing: Set<string>) {
598
+ const entries: { name: string; source: string; description: string; status: AgentItemStatus }[] = [
599
+ { name: 'test-driven-development', source: 'anthropic/courses/test-driven-development', description: 'TDD: Red → Green → Refactor', status: 'CREATE' },
600
+ { name: 'systematic-debugging', source: 'anthropic/courses/systematic-debugging', description: 'Structured debugging methodology', status: 'CREATE' },
601
+ { name: 'code-review', source: 'anthropic/courses/requesting-code-review', description: 'Code review best practices', status: 'CREATE' },
602
+ { name: 'security-best-practices', source: 'anthropic/courses/security-best-practices', description: 'Security patterns and vulnerability prevention', status: 'CREATE' },
603
+ { name: 'performance-optimization', source: 'anthropic/courses/performance-optimization', description: 'Performance analysis and optimization', status: 'CREATE' },
604
+ { name: 'git-workflow', source: 'anthropic/courses/git-workflow', description: 'Git branching, commits, collaboration', status: 'CREATE' },
605
+ ];
606
+
607
+ // Stack-specific skills
608
+ if (stack.languages.includes('TypeScript') || stack.languages.includes('JavaScript')) {
609
+ entries.push({ name: 'api-design-principles', source: 'anthropic/courses/api-design-principles', description: 'REST/GraphQL API design', status: 'CREATE' });
610
+ }
611
+ if (stack.frameworks.includes('Angular') || stack.frameworks.includes('Vue') || stack.frameworks.includes('React') || stack.frameworks.includes('Next.js')) {
612
+ entries.push(
613
+ { name: 'frontend-design', source: 'anthropic/courses/frontend-design', description: 'Modern frontend patterns', status: 'CREATE' },
614
+ { name: 'web-accessibility', source: 'anthropic/courses/web-accessibility', description: 'WCAG accessibility standards', status: 'CREATE' },
615
+ );
616
+ }
617
+ if (stack.languages.includes('Dart') || stack.frameworks.includes('Flutter')) {
618
+ entries.push({ name: 'flutter-animations', source: 'anthropic/courses/flutter-animations', description: 'Flutter animation patterns', status: 'CREATE' });
619
+ }
620
+ if (stack.languages.includes('Python')) {
621
+ entries.push({ name: 'python-performance', source: 'anthropic/courses/python-performance-optimization', description: 'Python optimization and profiling', status: 'CREATE' });
622
+ }
623
+ if (stack.hasDatabase) {
624
+ entries.push({ name: 'database-schema-design', source: 'anthropic/courses/database-schema-design', description: 'Schema design, indexing, migrations', status: 'CREATE' });
625
+ }
626
+
627
+ // Update status based on existing
628
+ for (const entry of entries) {
629
+ if (existing.has(entry.name)) entry.status = 'KEEP';
630
+ }
631
+
632
+ return entries;
633
+ }
634
+ }