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