@codexa/cli 9.0.6 → 9.0.8

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.
@@ -0,0 +1,272 @@
1
+ import { getDb } from "../db/connection";
2
+ import { initSchema, getPatternsForFiles, getRelatedDecisions, getArchitecturalAnalysisForSpec } from "../db/schema";
3
+ import { getKnowledgeForTask } from "../commands/knowledge";
4
+ import type { ContextSection, ContextData } from "./assembly";
5
+ import { assembleSections } from "./assembly";
6
+ import { getAgentDomain, adjustSectionPriorities, domainToScope } from "./domains";
7
+ import { filterRelevantDecisions, filterRelevantStandards } from "./scoring";
8
+ import {
9
+ buildProductSection,
10
+ buildArchitectureSection,
11
+ buildStandardsSection,
12
+ buildDecisionsSection,
13
+ buildReasoningSection,
14
+ buildAlertsSection,
15
+ buildDiscoveriesSection,
16
+ buildPatternsSection,
17
+ buildUtilitiesSection,
18
+ buildGraphSection,
19
+ buildStackSection,
20
+ buildHintsSection,
21
+ } from "./sections";
22
+
23
+ // v9.0: Contexto minimo para subagent (max ~2KB)
24
+ const MAX_MINIMAL_CONTEXT = 2048;
25
+
26
+ export function getMinimalContextForSubagent(taskId: number): string {
27
+ initSchema();
28
+ const db = getDb();
29
+
30
+ const task = db.query("SELECT * FROM tasks WHERE id = ?").get(taskId) as any;
31
+ if (!task) return "ERRO: Task nao encontrada";
32
+
33
+ const spec = db.query("SELECT * FROM specs WHERE id = ?").get(task.spec_id) as any;
34
+ const context = db.query("SELECT * FROM context WHERE spec_id = ?").get(task.spec_id) as any;
35
+
36
+ const taskFiles = task.files ? JSON.parse(task.files) : [];
37
+ const domain = domainToScope(getAgentDomain(task.agent));
38
+
39
+ // 1. Standards REQUIRED apenas (nao recommended)
40
+ const requiredStandards = db.query(
41
+ `SELECT rule FROM standards
42
+ WHERE enforcement = 'required' AND (scope = 'all' OR scope = ?)
43
+ LIMIT 10`
44
+ ).all(domain) as any[];
45
+
46
+ // 2. Blockers CRITICAL (spec atual + cross-feature)
47
+ const criticalBlockers = db.query(
48
+ `SELECT DISTINCT content FROM knowledge
49
+ WHERE severity = 'critical'
50
+ ORDER BY CASE WHEN spec_id = ? THEN 0 ELSE 1 END, created_at DESC
51
+ LIMIT 5`
52
+ ).all(task.spec_id) as any[];
53
+
54
+ // 3. Decisoes da task anterior (dependency direta)
55
+ const dependsOn = task.depends_on ? JSON.parse(task.depends_on) : [];
56
+ let depDecisions: any[] = [];
57
+ if (dependsOn.length > 0) {
58
+ const placeholders = dependsOn.map(() => '?').join(',');
59
+ const depTasks = db.query(
60
+ `SELECT id FROM tasks WHERE spec_id = ? AND number IN (${placeholders})`
61
+ ).all(task.spec_id, ...dependsOn) as any[];
62
+
63
+ for (const dt of depTasks) {
64
+ const reasoning = db.query(
65
+ `SELECT thought FROM reasoning_log
66
+ WHERE spec_id = ? AND task_id = ? AND category = 'recommendation'
67
+ ORDER BY created_at DESC LIMIT 2`
68
+ ).all(task.spec_id, dt.id) as any[];
69
+ depDecisions.push(...reasoning);
70
+ }
71
+ }
72
+
73
+ // Montar output minimo
74
+ let output = `## CONTEXTO MINIMO (Task #${task.number})
75
+
76
+ **Feature:** ${spec.name}
77
+ **Objetivo:** ${context?.objective || "N/A"}
78
+ **Arquivos:** ${taskFiles.join(", ") || "Nenhum especificado"}
79
+ `;
80
+
81
+ if (requiredStandards.length > 0) {
82
+ output += `\n**Standards (OBRIGATORIOS):**\n${requiredStandards.map((s: any) => `- ${s.rule}`).join("\n")}\n`;
83
+ }
84
+
85
+ if (criticalBlockers.length > 0) {
86
+ output += `\n**BLOCKERS CRITICOS:**\n${criticalBlockers.map((b: any) => `[X] ${b.content}`).join("\n")}\n`;
87
+ }
88
+
89
+ if (depDecisions.length > 0) {
90
+ output += `\n**Recomendacoes de tasks anteriores:**\n${depDecisions.map((d: any) => `- ${d.thought}`).join("\n")}\n`;
91
+ }
92
+
93
+ output += `
94
+ **Contexto expandido**: Se precisar de mais contexto, execute:
95
+ codexa context detail standards # Todos os standards
96
+ codexa context detail decisions # Todas as decisoes
97
+ codexa context detail patterns # Patterns do projeto
98
+ codexa context detail knowledge # Knowledge completo
99
+ codexa context detail architecture # Analise arquitetural
100
+ `;
101
+
102
+ // Truncar se exceder limite
103
+ if (output.length > MAX_MINIMAL_CONTEXT) {
104
+ output = output.substring(0, MAX_MINIMAL_CONTEXT - 100) + "\n\n[CONTEXTO TRUNCADO - use: codexa context detail <secao>]\n";
105
+ }
106
+
107
+ return output;
108
+ }
109
+
110
+ // ═══════════════════════════════════════════════════════════════
111
+ // CONTEXT BUILDER (v9.0 — decomposed from v8.1 monolith)
112
+ // ═══════════════════════════════════════════════════════════════
113
+
114
+ function fetchContextData(taskId: number): ContextData | null {
115
+ const db = getDb();
116
+
117
+ const task = db.query("SELECT * FROM tasks WHERE id = ?").get(taskId) as any;
118
+ if (!task) return null;
119
+
120
+ const spec = db.query("SELECT * FROM specs WHERE id = ?").get(task.spec_id) as any;
121
+ const context = db.query("SELECT * FROM context WHERE spec_id = ?").get(task.spec_id) as any;
122
+ const project = db.query("SELECT * FROM project WHERE id = 'default'").get() as any;
123
+
124
+ // v8.4: Analise arquitetural (link explicito via analysis_id ou nome)
125
+ const archAnalysis = getArchitecturalAnalysisForSpec(spec.name, task.spec_id);
126
+
127
+ // Arquivos da task para filtrar contexto relevante
128
+ const taskFiles = task.files ? JSON.parse(task.files) : [];
129
+ const domain = domainToScope(getAgentDomain(task.agent));
130
+
131
+ // Decisoes relevantes (max 8, priorizando as que mencionam arquivos da task)
132
+ const allDecisions = db
133
+ .query("SELECT * FROM decisions WHERE spec_id = ? AND status = 'active' ORDER BY created_at DESC")
134
+ .all(task.spec_id) as any[];
135
+ const decisions = filterRelevantDecisions(allDecisions, taskFiles, 8);
136
+
137
+ // Standards required + recommended que se aplicam aos arquivos
138
+ const standards = db
139
+ .query(
140
+ `SELECT * FROM standards
141
+ WHERE (scope = 'all' OR scope = ?)
142
+ ORDER BY enforcement DESC, category`
143
+ )
144
+ .all(domain) as any[];
145
+ const relevantStandards = filterRelevantStandards(standards, taskFiles);
146
+
147
+ // Knowledge com caps e indicadores de truncamento
148
+ const allKnowledge = getKnowledgeForTask(task.spec_id, taskId);
149
+ const allCriticalKnowledge = allKnowledge.filter((k: any) => k.severity === 'critical' || k.severity === 'warning');
150
+ const criticalKnowledge = allCriticalKnowledge.slice(0, 20);
151
+ const truncatedCritical = allCriticalKnowledge.length - criticalKnowledge.length;
152
+ const allInfoKnowledge = allKnowledge.filter((k: any) => k.severity === 'info');
153
+ const infoKnowledge = allInfoKnowledge.slice(0, 10);
154
+ const truncatedInfo = allInfoKnowledge.length - infoKnowledge.length;
155
+
156
+ const productContext = db.query("SELECT * FROM product_context WHERE id = 'default'").get() as any;
157
+ const patterns = getPatternsForFiles(taskFiles);
158
+
159
+ // v8.2: Reasoning de tasks dependentes + todas tasks completas recentes
160
+ const dependsOn = task.depends_on ? JSON.parse(task.depends_on) : [];
161
+ const depReasoning: any[] = [];
162
+ const seenTaskIds = new Set<number>();
163
+
164
+ if (dependsOn.length > 0) {
165
+ const placeholders = dependsOn.map(() => '?').join(',');
166
+ const depTasks = db.query(
167
+ `SELECT id, number FROM tasks WHERE spec_id = ? AND number IN (${placeholders})`
168
+ ).all(task.spec_id, ...dependsOn) as any[];
169
+
170
+ for (const depTask of depTasks) {
171
+ seenTaskIds.add(depTask.id);
172
+ const reasoning = db.query(
173
+ `SELECT category, thought FROM reasoning_log
174
+ WHERE spec_id = ? AND task_id = ?
175
+ AND category IN ('recommendation', 'decision', 'challenge')
176
+ ORDER BY
177
+ CASE importance WHEN 'critical' THEN 1 WHEN 'high' THEN 2 ELSE 3 END,
178
+ created_at DESC
179
+ LIMIT 3`
180
+ ).all(task.spec_id, depTask.id) as any[];
181
+ for (const r of reasoning) {
182
+ depReasoning.push({ ...r, fromTask: depTask.number });
183
+ }
184
+ }
185
+ }
186
+
187
+ const completedTasks = db.query(
188
+ `SELECT t.id, t.number FROM tasks t
189
+ WHERE t.spec_id = ? AND t.status = 'done' AND t.id != ?
190
+ ORDER BY t.completed_at DESC LIMIT 10`
191
+ ).all(task.spec_id, taskId) as any[];
192
+
193
+ for (const ct of completedTasks) {
194
+ if (seenTaskIds.has(ct.id)) continue;
195
+ const reasoning = db.query(
196
+ `SELECT category, thought FROM reasoning_log
197
+ WHERE spec_id = ? AND task_id = ?
198
+ AND category IN ('recommendation', 'challenge')
199
+ AND importance IN ('critical', 'high')
200
+ ORDER BY
201
+ CASE importance WHEN 'critical' THEN 1 ELSE 2 END,
202
+ created_at DESC
203
+ LIMIT 2`
204
+ ).all(task.spec_id, ct.id) as any[];
205
+ for (const r of reasoning) {
206
+ depReasoning.push({ ...r, fromTask: ct.number });
207
+ }
208
+ }
209
+
210
+ const libContexts = db.query(
211
+ "SELECT lib_name, version FROM lib_contexts ORDER BY lib_name LIMIT 10"
212
+ ).all() as any[];
213
+
214
+ const graphDecisions: any[] = [];
215
+ for (const file of taskFiles) {
216
+ try {
217
+ const related = getRelatedDecisions(file, "file");
218
+ for (const d of related) {
219
+ if (!graphDecisions.find((gd: any) => gd.id === d.id)) {
220
+ graphDecisions.push(d);
221
+ }
222
+ }
223
+ } catch { /* ignore if graph empty */ }
224
+ }
225
+
226
+ const discoveredPatterns = context?.patterns ? JSON.parse(context.patterns) : [];
227
+
228
+ return {
229
+ db, task, spec, context, project, taskFiles, domain, archAnalysis,
230
+ decisions, allDecisions, relevantStandards,
231
+ criticalKnowledge, truncatedCritical, infoKnowledge, truncatedInfo,
232
+ productContext, patterns, depReasoning, libContexts,
233
+ graphDecisions, discoveredPatterns,
234
+ };
235
+ }
236
+
237
+ // ── Main Entry Point ──────────────────────────────────────────
238
+
239
+ export function getContextForSubagent(taskId: number): string {
240
+ initSchema();
241
+
242
+ const data = fetchContextData(taskId);
243
+ if (!data) return "ERRO: Task nao encontrada";
244
+
245
+ const header = `## CONTEXTO (Task #${data.task.number})
246
+
247
+ **Feature:** ${data.spec.name}
248
+ **Objetivo:** ${data.context?.objective || "N/A"}
249
+ **Arquivos:** ${data.taskFiles.join(", ") || "Nenhum especificado"}
250
+ `;
251
+
252
+ const allSections = [
253
+ buildProductSection(data),
254
+ buildArchitectureSection(data),
255
+ buildStandardsSection(data),
256
+ buildDecisionsSection(data),
257
+ buildReasoningSection(data),
258
+ buildAlertsSection(data),
259
+ buildDiscoveriesSection(data),
260
+ buildPatternsSection(data),
261
+ buildUtilitiesSection(data),
262
+ buildGraphSection(data),
263
+ buildStackSection(data),
264
+ buildHintsSection(data),
265
+ ].filter((s): s is ContextSection => s !== null);
266
+
267
+ // v9.4: Domain-based priority adjustment (replaces binary AGENT_SECTIONS)
268
+ const agentDomain = getAgentDomain(data.task.agent);
269
+ const sections = adjustSectionPriorities(allSections, agentDomain);
270
+
271
+ return assembleSections(header, sections);
272
+ }
@@ -0,0 +1,21 @@
1
+ // Re-exports for backward compatibility
2
+ export { getContextForSubagent, getMinimalContextForSubagent } from "./generator";
3
+ export { assembleSections, MAX_CONTEXT_SIZE } from "./assembly";
4
+ export { AGENT_DOMAIN, DOMAIN_PROFILES, getAgentDomain, adjustSectionPriorities, domainToScope } from "./domains";
5
+ export type { AgentDomain, Relevance, SectionName, DomainProfile } from "./domains";
6
+ export type { ContextSection, ContextData } from "./assembly";
7
+ export { filterRelevantDecisions, filterRelevantStandards } from "./scoring";
8
+ export {
9
+ buildProductSection,
10
+ buildArchitectureSection,
11
+ buildStandardsSection,
12
+ buildDecisionsSection,
13
+ buildReasoningSection,
14
+ buildAlertsSection,
15
+ buildDiscoveriesSection,
16
+ buildPatternsSection,
17
+ buildUtilitiesSection,
18
+ buildGraphSection,
19
+ buildStackSection,
20
+ buildHintsSection,
21
+ } from "./sections";
@@ -0,0 +1,106 @@
1
+ // v8.3: Filtrar decisoes relevantes com scoring melhorado
2
+ export function filterRelevantDecisions(decisions: any[], taskFiles: string[], maxCount: number): any[] {
3
+ if (decisions.length === 0) return [];
4
+ if (taskFiles.length === 0) return decisions.slice(0, maxCount);
5
+
6
+ // Extrair keywords semanticas dos arquivos da task
7
+ const fileExtensions = new Set(taskFiles.map(f => f.split('.').pop()?.toLowerCase()).filter(Boolean));
8
+ const fileDirs = new Set(taskFiles.flatMap(f => f.split('/').slice(0, -1)).filter(Boolean));
9
+
10
+ // Keywords de dominio para scoring contextual
11
+ const domainKeywords: Record<string, string[]> = {
12
+ frontend: ['component', 'page', 'layout', 'css', 'style', 'ui', 'react', 'next', 'hook'],
13
+ backend: ['api', 'route', 'handler', 'middleware', 'server', 'endpoint', 'controller'],
14
+ database: ['schema', 'migration', 'query', 'table', 'index', 'sql', 'model'],
15
+ testing: ['test', 'spec', 'mock', 'fixture', 'assert', 'jest', 'vitest'],
16
+ };
17
+
18
+ const scored = decisions.map((d) => {
19
+ let score = 0;
20
+ const combined = `${d.decision || ''} ${d.title || ''} ${d.rationale || ''}`.toLowerCase();
21
+
22
+ // Arquivo exato e diretorio (+10/+5)
23
+ for (const file of taskFiles) {
24
+ const fileName = file.split("/").pop() || file;
25
+ const dirName = file.split("/").slice(-2, -1)[0] || "";
26
+
27
+ if (combined.includes(fileName.toLowerCase())) score += 10;
28
+ if (dirName && combined.includes(dirName.toLowerCase())) score += 5;
29
+ }
30
+
31
+ // v8.3: Extensao dos arquivos (+3)
32
+ for (const ext of fileExtensions) {
33
+ if (combined.includes(`.${ext}`)) { score += 3; break; }
34
+ }
35
+
36
+ // v8.3: Diretorio mencionado (+4)
37
+ for (const dir of fileDirs) {
38
+ if (combined.includes(dir.toLowerCase())) { score += 4; break; }
39
+ }
40
+
41
+ // v8.3: Keywords de dominio (+2)
42
+ const taskCombined = taskFiles.join(' ').toLowerCase();
43
+ for (const [, keywords] of Object.entries(domainKeywords)) {
44
+ for (const kw of keywords) {
45
+ if (combined.includes(kw) && taskCombined.includes(kw)) {
46
+ score += 2;
47
+ break;
48
+ }
49
+ }
50
+ }
51
+
52
+ // Recencia (+3/+1)
53
+ const age = Date.now() - new Date(d.created_at).getTime();
54
+ const hoursOld = age / (1000 * 60 * 60);
55
+ if (hoursOld < 1) score += 3;
56
+ else if (hoursOld < 24) score += 1;
57
+
58
+ return { ...d, _relevanceScore: score };
59
+ });
60
+
61
+ return scored
62
+ .sort((a, b) => b._relevanceScore - a._relevanceScore)
63
+ .slice(0, maxCount)
64
+ .map(({ _relevanceScore, ...d }) => d);
65
+ }
66
+
67
+ // v8.0: Filtrar standards relevantes para os arquivos da task
68
+ export function filterRelevantStandards(standards: any[], taskFiles: string[]): any[] {
69
+ if (standards.length === 0) return [];
70
+ if (taskFiles.length === 0) return standards;
71
+
72
+ // Extrair extensoes e diretorios dos arquivos da task
73
+ const extensions = new Set(taskFiles.map((f) => {
74
+ const ext = f.split(".").pop();
75
+ return ext ? `.${ext}` : "";
76
+ }).filter(Boolean));
77
+
78
+ const directories = new Set(taskFiles.map((f) => {
79
+ const parts = f.split("/");
80
+ return parts.length > 1 ? parts.slice(0, -1).join("/") : "";
81
+ }).filter(Boolean));
82
+
83
+ // Filtrar standards que se aplicam
84
+ return standards.filter((s) => {
85
+ // Standards de naming sempre aplicam
86
+ if (s.category === "naming") return true;
87
+
88
+ // Standards de code aplicam se mencionam extensao dos arquivos
89
+ if (s.category === "code") {
90
+ for (const ext of extensions) {
91
+ if (s.rule?.includes(ext) || s.scope === "all") return true;
92
+ }
93
+ }
94
+
95
+ // Standards de structure aplicam se mencionam diretorio
96
+ if (s.category === "structure") {
97
+ for (const dir of directories) {
98
+ if (s.rule?.includes(dir)) return true;
99
+ }
100
+ return s.scope === "all";
101
+ }
102
+
103
+ // Outros standards: incluir se scope combina
104
+ return true;
105
+ });
106
+ }
@@ -0,0 +1,247 @@
1
+ import { getUtilitiesForContext, getAgentHints } from "../db/schema";
2
+ import type { ContextSection, ContextData } from "./assembly";
3
+ import { getAgentDomain, domainToScope } from "./domains";
4
+
5
+ // ── Section Builders ──────────────────────────────────────────
6
+
7
+ export function buildProductSection(data: ContextData): ContextSection | null {
8
+ if (!data.productContext) return null;
9
+
10
+ let content = `
11
+ ### PRODUTO
12
+ - **Problema:** ${data.productContext.problem || "N/A"}
13
+ - **Usuarios:** ${data.productContext.target_users || "N/A"}`;
14
+ if (data.productContext.constraints) {
15
+ try {
16
+ const constraints = JSON.parse(data.productContext.constraints);
17
+ if (constraints.length > 0) {
18
+ content += `\n- **Restricoes:** ${constraints.slice(0, 3).join("; ")}${constraints.length > 3 ? ` [+${constraints.length - 3} mais]` : ''}`;
19
+ }
20
+ } catch { /* ignore parse errors */ }
21
+ }
22
+ content += "\n";
23
+
24
+ return { name: "PRODUTO", content, priority: 7 };
25
+ }
26
+
27
+ export function buildArchitectureSection(data: ContextData): ContextSection | null {
28
+ if (!data.archAnalysis) return null;
29
+
30
+ let content = `
31
+ ### ARQUITETURA (${data.archAnalysis.id})`;
32
+ if (data.archAnalysis.approach) {
33
+ const approachPreview = data.archAnalysis.approach.length > 500
34
+ ? data.archAnalysis.approach.substring(0, 500) + "..."
35
+ : data.archAnalysis.approach;
36
+ content += `\n**Abordagem:** ${approachPreview}`;
37
+ }
38
+ if (data.archAnalysis.risks) {
39
+ try {
40
+ const risks = JSON.parse(data.archAnalysis.risks);
41
+ if (risks.length > 0) {
42
+ const highRisks = risks.filter((r: any) => r.impact === 'high' || r.probability === 'high');
43
+ const risksToShow = highRisks.length > 0 ? highRisks.slice(0, 3) : risks.slice(0, 3);
44
+ content += `\n**Riscos:**`;
45
+ for (const r of risksToShow) {
46
+ content += `\n - ${r.description} (${r.probability}/${r.impact}) -> ${r.mitigation}`;
47
+ }
48
+ if (risks.length > risksToShow.length) {
49
+ content += `\n [+${risks.length - risksToShow.length} mais riscos]`;
50
+ }
51
+ }
52
+ } catch { /* ignore */ }
53
+ }
54
+ if (data.archAnalysis.decisions) {
55
+ try {
56
+ const archDecisions = JSON.parse(data.archAnalysis.decisions);
57
+ if (archDecisions.length > 0) {
58
+ content += `\n**Decisoes arquiteturais:**`;
59
+ for (const d of archDecisions.slice(0, 5)) {
60
+ content += `\n - ${d.decision}: ${d.rationale || ''}`;
61
+ }
62
+ if (archDecisions.length > 5) {
63
+ content += `\n [+${archDecisions.length - 5} mais]`;
64
+ }
65
+ }
66
+ } catch { /* ignore */ }
67
+ }
68
+ content += "\n";
69
+
70
+ return { name: "ARQUITETURA", content, priority: 3 };
71
+ }
72
+
73
+ export function buildStandardsSection(data: ContextData): ContextSection {
74
+ const requiredStds = data.relevantStandards.filter((s: any) => s.enforcement === 'required');
75
+ const recommendedStds = data.relevantStandards.filter((s: any) => s.enforcement === 'recommended');
76
+
77
+ let content = `
78
+ ### STANDARDS (${data.relevantStandards.length})`;
79
+ if (requiredStds.length > 0) {
80
+ content += `\n**Obrigatorios:**\n${requiredStds.map((s: any) => `- ${s.rule}`).join("\n")}`;
81
+ }
82
+ if (recommendedStds.length > 0) {
83
+ content += `\n**Recomendados:**\n${recommendedStds.map((s: any) => `- ${s.rule}`).join("\n")}`;
84
+ }
85
+ if (data.relevantStandards.length === 0) {
86
+ content += "\nNenhum standard aplicavel";
87
+ }
88
+ content += "\n";
89
+
90
+ return { name: "STANDARDS", content, priority: 1 };
91
+ }
92
+
93
+ export function buildDecisionsSection(data: ContextData): ContextSection {
94
+ const truncatedDecisions = data.allDecisions.length - data.decisions.length;
95
+ const content = `
96
+ ### DECISOES (${data.decisions.length}${truncatedDecisions > 0 ? ` [+${truncatedDecisions} mais - use: decisions list]` : ''})
97
+ ${data.decisions.length > 0 ? data.decisions.map((d) => `- **${d.title}**: ${d.decision}`).join("\n") : "Nenhuma"}
98
+ `;
99
+ return { name: "DECISOES", content, priority: 4 };
100
+ }
101
+
102
+ export function buildReasoningSection(data: ContextData): ContextSection | null {
103
+ if (data.depReasoning.length === 0) return null;
104
+
105
+ const content = `
106
+ ### CONTEXTO DE TASKS ANTERIORES
107
+ ${data.depReasoning.map((r: any) => `- [Task #${r.fromTask}/${r.category}] ${r.thought}`).join("\n")}
108
+ `;
109
+ return { name: "CONTEXTO DE TASKS ANTERIORES", content, priority: 5 };
110
+ }
111
+
112
+ export function buildAlertsSection(data: ContextData): ContextSection | null {
113
+ if (data.criticalKnowledge.length === 0) return null;
114
+
115
+ const severityIcon: Record<string, string> = { warning: "!!", critical: "XX" };
116
+ const content = `
117
+ ### ALERTAS (${data.criticalKnowledge.length}${data.truncatedCritical > 0 ? ` [+${data.truncatedCritical} mais - use: knowledge list --severity warning]` : ''})
118
+ ${data.criticalKnowledge.map((k: any) => `[${severityIcon[k.severity] || "!"}] ${k.content}`).join("\n")}
119
+ `;
120
+ return { name: "ALERTAS", content, priority: 2 };
121
+ }
122
+
123
+ export function buildDiscoveriesSection(data: ContextData): ContextSection | null {
124
+ if (data.infoKnowledge.length === 0) return null;
125
+
126
+ const content = `
127
+ ### DISCOVERIES DE TASKS ANTERIORES (${data.infoKnowledge.length}${data.truncatedInfo > 0 ? ` [+${data.truncatedInfo} mais - use: knowledge list]` : ''})
128
+ ${data.infoKnowledge.map((k: any) => `- ${k.content}`).join("\n")}
129
+ `;
130
+ return { name: "DISCOVERIES", content, priority: 8 };
131
+ }
132
+
133
+ export function buildPatternsSection(data: ContextData): ContextSection | null {
134
+ let content = "";
135
+
136
+ if (data.patterns.length > 0) {
137
+ content += `
138
+ ### PATTERNS DO PROJETO (${data.patterns.length})
139
+ ${data.patterns.map((p: any) => {
140
+ const tmpl = p.template || "";
141
+ const preview = tmpl.length > 200 ? tmpl.substring(0, 200) + `... [truncado de ${tmpl.length} chars]` : tmpl;
142
+ return `- **${p.name}** (${p.category}): ${preview || p.description || "Sem template"}`;
143
+ }).join("\n")}
144
+ `;
145
+ }
146
+
147
+ if (data.discoveredPatterns.length > 0) {
148
+ const patternsToShow = data.discoveredPatterns.slice(-10);
149
+ content += `
150
+ ### PATTERNS DESCOBERTOS (${data.discoveredPatterns.length})
151
+ ${data.discoveredPatterns.length > 10 ? `[mostrando ultimos 10 de ${data.discoveredPatterns.length}]\n` : ''}${patternsToShow.map((p: any) => `- ${p.pattern}${p.source_task ? ` (Task #${p.source_task})` : ""}`).join("\n")}
152
+ `;
153
+ }
154
+
155
+ if (!content) return null;
156
+ return { name: "PATTERNS", content, priority: 9 };
157
+ }
158
+
159
+ export function buildUtilitiesSection(data: ContextData): ContextSection | null {
160
+ try {
161
+ const taskDirs = [...new Set(data.taskFiles.map((f: string) => {
162
+ const parts = f.replace(/\\/g, "/").split("/");
163
+ return parts.slice(0, -1).join("/");
164
+ }).filter(Boolean))];
165
+
166
+ const agentScope = domainToScope(getAgentDomain(data.task.agent)) || undefined;
167
+ let relevantUtilities = getUtilitiesForContext(taskDirs, undefined, 15);
168
+
169
+ if (relevantUtilities.length < 5 && agentScope) {
170
+ const scopeUtils = getUtilitiesForContext([], agentScope, 15);
171
+ const existingKeys = new Set(relevantUtilities.map((u: any) => `${u.file_path}:${u.utility_name}`));
172
+ for (const u of scopeUtils) {
173
+ if (!existingKeys.has(`${u.file_path}:${u.utility_name}`)) {
174
+ relevantUtilities.push(u);
175
+ }
176
+ if (relevantUtilities.length >= 15) break;
177
+ }
178
+ }
179
+
180
+ if (relevantUtilities.length === 0) return null;
181
+
182
+ const totalCount = (data.db.query("SELECT COUNT(*) as c FROM project_utilities").get() as any)?.c || 0;
183
+ const truncated = totalCount - relevantUtilities.length;
184
+ const content = `
185
+ ### UTILITIES EXISTENTES (${relevantUtilities.length}${truncated > 0 ? ` [+${truncated} mais]` : ''})
186
+ **REGRA DRY**: Reutilize ao inves de recriar. Importe do arquivo existente.
187
+ ${relevantUtilities.map((u: any) => {
188
+ const sig = u.signature ? ` ${u.signature}` : '';
189
+ return `- **${u.utility_name}** [${u.utility_type}]${sig} <- \`${u.file_path}\``;
190
+ }).join("\n")}
191
+ `;
192
+ return { name: "UTILITIES", content, priority: 8 };
193
+ } catch { /* tabela pode nao existir ainda */ }
194
+ return null;
195
+ }
196
+
197
+ export function buildGraphSection(data: ContextData): ContextSection | null {
198
+ let content = "";
199
+
200
+ if (data.graphDecisions.length > 0) {
201
+ content += `
202
+ ### DECISOES QUE AFETAM SEUS ARQUIVOS (${data.graphDecisions.length})
203
+ ${data.graphDecisions.map((d: any) => `- **${d.title}**: ${d.decision}`).join("\n")}
204
+ `;
205
+ }
206
+
207
+ if (!content) return null;
208
+ return { name: "GRAPH", content, priority: 6 };
209
+ }
210
+
211
+ export function buildStackSection(data: ContextData): ContextSection | null {
212
+ let content = "";
213
+
214
+ if (data.project) {
215
+ const stack = JSON.parse(data.project.stack);
216
+ const allStackEntries = Object.entries(stack);
217
+ const mainStack = allStackEntries.slice(0, 6);
218
+ content += `
219
+ ### STACK
220
+ ${mainStack.map(([k, v]) => `${k}: ${v}`).join(" | ")}${allStackEntries.length > 6 ? ` [+${allStackEntries.length - 6} mais]` : ''}
221
+ `;
222
+ }
223
+
224
+ if (data.libContexts.length > 0) {
225
+ content += `
226
+ ### BIBLIOTECAS
227
+ ${data.libContexts.map((l: any) => `- ${l.lib_name}${l.version ? ` v${l.version}` : ""}`).join("\n")}
228
+ `;
229
+ }
230
+
231
+ if (!content) return null;
232
+ return { name: "STACK", content, priority: 11 };
233
+ }
234
+
235
+ export function buildHintsSection(data: ContextData): ContextSection | null {
236
+ const agentType = data.task.agent;
237
+ if (!agentType) return null;
238
+
239
+ const hints = getAgentHints(agentType);
240
+ if (hints.length === 0) return null;
241
+
242
+ const content = `
243
+ ### HISTORICO DO AGENTE (${agentType})
244
+ ${hints.map(h => `- ${h}`).join("\n")}
245
+ `;
246
+ return { name: "HINTS", content, priority: 10 };
247
+ }