codeorbit 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/dist/server.js ADDED
@@ -0,0 +1,3408 @@
1
+ // src/adapters/mcp/server.ts
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { z } from "zod";
5
+
6
+ // src/adapters/mcp/tools.ts
7
+ import fs7 from "fs";
8
+ import path10 from "path";
9
+
10
+ // src/infrastructure/SqliteGraphRepository.ts
11
+ import fs from "fs";
12
+ import path from "path";
13
+ import Database from "better-sqlite3";
14
+ var SCHEMA_SQL = `
15
+ CREATE TABLE IF NOT EXISTS nodes (
16
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
17
+ kind TEXT NOT NULL,
18
+ name TEXT NOT NULL,
19
+ qualified_name TEXT NOT NULL UNIQUE,
20
+ file_path TEXT NOT NULL,
21
+ line_start INTEGER,
22
+ line_end INTEGER,
23
+ language TEXT,
24
+ parent_name TEXT,
25
+ params TEXT,
26
+ return_type TEXT,
27
+ modifiers TEXT,
28
+ is_test INTEGER DEFAULT 0,
29
+ file_hash TEXT,
30
+ extra TEXT DEFAULT '{}',
31
+ updated_at REAL NOT NULL
32
+ );
33
+
34
+ CREATE TABLE IF NOT EXISTS edges (
35
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
36
+ kind TEXT NOT NULL,
37
+ source_qualified TEXT NOT NULL,
38
+ target_qualified TEXT NOT NULL,
39
+ file_path TEXT NOT NULL,
40
+ line INTEGER DEFAULT 0,
41
+ extra TEXT DEFAULT '{}',
42
+ updated_at REAL NOT NULL
43
+ );
44
+
45
+ CREATE TABLE IF NOT EXISTS metadata (
46
+ key TEXT PRIMARY KEY,
47
+ value TEXT NOT NULL
48
+ );
49
+
50
+ CREATE INDEX IF NOT EXISTS idx_nodes_file ON nodes(file_path);
51
+ CREATE INDEX IF NOT EXISTS idx_nodes_kind ON nodes(kind);
52
+ CREATE INDEX IF NOT EXISTS idx_nodes_qualified ON nodes(qualified_name);
53
+ CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source_qualified);
54
+ CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target_qualified);
55
+ CREATE INDEX IF NOT EXISTS idx_edges_kind ON edges(kind);
56
+ CREATE INDEX IF NOT EXISTS idx_edges_file ON edges(file_path);
57
+ `;
58
+ var SqliteGraphRepository = class {
59
+ db;
60
+ adjCache = null;
61
+ dbPath;
62
+ constructor(dbPath) {
63
+ this.dbPath = dbPath;
64
+ const dir = path.dirname(dbPath);
65
+ if (!fs.existsSync(dir)) {
66
+ fs.mkdirSync(dir, { recursive: true });
67
+ }
68
+ this.db = new Database(dbPath);
69
+ this.db.pragma("journal_mode = WAL");
70
+ this.db.pragma("busy_timeout = 5000");
71
+ try {
72
+ this.db.pragma("wal_checkpoint(TRUNCATE)");
73
+ } catch {
74
+ }
75
+ this._initSchema();
76
+ }
77
+ close() {
78
+ try {
79
+ this.db.pragma("wal_checkpoint(TRUNCATE)");
80
+ } catch {
81
+ }
82
+ this.db.close();
83
+ for (const suffix of ["-wal", "-shm"]) {
84
+ const side = this.dbPath + suffix;
85
+ try {
86
+ if (fs.existsSync(side)) {
87
+ fs.unlinkSync(side);
88
+ }
89
+ } catch {
90
+ }
91
+ }
92
+ }
93
+ // ---------------------------------------------------------------------------
94
+ // Write operations
95
+ // ---------------------------------------------------------------------------
96
+ upsertNode(node, fileHash = "") {
97
+ const now = Date.now() / 1e3;
98
+ const qualified = this._makeQualified(node);
99
+ const extra = node.extra ? JSON.stringify(node.extra) : "{}";
100
+ this.db.prepare(`
101
+ INSERT INTO nodes
102
+ (kind, name, qualified_name, file_path, line_start, line_end,
103
+ language, parent_name, params, return_type, modifiers, is_test,
104
+ file_hash, extra, updated_at)
105
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
106
+ ON CONFLICT(qualified_name) DO UPDATE SET
107
+ kind=excluded.kind, name=excluded.name,
108
+ file_path=excluded.file_path, line_start=excluded.line_start,
109
+ line_end=excluded.line_end, language=excluded.language,
110
+ parent_name=excluded.parent_name, params=excluded.params,
111
+ return_type=excluded.return_type, modifiers=excluded.modifiers,
112
+ is_test=excluded.is_test, file_hash=excluded.file_hash,
113
+ extra=excluded.extra, updated_at=excluded.updated_at
114
+ `).run(
115
+ node.kind,
116
+ node.name,
117
+ qualified,
118
+ node.filePath,
119
+ node.lineStart,
120
+ node.lineEnd,
121
+ node.language ?? null,
122
+ node.parentName ?? null,
123
+ node.params ?? null,
124
+ node.returnType ?? null,
125
+ node.modifiers ?? null,
126
+ node.isTest ? 1 : 0,
127
+ fileHash,
128
+ extra,
129
+ now
130
+ );
131
+ const row = this.db.prepare(
132
+ "SELECT id FROM nodes WHERE qualified_name = ?"
133
+ ).get(qualified);
134
+ return row.id;
135
+ }
136
+ upsertEdge(edge) {
137
+ const now = Date.now() / 1e3;
138
+ const extra = edge.extra ? JSON.stringify(edge.extra) : "{}";
139
+ const line = edge.line ?? 0;
140
+ const existing = this.db.prepare(`
141
+ SELECT id FROM edges
142
+ WHERE kind=? AND source_qualified=? AND target_qualified=?
143
+ AND file_path=? AND line=?
144
+ `).get(edge.kind, edge.source, edge.target, edge.filePath, line);
145
+ if (existing) {
146
+ this.db.prepare(
147
+ "UPDATE edges SET line=?, extra=?, updated_at=? WHERE id=?"
148
+ ).run(line, extra, now, existing.id);
149
+ return existing.id;
150
+ }
151
+ const result = this.db.prepare(`
152
+ INSERT INTO edges
153
+ (kind, source_qualified, target_qualified, file_path, line, extra, updated_at)
154
+ VALUES (?, ?, ?, ?, ?, ?, ?)
155
+ `).run(edge.kind, edge.source, edge.target, edge.filePath, line, extra, now);
156
+ return Number(result.lastInsertRowid);
157
+ }
158
+ removeFileData(filePath) {
159
+ this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(filePath);
160
+ this.db.prepare("DELETE FROM edges WHERE file_path = ?").run(filePath);
161
+ this._invalidateCache();
162
+ }
163
+ storeFileNodesEdges(filePath, nodes, edges, fileHash = "") {
164
+ const txn = this.db.transaction(() => {
165
+ this.removeFileData(filePath);
166
+ for (const node of nodes) {
167
+ this.upsertNode(node, fileHash);
168
+ }
169
+ for (const edge of edges) {
170
+ this.upsertEdge(edge);
171
+ }
172
+ });
173
+ txn();
174
+ this._invalidateCache();
175
+ }
176
+ setMetadata(key, value) {
177
+ this.db.prepare(
178
+ "INSERT OR REPLACE INTO metadata (key, value) VALUES (?, ?)"
179
+ ).run(key, value);
180
+ }
181
+ getMetadata(key) {
182
+ const row = this.db.prepare(
183
+ "SELECT value FROM metadata WHERE key = ?"
184
+ ).get(key);
185
+ return row?.value;
186
+ }
187
+ // ---------------------------------------------------------------------------
188
+ // Read operations
189
+ // ---------------------------------------------------------------------------
190
+ getNode(qualifiedName) {
191
+ const row = this.db.prepare(
192
+ "SELECT * FROM nodes WHERE qualified_name = ?"
193
+ ).get(qualifiedName);
194
+ return row ? this._rowToNode(row) : void 0;
195
+ }
196
+ getNodesByFile(filePath) {
197
+ const rows = this.db.prepare(
198
+ "SELECT * FROM nodes WHERE file_path = ? ORDER BY line_start"
199
+ ).all(filePath);
200
+ return rows.map((r) => this._rowToNode(r));
201
+ }
202
+ getEdgesBySource(qualifiedName) {
203
+ const rows = this.db.prepare(
204
+ "SELECT * FROM edges WHERE source_qualified = ?"
205
+ ).all(qualifiedName);
206
+ return rows.map((r) => this._rowToEdge(r));
207
+ }
208
+ getEdgesByTarget(qualifiedName) {
209
+ const rows = this.db.prepare(
210
+ "SELECT * FROM edges WHERE target_qualified = ?"
211
+ ).all(qualifiedName);
212
+ return rows.map((r) => this._rowToEdge(r));
213
+ }
214
+ searchEdgesByTargetName(name, kind = "CALLS") {
215
+ const rows = this.db.prepare(
216
+ "SELECT * FROM edges WHERE target_qualified = ? AND kind = ?"
217
+ ).all(name, kind);
218
+ return rows.map((r) => this._rowToEdge(r));
219
+ }
220
+ getAllFiles() {
221
+ const rows = this.db.prepare(
222
+ "SELECT DISTINCT file_path FROM nodes WHERE kind = 'File' ORDER BY file_path"
223
+ ).all();
224
+ return rows.map((r) => r.file_path);
225
+ }
226
+ searchNodes(query, limit = 20) {
227
+ const words = query.toLowerCase().split(/\s+/).filter(Boolean);
228
+ if (words.length === 0) {
229
+ return [];
230
+ }
231
+ const conditions = words.map(
232
+ () => "(LOWER(name) LIKE ? OR LOWER(qualified_name) LIKE ?)"
233
+ );
234
+ const params = [];
235
+ for (const word of words) {
236
+ params.push(`%${word}%`, `%${word}%`);
237
+ }
238
+ params.push(limit);
239
+ const where = conditions.join(" AND ");
240
+ const rows = this.db.prepare(
241
+ `SELECT * FROM nodes WHERE ${where} LIMIT ?`
242
+ ).all(...params);
243
+ return rows.map((r) => this._rowToNode(r));
244
+ }
245
+ getSubgraph(qualifiedNames) {
246
+ const nodes = [];
247
+ for (const qn of qualifiedNames) {
248
+ const n = this.getNode(qn);
249
+ if (n) {
250
+ nodes.push(n);
251
+ }
252
+ }
253
+ const qnSet = new Set(qualifiedNames);
254
+ const edges = [];
255
+ for (const qn of qualifiedNames) {
256
+ for (const e of this.getEdgesBySource(qn)) {
257
+ if (qnSet.has(e.targetQualified)) {
258
+ edges.push(e);
259
+ }
260
+ }
261
+ }
262
+ return { nodes, edges };
263
+ }
264
+ getStats() {
265
+ const totalNodes = this.db.prepare("SELECT COUNT(*) AS cnt FROM nodes").get().cnt;
266
+ const totalEdges = this.db.prepare("SELECT COUNT(*) AS cnt FROM edges").get().cnt;
267
+ const nodesByKind = {};
268
+ for (const r of this.db.prepare(
269
+ "SELECT kind, COUNT(*) AS cnt FROM nodes GROUP BY kind"
270
+ ).all()) {
271
+ nodesByKind[r.kind] = r.cnt;
272
+ }
273
+ const edgesByKind = {};
274
+ for (const r of this.db.prepare(
275
+ "SELECT kind, COUNT(*) AS cnt FROM edges GROUP BY kind"
276
+ ).all()) {
277
+ edgesByKind[r.kind] = r.cnt;
278
+ }
279
+ const languages = this.db.prepare(
280
+ "SELECT DISTINCT language FROM nodes WHERE language IS NOT NULL AND language != ''"
281
+ ).all().map((r) => r.language);
282
+ const filesCount = this.db.prepare(
283
+ "SELECT COUNT(*) AS cnt FROM nodes WHERE kind = 'File'"
284
+ ).get().cnt;
285
+ const lastUpdated = this.getMetadata("last_updated") ?? null;
286
+ let embeddingsCount = 0;
287
+ try {
288
+ embeddingsCount = this.db.prepare("SELECT COUNT(*) AS cnt FROM embeddings").get().cnt;
289
+ } catch {
290
+ }
291
+ return {
292
+ totalNodes,
293
+ totalEdges,
294
+ nodesByKind,
295
+ edgesByKind,
296
+ languages,
297
+ filesCount,
298
+ lastUpdated,
299
+ embeddingsCount
300
+ };
301
+ }
302
+ getNodesBySize(minLines = 50, maxLines, kind, filePathPattern, limit = 50) {
303
+ const conditions = [
304
+ "line_start IS NOT NULL",
305
+ "line_end IS NOT NULL",
306
+ "(line_end - line_start + 1) >= ?"
307
+ ];
308
+ const params = [minLines];
309
+ if (maxLines !== void 0) {
310
+ conditions.push("(line_end - line_start + 1) <= ?");
311
+ params.push(maxLines);
312
+ }
313
+ if (kind) {
314
+ conditions.push("kind = ?");
315
+ params.push(kind);
316
+ }
317
+ if (filePathPattern) {
318
+ conditions.push("file_path LIKE ?");
319
+ params.push(`%${filePathPattern}%`);
320
+ }
321
+ params.push(limit);
322
+ const where = conditions.join(" AND ");
323
+ const rows = this.db.prepare(
324
+ `SELECT * FROM nodes WHERE ${where} ORDER BY (line_end - line_start + 1) DESC LIMIT ?`
325
+ ).all(...params);
326
+ return rows.map((r) => ({
327
+ ...this._rowToNode(r),
328
+ lineCount: r.line_start != null && r.line_end != null ? r.line_end - r.line_start + 1 : 0
329
+ }));
330
+ }
331
+ getAllEdges() {
332
+ const rows = this.db.prepare("SELECT * FROM edges").all();
333
+ return rows.map((r) => this._rowToEdge(r));
334
+ }
335
+ getEdgesAmong(qualifiedNames) {
336
+ if (qualifiedNames.size === 0) {
337
+ return [];
338
+ }
339
+ const qns = [...qualifiedNames];
340
+ const results = [];
341
+ const batchSize = 450;
342
+ for (let i = 0; i < qns.length; i += batchSize) {
343
+ const batch = qns.slice(i, i + batchSize);
344
+ const placeholders = batch.map(() => "?").join(",");
345
+ const rows = this.db.prepare(
346
+ `SELECT * FROM edges WHERE source_qualified IN (${placeholders})`
347
+ ).all(...batch);
348
+ for (const r of rows) {
349
+ const edge = this._rowToEdge(r);
350
+ if (qualifiedNames.has(edge.targetQualified)) {
351
+ results.push(edge);
352
+ }
353
+ }
354
+ }
355
+ return results;
356
+ }
357
+ // ---------------------------------------------------------------------------
358
+ // Adjacency (BFS support for use cases)
359
+ // ---------------------------------------------------------------------------
360
+ getAdjacency() {
361
+ const cache = this._buildAdjacency();
362
+ return { outgoing: cache.out, incoming: cache.in };
363
+ }
364
+ // ---------------------------------------------------------------------------
365
+ // Private helpers
366
+ // ---------------------------------------------------------------------------
367
+ _initSchema() {
368
+ this.db.exec(SCHEMA_SQL);
369
+ this.setMetadata("schema_version", "1");
370
+ }
371
+ _invalidateCache() {
372
+ this.adjCache = null;
373
+ }
374
+ _buildAdjacency() {
375
+ if (this.adjCache) {
376
+ return this.adjCache;
377
+ }
378
+ const out = /* @__PURE__ */ new Map();
379
+ const inMap = /* @__PURE__ */ new Map();
380
+ const rows = this.db.prepare("SELECT source_qualified, target_qualified FROM edges").all();
381
+ for (const r of rows) {
382
+ if (!out.has(r.source_qualified)) {
383
+ out.set(r.source_qualified, /* @__PURE__ */ new Set());
384
+ }
385
+ out.get(r.source_qualified).add(r.target_qualified);
386
+ if (!inMap.has(r.target_qualified)) {
387
+ inMap.set(r.target_qualified, /* @__PURE__ */ new Set());
388
+ }
389
+ inMap.get(r.target_qualified).add(r.source_qualified);
390
+ }
391
+ this.adjCache = { out, in: inMap };
392
+ return this.adjCache;
393
+ }
394
+ _makeQualified(node) {
395
+ if (node.kind === "File") {
396
+ return node.filePath;
397
+ }
398
+ if (node.parentName) {
399
+ return `${node.filePath}::${node.parentName}.${node.name}`;
400
+ }
401
+ return `${node.filePath}::${node.name}`;
402
+ }
403
+ _rowToNode(row) {
404
+ return {
405
+ id: row.id,
406
+ kind: row.kind,
407
+ name: row.name,
408
+ qualifiedName: row.qualified_name,
409
+ filePath: row.file_path,
410
+ lineStart: row.line_start,
411
+ lineEnd: row.line_end,
412
+ language: row.language ?? null,
413
+ parentName: row.parent_name ?? null,
414
+ params: row.params ?? null,
415
+ returnType: row.return_type ?? null,
416
+ modifiers: row.modifiers ?? null,
417
+ isTest: row.is_test === 1,
418
+ fileHash: row.file_hash ?? null
419
+ };
420
+ }
421
+ _rowToEdge(row) {
422
+ return {
423
+ id: row.id,
424
+ kind: row.kind,
425
+ sourceQualified: row.source_qualified,
426
+ targetQualified: row.target_qualified,
427
+ filePath: row.file_path,
428
+ line: row.line ?? 0
429
+ };
430
+ }
431
+ };
432
+ function sanitizeName(s, maxLen = 256) {
433
+ let cleaned = "";
434
+ for (const ch of s) {
435
+ const code = ch.codePointAt(0) ?? 0;
436
+ if (ch === " " || ch === "\n" || code >= 32) {
437
+ cleaned += ch;
438
+ }
439
+ }
440
+ return cleaned.slice(0, maxLen);
441
+ }
442
+ function nodeToDict(n) {
443
+ return {
444
+ id: n.id,
445
+ kind: n.kind,
446
+ name: sanitizeName(n.name),
447
+ qualified_name: sanitizeName(n.qualifiedName),
448
+ file_path: n.filePath,
449
+ line_start: n.lineStart,
450
+ line_end: n.lineEnd,
451
+ language: n.language,
452
+ parent_name: n.parentName ? sanitizeName(n.parentName) : n.parentName,
453
+ is_test: n.isTest
454
+ };
455
+ }
456
+ function edgeToDict(e) {
457
+ return {
458
+ id: e.id,
459
+ kind: e.kind,
460
+ source: sanitizeName(e.sourceQualified),
461
+ target: sanitizeName(e.targetQualified),
462
+ file_path: e.filePath,
463
+ line: e.line
464
+ };
465
+ }
466
+
467
+ // src/infrastructure/TreeSitterParser.ts
468
+ import crypto from "crypto";
469
+ import fs2 from "fs";
470
+ import { createRequire } from "module";
471
+ import path2 from "path";
472
+ import Parser from "tree-sitter";
473
+ var _require = createRequire(import.meta.url);
474
+ function loadLanguage(pkg) {
475
+ try {
476
+ const mod = _require(pkg);
477
+ return mod.default ?? mod;
478
+ } catch {
479
+ return null;
480
+ }
481
+ }
482
+ var _languageCache = /* @__PURE__ */ new Map();
483
+ function getLanguage(name) {
484
+ if (_languageCache.has(name)) {
485
+ return _languageCache.get(name) ?? null;
486
+ }
487
+ const pkgMap = {
488
+ python: "tree-sitter-python",
489
+ javascript: "tree-sitter-javascript",
490
+ typescript: "tree-sitter-typescript/bindings/node/typescript",
491
+ tsx: "tree-sitter-typescript/bindings/node/tsx",
492
+ go: "tree-sitter-go",
493
+ rust: "tree-sitter-rust",
494
+ java: "tree-sitter-java",
495
+ c: "tree-sitter-c",
496
+ cpp: "tree-sitter-cpp",
497
+ csharp: "tree-sitter-c-sharp",
498
+ ruby: "tree-sitter-ruby",
499
+ kotlin: "tree-sitter-kotlin",
500
+ swift: "tree-sitter-swift",
501
+ php: "tree-sitter-php/php",
502
+ solidity: "tree-sitter-solidity",
503
+ vue: "tree-sitter-vue"
504
+ };
505
+ const pkg = pkgMap[name];
506
+ const lang = pkg ? loadLanguage(pkg) : null;
507
+ _languageCache.set(name, lang);
508
+ return lang;
509
+ }
510
+ var EXTENSION_TO_LANGUAGE = {
511
+ ".py": "python",
512
+ ".js": "javascript",
513
+ ".jsx": "javascript",
514
+ ".ts": "typescript",
515
+ ".tsx": "tsx",
516
+ ".go": "go",
517
+ ".rs": "rust",
518
+ ".java": "java",
519
+ ".cs": "csharp",
520
+ ".rb": "ruby",
521
+ ".cpp": "cpp",
522
+ ".cc": "cpp",
523
+ ".cxx": "cpp",
524
+ ".c": "c",
525
+ ".h": "c",
526
+ ".hpp": "cpp",
527
+ ".kt": "kotlin",
528
+ ".swift": "swift",
529
+ ".php": "php",
530
+ ".sol": "solidity",
531
+ ".vue": "vue"
532
+ };
533
+ var CLASS_TYPES = {
534
+ python: ["class_definition"],
535
+ javascript: ["class_declaration", "class"],
536
+ typescript: ["class_declaration", "class"],
537
+ tsx: ["class_declaration", "class"],
538
+ go: ["type_declaration"],
539
+ rust: ["struct_item", "enum_item", "impl_item"],
540
+ java: ["class_declaration", "interface_declaration", "enum_declaration"],
541
+ c: ["struct_specifier", "type_definition"],
542
+ cpp: ["class_specifier", "struct_specifier"],
543
+ csharp: ["class_declaration", "interface_declaration", "enum_declaration", "struct_declaration"],
544
+ ruby: ["class", "module"],
545
+ kotlin: ["class_declaration", "object_declaration"],
546
+ swift: ["class_declaration", "struct_declaration", "protocol_declaration"],
547
+ php: ["class_declaration", "interface_declaration"],
548
+ solidity: [
549
+ "contract_declaration",
550
+ "interface_declaration",
551
+ "library_declaration",
552
+ "struct_declaration",
553
+ "enum_declaration",
554
+ "error_declaration",
555
+ "user_defined_type_definition"
556
+ ]
557
+ };
558
+ var FUNCTION_TYPES = {
559
+ python: ["function_definition"],
560
+ javascript: ["function_declaration", "method_definition", "arrow_function"],
561
+ typescript: ["function_declaration", "method_definition", "arrow_function"],
562
+ tsx: ["function_declaration", "method_definition", "arrow_function"],
563
+ go: ["function_declaration", "method_declaration"],
564
+ rust: ["function_item"],
565
+ java: ["method_declaration", "constructor_declaration"],
566
+ c: ["function_definition"],
567
+ cpp: ["function_definition"],
568
+ csharp: ["method_declaration", "constructor_declaration"],
569
+ ruby: ["method", "singleton_method"],
570
+ kotlin: ["function_declaration"],
571
+ swift: ["function_declaration"],
572
+ php: ["function_definition", "method_declaration"],
573
+ solidity: [
574
+ "function_definition",
575
+ "constructor_definition",
576
+ "modifier_definition",
577
+ "event_definition",
578
+ "fallback_receive_definition"
579
+ ]
580
+ };
581
+ var IMPORT_TYPES = {
582
+ python: ["import_statement", "import_from_statement"],
583
+ javascript: ["import_statement"],
584
+ typescript: ["import_statement"],
585
+ tsx: ["import_statement"],
586
+ go: ["import_declaration"],
587
+ rust: ["use_declaration"],
588
+ java: ["import_declaration"],
589
+ c: ["preproc_include"],
590
+ cpp: ["preproc_include"],
591
+ csharp: ["using_directive"],
592
+ ruby: ["call"],
593
+ // require / require_relative
594
+ kotlin: ["import_header"],
595
+ swift: ["import_declaration"],
596
+ php: ["namespace_use_declaration"],
597
+ solidity: ["import_directive"]
598
+ };
599
+ var CALL_TYPES = {
600
+ python: ["call"],
601
+ javascript: ["call_expression", "new_expression"],
602
+ typescript: ["call_expression", "new_expression"],
603
+ tsx: ["call_expression", "new_expression"],
604
+ go: ["call_expression"],
605
+ rust: ["call_expression", "macro_invocation"],
606
+ java: ["method_invocation", "object_creation_expression"],
607
+ c: ["call_expression"],
608
+ cpp: ["call_expression"],
609
+ csharp: ["invocation_expression", "object_creation_expression"],
610
+ ruby: ["call", "method_call"],
611
+ kotlin: ["call_expression"],
612
+ swift: ["call_expression"],
613
+ php: ["function_call_expression", "member_call_expression"],
614
+ solidity: ["call_expression"]
615
+ };
616
+ var TEST_PATTERNS = [
617
+ /^test_/,
618
+ /^Test/,
619
+ /_test$/,
620
+ /\.test\./,
621
+ /\.spec\./,
622
+ /_spec$/
623
+ ];
624
+ var TEST_FILE_PATTERNS = [
625
+ /test_.*\.py$/,
626
+ /.*_test\.py$/,
627
+ /.*\.test\.[jt]sx?$/,
628
+ /.*\.spec\.[jt]sx?$/,
629
+ /.*_test\.go$/,
630
+ /tests?\//
631
+ ];
632
+ function isTestFile(filePath) {
633
+ return TEST_FILE_PATTERNS.some((p) => p.test(filePath));
634
+ }
635
+ var TEST_RUNNER_NAMES = /* @__PURE__ */ new Set([
636
+ "describe",
637
+ "it",
638
+ "test",
639
+ "beforeEach",
640
+ "afterEach",
641
+ "beforeAll",
642
+ "afterAll"
643
+ ]);
644
+ function isTestFunction(name, filePath) {
645
+ if (TEST_PATTERNS.some((p) => p.test(name))) {
646
+ return true;
647
+ }
648
+ if (isTestFile(filePath) && TEST_RUNNER_NAMES.has(name)) {
649
+ return true;
650
+ }
651
+ return false;
652
+ }
653
+ var MAX_AST_DEPTH = 180;
654
+ var MODULE_CACHE_MAX = 15e3;
655
+ var CodeParser = class {
656
+ parsers = /* @__PURE__ */ new Map();
657
+ moduleFileCache = /* @__PURE__ */ new Map();
658
+ getParser(language) {
659
+ if (this.parsers.has(language)) {
660
+ return this.parsers.get(language) ?? null;
661
+ }
662
+ try {
663
+ const lang = getLanguage(language);
664
+ if (!lang) {
665
+ return null;
666
+ }
667
+ const p = new Parser();
668
+ p.setLanguage(lang);
669
+ this.parsers.set(language, p);
670
+ return p;
671
+ } catch {
672
+ return null;
673
+ }
674
+ }
675
+ detectLanguage(filePath) {
676
+ const ext = path2.extname(filePath).toLowerCase();
677
+ return EXTENSION_TO_LANGUAGE[ext] ?? null;
678
+ }
679
+ parseFile(filePath) {
680
+ let source;
681
+ try {
682
+ source = fs2.readFileSync(filePath);
683
+ } catch {
684
+ return [[], []];
685
+ }
686
+ return this.parseBytes(filePath, source);
687
+ }
688
+ parseBytes(filePath, source) {
689
+ const language = this.detectLanguage(filePath);
690
+ if (!language) {
691
+ return [[], []];
692
+ }
693
+ if (language === "vue") {
694
+ return this._parseVue(filePath, source);
695
+ }
696
+ const parser = this.getParser(language);
697
+ if (!parser) {
698
+ return [[], []];
699
+ }
700
+ const tree = parser.parse(source.toString("utf-8"));
701
+ const nodes = [];
702
+ const edges = [];
703
+ const testFile = isTestFile(filePath);
704
+ const lineCount = source.toString("utf-8").split("\n").length;
705
+ nodes.push({
706
+ kind: "File",
707
+ name: filePath,
708
+ filePath,
709
+ lineStart: 1,
710
+ lineEnd: lineCount,
711
+ language,
712
+ isTest: testFile
713
+ });
714
+ const [importMap, definedNames] = this._collectFileScope(
715
+ tree.rootNode,
716
+ language,
717
+ source
718
+ );
719
+ this._extractFromTree(
720
+ tree.rootNode,
721
+ source,
722
+ language,
723
+ filePath,
724
+ nodes,
725
+ edges,
726
+ void 0,
727
+ void 0,
728
+ importMap,
729
+ definedNames
730
+ );
731
+ const resolvedEdges = this._resolveCallTargets(nodes, edges, filePath);
732
+ if (testFile) {
733
+ const testQNames = /* @__PURE__ */ new Set();
734
+ for (const n of nodes) {
735
+ if (n.isTest) {
736
+ testQNames.add(this._qualify(n.name, filePath, n.parentName ?? null));
737
+ }
738
+ }
739
+ const testedBy = [];
740
+ for (const edge of resolvedEdges) {
741
+ if (edge.kind === "CALLS" && testQNames.has(edge.source)) {
742
+ testedBy.push({
743
+ kind: "TESTED_BY",
744
+ source: edge.target,
745
+ target: edge.source,
746
+ filePath: edge.filePath,
747
+ line: edge.line
748
+ });
749
+ }
750
+ }
751
+ resolvedEdges.push(...testedBy);
752
+ }
753
+ return [nodes, resolvedEdges];
754
+ }
755
+ _parseVue(filePath, source) {
756
+ const vueParser = this.getParser("vue");
757
+ if (!vueParser) {
758
+ return [[], []];
759
+ }
760
+ const tree = vueParser.parse(source.toString("utf-8"));
761
+ const testFile = isTestFile(filePath);
762
+ const lineCount = source.toString("utf-8").split("\n").length;
763
+ const allNodes = [{
764
+ kind: "File",
765
+ name: filePath,
766
+ filePath,
767
+ lineStart: 1,
768
+ lineEnd: lineCount,
769
+ language: "vue",
770
+ isTest: testFile
771
+ }];
772
+ const allEdges = [];
773
+ for (const child of tree.rootNode.children) {
774
+ if (child.type !== "script_element") {
775
+ continue;
776
+ }
777
+ let scriptLang = "javascript";
778
+ let startTag = null;
779
+ let rawTextNode = null;
780
+ for (const sub of child.children) {
781
+ if (sub.type === "start_tag") {
782
+ startTag = sub;
783
+ } else if (sub.type === "raw_text") {
784
+ rawTextNode = sub;
785
+ }
786
+ }
787
+ if (startTag) {
788
+ for (const attr of startTag.children) {
789
+ if (attr.type === "attribute") {
790
+ let attrName = null;
791
+ let attrValue = null;
792
+ for (const a of attr.children) {
793
+ if (a.type === "attribute_name") {
794
+ attrName = a.text;
795
+ } else if (a.type === "quoted_attribute_value") {
796
+ for (const v of a.children) {
797
+ if (v.type === "attribute_value") {
798
+ attrValue = v.text;
799
+ }
800
+ }
801
+ }
802
+ }
803
+ if (attrName === "lang" && (attrValue === "ts" || attrValue === "typescript")) {
804
+ scriptLang = "typescript";
805
+ }
806
+ }
807
+ }
808
+ }
809
+ if (!rawTextNode) {
810
+ continue;
811
+ }
812
+ const scriptSource = Buffer.from(rawTextNode.text, "utf-8");
813
+ const lineOffset = rawTextNode.startPosition.row;
814
+ const scriptParser = this.getParser(scriptLang);
815
+ if (!scriptParser) {
816
+ continue;
817
+ }
818
+ const scriptTree = scriptParser.parse(scriptSource.toString("utf-8"));
819
+ const [importMap, definedNames] = this._collectFileScope(
820
+ scriptTree.rootNode,
821
+ scriptLang,
822
+ scriptSource
823
+ );
824
+ const nodes = [];
825
+ const edges = [];
826
+ this._extractFromTree(
827
+ scriptTree.rootNode,
828
+ scriptSource,
829
+ scriptLang,
830
+ filePath,
831
+ nodes,
832
+ edges,
833
+ void 0,
834
+ void 0,
835
+ importMap,
836
+ definedNames
837
+ );
838
+ for (const n of nodes) {
839
+ n.lineStart += lineOffset;
840
+ n.lineEnd += lineOffset;
841
+ n.language = "vue";
842
+ }
843
+ for (const e of edges) {
844
+ e.line = (e.line ?? 0) + lineOffset;
845
+ }
846
+ allNodes.push(...nodes);
847
+ allEdges.push(...edges);
848
+ }
849
+ if (testFile) {
850
+ const testQNames = /* @__PURE__ */ new Set();
851
+ for (const n of allNodes) {
852
+ if (n.isTest) {
853
+ testQNames.add(this._qualify(n.name, filePath, n.parentName ?? null));
854
+ }
855
+ }
856
+ const testedBy = [];
857
+ for (const edge of allEdges) {
858
+ if (edge.kind === "CALLS" && testQNames.has(edge.source)) {
859
+ testedBy.push({
860
+ kind: "TESTED_BY",
861
+ source: edge.target,
862
+ target: edge.source,
863
+ filePath: edge.filePath,
864
+ line: edge.line
865
+ });
866
+ }
867
+ }
868
+ allEdges.push(...testedBy);
869
+ }
870
+ return [allNodes, allEdges];
871
+ }
872
+ _resolveCallTargets(nodes, edges, filePath) {
873
+ const symbols = /* @__PURE__ */ new Map();
874
+ for (const node of nodes) {
875
+ if (["Function", "Class", "Type", "Test"].includes(node.kind)) {
876
+ const bare = node.name;
877
+ if (!symbols.has(bare)) {
878
+ symbols.set(bare, this._qualify(bare, filePath, node.parentName ?? null));
879
+ }
880
+ }
881
+ }
882
+ return edges.map((edge) => {
883
+ if (edge.kind === "CALLS" && !edge.target.includes("::")) {
884
+ const qualified = symbols.get(edge.target);
885
+ if (qualified) {
886
+ return { ...edge, target: qualified };
887
+ }
888
+ }
889
+ return edge;
890
+ });
891
+ }
892
+ _extractFromTree(root, source, language, filePath, nodes, edges, enclosingClass, enclosingFunc, importMap, definedNames, depth = 0) {
893
+ if (depth > MAX_AST_DEPTH) {
894
+ return;
895
+ }
896
+ const classTypes = new Set(CLASS_TYPES[language] ?? []);
897
+ const funcTypes = new Set(FUNCTION_TYPES[language] ?? []);
898
+ const importTypes = new Set(IMPORT_TYPES[language] ?? []);
899
+ const callTypes = new Set(CALL_TYPES[language] ?? []);
900
+ for (const child of root.children) {
901
+ const nodeType = child.type;
902
+ if (classTypes.has(nodeType)) {
903
+ const name = this._getName(child, language, "class");
904
+ if (name) {
905
+ nodes.push({
906
+ kind: "Class",
907
+ name,
908
+ filePath,
909
+ lineStart: child.startPosition.row + 1,
910
+ lineEnd: child.endPosition.row + 1,
911
+ language,
912
+ parentName: enclosingClass ?? null
913
+ });
914
+ edges.push({
915
+ kind: "CONTAINS",
916
+ source: filePath,
917
+ target: this._qualify(name, filePath, enclosingClass ?? null),
918
+ filePath,
919
+ line: child.startPosition.row + 1
920
+ });
921
+ const bases = this._getBases(child, language);
922
+ for (const base of bases) {
923
+ edges.push({
924
+ kind: "INHERITS",
925
+ source: this._qualify(name, filePath, enclosingClass ?? null),
926
+ target: base,
927
+ filePath,
928
+ line: child.startPosition.row + 1
929
+ });
930
+ }
931
+ this._extractFromTree(
932
+ child,
933
+ source,
934
+ language,
935
+ filePath,
936
+ nodes,
937
+ edges,
938
+ name,
939
+ null,
940
+ importMap,
941
+ definedNames,
942
+ depth + 1
943
+ );
944
+ continue;
945
+ }
946
+ }
947
+ if (funcTypes.has(nodeType)) {
948
+ const name = this._getName(child, language, "function");
949
+ if (name) {
950
+ const isTest = isTestFunction(name, filePath);
951
+ const kind = isTest ? "Test" : "Function";
952
+ const qualified = this._qualify(name, filePath, enclosingClass ?? null);
953
+ const params = this._getParams(child, language);
954
+ const retType = this._getReturnType(child, language);
955
+ nodes.push({
956
+ kind,
957
+ name,
958
+ filePath,
959
+ lineStart: child.startPosition.row + 1,
960
+ lineEnd: child.endPosition.row + 1,
961
+ language,
962
+ parentName: enclosingClass ?? null,
963
+ params,
964
+ returnType: retType,
965
+ isTest
966
+ });
967
+ const container = enclosingClass ? this._qualify(enclosingClass, filePath, null) : filePath;
968
+ edges.push({
969
+ kind: "CONTAINS",
970
+ source: container,
971
+ target: qualified,
972
+ filePath,
973
+ line: child.startPosition.row + 1
974
+ });
975
+ if (language === "solidity") {
976
+ for (const sub of child.children) {
977
+ if (sub.type === "modifier_invocation") {
978
+ for (const ident of sub.children) {
979
+ if (ident.type === "identifier") {
980
+ edges.push({
981
+ kind: "CALLS",
982
+ source: qualified,
983
+ target: ident.text,
984
+ filePath,
985
+ line: sub.startPosition.row + 1
986
+ });
987
+ break;
988
+ }
989
+ }
990
+ }
991
+ }
992
+ }
993
+ this._extractFromTree(
994
+ child,
995
+ source,
996
+ language,
997
+ filePath,
998
+ nodes,
999
+ edges,
1000
+ enclosingClass,
1001
+ name,
1002
+ importMap,
1003
+ definedNames,
1004
+ depth + 1
1005
+ );
1006
+ continue;
1007
+ }
1008
+ }
1009
+ if (importTypes.has(nodeType)) {
1010
+ const imports = this._extractImport(child, language);
1011
+ for (const impTarget of imports) {
1012
+ edges.push({
1013
+ kind: "IMPORTS_FROM",
1014
+ source: filePath,
1015
+ target: impTarget,
1016
+ filePath,
1017
+ line: child.startPosition.row + 1
1018
+ });
1019
+ }
1020
+ continue;
1021
+ }
1022
+ if (callTypes.has(nodeType)) {
1023
+ const callName = this._getCallName(child, language);
1024
+ if (callName && enclosingFunc) {
1025
+ const caller = this._qualify(enclosingFunc, filePath, enclosingClass ?? null);
1026
+ const target = this._resolveCallTarget(
1027
+ callName,
1028
+ filePath,
1029
+ language,
1030
+ importMap ?? /* @__PURE__ */ new Map(),
1031
+ definedNames ?? /* @__PURE__ */ new Set()
1032
+ );
1033
+ edges.push({
1034
+ kind: "CALLS",
1035
+ source: caller,
1036
+ target,
1037
+ filePath,
1038
+ line: child.startPosition.row + 1
1039
+ });
1040
+ }
1041
+ }
1042
+ if (language === "solidity") {
1043
+ if (nodeType === "emit_statement" && enclosingFunc) {
1044
+ for (const sub of child.children) {
1045
+ if (sub.type === "expression") {
1046
+ for (const ident of sub.children) {
1047
+ if (ident.type === "identifier") {
1048
+ const caller = this._qualify(
1049
+ enclosingFunc,
1050
+ filePath,
1051
+ enclosingClass ?? null
1052
+ );
1053
+ edges.push({
1054
+ kind: "CALLS",
1055
+ source: caller,
1056
+ target: ident.text,
1057
+ filePath,
1058
+ line: child.startPosition.row + 1
1059
+ });
1060
+ }
1061
+ }
1062
+ }
1063
+ }
1064
+ }
1065
+ if (nodeType === "state_variable_declaration" && enclosingClass) {
1066
+ let varName = null;
1067
+ let varVisibility = null;
1068
+ let varType = null;
1069
+ let varMutability = null;
1070
+ for (const sub of child.children) {
1071
+ if (sub.type === "identifier") {
1072
+ varName = sub.text;
1073
+ } else if (sub.type === "visibility") {
1074
+ varVisibility = sub.text;
1075
+ } else if (sub.type === "type_name") {
1076
+ varType = sub.text;
1077
+ } else if (sub.type === "constant" || sub.type === "immutable") {
1078
+ varMutability = sub.type;
1079
+ }
1080
+ }
1081
+ if (varName) {
1082
+ const qualified = this._qualify(varName, filePath, enclosingClass);
1083
+ nodes.push({
1084
+ kind: "Function",
1085
+ name: varName,
1086
+ filePath,
1087
+ lineStart: child.startPosition.row + 1,
1088
+ lineEnd: child.endPosition.row + 1,
1089
+ language,
1090
+ parentName: enclosingClass,
1091
+ returnType: varType,
1092
+ modifiers: varVisibility,
1093
+ extra: { solidity_kind: "state_variable", mutability: varMutability }
1094
+ });
1095
+ edges.push({
1096
+ kind: "CONTAINS",
1097
+ source: this._qualify(enclosingClass, filePath, null),
1098
+ target: qualified,
1099
+ filePath,
1100
+ line: child.startPosition.row + 1
1101
+ });
1102
+ continue;
1103
+ }
1104
+ }
1105
+ if (nodeType === "constant_variable_declaration") {
1106
+ let varName = null;
1107
+ let varType = null;
1108
+ for (const sub of child.children) {
1109
+ if (sub.type === "identifier") {
1110
+ varName = sub.text;
1111
+ } else if (sub.type === "type_name") {
1112
+ varType = sub.text;
1113
+ }
1114
+ }
1115
+ if (varName) {
1116
+ const qualified = this._qualify(varName, filePath, enclosingClass ?? null);
1117
+ nodes.push({
1118
+ kind: "Function",
1119
+ name: varName,
1120
+ filePath,
1121
+ lineStart: child.startPosition.row + 1,
1122
+ lineEnd: child.endPosition.row + 1,
1123
+ language,
1124
+ parentName: enclosingClass ?? null,
1125
+ returnType: varType,
1126
+ extra: { solidity_kind: "constant" }
1127
+ });
1128
+ const container = enclosingClass ? this._qualify(enclosingClass, filePath, null) : filePath;
1129
+ edges.push({
1130
+ kind: "CONTAINS",
1131
+ source: container,
1132
+ target: qualified,
1133
+ filePath,
1134
+ line: child.startPosition.row + 1
1135
+ });
1136
+ continue;
1137
+ }
1138
+ }
1139
+ if (nodeType === "using_directive") {
1140
+ let libName = null;
1141
+ for (const sub of child.children) {
1142
+ if (sub.type === "type_alias") {
1143
+ for (const ident of sub.children) {
1144
+ if (ident.type === "identifier") {
1145
+ libName = ident.text;
1146
+ break;
1147
+ }
1148
+ }
1149
+ }
1150
+ }
1151
+ if (libName) {
1152
+ const sourceName = enclosingClass ? this._qualify(enclosingClass, filePath, null) : filePath;
1153
+ edges.push({
1154
+ kind: "DEPENDS_ON",
1155
+ source: sourceName,
1156
+ target: libName,
1157
+ filePath,
1158
+ line: child.startPosition.row + 1
1159
+ });
1160
+ }
1161
+ continue;
1162
+ }
1163
+ }
1164
+ this._extractFromTree(
1165
+ child,
1166
+ source,
1167
+ language,
1168
+ filePath,
1169
+ nodes,
1170
+ edges,
1171
+ enclosingClass,
1172
+ enclosingFunc,
1173
+ importMap,
1174
+ definedNames,
1175
+ depth + 1
1176
+ );
1177
+ }
1178
+ }
1179
+ _collectFileScope(root, language, source) {
1180
+ const importMap = /* @__PURE__ */ new Map();
1181
+ const definedNames = /* @__PURE__ */ new Set();
1182
+ const classTypes = new Set(CLASS_TYPES[language] ?? []);
1183
+ const funcTypes = new Set(FUNCTION_TYPES[language] ?? []);
1184
+ const importTypes = new Set(IMPORT_TYPES[language] ?? []);
1185
+ const decoratorWrappers = /* @__PURE__ */ new Set(["decorated_definition", "decorator"]);
1186
+ for (const child of root.children) {
1187
+ const nodeType = child.type;
1188
+ let target = child;
1189
+ if (decoratorWrappers.has(nodeType)) {
1190
+ for (const inner of child.children) {
1191
+ if (funcTypes.has(inner.type) || classTypes.has(inner.type)) {
1192
+ target = inner;
1193
+ break;
1194
+ }
1195
+ }
1196
+ }
1197
+ const targetType = target.type;
1198
+ if (funcTypes.has(targetType) || classTypes.has(targetType)) {
1199
+ const name = this._getName(
1200
+ target,
1201
+ language,
1202
+ classTypes.has(targetType) ? "class" : "function"
1203
+ );
1204
+ if (name) {
1205
+ definedNames.add(name);
1206
+ }
1207
+ }
1208
+ if (importTypes.has(nodeType)) {
1209
+ this._collectImportNames(child, language, source, importMap);
1210
+ }
1211
+ }
1212
+ return [importMap, definedNames];
1213
+ }
1214
+ _collectImportNames(node, language, _source, importMap) {
1215
+ if (language === "python") {
1216
+ if (node.type === "import_from_statement") {
1217
+ let module = null;
1218
+ let seenImport = false;
1219
+ for (const child of node.children) {
1220
+ if (child.type === "dotted_name" && !seenImport) {
1221
+ module = child.text;
1222
+ } else if (child.type === "import") {
1223
+ seenImport = true;
1224
+ } else if (seenImport && module) {
1225
+ if (child.type === "identifier" || child.type === "dotted_name") {
1226
+ importMap.set(child.text, module);
1227
+ } else if (child.type === "aliased_import") {
1228
+ const names = child.children.filter(
1229
+ (c) => c.type === "identifier" || c.type === "dotted_name"
1230
+ ).map((c) => c.text);
1231
+ if (names.length > 0) {
1232
+ importMap.set(names[names.length - 1], module);
1233
+ }
1234
+ }
1235
+ }
1236
+ }
1237
+ }
1238
+ } else if (language === "javascript" || language === "typescript" || language === "tsx") {
1239
+ let module = null;
1240
+ for (const child of node.children) {
1241
+ if (child.type === "string") {
1242
+ module = child.text.replace(/^['"]|['"]$/g, "");
1243
+ }
1244
+ }
1245
+ if (module) {
1246
+ for (const child of node.children) {
1247
+ if (child.type === "import_clause") {
1248
+ this._collectJsImportNames(child, module, importMap);
1249
+ }
1250
+ }
1251
+ }
1252
+ }
1253
+ }
1254
+ _collectJsImportNames(clauseNode, module, importMap) {
1255
+ for (const child of clauseNode.children) {
1256
+ if (child.type === "identifier") {
1257
+ importMap.set(child.text, module);
1258
+ } else if (child.type === "named_imports") {
1259
+ for (const spec of child.children) {
1260
+ if (spec.type === "import_specifier") {
1261
+ const names = spec.children.filter(
1262
+ (s) => s.type === "identifier" || s.type === "property_identifier"
1263
+ ).map((s) => s.text);
1264
+ if (names.length > 0) {
1265
+ importMap.set(names[names.length - 1], module);
1266
+ }
1267
+ }
1268
+ }
1269
+ }
1270
+ }
1271
+ }
1272
+ _resolveModuleToFile(module, filePath, language) {
1273
+ const callerDir = path2.dirname(filePath);
1274
+ const cacheKey = `${language}:${callerDir}:${module}`;
1275
+ if (this.moduleFileCache.has(cacheKey)) {
1276
+ return this.moduleFileCache.get(cacheKey) ?? null;
1277
+ }
1278
+ const resolved = this._doResolveModule(module, filePath, language);
1279
+ if (this.moduleFileCache.size >= MODULE_CACHE_MAX) {
1280
+ this.moduleFileCache.clear();
1281
+ }
1282
+ this.moduleFileCache.set(cacheKey, resolved);
1283
+ return resolved;
1284
+ }
1285
+ _doResolveModule(module, filePath, language) {
1286
+ const callerDir = path2.dirname(filePath);
1287
+ if (language === "python") {
1288
+ const relPath = module.replace(/\./g, "/");
1289
+ const candidates = [`${relPath}.py`, `${relPath}/__init__.py`];
1290
+ let current = callerDir;
1291
+ while (true) {
1292
+ for (const candidate of candidates) {
1293
+ const target = path2.join(current, candidate);
1294
+ if (fs2.existsSync(target)) {
1295
+ return path2.resolve(target);
1296
+ }
1297
+ }
1298
+ const parent = path2.dirname(current);
1299
+ if (parent === current) {
1300
+ break;
1301
+ }
1302
+ current = parent;
1303
+ }
1304
+ } else if (language === "javascript" || language === "typescript" || language === "tsx" || language === "vue") {
1305
+ if (module.startsWith(".")) {
1306
+ const base = path2.join(callerDir, module);
1307
+ const extensions = [".ts", ".tsx", ".js", ".jsx", ".vue"];
1308
+ if (fs2.existsSync(base) && fs2.statSync(base).isFile()) {
1309
+ return path2.resolve(base);
1310
+ }
1311
+ for (const ext of extensions) {
1312
+ const target = base + ext;
1313
+ if (fs2.existsSync(target)) {
1314
+ return path2.resolve(target);
1315
+ }
1316
+ }
1317
+ if (fs2.existsSync(base) && fs2.statSync(base).isDirectory()) {
1318
+ for (const ext of extensions) {
1319
+ const target = path2.join(base, `index${ext}`);
1320
+ if (fs2.existsSync(target)) {
1321
+ return path2.resolve(target);
1322
+ }
1323
+ }
1324
+ }
1325
+ }
1326
+ }
1327
+ return null;
1328
+ }
1329
+ _resolveCallTarget(callName, filePath, language, importMap, definedNames) {
1330
+ if (definedNames.has(callName)) {
1331
+ return this._qualify(callName, filePath, null);
1332
+ }
1333
+ const importedFrom = importMap.get(callName);
1334
+ if (importedFrom) {
1335
+ const resolved = this._resolveModuleToFile(importedFrom, filePath, language);
1336
+ if (resolved) {
1337
+ return this._qualify(callName, resolved, null);
1338
+ }
1339
+ }
1340
+ return callName;
1341
+ }
1342
+ _qualify(name, filePath, enclosingClass) {
1343
+ if (enclosingClass) {
1344
+ return `${filePath}::${enclosingClass}.${name}`;
1345
+ }
1346
+ return `${filePath}::${name}`;
1347
+ }
1348
+ _getName(node, language, kind) {
1349
+ if (language === "solidity") {
1350
+ if (node.type === "constructor_definition") {
1351
+ return "constructor";
1352
+ }
1353
+ if (node.type === "fallback_receive_definition") {
1354
+ for (const child of node.children) {
1355
+ if (child.type === "receive" || child.type === "fallback") {
1356
+ return child.text;
1357
+ }
1358
+ }
1359
+ }
1360
+ }
1361
+ if ((language === "c" || language === "cpp") && kind === "function") {
1362
+ for (const child of node.children) {
1363
+ if (child.type === "function_declarator" || child.type === "pointer_declarator") {
1364
+ const result = this._getName(child, language, kind);
1365
+ if (result) {
1366
+ return result;
1367
+ }
1368
+ }
1369
+ }
1370
+ }
1371
+ for (const child of node.children) {
1372
+ if ([
1373
+ "identifier",
1374
+ "name",
1375
+ "type_identifier",
1376
+ "property_identifier",
1377
+ "simple_identifier",
1378
+ "constant"
1379
+ ].includes(child.type)) {
1380
+ return child.text;
1381
+ }
1382
+ }
1383
+ if (language === "go" && node.type === "type_declaration") {
1384
+ for (const child of node.children) {
1385
+ if (child.type === "type_spec") {
1386
+ return this._getName(child, language, kind);
1387
+ }
1388
+ }
1389
+ }
1390
+ return null;
1391
+ }
1392
+ _getParams(node, language) {
1393
+ for (const child of node.children) {
1394
+ if (["parameters", "formal_parameters", "parameter_list"].includes(child.type)) {
1395
+ return child.text;
1396
+ }
1397
+ }
1398
+ if (language === "solidity") {
1399
+ const params = node.children.filter((c) => c.type === "parameter").map((c) => c.text);
1400
+ if (params.length > 0) {
1401
+ return `(${params.join(", ")})`;
1402
+ }
1403
+ }
1404
+ return null;
1405
+ }
1406
+ _getReturnType(node, language) {
1407
+ for (const child of node.children) {
1408
+ if ([
1409
+ "type",
1410
+ "return_type",
1411
+ "type_annotation",
1412
+ "return_type_definition"
1413
+ ].includes(child.type)) {
1414
+ return child.text;
1415
+ }
1416
+ }
1417
+ if (language === "python") {
1418
+ for (let i = 0; i < node.children.length - 1; i++) {
1419
+ if (node.children[i].type === "->") {
1420
+ return node.children[i + 1].text;
1421
+ }
1422
+ }
1423
+ }
1424
+ return null;
1425
+ }
1426
+ _getBases(node, language) {
1427
+ const bases = [];
1428
+ if (language === "python") {
1429
+ for (const child of node.children) {
1430
+ if (child.type === "argument_list") {
1431
+ for (const arg of child.children) {
1432
+ if (arg.type === "identifier" || arg.type === "attribute") {
1433
+ bases.push(arg.text);
1434
+ }
1435
+ }
1436
+ }
1437
+ }
1438
+ } else if (language === "java" || language === "csharp" || language === "kotlin") {
1439
+ for (const child of node.children) {
1440
+ if ([
1441
+ "superclass",
1442
+ "super_interfaces",
1443
+ "extends_type",
1444
+ "implements_type",
1445
+ "type_identifier",
1446
+ "supertype",
1447
+ "delegation_specifier"
1448
+ ].includes(child.type)) {
1449
+ bases.push(child.text);
1450
+ }
1451
+ }
1452
+ } else if (language === "cpp") {
1453
+ for (const child of node.children) {
1454
+ if (child.type === "base_class_clause") {
1455
+ for (const sub of child.children) {
1456
+ if (sub.type === "type_identifier") {
1457
+ bases.push(sub.text);
1458
+ }
1459
+ }
1460
+ }
1461
+ }
1462
+ } else if (language === "typescript" || language === "javascript" || language === "tsx") {
1463
+ for (const child of node.children) {
1464
+ if (child.type === "extends_clause" || child.type === "implements_clause") {
1465
+ for (const sub of child.children) {
1466
+ if ([
1467
+ "identifier",
1468
+ "type_identifier",
1469
+ "nested_identifier"
1470
+ ].includes(sub.type)) {
1471
+ bases.push(sub.text);
1472
+ }
1473
+ }
1474
+ }
1475
+ }
1476
+ } else if (language === "solidity") {
1477
+ for (const child of node.children) {
1478
+ if (child.type === "inheritance_specifier") {
1479
+ for (const sub of child.children) {
1480
+ if (sub.type === "user_defined_type") {
1481
+ for (const ident of sub.children) {
1482
+ if (ident.type === "identifier") {
1483
+ bases.push(ident.text);
1484
+ }
1485
+ }
1486
+ }
1487
+ }
1488
+ }
1489
+ }
1490
+ } else if (language === "go") {
1491
+ for (const child of node.children) {
1492
+ if (child.type === "type_spec") {
1493
+ for (const sub of child.children) {
1494
+ if (sub.type === "struct_type" || sub.type === "interface_type") {
1495
+ for (const fieldNode of sub.children) {
1496
+ if (fieldNode.type === "field_declaration_list") {
1497
+ for (const f of fieldNode.children) {
1498
+ if (f.type === "type_identifier") {
1499
+ bases.push(f.text);
1500
+ }
1501
+ }
1502
+ }
1503
+ }
1504
+ }
1505
+ }
1506
+ }
1507
+ }
1508
+ }
1509
+ return bases;
1510
+ }
1511
+ _extractImport(node, language) {
1512
+ const imports = [];
1513
+ const text = node.text.trim();
1514
+ if (language === "python") {
1515
+ if (node.type === "import_from_statement") {
1516
+ for (const child of node.children) {
1517
+ if (child.type === "dotted_name") {
1518
+ imports.push(child.text);
1519
+ break;
1520
+ }
1521
+ }
1522
+ } else {
1523
+ for (const child of node.children) {
1524
+ if (child.type === "dotted_name") {
1525
+ imports.push(child.text);
1526
+ }
1527
+ }
1528
+ }
1529
+ } else if (language === "javascript" || language === "typescript" || language === "tsx") {
1530
+ for (const child of node.children) {
1531
+ if (child.type === "string") {
1532
+ imports.push(child.text.replace(/^['"]|['"]$/g, ""));
1533
+ }
1534
+ }
1535
+ } else if (language === "go") {
1536
+ for (const child of node.children) {
1537
+ if (child.type === "import_spec_list") {
1538
+ for (const spec of child.children) {
1539
+ if (spec.type === "import_spec") {
1540
+ for (const s of spec.children) {
1541
+ if (s.type === "interpreted_string_literal") {
1542
+ imports.push(s.text.replace(/^"|"$/g, ""));
1543
+ }
1544
+ }
1545
+ }
1546
+ }
1547
+ } else if (child.type === "import_spec") {
1548
+ for (const s of child.children) {
1549
+ if (s.type === "interpreted_string_literal") {
1550
+ imports.push(s.text.replace(/^"|"$/g, ""));
1551
+ }
1552
+ }
1553
+ }
1554
+ }
1555
+ } else if (language === "rust") {
1556
+ imports.push(text.replace(/^use\s+/, "").replace(/;$/, "").trim());
1557
+ } else if (language === "c" || language === "cpp") {
1558
+ for (const child of node.children) {
1559
+ if (child.type === "system_lib_string" || child.type === "string_literal") {
1560
+ imports.push(child.text.replace(/^[<""]|[>""]$/g, ""));
1561
+ }
1562
+ }
1563
+ } else if (language === "java" || language === "csharp") {
1564
+ const parts = text.split(/\s+/);
1565
+ if (parts.length >= 2) {
1566
+ imports.push(parts[parts.length - 1].replace(/;$/, ""));
1567
+ }
1568
+ } else if (language === "solidity") {
1569
+ for (const child of node.children) {
1570
+ if (child.type === "string") {
1571
+ const val = child.text.replace(/^"|"$/g, "");
1572
+ if (val) {
1573
+ imports.push(val);
1574
+ }
1575
+ }
1576
+ }
1577
+ } else if (language === "ruby") {
1578
+ if (text.includes("require")) {
1579
+ const match = /['"]([^'"]+)['"]/u.exec(text);
1580
+ if (match) {
1581
+ imports.push(match[1]);
1582
+ }
1583
+ }
1584
+ } else {
1585
+ imports.push(text);
1586
+ }
1587
+ return imports;
1588
+ }
1589
+ _getCallName(node, language) {
1590
+ if (!node.children || node.children.length === 0) {
1591
+ return null;
1592
+ }
1593
+ let first = node.children[0];
1594
+ if (language === "solidity" && first.type === "expression" && first.children.length > 0) {
1595
+ first = first.children[0];
1596
+ }
1597
+ if (first.type === "identifier") {
1598
+ return first.text;
1599
+ }
1600
+ const memberTypes = [
1601
+ "attribute",
1602
+ "member_expression",
1603
+ "field_expression",
1604
+ "selector_expression"
1605
+ ];
1606
+ if (memberTypes.includes(first.type)) {
1607
+ for (let i = first.children.length - 1; i >= 0; i--) {
1608
+ const child = first.children[i];
1609
+ if ([
1610
+ "identifier",
1611
+ "property_identifier",
1612
+ "field_identifier",
1613
+ "field_name"
1614
+ ].includes(child.type)) {
1615
+ return child.text;
1616
+ }
1617
+ }
1618
+ return first.text;
1619
+ }
1620
+ if (first.type === "scoped_identifier" || first.type === "qualified_name") {
1621
+ return first.text;
1622
+ }
1623
+ return null;
1624
+ }
1625
+ };
1626
+
1627
+ // src/infrastructure/SqliteEmbeddingStore.ts
1628
+ import crypto2 from "crypto";
1629
+ import Database2 from "better-sqlite3";
1630
+
1631
+ // src/infrastructure/LocalEmbeddingProvider.ts
1632
+ var NOMIC_MODEL = "Xenova/nomic-embed-text-v1.5";
1633
+ var MINILM_MODEL = "Xenova/all-MiniLM-L6-v2";
1634
+ var LocalEmbeddingProvider = class {
1635
+ _pipelinePromise = null;
1636
+ _model;
1637
+ _dim;
1638
+ constructor() {
1639
+ const hasToken = !!(process.env["HF_TOKEN"] ?? process.env["CODEORBIT_HF_TOKEN"]);
1640
+ this._model = hasToken ? NOMIC_MODEL : MINILM_MODEL;
1641
+ this._dim = hasToken ? 768 : 384;
1642
+ }
1643
+ _getPipeline() {
1644
+ if (!this._pipelinePromise) {
1645
+ const model = this._model;
1646
+ this._pipelinePromise = import("@huggingface/transformers").then((mod) => {
1647
+ const { pipeline, env } = mod;
1648
+ const hfToken = process.env["HF_TOKEN"] ?? process.env["CODEORBIT_HF_TOKEN"];
1649
+ if (hfToken) env["token"] = hfToken;
1650
+ return pipeline("feature-extraction", model);
1651
+ });
1652
+ }
1653
+ return this._pipelinePromise;
1654
+ }
1655
+ async embed(texts) {
1656
+ const pipe = await this._getPipeline();
1657
+ const inputs = this._model === NOMIC_MODEL ? texts.map((t) => `search_document: ${t}`) : texts;
1658
+ const output = await pipe(inputs, { pooling: "mean", normalize: true });
1659
+ const dim = this._dim;
1660
+ return Array.from(
1661
+ { length: texts.length },
1662
+ (_, i) => Array.from(output.data.subarray(i * dim, (i + 1) * dim))
1663
+ );
1664
+ }
1665
+ async embedQuery(text) {
1666
+ const pipe = await this._getPipeline();
1667
+ const input = this._model === NOMIC_MODEL ? `search_query: ${text}` : text;
1668
+ const output = await pipe([input], { pooling: "mean", normalize: true });
1669
+ return Array.from(output.data);
1670
+ }
1671
+ get dimension() {
1672
+ return this._dim;
1673
+ }
1674
+ get name() {
1675
+ return `local:${this._model.split("/")[1]}`;
1676
+ }
1677
+ };
1678
+
1679
+ // src/infrastructure/GoogleEmbeddingProvider.ts
1680
+ import { createRequire as createRequire2 } from "module";
1681
+ var _require2 = createRequire2(import.meta.url);
1682
+ var GoogleEmbeddingProvider = class {
1683
+ _model;
1684
+ _dimension = null;
1685
+ modelName;
1686
+ constructor(apiKey, model = "gemini-embedding-001") {
1687
+ this.modelName = model;
1688
+ const { GoogleGenerativeAI } = _require2("@google/generative-ai");
1689
+ const genAI = new GoogleGenerativeAI(apiKey);
1690
+ this._model = genAI.getGenerativeModel({ model });
1691
+ }
1692
+ async _withRetry(fn, maxRetries = 3) {
1693
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
1694
+ try {
1695
+ return await fn();
1696
+ } catch (e) {
1697
+ const msg = String(e);
1698
+ const retryable = msg.includes("429") || msg.includes("500") || msg.includes("503");
1699
+ if (!retryable || attempt === maxRetries - 1) throw e;
1700
+ await new Promise((r) => setTimeout(r, 2 ** attempt * 1e3));
1701
+ }
1702
+ }
1703
+ throw new Error("unreachable");
1704
+ }
1705
+ async embed(texts) {
1706
+ const batchSize = 100;
1707
+ const results = [];
1708
+ for (let i = 0; i < texts.length; i += batchSize) {
1709
+ const batch = texts.slice(i, i + batchSize);
1710
+ const response = await this._withRetry(
1711
+ () => this._model.batchEmbedContents({
1712
+ requests: batch.map((t) => ({
1713
+ content: { parts: [{ text: t }], role: "user" },
1714
+ taskType: "RETRIEVAL_DOCUMENT"
1715
+ }))
1716
+ })
1717
+ );
1718
+ results.push(...response.embeddings.map((e) => e.values));
1719
+ }
1720
+ if (this._dimension === null && results.length > 0) {
1721
+ this._dimension = results[0].length;
1722
+ }
1723
+ return results;
1724
+ }
1725
+ async embedQuery(text) {
1726
+ const response = await this._withRetry(
1727
+ () => this._model.embedContent({
1728
+ content: { parts: [{ text }], role: "user" },
1729
+ taskType: "RETRIEVAL_QUERY"
1730
+ })
1731
+ );
1732
+ const vec = response.embedding.values;
1733
+ if (this._dimension === null) this._dimension = vec.length;
1734
+ return vec;
1735
+ }
1736
+ get dimension() {
1737
+ return this._dimension ?? 768;
1738
+ }
1739
+ get name() {
1740
+ return `google:${this.modelName}`;
1741
+ }
1742
+ };
1743
+
1744
+ // src/infrastructure/SqliteEmbeddingStore.ts
1745
+ var EMBEDDINGS_SCHEMA = `
1746
+ CREATE TABLE IF NOT EXISTS embeddings (
1747
+ qualified_name TEXT PRIMARY KEY,
1748
+ vector BLOB NOT NULL,
1749
+ text_hash TEXT NOT NULL,
1750
+ provider TEXT NOT NULL DEFAULT 'unknown'
1751
+ );
1752
+ `;
1753
+ function encodeVector(vec) {
1754
+ const buf = Buffer.allocUnsafe(vec.length * 4);
1755
+ for (let i = 0; i < vec.length; i++) buf.writeFloatLE(vec[i], i * 4);
1756
+ return buf;
1757
+ }
1758
+ function decodeVector(blob) {
1759
+ const n = blob.length / 4;
1760
+ const result = new Array(n);
1761
+ for (let i = 0; i < n; i++) result[i] = blob.readFloatLE(i * 4);
1762
+ return result;
1763
+ }
1764
+ function cosineSimilarity(a, b) {
1765
+ if (a.length !== b.length) return 0;
1766
+ let dot = 0, normA = 0, normB = 0;
1767
+ for (let i = 0; i < a.length; i++) {
1768
+ dot += a[i] * b[i];
1769
+ normA += a[i] * a[i];
1770
+ normB += b[i] * b[i];
1771
+ }
1772
+ if (normA === 0 || normB === 0) return 0;
1773
+ return dot / (Math.sqrt(normA) * Math.sqrt(normB));
1774
+ }
1775
+ function nodeToText(node) {
1776
+ const parts = [node.name];
1777
+ if (node.kind !== "File") parts.push(node.kind.toLowerCase());
1778
+ if (node.parentName) parts.push(`in ${node.parentName}`);
1779
+ if (node.params) parts.push(node.params);
1780
+ if (node.returnType) parts.push(`returns ${node.returnType}`);
1781
+ if (node.language) parts.push(node.language);
1782
+ return parts.join(" ");
1783
+ }
1784
+ function getProvider(provider) {
1785
+ if (provider === "google") {
1786
+ const apiKey = process.env["GOOGLE_API_KEY"];
1787
+ if (!apiKey) return null;
1788
+ try {
1789
+ return new GoogleEmbeddingProvider(apiKey);
1790
+ } catch {
1791
+ return null;
1792
+ }
1793
+ }
1794
+ return new LocalEmbeddingProvider();
1795
+ }
1796
+ var SqliteEmbeddingStore = class {
1797
+ _db;
1798
+ available;
1799
+ _provider;
1800
+ constructor(dbPath, provider) {
1801
+ this._db = new Database2(dbPath);
1802
+ this._db.exec(EMBEDDINGS_SCHEMA);
1803
+ try {
1804
+ this._db.prepare("SELECT provider FROM embeddings LIMIT 1").get();
1805
+ } catch {
1806
+ this._db.exec(
1807
+ "ALTER TABLE embeddings ADD COLUMN provider TEXT NOT NULL DEFAULT 'unknown'"
1808
+ );
1809
+ }
1810
+ this._provider = getProvider(provider);
1811
+ this.available = this._provider !== null;
1812
+ }
1813
+ count() {
1814
+ const row = this._db.prepare("SELECT COUNT(*) AS cnt FROM embeddings").get();
1815
+ return row.cnt;
1816
+ }
1817
+ async embedNodes(nodes, batchSize = 64) {
1818
+ if (!this._provider) return 0;
1819
+ const providerName = this._provider.name;
1820
+ const toEmbed = [];
1821
+ for (const node of nodes) {
1822
+ if (node.kind === "File") continue;
1823
+ const text = nodeToText(node);
1824
+ const textHash = crypto2.createHash("sha256").update(text).digest("hex");
1825
+ const existing = this._db.prepare("SELECT text_hash, provider FROM embeddings WHERE qualified_name = ?").get(node.qualifiedName);
1826
+ if (existing && existing.text_hash === textHash && existing.provider === providerName) {
1827
+ continue;
1828
+ }
1829
+ toEmbed.push({ node, text, textHash });
1830
+ }
1831
+ if (toEmbed.length === 0) return 0;
1832
+ const insert = this._db.prepare(
1833
+ "INSERT OR REPLACE INTO embeddings (qualified_name, vector, text_hash, provider) VALUES (?, ?, ?, ?)"
1834
+ );
1835
+ for (let i = 0; i < toEmbed.length; i += batchSize) {
1836
+ const batch = toEmbed.slice(i, i + batchSize);
1837
+ const vectors = await this._provider.embed(batch.map((b) => b.text));
1838
+ this._db.transaction(() => {
1839
+ for (let j = 0; j < batch.length; j++) {
1840
+ const { node, textHash } = batch[j];
1841
+ insert.run(node.qualifiedName, encodeVector(vectors[j]), textHash, providerName);
1842
+ }
1843
+ })();
1844
+ }
1845
+ return toEmbed.length;
1846
+ }
1847
+ async search(query, limit = 20) {
1848
+ if (!this._provider) return [];
1849
+ const providerName = this._provider.name;
1850
+ const queryVec = await this._provider.embedQuery(query);
1851
+ const rows = this._db.prepare("SELECT qualified_name, vector FROM embeddings WHERE provider = ?").all(providerName);
1852
+ const scored = rows.map((row) => ({
1853
+ qualifiedName: row.qualified_name,
1854
+ score: cosineSimilarity(queryVec, decodeVector(row.vector))
1855
+ }));
1856
+ scored.sort((a, b) => b.score - a.score);
1857
+ return scored.slice(0, limit);
1858
+ }
1859
+ removeNode(qualifiedName) {
1860
+ this._db.prepare("DELETE FROM embeddings WHERE qualified_name = ?").run(qualifiedName);
1861
+ }
1862
+ close() {
1863
+ this._db.close();
1864
+ }
1865
+ };
1866
+
1867
+ // src/infrastructure/FileSystemHelper.ts
1868
+ import fs3 from "fs";
1869
+ import path3 from "path";
1870
+ import micromatch from "micromatch";
1871
+
1872
+ // src/infrastructure/GitRunner.ts
1873
+ import { spawnSync } from "child_process";
1874
+ var GIT_TIMEOUT_MS = Number(process.env["CRG_GIT_TIMEOUT"] ?? 30) * 1e3;
1875
+ function gitRun(args, cwd) {
1876
+ const result = spawnSync("git", args, {
1877
+ cwd,
1878
+ encoding: "utf-8",
1879
+ timeout: GIT_TIMEOUT_MS,
1880
+ stdio: ["ignore", "pipe", "ignore"]
1881
+ });
1882
+ if (result.error || result.status !== 0) {
1883
+ return "";
1884
+ }
1885
+ return result.stdout ?? "";
1886
+ }
1887
+ function getChangedFiles(repoRoot, base = "HEAD~1") {
1888
+ let output = gitRun(["diff", "--name-only", base], repoRoot);
1889
+ if (!output.trim()) {
1890
+ output = gitRun(["diff", "--name-only", "--cached"], repoRoot);
1891
+ }
1892
+ return output.split("\n").map((f) => f.trim()).filter(Boolean);
1893
+ }
1894
+ function getStagedAndUnstaged(repoRoot) {
1895
+ const output = gitRun(["status", "--porcelain"], repoRoot);
1896
+ const files = [];
1897
+ for (const line of output.split("\n")) {
1898
+ if (line.length > 3) {
1899
+ let entry = line.slice(3).trim();
1900
+ if (entry.includes(" -> ")) {
1901
+ entry = entry.split(" -> ")[1];
1902
+ }
1903
+ files.push(entry);
1904
+ }
1905
+ }
1906
+ return files;
1907
+ }
1908
+ function getAllTrackedFiles(repoRoot) {
1909
+ const output = gitRun(["ls-files"], repoRoot);
1910
+ return output.split("\n").map((f) => f.trim()).filter(Boolean);
1911
+ }
1912
+
1913
+ // src/infrastructure/FileSystemHelper.ts
1914
+ var DEFAULT_IGNORE_PATTERNS = [
1915
+ ".codeorbit/**",
1916
+ "node_modules/**",
1917
+ ".git/**",
1918
+ "__pycache__/**",
1919
+ "*.pyc",
1920
+ ".venv/**",
1921
+ "venv/**",
1922
+ "dist/**",
1923
+ "build/**",
1924
+ ".next/**",
1925
+ "target/**",
1926
+ "*.min.js",
1927
+ "*.min.css",
1928
+ "*.map",
1929
+ "*.lock",
1930
+ "package-lock.json",
1931
+ "yarn.lock",
1932
+ "*.db",
1933
+ "*.sqlite",
1934
+ "*.db-journal",
1935
+ "*.db-wal"
1936
+ ];
1937
+ var PRUNE_DIRS = /* @__PURE__ */ new Set([
1938
+ "node_modules",
1939
+ ".git",
1940
+ "__pycache__",
1941
+ ".next",
1942
+ ".nuxt",
1943
+ ".svelte-kit",
1944
+ "dist",
1945
+ "build",
1946
+ ".venv",
1947
+ "venv",
1948
+ "env",
1949
+ "target",
1950
+ ".mypy_cache",
1951
+ ".pytest_cache",
1952
+ "coverage",
1953
+ ".tox",
1954
+ ".cache",
1955
+ ".tmp",
1956
+ "tmp",
1957
+ "temp",
1958
+ "vendor",
1959
+ "Pods",
1960
+ "DerivedData",
1961
+ ".gradle",
1962
+ ".idea",
1963
+ ".vs"
1964
+ ]);
1965
+ function findRepoRoot(start) {
1966
+ let current = start ?? process.cwd();
1967
+ while (true) {
1968
+ if (fs3.existsSync(path3.join(current, ".git"))) {
1969
+ return current;
1970
+ }
1971
+ const parent = path3.dirname(current);
1972
+ if (parent === current) {
1973
+ break;
1974
+ }
1975
+ current = parent;
1976
+ }
1977
+ return void 0;
1978
+ }
1979
+ function findProjectRoot(start) {
1980
+ return findRepoRoot(start) ?? start ?? process.cwd();
1981
+ }
1982
+ function getDbPath(repoRoot) {
1983
+ const crgDir = path3.join(repoRoot, ".codeorbit");
1984
+ const newDb = path3.join(crgDir, "graph.db");
1985
+ if (!fs3.existsSync(crgDir)) {
1986
+ fs3.mkdirSync(crgDir, { recursive: true });
1987
+ }
1988
+ const innerGitignore = path3.join(crgDir, ".gitignore");
1989
+ if (!fs3.existsSync(innerGitignore)) {
1990
+ fs3.writeFileSync(
1991
+ innerGitignore,
1992
+ "# Auto-generated by codeorbit \u2014 do not commit database files.\n# The graph.db contains absolute paths and code structure metadata.\n*\n"
1993
+ );
1994
+ }
1995
+ const legacyDb = path3.join(repoRoot, ".codeorbit.db");
1996
+ if (fs3.existsSync(legacyDb) && !fs3.existsSync(newDb)) {
1997
+ fs3.renameSync(legacyDb, newDb);
1998
+ }
1999
+ for (const suffix of ["-wal", "-shm", "-journal"]) {
2000
+ const side = legacyDb + suffix;
2001
+ if (fs3.existsSync(side)) {
2002
+ try {
2003
+ fs3.unlinkSync(side);
2004
+ } catch {
2005
+ }
2006
+ }
2007
+ }
2008
+ return newDb;
2009
+ }
2010
+ function loadIgnorePatterns(repoRoot) {
2011
+ const patterns = [...DEFAULT_IGNORE_PATTERNS];
2012
+ const ignoreFile = path3.join(repoRoot, ".codeorbitignore");
2013
+ if (fs3.existsSync(ignoreFile)) {
2014
+ for (const line of fs3.readFileSync(ignoreFile, "utf-8").split("\n")) {
2015
+ const trimmed = line.trim();
2016
+ if (trimmed && !trimmed.startsWith("#")) {
2017
+ patterns.push(trimmed);
2018
+ }
2019
+ }
2020
+ }
2021
+ return patterns;
2022
+ }
2023
+ function shouldIgnore(filePath, patterns) {
2024
+ return micromatch.isMatch(filePath, patterns);
2025
+ }
2026
+ function isBinary(filePath) {
2027
+ try {
2028
+ const chunk = Buffer.alloc(8192);
2029
+ const fd = fs3.openSync(filePath, "r");
2030
+ const bytesRead = fs3.readSync(fd, chunk, 0, 8192, 0);
2031
+ fs3.closeSync(fd);
2032
+ return chunk.slice(0, bytesRead).includes(0);
2033
+ } catch {
2034
+ return true;
2035
+ }
2036
+ }
2037
+ function walkDir(dir, repoRoot) {
2038
+ const files = [];
2039
+ const entries = fs3.readdirSync(dir, { withFileTypes: true });
2040
+ for (const entry of entries) {
2041
+ if (entry.isDirectory()) {
2042
+ if (PRUNE_DIRS.has(entry.name)) {
2043
+ continue;
2044
+ }
2045
+ files.push(...walkDir(path3.join(dir, entry.name), repoRoot));
2046
+ } else if (entry.isFile()) {
2047
+ const rel = path3.relative(repoRoot, path3.join(dir, entry.name));
2048
+ files.push(rel);
2049
+ }
2050
+ }
2051
+ return files;
2052
+ }
2053
+ function collectAllFiles(repoRoot) {
2054
+ const ignorePatterns = loadIgnorePatterns(repoRoot);
2055
+ const parser = new CodeParser();
2056
+ const files = [];
2057
+ const tracked = getAllTrackedFiles(repoRoot);
2058
+ const candidates = tracked.length > 0 ? tracked : walkDir(repoRoot, repoRoot);
2059
+ for (const relPath of candidates) {
2060
+ if (shouldIgnore(relPath, ignorePatterns)) {
2061
+ continue;
2062
+ }
2063
+ const fullPath = path3.join(repoRoot, relPath);
2064
+ let stat;
2065
+ try {
2066
+ stat = fs3.lstatSync(fullPath);
2067
+ } catch {
2068
+ continue;
2069
+ }
2070
+ if (!stat.isFile() || stat.isSymbolicLink()) {
2071
+ continue;
2072
+ }
2073
+ if (!parser.detectLanguage(fullPath)) {
2074
+ continue;
2075
+ }
2076
+ if (isBinary(fullPath)) {
2077
+ continue;
2078
+ }
2079
+ files.push(relPath);
2080
+ }
2081
+ return files;
2082
+ }
2083
+
2084
+ // src/usecases/buildGraph.ts
2085
+ import crypto3 from "crypto";
2086
+ import fs4 from "fs";
2087
+ import path4 from "path";
2088
+ function fullBuild(repoRoot, repo, parser) {
2089
+ const files = collectAllFiles(repoRoot);
2090
+ const existingFiles = new Set(repo.getAllFiles());
2091
+ const currentAbs = new Set(files.map((f) => path4.join(repoRoot, f)));
2092
+ for (const stale of existingFiles) {
2093
+ if (!currentAbs.has(stale)) {
2094
+ repo.removeFileData(stale);
2095
+ }
2096
+ }
2097
+ let totalNodes = 0;
2098
+ let totalEdges = 0;
2099
+ const errors = [];
2100
+ for (let i = 0; i < files.length; i++) {
2101
+ const relPath = files[i];
2102
+ const fullPath = path4.join(repoRoot, relPath);
2103
+ try {
2104
+ const source = fs4.readFileSync(fullPath);
2105
+ const fhash = crypto3.createHash("sha256").update(source).digest("hex");
2106
+ const [nodes, edges] = parser.parseBytes(fullPath, source);
2107
+ repo.storeFileNodesEdges(fullPath, nodes, edges, fhash);
2108
+ totalNodes += nodes.length;
2109
+ totalEdges += edges.length;
2110
+ } catch (err) {
2111
+ errors.push(`${relPath}: ${String(err)}`);
2112
+ }
2113
+ if ((i + 1) % 50 === 0 || i + 1 === files.length) {
2114
+ process.stderr.write(`Progress: ${i + 1}/${files.length} files parsed
2115
+ `);
2116
+ }
2117
+ }
2118
+ repo.setMetadata("last_updated", (/* @__PURE__ */ new Date()).toISOString().replace(/\..+$/, ""));
2119
+ repo.setMetadata("last_build_type", "full");
2120
+ return {
2121
+ buildType: "full",
2122
+ filesUpdated: files.length,
2123
+ totalNodes,
2124
+ totalEdges,
2125
+ changedFiles: files,
2126
+ dependentFiles: [],
2127
+ errors
2128
+ };
2129
+ }
2130
+ function incrementalUpdate(repoRoot, repo, parser, base = "HEAD~1", changedFiles) {
2131
+ const ignorePatterns = loadIgnorePatterns(repoRoot);
2132
+ const changed = changedFiles ?? getChangedFiles(repoRoot, base);
2133
+ if (changed.length === 0) {
2134
+ return {
2135
+ buildType: "incremental",
2136
+ filesUpdated: 0,
2137
+ totalNodes: 0,
2138
+ totalEdges: 0,
2139
+ changedFiles: [],
2140
+ dependentFiles: [],
2141
+ errors: []
2142
+ };
2143
+ }
2144
+ const dependentFiles = /* @__PURE__ */ new Set();
2145
+ for (const relPath of changed) {
2146
+ const fullPath = path4.join(repoRoot, relPath);
2147
+ const deps = findDependents(repo, fullPath);
2148
+ for (const d of deps) {
2149
+ try {
2150
+ dependentFiles.add(path4.relative(repoRoot, d));
2151
+ } catch {
2152
+ dependentFiles.add(d);
2153
+ }
2154
+ }
2155
+ }
2156
+ const allFiles = /* @__PURE__ */ new Set([...changed, ...dependentFiles]);
2157
+ let totalNodes = 0;
2158
+ let totalEdges = 0;
2159
+ const errors = [];
2160
+ for (const relPath of allFiles) {
2161
+ if (shouldIgnore(relPath, ignorePatterns)) {
2162
+ continue;
2163
+ }
2164
+ const absPath = path4.join(repoRoot, relPath);
2165
+ if (!fs4.existsSync(absPath)) {
2166
+ repo.removeFileData(absPath);
2167
+ continue;
2168
+ }
2169
+ if (!parser.detectLanguage(absPath)) {
2170
+ continue;
2171
+ }
2172
+ try {
2173
+ const source = fs4.readFileSync(absPath);
2174
+ const fhash = crypto3.createHash("sha256").update(source).digest("hex");
2175
+ const existingNodes = repo.getNodesByFile(absPath);
2176
+ if (existingNodes.length > 0 && existingNodes[0].fileHash === fhash) {
2177
+ continue;
2178
+ }
2179
+ const [nodes, edges] = parser.parseBytes(absPath, source);
2180
+ repo.storeFileNodesEdges(absPath, nodes, edges, fhash);
2181
+ totalNodes += nodes.length;
2182
+ totalEdges += edges.length;
2183
+ } catch (err) {
2184
+ errors.push(`${relPath}: ${String(err)}`);
2185
+ }
2186
+ }
2187
+ repo.setMetadata("last_updated", (/* @__PURE__ */ new Date()).toISOString().replace(/\..+$/, ""));
2188
+ repo.setMetadata("last_build_type", "incremental");
2189
+ return {
2190
+ buildType: "incremental",
2191
+ filesUpdated: allFiles.size,
2192
+ totalNodes,
2193
+ totalEdges,
2194
+ changedFiles: changed,
2195
+ dependentFiles: [...dependentFiles],
2196
+ errors
2197
+ };
2198
+ }
2199
+ function findDependents(repo, filePath) {
2200
+ const dependents = /* @__PURE__ */ new Set();
2201
+ for (const e of repo.getEdgesByTarget(filePath)) {
2202
+ if (e.kind === "IMPORTS_FROM") {
2203
+ dependents.add(e.filePath);
2204
+ }
2205
+ }
2206
+ for (const node of repo.getNodesByFile(filePath)) {
2207
+ for (const e of repo.getEdgesByTarget(node.qualifiedName)) {
2208
+ if (["CALLS", "IMPORTS_FROM", "INHERITS", "IMPLEMENTS"].includes(e.kind)) {
2209
+ dependents.add(e.filePath);
2210
+ }
2211
+ }
2212
+ }
2213
+ dependents.delete(filePath);
2214
+ return [...dependents];
2215
+ }
2216
+
2217
+ // src/usecases/getImpactRadius.ts
2218
+ function computeImpactRadius(changedFiles, repo, maxDepth = 2, maxNodes = 500) {
2219
+ const adj = repo.getAdjacency();
2220
+ const seeds = /* @__PURE__ */ new Set();
2221
+ for (const f of changedFiles) {
2222
+ for (const node of repo.getNodesByFile(f)) {
2223
+ seeds.add(node.qualifiedName);
2224
+ }
2225
+ }
2226
+ const visited = /* @__PURE__ */ new Set();
2227
+ let frontier = new Set(seeds);
2228
+ const impacted = /* @__PURE__ */ new Set();
2229
+ let depth = 0;
2230
+ while (frontier.size > 0 && depth < maxDepth) {
2231
+ const nextFrontier = /* @__PURE__ */ new Set();
2232
+ for (const qn of frontier) {
2233
+ visited.add(qn);
2234
+ const outNeighbors = adj.outgoing.get(qn);
2235
+ if (outNeighbors) {
2236
+ for (const nb of outNeighbors) {
2237
+ if (!visited.has(nb)) {
2238
+ nextFrontier.add(nb);
2239
+ impacted.add(nb);
2240
+ }
2241
+ }
2242
+ }
2243
+ const inNeighbors = adj.incoming.get(qn);
2244
+ if (inNeighbors) {
2245
+ for (const nb of inNeighbors) {
2246
+ if (!visited.has(nb)) {
2247
+ nextFrontier.add(nb);
2248
+ impacted.add(nb);
2249
+ }
2250
+ }
2251
+ }
2252
+ }
2253
+ if (visited.size + nextFrontier.size > maxNodes) {
2254
+ break;
2255
+ }
2256
+ frontier = nextFrontier;
2257
+ depth++;
2258
+ }
2259
+ const changedNodes = [];
2260
+ for (const qn of seeds) {
2261
+ const n = repo.getNode(qn);
2262
+ if (n) {
2263
+ changedNodes.push(n);
2264
+ }
2265
+ }
2266
+ let impactedNodes = [];
2267
+ for (const qn of impacted) {
2268
+ if (seeds.has(qn)) {
2269
+ continue;
2270
+ }
2271
+ const n = repo.getNode(qn);
2272
+ if (n) {
2273
+ impactedNodes.push(n);
2274
+ }
2275
+ }
2276
+ const totalImpacted = impactedNodes.length;
2277
+ const truncated = totalImpacted > maxNodes;
2278
+ if (truncated) {
2279
+ impactedNodes = impactedNodes.slice(0, maxNodes);
2280
+ }
2281
+ const impactedFiles = [...new Set(impactedNodes.map((n) => n.filePath))];
2282
+ const allQns = /* @__PURE__ */ new Set([...seeds, ...impactedNodes.map((n) => n.qualifiedName)]);
2283
+ const edges = allQns.size > 0 ? repo.getEdgesAmong(allQns) : [];
2284
+ return { changedNodes, impactedNodes, impactedFiles, edges, truncated, totalImpacted };
2285
+ }
2286
+
2287
+ // src/usecases/queryGraph.ts
2288
+ import path5 from "path";
2289
+ var BUILTIN_CALL_NAMES = /* @__PURE__ */ new Set([
2290
+ "map",
2291
+ "filter",
2292
+ "reduce",
2293
+ "reduceRight",
2294
+ "forEach",
2295
+ "find",
2296
+ "findIndex",
2297
+ "some",
2298
+ "every",
2299
+ "includes",
2300
+ "indexOf",
2301
+ "lastIndexOf",
2302
+ "push",
2303
+ "pop",
2304
+ "shift",
2305
+ "unshift",
2306
+ "splice",
2307
+ "slice",
2308
+ "concat",
2309
+ "join",
2310
+ "flat",
2311
+ "flatMap",
2312
+ "sort",
2313
+ "reverse",
2314
+ "fill",
2315
+ "keys",
2316
+ "values",
2317
+ "entries",
2318
+ "from",
2319
+ "isArray",
2320
+ "of",
2321
+ "at",
2322
+ "trim",
2323
+ "trimStart",
2324
+ "trimEnd",
2325
+ "split",
2326
+ "replace",
2327
+ "replaceAll",
2328
+ "match",
2329
+ "matchAll",
2330
+ "search",
2331
+ "substring",
2332
+ "substr",
2333
+ "toLowerCase",
2334
+ "toUpperCase",
2335
+ "startsWith",
2336
+ "endsWith",
2337
+ "padStart",
2338
+ "padEnd",
2339
+ "repeat",
2340
+ "charAt",
2341
+ "charCodeAt",
2342
+ "assign",
2343
+ "freeze",
2344
+ "defineProperty",
2345
+ "getOwnPropertyNames",
2346
+ "hasOwnProperty",
2347
+ "create",
2348
+ "is",
2349
+ "fromEntries",
2350
+ "log",
2351
+ "warn",
2352
+ "error",
2353
+ "info",
2354
+ "debug",
2355
+ "trace",
2356
+ "dir",
2357
+ "table",
2358
+ "time",
2359
+ "timeEnd",
2360
+ "assert",
2361
+ "clear",
2362
+ "count",
2363
+ "then",
2364
+ "catch",
2365
+ "finally",
2366
+ "resolve",
2367
+ "reject",
2368
+ "all",
2369
+ "allSettled",
2370
+ "race",
2371
+ "any",
2372
+ "parse",
2373
+ "stringify",
2374
+ "floor",
2375
+ "ceil",
2376
+ "round",
2377
+ "random",
2378
+ "max",
2379
+ "min",
2380
+ "abs",
2381
+ "pow",
2382
+ "sqrt",
2383
+ "addEventListener",
2384
+ "removeEventListener",
2385
+ "querySelector",
2386
+ "querySelectorAll",
2387
+ "getElementById",
2388
+ "createElement",
2389
+ "appendChild",
2390
+ "removeChild",
2391
+ "setAttribute",
2392
+ "getAttribute",
2393
+ "preventDefault",
2394
+ "stopPropagation",
2395
+ "setTimeout",
2396
+ "clearTimeout",
2397
+ "setInterval",
2398
+ "clearInterval",
2399
+ "toString",
2400
+ "valueOf",
2401
+ "toJSON",
2402
+ "toISOString",
2403
+ "getTime",
2404
+ "getFullYear",
2405
+ "now",
2406
+ "isNaN",
2407
+ "parseInt",
2408
+ "parseFloat",
2409
+ "toFixed",
2410
+ "encodeURIComponent",
2411
+ "decodeURIComponent",
2412
+ "call",
2413
+ "apply",
2414
+ "bind",
2415
+ "next",
2416
+ "emit",
2417
+ "on",
2418
+ "off",
2419
+ "once",
2420
+ "pipe",
2421
+ "write",
2422
+ "read",
2423
+ "end",
2424
+ "close",
2425
+ "destroy",
2426
+ "send",
2427
+ "status",
2428
+ "json",
2429
+ "redirect",
2430
+ "set",
2431
+ "get",
2432
+ "delete",
2433
+ "has",
2434
+ "findUnique",
2435
+ "findFirst",
2436
+ "findMany",
2437
+ "createMany",
2438
+ "update",
2439
+ "updateMany",
2440
+ "deleteMany",
2441
+ "upsert",
2442
+ "aggregate",
2443
+ "groupBy",
2444
+ "transaction",
2445
+ "describe",
2446
+ "it",
2447
+ "test",
2448
+ "expect",
2449
+ "beforeEach",
2450
+ "afterEach",
2451
+ "beforeAll",
2452
+ "afterAll",
2453
+ "mock",
2454
+ "spyOn",
2455
+ "require",
2456
+ "fetch"
2457
+ ]);
2458
+ var QUERY_PATTERNS = {
2459
+ callers_of: "Find all functions that call a given function",
2460
+ callees_of: "Find all functions called by a given function",
2461
+ imports_of: "Find all imports of a given file or module",
2462
+ importers_of: "Find all files that import a given file or module",
2463
+ children_of: "Find all nodes contained in a file or class",
2464
+ tests_for: "Find all tests for a given function or class",
2465
+ inheritors_of: "Find all classes that inherit from a given class",
2466
+ file_summary: "Get a summary of all nodes in a file"
2467
+ };
2468
+ function queryGraph(args) {
2469
+ const { pattern, target, repo, repoRoot } = args;
2470
+ if (!QUERY_PATTERNS[pattern]) {
2471
+ return {
2472
+ status: "error",
2473
+ error: `Unknown pattern '${pattern}'. Available: ${Object.keys(QUERY_PATTERNS).join(", ")}`
2474
+ };
2475
+ }
2476
+ const results = [];
2477
+ const edgesOut = [];
2478
+ if (pattern === "callers_of" && BUILTIN_CALL_NAMES.has(target) && !target.includes("::")) {
2479
+ return {
2480
+ status: "ok",
2481
+ pattern,
2482
+ target,
2483
+ description: QUERY_PATTERNS[pattern],
2484
+ summary: `'${target}' is a common builtin \u2014 callers_of skipped to avoid noise.`,
2485
+ results: [],
2486
+ edges: []
2487
+ };
2488
+ }
2489
+ let node = repo.getNode(target);
2490
+ let resolvedTarget = target;
2491
+ if (!node) {
2492
+ const absTarget = path5.join(repoRoot, target);
2493
+ node = repo.getNode(absTarget);
2494
+ if (node) {
2495
+ resolvedTarget = absTarget;
2496
+ }
2497
+ }
2498
+ if (!node) {
2499
+ const candidates = repo.searchNodes(target, 5);
2500
+ if (candidates.length === 1) {
2501
+ node = candidates[0];
2502
+ resolvedTarget = node.qualifiedName;
2503
+ } else if (candidates.length > 1) {
2504
+ return {
2505
+ status: "ambiguous",
2506
+ summary: `Multiple matches for '${target}'. Please use a qualified name.`,
2507
+ candidates: candidates.map(nodeToDict)
2508
+ };
2509
+ }
2510
+ }
2511
+ if (!node && pattern !== "file_summary") {
2512
+ return { status: "not_found", summary: `No node found matching '${target}'.` };
2513
+ }
2514
+ const qn = node?.qualifiedName ?? resolvedTarget;
2515
+ if (pattern === "callers_of") {
2516
+ for (const e of repo.getEdgesByTarget(qn)) {
2517
+ if (e.kind === "CALLS") {
2518
+ const caller = repo.getNode(e.sourceQualified);
2519
+ if (caller) {
2520
+ results.push(nodeToDict(caller));
2521
+ }
2522
+ edgesOut.push(edgeToDict(e));
2523
+ }
2524
+ }
2525
+ if (results.length === 0 && node) {
2526
+ for (const e of repo.searchEdgesByTargetName(node.name)) {
2527
+ const caller = repo.getNode(e.sourceQualified);
2528
+ if (caller) {
2529
+ results.push(nodeToDict(caller));
2530
+ }
2531
+ edgesOut.push(edgeToDict(e));
2532
+ }
2533
+ }
2534
+ } else if (pattern === "callees_of") {
2535
+ for (const e of repo.getEdgesBySource(qn)) {
2536
+ if (e.kind === "CALLS") {
2537
+ const callee = repo.getNode(e.targetQualified);
2538
+ if (callee) {
2539
+ results.push(nodeToDict(callee));
2540
+ }
2541
+ edgesOut.push(edgeToDict(e));
2542
+ }
2543
+ }
2544
+ } else if (pattern === "imports_of") {
2545
+ for (const e of repo.getEdgesBySource(qn)) {
2546
+ if (e.kind === "IMPORTS_FROM") {
2547
+ results.push({ import_target: e.targetQualified });
2548
+ edgesOut.push(edgeToDict(e));
2549
+ }
2550
+ }
2551
+ } else if (pattern === "importers_of") {
2552
+ const absTarget = node ? node.filePath : path5.join(repoRoot, target);
2553
+ for (const e of repo.getEdgesByTarget(absTarget)) {
2554
+ if (e.kind === "IMPORTS_FROM") {
2555
+ results.push({ importer: e.sourceQualified, file: e.filePath });
2556
+ edgesOut.push(edgeToDict(e));
2557
+ }
2558
+ }
2559
+ } else if (pattern === "children_of") {
2560
+ for (const e of repo.getEdgesBySource(qn)) {
2561
+ if (e.kind === "CONTAINS") {
2562
+ const child = repo.getNode(e.targetQualified);
2563
+ if (child) {
2564
+ results.push(nodeToDict(child));
2565
+ }
2566
+ }
2567
+ }
2568
+ } else if (pattern === "tests_for") {
2569
+ for (const e of repo.getEdgesByTarget(qn)) {
2570
+ if (e.kind === "TESTED_BY") {
2571
+ const testNode = repo.getNode(e.sourceQualified);
2572
+ if (testNode) {
2573
+ results.push(nodeToDict(testNode));
2574
+ }
2575
+ }
2576
+ }
2577
+ const name = node?.name ?? target;
2578
+ const seenQns = new Set(results.map((r) => r["qualified_name"]));
2579
+ for (const t of [
2580
+ ...repo.searchNodes(`test_${name}`, 10),
2581
+ ...repo.searchNodes(`Test${name}`, 10)
2582
+ ]) {
2583
+ if (!seenQns.has(t.qualifiedName) && t.isTest) {
2584
+ results.push(nodeToDict(t));
2585
+ }
2586
+ }
2587
+ } else if (pattern === "inheritors_of") {
2588
+ for (const e of repo.getEdgesByTarget(qn)) {
2589
+ if (e.kind === "INHERITS" || e.kind === "IMPLEMENTS") {
2590
+ const child = repo.getNode(e.sourceQualified);
2591
+ if (child) {
2592
+ results.push(nodeToDict(child));
2593
+ }
2594
+ edgesOut.push(edgeToDict(e));
2595
+ }
2596
+ }
2597
+ } else if (pattern === "file_summary") {
2598
+ const absPath = path5.join(repoRoot, target);
2599
+ for (const n of repo.getNodesByFile(absPath)) {
2600
+ results.push(nodeToDict(n));
2601
+ }
2602
+ }
2603
+ return {
2604
+ status: "ok",
2605
+ pattern,
2606
+ target: resolvedTarget,
2607
+ description: QUERY_PATTERNS[pattern],
2608
+ summary: `Found ${results.length} result(s) for ${pattern}('${resolvedTarget}')`,
2609
+ results,
2610
+ edges: edgesOut
2611
+ };
2612
+ }
2613
+
2614
+ // src/usecases/getReviewContext.ts
2615
+ import fs5 from "fs";
2616
+ import path6 from "path";
2617
+ function getReviewContext(args) {
2618
+ const {
2619
+ changedFiles,
2620
+ repo,
2621
+ repoRoot,
2622
+ maxDepth = 2,
2623
+ includeSource = true,
2624
+ maxLinesPerFile = 200
2625
+ } = args;
2626
+ if (changedFiles.length === 0) {
2627
+ return { status: "ok", summary: "No changes detected. Nothing to review.", context: {} };
2628
+ }
2629
+ const absFiles = changedFiles.map((f) => path6.join(repoRoot, f));
2630
+ const impact = computeImpactRadius(absFiles, repo, maxDepth);
2631
+ const context = {
2632
+ changed_files: changedFiles,
2633
+ impacted_files: impact.impactedFiles,
2634
+ graph: {
2635
+ changed_nodes: impact.changedNodes.map(nodeToDict),
2636
+ impacted_nodes: impact.impactedNodes.map(nodeToDict),
2637
+ edges: impact.edges.map(edgeToDict)
2638
+ }
2639
+ };
2640
+ if (includeSource) {
2641
+ const snippets = {};
2642
+ for (const relPath of changedFiles) {
2643
+ const fullPath = path6.join(repoRoot, relPath);
2644
+ if (fs5.existsSync(fullPath) && fs5.statSync(fullPath).isFile()) {
2645
+ try {
2646
+ const content = fs5.readFileSync(fullPath, "utf-8");
2647
+ const lines = content.split("\n");
2648
+ if (lines.length > maxLinesPerFile) {
2649
+ snippets[relPath] = extractRelevantLines(lines, impact.changedNodes, fullPath);
2650
+ } else {
2651
+ snippets[relPath] = lines.map((l, i) => `${i + 1}: ${l}`).join("\n");
2652
+ }
2653
+ } catch {
2654
+ snippets[relPath] = "(could not read file)";
2655
+ }
2656
+ }
2657
+ }
2658
+ context["source_snippets"] = snippets;
2659
+ }
2660
+ const guidance = generateReviewGuidance(impact, changedFiles);
2661
+ context["review_guidance"] = guidance;
2662
+ const summaryParts = [
2663
+ `Review context for ${changedFiles.length} changed file(s):`,
2664
+ ` - ${impact.changedNodes.length} directly changed nodes`,
2665
+ ` - ${impact.impactedNodes.length} impacted nodes in ${impact.impactedFiles.length} files`,
2666
+ "",
2667
+ "Review guidance:",
2668
+ guidance
2669
+ ];
2670
+ return { status: "ok", summary: summaryParts.join("\n"), context };
2671
+ }
2672
+ function extractRelevantLines(lines, nodes, filePath) {
2673
+ const ranges = [];
2674
+ for (const n of nodes) {
2675
+ if (n.filePath === filePath) {
2676
+ const start = Math.max(0, (n.lineStart ?? 1) - 3);
2677
+ const end = Math.min(lines.length, (n.lineEnd ?? lines.length) + 2);
2678
+ ranges.push([start, end]);
2679
+ }
2680
+ }
2681
+ if (ranges.length === 0) {
2682
+ return lines.slice(0, 50).map((l, i) => `${i + 1}: ${l}`).join("\n");
2683
+ }
2684
+ ranges.sort((a, b) => a[0] - b[0]);
2685
+ const merged = [ranges[0]];
2686
+ for (const [start, end] of ranges.slice(1)) {
2687
+ const last = merged[merged.length - 1];
2688
+ if (start <= last[1] + 1) {
2689
+ merged[merged.length - 1] = [last[0], Math.max(last[1], end)];
2690
+ } else {
2691
+ merged.push([start, end]);
2692
+ }
2693
+ }
2694
+ const parts = [];
2695
+ for (const [start, end] of merged) {
2696
+ if (parts.length > 0) {
2697
+ parts.push("...");
2698
+ }
2699
+ for (let i = start; i < end; i++) {
2700
+ parts.push(`${i + 1}: ${lines[i] ?? ""}`);
2701
+ }
2702
+ }
2703
+ return parts.join("\n");
2704
+ }
2705
+ function generateReviewGuidance(impact, _changedFiles) {
2706
+ const guidanceParts = [];
2707
+ const changedFuncs = impact.changedNodes.filter((n) => n.kind === "Function");
2708
+ const testedFuncQns = new Set(
2709
+ impact.edges.filter((e) => e.kind === "TESTED_BY").map((e) => e.sourceQualified)
2710
+ );
2711
+ const untested = changedFuncs.filter(
2712
+ (f) => !testedFuncQns.has(f.qualifiedName) && !f.isTest
2713
+ );
2714
+ if (untested.length > 0) {
2715
+ guidanceParts.push(
2716
+ `- ${untested.length} changed function(s) lack test coverage: ` + untested.slice(0, 5).map((n) => n.name).join(", ")
2717
+ );
2718
+ }
2719
+ if (impact.impactedNodes.length > 20) {
2720
+ guidanceParts.push(
2721
+ `- Wide blast radius: ${impact.impactedNodes.length} nodes impacted. Review callers and dependents carefully.`
2722
+ );
2723
+ }
2724
+ const inheritanceEdges = impact.edges.filter(
2725
+ (e) => e.kind === "INHERITS" || e.kind === "IMPLEMENTS"
2726
+ );
2727
+ if (inheritanceEdges.length > 0) {
2728
+ guidanceParts.push(
2729
+ `- ${inheritanceEdges.length} inheritance/implementation relationship(s) affected. Check for Liskov substitution violations.`
2730
+ );
2731
+ }
2732
+ if (impact.impactedFiles.length > 3) {
2733
+ guidanceParts.push(
2734
+ `- Changes impact ${impact.impactedFiles.length} other files. Consider splitting into smaller PRs.`
2735
+ );
2736
+ }
2737
+ if (guidanceParts.length === 0) {
2738
+ guidanceParts.push("- Changes appear well-contained with minimal blast radius.");
2739
+ }
2740
+ return guidanceParts.join("\n");
2741
+ }
2742
+
2743
+ // src/usecases/semanticSearch.ts
2744
+ async function semanticSearchNodes(args) {
2745
+ const { query, kind = null, limit = 20, repo, embStore } = args;
2746
+ let searchMode = "keyword";
2747
+ try {
2748
+ if (embStore.available && embStore.count() > 0) {
2749
+ searchMode = "semantic";
2750
+ let raw = await semanticSearch(query, repo, embStore, limit * 2);
2751
+ if (kind) {
2752
+ raw = raw.filter((r) => r["kind"] === kind);
2753
+ }
2754
+ raw = raw.slice(0, limit);
2755
+ return {
2756
+ status: "ok",
2757
+ query,
2758
+ search_mode: searchMode,
2759
+ summary: `Found ${raw.length} node(s) matching '${query}' via semantic search` + (kind ? ` (kind=${kind})` : ""),
2760
+ results: raw
2761
+ };
2762
+ }
2763
+ } catch {
2764
+ searchMode = "keyword";
2765
+ }
2766
+ let results = repo.searchNodes(query, limit * 2);
2767
+ if (kind) {
2768
+ results = results.filter((r) => r.kind === kind);
2769
+ }
2770
+ const qLower = query.toLowerCase();
2771
+ results.sort((a, b) => {
2772
+ const aLower = a.name.toLowerCase();
2773
+ const bLower = b.name.toLowerCase();
2774
+ const aScore = aLower === qLower ? 0 : aLower.startsWith(qLower) ? 1 : 2;
2775
+ const bScore = bLower === qLower ? 0 : bLower.startsWith(qLower) ? 1 : 2;
2776
+ return aScore - bScore;
2777
+ });
2778
+ results = results.slice(0, limit);
2779
+ return {
2780
+ status: "ok",
2781
+ query,
2782
+ search_mode: searchMode,
2783
+ summary: `Found ${results.length} node(s) matching '${query}'` + (kind ? ` (kind=${kind})` : ""),
2784
+ results: results.map(nodeToDict)
2785
+ };
2786
+ }
2787
+ async function semanticSearch(query, repo, embStore, limit = 20) {
2788
+ if (embStore.available && embStore.count() > 0) {
2789
+ const results = await embStore.search(query, limit);
2790
+ const output = [];
2791
+ for (const { qualifiedName, score } of results) {
2792
+ const node = repo.getNode(qualifiedName);
2793
+ if (node) {
2794
+ const d = nodeToDict(node);
2795
+ d["similarity_score"] = Math.round(score * 1e4) / 1e4;
2796
+ output.push(d);
2797
+ }
2798
+ }
2799
+ return output;
2800
+ }
2801
+ return repo.searchNodes(query, limit).map((n) => nodeToDict(n));
2802
+ }
2803
+
2804
+ // src/usecases/listStats.ts
2805
+ import path7 from "path";
2806
+ function listStats(args) {
2807
+ const { repo, embStore, repoRoot } = args;
2808
+ const stats = repo.getStats();
2809
+ const rootName = path7.basename(repoRoot);
2810
+ const summaryParts = [
2811
+ `Graph statistics for ${rootName}:`,
2812
+ ` Files: ${stats.filesCount}`,
2813
+ ` Total nodes: ${stats.totalNodes}`,
2814
+ ` Total edges: ${stats.totalEdges}`,
2815
+ ` Languages: ${stats.languages.length > 0 ? stats.languages.join(", ") : "none"}`,
2816
+ ` Last updated: ${stats.lastUpdated ?? "never"}`,
2817
+ "",
2818
+ "Nodes by kind:",
2819
+ ...Object.entries(stats.nodesByKind).sort().map(([k, c]) => ` ${k}: ${c}`),
2820
+ "",
2821
+ "Edges by kind:",
2822
+ ...Object.entries(stats.edgesByKind).sort().map(([k, c]) => ` ${k}: ${c}`)
2823
+ ];
2824
+ let embCount = 0;
2825
+ try {
2826
+ embCount = embStore.count();
2827
+ summaryParts.push("", `Embeddings: ${embCount} nodes embedded`);
2828
+ if (!embStore.available) {
2829
+ summaryParts.push(" (install @huggingface/transformers for semantic search)");
2830
+ }
2831
+ } catch {
2832
+ }
2833
+ return {
2834
+ status: "ok",
2835
+ summary: summaryParts.join("\n"),
2836
+ total_nodes: stats.totalNodes,
2837
+ total_edges: stats.totalEdges,
2838
+ nodes_by_kind: stats.nodesByKind,
2839
+ edges_by_kind: stats.edgesByKind,
2840
+ languages: stats.languages,
2841
+ files_count: stats.filesCount,
2842
+ last_updated: stats.lastUpdated,
2843
+ embeddings_count: embCount
2844
+ };
2845
+ }
2846
+
2847
+ // src/usecases/embedGraph.ts
2848
+ async function embedAllNodes(repo, embStore) {
2849
+ if (!embStore.available) return 0;
2850
+ const allNodes = [];
2851
+ for (const f of repo.getAllFiles()) {
2852
+ allNodes.push(...repo.getNodesByFile(f));
2853
+ }
2854
+ return embStore.embedNodes(allNodes);
2855
+ }
2856
+ async function embedGraph(args) {
2857
+ const { repo, embStore } = args;
2858
+ if (!embStore.available) {
2859
+ return {
2860
+ status: "error",
2861
+ error: "@huggingface/transformers is not installed. Install with: npm install codeorbit (with optional deps)"
2862
+ };
2863
+ }
2864
+ const newlyEmbedded = await embedAllNodes(repo, embStore);
2865
+ const total = embStore.count();
2866
+ return {
2867
+ status: "ok",
2868
+ summary: `Embedded ${newlyEmbedded} new node(s). Total embeddings: ${total}. Semantic search is now active.`,
2869
+ newly_embedded: newlyEmbedded,
2870
+ total_embeddings: total
2871
+ };
2872
+ }
2873
+
2874
+ // src/usecases/getDocsSection.ts
2875
+ import fs6 from "fs";
2876
+ import path8 from "path";
2877
+ var AVAILABLE_SECTIONS = [
2878
+ "usage",
2879
+ "review-delta",
2880
+ "review-pr",
2881
+ "commands",
2882
+ "legal",
2883
+ "watch",
2884
+ "embeddings",
2885
+ "languages",
2886
+ "troubleshooting"
2887
+ ];
2888
+ function getDocsSection(args) {
2889
+ const { sectionName, searchRoots } = args;
2890
+ for (const searchRoot of searchRoots) {
2891
+ const candidate = path8.join(searchRoot, "docs", "LLM-OPTIMIZED-REFERENCE.md");
2892
+ if (fs6.existsSync(candidate)) {
2893
+ const content = fs6.readFileSync(candidate, "utf-8");
2894
+ const escapedName = sectionName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2895
+ const match = new RegExp(
2896
+ `<section name="${escapedName}">(.*?)</section>`,
2897
+ "si"
2898
+ ).exec(content);
2899
+ if (match) {
2900
+ return { status: "ok", section: sectionName, content: match[1].trim() };
2901
+ }
2902
+ }
2903
+ }
2904
+ return {
2905
+ status: "not_found",
2906
+ error: `Section '${sectionName}' not found. Available: ${AVAILABLE_SECTIONS.join(", ")}`
2907
+ };
2908
+ }
2909
+
2910
+ // src/usecases/findLargeFunctions.ts
2911
+ import path9 from "path";
2912
+ function findLargeFunctions(args) {
2913
+ const { minLines = 50, kind = null, filePathPattern = null, limit = 50, repo, repoRoot } = args;
2914
+ const nodes = repo.getNodesBySize(
2915
+ minLines,
2916
+ void 0,
2917
+ kind ?? void 0,
2918
+ filePathPattern ?? void 0,
2919
+ limit
2920
+ );
2921
+ const results = nodes.map((n) => {
2922
+ const d = nodeToDict(n);
2923
+ d["line_count"] = n.lineStart != null && n.lineEnd != null ? n.lineEnd - n.lineStart + 1 : 0;
2924
+ try {
2925
+ d["relative_path"] = path9.relative(repoRoot, n.filePath);
2926
+ } catch {
2927
+ d["relative_path"] = n.filePath;
2928
+ }
2929
+ return d;
2930
+ });
2931
+ const summaryParts = [
2932
+ `Found ${results.length} node(s) with >= ${minLines} lines` + (kind ? ` (kind=${kind})` : "") + (filePathPattern ? ` matching '${filePathPattern}'` : "") + ":"
2933
+ ];
2934
+ for (const r of results.slice(0, 10)) {
2935
+ summaryParts.push(
2936
+ ` ${String(r["line_count"]).padStart(4)} lines | ${String(r["kind"]).padStart(8)} | ${r["name"]} (${r["relative_path"]}:${r["line_start"]})`
2937
+ );
2938
+ }
2939
+ if (results.length > 10) {
2940
+ summaryParts.push(` ... and ${results.length - 10} more`);
2941
+ }
2942
+ return {
2943
+ status: "ok",
2944
+ summary: summaryParts.join("\n"),
2945
+ total_found: results.length,
2946
+ min_lines: minLines,
2947
+ results
2948
+ };
2949
+ }
2950
+
2951
+ // src/adapters/mcp/tools.ts
2952
+ function validateRepoRoot(repoRoot) {
2953
+ const resolved = path10.resolve(repoRoot);
2954
+ if (!fs7.existsSync(resolved) || !fs7.statSync(resolved).isDirectory()) {
2955
+ throw new Error(`repo_root is not an existing directory: ${resolved}`);
2956
+ }
2957
+ if (!fs7.existsSync(path10.join(resolved, ".git")) && !fs7.existsSync(path10.join(resolved, ".codeorbit"))) {
2958
+ throw new Error(
2959
+ `repo_root does not look like a project root (no .git or .codeorbit): ${resolved}`
2960
+ );
2961
+ }
2962
+ return resolved;
2963
+ }
2964
+ function resolveRoot(repoRoot) {
2965
+ return repoRoot ? validateRepoRoot(repoRoot) : findProjectRoot();
2966
+ }
2967
+ function buildOrUpdateGraph(args) {
2968
+ const { fullRebuild = false, repoRoot = null, base = "HEAD~1" } = args;
2969
+ const root = resolveRoot(repoRoot);
2970
+ const repo = new SqliteGraphRepository(getDbPath(root));
2971
+ const parser = new CodeParser();
2972
+ try {
2973
+ if (fullRebuild) {
2974
+ const result = fullBuild(root, repo, parser);
2975
+ return {
2976
+ status: "ok",
2977
+ build_type: "full",
2978
+ summary: `Full build complete: parsed ${result.filesUpdated} files, created ${result.totalNodes} nodes and ${result.totalEdges} edges.`,
2979
+ files_updated: result.filesUpdated,
2980
+ total_nodes: result.totalNodes,
2981
+ total_edges: result.totalEdges,
2982
+ errors: result.errors
2983
+ };
2984
+ } else {
2985
+ const result = incrementalUpdate(root, repo, parser, base);
2986
+ if (result.filesUpdated === 0) {
2987
+ return {
2988
+ status: "ok",
2989
+ build_type: "incremental",
2990
+ summary: "No changes detected. Graph is up to date.",
2991
+ files_updated: 0,
2992
+ total_nodes: 0,
2993
+ total_edges: 0,
2994
+ changed_files: [],
2995
+ dependent_files: [],
2996
+ errors: []
2997
+ };
2998
+ }
2999
+ return {
3000
+ status: "ok",
3001
+ build_type: "incremental",
3002
+ summary: `Incremental update: ${result.filesUpdated} files re-parsed, ${result.totalNodes} nodes and ${result.totalEdges} edges updated. Changed: ${JSON.stringify(result.changedFiles)}. Dependents also updated: ${JSON.stringify(result.dependentFiles)}.`,
3003
+ files_updated: result.filesUpdated,
3004
+ total_nodes: result.totalNodes,
3005
+ total_edges: result.totalEdges,
3006
+ changed_files: result.changedFiles,
3007
+ dependent_files: result.dependentFiles,
3008
+ errors: result.errors
3009
+ };
3010
+ }
3011
+ } finally {
3012
+ repo.close();
3013
+ }
3014
+ }
3015
+ function getImpactRadius(args) {
3016
+ const {
3017
+ changedFiles = null,
3018
+ maxDepth = 2,
3019
+ maxResults = 500,
3020
+ repoRoot = null,
3021
+ base = "HEAD~1"
3022
+ } = args;
3023
+ const root = resolveRoot(repoRoot);
3024
+ const repo = new SqliteGraphRepository(getDbPath(root));
3025
+ try {
3026
+ let changed = changedFiles;
3027
+ if (!changed) {
3028
+ changed = getChangedFiles(root, base);
3029
+ if (changed.length === 0) {
3030
+ changed = getStagedAndUnstaged(root);
3031
+ }
3032
+ }
3033
+ if (changed.length === 0) {
3034
+ return {
3035
+ status: "ok",
3036
+ summary: "No changed files detected.",
3037
+ changed_nodes: [],
3038
+ impacted_nodes: [],
3039
+ impacted_files: [],
3040
+ truncated: false,
3041
+ total_impacted: 0
3042
+ };
3043
+ }
3044
+ const absFiles = changed.map((f) => path10.join(root, f));
3045
+ const result = computeImpactRadius(absFiles, repo, maxDepth, maxResults);
3046
+ const summaryParts = [
3047
+ `Blast radius for ${changed.length} changed file(s):`,
3048
+ ` - ${result.changedNodes.length} nodes directly changed`,
3049
+ ` - ${result.impactedNodes.length} nodes impacted (within ${maxDepth} hops)`,
3050
+ ` - ${result.impactedFiles.length} additional files affected`
3051
+ ];
3052
+ if (result.truncated) {
3053
+ summaryParts.push(
3054
+ ` - Results truncated: showing ${result.impactedNodes.length} of ${result.totalImpacted} impacted nodes`
3055
+ );
3056
+ }
3057
+ return {
3058
+ status: "ok",
3059
+ summary: summaryParts.join("\n"),
3060
+ changed_files: changed,
3061
+ changed_nodes: result.changedNodes.map(nodeToDict),
3062
+ impacted_nodes: result.impactedNodes.map(nodeToDict),
3063
+ impacted_files: result.impactedFiles,
3064
+ edges: result.edges.map(edgeToDict),
3065
+ truncated: result.truncated,
3066
+ total_impacted: result.totalImpacted
3067
+ };
3068
+ } finally {
3069
+ repo.close();
3070
+ }
3071
+ }
3072
+ function queryGraph2(args) {
3073
+ const { pattern, target, repoRoot = null } = args;
3074
+ const root = resolveRoot(repoRoot);
3075
+ const repo = new SqliteGraphRepository(getDbPath(root));
3076
+ try {
3077
+ return queryGraph({ pattern, target, repo, repoRoot: root });
3078
+ } finally {
3079
+ repo.close();
3080
+ }
3081
+ }
3082
+ function getReviewContext2(args) {
3083
+ const {
3084
+ changedFiles = null,
3085
+ maxDepth = 2,
3086
+ includeSource = true,
3087
+ maxLinesPerFile = 200,
3088
+ repoRoot = null,
3089
+ base = "HEAD~1"
3090
+ } = args;
3091
+ const root = resolveRoot(repoRoot);
3092
+ const repo = new SqliteGraphRepository(getDbPath(root));
3093
+ try {
3094
+ let changed = changedFiles;
3095
+ if (!changed) {
3096
+ changed = getChangedFiles(root, base);
3097
+ if (changed.length === 0) {
3098
+ changed = getStagedAndUnstaged(root);
3099
+ }
3100
+ }
3101
+ if (changed.length === 0) {
3102
+ return {
3103
+ status: "ok",
3104
+ summary: "No changes detected. Nothing to review.",
3105
+ context: {}
3106
+ };
3107
+ }
3108
+ return getReviewContext({
3109
+ changedFiles: changed,
3110
+ repo,
3111
+ repoRoot: root,
3112
+ maxDepth,
3113
+ includeSource,
3114
+ maxLinesPerFile
3115
+ });
3116
+ } finally {
3117
+ repo.close();
3118
+ }
3119
+ }
3120
+ async function semanticSearchNodes2(args) {
3121
+ const { query, kind = null, limit = 20, repoRoot = null } = args;
3122
+ const root = resolveRoot(repoRoot);
3123
+ const dbPath = getDbPath(root);
3124
+ const repo = new SqliteGraphRepository(dbPath);
3125
+ const embStore = new SqliteEmbeddingStore(dbPath);
3126
+ try {
3127
+ return await semanticSearchNodes({ query, kind, limit, repo, embStore });
3128
+ } finally {
3129
+ embStore.close();
3130
+ repo.close();
3131
+ }
3132
+ }
3133
+ function listGraphStats(args) {
3134
+ const { repoRoot = null } = args;
3135
+ const root = resolveRoot(repoRoot);
3136
+ const dbPath = getDbPath(root);
3137
+ const repo = new SqliteGraphRepository(dbPath);
3138
+ const embStore = new SqliteEmbeddingStore(dbPath);
3139
+ try {
3140
+ return listStats({ repo, embStore, repoRoot: root });
3141
+ } finally {
3142
+ embStore.close();
3143
+ repo.close();
3144
+ }
3145
+ }
3146
+ async function embedGraph2(args) {
3147
+ const { repoRoot = null } = args;
3148
+ const root = resolveRoot(repoRoot);
3149
+ const dbPath = getDbPath(root);
3150
+ const repo = new SqliteGraphRepository(dbPath);
3151
+ const embStore = new SqliteEmbeddingStore(dbPath);
3152
+ try {
3153
+ return await embedGraph({ repo, embStore });
3154
+ } finally {
3155
+ embStore.close();
3156
+ repo.close();
3157
+ }
3158
+ }
3159
+ function getDocsSection2(args) {
3160
+ const { sectionName, repoRoot = null } = args;
3161
+ const searchRoots = [];
3162
+ if (repoRoot) {
3163
+ searchRoots.push(path10.resolve(repoRoot));
3164
+ }
3165
+ try {
3166
+ const root = resolveRoot(repoRoot);
3167
+ if (!searchRoots.includes(root)) {
3168
+ searchRoots.push(root);
3169
+ }
3170
+ } catch {
3171
+ }
3172
+ return getDocsSection({ sectionName, searchRoots });
3173
+ }
3174
+ function findLargeFunctions2(args) {
3175
+ const {
3176
+ minLines = 50,
3177
+ kind = null,
3178
+ filePathPattern = null,
3179
+ limit = 50,
3180
+ repoRoot = null
3181
+ } = args;
3182
+ const root = resolveRoot(repoRoot);
3183
+ const repo = new SqliteGraphRepository(getDbPath(root));
3184
+ try {
3185
+ return findLargeFunctions({ minLines, kind, filePathPattern, limit, repo, repoRoot: root });
3186
+ } finally {
3187
+ repo.close();
3188
+ }
3189
+ }
3190
+
3191
+ // src/adapters/mcp/server.ts
3192
+ var server = new McpServer(
3193
+ { name: "codeorbit", version: "0.1.0" },
3194
+ {
3195
+ instructions: "Persistent incremental knowledge graph for token-efficient, context-aware code reviews. Parses your codebase with Tree-sitter, builds a structural graph, and provides smart impact analysis."
3196
+ }
3197
+ );
3198
+ server.tool(
3199
+ "build_or_update_graph_tool",
3200
+ "Build or incrementally update the code knowledge graph.\n\nCall this first to initialize the graph, or after making changes.\nBy default performs an incremental update (only changed files).\nSet full_rebuild=True to re-parse every file.\n\nArgs:\n full_rebuild: If True, re-parse all files. Default: False (incremental).\n repo_root: Repository root path. Auto-detected from current directory if omitted.\n base: Git ref to diff against for incremental updates. Default: HEAD~1.",
3201
+ {
3202
+ full_rebuild: z.boolean().default(false),
3203
+ repo_root: z.string().nullable().default(null),
3204
+ base: z.string().default("HEAD~1")
3205
+ },
3206
+ async (args) => ({
3207
+ content: [
3208
+ {
3209
+ type: "text",
3210
+ text: JSON.stringify(
3211
+ buildOrUpdateGraph({
3212
+ fullRebuild: args.full_rebuild,
3213
+ repoRoot: args.repo_root,
3214
+ base: args.base
3215
+ })
3216
+ )
3217
+ }
3218
+ ]
3219
+ })
3220
+ );
3221
+ server.tool(
3222
+ "get_impact_radius_tool",
3223
+ "Analyze the blast radius of changed files in the codebase.\n\nShows which functions, classes, and files are impacted by changes.\nAuto-detects changed files from git if not specified.\n\nArgs:\n changed_files: List of changed file paths (relative to repo root). Auto-detected if omitted.\n max_depth: Number of hops to traverse in the dependency graph. Default: 2.\n repo_root: Repository root path. Auto-detected if omitted.\n base: Git ref for auto-detecting changes. Default: HEAD~1.",
3224
+ {
3225
+ changed_files: z.array(z.string()).nullable().default(null),
3226
+ max_depth: z.number().int().default(2),
3227
+ repo_root: z.string().nullable().default(null),
3228
+ base: z.string().default("HEAD~1")
3229
+ },
3230
+ async (args) => ({
3231
+ content: [
3232
+ {
3233
+ type: "text",
3234
+ text: JSON.stringify(
3235
+ getImpactRadius({
3236
+ changedFiles: args.changed_files,
3237
+ maxDepth: args.max_depth,
3238
+ repoRoot: args.repo_root,
3239
+ base: args.base
3240
+ })
3241
+ )
3242
+ }
3243
+ ]
3244
+ })
3245
+ );
3246
+ server.tool(
3247
+ "query_graph_tool",
3248
+ "Run a predefined graph query to explore code relationships.\n\nAvailable patterns:\n- callers_of: Find functions that call the target\n- callees_of: Find functions called by the target\n- imports_of: Find what the target imports\n- importers_of: Find files that import the target\n- children_of: Find nodes contained in a file or class\n- tests_for: Find tests for the target\n- inheritors_of: Find classes inheriting from the target\n- file_summary: Get all nodes in a file\n\nArgs:\n pattern: Query pattern name (see above).\n target: Node name, qualified name, or file path to query.\n repo_root: Repository root path. Auto-detected if omitted.",
3249
+ {
3250
+ pattern: z.string(),
3251
+ target: z.string(),
3252
+ repo_root: z.string().nullable().default(null)
3253
+ },
3254
+ async (args) => ({
3255
+ content: [
3256
+ {
3257
+ type: "text",
3258
+ text: JSON.stringify(
3259
+ queryGraph2({
3260
+ pattern: args.pattern,
3261
+ target: args.target,
3262
+ repoRoot: args.repo_root
3263
+ })
3264
+ )
3265
+ }
3266
+ ]
3267
+ })
3268
+ );
3269
+ server.tool(
3270
+ "get_review_context_tool",
3271
+ "Generate a focused, token-efficient review context for code changes.\n\nCombines impact analysis with source snippets and review guidance.\nUse this for comprehensive code reviews.\n\nArgs:\n changed_files: Files to review. Auto-detected from git diff if omitted.\n max_depth: Impact radius depth. Default: 2.\n include_source: Include source code snippets. Default: True.\n max_lines_per_file: Max source lines per file. Default: 200.\n repo_root: Repository root path. Auto-detected if omitted.\n base: Git ref for change detection. Default: HEAD~1.",
3272
+ {
3273
+ changed_files: z.array(z.string()).nullable().default(null),
3274
+ max_depth: z.number().int().default(2),
3275
+ include_source: z.boolean().default(true),
3276
+ max_lines_per_file: z.number().int().default(200),
3277
+ repo_root: z.string().nullable().default(null),
3278
+ base: z.string().default("HEAD~1")
3279
+ },
3280
+ async (args) => ({
3281
+ content: [
3282
+ {
3283
+ type: "text",
3284
+ text: JSON.stringify(
3285
+ getReviewContext2({
3286
+ changedFiles: args.changed_files,
3287
+ maxDepth: args.max_depth,
3288
+ includeSource: args.include_source,
3289
+ maxLinesPerFile: args.max_lines_per_file,
3290
+ repoRoot: args.repo_root,
3291
+ base: args.base
3292
+ })
3293
+ )
3294
+ }
3295
+ ]
3296
+ })
3297
+ );
3298
+ server.tool(
3299
+ "semantic_search_nodes_tool",
3300
+ "Search for code entities by name, keyword, or semantic similarity.\n\nUses vector embeddings for semantic search when available (run embed_graph_tool\nfirst, requires @huggingface/transformers). Falls back to keyword matching otherwise.\n\nArgs:\n query: Search string to match against node names.\n kind: Optional filter: File, Class, Function, Type, or Test.\n limit: Maximum results. Default: 20.\n repo_root: Repository root path. Auto-detected if omitted.",
3301
+ {
3302
+ query: z.string(),
3303
+ kind: z.string().nullable().default(null),
3304
+ limit: z.number().int().default(20),
3305
+ repo_root: z.string().nullable().default(null)
3306
+ },
3307
+ async (args) => ({
3308
+ content: [
3309
+ {
3310
+ type: "text",
3311
+ text: JSON.stringify(
3312
+ await semanticSearchNodes2({
3313
+ query: args.query,
3314
+ kind: args.kind,
3315
+ limit: args.limit,
3316
+ repoRoot: args.repo_root
3317
+ })
3318
+ )
3319
+ }
3320
+ ]
3321
+ })
3322
+ );
3323
+ server.tool(
3324
+ "embed_graph_tool",
3325
+ "Compute vector embeddings for all graph nodes to enable semantic search.\n\nRequires: npm install @huggingface/transformers\nOnly computes embeddings for nodes that do not already have them.\n\nArgs:\n repo_root: Repository root path. Auto-detected if omitted.",
3326
+ {
3327
+ repo_root: z.string().nullable().default(null)
3328
+ },
3329
+ async (args) => ({
3330
+ content: [
3331
+ {
3332
+ type: "text",
3333
+ text: JSON.stringify(await embedGraph2({ repoRoot: args.repo_root }))
3334
+ }
3335
+ ]
3336
+ })
3337
+ );
3338
+ server.tool(
3339
+ "list_graph_stats_tool",
3340
+ "Get aggregate statistics about the code knowledge graph.\n\nShows total nodes, edges, languages, files, and last update time.\nUseful for checking if the graph is built and up to date.\n\nArgs:\n repo_root: Repository root path. Auto-detected if omitted.",
3341
+ {
3342
+ repo_root: z.string().nullable().default(null)
3343
+ },
3344
+ async (args) => ({
3345
+ content: [
3346
+ {
3347
+ type: "text",
3348
+ text: JSON.stringify(listGraphStats({ repoRoot: args.repo_root }))
3349
+ }
3350
+ ]
3351
+ })
3352
+ );
3353
+ server.tool(
3354
+ "get_docs_section_tool",
3355
+ 'Get a specific section from the LLM-optimized documentation reference.\n\nReturns only the requested section content for minimal token usage.\n\nAvailable sections: usage, review-delta, review-pr, commands, legal,\nwatch, embeddings, languages, troubleshooting.\n\nArgs:\n section_name: The section to retrieve (e.g. "review-delta", "usage").',
3356
+ {
3357
+ section_name: z.string(),
3358
+ repo_root: z.string().nullable().default(null)
3359
+ },
3360
+ async (args) => ({
3361
+ content: [
3362
+ {
3363
+ type: "text",
3364
+ text: JSON.stringify(
3365
+ getDocsSection2({
3366
+ sectionName: args.section_name,
3367
+ repoRoot: args.repo_root
3368
+ })
3369
+ )
3370
+ }
3371
+ ]
3372
+ })
3373
+ );
3374
+ server.tool(
3375
+ "find_large_functions_tool",
3376
+ 'Find functions, classes, or files exceeding a line-count threshold.\n\nUseful for decomposition audits, code quality checks, and enforcing\nsize limits during code review. Results are ordered by line count.\n\nArgs:\n min_lines: Minimum line count to flag. Default: 50.\n kind: Optional filter: Function, Class, File, or Test.\n file_path_pattern: Filter by file path substring (e.g. "components/").\n limit: Maximum results. Default: 50.\n repo_root: Repository root path. Auto-detected if omitted.',
3377
+ {
3378
+ min_lines: z.number().int().default(50),
3379
+ kind: z.string().nullable().default(null),
3380
+ file_path_pattern: z.string().nullable().default(null),
3381
+ limit: z.number().int().default(50),
3382
+ repo_root: z.string().nullable().default(null)
3383
+ },
3384
+ async (args) => ({
3385
+ content: [
3386
+ {
3387
+ type: "text",
3388
+ text: JSON.stringify(
3389
+ findLargeFunctions2({
3390
+ minLines: args.min_lines,
3391
+ kind: args.kind,
3392
+ filePathPattern: args.file_path_pattern,
3393
+ limit: args.limit,
3394
+ repoRoot: args.repo_root
3395
+ })
3396
+ )
3397
+ }
3398
+ ]
3399
+ })
3400
+ );
3401
+ async function runMcpServer() {
3402
+ const transport = new StdioServerTransport();
3403
+ await server.connect(transport);
3404
+ }
3405
+ export {
3406
+ runMcpServer
3407
+ };
3408
+ //# sourceMappingURL=server.js.map