@girardelli/architect 1.2.1 → 2.1.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 (63) hide show
  1. package/README.md +111 -112
  2. package/dist/agent-generator.d.ts +95 -0
  3. package/dist/agent-generator.d.ts.map +1 -0
  4. package/dist/agent-generator.js +1295 -0
  5. package/dist/agent-generator.js.map +1 -0
  6. package/dist/cli.js +76 -2
  7. package/dist/cli.js.map +1 -1
  8. package/dist/html-reporter.d.ts +26 -4
  9. package/dist/html-reporter.d.ts.map +1 -1
  10. package/dist/html-reporter.js +832 -33
  11. package/dist/html-reporter.js.map +1 -1
  12. package/dist/index.d.ts +26 -2
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +85 -8
  15. package/dist/index.js.map +1 -1
  16. package/dist/refactor-engine.d.ts +18 -0
  17. package/dist/refactor-engine.d.ts.map +1 -0
  18. package/dist/refactor-engine.js +86 -0
  19. package/dist/refactor-engine.js.map +1 -0
  20. package/dist/refactor-reporter.d.ts +20 -0
  21. package/dist/refactor-reporter.d.ts.map +1 -0
  22. package/dist/refactor-reporter.js +389 -0
  23. package/dist/refactor-reporter.js.map +1 -0
  24. package/dist/rules/barrel-optimizer.d.ts +13 -0
  25. package/dist/rules/barrel-optimizer.d.ts.map +1 -0
  26. package/dist/rules/barrel-optimizer.js +77 -0
  27. package/dist/rules/barrel-optimizer.js.map +1 -0
  28. package/dist/rules/dead-code-detector.d.ts +21 -0
  29. package/dist/rules/dead-code-detector.d.ts.map +1 -0
  30. package/dist/rules/dead-code-detector.js +117 -0
  31. package/dist/rules/dead-code-detector.js.map +1 -0
  32. package/dist/rules/hub-splitter.d.ts +13 -0
  33. package/dist/rules/hub-splitter.d.ts.map +1 -0
  34. package/dist/rules/hub-splitter.js +110 -0
  35. package/dist/rules/hub-splitter.js.map +1 -0
  36. package/dist/rules/import-organizer.d.ts +13 -0
  37. package/dist/rules/import-organizer.d.ts.map +1 -0
  38. package/dist/rules/import-organizer.js +85 -0
  39. package/dist/rules/import-organizer.js.map +1 -0
  40. package/dist/rules/module-grouper.d.ts +13 -0
  41. package/dist/rules/module-grouper.d.ts.map +1 -0
  42. package/dist/rules/module-grouper.js +110 -0
  43. package/dist/rules/module-grouper.js.map +1 -0
  44. package/dist/scorer.d.ts +12 -0
  45. package/dist/scorer.d.ts.map +1 -1
  46. package/dist/scorer.js +61 -17
  47. package/dist/scorer.js.map +1 -1
  48. package/dist/types.d.ts +51 -0
  49. package/dist/types.d.ts.map +1 -1
  50. package/package.json +1 -1
  51. package/src/agent-generator.ts +1401 -0
  52. package/src/cli.ts +83 -2
  53. package/src/html-reporter.ts +872 -35
  54. package/src/index.ts +108 -9
  55. package/src/refactor-engine.ts +117 -0
  56. package/src/refactor-reporter.ts +408 -0
  57. package/src/rules/barrel-optimizer.ts +97 -0
  58. package/src/rules/dead-code-detector.ts +132 -0
  59. package/src/rules/hub-splitter.ts +123 -0
  60. package/src/rules/import-organizer.ts +98 -0
  61. package/src/rules/module-grouper.ts +124 -0
  62. package/src/scorer.ts +63 -17
  63. package/src/types.ts +52 -0
@@ -0,0 +1,1295 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'fs';
2
+ import { join } from 'path';
3
+ /**
4
+ * Agent Generator — Creates or audits .agent/ directories
5
+ * customized to the analyzed project's stack and architecture.
6
+ */
7
+ export class AgentGenerator {
8
+ /**
9
+ * Suggest agents without writing files — for unified report.
10
+ */
11
+ suggest(report, plan, projectPath) {
12
+ this.report = report;
13
+ this.plan = plan;
14
+ this.stack = this.detectStack(report);
15
+ const agentDir = join(projectPath, '.agent');
16
+ const isExisting = existsSync(agentDir);
17
+ const suggestedAgents = [];
18
+ // Always suggest core agents
19
+ suggestedAgents.push('AGENT-ORCHESTRATOR');
20
+ if (this.stack.hasBackend)
21
+ suggestedAgents.push(`${this.stack.primary.toUpperCase()}-BACKEND-DEVELOPER`);
22
+ if (this.stack.hasFrontend) {
23
+ const fw = this.stack.frameworks.find(f => ['Angular', 'Vue', 'Next.js', 'React'].includes(f)) || 'FRONTEND';
24
+ suggestedAgents.push(`${fw.toUpperCase().replace('.', '')}-FRONTEND-DEVELOPER`);
25
+ }
26
+ if (this.stack.hasMobile)
27
+ suggestedAgents.push('FLUTTER-UI-DEVELOPER');
28
+ if (this.stack.hasDatabase)
29
+ suggestedAgents.push('DATABASE-ENGINEER');
30
+ suggestedAgents.push('SECURITY-AUDITOR', 'QA-TEST-ENGINEER', 'TECH-DEBT-CONTROLLER');
31
+ const suggestedRules = ['00-general', '01-architecture', '02-security'];
32
+ if (this.stack.hasBackend)
33
+ suggestedRules.push(`03-${this.stack.primary.toLowerCase()}`);
34
+ const suggestedGuards = ['PREFLIGHT', 'QUALITY-GATES', 'CODE-REVIEW-CHECKLIST'];
35
+ const suggestedWorkflows = ['develop', 'fix-bug', 'review'];
36
+ // Skills from skills.sh — mapped to detected stack
37
+ const suggestedSkills = [
38
+ // Universal skills
39
+ { name: 'test-driven-development', source: 'anthropic/courses/test-driven-development', description: 'TDD workflow: Red → Green → Refactor' },
40
+ { name: 'systematic-debugging', source: 'anthropic/courses/systematic-debugging', description: 'Structured debugging methodology' },
41
+ { name: 'code-review', source: 'anthropic/courses/requesting-code-review', description: 'Code review best practices' },
42
+ { name: 'security-best-practices', source: 'anthropic/courses/security-best-practices', description: 'Security patterns and vulnerability prevention' },
43
+ { name: 'performance-optimization', source: 'anthropic/courses/performance-optimization', description: 'Performance analysis and optimization' },
44
+ { name: 'git-workflow', source: 'anthropic/courses/git-workflow', description: 'Git branching, commits, and collaboration' },
45
+ ];
46
+ // Stack-specific
47
+ if (this.stack.languages.includes('TypeScript') || this.stack.languages.includes('JavaScript')) {
48
+ suggestedSkills.push({ name: 'next-best-practices', source: 'vercel-labs/skills/next-best-practices', description: 'Next.js patterns and performance' }, { name: 'api-design-principles', source: 'anthropic/courses/api-design-principles', description: 'REST/GraphQL API design' });
49
+ }
50
+ if (this.stack.frameworks.includes('Angular') || this.stack.frameworks.includes('Vue') || this.stack.frameworks.includes('React') || this.stack.frameworks.includes('Next.js')) {
51
+ suggestedSkills.push({ name: 'frontend-design', source: 'anthropic/courses/frontend-design', description: 'Modern frontend patterns and UI/UX' }, { name: 'web-accessibility', source: 'anthropic/courses/web-accessibility', description: 'WCAG accessibility standards' }, { name: 'ui-ux-pro-max', source: 'anthropic/courses/ui-ux-pro-max', description: '50 styles, 21 palettes, 50 font pairings' });
52
+ }
53
+ if (this.stack.frameworks.includes('Vue')) {
54
+ suggestedSkills.push({ name: 'vue-best-practices', source: 'anthropic/courses/vue-best-practices', description: 'Vue.js composition API and patterns' });
55
+ }
56
+ if (this.stack.languages.includes('Dart') || this.stack.frameworks.includes('Flutter')) {
57
+ suggestedSkills.push({ name: 'flutter-animations', source: 'anthropic/courses/flutter-animations', description: 'Flutter animation patterns' });
58
+ }
59
+ if (this.stack.languages.includes('Python')) {
60
+ suggestedSkills.push({ name: 'python-performance', source: 'anthropic/courses/python-performance-optimization', description: 'Python optimization and profiling' });
61
+ }
62
+ if (this.stack.hasDatabase) {
63
+ suggestedSkills.push({ name: 'database-schema-design', source: 'anthropic/courses/database-schema-design', description: 'Schema design, indexing, migrations' });
64
+ }
65
+ let audit = [];
66
+ if (isExisting) {
67
+ audit = this.auditExisting(agentDir);
68
+ }
69
+ return {
70
+ stack: this.stack,
71
+ hasExistingAgents: isExisting,
72
+ suggestedAgents,
73
+ suggestedRules,
74
+ suggestedGuards,
75
+ suggestedWorkflows,
76
+ suggestedSkills,
77
+ audit,
78
+ command: `architect agents ${projectPath}`,
79
+ };
80
+ }
81
+ /**
82
+ * Main entry: generate or audit .agent/ for a project.
83
+ */
84
+ generate(report, plan, projectPath, outputDir) {
85
+ this.report = report;
86
+ this.plan = plan;
87
+ this.stack = this.detectStack(report);
88
+ const agentDir = outputDir || join(projectPath, '.agent');
89
+ const isExisting = existsSync(agentDir);
90
+ if (isExisting) {
91
+ const audit = this.auditExisting(agentDir);
92
+ const generated = this.generateMissing(agentDir, audit);
93
+ return { generated, audit };
94
+ }
95
+ const generated = this.generateFull(agentDir);
96
+ return { generated, audit: [] };
97
+ }
98
+ /**
99
+ * Detect technology stack from the analysis report.
100
+ */
101
+ detectStack(report) {
102
+ const files = report.dependencyGraph.nodes;
103
+ const extensions = new Set();
104
+ const languages = new Set();
105
+ const frameworks = new Set();
106
+ for (const file of files) {
107
+ const ext = file.split('.').pop()?.toLowerCase() || '';
108
+ extensions.add(ext);
109
+ }
110
+ // Detect languages
111
+ if (extensions.has('py'))
112
+ languages.add('Python');
113
+ if (extensions.has('ts') || extensions.has('tsx'))
114
+ languages.add('TypeScript');
115
+ if (extensions.has('js') || extensions.has('jsx'))
116
+ languages.add('JavaScript');
117
+ if (extensions.has('dart'))
118
+ languages.add('Dart');
119
+ if (extensions.has('go'))
120
+ languages.add('Go');
121
+ if (extensions.has('rs'))
122
+ languages.add('Rust');
123
+ if (extensions.has('java') || extensions.has('kt'))
124
+ languages.add('Java/Kotlin');
125
+ if (extensions.has('rb'))
126
+ languages.add('Ruby');
127
+ if (extensions.has('php'))
128
+ languages.add('PHP');
129
+ if (extensions.has('cs'))
130
+ languages.add('C#');
131
+ // Detect frameworks from file patterns
132
+ const allFiles = files.join(' ');
133
+ if (allFiles.includes('manage.py') || allFiles.includes('django'))
134
+ frameworks.add('Django');
135
+ if (allFiles.includes('flask') || allFiles.includes('app.py'))
136
+ frameworks.add('Flask');
137
+ if (allFiles.includes('fastapi'))
138
+ frameworks.add('FastAPI');
139
+ if (allFiles.includes('.module.ts') || allFiles.includes('nest'))
140
+ frameworks.add('NestJS');
141
+ if (allFiles.includes('.component.ts') || allFiles.includes('angular'))
142
+ frameworks.add('Angular');
143
+ if (allFiles.includes('.vue'))
144
+ frameworks.add('Vue');
145
+ if (allFiles.includes('.tsx') && allFiles.includes('next'))
146
+ frameworks.add('Next.js');
147
+ if (allFiles.includes('.dart'))
148
+ frameworks.add('Flutter');
149
+ if (allFiles.includes('go.mod'))
150
+ frameworks.add('Go Modules');
151
+ if (allFiles.includes('Cargo.toml'))
152
+ frameworks.add('Cargo');
153
+ if (allFiles.includes('pom.xml') || allFiles.includes('build.gradle'))
154
+ frameworks.add('Spring');
155
+ const primary = languages.size > 0 ? [...languages][0] : 'Unknown';
156
+ const hasBackend = languages.has('Python') || languages.has('TypeScript') ||
157
+ languages.has('Go') || languages.has('Java/Kotlin') || languages.has('Ruby') || languages.has('PHP');
158
+ const hasFrontend = frameworks.has('Angular') || frameworks.has('Vue') ||
159
+ frameworks.has('Next.js') || extensions.has('html');
160
+ const hasMobile = languages.has('Dart') || frameworks.has('Flutter');
161
+ const hasDatabase = allFiles.includes('migration') || allFiles.includes('entity') ||
162
+ allFiles.includes('model') || allFiles.includes('schema');
163
+ let testFramework = 'Jest';
164
+ if (languages.has('Python'))
165
+ testFramework = 'pytest';
166
+ if (languages.has('Go'))
167
+ testFramework = 'go test';
168
+ if (languages.has('Dart'))
169
+ testFramework = 'flutter_test';
170
+ let packageManager = 'npm';
171
+ if (languages.has('Python'))
172
+ packageManager = 'pip';
173
+ if (languages.has('Go'))
174
+ packageManager = 'go mod';
175
+ if (languages.has('Dart'))
176
+ packageManager = 'pub';
177
+ return {
178
+ primary, languages: [...languages], frameworks: [...frameworks],
179
+ hasBackend, hasFrontend, hasMobile, hasDatabase,
180
+ testFramework, packageManager,
181
+ };
182
+ }
183
+ // ── Audit Existing ──
184
+ auditExisting(agentDir) {
185
+ const findings = [];
186
+ const checkExists = (subpath, category, desc) => {
187
+ const full = join(agentDir, subpath);
188
+ if (!existsSync(full)) {
189
+ findings.push({ type: 'MISSING', category, file: subpath, description: desc });
190
+ }
191
+ else {
192
+ findings.push({ type: 'OK', category, file: subpath, description: `${subpath} exists` });
193
+ }
194
+ };
195
+ // Check required structure
196
+ checkExists('INDEX.md', 'core', 'Index file for agent navigation');
197
+ checkExists('agents/AGENT-ORCHESTRATOR.md', 'agents', 'Orchestrator agent');
198
+ checkExists('rules/00-general.md', 'rules', 'General rules');
199
+ checkExists('guards/PREFLIGHT.md', 'guards', 'Preflight checklist');
200
+ checkExists('workflows/develop.md', 'workflows', 'Development workflow');
201
+ // Check stack-specific agents
202
+ if (this.stack.hasBackend) {
203
+ const backendAgent = this.findAgentByRole(agentDir, 'backend');
204
+ if (!backendAgent) {
205
+ findings.push({
206
+ type: 'MISSING', category: 'agents',
207
+ file: `agents/${this.stack.primary.toUpperCase()}-BACKEND-DEVELOPER.md`,
208
+ description: `No backend developer agent for ${this.stack.primary}`,
209
+ suggestion: `Create a ${this.stack.primary} backend agent with patterns, conventions, and architecture rules`,
210
+ });
211
+ }
212
+ }
213
+ if (this.stack.hasFrontend) {
214
+ const frontAgent = this.findAgentByRole(agentDir, 'frontend');
215
+ if (!frontAgent) {
216
+ findings.push({
217
+ type: 'MISSING', category: 'agents',
218
+ file: 'agents/FRONTEND-DEVELOPER.md',
219
+ description: 'No frontend developer agent',
220
+ suggestion: `Create a frontend agent for ${this.stack.frameworks.join(', ')}`,
221
+ });
222
+ }
223
+ }
224
+ // Check for tech debt alignment
225
+ if (this.plan.steps.length > 0) {
226
+ const techDebtAgent = this.findAgentByRole(agentDir, 'tech-debt');
227
+ if (!techDebtAgent) {
228
+ findings.push({
229
+ type: 'IMPROVEMENT', category: 'agents',
230
+ file: 'agents/TECH-DEBT-CONTROLLER.md',
231
+ description: `${this.plan.steps.length} refactoring steps found but no Tech Debt agent`,
232
+ suggestion: 'Create a Tech Debt Controller with the refactoring backlog',
233
+ });
234
+ }
235
+ }
236
+ // Check quality gates match score
237
+ if (this.report.score.overall < 80) {
238
+ findings.push({
239
+ type: 'IMPROVEMENT', category: 'guards',
240
+ file: 'guards/QUALITY-GATES.md',
241
+ description: `Score is ${this.report.score.overall}/100 — quality gates should enforce improvement`,
242
+ suggestion: `Set minimum score threshold to ${this.report.score.overall + 5} and add regression guards`,
243
+ });
244
+ }
245
+ // Check anti-pattern rules
246
+ for (const ap of this.report.antiPatterns) {
247
+ findings.push({
248
+ type: 'IMPROVEMENT', category: 'rules',
249
+ file: `rules/anti-pattern-${ap.name.toLowerCase().replace(/\s+/g, '-')}.md`,
250
+ description: `Anti-pattern "${ap.name}" (${ap.severity}) detected but no prevention rule`,
251
+ suggestion: `Add a rule to prevent "${ap.name}" from recurring`,
252
+ });
253
+ }
254
+ return findings;
255
+ }
256
+ findAgentByRole(agentDir, role) {
257
+ const agentsDir = join(agentDir, 'agents');
258
+ if (!existsSync(agentsDir))
259
+ return null;
260
+ const files = readdirSync(agentsDir);
261
+ for (const file of files) {
262
+ const content = readFileSync(join(agentsDir, file), 'utf-8').toLowerCase();
263
+ if (content.includes(role))
264
+ return file;
265
+ }
266
+ return null;
267
+ }
268
+ generateMissing(agentDir, audit) {
269
+ const generated = [];
270
+ const missing = audit.filter(f => f.type === 'MISSING');
271
+ for (const finding of missing) {
272
+ const fullPath = join(agentDir, finding.file);
273
+ const dir = join(fullPath, '..');
274
+ if (!existsSync(dir))
275
+ mkdirSync(dir, { recursive: true });
276
+ const content = this.getTemplateFor(finding.category, finding.file);
277
+ if (content) {
278
+ writeFileSync(fullPath, content);
279
+ generated.push(finding.file);
280
+ }
281
+ }
282
+ return generated;
283
+ }
284
+ // ── Full Generation ──
285
+ generateFull(agentDir) {
286
+ const generated = [];
287
+ const dirs = ['agents', 'rules', 'guards', 'workflows', 'skills'];
288
+ for (const d of dirs)
289
+ mkdirSync(join(agentDir, d), { recursive: true });
290
+ // Core files
291
+ const coreFiles = {
292
+ 'INDEX.md': this.genIndex(),
293
+ 'AGENT-CARD-SCHEMA.md': this.genSchema(),
294
+ 'agents/AGENT-ORCHESTRATOR.md': this.genOrchestrator(),
295
+ 'agents/SECURITY-AUDITOR.md': this.genSecurityAgent(),
296
+ 'agents/QA-TEST-ENGINEER.md': this.genQAAgent(),
297
+ 'agents/TECH-DEBT-CONTROLLER.md': this.genTechDebtAgent(),
298
+ 'rules/00-general.md': this.genGeneralRules(),
299
+ 'rules/01-architecture.md': this.genArchitectureRules(),
300
+ 'rules/02-security.md': this.genSecurityRules(),
301
+ 'guards/PREFLIGHT.md': this.genPreflight(),
302
+ 'guards/QUALITY-GATES.md': this.genQualityGates(),
303
+ 'guards/CODE-REVIEW-CHECKLIST.md': this.genCodeReview(),
304
+ 'workflows/develop.md': this.genDevelopWorkflow(),
305
+ 'workflows/fix-bug.md': this.genFixBugWorkflow(),
306
+ 'workflows/review.md': this.genReviewWorkflow(),
307
+ };
308
+ // Stack-specific agents
309
+ if (this.stack.hasBackend) {
310
+ coreFiles[`agents/${this.stack.primary.toUpperCase()}-BACKEND-DEVELOPER.md`] =
311
+ this.genBackendAgent();
312
+ coreFiles[`rules/03-${this.stack.primary.toLowerCase()}.md`] =
313
+ this.genStackRules();
314
+ }
315
+ if (this.stack.hasFrontend) {
316
+ const fwName = this.stack.frameworks.find(f => ['Angular', 'Vue', 'Next.js', 'React'].includes(f)) || 'Frontend';
317
+ coreFiles[`agents/${fwName.toUpperCase().replace('.', '')}-FRONTEND-DEVELOPER.md`] =
318
+ this.genFrontendAgent();
319
+ }
320
+ if (this.stack.hasMobile) {
321
+ coreFiles['agents/FLUTTER-UI-DEVELOPER.md'] = this.genMobileAgent();
322
+ }
323
+ if (this.stack.hasDatabase) {
324
+ coreFiles['agents/DATABASE-ENGINEER.md'] = this.genDatabaseAgent();
325
+ }
326
+ for (const [path, content] of Object.entries(coreFiles)) {
327
+ writeFileSync(join(agentDir, path), content);
328
+ generated.push(path);
329
+ }
330
+ return generated;
331
+ }
332
+ getTemplateFor(category, file) {
333
+ if (file.includes('ORCHESTRATOR'))
334
+ return this.genOrchestrator();
335
+ if (file.includes('SECURITY'))
336
+ return this.genSecurityAgent();
337
+ if (file.includes('QA'))
338
+ return this.genQAAgent();
339
+ if (file.includes('TECH-DEBT'))
340
+ return this.genTechDebtAgent();
341
+ if (file.includes('BACKEND'))
342
+ return this.genBackendAgent();
343
+ if (file.includes('FRONTEND'))
344
+ return this.genFrontendAgent();
345
+ if (file.includes('INDEX'))
346
+ return this.genIndex();
347
+ if (file.includes('00-general'))
348
+ return this.genGeneralRules();
349
+ if (file.includes('PREFLIGHT'))
350
+ return this.genPreflight();
351
+ if (file.includes('develop'))
352
+ return this.genDevelopWorkflow();
353
+ return null;
354
+ }
355
+ // ── Template Generators ──
356
+ get projectName() {
357
+ return this.report.projectInfo.name || 'Project';
358
+ }
359
+ get stackLabel() {
360
+ return [
361
+ ...this.stack.languages,
362
+ ...this.stack.frameworks,
363
+ ].join(' + ');
364
+ }
365
+ genIndex() {
366
+ const agents = [
367
+ 'AGENT-ORCHESTRATOR',
368
+ ...(this.stack.hasBackend ? [`${this.stack.primary.toUpperCase()}-BACKEND-DEVELOPER`] : []),
369
+ ...(this.stack.hasFrontend ? ['FRONTEND-DEVELOPER'] : []),
370
+ ...(this.stack.hasMobile ? ['FLUTTER-UI-DEVELOPER'] : []),
371
+ ...(this.stack.hasDatabase ? ['DATABASE-ENGINEER'] : []),
372
+ 'SECURITY-AUDITOR',
373
+ 'QA-TEST-ENGINEER',
374
+ 'TECH-DEBT-CONTROLLER',
375
+ ];
376
+ return `# ${this.projectName} — Agent Framework
377
+
378
+ > **Auto-generated by [Architect v2.1](https://github.com/camilooscargbaptista/architect)**
379
+ > Stack: **${this.stackLabel}** | Score: **${this.report.score.overall}/100**
380
+
381
+ ---
382
+
383
+ ## 🔴 Leitura Obrigatória
384
+
385
+ | # | Arquivo | Propósito |
386
+ |---|---------|-----------|
387
+ | 1 | [00-general.md](./rules/00-general.md) | Regras gerais do projeto |
388
+ | 2 | [PREFLIGHT.md](./guards/PREFLIGHT.md) | Checklist pré-ação |
389
+ | 3 | [QUALITY-GATES.md](./guards/QUALITY-GATES.md) | Critérios mínimos |
390
+
391
+ ## 🤖 Agentes Disponíveis
392
+
393
+ | Agente | Arquivo | Role |
394
+ |--------|---------|------|
395
+ ${agents.map(a => `| ${a} | [${a}.md](./agents/${a}.md) | ${a.includes('ORCHESTRATOR') ? 'coordination' : a.includes('SECURITY') || a.includes('QA') ? 'quality' : 'development'} |`).join('\n')}
396
+
397
+ ## 📁 Estrutura
398
+
399
+ \`\`\`
400
+ .agent/
401
+ ├── agents/ → Agentes especializados
402
+ ├── rules/ → Regras de codificação
403
+ ├── guards/ → Checklists e quality gates
404
+ ├── workflows/ → Fluxos de trabalho
405
+ └── skills/ → Padrões e referências
406
+ \`\`\`
407
+
408
+ ---
409
+
410
+ **⚠️ REGRA DE OURO: Na dúvida, PARA e PERGUNTA.**
411
+ `;
412
+ }
413
+ genSchema() {
414
+ return `---
415
+ description: 'Schema de referência para Agent Cards — padrão A2A-inspired'
416
+ version: 1.0.0
417
+ ---
418
+
419
+ # Agent Card Schema
420
+
421
+ > Cada agente DEVE ter um bloco \`agent_card\` no frontmatter YAML.
422
+
423
+ ## Schema
424
+
425
+ \`\`\`yaml
426
+ agent_card:
427
+ id: "string" # kebab-case unique ID
428
+ name: "string" # Human readable name
429
+ role: "enum" # coordination | development | quality | protection | governance
430
+ capabilities: [] # List of skills
431
+ inputs: [] # What the agent needs
432
+ outputs: [] # What the agent produces
433
+ depends_on: [] # Agents that must run before
434
+ \`\`\`
435
+
436
+ ## Roles
437
+
438
+ | Role | Description |
439
+ |------|-------------|
440
+ | coordination | Orchestrates other agents |
441
+ | development | Writes production code |
442
+ | quality | Testing and QA |
443
+ | protection | Security and compliance |
444
+ | governance | Standards and tech debt |
445
+ `;
446
+ }
447
+ genOrchestrator() {
448
+ const layers = this.report.layers.map(l => l.name).join(', ');
449
+ const antiPatterns = this.report.antiPatterns.map(a => a.name).join(', ') || 'None detected';
450
+ return `---
451
+ antigravity:
452
+ trigger: 'always_on'
453
+ globs: ['**/*']
454
+ description: 'META-AGENT ORQUESTRADOR — Coordena todos os agentes para ${this.projectName}'
455
+ priority: CRITICAL
456
+ agent_card:
457
+ id: 'orchestrator'
458
+ name: 'Agent Orchestrator'
459
+ role: 'coordination'
460
+ capabilities: [request-decomposition, agent-dispatch, plan-consolidation, quality-verification]
461
+ inputs: [user-story, feature-request, bug-report, refactoring-request]
462
+ outputs: [consolidated-plan, implementation-blocks, effort-estimate]
463
+ depends_on: []
464
+ version: 1.0.0
465
+ ---
466
+
467
+ # 🎭 AGENT-ORCHESTRATOR: ${this.projectName}
468
+
469
+ > **Centro de comando.** Toda requisição passa por aqui.
470
+
471
+ ## Contexto do Projeto
472
+
473
+ - **Projeto:** ${this.projectName}
474
+ - **Stack:** ${this.stackLabel}
475
+ - **Score Atual:** ${this.report.score.overall}/100
476
+ - **Camadas:** ${layers}
477
+ - **Anti-Patterns:** ${antiPatterns}
478
+ - **Arquivos:** ${this.report.projectInfo.totalFiles} files, ${this.report.projectInfo.totalLines} lines
479
+
480
+ ## Missão
481
+
482
+ \`\`\`
483
+ RECEBER REQUISIÇÃO
484
+
485
+ ENTENDER CONTEXTO
486
+
487
+ DISPARAR AGENTES (paralelo)
488
+
489
+ CONSOLIDAR ANÁLISES
490
+
491
+ APRESENTAR PLANO
492
+
493
+ AGUARDAR APROVAÇÃO
494
+
495
+ DELEGAR IMPLEMENTAÇÃO
496
+
497
+ VERIFICAR QUALIDADE
498
+ \`\`\`
499
+
500
+ ## Protocolo de Recepção
501
+
502
+ ### FASE 0: Parsing da Requisição
503
+
504
+ \`\`\`
505
+ ✓ Nome da feature/fix: _______________
506
+ ✓ Tipo: [ ] Feature [ ] Bug Fix [ ] Refactoring [ ] Documentation
507
+ ✓ Camadas tocadas: ${layers}
508
+ ✓ Complexidade: [ ] XS [ ] S [ ] M [ ] L [ ] XL
509
+ ✓ Assunções (listar): _______________
510
+ \`\`\`
511
+
512
+ ### FASE 1: Disparo de Agentes
513
+
514
+ \`\`\`
515
+ ORQUESTRADOR analisa requisição
516
+
517
+ ${this.stack.hasBackend ? ` ├──→ [${this.stack.primary.toUpperCase()}-BACKEND]\n │ • Arquitetura de serviços\n │ • API contracts\n │ • Lógica de negócio\n │\n` : ''}${this.stack.hasFrontend ? ` ├──→ [FRONTEND-DEVELOPER]\n │ • Componentes e páginas\n │ • State management\n │ • UX/UI\n │\n` : ''}${this.stack.hasMobile ? ` ├──→ [FLUTTER-UI-DEVELOPER]\n │ • Screens mobile\n │ • Navigation\n │ • Widgets\n │\n` : ''}${this.stack.hasDatabase ? ` ├──→ [DATABASE-ENGINEER]\n │ • Schema design\n │ • Migrations\n │ • Performance\n │\n` : ''} ├──→ [SECURITY-AUDITOR]
518
+ │ • Análise de ameaças
519
+ │ • Compliance check
520
+
521
+ ├──→ [QA-TEST-ENGINEER]
522
+ │ • Test plan
523
+ │ • Coverage targets
524
+
525
+ └──→ [TECH-DEBT-CONTROLLER]
526
+ • Débito técnico existente
527
+ • Refatorações pré-requisito
528
+ \`\`\`
529
+
530
+ ### FASE 2: Consolidação
531
+
532
+ O orquestrador consolida em um plano com:
533
+ - Diagrama de arquitetura
534
+ - Cenários BDD
535
+ - Plano de testes
536
+ - Estimativa de esforço
537
+ - Riscos e mitigações
538
+
539
+ ### FASE 3: Implementação
540
+
541
+ Após \`/approved\`, delegar em blocos ordenados por dependência.
542
+
543
+ ---
544
+
545
+ ## Quality Gates
546
+
547
+ \`\`\`
548
+ □ Testes passando
549
+ □ Build compilando
550
+ □ Score >= ${Math.max(this.report.score.overall, 70)}/100
551
+ □ Sem regressão de score
552
+ □ Code review aprovado
553
+ \`\`\`
554
+
555
+ ---
556
+
557
+ **Gerado por Architect v2.1 · Score: ${this.report.score.overall}/100**
558
+ `;
559
+ }
560
+ genBackendAgent() {
561
+ const lang = this.stack.primary;
562
+ const fw = this.stack.frameworks.filter(f => ['Django', 'Flask', 'FastAPI', 'NestJS', 'Spring', 'Express'].includes(f)).join(', ') || lang;
563
+ return `---
564
+ antigravity:
565
+ trigger: 'on_demand'
566
+ globs: ['**/*.${lang === 'Python' ? 'py' : 'ts'}']
567
+ description: '${lang} Backend Developer — Arquitetura, APIs, serviços'
568
+ agent_card:
569
+ id: '${lang.toLowerCase()}-backend'
570
+ name: '${lang} Backend Developer'
571
+ role: 'development'
572
+ capabilities: [api-design, service-architecture, business-logic, data-modeling]
573
+ inputs: [user-story, api-contracts, business-rules]
574
+ outputs: [controllers, services, entities, migrations, tests]
575
+ depends_on: [${this.stack.hasDatabase ? 'database-engineer' : ''}]
576
+ ---
577
+
578
+ # 🔧 ${lang.toUpperCase()} BACKEND DEVELOPER
579
+
580
+ > Especialista em backend ${fw} para ${this.projectName}
581
+
582
+ ## Stack
583
+
584
+ - **Linguagem:** ${lang}
585
+ - **Framework:** ${fw}
586
+ - **Teste:** ${this.stack.testFramework}
587
+ - **Package Manager:** ${this.stack.packageManager}
588
+
589
+ ## Princípios
590
+
591
+ 1. **SOLID** — Single Responsibility, Open/Closed, Liskov, Interface Segregation, Dependency Inversion
592
+ 2. **Clean Architecture** — Separação de camadas
593
+ 3. **DRY** — Don't Repeat Yourself
594
+ 4. **KISS** — Keep It Simple
595
+ 5. **Fail Fast** — Validação na entrada
596
+
597
+ ## Padrões de Código
598
+
599
+ ### Estrutura de Módulo
600
+
601
+ \`\`\`
602
+ src/modules/[nome]/
603
+ ├── [nome].module.${lang === 'Python' ? 'py' : 'ts'}
604
+ ├── [nome].controller.${lang === 'Python' ? 'py' : 'ts'}
605
+ ├── [nome].service.${lang === 'Python' ? 'py' : 'ts'}
606
+ ├── dto/
607
+ ├── entities/
608
+ └── __tests__/
609
+ \`\`\`
610
+
611
+ ### Convenções
612
+
613
+ | Item | Padrão | Exemplo |
614
+ |------|--------|---------|
615
+ | Classes | PascalCase | \`UserService\` |
616
+ | Funções | camelCase / snake_case | \`get_user\` / \`getUser\` |
617
+ | Constantes | UPPER_SNAKE | \`MAX_RETRIES\` |
618
+ | Arquivos | kebab-case | \`user-service.${lang === 'Python' ? 'py' : 'ts'}\` |
619
+
620
+ ## Checklist por Entrega
621
+
622
+ \`\`\`
623
+ □ Tipos/interfaces definidos
624
+ □ Validação de entrada implementada
625
+ □ Erros tratados com mensagens claras
626
+ □ Testes unitários (mínimo 60%)
627
+ □ Sem secrets hardcoded
628
+ □ Logging adequado
629
+ □ Documentação de API
630
+ \`\`\`
631
+
632
+ ---
633
+
634
+ **Gerado por Architect v2.1 · Score: ${this.report.score.overall}/100**
635
+ `;
636
+ }
637
+ genFrontendAgent() {
638
+ const fw = this.stack.frameworks.find(f => ['Angular', 'Vue', 'Next.js', 'React'].includes(f)) || 'Frontend';
639
+ return `---
640
+ antigravity:
641
+ trigger: 'on_demand'
642
+ globs: ['src/**/*.{ts,tsx,vue,html,css}']
643
+ description: '${fw} Frontend Developer — Componentes, páginas, UX'
644
+ agent_card:
645
+ id: 'frontend-developer'
646
+ name: '${fw} Frontend Developer'
647
+ role: 'development'
648
+ capabilities: [component-design, state-management, responsive-ui, accessibility]
649
+ inputs: [mockups, api-contracts, user-stories]
650
+ outputs: [components, pages, services, styles, tests]
651
+ depends_on: ['${this.stack.primary.toLowerCase()}-backend']
652
+ ---
653
+
654
+ # 🎨 ${fw.toUpperCase()} FRONTEND DEVELOPER
655
+
656
+ > Especialista em frontend ${fw} para ${this.projectName}
657
+
658
+ ## Princípios
659
+
660
+ 1. **Component-Driven** — Componentes reutilizáveis
661
+ 2. **Responsive First** — Mobile-first design
662
+ 3. **Accessibility** — WCAG 2.1 AA compliance
663
+ 4. **Performance** — Lazy loading, tree shaking
664
+
665
+ ## Checklist
666
+
667
+ \`\`\`
668
+ □ Mockup HTML aprovado ANTES de codar
669
+ □ Componentes reutilizáveis
670
+ □ Estado gerenciado corretamente
671
+ □ Responsivo testado (mobile/tablet/desktop)
672
+ □ Loading states implementados
673
+ □ Error states implementados
674
+ □ Acessibilidade verificada
675
+ □ Performance otimizada
676
+ \`\`\`
677
+
678
+ ---
679
+
680
+ **Gerado por Architect v2.1**
681
+ `;
682
+ }
683
+ genMobileAgent() {
684
+ return `---
685
+ antigravity:
686
+ trigger: 'on_demand'
687
+ globs: ['lib/**/*.dart']
688
+ description: 'Flutter UI Developer — Screens, widgets, navigation'
689
+ agent_card:
690
+ id: 'flutter-ui'
691
+ name: 'Flutter UI Developer'
692
+ role: 'development'
693
+ capabilities: [screen-design, widget-composition, navigation, state-management]
694
+ inputs: [mockups, api-contracts]
695
+ outputs: [screens, widgets, blocs, tests]
696
+ depends_on: ['${this.stack.primary.toLowerCase()}-backend']
697
+ ---
698
+
699
+ # 📱 FLUTTER UI DEVELOPER
700
+
701
+ > Especialista em mobile Flutter para ${this.projectName}
702
+
703
+ ## Padrões
704
+
705
+ - **State:** BLoC / Provider
706
+ - **Navigation:** GoRouter / Navigator 2.0
707
+ - **Architecture:** Clean Architecture
708
+ - **Tests:** flutter_test + integration_test
709
+
710
+ ---
711
+
712
+ **Gerado por Architect v2.1**
713
+ `;
714
+ }
715
+ genDatabaseAgent() {
716
+ return `---
717
+ antigravity:
718
+ trigger: 'on_demand'
719
+ globs: ['**/migrations/**', '**/entities/**', '**/models/**']
720
+ description: 'Database Engineer — Schema, migrations, performance'
721
+ agent_card:
722
+ id: 'database-engineer'
723
+ name: 'Database Engineer'
724
+ role: 'development'
725
+ capabilities: [schema-design, migrations, indexing, query-optimization]
726
+ inputs: [business-rules, data-requirements]
727
+ outputs: [migrations, entities, indexes, constraints]
728
+ depends_on: []
729
+ ---
730
+
731
+ # 🗄️ DATABASE ENGINEER
732
+
733
+ > Especialista em banco de dados para ${this.projectName}
734
+
735
+ ## Regras
736
+
737
+ 1. **NUNCA** usar DELETE físico — sempre soft delete
738
+ 2. **SEMPRE** criar migration SQL (não ORM auto-generate)
739
+ 3. **SEMPRE** adicionar indexes para FKs e campos de busca
740
+ 4. **SEMPRE** validar constraints antes de deploy
741
+
742
+ ---
743
+
744
+ **Gerado por Architect v2.1**
745
+ `;
746
+ }
747
+ genSecurityAgent() {
748
+ return `---
749
+ antigravity:
750
+ trigger: 'on_demand'
751
+ globs: ['**/*']
752
+ description: 'Security Auditor — Análise de vulnerabilidades e compliance'
753
+ agent_card:
754
+ id: 'security-auditor'
755
+ name: 'Security Auditor'
756
+ role: 'protection'
757
+ capabilities: [threat-modeling, vulnerability-scan, compliance-check, auth-review]
758
+ inputs: [source-code, api-contracts, deployment-config]
759
+ outputs: [security-reports, threat-models, compliance-checklists]
760
+ depends_on: []
761
+ ---
762
+
763
+ # 🛡️ SECURITY AUDITOR
764
+
765
+ > Proteção contra ameaças para ${this.projectName}
766
+
767
+ ## Checklist de Segurança
768
+
769
+ \`\`\`
770
+ □ Sem secrets/credentials hardcoded
771
+ □ Sem logging de dados sensíveis (passwords, tokens, PII)
772
+ □ Inputs sanitizados
773
+ □ Queries parametrizadas (anti SQL injection)
774
+ □ Autenticação validada em todas as rotas
775
+ □ Autorização (RBAC) verificada
776
+ □ Rate limiting configurado
777
+ □ CORS configurado corretamente
778
+ □ Headers de segurança (HSTS, CSP, X-Frame)
779
+ □ Dependências sem vulnerabilidades conhecidas
780
+ \`\`\`
781
+
782
+ ## STRIDE Threat Model
783
+
784
+ | Ameaça | Descrição | Mitigação |
785
+ |--------|-----------|-----------|
786
+ | **S**poofing | Falsificação de identidade | JWT + MFA |
787
+ | **T**ampering | Alteração de dados | Validação + Checksums |
788
+ | **R**epudiation | Negação de ações | Audit logs |
789
+ | **I**nformation Disclosure | Vazamento de dados | Encryption + RBAC |
790
+ | **D**enial of Service | Indisponibilidade | Rate limiting + WAF |
791
+ | **E**levation of Privilege | Escalação de permissões | RBAC + Least privilege |
792
+
793
+ ---
794
+
795
+ **Gerado por Architect v2.1 · Score: ${this.report.score.overall}/100**
796
+ `;
797
+ }
798
+ genQAAgent() {
799
+ return `---
800
+ antigravity:
801
+ trigger: 'on_demand'
802
+ globs: ['**/*.{test,spec}.*', '**/__tests__/**']
803
+ description: 'QA Test Engineer — Testes, cobertura, qualidade'
804
+ agent_card:
805
+ id: 'qa-test-engineer'
806
+ name: 'QA Test Engineer'
807
+ role: 'quality'
808
+ capabilities: [bdd-specs, unit-tests, integration-tests, e2e-tests, coverage-analysis]
809
+ inputs: [user-stories, api-contracts, business-rules]
810
+ outputs: [test-suites, bdd-scenarios, coverage-reports]
811
+ depends_on: []
812
+ ---
813
+
814
+ # 🧪 QA TEST ENGINEER
815
+
816
+ > Qualidade e testes para ${this.projectName}
817
+
818
+ ## Stack de Testes
819
+
820
+ - **Framework:** ${this.stack.testFramework}
821
+ - **Cobertura mínima:** 60%
822
+ - **Padrão:** TDD (Red → Green → Refactor)
823
+
824
+ ## Fluxo TDD
825
+
826
+ \`\`\`
827
+ 1. RED → Escrever teste que FALHA
828
+ 2. GREEN → Código MÍNIMO para passar
829
+ 3. REFACTOR → Limpar sem quebrar
830
+ \`\`\`
831
+
832
+ ## Cenários Obrigatórios
833
+
834
+ \`\`\`
835
+ □ Happy path (fluxo principal)
836
+ □ Validação de entrada (dados inválidos)
837
+ □ Edge cases (limites, null, empty)
838
+ □ Erro handling (exceptions, timeouts)
839
+ □ Permissões (autorizado vs não autorizado)
840
+ □ Fluxos existentes NÃO quebrados
841
+ \`\`\`
842
+
843
+ ## Padrão BDD
844
+
845
+ \`\`\`gherkin
846
+ Feature: [Nome]
847
+ Scenario: [Happy Path]
848
+ Given [contexto]
849
+ When [ação]
850
+ Then [resultado esperado]
851
+
852
+ Scenario: [Erro]
853
+ Given [contexto]
854
+ When [ação inválida]
855
+ Then [erro esperado]
856
+ \`\`\`
857
+
858
+ ---
859
+
860
+ **Gerado por Architect v2.1**
861
+ `;
862
+ }
863
+ genTechDebtAgent() {
864
+ const steps = this.plan.steps.map(s => `| ${s.priority} | ${s.title} | ${s.operations.length} ops |`).join('\n');
865
+ return `---
866
+ antigravity:
867
+ trigger: 'on_demand'
868
+ globs: ['**/*']
869
+ description: 'Tech Debt Controller — Identifica e prioriza débito técnico'
870
+ agent_card:
871
+ id: 'tech-debt-controller'
872
+ name: 'Tech Debt Controller'
873
+ role: 'governance'
874
+ capabilities: [debt-identification, refactoring-planning, pattern-enforcement]
875
+ inputs: [architecture-report, anti-patterns, code-metrics]
876
+ outputs: [debt-backlog, refactoring-plans, improvement-metrics]
877
+ depends_on: []
878
+ ---
879
+
880
+ # 📊 TECH DEBT CONTROLLER
881
+
882
+ > Governança de débito técnico para ${this.projectName}
883
+
884
+ ## Estado Atual
885
+
886
+ - **Score:** ${this.report.score.overall}/100
887
+ - **Anti-patterns:** ${this.report.antiPatterns.length}
888
+ - **Refactoring steps:** ${this.plan.steps.length}
889
+
890
+ ## Backlog de Refactoring
891
+
892
+ | Prioridade | Item | Operações |
893
+ |------------|------|-----------|
894
+ ${steps || '| — | Nenhum item pendente | — |'}
895
+
896
+ ## Taxonomia de Dívida
897
+
898
+ | Tipo | Descrição | Impacto |
899
+ |------|-----------|---------|
900
+ | Architecture | Violações de camadas, hubs | Score |
901
+ | Code Quality | Complexidade, duplicação | Manutenção |
902
+ | Testing | Cobertura baixa, sem testes | Confiabilidade |
903
+ | Security | Vulnerabilidades conhecidas | Risco |
904
+ | Documentation | Docs ausentes ou desatualizados | Onboarding |
905
+
906
+ ---
907
+
908
+ **Gerado por Architect v2.1 · Score: ${this.report.score.overall}/100**
909
+ `;
910
+ }
911
+ genGeneralRules() {
912
+ return `---
913
+ antigravity:
914
+ trigger: 'always_on'
915
+ globs: ['**/*']
916
+ description: 'Regras gerais obrigatórias — ${this.projectName}'
917
+ ---
918
+
919
+ # ${this.projectName} — Regras Gerais
920
+
921
+ > **LEIA TUDO ANTES DE QUALQUER AÇÃO.**
922
+
923
+ ## 🥇 REGRAS DE OURO (INVIOLÁVEIS)
924
+
925
+ \`\`\`
926
+ 🥇 1. GIT FLOW COMPLETO
927
+ → Verificar branch + status ANTES de tudo
928
+ → feature/* → develop → staging → main
929
+ → NUNCA codificar direto em main/staging/develop
930
+
931
+ 🥇 2. DIAGNÓSTICO ANTES DE CODAR
932
+ → Ler código existente ANTES de implementar
933
+ → Verificar se já existe algo similar
934
+
935
+ 🥇 3. TDD
936
+ → Testes ANTES do código
937
+ → Red → Green → Refactor
938
+
939
+ 🥇 4. NÃO DECIDIR SOZINHO
940
+ → Dúvida? PARAR E PERGUNTAR
941
+
942
+ 🥇 5. QUALIDADE > VELOCIDADE
943
+ → Nunca atalhos. Fazer certo da primeira vez.
944
+ \`\`\`
945
+
946
+ ## Stack
947
+
948
+ | Camada | Tecnologia |
949
+ |--------|------------|
950
+ ${this.stack.languages.map(l => `| ${l} | ${this.stack.frameworks.filter(f => f).join(', ') || l} |`).join('\n')}
951
+
952
+ ## Convenções de Idioma
953
+
954
+ | Contexto | Idioma |
955
+ |----------|--------|
956
+ | Código (variáveis, funções) | Inglês |
957
+ | Comentários | Português (Brasil) |
958
+ | Git commits | Inglês (Conventional Commits) |
959
+ | Documentação | Português (Brasil) |
960
+
961
+ ## Nomenclatura
962
+
963
+ | Tipo | Padrão | Exemplo |
964
+ |------|--------|---------|
965
+ | Classes | PascalCase | \`UserService\` |
966
+ | Funções | camelCase | \`getUser\` |
967
+ | Constantes | UPPER_SNAKE | \`MAX_RETRIES\` |
968
+ | Arquivos | kebab-case | \`user-service.ts\` |
969
+
970
+ ## ⛔ O QUE NUNCA FAZER
971
+
972
+ \`\`\`
973
+ ❌ Commitar em main/staging/develop
974
+ ❌ Pular Git Flow
975
+ ❌ Assumir — VERIFICAR
976
+ ❌ Dizer "pronto" sem testes
977
+ ❌ Hardcoded secrets
978
+ \`\`\`
979
+
980
+ ---
981
+
982
+ **Gerado por Architect v2.1 · Score: ${this.report.score.overall}/100**
983
+ `;
984
+ }
985
+ genArchitectureRules() {
986
+ const layers = this.report.layers.map(l => `| ${l.name} | ${l.files.length} files | ${l.description} |`).join('\n');
987
+ return `---
988
+ antigravity:
989
+ trigger: 'always_on'
990
+ globs: ['**/*']
991
+ description: 'Regras de arquitetura — ${this.projectName}'
992
+ ---
993
+
994
+ # Regras de Arquitetura
995
+
996
+ ## Camadas Detectadas
997
+
998
+ | Camada | Arquivos | Descrição |
999
+ |--------|----------|-----------|
1000
+ ${layers}
1001
+
1002
+ ## Score Atual: ${this.report.score.overall}/100
1003
+
1004
+ | Métrica | Valor |
1005
+ |---------|-------|
1006
+ | Modularity | ${this.report.score.breakdown.modularity} |
1007
+ | Coupling | ${this.report.score.breakdown.coupling} |
1008
+ | Cohesion | ${this.report.score.breakdown.cohesion} |
1009
+ | Layering | ${this.report.score.breakdown.layering} |
1010
+
1011
+ ## Regras
1012
+
1013
+ 1. **Respeitar camadas** — Nunca importar de camada superior
1014
+ 2. **Máximo 5 dependências** — Acima disso, considerar split
1015
+ 3. **Sem imports circulares** — Sempre unidirecional
1016
+ 4. **Um propósito por arquivo** — Single Responsibility
1017
+
1018
+ ---
1019
+
1020
+ **Gerado por Architect v2.1**
1021
+ `;
1022
+ }
1023
+ genSecurityRules() {
1024
+ return `---
1025
+ antigravity:
1026
+ trigger: 'always_on'
1027
+ globs: ['**/*']
1028
+ description: 'Regras de segurança — ${this.projectName}'
1029
+ ---
1030
+
1031
+ # Regras de Segurança
1032
+
1033
+ ## NUNCA (Zero Tolerância)
1034
+
1035
+ \`\`\`
1036
+ ❌ Hardcoded secrets, API keys, passwords
1037
+ ❌ Logging de dados sensíveis (PII, tokens)
1038
+ ❌ SQL sem parameterização
1039
+ ❌ eval() ou exec() com input do usuário
1040
+ ❌ Endpoints sem autenticação
1041
+ ❌ CORS com wildcard (*) em produção
1042
+ \`\`\`
1043
+
1044
+ ## SEMPRE
1045
+
1046
+ \`\`\`
1047
+ ✅ Sanitizar inputs do usuário
1048
+ ✅ Usar queries parametrizadas
1049
+ ✅ Validar file uploads (tipo, tamanho)
1050
+ ✅ Rate limiting em APIs públicas
1051
+ ✅ Headers de segurança (HSTS, CSP)
1052
+ ✅ Audit logs para ações sensíveis
1053
+ \`\`\`
1054
+
1055
+ ---
1056
+
1057
+ **Gerado por Architect v2.1**
1058
+ `;
1059
+ }
1060
+ genStackRules() {
1061
+ const lang = this.stack.primary;
1062
+ return `---
1063
+ antigravity:
1064
+ trigger: 'on_demand'
1065
+ globs: ['**/*.${lang === 'Python' ? 'py' : lang === 'TypeScript' ? 'ts' : lang.toLowerCase()}']
1066
+ description: 'Regras específicas de ${lang} — ${this.projectName}'
1067
+ ---
1068
+
1069
+ # Regras ${lang}
1070
+
1071
+ ## Boas Práticas
1072
+
1073
+ ${lang === 'Python' ? `
1074
+ - Type hints em TODAS as funções
1075
+ - Docstrings em classes e funções públicas
1076
+ - PEP 8 compliance
1077
+ - Use \`pathlib\` ao invés de \`os.path\`
1078
+ - Use \`dataclasses\` ou \`pydantic\` para modelos
1079
+ - Virtual environment obrigatório
1080
+ ` : lang === 'TypeScript' ? `
1081
+ - Strict mode ativado
1082
+ - Interfaces para TODOS os contratos
1083
+ - Sem \`any\` (use \`unknown\` se necessário)
1084
+ - Async/await ao invés de callbacks
1085
+ - Enum ao invés de magic strings
1086
+ - JSDoc em funções públicas
1087
+ ` : `
1088
+ - Siga as convenções da linguagem
1089
+ - Documentação obrigatória
1090
+ - Testes unitários mínimo 60%
1091
+ `}
1092
+
1093
+ ---
1094
+
1095
+ **Gerado por Architect v2.1**
1096
+ `;
1097
+ }
1098
+ genPreflight() {
1099
+ return `# PREFLIGHT Checklist — ${this.projectName}
1100
+
1101
+ > **Execute ANTES de qualquer tarefa. Sem exceções.**
1102
+
1103
+ ## 🔴 Fase 0: Preparação
1104
+
1105
+ \`\`\`
1106
+ □ Li e entendi a tarefa completamente?
1107
+ □ Sei qual é o objetivo?
1108
+ □ Identifiquei o tipo: [ ] Backend [ ] Frontend [ ] Database [ ] Bug Fix [ ] Feature
1109
+ \`\`\`
1110
+
1111
+ ## 🔴 Fase 1: Ambiente
1112
+
1113
+ \`\`\`
1114
+ □ Qual branch estou? → git branch --show-current
1115
+ □ É main ou develop? → CRIAR BRANCH IMEDIATAMENTE
1116
+ □ Branch atualizada? → git pull origin develop
1117
+ \`\`\`
1118
+
1119
+ ## 🔴 Fase 2: Diagnóstico
1120
+
1121
+ \`\`\`
1122
+ □ Verifiquei código existente similar?
1123
+ □ Entendi a arquitetura afetada?
1124
+ □ Li lessons-learned (se existir)?
1125
+ \`\`\`
1126
+
1127
+ ## ⚠️ Red Flags - PARE
1128
+
1129
+ | Red Flag | Ação |
1130
+ |----------|------|
1131
+ | Não sei onde fica o código | Pesquisar ANTES |
1132
+ | Vou assumir algo | PERGUNTAR |
1133
+ | Estou em main/develop | CRIAR BRANCH |
1134
+ | "Acho que funciona" | TESTAR |
1135
+
1136
+ ---
1137
+
1138
+ **Gerado por Architect v2.1**
1139
+ `;
1140
+ }
1141
+ genQualityGates() {
1142
+ const minScore = Math.max(this.report.score.overall - 5, 60);
1143
+ return `# Quality Gates — ${this.projectName}
1144
+
1145
+ > Score atual: **${this.report.score.overall}/100**
1146
+
1147
+ ## Gates Obrigatórios
1148
+
1149
+ | Gate | Critério | Status |
1150
+ |------|----------|--------|
1151
+ | Build | Compila sem erros | ✅ Required |
1152
+ | Lint | Sem erros de lint | ✅ Required |
1153
+ | Tests | Todos passando | ✅ Required |
1154
+ | Coverage | >= 60% | ✅ Required |
1155
+ | Score | >= ${minScore}/100 | ✅ Required |
1156
+ | No Regression | Score não pode cair | ⚠️ Warning |
1157
+
1158
+ ## Métricas Atuais
1159
+
1160
+ | Métrica | Valor | Meta |
1161
+ |---------|-------|------|
1162
+ | Modularity | ${this.report.score.breakdown.modularity} | >= 80 |
1163
+ | Coupling | ${this.report.score.breakdown.coupling} | >= 70 |
1164
+ | Cohesion | ${this.report.score.breakdown.cohesion} | >= 80 |
1165
+ | Layering | ${this.report.score.breakdown.layering} | >= 80 |
1166
+
1167
+ ---
1168
+
1169
+ **Gerado por Architect v2.1**
1170
+ `;
1171
+ }
1172
+ genCodeReview() {
1173
+ return `# Code Review Checklist — ${this.projectName}
1174
+
1175
+ ## Funcionalidade
1176
+ \`\`\`
1177
+ □ Resolve o problema descrito?
1178
+ □ Edge cases tratados?
1179
+ □ Erros tratados com mensagens claras?
1180
+ \`\`\`
1181
+
1182
+ ## Qualidade
1183
+ \`\`\`
1184
+ □ Código legível e bem nomeado?
1185
+ □ Sem duplicação desnecessária?
1186
+ □ Princípios SOLID respeitados?
1187
+ □ Complexidade controlada?
1188
+ \`\`\`
1189
+
1190
+ ## Segurança
1191
+ \`\`\`
1192
+ □ Sem secrets hardcoded?
1193
+ □ Inputs validados?
1194
+ □ Queries parametrizadas?
1195
+ \`\`\`
1196
+
1197
+ ## Testes
1198
+ \`\`\`
1199
+ □ Testes unitários adicionados?
1200
+ □ Cenários de erro testados?
1201
+ □ Cobertura >= 60%?
1202
+ \`\`\`
1203
+
1204
+ ---
1205
+
1206
+ **Gerado por Architect v2.1**
1207
+ `;
1208
+ }
1209
+ genDevelopWorkflow() {
1210
+ return `---
1211
+ name: develop
1212
+ description: Fluxo completo de desenvolvimento — ${this.projectName}
1213
+ ---
1214
+
1215
+ # Workflow: Desenvolvimento Completo
1216
+
1217
+ ## 🎯 FLUXO OBRIGATÓRIO
1218
+
1219
+ \`\`\`
1220
+ 0️⃣ GIT FLOW → Criar feature branch
1221
+ 1️⃣ ENTENDIMENTO → Perguntas de clarificação
1222
+ 2️⃣ DIAGNÓSTICO → Verificar código existente
1223
+ 3️⃣ BDD → Cenários Gherkin (APROVAÇÃO)
1224
+ 4️⃣ TDD RED → Testes falhando
1225
+ 5️⃣ TDD GREEN → Código mínimo
1226
+ 6️⃣ REFACTOR → Código limpo
1227
+ 7️⃣ GIT COMMIT → Conventional Commits + Push
1228
+ \`\`\`
1229
+
1230
+ ## Pontos de Aprovação
1231
+
1232
+ 1. Após entendimento
1233
+ 2. Após cenários BDD
1234
+ 3. Após testes verdes
1235
+ 4. Após refatoração
1236
+ 5. Após commit e push
1237
+
1238
+ ## 🚫 PROIBIDO
1239
+
1240
+ - ❌ Trabalhar direto em develop/main
1241
+ - ❌ Código antes de teste
1242
+ - ❌ Avançar sem aprovação
1243
+ - ❌ Commit sem Conventional Commits
1244
+
1245
+ ---
1246
+
1247
+ **Gerado por Architect v2.1**
1248
+ `;
1249
+ }
1250
+ genFixBugWorkflow() {
1251
+ return `---
1252
+ name: fix-bug
1253
+ description: Corrigir bug com diagnóstico completo — ${this.projectName}
1254
+ ---
1255
+
1256
+ # Workflow: Fix Bug
1257
+
1258
+ \`\`\`
1259
+ 1️⃣ Criar branch fix/nome-do-bug
1260
+ 2️⃣ Reproduzir o bug
1261
+ 3️⃣ Escrever teste que FALHA reproduzindo o bug
1262
+ 4️⃣ Corrigir o código mínimo
1263
+ 5️⃣ Teste passa (GREEN)
1264
+ 6️⃣ Verificar que não quebrou nada
1265
+ 7️⃣ Commit: fix(scope): description
1266
+ \`\`\`
1267
+
1268
+ ---
1269
+
1270
+ **Gerado por Architect v2.1**
1271
+ `;
1272
+ }
1273
+ genReviewWorkflow() {
1274
+ return `---
1275
+ name: review
1276
+ description: Code review completo — ${this.projectName}
1277
+ ---
1278
+
1279
+ # Workflow: Code Review
1280
+
1281
+ \`\`\`
1282
+ 1️⃣ Ler a descrição do PR
1283
+ 2️⃣ Verificar diff por arquivo
1284
+ 3️⃣ Executar checklist de review
1285
+ 4️⃣ Rodar testes localmente
1286
+ 5️⃣ Aprovar ou solicitar mudanças
1287
+ \`\`\`
1288
+
1289
+ ---
1290
+
1291
+ **Gerado por Architect v2.1**
1292
+ `;
1293
+ }
1294
+ }
1295
+ //# sourceMappingURL=agent-generator.js.map