@saluzi/codegraph 0.2.0 → 0.2.2

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 (658) hide show
  1. package/README.md +2 -2
  2. package/dist/bin/codegraph.d.ts +26 -0
  3. package/dist/bin/codegraph.d.ts.map +1 -0
  4. package/dist/bin/codegraph.js +2249 -0
  5. package/dist/bin/codegraph.js.map +1 -0
  6. package/dist/bin/command-supervision.d.ts +49 -0
  7. package/dist/bin/command-supervision.d.ts.map +1 -0
  8. package/dist/bin/command-supervision.js +95 -0
  9. package/dist/bin/command-supervision.js.map +1 -0
  10. package/dist/bin/fatal-handler.d.ts +20 -0
  11. package/dist/bin/fatal-handler.d.ts.map +1 -0
  12. package/dist/bin/fatal-handler.js +118 -0
  13. package/dist/bin/fatal-handler.js.map +1 -0
  14. package/dist/bin/node-version-check.d.ts +37 -0
  15. package/dist/bin/node-version-check.d.ts.map +1 -0
  16. package/dist/bin/node-version-check.js +79 -0
  17. package/dist/bin/node-version-check.js.map +1 -0
  18. package/dist/bin/uninstall.d.ts +14 -0
  19. package/dist/bin/uninstall.d.ts.map +1 -0
  20. package/dist/bin/uninstall.js +36 -0
  21. package/dist/bin/uninstall.js.map +1 -0
  22. package/dist/context/formatter.d.ts +30 -0
  23. package/dist/context/formatter.d.ts.map +1 -0
  24. package/dist/context/formatter.js +263 -0
  25. package/dist/context/formatter.js.map +1 -0
  26. package/dist/context/index.d.ts +119 -0
  27. package/dist/context/index.d.ts.map +1 -0
  28. package/dist/context/index.js +1296 -0
  29. package/dist/context/index.js.map +1 -0
  30. package/dist/context/markers.d.ts +19 -0
  31. package/dist/context/markers.d.ts.map +1 -0
  32. package/dist/context/markers.js +22 -0
  33. package/dist/context/markers.js.map +1 -0
  34. package/dist/db/index.d.ts +201 -0
  35. package/dist/db/index.d.ts.map +1 -0
  36. package/dist/db/index.js +493 -0
  37. package/dist/db/index.js.map +1 -0
  38. package/dist/db/migrations.d.ts +44 -0
  39. package/dist/db/migrations.d.ts.map +1 -0
  40. package/dist/db/migrations.js +212 -0
  41. package/dist/db/migrations.js.map +1 -0
  42. package/dist/db/queries.d.ts +513 -0
  43. package/dist/db/queries.d.ts.map +1 -0
  44. package/dist/db/queries.js +1886 -0
  45. package/dist/db/queries.js.map +1 -0
  46. package/dist/db/schema.sql +194 -0
  47. package/dist/db/sqlite-adapter.d.ts +65 -0
  48. package/dist/db/sqlite-adapter.d.ts.map +1 -0
  49. package/dist/db/sqlite-adapter.js +274 -0
  50. package/dist/db/sqlite-adapter.js.map +1 -0
  51. package/dist/db/wal-valve.d.ts +106 -0
  52. package/dist/db/wal-valve.d.ts.map +1 -0
  53. package/dist/db/wal-valve.js +208 -0
  54. package/dist/db/wal-valve.js.map +1 -0
  55. package/dist/directory.d.ts +183 -0
  56. package/dist/directory.d.ts.map +1 -0
  57. package/dist/directory.js +797 -0
  58. package/dist/directory.js.map +1 -0
  59. package/dist/errors.d.ts +136 -0
  60. package/dist/errors.d.ts.map +1 -0
  61. package/dist/errors.js +219 -0
  62. package/dist/errors.js.map +1 -0
  63. package/dist/extraction/astro-extractor.d.ts +79 -0
  64. package/dist/extraction/astro-extractor.d.ts.map +1 -0
  65. package/dist/extraction/astro-extractor.js +320 -0
  66. package/dist/extraction/astro-extractor.js.map +1 -0
  67. package/dist/extraction/cfml-extractor.d.ts +107 -0
  68. package/dist/extraction/cfml-extractor.d.ts.map +1 -0
  69. package/dist/extraction/cfml-extractor.js +494 -0
  70. package/dist/extraction/cfml-extractor.js.map +1 -0
  71. package/dist/extraction/dfm-extractor.d.ts +31 -0
  72. package/dist/extraction/dfm-extractor.d.ts.map +1 -0
  73. package/dist/extraction/dfm-extractor.js +151 -0
  74. package/dist/extraction/dfm-extractor.js.map +1 -0
  75. package/dist/extraction/extraction-version.d.ts +25 -0
  76. package/dist/extraction/extraction-version.d.ts.map +1 -0
  77. package/dist/extraction/extraction-version.js +28 -0
  78. package/dist/extraction/extraction-version.js.map +1 -0
  79. package/dist/extraction/function-ref.d.ts +118 -0
  80. package/dist/extraction/function-ref.d.ts.map +1 -0
  81. package/dist/extraction/function-ref.js +727 -0
  82. package/dist/extraction/function-ref.js.map +1 -0
  83. package/dist/extraction/generated-detection.d.ts +30 -0
  84. package/dist/extraction/generated-detection.d.ts.map +1 -0
  85. package/dist/extraction/generated-detection.js +83 -0
  86. package/dist/extraction/generated-detection.js.map +1 -0
  87. package/dist/extraction/grammars.d.ts +138 -0
  88. package/dist/extraction/grammars.d.ts.map +1 -0
  89. package/dist/extraction/grammars.js +631 -0
  90. package/dist/extraction/grammars.js.map +1 -0
  91. package/dist/extraction/index.d.ts +232 -0
  92. package/dist/extraction/index.d.ts.map +1 -0
  93. package/dist/extraction/index.js +2409 -0
  94. package/dist/extraction/index.js.map +1 -0
  95. package/dist/extraction/languages/arkts.d.ts +3 -0
  96. package/dist/extraction/languages/arkts.d.ts.map +1 -0
  97. package/dist/extraction/languages/arkts.js +127 -0
  98. package/dist/extraction/languages/arkts.js.map +1 -0
  99. package/dist/extraction/languages/c-cpp.d.ts +110 -0
  100. package/dist/extraction/languages/c-cpp.d.ts.map +1 -0
  101. package/dist/extraction/languages/c-cpp.js +837 -0
  102. package/dist/extraction/languages/c-cpp.js.map +1 -0
  103. package/dist/extraction/languages/cfquery.d.ts +12 -0
  104. package/dist/extraction/languages/cfquery.d.ts.map +1 -0
  105. package/dist/extraction/languages/cfquery.js +28 -0
  106. package/dist/extraction/languages/cfquery.js.map +1 -0
  107. package/dist/extraction/languages/cfscript.d.ts +3 -0
  108. package/dist/extraction/languages/cfscript.d.ts.map +1 -0
  109. package/dist/extraction/languages/cfscript.js +73 -0
  110. package/dist/extraction/languages/cfscript.js.map +1 -0
  111. package/dist/extraction/languages/cobol.d.ts +33 -0
  112. package/dist/extraction/languages/cobol.d.ts.map +1 -0
  113. package/dist/extraction/languages/cobol.js +499 -0
  114. package/dist/extraction/languages/cobol.js.map +1 -0
  115. package/dist/extraction/languages/csharp.d.ts +25 -0
  116. package/dist/extraction/languages/csharp.d.ts.map +1 -0
  117. package/dist/extraction/languages/csharp.js +175 -0
  118. package/dist/extraction/languages/csharp.js.map +1 -0
  119. package/dist/extraction/languages/dart.d.ts +3 -0
  120. package/dist/extraction/languages/dart.d.ts.map +1 -0
  121. package/dist/extraction/languages/dart.js +374 -0
  122. package/dist/extraction/languages/dart.js.map +1 -0
  123. package/dist/extraction/languages/erlang.d.ts +3 -0
  124. package/dist/extraction/languages/erlang.d.ts.map +1 -0
  125. package/dist/extraction/languages/erlang.js +350 -0
  126. package/dist/extraction/languages/erlang.js.map +1 -0
  127. package/dist/extraction/languages/go.d.ts +3 -0
  128. package/dist/extraction/languages/go.d.ts.map +1 -0
  129. package/dist/extraction/languages/go.js +111 -0
  130. package/dist/extraction/languages/go.js.map +1 -0
  131. package/dist/extraction/languages/index.d.ts +10 -0
  132. package/dist/extraction/languages/index.d.ts.map +1 -0
  133. package/dist/extraction/languages/index.js +71 -0
  134. package/dist/extraction/languages/index.js.map +1 -0
  135. package/dist/extraction/languages/java.d.ts +3 -0
  136. package/dist/extraction/languages/java.d.ts.map +1 -0
  137. package/dist/extraction/languages/java.js +315 -0
  138. package/dist/extraction/languages/java.js.map +1 -0
  139. package/dist/extraction/languages/javascript.d.ts +3 -0
  140. package/dist/extraction/languages/javascript.d.ts.map +1 -0
  141. package/dist/extraction/languages/javascript.js +106 -0
  142. package/dist/extraction/languages/javascript.js.map +1 -0
  143. package/dist/extraction/languages/kotlin.d.ts +3 -0
  144. package/dist/extraction/languages/kotlin.d.ts.map +1 -0
  145. package/dist/extraction/languages/kotlin.js +379 -0
  146. package/dist/extraction/languages/kotlin.js.map +1 -0
  147. package/dist/extraction/languages/lua.d.ts +3 -0
  148. package/dist/extraction/languages/lua.d.ts.map +1 -0
  149. package/dist/extraction/languages/lua.js +150 -0
  150. package/dist/extraction/languages/lua.js.map +1 -0
  151. package/dist/extraction/languages/luau.d.ts +3 -0
  152. package/dist/extraction/languages/luau.d.ts.map +1 -0
  153. package/dist/extraction/languages/luau.js +37 -0
  154. package/dist/extraction/languages/luau.js.map +1 -0
  155. package/dist/extraction/languages/nix.d.ts +3 -0
  156. package/dist/extraction/languages/nix.d.ts.map +1 -0
  157. package/dist/extraction/languages/nix.js +294 -0
  158. package/dist/extraction/languages/nix.js.map +1 -0
  159. package/dist/extraction/languages/objc.d.ts +3 -0
  160. package/dist/extraction/languages/objc.d.ts.map +1 -0
  161. package/dist/extraction/languages/objc.js +175 -0
  162. package/dist/extraction/languages/objc.js.map +1 -0
  163. package/dist/extraction/languages/pascal.d.ts +3 -0
  164. package/dist/extraction/languages/pascal.d.ts.map +1 -0
  165. package/dist/extraction/languages/pascal.js +77 -0
  166. package/dist/extraction/languages/pascal.js.map +1 -0
  167. package/dist/extraction/languages/php.d.ts +3 -0
  168. package/dist/extraction/languages/php.d.ts.map +1 -0
  169. package/dist/extraction/languages/php.js +196 -0
  170. package/dist/extraction/languages/php.js.map +1 -0
  171. package/dist/extraction/languages/python.d.ts +3 -0
  172. package/dist/extraction/languages/python.d.ts.map +1 -0
  173. package/dist/extraction/languages/python.js +56 -0
  174. package/dist/extraction/languages/python.js.map +1 -0
  175. package/dist/extraction/languages/r.d.ts +3 -0
  176. package/dist/extraction/languages/r.d.ts.map +1 -0
  177. package/dist/extraction/languages/r.js +314 -0
  178. package/dist/extraction/languages/r.js.map +1 -0
  179. package/dist/extraction/languages/ruby.d.ts +3 -0
  180. package/dist/extraction/languages/ruby.d.ts.map +1 -0
  181. package/dist/extraction/languages/ruby.js +149 -0
  182. package/dist/extraction/languages/ruby.js.map +1 -0
  183. package/dist/extraction/languages/rust.d.ts +3 -0
  184. package/dist/extraction/languages/rust.d.ts.map +1 -0
  185. package/dist/extraction/languages/rust.js +142 -0
  186. package/dist/extraction/languages/rust.js.map +1 -0
  187. package/dist/extraction/languages/scala.d.ts +3 -0
  188. package/dist/extraction/languages/scala.d.ts.map +1 -0
  189. package/dist/extraction/languages/scala.js +209 -0
  190. package/dist/extraction/languages/scala.js.map +1 -0
  191. package/dist/extraction/languages/solidity.d.ts +3 -0
  192. package/dist/extraction/languages/solidity.d.ts.map +1 -0
  193. package/dist/extraction/languages/solidity.js +293 -0
  194. package/dist/extraction/languages/solidity.js.map +1 -0
  195. package/dist/extraction/languages/swift.d.ts +3 -0
  196. package/dist/extraction/languages/swift.d.ts.map +1 -0
  197. package/dist/extraction/languages/swift.js +152 -0
  198. package/dist/extraction/languages/swift.js.map +1 -0
  199. package/dist/extraction/languages/terraform.d.ts +3 -0
  200. package/dist/extraction/languages/terraform.d.ts.map +1 -0
  201. package/dist/extraction/languages/terraform.js +641 -0
  202. package/dist/extraction/languages/terraform.js.map +1 -0
  203. package/dist/extraction/languages/typescript.d.ts +16 -0
  204. package/dist/extraction/languages/typescript.d.ts.map +1 -0
  205. package/dist/extraction/languages/typescript.js +167 -0
  206. package/dist/extraction/languages/typescript.js.map +1 -0
  207. package/dist/extraction/languages/vbnet.d.ts +11 -0
  208. package/dist/extraction/languages/vbnet.d.ts.map +1 -0
  209. package/dist/extraction/languages/vbnet.js +141 -0
  210. package/dist/extraction/languages/vbnet.js.map +1 -0
  211. package/dist/extraction/liquid-extractor.d.ts +59 -0
  212. package/dist/extraction/liquid-extractor.d.ts.map +1 -0
  213. package/dist/extraction/liquid-extractor.js +357 -0
  214. package/dist/extraction/liquid-extractor.js.map +1 -0
  215. package/dist/extraction/mybatis-extractor.d.ts +68 -0
  216. package/dist/extraction/mybatis-extractor.d.ts.map +1 -0
  217. package/dist/extraction/mybatis-extractor.js +300 -0
  218. package/dist/extraction/mybatis-extractor.js.map +1 -0
  219. package/dist/extraction/parse-pool.d.ts +152 -0
  220. package/dist/extraction/parse-pool.d.ts.map +1 -0
  221. package/dist/extraction/parse-pool.js +387 -0
  222. package/dist/extraction/parse-pool.js.map +1 -0
  223. package/dist/extraction/parse-worker.d.ts +8 -0
  224. package/dist/extraction/parse-worker.d.ts.map +1 -0
  225. package/dist/extraction/parse-worker.js +104 -0
  226. package/dist/extraction/parse-worker.js.map +1 -0
  227. package/dist/extraction/razor-extractor.d.ts +42 -0
  228. package/dist/extraction/razor-extractor.d.ts.map +1 -0
  229. package/dist/extraction/razor-extractor.js +285 -0
  230. package/dist/extraction/razor-extractor.js.map +1 -0
  231. package/dist/extraction/svelte-extractor.d.ts +56 -0
  232. package/dist/extraction/svelte-extractor.d.ts.map +1 -0
  233. package/dist/extraction/svelte-extractor.js +275 -0
  234. package/dist/extraction/svelte-extractor.js.map +1 -0
  235. package/dist/extraction/tree-sitter-helpers.d.ts +28 -0
  236. package/dist/extraction/tree-sitter-helpers.d.ts.map +1 -0
  237. package/dist/extraction/tree-sitter-helpers.js +153 -0
  238. package/dist/extraction/tree-sitter-helpers.js.map +1 -0
  239. package/dist/extraction/tree-sitter-types.d.ts +258 -0
  240. package/dist/extraction/tree-sitter-types.d.ts.map +1 -0
  241. package/dist/extraction/tree-sitter-types.js +10 -0
  242. package/dist/extraction/tree-sitter-types.js.map +1 -0
  243. package/dist/extraction/tree-sitter.d.ts +706 -0
  244. package/dist/extraction/tree-sitter.d.ts.map +1 -0
  245. package/dist/extraction/tree-sitter.js +6506 -0
  246. package/dist/extraction/tree-sitter.js.map +1 -0
  247. package/dist/extraction/vue-extractor.d.ts +51 -0
  248. package/dist/extraction/vue-extractor.d.ts.map +1 -0
  249. package/dist/extraction/vue-extractor.js +254 -0
  250. package/dist/extraction/vue-extractor.js.map +1 -0
  251. package/dist/extraction/wasm/tree-sitter-arkts.wasm +0 -0
  252. package/dist/extraction/wasm/tree-sitter-c_sharp.wasm +0 -0
  253. package/dist/extraction/wasm/tree-sitter-cfml.wasm +0 -0
  254. package/dist/extraction/wasm/tree-sitter-cfquery.wasm +0 -0
  255. package/dist/extraction/wasm/tree-sitter-cfscript.wasm +0 -0
  256. package/dist/extraction/wasm/tree-sitter-cobol.wasm +0 -0
  257. package/dist/extraction/wasm/tree-sitter-erlang.wasm +0 -0
  258. package/dist/extraction/wasm/tree-sitter-lua.wasm +0 -0
  259. package/dist/extraction/wasm/tree-sitter-luau.wasm +0 -0
  260. package/dist/extraction/wasm/tree-sitter-nix.wasm +0 -0
  261. package/dist/extraction/wasm/tree-sitter-pascal.wasm +0 -0
  262. package/dist/extraction/wasm/tree-sitter-r.wasm +0 -0
  263. package/dist/extraction/wasm/tree-sitter-scala.wasm +0 -0
  264. package/dist/extraction/wasm/tree-sitter-terraform.wasm +0 -0
  265. package/dist/extraction/wasm/tree-sitter-vbnet.wasm +0 -0
  266. package/dist/extraction/wasm-runtime-flags.d.ts +38 -0
  267. package/dist/extraction/wasm-runtime-flags.d.ts.map +1 -0
  268. package/dist/extraction/wasm-runtime-flags.js +106 -0
  269. package/dist/extraction/wasm-runtime-flags.js.map +1 -0
  270. package/dist/graph/index.d.ts +8 -0
  271. package/dist/graph/index.d.ts.map +1 -0
  272. package/dist/graph/index.js +13 -0
  273. package/dist/graph/index.js.map +1 -0
  274. package/dist/graph/queries.d.ts +106 -0
  275. package/dist/graph/queries.d.ts.map +1 -0
  276. package/dist/graph/queries.js +339 -0
  277. package/dist/graph/queries.js.map +1 -0
  278. package/dist/graph/traversal.d.ts +127 -0
  279. package/dist/graph/traversal.d.ts.map +1 -0
  280. package/dist/graph/traversal.js +599 -0
  281. package/dist/graph/traversal.js.map +1 -0
  282. package/dist/index.d.ts +644 -0
  283. package/dist/index.d.ts.map +1 -0
  284. package/dist/index.js +1492 -0
  285. package/dist/index.js.map +1 -0
  286. package/dist/installer/config-writer.d.ts +28 -0
  287. package/dist/installer/config-writer.d.ts.map +1 -0
  288. package/dist/installer/config-writer.js +91 -0
  289. package/dist/installer/config-writer.js.map +1 -0
  290. package/dist/installer/index.d.ts +142 -0
  291. package/dist/installer/index.d.ts.map +1 -0
  292. package/dist/installer/index.js +619 -0
  293. package/dist/installer/index.js.map +1 -0
  294. package/dist/installer/instructions-template.d.ts +41 -0
  295. package/dist/installer/instructions-template.d.ts.map +1 -0
  296. package/dist/installer/instructions-template.js +53 -0
  297. package/dist/installer/instructions-template.js.map +1 -0
  298. package/dist/installer/targets/antigravity.d.ts +57 -0
  299. package/dist/installer/targets/antigravity.d.ts.map +1 -0
  300. package/dist/installer/targets/antigravity.js +308 -0
  301. package/dist/installer/targets/antigravity.js.map +1 -0
  302. package/dist/installer/targets/claude.d.ts +62 -0
  303. package/dist/installer/targets/claude.d.ts.map +1 -0
  304. package/dist/installer/targets/claude.js +454 -0
  305. package/dist/installer/targets/claude.js.map +1 -0
  306. package/dist/installer/targets/codex.d.ts +18 -0
  307. package/dist/installer/targets/codex.d.ts.map +1 -0
  308. package/dist/installer/targets/codex.js +185 -0
  309. package/dist/installer/targets/codex.js.map +1 -0
  310. package/dist/installer/targets/cursor.d.ts +35 -0
  311. package/dist/installer/targets/cursor.d.ts.map +1 -0
  312. package/dist/installer/targets/cursor.js +254 -0
  313. package/dist/installer/targets/cursor.js.map +1 -0
  314. package/dist/installer/targets/gemini.d.ts +26 -0
  315. package/dist/installer/targets/gemini.d.ts.map +1 -0
  316. package/dist/installer/targets/gemini.js +165 -0
  317. package/dist/installer/targets/gemini.js.map +1 -0
  318. package/dist/installer/targets/hermes.d.ts +18 -0
  319. package/dist/installer/targets/hermes.d.ts.map +1 -0
  320. package/dist/installer/targets/hermes.js +359 -0
  321. package/dist/installer/targets/hermes.js.map +1 -0
  322. package/dist/installer/targets/kiro.d.ts +27 -0
  323. package/dist/installer/targets/kiro.d.ts.map +1 -0
  324. package/dist/installer/targets/kiro.js +178 -0
  325. package/dist/installer/targets/kiro.js.map +1 -0
  326. package/dist/installer/targets/opencode.d.ts +38 -0
  327. package/dist/installer/targets/opencode.d.ts.map +1 -0
  328. package/dist/installer/targets/opencode.js +288 -0
  329. package/dist/installer/targets/opencode.js.map +1 -0
  330. package/dist/installer/targets/registry.d.ts +35 -0
  331. package/dist/installer/targets/registry.d.ts.map +1 -0
  332. package/dist/installer/targets/registry.js +91 -0
  333. package/dist/installer/targets/registry.js.map +1 -0
  334. package/dist/installer/targets/shared.d.ts +101 -0
  335. package/dist/installer/targets/shared.d.ts.map +1 -0
  336. package/dist/installer/targets/shared.js +264 -0
  337. package/dist/installer/targets/shared.js.map +1 -0
  338. package/dist/installer/targets/toml.d.ts +52 -0
  339. package/dist/installer/targets/toml.d.ts.map +1 -0
  340. package/dist/installer/targets/toml.js +147 -0
  341. package/dist/installer/targets/toml.js.map +1 -0
  342. package/dist/installer/targets/types.d.ts +108 -0
  343. package/dist/installer/targets/types.d.ts.map +1 -0
  344. package/dist/installer/targets/types.js +16 -0
  345. package/dist/installer/targets/types.js.map +1 -0
  346. package/dist/mcp/daemon-manager.d.ts +42 -0
  347. package/dist/mcp/daemon-manager.d.ts.map +1 -0
  348. package/dist/mcp/daemon-manager.js +129 -0
  349. package/dist/mcp/daemon-manager.js.map +1 -0
  350. package/dist/mcp/daemon-paths.d.ts +73 -0
  351. package/dist/mcp/daemon-paths.d.ts.map +1 -0
  352. package/dist/mcp/daemon-paths.js +165 -0
  353. package/dist/mcp/daemon-paths.js.map +1 -0
  354. package/dist/mcp/daemon-registry.d.ts +47 -0
  355. package/dist/mcp/daemon-registry.d.ts.map +1 -0
  356. package/dist/mcp/daemon-registry.js +233 -0
  357. package/dist/mcp/daemon-registry.js.map +1 -0
  358. package/dist/mcp/daemon.d.ts +290 -0
  359. package/dist/mcp/daemon.d.ts.map +1 -0
  360. package/dist/mcp/daemon.js +862 -0
  361. package/dist/mcp/daemon.js.map +1 -0
  362. package/dist/mcp/dynamic-boundaries.d.ts +41 -0
  363. package/dist/mcp/dynamic-boundaries.d.ts.map +1 -0
  364. package/dist/mcp/dynamic-boundaries.js +360 -0
  365. package/dist/mcp/dynamic-boundaries.js.map +1 -0
  366. package/dist/mcp/early-ppid.d.ts +26 -0
  367. package/dist/mcp/early-ppid.d.ts.map +1 -0
  368. package/dist/mcp/early-ppid.js +29 -0
  369. package/dist/mcp/early-ppid.js.map +1 -0
  370. package/dist/mcp/engine.d.ts +122 -0
  371. package/dist/mcp/engine.d.ts.map +1 -0
  372. package/dist/mcp/engine.js +350 -0
  373. package/dist/mcp/engine.js.map +1 -0
  374. package/dist/mcp/index.d.ts +113 -0
  375. package/dist/mcp/index.d.ts.map +1 -0
  376. package/dist/mcp/index.js +506 -0
  377. package/dist/mcp/index.js.map +1 -0
  378. package/dist/mcp/liveness-watchdog.d.ts +35 -0
  379. package/dist/mcp/liveness-watchdog.d.ts.map +1 -0
  380. package/dist/mcp/liveness-watchdog.js +267 -0
  381. package/dist/mcp/liveness-watchdog.js.map +1 -0
  382. package/dist/mcp/ppid-watchdog.d.ts +62 -0
  383. package/dist/mcp/ppid-watchdog.d.ts.map +1 -0
  384. package/dist/mcp/ppid-watchdog.js +64 -0
  385. package/dist/mcp/ppid-watchdog.js.map +1 -0
  386. package/dist/mcp/proxy.d.ts +87 -0
  387. package/dist/mcp/proxy.d.ts.map +1 -0
  388. package/dist/mcp/proxy.js +667 -0
  389. package/dist/mcp/proxy.js.map +1 -0
  390. package/dist/mcp/query-pool.d.ts +108 -0
  391. package/dist/mcp/query-pool.d.ts.map +1 -0
  392. package/dist/mcp/query-pool.js +315 -0
  393. package/dist/mcp/query-pool.js.map +1 -0
  394. package/dist/mcp/query-worker.d.ts +24 -0
  395. package/dist/mcp/query-worker.d.ts.map +1 -0
  396. package/dist/mcp/query-worker.js +87 -0
  397. package/dist/mcp/query-worker.js.map +1 -0
  398. package/dist/mcp/server-instructions.d.ts +34 -0
  399. package/dist/mcp/server-instructions.d.ts.map +1 -0
  400. package/dist/mcp/server-instructions.js +106 -0
  401. package/dist/mcp/server-instructions.js.map +1 -0
  402. package/dist/mcp/session.d.ts +93 -0
  403. package/dist/mcp/session.d.ts.map +1 -0
  404. package/dist/mcp/session.js +357 -0
  405. package/dist/mcp/session.js.map +1 -0
  406. package/dist/mcp/startup-handshake.d.ts +44 -0
  407. package/dist/mcp/startup-handshake.d.ts.map +1 -0
  408. package/dist/mcp/startup-handshake.js +73 -0
  409. package/dist/mcp/startup-handshake.js.map +1 -0
  410. package/dist/mcp/stdin-teardown.d.ts +27 -0
  411. package/dist/mcp/stdin-teardown.d.ts.map +1 -0
  412. package/dist/mcp/stdin-teardown.js +49 -0
  413. package/dist/mcp/stdin-teardown.js.map +1 -0
  414. package/dist/mcp/tools.d.ts +613 -0
  415. package/dist/mcp/tools.d.ts.map +1 -0
  416. package/dist/mcp/tools.js +4477 -0
  417. package/dist/mcp/tools.js.map +1 -0
  418. package/dist/mcp/transport.d.ts +188 -0
  419. package/dist/mcp/transport.d.ts.map +1 -0
  420. package/dist/mcp/transport.js +377 -0
  421. package/dist/mcp/transport.js.map +1 -0
  422. package/dist/mcp/version.d.ts +19 -0
  423. package/dist/mcp/version.d.ts.map +1 -0
  424. package/dist/mcp/version.js +71 -0
  425. package/dist/mcp/version.js.map +1 -0
  426. package/dist/project-config.d.ts +94 -0
  427. package/dist/project-config.d.ts.map +1 -0
  428. package/dist/project-config.js +374 -0
  429. package/dist/project-config.js.map +1 -0
  430. package/dist/resolution/c-fnptr-synthesizer.d.ts +6 -0
  431. package/dist/resolution/c-fnptr-synthesizer.d.ts.map +1 -0
  432. package/dist/resolution/c-fnptr-synthesizer.js +1062 -0
  433. package/dist/resolution/c-fnptr-synthesizer.js.map +1 -0
  434. package/dist/resolution/callback-synthesizer.d.ts +15 -0
  435. package/dist/resolution/callback-synthesizer.d.ts.map +1 -0
  436. package/dist/resolution/callback-synthesizer.js +3938 -0
  437. package/dist/resolution/callback-synthesizer.js.map +1 -0
  438. package/dist/resolution/cooperative-yield.d.ts +32 -0
  439. package/dist/resolution/cooperative-yield.d.ts.map +1 -0
  440. package/dist/resolution/cooperative-yield.js +42 -0
  441. package/dist/resolution/cooperative-yield.js.map +1 -0
  442. package/dist/resolution/frameworks/astro.d.ts +9 -0
  443. package/dist/resolution/frameworks/astro.d.ts.map +1 -0
  444. package/dist/resolution/frameworks/astro.js +169 -0
  445. package/dist/resolution/frameworks/astro.js.map +1 -0
  446. package/dist/resolution/frameworks/cargo-workspace.d.ts +18 -0
  447. package/dist/resolution/frameworks/cargo-workspace.d.ts.map +1 -0
  448. package/dist/resolution/frameworks/cargo-workspace.js +225 -0
  449. package/dist/resolution/frameworks/cargo-workspace.js.map +1 -0
  450. package/dist/resolution/frameworks/cics.d.ts +20 -0
  451. package/dist/resolution/frameworks/cics.d.ts.map +1 -0
  452. package/dist/resolution/frameworks/cics.js +90 -0
  453. package/dist/resolution/frameworks/cics.js.map +1 -0
  454. package/dist/resolution/frameworks/csharp.d.ts +8 -0
  455. package/dist/resolution/frameworks/csharp.d.ts.map +1 -0
  456. package/dist/resolution/frameworks/csharp.js +241 -0
  457. package/dist/resolution/frameworks/csharp.js.map +1 -0
  458. package/dist/resolution/frameworks/drupal.d.ts +51 -0
  459. package/dist/resolution/frameworks/drupal.d.ts.map +1 -0
  460. package/dist/resolution/frameworks/drupal.js +367 -0
  461. package/dist/resolution/frameworks/drupal.js.map +1 -0
  462. package/dist/resolution/frameworks/expo-modules.d.ts +3 -0
  463. package/dist/resolution/frameworks/expo-modules.d.ts.map +1 -0
  464. package/dist/resolution/frameworks/expo-modules.js +148 -0
  465. package/dist/resolution/frameworks/expo-modules.js.map +1 -0
  466. package/dist/resolution/frameworks/express.d.ts +8 -0
  467. package/dist/resolution/frameworks/express.d.ts.map +1 -0
  468. package/dist/resolution/frameworks/express.js +308 -0
  469. package/dist/resolution/frameworks/express.js.map +1 -0
  470. package/dist/resolution/frameworks/fabric.d.ts +3 -0
  471. package/dist/resolution/frameworks/fabric.d.ts.map +1 -0
  472. package/dist/resolution/frameworks/fabric.js +354 -0
  473. package/dist/resolution/frameworks/fabric.js.map +1 -0
  474. package/dist/resolution/frameworks/go.d.ts +8 -0
  475. package/dist/resolution/frameworks/go.d.ts.map +1 -0
  476. package/dist/resolution/frameworks/go.js +161 -0
  477. package/dist/resolution/frameworks/go.js.map +1 -0
  478. package/dist/resolution/frameworks/goframe.d.ts +41 -0
  479. package/dist/resolution/frameworks/goframe.d.ts.map +1 -0
  480. package/dist/resolution/frameworks/goframe.js +112 -0
  481. package/dist/resolution/frameworks/goframe.js.map +1 -0
  482. package/dist/resolution/frameworks/index.d.ts +50 -0
  483. package/dist/resolution/frameworks/index.d.ts.map +1 -0
  484. package/dist/resolution/frameworks/index.js +175 -0
  485. package/dist/resolution/frameworks/index.js.map +1 -0
  486. package/dist/resolution/frameworks/java.d.ts +8 -0
  487. package/dist/resolution/frameworks/java.d.ts.map +1 -0
  488. package/dist/resolution/frameworks/java.js +517 -0
  489. package/dist/resolution/frameworks/java.js.map +1 -0
  490. package/dist/resolution/frameworks/laravel.d.ts +13 -0
  491. package/dist/resolution/frameworks/laravel.d.ts.map +1 -0
  492. package/dist/resolution/frameworks/laravel.js +257 -0
  493. package/dist/resolution/frameworks/laravel.js.map +1 -0
  494. package/dist/resolution/frameworks/nestjs.d.ts +26 -0
  495. package/dist/resolution/frameworks/nestjs.d.ts.map +1 -0
  496. package/dist/resolution/frameworks/nestjs.js +698 -0
  497. package/dist/resolution/frameworks/nestjs.js.map +1 -0
  498. package/dist/resolution/frameworks/play.d.ts +19 -0
  499. package/dist/resolution/frameworks/play.d.ts.map +1 -0
  500. package/dist/resolution/frameworks/play.js +111 -0
  501. package/dist/resolution/frameworks/play.js.map +1 -0
  502. package/dist/resolution/frameworks/python.d.ts +10 -0
  503. package/dist/resolution/frameworks/python.d.ts.map +1 -0
  504. package/dist/resolution/frameworks/python.js +400 -0
  505. package/dist/resolution/frameworks/python.js.map +1 -0
  506. package/dist/resolution/frameworks/react-native.d.ts +3 -0
  507. package/dist/resolution/frameworks/react-native.d.ts.map +1 -0
  508. package/dist/resolution/frameworks/react-native.js +410 -0
  509. package/dist/resolution/frameworks/react-native.js.map +1 -0
  510. package/dist/resolution/frameworks/react.d.ts +8 -0
  511. package/dist/resolution/frameworks/react.d.ts.map +1 -0
  512. package/dist/resolution/frameworks/react.js +334 -0
  513. package/dist/resolution/frameworks/react.js.map +1 -0
  514. package/dist/resolution/frameworks/ruby.d.ts +8 -0
  515. package/dist/resolution/frameworks/ruby.d.ts.map +1 -0
  516. package/dist/resolution/frameworks/ruby.js +302 -0
  517. package/dist/resolution/frameworks/ruby.js.map +1 -0
  518. package/dist/resolution/frameworks/rust.d.ts +8 -0
  519. package/dist/resolution/frameworks/rust.d.ts.map +1 -0
  520. package/dist/resolution/frameworks/rust.js +304 -0
  521. package/dist/resolution/frameworks/rust.js.map +1 -0
  522. package/dist/resolution/frameworks/svelte.d.ts +9 -0
  523. package/dist/resolution/frameworks/svelte.d.ts.map +1 -0
  524. package/dist/resolution/frameworks/svelte.js +253 -0
  525. package/dist/resolution/frameworks/svelte.js.map +1 -0
  526. package/dist/resolution/frameworks/swift-objc.d.ts +37 -0
  527. package/dist/resolution/frameworks/swift-objc.d.ts.map +1 -0
  528. package/dist/resolution/frameworks/swift-objc.js +252 -0
  529. package/dist/resolution/frameworks/swift-objc.js.map +1 -0
  530. package/dist/resolution/frameworks/swift.d.ts +10 -0
  531. package/dist/resolution/frameworks/swift.d.ts.map +1 -0
  532. package/dist/resolution/frameworks/swift.js +400 -0
  533. package/dist/resolution/frameworks/swift.js.map +1 -0
  534. package/dist/resolution/frameworks/terraform.d.ts +38 -0
  535. package/dist/resolution/frameworks/terraform.d.ts.map +1 -0
  536. package/dist/resolution/frameworks/terraform.js +277 -0
  537. package/dist/resolution/frameworks/terraform.js.map +1 -0
  538. package/dist/resolution/frameworks/vue.d.ts +9 -0
  539. package/dist/resolution/frameworks/vue.d.ts.map +1 -0
  540. package/dist/resolution/frameworks/vue.js +303 -0
  541. package/dist/resolution/frameworks/vue.js.map +1 -0
  542. package/dist/resolution/go-module.d.ts +26 -0
  543. package/dist/resolution/go-module.d.ts.map +1 -0
  544. package/dist/resolution/go-module.js +78 -0
  545. package/dist/resolution/go-module.js.map +1 -0
  546. package/dist/resolution/goframe-synthesizer.d.ts +29 -0
  547. package/dist/resolution/goframe-synthesizer.d.ts.map +1 -0
  548. package/dist/resolution/goframe-synthesizer.js +163 -0
  549. package/dist/resolution/goframe-synthesizer.js.map +1 -0
  550. package/dist/resolution/import-resolver.d.ts +85 -0
  551. package/dist/resolution/import-resolver.d.ts.map +1 -0
  552. package/dist/resolution/import-resolver.js +1974 -0
  553. package/dist/resolution/import-resolver.js.map +1 -0
  554. package/dist/resolution/index.d.ts +258 -0
  555. package/dist/resolution/index.d.ts.map +1 -0
  556. package/dist/resolution/index.js +1746 -0
  557. package/dist/resolution/index.js.map +1 -0
  558. package/dist/resolution/lru-cache.d.ts +24 -0
  559. package/dist/resolution/lru-cache.d.ts.map +1 -0
  560. package/dist/resolution/lru-cache.js +62 -0
  561. package/dist/resolution/lru-cache.js.map +1 -0
  562. package/dist/resolution/name-matcher.d.ts +112 -0
  563. package/dist/resolution/name-matcher.d.ts.map +1 -0
  564. package/dist/resolution/name-matcher.js +1830 -0
  565. package/dist/resolution/name-matcher.js.map +1 -0
  566. package/dist/resolution/path-aliases.d.ts +68 -0
  567. package/dist/resolution/path-aliases.d.ts.map +1 -0
  568. package/dist/resolution/path-aliases.js +238 -0
  569. package/dist/resolution/path-aliases.js.map +1 -0
  570. package/dist/resolution/strip-comments.d.ts +27 -0
  571. package/dist/resolution/strip-comments.d.ts.map +1 -0
  572. package/dist/resolution/strip-comments.js +492 -0
  573. package/dist/resolution/strip-comments.js.map +1 -0
  574. package/dist/resolution/swift-objc-bridge.d.ts +134 -0
  575. package/dist/resolution/swift-objc-bridge.d.ts.map +1 -0
  576. package/dist/resolution/swift-objc-bridge.js +256 -0
  577. package/dist/resolution/swift-objc-bridge.js.map +1 -0
  578. package/dist/resolution/types.d.ts +262 -0
  579. package/dist/resolution/types.d.ts.map +1 -0
  580. package/dist/resolution/types.js +8 -0
  581. package/dist/resolution/types.js.map +1 -0
  582. package/dist/resolution/workspace-packages.d.ts +58 -0
  583. package/dist/resolution/workspace-packages.d.ts.map +1 -0
  584. package/dist/resolution/workspace-packages.js +346 -0
  585. package/dist/resolution/workspace-packages.js.map +1 -0
  586. package/dist/search/identifier-segments.d.ts +60 -0
  587. package/dist/search/identifier-segments.d.ts.map +1 -0
  588. package/dist/search/identifier-segments.js +176 -0
  589. package/dist/search/identifier-segments.js.map +1 -0
  590. package/dist/search/query-parser.d.ts +57 -0
  591. package/dist/search/query-parser.d.ts.map +1 -0
  592. package/dist/search/query-parser.js +177 -0
  593. package/dist/search/query-parser.js.map +1 -0
  594. package/dist/search/query-utils.d.ts +87 -0
  595. package/dist/search/query-utils.d.ts.map +1 -0
  596. package/dist/search/query-utils.js +449 -0
  597. package/dist/search/query-utils.js.map +1 -0
  598. package/dist/sync/git-hooks.d.ts +45 -0
  599. package/dist/sync/git-hooks.d.ts.map +1 -0
  600. package/dist/sync/git-hooks.js +227 -0
  601. package/dist/sync/git-hooks.js.map +1 -0
  602. package/dist/sync/index.d.ts +19 -0
  603. package/dist/sync/index.d.ts.map +1 -0
  604. package/dist/sync/index.js +35 -0
  605. package/dist/sync/index.js.map +1 -0
  606. package/dist/sync/watch-policy.d.ts +48 -0
  607. package/dist/sync/watch-policy.d.ts.map +1 -0
  608. package/dist/sync/watch-policy.js +124 -0
  609. package/dist/sync/watch-policy.js.map +1 -0
  610. package/dist/sync/watcher.d.ts +355 -0
  611. package/dist/sync/watcher.d.ts.map +1 -0
  612. package/dist/sync/watcher.js +848 -0
  613. package/dist/sync/watcher.js.map +1 -0
  614. package/dist/sync/worktree.d.ts +63 -0
  615. package/dist/sync/worktree.d.ts.map +1 -0
  616. package/dist/sync/worktree.js +182 -0
  617. package/dist/sync/worktree.js.map +1 -0
  618. package/dist/telemetry/index.d.ts +143 -0
  619. package/dist/telemetry/index.d.ts.map +1 -0
  620. package/dist/telemetry/index.js +541 -0
  621. package/dist/telemetry/index.js.map +1 -0
  622. package/dist/types.d.ts +415 -0
  623. package/dist/types.d.ts.map +1 -0
  624. package/dist/types.js +91 -0
  625. package/dist/types.js.map +1 -0
  626. package/dist/ui/glyphs.d.ts +42 -0
  627. package/dist/ui/glyphs.d.ts.map +1 -0
  628. package/dist/ui/glyphs.js +78 -0
  629. package/dist/ui/glyphs.js.map +1 -0
  630. package/dist/ui/shimmer-progress.d.ts +11 -0
  631. package/dist/ui/shimmer-progress.d.ts.map +1 -0
  632. package/dist/ui/shimmer-progress.js +90 -0
  633. package/dist/ui/shimmer-progress.js.map +1 -0
  634. package/dist/ui/shimmer-worker.d.ts +2 -0
  635. package/dist/ui/shimmer-worker.d.ts.map +1 -0
  636. package/dist/ui/shimmer-worker.js +118 -0
  637. package/dist/ui/shimmer-worker.js.map +1 -0
  638. package/dist/ui/types.d.ts +17 -0
  639. package/dist/ui/types.d.ts.map +1 -0
  640. package/dist/ui/types.js +3 -0
  641. package/dist/ui/types.js.map +1 -0
  642. package/dist/upgrade/index.d.ts +164 -0
  643. package/dist/upgrade/index.d.ts.map +1 -0
  644. package/dist/upgrade/index.js +646 -0
  645. package/dist/upgrade/index.js.map +1 -0
  646. package/dist/upgrade/remove-binary.d.ts +87 -0
  647. package/dist/upgrade/remove-binary.d.ts.map +1 -0
  648. package/dist/upgrade/remove-binary.js +289 -0
  649. package/dist/upgrade/remove-binary.js.map +1 -0
  650. package/dist/upgrade/update-check.d.ts +92 -0
  651. package/dist/upgrade/update-check.d.ts.map +1 -0
  652. package/dist/upgrade/update-check.js +258 -0
  653. package/dist/upgrade/update-check.js.map +1 -0
  654. package/dist/utils.d.ts +224 -0
  655. package/dist/utils.d.ts.map +1 -0
  656. package/dist/utils.js +583 -0
  657. package/dist/utils.js.map +1 -0
  658. package/package.json +1 -1
package/dist/index.js ADDED
@@ -0,0 +1,1492 @@
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.LockUnavailableError = 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.QueryBuilder = exports.DatabaseConnection = exports.getDatabasePath = void 0;
46
+ const path = __importStar(require("path"));
47
+ const db_1 = require("./db");
48
+ const wal_valve_1 = require("./db/wal-valve");
49
+ const queries_1 = require("./db/queries");
50
+ const directory_1 = require("./directory");
51
+ const extraction_1 = require("./extraction");
52
+ const resolution_1 = require("./resolution");
53
+ const graph_1 = require("./graph");
54
+ const context_1 = require("./context");
55
+ const utils_1 = require("./utils");
56
+ const sync_1 = require("./sync");
57
+ const extraction_version_1 = require("./extraction/extraction-version");
58
+ const directory_2 = require("./directory");
59
+ const query_utils_1 = require("./search/query-utils");
60
+ const version_1 = require("./mcp/version");
61
+ const identifier_segments_1 = require("./search/identifier-segments");
62
+ const cooperative_yield_1 = require("./resolution/cooperative-yield");
63
+ // Re-export types for consumers
64
+ __exportStar(require("./types"), exports);
65
+ // Storage building blocks for embedded/SDK consumers that drive the graph
66
+ // directly (open a DB, run prepared queries) rather than through the CodeGraph
67
+ // facade. Exposed from the package entry so they no longer require deep imports
68
+ // into dist/ (issue #354).
69
+ var db_2 = require("./db");
70
+ Object.defineProperty(exports, "getDatabasePath", { enumerable: true, get: function () { return db_2.getDatabasePath; } });
71
+ Object.defineProperty(exports, "DatabaseConnection", { enumerable: true, get: function () { return db_2.DatabaseConnection; } });
72
+ var queries_2 = require("./db/queries");
73
+ Object.defineProperty(exports, "QueryBuilder", { enumerable: true, get: function () { return queries_2.QueryBuilder; } });
74
+ var directory_3 = require("./directory");
75
+ Object.defineProperty(exports, "getCodeGraphDir", { enumerable: true, get: function () { return directory_3.getCodeGraphDir; } });
76
+ Object.defineProperty(exports, "isInitialized", { enumerable: true, get: function () { return directory_3.isInitialized; } });
77
+ Object.defineProperty(exports, "findNearestCodeGraphRoot", { enumerable: true, get: function () { return directory_3.findNearestCodeGraphRoot; } });
78
+ Object.defineProperty(exports, "CODEGRAPH_DIR", { enumerable: true, get: function () { return directory_3.CODEGRAPH_DIR; } });
79
+ var extraction_2 = require("./extraction");
80
+ Object.defineProperty(exports, "detectLanguage", { enumerable: true, get: function () { return extraction_2.detectLanguage; } });
81
+ Object.defineProperty(exports, "isLanguageSupported", { enumerable: true, get: function () { return extraction_2.isLanguageSupported; } });
82
+ Object.defineProperty(exports, "isGrammarLoaded", { enumerable: true, get: function () { return extraction_2.isGrammarLoaded; } });
83
+ Object.defineProperty(exports, "getSupportedLanguages", { enumerable: true, get: function () { return extraction_2.getSupportedLanguages; } });
84
+ Object.defineProperty(exports, "initGrammars", { enumerable: true, get: function () { return extraction_2.initGrammars; } });
85
+ Object.defineProperty(exports, "loadGrammarsForLanguages", { enumerable: true, get: function () { return extraction_2.loadGrammarsForLanguages; } });
86
+ Object.defineProperty(exports, "loadAllGrammars", { enumerable: true, get: function () { return extraction_2.loadAllGrammars; } });
87
+ var errors_1 = require("./errors");
88
+ Object.defineProperty(exports, "CodeGraphError", { enumerable: true, get: function () { return errors_1.CodeGraphError; } });
89
+ Object.defineProperty(exports, "FileError", { enumerable: true, get: function () { return errors_1.FileError; } });
90
+ Object.defineProperty(exports, "ParseError", { enumerable: true, get: function () { return errors_1.ParseError; } });
91
+ Object.defineProperty(exports, "DatabaseError", { enumerable: true, get: function () { return errors_1.DatabaseError; } });
92
+ Object.defineProperty(exports, "SearchError", { enumerable: true, get: function () { return errors_1.SearchError; } });
93
+ Object.defineProperty(exports, "VectorError", { enumerable: true, get: function () { return errors_1.VectorError; } });
94
+ Object.defineProperty(exports, "ConfigError", { enumerable: true, get: function () { return errors_1.ConfigError; } });
95
+ Object.defineProperty(exports, "setLogger", { enumerable: true, get: function () { return errors_1.setLogger; } });
96
+ Object.defineProperty(exports, "getLogger", { enumerable: true, get: function () { return errors_1.getLogger; } });
97
+ Object.defineProperty(exports, "silentLogger", { enumerable: true, get: function () { return errors_1.silentLogger; } });
98
+ Object.defineProperty(exports, "defaultLogger", { enumerable: true, get: function () { return errors_1.defaultLogger; } });
99
+ var utils_2 = require("./utils");
100
+ Object.defineProperty(exports, "Mutex", { enumerable: true, get: function () { return utils_2.Mutex; } });
101
+ Object.defineProperty(exports, "FileLock", { enumerable: true, get: function () { return utils_2.FileLock; } });
102
+ Object.defineProperty(exports, "processInBatches", { enumerable: true, get: function () { return utils_2.processInBatches; } });
103
+ Object.defineProperty(exports, "debounce", { enumerable: true, get: function () { return utils_2.debounce; } });
104
+ Object.defineProperty(exports, "throttle", { enumerable: true, get: function () { return utils_2.throttle; } });
105
+ Object.defineProperty(exports, "MemoryMonitor", { enumerable: true, get: function () { return utils_2.MemoryMonitor; } });
106
+ var sync_2 = require("./sync");
107
+ Object.defineProperty(exports, "FileWatcher", { enumerable: true, get: function () { return sync_2.FileWatcher; } });
108
+ Object.defineProperty(exports, "LockUnavailableError", { enumerable: true, get: function () { return sync_2.LockUnavailableError; } });
109
+ var mcp_1 = require("./mcp");
110
+ Object.defineProperty(exports, "MCPServer", { enumerable: true, get: function () { return mcp_1.MCPServer; } });
111
+ /**
112
+ * Main CodeGraph class
113
+ *
114
+ * Provides the primary interface for interacting with the code knowledge graph.
115
+ */
116
+ class CodeGraph {
117
+ db;
118
+ queries;
119
+ projectRoot;
120
+ // Assigned via wireLayers() from the constructor (and again on reopen) — the
121
+ // `!` tells TS these are definitely set even though the assignment is one
122
+ // method call away from the constructor body.
123
+ orchestrator;
124
+ resolver;
125
+ graphManager;
126
+ traverser;
127
+ contextBuilder;
128
+ // Mutex for preventing concurrent indexing operations (in-process)
129
+ indexMutex = new utils_1.Mutex();
130
+ // File lock for preventing concurrent writes across processes (CLI, MCP, git hooks)
131
+ fileLock;
132
+ // File watcher for auto-sync on file changes
133
+ watcher = null;
134
+ constructor(db, queries, projectRoot) {
135
+ this.db = db;
136
+ this.queries = queries;
137
+ this.projectRoot = projectRoot;
138
+ this.fileLock = new utils_1.FileLock(path.join((0, directory_2.getCodeGraphDir)(projectRoot), 'codegraph.lock'));
139
+ this.wireLayers();
140
+ }
141
+ /**
142
+ * (Re)build the query/extraction/graph layers over the current `this.queries`
143
+ * (which wraps `this.db`). Factored out of the constructor so `reopenIfReplaced`
144
+ * can rebuild them against a fresh connection without duplicating the wiring.
145
+ * The path-based `fileLock` is independent of the DB handle, so it stays put.
146
+ */
147
+ wireLayers() {
148
+ // Down-weight the project name as a query term in search ranking — it names
149
+ // the whole repo, not a symbol, so it has no discriminative value (#720).
150
+ try {
151
+ this.queries.setProjectNameTokens((0, query_utils_1.deriveProjectNameTokens)(this.projectRoot));
152
+ }
153
+ catch {
154
+ // Best-effort: ranking still works without it.
155
+ }
156
+ this.orchestrator = new extraction_1.ExtractionOrchestrator(this.projectRoot, this.queries);
157
+ this.resolver = (0, resolution_1.createResolver)(this.projectRoot, this.queries);
158
+ this.graphManager = new graph_1.GraphQueryManager(this.queries);
159
+ this.traverser = new graph_1.GraphTraverser(this.queries);
160
+ this.contextBuilder = (0, context_1.createContextBuilder)(this.projectRoot, this.queries, this.traverser);
161
+ }
162
+ /**
163
+ * Heal a stale database handle in place. If `.codegraph/` was removed and
164
+ * recreated at the SAME path while this instance held the DB open — a git
165
+ * worktree removed and re-added, or `rm -rf .codegraph` + `codegraph init` —
166
+ * our open fd points at the now-unlinked inode and can never see the new
167
+ * index, so every query returns the pre-removal snapshot until the process
168
+ * restarts (#925). When that's detected, open the live file at the same path,
169
+ * rebuild the query layers, and swap them IN PLACE, so every holder of this
170
+ * instance (the MCP daemon's default project, cached projectPath connections)
171
+ * heals without a restart. Returns true iff it reopened.
172
+ *
173
+ * POSIX-only in practice: `isReplacedOnDisk` never fires on Windows (an open
174
+ * file can't be unlinked there, and st_ino is unreliable).
175
+ */
176
+ reopenIfReplaced() {
177
+ if (!this.db.isReplacedOnDisk())
178
+ return false;
179
+ const dbPath = this.db.getPath();
180
+ // Open the live file FIRST — if that throws (e.g. mid-recreate), the old
181
+ // handle stays in place and the caller retries on the next query, rather
182
+ // than leaving this instance with no connection at all.
183
+ const fresh = db_1.DatabaseConnection.open(dbPath);
184
+ const stale = this.db;
185
+ this.db = fresh;
186
+ this.queries = new queries_1.QueryBuilder(fresh.getDb());
187
+ this.wireLayers();
188
+ // Releasing the dead handle also frees the leaked db/-wal/-shm fds that were
189
+ // pinning the unlinked inode (#925).
190
+ try {
191
+ stale.close();
192
+ }
193
+ catch { /* the old inode is gone; closing just frees fds */ }
194
+ return true;
195
+ }
196
+ // ===========================================================================
197
+ // Lifecycle Methods
198
+ // ===========================================================================
199
+ /**
200
+ * Initialize a new CodeGraph project
201
+ *
202
+ * Creates the .CodeGraph directory, database, and configuration.
203
+ *
204
+ * @param projectRoot - Path to the project root directory
205
+ * @param options - Initialization options
206
+ * @returns A new CodeGraph instance
207
+ */
208
+ static async init(projectRoot, options = {}) {
209
+ await (0, extraction_1.initGrammars)();
210
+ const resolvedRoot = path.resolve(projectRoot);
211
+ // Check if already initialized
212
+ if ((0, directory_1.isInitialized)(resolvedRoot)) {
213
+ throw new Error(`CodeGraph already initialized in ${resolvedRoot}`);
214
+ }
215
+ // Create directory structure
216
+ (0, directory_1.createDirectory)(resolvedRoot);
217
+ // Initialize database
218
+ const dbPath = (0, db_1.getDatabasePath)(resolvedRoot);
219
+ const db = db_1.DatabaseConnection.initialize(dbPath);
220
+ const queries = new queries_1.QueryBuilder(db.getDb());
221
+ const instance = new CodeGraph(db, queries, resolvedRoot);
222
+ // Run initial indexing if requested
223
+ if (options.index) {
224
+ await instance.indexAll({ onProgress: options.onProgress });
225
+ }
226
+ return instance;
227
+ }
228
+ /**
229
+ * Initialize synchronously (without indexing)
230
+ */
231
+ static initSync(projectRoot) {
232
+ const resolvedRoot = path.resolve(projectRoot);
233
+ // Check if already initialized
234
+ if ((0, directory_1.isInitialized)(resolvedRoot)) {
235
+ throw new Error(`CodeGraph already initialized in ${resolvedRoot}`);
236
+ }
237
+ // Create directory structure
238
+ (0, directory_1.createDirectory)(resolvedRoot);
239
+ // Initialize database
240
+ const dbPath = (0, db_1.getDatabasePath)(resolvedRoot);
241
+ const db = db_1.DatabaseConnection.initialize(dbPath);
242
+ const queries = new queries_1.QueryBuilder(db.getDb());
243
+ return new CodeGraph(db, queries, resolvedRoot);
244
+ }
245
+ /**
246
+ * Open an existing CodeGraph project
247
+ *
248
+ * @param projectRoot - Path to the project root directory
249
+ * @param options - Open options
250
+ * @returns A CodeGraph instance
251
+ */
252
+ static async open(projectRoot, options = {}) {
253
+ await (0, extraction_1.initGrammars)();
254
+ const resolvedRoot = path.resolve(projectRoot);
255
+ // Check if initialized
256
+ if (!(0, directory_1.isInitialized)(resolvedRoot)) {
257
+ throw new Error(`CodeGraph not initialized in ${resolvedRoot}. Run init() first.`);
258
+ }
259
+ // Validate directory structure
260
+ const validation = (0, directory_1.validateDirectory)(resolvedRoot);
261
+ if (!validation.valid) {
262
+ throw new Error(`Invalid CodeGraph directory: ${validation.errors.join(', ')}`);
263
+ }
264
+ // Open database
265
+ const dbPath = (0, db_1.getDatabasePath)(resolvedRoot);
266
+ const db = db_1.DatabaseConnection.open(dbPath);
267
+ const queries = new queries_1.QueryBuilder(db.getDb());
268
+ const instance = new CodeGraph(db, queries, resolvedRoot);
269
+ // Sync if requested
270
+ if (options.sync) {
271
+ await instance.sync();
272
+ }
273
+ return instance;
274
+ }
275
+ /**
276
+ * Rebuild the project's database from scratch and return a fresh, empty
277
+ * instance — the "same result as a fresh init" semantics that `codegraph
278
+ * index` documents.
279
+ *
280
+ * Unlike `open()` followed by `clear()`, this DISCARDS the existing
281
+ * `.codegraph/codegraph.db` (and its `-wal`/`-shm` sidecars) before
282
+ * re-initializing, instead of opening the old database and DELETE-ing every
283
+ * row. On a large or pre-fix poisoned index — e.g. an old graph that scanned
284
+ * an ignored gitlink corpus (#1065) into ~1.6M nodes with a multi-GB WAL —
285
+ * the per-row `nodes_fts` delete-trigger churn blocks the main thread long
286
+ * enough to trip the #850 liveness watchdog before indexing even starts, so a
287
+ * full re-index could never recover the bad state (#1067). Discarding the
288
+ * files is O(1) regardless of size, reclaims the disk, and sidesteps opening
289
+ * (and running migrations against) the poisoned database entirely.
290
+ */
291
+ static async recreate(projectRoot) {
292
+ await (0, extraction_1.initGrammars)();
293
+ const resolvedRoot = path.resolve(projectRoot);
294
+ // Check if initialized — recreate REBUILDS an existing project; it is not a
295
+ // first-time `init`.
296
+ if (!(0, directory_1.isInitialized)(resolvedRoot)) {
297
+ throw new Error(`CodeGraph not initialized in ${resolvedRoot}. Run init() first.`);
298
+ }
299
+ const dbPath = (0, db_1.getDatabasePath)(resolvedRoot);
300
+ try {
301
+ (0, db_1.removeDatabaseFiles)(dbPath);
302
+ }
303
+ catch (err) {
304
+ // POSIX unlinks an open file fine; this fires mainly on Windows when a
305
+ // live daemon/MCP server still holds the database. Turn the raw EBUSY into
306
+ // an actionable instruction instead of a generic failure.
307
+ const reason = err instanceof Error ? err.message : String(err);
308
+ throw new Error(`Could not rebuild the index — the database file is in use (${reason}). ` +
309
+ `Stop any running CodeGraph MCP server/daemon for this project and retry, ` +
310
+ `or remove the ${(0, directory_2.getCodeGraphDir)(resolvedRoot)} directory and run "codegraph init".`);
311
+ }
312
+ // Re-create an empty, freshly-schema'd database at the same path.
313
+ const db = db_1.DatabaseConnection.initialize(dbPath);
314
+ const queries = new queries_1.QueryBuilder(db.getDb());
315
+ return new CodeGraph(db, queries, resolvedRoot);
316
+ }
317
+ /**
318
+ * Open synchronously (without sync)
319
+ */
320
+ static openSync(projectRoot) {
321
+ const resolvedRoot = path.resolve(projectRoot);
322
+ // Check if initialized
323
+ if (!(0, directory_1.isInitialized)(resolvedRoot)) {
324
+ throw new Error(`CodeGraph not initialized in ${resolvedRoot}. Run init() first.`);
325
+ }
326
+ // Validate directory structure
327
+ const validation = (0, directory_1.validateDirectory)(resolvedRoot);
328
+ if (!validation.valid) {
329
+ throw new Error(`Invalid CodeGraph directory: ${validation.errors.join(', ')}`);
330
+ }
331
+ // Open database
332
+ const dbPath = (0, db_1.getDatabasePath)(resolvedRoot);
333
+ const db = db_1.DatabaseConnection.open(dbPath);
334
+ const queries = new queries_1.QueryBuilder(db.getDb());
335
+ return new CodeGraph(db, queries, resolvedRoot);
336
+ }
337
+ /**
338
+ * Check if a directory has been initialized as a CodeGraph project
339
+ */
340
+ static isInitialized(projectRoot) {
341
+ return (0, directory_1.isInitialized)(path.resolve(projectRoot));
342
+ }
343
+ /**
344
+ * Close the CodeGraph instance and release resources
345
+ */
346
+ close() {
347
+ this.unwatch();
348
+ // Release file lock if held
349
+ this.fileLock.release();
350
+ this.db.close();
351
+ }
352
+ /**
353
+ * Get the project root directory
354
+ */
355
+ getProjectRoot() {
356
+ return this.projectRoot;
357
+ }
358
+ // ===========================================================================
359
+ // Indexing
360
+ // ===========================================================================
361
+ /**
362
+ * Index all files in the project
363
+ *
364
+ * Uses a mutex to prevent concurrent indexing operations.
365
+ */
366
+ async indexAll(options = {}) {
367
+ return this.indexMutex.withLock(async () => {
368
+ try {
369
+ this.fileLock.acquire();
370
+ }
371
+ catch {
372
+ 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 };
373
+ }
374
+ // Defer WAL auto-checkpointing for the whole bulk run (#1231): the
375
+ // default 1000-page interval re-writes hot pages into the main DB file
376
+ // over and over — ~95% of all disk I/O during a bulk index, and a
377
+ // 19+min → 45s difference on HDD-class storage. The valve bounds WAL
378
+ // growth by backfilling PASSIVEly on a worker thread (never blocking
379
+ // the writer or the #850 watchdog heartbeat); runMaintenance below does
380
+ // the final fold-up before the interval is restored in the finally.
381
+ // Kill switch: CODEGRAPH_NO_WAL_DEFER=1. Non-WAL journal modes (some
382
+ // network filesystems) have no WAL to defer — skip.
383
+ const deferWal = process.env.CODEGRAPH_NO_WAL_DEFER !== '1' && this.db.getJournalMode() === 'wal';
384
+ let walValve = null;
385
+ let priorAutocheckpoint = 1000;
386
+ if (deferWal) {
387
+ priorAutocheckpoint = this.db.getWalAutocheckpoint();
388
+ this.db.setWalAutocheckpoint(0);
389
+ walValve = new wal_valve_1.WalCheckpointValve(this.db, undefined, undefined, options.verbose ? (m) => console.log(`[wal-valve] ${m}`) : undefined);
390
+ walValve.start();
391
+ }
392
+ try {
393
+ const before = this.queries.getNodeAndEdgeCount();
394
+ // Mark the index as in-flight BEFORE any writes: a run killed
395
+ // mid-index (OOM, SIGKILL, the #850 liveness watchdog) leaves this
396
+ // marker behind, so `codegraph status` can tell a truncated index
397
+ // from a completed one instead of silently serving partial results.
398
+ try {
399
+ this.queries.setMetadata('index_state', 'indexing');
400
+ }
401
+ catch { /* metadata is advisory */ }
402
+ // Segment vocabulary starts empty and is repopulated by the node write
403
+ // path as every file (re-)indexes below — so a full index is also the
404
+ // orphan-cleanup pass for names deleted since the last one.
405
+ try {
406
+ this.queries.clearNameSegmentVocab();
407
+ }
408
+ catch { /* vocab is advisory — never fail an index over it */ }
409
+ const result = await this.orchestrator.indexAll(options.onProgress, options.signal, options.verbose, walValve ? () => walValve.backpressure() : undefined);
410
+ // Fold the parse phase's WAL BEFORE the first post-parse reads
411
+ // (resolver re-init and resolution both read on the main thread):
412
+ // paging a bulk-write-sized WAL there is what blew the #850
413
+ // watchdog's 60s window in the #1231 repro. Off-thread + awaited,
414
+ // so the event loop keeps turning.
415
+ if (walValve)
416
+ await walValve.foldNow();
417
+ // Re-detect frameworks now that the index is populated. The resolver
418
+ // is constructed with createResolver() before any files exist, so
419
+ // framework resolvers whose detect() consults the indexed file list
420
+ // (e.g. UIKit/SwiftUI scanning for imports, swift-objc-bridge looking
421
+ // for both Swift and ObjC files) all return false on that initial pass
422
+ // and silently drop themselves. Re-initializing here gives them a
423
+ // chance to see the actual project before resolution runs.
424
+ if (result.success && result.filesIndexed > 0) {
425
+ this.resolver.initialize();
426
+ // Cross-file finalization (e.g. NestJS RouterModule prefixes). Runs
427
+ // before resolution so updated names show up in subsequent reads.
428
+ this.resolver.runPostExtract();
429
+ }
430
+ // Resolve references to create call/import/extends edges
431
+ if (result.success && result.filesIndexed > 0) {
432
+ // Get count without loading all refs into memory
433
+ const unresolvedCount = this.queries.getUnresolvedReferencesCount();
434
+ options.onProgress?.({
435
+ phase: 'resolving',
436
+ current: 0,
437
+ total: unresolvedCount,
438
+ });
439
+ await this.resolveReferencesBatched((current, total) => {
440
+ options.onProgress?.({
441
+ phase: 'resolving',
442
+ current,
443
+ total,
444
+ });
445
+ });
446
+ // Second pass: chained calls whose method lives on a supertype the
447
+ // receiver conforms to (protocol-extension / inherited / default-
448
+ // interface). Needs the implements/extends edges the main pass just
449
+ // built, so it runs after resolution (#750).
450
+ const tChained = Date.now();
451
+ await this.resolver.resolveChainedCallsViaConformance();
452
+ if (process.env.CODEGRAPH_SYNTH_TIMINGS)
453
+ console.error(`[synth-timing] chainedConformance: ${Date.now() - tChained}ms`);
454
+ // Same lifecycle for `this.<member>` callback registrations whose
455
+ // member is inherited from a supertype (#808).
456
+ const tDeferred = Date.now();
457
+ await this.resolver.resolveDeferredThisMemberRefs();
458
+ if (process.env.CODEGRAPH_SYNTH_TIMINGS)
459
+ console.error(`[synth-timing] deferredThisMember: ${Date.now() - tDeferred}ms`);
460
+ }
461
+ // Refresh planner stats + checkpoint the WAL after bulk writes.
462
+ // Off-thread (worker connection): on a multi-GB index this is minutes
463
+ // of IO, and inline it starved the #850 watchdog AFTER a fully
464
+ // successful index. Never load-bearing for correctness.
465
+ if (result.success && result.filesIndexed > 0) {
466
+ const tMaint = Date.now();
467
+ // Quiesce the valve first so its in-flight checkpoint and the
468
+ // maintenance checkpoint don't contend for the checkpointer lock
469
+ // (the loser would silently no-op and leave the WAL unfolded).
470
+ if (walValve) {
471
+ walValve.stop();
472
+ await walValve.drain();
473
+ }
474
+ await this.db.runMaintenance();
475
+ if (process.env.CODEGRAPH_SYNTH_TIMINGS)
476
+ console.error(`[phase-timing] maintenance: ${Date.now() - tMaint}ms`);
477
+ }
478
+ // The orchestrator only sees extraction-phase counts; resolution and
479
+ // synthesizer edges (often >50% of the graph on JVM repos) come later.
480
+ // Recompute against the DB so the CLI summary reports the true totals.
481
+ if (result.success && result.filesIndexed > 0) {
482
+ const tCount = Date.now();
483
+ const after = this.queries.getNodeAndEdgeCount();
484
+ if (process.env.CODEGRAPH_SYNTH_TIMINGS)
485
+ console.error(`[phase-timing] count-recompute: ${Date.now() - tCount}ms`);
486
+ result.nodesCreated = after.nodes - before.nodes;
487
+ result.edgesCreated = after.edges - before.edges;
488
+ }
489
+ // Stamp the index with the engine that built it, so `codegraph status`
490
+ // and `codegraph upgrade` can recommend a re-index when the running
491
+ // engine produces richer extraction than the one on disk. Only on a
492
+ // real full index — a sync touches a subset, so it must NOT advance the
493
+ // extraction stamp (the bulk would still be stale). See extraction-version.ts.
494
+ if (result.success && result.filesIndexed > 0) {
495
+ try {
496
+ this.queries.setMetadata('indexed_with_version', version_1.CodeGraphPackageVersion);
497
+ this.queries.setMetadata('indexed_with_extraction_version', String(extraction_version_1.EXTRACTION_VERSION));
498
+ }
499
+ catch { /* metadata is advisory — never fail an index over it */ }
500
+ }
501
+ // Reconcile the scan's ground truth against what the pipeline
502
+ // accounted for. A shortfall means files were silently dropped
503
+ // (observed in the wild: a run under heavy load came up 37 files
504
+ // short with no error) — record it and tell the user, don't let the
505
+ // index pass as complete.
506
+ try {
507
+ if (!result.success) {
508
+ this.queries.setMetadata('index_state', 'failed');
509
+ }
510
+ else {
511
+ const accounted = result.filesIndexed + result.filesSkipped + result.filesErrored;
512
+ const discovered = result.filesDiscovered;
513
+ const shortfall = discovered !== undefined ? discovered - accounted : 0;
514
+ if (discovered !== undefined && shortfall > 0) {
515
+ this.queries.setMetadata('index_state', 'partial');
516
+ this.queries.setMetadata('index_files_discovered', String(discovered));
517
+ this.queries.setMetadata('index_files_accounted', String(accounted));
518
+ result.errors.push({
519
+ message: `Index is missing ${shortfall} of ${discovered} discovered files (indexed ${result.filesIndexed}, skipped ${result.filesSkipped}, errored ${result.filesErrored}). The index is PARTIAL — re-run \`codegraph index\`.`,
520
+ severity: 'warning',
521
+ code: 'index_partial',
522
+ });
523
+ }
524
+ else {
525
+ this.queries.setMetadata('index_state', 'complete');
526
+ if (discovered !== undefined) {
527
+ this.queries.setMetadata('index_files_discovered', String(discovered));
528
+ this.queries.setMetadata('index_files_accounted', String(accounted));
529
+ }
530
+ }
531
+ }
532
+ }
533
+ catch { /* metadata is advisory — never fail an index over it */ }
534
+ return result;
535
+ }
536
+ finally {
537
+ // Restore the auto-checkpoint interval AFTER the fold-up above so the
538
+ // next ordinary write doesn't inherit a giant inline checkpoint. On
539
+ // the error path the WAL may still be large; correctness is unchanged
540
+ // (SQLite replays the WAL on the next open) and the follow-up write
541
+ // that folds it is the known cost of a failed run.
542
+ if (walValve) {
543
+ walValve.stop();
544
+ await walValve.drain();
545
+ }
546
+ if (deferWal) {
547
+ try {
548
+ this.db.setWalAutocheckpoint(priorAutocheckpoint);
549
+ }
550
+ catch { /* connection may be closing */ }
551
+ }
552
+ this.fileLock.release();
553
+ }
554
+ });
555
+ }
556
+ /**
557
+ * Index specific files
558
+ *
559
+ * Uses a mutex to prevent concurrent indexing operations.
560
+ */
561
+ async indexFiles(filePaths) {
562
+ return this.indexMutex.withLock(async () => {
563
+ try {
564
+ this.fileLock.acquire();
565
+ }
566
+ catch {
567
+ 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 };
568
+ }
569
+ try {
570
+ return this.orchestrator.indexFiles(filePaths);
571
+ }
572
+ finally {
573
+ this.fileLock.release();
574
+ }
575
+ });
576
+ }
577
+ /**
578
+ * Sync with current file state (incremental update)
579
+ *
580
+ * Uses a mutex to prevent concurrent indexing operations.
581
+ */
582
+ async sync(options = {}) {
583
+ return this.indexMutex.withLock(async () => {
584
+ try {
585
+ this.fileLock.acquire();
586
+ }
587
+ catch {
588
+ return { filesChecked: 0, filesAdded: 0, filesModified: 0, filesRemoved: 0, nodesUpdated: 0, durationMs: 0 };
589
+ }
590
+ try {
591
+ // Captured BEFORE the sync runs: the sync's own incremental writes
592
+ // populate vocab rows for the files it touches, so an end-of-sync
593
+ // emptiness check would see "non-empty" and skip the backfill forever,
594
+ // leaving every unchanged file's names unsegmented.
595
+ const vocabWasEmpty = (() => {
596
+ try {
597
+ return this.queries.isNameSegmentVocabEmpty();
598
+ }
599
+ catch {
600
+ return false;
601
+ }
602
+ })();
603
+ const result = await this.orchestrator.sync(options.onProgress);
604
+ // Cross-file finalization (e.g. NestJS RouterModule prefixes). Run on
605
+ // every sync that touched files so edits to `app.module.ts` propagate
606
+ // to controllers in unchanged files. The pass is idempotent and cheap
607
+ // (regex over *.module.ts only).
608
+ if (result.filesAdded > 0 || result.filesModified > 0) {
609
+ this.resolver.runPostExtract();
610
+ }
611
+ else if (result.filesRemoved > 0) {
612
+ // A pure-removal sync still resolves refs below — the deletion path
613
+ // resurrects the removed file's incoming edges as pending refs
614
+ // (#1240 removal case) and the orphan sweep consumes them. In a
615
+ // long-lived process (daemon) the resolver's name caches were
616
+ // warmed against the pre-removal graph; drop them so resolution
617
+ // sees the post-removal state. (runPostExtract above clears caches
618
+ // itself, so the changed-files branch is already covered.)
619
+ this.resolver.clearCaches();
620
+ }
621
+ // Resolve references if files were updated
622
+ const filesChanged = result.filesAdded > 0 || result.filesModified > 0;
623
+ if (filesChanged) {
624
+ if (result.changedFilePaths) {
625
+ // Scope resolution to changed files (git fast path — bounded set)
626
+ const tRefLoad = Date.now();
627
+ const unresolvedRefs = this.queries.getUnresolvedReferencesByFiles(result.changedFilePaths);
628
+ if (process.env.CODEGRAPH_SYNTH_TIMINGS)
629
+ console.error(`[phase-timing] sync-ref-load: ${Date.now() - tRefLoad}ms (${unresolvedRefs.length} refs)`);
630
+ options.onProgress?.({
631
+ phase: 'resolving',
632
+ current: 0,
633
+ total: unresolvedRefs.length,
634
+ });
635
+ this.resolver.resolveAndPersist(unresolvedRefs, (current, total) => {
636
+ options.onProgress?.({
637
+ phase: 'resolving',
638
+ current,
639
+ total,
640
+ });
641
+ });
642
+ // Retry previously-failed refs the changed files may now satisfy
643
+ // (#1240). Scoped resolution above only re-resolves refs FROM the
644
+ // changed files — but when a changed file gains an export/symbol,
645
+ // refs in UNCHANGED files that failed against the old graph can
646
+ // now resolve, and nothing else ever revisits them (their rows
647
+ // were parked as status='failed' by an earlier completed pass).
648
+ // Look them up by the symbol names the changed files now carry
649
+ // and re-resolve just that set. On a sync where no failed ref
650
+ // matches, this is one indexed lookup.
651
+ const tRetry = Date.now();
652
+ const retryable = this.queries.getRetryableFailedReferences(this.queries.getNodeNamesByFiles(result.changedFilePaths));
653
+ if (retryable.length > 0) {
654
+ options.onProgress?.({
655
+ phase: 'resolving',
656
+ current: 0,
657
+ total: retryable.length,
658
+ });
659
+ await this.resolver.resolveAndPersistListYielding(retryable);
660
+ options.onProgress?.({
661
+ phase: 'resolving',
662
+ current: retryable.length,
663
+ total: retryable.length,
664
+ });
665
+ }
666
+ if (process.env.CODEGRAPH_SYNTH_TIMINGS)
667
+ console.error(`[phase-timing] sync-failed-ref-retry: ${Date.now() - tRetry}ms (${retryable.length} refs)`);
668
+ }
669
+ else {
670
+ // No git info — use batched resolution to avoid OOM
671
+ const unresolvedCount = this.queries.getUnresolvedReferencesCount();
672
+ options.onProgress?.({
673
+ phase: 'resolving',
674
+ current: 0,
675
+ total: unresolvedCount,
676
+ });
677
+ await this.resolveReferencesBatched((current, total) => {
678
+ options.onProgress?.({
679
+ phase: 'resolving',
680
+ current,
681
+ total,
682
+ });
683
+ });
684
+ }
685
+ }
686
+ // Orphan sweep (#1187). A resolution pass that dies mid-run — the #850
687
+ // daemon liveness watchdog's SIGKILL (#1122), Ctrl-C, a crash — leaves
688
+ // the refs it never reached in unresolved_refs, and the git-scoped fast
689
+ // path above never revisits them (it reads only the changed files'
690
+ // rows). Those files' call edges were then missing PERMANENTLY, with
691
+ // nothing to see except a too-small blast radius, until a full
692
+ // re-index. A completed pass takes every row it processed out of the
693
+ // PENDING set (resolved rows are deleted, unresolvable ones parked as
694
+ // status='failed' for the #1240 retry above), so any pending row now
695
+ // is such an orphan — or a row from an older engine's scoped pass.
696
+ // Grind them down with the batched resolver; this also makes a bare
697
+ // `codegraph sync` the recovery command for a wedged index. On a
698
+ // healthy index this is one COUNT query.
699
+ const orphanCount = this.queries.getUnresolvedReferencesCount();
700
+ if (orphanCount > 0) {
701
+ options.onProgress?.({
702
+ phase: 'resolving',
703
+ current: 0,
704
+ total: orphanCount,
705
+ });
706
+ await this.resolveReferencesBatched((current, total) => {
707
+ options.onProgress?.({
708
+ phase: 'resolving',
709
+ current,
710
+ total,
711
+ });
712
+ });
713
+ }
714
+ if (filesChanged || orphanCount > 0) {
715
+ // Second pass: chained calls whose method lives on a supertype the
716
+ // receiver conforms to (protocol-extension / inherited). Needs the
717
+ // implements/extends edges built above (#750).
718
+ await this.resolver.resolveChainedCallsViaConformance();
719
+ // Same lifecycle for `this.<member>` callback registrations whose
720
+ // member is inherited from a supertype (#808).
721
+ await this.resolver.resolveDeferredThisMemberRefs();
722
+ }
723
+ // Refresh planner stats + checkpoint the WAL after bulk writes.
724
+ // Off-thread — see indexAll's call site.
725
+ if (filesChanged || result.filesRemoved > 0 || orphanCount > 0) {
726
+ await this.db.runMaintenance();
727
+ }
728
+ // Heal the segment vocabulary on indexes built before the table
729
+ // existed (upgrade path): incremental writes above only cover changed
730
+ // files, so a vocab that was empty when this sync STARTED means the
731
+ // bulk was never segmented — backfill it (INSERT OR IGNORE, so the
732
+ // rows the sync just wrote are fine). Batched + yielding — sync can
733
+ // run on the daemon's liveness-watchdog thread (#850/#1091).
734
+ try {
735
+ if (vocabWasEmpty && this.queries.getNodeAndEdgeCount().nodes > 0) {
736
+ await this.rebuildNameSegmentVocab();
737
+ }
738
+ }
739
+ catch { /* vocab is advisory — never fail a sync over it */ }
740
+ return result;
741
+ }
742
+ finally {
743
+ this.fileLock.release();
744
+ }
745
+ });
746
+ }
747
+ /**
748
+ * Check if an indexing operation is currently in progress
749
+ */
750
+ isIndexing() {
751
+ return this.indexMutex.isLocked();
752
+ }
753
+ // ===========================================================================
754
+ // File Watching
755
+ // ===========================================================================
756
+ /**
757
+ * Start watching for file changes and auto-syncing.
758
+ *
759
+ * Uses native OS file events (FSEvents on macOS, inotify on Linux 19+,
760
+ * ReadDirectoryChangesW on Windows) with debouncing to avoid thrashing.
761
+ *
762
+ * @param options - Watch options (debounce delay, callbacks)
763
+ * @returns true if watching started successfully
764
+ */
765
+ watch(options = {}) {
766
+ if (this.watcher?.isActive())
767
+ return true;
768
+ this.watcher = new sync_1.FileWatcher(this.projectRoot, async () => {
769
+ const result = await this.sync();
770
+ // sync() returns this exact zero-shape iff it failed to acquire the
771
+ // file lock (a real empty sync always has filesChecked > 0 because
772
+ // scanDirectory ran). Surface that to the watcher as a typed error
773
+ // so it keeps pendingFiles + reschedules instead of clearing them
774
+ // (#449).
775
+ if (result.filesChecked === 0 && result.durationMs === 0) {
776
+ throw new sync_1.LockUnavailableError();
777
+ }
778
+ const filesChanged = result.filesAdded + result.filesModified + result.filesRemoved;
779
+ return { filesChanged, durationMs: result.durationMs };
780
+ }, options);
781
+ return this.watcher.start();
782
+ }
783
+ /**
784
+ * Stop watching for file changes.
785
+ */
786
+ unwatch() {
787
+ if (this.watcher) {
788
+ this.watcher.stop();
789
+ this.watcher = null;
790
+ }
791
+ }
792
+ /**
793
+ * Check if the file watcher is active.
794
+ */
795
+ isWatching() {
796
+ return this.watcher?.isActive() ?? false;
797
+ }
798
+ /**
799
+ * True once live watching has permanently degraded (OS watch-resource
800
+ * exhaustion, or a write lock held past the retry budget) and auto-sync is
801
+ * disabled until the next {@link watch} call. Distinct from `!isWatching()`:
802
+ * a stopped/never-started watcher is inactive but NOT degraded. MCP tools use
803
+ * this to surface a whole-index "results may be stale" notice, since
804
+ * `getPendingFiles()` goes empty once watching stops (#876).
805
+ */
806
+ isWatcherDegraded() {
807
+ return this.watcher?.isDegraded() ?? false;
808
+ }
809
+ /** The reason live watching degraded, or null if it is healthy (#876). */
810
+ getWatcherDegradedReason() {
811
+ return this.watcher?.getDegradedReason() ?? null;
812
+ }
813
+ /**
814
+ * Files seen by the file watcher since the last successful sync —
815
+ * the per-file "stale" signal MCP tools attach to responses so an agent
816
+ * can fall back to {@link Read} for just the affected file without
817
+ * waiting for a debounced sync to complete (issue #403).
818
+ *
819
+ * Returns an empty list when the watcher isn't active, or no events have
820
+ * arrived. Each entry includes `firstSeenMs` and `lastSeenMs` (wall-clock
821
+ * `Date.now()` values) so callers can render "edited Nms ago", plus an
822
+ * `indexing` flag indicating whether the in-flight sync (if any) will
823
+ * absorb that file.
824
+ */
825
+ getPendingFiles() {
826
+ return this.watcher?.getPendingFiles() ?? [];
827
+ }
828
+ /**
829
+ * Resolves once the file watcher has installed its watch set. Useful for
830
+ * tests that need a deterministic boundary before asserting on
831
+ * `getPendingFiles()`. Resolves immediately when no watcher is active.
832
+ */
833
+ waitUntilWatcherReady(timeoutMs) {
834
+ return this.watcher ? this.watcher.waitUntilReady(timeoutMs) : Promise.resolve();
835
+ }
836
+ /**
837
+ * Get files that have changed since last index
838
+ */
839
+ getChangedFiles() {
840
+ return this.orchestrator.getChangedFiles();
841
+ }
842
+ /**
843
+ * Most recent index timestamp (ms since epoch) across all tracked files, or
844
+ * null when nothing is indexed yet. Lets library consumers check index
845
+ * freshness without shelling out to `codegraph status --json`. (#329)
846
+ */
847
+ getLastIndexedAt() {
848
+ return this.queries.getLastIndexedAt();
849
+ }
850
+ /**
851
+ * Completeness of the last full index run. `'complete'` is the only good
852
+ * state. `'indexing'` after the fact means a run was killed mid-index (OOM,
853
+ * SIGKILL, liveness watchdog) and the on-disk index is truncated;
854
+ * `'partial'` means the run finished but silently dropped files
855
+ * (discovered > indexed+skipped+errored); `'failed'` means it reported
856
+ * failure. `null` = index predates this marker. Surfaced by
857
+ * `codegraph status`.
858
+ */
859
+ getIndexState() {
860
+ const raw = this.queries.getMetadata('index_state');
861
+ return raw === 'indexing' || raw === 'complete' || raw === 'partial' || raw === 'failed'
862
+ ? raw
863
+ : null;
864
+ }
865
+ /**
866
+ * Which engine built the current index: the package version + extraction
867
+ * version stamped at the last full `indexAll`. Either field is null for an
868
+ * index built before stamping existed (treated as stale). See
869
+ * `extraction-version.ts` and `isIndexStale()`.
870
+ */
871
+ getIndexBuildInfo() {
872
+ const version = this.queries.getMetadata('indexed_with_version');
873
+ const ev = this.queries.getMetadata('indexed_with_extraction_version');
874
+ const parsed = ev != null ? parseInt(ev, 10) : NaN;
875
+ return { version, extractionVersion: Number.isFinite(parsed) ? parsed : null };
876
+ }
877
+ /**
878
+ * True when the on-disk index was built by an engine whose extraction is
879
+ * older than the one now running — i.e. a re-index would add data a migration
880
+ * can't backfill. False when there's no index yet (nothing to refresh) or the
881
+ * stamp is current. This is the signal behind `codegraph status`'s re-index
882
+ * hint and `codegraph upgrade`'s reminder.
883
+ */
884
+ isIndexStale() {
885
+ if (this.queries.getLastIndexedAt() == null)
886
+ return false;
887
+ const { extractionVersion } = this.getIndexBuildInfo();
888
+ return extractionVersion == null || extractionVersion < extraction_version_1.EXTRACTION_VERSION;
889
+ }
890
+ /**
891
+ * Extract nodes and edges from source code (without storing)
892
+ */
893
+ extractFromSource(filePath, source) {
894
+ return (0, extraction_1.extractFromSource)(filePath, source);
895
+ }
896
+ // ===========================================================================
897
+ // Reference Resolution
898
+ // ===========================================================================
899
+ /**
900
+ * Resolve unresolved references and create edges
901
+ *
902
+ * This method takes unresolved references from extraction and attempts
903
+ * to resolve them using multiple strategies:
904
+ * - Framework-specific patterns (React, Express, Laravel)
905
+ * - Import-based resolution
906
+ * - Name-based symbol matching
907
+ */
908
+ resolveReferences(onProgress) {
909
+ // Get all unresolved references from the database
910
+ const unresolvedRefs = this.queries.getUnresolvedReferences();
911
+ return this.resolver.resolveAndPersist(unresolvedRefs, onProgress);
912
+ }
913
+ /**
914
+ * Resolve references in batches to keep memory bounded on large codebases.
915
+ * Processes chunks of unresolved refs, persisting results after each batch.
916
+ */
917
+ async resolveReferencesBatched(onProgress) {
918
+ return this.resolver.resolveAndPersistBatched(onProgress);
919
+ }
920
+ /**
921
+ * References extracted but never attempted by a resolution pass. Zero on a
922
+ * healthy index — a completed pass consumes every pending row (resolving it
923
+ * or parking it as failed, #1240). Non-zero at rest means a pass was
924
+ * interrupted mid-run (killed indexer, crash — #1187), so some files' call
925
+ * edges are missing; the next `sync` sweeps them.
926
+ */
927
+ getPendingReferenceCount() {
928
+ return this.queries.getUnresolvedReferencesCount();
929
+ }
930
+ /**
931
+ * Get detected frameworks in the project
932
+ */
933
+ getDetectedFrameworks() {
934
+ return this.resolver.getDetectedFrameworks();
935
+ }
936
+ /**
937
+ * Re-initialize the resolver (useful after adding new files)
938
+ */
939
+ reinitializeResolver() {
940
+ this.resolver.initialize();
941
+ }
942
+ // ===========================================================================
943
+ // Graph Statistics
944
+ // ===========================================================================
945
+ /**
946
+ * Get statistics about the knowledge graph
947
+ */
948
+ getStats() {
949
+ const stats = this.queries.getStats();
950
+ stats.dbSizeBytes = this.db.getSize();
951
+ return stats;
952
+ }
953
+ /**
954
+ * Active SQLite backend for this project's connection — `node-sqlite` under
955
+ * Node (Node's built-in real-SQLite module) or `bun-sqlite` under Bun (Bun's
956
+ * native SQLite binding). Surfaced via `codegraph status` and the
957
+ * `codegraph_status` MCP tool alongside the effective journal mode.
958
+ */
959
+ getBackend() {
960
+ return this.db.getBackend();
961
+ }
962
+ /**
963
+ * The journal mode actually in effect ('wal', 'delete', …). 'wal' means
964
+ * readers never block on a concurrent writer; anything else means they can,
965
+ * which is the precondition for the "database is locked" failures in issue
966
+ * #238. Surfaced via `codegraph status` and the `codegraph_status` MCP tool.
967
+ */
968
+ getJournalMode() {
969
+ return this.db.getJournalMode();
970
+ }
971
+ // ===========================================================================
972
+ // Node Operations
973
+ // ===========================================================================
974
+ /**
975
+ * Get a node by ID
976
+ */
977
+ getNode(id) {
978
+ return this.queries.getNodeById(id);
979
+ }
980
+ /**
981
+ * Get all nodes in a file
982
+ */
983
+ getNodesInFile(filePath) {
984
+ return this.queries.getNodesByFile(filePath);
985
+ }
986
+ /**
987
+ * Get all nodes of a specific kind
988
+ */
989
+ getNodesByKind(kind) {
990
+ return this.queries.getNodesByKind(kind);
991
+ }
992
+ /**
993
+ * Get ALL nodes with an exact name (direct index lookup, not FTS-ranked/capped).
994
+ * Used to enumerate every overload of a heavily-overloaded name so the specific
995
+ * definition the caller wants is never dropped below a search cut.
996
+ */
997
+ getNodesByName(name) {
998
+ return this.queries.getNodesByName(name);
999
+ }
1000
+ /** Nodes whose name starts with `prefix` (index range scan, capped). */
1001
+ getNodesByNamePrefix(prefix, limit = 20) {
1002
+ return this.queries.getNodesByNamePrefix(prefix, limit);
1003
+ }
1004
+ /**
1005
+ * Search nodes by text
1006
+ */
1007
+ searchNodes(query, options) {
1008
+ return this.queries.searchNodes(query, options);
1009
+ }
1010
+ /**
1011
+ * Graph-derived prompt matching for the front-load hook's MEDIUM tier:
1012
+ * which indexed symbols do these prose words name? "state machine des
1013
+ * commandes" → `OrderStateMachine`, in any human language whose technical
1014
+ * nouns are Latin script — no keyword list involved.
1015
+ *
1016
+ * Precision comes from the repo's own naming statistics, not vocabulary:
1017
+ * - CO-OCCURRENCE: ≥2 words that are segments of the SAME name ("state" +
1018
+ * "machine" → OrderStateMachine) is strong evidence and always qualifies.
1019
+ * - RARITY: a single matched word qualifies only when its segment is
1020
+ * discriminative here (≤ {@link SEGMENT_RARITY_CEILING} distinct names) —
1021
+ * "checkout" in a shop backend yes, "state" in a react app no.
1022
+ * Every candidate is re-verified against `nodes` before being returned
1023
+ * (vocab rows are proposals; deletions leave orphans by design), so a
1024
+ * returned symbol is guaranteed to exist right now.
1025
+ */
1026
+ getSegmentMatches(words, limit = 6) {
1027
+ if (words.length === 0)
1028
+ return [];
1029
+ // Variant → original word (plural folding), for coverage accounting.
1030
+ const variantToWord = new Map();
1031
+ for (const word of words) {
1032
+ for (const variant of (0, identifier_segments_1.segmentLookupVariants)(word)) {
1033
+ if (!variantToWord.has(variant))
1034
+ variantToWord.set(variant, word);
1035
+ }
1036
+ }
1037
+ const variants = [...variantToWord.keys()];
1038
+ // Tier A: co-occurrence. The SQL folds variants back to their original
1039
+ // word (#1146), so minWords=2 means two distinct PROMPT WORDS — a name
1040
+ // matching both `service` and `services` can't tie with (or crowd past
1041
+ // the LIMIT) a genuine two-word match. The JS re-check below recomputes
1042
+ // the fold from live segments as the honesty layer.
1043
+ const variantPairs = [...variantToWord.entries()].map(([segment, word]) => ({ segment, word }));
1044
+ const candidates = [];
1045
+ for (const hit of this.queries.getSegmentCoOccurrence(variantPairs, 2, 24)) {
1046
+ const matched = this.wordsMatchingName(hit.name, variantToWord);
1047
+ if (matched.size >= 2)
1048
+ candidates.push({ name: hit.name, matchedWords: matched });
1049
+ }
1050
+ // Tier B: single rare word. Only when co-occurrence found nothing — a
1051
+ // co-occurring name is categorically stronger evidence — and under
1052
+ // stricter rules, because one word is thin: the word must be ≥5 chars
1053
+ // (measured FPs: "this", "typo"); the segment must appear in AT LEAST TWO
1054
+ // names (a concept the codebase is about clusters across names —
1055
+ // CheckoutService/CheckoutController — while a prose coincidence is a
1056
+ // singleton: measured FP "deploy to PRODUCTION" → the one name
1057
+ // matchesNonProductionDir); and the candidate name must have ≥2 segments
1058
+ // (a bare common verb matching a bare function name — "write" → `write` —
1059
+ // is prose coincidence, not the user naming a symbol).
1060
+ if (candidates.length === 0) {
1061
+ const singleWordVariants = variants.filter((v) => variantToWord.get(v).length >= 5);
1062
+ const counts = this.queries.getSegmentNameCounts(singleWordVariants);
1063
+ const rare = [...counts.entries()]
1064
+ .filter(([, n]) => n >= 2 && n <= CodeGraph.SEGMENT_RARITY_CEILING)
1065
+ .sort((a, b) => a[1] - b[1])
1066
+ .slice(0, 2);
1067
+ for (const [variant] of rare) {
1068
+ const word = variantToWord.get(variant);
1069
+ for (const name of this.queries.getNamesForSegment(variant, 12)) {
1070
+ if ((0, identifier_segments_1.splitIdentifierSegments)(name).length < 2)
1071
+ continue;
1072
+ candidates.push({ name, matchedWords: new Set([word]) });
1073
+ }
1074
+ }
1075
+ }
1076
+ // Verify against nodes (the honesty gate) and pick a representative
1077
+ // definition per name. A name whose only nodes are file/import kind has
1078
+ // no real definition to point at — surfacing the import statement instead
1079
+ // reads as a matched symbol but isn't one (#1144) — so it's skipped, the
1080
+ // same way an orphaned vocab row is. (Import names no longer enter the
1081
+ // vocab at write time, but rows written before that exclusion persist
1082
+ // until the next full index.)
1083
+ const out = [];
1084
+ const seen = new Set();
1085
+ candidates.sort((a, b) => b.matchedWords.size - a.matchedWords.size || a.name.length - b.name.length);
1086
+ for (const candidate of candidates) {
1087
+ if (out.length >= limit)
1088
+ break;
1089
+ if (seen.has(candidate.name))
1090
+ continue;
1091
+ seen.add(candidate.name);
1092
+ const nodes = this.queries.getNodesByName(candidate.name);
1093
+ if (nodes.length === 0)
1094
+ continue; // orphaned vocab row — name no longer exists
1095
+ const rep = nodes.find((n) => n.kind !== 'file' && n.kind !== 'import');
1096
+ if (!rep)
1097
+ continue; // no real definition — don't surface an import/file as one
1098
+ out.push({
1099
+ name: candidate.name,
1100
+ kind: rep.kind,
1101
+ filePath: rep.filePath,
1102
+ startLine: rep.startLine ?? 0,
1103
+ matchedWords: [...candidate.matchedWords].sort(),
1104
+ });
1105
+ }
1106
+ return out;
1107
+ }
1108
+ /** A single word ("state") can match hundreds of names in a big repo — that
1109
+ * is noise, not signal. Ceiling for the single-word tier; co-occurrence is
1110
+ * exempt because two words on one name is already discriminative. */
1111
+ static SEGMENT_RARITY_CEILING = 25;
1112
+ /** Which of the prompt's original words match `name`'s segments (via
1113
+ * variants). Segments are recomputed in JS — a name-keyed vocab lookup
1114
+ * would scan the (segment, name) primary key. */
1115
+ wordsMatchingName(name, variantToWord) {
1116
+ const segments = new Set((0, identifier_segments_1.splitIdentifierSegments)(name));
1117
+ const matched = new Set();
1118
+ for (const [variant, word] of variantToWord) {
1119
+ if (segments.has(variant))
1120
+ matched.add(word);
1121
+ }
1122
+ return matched;
1123
+ }
1124
+ /**
1125
+ * One-shot upgrade heal for callers that open the graph WITHOUT syncing —
1126
+ * concretely the prompt hook, whose MEDIUM tier reads the segment
1127
+ * vocabulary: a database migrated from before the vocab table existed
1128
+ * starts with it empty, and the only other backfill lives inside `sync()`,
1129
+ * which such callers never run (#1142). Returns true when the vocab is
1130
+ * usable (already populated — the overwhelmingly common one-SELECT case —
1131
+ * or healed here); false when it isn't (empty graph, or another process
1132
+ * holds the index lock — that process's own sync heals it).
1133
+ */
1134
+ async healSegmentVocabIfEmpty() {
1135
+ const empty = (() => {
1136
+ try {
1137
+ return this.queries.isNameSegmentVocabEmpty();
1138
+ }
1139
+ catch {
1140
+ return false;
1141
+ }
1142
+ })();
1143
+ if (!empty)
1144
+ return true;
1145
+ if (this.queries.getNodeAndEdgeCount().nodes === 0)
1146
+ return false;
1147
+ return this.indexMutex.withLock(async () => {
1148
+ try {
1149
+ this.fileLock.acquire();
1150
+ }
1151
+ catch {
1152
+ return false; // an index/sync is running — it backfills the vocab itself
1153
+ }
1154
+ try {
1155
+ if (!this.queries.isNameSegmentVocabEmpty())
1156
+ return true; // raced: healed meanwhile
1157
+ await this.rebuildNameSegmentVocab();
1158
+ return true;
1159
+ }
1160
+ finally {
1161
+ this.fileLock.release();
1162
+ }
1163
+ });
1164
+ }
1165
+ /**
1166
+ * Rebuild the segment vocabulary from the current graph, batched and
1167
+ * yielding — the upgrade-heal path for indexes built before the vocab table
1168
+ * existed. Runs inside the index mutex/lock (sync and
1169
+ * healSegmentVocabIfEmpty hold them).
1170
+ */
1171
+ async rebuildNameSegmentVocab() {
1172
+ const maybeYield = (0, cooperative_yield_1.createYielder)();
1173
+ const BATCH = 2000;
1174
+ for (let offset = 0;; offset += BATCH) {
1175
+ const names = this.queries.getDistinctNodeNames(BATCH, offset);
1176
+ if (names.length === 0)
1177
+ break;
1178
+ this.queries.insertNameSegmentsBatch(names);
1179
+ await maybeYield();
1180
+ }
1181
+ }
1182
+ /**
1183
+ * Normalized project-name tokens (go.mod / package.json / repo dir) used to
1184
+ * down-weight the non-discriminative project name in search ranking (#720).
1185
+ * Exposed so explore can exclude it from the PascalCase type-disambiguation
1186
+ * bias, which would otherwise pull overloaded tokens toward whichever stack
1187
+ * embeds the project name.
1188
+ */
1189
+ getProjectNameTokens() {
1190
+ return this.queries.getProjectNameTokens();
1191
+ }
1192
+ /**
1193
+ * Find the project's "primary route file" — the file with the densest
1194
+ * concentration of framework-emitted `route` nodes (≥3 routes, ≥30%
1195
+ * of all non-test routes). Used to inline the routing config in
1196
+ * `codegraph_explore` responses on small realworld template repos
1197
+ * (rails-realworld, laravel-realworld, drupal-admintoolbar, …) where
1198
+ * Glob+Read of `routes.rb`/`urls.py`/etc. otherwise beats codegraph.
1199
+ */
1200
+ getTopRouteFile() {
1201
+ return this.queries.getTopRouteFile();
1202
+ }
1203
+ /**
1204
+ * Build a URL → handler routing manifest from the index. Each entry
1205
+ * pairs a route node (URL + method) with its handler function/method
1206
+ * via the `references` edge that framework resolvers emit. Returns
1207
+ * null when fewer than 3 valid (non-test) routes exist.
1208
+ */
1209
+ getRoutingManifest(limit) {
1210
+ return this.queries.getRoutingManifest(limit);
1211
+ }
1212
+ // ===========================================================================
1213
+ // Edge Operations
1214
+ // ===========================================================================
1215
+ /**
1216
+ * Get outgoing edges from a node
1217
+ */
1218
+ getOutgoingEdges(nodeId) {
1219
+ return this.queries.getOutgoingEdges(nodeId);
1220
+ }
1221
+ /**
1222
+ * Get incoming edges to a node
1223
+ */
1224
+ getIncomingEdges(nodeId) {
1225
+ return this.queries.getIncomingEdges(nodeId);
1226
+ }
1227
+ // ===========================================================================
1228
+ // File Operations
1229
+ // ===========================================================================
1230
+ /**
1231
+ * Get a file record by path
1232
+ */
1233
+ getFile(filePath) {
1234
+ return this.queries.getFileByPath(filePath);
1235
+ }
1236
+ /**
1237
+ * Get all tracked files
1238
+ */
1239
+ getFiles() {
1240
+ return this.queries.getAllFiles();
1241
+ }
1242
+ // ===========================================================================
1243
+ // Graph Query Methods
1244
+ // ===========================================================================
1245
+ /**
1246
+ * Get the context for a node (ancestors, children, references)
1247
+ *
1248
+ * Returns comprehensive context about a node including its containment
1249
+ * hierarchy, children, incoming/outgoing references, type information,
1250
+ * and relevant imports.
1251
+ *
1252
+ * @param nodeId - ID of the focal node
1253
+ * @returns Context object with all related information
1254
+ */
1255
+ getContext(nodeId) {
1256
+ return this.graphManager.getContext(nodeId);
1257
+ }
1258
+ /**
1259
+ * Traverse the graph from a starting node
1260
+ *
1261
+ * Uses breadth-first search by default. Supports filtering by edge types,
1262
+ * node types, and traversal direction.
1263
+ *
1264
+ * @param startId - Starting node ID
1265
+ * @param options - Traversal options
1266
+ * @returns Subgraph containing traversed nodes and edges
1267
+ */
1268
+ traverse(startId, options) {
1269
+ return this.traverser.traverseBFS(startId, options);
1270
+ }
1271
+ /**
1272
+ * Get the call graph for a function
1273
+ *
1274
+ * Returns both callers (functions that call this function) and
1275
+ * callees (functions called by this function) up to the specified depth.
1276
+ *
1277
+ * @param nodeId - ID of the function/method node
1278
+ * @param depth - Maximum depth in each direction (default: 2)
1279
+ * @returns Subgraph containing the call graph
1280
+ */
1281
+ getCallGraph(nodeId, depth = 2) {
1282
+ return this.traverser.getCallGraph(nodeId, depth);
1283
+ }
1284
+ /**
1285
+ * Get the type hierarchy for a class/interface
1286
+ *
1287
+ * Returns both ancestors (types this extends/implements) and
1288
+ * descendants (types that extend/implement this).
1289
+ *
1290
+ * @param nodeId - ID of the class/interface node
1291
+ * @returns Subgraph containing the type hierarchy
1292
+ */
1293
+ getTypeHierarchy(nodeId) {
1294
+ return this.traverser.getTypeHierarchy(nodeId);
1295
+ }
1296
+ /**
1297
+ * Find all usages of a symbol
1298
+ *
1299
+ * Returns all nodes that reference the specified symbol through
1300
+ * any edge type (calls, references, type_of, etc.).
1301
+ *
1302
+ * @param nodeId - ID of the symbol node
1303
+ * @returns Array of nodes and edges that reference this symbol
1304
+ */
1305
+ findUsages(nodeId) {
1306
+ return this.traverser.findUsages(nodeId);
1307
+ }
1308
+ /**
1309
+ * Get callers of a function/method
1310
+ *
1311
+ * @param nodeId - ID of the function/method node
1312
+ * @param maxDepth - Maximum depth to traverse (default: 1)
1313
+ * @returns Array of nodes that call this function
1314
+ */
1315
+ getCallers(nodeId, maxDepth = 1) {
1316
+ return this.traverser.getCallers(nodeId, maxDepth);
1317
+ }
1318
+ /**
1319
+ * Get callees of a function/method
1320
+ *
1321
+ * @param nodeId - ID of the function/method node
1322
+ * @param maxDepth - Maximum depth to traverse (default: 1)
1323
+ * @returns Array of nodes called by this function
1324
+ */
1325
+ getCallees(nodeId, maxDepth = 1) {
1326
+ return this.traverser.getCallees(nodeId, maxDepth);
1327
+ }
1328
+ /**
1329
+ * Calculate the impact radius of a node
1330
+ *
1331
+ * Returns all nodes that could be affected by changes to this node.
1332
+ *
1333
+ * @param nodeId - ID of the node
1334
+ * @param maxDepth - Maximum depth to traverse (default: 3)
1335
+ * @returns Subgraph containing potentially impacted nodes
1336
+ */
1337
+ getImpactRadius(nodeId, maxDepth = 3) {
1338
+ return this.traverser.getImpactRadius(nodeId, maxDepth);
1339
+ }
1340
+ /**
1341
+ * Find the shortest path between two nodes
1342
+ *
1343
+ * @param fromId - Starting node ID
1344
+ * @param toId - Target node ID
1345
+ * @param edgeKinds - Edge types to consider (all if empty)
1346
+ * @returns Array of nodes and edges forming the path, or null if no path exists
1347
+ */
1348
+ findPath(fromId, toId, edgeKinds) {
1349
+ return this.traverser.findPath(fromId, toId, edgeKinds);
1350
+ }
1351
+ /**
1352
+ * Get ancestors of a node in the containment hierarchy
1353
+ *
1354
+ * @param nodeId - ID of the node
1355
+ * @returns Array of ancestor nodes from immediate parent to root
1356
+ */
1357
+ getAncestors(nodeId) {
1358
+ return this.traverser.getAncestors(nodeId);
1359
+ }
1360
+ /**
1361
+ * Get immediate children of a node
1362
+ *
1363
+ * @param nodeId - ID of the node
1364
+ * @returns Array of child nodes
1365
+ */
1366
+ getChildren(nodeId) {
1367
+ return this.traverser.getChildren(nodeId);
1368
+ }
1369
+ /**
1370
+ * Get dependencies of a file
1371
+ *
1372
+ * @param filePath - Path to the file
1373
+ * @returns Array of file paths this file depends on
1374
+ */
1375
+ getFileDependencies(filePath) {
1376
+ return this.graphManager.getFileDependencies(filePath);
1377
+ }
1378
+ /**
1379
+ * Get dependents of a file
1380
+ *
1381
+ * @param filePath - Path to the file
1382
+ * @returns Array of file paths that depend on this file
1383
+ */
1384
+ getFileDependents(filePath) {
1385
+ return this.graphManager.getFileDependents(filePath);
1386
+ }
1387
+ /**
1388
+ * Find circular dependencies in the codebase
1389
+ *
1390
+ * @returns Array of cycles, each cycle is an array of file paths
1391
+ */
1392
+ findCircularDependencies() {
1393
+ return this.graphManager.findCircularDependencies();
1394
+ }
1395
+ /**
1396
+ * Find dead code (unreferenced symbols)
1397
+ *
1398
+ * @param kinds - Node kinds to check (default: functions, methods, classes)
1399
+ * @returns Array of unreferenced nodes
1400
+ */
1401
+ findDeadCode(kinds) {
1402
+ return this.graphManager.findDeadCode(kinds);
1403
+ }
1404
+ /**
1405
+ * Get complexity metrics for a node
1406
+ *
1407
+ * @param nodeId - ID of the node
1408
+ * @returns Object containing various complexity metrics
1409
+ */
1410
+ getNodeMetrics(nodeId) {
1411
+ return this.graphManager.getNodeMetrics(nodeId);
1412
+ }
1413
+ // ===========================================================================
1414
+ // Context Building
1415
+ // ===========================================================================
1416
+ /**
1417
+ * Get the source code for a node
1418
+ *
1419
+ * Reads the file and extracts the code between startLine and endLine.
1420
+ *
1421
+ * @param nodeId - ID of the node
1422
+ * @returns Code string or null if not found
1423
+ */
1424
+ async getCode(nodeId) {
1425
+ return this.contextBuilder.getCode(nodeId);
1426
+ }
1427
+ /**
1428
+ * Find relevant subgraph for a query
1429
+ *
1430
+ * Combines semantic search with graph traversal to find the most
1431
+ * relevant nodes and their relationships for a given query.
1432
+ *
1433
+ * @param query - Natural language query describing the task
1434
+ * @param options - Search and traversal options
1435
+ * @returns Subgraph of relevant nodes and edges
1436
+ */
1437
+ async findRelevantContext(query, options) {
1438
+ return this.contextBuilder.findRelevantContext(query, options);
1439
+ }
1440
+ /**
1441
+ * Build context for a task
1442
+ *
1443
+ * Creates comprehensive context by:
1444
+ * 1. Running FTS search to find entry points
1445
+ * 2. Expanding the graph around entry points
1446
+ * 3. Extracting code blocks for key nodes
1447
+ * 4. Formatting output for Claude
1448
+ *
1449
+ * @param input - Task description (string or {title, description})
1450
+ * @param options - Build options (maxNodes, includeCode, format, etc.)
1451
+ * @returns TaskContext object or formatted string (markdown/JSON)
1452
+ */
1453
+ async buildContext(input, options) {
1454
+ return this.contextBuilder.buildContext(input, options);
1455
+ }
1456
+ // ===========================================================================
1457
+ // Database Management
1458
+ // ===========================================================================
1459
+ /**
1460
+ * Optimize the database (vacuum and analyze)
1461
+ */
1462
+ optimize() {
1463
+ this.db.optimize();
1464
+ }
1465
+ /**
1466
+ * Clear all data from the graph
1467
+ */
1468
+ clear() {
1469
+ this.queries.clear();
1470
+ }
1471
+ /**
1472
+ * Alias for close() for backwards compatibility.
1473
+ * @deprecated Use close() instead
1474
+ */
1475
+ destroy() {
1476
+ this.close();
1477
+ }
1478
+ /**
1479
+ * Completely remove CodeGraph from the project.
1480
+ * This closes the database and deletes the .CodeGraph directory.
1481
+ *
1482
+ * WARNING: This permanently deletes all CodeGraph data for the project.
1483
+ */
1484
+ uninitialize() {
1485
+ this.close();
1486
+ (0, directory_1.removeDirectory)(this.projectRoot);
1487
+ }
1488
+ }
1489
+ exports.CodeGraph = CodeGraph;
1490
+ // Default export
1491
+ exports.default = CodeGraph;
1492
+ //# sourceMappingURL=index.js.map