@saluzi/codegraph 0.2.0 → 0.2.1

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 (657) hide show
  1. package/dist/bin/codegraph.d.ts +26 -0
  2. package/dist/bin/codegraph.d.ts.map +1 -0
  3. package/dist/bin/codegraph.js +2248 -0
  4. package/dist/bin/codegraph.js.map +1 -0
  5. package/dist/bin/command-supervision.d.ts +49 -0
  6. package/dist/bin/command-supervision.d.ts.map +1 -0
  7. package/dist/bin/command-supervision.js +95 -0
  8. package/dist/bin/command-supervision.js.map +1 -0
  9. package/dist/bin/fatal-handler.d.ts +20 -0
  10. package/dist/bin/fatal-handler.d.ts.map +1 -0
  11. package/dist/bin/fatal-handler.js +118 -0
  12. package/dist/bin/fatal-handler.js.map +1 -0
  13. package/dist/bin/node-version-check.d.ts +37 -0
  14. package/dist/bin/node-version-check.d.ts.map +1 -0
  15. package/dist/bin/node-version-check.js +79 -0
  16. package/dist/bin/node-version-check.js.map +1 -0
  17. package/dist/bin/uninstall.d.ts +14 -0
  18. package/dist/bin/uninstall.d.ts.map +1 -0
  19. package/dist/bin/uninstall.js +36 -0
  20. package/dist/bin/uninstall.js.map +1 -0
  21. package/dist/context/formatter.d.ts +30 -0
  22. package/dist/context/formatter.d.ts.map +1 -0
  23. package/dist/context/formatter.js +263 -0
  24. package/dist/context/formatter.js.map +1 -0
  25. package/dist/context/index.d.ts +119 -0
  26. package/dist/context/index.d.ts.map +1 -0
  27. package/dist/context/index.js +1296 -0
  28. package/dist/context/index.js.map +1 -0
  29. package/dist/context/markers.d.ts +19 -0
  30. package/dist/context/markers.d.ts.map +1 -0
  31. package/dist/context/markers.js +22 -0
  32. package/dist/context/markers.js.map +1 -0
  33. package/dist/db/index.d.ts +201 -0
  34. package/dist/db/index.d.ts.map +1 -0
  35. package/dist/db/index.js +493 -0
  36. package/dist/db/index.js.map +1 -0
  37. package/dist/db/migrations.d.ts +44 -0
  38. package/dist/db/migrations.d.ts.map +1 -0
  39. package/dist/db/migrations.js +212 -0
  40. package/dist/db/migrations.js.map +1 -0
  41. package/dist/db/queries.d.ts +513 -0
  42. package/dist/db/queries.d.ts.map +1 -0
  43. package/dist/db/queries.js +1886 -0
  44. package/dist/db/queries.js.map +1 -0
  45. package/dist/db/schema.sql +194 -0
  46. package/dist/db/sqlite-adapter.d.ts +53 -0
  47. package/dist/db/sqlite-adapter.d.ts.map +1 -0
  48. package/dist/db/sqlite-adapter.js +117 -0
  49. package/dist/db/sqlite-adapter.js.map +1 -0
  50. package/dist/db/wal-valve.d.ts +106 -0
  51. package/dist/db/wal-valve.d.ts.map +1 -0
  52. package/dist/db/wal-valve.js +208 -0
  53. package/dist/db/wal-valve.js.map +1 -0
  54. package/dist/directory.d.ts +183 -0
  55. package/dist/directory.d.ts.map +1 -0
  56. package/dist/directory.js +797 -0
  57. package/dist/directory.js.map +1 -0
  58. package/dist/errors.d.ts +136 -0
  59. package/dist/errors.d.ts.map +1 -0
  60. package/dist/errors.js +219 -0
  61. package/dist/errors.js.map +1 -0
  62. package/dist/extraction/astro-extractor.d.ts +79 -0
  63. package/dist/extraction/astro-extractor.d.ts.map +1 -0
  64. package/dist/extraction/astro-extractor.js +320 -0
  65. package/dist/extraction/astro-extractor.js.map +1 -0
  66. package/dist/extraction/cfml-extractor.d.ts +107 -0
  67. package/dist/extraction/cfml-extractor.d.ts.map +1 -0
  68. package/dist/extraction/cfml-extractor.js +494 -0
  69. package/dist/extraction/cfml-extractor.js.map +1 -0
  70. package/dist/extraction/dfm-extractor.d.ts +31 -0
  71. package/dist/extraction/dfm-extractor.d.ts.map +1 -0
  72. package/dist/extraction/dfm-extractor.js +151 -0
  73. package/dist/extraction/dfm-extractor.js.map +1 -0
  74. package/dist/extraction/extraction-version.d.ts +25 -0
  75. package/dist/extraction/extraction-version.d.ts.map +1 -0
  76. package/dist/extraction/extraction-version.js +28 -0
  77. package/dist/extraction/extraction-version.js.map +1 -0
  78. package/dist/extraction/function-ref.d.ts +118 -0
  79. package/dist/extraction/function-ref.d.ts.map +1 -0
  80. package/dist/extraction/function-ref.js +727 -0
  81. package/dist/extraction/function-ref.js.map +1 -0
  82. package/dist/extraction/generated-detection.d.ts +30 -0
  83. package/dist/extraction/generated-detection.d.ts.map +1 -0
  84. package/dist/extraction/generated-detection.js +83 -0
  85. package/dist/extraction/generated-detection.js.map +1 -0
  86. package/dist/extraction/grammars.d.ts +138 -0
  87. package/dist/extraction/grammars.d.ts.map +1 -0
  88. package/dist/extraction/grammars.js +631 -0
  89. package/dist/extraction/grammars.js.map +1 -0
  90. package/dist/extraction/index.d.ts +232 -0
  91. package/dist/extraction/index.d.ts.map +1 -0
  92. package/dist/extraction/index.js +2409 -0
  93. package/dist/extraction/index.js.map +1 -0
  94. package/dist/extraction/languages/arkts.d.ts +3 -0
  95. package/dist/extraction/languages/arkts.d.ts.map +1 -0
  96. package/dist/extraction/languages/arkts.js +127 -0
  97. package/dist/extraction/languages/arkts.js.map +1 -0
  98. package/dist/extraction/languages/c-cpp.d.ts +110 -0
  99. package/dist/extraction/languages/c-cpp.d.ts.map +1 -0
  100. package/dist/extraction/languages/c-cpp.js +837 -0
  101. package/dist/extraction/languages/c-cpp.js.map +1 -0
  102. package/dist/extraction/languages/cfquery.d.ts +12 -0
  103. package/dist/extraction/languages/cfquery.d.ts.map +1 -0
  104. package/dist/extraction/languages/cfquery.js +28 -0
  105. package/dist/extraction/languages/cfquery.js.map +1 -0
  106. package/dist/extraction/languages/cfscript.d.ts +3 -0
  107. package/dist/extraction/languages/cfscript.d.ts.map +1 -0
  108. package/dist/extraction/languages/cfscript.js +73 -0
  109. package/dist/extraction/languages/cfscript.js.map +1 -0
  110. package/dist/extraction/languages/cobol.d.ts +33 -0
  111. package/dist/extraction/languages/cobol.d.ts.map +1 -0
  112. package/dist/extraction/languages/cobol.js +499 -0
  113. package/dist/extraction/languages/cobol.js.map +1 -0
  114. package/dist/extraction/languages/csharp.d.ts +25 -0
  115. package/dist/extraction/languages/csharp.d.ts.map +1 -0
  116. package/dist/extraction/languages/csharp.js +175 -0
  117. package/dist/extraction/languages/csharp.js.map +1 -0
  118. package/dist/extraction/languages/dart.d.ts +3 -0
  119. package/dist/extraction/languages/dart.d.ts.map +1 -0
  120. package/dist/extraction/languages/dart.js +374 -0
  121. package/dist/extraction/languages/dart.js.map +1 -0
  122. package/dist/extraction/languages/erlang.d.ts +3 -0
  123. package/dist/extraction/languages/erlang.d.ts.map +1 -0
  124. package/dist/extraction/languages/erlang.js +350 -0
  125. package/dist/extraction/languages/erlang.js.map +1 -0
  126. package/dist/extraction/languages/go.d.ts +3 -0
  127. package/dist/extraction/languages/go.d.ts.map +1 -0
  128. package/dist/extraction/languages/go.js +111 -0
  129. package/dist/extraction/languages/go.js.map +1 -0
  130. package/dist/extraction/languages/index.d.ts +10 -0
  131. package/dist/extraction/languages/index.d.ts.map +1 -0
  132. package/dist/extraction/languages/index.js +71 -0
  133. package/dist/extraction/languages/index.js.map +1 -0
  134. package/dist/extraction/languages/java.d.ts +3 -0
  135. package/dist/extraction/languages/java.d.ts.map +1 -0
  136. package/dist/extraction/languages/java.js +315 -0
  137. package/dist/extraction/languages/java.js.map +1 -0
  138. package/dist/extraction/languages/javascript.d.ts +3 -0
  139. package/dist/extraction/languages/javascript.d.ts.map +1 -0
  140. package/dist/extraction/languages/javascript.js +106 -0
  141. package/dist/extraction/languages/javascript.js.map +1 -0
  142. package/dist/extraction/languages/kotlin.d.ts +3 -0
  143. package/dist/extraction/languages/kotlin.d.ts.map +1 -0
  144. package/dist/extraction/languages/kotlin.js +379 -0
  145. package/dist/extraction/languages/kotlin.js.map +1 -0
  146. package/dist/extraction/languages/lua.d.ts +3 -0
  147. package/dist/extraction/languages/lua.d.ts.map +1 -0
  148. package/dist/extraction/languages/lua.js +150 -0
  149. package/dist/extraction/languages/lua.js.map +1 -0
  150. package/dist/extraction/languages/luau.d.ts +3 -0
  151. package/dist/extraction/languages/luau.d.ts.map +1 -0
  152. package/dist/extraction/languages/luau.js +37 -0
  153. package/dist/extraction/languages/luau.js.map +1 -0
  154. package/dist/extraction/languages/nix.d.ts +3 -0
  155. package/dist/extraction/languages/nix.d.ts.map +1 -0
  156. package/dist/extraction/languages/nix.js +294 -0
  157. package/dist/extraction/languages/nix.js.map +1 -0
  158. package/dist/extraction/languages/objc.d.ts +3 -0
  159. package/dist/extraction/languages/objc.d.ts.map +1 -0
  160. package/dist/extraction/languages/objc.js +175 -0
  161. package/dist/extraction/languages/objc.js.map +1 -0
  162. package/dist/extraction/languages/pascal.d.ts +3 -0
  163. package/dist/extraction/languages/pascal.d.ts.map +1 -0
  164. package/dist/extraction/languages/pascal.js +77 -0
  165. package/dist/extraction/languages/pascal.js.map +1 -0
  166. package/dist/extraction/languages/php.d.ts +3 -0
  167. package/dist/extraction/languages/php.d.ts.map +1 -0
  168. package/dist/extraction/languages/php.js +196 -0
  169. package/dist/extraction/languages/php.js.map +1 -0
  170. package/dist/extraction/languages/python.d.ts +3 -0
  171. package/dist/extraction/languages/python.d.ts.map +1 -0
  172. package/dist/extraction/languages/python.js +56 -0
  173. package/dist/extraction/languages/python.js.map +1 -0
  174. package/dist/extraction/languages/r.d.ts +3 -0
  175. package/dist/extraction/languages/r.d.ts.map +1 -0
  176. package/dist/extraction/languages/r.js +314 -0
  177. package/dist/extraction/languages/r.js.map +1 -0
  178. package/dist/extraction/languages/ruby.d.ts +3 -0
  179. package/dist/extraction/languages/ruby.d.ts.map +1 -0
  180. package/dist/extraction/languages/ruby.js +149 -0
  181. package/dist/extraction/languages/ruby.js.map +1 -0
  182. package/dist/extraction/languages/rust.d.ts +3 -0
  183. package/dist/extraction/languages/rust.d.ts.map +1 -0
  184. package/dist/extraction/languages/rust.js +142 -0
  185. package/dist/extraction/languages/rust.js.map +1 -0
  186. package/dist/extraction/languages/scala.d.ts +3 -0
  187. package/dist/extraction/languages/scala.d.ts.map +1 -0
  188. package/dist/extraction/languages/scala.js +209 -0
  189. package/dist/extraction/languages/scala.js.map +1 -0
  190. package/dist/extraction/languages/solidity.d.ts +3 -0
  191. package/dist/extraction/languages/solidity.d.ts.map +1 -0
  192. package/dist/extraction/languages/solidity.js +293 -0
  193. package/dist/extraction/languages/solidity.js.map +1 -0
  194. package/dist/extraction/languages/swift.d.ts +3 -0
  195. package/dist/extraction/languages/swift.d.ts.map +1 -0
  196. package/dist/extraction/languages/swift.js +152 -0
  197. package/dist/extraction/languages/swift.js.map +1 -0
  198. package/dist/extraction/languages/terraform.d.ts +3 -0
  199. package/dist/extraction/languages/terraform.d.ts.map +1 -0
  200. package/dist/extraction/languages/terraform.js +641 -0
  201. package/dist/extraction/languages/terraform.js.map +1 -0
  202. package/dist/extraction/languages/typescript.d.ts +16 -0
  203. package/dist/extraction/languages/typescript.d.ts.map +1 -0
  204. package/dist/extraction/languages/typescript.js +167 -0
  205. package/dist/extraction/languages/typescript.js.map +1 -0
  206. package/dist/extraction/languages/vbnet.d.ts +11 -0
  207. package/dist/extraction/languages/vbnet.d.ts.map +1 -0
  208. package/dist/extraction/languages/vbnet.js +141 -0
  209. package/dist/extraction/languages/vbnet.js.map +1 -0
  210. package/dist/extraction/liquid-extractor.d.ts +59 -0
  211. package/dist/extraction/liquid-extractor.d.ts.map +1 -0
  212. package/dist/extraction/liquid-extractor.js +357 -0
  213. package/dist/extraction/liquid-extractor.js.map +1 -0
  214. package/dist/extraction/mybatis-extractor.d.ts +68 -0
  215. package/dist/extraction/mybatis-extractor.d.ts.map +1 -0
  216. package/dist/extraction/mybatis-extractor.js +300 -0
  217. package/dist/extraction/mybatis-extractor.js.map +1 -0
  218. package/dist/extraction/parse-pool.d.ts +152 -0
  219. package/dist/extraction/parse-pool.d.ts.map +1 -0
  220. package/dist/extraction/parse-pool.js +387 -0
  221. package/dist/extraction/parse-pool.js.map +1 -0
  222. package/dist/extraction/parse-worker.d.ts +8 -0
  223. package/dist/extraction/parse-worker.d.ts.map +1 -0
  224. package/dist/extraction/parse-worker.js +104 -0
  225. package/dist/extraction/parse-worker.js.map +1 -0
  226. package/dist/extraction/razor-extractor.d.ts +42 -0
  227. package/dist/extraction/razor-extractor.d.ts.map +1 -0
  228. package/dist/extraction/razor-extractor.js +285 -0
  229. package/dist/extraction/razor-extractor.js.map +1 -0
  230. package/dist/extraction/svelte-extractor.d.ts +56 -0
  231. package/dist/extraction/svelte-extractor.d.ts.map +1 -0
  232. package/dist/extraction/svelte-extractor.js +275 -0
  233. package/dist/extraction/svelte-extractor.js.map +1 -0
  234. package/dist/extraction/tree-sitter-helpers.d.ts +28 -0
  235. package/dist/extraction/tree-sitter-helpers.d.ts.map +1 -0
  236. package/dist/extraction/tree-sitter-helpers.js +153 -0
  237. package/dist/extraction/tree-sitter-helpers.js.map +1 -0
  238. package/dist/extraction/tree-sitter-types.d.ts +258 -0
  239. package/dist/extraction/tree-sitter-types.d.ts.map +1 -0
  240. package/dist/extraction/tree-sitter-types.js +10 -0
  241. package/dist/extraction/tree-sitter-types.js.map +1 -0
  242. package/dist/extraction/tree-sitter.d.ts +706 -0
  243. package/dist/extraction/tree-sitter.d.ts.map +1 -0
  244. package/dist/extraction/tree-sitter.js +6506 -0
  245. package/dist/extraction/tree-sitter.js.map +1 -0
  246. package/dist/extraction/vue-extractor.d.ts +51 -0
  247. package/dist/extraction/vue-extractor.d.ts.map +1 -0
  248. package/dist/extraction/vue-extractor.js +254 -0
  249. package/dist/extraction/vue-extractor.js.map +1 -0
  250. package/dist/extraction/wasm/tree-sitter-arkts.wasm +0 -0
  251. package/dist/extraction/wasm/tree-sitter-c_sharp.wasm +0 -0
  252. package/dist/extraction/wasm/tree-sitter-cfml.wasm +0 -0
  253. package/dist/extraction/wasm/tree-sitter-cfquery.wasm +0 -0
  254. package/dist/extraction/wasm/tree-sitter-cfscript.wasm +0 -0
  255. package/dist/extraction/wasm/tree-sitter-cobol.wasm +0 -0
  256. package/dist/extraction/wasm/tree-sitter-erlang.wasm +0 -0
  257. package/dist/extraction/wasm/tree-sitter-lua.wasm +0 -0
  258. package/dist/extraction/wasm/tree-sitter-luau.wasm +0 -0
  259. package/dist/extraction/wasm/tree-sitter-nix.wasm +0 -0
  260. package/dist/extraction/wasm/tree-sitter-pascal.wasm +0 -0
  261. package/dist/extraction/wasm/tree-sitter-r.wasm +0 -0
  262. package/dist/extraction/wasm/tree-sitter-scala.wasm +0 -0
  263. package/dist/extraction/wasm/tree-sitter-terraform.wasm +0 -0
  264. package/dist/extraction/wasm/tree-sitter-vbnet.wasm +0 -0
  265. package/dist/extraction/wasm-runtime-flags.d.ts +38 -0
  266. package/dist/extraction/wasm-runtime-flags.d.ts.map +1 -0
  267. package/dist/extraction/wasm-runtime-flags.js +106 -0
  268. package/dist/extraction/wasm-runtime-flags.js.map +1 -0
  269. package/dist/graph/index.d.ts +8 -0
  270. package/dist/graph/index.d.ts.map +1 -0
  271. package/dist/graph/index.js +13 -0
  272. package/dist/graph/index.js.map +1 -0
  273. package/dist/graph/queries.d.ts +106 -0
  274. package/dist/graph/queries.d.ts.map +1 -0
  275. package/dist/graph/queries.js +339 -0
  276. package/dist/graph/queries.js.map +1 -0
  277. package/dist/graph/traversal.d.ts +127 -0
  278. package/dist/graph/traversal.d.ts.map +1 -0
  279. package/dist/graph/traversal.js +599 -0
  280. package/dist/graph/traversal.js.map +1 -0
  281. package/dist/index.d.ts +643 -0
  282. package/dist/index.d.ts.map +1 -0
  283. package/dist/index.js +1491 -0
  284. package/dist/index.js.map +1 -0
  285. package/dist/installer/config-writer.d.ts +28 -0
  286. package/dist/installer/config-writer.d.ts.map +1 -0
  287. package/dist/installer/config-writer.js +91 -0
  288. package/dist/installer/config-writer.js.map +1 -0
  289. package/dist/installer/index.d.ts +142 -0
  290. package/dist/installer/index.d.ts.map +1 -0
  291. package/dist/installer/index.js +619 -0
  292. package/dist/installer/index.js.map +1 -0
  293. package/dist/installer/instructions-template.d.ts +41 -0
  294. package/dist/installer/instructions-template.d.ts.map +1 -0
  295. package/dist/installer/instructions-template.js +53 -0
  296. package/dist/installer/instructions-template.js.map +1 -0
  297. package/dist/installer/targets/antigravity.d.ts +57 -0
  298. package/dist/installer/targets/antigravity.d.ts.map +1 -0
  299. package/dist/installer/targets/antigravity.js +308 -0
  300. package/dist/installer/targets/antigravity.js.map +1 -0
  301. package/dist/installer/targets/claude.d.ts +62 -0
  302. package/dist/installer/targets/claude.d.ts.map +1 -0
  303. package/dist/installer/targets/claude.js +454 -0
  304. package/dist/installer/targets/claude.js.map +1 -0
  305. package/dist/installer/targets/codex.d.ts +18 -0
  306. package/dist/installer/targets/codex.d.ts.map +1 -0
  307. package/dist/installer/targets/codex.js +185 -0
  308. package/dist/installer/targets/codex.js.map +1 -0
  309. package/dist/installer/targets/cursor.d.ts +35 -0
  310. package/dist/installer/targets/cursor.d.ts.map +1 -0
  311. package/dist/installer/targets/cursor.js +254 -0
  312. package/dist/installer/targets/cursor.js.map +1 -0
  313. package/dist/installer/targets/gemini.d.ts +26 -0
  314. package/dist/installer/targets/gemini.d.ts.map +1 -0
  315. package/dist/installer/targets/gemini.js +165 -0
  316. package/dist/installer/targets/gemini.js.map +1 -0
  317. package/dist/installer/targets/hermes.d.ts +18 -0
  318. package/dist/installer/targets/hermes.d.ts.map +1 -0
  319. package/dist/installer/targets/hermes.js +359 -0
  320. package/dist/installer/targets/hermes.js.map +1 -0
  321. package/dist/installer/targets/kiro.d.ts +27 -0
  322. package/dist/installer/targets/kiro.d.ts.map +1 -0
  323. package/dist/installer/targets/kiro.js +178 -0
  324. package/dist/installer/targets/kiro.js.map +1 -0
  325. package/dist/installer/targets/opencode.d.ts +38 -0
  326. package/dist/installer/targets/opencode.d.ts.map +1 -0
  327. package/dist/installer/targets/opencode.js +288 -0
  328. package/dist/installer/targets/opencode.js.map +1 -0
  329. package/dist/installer/targets/registry.d.ts +35 -0
  330. package/dist/installer/targets/registry.d.ts.map +1 -0
  331. package/dist/installer/targets/registry.js +91 -0
  332. package/dist/installer/targets/registry.js.map +1 -0
  333. package/dist/installer/targets/shared.d.ts +101 -0
  334. package/dist/installer/targets/shared.d.ts.map +1 -0
  335. package/dist/installer/targets/shared.js +264 -0
  336. package/dist/installer/targets/shared.js.map +1 -0
  337. package/dist/installer/targets/toml.d.ts +52 -0
  338. package/dist/installer/targets/toml.d.ts.map +1 -0
  339. package/dist/installer/targets/toml.js +147 -0
  340. package/dist/installer/targets/toml.js.map +1 -0
  341. package/dist/installer/targets/types.d.ts +108 -0
  342. package/dist/installer/targets/types.d.ts.map +1 -0
  343. package/dist/installer/targets/types.js +16 -0
  344. package/dist/installer/targets/types.js.map +1 -0
  345. package/dist/mcp/daemon-manager.d.ts +42 -0
  346. package/dist/mcp/daemon-manager.d.ts.map +1 -0
  347. package/dist/mcp/daemon-manager.js +129 -0
  348. package/dist/mcp/daemon-manager.js.map +1 -0
  349. package/dist/mcp/daemon-paths.d.ts +73 -0
  350. package/dist/mcp/daemon-paths.d.ts.map +1 -0
  351. package/dist/mcp/daemon-paths.js +165 -0
  352. package/dist/mcp/daemon-paths.js.map +1 -0
  353. package/dist/mcp/daemon-registry.d.ts +47 -0
  354. package/dist/mcp/daemon-registry.d.ts.map +1 -0
  355. package/dist/mcp/daemon-registry.js +233 -0
  356. package/dist/mcp/daemon-registry.js.map +1 -0
  357. package/dist/mcp/daemon.d.ts +290 -0
  358. package/dist/mcp/daemon.d.ts.map +1 -0
  359. package/dist/mcp/daemon.js +862 -0
  360. package/dist/mcp/daemon.js.map +1 -0
  361. package/dist/mcp/dynamic-boundaries.d.ts +41 -0
  362. package/dist/mcp/dynamic-boundaries.d.ts.map +1 -0
  363. package/dist/mcp/dynamic-boundaries.js +360 -0
  364. package/dist/mcp/dynamic-boundaries.js.map +1 -0
  365. package/dist/mcp/early-ppid.d.ts +26 -0
  366. package/dist/mcp/early-ppid.d.ts.map +1 -0
  367. package/dist/mcp/early-ppid.js +29 -0
  368. package/dist/mcp/early-ppid.js.map +1 -0
  369. package/dist/mcp/engine.d.ts +122 -0
  370. package/dist/mcp/engine.d.ts.map +1 -0
  371. package/dist/mcp/engine.js +350 -0
  372. package/dist/mcp/engine.js.map +1 -0
  373. package/dist/mcp/index.d.ts +113 -0
  374. package/dist/mcp/index.d.ts.map +1 -0
  375. package/dist/mcp/index.js +506 -0
  376. package/dist/mcp/index.js.map +1 -0
  377. package/dist/mcp/liveness-watchdog.d.ts +35 -0
  378. package/dist/mcp/liveness-watchdog.d.ts.map +1 -0
  379. package/dist/mcp/liveness-watchdog.js +267 -0
  380. package/dist/mcp/liveness-watchdog.js.map +1 -0
  381. package/dist/mcp/ppid-watchdog.d.ts +62 -0
  382. package/dist/mcp/ppid-watchdog.d.ts.map +1 -0
  383. package/dist/mcp/ppid-watchdog.js +64 -0
  384. package/dist/mcp/ppid-watchdog.js.map +1 -0
  385. package/dist/mcp/proxy.d.ts +87 -0
  386. package/dist/mcp/proxy.d.ts.map +1 -0
  387. package/dist/mcp/proxy.js +667 -0
  388. package/dist/mcp/proxy.js.map +1 -0
  389. package/dist/mcp/query-pool.d.ts +108 -0
  390. package/dist/mcp/query-pool.d.ts.map +1 -0
  391. package/dist/mcp/query-pool.js +315 -0
  392. package/dist/mcp/query-pool.js.map +1 -0
  393. package/dist/mcp/query-worker.d.ts +24 -0
  394. package/dist/mcp/query-worker.d.ts.map +1 -0
  395. package/dist/mcp/query-worker.js +87 -0
  396. package/dist/mcp/query-worker.js.map +1 -0
  397. package/dist/mcp/server-instructions.d.ts +34 -0
  398. package/dist/mcp/server-instructions.d.ts.map +1 -0
  399. package/dist/mcp/server-instructions.js +106 -0
  400. package/dist/mcp/server-instructions.js.map +1 -0
  401. package/dist/mcp/session.d.ts +93 -0
  402. package/dist/mcp/session.d.ts.map +1 -0
  403. package/dist/mcp/session.js +357 -0
  404. package/dist/mcp/session.js.map +1 -0
  405. package/dist/mcp/startup-handshake.d.ts +44 -0
  406. package/dist/mcp/startup-handshake.d.ts.map +1 -0
  407. package/dist/mcp/startup-handshake.js +73 -0
  408. package/dist/mcp/startup-handshake.js.map +1 -0
  409. package/dist/mcp/stdin-teardown.d.ts +27 -0
  410. package/dist/mcp/stdin-teardown.d.ts.map +1 -0
  411. package/dist/mcp/stdin-teardown.js +49 -0
  412. package/dist/mcp/stdin-teardown.js.map +1 -0
  413. package/dist/mcp/tools.d.ts +613 -0
  414. package/dist/mcp/tools.d.ts.map +1 -0
  415. package/dist/mcp/tools.js +4477 -0
  416. package/dist/mcp/tools.js.map +1 -0
  417. package/dist/mcp/transport.d.ts +188 -0
  418. package/dist/mcp/transport.d.ts.map +1 -0
  419. package/dist/mcp/transport.js +377 -0
  420. package/dist/mcp/transport.js.map +1 -0
  421. package/dist/mcp/version.d.ts +19 -0
  422. package/dist/mcp/version.d.ts.map +1 -0
  423. package/dist/mcp/version.js +71 -0
  424. package/dist/mcp/version.js.map +1 -0
  425. package/dist/project-config.d.ts +94 -0
  426. package/dist/project-config.d.ts.map +1 -0
  427. package/dist/project-config.js +374 -0
  428. package/dist/project-config.js.map +1 -0
  429. package/dist/resolution/c-fnptr-synthesizer.d.ts +6 -0
  430. package/dist/resolution/c-fnptr-synthesizer.d.ts.map +1 -0
  431. package/dist/resolution/c-fnptr-synthesizer.js +1062 -0
  432. package/dist/resolution/c-fnptr-synthesizer.js.map +1 -0
  433. package/dist/resolution/callback-synthesizer.d.ts +15 -0
  434. package/dist/resolution/callback-synthesizer.d.ts.map +1 -0
  435. package/dist/resolution/callback-synthesizer.js +3938 -0
  436. package/dist/resolution/callback-synthesizer.js.map +1 -0
  437. package/dist/resolution/cooperative-yield.d.ts +32 -0
  438. package/dist/resolution/cooperative-yield.d.ts.map +1 -0
  439. package/dist/resolution/cooperative-yield.js +42 -0
  440. package/dist/resolution/cooperative-yield.js.map +1 -0
  441. package/dist/resolution/frameworks/astro.d.ts +9 -0
  442. package/dist/resolution/frameworks/astro.d.ts.map +1 -0
  443. package/dist/resolution/frameworks/astro.js +169 -0
  444. package/dist/resolution/frameworks/astro.js.map +1 -0
  445. package/dist/resolution/frameworks/cargo-workspace.d.ts +18 -0
  446. package/dist/resolution/frameworks/cargo-workspace.d.ts.map +1 -0
  447. package/dist/resolution/frameworks/cargo-workspace.js +225 -0
  448. package/dist/resolution/frameworks/cargo-workspace.js.map +1 -0
  449. package/dist/resolution/frameworks/cics.d.ts +20 -0
  450. package/dist/resolution/frameworks/cics.d.ts.map +1 -0
  451. package/dist/resolution/frameworks/cics.js +90 -0
  452. package/dist/resolution/frameworks/cics.js.map +1 -0
  453. package/dist/resolution/frameworks/csharp.d.ts +8 -0
  454. package/dist/resolution/frameworks/csharp.d.ts.map +1 -0
  455. package/dist/resolution/frameworks/csharp.js +241 -0
  456. package/dist/resolution/frameworks/csharp.js.map +1 -0
  457. package/dist/resolution/frameworks/drupal.d.ts +51 -0
  458. package/dist/resolution/frameworks/drupal.d.ts.map +1 -0
  459. package/dist/resolution/frameworks/drupal.js +367 -0
  460. package/dist/resolution/frameworks/drupal.js.map +1 -0
  461. package/dist/resolution/frameworks/expo-modules.d.ts +3 -0
  462. package/dist/resolution/frameworks/expo-modules.d.ts.map +1 -0
  463. package/dist/resolution/frameworks/expo-modules.js +148 -0
  464. package/dist/resolution/frameworks/expo-modules.js.map +1 -0
  465. package/dist/resolution/frameworks/express.d.ts +8 -0
  466. package/dist/resolution/frameworks/express.d.ts.map +1 -0
  467. package/dist/resolution/frameworks/express.js +308 -0
  468. package/dist/resolution/frameworks/express.js.map +1 -0
  469. package/dist/resolution/frameworks/fabric.d.ts +3 -0
  470. package/dist/resolution/frameworks/fabric.d.ts.map +1 -0
  471. package/dist/resolution/frameworks/fabric.js +354 -0
  472. package/dist/resolution/frameworks/fabric.js.map +1 -0
  473. package/dist/resolution/frameworks/go.d.ts +8 -0
  474. package/dist/resolution/frameworks/go.d.ts.map +1 -0
  475. package/dist/resolution/frameworks/go.js +161 -0
  476. package/dist/resolution/frameworks/go.js.map +1 -0
  477. package/dist/resolution/frameworks/goframe.d.ts +41 -0
  478. package/dist/resolution/frameworks/goframe.d.ts.map +1 -0
  479. package/dist/resolution/frameworks/goframe.js +112 -0
  480. package/dist/resolution/frameworks/goframe.js.map +1 -0
  481. package/dist/resolution/frameworks/index.d.ts +50 -0
  482. package/dist/resolution/frameworks/index.d.ts.map +1 -0
  483. package/dist/resolution/frameworks/index.js +175 -0
  484. package/dist/resolution/frameworks/index.js.map +1 -0
  485. package/dist/resolution/frameworks/java.d.ts +8 -0
  486. package/dist/resolution/frameworks/java.d.ts.map +1 -0
  487. package/dist/resolution/frameworks/java.js +517 -0
  488. package/dist/resolution/frameworks/java.js.map +1 -0
  489. package/dist/resolution/frameworks/laravel.d.ts +13 -0
  490. package/dist/resolution/frameworks/laravel.d.ts.map +1 -0
  491. package/dist/resolution/frameworks/laravel.js +257 -0
  492. package/dist/resolution/frameworks/laravel.js.map +1 -0
  493. package/dist/resolution/frameworks/nestjs.d.ts +26 -0
  494. package/dist/resolution/frameworks/nestjs.d.ts.map +1 -0
  495. package/dist/resolution/frameworks/nestjs.js +698 -0
  496. package/dist/resolution/frameworks/nestjs.js.map +1 -0
  497. package/dist/resolution/frameworks/play.d.ts +19 -0
  498. package/dist/resolution/frameworks/play.d.ts.map +1 -0
  499. package/dist/resolution/frameworks/play.js +111 -0
  500. package/dist/resolution/frameworks/play.js.map +1 -0
  501. package/dist/resolution/frameworks/python.d.ts +10 -0
  502. package/dist/resolution/frameworks/python.d.ts.map +1 -0
  503. package/dist/resolution/frameworks/python.js +400 -0
  504. package/dist/resolution/frameworks/python.js.map +1 -0
  505. package/dist/resolution/frameworks/react-native.d.ts +3 -0
  506. package/dist/resolution/frameworks/react-native.d.ts.map +1 -0
  507. package/dist/resolution/frameworks/react-native.js +410 -0
  508. package/dist/resolution/frameworks/react-native.js.map +1 -0
  509. package/dist/resolution/frameworks/react.d.ts +8 -0
  510. package/dist/resolution/frameworks/react.d.ts.map +1 -0
  511. package/dist/resolution/frameworks/react.js +334 -0
  512. package/dist/resolution/frameworks/react.js.map +1 -0
  513. package/dist/resolution/frameworks/ruby.d.ts +8 -0
  514. package/dist/resolution/frameworks/ruby.d.ts.map +1 -0
  515. package/dist/resolution/frameworks/ruby.js +302 -0
  516. package/dist/resolution/frameworks/ruby.js.map +1 -0
  517. package/dist/resolution/frameworks/rust.d.ts +8 -0
  518. package/dist/resolution/frameworks/rust.d.ts.map +1 -0
  519. package/dist/resolution/frameworks/rust.js +304 -0
  520. package/dist/resolution/frameworks/rust.js.map +1 -0
  521. package/dist/resolution/frameworks/svelte.d.ts +9 -0
  522. package/dist/resolution/frameworks/svelte.d.ts.map +1 -0
  523. package/dist/resolution/frameworks/svelte.js +253 -0
  524. package/dist/resolution/frameworks/svelte.js.map +1 -0
  525. package/dist/resolution/frameworks/swift-objc.d.ts +37 -0
  526. package/dist/resolution/frameworks/swift-objc.d.ts.map +1 -0
  527. package/dist/resolution/frameworks/swift-objc.js +252 -0
  528. package/dist/resolution/frameworks/swift-objc.js.map +1 -0
  529. package/dist/resolution/frameworks/swift.d.ts +10 -0
  530. package/dist/resolution/frameworks/swift.d.ts.map +1 -0
  531. package/dist/resolution/frameworks/swift.js +400 -0
  532. package/dist/resolution/frameworks/swift.js.map +1 -0
  533. package/dist/resolution/frameworks/terraform.d.ts +38 -0
  534. package/dist/resolution/frameworks/terraform.d.ts.map +1 -0
  535. package/dist/resolution/frameworks/terraform.js +277 -0
  536. package/dist/resolution/frameworks/terraform.js.map +1 -0
  537. package/dist/resolution/frameworks/vue.d.ts +9 -0
  538. package/dist/resolution/frameworks/vue.d.ts.map +1 -0
  539. package/dist/resolution/frameworks/vue.js +303 -0
  540. package/dist/resolution/frameworks/vue.js.map +1 -0
  541. package/dist/resolution/go-module.d.ts +26 -0
  542. package/dist/resolution/go-module.d.ts.map +1 -0
  543. package/dist/resolution/go-module.js +78 -0
  544. package/dist/resolution/go-module.js.map +1 -0
  545. package/dist/resolution/goframe-synthesizer.d.ts +29 -0
  546. package/dist/resolution/goframe-synthesizer.d.ts.map +1 -0
  547. package/dist/resolution/goframe-synthesizer.js +163 -0
  548. package/dist/resolution/goframe-synthesizer.js.map +1 -0
  549. package/dist/resolution/import-resolver.d.ts +85 -0
  550. package/dist/resolution/import-resolver.d.ts.map +1 -0
  551. package/dist/resolution/import-resolver.js +1974 -0
  552. package/dist/resolution/import-resolver.js.map +1 -0
  553. package/dist/resolution/index.d.ts +258 -0
  554. package/dist/resolution/index.d.ts.map +1 -0
  555. package/dist/resolution/index.js +1746 -0
  556. package/dist/resolution/index.js.map +1 -0
  557. package/dist/resolution/lru-cache.d.ts +24 -0
  558. package/dist/resolution/lru-cache.d.ts.map +1 -0
  559. package/dist/resolution/lru-cache.js +62 -0
  560. package/dist/resolution/lru-cache.js.map +1 -0
  561. package/dist/resolution/name-matcher.d.ts +112 -0
  562. package/dist/resolution/name-matcher.d.ts.map +1 -0
  563. package/dist/resolution/name-matcher.js +1830 -0
  564. package/dist/resolution/name-matcher.js.map +1 -0
  565. package/dist/resolution/path-aliases.d.ts +68 -0
  566. package/dist/resolution/path-aliases.d.ts.map +1 -0
  567. package/dist/resolution/path-aliases.js +238 -0
  568. package/dist/resolution/path-aliases.js.map +1 -0
  569. package/dist/resolution/strip-comments.d.ts +27 -0
  570. package/dist/resolution/strip-comments.d.ts.map +1 -0
  571. package/dist/resolution/strip-comments.js +492 -0
  572. package/dist/resolution/strip-comments.js.map +1 -0
  573. package/dist/resolution/swift-objc-bridge.d.ts +134 -0
  574. package/dist/resolution/swift-objc-bridge.d.ts.map +1 -0
  575. package/dist/resolution/swift-objc-bridge.js +256 -0
  576. package/dist/resolution/swift-objc-bridge.js.map +1 -0
  577. package/dist/resolution/types.d.ts +262 -0
  578. package/dist/resolution/types.d.ts.map +1 -0
  579. package/dist/resolution/types.js +8 -0
  580. package/dist/resolution/types.js.map +1 -0
  581. package/dist/resolution/workspace-packages.d.ts +58 -0
  582. package/dist/resolution/workspace-packages.d.ts.map +1 -0
  583. package/dist/resolution/workspace-packages.js +346 -0
  584. package/dist/resolution/workspace-packages.js.map +1 -0
  585. package/dist/search/identifier-segments.d.ts +60 -0
  586. package/dist/search/identifier-segments.d.ts.map +1 -0
  587. package/dist/search/identifier-segments.js +176 -0
  588. package/dist/search/identifier-segments.js.map +1 -0
  589. package/dist/search/query-parser.d.ts +57 -0
  590. package/dist/search/query-parser.d.ts.map +1 -0
  591. package/dist/search/query-parser.js +177 -0
  592. package/dist/search/query-parser.js.map +1 -0
  593. package/dist/search/query-utils.d.ts +87 -0
  594. package/dist/search/query-utils.d.ts.map +1 -0
  595. package/dist/search/query-utils.js +449 -0
  596. package/dist/search/query-utils.js.map +1 -0
  597. package/dist/sync/git-hooks.d.ts +45 -0
  598. package/dist/sync/git-hooks.d.ts.map +1 -0
  599. package/dist/sync/git-hooks.js +227 -0
  600. package/dist/sync/git-hooks.js.map +1 -0
  601. package/dist/sync/index.d.ts +19 -0
  602. package/dist/sync/index.d.ts.map +1 -0
  603. package/dist/sync/index.js +35 -0
  604. package/dist/sync/index.js.map +1 -0
  605. package/dist/sync/watch-policy.d.ts +48 -0
  606. package/dist/sync/watch-policy.d.ts.map +1 -0
  607. package/dist/sync/watch-policy.js +124 -0
  608. package/dist/sync/watch-policy.js.map +1 -0
  609. package/dist/sync/watcher.d.ts +355 -0
  610. package/dist/sync/watcher.d.ts.map +1 -0
  611. package/dist/sync/watcher.js +848 -0
  612. package/dist/sync/watcher.js.map +1 -0
  613. package/dist/sync/worktree.d.ts +63 -0
  614. package/dist/sync/worktree.d.ts.map +1 -0
  615. package/dist/sync/worktree.js +182 -0
  616. package/dist/sync/worktree.js.map +1 -0
  617. package/dist/telemetry/index.d.ts +143 -0
  618. package/dist/telemetry/index.d.ts.map +1 -0
  619. package/dist/telemetry/index.js +541 -0
  620. package/dist/telemetry/index.js.map +1 -0
  621. package/dist/types.d.ts +415 -0
  622. package/dist/types.d.ts.map +1 -0
  623. package/dist/types.js +91 -0
  624. package/dist/types.js.map +1 -0
  625. package/dist/ui/glyphs.d.ts +42 -0
  626. package/dist/ui/glyphs.d.ts.map +1 -0
  627. package/dist/ui/glyphs.js +78 -0
  628. package/dist/ui/glyphs.js.map +1 -0
  629. package/dist/ui/shimmer-progress.d.ts +11 -0
  630. package/dist/ui/shimmer-progress.d.ts.map +1 -0
  631. package/dist/ui/shimmer-progress.js +90 -0
  632. package/dist/ui/shimmer-progress.js.map +1 -0
  633. package/dist/ui/shimmer-worker.d.ts +2 -0
  634. package/dist/ui/shimmer-worker.d.ts.map +1 -0
  635. package/dist/ui/shimmer-worker.js +118 -0
  636. package/dist/ui/shimmer-worker.js.map +1 -0
  637. package/dist/ui/types.d.ts +17 -0
  638. package/dist/ui/types.d.ts.map +1 -0
  639. package/dist/ui/types.js +3 -0
  640. package/dist/ui/types.js.map +1 -0
  641. package/dist/upgrade/index.d.ts +164 -0
  642. package/dist/upgrade/index.d.ts.map +1 -0
  643. package/dist/upgrade/index.js +646 -0
  644. package/dist/upgrade/index.js.map +1 -0
  645. package/dist/upgrade/remove-binary.d.ts +87 -0
  646. package/dist/upgrade/remove-binary.d.ts.map +1 -0
  647. package/dist/upgrade/remove-binary.js +289 -0
  648. package/dist/upgrade/remove-binary.js.map +1 -0
  649. package/dist/upgrade/update-check.d.ts +92 -0
  650. package/dist/upgrade/update-check.d.ts.map +1 -0
  651. package/dist/upgrade/update-check.js +258 -0
  652. package/dist/upgrade/update-check.js.map +1 -0
  653. package/dist/utils.d.ts +224 -0
  654. package/dist/utils.d.ts.map +1 -0
  655. package/dist/utils.js +583 -0
  656. package/dist/utils.js.map +1 -0
  657. package/package.json +1 -1
@@ -0,0 +1,2409 @@
1
+ "use strict";
2
+ /**
3
+ * Extraction Orchestrator
4
+ *
5
+ * Coordinates file scanning, parsing, and database storage.
6
+ */
7
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
+ if (k2 === undefined) k2 = k;
9
+ var desc = Object.getOwnPropertyDescriptor(m, k);
10
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
+ desc = { enumerable: true, get: function() { return m[k]; } };
12
+ }
13
+ Object.defineProperty(o, k2, desc);
14
+ }) : (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ o[k2] = m[k];
17
+ }));
18
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
20
+ }) : function(o, v) {
21
+ o["default"] = v;
22
+ });
23
+ var __importStar = (this && this.__importStar) || (function () {
24
+ var ownKeys = function(o) {
25
+ ownKeys = Object.getOwnPropertyNames || function (o) {
26
+ var ar = [];
27
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
28
+ return ar;
29
+ };
30
+ return ownKeys(o);
31
+ };
32
+ return function (mod) {
33
+ if (mod && mod.__esModule) return mod;
34
+ var result = {};
35
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
36
+ __setModuleDefault(result, mod);
37
+ return result;
38
+ };
39
+ })();
40
+ var __importDefault = (this && this.__importDefault) || function (mod) {
41
+ return (mod && mod.__esModule) ? mod : { "default": mod };
42
+ };
43
+ Object.defineProperty(exports, "__esModule", { value: true });
44
+ exports.loadAllGrammars = exports.loadGrammarsForLanguages = exports.initGrammars = exports.getSupportedLanguages = exports.isGrammarLoaded = exports.isLanguageSupported = exports.isSourceFile = exports.detectLanguage = exports.extractFromSource = exports.ExtractionOrchestrator = exports.ScopeIgnore = void 0;
45
+ exports.hashContent = hashContent;
46
+ exports.buildDefaultIgnore = buildDefaultIgnore;
47
+ exports.buildScopeIgnore = buildScopeIgnore;
48
+ exports.discoverEmbeddedRepoRoots = discoverEmbeddedRepoRoots;
49
+ exports.findUnindexedIgnoredRepos = findUnindexedIgnoredRepos;
50
+ exports.scanDirectory = scanDirectory;
51
+ exports.scanDirectoryAsync = scanDirectoryAsync;
52
+ const fs = __importStar(require("fs"));
53
+ const fsp = __importStar(require("fs/promises"));
54
+ const path = __importStar(require("path"));
55
+ const os = __importStar(require("os"));
56
+ const crypto = __importStar(require("crypto"));
57
+ const child_process_1 = require("child_process");
58
+ const tree_sitter_1 = require("./tree-sitter");
59
+ const parse_pool_1 = require("./parse-pool");
60
+ const grammars_1 = require("./grammars");
61
+ const project_config_1 = require("../project-config");
62
+ const directory_1 = require("../directory");
63
+ const errors_1 = require("../errors");
64
+ const utils_1 = require("../utils");
65
+ const ignore_1 = __importDefault(require("ignore"));
66
+ const frameworks_1 = require("../resolution/frameworks");
67
+ const cooperative_yield_1 = require("../resolution/cooperative-yield");
68
+ /**
69
+ * Number of files to read in parallel during indexing.
70
+ * File reads are I/O-bound; batching overlaps I/O wait with CPU parse work.
71
+ */
72
+ const FILE_IO_BATCH_SIZE = 10;
73
+ /**
74
+ * How many files the `sync()` reconcile processes between cooperative yields to
75
+ * the event loop. The reconcile runs two O(files) loops of synchronous `fs`
76
+ * calls (existsSync for removals, statSync for adds/mods); on a very large repo
77
+ * (~100k files) an un-yielded run wedges the main thread for minutes, which both
78
+ * trips the liveness watchdog (it SIGKILLs a process whose loop stops turning)
79
+ * and blocks the first MCP tool call behind the catch-up gate (issue #905).
80
+ * Yielding every N files keeps the socket, the watchdog heartbeat, and any
81
+ * concurrent read query responsive while the reconcile runs.
82
+ */
83
+ const SYNC_RECONCILE_YIELD_INTERVAL = 1000;
84
+ // PARSER_RESET_INTERVAL moved to parse-worker.ts (runs in worker thread)
85
+ /**
86
+ * Maximum time (ms) to wait for a single file to parse in the worker thread.
87
+ * If tree-sitter hangs or WASM runs out of memory, this prevents the entire
88
+ * indexing run from freezing. The worker is restarted after a (hard) timeout.
89
+ * Env-overridable via CODEGRAPH_PARSE_TIMEOUT_MS for slow storage (#1231).
90
+ */
91
+ const PARSE_TIMEOUT_MS = (0, parse_pool_1.resolveParseTimeoutMs)(process.env.CODEGRAPH_PARSE_TIMEOUT_MS);
92
+ /**
93
+ * Number of files to parse before recycling the worker thread.
94
+ * WASM linear memory can grow but NEVER shrink (WebAssembly spec limitation).
95
+ * The only way to reclaim tree-sitter's WASM heap is to destroy the entire
96
+ * V8 isolate by terminating the worker thread and spawning a fresh one.
97
+ * This interval balances memory usage against the cost of reloading grammars.
98
+ */
99
+ const WORKER_RECYCLE_INTERVAL = 250;
100
+ /**
101
+ * Calculate SHA256 hash of file contents
102
+ */
103
+ function hashContent(content) {
104
+ return crypto.createHash('sha256').update(content).digest('hex');
105
+ }
106
+ /**
107
+ * Skip files larger than this (bytes). Generated bundles, minified JS, and
108
+ * vendored blobs blow the WASM heap and the worker-recycle budget for no useful
109
+ * symbols. 1 MB covers essentially all hand-written source.
110
+ */
111
+ const MAX_FILE_SIZE = 1024 * 1024;
112
+ /**
113
+ * Directory names that are dependency, build, cache, or tooling output across the
114
+ * languages/frameworks CodeGraph supports — curated from the canonical
115
+ * github/gitignore templates. Excluded by default so the graph reflects your code,
116
+ * not third-party noise, without requiring a `.gitignore` (issue #407). The
117
+ * exclusion applies uniformly (git or not, tracked or not); the only opt-in is an
118
+ * explicit `.gitignore` negation (e.g. `!vendor/`). First-party-prone or generic
119
+ * names (`packages`, `lib`, `app`, `bin`, `src`, `deps`, `env`, `tmp`, `storage`,
120
+ * `Library`) are deliberately NOT listed, to avoid ever hiding real source.
121
+ *
122
+ * Only dirs that actually contain *indexable source* (or are enormous) earn a slot
123
+ * — IDE/state dirs like `.idea`/`.vs` are omitted because CodeGraph indexes only
124
+ * recognized source extensions, so they produce no symbols regardless.
125
+ */
126
+ const DEFAULT_IGNORE_DIRS = new Set([
127
+ // JS / TS — dependency directories
128
+ 'node_modules', 'bower_components', 'jspm_packages', 'web_modules',
129
+ '.yarn', '.pnpm-store',
130
+ // JS / TS — framework & bundler build / cache / deploy output
131
+ '.next', '.nuxt', '.svelte-kit', '.turbo', '.vite', '.parcel-cache', '.angular',
132
+ '.docusaurus', 'storybook-static', '.vinxi', '.nitro', 'out-tsc',
133
+ '.vercel', '.netlify', '.wrangler',
134
+ // Build output (common across ecosystems)
135
+ 'dist', 'build', 'out', '.output',
136
+ // Test / coverage
137
+ 'coverage', '.nyc_output',
138
+ // Python
139
+ '__pycache__', '__pypackages__', '.venv', 'venv', '.pixi', '.pdm-build',
140
+ '.mypy_cache', '.pytest_cache', '.ruff_cache', '.tox', '.nox', '.hypothesis',
141
+ '.ipynb_checkpoints', '.eggs',
142
+ // Rust / JVM (Maven, Gradle, Scala)
143
+ 'target', '.gradle',
144
+ // .NET
145
+ 'obj',
146
+ // Vendored deps (Go, PHP/Composer, Ruby/Bundler)
147
+ 'vendor',
148
+ // Swift / iOS
149
+ '.build', 'Pods', 'Carthage', 'DerivedData', '.swiftpm',
150
+ // Dart / Flutter
151
+ '.dart_tool', '.pub-cache',
152
+ // Native (Android NDK, C/C++ deps)
153
+ '.cxx', '.externalNativeBuild', 'vcpkg_installed',
154
+ // Scala tooling
155
+ '.bloop', '.metals',
156
+ // Lua / Luau (LuaRocks)
157
+ 'lua_modules', '.luarocks',
158
+ // Delphi / RAD Studio IDE backups (duplicate .pas source — would double-count)
159
+ '__history', '__recovery',
160
+ // Generic cache
161
+ '.cache',
162
+ ]);
163
+ /**
164
+ * Android resource directory types. A `res/` tree holds ONLY non-code resources —
165
+ * layouts, drawables, value bags (strings/colors/styles), menus, navigation
166
+ * graphs — split into one typed subdirectory per kind, optionally density/locale/
167
+ * version-qualified (`values-es`, `drawable-hdpi`, `layout-v21`, …). None of it
168
+ * yields an extractable code symbol, yet on an Android app it DOMINATES the tree
169
+ * (one report: 26k XML files = 97% of the project, 0 symbols), bloating the DB,
170
+ * slowing indexing, and skewing both the file count and `codegraph_explore`
171
+ * results (#1047). So these are excluded by default. The structure is
172
+ * self-identifying — a non-Android project has no `res/layout/` etc., so it's
173
+ * untouched — and the only XML that DOES produce symbols (MyBatis mappers) lives
174
+ * under `src/main/resources/`, never `res/`, so nothing useful is dropped.
175
+ * `res/raw/` is deliberately NOT here: it holds arbitrary bundled assets that can
176
+ * be code-ish (a `.sql` schema, a `.js`), so we leave it indexed. Override any of
177
+ * these with a `.gitignore` negation (e.g. `!res/values/`).
178
+ */
179
+ const ANDROID_RES_TYPES = [
180
+ 'anim', 'animator', 'color', 'drawable', 'font', 'layout',
181
+ 'menu', 'mipmap', 'navigation', 'transition', 'values', 'xml',
182
+ ];
183
+ /** Gitignore-style patterns for the `ignore` matcher: the dirs above plus a few globs. */
184
+ const DEFAULT_IGNORE_PATTERNS = [
185
+ ...Array.from(DEFAULT_IGNORE_DIRS, (d) => `${d}/`),
186
+ '*.egg-info/', // Python packaging metadata
187
+ 'cmake-build-*/', // CLion / CMake build trees
188
+ 'bazel-*/', // Bazel output symlink trees
189
+ // Android resource dirs at any depth, with their qualifier variants (#1047).
190
+ ...ANDROID_RES_TYPES.map((t) => `**/res/${t}*/`),
191
+ ];
192
+ /** True if `buf` decodes as strict UTF-8 (no invalid byte sequences). */
193
+ function isValidUtf8(buf) {
194
+ try {
195
+ new TextDecoder('utf-8', { fatal: true }).decode(buf);
196
+ return true;
197
+ }
198
+ catch {
199
+ return false;
200
+ }
201
+ }
202
+ /**
203
+ * Read a `.gitignore` and return patterns safe to hand to the `ignore` matcher —
204
+ * never throwing, even when the file isn't real gitignore text. Two failure
205
+ * modes, both seen in the wild (issue #682):
206
+ *
207
+ * - The file isn't valid UTF-8 — e.g. transparently encrypted in place by
208
+ * corporate DLP / endpoint-security software, leaving a UTF-16 header plus
209
+ * ciphertext. None of it is meaningful patterns, so the whole file is skipped.
210
+ * - The file is text but a single line can't be compiled to a regex by the
211
+ * `ignore` library — `\\[` and friends throw "Unterminated character class".
212
+ * Crucially the throw is LAZY (at match time, not `.add()`), so it would
213
+ * otherwise escape mid-scan. That one pattern is dropped; the rest are kept.
214
+ *
215
+ * Either way a warning that NAMES the file is logged (the reporter couldn't tell
216
+ * which `.gitignore` was at fault) and indexing continues instead of aborting.
217
+ * Returns '' when there's nothing usable.
218
+ */
219
+ function readGitignorePatterns(giPath) {
220
+ let buf;
221
+ try {
222
+ buf = fs.readFileSync(giPath);
223
+ }
224
+ catch {
225
+ return ''; // unreadable (permissions / race) — treat as absent
226
+ }
227
+ // A NUL byte never appears in real gitignore text, and a fatal UTF-8 decode
228
+ // catches the rest. Such a file isn't ignore patterns at all.
229
+ if (buf.includes(0) || !isValidUtf8(buf)) {
230
+ (0, errors_1.logWarn)('Ignoring a .gitignore that is not valid UTF-8 text — it may have been encrypted ' +
231
+ 'in place by endpoint-security software. Indexing continues without it.', { file: giPath });
232
+ return '';
233
+ }
234
+ const content = buf.toString('utf-8');
235
+ // Fast path: one `.ignores()` call forces the library to compile EVERY rule,
236
+ // so if it doesn't throw, the whole file is safe to use verbatim.
237
+ try {
238
+ (0, ignore_1.default)().add(content).ignores('.codegraph-probe');
239
+ return content;
240
+ }
241
+ catch {
242
+ // Fall through: a line is uncompilable — keep the good ones, drop the bad.
243
+ }
244
+ const kept = [];
245
+ let dropped = 0;
246
+ for (const line of content.split(/\r?\n/)) {
247
+ try {
248
+ (0, ignore_1.default)().add(line).ignores('.codegraph-probe');
249
+ kept.push(line);
250
+ }
251
+ catch {
252
+ dropped++;
253
+ }
254
+ }
255
+ if (dropped > 0) {
256
+ (0, errors_1.logWarn)(`Skipped ${dropped} unparseable pattern(s) in a .gitignore; the rest are applied.`, { file: giPath });
257
+ }
258
+ return kept.join('\n');
259
+ }
260
+ /**
261
+ * An `ignore` matcher seeded with the built-in defaults, merged with the project's
262
+ * root .gitignore so a negation there (e.g. `!vendor/`) overrides a default. Shared
263
+ * by both enumeration paths so behavior is identical with or without git — and so
264
+ * the defaults apply to tracked files too (committing a dependency dir doesn't make
265
+ * it project code; the explicit `.gitignore` negation is the only opt-in).
266
+ */
267
+ function buildDefaultIgnore(rootDir) {
268
+ const ig = (0, ignore_1.default)().add(DEFAULT_IGNORE_PATTERNS);
269
+ const rootGitignore = path.join(rootDir, '.gitignore');
270
+ if (fs.existsSync(rootGitignore))
271
+ ig.add(readGitignorePatterns(rootGitignore));
272
+ return ig;
273
+ }
274
+ /**
275
+ * Defaults-only ignore matcher (no root `.gitignore` merged). Used wherever the
276
+ * parent repo's own ignore rules must NOT apply — inside embedded child repos,
277
+ * whose gitignore semantics their own `git ls-files` already enforced (#514).
278
+ */
279
+ function defaultsOnlyIgnore() {
280
+ return (0, ignore_1.default)().add(DEFAULT_IGNORE_PATTERNS);
281
+ }
282
+ /**
283
+ * Matcher for the project's `codegraph.json` `includeIgnored` patterns — the
284
+ * explicit opt-in to index embedded git repos living inside gitignored
285
+ * directories (#622, #699). Returns `null` when the project opted in nothing,
286
+ * which is the zero-config DEFAULT: `.gitignore` is then fully respected and a
287
+ * gitignored directory (even one holding nested repos) is never walked or
288
+ * indexed (#970, #976). Built once per scan/sync/scope operation from the scan
289
+ * root and threaded down — never global, so multi-project daemons stay isolated.
290
+ */
291
+ function loadIncludeIgnoredMatcher(rootDir) {
292
+ const patterns = (0, project_config_1.loadIncludeIgnoredPatterns)(rootDir);
293
+ return patterns.length > 0 ? (0, ignore_1.default)().add(patterns) : null;
294
+ }
295
+ /**
296
+ * Matcher for the project's `codegraph.json` `exclude` patterns — paths to keep
297
+ * OUT of the index even when git-tracked, which `.gitignore` cannot do (#999).
298
+ * The escape hatch for a committed vendor/theme/SDK directory. Returns `null`
299
+ * when nothing is excluded (the zero-config default → no overhead). Matched
300
+ * against project-root-relative paths, so it applies uniformly across the whole
301
+ * workspace, including inside embedded repos (excluding `static/` means gone
302
+ * everywhere). Built once per scan/sync/scope operation from the scan root.
303
+ */
304
+ function loadExcludeMatcher(rootDir) {
305
+ const patterns = (0, project_config_1.loadExcludePatterns)(rootDir);
306
+ return patterns.length > 0 ? (0, ignore_1.default)().add(patterns) : null;
307
+ }
308
+ /**
309
+ * Matcher for the project's `codegraph.json` `include` patterns — first-party
310
+ * source to force INTO the index even when `.gitignore` drops it (the general
311
+ * whitelist `includeIgnored` never was — that one only revives *embedded git
312
+ * repos*). The case it exists for: a project under a second VCS (SVN/Perforce)
313
+ * `.gitignore`s its own real source so it stays out of Git, yet we still want it
314
+ * indexed. Returns `null` when nothing is force-included (the zero-config
315
+ * default → no overhead, no extra walk). Built once per scan/sync/scope
316
+ * operation from the scan root.
317
+ */
318
+ function loadIncludeMatcher(rootDir) {
319
+ const patterns = (0, project_config_1.loadIncludePatterns)(rootDir);
320
+ return patterns.length > 0 ? (0, ignore_1.default)().add(patterns) : null;
321
+ }
322
+ /** Glob metacharacters that end the static (literal) prefix of an `include` pattern. */
323
+ const GLOB_META = /[*?[\]{}!]/;
324
+ /**
325
+ * The static directory prefix of each `include` pattern — the literal leading
326
+ * path up to the first glob segment — trailing-slashed, used to (a) walk only
327
+ * the opted-in subtrees in `collectIncludedFiles` and (b) let `ScopeIgnore` keep
328
+ * the watcher descending toward them. `Tools/` stays `Tools/`; a recursive
329
+ * `Tools/**` glob yields `Tools/`; `src/local/file.ts` yields `src/local/` (the
330
+ * file's dir); a pattern that starts with a glob (like a leading `**`) yields
331
+ * `''`, meaning "no static root — walk the whole tree". Duplicates and roots
332
+ * nested under a broader root are collapsed so each subtree is walked once.
333
+ */
334
+ function includeStaticRoots(patterns) {
335
+ const roots = new Set();
336
+ for (const pattern of patterns) {
337
+ let p = pattern.replace(/^\/+/, '');
338
+ const trailingSlash = p.endsWith('/');
339
+ if (trailingSlash)
340
+ p = p.slice(0, -1);
341
+ const segs = p.split('/').filter(Boolean);
342
+ const lead = [];
343
+ for (const s of segs) {
344
+ if (GLOB_META.test(s))
345
+ break;
346
+ lead.push(s);
347
+ }
348
+ const hadWildcard = lead.length < segs.length;
349
+ // A wholly-literal pattern with no trailing slash names a file (or a dir we
350
+ // can't tell apart) — drop its last segment so we walk the containing dir
351
+ // and let the matcher pick the file. A trailing slash or a glob means the
352
+ // remaining `lead` is already the directory to walk.
353
+ if (!hadWildcard && !trailingSlash && lead.length > 0)
354
+ lead.pop();
355
+ if (lead.length === 0) {
356
+ roots.clear();
357
+ roots.add('');
358
+ return ['']; // a top-level glob forces a whole-tree walk; nothing narrower matters
359
+ }
360
+ roots.add(lead.join('/') + '/');
361
+ }
362
+ // Collapse roots nested under a broader one (e.g. drop `a/b/` if `a/` is present).
363
+ const all = [...roots];
364
+ return all.filter((r) => !all.some((other) => other !== r && r.startsWith(other)));
365
+ }
366
+ /**
367
+ * Actively discover the source files an `include` whitelist forces in. `git
368
+ * ls-files` never lists gitignored files, so a filtered filesystem walk of just
369
+ * the opted-in subtrees (`includeStaticRoots`) is the only way to find them.
370
+ * Returns project-root-relative, normalized source-file paths.
371
+ *
372
+ * A file is collected when it MATCHES `include`, is NOT hit by `exclude` (an
373
+ * explicit exclude always wins), is a recognized source file, and does not live
374
+ * under a built-in default-ignored dir (`node_modules`, `dist`, …), `.git`, or
375
+ * CodeGraph's data dir — those are never resurfaced, mirroring `ScopeIgnore`.
376
+ * `.gitignore` is deliberately NOT consulted: overriding it is the whole point.
377
+ */
378
+ function collectIncludedFiles(rootDir, include, exclude, roots, overrides) {
379
+ const out = new Set();
380
+ const defaults = defaultsOnlyIgnore();
381
+ const visited = new Set();
382
+ const consider = (abs, rel, isDir) => {
383
+ if (isDir) {
384
+ if (defaults.ignores(rel + '/'))
385
+ return; // never node_modules/dist/… via include
386
+ // An explicit `exclude` always wins over `include`; prune the whole subtree
387
+ // here so a large excluded dir (a committed frontend's own vendored deps,
388
+ // build output, …) is never walked — the per-file guard below still catches
389
+ // anything a directory pattern doesn't, so this is a pure efficiency win.
390
+ if (exclude && exclude.ignores(rel + '/'))
391
+ return;
392
+ walk(abs);
393
+ }
394
+ else {
395
+ if (defaults.ignores(rel))
396
+ return;
397
+ if (!include.ignores(rel))
398
+ return;
399
+ if (exclude && exclude.ignores(rel))
400
+ return;
401
+ if (!(0, grammars_1.isSourceFile)(rel, overrides))
402
+ return;
403
+ out.add(rel);
404
+ }
405
+ };
406
+ function walk(absDir) {
407
+ let realDir;
408
+ try {
409
+ realDir = fs.realpathSync(absDir);
410
+ }
411
+ catch {
412
+ return;
413
+ }
414
+ if (visited.has(realDir))
415
+ return; // symlink-cycle guard
416
+ visited.add(realDir);
417
+ let entries;
418
+ try {
419
+ entries = fs.readdirSync(absDir, { withFileTypes: true });
420
+ }
421
+ catch {
422
+ return;
423
+ }
424
+ for (const entry of entries) {
425
+ if (entry.name === '.git' || (0, directory_1.isCodeGraphDataDir)(entry.name))
426
+ continue;
427
+ const abs = path.join(absDir, entry.name);
428
+ const rel = (0, utils_1.normalizePath)(path.relative(rootDir, abs));
429
+ if (!rel || rel.startsWith('..'))
430
+ continue;
431
+ if (entry.isSymbolicLink()) {
432
+ try {
433
+ const st = fs.statSync(fs.realpathSync(abs));
434
+ consider(abs, rel, st.isDirectory());
435
+ }
436
+ catch {
437
+ // broken symlink — skip
438
+ }
439
+ continue;
440
+ }
441
+ consider(abs, rel, entry.isDirectory());
442
+ }
443
+ }
444
+ for (const root of roots) {
445
+ walk(root === '' ? rootDir : path.join(rootDir, root));
446
+ }
447
+ return out;
448
+ }
449
+ /**
450
+ * The included source files (`codegraph.json` `include`) for a scan root, or an
451
+ * empty set when nothing is force-included. Centralizes loading the matcher,
452
+ * roots, exclude, and overrides so both enumeration paths (git and filesystem
453
+ * walk) add the same files.
454
+ */
455
+ function collectIncludedFilesForRoot(rootDir) {
456
+ const include = loadIncludeMatcher(rootDir);
457
+ if (!include)
458
+ return new Set();
459
+ const roots = includeStaticRoots((0, project_config_1.loadIncludePatterns)(rootDir));
460
+ return collectIncludedFiles(rootDir, include, loadExcludeMatcher(rootDir), roots, (0, project_config_1.loadExtensionOverrides)(rootDir));
461
+ }
462
+ /**
463
+ * `git ls-files --directory` collapses a wholly-untracked/ignored directory into
464
+ * one entry — and when the command's own cwd is such a directory (the indexed
465
+ * root is itself a git-ignored subdir of an enclosing repo), git emits the
466
+ * literal `./` meaning "this entire directory". That sentinel is not a real
467
+ * nested path: feeding it to the `ignore` matcher throws ("path should be a
468
+ * `path.relative()`d string, but got "./""), which used to abort `buildScopeIgnore`
469
+ * and so break the MCP daemon's watcher/auto-sync on connect; and joining it back
470
+ * onto `repoDir` would just re-point at the cwd. Drop it wherever we consume
471
+ * `--directory` output. (#936)
472
+ */
473
+ function isWholeCwdEntry(entry) {
474
+ return entry === './' || entry === '.' || entry === '';
475
+ }
476
+ /**
477
+ * List the gitignored DIRECTORIES of a repo (collapsed, trailing-slash form),
478
+ * relative to `repoDir`. These are invisible to every other `git ls-files` /
479
+ * `git status` mode — and in a multi-repo workspace they are exactly where the
480
+ * nested project repos live (a super-repo `.gitignore`s its child repos to keep
481
+ * `git status` quiet; that does not make them third-party code). (#514)
482
+ */
483
+ function listIgnoredDirs(repoDir) {
484
+ try {
485
+ const out = (0, child_process_1.execFileSync)('git', ['ls-files', '-z', '-o', '-i', '--exclude-standard', '--directory'], { cwd: repoDir, encoding: 'utf-8', timeout: 30000, maxBuffer: 50 * 1024 * 1024, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
486
+ return out.split('\0').filter((e) => e.endsWith('/') && !isWholeCwdEntry(e));
487
+ }
488
+ catch {
489
+ return [];
490
+ }
491
+ }
492
+ /** Max directory depth searched below an ignored dir for nested `.git` roots. */
493
+ const EMBEDDED_REPO_SEARCH_DEPTH = 4;
494
+ /** Max directories examined per search — a huge ignored data dir must never stall a scan/sync. */
495
+ const EMBEDDED_REPO_SEARCH_ENTRIES = 2000;
496
+ /**
497
+ * Classify a directory's `.git` entry for embedded-repo discovery.
498
+ *
499
+ * - A `.git` **directory** is an embedded clone — distinct first-party code a
500
+ * super-repo merely hides from git; index it (#193, #514).
501
+ * - A `.git` **file** is a pointer (`gitdir: …`). A git **worktree** points into
502
+ * the host repo's own `.git/worktrees/<name>`, so it is a second working view
503
+ * of a repo CodeGraph already indexes — indexing it just duplicates the whole
504
+ * graph N times; skip it (#848). A **submodule worktree** points into
505
+ * `.git/modules/<module>/worktrees/<name>` — same duplication, so skip it too
506
+ * (#945). A **submodule** checkout points into `.git/modules/<module>` (no
507
+ * `worktrees/` segment) and is distinct code, so index it as before.
508
+ *
509
+ * Returns `'none'` when there is no `.git` entry here.
510
+ */
511
+ function classifyGitDir(absDir) {
512
+ let st;
513
+ try {
514
+ st = fs.statSync(path.join(absDir, '.git'));
515
+ }
516
+ catch {
517
+ return 'none';
518
+ }
519
+ if (st.isDirectory())
520
+ return 'embedded';
521
+ if (!st.isFile())
522
+ return 'none';
523
+ try {
524
+ const gitdir = fs.readFileSync(path.join(absDir, '.git'), 'utf8').match(/^gitdir:\s*(.+)$/m)?.[1]?.trim();
525
+ // A worktree's gitdir lives under some repo's `.git/worktrees/<name>` —
526
+ // either the top-level repo's (`.git/worktrees/`) or, for a worktree of a
527
+ // submodule, that submodule's gitdir (`.git/modules/<module>/worktrees/`).
528
+ // The optional `modules/<module>` segment covers the submodule case (#945).
529
+ // Match both separators so a Windows-style pointer is recognized too.
530
+ if (gitdir && /(^|[\\/])\.git[\\/](modules[\\/][^\\/]+[\\/])?worktrees[\\/]/.test(gitdir))
531
+ return 'worktree';
532
+ }
533
+ catch {
534
+ // Unreadable `.git` pointer — fall back to the prior "index it" behavior.
535
+ }
536
+ return 'embedded';
537
+ }
538
+ /**
539
+ * Find git repositories nested under `absDir` (inclusive), shallow bounded BFS.
540
+ * Stops descending at each repo root found — contents belong to that repo's own
541
+ * enumeration. Skips default-ignored dirs (`node_modules` can contain `.git`
542
+ * from npm git-dependencies — that never makes it project code) and CodeGraph
543
+ * data dirs. Depth- and entry-capped so a huge ignored tree can't stall the scan.
544
+ */
545
+ function findNestedGitRepos(absDir, relPrefix) {
546
+ const found = [];
547
+ const defaults = defaultsOnlyIgnore();
548
+ const queue = [
549
+ { abs: absDir, rel: relPrefix, depth: 0 },
550
+ ];
551
+ let examined = 0;
552
+ while (queue.length > 0) {
553
+ const { abs, rel, depth } = queue.shift();
554
+ if (++examined > EMBEDDED_REPO_SEARCH_ENTRIES) {
555
+ (0, errors_1.logDebug)('Embedded-repo search entry cap hit — deeper repos (if any) not discovered', { under: relPrefix });
556
+ break;
557
+ }
558
+ const cls = classifyGitDir(abs);
559
+ if (cls === 'worktree') {
560
+ continue; // a git worktree duplicates an already-indexed repo (#848) — skip
561
+ }
562
+ if (cls === 'embedded') {
563
+ found.push(rel);
564
+ continue; // its own git handles everything below
565
+ }
566
+ if (depth >= EMBEDDED_REPO_SEARCH_DEPTH)
567
+ continue;
568
+ let entries;
569
+ try {
570
+ entries = fs.readdirSync(abs, { withFileTypes: true });
571
+ }
572
+ catch {
573
+ continue;
574
+ }
575
+ for (const entry of entries) {
576
+ if (!entry.isDirectory())
577
+ continue;
578
+ if (entry.name === '.git' || (0, directory_1.isCodeGraphDataDir)(entry.name))
579
+ continue;
580
+ const childRel = rel + entry.name + '/';
581
+ if (defaults.ignores(childRel))
582
+ continue;
583
+ queue.push({ abs: path.join(abs, entry.name), rel: childRel, depth: depth + 1 });
584
+ }
585
+ }
586
+ return found;
587
+ }
588
+ /**
589
+ * Workspace-scope ignore matcher. Ordinary paths get the root's matcher
590
+ * (built-in defaults + root `.gitignore`); paths inside an EMBEDDED repo get
591
+ * that repo's own matcher (defaults + its root `.gitignore`) — the parent's
592
+ * `.gitignore` hides a child repo from git, not from the index (#514). A
593
+ * directory path (trailing slash) that is an ANCESTOR of an embedded root is
594
+ * never ignored, so directory-pruning callers (the Linux per-directory
595
+ * watcher) still descend to reach the embedded repos.
596
+ *
597
+ * Single source of truth for indexer and watcher scope — they must not diverge.
598
+ */
599
+ class ScopeIgnore {
600
+ rootMatcher;
601
+ exclude;
602
+ include;
603
+ includeRoots;
604
+ embedded;
605
+ defaults = defaultsOnlyIgnore();
606
+ constructor(rootMatcher, embedded,
607
+ /**
608
+ * Project `codegraph.json` `exclude` patterns (#999), matched against the
609
+ * full root-relative path. Wins over everything else — an explicit user
610
+ * exclude applies even to tracked files and even inside embedded repos.
611
+ */
612
+ exclude = null,
613
+ /**
614
+ * Project `codegraph.json` `include` patterns — first-party source forced
615
+ * INTO the index despite `.gitignore`. When a path matches, it is NOT
616
+ * ignored (so the watcher watches it), overriding `.gitignore`/`rootMatcher`
617
+ * — but never `exclude` (checked first) and never a built-in default-ignored
618
+ * dir. `includeRoots` are the static prefixes so a gitignored ANCESTOR
619
+ * directory of an included subtree still isn't pruned by the directory
620
+ * walker/watcher.
621
+ */
622
+ include = null, includeRoots = []) {
623
+ this.rootMatcher = rootMatcher;
624
+ this.exclude = exclude;
625
+ this.include = include;
626
+ this.includeRoots = includeRoots;
627
+ // Longest root first so paths in nested embedded repos hit the innermost matcher.
628
+ this.embedded = [...embedded].sort((a, b) => b.root.length - a.root.length);
629
+ }
630
+ ignores(rel) {
631
+ // User `exclude` (#999) is checked first and against the full root-relative
632
+ // path: it must drop git-TRACKED paths (which `.gitignore` can't) and apply
633
+ // everywhere, including ancestors of embedded repos.
634
+ if (this.exclude && this.exclude.ignores(rel))
635
+ return true;
636
+ // User `include`: force first-party source in despite `.gitignore`. Never
637
+ // resurfaces a built-in default-ignored dir (node_modules/dist/…), so an
638
+ // include pattern can't accidentally pull in dependency/build trees.
639
+ if (this.include && !this.defaults.ignores(rel)) {
640
+ if (rel.endsWith('/')) {
641
+ // A directory on (or leading to) an included subtree must stay walkable
642
+ // so the watcher/walker descends to reach the forced-in files.
643
+ if (this.includeRoots.some((r) => r.startsWith(rel) || rel.startsWith(r)))
644
+ return false;
645
+ }
646
+ else if (this.include.ignores(rel)) {
647
+ return false;
648
+ }
649
+ }
650
+ for (const { root, matcher } of this.embedded) {
651
+ if (rel.startsWith(root)) {
652
+ const inner = rel.slice(root.length);
653
+ if (inner === '')
654
+ return false;
655
+ // Built-in defaults apply to the FULL path uniformly (#407) — an
656
+ // embedded repo inside node_modules (an npm git-dependency) must stay
657
+ // excluded even though its own rules wouldn't ignore its files.
658
+ return this.defaults.ignores(rel) || matcher.ignores(inner);
659
+ }
660
+ }
661
+ // Never prune a directory that leads to an embedded repo.
662
+ if (rel.endsWith('/') && this.embedded.some(({ root }) => root.startsWith(rel))) {
663
+ return false;
664
+ }
665
+ return this.rootMatcher.ignores(rel);
666
+ }
667
+ }
668
+ exports.ScopeIgnore = ScopeIgnore;
669
+ /**
670
+ * Build the workspace-scope matcher. When the caller already knows the
671
+ * embedded roots (the scanner discovers them during collection), pass them to
672
+ * skip rediscovery; otherwise they're discovered here (the watcher path).
673
+ */
674
+ function buildScopeIgnore(rootDir, embeddedRoots) {
675
+ const roots = embeddedRoots ? [...embeddedRoots] : discoverEmbeddedRepoRoots(rootDir);
676
+ const include = loadIncludeMatcher(rootDir);
677
+ return new ScopeIgnore(buildDefaultIgnore(rootDir), roots.map((root) => ({ root, matcher: buildDefaultIgnore(path.join(rootDir, root)) })), loadExcludeMatcher(rootDir), include, include ? includeStaticRoots((0, project_config_1.loadIncludePatterns)(rootDir)) : []);
678
+ }
679
+ /**
680
+ * Whether an embedded repo found as a tracked gitlink (mode 160000, #1031/#1033)
681
+ * must be SKIPPED rather than indexed. A gitlink is tracked, so `.gitignore`
682
+ * can't untrack it — but the discovery passes for it must still honor the same
683
+ * scope rules as every other path, or a gitignored reference/data dir full of
684
+ * `git add`ed clones gets pulled into the index against the user's stated intent
685
+ * (#1065). Two reasons to skip:
686
+ * 1. It sits in a built-in default-ignored location — an npm git-dependency
687
+ * under `node_modules` is never project code; not even an explicit opt-in
688
+ * revives it (matches `findIgnoredEmbeddedRepos`).
689
+ * 2. The parent repo's own `.gitignore` covers its path and the project did
690
+ * NOT opt that path in via `codegraph.json` `includeIgnored`. The gitignore
691
+ * rule is the user's stated intent to keep that path out of scope, exactly
692
+ * as for an UNtracked embedded repo — respect it by default, opt back in
693
+ * with `includeIgnored` (#514, #970, #976).
694
+ * `relDir` is repoDir-relative (trailing-slashed); `prefix` is repoDir's
695
+ * scan-root-relative path so the `includeIgnored` pattern is matched on the full
696
+ * scan-root-relative path. `defaults` is `defaultsOnlyIgnore()` and `repoIgnore`
697
+ * is `buildDefaultIgnore(repoDir)` (defaults + the repo's own `.gitignore`),
698
+ * both passed in so they're built once per repo level rather than per gitlink.
699
+ */
700
+ function gitlinkEmbeddedRepoSkipped(relDir, prefix, defaults, repoIgnore, includeIgnored) {
701
+ if (defaults.ignores(relDir))
702
+ return true; // default-ignored — never index, opt-in can't revive
703
+ if (!repoIgnore.ignores(relDir))
704
+ return false; // not ignored at all — index as before (#1031/#1033)
705
+ // Gitignored by the repo's own rules — skip unless the project opted it in.
706
+ return !includeIgnored?.ignores((0, utils_1.normalizePath)(prefix + relDir));
707
+ }
708
+ /**
709
+ * Standalone discovery of every embedded repo root under `rootDir` (relative,
710
+ * trailing-slashed) — the untracked kind (#193) always, and the gitignored kind
711
+ * (#514) only for directories the project opted in via `codegraph.json`
712
+ * `includeIgnored` (#622, #699); otherwise `.gitignore` is respected and they
713
+ * are not discovered (#970, #976). Recursive (an embedded repo can embed further
714
+ * repos). Returns [] for non-git roots: the filesystem walk handles nested repos
715
+ * there already.
716
+ */
717
+ function discoverEmbeddedRepoRoots(rootDir) {
718
+ try {
719
+ (0, child_process_1.execFileSync)('git', ['rev-parse', '--git-dir'], { cwd: rootDir, encoding: 'utf-8', timeout: 5000, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
720
+ }
721
+ catch {
722
+ return [];
723
+ }
724
+ const out = [];
725
+ const defaults = defaultsOnlyIgnore();
726
+ const includeIgnored = loadIncludeIgnoredMatcher(rootDir);
727
+ const visit = (repoAbs, prefix) => {
728
+ const candidates = [];
729
+ try {
730
+ const o = (0, child_process_1.execFileSync)('git', ['ls-files', '-z', '-o', '--exclude-standard', '--directory'], { cwd: repoAbs, encoding: 'utf-8', timeout: 30000, maxBuffer: 50 * 1024 * 1024, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
731
+ for (const e of o.split('\0')) {
732
+ if (e.endsWith('/') && !isWholeCwdEntry(e) && !defaults.ignores(e)) {
733
+ candidates.push(...findNestedGitRepos(path.join(repoAbs, e), e));
734
+ }
735
+ }
736
+ }
737
+ catch { /* untracked listing failed — ignored-side discovery still runs */ }
738
+ // Unexpanded gitlinks (mode 160000) with a real checkout on disk — embedded
739
+ // repos `git add`ed without `.gitmodules`, or submodules not active here. The
740
+ // untracked listing above can't see them (they're tracked), so find them the
741
+ // same way collectGitFiles does, keeping watcher scope == indexer scope.
742
+ // (#1031, #1033)
743
+ try {
744
+ const staged = (0, child_process_1.execFileSync)('git', ['ls-files', '-z', '-s', '--recurse-submodules'], { cwd: repoAbs, encoding: 'utf-8', timeout: 30000, maxBuffer: 50 * 1024 * 1024, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
745
+ const repoIgnore = buildDefaultIgnore(repoAbs);
746
+ for (const entry of staged.split('\0')) {
747
+ if (!entry || entry.slice(0, 6) !== '160000')
748
+ continue;
749
+ const tab = entry.indexOf('\t');
750
+ if (tab === -1)
751
+ continue;
752
+ const rel = entry.slice(tab + 1);
753
+ const relDir = rel.endsWith('/') ? rel : rel + '/';
754
+ // A gitlink under a gitignored path is respected (not indexed) unless the
755
+ // project opted it in — same rule as the untracked-ignored kind (#1065).
756
+ if (gitlinkEmbeddedRepoSkipped(relDir, prefix, defaults, repoIgnore, includeIgnored))
757
+ continue;
758
+ if (classifyGitDir(path.join(repoAbs, rel)) === 'embedded')
759
+ candidates.push(relDir);
760
+ }
761
+ }
762
+ catch { /* staged listing failed — other discovery still runs */ }
763
+ candidates.push(...findIgnoredEmbeddedRepos(repoAbs, includeIgnored, prefix));
764
+ for (const rel of candidates) {
765
+ const full = (0, utils_1.normalizePath)(prefix + rel);
766
+ out.push(full);
767
+ visit(path.join(repoAbs, rel), full);
768
+ }
769
+ };
770
+ visit(rootDir, '');
771
+ return out;
772
+ }
773
+ /**
774
+ * Cap on how many skipped gitignored repos the CLI hint enumerates — a huge
775
+ * gitignored data dir full of clones must never turn the hint scan into a long
776
+ * walk. Enough to make the point; the caller says "+N more" past this.
777
+ */
778
+ const UNINDEXED_IGNORED_REPO_HINT_CAP = 100;
779
+ /**
780
+ * The INVERSE of the gitignored side of {@link discoverEmbeddedRepoRoots}:
781
+ * nested git repositories under a gitignored directory that the project has NOT
782
+ * opted into via `codegraph.json` `includeIgnored`. These are real repos the
783
+ * default `init`/`index` deliberately skips because `.gitignore` excludes them
784
+ * (#970, #976) — most visibly the "super-repo `.gitignore`s its child repos"
785
+ * layout (#1156), where `init` at the parent correctly indexes ~nothing while
786
+ * `init` inside each child works. The CLI uses this to turn that silent empty
787
+ * index into an actionable hint: it names the skipped repos and offers to opt
788
+ * them in. Paths are `rootDir`-relative and trailing-slashed (valid
789
+ * `includeIgnored` patterns as-is). Returns `[]` for a non-git root (a
790
+ * filesystem walk already descends into nested repos there), skips built-in
791
+ * default-ignored dirs (`node_modules`, …), and is bounded so it never stalls
792
+ * on a giant ignored tree.
793
+ */
794
+ function findUnindexedIgnoredRepos(rootDir) {
795
+ try {
796
+ (0, child_process_1.execFileSync)('git', ['rev-parse', '--git-dir'], { cwd: rootDir, encoding: 'utf-8', timeout: 5000, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
797
+ }
798
+ catch {
799
+ return [];
800
+ }
801
+ const defaults = defaultsOnlyIgnore();
802
+ const includeIgnored = loadIncludeIgnoredMatcher(rootDir);
803
+ const repos = [];
804
+ for (const dir of listIgnoredDirs(rootDir)) {
805
+ if (defaults.ignores(dir))
806
+ continue; // node_modules etc. — never project code
807
+ if (includeIgnored?.ignores((0, utils_1.normalizePath)(dir)))
808
+ continue; // already opted in — nothing to nag about
809
+ for (const repo of findNestedGitRepos(path.join(rootDir, dir), dir)) {
810
+ repos.push(repo);
811
+ if (repos.length >= UNINDEXED_IGNORED_REPO_HINT_CAP)
812
+ return repos;
813
+ }
814
+ }
815
+ return repos;
816
+ }
817
+ /**
818
+ * Discover embedded repos hidden by `repoDir`'s OWN gitignore rules: for each
819
+ * gitignored directory, search for nested `.git` roots. Returns repo paths
820
+ * relative to `repoDir`, trailing-slashed.
821
+ *
822
+ * OPT-IN ONLY. Walking into a gitignored directory contradicts what every other
823
+ * tool (and CodeGraph's own `git ls-files` foundation) does — `.gitignore`
824
+ * excludes. So this returns `[]` unless the project opted the directory in via
825
+ * `codegraph.json` `includeIgnored`; without that, a gitignored dir — including
826
+ * a huge reference/data dir full of nested clones — is left untouched (#970,
827
+ * #976). When opted in, it restores the super-repo-of-clones behavior (#622,
828
+ * #699). `prefix` is the scan-root-relative path of `repoDir`, so a pattern like
829
+ * `services/` opts that whole subtree in at any recursion depth. Built-in
830
+ * default excludes (`node_modules`, …) are always skipped.
831
+ */
832
+ function findIgnoredEmbeddedRepos(repoDir, includeIgnored, prefix) {
833
+ if (!includeIgnored)
834
+ return [];
835
+ const defaults = defaultsOnlyIgnore();
836
+ const repos = [];
837
+ for (const dir of listIgnoredDirs(repoDir)) {
838
+ if (defaults.ignores(dir))
839
+ continue;
840
+ if (!includeIgnored.ignores((0, utils_1.normalizePath)(prefix + dir)))
841
+ continue;
842
+ repos.push(...findNestedGitRepos(path.join(repoDir, dir), dir));
843
+ }
844
+ return repos;
845
+ }
846
+ /**
847
+ * Collect git-visible files (tracked + untracked, .gitignore-respected) from the
848
+ * git repository rooted at `repoDir`, adding each to `files` with `prefix`
849
+ * prepended so paths stay relative to the original scan root.
850
+ *
851
+ * Recurses into embedded git repositories — nested repos that are NOT submodules
852
+ * (independent clones living inside the workspace, common in CMake "super-repo"
853
+ * layouts). The parent repo's `git ls-files` cannot see into them: tracked output
854
+ * skips them entirely, and untracked output reports them only as an opaque
855
+ * "subdir/" entry (trailing slash) rather than expanding their files. Each
856
+ * embedded repo is its own git boundary, so we re-run `git ls-files` inside it.
857
+ * (See issue #193.) GITIGNORED embedded repos are invisible even to that; they
858
+ * are discovered separately via `findIgnoredEmbeddedRepos` (#514) but ONLY for
859
+ * directories the project opted in through `codegraph.json` `includeIgnored`
860
+ * (`includeIgnored` here, threaded from the scan root) — by default `.gitignore`
861
+ * is respected and they stay out (#970, #976). Every embedded repo root (however
862
+ * found) is recorded in `embeddedRoots` so callers can exempt its files from the
863
+ * parent's own gitignore rules.
864
+ */
865
+ function collectGitFiles(repoDir, prefix, files, embeddedRoots, includeIgnored = null) {
866
+ const gitOpts = { cwd: repoDir, encoding: 'utf-8', timeout: 30000, maxBuffer: 50 * 1024 * 1024, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true };
867
+ // Tracked files. --recurse-submodules pulls in files from active submodules,
868
+ // which the index would otherwise represent only as a commit pointer.
869
+ // Without this, monorepos using submodules index 0 files. (See issue #147.)
870
+ // Note: --recurse-submodules only supports -c/--cached and --stage modes — it
871
+ // can't be combined with -o, so untracked files are gathered separately below.
872
+ //
873
+ // We use --stage (-s) rather than -c so each entry carries its file mode. That
874
+ // lets us spot gitlink entries (mode 160000) that --recurse-submodules did NOT
875
+ // expand: a nested repo `git add`ed without a `.gitmodules` entry, or a
876
+ // submodule that isn't active/initialized in this checkout. Such a gitlink
877
+ // falls through every pass — it's tracked, so the untracked `-o` listing below
878
+ // never reports it, and --recurse-submodules only expands ACTIVE submodules —
879
+ // so its source would be silently skipped, leaving only the super-repo's own
880
+ // files indexed. We collect those gitlinks here and recurse into them below.
881
+ // (An active submodule is expanded inline by --recurse-submodules and so never
882
+ // surfaces as a 160000 entry — only the unhandled gitlinks do.) (#1031, #1033)
883
+ //
884
+ // -z gives NUL-separated, unquoted output so non-ASCII (e.g. CJK) paths
885
+ // survive verbatim. Without it git octal-escapes and double-quotes such paths
886
+ // (the core.quotepath default), and the quoted form never matches a real file
887
+ // on disk → those files are silently dropped from the index. (#541) With -s the
888
+ // path follows a TAB after the `<mode> <object> <stage>` prefix.
889
+ const gitlinkRels = [];
890
+ const tracked = (0, child_process_1.execFileSync)('git', ['ls-files', '-z', '-s', '--recurse-submodules'], gitOpts);
891
+ for (const entry of tracked.split('\0')) {
892
+ if (!entry)
893
+ continue;
894
+ const tab = entry.indexOf('\t');
895
+ if (tab === -1)
896
+ continue; // --stage always emits "<mode> <object> <stage>\t<path>"
897
+ const rel = entry.slice(tab + 1);
898
+ if (entry.slice(0, 6) === '160000') {
899
+ gitlinkRels.push(rel); // an unexpanded gitlink — recursed into below, not a source file itself
900
+ continue;
901
+ }
902
+ files.add((0, utils_1.normalizePath)(prefix + rel));
903
+ }
904
+ // Untracked files (submodules manage their own untracked state). Embedded git
905
+ // repos surface here as a single "subdir/" entry that git refuses to descend
906
+ // into — recurse into those as their own repos so their source gets indexed.
907
+ const untracked = (0, child_process_1.execFileSync)('git', ['ls-files', '-z', '-o', '--exclude-standard'], gitOpts);
908
+ for (const rel of untracked.split('\0')) {
909
+ if (!rel)
910
+ continue;
911
+ if (rel.endsWith('/')) {
912
+ // git only emits a trailing-slash directory entry for an embedded repo.
913
+ // Guard with a .git check anyway, and skip anything else exactly as git
914
+ // itself skips it (we never descend into a non-repo opaque dir). Never
915
+ // descend into default-ignored locations — an embedded repo inside
916
+ // node_modules is an npm git-dependency, not project code.
917
+ const childDir = path.join(repoDir, rel);
918
+ // A git worktree surfaces here as an opaque untracked dir too — skip it,
919
+ // it's a duplicate working view of an already-indexed repo (#848).
920
+ if (classifyGitDir(childDir) === 'embedded' && !defaultsOnlyIgnore().ignores(rel)) {
921
+ embeddedRoots?.add((0, utils_1.normalizePath)(prefix + rel));
922
+ collectGitFiles(childDir, prefix + rel, files, embeddedRoots, includeIgnored);
923
+ }
924
+ continue;
925
+ }
926
+ files.add((0, utils_1.normalizePath)(prefix + rel));
927
+ }
928
+ // Gitlink entries (mode 160000) that --recurse-submodules left unexpanded —
929
+ // an embedded repo `git add`ed without `.gitmodules`, or a submodule not
930
+ // active/initialized in this checkout. When such a gitlink has a real working
931
+ // tree on disk it is distinct first-party code we must index as its own
932
+ // embedded repo: the tracked pass skipped its contents and the untracked pass
933
+ // never sees it (it's tracked, not "other"). A gitlink with no checkout on disk
934
+ // (an uninitialized submodule — empty dir, no `.git`) has nothing to index and
935
+ // is left alone, as is a submodule worktree (a duplicate view, #945). (#1031, #1033)
936
+ if (gitlinkRels.length > 0) {
937
+ const defaults = defaultsOnlyIgnore();
938
+ const repoIgnore = buildDefaultIgnore(repoDir);
939
+ for (const rel of gitlinkRels) {
940
+ const relDir = rel.endsWith('/') ? rel : rel + '/';
941
+ // A gitlink under a gitignored path is respected (not indexed) unless the
942
+ // project opted it in via `includeIgnored` — keep tracked gitlinks under
943
+ // the same scope rule as the untracked-ignored kind below (#1065).
944
+ if (gitlinkEmbeddedRepoSkipped(relDir, prefix, defaults, repoIgnore, includeIgnored))
945
+ continue;
946
+ const childDir = path.join(repoDir, rel);
947
+ // 'embedded' = a real .git checkout on disk; 'worktree' and 'none' are skipped.
948
+ if (classifyGitDir(childDir) !== 'embedded')
949
+ continue;
950
+ embeddedRoots?.add((0, utils_1.normalizePath)(prefix + relDir));
951
+ collectGitFiles(childDir, prefix + relDir, files, embeddedRoots, includeIgnored);
952
+ }
953
+ }
954
+ // Embedded repos hidden by THIS repo's ignore rules (`/packages/` in a
955
+ // super-repo .gitignore) never appear in any listing above. By default they
956
+ // stay hidden — `.gitignore` is respected (#970, #976). They are recursed into
957
+ // only when the project opted the directory in via `codegraph.json`
958
+ // `includeIgnored` (#622, #699), which `findIgnoredEmbeddedRepos` enforces.
959
+ for (const rel of findIgnoredEmbeddedRepos(repoDir, includeIgnored, prefix)) {
960
+ embeddedRoots?.add((0, utils_1.normalizePath)(prefix + rel));
961
+ collectGitFiles(path.join(repoDir, rel), prefix + rel, files, embeddedRoots, includeIgnored);
962
+ }
963
+ }
964
+ /**
965
+ * Get all files visible to git (tracked + untracked but not ignored).
966
+ * Respects .gitignore at all levels (root, subdirectories) and descends into
967
+ * embedded (nested, non-submodule) git repos. Returns null on failure
968
+ * (non-git project) so callers can fall back to a filesystem walk.
969
+ */
970
+ function getGitVisibleFiles(rootDir) {
971
+ try {
972
+ // Check if the project directory is gitignored by a parent repo.
973
+ // When rootDir lives inside a parent git repo that ignores it,
974
+ // `git ls-files` returns nothing — fall back to filesystem walk.
975
+ const gitRoot = (0, child_process_1.execFileSync)('git', ['rev-parse', '--show-toplevel'], { cwd: rootDir, encoding: 'utf-8', timeout: 5000, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true }).trim();
976
+ if (path.resolve(gitRoot) !== path.resolve(rootDir)) {
977
+ try {
978
+ // git check-ignore exits 0 if the path IS ignored, 1 if not
979
+ (0, child_process_1.execFileSync)('git', ['check-ignore', '-q', path.resolve(rootDir)], { cwd: rootDir, encoding: 'utf-8', timeout: 5000, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
980
+ // Directory is gitignored by parent repo — fall back to filesystem walk
981
+ return null;
982
+ }
983
+ catch {
984
+ // Not ignored — safe to use git ls-files
985
+ }
986
+ }
987
+ const files = new Set();
988
+ const embeddedRoots = new Set();
989
+ collectGitFiles(rootDir, '', files, embeddedRoots, loadIncludeIgnoredMatcher(rootDir));
990
+ // Apply built-in default ignores uniformly — to tracked files too, since
991
+ // committing a dependency/build dir doesn't make it project code. A
992
+ // `.gitignore` negation (e.g. `!vendor/`) is the explicit opt-in. (issue #407)
993
+ // Files inside an EMBEDDED repo are matched against that repo's own rules,
994
+ // not the parent's: the parent's .gitignore hides the child repo from git,
995
+ // not from the index. (#514)
996
+ const ig = buildScopeIgnore(rootDir, embeddedRoots);
997
+ const visible = new Set([...files].filter((f) => !ig.ignores(f)));
998
+ // Force-include first-party source the project whitelisted in
999
+ // `codegraph.json` `include`. These are gitignored, so `git ls-files` never
1000
+ // listed them above — discover them directly off disk and add them. (The
1001
+ // common SVN+Git dual-VCS case: source committed to SVN, gitignored out of
1002
+ // Git, but still wanted in the graph.)
1003
+ for (const f of collectIncludedFilesForRoot(rootDir))
1004
+ visible.add(f);
1005
+ return visible;
1006
+ }
1007
+ catch {
1008
+ return null;
1009
+ }
1010
+ }
1011
+ /**
1012
+ * Use `git status` to detect changed files instead of scanning every file.
1013
+ * Returns null on failure so callers fall back to full scan.
1014
+ *
1015
+ * Recurses into embedded repos — the untracked kind (#193: the parent's status
1016
+ * collapses them to an opaque `?? subdir/` entry) always, and the gitignored
1017
+ * kind (#514: they never appear in the parent's status at all) only for
1018
+ * directories opted in via `codegraph.json` `includeIgnored` (#622, #699) —
1019
+ * running `git status` inside each, so changes in a multi-repo workspace sync
1020
+ * without a full rescan. By default a gitignored dir is left alone, matching the
1021
+ * full-index scan (#970, #976). Deleting an ENTIRE embedded repo dir is the one
1022
+ * case this cannot see (the child status that would report the deletions is gone
1023
+ * with it); a full `codegraph index` reconciles that.
1024
+ */
1025
+ function getGitChangedFiles(rootDir) {
1026
+ try {
1027
+ const changes = { modified: [], added: [], deleted: [] };
1028
+ // Custom extension → language overrides from the project's codegraph.json,
1029
+ // so change detection sees the same custom-extension files the full index does.
1030
+ const overrides = (0, project_config_1.loadExtensionOverrides)(rootDir);
1031
+ collectGitStatus(rootDir, '', changes, overrides, loadIncludeIgnoredMatcher(rootDir), loadExcludeMatcher(rootDir));
1032
+ return changes;
1033
+ }
1034
+ catch {
1035
+ return null;
1036
+ }
1037
+ }
1038
+ function collectGitStatus(repoDir, prefix, out, overrides, includeIgnored = null, exclude = null) {
1039
+ const output = (0, child_process_1.execFileSync)('git', ['status', '--porcelain', '--no-renames'], { cwd: repoDir, encoding: 'utf-8', timeout: 10000, maxBuffer: 50 * 1024 * 1024, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
1040
+ // This repo's own ignore rules — built-in defaults (#407) plus its .gitignore.
1041
+ // Change detection must exclude the SAME files the full index does, but git
1042
+ // status hides neither: it ignores nothing for *tracked* paths, and the
1043
+ // built-in defaults aren't gitignore at all. Without this filter a committed
1044
+ // vendor/ dir, or a tracked file under a .gitignored dir, surfaces here as a
1045
+ // change — so `codegraph status` (which reads getChangedFiles) reports a
1046
+ // pending edit the full index never tracks and `sync` never clears. Matching
1047
+ // repo-relative `rel` at each recursion level mirrors getGitVisibleFiles'
1048
+ // ScopeIgnore: every embedded repo is judged by ITS OWN rules, never the
1049
+ // parent's. (#766)
1050
+ const ig = buildDefaultIgnore(repoDir);
1051
+ const untrackedDirs = [];
1052
+ for (const line of output.split('\n')) {
1053
+ if (line.length < 4)
1054
+ continue; // Minimum: "XY file"
1055
+ const statusCode = line.substring(0, 2);
1056
+ const rel = (0, utils_1.normalizePath)(line.substring(3));
1057
+ // Untracked directory entries (trailing slash) may hide an embedded repo —
1058
+ // collect for the recursion below instead of treating as a file.
1059
+ if (statusCode === '??' && rel.endsWith('/')) {
1060
+ untrackedDirs.push(rel);
1061
+ continue;
1062
+ }
1063
+ const filePath = (0, utils_1.normalizePath)(prefix + rel);
1064
+ if (!(0, grammars_1.isSourceFile)(filePath, overrides))
1065
+ continue;
1066
+ if (statusCode.includes('D')) {
1067
+ // Deletions stay unfiltered: getChangedFiles acts on one only when the
1068
+ // path is already tracked in the DB, where removal is always correct — and
1069
+ // that lets a newly-excluded dir's stale rows clean themselves up. (#766)
1070
+ out.deleted.push(filePath);
1071
+ continue;
1072
+ }
1073
+ // Added (`??`) / modified files inside an excluded dir must not enter the
1074
+ // index — match against the repo-relative path, same as the full scan. (#766)
1075
+ if (ig.ignores(rel))
1076
+ continue;
1077
+ // User `codegraph.json` `exclude` (#999) is project-root-relative, so it's
1078
+ // matched against the full path — sync must not re-add a tracked file the
1079
+ // full index now keeps out. Deletions above stay unfiltered so a file that
1080
+ // WAS indexed before an exclude was added still cleans itself out.
1081
+ if (exclude && exclude.ignores(filePath))
1082
+ continue;
1083
+ if (statusCode === '??') {
1084
+ out.added.push(filePath);
1085
+ }
1086
+ else {
1087
+ // M, MM, AM, A (staged), etc. — treat as modified
1088
+ out.modified.push(filePath);
1089
+ }
1090
+ }
1091
+ // Recurse embedded repos found under untracked dirs (at the dir itself or
1092
+ // nested deeper). Gitignored dirs are walked only for the directories the
1093
+ // project opted in via `includeIgnored`; by default `.gitignore` is respected
1094
+ // and they are left alone (#970, #976), mirroring the full-index scan.
1095
+ for (const rel of untrackedDirs) {
1096
+ for (const repoRel of findNestedGitRepos(path.join(repoDir, rel), rel)) {
1097
+ collectGitStatus(path.join(repoDir, repoRel), prefix + repoRel, out, overrides, includeIgnored, exclude);
1098
+ }
1099
+ }
1100
+ for (const rel of findIgnoredEmbeddedRepos(repoDir, includeIgnored, prefix)) {
1101
+ collectGitStatus(path.join(repoDir, rel), prefix + rel, out, overrides, includeIgnored, exclude);
1102
+ }
1103
+ }
1104
+ /**
1105
+ * Recursively scan a directory for source files.
1106
+ *
1107
+ * In git repos, uses `git ls-files` (inherently respects .gitignore at all
1108
+ * levels), then keeps files with a supported source extension. For non-git
1109
+ * projects, falls back to a filesystem walk that parses .gitignore itself.
1110
+ */
1111
+ function scanDirectory(rootDir, onProgress) {
1112
+ // Custom extension → language overrides from the project's codegraph.json.
1113
+ const overrides = (0, project_config_1.loadExtensionOverrides)(rootDir);
1114
+ // Fast path: use git to get all visible files (respects .gitignore everywhere)
1115
+ const gitFiles = getGitVisibleFiles(rootDir);
1116
+ if (gitFiles) {
1117
+ const files = [];
1118
+ let count = 0;
1119
+ for (const filePath of gitFiles) {
1120
+ if ((0, grammars_1.isSourceFile)(filePath, overrides)) {
1121
+ files.push(filePath);
1122
+ count++;
1123
+ onProgress?.(count, filePath);
1124
+ }
1125
+ }
1126
+ return files;
1127
+ }
1128
+ // Fallback: walk filesystem for non-git projects
1129
+ return scanDirectoryWalk(rootDir, onProgress);
1130
+ }
1131
+ /**
1132
+ * Async variant of scanDirectory that yields to the event loop periodically,
1133
+ * allowing worker threads to receive and render progress messages.
1134
+ */
1135
+ async function scanDirectoryAsync(rootDir, onProgress) {
1136
+ // Custom extension → language overrides from the project's codegraph.json.
1137
+ const overrides = (0, project_config_1.loadExtensionOverrides)(rootDir);
1138
+ const gitFiles = getGitVisibleFiles(rootDir);
1139
+ if (gitFiles) {
1140
+ const files = [];
1141
+ let count = 0;
1142
+ for (const filePath of gitFiles) {
1143
+ if ((0, grammars_1.isSourceFile)(filePath, overrides)) {
1144
+ files.push(filePath);
1145
+ count++;
1146
+ onProgress?.(count, filePath);
1147
+ // Yield every 100 files so worker threads can render progress
1148
+ if (count % 100 === 0) {
1149
+ await new Promise(r => setImmediate(r));
1150
+ }
1151
+ }
1152
+ }
1153
+ return files;
1154
+ }
1155
+ return scanDirectoryWalk(rootDir, onProgress);
1156
+ }
1157
+ /**
1158
+ * Filesystem walk fallback for non-git projects.
1159
+ */
1160
+ function scanDirectoryWalk(rootDir, onProgress) {
1161
+ const files = [];
1162
+ let count = 0;
1163
+ const visitedDirs = new Set();
1164
+ // Custom extension → language overrides from the project's codegraph.json.
1165
+ const overrides = (0, project_config_1.loadExtensionOverrides)(rootDir);
1166
+ const loadIgnore = (dir) => {
1167
+ const giPath = path.join(dir, '.gitignore');
1168
+ if (!fs.existsSync(giPath))
1169
+ return null;
1170
+ // readGitignorePatterns is defensive: a non-UTF-8 (DLP-encrypted) or
1171
+ // uncompilable .gitignore is skipped/filtered with a warning, never thrown
1172
+ // (issue #682) — so the per-file `.ignores()` calls below can't crash.
1173
+ const patterns = readGitignorePatterns(giPath);
1174
+ return patterns ? { dir, ig: (0, ignore_1.default)().add(patterns) } : null;
1175
+ };
1176
+ const isIgnored = (fullPath, isDir, matchers) => {
1177
+ for (const { dir, ig } of matchers) {
1178
+ let rel = (0, utils_1.normalizePath)(path.relative(dir, fullPath));
1179
+ if (!rel || rel.startsWith('..'))
1180
+ continue; // not under this matcher's dir
1181
+ if (isDir)
1182
+ rel += '/'; // dir-only rules (e.g. `build/`) only match with the slash
1183
+ if (ig.ignores(rel))
1184
+ return true;
1185
+ }
1186
+ return false;
1187
+ };
1188
+ function walk(dir, matchers) {
1189
+ let realDir;
1190
+ try {
1191
+ realDir = fs.realpathSync(dir);
1192
+ }
1193
+ catch {
1194
+ (0, errors_1.logDebug)('Skipping unresolvable directory', { dir });
1195
+ return;
1196
+ }
1197
+ if (visitedDirs.has(realDir)) {
1198
+ (0, errors_1.logDebug)('Skipping already-visited directory (symlink cycle)', { dir, realDir });
1199
+ return;
1200
+ }
1201
+ visitedDirs.add(realDir);
1202
+ // This directory's own .gitignore (if present) applies to everything below it.
1203
+ // The root's .gitignore is already merged into the seeded base matcher (so a
1204
+ // negation there can override a built-in default), so skip it here.
1205
+ const own = dir === rootDir ? null : loadIgnore(dir);
1206
+ const active = own ? [...matchers, own] : matchers;
1207
+ let entries;
1208
+ try {
1209
+ entries = fs.readdirSync(dir, { withFileTypes: true });
1210
+ }
1211
+ catch (error) {
1212
+ (0, errors_1.logDebug)('Skipping unreadable directory', { dir, error: String(error) });
1213
+ return;
1214
+ }
1215
+ for (const entry of entries) {
1216
+ // Never descend into git internals or any CodeGraph data directory
1217
+ // (the active one or a sibling another environment created — #636).
1218
+ if (entry.name === '.git' || (0, directory_1.isCodeGraphDataDir)(entry.name))
1219
+ continue;
1220
+ const fullPath = path.join(dir, entry.name);
1221
+ const relativePath = (0, utils_1.normalizePath)(path.relative(rootDir, fullPath));
1222
+ if (entry.isSymbolicLink()) {
1223
+ try {
1224
+ const realTarget = fs.realpathSync(fullPath);
1225
+ const stat = fs.statSync(realTarget);
1226
+ if (stat.isDirectory()) {
1227
+ if (!isIgnored(fullPath, true, active)) {
1228
+ walk(fullPath, active);
1229
+ }
1230
+ }
1231
+ else if (stat.isFile()) {
1232
+ if (!isIgnored(fullPath, false, active) && (0, grammars_1.isSourceFile)(relativePath, overrides)) {
1233
+ files.push(relativePath);
1234
+ count++;
1235
+ onProgress?.(count, relativePath);
1236
+ }
1237
+ }
1238
+ }
1239
+ catch {
1240
+ (0, errors_1.logDebug)('Skipping broken symlink', { path: fullPath });
1241
+ }
1242
+ continue;
1243
+ }
1244
+ if (entry.isDirectory()) {
1245
+ if (!isIgnored(fullPath, true, active)) {
1246
+ walk(fullPath, active);
1247
+ }
1248
+ }
1249
+ else if (entry.isFile()) {
1250
+ if (!isIgnored(fullPath, false, active) && (0, grammars_1.isSourceFile)(relativePath, overrides)) {
1251
+ files.push(relativePath);
1252
+ count++;
1253
+ onProgress?.(count, relativePath);
1254
+ }
1255
+ }
1256
+ }
1257
+ }
1258
+ // Seed a base matcher with the built-in default ignores (merged with the root
1259
+ // .gitignore so a negation can override). Nested .gitignores still layer per-dir.
1260
+ const baseMatchers = [{ dir: rootDir, ig: buildDefaultIgnore(rootDir) }];
1261
+ // Project `codegraph.json` `exclude` patterns (#999), rooted at the project so
1262
+ // `isIgnored` matches them against root-relative paths — same coverage the
1263
+ // git path gets via ScopeIgnore, for non-git projects.
1264
+ const exclude = loadExcludeMatcher(rootDir);
1265
+ if (exclude)
1266
+ baseMatchers.push({ dir: rootDir, ig: exclude });
1267
+ walk(rootDir, baseMatchers);
1268
+ // Force-include first-party source whitelisted in `codegraph.json` `include`
1269
+ // — the walk above honours `.gitignore`, so anything gitignored was dropped;
1270
+ // add it back here (deduped). Mirrors the git path's union.
1271
+ const included = collectIncludedFilesForRoot(rootDir);
1272
+ if (included.size > 0) {
1273
+ const seen = new Set(files);
1274
+ for (const f of included) {
1275
+ if (!seen.has(f)) {
1276
+ files.push(f);
1277
+ seen.add(f);
1278
+ }
1279
+ }
1280
+ }
1281
+ return files;
1282
+ }
1283
+ /**
1284
+ * Resurrect a resolution edge that is about to be dropped (its target symbol
1285
+ * was removed, renamed, or its whole file deleted) as the ORIGINAL unresolved
1286
+ * reference that created it, read from the refName/refKind stamp
1287
+ * `createEdges` writes into edge metadata. Inserted as status='pending', the
1288
+ * ref is consumed by the same sync's resolution sweep: it rebinds to an
1289
+ * alternative definition if one exists, or parks as status='failed' where the
1290
+ * #1240 retry finds it if the symbol later reappears.
1291
+ *
1292
+ * Returns null — drop silently, the pre-#1240 behavior — for edges without a
1293
+ * refName stamp (created before the stamp existed, or synthesized): rebuilding
1294
+ * a ref from the target's plain node name would strip the receiver/qualifier
1295
+ * context the original text carried (`h.greet` → `greet`) and could rebind
1296
+ * somewhere a full re-index never would. Silent beats wrong.
1297
+ */
1298
+ function resurrectRefFromDroppedEdge(e) {
1299
+ const refName = e.metadata?.refName;
1300
+ if (typeof refName !== 'string' || refName.length === 0)
1301
+ return null;
1302
+ const refKind = typeof e.metadata?.refKind === 'string' ? e.metadata.refKind : e.kind;
1303
+ return {
1304
+ fromNodeId: e.source,
1305
+ referenceName: refName,
1306
+ referenceKind: refKind,
1307
+ line: e.line ?? 0,
1308
+ column: e.column ?? 0,
1309
+ filePath: e.sourceFilePath,
1310
+ language: e.sourceLanguage,
1311
+ };
1312
+ }
1313
+ /**
1314
+ * Extraction orchestrator
1315
+ */
1316
+ class ExtractionOrchestrator {
1317
+ rootDir;
1318
+ queries;
1319
+ /**
1320
+ * Names of frameworks detected for this project, populated by indexAll().
1321
+ * Passed to extractFromSource so framework-specific extractors (route nodes,
1322
+ * middleware, etc.) run after the tree-sitter pass. Cleared if detection
1323
+ * hasn't run yet so single-file re-index paths can detect on the spot.
1324
+ */
1325
+ detectedFrameworkNames = null;
1326
+ constructor(rootDir, queries) {
1327
+ this.rootDir = rootDir;
1328
+ this.queries = queries;
1329
+ }
1330
+ /**
1331
+ * Build a filesystem-backed ResolutionContext sufficient for framework
1332
+ * detection. Graph-query methods (getNodesByName etc.) return empty because
1333
+ * the DB hasn't been populated yet, but detect() only uses readFile,
1334
+ * fileExists, and getAllFiles, so that's fine.
1335
+ */
1336
+ buildDetectionContext(files) {
1337
+ const rootDir = this.rootDir;
1338
+ return {
1339
+ getNodesInFile: () => [],
1340
+ getNodesByName: () => [],
1341
+ getNodesByQualifiedName: () => [],
1342
+ getNodesByKind: () => [],
1343
+ getNodesByLowerName: () => [],
1344
+ getImportMappings: () => [],
1345
+ getAllFiles: () => files,
1346
+ getProjectRoot: () => rootDir,
1347
+ fileExists: (relativePath) => {
1348
+ const full = (0, utils_1.validatePathWithinRoot)(rootDir, relativePath);
1349
+ if (!full)
1350
+ return false;
1351
+ try {
1352
+ return fs.existsSync(full);
1353
+ }
1354
+ catch {
1355
+ return false;
1356
+ }
1357
+ },
1358
+ readFile: (relativePath) => {
1359
+ const full = (0, utils_1.validatePathWithinRoot)(rootDir, relativePath);
1360
+ if (!full)
1361
+ return null;
1362
+ try {
1363
+ return fs.readFileSync(full, 'utf-8');
1364
+ }
1365
+ catch {
1366
+ return null;
1367
+ }
1368
+ },
1369
+ // Monorepo support — needed by framework detect()s that probe
1370
+ // subpackage manifests (e.g. fabric-view looking at
1371
+ // packages/<sub>/package.json when the root manifest is just a
1372
+ // workspace declaration). Matches the resolver-context shape.
1373
+ listDirectories: (relativePath) => {
1374
+ const target = relativePath === '.' || relativePath === ''
1375
+ ? rootDir
1376
+ : path.join(rootDir, relativePath);
1377
+ try {
1378
+ return fs
1379
+ .readdirSync(target, { withFileTypes: true })
1380
+ .filter((entry) => entry.isDirectory())
1381
+ .map((entry) => entry.name);
1382
+ }
1383
+ catch {
1384
+ return [];
1385
+ }
1386
+ },
1387
+ };
1388
+ }
1389
+ /**
1390
+ * Detect frameworks on demand using the current scanned files (or a fresh
1391
+ * scan if none are provided). Cached on the orchestrator so repeat calls
1392
+ * inside a single run don't re-scan.
1393
+ */
1394
+ ensureDetectedFrameworks(files) {
1395
+ if (this.detectedFrameworkNames !== null)
1396
+ return this.detectedFrameworkNames;
1397
+ const fileList = files ?? scanDirectory(this.rootDir);
1398
+ const context = this.buildDetectionContext(fileList);
1399
+ this.detectedFrameworkNames = (0, frameworks_1.detectFrameworks)(context).map((r) => r.name);
1400
+ return this.detectedFrameworkNames;
1401
+ }
1402
+ /**
1403
+ * Index all files in the project
1404
+ */
1405
+ async indexAll(onProgress, signal, verbose,
1406
+ // Writer-side backstop for deferred WAL checkpointing (#1231): returns
1407
+ // null in the normal case, or a promise to await (at this safe,
1408
+ // between-transactions boundary) when the WAL has outrun the off-thread
1409
+ // checkpointer past its hard cap. See db/wal-valve.ts.
1410
+ walBackpressure) {
1411
+ await (0, grammars_1.initGrammars)();
1412
+ const startTime = Date.now();
1413
+ const errors = [];
1414
+ let filesIndexed = 0;
1415
+ let filesSkipped = 0;
1416
+ let filesErrored = 0;
1417
+ let totalNodes = 0;
1418
+ let totalEdges = 0;
1419
+ // Custom extension → language overrides from the project's codegraph.json.
1420
+ // Threaded into language detection so custom-extension files load the right
1421
+ // grammar and store under the mapped language.
1422
+ const overrides = (0, project_config_1.loadExtensionOverrides)(this.rootDir);
1423
+ const log = verbose
1424
+ ? (msg) => { console.log(`[worker] ${msg}`); }
1425
+ : (_msg) => { };
1426
+ // Phase 1: Scan for files
1427
+ onProgress?.({
1428
+ phase: 'scanning',
1429
+ current: 0,
1430
+ total: 0,
1431
+ });
1432
+ // Phase attribution to stderr (same opt-in as the synthesis timings):
1433
+ // early-run 5-10s single stalls were observed on 95k-file repos but never
1434
+ // attributed — these labels settle scan vs framework-detect vs grammars.
1435
+ const tScan = Date.now();
1436
+ const files = await scanDirectoryAsync(this.rootDir, (current, file) => {
1437
+ onProgress?.({
1438
+ phase: 'scanning',
1439
+ current,
1440
+ total: 0,
1441
+ currentFile: file,
1442
+ });
1443
+ });
1444
+ if (process.env.CODEGRAPH_SYNTH_TIMINGS)
1445
+ console.error(`[phase-timing] scan: ${Date.now() - tScan}ms (${files.length} files)`);
1446
+ // Detect frameworks once per indexAll run using the scanned file list.
1447
+ // Names are passed to each parse call so framework-specific extractors
1448
+ // (route nodes, middleware, etc.) run after the tree-sitter pass.
1449
+ // Framework detection is reset each run so adding e.g. requirements.txt
1450
+ // between runs is picked up without restarting the process.
1451
+ this.detectedFrameworkNames = null;
1452
+ const tFw = Date.now();
1453
+ const frameworkNames = this.ensureDetectedFrameworks(files);
1454
+ if (process.env.CODEGRAPH_SYNTH_TIMINGS)
1455
+ console.error(`[phase-timing] framework-detect: ${Date.now() - tFw}ms`);
1456
+ if (signal?.aborted) {
1457
+ return {
1458
+ success: false,
1459
+ filesIndexed: 0,
1460
+ filesSkipped: 0,
1461
+ filesErrored: 0,
1462
+ nodesCreated: 0,
1463
+ edgesCreated: 0,
1464
+ errors: [{ message: 'Aborted', severity: 'error' }],
1465
+ durationMs: Date.now() - startTime,
1466
+ };
1467
+ }
1468
+ // Phase 2: Parse files in a worker thread (keeps main thread unblocked for UI)
1469
+ const total = files.length;
1470
+ let processed = 0;
1471
+ // Emit parsing phase immediately so the progress bar appears during worker setup.
1472
+ // The yield lets the shimmer worker flush the phase transition to stdout before
1473
+ // the main thread starts synchronous grammar detection work.
1474
+ onProgress?.({
1475
+ phase: 'parsing',
1476
+ current: 0,
1477
+ total,
1478
+ });
1479
+ await new Promise(resolve => setImmediate(resolve));
1480
+ // Detect needed languages and load grammars in the parse worker
1481
+ const neededLanguages = [...new Set(files.map((f) => (0, grammars_1.detectLanguage)(f, undefined, overrides)))];
1482
+ // .h files default to 'c' but may be C++ — ensure cpp grammar is loaded when c is needed
1483
+ if (neededLanguages.includes('c') && !neededLanguages.includes('cpp')) {
1484
+ neededLanguages.push('cpp');
1485
+ }
1486
+ // Parse files on a pool of worker threads (keeps the main thread free for UI
1487
+ // and uses every core). Falls back to in-process parsing when the compiled
1488
+ // worker is unavailable (e.g. running from source in tests).
1489
+ const parseWorkerPath = path.join(__dirname, 'parse-worker.js');
1490
+ const useWorker = fs.existsSync(parseWorkerPath);
1491
+ let pool = null;
1492
+ if (useWorker) {
1493
+ // CODEGRAPH_PARSE_WORKERS: explicit worker count; 1 = the old single-worker
1494
+ // behaviour (the conservative rollback). Unset → clamp(cores-1, 1, 8).
1495
+ const poolSize = (0, parse_pool_1.resolveParsePoolSize)(process.env.CODEGRAPH_PARSE_WORKERS, os.cpus().length);
1496
+ // Read each needed grammar's WASM ONCE here and hand the bytes to every
1497
+ // worker, so spawns/respawns load grammars from memory instead of
1498
+ // re-reading them from disk (#1231: on an HDD, respawn re-reads amplify
1499
+ // the very I/O contention that caused the respawn).
1500
+ const grammarBuffers = await (0, grammars_1.readGrammarWasmBytes)(neededLanguages);
1501
+ pool = new parse_pool_1.ParseWorkerPool({
1502
+ languages: neededLanguages,
1503
+ size: poolSize,
1504
+ workerScriptPath: parseWorkerPath,
1505
+ recycleInterval: WORKER_RECYCLE_INTERVAL,
1506
+ parseTimeoutMs: PARSE_TIMEOUT_MS,
1507
+ log,
1508
+ grammarBuffers,
1509
+ });
1510
+ log(`Parse worker pool: ${poolSize} worker(s)`);
1511
+ }
1512
+ else {
1513
+ // In-process fallback: load grammars locally and parse on the main thread.
1514
+ await (0, grammars_1.loadGrammarsForLanguages)(neededLanguages);
1515
+ }
1516
+ /**
1517
+ * Parse one file: on the pool when available (the promise REJECTS on a worker
1518
+ * crash/timeout — the caller records it and the retry pass re-attempts), or
1519
+ * in-process synchronously as the no-worker fallback. The language is resolved
1520
+ * here on the main thread, where the codegraph.json overrides are loaded.
1521
+ */
1522
+ const parseFile = (filePath, content) => {
1523
+ const language = (0, grammars_1.detectLanguage)(filePath, content, overrides);
1524
+ if (!pool)
1525
+ return Promise.resolve((0, tree_sitter_1.extractFromSource)(filePath, content, language, frameworkNames));
1526
+ return pool.requestParse({ filePath, content, language, frameworkNames });
1527
+ };
1528
+ // --- Bounded rolling-window dispatch, ordered commit ---
1529
+ // Reads stay batched/parallel; parses run concurrently across the pool; the
1530
+ // SQLite store stays on the main thread (it isn't thread-safe). Crucially we
1531
+ // COMMIT results in original file order, not parse-completion order: the
1532
+ // resolution phase (run after indexing) resolves an ambiguous reference to one
1533
+ // of several same-named candidates by the nodes' DB insertion order, so a
1534
+ // stable commit order keeps the resulting graph deterministic — byte-identical
1535
+ // to the single-worker path — instead of drifting with parse timing. The
1536
+ // `completed` buffer holds at most ~windowSize out-of-order results, so memory
1537
+ // stays bounded.
1538
+ const windowSize = pool ? Math.max(4, pool.size * 2) : 1;
1539
+ const inFlight = new Set();
1540
+ const completed = new Map();
1541
+ let nextSeq = 0; // file-order sequence assigned at dispatch
1542
+ let nextToStore = 0; // cursor: next sequence to commit
1543
+ let aborted = false;
1544
+ // Yielder for the in-order commit path: a single giant generated file's
1545
+ // store is otherwise one unyielding multi-second transaction span on the
1546
+ // main thread (5–14s single stalls measured on llvm-project), starving
1547
+ // the #850 watchdog heartbeat on slow hardware.
1548
+ const commitYield = (0, cooperative_yield_1.createYielder)();
1549
+ const storeResult = async (filePath, content, stats, result) => {
1550
+ processed++;
1551
+ // WAL hard-cap backstop: between files (never mid-transaction), pause
1552
+ // the store until the off-thread checkpoint catches up. Resolves to
1553
+ // null in the normal case — a single size check, no cost.
1554
+ const bp = walBackpressure?.();
1555
+ if (bp)
1556
+ await bp;
1557
+ // Store in database on main thread (SQLite is not thread-safe)
1558
+ if (result.nodes.length > 0 || result.errors.length === 0) {
1559
+ const language = (0, grammars_1.detectLanguage)(filePath, content, overrides);
1560
+ await this.storeExtractionResult(filePath, content, language, stats, result, commitYield);
1561
+ }
1562
+ if (result.errors.length > 0) {
1563
+ for (const err of result.errors) {
1564
+ if (!err.filePath)
1565
+ err.filePath = filePath;
1566
+ }
1567
+ errors.push(...result.errors);
1568
+ }
1569
+ if (result.nodes.length > 0) {
1570
+ filesIndexed++;
1571
+ totalNodes += result.nodes.length;
1572
+ totalEdges += result.edges.length;
1573
+ }
1574
+ else if (result.errors.some((e) => e.severity === 'error')) {
1575
+ filesErrored++;
1576
+ }
1577
+ else {
1578
+ // Files with no symbols but no errors (yaml, twig, properties) are
1579
+ // tracked at the file level — count them as indexed so the CLI doesn't
1580
+ // misleadingly report "No files found to index".
1581
+ const lang = (0, grammars_1.detectLanguage)(filePath, content, overrides);
1582
+ if ((0, grammars_1.isFileLevelOnlyLanguage)(lang)) {
1583
+ filesIndexed++;
1584
+ }
1585
+ else {
1586
+ filesSkipped++;
1587
+ }
1588
+ }
1589
+ onProgress?.({ phase: 'parsing', current: processed, total, currentFile: filePath });
1590
+ };
1591
+ const recordParseFailure = (filePath, err) => {
1592
+ processed++;
1593
+ filesErrored++;
1594
+ errors.push({
1595
+ message: err instanceof Error ? err.message : String(err),
1596
+ filePath,
1597
+ severity: 'error',
1598
+ code: 'parse_error',
1599
+ });
1600
+ onProgress?.({ phase: 'parsing', current: processed, total });
1601
+ };
1602
+ // Commit buffered parses to the DB in file order, advancing the cursor over
1603
+ // contiguous completed results. Runs after each parse settles (and once more
1604
+ // after the drain). storeResult is now async (it yields between chunked
1605
+ // inserts), so commits are SERIALIZED on a promise chain — concurrent parse
1606
+ // completions append to the chain instead of interleaving mid-store, which
1607
+ // preserves both the file-order commit invariant (#1015: resolution
1608
+ // disambiguates same-named candidates by insertion order) and the
1609
+ // single-writer discipline for SQLite. Errors are recorded and re-thrown
1610
+ // at the drain, matching the old synchronous propagation.
1611
+ let flushChain = Promise.resolve();
1612
+ let flushError = null;
1613
+ const flushOrdered = () => {
1614
+ flushChain = flushChain.then(async () => {
1615
+ if (aborted || flushError)
1616
+ return;
1617
+ try {
1618
+ while (completed.has(nextToStore)) {
1619
+ const item = completed.get(nextToStore);
1620
+ completed.delete(nextToStore);
1621
+ nextToStore++;
1622
+ if (item.ok)
1623
+ await storeResult(item.filePath, item.content, item.stats, item.result);
1624
+ else
1625
+ recordParseFailure(item.filePath, item.err);
1626
+ }
1627
+ }
1628
+ catch (err) {
1629
+ flushError = err;
1630
+ }
1631
+ });
1632
+ return flushChain;
1633
+ };
1634
+ // Dispatch one file's parse (parses run concurrently across the pool), tagged
1635
+ // with its file-order sequence so flushOrdered commits results in order. The
1636
+ // backpressure below bounds how far parsing runs ahead of the in-order commit.
1637
+ const feed = async (filePath, content, stats) => {
1638
+ const seq = nextSeq++;
1639
+ const p = (async () => {
1640
+ try {
1641
+ const result = await parseFile(filePath, content);
1642
+ completed.set(seq, { ok: true, filePath, content, stats, result });
1643
+ }
1644
+ catch (parseErr) {
1645
+ completed.set(seq, { ok: false, filePath, err: parseErr });
1646
+ }
1647
+ flushOrdered();
1648
+ })();
1649
+ const tracked = p.finally(() => { inFlight.delete(tracked); });
1650
+ inFlight.add(tracked);
1651
+ // Backpressure on the dispatched-but-not-yet-committed count (in-flight +
1652
+ // buffered), not just in-flight: a slow file sitting at the commit cursor
1653
+ // lets later parses finish and buffer, which would otherwise grow without
1654
+ // bound. Wait for parses to settle (each may advance the cursor) until the
1655
+ // window has room. When nothing is in flight but the window is still full,
1656
+ // the async commit chain is what's behind — await it so the cursor
1657
+ // advances (buffered items hold whole file contents, so this bound is
1658
+ // load-bearing for memory).
1659
+ while (nextSeq - nextToStore >= windowSize) {
1660
+ if (inFlight.size > 0)
1661
+ await Promise.race(inFlight);
1662
+ else
1663
+ await flushOrdered();
1664
+ }
1665
+ };
1666
+ for (let i = 0; i < files.length; i += FILE_IO_BATCH_SIZE) {
1667
+ if (signal?.aborted) {
1668
+ aborted = true;
1669
+ break;
1670
+ }
1671
+ const batch = files.slice(i, i + FILE_IO_BATCH_SIZE);
1672
+ // Read files in parallel (with path validation before any I/O)
1673
+ const fileContents = await Promise.all(batch.map(async (fp) => {
1674
+ try {
1675
+ // Indexing read: follow in-root symlinks the directory walk already
1676
+ // descended into (the `../` guard still applies) so files reached
1677
+ // via an in-root symlink-to-outside still index (#935).
1678
+ const fullPath = (0, utils_1.validatePathWithinRoot)(this.rootDir, fp, { allowSymlinkEscape: true });
1679
+ if (!fullPath) {
1680
+ (0, errors_1.logWarn)('Path traversal blocked in batch reader', { filePath: fp });
1681
+ return { filePath: fp, content: null, stats: null, error: new Error('Path traversal blocked') };
1682
+ }
1683
+ const content = await fsp.readFile(fullPath, 'utf-8');
1684
+ const stats = await fsp.stat(fullPath);
1685
+ return { filePath: fp, content, stats, error: null };
1686
+ }
1687
+ catch (err) {
1688
+ return { filePath: fp, content: null, stats: null, error: err };
1689
+ }
1690
+ }));
1691
+ // Dispatch each readable file into the bounded parse window; the window
1692
+ // stores results on the main thread as they arrive.
1693
+ for (const { filePath, content, stats, error } of fileContents) {
1694
+ if (signal?.aborted) {
1695
+ aborted = true;
1696
+ break;
1697
+ }
1698
+ if (error || content === null || stats === null) {
1699
+ processed++;
1700
+ filesErrored++;
1701
+ errors.push({
1702
+ message: `Failed to read file: ${error instanceof Error ? error.message : String(error)}`,
1703
+ filePath,
1704
+ severity: 'error',
1705
+ code: 'read_error',
1706
+ });
1707
+ onProgress?.({ phase: 'parsing', current: processed, total });
1708
+ continue;
1709
+ }
1710
+ // Honour MAX_FILE_SIZE. Without this check, vendored generated
1711
+ // headers, minified bundles, and other multi-MB files get indexed,
1712
+ // wasting WASM heap and the worker recycle budget on inputs with no
1713
+ // useful symbols. The single-file extractFile path already enforces
1714
+ // this; the bulk path used to silently skip the check.
1715
+ if (stats.size > MAX_FILE_SIZE) {
1716
+ processed++;
1717
+ filesSkipped++;
1718
+ errors.push({
1719
+ message: `File exceeds max size (${stats.size} > ${MAX_FILE_SIZE})`,
1720
+ filePath,
1721
+ severity: 'warning',
1722
+ code: 'size_exceeded',
1723
+ });
1724
+ onProgress?.({ phase: 'parsing', current: processed, total });
1725
+ continue;
1726
+ }
1727
+ // Parse on the pool (main thread stays unblocked). Errors/timeouts are
1728
+ // handled inside feed() → recordParseFailure, feeding the retry pass.
1729
+ await feed(filePath, content, stats);
1730
+ }
1731
+ if (aborted)
1732
+ break;
1733
+ }
1734
+ // Drain parses still in flight (skip on abort — we tear down below instead),
1735
+ // then commit any results the cursor hasn't reached yet.
1736
+ if (!aborted) {
1737
+ await Promise.all(inFlight);
1738
+ await flushOrdered();
1739
+ if (flushError)
1740
+ throw flushError;
1741
+ }
1742
+ if (signal?.aborted || aborted) {
1743
+ if (pool)
1744
+ await pool.destroy();
1745
+ return {
1746
+ success: false,
1747
+ filesIndexed,
1748
+ filesSkipped,
1749
+ filesErrored,
1750
+ filesDiscovered: total,
1751
+ nodesCreated: totalNodes,
1752
+ edgesCreated: totalEdges,
1753
+ errors: [{ message: 'Aborted', severity: 'error' }, ...errors],
1754
+ durationMs: Date.now() - startTime,
1755
+ };
1756
+ }
1757
+ // Report 100% so the progress bar doesn't hang at 99%
1758
+ onProgress?.({
1759
+ phase: 'parsing',
1760
+ current: total,
1761
+ total,
1762
+ });
1763
+ // Yield so the shimmer worker's buffered stdout writes can flush.
1764
+ // Worker thread stdout is proxied through the main thread's event loop,
1765
+ // so synchronous work here blocks the animation from rendering.
1766
+ await new Promise(resolve => setImmediate(resolve));
1767
+ // Retry pass: files that failed due to WASM memory corruption may succeed
1768
+ // on a fresh worker with a clean heap. Recycle before each attempt so
1769
+ // every file gets the absolute cleanest WASM state possible. Timeouts are
1770
+ // retried too (#1231): most are main-thread-stall artifacts, not slow
1771
+ // parses, and this pass parses one file at a time with the store strictly
1772
+ // after each parse resolves, so the stall window can't recur here.
1773
+ const retryableErrors = errors.filter((e) => e.code === 'parse_error' && e.filePath &&
1774
+ (e.message.includes('Worker exited') ||
1775
+ e.message.includes('memory access out of bounds') ||
1776
+ e.message.includes('timed out')));
1777
+ if (retryableErrors.length > 0 && pool) {
1778
+ log(`Retrying ${retryableErrors.length} files that failed due to WASM memory errors or timeouts...`);
1779
+ // Fresh WASM heaps for the retry phase. A retry that still crashes its
1780
+ // worker makes the pool respawn it, so later retries keep landing on clean
1781
+ // workers too.
1782
+ pool.recycleAll();
1783
+ const stillFailing = [];
1784
+ for (const errEntry of retryableErrors) {
1785
+ const filePath = errEntry.filePath;
1786
+ if (signal?.aborted)
1787
+ break;
1788
+ let content;
1789
+ try {
1790
+ const fullPath = (0, utils_1.validatePathWithinRoot)(this.rootDir, filePath);
1791
+ if (!fullPath)
1792
+ continue;
1793
+ content = await fsp.readFile(fullPath, 'utf-8');
1794
+ }
1795
+ catch {
1796
+ continue;
1797
+ }
1798
+ let result;
1799
+ try {
1800
+ result = await parseFile(filePath, content);
1801
+ }
1802
+ catch {
1803
+ stillFailing.push(errEntry);
1804
+ continue;
1805
+ }
1806
+ if (result.nodes.length > 0 || result.errors.length === 0) {
1807
+ const language = (0, grammars_1.detectLanguage)(filePath, content, overrides);
1808
+ const stats = await fsp.stat(path.join(this.rootDir, filePath));
1809
+ await this.storeExtractionResult(filePath, content, language, stats, result, commitYield);
1810
+ const idx = errors.indexOf(errEntry);
1811
+ if (idx >= 0)
1812
+ errors.splice(idx, 1);
1813
+ filesErrored--;
1814
+ filesIndexed++;
1815
+ totalNodes += result.nodes.length;
1816
+ totalEdges += result.edges.length;
1817
+ log(`Retry OK: ${filePath} (${result.nodes.length} nodes)`);
1818
+ }
1819
+ }
1820
+ // Last resort: for files that still crash on a clean worker, strip
1821
+ // comment-only lines to reduce WASM memory pressure. Many compiler
1822
+ // test files are 90%+ comments (CHECK directives) that don't contribute
1823
+ // code nodes but consume parser memory.
1824
+ if (stillFailing.length > 0) {
1825
+ log(`${stillFailing.length} files still failing — retrying with comments stripped...`);
1826
+ pool.recycleAll();
1827
+ for (const errEntry of stillFailing) {
1828
+ const filePath = errEntry.filePath;
1829
+ if (signal?.aborted)
1830
+ break;
1831
+ let fullContent;
1832
+ try {
1833
+ const fullPath = (0, utils_1.validatePathWithinRoot)(this.rootDir, filePath);
1834
+ if (!fullPath)
1835
+ continue;
1836
+ fullContent = await fsp.readFile(fullPath, 'utf-8');
1837
+ }
1838
+ catch {
1839
+ continue;
1840
+ }
1841
+ // Strip lines that are entirely comments (preserving line numbers
1842
+ // by replacing with empty lines so node positions stay correct)
1843
+ const stripped = fullContent
1844
+ .split('\n')
1845
+ .map(line => /^\s*\/\//.test(line) ? '' : line)
1846
+ .join('\n');
1847
+ let result;
1848
+ try {
1849
+ result = await parseFile(filePath, stripped);
1850
+ }
1851
+ catch {
1852
+ continue;
1853
+ }
1854
+ if (result.nodes.length > 0 || result.errors.length === 0) {
1855
+ const language = (0, grammars_1.detectLanguage)(filePath, fullContent, overrides);
1856
+ const stats = await fsp.stat(path.join(this.rootDir, filePath));
1857
+ await this.storeExtractionResult(filePath, fullContent, language, stats, result, commitYield);
1858
+ const idx = errors.indexOf(errEntry);
1859
+ if (idx >= 0)
1860
+ errors.splice(idx, 1);
1861
+ filesErrored--;
1862
+ filesIndexed++;
1863
+ totalNodes += result.nodes.length;
1864
+ totalEdges += result.edges.length;
1865
+ log(`Retry (stripped) OK: ${filePath} (${result.nodes.length} nodes)`);
1866
+ }
1867
+ }
1868
+ }
1869
+ }
1870
+ // Shut down the parse worker pool.
1871
+ if (pool)
1872
+ await pool.destroy();
1873
+ return {
1874
+ success: filesIndexed > 0 || errors.filter((e) => e.severity === 'error').length === 0,
1875
+ filesIndexed,
1876
+ filesSkipped,
1877
+ filesErrored,
1878
+ filesDiscovered: total,
1879
+ nodesCreated: totalNodes,
1880
+ edgesCreated: totalEdges,
1881
+ errors,
1882
+ durationMs: Date.now() - startTime,
1883
+ };
1884
+ }
1885
+ /**
1886
+ * Index specific files
1887
+ */
1888
+ async indexFiles(filePaths) {
1889
+ const startTime = Date.now();
1890
+ const errors = [];
1891
+ let filesIndexed = 0;
1892
+ let filesSkipped = 0;
1893
+ let filesErrored = 0;
1894
+ let totalNodes = 0;
1895
+ let totalEdges = 0;
1896
+ for (const filePath of filePaths) {
1897
+ const result = await this.indexFile(filePath);
1898
+ if (result.errors.length > 0) {
1899
+ errors.push(...result.errors);
1900
+ }
1901
+ if (result.nodes.length > 0) {
1902
+ filesIndexed++;
1903
+ totalNodes += result.nodes.length;
1904
+ totalEdges += result.edges.length;
1905
+ }
1906
+ else if (result.errors.some((e) => e.severity === 'error')) {
1907
+ filesErrored++;
1908
+ }
1909
+ else {
1910
+ const tracked = this.queries.getFileByPath(filePath);
1911
+ if (tracked && (0, grammars_1.isFileLevelOnlyLanguage)(tracked.language)) {
1912
+ filesIndexed++;
1913
+ }
1914
+ else {
1915
+ filesSkipped++;
1916
+ }
1917
+ }
1918
+ }
1919
+ return {
1920
+ success: filesIndexed > 0 || errors.filter((e) => e.severity === 'error').length === 0,
1921
+ filesIndexed,
1922
+ filesSkipped,
1923
+ filesErrored,
1924
+ nodesCreated: totalNodes,
1925
+ edgesCreated: totalEdges,
1926
+ errors,
1927
+ durationMs: Date.now() - startTime,
1928
+ };
1929
+ }
1930
+ /**
1931
+ * Index a single file
1932
+ */
1933
+ async indexFile(relativePath) {
1934
+ // Indexing read: follow in-root symlinks (the `../` guard still applies), #935.
1935
+ const fullPath = (0, utils_1.validatePathWithinRoot)(this.rootDir, relativePath, { allowSymlinkEscape: true });
1936
+ if (!fullPath) {
1937
+ return {
1938
+ nodes: [],
1939
+ edges: [],
1940
+ unresolvedReferences: [],
1941
+ errors: [{ message: `Path traversal blocked: ${relativePath}`, filePath: relativePath, severity: 'error', code: 'path_traversal' }],
1942
+ durationMs: 0,
1943
+ };
1944
+ }
1945
+ // Read file content and stats
1946
+ let content;
1947
+ let stats;
1948
+ try {
1949
+ stats = await fsp.stat(fullPath);
1950
+ content = await fsp.readFile(fullPath, 'utf-8');
1951
+ }
1952
+ catch (error) {
1953
+ return {
1954
+ nodes: [],
1955
+ edges: [],
1956
+ unresolvedReferences: [],
1957
+ errors: [
1958
+ {
1959
+ message: `Failed to read file: ${error instanceof Error ? error.message : String(error)}`,
1960
+ filePath: relativePath,
1961
+ severity: 'error',
1962
+ code: 'read_error',
1963
+ },
1964
+ ],
1965
+ durationMs: 0,
1966
+ };
1967
+ }
1968
+ return this.indexFileWithContent(relativePath, content, stats);
1969
+ }
1970
+ /**
1971
+ * Index a single file with pre-read content and stats.
1972
+ * Used by the parallel batch reader to avoid redundant file I/O.
1973
+ */
1974
+ async indexFileWithContent(relativePath, content, stats) {
1975
+ // Prevent `../` traversal; follow in-root symlinks like the directory walk (#935).
1976
+ const fullPath = (0, utils_1.validatePathWithinRoot)(this.rootDir, relativePath, { allowSymlinkEscape: true });
1977
+ if (!fullPath) {
1978
+ (0, errors_1.logWarn)('Path traversal blocked in indexFileWithContent', { relativePath });
1979
+ return {
1980
+ nodes: [],
1981
+ edges: [],
1982
+ unresolvedReferences: [],
1983
+ errors: [{ message: 'Path traversal blocked', filePath: relativePath, severity: 'error', code: 'path_traversal' }],
1984
+ durationMs: 0,
1985
+ };
1986
+ }
1987
+ // Check file size
1988
+ if (stats.size > MAX_FILE_SIZE) {
1989
+ return {
1990
+ nodes: [],
1991
+ edges: [],
1992
+ unresolvedReferences: [],
1993
+ errors: [
1994
+ {
1995
+ message: `File exceeds max size (${stats.size} > ${MAX_FILE_SIZE})`,
1996
+ filePath: relativePath,
1997
+ severity: 'warning',
1998
+ code: 'size_exceeded',
1999
+ },
2000
+ ],
2001
+ durationMs: 0,
2002
+ };
2003
+ }
2004
+ // Detect language (honoring the project's codegraph.json extension overrides)
2005
+ const language = (0, grammars_1.detectLanguage)(relativePath, content, (0, project_config_1.loadExtensionOverrides)(this.rootDir));
2006
+ if (!(0, grammars_1.isLanguageSupported)(language)) {
2007
+ return {
2008
+ nodes: [],
2009
+ edges: [],
2010
+ unresolvedReferences: [],
2011
+ errors: [],
2012
+ durationMs: 0,
2013
+ };
2014
+ }
2015
+ // Extract from source. Use cached framework names if indexAll has run,
2016
+ // otherwise detect on the spot so single-file re-index paths still emit
2017
+ // route nodes / middleware / etc.
2018
+ const frameworkNames = this.ensureDetectedFrameworks();
2019
+ const result = (0, tree_sitter_1.extractFromSource)(relativePath, content, language, frameworkNames);
2020
+ // Store in database
2021
+ if (result.nodes.length > 0 || result.errors.length === 0) {
2022
+ await this.storeExtractionResult(relativePath, content, language, stats, result, (0, cooperative_yield_1.createYielder)());
2023
+ }
2024
+ return result;
2025
+ }
2026
+ /**
2027
+ * Store extraction result in database
2028
+ */
2029
+ async storeExtractionResult(filePath, content, language, stats, result, onYield) {
2030
+ // Bulk inserts run in bounded sub-transactions with a yield between, so a
2031
+ // giant generated file (tens of thousands of symbols) can't block the
2032
+ // event loop — and the #850 watchdog heartbeat — for the whole store.
2033
+ // The file was NEVER one atomic transaction (each insert call has its
2034
+ // own), and the files-table record still lands last, so crash recovery
2035
+ // is unchanged: a partially-stored file has no record and re-indexes.
2036
+ const STORE_CHUNK = 2000;
2037
+ const contentHash = hashContent(content);
2038
+ // Check if file already exists and hasn't changed
2039
+ const existingFile = this.queries.getFileByPath(filePath);
2040
+ if (existingFile && existingFile.contentHash === contentHash) {
2041
+ return; // No changes
2042
+ }
2043
+ // Snapshot incoming cross-file edges BEFORE deleting this file's nodes.
2044
+ // `deleteFile` cascades to delete every edge whose source OR target is a
2045
+ // node in this file (edges.FK ... ON DELETE CASCADE). Edges whose SOURCE is
2046
+ // in this file are re-emitted by the extractor below, but edges whose SOURCE
2047
+ // is in a *different* (unchanged) file are not — they would be silently
2048
+ // dropped, which is issue #899: re-indexing a callee file severs `calls`/
2049
+ // `references` edges from callers that import it via module-attribute
2050
+ // access (`pkg.mod.fn(...)`).
2051
+ //
2052
+ // We snapshot the edge plus the target node's (name, kind) so we can
2053
+ // re-resolve to the re-indexed target's NEW id. Node ids are
2054
+ // `sha256(filePath:kind:name:line)`, so any line shift in the callee file
2055
+ // (e.g. a docstring-only edit above the symbol) changes every target id and
2056
+ // a naive re-insert by old id would silently drop every edge. Matching by
2057
+ // (filePath, kind, name) is stable across line shifts; if the symbol was
2058
+ // renamed/removed, no match is found and the edge stays dropped (correct).
2059
+ const crossFileIncomingEdges = existingFile
2060
+ ? this.queries.getCrossFileIncomingEdgesWithTarget(filePath)
2061
+ : [];
2062
+ // Delete existing data for this file
2063
+ if (existingFile) {
2064
+ this.queries.deleteFile(filePath);
2065
+ }
2066
+ // Filter out nodes with missing required fields before insertion.
2067
+ // This prevents FK violations when edges reference nodes that would
2068
+ // be silently skipped by insertNode() (see issue #42).
2069
+ const validNodes = result.nodes.filter((n) => n.id && n.kind && n.name && n.filePath && n.language);
2070
+ // Insert nodes (chunked — see STORE_CHUNK above)
2071
+ for (let i = 0; i < validNodes.length; i += STORE_CHUNK) {
2072
+ this.queries.insertNodes(validNodes.slice(i, i + STORE_CHUNK));
2073
+ await onYield?.();
2074
+ }
2075
+ // Filter edges to only reference nodes that were actually inserted
2076
+ if (result.edges.length > 0) {
2077
+ const insertedIds = new Set(validNodes.map((n) => n.id));
2078
+ const validEdges = result.edges.filter((e) => insertedIds.has(e.source) && insertedIds.has(e.target));
2079
+ for (let i = 0; i < validEdges.length; i += STORE_CHUNK) {
2080
+ this.queries.insertEdges(validEdges.slice(i, i + STORE_CHUNK));
2081
+ await onYield?.();
2082
+ }
2083
+ }
2084
+ // Re-insert cross-file incoming edges snapshotted before the delete,
2085
+ // re-resolving each edge's target to the re-indexed node's new id by
2086
+ // (filePath, kind, name). Node ids include the source line, so any line
2087
+ // shift in the callee file (e.g. a docstring-only edit above the symbol)
2088
+ // changes every target id and a naive re-insert by old id would drop them
2089
+ // all. `insertEdges` still filters to endpoints that exist. This closes
2090
+ // the #899 edge-drop on `sync`.
2091
+ //
2092
+ // Edges whose callee (target) was renamed/removed during the re-index (no
2093
+ // match in `newNodesByKindName`) are not silently dropped anymore: each is
2094
+ // resurrected as its ORIGINAL unresolved ref (stamped on the edge as
2095
+ // metadata.refName/refKind at creation) so the same sync's resolution
2096
+ // sweep can rebind it to an alternative definition elsewhere, or park it
2097
+ // as status='failed' to be retried when the symbol reappears — the
2098
+ // removal-side counterpart of #1240. Edges without refName (built before
2099
+ // the stamp existed, or synthesized) still drop silently: reconstructing
2100
+ // a ref from the target's plain name would strip receiver/qualifier
2101
+ // context and risk a rebind a full re-index would never make.
2102
+ if (crossFileIncomingEdges.length > 0) {
2103
+ const newNodesByKindName = new Map();
2104
+ for (const n of validNodes) {
2105
+ newNodesByKindName.set(`${n.kind}\0${n.name}`, n.id);
2106
+ }
2107
+ const reinserted = [];
2108
+ const resurrected = [];
2109
+ for (const e of crossFileIncomingEdges) {
2110
+ const newTargetId = newNodesByKindName.get(`${e.targetKind}\0${e.targetName}`);
2111
+ if (newTargetId) {
2112
+ reinserted.push({ source: e.source, target: newTargetId, kind: e.kind, metadata: e.metadata, line: e.line, column: e.column, provenance: e.provenance });
2113
+ }
2114
+ else {
2115
+ const ref = resurrectRefFromDroppedEdge(e);
2116
+ if (ref)
2117
+ resurrected.push(ref);
2118
+ }
2119
+ }
2120
+ if (reinserted.length > 0) {
2121
+ this.queries.insertEdges(reinserted);
2122
+ }
2123
+ if (resurrected.length > 0) {
2124
+ this.queries.insertUnresolvedRefsBatch(resurrected);
2125
+ }
2126
+ }
2127
+ // Insert unresolved references in batch with denormalized filePath/language
2128
+ if (result.unresolvedReferences.length > 0) {
2129
+ const insertedIds = new Set(validNodes.map((n) => n.id));
2130
+ const refsWithContext = result.unresolvedReferences
2131
+ .filter((ref) => insertedIds.has(ref.fromNodeId))
2132
+ .map((ref) => ({
2133
+ ...ref,
2134
+ filePath: ref.filePath ?? filePath,
2135
+ language: ref.language ?? language,
2136
+ }));
2137
+ for (let i = 0; i < refsWithContext.length; i += STORE_CHUNK) {
2138
+ this.queries.insertUnresolvedRefsBatch(refsWithContext.slice(i, i + STORE_CHUNK));
2139
+ await onYield?.();
2140
+ }
2141
+ }
2142
+ // Insert file record
2143
+ const fileRecord = {
2144
+ path: filePath,
2145
+ contentHash,
2146
+ language,
2147
+ size: stats.size,
2148
+ modifiedAt: stats.mtimeMs,
2149
+ indexedAt: Date.now(),
2150
+ nodeCount: result.nodes.length,
2151
+ errors: result.errors.length > 0 ? result.errors : undefined,
2152
+ };
2153
+ this.queries.upsertFile(fileRecord);
2154
+ }
2155
+ /**
2156
+ * Sync the index with the current file state.
2157
+ *
2158
+ * Change detection is filesystem-based, never git: a (size, mtime) stat
2159
+ * pre-filter skips unchanged files, then a content-hash compare confirms real
2160
+ * changes. This works in non-git projects and catches committed changes from
2161
+ * `git pull`/`checkout`/`merge`/`rebase` that `git status` cannot see.
2162
+ */
2163
+ async sync(onProgress) {
2164
+ await (0, grammars_1.initGrammars)(); // Initialize WASM runtime (grammars loaded lazily below)
2165
+ const startTime = Date.now();
2166
+ let filesChecked = 0;
2167
+ let filesAdded = 0;
2168
+ let filesModified = 0;
2169
+ let filesRemoved = 0;
2170
+ let nodesUpdated = 0;
2171
+ const changedFilePaths = [];
2172
+ onProgress?.({
2173
+ phase: 'scanning',
2174
+ current: 0,
2175
+ total: 0,
2176
+ });
2177
+ const filesToIndex = [];
2178
+ // === Filesystem reconcile (git-independent) ===
2179
+ // The source of truth for "what changed" is the filesystem vs the indexed
2180
+ // state — never git. We enumerate the current source files and reconcile
2181
+ // each against the DB. A cheap (size, mtime) stat pre-filter skips unchanged
2182
+ // files without reading or hashing them, so the expensive read+hash+parse
2183
+ // only runs for files that actually changed. This catches edits/adds/deletes
2184
+ // whether or not the project uses git, and crucially also catches committed
2185
+ // changes from `git pull`/`checkout`/`merge`/`rebase` — which `git status`
2186
+ // cannot see, because the working tree is clean afterward.
2187
+ const tSyncScan = Date.now();
2188
+ const currentFiles = await scanDirectoryAsync(this.rootDir);
2189
+ if (process.env.CODEGRAPH_SYNTH_TIMINGS)
2190
+ console.error(`[phase-timing] sync-scan: ${Date.now() - tSyncScan}ms (${currentFiles.length} files)`);
2191
+ filesChecked = currentFiles.length;
2192
+ const currentSet = new Set(currentFiles);
2193
+ const tTracked = Date.now();
2194
+ const trackedFiles = this.queries.getAllFiles();
2195
+ if (process.env.CODEGRAPH_SYNTH_TIMINGS)
2196
+ console.error(`[phase-timing] sync-tracked-load: ${Date.now() - tTracked}ms (${trackedFiles.length} tracked)`);
2197
+ const trackedMap = new Map();
2198
+ for (const f of trackedFiles) {
2199
+ trackedMap.set(f.path, f);
2200
+ }
2201
+ // Removals: tracked in the DB but no longer a present source file. Check the
2202
+ // filesystem directly — `scanDirectory` (via `git ls-files`) still lists a
2203
+ // file deleted from disk but not yet staged, so set membership alone misses it.
2204
+ // `reconcileChecks` drives the cooperative yield shared with the adds/mods loop
2205
+ // below (see SYNC_RECONCILE_YIELD_INTERVAL / issue #905).
2206
+ let reconcileChecks = 0;
2207
+ for (const tracked of trackedFiles) {
2208
+ if (!currentSet.has(tracked.path) || !fs.existsSync(path.join(this.rootDir, tracked.path))) {
2209
+ // Before the cascade deletes them, resurrect incoming cross-file
2210
+ // resolution edges as their original refs (#1240 removal case): the
2211
+ // callers live in files this sync will NOT revisit, so this is their
2212
+ // only chance to rebind to an alternative definition — or to park as
2213
+ // failed until the symbol reappears somewhere. (A deleted file whose
2214
+ // CALLERS are also being deleted is fine: their nodes cascade later
2215
+ // in this loop and take the resurrected rows with them.)
2216
+ const incoming = this.queries.getCrossFileIncomingEdgesWithTarget(tracked.path);
2217
+ if (incoming.length > 0) {
2218
+ const resurrected = incoming
2219
+ .map((e) => resurrectRefFromDroppedEdge(e))
2220
+ .filter((r) => r !== null);
2221
+ if (resurrected.length > 0) {
2222
+ this.queries.insertUnresolvedRefsBatch(resurrected);
2223
+ }
2224
+ }
2225
+ this.queries.deleteFile(tracked.path);
2226
+ filesRemoved++;
2227
+ }
2228
+ if (++reconcileChecks % SYNC_RECONCILE_YIELD_INTERVAL === 0) {
2229
+ await new Promise((resolve) => setImmediate(resolve));
2230
+ }
2231
+ }
2232
+ // Adds / modifications.
2233
+ for (const filePath of currentFiles) {
2234
+ // Same cooperative yield as the removals loop — this is the other O(files)
2235
+ // synchronous-stat loop that wedges the main thread on a large repo (#905).
2236
+ // Yield at the top of the body so the `continue` fast-paths below still hit it.
2237
+ if (++reconcileChecks % SYNC_RECONCILE_YIELD_INTERVAL === 0) {
2238
+ await new Promise((resolve) => setImmediate(resolve));
2239
+ }
2240
+ const fullPath = path.join(this.rootDir, filePath);
2241
+ const tracked = trackedMap.get(filePath);
2242
+ // Cheap pre-filter: an already-indexed file whose size AND mtime both match
2243
+ // the DB is unchanged — skip it without reading or hashing. (A content
2244
+ // change that preserves both exactly is the blind spot every mtime-based
2245
+ // incremental tool accepts; `index --force` is the escape hatch. Git bumps
2246
+ // mtime on every file it writes during checkout/merge, so pulls are caught.)
2247
+ if (tracked) {
2248
+ try {
2249
+ const stat = fs.statSync(fullPath);
2250
+ if (stat.size === tracked.size && Math.floor(stat.mtimeMs) === Math.floor(tracked.modifiedAt)) {
2251
+ continue;
2252
+ }
2253
+ }
2254
+ catch (error) {
2255
+ (0, errors_1.logDebug)('Skipping unstattable file during sync', { filePath, error: String(error) });
2256
+ continue;
2257
+ }
2258
+ }
2259
+ // New, or size/mtime changed — read + hash to confirm a real content change.
2260
+ let content;
2261
+ try {
2262
+ content = fs.readFileSync(fullPath, 'utf-8');
2263
+ }
2264
+ catch (error) {
2265
+ (0, errors_1.logDebug)('Skipping unreadable file during sync', { filePath, error: String(error) });
2266
+ continue;
2267
+ }
2268
+ const contentHash = hashContent(content);
2269
+ if (!tracked) {
2270
+ filesToIndex.push(filePath);
2271
+ changedFilePaths.push(filePath);
2272
+ filesAdded++;
2273
+ }
2274
+ else if (tracked.contentHash !== contentHash) {
2275
+ filesToIndex.push(filePath);
2276
+ changedFilePaths.push(filePath);
2277
+ filesModified++;
2278
+ }
2279
+ }
2280
+ // Load only grammars needed for changed files
2281
+ if (filesToIndex.length > 0) {
2282
+ const overrides = (0, project_config_1.loadExtensionOverrides)(this.rootDir);
2283
+ const neededLanguages = [...new Set(filesToIndex.map((f) => (0, grammars_1.detectLanguage)(f, undefined, overrides)))];
2284
+ // .h files default to 'c' but may be C++ — ensure cpp grammar is loaded
2285
+ if (neededLanguages.includes('c') && !neededLanguages.includes('cpp')) {
2286
+ neededLanguages.push('cpp');
2287
+ }
2288
+ await (0, grammars_1.loadGrammarsForLanguages)(neededLanguages);
2289
+ }
2290
+ // Index changed files
2291
+ const total = filesToIndex.length;
2292
+ for (let i = 0; i < filesToIndex.length; i++) {
2293
+ const filePath = filesToIndex[i];
2294
+ onProgress?.({
2295
+ phase: 'parsing',
2296
+ current: i + 1,
2297
+ total,
2298
+ currentFile: filePath,
2299
+ });
2300
+ const result = await this.indexFile(filePath);
2301
+ nodesUpdated += result.nodes.length;
2302
+ }
2303
+ return {
2304
+ filesChecked,
2305
+ filesAdded,
2306
+ filesModified,
2307
+ filesRemoved,
2308
+ nodesUpdated,
2309
+ durationMs: Date.now() - startTime,
2310
+ changedFilePaths: changedFilePaths.length > 0 ? changedFilePaths : undefined,
2311
+ };
2312
+ }
2313
+ /**
2314
+ * Get files that have changed since last index.
2315
+ * Uses git status as a fast path when available, falling back to full scan.
2316
+ */
2317
+ getChangedFiles() {
2318
+ const gitChanges = getGitChangedFiles(this.rootDir);
2319
+ if (gitChanges) {
2320
+ // === Git fast path ===
2321
+ const added = [];
2322
+ const modified = [];
2323
+ const removed = [];
2324
+ // Deleted files — only report if tracked in DB
2325
+ for (const filePath of gitChanges.deleted) {
2326
+ const tracked = this.queries.getFileByPath(filePath);
2327
+ if (tracked) {
2328
+ removed.push(filePath);
2329
+ }
2330
+ }
2331
+ // Modified + added files — read + hash, compare with DB. Untracked (`??`)
2332
+ // files stay untracked in git even after indexing, so they must be
2333
+ // hash-compared like modified files instead of always counting as added —
2334
+ // otherwise status reports them as pending forever. (See issue #206.)
2335
+ for (const filePath of [...gitChanges.modified, ...gitChanges.added]) {
2336
+ const fullPath = path.join(this.rootDir, filePath);
2337
+ let content;
2338
+ try {
2339
+ content = fs.readFileSync(fullPath, 'utf-8');
2340
+ }
2341
+ catch (error) {
2342
+ (0, errors_1.logDebug)('Skipping unreadable file while detecting changes', { filePath, error: String(error) });
2343
+ continue;
2344
+ }
2345
+ const contentHash = hashContent(content);
2346
+ const tracked = this.queries.getFileByPath(filePath);
2347
+ if (!tracked) {
2348
+ added.push(filePath);
2349
+ }
2350
+ else if (tracked.contentHash !== contentHash) {
2351
+ modified.push(filePath);
2352
+ }
2353
+ }
2354
+ return { added, modified, removed };
2355
+ }
2356
+ // === Fallback: full scan (non-git project or git failure) ===
2357
+ const currentFiles = new Set(scanDirectory(this.rootDir));
2358
+ const trackedFiles = this.queries.getAllFiles();
2359
+ // Build Map for O(1) lookups
2360
+ const trackedMap = new Map();
2361
+ for (const f of trackedFiles) {
2362
+ trackedMap.set(f.path, f);
2363
+ }
2364
+ const added = [];
2365
+ const modified = [];
2366
+ const removed = [];
2367
+ // Find removed files
2368
+ for (const tracked of trackedFiles) {
2369
+ if (!currentFiles.has(tracked.path)) {
2370
+ removed.push(tracked.path);
2371
+ }
2372
+ }
2373
+ // Find added and modified files
2374
+ for (const filePath of currentFiles) {
2375
+ const fullPath = path.join(this.rootDir, filePath);
2376
+ let content;
2377
+ try {
2378
+ content = fs.readFileSync(fullPath, 'utf-8');
2379
+ }
2380
+ catch (error) {
2381
+ (0, errors_1.logDebug)('Skipping unreadable file while detecting changes', { filePath, error: String(error) });
2382
+ continue;
2383
+ }
2384
+ const contentHash = hashContent(content);
2385
+ const tracked = trackedMap.get(filePath);
2386
+ if (!tracked) {
2387
+ added.push(filePath);
2388
+ }
2389
+ else if (tracked.contentHash !== contentHash) {
2390
+ modified.push(filePath);
2391
+ }
2392
+ }
2393
+ return { added, modified, removed };
2394
+ }
2395
+ }
2396
+ exports.ExtractionOrchestrator = ExtractionOrchestrator;
2397
+ // Re-export useful types and functions
2398
+ var tree_sitter_2 = require("./tree-sitter");
2399
+ Object.defineProperty(exports, "extractFromSource", { enumerable: true, get: function () { return tree_sitter_2.extractFromSource; } });
2400
+ var grammars_2 = require("./grammars");
2401
+ Object.defineProperty(exports, "detectLanguage", { enumerable: true, get: function () { return grammars_2.detectLanguage; } });
2402
+ Object.defineProperty(exports, "isSourceFile", { enumerable: true, get: function () { return grammars_2.isSourceFile; } });
2403
+ Object.defineProperty(exports, "isLanguageSupported", { enumerable: true, get: function () { return grammars_2.isLanguageSupported; } });
2404
+ Object.defineProperty(exports, "isGrammarLoaded", { enumerable: true, get: function () { return grammars_2.isGrammarLoaded; } });
2405
+ Object.defineProperty(exports, "getSupportedLanguages", { enumerable: true, get: function () { return grammars_2.getSupportedLanguages; } });
2406
+ Object.defineProperty(exports, "initGrammars", { enumerable: true, get: function () { return grammars_2.initGrammars; } });
2407
+ Object.defineProperty(exports, "loadGrammarsForLanguages", { enumerable: true, get: function () { return grammars_2.loadGrammarsForLanguages; } });
2408
+ Object.defineProperty(exports, "loadAllGrammars", { enumerable: true, get: function () { return grammars_2.loadAllGrammars; } });
2409
+ //# sourceMappingURL=index.js.map