@grafema/mcp 0.2.5-beta → 0.2.7
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 +49 -25
- package/dist/analysis-worker.js +8 -4
- package/dist/analysis-worker.js.map +1 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +15 -3
- package/dist/config.js.map +1 -1
- package/dist/definitions.d.ts.map +1 -1
- package/dist/definitions.js +69 -0
- package/dist/definitions.js.map +1 -1
- package/dist/handlers/analysis-handlers.d.ts +9 -0
- package/dist/handlers/analysis-handlers.d.ts.map +1 -0
- package/dist/handlers/analysis-handlers.js +73 -0
- package/dist/handlers/analysis-handlers.js.map +1 -0
- package/dist/handlers/context-handlers.d.ts +21 -0
- package/dist/handlers/context-handlers.d.ts.map +1 -0
- package/dist/handlers/context-handlers.js +330 -0
- package/dist/handlers/context-handlers.js.map +1 -0
- package/dist/handlers/coverage-handlers.d.ts +6 -0
- package/dist/handlers/coverage-handlers.d.ts.map +1 -0
- package/dist/handlers/coverage-handlers.js +42 -0
- package/dist/handlers/coverage-handlers.js.map +1 -0
- package/dist/handlers/dataflow-handlers.d.ts +8 -0
- package/dist/handlers/dataflow-handlers.d.ts.map +1 -0
- package/dist/handlers/dataflow-handlers.js +140 -0
- package/dist/handlers/dataflow-handlers.js.map +1 -0
- package/dist/handlers/documentation-handlers.d.ts +6 -0
- package/dist/handlers/documentation-handlers.d.ts.map +1 -0
- package/dist/handlers/documentation-handlers.js +79 -0
- package/dist/handlers/documentation-handlers.js.map +1 -0
- package/dist/handlers/guarantee-handlers.d.ts +21 -0
- package/dist/handlers/guarantee-handlers.d.ts.map +1 -0
- package/dist/handlers/guarantee-handlers.js +251 -0
- package/dist/handlers/guarantee-handlers.js.map +1 -0
- package/dist/handlers/guard-handlers.d.ts +14 -0
- package/dist/handlers/guard-handlers.d.ts.map +1 -0
- package/dist/handlers/guard-handlers.js +77 -0
- package/dist/handlers/guard-handlers.js.map +1 -0
- package/dist/handlers/index.d.ts +14 -0
- package/dist/handlers/index.d.ts.map +1 -0
- package/dist/handlers/index.js +14 -0
- package/dist/handlers/index.js.map +1 -0
- package/dist/handlers/issue-handlers.d.ts +6 -0
- package/dist/handlers/issue-handlers.d.ts.map +1 -0
- package/dist/handlers/issue-handlers.js +66 -0
- package/dist/handlers/issue-handlers.js.map +1 -0
- package/dist/handlers/project-handlers.d.ts +7 -0
- package/dist/handlers/project-handlers.d.ts.map +1 -0
- package/dist/handlers/project-handlers.js +153 -0
- package/dist/handlers/project-handlers.js.map +1 -0
- package/dist/handlers/query-handlers.d.ts +8 -0
- package/dist/handlers/query-handlers.d.ts.map +1 -0
- package/dist/handlers/query-handlers.js +171 -0
- package/dist/handlers/query-handlers.js.map +1 -0
- package/dist/handlers.d.ts +3 -1
- package/dist/handlers.d.ts.map +1 -1
- package/dist/handlers.js +199 -4
- package/dist/handlers.js.map +1 -1
- package/dist/server.js +7 -1
- package/dist/server.js.map +1 -1
- package/dist/types.d.ts +9 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/analysis-worker.ts +10 -2
- package/src/config.ts +24 -0
- package/src/definitions.ts +70 -0
- package/src/handlers/analysis-handlers.ts +105 -0
- package/src/handlers/context-handlers.ts +410 -0
- package/src/handlers/coverage-handlers.ts +56 -0
- package/src/handlers/dataflow-handlers.ts +193 -0
- package/src/handlers/documentation-handlers.ts +89 -0
- package/src/handlers/guarantee-handlers.ts +278 -0
- package/src/handlers/guard-handlers.ts +100 -0
- package/src/handlers/index.ts +14 -0
- package/src/handlers/issue-handlers.ts +81 -0
- package/src/handlers/project-handlers.ts +200 -0
- package/src/handlers/query-handlers.ts +232 -0
- package/src/server.ts +13 -1
- package/src/types.ts +15 -0
- package/src/handlers.ts +0 -1373
package/src/handlers.ts
DELETED
|
@@ -1,1373 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* MCP Tool Handlers
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
import { ensureAnalyzed } from './analysis.js';
|
|
6
|
-
import { getProjectPath, getAnalysisStatus, getOrCreateBackend, getGuaranteeManager, getGuaranteeAPI, isAnalysisRunning } from './state.js';
|
|
7
|
-
import { CoverageAnalyzer, findCallsInFunction, findContainingFunction, validateServices, validatePatterns, validateWorkspace, getOnboardingInstruction } from '@grafema/core';
|
|
8
|
-
import type { CallInfo, CallerInfo } from '@grafema/core';
|
|
9
|
-
import { existsSync, readdirSync, statSync, writeFileSync, mkdirSync } from 'fs';
|
|
10
|
-
import type { Dirent } from 'fs';
|
|
11
|
-
import { join, basename } from 'path';
|
|
12
|
-
import { stringify as stringifyYAML } from 'yaml';
|
|
13
|
-
import {
|
|
14
|
-
normalizeLimit,
|
|
15
|
-
formatPaginationInfo,
|
|
16
|
-
guardResponseSize,
|
|
17
|
-
serializeBigInt,
|
|
18
|
-
findSimilarTypes,
|
|
19
|
-
textResult,
|
|
20
|
-
errorResult,
|
|
21
|
-
} from './utils.js';
|
|
22
|
-
import type {
|
|
23
|
-
ToolResult,
|
|
24
|
-
QueryGraphArgs,
|
|
25
|
-
FindCallsArgs,
|
|
26
|
-
FindNodesArgs,
|
|
27
|
-
TraceAliasArgs,
|
|
28
|
-
TraceDataFlowArgs,
|
|
29
|
-
CheckInvariantArgs,
|
|
30
|
-
AnalyzeProjectArgs,
|
|
31
|
-
GetSchemaArgs,
|
|
32
|
-
CreateGuaranteeArgs,
|
|
33
|
-
CheckGuaranteesArgs,
|
|
34
|
-
DeleteGuaranteeArgs,
|
|
35
|
-
GetCoverageArgs,
|
|
36
|
-
GetDocumentationArgs,
|
|
37
|
-
FindGuardsArgs,
|
|
38
|
-
GuardInfo,
|
|
39
|
-
GetFunctionDetailsArgs,
|
|
40
|
-
GraphNode,
|
|
41
|
-
DatalogBinding,
|
|
42
|
-
CallResult,
|
|
43
|
-
ReportIssueArgs,
|
|
44
|
-
ReadProjectStructureArgs,
|
|
45
|
-
WriteConfigArgs,
|
|
46
|
-
} from './types.js';
|
|
47
|
-
import { isGuaranteeType } from '@grafema/core';
|
|
48
|
-
|
|
49
|
-
// === QUERY HANDLERS ===
|
|
50
|
-
|
|
51
|
-
export async function handleQueryGraph(args: QueryGraphArgs): Promise<ToolResult> {
|
|
52
|
-
const db = await ensureAnalyzed();
|
|
53
|
-
const { query, limit: requestedLimit, offset: requestedOffset, format: _format, explain: _explain } = args;
|
|
54
|
-
|
|
55
|
-
const limit = normalizeLimit(requestedLimit);
|
|
56
|
-
const offset = Math.max(0, requestedOffset || 0);
|
|
57
|
-
|
|
58
|
-
try {
|
|
59
|
-
// Check if backend supports Datalog queries
|
|
60
|
-
if (!('checkGuarantee' in db)) {
|
|
61
|
-
return errorResult('Backend does not support Datalog queries');
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
const checkFn = (db as unknown as { checkGuarantee: (q: string) => Promise<Array<{ bindings: Array<{ name: string; value: string }> }>> }).checkGuarantee;
|
|
65
|
-
const results = await checkFn(query);
|
|
66
|
-
const total = results.length;
|
|
67
|
-
|
|
68
|
-
if (total === 0) {
|
|
69
|
-
const nodeCounts = await db.countNodesByType();
|
|
70
|
-
const totalNodes = Object.values(nodeCounts).reduce((a, b) => a + b, 0);
|
|
71
|
-
|
|
72
|
-
const typeMatch = query.match(/node\([^,]+,\s*"([^"]+)"\)/);
|
|
73
|
-
const queriedType = typeMatch ? typeMatch[1] : null;
|
|
74
|
-
|
|
75
|
-
let hint = '';
|
|
76
|
-
if (queriedType && !nodeCounts[queriedType]) {
|
|
77
|
-
const availableTypes = Object.keys(nodeCounts);
|
|
78
|
-
const similar = findSimilarTypes(queriedType, availableTypes);
|
|
79
|
-
if (similar.length > 0) {
|
|
80
|
-
hint = `\n💡 Did you mean: ${similar.join(', ')}?`;
|
|
81
|
-
} else {
|
|
82
|
-
hint = `\n💡 Available types: ${availableTypes.slice(0, 10).join(', ')}${availableTypes.length > 10 ? '...' : ''}`;
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
return textResult(
|
|
87
|
-
`Query returned no results.${hint}\n📊 Graph: ${totalNodes.toLocaleString()} nodes`
|
|
88
|
-
);
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
const paginatedResults = results.slice(offset, offset + limit);
|
|
92
|
-
const hasMore = offset + limit < total;
|
|
93
|
-
|
|
94
|
-
const enrichedResults: unknown[] = [];
|
|
95
|
-
for (const result of paginatedResults) {
|
|
96
|
-
const nodeId = result.bindings?.find((b: DatalogBinding) => b.name === 'X')?.value;
|
|
97
|
-
if (nodeId) {
|
|
98
|
-
const node = await db.getNode(nodeId);
|
|
99
|
-
if (node) {
|
|
100
|
-
enrichedResults.push({
|
|
101
|
-
...node,
|
|
102
|
-
id: nodeId,
|
|
103
|
-
file: node.file,
|
|
104
|
-
line: node.line,
|
|
105
|
-
});
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
const paginationInfo = formatPaginationInfo({
|
|
111
|
-
limit,
|
|
112
|
-
offset,
|
|
113
|
-
returned: enrichedResults.length,
|
|
114
|
-
total,
|
|
115
|
-
hasMore,
|
|
116
|
-
});
|
|
117
|
-
|
|
118
|
-
const responseText = `Found ${total} result(s):${paginationInfo}\n\n${JSON.stringify(
|
|
119
|
-
serializeBigInt(enrichedResults),
|
|
120
|
-
null,
|
|
121
|
-
2
|
|
122
|
-
)}`;
|
|
123
|
-
|
|
124
|
-
return textResult(guardResponseSize(responseText));
|
|
125
|
-
} catch (error) {
|
|
126
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
127
|
-
return errorResult(message);
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
export async function handleFindCalls(args: FindCallsArgs): Promise<ToolResult> {
|
|
132
|
-
const db = await ensureAnalyzed();
|
|
133
|
-
const { target: name, limit: requestedLimit, offset: requestedOffset, className } = args;
|
|
134
|
-
|
|
135
|
-
const limit = normalizeLimit(requestedLimit);
|
|
136
|
-
const offset = Math.max(0, requestedOffset || 0);
|
|
137
|
-
|
|
138
|
-
const calls: CallResult[] = [];
|
|
139
|
-
let skipped = 0;
|
|
140
|
-
let totalMatched = 0;
|
|
141
|
-
|
|
142
|
-
for await (const node of db.queryNodes({ type: 'CALL' })) {
|
|
143
|
-
if (node.name !== name && node['method'] !== name) continue;
|
|
144
|
-
if (className && node['object'] !== className) continue;
|
|
145
|
-
|
|
146
|
-
totalMatched++;
|
|
147
|
-
|
|
148
|
-
if (skipped < offset) {
|
|
149
|
-
skipped++;
|
|
150
|
-
continue;
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
if (calls.length >= limit) continue;
|
|
154
|
-
|
|
155
|
-
const callsEdges = await db.getOutgoingEdges(node.id, ['CALLS']);
|
|
156
|
-
const isResolved = callsEdges.length > 0;
|
|
157
|
-
|
|
158
|
-
let target = null;
|
|
159
|
-
if (isResolved) {
|
|
160
|
-
const targetNode = await db.getNode(callsEdges[0].dst);
|
|
161
|
-
target = targetNode
|
|
162
|
-
? {
|
|
163
|
-
type: targetNode.type,
|
|
164
|
-
name: targetNode.name ?? '',
|
|
165
|
-
file: targetNode.file,
|
|
166
|
-
line: targetNode.line,
|
|
167
|
-
}
|
|
168
|
-
: null;
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
calls.push({
|
|
172
|
-
id: node.id,
|
|
173
|
-
name: node.name,
|
|
174
|
-
object: node['object'] as string | undefined,
|
|
175
|
-
file: node.file,
|
|
176
|
-
line: node.line,
|
|
177
|
-
resolved: isResolved,
|
|
178
|
-
target,
|
|
179
|
-
});
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
if (totalMatched === 0) {
|
|
183
|
-
return textResult(`No calls found for "${className ? className + '.' : ''}${name}"`);
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
const resolved = calls.filter(c => c.resolved).length;
|
|
187
|
-
const unresolved = calls.length - resolved;
|
|
188
|
-
const hasMore = offset + calls.length < totalMatched;
|
|
189
|
-
|
|
190
|
-
const paginationInfo = formatPaginationInfo({
|
|
191
|
-
limit,
|
|
192
|
-
offset,
|
|
193
|
-
returned: calls.length,
|
|
194
|
-
total: totalMatched,
|
|
195
|
-
hasMore,
|
|
196
|
-
});
|
|
197
|
-
|
|
198
|
-
const responseText =
|
|
199
|
-
`Found ${totalMatched} call(s) to "${className ? className + '.' : ''}${name}":${paginationInfo}\n` +
|
|
200
|
-
`- Resolved: ${resolved}\n` +
|
|
201
|
-
`- Unresolved: ${unresolved}\n\n` +
|
|
202
|
-
JSON.stringify(serializeBigInt(calls), null, 2);
|
|
203
|
-
|
|
204
|
-
return textResult(guardResponseSize(responseText));
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
export async function handleFindNodes(args: FindNodesArgs): Promise<ToolResult> {
|
|
208
|
-
const db = await ensureAnalyzed();
|
|
209
|
-
const { type, name, file, limit: requestedLimit, offset: requestedOffset } = args;
|
|
210
|
-
|
|
211
|
-
const limit = normalizeLimit(requestedLimit);
|
|
212
|
-
const offset = Math.max(0, requestedOffset || 0);
|
|
213
|
-
|
|
214
|
-
const filter: Record<string, unknown> = {};
|
|
215
|
-
if (type) filter.type = type;
|
|
216
|
-
if (name) filter.name = name;
|
|
217
|
-
if (file) filter.file = file;
|
|
218
|
-
|
|
219
|
-
const nodes: GraphNode[] = [];
|
|
220
|
-
let skipped = 0;
|
|
221
|
-
let totalMatched = 0;
|
|
222
|
-
|
|
223
|
-
for await (const node of db.queryNodes(filter)) {
|
|
224
|
-
totalMatched++;
|
|
225
|
-
|
|
226
|
-
if (skipped < offset) {
|
|
227
|
-
skipped++;
|
|
228
|
-
continue;
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
if (nodes.length < limit) {
|
|
232
|
-
nodes.push(node);
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
if (totalMatched === 0) {
|
|
237
|
-
return textResult('No nodes found matching criteria');
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
const hasMore = offset + nodes.length < totalMatched;
|
|
241
|
-
const paginationInfo = formatPaginationInfo({
|
|
242
|
-
limit,
|
|
243
|
-
offset,
|
|
244
|
-
returned: nodes.length,
|
|
245
|
-
total: totalMatched,
|
|
246
|
-
hasMore,
|
|
247
|
-
});
|
|
248
|
-
|
|
249
|
-
return textResult(
|
|
250
|
-
`Found ${totalMatched} node(s):${paginationInfo}\n\n${JSON.stringify(
|
|
251
|
-
serializeBigInt(nodes),
|
|
252
|
-
null,
|
|
253
|
-
2
|
|
254
|
-
)}`
|
|
255
|
-
);
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
// === TRACE HANDLERS ===
|
|
259
|
-
|
|
260
|
-
export async function handleTraceAlias(args: TraceAliasArgs): Promise<ToolResult> {
|
|
261
|
-
const db = await ensureAnalyzed();
|
|
262
|
-
const { variableName, file } = args;
|
|
263
|
-
const _projectPath = getProjectPath();
|
|
264
|
-
|
|
265
|
-
let varNode: GraphNode | null = null;
|
|
266
|
-
|
|
267
|
-
for await (const node of db.queryNodes({ type: 'VARIABLE' })) {
|
|
268
|
-
if (node.name === variableName && node.file?.includes(file || '')) {
|
|
269
|
-
varNode = node;
|
|
270
|
-
break;
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
if (!varNode) {
|
|
275
|
-
for await (const node of db.queryNodes({ type: 'CONSTANT' })) {
|
|
276
|
-
if (node.name === variableName && node.file?.includes(file || '')) {
|
|
277
|
-
varNode = node;
|
|
278
|
-
break;
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
if (!varNode) {
|
|
284
|
-
return errorResult(`Variable "${variableName}" not found in ${file || 'project'}`);
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
const chain: unknown[] = [];
|
|
288
|
-
const visited = new Set<string>();
|
|
289
|
-
let current: GraphNode | null = varNode;
|
|
290
|
-
const MAX_DEPTH = 20;
|
|
291
|
-
|
|
292
|
-
while (current && chain.length < MAX_DEPTH) {
|
|
293
|
-
if (visited.has(current.id)) {
|
|
294
|
-
chain.push({ type: 'CYCLE_DETECTED', id: current.id });
|
|
295
|
-
break;
|
|
296
|
-
}
|
|
297
|
-
visited.add(current.id);
|
|
298
|
-
|
|
299
|
-
chain.push({
|
|
300
|
-
type: current.type,
|
|
301
|
-
name: current.name,
|
|
302
|
-
file: current.file,
|
|
303
|
-
line: current.line,
|
|
304
|
-
});
|
|
305
|
-
|
|
306
|
-
const edges = await db.getOutgoingEdges(current.id, ['ASSIGNED_FROM']);
|
|
307
|
-
if (edges.length === 0) break;
|
|
308
|
-
|
|
309
|
-
current = await db.getNode(edges[0].dst);
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
return textResult(
|
|
313
|
-
`Alias chain for "${variableName}" (${chain.length} steps):\n\n${JSON.stringify(
|
|
314
|
-
serializeBigInt(chain),
|
|
315
|
-
null,
|
|
316
|
-
2
|
|
317
|
-
)}`
|
|
318
|
-
);
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
export async function handleTraceDataFlow(args: TraceDataFlowArgs): Promise<ToolResult> {
|
|
322
|
-
const db = await ensureAnalyzed();
|
|
323
|
-
const { source, direction = 'forward', max_depth = 10 } = args;
|
|
324
|
-
|
|
325
|
-
// Find source node
|
|
326
|
-
let sourceNode: GraphNode | null = null;
|
|
327
|
-
|
|
328
|
-
// Try to find by ID first
|
|
329
|
-
sourceNode = await db.getNode(source);
|
|
330
|
-
|
|
331
|
-
// If not found, search by name
|
|
332
|
-
if (!sourceNode) {
|
|
333
|
-
for await (const node of db.queryNodes({ name: source })) {
|
|
334
|
-
sourceNode = node;
|
|
335
|
-
break;
|
|
336
|
-
}
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
if (!sourceNode) {
|
|
340
|
-
return errorResult(`Source "${source}" not found`);
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
const visited = new Set<string>();
|
|
344
|
-
const paths: unknown[] = [];
|
|
345
|
-
|
|
346
|
-
async function trace(nodeId: string, depth: number, path: string[]): Promise<void> {
|
|
347
|
-
if (depth > max_depth || visited.has(nodeId)) return;
|
|
348
|
-
visited.add(nodeId);
|
|
349
|
-
|
|
350
|
-
const newPath = [...path, nodeId];
|
|
351
|
-
|
|
352
|
-
if (direction === 'forward' || direction === 'both') {
|
|
353
|
-
const outEdges = await db.getOutgoingEdges(nodeId, [
|
|
354
|
-
'ASSIGNED_FROM',
|
|
355
|
-
'DERIVES_FROM',
|
|
356
|
-
'PASSES_ARGUMENT',
|
|
357
|
-
]);
|
|
358
|
-
for (const edge of outEdges) {
|
|
359
|
-
await trace(edge.dst, depth + 1, newPath);
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
if (direction === 'backward' || direction === 'both') {
|
|
364
|
-
const inEdges = await db.getIncomingEdges(nodeId, [
|
|
365
|
-
'ASSIGNED_FROM',
|
|
366
|
-
'DERIVES_FROM',
|
|
367
|
-
'PASSES_ARGUMENT',
|
|
368
|
-
]);
|
|
369
|
-
for (const edge of inEdges) {
|
|
370
|
-
await trace(edge.src, depth + 1, newPath);
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
if (depth > 0) {
|
|
375
|
-
paths.push(newPath);
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
await trace(sourceNode.id, 0, []);
|
|
380
|
-
|
|
381
|
-
return textResult(
|
|
382
|
-
`Data flow from "${source}" (${paths.length} paths):\n\n${JSON.stringify(paths, null, 2)}`
|
|
383
|
-
);
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
export async function handleCheckInvariant(args: CheckInvariantArgs): Promise<ToolResult> {
|
|
387
|
-
const db = await ensureAnalyzed();
|
|
388
|
-
const { rule, name: description } = args;
|
|
389
|
-
|
|
390
|
-
if (!('checkGuarantee' in db)) {
|
|
391
|
-
return errorResult('Backend does not support Datalog queries');
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
try {
|
|
395
|
-
const checkFn = (db as unknown as { checkGuarantee: (q: string) => Promise<Array<{ bindings: Array<{ name: string; value: string }> }>> }).checkGuarantee;
|
|
396
|
-
const violations = await checkFn(rule);
|
|
397
|
-
const total = violations.length;
|
|
398
|
-
|
|
399
|
-
if (total === 0) {
|
|
400
|
-
return textResult(`✅ Invariant holds: ${description || 'No violations found'}`);
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
const enrichedViolations: unknown[] = [];
|
|
404
|
-
for (const v of violations.slice(0, 20)) {
|
|
405
|
-
const nodeId = v.bindings?.find((b: any) => b.name === 'X')?.value;
|
|
406
|
-
if (nodeId) {
|
|
407
|
-
const node = await db.getNode(nodeId);
|
|
408
|
-
if (node) {
|
|
409
|
-
enrichedViolations.push({
|
|
410
|
-
id: nodeId,
|
|
411
|
-
type: node.type,
|
|
412
|
-
name: node.name,
|
|
413
|
-
file: node.file,
|
|
414
|
-
line: node.line,
|
|
415
|
-
});
|
|
416
|
-
}
|
|
417
|
-
}
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
return textResult(
|
|
421
|
-
`❌ ${total} violation(s) found:\n\n${JSON.stringify(
|
|
422
|
-
serializeBigInt(enrichedViolations),
|
|
423
|
-
null,
|
|
424
|
-
2
|
|
425
|
-
)}${total > 20 ? `\n\n... and ${total - 20} more` : ''}`
|
|
426
|
-
);
|
|
427
|
-
} catch (error) {
|
|
428
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
429
|
-
return errorResult(message);
|
|
430
|
-
}
|
|
431
|
-
}
|
|
432
|
-
|
|
433
|
-
// === ANALYSIS HANDLERS ===
|
|
434
|
-
|
|
435
|
-
export async function handleAnalyzeProject(args: AnalyzeProjectArgs): Promise<ToolResult> {
|
|
436
|
-
const { service, force } = args;
|
|
437
|
-
|
|
438
|
-
// Early check: return error for force=true if analysis is already running
|
|
439
|
-
// This provides immediate feedback instead of waiting or causing corruption
|
|
440
|
-
if (force && isAnalysisRunning()) {
|
|
441
|
-
return errorResult(
|
|
442
|
-
'Cannot force re-analysis: analysis is already in progress. ' +
|
|
443
|
-
'Use get_analysis_status to check current status, or wait for completion.'
|
|
444
|
-
);
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
// Note: setIsAnalyzed(false) is now handled inside ensureAnalyzed() within the lock
|
|
448
|
-
// to prevent race conditions where multiple calls could both clear the database
|
|
449
|
-
|
|
450
|
-
try {
|
|
451
|
-
await ensureAnalyzed(service || null, force || false);
|
|
452
|
-
const status = getAnalysisStatus();
|
|
453
|
-
|
|
454
|
-
return textResult(
|
|
455
|
-
`Analysis complete!\n` +
|
|
456
|
-
`- Services discovered: ${status.servicesDiscovered}\n` +
|
|
457
|
-
`- Services analyzed: ${status.servicesAnalyzed}\n` +
|
|
458
|
-
`- Total time: ${status.timings.total || 'N/A'}s`
|
|
459
|
-
);
|
|
460
|
-
} catch (error) {
|
|
461
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
462
|
-
return errorResult(message);
|
|
463
|
-
}
|
|
464
|
-
}
|
|
465
|
-
|
|
466
|
-
export async function handleGetAnalysisStatus(): Promise<ToolResult> {
|
|
467
|
-
const status = getAnalysisStatus();
|
|
468
|
-
|
|
469
|
-
return textResult(
|
|
470
|
-
`Analysis Status:\n` +
|
|
471
|
-
`- Running: ${status.running}\n` +
|
|
472
|
-
`- Phase: ${status.phase || 'N/A'}\n` +
|
|
473
|
-
`- Message: ${status.message || 'N/A'}\n` +
|
|
474
|
-
`- Services discovered: ${status.servicesDiscovered}\n` +
|
|
475
|
-
`- Services analyzed: ${status.servicesAnalyzed}\n` +
|
|
476
|
-
(status.error ? `- Error: ${status.error}\n` : '')
|
|
477
|
-
);
|
|
478
|
-
}
|
|
479
|
-
|
|
480
|
-
export async function handleGetStats(): Promise<ToolResult> {
|
|
481
|
-
const db = await getOrCreateBackend();
|
|
482
|
-
|
|
483
|
-
const nodeCount = await db.nodeCount();
|
|
484
|
-
const edgeCount = await db.edgeCount();
|
|
485
|
-
const nodesByType = await db.countNodesByType();
|
|
486
|
-
const edgesByType = await db.countEdgesByType();
|
|
487
|
-
|
|
488
|
-
return textResult(
|
|
489
|
-
`Graph Statistics:\n\n` +
|
|
490
|
-
`Total nodes: ${nodeCount.toLocaleString()}\n` +
|
|
491
|
-
`Total edges: ${edgeCount.toLocaleString()}\n\n` +
|
|
492
|
-
`Nodes by type:\n${JSON.stringify(nodesByType, null, 2)}\n\n` +
|
|
493
|
-
`Edges by type:\n${JSON.stringify(edgesByType, null, 2)}`
|
|
494
|
-
);
|
|
495
|
-
}
|
|
496
|
-
|
|
497
|
-
export async function handleGetSchema(args: GetSchemaArgs): Promise<ToolResult> {
|
|
498
|
-
const db = await getOrCreateBackend();
|
|
499
|
-
const { type = 'all' } = args;
|
|
500
|
-
|
|
501
|
-
const nodesByType = await db.countNodesByType();
|
|
502
|
-
const edgesByType = await db.countEdgesByType();
|
|
503
|
-
|
|
504
|
-
let output = '';
|
|
505
|
-
|
|
506
|
-
if (type === 'nodes' || type === 'all') {
|
|
507
|
-
output += `Node Types (${Object.keys(nodesByType).length}):\n`;
|
|
508
|
-
for (const [t, count] of Object.entries(nodesByType)) {
|
|
509
|
-
output += ` - ${t}: ${count}\n`;
|
|
510
|
-
}
|
|
511
|
-
}
|
|
512
|
-
|
|
513
|
-
if (type === 'edges' || type === 'all') {
|
|
514
|
-
output += `\nEdge Types (${Object.keys(edgesByType).length}):\n`;
|
|
515
|
-
for (const [t, count] of Object.entries(edgesByType)) {
|
|
516
|
-
output += ` - ${t}: ${count}\n`;
|
|
517
|
-
}
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
return textResult(output);
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
// === GUARANTEE HANDLERS ===
|
|
524
|
-
|
|
525
|
-
/**
|
|
526
|
-
* Create a new guarantee (Datalog-based or contract-based)
|
|
527
|
-
*/
|
|
528
|
-
export async function handleCreateGuarantee(args: CreateGuaranteeArgs): Promise<ToolResult> {
|
|
529
|
-
await getOrCreateBackend(); // Ensure managers are initialized
|
|
530
|
-
|
|
531
|
-
const { name, rule, type, priority, status, owner, schema, condition, description, governs, severity } = args;
|
|
532
|
-
|
|
533
|
-
try {
|
|
534
|
-
// Determine if this is a contract-based guarantee
|
|
535
|
-
if (type && isGuaranteeType(type)) {
|
|
536
|
-
// Contract-based guarantee
|
|
537
|
-
const api = getGuaranteeAPI();
|
|
538
|
-
if (!api) {
|
|
539
|
-
return errorResult('GuaranteeAPI not initialized');
|
|
540
|
-
}
|
|
541
|
-
|
|
542
|
-
const guarantee = await api.createGuarantee({
|
|
543
|
-
type,
|
|
544
|
-
name,
|
|
545
|
-
priority,
|
|
546
|
-
status,
|
|
547
|
-
owner,
|
|
548
|
-
schema,
|
|
549
|
-
condition,
|
|
550
|
-
description,
|
|
551
|
-
governs,
|
|
552
|
-
});
|
|
553
|
-
|
|
554
|
-
return textResult(
|
|
555
|
-
`✅ Created contract-based guarantee: ${guarantee.id}\n` +
|
|
556
|
-
`Type: ${guarantee.type}\n` +
|
|
557
|
-
`Priority: ${guarantee.priority}\n` +
|
|
558
|
-
`Status: ${guarantee.status}` +
|
|
559
|
-
(guarantee.description ? `\nDescription: ${guarantee.description}` : '')
|
|
560
|
-
);
|
|
561
|
-
} else {
|
|
562
|
-
// Datalog-based guarantee
|
|
563
|
-
if (!rule) {
|
|
564
|
-
return errorResult('Datalog-based guarantee requires "rule" field');
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
const manager = getGuaranteeManager();
|
|
568
|
-
if (!manager) {
|
|
569
|
-
return errorResult('GuaranteeManager not initialized');
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
const guarantee = await manager.create({
|
|
573
|
-
id: name,
|
|
574
|
-
name,
|
|
575
|
-
rule,
|
|
576
|
-
severity: severity || 'warning',
|
|
577
|
-
governs: governs || ['**/*.js'],
|
|
578
|
-
});
|
|
579
|
-
|
|
580
|
-
return textResult(
|
|
581
|
-
`✅ Created Datalog-based guarantee: ${guarantee.id}\n` +
|
|
582
|
-
`Rule: ${guarantee.rule}\n` +
|
|
583
|
-
`Severity: ${guarantee.severity}`
|
|
584
|
-
);
|
|
585
|
-
}
|
|
586
|
-
} catch (error) {
|
|
587
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
588
|
-
return errorResult(`Failed to create guarantee: ${message}`);
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
|
|
592
|
-
/**
|
|
593
|
-
* List all guarantees (both Datalog-based and contract-based)
|
|
594
|
-
*/
|
|
595
|
-
export async function handleListGuarantees(): Promise<ToolResult> {
|
|
596
|
-
await getOrCreateBackend(); // Ensure managers are initialized
|
|
597
|
-
|
|
598
|
-
const results: string[] = [];
|
|
599
|
-
|
|
600
|
-
try {
|
|
601
|
-
// List Datalog-based guarantees
|
|
602
|
-
const manager = getGuaranteeManager();
|
|
603
|
-
if (manager) {
|
|
604
|
-
const datalogGuarantees = await manager.list();
|
|
605
|
-
if (datalogGuarantees.length > 0) {
|
|
606
|
-
results.push('## Datalog-based Guarantees\n');
|
|
607
|
-
for (const g of datalogGuarantees) {
|
|
608
|
-
results.push(`- **${g.id}** (${g.severity})`);
|
|
609
|
-
results.push(` Rule: ${g.rule.substring(0, 80)}${g.rule.length > 80 ? '...' : ''}`);
|
|
610
|
-
}
|
|
611
|
-
}
|
|
612
|
-
}
|
|
613
|
-
|
|
614
|
-
// List contract-based guarantees
|
|
615
|
-
const api = getGuaranteeAPI();
|
|
616
|
-
if (api) {
|
|
617
|
-
const contractGuarantees = await api.findGuarantees();
|
|
618
|
-
if (contractGuarantees.length > 0) {
|
|
619
|
-
if (results.length > 0) results.push('\n');
|
|
620
|
-
results.push('## Contract-based Guarantees\n');
|
|
621
|
-
for (const g of contractGuarantees) {
|
|
622
|
-
results.push(`- **${g.id}** [${g.priority}] (${g.status})`);
|
|
623
|
-
if (g.description) results.push(` ${g.description}`);
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
}
|
|
627
|
-
|
|
628
|
-
if (results.length === 0) {
|
|
629
|
-
return textResult('No guarantees defined yet.');
|
|
630
|
-
}
|
|
631
|
-
|
|
632
|
-
return textResult(results.join('\n'));
|
|
633
|
-
} catch (error) {
|
|
634
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
635
|
-
return errorResult(`Failed to list guarantees: ${message}`);
|
|
636
|
-
}
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
/**
|
|
640
|
-
* Check guarantees (both Datalog-based and contract-based)
|
|
641
|
-
*/
|
|
642
|
-
export async function handleCheckGuarantees(args: CheckGuaranteesArgs): Promise<ToolResult> {
|
|
643
|
-
await getOrCreateBackend(); // Ensure managers are initialized
|
|
644
|
-
|
|
645
|
-
const { names } = args;
|
|
646
|
-
const results: string[] = [];
|
|
647
|
-
let totalPassed = 0;
|
|
648
|
-
let totalFailed = 0;
|
|
649
|
-
|
|
650
|
-
try {
|
|
651
|
-
const manager = getGuaranteeManager();
|
|
652
|
-
const api = getGuaranteeAPI();
|
|
653
|
-
|
|
654
|
-
if (names && names.length > 0) {
|
|
655
|
-
// Check specific guarantees
|
|
656
|
-
for (const name of names) {
|
|
657
|
-
// Try Datalog-based first
|
|
658
|
-
if (manager) {
|
|
659
|
-
try {
|
|
660
|
-
const result = await manager.check(name);
|
|
661
|
-
if (result.passed) {
|
|
662
|
-
totalPassed++;
|
|
663
|
-
results.push(`✅ ${result.guaranteeId}: PASSED`);
|
|
664
|
-
} else {
|
|
665
|
-
totalFailed++;
|
|
666
|
-
results.push(`❌ ${result.guaranteeId}: FAILED (${result.violationCount} violations)`);
|
|
667
|
-
for (const v of result.violations.slice(0, 5)) {
|
|
668
|
-
results.push(` - ${v.file}:${v.line} (${v.type})`);
|
|
669
|
-
}
|
|
670
|
-
if (result.violationCount > 5) {
|
|
671
|
-
results.push(` ... and ${result.violationCount - 5} more`);
|
|
672
|
-
}
|
|
673
|
-
}
|
|
674
|
-
continue;
|
|
675
|
-
} catch {
|
|
676
|
-
// Not a Datalog guarantee, try contract-based
|
|
677
|
-
}
|
|
678
|
-
}
|
|
679
|
-
|
|
680
|
-
// Try contract-based
|
|
681
|
-
if (api) {
|
|
682
|
-
try {
|
|
683
|
-
const result = await api.checkGuarantee(name);
|
|
684
|
-
if (result.passed) {
|
|
685
|
-
totalPassed++;
|
|
686
|
-
results.push(`✅ ${result.id}: PASSED`);
|
|
687
|
-
} else {
|
|
688
|
-
totalFailed++;
|
|
689
|
-
results.push(`❌ ${result.id}: FAILED`);
|
|
690
|
-
for (const err of result.errors.slice(0, 5)) {
|
|
691
|
-
results.push(` - ${err}`);
|
|
692
|
-
}
|
|
693
|
-
}
|
|
694
|
-
} catch {
|
|
695
|
-
results.push(`⚠️ ${name}: Not found`);
|
|
696
|
-
}
|
|
697
|
-
}
|
|
698
|
-
}
|
|
699
|
-
} else {
|
|
700
|
-
// Check all guarantees
|
|
701
|
-
if (manager) {
|
|
702
|
-
const datalogResult = await manager.checkAll();
|
|
703
|
-
totalPassed += datalogResult.passed;
|
|
704
|
-
totalFailed += datalogResult.failed;
|
|
705
|
-
|
|
706
|
-
if (datalogResult.total > 0) {
|
|
707
|
-
results.push('## Datalog Guarantees\n');
|
|
708
|
-
for (const r of datalogResult.results) {
|
|
709
|
-
if (r.passed) {
|
|
710
|
-
results.push(`✅ ${r.guaranteeId}: PASSED`);
|
|
711
|
-
} else {
|
|
712
|
-
results.push(`❌ ${r.guaranteeId}: FAILED (${r.violationCount} violations)`);
|
|
713
|
-
}
|
|
714
|
-
}
|
|
715
|
-
}
|
|
716
|
-
}
|
|
717
|
-
|
|
718
|
-
if (api) {
|
|
719
|
-
const contractResult = await api.checkAllGuarantees();
|
|
720
|
-
totalPassed += contractResult.passed;
|
|
721
|
-
totalFailed += contractResult.failed;
|
|
722
|
-
|
|
723
|
-
if (contractResult.total > 0) {
|
|
724
|
-
if (results.length > 0) results.push('\n');
|
|
725
|
-
results.push('## Contract Guarantees\n');
|
|
726
|
-
for (const r of contractResult.results) {
|
|
727
|
-
if (r.passed) {
|
|
728
|
-
results.push(`✅ ${r.id}: PASSED`);
|
|
729
|
-
} else {
|
|
730
|
-
results.push(`❌ ${r.id}: FAILED`);
|
|
731
|
-
}
|
|
732
|
-
}
|
|
733
|
-
}
|
|
734
|
-
}
|
|
735
|
-
}
|
|
736
|
-
|
|
737
|
-
if (results.length === 0) {
|
|
738
|
-
return textResult('No guarantees to check.');
|
|
739
|
-
}
|
|
740
|
-
|
|
741
|
-
const summary = `\n---\nTotal: ${totalPassed + totalFailed} | ✅ Passed: ${totalPassed} | ❌ Failed: ${totalFailed}`;
|
|
742
|
-
return textResult(results.join('\n') + summary);
|
|
743
|
-
} catch (error) {
|
|
744
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
745
|
-
return errorResult(`Failed to check guarantees: ${message}`);
|
|
746
|
-
}
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
/**
|
|
750
|
-
* Delete a guarantee
|
|
751
|
-
*/
|
|
752
|
-
export async function handleDeleteGuarantee(args: DeleteGuaranteeArgs): Promise<ToolResult> {
|
|
753
|
-
await getOrCreateBackend(); // Ensure managers are initialized
|
|
754
|
-
|
|
755
|
-
const { name } = args;
|
|
756
|
-
|
|
757
|
-
try {
|
|
758
|
-
// Try Datalog-based first
|
|
759
|
-
const manager = getGuaranteeManager();
|
|
760
|
-
if (manager) {
|
|
761
|
-
try {
|
|
762
|
-
await manager.delete(name);
|
|
763
|
-
return textResult(`✅ Deleted Datalog guarantee: ${name}`);
|
|
764
|
-
} catch {
|
|
765
|
-
// Not found in Datalog, try contract-based
|
|
766
|
-
}
|
|
767
|
-
}
|
|
768
|
-
|
|
769
|
-
// Try contract-based
|
|
770
|
-
const api = getGuaranteeAPI();
|
|
771
|
-
if (api) {
|
|
772
|
-
const deleted = await api.deleteGuarantee(name);
|
|
773
|
-
if (deleted) {
|
|
774
|
-
return textResult(`✅ Deleted contract guarantee: ${name}`);
|
|
775
|
-
}
|
|
776
|
-
}
|
|
777
|
-
|
|
778
|
-
return errorResult(`Guarantee not found: ${name}`);
|
|
779
|
-
} catch (error) {
|
|
780
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
781
|
-
return errorResult(`Failed to delete guarantee: ${message}`);
|
|
782
|
-
}
|
|
783
|
-
}
|
|
784
|
-
|
|
785
|
-
// === COVERAGE & DOCS ===
|
|
786
|
-
|
|
787
|
-
export async function handleGetCoverage(args: GetCoverageArgs): Promise<ToolResult> {
|
|
788
|
-
const db = await getOrCreateBackend();
|
|
789
|
-
const projectPath = getProjectPath();
|
|
790
|
-
const { path: targetPath = projectPath } = args;
|
|
791
|
-
|
|
792
|
-
try {
|
|
793
|
-
const analyzer = new CoverageAnalyzer(db, targetPath);
|
|
794
|
-
const result = await analyzer.analyze();
|
|
795
|
-
|
|
796
|
-
// Format output for AI agents
|
|
797
|
-
let output = `Analysis Coverage for ${targetPath}\n`;
|
|
798
|
-
output += `==============================\n\n`;
|
|
799
|
-
|
|
800
|
-
output += `File breakdown:\n`;
|
|
801
|
-
output += ` Total files: ${result.total}\n`;
|
|
802
|
-
output += ` Analyzed: ${result.analyzed.count} (${result.percentages.analyzed}%) - in graph\n`;
|
|
803
|
-
output += ` Unsupported: ${result.unsupported.count} (${result.percentages.unsupported}%) - no indexer available\n`;
|
|
804
|
-
output += ` Unreachable: ${result.unreachable.count} (${result.percentages.unreachable}%) - not imported from entrypoints\n`;
|
|
805
|
-
|
|
806
|
-
if (result.unsupported.count > 0) {
|
|
807
|
-
output += `\nUnsupported files by extension:\n`;
|
|
808
|
-
for (const [ext, files] of Object.entries(result.unsupported.byExtension)) {
|
|
809
|
-
output += ` ${ext}: ${files.length} files\n`;
|
|
810
|
-
}
|
|
811
|
-
}
|
|
812
|
-
|
|
813
|
-
if (result.unreachable.count > 0) {
|
|
814
|
-
output += `\nUnreachable source files:\n`;
|
|
815
|
-
for (const [ext, files] of Object.entries(result.unreachable.byExtension)) {
|
|
816
|
-
output += ` ${ext}: ${files.length} files\n`;
|
|
817
|
-
}
|
|
818
|
-
}
|
|
819
|
-
|
|
820
|
-
return textResult(output);
|
|
821
|
-
} catch (error) {
|
|
822
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
823
|
-
return errorResult(`Failed to calculate coverage: ${message}`);
|
|
824
|
-
}
|
|
825
|
-
}
|
|
826
|
-
|
|
827
|
-
export async function handleGetDocumentation(args: GetDocumentationArgs): Promise<ToolResult> {
|
|
828
|
-
const { topic = 'overview' } = args;
|
|
829
|
-
|
|
830
|
-
const docs: Record<string, string> = {
|
|
831
|
-
onboarding: getOnboardingInstruction(),
|
|
832
|
-
overview: `
|
|
833
|
-
# Grafema Code Analysis
|
|
834
|
-
|
|
835
|
-
Grafema is a static code analyzer that builds a graph of your codebase.
|
|
836
|
-
|
|
837
|
-
## Key Tools
|
|
838
|
-
- query_graph: Execute Datalog queries
|
|
839
|
-
- find_calls: Find function/method calls
|
|
840
|
-
- trace_alias: Trace variable aliases
|
|
841
|
-
- check_invariant: Verify code invariants
|
|
842
|
-
|
|
843
|
-
## Quick Start
|
|
844
|
-
1. Use get_stats to see graph size
|
|
845
|
-
2. Use find_nodes to explore the codebase
|
|
846
|
-
3. Use query_graph for complex queries
|
|
847
|
-
`,
|
|
848
|
-
queries: `
|
|
849
|
-
# Datalog Queries
|
|
850
|
-
|
|
851
|
-
## Syntax
|
|
852
|
-
violation(X) :- node(X, "TYPE"), attr(X, "name", "value").
|
|
853
|
-
|
|
854
|
-
## Available Predicates
|
|
855
|
-
- node(Id, Type) - match nodes
|
|
856
|
-
- edge(Src, Dst, Type) - match edges
|
|
857
|
-
- attr(Id, Name, Value) - match attributes
|
|
858
|
-
- \\+ - negation (not)
|
|
859
|
-
|
|
860
|
-
## Examples
|
|
861
|
-
Find all functions:
|
|
862
|
-
violation(X) :- node(X, "FUNCTION").
|
|
863
|
-
|
|
864
|
-
Find unresolved calls:
|
|
865
|
-
violation(X) :- node(X, "CALL"), \\+ edge(X, _, "CALLS").
|
|
866
|
-
`,
|
|
867
|
-
types: `
|
|
868
|
-
# Node & Edge Types
|
|
869
|
-
|
|
870
|
-
## Core Node Types
|
|
871
|
-
- MODULE, FUNCTION, CLASS, METHOD, VARIABLE
|
|
872
|
-
- CALL, PROPERTY_ACCESS, IMPORT, EXPORT, PARAMETER
|
|
873
|
-
|
|
874
|
-
## HTTP/Network
|
|
875
|
-
- http:route, http:request, db:query
|
|
876
|
-
|
|
877
|
-
## Edge Types
|
|
878
|
-
- CONTAINS, CALLS, DEPENDS_ON
|
|
879
|
-
- ASSIGNED_FROM, INSTANCE_OF, PASSES_ARGUMENT
|
|
880
|
-
`,
|
|
881
|
-
guarantees: `
|
|
882
|
-
# Code Guarantees
|
|
883
|
-
|
|
884
|
-
Guarantees are persistent code invariants.
|
|
885
|
-
|
|
886
|
-
## Create
|
|
887
|
-
Use create_guarantee with a name and Datalog rule.
|
|
888
|
-
|
|
889
|
-
## Check
|
|
890
|
-
Use check_guarantees to verify all guarantees.
|
|
891
|
-
|
|
892
|
-
## Example
|
|
893
|
-
Name: no-eval
|
|
894
|
-
Rule: violation(X) :- node(X, "CALL"), attr(X, "name", "eval").
|
|
895
|
-
`,
|
|
896
|
-
};
|
|
897
|
-
|
|
898
|
-
const content = docs[topic] || docs.overview;
|
|
899
|
-
return textResult(content.trim());
|
|
900
|
-
}
|
|
901
|
-
|
|
902
|
-
// === FIND GUARDS (REG-274) ===
|
|
903
|
-
|
|
904
|
-
/**
|
|
905
|
-
* Find conditional guards protecting a node.
|
|
906
|
-
*
|
|
907
|
-
* Walks up the containment tree via CONTAINS edges, collecting
|
|
908
|
-
* SCOPE nodes that have conditional=true (if_statement, else_statement, etc.).
|
|
909
|
-
*
|
|
910
|
-
* Returns guards in inner-to-outer order.
|
|
911
|
-
*/
|
|
912
|
-
export async function handleFindGuards(args: FindGuardsArgs): Promise<ToolResult> {
|
|
913
|
-
const db = await getOrCreateBackend();
|
|
914
|
-
const { nodeId } = args;
|
|
915
|
-
|
|
916
|
-
// Verify target node exists
|
|
917
|
-
const targetNode = await db.getNode(nodeId);
|
|
918
|
-
if (!targetNode) {
|
|
919
|
-
return errorResult(`Node not found: ${nodeId}`);
|
|
920
|
-
}
|
|
921
|
-
|
|
922
|
-
const guards: GuardInfo[] = [];
|
|
923
|
-
const visited = new Set<string>();
|
|
924
|
-
let currentId = nodeId;
|
|
925
|
-
|
|
926
|
-
// Walk up the containment tree
|
|
927
|
-
while (true) {
|
|
928
|
-
if (visited.has(currentId)) break;
|
|
929
|
-
visited.add(currentId);
|
|
930
|
-
|
|
931
|
-
// Get parent via incoming CONTAINS edge
|
|
932
|
-
const incomingEdges = await db.getIncomingEdges(currentId, ['CONTAINS']);
|
|
933
|
-
if (incomingEdges.length === 0) break;
|
|
934
|
-
|
|
935
|
-
const parentId = incomingEdges[0].src;
|
|
936
|
-
const parentNode = await db.getNode(parentId);
|
|
937
|
-
|
|
938
|
-
if (!parentNode) break;
|
|
939
|
-
|
|
940
|
-
// Check if this is a conditional scope
|
|
941
|
-
if (parentNode.conditional) {
|
|
942
|
-
// Parse constraints if stored as string
|
|
943
|
-
let constraints = parentNode.constraints;
|
|
944
|
-
if (typeof constraints === 'string') {
|
|
945
|
-
try {
|
|
946
|
-
constraints = JSON.parse(constraints);
|
|
947
|
-
} catch {
|
|
948
|
-
// Keep as string if not valid JSON
|
|
949
|
-
}
|
|
950
|
-
}
|
|
951
|
-
|
|
952
|
-
guards.push({
|
|
953
|
-
scopeId: parentNode.id,
|
|
954
|
-
scopeType: (parentNode.scopeType as string) || 'unknown',
|
|
955
|
-
condition: parentNode.condition as string | undefined,
|
|
956
|
-
constraints: constraints as unknown[] | undefined,
|
|
957
|
-
file: parentNode.file || '',
|
|
958
|
-
line: (parentNode.line as number) || 0,
|
|
959
|
-
});
|
|
960
|
-
}
|
|
961
|
-
|
|
962
|
-
currentId = parentId;
|
|
963
|
-
}
|
|
964
|
-
|
|
965
|
-
if (guards.length === 0) {
|
|
966
|
-
return textResult(
|
|
967
|
-
`No guards found for node: ${nodeId}\n` +
|
|
968
|
-
`The node is not protected by any conditional scope (if/else/switch/etc.).`
|
|
969
|
-
);
|
|
970
|
-
}
|
|
971
|
-
|
|
972
|
-
const summary = guards.map((g, i) => {
|
|
973
|
-
const indent = ' '.repeat(i);
|
|
974
|
-
return `${indent}${i + 1}. ${g.scopeType} at ${g.file}:${g.line}` +
|
|
975
|
-
(g.condition ? `\n${indent} condition: ${g.condition}` : '');
|
|
976
|
-
}).join('\n');
|
|
977
|
-
|
|
978
|
-
return textResult(
|
|
979
|
-
`Found ${guards.length} guard(s) for node: ${nodeId}\n` +
|
|
980
|
-
`(inner to outer order)\n\n` +
|
|
981
|
-
summary +
|
|
982
|
-
`\n\n` +
|
|
983
|
-
JSON.stringify(serializeBigInt(guards), null, 2)
|
|
984
|
-
);
|
|
985
|
-
}
|
|
986
|
-
|
|
987
|
-
// === GET FUNCTION DETAILS (REG-254) ===
|
|
988
|
-
|
|
989
|
-
/**
|
|
990
|
-
* Get comprehensive function details including calls made and callers.
|
|
991
|
-
*
|
|
992
|
-
* Graph structure:
|
|
993
|
-
* ```
|
|
994
|
-
* FUNCTION -[HAS_SCOPE]-> SCOPE -[CONTAINS]-> CALL/METHOD_CALL
|
|
995
|
-
* SCOPE -[CONTAINS]-> SCOPE (nested blocks)
|
|
996
|
-
* CALL -[CALLS]-> FUNCTION (target)
|
|
997
|
-
* ```
|
|
998
|
-
*
|
|
999
|
-
* This is the core tool for understanding function behavior.
|
|
1000
|
-
* Use transitive=true to follow call chains (A -> B -> C).
|
|
1001
|
-
*/
|
|
1002
|
-
export async function handleGetFunctionDetails(
|
|
1003
|
-
args: GetFunctionDetailsArgs
|
|
1004
|
-
): Promise<ToolResult> {
|
|
1005
|
-
const db = await ensureAnalyzed();
|
|
1006
|
-
const { name, file, transitive = false } = args;
|
|
1007
|
-
|
|
1008
|
-
// Step 1: Find the function
|
|
1009
|
-
const candidates: GraphNode[] = [];
|
|
1010
|
-
for await (const node of db.queryNodes({ type: 'FUNCTION' })) {
|
|
1011
|
-
if (node.name !== name) continue;
|
|
1012
|
-
if (file && !node.file?.includes(file)) continue;
|
|
1013
|
-
candidates.push(node);
|
|
1014
|
-
}
|
|
1015
|
-
|
|
1016
|
-
if (candidates.length === 0) {
|
|
1017
|
-
return errorResult(
|
|
1018
|
-
`Function "${name}" not found.` +
|
|
1019
|
-
(file ? ` (searched in files matching "${file}")` : '')
|
|
1020
|
-
);
|
|
1021
|
-
}
|
|
1022
|
-
|
|
1023
|
-
if (candidates.length > 1 && !file) {
|
|
1024
|
-
const locations = candidates.map(f => `${f.file}:${f.line}`).join(', ');
|
|
1025
|
-
return errorResult(
|
|
1026
|
-
`Multiple functions named "${name}" found: ${locations}. ` +
|
|
1027
|
-
`Use the "file" parameter to disambiguate.`
|
|
1028
|
-
);
|
|
1029
|
-
}
|
|
1030
|
-
|
|
1031
|
-
const targetFunction = candidates[0];
|
|
1032
|
-
|
|
1033
|
-
// Step 2: Find calls using shared utility
|
|
1034
|
-
const calls = await findCallsInFunction(db, targetFunction.id, {
|
|
1035
|
-
transitive,
|
|
1036
|
-
transitiveDepth: 5,
|
|
1037
|
-
});
|
|
1038
|
-
|
|
1039
|
-
// Step 3: Find callers
|
|
1040
|
-
const calledBy: CallerInfo[] = [];
|
|
1041
|
-
const incomingCalls = await db.getIncomingEdges(targetFunction.id, ['CALLS']);
|
|
1042
|
-
const seenCallers = new Set<string>();
|
|
1043
|
-
|
|
1044
|
-
for (const edge of incomingCalls) {
|
|
1045
|
-
const caller = await findContainingFunction(db, edge.src);
|
|
1046
|
-
if (caller && !seenCallers.has(caller.id)) {
|
|
1047
|
-
seenCallers.add(caller.id);
|
|
1048
|
-
calledBy.push(caller);
|
|
1049
|
-
}
|
|
1050
|
-
}
|
|
1051
|
-
|
|
1052
|
-
// Step 4: Build result
|
|
1053
|
-
const result = {
|
|
1054
|
-
id: targetFunction.id,
|
|
1055
|
-
name: targetFunction.name,
|
|
1056
|
-
file: targetFunction.file,
|
|
1057
|
-
line: targetFunction.line as number | undefined,
|
|
1058
|
-
async: targetFunction.async as boolean | undefined,
|
|
1059
|
-
calls,
|
|
1060
|
-
calledBy,
|
|
1061
|
-
};
|
|
1062
|
-
|
|
1063
|
-
// Format output
|
|
1064
|
-
const summary = [
|
|
1065
|
-
`Function: ${result.name}`,
|
|
1066
|
-
`File: ${result.file || 'unknown'}:${result.line || '?'}`,
|
|
1067
|
-
`Async: ${result.async || false}`,
|
|
1068
|
-
`Transitive: ${transitive}`,
|
|
1069
|
-
'',
|
|
1070
|
-
`Calls (${calls.length}):`,
|
|
1071
|
-
...formatCallsForDisplay(calls),
|
|
1072
|
-
'',
|
|
1073
|
-
`Called by (${calledBy.length}):`,
|
|
1074
|
-
...calledBy.map(c => ` - ${c.name} (${c.file}:${c.line})`),
|
|
1075
|
-
].join('\n');
|
|
1076
|
-
|
|
1077
|
-
return textResult(
|
|
1078
|
-
summary + '\n\n' +
|
|
1079
|
-
JSON.stringify(serializeBigInt(result), null, 2)
|
|
1080
|
-
);
|
|
1081
|
-
}
|
|
1082
|
-
|
|
1083
|
-
/**
|
|
1084
|
-
* Format calls for display, grouped by depth if transitive
|
|
1085
|
-
*/
|
|
1086
|
-
function formatCallsForDisplay(calls: CallInfo[]): string[] {
|
|
1087
|
-
const directCalls = calls.filter(c => (c.depth || 0) === 0);
|
|
1088
|
-
const transitiveCalls = calls.filter(c => (c.depth || 0) > 0);
|
|
1089
|
-
|
|
1090
|
-
const lines: string[] = [];
|
|
1091
|
-
|
|
1092
|
-
// Direct calls
|
|
1093
|
-
for (const c of directCalls) {
|
|
1094
|
-
const target = c.resolved
|
|
1095
|
-
? ` -> ${c.target?.name} (${c.target?.file}:${c.target?.line})`
|
|
1096
|
-
: ' (unresolved)';
|
|
1097
|
-
const prefix = c.type === 'METHOD_CALL' ? `${c.object}.` : '';
|
|
1098
|
-
lines.push(` - ${prefix}${c.name}()${target}`);
|
|
1099
|
-
}
|
|
1100
|
-
|
|
1101
|
-
// Transitive calls (grouped by depth)
|
|
1102
|
-
if (transitiveCalls.length > 0) {
|
|
1103
|
-
lines.push('');
|
|
1104
|
-
lines.push(' Transitive calls:');
|
|
1105
|
-
|
|
1106
|
-
const byDepth = new Map<number, CallInfo[]>();
|
|
1107
|
-
for (const c of transitiveCalls) {
|
|
1108
|
-
const depth = c.depth || 1;
|
|
1109
|
-
if (!byDepth.has(depth)) byDepth.set(depth, []);
|
|
1110
|
-
byDepth.get(depth)!.push(c);
|
|
1111
|
-
}
|
|
1112
|
-
|
|
1113
|
-
for (const [depth, depthCalls] of Array.from(byDepth.entries()).sort((a, b) => a[0] - b[0])) {
|
|
1114
|
-
for (const c of depthCalls) {
|
|
1115
|
-
const indent = ' '.repeat(depth + 1);
|
|
1116
|
-
const prefix = c.type === 'METHOD_CALL' ? `${c.object}.` : '';
|
|
1117
|
-
const target = c.resolved ? ` -> ${c.target?.name}` : '';
|
|
1118
|
-
lines.push(`${indent}[depth=${depth}] ${prefix}${c.name}()${target}`);
|
|
1119
|
-
}
|
|
1120
|
-
}
|
|
1121
|
-
}
|
|
1122
|
-
|
|
1123
|
-
return lines;
|
|
1124
|
-
}
|
|
1125
|
-
|
|
1126
|
-
// === BUG REPORTING ===
|
|
1127
|
-
|
|
1128
|
-
export async function handleReportIssue(args: ReportIssueArgs): Promise<ToolResult> {
|
|
1129
|
-
const { title, description, context, labels = ['bug'] } = args;
|
|
1130
|
-
// Use user's token if provided, otherwise fall back to project's issue-only token
|
|
1131
|
-
const GRAFEMA_ISSUE_TOKEN = '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';
|
|
1132
|
-
const githubToken = process.env.GITHUB_TOKEN || GRAFEMA_ISSUE_TOKEN;
|
|
1133
|
-
const repo = 'Disentinel/grafema';
|
|
1134
|
-
|
|
1135
|
-
// Build issue body
|
|
1136
|
-
const body = `## Description
|
|
1137
|
-
${description}
|
|
1138
|
-
|
|
1139
|
-
${context ? `## Context\n\`\`\`\n${context}\n\`\`\`\n` : ''}
|
|
1140
|
-
## Environment
|
|
1141
|
-
- Grafema version: 0.1.0-alpha.1
|
|
1142
|
-
- Reported via: MCP tool
|
|
1143
|
-
|
|
1144
|
-
---
|
|
1145
|
-
*This issue was automatically created via Grafema MCP server.*`;
|
|
1146
|
-
|
|
1147
|
-
// Try GitHub API if token is available
|
|
1148
|
-
if (githubToken) {
|
|
1149
|
-
try {
|
|
1150
|
-
const response = await fetch(`https://api.github.com/repos/${repo}/issues`, {
|
|
1151
|
-
method: 'POST',
|
|
1152
|
-
headers: {
|
|
1153
|
-
'Authorization': `token ${githubToken}`,
|
|
1154
|
-
'Content-Type': 'application/json',
|
|
1155
|
-
'Accept': 'application/vnd.github.v3+json',
|
|
1156
|
-
},
|
|
1157
|
-
body: JSON.stringify({
|
|
1158
|
-
title,
|
|
1159
|
-
body,
|
|
1160
|
-
labels: labels.filter(l => ['bug', 'enhancement', 'documentation', 'question'].includes(l)),
|
|
1161
|
-
}),
|
|
1162
|
-
});
|
|
1163
|
-
|
|
1164
|
-
if (response.ok) {
|
|
1165
|
-
const issue = await response.json() as { html_url: string; number: number };
|
|
1166
|
-
return textResult(
|
|
1167
|
-
`✅ Issue created successfully!\n\n` +
|
|
1168
|
-
`**Issue #${issue.number}**: ${issue.html_url}\n\n` +
|
|
1169
|
-
`Thank you for reporting this issue.`
|
|
1170
|
-
);
|
|
1171
|
-
} else {
|
|
1172
|
-
const error = await response.text();
|
|
1173
|
-
throw new Error(`GitHub API error: ${response.status} - ${error}`);
|
|
1174
|
-
}
|
|
1175
|
-
} catch (error) {
|
|
1176
|
-
// Fall through to manual template if API fails
|
|
1177
|
-
console.error('[report_issue] GitHub API failed:', error);
|
|
1178
|
-
}
|
|
1179
|
-
}
|
|
1180
|
-
|
|
1181
|
-
// Fallback: return template for manual submission
|
|
1182
|
-
const issueUrl = `https://github.com/${repo}/issues/new`;
|
|
1183
|
-
const encodedTitle = encodeURIComponent(title);
|
|
1184
|
-
const encodedBody = encodeURIComponent(body);
|
|
1185
|
-
const encodedLabels = encodeURIComponent(labels.join(','));
|
|
1186
|
-
const directUrl = `${issueUrl}?title=${encodedTitle}&body=${encodedBody}&labels=${encodedLabels}`;
|
|
1187
|
-
|
|
1188
|
-
return textResult(
|
|
1189
|
-
`⚠️ Failed to create issue automatically. Please create it manually:\n\n` +
|
|
1190
|
-
`**Quick link** (may truncate long descriptions):\n${directUrl}\n\n` +
|
|
1191
|
-
`**Or copy this template to** ${issueUrl}:\n\n` +
|
|
1192
|
-
`---\n**Title:** ${title}\n\n${body}\n---`
|
|
1193
|
-
);
|
|
1194
|
-
}
|
|
1195
|
-
|
|
1196
|
-
// === PROJECT STRUCTURE (REG-173) ===
|
|
1197
|
-
|
|
1198
|
-
export async function handleReadProjectStructure(
|
|
1199
|
-
args: ReadProjectStructureArgs
|
|
1200
|
-
): Promise<ToolResult> {
|
|
1201
|
-
const projectPath = getProjectPath();
|
|
1202
|
-
const subPath = args.path || '.';
|
|
1203
|
-
const maxDepth = Math.min(Math.max(1, args.depth || 3), 5);
|
|
1204
|
-
const includeFiles = args.include_files !== false;
|
|
1205
|
-
|
|
1206
|
-
const targetPath = join(projectPath, subPath);
|
|
1207
|
-
|
|
1208
|
-
if (!existsSync(targetPath)) {
|
|
1209
|
-
return errorResult(`Path does not exist: ${subPath}`);
|
|
1210
|
-
}
|
|
1211
|
-
|
|
1212
|
-
if (!statSync(targetPath).isDirectory()) {
|
|
1213
|
-
return errorResult(`Path is not a directory: ${subPath}`);
|
|
1214
|
-
}
|
|
1215
|
-
|
|
1216
|
-
const EXCLUDED = new Set([
|
|
1217
|
-
'node_modules', '.git', 'dist', 'build', '.grafema',
|
|
1218
|
-
'coverage', '.next', '.nuxt', '.cache', '.output',
|
|
1219
|
-
'__pycache__', '.tox', 'target',
|
|
1220
|
-
]);
|
|
1221
|
-
|
|
1222
|
-
const lines: string[] = [];
|
|
1223
|
-
|
|
1224
|
-
function walk(dir: string, prefix: string, depth: number): void {
|
|
1225
|
-
if (depth > maxDepth) return;
|
|
1226
|
-
|
|
1227
|
-
let entries: Dirent[];
|
|
1228
|
-
try {
|
|
1229
|
-
entries = readdirSync(dir, { withFileTypes: true });
|
|
1230
|
-
} catch {
|
|
1231
|
-
return;
|
|
1232
|
-
}
|
|
1233
|
-
|
|
1234
|
-
const dirs: string[] = [];
|
|
1235
|
-
const files: string[] = [];
|
|
1236
|
-
|
|
1237
|
-
for (const entry of entries) {
|
|
1238
|
-
if (EXCLUDED.has(entry.name)) continue;
|
|
1239
|
-
|
|
1240
|
-
if (entry.isDirectory()) {
|
|
1241
|
-
dirs.push(entry.name);
|
|
1242
|
-
} else if (includeFiles) {
|
|
1243
|
-
files.push(entry.name);
|
|
1244
|
-
}
|
|
1245
|
-
}
|
|
1246
|
-
|
|
1247
|
-
dirs.sort();
|
|
1248
|
-
files.sort();
|
|
1249
|
-
|
|
1250
|
-
const allEntries = [
|
|
1251
|
-
...dirs.map(d => ({ name: d, isDir: true })),
|
|
1252
|
-
...files.map(f => ({ name: f, isDir: false })),
|
|
1253
|
-
];
|
|
1254
|
-
|
|
1255
|
-
for (let i = 0; i < allEntries.length; i++) {
|
|
1256
|
-
const entry = allEntries[i];
|
|
1257
|
-
const isLast = i === allEntries.length - 1;
|
|
1258
|
-
const connector = isLast ? '└── ' : '├── ';
|
|
1259
|
-
const childPrefix = isLast ? ' ' : '│ ';
|
|
1260
|
-
|
|
1261
|
-
if (entry.isDir) {
|
|
1262
|
-
lines.push(`${prefix}${connector}${entry.name}/`);
|
|
1263
|
-
walk(join(dir, entry.name), prefix + childPrefix, depth + 1);
|
|
1264
|
-
} else {
|
|
1265
|
-
lines.push(`${prefix}${connector}${entry.name}`);
|
|
1266
|
-
}
|
|
1267
|
-
}
|
|
1268
|
-
}
|
|
1269
|
-
|
|
1270
|
-
lines.push(subPath === '.' ? basename(projectPath) + '/' : subPath + '/');
|
|
1271
|
-
walk(targetPath, '', 1);
|
|
1272
|
-
|
|
1273
|
-
if (lines.length === 1) {
|
|
1274
|
-
return textResult(`Directory is empty or contains only excluded entries: ${subPath}`);
|
|
1275
|
-
}
|
|
1276
|
-
|
|
1277
|
-
return textResult(lines.join('\n'));
|
|
1278
|
-
}
|
|
1279
|
-
|
|
1280
|
-
// === WRITE CONFIG (REG-173) ===
|
|
1281
|
-
|
|
1282
|
-
export async function handleWriteConfig(
|
|
1283
|
-
args: WriteConfigArgs
|
|
1284
|
-
): Promise<ToolResult> {
|
|
1285
|
-
const projectPath = getProjectPath();
|
|
1286
|
-
const grafemaDir = join(projectPath, '.grafema');
|
|
1287
|
-
const configPath = join(grafemaDir, 'config.yaml');
|
|
1288
|
-
|
|
1289
|
-
try {
|
|
1290
|
-
if (args.services) {
|
|
1291
|
-
validateServices(args.services, projectPath);
|
|
1292
|
-
}
|
|
1293
|
-
|
|
1294
|
-
if (args.include !== undefined || args.exclude !== undefined) {
|
|
1295
|
-
const warnings: string[] = [];
|
|
1296
|
-
validatePatterns(args.include, args.exclude, {
|
|
1297
|
-
warn: (msg: string) => warnings.push(msg),
|
|
1298
|
-
});
|
|
1299
|
-
}
|
|
1300
|
-
|
|
1301
|
-
if (args.workspace) {
|
|
1302
|
-
validateWorkspace(args.workspace, projectPath);
|
|
1303
|
-
}
|
|
1304
|
-
|
|
1305
|
-
const config: Record<string, unknown> = {};
|
|
1306
|
-
|
|
1307
|
-
if (args.services && args.services.length > 0) {
|
|
1308
|
-
config.services = args.services;
|
|
1309
|
-
}
|
|
1310
|
-
|
|
1311
|
-
if (args.plugins) {
|
|
1312
|
-
config.plugins = args.plugins;
|
|
1313
|
-
}
|
|
1314
|
-
|
|
1315
|
-
if (args.include) {
|
|
1316
|
-
config.include = args.include;
|
|
1317
|
-
}
|
|
1318
|
-
|
|
1319
|
-
if (args.exclude) {
|
|
1320
|
-
config.exclude = args.exclude;
|
|
1321
|
-
}
|
|
1322
|
-
|
|
1323
|
-
if (args.workspace) {
|
|
1324
|
-
config.workspace = args.workspace;
|
|
1325
|
-
}
|
|
1326
|
-
|
|
1327
|
-
const yaml = stringifyYAML(config, { lineWidth: 0 });
|
|
1328
|
-
const content =
|
|
1329
|
-
'# Grafema Configuration\n' +
|
|
1330
|
-
'# Generated by Grafema onboarding\n' +
|
|
1331
|
-
'# Documentation: https://github.com/grafema/grafema#configuration\n\n' +
|
|
1332
|
-
yaml;
|
|
1333
|
-
|
|
1334
|
-
if (!existsSync(grafemaDir)) {
|
|
1335
|
-
mkdirSync(grafemaDir, { recursive: true });
|
|
1336
|
-
}
|
|
1337
|
-
|
|
1338
|
-
writeFileSync(configPath, content);
|
|
1339
|
-
|
|
1340
|
-
const summary: string[] = ['Configuration written to .grafema/config.yaml'];
|
|
1341
|
-
|
|
1342
|
-
if (args.services && args.services.length > 0) {
|
|
1343
|
-
summary.push(`Services: ${args.services.map(s => s.name).join(', ')}`);
|
|
1344
|
-
} else {
|
|
1345
|
-
summary.push('Services: using auto-discovery (none explicitly configured)');
|
|
1346
|
-
}
|
|
1347
|
-
|
|
1348
|
-
if (args.plugins) {
|
|
1349
|
-
summary.push('Plugins: custom configuration');
|
|
1350
|
-
} else {
|
|
1351
|
-
summary.push('Plugins: using defaults');
|
|
1352
|
-
}
|
|
1353
|
-
|
|
1354
|
-
if (args.include) {
|
|
1355
|
-
summary.push(`Include patterns: ${args.include.join(', ')}`);
|
|
1356
|
-
}
|
|
1357
|
-
|
|
1358
|
-
if (args.exclude) {
|
|
1359
|
-
summary.push(`Exclude patterns: ${args.exclude.join(', ')}`);
|
|
1360
|
-
}
|
|
1361
|
-
|
|
1362
|
-
if (args.workspace?.roots) {
|
|
1363
|
-
summary.push(`Workspace roots: ${args.workspace.roots.join(', ')}`);
|
|
1364
|
-
}
|
|
1365
|
-
|
|
1366
|
-
summary.push('\nNext step: run analyze_project to build the graph.');
|
|
1367
|
-
|
|
1368
|
-
return textResult(summary.join('\n'));
|
|
1369
|
-
} catch (error) {
|
|
1370
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
1371
|
-
return errorResult(`Failed to write config: ${message}`);
|
|
1372
|
-
}
|
|
1373
|
-
}
|