@stupidloud/codegraph 0.7.7

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 (340) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +482 -0
  3. package/dist/bin/codegraph.d.ts +21 -0
  4. package/dist/bin/codegraph.d.ts.map +1 -0
  5. package/dist/bin/codegraph.js +1296 -0
  6. package/dist/bin/codegraph.js.map +1 -0
  7. package/dist/bin/node-version-check.d.ts +17 -0
  8. package/dist/bin/node-version-check.d.ts.map +1 -0
  9. package/dist/bin/node-version-check.js +39 -0
  10. package/dist/bin/node-version-check.js.map +1 -0
  11. package/dist/bin/uninstall.d.ts +14 -0
  12. package/dist/bin/uninstall.d.ts.map +1 -0
  13. package/dist/bin/uninstall.js +148 -0
  14. package/dist/bin/uninstall.js.map +1 -0
  15. package/dist/config.d.ts +51 -0
  16. package/dist/config.d.ts.map +1 -0
  17. package/dist/config.js +342 -0
  18. package/dist/config.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 +244 -0
  22. package/dist/context/formatter.js.map +1 -0
  23. package/dist/context/index.d.ts +99 -0
  24. package/dist/context/index.d.ts.map +1 -0
  25. package/dist/context/index.js +1075 -0
  26. package/dist/context/index.js.map +1 -0
  27. package/dist/db/index.d.ts +72 -0
  28. package/dist/db/index.d.ts.map +1 -0
  29. package/dist/db/index.js +200 -0
  30. package/dist/db/index.js.map +1 -0
  31. package/dist/db/migrations.d.ts +44 -0
  32. package/dist/db/migrations.d.ts.map +1 -0
  33. package/dist/db/migrations.js +160 -0
  34. package/dist/db/migrations.js.map +1 -0
  35. package/dist/db/queries.d.ts +253 -0
  36. package/dist/db/queries.d.ts.map +1 -0
  37. package/dist/db/queries.js +1202 -0
  38. package/dist/db/queries.js.map +1 -0
  39. package/dist/db/schema.sql +169 -0
  40. package/dist/db/sqlite-adapter.d.ts +52 -0
  41. package/dist/db/sqlite-adapter.d.ts.map +1 -0
  42. package/dist/db/sqlite-adapter.js +237 -0
  43. package/dist/db/sqlite-adapter.js.map +1 -0
  44. package/dist/directory.d.ts +57 -0
  45. package/dist/directory.d.ts.map +1 -0
  46. package/dist/directory.js +264 -0
  47. package/dist/directory.js.map +1 -0
  48. package/dist/errors.d.ts +136 -0
  49. package/dist/errors.d.ts.map +1 -0
  50. package/dist/errors.js +219 -0
  51. package/dist/errors.js.map +1 -0
  52. package/dist/extraction/dfm-extractor.d.ts +31 -0
  53. package/dist/extraction/dfm-extractor.d.ts.map +1 -0
  54. package/dist/extraction/dfm-extractor.js +151 -0
  55. package/dist/extraction/dfm-extractor.js.map +1 -0
  56. package/dist/extraction/grammars.d.ts +78 -0
  57. package/dist/extraction/grammars.d.ts.map +1 -0
  58. package/dist/extraction/grammars.js +322 -0
  59. package/dist/extraction/grammars.js.map +1 -0
  60. package/dist/extraction/index.d.ts +130 -0
  61. package/dist/extraction/index.d.ts.map +1 -0
  62. package/dist/extraction/index.js +1279 -0
  63. package/dist/extraction/index.js.map +1 -0
  64. package/dist/extraction/languages/c-cpp.d.ts +4 -0
  65. package/dist/extraction/languages/c-cpp.d.ts.map +1 -0
  66. package/dist/extraction/languages/c-cpp.js +126 -0
  67. package/dist/extraction/languages/c-cpp.js.map +1 -0
  68. package/dist/extraction/languages/csharp.d.ts +3 -0
  69. package/dist/extraction/languages/csharp.d.ts.map +1 -0
  70. package/dist/extraction/languages/csharp.js +72 -0
  71. package/dist/extraction/languages/csharp.js.map +1 -0
  72. package/dist/extraction/languages/dart.d.ts +3 -0
  73. package/dist/extraction/languages/dart.d.ts.map +1 -0
  74. package/dist/extraction/languages/dart.js +192 -0
  75. package/dist/extraction/languages/dart.js.map +1 -0
  76. package/dist/extraction/languages/go.d.ts +3 -0
  77. package/dist/extraction/languages/go.d.ts.map +1 -0
  78. package/dist/extraction/languages/go.js +58 -0
  79. package/dist/extraction/languages/go.js.map +1 -0
  80. package/dist/extraction/languages/index.d.ts +10 -0
  81. package/dist/extraction/languages/index.d.ts.map +1 -0
  82. package/dist/extraction/languages/index.js +45 -0
  83. package/dist/extraction/languages/index.js.map +1 -0
  84. package/dist/extraction/languages/java.d.ts +3 -0
  85. package/dist/extraction/languages/java.d.ts.map +1 -0
  86. package/dist/extraction/languages/java.js +64 -0
  87. package/dist/extraction/languages/java.js.map +1 -0
  88. package/dist/extraction/languages/javascript.d.ts +3 -0
  89. package/dist/extraction/languages/javascript.d.ts.map +1 -0
  90. package/dist/extraction/languages/javascript.js +90 -0
  91. package/dist/extraction/languages/javascript.js.map +1 -0
  92. package/dist/extraction/languages/kotlin.d.ts +3 -0
  93. package/dist/extraction/languages/kotlin.d.ts.map +1 -0
  94. package/dist/extraction/languages/kotlin.js +253 -0
  95. package/dist/extraction/languages/kotlin.js.map +1 -0
  96. package/dist/extraction/languages/pascal.d.ts +3 -0
  97. package/dist/extraction/languages/pascal.d.ts.map +1 -0
  98. package/dist/extraction/languages/pascal.js +66 -0
  99. package/dist/extraction/languages/pascal.js.map +1 -0
  100. package/dist/extraction/languages/php.d.ts +3 -0
  101. package/dist/extraction/languages/php.d.ts.map +1 -0
  102. package/dist/extraction/languages/php.js +107 -0
  103. package/dist/extraction/languages/php.js.map +1 -0
  104. package/dist/extraction/languages/python.d.ts +3 -0
  105. package/dist/extraction/languages/python.d.ts.map +1 -0
  106. package/dist/extraction/languages/python.js +56 -0
  107. package/dist/extraction/languages/python.js.map +1 -0
  108. package/dist/extraction/languages/ruby.d.ts +3 -0
  109. package/dist/extraction/languages/ruby.d.ts.map +1 -0
  110. package/dist/extraction/languages/ruby.js +114 -0
  111. package/dist/extraction/languages/ruby.js.map +1 -0
  112. package/dist/extraction/languages/rust.d.ts +3 -0
  113. package/dist/extraction/languages/rust.d.ts.map +1 -0
  114. package/dist/extraction/languages/rust.js +109 -0
  115. package/dist/extraction/languages/rust.js.map +1 -0
  116. package/dist/extraction/languages/scala.d.ts +3 -0
  117. package/dist/extraction/languages/scala.d.ts.map +1 -0
  118. package/dist/extraction/languages/scala.js +139 -0
  119. package/dist/extraction/languages/scala.js.map +1 -0
  120. package/dist/extraction/languages/swift.d.ts +3 -0
  121. package/dist/extraction/languages/swift.d.ts.map +1 -0
  122. package/dist/extraction/languages/swift.js +91 -0
  123. package/dist/extraction/languages/swift.js.map +1 -0
  124. package/dist/extraction/languages/typescript.d.ts +3 -0
  125. package/dist/extraction/languages/typescript.d.ts.map +1 -0
  126. package/dist/extraction/languages/typescript.js +129 -0
  127. package/dist/extraction/languages/typescript.js.map +1 -0
  128. package/dist/extraction/liquid-extractor.d.ts +52 -0
  129. package/dist/extraction/liquid-extractor.d.ts.map +1 -0
  130. package/dist/extraction/liquid-extractor.js +313 -0
  131. package/dist/extraction/liquid-extractor.js.map +1 -0
  132. package/dist/extraction/parse-worker.d.ts +8 -0
  133. package/dist/extraction/parse-worker.d.ts.map +1 -0
  134. package/dist/extraction/parse-worker.js +94 -0
  135. package/dist/extraction/parse-worker.js.map +1 -0
  136. package/dist/extraction/svelte-extractor.d.ts +56 -0
  137. package/dist/extraction/svelte-extractor.d.ts.map +1 -0
  138. package/dist/extraction/svelte-extractor.js +272 -0
  139. package/dist/extraction/svelte-extractor.js.map +1 -0
  140. package/dist/extraction/tree-sitter-helpers.d.ts +28 -0
  141. package/dist/extraction/tree-sitter-helpers.d.ts.map +1 -0
  142. package/dist/extraction/tree-sitter-helpers.js +103 -0
  143. package/dist/extraction/tree-sitter-helpers.js.map +1 -0
  144. package/dist/extraction/tree-sitter-types.d.ts +179 -0
  145. package/dist/extraction/tree-sitter-types.d.ts.map +1 -0
  146. package/dist/extraction/tree-sitter-types.js +10 -0
  147. package/dist/extraction/tree-sitter-types.js.map +1 -0
  148. package/dist/extraction/tree-sitter.d.ts +233 -0
  149. package/dist/extraction/tree-sitter.d.ts.map +1 -0
  150. package/dist/extraction/tree-sitter.js +2393 -0
  151. package/dist/extraction/tree-sitter.js.map +1 -0
  152. package/dist/extraction/vue-extractor.d.ts +36 -0
  153. package/dist/extraction/vue-extractor.d.ts.map +1 -0
  154. package/dist/extraction/vue-extractor.js +163 -0
  155. package/dist/extraction/vue-extractor.js.map +1 -0
  156. package/dist/extraction/wasm/tree-sitter-pascal.wasm +0 -0
  157. package/dist/extraction/wasm/tree-sitter-scala.wasm +0 -0
  158. package/dist/graph/index.d.ts +8 -0
  159. package/dist/graph/index.d.ts.map +1 -0
  160. package/dist/graph/index.js +13 -0
  161. package/dist/graph/index.js.map +1 -0
  162. package/dist/graph/queries.d.ts +106 -0
  163. package/dist/graph/queries.d.ts.map +1 -0
  164. package/dist/graph/queries.js +366 -0
  165. package/dist/graph/queries.js.map +1 -0
  166. package/dist/graph/traversal.d.ts +127 -0
  167. package/dist/graph/traversal.d.ts.map +1 -0
  168. package/dist/graph/traversal.js +493 -0
  169. package/dist/graph/traversal.js.map +1 -0
  170. package/dist/index.d.ts +504 -0
  171. package/dist/index.d.ts.map +1 -0
  172. package/dist/index.js +982 -0
  173. package/dist/index.js.map +1 -0
  174. package/dist/installer/claude-md-template.d.ts +10 -0
  175. package/dist/installer/claude-md-template.d.ts.map +1 -0
  176. package/dist/installer/claude-md-template.js +46 -0
  177. package/dist/installer/claude-md-template.js.map +1 -0
  178. package/dist/installer/config-writer.d.ts +36 -0
  179. package/dist/installer/config-writer.d.ts.map +1 -0
  180. package/dist/installer/config-writer.js +304 -0
  181. package/dist/installer/config-writer.js.map +1 -0
  182. package/dist/installer/index.d.ts +12 -0
  183. package/dist/installer/index.d.ts.map +1 -0
  184. package/dist/installer/index.js +201 -0
  185. package/dist/installer/index.js.map +1 -0
  186. package/dist/mcp/index.d.ts +82 -0
  187. package/dist/mcp/index.d.ts.map +1 -0
  188. package/dist/mcp/index.js +330 -0
  189. package/dist/mcp/index.js.map +1 -0
  190. package/dist/mcp/server-instructions.d.ts +19 -0
  191. package/dist/mcp/server-instructions.d.ts.map +1 -0
  192. package/dist/mcp/server-instructions.js +59 -0
  193. package/dist/mcp/server-instructions.js.map +1 -0
  194. package/dist/mcp/tools.d.ts +187 -0
  195. package/dist/mcp/tools.d.ts.map +1 -0
  196. package/dist/mcp/tools.js +1250 -0
  197. package/dist/mcp/tools.js.map +1 -0
  198. package/dist/mcp/transport.d.ts +89 -0
  199. package/dist/mcp/transport.d.ts.map +1 -0
  200. package/dist/mcp/transport.js +170 -0
  201. package/dist/mcp/transport.js.map +1 -0
  202. package/dist/resolution/frameworks/cargo-workspace.d.ts +18 -0
  203. package/dist/resolution/frameworks/cargo-workspace.d.ts.map +1 -0
  204. package/dist/resolution/frameworks/cargo-workspace.js +225 -0
  205. package/dist/resolution/frameworks/cargo-workspace.js.map +1 -0
  206. package/dist/resolution/frameworks/csharp.d.ts +8 -0
  207. package/dist/resolution/frameworks/csharp.d.ts.map +1 -0
  208. package/dist/resolution/frameworks/csharp.js +213 -0
  209. package/dist/resolution/frameworks/csharp.js.map +1 -0
  210. package/dist/resolution/frameworks/express.d.ts +8 -0
  211. package/dist/resolution/frameworks/express.d.ts.map +1 -0
  212. package/dist/resolution/frameworks/express.js +225 -0
  213. package/dist/resolution/frameworks/express.js.map +1 -0
  214. package/dist/resolution/frameworks/go.d.ts +8 -0
  215. package/dist/resolution/frameworks/go.d.ts.map +1 -0
  216. package/dist/resolution/frameworks/go.js +158 -0
  217. package/dist/resolution/frameworks/go.js.map +1 -0
  218. package/dist/resolution/frameworks/index.d.ts +41 -0
  219. package/dist/resolution/frameworks/index.d.ts.map +1 -0
  220. package/dist/resolution/frameworks/index.js +129 -0
  221. package/dist/resolution/frameworks/index.js.map +1 -0
  222. package/dist/resolution/frameworks/java.d.ts +8 -0
  223. package/dist/resolution/frameworks/java.d.ts.map +1 -0
  224. package/dist/resolution/frameworks/java.js +177 -0
  225. package/dist/resolution/frameworks/java.js.map +1 -0
  226. package/dist/resolution/frameworks/laravel.d.ts +13 -0
  227. package/dist/resolution/frameworks/laravel.d.ts.map +1 -0
  228. package/dist/resolution/frameworks/laravel.js +248 -0
  229. package/dist/resolution/frameworks/laravel.js.map +1 -0
  230. package/dist/resolution/frameworks/python.d.ts +10 -0
  231. package/dist/resolution/frameworks/python.d.ts.map +1 -0
  232. package/dist/resolution/frameworks/python.js +278 -0
  233. package/dist/resolution/frameworks/python.js.map +1 -0
  234. package/dist/resolution/frameworks/react.d.ts +8 -0
  235. package/dist/resolution/frameworks/react.d.ts.map +1 -0
  236. package/dist/resolution/frameworks/react.js +272 -0
  237. package/dist/resolution/frameworks/react.js.map +1 -0
  238. package/dist/resolution/frameworks/ruby.d.ts +8 -0
  239. package/dist/resolution/frameworks/ruby.d.ts.map +1 -0
  240. package/dist/resolution/frameworks/ruby.js +198 -0
  241. package/dist/resolution/frameworks/ruby.js.map +1 -0
  242. package/dist/resolution/frameworks/rust.d.ts +8 -0
  243. package/dist/resolution/frameworks/rust.d.ts.map +1 -0
  244. package/dist/resolution/frameworks/rust.js +207 -0
  245. package/dist/resolution/frameworks/rust.js.map +1 -0
  246. package/dist/resolution/frameworks/svelte.d.ts +9 -0
  247. package/dist/resolution/frameworks/svelte.d.ts.map +1 -0
  248. package/dist/resolution/frameworks/svelte.js +249 -0
  249. package/dist/resolution/frameworks/svelte.js.map +1 -0
  250. package/dist/resolution/frameworks/swift.d.ts +10 -0
  251. package/dist/resolution/frameworks/swift.d.ts.map +1 -0
  252. package/dist/resolution/frameworks/swift.js +376 -0
  253. package/dist/resolution/frameworks/swift.js.map +1 -0
  254. package/dist/resolution/frameworks/vue.d.ts +9 -0
  255. package/dist/resolution/frameworks/vue.d.ts.map +1 -0
  256. package/dist/resolution/frameworks/vue.js +306 -0
  257. package/dist/resolution/frameworks/vue.js.map +1 -0
  258. package/dist/resolution/import-resolver.d.ts +40 -0
  259. package/dist/resolution/import-resolver.d.ts.map +1 -0
  260. package/dist/resolution/import-resolver.js +663 -0
  261. package/dist/resolution/import-resolver.js.map +1 -0
  262. package/dist/resolution/index.d.ts +106 -0
  263. package/dist/resolution/index.d.ts.map +1 -0
  264. package/dist/resolution/index.js +709 -0
  265. package/dist/resolution/index.js.map +1 -0
  266. package/dist/resolution/name-matcher.d.ts +32 -0
  267. package/dist/resolution/name-matcher.d.ts.map +1 -0
  268. package/dist/resolution/name-matcher.js +384 -0
  269. package/dist/resolution/name-matcher.js.map +1 -0
  270. package/dist/resolution/path-aliases.d.ts +68 -0
  271. package/dist/resolution/path-aliases.d.ts.map +1 -0
  272. package/dist/resolution/path-aliases.js +238 -0
  273. package/dist/resolution/path-aliases.js.map +1 -0
  274. package/dist/resolution/strip-comments.d.ts +27 -0
  275. package/dist/resolution/strip-comments.d.ts.map +1 -0
  276. package/dist/resolution/strip-comments.js +441 -0
  277. package/dist/resolution/strip-comments.js.map +1 -0
  278. package/dist/resolution/types.d.ts +172 -0
  279. package/dist/resolution/types.d.ts.map +1 -0
  280. package/dist/resolution/types.js +8 -0
  281. package/dist/resolution/types.js.map +1 -0
  282. package/dist/search/query-parser.d.ts +57 -0
  283. package/dist/search/query-parser.d.ts.map +1 -0
  284. package/dist/search/query-parser.js +177 -0
  285. package/dist/search/query-parser.js.map +1 -0
  286. package/dist/search/query-utils.d.ts +53 -0
  287. package/dist/search/query-utils.d.ts.map +1 -0
  288. package/dist/search/query-utils.js +347 -0
  289. package/dist/search/query-utils.js.map +1 -0
  290. package/dist/sync/index.d.ts +13 -0
  291. package/dist/sync/index.d.ts.map +1 -0
  292. package/dist/sync/index.js +17 -0
  293. package/dist/sync/index.js.map +1 -0
  294. package/dist/sync/watcher.d.ts +81 -0
  295. package/dist/sync/watcher.d.ts.map +1 -0
  296. package/dist/sync/watcher.js +184 -0
  297. package/dist/sync/watcher.js.map +1 -0
  298. package/dist/types.d.ts +438 -0
  299. package/dist/types.d.ts.map +1 -0
  300. package/dist/types.js +263 -0
  301. package/dist/types.js.map +1 -0
  302. package/dist/ui/shimmer-progress.d.ts +11 -0
  303. package/dist/ui/shimmer-progress.d.ts.map +1 -0
  304. package/dist/ui/shimmer-progress.js +90 -0
  305. package/dist/ui/shimmer-progress.js.map +1 -0
  306. package/dist/ui/shimmer-worker.d.ts +2 -0
  307. package/dist/ui/shimmer-worker.d.ts.map +1 -0
  308. package/dist/ui/shimmer-worker.js +112 -0
  309. package/dist/ui/shimmer-worker.js.map +1 -0
  310. package/dist/ui/types.d.ts +17 -0
  311. package/dist/ui/types.d.ts.map +1 -0
  312. package/dist/ui/types.js +3 -0
  313. package/dist/ui/types.js.map +1 -0
  314. package/dist/utils.d.ts +205 -0
  315. package/dist/utils.d.ts.map +1 -0
  316. package/dist/utils.js +549 -0
  317. package/dist/utils.js.map +1 -0
  318. package/dist/vectors/embedder.d.ts +121 -0
  319. package/dist/vectors/embedder.d.ts.map +1 -0
  320. package/dist/vectors/embedder.js +237 -0
  321. package/dist/vectors/embedder.js.map +1 -0
  322. package/dist/vectors/index.d.ts +9 -0
  323. package/dist/vectors/index.d.ts.map +1 -0
  324. package/dist/vectors/index.js +20 -0
  325. package/dist/vectors/index.js.map +1 -0
  326. package/dist/vectors/manager.d.ts +124 -0
  327. package/dist/vectors/manager.d.ts.map +1 -0
  328. package/dist/vectors/manager.js +322 -0
  329. package/dist/vectors/manager.js.map +1 -0
  330. package/dist/vectors/search.d.ts +143 -0
  331. package/dist/vectors/search.d.ts.map +1 -0
  332. package/dist/vectors/search.js +460 -0
  333. package/dist/vectors/search.js.map +1 -0
  334. package/dist/visualizer/public/index.html +1994 -0
  335. package/dist/visualizer/server.d.ts +46 -0
  336. package/dist/visualizer/server.d.ts.map +1 -0
  337. package/dist/visualizer/server.js +491 -0
  338. package/dist/visualizer/server.js.map +1 -0
  339. package/package.json +60 -0
  340. package/scripts/patch-tree-sitter-dart.js +112 -0
@@ -0,0 +1,1296 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /**
4
+ * CodeGraph CLI
5
+ *
6
+ * Command-line interface for CodeGraph code intelligence.
7
+ *
8
+ * Usage:
9
+ * codegraph Run interactive installer (when no args)
10
+ * codegraph install Run interactive installer
11
+ * codegraph init [path] Initialize CodeGraph in a project
12
+ * codegraph uninit [path] Remove CodeGraph from a project
13
+ * codegraph index [path] Index all files in the project
14
+ * codegraph sync [path] Sync changes since last index
15
+ * codegraph status [path] Show index status
16
+ * codegraph query <search> Search for symbols
17
+ * codegraph files [options] Show project file structure
18
+ * codegraph context <task> Build context for a task
19
+ * codegraph affected [files] Find test files affected by changes
20
+ */
21
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
22
+ if (k2 === undefined) k2 = k;
23
+ var desc = Object.getOwnPropertyDescriptor(m, k);
24
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
25
+ desc = { enumerable: true, get: function() { return m[k]; } };
26
+ }
27
+ Object.defineProperty(o, k2, desc);
28
+ }) : (function(o, m, k, k2) {
29
+ if (k2 === undefined) k2 = k;
30
+ o[k2] = m[k];
31
+ }));
32
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
33
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
34
+ }) : function(o, v) {
35
+ o["default"] = v;
36
+ });
37
+ var __importStar = (this && this.__importStar) || (function () {
38
+ var ownKeys = function(o) {
39
+ ownKeys = Object.getOwnPropertyNames || function (o) {
40
+ var ar = [];
41
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
42
+ return ar;
43
+ };
44
+ return ownKeys(o);
45
+ };
46
+ return function (mod) {
47
+ if (mod && mod.__esModule) return mod;
48
+ var result = {};
49
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
50
+ __setModuleDefault(result, mod);
51
+ return result;
52
+ };
53
+ })();
54
+ Object.defineProperty(exports, "__esModule", { value: true });
55
+ const commander_1 = require("commander");
56
+ const path = __importStar(require("path"));
57
+ const fs = __importStar(require("fs"));
58
+ const child_process_1 = require("child_process");
59
+ const directory_1 = require("../directory");
60
+ const shimmer_progress_1 = require("../ui/shimmer-progress");
61
+ const node_version_check_1 = require("./node-version-check");
62
+ // Lazy-load heavy modules (CodeGraph, runInstaller) to keep CLI startup fast.
63
+ async function loadCodeGraph() {
64
+ try {
65
+ return await Promise.resolve().then(() => __importStar(require('../index')));
66
+ }
67
+ catch (err) {
68
+ const msg = err instanceof Error ? err.message : String(err);
69
+ console.error('\x1b[31m✗\x1b[0m Failed to load CodeGraph modules.');
70
+ console.error(`\n Node: ${process.version} Platform: ${process.platform} ${process.arch}`);
71
+ console.error(`\n Error: ${msg}`);
72
+ console.error('\n Try reinstalling with: npm install -g @stupidloud/codegraph\n');
73
+ process.exit(1);
74
+ }
75
+ }
76
+ // Dynamic import helper — tsc compiles import() to require() in CJS mode,
77
+ // which fails for ESM-only packages. This bypasses the transformation.
78
+ // eslint-disable-next-line @typescript-eslint/no-implied-eval
79
+ const importESM = new Function('specifier', 'return import(specifier)');
80
+ // Block CodeGraph on Node.js 25.x — V8's turboshaft WASM JIT has a Zone
81
+ // allocator bug that reliably crashes when compiling tree-sitter
82
+ // grammars (see #54, #81, #140). The previous behaviour was a soft
83
+ // console.warn that scrolls off-screen before the OOM crash 30 seconds
84
+ // later, leading to a steady stream of "what is this OOM" reports.
85
+ // Hard-exit before any WASM work; allow override via env var for users
86
+ // who patched V8 themselves or want to test a future fix.
87
+ const nodeVersion = process.versions.node;
88
+ const nodeMajor = parseInt(nodeVersion.split('.')[0] ?? '0', 10);
89
+ if (nodeMajor >= 25) {
90
+ process.stderr.write((0, node_version_check_1.buildNode25BlockBanner)(nodeVersion) + '\n');
91
+ if (!process.env.CODEGRAPH_ALLOW_UNSAFE_NODE) {
92
+ process.exit(1);
93
+ }
94
+ // Override active — banner shown for visibility, continuing.
95
+ }
96
+ // Check if running with no arguments - run installer
97
+ if (process.argv.length === 2) {
98
+ Promise.resolve().then(() => __importStar(require('../installer'))).then(({ runInstaller }) => runInstaller()).catch((err) => {
99
+ console.error('Installation failed:', err instanceof Error ? err.message : String(err));
100
+ process.exit(1);
101
+ });
102
+ }
103
+ else {
104
+ // Normal CLI flow
105
+ main();
106
+ }
107
+ process.on('uncaughtException', (error) => {
108
+ console.error('[CodeGraph] Uncaught exception:', error);
109
+ });
110
+ process.on('unhandledRejection', (reason) => {
111
+ console.error('[CodeGraph] Unhandled rejection:', reason);
112
+ });
113
+ function main() {
114
+ const program = new commander_1.Command();
115
+ // Version from package.json
116
+ const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf-8'));
117
+ // =============================================================================
118
+ // ANSI Color Helpers (avoid chalk ESM issues)
119
+ // =============================================================================
120
+ const colors = {
121
+ reset: '\x1b[0m',
122
+ bold: '\x1b[1m',
123
+ dim: '\x1b[2m',
124
+ red: '\x1b[31m',
125
+ green: '\x1b[32m',
126
+ yellow: '\x1b[33m',
127
+ blue: '\x1b[34m',
128
+ cyan: '\x1b[36m',
129
+ white: '\x1b[37m',
130
+ gray: '\x1b[90m',
131
+ };
132
+ const chalk = {
133
+ bold: (s) => `${colors.bold}${s}${colors.reset}`,
134
+ dim: (s) => `${colors.dim}${s}${colors.reset}`,
135
+ red: (s) => `${colors.red}${s}${colors.reset}`,
136
+ green: (s) => `${colors.green}${s}${colors.reset}`,
137
+ yellow: (s) => `${colors.yellow}${s}${colors.reset}`,
138
+ blue: (s) => `${colors.blue}${s}${colors.reset}`,
139
+ cyan: (s) => `${colors.cyan}${s}${colors.reset}`,
140
+ white: (s) => `${colors.white}${s}${colors.reset}`,
141
+ gray: (s) => `${colors.gray}${s}${colors.reset}`,
142
+ };
143
+ program
144
+ .name('codegraph')
145
+ .description('Code intelligence and knowledge graph for any codebase')
146
+ .version(packageJson.version);
147
+ // =============================================================================
148
+ // Helper Functions
149
+ // =============================================================================
150
+ /**
151
+ * Resolve project path from argument or current directory
152
+ * Walks up parent directories to find nearest initialized CodeGraph project
153
+ * (must have .codegraph/codegraph.db, not just .codegraph/lessons.db)
154
+ */
155
+ function resolveProjectPath(pathArg) {
156
+ const absolutePath = path.resolve(pathArg || process.cwd());
157
+ // If exact path is initialized (has codegraph.db), use it
158
+ if ((0, directory_1.isInitialized)(absolutePath)) {
159
+ return absolutePath;
160
+ }
161
+ // Walk up to find nearest parent with CodeGraph initialized
162
+ // Note: findNearestCodeGraphRoot finds any .codegraph folder, but we need one with codegraph.db
163
+ let current = absolutePath;
164
+ const root = path.parse(current).root;
165
+ while (current !== root) {
166
+ const parent = path.dirname(current);
167
+ if (parent === current)
168
+ break;
169
+ current = parent;
170
+ if ((0, directory_1.isInitialized)(current)) {
171
+ return current;
172
+ }
173
+ }
174
+ // Not found - return original path (will fail later with helpful error)
175
+ return absolutePath;
176
+ }
177
+ /**
178
+ * Format a number with commas
179
+ */
180
+ function formatNumber(n) {
181
+ return n.toLocaleString();
182
+ }
183
+ /**
184
+ * Format duration in milliseconds to human readable
185
+ */
186
+ function formatDuration(ms) {
187
+ if (ms < 1000) {
188
+ return `${ms}ms`;
189
+ }
190
+ const seconds = ms / 1000;
191
+ if (seconds < 60) {
192
+ return `${seconds.toFixed(1)}s`;
193
+ }
194
+ const minutes = Math.floor(seconds / 60);
195
+ const remainingSeconds = seconds % 60;
196
+ return `${minutes}m ${remainingSeconds.toFixed(0)}s`;
197
+ }
198
+ // Shimmer progress renderer (runs in a worker thread for smooth animation)
199
+ // Imported at top of file from '../ui/shimmer-progress'
200
+ /**
201
+ * Create a plain-text progress callback for --verbose mode.
202
+ * No animations, no ANSI tricks — just timestamped lines to stdout.
203
+ */
204
+ function createVerboseProgress() {
205
+ let lastPhase = '';
206
+ let lastPct = -1;
207
+ const startTime = Date.now();
208
+ return (progress) => {
209
+ const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
210
+ if (progress.phase !== lastPhase) {
211
+ lastPhase = progress.phase;
212
+ lastPct = -1;
213
+ console.log(`[${elapsed}s] Phase: ${progress.phase}`);
214
+ }
215
+ if (progress.total > 0) {
216
+ const pct = Math.floor((progress.current / progress.total) * 100);
217
+ // Log every 5% to keep output manageable
218
+ if (pct >= lastPct + 5 || progress.current === progress.total) {
219
+ lastPct = pct;
220
+ console.log(`[${elapsed}s] ${progress.current}/${progress.total} (${pct}%)${progress.currentFile ? ` — ${progress.currentFile}` : ''}`);
221
+ }
222
+ }
223
+ else if (progress.current > 0) {
224
+ // Scanning phase (no total yet) — log periodically
225
+ if (progress.current % 1000 === 0 || progress.current === 1) {
226
+ console.log(`[${elapsed}s] ${formatNumber(progress.current)} files found`);
227
+ }
228
+ }
229
+ };
230
+ }
231
+ /**
232
+ * Print success message
233
+ */
234
+ function success(message) {
235
+ console.log(chalk.green('✓') + ' ' + message);
236
+ }
237
+ /**
238
+ * Print error message
239
+ */
240
+ function error(message) {
241
+ console.error(chalk.red('✗') + ' ' + message);
242
+ }
243
+ /**
244
+ * Print info message
245
+ */
246
+ function info(message) {
247
+ console.log(chalk.blue('ℹ') + ' ' + message);
248
+ }
249
+ /**
250
+ * Print warning message
251
+ */
252
+ function warn(message) {
253
+ console.log(chalk.yellow('⚠') + ' ' + message);
254
+ }
255
+ /**
256
+ * Print indexing results using clack log methods
257
+ */
258
+ function printIndexResult(clack, result, projectPath) {
259
+ const hasErrors = result.filesErrored > 0;
260
+ // Surface non-file-level failures (e.g. lock-acquisition failure
261
+ // when another indexer is running) before the file-count branches.
262
+ // Without this the CLI falls through to "No files found to index",
263
+ // which is actively misleading — the index DID run, it just couldn't
264
+ // get the lock.
265
+ //
266
+ // If success is false but no severity:'error' entry exists in
267
+ // `result.errors` (degenerate case — shouldn't happen in practice
268
+ // but worth guarding because the result shape is plumbed through
269
+ // multiple call sites), fall back to a generic message rather than
270
+ // continuing to the misleading "No files found" branch or throwing.
271
+ if (!result.success && !hasErrors && result.filesIndexed === 0) {
272
+ const generic = result.errors.find((e) => e.severity === 'error');
273
+ clack.log.error(generic?.message ?? 'Indexing failed — no further details available');
274
+ return;
275
+ }
276
+ if (result.filesIndexed > 0) {
277
+ if (hasErrors) {
278
+ clack.log.success(`Indexed ${formatNumber(result.filesIndexed)} files (${formatNumber(result.filesErrored)} could not be parsed)`);
279
+ }
280
+ else {
281
+ clack.log.success(`Indexed ${formatNumber(result.filesIndexed)} files`);
282
+ }
283
+ clack.log.info(`${formatNumber(result.nodesCreated)} nodes, ${formatNumber(result.edgesCreated)} edges in ${formatDuration(result.durationMs)}`);
284
+ }
285
+ else if (hasErrors) {
286
+ clack.log.error(`Indexing failed — all ${formatNumber(result.filesErrored)} files had errors`);
287
+ }
288
+ else {
289
+ clack.log.warn('No files found to index');
290
+ }
291
+ if (hasErrors) {
292
+ const errorsByCode = new Map();
293
+ for (const err of result.errors) {
294
+ if (err.severity === 'error') {
295
+ const code = err.code || 'unknown';
296
+ errorsByCode.set(code, (errorsByCode.get(code) || 0) + 1);
297
+ }
298
+ }
299
+ const codeLabels = {
300
+ parse_error: 'files failed to parse',
301
+ read_error: 'files could not be read',
302
+ size_exceeded: 'files exceeded size limit',
303
+ path_traversal: 'blocked paths',
304
+ unsupported_language: 'unsupported language',
305
+ parser_error: 'parser initialization failures',
306
+ };
307
+ const breakdown = Array.from(errorsByCode)
308
+ .map(([code, count]) => `${formatNumber(count)} ${codeLabels[code] || code}`)
309
+ .join('\n');
310
+ clack.note(breakdown, 'Error breakdown');
311
+ if (projectPath) {
312
+ writeErrorLog(projectPath, result.errors);
313
+ clack.log.info('See .codegraph/errors.log for details');
314
+ }
315
+ if (result.filesIndexed > 0) {
316
+ clack.log.info('The index is fully usable — only the failed files are missing.');
317
+ }
318
+ }
319
+ else if (projectPath) {
320
+ const logPath = path.join(projectPath, '.codegraph', 'errors.log');
321
+ if (fs.existsSync(logPath)) {
322
+ fs.unlinkSync(logPath);
323
+ }
324
+ }
325
+ }
326
+ /**
327
+ * Write detailed error log to .codegraph/errors.log
328
+ */
329
+ function writeErrorLog(projectPath, errors) {
330
+ const cgDir = path.join(projectPath, '.codegraph');
331
+ if (!fs.existsSync(cgDir))
332
+ return;
333
+ const logPath = path.join(cgDir, 'errors.log');
334
+ // Group errors by file path
335
+ const errorsByFile = new Map();
336
+ const noFileErrors = [];
337
+ for (const err of errors) {
338
+ if (err.severity !== 'error')
339
+ continue;
340
+ if (err.filePath) {
341
+ let list = errorsByFile.get(err.filePath);
342
+ if (!list) {
343
+ list = [];
344
+ errorsByFile.set(err.filePath, list);
345
+ }
346
+ list.push({ message: err.message, code: err.code });
347
+ }
348
+ else {
349
+ noFileErrors.push({ message: err.message, code: err.code });
350
+ }
351
+ }
352
+ const lines = [
353
+ `CodeGraph Error Log — ${new Date().toISOString()}`,
354
+ `${errorsByFile.size} files with errors`,
355
+ '',
356
+ ];
357
+ for (const [filePath, fileErrors] of errorsByFile) {
358
+ for (const err of fileErrors) {
359
+ lines.push(`${filePath}: ${err.message}`);
360
+ }
361
+ }
362
+ for (const err of noFileErrors) {
363
+ lines.push(err.message);
364
+ }
365
+ fs.writeFileSync(logPath, lines.join('\n') + '\n');
366
+ }
367
+ // =============================================================================
368
+ // Commands
369
+ // =============================================================================
370
+ /**
371
+ * codegraph init [path]
372
+ */
373
+ program
374
+ .command('init [path]')
375
+ .description('Initialize CodeGraph in a project directory')
376
+ .option('-i, --index', 'Run initial indexing after initialization')
377
+ .option('-v, --verbose', 'Show detailed worker lifecycle and memory info')
378
+ .action(async (pathArg, options) => {
379
+ const projectPath = path.resolve(pathArg || process.cwd());
380
+ const clack = await importESM('@clack/prompts');
381
+ clack.intro('Initializing CodeGraph');
382
+ try {
383
+ if ((0, directory_1.isInitialized)(projectPath)) {
384
+ clack.log.warn(`Already initialized in ${projectPath}`);
385
+ clack.log.info('Use "codegraph index" to re-index or "codegraph sync" to update');
386
+ clack.outro('');
387
+ return;
388
+ }
389
+ const { default: CodeGraph } = await loadCodeGraph();
390
+ const cg = await CodeGraph.init(projectPath, { index: false });
391
+ clack.log.success(`Initialized in ${projectPath}`);
392
+ if (options.index) {
393
+ let result;
394
+ if (options.verbose) {
395
+ result = await cg.indexAll({
396
+ onProgress: createVerboseProgress(),
397
+ verbose: true,
398
+ });
399
+ }
400
+ else {
401
+ process.stdout.write(`${colors.dim}│${colors.reset}\n`);
402
+ const progress = (0, shimmer_progress_1.createShimmerProgress)();
403
+ result = await cg.indexAll({
404
+ onProgress: progress.onProgress,
405
+ });
406
+ await progress.stop();
407
+ }
408
+ printIndexResult(clack, result, projectPath);
409
+ }
410
+ else {
411
+ clack.log.info('Run "codegraph index" to index the project');
412
+ }
413
+ clack.outro('Done');
414
+ cg.destroy();
415
+ }
416
+ catch (err) {
417
+ clack.log.error(`Failed: ${err instanceof Error ? err.message : String(err)}`);
418
+ process.exit(1);
419
+ }
420
+ });
421
+ /**
422
+ * codegraph uninit [path]
423
+ */
424
+ program
425
+ .command('uninit [path]')
426
+ .description('Remove CodeGraph from a project (deletes .codegraph/ directory)')
427
+ .option('-f, --force', 'Skip confirmation prompt')
428
+ .action(async (pathArg, options) => {
429
+ const projectPath = resolveProjectPath(pathArg);
430
+ try {
431
+ if (!(0, directory_1.isInitialized)(projectPath)) {
432
+ warn(`CodeGraph is not initialized in ${projectPath}`);
433
+ return;
434
+ }
435
+ if (!options.force) {
436
+ // Confirm with user
437
+ const readline = await Promise.resolve().then(() => __importStar(require('readline')));
438
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
439
+ const answer = await new Promise((resolve) => {
440
+ rl.question(chalk.yellow('⚠ This will permanently delete all CodeGraph data. Continue? (y/N) '), resolve);
441
+ });
442
+ rl.close();
443
+ if (answer.toLowerCase() !== 'y') {
444
+ info('Cancelled');
445
+ return;
446
+ }
447
+ }
448
+ const { default: CodeGraph } = await loadCodeGraph();
449
+ const cg = CodeGraph.openSync(projectPath);
450
+ cg.uninitialize();
451
+ success(`Removed CodeGraph from ${projectPath}`);
452
+ }
453
+ catch (err) {
454
+ error(`Failed to uninitialize: ${err instanceof Error ? err.message : String(err)}`);
455
+ process.exit(1);
456
+ }
457
+ });
458
+ /**
459
+ * codegraph index [path]
460
+ */
461
+ program
462
+ .command('index [path]')
463
+ .description('Index all files in the project')
464
+ .option('-f, --force', 'Force full re-index even if already indexed')
465
+ .option('-q, --quiet', 'Suppress progress output')
466
+ .option('-v, --verbose', 'Show detailed worker lifecycle and memory info')
467
+ .action(async (pathArg, options) => {
468
+ const projectPath = resolveProjectPath(pathArg);
469
+ try {
470
+ if (!(0, directory_1.isInitialized)(projectPath)) {
471
+ error(`CodeGraph not initialized in ${projectPath}`);
472
+ info('Run "codegraph init" first');
473
+ process.exit(1);
474
+ }
475
+ const { default: CodeGraph } = await loadCodeGraph();
476
+ const cg = await CodeGraph.open(projectPath);
477
+ if (options.quiet) {
478
+ // Quiet mode: no UI, just run
479
+ if (options.force)
480
+ cg.clear();
481
+ const result = await cg.indexAll();
482
+ if (!result.success)
483
+ process.exit(1);
484
+ cg.destroy();
485
+ return;
486
+ }
487
+ const clack = await importESM('@clack/prompts');
488
+ clack.intro('Indexing project');
489
+ if (options.force) {
490
+ cg.clear();
491
+ clack.log.info('Cleared existing index');
492
+ }
493
+ let result;
494
+ if (options.verbose) {
495
+ result = await cg.indexAll({
496
+ onProgress: createVerboseProgress(),
497
+ verbose: true,
498
+ });
499
+ }
500
+ else {
501
+ process.stdout.write(`${colors.dim}│${colors.reset}\n`);
502
+ const progress = (0, shimmer_progress_1.createShimmerProgress)();
503
+ result = await cg.indexAll({
504
+ onProgress: progress.onProgress,
505
+ });
506
+ await progress.stop();
507
+ }
508
+ printIndexResult(clack, result, projectPath);
509
+ if (!result.success) {
510
+ process.exit(1);
511
+ }
512
+ clack.outro('Done');
513
+ cg.destroy();
514
+ }
515
+ catch (err) {
516
+ error(`Failed to index: ${err instanceof Error ? err.message : String(err)}`);
517
+ process.exit(1);
518
+ }
519
+ });
520
+ /**
521
+ * codegraph sync [path]
522
+ */
523
+ program
524
+ .command('sync [path]')
525
+ .description('Sync changes since last index')
526
+ .option('-q, --quiet', 'Suppress output (for git hooks)')
527
+ .action(async (pathArg, options) => {
528
+ const projectPath = resolveProjectPath(pathArg);
529
+ try {
530
+ if (!(0, directory_1.isInitialized)(projectPath)) {
531
+ if (!options.quiet) {
532
+ error(`CodeGraph not initialized in ${projectPath}`);
533
+ }
534
+ process.exit(1);
535
+ }
536
+ const { default: CodeGraph } = await loadCodeGraph();
537
+ const cg = await CodeGraph.open(projectPath);
538
+ if (options.quiet) {
539
+ await cg.sync();
540
+ cg.destroy();
541
+ return;
542
+ }
543
+ const clack = await importESM('@clack/prompts');
544
+ clack.intro('Syncing CodeGraph');
545
+ process.stdout.write(`${colors.dim}│${colors.reset}\n`);
546
+ const progress = (0, shimmer_progress_1.createShimmerProgress)();
547
+ const result = await cg.sync({
548
+ onProgress: progress.onProgress,
549
+ });
550
+ await progress.stop();
551
+ const totalChanges = result.filesAdded + result.filesModified + result.filesRemoved;
552
+ if (totalChanges === 0) {
553
+ clack.log.info('Already up to date');
554
+ }
555
+ else {
556
+ clack.log.success(`Synced ${formatNumber(totalChanges)} changed files`);
557
+ const details = [];
558
+ if (result.filesAdded > 0)
559
+ details.push(`Added: ${result.filesAdded}`);
560
+ if (result.filesModified > 0)
561
+ details.push(`Modified: ${result.filesModified}`);
562
+ if (result.filesRemoved > 0)
563
+ details.push(`Removed: ${result.filesRemoved}`);
564
+ clack.log.info(`${details.join(', ')} — ${formatNumber(result.nodesUpdated)} nodes in ${formatDuration(result.durationMs)}`);
565
+ }
566
+ clack.outro('Done');
567
+ cg.destroy();
568
+ }
569
+ catch (err) {
570
+ if (!options.quiet) {
571
+ error(`Failed to sync: ${err instanceof Error ? err.message : String(err)}`);
572
+ }
573
+ process.exit(1);
574
+ }
575
+ });
576
+ /**
577
+ * codegraph status [path]
578
+ */
579
+ program
580
+ .command('status [path]')
581
+ .description('Show index status and statistics')
582
+ .option('-j, --json', 'Output as JSON')
583
+ .action(async (pathArg, options) => {
584
+ const projectPath = resolveProjectPath(pathArg);
585
+ try {
586
+ if (!(0, directory_1.isInitialized)(projectPath)) {
587
+ if (options.json) {
588
+ console.log(JSON.stringify({ initialized: false, projectPath }));
589
+ return;
590
+ }
591
+ console.log(chalk.bold('\nCodeGraph Status\n'));
592
+ info(`Project: ${projectPath}`);
593
+ warn('Not initialized');
594
+ info('Run "codegraph init" to initialize');
595
+ return;
596
+ }
597
+ const { default: CodeGraph } = await loadCodeGraph();
598
+ const cg = await CodeGraph.open(projectPath);
599
+ const stats = cg.getStats();
600
+ const changes = cg.getChangedFiles();
601
+ const backend = cg.getBackend();
602
+ // JSON output mode
603
+ if (options.json) {
604
+ console.log(JSON.stringify({
605
+ initialized: true,
606
+ projectPath,
607
+ fileCount: stats.fileCount,
608
+ nodeCount: stats.nodeCount,
609
+ edgeCount: stats.edgeCount,
610
+ dbSizeBytes: stats.dbSizeBytes,
611
+ backend,
612
+ nodesByKind: stats.nodesByKind,
613
+ languages: Object.entries(stats.filesByLanguage).filter(([, count]) => count > 0).map(([lang]) => lang),
614
+ pendingChanges: {
615
+ added: changes.added.length,
616
+ modified: changes.modified.length,
617
+ removed: changes.removed.length,
618
+ },
619
+ }));
620
+ cg.destroy();
621
+ return;
622
+ }
623
+ console.log(chalk.bold('\nCodeGraph Status\n'));
624
+ // Project info
625
+ console.log(chalk.cyan('Project:'), projectPath);
626
+ console.log();
627
+ // Index stats
628
+ console.log(chalk.bold('Index Statistics:'));
629
+ console.log(` Files: ${formatNumber(stats.fileCount)}`);
630
+ console.log(` Nodes: ${formatNumber(stats.nodeCount)}`);
631
+ console.log(` Edges: ${formatNumber(stats.edgeCount)}`);
632
+ console.log(` DB Size: ${(stats.dbSizeBytes / 1024 / 1024).toFixed(2)} MB`);
633
+ // Surface the active SQLite backend so users can spot the silent
634
+ // WASM fallback (5-10x slower). better-sqlite3 is in
635
+ // `optionalDependencies`, so `npm install` succeeds without it
636
+ // when the native build fails.
637
+ const backendLabel = backend === 'native'
638
+ ? chalk.green('native')
639
+ : chalk.yellow('wasm — slower fallback; run `npm rebuild better-sqlite3`');
640
+ console.log(` Backend: ${backendLabel}`);
641
+ console.log();
642
+ // Node breakdown
643
+ console.log(chalk.bold('Nodes by Kind:'));
644
+ const nodesByKind = Object.entries(stats.nodesByKind)
645
+ .filter(([, count]) => count > 0)
646
+ .sort((a, b) => b[1] - a[1]);
647
+ for (const [kind, count] of nodesByKind) {
648
+ console.log(` ${kind.padEnd(15)} ${formatNumber(count)}`);
649
+ }
650
+ console.log();
651
+ // Language breakdown
652
+ console.log(chalk.bold('Files by Language:'));
653
+ const filesByLang = Object.entries(stats.filesByLanguage)
654
+ .filter(([, count]) => count > 0)
655
+ .sort((a, b) => b[1] - a[1]);
656
+ for (const [lang, count] of filesByLang) {
657
+ console.log(` ${lang.padEnd(15)} ${formatNumber(count)}`);
658
+ }
659
+ console.log();
660
+ // Pending changes
661
+ const totalChanges = changes.added.length + changes.modified.length + changes.removed.length;
662
+ if (totalChanges > 0) {
663
+ console.log(chalk.bold('Pending Changes:'));
664
+ if (changes.added.length > 0) {
665
+ console.log(` Added: ${changes.added.length} files`);
666
+ }
667
+ if (changes.modified.length > 0) {
668
+ console.log(` Modified: ${changes.modified.length} files`);
669
+ }
670
+ if (changes.removed.length > 0) {
671
+ console.log(` Removed: ${changes.removed.length} files`);
672
+ }
673
+ info('Run "codegraph sync" to update the index');
674
+ }
675
+ else {
676
+ success('Index is up to date');
677
+ }
678
+ console.log();
679
+ cg.destroy();
680
+ }
681
+ catch (err) {
682
+ error(`Failed to get status: ${err instanceof Error ? err.message : String(err)}`);
683
+ process.exit(1);
684
+ }
685
+ });
686
+ /**
687
+ * codegraph query <search>
688
+ */
689
+ program
690
+ .command('query <search>')
691
+ .description('Search for symbols in the codebase')
692
+ .option('-p, --path <path>', 'Project path')
693
+ .option('-l, --limit <number>', 'Maximum results', '10')
694
+ .option('-k, --kind <kind>', 'Filter by node kind (function, class, etc.)')
695
+ .option('-j, --json', 'Output as JSON')
696
+ .action(async (search, options) => {
697
+ const projectPath = resolveProjectPath(options.path);
698
+ try {
699
+ if (!(0, directory_1.isInitialized)(projectPath)) {
700
+ error(`CodeGraph not initialized in ${projectPath}`);
701
+ process.exit(1);
702
+ }
703
+ const { default: CodeGraph } = await loadCodeGraph();
704
+ const cg = await CodeGraph.open(projectPath);
705
+ const limit = parseInt(options.limit || '10', 10);
706
+ const results = cg.searchNodes(search, {
707
+ limit,
708
+ kinds: options.kind ? [options.kind] : undefined,
709
+ });
710
+ if (options.json) {
711
+ console.log(JSON.stringify(results, null, 2));
712
+ }
713
+ else {
714
+ if (results.length === 0) {
715
+ info(`No results found for "${search}"`);
716
+ }
717
+ else {
718
+ console.log(chalk.bold(`\nSearch Results for "${search}":\n`));
719
+ for (const result of results) {
720
+ const node = result.node;
721
+ const location = `${node.filePath}:${node.startLine}`;
722
+ const score = chalk.dim(`(${(result.score * 100).toFixed(0)}%)`);
723
+ console.log(chalk.cyan(node.kind.padEnd(12)) +
724
+ chalk.white(node.name) +
725
+ ' ' + score);
726
+ console.log(chalk.dim(` ${location}`));
727
+ if (node.signature) {
728
+ console.log(chalk.dim(` ${node.signature}`));
729
+ }
730
+ console.log();
731
+ }
732
+ }
733
+ }
734
+ cg.destroy();
735
+ }
736
+ catch (err) {
737
+ error(`Search failed: ${err instanceof Error ? err.message : String(err)}`);
738
+ process.exit(1);
739
+ }
740
+ });
741
+ /**
742
+ * codegraph files [path]
743
+ */
744
+ program
745
+ .command('files')
746
+ .description('Show project file structure from the index')
747
+ .option('-p, --path <path>', 'Project path')
748
+ .option('--filter <dir>', 'Filter to files under this directory')
749
+ .option('--pattern <glob>', 'Filter files matching this glob pattern')
750
+ .option('--format <format>', 'Output format (tree, flat, grouped)', 'tree')
751
+ .option('--max-depth <number>', 'Maximum directory depth for tree format')
752
+ .option('--no-metadata', 'Hide file metadata (language, symbol count)')
753
+ .option('-j, --json', 'Output as JSON')
754
+ .action(async (options) => {
755
+ const projectPath = resolveProjectPath(options.path);
756
+ try {
757
+ if (!(0, directory_1.isInitialized)(projectPath)) {
758
+ error(`CodeGraph not initialized in ${projectPath}`);
759
+ process.exit(1);
760
+ }
761
+ const { default: CodeGraph } = await loadCodeGraph();
762
+ const cg = await CodeGraph.open(projectPath);
763
+ let files = cg.getFiles();
764
+ if (files.length === 0) {
765
+ info('No files indexed. Run "codegraph index" first.');
766
+ cg.destroy();
767
+ return;
768
+ }
769
+ // Filter by path prefix
770
+ if (options.filter) {
771
+ const filter = options.filter;
772
+ files = files.filter(f => f.path.startsWith(filter) || f.path.startsWith('./' + filter));
773
+ }
774
+ // Filter by glob pattern
775
+ if (options.pattern) {
776
+ const regex = globToRegex(options.pattern);
777
+ files = files.filter(f => regex.test(f.path));
778
+ }
779
+ if (files.length === 0) {
780
+ info('No files found matching the criteria.');
781
+ cg.destroy();
782
+ return;
783
+ }
784
+ // JSON output
785
+ if (options.json) {
786
+ const output = files.map(f => ({
787
+ path: f.path,
788
+ language: f.language,
789
+ nodeCount: f.nodeCount,
790
+ size: f.size,
791
+ }));
792
+ console.log(JSON.stringify(output, null, 2));
793
+ cg.destroy();
794
+ return;
795
+ }
796
+ const includeMetadata = options.metadata !== false;
797
+ const format = options.format || 'tree';
798
+ const maxDepth = options.maxDepth ? parseInt(options.maxDepth, 10) : undefined;
799
+ // Format output
800
+ switch (format) {
801
+ case 'flat':
802
+ console.log(chalk.bold(`\nFiles (${files.length}):\n`));
803
+ for (const file of files.sort((a, b) => a.path.localeCompare(b.path))) {
804
+ if (includeMetadata) {
805
+ console.log(` ${file.path} ${chalk.dim(`(${file.language}, ${file.nodeCount} symbols)`)}`);
806
+ }
807
+ else {
808
+ console.log(` ${file.path}`);
809
+ }
810
+ }
811
+ break;
812
+ case 'grouped':
813
+ console.log(chalk.bold(`\nFiles by Language (${files.length} total):\n`));
814
+ const byLang = new Map();
815
+ for (const file of files) {
816
+ const existing = byLang.get(file.language) || [];
817
+ existing.push(file);
818
+ byLang.set(file.language, existing);
819
+ }
820
+ const sortedLangs = [...byLang.entries()].sort((a, b) => b[1].length - a[1].length);
821
+ for (const [lang, langFiles] of sortedLangs) {
822
+ console.log(chalk.cyan(`${lang} (${langFiles.length}):`));
823
+ for (const file of langFiles.sort((a, b) => a.path.localeCompare(b.path))) {
824
+ if (includeMetadata) {
825
+ console.log(` ${file.path} ${chalk.dim(`(${file.nodeCount} symbols)`)}`);
826
+ }
827
+ else {
828
+ console.log(` ${file.path}`);
829
+ }
830
+ }
831
+ console.log();
832
+ }
833
+ break;
834
+ case 'tree':
835
+ default:
836
+ console.log(chalk.bold(`\nProject Structure (${files.length} files):\n`));
837
+ printFileTree(files, includeMetadata, maxDepth, chalk);
838
+ break;
839
+ }
840
+ console.log();
841
+ cg.destroy();
842
+ }
843
+ catch (err) {
844
+ error(`Failed to list files: ${err instanceof Error ? err.message : String(err)}`);
845
+ process.exit(1);
846
+ }
847
+ });
848
+ /**
849
+ * Convert glob pattern to regex
850
+ */
851
+ function globToRegex(pattern) {
852
+ const escaped = pattern
853
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
854
+ .replace(/\*\*/g, '{{GLOBSTAR}}')
855
+ .replace(/\*/g, '[^/]*')
856
+ .replace(/\?/g, '[^/]')
857
+ .replace(/\{\{GLOBSTAR\}\}/g, '.*');
858
+ return new RegExp(escaped);
859
+ }
860
+ /**
861
+ * Print files as a tree
862
+ */
863
+ function printFileTree(files, includeMetadata, maxDepth, chalk) {
864
+ const root = { name: '', children: new Map() };
865
+ for (const file of files) {
866
+ const parts = file.path.split('/');
867
+ let current = root;
868
+ for (let i = 0; i < parts.length; i++) {
869
+ const part = parts[i];
870
+ if (!part)
871
+ continue;
872
+ if (!current.children.has(part)) {
873
+ current.children.set(part, { name: part, children: new Map() });
874
+ }
875
+ current = current.children.get(part);
876
+ if (i === parts.length - 1) {
877
+ current.file = { language: file.language, nodeCount: file.nodeCount };
878
+ }
879
+ }
880
+ }
881
+ const renderNode = (node, prefix, isLast, depth) => {
882
+ if (maxDepth !== undefined && depth > maxDepth)
883
+ return;
884
+ const connector = isLast ? '└── ' : '├── ';
885
+ const childPrefix = isLast ? ' ' : '│ ';
886
+ if (node.name) {
887
+ let line = prefix + connector + node.name;
888
+ if (node.file && includeMetadata) {
889
+ line += chalk.dim(` (${node.file.language}, ${node.file.nodeCount} symbols)`);
890
+ }
891
+ console.log(line);
892
+ }
893
+ const children = [...node.children.values()];
894
+ children.sort((a, b) => {
895
+ const aIsDir = a.children.size > 0 && !a.file;
896
+ const bIsDir = b.children.size > 0 && !b.file;
897
+ if (aIsDir !== bIsDir)
898
+ return aIsDir ? -1 : 1;
899
+ return a.name.localeCompare(b.name);
900
+ });
901
+ for (let i = 0; i < children.length; i++) {
902
+ const child = children[i];
903
+ const nextPrefix = node.name ? prefix + childPrefix : prefix;
904
+ renderNode(child, nextPrefix, i === children.length - 1, depth + 1);
905
+ }
906
+ };
907
+ renderNode(root, '', true, 0);
908
+ }
909
+ /**
910
+ * codegraph context <task>
911
+ */
912
+ program
913
+ .command('context <task>')
914
+ .description('Build context for a task (outputs markdown)')
915
+ .option('-p, --path <path>', 'Project path')
916
+ .option('-n, --max-nodes <number>', 'Maximum nodes to include', '50')
917
+ .option('-c, --max-code <number>', 'Maximum code blocks', '10')
918
+ .option('--no-code', 'Exclude code blocks')
919
+ .option('-f, --format <format>', 'Output format (markdown, json)', 'markdown')
920
+ .action(async (task, options) => {
921
+ const projectPath = resolveProjectPath(options.path);
922
+ try {
923
+ if (!(0, directory_1.isInitialized)(projectPath)) {
924
+ error(`CodeGraph not initialized in ${projectPath}`);
925
+ process.exit(1);
926
+ }
927
+ const { default: CodeGraph } = await loadCodeGraph();
928
+ const cg = await CodeGraph.open(projectPath);
929
+ const context = await cg.buildContext(task, {
930
+ maxNodes: parseInt(options.maxNodes || '50', 10),
931
+ maxCodeBlocks: parseInt(options.maxCode || '10', 10),
932
+ includeCode: options.code !== false,
933
+ format: options.format,
934
+ });
935
+ // Output the context
936
+ console.log(context);
937
+ cg.destroy();
938
+ }
939
+ catch (err) {
940
+ error(`Failed to build context: ${err instanceof Error ? err.message : String(err)}`);
941
+ process.exit(1);
942
+ }
943
+ });
944
+ /**
945
+ * codegraph serve
946
+ */
947
+ program
948
+ .command('serve')
949
+ .description('Start CodeGraph as an MCP server for AI assistants')
950
+ .option('-p, --path <path>', 'Project path (optional for MCP mode, uses rootUri from client)')
951
+ .option('--mcp', 'Run as MCP server (stdio transport)')
952
+ .action(async (options) => {
953
+ const projectPath = options.path ? resolveProjectPath(options.path) : undefined;
954
+ try {
955
+ if (options.mcp) {
956
+ // Start MCP server - it handles initialization lazily based on rootUri from client
957
+ const { MCPServer } = await Promise.resolve().then(() => __importStar(require('../mcp/index')));
958
+ const server = new MCPServer(projectPath);
959
+ await server.start();
960
+ // Server will run until terminated
961
+ }
962
+ else {
963
+ // Default: show info about MCP mode.
964
+ // Use stderr so stdout stays clean for any piped/stdio usage.
965
+ console.error(chalk.bold('\nCodeGraph MCP Server\n'));
966
+ console.error(chalk.blue('ℹ') + ' Use --mcp flag to start the MCP server');
967
+ console.error('\nTo use with Claude Code, add to your MCP configuration:');
968
+ console.error(chalk.dim(`
969
+ {
970
+ "mcpServers": {
971
+ "codegraph": {
972
+ "command": "codegraph",
973
+ "args": ["serve", "--mcp"]
974
+ }
975
+ }
976
+ }
977
+ `));
978
+ console.error('Available tools:');
979
+ console.error(chalk.cyan(' codegraph_search') + ' - Search for code symbols');
980
+ console.error(chalk.cyan(' codegraph_context') + ' - Build context for a task');
981
+ console.error(chalk.cyan(' codegraph_callers') + ' - Find callers of a symbol');
982
+ console.error(chalk.cyan(' codegraph_callees') + ' - Find what a symbol calls');
983
+ console.error(chalk.cyan(' codegraph_impact') + ' - Analyze impact of changes');
984
+ console.error(chalk.cyan(' codegraph_node') + ' - Get symbol details');
985
+ console.error(chalk.cyan(' codegraph_files') + ' - Get project file structure');
986
+ console.error(chalk.cyan(' codegraph_status') + ' - Get index status');
987
+ }
988
+ }
989
+ catch (err) {
990
+ error(`Failed to start server: ${err instanceof Error ? err.message : String(err)}`);
991
+ process.exit(1);
992
+ }
993
+ });
994
+ /**
995
+ * codegraph visualize [path]
996
+ */
997
+ program
998
+ .command('visualize [path]')
999
+ .description('Open interactive graph visualization in your browser')
1000
+ .option('-p, --port <port>', 'Port to listen on (default: auto)', parseInt)
1001
+ .option('--no-open', 'Do not open browser automatically')
1002
+ .action(async (pathArg, options) => {
1003
+ const projectPath = resolveProjectPath(pathArg);
1004
+ try {
1005
+ if (!(0, directory_1.isInitialized)(projectPath)) {
1006
+ error(`CodeGraph not initialized in ${projectPath}`);
1007
+ info('Run "codegraph init -i" first');
1008
+ process.exit(1);
1009
+ }
1010
+ const { default: CodeGraph } = await loadCodeGraph();
1011
+ const cg = await CodeGraph.open(projectPath);
1012
+ const stats = cg.getStats();
1013
+ console.log(chalk.bold('\n CodeGraph Explorer\n'));
1014
+ info(`Project: ${projectPath}`);
1015
+ info(`Indexed: ${formatNumber(stats.nodeCount)} nodes, ${formatNumber(stats.edgeCount)} edges, ${formatNumber(stats.fileCount)} files\n`);
1016
+ const { VisualizerServer } = await Promise.resolve().then(() => __importStar(require('../visualizer/server')));
1017
+ const server = new VisualizerServer(cg);
1018
+ const { url } = await server.start({ port: options.port, openBrowser: options.open !== false });
1019
+ success(`Visualizer running at ${chalk.cyan(url)}`);
1020
+ console.log(chalk.dim(' Press Ctrl+C to stop\n'));
1021
+ // Open browser
1022
+ if (options.open !== false) {
1023
+ const openCmd = process.platform === 'darwin' ? 'open' :
1024
+ process.platform === 'win32' ? 'start' : 'xdg-open';
1025
+ (0, child_process_1.spawn)(openCmd, [url], { detached: true, stdio: 'ignore' }).unref();
1026
+ }
1027
+ // Handle shutdown — force exit on second Ctrl+C
1028
+ let shuttingDown = false;
1029
+ const shutdown = () => {
1030
+ if (shuttingDown) {
1031
+ process.exit(1);
1032
+ }
1033
+ shuttingDown = true;
1034
+ console.log(chalk.dim('\n Shutting down...'));
1035
+ server.stop().then(() => {
1036
+ cg.close();
1037
+ process.exit(0);
1038
+ }).catch(() => process.exit(1));
1039
+ // Force exit after 2s if graceful shutdown hangs
1040
+ setTimeout(() => process.exit(1), 2000).unref();
1041
+ };
1042
+ process.on('SIGINT', shutdown);
1043
+ process.on('SIGTERM', shutdown);
1044
+ }
1045
+ catch (err) {
1046
+ error(`Failed to start visualizer: ${err instanceof Error ? err.message : String(err)}`);
1047
+ process.exit(1);
1048
+ }
1049
+ });
1050
+ /**
1051
+ * codegraph mark-dirty [path]
1052
+ *
1053
+ * Touches .codegraph/.dirty to signal that files have changed.
1054
+ * Used by Claude Code PostToolUse hooks to batch syncs.
1055
+ * Runs silently and always exits 0.
1056
+ */
1057
+ program
1058
+ .command('mark-dirty [path]')
1059
+ .description('Mark project as needing sync (used by Claude Code hooks)')
1060
+ .action(async (pathArg) => {
1061
+ try {
1062
+ const startPath = path.resolve(pathArg || process.cwd());
1063
+ const projectRoot = (0, directory_1.findNearestCodeGraphRoot)(startPath);
1064
+ if (!projectRoot) {
1065
+ // No .codegraph/ found — exit silently
1066
+ process.exit(0);
1067
+ }
1068
+ const dirtyPath = path.join((0, directory_1.getCodeGraphDir)(projectRoot), '.dirty');
1069
+ fs.writeFileSync(dirtyPath, Date.now().toString(), 'utf-8');
1070
+ }
1071
+ catch {
1072
+ // Never fail — this runs in the background during edits
1073
+ }
1074
+ process.exit(0);
1075
+ });
1076
+ /**
1077
+ * codegraph sync-if-dirty [path]
1078
+ *
1079
+ * Checks if .codegraph/.dirty exists and, if so, spawns a detached
1080
+ * background process to run `codegraph sync`. The hook process exits
1081
+ * immediately so Claude Code's Stop hook never blocks.
1082
+ *
1083
+ * Removes the marker BEFORE spawning so edits during sync
1084
+ * create a new marker for the next Stop event.
1085
+ * Runs silently and always exits 0.
1086
+ */
1087
+ program
1088
+ .command('sync-if-dirty [path]')
1089
+ .description('Sync if project was marked dirty (used by Claude Code hooks)')
1090
+ .action(async (pathArg) => {
1091
+ try {
1092
+ const startPath = path.resolve(pathArg || process.cwd());
1093
+ const projectRoot = (0, directory_1.findNearestCodeGraphRoot)(startPath);
1094
+ if (!projectRoot) {
1095
+ process.exit(0);
1096
+ }
1097
+ const dirtyPath = path.join((0, directory_1.getCodeGraphDir)(projectRoot), '.dirty');
1098
+ // No marker → nothing to do (sub-ms exit)
1099
+ if (!fs.existsSync(dirtyPath)) {
1100
+ process.exit(0);
1101
+ }
1102
+ // Remove marker FIRST so edits during sync create a new one
1103
+ try {
1104
+ fs.unlinkSync(dirtyPath);
1105
+ }
1106
+ catch { /* ignore */ }
1107
+ // If not fully initialized (no DB), exit
1108
+ if (!(0, directory_1.isInitialized)(projectRoot)) {
1109
+ process.exit(0);
1110
+ }
1111
+ // Spawn sync as a detached background process
1112
+ // so this hook exits immediately and doesn't block Claude Code.
1113
+ // Uses process.argv[0]/[1] (e.g. node /path/to/codegraph.js) so it
1114
+ // works whether invoked via global install, npx, or directly.
1115
+ const child = (0, child_process_1.spawn)(process.argv[0], [process.argv[1], 'sync', '--quiet', projectRoot], {
1116
+ detached: true,
1117
+ stdio: 'ignore',
1118
+ windowsHide: true,
1119
+ });
1120
+ child.unref();
1121
+ }
1122
+ catch {
1123
+ // Never fail — this runs at the end of Claude responses
1124
+ }
1125
+ process.exit(0);
1126
+ });
1127
+ /**
1128
+ * codegraph unlock [path]
1129
+ */
1130
+ program
1131
+ .command('unlock [path]')
1132
+ .description('Remove a stale lock file that is blocking indexing')
1133
+ .action(async (pathArg) => {
1134
+ const projectPath = resolveProjectPath(pathArg);
1135
+ try {
1136
+ if (!(0, directory_1.isInitialized)(projectPath)) {
1137
+ error(`CodeGraph not initialized in ${projectPath}`);
1138
+ return;
1139
+ }
1140
+ const lockPath = path.join((0, directory_1.getCodeGraphDir)(projectPath), 'codegraph.lock');
1141
+ if (!fs.existsSync(lockPath)) {
1142
+ info('No lock file found — nothing to do');
1143
+ return;
1144
+ }
1145
+ fs.unlinkSync(lockPath);
1146
+ success('Removed lock file. You can now run indexing again.');
1147
+ }
1148
+ catch (err) {
1149
+ error(`Failed to remove lock: ${err instanceof Error ? err.message : String(err)}`);
1150
+ process.exit(1);
1151
+ }
1152
+ });
1153
+ /**
1154
+ * codegraph affected [files...]
1155
+ *
1156
+ * Find test files affected by the given source files.
1157
+ * Traces dependency edges transitively to find test files that depend on changed code.
1158
+ *
1159
+ * Usage:
1160
+ * git diff --name-only | codegraph affected --stdin
1161
+ * codegraph affected src/lib/components/Editor.svelte src/routes/+page.svelte
1162
+ */
1163
+ program
1164
+ .command('affected [files...]')
1165
+ .description('Find test files affected by changed source files')
1166
+ .option('-p, --path <path>', 'Project path')
1167
+ .option('--stdin', 'Read file list from stdin (one per line)')
1168
+ .option('-d, --depth <number>', 'Max dependency traversal depth', '5')
1169
+ .option('-f, --filter <glob>', 'Custom glob filter for test files (e.g. "e2e/*.spec.ts")')
1170
+ .option('-j, --json', 'Output as JSON')
1171
+ .option('-q, --quiet', 'Only output file paths, no decoration')
1172
+ .action(async (fileArgs, options) => {
1173
+ const projectPath = resolveProjectPath(options.path);
1174
+ try {
1175
+ if (!(0, directory_1.isInitialized)(projectPath)) {
1176
+ error(`CodeGraph not initialized in ${projectPath}`);
1177
+ process.exit(1);
1178
+ }
1179
+ // Collect changed files from args or stdin
1180
+ let changedFiles = [...(fileArgs || [])];
1181
+ if (options.stdin) {
1182
+ const stdinData = fs.readFileSync(0, 'utf-8');
1183
+ const stdinFiles = stdinData.split('\n').map(f => f.trim()).filter(Boolean);
1184
+ changedFiles.push(...stdinFiles);
1185
+ }
1186
+ if (changedFiles.length === 0) {
1187
+ if (!options.quiet)
1188
+ info('No files provided. Use file arguments or --stdin.');
1189
+ process.exit(0);
1190
+ }
1191
+ const { default: CodeGraph } = await loadCodeGraph();
1192
+ const cg = await CodeGraph.open(projectPath);
1193
+ const maxDepth = parseInt(options.depth || '5', 10);
1194
+ // Common test file patterns
1195
+ const defaultTestPatterns = [
1196
+ /\.spec\./,
1197
+ /\.test\./,
1198
+ /\/__tests__\//,
1199
+ /\/tests?\//,
1200
+ /\/e2e\//,
1201
+ /\/spec\//,
1202
+ ];
1203
+ // Custom filter pattern
1204
+ let customFilter = null;
1205
+ if (options.filter) {
1206
+ // Convert glob to regex: ** → .+, * → [^/]*, . → \.
1207
+ const regex = options.filter
1208
+ .replace(/[+[\]{}()^$|\\]/g, '\\$&')
1209
+ .replace(/\./g, '\\.')
1210
+ .replace(/\*\*/g, '.+')
1211
+ .replace(/\*/g, '[^/]*');
1212
+ customFilter = new RegExp(regex);
1213
+ }
1214
+ function isTestFile(filePath) {
1215
+ if (customFilter)
1216
+ return customFilter.test(filePath);
1217
+ return defaultTestPatterns.some(p => p.test(filePath));
1218
+ }
1219
+ // BFS to find all transitive dependents of changed files, filtered to test files
1220
+ const affectedTests = new Set();
1221
+ const allDependents = new Set();
1222
+ for (const file of changedFiles) {
1223
+ // If the changed file is itself a test file, include it
1224
+ if (isTestFile(file)) {
1225
+ affectedTests.add(file);
1226
+ continue;
1227
+ }
1228
+ // BFS through dependents
1229
+ const queue = [{ file, depth: 0 }];
1230
+ const visited = new Set();
1231
+ visited.add(file);
1232
+ while (queue.length > 0) {
1233
+ const current = queue.shift();
1234
+ if (current.depth >= maxDepth)
1235
+ continue;
1236
+ const dependents = cg.getFileDependents(current.file);
1237
+ for (const dep of dependents) {
1238
+ if (visited.has(dep))
1239
+ continue;
1240
+ visited.add(dep);
1241
+ allDependents.add(dep);
1242
+ if (isTestFile(dep)) {
1243
+ affectedTests.add(dep);
1244
+ }
1245
+ else {
1246
+ queue.push({ file: dep, depth: current.depth + 1 });
1247
+ }
1248
+ }
1249
+ }
1250
+ }
1251
+ const sortedTests = Array.from(affectedTests).sort();
1252
+ // Output
1253
+ if (options.json) {
1254
+ console.log(JSON.stringify({
1255
+ changedFiles,
1256
+ affectedTests: sortedTests,
1257
+ totalDependentsTraversed: allDependents.size,
1258
+ }, null, 2));
1259
+ }
1260
+ else if (options.quiet) {
1261
+ for (const t of sortedTests)
1262
+ console.log(t);
1263
+ }
1264
+ else {
1265
+ if (sortedTests.length === 0) {
1266
+ info('No test files affected by the changed files.');
1267
+ }
1268
+ else {
1269
+ console.log(chalk.bold(`\nAffected test files (${sortedTests.length}):\n`));
1270
+ for (const t of sortedTests) {
1271
+ console.log(' ' + chalk.cyan(t));
1272
+ }
1273
+ console.log();
1274
+ }
1275
+ }
1276
+ cg.destroy();
1277
+ }
1278
+ catch (err) {
1279
+ error(`Affected analysis failed: ${err instanceof Error ? err.message : String(err)}`);
1280
+ process.exit(1);
1281
+ }
1282
+ });
1283
+ /**
1284
+ * codegraph install
1285
+ */
1286
+ program
1287
+ .command('install')
1288
+ .description('Run interactive installer for Claude Code integration')
1289
+ .action(async () => {
1290
+ const { runInstaller } = await Promise.resolve().then(() => __importStar(require('../installer')));
1291
+ await runInstaller();
1292
+ });
1293
+ // Parse and run
1294
+ program.parse();
1295
+ } // end main()
1296
+ //# sourceMappingURL=codegraph.js.map