scip-query 0.23.0 → 0.26.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 (650) hide show
  1. package/CHANGELOG.md +491 -2
  2. package/README.md +111 -122
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/by-kind-PRVFAGTQ.js +2 -0
  5. package/dist/call-graph-DVPAQV2F.js +2 -0
  6. package/dist/call-graph-evidence-CUtj8V2I.d.ts +19 -0
  7. package/dist/chunk-2FSBGL5P.js +2 -0
  8. package/dist/chunk-2HLAFUCY.js +2 -0
  9. package/dist/chunk-2IWUT6CJ.js +3 -0
  10. package/dist/chunk-2KNN7GTQ.js +2 -0
  11. package/dist/chunk-2LHXRE2B.js +8 -0
  12. package/dist/{chunk-EG2CPZMJ.js → chunk-2YXE77TJ.js} +2 -2
  13. package/dist/chunk-36SGVCGX.js +2 -0
  14. package/dist/chunk-3ABBFPTP.js +2 -0
  15. package/dist/chunk-3IVFU4FD.js +3 -0
  16. package/dist/chunk-3JIQS44J.js +7 -0
  17. package/dist/chunk-3ZRB6DNK.js +7 -0
  18. package/dist/{chunk-6YTSKJJ3.js → chunk-42EOW5VI.js} +1 -1
  19. package/dist/{chunk-6I6L7Z62.js → chunk-4BHGBMNO.js} +2 -2
  20. package/dist/chunk-4BP3UBDG.js +2 -0
  21. package/dist/chunk-4D6RO7G4.js +2 -0
  22. package/dist/chunk-4FEWQ6RH.js +2 -0
  23. package/dist/chunk-4IGEOBG7.js +2 -0
  24. package/dist/chunk-4QZXBUKC.js +2 -0
  25. package/dist/chunk-4WBDEVX2.js +4 -0
  26. package/dist/chunk-4WCUBZU3.js +8 -0
  27. package/dist/chunk-4WTUBQ36.js +40 -0
  28. package/dist/chunk-4XQ4O6IM.js +3 -0
  29. package/dist/chunk-55UQAMZO.js +4 -0
  30. package/dist/chunk-5D2LVK7O.js +125 -0
  31. package/dist/chunk-5IYJ56TT.js +2 -0
  32. package/dist/chunk-5PLMJC7Q.js +2 -0
  33. package/dist/chunk-5TNQJUR2.js +5 -0
  34. package/dist/chunk-62BDNPMI.js +2 -0
  35. package/dist/chunk-64DZ5TXR.js +7 -0
  36. package/dist/chunk-65245JCM.js +2 -0
  37. package/dist/chunk-6FFVZZL4.js +2 -0
  38. package/dist/chunk-6KO5JHAR.js +2 -0
  39. package/dist/chunk-6LRXOOSX.js +2 -0
  40. package/dist/chunk-6LSEIIF7.js +2 -0
  41. package/dist/chunk-6YMNWD3H.js +6 -0
  42. package/dist/chunk-72AD6ZRR.js +5 -0
  43. package/dist/chunk-73AAKPUC.js +4 -0
  44. package/dist/chunk-76CZ77DF.js +2 -0
  45. package/dist/chunk-7VPEEAAG.js +2 -0
  46. package/dist/chunk-7WTPQ4NX.js +14 -0
  47. package/dist/chunk-7Y5T6XDP.js +2 -0
  48. package/dist/chunk-A2IIGFMJ.js +5 -0
  49. package/dist/chunk-AB5KCTEV.js +2 -0
  50. package/dist/chunk-AC566WBP.js +6 -0
  51. package/dist/chunk-AGWFSTXC.js +3 -0
  52. package/dist/chunk-AOSIYPTA.js +2 -0
  53. package/dist/chunk-AUVEWPIF.js +2 -0
  54. package/dist/chunk-B56T42J3.js +25 -0
  55. package/dist/chunk-BIQEF5NE.js +2 -0
  56. package/dist/chunk-BL6XJKTA.js +3 -0
  57. package/dist/chunk-BMKOQJRI.js +2 -0
  58. package/dist/chunk-BOZ4EXBB.js +3 -0
  59. package/dist/chunk-BUTWYEPH.js +2 -0
  60. package/dist/chunk-BZB4QPIP.js +2 -0
  61. package/dist/{chunk-ILTDAWEF.js → chunk-CE357GEE.js} +4 -4
  62. package/dist/chunk-CFN45HFP.js +2 -0
  63. package/dist/chunk-CFYMZFXT.js +368 -0
  64. package/dist/chunk-CN5EH7O3.js +2 -0
  65. package/dist/chunk-D254DNNQ.js +4 -0
  66. package/dist/chunk-D3FDISIC.js +2 -0
  67. package/dist/chunk-D3NX5XIE.js +3 -0
  68. package/dist/chunk-DA7RPPDF.js +3 -0
  69. package/dist/chunk-DDMC3FON.js +3 -0
  70. package/dist/chunk-DIO3FUSG.js +2 -0
  71. package/dist/chunk-DJ2NNSUK.js +3 -0
  72. package/dist/chunk-DKYQIM3C.js +18 -0
  73. package/dist/{chunk-JTQVMR42.js → chunk-DOOEL2IV.js} +2 -2
  74. package/dist/chunk-DVFP6PZI.js +2 -0
  75. package/dist/chunk-E3FDPXZK.js +2 -0
  76. package/dist/chunk-E7YNJLCB.js +2 -0
  77. package/dist/chunk-EFGW5JPH.js +2 -0
  78. package/dist/chunk-EJVTR244.js +13 -0
  79. package/dist/chunk-EOV7RTRZ.js +2 -0
  80. package/dist/chunk-ETOIKRHO.js +2 -0
  81. package/dist/chunk-EYK3ZAO2.js +3 -0
  82. package/dist/chunk-F2V2LPET.js +52 -0
  83. package/dist/chunk-F4LUHJTF.js +2 -0
  84. package/dist/chunk-F4PUT6IT.js +2 -0
  85. package/dist/chunk-F56GCXXS.js +5 -0
  86. package/dist/chunk-FC2EVQRM.js +2 -0
  87. package/dist/chunk-FL7NBMHP.js +3 -0
  88. package/dist/chunk-FMRN2TRL.js +3 -0
  89. package/dist/chunk-FVULPZDF.js +20 -0
  90. package/dist/chunk-GCKCF5FL.js +43 -0
  91. package/dist/chunk-GH2PYF46.js +2 -0
  92. package/dist/chunk-GHJAGXIP.js +2 -0
  93. package/dist/{chunk-WIWY3CRX.js → chunk-GMVSHUKZ.js} +2 -2
  94. package/dist/chunk-GS6KDO4R.js +2 -0
  95. package/dist/chunk-GUUBXNN7.js +2 -0
  96. package/dist/chunk-GVWX5T43.js +80 -0
  97. package/dist/chunk-GZKFETP5.js +2 -0
  98. package/dist/chunk-H4EQHO6J.js +9 -0
  99. package/dist/chunk-H73WY2RM.js +2 -0
  100. package/dist/chunk-H75GSPRV.js +60 -0
  101. package/dist/chunk-HDR3AHSV.js +61 -0
  102. package/dist/chunk-HQBSL74Y.js +2 -0
  103. package/dist/chunk-HRRFKWPZ.js +2 -0
  104. package/dist/chunk-HXENDJC6.js +2 -0
  105. package/dist/chunk-IIBAZNSW.js +21 -0
  106. package/dist/chunk-INLMWEUU.js +12 -0
  107. package/dist/chunk-IWQPAF4F.js +2 -0
  108. package/dist/chunk-IZJ6YUKP.js +35 -0
  109. package/dist/chunk-J2TMAIN5.js +60 -0
  110. package/dist/chunk-J5FJMODQ.js +142 -0
  111. package/dist/chunk-J7HZPIO3.js +2 -0
  112. package/dist/chunk-JEVRKFRL.js +2 -0
  113. package/dist/chunk-JFXSGAEB.js +30 -0
  114. package/dist/chunk-JVRTHGFS.js +3 -0
  115. package/dist/chunk-JYWEX7RR.js +360 -0
  116. package/dist/chunk-K3YL22N6.js +2 -0
  117. package/dist/chunk-K4CN7GXK.js +12 -0
  118. package/dist/chunk-K5TBVXU4.js +30 -0
  119. package/dist/chunk-KDDIE2DP.js +9 -0
  120. package/dist/chunk-KHWRRPV4.js +2 -0
  121. package/dist/chunk-KI6NBKDY.js +14 -0
  122. package/dist/chunk-KU3QRSTH.js +2 -0
  123. package/dist/chunk-KZBJWZJB.js +2 -0
  124. package/dist/chunk-L7GFM3NP.js +3 -0
  125. package/dist/chunk-LMO6PK3V.js +35 -0
  126. package/dist/chunk-LN4YXJJU.js +2 -0
  127. package/dist/chunk-LOVIZBJ4.js +43 -0
  128. package/dist/chunk-LPCRK4A2.js +11 -0
  129. package/dist/chunk-MMHZKBFA.js +2 -0
  130. package/dist/{chunk-M2O5NY6W.js → chunk-MOQQBQRD.js} +2 -2
  131. package/dist/chunk-N2WN6I3L.js +2 -0
  132. package/dist/chunk-N3ORQT7L.js +2 -0
  133. package/dist/chunk-NAZ3RAIW.js +2 -0
  134. package/dist/chunk-NDUNO5JQ.js +2 -0
  135. package/dist/chunk-NEIWRNAZ.js +4 -0
  136. package/dist/chunk-NJJMVD65.js +2 -0
  137. package/dist/chunk-NLOQOBXI.js +20 -0
  138. package/dist/chunk-NOLZOVCU.js +2 -0
  139. package/dist/chunk-NOWINRRN.js +2 -0
  140. package/dist/chunk-NZAXKGRL.js +16 -0
  141. package/dist/chunk-O2C4UILI.js +2 -0
  142. package/dist/chunk-O3RHA6ZT.js +3 -0
  143. package/dist/chunk-O4UZSPPI.js +3 -0
  144. package/dist/chunk-OGFV2BUX.js +2 -0
  145. package/dist/chunk-OZCJXZK6.js +499 -0
  146. package/dist/chunk-P6ODM7BY.js +2 -0
  147. package/dist/{chunk-XBGWL66K.js → chunk-PAVGPRHJ.js} +2 -2
  148. package/dist/chunk-PH52RA7D.js +2 -0
  149. package/dist/chunk-PKN354TH.js +3 -0
  150. package/dist/chunk-PWOASWEG.js +11 -0
  151. package/dist/chunk-QIWXRW72.js +2 -0
  152. package/dist/chunk-QJRMOK5N.js +2 -0
  153. package/dist/{chunk-YXPUP5G2.js → chunk-QOIXNWQR.js} +2 -2
  154. package/dist/chunk-QXEUDXBT.js +3 -0
  155. package/dist/chunk-QYUVVBMR.js +6 -0
  156. package/dist/chunk-QZ7KQZRN.js +2 -0
  157. package/dist/chunk-R6LQBUDH.js +2 -0
  158. package/dist/chunk-RBS42E55.js +20 -0
  159. package/dist/chunk-RSJKPCFX.js +26 -0
  160. package/dist/chunk-S6CZA3MV.js +2 -0
  161. package/dist/chunk-STMVAHJP.js +2 -0
  162. package/dist/chunk-SYVPTTVW.js +2 -0
  163. package/dist/chunk-T3I6NHBH.js +2 -0
  164. package/dist/chunk-T6DK3ZP7.js +2 -0
  165. package/dist/chunk-TKD34PHN.js +4 -0
  166. package/dist/chunk-TNNQFH7W.js +2 -0
  167. package/dist/chunk-TNV7SSUF.js +2 -0
  168. package/dist/chunk-TO7ZR3EH.js +8 -0
  169. package/dist/chunk-TOU3CHK4.js +2 -0
  170. package/dist/chunk-TRBI4UKT.js +2 -0
  171. package/dist/chunk-TZCVNCAN.js +4 -0
  172. package/dist/chunk-U4LZA5LL.js +3 -0
  173. package/dist/chunk-U5RIG3JP.js +3 -0
  174. package/dist/chunk-UP5KXN2I.js +2 -0
  175. package/dist/chunk-UQFR3NDH.js +5 -0
  176. package/dist/chunk-UXYXF7GV.js +2 -0
  177. package/dist/chunk-VB3GOKOS.js +2 -0
  178. package/dist/chunk-VF5JZICY.js +2 -0
  179. package/dist/chunk-VTY3VK6E.js +2 -0
  180. package/dist/chunk-VX2O4RIS.js +2 -0
  181. package/dist/chunk-WKPV2TDZ.js +2 -0
  182. package/dist/chunk-WOFQ5DTB.js +2 -0
  183. package/dist/chunk-WS4C6TCK.js +2 -0
  184. package/dist/chunk-WXU3DGPU.js +2 -0
  185. package/dist/chunk-X6RMKHJQ.js +81 -0
  186. package/dist/{chunk-4ILJCCXV.js → chunk-XHMN6ZX7.js} +2 -2
  187. package/dist/chunk-XHTVFLWW.js +2 -0
  188. package/dist/chunk-XKIDJCIK.js +2 -0
  189. package/dist/chunk-XTYTYZPT.js +2 -0
  190. package/dist/chunk-Y2JHHTTA.js +2 -0
  191. package/dist/chunk-YGVRMGYN.js +4 -0
  192. package/dist/chunk-YNQCGEQE.js +2 -0
  193. package/dist/chunk-YOQVEXVE.js +14 -0
  194. package/dist/chunk-YRT2WLYY.js +2 -0
  195. package/dist/chunk-YTAP5Y2G.js +2 -0
  196. package/dist/chunk-YTYWI7VB.js +2 -0
  197. package/dist/chunk-YULZRALL.js +2 -0
  198. package/dist/chunk-Z33WQG4Q.js +2 -0
  199. package/dist/chunk-ZGTYGDMF.js +16 -0
  200. package/dist/chunk-ZHMRSZFD.js +43 -0
  201. package/dist/chunk-ZHSP366W.js +10 -0
  202. package/dist/chunk-ZIBYCYKK.js +7 -0
  203. package/dist/{chunk-GAS2LJMP.js → chunk-ZLADLUE6.js} +3 -3
  204. package/dist/chunk-ZO4YXUT6.js +4 -0
  205. package/dist/{chunk-HYO3NP5Q.js → chunk-ZR4HBC2H.js} +2 -2
  206. package/dist/cli-main.js +6 -6
  207. package/dist/cli.js +1 -1
  208. package/dist/{code-B17qEMbt.d.ts → code-BNyrCF3_.d.ts} +3 -2
  209. package/dist/code-IL5WH3NZ.js +2 -0
  210. package/dist/code-result-json-ANTBEDFP.js +4 -0
  211. package/dist/command-descriptors-HEEMDHTU.js +222 -0
  212. package/dist/deps-EOWFC6FD.js +2 -0
  213. package/dist/direct-navigation-Y5B6OSIQ.js +3 -0
  214. package/dist/{exploration-topology-BG4v30HZ.d.ts → exploration-topology-CSgEyAz-.d.ts} +3 -1
  215. package/dist/files-K4AI3JUM.js +2 -0
  216. package/dist/frontend-profile-roles-D7eCum8P.d.ts +10 -0
  217. package/dist/{health-CPp2Jf1Z.d.ts → health-BtfmNrfa.d.ts} +58 -74
  218. package/dist/hierarchy-6W5NDIFI.js +2 -0
  219. package/dist/imports-WH365QY4.js +2 -0
  220. package/dist/index.d.ts +13 -1
  221. package/dist/index.js +1 -1
  222. package/dist/members-K3PHMF5S.js +2 -0
  223. package/dist/methods-E7KVMBX4.js +2 -0
  224. package/dist/output-continuation-command-BJSY67SN.js +3 -0
  225. package/dist/output-pagination-UZJ5ACIX.js +24 -0
  226. package/dist/postinstall.js +1 -1
  227. package/dist/project-reindex-EP24WT4X.js +3 -0
  228. package/dist/queries/affected.js +1 -1
  229. package/dist/queries/architecture.d.ts +15 -4
  230. package/dist/queries/architecture.js +1 -1
  231. package/dist/queries/bottlenecks.js +1 -1
  232. package/dist/queries/by-kind.js +1 -1
  233. package/dist/queries/call-graph.d.ts +3 -1
  234. package/dist/queries/call-graph.js +1 -1
  235. package/dist/queries/change-surface.d.ts +1 -0
  236. package/dist/queries/change-surface.js +1 -1
  237. package/dist/queries/cleanup-plan.d.ts +3 -3
  238. package/dist/queries/cleanup-plan.js +1 -1
  239. package/dist/queries/co-change.d.ts +20 -2
  240. package/dist/queries/co-change.js +1 -1
  241. package/dist/queries/code.d.ts +1 -1
  242. package/dist/queries/code.js +1 -1
  243. package/dist/queries/complexity.d.ts +6 -3
  244. package/dist/queries/complexity.js +1 -1
  245. package/dist/queries/context.d.ts +1 -7
  246. package/dist/queries/context.js +1 -1
  247. package/dist/queries/coupling.js +1 -1
  248. package/dist/queries/cycles.js +1 -1
  249. package/dist/queries/dead.d.ts +2 -0
  250. package/dist/queries/dead.js +1 -1
  251. package/dist/queries/decorative-checkers.js +1 -1
  252. package/dist/queries/dependence-slice.d.ts +46 -22
  253. package/dist/queries/dependence-slice.js +1 -1
  254. package/dist/queries/dependency-depth.d.ts +1 -7
  255. package/dist/queries/dependency-depth.js +1 -1
  256. package/dist/queries/deps.js +1 -1
  257. package/dist/queries/diff-impact.d.ts +3 -1
  258. package/dist/queries/diff-impact.js +1 -1
  259. package/dist/queries/doc-drift.js +1 -1
  260. package/dist/queries/drift.d.ts +1 -1
  261. package/dist/queries/drift.js +1 -1
  262. package/dist/queries/duplicate-bodies.d.ts +29 -2
  263. package/dist/queries/duplicate-bodies.js +1 -1
  264. package/dist/queries/entry-map.d.ts +2 -4
  265. package/dist/queries/entry-map.js +1 -1
  266. package/dist/queries/evidence.d.ts +121 -61
  267. package/dist/queries/evidence.js +1 -1
  268. package/dist/queries/fan.js +1 -1
  269. package/dist/queries/files.js +1 -1
  270. package/dist/queries/health.d.ts +1 -1
  271. package/dist/queries/health.js +1 -1
  272. package/dist/queries/hierarchy.d.ts +2 -2
  273. package/dist/queries/hierarchy.js +1 -1
  274. package/dist/queries/hotspots.d.ts +1 -1
  275. package/dist/queries/hotspots.js +1 -1
  276. package/dist/queries/imports.d.ts +1 -0
  277. package/dist/queries/imports.js +1 -1
  278. package/dist/queries/incomplete-migration.d.ts +3 -3
  279. package/dist/queries/incomplete-migration.js +1 -1
  280. package/dist/queries/index.d.ts +17 -65
  281. package/dist/queries/index.js +1 -1
  282. package/dist/queries/locality-candidates.d.ts +4 -4
  283. package/dist/queries/locality-candidates.js +1 -1
  284. package/dist/queries/members.d.ts +2 -2
  285. package/dist/queries/members.js +1 -1
  286. package/dist/queries/methods.js +1 -1
  287. package/dist/queries/not-implemented.d.ts +2 -6
  288. package/dist/queries/not-implemented.js +1 -1
  289. package/dist/queries/outline.js +1 -1
  290. package/dist/queries/passthrough-candidates.d.ts +9 -1
  291. package/dist/queries/passthrough-candidates.js +1 -1
  292. package/dist/queries/react-component-duplicates.d.ts +19 -3
  293. package/dist/queries/react-component-duplicates.js +1 -1
  294. package/dist/queries/react-hook-candidates.d.ts +22 -3
  295. package/dist/queries/react-hook-candidates.js +1 -1
  296. package/dist/queries/react-large-component-pressure.d.ts +17 -3
  297. package/dist/queries/react-large-component-pressure.js +1 -1
  298. package/dist/queries/recent-duplicates.js +1 -1
  299. package/dist/queries/redundant-reexports.d.ts +4 -14
  300. package/dist/queries/redundant-reexports.js +1 -1
  301. package/dist/queries/refs.d.ts +4 -1
  302. package/dist/queries/refs.js +1 -1
  303. package/dist/queries/review.d.ts +188 -0
  304. package/dist/queries/review.js +2 -0
  305. package/dist/queries/similar-files.d.ts +7 -10
  306. package/dist/queries/similar-files.js +1 -1
  307. package/dist/queries/similar-signatures.js +1 -1
  308. package/dist/queries/similar.d.ts +19 -1
  309. package/dist/queries/similar.js +1 -1
  310. package/dist/queries/slice-cohesion.d.ts +205 -0
  311. package/dist/queries/slice-cohesion.js +2 -0
  312. package/dist/queries/source-inspection.d.ts +6 -202
  313. package/dist/queries/source-inspection.js +1 -1
  314. package/dist/queries/source-search.d.ts +2 -3
  315. package/dist/queries/source-search.js +1 -1
  316. package/dist/queries/stats.d.ts +1 -0
  317. package/dist/queries/stats.js +1 -1
  318. package/dist/queries/surface.js +1 -1
  319. package/dist/queries/symbols.js +1 -1
  320. package/dist/queries/system.d.ts +4 -2
  321. package/dist/queries/system.js +1 -1
  322. package/dist/queries/test-quality.d.ts +1 -1
  323. package/dist/queries/test-quality.js +1 -1
  324. package/dist/queries/twin-drift.d.ts +23 -7
  325. package/dist/queries/twin-drift.js +1 -1
  326. package/dist/queries/unused-imports.js +1 -1
  327. package/dist/queries/unused-params.d.ts +3 -15
  328. package/dist/queries/unused-params.js +1 -1
  329. package/dist/queries/vue-component-duplicates.js +1 -1
  330. package/dist/queries/vue-composable-candidates.js +1 -1
  331. package/dist/queries/vue-large-view-pressure.js +1 -1
  332. package/dist/query-service-fastpath.js +5 -5
  333. package/dist/query-service-server.js +4 -4
  334. package/dist/refs-CCBJG7WK.js +2 -0
  335. package/dist/refs-pagination-DRNLVU4S.js +2 -0
  336. package/dist/reindex-worker.js +79 -29
  337. package/dist/reindex.js +45 -45
  338. package/dist/repository-cache-worker.js +2 -0
  339. package/dist/runtime.d.ts +8 -8
  340. package/dist/runtime.js +3 -4
  341. package/dist/rust-semantic-session-server.js +1 -1
  342. package/dist/rust-semantic-session-worker.js +1 -1
  343. package/dist/rust-semantic-worker.js +1 -1
  344. package/dist/service-queries-2WAJI7R6.js +6 -0
  345. package/dist/source-inspection-91U9zdO3.d.ts +341 -0
  346. package/dist/{source-search-types-Dwz8KeuW.d.ts → source-search-types-DWGYNg8M.d.ts} +15 -2
  347. package/dist/stats-G7DIV6VU.js +2 -0
  348. package/dist/surface-IO55UALI.js +2 -0
  349. package/dist/system-ZBMSHJXU.js +2 -0
  350. package/dist/{queries/trace.d.ts → trace-BMjw3prn.d.ts} +1 -18
  351. package/dist/typescript-indexer.js +2 -0
  352. package/dist/typescript-mailbox-worker.js +1 -1
  353. package/dist/watch-server.js +3 -3
  354. package/docs/AGENT_GUIDE.md +19 -128
  355. package/docs/CLI_JSON_OUTPUT.md +21 -17
  356. package/docs/COMMAND_REFERENCE.md +34 -49
  357. package/docs/CURRENT_COMMANDS.md +123 -0
  358. package/docs/DETECTOR_EVIDENCE_CONTRACTS.md +0 -40
  359. package/docs/DETECTOR_GUIDE.md +55 -12
  360. package/docs/PRODUCT_VISION.md +135 -0
  361. package/docs/PROPERTY_TESTING.md +73 -0
  362. package/docs/REVIEW.md +76 -0
  363. package/docs/SKILLS.md +51 -0
  364. package/docs/WINDOWS_SIDECAR_RELEASE.md +12 -3
  365. package/docs/accuracy-audit-checklist.md +70 -13
  366. package/docs/analyzer-inventory.md +2 -2
  367. package/docs/locality-analyzer-design.md +9 -9
  368. package/package.json +18 -80
  369. package/scripts/evidence-product-contract.mjs +7 -3
  370. package/scripts/record-review-coverage.mjs +118 -0
  371. package/scripts/scip-windows-provenance.mjs +29 -19
  372. package/skills/scip-architecture-review/SKILL.md +57 -0
  373. package/skills/scip-architecture-review/agents/openai.yaml +4 -0
  374. package/skills/scip-architecture-review/references/design-checks.md +17 -0
  375. package/skills/scip-explore/SKILL.md +15 -59
  376. package/skills/scip-explore/agents/openai.yaml +3 -3
  377. package/skills/scip-explore/references/external-evidence.md +2 -2
  378. package/skills/scip-explore/references/information-model.md +26 -29
  379. package/skills/scip-explore/scripts/capture-evidence.mjs +68 -34
  380. package/skills/scip-integrity-audit/SKILL.md +53 -181
  381. package/skills/scip-integrity-audit/agents/openai.yaml +3 -3
  382. package/skills/scip-integrity-audit/references/integrity-probes.md +27 -0
  383. package/skills/scip-plan/SKILL.md +39 -65
  384. package/skills/scip-plan/agents/openai.yaml +2 -2
  385. package/skills/scip-query/SKILL.md +28 -81
  386. package/skills/scip-query/agents/openai.yaml +2 -2
  387. package/skills/scip-query/references/command-guide.md +169 -0
  388. package/skills/scip-setup/SKILL.md +4 -2
  389. package/skills/scip-setup/agents/openai.yaml +3 -3
  390. package/dist/by-kind-XI2CSWEY.js +0 -2
  391. package/dist/call-graph-UONR6JR5.js +0 -2
  392. package/dist/call-graph-evidence-lZa2dwQA.d.ts +0 -11
  393. package/dist/chunk-26CT72HM.js +0 -2
  394. package/dist/chunk-2E7CX53V.js +0 -2
  395. package/dist/chunk-2GRUZAQF.js +0 -43
  396. package/dist/chunk-2LDBDR6J.js +0 -29
  397. package/dist/chunk-2OOY75BW.js +0 -2
  398. package/dist/chunk-2R3V3PSD.js +0 -4
  399. package/dist/chunk-2WC2OEDO.js +0 -4
  400. package/dist/chunk-35NLDRZC.js +0 -2
  401. package/dist/chunk-3AF4TUFK.js +0 -3
  402. package/dist/chunk-3D3QG236.js +0 -2
  403. package/dist/chunk-3FHOF22C.js +0 -21
  404. package/dist/chunk-3JKSW6LJ.js +0 -2
  405. package/dist/chunk-3L2ZBPEX.js +0 -133
  406. package/dist/chunk-3PJABJSU.js +0 -2
  407. package/dist/chunk-3SVF22I5.js +0 -2
  408. package/dist/chunk-3WR4E3A3.js +0 -3
  409. package/dist/chunk-4FTZ4P5G.js +0 -2
  410. package/dist/chunk-4UX2F3JX.js +0 -2
  411. package/dist/chunk-4WNW27SX.js +0 -2
  412. package/dist/chunk-5ENOG4VP.js +0 -61
  413. package/dist/chunk-64BFSI5I.js +0 -2
  414. package/dist/chunk-66DVSJQG.js +0 -455
  415. package/dist/chunk-6HFCYNYE.js +0 -9
  416. package/dist/chunk-6PQNKL3G.js +0 -3
  417. package/dist/chunk-6V5CNXL6.js +0 -2
  418. package/dist/chunk-6VVV4WRR.js +0 -4
  419. package/dist/chunk-7BWFZPPZ.js +0 -2
  420. package/dist/chunk-7CYG22FH.js +0 -2
  421. package/dist/chunk-7F45LJKI.js +0 -2
  422. package/dist/chunk-7IWV2EG3.js +0 -3
  423. package/dist/chunk-7KCZELVM.js +0 -2
  424. package/dist/chunk-AFHTBORT.js +0 -2
  425. package/dist/chunk-AVRYW5OZ.js +0 -2
  426. package/dist/chunk-B3X6KU75.js +0 -2
  427. package/dist/chunk-B5D7QPBE.js +0 -4
  428. package/dist/chunk-BBCIS4DX.js +0 -16
  429. package/dist/chunk-BDUVI7TO.js +0 -3
  430. package/dist/chunk-BE7ZZTMC.js +0 -2
  431. package/dist/chunk-BHVUJOCQ.js +0 -3
  432. package/dist/chunk-BJT7LSPK.js +0 -3
  433. package/dist/chunk-BKVWUP7Y.js +0 -2
  434. package/dist/chunk-BQGB4HBD.js +0 -2
  435. package/dist/chunk-BRV7PIFF.js +0 -2
  436. package/dist/chunk-CEEZJXEF.js +0 -2
  437. package/dist/chunk-CIYLO6SI.js +0 -7
  438. package/dist/chunk-CJZXN4NU.js +0 -2
  439. package/dist/chunk-CNO7TOKL.js +0 -2
  440. package/dist/chunk-COF23M5F.js +0 -2
  441. package/dist/chunk-CWFP7GM5.js +0 -2
  442. package/dist/chunk-D2DHWI3D.js +0 -2
  443. package/dist/chunk-D4N5SQ2M.js +0 -4
  444. package/dist/chunk-DBRSYFXR.js +0 -2
  445. package/dist/chunk-DHUIOLDT.js +0 -2
  446. package/dist/chunk-DIRJWYBM.js +0 -6
  447. package/dist/chunk-DIUFNHRJ.js +0 -35
  448. package/dist/chunk-DRENNWRG.js +0 -2
  449. package/dist/chunk-DTZCKZEU.js +0 -4
  450. package/dist/chunk-DULC3QFP.js +0 -5
  451. package/dist/chunk-DYGHBZ2N.js +0 -16
  452. package/dist/chunk-E5R6AQ73.js +0 -40
  453. package/dist/chunk-E73UNJTF.js +0 -38
  454. package/dist/chunk-EKV5HX33.js +0 -2
  455. package/dist/chunk-EQHFIL6T.js +0 -3
  456. package/dist/chunk-ESIQ66Z7.js +0 -2
  457. package/dist/chunk-EVFUMY4R.js +0 -3
  458. package/dist/chunk-F7DY272B.js +0 -2
  459. package/dist/chunk-FBN2FGXG.js +0 -2
  460. package/dist/chunk-FDLOBR6P.js +0 -4
  461. package/dist/chunk-FESCRNVV.js +0 -5
  462. package/dist/chunk-FFRKR4EQ.js +0 -2
  463. package/dist/chunk-FGA2U4OR.js +0 -8
  464. package/dist/chunk-FIQRSHVM.js +0 -2
  465. package/dist/chunk-FPYLNQPT.js +0 -2
  466. package/dist/chunk-FRUSVINH.js +0 -2
  467. package/dist/chunk-GSP44ENC.js +0 -2
  468. package/dist/chunk-GUFSG5TX.js +0 -2
  469. package/dist/chunk-GYIZ4NXB.js +0 -2
  470. package/dist/chunk-GZIUDL6G.js +0 -2
  471. package/dist/chunk-H5EXS3HM.js +0 -2
  472. package/dist/chunk-HCXEQRFF.js +0 -18
  473. package/dist/chunk-HEHOQQKH.js +0 -2
  474. package/dist/chunk-HKGFPJ4T.js +0 -4
  475. package/dist/chunk-HLZTEXRA.js +0 -2
  476. package/dist/chunk-HOENASQM.js +0 -3
  477. package/dist/chunk-HVF5VBG6.js +0 -2
  478. package/dist/chunk-I55I7XXP.js +0 -2
  479. package/dist/chunk-IDFEUFKS.js +0 -2
  480. package/dist/chunk-IHGQTTVW.js +0 -2
  481. package/dist/chunk-IICPE7B2.js +0 -20
  482. package/dist/chunk-IL676XCC.js +0 -18
  483. package/dist/chunk-IW5XQG5G.js +0 -2
  484. package/dist/chunk-IZDPJ2QI.js +0 -2
  485. package/dist/chunk-J66VOFW6.js +0 -5
  486. package/dist/chunk-JFMEXGFE.js +0 -2
  487. package/dist/chunk-JGKUET5J.js +0 -3
  488. package/dist/chunk-JS4PGXMV.js +0 -3
  489. package/dist/chunk-JWTGMPIT.js +0 -80
  490. package/dist/chunk-JYR66JN5.js +0 -5
  491. package/dist/chunk-KFOYCQAJ.js +0 -9
  492. package/dist/chunk-KLFEXGQA.js +0 -2
  493. package/dist/chunk-KMVGRIO2.js +0 -2
  494. package/dist/chunk-KYSDI3GE.js +0 -5
  495. package/dist/chunk-L6PJPETJ.js +0 -29
  496. package/dist/chunk-LDVT66YM.js +0 -2
  497. package/dist/chunk-LEECKFCJ.js +0 -2
  498. package/dist/chunk-LMZ5PRUV.js +0 -2
  499. package/dist/chunk-LQRQN2XA.js +0 -2
  500. package/dist/chunk-LXABEJX3.js +0 -2
  501. package/dist/chunk-MNV5FSBW.js +0 -3
  502. package/dist/chunk-MPQ4OTBM.js +0 -2
  503. package/dist/chunk-MTDBHTSF.js +0 -2
  504. package/dist/chunk-MV3CDXPI.js +0 -38
  505. package/dist/chunk-MWN53KRN.js +0 -60
  506. package/dist/chunk-MXNGIEPU.js +0 -3
  507. package/dist/chunk-N2ZSIIGR.js +0 -117
  508. package/dist/chunk-N5B2NILC.js +0 -5
  509. package/dist/chunk-NJITK2GP.js +0 -2
  510. package/dist/chunk-NOGJXYFO.js +0 -2
  511. package/dist/chunk-NOYBFVJA.js +0 -554
  512. package/dist/chunk-NWQXSFFU.js +0 -3
  513. package/dist/chunk-ODDUPDP7.js +0 -13
  514. package/dist/chunk-OLIWTZI3.js +0 -3
  515. package/dist/chunk-OLNV6I6U.js +0 -2
  516. package/dist/chunk-OR2E3AGZ.js +0 -2
  517. package/dist/chunk-OSR2GEHQ.js +0 -2
  518. package/dist/chunk-OSSESPDX.js +0 -3
  519. package/dist/chunk-OWOOWNJ5.js +0 -7
  520. package/dist/chunk-P42EIXTA.js +0 -2
  521. package/dist/chunk-PJFGPYTU.js +0 -2
  522. package/dist/chunk-PP7KNN7L.js +0 -2
  523. package/dist/chunk-PU7T5QYQ.js +0 -2
  524. package/dist/chunk-PWWAJSKV.js +0 -74
  525. package/dist/chunk-PZL5T7SU.js +0 -73
  526. package/dist/chunk-QBE3YX64.js +0 -23
  527. package/dist/chunk-QGVTFRY2.js +0 -7
  528. package/dist/chunk-QOJONDS7.js +0 -2
  529. package/dist/chunk-QU5XRYB5.js +0 -4
  530. package/dist/chunk-QUU5OBVK.js +0 -11
  531. package/dist/chunk-RBLQNW26.js +0 -20
  532. package/dist/chunk-RTQ7NEKG.js +0 -81
  533. package/dist/chunk-SQXRS7BG.js +0 -4
  534. package/dist/chunk-SSK6LDPC.js +0 -2
  535. package/dist/chunk-SZHGTCPP.js +0 -7
  536. package/dist/chunk-T4N4P2K5.js +0 -16
  537. package/dist/chunk-TA3QKLLU.js +0 -2
  538. package/dist/chunk-TEBQMNVI.js +0 -43
  539. package/dist/chunk-TPFHAQ2G.js +0 -2
  540. package/dist/chunk-TQPCBMWT.js +0 -5
  541. package/dist/chunk-TQZV7KV4.js +0 -2
  542. package/dist/chunk-TRNAEQ6P.js +0 -3
  543. package/dist/chunk-TY7CRN3Z.js +0 -2
  544. package/dist/chunk-UHFYCMZO.js +0 -35
  545. package/dist/chunk-UICY4GTQ.js +0 -7
  546. package/dist/chunk-UVGEWT4Y.js +0 -26
  547. package/dist/chunk-UXW33INU.js +0 -29
  548. package/dist/chunk-VMPRET3I.js +0 -5
  549. package/dist/chunk-VNLGKHS6.js +0 -6
  550. package/dist/chunk-VQILFTEH.js +0 -2
  551. package/dist/chunk-VUPHCS7Y.js +0 -57
  552. package/dist/chunk-VVZSBTSU.js +0 -23
  553. package/dist/chunk-VZRNID6A.js +0 -2
  554. package/dist/chunk-W5OXRYGE.js +0 -7
  555. package/dist/chunk-W6STWDQI.js +0 -57
  556. package/dist/chunk-W7CXK74K.js +0 -2
  557. package/dist/chunk-WB3WYIRE.js +0 -4
  558. package/dist/chunk-WDNVY4E7.js +0 -20
  559. package/dist/chunk-WK46TNUM.js +0 -3
  560. package/dist/chunk-WNTFFKAX.js +0 -12
  561. package/dist/chunk-WOIKCX6A.js +0 -2
  562. package/dist/chunk-WUN6KBHV.js +0 -2
  563. package/dist/chunk-WYCTJDVR.js +0 -2
  564. package/dist/chunk-WYPL7GF7.js +0 -2
  565. package/dist/chunk-XDAUYDFT.js +0 -2
  566. package/dist/chunk-XDQMU3BT.js +0 -2
  567. package/dist/chunk-XFA4SSO3.js +0 -3
  568. package/dist/chunk-XGZEP6GR.js +0 -8
  569. package/dist/chunk-XPDPNWTQ.js +0 -368
  570. package/dist/chunk-XRYABF57.js +0 -8
  571. package/dist/chunk-YBGKCQIS.js +0 -2
  572. package/dist/chunk-YEN6CYC7.js +0 -16
  573. package/dist/chunk-YF5IB2LF.js +0 -2
  574. package/dist/chunk-YI2AWIHC.js +0 -3
  575. package/dist/chunk-YPWBKGFU.js +0 -2
  576. package/dist/chunk-YPWHBBIS.js +0 -2
  577. package/dist/chunk-YSH6U3L4.js +0 -3
  578. package/dist/chunk-YU5DZUZI.js +0 -10
  579. package/dist/chunk-YWO5DDRC.js +0 -16
  580. package/dist/chunk-Z4CDXYNQ.js +0 -2
  581. package/dist/chunk-ZF5KHH7C.js +0 -2
  582. package/dist/chunk-ZOHS7AQV.js +0 -21
  583. package/dist/chunk-ZTI4SBFV.js +0 -3
  584. package/dist/code-MI6F2TTU.js +0 -2
  585. package/dist/code-result-json-FXALY4HE.js +0 -2
  586. package/dist/command-descriptors-P34VABY5.js +0 -343
  587. package/dist/dataflow-4KEMJPC6.js +0 -2
  588. package/dist/dependence-slice-R7FPWD5M.js +0 -2
  589. package/dist/deps-7EMQUYUT.js +0 -2
  590. package/dist/direct-navigation-6YO234F2.js +0 -3
  591. package/dist/entry-map-KOOLR26E.js +0 -2
  592. package/dist/files-OPIPJIGZ.js +0 -2
  593. package/dist/graph-evidence-Bjyky2V4.d.ts +0 -126
  594. package/dist/hierarchy-QPD2CAER.js +0 -2
  595. package/dist/imports-M6HUXRXC.js +0 -2
  596. package/dist/members-I5MEFOCT.js +0 -2
  597. package/dist/methods-5JYGGHXA.js +0 -2
  598. package/dist/next-anchor-candidates-BwMczMvX.d.ts +0 -90
  599. package/dist/output-continuation-command-UPQAAKBP.js +0 -3
  600. package/dist/output-pagination-3OFL2MJV.js +0 -19
  601. package/dist/project-reindex-UKKQ5PLS.js +0 -3
  602. package/dist/queries/anchors.d.ts +0 -123
  603. package/dist/queries/anchors.js +0 -2
  604. package/dist/queries/complexity-hotspots.d.ts +0 -40
  605. package/dist/queries/complexity-hotspots.js +0 -2
  606. package/dist/queries/convergence.d.ts +0 -33
  607. package/dist/queries/convergence.js +0 -2
  608. package/dist/queries/dataflow.d.ts +0 -77
  609. package/dist/queries/dataflow.js +0 -2
  610. package/dist/queries/deep-chains.d.ts +0 -5
  611. package/dist/queries/deep-chains.js +0 -2
  612. package/dist/queries/extract-candidates.d.ts +0 -52
  613. package/dist/queries/extract-candidates.js +0 -2
  614. package/dist/queries/isolated.d.ts +0 -24
  615. package/dist/queries/isolated.js +0 -2
  616. package/dist/queries/plan-context.d.ts +0 -33
  617. package/dist/queries/plan-context.js +0 -2
  618. package/dist/queries/reference-neighborhood.d.ts +0 -4
  619. package/dist/queries/reference-neighborhood.js +0 -2
  620. package/dist/queries/reference-reachability.d.ts +0 -48
  621. package/dist/queries/reference-reachability.js +0 -2
  622. package/dist/queries/self-audit.d.ts +0 -63
  623. package/dist/queries/self-audit.js +0 -2
  624. package/dist/queries/similar-chains.d.ts +0 -48
  625. package/dist/queries/similar-chains.js +0 -2
  626. package/dist/queries/slice.d.ts +0 -4
  627. package/dist/queries/slice.js +0 -2
  628. package/dist/queries/stale-abstractions.d.ts +0 -72
  629. package/dist/queries/stale-abstractions.js +0 -2
  630. package/dist/queries/system-map.d.ts +0 -449
  631. package/dist/queries/system-map.js +0 -2
  632. package/dist/queries/trace.js +0 -2
  633. package/dist/queries/twin-ab.d.ts +0 -66
  634. package/dist/queries/twin-ab.js +0 -2
  635. package/dist/queries/value-flow.d.ts +0 -43
  636. package/dist/queries/value-flow.js +0 -2
  637. package/dist/queries/wrapper-candidates.d.ts +0 -34
  638. package/dist/queries/wrapper-candidates.js +0 -2
  639. package/dist/refs-PSU4JZZW.js +0 -2
  640. package/dist/refs-pagination-JG6CJMRC.js +0 -2
  641. package/dist/slice-HYRATV64.js +0 -2
  642. package/dist/source-snippet-_wrcgmZc.d.ts +0 -15
  643. package/dist/stats-OOJ74B32.js +0 -2
  644. package/dist/surface-VTGDYWF5.js +0 -2
  645. package/dist/symbol-resolution-WD5EU5JE.js +0 -2
  646. package/dist/system-LRQNFOR2.js +0 -2
  647. package/dist/trace-F4B6OLL4.js +0 -2
  648. package/dist/value-flow-VRPZY72V.js +0 -2
  649. package/skills/concrete-plan/SKILL.md +0 -8
  650. package/skills/concrete-plan/agents/openai.yaml +0 -4
@@ -1,4 +1,54 @@
1
- import{a as Ce,b as xn,c as En,d as In,e as vn,f as _n,g as Tn,h as wn}from"./chunk-LEECKFCJ.js";import{a as Ne,b as Ae,c as or}from"./chunk-BBCIS4DX.js";import{a as jr}from"./chunk-ILMHV3KM.js";import{a as Pt,b as Cr}from"./chunk-P42EIXTA.js";import{a as dn,b as ln}from"./chunk-BKVWUP7Y.js";import{e as Yn,f as Qn,g as Kn,i as Vn}from"./chunk-W6STWDQI.js";import"./chunk-MPQ4OTBM.js";import{b as Xn}from"./chunk-OSR2GEHQ.js";import"./chunk-FRUSVINH.js";import"./chunk-YEN6CYC7.js";import"./chunk-WRQXLNYE.js";import{b as Wn,c as De,d as Me,e as Hn,f as Jn,g as zn}from"./chunk-2GRUZAQF.js";import"./chunk-HOENASQM.js";import"./chunk-YUKYB54I.js";import"./chunk-BJT7LSPK.js";import{a as de,b as Oe,c as he,d as Nn,e as Ln,f as An,g as $n,h as Gn,j as Or}from"./chunk-4WNW27SX.js";import{a as hn,b as yn}from"./chunk-F4FNK44D.js";import{a as $}from"./chunk-IICPE7B2.js";import{b as ue}from"./chunk-TQZV7KV4.js";import"./chunk-3L2ZBPEX.js";import{a as ke}from"./chunk-YXPUP5G2.js";import"./chunk-DRENNWRG.js";import{a as sn,b as cn,c as ve,d as le,e as Zn,f as er,h as St,i as sr,n as Fr}from"./chunk-SZHGTCPP.js";import{a as qe,b as vr,d as _r}from"./chunk-FIQRSHVM.js";import{a as xt}from"./chunk-MXNGIEPU.js";import{b as Tr,c as wr,d as Rt}from"./chunk-BE7ZZTMC.js";import"./chunk-2OOY75BW.js";import{A as bt,B as hr,C as yr,D as Ue,E as Sr,F as br,G as Pr,c as ht,e as tr,f as Y,g as Q,h as Le,i as nr,j as rr,k as ir,l as ar,m as $e,n as cr,o as dr,p as lr,q as ur,r as pr,s as gr,t as fr,u as Ge,v as W,w as Be,y as mr}from"./chunk-IZDPJ2QI.js";import{a as Sn,b as A,d as Rn}from"./chunk-WYPL7GF7.js";import{a as Un,d as yt,l as qn}from"./chunk-RTQ7NEKG.js";import{c as ae,d as me,e as Te,g as ut,h as gn}from"./chunk-GUFSG5TX.js";import"./chunk-MWN53KRN.js";import"./chunk-IW5XQG5G.js";import{b as bn,c as ft,d as Pn}from"./chunk-3AF4TUFK.js";import{b as Fe,c as Bn,f as Rr,j as xr,k as Er,l as Ir}from"./chunk-FGA2U4OR.js";import{a as oe}from"./chunk-B3PYOSCX.js";import"./chunk-H5EXS3HM.js";import{a as fn,e as E,f as G,g as mn}from"./chunk-HGFDYOVB.js";import{a as Ie,b as z,c as U,d as C}from"./chunk-JFMEXGFE.js";import{B as we,F as je,M as Cn,N as X,O as se,P as ce,Q as jn,R as On,S as mt,V as Fn,a as _e,b as un,c as lt,d as pn,da as kn,ea as Dn,f as q,fa as Mn,h as M,q as pt,z as gt}from"./chunk-KYSDI3GE.js";import{a as an,c as Ee,f as ie,g as ge,h as fe,i as on}from"./chunk-7F45LJKI.js";import{createHash as Rc}from"crypto";import{existsSync as L,mkdirSync as rt,mkdtempSync as xc,readdirSync as ua,renameSync as pa,rmSync as Z,statSync as Qt}from"fs";import{basename as tt,dirname as x,extname as Ec,join as O,resolve as Zi}from"path";import{platform as ea}from"os";import{execFileSync as Ua}from"child_process";import{constants as qa,copyFileSync as kr,linkSync as Wa,rmSync as Ha,statSync as Ja}from"fs";import{platform as za}from"os";var Xa=Object.freeze({size:e=>Ja(e).size,clone:Va,copy:(e,t)=>kr(e,t),link:(e,t)=>Wa(e,t),remove:e=>Ha(e,{force:!0})}),Ya=new Set(["EXDEV","EPERM","EMLINK","ENOTSUP","EOPNOTSUPP","ENOSYS","EINVAL"]),Qa=new Set(["ENOSYS","ENOTSUP","EOPNOTSUPP","EINVAL","EXDEV","ENOTTY"]);function K(e,t,n=Xa,r={}){let a=n.size(e);n.remove?.(t);try{return n.clone(e,t),{method:"reflink",bytes:a}}catch(i){if(!eo(i))throw i}if(r.shareImmutable&&n.link)try{return n.link(e,t),{method:"link",bytes:a}}catch(i){if(!Ka(i))throw i}return n.copy(e,t),{method:"copy",bytes:a}}function Ka(e){let t=e?.code;return typeof t=="string"&&Ya.has(t)}function Va(e,t){if(za()!=="darwin"){kr(e,t,qa.COPYFILE_FICLONE_FORCE);return}try{Ua("/bin/cp",["-c",e,t],{timeout:6e4,maxBuffer:64*1024,stdio:["ignore","ignore","pipe"]})}catch(n){throw Za(n)}}function Za(e){let t=e?.stderr,n=Buffer.isBuffer(t)?t.toString("utf8"):t??"";return/operation not supported|not supported/i.test(n)?Object.assign(e instanceof Error?e:new Error(String(e)),{code:"ENOTSUP"}):/cross-device link/i.test(n)?Object.assign(e instanceof Error?e:new Error(String(e)),{code:"EXDEV"}):e}function eo(e){let t=e?.code;return t!==void 0&&Qa.has(t)}function Dr(){return{reflinkedBytes:0,fallbackCopiedBytes:0,incrementalWrittenBytes:0}}function V(e,t){t.method==="reflink"||t.method==="link"?e.reflinkedBytes+=t.bytes:e.fallbackCopiedBytes+=t.bytes}function We(e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error("incremental write bytes must be a non-negative integer");e.incrementalWrittenBytes=(e.incrementalWrittenBytes??0)+t}import{dirname as to,join as no}from"path";function Mr(e={}){return{id:"runtime-boundaries",facts:["runtime-boundary-observation","runtime-boundary-link"],run:async({projectRoot:t,dbPath:n,onStatus:r})=>{let a=new $({projectRoot:t,dbPath:n,indexPath:e.indexPath??no(to(n),"index.scip"),...e.evidenceDbPath?{evidenceDbPath:e.evidenceDbPath}:{}}),i,o=!1,s=!1;try{let d=e.reuseExisting||e.affectedFiles?Vn(a):null;e.reuseExisting&&d?.extractorVersion===Yn?(i=d,o=!0):(i=await Qn(a,{...d?{previousGraph:d}:{},...e.affectedFiles?{affectedFiles:e.affectedFiles}:{},...e.forceDerivedRebuild?{forceDerivedRebuild:!0}:{},profileSpan:E}),s=(i.coverage.filesReused??0)>0)}finally{a.close()}o||Kn(n,i);let c={reused:o,incrementallyUpdated:s,observations:i.observations.length,links:i.links.length,frontiers:i.frontiers.length,filesScanned:i.coverage.filesScanned,errors:i.coverage.extractionErrors.length,phases:i.coverage.phases};return r?.(c.reused?`Reused ${c.observations} cached runtime-boundary observation(s) and ${c.links} link(s).`:c.incrementallyUpdated?`Incrementally refreshed runtime-boundary observations (${c.filesScanned-(i.coverage.filesReused??0)} file(s) extracted, ${i.coverage.filesReused??0} reused) and rebuilt ${c.links} link(s).`:`Extracted ${c.observations} runtime-boundary observation(s), ${c.links} link(s), and ${c.frontiers} unresolved frontier(s).`),!o&&i.coverage.phases&&r?.(`Runtime-boundary phases: ${i.coverage.phases.map(d=>`${d.id} ${d.durationMs.toFixed(0)}ms`).join(", ")}.`),c}}}function ye(e){let t=new Set;for(let n of e.uncertainty)t.add(n);e.projectIdentityChanged&&t.add("project-identity-changed");for(let n of e.changes)n.kind==="added"&&t.add("file-added"),n.kind==="deleted"&&t.add("file-deleted"),n.inputKind==="config"&&t.add("configuration-changed"),n.inputKind==="ambient"&&t.add("ambient-declaration-changed"),n.inputKind==="other"&&t.add("unclassified-input");return{fullProject:t.size>0,reasons:[...t].sort()}}function Se(e,t,n){let r=e.changes.map(s=>s.path).sort();if(r.length===0&&!e.projectIdentityChanged&&e.uncertainty.length===0)return{mode:"none",changedFiles:r,affectedFiles:[],reasons:[]};let a=new Set(n),i=ye(e),o=new Set(i.reasons);return r.some(s=>!a.has(s))&&o.add("changed-file-outside-project"),t===null?(o.add("dependency-graph-unavailable"),Nr(r,a,o)):o.size>0?Nr(r,a,o):{mode:"closure",changedFiles:r,affectedFiles:ro(r,t,a),reasons:[]}}function Nr(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function ro(e,t,n){let r=new Map;for(let[o,s]of t)if(n.has(o))for(let c of s){if(!n.has(c))continue;let d=r.get(c)??new Set;d.add(o),r.set(c,d)}let a=new Set(e),i=[...e];for(let o=0;o<i.length;o+=1){let s=i[o];if(s!==void 0)for(let c of r.get(s)??[])a.has(c)||(a.add(c),i.push(c))}return[...a].sort()}import{createHash as io}from"crypto";import{existsSync as ao}from"fs";import{dirname as oo,join as Lr}from"path";var so="<global-symbols>";function co(e){let t=[];for(let n of e.all(`
1
+ import{a as wi,b as Fi,c as St,d as Le,e as xa,f as Ra,h as Fa,i as _a,m as Jn,o as Qa}from"./chunk-2LHXRE2B.js";import{a as vt,b as Ai,c as Mi,d as ji,e as Bi,f as $i,g as Ui,h as Gi}from"./chunk-VX2O4RIS.js";import{a as Dt,b as Mt,c as wa}from"./chunk-YOQVEXVE.js";import{a as Ja}from"./chunk-ILMHV3KM.js";import{a as $n,b as Xa}from"./chunk-GH2PYF46.js";import{a as Ht,b as qa,d as Va,e as za}from"./chunk-6LRXOOSX.js";import{b as Gt}from"./chunk-ZO4YXUT6.js";import{a as _i,b as Ni,c as Ba}from"./chunk-IWQPAF4F.js";import{b as ca}from"./chunk-65245JCM.js";import{a as Yr,c as Wa,d as Ka,e as Xn}from"./chunk-NJJMVD65.js";import{c as va}from"./chunk-H73WY2RM.js";import{e as la,f as F,g as da,h as Vn,i as Xe,j as zn,k as pa,l as Wn,m as ma,n as fa,o as ga,p as kt,q as ha,r as Lt,s as At,t as Je,u as Ye,v as ya}from"./chunk-ZHMRSZFD.js";import{p as Sa}from"./chunk-ZGTYGDMF.js";import{a as ba}from"./chunk-WRQXLNYE.js";import"./chunk-DVFP6PZI.js";import{d as qn}from"./chunk-QIWXRW72.js";import{b as ia,c as Nt,d as Ot,e as aa,f as oa,g as sa}from"./chunk-LOVIZBJ4.js";import"./chunk-QXEUDXBT.js";import"./chunk-O2C4UILI.js";import{c as _t}from"./chunk-WXU3DGPU.js";import"./chunk-YUKYB54I.js";import{a as ke,b as xt,c as We,d as Hi,e as Un,f as qi,g as Vi,h as zi,j as Ya}from"./chunk-WKPV2TDZ.js";import{a as ki,b as Li}from"./chunk-F4FNK44D.js";import"./chunk-6FFVZZL4.js";import{a as $}from"./chunk-RBS42E55.js";import{a as jt}from"./chunk-4FEWQ6RH.js";import{A as Z,B as $t,D as Da,F as Kn,G as ka,H as La,I as Ut,J as Aa,K as Ma,L as ja,a as ui,b as di,c as An,d as Mn,h as Bn,j as De,k as be,l as bt,m as Pi,n as Ii,o as Ei,q as Ci,r as Ti,s as Pa,t as Ia,u as Ea,v as Ca,w as Ta,x as Na,y as Oa,z as Bt}from"./chunk-BIQEF5NE.js";import{a as Si,b as H,d as Ri}from"./chunk-YTAP5Y2G.js";import{b as Ae}from"./chunk-CN5EH7O3.js";import"./chunk-T3I6NHBH.js";import{A as Hn,B as Yi,C as X,D as Qi,E as Zi,G as ea,H as Ft,J as ta,O as na,P as ra,Y as D,a as Wi,d as Ki,e as Se,ea as ua,g as ve,j as Xi,k as Et,l as Ke,q as Ct,s as K,t as Tt,u as wt,v as ne,w as Y,x as Q,y as q,z as Ji}from"./chunk-J5FJMODQ.js";import"./chunk-WOFQ5DTB.js";import{b as Pt,e as It}from"./chunk-PH52RA7D.js";import"./chunk-NDUNO5JQ.js";import{a as Gn}from"./chunk-7Y5T6XDP.js";import{a as ci,b as kn,c as ze,d as he,e as Ln,m as li}from"./chunk-X6RMKHJQ.js";import{c as _e,d as Ve,e as gt,g as Dn,h as si}from"./chunk-JEVRKFRL.js";import"./chunk-H75GSPRV.js";import{a as Rt}from"./chunk-QOIXNWQR.js";import{c as Ne}from"./chunk-GZKFETP5.js";import{c as vi,d as jn,e as xi}from"./chunk-BL6XJKTA.js";import{c as $a,g as Ua,h as Ga,i as Ha}from"./chunk-3JIQS44J.js";import{c as ai,d as oi}from"./chunk-O4UZSPPI.js";import{a as Oe}from"./chunk-B3PYOSCX.js";import"./chunk-HRRFKWPZ.js";import"./chunk-YULZRALL.js";import{a as Oi,e as P,f as W,g as Di}from"./chunk-HGFDYOVB.js";import{a as yt,b as ye,c as te,d as w}from"./chunk-QZ7KQZRN.js";import{A as yi,B as bi,e as ht,l as pi,n as mi,p as fi,u as gi,z as hi}from"./chunk-TKD34PHN.js";import"./chunk-2HLAFUCY.js";import{A as ti,F as ge,G as qe,H as ft,I as ni,J as ri,K as ii,a as Qr,b as Zr,c as pt,f as me,h as k,n as On,t as mt}from"./chunk-U5RIG3JP.js";import{a as ei,c as Ue,f as fe,h as Ge,i as He}from"./chunk-62BDNPMI.js";import{createHash as gg}from"crypto";import{existsSync as B,mkdirSync as Cn,mkdtempSync as hg,readdirSync as Cc,renameSync as Tc,rmSync as Ee,statSync as wc}from"fs";import{basename as In,dirname as I,extname as yg,join as O,resolve as yc}from"path";import{platform as Fc}from"os";import{execFileSync as ol}from"child_process";import{constants as sl,copyFileSync as Za,linkSync as cl,rmSync as ll,statSync as ul}from"fs";import{platform as dl}from"os";var pl=Object.freeze({size:e=>ul(e).size,clone:hl,copy:(e,t)=>Za(e,t),link:(e,t)=>cl(e,t),remove:e=>ll(e,{force:!0})}),ml=new Set(["EXDEV","EPERM","EMLINK","ENOTSUP","EOPNOTSUPP","ENOSYS","EINVAL"]),fl=new Set(["ENOSYS","ENOTSUP","EOPNOTSUPP","EINVAL","EXDEV","ENOTTY"]);function re(e,t,n=pl,r={}){let i=n.size(e);n.remove?.(t);try{return n.clone(e,t),{method:"reflink",bytes:i}}catch(a){if(!bl(a))throw a}if(r.shareImmutable&&n.link)try{return n.link(e,t),{method:"link",bytes:i}}catch(a){if(!gl(a))throw a}return n.copy(e,t),{method:"copy",bytes:i}}function gl(e){let t=e?.code;return typeof t=="string"&&ml.has(t)}function hl(e,t){if(dl()!=="darwin"){Za(e,t,sl.COPYFILE_FICLONE_FORCE);return}try{ol("/bin/cp",["-c",e,t],{timeout:6e4,maxBuffer:64*1024,stdio:["ignore","ignore","pipe"]})}catch(n){throw yl(n)}}function yl(e){let t=e?.stderr,n=Buffer.isBuffer(t)?t.toString("utf8"):t??"";return/operation not supported|not supported/i.test(n)?Object.assign(e instanceof Error?e:new Error(String(e)),{code:"ENOTSUP"}):/cross-device link/i.test(n)?Object.assign(e instanceof Error?e:new Error(String(e)),{code:"EXDEV"}):e}function bl(e){let t=e?.code;return t!==void 0&&fl.has(t)}function eo(){return{reflinkedBytes:0,fallbackCopiedBytes:0,incrementalWrittenBytes:0}}function ie(e,t){t.method==="reflink"||t.method==="link"?e.reflinkedBytes+=t.bytes:e.fallbackCopiedBytes+=t.bytes}function qt(e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error("incremental write bytes must be a non-negative integer");e.incrementalWrittenBytes=(e.incrementalWrittenBytes??0)+t}import{dirname as pp,join as mp}from"path";function Qe(e,t=[]){return ze(JSON.stringify({observations:e.map(({resolution:n,...r})=>r),bodies:t}))}function to(e,t){let{dbPath:n,indexPath:r,evidenceDbPath:i,sharedEvidenceDbPath:a,...o}=e.config;return ze(JSON.stringify({configuration:o,files:t.map(s=>[s,e.isIgnored(s)])}))}function Ze(e){if(Sl(e))return{result:structuredClone(e.previous.result),record:e.previous,reused:!0};let t=new $(e.db.config,{isIgnored:n=>e.db.isIgnored(n)});try{return t.generation.identity!==e.db.generation.identity?{result:e.compute(e.db),reused:!1}:vl(t,e)}finally{t.close()}}function Sl(e){let t=e.previous;if(!t||t.build!==kn()||t.scope!==e.scope||t.seeds!==e.seeds||!Array.isArray(t.sources)||!Array.isArray(t.result?.errors)||t.result.errors.length>0)return!1;let n=qn(e.db);return t.sources.every(i=>i&&typeof i.file=="string"&&typeof i.hash=="string"&&(n.get(i.file)??null)===i.indexedHash&&no(e.db,i.file)===i.hash)&&(e.compilerFactsUnchanged||Ki(e.db.db,t.database))}function vl(e,t){let n=new Set,r=new Map,i=new Map,a=!0,{result:o,proof:s}=Wi(e.db,()=>It(u=>n.add(u.replace(/\\/g,"/")),()=>t.compute(e),void 0,{source(u,d){if(u=u.replace(/\\/g,"/"),i.get(u)===d)return;i.set(u,d);let p=ze(d),m=r.get(u);m!==void 0&&m!==p&&(a=!1),r.set(u,p)},unavailable(){a=!1}})),c=qn(e),l=[...n].sort().map(u=>({file:u,hash:r.get(u),indexedHash:c.get(u)??null}));return!a||o.errors.length>0||l.some(({file:u,hash:d})=>d===void 0||no(e,u)!==d)?{result:o,reused:!1}:{result:o,reused:!1,record:{build:kn(),scope:t.scope,seeds:t.seeds,sources:l,database:s,result:structuredClone(o)}}}function no(e,t){try{return ze(gi(e.config.projectRoot,t,{inputKind:"runtime phase input"}))}catch{return null}}import{createHash as at}from"crypto";import{setImmediate as ns}from"timers/promises";import{createRequire as _d}from"module";var Vt=8;function zt(e,t,n){return nr(ro(e,t,Qn(n),0,new Set))}function Zn(e,t,n){return er(e,t,n,0,new Set)}function ro(e,t,n,r,i){if(r>Vt)return[];let a=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(n);return a?io(e,t,a[1],a[2],r,i):/^[A-Za-z_$][\w$]*$/u.test(n)?ao(e,t,n,r,i):[]}function io(e,t,n,r,i,a){let o=er(e,t,n,i+1,new Set(a)).flatMap(s=>q(s.initializer).namedChildren.flatMap(c=>xl(e,s.definition,c,r,i,a)));return nr(o)}function xl(e,t,n,r,i,a){if(n.type==="pair"){let s=n.childForFieldName("key")??n.namedChild(0);if(Cl(s)!==r)return[];let c=n.childForFieldName("value")??n.namedChild(1);return c?ro(e,t.relativePath,Qn(c.text),i+1,new Set(a)):[]}if(/(?:method|function)/u.test(n.type))return Rl(e,t,n,r);if(n.type!=="spread_element")return[];let o=n.namedChild(0);return o?er(e,t.relativePath,Qn(o.text),i+1,new Set(a)).flatMap(s=>io(e,s.definition.relativePath,s.definition.leaf,r,i+1,new Set(a))):[]}function Rl(e,t,n,r){if((n.childForFieldName("name")??n.namedChild(0))?.text!==r)return[];let a=Il(e,t.relativePath,r,n);return a.length>0?a:[Pl(t,r,n)]}function Pl(e,t,n){return{documentId:e.documentId,symbolId:-1,symbol:`source-callable:${e.relativePath}:${n.startPosition.row}:${n.startPosition.column}:${n.endPosition.row}:${n.endPosition.column}:${t}`,relativePath:e.relativePath,startLine:n.startPosition.row,startChar:n.startPosition.column,endLine:n.endPosition.row,endChar:n.endPosition.column,leaf:t,parentTypeName:e.leaf,isFunctionLike:!0,isTypeLike:!1,kind:null,documentation:null,enclosingSymbol:e.symbol}}function er(e,t,n,r,i){return r>Vt||!/^[A-Za-z_$][\w$]*$/u.test(n)?[]:ao(e,t,n,r,i).flatMap(a=>{let o=X(e,a.relativePath)?.rootNode,s=o?El(o,a.leaf):null;return s?[{definition:a,initializer:s}]:[]})}function ao(e,t,n,r,i){if(r>Vt)return[];let a=`${t}\0${n}`;if(i.has(a))return[];i.add(a);let o=D(e,t).filter(l=>l.leaf===n);if(o.length>0)return o;let s=tr(e,t,n);if(s.length>0)return s;let c=ra(e,t).find(l=>l.localName===n&&l.sourcePath);if(c?.sourcePath){let l=c.kind==="namespace"||c.importedName==="default"?n:c.importedName;return Yn(e,c.sourcePath,l,r+1,new Set(i))}return Yn(e,t,n,r+1,new Set(i))}function tr(e,t,n){let r=e.get("SELECT id FROM documents WHERE relative_path = ?",t)?.id;return r===void 0?[]:(Ft(e,t)?.callables??[]).filter(i=>i.name===n).map(i=>({documentId:r,symbolId:-1,symbol:`source-callable:${t}:${i.startLine}:${i.startColumn}:${i.endLine}:${i.endColumn}:${n}`,relativePath:t,startLine:i.startLine,startChar:i.startColumn??0,endLine:i.endLine,endChar:i.endColumn??0,leaf:n,parentTypeName:null,isFunctionLike:!0,isTypeLike:!1,kind:null,documentation:null,enclosingSymbol:null}))}function Yn(e,t,n,r,i){if(r>Vt)return[];let a=D(e,t).filter(o=>o.leaf===n);return a.length>0?a:nr(na(e,t).flatMap(o=>o.sourcePath?o.kind==="named"&&!o.names.includes(n)?[]:Yn(e,o.sourcePath,n,r+1,new Set(i)):[]))}function Il(e,t,n,r){return D(e,t).filter(i=>i.leaf===n&&i.startLine<=r.startPosition.row&&i.endLine>=r.endPosition.row)}function El(e,t){let n=null;return ne(e,r=>{n||r.type!=="variable_declarator"||(r.childForFieldName("name")??r.namedChild(0))?.text.trim()!==t||(n=r.childForFieldName("value")??r.namedChild(1))}),n}function Cl(e){return e?.text.replace(/^['"`]|['"`]$/gu,"")??null}function Qn(e){return e.replace(/\s+/gu,"").replace(/^\.\.\./u,"")}function nr(e){return[...new Map(e.map(t=>[t.symbol,t])).values()]}function ae(e,t){let n=F(e.file,e.root);if(n.hasObservedWrite(t))return{value:t.text,evidence:"expression",term:{kind:"unknown",reason:"binding-observed-write"}};let r=n.valueDeclaration(t);if(r){let u=D(e.db,e.file).filter(d=>d.leaf===r.name&&d.startLine===r.startLine&&(d.startChar??0)<=r.startColumn&&d.endLine>=r.endLine);return u.length===1?{value:t.text,evidence:"identifier",term:{kind:"symbol",symbol:u[0].symbol}}:{value:t.text,evidence:"identifier",term:{kind:"symbol",symbol:`${e.file}:${r.startLine}:${r.startColumn}:${r.endLine}:${r.endColumn}`}}}let i={startLine:t.startPosition.row,startColumn:t.startPosition.column,endLine:t.endPosition.row,endColumn:t.endPosition.column},a=Ye(e.db,e.file)?.targets.filter(u=>Xe(u.sourceRange,i))??[],o=new Set(a.map(u=>u.definition.symbol));if(o.size===1)return{value:t.text,evidence:"identifier",term:{kind:"symbol",symbol:[...o][0]}};let s=D(e.db,e.file).filter(u=>u.leaf===t.text&&u.startLine===i.startLine&&(u.startChar??0)<=i.startColumn&&u.endLine>=i.endLine);if(s.length===1)return{value:t.text,evidence:"identifier",term:{kind:"symbol",symbol:s[0].symbol}};let c=n.importedValue(t);if(c?.member){let u=Xi(e.db,e.file,c.module),d=u?da(e.db,u,c.member):[];if(d.length===1)return{value:t.text,evidence:"identifier",term:{kind:"symbol",symbol:d[0].symbol}}}let l=n.resource(t);return{value:t.text,term:{kind:"symbol",symbol:`${e.file}:${l.resourceKey}`},evidence:l.identityBasis==="compiler-binding-access-path"?"identifier":"expression"}}function oo(e,t){let n=F(e.file,e.root);if(kt(e,t))return null;let r={startLine:t.startPosition.row,startColumn:t.startPosition.column,endLine:t.endPosition.row,endColumn:t.endPosition.column},i=Ye(e.db,e.file)?.targets.filter(l=>Xe(l.sourceRange,r)&&l.definition.isFunctionLike)??[],a=new Map(i.map(l=>[l.definition.symbol,l.definition]));if(a.size===1)return[...a.values()][0];let o=ae(e,t);if(o.evidence==="expression"||o.term?.kind!=="symbol")return null;let s=o.term.symbol,c=D(e.db,e.file).filter(l=>l.symbol===s&&l.isFunctionLike);return c.length===1?c[0]:Tl(e,t,n)}function Tl(e,t,n){let r=n.callableValue(t),i=n.valueDeclaration(t)?.name??r?.childForFieldName("name")?.text;if(!r||!i)return null;let a=tr(e.db,e.file,i).filter(o=>o.startLine<=r.startPosition.row&&o.endLine===r.endPosition.row&&(o.startLine!==r.startPosition.row||(o.startChar??0)<=r.startPosition.column)&&o.endChar===r.endPosition.column);return a.length===1?a[0]:null}function rr(e){return e.precision?e.precision:e.term?lo(e.term):e.evidence==="expression"?"unknown":e.evidence==="identifier"?"symbolic":"literal"}function so(e){return co(e.map(rr))}function co(e){return["unknown","symbolic","constrained-pattern","finite-set"].find(t=>e.includes(t))??"literal"}function lo(e){switch(e.kind){case"literal":return"literal";case"finite-set":return"finite-set";case"pattern":return"constrained-pattern";case"parameter":case"symbol":return"symbolic";case"concat":return co(e.parts.map(lo));default:return"unknown"}}function Wt(e,t,n){if(!e)return{kind:"absent"};if(e.type!=="object")return{kind:"unknown"};let r={kind:"absent"};for(let i of e.namedChildren)r=wl(i,t,n)??r;return r}function wl(e,t,n){if(e.type==="comment")return null;if(e.type==="shorthand_property_identifier")return e.text===t?{kind:"value",node:e}:null;if(e.type!=="pair")return{kind:"unknown"};let r=e.childForFieldName("key"),i=Fl(r,n);if(i===null)return{kind:"unknown"};if(i!==t)return null;let a=e.childForFieldName("value");return a?{kind:"value",node:a}:{kind:"unknown"}}function Fl(e,t){return e?e.type==="property_identifier"?e.text:t(e):null}var uo=8;function U(e,t){return t?xe(e,t,0,new Set):null}function xe(e,t,n,r){if(n>uo)return L(t,"value-evaluation-depth");let i=q(t),a=$l(e.file,i);if(a)return Hl(e.file,i,a.term,a.value,a.precision);if(i.type==="binary_expression"&&i.childForFieldName("operator")?.text==="+"){let c=Vl(e,i,n,r);if(c)return c}let o=i.text.trim();if(["identifier","shorthand_property_identifier"].includes(i.type))return Ll(e,o,i,n,r);let s=ha(i);return s?Al(e,s.base,s.properties,i,n,r):i.type==="call_expression"||i.type==="call"?_l(e,i,n,r):L(i,`unsupported-expression:${i.type}`)}function _l(e,t,n,r){let i=t.childForFieldName("function");if(!i)return L(t,"call-target-unresolved");if(t.childForFieldName("arguments")?.namedChildren.some(p=>Xt(e,p)))return L(t,"call-argument-normal-completion-unproved");if(kt(e,i))return L(t,"call-target-written");let a=fa(e,i);if(!a)return L(t,"call-target-unresolved");let{context:o,callable:s}=a;if(s.childForFieldName("parameters")?.namedChildren.some(p=>kl(o,p)))return L(t,"call-parameter-normal-completion-unproved");let c=`${o.file}:${s.startIndex}:${s.endIndex}`;if(r.has(c))return L(t,"call-return-cycle");let l=Nl(o,s);if(!l)return L(t,"call-return-not-unconditional-synchronous-expression");let u=new Set(r).add(c),d=xe(o,l,n+1,u);return d?Jt(t,"bounded-call-return",d):L(t,"call-return-unresolved")}function Nl(e,t){if(t.children.some(a=>a.type==="async"||a.type==="*")||t.type.includes("generator"))return null;let n=t.childForFieldName("body");if(!n)return null;if(t.type==="arrow_function"&&n.type!=="statement_block")return n;let r=n.namedChildren.filter(a=>a.type!=="comment"),i=r.at(-1);return!i||i.type!=="return_statement"||r.slice(0,-1).some(a=>!["lexical_declaration","variable_declaration","function_declaration"].includes(a.type)||Xt(e,a))?null:i.childForFieldName("argument")??i.namedChild(0)}function Xt(e,t,n=0,r=!1){if(n>uo)return!0;let i=q(t);if(["function_declaration","function_expression","arrow_function","generator_function_declaration","generator_function","number","true","false","null","regex","comment"].includes(i.type))return!1;let a=Vn(i);if(a)return a.interpolated;let o=s=>Xt(e,s,n+1,r);if(["lexical_declaration","variable_declaration","array"].includes(i.type))return i.namedChildren.some(o);if(i.type==="variable_declarator"){let s=i.childForFieldName("value");return i.childForFieldName("name")?.type!=="identifier"||!!s&&o(s)}return i.type==="object"?i.namedChildren.some(s=>Dl(s,o)):["identifier","shorthand_property_identifier"].includes(i.type)?Ol(e,i,o,r):!0}function Ol(e,t,n,r){let i=F(e.file,e.root);if(!r&&i.isParameterBinding(t))return!1;let a=i.constantInitializer(t);return!a||a.endIndex>=t.startIndex||n(a)}function Dl(e,t){if(e.type==="comment")return!1;if(e.type==="shorthand_property_identifier")return t(e);let n=e.childForFieldName("key")??e.childForFieldName("name");if(!n||n.type==="computed_property_name")return!0;if(e.type==="method_definition")return!1;let r=e.childForFieldName("value");return e.type!=="pair"||!r||t(r)}function kl(e,t){if(t.type==="comment")return!1;let n=t.childForFieldName("pattern")??t.childForFieldName("name")??t.namedChild(0)??t;if((n.type==="rest_pattern"?n.namedChild(0):n)?.type!=="identifier")return!0;let i=t.childForFieldName("value");return!!i&&Xt(e,i,0,!0)}function Ll(e,t,n,r,i){let a=F(e.file,e.root),o=`${e.file}:${a.resource(n).resourceKey}`;if(i.has(o))return L(n,"value-cycle");let s=new Set(i).add(o),c=a.constantInitializer(n);if(c){let u=xe(e,c,r+1,s);return u?Jt(n,"local-constant",u):L(n,"non-foldable-local")}let l=zn(e,n);return l?zl(e,l,n,r,s):Kt(n,t,"unresolved-or-nonconstant-binding")}function Al(e,t,n,r,i,a){let o=Ml(e,t,n);if(typeof o=="string")return L(r,o);let{context:s}=o,c=o.node;for(let u of o.properties){c=jl(s,c);let d=Wt(c,u,p=>{let m=xe(s,Bl(p),i+1,new Set(a));return m?.precision==="literal"&&["literal","constant"].includes(m.evidence)?m.value:null});if(d.kind!=="value")return L(r,`member-property-${d.kind}:${u}`);c=d.node}let l=xe(s,c,i+1,new Set(a));return l?Jt(r,"member-constant",l):L(r,"member-value-unresolved")}function Ml(e,t,n){let r=F(e.file,e.root);if(r.hasObservedWrite(t,!0,n))return"member-base-observed-write";let i=r.constantInitializer(t);if(i)return Wn(e,t,n)?"member-shared-write-or-coverage-unproved":{context:e,node:i,properties:n};let a=zn(e,t,n[0]);if(!a)return"member-binding-unresolved";let o=pa(e,a);if(!o)return"member-definition-unparsed";let s=F(o.context.file,o.context.root),c=r.importedValue(t)?.member===null?n.slice(1):n;if(s.hasObservedWrite(o.declaration,!0,c))return"member-base-observed-write";if(Wn(o.context,o.declaration,c))return"member-shared-write-or-coverage-unproved";let l=s.constantInitializer(o.declaration);return l?{context:o.context,node:l,properties:c}:"member-base-nonconstant"}function jl(e,t){let n=q(t),r=new Set,i=F(e.file,e.root);for(;n.type==="identifier"&&!r.has(n.startIndex);){r.add(n.startIndex);let a=i.constantInitializer(n);if(!a)break;n=q(a)}return n}function Bl(e){return e.type==="computed_property_name"?e.namedChild(0)??e:e}function $l(e,t){let n=K(e);return n==="typescript"||n==="tsx"||n==="javascript"||Tt(e)?Ul(t):Gl(t)}function Ul(e){let t=Vn(e);return t?t.interpolated?{term:{kind:"pattern",language:"template",value:t.value},value:t.value,precision:"constrained-pattern"}:{term:{kind:"literal",value:t.value},value:t.value,precision:"literal"}:null}function Gl(e){if(e.type!=="string"&&e.type!=="string_literal")return null;let t=e.text.trim(),n=t[0];if(n!=="'"&&n!=='"'&&n!=="`"||t.at(-1)!==n)return null;let r=t.slice(1,-1);return t.startsWith(n.repeat(3))||["\\","$","#",`
2
+ `,"\r"].some(i=>r.includes(i))?null:{term:{kind:"literal",value:r},value:r,precision:"literal"}}function Hl(e,t,n,r,i){return{value:r,evidence:"literal",term:n,precision:i,derivation:Yt("direct-literal","direct",e,t)}}function ql(e,t,n,r,i,a){return{value:r,evidence:"constant",term:n,precision:i,derivation:{...Yt("constant-concatenation","mechanically-derived",e,t),inputFactIds:a.flatMap(o=>o.derivation.inputFactIds),sourceSpans:a.flatMap(o=>o.derivation.sourceSpans)}}}function Jt(e,t,n,r){return n.evidence==="expression"?{...n,derivation:{kind:"heuristic",rule:t,ruleVersion:"1",inputFactIds:[...n.derivation.inputFactIds,...r?[r]:[]],sourceSpans:n.derivation.sourceSpans}}:{...n,evidence:"constant",derivation:{kind:"mechanically-derived",rule:t,ruleVersion:"1",inputFactIds:[...n.derivation.inputFactIds,...r?[r]:[]],sourceSpans:n.derivation.sourceSpans}}}function Kt(e,t,n){return{value:e.text.trim(),evidence:"expression",term:{kind:"symbol",symbol:t},precision:"symbolic",derivation:Yt(n,"heuristic","",e)}}function L(e,t){return{value:e.text.trim(),evidence:"expression",term:{kind:"unknown",reason:t},precision:"unknown",derivation:Yt(t,"heuristic","",e)}}function Yt(e,t,n,r){return{kind:t,rule:e,ruleVersion:"1",inputFactIds:[],sourceSpans:n?[{file:n,startLine:r.startPosition.row,endLine:r.endPosition.row}]:[]}}function Vl(e,t,n,r){let i=t.namedChildren.map(a=>xe(e,a,n+1,new Set(r)));if(i.length>=2&&i.every(a=>a!==null)){let a=c=>c.precision==="literal"||c.precision==="constrained-pattern";if(!i.some(a))return L(t,"addition-operands-unproved");let o={kind:"concat",parts:i.map(c=>c.term)},s=i.map(c=>a(c)?c.value:"{}").join("");return ql(e.file,t,o,s,i.some(c=>c.precision!=="literal")?"constrained-pattern":"literal",i)}return null}function zl(e,t,n,r,i){let a=X(e.db,t.relativePath)?.rootNode;if(!a)return Kt(n,t.symbol,"import-definition-unparsed");let o=ga(a,t),s=o&&F(t.relativePath,a).constantInitializer(o);if(!s)return Kt(n,t.symbol,"import-definition-non-value");let c=xe({db:e.db,file:t.relativePath,root:a},s,r+1,i);return c?Jt(n,"imported-constant",c,t.symbol):Kt(n,t.symbol,"import-value-unresolved")}function Qt(e,t){let n=t.childForFieldName("function");if(!n||!["fetch","globalThis.fetch","window.fetch","self.fetch"].includes(n.text.replace(/\s+/gu,"")))return!1;let r=F(e.file,e.root);return r.available&&!r.hasLocalBinding(n)}function Me(e,t,n){return Wt(t,n,r=>{let i=U(e,r);return i&&["literal","constant"].includes(i.evidence)&&i.precision==="literal"?i.value:null})}function Zt(e,t){let n=Me(t,e,"method");if(n.kind==="absent")return"GET";if(n.kind==="unknown")return null;let r=U(t,n.node);return r&&r.precision==="literal"&&["literal","constant"].includes(r.evidence)?r.value.toUpperCase():null}import{createHash as Wl}from"crypto";function en(e){let t=e.replaceAll("\\","/");return va(t)==="test"?/(?:^|\/)__fixtures__\//iu.test(t)?"fixture":"test":/(?:^|\/)(?:fixtures?|testdata)\//iu.test(t)?"fixture":/(?:^|\/)(?:examples?|demos?|previews?)\//iu.test(t)?"example":/(?:^|\/)(?:generated|dist|build|coverage)\//iu.test(t)||/\.generated\./iu.test(t)?"generated":/^(?:scripts?|tools?)\//iu.test(t)?"script":"production"}var Kl=new WeakMap,yo=new Set(["delete","get","head","options","patch","post","put"]),bo=new Map([["express",new Set(["default","Router",null])],["fastify",new Set(["default","fastify",null])],["hono",new Set(["Hono"])],["koa-router",new Set(["default",null])],["@koa/router",new Set(["default","Router",null])]]),Xl=new Set(["findFirst","findMany","findUnique","from","get","select"]),Jl=new Set(["create","delete","insert","remove","update","upsert"]),Yl=new Set(["execute","query","raw"]),po=/(?:\b(?:name|id)|['"`](?:name|id)['"`])\s*:/u,mo=/(?:^\s*|[,{]\s*)(?:async\s+)?['"`]?(?:execute|handler|invoke|run)['"`]?\s*(?::|\([^)]*\)\s*\{)/mu,fo=/\b[A-Za-z_$][\w$-]*[_-][\w$-]*\s*\(/u,go=/\b(?:use|call|invoke|run|via|with|read|stop)(?:\s+the)?(?:\s+(?:tool|capability|command))?\s+[A-Za-z_$][\w$-]*\s*\(/iu,ar=[ru(),eu(),Zl(),au(),lu(),uu(),pu()],Ql=new Set(["exec","execFile","execFileSync","execSync","fork","spawn","spawnSync"]);function Zl(){return{id:"builtin.node-child-process",supports:e=>e.includes("child_process"),extract:e=>{let t=F(e.file,e.root),n=[];return oe(e.root,"call_expression",r=>{let i=r.childForFieldName("function"),a=i&&t.importedValue(i),o=a&&["node:child_process","child_process"].includes(a.module)?a.member:null;if(!o||!Ql.has(o))return;let s=Pe(r),c=V(s[0],e)??{value:s[0]?.text.trim()||"<missing>",evidence:"expression"},l=["exec","execFile","execFileSync","execSync"].includes(o)?"process.exec":"process.spawn";n.push(M(e,r,"builtin.node-child-process",l,[{name:"operation",value:o,evidence:"literal"},{name:"executable",...c}],"exact","node-child-process-import"))}),n}}}function G(e,t,n,r){let i=tn(r,"runtime-boundaries.context.ast",t,()=>n===void 0?X(e,t):Qi(e,t,n));if(!i)return Pt(t),null;let a=i.rootNode;n!==void 0&&Kl.set(a,i);let o=n??Et(e,t),s,c=()=>{if(s)return s;let l=tn(r,"runtime-boundaries.context.callable-sites",t,()=>{let d=K(t);return(d?ta(a,d):null)??Ft(e,t)?.callables??null}),u=tn(r,"runtime-boundaries.context.definitions",t,()=>D(e,t,{rangeCorrectionEvidence:{source:o,callables:l}},(d,p)=>tn(r,`runtime-boundaries.context.definitions.${d}`,t,p)));return s={definitions:u,owners:At(e,t,u,l??[])}};return{db:e,file:t,source:o,root:a,ownerAt:l=>{let{definitions:u,owners:d}=c(),p=K(t),m=p?Zi(l,p):null,f=u.filter(C=>!C.isFunctionLike&&C.startLine<=l.startPosition.row&&C.endLine>=l.endPosition.row),x=m?d.get(Lt(m)):f.length===1?f[0]:null;return{file:t,symbol:x?.symbol??null,name:m?.name??x?.leaf??null,startLine:m?.startLine??x?.startLine??l.startPosition.row,endLine:m?.endLine??x?.endLine??l.endPosition.row,startColumn:m?.startColumn??x?.startChar??l.startPosition.column,endColumn:m?.endColumn??x?.endChar??l.endPosition.column}}}}function tn(e,t,n,r){return e?e(t,r,{file:n}):r()}function eu(){return{id:"builtin.effect-httpapi",supports:e=>e.includes("effect/unstable/httpapi")||e.includes("@effect/platform"),extract:e=>{let t=[],n="HttpApiGroup",r="HttpApiBuilder";return oe(e.root,"call_expression",i=>{let a=xo(i);if(!a)return;let o=Pe(i);if(So(e,a.receiver,"HttpApiEndpoint")&&yo.has(a.member)){tu(t,e,i,a.member,o,n);return}nu(t,e,i,a.member,o,r)}),t}}}function tu(e,t,n,r,i,a){let o=V(i[0],t),s=V(i[1],t),c=vo(n,a,"make",0,t);if(!o||!s||!c)return;let l=r.toUpperCase();e.push(M(t,n,"builtin.effect-httpapi","http.handle",[{name:"method",value:l,evidence:"literal"},{name:"path",...s}],Re([{name:"path",...s}]),"effect-httpapi-endpoint-declaration")),e.push(M(t,n,"builtin.effect-httpapi","framework.declare",ir(c,o),Re(ir(c,o)),"effect-httpapi-operation-declaration"))}function nu(e,t,n,r,i,a){if(!["handle","handleRaw"].includes(r))return;let o=vo(n,a,"group",1,t),s=V(i[0],t),c=i[1];if(!o||!s||!c)return;let l=ir(o,s),u=oo(t,c),d=M(t,n,"builtin.effect-httpapi","framework.handle",l,u?Re(l):"candidate","effect-httpapi-handler-registration");u&&(d.owner={file:u.relativePath,symbol:u.symbol,name:u.leaf,startLine:u.startLine,endLine:u.endLine,startColumn:u.startChar,endColumn:u.endChar}),e.push(d)}function ir(e,t){return[{name:"adapter",value:"effect-httpapi",evidence:"literal"},{name:"group",...e},{name:"operation",...t}]}function So(e,t,n){let r=F(e.file,e.root).importedValue(t);return r?(r.module==="effect/unstable/httpapi"||r.module==="@effect/platform")&&r.member===n||r.module===`@effect/platform/${n}`&&r.member===null:!1}function vo(e,t,n,r,i){let a=e.parent;for(;a;){if(a.type==="call_expression"){let o=ho(a,t,n,r,i);if(o)return o;let s=a.childForFieldName("function")??a.namedChild(0),c=null;if(s&&Co(s,l=>{!c&&l.type==="call_expression"&&(c=ho(l,t,n,r,i))}),c)return c}a=a.parent}return null}function ho(e,t,n,r,i){let a=xo(e);return!a||a.member!==n||!So(i,a.receiver,t)?null:V(Pe(e)[r],i)}function xo(e){let t=e.childForFieldName("function")??e.namedChild(0);if(!t||!["member_expression","subscript_expression"].includes(t.type))return null;let n=t.childForFieldName("object")??t.namedChild(0),r=t.childForFieldName("property")??t.childForFieldName("index")??t.namedChild(1);return!n||!r?null:{receiver:n,member:r.text.replace(/^['"`]|['"`]$/gu,"")}}function ru(){return{id:"builtin.http",supports:e=>/\bfetch\s*\(|\baxios\b|\b(?:app|router|server)\s*\.\s*(?:get|post|put|patch|delete|options|head)\s*\(/u.test(e)||nn(e,["axios",...bo.keys()])||/\b(?:FastAPI|Flask|APIRouter|axum|Router::new)\b/u.test(e),extract:e=>{let t=[],n=o=>{let s=/^@[^\s(]+\.(get|post|put|patch|delete|options|head)\s*\(\s*(['"`])([^'"`]+)\2/iu.exec(o.text.trim());!s||!nn(e.source,["fastapi","flask"])||t.push(M(e,o,"builtin.http","http.handle",[{name:"method",value:s[1].toUpperCase(),evidence:"literal"},{name:"path",value:s[3],evidence:"literal"}],"candidate","framework-decorator-receiver-unverified"))},r=(o,s)=>{let c=V(s[0],e),l=/^\s*(get|post|put|patch|delete|options|head)\s*\(/iu.exec(s[1]?.text??"")?.[1];!c||!l||t.push(M(e,o,"builtin.http","http.handle",[{name:"method",value:l.toUpperCase(),evidence:"literal"},{name:"path",...c}],"candidate","framework-route-receiver-unverified"))},i=(o,s)=>{let c=V(s[0],e);if(!c)return;let l=Zt(s[1],e),u=[...l?[{name:"method",value:l,evidence:"literal"}]:[],{name:"path",...c}];t.push(M(e,o,"builtin.http","http.request",u,l?Re(u):"candidate","call-expression"))},a=(o,s,c)=>{if(!yo.has(c))return;let l=iu(e,o,c);if(!l)return;let u=V(s[0],e);u&&t.push(M(e,o,"builtin.http",l.action,[{name:"method",value:c.toUpperCase(),evidence:"literal"},{name:"path",...u},...l.action==="http.handle"?[{name:"router",...ae(e,l.router)}]:[]],Re([{name:"path",...u}]),l.evidence))};return oe(e.root,["decorator","call_expression"],o=>{if(o.type==="decorator")return n(o);if(o.type!=="call_expression")return;let s=an(o);if(!s)return;let c=s.split(".").at(-1)??"",l=Pe(o);if(c==="route"&&nn(e.source,["axum"]))return r(o,l);if(Qt(e,o))return i(o,l);a(o,l,c)}),t}}}function iu(e,t,n){let r=t.childForFieldName("function");if(!r)return null;let i=F(e.file,e.root),a=r.childForFieldName("object"),o=a&&i.constructedValue(a);if(o&&bo.get(o.module)?.has(o.member))return{action:"http.handle",evidence:"framework-adapter",router:a};let s=i.importedValue(r);return s?.module==="axios"&&s.member===n?{action:"http.request",evidence:"client-adapter"}:null}function au(){return{id:"builtin.capability-registry",supports:e=>po.test(e)&&mo.test(e)||fo.test(e)||go.test(e),extract:e=>{let t=[],n=new Set,r=[];return po.test(e.source)&&mo.test(e.source)&&r.push("pair"),(fo.test(e.source)||go.test(e.source))&&r.push("string","string_literal","template_string"),oe(e.root,r,i=>{if(i.type==="pair"){ou(t,n,e,i);return}su(t,n,e,i)}),t}}}function ou(e,t,n,r){let i=r.childForFieldName("key")??r.namedChild(0),a=r.childForFieldName("value")??r.namedChild(1),o=i?.text.replace(/^['"`]|['"`]$/gu,"");if(o!=="name"&&o!=="id")return;let s=yu(r);if(!s)return;let c=Ro(a,n);if(!c||c.evidence!=="literal")return;let l=`handle\0${c.value}\0${s.startPosition.row}`;t.has(l)||(t.add(l),e.push(M(n,s,"builtin.capability-registry","registry.handle",[{name:"key",...c}],"exact","capability-descriptor")))}function su(e,t,n,r){if(!["string","string_literal","template_string"].includes(r.type))return;let i=r.text.replace(/^['"`]|['"`]$/gu,"");for(let a of i.matchAll(/\b([A-Za-z_$][\w$-]*)\s*\(/gu)){let o=a[1];if(!cu(i,o,a.index))continue;let s=`reference\0${o}\0${r.startPosition.row}`;t.has(s)||(t.add(s),e.push(M(n,r,"builtin.capability-registry","registry.reference",[{name:"key",value:o,evidence:"literal"}],"exact","capability-instruction-reference")))}}function cu(e,t,n){if(t.includes("_")||t.includes("-"))return!0;let r=e.slice(Math.max(0,n-64),n);return/\b(?:use|call|invoke|run|via|with|read|stop)(?:\s+the)?(?:\s+(?:tool|capability|command))?\s*$/iu.test(r)}function lu(){return{id:"builtin.registry",supports:e=>/(?:Handlers?|Registry|Routes?)\b/iu.test(e),extract:e=>{let t=[];return oe(e.root,["pair","call_expression"],n=>{if(n.type==="pair"){Iu(e,n,t);return}if(n.type!=="call_expression")return;let r=n.childForFieldName("function")??n.namedChild(0);if(!r||r.type!=="subscript_expression")return;let i=r.childForFieldName("object"),a=V(r.childForFieldName("index"),e);if(!i||!a)return;let o=ae(e,i);t.push(M(e,n,"builtin.registry","registry.dispatch",[{name:"registry",...o},{name:"key",...a}],Re([{name:"registry",...o},{name:"key",...a}]),"indexed-access-call"))}),t}}}function uu(){return{id:"builtin.persistence",supports:e=>/\b(?:db|database|prisma|drizzle|[A-Za-z_$][\w$]*(?:Repository|Repo))\b[^;]{0,1024}?\.\s*(?:findFirst|findMany|findUnique|from|get|select|create|delete|insert|remove|update|upsert|execute|query|raw|transaction)(?:\s*<[^()]{1,512}>)?\s*\(/iu.test(e),extract:e=>{let t=[],n=xu(e.root);return oe(e.root,"call_expression",r=>{let i=an(r);if(!i)return;let a=i.split("."),o=a.at(-1)??"",s=Pe(r),c=s[0]?.text??"",l=vu(o,c);if(!l)return;let u=Io(a,n);if(!u)return;let d=du(s[0],e)??Ru(c),p=Pu(u,a,o,d);if(!p)return;let m=Eu(o,l,c);t.push(M(e,r,"builtin.persistence",l,[{name:"resource",...p}],"candidate",`${m}-receiver-and-resource-identity-unverified`))}),t}}}function du(e,t){if(!e)return null;let n=e.text.replace(/\s+/gu,"");return/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/u.test(n)?{value:n.split(".").at(-1),evidence:"identifier",term:{kind:"symbol",symbol:n}}:V(e,t)}function pu(){return{id:"builtin.queue",supports:e=>nn(e,["amqplib","bullmq","kafkajs","@aws-sdk/client-sqs","rabbitmq"])&&/\.(?:sendToQueue|consume|send|subscribe)\s*\(/u.test(e),extract:e=>{let t=[];return oe(e.root,"call_expression",n=>{let r=an(n);if(!r)return;let i=r.split(".").at(-1)??"",a=Pe(n),o=Cu(i);if(!o)return;let s=i==="send"||i==="subscribe"?gu(a[0],"topic",e):V(a[0],e);s&&t.push(M(e,n,"builtin.queue",o,[{name:"address",...s}],"candidate","queue-receiver-and-broker-identity-unverified"))}),t}}}function M(e,t,n,r,i,a,o){let s=e.ownerAt(t),c=JSON.stringify({extractor:n,action:r,file:e.file,line:t.startPosition.row,startColumn:t.startPosition.column,endLine:t.endPosition.row,endColumn:t.endPosition.column,keyParts:i});return{id:`boundary:${Wl("sha256").update(c).digest("hex").slice(0,16)}`,extractor:n,action:r,owner:s,source:{file:e.file,startLine:t.startPosition.row,endLine:t.endPosition.row,startColumn:t.startPosition.column,endColumn:t.endPosition.column},keyParts:i,evidence:o,strength:a,protocol:r.split(".")[0]??r,role:mu(r),executionDomain:fu(e.file),derivation:{kind:a==="candidate"?"heuristic":a==="derived"?"mechanically-derived":"direct",rule:o,ruleVersion:"1",inputFactIds:i.flatMap(l=>l.derivation?.inputFactIds??[]),sourceSpans:[{file:e.file,startLine:t.startPosition.row,endLine:t.endPosition.row},...i.flatMap(l=>l.derivation?.sourceSpans??[])]},valuePrecision:so(i),modality:"may",resolution:"unresolved",sourceScope:en(e.file)}}function mu(e){let t=e.split(".").at(-1)??e;return["handle","subscribe","consume","read"].includes(t)?"consumer":["request","publish","send","write","dispatch","reference","invoke","spawn","exec"].includes(t)?"producer":"observe"}function fu(e){let t=e.replaceAll("\\","/"),n=/^(apps|services|packages)\/([^/]+)/u.exec(t);return n?`${n[1]}/${n[2]}`:null}function nn(e,t){return t.some(n=>{let r=n.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`(?:\\bfrom\\s+${r}\\b|\\buse\\s+${r}\\b|(?:\\bfrom\\s*|\\brequire\\s*\\(\\s*)['"]${r}(?:[/']|"))`,"u").test(e)})}function rn(e,t,n,r,i,a,o){return M(e,t,n,r,i,a,o)}function an(e){return(e.childForFieldName("function")??e.namedChild(0))?.text.replace(/\s+/gu,"")??null}function Pe(e){return(e.childForFieldName("arguments")??e.namedChildren.find(n=>n.type==="arguments"))?.namedChildren??[]}function V(e,t){let n=U(t,e);return n?{value:n.value,evidence:n.evidence,term:n.term,precision:n.precision,derivation:n.derivation}:null}function gu(e,t,n){let r=Me(n,e??void 0,t);return r.kind==="value"?V(r.node,n):null}function Ro(e,t){if(!e)return null;let n=V(e,t);if(n?.evidence==="literal"||n?.evidence==="constant")return n;let r=e.text.trim();return/^[A-Za-z_$][\w$]*$/u.test(r)?{value:r,evidence:"identifier",term:{kind:"symbol",symbol:r}}:n}function Re(e,t="exact"){return t==="candidate"||e.some(n=>n.evidence==="expression"||["unknown","constrained-pattern","finite-set"].includes(rr(n)))?"candidate":t==="derived"||e.some(n=>n.evidence==="constant")?"derived":"exact"}function hu(e){let t=e.parent,n=t?.parent??null;for(;n&&["as_expression","satisfies_expression","type_assertion","parenthesized_expression"].includes(n.type);)n=n.parent;if(!t||!n||n.type!=="variable_declarator")return null;let r=n.childForFieldName("name")??n.namedChild(0),i=r?.text??"";return/(?:handlers?|registry|routes?)$/iu.test(i)?r:null}function or(e){return/(?:function|lambda|method)/u.test(e.type)||e.type==="arrow_function"}function Po(e){return or(e)||e.type==="member_expression"?!0:e.type==="identifier"&&/(?:command|controller|dispatch|handle|handler)/iu.test(e.text)}function yu(e){let t=e.parent;for(;t&&t.type!=="variable_declarator";){if(["object","object_literal","dictionary"].includes(t.type)){for(let n of t.namedChildren)if(bu(n))return t}t=t.parent}return null}function bu(e){if(e.type==="pair"&&Su(e))return!0;let t=e.childForFieldName("name")??e.namedChild(0);return!!(t&&["execute","handler","invoke","run"].includes(t.text.replace(/^['"`]|['"`]$/gu,""))&&/(?:function|method)/u.test(e.type))}function Su(e){let t=e.childForFieldName("key")??e.namedChild(0),n=e.childForFieldName("value")??e.namedChild(1),r=t?.text.replace(/^['"`]|['"`]$/gu,"");return!!r&&["execute","handler","invoke","run"].includes(r)&&!!n&&Po(n)}function Io(e,t=new Set){let n=e.slice(0,-1).map(r=>r.replace(/\([^)]*\)/gu,""));return n.some(r=>/^(?:prisma|drizzle)$/iu.test(r))?"orm":n.some(r=>/(?:Repository|Repo)$/u.test(r))?"repository":n.some(r=>/^(?:db|database)$/iu.test(r)||t.has(r))?"database":null}function vu(e,t){if(Xl.has(e))return"database.read";if(Jl.has(e))return"database.write";if(!Yl.has(e))return null;let n=/\b(SELECT|INSERT|UPDATE|DELETE)\b/iu.exec(t)?.[1]?.toUpperCase();return n==="SELECT"?"database.read":n?"database.write":null}function xu(e){let t=new Set;return oe(e,"call_expression",n=>{let r=an(n);if(!r)return;let i=r.split(".");if(!(i.at(-1)!=="transaction"||!Io(i)))for(let a of Pe(n)){if(!or(a))continue;let s=(a.childForFieldName("parameters")??a.namedChildren.find(l=>/parameters/u.test(l.type)))?.namedChildren[0],c=s?Ji(s):null;c&&t.add(c)}}),t}function Ru(e){let t=Eo(e);return t?{value:t,evidence:"identifier",term:{kind:"symbol",symbol:t}}:null}function Pu(e,t,n,r){if(e==="orm"&&t.length>=3)return{value:t.at(-2).replace(/\([^)]*\)/gu,""),evidence:"identifier"};if(e==="repository"){let a=t.at(-2)?.replace(/(?:Repository|Repo)$/u,"");return a?{value:a,evidence:"identifier"}:null}if(!r)return null;if(n==="from"||n==="insert")return r;let i=Eo(r.value);return i?{value:i,evidence:r.evidence}:null}function Eo(e){return/\b(?:from|into|update|table)\s+(?:\$\{\s*)?['"`]?([A-Za-z_$][\w$.-]*)/iu.exec(e)?.[1]??null}function Co(e,t){t(e);for(let n of e.namedChildren)Co(n,t)}function oe(e,t,n){for(let r of wt(e,t))n(r)}function Iu(e,t,n){let r=hu(t);if(!r)return;let i=t.childForFieldName("key")??t.namedChild(0),a=t.childForFieldName("value")??t.namedChild(1),o=Ro(i,e);if(!o||!a||!Po(a))return;let s=ae(e,r),c=Me(e,t.parent??void 0,o.value);if(c.kind==="value"&&c.node.startIndex!==a.startIndex)return;let u=!F(e.file,e.root).hasObservedWrite(r,!0)&&c.kind==="value"&&or(a)?"exact":"candidate";n.push(M(e,t,"builtin.registry","registry.handle",[{name:"registry",...s},{name:"key",...o}],Re([{name:"registry",...s},{name:"key",...o}],u),"object-member"))}function Eu(e,t,n){return e==="insert"?"persistence-insert":t==="database.read"&&/\bFOR\s+UPDATE\s+SKIP\s+LOCKED\b/iu.test(n)?"persistence-skip-locked-claim":"persistence-adapter"}function Cu(e){return e==="sendToQueue"||e==="send"?"queue.send":e==="consume"||e==="subscribe"?"queue.consume":null}var Tu=Ne("resolved-call-syntax",{clearGroups:[]}),sr=Ne("resolved-call-sites",{clearGroups:[]}),wu=Ne("resolved-call-sites-reference-evidence",{clearGroups:[]});function cr(e,t){return sr.get(e,t.symbolId,()=>wo(e,t,Fu(e,t)))}function To(e,t){let n=[...new Map(t.map(a=>[a.symbolId,a])).values()],r=n.filter(a=>!sr.has(e,a.symbolId)),i=Fo(e,r);return new Map(n.map(a=>[a.symbolId,sr.get(e,a.symbolId,()=>wo(e,a,i.get(a.symbolId)??[]))]))}function wo(e,t,n){let r=[],i=[],a=new Set,o=new Set;for(let s of n){a.add(s.file);let c=Tu.get(e,s.file,()=>Nu(e,s.file));if(!c){i.push({callee:t,file:s.file,line:s.startLine,reason:"ast-unavailable",candidates:0,referenceProvenance:s.provenance});continue}let l=ya(e,s.file,s.startLine,s.endLine,new Set([t.symbol]));if(!l.available){i.push({callee:t,file:s.file,line:s.startLine,reason:"compiler-binding-unavailable",candidates:0,referenceProvenance:s.provenance});continue}let u=At(e,s.file,D(e,s.file));for(let d of l.targets.filter(p=>p.definition.symbol===t.symbol)){if(d.implementationStatus==="unresolved"){i.push({callee:t,file:s.file,line:d.sourceLine,reason:"implementation-unresolved",candidates:1,referenceProvenance:s.provenance});continue}let p=c.calls.filter(x=>Xe(x.targetRange,d.sourceRange));if(p.length!==1){i.push({callee:t,file:s.file,line:d.sourceLine,reason:p.length?"ambiguous-call":"call-not-found",candidates:p.length,referenceProvenance:s.provenance});continue}let m=p[0],f=`${s.file}\0${m.callNode.startIndex}\0${m.callNode.endIndex}`;o.has(f)||(o.add(f),r.push({callee:t,caller:u.get(Lt(d.sourceOwner??null))??null,file:s.file,line:m.callNode.startPosition.row,startLine:m.callNode.startPosition.row,endLine:m.callNode.endPosition.row,targetText:m.targetNode.text,callNode:m.callNode,targetNode:m.targetNode,arguments:m.arguments,referenceProvenance:s.provenance}))}}return{sites:r,unresolved:i,filesVisited:a.size}}function Fu(e,t){return Fo(e,[t]).get(t.symbolId)??[]}function Fo(e,t){if(!_u(e))return new Map(t.map(r=>[r.symbolId,Sa(e,r,{semantic:!1}).map(i=>({file:i.file,startLine:i.line,endLine:i.line,provenance:i.provenance}))]));let n=new Map;for(let r of ba(e,t.map(i=>i.symbolId))){let i=n.get(r.symbol_id)??[];i.push({file:r.relative_path,startLine:r.chunk_start,endLine:r.chunk_end,provenance:"scip-reference-chunk"}),n.set(r.symbol_id,i)}return new Map(t.map(r=>[r.symbolId,n.get(r.symbolId)??[]]))}function _u(e){return wu.get(e,"project",()=>!!e.get("SELECT 1 AS present FROM mentions WHERE role != 1 LIMIT 1"))}function Nu(e,t){let n=X(e,t)?.rootNode,r=K(t);if(!n||!r)return null;let i=[];for(let a of wt(n,["call_expression","call","new_expression"])){let o=ea(a,r),s=a.childForFieldName("function")??a.childForFieldName("constructor")??a.namedChild(0);if(!o||!s)continue;let c=a.childForFieldName("arguments")??a.namedChildren.find(l=>l.type==="arguments");i.push({callNode:a,targetNode:s,targetRange:o.targetRange,arguments:c?.namedChildren.filter(l=>l.type!=="comment")??[]})}return{calls:i}}var Ou=Ne("call-parameter-value-flow",{clearGroups:[]});function et(e,t){let n=`${t.callee.symbolId}\0${t.file}\0${t.callNode.startIndex}\0${t.callNode.endIndex}`;return Ou.get(e,n,()=>Du(e,t,ku(e,t)))}function Du(e,t,n){let r=X(e,t.callee.relativePath)?.rootNode,i=Je(e,t.callee.relativePath,t.callee),a=r&&i?Q(r,i.startLine,i.endLine,Y,i):null,o=r?F(t.callee.relativePath,r):null;if(o&&!o.available)return n;let s=a&&o?o.callableParameters(a):null,c=s?.indexOf("rest")??-1,l=p=>s?c>=0&&p>=c?"callee-parameter-transform":p>=s.length?"argument-without-parameter":s[p]==="direct"?null:"callee-parameter-transform":"callee-parameter-unavailable",u=n.transfers.filter(p=>l(p.calleePosition)===null),d=n.transfers.flatMap(p=>{let m=l(p.calleePosition);return m?[{calleePosition:p.calleePosition,argumentText:p.argumentText,proof:p.proof,reason:m}]:[]});return{...n,transfers:u,unknown:[...n.unknown.map(p=>({...p,reason:l(p.calleePosition)??p.reason})),...d]}}function tt(e,t){let n=new Set(t);return[...new Set(e.transfers.flatMap(r=>n.has(r.calleePosition)?[r.callerPosition]:[]))].sort((r,i)=>r-i)}function ku(e,t){let n={file:t.file,startLine:t.startLine,endLine:t.endLine,startColumn:t.callNode.startPosition.column,endColumn:t.callNode.endPosition.column};if(!t.caller)return{callee:t.callee,caller:null,call:n,transfers:[],unknown:t.arguments.map((d,p)=>({calleePosition:p,argumentText:d.text.trim(),reason:"caller-unavailable",proof:n}))};let r=X(e,t.caller.relativePath)?.rootNode,i=Je(e,t.file,t.caller),a=r&&i?Q(r,i.startLine,i.endLine,Y,i):null;if(!a)return{callee:t.callee,caller:t.caller,call:n,transfers:[],unknown:t.arguments.map((d,p)=>({calleePosition:p,argumentText:d.text.trim(),reason:"caller-syntax-unavailable",proof:n}))};let o=F(t.file,r),s=!1,c=[],l=[];return t.arguments.flatMap(d=>{if(d.type!=="spread_element")return[d];let p=d.namedChild(0);return(p&&o.tupleElements(p))??[d]}).forEach((d,p)=>{let m=d.text.trim();s||=["spread_element","list_splat","dictionary_splat"].includes(d.type);let f=s?null:o.available?o.directParameterPosition(d):Lu(e,t.file,a,d);f!==null?c.push({calleePosition:p,callerPosition:f,argumentText:m,proof:n}):l.push({calleePosition:p,argumentText:m,reason:"argument-not-direct-parameter",proof:n})}),{callee:t.callee,caller:t.caller,call:n,transfers:c,unknown:l}}function Lu(e,t,n,r){if(r.type!=="identifier")return null;let i=Ye(e,t)?.locals??[],a=l=>i.find(u=>u.line===l.startPosition.row&&u.startChar===l.startPosition.column&&u.endLine===l.endPosition.row&&u.endChar===l.endPosition.column)?.symbol,o=a(r);if(!o)return null;let c=(n.childForFieldName("parameters")?.namedChildren.filter(l=>l.type!=="comment")??[]).findIndex(l=>{let u=l.childForFieldName("pattern")??l.childForFieldName("name")??l;return u.type==="identifier"&&a(u)===o});return c<0?null:c}var Au=8,Mu=8;function No(e,t){let n=[],r=Bu(e,t,n);return{summaries:[...r.summaries.values()],filesInspected:r.filesInspected,errors:n}}function Oo(e,t,n){let r=[...n.errors],i=new Map(n.summaries.map(s=>[s.definition.symbol,s])),a=$u(e,t,i,r),o=zu(e,t,r);return{observations:id([...a.observations,...o]),bodySummaries:i.size,discriminatorSummaries:a.summaries,filesInspected:n.filesInspected,errors:r}}function ju(e,t,n,r,i){for(let a of cr(e,t.definition).sites){if(!n(a.file))continue;let s=a.caller;if(!s)continue;let c=tt(et(e,a),t.parameterIndexes);if(c.length===0)continue;let l={definition:s,parameterIndexes:Bo(c),depth:t.depth+1,proofSpans:[...t.proofSpans,{file:a.file,startLine:a.startLine,endLine:a.endLine}]};Zu(r,l)&&i.push(r.get(s.symbol))}}function Bu(e,t,n){let r=new Map,i=[],a=new Map,o=c=>{if(a.has(c))return a.get(c)??null;let l=G(e,c);return a.set(c,l),l},s=new Map([...new Set(t.map(c=>c.definition.relativePath))].flatMap(c=>D(e,c)).map(c=>[_o(c),c]));for(let c of t){let l=s.get(_o(c.definition));if(!l){n.push(`builtin.carrier body summary definition is unavailable: ${c.definition.symbol}`);continue}let u={...c,definition:l,depth:0,proofSpans:[{file:c.definition.relativePath,startLine:c.definition.startLine,endLine:c.definition.endLine}]};r.set(c.definition.symbol,u),i.push(u)}for(;i.length>0;){let c=i.shift();if(!(c.depth>=Au))try{ju(e,c,o,r,i)}catch(l){n.push(`builtin.carrier body summary failed for ${c.definition.relativePath}: ${dr(l)}`)}}return{summaries:r,filesInspected:new Set(t.map(c=>c.definition.relativePath)).size}}function _o(e){return`${e.symbol}\0${e.relativePath}\0${e.startLine}\0${e.startChar}`}function $u(e,t,n,r){let i={summaries:new Map,queue:[],produced:[]};for(let a of t){let o=Gu(e,a,n);o&&qu(a,o,i)}for(;i.queue.length>0;){let a=i.queue.shift();if(!(a.depth>=Mu))try{Vu(e,a,i)}catch(o){r.push(`builtin.carrier discriminator summary failed for ${a.definition.relativePath}: ${dr(o)}`)}}return{observations:i.produced,summaries:i.summaries.size}}function Do(e,t){let n=ed(t);e.summaries.has(n)||(e.summaries.set(n,t),e.queue.push(t))}function Uu(e,t,n,r){let i=Ao(n.root,t.source.startLine),a=i.find(l=>l.startPosition.row===t.source.startLine)??i[0];if(!a)return null;let o=ur(a);if(!o)return null;let s=zt(e,t.source.file,o.text);if(s.length!==1)return null;let c=r.get(s[0].symbol);return c?{boundaryCall:a,bodySummary:c}:null}function Gu(e,t,n){if(t.action!=="http.request"||t.strength==="candidate"||t.sourceScope!=="production")return null;let r=Lo(t);if(!r)return null;let i=G(e,t.source.file);if(!i)return null;let a=Uu(e,t,i,n);if(!a)return null;let{boundaryCall:o,bodySummary:s}=a,c=t.owner.symbol?D(e,t.owner.file).find(d=>d.symbol===t.owner.symbol):null;if(!c)return null;let l=td(i,c),u=sn(o);return{carrier:r,context:i,owner:c,ownerParameters:l,args:u,bodySummary:s}}function Hu(e,t,n,r){let{carrier:i,context:a,owner:o,ownerParameters:s}=t;for(let c of rd(r)){let l=Mo(c),u=jo(c);if(!l||!u)continue;let d=s.indexOf(u.text.trim());if(d>=0){let m={definition:o,carrier:i,field:l,parameterIndex:d,depth:0,proofObservationIds:[e.id],proofSpans:[e.source,{file:e.source.file,startLine:c.startPosition.row,endLine:c.endPosition.row}]};Do(n,m);continue}let p=U(a,u);!p||p.precision!=="literal"||p.evidence==="expression"||n.produced.push(lr(a,c,"carrier.publish",i,l,p.value,[e.id]))}}function qu(e,t,n){let{context:r,args:i,bodySummary:a}=t;for(let o of a.parameterIndexes){let s=nd(r,i[o]);s&&Hu(e,t,n,s)}}function Vu(e,t,n){for(let r of cr(e,t.definition).sites){let i=G(e,r.file);if(!i)continue;let a=r.callNode,o=sn(a)[t.parameterIndex];if(!o)continue;let s=U(i,o);s&&s.precision==="literal"&&s.evidence!=="expression"&&n.produced.push(lr(i,a,"carrier.publish",t.carrier,t.field,s.value,t.proofObservationIds));let c=r.caller;if(!c)continue;let l=et(e,r).transfers.find(d=>d.calleePosition===t.parameterIndex)?.callerPosition;if(l===void 0)continue;let u={...t,definition:c,parameterIndex:l,depth:t.depth+1,proofSpans:[...t.proofSpans,{file:r.file,startLine:r.startLine,endLine:r.endLine}]};Do(n,u)}}function zu(e,t,n){let r=[],i=t.filter(a=>a.action==="registry.handle"&&a.strength!=="candidate"&&a.sourceScope==="production");for(let a of t){if(a.action!=="http.handle"||a.strength==="candidate"||a.sourceScope!=="production")continue;let o=Lo(a);if(!o)continue;let s=G(e,a.source.file);if(!s)continue;let c=Ao(s.root,a.source.startLine)[0];if(c)for(let l of sn(c).slice(1)){let u=zt(e,a.source.file,l.text);for(let d of u)Wu(e,a,o,d,i,r,n)}}return r}function Wu(e,t,n,r,i,a,o){try{let s=G(e,r.relativePath);if(!s)return;let c=on(s,r);if(!c)return;ne(c,l=>Ku(e,t,n,r,s,l,i,a))}catch(s){o.push(`builtin.carrier consumer analysis failed for ${r.relativePath}: ${dr(s)}`)}}function Ku(e,t,n,r,i,a,o,s){if(a.type!=="call_expression")return;let c=ur(a);if(!c)return;let l=/^([A-Za-z_$][\w$]*)\s*\[\s*([A-Za-z_$][\w$]*)\s*\]$/u.exec(c.text.trim());if(!l)return;let u=l[1],d=l[2],p=Yu(e,i,r,d);if(!p)return;let m=Qu(e,r.relativePath,u);for(let f of o)Xu(e,t,n,p,m,f,s)}function Xu(e,t,n,r,i,a,o){let s=a.keyParts.find(d=>d.name==="registry")?.value,c=a.keyParts.find(d=>d.name==="key")?.value;if(!s||!c||!i.some(d=>d.file===a.source.file&&d.binding===s))return;let l=G(e,a.source.file),u=l?Q(l.root,a.source.startLine,a.source.endLine,Y,a.source):null;!l||!u||o.push(lr(l,u,"carrier.consume",n,r,c,[t.id,a.id]))}function ko(e){let t=D(e.db,e.file),n=new Map;return ne(e.root,r=>{if(r.type!=="pair"||Mo(r)?.toLowerCase()!=="body")return;let i=jo(r);if(!i||!/\bJSON\.stringify\s*\(/u.test(i.text))return;let a=ua(t,r.startPosition.row),o=Ju(r);if(!a||!o)return;let s=Hn(o),c=new Set;Yi(i,s,c);let l=n.get(a.symbol)??new Set;s.forEach((u,d)=>{u&&c.has(u)&&l.add(d)}),l.size>0&&n.set(a.symbol,l)}),t.flatMap(r=>{let i=n.get(r.symbol),{symbol:a,relativePath:o,startLine:s,startChar:c,endLine:l,endChar:u}=r;return i?[{definition:{symbol:a,relativePath:o,startLine:s,startChar:c,endLine:l,endChar:u},parameterIndexes:[...i].sort((d,p)=>d-p)}]:[]})}function Ju(e){let t=e.parent;for(;t;){if(/(?:function|method|lambda)/u.test(t.type)||t.type==="arrow_function")return t;t=t.parent}return null}function Yu(e,t,n,r){let i=on(t,n);if(!i)return null;let a=new RegExp(`\\.body\\??\\.${Ct(r)}\\b`,"u");if(a.test(i.text))return r;let o=null;if(ne(i,u=>{if(o||u.type!=="variable_declarator")return;let d=u.childForFieldName("name")??u.namedChild(0),p=u.childForFieldName("value")??u.namedChild(1);!d||!p||!new RegExp(`(?:^|[,{}])\\s*${Ct(r)}\\s*(?:[,}]|$)`,"u").test(d.text)||p.type==="call_expression"&&(o=ur(p)?.text??null)}),!o)return null;let s=zt(e,n.relativePath,o);if(s.length!==1)return null;let c=G(e,s[0].relativePath),l=c?on(c,s[0]):null;return l&&a.test(l.text)&&new RegExp(`\\b${Ct(r)}\\s*[,}]`,"u").test(l.text)?r:null}function Qu(e,t,n){let r=[];for(let i of Zn(e,t,n)){let a=q(i.initializer);if(a.type==="call_expression")for(let o of sn(a)){let s=o.text.trim();if(/^[A-Za-z_$][\w$]*$/u.test(s))for(let c of Zn(e,i.definition.relativePath,s))r.push({file:c.definition.relativePath,binding:c.definition.leaf})}}return[...new Map(r.map(i=>[`${i.file}\0${i.binding}`,i])).values()]}function lr(e,t,n,r,i,a,o){let c=rn(e,t,"builtin.carrier",n,[{name:"carrier",value:r,evidence:"constant",term:{kind:"literal",value:r}},{name:"field",value:i,evidence:"literal",term:{kind:"literal",value:i}},{name:"value",value:a,evidence:"constant",term:{kind:"literal",value:a}}],"candidate","http-body-registry-discriminator-unverified-flow");return c.derivation={kind:"mechanically-derived",rule:"http-body-registry-discriminator",ruleVersion:"1",inputFactIds:[...o],sourceSpans:[c.source]},c}function Lo(e){let t=e.keyParts.find(r=>r.name==="method"&&r.evidence!=="expression")?.value,n=e.keyParts.find(r=>r.name==="path"&&r.evidence!=="expression")?.value;return t&&n?`${t.toUpperCase()} ${n}`:null}function Zu(e,t){let n=e.get(t.definition.symbol);if(!n)return e.set(t.definition.symbol,t),!0;let r=Bo([...n.parameterIndexes,...t.parameterIndexes]);return r.length===n.parameterIndexes.length&&t.depth>=n.depth?!1:(e.set(t.definition.symbol,{...n,parameterIndexes:r,depth:Math.min(n.depth,t.depth),proofSpans:[...n.proofSpans,...t.proofSpans]}),!0)}function ed(e){return`${e.definition.symbol}\0${e.carrier}\0${e.field}\0${e.parameterIndex}`}function td(e,t){let n=on(e,t);return n?Hn(n):[]}function Ao(e,t){let n=[];return ne(e,r=>{r.type==="call_expression"&&r.startPosition.row<=t&&r.endPosition.row>=t&&n.push(r)}),n.sort((r,i)=>r.endIndex-r.startIndex-(i.endIndex-i.startIndex))}function ur(e){return e.childForFieldName("function")??e.namedChild(0)}function sn(e){return(e.childForFieldName("arguments")??e.namedChildren.find(n=>n.type==="arguments"))?.namedChildren??[]}function nd(e,t){if(!t)return null;let n=t.text.trim();if(!/^[A-Za-z_$][\w$]*$/u.test(n))return q(t);let r=null;return ne(e.root,i=>{r||i.type!=="variable_declarator"||(i.childForFieldName("name")??i.namedChild(0))?.text.trim()!==n||(r=i.childForFieldName("value")??i.namedChild(1))}),r?q(r):q(t)}function rd(e){let t=q(e);return t.type==="object"?t.namedChildren.filter(n=>n.type==="pair"||n.type==="shorthand_property_identifier"):[]}function Mo(e){return e.type==="shorthand_property_identifier"?e.text:(e.childForFieldName("key")??e.namedChild(0))?.text.replace(/^['"`]|['"`]$/gu,"")??null}function jo(e){return e.type==="shorthand_property_identifier"?e:e.childForFieldName("value")??e.namedChild(1)}function Bo(e){return[...new Set(e)].sort((t,n)=>t-n)}function id(e){return[...new Map(e.map(t=>[t.id,t])).values()]}function dr(e){return e instanceof Error?e.message:String(e)}function on(e,t){let n=Je(e.db,e.file,t);return t.symbol.startsWith("source-callable:")?Q(e.root,t.startLine,t.endLine,Y,{startColumn:t.startChar,endColumn:t.endChar}):n?Q(e.root,n.startLine,n.endLine,Y,n):null}import{createHash as Uo}from"crypto";var $o=Se({kind:"runtime-boundary-mount-imports",invalidation:ve("runtime-boundary-mount-imports"),serialize:JSON.stringify,deserialize:e=>e==="true"?!0:e==="false"?!1:null});function Go(e,t){let n=ad(t),r=[],i=sd(e),a=[...i.frontiers],o=[...n].flatMap(([c,l])=>l.map(u=>({identity:c,handler:u,visited:new Set([c])}))),s=new Map;for(let c of i.mounts){let l=s.get(c.targetIdentity)??[];l.push(c),s.set(c.targetIdentity,l)}for(let c=0;c<o.length;c++){let l=o[c];for(let u of s.get(l.identity)??[]){if(r.length>=1e4)return a.push(cn(u.source,"http-mount-composition-limit",["remaining-mount-paths"])),{observations:r,filesInspected:i.filesInspected,mounts:i.mounts.length,frontiers:a};let d=od(l,u,r,a);d&&o.push(d)}}return{observations:r,filesInspected:i.filesInspected,mounts:i.mounts.length,frontiers:a}}function ad(e){let t=new Map;for(let n of e){if(n.action!=="http.handle"||n.sourceScope!=="production"||n.strength==="candidate")continue;let r=n.keyParts.find(a=>a.name==="router");if(r?.term?.kind!=="symbol"||r.evidence==="expression")continue;let i=t.get(r.term.symbol)??[];i.push(n),t.set(r.term.symbol,i)}return t}function od(e,t,n,r){let i=t.receiver.term;if(i?.kind!=="symbol")return null;if(e.visited.has(i.symbol))return r.push(cn(t.source,"http-mount-cycle",["acyclic-router-path"])),null;let a=n.length;return md(t,e.handler,n),n.length===a?null:{identity:i.symbol,handler:n.at(-1),visited:new Set(e.visited).add(i.symbol)}}function cn(e,t,n){return{observationId:`mount:${e.file}:${e.startLine}:${e.startColumn}:${t}`,reason:t,missingKeyParts:n,sourceScope:"production",kind:"value-flow",action:"http.handle",strength:"candidate",source:e}}function sd(e){let t=[],n=[],r=_t(e);for(let i of r){if(!["typescript","tsx","javascript"].includes(K(i)??""))continue;let a=Et(e,i),o=Uo("sha256").update(a).digest("hex");if($o.read(e,i,o)===!1)continue;let s=la(i,a);if(!s)continue;let c=s.some(u=>u.literal&&u.specifier==="express");if($o.write(e,i,o,c),!c)continue;let l=G(e,i,a);l&&qo(l.root,u=>ud(l,u,t,n))}return{mounts:t,filesInspected:r.length,frontiers:n}}function cd(e,t){if(t.type!=="call_expression")return null;let n=t.childForFieldName("function")??t.namedChild(0);if(n?.type!=="member_expression"||n.childForFieldName("property")?.text!=="use")return null;let r=n.childForFieldName("object");return r&&Ho(e,r)?r:null}function Ho(e,t){let n=F(e.file,e.root).constructedValue(t);return n?.module==="express"&&[null,"default","Router"].includes(n.member)}function ld(e,t){let n=t[0];if(!n)return null;let r=U(e,n);return r&&r.evidence!=="expression"&&r.precision==="literal"?{prefix:r,routers:t.slice(1)}:t.length===1||Ho(e,n)?{prefix:{value:"/",evidence:"constant",term:{kind:"literal",value:"/"}},routers:t}:null}function ud(e,t,n,r){let i=cd(e,t);if(!i)return;let a={file:e.file,startLine:t.startPosition.row,startColumn:t.startPosition.column,endLine:t.endPosition.row,endColumn:t.endPosition.column},o=ld(e,pd(t));if(!o){r.push(cn(a,"http-mount-prefix-unresolved",["literal-prefix"]));return}for(let s of o.routers){let c=ae(e,s);if(c.evidence==="expression"||c.term?.kind!=="symbol"){r.push(cn(a,"http-mount-target-unresolved",["router-instance-binding"]));continue}n.push({file:e.file,line:t.startPosition.row,prefix:o.prefix,targetIdentity:c.term.symbol,receiver:{name:"router",...ae(e,i)},source:a})}}function dd(e,t){let n=e==="/"?"":e.replace(/\/+$/u,""),r=t.startsWith("/")?t:`/${t}`;return`${n}${r}`||"/"}function pd(e){return(e.childForFieldName("arguments")??e.namedChildren.find(n=>n.type==="arguments"))?.namedChildren??[]}function qo(e,t){t(e);for(let n of e.namedChildren)qo(n,t)}function md(e,t,n){let r=t.keyParts.find(s=>s.name==="path");if(!r||r.evidence==="expression")return;let i=dd(e.prefix.value,r.value),a=t.keyParts.map(s=>s.name==="router"?e.receiver:s.name==="path"?{name:"path",value:i,evidence:"constant",term:{kind:"concat",parts:[e.prefix.term??{kind:"literal",value:e.prefix.value},r.term??{kind:"literal",value:r.value}]},derivation:{kind:"mechanically-derived",rule:"http.mount-prefix",ruleVersion:"1",inputFactIds:[t.id],sourceSpans:[t.source,e.source,...e.prefix.derivation?.sourceSpans??[],...r.derivation?.sourceSpans??[]]}}:s),o=`${t.id}\0${e.file}\0${e.line}:${e.source.startColumn}\0${i}`;n.push({...t,id:`boundary:${Uo("sha256").update(o).digest("hex").slice(0,16)}`,keyParts:a,strength:"derived",evidence:"framework-mount-composition",derivation:{kind:"mechanically-derived",rule:"http.mount-prefix",ruleVersion:"1",inputFactIds:[t.id],sourceSpans:[t.source,e.source]},resolution:"unresolved"})}function je(e){return[...new Map(e.map(t=>[t.observationId,t])).values()].sort((t,n)=>t.observationId.localeCompare(n.observationId))}import{createHash as fd}from"crypto";var nt=new Set(["DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT"]),gd=8;function pr(e){return e.filter(t=>t.action==="http.request"&&!!t.owner.symbol&&(t.evidence==="call-expression"||t.evidence==="client-adapter"))}var Vo=Se({kind:"runtime-boundary-http-roles",invalidation:ve("runtime-boundary-http-roles"),serialize:Rd,deserialize:Pd});function Wo(e,t,n){let r=n??((g,b)=>b()),i=new Map,a=[],o=[],s=new Set,c=[],l=[],u=new Map,d=new Map,p=new Map,m=g=>{if(u.has(g))return u.get(g)??null;let b=G(e,g);return u.set(g,b),b},f=g=>{let b=d.get(g);if(b)return b;let y=D(e,g);return d.set(g,y),y},x=(g,b,y)=>{let R=p.get(g.file);if(!R){let E=he(e,g.file,g.source),T=Vo.read(e,g.file,E)??[];R={contentHash:E,roles:new Map(T.map(z=>[z.symbol,z])),dirty:!1},p.set(g.file,R)}let S=`v2:${b.symbol}:${y.startLine}:${y.startColumn}:${y.endLine}:${y.endColumn}`,v=R.roles.get(S);if(v)return v;let h=vd(g,y);return R.roles.set(S,{symbol:S,...h}),R.dirty=!0,h};r("runtime-boundaries.http-summary.seed",()=>{for(let g of pr(t)){let b=f(g.owner.file).find(v=>v.symbol===g.owner.symbol);if(!b)continue;let y=m(b.relativePath);if(!y)continue;let R=x(y,b,g.source),S={definition:b,...R,depth:0,proofObservationIds:[g.id],proofSpans:[g.source]};Ko(i,S)&&a.push(S)}});let C={db:e,summaries:i,queue:a,derived:o,filesInspected:s,errors:c,frontiers:l,contextForFile:m};for(;a.length>0;){let g=a.splice(0,a.length),b=r("runtime-boundaries.http-summary.resolve-call-sites",()=>To(e,g.map(y=>y.definition)),{batchSize:g.length});r("runtime-boundaries.http-summary.process-call-sites",()=>{for(let y of g)hd(y,b,C)},{batchSize:g.length})}return Vo.writeBatch(e,[...p.entries()].flatMap(([g,b])=>b.dirty?[{relativePath:g,contentHash:b.contentHash,value:[...b.roles.values()].sort((y,R)=>y.symbol.localeCompare(R.symbol))}]:[])),{observations:o,frontiers:je(l),summaries:i.size,filesInspected:s.size,errors:c,summarySymbols:rt([...i.values()].map(g=>g.definition.symbol)),inspectedFiles:[...s].sort()}}function hd(e,t,n){let{errors:r,frontiers:i}=n;if(!(e.depth>=gd))try{let a=t.get(e.definition.symbolId);if(!a)return;i.push(...a.unresolved.map(o=>bd(e,o)));for(let o of a.sites)yd(e,o,n)}catch(a){r.push(`builtin.http-summary failed for ${e.definition.relativePath}:${e.definition.startLine+1}: ${a instanceof Error?a.message:String(a)}`)}}function yd(e,t,n){let{db:r,summaries:i,queue:a,derived:o,filesInspected:s,contextForFile:c}=n,l=c(t.file);if(!l)return;s.add(t.file);let u=t.callNode,d=Sd(e,u,l);d&&o.push(d);let p=t.caller;if(!p)return;let m=Id(r,e,t),f={definition:p,...m,constantMethods:rt([...e.constantMethods,...xd(e,u,l)]),depth:e.depth+1,proofObservationIds:rt([...e.proofObservationIds,...d?[d.id]:[]]),proofSpans:[...e.proofSpans,{file:t.file,startLine:t.startLine,endLine:t.endLine}]};Ko(i,f)&&a.push(f)}function bd(e,t){let n=rt([...e.pathParameterIndexes.length>0?["path"]:[],...e.methodParameterIndexes.length>0&&e.constantMethods.length!==1?["method"]:[]]),r=e.constantMethods.length===1?e.constantMethods[0]:"?",i=`${e.definition.symbol}\0${t.file}\0${t.line}\0${t.reason}`;return{observationId:`frontier:${fd("sha256").update(i).digest("hex").slice(0,16)}`,kind:"call-resolution",action:"http.request",strength:"candidate",source:{file:t.file,startLine:t.line,endLine:t.line},ownerShortName:null,address:`method=${r??"?"} path=?`,reason:`Compiler identity found a reference to ${e.definition.leaf}, but exact call recovery stopped with ${t.reason} (${t.candidates} syntax candidate(s)); HTTP value propagation did not cross this site.`,missingKeyParts:n.length>0?n:["call"],sourceScope:en(t.file)}}function Sd(e,t,n){let r=mr(t);if(r.some(d=>d.type==="spread_element"))return null;let i=e.pathParameterIndexes.flatMap(d=>{let p=U(n,r[d]);return p&&p.evidence!=="expression"&&Ed(p.value)?[{index:d,value:p}]:[]}),a=e.methodParameterIndexes.flatMap(d=>{let p=U(n,r[d]),m=p?.value.toUpperCase();return p&&m&&p.precision==="literal"&&p.evidence!=="expression"&&nt.has(m)?[{index:d,value:{...p,value:m}}]:[]}),o=rt([...e.constantMethods,...a.map(d=>d.value.value)]);if(i.length!==1||o.length!==1)return null;let s=i[0].value,c=a.find(d=>d.value.value===o[0])?.value,l=[{name:"method",value:o[0],evidence:c?"constant":"literal",term:c?.term??{kind:"literal",value:o[0]},precision:"literal",derivation:c?.derivation},{name:"path",value:s.value,evidence:"constant",term:s.term,precision:s.precision,derivation:s.derivation}],u=rn(n,t,"builtin.http-summary","http.request",l,"derived","compiler-resolved-http-summary");return u.derivation={kind:"mechanically-derived",rule:"compiler-resolved-http-summary",ruleVersion:"1",inputFactIds:e.proofObservationIds,sourceSpans:[...e.proofSpans,u.source]},u}function vd(e,t){let n={pathParameterIndexes:[],methodParameterIndexes:[],constantMethods:[]};if(t.startColumn===void 0||t.endColumn===void 0)return n;let r=Q(e.root,t.startLine,t.endLine,Y,t);if(r?.type!=="call_expression")return n;let i=F(e.file,e.root),a=r.childForFieldName("function"),o=a&&i.importedValue(a),s=Qt(e,r),c=o?.module==="axios"&&o.member?o.member.toUpperCase():null;if(!s&&(!c||!nt.has(c)))return n;let l=mr(r);if(l.some(f=>f.type==="spread_element"))return n;let u=l[0]?i.directParameterPosition(l[0]):null,d=s?Me(e,l[1],"method"):null,p=d?.kind==="value"?i.directParameterPosition(d.node):null,m=s?Zt(l[1],e):c;return{pathParameterIndexes:u===null?[]:[u],methodParameterIndexes:p===null?[]:[p],constantMethods:m&&nt.has(m)?[m]:[]}}function xd(e,t,n){let r=mr(t);return r.some(i=>i.type==="spread_element")?[]:e.methodParameterIndexes.flatMap(i=>{let a=U(n,r[i]);return a&&a.precision==="literal"&&["constant","literal"].includes(a.evidence)&&nt.has(a.value.toUpperCase())?[a.value.toUpperCase()]:[]})}function Rd(e){return e.map(t=>[encodeURIComponent(t.symbol),t.pathParameterIndexes.join(","),t.methodParameterIndexes.join(","),t.constantMethods.join(",")].join(" ")).join(`
3
+ `)}function Pd(e){if(!e)return[];let t=[];for(let n of e.split(`
4
+ `)){let r=n.split(" ");if(r.length!==4)return null;let i=zo(r[1]),a=zo(r[2]),o=r[3]?r[3].split(","):[];if(i===null||a===null||o.some(s=>!nt.has(s)))return null;t.push({symbol:decodeURIComponent(r[0]),pathParameterIndexes:i,methodParameterIndexes:a,constantMethods:o})}return t}function zo(e){if(!e)return[];let t=e.split(",").map(Number);return t.every(n=>Number.isSafeInteger(n)&&n>=0)?t:null}function Id(e,t,n){let r=et(e,n);return{pathParameterIndexes:tt(r,t.pathParameterIndexes),methodParameterIndexes:tt(r,t.methodParameterIndexes)}}function Ko(e,t){if(t.pathParameterIndexes.length===0)return!1;let n=JSON.stringify([t.definition.symbol,t.pathParameterIndexes,t.methodParameterIndexes,t.constantMethods]),r=e.get(n);return r&&r.depth<=t.depth?!1:(e.set(n,t),!0)}function mr(e){return(e.childForFieldName("arguments")??e.namedChildren.find(n=>n.type==="arguments"))?.namedChildren??[]}function Ed(e){return e.startsWith("/")||/^https?:\/\//iu.test(e)}function rt(e){return[...new Set(e)].sort()}var Cd=32;function Xo(e){let t=pr(e.observations),n=Td(t,e.previous),r=(c,l)=>Ze({db:e.db,scope:e.scope,seeds:Qe(c),compilerFactsUnchanged:e.compilerFactsUnchanged,previous:l?.record,compute:u=>Wo(u,c,e.profileSpan)}),i=n.map(c=>({...c,phase:r(c.seeds,c.previous)}));if(!wd(i.map(c=>c.phase.result))){let c=r(t);return{result:c.result,partitions:c.record?[{observationIds:t.map(l=>l.id),record:c.record}]:void 0,reused:!1,filesVisited:c.result.filesInspected}}let a=i.map(c=>c.phase.result),o=new Set(a.flatMap(c=>c.inspectedFiles));return{result:{observations:a.flatMap(c=>c.observations),frontiers:je(a.flatMap(c=>c.frontiers)),summaries:a.reduce((c,l)=>c+l.summaries,0),filesInspected:o.size,errors:a.flatMap(c=>c.errors),summarySymbols:a.flatMap(c=>c.summarySymbols).sort(),inspectedFiles:[...o].sort()},partitions:i.every(c=>c.phase.record)?i.map(c=>({observationIds:c.seeds.map(l=>l.id),record:c.phase.record})):void 0,reused:i.every(c=>c.phase.reused),filesVisited:new Set(i.filter(c=>!c.phase.reused).flatMap(c=>c.phase.result.inspectedFiles)).size}}function Td(e,t){if(!e.length)return[{seeds:e,previous:t?.find(i=>i.observationIds?.length===0)}];if(!t?.length||t.length>=Cd)return[{seeds:e,previous:void 0}];let n=new Map(e.map(i=>[i.id,i])),r=[];for(let i of t){if(!Array.isArray(i?.observationIds))return[{seeds:e,previous:void 0}];let a=new Set(i.observationIds),o=e.filter(s=>n.has(s.id)&&a.has(s.id));for(let s of o)n.delete(s.id);o.length&&r.push({seeds:o,previous:i})}return(n.size||!r.length)&&r.push({seeds:[...n.values()]}),r}function wd(e){if(e.length===1)return!0;let t=new Set;for(let n of e){if(n.errors.length||!Array.isArray(n.summarySymbols)||!Array.isArray(n.inspectedFiles))return!1;for(let r of n.summarySymbols){if(t.has(r))return!1;t.add(r)}}return!0}import{createHash as Fd}from"crypto";function Qo(e){let t=Jo(e.filter(r=>r.action==="database.read"&&r.evidence.startsWith("persistence-skip-locked-claim"))),n=Jo(e.filter(r=>r.action==="database.write"&&r.evidence.startsWith("persistence-insert")));return e.flatMap(r=>r.action==="database.write"&&r.evidence.startsWith("persistence-insert")?fr(r).flatMap(i=>{let a=t.get(i)?.[0];return a?[Yo(r,a,i,"queue.send")]:[]}):r.action==="database.read"&&r.evidence.startsWith("persistence-skip-locked-claim")?fr(r).flatMap(i=>{let a=n.get(i)?.[0];return a?[Yo(r,a,i,"queue.consume")]:[]}):[])}function Jo(e){let t=new Map;for(let n of e)for(let r of fr(n)){let i=t.get(r);i?i.push(n):t.set(r,[n])}for(let n of t.values())n.sort((r,i)=>r.id.localeCompare(i.id));return t}function fr(e){return e.keyParts.filter(t=>t.name==="resource").map(t=>t.value)}function Yo(e,t,n,r){let i=`database:${n}`,a=r==="queue.send"?"database-queue-insert":"database-queue-skip-locked-claim",o=[e.id,r,i,a].join("\0");return{...e,id:`boundary:${Fd("sha256").update(o).digest("hex").slice(0,16)}`,extractor:"builtin.database-queue",action:r,keyParts:[{name:"address",value:i,evidence:"identifier",term:{kind:"symbol",symbol:n},derivation:{kind:"mechanically-derived",rule:"database-work-queue.resource",ruleVersion:"1",inputFactIds:[e.id,t.id],sourceSpans:[e.source,t.source]}}],evidence:a,strength:"candidate",protocol:"queue",role:r==="queue.send"?"producer":"consumer",derivation:{kind:"mechanically-derived",rule:"database-work-queue.insert-skip-locked",ruleVersion:"1",inputFactIds:[e.id,t.id],sourceSpans:[e.source,t.source]},valuePrecision:"symbolic",resolution:"unresolved"}}var ce="runtime-boundaries-v32",Nd=_d(import.meta.url),N=Nd("typescript"),Od=new Set([N.SyntaxKind.WhitespaceTrivia,N.SyntaxKind.NewLineTrivia,N.SyntaxKind.SingleLineCommentTrivia,N.SyntaxKind.MultiLineCommentTrivia]),Dd=new Set([N.SyntaxKind.NoSubstitutionTemplateLiteral,N.SyntaxKind.TemplateHead,N.SyntaxKind.TemplateMiddle,N.SyntaxKind.TemplateTail]),Be=[{id:"http.method-path",unresolvedIdentity:"HTTP deployment and server instance identity are not established by a matching method and path.",protocol:"http",producerActions:["http.request"],consumerActions:["http.handle"],keyNames:["method","path"],traversable:!0},{id:"registry.identity-key",protocol:"registry",producerActions:["registry.dispatch"],consumerActions:["registry.handle"],keyNames:["registry","key"],traversable:!0},{id:"registry.capability-key",unresolvedIdentity:"A named capability in instruction text does not prove registration in the active tool registry or execution of that capability.",protocol:"registry",producerActions:["registry.reference"],consumerActions:["registry.handle"],keyNames:["key"],traversable:!0,requireUniqueConsumer:!0},{id:"queue.address",unresolvedIdentity:"Queue broker and namespace identity are not established by a matching address.",protocol:"queue",producerActions:["queue.send"],consumerActions:["queue.consume"],keyNames:["address"],traversable:!0},{id:"carrier.discriminator",protocol:"carrier",producerActions:["carrier.publish"],consumerActions:["carrier.consume"],keyNames:["carrier","field","value"],traversable:!0},{id:"resource.identity",protocol:"database",producerActions:["database.write"],consumerActions:["database.read"],keyNames:["resource"],traversable:!1},{id:"framework.effect-httpapi-operation",unresolvedIdentity:"Effect API instance identity and builder receiver flow are not established by matching group and operation names.",protocol:"framework",producerActions:[],consumerActions:["framework.handle"],declarationActions:["framework.declare"],keyNames:["adapter","group","operation"],traversable:!0,linkFrom:"declaration",requireUniquePair:!0}],kd=64;async function gr(e,t={}){let{files:n,previousFileCoverage:r,incrementallyReusable:i,retainedFileCoverage:a,retainedObservations:o,filesToExtract:s}=Ld(e,t),c=[],l=r?.reduce((A,Nn)=>A+Nn.observationIds.length,0)??0,u=performance.now(),d=await jd(e,s,t.profileSpan);se(c,"direct-extraction",u,s.length,d.observations.length,{filesVisited:s.length,filesReused:a.length,factsReused:o.length,factsInvalidated:Math.max(0,l-o.length)});let p=[...a,...d.fileCoverage].sort((A,Nn)=>A.file.localeCompare(Nn.file)),m=Kd(p),f=p.flatMap(A=>A.extractionErrors),x=it([...o,...d.observations]),C=it([...x,...Qo(x)]),g=to(e,n),b=!t.forceDerivedRebuild&&t.previousGraph?.extractorVersion===ce?t.previousGraph.phaseRecords:void 0,y=t.compilerFactsUnchanged===!0,R={};u=performance.now();let S=Xo({db:e,scope:g,observations:C,compilerFactsUnchanged:y,previous:b?.httpPartitions,profileSpan:t.profileSpan}),v=S.result;R.httpPartitions=S.partitions,se(c,"http-summary",u,C.length,v.observations.length,{filesVisited:S.filesVisited,...S.reused?{filesReused:v.filesInspected,factsReused:v.observations.length+v.frontiers.length,factsInvalidated:0}:{}}),m.set("builtin.wrapper",{id:"builtin.wrapper",applicableFiles:v.filesInspected,observations:v.observations.length,errors:v.errors.length}),f.push(...v.errors);let h=it([...C,...v.observations]);await Zo(S.reused),u=performance.now();let E=Go(e,h);se(c,"http-mount",u,h.length,E.observations.length,{filesVisited:E.filesInspected});let T=it([...h,...E.observations]);u=performance.now();let z=p.flatMap(A=>A.bodySummaries??[]),_=Ze({db:e,scope:g,seeds:Qe([],z),compilerFactsUnchanged:y,previous:b?.body,compute:A=>No(A,z)});R.body=_.record,se(c,"body-summary",u,z.length,_.result.summaries.length,{filesVisited:_.reused?0:_.result.filesInspected,..._.reused?{factsReused:_.result.summaries.length,factsInvalidated:0}:{}}),await Zo(_.reused),u=performance.now();let ee=Ze({db:e,scope:g,seeds:Qe(T,_.result),compilerFactsUnchanged:y,previous:b?.carrier,compute:A=>Oo(A,T,_.result)}),J=ee.result;R.carrier=ee.record,se(c,"carrier",u,T.length,J.observations.length,{filesVisited:ee.reused?0:J.filesInspected,...ee.reused?{filesReused:J.filesInspected,factsReused:J.observations.length,factsInvalidated:0}:{}}),m.set("builtin.carrier",{id:"builtin.carrier",applicableFiles:J.bodySummaries,observations:J.observations.length,errors:J.errors.length}),f.push(...J.errors);let pe=it([...T,...J.observations]);u=performance.now();let Fe=Jd(pe);se(c,"relations",u,pe.length,Fe.length),u=performance.now();let Xr=np(pe,Fe);se(c,"links",u,Fe.length,Xr.length),rp(pe,Fe),u=performance.now();let Jr=je([...ip(pe,Fe),...v.frontiers,...E.frontiers]);return se(c,"frontiers",u,pe.length,Jr.length),{schemaVersion:2,extractorVersion:ce,observations:pe,relationGroups:Fe,links:Xr,frontiers:Jr,coverage:{filesScanned:n.length,filesWithAst:p.filter(A=>A.hasAst).length,filesWithoutAst:p.filter(A=>!A.hasAst).length,...i?{filesReused:a.length}:{},extractors:[...m.values()],extractionErrors:f,phases:c},fileCoverage:p,phaseRecords:R}}async function Zo(e){e||(Gn(),await ns())}function Ld(e,t){let n=_t(e),r=new Set(n),i=new Set((t.affectedFiles??[]).map(Xd)),a=t.previousGraph?.fileCoverage;Ad(e,a,i);let o=i.size>0&&t.previousGraph?.extractorVersion===ce&&a!==void 0&&a.length===t.previousGraph.coverage.filesScanned,s=o?a.filter(d=>r.has(d.file)&&!i.has(d.file)):[],c=new Set(s.flatMap(d=>d.observationIds)),l=o?t.previousGraph.observations.filter(d=>c.has(d.id)&&r.has(d.source.file)):[],u=o?n.filter(d=>i.has(d)):n;return{files:n,affectedFiles:i,previousFileCoverage:a,incrementallyReusable:o,retainedFileCoverage:s,retainedObservations:l,filesToExtract:u}}function Ad(e,t,n){if(n.size!==0)for(let r of t??[]){if(!r.dependsOnReferenceSet)continue;let i=Ke(e,r.file);rs(e,r.file,he(e,r.file,i))||n.add(r.file)}}function se(e,t,n,r,i,a={}){e.push({id:t,durationMs:Math.max(0,performance.now()-n),inputFacts:r,outputFacts:i,...a})}var Md=256;async function jd(e,t,n){let r=[],i=[],a=n??((d,p)=>p()),o=[],s=[],c=new Map,l=d=>{let p=c.get(d);if(p!==void 0)return p;let m=he(e,d,Ke(e,d));return c.set(d,m),m},u=0;for(let d of t){u+=1,u>=Md&&(u=0,Gn(),await ns());let p=a("runtime-boundaries.file.read",()=>Ke(e,d)),m=he(e,d,p);c.set(d,m);let f=a("runtime-boundaries.file.direct-product",()=>rs(e,d,m,l));if(f){r.push(...f.observations),i.push(f.coverage);continue}let x=a("runtime-boundaries.file.supports",()=>ar.filter(h=>h.supports(p))),C=/\bJSON\.stringify\s*\(/u.test(p)&&/\bbody\s*:/u.test(p),g=a("runtime-boundaries.file.hashes",()=>{let h=es.read(e,d,m);if(h)return h;let E=qd(d,p);return o.push({relativePath:d,contentHash:m,value:E}),E}),b=new Set,y=new Map,R=!0,S=[],v=It(h=>b.add(h),()=>{let h=x.length>0||C?G(e,d,p,n):null,E={file:d,hasAst:h!==null||Wd(d,p),syntaxHash:g.syntaxHash,shapeHash:g.shapeHash,bodySummaries:h&&C?ko(h):[],observationIds:[],extractors:[],extractionErrors:[]};if(h)for(let T of x){let z={id:T.id,applicableFiles:1,observations:0,errors:0};try{let _=zd(n,`runtime-boundaries.extractor.${T.id}`,d,()=>T.extract(h));z.observations=_.length,S.push(..._),E.observationIds.push(..._.map(ee=>ee.id))}catch(_){Pt(d),z.errors=1,E.extractionErrors.push(`${T.id} failed for ${d}: ${_ instanceof Error?_.message:String(_)}`)}E.extractors.push(z)}return E},(h,E)=>y.set(h,E),{source(){},unavailable(){R=!1}});y.size>0&&(v.dependsOnReferenceSet=!0),r.push(...S),i.push(v),R&&(b.delete(d),s.push({relativePath:d,contentHash:m,value:{extractorVersion:ce,deps:[...b].sort().map(h=>({path:h,contentHash:l(h)})),symbolReferences:[...y].map(([h,E])=>({symbol:h,files:[...E]})),observations:S,coverage:v}}))}return o.length>0&&es.writeBatch(e,o),s.length>0&&is.writeBatch(e,s),{observations:r,fileCoverage:i}}var es=Se({kind:"runtime-boundary-source-hashes",invalidation:ve("runtime-boundary-source-hashes"),serialize:e=>JSON.stringify(e),deserialize:e=>{try{let t=JSON.parse(e);return typeof t.syntaxHash=="string"&&typeof t.shapeHash=="string"?{syntaxHash:t.syntaxHash,shapeHash:t.shapeHash}:null}catch{return null}}});function rs(e,t,n,r=i=>he(e,i,Ke(e,i))){let i=is.read(e,t,n);return!i||i.extractorVersion!==ce||i.coverage.dependsOnReferenceSet&&!i.symbolReferences?.length||!Bd(e,i.symbolReferences)?null:i.deps.every(a=>r(a.path)===a.contentHash)?i:null}function Bd(e,t){return t===void 0?!0:Array.isArray(t)?t.every(n=>n&&typeof n.symbol=="string"&&Array.isArray(n.files)&&JSON.stringify(ma(e,n.symbol))===JSON.stringify(n.files)):!1}var is=Se({kind:"runtime-boundary-direct-extraction",invalidation:ve("runtime-boundary-direct-extraction"),serialize:e=>JSON.stringify(e),deserialize:e=>{try{let t=JSON.parse(e);return typeof t.extractorVersion!="string"||!Array.isArray(t.deps)||!Array.isArray(t.observations)||typeof t.coverage!="object"||t.coverage===null||!t.deps.every(n=>typeof n=="object"&&n!==null&&typeof n.path=="string"&&typeof n.contentHash=="string")?null:t}catch{return null}}});function $d(e){let t=[0];for(let n=0;n<e.length;n+=1)e.charCodeAt(n)===10&&t.push(n+1);return t}function Ud(e,t,n){return t===N.SyntaxKind.CloseBraceToken&&n.length>0&&n.at(-1)===0&&(t=e.reScanTemplateToken(!1)),t}function Gd(e,t,n){for(;e[t+1]!==void 0&&e[t+1]<=n;)t+=1;return t}function ts(e,t,n,r,i){e.update(`${t}\0${i?n:""}\0${r}\0`)}function Hd(e,t){e===N.SyntaxKind.TemplateHead?t.push(0):e===N.SyntaxKind.TemplateTail?t.pop():e===N.SyntaxKind.OpenBraceToken&&t.length>0?t[t.length-1]+=1:e===N.SyntaxKind.CloseBraceToken&&t.length>0&&t.at(-1)>0&&(t[t.length-1]-=1)}function qd(e,t){if(!/\.(?:[cm]?[jt]sx?)$/iu.test(e)){let l=at("sha256").update(t).digest("hex");return{syntaxHash:l,shapeHash:l}}let n=/\.[jt]sx$/iu.test(e)?N.LanguageVariant.JSX:N.LanguageVariant.Standard,r=N.createScanner(N.ScriptTarget.Latest,!1,n,t),i=at("sha256"),a=at("sha256"),o=[],s=$d(t),c=0;for(let l=r.scan();l!==N.SyntaxKind.EndOfFileToken;l=r.scan()){if(l=Ud(r,l,o),Od.has(l))continue;let u=r.getTokenText();c=Gd(s,c,r.getTokenPos()),ts(i,l,u,c,!0),ts(a,l,u,c,!Dd.has(l)&&!Vd(l,u)),Hd(l,o)}return{syntaxHash:i.digest("hex"),shapeHash:a.digest("hex")}}function Vd(e,t){if(e!==N.SyntaxKind.StringLiteral||t.length<2)return!1;let n=t.slice(1,-1);return n.startsWith("/")||n.includes("://")}function zd(e,t,n,r){return e?e(t,r,{file:n}):r()}function Wd(e,t){return t?Tt(e)?/<script\b/iu.test(t):K(e)!==null:!1}function Kd(e){let t=new Map(ar.map(n=>[n.id,{id:n.id,applicableFiles:0,observations:0,errors:0}]));for(let n of e)for(let r of n.extractors){let i=t.get(r.id);i&&(i.applicableFiles+=r.applicableFiles,i.observations+=r.observations,i.errors+=r.errors)}return t}function Xd(e){return e.replaceAll("\\","/").replace(/^\.\//u,"")}function Jd(e){let t=new Map;for(let n of Be){let r=new Set([...n.producerActions,...n.consumerActions,...n.declarationActions??[]]);for(let i of e)Yd(t,n,r,i)}return[...t.values()].map(Qd).sort(cp)}function Yd(e,t,n,r){if(!n.has(r.action)||r.strength==="candidate")return;let i=op(r,t.keyNames);if(!i)return;let a=i.map(u=>`${u.name}=${os(u.name,u.value)}`).join("\0"),o=r.sourceScope==="production"?"production":r.sourceScope,s=`${t.id}\0${o}\0${a}`,c=`boundary-group:${at("sha256").update(s).digest("hex").slice(0,16)}`,l=e.get(c)??{id:c,protocol:t.protocol,joinRule:t.id,normalizedKey:a,keyParts:i,producerIds:[],consumerIds:[],declarationIds:[],derivation:{kind:"mechanically-derived",rule:t.id,ruleVersion:"2",inputFactIds:[],sourceSpans:[]}};t.producerActions.includes(r.action)&&l.producerIds.push(r.id),t.consumerActions.includes(r.action)&&l.consumerIds.push(r.id),t.declarationActions?.includes(r.action)&&l.declarationIds.push(r.id),l.derivation.inputFactIds.push(r.id),l.derivation.sourceSpans.push(r.source),e.set(c,l)}function Qd(e){return{...e,producerIds:ln(e.producerIds),consumerIds:ln(e.consumerIds),declarationIds:ln(e.declarationIds),derivation:{...e.derivation,inputFactIds:ln(e.derivation.inputFactIds),sourceSpans:[...new Map(e.derivation.sourceSpans.map(t=>[`${t.file}:${t.startLine}:${t.startColumn}:${t.endLine}:${t.endColumn}`,t])).values()]}}}function Zd(e,t,n){return n.length===0||e.consumerIds.length===0||t.requireUniquePair&&(n.length!==1||e.consumerIds.length!==1)||t.requireUniqueConsumer&&e.consumerIds.length!==1?!1:n.length*e.consumerIds.length<=kd}function ep(e){let t=Be.find(r=>r.id===e.joinRule);if(!t?.traversable)return[];let n=t.linkFrom==="declaration"?e.declarationIds:e.producerIds;return Zd(e,t,n)?n:[]}function tp(e,t,n,r){let i=r.get(t),a=r.get(n);if(!i||!a||sp(i,a))return null;let o=Be.find(l=>l.id===e.joinRule)?.unresolvedIdentity?"candidate":i.strength==="derived"||a.strength==="derived"?"derived":"exact",s=`${e.joinRule}\0${t}\0${n}`;return{id:`boundary-link:${at("sha256").update(s).digest("hex").slice(0,16)}`,from:t,to:n,joinRule:e.joinRule,matchedKeyParts:e.keyParts,strength:o,derivation:{kind:"mechanically-derived",rule:e.joinRule,ruleVersion:"2",inputFactIds:[t,n],sourceSpans:[i.source,a.source]}}}function np(e,t){let n=new Map(e.map(i=>[i.id,i])),r=new Map;for(let i of t){let a=ep(i);for(let o of a)for(let s of i.consumerIds){let c=tp(i,o,s,n);c&&r.set(c.id,c)}}return[...r.values()].sort(lp)}function rp(e,t){let n=new Set(t.filter(as).flatMap(ot)),r=new Set(t.filter(ap).flatMap(ot));for(let i of e)i.resolution=n.has(i.id)?"locally-linked":r.has(i.id)?"ambiguous":"unresolved"}function ip(e,t){let n=new Set(e.filter(a=>a.strength!=="candidate").map(a=>`${a.action}\0${a.source.file}\0${a.source.startLine}:${a.source.startColumn}\0${a.source.endLine}:${a.source.endColumn}`)),r=new Set(t.flatMap(ot)),i=new Set(t.filter(as).flatMap(ot));return e.filter(a=>a.sourceScope==="production").filter(a=>a.strength!=="candidate"||!n.has(`${a.action}\0${a.source.file}\0${a.source.startLine}:${a.source.startColumn}\0${a.source.endLine}:${a.source.endColumn}`)).filter(a=>!i.has(a.id)).map(a=>{let o=a.keyParts.filter(l=>l.evidence==="expression"||l.value.length===0).map(l=>l.name),c=t.filter(l=>ot(l).includes(a.id)).map(l=>Be.find(u=>u.id===l.joinRule)?.unresolvedIdentity).find(Boolean)??(o.length>0?`${a.extractor} observed ${a.action}, but ${o.join(", ")} remained symbolic or unknown.`:a.resolution==="ambiguous"?`${a.extractor} established the address for ${a.action}, but more than one indexed peer has the same runtime key.`:r.has(a.id)?`${a.extractor} established the address for ${a.action}, but the indexed production scope contains no counterpart role in that relation group.`:`${a.extractor} observed ${a.action}, but no supported factorization rule could establish its addressed relation.`);return{observationId:a.id,reason:c,missingKeyParts:o,sourceScope:a.sourceScope}}).sort((a,o)=>a.observationId.localeCompare(o.observationId))}function ot(e){return[...e.producerIds,...e.consumerIds,...e.declarationIds]}function as(e){let t=Be.find(r=>r.id===e.joinRule);if(!t||t.unresolvedIdentity||t.requireUniqueConsumer&&e.consumerIds.length!==1)return!1;let n=t.linkFrom==="declaration"?e.declarationIds:e.producerIds;return n.length===0||e.consumerIds.length===0?!1:!t.requireUniquePair||n.length===1&&e.consumerIds.length===1}function ap(e){let t=Be.find(r=>r.id===e.joinRule);if(!t?.requireUniquePair&&!t?.requireUniqueConsumer)return!1;let n=t.linkFrom==="declaration"?e.declarationIds:e.producerIds;return n.length>0&&e.consumerIds.length>0&&(e.consumerIds.length!==1||t.requireUniquePair===!0&&n.length!==1)}function op(e,t){let n=[];for(let r of t){let i=e.keyParts.find(o=>o.name===r);if(!i||i.evidence==="expression"||i.value.length===0)return null;let a=r==="registry"&&i.term?.kind==="symbol"?i.term.symbol:i.value;n.push({...i,value:os(r,a)})}return n}function os(e,t){return e==="method"?t.toUpperCase():t}function sp(e,t){return e.id===t.id||e.source.file===t.source.file&&e.source.startLine===t.source.startLine&&e.source.startColumn!==void 0&&e.source.startColumn===t.source.startColumn&&e.source.endLine===t.source.endLine&&e.source.endColumn===t.source.endColumn}function it(e){return[...new Map(e.map(t=>[t.id,t])).values()].sort((t,n)=>t.source.file.localeCompare(n.source.file)||t.source.startLine-n.source.startLine||t.action.localeCompare(n.action))}function ln(e){return[...new Set(e)].sort()}function cp(e,t){return e.joinRule.localeCompare(t.joinRule)||e.normalizedKey.localeCompare(t.normalizedKey)}function lp(e,t){return e.joinRule.localeCompare(t.joinRule)||e.from.localeCompare(t.from)||e.to.localeCompare(t.to)}import up from"better-sqlite3";var un="scip_query_runtime_boundaries",st="scip_query_runtime_observations",dn="scip_query_runtime_relation_groups",pn="scip_query_runtime_relation_participants";function hr(e,t){let n=new up(e);try{n.exec(`
5
+ CREATE TABLE IF NOT EXISTS ${un} (
6
+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
7
+ schema_version INTEGER NOT NULL,
8
+ extractor_version TEXT NOT NULL,
9
+ payload TEXT NOT NULL
10
+ )
11
+ `),dp(n),n.transaction(()=>{n.prepare(`INSERT OR REPLACE INTO ${un} (singleton, schema_version, extractor_version, payload) VALUES (1, ?, ?, ?)`).run(t.schemaVersion,t.extractorVersion,JSON.stringify(t)),n.prepare(`DELETE FROM ${st}`).run(),n.prepare(`DELETE FROM ${pn}`).run(),n.prepare(`DELETE FROM ${dn}`).run();let r=n.prepare(`INSERT INTO ${st}
12
+ (id, protocol, action, role, strength, source_scope, resolution, file, start_line, end_line, owner_symbol, payload)
13
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);for(let o of t.observations)r.run(o.id,o.protocol,o.action,o.role,o.strength,o.sourceScope,o.resolution,o.source.file,o.source.startLine,o.source.endLine,o.owner.symbol,JSON.stringify(o));let i=n.prepare(`INSERT INTO ${dn} (id, protocol, join_rule, normalized_key, payload) VALUES (?, ?, ?, ?, ?)`),a=n.prepare(`INSERT INTO ${pn} (group_id, observation_id, participant_role) VALUES (?, ?, ?)`);for(let o of t.relationGroups){i.run(o.id,o.protocol,o.joinRule,o.normalizedKey,JSON.stringify(o));for(let s of o.producerIds)a.run(o.id,s,"producer");for(let s of o.consumerIds)a.run(o.id,s,"consumer");for(let s of o.declarationIds)a.run(o.id,s,"declaration")}})()}finally{n.close()}}function dp(e){e.exec(`
14
+ CREATE TABLE IF NOT EXISTS ${st} (
15
+ id TEXT PRIMARY KEY,
16
+ protocol TEXT NOT NULL,
17
+ action TEXT NOT NULL,
18
+ role TEXT NOT NULL,
19
+ strength TEXT NOT NULL,
20
+ source_scope TEXT NOT NULL,
21
+ resolution TEXT NOT NULL,
22
+ file TEXT NOT NULL,
23
+ start_line INTEGER NOT NULL,
24
+ end_line INTEGER NOT NULL,
25
+ owner_symbol TEXT,
26
+ payload TEXT NOT NULL
27
+ );
28
+ CREATE INDEX IF NOT EXISTS idx_runtime_observations_protocol_action_scope
29
+ ON ${st}(protocol, action, source_scope);
30
+ CREATE INDEX IF NOT EXISTS idx_runtime_observations_file_line
31
+ ON ${st}(file, start_line);
32
+
33
+ CREATE TABLE IF NOT EXISTS ${dn} (
34
+ id TEXT PRIMARY KEY,
35
+ protocol TEXT NOT NULL,
36
+ join_rule TEXT NOT NULL,
37
+ normalized_key TEXT NOT NULL,
38
+ payload TEXT NOT NULL
39
+ );
40
+ CREATE INDEX IF NOT EXISTS idx_runtime_groups_protocol_key
41
+ ON ${dn}(protocol, join_rule, normalized_key);
42
+
43
+ CREATE TABLE IF NOT EXISTS ${pn} (
44
+ group_id TEXT NOT NULL,
45
+ observation_id TEXT NOT NULL,
46
+ participant_role TEXT NOT NULL,
47
+ PRIMARY KEY (group_id, observation_id, participant_role)
48
+ );
49
+ CREATE INDEX IF NOT EXISTS idx_runtime_participants_observation
50
+ ON ${pn}(observation_id, participant_role);
51
+ `)}function yr(e){if(!e.get("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",un))return null;let n=e.get(`SELECT schema_version, payload FROM ${un} WHERE singleton = 1`);if(!n||n.schema_version!==2)return null;try{let r=JSON.parse(n.payload);return r.schemaVersion===2&&Array.isArray(r.observations)&&Array.isArray(r.relationGroups)&&Array.isArray(r.links)?r:null}catch{return null}}function ss(e={}){return{id:"runtime-boundaries",facts:["runtime-boundary-observation","runtime-boundary-link"],run:async({projectRoot:t,dbPath:n,onStatus:r})=>{let i=new $({projectRoot:t,dbPath:n,indexPath:e.indexPath??mp(pp(n),"index.scip"),...e.evidenceDbPath?{evidenceDbPath:e.evidenceDbPath}:{}}),a,o=!1,s=!1;try{let l=e.reuseExisting||e.affectedFiles?yr(i):null;e.reuseExisting&&l?.extractorVersion===ce?(a=l,o=!0):(a=await gp(i,l,e),s=(a.coverage.filesReused??0)>0)}finally{i.close()}o||hr(n,a);let c={reused:o,incrementallyUpdated:s,observations:a.observations.length,links:a.links.length,frontiers:a.frontiers.length,filesScanned:a.coverage.filesScanned,errors:a.coverage.extractionErrors.length,phases:a.coverage.phases};return fp(c,a,r),c}}}function fp(e,t,n){n?.(e.reused?`Reused ${e.observations} cached runtime-boundary observation(s) and ${e.links} link(s).`:e.incrementallyUpdated?`Incrementally refreshed runtime-boundary observations (${e.filesScanned-(t.coverage.filesReused??0)} file(s) extracted, ${t.coverage.filesReused??0} reused) and rebuilt ${e.links} link(s).`:`Extracted ${e.observations} runtime-boundary observation(s), ${e.links} link(s), and ${e.frontiers} unresolved frontier(s).`),!e.reused&&t.coverage.phases&&n?.(`Runtime-boundary phases: ${t.coverage.phases.map(r=>`${r.id} ${r.durationMs.toFixed(0)}ms`).join(", ")}.`)}function gp(e,t,n){return gr(e,{...t?{previousGraph:t}:{},...n.affectedFiles?{affectedFiles:n.affectedFiles}:{},...n.forceDerivedRebuild?{forceDerivedRebuild:!0}:{},...n.compilerFactsUnchanged?{compilerFactsUnchanged:!0}:{},profileSpan:P})}var hp={config:"configuration-changed",ambient:"ambient-declaration-changed",other:"unclassified-input"};function Ie(e,t={}){let n=new Set;for(let r of e.uncertainty)n.add(r);e.projectIdentityChanged&&n.add("project-identity-changed"),t.maxChanges!==void 0&&e.changes.length>t.maxChanges&&n.add("change-limit-exceeded");for(let r of e.changes){r.kind==="added"&&n.add("file-added"),r.kind==="deleted"&&t.deletedFiles!=="closure"&&n.add("file-deleted");let i=hp[r.inputKind];i&&n.add(i)}return{fullProject:n.size>0,reasons:[...n].sort()}}function fn(e,t,n){let r=e.changes.map(s=>s.path).sort();if(r.length===0&&!e.projectIdentityChanged&&e.uncertainty.length===0)return{mode:"none",changedFiles:r,affectedFiles:[],reasons:[]};let i=new Set(n),a=Ie(e),o=new Set(a.reasons);return r.some(s=>!i.has(s))&&o.add("changed-file-outside-project"),t===null?(o.add("dependency-graph-unavailable"),mn(r,i,o)):o.size>0?mn(r,i,o):{mode:"closure",changedFiles:r,affectedFiles:yp(r,t,i),reasons:[]}}function mn(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function yp(e,t,n){let r=bp(t,n),i=new Set(e),a=[...e];for(let o=0;o<a.length;o+=1){let s=a[o];if(s!==void 0)for(let c of r.get(s)??[])i.has(c)||(i.add(c),a.push(c))}return[...i].sort()}function bp(e,t){let n=new Map;for(let[r,i]of e)if(t.has(r))for(let a of i){if(!t.has(a))continue;let o=n.get(a)??new Set;o.add(r),n.set(a,o)}return n}import{createHash as Sp}from"crypto";import{existsSync as vp}from"fs";import{dirname as xp,join as cs}from"path";var Rp="<global-symbols>";function Pp(e){let t=[];for(let n of e.all(`
2
52
  SELECT relative_path, language, position_encoding, text
3
53
  FROM documents
4
54
  `))t.push({relativePath:n.relative_path,kind:"document",values:[n.language,n.position_encoding,n.text]});for(let n of e.all(`
@@ -25,7 +75,7 @@ import{a as Ce,b as xn,c as En,d as In,e as vn,f as _n,g as Tn,h as wn}from"./ch
25
75
  FROM defn_enclosing_ranges r
26
76
  JOIN documents d ON d.id = r.document_id
27
77
  JOIN global_symbols g ON g.id = r.symbol_id
28
- `))t.push({relativePath:n.relative_path,kind:"definition",values:Et(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
78
+ `))t.push({relativePath:n.relative_path,kind:"definition",values:br(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
29
79
  SELECT d.relative_path,
30
80
  c.chunk_index,
31
81
  m.role,
@@ -40,7 +90,7 @@ import{a as Ce,b as xn,c as En,d as In,e as vn,f as _n,g as Tn,h as wn}from"./ch
40
90
  JOIN chunks c ON c.id = m.chunk_id
41
91
  JOIN documents d ON d.id = c.document_id
42
92
  JOIN global_symbols g ON g.id = m.symbol_id
43
- `))t.push({relativePath:n.relative_path,kind:"mention",values:Et(n,[n.chunk_index,n.role])});for(let n of e.all(`
93
+ `))t.push({relativePath:n.relative_path,kind:"mention",values:br(n,[n.chunk_index,n.role])});for(let n of e.all(`
44
94
  SELECT g.symbol,
45
95
  g.display_name,
46
96
  g.kind,
@@ -54,10 +104,10 @@ import{a as Ce,b as xn,c as En,d as In,e as vn,f as _n,g as Tn,h as wn}from"./ch
54
104
  ) AND NOT EXISTS (
55
105
  SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
56
106
  )
57
- `))t.push({relativePath:so,kind:"global-symbol",values:Et(n)});return lo(t)}function lo(e){let t=new Map;for(let r of e){let a=JSON.stringify([r.kind,r.values]),i=t.get(r.relativePath)??[];i.push(a),t.set(r.relativePath,i)}let n=new Map;for(let[r,a]of[...t].sort(([i],[o])=>i.localeCompare(o))){let i=io("sha256");for(let o of a.sort())i.update(String(Buffer.byteLength(o))),i.update(":"),i.update(o),i.update(`
58
- `);n.set(r,i.digest("hex"))}return n}function uo(e,t){let n=[],r=[],a=[],i=[],o=new Set([...e.keys(),...t.keys()]);for(let s of[...o].sort()){let c=e.get(s),d=t.get(s);c===void 0?n.push(s):d===void 0?a.push(s):c!==d?r.push(s):i.push(s)}return{addedFiles:n,modifiedFiles:r,deletedFiles:a,changedFiles:[...n,...r,...a].sort(),unchangedFiles:i}}function It(e,t,n){let r=new Set(e.affectedFiles),a=new Set(t.changedFiles),i=e.mode==="full-project"?[]:t.changedFiles.filter(c=>!r.has(c)),o=e.affectedFiles.filter(c=>!a.has(c)).sort(),s=t.changedFiles.length-i.length;return{passed:i.length===0,recall:t.changedFiles.length===0?1:s/t.changedFiles.length,affectedRatio:n===0?0:e.affectedFiles.length/n,predictedFiles:[...e.affectedFiles].sort(),actualFiles:[...t.changedFiles],missingFiles:i,extraFiles:o}}function vt(e,t=yo){let n=t.wallNow===void 0&&t.monotonicNow===void 0,r=t.monotonicNow??t.now,a=t.wallNow??t.now,i=r(),o=(d,l)=>{let g=r();return Br(e.refreshResult,d,n?g:a(),Math.max(0,g-i),l)};if(!t.databaseExists(e.previousDbPath))return o("prior-index-unavailable");if(!t.databaseExists(e.candidateDbPath))return o("candidate-index-unavailable");if(e.refreshResult==="rebuilt"&&q(e.previousSnapshot,e.currentSnapshot).changes.length===0)return o("no-input-changes");let s=null,c=null;try{s=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),c=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let d=[...new Set([...t.indexedPaths(s),...t.indexedPaths(c)])].sort(),l=q(e.previousSnapshot,e.currentSnapshot),g=new Set(d),p=l.changes.length>0&&!ye(l).fullProject&&l.changes.every(j=>g.has(j.path)),f=Se(l,p?t.dependencyGraph(s):new Map,d),R=uo(t.factDigests(s),t.factDigests(c)),T=r();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(n?T:a()).toISOString(),durationMs:Math.max(0,T-i),manifest:l,plan:f,comparison:R,evaluation:It(f,R,d.length)}}catch(d){return o("oracle-error",d instanceof Error?d.message:String(d))}finally{Ar(s),Ar(c)}}function $r(e,t,n,r=Date.now()){return Br(e,t,r,0,n)}function po(e){let t=oo(e);return{latestPath:Lr(t,"affected-shadow-latest.json"),historyPath:Lr(t,"affected-shadow.jsonl")}}function Gr(e,t,n=So){let r=po(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}var go=8*1024*1024,fo=Zn;function mo(e){let t={historyVersion:1,sourceVersion:e.version,refreshResult:e.refreshResult,recordedAt:e.recordedAt,durationMs:e.durationMs};return e.status==="unavailable"?{...t,status:"unavailable",reason:e.reason,...e.error?{error:e.error}:{}}:{...t,status:"evaluated",mode:e.plan.mode,passed:e.evaluation.passed,recall:e.evaluation.recall,affectedRatio:e.evaluation.affectedRatio,predictedFileCount:e.evaluation.predictedFiles.length,actualFileCount:e.evaluation.actualFiles.length,missingFileCount:e.evaluation.missingFiles.length,fallbackReasons:[...e.plan.reasons]}}function ho(e,t,n=go){er(e,mo(t),{maxSegmentBytes:n,previousSuffix:fo})}function Et(e,t=[]){let n=[];for(let r of t)n.push(r);return n.push(e.symbol,e.display_name,e.kind,e.documentation,e.signature_hex,e.enclosing_symbol,e.relationships_hex),n}var yo={now:()=>Date.now(),wallNow:()=>Date.now(),monotonicNow:C,databaseExists:e=>ao(e),openDatabase:(e,t,n)=>new $({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>ke(e),dependencyGraph:e=>Wn(e),factDigests:e=>co(e)},So={appendHistory:ho,writeLatest:(e,t)=>Fe(e,t,{spacing:2,trailingNewline:!0})};function Br(e,t,n,r,a){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(n).toISOString(),durationMs:r,reason:t,...a?{error:a}:{}}}function Ar(e){try{e?.close()}catch{}}import{readdirSync as bo}from"fs";import{isAbsolute as Ur,join as Po,resolve as Ro}from"path";var He="@sourcegraph/scip-typescript@0.4.0",qr="scip-python-plus@0.7.5",Wr="github.com/sourcegraph/scip-go@v0.2.7",Hr="scip-dotnet@0.2.14",xo="scip_dart@1.6.2",Eo={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:r})=>r?{binary:n,args:["index","--output",e,"--no-progress-bar","--no-global-caches",r]}:t?{binary:n,args:["index","--pnpm-workspaces","--output",e,"--no-progress-bar","--no-global-caches"]}:{binary:n,args:["index","--output",e,"--no-progress-bar","--no-global-caches"]},markerFiles:[...M.typescript],installMethods:[{label:"npm",identity:He,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",He]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--no-progress-bar","--no-global-caches"]}),markerFiles:[...M.javascript],installMethods:[{label:"npm",identity:He,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",He]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},java:{language:"java",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:[...M.java],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:[...M.scala],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:[...M.kotlin],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:de.language,indexerBinary:de.indexerBinary,checkCommand:`${de.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:de.indexerBinary,args:["scip",".","--output",e]}),markerFiles:[...M.rust],installMethods:[],installUrl:de.installUrl},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:[...M.python],installMethods:[{label:"npm",identity:qr,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",qr]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},clojure:{language:"clojure",indexerBinary:"scip-clojure",projectLocalBinaries:["node_modules/.bin/scip-clojure"],checkCommand:"scip-clojure -h",indexArgs:({projectRoot:e,outputPath:t,indexerBinary:n,configPath:r})=>{let a=["-root",e,"-output",t];return r&&a.push("-config",Ur(r)?r:Ro(e,r)),{binary:n,args:a}},markerFiles:[...M.clojure],installMethods:[],installUrl:"https://github.com/PlunderStruck/scip-clojure"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:[...M.ruby],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:[...M.go],installMethods:[{label:"go install",identity:Wr,destination:"Go bin directory (GOBIN or GOPATH/bin)",prerequisite:"go",binary:"go",args:["install",Wr]}],installUrl:"https://github.com/sourcegraph/scip-go"},cpp:{language:"cpp",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:[...M.cpp],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:[...M.c],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Jr(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...M.csharp],installMethods:[{label:"dotnet",identity:Hr,destination:"dotnet global tool directory",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet","--version","0.2.14"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},vb:{language:"vb",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Jr(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...M.vb],installMethods:[{label:"dotnet",identity:Hr,destination:"dotnet global tool directory",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet","--version","0.2.14"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},dart:{language:"dart",indexerBinary:"scip-dart",checkCommand:"scip-dart --version",indexArgs:({indexerBinary:e,outputPath:t})=>({binary:e,args:["--output",t]}),markerFiles:[...M.dart],installMethods:[{label:"dart pub",identity:xo,destination:"Dart pub global cache",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart","1.6.2"]}],installUrl:"https://github.com/Workiva/scip-dart/releases"},php:{language:"php",indexerBinary:"scip-php",projectLocalBinaries:["vendor/davidrjenni/scip-php/bin/scip-php","vendor/bin/scip-php"],checkCommand:"scip-php --version",indexArgs:({indexerBinary:e})=>Ur(e)?{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",e]}:{binary:e,args:[]},defaultOutputPath:"index.scip",markerFiles:[...M.php],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function zr(e){if(!(e.projectPath||e.pnpmWorkspaces)){if(e.language==="typescript")return"{}";if(e.language==="javascript")return'{"compilerOptions":{"allowJs":true}}'}}function _t(e){return Eo[e]}function Jr(e,t){let n;try{n=bo(e)}catch{return null}for(let r of t)for(let a of n)if(a.endsWith(r))return Po(e,a);return null}import{createHash as Io}from"crypto";import{existsSync as wt,rmSync as Xr,statSync as vo}from"fs";import{resolve as _o}from"path";import Kr from"better-sqlite3";var To={documents:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"language",type:"TEXT",notnull:0,pk:0},{name:"relative_path",type:"TEXT",notnull:1,pk:0},{name:"position_encoding",type:"TEXT",notnull:0,pk:0},{name:"text",type:"TEXT",notnull:0,pk:0}],chunks:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"chunk_index",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"occurrences",type:"BLOB",notnull:1,pk:0}],global_symbols:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"symbol",type:"TEXT",notnull:1,pk:0},{name:"display_name",type:"TEXT",notnull:0,pk:0},{name:"kind",type:"INTEGER",notnull:0,pk:0},{name:"documentation",type:"TEXT",notnull:0,pk:0},{name:"signature",type:"BLOB",notnull:0,pk:0},{name:"enclosing_symbol",type:"TEXT",notnull:0,pk:0},{name:"relationships",type:"BLOB",notnull:0,pk:0}],mentions:[{name:"chunk_id",type:"INTEGER",notnull:1,pk:1},{name:"symbol_id",type:"INTEGER",notnull:1,pk:2},{name:"role",type:"INTEGER",notnull:1,pk:3}],defn_enclosing_ranges:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"symbol_id",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"start_char",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"end_char",type:"INTEGER",notnull:1,pk:0}]},wo={idx_chunks_line_range:{table:"chunks",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_document:{table:"defn_enclosing_ranges",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_symbol_id:{table:"defn_enclosing_ranges",columns:["symbol_id"]},idx_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function Vr(e){let t=C(),n=Yr(e.affectedFiles),r=Yr(e.deletedFiles??[],!0),a=new Set(n);if(r.some(s=>!a.has(s)))throw new Error("deleted incremental documents must be included in the affected document set");let i=n.length-r.length;if(jo(e.previousDbPath,e.miniDbPath,e.candidateDbPath),!wt(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!wt(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");E("reindex.publish.sqlite-patch.validate-inputs",()=>{Tt(e.previousDbPath,"previous SQLite generation",!1),Tt(e.miniDbPath,"incremental SQLite mini database")}),e.reuseCandidate?E("reindex.publish.sqlite-patch.reuse-candidate",()=>Tt(e.candidateDbPath,"incremental SQLite candidate",!1)):E("reindex.publish.sqlite-patch.clone",()=>{Xr(e.candidateDbPath,{force:!0});let s=K(e.previousDbPath,e.candidateDbPath);e.writeTelemetry&&V(e.writeTelemetry,s)});let o=null;try{o=E("reindex.publish.sqlite-patch.open",()=>{let f=new Kr(e.candidateDbPath,{fileMustExist:!0});return f.pragma("busy_timeout = 5000"),f.pragma("foreign_keys = ON"),f.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),Ct(f,"main","candidate SQLite generation"),Ct(f,"incremental","incremental SQLite mini database"),f});let{priorAffectedCount:s,previousFactDigests:c}=E("reindex.publish.sqlite-patch.prepare",()=>(ko(o,n,r),{...Do(o,n.length,r.length),previousFactDigests:jt(o,"main",!0)})),d=H(o,"SELECT COUNT(*) AS value FROM main.documents"),l=o.transaction(()=>{E("reindex.publish.sqlite-patch.transaction.symbol-ownership",()=>Mo(o)),E("reindex.publish.sqlite-patch.transaction.shared-definitions",()=>No(o)),E("reindex.publish.sqlite-patch.transaction.delete",()=>Lo(o)),e.onStage?.("after-delete"),E("reindex.publish.sqlite-patch.transaction.reconcile-symbols",()=>Ao(o)),e.onStage?.("after-symbol-reconciliation"),E("reindex.publish.sqlite-patch.transaction.insert",()=>$o(o)),e.onStage?.("after-insert"),E("reindex.publish.sqlite-patch.transaction.prune-symbols",()=>Go(o,e.trustedPriorGeneration===!0)),E("reindex.publish.sqlite-patch.transaction.validate",()=>Bo(o,i,d,s)),e.onStage?.("before-commit")});E("reindex.publish.sqlite-patch.transaction",()=>l.immediate()),e.writeTelemetry&&We(e.writeTelemetry,2*Co(e.candidateDbPath)),E("reindex.publish.sqlite-patch.integrity",()=>Fo(o,"candidate SQLite generation",!e.deferIntegrity&&e.trustedPriorGeneration!==!0));let g=E("reindex.publish.sqlite-patch.validate-facts",()=>Uo(o)),p=[...new Set([...c.keys(),...g.keys()])].filter(f=>c.get(f)!==g.get(f)).sort();return o.exec("DETACH DATABASE incremental"),o.close(),o=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:p,durationMs:C()-t}}catch(s){try{o?.close()}finally{Xr(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}function Co(e){let t=0;for(let n of["-wal","-journal"]){let r=`${e}${n}`;wt(r)&&(t+=vo(r).size)}return t}function Yr(e,t=!1){if(!t&&e.length===0)throw new Error("incremental SQLite publication requires affected documents");let n=[...e].sort();for(let r of n)if(!r||r.startsWith("/")||r.includes("\\")||r.split("/").includes(".."))throw new Error(`invalid affected document path: ${r}`);if(new Set(n).size!==n.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return n}function jo(e,t,n){let r=[e,t,n].map(a=>_o(a));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function Tt(e,t,n=!0){let r=new Kr(e,{readonly:!0,fileMustExist:!0});try{Ct(r,"main",t),n&&Oo(r,"main",t)}finally{r.close()}}function Ct(e,t,n){for(let[r,a]of Object.entries(To)){let o=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:s,type:c,notnull:d,pk:l})=>({name:s,type:c.toUpperCase(),notnull:d,pk:l}));if(JSON.stringify(o)!==JSON.stringify(a))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,a]of Object.entries(wo)){let i=e.prepare(`SELECT tbl_name FROM ${t}.sqlite_master WHERE type = 'index' AND name = ?`).get(r),o=e.prepare(`PRAGMA ${t}.index_info('${r}')`).all().map(s=>s.name);if(i?.tbl_name!==a.table||JSON.stringify(o)!==JSON.stringify(a.columns))throw new Error(`${n} schema changed for index ${r}`)}Qr(e,t,"documents",["relative_path"],n),Qr(e,t,"global_symbols",["symbol"],n)}function Qr(e,t,n,r,a){if(!e.prepare(`PRAGMA ${t}.index_list('${n}')`).all().some(s=>{if(s.unique!==1)return!1;let c=e.prepare(`PRAGMA ${t}.index_info('${s.name}')`).all().map(d=>d.name);return JSON.stringify(c)===JSON.stringify(r)}))throw new Error(`${a} lost the unique ${n}(${r.join(", ")}) constraint`)}function Oo(e,t,n){let r=e.prepare(`PRAGMA ${t}.integrity_check`).pluck().get();if(r!=="ok")throw new Error(`${n} failed integrity_check: ${String(r)}`);if(e.prepare(`PRAGMA ${t}.foreign_key_check`).all().length>0)throw new Error(`${n} failed foreign_key_check`)}function Fo(e,t,n){if(e.pragma("foreign_keys",{simple:!0})!==1)throw new Error(`${t} lost foreign-key enforcement`);if(!n)return;let r=e.prepare("PRAGMA main.quick_check").pluck().get();if(r!=="ok")throw new Error(`${t} failed quick_check: ${String(r)}`)}function ko(e,t,n){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID"),e.exec("CREATE TEMP TABLE incremental_deleted_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let r=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)"),a=e.prepare("INSERT INTO temp.incremental_deleted_paths(relative_path) VALUES (?)");e.transaction(o=>{for(let s of o)r.run(s);for(let s of n)a.run(s)})(t)}function Do(e,t,n){let r=H(e,"SELECT COUNT(*) AS value FROM incremental.documents"),a=H(e,`SELECT COUNT(*) AS value
107
+ `))t.push({relativePath:Rp,kind:"global-symbol",values:br(n)});return Ip(t)}function Ip(e){let t=new Map;for(let r of e){let i=JSON.stringify([r.kind,r.values]),a=t.get(r.relativePath)??[];a.push(i),t.set(r.relativePath,a)}let n=new Map;for(let[r,i]of[...t].sort(([a],[o])=>a.localeCompare(o))){let a=Sp("sha256");for(let o of i.sort())a.update(String(Buffer.byteLength(o))),a.update(":"),a.update(o),a.update(`
108
+ `);n.set(r,a.digest("hex"))}return n}function Ep(e,t){let n=[],r=[],i=[],a=[],o=new Set([...e.keys(),...t.keys()]);for(let s of[...o].sort()){let c=e.get(s),l=t.get(s);c===void 0?n.push(s):l===void 0?i.push(s):c!==l?r.push(s):a.push(s)}return{addedFiles:n,modifiedFiles:r,deletedFiles:i,changedFiles:[...n,...r,...i].sort(),unchangedFiles:a}}function Sr(e,t,n){let r=new Set(e.affectedFiles),i=new Set(t.changedFiles),a=e.mode==="full-project"?[]:t.changedFiles.filter(c=>!r.has(c)),o=e.affectedFiles.filter(c=>!i.has(c)).sort(),s=t.changedFiles.length-a.length;return{passed:a.length===0,recall:t.changedFiles.length===0?1:s/t.changedFiles.length,affectedRatio:n===0?0:e.affectedFiles.length/n,predictedFiles:[...e.affectedFiles].sort(),actualFiles:[...t.changedFiles],missingFiles:a,extraFiles:o}}function vr(e,t=Np){let n=t.wallNow===void 0&&t.monotonicNow===void 0,r=t.monotonicNow??t.now,i=t.wallNow??t.now,a=r(),o=(l,u)=>{let d=r();return ps(e.refreshResult,l,n?d:i(),Math.max(0,d-a),u)};if(!t.databaseExists(e.previousDbPath))return o("prior-index-unavailable");if(!t.databaseExists(e.candidateDbPath))return o("candidate-index-unavailable");if(kp(e))return o("no-input-changes");let s=null,c=null;try{s=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),c=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let l=[...new Set([...t.indexedPaths(s),...t.indexedPaths(c)])].sort(),u=me(e.previousSnapshot,e.currentSnapshot),d=Dp(u,l,s,t),p=Ep(t.factDigests(s),t.factDigests(c)),m=r();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(n?m:i()).toISOString(),durationMs:Math.max(0,m-a),manifest:u,plan:d,comparison:p,evaluation:Sr(d,p,l.length)}}catch(l){return o("oracle-error",l instanceof Error?l.message:String(l))}finally{ls(s),ls(c)}}function us(e,t,n,r=Date.now()){return ps(e,t,r,0,n)}function Cp(e){let t=xp(e);return{latestPath:cs(t,"affected-shadow-latest.json"),historyPath:cs(t,"affected-shadow.jsonl")}}function ds(e,t,n=Op){let r=Cp(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}var Tp=8*1024*1024,wp=xa;function Fp(e){let t={historyVersion:1,sourceVersion:e.version,refreshResult:e.refreshResult,recordedAt:e.recordedAt,durationMs:e.durationMs};return e.status==="unavailable"?{...t,status:"unavailable",reason:e.reason,...e.error?{error:e.error}:{}}:{...t,status:"evaluated",mode:e.plan.mode,passed:e.evaluation.passed,recall:e.evaluation.recall,affectedRatio:e.evaluation.affectedRatio,predictedFileCount:e.evaluation.predictedFiles.length,actualFileCount:e.evaluation.actualFiles.length,missingFileCount:e.evaluation.missingFiles.length,fallbackReasons:[...e.plan.reasons]}}function _p(e,t,n=Tp){Ra(e,Fp(t),{maxSegmentBytes:n,previousSuffix:wp})}function br(e,t=[]){let n=[];for(let r of t)n.push(r);return n.push(e.symbol,e.display_name,e.kind,e.documentation,e.signature_hex,e.enclosing_symbol,e.relationships_hex),n}var Np={now:()=>Date.now(),wallNow:()=>Date.now(),monotonicNow:w,databaseExists:e=>vp(e),openDatabase:(e,t,n)=>new $({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>Rt(e),dependencyGraph:e=>ia(e),factDigests:e=>Pp(e)},Op={appendHistory:_p,writeLatest:(e,t)=>ai(e,t,{spacing:2,trailingNewline:!0})};function ps(e,t,n,r,i){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(n).toISOString(),durationMs:r,reason:t,...i?{error:i}:{}}}function ls(e){try{e?.close()}catch{}}function Dp(e,t,n,r){let i=new Set(t),a=e.changes.length>0&&!Ie(e).fullProject&&e.changes.every(s=>i.has(s.path));return fn(e,a?r.dependencyGraph(n):new Map,t)}function kp(e){return e.refreshResult!=="rebuilt"?!1:me(e.previousSnapshot,e.currentSnapshot).changes.length===0}import{readdirSync as Lp}from"fs";import{isAbsolute as ms,join as Ap,resolve as Mp}from"path";var gn="@sourcegraph/scip-typescript@0.4.0",fs="scip-python-plus@0.7.5",gs="github.com/sourcegraph/scip-go@v0.2.7",hs="scip-dotnet@0.2.14",jp="scip_dart@1.6.2",Bp={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:r})=>r?{binary:n,args:["index","--output",e,"--no-progress-bar","--no-global-caches",r]}:t?{binary:n,args:["index","--pnpm-workspaces","--output",e,"--no-progress-bar","--no-global-caches"]}:{binary:n,args:["index","--output",e,"--no-progress-bar","--no-global-caches"]},markerFiles:[...k.typescript],installMethods:[{label:"npm",identity:gn,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",gn]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--no-progress-bar","--no-global-caches"]}),markerFiles:[...k.javascript],installMethods:[{label:"npm",identity:gn,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",gn]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},java:{language:"java",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:[...k.java],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:[...k.scala],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:[...k.kotlin],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:ke.language,indexerBinary:ke.indexerBinary,checkCommand:`${ke.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:ke.indexerBinary,args:["scip",".","--output",e]}),markerFiles:[...k.rust],installMethods:[],installUrl:ke.installUrl},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:[...k.python],installMethods:[{label:"npm",identity:fs,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",fs]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},clojure:{language:"clojure",indexerBinary:"scip-clojure",projectLocalBinaries:["node_modules/.bin/scip-clojure"],checkCommand:"scip-clojure -h",indexArgs:({projectRoot:e,outputPath:t,indexerBinary:n,configPath:r})=>{let i=["-root",e,"-output",t];return r&&i.push("-config",ms(r)?r:Mp(e,r)),{binary:n,args:i}},markerFiles:[...k.clojure],installMethods:[],installUrl:"https://github.com/PlunderStruck/scip-clojure"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:[...k.ruby],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:[...k.go],installMethods:[{label:"go install",identity:gs,destination:"Go bin directory (GOBIN or GOPATH/bin)",prerequisite:"go",binary:"go",args:["install",gs]}],installUrl:"https://github.com/sourcegraph/scip-go"},cpp:{language:"cpp",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:[...k.cpp],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:[...k.c],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",ys(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...k.csharp],installMethods:[{label:"dotnet",identity:hs,destination:"dotnet global tool directory",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet","--version","0.2.14"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},vb:{language:"vb",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",ys(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...k.vb],installMethods:[{label:"dotnet",identity:hs,destination:"dotnet global tool directory",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet","--version","0.2.14"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},dart:{language:"dart",indexerBinary:"scip-dart",checkCommand:"scip-dart --version",indexArgs:({indexerBinary:e,outputPath:t})=>({binary:e,args:["--output",t]}),markerFiles:[...k.dart],installMethods:[{label:"dart pub",identity:jp,destination:"Dart pub global cache",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart","1.6.2"]}],installUrl:"https://github.com/Workiva/scip-dart/releases"},php:{language:"php",indexerBinary:"scip-php",projectLocalBinaries:["vendor/davidrjenni/scip-php/bin/scip-php","vendor/bin/scip-php"],checkCommand:"scip-php --version",indexArgs:({indexerBinary:e})=>ms(e)?{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",e]}:{binary:e,args:[]},defaultOutputPath:"index.scip",markerFiles:[...k.php],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function bs(e){if(!(e.projectPath||e.pnpmWorkspaces)){if(e.language==="typescript")return"{}";if(e.language==="javascript")return'{"compilerOptions":{"allowJs":true}}'}}function hn(e){return Bp[e]}function ys(e,t){let n;try{n=Lp(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return Ap(e,i);return null}import{createHash as $p}from"crypto";import{existsSync as Rr,rmSync as Ss,statSync as Up}from"fs";import{resolve as Gp}from"path";import Rs from"better-sqlite3";var Hp={documents:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"language",type:"TEXT",notnull:0,pk:0},{name:"relative_path",type:"TEXT",notnull:1,pk:0},{name:"position_encoding",type:"TEXT",notnull:0,pk:0},{name:"text",type:"TEXT",notnull:0,pk:0}],chunks:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"chunk_index",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"occurrences",type:"BLOB",notnull:1,pk:0}],global_symbols:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"symbol",type:"TEXT",notnull:1,pk:0},{name:"display_name",type:"TEXT",notnull:0,pk:0},{name:"kind",type:"INTEGER",notnull:0,pk:0},{name:"documentation",type:"TEXT",notnull:0,pk:0},{name:"signature",type:"BLOB",notnull:0,pk:0},{name:"enclosing_symbol",type:"TEXT",notnull:0,pk:0},{name:"relationships",type:"BLOB",notnull:0,pk:0}],mentions:[{name:"chunk_id",type:"INTEGER",notnull:1,pk:1},{name:"symbol_id",type:"INTEGER",notnull:1,pk:2},{name:"role",type:"INTEGER",notnull:1,pk:3}],defn_enclosing_ranges:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"symbol_id",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"start_char",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"end_char",type:"INTEGER",notnull:1,pk:0}]},qp={idx_chunks_line_range:{table:"chunks",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_document:{table:"defn_enclosing_ranges",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_symbol_id:{table:"defn_enclosing_ranges",columns:["symbol_id"]},idx_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function Ps(e){let t=w(),n=vs(e.affectedFiles),r=vs(e.deletedFiles??[],!0),i=new Set(n);if(r.some(s=>!i.has(s)))throw new Error("deleted incremental documents must be included in the affected document set");let a=n.length-r.length;if(zp(e.previousDbPath,e.miniDbPath,e.candidateDbPath),!Rr(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!Rr(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");P("reindex.publish.sqlite-patch.validate-inputs",()=>{xr(e.previousDbPath,"previous SQLite generation",!1),xr(e.miniDbPath,"incremental SQLite mini database")}),e.reuseCandidate?P("reindex.publish.sqlite-patch.reuse-candidate",()=>xr(e.candidateDbPath,"incremental SQLite candidate",!1)):P("reindex.publish.sqlite-patch.clone",()=>{Ss(e.candidateDbPath,{force:!0});let s=re(e.previousDbPath,e.candidateDbPath);e.writeTelemetry&&ie(e.writeTelemetry,s)});let o=null;try{o=P("reindex.publish.sqlite-patch.open",()=>{let m=new Rs(e.candidateDbPath,{fileMustExist:!0});return m.pragma("busy_timeout = 5000"),m.pragma("foreign_keys = ON"),m.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),Pr(m,"main","candidate SQLite generation"),Pr(m,"incremental","incremental SQLite mini database"),m});let{priorAffectedCount:s,previousFactDigests:c}=P("reindex.publish.sqlite-patch.prepare",()=>(Xp(o,n,r),{...Jp(o,n.length,r.length),previousFactDigests:Ir(o,"main",!0)})),l=le(o,"SELECT COUNT(*) AS value FROM main.documents"),u=o.transaction(()=>{P("reindex.publish.sqlite-patch.transaction.symbol-ownership",()=>Yp(o)),P("reindex.publish.sqlite-patch.transaction.shared-definitions",()=>Qp(o)),P("reindex.publish.sqlite-patch.transaction.delete",()=>Zp(o)),e.onStage?.("after-delete"),P("reindex.publish.sqlite-patch.transaction.reconcile-symbols",()=>em(o)),e.onStage?.("after-symbol-reconciliation"),P("reindex.publish.sqlite-patch.transaction.insert",()=>tm(o)),e.onStage?.("after-insert"),P("reindex.publish.sqlite-patch.transaction.prune-symbols",()=>nm(o,e.trustedPriorGeneration===!0)),P("reindex.publish.sqlite-patch.transaction.validate",()=>rm(o,a,l,s)),e.onStage?.("before-commit")});P("reindex.publish.sqlite-patch.transaction",()=>u.immediate()),e.writeTelemetry&&qt(e.writeTelemetry,2*Vp(e.candidateDbPath)),P("reindex.publish.sqlite-patch.integrity",()=>Kp(o,"candidate SQLite generation",!e.deferIntegrity&&e.trustedPriorGeneration!==!0));let d=P("reindex.publish.sqlite-patch.validate-facts",()=>im(o)),p=[...new Set([...c.keys(),...d.keys()])].filter(m=>c.get(m)!==d.get(m)).sort();return o.exec("DETACH DATABASE incremental"),o.close(),o=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:p,durationMs:w()-t}}catch(s){try{o?.close()}finally{Ss(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}function Vp(e){let t=0;for(let n of["-wal","-journal"]){let r=`${e}${n}`;Rr(r)&&(t+=Up(r).size)}return t}function vs(e,t=!1){if(!t&&e.length===0)throw new Error("incremental SQLite publication requires affected documents");let n=[...e].sort();for(let r of n)if(!r||r.startsWith("/")||r.includes("\\")||r.split("/").includes(".."))throw new Error(`invalid affected document path: ${r}`);if(new Set(n).size!==n.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return n}function zp(e,t,n){let r=[e,t,n].map(i=>Gp(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function xr(e,t,n=!0){let r=new Rs(e,{readonly:!0,fileMustExist:!0});try{Pr(r,"main",t),n&&Wp(r,"main",t)}finally{r.close()}}function Pr(e,t,n){for(let[r,i]of Object.entries(Hp)){let o=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:s,type:c,notnull:l,pk:u})=>({name:s,type:c.toUpperCase(),notnull:l,pk:u}));if(JSON.stringify(o)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(qp)){let a=e.prepare(`SELECT tbl_name FROM ${t}.sqlite_master WHERE type = 'index' AND name = ?`).get(r),o=e.prepare(`PRAGMA ${t}.index_info('${r}')`).all().map(s=>s.name);if(a?.tbl_name!==i.table||JSON.stringify(o)!==JSON.stringify(i.columns))throw new Error(`${n} schema changed for index ${r}`)}xs(e,t,"documents",["relative_path"],n),xs(e,t,"global_symbols",["symbol"],n)}function xs(e,t,n,r,i){if(!e.prepare(`PRAGMA ${t}.index_list('${n}')`).all().some(s=>{if(s.unique!==1)return!1;let c=e.prepare(`PRAGMA ${t}.index_info('${s.name}')`).all().map(l=>l.name);return JSON.stringify(c)===JSON.stringify(r)}))throw new Error(`${i} lost the unique ${n}(${r.join(", ")}) constraint`)}function Wp(e,t,n){let r=e.prepare(`PRAGMA ${t}.integrity_check`).pluck().get();if(r!=="ok")throw new Error(`${n} failed integrity_check: ${String(r)}`);if(e.prepare(`PRAGMA ${t}.foreign_key_check`).all().length>0)throw new Error(`${n} failed foreign_key_check`)}function Kp(e,t,n){if(e.pragma("foreign_keys",{simple:!0})!==1)throw new Error(`${t} lost foreign-key enforcement`);if(!n)return;let r=e.prepare("PRAGMA main.quick_check").pluck().get();if(r!=="ok")throw new Error(`${t} failed quick_check: ${String(r)}`)}function Xp(e,t,n){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID"),e.exec("CREATE TEMP TABLE incremental_deleted_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let r=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)"),i=e.prepare("INSERT INTO temp.incremental_deleted_paths(relative_path) VALUES (?)");e.transaction(o=>{for(let s of o)r.run(s);for(let s of n)i.run(s)})(t)}function Jp(e,t,n){let r=le(e,"SELECT COUNT(*) AS value FROM incremental.documents"),i=le(e,`SELECT COUNT(*) AS value
59
109
  FROM main.documents d
60
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),i=e.prepare(`SELECT p.relative_path
110
+ JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),a=e.prepare(`SELECT p.relative_path
61
111
  FROM temp.incremental_affected_paths p
62
112
  LEFT JOIN incremental.documents d ON d.relative_path = p.relative_path
63
113
  LEFT JOIN temp.incremental_deleted_paths deleted ON deleted.relative_path = p.relative_path
@@ -69,7 +119,7 @@ import{a as Ce,b as xn,c as En,d as In,e as vn,f as _n,g as Tn,h as wn}from"./ch
69
119
  LIMIT 1`).pluck().get(),s=e.prepare(`SELECT d.relative_path
70
120
  FROM incremental.documents d
71
121
  JOIN temp.incremental_deleted_paths deleted ON deleted.relative_path = d.relative_path
72
- LIMIT 1`).pluck().get();if(r!==t-n||i!==void 0||o!==void 0||s!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set");return{priorAffectedCount:a}}function Mo(e){e.exec(`
122
+ LIMIT 1`).pluck().get();if(r!==t-n||a!==void 0||o!==void 0||s!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set");return{priorAffectedCount:i}}function Yp(e){e.exec(`
73
123
  CREATE TEMP TABLE incremental_old_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
74
124
  INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
75
125
  SELECT g.symbol
@@ -109,7 +159,7 @@ import{a as Ce,b as xn,c as En,d as In,e as vn,f as _n,g as Tn,h as wn}from"./ch
109
159
  CROSS JOIN main.global_symbols g ON g.id = m.symbol_id;
110
160
  INSERT OR IGNORE INTO temp.incremental_touched_symbols(symbol)
111
161
  SELECT symbol FROM incremental.global_symbols;
112
- `)}function No(e){let t=e.prepare(`WITH changed_symbols AS (
162
+ `)}function Qp(e){let t=e.prepare(`WITH changed_symbols AS (
113
163
  SELECT symbol FROM temp.incremental_old_defined_symbols
114
164
  UNION
115
165
  SELECT symbol FROM temp.incremental_new_defined_symbols
@@ -131,7 +181,7 @@ import{a as Ce,b as xn,c as En,d as In,e as vn,f as _n,g as Tn,h as wn}from"./ch
131
181
  LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
132
182
  WHERE m.symbol_id = g.id AND m.role = 1 AND p.relative_path IS NULL
133
183
  )
134
- LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function Lo(e){e.exec(`
184
+ LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function Zp(e){e.exec(`
135
185
  DELETE FROM main.mentions
136
186
  WHERE chunk_id IN (
137
187
  SELECT c.id
@@ -153,7 +203,7 @@ import{a as Ce,b as xn,c as En,d as In,e as vn,f as _n,g as Tn,h as wn}from"./ch
153
203
  );
154
204
  DELETE FROM main.documents
155
205
  WHERE relative_path IN (SELECT relative_path FROM temp.incremental_affected_paths);
156
- `)}function Ao(e){e.exec(`
206
+ `)}function em(e){e.exec(`
157
207
  UPDATE main.global_symbols
158
208
  SET display_name = NULL,
159
209
  kind = NULL,
@@ -195,7 +245,7 @@ import{a as Ce,b as xn,c as En,d as In,e as vn,f as _n,g as Tn,h as wn}from"./ch
195
245
  WHERE source.symbol = main.global_symbols.symbol
196
246
  )
197
247
  WHERE symbol IN (SELECT symbol FROM temp.incremental_new_defined_symbols);
198
- `)}function $o(e){let t=H(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=H(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=H(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.defn_enclosing_ranges");e.prepare(`INSERT INTO main.documents(id, language, relative_path, position_encoding, text)
248
+ `)}function tm(e){let t=le(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=le(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=le(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.defn_enclosing_ranges");e.prepare(`INSERT INTO main.documents(id, language, relative_path, position_encoding, text)
199
249
  SELECT id + ?, language, relative_path, position_encoding, text
200
250
  FROM incremental.documents`).run(t),e.prepare(`INSERT INTO main.chunks(id, document_id, chunk_index, start_line, end_line, occurrences)
201
251
  SELECT id + ?, document_id + ?, chunk_index, start_line, end_line, occurrences
@@ -210,19 +260,19 @@ import{a as Ce,b as xn,c as En,d as In,e as vn,f as _n,g as Tn,h as wn}from"./ch
210
260
  r.start_line, r.start_char, r.end_line, r.end_char
211
261
  FROM incremental.defn_enclosing_ranges r
212
262
  CROSS JOIN incremental.global_symbols source ON source.id = r.symbol_id
213
- CROSS JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function Go(e,t){let n=t?"symbol IN (SELECT symbol FROM temp.incremental_touched_symbols) AND":"";e.exec(`
263
+ CROSS JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function nm(e,t){let n=t?"symbol IN (SELECT symbol FROM temp.incremental_touched_symbols) AND":"";e.exec(`
214
264
  DELETE FROM main.global_symbols
215
265
  WHERE ${n}
216
266
  NOT EXISTS (SELECT 1 FROM main.mentions m WHERE m.symbol_id = main.global_symbols.id)
217
267
  AND NOT EXISTS (
218
268
  SELECT 1 FROM main.defn_enclosing_ranges r WHERE r.symbol_id = main.global_symbols.id
219
269
  );
220
- `)}function Bo(e,t,n,r){let a=H(e,"SELECT COUNT(*) AS value FROM main.documents"),i=H(e,`SELECT COUNT(*) AS value
270
+ `)}function rm(e,t,n,r){let i=le(e,"SELECT COUNT(*) AS value FROM main.documents"),a=le(e,`SELECT COUNT(*) AS value
221
271
  FROM main.documents d
222
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),o=n-r+t;if(a!==o||i!==t)throw new Error("candidate SQLite document counts changed unexpectedly")}function Uo(e){let t=jt(e,"main",!0),n=jt(e,"incremental",!1);if(JSON.stringify([...t])!==JSON.stringify([...n]))throw new Error("candidate SQLite affected document facts differ from the mini database");return t}function jt(e,t,n){let r=n?"JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path":"",a=e.prepare(`SELECT d.relative_path, d.language, d.position_encoding, d.text
272
+ JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),o=n-r+t;if(i!==o||a!==t)throw new Error("candidate SQLite document counts changed unexpectedly")}function im(e){let t=Ir(e,"main",!0),n=Ir(e,"incremental",!1);if(JSON.stringify([...t])!==JSON.stringify([...n]))throw new Error("candidate SQLite affected document facts differ from the mini database");return t}function Ir(e,t,n){let r=n?"JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path":"",i=e.prepare(`SELECT d.relative_path, d.language, d.position_encoding, d.text
223
273
  FROM ${t}.documents d
224
274
  ${r}
225
- ORDER BY d.relative_path`).all(),i=e.prepare(`SELECT d.relative_path, c.chunk_index, c.start_line, c.end_line, hex(c.occurrences) AS occurrences
275
+ ORDER BY d.relative_path`).all(),a=e.prepare(`SELECT d.relative_path, c.chunk_index, c.start_line, c.end_line, hex(c.occurrences) AS occurrences
226
276
  FROM ${t}.chunks c
227
277
  JOIN ${t}.documents d ON d.id = c.document_id
228
278
  ${r}
@@ -241,9 +291,9 @@ import{a as Ce,b as xn,c as En,d as In,e as vn,f as _n,g as Tn,h as wn}from"./ch
241
291
  JOIN ${t}.documents d ON d.id = c.document_id
242
292
  JOIN ${t}.global_symbols g ON g.id = m.symbol_id
243
293
  ${r}
244
- ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[l,g]of Object.entries({documents:a,chunks:i,definitions:o,mentions:s}))for(let p of g){let f=JSON.stringify([l,p]),R=c.get(p.relative_path)??[];R.push(f),c.set(p.relative_path,R)}let d=new Map;for(let[l,g]of[...c].sort(([p],[f])=>p.localeCompare(f))){let p=Io("sha256");for(let f of g.sort())p.update(f).update(`
245
- `);d.set(l,p.digest("hex"))}return d}function H(e,t){return e.prepare(t).get().value}import qo from"better-sqlite3";var Je="idx_mentions_definitions",Wo=["symbol_id","chunk_id"];function Ot(e,t={}){let n=new qo(e),r=[],a=[],i=[];try{return n.transaction(()=>{Ho(n,r),ze(n,"idx_global_symbols_symbol")?.join("\0")==="symbol"&&Zr(n,"global_symbols").some(c=>c.name!=="idx_global_symbols_symbol"&&c.unique&&c.columns.join("\0")==="symbol")?(n.exec('DROP INDEX "idx_global_symbols_symbol"'),a.push("idx_global_symbols_symbol")):ze(n,"idx_global_symbols_symbol")&&i.push("idx_global_symbols_symbol");let o=ze(n,"idx_chunks_doc_id"),s=Zr(n,"chunks").some(c=>c.name!=="idx_chunks_doc_id"&&c.columns.length>1&&c.columns[0]==="document_id");o?.join("\0")==="document_id"&&s?(n.exec('DROP INDEX "idx_chunks_doc_id"'),a.push("idx_chunks_doc_id")):o&&i.push("idx_chunks_doc_id"),t.analyze!==!1&&n.exec("ANALYZE")})(),{added:r,removed:a,retained:i,analyzed:t.analyze!==!1}}catch(o){if(o.code==="SQLITE_NOTADB")return{added:[],removed:[],retained:[],analyzed:!1,skippedReason:"not-a-sqlite-database"};throw o}finally{n.close()}}function Ho(e,t){let n=ei(e,Je);if(n){let r=n.columns.join("\0")===Wo.join("\0"),a=/\bWHERE\s+role\s*=\s*1\b/iu.test(n.sql??"");if(!r||!a||n.table!=="mentions")throw new Error(`${Je} exists with an incompatible definition`);return}e.exec(`CREATE INDEX "${Je}" ON mentions(symbol_id, chunk_id) WHERE role = 1`),t.push(Je)}function Zr(e,t){return e.prepare(`PRAGMA index_list('${t.replaceAll("'","''")}')`).all().map(n=>({name:n.name,unique:n.unique===1,columns:ze(e,n.name)??[]}))}function ze(e,t){return ei(e,t)?.columns??null}function ei(e,t){let n=e.prepare("SELECT tbl_name, sql FROM sqlite_master WHERE type = 'index' AND name = ?").get(t);if(!n)return null;let r=e.prepare(`PRAGMA index_info('${t.replaceAll("'","''")}')`).all().map(a=>a.name);return{table:n.tbl_name,sql:n.sql,columns:r}}import{createHash as Jo}from"crypto";import{existsSync as Ft,readdirSync as zo}from"fs";import{dirname as kt,join as Xe,relative as Xo,resolve as Dt,sep as ti}from"path";function ni(e,t){let n=t.includes("."),r={};for(let i of t)r[i]=[];let a=[];for(let i of e){let o=oi(i.path,t);o?r[o].push(i):n?r["."].push(i):a.push(i)}return{files:r,shared:a}}function ri(e,t){let n=new Map;for(let a of e){let i=t[a]?.packageName;i&&n.set(i,a)}let r=new Map;for(let a of e)r.set(a,new Set);for(let a of e){let i=t[a],o=r.get(a);if(!i||i.parseFailed){for(let s of e)s!==a&&o.add(s);continue}for(let s of i.dependencyNames){let c=n.get(s);c&&c!==a&&o.add(c)}for(let s of[...i.pathsTargets,...i.referencesPaths]){let c=oi(s,e);c&&c!==a&&o.add(c)}}return Yo(e,r)}function ii(e,t,n){let r={};for(let a of e){let i=new Map;for(let o of t.files[a]??[])i.set(o.path,o);for(let o of n[a]??[])for(let s of t.files[o]??[])i.set(s.path,s);for(let o of t.shared)i.set(o.path,o);r[a]={files:[...i.values()].sort((o,s)=>o.path.localeCompare(s.path))}}return r}function Mt(e){if(e===".")return"root";let t=Jo("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function ai(e,t){let n=Dt(e),r={};for(let a of t)r[a]=Qo(n,a);return r}function oi(e,t){let n;for(let r of t)r!=="."&&(e===r||e.startsWith(`${r}/`))&&(!n||r.length>n.length)&&(n=r);return n}function Yo(e,t){let n={};for(let r of e){let a=new Set,i=[...t.get(r)??[]];for(;i.length>0;){let o=i.pop();if(!(o===r||a.has(o))){a.add(o);for(let s of t.get(o)??[])s!==r&&!a.has(s)&&i.push(s)}}n[r]=[...a].sort((o,s)=>o.localeCompare(s))}return n}function Qo(e,t){let n=t==="."?e:Xe(e,t),r=Ko(n),a=Vo(n),i=a?Zo(a,e):{pathsTargets:[],referencesPaths:[],failed:!1};return{packageName:r.name,dependencyNames:r.dependencyNames,pathsTargets:i.pathsTargets,referencesPaths:i.referencesPaths,parseFailed:r.failed||i.failed}}function Ko(e){let t=Xe(e,"package.json");if(!Ft(t))return{name:void 0,dependencyNames:[],failed:!1};let n=Nt(t);if(!n.ok)return{name:void 0,dependencyNames:[],failed:!0};let r=typeof n.value.name=="string"?n.value.name:void 0,a=new Set;for(let i of["dependencies","devDependencies","peerDependencies"]){let o=n.value[i];if(o&&typeof o=="object"&&!Array.isArray(o))for(let s of Object.keys(o))a.add(s)}return{name:r,dependencyNames:[...a],failed:!1}}function Vo(e){let t=Xe(e,"tsconfig.json");if(Ft(t))return t;let n;try{n=zo(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,a)=>r.localeCompare(a)),n.length>0?Xe(e,n[0]):void 0}function Zo(e,t){let n=Nt(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=es(n.value,e,t),a=si(e,n.value,t,0);return{pathsTargets:a.pathsTargets,referencesPaths:r,failed:a.failed}}function es(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let a=kt(t),i=new Set;for(let o of r){if(!o||typeof o!="object")continue;let s=o.path;if(typeof s!="string"||s.trim()==="")continue;let c=ci(s,a,n);c&&i.add(c)}return[...i]}function si(e,t,n,r){let a=ts(t);if(a)return{pathsTargets:ns(a,kt(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let i=rs(t.extends,e,n);if(!i)return{pathsTargets:[],failed:!1};let o=Nt(i);return o.ok?si(i,o.value,n,r+1):{pathsTargets:[],failed:!0}}function ts(e){let t=e.compilerOptions;if(!t||typeof t!="object"||Array.isArray(t))return;let n=t.paths;return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function ns(e,t,n){let r=new Set;for(let a of Object.values(e))if(Array.isArray(a))for(let i of a){if(typeof i!="string")continue;let o=ci(i,t,n);o&&r.add(o)}return[...r]}function rs(e,t,n){let r=Array.isArray(e)?e.at(-1):e;if(typeof r!="string"||r.trim()===""||!r.startsWith(".")&&!r.startsWith("/"))return;let a=Dt(kt(t),r);if(a.endsWith(".json")||(a=`${a}.json`),!a.split(ti).includes("node_modules")&&pt(n,a)&&Ft(a))return a}function ci(e,t,n){let r=e.replace(/\/?\*+$/,""),a=Dt(t,r===""?".":r);if(!pt(n,a))return;let o=Xo(n,a).split(ti).join("/");return o===""?".":o}function is(e){let t="",n=0,r=!1,a=e.length;for(;n<a;){let i=e[n];if(r){if(t+=i,i==="\\"&&n+1<a){t+=e[n+1],n+=2;continue}i==='"'&&(r=!1),n+=1;continue}if(i==='"'){r=!0,t+=i,n+=1;continue}if(i==="/"&&e[n+1]==="/"){for(n+=2;n<a&&e[n]!==`
246
- `;)n+=1;continue}if(i==="/"&&e[n+1]==="*"){for(n+=2;n<a&&!(e[n]==="*"&&e[n+1]==="/");)n+=1;n+=2;continue}t+=i,n+=1}return t}function Nt(e){try{let t=ge(e,{maxBytes:an,inputKind:"TypeScript project manifest"}),n=JSON.parse(is(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import as from"better-sqlite3";import{zstdCompressSync as os}from"zlib";import{setImmediate as di}from"timers/promises";var J=class extends Error{},ss=200,At=2,li=1,cs=2,ds=3,ls=4,us=5,ps=6,mi=1,hi=2,yi=3,gs=7,fs=1,ms=3,hs=5,ys=6,Ss=8,bs=1,ui=64,Ps=[`CREATE TABLE documents (
294
+ ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[u,d]of Object.entries({documents:i,chunks:a,definitions:o,mentions:s}))for(let p of d){let m=JSON.stringify([u,p]),f=c.get(p.relative_path)??[];f.push(m),c.set(p.relative_path,f)}let l=new Map;for(let[u,d]of[...c].sort(([p],[m])=>p.localeCompare(m))){let p=$p("sha256");for(let m of d.sort())p.update(m).update(`
295
+ `);l.set(u,p.digest("hex"))}return l}function le(e,t){return e.prepare(t).get().value}import am from"better-sqlite3";var yn="idx_mentions_definitions",om=["symbol_id","chunk_id"];function Er(e,t={}){let n=new am(e),r=[],i=[],a=[];try{return n.transaction(()=>{sm(n,r),bn(n,"idx_global_symbols_symbol")?.join("\0")==="symbol"&&Is(n,"global_symbols").some(c=>c.name!=="idx_global_symbols_symbol"&&c.unique&&c.columns.join("\0")==="symbol")?(n.exec('DROP INDEX "idx_global_symbols_symbol"'),i.push("idx_global_symbols_symbol")):bn(n,"idx_global_symbols_symbol")&&a.push("idx_global_symbols_symbol");let o=bn(n,"idx_chunks_doc_id"),s=Is(n,"chunks").some(c=>c.name!=="idx_chunks_doc_id"&&c.columns.length>1&&c.columns[0]==="document_id");o?.join("\0")==="document_id"&&s?(n.exec('DROP INDEX "idx_chunks_doc_id"'),i.push("idx_chunks_doc_id")):o&&a.push("idx_chunks_doc_id"),t.analyze!==!1&&n.exec("ANALYZE")})(),{added:r,removed:i,retained:a,analyzed:t.analyze!==!1}}catch(o){if(o.code==="SQLITE_NOTADB")return{added:[],removed:[],retained:[],analyzed:!1,skippedReason:"not-a-sqlite-database"};throw o}finally{n.close()}}function sm(e,t){let n=Es(e,yn);if(n){let r=n.columns.join("\0")===om.join("\0"),i=/\bWHERE\s+role\s*=\s*1\b/iu.test(n.sql??"");if(!r||!i||n.table!=="mentions")throw new Error(`${yn} exists with an incompatible definition`);return}e.exec(`CREATE INDEX "${yn}" ON mentions(symbol_id, chunk_id) WHERE role = 1`),t.push(yn)}function Is(e,t){return e.prepare(`PRAGMA index_list('${t.replaceAll("'","''")}')`).all().map(n=>({name:n.name,unique:n.unique===1,columns:bn(e,n.name)??[]}))}function bn(e,t){return Es(e,t)?.columns??null}function Es(e,t){let n=e.prepare("SELECT tbl_name, sql FROM sqlite_master WHERE type = 'index' AND name = ?").get(t);if(!n)return null;let r=e.prepare(`PRAGMA index_info('${t.replaceAll("'","''")}')`).all().map(i=>i.name);return{table:n.tbl_name,sql:n.sql,columns:r}}import{createHash as cm}from"crypto";import{existsSync as Cr,readdirSync as lm}from"fs";import{dirname as Tr,join as Sn,relative as um,resolve as wr,sep as Cs}from"path";function Ts(e,t){let n=t.includes("."),r={};for(let a of t)r[a]=[];let i=[];for(let a of e){let o=Ns(a.path,t);o?r[o].push(a):n?r["."].push(a):i.push(a)}return{files:r,shared:i}}function ws(e,t){let n=new Map;for(let i of e){let a=t[i]?.packageName;a&&n.set(a,i)}let r=new Map;for(let i of e)r.set(i,new Set);for(let i of e){let a=t[i],o=r.get(i);dm(i,e,a,n,o)}return mm(e,r)}function dm(e,t,n,r,i){if(!n||n.parseFailed){for(let a of t)a!==e&&i.add(a);return}for(let a of n.dependencyNames){let o=r.get(a);o&&o!==e&&i.add(o)}pm(e,t,n,i)}function pm(e,t,n,r){for(let i of[...n.pathsTargets,...n.referencesPaths]){let a=Ns(i,t);a&&a!==e&&r.add(a)}}function Fs(e,t,n){let r={};for(let i of e){let a=new Map;for(let o of t.files[i]??[])a.set(o.path,o);for(let o of n[i]??[])for(let s of t.files[o]??[])a.set(s.path,s);for(let o of t.shared)a.set(o.path,o);r[i]={files:[...a.values()].sort((o,s)=>o.path.localeCompare(s.path))}}return r}function Fr(e){if(e===".")return"root";let t=cm("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function _s(e,t){let n=wr(e),r={};for(let i of t)r[i]=fm(n,i);return r}function Ns(e,t){let n;for(let r of t)r!=="."&&(e===r||e.startsWith(`${r}/`))&&(!n||r.length>n.length)&&(n=r);return n}function mm(e,t){let n={};for(let r of e){let i=new Set,a=[...t.get(r)??[]];for(;a.length>0;){let o=a.pop();if(!(o===r||i.has(o))){i.add(o);for(let s of t.get(o)??[])s!==r&&!i.has(s)&&a.push(s)}}n[r]=[...i].sort((o,s)=>o.localeCompare(s))}return n}function fm(e,t){let n=t==="."?e:Sn(e,t),r=gm(n),i=hm(n),a=i?ym(i,e):{pathsTargets:[],referencesPaths:[],failed:!1};return{packageName:r.name,dependencyNames:r.dependencyNames,pathsTargets:a.pathsTargets,referencesPaths:a.referencesPaths,parseFailed:r.failed||a.failed}}function gm(e){let t=Sn(e,"package.json");if(!Cr(t))return{name:void 0,dependencyNames:[],failed:!1};let n=_r(t);if(!n.ok)return{name:void 0,dependencyNames:[],failed:!0};let r=typeof n.value.name=="string"?n.value.name:void 0,i=new Set;for(let a of["dependencies","devDependencies","peerDependencies"]){let o=n.value[a];if(o&&typeof o=="object"&&!Array.isArray(o))for(let s of Object.keys(o))i.add(s)}return{name:r,dependencyNames:[...i],failed:!1}}function hm(e){let t=Sn(e,"tsconfig.json");if(Cr(t))return t;let n;try{n=lm(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?Sn(e,n[0]):void 0}function ym(e,t){let n=_r(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=bm(n.value,e,t),i=Os(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function bm(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=Tr(t),a=new Set;for(let o of r){if(!o||typeof o!="object")continue;let s=o.path;if(typeof s!="string"||s.trim()==="")continue;let c=Ds(s,i,n);c&&a.add(c)}return[...a]}function Os(e,t,n,r){let i=Sm(t);if(i)return{pathsTargets:vm(i,Tr(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let a=xm(t.extends,e,n);if(!a)return{pathsTargets:[],failed:!1};let o=_r(a);return o.ok?Os(a,o.value,n,r+1):{pathsTargets:[],failed:!0}}function Sm(e){let t=e.compilerOptions;if(!t||typeof t!="object"||Array.isArray(t))return;let n=t.paths;return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function vm(e,t,n){let r=new Set;for(let i of Object.values(e))if(Array.isArray(i))for(let a of i){if(typeof a!="string")continue;let o=Ds(a,t,n);o&&r.add(o)}return[...r]}function xm(e,t,n){let r=Array.isArray(e)?e.at(-1):e;if(typeof r!="string"||r.trim()===""||!r.startsWith(".")&&!r.startsWith("/"))return;let i=wr(Tr(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(Cs).includes("node_modules")&&On(n,i)&&Cr(i))return i}function Ds(e,t,n){let r=e.replace(/\/?\*+$/,""),i=wr(t,r===""?".":r);if(!On(n,i))return;let o=um(n,i).split(Cs).join("/");return o===""?".":o}function Rm(e){let t="",n=0,r=!1,i=e.length;for(;n<i;){let a=e[n];if(r){t+=a;let o=Pm(e,n);t+=e.slice(n+1,o),a==='"'&&(r=!1),n=o;continue}if(a==='"'){r=!0,t+=a,n+=1;continue}if(a==="/"&&e[n+1]==="/"){n=Im(e,n+2);continue}if(a==="/"&&e[n+1]==="*"){n=Em(e,n+2);continue}t+=a,n+=1}return t}function Pm(e,t){return e[t]==="\\"&&t+1<e.length?t+2:t+1}function Im(e,t){for(;t<e.length&&e[t]!==`
296
+ `;)t+=1;return t}function Em(e,t){for(;t<e.length&&!(e[t]==="*"&&e[t+1]==="/");)t+=1;return t+2}function _r(e){try{let t=Ge(e,{maxBytes:ei,inputKind:"TypeScript project manifest"}),n=JSON.parse(Rm(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import Cm from"better-sqlite3";import{zstdCompressSync as Tm}from"zlib";import{setImmediate as wm}from"timers/promises";var ue=class extends Error{},Fm=200,Ms=2,js=1,_m=2,Nm=3,Om=4,Dm=5,km=6,Bs=1,$s=2,Us=3,Lm=7,Am=1,Mm=3,jm=5,Bm=6,$m=8,Um=1,Gm=64,Hm=[`CREATE TABLE documents (
247
297
  id INTEGER PRIMARY KEY,
248
298
  language TEXT,
249
299
  relative_path TEXT NOT NULL UNIQUE,
@@ -283,17 +333,17 @@ import{a as Ce,b as xn,c as En,d as In,e as vn,f as _n,g as Tn,h as wn}from"./ch
283
333
  end_char INTEGER NOT NULL,
284
334
  FOREIGN KEY (document_id) REFERENCES documents(id),
285
335
  FOREIGN KEY (symbol_id) REFERENCES global_symbols(id)
286
- )`],Rs=["CREATE INDEX idx_chunks_line_range ON chunks(document_id, start_line, end_line)","CREATE INDEX idx_mentions_symbol_id_role ON mentions(symbol_id, role)","CREATE INDEX idx_defn_enclosing_ranges_symbol_id ON defn_enclosing_ranges(symbol_id)","CREATE INDEX idx_defn_enclosing_ranges_document ON defn_enclosing_ranges(document_id, start_line, end_line)","CREATE INDEX idx_chunks_doc_id ON chunks(document_id)","CREATE INDEX idx_global_symbols_symbol ON global_symbols(symbol)"];function Lt(e){return e.startsWith("local ")}function pi(e,t,n,r){let a=t,i=0,o=0;for(;a<n;){let s=e[a];a+=1,o<53&&(i+=(s&127)*2**o),(s&128)===0?(r.push(i),i=0,o=0):o+=7}}function gi(e){return e.length===3?[e[0],e[1],e[0],e[2]]:e.length===4?[e[0],e[1],e[2],e[3]]:null}function xs(e,t){return e.startLine!==t.startLine?e.startLine-t.startLine:e.startChar!==t.startChar?e.startChar-t.startChar:e.endLine!==t.endLine?e.endLine-t.endLine:e.endChar!==t.endChar?e.endChar-t.endChar:e.symbol<t.symbol?-1:e.symbol>t.symbol?1:0}function Es(e,t,n,r){let a=[],i=[],o="",s=0;for(let d of Y(e,n,r))d.fieldNumber===mi?d.wireType===2?pi(e,d.valueStart,d.valueEnd,a):d.wireType===0&&a.push(d.varint):d.fieldNumber===hi&&d.wireType===2?o=pe.decode(e.subarray(d.valueStart,d.valueEnd)):d.fieldNumber===yi&&d.wireType===0?s=d.varint:d.fieldNumber===gs&&(d.wireType===2?pi(e,d.valueStart,d.valueEnd,i):d.wireType===0&&i.push(d.varint));let c=gi(a);return c?{startLine:c[0],startChar:c[1],endLine:c[2],endChar:c[3],symbol:o,roles:s,frameStart:t,frameEnd:r,merged:!1,enclosing:gi(i)}:null}function Is(e,t,n){let r={symbol:"",displayName:null,kind:null,documentation:[],enclosingSymbol:null};for(let a of Y(e,t,n))if(a.wireType===2){let i=()=>pe.decode(e.subarray(a.valueStart,a.valueEnd));a.fieldNumber===fs?r.symbol=i():a.fieldNumber===ms?r.documentation.push(i()):a.fieldNumber===ys?r.displayName=i():a.fieldNumber===Ss&&(r.enclosingSymbol=i())}else a.fieldNumber===hs&&a.wireType===0&&(r.kind=a.varint);return r}var pe=new TextDecoder;function vs(e,t){if(e.length===0)return[];let n=[],r=Math.min(e.length,t);for(let a=0;a<r&&r<=e.length;){for(;r<=e.length-1&&e[r-1].startLine===e[r].startLine;)r+=1;n.push(e.slice(a,r)),a=r,r=Math.min(e.length,r+t)}return n}function _s(e){let t=e.startLine===e.endLine?[e.startLine,e.startChar,e.endChar]:[e.startLine,e.startChar,e.endLine,e.endChar],n=[],r=Buffer.concat(t.map(o=>Q(o)));n.push(Le(mi),Q(r.length),r);let a=Buffer.from(e.symbol,"utf8");n.push(Le(hi),Q(a.length),a),e.roles!==0&&n.push(Q(yi*8),Q(e.roles));let i=Buffer.concat(n);return Buffer.concat([Le(At),Q(i.length),i])}function Ts(e,t){let n=[];for(let r of t)r.merged?n.push(_s(r)):n.push(e.subarray(r.frameStart,r.frameEnd));return os(Buffer.concat(n))}async function Si(e,t,n={}){let r=n.chunkSize??ss,a={documents:0,duplicateDocumentsSkipped:0,occurrences:0,illegalOccurrencesDropped:0,mergedOccurrences:0,chunks:0,mentions:0,globalSymbols:0,enclosingRanges:0},i=new as(t);try{i.pragma("synchronous = normal"),i.pragma("temp_store = memory"),i.pragma("foreign_keys = ON"),i.pragma("journal_mode = WAL");for(let v of Ps)i.exec(v);let o=i.prepare("INSERT INTO documents (id, language, relative_path, position_encoding, text) VALUES (?, ?, ?, ?, ?)"),s=i.prepare("INSERT INTO chunks (id, document_id, chunk_index, start_line, end_line, occurrences) VALUES (?, ?, ?, ?, ?, ?)"),c=i.prepare("INSERT INTO defn_enclosing_ranges (document_id, symbol_id, start_line, start_char, end_line, end_char) VALUES (?, ?, ?, ?, ?, ?)"),d=i.prepare("INSERT INTO global_symbols (id, symbol, display_name, kind, documentation, enclosing_symbol) VALUES (?, ?, ?, ?, ?, ?)"),l=i.prepare("INSERT INTO mentions (chunk_id, symbol_id, role) VALUES (?, ?, ?)"),g=new Map,p=new Map,f=1,R=1,T=1,j=(v,F,_,h,y)=>{let m=T;return T+=1,p.set(v,m),d.run(m,v,F,_,h,y),a.globalSymbols+=1,m};i.exec("BEGIN IMMEDIATE");let D=!1;try{let v=0;for(let _ of Y(e)){if(_.fieldNumber!==At||_.wireType!==2)continue;fi(n.signal),v+=1,v>=ui&&(v=0,await di());let h="",y=null,m=null,w=null,S=[];for(let u of Y(e,_.valueStart,_.valueEnd))u.wireType===2?u.fieldNumber===li?h=pe.decode(e.subarray(u.valueStart,u.valueEnd)):u.fieldNumber===ds?S.push(Is(e,u.valueStart,u.valueEnd)):u.fieldNumber===ls?y=pe.decode(e.subarray(u.valueStart,u.valueEnd)):u.fieldNumber===us&&(m=pe.decode(e.subarray(u.valueStart,u.valueEnd))):u.fieldNumber===ps&&u.wireType===0&&(w=ws(u.varint));if(h==="")throw new J("relative path must not be empty");if(g.has(h)){a.duplicateDocumentsSkipped+=1;continue}let P=f;f+=1,o.run(P,y===""?null:y,h,w,m===""?null:m),g.set(h,P),a.documents+=1;let I=new Map;for(let u of S){if(u.symbol==="")throw new J(`empty symbol in SymbolInformation for document ${h}`);let b=I.get(u.symbol);if(!b){I.set(u.symbol,u);continue}for(let k of u.documentation)b.documentation.includes(k)||b.documentation.push(k)}for(let u of[...I.values()].sort((b,k)=>b.symbol<k.symbol?-1:b.symbol>k.symbol?1:0))Lt(u.symbol)||p.has(u.symbol)||j(u.symbol,u.displayName===""?null:u.displayName,u.kind===0?null:u.kind,u.documentation.length===0?null:u.documentation.join(`
287
- `),u.enclosingSymbol===""?null:u.enclosingSymbol)}let F=new Set;v=0;for(let _ of Y(e)){if(_.fieldNumber!==At||_.wireType!==2)continue;fi(n.signal),v+=1,v>=ui&&(v=0,await di());let h="",y=[];for(let S of Y(e,_.valueStart,_.valueEnd))if(S.wireType===2){if(S.fieldNumber===li)h=pe.decode(e.subarray(S.valueStart,S.valueEnd));else if(S.fieldNumber===cs){let P=Es(e,S.fieldStart,S.valueStart,S.valueEnd);P?y.push(P):a.illegalOccurrencesDropped+=1}}if(F.has(h))continue;F.add(h);let m=g.get(h);if(m===void 0)continue;y.sort(xs);let w=[];for(let S of y){let P=w[w.length-1];if(P&&P.startLine===S.startLine&&P.startChar===S.startChar&&P.endLine===S.endLine&&P.endChar===S.endChar&&P.symbol===S.symbol){P.roles|=S.roles,P.merged=!0,a.mergedOccurrences+=1;continue}w.push(S)}a.occurrences+=w.length;for(let S of w){if((S.roles&bs)===0||Lt(S.symbol)||!S.enclosing)continue;let[P,I,u,b]=S.enclosing;if(P<0||I<0||u<P||u===P&&b<I)throw new J(`bad enclosing range for symbol ${S.symbol} in ${h}`);let k=p.get(S.symbol);if(k===void 0)throw new J(`symbol ${S.symbol} has definition occurrence, but no SymbolInformation`);c.run(m,k,P,I,u,b),a.enclosingRanges+=1}for(let[S,P]of vs(w,r).entries()){let I=R;R+=1,s.run(I,m,S,P[0].startLine,P[P.length-1].startLine,Ts(e,P)),a.chunks+=1;let u=new Map;for(let b of P){if(Lt(b.symbol))continue;let k=u.get(b.symbol);k||u.set(b.symbol,k=new Set),k.add(b.roles),p.has(b.symbol)||j(b.symbol,null,null,null,null)}for(let[b,k]of u){let B=p.get(b);for(let dt of k)l.run(I,B,dt),a.mentions+=1}}}i.exec("COMMIT"),D=!0}finally{if(!D)try{i.exec("ROLLBACK")}catch{}}i.exec("BEGIN IMMEDIATE");for(let v of Rs)i.exec(v);i.exec("COMMIT"),i.pragma("wal_checkpoint(TRUNCATE)")}finally{i.close()}return a}function ws(e){if(e===0)return null;if(e===1)return"UTF-8";if(e===2)return"UTF-16";if(e===3)return"UTF-32";throw new J(`unknown position encoding ${e}`)}function fi(e){if(e?.aborted)throw new J("SCIP SQLite conversion aborted")}import{readdirSync as Cs,rmSync as js}from"fs";import{cpus as Os,totalmem as Fs}from"os";import{join as Ye}from"path";var ks=2048,Ds=6*1024**3,Ms=4;function $t(e=process.env){let t=Number.parseInt(e.SCIP_QUERY_TS_COMPILER_SHARD_FILES??"",10);return Number.isSafeInteger(t)&&t>0?t:ks}function Pi(e,t){return e>Math.floor(t*1.5)}var Ns=1.25;function Ri(e,t,n){if(!Number.isSafeInteger(t)||t<1)throw new Error(`TypeScript compiler shard targetFiles must be a positive safe integer; received ${t}.`);let r=Math.max(1,Math.ceil(e/t));if(r<=1||n<=1)return r;let a=Math.floor(t*Ns),i=new Set([r,n*Math.floor(r/n),n*Math.ceil(r/n)]),o=c=>Math.ceil(c/n)*Math.ceil(e/c),s=r;for(let c of i)c<1||Math.ceil(e/c)>a||(o(c)<o(s)||o(c)===o(s)&&c<s)&&(s=c);return s}function Ls(e,t,n=()=>1){if(!Number.isSafeInteger(t)||t<1)throw new Error(`TypeScript compiler shard count must be a positive safe integer; received ${t}.`);let r=[...new Set(e)].sort((d,l)=>d.localeCompare(l));if(t===1||r.length<=t)return r.length<=t&&t>1?r.map(d=>[d]):r.length>0?[r]:[];let a=r.map(d=>Math.max(1,n(d))),i=a.reduce((d,l)=>d+l,0),o=[],s=[],c=0;for(let d=0;d<r.length;d+=1){s.push(r[d]),c+=a[d];let l=t-o.length-1,g=r.length-d-1;l>0&&g>=l&&(c>=i*(o.length+1)/t||g===l)&&(o.push(s),s=[])}return s.length>0&&o.push(s),o}function xi(e){let t=e.targetFiles??$t(),n=e.shardCount??Math.max(1,Math.ceil(new Set(e.inputPaths).size/Math.max(1,t)));return Ls(e.inputPaths,n,e.weightOf).map((r,a)=>{let i=Ye(e.projectRoot,jn(a)),o=`${JSON.stringify({extends:`./${e.rootConfigPath}`,compilerOptions:{incremental:!1},files:r.map(s=>`./${s}`),include:[],exclude:[]},null,2)}
288
- `;return{configPath:i,content:o,inputPaths:r}})}var Ei="typescript-shard-costs.json",bi=4;function Ii(e){let t;try{t=JSON.parse(on(Ye(e,Ei),"shard cost model"))}catch{return null}if(typeof t!="object"||t===null||t.version!==1)return null;let n=t.samples;return Array.isArray(n)&&n.every(a=>typeof a=="object"&&a!==null&&typeof a.firstPath=="string"&&typeof a.lastPath=="string"&&Number.isFinite(a.totalBytes)&&a.totalBytes>0&&Number.isFinite(a.durationMs)&&a.durationMs>0)?{version:1,samples:n}:null}function vi(e,t){Fe(Ye(e,Ei),t)}function _i(e){let t=(e?.samples??[]).filter(i=>i.totalBytes>0&&i.durationMs>0);if(t.length<2)return(i,o)=>o;let n=t.map(i=>i.durationMs/i.totalBytes).sort((i,o)=>i-o),r=n[Math.floor(n.length/2)];if(!(r>0))return(i,o)=>o;let a=[...t].sort((i,o)=>i.firstPath.localeCompare(o.firstPath));return(i,o)=>{for(let s of a){if(i.localeCompare(s.firstPath)<0)break;if(i.localeCompare(s.lastPath)>0)continue;let c=s.durationMs/s.totalBytes/r;return o*Math.min(bi,Math.max(1/bi,c))}return o}}function Ti(e,t){let n=[];for(let r of e){let a=r.inputPaths[0],i=r.inputPaths[r.inputPaths.length-1];if(a===void 0||i===void 0||!(r.durationMs>0))return null;let o=r.inputPaths.reduce((s,c)=>s+Math.max(1,t(c)),0);n.push({firstPath:a,lastPath:i,totalBytes:o,durationMs:r.durationMs})}return n.length>0?{version:1,samples:n}:null}function wi(e=process.env,t={totalmemBytes:Fs(),cpuCount:Os().length}){let n=Number.parseInt(e.SCIP_QUERY_TS_COMPILER_SHARD_CONCURRENCY??"",10);if(Number.isSafeInteger(n)&&n>0)return n;let r=Math.floor(t.totalmemBytes/2/Ds),a=Math.floor(t.cpuCount/2);return Math.max(1,Math.min(Ms,r,a))}function Ci(e){let t;try{t=Cs(e)}catch{return}for(let n of t)if(On(n))try{js(Ye(e,n))}catch{}}import{createHash as qt}from"crypto";import{existsSync as Ut,writeFileSync as Li}from"fs";import{join as zs}from"path";import{randomUUID as As}from"crypto";import{existsSync as ji,rmSync as Gt}from"fs";import{join as $s}from"path";var Gs=12e4,Bs=5,be=class extends Error{name="TypeScriptIndexMemoryPressureError"},Qe=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;mailboxLimits;emitLocally;requireService;localHost=null;constructor(t,n={}){this.projectRoot=Cn(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??Hs(),this.runtime=n.runtime??Js,this.mailboxLimits=n.mailboxLimits??{},this.emitLocally=n.emitLocally,this.requireService=n.requireService===!0}request(t){let n=wr(this.cacheDir),r=vr(this.cacheDir),a=Rt(n.statePath);if(!Oi(a,this.projectRoot,this.runtime))return this.requestLocally(t);let i=this.runtime.now(),o=i+this.timeoutMs,s=(this.runtime.monotonicNow??C)()+this.timeoutMs,c=xr("typescript-index-v5",{baseGeneration:this.baseGeneration,request:t}),d=Er(c),l=Ir(r,{mailboxVersion:Rr,operationKey:c,clientId:this.runtime.randomId(),enqueuedAtMs:i,deadlineAtMs:o,protocolVersion:qe,id:d,baseGeneration:this.baseGeneration,request:t},{nowMs:i,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??C)()<=s;){if(ji(l.responsePath))try{return Fi(ge(l.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),d,c,this.baseGeneration,t.producerIdentity,t.affectedFiles)}finally{Gt(l.responsePath,{force:!0})}let g=Rt(n.statePath);if(!Oi(g,this.projectRoot,this.runtime))return this.abandonPendingRequest(r,d),this.requestLocally(t);this.runtime.sleep(Bs)}if(ji(l.responsePath))try{return Fi(ge(l.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),d,c,this.baseGeneration,t.producerIdentity,t.affectedFiles)}finally{Gt(l.responsePath,{force:!0})}return this.abandonPendingRequest(r,d),this.requestLocally(t)}abandonPendingRequest(t,n){try{Gt($s(t.pendingDir,`${n}.json`),{force:!0})}catch{}}requestLocally(t){if(this.requireService)throw new Error("TypeScript incremental index service unavailable; refusing to load the whole compiler graph inside the reindex process");return this.emitLocally?Bt(this.emitLocally(t),t.producerIdentity,t.affectedFiles):(this.localHost??=new Cr({projectRoot:this.projectRoot,currentGeneration:()=>this.baseGeneration}),Bt(ki(this.localHost.handle(this.baseGeneration,t),t.producerIdentity),t.producerIdentity,t.affectedFiles))}};function Oi(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null,a=e?Date.parse(e.heartbeatAt):Number.NaN;return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===qe&&n.isProcessAlive(e.pid)&&Number.isFinite(a)&&n.now()-a<=Tr&&(!e.processIdentity||r!=null&&z(e.processIdentity,r))}function Fi(e,t,n,r,a,i){let o=JSON.parse(e);if(o.protocolVersion!==qe||o.id!==t||o.operationKey!==n||o.ok===!0&&o.baseGeneration!==r)throw new Error("TypeScript index service wrote an incompatible response.");if(o.ok!==!0){let s=typeof o.error=="string"?o.error:"TypeScript index service request failed.";throw Us(s)?new be(s):new Error(s)}return Bt(ki(o.response,a),a,i)}function Us(e){let t=e.toLowerCase();return t.includes("out of memory")||t.includes("memory limit")||t.includes("allocation failed")||t.includes("err_worker_out_of_memory")}function Bt(e,t,n){if(e.producerIdentity!==t)throw new Error("TypeScript index service wrote an invalid response.");let r=[...new Set(n)].sort(),a=e.fragments.map(i=>i.relativePath).sort();if(JSON.stringify(a)!==JSON.stringify(r))throw new Error("TypeScript index service omitted or added an affected document.");return e}function ki(e,t){if(!e||typeof e!="object")throw new Error("TypeScript index service wrote an invalid response.");let n=e;if(n.producerIdentity!==t||typeof n.cold!="boolean"||typeof n.durationMs!="number"||!Number.isFinite(n.durationMs)||!Array.isArray(n.fragments))throw new Error("TypeScript index service wrote an invalid response.");let r=new Set,a=n.fragments.map(i=>{if(!i||typeof i.relativePath!="string"||i.bytesBase64!==null&&typeof i.bytesBase64!="string"||typeof i.occurrences!="number"||!Number.isInteger(i.occurrences)||i.occurrences<0||typeof i.symbols!="number"||!Number.isInteger(i.symbols)||i.symbols<0||!Array.isArray(i.referenceFragments)||!i.referenceFragments.every(qs)||r.has(i.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(i.relativePath);let o=i.bytesBase64===null?null:Ws(i.bytesBase64);return{relativePath:i.relativePath,bytes:o,occurrences:i.occurrences,symbols:i.symbols,referenceFragments:i.referenceFragments}});return{producerIdentity:n.producerIdentity,cold:n.cold,durationMs:n.durationMs,fragments:a}}function qs(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.targetSymbol=="string"&&!!t.location&&typeof t.location.file=="string"&&Number.isInteger(t.location.line)&&Number.isInteger(t.location.column)}function Ws(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function Hs(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Gs}var Js={now:Date.now,monotonicNow:C,randomId:As,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:oe,readProcessIdentity:U};var Xs=128,Ys=256;function Qs(e){let t=e.projectMode==="workspace"?e.workspaceProjects??[]:["."],n=se(t);if(t.length===0)return{eligible:!1,reason:"workspace project roots unavailable"};if(t.length===1&&t[0]==="."&&!e.rootTsconfigExists)return{eligible:!1,reason:"root tsconfig unavailable"};if(!e.previousSnapshot)return{eligible:!1,reason:"prior project snapshot unavailable"};if(e.graph===null)return{eligible:!1,reason:"dependency graph unavailable"};if(e.projectFiles.length===0)return{eligible:!1,reason:"prior TypeScript documents unavailable"};let r=q(e.previousSnapshot,e.currentSnapshot);if(r.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};let a=r.changes.filter(m=>m.inputKind==="source"&&ue(m.path)),i=Ai(r,n),o={...r,changes:i},s=a.filter(m=>m.kind==="added").map(m=>m.path),c=a.filter(m=>m.kind==="deleted").map(m=>m.path),d=a.filter(m=>m.kind==="modified"),l=Ve(e.currentSnapshot,e.producerIdentity,n),g=Ve(e.previousSnapshot,e.producerIdentity,n),p=$i(r,i,l,g),f=!p&&Bi(r);if(a.length===0&&!p)return{eligible:!1,reason:"change does not affect the configured TypeScript project"};let R=e.currentSnapshot.files.filter(m=>_e(m.path,e.currentSnapshot.languages)==="source"&&ue(m.path)).map(m=>m.path).sort(),T=new Set(R),j=p?e.projectFiles.filter(m=>!T.has(m)).sort():[...c].sort(),D=p?o:{...r,changes:a},v=p?{eligible:!0,plan:{...Se(o,e.graph,[...new Set([...R,...j])]),mode:"full-project"}}:Vs(d,s,j,e.graph,e.projectFiles);if(!v.eligible)return v;let F=v.plan,_=new Set(j),h=Zs(F,t,e.graph,_);if(!h)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let y=h.length===1?h[0]:void 0;return{eligible:!0,manifest:D,plan:F,projectIdentity:l,previousFragmentGeneration:Ni(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:Ni(e.currentSnapshot,e.producerIdentity),projects:h,deletedFiles:j,replaceProject:p,dependencyGraphUnchanged:f,...y?{tsconfigPath:y.tsconfigPath,projectArgument:y.projectArgument}:{}}}function Ai(e,t){return e.changes.filter(n=>n.inputKind==="source"&&ue(n.path)||n.inputKind==="config"&&(!ce(n.path)||t.has(n.path))&&Ks(n)||n.inputKind==="ambient")}function Ks(e){return e.kind!=="modified"||e.before.semanticHash===void 0||e.after.semanticHash===void 0||e.before.semanticHash!==e.after.semanticHash}function $i(e,t,n,r){return n!==r||e.projectIdentityChanged||e.uncertainty.length>0||t.length>Ys||t.some(a=>a.inputKind==="config"||a.inputKind==="ambient")}function Vs(e,t,n,r,a){if(e.length===0)return t.length===0&&n.length===0?{eligible:!1,reason:"empty affected set"}:{eligible:!0,plan:{mode:"closure",changedFiles:[...new Set([...t,...n])].sort(),affectedFiles:[...new Set([...t,...Di(n,r,a)])].sort(),reasons:[]}};let i=Se({version:1,changes:e.filter(Gi),projectIdentityChanged:!1,uncertainty:[]},r,a);return i.mode==="full-project"?{eligible:!1,reason:i.reasons.length>0?`affected set widened: ${i.reasons.join(", ")}`:"empty affected set"}:{eligible:!0,plan:{mode:"closure",changedFiles:[...new Set([...e.map(o=>o.path),...t,...n])].sort(),affectedFiles:[...new Set([...i.affectedFiles,...e.map(o=>o.path),...t,...Di(n,r,a)])].sort(),reasons:[]}}}function Gi(e){return e.kind!=="modified"?!0:e.before.semanticHash===void 0||e.after.semanticHash===void 0||e.before.semanticHash!==e.after.semanticHash}function Bi(e){let t=e.changes.filter(n=>n.inputKind==="source"&&ue(n.path));return t.length>0&&t.every(n=>n.kind==="modified"&&!Gi(n))}function Zs(e,t,n,r){let a=new Map;for(let o of e.affectedFiles){let s=ec(o,t);if(!s)return null;let c=a.get(s)??[];c.push(o),a.set(s,c)}let i=[];for(let[o,s]of[...a].sort(([c],[d])=>c.localeCompare(d))){let c=new Set(s),d=e.changedFiles.filter(p=>!r.has(p)&&(c.has(p)||s.some(f=>Mi(f,p,n)))),l=e.changedFiles.filter(p=>r.has(p)&&(c.has(p)||s.some(f=>Mi(f,p,n)))),g=s.filter(p=>!r.has(p));if(d.length===0&&l.length===0&&g.length===0)return null;i.push({projectArgument:o,tsconfigPath:o==="."?"tsconfig.json":`${o}/tsconfig.json`,modifiedFiles:d,removedFiles:l,affectedFiles:[...g].sort()})}return i}function Di(e,t,n){let r=new Set(n),a=new Map;for(let[s,c]of t)if(r.has(s))for(let d of c){let l=a.get(d)??new Set;l.add(s),a.set(d,l)}let i=new Set(e),o=[...e];for(let s=0;s<o.length;s+=1){let c=o[s];if(c)for(let d of a.get(c)??[])i.has(d)||(i.add(d),o.push(d))}return[...i].sort()}function ec(e,t){let n=t.filter(i=>i==="."||e===i||e.startsWith(`${i}/`));if(n.length===0)return null;let r=[...new Set(n)].sort((i,o)=>Ke(o)-Ke(i)||i.localeCompare(o)),a=r[0];return r[1]&&Ke(r[1])===Ke(a)?null:a}function Ke(e){return e==="."?0:e.split("/").filter(Boolean).length}function Mi(e,t,n){let r=new Set,a=[e];for(let i=0;i<a.length;i+=1){let o=a[i];if(!(!o||r.has(o))){r.add(o);for(let s of n.get(o)??[]){if(s===t)return!0;r.has(s)||a.push(s)}}}return!1}function Ui(e){let t=C();try{if(!Ut(e.previousDbPath)||!Ut(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=Pt();if(!r.available)throw new Error(r.reason);let a=performance.now()-n;n=performance.now();let i=new $({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),o=nc(e.projectRoot,e.previousSnapshot,e.currentSnapshot),s=e.projectMode==="workspace"?X(e.projectRoot,e.currentSnapshot.typescriptProjects):["."],c=se(s),d,l,g;try{d=ke(i,{includeIgnored:!1}).filter(ue).sort();let I=o?q(o,e.currentSnapshot):null,u=I&&o&&$i(I,Ai(I,c),Ve(e.currentSnapshot,r.producerIdentity,c),Ve(o,r.producerIdentity,c)),b=I!==null&&!u&&Bi(I);u?(g=Me(i,"none")??void 0,l=new Map):b?l=new Map:(g=De(i),l=g.graph)}finally{i.close()}let p=performance.now()-n,f=Qs({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?s:void 0,previousSnapshot:o,currentSnapshot:e.currentSnapshot,projectFiles:d,graph:l,producerIdentity:r.producerIdentity,rootTsconfigExists:Ut(zs(e.projectRoot,"tsconfig.json"))});if(!f.eligible)throw new Error(f.reason);let R=_r(e.previousDbPath);if(!R)throw new Error("published TypeScript base generation unavailable");n=performance.now();let T=new Qe({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:R},{requireService:!0}),j=f.projects.flatMap(I=>{let u=tc(I.affectedFiles,Xs);return(u.length>0?u:[[]]).map((k,B)=>({project:I,affectedFiles:k,removedFiles:B===0?I.removedFiles:[],firstForProject:B===0}))}),D=[],v=new Map,F=[],_=!1,h=0,y=0,m=0,w=f.previousFragmentGeneration;for(let[I,u]of j.entries()){let b=T.request({kind:"emit-documents",tsconfigPath:u.project.tsconfigPath,projectArgument:u.project.projectArgument,projectIdentity:f.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:u.firstForProject?u.project.modifiedFiles:[],removedFiles:u.firstForProject?u.project.removedFiles:[],affectedFiles:u.affectedFiles});_||=b.cold,F.push(b.durationMs);let k=u.removedFiles.map(xe=>({relativePath:xe,bytes:null,occurrences:0,symbols:0,referenceFragments:[]})),B=[...b.fragments,...k];if(!f.replaceProject)for(let xe of B)v.set(xe.relativePath,xe.referenceFragments);let dt=performance.now(),$a=cr(b.fragments);h+=performance.now()-dt;let nn=I===0?e.candidateAffectedScipPath:`${e.candidateAffectedScipPath}.batch-${I}.scip`,Ga=performance.now();Li(nn,$a),m+=performance.now()-Ga;let Ba=performance.now(),rn=I===j.length-1?f.nextFragmentGeneration:rc({previousGenerationIdentity:w,targetGenerationIdentity:f.nextFragmentGeneration,fragments:B});lr({cacheDir:e.cacheDir,previousGenerationIdentity:w,nextGenerationIdentity:rn,producerIdentity:r.producerIdentity,projectIdentity:f.projectIdentity,baseShardCurrent:I===0?e.baseShardCurrent:!1,fragments:B,allowProjectIdentityChange:f.replaceProject&&I===0,allowLegacyProjectIdentityMigration:!0}),y+=performance.now()-Ba,w=rn,D.push({scipPath:nn,affectedFiles:[...u.affectedFiles,...u.removedFiles].sort(),deletedFiles:[...u.removedFiles].sort()})}let S=performance.now()-n,P={scipPath:e.previousShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,affectedBatches:D,completeScipUpdated:!1,durationMs:C()-t,cold:_,changedFiles:f.plan.changedFiles,affectedFiles:f.plan.affectedFiles,deletedFiles:f.deletedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:f.previousFragmentGeneration,nextFragmentGeneration:f.nextFragmentGeneration,manifest:f.manifest,plan:f.plan,projectFileCount:d.length,dependencyGraphSnapshot:g,dependencyGraphUnchanged:f.dependencyGraphUnchanged,referenceFragmentsByFile:v,timings:{runtimeMs:a,graphMs:p,requestMs:S,serviceMs:F.reduce((I,u)=>I+u,0),assemblyMs:h,fragmentStoreMs:y,writeMs:m}};return e.onStatus(`${f.replaceProject?"Bounded TypeScript project refresh":"Incremental TypeScript index"} emitted ${P.affectedFiles.length-P.deletedFiles.length} document(s), removed ${P.deletedFiles.length}, and produced ${D.length} bounded batch(es) across ${f.projects.length} project(s) in ${(P.durationMs/1e3).toFixed(3)}s (${P.cold?"cold":"warm"} service; whole SCIP deferred; runtime ${a.toFixed(0)}ms, graph ${p.toFixed(0)}ms, request ${S.toFixed(0)}ms, assembly ${h.toFixed(0)}ms, fragments ${y.toFixed(0)}ms, write ${m.toFixed(0)}ms).`),P}catch(n){let r=n instanceof Error?n.message:String(n);if(e.onUnavailable?.(r),n instanceof be)throw e.onStatus(`Incremental TypeScript index stopped after memory pressure survived one cold Worker retry: ${r}. Preserving the accepted index instead of starting a memory-heavier whole-project rebuild.`),n;return e.onStatus(`Incremental TypeScript index unavailable: ${r}.`),null}}function tc(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function nc(e,t,n){if(!t)return null;let r=new Map(n.files.map(o=>[o.path,o])),a=!1,i=t.files.map(o=>{let s=r.get(o.path);if(o.semanticHash!==void 0||s?.semanticHash===void 0)return o;let c=we(e,o.path,o.hash);return c===void 0?o:(a=!0,{...o,semanticHash:c})});return a?{...t,files:i}:t}function rc(e){let t=qt("sha256");t.update("typescript-overlay-batch-v1\0"),t.update(e.previousGenerationIdentity),t.update("\0"),t.update(e.targetGenerationIdentity);for(let n of[...e.fragments].sort((r,a)=>r.relativePath.localeCompare(a.relativePath)))t.update("\0path\0"),t.update(n.relativePath),n.bytes===null?t.update("\0deleted"):(t.update("\0bytes\0"),t.update(qt("sha256").update(n.bytes).digest()));return t.digest("hex")}function Wt(e){let t=Pt();if(!t.available)throw new Error(t.reason);let n=ur({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:ie(e.baseShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:Ee}),packageVersion:t.packageVersion});Li(e.candidateShardPath,n)}function Ve(e,t,n){let r=e.files.filter(a=>{let i=_e(a.path,e.languages);return i==="ambient"||i==="config"&&(!ce(a.path)||n.has(a.path))}).map(a=>{let o=_e(a.path,e.languages)==="config"?a.semanticHash:void 0;return{path:a.path,size:o===void 0?a.size:0,hash:o??a.hash}}).sort((a,i)=>a.path.localeCompare(i.path));return`typescript-project-v3:${qi(JSON.stringify({version:3,producerIdentity:t,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),nonSourceInputs:r}))}`}function Ni(e,t){return qi(JSON.stringify({version:1,producerIdentity:t,snapshot:pn(e)}))}function qi(e){return qt("sha256").update(e).digest("hex")}import{closeSync as ic,existsSync as Ze,fstatSync as ac,lstatSync as oc,openSync as sc,renameSync as Jt,rmSync as Pe,statSync as cc,writeSync as dc}from"fs";import{cpus as lc}from"os";import{join as zt}from"path";var Wi=8*1024;function Hi(e,t,n){let r=Buffer.from(t,"utf8"),a=()=>sc(e,"wx",384),i;try{i=a()}catch(o){if(o.code!=="EEXIST")throw o;if(n==="skip")return null;Pe(e,{force:!0}),i=a()}try{dc(i,r);let o=ac(i);return{path:e,content:r,device:o.dev,inode:o.ino}}finally{ic(i)}}function uc(e,t){let n=[];try{if(e.temporaryRootConfigContent!==void 0){let r=Hi(zt(t,"tsconfig.json"),e.temporaryRootConfigContent,"skip");r&&n.push(r)}for(let r of e.temporaryProjectConfigs??[]){let a=Hi(r.path,r.content,"replace");a&&n.push(a)}return n}catch(r){for(let a of n.reverse())Xi(a);throw r}}function Xi(e){if(e)try{let t=oc(e.path);if(!t.isFile()||t.dev!==e.device||t.ino!==e.inode||t.size!==e.content.byteLength)return;let n;try{n=ie(e.path,{maxBytes:e.content.byteLength,inputKind:"temporary TypeScript index configuration"})}catch{return}if(!n.equals(e.content))return;Pe(e.path)}catch(t){if(t.code!=="ENOENT")throw t}}function pc(e,t,n){if(!e.defaultOutputPath)return;let r=zt(t,e.defaultOutputPath);n!==r&&Ze(r)&&Jt(r,n)}function gc(e,t,n){if(!e.defaultOutputPath)return null;let r=zt(t,e.defaultOutputPath);if(r===n)return null;let a=`${n}.default-output-backup`;return Pe(a,{force:!0}),Ze(r)?(Jt(r,a),{defaultOutputPath:r,backupPath:a}):{defaultOutputPath:r,backupPath:null}}function fc(e){e&&(Pe(e.defaultOutputPath,{force:!0}),e.backupPath&&Ze(e.backupPath)&&Jt(e.backupPath,e.defaultOutputPath))}function mc(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),r=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(8,Math.max(1,lc().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function Yi(e,t,n,r,a){A(a,"Reindex cancelled by its owner.");let i=e.filter(d=>d.config.defaultOutputPath),o=e.filter(d=>!d.config.defaultOutputPath&&d.boundedConcurrency!==void 0),s=e.filter(d=>!d.config.defaultOutputPath&&d.boundedConcurrency===void 0),c=[];if(c.push(...await Ji(s,mc(s.length,r),t,n,a)),o.length>0){let d=Math.max(1,Math.min(...o.map(l=>l.boundedConcurrency)));c.push(...await Ji(o,d,t,n,a))}for(let d of i)A(a,"Reindex cancelled by its owner."),c.push((await Ht(d,t,n,a)).result);return c.sort((d,l)=>e.findIndex(g=>g.id===d.id)-e.findIndex(g=>g.id===l.id))}async function Ji(e,t,n,r,a){let i=await jr(e,Math.max(1,t),s=>Ht(s,n,r,a));if(t<=1)return i.map(({result:s})=>s);let o=new Map;for(let s of i.filter(c=>c.result.skipped&&c.retryable)){let c=e.find(d=>d.id===s.result.id);c&&(r(`Retrying ${c.label} indexer serially after parallel failure...`),A(a,"Reindex cancelled by its owner."),o.set(c.id,(await Ht(c,n,r,a)).result))}return i.map(({result:s})=>o.get(s.id)??s)}async function Ht(e,t,n,r){A(r,"Reindex cancelled by its owner."),n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Pe(e.scipPath,{force:!0});let a=gc(e.config,t,e.scipPath),i=[],o=[e.binary,...e.args].join(" "),s=C();try{i=uc(e,t),e.trustedProjectTool&&$n(t,e.trustedProjectTool);let d=yn(e.binary,e.args),l=await ve({command:d.binary,args:d.args,label:`${e.label} indexer`,cwd:t,env:e.env,timeoutMs:hc(),maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024,signal:r});if(l.status!==0){let g=l.stderr.trim();throw new Error(`${e.resolvedBinary} exited with status ${l.status}${g?`:
289
- ${g}`:""}`)}pc(e.config,t,e.scipPath)}catch(d){if(r?.aborted)throw Sn(r,"Reindex cancelled by its owner.");let l=d instanceof Error?d.message:String(d),g=l.length<=Wi?l:`${l.slice(0,Wi)}
290
- [indexer failure detail truncated]`,p=`${e.resolvedBinary} indexer failed: ${g}`,f=e.label===e.language?p:`${e.label}: ${p}`;return n(`Skipping ${e.label}: ${p}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:C()-s,command:o,...e.outputComposition?{outputComposition:e.outputComposition}:{},skipped:{language:e.language,reason:f}},retryable:yc(d)}}finally{fc(a);for(let d of i.reverse())Xi(d)}if(!Ze(e.scipPath)){let d=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,l=e.label===e.language?d:`${e.label}: ${d}`;return n(`Skipping ${e.label}: ${d}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:C()-s,command:o,...e.outputComposition?{outputComposition:e.outputComposition}:{},skipped:{language:e.language,reason:l}},retryable:!1}}let c;try{c=cc(e.scipPath).size}catch{c=void 0}return{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:C()-s,command:o,...e.outputComposition?{outputComposition:e.outputComposition}:{},outputBytes:c},retryable:!1}}function hc(){let e=Number(process.env.SCIP_QUERY_INDEXER_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):sn.indexer}function yc(e){return e instanceof cn?e.kind==="spawn"&&zi(e.cause):zi(e)}function zi(e){let t=e?.code;return t==="EAGAIN"||t==="ENOMEM"||t==="EMFILE"||t==="ENFILE"||t==="ETXTBSY"}import{execFileSync as Ki}from"child_process";import{homedir as Qi,platform as Sc}from"os";import{delimiter as bc,join as et}from"path";function Vi(e,t){let n=e.installMethods,r=Oe(e);if(!n?.length)return t(`No auto-install method available for ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1;for(let a of n){if(!a.identity||!a.destination){t(`Refusing ${a.label} installation for ${r}: the installer descriptor lacks an immutable identity or destination.`);continue}if(!hn(a.prerequisite))continue;let i=Pc(a);t(`Installing immutable ${a.identity} via ${a.label} into ${i}; expected executable: ${r}.`);try{Ki(a.binary,a.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:Sc()==="win32"});let o=he(e);if(o){let s=o===e.indexerBinary?"":` (using ${o})`;return t(`Successfully installed ${a.identity} via ${a.label}${s}; resolved executable: ${o}.`),!0}t(`${a.label} command completed but ${r} was not found on PATH`)}catch(o){let s=o instanceof Error?o.message:String(o);t(`${a.label} install failed: ${s}`)}}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function Pc(e){if(e.binary==="npm")return Xt("npm",["root","-g"])??e.destination;if(e.binary==="go"){let t=Xt("go",["env","GOBIN"]);if(t)return t;let n=Xt("go",["env","GOPATH"]);if(n)return et(n.split(bc)[0],"bin")}return e.binary==="dotnet"?et(process.env.DOTNET_CLI_HOME??Qi(),".dotnet","tools"):e.binary==="dart"?et(process.env.PUB_CACHE??et(Qi(),".pub-cache"),"bin"):e.destination}function Xt(e,t){try{return Ki(e,t,{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4,killSignal:"SIGKILL",env:process.env}).trim()||null}catch{return null}}async function ga(e){let{projectRoot:t,onStatus:n=console.log}=e,r=e.maxHeapMb??dn(process.env.NODE_OPTIONS)??8192,a=e.skipAutoInstall===!0||e.installMissing!==!0,i=_c(e),o=Date.now(),s=C();rt(x(i.outputScip),{recursive:!0}),rt(x(i.outputDb),{recursive:!0});let c=e.languages??tr(t);if(c.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");n(`Detected languages: ${c.join(", ")}`);let d=at(i.metaPath),l=E("reindex.fingerprint",()=>Mn(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath},d,e.changeJournal,ht(i.outputDb)),{languages:c.length}),g=l.fingerprint,p=l.mode==="delta"?e.changeJournal?.entries.filter(y=>y.kind!=="add").length??0:0,f=Math.max(0,(d?.files.length??0)-p);n(l.mode==="delta"?`Project fingerprint revalidated ${l.changedPaths.length} changed path(s), reused ${f} accepted file fingerprint(s), and accepted ${g.files.length} input(s)`:`Project fingerprint used full scan: ${l.reason}`);let R=await Ic({opts:e,paths:i,languages:c,fingerprint:g,onStatus:n}),T=R.snapshot,j=R.releaseBuildLock,D=_a(e.trigger),v=Rn(O(x(i.outputDb),"cache-lifecycle.lock"),{waitMs:D?1e3:3e4});if(!v)throw j?.(),new le(D?`Could not acquire scip-query cache lifecycle lock for ${x(i.outputDb)}; another refresh is publishing, so the watcher will retry.`:`Could not acquire scip-query cache lifecycle lock for ${x(i.outputDb)}. A watch daemon or another reindex may hold it. Run "scip-query watch --stop", retry the reindex, then restart with "scip-query watch --daemon".`);let F;try{F=await G("reindex.lock",()=>rd(O(x(i.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:n}),{languages:c.length})}catch(y){throw v.release(),j?.(),y}let _=null,h=Dr();try{l.mode==="delta"&&ht(i.outputDb)!==e.changeJournal?.baseGeneration&&(g=kn(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),l={mode:"full",fingerprint:g,reason:"accepted-generation-changed-before-lock"},T=void 0,j?.(),j=void 0,n("Project fingerprint used full scan: accepted-generation-changed-before-lock")),fr(i.outputDb,i.outputScip,i.metaPath);let y=jc(x(i.outputDb));y.removed>0&&n(`Removed ${y.removed} abandoned reindex workspace(s)`);for(let b of y.errors)n(`Could not remove abandoned reindex workspace: ${b}`);let m=null,w=await G("reindex.reuse-check",async()=>(m=await Tc({opts:e,paths:i,languages:c,fingerprint:g,start:o,monotonicStart:s,onStatus:n}),m),()=>({languages:c.length,reused:m!==null}));if(w){na({snapshot:T,paths:i,projectRoot:t,fingerprint:g,onStatus:n});let b=St(i.outputDb,w);return b.state==="failed"&&n(`Warning: reindex succeeded, but activity telemetry was not recorded: ${b.reason}`),gt(t,x(i.outputDb)),w}xn()&&await G("reindex.scip-cli-ready",()=>zc(a,n));let S=Cc(i);_=S.runDir;let P,I=await G("reindex.fresh",async()=>(P=await Oc({opts:e,languages:c,projectRoot:t,paths:i,tempPaths:S,fingerprint:g,start:o,monotonicStart:s,maxHeapMb:r,skipAutoInstall:a,onStatus:n,writeTelemetry:h}),P),()=>({languages:c.length,reused:P?.reused,skipped:P?.skipped.length}));na({snapshot:T,paths:i,projectRoot:t,fingerprint:g,onStatus:n});let u=St(i.outputDb,I);return u.state==="failed"&&n(`Warning: reindex succeeded, but activity telemetry was not recorded: ${u.reason}`),gt(t,x(i.outputDb)),I}catch(y){let m=ct({trigger:e.trigger,result:"failed",start:o,monotonicStart:s,error:y instanceof Error?y.message:String(y)});ja(i.metaPath,m);let w=sr(i.outputDb,m);throw w.state==="failed"&&n(`Warning: failed reindex activity telemetry was not recorded: ${w.reason}`),y}finally{_&&Z(_,{recursive:!0,force:!0}),F(),v.release(),j?.()}}async function Ic(e){let{opts:t,paths:n,languages:r,fingerprint:a,onStatus:i}=e,o=t.projectRoot;if(!(t.skipIfUnchanged!==!1&&!mr(o,n.outputDb)&&Zi(n.outputScip)===Zi(O(x(n.outputDb),"index.scip"))))return{snapshot:void 0,releaseBuildLock:void 0};let c=je(o),d=c?.clean?Be(c,a):void 0;if(c&&!c.clean&&!ra(n))return ta({context:c,languages:r,opts:t,paths:n,fingerprint:a,projectRoot:o,onStatus:i,successMessage:"dirty worktree reindex",failurePrefix:"Shared baseline fork failed"}),{snapshot:d,releaseBuildLock:void 0};if(!d)return{snapshot:void 0,releaseBuildLock:void 0};let l=bt(d);if(l){if(!vc(n,a))try{Ue({snapshot:d,manifest:l,targetCacheDir:x(n.outputDb),targetProjectRoot:o}),i(`Attached shared generation ${d.generationId.slice(0,12)}`)}catch(p){i(`Shared generation attach failed; continuing locally: ${ee(p)}`)}return{snapshot:d,releaseBuildLock:void 0}}c&&!ra(n)&&ta({context:c,languages:r,opts:t,paths:n,fingerprint:a,projectRoot:o,onStatus:i,successMessage:"cold worktree reindex",failurePrefix:"Compatible shared baseline fork failed",compatible:!0});let g=await Sr(d);if(g.kind==="owner")return{snapshot:d,releaseBuildLock:g.release};if(g.kind==="generation-ready"){let p=bt(d);if(p)try{Ue({snapshot:d,manifest:p,targetCacheDir:x(n.outputDb),targetProjectRoot:o,action:"waited"}),i(`Attached shared generation ${d.generationId.slice(0,12)} after waiting`)}catch(f){i(`Shared generation attach failed after waiting; continuing locally: ${ee(f)}`)}}else i("Shared generation build lock timed out; continuing with an isolated local reindex");return{snapshot:d,releaseBuildLock:void 0}}function ta(e){let t=hr(e.context,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath},e.fingerprint);if(t)try{Ue({snapshot:t.snapshot,manifest:t.manifest,targetCacheDir:x(e.paths.outputDb),targetProjectRoot:e.projectRoot,persistLease:!1}),Pr(t.snapshot,x(e.paths.outputDb)),e.onStatus(`Forked ${e.compatible?"compatible ":""}shared baseline ${t.snapshot.generationId.slice(0,12)} for ${e.successMessage}`)}catch(n){e.onStatus(`${e.failurePrefix}; continuing locally: ${ee(n)}`)}}function na(e){if(e.snapshot)try{let t=je(e.projectRoot),n=t?Be(t,e.fingerprint):void 0;if(!n||n.generationId!==e.snapshot.generationId){e.onStatus("Skipped shared generation publication because the worktree changed during indexing");return}let r=yr({snapshot:e.snapshot,sourceCacheDir:x(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let a=je(e.projectRoot);return(a?Be(a,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}});br(e.snapshot,x(e.paths.outputDb),"built"),e.onStatus(r.kind==="published"?`Published shared generation ${e.snapshot.generationId.slice(0,12)} (${r.achievedDurability})`:`Shared generation ${e.snapshot.generationId.slice(0,12)} was already available (${r.achievedDurability})`)}catch(t){e.onStatus(`Shared generation publication failed; local index remains valid: ${ee(t)}`)}}function vc(e,t){if(!L(e.outputScip)||!L(e.outputDb)||Ca(e.metaPath,t)===null)return!1;let n=W(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function ra(e){if(!L(e.outputScip)||!L(e.outputDb)||!re(e.metaPath))return!1;let t=W(e.outputDb,e.metaPath);return t.state!=="invalid"&&t.state!=="drifted"}function ee(e){return e instanceof Error?e.message:String(e)}async function Kt(e,t,n,r,a,i,o,s=!1){try{await or(Mr({indexPath:n,evidenceDbPath:o,reuseExisting:a,affectedFiles:i,forceDerivedRebuild:s}),{projectRoot:e,dbPath:t,onStatus:r})}catch(c){r(`Runtime-boundary extraction unavailable: ${c instanceof Error?c.message:String(c)}.`)}}function _c(e){let t=e.outputScip??O(e.projectRoot,"index.scip"),n=e.outputDb??O(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:O(x(n),"meta.json")}}async function Tc(e){let t=W(e.paths.outputDb,e.paths.metaPath),n=Ca(e.paths.metaPath,e.fingerprint);if(e.opts.skipIfUnchanged===!1||!L(e.paths.outputScip)||!L(e.paths.outputDb)||n===null||t.state==="invalid"||t.state==="drifted")return null;let r=$e(e.paths.outputDb,e.fingerprint,e.languages);if(r.state!=="complete")return e.onStatus(Vt("Accepted SQLite index",r)),null;Ae(Ne(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),await Kt(e.opts.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0),W(e.paths.outputDb,e.paths.metaPath).state==="drifted"&&(Ge(e.paths.outputDb,e.paths.metaPath),e.onStatus("Published refreshed SQLite generation after post-index augmentation")),n==="operational-config-compatible"&&(ud(e.paths.metaPath,e.fingerprint,e.languages,e.opts),Ge(e.paths.outputDb,e.paths.metaPath),e.onStatus("Migrated operational .scipquery.json metadata without rerunning language indexers."));let a=C()-e.monotonicStart,i=ct({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:e.languages,skipped:[]});return ja(e.paths.metaPath,i),e.onStatus(`Index unchanged; reused existing SQLite index in ${(a/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:a,reused:!0,skipped:[],lastRefresh:i,shards:wc(e.paths,e.languages,e.opts,e.fingerprint)}}function wc(e,t,n,r){let a=Zt(r,t,n);return t.map(i=>({id:i,language:i,reused:!0,strategy:"reused",fingerprint:Re(a[i]),outputBytes:te(en(e.outputDb,i)),durationMs:0}))}function Cc(e){let t=xc(O(x(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:O(t,tt(e.outputScip)),tempOutputDb:O(t,tt(e.outputDb)),tempMetaPath:O(t,tt(e.metaPath))}}function jc(e){let t=[],n;try{n=ua(e,{withFileTypes:!0})}catch(a){return{removed:0,errors:[ee(a)]}}let r=0;for(let a of n)if(!(!a.name.startsWith("reindex-")||!a.isDirectory()))try{Z(O(e,a.name),{recursive:!0,force:!0}),r+=1}catch(i){t.push(`${a.name}: ${ee(i)}`)}return{removed:r,errors:t}}async function Oc(e){let t={...process.env,NODE_OPTIONS:ln(process.env.NODE_OPTIONS,e.maxHeapMb)},n,r=await G("reindex.language-indexers",async()=>(n=await kc(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:a,skippedLanguages:i,reusedLanguages:o,languageFingerprints:s,shards:c,typescriptProjectShardContext:d,incrementalTypeScript:l}=r;if(o.length>0&&e.onStatus(`Reused ${o.length} cached language shard(s): ${o.join(", ")}`),Fc({run:e,indexedOutputs:a,skippedLanguages:i,reusedLanguages:o})){let f=await G("reindex.publish",()=>qc(e,a,i,o,s,d),{mode:"metadata-only",languages:a.length,reused:o.length}),R=f.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(R/1e3).toFixed(1)}s`),{languages:a.map(T=>T.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:R,reused:!0,skipped:i,lastRefresh:f,shards:c,writeTelemetry:e.writeTelemetry}}let g=await G("reindex.publish",()=>Bc(e,t,a,i,o,s,d,l),{mode:l?"incremental-or-fallback":"full",languages:a.length,reused:o.length,skipped:i.length}),p=g.durationMs;return e.onStatus(`Done in ${(p/1e3).toFixed(1)}s`),{languages:a.map(f=>f.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:p,reused:!1,skipped:i,lastRefresh:g,shards:c,writeTelemetry:e.writeTelemetry}}function Fc(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!L(e.run.paths.outputScip)||!L(e.run.paths.outputDb))return!1;let t=W(e.run.paths.outputDb,e.run.paths.metaPath);if(t.state==="invalid"||t.state==="drifted")return!1;let n=new Set(e.reusedLanguages),r=new Set(e.indexedOutputs.map(a=>a.language));return e.run.languages.length>0&&r.size===e.run.languages.length&&e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(a=>n.has(a)&&r.has(a))}async function kc(e,t){let n=e.opts.skipIfUnchanged===!1,r=Ac({paths:e.paths,projectRoot:e.projectRoot,languages:e.languages,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath,projectFingerprint:e.fingerprint});if(n)for(let[u,b]of r)b.reused&&r.set(u,{...b,reused:!1,reason:"forced reindex requested"});let a=[],i=new Set;for(let[u,b]of r)b.reused&&(a.push({language:u,scipPath:b.scipPath}),i.add(u));for(let u of i)e.onStatus(`Reusing cached ${u} SCIP shard (language inputs unchanged).`);let o=r.get("typescript"),s=W(e.paths.outputDb,e.paths.metaPath),c=re(e.paths.metaPath),d=s.state==="legacy"||s.state==="current",l=c?.scipCompanion!=="deferred"&&(s.state!=="current"||s.generation.publication?.scipCompanion!=="deferred"),g;n&&o&&!o.reused&&(g="forced reindex rebuilds from the compilers");let p=!n&&o&&!o.reused&&d?Ui({projectRoot:e.projectRoot,cacheDir:x(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:ne(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:ne(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:l,previousSnapshot:at(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus,onUnavailable:u=>{g=u}}):null,f=new Set(p?["typescript"]:[]);if(e.opts.allowExpensiveRebuild===!1){let u=e.languages.filter(b=>!i.has(b)&&!f.has(b));if(u.length>0){let b=u.length===1&&u[0]==="typescript"&&g?`: ${g}`:"";throw new Error(`Incremental indexing is unavailable for ${u.join(", ")}${b}. The accepted index was preserved because whole-project rebuilds are disabled; run scip-query reindex --allow-expensive-rebuild only when you explicitly want that fallback.`)}}let R=p||i.has("typescript")?void 0:Dc(e,r),T=R&&n?{...R,classification:new Map([...R.classification].map(([u,b])=>[u,b.reused?{...b,reused:!1,reason:"forced reindex requested"}:b])),reusedProjects:[],missedProjectIds:new Set(R.allProjects.map(u=>`typescript:${u}`))}:R,{preparedRuns:j,skippedLanguages:D,languageOutputScipPaths:v}=Xc({languages:e.languages.filter(u=>!i.has(u)&&!f.has(u)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,trustProjectTools:e.opts.trustProjectTools===!0,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:T?.allProjects,typescriptShardCostDir:x(e.paths.outputDb),clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),F=T?j.filter(u=>u.language!=="typescript"||T.missedProjectIds.has(u.id)):j,_=await Yi(F,e.projectRoot,e.onStatus,e.opts.indexerConcurrency,e.opts.signal);if(fn())for(let u of _)mn({type:"span",name:`reindex.language-indexer.${u.id}`,durationMs:Math.round(u.durationMs),ok:!u.skipped,language:u.language,indexerCommand:u.command,outputBytes:u.outputBytes,measurement:"indexer-run-result"});Qc(x(e.paths.outputDb),e.projectRoot,F,_);let h=[];if(T){Nc(e.paths.outputDb,_,e.writeTelemetry);let u=v.typescript??e.tempPaths.tempOutputScip;h=Lc({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:u,reusedProjects:T.reusedProjects,writeTelemetry:e.writeTelemetry})}let y=[..._,...h],{indexedOutputs:m}=Vc(y,D),w=p?[{language:"typescript",scipPath:p.scipPath}]:[],S=[...a,...w,...m];Zc(S,D,e.languages,e.opts.allowPartial,e.onStatus);let P=p?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:p.scipPath,outputScipPath:p.scipPath,durationMs:p.durationMs,command:"watch-service:typescript-index",outputBytes:te(p.scipPath)??void 0,producedOutputBytes:te(p.affectedScipPath)??void 0}]:[],I=$c(r,[..._,...P],T?{outputDb:e.paths.outputDb,classification:T.classification}:void 0,g);return{indexedOutputs:S,skippedLanguages:D,reusedLanguages:[...i],languageFingerprints:Gc(r,e.languages),shards:I,typescriptProjectShardContext:T?{projects:T.allProjects,fingerprints:T.fingerprints}:void 0,incrementalTypeScript:p??void 0}}function Dc(e,t){let n=t.get("typescript");if(!n||n.reused||n.cacheIntegrityFailed||e.opts.typescriptProjectMode!=="workspace")return;let r=X(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let a=ai(e.projectRoot,r),i=ni(n.fingerprint.files,r),o=ri(r,a),s=ii(r,i,o),c=re(e.paths.metaPath),l=Mc(c,s,R=>L(ot(e.paths.outputDb,R))),g=[...l.entries()].filter(([,R])=>R.reused).map(([R])=>R),p=new Set(g),f=new Set(r.filter(R=>!p.has(R)).map(R=>`typescript:${R}`));return{allProjects:r,fingerprints:s,classification:l,reusedProjects:g,missedProjectIds:f}}function Mc(e,t,n){let r=new Map;for(let a of Object.keys(t)){let i=t[a];if(!e){r.set(a,{reused:!1,reason:"no reindex metadata found",fingerprint:i});continue}let o=e.version===ae&&ut(e).typescriptProjectShardReuse?e.typescriptProjectShards?.[a]:void 0;if(!o){r.set(a,{reused:!1,reason:"no cached fingerprint for this project",fingerprint:i});continue}if(!n(a)){r.set(a,{reused:!1,reason:"cached shard file missing on disk",fingerprint:i});continue}if(N(o)!==N(i)){r.set(a,{reused:!1,reason:"project inputs changed since last index",fingerprint:i});continue}r.set(a,{reused:!0,fingerprint:i})}return r}function Nc(e,t,n){for(let r of t){if(r.skipped||!r.id.startsWith("typescript:"))continue;let a=r.id.slice(11),i=ot(e,a);rt(x(i),{recursive:!0}),V(n,K(r.scipPath,i,void 0,{shareImmutable:!0}))}}function Lc(e){return e.reusedProjects.map((t,n)=>{let r=ot(e.outputDb,t),a=ne(e.tempOutputScip,"typescript-project-cached",n);return V(e.writeTelemetry,K(r,a,void 0,{shareImmutable:!0})),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:a,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:te(a)??void 0}})}function Ac(e){let t=re(e.paths.metaPath),n=Zt(e.projectFingerprint,e.languages,e),r=t&&L(e.paths.outputDb)?$e(e.paths.outputDb,e.projectFingerprint,e.languages):null,a=new Map;for(let i of e.languages){let o=en(e.paths.outputDb,i),s=n[i];if(!t){a.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:s,scipPath:o});continue}if(t.version!==ae){a.set(i,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:s,scipPath:o});continue}if(!ut(t).languageShardReuse||!t.languageFingerprints){a.set(i,{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:s,scipPath:o});continue}let c=t.languageFingerprints[i];if(!c){a.set(i,{reused:!1,reason:"no cached fingerprint for this language",fingerprint:s,scipPath:o});continue}if(!L(o)){a.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:s,scipPath:o});continue}let d=i==="typescript"?cd(e.projectRoot,c):c;if(N(d)!==N(s)){a.set(i,{reused:!1,reason:"language inputs changed since last index",fingerprint:s,scipPath:o});continue}if(r?.state==="unavailable"||r?.state==="incomplete"&&r.affectedLanguages.includes(i)){a.set(i,{reused:!1,reason:Vt("accepted SQLite index",r),cacheIntegrityFailed:!0,fingerprint:s,scipPath:o});continue}a.set(i,{reused:!0,fingerprint:s,scipPath:o})}return a}function $c(e,t,n,r){let a=[];for(let[i,o]of e)o.reused&&a.push({id:i,language:i,reused:!0,strategy:"reused",fingerprint:Re(o.fingerprint),outputBytes:te(o.scipPath),durationMs:0});for(let i of t){let o=e.get(i.language),s=n&&i.id.startsWith("typescript:")?i.id.slice(11):null,c=s?n.classification.get(s):void 0;a.push({id:i.id,language:i.language,reused:!1,strategy:i.command==="watch-service:typescript-index"?"incremental":"full",missReason:c?.reason??o?.reason??i.skipped?.reason,fallbackReason:i.language==="typescript"?r:void 0,fingerprint:c?Re(c.fingerprint):o?Re(o.fingerprint):"unknown",outputBytes:i.outputBytes??null,producedOutputBytes:i.producedOutputBytes,durationMs:i.durationMs,command:i.command})}if(n)for(let[i,o]of n.classification)o.reused&&a.push({id:`typescript:${i}`,language:"typescript",reused:!0,strategy:"reused",fingerprint:Re(o.fingerprint),outputBytes:te(ot(n.outputDb,i)),durationMs:0});return a}function Re(e){return Rc("sha256").update(N(e)).digest("hex").slice(0,16)}function te(e){try{return Qt(e).size}catch{return null}}function Gc(e,t){let n={};for(let r of t){let a=e.get(r);a&&(n[r]=a.fingerprint)}return n}async function Bc(e,t,n,r,a,i,o,s){A(e.opts.signal,"Reindex cancelled by its owner.");let c=!s||s.completeScipUpdated,d=!1;c&&(d=E("reindex.publish.scip-output",()=>{let h=Jc({run:e,indexedOutputs:n,incrementalTypeScript:s,typescriptReused:a.includes("typescript")});return ia(e.paths.outputDb,h,e.writeTelemetry),aa(h,e.tempPaths.tempOutputScip,e.onStatus)}));let l=await G("reindex.publish.sqlite-output",()=>ed({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:a,incrementalTypeScript:s,completeScipAvailable:c,completeScipSanitized:d,materializeFullFallback:async()=>{if(A(e.opts.signal,"Reindex cancelled by its owner."),!s||s.completeScipUpdated)return d;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),Wt({cacheDir:x(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let h=n.map(y=>y.language==="typescript"?{language:y.language,scipPath:s.candidateScipPath}:y);return ia(e.paths.outputDb,h,e.writeTelemetry),d=aa(h,e.tempPaths.tempOutputScip,e.onStatus),d}}));A(e.opts.signal,"Reindex cancelled by its owner."),E("reindex.publish.auxiliary-documents",()=>{Ae(Ne(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus})}),await G("reindex.publish.runtime-boundaries",async()=>{let h=s?.plan.mode==="full-project",y=s?.dependencyGraphUnchanged===!0;h?e.onStatus("Rebuilding compiler-derived runtime-boundary relationships while retaining unchanged per-file extraction facts."):y&&e.onStatus("Reusing runtime-boundary relationships because TypeScript semantics are unchanged."),await Kt(e.projectRoot,e.tempPaths.tempOutputDb,e.tempPaths.tempOutputScip,e.onStatus,y,y?void 0:h?s?.changedFiles:s?.affectedFiles,O(x(e.paths.outputDb),Un),h)});let g=E("reindex.publish.sqlite-layout",()=>Ot(e.tempPaths.tempOutputDb,{analyze:Uc(s,l.mode)}));g.added.length>0&&e.onStatus(`Added SQLite query indexes: ${g.added.join(", ")}`),g.removed.length>0&&e.onStatus(`Removed redundant SQLite indexes: ${g.removed.join(", ")}`),E("reindex.publish.coverage",()=>Sa(e,e.tempPaths.tempOutputDb,n.map(h=>h.language)));let p,f=null;l.mode==="incremental"&&s&&E("reindex.publish.reference-fragments",()=>{if(s.dependencyGraphUnchanged){let m=new $({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});try{f=yt(m),e.onStatus("Preserved exact TypeScript reference fragments and dependency relationships because only trivia changed.")}finally{m.close()}return}let h=null,y=null;try{h=E("reindex.publish.reference-fragments.open-candidate",()=>new $({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip})),y=E("reindex.publish.reference-fragments.open-evidence",()=>new $({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip})),p=s.dependencyGraphSnapshot?E("reindex.publish.reference-fragments.dependency-graph",()=>Jn(h,s.dependencyGraphSnapshot,s.affectedFiles,s.deletedFiles))??void 0:void 0;let m=new Set(s.deletedFiles),w=m.size===0?s.referenceFragmentsByFile:new Map([...s.referenceFragmentsByFile].filter(([P])=>!m.has(P))),S=E("reindex.publish.reference-fragments.seed",()=>Xn(h,e.fingerprint,w,y,p,new Set(s.affectedFiles)));e.onStatus(`Cached exact TypeScript reference fragments for ${S.affectedFiles} affected document(s) and carried ${S.carriedFiles} unaffected document(s) forward.`),S.skippedAffectedFiles>0&&e.onStatus(`Skipped exact TypeScript reference fragment prefill for ${S.skippedAffectedFiles} affected document(s) whose semantic identity was unavailable.`)}catch(m){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${m instanceof Error?m.message:String(m)}.`)}finally{h?.close(),y?.close()}});let R=at(e.paths.metaPath);l.mode==="incremental"&&s||await fa({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousSnapshot:R,currentSnapshot:e.fingerprint,onStatus:e.onStatus});let T=E("reindex.publish.affected-shadow",()=>l.mode==="incremental"&&s?nd(s,l.changedDocumentPaths):vt({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:R,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"})),j=ct({trigger:e.opts.trigger,result:"rebuilt",start:e.start,monotonicStart:e.monotonicStart,languages:n.map(h=>h.language),skipped:[...r]}),D=l.mode==="incremental"&&l.scipCompanion==="deferred",{metadata:v,pruneProjects:F}=ha({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:a,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:j});v.scipCompanion=D?"deferred":"current",E("reindex.publish.metadata",()=>{ya(e),ba(e.paths.outputDb,F),st(e.tempPaths.tempMetaPath,v)});let _=E("reindex.publish.generation-handoff",()=>gr({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath,preserveOutputScip:l.mode==="incremental"&&l.scipCompanion==="deferred",publication:l.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:l.converterDurationMs,affectedDocumentCount:s?.affectedFiles.length,changedDocumentCount:l.changedDocumentPaths.length,producerDurationMs:s?.timings.serviceMs,materializationDurationMs:s?.durationMs,patchDurationMs:l.patchDurationMs,scipCompanion:l.scipCompanion,...l.scipCompanion==="deferred"&&s?{typescriptOverlayGeneration:s.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:l.converterDurationMs,scipCompanion:"current",...l.fallbackReason?{fallbackReason:l.fallbackReason}:{}}}));return _.achievedDurability==="file-flushed"&&e.onStatus(`Published local generation ${_.currentGeneration.slice(0,12)} (file-flushed; directory sync unsupported)`),l.mode==="incremental"&&s&&E("reindex.publish.dependency-graph",()=>{let h=null;try{h=new $({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let y=s.plan.mode==="full-project"&&s.plan.reasons.length===0?s.changedFiles:s.affectedFiles,m=!1;if(s.dependencyGraphUnchanged){let w=yt(h),S=f&&w?qn(h,"file-dependency-graph",f,w):0;m=S>0,e.onStatus(m?`Carried ${S} unchanged dependency graph product(s) forward without rebuilding them.`:"No persisted dependency graph product required rekeying; the next graph consumer can materialize it.")}else s.dependencyGraphSnapshot?m=Hn(h,s.dependencyGraphSnapshot,y,p):De(h);s.dependencyGraphUnchanged||e.onStatus(m?`Carried the dependency graph forward by replacing ${y.length} changed dependency owner(s).`:"Materialized a fresh dependency graph for the accepted generation because no compatible prior graph was available.")}catch(y){e.onStatus(`Dependency graph carry-forward unavailable: ${y instanceof Error?y.message:String(y)}. The next graph consumer will rebuild it.`)}finally{h?.close()}}),E("reindex.publish.cleanup",()=>{pr(x(e.paths.outputDb),l.mode==="incremental"&&l.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),dr(x(e.paths.outputDb),s?.completeScipUpdated?[s.nextFragmentGeneration]:[])}),E("reindex.publish.shadow-telemetry",()=>ma(e.paths.outputDb,T,e.onStatus)),j}function Uc(e,t){return t!=="incremental"||!e||e.plan.mode==="full-project"?!0:e.affectedFiles.length*20>=e.projectFileCount}async function qc(e,t,n,r,a,i){let o=at(e.paths.metaPath),s=null;try{V(e.writeTelemetry,K(e.paths.outputDb,e.tempPaths.tempOutputDb))}catch(p){s=$r("reused","oracle-error",`Could not snapshot the prior database: ${p instanceof Error?p.message:String(p)}`)}Ae(Ne(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),await Kt(e.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0);let c=Ot(e.paths.outputDb);c.added.length>0&&e.onStatus(`Added SQLite query indexes: ${c.added.join(", ")}`),c.removed.length>0&&e.onStatus(`Removed redundant SQLite indexes: ${c.removed.join(", ")}`),Sa(e,e.paths.outputDb,t.map(p=>p.language)),s==null&&await fa({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,previousSnapshot:o,currentSnapshot:e.fingerprint,onStatus:e.onStatus}),s??=vt({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.paths.outputDb,candidateIndexPath:e.paths.outputScip,previousSnapshot:o,currentSnapshot:e.fingerprint,refreshResult:"reused"});let d=ct({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:l,pruneProjects:g}=ha({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:a,typescriptProjectShardContext:i,lastRefresh:d});return ya(e),ba(e.paths.outputDb,g),st(e.paths.metaPath,l),Ge(e.paths.outputDb,e.paths.metaPath),ma(e.paths.outputDb,s,e.onStatus),d}async function fa(e){if(!L(e.previousDbPath))return;let t=q(e.previousSnapshot,e.currentSnapshot);if(t.changes.length===0||ye(t).fullProject)return;let n=null;try{if(n=new $({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),Me(n))return;let r=await G("reindex.publish.affected-shadow.warm-sources",()=>zn(n,{yieldToEventLoop:()=>new Promise(a=>setImmediate(a))}));e.onStatus(`Persisted import products for ${r.files} document(s) before the affected-set shadow.`)}catch(r){e.onStatus(`Affected-set shadow import warm-up unavailable: ${r instanceof Error?r.message:String(r)}.`)}finally{n?.close()}}function at(e){return lt(re(e)?.fingerprint)}function ma(e,t,n){try{Gr(e,t),t.status==="evaluated"?n(`Affected-set shadow: ${(t.evaluation.recall*100).toFixed(1)}% recall; ${t.plan.affectedFiles.length} predicted, ${t.comparison.changedFiles.length} changed.`):n(`Affected-set shadow unavailable: ${t.reason}.`)}catch(r){n(`Affected-set shadow telemetry unavailable: ${r instanceof Error?r.message:String(r)}`)}}function ha(e){let t=Wc({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:ae,status:e.skippedLanguages.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.run.fingerprint,sqliteLayoutVersion:1,languageFingerprints:e.languageFingerprints,typescriptProjectShards:t.field,requestedLanguages:e.run.languages,indexedLanguages:e.indexedOutputs.map(n=>n.language),skipped:[...e.skippedLanguages],lastRefresh:e.lastRefresh},pruneProjects:t.pruneProjects}}function ya(e){A(e.opts.signal,"Reindex cancelled by its owner.");let t=Dn(e.projectRoot,e.fingerprint);if(N(t)===N(e.fingerprint))return;let n=new Map(e.fingerprint.files.map(i=>[i.path,i])),r=new Map(t.files.map(i=>[i.path,i])),a=[...new Set([...n.keys(),...r.keys()])].filter(i=>N(n.get(i))!==N(r.get(i))).slice(0,5);throw new Error(`Project inputs changed during reindex (${a.join(", ")||"unknown path"}); refusing to publish artifacts built from a different filesystem snapshot.`)}function Sa(e,t,n){let r=$e(t,e.fingerprint,n);if(r.state!=="complete")throw new Error(`${Vt("Candidate SQLite index",r)} Refusing to publish it.`)}function Vt(e,t){if(t.state==="unavailable")return`${e} document coverage could not be verified (${t.reason}); rebuilding cached language shards.`;let n=t.missingPaths.length>0?` First missing path: ${t.missingPaths[0]}.`:"";return`${e} is missing ${t.missingDocumentCount} fingerprinted source document${t.missingDocumentCount===1?"":"s"}; rebuilding affected language shards.${n}`}function Wc(e){if(e.mode!=="workspace")return{field:void 0,pruneProjects:null};if(e.skippedLanguages.some(t=>t.language==="typescript"))return{field:void 0,pruneProjects:null};if(e.reusedLanguages.includes("typescript")){let t=re(e.metaPath),n=t?.version===ae?t.typescriptProjectShards:void 0;return{field:n,pruneProjects:n?Object.keys(n):[]}}return e.context?{field:e.context.fingerprints,pruneProjects:e.context.projects}:{field:void 0,pruneProjects:[]}}function ba(e,t){let n=wa(e);if(t===null){Z(n,{recursive:!0,force:!0});return}let r;try{r=ua(n)}catch{return}for(let a of Hc(r,t))Z(O(n,a),{force:!0})}function Hc(e,t){let n=new Set(t.map(r=>`${Mt(r)}.scip`));return e.filter(r=>!n.has(r))}function Jc(e){if(e.incrementalTypeScript?.completeScipUpdated)return[...e.indexedOutputs];let t=e.indexedOutputs.find(o=>o.language==="typescript");if(!t)return[...e.indexedOutputs];if(!e.typescriptReused)return[...e.indexedOutputs];let n=W(e.run.paths.outputDb,e.run.paths.metaPath),r=n.state==="current"?n.generation.publication?.typescriptOverlayGeneration:void 0;if(!(n.state==="current"?n.generation.publication?.scipCompanion==="deferred":re(e.run.paths.metaPath)?.scipCompanion==="deferred")||!r)return[...e.indexedOutputs];let i=ne(e.run.tempPaths.tempOutputScip,"typescript-deferred",0);return e.run.onStatus("Materializing the deferred whole TypeScript SCIP companion for complete publication..."),Wt({cacheDir:x(e.run.paths.outputDb),generationIdentity:r,baseShardPath:t.scipPath,candidateShardPath:i}),e.indexedOutputs.map(o=>o.language==="typescript"?{language:o.language,scipPath:i}:o)}function ia(e,t,n){for(let r of t){let a=en(e,r.language);rt(x(a),{recursive:!0}),r.scipPath!==a&&V(n,K(r.scipPath,a,void 0,{shareImmutable:!0}))}}async function zc(e,t){let n=In();if(n){if(n.source==="path"&&ea()!=="win32"){let r=_n();vn(r)||(e?t(`scip on PATH reports ${r??"an unknown version"}; the reviewed version is ${Ce} and compatibility is unverified. Run scip-query setup --install-missing to install the reviewed release.`):(t(`scip on PATH reports ${r??"an unknown version"}; installing the reviewed ${Ce}.`),await Tn(t)))}return}if(ea()==="win32")throw new Error("The scip CLI was not found. On Windows it ships via the npm sidecar package scip-query-scip-windows (installed automatically with scip-query). Reinstall scip-query with optional dependencies enabled, or follow 'scip-query setup' guidance for the exact sidecar package version, or set SCIP_QUERY_SCIP_BIN to a local scip.exe path.");if(e)throw new Error(`The scip CLI is required but not found on PATH.
336
+ )`],qm=["CREATE INDEX idx_chunks_line_range ON chunks(document_id, start_line, end_line)","CREATE INDEX idx_mentions_symbol_id_role ON mentions(symbol_id, role)","CREATE INDEX idx_defn_enclosing_ranges_symbol_id ON defn_enclosing_ranges(symbol_id)","CREATE INDEX idx_defn_enclosing_ranges_document ON defn_enclosing_ranges(document_id, start_line, end_line)","CREATE INDEX idx_chunks_doc_id ON chunks(document_id)","CREATE INDEX idx_global_symbols_symbol ON global_symbols(symbol)"];function Nr(e){return e.startsWith("local ")}function Vm(e,t,n,r){let i=t,a=0,o=0;for(;i<n;){let s=e[i];i+=1,o<53&&(a+=(s&127)*2**o),(s&128)===0?(r.push(a),a=0,o=0):o+=7}}function ks(e){return e.length===3?[e[0],e[1],e[0],e[2]]:e.length===4?[e[0],e[1],e[2],e[3]]:null}function zm(e,t){return e.startLine!==t.startLine?e.startLine-t.startLine:e.startChar!==t.startChar?e.startChar-t.startChar:e.endLine!==t.endLine?e.endLine-t.endLine:e.endChar!==t.endChar?e.endChar-t.endChar:e.symbol<t.symbol?-1:e.symbol>t.symbol?1:0}function Wm(e,t,n,r){let i=[],a=[],o="",s=0;for(let l of De(e,n,r))l.fieldNumber===Bs?As(e,l,i):l.fieldNumber===$s&&l.wireType===2?o=$e.decode(e.subarray(l.valueStart,l.valueEnd)):l.fieldNumber===Us&&l.wireType===0?s=l.varint:l.fieldNumber===Lm&&As(e,l,a);let c=ks(i);return c?{startLine:c[0],startChar:c[1],endLine:c[2],endChar:c[3],symbol:o,roles:s,frameStart:t,frameEnd:r,merged:!1,enclosing:ks(a)}:null}function Km(e,t,n){let r={symbol:"",displayName:null,kind:null,documentation:[],enclosingSymbol:null};for(let i of De(e,t,n))if(i.wireType===2){let a=()=>$e.decode(e.subarray(i.valueStart,i.valueEnd));i.fieldNumber===Am?r.symbol=a():i.fieldNumber===Mm?r.documentation.push(a()):i.fieldNumber===Bm?r.displayName=a():i.fieldNumber===$m&&(r.enclosingSymbol=a())}else i.fieldNumber===jm&&i.wireType===0&&(r.kind=i.varint);return r}var $e=new TextDecoder;function Xm(e,t){if(e.length===0)return[];let n=[],r=Math.min(e.length,t);for(let i=0;i<r&&r<=e.length;){for(;r<=e.length-1&&e[r-1].startLine===e[r].startLine;)r+=1;n.push(e.slice(i,r)),i=r,r=Math.min(e.length,r+t)}return n}function Jm(e){let t=e.startLine===e.endLine?[e.startLine,e.startChar,e.endChar]:[e.startLine,e.startChar,e.endLine,e.endChar],n=[],r=Buffer.concat(t.map(o=>be(o)));n.push(bt(Bs),be(r.length),r);let i=Buffer.from(e.symbol,"utf8");n.push(bt($s),be(i.length),i),e.roles!==0&&n.push(be(Us*8),be(e.roles));let a=Buffer.concat(n);return Buffer.concat([bt(Ms),be(a.length),a])}function Ym(e,t){let n=[];for(let r of t)r.merged?n.push(Jm(r)):n.push(e.subarray(r.frameStart,r.frameEnd));return Tm(Buffer.concat(n))}function Qm(e,t,n){let r="",i=null,a=null,o=null,s=[];for(let c of De(e,t,n))c.wireType===2?c.fieldNumber===js?r=$e.decode(e.subarray(c.valueStart,c.valueEnd)):c.fieldNumber===Nm?s.push(Km(e,c.valueStart,c.valueEnd)):c.fieldNumber===Om?i=$e.decode(e.subarray(c.valueStart,c.valueEnd)):c.fieldNumber===Dm&&(a=$e.decode(e.subarray(c.valueStart,c.valueEnd))):c.fieldNumber===km&&c.wireType===0&&(o=rf(c.varint));return{relativePath:r,language:i,text:a,positionEncoding:o,declaredSymbols:s}}function Zm(e,t){let n=new Map;for(let r of e){if(r.symbol==="")throw new ue(`empty symbol in SymbolInformation for document ${t}`);let i=n.get(r.symbol);if(!i){n.set(r.symbol,r);continue}for(let a of r.documentation)i.documentation.includes(a)||i.documentation.push(a)}return[...n.values()].sort((r,i)=>r.symbol<i.symbol?-1:r.symbol>i.symbol?1:0)}function ef(e,t,n,r){let i="",a=[];for(let o of De(e,t,n))if(o.wireType===2){if(o.fieldNumber===js)i=$e.decode(e.subarray(o.valueStart,o.valueEnd));else if(o.fieldNumber===_m){let s=Wm(e,o.fieldStart,o.valueStart,o.valueEnd);s?a.push(s):r.illegalOccurrencesDropped+=1}}return{relativePath:i,records:a}}function tf(e,t){e.sort(zm);let n=[];for(let r of e){let i=n[n.length-1];if(i&&i.startLine===r.startLine&&i.startChar===r.startChar&&i.endLine===r.endLine&&i.endChar===r.endChar&&i.symbol===r.symbol){i.roles|=r.roles,i.merged=!0,t.mergedOccurrences+=1;continue}n.push(r)}return t.occurrences+=n.length,n}function nf(e,t,n){let[r,i,a,o]=e;if(r<0||i<0||a<r||a===r&&o<i)throw new ue(`bad enclosing range for symbol ${t} in ${n}`)}var Or=class{constructor(t,n){this.stats=n;this.insertDocument=t.prepare("INSERT INTO documents (id, language, relative_path, position_encoding, text) VALUES (?, ?, ?, ?, ?)"),this.insertChunk=t.prepare("INSERT INTO chunks (id, document_id, chunk_index, start_line, end_line, occurrences) VALUES (?, ?, ?, ?, ?, ?)"),this.insertEnclosing=t.prepare("INSERT INTO defn_enclosing_ranges (document_id, symbol_id, start_line, start_char, end_line, end_char) VALUES (?, ?, ?, ?, ?, ?)"),this.insertSymbol=t.prepare("INSERT INTO global_symbols (id, symbol, display_name, kind, documentation, enclosing_symbol) VALUES (?, ?, ?, ?, ?, ?)"),this.insertMention=t.prepare("INSERT INTO mentions (chunk_id, symbol_id, role) VALUES (?, ?, ?)")}stats;insertDocument;insertChunk;insertEnclosing;insertSymbol;insertMention;documentIds=new Map;symbolIds=new Map;nextDocumentId=1;nextChunkId=1;nextSymbolId=1;addSymbol(t,n,r,i,a){let o=this.nextSymbolId;return this.nextSymbolId+=1,this.symbolIds.set(t,o),this.insertSymbol.run(o,t,n,r,i,a),this.stats.globalSymbols+=1,o}writeDeclarations(t){let{relativePath:n,language:r,text:i,positionEncoding:a,declaredSymbols:o}=t;if(n==="")throw new ue("relative path must not be empty");if(this.documentIds.has(n)){this.stats.duplicateDocumentsSkipped+=1;return}let s=this.nextDocumentId;this.nextDocumentId+=1,this.insertDocument.run(s,r===""?null:r,n,a,i===""?null:i),this.documentIds.set(n,s),this.stats.documents+=1,this.writeDeclaredSymbols(Zm(o,n))}writeDeclaredSymbols(t){for(let n of t)Nr(n.symbol)||this.symbolIds.has(n.symbol)||this.addSymbol(n.symbol,n.displayName===""?null:n.displayName,n.kind===0?null:n.kind,n.documentation.length===0?null:n.documentation.join(`
337
+ `),n.enclosingSymbol===""?null:n.enclosingSymbol)}writeEnclosingRanges(t,n,r){for(let i of r){if((i.roles&Um)===0||Nr(i.symbol)||!i.enclosing)continue;let[a,o,s,c]=i.enclosing;nf(i.enclosing,i.symbol,n);let l=this.symbolIds.get(i.symbol);if(l===void 0)throw new ue(`symbol ${i.symbol} has definition occurrence, but no SymbolInformation`);this.insertEnclosing.run(t,l,a,o,s,c),this.stats.enclosingRanges+=1}}writeChunks(t,n,r,i){for(let[a,o]of Xm(r,i).entries()){let s=this.nextChunkId;this.nextChunkId+=1,this.insertChunk.run(s,n,a,o[0].startLine,o[o.length-1].startLine,Ym(t,o)),this.stats.chunks+=1,this.writeMentions(s,o)}}writeMentions(t,n){let r=new Map;for(let i of n){if(Nr(i.symbol))continue;let a=r.get(i.symbol);a||r.set(i.symbol,a=new Set),a.add(i.roles),this.symbolIds.has(i.symbol)||this.addSymbol(i.symbol,null,null,null,null)}for(let[i,a]of r){let o=this.symbolIds.get(i);for(let s of a)this.insertMention.run(t,o,s),this.stats.mentions+=1}}};async function Ls(e,t,n){let r=0;for(let i of De(e))i.fieldNumber!==Ms||i.wireType!==2||(af(t),r+=1,r>=Gm&&(r=0,await wm()),n(i.valueStart,i.valueEnd))}async function Gs(e,t,n={}){let r=n.chunkSize??Fm,i={documents:0,duplicateDocumentsSkipped:0,occurrences:0,illegalOccurrencesDropped:0,mergedOccurrences:0,chunks:0,mentions:0,globalSymbols:0,enclosingRanges:0},a=new Cm(t);try{a.pragma("synchronous = normal"),a.pragma("temp_store = memory"),a.pragma("foreign_keys = ON"),a.pragma("journal_mode = WAL");for(let c of Hm)a.exec(c);let o=new Or(a,i);a.exec("BEGIN IMMEDIATE");let s=!1;try{await Ls(e,n.signal,(l,u)=>{o.writeDeclarations(Qm(e,l,u))});let c=new Set;await Ls(e,n.signal,(l,u)=>{let{relativePath:d,records:p}=ef(e,l,u,i);if(c.has(d))return;c.add(d);let m=o.documentIds.get(d);if(m===void 0)return;let f=tf(p,i);o.writeEnclosingRanges(m,d,f),o.writeChunks(e,m,f,r)}),a.exec("COMMIT"),s=!0}finally{if(!s)try{a.exec("ROLLBACK")}catch{}}a.exec("BEGIN IMMEDIATE");for(let c of qm)a.exec(c);a.exec("COMMIT"),a.pragma("wal_checkpoint(TRUNCATE)")}finally{a.close()}return i}function rf(e){if(e===0)return null;if(e===1)return"UTF-8";if(e===2)return"UTF-16";if(e===3)return"UTF-32";throw new ue(`unknown position encoding ${e}`)}function af(e){if(e?.aborted)throw new ue("SCIP SQLite conversion aborted")}function As(e,t,n){t.wireType===2?Vm(e,t.valueStart,t.valueEnd,n):t.wireType===0&&n.push(t.varint)}import{readdirSync as of,rmSync as sf}from"fs";import{cpus as cf,totalmem as lf}from"os";import{join as Hs}from"path";function qs(e,t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Invalid compiler worker count");let n=Math.min(e.length,t);return Array.from({length:n},(r,i)=>e.slice(Math.floor(e.length*i/n),Math.floor(e.length*(i+1)/n)))}var uf=2048,df=6*1024**3,pf=2;function Dr(e=process.env){let t=Number.parseInt(e.SCIP_QUERY_TS_COMPILER_SHARD_FILES??"",10);return Number.isSafeInteger(t)&&t>0?t:uf}function Vs(e,t){return e>Math.floor(t*1.5)}function mf(e,t,n=()=>1){if(!Number.isSafeInteger(t)||t<1)throw new Error(`TypeScript compiler shard count must be a positive safe integer; received ${t}.`);let r=[...new Set(e)].sort((l,u)=>l.localeCompare(u));if(t===1||r.length<=t)return ff(r,t);let i=r.map(l=>Math.max(1,n(l))),a=i.reduce((l,u)=>l+u,0),o=[],s=[],c=0;for(let l=0;l<r.length;l+=1){s.push(r[l]),c+=i[l];let u=t-o.length-1,d=r.length-l-1;gf(u,d,c,a,o.length,t)&&(o.push(s),s=[])}return s.length>0&&o.push(s),o}function zs(e){let t=e.targetFiles??Dr(),n=e.shardCount??Math.max(1,Math.ceil(new Set(e.inputPaths).size/Math.max(1,t)));return mf(e.inputPaths,n,e.weightOf).map((r,i)=>{let a=Hs(e.projectRoot,ni(i)),o=`${JSON.stringify({extends:`./${e.rootConfigPath}`,compilerOptions:{incremental:!1},scipQueryEmissionFiles:r},null,2)}
338
+ `;return{configPath:a,content:o,inputPaths:r}})}function Ws(e=process.env,t={totalmemBytes:lf(),cpuCount:cf().length}){let n=Number.parseInt(e.SCIP_QUERY_TS_COMPILER_SHARD_CONCURRENCY??"",10);if(Number.isSafeInteger(n)&&n>0)return n;let r=Math.floor(t.totalmemBytes/2/df),i=Math.floor(t.cpuCount/2);return Math.max(1,Math.min(pf,r,i))}function Ks(e){let t;try{t=of(e)}catch{return}for(let n of t)if(ri(n))try{sf(Hs(e,n))}catch{}}function ff(e,t){return e.length<=t&&t>1?e.map(n=>[n]):e.length>0?[e]:[]}function gf(e,t,n,r,i,a){return e>0&&t>=e&&(n>=r*(i+1)/a||t===e)}import{createHash as tc}from"crypto";import{existsSync as Ar,writeFileSync as ic}from"fs";import{join as Cf}from"path";import{randomUUID as hf}from"crypto";import{existsSync as Xs,rmSync as kr}from"fs";import{join as Js}from"path";var yf=12e4,bf=5,ct=class extends Error{name="TypeScriptIndexMemoryPressureError"},vn=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;mailboxLimits;emitLocally;requireService;localHost=null;constructor(t,n={}){this.projectRoot=ti(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??Rf(),this.runtime=n.runtime??Pf,this.mailboxLimits=n.mailboxLimits??{},this.emitLocally=n.emitLocally,this.requireService=n.requireService===!0}request(t){let n=Ka(this.cacheDir),r=qa(this.cacheDir),i=Xn(n.statePath);if(!Ys(i,this.projectRoot,this.runtime))return this.requestLocally(t);let a=this.runtime.now(),o=a+this.timeoutMs,s=(this.runtime.monotonicNow??w)()+this.timeoutMs,c=Ua("typescript-index-v6",{baseGeneration:this.baseGeneration,request:t}),l=Ga(c),u=Ha(r,{mailboxVersion:$a,operationKey:c,clientId:this.runtime.randomId(),enqueuedAtMs:a,deadlineAtMs:o,protocolVersion:Ht,id:l,baseGeneration:this.baseGeneration,request:t},{nowMs:a,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??w)()<=s;){if(Xs(u.responsePath))try{return Qs(Ge(u.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),l,c,this.baseGeneration,t)}finally{kr(u.responsePath,{force:!0})}let d=Xn(n.statePath);if(!Ys(d,this.projectRoot,this.runtime))return this.abandonPendingRequest(r,l),this.requestLocally(t);this.runtime.sleep(bf)}if(Xs(u.responsePath))try{return Qs(Ge(u.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),l,c,this.baseGeneration,t)}finally{kr(u.responsePath,{force:!0})}return this.abandonPendingRequest(r,l),this.requestLocally(t)}abandonPendingRequest(t,n){try{kr(Js(t.pendingDir,`${n}.json`),{force:!0})}catch{}}requestLocally(t){if(this.requireService)throw new Error("TypeScript incremental index service unavailable; refusing to load the whole compiler graph inside the reindex process. Check scip-query watch --status; run scip-query watch --daemon to start the service explicitly, then retry scip-query reindex");return this.emitLocally?Lr(this.emitLocally(t),t):(this.localHost??=new Xa({projectRoot:this.projectRoot,dbPath:Js(this.cacheDir,"index.db"),currentGeneration:()=>this.baseGeneration}),Lr(ec(this.localHost.handle(this.baseGeneration,t),t.producerIdentity),t))}};function Ys(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null,i=e?Date.parse(e.heartbeatAt):Number.NaN;return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===Ht&&n.isProcessAlive(e.pid)&&Ef(i,n)&&(!e.processIdentity||r!=null&&ye(e.processIdentity,r))}function Qs(e,t,n,r,i){let a=JSON.parse(e);if(a.protocolVersion!==Ht||a.id!==t||a.operationKey!==n||a.ok===!0&&a.baseGeneration!==r)throw new Error("TypeScript index service wrote an incompatible response.");if(a.ok!==!0){let o=typeof a.error=="string"?a.error:"TypeScript index service request failed.";throw Sf(o)?new ct(o):new Error(o)}return Lr(ec(a.response,i.producerIdentity),i)}function Sf(e){let t=e.toLowerCase();return t.includes("out of memory")||t.includes("memory limit")||t.includes("allocation failed")||t.includes("err_worker_out_of_memory")}function Lr(e,t){if(e.producerIdentity!==t.producerIdentity)throw new Error("TypeScript index service wrote an invalid response.");if(!za(e.retainedDocuments,t.affectedFiles))throw new Error("TypeScript index service wrote invalid retained documents.");let n=new Map(t.knownDocuments?.map(a=>[a.relativePath,a]));for(let a of e.retainedDocuments??[]){let o=n.get(a.relativePath);if(!o||o.blobHash!==a.blobHash||o.byteLength!==a.byteLength)throw new Error("TypeScript index service retained a document the requester does not hold.")}let r=[...new Set(t.affectedFiles)].sort(),i=[...e.fragments,...e.retainedDocuments??[]].map(a=>a.relativePath).sort();if(JSON.stringify(i)!==JSON.stringify(r))throw new Error("TypeScript index service omitted or added an affected document.");return e}function Zs(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function ec(e,t){if(!e||typeof e!="object")throw new Error("TypeScript index service wrote an invalid response.");let n=e;if(n.producerIdentity!==t||typeof n.cold!="boolean"||typeof n.durationMs!="number"||!Number.isFinite(n.durationMs)||!Array.isArray(n.fragments))throw new Error("TypeScript index service wrote an invalid response.");let r=new Set,i=n.fragments.map(a=>{if(!a||typeof a.relativePath!="string"||!If(a.bytesBase64)||!Zs(a.occurrences)||!Zs(a.symbols)||!Array.isArray(a.referenceFragments)||!a.referenceFragments.every(vf)||r.has(a.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(a.relativePath);let o=a.bytesBase64===null?null:xf(a.bytesBase64);return{relativePath:a.relativePath,bytes:o,occurrences:a.occurrences,symbols:a.symbols,referenceFragments:a.referenceFragments}});return{producerIdentity:n.producerIdentity,cold:n.cold,durationMs:n.durationMs,fragments:i,...n.retainedDocuments===void 0?{}:{retainedDocuments:n.retainedDocuments}}}function vf(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.targetSymbol=="string"&&!!t.location&&typeof t.location.file=="string"&&Number.isInteger(t.location.line)&&Number.isInteger(t.location.column)}function xf(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function Rf(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:yf}var Pf={now:Date.now,monotonicNow:w,randomId:hf,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:Oe,readProcessIdentity:te};function If(e){return e===null||typeof e=="string"}function Ef(e,t){return Number.isFinite(e)&&t.now()-e<=Wa}var Tf=128,wf=256;function Ff(e,t,n){let r=Nf(e,t);if(!r.eligible)return r;let{previousSnapshot:i,graph:a}=r,o=n??ac(i,e.currentSnapshot,e.producerIdentity,qe(t)),{manifest:s,compilerManifest:c,sourceChanges:l,projectIdentity:u,dependencyGraphUnchanged:d}=o;if(s.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};let p=l.filter(S=>S.kind==="deleted").map(S=>S.path),m=l.filter(S=>S.kind==="modified"),f=o.fallback.fullProject;if(l.length===0&&!f)return{eligible:!1,reason:"change does not affect the configured TypeScript project"};let{effectiveDeletedPaths:x,incrementalManifest:C,affected:g}=Of(e,a,s,c,l,m,p,o.fallback);if(!g.eligible)return g;let b=g.plan,y=new Set(x),R=Mf(b,t,a,y);return R?_f(e,i,C,b,u,R,x,f,d):{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"}}function _f(e,t,n,r,i,a,o,s,c){let l=a.length===1?a[0]:void 0;return{eligible:!0,manifest:n,plan:r,projectIdentity:i,previousFragmentGeneration:e.previousOverlayGeneration??Mn(t,e.producerIdentity),nextFragmentGeneration:Mn(e.currentSnapshot,e.producerIdentity),projects:a,deletedFiles:o,replaceProject:s,dependencyGraphUnchanged:c,...l?{tsconfigPath:l.tsconfigPath,projectArgument:l.projectArgument}:{}}}function Nf(e,t){return t.length===0?{eligible:!1,reason:"workspace project roots unavailable"}:t.length===1&&t[0]==="."&&!e.rootTsconfigExists?{eligible:!1,reason:"root tsconfig unavailable"}:e.previousSnapshot?e.graph===null?{eligible:!1,reason:"dependency graph unavailable"}:e.projectFiles.length===0?{eligible:!1,reason:"prior TypeScript documents unavailable"}:{eligible:!0,previousSnapshot:e.previousSnapshot,graph:e.graph}:{eligible:!1,reason:"prior project snapshot unavailable"}}function Of(e,t,n,r,i,a,o,s){let c=s.fullProject,l=e.currentSnapshot.files.filter(f=>Qr(f.path,e.currentSnapshot.languages)==="source"&&Ae(f.path)).map(f=>f.path).sort(),u=new Set(l),d=c?e.projectFiles.filter(f=>!u.has(f)).sort():[...o].sort(),p=c?r:{...n,changes:i},m=c?{eligible:!0,plan:mn(r.changes.map(f=>f.path).sort(),new Set([...l,...d]),new Set(s.reasons))}:Lf(a,d,t,e.projectFiles);return{effectiveDeletedPaths:d,incrementalManifest:p,affected:m}}function Df(e,t){return e.changes.filter(n=>n.inputKind==="source"&&Ae(n.path)||n.inputKind==="config"&&(!ft(n.path)||t.has(n.path))&&kf(n)||n.inputKind==="ambient")}function kf(e){return e.kind!=="modified"||e.before.semanticHash===void 0||e.after.semanticHash===void 0||e.before.semanticHash!==e.after.semanticHash}function ac(e,t,n,r){let i=me(e,t),a=An(t,n,r),o=An(e,n,r),s={...i,changes:Df(i,r)},c=Ie({...s,projectIdentityChanged:i.projectIdentityChanged||a!==o},{deletedFiles:"closure",maxChanges:wf});return{manifest:i,compilerManifest:s,sourceChanges:i.changes.filter(l=>l.inputKind==="source"&&Ae(l.path)),projectIdentity:a,fallback:c,dependencyGraphUnchanged:!c.fullProject&&Af(i)}}function Lf(e,t,n,r){if(e.length===0)return t.length===0?{eligible:!1,reason:"empty affected set"}:{eligible:!0,plan:{mode:"closure",changedFiles:[...new Set(t)].sort(),affectedFiles:nc(t,n,r),reasons:[]}};let i=fn({version:1,changes:e.filter(oc),projectIdentityChanged:!1,uncertainty:[]},n,r);return i.mode==="full-project"?{eligible:!1,reason:i.reasons.length>0?`affected set widened: ${i.reasons.join(", ")}`:"empty affected set"}:{eligible:!0,plan:{mode:"closure",changedFiles:[...new Set([...e.map(a=>a.path),...t])].sort(),affectedFiles:[...new Set([...i.affectedFiles,...e.map(a=>a.path),...nc(t,n,r)])].sort(),reasons:[]}}}function oc(e){return e.kind!=="modified"?!0:e.before.semanticHash===void 0||e.after.semanticHash===void 0||e.before.semanticHash!==e.after.semanticHash}function Af(e){let t=e.changes.filter(n=>n.inputKind==="source"&&Ae(n.path));return t.length>0&&t.every(n=>n.kind==="modified"&&!oc(n))}function Mf(e,t,n,r){let i=new Map;for(let o of e.affectedFiles){let s=jf(o,t);if(!s)return null;let c=i.get(s)??[];c.push(o),i.set(s,c)}let a=[];for(let[o,s]of[...i].sort(([c],[l])=>c.localeCompare(l))){let c=new Set(s),l=e.changedFiles.filter(p=>!r.has(p)&&(c.has(p)||s.some(m=>rc(m,p,n)))),u=e.changedFiles.filter(p=>r.has(p)&&(c.has(p)||s.some(m=>rc(m,p,n)))),d=s.filter(p=>!r.has(p));if(l.length===0&&u.length===0&&d.length===0)return null;a.push({projectArgument:o,tsconfigPath:o==="."?"tsconfig.json":`${o}/tsconfig.json`,modifiedFiles:l,removedFiles:u,affectedFiles:[...d].sort()})}return a}function nc(e,t,n){let r=new Set(n),i=new Map;for(let[s,c]of t)if(r.has(s))for(let l of c){let u=i.get(l)??new Set;u.add(s),i.set(l,u)}let a=new Set(e),o=[...e];for(let s=0;s<o.length;s+=1){let c=o[s];if(c)for(let l of i.get(c)??[])a.has(l)||(a.add(l),o.push(l))}return[...a].sort()}function jf(e,t){let n=t.filter(a=>a==="."||e===a||e.startsWith(`${a}/`));if(n.length===0)return null;let r=[...new Set(n)].sort((a,o)=>xn(o)-xn(a)||a.localeCompare(o)),i=r[0];return r[1]&&xn(r[1])===xn(i)?null:i}function xn(e){return e==="."?0:e.split("/").filter(Boolean).length}function rc(e,t,n){let r=new Set,i=[e];for(let a=0;a<i.length;a+=1){let o=i[a];if(!(!o||r.has(o))){r.add(o);for(let s of n.get(o)??[]){if(s===t)return!0;r.has(s)||i.push(s)}}}return!1}function sc(e){let t=w();try{if(!Ar(e.previousDbPath)||!Ar(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=Gt();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let{eligibility:a,baseGeneration:o,projectFiles:s,dependencyGraphSnapshot:c,graphMs:l}=Bf(e,r.producerIdentity,n);n=performance.now();let{affectedBatches:u,referenceFragmentsByFile:d,responseDurations:p,anyCold:m,assemblyMs:f,fragmentStoreMs:x,writeMs:C,retainedDocumentCount:g}=Gf(e,a,r.producerIdentity,o),b=performance.now()-n,y={scipPath:e.previousShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,affectedBatches:u,retainedDocumentCount:g,completeScipUpdated:!1,durationMs:w()-t,cold:m,changedFiles:a.plan.changedFiles,affectedFiles:a.plan.affectedFiles,deletedFiles:a.deletedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:a.previousFragmentGeneration,nextFragmentGeneration:a.nextFragmentGeneration,manifest:a.manifest,plan:a.plan,projectFileCount:s.length,dependencyGraphSnapshot:c,dependencyGraphUnchanged:a.dependencyGraphUnchanged,referenceFragmentsByFile:d,timings:{runtimeMs:i,graphMs:l,requestMs:b,serviceMs:p.reduce((R,S)=>R+S,0),assemblyMs:f,fragmentStoreMs:x,writeMs:C}};return e.onStatus(`${a.replaceProject?"Bounded TypeScript project refresh":"Incremental TypeScript index"} emitted ${y.affectedFiles.length-y.deletedFiles.length-g} document(s), retained ${g}, removed ${y.deletedFiles.length}, and produced ${u.length} bounded batch(es) across ${a.projects.length} project(s) in ${(y.durationMs/1e3).toFixed(3)}s (${y.cold?"cold":"warm"} service; whole SCIP deferred; runtime ${i.toFixed(0)}ms, graph ${l.toFixed(0)}ms, request ${b.toFixed(0)}ms, assembly ${f.toFixed(0)}ms, fragments ${x.toFixed(0)}ms, write ${C.toFixed(0)}ms).`),y}catch(n){let r=n instanceof Error?n.message:String(n);if(e.onUnavailable?.(r),n instanceof ct)throw e.onStatus(`Incremental TypeScript index stopped after memory pressure survived one cold Worker retry: ${r}. Preserving the accepted index instead of starting a memory-heavier whole-project rebuild.`),n;return e.onStatus(`Incremental TypeScript index unavailable: ${r}.`),null}}function Bf(e,t,n){let r=zf(e.projectRoot,e.previousSnapshot,e.currentSnapshot),i=e.projectMode==="workspace"?ge(e.projectRoot,e.currentSnapshot.typescriptProjects):["."],a=qe(i),o=r?ac(r,e.currentSnapshot,t,a):void 0,s,c,l,u=new $({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath});try{s=Rt(u,{includeIgnored:!1}).filter(Ae).sort();let f=$f(u,o);c=f.graph,l=f.dependencyGraphSnapshot}finally{u.close()}let d=performance.now()-n,p=Ff({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?i:void 0,previousSnapshot:r,currentSnapshot:e.currentSnapshot,projectFiles:s,graph:c,producerIdentity:t,rootTsconfigExists:Ar(Cf(e.projectRoot,"tsconfig.json")),...e.previousOverlayGeneration===void 0?{}:{previousOverlayGeneration:e.previousOverlayGeneration}},i,o);if(!p.eligible)throw new Error(p.reason);let m=Va(e.previousDbPath);if(!m)throw new Error("published TypeScript base generation unavailable");return{eligibility:p,baseGeneration:m,projectFiles:s,dependencyGraphSnapshot:l,graphMs:d}}function $f(e,t){let n,r;return t?.fallback.fullProject?(r=Ot(e,"none")??void 0,n=new Map):t?.dependencyGraphUnchanged?n=new Map:(r=Nt(e),n=r.graph),{graph:n,dependencyGraphSnapshot:r}}function Uf(e){return e.flatMap(t=>{let n=Ba(t.affectedFiles,Tf);return(n.length>0?n:[[]]).map((i,a)=>({project:t,affectedFiles:i,removedFiles:a===0?t.removedFiles:[],firstForProject:a===0}))})}function Gf(e,t,n,r){let i=new vn({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:r},{requireService:!0}),a=Uf(t.projects),o=Hf(e,t,n),s=[],c=new Map,l=[],u=!1,d=0,p=0,m=0,f=0,x=t.previousFragmentGeneration;for(let[C,g]of a.entries()){let b=i.request({kind:"emit-documents",tsconfigPath:g.project.tsconfigPath,projectArgument:g.project.projectArgument,projectIdentity:t.projectIdentity,producerIdentity:n,modifiedFiles:g.firstForProject?g.project.modifiedFiles:[],removedFiles:g.firstForProject?g.project.removedFiles:[],affectedFiles:g.affectedFiles,knownDocuments:g.affectedFiles.flatMap(v=>o.get(v)??[])});u||=b.cold,d+=b.retainedDocuments?.length??0,l.push(b.durationMs);let y=g.removedFiles.map(v=>({relativePath:v,bytes:null,occurrences:0,symbols:0,referenceFragments:[]})),R=[...b.fragments,...y];if(!t.replaceProject)for(let v of R)c.set(v.relativePath,v.referenceFragments);let S=Vf({input:e,eligibility:t,producerIdentity:n,response:b,fragments:R,batch:g,batchIndex:C,lastBatch:C===a.length-1,previousOverlayGeneration:x});p+=S.assemblyMs,f+=S.writeMs,m+=S.fragmentStoreMs,x=S.nextOverlayGeneration,S.affectedBatch.affectedFiles.length&&s.push(S.affectedBatch)}return{affectedBatches:s,referenceFragmentsByFile:c,responseDurations:l,anyCold:u,retainedDocumentCount:d,assemblyMs:p,fragmentStoreMs:m,writeMs:f}}function Hf(e,t,n){let r=new Map;if(t.replaceProject||t.projects.length!==1||e.projectMode==="workspace"&&ge(e.projectRoot,e.currentSnapshot.typescriptProjects).length!==1)return r;let i=qf(e,t,n);if(i?.producerIdentity!==n||i.projectIdentity!==t.projectIdentity)return r;for(let a of i.overlays)a.blobHash!==null&&r.set(a.relativePath,{...a,blobHash:a.blobHash});return r}function qf(e,t,n){let r=Ti(e.cacheDir,t.previousFragmentGeneration);if(!r&&e.baseShardCurrent&&e.currentSnapshot.languages.length===1&&e.currentSnapshot.languages[0]==="typescript"){let i=Gt();i.available&&i.producerIdentity===n&&(r=Ii({cacheDir:e.cacheDir,generationIdentity:t.previousFragmentGeneration,producerIdentity:n,projectIdentity:t.projectIdentity,packageVersion:i.packageVersion,indexBytes:fe(e.previousIndexPath,{inputKind:"accepted TypeScript index",maxBytes:Ue})}))}return r}function Vf(e){let{input:t,eligibility:n,producerIdentity:r,response:i,fragments:a,batch:o,batchIndex:s,lastBatch:c,previousOverlayGeneration:l}=e,u=performance.now(),d=a.length?ui(i.fragments):null,p=performance.now()-u,m=s===0?t.candidateAffectedScipPath:`${t.candidateAffectedScipPath}.batch-${s}.scip`,f=performance.now();d&&ic(m,d);let x=performance.now()-f,C=performance.now(),g=c?n.nextFragmentGeneration:Wf({previousGenerationIdentity:l,targetGenerationIdentity:n.nextFragmentGeneration,fragments:a,retainedDocuments:i.retainedDocuments});Pi({cacheDir:t.cacheDir,previousGenerationIdentity:l,nextGenerationIdentity:g,producerIdentity:r,projectIdentity:n.projectIdentity,baseShardCurrent:s===0?t.baseShardCurrent:!1,fragments:a,retainedDocuments:i.retainedDocuments,allowProjectIdentityChange:n.replaceProject&&s===0,allowLegacyProjectIdentityMigration:!0});let b=performance.now()-C,y={scipPath:m,affectedFiles:a.map(R=>R.relativePath).sort(),deletedFiles:[...o.removedFiles].sort()};return{assemblyMs:p,writeMs:x,fragmentStoreMs:b,nextOverlayGeneration:g,affectedBatch:y}}function zf(e,t,n){if(!t)return null;let r=new Map(n.files.map(o=>[o.path,o])),i=!1,a=t.files.map(o=>{let s=r.get(o.path);if(o.semanticHash!==void 0||s?.semanticHash===void 0)return o;let c=ht(e,o.path,o.hash);return c===void 0?o:(i=!0,{...o,semanticHash:c})});return i?{...t,files:a}:t}function Wf(e){let t=tc("sha256");t.update("typescript-overlay-batch-v1\0"),t.update(e.previousGenerationIdentity),t.update("\0"),t.update(e.targetGenerationIdentity);for(let n of[...e.fragments].sort((r,i)=>r.relativePath.localeCompare(i.relativePath)))t.update("\0path\0"),t.update(n.relativePath),n.bytes===null?t.update("\0deleted"):(t.update("\0bytes\0"),t.update(tc("sha256").update(n.bytes).digest()));for(let n of[...e.retainedDocuments??[]].sort((r,i)=>r.relativePath.localeCompare(i.relativePath)))t.update("\0retained\0").update(JSON.stringify([n.relativePath,n.blobHash,n.byteLength]));return t.digest("hex")}function Mr(e){let t=Gt();if(!t.available)throw new Error(t.reason);let n=Ei({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:fe(e.baseShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:Ue}),packageVersion:t.packageVersion});ic(e.candidateShardPath,n)}import{closeSync as Kf,existsSync as Rn,fstatSync as Xf,lstatSync as Jf,openSync as Yf,renameSync as Br,rmSync as lt,statSync as Qf,writeSync as Zf}from"fs";import{cpus as eg}from"os";import{join as $r}from"path";var cc=8*1024;function lc(e,t,n){let r=Buffer.from(t,"utf8"),i=()=>Yf(e,"wx",384),a;try{a=i()}catch(o){if(o.code!=="EEXIST")throw o;if(n==="skip")return null;lt(e,{force:!0}),a=i()}try{Zf(a,r);let o=Xf(a);return{path:e,content:r,device:o.dev,inode:o.ino}}finally{Kf(a)}}function tg(e,t){let n=[];try{if(e.temporaryRootConfigContent!==void 0){let r=lc($r(t,"tsconfig.json"),e.temporaryRootConfigContent,"skip");r&&n.push(r)}for(let r of e.temporaryProjectConfigs??[]){let i=lc(r.path,r.content,"replace");i&&n.push(i)}return n}catch(r){for(let i of n.reverse())pc(i);throw r}}function pc(e){if(e)try{let t=Jf(e.path);if(!t.isFile()||t.dev!==e.device||t.ino!==e.inode||t.size!==e.content.byteLength)return;let n;try{n=fe(e.path,{maxBytes:e.content.byteLength,inputKind:"temporary TypeScript index configuration"})}catch{return}if(!n.equals(e.content))return;lt(e.path)}catch(t){if(t.code!=="ENOENT")throw t}}function ng(e,t,n){if(!e.defaultOutputPath)return;let r=$r(t,e.defaultOutputPath);n!==r&&Rn(r)&&Br(r,n)}function rg(e,t,n){if(!e.defaultOutputPath)return null;let r=$r(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return lt(i,{force:!0}),Rn(r)?(Br(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function ig(e){e&&(lt(e.defaultOutputPath,{force:!0}),e.backupPath&&Rn(e.backupPath)&&Br(e.backupPath,e.defaultOutputPath))}function ag(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),r=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(8,Math.max(1,eg().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function mc(e,t,n,r,i){H(i,"Reindex cancelled by its owner.");let a=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath&&l.boundedConcurrency!==void 0),s=e.filter(l=>!l.config.defaultOutputPath&&l.boundedConcurrency===void 0),c=[];if(c.push(...await uc(s,ag(s.length,r),t,n,i)),o.length>0){let l=Math.max(1,Math.min(...o.map(u=>u.boundedConcurrency)));c.push(...await uc(o,l,t,n,i))}for(let l of a)H(i,"Reindex cancelled by its owner."),c.push((await jr(l,t,n,i)).result);return c.sort((l,u)=>e.findIndex(d=>d.id===l.id)-e.findIndex(d=>d.id===u.id))}async function uc(e,t,n,r,i){let a=await Ja(e,Math.max(1,t),s=>jr(s,n,r,i));if(t<=1)return a.map(({result:s})=>s);let o=new Map;for(let s of a.filter(c=>c.result.skipped&&c.retryable)){let c=e.find(l=>l.id===s.result.id);c&&(r(`Retrying ${c.label} indexer serially after parallel failure...`),H(i,"Reindex cancelled by its owner."),o.set(c.id,(await jr(c,n,r,i)).result))}return a.map(({result:s})=>o.get(s.id)??s)}async function jr(e,t,n,r){H(r,"Reindex cancelled by its owner."),n(`Indexing ${e.label} with ${e.resolvedBinary}...`),lt(e.scipPath,{force:!0});let i=rg(e.config,t,e.scipPath),a=[],o=[e.binary,...e.args].join(" "),s=w();try{a=tg(e,t),e.trustedProjectTool&&Vi(t,e.trustedProjectTool);let l=Li(e.binary,e.args),u=await St({command:l.binary,args:l.args,label:`${e.label} indexer`,cwd:t,env:e.env,timeoutMs:cg(),maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024,signal:r});if(u.status!==0){let d=u.stderr.trim();throw new Error(`${e.resolvedBinary} exited with status ${u.status}${d?`:
339
+ ${d}`:""}`)}ng(e.config,t,e.scipPath)}catch(l){if(r?.aborted)throw Si(r,"Reindex cancelled by its owner.");return sg(e,l,n,s,o)}finally{ig(i);for(let l of a.reverse())pc(l)}if(!Rn(e.scipPath))return og(e,n,s,o);let c;try{c=Qf(e.scipPath).size}catch{c=void 0}return{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:w()-s,command:o,...e.outputComposition?{outputComposition:e.outputComposition}:{},outputBytes:c},retryable:!1}}function og(e,t,n,r){let i=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,a=e.label===e.language?i:`${e.label}: ${i}`;return t(`Skipping ${e.label}: ${i}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:w()-n,command:r,...e.outputComposition?{outputComposition:e.outputComposition}:{},skipped:{language:e.language,reason:a}},retryable:!1}}function sg(e,t,n,r,i){let a=t instanceof Error?t.message:String(t),o=a.length<=cc?a:`${a.slice(0,cc)}
340
+ [indexer failure detail truncated]`,s=`${e.resolvedBinary} indexer failed: ${o}`,c=e.label===e.language?s:`${e.label}: ${s}`;return n(`Skipping ${e.label}: ${s}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:w()-r,command:i,...e.outputComposition?{outputComposition:e.outputComposition}:{},skipped:{language:e.language,reason:c}},retryable:lg(t)}}function cg(){let e=Number(process.env.SCIP_QUERY_INDEXER_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):wi.indexer}function lg(e){return e instanceof Fi?e.kind==="spawn"&&dc(e.cause):dc(e)}function dc(e){let t=e?.code;return t==="EAGAIN"||t==="ENOMEM"||t==="EMFILE"||t==="ENFILE"||t==="ETXTBSY"}import{execFileSync as gc}from"child_process";import{homedir as fc,platform as ug}from"os";import{delimiter as dg,join as Pn}from"path";function hc(e,t){let n=e.installMethods,r=xt(e);if(!n?.length)return t(`No auto-install method available for ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1;for(let i of n){if(!i.identity||!i.destination){t(`Refusing ${i.label} installation for ${r}: the installer descriptor lacks an immutable identity or destination.`);continue}if(!ki(i.prerequisite))continue;let a=pg(i);if(t(`Installing immutable ${i.identity} via ${i.label} into ${a}; expected executable: ${r}.`),mg(e,i,r,t))return!0}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function pg(e){if(e.binary==="npm")return Ur("npm",["root","-g"])??e.destination;if(e.binary==="go"){let t=Ur("go",["env","GOBIN"]);if(t)return t;let n=Ur("go",["env","GOPATH"]);if(n)return Pn(n.split(dg)[0],"bin")}return e.binary==="dotnet"?Pn(process.env.DOTNET_CLI_HOME??fc(),".dotnet","tools"):e.binary==="dart"?Pn(process.env.PUB_CACHE??Pn(fc(),".pub-cache"),"bin"):e.destination}function Ur(e,t){try{return gc(e,t,{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4,killSignal:"SIGKILL",env:process.env}).trim()||null}catch{return null}}function mg(e,t,n,r){try{gc(t.binary,t.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:ug()==="win32"});let i=We(e);if(i){let a=i===e.indexerBinary?"":` (using ${i})`;return r(`Successfully installed ${t.identity} via ${t.label}${a}; resolved executable: ${i}.`),!0}r(`${t.label} command completed but ${n} was not found on PATH`)}catch(i){let a=i instanceof Error?i.message:String(i);r(`${t.label} install failed: ${a}`)}return!1}function bg(e,t,n,r){let i=t.mode==="delta"?e.changeJournal?.entries.filter(o=>o.kind!=="add").length??0:0,a=Math.max(0,(n?.files.length??0)-i);r(t.mode==="delta"?`Project fingerprint revalidated ${t.changedPaths.length} changed path(s), reused ${a} accepted file fingerprint(s), and accepted ${t.fingerprint.files.length} input(s)`:`Project fingerprint used full scan: ${t.reason}`)}function Sg(e,t,n){let r=Wc(t),i=Ri(O(I(e),"cache-lifecycle.lock"),{waitMs:r?1e3:3e4});if(!i)throw n?.(),new Le(r?`Could not acquire scip-query cache lifecycle lock for ${I(e)}; another refresh is publishing, so the watcher will retry.`:`Could not acquire scip-query cache lifecycle lock for ${I(e)}. A watch daemon or another reindex may hold it. Run "scip-query watch --stop", retry the reindex, then restart with "scip-query watch --daemon".`);return i}function vg(e,t){let n=Lg(I(e));n.removed>0&&t(`Removed ${n.removed} abandoned reindex workspace(s)`);for(let r of n.errors)t(`Could not remove abandoned reindex workspace: ${r}`)}function bc(e,t){_g(e);let n=Fa(e.paths.outputDb,t);n.state==="failed"&&e.onStatus(`Warning: reindex succeeded, but activity telemetry was not recorded: ${n.reason}`),pi(e.projectRoot,I(e.paths.outputDb))}function xg(e,t,n,r,i,a){let o=_n({trigger:e.trigger,result:"failed",start:n,monotonicStart:r,error:i instanceof Error?i.message:String(i)});Yc(t.metaPath,o);let s=_a(t.outputDb,o);s.state==="failed"&&a(`Warning: failed reindex activity telemetry was not recorded: ${s.reason}`)}function Rg(e,t){let n=e.languages??Pa(e.projectRoot);if(n.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");return t(`Detected languages: ${n.join(", ")}`),n}function Pg(e){return e.maxHeapMb??_i(process.env.NODE_OPTIONS)??8192}async function _c(e){let t=Dc(e);return mi(e.projectRoot,I(t.outputDb),()=>Ig(e))}async function Ig(e){let{projectRoot:t,onStatus:n=console.log}=e,r=Pg(e),i=e.skipAutoInstall===!0||e.installMissing!==!0,a=Dc(e),o=Date.now(),s=w();Cn(I(a.outputScip),{recursive:!0}),Cn(I(a.outputDb),{recursive:!0});let c=Rg(e,n),l=wn(a.metaPath),u=P("reindex.fingerprint",()=>bi(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath},l,e.changeJournal,Bn(a.outputDb)),{languages:c.length}),d=u.fingerprint;bg(e,u,l,n);let p=await Eg({opts:e,paths:a,languages:c,fingerprint:d,onStatus:n}),m=p.snapshot,f=p.releaseBuildLock,x=Sg(a.outputDb,e.trigger,f),C;try{C=await W("reindex.lock",()=>Ih(O(I(a.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:n}),{languages:c.length})}catch(y){throw x.release(),f?.(),y}let g=null,b=eo();try{u.mode==="delta"&&Bn(a.outputDb)!==e.changeJournal?.baseGeneration&&(d=hi(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),u={mode:"full",fingerprint:d,reason:"accepted-generation-changed-before-lock"},m=void 0,f?.(),f=void 0,n("Project fingerprint used full scan: accepted-generation-changed-before-lock")),Oa(a.outputDb,a.outputScip,a.metaPath),vg(a.outputDb,n);let y=null,R=await W("reindex.reuse-check",async()=>(y=await Og({opts:e,paths:a,languages:c,fingerprint:d,start:o,monotonicStart:s,onStatus:n}),y),()=>({languages:c.length,reused:y!==null}));if(R)return bc({snapshot:m,paths:a,projectRoot:t,fingerprint:d,onStatus:n},R),R;Ai()&&await W("reindex.scip-cli-ready",()=>dh(i,n));let S=kg(a);g=S.runDir;let v,h=await W("reindex.fresh",async()=>(v=await Ag({opts:e,languages:c,projectRoot:t,paths:a,tempPaths:S,fingerprint:d,start:o,monotonicStart:s,maxHeapMb:r,skipAutoInstall:i,onStatus:n,writeTelemetry:b}),v),()=>({languages:c.length,reused:v?.reused,skipped:v?.skipped.length}));return bc({snapshot:m,paths:a,projectRoot:t,fingerprint:d,onStatus:n},h),h}catch(y){throw xg(e,a,o,s,y,n),y}finally{g&&Ee(g,{recursive:!0,force:!0}),C(),x.release(),f?.()}}async function Eg(e){let{opts:t,paths:n,languages:r,fingerprint:i,onStatus:a}=e,o=t.projectRoot;if(!Tg(t,n,o))return{snapshot:void 0,releaseBuildLock:void 0};let c=mt(o),l=c?.clean?$t(c,i):void 0;if(c&&!c.clean&&!Oc(n))return Nc({context:c,languages:r,opts:t,paths:n,fingerprint:i,projectRoot:o,onStatus:a,successMessage:"dirty worktree reindex",failurePrefix:"Shared baseline fork failed"}),{snapshot:l,releaseBuildLock:void 0};if(!l)return{snapshot:void 0,releaseBuildLock:void 0};let u=Kn(l);if(u)return wg(u,l,n,i,o,a),{snapshot:l,releaseBuildLock:void 0};Cg(c,r,t,n,i,o,a);let d=await Aa(l);return d.kind==="owner"?{snapshot:l,releaseBuildLock:d.release}:(Fg(d,l,n,o,a),{snapshot:l,releaseBuildLock:void 0})}function Cg(e,t,n,r,i,a,o){e&&!Oc(r)&&Nc({context:e,languages:t,opts:n,paths:r,fingerprint:i,projectRoot:a,onStatus:o,successMessage:"cold worktree reindex",failurePrefix:"Compatible shared baseline fork failed",compatible:!0})}function Tg(e,t,n){return e.skipIfUnchanged!==!1&&!Da(n,t.outputDb)&&yc(t.outputScip)===yc(O(I(t.outputDb),"index.scip"))}function wg(e,t,n,r,i,a){if(!Ng(n,r))try{Ut({snapshot:t,manifest:e,targetCacheDir:I(n.outputDb),targetProjectRoot:i}),a(`Attached shared generation ${t.generationId.slice(0,12)}`)}catch(o){a(`Shared generation attach failed; continuing locally: ${Ce(o)}`)}}function Fg(e,t,n,r,i){if(e.kind==="generation-ready"){let a=Kn(t);if(a)try{Ut({snapshot:t,manifest:a,targetCacheDir:I(n.outputDb),targetProjectRoot:r,action:"waited"}),i(`Attached shared generation ${t.generationId.slice(0,12)} after waiting`)}catch(o){i(`Shared generation attach failed after waiting; continuing locally: ${Ce(o)}`)}}else i("Shared generation build lock timed out; continuing with an isolated local reindex")}function Nc(e){let t=ka(e.context,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath},e.fingerprint);if(t)try{Ut({snapshot:t.snapshot,manifest:t.manifest,targetCacheDir:I(e.paths.outputDb),targetProjectRoot:e.projectRoot,persistLease:!1}),ja(t.snapshot,I(e.paths.outputDb)),e.onStatus(`Forked ${e.compatible?"compatible ":""}shared baseline ${t.snapshot.generationId.slice(0,12)} for ${e.successMessage}`)}catch(n){e.onStatus(`${e.failurePrefix}; continuing locally: ${Ce(n)}`)}}function _g(e){if(e.snapshot)try{let t=mt(e.projectRoot),n=t?$t(t,e.fingerprint):void 0;if(!n||n.generationId!==e.snapshot.generationId){e.onStatus("Skipped shared generation publication because the worktree changed during indexing");return}let r=La({snapshot:e.snapshot,sourceCacheDir:I(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let i=mt(e.projectRoot);return(i?$t(i,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}});Ma(e.snapshot,I(e.paths.outputDb),"built"),e.onStatus(r.kind==="published"?`Published shared generation ${e.snapshot.generationId.slice(0,12)} (${r.achievedDurability})`:`Shared generation ${e.snapshot.generationId.slice(0,12)} was already available (${r.achievedDurability})`)}catch(t){e.onStatus(`Shared generation publication failed; local index remains valid: ${Ce(t)}`)}}function Ng(e,t){if(!B(e.outputScip)||!B(e.outputDb)||Jc(e.metaPath,t)===null)return!1;let n=Z(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function Oc(e){if(!B(e.outputScip)||!B(e.outputDb)||!de(e.metaPath))return!1;let t=Z(e.outputDb,e.metaPath);return t.state!=="invalid"&&t.state!=="drifted"}function Ce(e){return e instanceof Error?e.message:String(e)}async function qr(e,t,n,r,i,a,o,s=!1,c=!1){try{await wa(ss({indexPath:n,evidenceDbPath:o,reuseExisting:i,affectedFiles:a,forceDerivedRebuild:s,compilerFactsUnchanged:c}),{projectRoot:e,dbPath:t,onStatus:r})}catch(l){r(`Runtime-boundary extraction unavailable: ${l instanceof Error?l.message:String(l)}.`)}}function Dc(e){let t=e.outputScip??O(e.projectRoot,"index.scip"),n=e.outputDb??O(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:O(I(n),"meta.json")}}async function Og(e){let t=Z(e.paths.outputDb,e.paths.metaPath),n=Jc(e.paths.metaPath,e.fingerprint);if(e.opts.skipIfUnchanged===!1||!B(e.paths.outputScip)||!B(e.paths.outputDb)||n===null||t.state==="invalid"||t.state==="drifted")return null;let r=jt(e.paths.outputDb,e.fingerprint,e.languages);if(r.state!=="complete")return e.onStatus(Vr("Accepted SQLite index",r)),null;Mt(Dt(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),$n({projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,fingerprint:e.fingerprint}),await qr(e.opts.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0),Z(e.paths.outputDb,e.paths.metaPath).state==="drifted"&&(Bt(e.paths.outputDb,e.paths.metaPath),e.onStatus("Published refreshed SQLite generation after post-index augmentation")),n==="operational-config-compatible"&&(Oh(e.paths.metaPath,e.fingerprint,e.languages,e.opts),Bt(e.paths.outputDb,e.paths.metaPath),e.onStatus("Migrated operational .scipquery.json metadata without rerunning language indexers."));let i=w()-e.monotonicStart,a=_n({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:e.languages,skipped:[]});return Yc(e.paths.metaPath,a),e.onStatus(`Index unchanged; reused existing SQLite index in ${(i/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:i,reused:!0,skipped:[],lastRefresh:a,shards:Dg(e.paths,e.languages,e.opts,e.fingerprint)}}function Dg(e,t,n,r){let i=zr(r,t,n);return t.map(a=>({id:a,language:a,reused:!0,strategy:"reused",fingerprint:ut(i[a]),outputBytes:Te(Wr(e.outputDb,a)),durationMs:0}))}function kg(e){let t=hg(O(I(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:O(t,In(e.outputScip)),tempOutputDb:O(t,In(e.outputDb)),tempMetaPath:O(t,In(e.metaPath))}}function Lg(e){let t=[],n;try{n=Cc(e,{withFileTypes:!0})}catch(i){return{removed:0,errors:[Ce(i)]}}let r=0;for(let i of n)if(!(!i.name.startsWith("reindex-")||!i.isDirectory()))try{Ee(O(e,i.name),{recursive:!0,force:!0}),r+=1}catch(a){t.push(`${i.name}: ${Ce(a)}`)}return{removed:r,errors:t}}async function Ag(e){let t={...process.env,NODE_OPTIONS:Ni(process.env.NODE_OPTIONS,e.maxHeapMb)},n,r=await W("reindex.language-indexers",async()=>(n=await jg(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:i,skippedLanguages:a,reusedLanguages:o,languageFingerprints:s,shards:c,typescriptProjectShardContext:l,incrementalTypeScript:u}=r;if(o.length>0&&e.onStatus(`Reused ${o.length} cached language shard(s): ${o.join(", ")}`),Mg({run:e,indexedOutputs:i,skippedLanguages:a,reusedLanguages:o})){let m=await W("reindex.publish",()=>oh(e,i,a,o,s,l),{mode:"metadata-only",languages:i.length,reused:o.length}),f=m.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(f/1e3).toFixed(1)}s`),{languages:i.map(x=>x.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:f,reused:!0,skipped:a,lastRefresh:m,shards:c,writeTelemetry:e.writeTelemetry}}let d=await W("reindex.publish",()=>ih(e,t,i,a,o,s,l,u),{mode:u?"incremental-or-fallback":"full",languages:i.length,reused:o.length,skipped:a.length}),p=d.durationMs;return e.onStatus(`Done in ${(p/1e3).toFixed(1)}s`),{languages:i.map(m=>m.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:p,reused:!1,skipped:a,lastRefresh:d,shards:c,writeTelemetry:e.writeTelemetry}}function Mg(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!B(e.run.paths.outputScip)||!B(e.run.paths.outputDb))return!1;let t=Z(e.run.paths.outputDb,e.run.paths.metaPath);if(t.state==="invalid"||t.state==="drifted")return!1;let n=new Set(e.reusedLanguages),r=new Set(e.indexedOutputs.map(i=>i.language));return e.run.languages.length>0&&r.size===e.run.languages.length&&e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(i=>n.has(i)&&r.has(i))}async function jg(e,t){let n=e.opts.skipIfUnchanged===!1,{classification:r,reusableOutputs:i,reused:a}=Bg(e,n),{incrementalTypeScript:o,typescriptIncrementalUnavailableReason:s}=$g(e,r,n),c=new Set(o?["typescript"]:[]);Gg(e,a,c,s);let l=Hg(e,r,!!o||a.has("typescript"),n),{preparedRuns:u,skippedLanguages:d,languageOutputScipPaths:p}=ph({languages:e.languages.filter(v=>!a.has(v)&&!c.has(v)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,trustProjectTools:e.opts.trustProjectTools===!0,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:l?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),m=l?u.filter(v=>v.language!=="typescript"||l.missedProjectIds.has(v.id)):u,f=await mc(m,e.projectRoot,e.onStatus,e.opts.indexerConcurrency,e.opts.signal);qg(e,m,f);let x=Vg(e,l,f,p),C=[...f,...x],{indexedOutputs:g}=Sh(C,d),b=o?[{language:"typescript",scipPath:o.scipPath}]:[],y=[...i,...b,...g];vh(y,d,e.languages,e.opts.allowPartial,e.onStatus);let R=zg(o),S=eh(r,[...f,...R],l?{outputDb:e.paths.outputDb,classification:l.classification}:void 0,s);return{indexedOutputs:y,skippedLanguages:d,reusedLanguages:[...a],languageFingerprints:rh(r,e.languages),shards:S,typescriptProjectShardContext:l?{projects:l.allProjects,fingerprints:l.fingerprints}:void 0,incrementalTypeScript:o??void 0}}function Bg(e,t){let n=Yg({paths:e.paths,projectRoot:e.projectRoot,languages:e.languages,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath,projectFingerprint:e.fingerprint});if(t)for(let[a,o]of n)o.reused&&n.set(a,{...o,reused:!1,reason:"forced reindex requested"});let r=[],i=new Set;for(let[a,o]of n)o.reused&&(r.push({language:a,scipPath:o.scipPath}),i.add(a));for(let a of i)e.onStatus(`Reusing cached ${a} SCIP shard (language inputs unchanged).`);return{classification:n,reusableOutputs:r,reused:i}}function $g(e,t,n){let r=t.get("typescript"),{incrementalGenerationUsable:i,baseShardCurrent:a,previousOverlay:o}=Ug(e.paths),s;return n&&r&&!r.reused&&(s="forced reindex rebuilds from the compilers"),{incrementalTypeScript:!n&&r&&!r.reused&&i?sc({projectRoot:e.projectRoot,cacheDir:I(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:r.scipPath,candidateShardPath:we(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:we(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:a,previousSnapshot:wn(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,...o,onStatus:e.onStatus,onUnavailable:l=>{s=l}}):null,typescriptIncrementalUnavailableReason:s}}function Ug(e){let t=Z(e.outputDb,e.metaPath),n=de(e.metaPath),r=t.state==="legacy"||t.state==="current",i=n?.scipCompanion!=="deferred"&&(t.state!=="current"||t.generation.publication?.scipCompanion!=="deferred"),a=t.state==="current"&&t.generation.publication?.scipCompanion==="deferred"&&t.generation.publication.typescriptOverlayGeneration?{previousOverlayGeneration:t.generation.publication.typescriptOverlayGeneration}:{};return{incrementalGenerationUsable:r,baseShardCurrent:i,previousOverlay:a}}function Gg(e,t,n,r){if(e.opts.allowExpensiveRebuild===!1){let i=e.languages.filter(a=>!t.has(a)&&!n.has(a));if(i.length>0){let a=i.length===1&&i[0]==="typescript"&&r?`: ${r}`:"";throw new Error(`Incremental indexing is unavailable for ${i.join(", ")}${a}. The accepted index was preserved because whole-project rebuilds are disabled; run scip-query reindex --allow-expensive-rebuild only when you explicitly want that fallback.`)}}}function Hg(e,t,n,r){let i=n?void 0:Wg(e,t);return i&&r?{...i,classification:new Map([...i.classification].map(([o,s])=>[o,s.reused?{...s,reused:!1,reason:"forced reindex requested"}:s])),reusedProjects:[],missedProjectIds:new Set(i.allProjects.map(o=>`typescript:${o}`))}:i}function qg(e,t,n){if(Oi())for(let r of n)Di({type:"span",name:`reindex.language-indexer.${r.id}`,durationMs:Math.round(r.durationMs),ok:!r.skipped,language:r.language,indexerCommand:r.command,outputBytes:r.outputBytes,measurement:"indexer-run-result"})}function Vg(e,t,n,r){let i=[];if(t){Xg(e.paths.outputDb,n,e.writeTelemetry);let a=r.typescript??e.tempPaths.tempOutputScip;i=Jg({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:a,reusedProjects:t.reusedProjects,writeTelemetry:e.writeTelemetry})}return i}function zg(e){return e?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:e.scipPath,outputScipPath:e.scipPath,durationMs:e.durationMs,command:"watch-service:typescript-index",outputBytes:Te(e.scipPath)??void 0,producedOutputBytes:Te(e.affectedScipPath)??void 0}]:[]}function Wg(e,t){let n=t.get("typescript");if(!n||n.reused||n.cacheIntegrityFailed||e.opts.typescriptProjectMode!=="workspace")return;let r=ge(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=_s(e.projectRoot,r),a=Ts(n.fingerprint.files,r),o=ws(r,i),s=Fs(r,a,o),c=de(e.paths.metaPath),u=Kg(c,s,f=>B(Fn(e.paths.outputDb,f))),d=[...u.entries()].filter(([,f])=>f.reused).map(([f])=>f),p=new Set(d),m=new Set(r.filter(f=>!p.has(f)).map(f=>`typescript:${f}`));return{allProjects:r,fingerprints:s,classification:u,reusedProjects:d,missedProjectIds:m}}function Kg(e,t,n){let r=new Map;for(let i of Object.keys(t)){let a=t[i];if(!e){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:a});continue}let o=e.version===_e&&pt(e.fingerprint)?.typescriptSymbolIdentityVersion===6&&Dn(e).typescriptProjectShardReuse?e.typescriptProjectShards?.[i]:void 0;if(!o){r.set(i,{reused:!1,reason:"no cached fingerprint for this project",fingerprint:a});continue}if(!n(i)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:a});continue}if(j(o)!==j(a)){r.set(i,{reused:!1,reason:"project inputs changed since last index",fingerprint:a});continue}r.set(i,{reused:!0,fingerprint:a})}return r}function Xg(e,t,n){for(let r of t){if(r.skipped||!r.id.startsWith("typescript:"))continue;let i=r.id.slice(11),a=Fn(e,i);Cn(I(a),{recursive:!0}),ie(n,re(r.scipPath,a,void 0,{shareImmutable:!0}))}}function Jg(e){return e.reusedProjects.map((t,n)=>{let r=Fn(e.outputDb,t),i=we(e.tempOutputScip,"typescript-project-cached",n);return ie(e.writeTelemetry,re(r,i,void 0,{shareImmutable:!0})),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:Te(i)??void 0}})}function Yg(e){let t=de(e.paths.metaPath),n=zr(e.projectFingerprint,e.languages,e),r=t&&B(e.paths.outputDb)?jt(e.paths.outputDb,e.projectFingerprint,e.languages):null,i=new Map;for(let a of e.languages){let o=Wr(e.paths.outputDb,a),s=n[a];i.set(a,Qg(e.projectRoot,a,s,o,t,r))}return i}function Qg(e,t,n,r,i,a){return i?i.version!==_e?{reused:!1,reason:`metadata version ${String(i.version??"unknown")} predates per-language shard caching`,fingerprint:n,scipPath:r}:!Dn(i).languageShardReuse||!i.languageFingerprints?{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:n,scipPath:r}:Zg(e,t,n,r,i.languageFingerprints[t],a):{reused:!1,reason:"no reindex metadata found",fingerprint:n,scipPath:r}}function Zg(e,t,n,r,i,a){if(!i)return{reused:!1,reason:"no cached fingerprint for this language",fingerprint:n,scipPath:r};if(!B(r))return{reused:!1,reason:"cached shard file missing on disk",fingerprint:n,scipPath:r};let o=t==="typescript"?Fh(e,i):i;return j(o)!==j(n)?{reused:!1,reason:"language inputs changed since last index",fingerprint:n,scipPath:r}:a?.state==="unavailable"||a?.state==="incomplete"&&a.affectedLanguages.includes(t)?{reused:!1,reason:Vr("accepted SQLite index",a),cacheIntegrityFailed:!0,fingerprint:n,scipPath:r}:{reused:!0,fingerprint:n,scipPath:r}}function eh(e,t,n,r){let i=[];for(let[a,o]of e)o.reused&&i.push({id:a,language:a,reused:!0,strategy:"reused",fingerprint:ut(o.fingerprint),outputBytes:Te(o.scipPath),durationMs:0});if(th(i,e,t,n,r),n)for(let[a,o]of n.classification)o.reused&&i.push({id:`typescript:${a}`,language:"typescript",reused:!0,strategy:"reused",fingerprint:ut(o.fingerprint),outputBytes:Te(Fn(n.outputDb,a)),durationMs:0});return i}function th(e,t,n,r,i){for(let a of n){let o=t.get(a.language),s=r&&a.id.startsWith("typescript:")?a.id.slice(11):null,c=s?r.classification.get(s):void 0;e.push({id:a.id,language:a.language,reused:!1,strategy:a.command==="watch-service:typescript-index"?"incremental":"full",missReason:c?.reason??o?.reason??a.skipped?.reason,fallbackReason:a.language==="typescript"?i:void 0,fingerprint:nh(c,o),outputBytes:a.outputBytes??null,producedOutputBytes:a.producedOutputBytes,durationMs:a.durationMs,command:a.command})}}function nh(e,t){return e?ut(e.fingerprint):t?ut(t.fingerprint):"unknown"}function ut(e){return gg("sha256").update(j(e)).digest("hex").slice(0,16)}function Te(e){try{return wc(e).size}catch{return null}}function rh(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}async function ih(e,t,n,r,i,a,o,s){H(e.opts.signal,"Reindex cancelled by its owner.");let c=!s||s.completeScipUpdated,l=!1;c&&(l=P("reindex.publish.scip-output",()=>{let h=uh({run:e,indexedOutputs:n,incrementalTypeScript:s,typescriptReused:i.includes("typescript")});return vc(e.paths.outputDb,h,e.writeTelemetry),xc(h,e.tempPaths.tempOutputScip,e.onStatus)}));let u=await W("reindex.publish.sqlite-output",()=>xh({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:s,completeScipAvailable:c,completeScipSanitized:l,materializeFullFallback:async()=>{if(H(e.opts.signal,"Reindex cancelled by its owner."),!s||s.completeScipUpdated)return l;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),Mr({cacheDir:I(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let h=n.map(E=>E.language==="typescript"?{language:E.language,scipPath:s.candidateScipPath}:E);return vc(e.paths.outputDb,h,e.writeTelemetry),l=xc(h,e.tempPaths.tempOutputScip,e.onStatus),l}}));H(e.opts.signal,"Reindex cancelled by its owner.");let d=Ah(u),{metadata:p,pruneProjects:m}=Ac({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:a,typescriptProjectShardContext:o});p.scipCompanion=d?"deferred":"current",dt(e.tempPaths.tempMetaPath,p);let f=P("reindex.publish.auxiliary-documents",()=>Mt(Dt(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus})),x=P("reindex.publish.source-checkpoints",()=>$n({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,fingerprint:e.fingerprint,changedFiles:s?.changedFiles}));await W("reindex.publish.runtime-boundaries",async()=>{let h=s?.plan.mode==="full-project";h&&e.onStatus("Rebuilding compiler-derived runtime-boundary relationships while retaining unchanged per-file extraction facts."),await qr(e.projectRoot,e.tempPaths.tempOutputDb,e.tempPaths.tempOutputScip,e.onStatus,!1,h?s?.changedFiles:s?.affectedFiles,O(I(e.paths.outputDb),ci),h,u.mode==="incremental"&&u.compilerFactsUnchanged===!0&&f.result.inserted===0&&x===0)});let C=P("reindex.publish.sqlite-layout",()=>Er(e.tempPaths.tempOutputDb,{analyze:ah(s,u.mode)}));kh(C,e),P("reindex.publish.coverage",()=>jc(e,e.tempPaths.tempOutputDb,n.map(h=>h.language)));let g,b=null;u.mode==="incremental"&&s&&P("reindex.publish.reference-fragments",()=>{if(s.dependencyGraphUnchanged){let T=new $({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});try{b=Ln(T),e.onStatus("Preserved exact TypeScript reference fragments and dependency relationships because only trivia changed.")}finally{T.close()}return}let h=null,E=null;try{h=P("reindex.publish.reference-fragments.open-candidate",()=>new $({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip})),E=P("reindex.publish.reference-fragments.open-evidence",()=>new $({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip})),g=s.dependencyGraphSnapshot?P("reindex.publish.reference-fragments.dependency-graph",()=>oa(h,s.dependencyGraphSnapshot,Sc(s,u),s.deletedFiles))??void 0:void 0;let T=new Set(s.deletedFiles),z=T.size===0?s.referenceFragmentsByFile:new Map([...s.referenceFragmentsByFile].filter(([ee])=>!T.has(ee))),_=P("reindex.publish.reference-fragments.seed",()=>ca(h,e.fingerprint,z,E,g,new Set(s.affectedFiles)));e.onStatus(`Cached exact TypeScript reference fragments for ${_.affectedFiles} affected document(s) and carried ${_.carriedFiles} unaffected document(s) forward.`),_.skippedAffectedFiles>0&&e.onStatus(`Skipped exact TypeScript reference fragment prefill for ${_.skippedAffectedFiles} affected document(s) whose semantic identity was unavailable.`)}catch(T){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${T instanceof Error?T.message:String(T)}.`)}finally{h?.close(),E?.close()}});let y=wn(e.paths.metaPath);u.mode==="incremental"&&s||await kc({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousSnapshot:y,currentSnapshot:e.fingerprint,onStatus:e.onStatus});let R=P("reindex.publish.affected-shadow",()=>u.mode==="incremental"&&s?Ph(s,u.changedDocumentPaths):vr({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:y,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"})),S=_n({trigger:e.opts.trigger,result:"rebuilt",start:e.start,monotonicStart:e.monotonicStart,languages:n.map(h=>h.language),skipped:[...r]});p.lastRefresh=S,p.updatedAt=S.completedAt,P("reindex.publish.metadata",()=>{Mc(e),Bc(e.paths.outputDb,m),dt(e.tempPaths.tempMetaPath,p)});let v=P("reindex.publish.generation-handoff",()=>Na({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath,preserveOutputScip:u.mode==="incremental"&&u.scipCompanion==="deferred",publication:u.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:u.converterDurationMs,affectedDocumentCount:s?.affectedFiles.length,changedDocumentCount:u.changedDocumentPaths.length,producerDurationMs:s?.timings.serviceMs,materializationDurationMs:s?.durationMs,patchDurationMs:u.patchDurationMs,scipCompanion:u.scipCompanion,...u.scipCompanion==="deferred"&&s?{typescriptOverlayGeneration:s.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:u.converterDurationMs,scipCompanion:"current",...u.fallbackReason?{fallbackReason:u.fallbackReason}:{}}}));return Lh(v,e),u.mode==="incremental"&&s&&P("reindex.publish.dependency-graph",()=>{let h=null;try{h=new $({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let E=Sc(s,u),T=!1;s.dependencyGraphUnchanged?T=Bh(h,b,e):s.dependencyGraphSnapshot?T=aa(h,s.dependencyGraphSnapshot,E,g):Nt(h),s.dependencyGraphUnchanged||e.onStatus(T?`Carried the dependency graph forward by replacing ${E.length} changed dependency owner(s).`:"Materialized a fresh dependency graph for the accepted generation because no compatible prior graph was available.")}catch(E){e.onStatus(`Dependency graph carry-forward unavailable: ${E instanceof Error?E.message:String(E)}. The next graph consumer will rebuild it.`)}finally{h?.close()}}),P("reindex.publish.cleanup",()=>{Ci(I(e.paths.outputDb),u.mode==="incremental"&&u.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),di(I(e.paths.outputDb),s?.completeScipUpdated?[s.nextFragmentGeneration]:[])}),P("reindex.publish.shadow-telemetry",()=>Lc(e.paths.outputDb,R,e.onStatus)),S}function Sc(e,t){return t.mode==="incremental"&&t.compilerFactsUnchanged&&e.dependencyGraphSnapshot?.sourceEdges==="none"?[]:e.plan.mode==="full-project"&&e.plan.reasons.length===0?e.changedFiles:e.affectedFiles}function ah(e,t){return t!=="incremental"||!e||e.plan.mode==="full-project"?!0:e.affectedFiles.length*20>=e.projectFileCount}async function oh(e,t,n,r,i,a){let o=wn(e.paths.metaPath),s=null;try{ie(e.writeTelemetry,re(e.paths.outputDb,e.tempPaths.tempOutputDb))}catch(p){s=us("reused","oracle-error",`Could not snapshot the prior database: ${p instanceof Error?p.message:String(p)}`)}Mt(Dt(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),await qr(e.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0);let c=Er(e.paths.outputDb);c.added.length>0&&e.onStatus(`Added SQLite query indexes: ${c.added.join(", ")}`),c.removed.length>0&&e.onStatus(`Removed redundant SQLite indexes: ${c.removed.join(", ")}`),jc(e,e.paths.outputDb,t.map(p=>p.language)),s==null&&await kc({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,previousSnapshot:o,currentSnapshot:e.fingerprint,onStatus:e.onStatus}),s??=vr({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.paths.outputDb,candidateIndexPath:e.paths.outputScip,previousSnapshot:o,currentSnapshot:e.fingerprint,refreshResult:"reused"});let l=_n({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:u,pruneProjects:d}=Ac({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:a,lastRefresh:l});return u.scipCompanion=sh(e.paths),Mc(e),Bc(e.paths.outputDb,d),dt(e.paths.metaPath,u),Bt(e.paths.outputDb,e.paths.metaPath),Lc(e.paths.outputDb,s,e.onStatus),l}function sh(e){let t=de(e.metaPath)?.scipCompanion;if(t)return t;let n=Z(e.outputDb,e.metaPath);return n.state==="current"&&n.generation.publication?.scipCompanion==="deferred"?"deferred":"current"}async function kc(e){if(!B(e.previousDbPath))return;let t=me(e.previousSnapshot,e.currentSnapshot);if(t.changes.length===0||Ie(t).fullProject)return;let n=null;try{if(n=new $({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),Ot(n))return;let r=await W("reindex.publish.affected-shadow.warm-sources",()=>sa(n,{yieldToEventLoop:()=>new Promise(i=>setImmediate(i))}));e.onStatus(`Persisted import products for ${r.files} document(s) before the affected-set shadow.`)}catch(r){e.onStatus(`Affected-set shadow import warm-up unavailable: ${r instanceof Error?r.message:String(r)}.`)}finally{n?.close()}}function wn(e){return pt(de(e)?.fingerprint)}function Lc(e,t,n){try{ds(e,t),t.status==="evaluated"?n(`Affected-set shadow: ${(t.evaluation.recall*100).toFixed(1)}% recall; ${t.plan.affectedFiles.length} predicted, ${t.comparison.changedFiles.length} changed.`):n(`Affected-set shadow unavailable: ${t.reason}.`)}catch(r){n(`Affected-set shadow telemetry unavailable: ${r instanceof Error?r.message:String(r)}`)}}function Ac(e){let t=ch({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:_e,status:e.skippedLanguages.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.run.fingerprint,sqliteLayoutVersion:1,languageFingerprints:e.languageFingerprints,typescriptProjectShards:t.field,requestedLanguages:e.run.languages,indexedLanguages:e.indexedOutputs.map(n=>n.language),skipped:[...e.skippedLanguages],lastRefresh:e.lastRefresh},pruneProjects:t.pruneProjects}}function Mc(e){H(e.opts.signal,"Reindex cancelled by its owner.");let t=yi(e.projectRoot,e.fingerprint);if(j(t)===j(e.fingerprint))return;let n=new Map(e.fingerprint.files.map(a=>[a.path,a])),r=new Map(t.files.map(a=>[a.path,a])),i=[...new Set([...n.keys(),...r.keys()])].filter(a=>j(n.get(a))!==j(r.get(a))).slice(0,5);throw new Error(`Project inputs changed during reindex (${i.join(", ")||"unknown path"}); refusing to publish artifacts built from a different filesystem snapshot.`)}function jc(e,t,n){let r=jt(t,e.fingerprint,n);if(r.state!=="complete")throw new Error(`${Vr("Candidate SQLite index",r)} Refusing to publish it.`)}function Vr(e,t){if(t.state==="unavailable")return`${e} document coverage could not be verified (${t.reason}); rebuilding cached language shards.`;let n=t.missingPaths.length>0?` First missing path: ${t.missingPaths[0]}.`:"";return`${e} is missing ${t.missingDocumentCount} fingerprinted source document${t.missingDocumentCount===1?"":"s"}; rebuilding affected language shards.${n}`}function ch(e){if(e.mode!=="workspace")return{field:void 0,pruneProjects:null};if(e.skippedLanguages.some(t=>t.language==="typescript"))return{field:void 0,pruneProjects:null};if(e.reusedLanguages.includes("typescript")){let t=de(e.metaPath),n=t?.version===_e?t.typescriptProjectShards:void 0;return{field:n,pruneProjects:n?Object.keys(n):[]}}return e.context?{field:e.context.fingerprints,pruneProjects:e.context.projects}:{field:void 0,pruneProjects:[]}}function Bc(e,t){let n=Xc(e);if(t===null){Ee(n,{recursive:!0,force:!0});return}let r;try{r=Cc(n)}catch{return}for(let i of lh(r,t))Ee(O(n,i),{force:!0})}function lh(e,t){let n=new Set(t.map(r=>`${Fr(r)}.scip`));return e.filter(r=>!n.has(r))}function uh(e){if(e.incrementalTypeScript?.completeScipUpdated)return[...e.indexedOutputs];let t=e.indexedOutputs.find(o=>o.language==="typescript");if(!t)return[...e.indexedOutputs];if(!e.typescriptReused)return[...e.indexedOutputs];let n=Z(e.run.paths.outputDb,e.run.paths.metaPath),r=n.state==="current"?n.generation.publication?.typescriptOverlayGeneration:void 0;if(!(n.state==="current"?n.generation.publication?.scipCompanion==="deferred":de(e.run.paths.metaPath)?.scipCompanion==="deferred")||!r)return[...e.indexedOutputs];let a=we(e.run.tempPaths.tempOutputScip,"typescript-deferred",0);return e.run.onStatus("Materializing the deferred whole TypeScript SCIP companion for complete publication..."),Mr({cacheDir:I(e.run.paths.outputDb),generationIdentity:r,baseShardPath:t.scipPath,candidateShardPath:a}),e.indexedOutputs.map(o=>o.language==="typescript"?{language:o.language,scipPath:a}:o)}function vc(e,t,n){for(let r of t){let i=Wr(e,r.language);Cn(I(i),{recursive:!0}),r.scipPath!==i&&ie(n,re(r.scipPath,i,void 0,{shareImmutable:!0}))}}async function dh(e,t){let n=ji();if(n){let r=jh(n,e,t);r&&await r;return}if(Fc()==="win32")throw new Error("The scip CLI was not found. On Windows it ships via the npm sidecar package scip-query-scip-windows (installed automatically with scip-query). Reinstall scip-query with optional dependencies enabled, or follow 'scip-query setup' guidance for the exact sidecar package version, or set SCIP_QUERY_SCIP_BIN to a local scip.exe path.");if(e)throw new Error(`The scip CLI is required but not found on PATH.
291
341
  To install the reviewed version, run: scip-query reindex --install-missing
292
- Or install manually from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!await wn(t))throw new Error(`The scip CLI is required but could not be installed.
293
- Install manually from: https://github.com/sourcegraph/scip/releases/tag/${Ce}`)}function Xc(e){let t=[],n=[],r=e.languages.map((i,o)=>({language:i,scipPath:e.languages.length>1?ne(e.tempOutputScip,i,o):e.tempOutputScip})),a=Object.fromEntries(r.map(({language:i,scipPath:o})=>[i,o]));for(let{language:i,scipPath:o}of r){let s=Yc({...e,language:i,scipPath:o});for(let c of s)"skipped"in c?Pa(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:a}}function Yc(e){if(e.language!=="typescript")return[nt({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.typescriptProjectMode==="workspace",n=t?e.preDiscoveredTypeScriptProjects??X(e.projectRoot,e.typescriptProjects):["."];return n.length===0?[nt({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})]:(t&&e.onStatus(`Indexing TypeScript workspace as ${n.length} project shard(s).`),n.flatMap((r,a)=>{let i=t?`typescript:${r}`:"typescript",o=t?`typescript (${r})`:"typescript",s=t?ne(e.tempOutputScip,"typescript-project",a):e.scipPath,c={...e,id:i,label:o,scipPath:s,outputScipPath:e.scipPath,pnpmWorkspaces:!1};if(!t&&r==="."&&!e.pnpmWorkspaces){let d=Kc(e,c);if(d)return d}return[nt({...c,...t?{projectPath:r}:{}})]}))}function Qc(e,t,n,r){let a=n.filter(s=>s.shardInputPaths!==void 0);if(a.length===0)return;let i=new Map(r.filter(s=>!s.skipped).map(s=>[s.id,s.durationMs])),o=[];for(let s of a){let c=i.get(s.id);if(c===void 0||!(c>0))return;o.push({inputPaths:s.shardInputPaths,durationMs:c})}try{let s=Ti(o,c=>{try{return Qt(O(t,c)).size}catch{return 1}});s&&vi(e,s)}catch{}}function Kc(e,t){let n=$t(),r=mt(e.projectRoot,"single");if(!r||!Pi(r.size,n))return null;Ci(e.projectRoot);let a=wi(),i=Ri(r.size,n,a),o=e.typescriptShardCostDir?Ii(e.typescriptShardCostDir):null,s=_i(o),c=xi({projectRoot:e.projectRoot,rootConfigPath:"tsconfig.json",inputPaths:[...r],targetFiles:n,shardCount:i,weightOf:l=>{let g=1;try{g=Qt(O(e.projectRoot,l)).size}catch{}return s(l,g)}}),d=Math.min(a,c.length);return e.onStatus(`Indexing ${r.size} TypeScript inputs as ${c.length} ${o?"cost-balanced":"byte-balanced"} compiler shard(s), ${d} at a time.`),c.map((l,g)=>nt({...t,id:`typescript-compiler-shard:${g}`,label:`typescript compiler shard ${g+1}/${c.length}`,scipPath:ne(e.tempOutputScip,"typescript-compiler-shard",g),projectPath:l.configPath,temporaryProjectConfigs:[{path:l.configPath,content:l.content}],boundedConcurrency:d,outputComposition:"protobuf-concatenate",shardInputPaths:l.inputPaths}))}function nt(e){let t=_t(e.language),n=Oe(t),r=Ln(t,e.projectRoot),a=e.trustProjectTools&&r?An(t,e.projectRoot):null,i=he(t);if(!a&&!i&&r){let l=`${n} is available only as repository-local code at ${r}. Review that exact tool and rerun with --trust-project-tools.`;return e.onStatus(`Skipping ${e.language}: ${l}`),{skipped:{language:e.language,reason:l}}}if(!a&&!i&&!Nn(t)){if(e.skipAutoInstall){let l=`${n} not found on PATH. To install the reviewed version, run: scip-query reindex --install-missing${t.installUrl?` (manual source: ${t.installUrl})`:""}`;return e.onStatus(`Skipping ${e.language}: ${l}`),{skipped:{language:e.language,reason:l}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!Vi(t,e.onStatus)){let l=`${n} could not be auto-installed. ${t.installUrl?`Install manually from ${t.installUrl}`:`Install ${n} and put it on PATH.`}`;return e.onStatus(`Skipping ${e.language}: ${l}`),{skipped:{language:e.language,reason:l}}}}let o=a?.canonicalPath??he(t);if(!o){let l=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${l}`),{skipped:{language:e.language,reason:l}}}let{binary:s,args:c}=t.indexArgs({projectRoot:e.projectRoot,outputPath:e.scipPath,pnpmWorkspaces:e.pnpmWorkspaces,indexerBinary:o,projectPath:e.projectPath,configPath:e.language==="clojure"?e.clojureConfigPath:void 0}),d=zr({language:e.language,projectPath:e.projectPath,pnpmWorkspaces:e.pnpmWorkspaces});if(a&&!a.executable){let l=`${a.relativePath} is not executable; refusing project-local indexer.`;return e.onStatus(`Skipping ${e.language}: ${l}`),{skipped:{language:e.language,reason:l}}}return a&&e.onStatus(`Trusted project-local ${e.language} indexer ${a.relativePath} (${a.sha256.slice(0,12)}\u2026, ${a.canonicalPath}).`),{prepared:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,config:t,resolvedBinary:o,binary:s,args:c,env:Gn(t,e.env,o),...d===void 0?{}:{temporaryRootConfigContent:d},...e.temporaryProjectConfigs===void 0?{}:{temporaryProjectConfigs:e.temporaryProjectConfigs},...e.boundedConcurrency===void 0?{}:{boundedConcurrency:e.boundedConcurrency},...e.outputComposition?{outputComposition:e.outputComposition}:{},...e.shardInputPaths===void 0?{}:{shardInputPaths:e.shardInputPaths},...a?{trustedProjectTool:a}:{}}}}function Vc(e,t){let n=new Set(e.filter(i=>i.skipped&&i.outputComposition).map(i=>`${i.language}\0${i.outputScipPath}`)),r=new Map;for(let i of e)if(i.skipped)Pa(t,i.skipped);else{let o=`${i.language}\0${i.outputScipPath}`;if(n.has(o))continue;let s=r.get(o)??{language:i.language,outputScipPath:i.outputScipPath,scipPaths:[],concatenate:!0};s.scipPaths.push(i.scipPath),i.outputComposition!=="protobuf-concatenate"&&(s.concatenate=!1),r.set(o,s)}let a=[];for(let i of r.values())if(i.scipPaths.length>1)i.concatenate?ir(i.scipPaths,i.outputScipPath):rr(i.scipPaths,i.outputScipPath),a.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&pa(o,i.outputScipPath),a.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:a}}function Pa(e,t){let n=e.find(r=>r.language===t.language);if(!n){e.push(t);return}n.reason.includes(t.reason)||(n.reason=`${n.reason}; ${t.reason}`)}function Zc(e,t,n,r,a){if(e.length===0){let i=t.map(o=>` - ${o.language}: ${o.reason}`).join(`
342
+ Or install manually from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!await Gi(t))throw new Error(`The scip CLI is required but could not be installed.
343
+ Install manually from: https://github.com/sourcegraph/scip/releases/tag/${vt}`)}function ph(e){let t=[],n=[],r=e.languages.map((a,o)=>({language:a,scipPath:e.languages.length>1?we(e.tempOutputScip,a,o):e.tempOutputScip})),i=Object.fromEntries(r.map(({language:a,scipPath:o})=>[a,o]));for(let{language:a,scipPath:o}of r){let s=mh({...e,language:a,scipPath:o});for(let c of s)"skipped"in c?$c(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function mh(e){if(e.language!=="typescript")return[En({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.typescriptProjectMode==="workspace",n=t?e.preDiscoveredTypeScriptProjects??ge(e.projectRoot,e.typescriptProjects):["."];return n.length===0?[En({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})]:(t&&e.onStatus(`Indexing TypeScript workspace as ${n.length} project shard(s).`),n.flatMap((r,i)=>{let a=t?`typescript:${r}`:"typescript",o=t?`typescript (${r})`:"typescript",s=t?we(e.tempOutputScip,"typescript-project",i):e.scipPath,c={...e,id:a,label:o,scipPath:s,outputScipPath:e.scipPath,pnpmWorkspaces:!1};if(!t&&r==="."&&!e.pnpmWorkspaces){let l=fh(e,c);if(l)return l}return[En({...c,...t?{projectPath:r}:{}})]}))}function fh(e,t){if(e.trustProjectTools&&Un(hn("typescript"),e.projectRoot))return null;let n=Dr(),r=ii(e.projectRoot,"single");if(!r||!Vs(r.size,n))return null;Ks(e.projectRoot);let i=Ws(),a=zs({projectRoot:e.projectRoot,rootConfigPath:"tsconfig.json",inputPaths:[...r],targetFiles:n,weightOf:s=>{let c=1;try{c=wc(O(e.projectRoot,s)).size}catch{}return c}}),o=Math.min(i,a.length);return e.onStatus(`Indexing ${r.size} TypeScript inputs as ${a.length} byte-balanced compiler shard(s), ${o} at a time.`),qs(a,o).map((s,c)=>{let l=En({...t,id:`typescript-compiler-worker:${c}`,label:`typescript compiler worker ${c+1}/${o} (${s.length} emission batches)`,scipPath:we(e.tempOutputScip,"typescript-compiler-shard",c),projectPath:s[0].configPath,temporaryProjectConfigs:s.map(u=>({path:u.configPath,content:u.content})),boundedConcurrency:o,outputComposition:"protobuf-concatenate"});return"prepared"in l&&s.length>1&&(l.prepared.args=l.prepared.args.filter(u=>u!=="--no-global-caches"),l.prepared.args.push(...s.slice(1).map(u=>u.configPath))),l})}function Gr(e,t){return e.onStatus(`Skipping ${e.language}: ${t}`),{skipped:{language:e.language,reason:t}}}function gh(e,t,n){return Hi(e)?null:n.skipAutoInstall?`${t} not found on PATH. To install the reviewed version, run: scip-query reindex --install-missing${e.installUrl?` (manual source: ${e.installUrl})`:""}`:(n.onStatus(`${t} not found. Attempting auto-install...`),hc(e,n.onStatus)?null:`${t} could not be auto-installed. ${e.installUrl?`Install manually from ${e.installUrl}`:`Install ${t} and put it on PATH.`}`)}function hh(e,t,n){return e.trustProjectTools&&n?qi(t,e.projectRoot):null}function yh(e,t){let n=xt(t),r=Un(t,e.projectRoot),i=hh(e,t,r),a=We(t);if(!i&&!a&&r){let s=`${n} is available only as repository-local code at ${r}. Review that exact tool and rerun with --trust-project-tools.`;return Gr(e,s)}if(!i&&!a){let s=gh(t,n,e);if(s!==null)return Gr(e,s)}let o=i?.canonicalPath??We(t);if(!o){let s=`${n} was not found after installation checks.`;return Gr(e,s)}return{resolvedBinary:o,trustedProjectTool:i}}function bh(e,t){return{...t===void 0?{}:{temporaryRootConfigContent:t},...e.temporaryProjectConfigs===void 0?{}:{temporaryProjectConfigs:e.temporaryProjectConfigs},...e.boundedConcurrency===void 0?{}:{boundedConcurrency:e.boundedConcurrency},...e.outputComposition?{outputComposition:e.outputComposition}:{}}}function En(e){let t=hn(e.language),n=yh(e,t);if("skipped"in n)return n;let{resolvedBinary:r,trustedProjectTool:i}=n,{binary:a,args:o}=t.indexArgs({projectRoot:e.projectRoot,outputPath:e.scipPath,pnpmWorkspaces:e.pnpmWorkspaces,indexerBinary:r,projectPath:e.projectPath,configPath:e.language==="clojure"?e.clojureConfigPath:void 0}),s=bs({language:e.language,projectPath:e.projectPath,pnpmWorkspaces:e.pnpmWorkspaces});if(i&&!i.executable){let c=`${i.relativePath} is not executable; refusing project-local indexer.`;return e.onStatus(`Skipping ${e.language}: ${c}`),{skipped:{language:e.language,reason:c}}}return i&&e.onStatus(`Trusted project-local ${e.language} indexer ${i.relativePath} (${i.sha256.slice(0,12)}\u2026, ${i.canonicalPath}).`),{prepared:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,config:t,resolvedBinary:r,binary:a,args:o,env:zi(t,e.env,r),...bh(e,s),...i?{trustedProjectTool:i}:{}}}}function Sh(e,t){let n=new Set(e.filter(a=>a.skipped&&a.outputComposition).map(a=>`${a.language}\0${a.outputScipPath}`)),r=new Map;for(let a of e)if(a.skipped)$c(t,a.skipped);else{let o=`${a.language}\0${a.outputScipPath}`;if(n.has(o))continue;let s=r.get(o)??{language:a.language,outputScipPath:a.outputScipPath,scipPaths:[],concatenate:!0};s.scipPaths.push(a.scipPath),a.outputComposition!=="protobuf-concatenate"&&(s.concatenate=!1),r.set(o,s)}return{indexedOutputs:Dh(r)}}function $c(e,t){let n=e.find(r=>r.language===t.language);if(!n){e.push(t);return}n.reason.includes(t.reason)||(n.reason=`${n.reason}; ${t.reason}`)}function vh(e,t,n,r,i){if(e.length===0){let a=t.map(o=>` - ${o.language}: ${o.reason}`).join(`
294
344
  `);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
295
- `+i)}if(t.length!==0&&(a(`Indexed ${e.length} language output(s); skipped or incomplete: ${t.map(i=>i.language).join(", ")}.`),!r))throw new Error(`Failed to index all required languages; preserving the previous index. Pass --allow-partial to intentionally write an incomplete index.
296
- `+t.map(i=>` - ${i.language}: ${i.reason}`).join(`
297
- `))}function aa(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),a=ar(e.map(i=>i.scipPath),t);return xa(a,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&pa(e[0].scipPath,t);return!1}async function ed(e){let t;if(td(e))try{let a=e.incrementalTypeScript.affectedBatches.length>0?e.incrementalTypeScript.affectedBatches:[{scipPath:e.incrementalTypeScript.affectedScipPath,affectedFiles:e.incrementalTypeScript.affectedFiles,deletedFiles:e.incrementalTypeScript.deletedFiles}],i=new Set,o=0,s=0;for(let[c,d]of a.entries()){let l=O(e.run.tempPaths.runDir,`typescript-affected-${c}.db`);Ra(d.scipPath,e.run.onStatus),e.run.onStatus(`Converting bounded TypeScript batch ${c+1}/${a.length} (${d.affectedFiles.length-d.deletedFiles.length} emitted, ${d.deletedFiles.length} removed) to SQLite...`);let g=performance.now();await oa(d.scipPath,l,e.env,e.run.onStatus,!0,e.run.opts.signal),o+=performance.now()-g,We(e.run.writeTelemetry,te(l)??0);let p=Vr({previousDbPath:e.run.paths.outputDb,miniDbPath:l,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:d.affectedFiles,deletedFiles:d.deletedFiles,reuseCandidate:c>0,deferIntegrity:c<a.length-1,trustedPriorGeneration:!0,writeTelemetry:e.run.writeTelemetry});s+=p.durationMs;for(let f of p.changedDocumentPaths)i.add(f);Z(l,{force:!0})}return e.run.onStatus(`Patched ${e.incrementalTypeScript.affectedFiles.length} SQLite document path(s) across ${a.length} bounded batch(es) in ${(s/1e3).toFixed(3)}s.`),{mode:"incremental",changedDocumentPaths:[...i].sort(),patchDurationMs:s,converterDurationMs:o,scipCompanion:e.incrementalTypeScript.completeScipUpdated?"current":"deferred"}}catch(a){if(A(e.run.opts.signal,"Reindex cancelled by its owner."),t=a instanceof Error?a.message:String(a),Z(e.run.tempPaths.tempOutputDb,{force:!0}),e.run.opts.allowExpensiveRebuild===!1)throw new Error(`Bounded incremental SQLite publication failed and the whole-project fallback is disabled: ${t}`,{cause:a});e.run.onStatus(`Incremental SQLite publication unavailable: ${t}. Falling back to complete conversion.`)}let n=e.completeScipSanitized;e.completeScipAvailable||(n=await e.materializeFullFallback());let r=performance.now();return await oa(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n,e.run.opts.signal),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function td(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!L(e.run.paths.outputDb)||!L(e.run.paths.outputScip))return!1;let t=new Set(e.reusedLanguages);return e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(n=>n==="typescript"||t.has(n))}function nd(e,t){let n=C(),r=[...t].sort(),a=new Set(r),i={addedFiles:[],modifiedFiles:r,deletedFiles:[],changedFiles:r,unchangedFiles:e.affectedFiles.filter(o=>!a.has(o)).sort()};return{version:1,status:"evaluated",refreshResult:"rebuilt",recordedAt:new Date().toISOString(),durationMs:C()-n,manifest:e.manifest,plan:e.plan,comparison:i,evaluation:It(e.plan,i,e.projectFileCount)}}async function oa(e,t,n,r,a=!1,i){if(A(i,"Reindex cancelled by its owner."),r("Converting to SQLite..."),!L(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{if(a||Ra(e,r),n.SCIP_QUERY_SQLITE_CONVERTER==="scip-cli"){let o=En();if(!o)throw new Error("scip CLI is not available");let s=await ve({command:o,args:["expt-convert","--output",t,e],label:"SCIP SQLite conversion",env:n,maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024,timeoutMs:3e5,signal:i});if(s.status!==0)throw new Error(`scip expt-convert exited with ${s.status}${s.stderr.trim()?`: ${s.stderr.trim()}`:""}`)}else Z(t,{force:!0}),await Si(ie(e,{maxBytes:Ee,inputKind:"SCIP index"}),t,{signal:i})}catch(o){A(i,"Reindex cancelled by its owner.");let s=o instanceof Error?o.message:String(o);throw new Error(`Failed to convert SCIP index to SQLite: ${s}`,{cause:o})}}function Ra(e,t){let n=nr(e);xa(n,t)}function xa(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function ne(e,t,n){let r=Ec(e)||".scip",a=tt(e,r);return O(x(e),`${a}.${n+1}.${t}${r}`)}async function rd(e,t){for(let n=0;n<2;n++){let r=id(e,t);if(r)return r;let a=ad(e);if(a&&va(t.trigger,a)){t.onStatus(`Manual reindex preempting watcher refresh started at ${a.startedAt}.`);let i;try{i=await od(a)}catch(s){throw new Error(`Could not verify the watcher's in-progress reindex owner (pid ${a.pid}); refusing to steal an active lock: ${ee(s)}`,{cause:s})}if(!i)throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${a.pid}) terminated for ${x(e)}; refusing to steal an active lock.`);let o=ft(e,{parseLegacy:it});if(!Pn(e,o,{parseLegacy:it}))throw new Error(`Reindex lock ownership changed before preemption completed for ${x(e)}.`);continue}throw new le(`Another scip-query reindex is already running for ${x(e)}.`)}throw new le(`Could not acquire scip-query reindex lock for ${x(e)}.`)}function id(e,t){let n=U(process.pid),r=bn(e,{kind:"reindex",processIdentity:n,detail:{projectRoot:t.projectRoot,...process.env.SCIP_REINDEX_PROCESS_GROUP_LEADER==="1"?{processGroupLeader:!0}:{},...t.trigger?{trigger:t.trigger}:{}},parseLegacy:it});if(r.kind==="acquired"&&r.reclaimed){let a=Ea(r.reclaimed,e);a&&va(t.trigger,a)?t.onStatus(`Manual reindex preempting watcher refresh started at ${a.startedAt}; its prior owner was already stale.`):t.onStatus(`Recovered an abandoned or incomplete reindex lock for ${x(e)}.`)}return r.kind==="acquired"?()=>{r.lock.release()}:null}function ad(e){return Ea(ft(e,{parseLegacy:it}),e)}var it=e=>{let t=Ia(e,"");return t?{pid:t.pid,...t.processIdentity?{processIdentity:t.processIdentity}:{}}:null};function Ea(e,t){if(e.state==="valid"&&e.record?.kind==="reindex"){let n=e.record.detail??{};return{version:2,pid:e.record.pid,...e.record.processIdentity?{processIdentity:e.record.processIdentity}:{},...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:x(t),startedAt:e.record.startedAt,trigger:n.trigger}}return Ia(e.parsed,t)}function Ia(e,t){try{let n=e;return typeof n.pid!="number"||!Number.isInteger(n.pid)||n.pid<=0?null:{version:n.version===2?2:1,pid:n.pid,...n.processIdentity===void 0?{}:(()=>{let r=Ie(n.processIdentity);return r?.pid===n.pid?{processIdentity:r}:{}})(),...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:x(t),startedAt:typeof n.startedAt=="string"?n.startedAt:"unknown",trigger:n.trigger}}catch{return null}}function va(e,t){return e?.kind==="manual-cli"&&_a(t?.trigger)}function _a(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function od(e){return!oe(e.pid)||(Yt(e),sa(e,"SIGTERM"),await ca(e,2e3))?!0:(Yt(e),sa(e,"SIGKILL"),ca(e,1e3))}function sa(e,t){if(e.processGroupLeader)try{process.kill(-e.pid,t);return}catch{if(!oe(e.pid))return;Yt(e)}try{process.kill(e.pid,t)}catch{}}async function ca(e,t){let n=C()+t;for(;C()<n;){if(da(e))return!0;await sd(50)}return da(e)}function Yt(e){if(!e.processIdentity)throw new Error(`Refusing to signal reindex pid ${e.pid}: its ownership record has no process identity.`);let t=U(e.pid);if(!t)throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity is unavailable.`);if(!z(e.processIdentity,t))throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity does not match the ownership record.`)}function da(e){if(!oe(e.pid))return!0;if(!e.processIdentity)return!1;let t=U(e.pid);return t!==null&&!z(e.processIdentity,t)}function sd(e){return new Promise(t=>setTimeout(t,e))}function Zt(e,t,n){return Object.fromEntries(t.map(r=>{let a=r==="typescript"?Fn(n.typescriptProjects):[],i=r==="clojure"?dd(n.clojureConfigPath):void 0,o=[..._t(r).markerFiles,...a,...i?[i]:[]],s=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:a}:{typescriptProjectMode:"single",typescriptProjects:[]};return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&ld(n),...s,clojureConfigPath:i,files:e.files.filter(c=>un(c.path,r,o)).map(c=>Ta(c,r))}]}))}function Ta(e,t){let n=t==="typescript"&&/(?:^|\/)package\.json$/iu.test(e.path)?e.semanticHash:void 0;return{path:e.path,size:n===void 0?e.size:0,hash:n??e.hash}}function cd(e,t){let n=lt(t);if(!n)return t;let r=n.typescriptProjectMode==="workspace"?X(e,n.typescriptProjects):["."],a=se(r);return{...n,files:n.files.filter(i=>!ce(i.path)||a.has(i.path)).map(i=>{let o=i.semanticHash??we(e,i.path,i.hash);return Ta(o===void 0?i:{...i,semanticHash:o},"typescript")})}}function dd(e){return e?.trim()||void 0}function ld(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function en(e,t){return O(x(e),"language-indexes",`${t}.scip`)}function wa(e){return O(x(e),"language-indexes","typescript-projects")}function ot(e,t){return O(wa(e),`${Mt(t)}.scip`)}function re(e){try{return Te(me(fe(e,"reindex metadata")))}catch{return null}}function Ca(e,t){try{let n=me(fe(e,"reindex metadata"));if(n.kind!=="legacy"&&n.kind!=="supported")return null;let r=n.metadata;return!n.capabilities.publishableGeneration||!gn(r)||N([...r.indexedLanguages??[]].sort())!==N(t.languages)?null:N(r.fingerprint)===N(t)?"exact":N(la(r.fingerprint))===N(la(t))?"operational-config-compatible":null}catch{return null}}function la(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return Array.isArray(t.files)?{...t,files:t.files.filter(n=>typeof n!="object"||n===null||Array.isArray(n)||n.path!==".scipquery.json")}:e}function ud(e,t,n,r){let a=Te(me(fe(e,"reindex metadata")));a&&st(e,{...a,fingerprint:t,...a.version===ae?{languageFingerprints:Zt(t,n,r)}:{}})}function st(e,t){Bn(e,t,{spacing:2,trailingNewline:!0})}function ja(e,t){try{let n=Te(me(fe(e,"reindex metadata")));if(!n)return;st(e,{...n,lastRefresh:t})}catch{}}function ct(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:C()-e.monotonicStart,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function N(e){return JSON.stringify(e)}var pd={readIdentity:U,setInterval(e,t){let n=setInterval(e,t);return n.unref(),n},clearInterval};function Oa(e,t,n={}){let r=n.runtime??pd,a=n.intervalMs??1e3;if(!Number.isSafeInteger(a)||a<=0)throw new TypeError("parent process monitor interval must be a positive safe integer");let i=!0,o,s=()=>{if(!i)return;let c=r.readIdentity(e.pid);c&&z(e,c)||(i=!1,o&&r.clearInterval(o),t(c?`parent process ${e.pid} changed identity`:`parent process ${e.pid} exited`))};return s(),i&&(o=r.setInterval(s,a)),{stop(){i&&(i=!1,o&&r.clearInterval(o))}}}var Da=process.env.SCIP_REINDEX_PROJECT_ROOT,Ma=process.env.SCIP_REINDEX_OUTPUT_SCIP,Na=process.env.SCIP_REINDEX_OUTPUT_DB,Fa=process.env.SCIP_REINDEX_LANGUAGES,fd=Or(process.env.SCIP_REINDEX_INDEXER_CONCURRENCY),md=process.env.SCIP_REINDEX_PNPM_WORKSPACES==="1",tn=Cd(process.env.SCIP_REINDEX_TYPESCRIPT_CONFIG),hd=process.env.SCIP_REINDEX_CLOJURE_CONFIG_PATH||void 0,yd=wd(process.env.SCIP_REINDEX_TRIGGER_KIND),Sd=process.env.SCIP_REINDEX_TRIGGER_DETAIL,bd=Fr(process.env.SCIP_REINDEX_CHANGE_JOURNAL),Pd=process.env.SCIP_REINDEX_ALLOW_EXPENSIVE!=="0",La=Td(process.env.SCIP_REINDEX_PARENT_IDENTITY);(!Da||!Ma||!Na||!La)&&(console.error("reindex-worker: missing required env vars"),process.exit(1));var Rd=Da,xd=Ma,Ed=Na,Id=La,ka=Fa?Fa.split(",").filter(Boolean):void 0,Aa=new AbortController,vd=Oa(Id,e=>{Aa.abort(new Error(`Reindex worker owner lost: ${e}`))});_d();async function _d(){try{await ga({projectRoot:Rd,outputScip:xd,outputDb:Ed,languages:ka?.length?ka:void 0,pnpmWorkspaces:md,typescriptProjectMode:tn.projectMode,typescriptProjects:tn.projects,maxHeapMb:tn.maxHeapMb,clojureConfigPath:hd,indexerConcurrency:fd,trigger:{kind:yd,detail:Sd||void 0},changeJournal:bd,allowExpensiveRebuild:Pd,signal:Aa.signal,onStatus:e=>process.stderr.write(`[reindex] ${xt(e)}
298
- `)})}catch(e){console.error(`reindex-worker error: ${xt(String(e))}`),process.exitCode=e instanceof le?75:1}finally{vd.stop()}}function Td(e){if(!e)return null;try{return Ie(JSON.parse(e))}catch{return null}}function wd(e){switch(e){case"manual-cli":case"setup":case"watch-source":case"watch-git-head":case"watch-git-index":case"watch-git-state":return e;default:return"unknown"}}function Cd(e){if(!e)return{};try{let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return{};let n=t,r=n.projectMode==="single"||n.projectMode==="workspace"?n.projectMode:void 0,a=Array.isArray(n.projects)?n.projects.filter(o=>typeof o=="string"&&o.trim()!==""):void 0,i=typeof n.maxHeapMb=="number"&&Number.isInteger(n.maxHeapMb)&&n.maxHeapMb>0?n.maxHeapMb:void 0;return{projectMode:r,projects:a&&a.length>0?a:void 0,maxHeapMb:i}}catch{return{}}}
345
+ `+a)}if(t.length!==0&&(i(`Indexed ${e.length} language output(s); skipped or incomplete: ${t.map(a=>a.language).join(", ")}.`),!r))throw new Error(`Failed to index all required languages; preserving the previous index. Pass --allow-partial to intentionally write an incomplete index.
346
+ `+t.map(a=>` - ${a.language}: ${a.reason}`).join(`
347
+ `))}function xc(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=Ta(e.map(a=>a.scipPath),t);return Hc(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&Tc(e[0].scipPath,t);return!1}async function xh(e){let t;if(Rh(e))try{return await Mh(e)}catch(i){if(H(e.run.opts.signal,"Reindex cancelled by its owner."),t=i instanceof Error?i.message:String(i),Ee(e.run.tempPaths.tempOutputDb,{force:!0}),e.run.opts.allowExpensiveRebuild===!1)throw new Error(`Bounded incremental SQLite publication failed and the whole-project fallback is disabled: ${t}`,{cause:i});e.run.onStatus(`Incremental SQLite publication unavailable: ${t}. Falling back to complete conversion.`)}let n=e.completeScipSanitized;e.completeScipAvailable||(n=await e.materializeFullFallback());let r=performance.now();return await Uc(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n,e.run.opts.signal),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function Rh(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!B(e.run.paths.outputDb)||!B(e.run.paths.outputScip))return!1;let t=new Set(e.reusedLanguages);return e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(n=>n==="typescript"||t.has(n))}function Ph(e,t){let n=w(),r=[...t].sort(),i=new Set(r),a={addedFiles:[],modifiedFiles:r,deletedFiles:[],changedFiles:r,unchangedFiles:e.affectedFiles.filter(o=>!i.has(o)).sort()};return{version:1,status:"evaluated",refreshResult:"rebuilt",recordedAt:new Date().toISOString(),durationMs:w()-n,manifest:e.manifest,plan:e.plan,comparison:a,evaluation:Sr(e.plan,a,e.projectFileCount)}}async function Uc(e,t,n,r,i=!1,a){if(H(a,"Reindex cancelled by its owner."),r("Converting to SQLite..."),!B(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{if(i||Gc(e,r),n.SCIP_QUERY_SQLITE_CONVERTER==="scip-cli"){let o=Mi();if(!o)throw new Error("scip CLI is not available");let s=await St({command:o,args:["expt-convert","--output",t,e],label:"SCIP SQLite conversion",env:n,maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024,timeoutMs:3e5,signal:a});if(s.status!==0)throw new Error(`scip expt-convert exited with ${s.status}${s.stderr.trim()?`: ${s.stderr.trim()}`:""}`)}else Ee(t,{force:!0}),await Gs(fe(e,{maxBytes:Ue,inputKind:"SCIP index"}),t,{signal:a})}catch(o){H(a,"Reindex cancelled by its owner.");let s=o instanceof Error?o.message:String(o);throw new Error(`Failed to convert SCIP index to SQLite: ${s}`,{cause:o})}}function Gc(e,t){let n=Ia(e);Hc(n,t)}function Hc(e,t){e.recoveredDefinitionSymbols&&t(`Preserved definition occurrences and recovered ${e.recoveredDefinitionSymbols} missing symbol metadata record(s); kind and documentation remain unknown.`),e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function we(e,t,n){let r=yg(e)||".scip",i=In(e,r);return O(I(e),`${i}.${n+1}.${t}${r}`)}async function Ih(e,t){for(let n=0;n<2;n++){let r=Eh(e,t);if(r)return r;let i=Ch(e);if(i&&zc(t.trigger,i)){t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`);let a;try{a=await Th(i)}catch(s){throw new Error(`Could not verify the watcher's in-progress reindex owner (pid ${i.pid}); refusing to steal an active lock: ${Ce(s)}`,{cause:s})}if(!a)throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${I(e)}; refusing to steal an active lock.`);let o=jn(e,{parseLegacy:Tn});if(!xi(e,o,{parseLegacy:Tn}))throw new Error(`Reindex lock ownership changed before preemption completed for ${I(e)}.`);continue}throw new Le(`Another scip-query reindex is already running for ${I(e)}.`)}throw new Le(`Could not acquire scip-query reindex lock for ${I(e)}.`)}function Eh(e,t){let n=te(process.pid),r=vi(e,{kind:"reindex",processIdentity:n,detail:{projectRoot:t.projectRoot,...process.env.SCIP_REINDEX_PROCESS_GROUP_LEADER==="1"?{processGroupLeader:!0}:{},...t.trigger?{trigger:t.trigger}:{}},parseLegacy:Tn});if(r.kind==="acquired"&&r.reclaimed){let i=qc(r.reclaimed,e);i&&zc(t.trigger,i)?t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}; its prior owner was already stale.`):t.onStatus(`Recovered an abandoned or incomplete reindex lock for ${I(e)}.`)}return r.kind==="acquired"?()=>{r.lock.release()}:null}function Ch(e){return qc(jn(e,{parseLegacy:Tn}),e)}var Tn=e=>{let t=Vc(e,"");return t?{pid:t.pid,...t.processIdentity?{processIdentity:t.processIdentity}:{}}:null};function qc(e,t){if(e.state==="valid"&&e.record?.kind==="reindex"){let n=e.record.detail??{};return{version:2,pid:e.record.pid,...e.record.processIdentity?{processIdentity:e.record.processIdentity}:{},...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:I(t),startedAt:e.record.startedAt,trigger:n.trigger}}return Vc(e.parsed,t)}function Vc(e,t){try{let n=e;return typeof n.pid!="number"||!Number.isInteger(n.pid)||n.pid<=0?null:{version:n.version===2?2:1,pid:n.pid,...n.processIdentity===void 0?{}:(()=>{let r=yt(n.processIdentity);return r?.pid===n.pid?{processIdentity:r}:{}})(),...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:I(t),startedAt:typeof n.startedAt=="string"?n.startedAt:"unknown",trigger:n.trigger}}catch{return null}}function zc(e,t){return e?.kind==="manual-cli"&&Wc(t?.trigger)}function Wc(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function Th(e){return!Oe(e.pid)||(Hr(e),Rc(e,"SIGTERM"),await Pc(e,2e3))?!0:(Hr(e),Rc(e,"SIGKILL"),Pc(e,1e3))}function Rc(e,t){if(e.processGroupLeader)try{process.kill(-e.pid,t);return}catch{if(!Oe(e.pid))return;Hr(e)}try{process.kill(e.pid,t)}catch{}}async function Pc(e,t){let n=w()+t;for(;w()<n;){if(Ic(e))return!0;await wh(50)}return Ic(e)}function Hr(e){if(!e.processIdentity)throw new Error(`Refusing to signal reindex pid ${e.pid}: its ownership record has no process identity.`);let t=te(e.pid);if(!t)throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity is unavailable.`);if(!ye(e.processIdentity,t))throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity does not match the ownership record.`)}function Ic(e){if(!Oe(e.pid))return!0;if(!e.processIdentity)return!1;let t=te(e.pid);return t!==null&&!ye(e.processIdentity,t)}function wh(e){return new Promise(t=>setTimeout(t,e))}function zr(e,t,n){return Object.fromEntries(t.map(r=>{let i=r==="typescript"?fi(n.typescriptProjects):[],a=r==="clojure"?_h(n.clojureConfigPath):void 0,o=[...hn(r).markerFiles,...i,...a?[a]:[]],s=r==="typescript"?{typescriptSymbolIdentityVersion:6,typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:i}:{typescriptProjectMode:"single",typescriptProjects:[]};return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&Nh(n),...s,clojureConfigPath:a,files:e.files.filter(c=>Zr(c.path,r,o)).map(c=>Kc(c,r))}]}))}function Kc(e,t){let n=t==="typescript"&&/(?:^|\/)package\.json$/iu.test(e.path)?e.semanticHash:void 0;return{path:e.path,size:n===void 0?e.size:0,hash:n??e.hash}}function Fh(e,t){let n=pt(t);if(!n)return t;let r=n.typescriptProjectMode==="workspace"?ge(e,n.typescriptProjects):["."],i=qe(r);return{...n,files:n.files.filter(a=>!ft(a.path)||i.has(a.path)).map(a=>{let o=a.semanticHash??ht(e,a.path,a.hash);return Kc(o===void 0?a:{...a,semanticHash:o},"typescript")})}}function _h(e){return e?.trim()||void 0}function Nh(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Wr(e,t){return O(I(e),"language-indexes",`${t}.scip`)}function Xc(e){return O(I(e),"language-indexes","typescript-projects")}function Fn(e,t){return O(Xc(e),`${Fr(t)}.scip`)}function de(e){try{return gt(Ve(He(e,"reindex metadata")))}catch{return null}}function Jc(e,t){try{let n=Ve(He(e,"reindex metadata"));if(n.kind!=="legacy"&&n.kind!=="supported")return null;let r=n.metadata;return!n.capabilities.publishableGeneration||!si(r)||j([...r.indexedLanguages??[]].sort())!==j(t.languages)?null:j(r.fingerprint)===j(t)?"exact":j(Ec(r.fingerprint))===j(Ec(t))?"operational-config-compatible":null}catch{return null}}function Ec(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return Array.isArray(t.files)?{...t,files:t.files.filter(n=>typeof n!="object"||n===null||Array.isArray(n)||n.path!==".scipquery.json")}:e}function Oh(e,t,n,r){let i=gt(Ve(He(e,"reindex metadata")));i&&dt(e,{...i,fingerprint:t,...i.version===_e?{languageFingerprints:zr(t,n,r)}:{}})}function dt(e,t){oi(e,t,{spacing:2,trailingNewline:!0})}function Yc(e,t){try{let n=gt(Ve(He(e,"reindex metadata")));if(!n)return;dt(e,{...n,lastRefresh:t})}catch{}}function _n(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:w()-e.monotonicStart,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function j(e){return JSON.stringify(e)}function Dh(e){let t=[];for(let n of e.values())if(n.scipPaths.length>1)n.concatenate?Ca(n.scipPaths,n.outputScipPath):Ea(n.scipPaths,n.outputScipPath),t.push({language:n.language,scipPath:n.outputScipPath});else{let r=n.scipPaths[0];r!==n.outputScipPath&&Tc(r,n.outputScipPath),t.push({language:n.language,scipPath:n.outputScipPath})}return t}function kh(e,t){e.added.length>0&&t.onStatus(`Added SQLite query indexes: ${e.added.join(", ")}`),e.removed.length>0&&t.onStatus(`Removed redundant SQLite indexes: ${e.removed.join(", ")}`)}function Lh(e,t){e.achievedDurability==="file-flushed"&&t.onStatus(`Published local generation ${e.currentGeneration.slice(0,12)} (file-flushed; directory sync unsupported)`)}function Ah(e){return e.mode==="incremental"&&e.scipCompanion==="deferred"}async function Mh(e){if(e.incrementalTypeScript.affectedBatches.length===0&&e.incrementalTypeScript.retainedDocumentCount===e.incrementalTypeScript.affectedFiles.length&&e.incrementalTypeScript.retainedDocumentCount>0){let a=performance.now();return ie(e.run.writeTelemetry,re(e.run.paths.outputDb,e.run.tempPaths.tempOutputDb)),e.run.onStatus(`Retained all ${e.incrementalTypeScript.retainedDocumentCount} verified TypeScript documents; SQLite conversion is unnecessary.`),{mode:"incremental",changedDocumentPaths:[],compilerFactsUnchanged:!0,patchDurationMs:performance.now()-a,converterDurationMs:0,scipCompanion:"deferred"}}let t=e.incrementalTypeScript.affectedBatches.length>0?e.incrementalTypeScript.affectedBatches:[{scipPath:e.incrementalTypeScript.affectedScipPath,affectedFiles:e.incrementalTypeScript.affectedFiles,deletedFiles:e.incrementalTypeScript.deletedFiles}],n=new Set,r=0,i=0;for(let[a,o]of t.entries()){let s=O(e.run.tempPaths.runDir,`typescript-affected-${a}.db`);Gc(o.scipPath,e.run.onStatus),e.run.onStatus(`Converting bounded TypeScript batch ${a+1}/${t.length} (${o.affectedFiles.length-o.deletedFiles.length} emitted, ${o.deletedFiles.length} removed) to SQLite...`);let c=performance.now();await Uc(o.scipPath,s,e.env,e.run.onStatus,!0,e.run.opts.signal),r+=performance.now()-c,qt(e.run.writeTelemetry,Te(s)??0);let l=Ps({previousDbPath:e.run.paths.outputDb,miniDbPath:s,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:o.affectedFiles,deletedFiles:o.deletedFiles,reuseCandidate:a>0,deferIntegrity:a<t.length-1,trustedPriorGeneration:!0,writeTelemetry:e.run.writeTelemetry});i+=l.durationMs;for(let u of l.changedDocumentPaths)n.add(u);Ee(s,{force:!0})}return e.run.onStatus(`Patched ${t.reduce((a,o)=>a+o.affectedFiles.length,0)} SQLite document path(s) across ${t.length} bounded batch(es) in ${(i/1e3).toFixed(3)}s.`),{mode:"incremental",changedDocumentPaths:[...n].sort(),patchDurationMs:i,converterDurationMs:r,scipCompanion:e.incrementalTypeScript.completeScipUpdated?"current":"deferred"}}function jh(e,t,n){if(e.source==="path"&&Fc()!=="win32"){let r=$i();if(!Bi(r))if(t)n(`scip on PATH reports ${r??"an unknown version"}; the reviewed version is ${vt} and compatibility is unverified. Run scip-query setup --install-missing to install the reviewed release.`);else return n(`scip on PATH reports ${r??"an unknown version"}; installing the reviewed ${vt}.`),Ui(n)}}function Bh(e,t,n){let r=Ln(e),i=t&&r?li(e,"file-dependency-graph",t,r):0,a=i>0;return n.onStatus(a?`Carried ${i} unchanged dependency graph product(s) forward without rebuilding them.`:"No persisted dependency graph product required rekeying; the next graph consumer can materialize it."),a}var $h={readIdentity:te,setInterval(e,t){let n=setInterval(e,t);return n.unref(),n},clearInterval};function Qc(e,t,n={}){let r=n.runtime??$h,i=n.intervalMs??1e3;if(!Number.isSafeInteger(i)||i<=0)throw new TypeError("parent process monitor interval must be a positive safe integer");let a=!0,o,s=()=>{if(!a)return;let c=r.readIdentity(e.pid);c&&ye(e,c)||(a=!1,o&&r.clearInterval(o),t(c?`parent process ${e.pid} changed identity`:`parent process ${e.pid} exited`))};return s(),a&&(o=r.setInterval(s,i)),{stop(){a&&(a=!1,o&&r.clearInterval(o))}}}var tl=process.env.SCIP_REINDEX_PROJECT_ROOT,nl=process.env.SCIP_REINDEX_OUTPUT_SCIP,rl=process.env.SCIP_REINDEX_OUTPUT_DB,Zc=process.env.SCIP_REINDEX_LANGUAGES,Gh=Ya(process.env.SCIP_REINDEX_INDEXER_CONCURRENCY),Hh=process.env.SCIP_REINDEX_PNPM_WORKSPACES==="1",Kr=ry(process.env.SCIP_REINDEX_TYPESCRIPT_CONFIG),qh=process.env.SCIP_REINDEX_CLOJURE_CONFIG_PATH||void 0,Vh=ny(process.env.SCIP_REINDEX_TRIGGER_KIND),zh=process.env.SCIP_REINDEX_TRIGGER_DETAIL,Wh=Qa(process.env.SCIP_REINDEX_CHANGE_JOURNAL),Kh=process.env.SCIP_REINDEX_ALLOW_EXPENSIVE!=="0",il=ty(process.env.SCIP_REINDEX_PARENT_IDENTITY);(!tl||!nl||!rl||!il)&&(console.error("reindex-worker: missing required env vars"),process.exit(1));var Xh=tl,Jh=nl,Yh=rl,Qh=il,el=Zc?Zc.split(",").filter(Boolean):void 0,al=new AbortController,Zh=Qc(Qh,e=>{al.abort(new Error(`Reindex worker owner lost: ${e}`))});ey();async function ey(){try{await _c({projectRoot:Xh,outputScip:Jh,outputDb:Yh,languages:el?.length?el:void 0,pnpmWorkspaces:Hh,typescriptProjectMode:Kr.projectMode,typescriptProjects:Kr.projects,maxHeapMb:Kr.maxHeapMb,clojureConfigPath:qh,indexerConcurrency:Gh,trigger:{kind:Vh,detail:zh||void 0},changeJournal:Wh,allowExpensiveRebuild:Kh,signal:al.signal,onStatus:e=>process.stderr.write(`[reindex] ${Jn(e)}
348
+ `)})}catch(e){console.error(`reindex-worker error: ${Jn(String(e))}`),process.exitCode=e instanceof Le?75:1}finally{Zh.stop()}}function ty(e){if(!e)return null;try{return yt(JSON.parse(e))}catch{return null}}function ny(e){return Yr(e)?e:"unknown"}function ry(e){if(!e)return{};try{let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return{};let n=t,r=n.projectMode==="single"||n.projectMode==="workspace"?n.projectMode:void 0,i=iy(n.projects),a=ay(n.maxHeapMb);return{projectMode:r,projects:i,maxHeapMb:a}}catch{return{}}}function iy(e){let t=Array.isArray(e)?e.filter(n=>typeof n=="string"&&n.trim()!==""):void 0;return t&&t.length>0?t:void 0}function ay(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:void 0}
299
349
  //# sourceMappingURL=reindex-worker.js.map