@esankhan3/anvil-knowledge-core 0.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.
- package/README.md +194 -0
- package/dist/__tests__/chunker.test.d.ts +10 -0
- package/dist/__tests__/chunker.test.d.ts.map +1 -0
- package/dist/__tests__/chunker.test.js +161 -0
- package/dist/__tests__/chunker.test.js.map +1 -0
- package/dist/__tests__/query-classifier.test.d.ts +5 -0
- package/dist/__tests__/query-classifier.test.d.ts.map +1 -0
- package/dist/__tests__/query-classifier.test.js +158 -0
- package/dist/__tests__/query-classifier.test.js.map +1 -0
- package/dist/__tests__/retriever-defaults.test.d.ts +12 -0
- package/dist/__tests__/retriever-defaults.test.d.ts.map +1 -0
- package/dist/__tests__/retriever-defaults.test.js +37 -0
- package/dist/__tests__/retriever-defaults.test.js.map +1 -0
- package/dist/__tests__/structural-hasher.test.d.ts +5 -0
- package/dist/__tests__/structural-hasher.test.d.ts.map +1 -0
- package/dist/__tests__/structural-hasher.test.js +185 -0
- package/dist/__tests__/structural-hasher.test.js.map +1 -0
- package/dist/ast-graph-builder.d.ts +38 -0
- package/dist/ast-graph-builder.d.ts.map +1 -0
- package/dist/ast-graph-builder.js +1041 -0
- package/dist/ast-graph-builder.js.map +1 -0
- package/dist/chunker.d.ts +47 -0
- package/dist/chunker.d.ts.map +1 -0
- package/dist/chunker.js +428 -0
- package/dist/chunker.js.map +1 -0
- package/dist/claude-runner.d.ts +10 -0
- package/dist/claude-runner.d.ts.map +1 -0
- package/dist/claude-runner.js +10 -0
- package/dist/claude-runner.js.map +1 -0
- package/dist/config.d.ts +36 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +83 -0
- package/dist/config.js.map +1 -0
- package/dist/cross-repo-detector.d.ts +7 -0
- package/dist/cross-repo-detector.d.ts.map +1 -0
- package/dist/cross-repo-detector.js +990 -0
- package/dist/cross-repo-detector.js.map +1 -0
- package/dist/embedder.d.ts +84 -0
- package/dist/embedder.d.ts.map +1 -0
- package/dist/embedder.js +378 -0
- package/dist/embedder.js.map +1 -0
- package/dist/file-walker.d.ts +18 -0
- package/dist/file-walker.d.ts.map +1 -0
- package/dist/file-walker.js +221 -0
- package/dist/file-walker.js.map +1 -0
- package/dist/git-diff.d.ts +32 -0
- package/dist/git-diff.d.ts.map +1 -0
- package/dist/git-diff.js +145 -0
- package/dist/git-diff.js.map +1 -0
- package/dist/graph-metrics.d.ts +31 -0
- package/dist/graph-metrics.d.ts.map +1 -0
- package/dist/graph-metrics.js +277 -0
- package/dist/graph-metrics.js.map +1 -0
- package/dist/graph-query.d.ts +8 -0
- package/dist/graph-query.d.ts.map +1 -0
- package/dist/graph-query.js +79 -0
- package/dist/graph-query.js.map +1 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +43 -0
- package/dist/index.js.map +1 -0
- package/dist/indexer.d.ts +98 -0
- package/dist/indexer.d.ts.map +1 -0
- package/dist/indexer.js +635 -0
- package/dist/indexer.js.map +1 -0
- package/dist/project-graph-builder-core.d.ts +48 -0
- package/dist/project-graph-builder-core.d.ts.map +1 -0
- package/dist/project-graph-builder-core.js +213 -0
- package/dist/project-graph-builder-core.js.map +1 -0
- package/dist/project-graph-builder.d.ts +39 -0
- package/dist/project-graph-builder.d.ts.map +1 -0
- package/dist/project-graph-builder.js +640 -0
- package/dist/project-graph-builder.js.map +1 -0
- package/dist/query-classifier.d.ts +38 -0
- package/dist/query-classifier.d.ts.map +1 -0
- package/dist/query-classifier.js +199 -0
- package/dist/query-classifier.js.map +1 -0
- package/dist/query-router.d.ts +82 -0
- package/dist/query-router.d.ts.map +1 -0
- package/dist/query-router.js +278 -0
- package/dist/query-router.js.map +1 -0
- package/dist/rag-evaluator.d.ts +53 -0
- package/dist/rag-evaluator.d.ts.map +1 -0
- package/dist/rag-evaluator.js +217 -0
- package/dist/rag-evaluator.js.map +1 -0
- package/dist/repo-profiler.d.ts +62 -0
- package/dist/repo-profiler.d.ts.map +1 -0
- package/dist/repo-profiler.js +488 -0
- package/dist/repo-profiler.js.map +1 -0
- package/dist/reranker.d.ts +8 -0
- package/dist/reranker.d.ts.map +1 -0
- package/dist/reranker.js +250 -0
- package/dist/reranker.js.map +1 -0
- package/dist/retriever.d.ts +42 -0
- package/dist/retriever.d.ts.map +1 -0
- package/dist/retriever.js +320 -0
- package/dist/retriever.js.map +1 -0
- package/dist/semantic-edge-detector.d.ts +28 -0
- package/dist/semantic-edge-detector.d.ts.map +1 -0
- package/dist/semantic-edge-detector.js +191 -0
- package/dist/semantic-edge-detector.js.map +1 -0
- package/dist/service-mesh-inferrer.d.ts +57 -0
- package/dist/service-mesh-inferrer.d.ts.map +1 -0
- package/dist/service-mesh-inferrer.js +322 -0
- package/dist/service-mesh-inferrer.js.map +1 -0
- package/dist/structural-hasher.d.ts +57 -0
- package/dist/structural-hasher.d.ts.map +1 -0
- package/dist/structural-hasher.js +350 -0
- package/dist/structural-hasher.js.map +1 -0
- package/dist/tree-sitter-parser.d.ts +71 -0
- package/dist/tree-sitter-parser.d.ts.map +1 -0
- package/dist/tree-sitter-parser.js +633 -0
- package/dist/tree-sitter-parser.js.map +1 -0
- package/dist/types.d.ts +179 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/vector-store.d.ts +56 -0
- package/dist/vector-store.d.ts.map +1 -0
- package/dist/vector-store.js +299 -0
- package/dist/vector-store.js.map +1 -0
- package/dist/workspace-detector.d.ts +11 -0
- package/dist/workspace-detector.d.ts.map +1 -0
- package/dist/workspace-detector.js +587 -0
- package/dist/workspace-detector.js.map +1 -0
- package/package.json +41 -0
|
@@ -0,0 +1,640 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LLM-powered project graph builder.
|
|
3
|
+
*
|
|
4
|
+
* Assembles context from factory.yaml, per-repo graph reports, and
|
|
5
|
+
* cross-repo edges, then sends a single LLM call to produce a semantic
|
|
6
|
+
* understanding of the project architecture.
|
|
7
|
+
*
|
|
8
|
+
* The result is a ProjectGraph — stored as PROJECT_GRAPH.json and
|
|
9
|
+
* PROJECT_SUMMARY.md — that agents use for cross-repo decision making.
|
|
10
|
+
*/
|
|
11
|
+
// Re-export legacy class for backward compat
|
|
12
|
+
export { ProjectGraphBuilder } from './project-graph-builder-core.js';
|
|
13
|
+
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
|
14
|
+
import { join } from 'node:path';
|
|
15
|
+
import { homedir } from 'node:os';
|
|
16
|
+
import { execSync, execFileSync } from 'node:child_process';
|
|
17
|
+
// ---------------------------------------------------------------------------
|
|
18
|
+
// Constants
|
|
19
|
+
// ---------------------------------------------------------------------------
|
|
20
|
+
const KB_DIR = join(process.env.ANVIL_HOME || process.env.FF_HOME || join(homedir(), '.anvil'), 'knowledge-base');
|
|
21
|
+
const PROJECT_GRAPH_FILE = 'PROJECT_GRAPH.json';
|
|
22
|
+
const PROJECT_SUMMARY_FILE = 'PROJECT_SUMMARY.md';
|
|
23
|
+
/**
|
|
24
|
+
* Detect which LLM provider is available from environment variables.
|
|
25
|
+
* Returns provider name and API key, preferring cheaper models.
|
|
26
|
+
*/
|
|
27
|
+
function detectProvider(preferredProvider) {
|
|
28
|
+
// If user specified a provider, try that first
|
|
29
|
+
if (preferredProvider) {
|
|
30
|
+
const found = tryProvider(preferredProvider);
|
|
31
|
+
if (found)
|
|
32
|
+
return found;
|
|
33
|
+
throw new Error(`Provider "${preferredProvider}" not available. Check your API key.`);
|
|
34
|
+
}
|
|
35
|
+
// Auto-detect in order of preference (CLI tools first, then API providers)
|
|
36
|
+
for (const p of ['claude-cli', 'gemini-cli', 'anthropic', 'openai', 'gemini', 'openrouter']) {
|
|
37
|
+
const found = tryProvider(p);
|
|
38
|
+
if (found)
|
|
39
|
+
return found;
|
|
40
|
+
}
|
|
41
|
+
throw new Error('No LLM provider available. Set an API key (OPENAI_API_KEY, ANTHROPIC_API_KEY, GOOGLE_API_KEY) or install claude/gemini CLI.');
|
|
42
|
+
}
|
|
43
|
+
function tryProvider(name) {
|
|
44
|
+
switch (name) {
|
|
45
|
+
case 'openai': {
|
|
46
|
+
const key = process.env.OPENAI_API_KEY;
|
|
47
|
+
if (!key)
|
|
48
|
+
return null;
|
|
49
|
+
return { provider: 'openai', apiKey: key, model: 'gpt-4o-mini', endpoint: 'https://api.openai.com/v1/chat/completions' };
|
|
50
|
+
}
|
|
51
|
+
case 'gemini': {
|
|
52
|
+
const key = process.env.GOOGLE_API_KEY || process.env.GEMINI_API_KEY;
|
|
53
|
+
if (!key)
|
|
54
|
+
return null;
|
|
55
|
+
return { provider: 'gemini', apiKey: key, model: 'gemini-2.0-flash', endpoint: `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${key}` };
|
|
56
|
+
}
|
|
57
|
+
case 'anthropic': {
|
|
58
|
+
const key = process.env.ANTHROPIC_API_KEY;
|
|
59
|
+
if (!key)
|
|
60
|
+
return null;
|
|
61
|
+
return { provider: 'anthropic', apiKey: key, model: 'claude-sonnet-4-20250514', endpoint: 'https://api.anthropic.com/v1/messages' };
|
|
62
|
+
}
|
|
63
|
+
case 'openrouter': {
|
|
64
|
+
const key = process.env.OPENROUTER_API_KEY;
|
|
65
|
+
if (!key)
|
|
66
|
+
return null;
|
|
67
|
+
return { provider: 'openrouter', apiKey: key, model: 'anthropic/claude-sonnet-4-20250514', endpoint: 'https://openrouter.ai/api/v1/chat/completions' };
|
|
68
|
+
}
|
|
69
|
+
case 'claude-cli': {
|
|
70
|
+
try {
|
|
71
|
+
execSync('claude --version', { stdio: 'pipe', timeout: 5000 });
|
|
72
|
+
return { provider: 'claude-cli', apiKey: 'cli', model: 'claude-sonnet-4-20250514', endpoint: 'cli' };
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
case 'gemini-cli': {
|
|
79
|
+
try {
|
|
80
|
+
execSync('gemini --version', { stdio: 'pipe', timeout: 5000 });
|
|
81
|
+
return { provider: 'gemini-cli', apiKey: 'cli', model: 'gemini-2.0-flash', endpoint: 'cli' };
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
default:
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Call an LLM via OpenAI-compatible API (works for OpenAI, OpenRouter)
|
|
93
|
+
* or Anthropic/Gemini specific APIs.
|
|
94
|
+
*/
|
|
95
|
+
async function callLLM(provider, projectPrompt, userPrompt, modelOverride) {
|
|
96
|
+
const model = modelOverride || provider.model;
|
|
97
|
+
if (provider.provider === 'claude-cli') {
|
|
98
|
+
return callClaudeCli(projectPrompt, userPrompt);
|
|
99
|
+
}
|
|
100
|
+
if (provider.provider === 'gemini-cli') {
|
|
101
|
+
return callGeminiCli(projectPrompt, userPrompt);
|
|
102
|
+
}
|
|
103
|
+
if (provider.provider === 'anthropic') {
|
|
104
|
+
return callAnthropic(provider.apiKey, model, projectPrompt, userPrompt);
|
|
105
|
+
}
|
|
106
|
+
if (provider.provider === 'gemini') {
|
|
107
|
+
return callGemini(provider.apiKey, model, projectPrompt, userPrompt);
|
|
108
|
+
}
|
|
109
|
+
// OpenAI-compatible (openai, openrouter)
|
|
110
|
+
return callOpenAICompatible(provider, model, projectPrompt, userPrompt);
|
|
111
|
+
}
|
|
112
|
+
async function callOpenAICompatible(provider, model, projectPrompt, userPrompt) {
|
|
113
|
+
const response = await fetch(provider.endpoint, {
|
|
114
|
+
method: 'POST',
|
|
115
|
+
headers: {
|
|
116
|
+
'Content-Type': 'application/json',
|
|
117
|
+
Authorization: `Bearer ${provider.apiKey}`,
|
|
118
|
+
},
|
|
119
|
+
body: JSON.stringify({
|
|
120
|
+
model,
|
|
121
|
+
messages: [
|
|
122
|
+
{ role: 'project', content: projectPrompt },
|
|
123
|
+
{ role: 'user', content: userPrompt },
|
|
124
|
+
],
|
|
125
|
+
temperature: 0.2,
|
|
126
|
+
max_tokens: 4096,
|
|
127
|
+
response_format: { type: 'json_object' },
|
|
128
|
+
}),
|
|
129
|
+
});
|
|
130
|
+
if (!response.ok) {
|
|
131
|
+
const body = await response.text();
|
|
132
|
+
throw new Error(`${provider.provider} API error (${response.status}): ${body.slice(0, 300)}`);
|
|
133
|
+
}
|
|
134
|
+
const json = await response.json();
|
|
135
|
+
const content = json.choices?.[0]?.message?.content ?? '';
|
|
136
|
+
const usage = json.usage ?? {};
|
|
137
|
+
return {
|
|
138
|
+
content,
|
|
139
|
+
inputTokens: usage.prompt_tokens ?? 0,
|
|
140
|
+
outputTokens: usage.completion_tokens ?? 0,
|
|
141
|
+
costUsd: estimateCost(provider.provider, model, usage.prompt_tokens ?? 0, usage.completion_tokens ?? 0),
|
|
142
|
+
model,
|
|
143
|
+
provider: provider.provider,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
async function callAnthropic(apiKey, model, projectPrompt, userPrompt) {
|
|
147
|
+
const response = await fetch('https://api.anthropic.com/v1/messages', {
|
|
148
|
+
method: 'POST',
|
|
149
|
+
headers: {
|
|
150
|
+
'Content-Type': 'application/json',
|
|
151
|
+
'x-api-key': apiKey,
|
|
152
|
+
'anthropic-version': '2023-06-01',
|
|
153
|
+
},
|
|
154
|
+
body: JSON.stringify({
|
|
155
|
+
model,
|
|
156
|
+
max_tokens: 4096,
|
|
157
|
+
temperature: 0.2,
|
|
158
|
+
project: projectPrompt,
|
|
159
|
+
messages: [{ role: 'user', content: userPrompt + '\n\nRespond with valid JSON only.' }],
|
|
160
|
+
}),
|
|
161
|
+
});
|
|
162
|
+
if (!response.ok) {
|
|
163
|
+
const body = await response.text();
|
|
164
|
+
throw new Error(`Anthropic API error (${response.status}): ${body.slice(0, 300)}`);
|
|
165
|
+
}
|
|
166
|
+
const json = await response.json();
|
|
167
|
+
const content = json.content?.[0]?.text ?? '';
|
|
168
|
+
const usage = json.usage ?? {};
|
|
169
|
+
return {
|
|
170
|
+
content,
|
|
171
|
+
inputTokens: usage.input_tokens ?? 0,
|
|
172
|
+
outputTokens: usage.output_tokens ?? 0,
|
|
173
|
+
costUsd: estimateCost('anthropic', model, usage.input_tokens ?? 0, usage.output_tokens ?? 0),
|
|
174
|
+
model,
|
|
175
|
+
provider: 'anthropic',
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
async function callGemini(apiKey, model, projectPrompt, userPrompt) {
|
|
179
|
+
const endpoint = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`;
|
|
180
|
+
const response = await fetch(endpoint, {
|
|
181
|
+
method: 'POST',
|
|
182
|
+
headers: { 'Content-Type': 'application/json' },
|
|
183
|
+
body: JSON.stringify({
|
|
184
|
+
contents: [{ parts: [{ text: projectPrompt + '\n\n' + userPrompt + '\n\nRespond with valid JSON only.' }] }],
|
|
185
|
+
generationConfig: { temperature: 0.2, maxOutputTokens: 4096, responseMimeType: 'application/json' },
|
|
186
|
+
}),
|
|
187
|
+
});
|
|
188
|
+
if (!response.ok) {
|
|
189
|
+
const body = await response.text();
|
|
190
|
+
throw new Error(`Gemini API error (${response.status}): ${body.slice(0, 300)}`);
|
|
191
|
+
}
|
|
192
|
+
const json = await response.json();
|
|
193
|
+
const content = json.candidates?.[0]?.content?.parts?.[0]?.text ?? '';
|
|
194
|
+
const usage = json.usageMetadata ?? {};
|
|
195
|
+
return {
|
|
196
|
+
content,
|
|
197
|
+
inputTokens: usage.promptTokenCount ?? 0,
|
|
198
|
+
outputTokens: usage.candidatesTokenCount ?? 0,
|
|
199
|
+
costUsd: estimateCost('gemini', model, usage.promptTokenCount ?? 0, usage.candidatesTokenCount ?? 0),
|
|
200
|
+
model,
|
|
201
|
+
provider: 'gemini',
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
async function callClaudeCli(projectPrompt, userPrompt) {
|
|
205
|
+
const fullPrompt = projectPrompt + '\n\n' + userPrompt + '\n\nRespond with valid JSON only.';
|
|
206
|
+
const startTime = Date.now();
|
|
207
|
+
const output = execFileSync('claude', ['-p', fullPrompt, '--output-format', 'text'], {
|
|
208
|
+
encoding: 'utf-8',
|
|
209
|
+
timeout: 120_000,
|
|
210
|
+
maxBuffer: 10 * 1024 * 1024,
|
|
211
|
+
});
|
|
212
|
+
const durationMs = Date.now() - startTime;
|
|
213
|
+
const estimatedTokens = Math.ceil(fullPrompt.length / 4);
|
|
214
|
+
const estimatedOutputTokens = Math.ceil(output.length / 4);
|
|
215
|
+
return {
|
|
216
|
+
content: output,
|
|
217
|
+
inputTokens: estimatedTokens,
|
|
218
|
+
outputTokens: estimatedOutputTokens,
|
|
219
|
+
costUsd: estimateCost('anthropic', 'claude-sonnet-4-20250514', estimatedTokens, estimatedOutputTokens),
|
|
220
|
+
model: 'claude-sonnet-4-20250514',
|
|
221
|
+
provider: 'claude-cli',
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
async function callGeminiCli(projectPrompt, userPrompt) {
|
|
225
|
+
const fullPrompt = projectPrompt + '\n\n' + userPrompt + '\n\nRespond with valid JSON only.';
|
|
226
|
+
const startTime = Date.now();
|
|
227
|
+
const output = execFileSync('gemini', ['-p', fullPrompt], {
|
|
228
|
+
encoding: 'utf-8',
|
|
229
|
+
timeout: 120_000,
|
|
230
|
+
maxBuffer: 10 * 1024 * 1024,
|
|
231
|
+
});
|
|
232
|
+
const durationMs = Date.now() - startTime;
|
|
233
|
+
const estimatedTokens = Math.ceil(fullPrompt.length / 4);
|
|
234
|
+
const estimatedOutputTokens = Math.ceil(output.length / 4);
|
|
235
|
+
return {
|
|
236
|
+
content: output,
|
|
237
|
+
inputTokens: estimatedTokens,
|
|
238
|
+
outputTokens: estimatedOutputTokens,
|
|
239
|
+
costUsd: estimateCost('gemini', 'gemini-2.0-flash', estimatedTokens, estimatedOutputTokens),
|
|
240
|
+
model: 'gemini-2.0-flash',
|
|
241
|
+
provider: 'gemini-cli',
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
function estimateCost(provider, model, inputTokens, outputTokens) {
|
|
245
|
+
// Approximate pricing per 1M tokens [input, output]
|
|
246
|
+
const pricing = {
|
|
247
|
+
'gpt-4o-mini': [0.15, 0.60],
|
|
248
|
+
'gpt-4o': [2.50, 10.00],
|
|
249
|
+
'claude-sonnet-4-20250514': [3.00, 15.00],
|
|
250
|
+
'claude-haiku-4-5-20251001': [0.80, 4.00],
|
|
251
|
+
'gemini-2.0-flash': [0.10, 0.40],
|
|
252
|
+
};
|
|
253
|
+
const [inputRate, outputRate] = pricing[model] ?? [1.00, 3.00];
|
|
254
|
+
return (inputTokens * inputRate + outputTokens * outputRate) / 1_000_000;
|
|
255
|
+
}
|
|
256
|
+
// ---------------------------------------------------------------------------
|
|
257
|
+
// Prompt assembly
|
|
258
|
+
// ---------------------------------------------------------------------------
|
|
259
|
+
const SYSTEM_PROMPT = `You are a senior software architect analyzing a multi-repo project.
|
|
260
|
+
Given the project definition, per-repo code analysis reports, and detected cross-repo relationships,
|
|
261
|
+
produce a structured JSON analysis of the project architecture.
|
|
262
|
+
|
|
263
|
+
Your analysis helps engineers understand how repos work together so they can make correct
|
|
264
|
+
cross-repo changes. Focus on: data flows, ownership boundaries, communication patterns,
|
|
265
|
+
and what breaks if a component changes.
|
|
266
|
+
|
|
267
|
+
Respond with ONLY valid JSON matching this exact structure:
|
|
268
|
+
{
|
|
269
|
+
"architectureSummary": "2-3 paragraph overview of the project architecture",
|
|
270
|
+
"repoRoles": {
|
|
271
|
+
"<repo-name>": {
|
|
272
|
+
"role": "one-line role description",
|
|
273
|
+
"responsibilities": ["responsibility 1", "responsibility 2"],
|
|
274
|
+
"ownsData": ["data owned by this repo"],
|
|
275
|
+
"criticality": "high|medium|low"
|
|
276
|
+
}
|
|
277
|
+
},
|
|
278
|
+
"communityLabels": {
|
|
279
|
+
"<community-id>": {
|
|
280
|
+
"label": "semantic name for this cluster",
|
|
281
|
+
"description": "what this community does",
|
|
282
|
+
"repos": ["repo names involved"]
|
|
283
|
+
}
|
|
284
|
+
},
|
|
285
|
+
"relationships": [
|
|
286
|
+
{
|
|
287
|
+
"from": "source-repo",
|
|
288
|
+
"to": "target-repo",
|
|
289
|
+
"type": "sync-http|async-event|shared-db|shared-types|deploys-to|other",
|
|
290
|
+
"description": "what this connection does",
|
|
291
|
+
"contract": "where the contract is defined (file, schema, etc)",
|
|
292
|
+
"criticality": "high|medium|low",
|
|
293
|
+
"direction": "unidirectional|bidirectional"
|
|
294
|
+
}
|
|
295
|
+
],
|
|
296
|
+
"keyFlows": [
|
|
297
|
+
{
|
|
298
|
+
"name": "flow name",
|
|
299
|
+
"trigger": "what starts this flow",
|
|
300
|
+
"steps": [
|
|
301
|
+
{
|
|
302
|
+
"repo": "repo-name",
|
|
303
|
+
"component": "path or module",
|
|
304
|
+
"action": "what happens here",
|
|
305
|
+
"protocol": "http|kafka|grpc|db|etc",
|
|
306
|
+
"nextStep": "what happens next"
|
|
307
|
+
}
|
|
308
|
+
],
|
|
309
|
+
"failureMode": "what happens when this flow fails"
|
|
310
|
+
}
|
|
311
|
+
]
|
|
312
|
+
}`;
|
|
313
|
+
/**
|
|
314
|
+
* Assemble the user prompt from available project data.
|
|
315
|
+
*/
|
|
316
|
+
function assembleUserPrompt(factoryYaml, graphReports, crossRepoEdges) {
|
|
317
|
+
const sections = [];
|
|
318
|
+
sections.push('## Project Definition (factory.yaml)\n');
|
|
319
|
+
sections.push(factoryYaml.slice(0, 4000));
|
|
320
|
+
if (graphReports.length > 0) {
|
|
321
|
+
sections.push('\n## Per-Repo Code Analysis Reports\n');
|
|
322
|
+
for (const { repo, report } of graphReports) {
|
|
323
|
+
// Truncate each report to ~800 tokens to keep total input manageable
|
|
324
|
+
const truncated = report.length > 3200 ? report.slice(0, 3200) + '\n[... truncated]' : report;
|
|
325
|
+
sections.push(`### ${repo}\n${truncated}\n`);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
if (crossRepoEdges.length > 0) {
|
|
329
|
+
sections.push('\n## Detected Cross-Repo Relationships\n');
|
|
330
|
+
for (const edge of crossRepoEdges.slice(0, 30)) {
|
|
331
|
+
sections.push(`- ${edge.source} → ${edge.target} (${edge.type}): ${edge.evidence}`);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
sections.push('\n\nAnalyze this project and produce the structured JSON response.');
|
|
335
|
+
return sections.join('\n');
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Build an LLM-powered project graph for the given project.
|
|
339
|
+
*/
|
|
340
|
+
export async function buildProjectGraph(project, factoryYamlPath, options) {
|
|
341
|
+
const log = options?.onProgress ?? (() => { });
|
|
342
|
+
const projectDir = join(KB_DIR, project);
|
|
343
|
+
const startTime = Date.now();
|
|
344
|
+
// 1. Read factory.yaml
|
|
345
|
+
log('Reading project configuration...');
|
|
346
|
+
if (!existsSync(factoryYamlPath)) {
|
|
347
|
+
throw new Error(`factory.yaml not found at ${factoryYamlPath}`);
|
|
348
|
+
}
|
|
349
|
+
const factoryYaml = readFileSync(factoryYamlPath, 'utf-8');
|
|
350
|
+
// 2. Collect per-repo graph reports
|
|
351
|
+
log('Collecting per-repo graph reports...');
|
|
352
|
+
const graphReports = [];
|
|
353
|
+
if (existsSync(projectDir)) {
|
|
354
|
+
const { readdirSync, statSync } = await import('node:fs');
|
|
355
|
+
for (const entry of readdirSync(projectDir)) {
|
|
356
|
+
const reportPath = join(projectDir, entry, 'GRAPH_REPORT.md');
|
|
357
|
+
if (existsSync(reportPath)) {
|
|
358
|
+
try {
|
|
359
|
+
const report = readFileSync(reportPath, 'utf-8');
|
|
360
|
+
graphReports.push({ repo: entry, report });
|
|
361
|
+
}
|
|
362
|
+
catch { /* skip unreadable */ }
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
if (graphReports.length === 0) {
|
|
367
|
+
log('Warning: No per-repo graph reports found. Run "anvil index" or refresh KB first for better results.');
|
|
368
|
+
}
|
|
369
|
+
// 3. Collect cross-repo edges from project graph
|
|
370
|
+
log('Reading cross-repo relationships...');
|
|
371
|
+
const crossRepoEdges = [];
|
|
372
|
+
const projectGraphPath = join(projectDir, 'system_graph_v2.json');
|
|
373
|
+
if (existsSync(projectGraphPath)) {
|
|
374
|
+
try {
|
|
375
|
+
const graphData = JSON.parse(readFileSync(projectGraphPath, 'utf-8'));
|
|
376
|
+
// graphology export format
|
|
377
|
+
const edges = graphData.edges ?? [];
|
|
378
|
+
for (const e of edges) {
|
|
379
|
+
if (e.attributes?.crossRepo) {
|
|
380
|
+
crossRepoEdges.push({
|
|
381
|
+
source: e.source,
|
|
382
|
+
target: e.target,
|
|
383
|
+
type: e.attributes.type ?? 'unknown',
|
|
384
|
+
evidence: e.attributes.evidence ?? '',
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
catch { /* skip */ }
|
|
390
|
+
}
|
|
391
|
+
// 4. Assemble prompt
|
|
392
|
+
const userPrompt = assembleUserPrompt(factoryYaml, graphReports, crossRepoEdges);
|
|
393
|
+
const estimatedInputTokens = Math.ceil((SYSTEM_PROMPT.length + userPrompt.length) / 4);
|
|
394
|
+
log(`Assembled prompt: ~${estimatedInputTokens} input tokens`);
|
|
395
|
+
if (options?.dryRun) {
|
|
396
|
+
log('Dry run — not calling LLM. Prompt assembled successfully.');
|
|
397
|
+
const dryGraph = {
|
|
398
|
+
meta: {
|
|
399
|
+
generatedAt: new Date().toISOString(),
|
|
400
|
+
model: 'dry-run',
|
|
401
|
+
provider: 'none',
|
|
402
|
+
costUsd: 0,
|
|
403
|
+
inputTokens: estimatedInputTokens,
|
|
404
|
+
outputTokens: 0,
|
|
405
|
+
durationMs: 0,
|
|
406
|
+
},
|
|
407
|
+
architectureSummary: '(dry run — no LLM call made)',
|
|
408
|
+
repoRoles: {},
|
|
409
|
+
communityLabels: {},
|
|
410
|
+
relationships: [],
|
|
411
|
+
keyFlows: [],
|
|
412
|
+
};
|
|
413
|
+
return dryGraph;
|
|
414
|
+
}
|
|
415
|
+
// 5. Detect provider and call LLM
|
|
416
|
+
const providerConfig = detectProvider(options?.provider);
|
|
417
|
+
log(`Using ${providerConfig.provider} (${options?.model || providerConfig.model})...`);
|
|
418
|
+
const result = await callLLM(providerConfig, SYSTEM_PROMPT, userPrompt, options?.model);
|
|
419
|
+
log(`LLM response: ${result.inputTokens} input, ${result.outputTokens} output tokens ($${result.costUsd.toFixed(4)})`);
|
|
420
|
+
// 6. Parse response
|
|
421
|
+
let parsed;
|
|
422
|
+
try {
|
|
423
|
+
// Strip markdown code fences if present
|
|
424
|
+
let content = result.content.trim();
|
|
425
|
+
if (content.startsWith('```')) {
|
|
426
|
+
content = content.replace(/^```(?:json)?\n?/, '').replace(/\n?```$/, '');
|
|
427
|
+
}
|
|
428
|
+
parsed = JSON.parse(content);
|
|
429
|
+
}
|
|
430
|
+
catch (err) {
|
|
431
|
+
// Retry once with a nudge
|
|
432
|
+
log('First response was not valid JSON. Retrying...');
|
|
433
|
+
const retryResult = await callLLM(providerConfig, SYSTEM_PROMPT, userPrompt + '\n\nIMPORTANT: Your previous response was not valid JSON. Return ONLY the JSON object, no markdown fences or extra text.', options?.model);
|
|
434
|
+
try {
|
|
435
|
+
let content = retryResult.content.trim();
|
|
436
|
+
if (content.startsWith('```')) {
|
|
437
|
+
content = content.replace(/^```(?:json)?\n?/, '').replace(/\n?```$/, '');
|
|
438
|
+
}
|
|
439
|
+
parsed = JSON.parse(content);
|
|
440
|
+
result.inputTokens += retryResult.inputTokens;
|
|
441
|
+
result.outputTokens += retryResult.outputTokens;
|
|
442
|
+
result.costUsd += retryResult.costUsd;
|
|
443
|
+
}
|
|
444
|
+
catch {
|
|
445
|
+
throw new Error(`LLM returned invalid JSON after retry: ${retryResult.content.slice(0, 200)}`);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
// 7. Build ProjectGraph with validated fields
|
|
449
|
+
const meta = {
|
|
450
|
+
generatedAt: new Date().toISOString(),
|
|
451
|
+
model: result.model,
|
|
452
|
+
provider: result.provider,
|
|
453
|
+
costUsd: result.costUsd,
|
|
454
|
+
inputTokens: result.inputTokens,
|
|
455
|
+
outputTokens: result.outputTokens,
|
|
456
|
+
durationMs: Date.now() - startTime,
|
|
457
|
+
};
|
|
458
|
+
const graph = {
|
|
459
|
+
meta,
|
|
460
|
+
architectureSummary: parsed.architectureSummary ?? '(no summary generated)',
|
|
461
|
+
repoRoles: parsed.repoRoles ?? {},
|
|
462
|
+
communityLabels: parsed.communityLabels ?? {},
|
|
463
|
+
relationships: Array.isArray(parsed.relationships) ? parsed.relationships : [],
|
|
464
|
+
keyFlows: Array.isArray(parsed.keyFlows) ? parsed.keyFlows : [],
|
|
465
|
+
};
|
|
466
|
+
// 8. Save
|
|
467
|
+
mkdirSync(projectDir, { recursive: true });
|
|
468
|
+
writeFileSync(join(projectDir, PROJECT_GRAPH_FILE), JSON.stringify(graph, null, 2), 'utf-8');
|
|
469
|
+
const summary = renderProjectSummary(project, graph);
|
|
470
|
+
writeFileSync(join(projectDir, PROJECT_SUMMARY_FILE), summary, 'utf-8');
|
|
471
|
+
log(`Saved PROJECT_GRAPH.json and PROJECT_SUMMARY.md to ${projectDir}`);
|
|
472
|
+
return graph;
|
|
473
|
+
}
|
|
474
|
+
// ---------------------------------------------------------------------------
|
|
475
|
+
// Load existing project graph
|
|
476
|
+
// ---------------------------------------------------------------------------
|
|
477
|
+
export function loadProjectGraph(project) {
|
|
478
|
+
const path = join(KB_DIR, project, PROJECT_GRAPH_FILE);
|
|
479
|
+
if (!existsSync(path))
|
|
480
|
+
return null;
|
|
481
|
+
try {
|
|
482
|
+
return JSON.parse(readFileSync(path, 'utf-8'));
|
|
483
|
+
}
|
|
484
|
+
catch {
|
|
485
|
+
return null;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
export function loadProjectSummary(project) {
|
|
489
|
+
const path = join(KB_DIR, project, PROJECT_SUMMARY_FILE);
|
|
490
|
+
if (!existsSync(path))
|
|
491
|
+
return null;
|
|
492
|
+
try {
|
|
493
|
+
return readFileSync(path, 'utf-8');
|
|
494
|
+
}
|
|
495
|
+
catch {
|
|
496
|
+
return null;
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
export function getProjectGraphStatus(project) {
|
|
500
|
+
const graph = loadProjectGraph(project);
|
|
501
|
+
if (!graph) {
|
|
502
|
+
return { exists: false, generatedAt: null, model: null, costUsd: null };
|
|
503
|
+
}
|
|
504
|
+
return {
|
|
505
|
+
exists: true,
|
|
506
|
+
generatedAt: graph.meta.generatedAt,
|
|
507
|
+
model: graph.meta.model,
|
|
508
|
+
costUsd: graph.meta.costUsd,
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
// ---------------------------------------------------------------------------
|
|
512
|
+
// Cost estimation (no LLM call)
|
|
513
|
+
// ---------------------------------------------------------------------------
|
|
514
|
+
export function estimateProjectGraphCost(project, factoryYamlPath, provider) {
|
|
515
|
+
const factoryYaml = existsSync(factoryYamlPath)
|
|
516
|
+
? readFileSync(factoryYamlPath, 'utf-8')
|
|
517
|
+
: '';
|
|
518
|
+
const graphReports = [];
|
|
519
|
+
const projectDir = join(KB_DIR, project);
|
|
520
|
+
if (existsSync(projectDir)) {
|
|
521
|
+
try {
|
|
522
|
+
const { readdirSync } = require('node:fs');
|
|
523
|
+
for (const entry of readdirSync(projectDir)) {
|
|
524
|
+
const reportPath = join(projectDir, entry, 'GRAPH_REPORT.md');
|
|
525
|
+
if (existsSync(reportPath)) {
|
|
526
|
+
graphReports.push({ repo: entry, report: readFileSync(reportPath, 'utf-8') });
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
catch { /* skip */ }
|
|
531
|
+
}
|
|
532
|
+
const userPrompt = assembleUserPrompt(factoryYaml, graphReports, []);
|
|
533
|
+
const inputTokens = Math.ceil((SYSTEM_PROMPT.length + userPrompt.length) / 4);
|
|
534
|
+
const outputTokens = 2000; // Estimate ~2K output tokens
|
|
535
|
+
const detected = detectProvider(provider);
|
|
536
|
+
const cost = estimateCost(detected.provider, detected.model, inputTokens, outputTokens);
|
|
537
|
+
return {
|
|
538
|
+
estimatedInputTokens: inputTokens,
|
|
539
|
+
estimatedOutputTokens: outputTokens,
|
|
540
|
+
estimatedCostUsd: cost,
|
|
541
|
+
model: detected.model,
|
|
542
|
+
provider: detected.provider,
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
// ---------------------------------------------------------------------------
|
|
546
|
+
// Markdown rendering
|
|
547
|
+
// ---------------------------------------------------------------------------
|
|
548
|
+
export function renderProjectSummary(project, graph) {
|
|
549
|
+
const sections = [];
|
|
550
|
+
sections.push(`# Project Graph: ${project}`);
|
|
551
|
+
sections.push(`\n> Generated ${graph.meta.generatedAt} using ${graph.meta.model} ($${graph.meta.costUsd.toFixed(4)})\n`);
|
|
552
|
+
// Architecture summary
|
|
553
|
+
sections.push(`## Architecture\n`);
|
|
554
|
+
sections.push(graph.architectureSummary);
|
|
555
|
+
// Repo roles
|
|
556
|
+
const repoEntries = Object.entries(graph.repoRoles);
|
|
557
|
+
if (repoEntries.length > 0) {
|
|
558
|
+
sections.push(`\n## Repo Roles\n`);
|
|
559
|
+
for (const [repo, role] of repoEntries) {
|
|
560
|
+
sections.push(`### ${repo} (${role.criticality} criticality)`);
|
|
561
|
+
sections.push(`**Role:** ${role.role}\n`);
|
|
562
|
+
if (role.responsibilities.length > 0) {
|
|
563
|
+
sections.push('**Responsibilities:**');
|
|
564
|
+
for (const r of role.responsibilities) {
|
|
565
|
+
sections.push(`- ${r}`);
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
if (role.ownsData.length > 0) {
|
|
569
|
+
sections.push(`\n**Owns:** ${role.ownsData.join(', ')}`);
|
|
570
|
+
}
|
|
571
|
+
sections.push('');
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
// Relationships
|
|
575
|
+
if (graph.relationships.length > 0) {
|
|
576
|
+
sections.push(`## Cross-Repo Relationships\n`);
|
|
577
|
+
sections.push('| From | To | Type | Description | Criticality |');
|
|
578
|
+
sections.push('|------|-----|------|-------------|-------------|');
|
|
579
|
+
for (const rel of graph.relationships) {
|
|
580
|
+
sections.push(`| ${rel.from} | ${rel.to} | ${rel.type} | ${rel.description} | ${rel.criticality} |`);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
// Key flows
|
|
584
|
+
if (graph.keyFlows.length > 0) {
|
|
585
|
+
sections.push(`\n## Key Flows\n`);
|
|
586
|
+
for (const flow of graph.keyFlows) {
|
|
587
|
+
sections.push(`### ${flow.name}`);
|
|
588
|
+
sections.push(`**Trigger:** ${flow.trigger}\n`);
|
|
589
|
+
for (let i = 0; i < flow.steps.length; i++) {
|
|
590
|
+
const step = flow.steps[i];
|
|
591
|
+
const arrow = i < flow.steps.length - 1 ? ' →' : '';
|
|
592
|
+
sections.push(`${i + 1}. **${step.repo}** (${step.component}): ${step.action} [${step.protocol}]${arrow}`);
|
|
593
|
+
}
|
|
594
|
+
if (flow.failureMode) {
|
|
595
|
+
sections.push(`\n**Failure mode:** ${flow.failureMode}`);
|
|
596
|
+
}
|
|
597
|
+
sections.push('');
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
// Community labels
|
|
601
|
+
const communities = Object.entries(graph.communityLabels);
|
|
602
|
+
if (communities.length > 0) {
|
|
603
|
+
sections.push(`## Module Communities\n`);
|
|
604
|
+
for (const [id, community] of communities) {
|
|
605
|
+
sections.push(`- **${community.label}** (${community.repos.join(', ')}): ${community.description}`);
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
return sections.join('\n');
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* Format project graph for injection into agent prompts.
|
|
612
|
+
* Returns a compact version (~200-400 tokens) suitable for L0+L1 identity.
|
|
613
|
+
*/
|
|
614
|
+
export function formatProjectGraphForPrompt(graph) {
|
|
615
|
+
const lines = [];
|
|
616
|
+
// Architecture summary (truncated)
|
|
617
|
+
const summary = graph.architectureSummary.length > 600
|
|
618
|
+
? graph.architectureSummary.slice(0, 600) + '...'
|
|
619
|
+
: graph.architectureSummary;
|
|
620
|
+
lines.push(`Architecture: ${summary}`);
|
|
621
|
+
// Repo roles (compact)
|
|
622
|
+
const roles = Object.entries(graph.repoRoles);
|
|
623
|
+
if (roles.length > 0) {
|
|
624
|
+
lines.push('\nRepo roles:');
|
|
625
|
+
for (const [repo, role] of roles) {
|
|
626
|
+
const data = role.ownsData.length > 0 ? ` Owns: ${role.ownsData.join(', ')}.` : '';
|
|
627
|
+
lines.push(`- ${repo}: ${role.role}${data} Criticality: ${role.criticality}.`);
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
// Key flows (compact)
|
|
631
|
+
if (graph.keyFlows.length > 0) {
|
|
632
|
+
lines.push('\nKey flows:');
|
|
633
|
+
for (const flow of graph.keyFlows.slice(0, 5)) {
|
|
634
|
+
const path = flow.steps.map(s => s.repo).join(' → ');
|
|
635
|
+
lines.push(`- ${flow.name}: ${path}`);
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
return lines.join('\n');
|
|
639
|
+
}
|
|
640
|
+
//# sourceMappingURL=project-graph-builder.js.map
|