wegho-agentes 4.0.1

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 (94) hide show
  1. package/.agents/AGENT_WORKFLOW.md +528 -0
  2. package/.agents/AI_COMPATIBILITY.md +332 -0
  3. package/.agents/CLI.md +222 -0
  4. package/.agents/README.md +130 -0
  5. package/.agents/cli.js +389 -0
  6. package/.agents/code-auditor-agent.ts +333 -0
  7. package/.agents/config.ts +145 -0
  8. package/.agents/context-loader.ts +300 -0
  9. package/.agents/core/agent-parallelizer.test.ts +94 -0
  10. package/.agents/core/agent-parallelizer.ts +108 -0
  11. package/.agents/core/architecture-agent.ts +237 -0
  12. package/.agents/core/base-agent.ts +311 -0
  13. package/.agents/core/cache-manager.test.ts +147 -0
  14. package/.agents/core/cache-manager.ts +184 -0
  15. package/.agents/core/documentation-agent.ts +183 -0
  16. package/.agents/core/feedback-collector.ts +207 -0
  17. package/.agents/core/frontend-agent.ts +210 -0
  18. package/.agents/core/inventory-agent.ts +582 -0
  19. package/.agents/core/memory-system.ts +397 -0
  20. package/.agents/core/quality-agent.ts +268 -0
  21. package/.agents/core/retry-utility.test.ts +165 -0
  22. package/.agents/core/retry-utility.ts +140 -0
  23. package/.agents/core/security-agent.ts +217 -0
  24. package/.agents/core/workflow-validator.test.ts +171 -0
  25. package/.agents/core/workflow-validator.ts +158 -0
  26. package/.agents/domains/README.md +53 -0
  27. package/.agents/domains/logistics/route-agent.ts +177 -0
  28. package/.agents/domains/news/cms-agent.ts +158 -0
  29. package/.agents/domains/news/seo-agent.ts +170 -0
  30. package/.agents/domains/production/production-control-agent.ts +169 -0
  31. package/.agents/example-learning-system.js +118 -0
  32. package/.agents/init.ts +164 -0
  33. package/.agents/memory/architecture-agent/failures.json +1 -0
  34. package/.agents/memory/architecture-agent/learnings.json +1 -0
  35. package/.agents/memory/architecture-agent/specialty.md +31 -0
  36. package/.agents/memory/architecture-agent/successes.json +16 -0
  37. package/.agents/memory/cms-agent/failures.json +1 -0
  38. package/.agents/memory/cms-agent/learnings.json +1 -0
  39. package/.agents/memory/cms-agent/specialty.md +30 -0
  40. package/.agents/memory/cms-agent/successes.json +16 -0
  41. package/.agents/memory/documentation-agent/failures.json +1 -0
  42. package/.agents/memory/documentation-agent/learnings.json +1 -0
  43. package/.agents/memory/documentation-agent/specialty.md +33 -0
  44. package/.agents/memory/documentation-agent/successes.json +16 -0
  45. package/.agents/memory/frontend-agent/failures.json +1 -0
  46. package/.agents/memory/frontend-agent/learnings.json +1 -0
  47. package/.agents/memory/frontend-agent/specialty.md +30 -0
  48. package/.agents/memory/frontend-agent/successes.json +16 -0
  49. package/.agents/memory/inventory-agent/failures.json +1 -0
  50. package/.agents/memory/inventory-agent/inventory/index.json +8 -0
  51. package/.agents/memory/inventory-agent/inventory/types.json +77716 -0
  52. package/.agents/memory/inventory-agent/inventory/variables.json +405 -0
  53. package/.agents/memory/inventory-agent/learnings.json +1 -0
  54. package/.agents/memory/inventory-agent/specialty.md +129 -0
  55. package/.agents/memory/inventory-agent/successes.json +30 -0
  56. package/.agents/memory/production-control-agent/failures.json +1 -0
  57. package/.agents/memory/production-control-agent/learnings.json +1 -0
  58. package/.agents/memory/production-control-agent/specialty.md +29 -0
  59. package/.agents/memory/production-control-agent/successes.json +16 -0
  60. package/.agents/memory/quality-agent/failures.json +16 -0
  61. package/.agents/memory/quality-agent/learnings.json +1 -0
  62. package/.agents/memory/quality-agent/specialty.md +31 -0
  63. package/.agents/memory/quality-agent/successes.json +1 -0
  64. package/.agents/memory/reference-repositories.json +271 -0
  65. package/.agents/memory/route-agent/failures.json +1 -0
  66. package/.agents/memory/route-agent/learnings.json +1 -0
  67. package/.agents/memory/route-agent/specialty.md +29 -0
  68. package/.agents/memory/route-agent/successes.json +16 -0
  69. package/.agents/memory/security-agent/failures.json +1 -0
  70. package/.agents/memory/security-agent/learnings.json +1 -0
  71. package/.agents/memory/security-agent/specialty.md +31 -0
  72. package/.agents/memory/security-agent/successes.json +16 -0
  73. package/.agents/memory/seo-agent/failures.json +1 -0
  74. package/.agents/memory/seo-agent/learnings.json +1 -0
  75. package/.agents/memory/seo-agent/specialty.md +31 -0
  76. package/.agents/memory/seo-agent/successes.json +16 -0
  77. package/.agents/orchestrator.ts +438 -0
  78. package/.agents/project-discovery-agent.ts +342 -0
  79. package/.agents/security/pentesting-agent.py +387 -0
  80. package/.agents/security/python-bridge.ts +193 -0
  81. package/.agents/security/vulnerability-db.json +201 -0
  82. package/.agents/task-analyzer-agent.ts +346 -0
  83. package/.agents/test-init-context.js +67 -0
  84. package/INSTALL.md +300 -0
  85. package/LICENSE +21 -0
  86. package/README.md +315 -0
  87. package/docs/AGENT_RULES.md +292 -0
  88. package/docs/BUILD_HISTORY.md +65 -0
  89. package/docs/DESIGN_SYSTEM.md +256 -0
  90. package/docs/LEARNING_SYSTEM.md +326 -0
  91. package/docs/SYMBOLS_TREE.md +182 -0
  92. package/docs/VERSION.md +6 -0
  93. package/docs/architecture.md +111 -0
  94. package/package.json +60 -0
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Workflow Validator - Garante que agentes sigam os 6 passos obrigatórios
3
+ *
4
+ * Passos obrigatórios do AGENT_WORKFLOW.md:
5
+ * 1. Consultar memória para casos similares
6
+ * 2. Obter recomendações de aprendizados
7
+ * 3. Consultar repositórios de referência relevantes
8
+ * 4. Aplicar aprendizados com alta confiança (>0.7)
9
+ * 5. Registrar resultado (sucesso ou falha)
10
+ * 6. Gerar aprendizados baseado em feedback (opcional)
11
+ */
12
+
13
+ export interface WorkflowStep {
14
+ name: string;
15
+ required: boolean;
16
+ completed: boolean;
17
+ timestamp?: Date;
18
+ details?: any;
19
+ }
20
+
21
+ export interface WorkflowValidationResult {
22
+ compliant: boolean;
23
+ missingSteps: string[];
24
+ warnings: string[];
25
+ completedSteps: string[];
26
+ totalRequired: number;
27
+ totalCompleted: number;
28
+ }
29
+
30
+ export class WorkflowValidator {
31
+ /**
32
+ * Valida se um agente seguiu todos os passos obrigatórios
33
+ */
34
+ validateAgentExecution(agentName: string, executionLog: WorkflowStep[]): WorkflowValidationResult {
35
+ const requiredSteps = executionLog.filter(step => step.required);
36
+ const completedRequired = requiredSteps.filter(step => step.completed);
37
+ const missingSteps = requiredSteps
38
+ .filter(step => !step.completed)
39
+ .map(step => step.name);
40
+
41
+ const warnings: string[] = [];
42
+ const completedSteps = executionLog
43
+ .filter(step => step.completed)
44
+ .map(step => step.name);
45
+
46
+ // Verificar se passos foram executados na ordem correta
47
+ const expectedOrder = [
48
+ 'Consultar Memória',
49
+ 'Obter Recomendações',
50
+ 'Consultar Repositórios',
51
+ 'Aplicar Aprendizados',
52
+ 'Registrar Resultado'
53
+ ];
54
+
55
+ const completedOrder = executionLog
56
+ .filter(step => step.completed && step.timestamp)
57
+ .sort((a, b) => a.timestamp!.getTime() - b.timestamp!.getTime())
58
+ .map(step => step.name);
59
+
60
+ // Verificar ordem (warning, não erro)
61
+ for (let i = 0; i < completedOrder.length - 1; i++) {
62
+ const currentIndex = expectedOrder.indexOf(completedOrder[i]);
63
+ const nextIndex = expectedOrder.indexOf(completedOrder[i + 1]);
64
+
65
+ if (currentIndex !== -1 && nextIndex !== -1 && currentIndex > nextIndex) {
66
+ warnings.push(
67
+ `Passos executados fora de ordem: "${completedOrder[i]}" antes de "${completedOrder[i + 1]}"`
68
+ );
69
+ }
70
+ }
71
+
72
+ // Verificar se passos críticos foram pulados
73
+ const criticalSteps = ['Consultar Memória', 'Registrar Resultado'];
74
+ const missingCritical = criticalSteps.filter(
75
+ step => !completedSteps.includes(step)
76
+ );
77
+
78
+ if (missingCritical.length > 0) {
79
+ warnings.push(
80
+ `Passos críticos não executados: ${missingCritical.join(', ')}`
81
+ );
82
+ }
83
+
84
+ const compliant = missingSteps.length === 0;
85
+
86
+ return {
87
+ compliant,
88
+ missingSteps,
89
+ warnings,
90
+ completedSteps,
91
+ totalRequired: requiredSteps.length,
92
+ totalCompleted: completedRequired.length
93
+ };
94
+ }
95
+
96
+ /**
97
+ * Gera relatório detalhado de validação
98
+ */
99
+ generateValidationReport(agentName: string, validation: WorkflowValidationResult): string {
100
+ const lines: string[] = [];
101
+
102
+ lines.push(`\n━━━ Validação de Workflow: ${agentName} ━━━`);
103
+ lines.push(`Status: ${validation.compliant ? '✅ COMPLIANT' : '❌ NON-COMPLIANT'}`);
104
+ lines.push(`Passos Completados: ${validation.totalCompleted}/${validation.totalRequired}`);
105
+
106
+ if (validation.completedSteps.length > 0) {
107
+ lines.push(`\n✅ Passos Executados:`);
108
+ validation.completedSteps.forEach(step => {
109
+ lines.push(` - ${step}`);
110
+ });
111
+ }
112
+
113
+ if (validation.missingSteps.length > 0) {
114
+ lines.push(`\n❌ Passos Faltantes:`);
115
+ validation.missingSteps.forEach(step => {
116
+ lines.push(` - ${step}`);
117
+ });
118
+ }
119
+
120
+ if (validation.warnings.length > 0) {
121
+ lines.push(`\n⚠️ Avisos:`);
122
+ validation.warnings.forEach(warning => {
123
+ lines.push(` - ${warning}`);
124
+ });
125
+ }
126
+
127
+ lines.push(`━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`);
128
+
129
+ return lines.join('\n');
130
+ }
131
+
132
+ /**
133
+ * Valida múltiplos agentes e retorna resumo
134
+ */
135
+ validateMultipleAgents(
136
+ agentExecutions: Array<{ agentName: string; steps: WorkflowStep[] }>
137
+ ): {
138
+ allCompliant: boolean;
139
+ compliantCount: number;
140
+ nonCompliantCount: number;
141
+ details: Array<{ agentName: string; validation: WorkflowValidationResult }>;
142
+ } {
143
+ const details = agentExecutions.map(({ agentName, steps }) => ({
144
+ agentName,
145
+ validation: this.validateAgentExecution(agentName, steps)
146
+ }));
147
+
148
+ const compliantCount = details.filter(d => d.validation.compliant).length;
149
+ const nonCompliantCount = details.length - compliantCount;
150
+
151
+ return {
152
+ allCompliant: nonCompliantCount === 0,
153
+ compliantCount,
154
+ nonCompliantCount,
155
+ details
156
+ };
157
+ }
158
+ }
@@ -0,0 +1,53 @@
1
+ # Agentes de Domínio
2
+
3
+ Agentes especializados para diferentes domínios de negócio.
4
+
5
+ ---
6
+
7
+ ## 📰 News Domain (Site de Notícias)
8
+
9
+ ### ✅ Implementados:
10
+ - **cms-agent.ts** - Validação de artigos/posts
11
+ - **seo-agent.ts** - Meta tags, structured data, sitemap
12
+
13
+ ### 🚧 Pendentes:
14
+ - **content-agent.ts** - Qualidade de conteúdo, links quebrados
15
+ - **analytics-agent.ts** - Métricas, dashboards, A/B tests
16
+
17
+ ---
18
+
19
+ ## 🏭 Production Domain (Produção/Expedição)
20
+
21
+ ### ✅ Implementados:
22
+ - **production-control-agent.ts** - Eventos, gargalos, fluxo
23
+
24
+ ### 🚧 Pendentes:
25
+ - **quality-control-agent.ts** - Inspeções, não-conformidade
26
+ - **shipping-agent.ts** - Pedidos expedidos, fretes
27
+ - **inventory-agent.ts** - Estoque, níveis críticos
28
+
29
+ ---
30
+
31
+ ## 🚚 Logistics Domain (Logística)
32
+
33
+ ### ✅ Implementados:
34
+ - **route-agent.ts** - Rotas, distâncias, otimização
35
+
36
+ ### 🚧 Pendentes:
37
+ - **fleet-agent.ts** - Frota, manutenção, documentos
38
+ - **warehouse-agent.ts** - Armazéns, picking, packing
39
+ - **tracking-agent.ts** - Rastreamento GPS em tempo real
40
+
41
+ ---
42
+
43
+ ## 🔧 Como Adicionar Novo Agente
44
+
45
+ 1. Crie arquivo em `.agents/domains/{dominio}/{nome}-agent.ts`
46
+ 2. Implemente interface padrão com métodos `validate*`
47
+ 3. Adicione testes em `.agents/domains/{dominio}/tests/`
48
+ 4. Documente no README.md do domínio
49
+
50
+ ---
51
+
52
+ **Status**: 5/12 implementados (42%)
53
+ **Última atualização**: 2026-01-20
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Route Agent (com Memória)
3
+ * Domínio: Logística
4
+ *
5
+ * Responsabilidades:
6
+ * - Otimizar rotas de entrega
7
+ * - Calcular distâncias e tempo estimado
8
+ * - Validar waypoints e sequência
9
+ * - Sugerir rotas eficientes
10
+ * - Aprender padrões de rotas otimizadas
11
+ */
12
+
13
+ import { BaseAgent, TaskContext, TaskResult } from '../../core/base-agent';
14
+
15
+ export interface Waypoint {
16
+ lat: number;
17
+ lng: number;
18
+ address: string;
19
+ order: number;
20
+ }
21
+
22
+ export interface Route {
23
+ id: string;
24
+ name: string;
25
+ waypoints: Waypoint[];
26
+ totalDistance?: number; // em km
27
+ estimatedDuration?: number; // em minutos
28
+ }
29
+
30
+ export class RouteAgent extends BaseAgent {
31
+ constructor(memoryBasePath: string = '.agents/memory') {
32
+ super('route-agent', memoryBasePath);
33
+ }
34
+
35
+ /**
36
+ * Implementação da otimização de rotas
37
+ */
38
+ async executeTask(taskDescription: string, context: TaskContext): Promise<TaskResult> {
39
+ const warnings: string[] = [];
40
+ const recommendations: string[] = [];
41
+
42
+ // Aqui seria feita a otimização real de rotas
43
+ const success = warnings.length === 0;
44
+ const details = success
45
+ ? 'Rotas otimizadas com sucesso'
46
+ : `Avisos: ${warnings.join(', ')}`;
47
+
48
+ return {
49
+ success,
50
+ details,
51
+ warnings: warnings.length > 0 ? warnings : undefined,
52
+ recommendations: recommendations.length > 0 ? recommendations : undefined
53
+ };
54
+ }
55
+
56
+ /**
57
+ * Valida rota
58
+ */
59
+ validateRoute(route: Partial<Route>): { valid: boolean; errors: string[]; warnings: string[] } {
60
+ const errors: string[] = [];
61
+ const warnings: string[] = [];
62
+
63
+ if (!route.name || route.name.trim().length === 0) {
64
+ errors.push('Nome da rota é obrigatório');
65
+ }
66
+
67
+ if (!route.waypoints || route.waypoints.length === 0) {
68
+ errors.push('Rota deve ter pelo menos um waypoint');
69
+ } else if (route.waypoints.length === 1) {
70
+ warnings.push('Rota com apenas um waypoint (considere adicionar mais paradas)');
71
+ }
72
+
73
+ // Validar coordenadas
74
+ route.waypoints?.forEach((wp, index) => {
75
+ if (wp.lat < -90 || wp.lat > 90) {
76
+ errors.push(`Waypoint ${index + 1}: Latitude inválida (${wp.lat})`);
77
+ }
78
+ if (wp.lng < -180 || wp.lng > 180) {
79
+ errors.push(`Waypoint ${index + 1}: Longitude inválida (${wp.lng})`);
80
+ }
81
+ if (!wp.address || wp.address.trim().length === 0) {
82
+ warnings.push(`Waypoint ${index + 1}: Endereço vazio`);
83
+ }
84
+ });
85
+
86
+ // Validar ordem sequencial
87
+ const orders = route.waypoints?.map(wp => wp.order).sort((a, b) => a - b) || [];
88
+ const expectedOrders = Array.from({ length: orders.length }, (_, i) => i + 1);
89
+ if (JSON.stringify(orders) !== JSON.stringify(expectedOrders)) {
90
+ warnings.push('Ordem dos waypoints não é sequencial (1, 2, 3...)');
91
+ }
92
+
93
+ return { valid: errors.length === 0, errors, warnings };
94
+ }
95
+
96
+ /**
97
+ * Calcula distância aproximada entre dois pontos (Haversine)
98
+ */
99
+ calculateDistance(lat1: number, lng1: number, lat2: number, lng2: number): number {
100
+ const R = 6371; // Raio da Terra em km
101
+ const dLat = this.deg2rad(lat2 - lat1);
102
+ const dLng = this.deg2rad(lng2 - lng1);
103
+
104
+ const a =
105
+ Math.sin(dLat / 2) * Math.sin(dLat / 2) +
106
+ Math.cos(this.deg2rad(lat1)) *
107
+ Math.cos(this.deg2rad(lat2)) *
108
+ Math.sin(dLng / 2) *
109
+ Math.sin(dLng / 2);
110
+
111
+ const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
112
+ return R * c; // Distância em km
113
+ }
114
+
115
+ private deg2rad(deg: number): number {
116
+ return deg * (Math.PI / 180);
117
+ }
118
+
119
+ /**
120
+ * Estima distância total da rota
121
+ */
122
+ estimateTotalDistance(waypoints: Waypoint[]): number {
123
+ if (waypoints.length < 2) return 0;
124
+
125
+ let totalDistance = 0;
126
+ for (let i = 0; i < waypoints.length - 1; i++) {
127
+ const wp1 = waypoints[i];
128
+ const wp2 = waypoints[i + 1];
129
+ totalDistance += this.calculateDistance(wp1.lat, wp1.lng, wp2.lat, wp2.lng);
130
+ }
131
+
132
+ return Math.round(totalDistance * 10) / 10; // Arredondar para 1 casa decimal
133
+ }
134
+
135
+ /**
136
+ * Estima duração (assumindo velocidade média de 50 km/h)
137
+ */
138
+ estimateDuration(distanceKm: number, avgSpeedKmH: number = 50): number {
139
+ return Math.round((distanceKm / avgSpeedKmH) * 60); // Retorna em minutos
140
+ }
141
+
142
+ /**
143
+ * Especialidade padrão do Route Agent
144
+ */
145
+ protected getDefaultSpecialty(): string {
146
+ return `# Route Agent - Especialidade
147
+
148
+ ## Responsabilidades
149
+ - Otimizar rotas de entrega
150
+ - Calcular distâncias e tempo estimado
151
+ - Validar waypoints e sequência
152
+ - Sugerir rotas eficientes
153
+ - Minimizar tempo e custo de transporte
154
+
155
+ ## Expertise
156
+ - Otimização de Rotas
157
+ - Algoritmos de Roteamento (TSP, VRP)
158
+ - Cálculo de Distâncias (Haversine)
159
+ - Logística de Transporte
160
+ - Google Maps API / Mapbox
161
+
162
+ ## Regras
163
+ - Waypoints devem ter coordenadas válidas
164
+ - Ordem deve ser sequencial
165
+ - Minimizar distância total
166
+ - Considerar restrições de tempo
167
+ - Validar endereços
168
+
169
+ ## Tarefas Típicas
170
+ - Otimizar sequência de entregas
171
+ - Calcular distância total de rota
172
+ - Estimar tempo de viagem
173
+ - Validar coordenadas GPS
174
+ - Sugerir rotas alternativas
175
+ `;
176
+ }
177
+ }
@@ -0,0 +1,158 @@
1
+ /**
2
+ * CMS Agent (com Memória)
3
+ * Domínio: Site de Notícias
4
+ *
5
+ * Responsabilidades:
6
+ * - Validar estrutura de artigos/posts
7
+ * - Verificar campos obrigatórios (título, slug, conteúdo, autor)
8
+ * - Sugerir taxonomia (categorias, tags)
9
+ * - Validar schema do Supabase
10
+ * - Aprender padrões de conteúdo que funcionam
11
+ */
12
+
13
+ import { BaseAgent, TaskContext, TaskResult } from '../../core/base-agent';
14
+
15
+ export interface Article {
16
+ id: string;
17
+ title: string;
18
+ slug: string;
19
+ content: string;
20
+ author_id: string;
21
+ published_at: string | null;
22
+ category_id: string;
23
+ tags: string[];
24
+ }
25
+
26
+ export class CMSAgent extends BaseAgent {
27
+ constructor(memoryBasePath: string = '.agents/memory') {
28
+ super('cms-agent', memoryBasePath);
29
+ }
30
+
31
+ /**
32
+ * Implementação da validação de CMS
33
+ */
34
+ async executeTask(taskDescription: string, context: TaskContext): Promise<TaskResult> {
35
+ const issues: string[] = [];
36
+ const recommendations: string[] = [];
37
+
38
+ // Aqui seria feita a validação real de artigos
39
+ // Por enquanto, retorna sucesso
40
+ const success = issues.length === 0;
41
+ const details = success
42
+ ? 'Estrutura de CMS validada com sucesso'
43
+ : `Problemas encontrados: ${issues.join(', ')}`;
44
+
45
+ return {
46
+ success,
47
+ details,
48
+ issues: issues.length > 0 ? issues : undefined,
49
+ recommendations: recommendations.length > 0 ? recommendations : undefined
50
+ };
51
+ }
52
+
53
+ /**
54
+ * Valida estrutura de artigo
55
+ */
56
+ validateArticle(article: Partial<Article>): { valid: boolean; errors: string[] } {
57
+ const errors: string[] = [];
58
+
59
+ if (!article.title || article.title.trim().length === 0) {
60
+ errors.push('Título é obrigatório');
61
+ }
62
+
63
+ if (!article.slug || article.slug.trim().length === 0) {
64
+ errors.push('Slug é obrigatório');
65
+ } else if (!/^[a-z0-9-]+$/.test(article.slug)) {
66
+ errors.push('Slug deve conter apenas letras minúsculas, números e hífens');
67
+ }
68
+
69
+ if (!article.content || article.content.trim().length === 0) {
70
+ errors.push('Conteúdo é obrigatório');
71
+ }
72
+
73
+ if (!article.author_id) {
74
+ errors.push('Autor é obrigatório');
75
+ }
76
+
77
+ if (!article.category_id) {
78
+ errors.push('Categoria é obrigatória');
79
+ }
80
+
81
+ return { valid: errors.length === 0, errors };
82
+ }
83
+
84
+ /**
85
+ * Gera slug a partir do título
86
+ */
87
+ generateSlug(title: string): string {
88
+ return title
89
+ .toLowerCase()
90
+ .normalize('NFD')
91
+ .replace(/[\u0300-\u036f]/g, '') // Remove acentos
92
+ .replace(/[^a-z0-9\s-]/g, '') // Remove caracteres especiais
93
+ .trim()
94
+ .replace(/\s+/g, '-') // Substitui espaços por hífens
95
+ .replace(/-+/g, '-'); // Remove hífens duplicados
96
+ }
97
+
98
+ /**
99
+ * Valida schema Supabase para CMS
100
+ */
101
+ validateSchema(migrations: string[]): { valid: boolean; recommendations: string[] } {
102
+ const recommendations: string[] = [];
103
+ const hasArticlesTable = migrations.some(m => m.includes('create table articles'));
104
+ const hasCategoriesTable = migrations.some(m => m.includes('create table categories'));
105
+ const hasTagsTable = migrations.some(m => m.includes('create table tags'));
106
+
107
+ if (!hasArticlesTable) {
108
+ recommendations.push('Criar tabela "articles" (id, title, slug, content, author_id, published_at, category_id)');
109
+ }
110
+
111
+ if (!hasCategoriesTable) {
112
+ recommendations.push('Criar tabela "categories" (id, name, slug)');
113
+ }
114
+
115
+ if (!hasTagsTable) {
116
+ recommendations.push('Criar tabela "tags" (id, name) e tabela de relacionamento "article_tags"');
117
+ }
118
+
119
+ return { valid: recommendations.length === 0, recommendations };
120
+ }
121
+
122
+ /**
123
+ * Especialidade padrão do CMS Agent
124
+ */
125
+ protected getDefaultSpecialty(): string {
126
+ return `# CMS Agent - Especialidade
127
+
128
+ ## Responsabilidades
129
+ - Validar estrutura de artigos/posts
130
+ - Verificar campos obrigatórios (título, slug, conteúdo, autor)
131
+ - Sugerir taxonomia (categorias, tags)
132
+ - Validar schema do Supabase para CMS
133
+ - Gerar slugs automaticamente
134
+
135
+ ## Expertise
136
+ - Content Management Systems
137
+ - Taxonomia (categorias, tags)
138
+ - Schema de banco de dados para CMS
139
+ - SEO-friendly URLs (slugs)
140
+ - Estrutura de artigos/posts
141
+
142
+ ## Regras
143
+ - Título é obrigatório
144
+ - Slug deve ser único e SEO-friendly
145
+ - Conteúdo não pode estar vazio
146
+ - Autor deve estar vinculado
147
+ - Categoria é obrigatória
148
+ - Tags são opcionais mas recomendadas
149
+
150
+ ## Tarefas Típicas
151
+ - Validar estrutura de novos artigos
152
+ - Gerar slugs a partir de títulos
153
+ - Sugerir categorias e tags
154
+ - Validar schema de banco de dados
155
+ - Recomendar melhorias de taxonomia
156
+ `;
157
+ }
158
+ }