codegraph-java 0.1.0

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