@quolu/lattice 0.1.0

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