homegraph 1.0.0 → 1.1.2

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