@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
@@ -0,0 +1,2249 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /**
4
+ * CodeGraph CLI
5
+ *
6
+ * Command-line interface for CodeGraph code intelligence.
7
+ *
8
+ * Usage:
9
+ * codegraph Run interactive installer (when no args)
10
+ * codegraph install Run interactive installer
11
+ * codegraph uninstall Remove CodeGraph from your agents
12
+ * codegraph init [path] Initialize CodeGraph in a project
13
+ * codegraph uninit [path] Remove CodeGraph from a project
14
+ * codegraph index [path] Index all files in the project
15
+ * codegraph sync [path] Sync changes since last index
16
+ * codegraph status [path] Show index status
17
+ * codegraph query <search> Search for symbols
18
+ * codegraph files [options] Show project file structure
19
+ * codegraph context <task> Build context for a task
20
+ * codegraph callers <symbol> Find what calls a function/method
21
+ * codegraph callees <symbol> Find what a function/method calls
22
+ * codegraph impact <symbol> Analyze what code is affected by changing a symbol
23
+ * codegraph affected [files] Find test files affected by changes
24
+ * codegraph upgrade [version] Update CodeGraph to the latest release
25
+ */
26
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
27
+ if (k2 === undefined) k2 = k;
28
+ var desc = Object.getOwnPropertyDescriptor(m, k);
29
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
30
+ desc = { enumerable: true, get: function() { return m[k]; } };
31
+ }
32
+ Object.defineProperty(o, k2, desc);
33
+ }) : (function(o, m, k, k2) {
34
+ if (k2 === undefined) k2 = k;
35
+ o[k2] = m[k];
36
+ }));
37
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
38
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
39
+ }) : function(o, v) {
40
+ o["default"] = v;
41
+ });
42
+ var __importStar = (this && this.__importStar) || (function () {
43
+ var ownKeys = function(o) {
44
+ ownKeys = Object.getOwnPropertyNames || function (o) {
45
+ var ar = [];
46
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
47
+ return ar;
48
+ };
49
+ return ownKeys(o);
50
+ };
51
+ return function (mod) {
52
+ if (mod && mod.__esModule) return mod;
53
+ var result = {};
54
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
55
+ __setModuleDefault(result, mod);
56
+ return result;
57
+ };
58
+ })();
59
+ Object.defineProperty(exports, "__esModule", { value: true });
60
+ // FIRST import, before anything else loads: capture process.ppid while our
61
+ // launcher is (almost certainly) still alive. A launcher killed mid-startup
62
+ // otherwise blinds the PPID watchdog forever (#1185) — see early-ppid.ts.
63
+ require("../mcp/early-ppid");
64
+ const commander_1 = require("commander");
65
+ const path = __importStar(require("path"));
66
+ const fs = __importStar(require("fs"));
67
+ const directory_1 = require("../directory");
68
+ const identifier_segments_1 = require("../search/identifier-segments");
69
+ const worktree_1 = require("../sync/worktree");
70
+ const shimmer_progress_1 = require("../ui/shimmer-progress");
71
+ const glyphs_1 = require("../ui/glyphs");
72
+ const node_version_check_1 = require("./node-version-check");
73
+ const fatal_handler_1 = require("./fatal-handler");
74
+ const wasm_runtime_flags_1 = require("../extraction/wasm-runtime-flags");
75
+ const command_supervision_1 = require("./command-supervision");
76
+ const extraction_version_1 = require("../extraction/extraction-version");
77
+ const telemetry_1 = require("../telemetry");
78
+ // Lazy-load heavy modules (CodeGraph, runInstaller) to keep CLI startup fast.
79
+ async function loadCodeGraph() {
80
+ try {
81
+ return await Promise.resolve().then(() => __importStar(require('../index')));
82
+ }
83
+ catch (err) {
84
+ const msg = err instanceof Error ? err.message : String(err);
85
+ console.error(`\x1b[31m${(0, glyphs_1.getGlyphs)().err}\x1b[0m Failed to load CodeGraph modules.`);
86
+ console.error(`\n Node: ${process.version} Platform: ${process.platform} ${process.arch}`);
87
+ console.error(`\n Error: ${msg}`);
88
+ console.error('\n Try reinstalling with: npm install -g @colbymchenry/codegraph\n');
89
+ process.exit(1);
90
+ }
91
+ }
92
+ // Dynamic import helper — tsc compiles import() to require() in CJS mode,
93
+ // which fails for ESM-only packages. This bypasses the transformation.
94
+ // eslint-disable-next-line @typescript-eslint/no-implied-eval
95
+ const importESM = new Function('specifier', 'return import(specifier)');
96
+ // Block CodeGraph on Node.js 25.x — V8's turboshaft WASM JIT has a Zone
97
+ // allocator bug that reliably crashes when compiling tree-sitter
98
+ // grammars (see #54, #81, #140). The previous behaviour was a soft
99
+ // console.warn that scrolls off-screen before the OOM crash 30 seconds
100
+ // later, leading to a steady stream of "what is this OOM" reports.
101
+ // Hard-exit before any WASM work; allow override via env var for users
102
+ // who patched V8 themselves or want to test a future fix.
103
+ const nodeVersion = process.versions.node;
104
+ const nodeMajor = parseInt(nodeVersion.split('.')[0] ?? '0', 10);
105
+ if (nodeMajor >= 25) {
106
+ process.stderr.write((0, node_version_check_1.buildNode25BlockBanner)(nodeVersion) + '\n');
107
+ if (!process.env.CODEGRAPH_ALLOW_UNSAFE_NODE) {
108
+ process.exit(1);
109
+ }
110
+ // Override active — banner shown for visibility, continuing.
111
+ }
112
+ // Enforce the supported Node floor. `engines` in package.json only *warns* on
113
+ // install (unless engine-strict), so hard-block here to actually keep users off
114
+ // unsupported versions. Mirrors the 25+ block above. See package.json `engines`.
115
+ if (nodeMajor < node_version_check_1.MIN_NODE_MAJOR) {
116
+ process.stderr.write((0, node_version_check_1.buildNodeTooOldBanner)(nodeVersion) + '\n');
117
+ if (!process.env.CODEGRAPH_ALLOW_UNSAFE_NODE) {
118
+ process.exit(1);
119
+ }
120
+ // Override active — banner shown for visibility, continuing.
121
+ }
122
+ // Re-exec with V8's `--liftoff-only` if it isn't already set, so tree-sitter's
123
+ // large WASM grammars never hit the turboshaft Zone OOM (`Fatal process out of
124
+ // memory: Zone`) on Node >= 22. No-op under the bundled launcher, which already
125
+ // passes the flag. Must run before any grammar (in the parse worker, which
126
+ // inherits this process's flags) is compiled. See ../extraction/wasm-runtime-flags.
127
+ (0, wasm_runtime_flags_1.relaunchWithWasmRuntimeFlagsIfNeeded)(__filename);
128
+ // Last-resort fatal handlers: log a bounded line and exit non-zero. A fault
129
+ // that reaches here escaped every boundary, so the process is in an undefined
130
+ // state — keeping it alive is what let the detached MCP daemon orphan and pin a
131
+ // CPU core with no recovery (#799, #850). Installed before the command branch
132
+ // so it also covers a synchronous throw during startup. See ./fatal-handler.
133
+ (0, fatal_handler_1.installFatalHandlers)();
134
+ // Check if running with no arguments - run installer
135
+ if (process.argv.length === 2) {
136
+ Promise.resolve().then(() => __importStar(require('../installer'))).then(({ runInstaller }) => runInstaller()).catch((err) => {
137
+ console.error('Installation failed:', err instanceof Error ? err.message : String(err));
138
+ process.exit(1);
139
+ });
140
+ }
141
+ else {
142
+ // Normal CLI flow
143
+ main();
144
+ }
145
+ function main() {
146
+ const program = new commander_1.Command();
147
+ // Version from package.json
148
+ const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf-8'));
149
+ // Make the version trivial to reach. commander's `.version()` (below) wires up
150
+ // `--version` and `-V`; intercept the spellings it can't — lowercase `-v` and
151
+ // single-dash `-version` — before any parsing. (commander's version short flag
152
+ // is the capital `-V`, and its parser rejects a multi-character single-dash
153
+ // flag.) The bare `codegraph version` subcommand is registered further down so
154
+ // the affordance also shows up in `codegraph --help`.
155
+ const firstArg = process.argv[2];
156
+ if (firstArg === '-v' || firstArg === '-version') {
157
+ console.log(packageJson.version);
158
+ return;
159
+ }
160
+ // =============================================================================
161
+ // ANSI Color Helpers (avoid chalk ESM issues)
162
+ // =============================================================================
163
+ const colors = {
164
+ reset: '\x1b[0m',
165
+ bold: '\x1b[1m',
166
+ dim: '\x1b[2m',
167
+ red: '\x1b[31m',
168
+ green: '\x1b[32m',
169
+ yellow: '\x1b[33m',
170
+ blue: '\x1b[34m',
171
+ cyan: '\x1b[36m',
172
+ white: '\x1b[37m',
173
+ gray: '\x1b[90m',
174
+ };
175
+ const chalk = {
176
+ bold: (s) => `${colors.bold}${s}${colors.reset}`,
177
+ dim: (s) => `${colors.dim}${s}${colors.reset}`,
178
+ red: (s) => `${colors.red}${s}${colors.reset}`,
179
+ green: (s) => `${colors.green}${s}${colors.reset}`,
180
+ yellow: (s) => `${colors.yellow}${s}${colors.reset}`,
181
+ blue: (s) => `${colors.blue}${s}${colors.reset}`,
182
+ cyan: (s) => `${colors.cyan}${s}${colors.reset}`,
183
+ white: (s) => `${colors.white}${s}${colors.reset}`,
184
+ gray: (s) => `${colors.gray}${s}${colors.reset}`,
185
+ };
186
+ program
187
+ .name('codegraph')
188
+ .description('Code intelligence and knowledge graph for any codebase')
189
+ .version(packageJson.version);
190
+ // Anonymous usage telemetry (see TELEMETRY.md): record the invoked subcommand
191
+ // NAME only — never arguments or paths. Counts buffer locally; network sends
192
+ // piggyback on commands that run long anyway (quick commands only append to
193
+ // the local buffer at exit, costing nothing).
194
+ // install/uninstall are absent on purpose: the installer flushes at its own
195
+ // end, AFTER its consent prompt — a flush here would fire the first-run
196
+ // notice before the user ever sees the toggle.
197
+ const TELEMETRY_FLUSH_COMMANDS = new Set(['init', 'uninit', 'index', 'sync', 'upgrade']);
198
+ program.hook('preAction', (_thisCommand, actionCommand) => {
199
+ try {
200
+ // The detached daemon re-invokes `serve --mcp` internally — not a user action.
201
+ if (process.env.CODEGRAPH_DAEMON_INTERNAL)
202
+ return;
203
+ const name = actionCommand.name();
204
+ if (name === 'telemetry')
205
+ return; // managing telemetry is not usage
206
+ (0, telemetry_1.getTelemetry)().recordUsage('cli_command', name, true);
207
+ if (TELEMETRY_FLUSH_COMMANDS.has(name))
208
+ (0, telemetry_1.getTelemetry)().maybeFlush();
209
+ }
210
+ catch {
211
+ /* telemetry must never break the CLI */
212
+ }
213
+ });
214
+ // =============================================================================
215
+ // Helper Functions
216
+ // =============================================================================
217
+ /**
218
+ * Resolve project path from argument or current directory
219
+ * Walks up parent directories to find nearest initialized CodeGraph project
220
+ * (must have .codegraph/codegraph.db, not just .codegraph/lessons.db)
221
+ */
222
+ function resolveProjectPath(pathArg) {
223
+ const absolutePath = path.resolve(pathArg || process.cwd());
224
+ // If exact path is initialized (has codegraph.db), use it
225
+ if ((0, directory_1.isInitialized)(absolutePath)) {
226
+ return absolutePath;
227
+ }
228
+ // Walk up to find nearest parent with CodeGraph initialized
229
+ // Note: findNearestCodeGraphRoot finds any .codegraph folder, but we need one with codegraph.db
230
+ let current = absolutePath;
231
+ const root = path.parse(current).root;
232
+ while (current !== root) {
233
+ const parent = path.dirname(current);
234
+ if (parent === current)
235
+ break;
236
+ current = parent;
237
+ if ((0, directory_1.isInitialized)(current)) {
238
+ return current;
239
+ }
240
+ }
241
+ // Not found - return original path (will fail later with helpful error)
242
+ return absolutePath;
243
+ }
244
+ /**
245
+ * Format a number with commas
246
+ */
247
+ function formatNumber(n) {
248
+ return n.toLocaleString();
249
+ }
250
+ /**
251
+ * Format duration in milliseconds to human readable
252
+ */
253
+ function formatDuration(ms) {
254
+ if (ms < 1000) {
255
+ return `${ms}ms`;
256
+ }
257
+ const seconds = ms / 1000;
258
+ if (seconds < 60) {
259
+ return `${seconds.toFixed(1)}s`;
260
+ }
261
+ const minutes = Math.floor(seconds / 60);
262
+ const remainingSeconds = seconds % 60;
263
+ return `${minutes}m ${remainingSeconds.toFixed(0)}s`;
264
+ }
265
+ // Shimmer progress renderer (runs in a worker thread for smooth animation)
266
+ // Imported at top of file from '../ui/shimmer-progress'
267
+ /**
268
+ * Create a plain-text progress callback for --verbose mode.
269
+ * No animations, no ANSI tricks — just timestamped lines to stdout.
270
+ */
271
+ function createVerboseProgress() {
272
+ let lastPhase = '';
273
+ let lastPct = -1;
274
+ const startTime = Date.now();
275
+ return (progress) => {
276
+ const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
277
+ if (progress.phase !== lastPhase) {
278
+ lastPhase = progress.phase;
279
+ lastPct = -1;
280
+ console.log(`[${elapsed}s] Phase: ${progress.phase}`);
281
+ }
282
+ if (progress.total > 0) {
283
+ const pct = Math.floor((progress.current / progress.total) * 100);
284
+ // Log every 5% to keep output manageable
285
+ if (pct >= lastPct + 5 || progress.current === progress.total) {
286
+ lastPct = pct;
287
+ console.log(`[${elapsed}s] ${progress.current}/${progress.total} (${pct}%)${progress.currentFile ? ` ${(0, glyphs_1.getGlyphs)().dash} ${progress.currentFile}` : ''}`);
288
+ }
289
+ }
290
+ else if (progress.current > 0) {
291
+ // Scanning phase (no total yet) — log periodically
292
+ if (progress.current % 1000 === 0 || progress.current === 1) {
293
+ console.log(`[${elapsed}s] ${formatNumber(progress.current)} files found`);
294
+ }
295
+ }
296
+ };
297
+ }
298
+ /**
299
+ * Print success message
300
+ */
301
+ function success(message) {
302
+ console.log(chalk.green((0, glyphs_1.getGlyphs)().ok) + ' ' + message);
303
+ }
304
+ /**
305
+ * Print error message
306
+ */
307
+ function error(message) {
308
+ console.error(chalk.red((0, glyphs_1.getGlyphs)().err) + ' ' + message);
309
+ }
310
+ /**
311
+ * Print info message
312
+ */
313
+ function info(message) {
314
+ console.log(chalk.blue((0, glyphs_1.getGlyphs)().info) + ' ' + message);
315
+ }
316
+ /**
317
+ * Print warning message
318
+ */
319
+ function warn(message) {
320
+ console.log(chalk.yellow((0, glyphs_1.getGlyphs)().warn) + ' ' + message);
321
+ }
322
+ /**
323
+ * Print indexing results using clack log methods
324
+ */
325
+ function printIndexResult(clack, result, projectPath) {
326
+ const hasErrors = result.filesErrored > 0;
327
+ // Surface non-file-level failures (e.g. lock-acquisition failure
328
+ // when another indexer is running) before the file-count branches.
329
+ // Without this the CLI falls through to "No files found to index",
330
+ // which is actively misleading — the index DID run, it just couldn't
331
+ // get the lock.
332
+ //
333
+ // If success is false but no severity:'error' entry exists in
334
+ // `result.errors` (degenerate case — shouldn't happen in practice
335
+ // but worth guarding because the result shape is plumbed through
336
+ // multiple call sites), fall back to a generic message rather than
337
+ // continuing to the misleading "No files found" branch or throwing.
338
+ if (!result.success && !hasErrors && result.filesIndexed === 0) {
339
+ const generic = result.errors.find((e) => e.severity === 'error');
340
+ clack.log.error(generic?.message ?? `Indexing failed ${(0, glyphs_1.getGlyphs)().dash} no further details available`);
341
+ return;
342
+ }
343
+ if (result.filesIndexed > 0) {
344
+ if (hasErrors) {
345
+ clack.log.success(`Indexed ${formatNumber(result.filesIndexed)} files (${formatNumber(result.filesErrored)} could not be parsed)`);
346
+ }
347
+ else {
348
+ clack.log.success(`Indexed ${formatNumber(result.filesIndexed)} files`);
349
+ }
350
+ clack.log.info(`${formatNumber(result.nodesCreated)} nodes, ${formatNumber(result.edgesCreated)} edges in ${formatDuration(result.durationMs)}`);
351
+ // A PARTIAL index (files silently dropped mid-pipeline) must not pass
352
+ // as a clean run — it's the difference between "indexed the repo" and
353
+ // "indexed most of the repo, quietly". Only the completeness
354
+ // reconciliation warning; per-file extractor warnings stay in the
355
+ // error-code summary below.
356
+ for (const w of result.errors.filter((e) => e.code === 'index_partial')) {
357
+ clack.log.warn(w.message);
358
+ }
359
+ }
360
+ else if (hasErrors) {
361
+ clack.log.error(`Indexing failed ${(0, glyphs_1.getGlyphs)().dash} all ${formatNumber(result.filesErrored)} files had errors`);
362
+ }
363
+ else {
364
+ clack.log.warn('No files found to index');
365
+ }
366
+ if (hasErrors) {
367
+ const errorsByCode = new Map();
368
+ for (const err of result.errors) {
369
+ if (err.severity === 'error') {
370
+ const code = err.code || 'unknown';
371
+ errorsByCode.set(code, (errorsByCode.get(code) || 0) + 1);
372
+ }
373
+ }
374
+ const codeLabels = {
375
+ parse_error: 'files failed to parse',
376
+ read_error: 'files could not be read',
377
+ size_exceeded: 'files exceeded size limit',
378
+ path_traversal: 'blocked paths',
379
+ unsupported_language: 'unsupported language',
380
+ parser_error: 'parser initialization failures',
381
+ };
382
+ const breakdown = Array.from(errorsByCode)
383
+ .map(([code, count]) => `${formatNumber(count)} ${codeLabels[code] || code}`)
384
+ .join('\n');
385
+ clack.note(breakdown, 'Error breakdown');
386
+ if (projectPath) {
387
+ writeErrorLog(projectPath, result.errors);
388
+ clack.log.info('See .codegraph/errors.log for details');
389
+ }
390
+ if (result.filesIndexed > 0) {
391
+ clack.log.info(`The index is fully usable ${(0, glyphs_1.getGlyphs)().dash} only the failed files are missing.`);
392
+ }
393
+ }
394
+ else if (projectPath) {
395
+ const logPath = path.join((0, directory_1.getCodeGraphDir)(projectPath), 'errors.log');
396
+ if (fs.existsSync(logPath)) {
397
+ fs.unlinkSync(logPath);
398
+ }
399
+ }
400
+ }
401
+ /**
402
+ * When an `init`/`index` produced an EMPTY graph and the reason is that the
403
+ * project's own `.gitignore` excludes nested git repositories — the "super-repo
404
+ * gitignores its child repos" layout (#1156), where `init` at the parent
405
+ * correctly indexes ~nothing while `init` inside each child works — name those
406
+ * repos and offer to index them. An interactive terminal gets a yes/no prompt
407
+ * that writes `includeIgnored` to codegraph.json and re-indexes; a
408
+ * non-interactive run just prints the one-line opt-in snippet. The caller gates
409
+ * this on `nodesCreated === 0`, so a project that DID index real content is
410
+ * never nagged about the gitignored reference clones it deliberately keeps out
411
+ * (#970, #1065). Best-effort throughout: detection never breaks the command.
412
+ */
413
+ async function offerIndexIgnoredRepos(clack, projectPath, reindex, opts) {
414
+ let repos;
415
+ try {
416
+ const { findUnindexedIgnoredRepos } = await Promise.resolve().then(() => __importStar(require('../extraction')));
417
+ repos = findUnindexedIgnoredRepos(projectPath);
418
+ }
419
+ catch {
420
+ return; // detection is advisory — never let it break the command
421
+ }
422
+ if (repos.length === 0)
423
+ return;
424
+ const { PROJECT_CONFIG_FILENAME } = await Promise.resolve().then(() => __importStar(require('../project-config')));
425
+ const isOne = repos.length === 1;
426
+ const SHOWN = 6;
427
+ const names = repos.slice(0, SHOWN).map((r) => r.replace(/\/$/, ''));
428
+ const extra = repos.length > SHOWN ? ` (+${formatNumber(repos.length - SHOWN)} more)` : '';
429
+ const snippet = `{ "includeIgnored": [${repos.map((p) => JSON.stringify(p)).join(', ')}] }`;
430
+ clack.log.warn(`Your .gitignore excludes ${isOne ? 'a nested git repository' : `${formatNumber(repos.length)} nested git repositories`} here, ` +
431
+ `so ${isOne ? 'it was' : 'they were'} not indexed: ${names.join(', ')}${extra}.`);
432
+ const manualHint = () => {
433
+ clack.log.info(`If ${isOne ? "it's" : "they're"} your code, add ${isOne ? 'it' : 'them'} to ${PROJECT_CONFIG_FILENAME} and re-index:`);
434
+ clack.log.info(` ${snippet}`);
435
+ };
436
+ if (!opts.interactive || !process.stdin.isTTY) {
437
+ manualHint();
438
+ return;
439
+ }
440
+ const yes = await clack.confirm({
441
+ message: `Index ${isOne ? 'it' : `these ${formatNumber(repos.length)}`} now? Adds ${isOne ? 'it' : 'them'} to ${PROJECT_CONFIG_FILENAME}.`,
442
+ initialValue: true,
443
+ });
444
+ if (clack.isCancel(yes) || !yes) {
445
+ manualHint();
446
+ return;
447
+ }
448
+ let added;
449
+ try {
450
+ const { addIncludeIgnoredPatterns } = await Promise.resolve().then(() => __importStar(require('../project-config')));
451
+ added = addIncludeIgnoredPatterns(projectPath, repos);
452
+ }
453
+ catch (err) {
454
+ clack.log.error(`Could not update ${PROJECT_CONFIG_FILENAME}: ${err instanceof Error ? err.message : String(err)}`);
455
+ manualHint();
456
+ return;
457
+ }
458
+ clack.log.success(`Added ${formatNumber(added)} ${added === 1 ? 'entry' : 'entries'} to ${PROJECT_CONFIG_FILENAME} ${(0, glyphs_1.getGlyphs)().dash} re-indexing…`);
459
+ const result = await reindex();
460
+ printIndexResult(clack, result, projectPath);
461
+ return result;
462
+ }
463
+ /**
464
+ * Write detailed error log to .codegraph/errors.log
465
+ */
466
+ function writeErrorLog(projectPath, errors) {
467
+ const cgDir = (0, directory_1.getCodeGraphDir)(projectPath);
468
+ if (!fs.existsSync(cgDir))
469
+ return;
470
+ const logPath = path.join(cgDir, 'errors.log');
471
+ // Group errors by file path
472
+ const errorsByFile = new Map();
473
+ const noFileErrors = [];
474
+ for (const err of errors) {
475
+ if (err.severity !== 'error')
476
+ continue;
477
+ if (err.filePath) {
478
+ let list = errorsByFile.get(err.filePath);
479
+ if (!list) {
480
+ list = [];
481
+ errorsByFile.set(err.filePath, list);
482
+ }
483
+ list.push({ message: err.message, code: err.code });
484
+ }
485
+ else {
486
+ noFileErrors.push({ message: err.message, code: err.code });
487
+ }
488
+ }
489
+ const lines = [
490
+ `CodeGraph Error Log - ${new Date().toISOString()}`,
491
+ `${errorsByFile.size} files with errors`,
492
+ '',
493
+ ];
494
+ for (const [filePath, fileErrors] of errorsByFile) {
495
+ for (const err of fileErrors) {
496
+ lines.push(`${filePath}: ${err.message}`);
497
+ }
498
+ }
499
+ for (const err of noFileErrors) {
500
+ lines.push(err.message);
501
+ }
502
+ fs.writeFileSync(logPath, lines.join('\n') + '\n');
503
+ }
504
+ /**
505
+ * Telemetry for a completed full index (see TELEMETRY.md). The bounded flush
506
+ * keeps init/index responsive (these commands just ran for seconds anyway)
507
+ * while delivering the event promptly.
508
+ */
509
+ async function recordIndexTelemetry(cg, result) {
510
+ (0, telemetry_1.recordIndexEvent)(cg, result);
511
+ await (0, telemetry_1.getTelemetry)().flushNow();
512
+ }
513
+ // =============================================================================
514
+ // Commands
515
+ // =============================================================================
516
+ /**
517
+ * codegraph init [path]
518
+ */
519
+ program
520
+ .command('init [path]')
521
+ .description('Initialize CodeGraph in a project directory and build the initial index')
522
+ .option('-i, --index', 'Deprecated: indexing now runs by default; flag accepted for backward compatibility')
523
+ .option('-f, --force', 'Initialize even if the path looks like your home directory or a filesystem root')
524
+ .option('-v, --verbose', 'Show detailed worker lifecycle and memory info')
525
+ .action(async (pathArg, options) => {
526
+ const projectPath = path.resolve(pathArg || process.cwd());
527
+ const clack = await importESM('@clack/prompts');
528
+ clack.intro('Initializing CodeGraph');
529
+ try {
530
+ // Refuse to index your home directory / a filesystem root — it pulls in
531
+ // caches, other projects, and your whole tree (a multi-GB index + watcher
532
+ // churn, and on pre-1.0 macOS a machine-crashing fd blowup, #845).
533
+ const unsafe = (0, directory_1.unsafeIndexRootReason)(projectPath);
534
+ if (unsafe && !options.force) {
535
+ clack.log.error(`Refusing to initialize in ${projectPath} — it looks like ${unsafe}.`);
536
+ clack.log.info('Run this inside a specific project directory, or pass --force if you really mean to index everything under it.');
537
+ clack.outro('');
538
+ process.exitCode = 1;
539
+ return;
540
+ }
541
+ if ((0, directory_1.isInitialized)(projectPath)) {
542
+ clack.log.warn(`Already initialized in ${projectPath}`);
543
+ clack.log.info('Use "codegraph index" to re-index or "codegraph sync" to update');
544
+ try {
545
+ const { offerWatchFallback } = await Promise.resolve().then(() => __importStar(require('../installer')));
546
+ await offerWatchFallback(clack, projectPath);
547
+ }
548
+ catch { /* non-fatal */ }
549
+ clack.outro('');
550
+ return;
551
+ }
552
+ const { default: CodeGraph, getDatabasePath } = await loadCodeGraph();
553
+ const cg = await CodeGraph.init(projectPath, { index: false });
554
+ clack.log.success(`Initialized in ${projectPath}`);
555
+ // Indexing runs by default now. The legacy -i/--index flag is still
556
+ // accepted (so existing muscle memory and scripts don't break) but is a
557
+ // no-op — initializing always builds the initial index.
558
+ // Supervise the index: self-terminate if orphaned or wedged (#999).
559
+ // The DB + WAL paths let the liveness watchdog tell a slow store on
560
+ // degraded storage from a true wedge (#1231).
561
+ // A closure so we can re-run the exact same supervised, progress-rendered
562
+ // index if the user opts gitignored child repos in below (#1156).
563
+ const dbPath = getDatabasePath(projectPath);
564
+ const runIndex = async () => {
565
+ const supervision = (0, command_supervision_1.installCommandSupervision)('init', { progressPaths: [dbPath, `${dbPath}-wal`] });
566
+ try {
567
+ if (options.verbose) {
568
+ return await cg.indexAll({ onProgress: createVerboseProgress(), verbose: true });
569
+ }
570
+ process.stdout.write(`${colors.dim}${(0, glyphs_1.getGlyphs)().rail}${colors.reset}\n`);
571
+ const progress = (0, shimmer_progress_1.createShimmerProgress)();
572
+ const r = await cg.indexAll({ onProgress: progress.onProgress });
573
+ await progress.stop();
574
+ return r;
575
+ }
576
+ finally {
577
+ supervision.stop();
578
+ }
579
+ };
580
+ const result = await runIndex();
581
+ printIndexResult(clack, result, projectPath);
582
+ await recordIndexTelemetry(cg, result);
583
+ // An empty graph at a git super-repo usually means `.gitignore` excludes
584
+ // the child repos that hold the code — surface them and offer to opt in
585
+ // rather than leaving the user with a silent 0-node "Done". (#1156)
586
+ if (result.nodesCreated === 0) {
587
+ await offerIndexIgnoredRepos(clack, projectPath, runIndex, { interactive: true });
588
+ }
589
+ try {
590
+ const { offerWatchFallback } = await Promise.resolve().then(() => __importStar(require('../installer')));
591
+ await offerWatchFallback(clack, projectPath);
592
+ }
593
+ catch { /* non-fatal */ }
594
+ clack.outro('Done');
595
+ cg.destroy();
596
+ }
597
+ catch (err) {
598
+ clack.log.error(`Failed: ${err instanceof Error ? err.message : String(err)}`);
599
+ process.exit(1);
600
+ }
601
+ });
602
+ /**
603
+ * codegraph uninit [path]
604
+ */
605
+ program
606
+ .command('uninit [path]')
607
+ .description('Remove CodeGraph from a project (deletes .codegraph/ directory)')
608
+ .option('-f, --force', 'Skip confirmation prompt')
609
+ .action(async (pathArg, options) => {
610
+ const projectPath = resolveProjectPath(pathArg);
611
+ try {
612
+ if (!(0, directory_1.isInitialized)(projectPath)) {
613
+ warn(`CodeGraph is not initialized in ${projectPath}`);
614
+ return;
615
+ }
616
+ if (!options.force) {
617
+ // Confirm with user
618
+ const readline = await Promise.resolve().then(() => __importStar(require('readline')));
619
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
620
+ const answer = await new Promise((resolve) => {
621
+ rl.question(chalk.yellow(`${(0, glyphs_1.getGlyphs)().warn} This will permanently delete all CodeGraph data. Continue? (y/N) `), resolve);
622
+ });
623
+ rl.close();
624
+ if (answer.toLowerCase() !== 'y') {
625
+ info('Cancelled');
626
+ return;
627
+ }
628
+ }
629
+ const { default: CodeGraph } = await loadCodeGraph();
630
+ const cg = CodeGraph.openSync(projectPath);
631
+ cg.uninitialize();
632
+ // Clean up any git sync hooks we installed (no-op if none / not a repo).
633
+ try {
634
+ const { removeGitSyncHook } = await Promise.resolve().then(() => __importStar(require('../sync/git-hooks')));
635
+ const removed = removeGitSyncHook(projectPath);
636
+ if (removed.installed.length > 0) {
637
+ info(`Removed git ${removed.installed.join(', ')} sync hook${removed.installed.length > 1 ? 's' : ''}`);
638
+ }
639
+ }
640
+ catch { /* non-fatal */ }
641
+ success(`Removed CodeGraph from ${projectPath}`);
642
+ // Churn signal — and flush now, since after an uninit there may be no
643
+ // "next run" to deliver it.
644
+ try {
645
+ (0, telemetry_1.getTelemetry)().recordLifecycle('uninstall', {});
646
+ await (0, telemetry_1.getTelemetry)().flushNow();
647
+ }
648
+ catch { /* non-fatal */ }
649
+ }
650
+ catch (err) {
651
+ error(`Failed to uninitialize: ${err instanceof Error ? err.message : String(err)}`);
652
+ process.exit(1);
653
+ }
654
+ });
655
+ /**
656
+ * codegraph index [path]
657
+ */
658
+ program
659
+ .command('index [path]')
660
+ .description('Rebuild the full index from scratch (same result as a fresh init)')
661
+ .option('-f, --force', 'Index even if the path looks like your home directory or a filesystem root')
662
+ .option('-q, --quiet', 'Suppress progress output')
663
+ .option('-v, --verbose', 'Show detailed worker lifecycle and memory info')
664
+ .action(async (pathArg, options) => {
665
+ const projectPath = resolveProjectPath(pathArg);
666
+ try {
667
+ // Don't (re)index your home directory / a filesystem root (#845). --force
668
+ // doubles as the override.
669
+ const unsafe = (0, directory_1.unsafeIndexRootReason)(projectPath);
670
+ if (unsafe && !options.force) {
671
+ error(`Refusing to index ${projectPath} — it looks like ${unsafe}. Pass --force to override.`);
672
+ process.exit(1);
673
+ }
674
+ if (!(0, directory_1.isInitialized)(projectPath)) {
675
+ error(`CodeGraph not initialized in ${projectPath}`);
676
+ info('Run "codegraph init" first');
677
+ process.exit(1);
678
+ }
679
+ const { default: CodeGraph, getDatabasePath } = await loadCodeGraph();
680
+ // `index` is a FULL re-index — identical to a fresh `init`. RECREATE the
681
+ // database from scratch (discard .codegraph/codegraph.db + its WAL) rather
682
+ // than opening the old graph and DELETE-ing every row. The clear-then-index
683
+ // approach reported "0 nodes" without the clear (#874); the recreate keeps
684
+ // that fixed AND avoids the failure mode where, on a large or pre-fix
685
+ // poisoned index, the per-row FTS delete churn wedged the main thread long
686
+ // enough to trip the liveness watchdog before scanning even began (#1067).
687
+ // recreate() hands back a fresh, empty instance — no clear() needed. For
688
+ // fast incremental updates use `sync`.
689
+ const cg = await CodeGraph.recreate(projectPath);
690
+ // Supervise the indexer: self-terminate if orphaned (parent shim killed)
691
+ // or if the main thread wedges — neither was guarded on this path (#999).
692
+ // The DB + WAL paths let the liveness watchdog tell a slow store on
693
+ // degraded storage from a true wedge (#1231).
694
+ const dbPath = getDatabasePath(projectPath);
695
+ const supervision = (0, command_supervision_1.installCommandSupervision)('index', { progressPaths: [dbPath, `${dbPath}-wal`] });
696
+ try {
697
+ if (options.quiet) {
698
+ // Quiet mode: no UI, just run against the freshly-recreated graph.
699
+ const result = await cg.indexAll();
700
+ if (!result.success)
701
+ process.exit(1);
702
+ cg.destroy();
703
+ return;
704
+ }
705
+ const clack = await importESM('@clack/prompts');
706
+ clack.intro('Indexing project');
707
+ // A closure so a re-index (after opting gitignored child repos in, #1156)
708
+ // renders identically. Supervision already wraps the whole command.
709
+ const renderIndex = async () => {
710
+ if (options.verbose) {
711
+ return await cg.indexAll({ onProgress: createVerboseProgress(), verbose: true });
712
+ }
713
+ process.stdout.write(`${colors.dim}${(0, glyphs_1.getGlyphs)().rail}${colors.reset}\n`);
714
+ const progress = (0, shimmer_progress_1.createShimmerProgress)();
715
+ const r = await cg.indexAll({ onProgress: progress.onProgress });
716
+ await progress.stop();
717
+ return r;
718
+ };
719
+ const result = await renderIndex();
720
+ printIndexResult(clack, result, projectPath);
721
+ await recordIndexTelemetry(cg, result);
722
+ // Empty graph at a git super-repo → likely `.gitignore`d child repos;
723
+ // name them and offer to opt in instead of a silent 0-node result (#1156).
724
+ let finalResult = result;
725
+ if (result.nodesCreated === 0) {
726
+ finalResult = (await offerIndexIgnoredRepos(clack, projectPath, renderIndex, { interactive: true })) ?? result;
727
+ }
728
+ if (!finalResult.success) {
729
+ process.exit(1);
730
+ }
731
+ clack.outro('Done');
732
+ cg.destroy();
733
+ }
734
+ finally {
735
+ supervision.stop();
736
+ }
737
+ }
738
+ catch (err) {
739
+ error(`Failed to index: ${err instanceof Error ? err.message : String(err)}`);
740
+ process.exit(1);
741
+ }
742
+ });
743
+ /**
744
+ * codegraph sync [path]
745
+ */
746
+ program
747
+ .command('sync [path]')
748
+ .description('Sync changes since last index')
749
+ .option('-q, --quiet', 'Suppress output (for git hooks)')
750
+ .action(async (pathArg, options) => {
751
+ const projectPath = resolveProjectPath(pathArg);
752
+ try {
753
+ if (!(0, directory_1.isInitialized)(projectPath)) {
754
+ if (!options.quiet) {
755
+ error(`CodeGraph not initialized in ${projectPath}`);
756
+ }
757
+ process.exit(1);
758
+ }
759
+ const { default: CodeGraph } = await loadCodeGraph();
760
+ const cg = await CodeGraph.open(projectPath);
761
+ if (options.quiet) {
762
+ await cg.sync();
763
+ cg.destroy();
764
+ return;
765
+ }
766
+ const clack = await importESM('@clack/prompts');
767
+ clack.intro('Syncing CodeGraph');
768
+ process.stdout.write(`${colors.dim}${(0, glyphs_1.getGlyphs)().rail}${colors.reset}\n`);
769
+ const progress = (0, shimmer_progress_1.createShimmerProgress)();
770
+ const result = await cg.sync({
771
+ onProgress: progress.onProgress,
772
+ });
773
+ await progress.stop();
774
+ const totalChanges = result.filesAdded + result.filesModified + result.filesRemoved;
775
+ if (totalChanges === 0) {
776
+ clack.log.info('Already up to date');
777
+ }
778
+ else {
779
+ clack.log.success(`Synced ${formatNumber(totalChanges)} changed files`);
780
+ const details = [];
781
+ if (result.filesAdded > 0)
782
+ details.push(`Added: ${result.filesAdded}`);
783
+ if (result.filesModified > 0)
784
+ details.push(`Modified: ${result.filesModified}`);
785
+ if (result.filesRemoved > 0)
786
+ details.push(`Removed: ${result.filesRemoved}`);
787
+ clack.log.info(`${details.join(', ')} ${(0, glyphs_1.getGlyphs)().dash} ${formatNumber(result.nodesUpdated)} nodes in ${formatDuration(result.durationMs)}`);
788
+ }
789
+ clack.outro('Done');
790
+ cg.destroy();
791
+ }
792
+ catch (err) {
793
+ if (!options.quiet) {
794
+ error(`Failed to sync: ${err instanceof Error ? err.message : String(err)}`);
795
+ }
796
+ process.exit(1);
797
+ }
798
+ });
799
+ /**
800
+ * codegraph status [path]
801
+ */
802
+ program
803
+ .command('status [path]')
804
+ .description('Show index status and statistics')
805
+ .option('-j, --json', 'Output as JSON')
806
+ .action(async (pathArg, options) => {
807
+ const projectPath = resolveProjectPath(pathArg);
808
+ // The directory the user actually ran from, before walking up to the index
809
+ // root. Used to detect when the resolved index lives in a different git
810
+ // working tree (e.g. a nested worktree borrowing the main checkout's index).
811
+ const startPath = path.resolve(pathArg || process.cwd());
812
+ const worktreeMismatch = (0, worktree_1.detectWorktreeIndexMismatch)(startPath, projectPath);
813
+ try {
814
+ if (!(0, directory_1.isInitialized)(projectPath)) {
815
+ if (options.json) {
816
+ console.log(JSON.stringify({
817
+ initialized: false,
818
+ version: packageJson.version,
819
+ projectPath,
820
+ indexPath: (0, directory_1.getCodeGraphDir)(projectPath),
821
+ lastIndexed: null,
822
+ }));
823
+ return;
824
+ }
825
+ console.log(chalk.bold('\nCodeGraph Status\n'));
826
+ info(`Project: ${projectPath}`);
827
+ warn('Not initialized');
828
+ info('Run "codegraph init" to initialize');
829
+ return;
830
+ }
831
+ const { default: CodeGraph } = await loadCodeGraph();
832
+ const cg = await CodeGraph.open(projectPath);
833
+ const stats = cg.getStats();
834
+ const changes = cg.getChangedFiles();
835
+ const backend = cg.getBackend();
836
+ const journalMode = cg.getJournalMode();
837
+ const buildInfo = cg.getIndexBuildInfo();
838
+ const reindexRecommended = cg.isIndexStale();
839
+ const indexState = cg.getIndexState();
840
+ // Zero on a healthy index; non-zero at rest means a resolution pass was
841
+ // interrupted, so some files' call edges are missing (#1187).
842
+ const pendingRefs = cg.getPendingReferenceCount();
843
+ // JSON output mode
844
+ if (options.json) {
845
+ const lastIndexedMs = cg.getLastIndexedAt();
846
+ console.log(JSON.stringify({
847
+ initialized: true,
848
+ version: packageJson.version,
849
+ projectPath,
850
+ indexPath: (0, directory_1.getCodeGraphDir)(projectPath),
851
+ lastIndexed: lastIndexedMs != null ? new Date(lastIndexedMs).toISOString() : null,
852
+ fileCount: stats.fileCount,
853
+ nodeCount: stats.nodeCount,
854
+ edgeCount: stats.edgeCount,
855
+ dbSizeBytes: stats.dbSizeBytes,
856
+ backend,
857
+ journalMode,
858
+ nodesByKind: stats.nodesByKind,
859
+ languages: Object.entries(stats.filesByLanguage).filter(([, count]) => count > 0).map(([lang]) => lang),
860
+ pendingChanges: {
861
+ added: changes.added.length,
862
+ modified: changes.modified.length,
863
+ removed: changes.removed.length,
864
+ },
865
+ worktreeMismatch: worktreeMismatch
866
+ ? { worktreeRoot: worktreeMismatch.worktreeRoot, indexRoot: worktreeMismatch.indexRoot }
867
+ : null,
868
+ index: {
869
+ builtWithVersion: buildInfo.version,
870
+ builtWithExtractionVersion: buildInfo.extractionVersion,
871
+ currentExtractionVersion: extraction_version_1.EXTRACTION_VERSION,
872
+ reindexRecommended,
873
+ // 'complete' | 'partial' (files silently dropped) | 'indexing'
874
+ // (a run was killed mid-index — the index is truncated) |
875
+ // 'failed' | null (predates the marker).
876
+ state: indexState,
877
+ // References awaiting resolution. Non-zero at rest means an
878
+ // interrupted resolution pass left edges missing; the next
879
+ // sync sweeps them (#1187).
880
+ pendingRefs,
881
+ },
882
+ }));
883
+ cg.destroy();
884
+ return;
885
+ }
886
+ console.log(chalk.bold('\nCodeGraph Status\n'));
887
+ // Project info
888
+ console.log(chalk.cyan('Project:'), projectPath);
889
+ if (worktreeMismatch) {
890
+ warn((0, worktree_1.worktreeMismatchWarning)(worktreeMismatch));
891
+ }
892
+ if (indexState === 'indexing') {
893
+ warn('The last index run never finished (killed mid-index?) — the index is truncated. Re-run "codegraph index".');
894
+ }
895
+ else if (indexState === 'partial') {
896
+ warn('The last index run silently dropped files — the index is partial. Re-run "codegraph index".');
897
+ }
898
+ else if (indexState === 'failed') {
899
+ warn('The last index run failed — results may be incomplete. Re-run "codegraph index".');
900
+ }
901
+ if (pendingRefs > 0) {
902
+ warn(`${formatNumber(pendingRefs)} references from an interrupted run are awaiting resolution — some callers/impact edges are missing. Run "codegraph sync" to resolve them.`);
903
+ }
904
+ console.log();
905
+ // Index stats
906
+ console.log(chalk.bold('Index Statistics:'));
907
+ console.log(` Files: ${formatNumber(stats.fileCount)}`);
908
+ console.log(` Nodes: ${formatNumber(stats.nodeCount)}`);
909
+ console.log(` Edges: ${formatNumber(stats.edgeCount)}`);
910
+ console.log(` DB Size: ${(stats.dbSizeBytes / 1024 / 1024).toFixed(2)} MB`);
911
+ // Surface the active SQLite backend (bun:sqlite under Bun, node:sqlite
912
+ // under Node — both real SQLite, full WAL + FTS5, no native build).
913
+ const backendName = backend === 'bun-sqlite' ? 'bun:sqlite' : 'node:sqlite';
914
+ const backendLabel = chalk.green(`${backendName} ${(0, glyphs_1.getGlyphs)().dash} built-in (full WAL)`);
915
+ console.log(` Backend: ${backendLabel}`);
916
+ // Effective journal mode: 'wal' means concurrent reads never block on a
917
+ // writer; anything else means they can ("database is locked"). node:sqlite
918
+ // supports WAL everywhere, so a non-wal mode means the filesystem can't
919
+ // (network mounts, WSL2 /mnt). See issue #238.
920
+ const journalLabel = journalMode === 'wal'
921
+ ? chalk.green('wal')
922
+ : chalk.yellow(`${journalMode || 'unknown'} ${(0, glyphs_1.getGlyphs)().dash} WAL inactive; reads can block on writes`);
923
+ console.log(` Journal: ${journalLabel}`);
924
+ console.log();
925
+ // Node breakdown
926
+ console.log(chalk.bold('Nodes by Kind:'));
927
+ const nodesByKind = Object.entries(stats.nodesByKind)
928
+ .filter(([, count]) => count > 0)
929
+ .sort((a, b) => b[1] - a[1]);
930
+ for (const [kind, count] of nodesByKind) {
931
+ console.log(` ${kind.padEnd(15)} ${formatNumber(count)}`);
932
+ }
933
+ console.log();
934
+ // Language breakdown
935
+ console.log(chalk.bold('Files by Language:'));
936
+ const filesByLang = Object.entries(stats.filesByLanguage)
937
+ .filter(([, count]) => count > 0)
938
+ .sort((a, b) => b[1] - a[1]);
939
+ for (const [lang, count] of filesByLang) {
940
+ console.log(` ${lang.padEnd(15)} ${formatNumber(count)}`);
941
+ }
942
+ console.log();
943
+ // Pending changes
944
+ const totalChanges = changes.added.length + changes.modified.length + changes.removed.length;
945
+ if (totalChanges > 0) {
946
+ console.log(chalk.bold('Pending Changes:'));
947
+ if (changes.added.length > 0) {
948
+ console.log(` Added: ${changes.added.length} files`);
949
+ }
950
+ if (changes.modified.length > 0) {
951
+ console.log(` Modified: ${changes.modified.length} files`);
952
+ }
953
+ if (changes.removed.length > 0) {
954
+ console.log(` Removed: ${changes.removed.length} files`);
955
+ }
956
+ info('Run "codegraph sync" to update the index');
957
+ }
958
+ else {
959
+ success('Index is up to date');
960
+ }
961
+ console.log();
962
+ // Re-index hint: the index was built by an older engine than the one now
963
+ // running, so a rebuild would add data a migration can't backfill.
964
+ if (reindexRecommended) {
965
+ const builtWith = buildInfo.version ? `v${buildInfo.version.replace(/^v/, '')}` : 'an earlier version';
966
+ warn(`Index was built by ${builtWith}; re-index to pick up this engine's improvements.`);
967
+ info('Run "codegraph index" (full rebuild) or "codegraph sync"');
968
+ console.log();
969
+ }
970
+ cg.destroy();
971
+ }
972
+ catch (err) {
973
+ error(`Failed to get status: ${err instanceof Error ? err.message : String(err)}`);
974
+ process.exit(1);
975
+ }
976
+ });
977
+ /**
978
+ * codegraph query <search>
979
+ */
980
+ program
981
+ .command('query <search>')
982
+ .description('Search for symbols in the codebase')
983
+ .option('-p, --path <path>', 'Project path')
984
+ .option('-l, --limit <number>', 'Maximum results', '10')
985
+ .option('-k, --kind <kind>', 'Filter by node kind (function, class, etc.)')
986
+ .option('-j, --json', 'Output as JSON')
987
+ .action(async (search, options) => {
988
+ const projectPath = resolveProjectPath(options.path);
989
+ try {
990
+ if (!(0, directory_1.isInitialized)(projectPath)) {
991
+ error(`CodeGraph not initialized in ${projectPath}`);
992
+ process.exit(1);
993
+ }
994
+ const { default: CodeGraph } = await loadCodeGraph();
995
+ const cg = await CodeGraph.open(projectPath);
996
+ const limit = parseInt(options.limit || '10', 10);
997
+ const rawResults = cg.searchNodes(search, {
998
+ limit,
999
+ kinds: options.kind ? [options.kind] : undefined,
1000
+ });
1001
+ // Mirror the MCP search down-rank so the CLI also surfaces the
1002
+ // hand-written implementation before protobuf/gRPC scaffolding
1003
+ // when both share a name. See extraction/generated-detection.ts.
1004
+ const { isGeneratedFile } = await Promise.resolve().then(() => __importStar(require('../extraction/generated-detection')));
1005
+ const results = [...rawResults].sort((a, b) => {
1006
+ const aGen = isGeneratedFile(a.node.filePath) ? 1 : 0;
1007
+ const bGen = isGeneratedFile(b.node.filePath) ? 1 : 0;
1008
+ return aGen - bGen;
1009
+ });
1010
+ if (options.json) {
1011
+ console.log(JSON.stringify(results, null, 2));
1012
+ }
1013
+ else {
1014
+ if (results.length === 0) {
1015
+ info(`No results found for "${search}"`);
1016
+ }
1017
+ else {
1018
+ console.log(chalk.bold(`\nSearch Results for "${search}":\n`));
1019
+ // Results arrive already ranked by relevance, so the order conveys
1020
+ // it. We don't print the raw score: it's an unbounded BM25/FTS value
1021
+ // (relative-ranking only), and the old `(score * 100)%` rendered it
1022
+ // as nonsensical percentages like "12042%" (#1045). The MCP search
1023
+ // tool likewise shows no score. Raw `score` stays in --json output.
1024
+ for (const result of results) {
1025
+ const node = result.node;
1026
+ const location = `${node.filePath}:${node.startLine}`;
1027
+ console.log(chalk.cyan(node.kind.padEnd(12)) +
1028
+ chalk.white(node.name));
1029
+ console.log(chalk.dim(` ${location}`));
1030
+ if (node.signature) {
1031
+ console.log(chalk.dim(` ${node.signature}`));
1032
+ }
1033
+ console.log();
1034
+ }
1035
+ }
1036
+ }
1037
+ cg.destroy();
1038
+ }
1039
+ catch (err) {
1040
+ error(`Search failed: ${err instanceof Error ? err.message : String(err)}`);
1041
+ process.exit(1);
1042
+ }
1043
+ });
1044
+ /**
1045
+ * codegraph explore <query...>
1046
+ *
1047
+ * The CLI face of the MCP codegraph_explore tool — same handler, same
1048
+ * output (source of the relevant symbols grouped by file + the call path
1049
+ * among them). Exists so agents WITHOUT the MCP tools — Task-tool
1050
+ * subagents (which don't inherit MCP tools, #704) and non-MCP harnesses —
1051
+ * can reach the graph through a plain shell command.
1052
+ */
1053
+ program
1054
+ .command('explore <query...>')
1055
+ .description('Explore an area: relevant symbols\' source + call paths in one shot (same output as the codegraph_explore MCP tool)')
1056
+ .option('-p, --path <path>', 'Project path')
1057
+ .option('--max-files <number>', 'Maximum number of files to include source from')
1058
+ .action(async (queryParts, options) => {
1059
+ const projectPath = resolveProjectPath(options.path);
1060
+ try {
1061
+ if (!(0, directory_1.isInitialized)(projectPath)) {
1062
+ error(`CodeGraph isn't available here — no .codegraph/ index exists in ${projectPath}. If you are an AI agent: continue with your usual tools; indexing is the user's decision, do not run it yourself. (The project owner can enable CodeGraph with 'codegraph init'.)`);
1063
+ process.exit(1);
1064
+ }
1065
+ const { default: CodeGraph } = await loadCodeGraph();
1066
+ const cg = await CodeGraph.open(projectPath);
1067
+ const { ToolHandler } = await Promise.resolve().then(() => __importStar(require('../mcp/tools')));
1068
+ const handler = new ToolHandler(cg);
1069
+ const args = { query: queryParts.join(' ') };
1070
+ if (options.maxFiles)
1071
+ args.maxFiles = parseInt(options.maxFiles, 10);
1072
+ const result = await handler.execute('codegraph_explore', args);
1073
+ console.log(result.content[0]?.text ?? '');
1074
+ cg.destroy();
1075
+ if (result.isError)
1076
+ process.exit(1);
1077
+ }
1078
+ catch (err) {
1079
+ error(`Explore failed: ${err instanceof Error ? err.message : String(err)}`);
1080
+ process.exit(1);
1081
+ }
1082
+ });
1083
+ /**
1084
+ * codegraph prompt-hook (hidden)
1085
+ *
1086
+ * A Claude Code `UserPromptSubmit` hook entry point. Reads `{prompt, cwd}` JSON
1087
+ * on stdin; for a structural/flow/impact prompt it runs `codegraph_explore` on
1088
+ * the indexed project and prints the result to stdout, which Claude injects into
1089
+ * the agent's context — so the agent's reflex grep/read has nothing left to find
1090
+ * and reliably uses CodeGraph (the adoption problem). Installed by the installer
1091
+ * into Claude's settings.json (opt-in, default-yes).
1092
+ *
1093
+ * LOAD-BEARING: this must NEVER break the user's prompt. Every failure path —
1094
+ * kill-switch, non-structural prompt, no index, engine error — exits 0 with no
1095
+ * output. The only effect is additive context when it can confidently provide it.
1096
+ */
1097
+ program
1098
+ .command('prompt-hook', { hidden: true })
1099
+ .description('Claude UserPromptSubmit hook: inject CodeGraph context for structural prompts (reads {prompt,cwd} JSON on stdin)')
1100
+ .action(async () => {
1101
+ try {
1102
+ // Kill-switch: lets a user disable the nudge without uninstalling /
1103
+ // editing settings.json (CI, low-power machines, personal preference).
1104
+ if (process.env.CODEGRAPH_NO_PROMPT_HOOK === '1' || process.env.CODEGRAPH_PROMPT_HOOK === '0')
1105
+ return;
1106
+ if (process.stdin.isTTY)
1107
+ return; // invoked by hand, no piped payload
1108
+ const raw = await new Promise((resolve) => {
1109
+ let data = '';
1110
+ process.stdin.setEncoding('utf8');
1111
+ process.stdin.on('data', (c) => { data += c; });
1112
+ process.stdin.on('end', () => resolve(data));
1113
+ process.stdin.on('error', () => resolve(data));
1114
+ });
1115
+ let input = {};
1116
+ try {
1117
+ input = JSON.parse(raw);
1118
+ }
1119
+ catch {
1120
+ return;
1121
+ }
1122
+ const prompt = String(input.prompt || '');
1123
+ // Gate telemetry: how often each tier fires vs. no-ops — counter names
1124
+ // only, NEVER prompt content (see TELEMETRY.md). This is the data that
1125
+ // turns "is the gate any good" from vibes into a measured recall rate.
1126
+ const gate = (outcome) => {
1127
+ try {
1128
+ (0, telemetry_1.getTelemetry)().recordUsage('cli_command', `prompt-hook-gate-${outcome}`, true);
1129
+ }
1130
+ catch { /* never break the hook */ }
1131
+ };
1132
+ // Gate, tiered by confidence (#994, #1126):
1133
+ // HIGH — a structural keyword (any covered language), or a code-shaped
1134
+ // token verified in the index → full explore injection.
1135
+ // MEDIUM — no keyword/token, but prose words match indexed symbol-name
1136
+ // SEGMENTS ("state machine" → OrderStateMachine, in any
1137
+ // language): inject a short list of the matching symbols and
1138
+ // let the AGENT write the explore query — the graph-derived
1139
+ // tier, no vocabulary involved.
1140
+ // silent — nothing verified. Every other prompt ("fix this typo")
1141
+ // stays a zero-cost no-op.
1142
+ // Keywords fire on their own; a token or prose word is only a CANDIDATE
1143
+ // verified against the graph below, so a tech brand ("JavaScript") that
1144
+ // merely looks like code doesn't inject spurious context.
1145
+ const keyworded = (0, directory_1.hasStructuralKeyword)(prompt);
1146
+ const codeTokens = keyworded ? [] : (0, directory_1.extractCodeTokens)(prompt);
1147
+ const proseWords = keyworded ? [] : (0, identifier_segments_1.extractProseCandidates)(prompt);
1148
+ if (!keyworded && codeTokens.length === 0 && proseWords.length === 0) {
1149
+ gate('noop-shape');
1150
+ return;
1151
+ }
1152
+ // Decide what to inject, shaped by WHERE the index(es) are: the nearest
1153
+ // indexed ancestor of cwd, or — when cwd is an un-indexed workspace root
1154
+ // whose indexed project(s) live in sub-dirs (the monorepo case, #964) —
1155
+ // the sub-project the prompt points at, plus a `projectPath` nudge for any
1156
+ // others. Without the down-scan the hook injected nothing at a monorepo
1157
+ // root (it only walked up), so the validated adoption lever never fired
1158
+ // exactly where the agent most needs it.
1159
+ const plan = (0, directory_1.planFrontload)(String(input.cwd || process.cwd()), prompt);
1160
+ if (!plan.exploreRoot && plan.nudgeProjects.length === 0) {
1161
+ gate('noop-no-index');
1162
+ return;
1163
+ } // nothing reachable — the agent's normal tools apply
1164
+ // A "pass projectPath" line for indexed sub-projects we did NOT front-load.
1165
+ // Follow-up codegraph_explore calls against a sub-project (cwd isn't its
1166
+ // index root) need an explicit projectPath, so spell it out.
1167
+ const nudge = (projects, lead) => `${lead}\n${projects.map((p) => ` - projectPath: "${p}"`).join('\n')}\n`;
1168
+ if (plan.exploreRoot) {
1169
+ const { default: CodeGraph } = await loadCodeGraph();
1170
+ const cg = await CodeGraph.open(plan.exploreRoot);
1171
+ try {
1172
+ const others = plan.nudgeProjects.length
1173
+ ? `\n${nudge(plan.nudgeProjects, 'Other indexed projects in this workspace — pass projectPath to query them:')}`
1174
+ : '';
1175
+ // Tier decision against THIS index (issue #994 follow-up: candidates
1176
+ // must be real here — a brand name or prose about another domain
1177
+ // must not inject). Keyword-bearing prompts skip verification — the
1178
+ // keyword is signal enough.
1179
+ const tokenVerified = !keyworded && codeTokens.some((t) => cg.getNodesByName(t).length > 0);
1180
+ if (keyworded || tokenVerified) {
1181
+ const { ToolHandler } = await Promise.resolve().then(() => __importStar(require('../mcp/tools')));
1182
+ const handler = new ToolHandler(cg);
1183
+ const result = await handler.execute('codegraph_explore', { query: prompt });
1184
+ const text = result.content[0]?.text ?? '';
1185
+ if (!result.isError && text.trim()) {
1186
+ // Cap the injection so a large-repo explore can't flood the prompt.
1187
+ const MAX = 16000;
1188
+ const body = text.length > MAX ? `${text.slice(0, MAX)}\n…(truncated; call codegraph_explore for the rest)` : text;
1189
+ // For a front-loaded SUB-project, a follow-up explore needs its path.
1190
+ const more = plan.viaSubScan
1191
+ ? `call codegraph_explore with projectPath: "${plan.exploreRoot}" for more`
1192
+ : 'call codegraph_explore for more';
1193
+ process.stdout.write(`<codegraph_context note="Structural context from CodeGraph for this prompt — treat returned source as already read; ${more}.">\n${body}${others}\n</codegraph_context>\n`);
1194
+ gate(keyworded ? 'high-keyword' : 'high-token');
1195
+ }
1196
+ else {
1197
+ // A high-* outcome must mean context was actually delivered —
1198
+ // the funnel's noop-vs-high split is how gate recall is
1199
+ // measured (#1143). An explore error or empty result is a
1200
+ // delivery failure, not a gate success.
1201
+ gate(keyworded ? 'noop-explore-keyword' : 'noop-explore-token');
1202
+ }
1203
+ return;
1204
+ }
1205
+ // MEDIUM: prose words → symbol-name segments, co-occurrence/rarity
1206
+ // scored, each hit re-verified to exist (see getSegmentMatches). The
1207
+ // payload names the symbols but does NOT run explore — the agent owns
1208
+ // the query where the hook's confidence is only "these are related".
1209
+ //
1210
+ // A database indexed before the vocab table existed starts with it
1211
+ // EMPTY, and only sync() backfills it — which this hook never runs
1212
+ // (#1142). Heal it here: on a populated vocab this is one SELECT;
1213
+ // the actual backfill is a one-time batched pass whose cost the MCP
1214
+ // server's own catch-up sync usually pays first (it runs at every
1215
+ // session start). A distinct noop outcome keeps a dormant vocab
1216
+ // from polluting the noop-unverified recall signal.
1217
+ const vocabReady = await cg.healSegmentVocabIfEmpty().catch(() => false);
1218
+ if (!vocabReady) {
1219
+ gate('noop-vocab-empty');
1220
+ return;
1221
+ }
1222
+ const related = cg.getSegmentMatches(proseWords);
1223
+ if (related.length === 0) {
1224
+ gate('noop-unverified');
1225
+ return;
1226
+ }
1227
+ const lines = related
1228
+ .map((m) => ` - ${m.name} (${m.kind} — ${m.filePath}:${m.startLine})`)
1229
+ .join('\n');
1230
+ const exampleQuery = related.slice(0, 3).map((m) => m.name).join(' ');
1231
+ const projectHint = plan.viaSubScan ? ` with projectPath: "${plan.exploreRoot}"` : '';
1232
+ process.stdout.write(`<codegraph_context note="CodeGraph found indexed symbols matching this prompt — query the graph before searching files.">\n` +
1233
+ `This project's CodeGraph index contains symbols matching this request:\n${lines}\n` +
1234
+ `Call codegraph_explore ONCE${projectHint} with the relevant names in one query (e.g. "${exampleQuery}") ` +
1235
+ `to get their source, call paths, and blast radius — cheaper and more complete than Read/Grep.\n${others}` +
1236
+ `</codegraph_context>\n`);
1237
+ gate('medium-segment');
1238
+ }
1239
+ finally {
1240
+ cg.destroy();
1241
+ }
1242
+ }
1243
+ else {
1244
+ // Several indexed sub-projects, none a clear match — don't guess; tell
1245
+ // the agent they exist and how to query one.
1246
+ process.stdout.write(`<codegraph_context note="CodeGraph is available for this workspace's indexed sub-projects — query one by passing projectPath to codegraph_explore.">\n` +
1247
+ nudge(plan.nudgeProjects, "This workspace's CodeGraph indexes live in sub-projects. To use CodeGraph, call codegraph_explore with the projectPath of the relevant one:") +
1248
+ `</codegraph_context>\n`);
1249
+ gate('nudge-projects');
1250
+ }
1251
+ }
1252
+ catch {
1253
+ // Degradable by contract: never surface an error to the prompt pipeline.
1254
+ }
1255
+ });
1256
+ /**
1257
+ * codegraph node [name]
1258
+ *
1259
+ * The CLI face of the MCP codegraph_node tool: one symbol's source +
1260
+ * caller/callee trail, or a whole file with line numbers + dependents
1261
+ * (Read-parity). Same subagent/non-MCP rationale as `explore`.
1262
+ *
1263
+ * `name` is OPTIONAL because `--file` (file-read mode) carries no symbol —
1264
+ * a required `<name>` made `codegraph node -f <file>` unreachable (#1044).
1265
+ */
1266
+ program
1267
+ .command('node [name]')
1268
+ .description('One symbol\'s source + caller/callee trail, or read a file with line numbers + dependents (same output as the codegraph_node MCP tool)')
1269
+ .option('-p, --path <path>', 'Project path')
1270
+ .option('-f, --file <file>', 'Treat as file mode (or disambiguate a symbol to this file)')
1271
+ .option('--offset <number>', 'File mode: 1-based start line')
1272
+ .option('--limit <number>', 'File mode: maximum lines')
1273
+ .option('--symbols-only', 'File mode: just the symbol map + dependents')
1274
+ .action(async (name, options) => {
1275
+ // Need a symbol (positional) OR a file (--file / a path-like positional).
1276
+ // With [name] optional, a bare `codegraph node` reaches here with neither
1277
+ // and must be told what to pass, rather than crashing downstream.
1278
+ if (!name && !options.file) {
1279
+ error("Pass a symbol name (e.g. 'codegraph node parseToken') or a file (e.g. 'codegraph node -f src/auth.ts', or 'codegraph node src/auth.ts').");
1280
+ process.exit(1);
1281
+ }
1282
+ const projectPath = resolveProjectPath(options.path);
1283
+ try {
1284
+ if (!(0, directory_1.isInitialized)(projectPath)) {
1285
+ error(`CodeGraph isn't available here — no .codegraph/ index exists in ${projectPath}. If you are an AI agent: continue with your usual tools; indexing is the user's decision, do not run it yourself. (The project owner can enable CodeGraph with 'codegraph init'.)`);
1286
+ process.exit(1);
1287
+ }
1288
+ const { default: CodeGraph } = await loadCodeGraph();
1289
+ const cg = await CodeGraph.open(projectPath);
1290
+ const { ToolHandler } = await Promise.resolve().then(() => __importStar(require('../mcp/tools')));
1291
+ const handler = new ToolHandler(cg);
1292
+ // A name with a path separator is a file read; otherwise a symbol
1293
+ // (use --file for basename-only file reads or to pin an overload).
1294
+ // Both separators: Windows users type src\auth\session.ts. Symbols
1295
+ // never contain either ('/' isn't an identifier char anywhere we
1296
+ // index; C++ scope is '::', JS members '.').
1297
+ const args = {};
1298
+ if (options.file) {
1299
+ args.file = options.file;
1300
+ if (name && name !== options.file)
1301
+ args.symbol = name;
1302
+ }
1303
+ else if (name && (name.includes('/') || name.includes('\\'))) {
1304
+ args.file = name.replace(/\\/g, '/');
1305
+ }
1306
+ else if (name) {
1307
+ args.symbol = name;
1308
+ args.includeCode = true;
1309
+ }
1310
+ if (options.offset)
1311
+ args.offset = parseInt(options.offset, 10);
1312
+ if (options.limit)
1313
+ args.limit = parseInt(options.limit, 10);
1314
+ if (options.symbolsOnly)
1315
+ args.symbolsOnly = true;
1316
+ const result = await handler.execute('codegraph_node', args);
1317
+ console.log(result.content[0]?.text ?? '');
1318
+ cg.destroy();
1319
+ if (result.isError)
1320
+ process.exit(1);
1321
+ }
1322
+ catch (err) {
1323
+ error(`Node lookup failed: ${err instanceof Error ? err.message : String(err)}`);
1324
+ process.exit(1);
1325
+ }
1326
+ });
1327
+ /**
1328
+ * codegraph files [path]
1329
+ */
1330
+ program
1331
+ .command('files')
1332
+ .description('Show project file structure from the index')
1333
+ .option('-p, --path <path>', 'Project path')
1334
+ .option('--filter <dir>', 'Filter to files under this directory')
1335
+ .option('--pattern <glob>', 'Filter files matching this glob pattern')
1336
+ .option('--format <format>', 'Output format (tree, flat, grouped)', 'tree')
1337
+ .option('--max-depth <number>', 'Maximum directory depth for tree format')
1338
+ .option('--no-metadata', 'Hide file metadata (language, symbol count)')
1339
+ .option('-j, --json', 'Output as JSON')
1340
+ .action(async (options) => {
1341
+ const projectPath = resolveProjectPath(options.path);
1342
+ try {
1343
+ if (!(0, directory_1.isInitialized)(projectPath)) {
1344
+ error(`CodeGraph not initialized in ${projectPath}`);
1345
+ process.exit(1);
1346
+ }
1347
+ const { default: CodeGraph } = await loadCodeGraph();
1348
+ const cg = await CodeGraph.open(projectPath);
1349
+ let files = cg.getFiles();
1350
+ if (files.length === 0) {
1351
+ info('No files indexed. Run "codegraph index" first.');
1352
+ cg.destroy();
1353
+ return;
1354
+ }
1355
+ // Filter by path prefix
1356
+ if (options.filter) {
1357
+ const filter = options.filter;
1358
+ files = files.filter(f => f.path.startsWith(filter) || f.path.startsWith('./' + filter));
1359
+ }
1360
+ // Filter by glob pattern
1361
+ if (options.pattern) {
1362
+ const regex = globToRegex(options.pattern);
1363
+ files = files.filter(f => regex.test(f.path));
1364
+ }
1365
+ if (files.length === 0) {
1366
+ info('No files found matching the criteria.');
1367
+ cg.destroy();
1368
+ return;
1369
+ }
1370
+ // JSON output
1371
+ if (options.json) {
1372
+ const output = files.map(f => ({
1373
+ path: f.path,
1374
+ language: f.language,
1375
+ nodeCount: f.nodeCount,
1376
+ size: f.size,
1377
+ }));
1378
+ console.log(JSON.stringify(output, null, 2));
1379
+ cg.destroy();
1380
+ return;
1381
+ }
1382
+ const includeMetadata = options.metadata !== false;
1383
+ const format = options.format || 'tree';
1384
+ const maxDepth = options.maxDepth ? parseInt(options.maxDepth, 10) : undefined;
1385
+ // Format output
1386
+ switch (format) {
1387
+ case 'flat':
1388
+ console.log(chalk.bold(`\nFiles (${files.length}):\n`));
1389
+ for (const file of files.sort((a, b) => a.path.localeCompare(b.path))) {
1390
+ if (includeMetadata) {
1391
+ console.log(` ${file.path} ${chalk.dim(`(${file.language}, ${file.nodeCount} symbols)`)}`);
1392
+ }
1393
+ else {
1394
+ console.log(` ${file.path}`);
1395
+ }
1396
+ }
1397
+ break;
1398
+ case 'grouped':
1399
+ console.log(chalk.bold(`\nFiles by Language (${files.length} total):\n`));
1400
+ const byLang = new Map();
1401
+ for (const file of files) {
1402
+ const existing = byLang.get(file.language) || [];
1403
+ existing.push(file);
1404
+ byLang.set(file.language, existing);
1405
+ }
1406
+ const sortedLangs = [...byLang.entries()].sort((a, b) => b[1].length - a[1].length);
1407
+ for (const [lang, langFiles] of sortedLangs) {
1408
+ console.log(chalk.cyan(`${lang} (${langFiles.length}):`));
1409
+ for (const file of langFiles.sort((a, b) => a.path.localeCompare(b.path))) {
1410
+ if (includeMetadata) {
1411
+ console.log(` ${file.path} ${chalk.dim(`(${file.nodeCount} symbols)`)}`);
1412
+ }
1413
+ else {
1414
+ console.log(` ${file.path}`);
1415
+ }
1416
+ }
1417
+ console.log();
1418
+ }
1419
+ break;
1420
+ case 'tree':
1421
+ default:
1422
+ console.log(chalk.bold(`\nProject Structure (${files.length} files):\n`));
1423
+ printFileTree(files, includeMetadata, maxDepth, chalk);
1424
+ break;
1425
+ }
1426
+ console.log();
1427
+ cg.destroy();
1428
+ }
1429
+ catch (err) {
1430
+ error(`Failed to list files: ${err instanceof Error ? err.message : String(err)}`);
1431
+ process.exit(1);
1432
+ }
1433
+ });
1434
+ /**
1435
+ * Normalize a user-supplied file path to the project-relative, forward-slash
1436
+ * form CodeGraph stores in the index. Accepts an absolute path, a `./`-prefixed
1437
+ * path, or Windows back-slashes; an empty string when the input is blank. Used
1438
+ * by `codegraph affected` so `./src/x.ts`, `/abs/repo/src/x.ts`, and
1439
+ * `src/x.ts` all match the same indexed file. (#825)
1440
+ */
1441
+ function normalizeIndexPath(filePath, projectPath) {
1442
+ let f = filePath.trim();
1443
+ if (!f)
1444
+ return '';
1445
+ if (path.isAbsolute(f))
1446
+ f = path.relative(projectPath, f);
1447
+ // Collapse `.`/`..` segments, then force forward slashes and drop a leading
1448
+ // `./` (path.normalize already strips it on POSIX; explicit for Windows).
1449
+ f = path.normalize(f).replace(/\\/g, '/').replace(/^\.\//, '');
1450
+ return f;
1451
+ }
1452
+ /**
1453
+ * Convert glob pattern to regex
1454
+ */
1455
+ function globToRegex(pattern) {
1456
+ const escaped = pattern
1457
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
1458
+ .replace(/\*\*/g, '{{GLOBSTAR}}')
1459
+ .replace(/\*/g, '[^/]*')
1460
+ .replace(/\?/g, '[^/]')
1461
+ .replace(/\{\{GLOBSTAR\}\}/g, '.*');
1462
+ return new RegExp(escaped);
1463
+ }
1464
+ /**
1465
+ * Print files as a tree
1466
+ */
1467
+ function printFileTree(files, includeMetadata, maxDepth, chalk) {
1468
+ const root = { name: '', children: new Map() };
1469
+ for (const file of files) {
1470
+ const parts = file.path.split('/');
1471
+ let current = root;
1472
+ for (let i = 0; i < parts.length; i++) {
1473
+ const part = parts[i];
1474
+ if (!part)
1475
+ continue;
1476
+ if (!current.children.has(part)) {
1477
+ current.children.set(part, { name: part, children: new Map() });
1478
+ }
1479
+ current = current.children.get(part);
1480
+ if (i === parts.length - 1) {
1481
+ current.file = { language: file.language, nodeCount: file.nodeCount };
1482
+ }
1483
+ }
1484
+ }
1485
+ const renderNode = (node, prefix, isLast, depth) => {
1486
+ if (maxDepth !== undefined && depth > maxDepth)
1487
+ return;
1488
+ const glyphs = (0, glyphs_1.getGlyphs)();
1489
+ const connector = isLast ? glyphs.treeLast : glyphs.treeBranch;
1490
+ const childPrefix = isLast ? ' ' : glyphs.treePipe;
1491
+ if (node.name) {
1492
+ let line = prefix + connector + node.name;
1493
+ if (node.file && includeMetadata) {
1494
+ line += chalk.dim(` (${node.file.language}, ${node.file.nodeCount} symbols)`);
1495
+ }
1496
+ console.log(line);
1497
+ }
1498
+ const children = [...node.children.values()];
1499
+ children.sort((a, b) => {
1500
+ const aIsDir = a.children.size > 0 && !a.file;
1501
+ const bIsDir = b.children.size > 0 && !b.file;
1502
+ if (aIsDir !== bIsDir)
1503
+ return aIsDir ? -1 : 1;
1504
+ return a.name.localeCompare(b.name);
1505
+ });
1506
+ for (let i = 0; i < children.length; i++) {
1507
+ const child = children[i];
1508
+ const nextPrefix = node.name ? prefix + childPrefix : prefix;
1509
+ renderNode(child, nextPrefix, i === children.length - 1, depth + 1);
1510
+ }
1511
+ };
1512
+ renderNode(root, '', true, 0);
1513
+ }
1514
+ /**
1515
+ * codegraph daemon — interactive manager for the background daemons. Arrow keys
1516
+ * to pick one (the current project's daemon floats to the top, auto-selected),
1517
+ * enter to stop it. Falls back to a plain list when output isn't a TTY.
1518
+ */
1519
+ program
1520
+ .command('daemon')
1521
+ .aliases(['daemons'])
1522
+ .description('Manage running CodeGraph background daemons — pick one and press enter to stop it')
1523
+ .action(async () => {
1524
+ const { listDaemons, stopDaemonAt, stopAllDaemons } = await Promise.resolve().then(() => __importStar(require('../mcp/daemon-registry')));
1525
+ const { runDaemonPicker } = await Promise.resolve().then(() => __importStar(require('../mcp/daemon-manager')));
1526
+ const daemons = listDaemons();
1527
+ if (daemons.length === 0) {
1528
+ info('No CodeGraph daemons running.');
1529
+ return;
1530
+ }
1531
+ // No TTY (piped / CI / non-interactive) — can't do arrow-key selection, so
1532
+ // just print what's running instead of crashing on a prompt with no input.
1533
+ if (!process.stdout.isTTY || !process.stdin.isTTY) {
1534
+ for (const d of daemons) {
1535
+ console.log(`pid ${d.pid} v${d.version} up ${formatDuration(Date.now() - d.startedAt)} ${d.root}`);
1536
+ }
1537
+ return;
1538
+ }
1539
+ // The current project's daemon floats to the top and is pre-selected.
1540
+ let cwdRoot = null;
1541
+ const found = (0, directory_1.findNearestCodeGraphRoot)(process.cwd());
1542
+ if (found) {
1543
+ try {
1544
+ cwdRoot = fs.realpathSync(found);
1545
+ }
1546
+ catch {
1547
+ cwdRoot = found;
1548
+ }
1549
+ }
1550
+ const clack = await importESM('@clack/prompts');
1551
+ clack.intro('CodeGraph daemons');
1552
+ await runDaemonPicker({
1553
+ list: listDaemons,
1554
+ stop: stopDaemonAt,
1555
+ stopAll: stopAllDaemons,
1556
+ cwdRoot,
1557
+ now: () => Date.now(),
1558
+ select: (opts) => clack.select(opts),
1559
+ isCancel: (v) => clack.isCancel(v),
1560
+ note: (m) => clack.log.success(m),
1561
+ done: (m) => clack.outro(m),
1562
+ });
1563
+ });
1564
+ /**
1565
+ * codegraph serve
1566
+ */
1567
+ program
1568
+ // Hidden from `--help`: this is the stdio entry point an AI agent launches
1569
+ // for itself (the installer wires `args: ['serve','--mcp']` into every
1570
+ // agent's MCP config), not a command a human runs. It still works when
1571
+ // invoked — hiding only removes it from the listing. See the interactive-TTY
1572
+ // guard below, which explains this to anyone who runs it by hand.
1573
+ .command('serve', { hidden: true })
1574
+ .description('Start CodeGraph as an MCP server for AI assistants')
1575
+ .option('-p, --path <path>', 'Project path (optional for MCP mode, uses rootUri from client)')
1576
+ .option('--mcp', 'Run as MCP server (stdio transport)')
1577
+ .option('--no-watch', 'Disable the file watcher (no auto-sync; useful on slow filesystems like WSL2 /mnt drives)')
1578
+ .action(async (options) => {
1579
+ const projectPath = options.path ? resolveProjectPath(options.path) : undefined;
1580
+ // Commander sets watch=false when --no-watch is passed. Route it through
1581
+ // the same env-var chokepoint the watcher and MCP server already honor.
1582
+ if (options.watch === false) {
1583
+ process.env.CODEGRAPH_NO_WATCH = '1';
1584
+ }
1585
+ try {
1586
+ if (options.mcp) {
1587
+ // `serve --mcp` is the stdio MCP server an AI agent launches for itself,
1588
+ // not a command to run by hand. A human in a terminal would otherwise
1589
+ // see it hang waiting for JSON-RPC on stdin, which reads as broken. If
1590
+ // stdin is an interactive TTY, explain instead of hanging. The agent's
1591
+ // pipe and the detached daemon both have a non-TTY stdin, so this only
1592
+ // ever fires for a person who typed it.
1593
+ if (process.stdin.isTTY && !process.env.CODEGRAPH_DAEMON_INTERNAL) {
1594
+ console.error(chalk.bold('\nCodeGraph MCP server\n'));
1595
+ console.error("This is the MCP server your AI agent (Claude Code, Cursor, Codex, opencode, …)");
1596
+ console.error("starts automatically — you don't run it yourself.");
1597
+ console.error(`\nIt's already wired up by ${chalk.cyan('codegraph install')}. To check on things:`);
1598
+ console.error(` ${chalk.cyan('codegraph status')} ${chalk.dim('— is this project indexed and healthy?')}`);
1599
+ console.error(` ${chalk.cyan('codegraph daemon')} ${chalk.dim('— list or stop background MCP servers')}`);
1600
+ console.error(chalk.dim('\n(Running it directly only does something when an MCP client drives it over stdin.)'));
1601
+ return;
1602
+ }
1603
+ // Start MCP server - it handles initialization lazily based on rootUri from client
1604
+ const { MCPServer } = await Promise.resolve().then(() => __importStar(require('../mcp/index')));
1605
+ const server = new MCPServer(projectPath);
1606
+ await server.start();
1607
+ // Server will run until terminated
1608
+ }
1609
+ else {
1610
+ // Default: show info about MCP mode.
1611
+ // Use stderr so stdout stays clean for any piped/stdio usage.
1612
+ console.error(chalk.bold('\nCodeGraph MCP Server\n'));
1613
+ console.error(chalk.blue((0, glyphs_1.getGlyphs)().info) + ' Use --mcp flag to start the MCP server');
1614
+ console.error('\nTo use with Claude Code, add to your MCP configuration:');
1615
+ console.error(chalk.dim(`
1616
+ {
1617
+ "mcpServers": {
1618
+ "codegraph": {
1619
+ "command": "codegraph",
1620
+ "args": ["serve", "--mcp"]
1621
+ }
1622
+ }
1623
+ }
1624
+ `));
1625
+ console.error('Available tools:');
1626
+ console.error(chalk.cyan(' codegraph_explore') + ' - Primary: source of the relevant symbols for any question');
1627
+ console.error(chalk.cyan(' codegraph_search') + ' - Search for code symbols');
1628
+ console.error(chalk.cyan(' codegraph_callers') + ' - Find callers of a symbol');
1629
+ console.error(chalk.cyan(' codegraph_callees') + ' - Find what a symbol calls');
1630
+ console.error(chalk.cyan(' codegraph_impact') + ' - Analyze impact of changes');
1631
+ console.error(chalk.cyan(' codegraph_node') + ' - Get symbol details');
1632
+ console.error(chalk.cyan(' codegraph_files') + ' - Get project file structure');
1633
+ console.error(chalk.cyan(' codegraph_status') + ' - Get index status');
1634
+ }
1635
+ }
1636
+ catch (err) {
1637
+ error(`Failed to start server: ${err instanceof Error ? err.message : String(err)}`);
1638
+ process.exit(1);
1639
+ }
1640
+ });
1641
+ /**
1642
+ * codegraph unlock [path]
1643
+ */
1644
+ program
1645
+ .command('unlock [path]')
1646
+ .description('Remove a stale lock file that is blocking indexing')
1647
+ .action(async (pathArg) => {
1648
+ const projectPath = resolveProjectPath(pathArg);
1649
+ try {
1650
+ if (!(0, directory_1.isInitialized)(projectPath)) {
1651
+ error(`CodeGraph not initialized in ${projectPath}`);
1652
+ return;
1653
+ }
1654
+ const lockPath = path.join((0, directory_1.getCodeGraphDir)(projectPath), 'codegraph.lock');
1655
+ if (!fs.existsSync(lockPath)) {
1656
+ info(`No lock file found ${(0, glyphs_1.getGlyphs)().dash} nothing to do`);
1657
+ return;
1658
+ }
1659
+ fs.unlinkSync(lockPath);
1660
+ success('Removed lock file. You can now run indexing again.');
1661
+ }
1662
+ catch (err) {
1663
+ error(`Failed to remove lock: ${err instanceof Error ? err.message : String(err)}`);
1664
+ process.exit(1);
1665
+ }
1666
+ });
1667
+ /**
1668
+ * codegraph callers <symbol>
1669
+ *
1670
+ * CLI parity with the MCP graph tools (codegraph_callers/callees/impact) so the
1671
+ * traversal queries work in scripts, CI, and git hooks without a running MCP
1672
+ * server.
1673
+ */
1674
+ program
1675
+ .command('callers <symbol>')
1676
+ .description('Find all functions/methods that call a specific symbol')
1677
+ .option('-p, --path <path>', 'Project path')
1678
+ .option('-l, --limit <number>', 'Maximum results', '20')
1679
+ .option('-j, --json', 'Output as JSON')
1680
+ .action(async (symbol, options) => {
1681
+ const projectPath = resolveProjectPath(options.path);
1682
+ try {
1683
+ if (!(0, directory_1.isInitialized)(projectPath)) {
1684
+ error(`CodeGraph not initialized in ${projectPath}`);
1685
+ process.exit(1);
1686
+ }
1687
+ const { default: CodeGraph } = await loadCodeGraph();
1688
+ const cg = await CodeGraph.open(projectPath);
1689
+ const limit = parseInt(options.limit || '20', 10);
1690
+ const matches = cg.searchNodes(symbol, { limit: 50 });
1691
+ if (matches.length === 0) {
1692
+ info(`Symbol "${symbol}" not found`);
1693
+ cg.destroy();
1694
+ return;
1695
+ }
1696
+ const seen = new Set();
1697
+ const allCallers = [];
1698
+ for (const match of matches) {
1699
+ const exactMatch = match.node.name === symbol || match.node.name.endsWith(`.${symbol}`) || match.node.name.endsWith(`::${symbol}`);
1700
+ if (!exactMatch && matches.length > 1)
1701
+ continue;
1702
+ for (const c of cg.getCallers(match.node.id)) {
1703
+ if (!seen.has(c.node.id)) {
1704
+ seen.add(c.node.id);
1705
+ allCallers.push({ name: c.node.name, kind: c.node.kind, filePath: c.node.filePath, startLine: c.node.startLine });
1706
+ }
1707
+ }
1708
+ }
1709
+ // Fallback: if exact filter removed everything, use the top match
1710
+ if (allCallers.length === 0 && matches[0]) {
1711
+ for (const c of cg.getCallers(matches[0].node.id)) {
1712
+ if (!seen.has(c.node.id)) {
1713
+ seen.add(c.node.id);
1714
+ allCallers.push({ name: c.node.name, kind: c.node.kind, filePath: c.node.filePath, startLine: c.node.startLine });
1715
+ }
1716
+ }
1717
+ }
1718
+ const limited = allCallers.slice(0, limit);
1719
+ if (options.json) {
1720
+ console.log(JSON.stringify({ symbol, callers: limited }, null, 2));
1721
+ }
1722
+ else if (limited.length === 0) {
1723
+ info(`No callers found for "${symbol}"`);
1724
+ }
1725
+ else {
1726
+ console.log(chalk.bold(`\nCallers of "${symbol}" (${limited.length}):\n`));
1727
+ for (const node of limited) {
1728
+ const loc = node.startLine ? `:${node.startLine}` : '';
1729
+ console.log(chalk.cyan(node.kind.padEnd(12)) +
1730
+ chalk.white(node.name));
1731
+ console.log(chalk.dim(` ${node.filePath}${loc}`));
1732
+ console.log();
1733
+ }
1734
+ }
1735
+ cg.destroy();
1736
+ }
1737
+ catch (err) {
1738
+ error(`callers failed: ${err instanceof Error ? err.message : String(err)}`);
1739
+ process.exit(1);
1740
+ }
1741
+ });
1742
+ /**
1743
+ * codegraph callees <symbol>
1744
+ */
1745
+ program
1746
+ .command('callees <symbol>')
1747
+ .description('Find all functions/methods that a specific symbol calls')
1748
+ .option('-p, --path <path>', 'Project path')
1749
+ .option('-l, --limit <number>', 'Maximum results', '20')
1750
+ .option('-j, --json', 'Output as JSON')
1751
+ .action(async (symbol, options) => {
1752
+ const projectPath = resolveProjectPath(options.path);
1753
+ try {
1754
+ if (!(0, directory_1.isInitialized)(projectPath)) {
1755
+ error(`CodeGraph not initialized in ${projectPath}`);
1756
+ process.exit(1);
1757
+ }
1758
+ const { default: CodeGraph } = await loadCodeGraph();
1759
+ const cg = await CodeGraph.open(projectPath);
1760
+ const limit = parseInt(options.limit || '20', 10);
1761
+ const matches = cg.searchNodes(symbol, { limit: 50 });
1762
+ if (matches.length === 0) {
1763
+ info(`Symbol "${symbol}" not found`);
1764
+ cg.destroy();
1765
+ return;
1766
+ }
1767
+ const seen = new Set();
1768
+ const allCallees = [];
1769
+ for (const match of matches) {
1770
+ const exactMatch = match.node.name === symbol || match.node.name.endsWith(`.${symbol}`) || match.node.name.endsWith(`::${symbol}`);
1771
+ if (!exactMatch && matches.length > 1)
1772
+ continue;
1773
+ for (const c of cg.getCallees(match.node.id)) {
1774
+ if (!seen.has(c.node.id)) {
1775
+ seen.add(c.node.id);
1776
+ allCallees.push({ name: c.node.name, kind: c.node.kind, filePath: c.node.filePath, startLine: c.node.startLine });
1777
+ }
1778
+ }
1779
+ }
1780
+ if (allCallees.length === 0 && matches[0]) {
1781
+ for (const c of cg.getCallees(matches[0].node.id)) {
1782
+ if (!seen.has(c.node.id)) {
1783
+ seen.add(c.node.id);
1784
+ allCallees.push({ name: c.node.name, kind: c.node.kind, filePath: c.node.filePath, startLine: c.node.startLine });
1785
+ }
1786
+ }
1787
+ }
1788
+ const limited = allCallees.slice(0, limit);
1789
+ if (options.json) {
1790
+ console.log(JSON.stringify({ symbol, callees: limited }, null, 2));
1791
+ }
1792
+ else if (limited.length === 0) {
1793
+ info(`No callees found for "${symbol}"`);
1794
+ }
1795
+ else {
1796
+ console.log(chalk.bold(`\nCallees of "${symbol}" (${limited.length}):\n`));
1797
+ for (const node of limited) {
1798
+ const loc = node.startLine ? `:${node.startLine}` : '';
1799
+ console.log(chalk.cyan(node.kind.padEnd(12)) +
1800
+ chalk.white(node.name));
1801
+ console.log(chalk.dim(` ${node.filePath}${loc}`));
1802
+ console.log();
1803
+ }
1804
+ }
1805
+ cg.destroy();
1806
+ }
1807
+ catch (err) {
1808
+ error(`callees failed: ${err instanceof Error ? err.message : String(err)}`);
1809
+ process.exit(1);
1810
+ }
1811
+ });
1812
+ /**
1813
+ * codegraph impact <symbol>
1814
+ */
1815
+ program
1816
+ .command('impact <symbol>')
1817
+ .description('Analyze what code is affected by changing a symbol')
1818
+ .option('-p, --path <path>', 'Project path')
1819
+ .option('-d, --depth <number>', 'Traversal depth', '2')
1820
+ .option('-j, --json', 'Output as JSON')
1821
+ .action(async (symbol, options) => {
1822
+ const projectPath = resolveProjectPath(options.path);
1823
+ try {
1824
+ if (!(0, directory_1.isInitialized)(projectPath)) {
1825
+ error(`CodeGraph not initialized in ${projectPath}`);
1826
+ process.exit(1);
1827
+ }
1828
+ const { default: CodeGraph } = await loadCodeGraph();
1829
+ const cg = await CodeGraph.open(projectPath);
1830
+ const depth = Math.min(Math.max(parseInt(options.depth || '2', 10), 1), 10);
1831
+ const matches = cg.searchNodes(symbol, { limit: 50 });
1832
+ if (matches.length === 0) {
1833
+ info(`Symbol "${symbol}" not found`);
1834
+ cg.destroy();
1835
+ return;
1836
+ }
1837
+ // Merge impact subgraphs across all exact-matching symbols
1838
+ const mergedNodes = new Map();
1839
+ const seenEdges = new Set();
1840
+ let edgeCount = 0;
1841
+ for (const match of matches) {
1842
+ const exactMatch = match.node.name === symbol || match.node.name.endsWith(`.${symbol}`) || match.node.name.endsWith(`::${symbol}`);
1843
+ if (!exactMatch && matches.length > 1)
1844
+ continue;
1845
+ const impact = cg.getImpactRadius(match.node.id, depth);
1846
+ for (const [id, n] of impact.nodes) {
1847
+ mergedNodes.set(id, { name: n.name, kind: n.kind, filePath: n.filePath, startLine: n.startLine });
1848
+ }
1849
+ for (const e of impact.edges) {
1850
+ const key = `${e.source}->${e.target}:${e.kind}`;
1851
+ if (!seenEdges.has(key)) {
1852
+ seenEdges.add(key);
1853
+ edgeCount++;
1854
+ }
1855
+ }
1856
+ }
1857
+ // Fallback to top match if exact filter removed everything
1858
+ if (mergedNodes.size === 0 && matches[0]) {
1859
+ const impact = cg.getImpactRadius(matches[0].node.id, depth);
1860
+ for (const [id, n] of impact.nodes) {
1861
+ mergedNodes.set(id, { name: n.name, kind: n.kind, filePath: n.filePath, startLine: n.startLine });
1862
+ }
1863
+ edgeCount = impact.edges.length;
1864
+ }
1865
+ if (options.json) {
1866
+ console.log(JSON.stringify({
1867
+ symbol,
1868
+ depth,
1869
+ nodeCount: mergedNodes.size,
1870
+ edgeCount,
1871
+ affected: Array.from(mergedNodes.values()),
1872
+ }, null, 2));
1873
+ }
1874
+ else if (mergedNodes.size === 0) {
1875
+ info(`No affected symbols found for "${symbol}"`);
1876
+ }
1877
+ else {
1878
+ console.log(chalk.bold(`\nImpact of changing "${symbol}" — ${mergedNodes.size} affected symbols:\n`));
1879
+ // Group by file
1880
+ const byFile = new Map();
1881
+ for (const node of mergedNodes.values()) {
1882
+ const list = byFile.get(node.filePath) || [];
1883
+ list.push({ name: node.name, kind: node.kind, startLine: node.startLine });
1884
+ byFile.set(node.filePath, list);
1885
+ }
1886
+ for (const [file, nodes] of byFile) {
1887
+ console.log(chalk.cyan(file));
1888
+ for (const node of nodes) {
1889
+ const loc = node.startLine ? `:${node.startLine}` : '';
1890
+ console.log(` ${chalk.dim(node.kind.padEnd(12))}${node.name}${chalk.dim(loc)}`);
1891
+ }
1892
+ console.log();
1893
+ }
1894
+ }
1895
+ cg.destroy();
1896
+ }
1897
+ catch (err) {
1898
+ error(`impact failed: ${err instanceof Error ? err.message : String(err)}`);
1899
+ process.exit(1);
1900
+ }
1901
+ });
1902
+ /**
1903
+ * codegraph affected [files...]
1904
+ *
1905
+ * Find test files affected by the given source files.
1906
+ * Traces dependency edges transitively to find test files that depend on changed code.
1907
+ *
1908
+ * Usage:
1909
+ * git diff --name-only | codegraph affected --stdin
1910
+ * codegraph affected src/lib/components/Editor.svelte src/routes/+page.svelte
1911
+ */
1912
+ program
1913
+ .command('affected [files...]')
1914
+ .description('Find test files affected by changed source files')
1915
+ .option('-p, --path <path>', 'Project path')
1916
+ .option('--stdin', 'Read file list from stdin (one per line)')
1917
+ .option('-d, --depth <number>', 'Max dependency traversal depth', '5')
1918
+ .option('-f, --filter <glob>', 'Custom glob filter for test files (e.g. "e2e/*.spec.ts")')
1919
+ .option('-j, --json', 'Output as JSON')
1920
+ .option('-q, --quiet', 'Only output file paths, no decoration')
1921
+ .action(async (fileArgs, options) => {
1922
+ const projectPath = resolveProjectPath(options.path);
1923
+ try {
1924
+ if (!(0, directory_1.isInitialized)(projectPath)) {
1925
+ error(`CodeGraph not initialized in ${projectPath}`);
1926
+ process.exit(1);
1927
+ }
1928
+ // Collect changed files from args or stdin
1929
+ let changedFiles = [...(fileArgs || [])];
1930
+ if (options.stdin) {
1931
+ const stdinData = fs.readFileSync(0, 'utf-8');
1932
+ const stdinFiles = stdinData.split('\n').map(f => f.trim()).filter(Boolean);
1933
+ changedFiles.push(...stdinFiles);
1934
+ }
1935
+ // Normalize inputs to the project-relative, forward-slash form the index
1936
+ // stores. Without this, `affected ./src/x.ts`, an absolute path (what a
1937
+ // wrapping script often passes), or a Windows back-slash path silently
1938
+ // matches nothing and reports 0 affected tests. (#825)
1939
+ changedFiles = changedFiles
1940
+ .map((f) => normalizeIndexPath(f, projectPath))
1941
+ .filter(Boolean);
1942
+ if (changedFiles.length === 0) {
1943
+ if (!options.quiet)
1944
+ info('No files provided. Use file arguments or --stdin.');
1945
+ process.exit(0);
1946
+ }
1947
+ const { default: CodeGraph } = await loadCodeGraph();
1948
+ const cg = await CodeGraph.open(projectPath);
1949
+ const maxDepth = parseInt(options.depth || '5', 10);
1950
+ // Common test file patterns
1951
+ const defaultTestPatterns = [
1952
+ /\.spec\./,
1953
+ /\.test\./,
1954
+ /\/__tests__\//,
1955
+ /\/tests?\//,
1956
+ /\/e2e\//,
1957
+ /\/spec\//,
1958
+ ];
1959
+ // Custom filter pattern
1960
+ let customFilter = null;
1961
+ if (options.filter) {
1962
+ // Convert glob to regex: ** → .+, * → [^/]*, . → \.
1963
+ const regex = options.filter
1964
+ .replace(/[+[\]{}()^$|\\]/g, '\\$&')
1965
+ .replace(/\./g, '\\.')
1966
+ .replace(/\*\*/g, '.+')
1967
+ .replace(/\*/g, '[^/]*');
1968
+ customFilter = new RegExp(regex);
1969
+ }
1970
+ function isTestFile(filePath) {
1971
+ if (customFilter)
1972
+ return customFilter.test(filePath);
1973
+ return defaultTestPatterns.some(p => p.test(filePath));
1974
+ }
1975
+ // BFS to find all transitive dependents of changed files, filtered to test files
1976
+ const affectedTests = new Set();
1977
+ const allDependents = new Set();
1978
+ for (const file of changedFiles) {
1979
+ // If the changed file is itself a test file, include it
1980
+ if (isTestFile(file)) {
1981
+ affectedTests.add(file);
1982
+ continue;
1983
+ }
1984
+ // BFS through dependents
1985
+ const queue = [{ file, depth: 0 }];
1986
+ const visited = new Set();
1987
+ visited.add(file);
1988
+ while (queue.length > 0) {
1989
+ const current = queue.shift();
1990
+ if (current.depth >= maxDepth)
1991
+ continue;
1992
+ const dependents = cg.getFileDependents(current.file);
1993
+ for (const dep of dependents) {
1994
+ if (visited.has(dep))
1995
+ continue;
1996
+ visited.add(dep);
1997
+ allDependents.add(dep);
1998
+ if (isTestFile(dep)) {
1999
+ affectedTests.add(dep);
2000
+ }
2001
+ else {
2002
+ queue.push({ file: dep, depth: current.depth + 1 });
2003
+ }
2004
+ }
2005
+ }
2006
+ }
2007
+ const sortedTests = Array.from(affectedTests).sort();
2008
+ // Output
2009
+ if (options.json) {
2010
+ console.log(JSON.stringify({
2011
+ changedFiles,
2012
+ affectedTests: sortedTests,
2013
+ totalDependentsTraversed: allDependents.size,
2014
+ }, null, 2));
2015
+ }
2016
+ else if (options.quiet) {
2017
+ for (const t of sortedTests)
2018
+ console.log(t);
2019
+ }
2020
+ else {
2021
+ if (sortedTests.length === 0) {
2022
+ info('No test files affected by the changed files.');
2023
+ }
2024
+ else {
2025
+ console.log(chalk.bold(`\nAffected test files (${sortedTests.length}):\n`));
2026
+ for (const t of sortedTests) {
2027
+ console.log(' ' + chalk.cyan(t));
2028
+ }
2029
+ console.log();
2030
+ }
2031
+ }
2032
+ cg.destroy();
2033
+ }
2034
+ catch (err) {
2035
+ error(`Affected analysis failed: ${err instanceof Error ? err.message : String(err)}`);
2036
+ process.exit(1);
2037
+ }
2038
+ });
2039
+ /**
2040
+ * codegraph install
2041
+ */
2042
+ program
2043
+ .command('install')
2044
+ .description('Install codegraph MCP server into one or more agents (Claude Code, Cursor, Codex CLI, opencode, Hermes Agent)')
2045
+ .option('-t, --target <ids>', 'Target agent(s): comma-separated ids, or "auto"|"all"|"none". Default: prompt')
2046
+ .option('-l, --location <where>', 'Install location: "global" or "local". Default: prompt')
2047
+ .option('-y, --yes', 'Non-interactive: defaults to --location=global --target=auto, auto-allow on')
2048
+ .option('--no-permissions', 'Skip writing the auto-allow permissions list (Claude Code only)')
2049
+ .option('--print-config <id>', 'Print MCP config snippet for the named agent and exit (no file writes)')
2050
+ .option('--refresh', 'Rewrite what previous installs configured, for already-configured agents only (never adds new ones). Run automatically by `codegraph upgrade`')
2051
+ .action(async (opts) => {
2052
+ if (opts.printConfig) {
2053
+ const { getTarget, listTargetIds } = await Promise.resolve().then(() => __importStar(require('../installer/targets/registry')));
2054
+ const target = getTarget(opts.printConfig);
2055
+ if (!target) {
2056
+ const known = listTargetIds().join(', ');
2057
+ error(`Unknown target "${opts.printConfig}". Known: ${known}.`);
2058
+ process.exit(1);
2059
+ }
2060
+ const loc = (opts.location === 'local' ? 'local' : 'global');
2061
+ process.stdout.write(target.printConfig(loc));
2062
+ return;
2063
+ }
2064
+ // --refresh: non-interactive sweep that re-writes what previous
2065
+ // installs configured (instructions section, MCP entry, legacy-hook
2066
+ // cleanups) for already-configured agents, so those surfaces match
2067
+ // THIS binary's templates. Skips everything else — never a first
2068
+ // install, never touches permissions or the prompt hook. Sweeps both
2069
+ // locations unless --location narrows it.
2070
+ if (opts.refresh) {
2071
+ const { refreshTargets } = await Promise.resolve().then(() => __importStar(require('../installer')));
2072
+ const { ALL_TARGETS } = await Promise.resolve().then(() => __importStar(require('../installer/targets/registry')));
2073
+ if (opts.location && opts.location !== 'global' && opts.location !== 'local') {
2074
+ error(`--location must be "global" or "local" (got "${opts.location}").`);
2075
+ process.exit(1);
2076
+ }
2077
+ const locs = opts.location
2078
+ ? [opts.location]
2079
+ : ['global', 'local'];
2080
+ let changed = 0;
2081
+ for (const loc of locs) {
2082
+ for (const report of refreshTargets(ALL_TARGETS, loc)) {
2083
+ for (const p of report.changedPaths) {
2084
+ changed += 1;
2085
+ console.log(` ${report.displayName}: refreshed ${p}`);
2086
+ }
2087
+ }
2088
+ }
2089
+ if (changed === 0) {
2090
+ console.log('All configured agent surfaces are already current.');
2091
+ }
2092
+ return;
2093
+ }
2094
+ const { runInstallerWithOptions } = await Promise.resolve().then(() => __importStar(require('../installer')));
2095
+ if (opts.location && opts.location !== 'global' && opts.location !== 'local') {
2096
+ error(`--location must be "global" or "local" (got "${opts.location}").`);
2097
+ process.exit(1);
2098
+ }
2099
+ try {
2100
+ // Commander's `--no-permissions` makes `opts.permissions === false`;
2101
+ // omitting the flag leaves it `true` (the positive-form default).
2102
+ // We MUST treat the default-true as "user did not override — let
2103
+ // the orchestrator prompt" and only forward an explicit `false`
2104
+ // (or `true` when --yes implies it). Otherwise the auto-allow
2105
+ // prompt is silently skipped on every interactive run.
2106
+ const explicitNoPermissions = opts.permissions === false;
2107
+ const autoAllow = explicitNoPermissions
2108
+ ? false
2109
+ : opts.yes
2110
+ ? true
2111
+ : undefined;
2112
+ await runInstallerWithOptions({
2113
+ target: opts.target,
2114
+ location: opts.location,
2115
+ autoAllow,
2116
+ yes: opts.yes,
2117
+ });
2118
+ }
2119
+ catch (err) {
2120
+ error(err instanceof Error ? err.message : String(err));
2121
+ process.exit(1);
2122
+ }
2123
+ });
2124
+ /**
2125
+ * codegraph uninstall
2126
+ *
2127
+ * Inverse of `install`. Removes the codegraph MCP server entry,
2128
+ * instructions block, and permissions from every agent (or a
2129
+ * `--target` subset). Prompts global-vs-local when not given. Does NOT
2130
+ * delete the `.codegraph/` index — that's `codegraph uninit`.
2131
+ */
2132
+ program
2133
+ .command('uninstall')
2134
+ .description('Remove codegraph from your agents (Claude Code, Cursor, Codex CLI, opencode, Hermes Agent)')
2135
+ .option('-t, --target <ids>', 'Target agent(s): comma-separated ids, or "all". Default: all')
2136
+ .option('-l, --location <where>', 'Uninstall location: "global" or "local". Default: prompt')
2137
+ .option('-y, --yes', 'Non-interactive: defaults to --location=global --target=all')
2138
+ .option('--keep-cli', 'Remove agent configs only — leave the codegraph CLI installed')
2139
+ .action(async (opts) => {
2140
+ const { runUninstaller } = await Promise.resolve().then(() => __importStar(require('../installer')));
2141
+ if (opts.location && opts.location !== 'global' && opts.location !== 'local') {
2142
+ error(`--location must be "global" or "local" (got "${opts.location}").`);
2143
+ process.exit(1);
2144
+ }
2145
+ try {
2146
+ await runUninstaller({
2147
+ target: opts.target,
2148
+ location: opts.location,
2149
+ yes: opts.yes,
2150
+ keepCli: opts.keepCli,
2151
+ cliFilename: __filename,
2152
+ });
2153
+ }
2154
+ catch (err) {
2155
+ error(err instanceof Error ? err.message : String(err));
2156
+ process.exit(1);
2157
+ }
2158
+ });
2159
+ /**
2160
+ * codegraph telemetry [on|off|status]
2161
+ */
2162
+ program
2163
+ .command('telemetry [action]')
2164
+ .description('Show or change anonymous usage telemetry (status, on, off)')
2165
+ .action((action) => {
2166
+ const t = (0, telemetry_1.getTelemetry)();
2167
+ if (action === 'on' || action === 'off') {
2168
+ t.setEnabled(action === 'on', 'cli');
2169
+ if (action === 'on') {
2170
+ success('Telemetry enabled — anonymous usage stats only (no code, paths, or names).');
2171
+ }
2172
+ else {
2173
+ success('Telemetry disabled. Buffered, unsent data was deleted.');
2174
+ }
2175
+ const effective = t.getStatus();
2176
+ if (effective.decidedBy === 'DO_NOT_TRACK' || effective.decidedBy === 'CODEGRAPH_TELEMETRY') {
2177
+ warn(`The ${effective.decidedBy} environment variable overrides this choice — ` +
2178
+ `effective state right now: ${effective.enabled ? 'enabled' : 'disabled'}.`);
2179
+ }
2180
+ return;
2181
+ }
2182
+ if (action !== undefined && action !== 'status') {
2183
+ error(`Unknown action: ${action} (expected status, on, or off)`);
2184
+ process.exit(1);
2185
+ }
2186
+ const s = t.getStatus();
2187
+ const decidedBy = {
2188
+ DO_NOT_TRACK: 'DO_NOT_TRACK environment variable',
2189
+ CODEGRAPH_TELEMETRY: 'CODEGRAPH_TELEMETRY environment variable',
2190
+ config: 'your saved choice',
2191
+ default: 'default',
2192
+ };
2193
+ console.log(`\nTelemetry: ${s.enabled ? chalk.green('enabled') : chalk.yellow('disabled')} ${chalk.dim(`(${decidedBy[s.decidedBy]})`)}`);
2194
+ console.log(`Machine ID: ${s.machineId ?? chalk.dim('(random UUID, created on first use)')}`);
2195
+ console.log(`Config: ${s.configPath}`);
2196
+ console.log(chalk.dim(`\nExactly what is collected (and never collected): ${telemetry_1.TELEMETRY_DOCS}\n`));
2197
+ });
2198
+ /**
2199
+ * codegraph upgrade [version]
2200
+ *
2201
+ * Self-update, however CodeGraph was installed (bundle via install.sh/.ps1,
2202
+ * npm-global, npx, or a source checkout). See ../upgrade for the detection and
2203
+ * per-method upgrade logic.
2204
+ */
2205
+ program
2206
+ .command('upgrade [version]')
2207
+ .description('Update CodeGraph to the latest release (or a specific version)')
2208
+ .option('--check', 'Check whether an update is available without installing')
2209
+ .option('-f, --force', 'Reinstall even if already on the target version')
2210
+ .action(async (versionArg, options) => {
2211
+ const up = await Promise.resolve().then(() => __importStar(require('../upgrade')));
2212
+ const method = up.detectInstallMethod({
2213
+ filename: __filename,
2214
+ platform: process.platform,
2215
+ cwd: process.cwd(),
2216
+ });
2217
+ const pin = versionArg || process.env.CODEGRAPH_VERSION || undefined;
2218
+ const code = await up.runUpgrade({ version: pin, check: options.check, force: options.force }, {
2219
+ currentVersion: packageJson.version,
2220
+ method,
2221
+ resolveLatest: () => up.resolveLatestVersion(),
2222
+ run: up.defaultRun,
2223
+ capture: up.defaultCapture,
2224
+ hasCommand: up.hasCommand,
2225
+ log: (m) => console.log(m),
2226
+ warn: (m) => warn(m),
2227
+ error: (m) => error(m),
2228
+ platform: process.platform,
2229
+ });
2230
+ process.exit(code);
2231
+ });
2232
+ /**
2233
+ * codegraph version
2234
+ *
2235
+ * The bare-noun form of `--version`. commander already provides `--version`
2236
+ * and `-V`, and the `-v` / `-version` spellings are intercepted before parse
2237
+ * (see top of main). This subcommand makes `codegraph version` work and lists
2238
+ * the version affordance in `codegraph --help`.
2239
+ */
2240
+ program
2241
+ .command('version')
2242
+ .description('Print the installed CodeGraph version (also: -v, --version)')
2243
+ .action(() => {
2244
+ console.log(packageJson.version);
2245
+ });
2246
+ // Parse and run
2247
+ program.parse();
2248
+ } // end main()
2249
+ //# sourceMappingURL=codegraph.js.map