scip-query 0.22.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (470) hide show
  1. package/CHANGELOG.md +500 -0
  2. package/README.md +13 -0
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/by-kind-H3P6BR5G.js +2 -0
  5. package/dist/call-graph-VTG2CUOQ.js +2 -0
  6. package/dist/call-graph-evidence-BociKRpF.d.ts +19 -0
  7. package/dist/chunk-2BMSSRBH.js +2 -0
  8. package/dist/{chunk-TAYD3AE7.js → chunk-2GJSD5GY.js} +2 -2
  9. package/dist/{chunk-TUQIPUDS.js → chunk-2M2LSIMY.js} +3 -3
  10. package/dist/{chunk-GIQ6CSL4.js → chunk-2N6WBNDC.js} +2 -2
  11. package/dist/{chunk-JHH5SCZ3.js → chunk-2OOY75BW.js} +2 -2
  12. package/dist/{chunk-EELPBR7E.js → chunk-2USA3S3P.js} +2 -2
  13. package/dist/chunk-2VAHDDLM.js +133 -0
  14. package/dist/chunk-2XWIUW5Z.js +455 -0
  15. package/dist/{chunk-57N6LN2A.js → chunk-3AF4TUFK.js} +2 -2
  16. package/dist/chunk-3D4BOXW6.js +20 -0
  17. package/dist/{chunk-FFJQZG6J.js → chunk-3LO4FST5.js} +2 -2
  18. package/dist/{chunk-HXOU4XNH.js → chunk-3WTY4LP2.js} +2 -2
  19. package/dist/{chunk-DPWKKNKI.js → chunk-3Z5AMSK6.js} +2 -2
  20. package/dist/{chunk-F24G5NBE.js → chunk-44IETFOU.js} +2 -2
  21. package/dist/chunk-4FR6GQIT.js +2 -0
  22. package/dist/chunk-4KBTHJLP.js +2 -0
  23. package/dist/chunk-5BIKR67W.js +2 -0
  24. package/dist/{chunk-DJAO2OZJ.js → chunk-5PROPLHI.js} +2 -2
  25. package/dist/chunk-5V7EPTII.js +2 -0
  26. package/dist/{chunk-VZ7NXSHV.js → chunk-62LPZCBQ.js} +2 -2
  27. package/dist/{chunk-LXQUF2RP.js → chunk-64O2JHQA.js} +2 -2
  28. package/dist/chunk-6D4F5VWG.js +10 -0
  29. package/dist/{chunk-NEIQPFBI.js → chunk-6ERFBC3X.js} +2 -2
  30. package/dist/{chunk-4HE7MVWD.js → chunk-6ILKOOGH.js} +2 -2
  31. package/dist/chunk-6MFXCMZC.js +2 -0
  32. package/dist/chunk-6O7FACKB.js +2 -0
  33. package/dist/{chunk-R6M456QG.js → chunk-6TS3KOXR.js} +2 -2
  34. package/dist/{chunk-7U2YQSDE.js → chunk-76QOU4PK.js} +2 -2
  35. package/dist/{chunk-25GWKRUZ.js → chunk-7DUI77BN.js} +2 -2
  36. package/dist/chunk-7F45LJKI.js +2 -0
  37. package/dist/{chunk-DEAB5TGT.js → chunk-7F7T6DCR.js} +2 -2
  38. package/dist/chunk-7H6VHWWJ.js +2 -0
  39. package/dist/chunk-7HXT6YLU.js +5 -0
  40. package/dist/{chunk-KZYID5KV.js → chunk-7R4V5ES6.js} +4 -4
  41. package/dist/chunk-7RIRIADH.js +7 -0
  42. package/dist/chunk-7ZLWLOGT.js +2 -0
  43. package/dist/{chunk-WHADK6OS.js → chunk-A4WEAK35.js} +2 -2
  44. package/dist/chunk-AADQLOQ4.js +38 -0
  45. package/dist/{chunk-XFMVKFSF.js → chunk-AN76MGUE.js} +2 -2
  46. package/dist/chunk-ANLNLY66.js +2 -0
  47. package/dist/chunk-ATXPTSEI.js +81 -0
  48. package/dist/{chunk-EELG7D3Q.js → chunk-AX7IDVFT.js} +2 -2
  49. package/dist/chunk-B3PYOSCX.js +2 -0
  50. package/dist/chunk-B7MPDEAK.js +3 -0
  51. package/dist/chunk-BBB5FBX4.js +2 -0
  52. package/dist/{chunk-Y2VM4CJC.js → chunk-BHKK5RJY.js} +2 -2
  53. package/dist/chunk-BJWFVAA5.js +2 -0
  54. package/dist/chunk-BKVWUP7Y.js +2 -0
  55. package/dist/{chunk-7XA3OM44.js → chunk-BKZYTLGE.js} +2 -2
  56. package/dist/chunk-BL6DCHQP.js +2 -0
  57. package/dist/chunk-BOW7SSQH.js +43 -0
  58. package/dist/{chunk-KQHJEU6V.js → chunk-C4RHHCKL.js} +2 -2
  59. package/dist/chunk-C7C6AKAT.js +117 -0
  60. package/dist/chunk-CD6M6LS2.js +16 -0
  61. package/dist/chunk-CFE6PSG6.js +2 -0
  62. package/dist/{chunk-GPGRZJ3R.js → chunk-CFNIGQMT.js} +2 -2
  63. package/dist/{chunk-K3XFWJI2.js → chunk-CKBUBRYD.js} +2 -2
  64. package/dist/chunk-CZW5MZ5B.js +2 -0
  65. package/dist/chunk-DBBZ63ZX.js +2 -0
  66. package/dist/chunk-DBN7DMJB.js +18 -0
  67. package/dist/{chunk-CKRWA452.js → chunk-DUULLZHZ.js} +2 -2
  68. package/dist/{chunk-6HRZQLOI.js → chunk-DV5Y5NOS.js} +2 -2
  69. package/dist/chunk-DZOIKCTM.js +3 -0
  70. package/dist/chunk-E4PKTOL3.js +2 -0
  71. package/dist/{chunk-GVOMSPGL.js → chunk-E65ELFKU.js} +2 -2
  72. package/dist/{chunk-VXJJTQYE.js → chunk-E7QR35ST.js} +2 -2
  73. package/dist/{chunk-2RE5OCHZ.js → chunk-EFSXAINW.js} +2 -2
  74. package/dist/{chunk-GY7CCCEZ.js → chunk-EHVEIEQN.js} +2 -2
  75. package/dist/{chunk-BVFYEEBH.js → chunk-EHYDXE3Z.js} +2 -2
  76. package/dist/{chunk-HISEUIL2.js → chunk-EP63Y6LD.js} +2 -2
  77. package/dist/chunk-EPX6NQN6.js +4 -0
  78. package/dist/chunk-ETC674NS.js +5 -0
  79. package/dist/{chunk-5H5WTJSD.js → chunk-F5GSBHC6.js} +2 -2
  80. package/dist/chunk-FH3DGXC6.js +2 -0
  81. package/dist/{chunk-2XCGSDIT.js → chunk-FI7VGOR4.js} +2 -2
  82. package/dist/chunk-FJF6VO2P.js +2 -0
  83. package/dist/{chunk-FELGD32K.js → chunk-FLMTCX5R.js} +2 -2
  84. package/dist/chunk-FVFDOIM3.js +2 -0
  85. package/dist/{chunk-AQ2PORIO.js → chunk-G2HU5WRN.js} +2 -2
  86. package/dist/{chunk-7YQOCABQ.js → chunk-G4ALYS4J.js} +2 -2
  87. package/dist/{chunk-SWK4XPUS.js → chunk-G56I7K4W.js} +2 -2
  88. package/dist/{chunk-JFQBRL3J.js → chunk-GC4DG2V5.js} +2 -2
  89. package/dist/chunk-GG45PK4S.js +4 -0
  90. package/dist/{chunk-XN22RGSR.js → chunk-GHNPACNP.js} +2 -2
  91. package/dist/{chunk-XU75YQN4.js → chunk-GINH3YQU.js} +2 -2
  92. package/dist/chunk-GTZZVLKJ.js +2 -0
  93. package/dist/chunk-GXXW5ZHH.js +2 -0
  94. package/dist/{chunk-RNKPYYYE.js → chunk-HAXXKRTD.js} +2 -2
  95. package/dist/chunk-HEZWBAZY.js +2 -0
  96. package/dist/chunk-HMEWLMML.js +2 -0
  97. package/dist/{chunk-2KVU55CW.js → chunk-HOBOVYPO.js} +2 -2
  98. package/dist/{chunk-2YC7YNKT.js → chunk-HRFQ6GW5.js} +2 -2
  99. package/dist/{chunk-RYOYJMGF.js → chunk-HX4X7KG3.js} +2 -2
  100. package/dist/{chunk-AZS7YPCB.js → chunk-HYT2R7LX.js} +2 -2
  101. package/dist/chunk-IKQVBVQL.js +40 -0
  102. package/dist/chunk-J6GLBBRK.js +4 -0
  103. package/dist/{chunk-TNG2FYS5.js → chunk-J7A4PWFX.js} +2 -2
  104. package/dist/chunk-JCSAZ35V.js +2 -0
  105. package/dist/{chunk-EWWY2ZFL.js → chunk-JDU2IV3A.js} +2 -2
  106. package/dist/{chunk-SB25YMEQ.js → chunk-JFMEXGFE.js} +2 -2
  107. package/dist/chunk-JFMI5SGB.js +4 -0
  108. package/dist/chunk-JJP37RGX.js +57 -0
  109. package/dist/chunk-JZ2A7LDM.js +5 -0
  110. package/dist/chunk-KNLQGXVH.js +80 -0
  111. package/dist/chunk-KVQCECPR.js +2 -0
  112. package/dist/{chunk-F24QUEQP.js → chunk-KXXORBZ2.js} +2 -2
  113. package/dist/{chunk-IKVNEGTW.js → chunk-L5KYH6U3.js} +2 -2
  114. package/dist/chunk-L6XHYJPZ.js +21 -0
  115. package/dist/chunk-L7KTFEAV.js +43 -0
  116. package/dist/{chunk-UAQ4T73O.js → chunk-LDXHR5EL.js} +2 -2
  117. package/dist/chunk-LEECKFCJ.js +2 -0
  118. package/dist/{chunk-LO5JSW2C.js → chunk-MHGDSBFX.js} +2 -2
  119. package/dist/{chunk-JUN5DOAK.js → chunk-MLQVVDG3.js} +2 -2
  120. package/dist/chunk-MOKUWRHO.js +3 -0
  121. package/dist/{chunk-44T4DUAA.js → chunk-MPYAPMNE.js} +2 -2
  122. package/dist/{chunk-ARVO6TTW.js → chunk-MV6SPXCR.js} +2 -2
  123. package/dist/{chunk-NRBNAECH.js → chunk-MWN53KRN.js} +2 -2
  124. package/dist/{chunk-TH6IC56G.js → chunk-MZPXPSUJ.js} +2 -2
  125. package/dist/{chunk-FBCVASUG.js → chunk-N55KIE46.js} +2 -2
  126. package/dist/{chunk-VMWUV6WB.js → chunk-NB4D3BNM.js} +2 -2
  127. package/dist/{chunk-JAT6C3VX.js → chunk-NGKBOT6G.js} +2 -2
  128. package/dist/{chunk-Q6T2CAJL.js → chunk-NJGKXKQF.js} +2 -2
  129. package/dist/chunk-NJQISBL4.js +8 -0
  130. package/dist/chunk-NJT3ZEKY.js +16 -0
  131. package/dist/{chunk-KFVSJX25.js → chunk-NKMKZP6A.js} +2 -2
  132. package/dist/chunk-NODFZ6ED.js +2 -0
  133. package/dist/{chunk-ERCYGVAM.js → chunk-NSM5IEVW.js} +2 -2
  134. package/dist/{chunk-YAGYMBEX.js → chunk-NTGUVNR2.js} +2 -2
  135. package/dist/{chunk-N7FP5H5U.js → chunk-NU3KFF2O.js} +8 -8
  136. package/dist/chunk-NWLVNU66.js +557 -0
  137. package/dist/{chunk-Q55NF3ZG.js → chunk-NYKZMCRC.js} +2 -2
  138. package/dist/{chunk-I6UTXNHU.js → chunk-O6BUXZEH.js} +2 -2
  139. package/dist/chunk-ODPDP7A4.js +3 -0
  140. package/dist/{chunk-ZAZGGSM3.js → chunk-OHIV323X.js} +2 -2
  141. package/dist/chunk-OIAPEKMT.js +3 -0
  142. package/dist/chunk-OIOC5EHF.js +3 -0
  143. package/dist/{chunk-YIHNPKWD.js → chunk-ONPPQM4G.js} +2 -2
  144. package/dist/{chunk-RHHCLWQ6.js → chunk-OUHEZBYI.js} +2 -2
  145. package/dist/{chunk-MSR2QRUE.js → chunk-OVGYW7UD.js} +2 -2
  146. package/dist/{chunk-OPSAW5DT.js → chunk-OYKU4B3Y.js} +2 -2
  147. package/dist/{chunk-5YRQIE2B.js → chunk-POBJ6FR2.js} +2 -2
  148. package/dist/{chunk-ZGW4HLPD.js → chunk-PSZPMMWN.js} +2 -2
  149. package/dist/chunk-PXTRBKRK.js +3 -0
  150. package/dist/{chunk-U2N2KE7A.js → chunk-Q5JRIHT3.js} +2 -2
  151. package/dist/{chunk-GRX7JOXQ.js → chunk-Q7ATHARX.js} +2 -2
  152. package/dist/{chunk-5ZMBRQFC.js → chunk-Q7CSKIDM.js} +2 -2
  153. package/dist/{chunk-HG722PO7.js → chunk-QBQE7ZJ5.js} +2 -2
  154. package/dist/{chunk-Z2PZVKPR.js → chunk-QH22UIXP.js} +2 -2
  155. package/dist/chunk-QXCKQTKR.js +60 -0
  156. package/dist/chunk-RBAD4GJ2.js +13 -0
  157. package/dist/chunk-RMDPFPNW.js +2 -0
  158. package/dist/chunk-ROPJDEJZ.js +4 -0
  159. package/dist/{chunk-56NQAEPJ.js → chunk-RVZC6TJE.js} +2 -2
  160. package/dist/{chunk-XJX6LGHL.js → chunk-S4QZBKSR.js} +2 -2
  161. package/dist/chunk-SCPMZ73U.js +2 -0
  162. package/dist/{chunk-7IQXARSQ.js → chunk-SIAP5RGI.js} +2 -2
  163. package/dist/{chunk-4TQU4TX2.js → chunk-SIX4RFR3.js} +2 -2
  164. package/dist/{chunk-AYPDH2LU.js → chunk-SKKXTABJ.js} +2 -2
  165. package/dist/{chunk-ZYM4HOFA.js → chunk-SSRFUQBD.js} +2 -2
  166. package/dist/chunk-SYVJEEUJ.js +3 -0
  167. package/dist/chunk-T3CZAZSI.js +8 -0
  168. package/dist/chunk-T3I6NHBH.js +2 -0
  169. package/dist/{chunk-GDRJB3SB.js → chunk-T6DWDI5E.js} +2 -2
  170. package/dist/chunk-T6HRIROJ.js +7 -0
  171. package/dist/{chunk-OTSPRVNW.js → chunk-TAA7HXHE.js} +2 -2
  172. package/dist/{chunk-IJMD6BRI.js → chunk-TJ2JQYT3.js} +2 -2
  173. package/dist/chunk-TULNMD5T.js +368 -0
  174. package/dist/chunk-U2FPY5XA.js +3 -0
  175. package/dist/chunk-U3SXIMII.js +38 -0
  176. package/dist/{chunk-ENWQWA2R.js → chunk-U6KCHXJ4.js} +2 -2
  177. package/dist/chunk-UH3XSKS5.js +9 -0
  178. package/dist/{chunk-UDY7MIAW.js → chunk-UIFUZVCC.js} +2 -2
  179. package/dist/{chunk-BDGTPN27.js → chunk-UXKURIVI.js} +2 -2
  180. package/dist/{chunk-FGNCOQUX.js → chunk-V2RBODHL.js} +2 -2
  181. package/dist/chunk-VBKUWB6N.js +2 -0
  182. package/dist/{chunk-PIFTZEEM.js → chunk-VBV6ALJE.js} +2 -2
  183. package/dist/{chunk-2OXVP5U5.js → chunk-VDGFWCQV.js} +2 -2
  184. package/dist/chunk-VDSDOEWF.js +2 -0
  185. package/dist/{chunk-C76O5MDS.js → chunk-VZPWVCLN.js} +2 -2
  186. package/dist/chunk-WDSFQDPN.js +2 -0
  187. package/dist/{chunk-BTVKZGWT.js → chunk-WFA35BGR.js} +2 -2
  188. package/dist/{chunk-H7CG6LOE.js → chunk-WLMP3OCW.js} +2 -2
  189. package/dist/{chunk-WOOAY3PA.js → chunk-WSA52GOR.js} +2 -2
  190. package/dist/chunk-WYPL7GF7.js +2 -0
  191. package/dist/{chunk-RDULNRSJ.js → chunk-X3YVZAKZ.js} +2 -2
  192. package/dist/chunk-X6OGVFIT.js +2 -0
  193. package/dist/{chunk-ISWFRGJ6.js → chunk-XKXTR6ZI.js} +2 -2
  194. package/dist/chunk-Y5DFAW5W.js +4 -0
  195. package/dist/chunk-YSYPDRD5.js +3 -0
  196. package/dist/chunk-ZFVPWH62.js +5 -0
  197. package/dist/chunk-ZGIHTH27.js +2 -0
  198. package/dist/{chunk-QKT4UI2Y.js → chunk-ZGIQN2SX.js} +2 -2
  199. package/dist/chunk-ZHG4WAHR.js +12 -0
  200. package/dist/{chunk-CLG6DWVS.js → chunk-ZKB2XUEN.js} +2 -2
  201. package/dist/chunk-ZLMXIQLC.js +21 -0
  202. package/dist/chunk-ZMCQIHI4.js +2 -0
  203. package/dist/cli-main.js +2 -2
  204. package/dist/code-TAVIKWJI.js +2 -0
  205. package/dist/code-result-json-5FEFQCAQ.js +2 -0
  206. package/dist/command-descriptors-7BKH53Y3.js +343 -0
  207. package/dist/dataflow-GFBTVDH3.js +2 -0
  208. package/dist/dependence-slice-GWGQCODG.js +2 -0
  209. package/dist/deps-4QHVDPYA.js +2 -0
  210. package/dist/direct-navigation-4UBC6HNW.js +3 -0
  211. package/dist/entry-map-QCTF4RVY.js +2 -0
  212. package/dist/files-M2UBF5HJ.js +2 -0
  213. package/dist/frontend-profile-roles-D7eCum8P.d.ts +10 -0
  214. package/dist/{health-CPp2Jf1Z.d.ts → health-BI2a9WPy.d.ts} +60 -2
  215. package/dist/hierarchy-2UIHRLW4.js +2 -0
  216. package/dist/imports-WIE3YZOB.js +2 -0
  217. package/dist/index.d.ts +1 -1
  218. package/dist/index.js +1 -1
  219. package/dist/members-YKD636DA.js +2 -0
  220. package/dist/methods-VDF4IMYG.js +2 -0
  221. package/dist/output-continuation-command-4UMDOOLO.js +3 -0
  222. package/dist/output-pagination-2GME6OPY.js +19 -0
  223. package/dist/postinstall.js +1 -1
  224. package/dist/project-reindex-XEQTRCV5.js +3 -0
  225. package/dist/queries/affected.js +1 -1
  226. package/dist/queries/anchors.d.ts +1 -1
  227. package/dist/queries/anchors.js +1 -1
  228. package/dist/queries/architecture.js +1 -1
  229. package/dist/queries/bottlenecks.js +1 -1
  230. package/dist/queries/by-kind.js +1 -1
  231. package/dist/queries/call-graph.d.ts +2 -0
  232. package/dist/queries/call-graph.js +1 -1
  233. package/dist/queries/change-surface.js +1 -1
  234. package/dist/queries/cleanup-plan.js +1 -1
  235. package/dist/queries/co-change.d.ts +20 -2
  236. package/dist/queries/co-change.js +1 -1
  237. package/dist/queries/code.js +1 -1
  238. package/dist/queries/complexity-hotspots.js +1 -1
  239. package/dist/queries/complexity.js +1 -1
  240. package/dist/queries/context.js +1 -1
  241. package/dist/queries/convergence.js +1 -1
  242. package/dist/queries/coupling.js +1 -1
  243. package/dist/queries/cycles.js +1 -1
  244. package/dist/queries/dataflow.js +1 -1
  245. package/dist/queries/dead.d.ts +2 -0
  246. package/dist/queries/dead.js +1 -1
  247. package/dist/queries/decorative-checkers.js +1 -1
  248. package/dist/queries/deep-chains.js +1 -1
  249. package/dist/queries/dependence-slice.js +1 -1
  250. package/dist/queries/dependency-depth.js +1 -1
  251. package/dist/queries/deps.js +1 -1
  252. package/dist/queries/diff-impact.d.ts +9 -0
  253. package/dist/queries/diff-impact.js +1 -1
  254. package/dist/queries/doc-drift.js +1 -1
  255. package/dist/queries/drift.js +1 -1
  256. package/dist/queries/duplicate-bodies.d.ts +28 -1
  257. package/dist/queries/duplicate-bodies.js +1 -1
  258. package/dist/queries/entry-map.d.ts +1 -1
  259. package/dist/queries/entry-map.js +1 -1
  260. package/dist/queries/evidence.js +1 -1
  261. package/dist/queries/extract-candidates.d.ts +50 -23
  262. package/dist/queries/extract-candidates.js +1 -1
  263. package/dist/queries/fan.js +1 -1
  264. package/dist/queries/files.js +1 -1
  265. package/dist/queries/health.d.ts +1 -1
  266. package/dist/queries/health.js +1 -1
  267. package/dist/queries/hierarchy.js +1 -1
  268. package/dist/queries/hotspots.js +1 -1
  269. package/dist/queries/imports.js +1 -1
  270. package/dist/queries/incomplete-migration.js +1 -1
  271. package/dist/queries/index.d.ts +4 -3
  272. package/dist/queries/index.js +1 -1
  273. package/dist/queries/isolated.js +1 -1
  274. package/dist/queries/locality-candidates.js +1 -1
  275. package/dist/queries/members.js +1 -1
  276. package/dist/queries/methods.js +1 -1
  277. package/dist/queries/not-implemented.js +1 -1
  278. package/dist/queries/outline.js +1 -1
  279. package/dist/queries/passthrough-candidates.d.ts +9 -1
  280. package/dist/queries/passthrough-candidates.js +1 -1
  281. package/dist/queries/plan-context.js +1 -1
  282. package/dist/queries/react-component-duplicates.d.ts +19 -3
  283. package/dist/queries/react-component-duplicates.js +1 -1
  284. package/dist/queries/react-hook-candidates.d.ts +22 -3
  285. package/dist/queries/react-hook-candidates.js +1 -1
  286. package/dist/queries/react-large-component-pressure.d.ts +17 -3
  287. package/dist/queries/react-large-component-pressure.js +1 -1
  288. package/dist/queries/recent-duplicates.js +1 -1
  289. package/dist/queries/redundant-reexports.js +1 -1
  290. package/dist/queries/reference-neighborhood.js +1 -1
  291. package/dist/queries/reference-reachability.js +1 -1
  292. package/dist/queries/refs.js +1 -1
  293. package/dist/queries/self-audit.d.ts +7 -1
  294. package/dist/queries/self-audit.js +1 -1
  295. package/dist/queries/similar-chains.js +1 -1
  296. package/dist/queries/similar-files.js +1 -1
  297. package/dist/queries/similar-signatures.js +1 -1
  298. package/dist/queries/similar.js +1 -1
  299. package/dist/queries/slice.js +1 -1
  300. package/dist/queries/source-inspection.js +1 -1
  301. package/dist/queries/source-search.js +1 -1
  302. package/dist/queries/stale-abstractions.js +1 -1
  303. package/dist/queries/surface.js +1 -1
  304. package/dist/queries/symbols.js +1 -1
  305. package/dist/queries/system-map.d.ts +1 -1
  306. package/dist/queries/system-map.js +1 -1
  307. package/dist/queries/system.js +1 -1
  308. package/dist/queries/test-quality.js +1 -1
  309. package/dist/queries/trace.js +1 -1
  310. package/dist/queries/twin-ab.js +1 -1
  311. package/dist/queries/twin-drift.d.ts +22 -6
  312. package/dist/queries/twin-drift.js +1 -1
  313. package/dist/queries/unused-imports.js +1 -1
  314. package/dist/queries/unused-params.js +1 -1
  315. package/dist/queries/value-flow.js +1 -1
  316. package/dist/queries/vue-component-duplicates.js +1 -1
  317. package/dist/queries/vue-composable-candidates.js +1 -1
  318. package/dist/queries/vue-large-view-pressure.js +1 -1
  319. package/dist/queries/wrapper-candidates.d.ts +16 -1
  320. package/dist/queries/wrapper-candidates.js +1 -1
  321. package/dist/query-service-fastpath.js +5 -5
  322. package/dist/query-service-server.js +3 -3
  323. package/dist/refs-JNK5CLM7.js +2 -0
  324. package/dist/refs-pagination-6BLRYGMV.js +2 -0
  325. package/dist/reindex-worker.js +25 -25
  326. package/dist/reindex.d.ts +3 -2
  327. package/dist/reindex.js +35 -35
  328. package/dist/runtime.d.ts +34 -2
  329. package/dist/runtime.js +4 -4
  330. package/dist/rust-semantic-session-server.js +1 -1
  331. package/dist/rust-semantic-session-worker.js +1 -1
  332. package/dist/rust-semantic-worker.js +1 -1
  333. package/dist/{scip-cli-H-n59izO.d.ts → scip-cli-DOerTq-R.d.ts} +42 -4
  334. package/dist/slice-PHPVNCWX.js +2 -0
  335. package/dist/surface-MQX5MPIV.js +2 -0
  336. package/dist/symbol-resolution-DBLVXLBC.js +2 -0
  337. package/dist/system-JOPKV4OG.js +2 -0
  338. package/dist/trace-I2P2YFH4.js +2 -0
  339. package/dist/typescript-mailbox-worker.js +1 -1
  340. package/dist/value-flow-JJVMF7NP.js +2 -0
  341. package/dist/watch-server.js +3 -3
  342. package/docs/COMMAND_REFERENCE.md +2 -2
  343. package/docs/DETECTOR_GUIDE.md +51 -12
  344. package/docs/accuracy-audit-checklist.md +36 -13
  345. package/docs/locality-analyzer-design.md +9 -9
  346. package/package.json +2 -2
  347. package/skills/conductor/SKILL.md +110 -0
  348. package/skills/conductor/agents/openai.yaml +4 -0
  349. package/skills/principal-maintainability-review/SKILL.md +273 -0
  350. package/skills/principal-maintainability-review/agents/openai.yaml +4 -0
  351. package/skills/scip-calibrate/SKILL.md +102 -0
  352. package/skills/scip-calibrate/agents/openai.yaml +4 -0
  353. package/skills/scip-claim-audit/SKILL.md +113 -0
  354. package/skills/scip-claim-audit/agents/openai.yaml +4 -0
  355. package/skills/scip-probe-reachability/SKILL.md +93 -0
  356. package/skills/scip-probe-reachability/agents/openai.yaml +4 -0
  357. package/skills/scip-root-cause/SKILL.md +160 -0
  358. package/skills/scip-root-cause/agents/openai.yaml +4 -0
  359. package/skills/scip-system-compression/SKILL.md +252 -0
  360. package/skills/scip-system-compression/agents/openai.yaml +4 -0
  361. package/skills/scip-system-compression/references/compression-atlas.md +116 -0
  362. package/skills/scip-system-compression/references/compression-patterns.md +87 -0
  363. package/skills/scip-twin-drift/SKILL.md +109 -0
  364. package/skills/scip-twin-drift/agents/openai.yaml +4 -0
  365. package/dist/by-kind-4IYG2SKW.js +0 -2
  366. package/dist/call-graph-WQNXMNNN.js +0 -2
  367. package/dist/call-graph-evidence-lZa2dwQA.d.ts +0 -11
  368. package/dist/chunk-2BTJALUS.js +0 -454
  369. package/dist/chunk-3QXC54FQ.js +0 -3
  370. package/dist/chunk-3TJY6M3B.js +0 -7
  371. package/dist/chunk-42W3LFUK.js +0 -13
  372. package/dist/chunk-4GAQ6FI4.js +0 -43
  373. package/dist/chunk-6NC3YSPY.js +0 -38
  374. package/dist/chunk-6VEFRPTD.js +0 -5
  375. package/dist/chunk-7C26EKLZ.js +0 -4
  376. package/dist/chunk-7JYHQAH2.js +0 -22
  377. package/dist/chunk-7KSO2OAP.js +0 -2
  378. package/dist/chunk-7XZGZBSQ.js +0 -2
  379. package/dist/chunk-A77SCPW2.js +0 -3
  380. package/dist/chunk-AK3PYTIK.js +0 -5
  381. package/dist/chunk-AMIMMNA4.js +0 -11
  382. package/dist/chunk-AUY5BL74.js +0 -2
  383. package/dist/chunk-BDHFVH2M.js +0 -18
  384. package/dist/chunk-BECZLYNU.js +0 -8
  385. package/dist/chunk-BUTEIZKP.js +0 -10
  386. package/dist/chunk-BWVQP3LB.js +0 -38
  387. package/dist/chunk-BYDAFMSR.js +0 -57
  388. package/dist/chunk-BZYSGZRK.js +0 -2
  389. package/dist/chunk-C7IJMOFP.js +0 -134
  390. package/dist/chunk-CBBHFNLX.js +0 -2
  391. package/dist/chunk-D2MVJSP4.js +0 -21
  392. package/dist/chunk-D35XIZGN.js +0 -2
  393. package/dist/chunk-DKM723YF.js +0 -79
  394. package/dist/chunk-DRENNWRG.js +0 -2
  395. package/dist/chunk-E44IVWIJ.js +0 -367
  396. package/dist/chunk-EDMB6SSO.js +0 -7
  397. package/dist/chunk-EETGXQY7.js +0 -3
  398. package/dist/chunk-FKGQOTKD.js +0 -2
  399. package/dist/chunk-GH5YSGZL.js +0 -5
  400. package/dist/chunk-GQIDEID3.js +0 -2
  401. package/dist/chunk-HCVJR2V4.js +0 -3
  402. package/dist/chunk-IMKZEXZG.js +0 -2
  403. package/dist/chunk-ISIQLPJ2.js +0 -61
  404. package/dist/chunk-IXESDH3J.js +0 -2
  405. package/dist/chunk-JJ62MTQH.js +0 -40
  406. package/dist/chunk-JT6XX7QY.js +0 -8
  407. package/dist/chunk-KFOYCQAJ.js +0 -9
  408. package/dist/chunk-LRI5OMPE.js +0 -2
  409. package/dist/chunk-MHIEP7EG.js +0 -4
  410. package/dist/chunk-NK3JMP22.js +0 -2
  411. package/dist/chunk-NVSZNESQ.js +0 -2
  412. package/dist/chunk-OJNK5ALA.js +0 -2
  413. package/dist/chunk-OXYAWIEA.js +0 -2
  414. package/dist/chunk-OZETODHH.js +0 -2
  415. package/dist/chunk-PBUH2P5S.js +0 -3
  416. package/dist/chunk-PLJUQFQN.js +0 -2
  417. package/dist/chunk-PLYUVM4F.js +0 -2
  418. package/dist/chunk-PXXYQK55.js +0 -2
  419. package/dist/chunk-Q5TA4OY4.js +0 -20
  420. package/dist/chunk-Q7GBK5T7.js +0 -81
  421. package/dist/chunk-QLBSG7U5.js +0 -3
  422. package/dist/chunk-QWKHW6VZ.js +0 -2
  423. package/dist/chunk-RPL3ARU7.js +0 -16
  424. package/dist/chunk-SVHTMVA4.js +0 -4
  425. package/dist/chunk-T6QD2ZQB.js +0 -43
  426. package/dist/chunk-TD7VKJ2Y.js +0 -117
  427. package/dist/chunk-TKDNDQA7.js +0 -3
  428. package/dist/chunk-TQZV7KV4.js +0 -2
  429. package/dist/chunk-TUSPIVZ3.js +0 -4
  430. package/dist/chunk-URSGGIZX.js +0 -2
  431. package/dist/chunk-UT7TADJX.js +0 -2
  432. package/dist/chunk-V4NG5OMS.js +0 -554
  433. package/dist/chunk-VTCIYFEK.js +0 -2
  434. package/dist/chunk-VU6LIWHT.js +0 -2
  435. package/dist/chunk-VUSKPCUB.js +0 -2
  436. package/dist/chunk-WN3TCGJ4.js +0 -2
  437. package/dist/chunk-WSLEJSFR.js +0 -2
  438. package/dist/chunk-WYZIHUPZ.js +0 -16
  439. package/dist/chunk-XE33FV5W.js +0 -2
  440. package/dist/chunk-XGGBK66W.js +0 -4
  441. package/dist/chunk-XSWYJCAK.js +0 -2
  442. package/dist/chunk-Y334QQU5.js +0 -3
  443. package/dist/chunk-Z2AWCTN6.js +0 -2
  444. package/dist/chunk-ZOXKSQQB.js +0 -2
  445. package/dist/chunk-ZPASRBLF.js +0 -2
  446. package/dist/chunk-ZZ3Z7D56.js +0 -2
  447. package/dist/code-EQJFDT6I.js +0 -2
  448. package/dist/code-result-json-7UWIWBOO.js +0 -2
  449. package/dist/command-descriptors-ORNTVNYV.js +0 -342
  450. package/dist/dataflow-6VL54GX5.js +0 -2
  451. package/dist/dependence-slice-DT2NUHD2.js +0 -2
  452. package/dist/deps-DB7H5IKC.js +0 -2
  453. package/dist/direct-navigation-O3LUAYWQ.js +0 -3
  454. package/dist/entry-map-6K62RV3D.js +0 -2
  455. package/dist/files-MSLD7MO6.js +0 -2
  456. package/dist/hierarchy-IVBXAKFA.js +0 -2
  457. package/dist/imports-FRAVZ3Y2.js +0 -2
  458. package/dist/members-KJOJDYGO.js +0 -2
  459. package/dist/methods-2AYABBT3.js +0 -2
  460. package/dist/output-continuation-command-JHMPH6NC.js +0 -3
  461. package/dist/output-pagination-3OFL2MJV.js +0 -19
  462. package/dist/project-reindex-HYO4WD7Z.js +0 -3
  463. package/dist/refs-ARMA6XUJ.js +0 -2
  464. package/dist/refs-pagination-VUGIWN6U.js +0 -2
  465. package/dist/slice-YOB5YFAM.js +0 -2
  466. package/dist/surface-VY5EFWTW.js +0 -2
  467. package/dist/symbol-resolution-DGQN4XIV.js +0 -2
  468. package/dist/system-2KQ3QD2P.js +0 -2
  469. package/dist/trace-HTIPTXAE.js +0 -2
  470. package/dist/value-flow-5FV3VQI7.js +0 -2
@@ -1,2 +1,2 @@
1
- import{b as T}from"./chunk-GRX7JOXQ.js";import{a as M}from"./chunk-CBBHFNLX.js";import{a as P,c as j}from"./chunk-EETGXQY7.js";import"./chunk-C76O5MDS.js";import{c as b,e as v,f as l}from"./chunk-TQZV7KV4.js";import"./chunk-C7IJMOFP.js";import"./chunk-YXPUP5G2.js";import"./chunk-DRENNWRG.js";import{d as g}from"./chunk-7YQOCABQ.js";import"./chunk-QWKHW6VZ.js";import"./chunk-DHEQMPLW.js";import{a as w}from"./chunk-ENWQWA2R.js";import"./chunk-WN3TCGJ4.js";import"./chunk-DKM723YF.js";import{d as f}from"./chunk-K3XFWJI2.js";import"./chunk-NRBNAECH.js";import"./chunk-IW5XQG5G.js";import"./chunk-57N6LN2A.js";import"./chunk-JT6XX7QY.js";import"./chunk-H5EXS3HM.js";import{c as y,d}from"./chunk-HGFDYOVB.js";import{c as m}from"./chunk-SB25YMEQ.js";import{o as h,r as S}from"./chunk-AK3PYTIK.js";import{parentPort as c,workerData as O}from"worker_threads";import{randomUUID as C}from"crypto";import{resolve as R}from"path";var a=class{loadModule;discoverTsconfigs;createProjects;createProvider;db;module=null;projects=null;provider=null;stats={providerRequests:0,sessionsCreated:0,sessionsReused:0,sessionsRefreshed:0,sessionsReplaced:0,projectsCreated:0};constructor(e,t={}){this.db=e,this.loadModule=t.loadModule??b,this.discoverTsconfigs=t.discoverTsconfigs??P,this.createProjects=t.createProjects??v,this.createProvider=t.createProvider??((i,s,o)=>j(i,s,o,{reusedProjects:!0}))}semanticProvider(){return this.stats.providerRequests+=1,this.provider?(this.stats.sessionsReused+=1,this.provider):this.createSession()}advanceGeneration(e,t){let i=q(t);return this.provider?.dispose?.(),this.provider=null,this.db=e,this.projects?i.mode==="replace"?(this.projects=null,this.module=null,this.stats.sessionsReplaced+=1,i):(i.mode==="refresh"&&(D(this.projects,e.config.projectRoot,i),this.stats.sessionsRefreshed+=1),i):i}snapshotStats(){return{...this.stats}}dispose(){this.provider?.dispose?.(),this.provider=null,this.projects=null,this.module=null}createSession(){let e=this.module??this.loadModule();if(!e)return this.provider=l("ts-morph is not installed"),this.provider;if(this.module=e,!this.projects){let t=this.discoverTsconfigs(this.db);if(t.length===0)return this.provider=l("no tsconfig found"),this.provider;this.projects=this.createProjects(e,t),this.stats.projectsCreated+=this.projects.length}return this.provider=this.createProvider(this.db,e,this.projects),this.stats.sessionsCreated+=1,this.provider}};function q(r){let e=new Set;r.projectIdentityChanged&&e.add("project-identity-changed");for(let o of r.uncertainty)e.add(o);for(let o of r.changes)o.inputKind!=="source"&&e.add(`${o.inputKind}-input-changed`);if(e.size>0)return{mode:"replace",addedFiles:[],modifiedFiles:[],deletedFiles:[],reasons:[...e].sort()};let t=u(r.changes,"added"),i=u(r.changes,"modified"),s=u(r.changes,"deleted");return{mode:t.length+i.length+s.length===0?"reuse":"refresh",addedFiles:t,modifiedFiles:i,deletedFiles:s,reasons:[]}}function u(r,e){return r.filter(t=>t.kind===e).map(t=>t.path).sort()}function D(r,e,t){for(let i of r){for(let s of t.deletedFiles)i.project.getSourceFile(R(e,s))?.forget();for(let s of t.modifiedFiles){let o=i.project.getSourceFile(R(e,s));o&&o.refreshFromFileSystemSync()}t.addedFiles.length>0&&i.project.addSourceFilesFromTsConfig(i.tsconfigPath)}}var p=class{openDb;createHost;generationIdentity;readSnapshot;now;db=null;host=null;generation=null;snapshot=null;requests=0;lastRequestAtMs=null;lastError=null;available=null;constructor(e){this.openDb=e.openDb,this.createHost=e.createHost??(t=>new a(t)),this.generationIdentity=e.generationIdentity?t=>e.generationIdentity(t.config.dbPath):t=>t.generation.identity,this.readSnapshot=e.readSnapshot?t=>e.readSnapshot(t.config.dbPath):H,this.now=e.now??Date.now}handle(e,t){try{this.syncGeneration(e);let i=this.host.semanticProvider();switch(this.available=i.availability().available,this.requests+=1,this.lastRequestAtMs=this.now(),this.lastError=null,t.kind){case"availability":return i.availability();case"import-usage":return i.importUsage(t.file);case"references":return[...F(i,t.definitions,{exact:t.exact===!0})];case"reference-fragments":if(!i.referenceFragmentsForFiles)throw new Error("TypeScript provider does not support reference fragments.");return[...i.referenceFragmentsForFiles(t.files)];case"callees":return[...A(i,t.definitions)];case"signature":return i.signatureFor(t.definition);default:return B(t)}}catch(i){throw this.lastError=i instanceof Error?i.message:String(i),i}}status(e){let t=this.host?.snapshotStats();return{protocolVersion:w,state:this.lastError?"error":this.host?this.available?"ready":"unavailable":"idle",requests:this.requests,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastError?{lastError:this.lastError}:{},sessionsCreated:t?.sessionsCreated??0,sessionsReused:t?.sessionsReused??0,sessionsRefreshed:t?.sessionsRefreshed??0,sessionsReplaced:t?.sessionsReplaced??0,projectsCreated:t?.projectsCreated??0,...e?{mailbox:e}:{}}}closeTypeScriptService(){this.host?.dispose(),this.db?.close(),this.host=null,this.db=null,this.generation=null,this.snapshot=null,this.available=null}syncGeneration(e){if(this.generation===e&&this.host&&this.db)return;let t=this.openDb(),i=this.generationIdentity(t);if(!i||i!==e)throw t.close(),new Error("TypeScript semantic request does not match the currently published index generation.");let s=this.readSnapshot(t);if(!this.host||!this.db)this.db=t,this.host=this.createHost(t);else{let o=this.db;this.host.advanceGeneration(t,N(this.snapshot,s)),this.db=t,o.close()}this.generation=i,this.snapshot=s,this.available=null}};function F(r,e,t){return r.referencesForDefinitions?.(e,t)??new Map(e.map(i=>[i.symbolId,r.referencesFor(i)]))}function A(r,e){return r.calleesForDefinitions?.(e)??new Map(e.map(t=>[t.symbolId,r.calleesFor(t)]))}function H(r){if(!r.generation.metadataRaw)return null;let e=f(r.generation.metadataRaw);return e.kind!=="legacy"&&e.kind!=="supported"||!e.capabilities.usableForEvidenceCache?null:h(e.metadata.fingerprint)}function N(r,e){return e?S(r,e):{version:1,changes:[],projectIdentityChanged:!0,uncertainty:["prior-snapshot-unavailable"]}}function B(r){throw new Error(`Unhandled TypeScript semantic request: ${JSON.stringify(r)}`)}var Z=`typescript-semantic-${process.pid}-${C()}`,x=m(process.pid),ee={pid:process.pid,...x?{processIdentity:x}:{}};var n=L(O);if(!c)throw new Error("TypeScript mailbox worker requires a parent port.");if(n.kind==="index"){let r=new T({projectRoot:n.projectRoot,currentGeneration:()=>g(n.dbPath),...n.maxActiveSessions===void 0?{}:{maxActiveSessions:n.maxActiveSessions},...n.softMemoryLimitMb===void 0?{}:{softMemoryLimitMb:n.softMemoryLimitMb}});c.on("message",e=>{let t=k(e);I(t,()=>r.handle(t.payload.baseGeneration,t.payload.request),()=>r.status())})}else{let r=new p({openDb:()=>M(n.projectRoot)});c.on("message",e=>{let t=k(e),i=y();d(t.payload.profileEnvironment??{});try{I(t,()=>r.handle(t.payload.generation,t.payload.request),()=>r.status())}finally{d(i)}})}function I(r,e,t){let i;try{if(Date.now()>r.deadlineAtMs)throw new Error("TypeScript mailbox request expired before processing.");let s=e();if(Date.now()>r.deadlineAtMs)throw new Error("TypeScript mailbox request expired while the worker was processing it.");i={kind:"response",requestId:r.requestId,ok:!0,result:s,status:t()}}catch(s){i={kind:"response",requestId:r.requestId,ok:!1,error:s instanceof Error?s.message:String(s),status:t()}}c.postMessage(i)}function L(r){if(!r||typeof r!="object")throw new Error("TypeScript mailbox worker data is missing.");let e=r;if(e.kind==="index"&&typeof e.projectRoot=="string"&&typeof e.dbPath=="string"&&E(e.maxActiveSessions)&&E(e.softMemoryLimitMb))return{kind:"index",projectRoot:e.projectRoot,dbPath:e.dbPath,...e.maxActiveSessions===void 0?{}:{maxActiveSessions:e.maxActiveSessions},...e.softMemoryLimitMb===void 0?{}:{softMemoryLimitMb:e.softMemoryLimitMb}};if(e.kind==="semantic"&&typeof e.projectRoot=="string")return{kind:"semantic",projectRoot:e.projectRoot};throw new Error("TypeScript mailbox worker data is invalid.")}function E(r){return r===void 0||Number.isInteger(r)&&r>0}function k(r){if(!r||typeof r!="object")throw new Error("TypeScript mailbox worker request is missing.");let e=r;if(e.kind!=="request"||typeof e.requestId!="string"||!Number.isSafeInteger(e.deadlineAtMs)||typeof e.payload!="object"||e.payload===null)throw new Error("TypeScript mailbox worker request is invalid.");return e}
1
+ import{b as P}from"./chunk-Q7ATHARX.js";import{a as T}from"./chunk-VBKUWB6N.js";import{a as j,c as w}from"./chunk-MOKUWRHO.js";import"./chunk-VZPWVCLN.js";import{c as v,e as M,h as l}from"./chunk-FVFDOIM3.js";import"./chunk-2VAHDDLM.js";import"./chunk-YXPUP5G2.js";import"./chunk-BL6DCHQP.js";import{d as g}from"./chunk-G4ALYS4J.js";import"./chunk-HMEWLMML.js";import"./chunk-DHEQMPLW.js";import{a as R}from"./chunk-U6KCHXJ4.js";import"./chunk-RMDPFPNW.js";import"./chunk-WYPL7GF7.js";import"./chunk-T3I6NHBH.js";import"./chunk-ATXPTSEI.js";import{d as S}from"./chunk-CKBUBRYD.js";import"./chunk-MWN53KRN.js";import"./chunk-IW5XQG5G.js";import"./chunk-3AF4TUFK.js";import"./chunk-T3CZAZSI.js";import"./chunk-B3PYOSCX.js";import"./chunk-H5EXS3HM.js";import{c as b,d}from"./chunk-HGFDYOVB.js";import{c as h}from"./chunk-JFMEXGFE.js";import{c as y,f}from"./chunk-7HXT6YLU.js";import"./chunk-7F45LJKI.js";import{parentPort as c,workerData as O}from"worker_threads";import{getHeapStatistics as D}from"v8";import{randomUUID as L}from"crypto";import{resolve as x}from"path";var a=class{loadModule;discoverTsconfigs;createProjects;createProvider;db;module=null;projects=null;provider=null;retiredProjects=0;stats={providerRequests:0,sessionsCreated:0,sessionsReused:0,sessionsRefreshed:0,sessionsReplaced:0,projectsCreated:0};constructor(e,t={}){this.db=e,this.loadModule=t.loadModule??v,this.discoverTsconfigs=t.discoverTsconfigs??j,this.createProjects=t.createProjects??M,this.createProvider=t.createProvider??((r,s,o)=>w(r,s,o,{reusedProjects:!0}))}semanticProvider(){return this.stats.providerRequests+=1,this.provider?(this.stats.sessionsReused+=1,this.provider):this.createSession()}advanceGeneration(e,t){let r=q(t);return this.provider?.dispose?.(),this.provider=null,this.db=e,this.projects?r.mode==="replace"?(this.retiredProjects+=this.loadedProjectCount(),this.projects=null,this.module=null,this.stats.sessionsReplaced+=1,r):(r.mode==="refresh"&&(C(this.projects,e.config.projectRoot,r),this.stats.sessionsRefreshed+=1),r):r}snapshotStats(){return{...this.stats,projectsCreated:this.retiredProjects+this.loadedProjectCount()}}loadedProjectCount(){return this.projects?.filter(e=>e.loaded).length??0}dispose(){this.provider?.dispose?.(),this.provider=null,this.retiredProjects+=this.loadedProjectCount(),this.projects=null,this.module=null}createSession(){let e=this.module??this.loadModule();if(!e)return this.provider=l("ts-morph is not installed"),this.provider;if(this.module=e,!this.projects){let t=this.discoverTsconfigs(this.db);if(t.length===0)return this.provider=l("no tsconfig found"),this.provider;this.projects=this.createProjects(e,t)}return this.provider=this.createProvider(this.db,e,this.projects),this.stats.sessionsCreated+=1,this.provider}};function q(i){let e=new Set;i.projectIdentityChanged&&e.add("project-identity-changed");for(let o of i.uncertainty)e.add(o);for(let o of i.changes)o.inputKind!=="source"&&e.add(`${o.inputKind}-input-changed`);if(e.size>0)return{mode:"replace",addedFiles:[],modifiedFiles:[],deletedFiles:[],reasons:[...e].sort()};let t=u(i.changes,"added"),r=u(i.changes,"modified"),s=u(i.changes,"deleted");return{mode:t.length+r.length+s.length===0?"reuse":"refresh",addedFiles:t,modifiedFiles:r,deletedFiles:s,reasons:[]}}function u(i,e){return i.filter(t=>t.kind===e).map(t=>t.path).sort()}function C(i,e,t){for(let r of i)if(r.loaded){for(let s of t.deletedFiles)r.project.getSourceFile(x(e,s))?.forget();for(let s of t.modifiedFiles){let o=r.project.getSourceFile(x(e,s));o&&o.refreshFromFileSystemSync()}t.addedFiles.length>0&&r.project.addSourceFilesFromTsConfig(r.tsconfigPath)}}var p=class{openDb;createHost;generationIdentity;readSnapshot;now;db=null;host=null;generation=null;snapshot=null;requests=0;lastRequestAtMs=null;lastError=null;available=null;projectScope=null;softMemoryLimitBytes;memoryUsage;constructor(e){if(this.openDb=e.openDb,e.softMemoryLimitMb!==void 0&&(!Number.isInteger(e.softMemoryLimitMb)||e.softMemoryLimitMb<1))throw new Error("TypeScript semantic softMemoryLimitMb must be a positive integer.");this.softMemoryLimitBytes=e.softMemoryLimitMb===void 0?null:e.softMemoryLimitMb*1024*1024,this.memoryUsage=e.memoryUsage??(()=>({heapUsedBytes:process.memoryUsage().heapUsed,heapLimitBytes:D().heap_size_limit})),this.createHost=e.createHost??(t=>new a(t)),this.generationIdentity=e.generationIdentity?t=>e.generationIdentity(t.config.dbPath):t=>t.generation.identity,this.readSnapshot=e.readSnapshot?t=>e.readSnapshot(t.config.dbPath):A,this.now=e.now??Date.now}handle(e,t){try{this.syncGeneration(e);let r=this.host.semanticProvider(),s=r.availability();switch(this.available=s.available,this.projectScope=s.projectScope??null,this.requests+=1,this.lastRequestAtMs=this.now(),this.lastError=null,t.kind){case"availability":return r.availability();case"import-usage":return r.importUsage(t.file);case"references":return[...F(r,t.definitions,{exact:t.exact===!0})];case"reference-fragments":if(!r.referenceFragmentsForFiles)throw new Error("TypeScript provider does not support reference fragments.");return[...r.referenceFragmentsForFiles(t.files)];case"callees":return[...B(r,t.definitions)];case"callee-coverage":return[...r.calleeCoverageForDefinitions?.(t.definitions)??new Map];case"signature":return r.signatureFor(t.definition);default:return N(t)}}catch(r){throw this.lastError=r instanceof Error?r.message:String(r),r}}status(e){let t=this.host?.snapshotStats(),r=this.memoryUsage(),s=this.softMemoryLimitBytes!==null&&r.heapUsedBytes>=this.softMemoryLimitBytes;return{protocolVersion:R,state:this.lastError?"error":this.host?this.available?"ready":"unavailable":"idle",requests:this.requests,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastError?{lastError:this.lastError}:{},sessionsCreated:t?.sessionsCreated??0,sessionsReused:t?.sessionsReused??0,sessionsRefreshed:t?.sessionsRefreshed??0,sessionsReplaced:t?.sessionsReplaced??0,projectsCreated:t?.projectsCreated??0,heapUsedBytes:r.heapUsedBytes,heapLimitBytes:r.heapLimitBytes,...this.projectScope?{projectScope:this.projectScope}:{},...this.softMemoryLimitBytes===null?{}:{softMemoryLimitBytes:this.softMemoryLimitBytes},retireRequested:s,...e?{mailbox:e}:{}}}closeTypeScriptService(){this.host?.dispose(),this.db?.close(),this.host=null,this.db=null,this.generation=null,this.snapshot=null,this.available=null}syncGeneration(e){if(this.generation===e&&this.host&&this.db)return;let t=this.openDb(),r=this.generationIdentity(t);if(!r||r!==e)throw t.close(),new Error("TypeScript semantic request does not match the currently published index generation.");let s=this.readSnapshot(t);if(!this.host||!this.db)this.db=t,this.host=this.createHost(t);else{let o=this.db;this.host.advanceGeneration(t,H(this.snapshot,s)),this.db=t,o.close()}this.generation=r,this.snapshot=s,this.available=null}};function F(i,e,t){return i.referencesForDefinitions?.(e,t)??new Map(e.map(r=>[r.symbolId,i.referencesFor(r)]))}function B(i,e){return i.calleesForDefinitions?.(e)??new Map(e.map(t=>[t.symbolId,i.calleesFor(t)]))}function A(i){if(!i.generation.metadataRaw)return null;let e=S(i.generation.metadataRaw);return e.kind!=="legacy"&&e.kind!=="supported"||!e.capabilities.usableForEvidenceCache?null:y(e.metadata.fingerprint)}function H(i,e){return e?f(i,e):{version:1,changes:[],projectIdentityChanged:!0,uncertainty:["prior-snapshot-unavailable"]}}function N(i){throw new Error(`Unhandled TypeScript semantic request: ${JSON.stringify(i)}`)}var te=`typescript-semantic-${process.pid}-${L()}`,I=h(process.pid),re={pid:process.pid,...I?{processIdentity:I}:{}};var n=_(O);if(!c)throw new Error("TypeScript mailbox worker requires a parent port.");if(n.kind==="index"){let i=new P({projectRoot:n.projectRoot,currentGeneration:()=>g(n.dbPath),...n.maxActiveSessions===void 0?{}:{maxActiveSessions:n.maxActiveSessions},...n.softMemoryLimitMb===void 0?{}:{softMemoryLimitMb:n.softMemoryLimitMb}});c.on("message",e=>{let t=k(e);E(t,()=>i.handle(t.payload.baseGeneration,t.payload.request),()=>i.status())})}else{let i=new p({openDb:()=>T(n.projectRoot),...n.softMemoryLimitMb===void 0?{}:{softMemoryLimitMb:n.softMemoryLimitMb}});c.on("message",e=>{let t=k(e),r=b();d(t.payload.profileEnvironment??{});try{E(t,()=>i.handle(t.payload.generation,t.payload.request),()=>i.status())}finally{d(r)}})}function E(i,e,t){let r;try{if(Date.now()>i.deadlineAtMs)throw new Error("TypeScript mailbox request expired before processing.");let s=e();if(Date.now()>i.deadlineAtMs)throw new Error("TypeScript mailbox request expired while the worker was processing it.");r={kind:"response",requestId:i.requestId,ok:!0,result:s,status:t()}}catch(s){r={kind:"response",requestId:i.requestId,ok:!1,error:s instanceof Error?s.message:String(s),status:t()}}c.postMessage(r)}function _(i){if(!i||typeof i!="object")throw new Error("TypeScript mailbox worker data is missing.");let e=i;if(e.kind==="index"&&typeof e.projectRoot=="string"&&typeof e.dbPath=="string"&&m(e.maxActiveSessions)&&m(e.softMemoryLimitMb))return{kind:"index",projectRoot:e.projectRoot,dbPath:e.dbPath,...e.maxActiveSessions===void 0?{}:{maxActiveSessions:e.maxActiveSessions},...e.softMemoryLimitMb===void 0?{}:{softMemoryLimitMb:e.softMemoryLimitMb}};if(e.kind==="semantic"&&typeof e.projectRoot=="string"&&m(e.softMemoryLimitMb))return{kind:"semantic",projectRoot:e.projectRoot,...e.softMemoryLimitMb===void 0?{}:{softMemoryLimitMb:e.softMemoryLimitMb}};throw new Error("TypeScript mailbox worker data is invalid.")}function m(i){return i===void 0||Number.isInteger(i)&&i>0}function k(i){if(!i||typeof i!="object")throw new Error("TypeScript mailbox worker request is missing.");let e=i;if(e.kind!=="request"||typeof e.requestId!="string"||!Number.isSafeInteger(e.deadlineAtMs)||typeof e.payload!="object"||e.payload===null)throw new Error("TypeScript mailbox worker request is invalid.");return e}
2
2
  //# sourceMappingURL=typescript-mailbox-worker.js.map
@@ -0,0 +1,2 @@
1
+ import{a}from"./chunk-CFNIGQMT.js";import"./chunk-L6XHYJPZ.js";import"./chunk-3TNRNKAT.js";import"./chunk-7KCZELVM.js";import"./chunk-GHNPACNP.js";import"./chunk-HAXXKRTD.js";import"./chunk-JFMI5SGB.js";import"./chunk-BGBBVSH4.js";import"./chunk-AADQLOQ4.js";import"./chunk-MTDBHTSF.js";import"./chunk-WDSFQDPN.js";import"./chunk-ANLNLY66.js";import"./chunk-JJP37RGX.js";import"./chunk-HX4X7KG3.js";import"./chunk-JCSAZ35V.js";import"./chunk-NJGKXKQF.js";import"./chunk-FI7VGOR4.js";import"./chunk-WRQXLNYE.js";import"./chunk-L7KTFEAV.js";import"./chunk-2USA3S3P.js";import"./chunk-YUKYB54I.js";import"./chunk-BJT7LSPK.js";import"./chunk-5BIKR67W.js";import"./chunk-CZW5MZ5B.js";import"./chunk-F4FNK44D.js";import"./chunk-ODPDP7A4.js";import"./chunk-MOKUWRHO.js";import"./chunk-FVFDOIM3.js";import"./chunk-2VAHDDLM.js";import"./chunk-YXPUP5G2.js";import"./chunk-BL6DCHQP.js";import"./chunk-EHYDXE3Z.js";import"./chunk-2OOY75BW.js";import"./chunk-DHEQMPLW.js";import"./chunk-U6KCHXJ4.js";import"./chunk-T3I6NHBH.js";import"./chunk-ATXPTSEI.js";import"./chunk-CKBUBRYD.js";import"./chunk-IW5XQG5G.js";import"./chunk-T3CZAZSI.js";import"./chunk-B3PYOSCX.js";import"./chunk-H5EXS3HM.js";import"./chunk-HGFDYOVB.js";import"./chunk-JFMEXGFE.js";import"./chunk-7HXT6YLU.js";import"./chunk-7F45LJKI.js";export{a as valueFlow};
2
+ //# sourceMappingURL=value-flow-JJVMF7NP.js.map
@@ -1,4 +1,4 @@
1
- import{b as Je,c as Ve,g as ut,j as ht,k as X,l as pt,m as xe}from"./chunk-EDMB6SSO.js";import{a as K,b as St,c as vt}from"./chunk-7YQOCABQ.js";import{a as Pe,b as kt,c as Pt,d as Tt,e as Te,f as Ct,g as Ce,h as Wt,i as Et,j as Mt,k as At,l as Lt,m as _t,n as jt}from"./chunk-AUY5BL74.js";import{a as wt}from"./chunk-MXNGIEPU.js";import{a as Rt,c as Y}from"./chunk-BVFYEEBH.js";import"./chunk-JHH5SCZ3.js";import{d as B,e as Q,f as ke,g as bt}from"./chunk-QWKHW6VZ.js";import"./chunk-DHEQMPLW.js";import{a as Z,b as It,c as xt}from"./chunk-ENWQWA2R.js";import{L as ft,c as st,d as ye,g as q}from"./chunk-WN3TCGJ4.js";import{e as lt}from"./chunk-DKM723YF.js";import{a as ge,d as Xe}from"./chunk-K3XFWJI2.js";import{a as dt}from"./chunk-NRBNAECH.js";import"./chunk-IW5XQG5G.js";import"./chunk-57N6LN2A.js";import{a as M,c as Se,h as ve,j as Re,n as gt,o as mt,p as we,q as be,r as Ie,s as yt}from"./chunk-JT6XX7QY.js";import"./chunk-H5EXS3HM.js";import"./chunk-HGFDYOVB.js";import{c as T,d as C,e as Ke}from"./chunk-SB25YMEQ.js";import{H as Ye,I as F,J as Qe,L as Ze,M as O,O as N,S as et,T as tt,W as rt,X as it,Y as me,Z as nt,ba as ot,ea as at,h as R,m as fe,o as He,ua as ct}from"./chunk-AK3PYTIK.js";import v from"process";import{rmSync as mr}from"fs";import{resolve as Ai}from"path";import{pathToFileURL as Li}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 Ae,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 Le,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(Ye(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??pt,er.set(this,{projectRoot:e.projectRoot,config:e.config,gitReader:e.gitReader??et,languages:rr(e.languages??e.config.languages),typeScriptInputPaths:null,stagedIndexEntries:null}),this.gitignoreFilter=dt(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=We(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(ut))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=Le(e)?e:b(this.projectRoot,e);return Kt(this.projectRoot,r).replaceAll("\\","/")}scheduleReindex(e,r,i=!1){this.pendingTrigger=We(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&&_.get(this)!==s&&(_.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(_.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=We(this.pendingTrigger,n)):te.set(this,0),!u&&_.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),_.get(this)===o&&_.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 xe(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&&(I(this).stagedIndexEntries=Ht(this.projectRoot,I(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=I(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:Ae(b(this.projectRoot,d))?"change":"delete"}));i&&n?this.scheduleReindex({kind:"watch-git-state",detail:Ee("HEAD and index changed",l)},u,u!==void 0):i?this.scheduleReindex({kind:"watch-git-head",detail:Ee("HEAD changed",l)},u,u!==void 0):n&&this.scheduleReindex({kind:"watch-git-index",detail:Ee(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=I(this).gitReader,r=me(this.projectRoot,["rev-parse","--git-path","index"],e);if(!r)return null;let i=nt(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,_=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 I(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=T){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?xe(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:C,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 Me(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"}},Me=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":Ae(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=Ve({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 Je&&(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 We(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 _e=/^[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=Le(s)?s:Yt(t,s)}else return null;return Ae(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(_e.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?Le(e)?e:Yt(t,e):t}catch{return t}}function $t(t,e){try{let r=R(b(t,e),"Git reference").trim();return _e.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&&_e.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=I(t);r.config=B(e),r.languages=rr(r.config.languages)}catch{I(t).languages=ge}}function Jt(t,e,r){let i=I(t);if(fe(r,i.languages)==="other")return null;let s=zr(e);if(r===".scipquery.json"||ot(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=I(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=I(t);if(!e.languages.includes("typescript"))return e.typeScriptInputPaths=null,null;try{let r=e.config.indexer?.typescript,i=at(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=Xe(R(O(t,e).metaPath,"reindex metadata"));if(i.kind!=="supported"&&i.kind!=="legacy")return null;let n=He(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=ct(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 Ee(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 j,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(!Ze())return{kind:"disabled"};let i=r.repositoryId===void 0?tt(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=st(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(!De(f.lease))continue;if(!ne(f.lease.localCacheDir)){j(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(je(f.lease,!0))continue;try{Mt({projectRoot:f.lease.projectRoot,cacheDir:f.lease.localCacheDir,cliVersion:i})}catch{continue}if(je(f.lease,!0))continue;j(f.lease.localCacheDir,{recursive:!0,force:!0}),j(f.leasePath,{force:!0}),h+=1}finally{y.release()}}for(let f of u.deleteLocks)j(f.path,{force:!0});for(let f of u.deleteTemporaries)j(f.path,{recursive:!0,force:!0});for(let f of u.deleteGenerations)j(f.path,{recursive:!0,force:!0}),d+=f.size;lt(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(it(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&&De(d),live:n.has(h)||ne(h),busy:je(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=Ge(d),p=h!==void 0&&M(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)&&M(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 De(t){if(t.ownershipChecksum!==ft(t)||N(t.localCacheDir)!==N(Qe(t.projectRoot)))return!1;let e=N(S(F(),"projects"));return N(t.localCacheDir).startsWith(`${e}${ar}`)}function yi(t){if(!De(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 je(t,e=!1){for(let i of e?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let n=Ge(S(t.localCacheDir,i));if(n!==void 0&&M(n))return!0}let r=Ge(Y(t.localCacheDir).lockPath);return r!==void 0&&M(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 Ge(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=Ce(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 Te(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?(Te(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=Ce(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{rmSync as xi}from"fs";import{Worker as ki}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(Fe(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(Oe(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(Fe(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: ${Oe(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(Fe(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: ${Oe(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 Fe(t){return t instanceof Error?t:new Error(String(t))}function Oe(t){return t instanceof Error?t.message:String(t)}var Pi=6e4,Ti=10*6e4;function ur(t){let e=t.maxActiveSessions??8,r=t.workerSoftMemoryMb??Wi(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){we(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){be(t.paths,n,{ok:!1,protocolVersion:K,id:s,error:a},a,{nowMs:o,limits:t.limits})},idleTtlMs:t.workerIdleMs??Ti,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){we(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){be(t.paths,r,{ok:!1,protocolVersion:Z,id:i,error:n},n,{nowMs:s,limits:t.limits})},idleTtlMs:Pi,onBusy:t.onBusy,onFatal:t.onFatal})}function pr(t){let e=t.now??Date.now,r=T(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 x=e();try{t.complete(y.claim,y.envelope,m,x)}catch(k){if(!(k instanceof ve))throw k;try{t.reject(y.claim,y.envelope.id,k.message,x)}catch(P){if(!(P instanceof ve))throw P;xi(y.claim.path,{force:!0})}}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:M,readProcessIdentity:T}})[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=Mi(f);try{t.reject(p,m,y,e()),a?.claim===p&&h(a)}catch(x){l(Ei(x))}}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 Ci=6144;function fr(){let t=Number.parseInt(process.env.SCIP_TS_WORKER_HEAP_MB??"",10);return Number.isFinite(t)&&t>0?t:Ci}function Wi(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 ki(r,{workerData:e,resourceLimits:{maxOldGenerationSizeMb:t.workerHeapMb??fr()}})}function Ei(t){return t instanceof Error?t:new Error(String(t))}function Mi(t){return t instanceof Error?t.message:String(t)}var yr=2e3,_i=5e3,ji=5e3,Gi=6e4,Di=10,Fi=50,Oi=1e4;function Ni(t,e=1){return Ke(t,e,Di,Fi,Oi,8)}function qi(t,e){let r;return{begin(){return r||(e.requestStop(),e.closeWake(),r=t.stop(),r.catch(()=>{})),r}}}async function Bi(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=Ni(n,s);return await e.wait(a),{indexRequests:r,semanticRequests:i,processedRequests:n,consecutiveIdlePolls:s,stopped:!1,delayMs:a}}function $i(t){return t==="fresh"?null:{kind:"watch-startup",detail:`index ${t} when watch service started`}}function Ui(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 zi(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=C();if(o-i>=ji&&(i=o,!Ft(t.worktreeLiveness))){t.requestStop();return}if(o-s>=Gi&&(s=o,Ie(t.indexMailboxPaths),Ie(t.semanticMailboxPaths)),o-n>=se&&(n=o,cr(t.projectRoot,t.cliVersion)),o-r>=_i){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 Ji(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 Bi(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 Vi(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 Hi(t,e,r={}){let i=Et(t,e),n=i.projectRoot,s=i.worktreeKind==="git"?Xi(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=T(v.pid),h=_t(u.lockPath,n,{readProcessIdentity:g=>g===v.pid?d:T(g)});if(!h.acquired)return;let p=new oe(u.refreshRequestsPath,{retryDelayMs:Math.max(1e3,c.cooldownMs)});p.initializeAfterOwnershipAcquired();let m=Date.now(),f=C(),y=m,x=f,k={state:"idle"},P,ce,W,le,de=X(l.dbPath),V=!1,Ne=!1,qe=Number.NEGATIVE_INFINITY,Be,$e,G=It(l.cacheDir),D=St(l.cacheDir);Re(G),Re(D);let Ue=Pe([D.pendingDir,D.legacyRequestDir,G.pendingDir,G.legacyRequestDir,u.refreshRequestsPath]),w=(g=!1,E=g?"durable":"visibility")=>{if(!Ne)return;let pe=Date.now(),L=C();!g&&L-qe<yr||(qe=L,Ui({statePath:u.statePath,durability:E,processIdentity:d,projectRoot:n,worktreeId:i.worktreeId,cliVersion:e,startedAtMs:m,nowMs:pe,lastActivityAtMs:y,idleTimeoutMs:c.idleTimeoutMs,watcherStatus:k,indexGeneration:P,lastRefresh:ce,lastError:W,reindexActivity:de,refreshCoordinator:p,semanticLane:ue,indexLane:he,semanticBusyUntilMs:Be,indexBusyUntilMs:$e}))},A=()=>{y=Date.now(),x=C()},Sr=g=>{A(),le??=g,W={at:new Date().toISOString(),message:g.message},w(!0,"visibility")},{semanticLane:ue,indexLane:he}=Vi({semanticPaths:G,indexPaths:D,projectRoot:n,dbPath:l.dbPath,config:o,onSemanticBusy(g){Be=g===void 0?void 0:g+5e3,w(!0,"visibility")},onIndexBusy(g){$e=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){k=g,g.state!=="idle"&&(P=void 0),g.state!=="idle"&&A(),w(!0)},onReindexComplete(g,E,pe){A();let L=pe?.pendingChanges!==!1?ke(n,o,l):bt(l);return ce=L.lastRefresh,P=L.state==="fresh"?q(l.dbPath)??void 0:void 0,de=X(l.dbPath),p.completeActive(),W=void 0,w(!0),L.state==="fresh"},onReindexError(){p.failActive()},onRefreshSuppressed(g){let E=ht(l.dbPath,g);E.state==="failed"&&(W={at:new Date().toISOString(),message:`Suppressed-refresh telemetry was not recorded: ${E.reason}`},w(!0,"visibility")),de=X(l.dbPath)},onError(g){A(),P=void 0,W={at:new Date().toISOString(),message:g.message},w(!0)}}),ze=qi(H,{requestStop(){V=!0},closeWake(){Ue.close()}}),vr=()=>{ze.begin()},Rr=zi({worktreeLiveness:a,indexMailboxPaths:D,semanticMailboxPaths:G,projectRoot:n,cliVersion:e,activityPath:u.activityPath,refreshCoordinator:p,watcherStatus:()=>k,requestRefresh:g=>H.requestRefresh({kind:"watch-demand",detail:g},{immediate:!0}),requestStop:()=>{V=!0},recordActivity:A,updateObservedActivity(g,E){g<=y||(y=g,x=E)},persistState:w});await Ji({watcher:H,shutdown:ze,stopSignal:vr,initializeFreshness(){let g=ke(n,o,l);return ce=g.lastRefresh,P=g.state==="fresh"?q(l.dbPath)??void 0:void 0,$i(g.state)},markReady:()=>{Ne=!0},recordActivity:A,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:k,lastActivityAtMs:x,nowMs:C(),idleTimeoutMs:c.idleTimeoutMs}),wait:g=>Ue.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 W={at:new Date().toISOString(),message:`Watch service shutdown is degraded: ${g.join("; ")}`},w(!0),new Error(W.message)}})}function Xi(t,e){let r=rt(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 Ki(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 Yi=v.argv[1]?Li(Ai(v.argv[1])).href:null;if(Yi===import.meta.url){let t=v.argv[2],e=v.argv[3],r=Qi(v.argv[4]);if(!t||!e)console.error("watch-service: expected <project-root> <cli-version>"),v.exitCode=1;else try{await Hi(t,e,r)}catch(i){Ki(i)}}function Qi(t){if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}}export{Pe as createPathChangeWake,qi as createWatchServiceShutdown,Bi as runWatchServiceLoopIteration,Hi as runWatchServiceServer,$i as startupRefreshTrigger,Ki as terminateWatchServiceProcess,Ni as watchServiceLoopDelayMs};
1
+ import{b as Ke,c as Xe,g as gt,j as yt,k as X,l as St,m as ke}from"./chunk-7RIRIADH.js";import{a as Y,b as xt,c as It}from"./chunk-G4ALYS4J.js";import{a as Te,b as Mt,c as Wt,d as At,e as Pe,f as Lt,g as Ce,h as _t,i as jt,j as Gt,k as Dt,l as Ft,m as Ot,n as Nt}from"./chunk-X6OGVFIT.js";import{a as Tt}from"./chunk-MXNGIEPU.js";import{a as kt,c as Q}from"./chunk-EHYDXE3Z.js";import"./chunk-2OOY75BW.js";import{d as B,e as Z,f as $,g as Pt}from"./chunk-HMEWLMML.js";import"./chunk-DHEQMPLW.js";import{a as ee,b as Ct,c as Et}from"./chunk-U6KCHXJ4.js";import{H as Rt,c as _}from"./chunk-RMDPFPNW.js";import{c as it,d as ye}from"./chunk-WYPL7GF7.js";import{a as pt,b as ft}from"./chunk-T3I6NHBH.js";import{e as ht}from"./chunk-ATXPTSEI.js";import{a as ge,d as Qe}from"./chunk-CKBUBRYD.js";import{a as mt}from"./chunk-MWN53KRN.js";import"./chunk-IW5XQG5G.js";import"./chunk-3AF4TUFK.js";import{b as Re,g as ve,i as be,m as vt,n as bt,o as we,p as xe,q as Ie,r as wt}from"./chunk-T3CZAZSI.js";import{a as W}from"./chunk-B3PYOSCX.js";import"./chunk-H5EXS3HM.js";import"./chunk-HGFDYOVB.js";import{c as P,d as C,e as Ze}from"./chunk-JFMEXGFE.js";import{B as q,F as nt,G as st,J as ot,K as at,L as Se,M as ct,Q as lt,T as dt,a as me,c as Ye,ha as ut,u as et,v as O,w as tt,y as rt,z as N}from"./chunk-7HXT6YLU.js";import{a as Je,g as Ve,h as v}from"./chunk-7F45LJKI.js";import Bi from"better-sqlite3";import R from"process";import{rmSync as Ir}from"fs";import{resolve as $i}from"path";import{pathToFileURL as Ui}from"url";import{lstatSync as Er}from"fs";function Bt(t,e){let r=te(t);if(r.kind!=="directory")throw new Error(`Watcher root is not a directory: ${t}`);if(!e)return{projectRoot:t,projectDirectory:r};let i=te(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 $t(t){try{if(!qt(t.projectDirectory,te(t.projectRoot)))return!1;let e=t.gitControlDirectory;return!e||qt(e.identity,te(e.path))}catch{return!1}}function te(t){let e=Er(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 qt(t,e){return t.device===e.device&&t.inode===e.inode&&t.birthtimeNs===e.birthtimeNs&&t.kind===e.kind}import{existsSync as Le,lstatSync as Wr,statSync as Zt,watch as Ar}from"fs";import{EventEmitter as Lr}from"events";import{basename as _r,dirname as er,isAbsolute as _e,join as b,relative as tr,resolve as rr}from"path";import{watch as jr}from"chokidar";import Gr from"ignore";var ir=5e3,ne=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;lastObservedGeneration=null;publishedGeneration;indexFreshness;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;reconcileTimer=null;lastGitState=null;preferFilesystemGitState=!0;watchGitLayout=null;localCacheWatchPath;gitignoreFilter;extraIgnore;stopped=!1;constructor(e){this.projectRoot=e.projectRoot,this.config=e.config,this.watchConfig=Z(e.config),this.outputDb=e.outputDb??b(et(this.projectRoot,e.config),"index.db"),this.preferFilesystemGitState=e.gitReader===void 0,this.localCacheWatchPath=ai(this.projectRoot,er(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??qr,nr.set(this,ci(e.stopTimeoutMs??ir,"watcher stop timeout")),this.reindexRunner=e.reindexRunner??Yr(),this.subscriptionFactory=e.subscriptionFactory??Br,this.budgetInspector=e.budgetInspector??St,this.publishedGeneration=e.publishedGeneration??_,this.indexFreshness=e.indexFreshness??oi,this.lastObservedGeneration=this.readPublishedGeneration(),sr.set(this,{projectRoot:e.projectRoot,config:e.config,gitReader:e.gitReader??nt,languages:ar(e.languages??e.config.languages),typeScriptInputPaths:null,stagedIndexEntries:null}),this.gitignoreFilter=mt(e.projectRoot),this.extraIgnore=Gr(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore),Me(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,ie(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(),this.clearReconcileTimer();let r=this.activeOperation;r&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"});let i=[...ie(this).closures],n=Fr(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=Ee(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||!ti(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(ie(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(Jt(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("../")||Jt(i,this.localCacheWatchPath)||this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)||i.endsWith("index.db")||i.endsWith("index.scip")||i.endsWith("index.db.tmp")||_r(i).startsWith(gt))return;i===".scipquery.json"&&Xt(this,this.projectRoot);let n=Yt(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=_e(e)?e:b(this.projectRoot,e);return tr(this.projectRoot,r).replaceAll("\\","/")}scheduleReindex(e,r,i=!1){this.pendingTrigger=Ee(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&&j.get(this)!==s&&(j.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||this.reconcileExternalPublication())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(),re.set(this,0),this.stopped)return;if(j.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}Me(this),this.lastObservedGeneration=this.readPublishedGeneration();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=or(l),d=0;if(u?(d=(re.get(this)??0)+1,re.set(this,d),this.dirty=!0,this.pendingTrigger=Ee(this.pendingTrigger,n)):re.set(this,0),!u&&j.get(this)!==o&&(this.onReindexError(l,n),this.onError(l)),this.dirty){let h=u?Xr(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),j.get(this)===o&&j.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 Dr(l,n,this.clock),d=ie(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,e.state==="cooldown"||e.state==="budget-paused"?this.armReconcileTimer(e.until):this.clearReconcileTimer(),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=Zr(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=_(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 ke(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=Qt(this.projectRoot,x(this).gitReader),this.gitPollTimer=this.clock.setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}armReconcileTimer(e){this.clearReconcileTimer();let r=e-this.wallNow();if(r<=0||!(this.watchConfig.gitPollMs>0))return;let i=Math.min(this.watchConfig.gitPollMs,r);this.reconcileTimer=this.clock.setTimeout(()=>{this.reconcileTimer=null,!(this.stopped||this.reconcileExternalPublication())&&(this.status.state==="cooldown"||this.status.state==="budget-paused")&&this.armReconcileTimer(this.status.until)},i),this.reconcileTimer.unref?.()}clearReconcileTimer(){this.reconcileTimer&&(this.clock.clearTimeout(this.reconcileTimer),this.reconcileTimer=null)}readPublishedGeneration(){try{return this.publishedGeneration(this.outputDb)}catch{return null}}reconcileExternalPublication(){if(this.stopped||this.reindexInFlight||!(this.dirty||this.status.state==="budget-paused"||this.status.state==="cooldown"||this.status.state==="waiting"))return!1;let r=this.readPublishedGeneration();if(r===null||r===this.lastObservedGeneration)return!1;this.lastObservedGeneration=r;let i;try{i=this.indexFreshness(this.projectRoot,this.config,this.outputDb)}catch{return!1}if(i!=="fresh")return!1;let n=this.pendingTrigger??{kind:"unknown"};return this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearBudgetTimer(),this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.resetPendingChanges(),Me(this),this.onRefreshSuppressed({...n,detail:`a generation published outside the watcher is fresh${n.detail?` (${n.detail})`:""}`}),this.setStatus({state:"idle"}),!0}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=Qt(this.projectRoot,s.gitReader);s.stagedIndexEntries=o;let c=hi(this.projectRoot,s.gitReader,e,r,a,o,i,n),l=null;if(c!==null&&(c.includes(".scipquery.json")&&Xt(this,this.projectRoot),l=c.filter(d=>Yt(this,"add",d)!==null),l.length===0))return;let u=l?.map(d=>({path:d,kind:Le(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??ri(this.projectRoot);if(!e)return null;this.watchGitLayout=e;let r=ii(e.gitDir);return r?Kt(r,e.indexPath):null}readGitStateFromGit(){let e=x(this).gitReader,r=Se(this.projectRoot,["rev-parse","--git-path","index"],e);if(!r)return null;let i=ct(this.projectRoot,r);return Kt(Se(this.projectRoot,["rev-parse","--verify","HEAD"],e),i)}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};async function Dr(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 Ht=new WeakMap,nr=new WeakMap,sr=new WeakMap,j=new WeakMap,re=new WeakMap;function ie(t){let e=Ht.get(t);if(e)return e;let r={closures:new Set,errors:[]};return Ht.set(t,r),r}function Fr(t){return nr.get(t)??ir}function x(t){let e=sr.get(t);if(!e)throw new Error("Watcher input state was not initialized.");return e}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 Nr(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=N(r,h),g=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:g?.pnpmWorkspaces??s?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:g?.projectMode??a,projects:g?.projects??o??[],maxHeapMb:g?.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?ke(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 qr={now:C,wallNow:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},Br=(t,e)=>$r(process.platform,e.usePolling)?new Ae(t):jr(t,e);function $r(t,e){return t==="darwin"&&e!==!0}var U=class extends Error{constructor(e,r){super(e,r===void 0?void 0:{cause:r}),this.name="RecursiveSourceWatchError"}},Ae=class{events=new Lr;watcher;constructor(e){this.watcher=Ar(e,{recursive:!0},(r,i)=>{if(i===null){this.events.emit("error",new U("Recursive source watcher omitted the changed path."));return}let n=b(e,i.toString());this.events.emit("all",Ur(r,n),n)}),this.watcher.on("error",r=>{this.events.emit("error",new U(`Recursive source watcher failed: ${r.message}`,r))})}on=(e,r)=>(this.events.on(e,r),this);close(){this.watcher.close()}};function Ur(t,e){return t==="change"?"change":Le(e)?Zt(e).isDirectory()?"addDir":"add":"unlink"}var Hr=15*6e4,zr=1e3,Jr=64*1024;function Vr(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function zt(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 Kr(t,e){return Object.assign(new Error(t,e===void 0?void 0:{cause:e}),{retryable:!0})}function or(t){return t instanceof Error&&"retryable"in t&&t.retryable===!0}function Xr(t,e){let r=t*2**Math.min(5,Math.max(0,e-1));return Math.max(t,Math.min(3e4,r))}function Yr(t={}){let e=t.timeoutMs??Hr,r=t.terminationGraceMs??zr,i=t.maxOutputBytes??Jr,n=t.resolveLaunch??Nr;return{start(s){let a=n(s),o=new AbortController,c=Vr(),l=!1,u=Xe({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=zt(new Error(`Reindex worker exited with ${d.signal?`signal ${d.signal}`:`code ${d.status}`}`),c);throw d.status===75?Kr(h):new Error(h)}return d.durationMs}).catch(d=>{throw or(d)?d:(d instanceof Ke&&(c={stdoutTail:d.stdout,stderrTail:d.stderr,stdoutTruncated:d.stdoutTruncated,stderrTruncated:d.stderrTruncated}),new Error(zt(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 Ee(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 Qr(t){if(t==="add")return"add";if(t==="change")return"change";if(t==="unlink")return"delete"}function Zr(t,e){return t?t==="add"?e==="delete"?null:"add":t==="delete"&&e==="add"?"change":e:e}function ei(t){return t instanceof Error&&"code"in t&&t.code==="EMFILE"||String(t).includes("EMFILE: too many open files")}function ti(t){return t instanceof U||ei(t)}var je=/^[0-9a-f]{40,64}$/i;function Jt(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 ri(t){let e=b(t,".git");try{let r=Wr(e),i;if(r.isDirectory())i=e;else if(r.isFile()){let n=/^gitdir:\s*(.+)\s*$/m.exec(v(e,"Git directory marker"));if(!n?.[1])return null;let s=n[1].trim();i=_e(s)?s:rr(t,s)}else return null;return Le(i)?{gitDir:i,indexPath:b(i,"index")}:null}catch{return null}}function ii(t){let e;try{e=v(b(t,"HEAD"),"Git HEAD").trim()}catch{return}if(je.test(e))return e.toLowerCase();let r=/^ref:\s*(.+)$/.exec(e)?.[1]?.trim();if(!r)return;let i=ni(t);return Vt(t,r)??Vt(i,r)??si(i,r)}function ni(t){try{let e=v(b(t,"commondir"),"Git common-directory marker").trim();return e?_e(e)?e:rr(t,e):t}catch{return t}}function Vt(t,e){try{let r=v(b(t,e),"Git reference").trim();return je.test(r)?r.toLowerCase():void 0}catch{return}}function si(t,e){try{for(let r of v(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&&je.test(n))return n.toLowerCase()}}catch{return}}function oi(t,e,r){let i=er(r);return $(t,e,{dbPath:r,metaPath:b(i,"meta.json"),cacheDir:i}).state}function Kt(t,e){let r={head:t,indexPath:e};try{let i=Zt(e);r.indexMtimeMs=i.mtimeMs,r.indexSize=i.size}catch{r.indexMtimeMs=void 0,r.indexSize=void 0}return r}function ai(t,e){let r=tr(t,e).replaceAll("\\","/");if(!(!r||r===".."||r.startsWith("../")))return r}function ci(t,e){if(!Number.isSafeInteger(t)||t<=0)throw new Error(`${e} must be a positive integer.`);return t}function ar(t){return t&&t.length>0?[...t]:ge}function Xt(t,e){try{let r=x(t);r.config=B(e),r.languages=ar(r.config.languages)}catch{x(t).languages=ge}}function Yt(t,e,r){let i=x(t);if(me(r,i.languages)==="other")return null;let s=Qr(e);if(r===".scipquery.json"||lt(r))return i.typeScriptInputPaths=null,s;if(!li(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=cr(t);return c?c.has(r)?"add":null:s}function Me(t){let e=x(t);if(!e.languages.includes("typescript")){e.typeScriptInputPaths=null;return}let r=di(e.projectRoot,e.config,e.languages);e.typeScriptInputPaths=r??cr(t)}function cr(t){let e=x(t);if(!e.languages.includes("typescript"))return e.typeScriptInputPaths=null,null;try{let r=e.config.indexer?.typescript,i=dt(e.projectRoot,r?.projectMode,r?.projects);return e.typeScriptInputPaths=i,i}catch{return e.typeScriptInputPaths=null,null}}function li(t,e){if(!e.includes("typescript"))return!1;let r=me(t,["typescript","javascript"]);return r==="source"||r==="ambient"}function di(t,e,r){try{let i=Qe(v(N(t,e).metaPath,"reindex metadata"));if(i.kind!=="supported"&&i.kind!=="legacy")return null;let n=Ye(i.metadata.fingerprint);return!n||!ui(n,r,e)?null:new Set(n.files.map(s=>s.path))}catch{return null}}function ui(t,e,r){let i=ut(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 hi(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 pi(l.output))c.add(u)}if(o){if(n===null||s===null)return null;for(let l of mi(n,s))c.add(l)}return[...c].sort()}function Qt(t,e){let r=e.runResult(t,["diff","--cached","--raw","-z","--no-renames","--relative","--"]);return r.kind==="success"?fi(r.output):null}function pi(t){return t.split("\0").filter(e=>e.length>0)}function fi(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 mi(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 se,lstatSync as H,readdirSync as ur,realpathSync as lr,rmSync as G,statSync as gi}from"fs";import{join as S,resolve as z,sep as hr}from"path";var yi=3600*1e3,Si=2*1024*1024*1024,oe=300*1e3,Ri="gc-state.json",vi="gc.lock";function bi(t){let e=t.leases.filter(o=>o.managed&&!o.live&&!o.busy),r=wi(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 wi(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 pr(t,e,r={}){if(!rt())return{kind:"disabled"};let i=r.repositoryId===void 0?st(t)?.repositoryId:r.repositoryId;if(!i)return{kind:"unavailable"};let n=S(O(),"repositories",i),s=(r.now??Date.now)(),a=se(n)?fr(t,n,i,e,s,r):{kind:"unavailable"};return xi(t,i,e,s,r),a}function fr(t,e,r,i,n,s){let a=S(e,"gc-state.json"),o=Pi(a);if(!s.force&&o&&n-Date.parse(o.lastSweepAt)<oe)return{kind:"throttled",sweptAt:o.lastSweepAt};let c=it(e,{now:()=>n});if(!c)return{kind:"busy"};try{let l=Ii(t,e,r,o?.unreferencedSince??{}),u=bi({nowMs:n,...l,policy:{generationTtlMs:s.policy?.generationTtlMs??yi,budgetBytes:s.policy?.budgetBytes??Si}}),d=0,h=0;for(let f of u.deleteWorktrees){if(!Fe(f.lease))continue;if(!se(f.lease.localCacheDir)){G(f.leasePath,{force:!0}),h+=1;continue}if(!ki(f.lease))continue;let y=ye(S(f.lease.localCacheDir,"cache-lifecycle.lock"));if(y)try{if(Ge(f.lease,!0))continue;try{Gt({projectRoot:f.lease.projectRoot,cacheDir:f.lease.localCacheDir,cliVersion:i})}catch{continue}if(Ge(f.lease,!0))continue;G(f.lease.localCacheDir,{recursive:!0,force:!0}),G(f.leasePath,{force:!0}),h+=1}finally{y.release()}}for(let f of u.deleteLocks)G(f.path,{force:!0});for(let f of u.deleteTemporaries)G(f.path,{recursive:!0,force:!0});for(let f of u.deleteGenerations)G(f.path,{recursive:!0,force:!0}),d+=f.size;ht(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},g={version:1,lastSweepAt:p.sweptAt,unreferencedSince:u.unreferencedSince,lastResult:p};return Re(a,g,{spacing:2,trailingNewline:!0}),p}catch(l){return{kind:"failed",error:l instanceof Error?l.message:String(l)}}finally{c.release()}}function xi(t,e,r,i,n){let s=S(O(),"repositories");if(!se(s))return;let a=S(s,Ri),o=Ci(a);if(!n.force&&o!==void 0&&i-o<oe)return;let c=ye(S(s,vi));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=H(u)}catch{continue}if(!d.isDirectory()||d.isSymbolicLink())continue;let h=Ti(u)??t;fr(h,u,l,r,i,n)}Re(a,{version:1,lastSweepAt:new Date(i).toISOString()},{spacing:2,trailingNewline:!0})}finally{c.release()}}function Ii(t,e,r,i){let n=new Set(at(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=mr(u);if(!d)continue;let h=z(d.projectRoot);s.push({leasePath:u,lease:d,managed:d.repositoryId===r&&Fe(d),live:n.has(h)||se(h),busy:Ge(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=De(d),p=h!==void 0&&W(h),g=u[1];a.push({generationId:g,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),g=Number(u[1]);try{c.push({path:p,size:dr(p),live:Number.isSafeInteger(g)&&W(g)})}catch{}continue}if(!/^[a-f0-9]{64}$/.test(l))continue;let d=S(e,"generations",l),h;try{h=H(d)}catch{continue}!h.isDirectory()||h.isSymbolicLink()||o.push({generationId:l,path:d,size:dr(d),...i[l]===void 0?{}:{unreferencedAt:i[l]}})}return{leases:s,generations:o,locks:a,temporaries:c}}function Fe(t){if(t.ownershipChecksum!==Rt(t)||q(t.localCacheDir)!==q(tt(t.projectRoot)))return!1;let e=q(S(O(),"projects"));return q(t.localCacheDir).startsWith(`${e}${hr}`)}function ki(t){if(!Fe(t))return!1;let e=z(O()),r=z(S(e,"projects")),i=z(t.localCacheDir);try{let n=H(e),s=H(r),a=H(i);if(!n.isDirectory()||n.isSymbolicLink()||!s.isDirectory()||s.isSymbolicLink()||!a.isDirectory()||a.isSymbolicLink())return!1;let o=lr(r);return lr(i).startsWith(`${o}${hr}`)}catch{return!1}}function Ti(t){for(let e of J(S(t,"worktrees"))){if(!e.endsWith(".json"))continue;let r=mr(S(t,"worktrees",e));if(r)return r.projectRoot}}function Ge(t,e=!1){for(let i of e?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let n=De(S(t.localCacheDir,i));if(n!==void 0&&W(n))return!0}let r=De(Q(t.localCacheDir).lockPath);return r!==void 0&&W(r)}function mr(t){try{let e=JSON.parse(v(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 De(t){try{let e=JSON.parse(v(t,"watch lock record"));return typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0?e.pid:void 0}catch{return}}function Pi(t){try{let e=JSON.parse(v(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 Ci(t){try{let e=JSON.parse(v(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 ur(t)}catch{return[]}}function dr(t){let e=0,r=[t];for(;r.length>0;){let i=r.pop();for(let n of ur(i,{withFileTypes:!0})){let s=S(i,n.name);n.isDirectory()?r.push(s):n.isFile()&&(e+=gi(s).size)}}return e}var ae=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=Ce(e)}initializeAfterOwnershipAcquired(){let e=Lt(this.root),r=_t(this.root,{now:()=>new Date(this.now())});return this.refreshStatus(),{recoveredClaims:e,prunedHistory:r}}observeLegacyRequest(e,r){Mt(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=Wt(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(Ei(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?(At(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=Ce(this.root)}};function Ei(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{totalmem as Wi}from"os";import{randomUUID as Ai}from"crypto";import{rmSync as Li}from"fs";import{Worker as _i}from"worker_threads";var ce=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(Oe(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(Ne(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=Mi(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(Oe(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: ${Ne(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(Oe(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: ${Ne(i)}`,{cause:i})),!1}finally{r===this.workerGeneration&&(this.terminating=null)}})(),this.terminating}};function Mi(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 Oe(t){return t instanceof Error?t:new Error(String(t))}function Ne(t){return t instanceof Error?t.message:String(t)}var ji=6e4,Gi=10*6e4;function gr(t){let e=t.maxActiveSessions??8,r=t.workerSoftMemoryMb??wr(t.workerHeapMb),i=()=>({protocolVersion:Y,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 Sr({name:"TypeScript index",paths:t.paths,now:t.now,limits:t.limits,initialStatus:i,parseEnvelope:It,createWorker:()=>xr(t,{kind:"index",projectRoot:t.projectRoot,dbPath:t.dbPath,maxActiveSessions:e,softMemoryLimitMb:r}),complete(n,s,a,o){we(t.paths,n,{ok:!0,protocolVersion:Y,id:s.id,baseGeneration:s.baseGeneration,response:a},{nowMs:o,limits:t.limits})},reject(n,s,a,o){xe(t.paths,n,{ok:!1,protocolVersion:Y,id:s,error:a},a,{nowMs:o,limits:t.limits})},idleTtlMs:t.workerIdleMs??Gi,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 yr(t){let e=t.workerSoftMemoryMb??wr(t.workerHeapMb),r=()=>({protocolVersion:ee,state:"idle",requests:0,sessionsCreated:0,sessionsReused:0,sessionsRefreshed:0,sessionsReplaced:0,projectsCreated:0,softMemoryLimitBytes:e*1024*1024,retireRequested:!1});return Sr({name:"TypeScript semantic",paths:t.paths,now:t.now,limits:t.limits,initialStatus:r,parseEnvelope:Et,createWorker:()=>xr(t,{kind:"semantic",projectRoot:t.projectRoot,softMemoryLimitMb:e}),complete(i,n,s,a){we(t.paths,i,{ok:!0,protocolVersion:ee,id:n.id,generation:n.generation,response:s},{nowMs:a,limits:t.limits})},reject(i,n,s,a){xe(t.paths,i,{ok:!1,protocolVersion:ee,id:n,error:s},s,{nowMs:a,limits:t.limits})},idleTtlMs:ji,maxWorkerFailureRetries:1,retireAfterResponse:i=>i.retireRequested===!0,statusWhenWorkerAbsent:i=>({...i,state:"idle",heapUsedBytes:0,retireRequested:!1}),onBusy:t.onBusy,onFatal:t.onFatal})}function Sr(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}-${Ai()}`,s={...t.limits,maxBatch:1},a=null,o=t.initialStatus(),c=!1,l=p=>{c=!0,t.onFatal(p)},u=new ce({name:t.name,createWorker:t.createWorker,now:e,idleTtlMs:t.idleTtlMs,maxWorkerFailureRetries:t.maxWorkerFailureRetries,retireAfterResponse:t.retireAfterResponse,onComplete(p,g,f){let y=d(p.requestId);o=f;let I=e();try{t.complete(y.claim,y.envelope,g,I)}catch(k){if(!(k instanceof ve))throw k;try{t.reject(y.claim,y.envelope.id,k.message,I)}catch(T){if(!(T instanceof ve))throw T;Li(y.claim.path,{force:!0})}}h(y)},onReject(p,g,f){let y=d(p.requestId);f!==void 0&&(o=f),t.reject(y.claim,y.envelope.id,g,e()),h(y)},onStatus(p){o=p},onFatal:l});return{poll(){if(c||!u.canAccept())return 0;let p=vt(t.paths,{ownerId:n,nowMs:e(),limits:s,owner:i,liveness:{isProcessAlive:W,readProcessIdentity:P}})[0];if(!p)return 0;let g=p.requestId;try{let f=t.parseEnvelope(bt(p,s));if(g=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=qi(f);try{t.reject(p,g,y,e()),a?.claim===p&&h(a)}catch(I){l(Ni(I))}}return 1},status(){return{...u.hasWorker()||!t.statusWhenWorkerAbsent?o:t.statusWhenWorkerAbsent(o),mailbox:wt(t.paths)}},async close(p){await u.close(p)}};function d(p){let g=a;if(!g||g.envelope.id!==p)throw new Error(`${t.name} parent lost the active mailbox claim.`);return g}function h(p){a===p&&(a=null,t.onBusy?.(void 0))}}var Rr=6144;function vr(){let t=Number.parseInt(process.env.SCIP_TS_WORKER_HEAP_MB??"",10);return Number.isFinite(t)&&t>0?t:Rr}var Di=.6;function br(t,e=Fi()){let r=Number.parseInt(process.env.SCIP_TS_WORKER_HEAP_MB??"",10);if(Number.isFinite(r)&&r>0)return r;let i=Math.ceil(pt+t*ft),n=Math.floor(e*Di/(1024*1024));return Math.max(Rr,Math.min(i,n))}function Fi(t=Oi,e=Wi()){let r=[t("/sys/fs/cgroup/memory.max"),t("/sys/fs/cgroup/memory/memory.limit_in_bytes")].map(i=>i===null?Number.NaN:Number.parseInt(i.trim(),10)).filter(i=>Number.isFinite(i)&&i>0&&i<e);return r.length>0?Math.min(...r):e}function Oi(t){try{return Ve(t,{maxBytes:Je,inputKind:"cgroup memory limit"})}catch{return null}}function wr(t){return Math.max(1,Math.floor((t??vr())*.9))}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 _i(r,{workerData:e,resourceLimits:{maxOldGenerationSizeMb:t.workerHeapMb??vr()}})}function Ni(t){return t instanceof Error?t:new Error(String(t))}function qi(t){return t instanceof Error?t.message:String(t)}var kr=2e3,Hi=5e3,zi=5e3,Ji=6e4,Vi=10,Ki=50,Xi=1e4;function Yi(t,e=1){return Ze(t,e,Vi,Ki,Xi,8)}function Qi(t,e){let r;return{begin(){return r||(e.requestStop(),e.closeWake(),r=t.stop(),r.catch(()=>{})),r}}}async function Zi(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=Yi(n,s);return await e.wait(a),{indexRequests:r,semanticRequests:i,processedRequests:n,consecutiveIdlePolls:s,stopped:!1,delayMs:a}}function en(t){return t==="fresh"?null:{kind:"watch-startup",detail:`index ${t} when watch service started`}}function tn(t){Dt(t.statePath,{version:1,protocolVersion:kt,pid:R.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 rn(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=C();if(o-i>=zi&&(i=o,!$t(t.worktreeLiveness))){t.requestStop();return}if(o-s>=Ji&&(s=o,Ie(t.indexMailboxPaths),Ie(t.semanticMailboxPaths)),o-n>=oe&&(n=o,pr(t.projectRoot,t.cliVersion)),o-r>=Hi){r=o;let c=Ft(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 nn(t){let e,r=0,i=!1,n,s;R.once("SIGINT",t.stopSignal),R.once("SIGTERM",t.stopSignal);try{t.watcher.start();let o=t.initializeFreshness();for(t.recordActivity(),t.markReady(),t.persistState(!0),e=setInterval(()=>t.persistState(),kr),e.unref?.(),o&&t.requestRefresh(o);!t.stopRequested();){let c=await Zi(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{R.off("SIGINT",t.stopSignal),R.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 sn(t){try{let e=new Bi(t,{readonly:!0,fileMustExist:!0});try{return e.prepare("SELECT count(*) AS documents FROM documents").get().documents}finally{e.close()}}catch{return 0}}function on(t){let e=t.config.indexer?.typescript,r=e?.workerHeapMb??br(sn(t.dbPath)),i=yr({paths:t.semanticPaths,projectRoot:t.projectRoot,workerHeapMb:r,onBusy:t.onSemanticBusy,onFatal:t.onFatal}),n=gr({paths:t.indexPaths,projectRoot:t.projectRoot,dbPath:t.dbPath,...e?.maxWarmSessions===void 0?{}:{maxActiveSessions:e.maxWarmSessions},...e?.workerIdleMs===void 0?{}:{workerIdleMs:e.workerIdleMs},...e?.workerSoftMemoryMb===void 0?{}:{workerSoftMemoryMb:e.workerSoftMemoryMb},workerHeapMb:r,onBusy:t.onIndexBusy,onFatal:t.onFatal});return{semanticLane:i,indexLane:n}}async function an(t,e,r={}){let i=jt(t,e),n=i.projectRoot,s=i.worktreeKind==="git"?cn(n,i.worktreeId):void 0,a=Bt(n,s),o=B(n);o.watch={...o.watch,...r};let c=Z(o);if(!c.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let l=N(n,o),u=Q(l.cacheDir),d=P(R.pid),h=Ot(u.lockPath,n,{readProcessIdentity:m=>m===R.pid?d:P(m)});if(!h.acquired)return;let p=new ae(u.refreshRequestsPath,{retryDelayMs:Math.max(1e3,c.cooldownMs)});p.initializeAfterOwnershipAcquired();let g=Date.now(),f=C(),y=g,I=f,k={state:"idle"},T,le,E,de,ue=X(l.dbPath),V=!1,qe=!1,Be=Number.NEGATIVE_INFINITY,$e,Ue,D=Ct(l.cacheDir),F=xt(l.cacheDir);be(D),be(F);let He=Te([F.pendingDir,F.legacyRequestDir,D.pendingDir,D.legacyRequestDir,u.refreshRequestsPath]),w=(m=!1,M=m?"durable":"visibility")=>{if(!qe)return;let fe=Date.now(),L=C();!m&&L-Be<kr||(Be=L,tn({statePath:u.statePath,durability:M,processIdentity:d,projectRoot:n,worktreeId:i.worktreeId,cliVersion:e,startedAtMs:g,nowMs:fe,lastActivityAtMs:y,idleTimeoutMs:c.idleTimeoutMs,watcherStatus:k,indexGeneration:T,lastRefresh:le,lastError:E,reindexActivity:ue,refreshCoordinator:p,semanticLane:he,indexLane:pe,semanticBusyUntilMs:$e,indexBusyUntilMs:Ue}))},A=()=>{y=Date.now(),I=C()},Tr=m=>{A(),de??=m,E={at:new Date().toISOString(),message:m.message},w(!0,"visibility")},{semanticLane:he,indexLane:pe}=on({semanticPaths:D,indexPaths:F,projectRoot:n,dbPath:l.dbPath,config:o,onSemanticBusy(m){$e=m===void 0?void 0:m+5e3,w(!0,"visibility")},onIndexBusy(m){Ue=m===void 0?void 0:m+5e3,w(!0,"visibility")},onFatal:Tr}),K=new ne({projectRoot:n,config:{...o,watch:c},outputDb:l.dbPath,languages:o.languages,onStatus(m){k=m,m.state!=="idle"&&(T=void 0),m.state!=="idle"&&A(),w(!0)},onReindexComplete(m,M,fe){A();let L=fe?.pendingChanges!==!1?$(n,o,l):Pt(l);return le=L.lastRefresh,T=L.state==="fresh"?_(l.dbPath)??void 0:void 0,ue=X(l.dbPath),p.completeActive(),E=void 0,w(!0),L.state==="fresh"},onReindexError(){p.failActive()},onRefreshSuppressed(m){let M=yt(l.dbPath,m);M.state==="failed"&&(E={at:new Date().toISOString(),message:`Suppressed-refresh telemetry was not recorded: ${M.reason}`},w(!0,"visibility")),ue=X(l.dbPath)},onError(m){A(),T=void 0,E={at:new Date().toISOString(),message:m.message},w(!0)}}),ze=Qi(K,{requestStop(){V=!0},closeWake(){He.close()}}),Pr=()=>{ze.begin()},Cr=rn({worktreeLiveness:a,indexMailboxPaths:F,semanticMailboxPaths:D,projectRoot:n,cliVersion:e,activityPath:u.activityPath,refreshCoordinator:p,watcherStatus:()=>k,requestRefresh:m=>K.requestRefresh({kind:"watch-demand",detail:m},{immediate:!0}),requestStop:()=>{V=!0},recordActivity:A,updateObservedActivity(m,M){m<=y||(y=m,I=M)},persistState:w});await nn({watcher:K,shutdown:ze,stopSignal:Pr,initializeFreshness(){let m=$(n,o,l);return le=m.lastRefresh,T=m.state==="fresh"?_(l.dbPath)??void 0:void 0,en(m.state)},markReady:()=>{qe=!0},recordActivity:A,persistState:w,requestRefresh:m=>K.requestRefresh(m,{immediate:!0}),stopRequested:()=>V,processIndexRequests:()=>pe.poll(),processSemanticRequests:()=>he.poll(),afterMailboxPoll:Cr,shouldStop:()=>V||de!==void 0||Nt({watcher:k,lastActivityAtMs:I,nowMs:C(),idleTimeoutMs:c.idleTimeoutMs}),wait:m=>He.wait(m),closeLanes:()=>Promise.all([he.close("TypeScript semantic service stopped before completing the request."),pe.close("TypeScript index service stopped before completing the request.")]).then(()=>{}),mailboxFatalError:()=>de,finalizeStopped(){Ir(u.statePath,{force:!0}),Ir(u.activityPath,{force:!0}),h.release()},finalizeDegraded(m){return E={at:new Date().toISOString(),message:`Watch service shutdown is degraded: ${m.join("; ")}`},w(!0),new Error(E.message)}})}function cn(t,e){let r=ot(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 ln(t,e={report:r=>console.error(r),exit:r=>R.exit(r)}){return e.report(`watch-service: ${Tt(t instanceof Error?t.message:String(t))}`),e.exit(1)}var dn=R.argv[1]?Ui($i(R.argv[1])).href:null;if(dn===import.meta.url){let t=R.argv[2],e=R.argv[3],r=un(R.argv[4]);if(!t||!e)console.error("watch-service: expected <project-root> <cli-version>"),R.exitCode=1;else try{await an(t,e,r)}catch(i){ln(i)}}function un(t){if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}}export{Te as createPathChangeWake,Qi as createWatchServiceShutdown,Zi as runWatchServiceLoopIteration,an as runWatchServiceServer,en as startupRefreshTrigger,ln as terminateWatchServiceProcess,Yi as watchServiceLoopDelayMs};
4
4
  //# sourceMappingURL=watch-server.js.map
@@ -208,7 +208,7 @@ An unavailable frontier is a relationship class for which no registered analyzer
208
208
  | `vue-composable-candidates [file]` | Find heuristic Vue composable extraction candidates from shared state, effects, requests, and template bindings | variable | `inspect`, `code` | `--min-similarity <n>`<br>`--min-shared-behaviors <n>`<br>`-n, --limit <n>`<br>`-s, --scope <path>`<br>`--full`<br>`--json`<br>`--result-only`<br>`--compact` |
209
209
  | `vue-large-view-pressure [file]` | Find heuristic large Vue view pressure candidates from template, script, style, and external script line counts | variable | `inspect`, `code` | `--min-total-lines <n>`<br>`--min-template-lines <n>`<br>`--min-script-lines <n>`<br>`--min-style-lines <n>`<br>`--review-thresholds`<br>`-n, --limit <n>`<br>`-s, --scope <path>`<br>`--full`<br>`--json`<br>`--result-only`<br>`--compact` |
210
210
  | `similar-chains` | Find heuristic similar-chain candidates from dependency flows | variable | `inspect`, `code` | `--min-similarity <n>`<br>`-n, --limit <n>`<br>`-s, --scope <path>`<br>`--min-length <n>`<br>`--max-length <n>`<br>`--full`<br>`--json`<br>`--result-only`<br>`--compact` |
211
- | `extract-candidates` | Find heuristic extraction candidates from isolated callee clusters | variable | `inspect`, `code` | `-s, --scope <path>`<br>`--min-loc <n>`<br>`--min-callees <n>`<br>`-n, --limit <n>`<br>`--full`<br>`--json`<br>`--result-only`<br>`--compact` |
211
+ | `extract-candidates` | Find extraction candidates: contiguous regions whose callees are used nowhere else in the function | variable | `inspect`, `code` | `-s, --scope <path>`<br>`--min-loc <n>`<br>`--min-callees <n>`<br>`-n, --limit <n>`<br>`--full`<br>`--json`<br>`--result-only`<br>`--compact` |
212
212
  | `locality-candidates [symbol-or-file]` | Find directory-locality and ancestry candidates from consumer ownership | variable | `inspect`, `code` | `-s, --scope <path>`<br>`--min-consumers <n>`<br>`-n, --limit <n>`<br>`--full`<br>`--json`<br>`--result-only`<br>`--compact` |
213
213
  | `cleanup-plan` | Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks | variable | `inspect`, `code` | `-s, --scope <path>`<br>`--min-loc <n>`<br>`--max-depth <n>`<br>`--verify`<br>`--patch`<br>`--full`<br>`--json`<br>`--result-only`<br>`--compact` |
214
214
  | `recent-duplicates` | Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code | variable | `inspect`, `code` | `--window <n>`<br>`--min-similarity <n>`<br>`-n, --limit <n>`<br>`-s, --scope <path>`<br>`--full`<br>`--json`<br>`--result-only`<br>`--compact` |
@@ -278,7 +278,7 @@ An unavailable frontier is a relationship class for which no registered analyzer
278
278
 
279
279
  | Command | Description | Cost | Closes disclosed gaps with | Options |
280
280
  |---|---|---|---|---|
281
- | `install-skills` | Install skills (scip-query, scip-explore, scip-plan, scip-setup, scip-integrity-audit) into Claude Code, Codex, and shared agent roots | variable | - | - |
281
+ | `install-skills` | Install skills (scip-query, scip-explore, scip-plan, scip-setup, scip-integrity-audit, principal-maintainability-review, scip-system-compression, scip-root-cause, scip-claim-audit, scip-probe-reachability, scip-twin-drift, scip-calibrate, conductor) into Claude Code, Codex, and shared agent roots | variable | - | - |
282
282
  | `check-deps` | Check whether scip-query and the detected language indexers are runnable | bounded | `inspect`, `code` | - |
283
283
  | `capabilities` | Report which mapping and analysis capabilities are available in this project | bounded | `inspect`, `code` | `--matrix`<br>`--json`<br>`--result-only`<br>`--compact` |
284
284
  | `init` | Create a .scipquery.json configuration file for this project | variable | - | - |
@@ -13,21 +13,27 @@ scip-query health --full
13
13
 
14
14
  The health report combines graph structure, duplication, drift, complexity,
15
15
  history, suppressions, coverage contracts, and React and Vue analyses. Its
16
- score is a summary, not proof of correctness.
16
+ score is a summary, not proof of correctness. The `Input:` line under the
17
+ file and symbol counts names the index generation and the git commit,
18
+ branch, and uncommitted-path count the report was computed from
19
+ (`provenance` in `health --json`); compare two reports only when that line
20
+ matches, because a repository change and a detector change move the same
21
+ numbers.
17
22
 
18
23
  ## Focused detector families
19
24
 
20
- | Concern | Commands |
21
- | --- | --- |
22
- | Exact or near duplication | `duplicate-bodies`, `similar`, `recent-duplicates` |
23
- | Parallel implementations | `twin-drift`, `incomplete-migration`, `drift` |
24
- | Unused or disconnected code | `dead`, `isolated`, `unused-params` |
25
- | Excess indirection | `wrapper-candidates`, `passthrough-candidates`, `stale-abstractions`, `redundant-reexports` |
26
- | Change pressure | `complexity-hotspots`, `co-change`, `cycles` |
27
- | Documentation | `doc-drift` |
28
- | React | `react-component-duplicates`, `react-hook-candidates`, `react-large-component-pressure` |
29
- | Vue | `vue-component-duplicates`, `vue-composable-candidates`, `vue-large-view-pressure` |
30
- | Team structure policy | `architecture` |
25
+ | Concern | Commands |
26
+ | --------------------------- | ------------------------------------------------------------------------------------------- |
27
+ | Exact or near duplication | `duplicate-bodies`, `similar`, `recent-duplicates` |
28
+ | Parallel implementations | `twin-drift`, `incomplete-migration`, `drift` |
29
+ | Unused or disconnected code | `dead`, `isolated`, `unused-params` |
30
+ | Excess indirection | `wrapper-candidates`, `passthrough-candidates`, `stale-abstractions`, `redundant-reexports` |
31
+ | Extraction seams | `extract-candidates` |
32
+ | Change pressure | `complexity-hotspots`, `co-change`, `cycles` |
33
+ | Documentation | `doc-drift` |
34
+ | React | `react-component-duplicates`, `react-hook-candidates`, `react-large-component-pressure` |
35
+ | Vue | `vue-component-duplicates`, `vue-composable-candidates`, `vue-large-view-pressure` |
36
+ | Team structure policy | `architecture` |
31
37
 
32
38
  Run focused commands through the `scip-query` CLI. Add `--full` only when that
33
39
  command supports it and exhaustive command coverage can change the decision.
@@ -44,3 +50,36 @@ command supports it and exhaustive command coverage can change the decision.
44
50
  Suppress a false or accepted finding with `scip-query suppress <id>` and a
45
51
  specific reason. A suppression addresses one finding; it must not disable an
46
52
  unrelated detector family.
53
+
54
+ ## Policy exclusions
55
+
56
+ Some rows match a detector's pattern because a convention demands the
57
+ match, not because anyone copied or wrapped anything. Detectors remove those
58
+ rows from the counts `health` scores and disclose the removal instead of
59
+ hiding it, under `Policy exclusions` in the text report and `policyExclusions`
60
+ in `health --json`. An excluded row is still listed by its focused command
61
+ (often at support tier), so a reviewer who disagrees with the policy can
62
+ still find it.
63
+
64
+ | Detector | Excluded by policy |
65
+ | --------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
66
+ | `react-component-duplicates`, `react-hook-candidates`, `react-large-component-pressure` | components in test files; pairs of vendored UI-kit primitives (the shadcn `components.json` `aliases.ui` directory or a `components/ui` directory); hook-versus-component pairs; loading placeholders that share only a skeleton primitive |
67
+ | `react-component-duplicates` | two framework route entries whose JSX overlaps (support tier: routing scaffolding); shared _behavior_ between route entries still counts |
68
+ | `react-component-duplicates`, `react-hook-candidates` | an intercepting route and its target are kept, with the recommendation to render one shared view |
69
+ | `react-hook-candidates` | pairs whose overlap is only generic React or data-fetching mechanics (`useState`, `useMutation`, `.mutate()`, `useRouter`) |
70
+ | `wrapper-candidates` | constructors; single-consumer callables whose body is not exactly one call with plain-value arguments (a preparatory statement, a callback, a nested call, or a literal the body builds makes it `bodyShape: helper`, signal tier) |
71
+ | `duplicate-bodies` | duplicate members that are constructors, test-file bodies, route-file verb exports, or vendored UI-kit bodies; a group must keep two product files to count |
72
+ | `dead` | zero-reference symbols in framework entry surfaces (route handlers, pages, Trigger.dev task directories from `trigger.config.*`, live barrels) and in generated artifacts (`drizzle-kit pull` dumps, migration snapshots, codegen output) |
73
+ | `dead` | exports of source files a root configuration names by path (`next.config.js` `images.loaderFile`, `package.json` scripts) |
74
+ | `twin-drift` | route-file convention names (`handler`, `handleGet`, `*Page`, `generateMetadata`) inside framework entry files |
75
+ | `twin-drift` | CRUD and lifecycle method names (`create`, `delete`, `getById`, `shutdown`, ...) declared directly on unrelated classes; free functions with those names keep the ordinary rules |
76
+ | `twin-drift` | a member that calls its same-name counterpart, directly or under an import alias (an operations function over its use-case, a component over the function it renders): a layer, not a parallel implementation |
77
+ | `twin-drift` | a thin forwarder whose single call is named differently from itself (a web API client, a vendor adapter) is a stub over its peer's concept; overrides of one abstract member; key-qualified lookup members (`getBySlug`, `findByEmail`) on unrelated classes |
78
+ | `passthrough-candidates` | a file with three or more methods forwarding to the same collaborator is a facade; its forwards become boundary signals instead of direct inline advice |
79
+ | `wrapper-candidates`, `passthrough-candidates` | boundary terms are read from leaf names, and a term both sides carry (`toBaseRate` forwarding to `parseBaseRate`; a wrapper and its caller both under `lib/auth/`) is shared vocabulary, not a boundary; only asymmetric terms demote a finding to signal tier |
80
+ | `passthrough-candidates` | a class whose methods forward to members of three or more collaborators is a composed-service facade; a curried handler (`return jsonHandler(async () => {...})(req, res, next)`) is not a literal forward |
81
+ | `wrapper-candidates` | a forward through a module-private variable (`return loadedLanguages.has(lang)`) is a boundary signal because inlining would export the state |
82
+ | `co-change` (hidden coupling) | documentation that changes alongside the code it describes (`doc-drift` owns stale docs); generated artifacts such as migration journals, snapshots, and codegen output |
83
+ | `co-change` | pairs whose shared commits were only broad sweeps, stale pairs with at most two focused co-changes, and configuration or schema partners (signal tier; listed by co-change) |
84
+ | `complexity-hotspots` (extreme count) | callables above the extreme score only through fan-in, with fewer than 10 branches |
85
+ | `extract-candidates` | regions whose extraction would take more than five locals in or hand more than two back (support tier: wide interface); only regions with a narrow or unknown interface count |
@@ -42,6 +42,29 @@ The certification thresholds and publication rules live in
42
42
  Program closure and the private-shadow decision live in
43
43
  [`2026-07-11-accuracy-program-closure.md`](./validation/2026-07-11-accuracy-program-closure.md).
44
44
 
45
+ ## 2026-09-02 TypeScript label review
46
+
47
+ The matrix below is the 2026-07-10 snapshot. On 2026-09-02 the TypeScript
48
+ detectors that feed the health report were re-audited against reviewed
49
+ label sets (`docs/validation/labels/<repository>/<detector>.json`, scored by
50
+ `scripts/score-detector-labels.ts`). Each row names the repository, the
51
+ sample, and the result after that day's fixes; the truth rules are in the
52
+ label files' notes.
53
+
54
+ | Detector | Repository | Sample | Precision / recall of labeled rows | Notes |
55
+ | ----------------------------------------------------- | ----------------- | -------------------------- | -------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
56
+ | `dead` | Launchpoint | 20 of 65 dead-code rows | 0.95 / 1.0, then 1.0 after the config-referenced entry surface | word search outside the defining file as the truth rule |
57
+ | `similar` | Launchpoint | 20 pairs | 1.0 / 0.43 | four true pairs sit at signal tier by the earlier scaffolding calibration |
58
+ | `stale-abstractions` | Launchpoint | 5 direct, 10 signal | 1.0 / 1.0 | signal rows are counted findings (`countedTiers`) |
59
+ | `complexity-hotspots` | Launchpoint | 20 of the 192 extreme rows | 1.0 / 1.0 | text recount of branch tokens agrees |
60
+ | `react-large-component-pressure` | Launchpoint | 20 components | 1.0 / 1.0 | two static templates labeled uncertain |
61
+ | `co-change` | Launchpoint | 20 non-doc pairs | 0.53 before the signal tier | sweep-only, stale, and configuration pairs are signal tier and not counted |
62
+ | `extract-candidates` | Launchpoint, Vega | 20 each | 1.0 / 1.0; 0.875 / 0.54 | Vega misses are wide-interface support rows; element-boundary snapping added |
63
+ | `wrapper-candidates` | Launchpoint, Vega | 20 each | direct tier 0 false; 1.0 / 1.0 | forwarding shape, owner-qualified boundary names, module-private state |
64
+ | `passthrough-candidates` | Launchpoint, Vega | 20 each | 1.0 / 1.0; 1.0 / 1.0 | shared vocabulary, composed-service facades, curried handlers |
65
+ | `twin-drift` | Launchpoint, Vega | 20 groups each | 0.77 / 1.0; 0.83 / 0.71 | layering, stubs, overrides, key-qualified lookups, near-name suffix words |
66
+ | `react-component-duplicates`, `react-hook-candidates` | Launchpoint | full-list review (morning) | see the calibration document | policy exclusions for generic mechanics, hook/component pairs, vendored primitives |
67
+
45
68
  ## Certification Matrix
46
69
 
47
70
  Legend: `certified`, `qualified`, `experimental`, `insufficient`, `unsupported`,
@@ -97,8 +120,8 @@ state. A checked box does not upgrade an `insufficient` state to `certified`.
97
120
 
98
121
  - [x] `unused-imports` — certified
99
122
  - [x] `unused-params` — insufficient population evidence
100
- - [x] `cycles` — insufficient population evidence
101
- - [x] `duplicate-bodies` — certified
123
+ - [x] `cycles` — insufficient population evidence (2026-09-02: consistent across generations; the Launchpoint change was the repository removing its cycles)
124
+ - [x] `duplicate-bodies` — certified (2026-09-02: constructors, test bodies, route verb exports, and UI-kit bodies removed before grouping)
102
125
  - [x] `complexity` — certified
103
126
  - [x] `isolated` — insufficient population evidence
104
127
  - [x] `redundant-reexports` — certified
@@ -151,8 +174,8 @@ certificate:
151
174
  - [x] `similar-files` — certified relationship
152
175
  - [x] `similar-chains` — qualified within a bounded candidate frame
153
176
  - [x] `similar-signatures` — certified relationship
154
- - [x] `twin-drift` — qualified; 37/40 valid
155
- - [x] `react-component-duplicates` — certified relationship
177
+ - [x] `twin-drift` — qualified; 37/40 valid (2026-09-02: route-convention and CRUD/lifecycle member names excluded; no reviewed precision sample yet)
178
+ - [x] `react-component-duplicates` — certified relationship (2026-09-02: test-file, UI-kit, route-scaffolding, and hook-versus-component policies; Launchpoint label set precision 1.0 / recall 1.0)
156
179
  - [x] `vue-component-duplicates` — certified relationship
157
180
  - [x] `convergence` alias parity with `similar --plan`
158
181
  - [x] `twin-ab` — certified generated-scaffold correctness for importable named
@@ -164,18 +187,18 @@ consolidation would improve the code.
164
187
 
165
188
  ## Architecture and Refactoring Signals
166
189
 
167
- - [x] `wrapper-candidates` — certified production single-caller relationship
168
- - [x] `passthrough-candidates` — certified literal-forwarding relationship
190
+ - [x] `wrapper-candidates` — certified production single-caller relationship (2026-09-02: constructors excluded, body shape distinguishes forwarders from helpers; no reviewed precision sample yet)
191
+ - [x] `passthrough-candidates` — certified literal-forwarding relationship (2026-09-02: facade files (three or more forwards to one collaborator) become boundary signals; no reviewed precision sample yet)
169
192
  - [x] `stale-abstractions` — certified relationship
170
- - [x] `extract-candidates` — certified measurement; extraction remains contextual
193
+ - [x] `extract-candidates` — certified measurement; extraction remains contextual. Rebuilt 2026-09-02 around exclusive line regions with compiler-known locals; the Python row above predates the rebuild, and the current reviewed sample is `docs/validation/labels/launchpoint-backend/extract-candidates.json`
171
194
  - [x] `locality-candidates` — certified relationship; movement remains contextual
172
195
  - [x] `drift` — qualified; subtype breadth incomplete
173
- - [x] `co-change` — certified relationship
196
+ - [x] `co-change` — certified relationship (2026-09-02: doc-code and generated-artifact partners weight zero)
174
197
  - [x] `doc-drift` — certified relationship
175
198
  - [x] `coupling` — certified graph fact
176
199
  - [x] `bottlenecks` — certified disclosed graph fact; utility remains contextual
177
200
  - [x] `deep-chains` — certified condensed-component path
178
- - [x] `complexity-hotspots` — certified measurement
201
+ - [x] `complexity-hotspots` — certified measurement (2026-09-02: rendered children count as fan-out; extreme requires ten branches; pressure threshold scales with file count)
179
202
  - [x] `hotspots` — certified graph fact
180
203
  - [x] `fan-in` — certified exact-symbol graph fact
181
204
  - [x] `fan-out` — certified graph fact
@@ -185,9 +208,9 @@ action. A real relationship can still be an unhelpful recommendation.
185
208
 
186
209
  ## React and Vue Signals
187
210
 
188
- - [x] `react-component-duplicates` — 48/48, certified relationship
189
- - [x] `react-hook-candidates` — 48/48, certified relationship
190
- - [x] `react-large-component-pressure` — 48/48, certified measurement
211
+ - [x] `react-component-duplicates` — 48/48, certified relationship (2026-09-02: test-file, UI-kit, route-scaffolding, and hook-versus-component policies; Launchpoint label set precision 1.0 / recall 1.0)
212
+ - [x] `react-hook-candidates` — 48/48, certified relationship (2026-09-02: generic-mechanics and shared-hook policies; Launchpoint label set precision 1.0 / recall 1.0)
213
+ - [x] `react-large-component-pressure` — 48/48, certified measurement (2026-09-02: UI-kit directories excluded; token axes gated by size)
191
214
  - [x] `vue-component-duplicates` — 41/41, certified relationship
192
215
  - [x] `vue-composable-candidates` — 48/48, certified relationship
193
216
  - [x] `vue-large-view-pressure` — 64/64, certified measurement
@@ -218,7 +241,7 @@ was not independently actionable without local design context.
218
241
  - [x] `new-dead` — qualified candidate with unconfirmed tier
219
242
  - [x] `baseline` — qualified exact set difference
220
243
  - [x] `health` — experimental composite; private shadow only
221
- - [x] `self-audit` — qualified; partial oracles withhold precision
244
+ - [x] `self-audit` — qualified; partial oracles withhold precision (2026-09-02: renders question, per-symbol complete oracle, callee precision measured (Vega 1.0 / Launchpoint 0.988))
222
245
  - [x] `effectiveness` — qualified ledger-transition facts
223
246
  - [x] `affected` — qualified indexed closure
224
247
  - [x] `change-surface` — qualified indexed consumer counts