scip-query 0.20.0 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (594) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/README.md +255 -884
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/by-kind-XXGZGNZ6.js +2 -0
  5. package/dist/call-graph-VGY3R4L3.js +2 -0
  6. package/dist/call-graph-evidence-lZa2dwQA.d.ts +11 -0
  7. package/dist/change-analysis-types-CCtoCHbC.d.ts +9 -0
  8. package/dist/chunk-26CT72HM.js +2 -0
  9. package/dist/chunk-27OUNZW5.js +3 -0
  10. package/dist/chunk-2LJLEM5B.js +2 -0
  11. package/dist/chunk-3KXFB2FM.js +2 -0
  12. package/dist/chunk-3T5U2EQ2.js +2 -0
  13. package/dist/chunk-3TNRNKAT.js +2 -0
  14. package/dist/{chunk-PXY7F6Y4.js → chunk-3XQLJG7V.js} +5 -5
  15. package/dist/chunk-3XZELASU.js +2 -0
  16. package/dist/chunk-3YETOKNO.js +4 -0
  17. package/dist/chunk-47WX6UC4.js +2 -0
  18. package/dist/{chunk-7SQQWSY3.js → chunk-4HQYNZ3P.js} +2 -2
  19. package/dist/chunk-4IASLUOP.js +3 -0
  20. package/dist/{chunk-KMKTIO2G.js → chunk-4KIPF45P.js} +2 -2
  21. package/dist/chunk-4SZJF4GK.js +2 -0
  22. package/dist/chunk-4TOU7HHQ.js +2 -0
  23. package/dist/chunk-4ZCLDH6T.js +11 -0
  24. package/dist/{chunk-DQGFVPUV.js → chunk-527HV7JY.js} +3 -3
  25. package/dist/{chunk-ZTETIQ35.js → chunk-5BJPJUXF.js} +2 -2
  26. package/dist/chunk-5J3A6RBZ.js +16 -0
  27. package/dist/chunk-5KIJMEPC.js +2 -0
  28. package/dist/{chunk-JDOEX4E6.js → chunk-5QM7QT5B.js} +2 -2
  29. package/dist/chunk-5Z2H76VD.js +11 -0
  30. package/dist/chunk-63TFRBMB.js +2 -0
  31. package/dist/chunk-67FK5KGV.js +3 -0
  32. package/dist/chunk-6DO3VBLV.js +2 -0
  33. package/dist/chunk-6LS3IG2I.js +13 -0
  34. package/dist/chunk-6QN4FYQW.js +2 -0
  35. package/dist/chunk-6X4KO5A7.js +11 -0
  36. package/dist/chunk-743MEVFJ.js +8 -0
  37. package/dist/chunk-7G2WIVIX.js +2 -0
  38. package/dist/chunk-7KCZELVM.js +2 -0
  39. package/dist/chunk-7MUHSZGN.js +3 -0
  40. package/dist/chunk-7YZGSLW6.js +3 -0
  41. package/dist/chunk-7Z4GMCHM.js +117 -0
  42. package/dist/{chunk-32LVLCLN.js → chunk-AAOEROT3.js} +3 -3
  43. package/dist/chunk-AFRS7WJU.js +26 -0
  44. package/dist/chunk-ANCHW2R4.js +57 -0
  45. package/dist/{chunk-SXP2MBJH.js → chunk-AQF35NGT.js} +2 -2
  46. package/dist/chunk-ARGPDW2Y.js +6 -0
  47. package/dist/chunk-B3AREUQK.js +16 -0
  48. package/dist/chunk-BCTCADNB.js +2 -0
  49. package/dist/chunk-BM4OTGSY.js +3 -0
  50. package/dist/chunk-BMKTDJI6.js +16 -0
  51. package/dist/chunk-BOJ5SVE2.js +2 -0
  52. package/dist/{chunk-WXZLAAWK.js → chunk-BVR44XXB.js} +2 -2
  53. package/dist/{chunk-RUJURYSV.js → chunk-BYXWXLKM.js} +2 -2
  54. package/dist/chunk-BZCRHP46.js +3 -0
  55. package/dist/chunk-BZYSGZRK.js +2 -0
  56. package/dist/chunk-C52Q3JEQ.js +2 -0
  57. package/dist/chunk-C7WSQA6A.js +21 -0
  58. package/dist/{chunk-BDCC2NPY.js → chunk-CNT4ND5O.js} +2 -2
  59. package/dist/chunk-CQVDALWQ.js +2 -0
  60. package/dist/chunk-CTO3TRX7.js +2 -0
  61. package/dist/chunk-CXT3GZSQ.js +2 -0
  62. package/dist/{chunk-JVYA47YU.js → chunk-DGM2RJ3I.js} +2 -2
  63. package/dist/{chunk-7PIO7NKH.js → chunk-DK6MB565.js} +2 -2
  64. package/dist/chunk-DNPETNXT.js +2 -0
  65. package/dist/chunk-DRENNWRG.js +2 -0
  66. package/dist/chunk-DUDUIT5P.js +2 -0
  67. package/dist/chunk-DXEJ4FLZ.js +21 -0
  68. package/dist/chunk-DXYMTQZ4.js +2 -0
  69. package/dist/chunk-DZA7MQMU.js +6 -0
  70. package/dist/{chunk-ZHXX42OH.js → chunk-DZNWXJN2.js} +4 -4
  71. package/dist/{chunk-CJST5ETY.js → chunk-E6N6YTVM.js} +2 -2
  72. package/dist/chunk-E7CJ6O72.js +2 -0
  73. package/dist/chunk-EJHNTAEE.js +2 -0
  74. package/dist/chunk-EPLE5O5O.js +2 -0
  75. package/dist/chunk-F4FNK44D.js +2 -0
  76. package/dist/chunk-FCGMQETU.js +2 -0
  77. package/dist/chunk-FIO44MVK.js +3 -0
  78. package/dist/chunk-FLSVYEPL.js +2 -0
  79. package/dist/chunk-FOP7HD6H.js +3 -0
  80. package/dist/chunk-FSPENGSU.js +4 -0
  81. package/dist/chunk-FUUDUAKM.js +2 -0
  82. package/dist/chunk-FYCH2EYQ.js +2 -0
  83. package/dist/{chunk-5E4WNAVD.js → chunk-G47MFF47.js} +2 -2
  84. package/dist/chunk-G6VV7ROY.js +2 -0
  85. package/dist/chunk-GBZCVYWA.js +2 -0
  86. package/dist/chunk-GSHTVE56.js +3 -0
  87. package/dist/chunk-GTZFKDP3.js +2 -0
  88. package/dist/{chunk-2HPVVXM5.js → chunk-H2RBDP5S.js} +2 -2
  89. package/dist/chunk-H5EXS3HM.js +2 -0
  90. package/dist/chunk-HR5JYLVV.js +4 -0
  91. package/dist/chunk-HW7FASEL.js +2 -0
  92. package/dist/chunk-HYU4W353.js +10 -0
  93. package/dist/{chunk-FKSELJQF.js → chunk-I2LY3KN7.js} +2 -2
  94. package/dist/chunk-IGBQVEHE.js +2 -0
  95. package/dist/{chunk-3G66UZBH.js → chunk-IH3K5J6K.js} +2 -2
  96. package/dist/chunk-IHGK3SZ7.js +29 -0
  97. package/dist/chunk-IM23CSG5.js +2 -0
  98. package/dist/chunk-IQMGNIGY.js +2 -0
  99. package/dist/chunk-ITF3CWS5.js +2 -0
  100. package/dist/chunk-IZKJQQCQ.js +3 -0
  101. package/dist/chunk-J4HUBIVF.js +5 -0
  102. package/dist/{chunk-AZJQQKDD.js → chunk-JGMD6JGB.js} +2 -2
  103. package/dist/chunk-JLZWYDCZ.js +4 -0
  104. package/dist/chunk-JO6FK3Q5.js +2 -0
  105. package/dist/chunk-JSHDCVUM.js +81 -0
  106. package/dist/chunk-K2DZCH2K.js +2 -0
  107. package/dist/chunk-K63CAPS2.js +23 -0
  108. package/dist/chunk-KBIC6JHJ.js +2 -0
  109. package/dist/chunk-KFFQURUZ.js +2 -0
  110. package/dist/chunk-KFOYCQAJ.js +9 -0
  111. package/dist/chunk-KGKCJFWZ.js +6 -0
  112. package/dist/chunk-KK7GPALL.js +28 -0
  113. package/dist/chunk-L7WRUNKJ.js +2 -0
  114. package/dist/{chunk-W4ETQAXM.js → chunk-LFWB7TOJ.js} +2 -2
  115. package/dist/chunk-LGVTIZPV.js +61 -0
  116. package/dist/chunk-LIWIV26I.js +29 -0
  117. package/dist/chunk-LJMWILX6.js +3 -0
  118. package/dist/{chunk-BPAPWKP6.js → chunk-LXMW6ZAX.js} +8 -8
  119. package/dist/chunk-MFBVUQJZ.js +2 -0
  120. package/dist/{chunk-O64IZ6UX.js → chunk-MLTKGHD2.js} +2 -2
  121. package/dist/chunk-MLTSTKXD.js +5 -0
  122. package/dist/chunk-MR4ZKWO6.js +57 -0
  123. package/dist/{chunk-EN3O7VJA.js → chunk-MRXBLYRE.js} +2 -2
  124. package/dist/chunk-MXNGIEPU.js +3 -0
  125. package/dist/chunk-N4EFQIRX.js +20 -0
  126. package/dist/chunk-ND3BWIVN.js +7 -0
  127. package/dist/chunk-NODZYYGC.js +2 -0
  128. package/dist/chunk-NP4JFCLE.js +133 -0
  129. package/dist/chunk-NQXWWE6S.js +8 -0
  130. package/dist/chunk-NSDPPUDY.js +7 -0
  131. package/dist/chunk-NT4NVEHU.js +18 -0
  132. package/dist/chunk-O2VY47Y5.js +325 -0
  133. package/dist/chunk-O3EX5STE.js +5 -0
  134. package/dist/chunk-O4PZFAXA.js +3 -0
  135. package/dist/chunk-OA2BO4DR.js +2 -0
  136. package/dist/chunk-OFZVFIDF.js +3 -0
  137. package/dist/{chunk-PQCI4SQX.js → chunk-OG5UK2K7.js} +2 -2
  138. package/dist/chunk-OMVNRPST.js +2 -0
  139. package/dist/{chunk-7BAVHKMJ.js → chunk-OU6SDWAM.js} +9 -9
  140. package/dist/{chunk-LY4WC4AD.js → chunk-OY7PCALC.js} +2 -2
  141. package/dist/{chunk-A73XVBCR.js → chunk-P3UFF22M.js} +2 -2
  142. package/dist/chunk-PAZSBPJR.js +3 -0
  143. package/dist/chunk-PJBYDCBQ.js +38 -0
  144. package/dist/chunk-PRLU3I7G.js +79 -0
  145. package/dist/chunk-PU6XDQ2X.js +16 -0
  146. package/dist/{chunk-3CLX5EOX.js → chunk-PWEQ6CZZ.js} +2 -2
  147. package/dist/{chunk-XSRF6Q77.js → chunk-PX6QNUYF.js} +2 -2
  148. package/dist/chunk-Q4MRRB3C.js +3 -0
  149. package/dist/chunk-QGVUPYBC.js +35 -0
  150. package/dist/chunk-QH5Q6M5C.js +2 -0
  151. package/dist/chunk-QLWZUFDT.js +2 -0
  152. package/dist/chunk-QN2AI3D2.js +3 -0
  153. package/dist/{chunk-JAYYFEQY.js → chunk-QZCACNV5.js} +2 -2
  154. package/dist/chunk-RNKRYK6B.js +4 -0
  155. package/dist/chunk-RSUH7G5T.js +29 -0
  156. package/dist/chunk-RZWBTKXO.js +5 -0
  157. package/dist/chunk-SBFDPHKH.js +4 -0
  158. package/dist/{chunk-HX4GQPZP.js → chunk-SGSPCEFC.js} +3 -3
  159. package/dist/chunk-SIGVQT43.js +2 -0
  160. package/dist/chunk-SRIZDEWX.js +4 -0
  161. package/dist/chunk-SV2LEFVM.js +2 -0
  162. package/dist/chunk-T2PBOVDI.js +3 -0
  163. package/dist/chunk-TP2X2C2Y.js +3 -0
  164. package/dist/chunk-U2MNECDU.js +2 -0
  165. package/dist/chunk-U7DOYZDH.js +2 -0
  166. package/dist/chunk-UAQQR55F.js +2 -0
  167. package/dist/chunk-UBETC3Q2.js +2 -0
  168. package/dist/chunk-UEQORB2A.js +2 -0
  169. package/dist/chunk-UM56ZET4.js +38 -0
  170. package/dist/chunk-UXNXOMXJ.js +2 -0
  171. package/dist/{chunk-6SHPK5ZE.js → chunk-V6XENWOF.js} +2 -2
  172. package/dist/chunk-VJAD5WX5.js +2 -0
  173. package/dist/chunk-VRJG7N3I.js +453 -0
  174. package/dist/chunk-W7HN6V4E.js +7 -0
  175. package/dist/chunk-WCIKJ2E3.js +3 -0
  176. package/dist/chunk-WEXQYJY3.js +5 -0
  177. package/dist/chunk-WOPZX5GM.js +2 -0
  178. package/dist/chunk-WRQXLNYE.js +9 -0
  179. package/dist/{chunk-XKWKXZKW.js → chunk-WV6R37XV.js} +2 -2
  180. package/dist/{chunk-N5W4YZMK.js → chunk-WZ7V4BQV.js} +2 -2
  181. package/dist/chunk-WZRNEVYC.js +2 -0
  182. package/dist/chunk-X5MWO4DM.js +7 -0
  183. package/dist/chunk-XDAUYDFT.js +2 -0
  184. package/dist/{chunk-L7AW2QB5.js → chunk-XDOEHEET.js} +2 -2
  185. package/dist/chunk-XDQX6LDT.js +4 -0
  186. package/dist/chunk-XFRHBAIT.js +2 -0
  187. package/dist/chunk-XIPGCT3D.js +5 -0
  188. package/dist/chunk-XKM5D2XS.js +16 -0
  189. package/dist/chunk-XNF5T4T2.js +4 -0
  190. package/dist/chunk-Y2S4YNLH.js +3 -0
  191. package/dist/chunk-YA72ZUKO.js +2 -0
  192. package/dist/chunk-YBWE6J32.js +43 -0
  193. package/dist/chunk-YCXQQ3YB.js +2 -0
  194. package/dist/chunk-YDTK77JP.js +43 -0
  195. package/dist/chunk-YF25RQER.js +4 -0
  196. package/dist/chunk-YKHL4J3G.js +2 -0
  197. package/dist/chunk-YLNCTPOI.js +4 -0
  198. package/dist/chunk-YR7VRWNX.js +2 -0
  199. package/dist/chunk-YT4IQBET.js +3 -0
  200. package/dist/chunk-YUKYB54I.js +1 -0
  201. package/dist/chunk-Z2KGMIL4.js +2 -0
  202. package/dist/chunk-Z2QB75BS.js +3 -0
  203. package/dist/chunk-Z67JOKRE.js +554 -0
  204. package/dist/chunk-ZGDHC5AT.js +2 -0
  205. package/dist/chunk-ZMS4YCY7.js +2 -0
  206. package/dist/chunk-ZNW5A5VX.js +3 -0
  207. package/dist/{chunk-TFRAYKN6.js → chunk-ZP2WUVZ5.js} +2 -2
  208. package/dist/chunk-ZQUNCTEZ.js +2 -0
  209. package/dist/cli-main.js +8 -0
  210. package/dist/cli.js +1 -3
  211. package/dist/code-AXLJBZ6T.js +2 -0
  212. package/dist/code-B17qEMbt.d.ts +121 -0
  213. package/dist/code-result-json-CTZHAQXJ.js +2 -0
  214. package/dist/command-descriptors-6INSCKLW.js +342 -0
  215. package/dist/{config-types-jVM3D7MA.d.ts → config-types-B9B60MiR.d.ts} +199 -23
  216. package/dist/dataflow-AFXY423Q.js +2 -0
  217. package/dist/{db-B5PM5yNk.d.ts → db-BwIVAYNB.d.ts} +1 -1
  218. package/dist/dependence-slice-2G4X6VSJ.js +2 -0
  219. package/dist/deps-LMCAV5DO.js +2 -0
  220. package/dist/direct-navigation-2ONV22Y2.js +3 -0
  221. package/dist/entry-map-ZOC3VXO5.js +2 -0
  222. package/dist/exploration-topology-BG4v30HZ.d.ts +256 -0
  223. package/dist/file-dep-graph-Bqg3t3Px.d.ts +4 -0
  224. package/dist/file-kind-BKCVMNUf.d.ts +10 -0
  225. package/dist/files-WJQJLHMH.js +2 -0
  226. package/dist/graph-evidence-Bjyky2V4.d.ts +126 -0
  227. package/dist/graph-exploration-contract-CqDsnPQL.d.ts +7 -0
  228. package/dist/{health-Do5TKSJI.d.ts → health-CPp2Jf1Z.d.ts} +33 -34
  229. package/dist/hierarchy-ASNIHAX4.js +2 -0
  230. package/dist/imports-JICEKDKK.js +2 -0
  231. package/dist/index.d.ts +4 -31
  232. package/dist/index.js +1 -1
  233. package/dist/members-C5H2K3MS.js +2 -0
  234. package/dist/methods-KZOZHSD4.js +2 -0
  235. package/dist/next-anchor-candidates-BwMczMvX.d.ts +90 -0
  236. package/dist/output-continuation-command-NX3RH3TP.js +3 -0
  237. package/dist/output-pagination-3OFL2MJV.js +19 -0
  238. package/dist/postinstall.js +1 -1
  239. package/dist/project-reindex-A2SXUH2H.js +3 -0
  240. package/dist/queries/affected.d.ts +22 -4
  241. package/dist/queries/affected.js +1 -1
  242. package/dist/queries/anchors.d.ts +123 -0
  243. package/dist/queries/anchors.js +2 -0
  244. package/dist/queries/architecture.d.ts +3 -2
  245. package/dist/queries/architecture.js +1 -1
  246. package/dist/queries/bottlenecks.d.ts +26 -7
  247. package/dist/queries/bottlenecks.js +1 -1
  248. package/dist/queries/by-kind.d.ts +2 -2
  249. package/dist/queries/by-kind.js +1 -1
  250. package/dist/queries/call-graph.d.ts +17 -3
  251. package/dist/queries/call-graph.js +1 -1
  252. package/dist/queries/change-surface.d.ts +2 -2
  253. package/dist/queries/change-surface.js +1 -1
  254. package/dist/queries/cleanup-plan.d.ts +2 -2
  255. package/dist/queries/cleanup-plan.js +1 -1
  256. package/dist/queries/co-change.d.ts +2 -2
  257. package/dist/queries/co-change.js +1 -1
  258. package/dist/queries/code.d.ts +5 -26
  259. package/dist/queries/code.js +1 -1
  260. package/dist/queries/complexity-hotspots.d.ts +2 -2
  261. package/dist/queries/complexity-hotspots.js +1 -1
  262. package/dist/queries/complexity.d.ts +2 -2
  263. package/dist/queries/complexity.js +1 -1
  264. package/dist/queries/context.d.ts +145 -0
  265. package/dist/queries/context.js +2 -0
  266. package/dist/queries/convergence.d.ts +2 -2
  267. package/dist/queries/convergence.js +1 -1
  268. package/dist/queries/coupling.d.ts +8 -3
  269. package/dist/queries/coupling.js +1 -1
  270. package/dist/queries/cycles.d.ts +34 -7
  271. package/dist/queries/cycles.js +1 -1
  272. package/dist/queries/dataflow.d.ts +40 -14
  273. package/dist/queries/dataflow.js +1 -1
  274. package/dist/queries/dead.d.ts +2 -2
  275. package/dist/queries/dead.js +1 -1
  276. package/dist/queries/decorative-checkers.d.ts +3 -3
  277. package/dist/queries/decorative-checkers.js +1 -1
  278. package/dist/queries/deep-chains.d.ts +4 -38
  279. package/dist/queries/deep-chains.js +1 -1
  280. package/dist/queries/dependence-slice.d.ts +47 -0
  281. package/dist/queries/dependence-slice.js +2 -0
  282. package/dist/queries/dependency-depth.d.ts +49 -0
  283. package/dist/queries/dependency-depth.js +2 -0
  284. package/dist/queries/deps.d.ts +4 -2
  285. package/dist/queries/deps.js +1 -1
  286. package/dist/queries/diff-impact.d.ts +3 -3
  287. package/dist/queries/diff-impact.js +1 -1
  288. package/dist/queries/doc-drift.d.ts +4 -4
  289. package/dist/queries/doc-drift.js +1 -1
  290. package/dist/queries/drift.d.ts +2 -2
  291. package/dist/queries/drift.js +1 -1
  292. package/dist/queries/duplicate-bodies.d.ts +2 -2
  293. package/dist/queries/duplicate-bodies.js +1 -1
  294. package/dist/queries/entry-map.d.ts +121 -0
  295. package/dist/queries/entry-map.js +2 -0
  296. package/dist/queries/evidence.d.ts +70 -0
  297. package/dist/queries/evidence.js +2 -0
  298. package/dist/queries/extract-candidates.d.ts +2 -2
  299. package/dist/queries/extract-candidates.js +1 -1
  300. package/dist/queries/fan.d.ts +18 -5
  301. package/dist/queries/fan.js +1 -1
  302. package/dist/queries/files.d.ts +2 -2
  303. package/dist/queries/files.js +1 -1
  304. package/dist/queries/health.d.ts +4 -3
  305. package/dist/queries/health.js +1 -1
  306. package/dist/queries/hierarchy.d.ts +5 -3
  307. package/dist/queries/hierarchy.js +1 -1
  308. package/dist/queries/hotspots.d.ts +11 -5
  309. package/dist/queries/hotspots.js +1 -1
  310. package/dist/queries/imports.d.ts +2 -2
  311. package/dist/queries/imports.js +1 -1
  312. package/dist/queries/incomplete-migration.d.ts +4 -4
  313. package/dist/queries/incomplete-migration.js +1 -1
  314. package/dist/queries/index.d.ts +56 -136
  315. package/dist/queries/index.js +1 -1
  316. package/dist/queries/isolated.d.ts +2 -2
  317. package/dist/queries/isolated.js +1 -1
  318. package/dist/queries/locality-candidates.d.ts +2 -2
  319. package/dist/queries/locality-candidates.js +1 -1
  320. package/dist/queries/members.d.ts +2 -2
  321. package/dist/queries/members.js +1 -1
  322. package/dist/queries/methods.d.ts +2 -2
  323. package/dist/queries/methods.js +1 -1
  324. package/dist/queries/not-implemented.d.ts +3 -3
  325. package/dist/queries/not-implemented.js +1 -1
  326. package/dist/queries/outline.d.ts +2 -2
  327. package/dist/queries/outline.js +1 -1
  328. package/dist/queries/passthrough-candidates.d.ts +5 -9
  329. package/dist/queries/passthrough-candidates.js +1 -1
  330. package/dist/queries/plan-context.d.ts +27 -64
  331. package/dist/queries/plan-context.js +1 -1
  332. package/dist/queries/react-component-duplicates.d.ts +2 -2
  333. package/dist/queries/react-component-duplicates.js +1 -1
  334. package/dist/queries/react-hook-candidates.d.ts +2 -2
  335. package/dist/queries/react-hook-candidates.js +1 -1
  336. package/dist/queries/react-large-component-pressure.d.ts +2 -2
  337. package/dist/queries/react-large-component-pressure.js +1 -1
  338. package/dist/queries/recent-duplicates.d.ts +2 -2
  339. package/dist/queries/recent-duplicates.js +1 -1
  340. package/dist/queries/redundant-reexports.d.ts +2 -2
  341. package/dist/queries/redundant-reexports.js +1 -1
  342. package/dist/queries/reference-neighborhood.d.ts +4 -0
  343. package/dist/queries/reference-neighborhood.js +2 -0
  344. package/dist/queries/reference-reachability.d.ts +48 -0
  345. package/dist/queries/reference-reachability.js +2 -0
  346. package/dist/queries/refs.d.ts +2 -2
  347. package/dist/queries/refs.js +1 -1
  348. package/dist/queries/self-audit.d.ts +2 -2
  349. package/dist/queries/self-audit.js +1 -1
  350. package/dist/queries/similar-chains.d.ts +2 -2
  351. package/dist/queries/similar-chains.js +1 -1
  352. package/dist/queries/similar-files.d.ts +2 -2
  353. package/dist/queries/similar-files.js +1 -1
  354. package/dist/queries/similar-signatures.d.ts +2 -2
  355. package/dist/queries/similar-signatures.js +1 -1
  356. package/dist/queries/similar.d.ts +2 -2
  357. package/dist/queries/similar.js +1 -1
  358. package/dist/queries/slice.d.ts +3 -36
  359. package/dist/queries/slice.js +1 -1
  360. package/dist/queries/source-inspection.d.ts +209 -0
  361. package/dist/queries/source-inspection.js +2 -0
  362. package/dist/queries/source-search.d.ts +13 -0
  363. package/dist/queries/source-search.js +2 -0
  364. package/dist/queries/stale-abstractions.d.ts +2 -2
  365. package/dist/queries/stale-abstractions.js +1 -1
  366. package/dist/queries/stats.d.ts +2 -2
  367. package/dist/queries/surface.d.ts +13 -4
  368. package/dist/queries/surface.js +1 -1
  369. package/dist/queries/symbols.d.ts +2 -2
  370. package/dist/queries/symbols.js +1 -1
  371. package/dist/queries/system-map.d.ts +449 -0
  372. package/dist/queries/system-map.js +2 -0
  373. package/dist/queries/system.d.ts +5 -3
  374. package/dist/queries/system.js +1 -1
  375. package/dist/queries/test-quality.d.ts +2 -2
  376. package/dist/queries/test-quality.js +1 -1
  377. package/dist/queries/trace.d.ts +47 -3
  378. package/dist/queries/trace.js +1 -1
  379. package/dist/queries/twin-ab.d.ts +3 -3
  380. package/dist/queries/twin-ab.js +1 -1
  381. package/dist/queries/twin-drift.d.ts +3 -3
  382. package/dist/queries/twin-drift.js +1 -1
  383. package/dist/queries/unused-imports.d.ts +2 -2
  384. package/dist/queries/unused-imports.js +1 -1
  385. package/dist/queries/unused-params.d.ts +2 -2
  386. package/dist/queries/unused-params.js +1 -1
  387. package/dist/queries/value-flow.d.ts +43 -0
  388. package/dist/queries/value-flow.js +2 -0
  389. package/dist/queries/vue-component-duplicates.d.ts +2 -2
  390. package/dist/queries/vue-component-duplicates.js +1 -1
  391. package/dist/queries/vue-composable-candidates.d.ts +2 -2
  392. package/dist/queries/vue-composable-candidates.js +1 -1
  393. package/dist/queries/vue-large-view-pressure.d.ts +2 -2
  394. package/dist/queries/vue-large-view-pressure.js +1 -1
  395. package/dist/queries/wrapper-candidates.d.ts +2 -2
  396. package/dist/queries/wrapper-candidates.js +1 -1
  397. package/dist/query-service-fastpath.js +6 -0
  398. package/dist/query-service-server.js +5 -0
  399. package/dist/refs-ZOORVRQC.js +2 -0
  400. package/dist/refs-pagination-SRCUOYRD.js +2 -0
  401. package/dist/reindex-worker.js +85 -86
  402. package/dist/reindex.d.ts +64 -42
  403. package/dist/reindex.js +93 -77
  404. package/dist/repository-text-C0Q8VYdN.d.ts +19 -0
  405. package/dist/runtime.d.ts +287 -8
  406. package/dist/runtime.js +4 -3
  407. package/dist/rust-semantic-session-server.js +1 -1
  408. package/dist/rust-semantic-session-worker.js +1 -1
  409. package/dist/rust-semantic-worker.js +1 -1
  410. package/dist/{scip-cli-BnEwZRLJ.d.ts → scip-cli-H-n59izO.d.ts} +33 -2
  411. package/dist/slice-NOTBWA7S.js +2 -0
  412. package/dist/source-search-types-Dwz8KeuW.d.ts +79 -0
  413. package/dist/source-snippet-_wrcgmZc.d.ts +15 -0
  414. package/dist/stats-OOJ74B32.js +2 -0
  415. package/dist/surface-BTBCLKNA.js +2 -0
  416. package/dist/symbol-resolution-SVSMX4RN.js +2 -0
  417. package/dist/system-2EIUFP6B.js +2 -0
  418. package/dist/trace-BB2GHQPG.js +2 -0
  419. package/dist/typescript-mailbox-worker.js +1 -1
  420. package/dist/value-flow-OA7AHSUG.js +2 -0
  421. package/dist/watch-server.js +3 -2
  422. package/docs/AGENT_GUIDE.md +133 -476
  423. package/docs/AI_FAILURE_MODES.md +30 -301
  424. package/docs/API.md +1 -1
  425. package/docs/API_EVOLUTION.md +6 -0
  426. package/docs/CLI_JSON_OUTPUT.md +207 -29
  427. package/docs/COMMAND_REFERENCE.md +255 -154
  428. package/docs/CONFIGURATION_WRITE_SAFETY.md +14 -13
  429. package/docs/DETECTOR_EVIDENCE_CONTRACTS.md +84 -0
  430. package/docs/DETECTOR_GUIDE.md +46 -138
  431. package/docs/DURABILITY.md +7 -1
  432. package/docs/INDEX_GENERATIONS.md +6 -0
  433. package/docs/LOCK_PROTOCOL.md +8 -0
  434. package/docs/REINDEX_METADATA_COMPATIBILITY.md +13 -3
  435. package/docs/SECURITY_MODEL.md +39 -42
  436. package/docs/accuracy-audit-checklist.md +4 -0
  437. package/docs/accuracy-hardening-goal.md +9 -2
  438. package/docs/analyzer-inventory.md +59 -264
  439. package/docs/analyzer-validation-protocol.md +62 -170
  440. package/docs/architecture-coherence-vision.md +18 -12
  441. package/docs/locality-analyzer-design.md +1 -1
  442. package/docs/schemas/cli-json-envelope.schema.json +212 -27
  443. package/docs/schemas/cli-json-export-receipt.schema.json +25 -0
  444. package/docs/schemas/cli-output-page.schema.json +1 -1
  445. package/docs/schemas/observation-receipt.schema.json +164 -0
  446. package/docs/schemas/project-config.schema.json +37 -45
  447. package/docs/schemas/suppression-record.schema.json +1 -34
  448. package/package.json +69 -11
  449. package/skills/concrete-plan/SKILL.md +8 -0
  450. package/skills/concrete-plan/agents/openai.yaml +4 -0
  451. package/skills/scip-explore/SKILL.md +49 -61
  452. package/skills/scip-explore/agents/openai.yaml +3 -3
  453. package/skills/scip-explore/references/delegated-exploration.md +51 -0
  454. package/skills/scip-explore/references/external-evidence.md +72 -0
  455. package/skills/scip-explore/references/information-model.md +51 -0
  456. package/skills/scip-explore/scripts/capture-evidence.mjs +666 -0
  457. package/skills/scip-integrity-audit/SKILL.md +185 -0
  458. package/skills/scip-integrity-audit/agents/openai.yaml +4 -0
  459. package/skills/scip-plan/SKILL.md +67 -49
  460. package/skills/scip-plan/agents/openai.yaml +3 -3
  461. package/skills/scip-query/SKILL.md +98 -77
  462. package/skills/scip-query/agents/openai.yaml +3 -3
  463. package/skills/scip-setup/SKILL.md +10 -102
  464. package/skills/scip-setup/agents/openai.yaml +3 -3
  465. package/dist/chunk-26QA6FAI.js +0 -8
  466. package/dist/chunk-2KAZEZ6M.js +0 -2
  467. package/dist/chunk-3ORVDL3H.js +0 -2
  468. package/dist/chunk-46XGSFNI.js +0 -2
  469. package/dist/chunk-4MAK2HOY.js +0 -6
  470. package/dist/chunk-4TURLRL5.js +0 -16
  471. package/dist/chunk-4UQVNCQE.js +0 -2
  472. package/dist/chunk-55Q3WLZX.js +0 -2
  473. package/dist/chunk-5I5G2QOX.js +0 -3
  474. package/dist/chunk-6LDJQXAH.js +0 -2
  475. package/dist/chunk-6O5TICIZ.js +0 -3
  476. package/dist/chunk-7O5IKBTZ.js +0 -16
  477. package/dist/chunk-7S5E7KWT.js +0 -2
  478. package/dist/chunk-7WPLAODU.js +0 -5
  479. package/dist/chunk-AFHORGLH.js +0 -42
  480. package/dist/chunk-AIE7TFJW.js +0 -9
  481. package/dist/chunk-AQOFWNQJ.js +0 -1
  482. package/dist/chunk-B2PX5I6M.js +0 -2
  483. package/dist/chunk-B75HZHUP.js +0 -2
  484. package/dist/chunk-B7PBSLZN.js +0 -2
  485. package/dist/chunk-BBW6JFHN.js +0 -2
  486. package/dist/chunk-BNXCIFVY.js +0 -2
  487. package/dist/chunk-BS2NMXQZ.js +0 -4
  488. package/dist/chunk-C3KV2II6.js +0 -2
  489. package/dist/chunk-C43RDDP4.js +0 -20
  490. package/dist/chunk-DAFAHMNB.js +0 -42
  491. package/dist/chunk-DQLPXMH6.js +0 -8
  492. package/dist/chunk-EKZTZXHZ.js +0 -117
  493. package/dist/chunk-EW2NTSFA.js +0 -18
  494. package/dist/chunk-F3Z4OUDS.js +0 -8
  495. package/dist/chunk-FJH2NW7J.js +0 -66
  496. package/dist/chunk-FTFP6O3L.js +0 -11
  497. package/dist/chunk-FYLK2DEJ.js +0 -2
  498. package/dist/chunk-GH74ASD6.js +0 -11
  499. package/dist/chunk-GMXWZP2B.js +0 -2
  500. package/dist/chunk-GOUBFH5O.js +0 -3
  501. package/dist/chunk-HLF2TX6R.js +0 -2
  502. package/dist/chunk-HX7M4BDI.js +0 -30
  503. package/dist/chunk-HZ72SESS.js +0 -128
  504. package/dist/chunk-IB2N4FIY.js +0 -10
  505. package/dist/chunk-IZYYAFN5.js +0 -2
  506. package/dist/chunk-JFGGXWQF.js +0 -947
  507. package/dist/chunk-JN4NMBEX.js +0 -8
  508. package/dist/chunk-JW56N3KI.js +0 -4
  509. package/dist/chunk-JZ2OXNWB.js +0 -2
  510. package/dist/chunk-KFZNKUNT.js +0 -2
  511. package/dist/chunk-L5GJNV2T.js +0 -8
  512. package/dist/chunk-L7JDSCDF.js +0 -4
  513. package/dist/chunk-LU47HG23.js +0 -14
  514. package/dist/chunk-LVY7NPF7.js +0 -2
  515. package/dist/chunk-MKCDWWGV.js +0 -4
  516. package/dist/chunk-MNE7YG56.js +0 -2
  517. package/dist/chunk-MRXBEXSY.js +0 -26
  518. package/dist/chunk-MV7OWDUX.js +0 -2
  519. package/dist/chunk-NGEXCJJW.js +0 -11
  520. package/dist/chunk-NIW6JDC5.js +0 -29
  521. package/dist/chunk-PBUQFCNB.js +0 -16
  522. package/dist/chunk-POAVPHH7.js +0 -2
  523. package/dist/chunk-QZ4JVECJ.js +0 -2
  524. package/dist/chunk-RDO52JGY.js +0 -2
  525. package/dist/chunk-RJT3TUUZ.js +0 -2
  526. package/dist/chunk-RVLDN63O.js +0 -4
  527. package/dist/chunk-RXOXSKY3.js +0 -2
  528. package/dist/chunk-S7OYBOCK.js +0 -2
  529. package/dist/chunk-SMNXQT5Z.js +0 -3
  530. package/dist/chunk-SRAFT254.js +0 -2
  531. package/dist/chunk-T7YQSHPQ.js +0 -3
  532. package/dist/chunk-UJCOIXDY.js +0 -2
  533. package/dist/chunk-UJPRPGCO.js +0 -13
  534. package/dist/chunk-WCCFZ7V7.js +0 -113
  535. package/dist/chunk-WUPW3UN3.js +0 -3
  536. package/dist/chunk-X54AGLVX.js +0 -2
  537. package/dist/chunk-Y2MVPNKY.js +0 -5
  538. package/dist/chunk-YKUU5AIC.js +0 -3
  539. package/dist/chunk-YLCJLTPL.js +0 -2
  540. package/dist/chunk-YTQVETEO.js +0 -2
  541. package/dist/chunk-Z4N3MZYA.js +0 -38
  542. package/dist/chunk-ZJOOT3BG.js +0 -2
  543. package/dist/chunk-ZK26BAQL.js +0 -2
  544. package/dist/command-descriptors-DSS46KXI.js +0 -642
  545. package/dist/diff-gate-types-B0QYpDv1.d.ts +0 -11
  546. package/dist/direct-navigation-6YHV6IB5.js +0 -3
  547. package/dist/queries/diff-gate.d.ts +0 -253
  548. package/dist/queries/diff-gate.js +0 -2
  549. package/docs/COMMITTED_RECORD_COMPATIBILITY.md +0 -154
  550. package/docs/analyzer-validation-ledger.md +0 -516
  551. package/docs/schemas/outcome-event-record.schema.json +0 -95
  552. package/skills/_shared/SKILL.md +0 -101
  553. package/skills/_shared/agents/openai.yaml +0 -4
  554. package/skills/_shared/references/agent-contract-catalog.md +0 -105
  555. package/skills/_shared/references/command-catalog.md +0 -118
  556. package/skills/_shared/references/detector-precision-and-diffgate.md +0 -59
  557. package/skills/_shared/references/evidence-and-dead-code.md +0 -25
  558. package/skills/scip-audit/SKILL.md +0 -77
  559. package/skills/scip-audit/agents/openai.yaml +0 -4
  560. package/skills/scip-audit/references/claims.md +0 -98
  561. package/skills/scip-audit/references/cleanup.md +0 -100
  562. package/skills/scip-audit/references/directory.md +0 -222
  563. package/skills/scip-audit/references/frontend.md +0 -130
  564. package/skills/scip-audit/references/integrity.md +0 -154
  565. package/skills/scip-audit/references/maintainability.md +0 -162
  566. package/skills/scip-audit/references/twin-drift.md +0 -104
  567. package/skills/scip-diagnose/SKILL.md +0 -52
  568. package/skills/scip-diagnose/agents/openai.yaml +0 -4
  569. package/skills/scip-diagnose/references/debug.md +0 -117
  570. package/skills/scip-diagnose/references/probe-reachability.md +0 -77
  571. package/skills/scip-diagnose/references/root-cause.md +0 -145
  572. package/skills/scip-diagnose/references/triage.md +0 -119
  573. package/skills/scip-explore/references/diagrams.md +0 -40
  574. package/skills/scip-explore/references/language-playbook.md +0 -49
  575. package/skills/scip-improve/SKILL.md +0 -56
  576. package/skills/scip-improve/agents/openai.yaml +0 -4
  577. package/skills/scip-improve/references/cleanup-batches.md +0 -53
  578. package/skills/scip-improve/references/directory-moves.md +0 -53
  579. package/skills/scip-improve/references/doc-reconcile.md +0 -30
  580. package/skills/scip-improve/references/frontend-extraction.md +0 -39
  581. package/skills/scip-improve/references/maintainability-mechanism.md +0 -43
  582. package/skills/scip-improve/references/twin-drift.md +0 -35
  583. package/skills/scip-plan/references/api-impact.md +0 -19
  584. package/skills/scip-plan/references/conductor.md +0 -41
  585. package/skills/scip-plan/references/high-assurance.md +0 -43
  586. package/skills/scip-plan/references/hyper-optimization.md +0 -50
  587. package/skills/scip-plan/references/tla-model.md +0 -88
  588. package/skills/scip-setup/references/bootstrap-workflow.md +0 -119
  589. package/skills/scip-setup/references/language-verification.md +0 -61
  590. package/skills/scip-setup/references/lifecycle-commands.md +0 -119
  591. package/skills/scip-setup/references/per-repo-triage.md +0 -24
  592. package/skills/scip-verify/SKILL.md +0 -229
  593. package/skills/scip-verify/agents/openai.yaml +0 -4
  594. package/skills/scip-verify/references/calibrate-detectors.md +0 -170
@@ -1,3 +1,4 @@
1
- import{c as vt,f as yt,g as ee,h as Le,i as L,j as Wt,k as re,m as Tt,n as Et,o as Pt}from"./chunk-L5GJNV2T.js";import"./chunk-IZYYAFN5.js";import{b as Ct,c as ie,d as ne,e as Oe,f as se,g as Mt,h as De,i as At,k as qt}from"./chunk-DAFAHMNB.js";import{Aa as kt,B as gt,g as ke,h as st,i as ot,j as K,l as We,m as ct,n as lt,o as dt,p as Ee,q as ut,r as Pe,s as ft,t as mt,va as Rt,ya as te,za as xt}from"./chunk-HZ72SESS.js";import{g as St}from"./chunk-FJH2NW7J.js";import"./chunk-WUPW3UN3.js";import{A as wt,B as bt,C as Ae,D as qe,E as _e,F as It,b as N,i as xe,j as _,k as nt,l as I,m as Ce,n as ht,o as Me,p as pt,r as Q,s as Z}from"./chunk-AIE7TFJW.js";import"./chunk-HGFDYOVB.js";import{a as b,b as at,c as Te,d as x}from"./chunk-MNE7YG56.js";import{h as E}from"./chunk-46XGSFNI.js";import R from"process";import{rmSync as kr}from"fs";import{resolve as Ei}from"path";import{pathToFileURL as Pi}from"url";import{statSync as Tr}from"fs";import{basename as Er,isAbsolute as Pr,join as Cr,relative as Mr}from"path";import{watch as Ar}from"chokidar";import qr from"ignore";var Dt=5e3,ae=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onReindexError;onRefreshSuppressed;onError;reindexRunner;subscriptionFactory;clock;activeOperation=null;stopPromise=null;stopInProgress=!1;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(e){this.projectRoot=e.projectRoot,this.config=e.config,this.watchConfig=ne(e.config),this.languages=e.languages,this.pnpmWorkspaces=e.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=e.config.indexer?.typescript?.projectMode,this.typescriptProjects=e.config.indexer?.typescript?.projects,this.clojureConfigPath=e.config.indexer?.clojure?.configPath,this.indexerConcurrency=e.config.indexerConcurrency,this.onStatus=e.onStatus??(()=>{}),this.onReindexComplete=e.onReindexComplete??(()=>{}),this.onReindexError=e.onReindexError??(()=>{}),this.onRefreshSuppressed=e.onRefreshSuppressed??(()=>{}),this.onError=e.onError??(r=>console.error(r.message)),this.clock=e.clock??jr,jt.set(this,Hr(e.stopTimeoutMs??Dt,"watcher stop timeout")),this.reindexRunner=e.reindexRunner??Vr(),this.subscriptionFactory=e.subscriptionFactory??Nr,this.gitignoreFilter=St(e.projectRoot),this.extraIgnore=qr(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){if(this.stopInProgress)throw new Error("Cannot restart a watcher while its previous ownership is still draining.");this.stopped=!1,this.stopPromise=null,oe(this).errors=[],this.sourcePollingFallbackStarted=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{this.startSourceWatcher()}catch(e){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(e)}`))}}stop(){if(this.stopPromise)return this.stopPromise;this.stopped=!0,this.stopInProgress=!0;let e=this.fsWatchers;this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer();let r=this.activeOperation;r&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"});let i=[...oe(this).closures],n=Lr(this),s=this.clock.now()+n;return this.stopPromise=this.finishStop(e,i,r,s,n).catch(a=>{throw this.stopInProgress=!1,a}),this.stopPromise}requestRefresh(e,r={}){if(!this.stopped){if(!r.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(e);return}this.pendingTrigger=Ot(this.pendingTrigger,e),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}}startSourceWatcher(e=!1){let r=this.subscriptionFactory(this.projectRoot,{ignoreInitial:!0,ignored:(i,n)=>this.isIgnoredWatchPath(i,n?.isDirectory()??!1),usePolling:e,...e?{interval:500,binaryInterval:1e3}:{}});r.on("all",(i,n)=>{this.stopped||this.handleFileChange(n)}),r.on("error",i=>this.handleSourceWatcherError(r,i,e)),this.fsWatchers.push(r)}handleSourceWatcherError(e,r,i){if(i||this.sourcePollingFallbackStarted||!Ur(r)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(r)}`));return}this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(n=>n!==e),Or(oe(this),e,n=>this.onError(n));try{this.startSourceWatcher(!0)}catch(n){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`))}}isIgnoredWatchPath(e,r){let i=this.relativeWatchPath(e);if(!i)return!1;let n=r?`${i}/`:i;return n===".git/"||n.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)}handleFileChange(e){let r=this.relativeWatchPath(e);!r||r===".."||r.startsWith("../")||r===".git"||r.startsWith(".git/")||this.gitignoreFilter.isIgnored(r)||this.extraIgnore.ignores(r)||r.endsWith("index.db")||r.endsWith("index.scip")||r.endsWith("index.db.tmp")||Er(r).startsWith(vt)||this.scheduleReindex({kind:"watch-source",detail:r})}relativeWatchPath(e){let r=Pr(e)?e:Cr(this.projectRoot,e);return Mr(this.projectRoot,r).replaceAll("\\","/")}scheduleReindex(e){if(this.pendingTrigger=Ot(this.pendingTrigger,e),this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}this.clearDebounceTimer();let r=this.wallNow()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:r}),this.debounceTimer=this.clock.setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let e=this.clock.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&e<this.watchConfig.cooldownMs){let s=this.watchConfig.cooldownMs-e;this.dirty=!0;let a=this.wallNow()+s;this.setStatus({state:"cooldown",until:a,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},s);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let r=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let i=this.wallNow();this.setStatus({state:"indexing",startedAt:i});let n=this.reindexRunner.start(this.reindexRequest(r));this.activeOperation=n,n.completion.then(s=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let a=!1;try{a=this.onReindexComplete(s,r)===!0}catch(o){this.onError(o instanceof Error?o:new Error(String(o)))}if(this.dirty&&!this.stopped){if(a){let c=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.onRefreshSuppressed(c),this.setStatus({state:"idle"});return}let o=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(s=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let a=s instanceof Error?s:new Error(String(s));this.onReindexError(a,r),this.onError(a),this.setStatus({state:"idle"})}).finally(()=>{this.activeOperation===n&&(this.activeOperation=null)})}async finishStop(e,r,i,n,s){let a=[],o=e.map(async m=>{try{await m.close()}catch(h){a.push(`watch subscription close failed: ${String(h)}`)}});o.push(...r),i&&o.push((async()=>{try{let m=await i.cancel();m.state==="degraded"&&a.push(m.reason)}catch(m){a.push(`reindex cancellation failed: ${m instanceof Error?m.message:String(m)}`)}})());let c=o.length,l=o.map(m=>m.finally(()=>{c-=1})),u=await _r(l,n,this.clock),d=oe(this);return a.push(...d.errors),d.errors=[],u?this.stopInProgress=!1:(a.push(`watch shutdown exceeded the ${s}ms deadline with ${c} operation(s) still pending`),Promise.all(l).then(()=>{this.stopInProgress=!1})),a.length>0?(this.setStatus({state:"draining",startedAt:this.wallNow(),reason:a.join("; ")}),{state:"degraded",reasons:a}):(this.setStatus({state:"idle"}),{state:"stopped"})}wallNow(){return this.clock.wallNow?.()??this.clock.now()}reindexRequest(e){return{projectRoot:this.projectRoot,config:this.config,languages:this.languages,pnpmWorkspaces:this.pnpmWorkspaces,typescriptProjectMode:this.typescriptProjectMode,typescriptProjects:this.typescriptProjects,clojureConfigPath:this.clojureConfigPath,indexerConcurrency:this.indexerConcurrency,trigger:e}}setStatus(e){this.status=e,this.onStatus(e)}clearDebounceTimer(){this.debounceTimer&&(this.clock.clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(this.clock.clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=this.clock.setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let e=this.lastGitState,r=this.readGitState();if(!e||!r||this.stopped){this.lastGitState=r;return}this.lastGitState=r;let i=e.head!==r.head,n=e.indexPath!==r.indexPath||e.indexMtimeMs!==r.indexMtimeMs||e.indexSize!==r.indexSize;i&&n?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):i?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):n&&this.scheduleReindex({kind:"watch-git-index",detail:r.indexPath??"index changed"})}readGitState(){let e=Ee(this.projectRoot,["rev-parse","--git-path","index"]);if(!e)return null;let r=ut(this.projectRoot,e),i={head:Ee(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:r};try{let n=Tr(r);i.indexMtimeMs=n.mtimeMs,i.indexSize=n.size}catch{i.indexMtimeMs=void 0,i.indexSize=void 0}return i}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};async function _r(t,e,r){if(t.length===0)return!0;let i=Promise.all(t).then(()=>!0),n=Math.max(0,e-r.now()),s=null,a=new Promise(c=>{s=r.setTimeout(()=>c(!1),n)}),o=await Promise.race([i,a]);return o&&s&&r.clearTimeout(s),o}var _t=new WeakMap,jt=new WeakMap;function oe(t){let e=_t.get(t);if(e)return e;let r={closures:new Set,errors:[]};return _t.set(t,r),r}function Lr(t){return jt.get(t)??Dt}function Or(t,e,r){let i=Promise.resolve().then(()=>e.close()).catch(n=>{let s=`watch subscription close failed during polling fallback: ${String(n)}`;t.errors.push(s),r(new Error(s))});t.closures.add(i),i.then(()=>t.closures.delete(i))}function Dr(t){let{projectRoot:e,config:r,languages:i,pnpmWorkspaces:n,typescriptProjectMode:s,typescriptProjects:a,clojureConfigPath:o,indexerConcurrency:c,trigger:l}=t,u=ie(e),d=Object.keys(u).length>0?u:r,m=K(e,d),h=d.indexer?.typescript,g=d.indexer?.clojure;return{workerPath:new URL("./reindex-worker.js",import.meta.url).pathname,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:e,SCIP_REINDEX_OUTPUT_SCIP:m.indexPath,SCIP_REINDEX_OUTPUT_DB:m.dbPath,SCIP_REINDEX_LANGUAGES:(d.languages??i)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(d.indexerConcurrency??c??""),SCIP_REINDEX_PNPM_WORKSPACES:h?.pnpmWorkspaces??n?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:h?.projectMode??s,projects:h?.projects??a??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:g?.configPath??o??"",SCIP_REINDEX_TRIGGER_KIND:l.kind,SCIP_REINDEX_TRIGGER_DETAIL:l.detail??"",SCIP_REINDEX_PROCESS_GROUP_LEADER:"1"}}}var jr={now:b,wallNow:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},Nr=(t,e)=>Ar(t,e),Gr=15*6e4,Fr=1e3,$r=64*1024;function Br(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function Lt(t,e){let r=t instanceof Error?t.message:String(t),i=e.stderrTail.trim()||e.stdoutTail.trim();return i?`${r}
2
- ${i}`:r}function Vr(t={}){let e=t.timeoutMs??Gr,r=t.terminationGraceMs??Fr,i=t.maxOutputBytes??$r,n=t.resolveLaunch??Dr;return{start(s){let a=n(s),o=new AbortController,c=Br(),l=!1,u=Et({command:process.execPath,args:[...process.execArgv,a.workerPath],label:"watch reindex worker",env:a.env,timeoutMs:e,terminationGraceMs:r,maxStdoutBytes:i,maxStderrBytes:i,outputLimitBehavior:"truncate-tail",signal:o.signal,detached:!0}).then(d=>{if(c={stdoutTail:d.stdout,stderrTail:d.stderr,stdoutTruncated:d.stdoutTruncated,stderrTruncated:d.stderrTruncated},d.status!==0)throw new Error(Lt(new Error(`Reindex worker exited with ${d.signal?`signal ${d.signal}`:`code ${d.status}`}`),c));return d.durationMs}).catch(d=>{throw d instanceof Tt&&(c={stdoutTail:d.stdout,stderrTail:d.stderr,stdoutTruncated:d.stdoutTruncated,stderrTruncated:d.stderrTruncated}),new Error(Lt(d,c),{cause:d})}).finally(()=>{l=!0});return{completion:u,async cancel(){l||o.abort();try{await u}catch{}return{state:"exited",diagnostics:c}},diagnostics:()=>c}}}}function Ot(t,e){return t?t.kind===e.kind?t.detail===e.detail?t:{kind:t.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${t.kind}, ${e.kind}`}:e}function Ur(t){return t instanceof Error&&"code"in t&&t.code==="EMFILE"||String(t).includes("EMFILE: too many open files")}function Hr(t,e){if(!Number.isSafeInteger(t)||t<=0)throw new Error(`${e} must be a positive integer.`);return t}import{spawn as oi}from"child_process";import{existsSync as ai,rmSync as er}from"fs";import{dirname as mn,resolve as Ue}from"path";import{fileURLToPath as Sn}from"url";import{createHash as zr,randomUUID as je}from"crypto";import{existsSync as Yr,linkSync as Jr,readdirSync as Xr,rmSync as O}from"fs";import{basename as Kr,dirname as Qr,join as v}from"path";var A=1,Zr=10*6e4,ei=10080*6e4,le="requests",G="claims",ce="completions",Gt="staging";function Ft(t,e,r={}){let i=r.now?.()??new Date,n=ri(r.ttlMs),s=ii(r.idempotencyKey),a=s?`key-${zr("sha256").update(s).digest("hex")}`:`request-${(r.randomId??je)()}`,o={version:A,requestId:a,...s?{idempotencyKey:s}:{},createdAt:i.toISOString(),deadlineAt:new Date(i.getTime()+n).toISOString(),detail:e.trim().slice(0,2048)||"stale index observed by a command"},c=Kt(t,a),l=Fe(t,c,o,r.onStage);if(l.published)return{disposition:"accepted",request:o,achievedDurability:l.achievedDurability,directorySync:l.directorySync};let u=Ge(c);if(!u)throw new Error(`Watch refresh request identity ${a} exists but is malformed.`);return{disposition:"duplicate",request:u}}function $t(t,e={}){let r=e.now?.()??new Date,i=`claim-${(e.randomId??je)()}`,n=Math.max(1,Math.floor(e.limit??64)),s=Yt(t).sort(ni),a=[];for(let o of s){if(a.length>=n)break;if(Nt(t,o.requestId))continue;if(Date.parse(o.deadlineAt)<=r.getTime()){zt(t,{version:A,requestId:o.requestId,outcome:"expired",completedAt:r.toISOString()});continue}let c={version:A,requestId:o.requestId,claimId:i,claimedAt:r.toISOString()};if(Fe(t,Qt(t,o.requestId),c).published){if(Nt(t,o.requestId)){Jt(t,o.requestId,i);continue}a.push(o)}}return{claimId:i,requests:a}}function Bt(t,e,r=()=>new Date,i){let n=r().toISOString();for(let s of e.requests)zt(t,{version:A,requestId:s.requestId,claimId:e.claimId,outcome:"completed",completedAt:n});i?.("after-completion"),de(t,e),i?.("after-claim-release")}function de(t,e){for(let r of e.requests)Jt(t,r.requestId,e.claimId)}function Vt(t){let e=0;for(let r of q(v(t,G)))O(r,{force:!0}),e++;return e>0&&_(v(t,G)),Xt(t),e}function Ne(t){let e=Yt(t),r=new Map,i=ti(v(t,le),Ge);for(let c of q(v(t,ce))){let l=ue(c);if(!l){i++;continue}r.set(l.requestId,l)}let n=new Set;for(let c of q(v(t,G))){let l=Ht(c);if(!l){i++;continue}n.add(l.requestId)}let s=e.filter(c=>!r.has(c.requestId)&&!n.has(c.requestId)),a=[...r.values()].filter(c=>c.outcome==="completed").length,o=[...r.values()].filter(c=>c.outcome==="expired").length;return{pending:s.length,claimed:e.filter(c=>!r.has(c.requestId)&&n.has(c.requestId)).length,completed:a,expired:o,invalid:i,...s.length>0?{oldestPendingAt:s.map(c=>c.createdAt).reduce((c,l)=>si(c,l))}:{}}}function Ut(t,e={}){let r=(e.now?.()??new Date).getTime(),i=Math.max(0,e.retentionMs??ei),n=0;for(let s of q(v(t,ce))){let a=ue(s);!a||r-Date.parse(a.completedAt)<i||(O(s,{force:!0}),O(Kt(t,a.requestId),{force:!0}),n++)}return n>0&&(_(v(t,ce)),_(v(t,le))),Xt(t),n}function Ge(t){return $e(t,e=>{let r=e;return r.version===A&&F(r.requestId)&&(r.idempotencyKey===void 0||typeof r.idempotencyKey=="string")&&N(r.createdAt)&&N(r.deadlineAt)&&Date.parse(r.deadlineAt)>=Date.parse(r.createdAt)&&typeof r.detail=="string"&&r.detail.length>0})}function Ht(t){return $e(t,e=>{let r=e;return r.version===A&&F(r.requestId)&&F(r.claimId)&&N(r.claimedAt)})}function ue(t){return $e(t,e=>{let r=e;return r.version===A&&F(r.requestId)&&(r.claimId===void 0||F(r.claimId))&&(r.outcome==="completed"||r.outcome==="expired")&&N(r.completedAt)})}function zt(t,e){let r=Zt(t,e.requestId);if(Fe(t,r,e).published)return;let i=ue(r);if(!i||i.requestId!==e.requestId||i.outcome!==e.outcome)throw new Error(`Watch refresh completion ${e.requestId} conflicts with an existing record.`)}function Fe(t,e,r,i){let n=v(t,Gt),s=Qr(e),a=xe(n),o=xe(s),c=v(n,`${Kr(e)}.${process.pid}.${je()}.tmp`);try{let l=Z(c,r,{spacing:2,trailingNewline:!0});i?.("after-staged");try{Jr(c,e)}catch(d){if(d.code==="EEXIST")return{published:!1};throw d}let u=nt(a,o,l.directorySync,_(s));return i?.("after-published"),{published:!0,achievedDurability:u==="synced"?"directory-durable":"file-flushed",directorySync:u}}finally{O(c,{force:!0})}}function Yt(t){let e=[];for(let r of q(v(t,le))){let i=Ge(r);i&&e.push(i)}return e}function Jt(t,e,r){let i=Qt(t,e),n=Ht(i);!n||n.claimId!==r||(O(i,{force:!0}),_(v(t,G)))}function Xt(t){for(let e of q(v(t,Gt),".tmp"))O(e,{force:!0})}function ti(t,e){return q(t).filter(r=>!e(r)).length}function q(t,e=".json"){return Yr(t)?Xr(t,{withFileTypes:!0}).filter(r=>r.isFile()&&r.name.endsWith(e)).map(r=>v(t,r.name)).sort():[]}function $e(t,e){try{let r=JSON.parse(E(t,"watch refresh request record"));return e(r)?r:null}catch{return null}}function Kt(t,e){return v(t,le,`${e}.json`)}function Qt(t,e){return v(t,G,`${e}.json`)}function Zt(t,e){return v(t,ce,`${e}.json`)}function Nt(t,e){return ue(Zt(t,e))!==null}function ri(t){if(t===void 0)return Zr;if(!Number.isFinite(t)||t<=0)throw new Error("Watch refresh request ttlMs must be positive.");return Math.floor(t)}function ii(t){let e=t?.trim();return e?e.slice(0,512):void 0}function F(t){return typeof t=="string"&&/^[a-z0-9][a-z0-9-]{0,127}$/i.test(t)}function ni(t,e){return Date.parse(t.createdAt)-Date.parse(e.createdAt)||t.requestId.localeCompare(e.requestId)}function si(t,e){return Date.parse(e)<Date.parse(t)?e:t}var ci=6e3,li=1e3,tr=10;function nr(t,e,r){let i=Pe(Ue(t));if(r&&Pe(r.projectRoot)===i)return{projectRoot:i,worktreeKind:"git",worktreeId:r.worktreeId,cliVersion:e};let n=lt(i);if(n.kind==="error")throw new Error(`Could not establish Git worktree identity for ${i}: ${n.message}`);return n.kind==="non-git"?{projectRoot:i,worktreeKind:"non-git",cliVersion:e}:{projectRoot:i,worktreeKind:"git",worktreeId:n.identity.worktreeId,cliVersion:e}}function sr(t){let e=t.runtime??hi,r=L(t.cacheDir),i=Wt(r.statePath),n=i?e.isProcessAlive(i.pid)?{kind:"live",state:i}:{kind:"stale",state:i,reason:"dead-process"}:{kind:"stopped"},s=di("stop",n);if(s.kind==="signal-stop")return rr(s.state,t,e),Be(r,s.state.pid,e),{disposition:"stopped",pid:s.state.pid};if(s.kind==="clean-stale")return Be(r,s.state.pid,e),{disposition:"stopped",pid:s.state.pid};let a=lr(r.lockPath);return s.kind==="already-stopped"&&a&&e.isProcessAlive(a.pid)?(rr(a,t,e),Be(r,a.pid,e),{disposition:"stopped",pid:a.pid}):{disposition:"already-stopped"}}function or(t,e,r={}){let{durability:i="durable",...n}=r;i==="durable"?Z(t,e,n):Q(t,e,n)}function ar(t){try{let e=JSON.parse(E(t,"watch activity record"));return e.version!==1||!re(e.at)||e.refreshRequestedAt!==void 0&&!re(e.refreshRequestedAt)||e.refreshDetail!==void 0&&typeof e.refreshDetail!="string"?null:{atMs:Date.parse(e.at),...e.refreshRequestedAt===void 0?{}:{refreshRequestedAtMs:Date.parse(e.refreshRequestedAt)},...e.refreshDetail===void 0?{}:{refreshDetail:e.refreshDetail}}}catch{return null}}function cr(t,e,r={}){let i=r.pid??process.pid,n=r.isProcessAlive??I,s=()=>{},a=r.readProcessIdentity??x,o=r.now??(()=>new Date),c={...Ce,wallNow:()=>o().getTime(),isProcessAlive:n,readProcessIdentity:a},l=ht(t,{kind:"watch",pid:i,processIdentity:a(i),detail:{projectRoot:Ue(e)},parseLegacy:he,runtime:c});if(l.kind==="contended"){let u=dr(l.observation);return{acquired:!1,lockPath:t,message:ui(t,e,u),release:s}}return{acquired:!0,lockPath:t,message:"",release:()=>{l.lock.release()}}}function lr(t){return dr(Me(t,{parseLegacy:he}))}var he=t=>{let e=ur(t);return e?{pid:e.pid,...e.processIdentity?{processIdentity:e.processIdentity}:{}}:null};function dr(t){if(t.state==="valid"&&t.record?.kind==="watch"){let e=t.record.detail?.projectRoot;return typeof e!="string"?null:{version:1,pid:t.record.pid,...t.record.processIdentity?{processIdentity:t.record.processIdentity}:{},projectRoot:e,startedAt:t.record.startedAt}}return ur(t.parsed)}function ur(t){try{let e=t;if(e.version!==1||typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0||typeof e.projectRoot!="string"||!re(e.startedAt))return null;let r=e.processIdentity===void 0?null:at(e.processIdentity);return e.processIdentity!==void 0&&(!r||r.pid!==e.pid)?null:{version:1,pid:e.pid,...r?{processIdentity:r}:{},projectRoot:e.projectRoot,startedAt:e.startedAt}}catch{return null}}function di(t,e){switch(t){case"status":return{kind:"report",classification:e};case"ensure":switch(e.kind){case"stopped":return{kind:"start"};case"stale":return e.reason==="old-heartbeat"?{kind:"refuse-replace",state:e.state,reason:"old-heartbeat"}:{kind:"start"};case"live":return{kind:"reuse",state:e.state};case"incompatible":return{kind:"replace",state:e.state};default:return Ve(e)}case"stop":switch(e.kind){case"stopped":return{kind:"already-stopped"};case"stale":return e.reason==="old-heartbeat"?{kind:"signal-stop",state:e.state}:{kind:"clean-stale",state:e.state};case"live":case"incompatible":return{kind:"signal-stop",state:e.state};default:return Ve(e)}default:return Ve(t)}}function hr(t){return t.idleTimeoutMs===0||t.watcher.state!=="idle"?!1:t.nowMs-t.lastActivityAtMs>=t.idleTimeoutMs}function rr(t,e,r){let{pid:i}=t;if(!r.isProcessAlive(i))return;ir(t,r),r.signalProcess(i);let n=e.stopTimeoutMs??ci,s=r.monotonicNow??b,a=s()+n;for(;s()<=a;){if(!r.isProcessAlive(i))return;r.sleep(tr)}if(!r.forceSignalProcess)throw new Error(`scip-query watch service pid ${i} did not stop within ${n}ms and forced termination is unavailable.`);ir(t,r),r.forceSignalProcess(i);let o=e.forceStopTimeoutMs??li,c=s()+o;for(;s()<=c;){if(!r.isProcessAlive(i))return;let l=r.readProcessIdentity(i);if(t.processIdentity&&l&&!Te(t.processIdentity,l))return;r.sleep(tr)}throw new Error(`scip-query watch service pid ${i} remained alive ${o}ms after forced termination.`)}function Be(t,e,r){if(er(t.statePath,{force:!0}),er(t.activityPath,{force:!0}),lr(t.lockPath)?.pid===e&&!r.isProcessAlive(e)){let n={...Ce,wallNow:r.now,isProcessAlive:r.isProcessAlive,readProcessIdentity:r.readProcessIdentity},s=Me(t.lockPath,{parseLegacy:he,runtime:n});pt(t.lockPath,s,{parseLegacy:he,runtime:n})}}function ui(t,e,r){return`error: scip-query watch is already running for ${Ue(e)}${r?` (pid ${r.pid}, started ${r.startedAt}; lock: ${t})`:` (lock: ${t})`}. Stop that watcher before starting another.`}var hi={now:Date.now,monotonicNow:b,isProcessAlive:I,readProcessIdentity:x,spawnServer(t,e,r,i){if(!ai(t))throw new Error(`Watch service helper was not found at ${t}. Run npm run build first.`);oi(process.execPath,[t,e,r,JSON.stringify(i)],{detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"}}).unref()},signalProcess(t){process.kill(t,"SIGTERM")},forceSignalProcess(t){process.kill(t,"SIGKILL")},sleep(t){let e=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(e,0,0,t)}};function ir(t,e){if(!t.processIdentity)throw new Error(`Refusing to signal scip-query watch pid ${t.pid}: its ownership record has no process identity.`);let r=e.readProcessIdentity(t.pid);if(!r)throw new Error(`Refusing to signal scip-query watch pid ${t.pid}: its process identity is unavailable.`);if(!Te(t.processIdentity,r))throw new Error(`Refusing to signal scip-query watch pid ${t.pid}: its process identity does not match the ownership record.`)}function Ve(t){throw new Error(`Unhandled watch service value: ${JSON.stringify(t)}`)}import{existsSync as gr,lstatSync as pe,readdirSync as Sr,realpathSync as pr,rmSync as $,statSync as pi}from"fs";import{join as y,resolve as B,sep as fr}from"path";var fi=3600*1e3,mi=2*1024*1024*1024,gi=300*1e3;function Si(t){let e=t.leases.filter(o=>o.managed&&!o.live&&!o.busy),r=vi(t.leases,t.locks),i={};for(let o of t.generations)r.has(o.generationId)||(i[o.generationId]=o.unreferencedAt??t.nowMs);let n=t.generations.filter(o=>!r.has(o.generationId)).sort((o,c)=>i[o.generationId]-i[c.generationId]||o.generationId.localeCompare(c.generationId)),s=new Set;for(let o of n)t.nowMs-i[o.generationId]>=t.policy.generationTtlMs&&s.add(o.generationId);let a=t.generations.filter(o=>!s.has(o.generationId)).reduce((o,c)=>o+c.size,0);for(let o of n){if(a<=t.policy.budgetBytes)break;s.has(o.generationId)||(s.add(o.generationId),a-=o.size)}for(let o of s)delete i[o];return{deleteWorktrees:e,deleteGenerations:t.generations.filter(o=>s.has(o.generationId)),deleteLocks:t.locks.filter(o=>!o.live),deleteTemporaries:t.temporaries.filter(o=>!o.live),protectedGenerationIds:[...r].sort(),unreferencedSince:i}}function vi(t,e){let r=new Set(t.filter(i=>i.managed&&(i.live||i.busy)).flatMap(i=>[i.lease.baseGenerationId,i.lease.activeGenerationId]).filter(i=>i!==void 0));for(let i of e)i.live&&r.add(i.generationId);return r}function vr(t,e,r={}){if(!ot())return{kind:"disabled"};let i=ct(t);if(!i)return{kind:"unavailable"};let n=y(ke(),"repositories",i.repositoryId);if(!gr(n))return{kind:"unavailable"};let s=(r.now??Date.now)(),a=y(n,"gc-state.json"),o=wi(a);if(!r.force&&o&&s-Date.parse(o.lastSweepAt)<gi)return{kind:"throttled",sweptAt:o.lastSweepAt};let c=ft(n,{now:()=>s});if(!c)return{kind:"busy"};try{let l=yi(t,n,i.repositoryId,o?.unreferencedSince??{}),u=Si({nowMs:s,...l,policy:{generationTtlMs:r.policy?.generationTtlMs??fi,budgetBytes:r.policy?.budgetBytes??mi}}),d=0,m=0;for(let p of u.deleteWorktrees){if(!yr(p.lease))continue;let S=mt(y(p.lease.localCacheDir,"cache-lifecycle.lock"));if(S)try{if(ze(p.lease,!0))continue;try{sr({projectRoot:p.lease.projectRoot,cacheDir:p.lease.localCacheDir,cliVersion:e})}catch{continue}if(ze(p.lease,!0))continue;$(p.lease.localCacheDir,{recursive:!0,force:!0}),$(p.leasePath,{force:!0}),m+=1}finally{S.release()}}for(let p of u.deleteLocks)$(p.path,{force:!0});for(let p of u.deleteTemporaries)$(p.path,{recursive:!0,force:!0});for(let p of u.deleteGenerations)$(p.path,{recursive:!0,force:!0}),d+=p.size;gt(y(n,"evidence.db"));let h={kind:"swept",sweptAt:new Date(s).toISOString(),deletedWorktrees:m,deletedGenerations:u.deleteGenerations.length,deletedBytes:d,protectedGenerations:u.protectedGenerationIds.length},g={version:1,lastSweepAt:h.sweptAt,unreferencedSince:u.unreferencedSince,lastResult:h};return Q(a,g,{spacing:2,trailingNewline:!0}),h}catch(l){return{kind:"failed",error:l instanceof Error?l.message:String(l)}}finally{c.release()}}function yi(t,e,r,i){let n=new Set(dt(t).map(l=>B(l.path))),s=[];for(let l of He(y(e,"worktrees"))){if(!l.endsWith(".json"))continue;let u=y(e,"worktrees",l),d=Ri(u);if(!d)continue;let m=B(d.projectRoot);s.push({leasePath:u,lease:d,managed:d.repositoryId===r&&yr(d),live:n.has(m)||gr(m),busy:ze(d)})}let a=[];for(let l of He(y(e,"locks"))){let u=/^([a-f0-9]{64})\.lock$/.exec(l);if(!u)continue;let d=y(e,"locks",l),m=Ye(d),h=m!==void 0&&I(m),g=u[1];a.push({generationId:g,path:d,live:h})}let o=[],c=[];for(let l of He(y(e,"generations"))){let u=/^\.tmp-(\d+)-/.exec(l);if(u){let h=y(e,"generations",l),g=Number(u[1]);try{c.push({path:h,size:mr(h),live:Number.isSafeInteger(g)&&I(g)})}catch{}continue}if(!/^[a-f0-9]{64}$/.test(l))continue;let d=y(e,"generations",l),m;try{m=pe(d)}catch{continue}!m.isDirectory()||m.isSymbolicLink()||o.push({generationId:l,path:d,size:mr(d),...i[l]===void 0?{}:{unreferencedAt:i[l]}})}return{leases:s,generations:o,locks:a,temporaries:c}}function yr(t){if(t.ownershipChecksum!==Rt(t)||We(t.localCacheDir)!==We(st(t.projectRoot)))return!1;let e=B(ke()),r=B(y(e,"projects")),i=B(t.localCacheDir);if(!i.startsWith(`${r}${fr}`))return!1;try{let n=pe(e),s=pe(r),a=pe(i);if(!n.isDirectory()||n.isSymbolicLink()||!s.isDirectory()||s.isSymbolicLink()||!a.isDirectory()||a.isSymbolicLink())return!1;let o=pr(r);return pr(i).startsWith(`${o}${fr}`)}catch{return!1}}function ze(t,e=!1){for(let i of e?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let n=Ye(y(t.localCacheDir,i));if(n!==void 0&&I(n))return!0}let r=Ye(L(t.localCacheDir).lockPath);return r!==void 0&&I(r)}function Ri(t){try{let e=JSON.parse(E(t,"worktree cache lease"));return e.version!==1||typeof e.repositoryId!="string"||typeof e.worktreeId!="string"||typeof e.projectRoot!="string"||e.treeOid!==void 0&&typeof e.treeOid!="string"||typeof e.localCacheDir!="string"||e.baseGenerationId!==void 0&&typeof e.baseGenerationId!="string"||e.activeGenerationId!==void 0&&typeof e.activeGenerationId!="string"||typeof e.ownershipChecksum!="string"||!/^[a-f0-9]{64}$/.test(e.ownershipChecksum)||typeof e.lastAction!="string"||e.lastReason!==void 0&&typeof e.lastReason!="string"||typeof e.lastSeenAt!="string"?null:e}catch{return null}}function Ye(t){try{let e=JSON.parse(E(t,"watch lock record"));return typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0?e.pid:void 0}catch{return}}function wi(t){try{let e=JSON.parse(E(t,"repository cache GC state"));return e.version!==1||typeof e.lastSweepAt!="string"||!Number.isFinite(Date.parse(e.lastSweepAt))||!e.unreferencedSince||typeof e.unreferencedSince!="object"||!e.lastResult?null:e}catch{return null}}function He(t){try{return Sr(t)}catch{return[]}}function mr(t){let e=0,r=[t];for(;r.length>0;){let i=r.pop();for(let n of Sr(i,{withFileTypes:!0})){let s=y(i,n.name);n.isDirectory()?r.push(s):n.isFile()&&(e+=pi(s).size)}}return e}var fe=class{root;now;randomId;retryDelayMs;active;retryNotBeforeMs=0;currentStatus;constructor(e,r={}){this.root=e,this.now=r.now??Date.now,this.randomId=r.randomId,this.retryDelayMs=Math.max(1,Math.floor(r.retryDelayMs??1e3)),this.currentStatus=Ne(e)}initializeAfterOwnershipAcquired(){let e=Vt(this.root),r=Ut(this.root,{now:()=>new Date(this.now())});return this.refreshStatus(),{recoveredClaims:e,prunedHistory:r}}observeLegacyRequest(e,r){Ft(this.root,r??"stale index observed by a legacy command",{idempotencyKey:`legacy-activity:${e}`,now:()=>new Date(e)}),this.refreshStatus()}poll(e,r){if(this.active||e.state!=="idle"||this.now()<this.retryNotBeforeMs)return!1;let i=$t(this.root,{now:()=>new Date(this.now()),...this.randomId?{randomId:this.randomId}:{}});if(this.refreshStatus(),i.requests.length===0)return!1;this.active=i;try{return r(bi(i)),!0}catch(n){throw de(this.root,i),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),n}}completeActive(){return this.active?(Bt(this.root,this.active,()=>new Date(this.now())),this.active=void 0,this.retryNotBeforeMs=0,this.refreshStatus(),!0):!1}failActive(){return this.active?(de(this.root,this.active),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),!0):!1}status(){return{...this.currentStatus}}refreshStatus(){this.currentStatus=Ne(this.root)}};function bi(t){if(t.requests.length===1)return t.requests[0].detail;let r=[...new Set(t.requests.map(i=>i.detail))].slice(0,3).join("; ");return`${t.requests.length} coalesced refresh requests${r?`: ${r}`:""}`.slice(0,2048)}import{randomUUID as xi}from"crypto";import{Worker as ki}from"worker_threads";var me=class{constructor(e){this.options=e;this.now=e.now??Date.now,this.setTimer=e.setTimer??setTimeout,this.clearTimer=e.clearTimer??clearTimeout}options;now;setTimer;clearTimer;worker=null;active=null;activeFailure=null;terminating=null;closed=!1;workerGeneration=0;canAccept(){return!this.closed&&this.active===null&&this.terminating===null}start(e){if(!this.canAccept())return!1;if(e.deadlineAtMs<this.now()){try{this.options.onReject(e,`${this.options.name} request expired before processing.`)}catch(s){this.closed=!0,this.options.onFatal(Je(s))}return!0}let r=this.ensureWorker(),i=Math.max(1,Math.min(2147483647,e.deadlineAtMs-this.now())),n=this.setTimer(()=>{this.failActiveAfterTermination(`${this.options.name} request exceeded its deadline.`)},i);this.active={request:e,timer:n};try{r.postMessage({kind:"request",...e})}catch(s){this.failActiveAfterTermination(Rr(s))}return!0}async close(e=`${this.options.name} service is shutting down.`){if(this.closed=!0,this.active){await this.failActiveAfterTermination(e);return}await this.terminateWorker()}ensureWorker(){if(this.worker)return this.worker;let e=this.options.createWorker(),r=++this.workerGeneration;return e.on("message",i=>this.handleMessage(r,i)),e.on("error",i=>{r===this.workerGeneration&&this.failActiveAfterTermination(`${this.options.name} worker failed: ${i.message}`)}),e.on("exit",i=>{r!==this.workerGeneration||this.terminating||(this.worker=null,this.active&&this.failActiveAfterTermination(`${this.options.name} worker exited unexpectedly with code ${i}.`))}),this.worker=e,e}handleMessage(e,r){if(e!==this.workerGeneration||this.closed||!this.active)return;let i=Ii(r);if(!i){this.failActiveAfterTermination(`${this.options.name} worker returned an invalid response.`);return}if(i.requestId!==this.active.request.requestId){this.failActiveAfterTermination(`${this.options.name} worker returned a mismatched request identity.`);return}if(this.now()>this.active.request.deadlineAtMs){this.failActiveAfterTermination(`${this.options.name} request expired while it was processing.`);return}let n=this.active;try{this.options.onStatus(i.status),i.ok?this.options.onComplete(n.request,i.result,i.status):this.options.onReject(n.request,i.error,i.status)}catch(s){this.closed=!0,this.clearTimer(n.timer),this.options.onFatal(Je(s));return}this.releaseActive(n)}async failActiveAfterTermination(e){if(this.activeFailure){await this.activeFailure;return}let r=this.active;if(!r){await this.terminateWorker();return}this.clearTimer(r.timer);let i=(async()=>{if(await this.terminateWorker()){try{this.options.onReject(r.request,e)}catch(s){this.closed=!0,this.options.onFatal(Je(s));return}this.releaseActive(r)}})();this.activeFailure=i;try{await i}finally{this.activeFailure===i&&(this.activeFailure=null)}}releaseActive(e){this.active===e&&(this.active=null,this.clearTimer(e.timer))}async terminateWorker(){if(this.terminating)return this.terminating;let e=this.worker;if(!e)return!0;this.worker=null;let r=++this.workerGeneration;return this.terminating=(async()=>{try{return await e.terminate(),!0}catch(i){return this.closed=!0,this.options.onFatal(new Error(`${this.options.name} worker termination failed: ${Rr(i)}`,{cause:i})),!1}finally{r===this.workerGeneration&&(this.terminating=null)}})(),this.terminating}};function Ii(t){if(!t||typeof t!="object")return null;let e=t;if(e.kind!=="response"||typeof e.requestId!="string"||!("status"in e))return null;if(e.ok===!0){if(!("result"in e)||"error"in e)return null}else if(e.ok===!1){if("result"in e||typeof e.error!="string")return null}else return null;return e}function Je(t){return t instanceof Error?t:new Error(String(t))}function Rr(t){return t instanceof Error?t.message:String(t)}function wr(t){let e=()=>({protocolVersion:te,state:"idle",requests:0,sessionsCreated:0,sessionsReplaced:0,initializations:0,programUpdates:0,documentsEmitted:0,documentsRemoved:0});return Ir({name:"TypeScript index",paths:t.paths,now:t.now,limits:t.limits,initialStatus:e,parseEnvelope:kt,createWorker:()=>xr(t,{kind:"index",projectRoot:t.projectRoot,dbPath:t.dbPath}),complete(r,i,n,s){Ae(t.paths,r,{ok:!0,protocolVersion:te,id:i.id,baseGeneration:i.baseGeneration,response:n},{nowMs:s,limits:t.limits})},reject(r,i,n,s){qe(t.paths,r,{ok:!1,protocolVersion:te,id:i,error:n},n,{nowMs:s,limits:t.limits})},onBusy:t.onBusy,onFatal:t.onFatal})}function br(t){let e=()=>({protocolVersion:se,state:"idle",requests:0,sessionsCreated:0,sessionsReused:0,sessionsRefreshed:0,sessionsReplaced:0,projectsCreated:0});return Ir({name:"TypeScript semantic",paths:t.paths,now:t.now,limits:t.limits,initialStatus:e,parseEnvelope:At,createWorker:()=>xr(t,{kind:"semantic",projectRoot:t.projectRoot}),complete(r,i,n,s){Ae(t.paths,r,{ok:!0,protocolVersion:se,id:i.id,generation:i.generation,response:n},{nowMs:s,limits:t.limits})},reject(r,i,n,s){qe(t.paths,r,{ok:!1,protocolVersion:se,id:i,error:n},n,{nowMs:s,limits:t.limits})},onBusy:t.onBusy,onFatal:t.onFatal})}function Ir(t){let e=t.now??Date.now,r=x(process.pid),i={pid:process.pid,...r?{processIdentity:r}:{}},n=`${t.name.toLowerCase().replaceAll(" ","-")}-${process.pid}-${xi()}`,s={...t.limits,maxBatch:1},a=null,o=t.initialStatus(),c=!1,l=h=>{c=!0,t.onFatal(h)},u=new me({name:t.name,createWorker:t.createWorker,now:e,onComplete(h,g,p){let S=d(h.requestId);o=p,t.complete(S.claim,S.envelope,g,e()),m(S)},onReject(h,g,p){let S=d(h.requestId);p!==void 0&&(o=p),t.reject(S.claim,S.envelope.id,g,e()),m(S)},onStatus(h){o=h},onFatal:l});return{poll(){if(c||!u.canAccept())return 0;let h=wt(t.paths,{ownerId:n,nowMs:e(),limits:s,owner:i,liveness:{isProcessAlive:I,readProcessIdentity:x}})[0];if(!h)return 0;let g=h.requestId;try{let p=t.parseEnvelope(bt(h,s));if(g=p.id,p.id!==h.requestId)throw new Error(`${t.name} request identity does not match its mailbox path.`);if(p.deadlineAtMs<e())throw new Error(`${t.name} request expired before processing.`);if(a={claim:h,envelope:p},t.onBusy?.(p.deadlineAtMs),!u.start({requestId:p.id,deadlineAtMs:p.deadlineAtMs,payload:p}))throw new Error(`${t.name} worker lane closed admission after claiming a request.`)}catch(p){let S=Ti(p);try{t.reject(h,g,S,e()),a?.claim===h&&m(a)}catch(k){l(Wi(k))}}return 1},status(){return{...o,mailbox:It(t.paths)}},async close(h){await u.close(h)}};function d(h){let g=a;if(!g||g.envelope.id!==h)throw new Error(`${t.name} parent lost the active mailbox claim.`);return g}function m(h){a===h&&(a=null,t.onBusy?.(void 0))}}function xr(t,e){if(t.createWorker)return t.createWorker(e);let r=t.workerUrl??new URL("./typescript-mailbox-worker.js",import.meta.url);return new ki(r,{workerData:e})}function Wi(t){return t instanceof Error?t:new Error(String(t))}function Ti(t){return t instanceof Error?t.message:String(t)}var Ci=1e3,Mi=250,Ai=6e4,qi=10,_i=50,Li=250;function Oi(t,e=1){if(t>0)return qi;let r=Math.max(0,Math.min(3,e-1));return Math.min(Li,_i*2**r)}async function Di(t,e){let r=e.processIndexRequests(),i=e.processSemanticRequests(),n=r+i,s=n>0?0:t+1;if(e.afterMailboxPoll({indexRequests:r,semanticRequests:i,processedRequests:n}),e.shouldStop())return{indexRequests:r,semanticRequests:i,processedRequests:n,consecutiveIdlePolls:s,stopped:!0};let a=Oi(n,s);return await e.wait(a),{indexRequests:r,semanticRequests:i,processedRequests:n,consecutiveIdlePolls:s,stopped:!1,delayMs:a}}function ji(t){return t==="fresh"?null:{kind:"watch-startup",detail:`index ${t} when watch service started`}}async function Ni(t,e,r={}){let i=nr(t,e),n=i.projectRoot,s=ie(n);s.watch={...s.watch,...r};let a=ne(s);if(!a.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let o=K(n,s),c=L(o.cacheDir),l=x(R.pid),u=cr(c.lockPath,n,{readProcessIdentity:f=>f===R.pid?l:x(f)});if(!u.acquired)return;let d=new fe(c.refreshRequestsPath,{retryDelayMs:Math.max(1e3,a.cooldownMs)});d.initializeAfterOwnershipAcquired();let m=Date.now(),h=b(),g=m,p=h,S={state:"idle"},k,V,W,U,ge=ee(o.dbPath),Se=!1,Xe=!1,Ke=0,Qe=Number.NEGATIVE_INFINITY,Ze=Number.NEGATIVE_INFINITY,et=Number.NEGATIVE_INFINITY,tt=Number.NEGATIVE_INFINITY,ve,ye,rt=0,Re=Mt(o.cacheDir),we=xt(o.cacheDir);qt(Re),Ct(we);let w=(f=!1,C=f?"durable":"visibility")=>{if(!Xe)return;let J=Date.now(),X=b();!f&&X-Qe<Ci||(Qe=X,or(c.statePath,{version:1,protocolVersion:Le,pid:R.pid,...l?{processIdentity:l}:{},projectRoot:n,...i.worktreeId?{worktreeId:i.worktreeId}:{},cliVersion:e,startedAt:new Date(m).toISOString(),heartbeatAt:new Date(J).toISOString(),lastActivityAt:new Date(g).toISOString(),...a.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date(g+a.idleTimeoutMs).toISOString()},watcher:S,...S.state==="idle"&&k?{indexGeneration:k}:{},...V?{lastRefresh:V}:{},...W?{lastError:W}:{},reindexActivity:ge,refreshRequests:d.status(),typescriptSemantic:{...be.status(),...ve===void 0?{}:{busyUntil:new Date(ve).toISOString()}},typescriptIndex:{...Ie.status(),...ye===void 0?{}:{busyUntil:new Date(ye).toISOString()}}},{durability:C}))},P=()=>{g=Date.now(),p=b()},it=f=>{P(),U??=f,W={at:new Date().toISOString(),message:f.message},w(!0,"visibility")},be=br({paths:Re,projectRoot:n,onBusy(f){ve=f===void 0?void 0:f+5e3,w(!0,"visibility")},onFatal:it}),Ie=wr({paths:we,projectRoot:n,dbPath:o.dbPath,onBusy(f){ye=f===void 0?void 0:f+5e3,w(!0,"visibility")},onFatal:it}),H=new ae({projectRoot:n,config:{...s,watch:a},languages:s.languages,onStatus(f){S=f,f.state!=="idle"&&(k=void 0),f.state!=="idle"&&P(),w(!0)},onReindexComplete(){P();let f=Oe(n,s,o);return V=f.lastRefresh,k=f.state==="fresh"?De(o.dbPath)??void 0:void 0,ge=ee(o.dbPath),d.completeActive(),W=void 0,w(!0),f.state==="fresh"},onReindexError(){d.failActive()},onRefreshSuppressed(f){let C=yt(o.dbPath,f);C.state==="failed"&&(W={at:new Date().toISOString(),message:`Suppressed-refresh telemetry was not recorded: ${C.reason}`},w(!0,"visibility")),ge=ee(o.dbPath)},onError(f){P(),k=void 0,W={at:new Date().toISOString(),message:f.message},w(!0)}}),z=()=>{Se=!0};R.once("SIGINT",z),R.once("SIGTERM",z);let D=!1,Y,j;try{H.start();let f=Oe(n,s,o);V=f.lastRefresh,k=f.state==="fresh"?De(o.dbPath)??void 0:void 0;let C=ji(f.state);for(C&&H.requestRefresh(C,{immediate:!0}),P(),Xe=!0,w(!0);!Se;){let J=await Di(rt,{processIndexRequests:()=>Ie.poll(),processSemanticRequests:()=>be.poll(),afterMailboxPoll:({processedRequests:X})=>{let M=b();if(M-tt>=Ai&&(tt=M,_e(we),_e(Re)),M-et>=6e4&&(et=M,vr(n,e)),M-Ze>=Mi){Ze=M;let T=ar(c.activityPath);T&&T.atMs>g&&(g=T.atMs,p=M),T?.refreshRequestedAtMs!==void 0&&T.refreshRequestedAtMs>Ke&&(Ke=T.refreshRequestedAtMs,d.observeLegacyRequest(T.refreshRequestedAtMs,T.refreshDetail??"stale index observed by a legacy command")),d.poll(S,Wr=>{P(),H.requestRefresh({kind:"watch-demand",detail:Wr},{immediate:!0})})}X>0&&(P(),w(!0,"visibility")),w()},shouldStop:()=>Se||U!==void 0||hr({watcher:S,lastActivityAtMs:p,nowMs:b(),idleTimeoutMs:a.idleTimeoutMs}),wait:Gi});if(rt=J.consecutiveIdlePolls,J.stopped)break}}catch(f){D=!0,Y=f}finally{R.off("SIGINT",z),R.off("SIGTERM",z),await Promise.all([be.close("TypeScript semantic service stopped before completing the request."),Ie.close("TypeScript index service stopped before completing the request.")]);let f=await H.stop();f.state==="stopped"?(kr(c.statePath,{force:!0}),kr(c.activityPath,{force:!0}),u.release()):(W={at:new Date().toISOString(),message:`Watch service shutdown is degraded: ${f.reasons.join("; ")}`},w(!0),j=new Error(W.message))}if(!D&&U&&(D=!0,Y=U),D&&j)throw new AggregateError([Y,j],"Watch service execution and shutdown both failed.");if(D)throw Y;if(j)throw j}function Gi(t){return new Promise(e=>setTimeout(e,t))}function Fi(t,e={report:r=>console.error(r),exit:r=>R.exit(r)}){return e.report(`watch-service: ${Pt(t instanceof Error?t.message:String(t))}`),e.exit(1)}var $i=R.argv[1]?Pi(Ei(R.argv[1])).href:null;if($i===import.meta.url){let t=R.argv[2],e=R.argv[3],r=Bi(R.argv[4]);if(!t||!e)console.error("watch-service: expected <project-root> <cli-version>"),R.exitCode=1;else try{await Ni(t,e,r)}catch(i){Fi(i)}}function Bi(t){if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}}export{Di as runWatchServiceLoopIteration,Ni as runWatchServiceServer,ji as startupRefreshTrigger,Fi as terminateWatchServiceProcess,Oi as watchServiceLoopDelayMs};
1
+ import{b as ze,c as Je,g as dt,j as ut,k as X,l as ht,m as Ie}from"./chunk-W7HN6V4E.js";import{a as K,b as St,c as vt}from"./chunk-3KXFB2FM.js";import{a as ke,b as kt,c as Pt,d as Tt,e as Pe,f as Ct,g as Te,h as Wt,i as Et,j as Mt,k as At,l as Lt,m as _t,n as jt}from"./chunk-U7DOYZDH.js";import{a as wt}from"./chunk-MXNGIEPU.js";import{a as Rt,c as Y}from"./chunk-UXNXOMXJ.js";import"./chunk-4SZJF4GK.js";import{d as B,e as Q,f as xe,g as bt}from"./chunk-WOPZX5GM.js";import"./chunk-DHEQMPLW.js";import{a as Z,b as It,c as xt}from"./chunk-DUDUIT5P.js";import{H as pt,c as nt,d as ye,g as q}from"./chunk-SIGVQT43.js";import{e as ct}from"./chunk-PRLU3I7G.js";import{a as ge,d as He}from"./chunk-DXYMTQZ4.js";import{a as lt}from"./chunk-DK6MB565.js";import"./chunk-FYCH2EYQ.js";import"./chunk-O4PZFAXA.js";import{a as E,c as Se,h as ft,j as ve,n as gt,o as mt,p as Re,q as we,r as be,s as yt}from"./chunk-NQXWWE6S.js";import"./chunk-H5EXS3HM.js";import"./chunk-HGFDYOVB.js";import{c as P,d as T,e as Xe}from"./chunk-Z2KGMIL4.js";import{G as Ke,H as F,I as Ye,K as Qe,L as O,N,R as Ze,S as et,V as tt,W as rt,X as me,Y as it,aa as st,ba as ot,h as R,l as fe,n as Ve,ra as at}from"./chunk-XIPGCT3D.js";import v from"process";import{rmSync as mr}from"fs";import{resolve as Mi}from"path";import{pathToFileURL as Ai}from"url";import{lstatSync as wr}from"fs";function Dt(t,e){let r=ee(t);if(r.kind!=="directory")throw new Error(`Watcher root is not a directory: ${t}`);if(!e)return{projectRoot:t,projectDirectory:r};let i=ee(e);if(i.kind!=="directory")throw new Error(`Git control path is not a directory: ${e}`);return{projectRoot:t,projectDirectory:r,gitControlDirectory:{path:e,identity:i}}}function Ft(t){try{if(!Gt(t.projectDirectory,ee(t.projectRoot)))return!1;let e=t.gitControlDirectory;return!e||Gt(e.identity,ee(e.path))}catch{return!1}}function ee(t){let e=wr(t,{bigint:!0}),r=e.isDirectory()?"directory":e.isFile()?"file":void 0;if(!r||e.isSymbolicLink())throw new Error(`Unsupported watcher identity path: ${t}`);return{device:e.dev,inode:e.ino,birthtimeNs:e.birthtimeNs,kind:r}}function Gt(t,e){return t.device===e.device&&t.inode===e.inode&&t.birthtimeNs===e.birthtimeNs&&t.kind===e.kind}import{existsSync as Me,lstatSync as Ir,statSync as Xt,watch as xr}from"fs";import{EventEmitter as kr}from"events";import{basename as Pr,dirname as Tr,isAbsolute as Ae,join as b,relative as Kt,resolve as Yt}from"path";import{watch as Cr}from"chokidar";import Wr from"ignore";var Qt=5e3,ie=class{projectRoot;config;watchConfig;outputDb;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onReindexError;onRefreshSuppressed;onError;reindexRunner;subscriptionFactory;budgetInspector;clock;activeOperation=null;stopPromise=null;stopInProgress=!1;status={state:"idle"};debounceTimer=null;cooldownTimer=null;budgetTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;pendingChanges=new Map;pendingChangesComplete=!0;pendingChangesIncompleteReason;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;lastGitState=null;preferFilesystemGitState=!0;watchGitLayout=null;localCacheWatchPath;gitignoreFilter;extraIgnore;stopped=!1;constructor(e){this.projectRoot=e.projectRoot,this.config=e.config,this.watchConfig=Q(e.config),this.outputDb=e.outputDb??b(Ke(this.projectRoot,e.config),"index.db"),this.preferFilesystemGitState=e.gitReader===void 0,this.localCacheWatchPath=Zr(this.projectRoot,Tr(this.outputDb)),this.languages=e.languages,this.pnpmWorkspaces=e.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=e.config.indexer?.typescript?.projectMode,this.typescriptProjects=e.config.indexer?.typescript?.projects,this.clojureConfigPath=e.config.indexer?.clojure?.configPath,this.indexerConcurrency=e.config.indexerConcurrency,this.onStatus=e.onStatus??(()=>{}),this.onReindexComplete=e.onReindexComplete??(()=>{}),this.onReindexError=e.onReindexError??(()=>{}),this.onRefreshSuppressed=e.onRefreshSuppressed??(()=>{}),this.onError=e.onError??(r=>console.error(r.message)),this.clock=e.clock??_r,Zt.set(this,ei(e.stopTimeoutMs??Qt,"watcher stop timeout")),this.reindexRunner=e.reindexRunner??Ur(),this.subscriptionFactory=e.subscriptionFactory??jr,this.budgetInspector=e.budgetInspector??ht,er.set(this,{projectRoot:e.projectRoot,config:e.config,gitReader:e.gitReader??Ze,languages:rr(e.languages??e.config.languages),typeScriptInputPaths:null,stagedIndexEntries:null}),this.gitignoreFilter=lt(e.projectRoot),this.extraIgnore=Wr(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore),Vt(this)}start(){if(this.stopInProgress)throw new Error("Cannot restart a watcher while its previous ownership is still draining.");this.stopped=!1,this.stopPromise=null,re(this).errors=[],this.sourcePollingFallbackStarted=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{this.startSourceWatcher()}catch(e){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(e)}`))}}stop(){if(this.stopPromise)return this.stopPromise;this.stopped=!0,this.stopInProgress=!0;let e=this.fsWatchers;this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearBudgetTimer(),this.clearGitPollTimer();let r=this.activeOperation;r&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"});let i=[...re(this).closures],n=Mr(this),s=this.clock.now()+n;return this.stopPromise=this.finishStop(e,i,r,s,n).catch(a=>{throw this.stopInProgress=!1,a}),this.stopPromise}requestRefresh(e,r={}){if(!this.stopped){if(this.markPendingChangesIncomplete(`unstructured-trigger:${e.kind}`),!r.immediate||this.reindexInFlight||this.status.state==="cooldown"||this.status.state==="budget-paused"){this.scheduleReindex(e);return}this.pendingTrigger=Ce(this.pendingTrigger,e),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}}startSourceWatcher(e=!1){let r=this.subscriptionFactory(this.projectRoot,{ignoreInitial:!0,ignored:(i,n)=>this.isIgnoredWatchPath(i,n?.isDirectory()??!1),usePolling:e,ignorePermissionErrors:!0,...e?{interval:5e3,binaryInterval:1e4}:{}});r.on("all",(i,n)=>{!this.stopped&&i!=="addDir"&&i!=="unlinkDir"&&this.handleFileChange(i,n)}),r.on("error",i=>this.handleSourceWatcherError(r,i,e)),this.fsWatchers.push(r)}handleSourceWatcherError(e,r,i){if(this.markPendingChangesIncomplete("source-watcher-error"),i||this.sourcePollingFallbackStarted||!Hr(r)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(r)}`));return}this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(n=>n!==e),Ar(re(this),e,n=>this.onError(n));try{this.startSourceWatcher(!0)}catch(n){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`))}}isIgnoredWatchPath(e,r){let i=this.relativeWatchPath(e);if(!i)return!1;if(Bt(i,this.localCacheWatchPath))return!0;let n=r?`${i}/`:i;return this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)}handleFileChange(e,r){let i=this.relativeWatchPath(r);if(!i||i===".."||i.startsWith("../")||Bt(i,this.localCacheWatchPath)||this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)||i.endsWith("index.db")||i.endsWith("index.scip")||i.endsWith("index.db.tmp")||Pr(i).startsWith(dt))return;i===".scipquery.json"&&zt(this,this.projectRoot);let n=Jt(this,e,i);n!==null&&(n||this.markPendingChangesIncomplete(`unsupported-source-event:${e}`),this.scheduleReindex({kind:"watch-source",detail:i},n?[{path:i,kind:n}]:void 0,n!==void 0))}relativeWatchPath(e){let r=Ae(e)?e:b(this.projectRoot,e);return Kt(this.projectRoot,r).replaceAll("\\","/")}scheduleReindex(e,r,i=!1){this.pendingTrigger=Ce(this.pendingTrigger,e),i||this.markPendingChangesIncomplete(`unstructured-trigger:${e.kind}`);for(let s of r??[])this.recordPendingChange(s);if(this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});let s=this.activeOperation;s&&L.get(this)!==s&&(L.set(this,s),s.cancel().then(a=>{a.state==="degraded"&&!this.stopped&&this.onError(new Error(a.reason))},a=>{this.stopped||this.onError(a instanceof Error?a:new Error(String(a)))}));return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}if(this.status.state==="budget-paused"){this.dirty=!0,this.setStatus({...this.status,dirty:!0});return}this.clearDebounceTimer();let n=this.wallNow()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:n}),this.debounceTimer=this.clock.setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let e=this.inspectBudget(),r=this.watchConfig.allowExpensiveRebuild&&e.state!=="paused";if(e.state==="paused"&&e.reason!=="rebuild-count"){this.dirty=!0;let c=Math.max(this.wallNow()+1,e.until);this.setStatus({state:"budget-paused",until:c,dirty:!0,reason:e.detail,rebuilt:e.rebuilt,estimatedWriteBytes:e.estimatedWriteBytes}),this.clearBudgetTimer(),this.budgetTimer=this.clock.setTimeout(()=>{this.budgetTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},Math.min(2147483647,Math.max(1,c-this.wallNow())));return}let i=this.clock.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&i<this.watchConfig.cooldownMs){let c=this.watchConfig.cooldownMs-i;this.dirty=!0;let l=this.wallNow()+c;this.setStatus({state:"cooldown",until:l,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},c);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let n=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let s=this.consumePendingChangeJournal(),a=this.wallNow();this.setStatus({state:"indexing",startedAt:a});let o=this.reindexRunner.start(this.reindexRequest(n,r,s));this.activeOperation=o,o.completion.then(c=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),te.set(this,0),this.stopped)return;if(L.get(this)===o){if(this.restorePendingChangeJournal(s),this.dirty){let u=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:u,dirty:!0}),this.clearCooldownTimer(),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"});return}Vt(this);let l=!1;try{l=this.onReindexComplete(c,n,{pendingChanges:this.dirty})===!0}catch(u){this.onError(u instanceof Error?u:new Error(String(u)))}if(this.dirty&&!this.stopped){if(l){let d=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.resetPendingChanges(),this.onRefreshSuppressed(d),this.setStatus({state:"idle"});return}let u=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:u,dirty:!0}),this.clearCooldownTimer(),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(c=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let l=c instanceof Error?c:new Error(String(c));this.restorePendingChangeJournal(s);let u=tr(l),d=0;if(u?(d=(te.get(this)??0)+1,te.set(this,d),this.dirty=!0,this.pendingTrigger=Ce(this.pendingTrigger,n)):te.set(this,0),!u&&L.get(this)!==o&&(this.onReindexError(l,n),this.onError(l)),this.dirty){let h=u?$r(this.watchConfig.cooldownMs,d):this.watchConfig.cooldownMs,p=this.wallNow()+h;this.setStatus({state:"cooldown",until:p,dirty:!0}),this.clearCooldownTimer(),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},h);return}this.setStatus({state:"idle"})}).finally(()=>{this.activeOperation===o&&(this.activeOperation=null),L.get(this)===o&&L.delete(this)})}async finishStop(e,r,i,n,s){let a=[],o=e.map(async h=>{try{await h.close()}catch(p){a.push(`watch subscription close failed: ${String(p)}`)}});o.push(...r),i&&o.push((async()=>{try{let h=await i.cancel();h.state==="degraded"&&a.push(h.reason)}catch(h){a.push(`reindex cancellation failed: ${h instanceof Error?h.message:String(h)}`)}})());let c=o.length,l=o.map(h=>h.finally(()=>{c-=1})),u=await Er(l,n,this.clock),d=re(this);return a.push(...d.errors),d.errors=[],u?this.stopInProgress=!1:(a.push(`watch shutdown exceeded the ${s}ms deadline with ${c} operation(s) still pending`),Promise.all(l).then(()=>{this.stopInProgress=!1})),a.length>0?(this.setStatus({state:"draining",startedAt:this.wallNow(),reason:a.join("; ")}),{state:"degraded",reasons:a}):(this.setStatus({state:"idle"}),{state:"stopped"})}wallNow(){return this.clock.wallNow?.()??this.clock.now()}inspectBudget(){try{return this.budgetInspector(this.outputDb,this.watchConfig.resourceBudget,new Date(this.wallNow()))}catch(e){return{state:"paused",reason:"activity-evidence",until:this.wallNow()+this.watchConfig.resourceBudget.windowMs,rebuilt:0,estimatedWriteBytes:0,detail:`reindex activity evidence could not be read: ${e instanceof Error?e.message:String(e)}`}}}reindexRequest(e,r=!0,i){return{projectRoot:this.projectRoot,config:this.config,languages:this.languages,pnpmWorkspaces:this.pnpmWorkspaces,typescriptProjectMode:this.typescriptProjectMode,typescriptProjects:this.typescriptProjects,clojureConfigPath:this.clojureConfigPath,indexerConcurrency:this.indexerConcurrency,trigger:e,changeJournal:i,allowExpensiveRebuild:r}}setStatus(e){this.status=e,this.onStatus(e)}recordPendingChange(e){if(this.pendingChanges.size>=1024&&!this.pendingChanges.has(e.path)){this.pendingChanges.clear(),this.markPendingChangesIncomplete("change-entry-limit");return}let r=this.pendingChanges.get(e.path),i=Jr(r,e.kind);i===null?this.pendingChanges.delete(e.path):this.pendingChanges.set(e.path,i)}markPendingChangesIncomplete(e){this.pendingChangesComplete=!1,this.pendingChangesIncompleteReason??=e}consumePendingChangeJournal(){let e=q(this.outputDb),r=[...this.pendingChanges.entries()].map(([a,o])=>({path:a,kind:o})).sort((a,o)=>a.path.localeCompare(o.path)),i=this.pendingChangesComplete,n=this.pendingChangesIncompleteReason;e||(i=!1,n??="accepted-generation-unavailable");let s={version:1,baseGeneration:e,complete:i,...n?{incompleteReason:n}:{},entries:r};return Ie(s)||(s={version:1,baseGeneration:e,complete:!1,incompleteReason:"change-journal-byte-limit",entries:[]}),this.resetPendingChanges(),s}restorePendingChangeJournal(e){let r=[...this.pendingChanges.entries()].map(([s,a])=>({path:s,kind:a})),i=this.pendingChangesComplete,n=this.pendingChangesIncompleteReason;this.resetPendingChanges(),e.complete||this.markPendingChangesIncomplete(e.incompleteReason??"failed-reindex");for(let s of e.entries)this.recordPendingChange(s);i||this.markPendingChangesIncomplete(n??"failed-reindex");for(let s of r)this.recordPendingChange(s)}resetPendingChanges(){this.pendingChanges.clear(),this.pendingChangesComplete=!0,this.pendingChangesIncompleteReason=void 0}clearDebounceTimer(){this.debounceTimer&&(this.clock.clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(this.clock.clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}clearBudgetTimer(){this.budgetTimer&&(this.clock.clearTimeout(this.budgetTimer),this.budgetTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(x(this).stagedIndexEntries=Ht(this.projectRoot,x(this).gitReader),this.gitPollTimer=this.clock.setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){if(this.reindexInFlight||this.stopped)return;let e=this.lastGitState,r=this.readGitState();if(!e||!r||this.stopped){this.lastGitState=r;return}this.lastGitState=r;let i=e.head!==r.head,n=e.indexPath!==r.indexPath||e.indexMtimeMs!==r.indexMtimeMs||e.indexSize!==r.indexSize;if(!i&&!n)return;let s=x(this),a=s.stagedIndexEntries,o=Ht(this.projectRoot,s.gitReader);s.stagedIndexEntries=o;let c=ni(this.projectRoot,s.gitReader,e,r,a,o,i,n),l=null;if(c!==null&&(c.includes(".scipquery.json")&&zt(this,this.projectRoot),l=c.filter(d=>Jt(this,"add",d)!==null),l.length===0))return;let u=l?.map(d=>({path:d,kind:Me(b(this.projectRoot,d))?"change":"delete"}));i&&n?this.scheduleReindex({kind:"watch-git-state",detail:We("HEAD and index changed",l)},u,u!==void 0):i?this.scheduleReindex({kind:"watch-git-head",detail:We("HEAD changed",l)},u,u!==void 0):n&&this.scheduleReindex({kind:"watch-git-index",detail:We(r.indexPath??"index changed",l)},u,u!==void 0)}readGitState(){if(this.preferFilesystemGitState){let e=this.readFilesystemGitState();if(e)return e}return this.readGitStateFromGit()}readFilesystemGitState(){let e=this.watchGitLayout??Xr(this.projectRoot);if(!e)return null;this.watchGitLayout=e;let r=Kr(e.gitDir);return r?Ut(r,e.indexPath):null}readGitStateFromGit(){let e=x(this).gitReader,r=me(this.projectRoot,["rev-parse","--git-path","index"],e);if(!r)return null;let i=it(this.projectRoot,r);return Ut(me(this.projectRoot,["rev-parse","--verify","HEAD"],e),i)}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};async function Er(t,e,r){if(t.length===0)return!0;let i=Promise.all(t).then(()=>!0),n=Math.max(0,e-r.now()),s=null,a=new Promise(c=>{s=r.setTimeout(()=>c(!1),n)}),o=await Promise.race([i,a]);return o&&s&&r.clearTimeout(s),o}var Nt=new WeakMap,Zt=new WeakMap,er=new WeakMap,L=new WeakMap,te=new WeakMap;function re(t){let e=Nt.get(t);if(e)return e;let r={closures:new Set,errors:[]};return Nt.set(t,r),r}function Mr(t){return Zt.get(t)??Qt}function x(t){let e=er.get(t);if(!e)throw new Error("Watcher input state was not initialized.");return e}function Ar(t,e,r){let i=Promise.resolve().then(()=>e.close()).catch(n=>{let s=`watch subscription close failed during polling fallback: ${String(n)}`;t.errors.push(s),r(new Error(s))});t.closures.add(i),i.then(()=>t.closures.delete(i))}function Lr(t,e=P){let{projectRoot:r,config:i,languages:n,pnpmWorkspaces:s,typescriptProjectMode:a,typescriptProjects:o,clojureConfigPath:c,indexerConcurrency:l,trigger:u}=t,d=B(r),h=Object.keys(d).length>0?d:i,p=O(r,h),m=h.indexer?.typescript,f=h.indexer?.clojure,y=e(process.pid);if(!y)throw new Error(`Could not establish watcher process identity for reindex worker ownership (pid ${process.pid}).`);return{workerPath:new URL("./reindex-worker.js",import.meta.url).pathname,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:r,SCIP_REINDEX_OUTPUT_SCIP:p.indexPath,SCIP_REINDEX_OUTPUT_DB:p.dbPath,SCIP_REINDEX_LANGUAGES:(h.languages??n)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(h.indexerConcurrency??l??""),SCIP_REINDEX_PNPM_WORKSPACES:m?.pnpmWorkspaces??s?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:m?.projectMode??a,projects:m?.projects??o??[],maxHeapMb:m?.maxHeapMb}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:f?.configPath??c??"",SCIP_REINDEX_TRIGGER_KIND:u.kind,SCIP_REINDEX_TRIGGER_DETAIL:u.detail??"",SCIP_REINDEX_CHANGE_JOURNAL:t.changeJournal?Ie(t.changeJournal)??"":"",SCIP_REINDEX_ALLOW_EXPENSIVE:t.allowExpensiveRebuild===!1?"0":"1",SCIP_REINDEX_PROCESS_GROUP_LEADER:"1",SCIP_REINDEX_PARENT_IDENTITY:JSON.stringify(y)}}}var _r={now:T,wallNow:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},jr=(t,e)=>Gr(process.platform,e.usePolling)?new Ee(t):Cr(t,e);function Gr(t,e){return t==="darwin"&&e!==!0}var $=class extends Error{constructor(e,r){super(e,r===void 0?void 0:{cause:r}),this.name="RecursiveSourceWatchError"}},Ee=class{events=new kr;watcher;constructor(e){this.watcher=xr(e,{recursive:!0},(r,i)=>{if(i===null){this.events.emit("error",new $("Recursive source watcher omitted the changed path."));return}let n=b(e,i.toString());this.events.emit("all",Dr(r,n),n)}),this.watcher.on("error",r=>{this.events.emit("error",new $(`Recursive source watcher failed: ${r.message}`,r))})}on=(e,r)=>(this.events.on(e,r),this);close(){this.watcher.close()}};function Dr(t,e){return t==="change"?"change":Me(e)?Xt(e).isDirectory()?"addDir":"add":"unlink"}var Fr=15*6e4,Or=1e3,Nr=64*1024;function qr(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function qt(t,e){let r=t instanceof Error?t.message:String(t),i=e.stderrTail.trim()||e.stdoutTail.trim();return i?`${r}
2
+ ${i}`:r}function Br(t,e){return Object.assign(new Error(t,e===void 0?void 0:{cause:e}),{retryable:!0})}function tr(t){return t instanceof Error&&"retryable"in t&&t.retryable===!0}function $r(t,e){let r=t*2**Math.min(5,Math.max(0,e-1));return Math.max(t,Math.min(3e4,r))}function Ur(t={}){let e=t.timeoutMs??Fr,r=t.terminationGraceMs??Or,i=t.maxOutputBytes??Nr,n=t.resolveLaunch??Lr;return{start(s){let a=n(s),o=new AbortController,c=qr(),l=!1,u=Je({command:process.execPath,args:[...process.execArgv,a.workerPath],label:"watch reindex worker",env:a.env,timeoutMs:e,terminationGraceMs:r,maxStdoutBytes:i,maxStderrBytes:i,outputLimitBehavior:"truncate-tail",signal:o.signal,detached:!0}).then(d=>{if(c={stdoutTail:d.stdout,stderrTail:d.stderr,stdoutTruncated:d.stdoutTruncated,stderrTruncated:d.stderrTruncated},d.status!==0){let h=qt(new Error(`Reindex worker exited with ${d.signal?`signal ${d.signal}`:`code ${d.status}`}`),c);throw d.status===75?Br(h):new Error(h)}return d.durationMs}).catch(d=>{throw tr(d)?d:(d instanceof ze&&(c={stdoutTail:d.stdout,stderrTail:d.stderr,stdoutTruncated:d.stdoutTruncated,stderrTruncated:d.stderrTruncated}),new Error(qt(d,c),{cause:d}))}).finally(()=>{l=!0});return{completion:u,async cancel(){l||o.abort();try{await u}catch{}return{state:"exited",diagnostics:c}},diagnostics:()=>c}}}}function Ce(t,e){return t?t.kind===e.kind?t.detail===e.detail?t:{kind:t.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${t.kind}, ${e.kind}`}:e}function zr(t){if(t==="add")return"add";if(t==="change")return"change";if(t==="unlink")return"delete"}function Jr(t,e){return t?t==="add"?e==="delete"?null:"add":t==="delete"&&e==="add"?"change":e:e}function Vr(t){return t instanceof Error&&"code"in t&&t.code==="EMFILE"||String(t).includes("EMFILE: too many open files")}function Hr(t){return t instanceof $||Vr(t)}var Le=/^[0-9a-f]{40,64}$/i;function Bt(t,e){return t===".git"||t.startsWith(".git/")||t==="node_modules"||t.startsWith("node_modules/")||t.endsWith("/node_modules")||t.includes("/node_modules/")?!0:e!==void 0&&(t===e||t.startsWith(`${e}/`))}function Xr(t){let e=b(t,".git");try{let r=Ir(e),i;if(r.isDirectory())i=e;else if(r.isFile()){let n=/^gitdir:\s*(.+)\s*$/m.exec(R(e,"Git directory marker"));if(!n?.[1])return null;let s=n[1].trim();i=Ae(s)?s:Yt(t,s)}else return null;return Me(i)?{gitDir:i,indexPath:b(i,"index")}:null}catch{return null}}function Kr(t){let e;try{e=R(b(t,"HEAD"),"Git HEAD").trim()}catch{return}if(Le.test(e))return e.toLowerCase();let r=/^ref:\s*(.+)$/.exec(e)?.[1]?.trim();if(!r)return;let i=Yr(t);return $t(t,r)??$t(i,r)??Qr(i,r)}function Yr(t){try{let e=R(b(t,"commondir"),"Git common-directory marker").trim();return e?Ae(e)?e:Yt(t,e):t}catch{return t}}function $t(t,e){try{let r=R(b(t,e),"Git reference").trim();return Le.test(r)?r.toLowerCase():void 0}catch{return}}function Qr(t,e){try{for(let r of R(b(t,"packed-refs"),"Git packed references").split(`
3
+ `)){if(r.startsWith("#")||r.startsWith("^"))continue;let i=r.indexOf(" ");if(i===-1)continue;let n=r.slice(0,i);if(r.slice(i+1).trim()===e&&Le.test(n))return n.toLowerCase()}}catch{return}}function Ut(t,e){let r={head:t,indexPath:e};try{let i=Xt(e);r.indexMtimeMs=i.mtimeMs,r.indexSize=i.size}catch{r.indexMtimeMs=void 0,r.indexSize=void 0}return r}function Zr(t,e){let r=Kt(t,e).replaceAll("\\","/");if(!(!r||r===".."||r.startsWith("../")))return r}function ei(t,e){if(!Number.isSafeInteger(t)||t<=0)throw new Error(`${e} must be a positive integer.`);return t}function rr(t){return t&&t.length>0?[...t]:ge}function zt(t,e){try{let r=x(t);r.config=B(e),r.languages=rr(r.config.languages)}catch{x(t).languages=ge}}function Jt(t,e,r){let i=x(t);if(fe(r,i.languages)==="other")return null;let s=zr(e);if(r===".scipquery.json"||st(r))return i.typeScriptInputPaths=null,s;if(!ti(r,i.languages))return s;let a=i.typeScriptInputPaths;if(!a)return s;let o=a.has(r);if(s!=="add")return o?s:null;if(o)return"change";let c=ir(t);return c?c.has(r)?"add":null:s}function Vt(t){let e=x(t);if(!e.languages.includes("typescript")){e.typeScriptInputPaths=null;return}let r=ri(e.projectRoot,e.config,e.languages);e.typeScriptInputPaths=r??ir(t)}function ir(t){let e=x(t);if(!e.languages.includes("typescript"))return e.typeScriptInputPaths=null,null;try{let r=e.config.indexer?.typescript,i=ot(e.projectRoot,r?.projectMode,r?.projects);return e.typeScriptInputPaths=i,i}catch{return e.typeScriptInputPaths=null,null}}function ti(t,e){if(!e.includes("typescript"))return!1;let r=fe(t,["typescript","javascript"]);return r==="source"||r==="ambient"}function ri(t,e,r){try{let i=He(R(O(t,e).metaPath,"reindex metadata"));if(i.kind!=="supported"&&i.kind!=="legacy")return null;let n=Ve(i.metadata.fingerprint);return!n||!ii(n,r,e)?null:new Set(n.files.map(s=>s.path))}catch{return null}}function ii(t,e,r){let i=at(e,{pnpmWorkspaces:r.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:r.indexer?.typescript?.projectMode,typescriptProjects:r.indexer?.typescript?.projects,clojureConfigPath:r.indexer?.clojure?.configPath});return t.version===i.version&&JSON.stringify([...t.languages].sort())===JSON.stringify(i.languages)&&t.pnpmWorkspaces===i.pnpmWorkspaces&&t.typescriptProjectMode===i.typescriptProjectMode&&JSON.stringify([...t.typescriptProjects].sort())===JSON.stringify(i.typescriptProjects)&&t.clojureConfigPath===i.clojureConfigPath}function ni(t,e,r,i,n,s,a,o){let c=new Set;if(a){if(!r.head||!i.head)return null;let l=e.runResult(t,["diff","--name-only","-z","--no-renames","--relative",r.head,i.head,"--"]);if(l.kind!=="success")return null;for(let u of si(l.output))c.add(u)}if(o){if(n===null||s===null)return null;for(let l of ai(n,s))c.add(l)}return[...c].sort()}function Ht(t,e){let r=e.runResult(t,["diff","--cached","--raw","-z","--no-renames","--relative","--"]);return r.kind==="success"?oi(r.output):null}function si(t){return t.split("\0").filter(e=>e.length>0)}function oi(t){let e=t.split("\0");if(e.at(-1)===""&&e.pop(),e.length%2!==0)return null;let r=new Map;for(let i=0;i<e.length;i+=2){let n=e[i],s=e[i+1];if(!n.startsWith(":")||!s)return null;r.set(s,n)}return r}function ai(t,e){return[...new Set([...t.keys(),...e.keys()])].filter(i=>t.get(i)!==e.get(i))}function We(t,e){return e===null?`${t}; changed paths unavailable`:e.length===0?t:e.length===1?e[0]:`${e.length} compiler inputs changed`}import{existsSync as ne,lstatSync as U,readdirSync as or,realpathSync as nr,rmSync as _,statSync as ci}from"fs";import{join as S,resolve as z,sep as ar}from"path";var li=3600*1e3,di=2*1024*1024*1024,se=300*1e3,ui="gc-state.json",hi="gc.lock";function pi(t){let e=t.leases.filter(o=>o.managed&&!o.live&&!o.busy),r=fi(t.leases,t.locks),i={};for(let o of t.generations)r.has(o.generationId)||(i[o.generationId]=o.unreferencedAt??t.nowMs);let n=t.generations.filter(o=>!r.has(o.generationId)).sort((o,c)=>i[o.generationId]-i[c.generationId]||o.generationId.localeCompare(c.generationId)),s=new Set;for(let o of n)t.nowMs-i[o.generationId]>=t.policy.generationTtlMs&&s.add(o.generationId);let a=t.generations.filter(o=>!s.has(o.generationId)).reduce((o,c)=>o+c.size,0);for(let o of n){if(a<=t.policy.budgetBytes)break;s.has(o.generationId)||(s.add(o.generationId),a-=o.size)}for(let o of s)delete i[o];return{deleteWorktrees:e,deleteGenerations:t.generations.filter(o=>s.has(o.generationId)),deleteLocks:t.locks.filter(o=>!o.live),deleteTemporaries:t.temporaries.filter(o=>!o.live),protectedGenerationIds:[...r].sort(),unreferencedSince:i}}function fi(t,e){let r=new Set(t.filter(i=>i.managed&&(i.live||i.busy)).flatMap(i=>[i.lease.baseGenerationId,i.lease.activeGenerationId]).filter(i=>i!==void 0));for(let i of e)i.live&&r.add(i.generationId);return r}function cr(t,e,r={}){if(!Qe())return{kind:"disabled"};let i=r.repositoryId===void 0?et(t)?.repositoryId:r.repositoryId;if(!i)return{kind:"unavailable"};let n=S(F(),"repositories",i),s=(r.now??Date.now)(),a=ne(n)?lr(t,n,i,e,s,r):{kind:"unavailable"};return gi(t,i,e,s,r),a}function lr(t,e,r,i,n,s){let a=S(e,"gc-state.json"),o=vi(a);if(!s.force&&o&&n-Date.parse(o.lastSweepAt)<se)return{kind:"throttled",sweptAt:o.lastSweepAt};let c=nt(e,{now:()=>n});if(!c)return{kind:"busy"};try{let l=mi(t,e,r,o?.unreferencedSince??{}),u=pi({nowMs:n,...l,policy:{generationTtlMs:s.policy?.generationTtlMs??li,budgetBytes:s.policy?.budgetBytes??di}}),d=0,h=0;for(let f of u.deleteWorktrees){if(!Ge(f.lease))continue;if(!ne(f.lease.localCacheDir)){_(f.leasePath,{force:!0}),h+=1;continue}if(!yi(f.lease))continue;let y=ye(S(f.lease.localCacheDir,"cache-lifecycle.lock"));if(y)try{if(_e(f.lease,!0))continue;try{Mt({projectRoot:f.lease.projectRoot,cacheDir:f.lease.localCacheDir,cliVersion:i})}catch{continue}if(_e(f.lease,!0))continue;_(f.lease.localCacheDir,{recursive:!0,force:!0}),_(f.leasePath,{force:!0}),h+=1}finally{y.release()}}for(let f of u.deleteLocks)_(f.path,{force:!0});for(let f of u.deleteTemporaries)_(f.path,{recursive:!0,force:!0});for(let f of u.deleteGenerations)_(f.path,{recursive:!0,force:!0}),d+=f.size;ct(S(e,"evidence.db"));let p={kind:"swept",sweptAt:new Date(n).toISOString(),deletedWorktrees:h,deletedGenerations:u.deleteGenerations.length,deletedBytes:d,protectedGenerations:u.protectedGenerationIds.length},m={version:1,lastSweepAt:p.sweptAt,unreferencedSince:u.unreferencedSince,lastResult:p};return Se(a,m,{spacing:2,trailingNewline:!0}),p}catch(l){return{kind:"failed",error:l instanceof Error?l.message:String(l)}}finally{c.release()}}function gi(t,e,r,i,n){let s=S(F(),"repositories");if(!ne(s))return;let a=S(s,ui),o=Ri(a);if(!n.force&&o!==void 0&&i-o<se)return;let c=ye(S(s,hi));if(c)try{for(let l of J(s)){if(l===e||!/^[a-f0-9]{24}$/.test(l))continue;let u=S(s,l),d;try{d=U(u)}catch{continue}if(!d.isDirectory()||d.isSymbolicLink())continue;let h=Si(u)??t;lr(h,u,l,r,i,n)}Se(a,{version:1,lastSweepAt:new Date(i).toISOString()},{spacing:2,trailingNewline:!0})}finally{c.release()}}function mi(t,e,r,i){let n=new Set(rt(t).map(l=>z(l.path))),s=[];for(let l of J(S(e,"worktrees"))){if(!l.endsWith(".json"))continue;let u=S(e,"worktrees",l),d=dr(u);if(!d)continue;let h=z(d.projectRoot);s.push({leasePath:u,lease:d,managed:d.repositoryId===r&&Ge(d),live:n.has(h)||ne(h),busy:_e(d)})}let a=[];for(let l of J(S(e,"locks"))){let u=/^([a-f0-9]{64})\.lock$/.exec(l);if(!u)continue;let d=S(e,"locks",l),h=je(d),p=h!==void 0&&E(h),m=u[1];a.push({generationId:m,path:d,live:p})}let o=[],c=[];for(let l of J(S(e,"generations"))){let u=/^\.tmp-(\d+)-/.exec(l);if(u){let p=S(e,"generations",l),m=Number(u[1]);try{c.push({path:p,size:sr(p),live:Number.isSafeInteger(m)&&E(m)})}catch{}continue}if(!/^[a-f0-9]{64}$/.test(l))continue;let d=S(e,"generations",l),h;try{h=U(d)}catch{continue}!h.isDirectory()||h.isSymbolicLink()||o.push({generationId:l,path:d,size:sr(d),...i[l]===void 0?{}:{unreferencedAt:i[l]}})}return{leases:s,generations:o,locks:a,temporaries:c}}function Ge(t){if(t.ownershipChecksum!==pt(t)||N(t.localCacheDir)!==N(Ye(t.projectRoot)))return!1;let e=N(S(F(),"projects"));return N(t.localCacheDir).startsWith(`${e}${ar}`)}function yi(t){if(!Ge(t))return!1;let e=z(F()),r=z(S(e,"projects")),i=z(t.localCacheDir);try{let n=U(e),s=U(r),a=U(i);if(!n.isDirectory()||n.isSymbolicLink()||!s.isDirectory()||s.isSymbolicLink()||!a.isDirectory()||a.isSymbolicLink())return!1;let o=nr(r);return nr(i).startsWith(`${o}${ar}`)}catch{return!1}}function Si(t){for(let e of J(S(t,"worktrees"))){if(!e.endsWith(".json"))continue;let r=dr(S(t,"worktrees",e));if(r)return r.projectRoot}}function _e(t,e=!1){for(let i of e?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let n=je(S(t.localCacheDir,i));if(n!==void 0&&E(n))return!0}let r=je(Y(t.localCacheDir).lockPath);return r!==void 0&&E(r)}function dr(t){try{let e=JSON.parse(R(t,"worktree cache lease"));return e.version!==1||typeof e.repositoryId!="string"||typeof e.worktreeId!="string"||typeof e.projectRoot!="string"||e.treeOid!==void 0&&typeof e.treeOid!="string"||typeof e.localCacheDir!="string"||e.baseGenerationId!==void 0&&typeof e.baseGenerationId!="string"||e.activeGenerationId!==void 0&&typeof e.activeGenerationId!="string"||typeof e.ownershipChecksum!="string"||!/^[a-f0-9]{64}$/.test(e.ownershipChecksum)||typeof e.lastAction!="string"||e.lastReason!==void 0&&typeof e.lastReason!="string"||typeof e.lastSeenAt!="string"?null:e}catch{return null}}function je(t){try{let e=JSON.parse(R(t,"watch lock record"));return typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0?e.pid:void 0}catch{return}}function vi(t){try{let e=JSON.parse(R(t,"repository cache GC state"));return e.version!==1||typeof e.lastSweepAt!="string"||!Number.isFinite(Date.parse(e.lastSweepAt))||!e.unreferencedSince||typeof e.unreferencedSince!="object"||!e.lastResult?null:e}catch{return null}}function Ri(t){try{let e=JSON.parse(R(t,"global repository cache GC state"));if(e.version!==1||typeof e.lastSweepAt!="string")return;let r=Date.parse(e.lastSweepAt);return Number.isFinite(r)?r:void 0}catch{return}}function J(t){try{return or(t)}catch{return[]}}function sr(t){let e=0,r=[t];for(;r.length>0;){let i=r.pop();for(let n of or(i,{withFileTypes:!0})){let s=S(i,n.name);n.isDirectory()?r.push(s):n.isFile()&&(e+=ci(s).size)}}return e}var oe=class{root;now;randomId;retryDelayMs;active;retryNotBeforeMs=0;currentStatus;constructor(e,r={}){this.root=e,this.now=r.now??Date.now,this.randomId=r.randomId,this.retryDelayMs=Math.max(1,Math.floor(r.retryDelayMs??1e3)),this.currentStatus=Te(e)}initializeAfterOwnershipAcquired(){let e=Ct(this.root),r=Wt(this.root,{now:()=>new Date(this.now())});return this.refreshStatus(),{recoveredClaims:e,prunedHistory:r}}observeLegacyRequest(e,r){kt(this.root,r??"stale index observed by a legacy command",{idempotencyKey:`legacy-activity:${e}`,now:()=>new Date(e)}),this.refreshStatus()}poll(e,r){if(this.active||e.state!=="idle"||this.now()<this.retryNotBeforeMs)return!1;let i=Pt(this.root,{now:()=>new Date(this.now()),...this.randomId?{randomId:this.randomId}:{}});if(this.refreshStatus(),i.requests.length===0)return!1;this.active=i;try{return r(wi(i)),!0}catch(n){throw Pe(this.root,i),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),n}}completeActive(){return this.active?(Tt(this.root,this.active,()=>new Date(this.now())),this.active=void 0,this.retryNotBeforeMs=0,this.refreshStatus(),!0):!1}failActive(){return this.active?(Pe(this.root,this.active),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),!0):!1}status(){return{...this.currentStatus}}refreshStatus(){this.currentStatus=Te(this.root)}};function wi(t){if(t.requests.length===1)return t.requests[0].detail;let r=[...new Set(t.requests.map(i=>i.detail))].slice(0,3).join("; ");return`${t.requests.length} coalesced refresh requests${r?`: ${r}`:""}`.slice(0,2048)}import{randomUUID as Ii}from"crypto";import{Worker as xi}from"worker_threads";var ae=class{constructor(e){this.options=e;if(this.now=e.now??Date.now,this.setTimer=e.setTimer??setTimeout,this.clearTimer=e.clearTimer??clearTimeout,e.maxWorkerFailureRetries!==void 0&&(!Number.isInteger(e.maxWorkerFailureRetries)||e.maxWorkerFailureRetries<0))throw new Error("Worker maxWorkerFailureRetries must be a non-negative integer.")}options;now;setTimer;clearTimer;worker=null;active=null;activeFailure=null;terminating=null;closed=!1;workerGeneration=0;idleTimer=null;canAccept(){return!this.closed&&this.active===null&&this.terminating===null}hasWorker(){return this.worker!==null}start(e){if(!this.canAccept())return!1;if(this.clearIdleTimer(),e.deadlineAtMs<this.now()){try{this.options.onReject(e,`${this.options.name} request expired before processing.`)}catch(n){this.closed=!0,this.options.onFatal(De(n))}return!0}let r=this.ensureWorker(),i=this.deadlineTimer(e);this.active={request:e,timer:i,workerFailureRetries:0,workerFailureReasons:[]};try{r.postMessage({kind:"request",...e})}catch(n){this.failActiveAfterTermination(Fe(n),!0)}return!0}async close(e=`${this.options.name} service is shutting down.`){if(this.closed=!0,this.clearIdleTimer(),this.active){await this.failActiveAfterTermination(e);return}await this.terminateWorker()}ensureWorker(){if(this.worker)return this.worker;let e=this.options.createWorker(),r=++this.workerGeneration;return e.on("message",i=>this.handleMessage(r,i)),e.on("error",i=>{r===this.workerGeneration&&this.failActiveAfterTermination(`${this.options.name} worker failed: ${i.message}`,!0)}),e.on("exit",i=>{r!==this.workerGeneration||this.terminating||(this.worker=null,this.active&&this.failActiveAfterTermination(`${this.options.name} worker exited unexpectedly with code ${i}.`,!0))}),this.worker=e,e}handleMessage(e,r){if(e!==this.workerGeneration||this.closed||!this.active)return;let i=bi(r);if(!i){this.failActiveAfterTermination(`${this.options.name} worker returned an invalid response.`);return}if(i.requestId!==this.active.request.requestId){this.failActiveAfterTermination(`${this.options.name} worker returned a mismatched request identity.`);return}if(this.now()>this.active.request.deadlineAtMs){this.failActiveAfterTermination(`${this.options.name} request expired while it was processing.`);return}let n=this.active,s;try{this.options.onStatus(i.status),i.ok?this.options.onComplete(n.request,i.result,i.status):this.options.onReject(n.request,i.error,i.status),s=this.options.retireAfterResponse?.(i.status)??!1}catch(a){this.closed=!0,this.clearTimer(n.timer),this.options.onFatal(De(a));return}this.releaseActive(n),s?this.terminateWorker():this.scheduleIdleTermination()}async failActiveAfterTermination(e,r=!1){if(this.activeFailure){await this.activeFailure;return}let i=this.active;if(!i){await this.terminateWorker();return}this.clearTimer(i.timer),r&&i.workerFailureReasons.push(e);let n=(async()=>{if(!await this.terminateWorker())return;let a=this.options.maxWorkerFailureRetries??0;if(r&&!this.closed&&i.workerFailureRetries<a&&this.now()<=i.request.deadlineAtMs){i.workerFailureRetries+=1;try{let c=this.ensureWorker();i.timer=this.deadlineTimer(i.request),c.postMessage({kind:"request",...i.request});return}catch(c){let l=`Cold Worker retry failed: ${Fe(c)}`;if(i.workerFailureReasons.push(l),e=`${e} ${l}`,!await this.terminateWorker())return}}let o=i.workerFailureReasons.length===0?e:[...new Set([...i.workerFailureReasons,e])].join(" Cold Worker retry: ");try{this.options.onReject(i.request,o)}catch(c){this.closed=!0,this.options.onFatal(De(c));return}this.releaseActive(i)})();this.activeFailure=n;try{await n}finally{this.activeFailure===n&&(this.activeFailure=null)}}deadlineTimer(e){let r=Math.max(1,Math.min(2147483647,e.deadlineAtMs-this.now()));return this.setTimer(()=>{this.failActiveAfterTermination(`${this.options.name} request exceeded its deadline.`)},r)}releaseActive(e){this.active===e&&(this.active=null,this.clearTimer(e.timer))}scheduleIdleTermination(){let e=this.options.idleTtlMs;!e||e<=0||this.closed||this.active||!this.worker||(this.clearIdleTimer(),this.idleTimer=this.setTimer(()=>{this.idleTimer=null,!(this.closed||this.active||!this.worker)&&this.terminateWorker()},e))}clearIdleTimer(){this.idleTimer&&(this.clearTimer(this.idleTimer),this.idleTimer=null)}async terminateWorker(){if(this.clearIdleTimer(),this.terminating)return this.terminating;let e=this.worker;if(!e)return!0;this.worker=null;let r=++this.workerGeneration;return this.terminating=(async()=>{try{return await e.terminate(),!0}catch(i){return this.closed=!0,this.options.onFatal(new Error(`${this.options.name} worker termination failed: ${Fe(i)}`,{cause:i})),!1}finally{r===this.workerGeneration&&(this.terminating=null)}})(),this.terminating}};function bi(t){if(!t||typeof t!="object")return null;let e=t;if(e.kind!=="response"||typeof e.requestId!="string"||!("status"in e))return null;if(e.ok===!0){if(!("result"in e)||"error"in e)return null}else if(e.ok===!1){if("result"in e||typeof e.error!="string")return null}else return null;return e}function De(t){return t instanceof Error?t:new Error(String(t))}function Fe(t){return t instanceof Error?t.message:String(t)}var ki=6e4,Pi=10*6e4;function ur(t){let e=t.maxActiveSessions??8,r=t.workerSoftMemoryMb??Ci(t.workerHeapMb),i=()=>({protocolVersion:K,state:"idle",requests:0,sessionsCreated:0,sessionsReplaced:0,sessionsEvicted:0,activeSessions:0,maxActiveSessions:e,softMemoryLimitBytes:r*1024*1024,retireRequested:!1,initializations:0,programUpdates:0,documentsEmitted:0,documentsRemoved:0});return pr({name:"TypeScript index",paths:t.paths,now:t.now,limits:t.limits,initialStatus:i,parseEnvelope:vt,createWorker:()=>gr(t,{kind:"index",projectRoot:t.projectRoot,dbPath:t.dbPath,maxActiveSessions:e,softMemoryLimitMb:r}),complete(n,s,a,o){Re(t.paths,n,{ok:!0,protocolVersion:K,id:s.id,baseGeneration:s.baseGeneration,response:a},{nowMs:o,limits:t.limits})},reject(n,s,a,o){we(t.paths,n,{ok:!1,protocolVersion:K,id:s,error:a},a,{nowMs:o,limits:t.limits})},idleTtlMs:t.workerIdleMs??Pi,maxWorkerFailureRetries:1,retireAfterResponse:n=>n.retireRequested===!0,statusWhenWorkerAbsent:n=>({...n,state:"idle",activeSessions:0,heapUsedBytes:0,retireRequested:!1}),onBusy:t.onBusy,onFatal:t.onFatal})}function hr(t){let e=()=>({protocolVersion:Z,state:"idle",requests:0,sessionsCreated:0,sessionsReused:0,sessionsRefreshed:0,sessionsReplaced:0,projectsCreated:0});return pr({name:"TypeScript semantic",paths:t.paths,now:t.now,limits:t.limits,initialStatus:e,parseEnvelope:xt,createWorker:()=>gr(t,{kind:"semantic",projectRoot:t.projectRoot}),complete(r,i,n,s){Re(t.paths,r,{ok:!0,protocolVersion:Z,id:i.id,generation:i.generation,response:n},{nowMs:s,limits:t.limits})},reject(r,i,n,s){we(t.paths,r,{ok:!1,protocolVersion:Z,id:i,error:n},n,{nowMs:s,limits:t.limits})},idleTtlMs:ki,onBusy:t.onBusy,onFatal:t.onFatal})}function pr(t){let e=t.now??Date.now,r=P(process.pid),i={pid:process.pid,...r?{processIdentity:r}:{}},n=`${t.name.toLowerCase().replaceAll(" ","-")}-${process.pid}-${Ii()}`,s={...t.limits,maxBatch:1},a=null,o=t.initialStatus(),c=!1,l=p=>{c=!0,t.onFatal(p)},u=new ae({name:t.name,createWorker:t.createWorker,now:e,idleTtlMs:t.idleTtlMs,maxWorkerFailureRetries:t.maxWorkerFailureRetries,retireAfterResponse:t.retireAfterResponse,onComplete(p,m,f){let y=d(p.requestId);o=f;let k=e();try{t.complete(y.claim,y.envelope,m,k)}catch(I){if(!(I instanceof ft)||I.code!=="item-too-large")throw I;t.reject(y.claim,y.envelope.id,I.message,k)}h(y)},onReject(p,m,f){let y=d(p.requestId);f!==void 0&&(o=f),t.reject(y.claim,y.envelope.id,m,e()),h(y)},onStatus(p){o=p},onFatal:l});return{poll(){if(c||!u.canAccept())return 0;let p=gt(t.paths,{ownerId:n,nowMs:e(),limits:s,owner:i,liveness:{isProcessAlive:E,readProcessIdentity:P}})[0];if(!p)return 0;let m=p.requestId;try{let f=t.parseEnvelope(mt(p,s));if(m=f.id,f.id!==p.requestId)throw new Error(`${t.name} request identity does not match its mailbox path.`);if(f.deadlineAtMs<e())throw new Error(`${t.name} request expired before processing.`);if(a={claim:p,envelope:f},t.onBusy?.(f.deadlineAtMs),!u.start({requestId:f.id,deadlineAtMs:f.deadlineAtMs,payload:f}))throw new Error(`${t.name} worker lane closed admission after claiming a request.`)}catch(f){let y=Ei(f);try{t.reject(p,m,y,e()),a?.claim===p&&h(a)}catch(k){l(Wi(k))}}return 1},status(){return{...u.hasWorker()||!t.statusWhenWorkerAbsent?o:t.statusWhenWorkerAbsent(o),mailbox:yt(t.paths)}},async close(p){await u.close(p)}};function d(p){let m=a;if(!m||m.envelope.id!==p)throw new Error(`${t.name} parent lost the active mailbox claim.`);return m}function h(p){a===p&&(a=null,t.onBusy?.(void 0))}}var Ti=6144;function fr(){let t=Number.parseInt(process.env.SCIP_TS_WORKER_HEAP_MB??"",10);return Number.isFinite(t)&&t>0?t:Ti}function Ci(t){return Math.max(1,Math.floor((t??fr())*.9))}function gr(t,e){if(t.createWorker)return t.createWorker(e);let r=t.workerUrl??new URL("./typescript-mailbox-worker.js",import.meta.url);return new xi(r,{workerData:e,resourceLimits:{maxOldGenerationSizeMb:t.workerHeapMb??fr()}})}function Wi(t){return t instanceof Error?t:new Error(String(t))}function Ei(t){return t instanceof Error?t.message:String(t)}var yr=2e3,Li=5e3,_i=5e3,ji=6e4,Gi=10,Di=50,Fi=1e4;function Oi(t,e=1){return Xe(t,e,Gi,Di,Fi,8)}function Ni(t,e){let r;return{begin(){return r||(e.requestStop(),e.closeWake(),r=t.stop(),r.catch(()=>{})),r}}}async function qi(t,e){let r=e.processIndexRequests(),i=e.processSemanticRequests(),n=r+i,s=n>0?0:t+1;if(e.afterMailboxPoll({indexRequests:r,semanticRequests:i,processedRequests:n}),e.shouldStop())return{indexRequests:r,semanticRequests:i,processedRequests:n,consecutiveIdlePolls:s,stopped:!0};let a=Oi(n,s);return await e.wait(a),{indexRequests:r,semanticRequests:i,processedRequests:n,consecutiveIdlePolls:s,stopped:!1,delayMs:a}}function Bi(t){return t==="fresh"?null:{kind:"watch-startup",detail:`index ${t} when watch service started`}}function $i(t){At(t.statePath,{version:1,protocolVersion:Rt,pid:v.pid,...t.processIdentity?{processIdentity:t.processIdentity}:{},projectRoot:t.projectRoot,...t.worktreeId?{worktreeId:t.worktreeId}:{},cliVersion:t.cliVersion,startedAt:new Date(t.startedAtMs).toISOString(),heartbeatAt:new Date(t.nowMs).toISOString(),lastActivityAt:new Date(t.lastActivityAtMs).toISOString(),...t.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date(t.lastActivityAtMs+t.idleTimeoutMs).toISOString()},watcher:t.watcherStatus,...t.watcherStatus.state==="idle"&&t.indexGeneration?{indexGeneration:t.indexGeneration}:{},...t.lastRefresh?{lastRefresh:t.lastRefresh}:{},...t.lastError?{lastError:t.lastError}:{},reindexActivity:t.reindexActivity,refreshRequests:t.refreshCoordinator.status(),typescriptSemantic:{...t.semanticLane.status(),...t.semanticBusyUntilMs===void 0?{}:{busyUntil:new Date(t.semanticBusyUntilMs).toISOString()}},typescriptIndex:{...t.indexLane.status(),...t.indexBusyUntilMs===void 0?{}:{busyUntil:new Date(t.indexBusyUntilMs).toISOString()}}},{durability:t.durability})}function Ui(t){let e=0,r=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY,n=Number.NEGATIVE_INFINITY,s=Number.NEGATIVE_INFINITY;return({processedRequests:a})=>{let o=T();if(o-i>=_i&&(i=o,!Ft(t.worktreeLiveness))){t.requestStop();return}if(o-s>=ji&&(s=o,be(t.indexMailboxPaths),be(t.semanticMailboxPaths)),o-n>=se&&(n=o,cr(t.projectRoot,t.cliVersion)),o-r>=Li){r=o;let c=Lt(t.activityPath);c&&t.updateObservedActivity(c.atMs,o),c?.refreshRequestedAtMs!==void 0&&c.refreshRequestedAtMs>e&&(e=c.refreshRequestedAtMs,t.refreshCoordinator.observeLegacyRequest(c.refreshRequestedAtMs,c.refreshDetail??"stale index observed by a legacy command"))}t.refreshCoordinator.poll(t.watcherStatus(),c=>{t.recordActivity(),t.requestRefresh(c)}),a>0&&(t.recordActivity(),t.persistState(!0,"visibility")),t.persistState()}}async function zi(t){let e,r=0,i=!1,n,s;v.once("SIGINT",t.stopSignal),v.once("SIGTERM",t.stopSignal);try{t.watcher.start();let o=t.initializeFreshness();for(t.recordActivity(),t.markReady(),t.persistState(!0),e=setInterval(()=>t.persistState(),yr),e.unref?.(),o&&t.requestRefresh(o);!t.stopRequested();){let c=await qi(r,{processIndexRequests:t.processIndexRequests,processSemanticRequests:t.processSemanticRequests,afterMailboxPoll:t.afterMailboxPoll,shouldStop:t.shouldStop,wait:t.wait});if(r=c.consecutiveIdlePolls,c.stopped)break}}catch(o){i=!0,n=o}finally{v.off("SIGINT",t.stopSignal),v.off("SIGTERM",t.stopSignal),e!==void 0&&clearInterval(e);let o=t.shutdown.begin();await t.closeLanes();let c=await o;c.state==="stopped"?t.finalizeStopped():s=t.finalizeDegraded(c.reasons)}let a=t.mailboxFatalError();if(!i&&a&&(i=!0,n=a),i&&s)throw new AggregateError([n,s],"Watch service execution and shutdown both failed.");if(i)throw n;if(s)throw s}function Ji(t){let e=hr({paths:t.semanticPaths,projectRoot:t.projectRoot,onBusy:t.onSemanticBusy,onFatal:t.onFatal}),r=t.config.indexer?.typescript,i=ur({paths:t.indexPaths,projectRoot:t.projectRoot,dbPath:t.dbPath,...r?.maxWarmSessions===void 0?{}:{maxActiveSessions:r.maxWarmSessions},...r?.workerIdleMs===void 0?{}:{workerIdleMs:r.workerIdleMs},...r?.workerSoftMemoryMb===void 0?{}:{workerSoftMemoryMb:r.workerSoftMemoryMb},...r?.workerHeapMb===void 0?{}:{workerHeapMb:r.workerHeapMb},onBusy:t.onIndexBusy,onFatal:t.onFatal});return{semanticLane:e,indexLane:i}}async function Vi(t,e,r={}){let i=Et(t,e),n=i.projectRoot,s=i.worktreeKind==="git"?Hi(n,i.worktreeId):void 0,a=Dt(n,s),o=B(n);o.watch={...o.watch,...r};let c=Q(o);if(!c.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let l=O(n,o),u=Y(l.cacheDir),d=P(v.pid),h=_t(u.lockPath,n,{readProcessIdentity:g=>g===v.pid?d:P(g)});if(!h.acquired)return;let p=new oe(u.refreshRequestsPath,{retryDelayMs:Math.max(1e3,c.cooldownMs)});p.initializeAfterOwnershipAcquired();let m=Date.now(),f=T(),y=m,k=f,I={state:"idle"},j,ce,C,le,de=X(l.dbPath),V=!1,Oe=!1,Ne=Number.NEGATIVE_INFINITY,qe,Be,G=It(l.cacheDir),D=St(l.cacheDir);ve(G),ve(D);let $e=ke([D.pendingDir,D.legacyRequestDir,G.pendingDir,G.legacyRequestDir,u.refreshRequestsPath]),w=(g=!1,W=g?"durable":"visibility")=>{if(!Oe)return;let pe=Date.now(),A=T();!g&&A-Ne<yr||(Ne=A,$i({statePath:u.statePath,durability:W,processIdentity:d,projectRoot:n,worktreeId:i.worktreeId,cliVersion:e,startedAtMs:m,nowMs:pe,lastActivityAtMs:y,idleTimeoutMs:c.idleTimeoutMs,watcherStatus:I,indexGeneration:j,lastRefresh:ce,lastError:C,reindexActivity:de,refreshCoordinator:p,semanticLane:ue,indexLane:he,semanticBusyUntilMs:qe,indexBusyUntilMs:Be}))},M=()=>{y=Date.now(),k=T()},Sr=g=>{M(),le??=g,C={at:new Date().toISOString(),message:g.message},w(!0,"visibility")},{semanticLane:ue,indexLane:he}=Ji({semanticPaths:G,indexPaths:D,projectRoot:n,dbPath:l.dbPath,config:o,onSemanticBusy(g){qe=g===void 0?void 0:g+5e3,w(!0,"visibility")},onIndexBusy(g){Be=g===void 0?void 0:g+5e3,w(!0,"visibility")},onFatal:Sr}),H=new ie({projectRoot:n,config:{...o,watch:c},outputDb:l.dbPath,languages:o.languages,onStatus(g){I=g,g.state!=="idle"&&(j=void 0),g.state!=="idle"&&M(),w(!0)},onReindexComplete(g,W,pe){M();let A=pe?.pendingChanges!==!1?xe(n,o,l):bt(l);return ce=A.lastRefresh,j=A.state==="fresh"?q(l.dbPath)??void 0:void 0,de=X(l.dbPath),p.completeActive(),C=void 0,w(!0),A.state==="fresh"},onReindexError(){p.failActive()},onRefreshSuppressed(g){let W=ut(l.dbPath,g);W.state==="failed"&&(C={at:new Date().toISOString(),message:`Suppressed-refresh telemetry was not recorded: ${W.reason}`},w(!0,"visibility")),de=X(l.dbPath)},onError(g){M(),j=void 0,C={at:new Date().toISOString(),message:g.message},w(!0)}}),Ue=Ni(H,{requestStop(){V=!0},closeWake(){$e.close()}}),vr=()=>{Ue.begin()},Rr=Ui({worktreeLiveness:a,indexMailboxPaths:D,semanticMailboxPaths:G,projectRoot:n,cliVersion:e,activityPath:u.activityPath,refreshCoordinator:p,watcherStatus:()=>I,requestRefresh:g=>H.requestRefresh({kind:"watch-demand",detail:g},{immediate:!0}),requestStop:()=>{V=!0},recordActivity:M,updateObservedActivity(g,W){g<=y||(y=g,k=W)},persistState:w});await zi({watcher:H,shutdown:Ue,stopSignal:vr,initializeFreshness(){let g=xe(n,o,l);return ce=g.lastRefresh,j=g.state==="fresh"?q(l.dbPath)??void 0:void 0,Bi(g.state)},markReady:()=>{Oe=!0},recordActivity:M,persistState:w,requestRefresh:g=>H.requestRefresh(g,{immediate:!0}),stopRequested:()=>V,processIndexRequests:()=>he.poll(),processSemanticRequests:()=>ue.poll(),afterMailboxPoll:Rr,shouldStop:()=>V||le!==void 0||jt({watcher:I,lastActivityAtMs:k,nowMs:T(),idleTimeoutMs:c.idleTimeoutMs}),wait:g=>$e.wait(g),closeLanes:()=>Promise.all([ue.close("TypeScript semantic service stopped before completing the request."),he.close("TypeScript index service stopped before completing the request.")]).then(()=>{}),mailboxFatalError:()=>le,finalizeStopped(){mr(u.statePath,{force:!0}),mr(u.activityPath,{force:!0}),h.release()},finalizeDegraded(g){return C={at:new Date().toISOString(),message:`Watch service shutdown is degraded: ${g.join("; ")}`},w(!0),new Error(C.message)}})}function Hi(t,e){let r=tt(t);if(r.kind!=="worktree"||r.identity.worktreeId!==e)throw new Error(`Git worktree identity changed while starting the watch service for ${t}.`);return r.identity.gitDir}function Xi(t,e={report:r=>console.error(r),exit:r=>v.exit(r)}){return e.report(`watch-service: ${wt(t instanceof Error?t.message:String(t))}`),e.exit(1)}var Ki=v.argv[1]?Ai(Mi(v.argv[1])).href:null;if(Ki===import.meta.url){let t=v.argv[2],e=v.argv[3],r=Yi(v.argv[4]);if(!t||!e)console.error("watch-service: expected <project-root> <cli-version>"),v.exitCode=1;else try{await Vi(t,e,r)}catch(i){Xi(i)}}function Yi(t){if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}}export{ke as createPathChangeWake,Ni as createWatchServiceShutdown,qi as runWatchServiceLoopIteration,Vi as runWatchServiceServer,Bi as startupRefreshTrigger,Xi as terminateWatchServiceProcess,Oi as watchServiceLoopDelayMs};
3
4
  //# sourceMappingURL=watch-server.js.map