scip-query 0.23.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 (432) hide show
  1. package/CHANGELOG.md +244 -1
  2. package/README.md +2 -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-WIWY3CRX.js → chunk-2GJSD5GY.js} +2 -2
  9. package/dist/{chunk-W5OXRYGE.js → chunk-2M2LSIMY.js} +3 -3
  10. package/dist/{chunk-2LDBDR6J.js → chunk-2N6WBNDC.js} +2 -2
  11. package/dist/{chunk-HOENASQM.js → chunk-2USA3S3P.js} +2 -2
  12. package/dist/chunk-2VAHDDLM.js +133 -0
  13. package/dist/chunk-2XWIUW5Z.js +455 -0
  14. package/dist/chunk-3D4BOXW6.js +20 -0
  15. package/dist/{chunk-BBCIS4DX.js → chunk-3LO4FST5.js} +2 -2
  16. package/dist/chunk-3WTY4LP2.js +3 -0
  17. package/dist/{chunk-UXW33INU.js → chunk-3Z5AMSK6.js} +2 -2
  18. package/dist/{chunk-4ILJCCXV.js → chunk-44IETFOU.js} +2 -2
  19. package/dist/chunk-4FR6GQIT.js +2 -0
  20. package/dist/chunk-4KBTHJLP.js +2 -0
  21. package/dist/{chunk-SSK6LDPC.js → chunk-5BIKR67W.js} +2 -2
  22. package/dist/{chunk-IHGQTTVW.js → chunk-5PROPLHI.js} +2 -2
  23. package/dist/{chunk-TA3QKLLU.js → chunk-5V7EPTII.js} +2 -2
  24. package/dist/{chunk-JS4PGXMV.js → chunk-62LPZCBQ.js} +2 -2
  25. package/dist/{chunk-DBRSYFXR.js → chunk-64O2JHQA.js} +2 -2
  26. package/dist/chunk-6D4F5VWG.js +10 -0
  27. package/dist/{chunk-BHVUJOCQ.js → chunk-6ERFBC3X.js} +2 -2
  28. package/dist/{chunk-ILTDAWEF.js → chunk-6ILKOOGH.js} +2 -2
  29. package/dist/chunk-6MFXCMZC.js +2 -0
  30. package/dist/chunk-6O7FACKB.js +2 -0
  31. package/dist/{chunk-XDQMU3BT.js → chunk-6TS3KOXR.js} +2 -2
  32. package/dist/{chunk-YI2AWIHC.js → chunk-76QOU4PK.js} +2 -2
  33. package/dist/{chunk-7CYG22FH.js → chunk-7DUI77BN.js} +2 -2
  34. package/dist/{chunk-IDFEUFKS.js → chunk-7F7T6DCR.js} +2 -2
  35. package/dist/chunk-7H6VHWWJ.js +2 -0
  36. package/dist/chunk-7HXT6YLU.js +5 -0
  37. package/dist/{chunk-DIRJWYBM.js → chunk-7R4V5ES6.js} +4 -4
  38. package/dist/{chunk-SZHGTCPP.js → chunk-7RIRIADH.js} +2 -2
  39. package/dist/chunk-7ZLWLOGT.js +2 -0
  40. package/dist/{chunk-M2O5NY6W.js → chunk-A4WEAK35.js} +2 -2
  41. package/dist/chunk-AADQLOQ4.js +38 -0
  42. package/dist/{chunk-OLNV6I6U.js → chunk-AN76MGUE.js} +2 -2
  43. package/dist/chunk-ANLNLY66.js +2 -0
  44. package/dist/chunk-ATXPTSEI.js +81 -0
  45. package/dist/{chunk-YPWBKGFU.js → chunk-AX7IDVFT.js} +2 -2
  46. package/dist/chunk-B7MPDEAK.js +3 -0
  47. package/dist/chunk-BBB5FBX4.js +2 -0
  48. package/dist/{chunk-6I6L7Z62.js → chunk-BHKK5RJY.js} +2 -2
  49. package/dist/chunk-BJWFVAA5.js +2 -0
  50. package/dist/{chunk-UHFYCMZO.js → chunk-BKZYTLGE.js} +2 -2
  51. package/dist/chunk-BL6DCHQP.js +2 -0
  52. package/dist/{chunk-TEBQMNVI.js → chunk-BOW7SSQH.js} +2 -2
  53. package/dist/{chunk-OWOOWNJ5.js → chunk-C4RHHCKL.js} +2 -2
  54. package/dist/{chunk-N2ZSIIGR.js → chunk-C7C6AKAT.js} +6 -6
  55. package/dist/chunk-CD6M6LS2.js +16 -0
  56. package/dist/chunk-CFE6PSG6.js +2 -0
  57. package/dist/{chunk-6V5CNXL6.js → chunk-CFNIGQMT.js} +2 -2
  58. package/dist/{chunk-GUFSG5TX.js → chunk-CKBUBRYD.js} +2 -2
  59. package/dist/{chunk-4WNW27SX.js → chunk-CZW5MZ5B.js} +2 -2
  60. package/dist/chunk-DBBZ63ZX.js +2 -0
  61. package/dist/{chunk-HCXEQRFF.js → chunk-DBN7DMJB.js} +2 -2
  62. package/dist/{chunk-6PQNKL3G.js → chunk-DUULLZHZ.js} +2 -2
  63. package/dist/{chunk-Z4CDXYNQ.js → chunk-DV5Y5NOS.js} +2 -2
  64. package/dist/chunk-DZOIKCTM.js +3 -0
  65. package/dist/chunk-E4PKTOL3.js +2 -0
  66. package/dist/{chunk-EG2CPZMJ.js → chunk-E65ELFKU.js} +2 -2
  67. package/dist/{chunk-CNO7TOKL.js → chunk-E7QR35ST.js} +2 -2
  68. package/dist/{chunk-3D3QG236.js → chunk-EFSXAINW.js} +2 -2
  69. package/dist/{chunk-IL676XCC.js → chunk-EHVEIEQN.js} +2 -2
  70. package/dist/{chunk-BE7ZZTMC.js → chunk-EHYDXE3Z.js} +2 -2
  71. package/dist/{chunk-LXABEJX3.js → chunk-EP63Y6LD.js} +2 -2
  72. package/dist/{chunk-QU5XRYB5.js → chunk-EPX6NQN6.js} +2 -2
  73. package/dist/{chunk-FESCRNVV.js → chunk-ETC674NS.js} +2 -2
  74. package/dist/{chunk-OSSESPDX.js → chunk-F5GSBHC6.js} +2 -2
  75. package/dist/chunk-FH3DGXC6.js +2 -0
  76. package/dist/{chunk-YEN6CYC7.js → chunk-FI7VGOR4.js} +2 -2
  77. package/dist/chunk-FJF6VO2P.js +2 -0
  78. package/dist/{chunk-FRUSVINH.js → chunk-FLMTCX5R.js} +2 -2
  79. package/dist/chunk-FVFDOIM3.js +2 -0
  80. package/dist/{chunk-PJFGPYTU.js → chunk-G2HU5WRN.js} +2 -2
  81. package/dist/{chunk-FIQRSHVM.js → chunk-G4ALYS4J.js} +2 -2
  82. package/dist/{chunk-UVGEWT4Y.js → chunk-G56I7K4W.js} +2 -2
  83. package/dist/{chunk-WOIKCX6A.js → chunk-GC4DG2V5.js} +2 -2
  84. package/dist/chunk-GG45PK4S.js +4 -0
  85. package/dist/{chunk-XBGWL66K.js → chunk-GHNPACNP.js} +2 -2
  86. package/dist/{chunk-IICPE7B2.js → chunk-GINH3YQU.js} +2 -2
  87. package/dist/{chunk-HLZTEXRA.js → chunk-GTZZVLKJ.js} +2 -2
  88. package/dist/chunk-GXXW5ZHH.js +2 -0
  89. package/dist/{chunk-B5D7QPBE.js → chunk-HAXXKRTD.js} +2 -2
  90. package/dist/chunk-HEZWBAZY.js +2 -0
  91. package/dist/chunk-HMEWLMML.js +2 -0
  92. package/dist/{chunk-QUU5OBVK.js → chunk-HOBOVYPO.js} +2 -2
  93. package/dist/{chunk-XGZEP6GR.js → chunk-HRFQ6GW5.js} +2 -2
  94. package/dist/{chunk-MPQ4OTBM.js → chunk-HX4X7KG3.js} +2 -2
  95. package/dist/{chunk-FDLOBR6P.js → chunk-HYT2R7LX.js} +2 -2
  96. package/dist/chunk-IKQVBVQL.js +40 -0
  97. package/dist/chunk-J6GLBBRK.js +4 -0
  98. package/dist/{chunk-ZTI4SBFV.js → chunk-J7A4PWFX.js} +2 -2
  99. package/dist/{chunk-OSR2GEHQ.js → chunk-JCSAZ35V.js} +2 -2
  100. package/dist/{chunk-ESIQ66Z7.js → chunk-JDU2IV3A.js} +2 -2
  101. package/dist/chunk-JFMI5SGB.js +4 -0
  102. package/dist/{chunk-W6STWDQI.js → chunk-JJP37RGX.js} +2 -2
  103. package/dist/chunk-JZ2A7LDM.js +5 -0
  104. package/dist/chunk-KNLQGXVH.js +80 -0
  105. package/dist/chunk-KVQCECPR.js +2 -0
  106. package/dist/{chunk-SQXRS7BG.js → chunk-KXXORBZ2.js} +2 -2
  107. package/dist/{chunk-DIUFNHRJ.js → chunk-L5KYH6U3.js} +2 -2
  108. package/dist/chunk-L6XHYJPZ.js +21 -0
  109. package/dist/{chunk-2GRUZAQF.js → chunk-L7KTFEAV.js} +2 -2
  110. package/dist/{chunk-QBE3YX64.js → chunk-LDXHR5EL.js} +2 -2
  111. package/dist/{chunk-HEHOQQKH.js → chunk-MHGDSBFX.js} +2 -2
  112. package/dist/{chunk-PWWAJSKV.js → chunk-MLQVVDG3.js} +2 -2
  113. package/dist/chunk-MOKUWRHO.js +3 -0
  114. package/dist/{chunk-VQILFTEH.js → chunk-MPYAPMNE.js} +2 -2
  115. package/dist/{chunk-UICY4GTQ.js → chunk-MV6SPXCR.js} +2 -2
  116. package/dist/{chunk-HYO3NP5Q.js → chunk-MZPXPSUJ.js} +2 -2
  117. package/dist/{chunk-VZRNID6A.js → chunk-N55KIE46.js} +2 -2
  118. package/dist/{chunk-YF5IB2LF.js → chunk-NB4D3BNM.js} +2 -2
  119. package/dist/{chunk-VVZSBTSU.js → chunk-NGKBOT6G.js} +2 -2
  120. package/dist/{chunk-NJITK2GP.js → chunk-NJGKXKQF.js} +2 -2
  121. package/dist/chunk-NJQISBL4.js +8 -0
  122. package/dist/{chunk-T4N4P2K5.js → chunk-NJT3ZEKY.js} +2 -2
  123. package/dist/{chunk-FPYLNQPT.js → chunk-NKMKZP6A.js} +2 -2
  124. package/dist/chunk-NODFZ6ED.js +2 -0
  125. package/dist/{chunk-BRV7PIFF.js → chunk-NSM5IEVW.js} +2 -2
  126. package/dist/{chunk-3WR4E3A3.js → chunk-NTGUVNR2.js} +2 -2
  127. package/dist/{chunk-VUPHCS7Y.js → chunk-NU3KFF2O.js} +2 -2
  128. package/dist/chunk-NWLVNU66.js +557 -0
  129. package/dist/{chunk-D4N5SQ2M.js → chunk-NYKZMCRC.js} +2 -2
  130. package/dist/{chunk-VNLGKHS6.js → chunk-O6BUXZEH.js} +2 -2
  131. package/dist/chunk-ODPDP7A4.js +3 -0
  132. package/dist/{chunk-JTQVMR42.js → chunk-OHIV323X.js} +2 -2
  133. package/dist/chunk-OIAPEKMT.js +3 -0
  134. package/dist/chunk-OIOC5EHF.js +3 -0
  135. package/dist/{chunk-YBGKCQIS.js → chunk-ONPPQM4G.js} +2 -2
  136. package/dist/{chunk-64BFSI5I.js → chunk-OUHEZBYI.js} +2 -2
  137. package/dist/{chunk-L6PJPETJ.js → chunk-OVGYW7UD.js} +2 -2
  138. package/dist/{chunk-I55I7XXP.js → chunk-OYKU4B3Y.js} +2 -2
  139. package/dist/{chunk-J66VOFW6.js → chunk-POBJ6FR2.js} +2 -2
  140. package/dist/{chunk-CWFP7GM5.js → chunk-PSZPMMWN.js} +2 -2
  141. package/dist/chunk-PXTRBKRK.js +3 -0
  142. package/dist/{chunk-HKGFPJ4T.js → chunk-Q5JRIHT3.js} +2 -2
  143. package/dist/{chunk-P42EIXTA.js → chunk-Q7ATHARX.js} +2 -2
  144. package/dist/{chunk-JYR66JN5.js → chunk-Q7CSKIDM.js} +2 -2
  145. package/dist/{chunk-TRNAEQ6P.js → chunk-QBQE7ZJ5.js} +2 -2
  146. package/dist/{chunk-DULC3QFP.js → chunk-QH22UIXP.js} +2 -2
  147. package/dist/chunk-QXCKQTKR.js +60 -0
  148. package/dist/{chunk-ODDUPDP7.js → chunk-RBAD4GJ2.js} +5 -5
  149. package/dist/{chunk-IZDPJ2QI.js → chunk-RMDPFPNW.js} +2 -2
  150. package/dist/chunk-ROPJDEJZ.js +4 -0
  151. package/dist/{chunk-EKV5HX33.js → chunk-RVZC6TJE.js} +2 -2
  152. package/dist/{chunk-XFA4SSO3.js → chunk-S4QZBKSR.js} +2 -2
  153. package/dist/{chunk-D2DHWI3D.js → chunk-SCPMZ73U.js} +2 -2
  154. package/dist/{chunk-PZL5T7SU.js → chunk-SIAP5RGI.js} +2 -2
  155. package/dist/{chunk-7IWV2EG3.js → chunk-SIX4RFR3.js} +2 -2
  156. package/dist/{chunk-DYGHBZ2N.js → chunk-SKKXTABJ.js} +2 -2
  157. package/dist/{chunk-F7DY272B.js → chunk-SSRFUQBD.js} +2 -2
  158. package/dist/chunk-SYVJEEUJ.js +3 -0
  159. package/dist/{chunk-FGA2U4OR.js → chunk-T3CZAZSI.js} +2 -2
  160. package/dist/chunk-T3I6NHBH.js +2 -0
  161. package/dist/{chunk-EQHFIL6T.js → chunk-T6DWDI5E.js} +2 -2
  162. package/dist/chunk-T6HRIROJ.js +7 -0
  163. package/dist/{chunk-GSP44ENC.js → chunk-TAA7HXHE.js} +2 -2
  164. package/dist/{chunk-BQGB4HBD.js → chunk-TJ2JQYT3.js} +2 -2
  165. package/dist/{chunk-XPDPNWTQ.js → chunk-TULNMD5T.js} +19 -19
  166. package/dist/chunk-U2FPY5XA.js +3 -0
  167. package/dist/chunk-U3SXIMII.js +38 -0
  168. package/dist/{chunk-NOGJXYFO.js → chunk-U6KCHXJ4.js} +2 -2
  169. package/dist/chunk-UH3XSKS5.js +9 -0
  170. package/dist/{chunk-AFHTBORT.js → chunk-UIFUZVCC.js} +2 -2
  171. package/dist/{chunk-7BWFZPPZ.js → chunk-UXKURIVI.js} +2 -2
  172. package/dist/{chunk-2E7CX53V.js → chunk-V2RBODHL.js} +2 -2
  173. package/dist/{chunk-KLFEXGQA.js → chunk-VBKUWB6N.js} +2 -2
  174. package/dist/{chunk-WUN6KBHV.js → chunk-VBV6ALJE.js} +2 -2
  175. package/dist/{chunk-GZIUDL6G.js → chunk-VDGFWCQV.js} +2 -2
  176. package/dist/chunk-VDSDOEWF.js +2 -0
  177. package/dist/{chunk-WDNVY4E7.js → chunk-VZPWVCLN.js} +2 -2
  178. package/dist/chunk-WDSFQDPN.js +2 -0
  179. package/dist/{chunk-CIYLO6SI.js → chunk-WFA35BGR.js} +2 -2
  180. package/dist/{chunk-LMZ5PRUV.js → chunk-WLMP3OCW.js} +2 -2
  181. package/dist/{chunk-3SVF22I5.js → chunk-WSA52GOR.js} +2 -2
  182. package/dist/{chunk-VMPRET3I.js → chunk-X3YVZAKZ.js} +2 -2
  183. package/dist/{chunk-GYIZ4NXB.js → chunk-X6OGVFIT.js} +2 -2
  184. package/dist/{chunk-6HFCYNYE.js → chunk-XKXTR6ZI.js} +2 -2
  185. package/dist/{chunk-6VVV4WRR.js → chunk-Y5DFAW5W.js} +2 -2
  186. package/dist/chunk-YSYPDRD5.js +3 -0
  187. package/dist/{chunk-TQPCBMWT.js → chunk-ZFVPWH62.js} +2 -2
  188. package/dist/chunk-ZGIHTH27.js +2 -0
  189. package/dist/{chunk-OR2E3AGZ.js → chunk-ZGIQN2SX.js} +2 -2
  190. package/dist/{chunk-WNTFFKAX.js → chunk-ZHG4WAHR.js} +2 -2
  191. package/dist/{chunk-DTZCKZEU.js → chunk-ZKB2XUEN.js} +2 -2
  192. package/dist/chunk-ZLMXIQLC.js +21 -0
  193. package/dist/chunk-ZMCQIHI4.js +2 -0
  194. package/dist/cli-main.js +2 -2
  195. package/dist/code-TAVIKWJI.js +2 -0
  196. package/dist/code-result-json-5FEFQCAQ.js +2 -0
  197. package/dist/{command-descriptors-P34VABY5.js → command-descriptors-7BKH53Y3.js} +124 -124
  198. package/dist/dataflow-GFBTVDH3.js +2 -0
  199. package/dist/dependence-slice-GWGQCODG.js +2 -0
  200. package/dist/deps-4QHVDPYA.js +2 -0
  201. package/dist/direct-navigation-4UBC6HNW.js +3 -0
  202. package/dist/entry-map-QCTF4RVY.js +2 -0
  203. package/dist/files-M2UBF5HJ.js +2 -0
  204. package/dist/frontend-profile-roles-D7eCum8P.d.ts +10 -0
  205. package/dist/{health-CPp2Jf1Z.d.ts → health-BI2a9WPy.d.ts} +60 -2
  206. package/dist/hierarchy-2UIHRLW4.js +2 -0
  207. package/dist/imports-WIE3YZOB.js +2 -0
  208. package/dist/index.d.ts +1 -1
  209. package/dist/index.js +1 -1
  210. package/dist/members-YKD636DA.js +2 -0
  211. package/dist/methods-VDF4IMYG.js +2 -0
  212. package/dist/output-continuation-command-4UMDOOLO.js +3 -0
  213. package/dist/output-pagination-2GME6OPY.js +19 -0
  214. package/dist/postinstall.js +1 -1
  215. package/dist/project-reindex-XEQTRCV5.js +3 -0
  216. package/dist/queries/affected.js +1 -1
  217. package/dist/queries/anchors.d.ts +1 -1
  218. package/dist/queries/anchors.js +1 -1
  219. package/dist/queries/architecture.js +1 -1
  220. package/dist/queries/bottlenecks.js +1 -1
  221. package/dist/queries/by-kind.js +1 -1
  222. package/dist/queries/call-graph.d.ts +2 -0
  223. package/dist/queries/call-graph.js +1 -1
  224. package/dist/queries/change-surface.js +1 -1
  225. package/dist/queries/cleanup-plan.js +1 -1
  226. package/dist/queries/co-change.d.ts +20 -2
  227. package/dist/queries/co-change.js +1 -1
  228. package/dist/queries/code.js +1 -1
  229. package/dist/queries/complexity-hotspots.js +1 -1
  230. package/dist/queries/complexity.js +1 -1
  231. package/dist/queries/context.js +1 -1
  232. package/dist/queries/convergence.js +1 -1
  233. package/dist/queries/coupling.js +1 -1
  234. package/dist/queries/cycles.js +1 -1
  235. package/dist/queries/dataflow.js +1 -1
  236. package/dist/queries/dead.d.ts +2 -0
  237. package/dist/queries/dead.js +1 -1
  238. package/dist/queries/decorative-checkers.js +1 -1
  239. package/dist/queries/deep-chains.js +1 -1
  240. package/dist/queries/dependence-slice.js +1 -1
  241. package/dist/queries/dependency-depth.js +1 -1
  242. package/dist/queries/deps.js +1 -1
  243. package/dist/queries/diff-impact.js +1 -1
  244. package/dist/queries/doc-drift.js +1 -1
  245. package/dist/queries/drift.js +1 -1
  246. package/dist/queries/duplicate-bodies.d.ts +28 -1
  247. package/dist/queries/duplicate-bodies.js +1 -1
  248. package/dist/queries/entry-map.d.ts +1 -1
  249. package/dist/queries/entry-map.js +1 -1
  250. package/dist/queries/evidence.js +1 -1
  251. package/dist/queries/extract-candidates.d.ts +50 -23
  252. package/dist/queries/extract-candidates.js +1 -1
  253. package/dist/queries/fan.js +1 -1
  254. package/dist/queries/files.js +1 -1
  255. package/dist/queries/health.d.ts +1 -1
  256. package/dist/queries/health.js +1 -1
  257. package/dist/queries/hierarchy.js +1 -1
  258. package/dist/queries/hotspots.js +1 -1
  259. package/dist/queries/imports.js +1 -1
  260. package/dist/queries/incomplete-migration.js +1 -1
  261. package/dist/queries/index.d.ts +4 -3
  262. package/dist/queries/index.js +1 -1
  263. package/dist/queries/isolated.js +1 -1
  264. package/dist/queries/locality-candidates.js +1 -1
  265. package/dist/queries/members.js +1 -1
  266. package/dist/queries/methods.js +1 -1
  267. package/dist/queries/not-implemented.js +1 -1
  268. package/dist/queries/outline.js +1 -1
  269. package/dist/queries/passthrough-candidates.d.ts +9 -1
  270. package/dist/queries/passthrough-candidates.js +1 -1
  271. package/dist/queries/plan-context.js +1 -1
  272. package/dist/queries/react-component-duplicates.d.ts +19 -3
  273. package/dist/queries/react-component-duplicates.js +1 -1
  274. package/dist/queries/react-hook-candidates.d.ts +22 -3
  275. package/dist/queries/react-hook-candidates.js +1 -1
  276. package/dist/queries/react-large-component-pressure.d.ts +17 -3
  277. package/dist/queries/react-large-component-pressure.js +1 -1
  278. package/dist/queries/recent-duplicates.js +1 -1
  279. package/dist/queries/redundant-reexports.js +1 -1
  280. package/dist/queries/reference-neighborhood.js +1 -1
  281. package/dist/queries/reference-reachability.js +1 -1
  282. package/dist/queries/refs.js +1 -1
  283. package/dist/queries/self-audit.d.ts +7 -1
  284. package/dist/queries/self-audit.js +1 -1
  285. package/dist/queries/similar-chains.js +1 -1
  286. package/dist/queries/similar-files.js +1 -1
  287. package/dist/queries/similar-signatures.js +1 -1
  288. package/dist/queries/similar.js +1 -1
  289. package/dist/queries/slice.js +1 -1
  290. package/dist/queries/source-inspection.js +1 -1
  291. package/dist/queries/source-search.js +1 -1
  292. package/dist/queries/stale-abstractions.js +1 -1
  293. package/dist/queries/surface.js +1 -1
  294. package/dist/queries/symbols.js +1 -1
  295. package/dist/queries/system-map.d.ts +1 -1
  296. package/dist/queries/system-map.js +1 -1
  297. package/dist/queries/system.js +1 -1
  298. package/dist/queries/test-quality.js +1 -1
  299. package/dist/queries/trace.js +1 -1
  300. package/dist/queries/twin-ab.js +1 -1
  301. package/dist/queries/twin-drift.d.ts +22 -6
  302. package/dist/queries/twin-drift.js +1 -1
  303. package/dist/queries/unused-imports.js +1 -1
  304. package/dist/queries/unused-params.js +1 -1
  305. package/dist/queries/value-flow.js +1 -1
  306. package/dist/queries/vue-component-duplicates.js +1 -1
  307. package/dist/queries/vue-composable-candidates.js +1 -1
  308. package/dist/queries/vue-large-view-pressure.js +1 -1
  309. package/dist/queries/wrapper-candidates.d.ts +16 -1
  310. package/dist/queries/wrapper-candidates.js +1 -1
  311. package/dist/query-service-fastpath.js +5 -5
  312. package/dist/query-service-server.js +2 -2
  313. package/dist/refs-JNK5CLM7.js +2 -0
  314. package/dist/refs-pagination-6BLRYGMV.js +2 -0
  315. package/dist/reindex-worker.js +10 -10
  316. package/dist/reindex.js +18 -18
  317. package/dist/runtime.js +4 -4
  318. package/dist/rust-semantic-session-server.js +1 -1
  319. package/dist/rust-semantic-session-worker.js +1 -1
  320. package/dist/rust-semantic-worker.js +1 -1
  321. package/dist/slice-PHPVNCWX.js +2 -0
  322. package/dist/surface-MQX5MPIV.js +2 -0
  323. package/dist/{symbol-resolution-WD5EU5JE.js → symbol-resolution-DBLVXLBC.js} +2 -2
  324. package/dist/system-JOPKV4OG.js +2 -0
  325. package/dist/trace-I2P2YFH4.js +2 -0
  326. package/dist/typescript-mailbox-worker.js +1 -1
  327. package/dist/value-flow-JJVMF7NP.js +2 -0
  328. package/dist/watch-server.js +3 -3
  329. package/docs/COMMAND_REFERENCE.md +2 -2
  330. package/docs/DETECTOR_GUIDE.md +51 -12
  331. package/docs/accuracy-audit-checklist.md +36 -13
  332. package/docs/locality-analyzer-design.md +9 -9
  333. package/package.json +2 -2
  334. package/skills/conductor/SKILL.md +110 -0
  335. package/skills/conductor/agents/openai.yaml +4 -0
  336. package/skills/principal-maintainability-review/SKILL.md +273 -0
  337. package/skills/principal-maintainability-review/agents/openai.yaml +4 -0
  338. package/skills/scip-calibrate/SKILL.md +102 -0
  339. package/skills/scip-calibrate/agents/openai.yaml +4 -0
  340. package/skills/scip-claim-audit/SKILL.md +113 -0
  341. package/skills/scip-claim-audit/agents/openai.yaml +4 -0
  342. package/skills/scip-probe-reachability/SKILL.md +93 -0
  343. package/skills/scip-probe-reachability/agents/openai.yaml +4 -0
  344. package/skills/scip-root-cause/SKILL.md +160 -0
  345. package/skills/scip-root-cause/agents/openai.yaml +4 -0
  346. package/skills/scip-system-compression/SKILL.md +252 -0
  347. package/skills/scip-system-compression/agents/openai.yaml +4 -0
  348. package/skills/scip-system-compression/references/compression-atlas.md +116 -0
  349. package/skills/scip-system-compression/references/compression-patterns.md +87 -0
  350. package/skills/scip-twin-drift/SKILL.md +109 -0
  351. package/skills/scip-twin-drift/agents/openai.yaml +4 -0
  352. package/dist/by-kind-XI2CSWEY.js +0 -2
  353. package/dist/call-graph-UONR6JR5.js +0 -2
  354. package/dist/call-graph-evidence-lZa2dwQA.d.ts +0 -11
  355. package/dist/chunk-2R3V3PSD.js +0 -4
  356. package/dist/chunk-2WC2OEDO.js +0 -4
  357. package/dist/chunk-3FHOF22C.js +0 -21
  358. package/dist/chunk-3JKSW6LJ.js +0 -2
  359. package/dist/chunk-3L2ZBPEX.js +0 -133
  360. package/dist/chunk-3PJABJSU.js +0 -2
  361. package/dist/chunk-4FTZ4P5G.js +0 -2
  362. package/dist/chunk-4UX2F3JX.js +0 -2
  363. package/dist/chunk-5ENOG4VP.js +0 -61
  364. package/dist/chunk-66DVSJQG.js +0 -455
  365. package/dist/chunk-AVRYW5OZ.js +0 -2
  366. package/dist/chunk-BDUVI7TO.js +0 -3
  367. package/dist/chunk-CEEZJXEF.js +0 -2
  368. package/dist/chunk-CJZXN4NU.js +0 -2
  369. package/dist/chunk-COF23M5F.js +0 -2
  370. package/dist/chunk-DHUIOLDT.js +0 -2
  371. package/dist/chunk-DRENNWRG.js +0 -2
  372. package/dist/chunk-E5R6AQ73.js +0 -40
  373. package/dist/chunk-E73UNJTF.js +0 -38
  374. package/dist/chunk-EVFUMY4R.js +0 -3
  375. package/dist/chunk-FBN2FGXG.js +0 -2
  376. package/dist/chunk-FFRKR4EQ.js +0 -2
  377. package/dist/chunk-GAS2LJMP.js +0 -3
  378. package/dist/chunk-HVF5VBG6.js +0 -2
  379. package/dist/chunk-JGKUET5J.js +0 -3
  380. package/dist/chunk-JWTGMPIT.js +0 -80
  381. package/dist/chunk-KFOYCQAJ.js +0 -9
  382. package/dist/chunk-KYSDI3GE.js +0 -5
  383. package/dist/chunk-LDVT66YM.js +0 -2
  384. package/dist/chunk-LQRQN2XA.js +0 -2
  385. package/dist/chunk-MNV5FSBW.js +0 -3
  386. package/dist/chunk-MV3CDXPI.js +0 -38
  387. package/dist/chunk-N5B2NILC.js +0 -5
  388. package/dist/chunk-NOYBFVJA.js +0 -554
  389. package/dist/chunk-NWQXSFFU.js +0 -3
  390. package/dist/chunk-OLIWTZI3.js +0 -3
  391. package/dist/chunk-PP7KNN7L.js +0 -2
  392. package/dist/chunk-PU7T5QYQ.js +0 -2
  393. package/dist/chunk-QGVTFRY2.js +0 -7
  394. package/dist/chunk-QOJONDS7.js +0 -2
  395. package/dist/chunk-RBLQNW26.js +0 -20
  396. package/dist/chunk-RTQ7NEKG.js +0 -81
  397. package/dist/chunk-TPFHAQ2G.js +0 -2
  398. package/dist/chunk-TQZV7KV4.js +0 -2
  399. package/dist/chunk-TY7CRN3Z.js +0 -2
  400. package/dist/chunk-W7CXK74K.js +0 -2
  401. package/dist/chunk-WB3WYIRE.js +0 -4
  402. package/dist/chunk-WK46TNUM.js +0 -3
  403. package/dist/chunk-WYCTJDVR.js +0 -2
  404. package/dist/chunk-XRYABF57.js +0 -8
  405. package/dist/chunk-YPWHBBIS.js +0 -2
  406. package/dist/chunk-YSH6U3L4.js +0 -3
  407. package/dist/chunk-YU5DZUZI.js +0 -10
  408. package/dist/chunk-YWO5DDRC.js +0 -16
  409. package/dist/chunk-ZF5KHH7C.js +0 -2
  410. package/dist/chunk-ZOHS7AQV.js +0 -21
  411. package/dist/code-MI6F2TTU.js +0 -2
  412. package/dist/code-result-json-FXALY4HE.js +0 -2
  413. package/dist/dataflow-4KEMJPC6.js +0 -2
  414. package/dist/dependence-slice-R7FPWD5M.js +0 -2
  415. package/dist/deps-7EMQUYUT.js +0 -2
  416. package/dist/direct-navigation-6YO234F2.js +0 -3
  417. package/dist/entry-map-KOOLR26E.js +0 -2
  418. package/dist/files-OPIPJIGZ.js +0 -2
  419. package/dist/hierarchy-QPD2CAER.js +0 -2
  420. package/dist/imports-M6HUXRXC.js +0 -2
  421. package/dist/members-I5MEFOCT.js +0 -2
  422. package/dist/methods-5JYGGHXA.js +0 -2
  423. package/dist/output-continuation-command-UPQAAKBP.js +0 -3
  424. package/dist/output-pagination-3OFL2MJV.js +0 -19
  425. package/dist/project-reindex-UKKQ5PLS.js +0 -3
  426. package/dist/refs-PSU4JZZW.js +0 -2
  427. package/dist/refs-pagination-JG6CJMRC.js +0 -2
  428. package/dist/slice-HYRATV64.js +0 -2
  429. package/dist/surface-VTGDYWF5.js +0 -2
  430. package/dist/system-LRQNFOR2.js +0 -2
  431. package/dist/trace-F4B6OLL4.js +0 -2
  432. package/dist/value-flow-VRPZY72V.js +0 -2
package/dist/runtime.js CHANGED
@@ -1,5 +1,5 @@
1
- import{C as lt,D as pt,M as ht,O as ue,b as at,c as ct,i as On,j as En,k as wn,q as dt,z as ut}from"./chunk-WNTFFKAX.js";import{c as qe,u as ce,x as st}from"./chunk-5ENOG4VP.js";import{c as Ue,e as q,g as Ke,h as Ye}from"./chunk-TRNAEQ6P.js";import"./chunk-DHEQMPLW.js";import"./chunk-JWTGMPIT.js";import{$ as Xe,C as $e,D as Ge,Da as it,Fa as ot,I as Je,Ia as K,J as v,L as Be,T as He,X as Qe,_ as ze,aa as de,ba as Ze,f as Le,fa as et,g as ae,i as B,ia as tt,ja as nt,k as Fe,ma as rt,n as p,p as C,q as k,r as D,ra as H,s as We,t as g,v as L,x as U}from"./chunk-N5B2NILC.js";import{existsSync as or}from"fs";import{randomUUID as sr}from"crypto";import{isAbsolute as Ki,join as At,relative as Yi,resolve as Qi}from"path";var E=1,T=2,Pn="./node_modules/scip-query/docs/schemas/project-config.schema.json";function le(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(a){return{kind:"malformed",reason:`invalid JSON: ${a instanceof Error?a.message:String(a)}`}}if(!p(t))return{kind:"malformed",reason:"project config must be a JSON object"};let n=t.schemaVersion;if(n!==void 0&&!Number.isInteger(n))return{kind:"malformed",reason:"schemaVersion must be an integer"};let r=n===void 0?E:n;if(r!==E&&r!==T)return{kind:"unsupported",schemaVersion:r,direction:r<E?"older":"future"};let i=t.$schema;if(i!==void 0&&(typeof i!="string"||i.trim()===""))return{kind:"malformed",reason:"$schema must be a non-empty string when present"};let o=Y(t),s=r!==T||typeof t.$schema!="string";return r===E?{kind:"legacy",sourceVersion:E,config:o,needsMigration:s}:{kind:"supported",sourceVersion:T,config:o,needsMigration:s}}function Y(e){let t=e,{$schema:n,schemaVersion:r,...i}=t;return{$schema:typeof n=="string"&&n.trim()!==""?n:Pn,schemaVersion:T,...i}}function pe(e){return`${JSON.stringify(Y(e),null,2)}
2
- `}import{createHash as kn}from"crypto";var f=1,I=2,Q=1,W=1,F="sha256",me=1;function Ct(e,t,n){if(!g(e)||!D(t))throw new Error("Observation identity requires a bounded projection name and positive projection version.");return{schemaVersion:Q,canonicalizationVersion:W,hashAlgorithm:F,projection:{name:e,version:t},digest:kn(F).update(Tn(e,t,n)).digest("hex")}}function Tn(e,t,n){return`{"canonicalizationVersion":${W},"projection":${JSON.stringify(e)},"projectionVersion":${t},"value":${JSON.stringify(n)}}`}function ge(e){if(!p(e))return{kind:"malformed",reason:"observation receipt must be an object"};let t=e.schemaVersion;if(!Number.isInteger(t))return{kind:"malformed",reason:"observation receipt schemaVersion must be an integer"};if(t===f)return Vn(e)?{kind:"legacy",schemaVersion:f,receipt:e}:{kind:"malformed",reason:"observation receipt v1 fields are malformed or contradictory"};if(t===I)return Dn(e)?{kind:"supported",schemaVersion:I,receipt:e}:{kind:"malformed",reason:"observation receipt v2 facts are malformed or contradictory"};let n=t;return{kind:"unsupported",schemaVersion:n,direction:n<f?"older":"future"}}function z(e){let t=ge(e);return t.kind==="legacy"||t.kind==="supported"}function ye(e,t){return{collaborationDomain:w(b(e,n=>n.facts.collaborationDomain),b(t,n=>n.facts.collaborationDomain)),repositoryLineage:w(b(e,n=>n.facts.repositoryLineage),b(t,n=>n.facts.repositoryLineage)),workspaceInstance:w(b(e,n=>n.facts.workspaceInstance),b(t,n=>n.facts.workspaceInstance)),wholeContent:w(b(e,n=>n.facts.wholeContent),b(t,n=>n.facts.wholeContent)),relevantInputs:_n(e,t),indexInput:w(b(e,n=>n.facts.index?.inputs),b(t,n=>n.facts.index?.inputs)),indexGeneration:An(e,t),observationStability:jn(e,t)}}function X(e,t,n=ye(e,t)){let r=[["collaborationDomain",n.collaborationDomain],["wholeContent",n.wholeContent],["observationStability",n.observationStability]],i=[];for(let[s,a]of r)a.state!=="established"&&i.push(`${s}:${a.state}`);for(let[s,a]of[["left",e],["right",t]]){let c=Mn(a);c!=="not-applicable"&&c!=="established"&&i.push(`${s}IndexAlignment:${c}`)}let o=r.some(([,s])=>s.state==="disproven")||i.some(s=>s.endsWith(":disproven"));return{policyVersion:me,authority:i.length===0?"completion":o?"none":"advisory",requiredRelationships:["collaborationDomain","wholeContent","observationStability"],reasons:i}}function bt(e){return e.schemaVersion===f?e.index?.generationIdentity:e.facts.index?.generation.digest}function vt(e){return e.schemaVersion===f?void 0:e.facts.workspaceInstance?.digest}function Rt(e){if(e.schemaVersion===f)return e.index?.alignment??"not-established";let t=e.stabilityProofs.filter(n=>n.source!=="process");return t.some(n=>n.kind==="invalidated")?"invalidated":t.length>0&&t.every(n=>n.kind==="immutable"||n.kind==="fixed-snapshot")?"fixed":t.some(n=>n.kind==="bracketed")?"bracketed":"not-established"}function _n(e,t){let n=ft(e),r=ft(t);return[...new Set([...n.keys(),...r.keys()])].sort().map(o=>{let s=n.get(o),a=r.get(o),c=s?.subject??a?.subject??o,d=s?.identity.projection.name??a?.identity.projection.name??o;return{subject:c,projection:d,judgment:w(s?.identity,a?.identity)}})}function ft(e){return e.schemaVersion!==I?new Map:new Map((e.facts.relevantInputs??[]).map(t=>[`${t.subject}\0${t.identity.projection.name}`,t]))}function An(e,t){return e.schemaVersion===f&&t.schemaVersion===f?Nn(e.index?.generationIdentity,t.index?.generationIdentity):e.schemaVersion===f||t.schemaVersion===f?R("unknown",["legacy-fact-not-comparable"],gt(e),gt(t)):w(e.facts.index?.generation,t.facts.index?.generation)}function Nn(e,t){let n=e?[{kind:"legacy-index-generation",value:e}]:[],r=t?[{kind:"legacy-index-generation",value:t}]:[];return e===void 0||t===void 0?St(n,r):R(e===t?"established":"disproven",[e===t?"identities-equal":"identities-different"],n,r)}function w(e,t){let n=e?[{kind:"identity",identity:e}]:[],r=t?[{kind:"identity",identity:t}]:[];return!e||!t?St(n,r):Ce(e,t)?R(e.digest===t.digest?"established":"disproven",[e.digest===t.digest?"identities-equal":"identities-different"],n,r):R("unknown",["identity-projections-not-comparable"],n,r)}function jn(e,t){if(e.schemaVersion===f||t.schemaVersion===f)return R("unknown",["legacy-fact-not-comparable"],[],[]);let n=yt(e),r=yt(t),i=mt(e),o=mt(t);return i==="invalidated"||o==="invalidated"?R("disproven",[...i==="invalidated"?["left-observation-invalidated"]:[],...o==="invalidated"?["right-observation-invalidated"]:[]],n,r):i!=="fixed"||o!=="fixed"?R("unknown",[...i==="no-repository-source"?["left-observation-has-no-repository-source"]:i!=="fixed"?["left-observation-not-fixed"]:[],...o==="no-repository-source"?["right-observation-has-no-repository-source"]:o!=="fixed"?["right-observation-not-fixed"]:[]],n,r):R("established",["all-observed-sources-fixed"],n,r)}function mt(e){let t=e.observedSources.filter(r=>r.kind!=="process");if(t.length===0)return"no-repository-source";let n=new Map(e.stabilityProofs.map(r=>[r.source,r.kind]));return t.some(r=>n.get(r.kind)==="invalidated")?"invalidated":t.every(r=>{let i=n.get(r.kind);return i==="immutable"||i==="fixed-snapshot"})?"fixed":"unknown"}function Mn(e){if(e.schemaVersion!==I)return e.index?"unknown":"not-applicable";if(!e.observedSources.some(r=>r.kind==="index-generation"))return"not-applicable";let t=e.facts.index?.inputs;if(!t)return"unknown";let n=(e.facts.relevantInputs??[]).find(r=>Ce(r.identity,t))?.identity;return n?n.digest===t.digest?"established":"disproven":"unknown"}function b(e,t){return e.schemaVersion===I?t(e):void 0}function gt(e){return e.schemaVersion===f&&e.index?[{kind:"legacy-index-generation",value:e.index.generationIdentity}]:e.schemaVersion===I&&e.facts.index?[{kind:"identity",identity:e.facts.index.generation}]:[]}function yt(e){return e.stabilityProofs.map(t=>({kind:"stability",proof:t}))}function St(e,t){let n=e.length===0&&t.length===0?"both-facts-missing":e.length===0?"left-fact-missing":"right-fact-missing";return R("unknown",[n],e,t)}function R(e,t,n,r){return{state:e,reasons:t,facts:{left:n,right:r}}}function Ce(e,t){return e.schemaVersion===t.schemaVersion&&e.canonicalizationVersion===t.canonicalizationVersion&&e.hashAlgorithm===t.hashAlgorithm&&e.projection.name===t.projection.name&&e.projection.version===t.projection.version}function Vn(e){if(!p(e))return!1;let t=e.index,n=e.worktree;return It(e.observedAt)&&g(e.projectIdentity)&&Bn(e.authorityKind)&&(t===void 0||p(t)&&g(t.generationIdentity)&&(t.source==="immutable"||t.source==="legacy")&&(t.alignment==="not-certified"||t.alignment==="leased"))&&(n===void 0||p(n)&&g(n.identity)&&typeof n.clean=="boolean"&&(n.headCommit===void 0||g(n.headCommit))&&(n.treeOid===void 0||g(n.treeOid)))&&Jn(e.authorityKind,t,n)}function Dn(e){if(!p(e))return!1;let t=e.facts,n=e.observedSources,r=e.stabilityProofs;if(!It(e.observedAt)||!p(t)||!Array.isArray(n)||n.length===0||!n.every(Fn)||!fe(n,c=>c.kind)||!Array.isArray(r)||!r.every(Wn)||!fe(r,c=>c.source)||r.some(c=>!n.some(d=>d.kind===c.source))||!r.every(c=>Gn(c,t))||["collaborationDomain","repositoryLineage","workspaceInstance","wholeContent"].some(c=>t[c]!==void 0&&!x(t[c])))return!1;let o=t.relevantInputs;if(o!==void 0&&(!Array.isArray(o)||!o.every(Ln)||!fe(o,c=>`${c.subject}\0${c.identity.projection.name}`)))return!1;let s=t.index;if(s!==void 0&&(!p(s)||!x(s.generation)||s.inputs!==void 0&&!x(s.inputs)||s.source!=="immutable"&&s.source!=="legacy"))return!1;let a=e.diagnostics;return(a===void 0||p(a)&&(a.clean===void 0||typeof a.clean=="boolean")&&(a.headCommit===void 0||g(a.headCommit))&&(a.treeOid===void 0||g(a.treeOid)))&&$n(t,n)}function x(e){return!p(e)||!p(e.projection)?!1:e.schemaVersion===Q&&e.canonicalizationVersion===W&&e.hashAlgorithm===F&&g(e.projection.name)&&D(e.projection.version)&&We(e.digest)}function Ln(e){return p(e)&&g(e.subject)&&x(e.identity)}function Fn(e){return p(e)&&xt(e.kind)&&(e.identity===void 0||x(e.identity))}function Wn(e){return p(e)&&xt(e.source)&&(e.kind==="immutable"||e.kind==="fixed-snapshot"||e.kind==="bracketed"||e.kind==="not-established"||e.kind==="invalidated")}function $n(e,t){let n=e.index,r=t.find(c=>c.kind==="index-generation");if(r){if(!p(n)||!x(n.generation)||r.identity&&!he(r.identity,n.generation))return!1}else if(n!==void 0)return!1;let i=e.workspaceInstance,o=t.find(c=>c.kind==="live-workspace");if(o?.identity&&(!x(i)||!he(o.identity,i)))return!1;let s=e.wholeContent,a=t.find(c=>c.kind==="repository-snapshot");return!(a?.identity&&(!x(s)||!he(a.identity,s)))}function Gn(e,t){return e.kind==="not-established"||e.kind==="invalidated"?!0:e.source==="index-generation"?e.kind==="immutable"&&p(t.index)&&t.index.source==="immutable":e.source==="repository-snapshot"?e.kind==="fixed-snapshot":e.source==="live-workspace"?e.kind==="bracketed":!1}function he(e,t){return Ce(e,t)&&e.digest===t.digest}function Jn(e,t,n){return e==="index-worktree"?t!==void 0&&n!==void 0:e==="index-only"?t!==void 0&&n===void 0:e==="worktree-only"?t===void 0&&n!==void 0:e==="process-local"&&t===void 0&&n===void 0}function Bn(e){return e==="index-worktree"||e==="index-only"||e==="worktree-only"||e==="process-local"}function xt(e){return e==="index-generation"||e==="repository-snapshot"||e==="live-workspace"||e==="process"}function It(e){return typeof e=="string"&&!Number.isNaN(Date.parse(e))}function fe(e,t){return new Set(e.map(t)).size===e.length}import{createHash as Ot}from"crypto";import{closeSync as Un,fstatSync as Et,lstatSync as qn,openSync as Hn,readlinkSync as Kn,realpathSync as Yn,rmSync as Qn}from"fs";import{dirname as kt,resolve as zn}from"path";var Xn=2e3,Zn=10,er=3,ee=class extends Error{constructor(n,r,i){super(`Concurrent edit detected for ${n}; expected revision ${Pt(r)}, but found ${Pt(i)}. The latest file was left untouched.`);this.path=n;this.original=r;this.latest=i;this.name="FileRevisionConflictError"}path;original;latest};function Tt(e,t,n={}){let r=tr(e),i=nr(r,n.lockTimeoutMs??Xn,n.monotonicNow??q);try{let o=Math.max(0,Math.floor(n.maxRetries??er));for(let s=0;;s+=1){let a=Z(r),c=t(a,s);if(c.kind==="unchanged")return{changed:!1,attempts:s+1,previous:a,current:a};n.onBeforeCommit?.({attempt:s,snapshot:a,mutation:c});let d=Z(r);if(!ir(a.revision,d.revision)){if(s<o)continue;throw new ee(r,a.revision,d.revision)}try{rr(r,c,a.revision)}catch(l){if(l.code==="EEXIST"){let u=Z(r);if(s<o)continue;throw new ee(r,a.revision,u.revision)}throw l}return{changed:!0,attempts:s+1,previous:a,current:Z(r)}}}finally{i.release()}}function tr(e){let t;try{if(!qn(e).isSymbolicLink())return e;t=Kn(e)}catch{return e}try{return Yn(e)}catch{return zn(kt(e),t)}}function Z(e){for(let t=0;t<4;t+=1){let n;try{n=Hn(e,"r");let r=wt(Et(n)),i=Be(n,{maxBytes:Ge,inputKind:"revisioned text file"}),o=wt(Et(n));if(!_t(r,o))continue;return{path:e,text:i,revision:{exists:!0,hash:Ot("sha256").update(i).digest("hex"),identity:o}}}catch(r){if(r.code==="ENOENT")return{path:e,text:"",revision:{exists:!1,hash:Ot("sha256").update("").digest("hex")}};throw r}finally{n!==void 0&&Un(n)}}throw new Error(`Could not read a stable revision of ${e}; the file is changing continuously.`)}function nr(e,t,n){let r=`${e}.scip-query-write.lock`,i=n()+Math.max(0,t);for(;;){let o=qe(r,{kind:"revisioned-file-mutation",detail:{target:e}});if(o.kind==="acquired")return o.lock;if(n()>=i)throw new Error(`Timed out after ${t}ms waiting to update ${e}; the file was left untouched.`);Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,Zn)}}function rr(e,t,n){if(t.kind==="delete"){if(!n.exists)return;Qn(e),He(kt(e));return}let r=t.mode??n.identity?.mode;n.exists?Ke(e,t.text,{durability:"durable",mode:r}):Ye(e,t.text,{durability:"durable",mode:r})}function ir(e,t){return e.exists===t.exists&&e.hash===t.hash&&(e.identity===void 0?t.identity===void 0:t.identity!==void 0&&_t(e.identity,t.identity))}function wt(e){return{dev:e.dev,ino:e.ino,size:e.size,mtimeMs:e.mtimeMs,mode:e.mode&511}}function _t(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.size===t.size&&e.mtimeMs===t.mtimeMs&&e.mode===t.mode}function Pt(e){return e.exists?e.hash.slice(0,12):"<absent>"}var $=".scipquery.json",Nt=2e3,jt=5e3,be=jt,Mt=15*6e4,ve={enabled:!0,windowMs:15*6e4,maxRebuilds:2,maxEstimatedWriteBytes:1024*1024*1024},ar={enabled:!1,autoStart:!1,allowExpensiveRebuild:!1,debounceMs:Nt,cooldownMs:be,gitPollMs:2e3,idleTimeoutMs:Mt,autoRefresh:!0,ignore:[],resourceBudget:ve};var to=new Set(L);function te(e){let t=At(e,$);if(!or(t))return{};let n;try{n=Je(t,{maxBytes:$e,inputKind:"scip-query project config"})}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`unable to read ${$} at ${t}: ${i}`,{cause:r})}return Dt(le(n),t,"read").config}function Vt(e){return{...ar,...e.watch,cooldownMs:Math.max(jt,e.watch?.cooldownMs??be),resourceBudget:{...ve,...e.watch?.resourceBudget}}}function cr(e,t){return dr(e,t).configPath}function dr(e,t){let n=At(e,$),r=sr(),i={collaborationDomainId:r,languages:t,watch:{enabled:!0,debounceMs:Nt,cooldownMs:be,gitPollMs:2e3,idleTimeoutMs:Mt,autoRefresh:!0,resourceBudget:{...ve}}},o=Tt(n,s=>{if(!s.revision.exists)return{kind:"write",text:pe(i)};let a=ur(s,i);return a.config.collaborationDomainId?{kind:"unchanged"}:{kind:"write",text:pe({...a.config,collaborationDomainId:r})}});return{configPath:n,changed:o.changed}}function ur(e,t){if(!e.revision.exists)return{config:Y(t),needsMigration:!0};let n=Dt(le(e.text),e.path,"update");return{config:n.config,needsMigration:n.needsMigration}}function Dt(e,t,n){if(e.kind==="legacy"||e.kind==="supported")return e;if(e.kind==="malformed"){let i=n==="read"?`invalid ${$} at ${t}: ${e.reason}`:`Cannot update ${t}: the latest project config is ${e.reason}.`;throw new Error(`${i} The file was left untouched.`)}let r=n==="read"?`invalid ${$} at ${t}`:`Cannot update ${t}: the latest project config is invalid`;throw new Error(`${r} (unsupported ${e.direction} schemaVersion ${e.schemaVersion}; this scip-query reads legacy v${E} and current v${T}). Upgrade scip-query before retrying; the file was left untouched.`)}import{existsSync as we,lstatSync as Cr,statSync as Yt,watch as br}from"fs";import{EventEmitter as vr}from"events";import{basename as Rr,dirname as Qt,isAbsolute as Pe,join as y,relative as zt,resolve as Xt}from"path";import{watch as Sr}from"chokidar";import xr from"ignore";function Re(e){let t=JSON.stringify(e);return Buffer.byteLength(t)<=65536?t:void 0}import{existsSync as Lt,lstatSync as lr}from"fs";import{resolve as pr}from"path";function Ft(e,t,n,r={}){let i=new Date().toISOString();if(!Lt(n.dbPath))return{state:"missing",checkedAt:i,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!Lt(n.metaPath))return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let o=U(v(n.metaPath,"reindex metadata"));if(o.kind==="unsupported")return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Reindex metadata version ${o.version} is unsupported by this scip-query build.`,remedy:"Upgrade scip-query or run: scip-query reindex"};if(o.kind==="malformed")return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Could not decode reindex metadata: ${o.reason}`,remedy:"Run: scip-query reindex"};let s=o.metadata,a=t.languages??dt(e),c=s.fingerprint,d=n.cacheDir&&r.gitContext&&ue(r.gitContext,n.cacheDir,c)?c:void 0,l=n.cacheDir&&r.gitContext&&d&&fr(d,a,t)&&mr(e,d,t)?r.gitObservation?.context===r.gitContext?r.gitContext:ze(r.gitContext):void 0,u=r.gitObservation&&r.gitObservation.context===r.gitContext?r.gitObservation.projectFileInventorySequence:void 0,h=l?.clean&&Xe(e,void 0,{cachedInventoryAfterSequence:u})?l:void 0,m=n.cacheDir&&h&&d&&ue(h,n.cacheDir,d)?d:hr(e,a,t),O=[...s.indexedLanguages??[]].sort(),V=o.capabilities.publishableGeneration&&Fe(B(s.fingerprint),m)&&JSON.stringify(O)===JSON.stringify(m.languages),P=ht(n.dbPath,n.metaPath),Me=P.state==="invalid"||P.state==="drifted",se=V?pt(n.dbPath,m,O):void 0,Ve=se?.state==="incomplete",De=V&&!Me&&!Ve;return{state:De?"fresh":"stale",checkedAt:i,metaPath:n.metaPath,updatedAt:s.updatedAt,lastRefresh:s.lastRefresh,reason:Me?`SQLite generation requires repair: ${P.reason}`:Ve?`SQLite generation is missing ${se.missingDocumentCount} indexed source document(s): ${se.missingPaths.join(", ")}`:V?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:De?void 0:"Run: scip-query reindex"}}catch(o){return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Could not read reindex metadata: ${o instanceof Error?o.message:String(o)}`,remedy:"Run: scip-query reindex"}}}function hr(e,t,n){return ot(e,t,{pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:n.indexer?.typescript?.projectMode,typescriptProjects:n.indexer?.typescript?.projects,clojureConfigPath:n.indexer?.clojure?.configPath})}function fr(e,t,n){let r=gr(t,n);return e.version===r.version&&JSON.stringify([...e.languages].sort())===JSON.stringify(r.languages)&&e.pnpmWorkspaces===r.pnpmWorkspaces&&e.typescriptProjectMode===r.typescriptProjectMode&&JSON.stringify([...e.typescriptProjects].sort())===JSON.stringify(r.typescriptProjects)&&e.clojureConfigPath===r.clojureConfigPath}function mr(e,t,n){if(!(t.languages.includes("typescript")||!!t.clojureConfigPath))return!0;let i=it(e);if(t.clojureConfigPath){let o=Le(t.clojureConfigPath);if(!i.includes(o))return!1;try{if(!lr(pr(e,o)).isFile())return!1}catch{return!1}}return!t.languages.includes("typescript")||nt(e,n.indexer?.typescript?.projectMode,n.indexer?.typescript?.projects??[],i)}function gr(e,t){return K(e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}var Zt=5e3,Oe=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(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=Vt(t.config),this.outputDb=t.outputDb??y(rt(this.projectRoot,t.config),"index.db"),this.preferFilesystemGitState=t.gitReader===void 0,this.localCacheWatchPath=qr(this.projectRoot,Qt(this.outputDb)),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=t.config.indexer?.typescript?.projectMode,this.typescriptProjects=t.config.indexer?.typescript?.projects,this.clojureConfigPath=t.config.indexer?.clojure?.configPath,this.indexerConcurrency=t.config.indexerConcurrency,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onReindexError=t.onReindexError??(()=>{}),this.onRefreshSuppressed=t.onRefreshSuppressed??(()=>{}),this.onError=t.onError??(n=>console.error(n.message)),this.clock=t.clock??wr,en.set(this,Hr(t.stopTimeoutMs??Zt,"watcher stop timeout")),this.reindexRunner=t.reindexRunner??on(),this.subscriptionFactory=t.subscriptionFactory??Pr,this.budgetInspector=t.budgetInspector??lt,this.publishedGeneration=t.publishedGeneration??ce,this.indexFreshness=t.indexFreshness??Ur,this.lastObservedGeneration=this.readPublishedGeneration(),tn.set(this,{projectRoot:t.projectRoot,config:t.config,gitReader:t.gitReader??Qe,languages:sn(t.languages??t.config.languages),typeScriptInputPaths:null,stagedIndexEntries:null}),this.gitignoreFilter=st(t.projectRoot),this.extraIgnore=xr(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore),xe(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(t){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}}stop(){if(this.stopPromise)return this.stopPromise;this.stopped=!0,this.stopInProgress=!0;let t=this.fsWatchers;this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearBudgetTimer(),this.clearGitPollTimer(),this.clearReconcileTimer();let n=this.activeOperation;n&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"});let r=[...re(this).closures],i=Or(this),o=this.clock.now()+i;return this.stopPromise=this.finishStop(t,r,n,o,i).catch(s=>{throw this.stopInProgress=!1,s}),this.stopPromise}requestRefresh(t,n={}){if(!this.stopped){if(this.markPendingChangesIncomplete(`unstructured-trigger:${t.kind}`),!n.immediate||this.reindexInFlight||this.status.state==="cooldown"||this.status.state==="budget-paused"){this.scheduleReindex(t);return}this.pendingTrigger=Se(this.pendingTrigger,t),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}}startSourceWatcher(t=!1){let n=this.subscriptionFactory(this.projectRoot,{ignoreInitial:!0,ignored:(r,i)=>this.isIgnoredWatchPath(r,i?.isDirectory()??!1),usePolling:t,ignorePermissionErrors:!0,...t?{interval:5e3,binaryInterval:1e4}:{}});n.on("all",(r,i)=>{!this.stopped&&r!=="addDir"&&r!=="unlinkDir"&&this.handleFileChange(r,i)}),n.on("error",r=>this.handleSourceWatcherError(n,r,t)),this.fsWatchers.push(n)}handleSourceWatcherError(t,n,r){if(this.markPendingChangesIncomplete("source-watcher-error"),r||this.sourcePollingFallbackStarted||!Wr(n)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`));return}this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(i=>i!==t),Er(re(this),t,i=>this.onError(i));try{this.startSourceWatcher(!0)}catch(i){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(i)}`))}}isIgnoredWatchPath(t,n){let r=this.relativeWatchPath(t);if(!r)return!1;if(Jt(r,this.localCacheWatchPath))return!0;let i=n?`${r}/`:r;return this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)}handleFileChange(t,n){let r=this.relativeWatchPath(n);if(!r||r===".."||r.startsWith("../")||Jt(r,this.localCacheWatchPath)||this.gitignoreFilter.isIgnored(r)||this.extraIgnore.ignores(r)||r.endsWith("index.db")||r.endsWith("index.scip")||r.endsWith("index.db.tmp")||Rr(r).startsWith(ut))return;r===".scipquery.json"&&qt(this,this.projectRoot);let i=Ht(this,t,r);i!==null&&(i||this.markPendingChangesIncomplete(`unsupported-source-event:${t}`),this.scheduleReindex({kind:"watch-source",detail:r},i?[{path:r,kind:i}]:void 0,i!==void 0))}relativeWatchPath(t){let n=Pe(t)?t:y(this.projectRoot,t);return zt(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t,n,r=!1){this.pendingTrigger=Se(this.pendingTrigger,t),r||this.markPendingChangesIncomplete(`unstructured-trigger:${t.kind}`);for(let o of n??[])this.recordPendingChange(o);if(this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});let o=this.activeOperation;o&&_.get(this)!==o&&(_.set(this,o),o.cancel().then(s=>{s.state==="degraded"&&!this.stopped&&this.onError(new Error(s.reason))},s=>{this.stopped||this.onError(s instanceof Error?s:new Error(String(s)))}));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 i=this.wallNow()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:i}),this.debounceTimer=this.clock.setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped||this.reconcileExternalPublication())return;let t=this.inspectBudget(),n=this.watchConfig.allowExpensiveRebuild&&t.state!=="paused";if(t.state==="paused"&&t.reason!=="rebuild-count"){this.dirty=!0;let c=Math.max(this.wallNow()+1,t.until);this.setStatus({state:"budget-paused",until:c,dirty:!0,reason:t.detail,rebuilt:t.rebuilt,estimatedWriteBytes:t.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 r=this.clock.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&r<this.watchConfig.cooldownMs){let c=this.watchConfig.cooldownMs-r;this.dirty=!0;let d=this.wallNow()+c;this.setStatus({state:"cooldown",until:d,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 i=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let o=this.consumePendingChangeJournal(),s=this.wallNow();this.setStatus({state:"indexing",startedAt:s});let a=this.reindexRunner.start(this.reindexRequest(i,n,o));this.activeOperation=a,a.completion.then(c=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),ne.set(this,0),this.stopped)return;if(_.get(this)===a){if(this.restorePendingChangeJournal(o),this.dirty){let l=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:l,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}xe(this),this.lastObservedGeneration=this.readPublishedGeneration();let d=!1;try{d=this.onReindexComplete(c,i,{pendingChanges:this.dirty})===!0}catch(l){this.onError(l instanceof Error?l:new Error(String(l)))}if(this.dirty&&!this.stopped){if(d){let u=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.resetPendingChanges(),this.onRefreshSuppressed(u),this.setStatus({state:"idle"});return}let l=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:l,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 d=c instanceof Error?c:new Error(String(c));this.restorePendingChangeJournal(o);let l=rn(d),u=0;if(l?(u=(ne.get(this)??0)+1,ne.set(this,u),this.dirty=!0,this.pendingTrigger=Se(this.pendingTrigger,i)):ne.set(this,0),!l&&_.get(this)!==a&&(this.onReindexError(d,i),this.onError(d)),this.dirty){let h=l?Vr(this.watchConfig.cooldownMs,u):this.watchConfig.cooldownMs,m=this.wallNow()+h;this.setStatus({state:"cooldown",until:m,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===a&&(this.activeOperation=null),_.get(this)===a&&_.delete(this)})}async finishStop(t,n,r,i,o){let s=[],a=t.map(async h=>{try{await h.close()}catch(m){s.push(`watch subscription close failed: ${String(m)}`)}});a.push(...n),r&&a.push((async()=>{try{let h=await r.cancel();h.state==="degraded"&&s.push(h.reason)}catch(h){s.push(`reindex cancellation failed: ${h instanceof Error?h.message:String(h)}`)}})());let c=a.length,d=a.map(h=>h.finally(()=>{c-=1})),l=await Ir(d,i,this.clock),u=re(this);return s.push(...u.errors),u.errors=[],l?this.stopInProgress=!1:(s.push(`watch shutdown exceeded the ${o}ms deadline with ${c} operation(s) still pending`),Promise.all(d).then(()=>{this.stopInProgress=!1})),s.length>0?(this.setStatus({state:"draining",startedAt:this.wallNow(),reason:s.join("; ")}),{state:"degraded",reasons:s}):(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(t){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: ${t instanceof Error?t.message:String(t)}`}}}reindexRequest(t,n=!0,r){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:t,changeJournal:r,allowExpensiveRebuild:n}}setStatus(t){this.status=t,t.state==="cooldown"||t.state==="budget-paused"?this.armReconcileTimer(t.until):this.clearReconcileTimer(),this.onStatus(t)}recordPendingChange(t){if(this.pendingChanges.size>=1024&&!this.pendingChanges.has(t.path)){this.pendingChanges.clear(),this.markPendingChangesIncomplete("change-entry-limit");return}let n=this.pendingChanges.get(t.path),r=Lr(n,t.kind);r===null?this.pendingChanges.delete(t.path):this.pendingChanges.set(t.path,r)}markPendingChangesIncomplete(t){this.pendingChangesComplete=!1,this.pendingChangesIncompleteReason??=t}consumePendingChangeJournal(){let t=ce(this.outputDb),n=[...this.pendingChanges.entries()].map(([s,a])=>({path:s,kind:a})).sort((s,a)=>s.path.localeCompare(a.path)),r=this.pendingChangesComplete,i=this.pendingChangesIncompleteReason;t||(r=!1,i??="accepted-generation-unavailable");let o={version:1,baseGeneration:t,complete:r,...i?{incompleteReason:i}:{},entries:n};return Re(o)||(o={version:1,baseGeneration:t,complete:!1,incompleteReason:"change-journal-byte-limit",entries:[]}),this.resetPendingChanges(),o}restorePendingChangeJournal(t){let n=[...this.pendingChanges.entries()].map(([o,s])=>({path:o,kind:s})),r=this.pendingChangesComplete,i=this.pendingChangesIncompleteReason;this.resetPendingChanges(),t.complete||this.markPendingChangesIncomplete(t.incompleteReason??"failed-reindex");for(let o of t.entries)this.recordPendingChange(o);r||this.markPendingChangesIncomplete(i??"failed-reindex");for(let o of n)this.recordPendingChange(o)}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&&(S(this).stagedIndexEntries=Kt(this.projectRoot,S(this).gitReader),this.gitPollTimer=this.clock.setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}armReconcileTimer(t){this.clearReconcileTimer();let n=t-this.wallNow();if(n<=0||!(this.watchConfig.gitPollMs>0))return;let r=Math.min(this.watchConfig.gitPollMs,n);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)},r),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 n=this.readPublishedGeneration();if(n===null||n===this.lastObservedGeneration)return!1;this.lastObservedGeneration=n;let r;try{r=this.indexFreshness(this.projectRoot,this.config,this.outputDb)}catch{return!1}if(r!=="fresh")return!1;let i=this.pendingTrigger??{kind:"unknown"};return this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearBudgetTimer(),this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.resetPendingChanges(),xe(this),this.onRefreshSuppressed({...i,detail:`a generation published outside the watcher is fresh${i.detail?` (${i.detail})`:""}`}),this.setStatus({state:"idle"}),!0}pollGitState(){if(this.reindexInFlight||this.stopped)return;let t=this.lastGitState,n=this.readGitState();if(!t||!n||this.stopped){this.lastGitState=n;return}this.lastGitState=n;let r=t.head!==n.head,i=t.indexPath!==n.indexPath||t.indexMtimeMs!==n.indexMtimeMs||t.indexSize!==n.indexSize;if(!r&&!i)return;let o=S(this),s=o.stagedIndexEntries,a=Kt(this.projectRoot,o.gitReader);o.stagedIndexEntries=a;let c=zr(this.projectRoot,o.gitReader,t,n,s,a,r,i),d=null;if(c!==null&&(c.includes(".scipquery.json")&&qt(this,this.projectRoot),d=c.filter(u=>Ht(this,"add",u)!==null),d.length===0))return;let l=d?.map(u=>({path:u,kind:we(y(this.projectRoot,u))?"change":"delete"}));r&&i?this.scheduleReindex({kind:"watch-git-state",detail:Ie("HEAD and index changed",d)},l,l!==void 0):r?this.scheduleReindex({kind:"watch-git-head",detail:Ie("HEAD changed",d)},l,l!==void 0):i&&this.scheduleReindex({kind:"watch-git-index",detail:Ie(n.indexPath??"index changed",d)},l,l!==void 0)}readGitState(){if(this.preferFilesystemGitState){let t=this.readFilesystemGitState();if(t)return t}return this.readGitStateFromGit()}readFilesystemGitState(){let t=this.watchGitLayout??$r(this.projectRoot);if(!t)return null;this.watchGitLayout=t;let n=Gr(t.gitDir);return n?Ut(n,t.indexPath):null}readGitStateFromGit(){let t=S(this).gitReader,n=de(this.projectRoot,["rev-parse","--git-path","index"],t);if(!n)return null;let r=Ze(this.projectRoot,n);return Ut(de(this.projectRoot,["rev-parse","--verify","HEAD"],t),r)}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};async function Ir(e,t,n){if(e.length===0)return!0;let r=Promise.all(e).then(()=>!0),i=Math.max(0,t-n.now()),o=null,s=new Promise(c=>{o=n.setTimeout(()=>c(!1),i)}),a=await Promise.race([r,s]);return a&&o&&n.clearTimeout(o),a}var $t=new WeakMap,en=new WeakMap,tn=new WeakMap,_=new WeakMap,ne=new WeakMap;function re(e){let t=$t.get(e);if(t)return t;let n={closures:new Set,errors:[]};return $t.set(e,n),n}function Or(e){return en.get(e)??Zt}function S(e){let t=tn.get(e);if(!t)throw new Error("Watcher input state was not initialized.");return t}function Er(e,t,n){let r=Promise.resolve().then(()=>t.close()).catch(i=>{let o=`watch subscription close failed during polling fallback: ${String(i)}`;e.errors.push(o),n(new Error(o))});e.closures.add(r),r.then(()=>e.closures.delete(r))}function nn(e,t=Ue){let{projectRoot:n,config:r,languages:i,pnpmWorkspaces:o,typescriptProjectMode:s,typescriptProjects:a,clojureConfigPath:c,indexerConcurrency:d,trigger:l}=e,u=te(n),h=Object.keys(u).length>0?u:r,m=H(n,h),O=h.indexer?.typescript,V=h.indexer?.clojure,P=t(process.pid);if(!P)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:n,SCIP_REINDEX_OUTPUT_SCIP:m.indexPath,SCIP_REINDEX_OUTPUT_DB:m.dbPath,SCIP_REINDEX_LANGUAGES:(h.languages??i)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(h.indexerConcurrency??d??""),SCIP_REINDEX_PNPM_WORKSPACES:O?.pnpmWorkspaces??o?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:O?.projectMode??s,projects:O?.projects??a??[],maxHeapMb:O?.maxHeapMb}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:V?.configPath??c??"",SCIP_REINDEX_TRIGGER_KIND:l.kind,SCIP_REINDEX_TRIGGER_DETAIL:l.detail??"",SCIP_REINDEX_CHANGE_JOURNAL:e.changeJournal?Re(e.changeJournal)??"":"",SCIP_REINDEX_ALLOW_EXPENSIVE:e.allowExpensiveRebuild===!1?"0":"1",SCIP_REINDEX_PROCESS_GROUP_LEADER:"1",SCIP_REINDEX_PARENT_IDENTITY:JSON.stringify(P)}}}var wr={now:q,wallNow:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Pr=(e,t)=>kr(process.platform,t.usePolling)?new Ee(e):Sr(e,t);function kr(e,t){return e==="darwin"&&t!==!0}var G=class extends Error{constructor(t,n){super(t,n===void 0?void 0:{cause:n}),this.name="RecursiveSourceWatchError"}},Ee=class{events=new vr;watcher;constructor(t){this.watcher=br(t,{recursive:!0},(n,r)=>{if(r===null){this.events.emit("error",new G("Recursive source watcher omitted the changed path."));return}let i=y(t,r.toString());this.events.emit("all",Tr(n,i),i)}),this.watcher.on("error",n=>{this.events.emit("error",new G(`Recursive source watcher failed: ${n.message}`,n))})}on=(t,n)=>(this.events.on(t,n),this);close(){this.watcher.close()}};function Tr(e,t){return e==="change"?"change":we(t)?Yt(t).isDirectory()?"addDir":"add":"unlink"}var _r=15*6e4,Ar=1e3,Nr=64*1024;function jr(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function Gt(e,t){let n=e instanceof Error?e.message:String(e),r=t.stderrTail.trim()||t.stdoutTail.trim();return r?`${n}
3
- ${r}`:n}function Mr(e,t){return Object.assign(new Error(e,t===void 0?void 0:{cause:t}),{retryable:!0})}function rn(e){return e instanceof Error&&"retryable"in e&&e.retryable===!0}function Vr(e,t){let n=e*2**Math.min(5,Math.max(0,t-1));return Math.max(e,Math.min(3e4,n))}function on(e={}){let t=e.timeoutMs??_r,n=e.terminationGraceMs??Ar,r=e.maxOutputBytes??Nr,i=e.resolveLaunch??nn;return{start(o){let s=i(o),a=new AbortController,c=jr(),d=!1,l=ct({command:process.execPath,args:[...process.execArgv,s.workerPath],label:"watch reindex worker",env:s.env,timeoutMs:t,terminationGraceMs:n,maxStdoutBytes:r,maxStderrBytes:r,outputLimitBehavior:"truncate-tail",signal:a.signal,detached:!0}).then(u=>{if(c={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated},u.status!==0){let h=Gt(new Error(`Reindex worker exited with ${u.signal?`signal ${u.signal}`:`code ${u.status}`}`),c);throw u.status===75?Mr(h):new Error(h)}return u.durationMs}).catch(u=>{throw rn(u)?u:(u instanceof at&&(c={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated}),new Error(Gt(u,c),{cause:u}))}).finally(()=>{d=!0});return{completion:l,async cancel(){d||a.abort();try{await l}catch{}return{state:"exited",diagnostics:c}},diagnostics:()=>c}}}}function Se(e,t){return e?e.kind===t.kind?e.detail===t.detail?e:{kind:e.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${e.kind}, ${t.kind}`}:t}function Dr(e){if(e==="add")return"add";if(e==="change")return"change";if(e==="unlink")return"delete"}function Lr(e,t){return e?e==="add"?t==="delete"?null:"add":e==="delete"&&t==="add"?"change":t:t}function Fr(e){return e instanceof Error&&"code"in e&&e.code==="EMFILE"||String(e).includes("EMFILE: too many open files")}function Wr(e){return e instanceof G||Fr(e)}var ke=/^[0-9a-f]{40,64}$/i;function Jt(e,t){return e===".git"||e.startsWith(".git/")||e==="node_modules"||e.startsWith("node_modules/")||e.endsWith("/node_modules")||e.includes("/node_modules/")?!0:t!==void 0&&(e===t||e.startsWith(`${t}/`))}function $r(e){let t=y(e,".git");try{let n=Cr(t),r;if(n.isDirectory())r=t;else if(n.isFile()){let i=/^gitdir:\s*(.+)\s*$/m.exec(v(t,"Git directory marker"));if(!i?.[1])return null;let o=i[1].trim();r=Pe(o)?o:Xt(e,o)}else return null;return we(r)?{gitDir:r,indexPath:y(r,"index")}:null}catch{return null}}function Gr(e){let t;try{t=v(y(e,"HEAD"),"Git HEAD").trim()}catch{return}if(ke.test(t))return t.toLowerCase();let n=/^ref:\s*(.+)$/.exec(t)?.[1]?.trim();if(!n)return;let r=Jr(e);return Bt(e,n)??Bt(r,n)??Br(r,n)}function Jr(e){try{let t=v(y(e,"commondir"),"Git common-directory marker").trim();return t?Pe(t)?t:Xt(e,t):e}catch{return e}}function Bt(e,t){try{let n=v(y(e,t),"Git reference").trim();return ke.test(n)?n.toLowerCase():void 0}catch{return}}function Br(e,t){try{for(let n of v(y(e,"packed-refs"),"Git packed references").split(`
4
- `)){if(n.startsWith("#")||n.startsWith("^"))continue;let r=n.indexOf(" ");if(r===-1)continue;let i=n.slice(0,r);if(n.slice(r+1).trim()===t&&ke.test(i))return i.toLowerCase()}}catch{return}}function Ur(e,t,n){let r=Qt(n);return Ft(e,t,{dbPath:n,metaPath:y(r,"meta.json"),cacheDir:r}).state}function Ut(e,t){let n={head:e,indexPath:t};try{let r=Yt(t);n.indexMtimeMs=r.mtimeMs,n.indexSize=r.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}function qr(e,t){let n=zt(e,t).replaceAll("\\","/");if(!(!n||n===".."||n.startsWith("../")))return n}function Hr(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`${t} must be a positive integer.`);return e}function sn(e){return e&&e.length>0?[...e]:L}function qt(e,t){try{let n=S(e);n.config=te(t),n.languages=sn(n.config.languages)}catch{S(e).languages=L}}function Ht(e,t,n){let r=S(e);if(ae(n,r.languages)==="other")return null;let o=Dr(t);if(n===".scipquery.json"||et(n))return r.typeScriptInputPaths=null,o;if(!Kr(n,r.languages))return o;let s=r.typeScriptInputPaths;if(!s)return o;let a=s.has(n);if(o!=="add")return a?o:null;if(a)return"change";let c=an(e);return c?c.has(n)?"add":null:o}function xe(e){let t=S(e);if(!t.languages.includes("typescript")){t.typeScriptInputPaths=null;return}let n=Yr(t.projectRoot,t.config,t.languages);t.typeScriptInputPaths=n??an(e)}function an(e){let t=S(e);if(!t.languages.includes("typescript"))return t.typeScriptInputPaths=null,null;try{let n=t.config.indexer?.typescript,r=tt(t.projectRoot,n?.projectMode,n?.projects);return t.typeScriptInputPaths=r,r}catch{return t.typeScriptInputPaths=null,null}}function Kr(e,t){if(!t.includes("typescript"))return!1;let n=ae(e,["typescript","javascript"]);return n==="source"||n==="ambient"}function Yr(e,t,n){try{let r=U(v(H(e,t).metaPath,"reindex metadata"));if(r.kind!=="supported"&&r.kind!=="legacy")return null;let i=B(r.metadata.fingerprint);return!i||!Qr(i,n,t)?null:new Set(i.files.map(o=>o.path))}catch{return null}}function Qr(e,t,n){let r=K(t,{pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:n.indexer?.typescript?.projectMode,typescriptProjects:n.indexer?.typescript?.projects,clojureConfigPath:n.indexer?.clojure?.configPath});return e.version===r.version&&JSON.stringify([...e.languages].sort())===JSON.stringify(r.languages)&&e.pnpmWorkspaces===r.pnpmWorkspaces&&e.typescriptProjectMode===r.typescriptProjectMode&&JSON.stringify([...e.typescriptProjects].sort())===JSON.stringify(r.typescriptProjects)&&e.clojureConfigPath===r.clojureConfigPath}function zr(e,t,n,r,i,o,s,a){let c=new Set;if(s){if(!n.head||!r.head)return null;let d=t.runResult(e,["diff","--name-only","-z","--no-renames","--relative",n.head,r.head,"--"]);if(d.kind!=="success")return null;for(let l of Xr(d.output))c.add(l)}if(a){if(i===null||o===null)return null;for(let d of ei(i,o))c.add(d)}return[...c].sort()}function Kt(e,t){let n=t.runResult(e,["diff","--cached","--raw","-z","--no-renames","--relative","--"]);return n.kind==="success"?Zr(n.output):null}function Xr(e){return e.split("\0").filter(t=>t.length>0)}function Zr(e){let t=e.split("\0");if(t.at(-1)===""&&t.pop(),t.length%2!==0)return null;let n=new Map;for(let r=0;r<t.length;r+=2){let i=t[r],o=t[r+1];if(!i.startsWith(":")||!o)return null;n.set(o,i)}return n}function ei(e,t){return[...new Set([...e.keys(),...t.keys()])].filter(r=>e.get(r)!==t.get(r))}function Ie(e,t){return t===null?`${e}; changed paths unavailable`:t.length===0?e:t.length===1?t[0]:`${t.length} compiler inputs changed`}import{existsSync as Te,mkdirSync as ti,symlinkSync as ni,readlinkSync as cn,unlinkSync as dn,readdirSync as ri}from"fs";import{join as A,dirname as _e,resolve as N,relative as ii,isAbsolute as oi}from"path";import{homedir as si,platform as ai}from"os";import{fileURLToPath as ci}from"url";var di=ai()==="win32";var un=["scip-query","scip-plan","scip-setup","scip-integrity-audit","scip-explore","concrete-plan"];function ui(e={}){let t=e.quiet?()=>{}:console.log,n=ci(import.meta.url),r=N(_e(n),"..","skills"),i=e.homeDir??process.env.SCIP_QUERY_SKILLS_HOME??si(),o=[A(i,".claude","skills"),A(i,".codex","skills"),A(i,".agents","skills")],s={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let a of o){let c=_e(a);if(!Te(c))continue;ti(a,{recursive:!0});let d=hi(a);li(a,r,d,s,t);for(let l of un){let u=A(r,l),h=A(a,l);if(!Te(u)){s.skipped.push(`${d}/${l}`);continue}if(Te(h)){try{let m=cn(h);if(N(m)===N(u)){s.alreadyLinked.push(`${d}/${l}`),t(` ok: ${l} \u2192 ${d} (already linked)`);continue}}catch{s.skipped.push(`${d}/${l}`),t(` skip: ${l} \u2192 ${d} (exists, not a symlink)`);continue}dn(h)}ni(u,h,di?"junction":"dir"),s.installed.push(`${d}/${l}`),t(` done: ${l} \u2192 ${d}`)}}return s}function li(e,t,n,r,i){let o=new Set(un);for(let s of ri(e)){if(o.has(s))continue;let a=A(e,s),c;try{c=N(_e(a),cn(a))}catch{continue}pi(c,t)&&(dn(a),r.pruned.push(`${n}/${s}`),i(` prune: ${s} \u2192 ${n} (removed stale scip-query skill link)`))}}function pi(e,t){let n=ii(N(t),N(e));return n===""||!n.startsWith("..")&&!oi(n)}function hi(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}var ln=["repository-observation","repository-preview","mutation","composite","environment-observation","tool-information"];function fi(e,t=[]){return{defaultRole:e,...t.length>0?{rules:t}:{}}}function mi(e,t){for(let n of e.rules??[]){if(n.when.kind==="option-present"){let i=t.options[n.when.name];if(i!==void 0&&i!==!1)return n.role;continue}if((n.when.kind==="argument"?t.args[n.when.index]:t.options[n.when.name])===n.when.equals)return n.role}return e.defaultRole}function gi(e){return[...new Set([e.defaultRole,...(e.rules??[]).map(t=>t.role)])]}function ie(e){return ln.includes(e)}function yi(e){return e==="repository-observation"||e==="repository-preview"||e==="composite"}var Ae=1,Ne=1,oe=["compiler-graph","semantic-analysis","repository-source","change-history","runtime-measurement","heuristic","mixed","unknown"],pn=["complete","partial","unknown"],hn=["validated","failed","not-evaluated","not-applicable"],fn=["observe","advise","require-adjudication","block","not-established"],mn={policyId:"scip-query:unresolved-repository-policy",policyVersion:Ne,permission:"not-established",reasons:["No repository action policy was supplied for this claim."]};function Ci(e){return{schemaVersion:Ae,origin:e.contract.origin,coverage:gn(e.coverage),producerValidation:e.contract.producerValidation,stateAuthority:X(e.receipt,e.receipt),repositoryPolicy:e.repositoryPolicy??mn,...e.contract.families?{families:e.contract.families}:{}}}function gn(e){return e?e.complete===!0?{state:"complete",returned:e.returned,totalKnown:!0,total:e.total??e.returned,omitted:0}:e.totalKnown?{state:"partial",returned:e.returned,totalKnown:!0,...e.total===void 0?{}:{total:e.total},...e.omitted===void 0?{}:{omitted:e.omitted}}:{state:"unknown",returned:e.returned,totalKnown:!1}:{state:"unknown",returned:0,totalKnown:!1}}function bi(e,t){let n=[];return J(n,"origin",t.origins,e.origin),J(n,"coverage",t.coverage,e.coverage.state),J(n,"producer-validation",t.producerValidation,e.producerValidation.status),J(n,"state-authority",t.stateAuthority,e.stateAuthority.authority),J(n,"action-permission",t.actionPermission,e.repositoryPolicy.permission),{satisfied:n.every(r=>r.satisfied),predicates:n}}function J(e,t,n,r){n&&e.push({predicate:t,satisfied:n.includes(r),required:n,actual:r})}function je(e){return!p(e)||e.schemaVersion!==Ae||!j(e.origin,oe)||!vi(e.coverage)||!Ri(e.producerValidation)||!Si(e.stateAuthority)||!xi(e.repositoryPolicy)?!1:e.families===void 0||Ii(e.families)}function vi(e){return!p(e)||!j(e.state,pn)||!k(e.returned)||typeof e.totalKnown!="boolean"||e.total!==void 0&&!k(e.total)||e.omitted!==void 0&&!k(e.omitted)?!1:e.state==="complete"?e.totalKnown===!0&&e.total===e.returned&&e.omitted===0:e.state==="partial"?e.totalKnown===!0&&k(e.total)&&k(e.omitted)&&e.total===Number(e.returned)+Number(e.omitted):e.totalKnown===!1}function Ri(e){if(!p(e)||!j(e.status,hn))return!1;let t=e.certification;return e.status==="validated"||e.status==="failed"?p(t)&&C(t.id)&&Number.isSafeInteger(t.version)&&Number(t.version)>0&&C(t.corpus):t===void 0}function Si(e){return p(e)&&Number.isSafeInteger(e.policyVersion)&&(e.authority==="completion"||e.authority==="advisory"||e.authority==="none")&&Array.isArray(e.requiredRelationships)&&e.requiredRelationships.every(C)&&Array.isArray(e.reasons)&&e.reasons.every(C)}function xi(e){return p(e)&&C(e.policyId)&&e.policyVersion===Ne&&j(e.permission,fn)&&Array.isArray(e.reasons)&&e.reasons.every(C)}function Ii(e){return Array.isArray(e)&&e.every(t=>p(t)&&C(t.id)&&C(t.selector)&&Oi(t.origin))}function Oi(e){return p(e)?e.kind==="fixed"?j(e.origin,oe)&&e.origin!=="mixed":e.kind!=="result-field"||!C(e.field)||!p(e.values)?!1:Object.values(e.values).every(t=>j(t,oe)&&t!=="mixed"):!1}function j(e,t){return typeof e=="string"&&t.includes(e)}var bn="scip-query-result",vn=0,M=1,Ei=1,Rn=1,Sn=1;function xn(e){if(!p(e))return{kind:"malformed",reason:"CLI JSON output must be an object."};let t=Object.hasOwn(e,"kind"),n=Object.hasOwn(e,"schemaVersion");if(!t&&!n){let s=yn(e);return s?{kind:"malformed",reason:`Legacy CLI JSON envelope: ${s}`}:{kind:"legacy",schemaVersion:vn,envelope:e}}if(!t||!n)return{kind:"malformed",reason:"CLI JSON envelope must contain both kind and schemaVersion."};if(e.kind!==bn)return{kind:"malformed",reason:`Unsupported CLI JSON envelope kind: ${Ti(e.kind)}.`};let r=e.schemaVersion;if(!Number.isSafeInteger(r)||Number(r)<1)return{kind:"malformed",reason:"CLI JSON envelope schemaVersion must be a positive safe integer."};if(r!==M)return{kind:"unsupported",schemaVersion:Number(r),direction:Number(r)<M?"older":"future",...Cn(e.producer)?{producer:e.producer}:{}};let i=yn(e);if(i)return{kind:"malformed",reason:`CLI JSON envelope v1: ${i}`};if(!Cn(e.producer))return{kind:"malformed",reason:"CLI JSON envelope v1: producer must identify scip-query and its non-empty version."};if(!D(e.resultSchemaVersion))return{kind:"malformed",reason:"CLI JSON envelope v1: resultSchemaVersion must be a positive safe integer."};if(e.resultProjection!==void 0&&e.resultProjection!=="agent")return{kind:"malformed",reason:'CLI JSON envelope v1: resultProjection must be "agent" when present.'};let o=In(e.command);return o.includes(e.resultSchemaVersion)?e.evidenceContext!==void 0&&!ki(e.evidenceContext)?{kind:"malformed",reason:"CLI JSON envelope v1: evidenceContext must contain a supported receipt and analysis manifest."}:e.operationRole!==void 0&&!ie(e.operationRole)?{kind:"malformed",reason:"CLI JSON envelope v1: operationRole must be a supported command operation role."}:p(e.evidenceContext)&&e.operationRole!==void 0&&e.evidenceContext.operationRole!==void 0&&e.operationRole!==e.evidenceContext.operationRole?{kind:"malformed",reason:"CLI JSON envelope v1: top-level and evidence-context operation roles must agree."}:{kind:"supported",schemaVersion:M,envelope:e}:{kind:"unsupported-result",schemaVersion:M,command:e.command,resultSchemaVersion:e.resultSchemaVersion,supportedResultSchemaVersions:o}}function wi(e){let t=xn(e);if(t.kind==="legacy"||t.kind==="supported")return t;if(t.kind==="unsupported"){let n=t.producer?` from ${t.producer.name}@${t.producer.version}`:"";throw new Error(`Unsupported scip-query CLI JSON schemaVersion ${t.schemaVersion}${n}; this consumer supports the legacy unversioned envelope and schemaVersion ${M}.`)}throw t.kind==="unsupported-result"?new Error(`Unsupported resultSchemaVersion ${t.resultSchemaVersion} for scip-query command ${JSON.stringify(t.command)}; this consumer supports ${t.supportedResultSchemaVersions.join(", ")}.`):new Error(`Malformed scip-query CLI JSON envelope: ${t.reason}`)}function In(e){return Pi[e]??[Ei]}var Pi={};function yn(e){return typeof e.command!="string"||e.command.length===0?"command must be a non-empty string.":Array.isArray(e.args)?p(e.options)?Object.hasOwn(e,"result")?null:"result is required.":"options must be an object.":"args must be an array."}function Cn(e){return p(e)&&e.name==="scip-query"&&typeof e.version=="string"&&e.version.length>0}function ki(e){if(!p(e)||e.schemaVersion!==Rn||e.operationRole!==void 0&&!ie(e.operationRole)||!z(e.receipt))return!1;let t=e.analysisManifest;return p(t)&&t.schemaVersion===Sn&&(t.evidence===void 0||t.evidence==="graph-fact"||t.evidence==="heuristic"||t.evidence==="mixed")&&(t.claimQualification===void 0||je(t.claimQualification))}function Ti(e){return typeof e=="string"?JSON.stringify(e):String(e)}export{fn as CLAIM_ACTION_PERMISSIONS,Ne as CLAIM_ACTION_POLICY_VERSION,pn as CLAIM_COVERAGE_STATES,oe as CLAIM_ORIGINS,Ae as CLAIM_QUALIFICATION_SCHEMA_VERSION,Sn as CLI_ANALYSIS_MANIFEST_SCHEMA_VERSION,Rn as CLI_EVIDENCE_CONTEXT_SCHEMA_VERSION,bn as CLI_JSON_ENVELOPE_KIND,ln as COMMAND_OPERATION_ROLES,M as CURRENT_CLI_JSON_ENVELOPE_SCHEMA_VERSION,mn as DEFAULT_REPOSITORY_POLICY_ACTION,vn as LEGACY_CLI_JSON_ENVELOPE_SCHEMA_VERSION,f as LEGACY_OBSERVATION_RECEIPT_SCHEMA_VERSION,W as OBSERVATION_IDENTITY_CANONICALIZATION_VERSION,F as OBSERVATION_IDENTITY_HASH_ALGORITHM,Q as OBSERVATION_IDENTITY_SCHEMA_VERSION,I as OBSERVATION_RECEIPT_SCHEMA_VERSION,me as OBSERVATION_STATE_AUTHORITY_POLICY_VERSION,hn as PRODUCER_VALIDATION_STATUSES,Oe as Watcher,fi as commandOperation,gi as commandOperationRoles,ye as compareObservationReceipts,Ct as createObservationIdentity,on as createReindexRunner,xn as decodeCliJsonEnvelope,ge as decodeObservationReceipt,gn as deriveClaimCoverage,Ci as deriveClaimQualification,X as deriveObservationStateAuthority,bi as evaluateClaimQualification,En as getScipVersion,cr as initProjectConfig,ui as installSkills,je as isClaimQualificationV1,ie as isCommandOperationRole,z as isObservationReceipt,On as isScipInstalled,te as loadProjectConfig,bt as observationReceiptGenerationIdentity,Rt as observationReceiptStabilityLabel,vt as observationReceiptWorkspaceIdentity,yi as operationObservesRepository,wn as printScipInstallInstructions,wi as requireCompatibleCliJsonEnvelope,mi as resolveCommandOperationRole,H as resolveIndexStoragePaths,nn as resolveReindexWorkerLaunch,In as supportedCliResultSchemaVersions};
1
+ import{C as lt,D as pt,M as ht,O as ue,b as at,c as ct,i as On,j as En,k as wn,q as dt,z as ut}from"./chunk-ZHG4WAHR.js";import{a as st}from"./chunk-QXCKQTKR.js";import{c as qe,u as ce}from"./chunk-SYVJEEUJ.js";import{c as Ue,e as q,g as Ke,h as Ye}from"./chunk-QBQE7ZJ5.js";import"./chunk-DHEQMPLW.js";import"./chunk-KNLQGXVH.js";import{$ as Xe,C as $e,D as Ge,Ea as it,Ga as ot,I as Je,J as v,Ja as K,L as Be,T as He,X as Qe,_ as ze,aa as de,ba as Ze,f as Le,fa as et,g as ae,i as B,ia as tt,ja as nt,k as Fe,n as p,na as rt,p as b,q as k,r as D,s as We,sa as H,t as g,v as L,x as U}from"./chunk-JZ2A7LDM.js";import{existsSync as or}from"fs";import{randomUUID as sr}from"crypto";import{isAbsolute as Ki,join as At,relative as Yi,resolve as Qi}from"path";var E=1,T=2,Pn="./node_modules/scip-query/docs/schemas/project-config.schema.json";function le(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(a){return{kind:"malformed",reason:`invalid JSON: ${a instanceof Error?a.message:String(a)}`}}if(!p(t))return{kind:"malformed",reason:"project config must be a JSON object"};let n=t.schemaVersion;if(n!==void 0&&!Number.isInteger(n))return{kind:"malformed",reason:"schemaVersion must be an integer"};let r=n===void 0?E:n;if(r!==E&&r!==T)return{kind:"unsupported",schemaVersion:r,direction:r<E?"older":"future"};let i=t.$schema;if(i!==void 0&&(typeof i!="string"||i.trim()===""))return{kind:"malformed",reason:"$schema must be a non-empty string when present"};let o=Y(t),s=r!==T||typeof t.$schema!="string";return r===E?{kind:"legacy",sourceVersion:E,config:o,needsMigration:s}:{kind:"supported",sourceVersion:T,config:o,needsMigration:s}}function Y(e){let t=e,{$schema:n,schemaVersion:r,...i}=t;return{$schema:typeof n=="string"&&n.trim()!==""?n:Pn,schemaVersion:T,...i}}function pe(e){return`${JSON.stringify(Y(e),null,2)}
2
+ `}import{createHash as kn}from"crypto";var f=1,I=2,Q=1,W=1,F="sha256",me=1;function bt(e,t,n){if(!g(e)||!D(t))throw new Error("Observation identity requires a bounded projection name and positive projection version.");return{schemaVersion:Q,canonicalizationVersion:W,hashAlgorithm:F,projection:{name:e,version:t},digest:kn(F).update(Tn(e,t,n)).digest("hex")}}function Tn(e,t,n){return`{"canonicalizationVersion":${W},"projection":${JSON.stringify(e)},"projectionVersion":${t},"value":${JSON.stringify(n)}}`}function ge(e){if(!p(e))return{kind:"malformed",reason:"observation receipt must be an object"};let t=e.schemaVersion;if(!Number.isInteger(t))return{kind:"malformed",reason:"observation receipt schemaVersion must be an integer"};if(t===f)return Vn(e)?{kind:"legacy",schemaVersion:f,receipt:e}:{kind:"malformed",reason:"observation receipt v1 fields are malformed or contradictory"};if(t===I)return Dn(e)?{kind:"supported",schemaVersion:I,receipt:e}:{kind:"malformed",reason:"observation receipt v2 facts are malformed or contradictory"};let n=t;return{kind:"unsupported",schemaVersion:n,direction:n<f?"older":"future"}}function z(e){let t=ge(e);return t.kind==="legacy"||t.kind==="supported"}function ye(e,t){return{collaborationDomain:w(C(e,n=>n.facts.collaborationDomain),C(t,n=>n.facts.collaborationDomain)),repositoryLineage:w(C(e,n=>n.facts.repositoryLineage),C(t,n=>n.facts.repositoryLineage)),workspaceInstance:w(C(e,n=>n.facts.workspaceInstance),C(t,n=>n.facts.workspaceInstance)),wholeContent:w(C(e,n=>n.facts.wholeContent),C(t,n=>n.facts.wholeContent)),relevantInputs:_n(e,t),indexInput:w(C(e,n=>n.facts.index?.inputs),C(t,n=>n.facts.index?.inputs)),indexGeneration:An(e,t),observationStability:jn(e,t)}}function X(e,t,n=ye(e,t)){let r=[["collaborationDomain",n.collaborationDomain],["wholeContent",n.wholeContent],["observationStability",n.observationStability]],i=[];for(let[s,a]of r)a.state!=="established"&&i.push(`${s}:${a.state}`);for(let[s,a]of[["left",e],["right",t]]){let c=Mn(a);c!=="not-applicable"&&c!=="established"&&i.push(`${s}IndexAlignment:${c}`)}let o=r.some(([,s])=>s.state==="disproven")||i.some(s=>s.endsWith(":disproven"));return{policyVersion:me,authority:i.length===0?"completion":o?"none":"advisory",requiredRelationships:["collaborationDomain","wholeContent","observationStability"],reasons:i}}function Ct(e){return e.schemaVersion===f?e.index?.generationIdentity:e.facts.index?.generation.digest}function vt(e){return e.schemaVersion===f?void 0:e.facts.workspaceInstance?.digest}function Rt(e){if(e.schemaVersion===f)return e.index?.alignment??"not-established";let t=e.stabilityProofs.filter(n=>n.source!=="process");return t.some(n=>n.kind==="invalidated")?"invalidated":t.length>0&&t.every(n=>n.kind==="immutable"||n.kind==="fixed-snapshot")?"fixed":t.some(n=>n.kind==="bracketed")?"bracketed":"not-established"}function _n(e,t){let n=ft(e),r=ft(t);return[...new Set([...n.keys(),...r.keys()])].sort().map(o=>{let s=n.get(o),a=r.get(o),c=s?.subject??a?.subject??o,d=s?.identity.projection.name??a?.identity.projection.name??o;return{subject:c,projection:d,judgment:w(s?.identity,a?.identity)}})}function ft(e){return e.schemaVersion!==I?new Map:new Map((e.facts.relevantInputs??[]).map(t=>[`${t.subject}\0${t.identity.projection.name}`,t]))}function An(e,t){return e.schemaVersion===f&&t.schemaVersion===f?Nn(e.index?.generationIdentity,t.index?.generationIdentity):e.schemaVersion===f||t.schemaVersion===f?R("unknown",["legacy-fact-not-comparable"],gt(e),gt(t)):w(e.facts.index?.generation,t.facts.index?.generation)}function Nn(e,t){let n=e?[{kind:"legacy-index-generation",value:e}]:[],r=t?[{kind:"legacy-index-generation",value:t}]:[];return e===void 0||t===void 0?St(n,r):R(e===t?"established":"disproven",[e===t?"identities-equal":"identities-different"],n,r)}function w(e,t){let n=e?[{kind:"identity",identity:e}]:[],r=t?[{kind:"identity",identity:t}]:[];return!e||!t?St(n,r):be(e,t)?R(e.digest===t.digest?"established":"disproven",[e.digest===t.digest?"identities-equal":"identities-different"],n,r):R("unknown",["identity-projections-not-comparable"],n,r)}function jn(e,t){if(e.schemaVersion===f||t.schemaVersion===f)return R("unknown",["legacy-fact-not-comparable"],[],[]);let n=yt(e),r=yt(t),i=mt(e),o=mt(t);return i==="invalidated"||o==="invalidated"?R("disproven",[...i==="invalidated"?["left-observation-invalidated"]:[],...o==="invalidated"?["right-observation-invalidated"]:[]],n,r):i!=="fixed"||o!=="fixed"?R("unknown",[...i==="no-repository-source"?["left-observation-has-no-repository-source"]:i!=="fixed"?["left-observation-not-fixed"]:[],...o==="no-repository-source"?["right-observation-has-no-repository-source"]:o!=="fixed"?["right-observation-not-fixed"]:[]],n,r):R("established",["all-observed-sources-fixed"],n,r)}function mt(e){let t=e.observedSources.filter(r=>r.kind!=="process");if(t.length===0)return"no-repository-source";let n=new Map(e.stabilityProofs.map(r=>[r.source,r.kind]));return t.some(r=>n.get(r.kind)==="invalidated")?"invalidated":t.every(r=>{let i=n.get(r.kind);return i==="immutable"||i==="fixed-snapshot"})?"fixed":"unknown"}function Mn(e){if(e.schemaVersion!==I)return e.index?"unknown":"not-applicable";if(!e.observedSources.some(r=>r.kind==="index-generation"))return"not-applicable";let t=e.facts.index?.inputs;if(!t)return"unknown";let n=(e.facts.relevantInputs??[]).find(r=>be(r.identity,t))?.identity;return n?n.digest===t.digest?"established":"disproven":"unknown"}function C(e,t){return e.schemaVersion===I?t(e):void 0}function gt(e){return e.schemaVersion===f&&e.index?[{kind:"legacy-index-generation",value:e.index.generationIdentity}]:e.schemaVersion===I&&e.facts.index?[{kind:"identity",identity:e.facts.index.generation}]:[]}function yt(e){return e.stabilityProofs.map(t=>({kind:"stability",proof:t}))}function St(e,t){let n=e.length===0&&t.length===0?"both-facts-missing":e.length===0?"left-fact-missing":"right-fact-missing";return R("unknown",[n],e,t)}function R(e,t,n,r){return{state:e,reasons:t,facts:{left:n,right:r}}}function be(e,t){return e.schemaVersion===t.schemaVersion&&e.canonicalizationVersion===t.canonicalizationVersion&&e.hashAlgorithm===t.hashAlgorithm&&e.projection.name===t.projection.name&&e.projection.version===t.projection.version}function Vn(e){if(!p(e))return!1;let t=e.index,n=e.worktree;return It(e.observedAt)&&g(e.projectIdentity)&&Bn(e.authorityKind)&&(t===void 0||p(t)&&g(t.generationIdentity)&&(t.source==="immutable"||t.source==="legacy")&&(t.alignment==="not-certified"||t.alignment==="leased"))&&(n===void 0||p(n)&&g(n.identity)&&typeof n.clean=="boolean"&&(n.headCommit===void 0||g(n.headCommit))&&(n.treeOid===void 0||g(n.treeOid)))&&Jn(e.authorityKind,t,n)}function Dn(e){if(!p(e))return!1;let t=e.facts,n=e.observedSources,r=e.stabilityProofs;if(!It(e.observedAt)||!p(t)||!Array.isArray(n)||n.length===0||!n.every(Fn)||!fe(n,c=>c.kind)||!Array.isArray(r)||!r.every(Wn)||!fe(r,c=>c.source)||r.some(c=>!n.some(d=>d.kind===c.source))||!r.every(c=>Gn(c,t))||["collaborationDomain","repositoryLineage","workspaceInstance","wholeContent"].some(c=>t[c]!==void 0&&!x(t[c])))return!1;let o=t.relevantInputs;if(o!==void 0&&(!Array.isArray(o)||!o.every(Ln)||!fe(o,c=>`${c.subject}\0${c.identity.projection.name}`)))return!1;let s=t.index;if(s!==void 0&&(!p(s)||!x(s.generation)||s.inputs!==void 0&&!x(s.inputs)||s.source!=="immutable"&&s.source!=="legacy"))return!1;let a=e.diagnostics;return(a===void 0||p(a)&&(a.clean===void 0||typeof a.clean=="boolean")&&(a.headCommit===void 0||g(a.headCommit))&&(a.treeOid===void 0||g(a.treeOid)))&&$n(t,n)}function x(e){return!p(e)||!p(e.projection)?!1:e.schemaVersion===Q&&e.canonicalizationVersion===W&&e.hashAlgorithm===F&&g(e.projection.name)&&D(e.projection.version)&&We(e.digest)}function Ln(e){return p(e)&&g(e.subject)&&x(e.identity)}function Fn(e){return p(e)&&xt(e.kind)&&(e.identity===void 0||x(e.identity))}function Wn(e){return p(e)&&xt(e.source)&&(e.kind==="immutable"||e.kind==="fixed-snapshot"||e.kind==="bracketed"||e.kind==="not-established"||e.kind==="invalidated")}function $n(e,t){let n=e.index,r=t.find(c=>c.kind==="index-generation");if(r){if(!p(n)||!x(n.generation)||r.identity&&!he(r.identity,n.generation))return!1}else if(n!==void 0)return!1;let i=e.workspaceInstance,o=t.find(c=>c.kind==="live-workspace");if(o?.identity&&(!x(i)||!he(o.identity,i)))return!1;let s=e.wholeContent,a=t.find(c=>c.kind==="repository-snapshot");return!(a?.identity&&(!x(s)||!he(a.identity,s)))}function Gn(e,t){return e.kind==="not-established"||e.kind==="invalidated"?!0:e.source==="index-generation"?e.kind==="immutable"&&p(t.index)&&t.index.source==="immutable":e.source==="repository-snapshot"?e.kind==="fixed-snapshot":e.source==="live-workspace"?e.kind==="bracketed":!1}function he(e,t){return be(e,t)&&e.digest===t.digest}function Jn(e,t,n){return e==="index-worktree"?t!==void 0&&n!==void 0:e==="index-only"?t!==void 0&&n===void 0:e==="worktree-only"?t===void 0&&n!==void 0:e==="process-local"&&t===void 0&&n===void 0}function Bn(e){return e==="index-worktree"||e==="index-only"||e==="worktree-only"||e==="process-local"}function xt(e){return e==="index-generation"||e==="repository-snapshot"||e==="live-workspace"||e==="process"}function It(e){return typeof e=="string"&&!Number.isNaN(Date.parse(e))}function fe(e,t){return new Set(e.map(t)).size===e.length}import{createHash as Ot}from"crypto";import{closeSync as Un,fstatSync as Et,lstatSync as qn,openSync as Hn,readlinkSync as Kn,realpathSync as Yn,rmSync as Qn}from"fs";import{dirname as kt,resolve as zn}from"path";var Xn=2e3,Zn=10,er=3,ee=class extends Error{constructor(n,r,i){super(`Concurrent edit detected for ${n}; expected revision ${Pt(r)}, but found ${Pt(i)}. The latest file was left untouched.`);this.path=n;this.original=r;this.latest=i;this.name="FileRevisionConflictError"}path;original;latest};function Tt(e,t,n={}){let r=tr(e),i=nr(r,n.lockTimeoutMs??Xn,n.monotonicNow??q);try{let o=Math.max(0,Math.floor(n.maxRetries??er));for(let s=0;;s+=1){let a=Z(r),c=t(a,s);if(c.kind==="unchanged")return{changed:!1,attempts:s+1,previous:a,current:a};n.onBeforeCommit?.({attempt:s,snapshot:a,mutation:c});let d=Z(r);if(!ir(a.revision,d.revision)){if(s<o)continue;throw new ee(r,a.revision,d.revision)}try{rr(r,c,a.revision)}catch(l){if(l.code==="EEXIST"){let u=Z(r);if(s<o)continue;throw new ee(r,a.revision,u.revision)}throw l}return{changed:!0,attempts:s+1,previous:a,current:Z(r)}}}finally{i.release()}}function tr(e){let t;try{if(!qn(e).isSymbolicLink())return e;t=Kn(e)}catch{return e}try{return Yn(e)}catch{return zn(kt(e),t)}}function Z(e){for(let t=0;t<4;t+=1){let n;try{n=Hn(e,"r");let r=wt(Et(n)),i=Be(n,{maxBytes:Ge,inputKind:"revisioned text file"}),o=wt(Et(n));if(!_t(r,o))continue;return{path:e,text:i,revision:{exists:!0,hash:Ot("sha256").update(i).digest("hex"),identity:o}}}catch(r){if(r.code==="ENOENT")return{path:e,text:"",revision:{exists:!1,hash:Ot("sha256").update("").digest("hex")}};throw r}finally{n!==void 0&&Un(n)}}throw new Error(`Could not read a stable revision of ${e}; the file is changing continuously.`)}function nr(e,t,n){let r=`${e}.scip-query-write.lock`,i=n()+Math.max(0,t);for(;;){let o=qe(r,{kind:"revisioned-file-mutation",detail:{target:e}});if(o.kind==="acquired")return o.lock;if(n()>=i)throw new Error(`Timed out after ${t}ms waiting to update ${e}; the file was left untouched.`);Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,Zn)}}function rr(e,t,n){if(t.kind==="delete"){if(!n.exists)return;Qn(e),He(kt(e));return}let r=t.mode??n.identity?.mode;n.exists?Ke(e,t.text,{durability:"durable",mode:r}):Ye(e,t.text,{durability:"durable",mode:r})}function ir(e,t){return e.exists===t.exists&&e.hash===t.hash&&(e.identity===void 0?t.identity===void 0:t.identity!==void 0&&_t(e.identity,t.identity))}function wt(e){return{dev:e.dev,ino:e.ino,size:e.size,mtimeMs:e.mtimeMs,mode:e.mode&511}}function _t(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.size===t.size&&e.mtimeMs===t.mtimeMs&&e.mode===t.mode}function Pt(e){return e.exists?e.hash.slice(0,12):"<absent>"}var $=".scipquery.json",Nt=2e3,jt=5e3,Ce=jt,Mt=15*6e4,ve={enabled:!0,windowMs:15*6e4,maxRebuilds:2,maxEstimatedWriteBytes:1024*1024*1024},ar={enabled:!1,autoStart:!1,allowExpensiveRebuild:!1,debounceMs:Nt,cooldownMs:Ce,gitPollMs:2e3,idleTimeoutMs:Mt,autoRefresh:!0,ignore:[],resourceBudget:ve};var to=new Set(L);function te(e){let t=At(e,$);if(!or(t))return{};let n;try{n=Je(t,{maxBytes:$e,inputKind:"scip-query project config"})}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`unable to read ${$} at ${t}: ${i}`,{cause:r})}return Dt(le(n),t,"read").config}function Vt(e){return{...ar,...e.watch,cooldownMs:Math.max(jt,e.watch?.cooldownMs??Ce),resourceBudget:{...ve,...e.watch?.resourceBudget}}}function cr(e,t){return dr(e,t).configPath}function dr(e,t){let n=At(e,$),r=sr(),i={collaborationDomainId:r,languages:t,watch:{enabled:!0,debounceMs:Nt,cooldownMs:Ce,gitPollMs:2e3,idleTimeoutMs:Mt,autoRefresh:!0,resourceBudget:{...ve}}},o=Tt(n,s=>{if(!s.revision.exists)return{kind:"write",text:pe(i)};let a=ur(s,i);return a.config.collaborationDomainId?{kind:"unchanged"}:{kind:"write",text:pe({...a.config,collaborationDomainId:r})}});return{configPath:n,changed:o.changed}}function ur(e,t){if(!e.revision.exists)return{config:Y(t),needsMigration:!0};let n=Dt(le(e.text),e.path,"update");return{config:n.config,needsMigration:n.needsMigration}}function Dt(e,t,n){if(e.kind==="legacy"||e.kind==="supported")return e;if(e.kind==="malformed"){let i=n==="read"?`invalid ${$} at ${t}: ${e.reason}`:`Cannot update ${t}: the latest project config is ${e.reason}.`;throw new Error(`${i} The file was left untouched.`)}let r=n==="read"?`invalid ${$} at ${t}`:`Cannot update ${t}: the latest project config is invalid`;throw new Error(`${r} (unsupported ${e.direction} schemaVersion ${e.schemaVersion}; this scip-query reads legacy v${E} and current v${T}). Upgrade scip-query before retrying; the file was left untouched.`)}import{existsSync as we,lstatSync as br,statSync as Yt,watch as Cr}from"fs";import{EventEmitter as vr}from"events";import{basename as Rr,dirname as Qt,isAbsolute as Pe,join as y,relative as zt,resolve as Xt}from"path";import{watch as Sr}from"chokidar";import xr from"ignore";function Re(e){let t=JSON.stringify(e);return Buffer.byteLength(t)<=65536?t:void 0}import{existsSync as Lt,lstatSync as lr}from"fs";import{resolve as pr}from"path";function Ft(e,t,n,r={}){let i=new Date().toISOString();if(!Lt(n.dbPath))return{state:"missing",checkedAt:i,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!Lt(n.metaPath))return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let o=U(v(n.metaPath,"reindex metadata"));if(o.kind==="unsupported")return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Reindex metadata version ${o.version} is unsupported by this scip-query build.`,remedy:"Upgrade scip-query or run: scip-query reindex"};if(o.kind==="malformed")return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Could not decode reindex metadata: ${o.reason}`,remedy:"Run: scip-query reindex"};let s=o.metadata,a=t.languages??dt(e),c=s.fingerprint,d=n.cacheDir&&r.gitContext&&ue(r.gitContext,n.cacheDir,c)?c:void 0,l=n.cacheDir&&r.gitContext&&d&&fr(d,a,t)&&mr(e,d,t)?r.gitObservation?.context===r.gitContext?r.gitContext:ze(r.gitContext):void 0,u=r.gitObservation&&r.gitObservation.context===r.gitContext?r.gitObservation.projectFileInventorySequence:void 0,h=l?.clean&&Xe(e,void 0,{cachedInventoryAfterSequence:u})?l:void 0,m=n.cacheDir&&h&&d&&ue(h,n.cacheDir,d)?d:hr(e,a,t),O=[...s.indexedLanguages??[]].sort(),V=o.capabilities.publishableGeneration&&Fe(B(s.fingerprint),m)&&JSON.stringify(O)===JSON.stringify(m.languages),P=ht(n.dbPath,n.metaPath),Me=P.state==="invalid"||P.state==="drifted",se=V?pt(n.dbPath,m,O):void 0,Ve=se?.state==="incomplete",De=V&&!Me&&!Ve;return{state:De?"fresh":"stale",checkedAt:i,metaPath:n.metaPath,updatedAt:s.updatedAt,lastRefresh:s.lastRefresh,reason:Me?`SQLite generation requires repair: ${P.reason}`:Ve?`SQLite generation is missing ${se.missingDocumentCount} indexed source document(s): ${se.missingPaths.join(", ")}`:V?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:De?void 0:"Run: scip-query reindex"}}catch(o){return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Could not read reindex metadata: ${o instanceof Error?o.message:String(o)}`,remedy:"Run: scip-query reindex"}}}function hr(e,t,n){return ot(e,t,{pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:n.indexer?.typescript?.projectMode,typescriptProjects:n.indexer?.typescript?.projects,clojureConfigPath:n.indexer?.clojure?.configPath})}function fr(e,t,n){let r=gr(t,n);return e.version===r.version&&JSON.stringify([...e.languages].sort())===JSON.stringify(r.languages)&&e.pnpmWorkspaces===r.pnpmWorkspaces&&e.typescriptProjectMode===r.typescriptProjectMode&&JSON.stringify([...e.typescriptProjects].sort())===JSON.stringify(r.typescriptProjects)&&e.clojureConfigPath===r.clojureConfigPath}function mr(e,t,n){if(!(t.languages.includes("typescript")||!!t.clojureConfigPath))return!0;let i=it(e);if(t.clojureConfigPath){let o=Le(t.clojureConfigPath);if(!i.includes(o))return!1;try{if(!lr(pr(e,o)).isFile())return!1}catch{return!1}}return!t.languages.includes("typescript")||nt(e,n.indexer?.typescript?.projectMode,n.indexer?.typescript?.projects??[],i)}function gr(e,t){return K(e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}var Zt=5e3,Oe=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(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=Vt(t.config),this.outputDb=t.outputDb??y(rt(this.projectRoot,t.config),"index.db"),this.preferFilesystemGitState=t.gitReader===void 0,this.localCacheWatchPath=qr(this.projectRoot,Qt(this.outputDb)),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=t.config.indexer?.typescript?.projectMode,this.typescriptProjects=t.config.indexer?.typescript?.projects,this.clojureConfigPath=t.config.indexer?.clojure?.configPath,this.indexerConcurrency=t.config.indexerConcurrency,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onReindexError=t.onReindexError??(()=>{}),this.onRefreshSuppressed=t.onRefreshSuppressed??(()=>{}),this.onError=t.onError??(n=>console.error(n.message)),this.clock=t.clock??wr,en.set(this,Hr(t.stopTimeoutMs??Zt,"watcher stop timeout")),this.reindexRunner=t.reindexRunner??on(),this.subscriptionFactory=t.subscriptionFactory??Pr,this.budgetInspector=t.budgetInspector??lt,this.publishedGeneration=t.publishedGeneration??ce,this.indexFreshness=t.indexFreshness??Ur,this.lastObservedGeneration=this.readPublishedGeneration(),tn.set(this,{projectRoot:t.projectRoot,config:t.config,gitReader:t.gitReader??Qe,languages:sn(t.languages??t.config.languages),typeScriptInputPaths:null,stagedIndexEntries:null}),this.gitignoreFilter=st(t.projectRoot),this.extraIgnore=xr(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore),xe(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(t){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}}stop(){if(this.stopPromise)return this.stopPromise;this.stopped=!0,this.stopInProgress=!0;let t=this.fsWatchers;this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearBudgetTimer(),this.clearGitPollTimer(),this.clearReconcileTimer();let n=this.activeOperation;n&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"});let r=[...re(this).closures],i=Or(this),o=this.clock.now()+i;return this.stopPromise=this.finishStop(t,r,n,o,i).catch(s=>{throw this.stopInProgress=!1,s}),this.stopPromise}requestRefresh(t,n={}){if(!this.stopped){if(this.markPendingChangesIncomplete(`unstructured-trigger:${t.kind}`),!n.immediate||this.reindexInFlight||this.status.state==="cooldown"||this.status.state==="budget-paused"){this.scheduleReindex(t);return}this.pendingTrigger=Se(this.pendingTrigger,t),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}}startSourceWatcher(t=!1){let n=this.subscriptionFactory(this.projectRoot,{ignoreInitial:!0,ignored:(r,i)=>this.isIgnoredWatchPath(r,i?.isDirectory()??!1),usePolling:t,ignorePermissionErrors:!0,...t?{interval:5e3,binaryInterval:1e4}:{}});n.on("all",(r,i)=>{!this.stopped&&r!=="addDir"&&r!=="unlinkDir"&&this.handleFileChange(r,i)}),n.on("error",r=>this.handleSourceWatcherError(n,r,t)),this.fsWatchers.push(n)}handleSourceWatcherError(t,n,r){if(this.markPendingChangesIncomplete("source-watcher-error"),r||this.sourcePollingFallbackStarted||!Wr(n)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`));return}this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(i=>i!==t),Er(re(this),t,i=>this.onError(i));try{this.startSourceWatcher(!0)}catch(i){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(i)}`))}}isIgnoredWatchPath(t,n){let r=this.relativeWatchPath(t);if(!r)return!1;if(Jt(r,this.localCacheWatchPath))return!0;let i=n?`${r}/`:r;return this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)}handleFileChange(t,n){let r=this.relativeWatchPath(n);if(!r||r===".."||r.startsWith("../")||Jt(r,this.localCacheWatchPath)||this.gitignoreFilter.isIgnored(r)||this.extraIgnore.ignores(r)||r.endsWith("index.db")||r.endsWith("index.scip")||r.endsWith("index.db.tmp")||Rr(r).startsWith(ut))return;r===".scipquery.json"&&qt(this,this.projectRoot);let i=Ht(this,t,r);i!==null&&(i||this.markPendingChangesIncomplete(`unsupported-source-event:${t}`),this.scheduleReindex({kind:"watch-source",detail:r},i?[{path:r,kind:i}]:void 0,i!==void 0))}relativeWatchPath(t){let n=Pe(t)?t:y(this.projectRoot,t);return zt(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t,n,r=!1){this.pendingTrigger=Se(this.pendingTrigger,t),r||this.markPendingChangesIncomplete(`unstructured-trigger:${t.kind}`);for(let o of n??[])this.recordPendingChange(o);if(this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});let o=this.activeOperation;o&&_.get(this)!==o&&(_.set(this,o),o.cancel().then(s=>{s.state==="degraded"&&!this.stopped&&this.onError(new Error(s.reason))},s=>{this.stopped||this.onError(s instanceof Error?s:new Error(String(s)))}));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 i=this.wallNow()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:i}),this.debounceTimer=this.clock.setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped||this.reconcileExternalPublication())return;let t=this.inspectBudget(),n=this.watchConfig.allowExpensiveRebuild&&t.state!=="paused";if(t.state==="paused"&&t.reason!=="rebuild-count"){this.dirty=!0;let c=Math.max(this.wallNow()+1,t.until);this.setStatus({state:"budget-paused",until:c,dirty:!0,reason:t.detail,rebuilt:t.rebuilt,estimatedWriteBytes:t.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 r=this.clock.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&r<this.watchConfig.cooldownMs){let c=this.watchConfig.cooldownMs-r;this.dirty=!0;let d=this.wallNow()+c;this.setStatus({state:"cooldown",until:d,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 i=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let o=this.consumePendingChangeJournal(),s=this.wallNow();this.setStatus({state:"indexing",startedAt:s});let a=this.reindexRunner.start(this.reindexRequest(i,n,o));this.activeOperation=a,a.completion.then(c=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),ne.set(this,0),this.stopped)return;if(_.get(this)===a){if(this.restorePendingChangeJournal(o),this.dirty){let l=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:l,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}xe(this),this.lastObservedGeneration=this.readPublishedGeneration();let d=!1;try{d=this.onReindexComplete(c,i,{pendingChanges:this.dirty})===!0}catch(l){this.onError(l instanceof Error?l:new Error(String(l)))}if(this.dirty&&!this.stopped){if(d){let u=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.resetPendingChanges(),this.onRefreshSuppressed(u),this.setStatus({state:"idle"});return}let l=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:l,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 d=c instanceof Error?c:new Error(String(c));this.restorePendingChangeJournal(o);let l=rn(d),u=0;if(l?(u=(ne.get(this)??0)+1,ne.set(this,u),this.dirty=!0,this.pendingTrigger=Se(this.pendingTrigger,i)):ne.set(this,0),!l&&_.get(this)!==a&&(this.onReindexError(d,i),this.onError(d)),this.dirty){let h=l?Vr(this.watchConfig.cooldownMs,u):this.watchConfig.cooldownMs,m=this.wallNow()+h;this.setStatus({state:"cooldown",until:m,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===a&&(this.activeOperation=null),_.get(this)===a&&_.delete(this)})}async finishStop(t,n,r,i,o){let s=[],a=t.map(async h=>{try{await h.close()}catch(m){s.push(`watch subscription close failed: ${String(m)}`)}});a.push(...n),r&&a.push((async()=>{try{let h=await r.cancel();h.state==="degraded"&&s.push(h.reason)}catch(h){s.push(`reindex cancellation failed: ${h instanceof Error?h.message:String(h)}`)}})());let c=a.length,d=a.map(h=>h.finally(()=>{c-=1})),l=await Ir(d,i,this.clock),u=re(this);return s.push(...u.errors),u.errors=[],l?this.stopInProgress=!1:(s.push(`watch shutdown exceeded the ${o}ms deadline with ${c} operation(s) still pending`),Promise.all(d).then(()=>{this.stopInProgress=!1})),s.length>0?(this.setStatus({state:"draining",startedAt:this.wallNow(),reason:s.join("; ")}),{state:"degraded",reasons:s}):(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(t){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: ${t instanceof Error?t.message:String(t)}`}}}reindexRequest(t,n=!0,r){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:t,changeJournal:r,allowExpensiveRebuild:n}}setStatus(t){this.status=t,t.state==="cooldown"||t.state==="budget-paused"?this.armReconcileTimer(t.until):this.clearReconcileTimer(),this.onStatus(t)}recordPendingChange(t){if(this.pendingChanges.size>=1024&&!this.pendingChanges.has(t.path)){this.pendingChanges.clear(),this.markPendingChangesIncomplete("change-entry-limit");return}let n=this.pendingChanges.get(t.path),r=Lr(n,t.kind);r===null?this.pendingChanges.delete(t.path):this.pendingChanges.set(t.path,r)}markPendingChangesIncomplete(t){this.pendingChangesComplete=!1,this.pendingChangesIncompleteReason??=t}consumePendingChangeJournal(){let t=ce(this.outputDb),n=[...this.pendingChanges.entries()].map(([s,a])=>({path:s,kind:a})).sort((s,a)=>s.path.localeCompare(a.path)),r=this.pendingChangesComplete,i=this.pendingChangesIncompleteReason;t||(r=!1,i??="accepted-generation-unavailable");let o={version:1,baseGeneration:t,complete:r,...i?{incompleteReason:i}:{},entries:n};return Re(o)||(o={version:1,baseGeneration:t,complete:!1,incompleteReason:"change-journal-byte-limit",entries:[]}),this.resetPendingChanges(),o}restorePendingChangeJournal(t){let n=[...this.pendingChanges.entries()].map(([o,s])=>({path:o,kind:s})),r=this.pendingChangesComplete,i=this.pendingChangesIncompleteReason;this.resetPendingChanges(),t.complete||this.markPendingChangesIncomplete(t.incompleteReason??"failed-reindex");for(let o of t.entries)this.recordPendingChange(o);r||this.markPendingChangesIncomplete(i??"failed-reindex");for(let o of n)this.recordPendingChange(o)}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&&(S(this).stagedIndexEntries=Kt(this.projectRoot,S(this).gitReader),this.gitPollTimer=this.clock.setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}armReconcileTimer(t){this.clearReconcileTimer();let n=t-this.wallNow();if(n<=0||!(this.watchConfig.gitPollMs>0))return;let r=Math.min(this.watchConfig.gitPollMs,n);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)},r),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 n=this.readPublishedGeneration();if(n===null||n===this.lastObservedGeneration)return!1;this.lastObservedGeneration=n;let r;try{r=this.indexFreshness(this.projectRoot,this.config,this.outputDb)}catch{return!1}if(r!=="fresh")return!1;let i=this.pendingTrigger??{kind:"unknown"};return this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearBudgetTimer(),this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.resetPendingChanges(),xe(this),this.onRefreshSuppressed({...i,detail:`a generation published outside the watcher is fresh${i.detail?` (${i.detail})`:""}`}),this.setStatus({state:"idle"}),!0}pollGitState(){if(this.reindexInFlight||this.stopped)return;let t=this.lastGitState,n=this.readGitState();if(!t||!n||this.stopped){this.lastGitState=n;return}this.lastGitState=n;let r=t.head!==n.head,i=t.indexPath!==n.indexPath||t.indexMtimeMs!==n.indexMtimeMs||t.indexSize!==n.indexSize;if(!r&&!i)return;let o=S(this),s=o.stagedIndexEntries,a=Kt(this.projectRoot,o.gitReader);o.stagedIndexEntries=a;let c=zr(this.projectRoot,o.gitReader,t,n,s,a,r,i),d=null;if(c!==null&&(c.includes(".scipquery.json")&&qt(this,this.projectRoot),d=c.filter(u=>Ht(this,"add",u)!==null),d.length===0))return;let l=d?.map(u=>({path:u,kind:we(y(this.projectRoot,u))?"change":"delete"}));r&&i?this.scheduleReindex({kind:"watch-git-state",detail:Ie("HEAD and index changed",d)},l,l!==void 0):r?this.scheduleReindex({kind:"watch-git-head",detail:Ie("HEAD changed",d)},l,l!==void 0):i&&this.scheduleReindex({kind:"watch-git-index",detail:Ie(n.indexPath??"index changed",d)},l,l!==void 0)}readGitState(){if(this.preferFilesystemGitState){let t=this.readFilesystemGitState();if(t)return t}return this.readGitStateFromGit()}readFilesystemGitState(){let t=this.watchGitLayout??$r(this.projectRoot);if(!t)return null;this.watchGitLayout=t;let n=Gr(t.gitDir);return n?Ut(n,t.indexPath):null}readGitStateFromGit(){let t=S(this).gitReader,n=de(this.projectRoot,["rev-parse","--git-path","index"],t);if(!n)return null;let r=Ze(this.projectRoot,n);return Ut(de(this.projectRoot,["rev-parse","--verify","HEAD"],t),r)}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};async function Ir(e,t,n){if(e.length===0)return!0;let r=Promise.all(e).then(()=>!0),i=Math.max(0,t-n.now()),o=null,s=new Promise(c=>{o=n.setTimeout(()=>c(!1),i)}),a=await Promise.race([r,s]);return a&&o&&n.clearTimeout(o),a}var $t=new WeakMap,en=new WeakMap,tn=new WeakMap,_=new WeakMap,ne=new WeakMap;function re(e){let t=$t.get(e);if(t)return t;let n={closures:new Set,errors:[]};return $t.set(e,n),n}function Or(e){return en.get(e)??Zt}function S(e){let t=tn.get(e);if(!t)throw new Error("Watcher input state was not initialized.");return t}function Er(e,t,n){let r=Promise.resolve().then(()=>t.close()).catch(i=>{let o=`watch subscription close failed during polling fallback: ${String(i)}`;e.errors.push(o),n(new Error(o))});e.closures.add(r),r.then(()=>e.closures.delete(r))}function nn(e,t=Ue){let{projectRoot:n,config:r,languages:i,pnpmWorkspaces:o,typescriptProjectMode:s,typescriptProjects:a,clojureConfigPath:c,indexerConcurrency:d,trigger:l}=e,u=te(n),h=Object.keys(u).length>0?u:r,m=H(n,h),O=h.indexer?.typescript,V=h.indexer?.clojure,P=t(process.pid);if(!P)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:n,SCIP_REINDEX_OUTPUT_SCIP:m.indexPath,SCIP_REINDEX_OUTPUT_DB:m.dbPath,SCIP_REINDEX_LANGUAGES:(h.languages??i)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(h.indexerConcurrency??d??""),SCIP_REINDEX_PNPM_WORKSPACES:O?.pnpmWorkspaces??o?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:O?.projectMode??s,projects:O?.projects??a??[],maxHeapMb:O?.maxHeapMb}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:V?.configPath??c??"",SCIP_REINDEX_TRIGGER_KIND:l.kind,SCIP_REINDEX_TRIGGER_DETAIL:l.detail??"",SCIP_REINDEX_CHANGE_JOURNAL:e.changeJournal?Re(e.changeJournal)??"":"",SCIP_REINDEX_ALLOW_EXPENSIVE:e.allowExpensiveRebuild===!1?"0":"1",SCIP_REINDEX_PROCESS_GROUP_LEADER:"1",SCIP_REINDEX_PARENT_IDENTITY:JSON.stringify(P)}}}var wr={now:q,wallNow:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Pr=(e,t)=>kr(process.platform,t.usePolling)?new Ee(e):Sr(e,t);function kr(e,t){return e==="darwin"&&t!==!0}var G=class extends Error{constructor(t,n){super(t,n===void 0?void 0:{cause:n}),this.name="RecursiveSourceWatchError"}},Ee=class{events=new vr;watcher;constructor(t){this.watcher=Cr(t,{recursive:!0},(n,r)=>{if(r===null){this.events.emit("error",new G("Recursive source watcher omitted the changed path."));return}let i=y(t,r.toString());this.events.emit("all",Tr(n,i),i)}),this.watcher.on("error",n=>{this.events.emit("error",new G(`Recursive source watcher failed: ${n.message}`,n))})}on=(t,n)=>(this.events.on(t,n),this);close(){this.watcher.close()}};function Tr(e,t){return e==="change"?"change":we(t)?Yt(t).isDirectory()?"addDir":"add":"unlink"}var _r=15*6e4,Ar=1e3,Nr=64*1024;function jr(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function Gt(e,t){let n=e instanceof Error?e.message:String(e),r=t.stderrTail.trim()||t.stdoutTail.trim();return r?`${n}
3
+ ${r}`:n}function Mr(e,t){return Object.assign(new Error(e,t===void 0?void 0:{cause:t}),{retryable:!0})}function rn(e){return e instanceof Error&&"retryable"in e&&e.retryable===!0}function Vr(e,t){let n=e*2**Math.min(5,Math.max(0,t-1));return Math.max(e,Math.min(3e4,n))}function on(e={}){let t=e.timeoutMs??_r,n=e.terminationGraceMs??Ar,r=e.maxOutputBytes??Nr,i=e.resolveLaunch??nn;return{start(o){let s=i(o),a=new AbortController,c=jr(),d=!1,l=ct({command:process.execPath,args:[...process.execArgv,s.workerPath],label:"watch reindex worker",env:s.env,timeoutMs:t,terminationGraceMs:n,maxStdoutBytes:r,maxStderrBytes:r,outputLimitBehavior:"truncate-tail",signal:a.signal,detached:!0}).then(u=>{if(c={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated},u.status!==0){let h=Gt(new Error(`Reindex worker exited with ${u.signal?`signal ${u.signal}`:`code ${u.status}`}`),c);throw u.status===75?Mr(h):new Error(h)}return u.durationMs}).catch(u=>{throw rn(u)?u:(u instanceof at&&(c={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated}),new Error(Gt(u,c),{cause:u}))}).finally(()=>{d=!0});return{completion:l,async cancel(){d||a.abort();try{await l}catch{}return{state:"exited",diagnostics:c}},diagnostics:()=>c}}}}function Se(e,t){return e?e.kind===t.kind?e.detail===t.detail?e:{kind:e.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${e.kind}, ${t.kind}`}:t}function Dr(e){if(e==="add")return"add";if(e==="change")return"change";if(e==="unlink")return"delete"}function Lr(e,t){return e?e==="add"?t==="delete"?null:"add":e==="delete"&&t==="add"?"change":t:t}function Fr(e){return e instanceof Error&&"code"in e&&e.code==="EMFILE"||String(e).includes("EMFILE: too many open files")}function Wr(e){return e instanceof G||Fr(e)}var ke=/^[0-9a-f]{40,64}$/i;function Jt(e,t){return e===".git"||e.startsWith(".git/")||e==="node_modules"||e.startsWith("node_modules/")||e.endsWith("/node_modules")||e.includes("/node_modules/")?!0:t!==void 0&&(e===t||e.startsWith(`${t}/`))}function $r(e){let t=y(e,".git");try{let n=br(t),r;if(n.isDirectory())r=t;else if(n.isFile()){let i=/^gitdir:\s*(.+)\s*$/m.exec(v(t,"Git directory marker"));if(!i?.[1])return null;let o=i[1].trim();r=Pe(o)?o:Xt(e,o)}else return null;return we(r)?{gitDir:r,indexPath:y(r,"index")}:null}catch{return null}}function Gr(e){let t;try{t=v(y(e,"HEAD"),"Git HEAD").trim()}catch{return}if(ke.test(t))return t.toLowerCase();let n=/^ref:\s*(.+)$/.exec(t)?.[1]?.trim();if(!n)return;let r=Jr(e);return Bt(e,n)??Bt(r,n)??Br(r,n)}function Jr(e){try{let t=v(y(e,"commondir"),"Git common-directory marker").trim();return t?Pe(t)?t:Xt(e,t):e}catch{return e}}function Bt(e,t){try{let n=v(y(e,t),"Git reference").trim();return ke.test(n)?n.toLowerCase():void 0}catch{return}}function Br(e,t){try{for(let n of v(y(e,"packed-refs"),"Git packed references").split(`
4
+ `)){if(n.startsWith("#")||n.startsWith("^"))continue;let r=n.indexOf(" ");if(r===-1)continue;let i=n.slice(0,r);if(n.slice(r+1).trim()===t&&ke.test(i))return i.toLowerCase()}}catch{return}}function Ur(e,t,n){let r=Qt(n);return Ft(e,t,{dbPath:n,metaPath:y(r,"meta.json"),cacheDir:r}).state}function Ut(e,t){let n={head:e,indexPath:t};try{let r=Yt(t);n.indexMtimeMs=r.mtimeMs,n.indexSize=r.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}function qr(e,t){let n=zt(e,t).replaceAll("\\","/");if(!(!n||n===".."||n.startsWith("../")))return n}function Hr(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`${t} must be a positive integer.`);return e}function sn(e){return e&&e.length>0?[...e]:L}function qt(e,t){try{let n=S(e);n.config=te(t),n.languages=sn(n.config.languages)}catch{S(e).languages=L}}function Ht(e,t,n){let r=S(e);if(ae(n,r.languages)==="other")return null;let o=Dr(t);if(n===".scipquery.json"||et(n))return r.typeScriptInputPaths=null,o;if(!Kr(n,r.languages))return o;let s=r.typeScriptInputPaths;if(!s)return o;let a=s.has(n);if(o!=="add")return a?o:null;if(a)return"change";let c=an(e);return c?c.has(n)?"add":null:o}function xe(e){let t=S(e);if(!t.languages.includes("typescript")){t.typeScriptInputPaths=null;return}let n=Yr(t.projectRoot,t.config,t.languages);t.typeScriptInputPaths=n??an(e)}function an(e){let t=S(e);if(!t.languages.includes("typescript"))return t.typeScriptInputPaths=null,null;try{let n=t.config.indexer?.typescript,r=tt(t.projectRoot,n?.projectMode,n?.projects);return t.typeScriptInputPaths=r,r}catch{return t.typeScriptInputPaths=null,null}}function Kr(e,t){if(!t.includes("typescript"))return!1;let n=ae(e,["typescript","javascript"]);return n==="source"||n==="ambient"}function Yr(e,t,n){try{let r=U(v(H(e,t).metaPath,"reindex metadata"));if(r.kind!=="supported"&&r.kind!=="legacy")return null;let i=B(r.metadata.fingerprint);return!i||!Qr(i,n,t)?null:new Set(i.files.map(o=>o.path))}catch{return null}}function Qr(e,t,n){let r=K(t,{pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:n.indexer?.typescript?.projectMode,typescriptProjects:n.indexer?.typescript?.projects,clojureConfigPath:n.indexer?.clojure?.configPath});return e.version===r.version&&JSON.stringify([...e.languages].sort())===JSON.stringify(r.languages)&&e.pnpmWorkspaces===r.pnpmWorkspaces&&e.typescriptProjectMode===r.typescriptProjectMode&&JSON.stringify([...e.typescriptProjects].sort())===JSON.stringify(r.typescriptProjects)&&e.clojureConfigPath===r.clojureConfigPath}function zr(e,t,n,r,i,o,s,a){let c=new Set;if(s){if(!n.head||!r.head)return null;let d=t.runResult(e,["diff","--name-only","-z","--no-renames","--relative",n.head,r.head,"--"]);if(d.kind!=="success")return null;for(let l of Xr(d.output))c.add(l)}if(a){if(i===null||o===null)return null;for(let d of ei(i,o))c.add(d)}return[...c].sort()}function Kt(e,t){let n=t.runResult(e,["diff","--cached","--raw","-z","--no-renames","--relative","--"]);return n.kind==="success"?Zr(n.output):null}function Xr(e){return e.split("\0").filter(t=>t.length>0)}function Zr(e){let t=e.split("\0");if(t.at(-1)===""&&t.pop(),t.length%2!==0)return null;let n=new Map;for(let r=0;r<t.length;r+=2){let i=t[r],o=t[r+1];if(!i.startsWith(":")||!o)return null;n.set(o,i)}return n}function ei(e,t){return[...new Set([...e.keys(),...t.keys()])].filter(r=>e.get(r)!==t.get(r))}function Ie(e,t){return t===null?`${e}; changed paths unavailable`:t.length===0?e:t.length===1?t[0]:`${t.length} compiler inputs changed`}import{existsSync as Te,mkdirSync as ti,symlinkSync as ni,readlinkSync as cn,unlinkSync as dn,readdirSync as ri}from"fs";import{join as A,dirname as _e,resolve as N,relative as ii,isAbsolute as oi}from"path";import{homedir as si,platform as ai}from"os";import{fileURLToPath as ci}from"url";var di=ai()==="win32";var un=["scip-query","scip-plan","scip-setup","scip-integrity-audit","scip-explore","principal-maintainability-review","scip-system-compression","scip-root-cause","scip-claim-audit","scip-probe-reachability","scip-twin-drift","scip-calibrate","conductor","concrete-plan"];function ui(e={}){let t=e.quiet?()=>{}:console.log,n=ci(import.meta.url),r=N(_e(n),"..","skills"),i=e.homeDir??process.env.SCIP_QUERY_SKILLS_HOME??si(),o=[A(i,".claude","skills"),A(i,".codex","skills"),A(i,".agents","skills")],s={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let a of o){let c=_e(a);if(!Te(c))continue;ti(a,{recursive:!0});let d=hi(a);li(a,r,d,s,t);for(let l of un){let u=A(r,l),h=A(a,l);if(!Te(u)){s.skipped.push(`${d}/${l}`);continue}if(Te(h)){try{let m=cn(h);if(N(m)===N(u)){s.alreadyLinked.push(`${d}/${l}`),t(` ok: ${l} \u2192 ${d} (already linked)`);continue}}catch{s.skipped.push(`${d}/${l}`),t(` skip: ${l} \u2192 ${d} (exists, not a symlink)`);continue}dn(h)}ni(u,h,di?"junction":"dir"),s.installed.push(`${d}/${l}`),t(` done: ${l} \u2192 ${d}`)}}return s}function li(e,t,n,r,i){let o=new Set(un);for(let s of ri(e)){if(o.has(s))continue;let a=A(e,s),c;try{c=N(_e(a),cn(a))}catch{continue}pi(c,t)&&(dn(a),r.pruned.push(`${n}/${s}`),i(` prune: ${s} \u2192 ${n} (removed stale scip-query skill link)`))}}function pi(e,t){let n=ii(N(t),N(e));return n===""||!n.startsWith("..")&&!oi(n)}function hi(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}var ln=["repository-observation","repository-preview","mutation","composite","environment-observation","tool-information"];function fi(e,t=[]){return{defaultRole:e,...t.length>0?{rules:t}:{}}}function mi(e,t){for(let n of e.rules??[]){if(n.when.kind==="option-present"){let i=t.options[n.when.name];if(i!==void 0&&i!==!1)return n.role;continue}if((n.when.kind==="argument"?t.args[n.when.index]:t.options[n.when.name])===n.when.equals)return n.role}return e.defaultRole}function gi(e){return[...new Set([e.defaultRole,...(e.rules??[]).map(t=>t.role)])]}function ie(e){return ln.includes(e)}function yi(e){return e==="repository-observation"||e==="repository-preview"||e==="composite"}var Ae=1,Ne=1,oe=["compiler-graph","semantic-analysis","repository-source","change-history","runtime-measurement","heuristic","mixed","unknown"],pn=["complete","partial","unknown"],hn=["validated","failed","not-evaluated","not-applicable"],fn=["observe","advise","require-adjudication","block","not-established"],mn={policyId:"scip-query:unresolved-repository-policy",policyVersion:Ne,permission:"not-established",reasons:["No repository action policy was supplied for this claim."]};function bi(e){return{schemaVersion:Ae,origin:e.contract.origin,coverage:gn(e.coverage),producerValidation:e.contract.producerValidation,stateAuthority:X(e.receipt,e.receipt),repositoryPolicy:e.repositoryPolicy??mn,...e.contract.families?{families:e.contract.families}:{}}}function gn(e){return e?e.complete===!0?{state:"complete",returned:e.returned,totalKnown:!0,total:e.total??e.returned,omitted:0}:e.totalKnown?{state:"partial",returned:e.returned,totalKnown:!0,...e.total===void 0?{}:{total:e.total},...e.omitted===void 0?{}:{omitted:e.omitted}}:{state:"unknown",returned:e.returned,totalKnown:!1}:{state:"unknown",returned:0,totalKnown:!1}}function Ci(e,t){let n=[];return J(n,"origin",t.origins,e.origin),J(n,"coverage",t.coverage,e.coverage.state),J(n,"producer-validation",t.producerValidation,e.producerValidation.status),J(n,"state-authority",t.stateAuthority,e.stateAuthority.authority),J(n,"action-permission",t.actionPermission,e.repositoryPolicy.permission),{satisfied:n.every(r=>r.satisfied),predicates:n}}function J(e,t,n,r){n&&e.push({predicate:t,satisfied:n.includes(r),required:n,actual:r})}function je(e){return!p(e)||e.schemaVersion!==Ae||!j(e.origin,oe)||!vi(e.coverage)||!Ri(e.producerValidation)||!Si(e.stateAuthority)||!xi(e.repositoryPolicy)?!1:e.families===void 0||Ii(e.families)}function vi(e){return!p(e)||!j(e.state,pn)||!k(e.returned)||typeof e.totalKnown!="boolean"||e.total!==void 0&&!k(e.total)||e.omitted!==void 0&&!k(e.omitted)?!1:e.state==="complete"?e.totalKnown===!0&&e.total===e.returned&&e.omitted===0:e.state==="partial"?e.totalKnown===!0&&k(e.total)&&k(e.omitted)&&e.total===Number(e.returned)+Number(e.omitted):e.totalKnown===!1}function Ri(e){if(!p(e)||!j(e.status,hn))return!1;let t=e.certification;return e.status==="validated"||e.status==="failed"?p(t)&&b(t.id)&&Number.isSafeInteger(t.version)&&Number(t.version)>0&&b(t.corpus):t===void 0}function Si(e){return p(e)&&Number.isSafeInteger(e.policyVersion)&&(e.authority==="completion"||e.authority==="advisory"||e.authority==="none")&&Array.isArray(e.requiredRelationships)&&e.requiredRelationships.every(b)&&Array.isArray(e.reasons)&&e.reasons.every(b)}function xi(e){return p(e)&&b(e.policyId)&&e.policyVersion===Ne&&j(e.permission,fn)&&Array.isArray(e.reasons)&&e.reasons.every(b)}function Ii(e){return Array.isArray(e)&&e.every(t=>p(t)&&b(t.id)&&b(t.selector)&&Oi(t.origin))}function Oi(e){return p(e)?e.kind==="fixed"?j(e.origin,oe)&&e.origin!=="mixed":e.kind!=="result-field"||!b(e.field)||!p(e.values)?!1:Object.values(e.values).every(t=>j(t,oe)&&t!=="mixed"):!1}function j(e,t){return typeof e=="string"&&t.includes(e)}var Cn="scip-query-result",vn=0,M=1,Ei=1,Rn=1,Sn=1;function xn(e){if(!p(e))return{kind:"malformed",reason:"CLI JSON output must be an object."};let t=Object.hasOwn(e,"kind"),n=Object.hasOwn(e,"schemaVersion");if(!t&&!n){let s=yn(e);return s?{kind:"malformed",reason:`Legacy CLI JSON envelope: ${s}`}:{kind:"legacy",schemaVersion:vn,envelope:e}}if(!t||!n)return{kind:"malformed",reason:"CLI JSON envelope must contain both kind and schemaVersion."};if(e.kind!==Cn)return{kind:"malformed",reason:`Unsupported CLI JSON envelope kind: ${Ti(e.kind)}.`};let r=e.schemaVersion;if(!Number.isSafeInteger(r)||Number(r)<1)return{kind:"malformed",reason:"CLI JSON envelope schemaVersion must be a positive safe integer."};if(r!==M)return{kind:"unsupported",schemaVersion:Number(r),direction:Number(r)<M?"older":"future",...bn(e.producer)?{producer:e.producer}:{}};let i=yn(e);if(i)return{kind:"malformed",reason:`CLI JSON envelope v1: ${i}`};if(!bn(e.producer))return{kind:"malformed",reason:"CLI JSON envelope v1: producer must identify scip-query and its non-empty version."};if(!D(e.resultSchemaVersion))return{kind:"malformed",reason:"CLI JSON envelope v1: resultSchemaVersion must be a positive safe integer."};if(e.resultProjection!==void 0&&e.resultProjection!=="agent")return{kind:"malformed",reason:'CLI JSON envelope v1: resultProjection must be "agent" when present.'};let o=In(e.command);return o.includes(e.resultSchemaVersion)?e.evidenceContext!==void 0&&!ki(e.evidenceContext)?{kind:"malformed",reason:"CLI JSON envelope v1: evidenceContext must contain a supported receipt and analysis manifest."}:e.operationRole!==void 0&&!ie(e.operationRole)?{kind:"malformed",reason:"CLI JSON envelope v1: operationRole must be a supported command operation role."}:p(e.evidenceContext)&&e.operationRole!==void 0&&e.evidenceContext.operationRole!==void 0&&e.operationRole!==e.evidenceContext.operationRole?{kind:"malformed",reason:"CLI JSON envelope v1: top-level and evidence-context operation roles must agree."}:{kind:"supported",schemaVersion:M,envelope:e}:{kind:"unsupported-result",schemaVersion:M,command:e.command,resultSchemaVersion:e.resultSchemaVersion,supportedResultSchemaVersions:o}}function wi(e){let t=xn(e);if(t.kind==="legacy"||t.kind==="supported")return t;if(t.kind==="unsupported"){let n=t.producer?` from ${t.producer.name}@${t.producer.version}`:"";throw new Error(`Unsupported scip-query CLI JSON schemaVersion ${t.schemaVersion}${n}; this consumer supports the legacy unversioned envelope and schemaVersion ${M}.`)}throw t.kind==="unsupported-result"?new Error(`Unsupported resultSchemaVersion ${t.resultSchemaVersion} for scip-query command ${JSON.stringify(t.command)}; this consumer supports ${t.supportedResultSchemaVersions.join(", ")}.`):new Error(`Malformed scip-query CLI JSON envelope: ${t.reason}`)}function In(e){return Pi[e]??[Ei]}var Pi={};function yn(e){return typeof e.command!="string"||e.command.length===0?"command must be a non-empty string.":Array.isArray(e.args)?p(e.options)?Object.hasOwn(e,"result")?null:"result is required.":"options must be an object.":"args must be an array."}function bn(e){return p(e)&&e.name==="scip-query"&&typeof e.version=="string"&&e.version.length>0}function ki(e){if(!p(e)||e.schemaVersion!==Rn||e.operationRole!==void 0&&!ie(e.operationRole)||!z(e.receipt))return!1;let t=e.analysisManifest;return p(t)&&t.schemaVersion===Sn&&(t.evidence===void 0||t.evidence==="graph-fact"||t.evidence==="heuristic"||t.evidence==="mixed")&&(t.claimQualification===void 0||je(t.claimQualification))}function Ti(e){return typeof e=="string"?JSON.stringify(e):String(e)}export{fn as CLAIM_ACTION_PERMISSIONS,Ne as CLAIM_ACTION_POLICY_VERSION,pn as CLAIM_COVERAGE_STATES,oe as CLAIM_ORIGINS,Ae as CLAIM_QUALIFICATION_SCHEMA_VERSION,Sn as CLI_ANALYSIS_MANIFEST_SCHEMA_VERSION,Rn as CLI_EVIDENCE_CONTEXT_SCHEMA_VERSION,Cn as CLI_JSON_ENVELOPE_KIND,ln as COMMAND_OPERATION_ROLES,M as CURRENT_CLI_JSON_ENVELOPE_SCHEMA_VERSION,mn as DEFAULT_REPOSITORY_POLICY_ACTION,vn as LEGACY_CLI_JSON_ENVELOPE_SCHEMA_VERSION,f as LEGACY_OBSERVATION_RECEIPT_SCHEMA_VERSION,W as OBSERVATION_IDENTITY_CANONICALIZATION_VERSION,F as OBSERVATION_IDENTITY_HASH_ALGORITHM,Q as OBSERVATION_IDENTITY_SCHEMA_VERSION,I as OBSERVATION_RECEIPT_SCHEMA_VERSION,me as OBSERVATION_STATE_AUTHORITY_POLICY_VERSION,hn as PRODUCER_VALIDATION_STATUSES,Oe as Watcher,fi as commandOperation,gi as commandOperationRoles,ye as compareObservationReceipts,bt as createObservationIdentity,on as createReindexRunner,xn as decodeCliJsonEnvelope,ge as decodeObservationReceipt,gn as deriveClaimCoverage,bi as deriveClaimQualification,X as deriveObservationStateAuthority,Ci as evaluateClaimQualification,En as getScipVersion,cr as initProjectConfig,ui as installSkills,je as isClaimQualificationV1,ie as isCommandOperationRole,z as isObservationReceipt,On as isScipInstalled,te as loadProjectConfig,Ct as observationReceiptGenerationIdentity,Rt as observationReceiptStabilityLabel,vt as observationReceiptWorkspaceIdentity,yi as operationObservesRepository,wn as printScipInstallInstructions,wi as requireCompatibleCliJsonEnvelope,mi as resolveCommandOperationRole,H as resolveIndexStoragePaths,nn as resolveReindexWorkerLaunch,In as supportedCliResultSchemaVersions};
5
5
  //# sourceMappingURL=runtime.js.map
@@ -1,2 +1,2 @@
1
- import{j as O}from"./chunk-OWOOWNJ5.js";import{e as E,f as A,g as C,h as V,m as F}from"./chunk-SSK6LDPC.js";import"./chunk-4WNW27SX.js";import"./chunk-F4FNK44D.js";import"./chunk-GAS2LJMP.js";import"./chunk-DRENNWRG.js";import"./chunk-2OOY75BW.js";import{b as h}from"./chunk-3AF4TUFK.js";import{b as q,c as N,h as _,i as T,m as g,n as k,o as P,p as B,r as U}from"./chunk-FGA2U4OR.js";import{a as x}from"./chunk-B3PYOSCX.js";import"./chunk-H5EXS3HM.js";import"./chunk-HGFDYOVB.js";import{c as L,d as b,e as v}from"./chunk-JFMEXGFE.js";import"./chunk-KYSDI3GE.js";import"./chunk-7F45LJKI.js";import n from"process";import{randomUUID as J}from"crypto";import{rmSync as W}from"fs";import{resolve as S}from"path";import{pathToFileURL as X}from"url";var G=10*6e4,j=10,z=250,Y=1e3;function $(e,t,o={}){let M=_(e),d=o.now??(o.nowMs===void 0?Date.now:()=>o.nowMs),f=d(),y=A(e),w=g(M,{ownerId:o.ownerId??re,nowMs:f,limits:o.limits,owner:ne,liveness:ie}),p=0;for(let i of w){let s=null,c,m="handler-error";try{let a=k(i,o.limits),u;try{u=JSON.parse(a)}catch{throw m="malformed-request",new Error("Durable Rust semantic helper received malformed request JSON.")}let r=C(u,{claimRequestId:i.requestId,sessionIdentity:y,nowMs:d()});if(!r.ok)throw m=r.code,c=r.responseIdentity,new Error(r.error);s=r.value,c={id:s.id,sessionIdentity:s.sessionIdentity,deadlineAtMs:s.deadlineAtMs};let l=K(s.request,o.monotonicNowMs??b());o.beforeRequest?.(l);let R=t.handle(l),I=d();if(s.deadlineAtMs<I)throw m="expired-request",new Error("Durable Rust semantic request expired while the helper was processing it.");P(M,i,{ok:!0,protocolVersion:E,id:s.id,sessionIdentity:s.sessionIdentity,deadlineAtMs:s.deadlineAtMs,...R},{nowMs:I,limits:o.limits})}catch(a){let u=d(),r=c??(s?{id:s.id,sessionIdentity:s.sessionIdentity,deadlineAtMs:s.deadlineAtMs}:void 0),l=a instanceof Error?a.message:String(a);B(M,i,{ok:!1,protocolVersion:E,id:r?.id??i.requestId,...r?{sessionIdentity:r.sessionIdentity,deadlineAtMs:r.deadlineAtMs}:{},errorCode:m,error:l},l,{nowMs:u,limits:o.limits})}p+=1}return p}function K(e,t){let o=t+Math.max(1,e.timeoutMs-1e3);return{...e,request:{...e.request,readinessDeadlineMs:o}}}async function Q(e,t){let o=_(e);T(o);let M=S(e,"server.lock"),d=te(M);if(!d)return;let f=new V(()=>F({semanticWorkerPath:t,shareEnvironment:!0})),y=!1,w=b(),p=Number.NEGATIVE_INFINITY,i,s=0,c=L(n.pid),m=A(e),a=()=>{y=!0};n.once("SIGINT",a),n.once("SIGTERM",a);let u=(r=!1,l=r?"durable":"visibility")=>{let R=Date.now(),I=b();if(!r&&I-p<Y)return;p=I;let D={protocolVersion:E,sessionIdentity:m,pid:n.pid,...c?{processIdentity:c}:{},heartbeatAtMs:R,...i===void 0?{}:{busyUntilMs:i},mailbox:U(o)};l==="durable"?N(S(e,"server.json"),D):q(S(e,"server.json"),D)};try{u(!0);let r=se();for(;!y&&b()-w<r;){let l=$(e,f,{beforeRequest(R){i=Date.now()+R.timeoutMs+5e3,u(!0,"visibility")}});l>0?(s=0,w=b(),i=void 0,u(!0,"visibility")):(s+=1,u()),await O(Z(l,s))}}finally{f.shutdown(),W(S(e,"server.json"),{force:!0}),d.release()}}function Z(e,t=1){return v(e,t,j,j,z,5)}var ee=e=>{let t=Number(e);return Number.isInteger(t)&&t>0?{pid:t}:null};function te(e){let t=h(e,{kind:"rust-durable-session-server",parseLegacy:ee});return t.kind==="acquired"?t.lock:null}function se(){let e=Number(n.env.SCIP_RUST_SEMANTIC_DURABLE_IDLE_MS);return Number.isInteger(e)&&e>=0?e:G}var oe=n.argv[1]?X(S(n.argv[1])).href:null;if(oe===import.meta.url){let e=n.argv[2],t=n.argv[3];!e||!t?(console.error("durable-rust-session: expected <session-dir> <semantic-worker-path>"),n.exitCode=1):await Q(e,t)}var re=`rust-semantic-${n.pid}-${J()}`,H=L(n.pid),ne={pid:n.pid,...H?{processIdentity:H}:{}},ie={isProcessAlive:x,readProcessIdentity:L};export{te as acquireDurableRustSessionServerLock,Z as durableSessionLoopDelayMs,$ as processDurableRustSessionRequests};
1
+ import{j as O}from"./chunk-C4RHHCKL.js";import{e as E,f as A,g as C,h as V,m as F}from"./chunk-5BIKR67W.js";import"./chunk-CZW5MZ5B.js";import"./chunk-F4FNK44D.js";import"./chunk-ODPDP7A4.js";import"./chunk-BL6DCHQP.js";import"./chunk-2OOY75BW.js";import{b as h}from"./chunk-3AF4TUFK.js";import{b as q,c as N,h as _,i as T,m as g,n as k,o as P,p as B,r as U}from"./chunk-T3CZAZSI.js";import{a as x}from"./chunk-B3PYOSCX.js";import"./chunk-H5EXS3HM.js";import"./chunk-HGFDYOVB.js";import{c as L,d as b,e as v}from"./chunk-JFMEXGFE.js";import"./chunk-7HXT6YLU.js";import"./chunk-7F45LJKI.js";import n from"process";import{randomUUID as J}from"crypto";import{rmSync as W}from"fs";import{resolve as S}from"path";import{pathToFileURL as X}from"url";var G=10*6e4,j=10,z=250,Y=1e3;function $(e,t,o={}){let M=_(e),d=o.now??(o.nowMs===void 0?Date.now:()=>o.nowMs),f=d(),y=A(e),w=g(M,{ownerId:o.ownerId??re,nowMs:f,limits:o.limits,owner:ne,liveness:ie}),p=0;for(let i of w){let s=null,c,m="handler-error";try{let a=k(i,o.limits),u;try{u=JSON.parse(a)}catch{throw m="malformed-request",new Error("Durable Rust semantic helper received malformed request JSON.")}let r=C(u,{claimRequestId:i.requestId,sessionIdentity:y,nowMs:d()});if(!r.ok)throw m=r.code,c=r.responseIdentity,new Error(r.error);s=r.value,c={id:s.id,sessionIdentity:s.sessionIdentity,deadlineAtMs:s.deadlineAtMs};let l=K(s.request,o.monotonicNowMs??b());o.beforeRequest?.(l);let R=t.handle(l),I=d();if(s.deadlineAtMs<I)throw m="expired-request",new Error("Durable Rust semantic request expired while the helper was processing it.");P(M,i,{ok:!0,protocolVersion:E,id:s.id,sessionIdentity:s.sessionIdentity,deadlineAtMs:s.deadlineAtMs,...R},{nowMs:I,limits:o.limits})}catch(a){let u=d(),r=c??(s?{id:s.id,sessionIdentity:s.sessionIdentity,deadlineAtMs:s.deadlineAtMs}:void 0),l=a instanceof Error?a.message:String(a);B(M,i,{ok:!1,protocolVersion:E,id:r?.id??i.requestId,...r?{sessionIdentity:r.sessionIdentity,deadlineAtMs:r.deadlineAtMs}:{},errorCode:m,error:l},l,{nowMs:u,limits:o.limits})}p+=1}return p}function K(e,t){let o=t+Math.max(1,e.timeoutMs-1e3);return{...e,request:{...e.request,readinessDeadlineMs:o}}}async function Q(e,t){let o=_(e);T(o);let M=S(e,"server.lock"),d=te(M);if(!d)return;let f=new V(()=>F({semanticWorkerPath:t,shareEnvironment:!0})),y=!1,w=b(),p=Number.NEGATIVE_INFINITY,i,s=0,c=L(n.pid),m=A(e),a=()=>{y=!0};n.once("SIGINT",a),n.once("SIGTERM",a);let u=(r=!1,l=r?"durable":"visibility")=>{let R=Date.now(),I=b();if(!r&&I-p<Y)return;p=I;let D={protocolVersion:E,sessionIdentity:m,pid:n.pid,...c?{processIdentity:c}:{},heartbeatAtMs:R,...i===void 0?{}:{busyUntilMs:i},mailbox:U(o)};l==="durable"?N(S(e,"server.json"),D):q(S(e,"server.json"),D)};try{u(!0);let r=se();for(;!y&&b()-w<r;){let l=$(e,f,{beforeRequest(R){i=Date.now()+R.timeoutMs+5e3,u(!0,"visibility")}});l>0?(s=0,w=b(),i=void 0,u(!0,"visibility")):(s+=1,u()),await O(Z(l,s))}}finally{f.shutdown(),W(S(e,"server.json"),{force:!0}),d.release()}}function Z(e,t=1){return v(e,t,j,j,z,5)}var ee=e=>{let t=Number(e);return Number.isInteger(t)&&t>0?{pid:t}:null};function te(e){let t=h(e,{kind:"rust-durable-session-server",parseLegacy:ee});return t.kind==="acquired"?t.lock:null}function se(){let e=Number(n.env.SCIP_RUST_SEMANTIC_DURABLE_IDLE_MS);return Number.isInteger(e)&&e>=0?e:G}var oe=n.argv[1]?X(S(n.argv[1])).href:null;if(oe===import.meta.url){let e=n.argv[2],t=n.argv[3];!e||!t?(console.error("durable-rust-session: expected <session-dir> <semantic-worker-path>"),n.exitCode=1):await Q(e,t)}var re=`rust-semantic-${n.pid}-${J()}`,H=L(n.pid),ne={pid:n.pid,...H?{processIdentity:H}:{}},ie={isProcessAlive:x,readProcessIdentity:L};export{te as acquireDurableRustSessionServerLock,Z as durableSessionLoopDelayMs,$ as processDurableRustSessionRequests};
2
2
  //# sourceMappingURL=rust-semantic-session-server.js.map
@@ -1,2 +1,2 @@
1
- import{b as H,c as U,d as K,e as W,f as le,i as ce,j as ue,k as de,l as fe,m as D,o as me,p as pe}from"./chunk-BDUVI7TO.js";import{a as P,b as ne}from"./chunk-ILMHV3KM.js";import{b as te,c as ie,d as C,e as N,f as G,h as E,i as B,j as S}from"./chunk-OWOOWNJ5.js";import{d as F,e as se,f as re,g as oe,h as ae}from"./chunk-GAS2LJMP.js";import"./chunk-2OOY75BW.js";import{a as j,f as d,g as M}from"./chunk-HGFDYOVB.js";import"./chunk-JFMEXGFE.js";import{$ as ee,_ as q}from"./chunk-KYSDI3GE.js";import"./chunk-7F45LJKI.js";import k from"process";import{existsSync as Te,writeFileSync as ve}from"fs";import{dirname as Ae,isAbsolute as Ie,resolve as Ce}from"path";import{performance as L}from"perf_hooks";import{parentPort as Ee}from"worker_threads";import{resolve as he}from"path";var ze=4,x=class{constructor(n=ze){this.capacity=n;if(!Number.isSafeInteger(n)||n<=0)throw new Error("Rust analyzer session capacity must be a positive safe integer.")}capacity;entries=new Map;get(n){let i=this.entries.get(n);if(i)return this.entries.delete(n),this.entries.set(n,i),i}async acquire(n,i,t){let s=this.get(n);if(s)return s;if(this.entries.size>=this.capacity){let o=this.entries.entries().next().value;if(!o)throw new Error("Rust analyzer session registry capacity accounting is inconsistent.");this.entries.delete(o[0]);try{await t(o[1])}catch(l){throw this.restoreOldest(o),l}}let r=await i();if(r.key!==n){try{await t(r)}catch(o){throw new AggregateError([o],`Rust analyzer session factory returned '${r.key}' for reserved key '${n}', and the mismatched session could not be reaped.`,{cause:o})}throw new Error(`Rust analyzer session factory returned '${r.key}' for reserved key '${n}'.`)}return this.entries.set(n,r),r}deleteIfSame(n){return this.entries.get(n.key)!==n?!1:this.entries.delete(n.key)}async shutdownAll(n){let i=[...this.entries.values()];this.entries.clear();let t=await Promise.allSettled(i.map(n)),s=[];for(let r=0;r<t.length;r+=1){let o=t[r];if(o.status==="fulfilled")continue;let l=i[r];s.push({session:l,reason:o.reason}),this.entries.set(l.key,l)}if(s.length>0)throw new AggregateError(s.map(r=>r.reason),`Failed to shut down ${s.length} retained rust-analyzer session(s).`)}get size(){return this.entries.size}restoreOldest(n){let i=[...this.entries.entries()];this.entries.clear(),this.entries.set(n[0],n[1]);for(let[t,s]of i)this.entries.set(t,s)}};function Re(e,n){let i=he(e);return[...new Set(n.map(t=>he(i,t)))].sort((t,s)=>t<s?-1:t>s?1:0)}function ye(e,n,i){return JSON.stringify({binary:e,sessionRoot:n,linkedProjects:i})}var Fe="SCIP_RUST_SEMANTIC_REFERENCE_TASK_PROFILE_MS",We="SCIP_RUST_SEMANTIC_CALLEE_TASK_PROFILE_MS",_=new x,ge=Promise.resolve(),Me;Ee?.on("message",e=>{ge=ge.then(()=>xe(e)).catch(()=>{})});async function xe(e){if(Me??=Ae(e.responsePath),e.kind==="shutdown"){await He(),g(e.responsePath,{ok:!0},e.sharedBuffer);return}if(e.kind==="import-definitions"){try{let n=await Le(e.request);g(e.responsePath,{ok:!0,response:n},e.sharedBuffer)}catch(n){let i=B(n);if(i){g(e.responsePath,i,e.sharedBuffer);return}let t={available:!1,reason:n instanceof Error?n.message:String(n),sourcePaths:e.request.positions.map(s=>[s.id,null])};g(e.responsePath,{ok:!0,response:t},e.sharedBuffer)}return}try{let n=await _e(e.request);g(e.responsePath,{ok:!0,response:n},e.sharedBuffer)}catch(n){let i=B(n);if(i){g(e.responsePath,i,e.sharedBuffer);return}let t=De(e.request,n instanceof Error?n.message:String(n));g(e.responsePath,{ok:!0,response:t},e.sharedBuffer)}}async function Le(e){let n={timeoutMs:e.requestTimeoutMs,deadlineMs:e.readinessDeadlineMs},i=await d("rust.semantic.worker.session",()=>Pe(e.projectRoot,e.rustAnalyzerBinary,[e.file],{requestTimeoutMs:e.requestTimeoutMs,readinessDeadlineMs:e.readinessDeadlineMs}),()=>({kind:"import-definitions",files:1,positions:e.positions.length}));if(!i.capabilities.definitionProvider)return{available:!1,reason:"rust-analyzer initialized without textDocument/definition support.",sourcePaths:e.positions.map(o=>[o.id,null])};let t=0;await E(()=>d("rust.semantic.worker.open-source-documents",async()=>{t=await Ne(i,e.projectRoot,[e.file],{diagnosticsTimeoutMs:e.diagnosticsTimeoutMs,settleDelayMs:e.settleDelayMs,readinessDeadlineMs:e.readinessDeadlineMs})},()=>({files:1,openedDocuments:t,positions:e.positions.length})),()=>ke(_,i,e.readinessDeadlineMs));let s=0;return{available:!0,sourcePaths:await d("rust.semantic.worker.import-definitions",()=>P(e.positions,e.concurrency??8,async o=>{let l=await i.client.definition({textDocument:{uri:F(e.projectRoot,o.file)},position:{line:o.line,character:o.column}},n),u=Ge(e.projectRoot,l);return u&&(s+=1),[o.id,u]}),()=>({positions:e.positions.length,resolvedPositions:s,concurrency:e.concurrency??8}))}}async function _e(e){let n={timeoutMs:e.requestTimeoutMs,deadlineMs:e.readinessDeadlineMs},i=e.includeReferences!==!1,t=e.includeCallees===!0,s=e.includeSignatures===!0,r=H(e),o=U(e),l=K(e),u=W(e),c=await d("rust.semantic.worker.session",()=>Oe(e),()=>({kind:"semantic",definitions:u.length,referenceDefinitions:r.length,calleeDefinitions:o.length,signatureDefinitions:l.length,references:i,callees:t,signatures:s})),p=Be(c.capabilities,{references:i,callees:t,signatures:s});if(p)return De(e,p);let f=0;await E(()=>d("rust.semantic.worker.open-definition-documents",async()=>{f=await je(c,e)},()=>({definitions:u.length,openedDocuments:f})),()=>ke(_,c,e.readinessDeadlineMs));let m=0,b=0,y=j(),$=y?new Map:null,z=y?we(k.env[Fe]):null,J=()=>i?d("rust.semantic.worker.references",()=>P(r,e.concurrency??8,async a=>{let w=y?L.now():0,R=await me(c.client,re(e.projectRoot,a,!1),{requestTimeoutMs:e.requestTimeoutMs,retryTimeoutMs:e.referenceRetryTimeoutMs,deadlineMs:e.readinessDeadlineMs}),h=ae(oe(e.projectRoot,R.locations)),I=y?Math.round(L.now()-w):0;return Ue($,a.relativePath,{durationMs:I,references:h.length,hasReferences:h.length>0,slow:z!==null&&I>=z}),z!==null&&I>=z&&M({type:"span",name:"rust.semantic.worker.reference-task",durationMs:I,ok:!0,symbolId:a.symbolId,relativePath:a.relativePath,leaf:a.leaf,kind:a.kind,startLine:a.startLine,endLine:a.endLine,references:h.length,complete:R.complete}),h.length>0&&(b+=1),m+=h.length,{symbolId:a.symbolId,references:h,complete:R.complete}}),()=>({definitions:r.length,concurrency:e.concurrency??8,definitionsWithReferences:b,references:m})):Promise.resolve(r.map(a=>({symbolId:a.symbolId,references:[],complete:!0}))),V=0,Y=0,T=j(),Z=T?new Map:null,v=T?we(k.env[We]):null,Q=()=>t?d("rust.semantic.worker.callees",()=>P(o,e.concurrency??8,async a=>{let w=T?L.now():0,R=await pe(c.client,e.projectRoot,a,n),h=T?Math.round(L.now()-w):0;return Je(Z,a.relativePath,{durationMs:h,callees:R.length,hasCallees:R.length>0,slow:v!==null&&h>=v}),v!==null&&h>=v&&M({type:"span",name:"rust.semantic.worker.callee-task",durationMs:h,ok:!0,symbolId:a.symbolId,relativePath:a.relativePath,leaf:a.leaf,kind:a.kind,startLine:a.startLine,endLine:a.endLine,callees:R.length}),R.length>0&&(Y+=1),V+=R.length,{symbolId:a.symbolId,callees:R}}),()=>({definitions:o.length,concurrency:e.concurrency??8,definitionsWithCallees:Y,callees:V})):Promise.resolve([]),A,O;i&&t&&r.length>0&&o.length>0&&Ze()?[A,O]=await ne([J(),Q()]):(A=await J(),O=await Q()),Ke($),Ve(Z);let X=0,be=s?await d("rust.semantic.worker.signatures",()=>P(l,e.concurrency??8,async a=>{let w=await le(c.client,e.projectRoot,a,n);return w&&(X+=1),{symbolId:a.symbolId,signature:w}}),()=>({definitions:l.length,concurrency:e.concurrency??8,signaturesFound:X})):[];return{available:!0,references:A.filter(a=>a.complete).map(a=>[a.symbolId,a.references]),incompleteReferenceSymbolIds:A.filter(a=>!a.complete).map(a=>a.symbolId),...t?{callees:O.map(a=>[a.symbolId,a.callees])}:{},...s?{signatures:be.map(a=>[a.symbolId,a.signature])}:{}}}async function Oe(e){return Pe(e.projectRoot,e.rustAnalyzerBinary,W(e).map(n=>n.relativePath),{requestTimeoutMs:e.requestTimeoutMs,readinessDeadlineMs:e.readinessDeadlineMs})}async function Pe(e,n,i,t){let s=Re(e,de(e,i.map(l=>({relativePath:l})))),r=ue(e,s),o=ye(n,r,s);return _.acquire(o,async()=>{let l=ce(s),u=new te(ie(n,r,k.env,Me),{requestTimeoutMs:t.requestTimeoutMs,configuration:l}),c=t.readinessDeadlineMs===void 0?null:{afterGeneration:u.serverStatusGeneration(),deadlineMs:t.readinessDeadlineMs},p=await E(()=>d("rust.semantic.worker.initialize",()=>u.initialize({processId:k.pid,rootUri:F(r,"."),capabilities:{textDocument:{references:{dynamicRegistration:!1},definition:{dynamicRegistration:!1},callHierarchy:{dynamicRegistration:!1},hover:{dynamicRegistration:!1}}},initializationOptions:l},{timeoutMs:t.requestTimeoutMs,deadlineMs:t.readinessDeadlineMs}),()=>({linkedProjects:s.length,relativePaths:i.length})),()=>u.shutdownAndReap({deadlineMs:t.readinessDeadlineMs}));return{key:o,client:u,capabilities:p.capabilities,openedPaths:new Set,initializationReadiness:c}},l=>l.client.shutdownAndReap({deadlineMs:t.readinessDeadlineMs}))}async function je(e,n){let i=W(n).filter(c=>e.openedPaths.has(c.relativePath)?!1:Te(Ce(n.projectRoot,c.relativePath)));if(i.length===0)return await Se(e),0;let t=e.initializationReadiness,s=n.readinessDeadlineMs===void 0?null:{statusSnapshot:t?null:e.client.serverStatusSnapshot(),initializationGeneration:t?.afterGeneration,deadlineMs:n.readinessDeadlineMs},r=fe(e.client,n.projectRoot,i);for(let c of i)e.openedPaths.add(c.relativePath);let o=n.diagnosticsTimeoutMs??1e4,l=o;await d("rust.semantic.worker.diagnostics",()=>s?G(c=>(l=c,D(e.client,r,c)),o,s.deadlineMs):D(e.client,r,o),()=>({openedDocuments:r.length,timeoutMs:l}));let u=n.settleDelayMs??5e3;if(!s)await d("rust.semantic.worker.settle",()=>S(u),()=>({openedDocuments:r.length,settleDelayMs:u}));else{let c;await d("rust.semantic.worker.readiness",async()=>{let p=m=>d("rust.semantic.worker.settle",()=>S(m),()=>({openedDocuments:r.length,settleDelayMs:m})),f=s.initializationGeneration===void 0?await N(e.client,s.statusSnapshot,r.length,s.deadlineMs,u,Date.now,p):await C(e.client,s.initializationGeneration,r.length,s.deadlineMs,u,Date.now,p);s.initializationGeneration!==void 0&&(e.initializationReadiness=null),c=f?.health},()=>({phase:s.initializationGeneration===void 0?"didOpen":"initialize+didOpen",openedDocuments:r.length,health:c}))}return r.length}async function Ne(e,n,i,t){let s=i.filter(f=>!e.openedPaths.has(f));if(s.length===0)return await Se(e),0;let r=e.initializationReadiness,o=t.readinessDeadlineMs===void 0?null:{statusSnapshot:r?null:e.client.serverStatusSnapshot(),initializationGeneration:r?.afterGeneration,deadlineMs:t.readinessDeadlineMs},l=[];for(let f of s)try{let m=F(n,f);e.client.didOpenTextDocument({uri:m,languageId:"rust",version:1,text:q(n,f,{inputKind:"indexed Rust source file"})}),e.openedPaths.add(f),l.push(m)}catch(m){if(!ee(m))throw m}let u=t.diagnosticsTimeoutMs??1e4,c=u;await d("rust.semantic.worker.diagnostics",()=>o?G(f=>(c=f,D(e.client,l,f)),u,o.deadlineMs):D(e.client,l,u),()=>({openedDocuments:l.length,timeoutMs:c}));let p=t.settleDelayMs??5e3;if(!o)await d("rust.semantic.worker.settle",()=>S(p),()=>({openedDocuments:l.length,settleDelayMs:p}));else{let f;await d("rust.semantic.worker.readiness",async()=>{let m=y=>d("rust.semantic.worker.settle",()=>S(y),()=>({openedDocuments:l.length,settleDelayMs:y})),b=o.initializationGeneration===void 0?await N(e.client,o.statusSnapshot,l.length,o.deadlineMs,p,Date.now,m):await C(e.client,o.initializationGeneration,l.length,o.deadlineMs,p,Date.now,m);o.initializationGeneration!==void 0&&(e.initializationReadiness=null),f=b?.health},()=>({phase:o.initializationGeneration===void 0?"didOpen":"initialize+didOpen",openedDocuments:l.length,health:f}))}return l.length}async function Se(e){let n=e.initializationReadiness;if(!n)return;let i;await d("rust.semantic.worker.readiness",async()=>{i=(await C(e.client,n.afterGeneration,0,n.deadlineMs,0)).health,e.initializationReadiness=null},()=>({phase:"initialize",openedDocuments:0,health:i}))}function Ge(e,n){for(let i of n){let t=se(e,i.uri);if(!(!t||t===".."||t.startsWith("../")||Ie(t)))return t}return null}function Be(e,n){return n.references&&!e.referencesProvider?"rust-analyzer initialized without textDocument/references support.":n.callees&&!e.callHierarchyProvider?"rust-analyzer initialized without call hierarchy support.":n.signatures&&!e.hoverProvider?"rust-analyzer initialized without hover support.":null}function De(e,n){let i=H(e),t=U(e),s=K(e);return{available:!1,reason:n,references:i.map(r=>[r.symbolId,[]]),...e.includeCallees?{callees:t.map(r=>[r.symbolId,[]])}:{},...e.includeSignatures?{signatures:s.map(r=>[r.symbolId,null])}:{}}}async function He(){await _.shutdownAll(e=>e.client.shutdownAndReap())}async function ke(e,n,i){e.deleteIfSame(n),await n.client.shutdownAndReap({deadlineMs:i})}function Ue(e,n,i){if(!e)return;let t=$e(e,n);t.definitions+=1,i.hasReferences&&(t.definitionsWithReferences+=1),t.references+=i.references,t.durationMs+=i.durationMs,t.maxDurationMs=Math.max(t.maxDurationMs,i.durationMs),i.slow&&(t.slowTasks+=1)}function Ke(e){if(!e)return;let n=[...e.entries()].sort(([i,t],[s,r])=>r.durationMs-t.durationMs||i.localeCompare(s));for(let[i,t]of n)M({type:"span",name:"rust.semantic.worker.references.by-file",durationMs:t.durationMs,ok:!0,relativePath:i,definitions:t.definitions,definitionsWithReferences:t.definitionsWithReferences,references:t.references,maxDurationMs:t.maxDurationMs,slowTasks:t.slowTasks,aggregate:"sum-task-duration"})}function $e(e,n){let i=e.get(n);if(i)return i;let t={definitions:0,definitionsWithReferences:0,references:0,durationMs:0,maxDurationMs:0,slowTasks:0};return e.set(n,t),t}function Je(e,n,i){if(!e)return;let t=Ye(e,n);t.definitions+=1,i.hasCallees&&(t.definitionsWithCallees+=1),t.callees+=i.callees,t.durationMs+=i.durationMs,t.maxDurationMs=Math.max(t.maxDurationMs,i.durationMs),i.slow&&(t.slowTasks+=1)}function Ve(e){if(!e)return;let n=[...e.entries()].sort(([i,t],[s,r])=>r.durationMs-t.durationMs||i.localeCompare(s));for(let[i,t]of n)M({type:"span",name:"rust.semantic.worker.callees.by-file",durationMs:t.durationMs,ok:!0,relativePath:i,definitions:t.definitions,definitionsWithCallees:t.definitionsWithCallees,callees:t.callees,maxDurationMs:t.maxDurationMs,slowTasks:t.slowTasks,aggregate:"sum-task-duration"})}function Ye(e,n){let i=e.get(n);if(i)return i;let t={definitions:0,definitionsWithCallees:0,callees:0,durationMs:0,maxDurationMs:0,slowTasks:0};return e.set(n,t),t}function we(e){if(e===void 0||e==="")return null;let n=Number(e);return Number.isInteger(n)&&n>=0?n:null}function Ze(){let e=k.env.SCIP_RUST_SEMANTIC_PARALLEL_OPERATIONS;return e!=="0"&&e!=="false"}function g(e,n,i){ve(e,JSON.stringify(n));let t=new Int32Array(i);Atomics.store(t,0,1),Atomics.notify(t,0)}export{ke as discardRustAnalyzerSession};
1
+ import{b as H,c as U,d as K,e as W,f as le,i as ce,j as ue,k as de,l as fe,m as D,o as me,p as pe}from"./chunk-3WTY4LP2.js";import{a as P,b as ne}from"./chunk-ILMHV3KM.js";import{b as te,c as ie,d as C,e as N,f as G,h as E,i as B,j as S}from"./chunk-C4RHHCKL.js";import{d as F,e as se,f as re,g as oe,h as ae}from"./chunk-ODPDP7A4.js";import"./chunk-2OOY75BW.js";import{a as j,f as d,g as M}from"./chunk-HGFDYOVB.js";import"./chunk-JFMEXGFE.js";import{$ as q,aa as ee}from"./chunk-7HXT6YLU.js";import"./chunk-7F45LJKI.js";import k from"process";import{existsSync as Te,writeFileSync as ve}from"fs";import{dirname as Ae,isAbsolute as Ie,resolve as Ce}from"path";import{performance as L}from"perf_hooks";import{parentPort as Ee}from"worker_threads";import{resolve as he}from"path";var ze=4,x=class{constructor(n=ze){this.capacity=n;if(!Number.isSafeInteger(n)||n<=0)throw new Error("Rust analyzer session capacity must be a positive safe integer.")}capacity;entries=new Map;get(n){let i=this.entries.get(n);if(i)return this.entries.delete(n),this.entries.set(n,i),i}async acquire(n,i,t){let s=this.get(n);if(s)return s;if(this.entries.size>=this.capacity){let o=this.entries.entries().next().value;if(!o)throw new Error("Rust analyzer session registry capacity accounting is inconsistent.");this.entries.delete(o[0]);try{await t(o[1])}catch(l){throw this.restoreOldest(o),l}}let r=await i();if(r.key!==n){try{await t(r)}catch(o){throw new AggregateError([o],`Rust analyzer session factory returned '${r.key}' for reserved key '${n}', and the mismatched session could not be reaped.`,{cause:o})}throw new Error(`Rust analyzer session factory returned '${r.key}' for reserved key '${n}'.`)}return this.entries.set(n,r),r}deleteIfSame(n){return this.entries.get(n.key)!==n?!1:this.entries.delete(n.key)}async shutdownAll(n){let i=[...this.entries.values()];this.entries.clear();let t=await Promise.allSettled(i.map(n)),s=[];for(let r=0;r<t.length;r+=1){let o=t[r];if(o.status==="fulfilled")continue;let l=i[r];s.push({session:l,reason:o.reason}),this.entries.set(l.key,l)}if(s.length>0)throw new AggregateError(s.map(r=>r.reason),`Failed to shut down ${s.length} retained rust-analyzer session(s).`)}get size(){return this.entries.size}restoreOldest(n){let i=[...this.entries.entries()];this.entries.clear(),this.entries.set(n[0],n[1]);for(let[t,s]of i)this.entries.set(t,s)}};function Re(e,n){let i=he(e);return[...new Set(n.map(t=>he(i,t)))].sort((t,s)=>t<s?-1:t>s?1:0)}function ye(e,n,i){return JSON.stringify({binary:e,sessionRoot:n,linkedProjects:i})}var Fe="SCIP_RUST_SEMANTIC_REFERENCE_TASK_PROFILE_MS",We="SCIP_RUST_SEMANTIC_CALLEE_TASK_PROFILE_MS",_=new x,ge=Promise.resolve(),Me;Ee?.on("message",e=>{ge=ge.then(()=>xe(e)).catch(()=>{})});async function xe(e){if(Me??=Ae(e.responsePath),e.kind==="shutdown"){await He(),g(e.responsePath,{ok:!0},e.sharedBuffer);return}if(e.kind==="import-definitions"){try{let n=await Le(e.request);g(e.responsePath,{ok:!0,response:n},e.sharedBuffer)}catch(n){let i=B(n);if(i){g(e.responsePath,i,e.sharedBuffer);return}let t={available:!1,reason:n instanceof Error?n.message:String(n),sourcePaths:e.request.positions.map(s=>[s.id,null])};g(e.responsePath,{ok:!0,response:t},e.sharedBuffer)}return}try{let n=await _e(e.request);g(e.responsePath,{ok:!0,response:n},e.sharedBuffer)}catch(n){let i=B(n);if(i){g(e.responsePath,i,e.sharedBuffer);return}let t=De(e.request,n instanceof Error?n.message:String(n));g(e.responsePath,{ok:!0,response:t},e.sharedBuffer)}}async function Le(e){let n={timeoutMs:e.requestTimeoutMs,deadlineMs:e.readinessDeadlineMs},i=await d("rust.semantic.worker.session",()=>Pe(e.projectRoot,e.rustAnalyzerBinary,[e.file],{requestTimeoutMs:e.requestTimeoutMs,readinessDeadlineMs:e.readinessDeadlineMs}),()=>({kind:"import-definitions",files:1,positions:e.positions.length}));if(!i.capabilities.definitionProvider)return{available:!1,reason:"rust-analyzer initialized without textDocument/definition support.",sourcePaths:e.positions.map(o=>[o.id,null])};let t=0;await E(()=>d("rust.semantic.worker.open-source-documents",async()=>{t=await Ne(i,e.projectRoot,[e.file],{diagnosticsTimeoutMs:e.diagnosticsTimeoutMs,settleDelayMs:e.settleDelayMs,readinessDeadlineMs:e.readinessDeadlineMs})},()=>({files:1,openedDocuments:t,positions:e.positions.length})),()=>ke(_,i,e.readinessDeadlineMs));let s=0;return{available:!0,sourcePaths:await d("rust.semantic.worker.import-definitions",()=>P(e.positions,e.concurrency??8,async o=>{let l=await i.client.definition({textDocument:{uri:F(e.projectRoot,o.file)},position:{line:o.line,character:o.column}},n),u=Ge(e.projectRoot,l);return u&&(s+=1),[o.id,u]}),()=>({positions:e.positions.length,resolvedPositions:s,concurrency:e.concurrency??8}))}}async function _e(e){let n={timeoutMs:e.requestTimeoutMs,deadlineMs:e.readinessDeadlineMs},i=e.includeReferences!==!1,t=e.includeCallees===!0,s=e.includeSignatures===!0,r=H(e),o=U(e),l=K(e),u=W(e),c=await d("rust.semantic.worker.session",()=>Oe(e),()=>({kind:"semantic",definitions:u.length,referenceDefinitions:r.length,calleeDefinitions:o.length,signatureDefinitions:l.length,references:i,callees:t,signatures:s})),p=Be(c.capabilities,{references:i,callees:t,signatures:s});if(p)return De(e,p);let f=0;await E(()=>d("rust.semantic.worker.open-definition-documents",async()=>{f=await je(c,e)},()=>({definitions:u.length,openedDocuments:f})),()=>ke(_,c,e.readinessDeadlineMs));let m=0,b=0,y=j(),$=y?new Map:null,z=y?we(k.env[Fe]):null,J=()=>i?d("rust.semantic.worker.references",()=>P(r,e.concurrency??8,async a=>{let w=y?L.now():0,R=await me(c.client,re(e.projectRoot,a,!1),{requestTimeoutMs:e.requestTimeoutMs,retryTimeoutMs:e.referenceRetryTimeoutMs,deadlineMs:e.readinessDeadlineMs}),h=ae(oe(e.projectRoot,R.locations)),I=y?Math.round(L.now()-w):0;return Ue($,a.relativePath,{durationMs:I,references:h.length,hasReferences:h.length>0,slow:z!==null&&I>=z}),z!==null&&I>=z&&M({type:"span",name:"rust.semantic.worker.reference-task",durationMs:I,ok:!0,symbolId:a.symbolId,relativePath:a.relativePath,leaf:a.leaf,kind:a.kind,startLine:a.startLine,endLine:a.endLine,references:h.length,complete:R.complete}),h.length>0&&(b+=1),m+=h.length,{symbolId:a.symbolId,references:h,complete:R.complete}}),()=>({definitions:r.length,concurrency:e.concurrency??8,definitionsWithReferences:b,references:m})):Promise.resolve(r.map(a=>({symbolId:a.symbolId,references:[],complete:!0}))),V=0,Y=0,T=j(),Z=T?new Map:null,v=T?we(k.env[We]):null,Q=()=>t?d("rust.semantic.worker.callees",()=>P(o,e.concurrency??8,async a=>{let w=T?L.now():0,R=await pe(c.client,e.projectRoot,a,n),h=T?Math.round(L.now()-w):0;return Je(Z,a.relativePath,{durationMs:h,callees:R.length,hasCallees:R.length>0,slow:v!==null&&h>=v}),v!==null&&h>=v&&M({type:"span",name:"rust.semantic.worker.callee-task",durationMs:h,ok:!0,symbolId:a.symbolId,relativePath:a.relativePath,leaf:a.leaf,kind:a.kind,startLine:a.startLine,endLine:a.endLine,callees:R.length}),R.length>0&&(Y+=1),V+=R.length,{symbolId:a.symbolId,callees:R}}),()=>({definitions:o.length,concurrency:e.concurrency??8,definitionsWithCallees:Y,callees:V})):Promise.resolve([]),A,O;i&&t&&r.length>0&&o.length>0&&Ze()?[A,O]=await ne([J(),Q()]):(A=await J(),O=await Q()),Ke($),Ve(Z);let X=0,be=s?await d("rust.semantic.worker.signatures",()=>P(l,e.concurrency??8,async a=>{let w=await le(c.client,e.projectRoot,a,n);return w&&(X+=1),{symbolId:a.symbolId,signature:w}}),()=>({definitions:l.length,concurrency:e.concurrency??8,signaturesFound:X})):[];return{available:!0,references:A.filter(a=>a.complete).map(a=>[a.symbolId,a.references]),incompleteReferenceSymbolIds:A.filter(a=>!a.complete).map(a=>a.symbolId),...t?{callees:O.map(a=>[a.symbolId,a.callees])}:{},...s?{signatures:be.map(a=>[a.symbolId,a.signature])}:{}}}async function Oe(e){return Pe(e.projectRoot,e.rustAnalyzerBinary,W(e).map(n=>n.relativePath),{requestTimeoutMs:e.requestTimeoutMs,readinessDeadlineMs:e.readinessDeadlineMs})}async function Pe(e,n,i,t){let s=Re(e,de(e,i.map(l=>({relativePath:l})))),r=ue(e,s),o=ye(n,r,s);return _.acquire(o,async()=>{let l=ce(s),u=new te(ie(n,r,k.env,Me),{requestTimeoutMs:t.requestTimeoutMs,configuration:l}),c=t.readinessDeadlineMs===void 0?null:{afterGeneration:u.serverStatusGeneration(),deadlineMs:t.readinessDeadlineMs},p=await E(()=>d("rust.semantic.worker.initialize",()=>u.initialize({processId:k.pid,rootUri:F(r,"."),capabilities:{textDocument:{references:{dynamicRegistration:!1},definition:{dynamicRegistration:!1},callHierarchy:{dynamicRegistration:!1},hover:{dynamicRegistration:!1}}},initializationOptions:l},{timeoutMs:t.requestTimeoutMs,deadlineMs:t.readinessDeadlineMs}),()=>({linkedProjects:s.length,relativePaths:i.length})),()=>u.shutdownAndReap({deadlineMs:t.readinessDeadlineMs}));return{key:o,client:u,capabilities:p.capabilities,openedPaths:new Set,initializationReadiness:c}},l=>l.client.shutdownAndReap({deadlineMs:t.readinessDeadlineMs}))}async function je(e,n){let i=W(n).filter(c=>e.openedPaths.has(c.relativePath)?!1:Te(Ce(n.projectRoot,c.relativePath)));if(i.length===0)return await Se(e),0;let t=e.initializationReadiness,s=n.readinessDeadlineMs===void 0?null:{statusSnapshot:t?null:e.client.serverStatusSnapshot(),initializationGeneration:t?.afterGeneration,deadlineMs:n.readinessDeadlineMs},r=fe(e.client,n.projectRoot,i);for(let c of i)e.openedPaths.add(c.relativePath);let o=n.diagnosticsTimeoutMs??1e4,l=o;await d("rust.semantic.worker.diagnostics",()=>s?G(c=>(l=c,D(e.client,r,c)),o,s.deadlineMs):D(e.client,r,o),()=>({openedDocuments:r.length,timeoutMs:l}));let u=n.settleDelayMs??5e3;if(!s)await d("rust.semantic.worker.settle",()=>S(u),()=>({openedDocuments:r.length,settleDelayMs:u}));else{let c;await d("rust.semantic.worker.readiness",async()=>{let p=m=>d("rust.semantic.worker.settle",()=>S(m),()=>({openedDocuments:r.length,settleDelayMs:m})),f=s.initializationGeneration===void 0?await N(e.client,s.statusSnapshot,r.length,s.deadlineMs,u,Date.now,p):await C(e.client,s.initializationGeneration,r.length,s.deadlineMs,u,Date.now,p);s.initializationGeneration!==void 0&&(e.initializationReadiness=null),c=f?.health},()=>({phase:s.initializationGeneration===void 0?"didOpen":"initialize+didOpen",openedDocuments:r.length,health:c}))}return r.length}async function Ne(e,n,i,t){let s=i.filter(f=>!e.openedPaths.has(f));if(s.length===0)return await Se(e),0;let r=e.initializationReadiness,o=t.readinessDeadlineMs===void 0?null:{statusSnapshot:r?null:e.client.serverStatusSnapshot(),initializationGeneration:r?.afterGeneration,deadlineMs:t.readinessDeadlineMs},l=[];for(let f of s)try{let m=F(n,f);e.client.didOpenTextDocument({uri:m,languageId:"rust",version:1,text:q(n,f,{inputKind:"indexed Rust source file"})}),e.openedPaths.add(f),l.push(m)}catch(m){if(!ee(m))throw m}let u=t.diagnosticsTimeoutMs??1e4,c=u;await d("rust.semantic.worker.diagnostics",()=>o?G(f=>(c=f,D(e.client,l,f)),u,o.deadlineMs):D(e.client,l,u),()=>({openedDocuments:l.length,timeoutMs:c}));let p=t.settleDelayMs??5e3;if(!o)await d("rust.semantic.worker.settle",()=>S(p),()=>({openedDocuments:l.length,settleDelayMs:p}));else{let f;await d("rust.semantic.worker.readiness",async()=>{let m=y=>d("rust.semantic.worker.settle",()=>S(y),()=>({openedDocuments:l.length,settleDelayMs:y})),b=o.initializationGeneration===void 0?await N(e.client,o.statusSnapshot,l.length,o.deadlineMs,p,Date.now,m):await C(e.client,o.initializationGeneration,l.length,o.deadlineMs,p,Date.now,m);o.initializationGeneration!==void 0&&(e.initializationReadiness=null),f=b?.health},()=>({phase:o.initializationGeneration===void 0?"didOpen":"initialize+didOpen",openedDocuments:l.length,health:f}))}return l.length}async function Se(e){let n=e.initializationReadiness;if(!n)return;let i;await d("rust.semantic.worker.readiness",async()=>{i=(await C(e.client,n.afterGeneration,0,n.deadlineMs,0)).health,e.initializationReadiness=null},()=>({phase:"initialize",openedDocuments:0,health:i}))}function Ge(e,n){for(let i of n){let t=se(e,i.uri);if(!(!t||t===".."||t.startsWith("../")||Ie(t)))return t}return null}function Be(e,n){return n.references&&!e.referencesProvider?"rust-analyzer initialized without textDocument/references support.":n.callees&&!e.callHierarchyProvider?"rust-analyzer initialized without call hierarchy support.":n.signatures&&!e.hoverProvider?"rust-analyzer initialized without hover support.":null}function De(e,n){let i=H(e),t=U(e),s=K(e);return{available:!1,reason:n,references:i.map(r=>[r.symbolId,[]]),...e.includeCallees?{callees:t.map(r=>[r.symbolId,[]])}:{},...e.includeSignatures?{signatures:s.map(r=>[r.symbolId,null])}:{}}}async function He(){await _.shutdownAll(e=>e.client.shutdownAndReap())}async function ke(e,n,i){e.deleteIfSame(n),await n.client.shutdownAndReap({deadlineMs:i})}function Ue(e,n,i){if(!e)return;let t=$e(e,n);t.definitions+=1,i.hasReferences&&(t.definitionsWithReferences+=1),t.references+=i.references,t.durationMs+=i.durationMs,t.maxDurationMs=Math.max(t.maxDurationMs,i.durationMs),i.slow&&(t.slowTasks+=1)}function Ke(e){if(!e)return;let n=[...e.entries()].sort(([i,t],[s,r])=>r.durationMs-t.durationMs||i.localeCompare(s));for(let[i,t]of n)M({type:"span",name:"rust.semantic.worker.references.by-file",durationMs:t.durationMs,ok:!0,relativePath:i,definitions:t.definitions,definitionsWithReferences:t.definitionsWithReferences,references:t.references,maxDurationMs:t.maxDurationMs,slowTasks:t.slowTasks,aggregate:"sum-task-duration"})}function $e(e,n){let i=e.get(n);if(i)return i;let t={definitions:0,definitionsWithReferences:0,references:0,durationMs:0,maxDurationMs:0,slowTasks:0};return e.set(n,t),t}function Je(e,n,i){if(!e)return;let t=Ye(e,n);t.definitions+=1,i.hasCallees&&(t.definitionsWithCallees+=1),t.callees+=i.callees,t.durationMs+=i.durationMs,t.maxDurationMs=Math.max(t.maxDurationMs,i.durationMs),i.slow&&(t.slowTasks+=1)}function Ve(e){if(!e)return;let n=[...e.entries()].sort(([i,t],[s,r])=>r.durationMs-t.durationMs||i.localeCompare(s));for(let[i,t]of n)M({type:"span",name:"rust.semantic.worker.callees.by-file",durationMs:t.durationMs,ok:!0,relativePath:i,definitions:t.definitions,definitionsWithCallees:t.definitionsWithCallees,callees:t.callees,maxDurationMs:t.maxDurationMs,slowTasks:t.slowTasks,aggregate:"sum-task-duration"})}function Ye(e,n){let i=e.get(n);if(i)return i;let t={definitions:0,definitionsWithCallees:0,callees:0,durationMs:0,maxDurationMs:0,slowTasks:0};return e.set(n,t),t}function we(e){if(e===void 0||e==="")return null;let n=Number(e);return Number.isInteger(n)&&n>=0?n:null}function Ze(){let e=k.env.SCIP_RUST_SEMANTIC_PARALLEL_OPERATIONS;return e!=="0"&&e!=="false"}function g(e,n,i){ve(e,JSON.stringify(n));let t=new Int32Array(i);Atomics.store(t,0,1),Atomics.notify(t,0)}export{ke as discardRustAnalyzerSession};
2
2
  //# sourceMappingURL=rust-semantic-session-worker.js.map
@@ -1,2 +1,2 @@
1
- import{a as b,b as c,c as d,d as e,e as f,f as g,g as h,h as i,i as j,j as k,k as l,l as m,m as n,n as o,o as p,p as q}from"./chunk-BDUVI7TO.js";import{a}from"./chunk-ILMHV3KM.js";import"./chunk-OWOOWNJ5.js";import"./chunk-GAS2LJMP.js";import"./chunk-2OOY75BW.js";import"./chunk-JFMEXGFE.js";import"./chunk-KYSDI3GE.js";import"./chunk-7F45LJKI.js";export{q as calleesForDefinition,l as cargoManifestsForDefinitions,i as hoverToRustSignature,h as hoverWithRetry,m as openDefinitionDocuments,p as referencesWithCompletion,o as referencesWithRetry,b as runRustAnalyzerReferenceBatch,a as runWithConcurrency,j as rustAnalyzerInitializationOptions,k as rustAnalyzerSessionRoot,d as rustRequestCalleeDefinitions,c as rustRequestReferenceDefinitions,f as rustRequestSessionDefinitions,e as rustRequestSignatureDefinitions,g as signatureForDefinition,n as waitForOpenedDocuments};
1
+ import{a as b,b as c,c as d,d as e,e as f,f as g,g as h,h as i,i as j,j as k,k as l,l as m,m as n,n as o,o as p,p as q}from"./chunk-3WTY4LP2.js";import{a}from"./chunk-ILMHV3KM.js";import"./chunk-C4RHHCKL.js";import"./chunk-ODPDP7A4.js";import"./chunk-2OOY75BW.js";import"./chunk-JFMEXGFE.js";import"./chunk-7HXT6YLU.js";import"./chunk-7F45LJKI.js";export{q as calleesForDefinition,l as cargoManifestsForDefinitions,i as hoverToRustSignature,h as hoverWithRetry,m as openDefinitionDocuments,p as referencesWithCompletion,o as referencesWithRetry,b as runRustAnalyzerReferenceBatch,a as runWithConcurrency,j as rustAnalyzerInitializationOptions,k as rustAnalyzerSessionRoot,d as rustRequestCalleeDefinitions,c as rustRequestReferenceDefinitions,f as rustRequestSessionDefinitions,e as rustRequestSignatureDefinitions,g as signatureForDefinition,n as waitForOpenedDocuments};
2
2
  //# sourceMappingURL=rust-semantic-worker.js.map
@@ -0,0 +1,2 @@
1
+ import{a,b}from"./chunk-AN76MGUE.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-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 referenceReachability,b as slice};
2
+ //# sourceMappingURL=slice-PHPVNCWX.js.map
@@ -0,0 +1,2 @@
1
+ import{a,b}from"./chunk-2N6WBNDC.js";import"./chunk-RVZC6TJE.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-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{b as consumerSurface,a as surface};
2
+ //# sourceMappingURL=surface-MQX5MPIV.js.map
@@ -1,2 +1,2 @@
1
- import{a}from"./chunk-DTZCKZEU.js";import{a as c}from"./chunk-26CT72HM.js";import{b as i,e as m}from"./chunk-HOENASQM.js";import"./chunk-3L2ZBPEX.js";import"./chunk-YXPUP5G2.js";import{c as l}from"./chunk-DRENNWRG.js";import"./chunk-MXNGIEPU.js";import"./chunk-RTQ7NEKG.js";import"./chunk-GUFSG5TX.js";import"./chunk-IW5XQG5G.js";import"./chunk-H5EXS3HM.js";import"./chunk-HGFDYOVB.js";import"./chunk-KYSDI3GE.js";import"./chunk-7F45LJKI.js";function g(o,t){let s=i(o,t),e=f(s);for(let n of e)console.log(n)}function R(o,t,s="No results found for resolved symbol."){return i(o,t).match?s:p(t,m(o,t,5))}function S(o,t,s,e){return{...a(o,t),[e]:s}}function p(o,t){let s=`No definition matched '${o}'.`;return t.length>0?`${s} Suggestions: ${t.join(", ")}`:s}function f(o){if(!o.match||o.total<=1)return[];let t=o.match,s=Math.max(0,o.total-1),e=[`Resolved: ${l(t.symbol)} (${t.relativePath}) -- ${s} other definition(s) share this name; qualify as <dir/leaf> to target another.`],n=o.candidates.slice(0,3);return n.length>0&&e.push(`Alternates: ${n.map(r=>`${r.shortName} (${r.relativePath}:${c(r.startLine)})`).join("; ")}`),e.push(""),e}export{p as noMatchMessage,g as symbolResolutionBefore,R as symbolResolutionEmptyMessage,a as symbolResolutionJson,S as withSymbolResolutionJson};
2
- //# sourceMappingURL=symbol-resolution-WD5EU5JE.js.map
1
+ import{a}from"./chunk-ZKB2XUEN.js";import{a as c}from"./chunk-26CT72HM.js";import{b as i,e as m}from"./chunk-2USA3S3P.js";import"./chunk-2VAHDDLM.js";import"./chunk-YXPUP5G2.js";import{c as l}from"./chunk-BL6DCHQP.js";import"./chunk-MXNGIEPU.js";import"./chunk-ATXPTSEI.js";import"./chunk-CKBUBRYD.js";import"./chunk-IW5XQG5G.js";import"./chunk-H5EXS3HM.js";import"./chunk-HGFDYOVB.js";import"./chunk-7HXT6YLU.js";import"./chunk-7F45LJKI.js";function g(o,t){let s=i(o,t),e=f(s);for(let n of e)console.log(n)}function R(o,t,s="No results found for resolved symbol."){return i(o,t).match?s:p(t,m(o,t,5))}function S(o,t,s,e){return{...a(o,t),[e]:s}}function p(o,t){let s=`No definition matched '${o}'.`;return t.length>0?`${s} Suggestions: ${t.join(", ")}`:s}function f(o){if(!o.match||o.total<=1)return[];let t=o.match,s=Math.max(0,o.total-1),e=[`Resolved: ${l(t.symbol)} (${t.relativePath}) -- ${s} other definition(s) share this name; qualify as <dir/leaf> to target another.`],n=o.candidates.slice(0,3);return n.length>0&&e.push(`Alternates: ${n.map(r=>`${r.shortName} (${r.relativePath}:${c(r.startLine)})`).join("; ")}`),e.push(""),e}export{p as noMatchMessage,g as symbolResolutionBefore,R as symbolResolutionEmptyMessage,a as symbolResolutionJson,S as withSymbolResolutionJson};
2
+ //# sourceMappingURL=symbol-resolution-DBLVXLBC.js.map
@@ -0,0 +1,2 @@
1
+ import{a,b}from"./chunk-HYT2R7LX.js";import"./chunk-RVZC6TJE.js";import"./chunk-L7KTFEAV.js";import"./chunk-2USA3S3P.js";import"./chunk-2VAHDDLM.js";import"./chunk-YXPUP5G2.js";import"./chunk-BL6DCHQP.js";import"./chunk-ATXPTSEI.js";import"./chunk-CKBUBRYD.js";import"./chunk-IW5XQG5G.js";import"./chunk-H5EXS3HM.js";import"./chunk-HGFDYOVB.js";import"./chunk-7HXT6YLU.js";import"./chunk-7F45LJKI.js";export{b as moduleMap,a as system};
2
+ //# sourceMappingURL=system-JOPKV4OG.js.map
@@ -0,0 +1,2 @@
1
+ import{a,b,c}from"./chunk-NYKZMCRC.js";import"./chunk-POBJ6FR2.js";import"./chunk-HAXXKRTD.js";import"./chunk-WDSFQDPN.js";import"./chunk-ANLNLY66.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-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-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{c as qualifiedTraceEvidence,a as trace,b as traceEvidence};
2
+ //# sourceMappingURL=trace-I2P2YFH4.js.map
@@ -1,2 +1,2 @@
1
- import{b as T}from"./chunk-P42EIXTA.js";import{a as M}from"./chunk-KLFEXGQA.js";import{a as P,c as j}from"./chunk-WK46TNUM.js";import"./chunk-IICPE7B2.js";import{c as b,e as v,f as l}from"./chunk-TQZV7KV4.js";import"./chunk-3L2ZBPEX.js";import"./chunk-YXPUP5G2.js";import"./chunk-DRENNWRG.js";import{d as g}from"./chunk-FIQRSHVM.js";import"./chunk-TY7CRN3Z.js";import"./chunk-DHEQMPLW.js";import{a as w}from"./chunk-NOGJXYFO.js";import"./chunk-IZDPJ2QI.js";import"./chunk-WYPL7GF7.js";import"./chunk-RTQ7NEKG.js";import{d as f}from"./chunk-GUFSG5TX.js";import"./chunk-MWN53KRN.js";import"./chunk-IW5XQG5G.js";import"./chunk-3AF4TUFK.js";import"./chunk-FGA2U4OR.js";import"./chunk-B3PYOSCX.js";import"./chunk-H5EXS3HM.js";import{c as y,d}from"./chunk-HGFDYOVB.js";import{c as m}from"./chunk-JFMEXGFE.js";import{c as h,f as S}from"./chunk-KYSDI3GE.js";import"./chunk-7F45LJKI.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