-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodegraphplus.ts
More file actions
312 lines (290 loc) · 11.5 KB
/
Copy pathcodegraphplus.ts
File metadata and controls
312 lines (290 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
#!/usr/bin/env node
/**
* CodeGraphPlus CLI
*/
import { Command } from 'commander';
import * as fs from 'fs';
import * as path from 'path';
async function loadCodeGraphPlus() {
return import('../index');
}
const STUB_INDEX_MSG =
'Indexing: reserved (not implemented yet). Run `codegraphplus index` when indexers are ready.';
const program = new Command();
const pkg = JSON.parse(
fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf-8'),
);
program
.name('codegraphplus')
.description('Multi-asset API graph for cross-project search via MCP')
.version(pkg.version);
program
.command('init [path]')
.description('Initialize CodeGraphPlus in a project (.codegraphplus/)')
.option('-i, --index', 'Run stub index pass after init')
.action(async (target: string | undefined, opts: { index?: boolean }) => {
const { CodeGraphPlus } = await loadCodeGraphPlus();
const root = path.resolve(target ?? process.cwd());
const ag = CodeGraphPlus.init(root, {
index: opts.index,
onProgress: (p) => {
if (p.file) {
process.stderr.write(`[${p.plugin ?? 'scan'}] ${p.file} (${p.current}/${p.total})\n`);
}
},
});
ag.close();
console.log(`codegraphplus initialized in ${root}`);
if (opts.index) {
console.log(STUB_INDEX_MSG);
} else {
console.log('Run `codegraphplus init -i` or `codegraphplus index` to scan (stub indexers).');
}
});
program
.command('index [path]')
.description('Run stub index pass over the project')
.action(async (target: string | undefined) => {
const { CodeGraphPlus } = await loadCodeGraphPlus();
const root = path.resolve(target ?? process.cwd());
const ag = CodeGraphPlus.openSync(root);
const result = ag.index((p) => {
if (p.file) process.stderr.write(`[${p.plugin ?? 'scan'}] ${p.file}\n`);
});
ag.close();
console.log(
`Stub index complete: ${result.filesIndexed} file(s) tracked, ` +
`${result.assetsAdded} assets, ${result.relationsAdded} relations (${result.durationMs}ms)`,
);
console.log(STUB_INDEX_MSG);
});
program
.command('status [path]')
.description('Show index status')
.action(async (target: string | undefined) => {
const { CodeGraphPlus, isInitialized, ASSET_KINDS } = await loadCodeGraphPlus();
const root = path.resolve(target ?? process.cwd());
if (!isInitialized(root)) {
console.log('Not initialized. Run: codegraphplus init -i');
return;
}
const ag = CodeGraphPlus.openSync(root);
const stats = ag.getStats();
ag.close();
console.log(`Project: ${root}`);
console.log(`graphVersion: ${ag.getGraphVersion()}`);
console.log(`indexStatus: ${stats.indexStatus}`);
console.log(`Total assets: ${stats.totalAssets}`);
console.log(`Relations: ${stats.relationCount}`);
console.log(`Tracked files: ${stats.fileCount}`);
for (const kind of ASSET_KINDS) {
console.log(` ${kind}: ${stats.byKind[kind]}`);
}
});
program
.command('search <query> [path]')
.description('Search indexed assets')
.action(async (query: string, target: string | undefined) => {
const { CodeGraphPlus } = await loadCodeGraphPlus();
const ag = CodeGraphPlus.openSync(path.resolve(target ?? process.cwd()));
const results = ag.search(query);
ag.close();
if (results.length === 0) {
console.log('No results.');
return;
}
for (const r of results) {
console.log(`[${r.kind}] ${r.qualifiedName} — ${r.detail} (${r.sourceFile})`);
}
});
program
.command('traverse [path]')
.description('Paginated traversal by asset kind for Agent updates (table names, API URLs, etc.)')
.requiredOption('--kind <kind>', 'Asset kind: http_api, db_table, redis_key, topic, ...')
.option('--offset <n>', 'Pagination offset', '0')
.option('--limit <n>', 'Page size (1–100)', '20')
.option('--definition', 'Include definition JSON snippet per item')
.action(async (target: string | undefined, opts: { kind: string; offset: string; limit: string; definition?: boolean }) => {
const { CodeGraphPlus } = await loadCodeGraphPlus();
const ag = CodeGraphPlus.openSync(path.resolve(target ?? process.cwd()));
const result = ag.traverse({
kind: opts.kind as import('../types').AssetKind,
offset: parseInt(opts.offset, 10) || 0,
limit: parseInt(opts.limit, 10) || 20,
includeDefinition: opts.definition ?? false,
});
console.log(result.text);
ag.close();
});
program
.command('baseline [path]')
.description('Export Indexer baseline report for Agent enrichment')
.option('--kind <kind>', 'Filter by asset kind')
.option('--limit <n>', 'Max items to list', '50')
.option('--no-files', 'Omit tracked files without assets')
.action(async (target: string | undefined, opts: { kind?: string; limit: string; files: boolean }) => {
const { CodeGraphPlus } = await loadCodeGraphPlus();
const ag = CodeGraphPlus.openSync(path.resolve(target ?? process.cwd()));
console.log(ag.getBaseline({
kind: opts.kind as import('../types').AssetKind | undefined,
includeFiles: opts.files,
limit: parseInt(opts.limit, 10) || 50,
}));
ag.close();
});
program
.command('plugins [path]')
.description('List built-in and external Indexer plugins for a project')
.action(async (target: string | undefined) => {
const { CodeGraphPlus, isInitialized } = await loadCodeGraphPlus();
const root = path.resolve(target ?? process.cwd());
if (!isInitialized(root)) {
console.error('Not initialized. Run: codegraphplus init -i');
process.exitCode = 1;
return;
}
const ag = CodeGraphPlus.openSync(root);
const resolved = ag.listIndexerPlugins();
console.log(`Indexer slots — ${root}\n`);
console.log('Slot'.padEnd(18), 'Source'.padEnd(10), 'Script / plugin');
console.log('-'.repeat(72));
for (const s of resolved.slots) {
const script = s.scriptPath ?? '(built-in stub)';
const plugin = s.pluginName ? ` → ${s.pluginName}` : '';
const err = s.error ? ` [ERROR: ${s.error}]` : '';
console.log(s.slot.padEnd(18), s.source.padEnd(10), `${script}${plugin}${err}`);
}
if (resolved.loadErrors.length > 0) {
console.log('\nLoad errors:');
for (const e of resolved.loadErrors) console.log(` - ${e}`);
}
ag.close();
});
program
.command('apply')
.description('Apply Agent update patches from a JSON file')
.requiredOption('--file <path>', 'JSON file with assets/relations (same schema as codegraphplus_apply_updates)')
.option('--path <project>', 'Target project root')
.option('--dry-run', 'Validate without writing')
.option('--base-version <version>', 'Require local graph.version to match before apply')
.action(async (opts: { file: string; path?: string; dryRun?: boolean; baseVersion?: string }) => {
const { CodeGraphPlus } = await loadCodeGraphPlus();
const root = path.resolve(opts.path ?? process.cwd());
const raw = JSON.parse(fs.readFileSync(opts.file, 'utf-8')) as Record<string, unknown>;
const ag = CodeGraphPlus.openSync(root);
const payload: import('../enrich/types').AgentUpdatePayload = {
assets: Array.isArray(raw.assets) ? raw.assets as import('../enrich/types').AgentAssetPatch[] : [],
relations: Array.isArray(raw.relations) ? raw.relations as import('../enrich/types').AgentRelationPatch[] : [],
};
if (typeof raw.baseVersion === 'string') payload.baseVersion = raw.baseVersion;
const result = ag.applyAgentUpdates(payload, {
dryRun: opts.dryRun ?? false,
baseVersion: opts.baseVersion ?? payload.baseVersion,
});
console.log(ag.formatApplyResult(result));
ag.close();
});
const versionCmd = program
.command('version')
.description('Show or set graph.version (XXXX.XXXX.XXXX.XXXX)');
versionCmd
.command('set <version> [path]')
.description('Set graph version manually (milestones — segments 1–3; segment 4 auto-bumps on apply)')
.action(async (version: string, target: string | undefined) => {
const { CodeGraphPlus, isInitialized } = await loadCodeGraphPlus();
const root = path.resolve(target ?? process.cwd());
if (!isInitialized(root)) {
console.error('Not initialized. Run: codegraphplus init -i');
process.exitCode = 1;
return;
}
const ag = CodeGraphPlus.openSync(root);
try {
const set = ag.setGraphVersion(version);
console.log(`graphVersion set to ${set}`);
} catch (e) {
console.error(e instanceof Error ? e.message : String(e));
process.exitCode = 1;
}
ag.close();
});
versionCmd
.command('show [path]', { isDefault: true })
.description('Print current graph.version (default)')
.action(async (target: string | undefined) => {
const { CodeGraphPlus, isInitialized } = await loadCodeGraphPlus();
const root = path.resolve(target ?? process.cwd());
if (!isInitialized(root)) {
console.error('Not initialized. Run: codegraphplus init -i');
process.exitCode = 1;
return;
}
const ag = CodeGraphPlus.openSync(root);
console.log(ag.getGraphVersion());
ag.close();
});
program
.command('install')
.description('Register CodeGraphPlus MCP server in Cursor / OpenCode config')
.option('--target <id>', 'cursor | opencode | all', 'all')
.option('--location <scope>', 'global (default) or local (project .cursor/)', 'global')
.option('--dev', 'Use node + script path instead of codegraphplus on PATH (local development)')
.option('--print', 'Print config snippet without writing files')
.option('--uninstall', 'Remove CodeGraphPlus MCP entries')
.action(async (opts: {
target: string;
location: string;
dev?: boolean;
print?: boolean;
uninstall?: boolean;
}) => {
const { installMcp, uninstallMcp, printMcpConfig, formatInstallResults } = await import('../installer/index');
const location = opts.location === 'local' ? 'local' : 'global';
const target = opts.target as import('../installer/types').InstallTargetId | 'all';
const validTargets = new Set(['cursor', 'opencode', 'all']);
if (!validTargets.has(target)) {
console.error(`Unknown target "${opts.target}". Use cursor, opencode, or all.`);
process.exitCode = 1;
return;
}
if (opts.print) {
console.log(printMcpConfig(target, location, { dev: opts.dev }));
return;
}
if (opts.uninstall) {
const results = uninstallMcp(target, location);
console.log(formatInstallResults(results));
return;
}
const results = installMcp(target, location, { dev: opts.dev });
console.log(formatInstallResults(results));
if (opts.dev) {
console.log('\nDev mode: MCP uses node + absolute script path.');
} else {
console.log('\nEnsure `codegraphplus` is on PATH (npm i -g codegraphplus or npm link).');
}
});
program
.command('serve')
.description('Start MCP server')
.option('--mcp', 'Run as MCP server over stdio')
.option('--path <path>', 'Explicit project path (recommended for Cursor)')
.action(async (opts: { mcp?: boolean; path?: string }) => {
if (!opts.mcp) {
console.error('Use --mcp to start the MCP server');
console.error('\nExample MCP config:');
console.error(JSON.stringify({
mcpServers: {
CodeGraphPlus: {
command: 'node',
args: [path.join(__dirname, 'codegraphplus.js'), 'serve', '--mcp', '--path', '${workspaceFolder}'],
},
},
}, null, 2));
return;
}
const { MCPServer } = await import('../mcp/index');
const server = new MCPServer(opts.path);
await server.start();
});
program.parse();