codegraph-java 0.1.0

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