@saluzi/codegraph 0.1.0 → 0.2.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.
Files changed (246) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +885 -0
  3. package/package.json +42 -10
  4. package/scripts/add-lang/bench.sh +60 -0
  5. package/scripts/add-lang/check-grammar.mjs +75 -0
  6. package/scripts/add-lang/dump-ast.mjs +103 -0
  7. package/scripts/add-lang/verify-extraction.mjs +70 -0
  8. package/scripts/agent-eval/ab-adoption.sh +91 -0
  9. package/scripts/agent-eval/ab-hook.sh +86 -0
  10. package/scripts/agent-eval/ab-impl.sh +78 -0
  11. package/scripts/agent-eval/ab-new-vs-baseline.sh +102 -0
  12. package/scripts/agent-eval/ab-sufficiency.sh +78 -0
  13. package/scripts/agent-eval/arms-F.sh +21 -0
  14. package/scripts/agent-eval/arms-matrix.sh +37 -0
  15. package/scripts/agent-eval/audit.sh +68 -0
  16. package/scripts/agent-eval/bench-readme.sh +28 -0
  17. package/scripts/agent-eval/bench-why-repo.sh +22 -0
  18. package/scripts/agent-eval/block-read-hook.sh +19 -0
  19. package/scripts/agent-eval/hook-settings.json +15 -0
  20. package/scripts/agent-eval/itrun.sh +120 -0
  21. package/scripts/agent-eval/offload-eval-3arm.sh +72 -0
  22. package/scripts/agent-eval/offload-eval-cost.mjs +133 -0
  23. package/scripts/agent-eval/offload-eval-effort.mjs +108 -0
  24. package/scripts/agent-eval/offload-eval-frontload-matrix.sh +25 -0
  25. package/scripts/agent-eval/offload-eval-frontload.sh +47 -0
  26. package/scripts/agent-eval/offload-eval-ground-truth.json +18 -0
  27. package/scripts/agent-eval/offload-eval-hook.mjs +84 -0
  28. package/scripts/agent-eval/offload-eval-judge.mjs +103 -0
  29. package/scripts/agent-eval/offload-eval-matrix.sh +20 -0
  30. package/scripts/agent-eval/offload-eval-metrics.mjs +94 -0
  31. package/scripts/agent-eval/offload-eval-refs1.sh +50 -0
  32. package/scripts/agent-eval/offload-eval-setup.sh +24 -0
  33. package/scripts/agent-eval/offload-eval-styles.sh +72 -0
  34. package/scripts/agent-eval/offload-eval-summarize.mjs +68 -0
  35. package/scripts/agent-eval/offload-eval.md +76 -0
  36. package/scripts/agent-eval/parse-arms.mjs +116 -0
  37. package/scripts/agent-eval/parse-bench-readme.mjs +84 -0
  38. package/scripts/agent-eval/parse-run.mjs +45 -0
  39. package/scripts/agent-eval/parse-session.mjs +93 -0
  40. package/scripts/agent-eval/probe-context.mjs +21 -0
  41. package/scripts/agent-eval/probe-explore.mjs +40 -0
  42. package/scripts/agent-eval/probe-node.mjs +20 -0
  43. package/scripts/agent-eval/probe-sweep.mjs +119 -0
  44. package/scripts/agent-eval/probe-trace.mjs +20 -0
  45. package/scripts/agent-eval/redirect-read-hook.sh +38 -0
  46. package/scripts/agent-eval/repro-concurrent-explore.mjs +119 -0
  47. package/scripts/agent-eval/repro-daemon-clients.mjs +125 -0
  48. package/scripts/agent-eval/run-agent.sh +34 -0
  49. package/scripts/agent-eval/run-all.sh +75 -0
  50. package/scripts/agent-eval/run-arms.sh +56 -0
  51. package/scripts/agent-eval/seq-matrix.mjs +137 -0
  52. package/scripts/build-bundle.sh +123 -0
  53. package/scripts/extract-release-notes.mjs +130 -0
  54. package/scripts/local-install.sh +41 -0
  55. package/scripts/npm-sdk.js +75 -0
  56. package/scripts/npm-shim.js +275 -0
  57. package/scripts/pack-npm.sh +119 -0
  58. package/scripts/prepare-release.mjs +270 -0
  59. package/dist/bin/codegraph.d.ts +0 -25
  60. package/dist/bin/node-version-check.d.ts +0 -37
  61. package/dist/bin/uninstall.d.ts +0 -14
  62. package/dist/context/formatter.d.ts +0 -33
  63. package/dist/context/formatter.js +0 -244
  64. package/dist/context/index.d.ts +0 -117
  65. package/dist/context/index.js +0 -1050
  66. package/dist/db/index.d.ts +0 -101
  67. package/dist/db/index.js +0 -250
  68. package/dist/db/migrations.d.ts +0 -47
  69. package/dist/db/migrations.js +0 -131
  70. package/dist/db/queries.d.ts +0 -291
  71. package/dist/db/queries.js +0 -1349
  72. package/dist/db/schema.sql +0 -151
  73. package/dist/db/sqlite-adapter.d.ts +0 -49
  74. package/dist/db/sqlite-adapter.js +0 -141
  75. package/dist/directory.d.ts +0 -62
  76. package/dist/directory.js +0 -264
  77. package/dist/errors.d.ts +0 -149
  78. package/dist/errors.js +0 -219
  79. package/dist/extraction/dfm-extractor.d.ts +0 -31
  80. package/dist/extraction/dfm-extractor.js +0 -151
  81. package/dist/extraction/grammars.d.ts +0 -94
  82. package/dist/extraction/grammars.js +0 -357
  83. package/dist/extraction/index.d.ts +0 -148
  84. package/dist/extraction/index.js +0 -1286
  85. package/dist/extraction/languages/c-cpp.d.ts +0 -4
  86. package/dist/extraction/languages/c-cpp.js +0 -126
  87. package/dist/extraction/languages/csharp.d.ts +0 -3
  88. package/dist/extraction/languages/csharp.js +0 -72
  89. package/dist/extraction/languages/dart.d.ts +0 -3
  90. package/dist/extraction/languages/dart.js +0 -192
  91. package/dist/extraction/languages/go.d.ts +0 -3
  92. package/dist/extraction/languages/go.js +0 -58
  93. package/dist/extraction/languages/index.d.ts +0 -10
  94. package/dist/extraction/languages/index.js +0 -49
  95. package/dist/extraction/languages/java.d.ts +0 -3
  96. package/dist/extraction/languages/java.js +0 -64
  97. package/dist/extraction/languages/javascript.d.ts +0 -3
  98. package/dist/extraction/languages/javascript.js +0 -90
  99. package/dist/extraction/languages/kotlin.d.ts +0 -3
  100. package/dist/extraction/languages/kotlin.js +0 -253
  101. package/dist/extraction/languages/lua.d.ts +0 -3
  102. package/dist/extraction/languages/lua.js +0 -150
  103. package/dist/extraction/languages/luau.d.ts +0 -3
  104. package/dist/extraction/languages/luau.js +0 -37
  105. package/dist/extraction/languages/pascal.d.ts +0 -3
  106. package/dist/extraction/languages/pascal.js +0 -66
  107. package/dist/extraction/languages/php.d.ts +0 -3
  108. package/dist/extraction/languages/php.js +0 -107
  109. package/dist/extraction/languages/python.d.ts +0 -3
  110. package/dist/extraction/languages/python.js +0 -56
  111. package/dist/extraction/languages/ruby.d.ts +0 -3
  112. package/dist/extraction/languages/ruby.js +0 -114
  113. package/dist/extraction/languages/rust.d.ts +0 -3
  114. package/dist/extraction/languages/rust.js +0 -109
  115. package/dist/extraction/languages/scala.d.ts +0 -3
  116. package/dist/extraction/languages/scala.js +0 -139
  117. package/dist/extraction/languages/swift.d.ts +0 -3
  118. package/dist/extraction/languages/swift.js +0 -91
  119. package/dist/extraction/languages/typescript.d.ts +0 -3
  120. package/dist/extraction/languages/typescript.js +0 -129
  121. package/dist/extraction/liquid-extractor.d.ts +0 -52
  122. package/dist/extraction/liquid-extractor.js +0 -313
  123. package/dist/extraction/parse-worker.d.ts +0 -8
  124. package/dist/extraction/parse-worker.js +0 -94
  125. package/dist/extraction/svelte-extractor.d.ts +0 -56
  126. package/dist/extraction/svelte-extractor.js +0 -272
  127. package/dist/extraction/tree-sitter-helpers.d.ts +0 -39
  128. package/dist/extraction/tree-sitter-helpers.js +0 -103
  129. package/dist/extraction/tree-sitter-types.d.ts +0 -191
  130. package/dist/extraction/tree-sitter-types.js +0 -10
  131. package/dist/extraction/tree-sitter.d.ts +0 -238
  132. package/dist/extraction/tree-sitter.js +0 -2430
  133. package/dist/extraction/vue-extractor.d.ts +0 -36
  134. package/dist/extraction/vue-extractor.js +0 -163
  135. package/dist/extraction/wasm/tree-sitter-c.wasm +0 -0
  136. package/dist/extraction/wasm/tree-sitter-c_sharp.wasm +0 -0
  137. package/dist/extraction/wasm/tree-sitter-cpp.wasm +0 -0
  138. package/dist/extraction/wasm/tree-sitter-dart.wasm +0 -0
  139. package/dist/extraction/wasm/tree-sitter-go.wasm +0 -0
  140. package/dist/extraction/wasm/tree-sitter-java.wasm +0 -0
  141. package/dist/extraction/wasm/tree-sitter-javascript.wasm +0 -0
  142. package/dist/extraction/wasm/tree-sitter-kotlin.wasm +0 -0
  143. package/dist/extraction/wasm/tree-sitter-lua.wasm +0 -0
  144. package/dist/extraction/wasm/tree-sitter-luau.wasm +0 -0
  145. package/dist/extraction/wasm/tree-sitter-pascal.wasm +0 -0
  146. package/dist/extraction/wasm/tree-sitter-php.wasm +0 -0
  147. package/dist/extraction/wasm/tree-sitter-python.wasm +0 -0
  148. package/dist/extraction/wasm/tree-sitter-ruby.wasm +0 -0
  149. package/dist/extraction/wasm/tree-sitter-rust.wasm +0 -0
  150. package/dist/extraction/wasm/tree-sitter-scala.wasm +0 -0
  151. package/dist/extraction/wasm/tree-sitter-swift.wasm +0 -0
  152. package/dist/extraction/wasm/tree-sitter-tsx.wasm +0 -0
  153. package/dist/extraction/wasm/tree-sitter-typescript.wasm +0 -0
  154. package/dist/extraction/wasm-runtime-flags.d.ts +0 -46
  155. package/dist/extraction/wasm-runtime-flags.js +0 -105
  156. package/dist/graph/index.d.ts +0 -8
  157. package/dist/graph/index.js +0 -13
  158. package/dist/graph/queries.d.ts +0 -109
  159. package/dist/graph/queries.js +0 -366
  160. package/dist/graph/traversal.d.ts +0 -137
  161. package/dist/graph/traversal.js +0 -528
  162. package/dist/index.d.ts +0 -509
  163. package/dist/index.js +0 -800
  164. package/dist/installer/claude-md-template.d.ts +0 -19
  165. package/dist/installer/config-writer.d.ts +0 -29
  166. package/dist/installer/index.d.ts +0 -140
  167. package/dist/installer/instructions-template.d.ts +0 -30
  168. package/dist/installer/targets/claude.d.ts +0 -55
  169. package/dist/installer/targets/codex.d.ts +0 -18
  170. package/dist/installer/targets/cursor.d.ts +0 -35
  171. package/dist/installer/targets/hermes.d.ts +0 -18
  172. package/dist/installer/targets/opencode.d.ts +0 -30
  173. package/dist/installer/targets/registry.d.ts +0 -38
  174. package/dist/installer/targets/shared.d.ts +0 -92
  175. package/dist/installer/targets/toml.d.ts +0 -64
  176. package/dist/installer/targets/types.d.ts +0 -122
  177. package/dist/mcp/index.d.ts +0 -98
  178. package/dist/mcp/server-instructions.d.ts +0 -20
  179. package/dist/mcp/tools.d.ts +0 -269
  180. package/dist/mcp/transport.d.ts +0 -117
  181. package/dist/resolution/frameworks/cargo-workspace.d.ts +0 -20
  182. package/dist/resolution/frameworks/cargo-workspace.js +0 -225
  183. package/dist/resolution/frameworks/csharp.d.ts +0 -8
  184. package/dist/resolution/frameworks/csharp.js +0 -213
  185. package/dist/resolution/frameworks/drupal.d.ts +0 -51
  186. package/dist/resolution/frameworks/drupal.js +0 -335
  187. package/dist/resolution/frameworks/express.d.ts +0 -8
  188. package/dist/resolution/frameworks/express.js +0 -225
  189. package/dist/resolution/frameworks/go.d.ts +0 -8
  190. package/dist/resolution/frameworks/go.js +0 -158
  191. package/dist/resolution/frameworks/index.d.ts +0 -52
  192. package/dist/resolution/frameworks/index.js +0 -137
  193. package/dist/resolution/frameworks/java.d.ts +0 -8
  194. package/dist/resolution/frameworks/java.js +0 -177
  195. package/dist/resolution/frameworks/laravel.d.ts +0 -13
  196. package/dist/resolution/frameworks/laravel.js +0 -248
  197. package/dist/resolution/frameworks/nestjs.d.ts +0 -26
  198. package/dist/resolution/frameworks/nestjs.js +0 -374
  199. package/dist/resolution/frameworks/python.d.ts +0 -10
  200. package/dist/resolution/frameworks/python.js +0 -278
  201. package/dist/resolution/frameworks/react.d.ts +0 -8
  202. package/dist/resolution/frameworks/react.js +0 -272
  203. package/dist/resolution/frameworks/ruby.d.ts +0 -8
  204. package/dist/resolution/frameworks/ruby.js +0 -198
  205. package/dist/resolution/frameworks/rust.d.ts +0 -8
  206. package/dist/resolution/frameworks/rust.js +0 -207
  207. package/dist/resolution/frameworks/svelte.d.ts +0 -9
  208. package/dist/resolution/frameworks/svelte.js +0 -249
  209. package/dist/resolution/frameworks/swift.d.ts +0 -10
  210. package/dist/resolution/frameworks/swift.js +0 -376
  211. package/dist/resolution/frameworks/vue.d.ts +0 -9
  212. package/dist/resolution/frameworks/vue.js +0 -306
  213. package/dist/resolution/import-resolver.d.ts +0 -61
  214. package/dist/resolution/import-resolver.js +0 -663
  215. package/dist/resolution/index.d.ts +0 -118
  216. package/dist/resolution/index.js +0 -744
  217. package/dist/resolution/lru-cache.d.ts +0 -24
  218. package/dist/resolution/lru-cache.js +0 -62
  219. package/dist/resolution/name-matcher.d.ts +0 -50
  220. package/dist/resolution/name-matcher.js +0 -384
  221. package/dist/resolution/path-aliases.d.ts +0 -72
  222. package/dist/resolution/path-aliases.js +0 -238
  223. package/dist/resolution/strip-comments.d.ts +0 -40
  224. package/dist/resolution/strip-comments.js +0 -441
  225. package/dist/resolution/types.d.ts +0 -181
  226. package/dist/resolution/types.js +0 -8
  227. package/dist/search/query-parser.d.ts +0 -61
  228. package/dist/search/query-parser.js +0 -177
  229. package/dist/search/query-utils.d.ts +0 -59
  230. package/dist/search/query-utils.js +0 -383
  231. package/dist/sync/git-hooks.d.ts +0 -54
  232. package/dist/sync/git-hooks.js +0 -223
  233. package/dist/sync/index.d.ts +0 -25
  234. package/dist/sync/index.js +0 -28
  235. package/dist/sync/watch-policy.d.ts +0 -51
  236. package/dist/sync/watch-policy.js +0 -124
  237. package/dist/sync/watcher.d.ts +0 -83
  238. package/dist/sync/watcher.js +0 -192
  239. package/dist/types.d.ts +0 -433
  240. package/dist/types.js +0 -75
  241. package/dist/ui/glyphs.d.ts +0 -42
  242. package/dist/ui/shimmer-progress.d.ts +0 -11
  243. package/dist/ui/shimmer-worker.d.ts +0 -2
  244. package/dist/ui/types.d.ts +0 -20
  245. package/dist/utils.d.ts +0 -231
  246. package/dist/utils.js +0 -549
package/dist/index.js DELETED
@@ -1,800 +0,0 @@
1
- "use strict";
2
- /**
3
- * CodeGraph
4
- *
5
- * A local-first code intelligence system that builds a semantic
6
- * knowledge graph from any codebase.
7
- */
8
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9
- if (k2 === undefined) k2 = k;
10
- var desc = Object.getOwnPropertyDescriptor(m, k);
11
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
12
- desc = { enumerable: true, get: function() { return m[k]; } };
13
- }
14
- Object.defineProperty(o, k2, desc);
15
- }) : (function(o, m, k, k2) {
16
- if (k2 === undefined) k2 = k;
17
- o[k2] = m[k];
18
- }));
19
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
20
- Object.defineProperty(o, "default", { enumerable: true, value: v });
21
- }) : function(o, v) {
22
- o["default"] = v;
23
- });
24
- var __importStar = (this && this.__importStar) || (function () {
25
- var ownKeys = function(o) {
26
- ownKeys = Object.getOwnPropertyNames || function (o) {
27
- var ar = [];
28
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
- return ar;
30
- };
31
- return ownKeys(o);
32
- };
33
- return function (mod) {
34
- if (mod && mod.__esModule) return mod;
35
- var result = {};
36
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
- __setModuleDefault(result, mod);
38
- return result;
39
- };
40
- })();
41
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
42
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
43
- };
44
- Object.defineProperty(exports, "__esModule", { value: true });
45
- exports.CodeGraph = exports.MCPServer = exports.FileWatcher = exports.MemoryMonitor = exports.throttle = exports.debounce = exports.processInBatches = exports.FileLock = exports.Mutex = exports.defaultLogger = exports.silentLogger = exports.getLogger = exports.setLogger = exports.ConfigError = exports.VectorError = exports.SearchError = exports.DatabaseError = exports.ParseError = exports.FileError = exports.CodeGraphError = exports.loadAllGrammars = exports.loadGrammarsForLanguages = exports.initGrammars = exports.getSupportedLanguages = exports.isGrammarLoaded = exports.isLanguageSupported = exports.detectLanguage = exports.CODEGRAPH_DIR = exports.findNearestCodeGraphRoot = exports.isInitialized = exports.getCodeGraphDir = exports.getDatabasePath = void 0;
46
- const path = __importStar(require("path"));
47
- const db_1 = require("./db");
48
- const queries_1 = require("./db/queries");
49
- const directory_1 = require("./directory");
50
- const extraction_1 = require("./extraction");
51
- const resolution_1 = require("./resolution");
52
- const graph_1 = require("./graph");
53
- const context_1 = require("./context");
54
- const utils_1 = require("./utils");
55
- const sync_1 = require("./sync");
56
- // Re-export types for consumers
57
- __exportStar(require("./types"), exports);
58
- var db_2 = require("./db");
59
- Object.defineProperty(exports, "getDatabasePath", { enumerable: true, get: function () { return db_2.getDatabasePath; } });
60
- var directory_2 = require("./directory");
61
- Object.defineProperty(exports, "getCodeGraphDir", { enumerable: true, get: function () { return directory_2.getCodeGraphDir; } });
62
- Object.defineProperty(exports, "isInitialized", { enumerable: true, get: function () { return directory_2.isInitialized; } });
63
- Object.defineProperty(exports, "findNearestCodeGraphRoot", { enumerable: true, get: function () { return directory_2.findNearestCodeGraphRoot; } });
64
- Object.defineProperty(exports, "CODEGRAPH_DIR", { enumerable: true, get: function () { return directory_2.CODEGRAPH_DIR; } });
65
- var extraction_2 = require("./extraction");
66
- Object.defineProperty(exports, "detectLanguage", { enumerable: true, get: function () { return extraction_2.detectLanguage; } });
67
- Object.defineProperty(exports, "isLanguageSupported", { enumerable: true, get: function () { return extraction_2.isLanguageSupported; } });
68
- Object.defineProperty(exports, "isGrammarLoaded", { enumerable: true, get: function () { return extraction_2.isGrammarLoaded; } });
69
- Object.defineProperty(exports, "getSupportedLanguages", { enumerable: true, get: function () { return extraction_2.getSupportedLanguages; } });
70
- Object.defineProperty(exports, "initGrammars", { enumerable: true, get: function () { return extraction_2.initGrammars; } });
71
- Object.defineProperty(exports, "loadGrammarsForLanguages", { enumerable: true, get: function () { return extraction_2.loadGrammarsForLanguages; } });
72
- Object.defineProperty(exports, "loadAllGrammars", { enumerable: true, get: function () { return extraction_2.loadAllGrammars; } });
73
- var errors_1 = require("./errors");
74
- Object.defineProperty(exports, "CodeGraphError", { enumerable: true, get: function () { return errors_1.CodeGraphError; } });
75
- Object.defineProperty(exports, "FileError", { enumerable: true, get: function () { return errors_1.FileError; } });
76
- Object.defineProperty(exports, "ParseError", { enumerable: true, get: function () { return errors_1.ParseError; } });
77
- Object.defineProperty(exports, "DatabaseError", { enumerable: true, get: function () { return errors_1.DatabaseError; } });
78
- Object.defineProperty(exports, "SearchError", { enumerable: true, get: function () { return errors_1.SearchError; } });
79
- Object.defineProperty(exports, "VectorError", { enumerable: true, get: function () { return errors_1.VectorError; } });
80
- Object.defineProperty(exports, "ConfigError", { enumerable: true, get: function () { return errors_1.ConfigError; } });
81
- Object.defineProperty(exports, "setLogger", { enumerable: true, get: function () { return errors_1.setLogger; } });
82
- Object.defineProperty(exports, "getLogger", { enumerable: true, get: function () { return errors_1.getLogger; } });
83
- Object.defineProperty(exports, "silentLogger", { enumerable: true, get: function () { return errors_1.silentLogger; } });
84
- Object.defineProperty(exports, "defaultLogger", { enumerable: true, get: function () { return errors_1.defaultLogger; } });
85
- var utils_2 = require("./utils");
86
- Object.defineProperty(exports, "Mutex", { enumerable: true, get: function () { return utils_2.Mutex; } });
87
- Object.defineProperty(exports, "FileLock", { enumerable: true, get: function () { return utils_2.FileLock; } });
88
- Object.defineProperty(exports, "processInBatches", { enumerable: true, get: function () { return utils_2.processInBatches; } });
89
- Object.defineProperty(exports, "debounce", { enumerable: true, get: function () { return utils_2.debounce; } });
90
- Object.defineProperty(exports, "throttle", { enumerable: true, get: function () { return utils_2.throttle; } });
91
- Object.defineProperty(exports, "MemoryMonitor", { enumerable: true, get: function () { return utils_2.MemoryMonitor; } });
92
- var sync_2 = require("./sync");
93
- Object.defineProperty(exports, "FileWatcher", { enumerable: true, get: function () { return sync_2.FileWatcher; } });
94
- /**
95
- * Main CodeGraph class
96
- *
97
- * Provides the primary interface for interacting with the code knowledge graph.
98
- */
99
- class CodeGraph {
100
- db;
101
- queries;
102
- projectRoot;
103
- orchestrator;
104
- resolver;
105
- graphManager;
106
- traverser;
107
- contextBuilder;
108
- // Mutex for preventing concurrent indexing operations (in-process)
109
- indexMutex = new utils_1.Mutex();
110
- // File lock for preventing concurrent writes across processes (CLI, MCP, git hooks)
111
- fileLock;
112
- // File watcher for auto-sync on file changes
113
- watcher = null;
114
- constructor(db, queries, projectRoot) {
115
- this.db = db;
116
- this.queries = queries;
117
- this.projectRoot = projectRoot;
118
- this.fileLock = new utils_1.FileLock(path.join(projectRoot, '.codegraph', 'codegraph.lock'));
119
- this.orchestrator = new extraction_1.ExtractionOrchestrator(projectRoot, queries);
120
- this.resolver = (0, resolution_1.createResolver)(projectRoot, queries);
121
- this.graphManager = new graph_1.GraphQueryManager(queries);
122
- this.traverser = new graph_1.GraphTraverser(queries);
123
- this.contextBuilder = (0, context_1.createContextBuilder)(projectRoot, queries, this.traverser);
124
- }
125
- // ===========================================================================
126
- // Lifecycle Methods
127
- // ===========================================================================
128
- /**
129
- * Initialize a new CodeGraph project
130
- *
131
- * Creates the .CodeGraph directory, database, and configuration.
132
- *
133
- * @param projectRoot - Path to the project root directory
134
- * @param options - Initialization options
135
- * @returns A new CodeGraph instance
136
- */
137
- static async init(projectRoot, options = {}) {
138
- await (0, extraction_1.initGrammars)();
139
- const resolvedRoot = path.resolve(projectRoot);
140
- // Check if already initialized
141
- if ((0, directory_1.isInitialized)(resolvedRoot)) {
142
- throw new Error(`CodeGraph already initialized in ${resolvedRoot}`);
143
- }
144
- // Create directory structure
145
- (0, directory_1.createDirectory)(resolvedRoot);
146
- // Initialize database
147
- const dbPath = (0, db_1.getDatabasePath)(resolvedRoot);
148
- const db = db_1.DatabaseConnection.initialize(dbPath);
149
- const queries = new queries_1.QueryBuilder(db.getDb());
150
- const instance = new CodeGraph(db, queries, resolvedRoot);
151
- // Run initial indexing if requested
152
- if (options.index) {
153
- await instance.indexAll({ onProgress: options.onProgress });
154
- }
155
- return instance;
156
- }
157
- /**
158
- * Initialize synchronously (without indexing)
159
- */
160
- static initSync(projectRoot) {
161
- const resolvedRoot = path.resolve(projectRoot);
162
- // Check if already initialized
163
- if ((0, directory_1.isInitialized)(resolvedRoot)) {
164
- throw new Error(`CodeGraph already initialized in ${resolvedRoot}`);
165
- }
166
- // Create directory structure
167
- (0, directory_1.createDirectory)(resolvedRoot);
168
- // Initialize database
169
- const dbPath = (0, db_1.getDatabasePath)(resolvedRoot);
170
- const db = db_1.DatabaseConnection.initialize(dbPath);
171
- const queries = new queries_1.QueryBuilder(db.getDb());
172
- return new CodeGraph(db, queries, resolvedRoot);
173
- }
174
- /**
175
- * Open an existing CodeGraph project
176
- *
177
- * @param projectRoot - Path to the project root directory
178
- * @param options - Open options
179
- * @returns A CodeGraph instance
180
- */
181
- static async open(projectRoot, options = {}) {
182
- await (0, extraction_1.initGrammars)();
183
- const resolvedRoot = path.resolve(projectRoot);
184
- // Check if initialized
185
- if (!(0, directory_1.isInitialized)(resolvedRoot)) {
186
- throw new Error(`CodeGraph not initialized in ${resolvedRoot}. Run init() first.`);
187
- }
188
- // Validate directory structure
189
- const validation = (0, directory_1.validateDirectory)(resolvedRoot);
190
- if (!validation.valid) {
191
- throw new Error(`Invalid CodeGraph directory: ${validation.errors.join(', ')}`);
192
- }
193
- // Open database
194
- const dbPath = (0, db_1.getDatabasePath)(resolvedRoot);
195
- const db = db_1.DatabaseConnection.open(dbPath);
196
- const queries = new queries_1.QueryBuilder(db.getDb());
197
- const instance = new CodeGraph(db, queries, resolvedRoot);
198
- // Sync if requested
199
- if (options.sync) {
200
- await instance.sync();
201
- }
202
- return instance;
203
- }
204
- /**
205
- * Open synchronously (without sync)
206
- */
207
- static openSync(projectRoot) {
208
- const resolvedRoot = path.resolve(projectRoot);
209
- // Check if initialized
210
- if (!(0, directory_1.isInitialized)(resolvedRoot)) {
211
- throw new Error(`CodeGraph not initialized in ${resolvedRoot}. Run init() first.`);
212
- }
213
- // Validate directory structure
214
- const validation = (0, directory_1.validateDirectory)(resolvedRoot);
215
- if (!validation.valid) {
216
- throw new Error(`Invalid CodeGraph directory: ${validation.errors.join(', ')}`);
217
- }
218
- // Open database
219
- const dbPath = (0, db_1.getDatabasePath)(resolvedRoot);
220
- const db = db_1.DatabaseConnection.open(dbPath);
221
- const queries = new queries_1.QueryBuilder(db.getDb());
222
- return new CodeGraph(db, queries, resolvedRoot);
223
- }
224
- /**
225
- * Check if a directory has been initialized as a CodeGraph project
226
- */
227
- static isInitialized(projectRoot) {
228
- return (0, directory_1.isInitialized)(path.resolve(projectRoot));
229
- }
230
- /**
231
- * Close the CodeGraph instance and release resources
232
- */
233
- close() {
234
- this.unwatch();
235
- // Release file lock if held
236
- this.fileLock.release();
237
- this.db.close();
238
- }
239
- /**
240
- * Get the project root directory
241
- */
242
- getProjectRoot() {
243
- return this.projectRoot;
244
- }
245
- // ===========================================================================
246
- // Indexing
247
- // ===========================================================================
248
- /**
249
- * Index all files in the project
250
- *
251
- * Uses a mutex to prevent concurrent indexing operations.
252
- */
253
- async indexAll(options = {}) {
254
- return this.indexMutex.withLock(async () => {
255
- try {
256
- this.fileLock.acquire();
257
- }
258
- catch {
259
- return { success: false, filesIndexed: 0, filesSkipped: 0, filesErrored: 0, nodesCreated: 0, edgesCreated: 0, errors: [{ message: 'Could not acquire file lock - another process may be indexing', severity: 'error' }], durationMs: 0 };
260
- }
261
- try {
262
- const result = await this.orchestrator.indexAll(options.onProgress, options.signal, options.verbose);
263
- // Resolve references to create call/import/extends edges
264
- if (result.success && result.filesIndexed > 0) {
265
- // Get count without loading all refs into memory
266
- const unresolvedCount = this.queries.getUnresolvedReferencesCount();
267
- options.onProgress?.({
268
- phase: 'resolving',
269
- current: 0,
270
- total: unresolvedCount,
271
- });
272
- await this.resolveReferencesBatched((current, total) => {
273
- options.onProgress?.({
274
- phase: 'resolving',
275
- current,
276
- total,
277
- });
278
- });
279
- }
280
- // Refresh planner stats + checkpoint the WAL after bulk writes.
281
- // Cheap and non-blocking; never load-bearing for correctness.
282
- if (result.success && result.filesIndexed > 0) {
283
- this.db.runMaintenance();
284
- }
285
- return result;
286
- }
287
- finally {
288
- this.fileLock.release();
289
- }
290
- });
291
- }
292
- /**
293
- * Index specific files
294
- *
295
- * Uses a mutex to prevent concurrent indexing operations.
296
- */
297
- async indexFiles(filePaths) {
298
- return this.indexMutex.withLock(async () => {
299
- try {
300
- this.fileLock.acquire();
301
- }
302
- catch {
303
- return { success: false, filesIndexed: 0, filesSkipped: 0, filesErrored: 0, nodesCreated: 0, edgesCreated: 0, errors: [{ message: 'Could not acquire file lock - another process may be indexing', severity: 'error' }], durationMs: 0 };
304
- }
305
- try {
306
- return this.orchestrator.indexFiles(filePaths);
307
- }
308
- finally {
309
- this.fileLock.release();
310
- }
311
- });
312
- }
313
- /**
314
- * Sync with current file state (incremental update)
315
- *
316
- * Uses a mutex to prevent concurrent indexing operations.
317
- */
318
- async sync(options = {}) {
319
- return this.indexMutex.withLock(async () => {
320
- try {
321
- this.fileLock.acquire();
322
- }
323
- catch {
324
- return { filesChecked: 0, filesAdded: 0, filesModified: 0, filesRemoved: 0, nodesUpdated: 0, durationMs: 0 };
325
- }
326
- try {
327
- const result = await this.orchestrator.sync(options.onProgress);
328
- // Resolve references if files were updated
329
- if (result.filesAdded > 0 || result.filesModified > 0) {
330
- if (result.changedFilePaths) {
331
- // Scope resolution to changed files (git fast path — bounded set)
332
- const unresolvedRefs = this.queries.getUnresolvedReferencesByFiles(result.changedFilePaths);
333
- options.onProgress?.({
334
- phase: 'resolving',
335
- current: 0,
336
- total: unresolvedRefs.length,
337
- });
338
- this.resolver.resolveAndPersist(unresolvedRefs, (current, total) => {
339
- options.onProgress?.({
340
- phase: 'resolving',
341
- current,
342
- total,
343
- });
344
- });
345
- }
346
- else {
347
- // No git info — use batched resolution to avoid OOM
348
- const unresolvedCount = this.queries.getUnresolvedReferencesCount();
349
- options.onProgress?.({
350
- phase: 'resolving',
351
- current: 0,
352
- total: unresolvedCount,
353
- });
354
- await this.resolveReferencesBatched((current, total) => {
355
- options.onProgress?.({
356
- phase: 'resolving',
357
- current,
358
- total,
359
- });
360
- });
361
- }
362
- }
363
- // Refresh planner stats + checkpoint the WAL after bulk writes.
364
- if (result.filesAdded > 0 || result.filesModified > 0 || result.filesRemoved > 0) {
365
- this.db.runMaintenance();
366
- }
367
- return result;
368
- }
369
- finally {
370
- this.fileLock.release();
371
- }
372
- });
373
- }
374
- /**
375
- * Check if an indexing operation is currently in progress
376
- */
377
- isIndexing() {
378
- return this.indexMutex.isLocked();
379
- }
380
- // ===========================================================================
381
- // File Watching
382
- // ===========================================================================
383
- /**
384
- * Start watching for file changes and auto-syncing.
385
- *
386
- * Uses native OS file events (FSEvents on macOS, inotify on Linux 19+,
387
- * ReadDirectoryChangesW on Windows) with debouncing to avoid thrashing.
388
- *
389
- * @param options - Watch options (debounce delay, callbacks)
390
- * @returns true if watching started successfully
391
- */
392
- watch(options = {}) {
393
- if (this.watcher?.isActive())
394
- return true;
395
- this.watcher = new sync_1.FileWatcher(this.projectRoot, async () => {
396
- const result = await this.sync();
397
- const filesChanged = result.filesAdded + result.filesModified + result.filesRemoved;
398
- return { filesChanged, durationMs: result.durationMs };
399
- }, options);
400
- return this.watcher.start();
401
- }
402
- /**
403
- * Stop watching for file changes.
404
- */
405
- unwatch() {
406
- if (this.watcher) {
407
- this.watcher.stop();
408
- this.watcher = null;
409
- }
410
- }
411
- /**
412
- * Check if the file watcher is active.
413
- */
414
- isWatching() {
415
- return this.watcher?.isActive() ?? false;
416
- }
417
- /**
418
- * Get files that have changed since last index
419
- */
420
- getChangedFiles() {
421
- return this.orchestrator.getChangedFiles();
422
- }
423
- /**
424
- * Extract nodes and edges from source code (without storing)
425
- */
426
- extractFromSource(filePath, source) {
427
- return (0, extraction_1.extractFromSource)(filePath, source);
428
- }
429
- // ===========================================================================
430
- // Reference Resolution
431
- // ===========================================================================
432
- /**
433
- * Resolve unresolved references and create edges
434
- *
435
- * This method takes unresolved references from extraction and attempts
436
- * to resolve them using multiple strategies:
437
- * - Framework-specific patterns (React, Express, Laravel)
438
- * - Import-based resolution
439
- * - Name-based symbol matching
440
- */
441
- resolveReferences(onProgress) {
442
- // Get all unresolved references from the database
443
- const unresolvedRefs = this.queries.getUnresolvedReferences();
444
- return this.resolver.resolveAndPersist(unresolvedRefs, onProgress);
445
- }
446
- /**
447
- * Resolve references in batches to keep memory bounded on large codebases.
448
- * Processes chunks of unresolved refs, persisting results after each batch.
449
- */
450
- async resolveReferencesBatched(onProgress) {
451
- return this.resolver.resolveAndPersistBatched(onProgress);
452
- }
453
- /**
454
- * Get detected frameworks in the project
455
- */
456
- getDetectedFrameworks() {
457
- return this.resolver.getDetectedFrameworks();
458
- }
459
- /**
460
- * Re-initialize the resolver (useful after adding new files)
461
- */
462
- reinitializeResolver() {
463
- this.resolver.initialize();
464
- }
465
- // ===========================================================================
466
- // Graph Statistics
467
- // ===========================================================================
468
- /**
469
- * Get statistics about the knowledge graph
470
- */
471
- getStats() {
472
- const stats = this.queries.getStats();
473
- stats.dbSizeBytes = this.db.getSize();
474
- return stats;
475
- }
476
- /**
477
- * Active SQLite backend for this project's connection (`node-sqlite` — Node's
478
- * built-in real-SQLite module). Surfaced via `codegraph status` and the
479
- * `codegraph_status` MCP tool alongside the effective journal mode.
480
- */
481
- getBackend() {
482
- return this.db.getBackend();
483
- }
484
- /**
485
- * The journal mode actually in effect ('wal', 'delete', …). 'wal' means
486
- * readers never block on a concurrent writer; anything else means they can,
487
- * which is the precondition for the "database is locked" failures in issue
488
- * #238. Surfaced via `codegraph status` and the `codegraph_status` MCP tool.
489
- */
490
- getJournalMode() {
491
- return this.db.getJournalMode();
492
- }
493
- // ===========================================================================
494
- // Node Operations
495
- // ===========================================================================
496
- /**
497
- * Get a node by ID
498
- */
499
- getNode(id) {
500
- return this.queries.getNodeById(id);
501
- }
502
- /**
503
- * Get all nodes in a file
504
- */
505
- getNodesInFile(filePath) {
506
- return this.queries.getNodesByFile(filePath);
507
- }
508
- /**
509
- * Get all nodes of a specific kind
510
- */
511
- getNodesByKind(kind) {
512
- return this.queries.getNodesByKind(kind);
513
- }
514
- /**
515
- * Search nodes by text
516
- */
517
- searchNodes(query, options) {
518
- return this.queries.searchNodes(query, options);
519
- }
520
- // ===========================================================================
521
- // Edge Operations
522
- // ===========================================================================
523
- /**
524
- * Get outgoing edges from a node
525
- */
526
- getOutgoingEdges(nodeId) {
527
- return this.queries.getOutgoingEdges(nodeId);
528
- }
529
- /**
530
- * Get incoming edges to a node
531
- */
532
- getIncomingEdges(nodeId) {
533
- return this.queries.getIncomingEdges(nodeId);
534
- }
535
- // ===========================================================================
536
- // File Operations
537
- // ===========================================================================
538
- /**
539
- * Get a file record by path
540
- */
541
- getFile(filePath) {
542
- return this.queries.getFileByPath(filePath);
543
- }
544
- /**
545
- * Get all tracked files
546
- */
547
- getFiles() {
548
- return this.queries.getAllFiles();
549
- }
550
- // ===========================================================================
551
- // Graph Query Methods
552
- // ===========================================================================
553
- /**
554
- * Get the context for a node (ancestors, children, references)
555
- *
556
- * Returns comprehensive context about a node including its containment
557
- * hierarchy, children, incoming/outgoing references, type information,
558
- * and relevant imports.
559
- *
560
- * @param nodeId - ID of the focal node
561
- * @returns Context object with all related information
562
- */
563
- getContext(nodeId) {
564
- return this.graphManager.getContext(nodeId);
565
- }
566
- /**
567
- * Traverse the graph from a starting node
568
- *
569
- * Uses breadth-first search by default. Supports filtering by edge types,
570
- * node types, and traversal direction.
571
- *
572
- * @param startId - Starting node ID
573
- * @param options - Traversal options
574
- * @returns Subgraph containing traversed nodes and edges
575
- */
576
- traverse(startId, options) {
577
- return this.traverser.traverseBFS(startId, options);
578
- }
579
- /**
580
- * Get the call graph for a function
581
- *
582
- * Returns both callers (functions that call this function) and
583
- * callees (functions called by this function) up to the specified depth.
584
- *
585
- * @param nodeId - ID of the function/method node
586
- * @param depth - Maximum depth in each direction (default: 2)
587
- * @returns Subgraph containing the call graph
588
- */
589
- getCallGraph(nodeId, depth = 2) {
590
- return this.traverser.getCallGraph(nodeId, depth);
591
- }
592
- /**
593
- * Get the type hierarchy for a class/interface
594
- *
595
- * Returns both ancestors (types this extends/implements) and
596
- * descendants (types that extend/implement this).
597
- *
598
- * @param nodeId - ID of the class/interface node
599
- * @returns Subgraph containing the type hierarchy
600
- */
601
- getTypeHierarchy(nodeId) {
602
- return this.traverser.getTypeHierarchy(nodeId);
603
- }
604
- /**
605
- * Find all usages of a symbol
606
- *
607
- * Returns all nodes that reference the specified symbol through
608
- * any edge type (calls, references, type_of, etc.).
609
- *
610
- * @param nodeId - ID of the symbol node
611
- * @returns Array of nodes and edges that reference this symbol
612
- */
613
- findUsages(nodeId) {
614
- return this.traverser.findUsages(nodeId);
615
- }
616
- /**
617
- * Get callers of a function/method
618
- *
619
- * @param nodeId - ID of the function/method node
620
- * @param maxDepth - Maximum depth to traverse (default: 1)
621
- * @returns Array of nodes that call this function
622
- */
623
- getCallers(nodeId, maxDepth = 1) {
624
- return this.traverser.getCallers(nodeId, maxDepth);
625
- }
626
- /**
627
- * Get callees of a function/method
628
- *
629
- * @param nodeId - ID of the function/method node
630
- * @param maxDepth - Maximum depth to traverse (default: 1)
631
- * @returns Array of nodes called by this function
632
- */
633
- getCallees(nodeId, maxDepth = 1) {
634
- return this.traverser.getCallees(nodeId, maxDepth);
635
- }
636
- /**
637
- * Calculate the impact radius of a node
638
- *
639
- * Returns all nodes that could be affected by changes to this node.
640
- *
641
- * @param nodeId - ID of the node
642
- * @param maxDepth - Maximum depth to traverse (default: 3)
643
- * @returns Subgraph containing potentially impacted nodes
644
- */
645
- getImpactRadius(nodeId, maxDepth = 3) {
646
- return this.traverser.getImpactRadius(nodeId, maxDepth);
647
- }
648
- /**
649
- * Find the shortest path between two nodes
650
- *
651
- * @param fromId - Starting node ID
652
- * @param toId - Target node ID
653
- * @param edgeKinds - Edge types to consider (all if empty)
654
- * @returns Array of nodes and edges forming the path, or null if no path exists
655
- */
656
- findPath(fromId, toId, edgeKinds) {
657
- return this.traverser.findPath(fromId, toId, edgeKinds);
658
- }
659
- /**
660
- * Get ancestors of a node in the containment hierarchy
661
- *
662
- * @param nodeId - ID of the node
663
- * @returns Array of ancestor nodes from immediate parent to root
664
- */
665
- getAncestors(nodeId) {
666
- return this.traverser.getAncestors(nodeId);
667
- }
668
- /**
669
- * Get immediate children of a node
670
- *
671
- * @param nodeId - ID of the node
672
- * @returns Array of child nodes
673
- */
674
- getChildren(nodeId) {
675
- return this.traverser.getChildren(nodeId);
676
- }
677
- /**
678
- * Get dependencies of a file
679
- *
680
- * @param filePath - Path to the file
681
- * @returns Array of file paths this file depends on
682
- */
683
- getFileDependencies(filePath) {
684
- return this.graphManager.getFileDependencies(filePath);
685
- }
686
- /**
687
- * Get dependents of a file
688
- *
689
- * @param filePath - Path to the file
690
- * @returns Array of file paths that depend on this file
691
- */
692
- getFileDependents(filePath) {
693
- return this.graphManager.getFileDependents(filePath);
694
- }
695
- /**
696
- * Find circular dependencies in the codebase
697
- *
698
- * @returns Array of cycles, each cycle is an array of file paths
699
- */
700
- findCircularDependencies() {
701
- return this.graphManager.findCircularDependencies();
702
- }
703
- /**
704
- * Find dead code (unreferenced symbols)
705
- *
706
- * @param kinds - Node kinds to check (default: functions, methods, classes)
707
- * @returns Array of unreferenced nodes
708
- */
709
- findDeadCode(kinds) {
710
- return this.graphManager.findDeadCode(kinds);
711
- }
712
- /**
713
- * Get complexity metrics for a node
714
- *
715
- * @param nodeId - ID of the node
716
- * @returns Object containing various complexity metrics
717
- */
718
- getNodeMetrics(nodeId) {
719
- return this.graphManager.getNodeMetrics(nodeId);
720
- }
721
- // ===========================================================================
722
- // Context Building
723
- // ===========================================================================
724
- /**
725
- * Get the source code for a node
726
- *
727
- * Reads the file and extracts the code between startLine and endLine.
728
- *
729
- * @param nodeId - ID of the node
730
- * @returns Code string or null if not found
731
- */
732
- async getCode(nodeId) {
733
- return this.contextBuilder.getCode(nodeId);
734
- }
735
- /**
736
- * Find relevant subgraph for a query
737
- *
738
- * Combines semantic search with graph traversal to find the most
739
- * relevant nodes and their relationships for a given query.
740
- *
741
- * @param query - Natural language query describing the task
742
- * @param options - Search and traversal options
743
- * @returns Subgraph of relevant nodes and edges
744
- */
745
- async findRelevantContext(query, options) {
746
- return this.contextBuilder.findRelevantContext(query, options);
747
- }
748
- /**
749
- * Build context for a task
750
- *
751
- * Creates comprehensive context by:
752
- * 1. Running FTS search to find entry points
753
- * 2. Expanding the graph around entry points
754
- * 3. Extracting code blocks for key nodes
755
- * 4. Formatting output for Claude
756
- *
757
- * @param input - Task description (string or {title, description})
758
- * @param options - Build options (maxNodes, includeCode, format, etc.)
759
- * @returns TaskContext object or formatted string (markdown/JSON)
760
- */
761
- async buildContext(input, options) {
762
- return this.contextBuilder.buildContext(input, options);
763
- }
764
- // ===========================================================================
765
- // Database Management
766
- // ===========================================================================
767
- /**
768
- * Optimize the database (vacuum and analyze)
769
- */
770
- optimize() {
771
- this.db.optimize();
772
- }
773
- /**
774
- * Clear all data from the graph
775
- */
776
- clear() {
777
- this.queries.clear();
778
- }
779
- /**
780
- * Alias for close() for backwards compatibility.
781
- * @deprecated Use close() instead
782
- */
783
- destroy() {
784
- this.close();
785
- }
786
- /**
787
- * Completely remove CodeGraph from the project.
788
- * This closes the database and deletes the .CodeGraph directory.
789
- *
790
- * WARNING: This permanently deletes all CodeGraph data for the project.
791
- */
792
- uninitialize() {
793
- this.close();
794
- (0, directory_1.removeDirectory)(this.projectRoot);
795
- }
796
- }
797
- exports.CodeGraph = CodeGraph;
798
- // Default export
799
- exports.default = CodeGraph;
800
- //# sourceMappingURL=index.js.map