scip-query 0.22.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (470) hide show
  1. package/CHANGELOG.md +500 -0
  2. package/README.md +13 -0
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/by-kind-H3P6BR5G.js +2 -0
  5. package/dist/call-graph-VTG2CUOQ.js +2 -0
  6. package/dist/call-graph-evidence-BociKRpF.d.ts +19 -0
  7. package/dist/chunk-2BMSSRBH.js +2 -0
  8. package/dist/{chunk-TAYD3AE7.js → chunk-2GJSD5GY.js} +2 -2
  9. package/dist/{chunk-TUQIPUDS.js → chunk-2M2LSIMY.js} +3 -3
  10. package/dist/{chunk-GIQ6CSL4.js → chunk-2N6WBNDC.js} +2 -2
  11. package/dist/{chunk-JHH5SCZ3.js → chunk-2OOY75BW.js} +2 -2
  12. package/dist/{chunk-EELPBR7E.js → chunk-2USA3S3P.js} +2 -2
  13. package/dist/chunk-2VAHDDLM.js +133 -0
  14. package/dist/chunk-2XWIUW5Z.js +455 -0
  15. package/dist/{chunk-57N6LN2A.js → chunk-3AF4TUFK.js} +2 -2
  16. package/dist/chunk-3D4BOXW6.js +20 -0
  17. package/dist/{chunk-FFJQZG6J.js → chunk-3LO4FST5.js} +2 -2
  18. package/dist/{chunk-HXOU4XNH.js → chunk-3WTY4LP2.js} +2 -2
  19. package/dist/{chunk-DPWKKNKI.js → chunk-3Z5AMSK6.js} +2 -2
  20. package/dist/{chunk-F24G5NBE.js → chunk-44IETFOU.js} +2 -2
  21. package/dist/chunk-4FR6GQIT.js +2 -0
  22. package/dist/chunk-4KBTHJLP.js +2 -0
  23. package/dist/chunk-5BIKR67W.js +2 -0
  24. package/dist/{chunk-DJAO2OZJ.js → chunk-5PROPLHI.js} +2 -2
  25. package/dist/chunk-5V7EPTII.js +2 -0
  26. package/dist/{chunk-VZ7NXSHV.js → chunk-62LPZCBQ.js} +2 -2
  27. package/dist/{chunk-LXQUF2RP.js → chunk-64O2JHQA.js} +2 -2
  28. package/dist/chunk-6D4F5VWG.js +10 -0
  29. package/dist/{chunk-NEIQPFBI.js → chunk-6ERFBC3X.js} +2 -2
  30. package/dist/{chunk-4HE7MVWD.js → chunk-6ILKOOGH.js} +2 -2
  31. package/dist/chunk-6MFXCMZC.js +2 -0
  32. package/dist/chunk-6O7FACKB.js +2 -0
  33. package/dist/{chunk-R6M456QG.js → chunk-6TS3KOXR.js} +2 -2
  34. package/dist/{chunk-7U2YQSDE.js → chunk-76QOU4PK.js} +2 -2
  35. package/dist/{chunk-25GWKRUZ.js → chunk-7DUI77BN.js} +2 -2
  36. package/dist/chunk-7F45LJKI.js +2 -0
  37. package/dist/{chunk-DEAB5TGT.js → chunk-7F7T6DCR.js} +2 -2
  38. package/dist/chunk-7H6VHWWJ.js +2 -0
  39. package/dist/chunk-7HXT6YLU.js +5 -0
  40. package/dist/{chunk-KZYID5KV.js → chunk-7R4V5ES6.js} +4 -4
  41. package/dist/chunk-7RIRIADH.js +7 -0
  42. package/dist/chunk-7ZLWLOGT.js +2 -0
  43. package/dist/{chunk-WHADK6OS.js → chunk-A4WEAK35.js} +2 -2
  44. package/dist/chunk-AADQLOQ4.js +38 -0
  45. package/dist/{chunk-XFMVKFSF.js → chunk-AN76MGUE.js} +2 -2
  46. package/dist/chunk-ANLNLY66.js +2 -0
  47. package/dist/chunk-ATXPTSEI.js +81 -0
  48. package/dist/{chunk-EELG7D3Q.js → chunk-AX7IDVFT.js} +2 -2
  49. package/dist/chunk-B3PYOSCX.js +2 -0
  50. package/dist/chunk-B7MPDEAK.js +3 -0
  51. package/dist/chunk-BBB5FBX4.js +2 -0
  52. package/dist/{chunk-Y2VM4CJC.js → chunk-BHKK5RJY.js} +2 -2
  53. package/dist/chunk-BJWFVAA5.js +2 -0
  54. package/dist/chunk-BKVWUP7Y.js +2 -0
  55. package/dist/{chunk-7XA3OM44.js → chunk-BKZYTLGE.js} +2 -2
  56. package/dist/chunk-BL6DCHQP.js +2 -0
  57. package/dist/chunk-BOW7SSQH.js +43 -0
  58. package/dist/{chunk-KQHJEU6V.js → chunk-C4RHHCKL.js} +2 -2
  59. package/dist/chunk-C7C6AKAT.js +117 -0
  60. package/dist/chunk-CD6M6LS2.js +16 -0
  61. package/dist/chunk-CFE6PSG6.js +2 -0
  62. package/dist/{chunk-GPGRZJ3R.js → chunk-CFNIGQMT.js} +2 -2
  63. package/dist/{chunk-K3XFWJI2.js → chunk-CKBUBRYD.js} +2 -2
  64. package/dist/chunk-CZW5MZ5B.js +2 -0
  65. package/dist/chunk-DBBZ63ZX.js +2 -0
  66. package/dist/chunk-DBN7DMJB.js +18 -0
  67. package/dist/{chunk-CKRWA452.js → chunk-DUULLZHZ.js} +2 -2
  68. package/dist/{chunk-6HRZQLOI.js → chunk-DV5Y5NOS.js} +2 -2
  69. package/dist/chunk-DZOIKCTM.js +3 -0
  70. package/dist/chunk-E4PKTOL3.js +2 -0
  71. package/dist/{chunk-GVOMSPGL.js → chunk-E65ELFKU.js} +2 -2
  72. package/dist/{chunk-VXJJTQYE.js → chunk-E7QR35ST.js} +2 -2
  73. package/dist/{chunk-2RE5OCHZ.js → chunk-EFSXAINW.js} +2 -2
  74. package/dist/{chunk-GY7CCCEZ.js → chunk-EHVEIEQN.js} +2 -2
  75. package/dist/{chunk-BVFYEEBH.js → chunk-EHYDXE3Z.js} +2 -2
  76. package/dist/{chunk-HISEUIL2.js → chunk-EP63Y6LD.js} +2 -2
  77. package/dist/chunk-EPX6NQN6.js +4 -0
  78. package/dist/chunk-ETC674NS.js +5 -0
  79. package/dist/{chunk-5H5WTJSD.js → chunk-F5GSBHC6.js} +2 -2
  80. package/dist/chunk-FH3DGXC6.js +2 -0
  81. package/dist/{chunk-2XCGSDIT.js → chunk-FI7VGOR4.js} +2 -2
  82. package/dist/chunk-FJF6VO2P.js +2 -0
  83. package/dist/{chunk-FELGD32K.js → chunk-FLMTCX5R.js} +2 -2
  84. package/dist/chunk-FVFDOIM3.js +2 -0
  85. package/dist/{chunk-AQ2PORIO.js → chunk-G2HU5WRN.js} +2 -2
  86. package/dist/{chunk-7YQOCABQ.js → chunk-G4ALYS4J.js} +2 -2
  87. package/dist/{chunk-SWK4XPUS.js → chunk-G56I7K4W.js} +2 -2
  88. package/dist/{chunk-JFQBRL3J.js → chunk-GC4DG2V5.js} +2 -2
  89. package/dist/chunk-GG45PK4S.js +4 -0
  90. package/dist/{chunk-XN22RGSR.js → chunk-GHNPACNP.js} +2 -2
  91. package/dist/{chunk-XU75YQN4.js → chunk-GINH3YQU.js} +2 -2
  92. package/dist/chunk-GTZZVLKJ.js +2 -0
  93. package/dist/chunk-GXXW5ZHH.js +2 -0
  94. package/dist/{chunk-RNKPYYYE.js → chunk-HAXXKRTD.js} +2 -2
  95. package/dist/chunk-HEZWBAZY.js +2 -0
  96. package/dist/chunk-HMEWLMML.js +2 -0
  97. package/dist/{chunk-2KVU55CW.js → chunk-HOBOVYPO.js} +2 -2
  98. package/dist/{chunk-2YC7YNKT.js → chunk-HRFQ6GW5.js} +2 -2
  99. package/dist/{chunk-RYOYJMGF.js → chunk-HX4X7KG3.js} +2 -2
  100. package/dist/{chunk-AZS7YPCB.js → chunk-HYT2R7LX.js} +2 -2
  101. package/dist/chunk-IKQVBVQL.js +40 -0
  102. package/dist/chunk-J6GLBBRK.js +4 -0
  103. package/dist/{chunk-TNG2FYS5.js → chunk-J7A4PWFX.js} +2 -2
  104. package/dist/chunk-JCSAZ35V.js +2 -0
  105. package/dist/{chunk-EWWY2ZFL.js → chunk-JDU2IV3A.js} +2 -2
  106. package/dist/{chunk-SB25YMEQ.js → chunk-JFMEXGFE.js} +2 -2
  107. package/dist/chunk-JFMI5SGB.js +4 -0
  108. package/dist/chunk-JJP37RGX.js +57 -0
  109. package/dist/chunk-JZ2A7LDM.js +5 -0
  110. package/dist/chunk-KNLQGXVH.js +80 -0
  111. package/dist/chunk-KVQCECPR.js +2 -0
  112. package/dist/{chunk-F24QUEQP.js → chunk-KXXORBZ2.js} +2 -2
  113. package/dist/{chunk-IKVNEGTW.js → chunk-L5KYH6U3.js} +2 -2
  114. package/dist/chunk-L6XHYJPZ.js +21 -0
  115. package/dist/chunk-L7KTFEAV.js +43 -0
  116. package/dist/{chunk-UAQ4T73O.js → chunk-LDXHR5EL.js} +2 -2
  117. package/dist/chunk-LEECKFCJ.js +2 -0
  118. package/dist/{chunk-LO5JSW2C.js → chunk-MHGDSBFX.js} +2 -2
  119. package/dist/{chunk-JUN5DOAK.js → chunk-MLQVVDG3.js} +2 -2
  120. package/dist/chunk-MOKUWRHO.js +3 -0
  121. package/dist/{chunk-44T4DUAA.js → chunk-MPYAPMNE.js} +2 -2
  122. package/dist/{chunk-ARVO6TTW.js → chunk-MV6SPXCR.js} +2 -2
  123. package/dist/{chunk-NRBNAECH.js → chunk-MWN53KRN.js} +2 -2
  124. package/dist/{chunk-TH6IC56G.js → chunk-MZPXPSUJ.js} +2 -2
  125. package/dist/{chunk-FBCVASUG.js → chunk-N55KIE46.js} +2 -2
  126. package/dist/{chunk-VMWUV6WB.js → chunk-NB4D3BNM.js} +2 -2
  127. package/dist/{chunk-JAT6C3VX.js → chunk-NGKBOT6G.js} +2 -2
  128. package/dist/{chunk-Q6T2CAJL.js → chunk-NJGKXKQF.js} +2 -2
  129. package/dist/chunk-NJQISBL4.js +8 -0
  130. package/dist/chunk-NJT3ZEKY.js +16 -0
  131. package/dist/{chunk-KFVSJX25.js → chunk-NKMKZP6A.js} +2 -2
  132. package/dist/chunk-NODFZ6ED.js +2 -0
  133. package/dist/{chunk-ERCYGVAM.js → chunk-NSM5IEVW.js} +2 -2
  134. package/dist/{chunk-YAGYMBEX.js → chunk-NTGUVNR2.js} +2 -2
  135. package/dist/{chunk-N7FP5H5U.js → chunk-NU3KFF2O.js} +8 -8
  136. package/dist/chunk-NWLVNU66.js +557 -0
  137. package/dist/{chunk-Q55NF3ZG.js → chunk-NYKZMCRC.js} +2 -2
  138. package/dist/{chunk-I6UTXNHU.js → chunk-O6BUXZEH.js} +2 -2
  139. package/dist/chunk-ODPDP7A4.js +3 -0
  140. package/dist/{chunk-ZAZGGSM3.js → chunk-OHIV323X.js} +2 -2
  141. package/dist/chunk-OIAPEKMT.js +3 -0
  142. package/dist/chunk-OIOC5EHF.js +3 -0
  143. package/dist/{chunk-YIHNPKWD.js → chunk-ONPPQM4G.js} +2 -2
  144. package/dist/{chunk-RHHCLWQ6.js → chunk-OUHEZBYI.js} +2 -2
  145. package/dist/{chunk-MSR2QRUE.js → chunk-OVGYW7UD.js} +2 -2
  146. package/dist/{chunk-OPSAW5DT.js → chunk-OYKU4B3Y.js} +2 -2
  147. package/dist/{chunk-5YRQIE2B.js → chunk-POBJ6FR2.js} +2 -2
  148. package/dist/{chunk-ZGW4HLPD.js → chunk-PSZPMMWN.js} +2 -2
  149. package/dist/chunk-PXTRBKRK.js +3 -0
  150. package/dist/{chunk-U2N2KE7A.js → chunk-Q5JRIHT3.js} +2 -2
  151. package/dist/{chunk-GRX7JOXQ.js → chunk-Q7ATHARX.js} +2 -2
  152. package/dist/{chunk-5ZMBRQFC.js → chunk-Q7CSKIDM.js} +2 -2
  153. package/dist/{chunk-HG722PO7.js → chunk-QBQE7ZJ5.js} +2 -2
  154. package/dist/{chunk-Z2PZVKPR.js → chunk-QH22UIXP.js} +2 -2
  155. package/dist/chunk-QXCKQTKR.js +60 -0
  156. package/dist/chunk-RBAD4GJ2.js +13 -0
  157. package/dist/chunk-RMDPFPNW.js +2 -0
  158. package/dist/chunk-ROPJDEJZ.js +4 -0
  159. package/dist/{chunk-56NQAEPJ.js → chunk-RVZC6TJE.js} +2 -2
  160. package/dist/{chunk-XJX6LGHL.js → chunk-S4QZBKSR.js} +2 -2
  161. package/dist/chunk-SCPMZ73U.js +2 -0
  162. package/dist/{chunk-7IQXARSQ.js → chunk-SIAP5RGI.js} +2 -2
  163. package/dist/{chunk-4TQU4TX2.js → chunk-SIX4RFR3.js} +2 -2
  164. package/dist/{chunk-AYPDH2LU.js → chunk-SKKXTABJ.js} +2 -2
  165. package/dist/{chunk-ZYM4HOFA.js → chunk-SSRFUQBD.js} +2 -2
  166. package/dist/chunk-SYVJEEUJ.js +3 -0
  167. package/dist/chunk-T3CZAZSI.js +8 -0
  168. package/dist/chunk-T3I6NHBH.js +2 -0
  169. package/dist/{chunk-GDRJB3SB.js → chunk-T6DWDI5E.js} +2 -2
  170. package/dist/chunk-T6HRIROJ.js +7 -0
  171. package/dist/{chunk-OTSPRVNW.js → chunk-TAA7HXHE.js} +2 -2
  172. package/dist/{chunk-IJMD6BRI.js → chunk-TJ2JQYT3.js} +2 -2
  173. package/dist/chunk-TULNMD5T.js +368 -0
  174. package/dist/chunk-U2FPY5XA.js +3 -0
  175. package/dist/chunk-U3SXIMII.js +38 -0
  176. package/dist/{chunk-ENWQWA2R.js → chunk-U6KCHXJ4.js} +2 -2
  177. package/dist/chunk-UH3XSKS5.js +9 -0
  178. package/dist/{chunk-UDY7MIAW.js → chunk-UIFUZVCC.js} +2 -2
  179. package/dist/{chunk-BDGTPN27.js → chunk-UXKURIVI.js} +2 -2
  180. package/dist/{chunk-FGNCOQUX.js → chunk-V2RBODHL.js} +2 -2
  181. package/dist/chunk-VBKUWB6N.js +2 -0
  182. package/dist/{chunk-PIFTZEEM.js → chunk-VBV6ALJE.js} +2 -2
  183. package/dist/{chunk-2OXVP5U5.js → chunk-VDGFWCQV.js} +2 -2
  184. package/dist/chunk-VDSDOEWF.js +2 -0
  185. package/dist/{chunk-C76O5MDS.js → chunk-VZPWVCLN.js} +2 -2
  186. package/dist/chunk-WDSFQDPN.js +2 -0
  187. package/dist/{chunk-BTVKZGWT.js → chunk-WFA35BGR.js} +2 -2
  188. package/dist/{chunk-H7CG6LOE.js → chunk-WLMP3OCW.js} +2 -2
  189. package/dist/{chunk-WOOAY3PA.js → chunk-WSA52GOR.js} +2 -2
  190. package/dist/chunk-WYPL7GF7.js +2 -0
  191. package/dist/{chunk-RDULNRSJ.js → chunk-X3YVZAKZ.js} +2 -2
  192. package/dist/chunk-X6OGVFIT.js +2 -0
  193. package/dist/{chunk-ISWFRGJ6.js → chunk-XKXTR6ZI.js} +2 -2
  194. package/dist/chunk-Y5DFAW5W.js +4 -0
  195. package/dist/chunk-YSYPDRD5.js +3 -0
  196. package/dist/chunk-ZFVPWH62.js +5 -0
  197. package/dist/chunk-ZGIHTH27.js +2 -0
  198. package/dist/{chunk-QKT4UI2Y.js → chunk-ZGIQN2SX.js} +2 -2
  199. package/dist/chunk-ZHG4WAHR.js +12 -0
  200. package/dist/{chunk-CLG6DWVS.js → chunk-ZKB2XUEN.js} +2 -2
  201. package/dist/chunk-ZLMXIQLC.js +21 -0
  202. package/dist/chunk-ZMCQIHI4.js +2 -0
  203. package/dist/cli-main.js +2 -2
  204. package/dist/code-TAVIKWJI.js +2 -0
  205. package/dist/code-result-json-5FEFQCAQ.js +2 -0
  206. package/dist/command-descriptors-7BKH53Y3.js +343 -0
  207. package/dist/dataflow-GFBTVDH3.js +2 -0
  208. package/dist/dependence-slice-GWGQCODG.js +2 -0
  209. package/dist/deps-4QHVDPYA.js +2 -0
  210. package/dist/direct-navigation-4UBC6HNW.js +3 -0
  211. package/dist/entry-map-QCTF4RVY.js +2 -0
  212. package/dist/files-M2UBF5HJ.js +2 -0
  213. package/dist/frontend-profile-roles-D7eCum8P.d.ts +10 -0
  214. package/dist/{health-CPp2Jf1Z.d.ts → health-BI2a9WPy.d.ts} +60 -2
  215. package/dist/hierarchy-2UIHRLW4.js +2 -0
  216. package/dist/imports-WIE3YZOB.js +2 -0
  217. package/dist/index.d.ts +1 -1
  218. package/dist/index.js +1 -1
  219. package/dist/members-YKD636DA.js +2 -0
  220. package/dist/methods-VDF4IMYG.js +2 -0
  221. package/dist/output-continuation-command-4UMDOOLO.js +3 -0
  222. package/dist/output-pagination-2GME6OPY.js +19 -0
  223. package/dist/postinstall.js +1 -1
  224. package/dist/project-reindex-XEQTRCV5.js +3 -0
  225. package/dist/queries/affected.js +1 -1
  226. package/dist/queries/anchors.d.ts +1 -1
  227. package/dist/queries/anchors.js +1 -1
  228. package/dist/queries/architecture.js +1 -1
  229. package/dist/queries/bottlenecks.js +1 -1
  230. package/dist/queries/by-kind.js +1 -1
  231. package/dist/queries/call-graph.d.ts +2 -0
  232. package/dist/queries/call-graph.js +1 -1
  233. package/dist/queries/change-surface.js +1 -1
  234. package/dist/queries/cleanup-plan.js +1 -1
  235. package/dist/queries/co-change.d.ts +20 -2
  236. package/dist/queries/co-change.js +1 -1
  237. package/dist/queries/code.js +1 -1
  238. package/dist/queries/complexity-hotspots.js +1 -1
  239. package/dist/queries/complexity.js +1 -1
  240. package/dist/queries/context.js +1 -1
  241. package/dist/queries/convergence.js +1 -1
  242. package/dist/queries/coupling.js +1 -1
  243. package/dist/queries/cycles.js +1 -1
  244. package/dist/queries/dataflow.js +1 -1
  245. package/dist/queries/dead.d.ts +2 -0
  246. package/dist/queries/dead.js +1 -1
  247. package/dist/queries/decorative-checkers.js +1 -1
  248. package/dist/queries/deep-chains.js +1 -1
  249. package/dist/queries/dependence-slice.js +1 -1
  250. package/dist/queries/dependency-depth.js +1 -1
  251. package/dist/queries/deps.js +1 -1
  252. package/dist/queries/diff-impact.d.ts +9 -0
  253. package/dist/queries/diff-impact.js +1 -1
  254. package/dist/queries/doc-drift.js +1 -1
  255. package/dist/queries/drift.js +1 -1
  256. package/dist/queries/duplicate-bodies.d.ts +28 -1
  257. package/dist/queries/duplicate-bodies.js +1 -1
  258. package/dist/queries/entry-map.d.ts +1 -1
  259. package/dist/queries/entry-map.js +1 -1
  260. package/dist/queries/evidence.js +1 -1
  261. package/dist/queries/extract-candidates.d.ts +50 -23
  262. package/dist/queries/extract-candidates.js +1 -1
  263. package/dist/queries/fan.js +1 -1
  264. package/dist/queries/files.js +1 -1
  265. package/dist/queries/health.d.ts +1 -1
  266. package/dist/queries/health.js +1 -1
  267. package/dist/queries/hierarchy.js +1 -1
  268. package/dist/queries/hotspots.js +1 -1
  269. package/dist/queries/imports.js +1 -1
  270. package/dist/queries/incomplete-migration.js +1 -1
  271. package/dist/queries/index.d.ts +4 -3
  272. package/dist/queries/index.js +1 -1
  273. package/dist/queries/isolated.js +1 -1
  274. package/dist/queries/locality-candidates.js +1 -1
  275. package/dist/queries/members.js +1 -1
  276. package/dist/queries/methods.js +1 -1
  277. package/dist/queries/not-implemented.js +1 -1
  278. package/dist/queries/outline.js +1 -1
  279. package/dist/queries/passthrough-candidates.d.ts +9 -1
  280. package/dist/queries/passthrough-candidates.js +1 -1
  281. package/dist/queries/plan-context.js +1 -1
  282. package/dist/queries/react-component-duplicates.d.ts +19 -3
  283. package/dist/queries/react-component-duplicates.js +1 -1
  284. package/dist/queries/react-hook-candidates.d.ts +22 -3
  285. package/dist/queries/react-hook-candidates.js +1 -1
  286. package/dist/queries/react-large-component-pressure.d.ts +17 -3
  287. package/dist/queries/react-large-component-pressure.js +1 -1
  288. package/dist/queries/recent-duplicates.js +1 -1
  289. package/dist/queries/redundant-reexports.js +1 -1
  290. package/dist/queries/reference-neighborhood.js +1 -1
  291. package/dist/queries/reference-reachability.js +1 -1
  292. package/dist/queries/refs.js +1 -1
  293. package/dist/queries/self-audit.d.ts +7 -1
  294. package/dist/queries/self-audit.js +1 -1
  295. package/dist/queries/similar-chains.js +1 -1
  296. package/dist/queries/similar-files.js +1 -1
  297. package/dist/queries/similar-signatures.js +1 -1
  298. package/dist/queries/similar.js +1 -1
  299. package/dist/queries/slice.js +1 -1
  300. package/dist/queries/source-inspection.js +1 -1
  301. package/dist/queries/source-search.js +1 -1
  302. package/dist/queries/stale-abstractions.js +1 -1
  303. package/dist/queries/surface.js +1 -1
  304. package/dist/queries/symbols.js +1 -1
  305. package/dist/queries/system-map.d.ts +1 -1
  306. package/dist/queries/system-map.js +1 -1
  307. package/dist/queries/system.js +1 -1
  308. package/dist/queries/test-quality.js +1 -1
  309. package/dist/queries/trace.js +1 -1
  310. package/dist/queries/twin-ab.js +1 -1
  311. package/dist/queries/twin-drift.d.ts +22 -6
  312. package/dist/queries/twin-drift.js +1 -1
  313. package/dist/queries/unused-imports.js +1 -1
  314. package/dist/queries/unused-params.js +1 -1
  315. package/dist/queries/value-flow.js +1 -1
  316. package/dist/queries/vue-component-duplicates.js +1 -1
  317. package/dist/queries/vue-composable-candidates.js +1 -1
  318. package/dist/queries/vue-large-view-pressure.js +1 -1
  319. package/dist/queries/wrapper-candidates.d.ts +16 -1
  320. package/dist/queries/wrapper-candidates.js +1 -1
  321. package/dist/query-service-fastpath.js +5 -5
  322. package/dist/query-service-server.js +3 -3
  323. package/dist/refs-JNK5CLM7.js +2 -0
  324. package/dist/refs-pagination-6BLRYGMV.js +2 -0
  325. package/dist/reindex-worker.js +25 -25
  326. package/dist/reindex.d.ts +3 -2
  327. package/dist/reindex.js +35 -35
  328. package/dist/runtime.d.ts +34 -2
  329. package/dist/runtime.js +4 -4
  330. package/dist/rust-semantic-session-server.js +1 -1
  331. package/dist/rust-semantic-session-worker.js +1 -1
  332. package/dist/rust-semantic-worker.js +1 -1
  333. package/dist/{scip-cli-H-n59izO.d.ts → scip-cli-DOerTq-R.d.ts} +42 -4
  334. package/dist/slice-PHPVNCWX.js +2 -0
  335. package/dist/surface-MQX5MPIV.js +2 -0
  336. package/dist/symbol-resolution-DBLVXLBC.js +2 -0
  337. package/dist/system-JOPKV4OG.js +2 -0
  338. package/dist/trace-I2P2YFH4.js +2 -0
  339. package/dist/typescript-mailbox-worker.js +1 -1
  340. package/dist/value-flow-JJVMF7NP.js +2 -0
  341. package/dist/watch-server.js +3 -3
  342. package/docs/COMMAND_REFERENCE.md +2 -2
  343. package/docs/DETECTOR_GUIDE.md +51 -12
  344. package/docs/accuracy-audit-checklist.md +36 -13
  345. package/docs/locality-analyzer-design.md +9 -9
  346. package/package.json +2 -2
  347. package/skills/conductor/SKILL.md +110 -0
  348. package/skills/conductor/agents/openai.yaml +4 -0
  349. package/skills/principal-maintainability-review/SKILL.md +273 -0
  350. package/skills/principal-maintainability-review/agents/openai.yaml +4 -0
  351. package/skills/scip-calibrate/SKILL.md +102 -0
  352. package/skills/scip-calibrate/agents/openai.yaml +4 -0
  353. package/skills/scip-claim-audit/SKILL.md +113 -0
  354. package/skills/scip-claim-audit/agents/openai.yaml +4 -0
  355. package/skills/scip-probe-reachability/SKILL.md +93 -0
  356. package/skills/scip-probe-reachability/agents/openai.yaml +4 -0
  357. package/skills/scip-root-cause/SKILL.md +160 -0
  358. package/skills/scip-root-cause/agents/openai.yaml +4 -0
  359. package/skills/scip-system-compression/SKILL.md +252 -0
  360. package/skills/scip-system-compression/agents/openai.yaml +4 -0
  361. package/skills/scip-system-compression/references/compression-atlas.md +116 -0
  362. package/skills/scip-system-compression/references/compression-patterns.md +87 -0
  363. package/skills/scip-twin-drift/SKILL.md +109 -0
  364. package/skills/scip-twin-drift/agents/openai.yaml +4 -0
  365. package/dist/by-kind-4IYG2SKW.js +0 -2
  366. package/dist/call-graph-WQNXMNNN.js +0 -2
  367. package/dist/call-graph-evidence-lZa2dwQA.d.ts +0 -11
  368. package/dist/chunk-2BTJALUS.js +0 -454
  369. package/dist/chunk-3QXC54FQ.js +0 -3
  370. package/dist/chunk-3TJY6M3B.js +0 -7
  371. package/dist/chunk-42W3LFUK.js +0 -13
  372. package/dist/chunk-4GAQ6FI4.js +0 -43
  373. package/dist/chunk-6NC3YSPY.js +0 -38
  374. package/dist/chunk-6VEFRPTD.js +0 -5
  375. package/dist/chunk-7C26EKLZ.js +0 -4
  376. package/dist/chunk-7JYHQAH2.js +0 -22
  377. package/dist/chunk-7KSO2OAP.js +0 -2
  378. package/dist/chunk-7XZGZBSQ.js +0 -2
  379. package/dist/chunk-A77SCPW2.js +0 -3
  380. package/dist/chunk-AK3PYTIK.js +0 -5
  381. package/dist/chunk-AMIMMNA4.js +0 -11
  382. package/dist/chunk-AUY5BL74.js +0 -2
  383. package/dist/chunk-BDHFVH2M.js +0 -18
  384. package/dist/chunk-BECZLYNU.js +0 -8
  385. package/dist/chunk-BUTEIZKP.js +0 -10
  386. package/dist/chunk-BWVQP3LB.js +0 -38
  387. package/dist/chunk-BYDAFMSR.js +0 -57
  388. package/dist/chunk-BZYSGZRK.js +0 -2
  389. package/dist/chunk-C7IJMOFP.js +0 -134
  390. package/dist/chunk-CBBHFNLX.js +0 -2
  391. package/dist/chunk-D2MVJSP4.js +0 -21
  392. package/dist/chunk-D35XIZGN.js +0 -2
  393. package/dist/chunk-DKM723YF.js +0 -79
  394. package/dist/chunk-DRENNWRG.js +0 -2
  395. package/dist/chunk-E44IVWIJ.js +0 -367
  396. package/dist/chunk-EDMB6SSO.js +0 -7
  397. package/dist/chunk-EETGXQY7.js +0 -3
  398. package/dist/chunk-FKGQOTKD.js +0 -2
  399. package/dist/chunk-GH5YSGZL.js +0 -5
  400. package/dist/chunk-GQIDEID3.js +0 -2
  401. package/dist/chunk-HCVJR2V4.js +0 -3
  402. package/dist/chunk-IMKZEXZG.js +0 -2
  403. package/dist/chunk-ISIQLPJ2.js +0 -61
  404. package/dist/chunk-IXESDH3J.js +0 -2
  405. package/dist/chunk-JJ62MTQH.js +0 -40
  406. package/dist/chunk-JT6XX7QY.js +0 -8
  407. package/dist/chunk-KFOYCQAJ.js +0 -9
  408. package/dist/chunk-LRI5OMPE.js +0 -2
  409. package/dist/chunk-MHIEP7EG.js +0 -4
  410. package/dist/chunk-NK3JMP22.js +0 -2
  411. package/dist/chunk-NVSZNESQ.js +0 -2
  412. package/dist/chunk-OJNK5ALA.js +0 -2
  413. package/dist/chunk-OXYAWIEA.js +0 -2
  414. package/dist/chunk-OZETODHH.js +0 -2
  415. package/dist/chunk-PBUH2P5S.js +0 -3
  416. package/dist/chunk-PLJUQFQN.js +0 -2
  417. package/dist/chunk-PLYUVM4F.js +0 -2
  418. package/dist/chunk-PXXYQK55.js +0 -2
  419. package/dist/chunk-Q5TA4OY4.js +0 -20
  420. package/dist/chunk-Q7GBK5T7.js +0 -81
  421. package/dist/chunk-QLBSG7U5.js +0 -3
  422. package/dist/chunk-QWKHW6VZ.js +0 -2
  423. package/dist/chunk-RPL3ARU7.js +0 -16
  424. package/dist/chunk-SVHTMVA4.js +0 -4
  425. package/dist/chunk-T6QD2ZQB.js +0 -43
  426. package/dist/chunk-TD7VKJ2Y.js +0 -117
  427. package/dist/chunk-TKDNDQA7.js +0 -3
  428. package/dist/chunk-TQZV7KV4.js +0 -2
  429. package/dist/chunk-TUSPIVZ3.js +0 -4
  430. package/dist/chunk-URSGGIZX.js +0 -2
  431. package/dist/chunk-UT7TADJX.js +0 -2
  432. package/dist/chunk-V4NG5OMS.js +0 -554
  433. package/dist/chunk-VTCIYFEK.js +0 -2
  434. package/dist/chunk-VU6LIWHT.js +0 -2
  435. package/dist/chunk-VUSKPCUB.js +0 -2
  436. package/dist/chunk-WN3TCGJ4.js +0 -2
  437. package/dist/chunk-WSLEJSFR.js +0 -2
  438. package/dist/chunk-WYZIHUPZ.js +0 -16
  439. package/dist/chunk-XE33FV5W.js +0 -2
  440. package/dist/chunk-XGGBK66W.js +0 -4
  441. package/dist/chunk-XSWYJCAK.js +0 -2
  442. package/dist/chunk-Y334QQU5.js +0 -3
  443. package/dist/chunk-Z2AWCTN6.js +0 -2
  444. package/dist/chunk-ZOXKSQQB.js +0 -2
  445. package/dist/chunk-ZPASRBLF.js +0 -2
  446. package/dist/chunk-ZZ3Z7D56.js +0 -2
  447. package/dist/code-EQJFDT6I.js +0 -2
  448. package/dist/code-result-json-7UWIWBOO.js +0 -2
  449. package/dist/command-descriptors-ORNTVNYV.js +0 -342
  450. package/dist/dataflow-6VL54GX5.js +0 -2
  451. package/dist/dependence-slice-DT2NUHD2.js +0 -2
  452. package/dist/deps-DB7H5IKC.js +0 -2
  453. package/dist/direct-navigation-O3LUAYWQ.js +0 -3
  454. package/dist/entry-map-6K62RV3D.js +0 -2
  455. package/dist/files-MSLD7MO6.js +0 -2
  456. package/dist/hierarchy-IVBXAKFA.js +0 -2
  457. package/dist/imports-FRAVZ3Y2.js +0 -2
  458. package/dist/members-KJOJDYGO.js +0 -2
  459. package/dist/methods-2AYABBT3.js +0 -2
  460. package/dist/output-continuation-command-JHMPH6NC.js +0 -3
  461. package/dist/output-pagination-3OFL2MJV.js +0 -19
  462. package/dist/project-reindex-HYO4WD7Z.js +0 -3
  463. package/dist/refs-ARMA6XUJ.js +0 -2
  464. package/dist/refs-pagination-VUGIWN6U.js +0 -2
  465. package/dist/slice-YOB5YFAM.js +0 -2
  466. package/dist/surface-VY5EFWTW.js +0 -2
  467. package/dist/symbol-resolution-DGQN4XIV.js +0 -2
  468. package/dist/system-2KQ3QD2P.js +0 -2
  469. package/dist/trace-HTIPTXAE.js +0 -2
  470. package/dist/value-flow-5FV3VQI7.js +0 -2
@@ -1,554 +0,0 @@
1
- #!/usr/bin/env node
2
- import{$a as nf,$b as pf,$c as wf,Aa as xt,Ab as Ce,Ac as yf,Ad as li,B as ml,Ba as Ms,Bb as pn,Bc as U,Bd as Lt,C as pl,Ca as Zr,Cb as Xi,Cc as Le,Da as Nt,Db as cf,Dc as bf,Dd as vr,De as Gf,E as jp,Eb as lf,Ec as Sf,Ee as zf,Fa as yl,Fb as se,Fc as Zi,Fd as Ff,Fe as Kf,G as Hp,Ga as Xp,Gb as uf,Gc as $s,Gd as Nf,Ge as Wf,Hb as Ns,Hc as vf,Hd as Cr,He as Vf,Ia as yr,Ib as vl,Ic as Ne,Id as _f,Jb as Cl,Jc as js,Jd as hn,Kb as br,Kc as xe,Lc as q,Ld as zs,M as Up,Mc as gn,Na as Qp,Nb as J,Nc as ai,Nd as Hn,Oa as Vi,Ob as _n,Oc as Cf,Od as xr,Pa as Fn,Pb as K,Pc as ne,Pd as Ks,Qa as ge,Qb as df,Qc as Qe,Ra as Zp,Rb as _s,Rc as Sr,Sb as Et,Sc as Hs,T as qp,Ta as qt,Tb as Gt,Tc as xf,Ua as Rt,Ub as mf,Uc as Rf,Va as mn,Vc as Ef,Wc as Us,Wd as Of,Xb as ti,Xc as _t,Y as Gp,Ya as ef,Yb as Os,Yc as $n,Ye as Ll,Za as tf,Zb as It,Zc as zt,Zd as Bf,_ as hr,_a as bl,_b as ni,_c as If,_d as Rl,_e as Pl,ab as Z,ad as Lf,ae as Ws,af as Yf,bb as ei,bc as Qi,bd as xl,be as Un,c as Wi,cb as rf,cc as ae,cd as Pf,ce as Vs,da as zp,db as of,dc as ri,de as $f,e as _p,ec as Bs,ee as Ys,fb as Sl,fc as On,fd as Df,fe as jf,ff as Jf,gb as sf,gc as Me,gd as eo,ge as to,gf as Xf,h as Op,hb as Yi,hd as Mf,i as ws,ia as fl,ib as be,id as jn,ie as El,j as it,jd as Tf,je as Il,k as Fe,ka as Ps,ke as wl,la as gl,lc as fn,le as qn,lf as Qf,m as un,ma as Kp,mc as Bn,me as Hf,mf as Zf,n as Ls,na as Wp,nb as af,nc as ff,ne as Uf,nf as eg,o as dn,oa as Ye,ob as N,oc as T,od as kf,oe as qf,p as Xr,pa as Je,pc as z,qa as Ct,qb as Ts,qc as wt,ra as Ds,rb as dt,rc as Xe,s as Qr,sa as Vp,sb as Ji,sc as Se,se as no,t as vt,ta as Yp,tb as $e,tc as me,te as Js,u as Ve,ub as W,uc as je,vb as Nn,vc as ii,w as Bp,wa as Jp,wb as V,wc as gf,wd as Af,x as dl,xa as Q,xb as ks,xc as hf,xd as ci,xe as ui,y as $p,yb as As,yc as oi,yd as qs,za as hl,zb as Fs,zc as si,zd as Gs}from"./chunk-2BTJALUS.js";import{existsSync as nw}from"fs";import{isAbsolute as tg,join as rw}from"path";function mt(e,t){let n=Dl(e,t,{allowMultiple:!1})[0]?.relativePath;return n||ig(e,t)}function Rr(e,t){return Dl(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function ng(e,t){let n=Dl(e,t,{allowMultiple:!0});return n.length===1?n[0].relativePath:null}function rg(e,t){let n=ei(e,t,{allowMultiple:!0,requirePathMatch:!0});return n.length===1?n[0].relativePath:null}function ig(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=tg(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,i=rw(e.config.projectRoot,r);return nw(i)?r:null}function Dl(e,t,n){let r=ig(e,t);if(r)return ei(e,r,n).filter(a=>a.relativePath===r);let i=t.replace(/\\/g,"/").replace(/^\.\//,""),o=tg(i)||i.includes("/"),s=ei(e,t,{...n,requirePathMatch:o});if(s.length===0){if(o)return[];let a=ne(e,t);return!a||e.isIgnored(a.relativePath)?[]:[{relativePath:a.relativePath,score:700}]}return s}function og(e,t){let n=ng(e,t);if(!n)return[];let r=$s(e,[n],{sort:!0});if(r.length===0)return[];let i=Math.max(0,Nn(W(e,n)).length-1),o=r.map(c=>({symbol:c.symbol,shortName:c.shortName,startLine:c.startLine,endLine:Math.min(c.endLine,i),signature:c.signature,children:[]})),s=new Map;for(let c of o)s.set(c.symbol,c);let a=[];for(let c=0;c<r.length;c++){let l=r[c],u=o[c];if(l.enclosingSymbol&&s.has(l.enclosingSymbol)){s.get(l.enclosingSymbol).children.push(u);continue}let d=null,m=1/0;for(let p of o)if(p!==u&&p.startLine<=u.startLine&&p.endLine>=u.endLine){if(p.startLine===u.startLine&&p.endLine===u.endLine&&!hf(p.symbol,u.symbol))continue;let g=p.endLine-p.startLine;g<m&&(m=g,d=p)}d?d.children.push(u):a.push(u)}return a}import{basename as mL,extname as jg}from"path";function pt(e,t){let n=V(e,t.relativePath);if(n.length===0)return!1;let r=z(t.symbol);if(!r)return!1;let i=n.slice(Math.max(0,t.startLine-2),t.startLine+1).join(`
3
- `),o=Ce(r);return new RegExp(`^\\s*export\\s+(?:default\\s+)?(?:(?:async\\s+)?function\\s+${o}\\b|(?:abstract\\s+)?class\\s+${o}\\b|(?:interface|type|enum|namespace|module)\\s+${o}\\b|(?:const|let|var)\\s+${o}\\b)`,"m").test(i)?!0:iw(n,r)}function iw(e,t){if(!t)return!1;let n=new RegExp(`^\\s*export\\s*\\{[^}\\n]*\\b${Ce(t)}\\b`);return e.some(r=>n.test(r))}import{createHash as ow}from"crypto";import{isUtf8 as sw}from"buffer";import{TextDecoder as aw}from"util";var ag=new aw("utf-8",{fatal:!0});function Tl(e){return Ds(e.config.projectRoot)}function Xs(e,t){let n=un(t),r;try{r=gl(e.config.projectRoot,n,{inputKind:"repository text file"})}catch(o){if(Je(o)||o instanceof fl)return null;throw o}let i=cw(r);return i===null?null:lg(n,r,i,dg(e),ug(e))}function cg(e,t={}){let n=[],r=Qs(e,t,i=>n.push(i));return{files:n,candidateFiles:r.candidateFiles,scannedBytes:r.scannedBytes,skippedBinaryPaths:r.skippedBinaryPaths,skippedUnreadablePaths:r.skippedUnreadablePaths,skippedOversizedPaths:r.skippedOversizedPaths}}function Qs(e,t,n){let r=Tl(e).filter(f=>!t.scope||f.includes(t.scope)),i=dg(e),o=ug(e),s=[],a=[],c=[],l=0,u=0,d={aligned:0,stale:0,unavailable:0},m=t.literalBytes?Buffer.isBuffer(t.literalBytes)?[t.literalBytes]:[...t.literalBytes]:[],p=m.length>0?Buffer.allocUnsafe(1024*1024):void 0;for(let f of r){let g,h,b=[],S=o.has(f);try{if(m.length>0){let x=m.length===1?Kp(e.config.projectRoot,f,m[0],{inputKind:"repository text file",computeSha256:S,scratchBuffer:p}):Wp(e.config.projectRoot,f,m,{inputKind:"repository text file",computeSha256:S,scratchBuffer:p});if(!x.isUtf8Text){s.push(f);continue}l+=x.byteLength,u+=1,h=x.sha256;let v=Ml(f,h,i,o);if(d[v.state]+=1,b="matchedLiteralIndexes"in x?x.matchedLiteralIndexes:x.includesLiteral?[0]:[],b.length===0||!x.bytes)continue;g=x.bytes}else g=gl(e.config.projectRoot,f,{inputKind:"repository text file"})}catch(x){if(x instanceof fl){c.push(f);continue}if(Je(x))continue;a.push(f);continue}if(m.length===0&&!mg(g)){s.push(f);continue}if(m.length===0){l+=g.byteLength,u+=1,h=S?pg(g):void 0;let x=Ml(f,h,i,o);d[x.state]+=1}if(t.includeBytes&&!t.includeBytes(f,g))continue;let y=ag.decode(g);n(lg(f,g,y,i,o,h),b)}return{candidateFiles:r.length,scannedTextFiles:u,semanticFiles:d,scannedBytes:l,skippedBinaryPaths:s,skippedUnreadablePaths:a,skippedOversizedPaths:c}}function lg(e,t,n,r,i,o){let s=o??pg(t);return{relativePath:e,text:n,bytes:t.byteLength,freshness:{exactText:{state:"current",basis:"working-tree-read",sha256:s},semantic:Ml(e,s,r,i)}}}function Ml(e,t,n,r){if(!r.has(e))return{state:"unavailable",basis:"no-compiler-document"};let i=n.get(e);return!i||!t?{state:"unavailable",basis:"fingerprint-unavailable"}:{state:i===t?"aligned":"stale",basis:"indexed-input-fingerprint"}}function ug(e){return new Set(e.all(`SELECT documents.relative_path FROM documents WHERE 1 = 1 ${e.pathExclusionsFor("documents")}`).map(t=>t.relative_path))}function dg(e){let t=new Map;if(!e.generation.metadataRaw)return t;let n=yr(e.generation.metadataRaw);if(n.kind!=="legacy"&&n.kind!=="supported")return t;let r=n.metadata.fingerprint;if(!sg(r)||!Array.isArray(r.files))return t;for(let i of r.files)!sg(i)||typeof i.path!="string"||typeof i.hash!="string"||t.set(i.path,i.hash);return t}function cw(e){return mg(e)?ag.decode(e):null}function mg(e){return!e.includes(0)&&sw(e)}function pg(e){return ow("sha256").update(e).digest("hex")}function sg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{SymbolInformation_Kind as ue}from"@c4312/scip";var Zs=new Map(Object.entries(ue).filter(([e,t])=>Number.isInteger(Number(e))&&typeof t=="string").map(([e,t])=>[Number(e),t])),fg=new Map([...Zs.entries()].map(([e,t])=>[t.toLowerCase(),e]));function ro(e){return Zs.get(e)??"Unknown"}function Kt(){return[ue.Function,ue.Method,ue.Macro,ue.Constructor,ue.Getter,ue.Setter,ue.StaticMethod,ue.SingletonMethod,ue.AbstractMethod,ue.ProtocolMethod,ue.TraitMethod]}function gg(){return[ue.Class,ue.Interface,ue.Struct,ue.Trait,ue.Type,ue.TypeAlias,ue.Enum,ue.Union,ue.Protocol]}function a4(){return[ue.Constant,ue.Variable,ue.Value,ue.Field,ue.Property,ue.StaticDataMember,ue.StaticField,ue.StaticProperty,ue.StaticVariable,ue.EnumMember]}function Pt(e,t,n={}){let r=Er(e,[t],{additive:n.additive,semantic:n.semantic,semanticEvidence:n.semanticEvidence}),i=n.callableOnly?(r.get(t.symbolId)??[]).filter(o=>Xe(o.symbol)||o.source==="ast-callsite"):r.get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}function Gn(e,t,n){return yn(e,[t],n).get(t.symbolId)??[]}function yn(e,t,n){let r=mw(e)?fw(e,t,{semantic:n.semantic!==!1,semanticEvidence:n.semanticEvidence}):pw(e,n.semanticEvidence);return typeof n.limit!="number"?new Map(t.map(i=>[i.symbolId,r.get(i.symbolId)??[]])):new Map(t.map(i=>[i.symbolId,(r.get(i.symbolId)??[]).slice(0,n.limit)]))}var lw=ge("caller-rows",{clearGroups:["whole-project"]}),uw=ge("targeted-caller-strategy",{clearGroups:["whole-project"]}),dw=2e4;function mw(e){return uw.get(e,()=>(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>dw)}function pw(e,t){return lw.get(e,()=>{let n=Le(e),r=Er(e,n,{semanticEvidence:t}),i=new Map;for(let a of n)i.set(a.symbol,a.symbolId);let o=new Map,s=new Map;for(let a of n){let c=r.get(a.symbolId);if(!(!c||c.length===0))for(let l of c){let u=i.get(l.symbol);if(u===void 0||u===a.symbolId)continue;let d=o.get(u);d||(d=[],o.set(u,d),s.set(u,new Set));let m=`${a.symbol}|${a.relativePath}`;s.get(u).has(m)||(s.get(u).add(m),d.push({symbol:a.symbol,file:a.relativePath,source:"caller-map-inversion",callEvidence:l.source}))}}return o})}function fw(e,t,n){let r=n.semantic&&n.semanticEvidence?t.flatMap(p=>{let f=gw(e,p);return f?[f]:[]}):[],i=new Map(r.map(p=>[p.symbolId,p])),o=n.semanticEvidence?.referenceMap(e,r)??new Map,s=Mf(e,t),a=new Set(t.map(p=>p.symbol)),l=[...new Set(t.flatMap(p=>On(e,"reverse",[p.relativePath])))].flatMap(p=>U(e,p)),u=new Map,d=yg(e,l);for(let p of l)for(let f of d.get(p.symbolId)??[]){if(!a.has(f.symbol))continue;let g=u.get(f.symbol)??[];g.push({symbol:p.symbol,file:p.relativePath,source:"caller-map-inversion",callEvidence:f.source}),u.set(f.symbol,g)}let m=new Map;for(let p of t){let f=[],g=new Set,h=S=>{if(S.symbol===p.symbol)return;let y=`${S.symbol}|${S.file}`;g.has(y)||(g.add(y),f.push(S))};for(let S of u.get(p.symbol)??[])h(S);for(let S of s.get(p.symbolId)??[])S.file!==p.relativePath&&h({symbol:S.enclosingSymbol??S.file,file:S.file,source:"resolved-reference"});let b=i.get(p.symbolId);if(b)for(let S of o.get(b.symbolId)??[]){if(S.file===p.relativePath||e.isIgnored(S.file))continue;let y=Ne(U(e,S.file),S.line);h({symbol:y?.symbol??S.file,file:S.file,source:"semantic-reference"})}m.set(p.symbolId,f)}return m}function gw(e,t){let n=Kt().join(", "),r=gg().join(", ");return e.get(`SELECT
4
- d.id AS documentId,
5
- gs.id AS symbolId,
6
- gs.symbol,
7
- d.relative_path AS relativePath,
8
- COALESCE(der.start_line, c.start_line) AS startLine,
9
- COALESCE(der.end_line, c.end_line) AS endLine,
10
- COALESCE(gs.display_name, '') AS leaf,
11
- NULL AS parentTypeName,
12
- CASE WHEN gs.kind IN (${n}) OR gs.symbol LIKE '%().' THEN 1 ELSE 0 END AS isFunctionLike,
13
- CASE WHEN gs.kind IN (${r}) THEN 1 ELSE 0 END AS isTypeLike,
14
- gs.kind AS kind,
15
- gs.documentation AS documentation,
16
- gs.enclosing_symbol AS enclosingSymbol
17
- FROM global_symbols gs
18
- LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
19
- LEFT JOIN chunks c ON c.document_id = der.document_id
20
- JOIN documents d ON d.id = COALESCE(der.document_id, c.document_id)
21
- WHERE gs.id = ?
22
- LIMIT 1`,t.symbolId)??null}function Er(e,t,n={}){if(t.length===0)return new Map;let r=n.additive??!1,i=[],o=[];for(let u of t)se(u.relativePath)&&Gt(e,u.relativePath)!==null?i.push(u):o.push(u);let s=new Map,a=new Map,c=u=>{for(let[d,m]of u){let p=s.get(d);p||(p=[],s.set(d,p));let f=a.get(d);f||(f=new Set,a.set(d,f));for(let g of m){let h=`${g.symbol}|${g.chunkId}`;f.has(h)||(f.add(h),p.push(g))}}};i.length>0&&c(yg(e,i)),n.semantic!==!1&&n.semanticEvidence&&c(Cw(n.semanticEvidence.calleeMap(e,t)));let l=r?t:o;return l.length>0&&c(Sw(e,l)),s}function yg(e,t){let n=new Map,r=hw(t,n),i=zt(e);for(let[o,s]of r){let a=Gt(e,o);if(!a)continue;let c=vf(s);for(let l of a){let u=c.get(l.line);if(!u)continue;let d=yw(e,o,i,l);d&&d.symbol!==u.symbol&&n.get(u.symbolId).push({symbol:d.symbol,file:d.file,chunkId:l.line,source:"ast-callsite",callsiteLine:l.line})}}return n}function hw(e,t){let n=new Map;for(let r of e){let i=n.get(r.relativePath);i?i.push(r):n.set(r.relativePath,[r]),t.set(r.symbolId,[])}for(let r of n.values())r.sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine));return n}function yw(e,t,n,r){let i=ri(e,t,r.calleeLeaf);if(i){let a=_t(t,n.get(i.importedName)??[]).filter(c=>Fe(i.sourcePath,c.file));return a.length===1?a[0]:null}let o=_t(t,n.get(r.calleeLeaf)??[]);if(o.length===0)return null;let s=bw(e,t,o,r.calleeQualifier);return s||$n(e,t,o,r.memberAccess,r.calleeQualifier)}function bw(e,t,n,r){if(!r||se(t)!=="clojure")return null;let o=ae(e,t).filter(s=>s.kind==="namespace"&&s.localName===r&&s.sourcePath).map(s=>s.sourcePath);for(let s of o){let a=n.find(c=>Fe(s,c.file));if(a)return a}return n.find(s=>/`([^`]+)`\//.exec(s.symbol)?.[1]===r)??null}function Sw(e,t){if(t.length===0)return new Map;let r=kl(t.map(p=>p.documentId)).flatMap(p=>e.all(`SELECT c.document_id, c.id AS chunk_id, c.start_line, c.end_line, m.symbol_id
23
- FROM mentions m
24
- JOIN chunks c ON m.chunk_id = c.id
25
- WHERE m.role != 1
26
- AND c.document_id IN (${p.map(()=>"?").join(",")})`,...p)),i=new Map;for(let p of r)i.has(p.document_id)||i.set(p.document_id,[]),i.get(p.document_id).push(p);let s=kl(r.map(p=>p.symbol_id)).flatMap(p=>e.all(`SELECT gs.id AS symbol_id, gs.symbol,
27
- COALESCE(der.document_id, def_chunk.document_id) AS document_id
28
- FROM global_symbols gs
29
- LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
30
- LEFT JOIN (
31
- SELECT m.symbol_id, MIN(c.document_id) AS document_id
32
- FROM mentions m
33
- JOIN chunks c ON m.chunk_id = c.id
34
- WHERE m.role = 1
35
- AND m.symbol_id IN (${p.map(()=>"?").join(",")})
36
- GROUP BY m.symbol_id
37
- ) def_chunk ON def_chunk.symbol_id = gs.id
38
- WHERE gs.id IN (${p.map(()=>"?").join(",")})`,...p,...p)),a=kl([...t.map(p=>p.documentId),...s.flatMap(p=>p.document_id===null?[]:[p.document_id])]),c=new Map(a.flatMap(p=>e.all(`SELECT id, relative_path FROM documents
39
- WHERE id IN (${p.map(()=>"?").join(",")})`,...p).map(f=>[f.id,f.relative_path]))),l=new Map;for(let p of s)l.has(p.symbol_id)||l.set(p.symbol_id,{symbol:p.symbol,file:p.document_id!==null?c.get(p.document_id)??"":""});let u=new Map,d=c,m=vw(t);for(let[p,f]of m){let h=[...i.get(p)??[]].sort((x,v)=>x.start_line-v.start_line||x.end_line-v.end_line),b=[...f].sort((x,v)=>x.startLine-v.startLine||x.endLine-v.endLine),S=new Set,y=0;for(let x of b){for(;y<h.length&&h[y].start_line<=x.endLine;)S.add(h[y]),y+=1;for(let w of S)w.end_line<x.startLine&&S.delete(w);let v=new Set,C=[],R=null,E=()=>{if(R)return R;let w=d.get(x.documentId)??"",I=new Set;if(w){let k=Cf(e,w),D=Math.max(0,x.startLine),F=Math.min(k.length-1,x.endLine);for(let L=D;L<=F;L+=1)for(let A of k[L])I.add(A)}return R=I,I};for(let w of S){if(w.symbol_id===x.symbolId)continue;let I=l.get(w.symbol_id);if(!I)continue;if(!(w.start_line>=x.startLine&&w.end_line<=x.endLine)){if(!(w.start_line<=x.endLine&&w.end_line>=x.startLine))continue;let L=z(I.symbol);if(!L||!E().has(L))continue}let D=`${I.symbol}|${w.chunk_id}`;v.has(D)||(v.add(D),C.push({...I,chunkId:w.chunk_id,source:"scip-chunk"}))}u.set(x.symbolId,C)}}return u}var hg=500;function kl(e){let t=[...new Set(e)],n=[];for(let r=0;r<t.length;r+=hg)n.push(t.slice(r,r+hg));return n}function vw(e){let t=new Map;for(let n of e){let r=t.get(n.documentId);r?r.push(n):t.set(n.documentId,[n])}return t}function Cw(e){let t=new Map;for(let[n,r]of e){let i=[];for(let o of r)i.push({symbol:o.symbol,file:o.file,chunkId:-1,source:"semantic-callee",...o.callsiteLine===void 0?{}:{callsiteLine:o.callsiteLine}});t.set(n,i)}return t}var xw=12,Rw=280;function di(e,t,n,r){let i=Ew(e,t,n,r);if(i.size===0)return Pw();let o=[],s=new Set,a=(l,u,d,m)=>{if(u===t&&d<=r&&m>=n)return;let p=`${u}:${d}:${m}:${l}`;s.has(p)||(s.add(p),o.push({name:l,relativePath:u,startLine:d,endLine:m}))};for(let l of U(e,t))i.has(l.leaf)&&a(l.leaf,l.relativePath,l.startLine,l.endLine);for(let l of ae(e,t)){let u=l.localName;if(!u||!i.has(u)||!l.sourcePath||l.kind==="namespace")continue;let d=l.importedName==="default"?u:l.importedName;for(let m of qn(e,l.sourcePath,d,{maxReexportDepth:3}))a(u,m.relativePath,m.startLine,m.endLine)}o.sort(Sg);let c=o.map(l=>{let u=Iw(e,l);return u?{...l,source:u}:null}).filter(l=>l!==null).slice(0,xw);return Al(c)}function ea(e,t=[]){return Al(ww(e.flatMap(n=>n?.inline??[]),t))}function bg(e){return e?e.inline.reduce((t,n)=>t+n.name.length+n.source.length+32,0):0}function Ew(e,t,n,r){let i=K(e,t),o=new Set;if(!i)return o;for(let s=n;s<=r;s+=1)for(let a of i.identifiersByLine[s]??[])o.add(a);return o}function Iw(e,t){if(t.startLine!==t.endLine)return null;let n=(V(e,t.relativePath)[t.startLine]??"").trim();if(!n||n.length>Rw)return null;let r=n.indexOf("=");if(r<0||n[r+1]===">")return null;let i=n.slice(r+1).replace(/(?:\/\/|#).*$/u,"").trim();if(!i||i.includes("${")||/\b(?:function|class|struct|interface|trait|enum|lambda)\b/u.test(i))return null;let s=i.replace(/(['"`])(?:\\.|(?!\1).)*\1/gu,"").replace(/\b(?:0[xX][\dA-Fa-f_]+|0[bB][01_]+|0[oO][0-7_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:[eE][+-]?\d+)?)n?\b/gu,""),a=new Set(["true","false","null","undefined","None","True","False"]);return(s.match(/[A-Za-z_][A-Za-z0-9_]*/gu)??[]).some(l=>!a.has(l))?null:n}function ww(e,t){let n=new Map;for(let r of e){if(Lw(r,t))continue;let i=`${r.relativePath}:${r.startLine}:${r.endLine}:${r.name}`;n.has(i)||n.set(i,{...r})}return[...n.values()].sort(Sg)}function Lw(e,t){return t.some(n=>n.relativePath===e.relativePath&&n.startLine<=e.startLine&&n.endLine>=e.endLine)}function Sg(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||e.name.localeCompare(t.name)}function Al(e){return{coverage:"indexed-project-literal-values",inline:e}}function Pw(){return Al([])}var Dw=12,Mw=20,Nl=200,_l=800,Tw=.9,kw=64,Aw=Zp("behavior-construct-ranges"),Cg={if_statement:"branch",conditional_expression:"branch",ternary_expression:"branch",switch_statement:"branch",switch_expression:"branch",switch_case:"branch",case_statement:"branch",match_statement:"branch",match_expression:"branch",match_arm:"branch",for_statement:"loop",for_in_statement:"loop",for_of_statement:"loop",while_statement:"loop",do_statement:"loop",await_expression:"await",return_statement:"return",throw_statement:"throw",raise_statement:"throw",assignment_expression:"mutation",augmented_assignment_expression:"mutation",assignment:"mutation",pair:"shape",field_initializer:"shape",spread_element:"spread",dictionary_splat:"spread",catch_clause:"catch",except_clause:"catch",finally_clause:"finally"},sa=["anchor","signature","binding","branch","loop","call","await","return","throw","mutation","shape","spread","catch","finally"],xg=[...sa,"lifecycle"],Rg=["loop","await","throw","mutation","spread","catch","finally","lifecycle"],Fw=new Set(["onBeforeMount","onBeforeUnmount","onMounted","onUnmounted","useEffect","useInsertionEffect","useLayoutEffect"]);var Eg=new Set(["object","object_pattern","dictionary","field_declaration_list","struct_expression","struct_pattern"]);function mi(e,t,n,r,i=[],o={}){let s=J(e,t);if(!s)return null;let a=V(e,t),c=ot(e,t,n,r,i),l=la(e,t,c.startLine,c.endLine),u=l?.startLine??n,d=l?.endLine??r,m=(l?pi(s.rootNode,c.startLine,c.endLine):null)??br(s.rootNode,u,d);if(!m)return null;let p=Dg(m,a,u,d,i);if(!p||p.lines.length===0||p.lines.some(b=>b.text.length>_l))return null;let f=Zw(a,u,d),g=eL(p);if((o.requireSavings??!0)&&g>=f*Tw)return null;let h=sa.filter(b=>p.lines.some(S=>S.signals.includes(b)));return{...l?{callable:{name:l.name,startLine:l.startLine,endLine:l.endLine}}:{},representation:"outline",constructKind:p.constructKind,signature:p.signature,lines:p.lines,signals:h,testCases:q(t)==="test"?oL(a,u,d):[],coverage:{sourceStatements:p.sourceStatements,representedStatements:p.sourceStatements,copiedStatements:p.copiedStatements,omittedStatements:0},rawCharacters:f,outlineCharacters:g,candidateLines:p.sourceStatements,omittedLines:0}}function aa(e,t,n,r,i){if(i.length===0)return[];let o=J(e,t);if(!o)return[];let s=V(e,t),a=ot(e,t,n,r,i),c=la(e,t,a.startLine,a.endLine),l=c?.startLine??n,u=c?.endLine??r,d=(c?pi(o.rootNode,a.startLine,a.endLine):null)??br(o.rootNode,l,u);if(!d)return[];let m=Dg(d,s,l,u,i);return m?m.lines.filter(p=>p.text.length<=_l&&p.signals.some(f=>["branch","loop","catch","finally"].includes(f))&&i.some(f=>f>=p.line&&f<=p.endLine)):[]}function Ig(e,t,n,r){let i=J(e,t);if(!i)return null;let o=pi(i.rootNode,n,r)??br(i.rootNode,n,r);if(!o)return null;let s=[],a=$l(o),c=[];return jl(o,o,l=>{if(oo.has(l.type)||_w.has(l.type)){Bw(s,c,l);return}if(ca.has(l.type)){$w(s,c,l);return}if(lo.has(l.type)){jw(s,c,l);return}uo.has(l.type)&&Hw(s,l)}),{facts:Kw(s),terminals:Pg(a),unsupported:c}}function ot(e,t,n,r,i=[]){let o=i.filter(u=>u>=n&&u<=r),s=Aw.get(e,t,W(e,t)??"",()=>new Map),a=`${n}:${r}:${o.join(",")}`,c=s.get(a);if(c)return s.delete(a),s.set(a,c),{startLine:c[0],endLine:c[1]};let l=Nw(e,t,n,r,o);if(s.set(a,[l.startLine,l.endLine]),s.size>kw){let u=s.keys().next().value;u!==void 0&&s.delete(u)}return l}function Nw(e,t,n,r,i){let o=J(e,t),s=[];if(i.length>0&&o){let u=[],d=i[0],m=d;for(let f of i)d=Math.min(d,f),m=Math.max(m,f);kg(o.rootNode,d,m,f=>{Ww(f)&&f.startPosition.row>=n&&f.endPosition.row<=r&&i.every(g=>f.startPosition.row<=g&&f.endPosition.row>=g)&&u.push(f),zn.has(f.type)&&f.startPosition.row>=n&&f.endPosition.row<=r&&i.every(g=>f.startPosition.row<=g&&f.endPosition.row>=g)&&s.push(f)});let p=u.sort((f,g)=>f.endPosition.row-f.startPosition.row-(g.endPosition.row-g.startPosition.row)||f.startPosition.row-g.startPosition.row)[0];if(p)return{startLine:p.startPosition.row,endLine:p.endPosition.row}}let a=la(e,t,n,r);if(a)return{startLine:a.startLine,endLine:a.endLine};if(i.length===0)return{startLine:n,endLine:r};let c=(K(e,t)?.callables??[]).filter(u=>u.startLine>=n&&u.endLine<=r&&i.every(d=>u.startLine<=d&&u.endLine>=d)).sort((u,d)=>u.endLine-u.startLine-(d.endLine-d.startLine)||u.startLine-d.startLine)[0];if(!o)return c?{startLine:c.startLine,endLine:c.endLine}:{startLine:n,endLine:r};let l=s.sort((u,d)=>u.endPosition.row-u.startPosition.row-(d.endPosition.row-d.startPosition.row)||u.startPosition.row-d.startPosition.row)[0];return l?{startLine:l.startPosition.row,endLine:l.endPosition.row}:c?{startLine:c.startLine,endLine:c.endLine}:{startLine:n,endLine:r}}function Ol(e,t,n,r,i={}){if(r-n+1<(i.minimumBodyLines??Mw))return null;let s=Tg(e,t,n,r,[],!1);if(!s)return null;let a=s.candidates.map(b=>({...b,signals:b.signals.filter(S=>S!=="anchor"&&S!=="signature")})).filter(b=>b.signals.length>0);if(a.length===0)return null;let c=rL(a),l=a.filter(b=>b.text.length<=Nl);if(l.length===0)return null;let u=Rg.filter(b=>(c[b]??0)>0),d=u.filter(b=>b!=="await"),m=s.shapes.reduce((b,S)=>b+S.fields.length,0);if(d.length===0&&!((c.await??0)>0&&m>0)&&m<3)return null;let p=iL(l,c),f=new Map;for(let b of u){let S=p.find(y=>y.signals.includes(b));S&&f.set(S.line,S)}if(f.size===0){let b=p.find(S=>S.signals.includes("branch"));b&&f.set(b.line,b)}let g=Math.min(10,Math.max(1,i.maxLines??f.size)),h=new Map;for(let b of f.values()){if(h.size>=g)break;h.set(b.line,b)}return h.size>=a.length&&s.shapes.length===0?null:{owner:s.callable?.name??null,startLine:n,endLine:r,lines:[...h.values()].sort((b,S)=>b.line-S.line),shapes:s.shapes,signalCounts:c,candidateLines:a.length,omittedLines:a.length-h.size}}function bn(e,t,n,r){let i=Tg(e,t,n,r,[],!1);return i?new Map(i.candidates.map(o=>[o.line,o.signals.filter(s=>s!=="lifecycle")])):new Map}var zn=new Set(["arrow_function","constructor_declaration","function_declaration","function_definition","function_expression","generator_function","generator_function_declaration","function_item","lambda","lambda_expression","method","method_declaration","method_definition"]),ft=new Set(["block","body","compound_statement","declaration_list","statement_block"]),oo=new Set(["if_expression","if_statement","unless","unless_statement"]),_w=new Set(["conditional_expression","ternary_expression"]),ca=new Set(["do_statement","enhanced_for_statement","for_expression","for_in_statement","for_of_statement","for_statement","loop_expression","while_statement"]),lo=new Set(["match_expression","match_statement","switch_expression","switch_statement"]),wg=new Set(["case_statement","match_arm","switch_case","switch_default"]),uo=new Set(["try_expression","try_statement"]),ra=new Set(["catch_clause","except_clause","rescue"]),ao=new Set(["ensure","finally_clause"]),so=new Set(["else","else_clause"]),Lg=new Set(["raise_statement","return_statement","throw_statement"]),Ow=new Set(["block_comment","comment","line_comment"]);function Bw(e,t,n){let r=n.childForFieldName("condition")??Ul(n),i=n.childForFieldName("consequence")??n.childForFieldName("body")??n.namedChildren.find(c=>ft.has(c.type)),o=n.childForFieldName("alternative")??n.namedChildren.find(c=>so.has(c.type));if(!r||!i){t.push(Hl(n,"conditional-fields-unresolved"));return}let s=Vt(r,"predicate",r.text),a=Vt(i,vg(i),"consequence");if(Wt(e,s,a,"predicate-consequence",{branchRole:"consequence"}),ia(e,s,i,"consequence"),o){let c=Vt(o,vg(o),"alternative");Wt(e,s,c,"predicate-alternative",{branchRole:"alternative"}),ia(e,s,o,"alternative");return}Wt(e,s,Bl(s,"otherwise continue"),"predicate-fallthrough",{branchRole:"fallthrough"})}function $w(e,t,n){let r=n.childForFieldName("body")??n.namedChildren.find(s=>ft.has(s.type));if(!r){t.push(Hl(n,"loop-body-unresolved"));return}let i=n.childForFieldName("condition"),o=Vt(i??n,"predicate",i?.text??Ot(n,r));Wt(e,o,Vt(r,"outcome","iteration"),"loop-iteration",{branchRole:"iteration"}),ia(e,o,r,"iteration"),Wt(e,o,Bl(o,"loop exits"),"loop-exit",{branchRole:"exit"})}function jw(e,t,n){let r=n.childForFieldName("body")??n.namedChildren.find(c=>ft.has(c.type)),i=n.childForFieldName("value")??n.childForFieldName("condition")??n.childForFieldName("subject")??Ul(n),o=qw(r??n);if(!i||o.length===0){t.push(Hl(n,"switch-cases-unresolved"));return}let s=Vt(i,"predicate",i.text),a=!1;for(let c of o){let l=zw(c);a||=l;let u=Ot(c,c.namedChildren.find(d=>oa(d)));Wt(e,s,Vt(c,"outcome",u||(l?"default":"case")),l?"predicate-default":"predicate-case",{branchRole:l?"default":"case"}),ia(e,s,c,l?"default":"case")}a||Wt(e,s,Bl(s,"no case matched"),"predicate-fallthrough",{branchRole:"fallthrough"})}function Hw(e,t){let n=Vt(t,"scope","try");for(let r of Gw(t)){let i=ao.has(r.type),o=Vt(r,"handler",i?"finally":Ot(r,ta(r)));Wt(e,n,o,i?"finally-cleanup":"exception-handler",{branchRole:i?"finally":"catch"}),Uw(e,o,r,i?"finally":"catch")}}function Uw(e,t,n,r){for(let i of $l(n)){let o=i.label.startsWith("throw")||i.label.startsWith("raise")?"throw":"return";Wt(e,t,i,o==="throw"?"handler-throw":"handler-return",{branchRole:r,terminalKind:o})}}function ia(e,t,n,r){for(let i of $l(n)){let o=i.label.startsWith("throw")||i.label.startsWith("raise")?"throw":"return";Wt(e,t,i,o==="throw"?"predicate-throw":"predicate-return",{branchRole:r,terminalKind:o})}}function Wt(e,t,n,r,i){e.push({controller:t,outcome:n,subtype:r,attributes:i})}function Vt(e,t,n){return{kind:t,label:co(n).slice(0,_l),startLine:e.startPosition.row,endLine:e.endPosition.row,implicit:!1}}function Bl(e,t){return{...e,kind:"outcome",label:t,implicit:!0}}function vg(e){return Lg.has(e.type)?"terminal":"outcome"}function $l(e){let t=[];return jl(e,e,n=>{Lg.has(n.type)&&t.push(Vt(n,"terminal",n.text))}),Pg(t)}function jl(e,t,n){n(t);for(let r of t.namedChildren)r!==e&&zn.has(r.type)||jl(e,r,n)}function qw(e){let t=[],n=r=>{for(let i of r.namedChildren)lo.has(i.type)||(wg.has(i.type)?t.push(i):n(i))};return n(e),t}function Gw(e){let t=[],n=r=>{for(let i of r.namedChildren)uo.has(i.type)||(ra.has(i.type)||ao.has(i.type)?t.push(i):zn.has(i.type)||n(i))};return n(e),t}function zw(e){let t=Ot(e,e.namedChildren.find(n=>oa(n))).trim();return e.type==="switch_default"||/^(?:default\b|_\s*=>)/u.test(t)}function Hl(e,t){return{startLine:e.startPosition.row,endLine:e.endPosition.row,reason:t}}function Kw(e){let t=new Map;for(let n of e)t.set(`${n.controller.startLine}\0${n.controller.endLine}\0${n.outcome.startLine}\0${n.outcome.endLine}\0${n.subtype}\0${n.outcome.label}`,n);return[...t.values()]}function Pg(e){let t=new Map;for(let n of e)t.set(`${n.startLine}\0${n.endLine}\0${n.kind}\0${n.label}`,n);return[...t.values()]}function Ww(e){return zn.has(e.type)||ca.has(e.type)||lo.has(e.type)||uo.has(e.type)||ra.has(e.type)||ao.has(e.type)}function Dg(e,t,n,r,i){let s=pi(e,n,r)??e,a=ta(s),c=[],l=0,u=0,d=(C,R,E,w,I=!1,k=!0)=>{let D=I?E.trim():co(E);if(!D)return;let F=Math.max(n,C.startPosition.row),L=Math.min(r,C.endPosition.row);c.push({line:F,endLine:Math.max(F,L),depth:R,signals:sa.filter(A=>w.includes(A)||A==="anchor"&&i.some(P=>P>=F&&P<=L)),text:D,copied:I}),k&&(l+=1,I&&(u+=1))},m=(C,R)=>{for(let E of C.namedChildren)v(E,R)},p=(C,R)=>{if(oo.has(C.type)){f(C,R,"else if");return}if(so.has(C.type)){let E=C.namedChildren.find(I=>oo.has(I.type));if(E){f(E,R,"else if");return}d(C,R,"else",["branch"],!1,!1);let w=ta(C)??C.namedChildren.find(I=>ft.has(I.type));if(w)v(w,R+1);else for(let I of C.namedChildren)v(I,R+1);return}d(C,R,"else",["branch"],!1,!1),v(C,R+1)},f=(C,R,E=C.type.startsWith("unless")?"unless":"if")=>{let w=C.childForFieldName("condition")??Ul(C),I=C.childForFieldName("consequence")??C.childForFieldName("body")??C.namedChildren.find(F=>ft.has(F.type)),k=C.childForFieldName("alternative")??C.namedChildren.find(F=>so.has(F.type)),D=w?w.text:Ot(C,I);d(C,R,`${E} ${Xw(D)}`,io(w,["branch"])),I&&v(I,R+1),k&&p(k,R)},g=(C,R)=>{let E=C.childForFieldName("body")??C.namedChildren.find(w=>ft.has(w.type));d(C,R,Ot(C,E),io(C,["loop"])),E&&v(E,R+1)},h=(C,R)=>{let E=C.childForFieldName("body")??C.namedChildren.find(w=>ft.has(w.type));d(C,R,Ot(C,E),io(C,["branch"])),E&&v(E,R+1)},b=(C,R)=>{let E=C.namedChildren.find(w=>oa(w));d(C,R,Ot(C,E),["branch"],!1,!1);for(let w of C.namedChildren)(w===E||oa(w))&&v(w,R+1)},S=(C,R)=>{d(C,R,"try",[],!1);for(let E of C.namedChildren)ft.has(E.type)?v(E,R+1):(ra.has(E.type)||ao.has(E.type))&&v(E,R)},y=(C,R,E)=>{let w=C.childForFieldName("body")??C.namedChildren.find(k=>ft.has(k.type)),I=E==="finally"?"finally":Ot(C,w);d(C,R,I,[E],!1,!1),w&&v(w,R+1)},x=(C,R)=>{let E=ta(C);d(C,R,Ot(C,E),io(C,["binding"])),E&&v(E,R+1)},v=(C,R)=>{if(C.startPosition.row>r||C.endPosition.row<n||Ow.has(C.type)||C.type==="empty_statement")return;if(ft.has(C.type)){m(C,R);return}if(oo.has(C.type)){f(C,R);return}if(ca.has(C.type)){g(C,R);return}if(lo.has(C.type)){h(C,R);return}if(wg.has(C.type)){b(C,R);return}if(uo.has(C.type)){S(C,R);return}if(ra.has(C.type)){y(C,R,"catch");return}if(ao.has(C.type)){y(C,R,"finally");return}if(so.has(C.type)){p(C,R);return}if(zn.has(C.type)){x(C,R);return}let w=!Mg(C)||Qw(C);d(C,R,C.text,io(C),w)};return v(a&&a!==s?a:s,0),l===0?null:{constructKind:Jw(s),signature:Yw(s,a,t,n),lines:c,sourceStatements:l,copiedStatements:u}}function pi(e,t,n){let r=e.namedChildren.filter(i=>i.startPosition.row<=t&&i.endPosition.row>=n);for(let i of r.sort(Vw)){let o=pi(i,t,n);if(o)return o}return zn.has(e.type)&&e.startPosition.row<=t&&e.endPosition.row>=n?e:null}function Vw(e,t){return e.endPosition.row-e.startPosition.row-(t.endPosition.row-t.startPosition.row)||e.startPosition.row-t.startPosition.row}function ta(e){return e.childForFieldName("body")??e.childForFieldName("consequence")??e.namedChildren.find(t=>ft.has(t.type))??null}function Yw(e,t,n,r){let i=Ot(e,t);return i||(n[r]??e.text).trim()}function Jw(e){return e.type.includes("constructor")?"constructor":e.type.includes("method")||e.type==="method"?Fl(e,new Set(["class_body","class_declaration","class_definition"]))?"class method":"object method":e.type==="arrow_function"||e.type==="function_expression"||e.type==="lambda"?Fl(e,new Set(["object","pair"]))?"object member":"function value":e.type.includes("function")?Fl(e,zn)?"nested function":"module function":"source construct"}function Fl(e,t){let n=e.parent;for(;n;){if(t.has(n.type))return!0;n=n.parent}return!1}function Ul(e){return e.namedChildren.find(t=>!ft.has(t.type)&&!so.has(t.type))??null}function Ot(e,t){if(!t)return co(e.text);let n=Math.max(0,t.startIndex-e.startIndex);return co(e.text.slice(0,n)).replace(/[:{]\s*$/u,"").trim()}function Xw(e){let t=co(e);return t.startsWith("(")&&t.endsWith(")")?t.slice(1,-1).trim():t}function co(e){return e.trim().replace(/\r?\n[\t ]*/gu," ")}function io(e,t=[]){let n=new Set(t);return e&&mo(e,r=>{let i=Cg[r.type];i&&n.add(i),r.type==="call_expression"&&(n.add("call"),Ag(r)&&n.add("shape")),ql.has(r.type)&&n.add("binding")}),sa.filter(r=>n.has(r))}function Qw(e){let t=!1;return mo(e,n=>{t||!n.text.includes(`
40
- `)||/(?:string|template|heredoc|raw_string)/u.test(n.type)&&(t=!0)}),t}function oa(e){return ft.has(e.type)||oo.has(e.type)||ca.has(e.type)||lo.has(e.type)||uo.has(e.type)||zn.has(e.type)||Mg(e)}function Mg(e){return/(?:statement|declaration|expression|assignment|return|throw|raise|break|continue|yield|with_item)$/u.test(e.type)||ql.has(e.type)}function Zw(e,t,n){let r=0;for(let i=t;i<=n;i+=1)r+=(e[i]?.length??0)+10;return r}function eL(e){return e.constructKind.length+e.signature.length+80+e.lines.reduce((t,n)=>t+n.text.length+n.depth*2+10,0)}function Tg(e,t,n,r,i,o){let s=J(e,t);if(!s)return null;let a=V(e,t),c=la(e,t,n,r),l=o?c?.startLine??n:n,u=o?c?.endLine??r:r,m=(c?.startLine===l&&c.endLine===u?pi(s.rootNode,l,u):null)??br(s.rootNode,l,u);if(!m)return null;let p=new Map,f=new Map,g=new Map,h=(y,x)=>{if(y<l||y>u)return;let v=p.get(y)??new Set;v.add(x),p.set(y,v)};c&&h(c.startLine,"signature");for(let y of i)h(y,"anchor");mo(m,y=>{let x=Cg[y.type];if(x&&h(y.startPosition.row,x),x==="shape"&&tL(f,y,m,l,u),y.type==="call_expression"){let C=(y.childForFieldName("function")??y.namedChild(0))?.text.split(".").at(-1);if(Ag(y)){h(y.startPosition.row,"shape");let R=na(y.text);R.length<=Nl&&g.set(y.startPosition.row,R)}if(C&&Fw.has(C)){h(y.startPosition.row,"lifecycle");let R=na(y.text);R.length<=Nl&&g.set(y.startPosition.row,R)}}ql.has(y.type)&&h(y.startPosition.row,"binding")});let b=K(e,t);for(let y of b?.callSites??[])y.line<l||y.line>u||(h(y.line,"call"),y.calleeLeaf==="catch"&&h(y.line,"catch"));let S=[...p.entries()].sort(([y],[x])=>y-x).map(([y,x])=>({line:y,signals:xg.filter(v=>x.has(v)),text:g.get(y)??na(a[y]??"")})).filter(y=>y.text.length>0||y.signals.includes("anchor"));return{...c?{callable:c}:{},rangeStart:l,rangeEnd:u,sourceLines:a,candidates:S,shapes:[...f.values()].sort((y,x)=>y.startLine-x.startLine)}}function tL(e,t,n,r,i){if(t.startPosition.row<r||t.endPosition.row>i)return;let o=t.childForFieldName("key")??t.childForFieldName("name")??t.namedChild(0),s=na(o?.text??"");if(!s||s.includes(`
41
- `)||s.length>60)return;let a=nL(t,n);if(a.startPosition.row<r||a.endPosition.row>i)return;let c=`${a.startPosition.row}:${a.endPosition.row}`,l=e.get(c)??{startLine:a.startPosition.row,endLine:a.endPosition.row,fields:[]};l.fields.some(u=>u.name===s&&u.line===t.startPosition.row)||l.fields.push({name:s,line:t.startPosition.row}),e.set(c,l)}function nL(e,t){let n=e.parent;for(;n&&n!==t.parent;){if(Eg.has(n.type))return n;if(n===t)break;n=n.parent}return e.parent??e}function la(e,t,n,r){return K(e,t)?.callables.filter(i=>i.startLine<=n&&i.endLine>=r).sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine)||i.startLine-o.startLine)[0]}function mo(e,t){t(e);for(let n of e.namedChildren)mo(n,t)}function kg(e,t,n,r){r(e);for(let i of e.namedChildren)i.startPosition.row>t||i.endPosition.row<n||kg(i,t,n,r)}function na(e){return e.trim().replace(/\s+/gu," ")}function Ag(e){if(e.type!=="call_expression")return!1;let t=e.childForFieldName("arguments")??e.namedChildren.find(r=>r.type==="arguments"||r.type==="argument_list");if(!t)return!1;let n=!1;return mo(t,r=>{Eg.has(r.type)&&(n=!0)}),n}function rL(e){let t={};for(let n of xg){let r=e.filter(i=>i.signals.includes(n)).length;r>0&&(t[n]=r)}return t}function iL(e,t){let n=new Map;for(let o of e){let s=o.signals.join(",");n.set(s,(n.get(s)??0)+1)}let r=new Set(Rg),i=o=>{let s=n.get(o.signals.join(","))??1,a=Math.min(...o.signals.map(u=>t[u]??1)),c=o.signals.some(u=>r.has(u))?3:1,l=Math.max(0,o.signals.length-1)*1e3;return c*(1e3/s+1e3/a)+l};return[...e].sort((o,s)=>i(s)-i(o)||s.line-o.line)}var ql=new Set(["lexical_declaration","variable_declarator","const_item","static_item","let_declaration","assignment"]);function oL(e,t,n){let r=[],i=/\b(?:describe|it|test)(?:\.(?:only|skip|todo))?\s*\(\s*(['"`])([^'"`]+)\1/u;for(let o=t;o<=n;o+=1){let s=i.exec(e[o]??"")?.[2];if(!(!s||r.includes(s))&&(r.push(s),r.length>=Dw))break}return r}var sL=new Set(["arrow_function","class_declaration","constructor_declaration","field_definition","function_declaration","function_definition","function_expression","function_item","generator_function_declaration","generator_function","lexical_declaration","method","method_declaration","method_definition","object_method","variable_declaration"]);function fi(e,t,n){let r=J(e,t)?.rootNode??null,i=aL(r,n);if(!i)return null;let o=V(e,t);if(o.length===0)return null;let s=Math.max(0,i.startPosition.row),a=i.endPosition.column===0?i.endPosition.row-1:i.endPosition.row;return{type:i.type,startLine:s,endLine:Math.min(o.length-1,Math.max(s,a))}}function po(e,t,n,r,i){let o=ot(e,t,r,i,[n]),s=o.startLine===o.endLine&&/(?:=>|\(|\{|\[|,)\s*$/u.test(V(e,t)[o.startLine]??"");if(!s&&(o.startLine>r||o.endLine<i))return o;let a=fi(e,t,n);return s&&a?{startLine:a.startLine,endLine:a.endLine}:a&&a.startLine>=r&&a.endLine<=i?{startLine:a.startLine,endLine:a.endLine}:{startLine:r,endLine:i}}function aL(e,t){if(!e||!_g(e,t))return null;let n=Ng(e,t);for(;n;){if(sL.has(n.type))return n;n=n.parent}return null}function Ng(e,t){let n=e.namedChildren.filter(r=>_g(r,t)).sort((r,i)=>Fg(r)-Fg(i));return n.length>0?Ng(n[0],t):e}function _g(e,t){return e.startPosition.row<=t&&e.endPosition.row>=t}function Fg(e){return e.endIndex-e.startIndex}var cL=new Set(["call","call_expression","command","command_call","function_call_expression","invocation_expression","macro_invocation","method_call","method_invocation","new_expression","object_creation_expression"]);function ua(e,t,n,r){if(!Number.isSafeInteger(n)||n<0)return null;if(!Number.isSafeInteger(r)||r<0)throw new RangeError(`contextLines must be a non-negative safe integer; received ${r}`);let i=V(e,t);if(i.length===0||n>=i.length)return null;let o=Math.max(0,n-r),s=Math.min(i.length-1,n+r);return{relativePath:t,startLine:o,endLine:s,focusLine:n,source:i.slice(o,s+1).join(`
42
- `)}}function Og(e,t,n,r,i){let o=ua(e,t,n,r);if(!o)return null;let s=J(e,t)?.rootNode??null;if(!s)return{...o,kind:"bounded-context"};let a=lL(s,n,i);if(a.length!==1)return{...o,kind:a.length===0?"non-call-reference":"bounded-context"};let c=a[0],l=V(e,t),u=Math.max(0,c.startPosition.row),d=c.endPosition.column===0?c.endPosition.row-1:c.endPosition.row,m=Math.min(l.length-1,Math.max(u,d));return{relativePath:t,startLine:u,endLine:m,focusLine:n,source:l.slice(u,m+1).join(`
43
- `),kind:"complete-call-expression"}}function Bg(e,t,n,r,i){if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`maxLines must be a positive safe integer; received ${i}`);let o=V(e,t);if(o.length===0||n<0||n>=o.length)return null;let s=Math.min(o.length-1,r,n+i-1);return{relativePath:t,startLine:n,endLine:s,focusLine:n,source:o.slice(n,s+1).join(`
44
- `)}}function Kn(e,t,n,r,i=6){if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`maxLines must be a positive safe integer; received ${r}`);let o=V(e,t);if(o.length===0||n<0||n>=o.length)return null;let s=fi(e,t,n);if(!s){let g=ua(e,t,n,i);return g?{...g,unitType:null,unitStartLine:g.startLine,unitEndLine:g.endLine,omittedLines:0}:null}let a=s.startLine,c=s.endLine,l=c-a+1,u=Math.min(l,r),d=n-a-Math.floor(u/2),m=Math.max(0,Math.min(l-u,d)),p=a+m,f=p+u-1;return{relativePath:t,startLine:p,endLine:f,focusLine:n,source:o.slice(p,f+1).join(`
45
- `),unitType:s.type,unitStartLine:a,unitEndLine:c,omittedLines:l-u}}function lL(e,t,n){let r=[];return $g(e,t,n,r),r.filter(i=>!r.some(o=>o!==i&&o.startIndex>=i.startIndex&&o.endIndex<=i.endIndex))}function $g(e,t,n,r){if(dL(e,t)){cL.has(e.type)&&uL(e)===n&&r.push(e);for(let i of e.namedChildren)$g(i,t,n,r)}}function uL(e){let t=e.childForFieldName("function")??e.childForFieldName("constructor")??e.childForFieldName("method")??e.childForFieldName("name")??e.namedChild(0);return t?t.text.match(/[\p{L}_$][\p{L}\p{N}_$!?-]*/gu)?.at(-1)??null:null}function dL(e,t){return e.startPosition.row<=t&&e.endPosition.row>=t}function Hg(e,t,n={}){let{context:r=0}=n,i=Xg(t);if(i)return Qg(e,i.filePath,i.startLine,i.endLine,r);let o=Yg(e,t);if(o)return Kg(e,o);let s=ne(e,t);return s?fo(e,s,r):null}function Z4(e,t,n={}){if(t.length===0)throw new RangeError("code requires at least one selector.");if(t.length>24)throw new RangeError(`code accepts at most ${24} selectors per complete packet; received ${t.length}.`);let r=n.context??0,i=n.members??"exported",o=t.map(c=>pL(e,c,r,i)),s=o.flatMap(c=>c.results),a=s.map(c=>({relativePath:c.relativePath,startLine:c.startLine,endLine:c.endLine}));return{requested:t.length,matched:o.filter(c=>c.status==="matched").length,ambiguous:o.filter(c=>c.status==="ambiguous").length,missing:o.filter(c=>c.status==="missing").length,entries:o,bindingClosure:ea(s.map(c=>c.bindingClosure),a)}}function pL(e,t,n,r){let i=Xg(t);if(i){let u=Qg(e,i.filePath,i.startLine,i.endLine,n);return u?fL(e,t,u,n):Gl(e,t,"definition-source-unreadable")}let o=Yg(e,t);if(o)return hL(e,t,o,n,r);let s=Qe(e,t);if(!s.match)return Gl(e,t,"definition-not-found");let a=IL(e,s),c=a.map(Jg);if(s.total>1){let u=s.total<=4&&a.length===s.total;return{selector:t,status:"ambiguous",kind:"source",totalCandidates:s.total,results:u?a.flatMap(d=>{let m=fo(e,d,n);return m?[m]:[]}):[],definitions:[],candidates:c,omittedCandidates:Math.max(0,s.total-c.length),suggestions:[]}}let l=fo(e,s.match,n);return l?EL(t,l):Gl(e,t,"definition-source-unreadable")}function fL(e,t,n,r){let i=U(e,n.relativePath).filter(l=>!Ug(l,n.relativePath)),o=gL(e,n,i),s=zg(o.map(l=>fo(e,l,r)).filter(l=>l!==null)).filter(l=>!Vg(n,l)),a=new Set(s.map(l=>l.symbol)),c=o.filter(l=>!a.has(l.symbol)&&!(n.startLine<=l.startLine&&n.endLine>=l.endLine)).map(Jg);return{selector:t,status:"matched",kind:"source",totalCandidates:1,results:[n,...s],definitions:[],candidates:[],omittedCandidates:0,suggestions:[],rangeCoverage:{basis:"requested-range-and-same-file-call-closure",referencedDefinitions:o.length,returnedDefinitions:o.length-c.length,returnedBodies:s.length,omittedDefinitions:c.length,omittedLedger:c}}}function gL(e,t,n){if(!go(t.freshness))return[];if(n.length===0)return[];let r=Er(e,n,{additive:!1,semantic:!1}),i=new Map;for(let s of n){let a=i.get(s.symbol)??[];a.push(s),i.set(s.symbol,a)}let o=new Map;for(let s of n)if(!(s.endLine<t.startLine||s.startLine>t.endLine)){for(let a of r.get(s.symbolId)??[])if(a.file===t.relativePath&&!(a.source==="ast-callsite"&&(a.chunkId<t.startLine||a.chunkId>t.endLine)))for(let c of i.get(a.symbol)??[])o.set(c.symbolId,c)}return Gg(e,[...o.values()],n)}function hL(e,t,n,r,i){let o=n.relativePath,s=bL(e,o),a=go(n.freshness)?U(e,o).filter(g=>!Ug(g,o)):[],c=a.filter(g=>pt(e,g)),l=c.length>0?c:yL(s,a),u=i==="all"?[]:Gg(e,l,a),d=i==="all"||a.length===0?[Kg(e,n)]:zg(u.map(g=>fo(e,g,r)).filter(g=>g!==null)),m=vL(s,d),p=CL(o,s,d),f=xL(s);return{selector:t,status:"matched",kind:"file-source",totalCandidates:1,results:d,definitions:[],candidates:[],omittedCandidates:0,suggestions:[],fileCoverage:{members:i,basis:i==="all"||a.length===0?"complete-file-source":c.length>0?"explicit-exports-and-same-file-reference-closure":"top-level-and-same-file-reference-closure",totalDefinitions:f,returnedDefinitions:m,returnedBodies:d.length,omittedDefinitions:Math.max(0,f-m),omittedLedger:p}}}function yL(e,t){let n=new Set(e.map(r=>r.symbol));return t.filter(r=>n.has(r.symbol))}function bL(e,t){return og(e,t).flatMap(n=>SL(n,t)?n.children:[n])}function Ug(e,t){return qg(t).has(e.leaf)}function SL(e,t){return qg(t).has(z(e.symbol))}function qg(e){let t=mL(e);return new Set([t,t.slice(0,Math.max(0,t.length-jg(t).length))])}function Gg(e,t,n){if(t.length===0)return[];let r=Er(e,n,{additive:!0,semantic:!1}),i=new Map;for(let a of n){let c=i.get(a.symbol)??[];c.push(a),i.set(a.symbol,c)}let o=new Map,s=[...t];for(;s.length>0;){let a=s.shift();if(!o.has(a.symbolId)){o.set(a.symbolId,a);for(let c of r.get(a.symbolId)??[])for(let l of i.get(c.symbol)??[])o.has(l.symbolId)||s.push(l)}}return[...o.values()].sort(RL)}function zg(e){let t=[...e].sort((r,i)=>r.relativePath.localeCompare(i.relativePath)||r.startLine-i.startLine||i.endLine-r.endLine),n=[];for(let r of t)n.some(i=>Vg(i,r))||n.push(r);return n}function Kg(e,t){let n=t.text.split(`
46
- `);return{symbol:t.relativePath,shortName:t.relativePath,relativePath:t.relativePath,startLine:0,endLine:Math.max(0,n.length-1),language:e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath)?.language??Kl(t.relativePath),source:t.text,freshness:t.freshness,...go(t.freshness)?{bindingClosure:di(e,t.relativePath,0,Math.max(0,n.length-1))}:{}}}function vL(e,t){return da(e).filter(n=>t.some(r=>zl(n,r))).length}function CL(e,t,n){let r=[];return Wg(r,e,t,n,0),r}function Wg(e,t,n,r,i){for(let o of n){if(r.some(a=>zl(o,a)))continue;let s=da(o.children).filter(a=>!r.some(c=>zl(a,c))).length;e.push({symbol:o.symbol,shortName:o.shortName,relativePath:t,startLine:o.startLine,endLine:o.endLine,signature:o.signature,depth:i,nestedDefinitions:s}),Wg(e,t,o.children,r,i+1)}}function da(e){return e.flatMap(t=>[t,...da(t.children)])}function xL(e){return da(e).length}function zl(e,t){return t.startLine<=e.startLine&&t.endLine>=e.endLine}function Vg(e,t){return e.relativePath===t.relativePath&&e.startLine<=t.startLine&&e.endLine>=t.endLine}function RL(e,t){return e.startLine-t.startLine||t.endLine-e.endLine||e.symbol.localeCompare(t.symbol)}function EL(e,t){return{selector:e,status:"matched",kind:"source",totalCandidates:1,results:[t],definitions:[],candidates:[],omittedCandidates:0,suggestions:[]}}function Gl(e,t,n){return{selector:t,status:"missing",kind:"source",totalCandidates:0,results:[],definitions:[],candidates:[],omittedCandidates:0,suggestions:Hs(e,t,5),reason:n}}function Yg(e,t){try{return Xs(e,t)}catch(n){if(n instanceof Op)return null;throw n}}function IL(e,t){if(!t.match)return[];let n=[t.match];for(let i of t.candidates){let o=U(e,i.relativePath).find(s=>s.symbol===i.symbol&&s.startLine===i.startLine);o&&n.push(o)}let r=new Set;return n.filter(i=>{let o=`${i.relativePath}:${i.startLine}:${i.endLine}:${i.symbol}`;return r.has(o)?!1:(r.add(o),!0)})}function Jg(e){return{symbol:e.symbol,shortName:T(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine}}function Xg(e){let t=e.match(/^(.+):(\d+)-(\d+)$/);if(!t)return null;let n=Number(t[2]),r=Number(t[3]);if(!Number.isSafeInteger(n)||n<1)throw new RangeError(`Source range start line must be a positive integer, got "${t[2]}".`);if(!Number.isSafeInteger(r)||r<n)throw new RangeError(`Source range end line must be an integer at or after ${n}, got "${t[3]}".`);return{filePath:t[1],startLine:n,endLine:r}}function fo(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=Xs(e,t.relativePath);if(!i)return null;let s=i.text.split(`
47
- `),a=t.endLine<=t.startLine?Kn(e,t.relativePath,t.startLine,Number.MAX_SAFE_INTEGER):null,c=a?.unitType?a.unitStartLine:t.startLine,l=a?.unitType?a.unitEndLine:t.endLine,u=Math.max(0,c-n),d=Math.min(s.length-1,l+n),m=s.slice(u,d+1).join(`
48
- `);return{symbol:t.symbol,shortName:T(t.symbol),relativePath:t.relativePath,startLine:u,endLine:d,language:r?.language??Kl(t.relativePath),source:m,freshness:i.freshness,...go(i.freshness)?{bindingClosure:di(e,t.relativePath,u,d)}:{}}}function Qg(e,t,n,r,i){let o=Xs(e,t);if(!o)return null;let s=e.get("SELECT language FROM documents WHERE relative_path = ?",o.relativePath),c=o.text.split(`
49
- `);if(n>c.length)return null;let l=Math.max(0,n-1-i),u=Math.min(c.length-1,r-1+i),d=c.slice(l,u+1).join(`
50
- `);return{symbol:`${o.relativePath}:${n}-${r}`,shortName:`${o.relativePath}:${n}-${r}`,relativePath:o.relativePath,startLine:l,endLine:u,language:s?.language??Kl(o.relativePath),source:d,freshness:o.freshness,...go(o.freshness)?{bindingClosure:di(e,o.relativePath,l,u)}:{}}}function go(e){return!!(e&&e.semantic.state!=="stale"&&e.semantic.basis!=="no-compiler-document")}function Kl(e){switch(jg(e).toLowerCase()){case".ts":case".tsx":case".mts":case".cts":return"typescript";case".js":case".jsx":case".mjs":case".cjs":return"javascript";case".py":case".pyi":return"python";case".rs":return"rust";case".go":return"go";case".java":return"java";case".kt":case".kts":return"kotlin";case".scala":return"scala";case".rb":return"ruby";case".php":return"php";case".cs":return"csharp";case".vb":return"vb";case".dart":return"dart";case".c":case".h":return"c";case".cc":case".cpp":case".cxx":case".hpp":case".hh":case".hxx":return"cpp";case".vue":return"vue";default:return null}}function ma(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath)??[];r.push(n),t.set(n.relativePath,r)}return t}function Zg(e){let t=new Map,n=LL(e),r=new Map;return i=>{let o=wL(i),s=r.get(o);if(s!==void 0)return s;if(!n.has(i.file))return r.set(o,i.symbol),i.symbol;let a=t.get(i.file);a||(a=PL(U(e,i.file)),t.set(i.file,a));let c=DL(a,i);return r.set(o,c),c}}function wL(e){return`${e.file}\0${e.symbol}\0${e.line}`}function LL(e){return new Set(e.all("SELECT relative_path FROM documents").map(t=>t.relative_path))}function PL(e){let t=new Map,n=new Map;for(let r of e){let i=t.get(r.leaf);i?i.push(r):t.set(r.leaf,[r]);let o=n.get(r.startLine);o?o.push(r):n.set(r.startLine,[r])}return{definitions:e,byLeaf:t,byStartLine:n}}function DL(e,t){if(e.definitions.length===0)return t.symbol;let n=kL(t.symbol),r=ML(e.byLeaf,n),i=TL(r,t.line);if(i)return i.symbol;let o=e.byStartLine.get(t.line)??[];return o.length===1?o[0].symbol:t.symbol}function ML(e,t){let n=[],r=new Set;for(let i of t)for(let o of e.get(i)??[])r.has(o.symbolId)||(r.add(o.symbolId),n.push(o));return n}function TL(e,t){let n=null;for(let r of e)if(!(r.startLine>t||r.endLine<t)){if(r.startLine===t)return r;(!n||r.endLine-r.startLine<n.endLine-n.startLine)&&(n=r)}return n}function kL(e){let t=new Set([e]),r=e.split(/::|\.|#/).filter(Boolean).at(-1);return r&&t.add(r),t}function eh(e,t){let r=ae(e,t).map(i=>FL(t,i));return{usage:r,positions:NL(e,t,r)}}function th(e,t){return{importUsage(n){let r=e.importUsageFacts(n);if(!t||r.positions.length===0)return r.usage;let i=t.importDefinitionsForFile(n,r.positions);return i.available?AL(r.usage,i.sourcePaths):r.usage}}}function AL(e,t){return e.map((n,r)=>{let i=t.get(String(r));return i?{...n,sourcePath:i}:n})}function FL(e,t){let n=t.isTypeOnly===!0,r=t.kind==="side-effect"||n||t.used;return{importer:e,sourcePath:t.sourcePath,importedName:t.importedName,localName:t.localName,kind:t.kind,isTypeOnly:n,isUsed:r,isTypeUsed:n,isValueUsed:t.kind==="side-effect"||!n&&t.used,references:[]}}function NL(e,t,n){let r=J(e,t);if(!r)return[];let i=_L(r.rootNode),o=new Map;for(let a of i){let c=o.get(Vl(a.importedName,a.localName));c?c.push(a.position):o.set(Vl(a.importedName,a.localName),[a.position])}let s=[];return n.forEach((a,c)=>{let l=o.get(Vl(a.importedName,a.localName??a.importedName))?.shift();l&&s.push({...l,id:String(c),file:t})}),s}function _L(e){let t=[];for(let n of e.descendantsOfType("use_declaration")){let r=n.namedChildren.find(i=>i.type!=="visibility_modifier");r&&t.push(...pa(r,""))}return t.filter(n=>n.importedName!=="*")}function pa(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":return[{importedName:e.text,localName:e.text,position:Wl(e,e.text)}];case"scoped_identifier":{let n=e.text.split("::").pop()??e.text;return[{importedName:n,localName:n,position:Wl(e,n)}]}case"scoped_use_list":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=pf(t,n.text);return r.namedChildren.flatMap(o=>pa(o,i))}case"use_list":return e.namedChildren.flatMap(n=>pa(n,t));case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);return!n||!r?[]:pa(n,t).map(i=>({...i,localName:r.text}))}case"use_wildcard":{let n=e.namedChild(0),r="*";return[{importedName:r,localName:r,position:Wl(n??e,r)}]}default:return[]}}function Wl(e,t){let n=Math.max(0,e.text.lastIndexOf(t));return{id:"",file:"",line:e.startPosition.row,column:e.startPosition.column+n+OL(t)}}function OL(e){return Math.max(0,Math.min(e.length-1,1))}function Vl(e,t){return`${e}\0${t}`}import{spawnSync as su}from"child_process";import{existsSync as au}from"fs";import{fileURLToPath as OP}from"url";function Vn(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function fa(e){let t=Af(kf,e),n=t.runnable;return n?{available:!0,dependencyAvailable:n,resolvedBinary:t.resolvedBinary??void 0,note:"rust-analyzer semantic reference queries are enabled."}:{available:!1,dependencyAvailable:n,resolvedBinary:t.resolvedBinary??void 0,reason:"rust-analyzer is not runnable; Rust semantic checks will use SCIP/source evidence only."}}import{existsSync as xP,mkdtempSync as Eh,rmSync as eu}from"fs";import{tmpdir as ru}from"os";import{join as tu}from"path";import{fileURLToPath as xo,pathToFileURL as RP}from"url";import{SHARE_ENV as EP,Worker as IP}from"worker_threads";function Yn(e,t,n=new Set){let r=new Map;for(let i of e)n.has(i.symbolId)||r.set(i.symbolId,t.get(i.symbolId)??[]);return r}function Ir(e,t,n){let r=Vn(process.env.SCIP_RUST_SEMANTIC_BATCH_TIMEOUT_MS)??0;if(r>0)return r;let i=Math.max(1,Math.ceil(e/Math.max(1,n)));return Math.max(12e4,3e4+i*t)}import{spawn as nP}from"child_process";import{createHash as rP,randomUUID as iP}from"crypto";import{existsSync as hh,realpathSync as oP,rmSync as sP}from"fs";import{tmpdir as aP}from"os";import{resolve as hi}from"path";import{execFileSync as zL}from"child_process";import{existsSync as BL}from"fs";import{deserializeSCIP as $L,SymbolRole as jL}from"@c4312/scip";import{realpathSync as f3}from"fs";import{basename as h3,dirname as y3,join as b3,relative as S3,sep as v3}from"path";import{fileURLToPath as x3,pathToFileURL as R3}from"url";function ga(e){let t=new Map;for(let n of e)t.set(`${n.file}\0${n.line}\0${n.column}`,n);return[...t.values()].sort((n,r)=>{let i=n.file.localeCompare(r.file);return i!==0?i:n.line!==r.line?n.line-r.line:n.column-r.column})}var Yl=new WeakMap,HL="SCIP_RUST_SCIP_OCCURRENCE_REFERENCE_MODE";function nh(e,t){let n=new Map,r=ha(),i=t.filter(s=>oh(s,r));if(i.length===0)return n;let o=sh(e);if(!o)return n;for(let s of i){let a=ih(o,s);a!==null&&n.set(s.symbolId,a)}return n}function rh(e,t){if(!oh(t,ha()))return null;let n=sh(e);return n?ih(n,t):null}function ih(e,t){return e.referencesBySymbol.get(t.symbol)??[]}function oh(e,t="safe"){if(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||je(e.symbol)||/impl#\[[^\]]+\]\[Default\]default\(\)\.$/.test(e.symbol))return!1;if(t==="all")return!0;let n=wt(e.symbol);if(n==="method")return!0;if(n!=="term")return!1;let r=Bn(e.symbol);return"kind"in r?!1:!UL(r)}function UL(e){for(let t=0;t<e.descriptors.length-1;t+=1)if(e.descriptors[t]?.suffix==="type")return!0;return!1}function sh(e){if(Yl.has(e))return Yl.get(e)??null;let t=qL(e);return Yl.set(e,t),t}function qL(e){if(!e.generation.indexPath||!BL(e.generation.indexPath))return null;try{let t=$L(Qr(e.generation.indexPath,{inputKind:"SCIP occurrence-reference index",maxBytes:Xr})),n=new Map;for(let r of t.documents??[]){let i=r.relativePath;if(!(!i||e.isIgnored(i)))for(let o of r.occurrences??[]){if(!o.symbol||(o.symbolRoles&jL.Definition)!==0)continue;let s=GL(i,o.range);if(!s)continue;let a=n.get(o.symbol)??[];a.push(s),n.set(o.symbol,a)}}for(let[r,i]of n)n.set(r,ga(i));return{referencesBySymbol:n}}catch{return null}}function GL(e,t){if(t.length<3)return null;let n=t[0],r=t[1];return!Number.isInteger(n)||!Number.isInteger(r)?null:{file:e,line:n,column:r}}function ha(){return process.env[HL]==="all"?"all":"safe"}var ah=new Map;function Jl(e){let n=fa(e).resolvedBinary??null;return{engine:"rust-analyzer",resolvedBinary:n,version:n?KL(e,n):"unavailable"}}function wr(e){return{...Jl(e),scipOccurrenceReferenceMode:ha()}}function KL(e,t){let n=`${e}\0${t}`,r=ah.get(n);if(r)return r;let i;try{i=zL(t,["--version"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim()}catch{i="unknown"}return ah.set(n,i),i}import{createHash as WL}from"crypto";var VL=new Set(["Cargo.lock","Cargo.toml","rust-project.json","rust-toolchain","rust-toolchain.toml"]);function ch(e){let t=Vp(e,{includePath:YL});return WL("sha256").update(JSON.stringify(t)).digest("hex")}function YL(e){let t=e.replaceAll("\\","/"),n=t.split("/").at(-1)??t;return t.endsWith(".rs")||VL.has(n)?!0:t===".cargo/config"||t===".cargo/config.toml"||t.endsWith("/.cargo/config")||t.endsWith("/.cargo/config.toml")}import{createHash as JL}from"crypto";import{resolve as XL}from"path";var gi=3;function Ql(e){return JL("sha256").update(vr({kind:"scip-query-durable-rust-mailbox",protocolVersion:gi,sessionDir:XL(e)})).digest("hex")}function dh(e,t){return Q(e)?e.protocolVersion!==gi?uh(e.protocolVersion===void 0?"helper wrote a prior uncorrelated response protocol":`helper wrote unsupported response protocol ${String(e.protocolVersion)}`):e.mailboxVersion!==hn||e.id!==t.requestId||e.operationKey!==t.operationKey||e.sessionIdentity!==t.sessionIdentity||e.deadlineAtMs!==t.deadlineAtMs?uh("helper wrote an incompatible response identity"):typeof e.completedAtMs!="number"||!Number.isFinite(e.completedAtMs)||e.completedAtMs>t.deadlineAtMs||t.nowMs>t.deadlineAtMs?{ok:!1,code:"expired-request",error:"helper response arrived after the durable request deadline"}:e.ok===!1?typeof e.error!="string"||!tP(e.errorCode)?Xl("helper wrote an invalid rejection response"):{ok:!1,code:e.errorCode,error:e.error}:e.ok!==!0||e.session!=="created"&&e.session!=="reused"&&e.session!=="invalidated"||!QL(e.response,t.requestKind)?Xl("helper wrote an invalid success response"):{ok:!0,session:e.session,response:e.response}:Xl("helper wrote an invalid response object")}function QL(e,t){return!Q(e)||typeof e.available!="boolean"||e.available===!1&&(typeof e.reason!="string"||e.reason.length===0)||e.available===!0&&e.reason!==void 0?!1:t==="import-definitions"?Array.isArray(e.sourcePaths)&&e.sourcePaths.every(n=>Array.isArray(n)&&n.length===2&&typeof n[0]=="string"&&(n[1]===null||typeof n[1]=="string")):lh(e.references,ZL)&&(e.incompleteReferenceSymbolIds===void 0||Array.isArray(e.incompleteReferenceSymbolIds)&&e.incompleteReferenceSymbolIds.every(n=>Number.isSafeInteger(n)))&&(e.callees===void 0||lh(e.callees,eP))&&(e.signatures===void 0||Array.isArray(e.signatures)&&e.signatures.every(n=>Array.isArray(n)&&n.length===2&&Number.isSafeInteger(n[0])&&(n[1]===null||typeof n[1]=="string")))}function lh(e,t){return Array.isArray(e)&&e.every(n=>Array.isArray(n)&&n.length===2&&Number.isSafeInteger(n[0])&&Array.isArray(n[1])&&n[1].every(t))}function ZL(e){return Q(e)&&typeof e.file=="string"&&xt(e.line)&&xt(e.column)}function eP(e){return Q(e)&&typeof e.symbol=="string"&&typeof e.file=="string"&&xt(e.line)&&(e.callsiteLine===void 0||xt(e.callsiteLine))}function tP(e){return e==="unsupported-protocol"||e==="malformed-request"||e==="expired-request"||e==="handler-error"}function Xl(e){return{ok:!1,code:"malformed-response",error:e}}function uh(e){return{ok:!1,code:"incompatible-response",error:e}}var cP=5e3,yh=10,lP=3e4;function mh(e,t,n,r=Ch){let i=r.engineIdentity(e),o={protocolVersion:gi,projectRoot:r.canonicalProjectRoot(e),projectFingerprint:r.projectFingerprint(e),engine:{engine:i.engine,resolvedBinary:i.resolvedBinary,version:i.version},workerFingerprint:r.fileFingerprint(t),environment:bh(r.environment())};return{key:xh(vr(o)),...o}}function ho(e,t,n,r){if(e.protocolVersion!==gi||!n(e.pid))return!1;if(!e.processIdentity)return!0;let i=r?.(e.pid);return i!=null&&Gs(e.processIdentity,i)}function Zl(e,t,n){let r;try{r=dl(t,{maxBytes:dn,inputKind:"Rust semantic engine artifact"})}catch{r="missing"}let i=xh(vr({projectRoot:hi(e),serverPath:hi(t),serverFingerprint:r})).slice(0,20);return hi(n,`scip-query-rust-session-${i}`)}function ph(e){let t=e===void 0?Number.NaN:Number(e);return Number.isInteger(t)&&t>=0?t:0}function bh(e){return Object.fromEntries(Object.entries(e).filter(([t])=>vh(t)).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,n??null]))}function Sh(e,t){let n=t.runtime??gP,r=t.identityRuntime??Ch,i=Zl(e,t.serverPath,t.tempRoot??aP()),o=!1,s=(a,c)=>{if(o)throw new Error("Durable Rust semantic session was already disposed.");return dP(i,t.serverPath,t.semanticWorkerPath,a,c,n,t.mailboxLimits)};return{requestSemantic(a,c){let l=mh(e,t.semanticWorkerPath,a,r),{readinessDeadlineMs:u,...d}=a;return s({kind:"semantic",identityKey:l.key,workerEnvironment:gh(),request:{...d,referenceRetryTimeoutMs:uP(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,a.referenceRetryTimeoutMs),settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:ph(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},requestImportDefinitions(a,c){let l=mh(e,t.semanticWorkerPath,a,r),{readinessDeadlineMs:u,...d}=a;return s({kind:"import-definitions",identityKey:l.key,workerEnvironment:gh(),request:{...d,settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:ph(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},shutdown(){o=!0}}}function uP(e,t){return t!==void 0?t:e===void 0?lP:void 0}function dP(e,t,n,r,i,o,s={}){let a=o.now(),c=a+i,l=(o.monotonicNow??Lt)(),u=l+i,d=Hn("rust-semantic-v3",r),m=xr(d),p=zs(e),f=Ql(e),g=Ks(p,{mailboxVersion:hn,protocolVersion:gi,id:m,operationKey:d,clientId:o.randomId(),enqueuedAtMs:a,deadlineAtMs:c,sessionIdentity:f,request:r},{nowMs:a,limits:s});for(fh(e,t,n,u,o);(o.monotonicNow??Lt)()<=u;){if(hh(g.responsePath)){let b=mP(vt(g.responsePath,{maxBytes:s.maxItemBytes??dn,inputKind:"durable Rust semantic mailbox response"}),{requestId:m,operationKey:d,sessionIdentity:f,deadlineAtMs:g.authoritativeDeadlineAtMs,requestKind:r.kind,nowMs:o.now()});if(!b.ok)throw new Error(b.error);return be()&&Ts({type:"span",name:"rust.semantic.durable-session.request",durationMs:(o.monotonicNow??Lt)()-l,ok:!0,session:b.session,kind:r.kind}),b.response}let h=yo(e);(!h||!ho(h,o.now(),o.isProcessAlive,o.readProcessIdentity))&&fh(e,t,n,u,o),o.sleep(yh)}throw new Error(`Durable Rust semantic session timed out after ${(i/1e3).toFixed(0)}s.`)}function fh(e,t,n,r,i){let o=yo(e);if(o&&ho(o,i.now(),i.isProcessAlive,i.readProcessIdentity))return;sP(hi(e,"server.json"),{force:!0}),i.spawnServer(t,e,n);let s=i.monotonicNow??Lt,a=Math.min(r,s()+cP);for(;s()<=a;){let c=yo(e);if(c&&ho(c,i.now(),i.isProcessAlive,i.readProcessIdentity))return;i.sleep(yh)}throw new Error("Durable Rust semantic session helper did not become ready within 5s.")}function yo(e){try{let t=JSON.parse(vt(hi(e,"server.json"),{maxBytes:Ls,inputKind:"durable Rust session state"}));if(typeof t.protocolVersion!="number"||t.sessionIdentity!==void 0&&(typeof t.sessionIdentity!="string"||t.sessionIdentity!==Ql(e))||typeof t.pid!="number"||typeof t.heartbeatAtMs!="number"||t.busyUntilMs!==void 0&&typeof t.busyUntilMs!="number"||t.mailbox!==void 0&&!pP(t.mailbox))return null;let n=t.processIdentity===void 0?null:qs(t.processIdentity);return t.processIdentity!==void 0&&(!n||n.pid!==t.pid)?null:{protocolVersion:t.protocolVersion,...t.sessionIdentity===void 0?{}:{sessionIdentity:t.sessionIdentity},pid:t.pid,...n?{processIdentity:n}:{},heartbeatAtMs:t.heartbeatAtMs,...t.busyUntilMs===void 0?{}:{busyUntilMs:t.busyUntilMs},...t.mailbox===void 0?{}:{mailbox:t.mailbox}}}catch{return null}}function mP(e,t){try{return dh(JSON.parse(e),t)}catch(n){return{ok:!1,code:"malformed-response",error:`helper wrote malformed JSON: ${n instanceof Error?n.message:String(n)}`}}}function pP(e){if(!e||typeof e!="object")return!1;let t=e;return xt(t.pending)&&xt(t.inflight)&&xt(t.responses)&&xt(t.deadLetters)&&xt(t.invalid)&&xt(t.totalItems)&&typeof t.totalBytes=="number"&&Number.isFinite(t.totalBytes)&&t.totalBytes>=0&&(t.oldestPendingAt===void 0||Number.isFinite(Date.parse(t.oldestPendingAt)))}function gh(){return Object.fromEntries(Object.entries(process.env).filter(([e])=>fP(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t??null]))}function vh(e){return e==="HOME"||e==="PATH"||e.startsWith("CARGO_")||e.startsWith("RA_")||e.startsWith("RUST")}function fP(e){return vh(e)||e.startsWith("SCIP_RUST_")||e==="SCIP_QUERY_PROFILE"||e==="SCIP_QUERY_PROFILE_CACHE_STATE"||e==="SCIP_QUERY_PROFILE_COMMAND"||e==="SCIP_QUERY_PROFILE_OUT"||e==="SCIP_QUERY_PROFILE_RUN_ID"||e==="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY"||e==="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY_KIND"||e==="SCIP_QUERY_PROFILE_MIN_MS"}var Ch={canonicalProjectRoot(e){try{return oP(e)}catch{return hi(e)}},projectFingerprint(e){return ch(e)},engineIdentity:Jl,fileFingerprint(e){return dl(e,{maxBytes:dn,inputKind:"Rust semantic engine artifact"})},environment(){return bh(process.env)}},gP={now:Date.now,monotonicNow:Lt,randomId:iP,isProcessAlive:ci,readProcessIdentity:li,spawnServer(e,t,n){if(!hh(e))throw new Error(`Durable Rust semantic session helper was not found at ${e}. Run npm run build first.`);nP(process.execPath,[e,t,n],{detached:!0,stdio:"ignore"}).unref()},sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)}};function xh(e){return rP("sha256").update(e).digest("hex")}import{randomUUID as uQ}from"crypto";import{readdirSync as hP,rmSync as mQ,writeFileSync as pQ}from"fs";import{join as yP}from"path";var bP="rust-analyzer-owner-",SP=".json",vP=16*1024;async function Rh(e,t){if(!e)return[];let n;try{n=hP(e)}catch{return[]}let r=n.filter(s=>s.startsWith(bP)&&s.endsWith(SP)).map(s=>yP(e,s)),i=[],o=[];for(let s of r){let a=CP(s);a?o.push(a):i.push({reaped:!1,reason:"identity-unavailable",detail:`Rust analyzer ownership record ${s} could not be validated.`})}return i.push(...await Promise.all(o.map(s=>Of(s,t)))),i}function CP(e){try{let t=vt(e,{maxBytes:vP,inputKind:"rust-analyzer process ownership record"}),n=JSON.parse(t),r=qs(n.rootIdentity);return n.version!==1||!r||typeof n.ownsProcessGroup!="boolean"?null:{rootPid:r.pid,rootIdentity:r,ownsProcessGroup:n.ownsProcessGroup,knownMembers:new Map([[r.pid,r]])}}catch{return null}}var Ih=15e3,wh=8,Ph=5e3,wP=64,LP=96,iu=class{constructor(t,n,r={}){this.projectRoot=t;this.status=n;this.opts=r;this.requester=r.requester??MP(t,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION)}projectRoot;status;opts;requester;referencesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:So(n),references:vo(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!0});return{...bo(r),resolvedBinary:n.resolvedBinary,references:Yn(t,new Map(r.references),new Set(r.incompleteReferenceSymbolIds??[]))}}catch(r){return this.opts.fallbackReferenceResolver?.referencesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),references:vo(t)}}}calleesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:So(n),callees:Co(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!0});return{...bo(r),resolvedBinary:n.resolvedBinary,callees:nu(t,new Map(r.callees??[]))}}catch(r){return this.opts.fallbackCalleeResolver?.calleesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),callees:Co(t)}}}referencesAndCalleesForDefinitions(t,n){let r=this.status(this.projectRoot);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:So(r),references:vo(t),callees:Co(n)};let i=[...t,...n];try{let o=this.requestSession(r.resolvedBinary,i,{includeReferences:t.length>0,includeCallees:n.length>0,referenceDefinitions:t,calleeDefinitions:n});return{...bo(o),resolvedBinary:r.resolvedBinary,references:Yn(t,new Map(o.references),new Set(o.incompleteReferenceSymbolIds??[])),callees:nu(n,new Map(o.callees??[]))}}catch(o){return this.fallbackReferencesAndCallees(r,t,n,o)}}signaturesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:So(n),signatures:Lh(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!1,includeSignatures:!0});return{...bo(r),resolvedBinary:n.resolvedBinary,signatures:NP(t,new Map(r.signatures??[]))}}catch(r){return this.opts.fallbackSignatureResolver?.signaturesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),signatures:Lh(t)}}}importDefinitionsForFile(t,n){let r=this.status(this.projectRoot);if(n.length===0)return r.available?{available:!0,resolvedBinary:r.resolvedBinary,sourcePaths:new Map}:{available:!1,reason:r.reason,resolvedBinary:r.resolvedBinary,sourcePaths:new Map};if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:So(r),sourcePaths:new Map(n.map(i=>[i.id,null]))};try{let i=this.requestImportDefinitions(r.resolvedBinary,t,n);return{...bo(i),resolvedBinary:r.resolvedBinary,sourcePaths:new Map(i.sourcePaths)}}catch(i){return{available:!1,resolvedBinary:r.resolvedBinary,reason:i instanceof Error?i.message:String(i),sourcePaths:new Map(n.map(o=>[o.id,null]))}}}dispose(){this.requester.shutdown()}requestSession(t,n,r){let i=ya(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Ih),o=ba(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),s=ya(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,wh),a=ba(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),c=r.referenceDefinitions?[...r.referenceDefinitions]:void 0,l=r.calleeDefinitions?[...r.calleeDefinitions]:void 0,u=r.signatureDefinitions?[...r.signatureDefinitions]:void 0,d=Ro(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,...r}),m={projectRoot:this.projectRoot,rustAnalyzerBinary:t,definitions:[...n],...c?{referenceDefinitions:c}:{},...l?{calleeDefinitions:l}:{},...u?{signatureDefinitions:u}:{},requestTimeoutMs:i,...r.includeReferences!==!1&&o>0?{referenceRetryTimeoutMs:o}:{},diagnosticsTimeoutMs:a,settleDelayMs:d,concurrency:s,includeReferences:r.includeReferences,includeCallees:r.includeCallees,includeSignatures:r.includeSignatures},p=_P(m);return N("rust.semantic.session.request",()=>this.requester.requestSemantic(m,Ir(p,ou(i,m.referenceRetryTimeoutMs),s)),()=>({definitions:n.length,operationDefinitions:p,referenceDefinitions:m.referenceDefinitions?.length,calleeDefinitions:m.calleeDefinitions?.length,signatureDefinitions:m.signatureDefinitions?.length,references:m.includeReferences!==!1,callees:m.includeCallees===!0,signatures:m.includeSignatures===!0,referenceRetryTimeoutMs:m.referenceRetryTimeoutMs}))}fallbackReferencesAndCallees(t,n,r,i){let o=n.length===0?{available:!0,resolvedBinary:t.resolvedBinary,references:vo(n)}:this.opts.fallbackReferenceResolver?.referencesForDefinitions(n),s=r.length===0?{available:!0,resolvedBinary:t.resolvedBinary,callees:Co(r)}:this.opts.fallbackCalleeResolver?.calleesForDefinitions(r);if(o&&s){let a={resolvedBinary:o.resolvedBinary??s.resolvedBinary??t.resolvedBinary,references:Yn(n,o.references),callees:nu(r,s.callees)};return o.available&&s.available?{available:!0,...a}:{available:!1,reason:(o.available?void 0:o.reason)??(s.available?void 0:s.reason)??"Rust semantic fallback was unavailable.",...a}}return{available:!1,resolvedBinary:t.resolvedBinary,reason:i instanceof Error?i.message:String(i),references:vo(n),callees:Co(r)}}requestImportDefinitions(t,n,r){let i=ya(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Ih),o=ya(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,wh),s=ba(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),a=ba(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,Ph),c={projectRoot:this.projectRoot,rustAnalyzerBinary:t,file:n,positions:[...r],requestTimeoutMs:i,diagnosticsTimeoutMs:s,settleDelayMs:a,concurrency:o};return N("rust.semantic.import-definitions.session.request",()=>this.requester.requestImportDefinitions(c,Ir(r.length,i,o)),()=>({file:n,positions:r.length}))}};function bo(e){return e.available?{available:!0}:{available:!1,reason:e.reason}}function So(e){return e.available?"rust-analyzer binary path is unavailable.":e.reason}function Dh(e,t,n={}){return new iu(e,t,n)}function Ro(e,t){let n=Ah(e);if(n!==null)return n;let r=t.includeReferences!==!1;return r&&t.includeCallees!==!0&&t.includeSignatures!==!0&&t.definitionCount<=wP||r&&t.includeCallees===!0&&t.includeSignatures!==!0&&t.definitionCount<=LP?0:Ph}function Mh(e){let t=e?.trim().toLowerCase(),n=t==="0"||t==="false"||t==="off"||t==="worker",r=t==="1"||t==="true"||t==="on"||t==="durable",i=t===void 0||t==="";return{transport:n||!i&&!r?"worker":"durable",source:i?"default":"environment",fallback:"worker",valid:i||n||r,optOut:"SCIP_RUST_SEMANTIC_DURABLE_SESSION=0"}}function PP(e){return Mh(e).transport}function kQ(e,t){let n=Mh(t);if(n.transport==="worker")return{...n,state:"per-command"};let r=xo(kh()),i=Zl(e,r,ru()),o=yo(i);return o?{...n,state:ho(o,Date.now(),ci,li)?"live":"stale",pid:o.pid,heartbeatAtMs:o.heartbeatAtMs,...o.busyUntilMs===void 0?{}:{busyUntilMs:o.busyUntilMs}}:{...n,state:"stopped"}}function DP(e,t){let n=null,r=!1,i=!1,o=!1,s=()=>n??=t(),a=()=>{i||(e.shutdown(),i=!0)},c=(u,d,m)=>{let p=FP(u);r=!0;try{a()}catch{}be()&&Ts({type:"span",name:"rust.semantic.durable-session.request",durationMs:m,ok:!1,kind:d,session:"worker-fallback",reason:p})},l=(u,d,m)=>{if(o)throw new Error("Rust semantic failover session was already disposed.");if(r)return m(s());let p=performance.now();try{return d(e)}catch(f){c(f,u,performance.now()-p)}return m(s())};return{requestSemantic(u,d){return l("semantic",m=>m.requestSemantic(u,d),m=>m.requestSemantic(u,d))},requestImportDefinitions(u,d){return l("import-definitions",m=>m.requestImportDefinitions(u,d),m=>m.requestImportDefinitions(u,d))},shutdown(){if(o)return;o=!0;let u=[];try{a()}catch(d){u.push(d)}try{n?.shutdown()}catch(d){u.push(d)}if(u.length>0)throw u[0]}}}function MP(e,t,n={worker:()=>TP(),durable:()=>Sh(e,{serverPath:xo(kh()),semanticWorkerPath:xo(Th())})}){return PP(t)==="durable"?DP(n.durable(),n.worker):n.worker()}function TP(e={}){let t=null,n=null,r=1,i=!1,o=null,s=null,a=d=>{d&&eu(d,{recursive:!0,force:!0})},c=()=>{if(o)return;let d=t,m=n;t=null,n=null;let p=d?d.terminate():Promise.resolve(0);o=Promise.allSettled([p,Rh(m,{gracefulMs:1e3,forceMs:1e3})]).then(([f,g])=>{let b=(g.status==="fulfilled"?g.value:[{reaped:!1,detail:String(g.reason)}]).filter(S=>!S.reaped);if(f.status==="rejected"||b.length>0){s=new Error(`Rust semantic worker cleanup did not complete; ownership evidence remains at ${m??"unknown"}.`);return}a(m)}).finally(()=>{o=null})},l=()=>{if(t)return t;if(o)throw new Error("The previous Rust semantic session worker is still terminating; retry the request.");if(s)throw s;let d=e.semanticWorkerPath?RP(e.semanticWorkerPath):Th();if(!xP(xo(d)))throw new Error(`Rust semantic session worker was not found at ${xo(d)}. Run npm run build before using built semantic Rust queries.`);return n=Eh(tu(ru(),"scip-query-rust-session-")),t=new IP(d,e.shareEnvironment?{env:EP}:void 0),t.unref(),t},u=()=>{let d=n??Eh(tu(ru(),"scip-query-rust-session-"));return n=d,tu(d,`${r++}.json`)};return{requestSemantic(d,m){if(i)throw new Error("Rust semantic session was already disposed.");let p=l(),f=u(),g=new SharedArrayBuffer(4),h=new Int32Array(g);if(p.postMessage({kind:"semantic",request:d,responsePath:f,sharedBuffer:g}),Atomics.wait(h,0,0,m)==="timed-out")throw c(),new Error(`Rust semantic session worker timed out after ${(m/1e3).toFixed(0)}s`);try{let S=kP(vt(f,{maxBytes:dn,inputKind:"Rust semantic worker response"}));if(!S.ok)throw new Error(S.error);return S.response}finally{eu(f,{force:!0})}},requestImportDefinitions(d,m){if(i)throw new Error("Rust semantic session was already disposed.");let p=l(),f=u(),g=new SharedArrayBuffer(4),h=new Int32Array(g);if(p.postMessage({kind:"import-definitions",request:d,responsePath:f,sharedBuffer:g}),Atomics.wait(h,0,0,m)==="timed-out")throw c(),new Error(`Rust semantic import-definition session worker timed out after ${(m/1e3).toFixed(0)}s`);try{let S=AP(vt(f,{maxBytes:dn,inputKind:"Rust import-definition worker response"}));if(!S.ok)throw new Error(S.error);return S.response}finally{eu(f,{force:!0})}},shutdown(){if(i)return;if(i=!0,!t){a(n),n=null;return}let d=u(),m=new SharedArrayBuffer(4),p=new Int32Array(m);t.postMessage({kind:"shutdown",responsePath:d,sharedBuffer:m}),Atomics.wait(p,0,0,5e3),c()}}}function kP(e){let t=JSON.parse(e);if(!t||typeof t!="object")return{ok:!1,error:"Rust semantic session worker wrote a non-object response."};let n=t;return n.ok===!0&&"response"in n?{ok:!0,response:n.response}:{ok:!1,error:typeof t.error=="string"?t.error:"Rust semantic session worker failed."}}function AP(e){let t=JSON.parse(e);if(!t||typeof t!="object")return{ok:!1,error:"Rust semantic session worker wrote a non-object response."};let n=t;return n.ok===!0&&"response"in n?{ok:!0,response:n.response}:{ok:!1,error:typeof t.error=="string"?t.error:"Rust semantic session worker failed."}}function FP(e){let t=e instanceof Error?`${e.name} ${e.message}`.toLowerCase():String(e).toLowerCase();return t.includes("readiness")?"readiness":t.includes("timeout")||t.includes("timed out")?"timeout":t.includes("helper")?"helper":"request"}function vo(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Co(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Lh(e){return new Map(e.map(t=>[t.symbolId,null]))}function nu(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??[]]))}function NP(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function _P(e){let t=0;return e.includeReferences!==!1&&(t+=(e.referenceDefinitions??e.definitions).length),e.includeCallees===!0&&(t+=(e.calleeDefinitions??e.definitions).length),e.includeSignatures===!0&&(t+=(e.signatureDefinitions??e.definitions).length),Math.max(1,t)}function ou(e,t){return t&&t>0?Math.max(e,t):e}function Th(){return new URL("./rust-semantic-session-worker.js",import.meta.url)}function kh(){return new URL("./rust-semantic-session-server.js",import.meta.url)}function ya(e,t){return Vn(e)??t}function ba(e,t){return Ah(e)??t}function Ah(e){if(!e)return null;let t=Number(e);return Number.isInteger(t)&&t>=0?t:null}var cu=15e3,lu=8;function Oh(e,t={}){let n=t.status??fa,r=jP(e,n),i=HP(e,n),o=UP(e,n),s=t.referenceResolver||t.calleeResolver||t.signatureResolver||!BP(t)?null:Dh(e,n,{fallbackReferenceResolver:r,fallbackCalleeResolver:i,fallbackSignatureResolver:o}),a=t.referenceResolver??s??r,c=t.calleeResolver??s??i,l=t.signatureResolver??s??o,u=t.importUsageResolver??th(t.sourceImportUsageResolver??$P(),t.importDefinitionResolver??s),d=t.calleeSymbolResolver,m=t.sourceZeroCalleeOracle,p=t.scipOccurrenceCalleeOracle,f=new Map,g=new Map,h=null,b=null,S=()=>(h??=n(e),h),y=()=>{let E=S();return E.dependencyAvailable?b??E:E},x=E=>{if(E.length===0)return new Map;let w=Io(E);try{let I=a.referencesForDefinitions(w),k=S();return b=Sa(k,I),I.available?new Map(I.references):Yn(w,I.references)}catch(I){let k=S();return b=Eo(k,I),Lr(w)}},v=E=>{if(E.length===0)return new Map;let w=Io(E),I=w.filter(Fh);if(I.length===0)return Pr(w);let k=new Map,D=_h(I,p),F=[];for(let L of I)g.has(L.symbolId)?k.set(L.symbolId,g.get(L.symbolId)??[]):D.has(L.symbolId)?k.set(L.symbolId,D.get(L.symbolId)??[]):Nh(L,m)?k.set(L.symbolId,[]):F.push(L);if(F.length===0)return yi(w,k,void 0);try{let L=c.calleesForDefinitions(F),A=S();b=Sa(A,L);let P=yi(F,L.callees,d);for(let[j,B]of P)k.set(j,B);return yi(w,k,void 0)}catch(L){let A=S();return b=Eo(A,L),Pr(w)}},C=(E,w)=>{let I=Io(E),k=Io(w),D=k.filter(Fh),F=new Map,L=_h(D,p),A=[];for(let P of D)L.has(P.symbolId)?F.set(P.symbolId,L.get(P.symbolId)??[]):Nh(P,m)?F.set(P.symbolId,[]):A.push(P);if(I.length===0&&A.length===0)return{references:Lr(I),callees:yi(k,F,void 0)};try{let P=s?s.referencesAndCalleesForDefinitions(I,A):KP(a,c,{referenceDefinitions:I,calleeDefinitions:A}),j=S();b=Sa(j,P);let B=P.available?new Map(P.references):Yn(I,P.references);for(let[G,O]of P.callees)F.set(G,O);let X=yi(k,F,d);for(let[G,O]of X)g.set(G,O);return{references:B,callees:X}}catch(P){let j=S();return b=Eo(j,P),{references:Lr(I),callees:Pr(k)}}},R=E=>{if(E.length===0)return new Map;let w=Io(E);try{let I=l.signaturesForDefinitions(w),k=S();return b=Sa(k,I),Bh(w,I.signatures)}catch(I){let k=S();return b=Eo(k,I),va(w)}};return{language:"rust",availability:y,dispose:()=>{s?.dispose()},importUsage:E=>{let w=f.get(E);if(w)return w;try{let I=u.importUsage(E);return f.set(E,I),I}catch(I){let k=S();return b=Eo(k,I),[]}},referencesFor:E=>x([E]).get(E.symbolId)??[],referencesForDefinitions:x,referencesAndCalleesForDefinitions:C,calleesFor:E=>v([E]).get(E.symbolId)??[],calleesForDefinitions:v,signatureFor:E=>R([E]).get(E.symbolId)??null}}function Sa(e,t){let n={dependencyAvailable:e.dependencyAvailable,resolvedBinary:t.resolvedBinary??e.resolvedBinary,...e.note?{note:e.note}:{}};return t.available?{available:!0,...n}:{available:!1,reason:t.reason,...n}}function Eo(e,t){return{available:!1,dependencyAvailable:e.dependencyAvailable,resolvedBinary:e.resolvedBinary,...e.note?{note:e.note}:{},reason:t instanceof Error?t.message:String(t)}}function BP(e){if(e.usePersistentSession!==void 0)return e.usePersistentSession;let t=process.env.SCIP_RUST_SEMANTIC_SESSION;return t!=="0"&&t!=="false"}function $P(){return{importUsageFacts:()=>({usage:[],positions:[]})}}function Io(e){return e.map(t=>{let n=t;return{...t,leaf:typeof n.leaf=="string"?n.leaf:z(t.symbol),parentTypeName:n.parentTypeName??null,isFunctionLike:typeof n.isFunctionLike=="boolean"?n.isFunctionLike:Se(t.symbol),isTypeLike:n.isTypeLike??!1,kind:n.kind??null,documentation:n.documentation??null,enclosingSymbol:n.enclosingSymbol??null}})}function Fh(e){return e.isFunctionLike}function Nh(e,t){if(!t)return!1;try{return t(e)}catch{return!1}}function _h(e,t){if(!t||e.length===0)return new Map;try{return t(e)}catch{return new Map}}function jP(e,t){return{referencesForDefinitions:n=>qP(e,t,n)}}function HP(e,t){return{calleesForDefinitions:n=>GP(e,t,n)}}function UP(e,t){return{signaturesForDefinitions:n=>zP(e,t,n)}}function qP(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:mu(r),references:Lr(n)};let i=uu();if(!au(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,references:Lr(n)};let o=bi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,cu),s=Ca(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),a=bi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,lu),c=Ca(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),l=Ro(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!0}),u={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,...s>0?{referenceRetryTimeoutMs:s}:{},diagnosticsTimeoutMs:c,settleDelayMs:l,concurrency:a},d=su(process.execPath,[i],{cwd:e,input:JSON.stringify(u),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Ir(n.length,ou(o,u.referenceRetryTimeoutMs),a)}),m=pu(d.stdout);if(m)return{...du(m),resolvedBinary:r.resolvedBinary,references:Yn(n,new Map(m.references),new Set(m.incompleteReferenceSymbolIds??[]))};let p=d.error instanceof Error?d.error.message:d.stderr.trim()||`Rust semantic worker exited with status ${d.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:p,references:Lr(n)}}function GP(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:mu(r),callees:Pr(n)};let i=uu();if(!au(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,callees:Pr(n)};let o=bi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,cu),s=bi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,lu),a=Ca(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=Ro(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!0}),l={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:c,concurrency:s,includeReferences:!1,includeCallees:!0},u=su(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Ir(n.length,o,s)}),d=pu(u.stdout);if(d)return{...du(d),resolvedBinary:r.resolvedBinary,callees:yi(n,new Map(d.callees??[]),void 0)};let m=u.error instanceof Error?u.error.message:u.stderr.trim()||`Rust semantic worker exited with status ${u.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:m,callees:Pr(n)}}function zP(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:mu(r),signatures:va(n)};let i=uu();if(!au(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,signatures:va(n)};let o=bi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,cu),s=bi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,lu),a=Ca(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=Ro(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!1,includeSignatures:!0}),l={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:c,concurrency:s,includeReferences:!1,includeCallees:!1,includeSignatures:!0},u=su(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Ir(n.length,o,s)}),d=pu(u.stdout);if(d)return{...du(d),resolvedBinary:r.resolvedBinary,signatures:Bh(n,new Map(d.signatures??[]))};let m=u.error instanceof Error?u.error.message:u.stderr.trim()||`Rust semantic worker exited with status ${u.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:m,signatures:va(n)}}function KP(e,t,n){let r=n.referenceDefinitions.length>0?e.referencesForDefinitions(n.referenceDefinitions):{available:!0,references:Lr(n.referenceDefinitions)},i=n.calleeDefinitions.length>0?t.calleesForDefinitions(n.calleeDefinitions):{available:!0,callees:Pr(n.calleeDefinitions)},o={resolvedBinary:r.resolvedBinary??i.resolvedBinary,references:r.references,callees:i.callees};return r.available&&i.available?{available:!0,...o}:{available:!1,reason:(r.available?void 0:r.reason)??(i.available?void 0:i.reason)??"Rust semantic resolution was unavailable.",...o}}function Lr(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Pr(e){return new Map(e.map(t=>[t.symbolId,[]]))}function va(e){return new Map(e.map(t=>[t.symbolId,null]))}function yi(e,t,n){let r=0,i=0;return N("rust.semantic.callees.complete-map",()=>{let o=new Map;for(let s of e){let a=t.get(s.symbolId)??[];a.length>0&&(r+=1),i+=a.length,o.set(s.symbolId,a.map(c=>({...c,symbol:n?n(c):c.symbol})))}return o},()=>({definitions:e.length,rows:r,callees:i,resolveSymbols:!!n}))}function Bh(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function uu(){return OP(new URL("./rust-semantic-worker.js",import.meta.url))}function du(e){return e.available?{available:!0}:{available:!1,reason:e.reason}}function mu(e){return e.available?"rust-analyzer binary path is unavailable.":e.reason}function pu(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;if(typeof n.available!="boolean"||!Array.isArray(n.references)||n.available===!1&&typeof n.reason!="string"||n.available===!0&&n.reason!==void 0)return null;let r={references:n.references,incompleteReferenceSymbolIds:Array.isArray(n.incompleteReferenceSymbolIds)?n.incompleteReferenceSymbolIds.filter(i=>typeof i=="number"):void 0,callees:Array.isArray(n.callees)?n.callees:void 0,signatures:Array.isArray(n.signatures)?n.signatures:void 0};return n.available===!0?{available:!0,...r}:{available:!1,reason:String(n.reason),...r}}catch{return null}}function bi(e,t){return Vn(e)??t}function Ca(e,t){if(!e)return t;let n=Number(e);return Number.isInteger(n)&&n>=0?n:t}import{existsSync as WP}from"fs";import{deserializeSCIP as VP,SymbolRole as YP}from"@c4312/scip";var fu=new WeakMap;function jh(e,t){let n=t.filter(JP);if(n.length===0)return new Map;let r=!1,i=0,o=0;return N("rust.scip-occurrence.callees",()=>{let s=ZP(e);if(r=!!s,!s)return new Map;let a=new Map;for(let c of n){let l=XP(e,s,c);l!==null&&(a.set(c.symbolId,l),i+=1,o+=l.length)}return a},()=>({definitions:t.length,candidates:n.length,indexAvailable:r,resolvedDefinitions:i,resolvedCallees:o}))}function JP(e){return!(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||!e.isFunctionLike||e.leaf==="main"||je(e.symbol))}function XP(e,t,n){let r=K(e,n.relativePath);if(!r||r.language!=="rust")return null;let i=r.callables.find(l=>l.startLine!==n.startLine||l.endLine!==n.endLine?!1:l.name===n.leaf||n.leaf.endsWith(l.name)||l.name.endsWith(n.leaf));if(!i)return null;let o=r.callSites.filter(l=>l.line>=i.startLine&&l.line<=i.endLine);if(o.length===0)return null;let s=(t.occurrencesByFile.get(n.relativePath)??[]).filter(l=>l.line>=i.startLine&&l.line<=i.endLine&&l.callee.symbol!==n.symbol);if(s.some(l=>l.traitImplMember)||!QP(o,s))return null;let a=[],c=new Set;for(let l of s){let u=`${l.callee.symbol}\0${l.callee.file}\0${l.callee.line}`;c.has(u)||(c.add(u),a.push(l.callee))}return a}function QP(e,t){let n=$h(e),r=$h(t);if(n.size!==r.size)return!1;for(let[i,o]of n)if(r.get(i)!==o)return!1;return!0}function $h(e){let t=new Map;for(let n of e){let r=n.calleeLeaf??n.leaf;if(!r)continue;let i=`${n.line}\0${r}`;t.set(i,(t.get(i)??0)+1)}return t}function ZP(e){if(fu.has(e))return fu.get(e)??null;let t=eD(e);return fu.set(e,t),t}function eD(e){if(!e.generation.indexPath||!WP(e.generation.indexPath))return null;try{let t=Le(e).filter(o=>o.symbol.startsWith("rust-analyzer ")&&o.relativePath.endsWith(".rs")&&o.isFunctionLike),n=new Map(t.map(o=>[o.symbol,o])),r=VP(Qr(e.generation.indexPath,{inputKind:"SCIP occurrence-callee index",maxBytes:Xr})),i=new Map;for(let o of r.documents??[]){let s=o.relativePath;if(!s||!s.endsWith(".rs")||e.isIgnored(s))continue;let a=[];for(let c of o.occurrences??[]){if(!c.symbol||(c.symbolRoles&YP.Definition)!==0)continue;let l=n.get(c.symbol);if(!l)continue;let u=c.range?.[0];Number.isInteger(u)&&a.push({line:u,leaf:l.leaf,traitImplMember:je(l.symbol),callee:{symbol:l.symbol,file:l.relativePath,line:l.startLine,callsiteLine:u}})}i.set(s,a)}return{occurrencesByFile:i}}catch{return null}}var xa=class{sessions=new WeakMap;getOrCreate(t,n,r){let i=tD(t,n),o=this.sessions.get(t);o||(o=new Map,this.sessions.set(t,o));let s=o.get(i);if(s)return s.hits+=1,s.lastUsedAtMs=Date.now(),s.provider;let a=Date.now(),c=r();return o.set(i,{key:i,language:n,projectRoot:t.config.projectRoot,provider:c,createdAtMs:a,lastUsedAtMs:a,hits:1}),c}sessionsFor(t){return[...this.sessions.get(t)?.values()??[]]}clear(t){let n=this.sessions.get(t);if(n)for(let r of n.values())r.provider.dispose?.();this.sessions.delete(t)}};function tD(e,t){return`${e.config.projectRoot}:${t}-workspace`}import{randomUUID as DD}from"crypto";import{existsSync as MD}from"fs";import{dirname as TD}from"path";function Hh(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(typeof t.available!="boolean"||t.dependencyAvailable!==void 0&&typeof t.dependencyAvailable!="boolean"||t.tsconfigPath!==void 0&&typeof t.tsconfigPath!="string"||t.tsconfigPaths!==void 0&&(!Array.isArray(t.tsconfigPaths)||!t.tsconfigPaths.every(n=>typeof n=="string"))||t.resolvedBinary!==void 0&&typeof t.resolvedBinary!="string"||t.note!==void 0&&typeof t.note!="string")return null;if(t.available===!0){if(t.reason!==void 0)return null}else if(typeof t.reason!="string"||t.reason.length===0)return null;return t}import{performance as le}from"perf_hooks";function Dt(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}import Gh from"path";import{realpathSync as Uh}from"fs";function nD(e,t){return e.getReferences().map(n=>{let r=n.getNode();return Ra(r,t)})}function rD(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function zh(e,t,n,r){let i=[];for(let o of rD(e))for(let s of nD(o,r))s.file===t.relativePath&&s.line>=t.startLine&&s.line<=t.endLine||i.push(s);for(let o of n)i.push(o);return Si(i)}function Kh(e,t,n,r){let i=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();vi(r,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||i.push({location:Ra(a,r),node:a}))}return i}function Ra(e,t){let n=e.getSourceFile(),r=n.getLineAndColumnAtPos(e.getStart());return{file:vi(t,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function Wh(e,t,n){let r=e.getSourceFile(),i=hu(r,e),o=e.getText(),s=new RegExp(`\\b${Ce(o)}\\b`,"g"),a=r.getFullText().split(`
51
- `),c=[];for(let l=0;l<a.length;l++){if(l===i)continue;let u=a[l]??"";s.lastIndex=0;let d;for(;(d=s.exec(u))!==null;)c.push({file:t,line:l,column:d.index})}return Si(c.filter(l=>vi(n,Gh.join(n,l.file))===t))}function gu(e){for(let t=e;t;t=t.getParent()){let n=t.getKindName();if(n.includes("Type")||n==="InterfaceDeclaration"||n==="TypeAliasDeclaration")return!0;if(n==="CallExpression"||n==="NewExpression"||n==="ExpressionStatement")return!1}return!1}function hu(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function Si(e){let t=new Set,n=[];for(let r of e){let i=`${r.file}:${r.line}:${r.column}`;t.has(i)||(t.add(i),n.push(r))}return n}function vi(e,t){let n=e||process.cwd(),r=qh(n,t);if(r)return r;try{return qh(Uh(n),Uh(t))}catch{return null}}function qh(e,t){let n=Gh.relative(e,t).replace(/\\/g,"/");return!n||n===".."||n.startsWith("../")?null:n}function Vh(e,t,n,r){let i=iD(t,r);return i.size===0?new Map:oD(e,n,i)}function iD(e,t){let n=new Map;for(let r of U(e,t)){let i=z(r.symbol)??r.leaf;if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push(r)}return n}function oD(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of sD(e,o)){let a=n.get(s);if(!a)continue;let c=hu(t,o);for(let l of a){if(c<l.startLine-1||c>l.endLine+1)continue;let u=Math.abs(c-l.startLine),d=i.get(l.symbolId);d!==void 0&&d<=u||(i.set(l.symbolId,u),r.set(l.symbolId,o))}}}),r}function sD(e,t){let n=[],r=i=>{i&&!n.includes(i)&&n.push(i)};if("getNameNode"in t&&typeof t.getNameNode=="function"){let i=t.getNameNode();r(i?.getText())}if("getName"in t&&typeof t.getName=="function"){let i=t.getName();r(i)}return e.Node.isIdentifier(t)&&r(t.getText()),n}var aD=Fn("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function Yh(e,t,n,r){let i=Su(e,t),o=yu(i.get(r)??[],n);if(o)return o;let s=[];for(let a of i.values())for(let c of a)((c.leaf||z(c.symbol)||"").includes(r)||c.symbol.includes(r))&&s.push(c);return yu(s,n)}function bu(e,t,n,r){return yu(Su(e,t).get(r)??[],n)}function Jh(e,t){let n=new Map;for(let[r,i]of Su(e,t)){let o=i[0];o&&n.set(r,o)}return n}function Su(e,t){return aD.get(e,t,()=>{let n=new Map;for(let r of U(e,t)){let i=r.leaf||z(r.symbol);if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push({...r,leaf:i})}for(let r of n.values())r.sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine||i.symbolId-o.symbolId);return n})}function yu(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let i of e){let o=Math.abs(i.startLine-t);(o<r||o===r&&n&&i.startLine<n.startLine)&&(n=i,r=o)}return n}import cD from"path";import{realpathSync as lD}from"fs";function Xh(e,t){let n=new Map,r=null,i=null,o=()=>(i??=Z(e,{extensions:Ws}),i),s=()=>(r??=N("typescript.source-file-index",()=>uD(e.config.projectRoot,t,o()),()=>({projects:t.length,indexedDocuments:o().length})),r),a=c=>Un(c)?Dt(n,c,()=>{let l=Qh(e.config.projectRoot,c);if(!l)return null;for(let{project:u,sourceFiles:d}of s()){let m=d.get(l)??null;if(m||(m=u.addSourceFileAtPathIfExists(l)??null,m&&vu(d,m)),m)return{project:u,sourceFile:m}}return null}):null;return{sourceFile:c=>a(c)?.sourceFile??null,sourceFileMatch:a,indexedTypeScriptLikeDocuments:o}}function uD(e,t,n){let r=t.map(({project:i})=>{let o=new Map;for(let s of i.getSourceFiles())vu(o,s);return{project:i,sourceFiles:o}});for(let i of n){let o=Qh(e,i);if(o)for(let s of r){if(s.sourceFiles.has(o))break;let a=s.project.addSourceFileAtPathIfExists(o)??null;if(a){vu(s.sourceFiles,a);break}}}return r}function vu(e,t){let n=Cu(t.getFilePath());e.set(n,t);try{e.set(Cu(lD(n)),t)}catch(r){if(!Je(r))throw r}}function Qh(e,t){try{return Cu(Ps(e,t,{inputKind:"indexed TypeScript source file"}).absolutePath)}catch(n){if(!Je(n))throw n;return null}}function Cu(e){return cD.resolve(e)}function xu(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function Zh(e){let t=`${e.relativeDir}/src`;return[`${t}/index.ts`,`${t}/index.tsx`,`${t}/index.mts`,`${t}/index.cts`]}import{existsSync as wo}from"fs";import Ze from"path";var Ru=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Eu(e,t){let r=t?Ze.dirname(Ze.join(e,t)):e,i=Ze.resolve(e);for(;r.startsWith(i);){for(let s of Ru){let a=Ze.join(r,s);if(wo(a))return a}let o=Ze.dirname(r);if(o===r)break;r=o}for(let o of Ru){let s=Ze.join(e,o);if(wo(s))return s}return null}function ey(e){let t=e.config.projectRoot,n=new Set(dD(t,e.config.semantic?.typescript?.tsconfigs)),r=Z(e,{includeIgnored:!1,extensions:Ws});for(let i of r){let o=Eu(t,i);o&&n.add(Ze.resolve(o))}if(n.size===0){let i=Eu(t);i&&n.add(Ze.resolve(i))}return[...n].filter(i=>!ty(t,i)).sort((i,o)=>i.localeCompare(o))}function dD(e,t=[]){let n=new Set;for(let r of t){let i=Ze.isAbsolute(r)?r:Ze.join(e,r);wo(i)&&n.add(Ze.resolve(i))}for(let r of mD(e))for(let i of Ru){let o=Ze.join(r,i);wo(o)&&n.add(Ze.resolve(o))}if(n.size===0){let r=Eu(e);r&&n.add(Ze.resolve(r))}return[...n].filter(r=>!ty(e,r)).sort((r,i)=>r.localeCompare(i))}function mD(e){let t=Ze.join(e,"package.json");if(!wo(t))return[];let n;try{n=JSON.parse(Ve(t,"project package manifest"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>of(e,i))}function ty(e,t){let n=Ze.relative(e,t).replace(/\\/g,"/");return n.startsWith("..")||n.includes("/node_modules/")||n.startsWith("node_modules/")||n.includes("/dist/")||n.startsWith("dist/")}var pD=32;function ay(e,t){let n=N("typescript.provider.load",()=>Vs());if(!n)return Ys("ts-morph is not installed");let r=N("typescript.provider.tsconfig-discovery",()=>ey(e));if(r.length===0)return Ys("no tsconfig found");try{let i=N("typescript.provider.project-bundles",()=>$f(n,r),()=>({tsconfigs:r.length}));return fD(e,n,i)}catch(i){return Ys(i instanceof Error?i.message:String(i),r[0],r)}}function fD(e,t,n,r={}){return N("typescript.provider.construct",()=>new Iu(e,t,n),()=>({tsconfigs:n.length,reusedProjects:r.reusedProjects===!0}))}var Iu=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=rf(t.config.projectRoot),this.sourceFiles=Xh(t,r)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;compilerCheckerCache=new WeakMap;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(t=>t.tsconfigPath)}}importUsage(t){return Dt(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let r=hD();return N("typescript.import-usage.file",()=>this.importUsageForSourceFile(t,n,r),()=>({file:t,...r}))})}referencesFor(t){return Dt(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);return this.referencesForDefinitionNode(t,n)})}referencesForDefinitions(t,n={}){let r=new Map,i=be(),o=[];for(let u of t){let d=this.referencesCache.get(u.symbolId);d?r.set(u.symbolId,d):o.push(u)}if(o.length===0)return r;let s=o,a=n.exact?[]:o.filter(u=>!ry(u));if(a.length>=pD){let u=this.referencesForDefinitionsBySymbolScan(a);for(let d of a){let m=u.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,m),r.set(d.symbolId,m)}if(s=o.filter(d=>ry(d)),s.length===0)return r}let c=new Map;for(let u of s){let d=c.get(u.relativePath);d?d.push(u):c.set(u.relativePath,[u])}let l=[];for(let[u,d]of c){let m=iy();N("typescript.references-map.file",()=>{let p=this.definitionNodesForFile(u);for(let f of d){i&&(m.cacheMisses+=1);let g=p.get(f.symbolId)??null;i&&(g?m.nodeHits+=1:m.nodeMisses+=1);try{let h=this.referencesForDefinitionNode(f,g,i?m:void 0);this.referencesCache.set(f.symbolId,h),r.set(f.symbolId,h)}catch{m.preciseSearchFailures+=1,l.push(f)}}},()=>({relativePath:u,definitions:d.length,...oy(m)}))}if(l.length>0){let u=this.referencesForDefinitionsBySymbolScan(l);for(let d of l){let m=u.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,m),r.set(d.symbolId,m)}}return r}referenceFragmentsForFiles(t){let n=Le(this.db).filter(o=>Un(o.relativePath)),r=t.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(n,r);return jf(n,i,r)}referencesForDefinitionsBySymbolScan(t,n){let r=be(),i=iy(),o=new Map,s=new Set(t.map(c=>c.symbolId)),a=new Map(t.map(c=>[c.symbolId,c]));for(let c of t)o.set(c.symbolId,[]);return N("typescript.references-map.inverted-scan",()=>{let c=r?le.now():0,l=n?this.packageImportReferencesForFiles(n):this.packageImportReferences();for(let h of t){let b=l.get(h.symbolId)??[];if(b.length>0){let S=o.get(h.symbolId)??[];S.push(...b),o.set(h.symbolId,S)}r&&(i.packageReferenceCount+=b.length)}r&&(i.packageRefsMs+=le.now()-c);let u=new Map,d=new Map,m=this.hierarchyTargetsForDefinitions(t),p=new Set(t.map(h=>h.leaf).filter(Boolean)),f=r?le.now():0;for(let h of n??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(h))continue;let b=this.sourceFiles.sourceFile(h);b&&(r&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(b,h,s,a,m,p,u,d,o,r?i:void 0))}r&&(i.scanMs+=le.now()-f);let g=r?le.now():0;this.addHierarchyMemberReferences(t,o,r?i:void 0),r&&(i.hierarchyMs+=le.now()-g);for(let[h,b]of o){let S=Si(b);o.set(h,S),r&&(i.referenceCount+=S.length)}},()=>({definitions:t.length,...oy(i)})),o}addReferencesFromSourceFileScan(t,n,r,i,o,s,a,c,l,u){let d=this.compilerCheckerForSourceFile(t),m=t.compilerNode,p=SD(t),f=g=>{if(this.tsMorph.ts.isIdentifier(g)){if(u&&(u.identifiers+=1),!s.has(g.text)&&!p.has(g.text)){this.tsMorph.ts.forEachChild(g,f);return}let h=this.compilerReferenceSymbol(d,g,u);if(h){let b;a.has(h)?b=a.get(h)??null:(b=this.referenceDefinitionFromCompilerSymbol(h),a.set(h,b)),u&&(b?u.targetHits+=1:u.targetMisses+=1);let S=Dt(c,h,()=>this.compilerSymbolKeys(h)),y=null,x=null,v=b&&r.has(b.symbolId)?i.get(b.symbolId):void 0;if(v&&(y=Ea(m,g),!ny(v,n,y))){let C=m.getLineAndCharacterOfPosition(g.getStart(m));x={file:n,line:C.line,column:C.character};let R=l.get(v.symbolId)??[];R.push(x),l.set(v.symbolId,R),u&&(u.requestedHits+=1)}for(let C of S)for(let R of o.get(C)?.values()??[]){if(y??=Ea(m,g),ny(R,n,y))continue;if(!x){let w=m.getLineAndCharacterOfPosition(g.getStart(m));x={file:n,line:w.line,column:w.character}}let E=l.get(R.symbolId)??[];E.push(x),l.set(R.symbolId,E),u&&(u.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(g,f)};f(m)}hierarchyTargetsForDefinitions(t){let n=new Map;for(let r of t){let i=this.nodeForDefinition(r),o=i?.compilerNode;if(!o||!this.isHierarchyMethod(o))continue;let s=o.parent;if(!this.isHierarchyContainer(s))continue;let a=this.compilerCheckerForSourceFile(i.getSourceFile()),c=a.getSymbolAtLocation(o.name);if(c)for(let l of this.hierarchyMemberSymbols(a,s,c))for(let u of this.compilerSymbolKeys(l)){let d=n.get(u)??new Map;d.set(r.symbolId,r),n.set(u,d)}}return n}hierarchyMemberSymbols(t,n,r){let i=new Set,o=new Set,s=(a,c,l)=>{if(!o.has(a)){o.add(a),i.add(c);for(let u of l){let d=u.getProperty(r.name);d&&s(u,d,this.hierarchyAncestorTypesForType(t,u))}}};return s(t.getTypeAtLocation(n),r,this.hierarchyAncestorTypes(t,n)),i}addHierarchyMemberReferences(t,n,r){let i=new Map;for(let o of t){let s=this.nodeForDefinition(o),a=s?.compilerNode;if(!a||!this.isHierarchyMethod(a))continue;let c=a.parent;if(!this.isHierarchyContainer(c))continue;let l=this.compilerCheckerForSourceFile(s.getSourceFile()),u=l.getSymbolAtLocation(a.name);if(!u)continue;let d=a.getSourceFile(),m=d.getLineAndCharacterOfPosition(a.name.getStart(d)),p={definition:o,location:{file:o.relativePath,line:m.line,column:m.character}},f=n.get(o.symbolId)??[];for(let h of this.hierarchyMemberSymbols(l,c,u))if(h!==u)for(let b of this.compilerSymbolLocations(h))f.push(b),r&&(r.hierarchyReferences+=1);n.set(o.symbolId,f);let g=this.hierarchyRootMemberSymbols(l,c,u);for(let h of g){let b=i.get(h)??new Map;b.set(o.symbolId,p),i.set(h,b)}r&&(r.hierarchyDefinitions+=1)}for(let o of i.values())if(!(o.size<2)){r&&(r.hierarchyFamilies+=1);for(let{definition:s}of o.values()){let a=n.get(s.symbolId)??[];for(let c of o.values())c.definition.symbolId!==s.symbolId&&(a.push(c.location),r&&(r.hierarchyReferences+=1));n.set(s.symbolId,a)}}}hierarchyRootMemberSymbols(t,n,r){let i=new Set,o=new Set,s=(a,c,l)=>{if(o.has(a))return;o.add(a);let u=!1;for(let d of l){let m=d.getProperty(r.name);m&&(u=!0,s(d,m,this.hierarchyAncestorTypesForType(t,d)))}if(!u)for(let d of this.compilerSymbolKeys(c))i.add(d)};return s(t.getTypeAtLocation(n),r,this.hierarchyAncestorTypes(t,n)),i}compilerSymbolKeys(t){return(t.declarations??[]).map(n=>{let r=n.getSourceFile();return`${r.fileName}\0${n.getStart(r)}\0${t.name}`})}compilerSymbolLocations(t){let n=[];for(let r of t.declarations??[]){let i=r.getSourceFile(),o=vi(this.db.config.projectRoot,i.fileName);if(!o)continue;let s=r.name,a=i.getLineAndCharacterOfPosition((s??r).getStart(i));n.push({file:o,line:a.line,column:a.character})}return n}baseTypes(t,n){try{return t.getBaseTypes(n)??[]}catch{return[]}}hierarchyAncestorTypes(t,n){let r=new Set(this.hierarchyAncestorTypesForType(t,t.getTypeAtLocation(n)));for(let i of n.heritageClauses??[])for(let o of i.types)r.add(t.getTypeAtLocation(o));return[...r]}hierarchyAncestorTypesForType(t,n){let r=new Set(this.baseTypes(t,n));for(let i of n.getSymbol()?.declarations??[])if(this.isHierarchyContainer(i))for(let o of i.heritageClauses??[])for(let s of o.types)r.add(t.getTypeAtLocation(s));return[...r]}isHierarchyMethod(t){return this.tsMorph.ts.isMethodDeclaration(t)||this.tsMorph.ts.isMethodSignature(t)}isHierarchyContainer(t){return this.tsMorph.ts.isClassDeclaration(t)||this.tsMorph.ts.isClassExpression(t)||this.tsMorph.ts.isInterfaceDeclaration(t)}compilerReferenceSymbol(t,n,r){r&&(r.symbolLookups+=1);let i=t.getSymbolAtLocation(n);if(i){if((i.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return i;try{return r&&(r.aliasResolutions+=1),t.getAliasedSymbol(i)}catch{return i}}}calleesFor(t){return Dt(this.calleesCache,t.symbolId,()=>Dt(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}calleesForDefinitions(t){let n=new Map,r=new Map;for(let i of t){let o=r.get(i.relativePath);o?o.push(i):r.set(i.relativePath,[i])}for(let[i,o]of r){let s=this.fileCalleesCache.get(i),a=new Set(o.map(l=>l.symbolId)),c=s??this.calleeMapForFile(i,a);for(let l of o){let u=c.get(l.symbolId)??[];this.calleesCache.set(l.symbolId,u),n.set(l.symbolId,u)}}return n}referencesForDefinitionNode(t,n,r){let i=r?le.now():0,o=this.packageImportReferencesForDefinition(t);if(r&&(r.packageRefsMs+=le.now()-i,r.packageReferenceCount+=o.length),!n)return o;let s=r?le.now():0,a=zh(n,t,o,this.db.config.projectRoot);return r&&(r.semanticRefsMs+=le.now()-s,r.referenceCount+=a.length),a}signatureFor(t){return Dt(this.signatureCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);if(!n||!this.tsMorph.Node.isFunctionDeclaration(n)&&!this.tsMorph.Node.isMethodDeclaration(n)&&!this.tsMorph.Node.isArrowFunction(n)&&!this.tsMorph.Node.isFunctionExpression(n)&&!this.tsMorph.Node.isConstructorDeclaration(n))return null;let r=n.getType().getCallSignatures()[0];if(!r)return null;let i=r.getParameters().map(s=>{let a=s.getDeclarations()[0],c=a?s.getTypeAtLocation(a).getText(a):s.getValueDeclaration()?.getType().getText()??"unknown";return sy(c)}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${sy(o)}`})}importUsageForSourceFile(t,n,r){let i=[],o=new Map;for(let s of n.getImportDeclarations()){r.declarations+=1;let a=Sl(this.db,t,s.getModuleSpecifierValue()),c=s.getImportClause()?.isTypeOnly()??!1;for(let l of wu(s)){r.entries+=1;let u=c?null:l.identifier?.getSymbol()?.compilerSymbol??null;!c&&l.identifier&&(u?r.bindingSymbols+=1:r.missingBindingSymbols+=1);let d={sourcePath:a,entry:l,typeOnlyDeclaration:c,bindingSymbol:u,references:[]};if(i.push(d),c||!l.localName||!u)continue;let m=o.get(l.localName);m?m.push(d):o.set(l.localName,[d])}}return o.size>0&&n.forEachDescendant(s=>{if(s.getKindName()!=="Identifier")return;let a=o.get(s.getText());if(!a||yD(s))return;r.scannedIdentifiers+=1;let c=s.getSymbol()?.compilerSymbol;if(r.symbolLookups+=1,!!c){for(let l of a)if(l.bindingSymbol===c){l.references.push({location:Ra(s,this.db.config.projectRoot),node:s}),r.matchedReferences+=1;break}}}),i.map(s=>s.typeOnlyDeclaration?gD(t,s.sourcePath,s.entry):s.entry.identifier&&!s.bindingSymbol?(r.fallbackEntries+=1,this.valueImportUsageForEntry(t,s.sourcePath,s.entry)):this.valueImportUsageFromLocations(t,s.sourcePath,s.entry,s.references))}valueImportUsageForEntry(t,n,r){let i=r.identifier?r.identifier.findReferences():[],o=[];for(let s of i)for(let a of Kh(s,t,r.identifier,this.db.config.projectRoot))o.push(a);return this.valueImportUsageFromLocations(t,n,r,o)}valueImportUsageFromLocations(t,n,r,i){let o=i.some(c=>!gu(c.node)),s=i.some(c=>gu(c.node)),a=r.isTypeOnly;return{importer:t,sourcePath:n,importedName:r.importedName,localName:r.localName,kind:r.kind,isTypeOnly:a,isUsed:a||i.length>0,isTypeUsed:a||s,isValueUsed:o,references:i.map(c=>c.location)}}packageImportReferencesForDefinition(t){return this.packageImportReferences().get(t.symbolId)??[]}packageImportReferencesForFiles(t){let n=new Map,r=new Set;for(let o of t){let s=this.sourceFiles.sourceFile(o);if(s)for(let a of s.getImportDeclarations()){let c=xu(this.workspacePackages,a.getModuleSpecifierValue());c&&r.add(c)}}if(r.size===0)return n;let i=this.packageExportsForNames(r);for(let o of t)this.addPackageImportReferencesForDocument(n,i,o);for(let[o,s]of n)n.set(o,Si(s));return n}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let t=new Map,n=this.packageExports();for(let r of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(t,n,r);for(let[r,i]of t)t.set(r,Si(i));return this.packageImportReferenceIndex=t,t}addPackageImportReferencesForDocument(t,n,r){if(this.db.isIgnored(r))return;let i=this.sourceFiles.sourceFileMatch(r);if(i)for(let o of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(t,n,r,o)}addPackageImportReferencesForDeclaration(t,n,r,i){let o=xu(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of wu(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=Wh(a.identifier,r,this.db.config.projectRoot);l.length>0&&RD(t,c,l)}}packageExports(){return this.packageExportIndex?this.packageExportIndex:(this.packageExportIndex=this.packageExportsForNames(new Set(this.workspacePackages.map(t=>t.name))),this.packageExportIndex)}packageExportsForNames(t){let n=new Map;for(let r of this.workspacePackages){if(!t.has(r.name))continue;let i=new Map;for(let o of Zh(r))this.collectPackageExports(r,o,i,new Set);i.size>0&&n.set(r.name,i)}return n}collectPackageExports(t,n,r,i){if(i.has(n))return;i.add(n);let o=this.sourceFiles.sourceFile(n);if(o)for(let s of o.getExportDeclarations()){let a=s.getModuleSpecifierValue(),c=a?Sl(this.db,n,a):n;if(!c||!c.startsWith(`${t.relativeDir}/src/`))continue;let l=s.getNamedExports();if(l.length===0){if(s.isNamespaceExport())continue;this.collectPackageExports(t,c,r,i);continue}for(let u of l){let d=u.getNameNode().getText(),m=u.getAliasNode()?.getText()??d,p=this.indexedDefinitionByLeaf(c,d);if(!p)continue;let f=r.get(m);f||(f=new Set,r.set(m,f)),f.add(p.symbolId)}}}indexedDefinitionByLeaf(t,n){return Dt(this.indexedDefinitionLeafCache,t,()=>Jh(this.db,t)).get(n)??null}nodeForDefinition(t){return Dt(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return Dt(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?Vh(this.tsMorph,this.db,n,t):new Map})}referenceDefinitionFromCompilerSymbol(t){return this.definitionFromCompilerSymbol(t,void 0,!0)}definitionFromCompilerSymbol(t,n,r=!1){let i=t.name,o=n?le.now():0,s=t.declarations??[];n&&(n.declarationsMs+=le.now()-o,n.declarationChecks+=s.length);for(let a of s){let c=n?le.now():0,l=a.getSourceFile(),u=vi(this.db.config.projectRoot,l.fileName),d=l.getLineAndCharacterOfPosition(a.getStart(l)).line;if(n&&(n.declarationLocationMs+=le.now()-c),!u||this.db.isIgnored(u))continue;let m=n?le.now():0,p=this.compilerDeclarationName(a),f=r?bu(this.db,u,d,i)??(p&&p!==i?bu(this.db,u,d,p):null):Yh(this.db,u,d,i);if(n&&(n.indexedLookupMs+=le.now()-m),f)return{symbolId:f.symbolId,symbol:f.symbol,file:f.relativePath,line:f.startLine}}return null}compilerDeclarationName(t){let n=t.name;return n&&this.tsMorph.ts.isIdentifier(n)?n.text:null}calleeMapForFile(t,n){let r=be(),i=0,o=0,s=0,a=0,c=0,l=0,u=0,d=0,m=r?CD():void 0;return N("typescript.callee-map.file",()=>{let p=r?le.now():0,f=this.sourceFiles.sourceFile(t);if(r&&(c=Math.round(le.now()-p)),!f)return new Map;let g=r?le.now():0,h=U(this.db,t).sort((E,w)=>E.startLine-w.startLine||w.endLine-E.endLine);if(r&&(l=Math.round(le.now()-g)),i=h.length,h.length===0)return new Map;let b=new Map,S=r?le.now():0,y=this.compilerCheckerForSourceFile(f),x=f.compilerNode;r&&(u=Math.round(le.now()-S));let v=new Map,C=E=>{if(this.tsMorph.ts.isCallExpression(E)||this.tsMorph.ts.isNewExpression(E)){r&&(o+=1);let w=this.semanticCalleeForCallNode(y,x,h,E,v,n,m);w&&(r&&(s+=1),bD(b,w.callerId,w.target))}this.tsMorph.ts.forEachChild(E,C)},R=r?le.now():0;C(x),r&&(d=Math.round(le.now()-R));for(let[E,w]of b)b.set(E,ED(w));return a=b.size,b},()=>({relativePath:t,definitions:i,callNodes:o,resolvedCallees:s,outputRows:a,requestedDefinitions:n?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:u,traversalMs:d,...m?xD(m):{}}))}semanticCalleeForCallNode(t,n,r,i,o,s,a){let c=a?le.now():0,l=vD(r,Ea(n,i));if(a&&(a.callerLookupMs+=le.now()-c),!l)return null;if(s&&!s.has(l.symbolId))return a&&(a.skippedUnrequestedCallers+=1),null;let u=i.expression,d=this.compilerSymbolForExpression(t,u,a),m=null;if(d)if(a&&(a.targetSymbolHits+=1),o.has(d))a&&(a.compilerSymbolCacheHits+=1),m=o.get(d)??null;else{a&&(a.compilerSymbolCacheMisses+=1);let p=a?le.now():0;m=this.definitionFromCompilerSymbol(d,a),a&&(a.targetLookupMs+=le.now()-p),o.set(d,m)}else a&&(a.targetMisses+=1);return m?{callerId:l.symbolId,target:{symbol:m.symbol,file:m.file,line:m.line,callsiteLine:Ea(n,i)}}:null}compilerSymbolForExpression(t,n,r){let i=r?le.now():0,o=t.getSymbolAtLocation(n);if(r&&(r.expressionSymbolMs+=le.now()-i),o)return o;r&&(r.typeFallbacks+=1);let s=r?le.now():0,a=t.getTypeAtLocation(n).getSymbol();return r&&(r.typeSymbolMs+=le.now()-s),a}compilerCheckerForSourceFile(t){let n=t.getProject(),r=this.compilerCheckerCache.get(n);return r||(r=n.getTypeChecker().compilerObject,this.compilerCheckerCache.set(n,r)),r}};function wu(e){let t=[],n=e.getDefaultImport();n&&t.push({identifier:n,importedName:"default",localName:n.getText(),kind:"default",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});let r=e.getNamespaceImport();r&&t.push({identifier:r,importedName:"*",localName:r.getText(),kind:"namespace",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});for(let i of e.getNamedImports()){let o=i.getNameNode(),a=i.getAliasNode()??(o.getKindName()==="Identifier"?o:null);t.push({identifier:a,importedName:o.getText(),localName:a?.getText()??o.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(e.getImportClause()?.isTypeOnly()??!1)})}return t.length===0&&t.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),t}function gD(e,t,n){return{importer:e,sourcePath:t,importedName:n.importedName,localName:n.localName,kind:n.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function hD(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function yD(e){for(let t=e;t;t=t.getParent())if(t.getKindName()==="ImportDeclaration")return!0;return!1}function bD(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function SD(e){let t=new Set;for(let n of e.getImportDeclarations())for(let r of wu(n))r.localName&&t.add(r.localName);return t}function vD(e,t){let n=null;for(let r of e)t<r.startLine||t>r.endLine||(!n||r.startLine>=n.startLine)&&(n=r);return n}function Ea(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line}function ny(e,t,n){return t===e.relativePath&&n>=e.startLine&&n<=e.endLine}function ry(e){return e.symbol.includes("#")?wt(e.symbol)==="type"&&e.relativePath.endsWith(".d.ts"):!1}function CD(){return{callerLookupMs:0,expressionSymbolMs:0,typeSymbolMs:0,targetLookupMs:0,declarationsMs:0,declarationLocationMs:0,indexedLookupMs:0,compilerSymbolCacheHits:0,compilerSymbolCacheMisses:0,targetSymbolHits:0,targetMisses:0,typeFallbacks:0,declarationChecks:0,skippedUnrequestedCallers:0}}function xD(e){return{...e,callerLookupMs:Math.round(e.callerLookupMs),expressionSymbolMs:Math.round(e.expressionSymbolMs),typeSymbolMs:Math.round(e.typeSymbolMs),targetLookupMs:Math.round(e.targetLookupMs),declarationsMs:Math.round(e.declarationsMs),declarationLocationMs:Math.round(e.declarationLocationMs),indexedLookupMs:Math.round(e.indexedLookupMs)}}function iy(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0,preciseSearchFailures:0,hierarchyDefinitions:0,hierarchyFamilies:0,hierarchyReferences:0,hierarchyMs:0}}function oy(e){return{...e,scanMs:Math.round(e.scanMs),packageRefsMs:Math.round(e.packageRefsMs),semanticRefsMs:Math.round(e.semanticRefsMs),hierarchyMs:Math.round(e.hierarchyMs)}}function RD(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function ED(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}|${r.line}|${r.callsiteLine??""}`;t.has(i)||(t.add(i),n.push(r))}return n}function sy(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}import{join as ID}from"path";var Ci=3,wD=2,LD="typescript-semantic";function ly(e){let t=ID(e,LD),n=zs(t);return{...n,requestDir:n.legacyRequestDir}}function X6(e){let t=JSON.parse(e),n=t.protocolVersion,r=n===wD;if(!r&&n!==Ci||typeof t.id!="string"||typeof t.generation!="string"||typeof t.deadlineAtMs!="number"||!Number.isFinite(t.deadlineAtMs)||t.profileEnvironment!==void 0&&!hl(t.profileEnvironment)||!t.request||!PD(t.request)||!r&&(t.mailboxVersion!==hn||typeof t.operationKey!="string"||!/^[a-f0-9]{64}$/.test(t.operationKey)||t.id!==xr(t.operationKey)||typeof t.clientId!="string"||!t.clientId||typeof t.enqueuedAtMs!="number"||!Number.isFinite(t.enqueuedAtMs)||t.deadlineAtMs<t.enqueuedAtMs))throw new Error("TypeScript semantic service received an invalid mailbox request.");if(!r){let o=t,s=Hn("typescript-semantic-v3",{generation:o.generation,profileEnvironment:o.profileEnvironment,request:o.request});if(o.operationKey!==s)throw new Error("TypeScript semantic service received a mismatched mailbox operation identity.");return o}let i=Hn("typescript-semantic-v2",{id:t.id,generation:t.generation,request:t.request});return{protocolVersion:Ci,mailboxVersion:hn,id:t.id,operationKey:i,clientId:"legacy-v2",enqueuedAtMs:t.deadlineAtMs,deadlineAtMs:t.deadlineAtMs,generation:t.generation,...t.profileEnvironment?{profileEnvironment:t.profileEnvironment}:{},request:t.request}}function PD(e){if(!e||typeof e!="object"||!("kind"in e))return!1;let t=e;switch(t.kind){case"availability":return!0;case"import-usage":return typeof t.file=="string";case"reference-fragments":return Yi(t.files)!==null;case"references":return cy(t.definitions)&&(t.exact===void 0||typeof t.exact=="boolean");case"callees":return cy(t.definitions);case"signature":return uy(t.definition);default:return!1}}function cy(e){return Array.isArray(e)&&e.every(uy)}function uy(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.symbolId=="number"&&typeof t.documentId=="number"&&typeof t.symbol=="string"&&typeof t.relativePath=="string"&&typeof t.leaf=="string"&&typeof t.startLine=="number"&&typeof t.endLine=="number"}var kD=12e4,AD=5;function py(e,t,n={}){let r=new Lu(e,n),i=null,o=null,s=process.env.SCIP_QUERY_SKIP_WATCH_SERVICE==="1",a=()=>(i??=ay(e,t),i),c=(d,m,p)=>{if(s)return p();try{return m(r.request(d))}catch{return s=!0,p()}},l=(d,m)=>c({kind:"references",definitions:[...d],...m?.exact?{exact:!0}:{}},p=>my(p),()=>a().referencesForDefinitions?.(d,m)??new Map(d.map(p=>[p.symbolId,a().referencesFor(p)]))),u=d=>c({kind:"callees",definitions:[...d]},m=>my(m),()=>a().calleesForDefinitions?.(d)??new Map(d.map(m=>[m.symbolId,a().calleesFor(m)])));return{language:"typescript",availability:()=>(o??=c({kind:"availability"},_D,()=>a().availability()),o),importUsage:d=>c({kind:"import-usage",file:d},m=>m,()=>a().importUsage(d)),referencesFor:d=>l([d]).get(d.symbolId)??[],referencesForDefinitions:l,referenceFragmentsForFiles:d=>c({kind:"reference-fragments",files:[...d]},m=>ND(m),()=>a().referenceFragmentsForFiles?.(d)??new Map),calleesFor:d=>u([d]).get(d.symbolId)??[],calleesForDefinitions:u,signatureFor:d=>c({kind:"signature",definition:d},OD,()=>a().signatureFor(d)),dispose:()=>i?.dispose?.()}}var Lu=class{constructor(t,n={}){this.db=t;this.runtime=n.runtime??$D,this.timeoutMs=n.timeoutMs??BD(),this.mailboxLimits=n.mailboxLimits??{},this.cacheDir=TD(t.config.dbPath),this.projectRoot=Up(t.config.projectRoot)}db;runtime;timeoutMs;cacheDir;projectRoot;mailboxLimits;request(t){let n=Bf(this.cacheDir),r=ly(this.cacheDir),i=Rl(n.statePath);if(!dy(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript semantic service is not running.");let o=this.db.generation.identity;if(!o)throw new Error("Published TypeScript generation identity is unavailable.");let s=this.runtime.now(),a=s+this.timeoutMs,c=(this.runtime.monotonicNow??Lt)()+this.timeoutMs,l=af(),u=Hn("typescript-semantic-v3",{generation:o,profileEnvironment:l,request:t}),d=xr(u),m=Ks(r,{mailboxVersion:hn,operationKey:u,clientId:this.runtime.randomId(),enqueuedAtMs:s,deadlineAtMs:a,protocolVersion:Ci,id:d,generation:o,profileEnvironment:l,request:t},{nowMs:s,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??Lt)()<=c;){if(MD(m.responsePath))return FD(vt(m.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript semantic mailbox response"}),d,o,u);let p=Rl(n.statePath);if(!dy(p,this.projectRoot,this.runtime))throw new Error("TypeScript semantic service stopped while processing a request.");this.runtime.sleep(AD)}throw new Error(`TypeScript semantic service timed out after ${this.timeoutMs}ms.`)}};function dy(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null;return e!==null&&e.projectRoot===t&&e.typescriptSemantic?.protocolVersion===Ci&&n.isProcessAlive(e.pid)&&(!e.processIdentity||r!=null&&Gs(e.processIdentity,r))}function FD(e,t,n,r){let i=JSON.parse(e);if(i.protocolVersion!==Ci||i.id!==t||i.operationKey!==r||i.ok===!0&&i.generation!==n)throw new Error("TypeScript semantic service wrote an incompatible response.");if(i.ok===!0)return i.response;throw new Error(typeof i.error=="string"?i.error:"TypeScript semantic service request failed.")}function my(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid numeric map.");return new Map(e)}function ND(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid string map.");return new Map(e)}function _D(e){let t=Hh(e);if(!t)throw new Error("TypeScript semantic service wrote invalid availability.");return t}function OD(e){if(e!==null&&typeof e!="string")throw new Error("TypeScript semantic service wrote an invalid signature.");return e}function BD(){let e=Number(process.env.SCIP_TYPESCRIPT_SEMANTIC_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:kD}var $D={now:Date.now,monotonicNow:Lt,randomId:DD,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:ci,readProcessIdentity:li};var fy=new xa;Qp({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>fy.clear(e)});function Dr(e,t){let n=He(t)??"typescript";return fy.getOrCreate(e,n,()=>n==="rust"?Oh(e.config.projectRoot,{sourceImportUsageResolver:{importUsageFacts:r=>eh(e,r)},calleeSymbolResolver:Zg(e),sourceZeroCalleeOracle:r=>jD(e,r),scipOccurrenceCalleeOracle:r=>jh(e,r)}):py(e,t))}function He(e){return e?se(e)==="rust"?"rust":Un(e)?"typescript":null:"typescript"}function jD(e,t){let n=K(e,t.relativePath);if(!n||n.language!=="rust")return!1;let r=n.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine&&i.name===t.leaf)??n.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine);return r?!n.callSites.some(i=>i.line>=r.startLine&&i.line<=r.endLine):!1}var HD=/^[A-Za-z_][A-Za-z0-9_]*$/,gy=/\bDefault::default\b/g,UD=/^\.\.\s*Default::default\b/;function hy(e,t){let n=new Map,r=new Map;for(let i of t){let o=Pu(e,i,r);o!==null&&n.set(i.symbolId,o)}return n}function Pu(e,t,n=new Map){let r=GD(t.symbol);if(!r)return null;let i=Us(e,[t.symbolId]);if(i.length===0)return null;let o=new RegExp(`(^|[^A-Za-z0-9_])${Ce(r)}::default\\b`,"g"),s=new RegExp(`(^|[^A-Za-z0-9_])${Ce(r)}\\s*$`),a=qD(e,t.symbolId),c=[];for(let l of i){let u=zD(e,l.relative_path,n);if(u===null)return null;let d=u.split(/\r?\n/),m=0,p=[],f=0;for(let g=l.chunk_start;g<=l.chunk_end&&g<d.length;g+=1){let b=d[g]??"",S=new Set;o.lastIndex=0;let y;for(;y=o.exec(b);)c.push({file:l.relative_path,line:g,column:y.index+y[1].length+r.length+2}),f+=1;for(let x=0;x<b.length;x+=1){let v=UD.exec(b.slice(x));if(v){if(a&&p.includes(m)){let R=x+v[0].lastIndexOf("default");c.push({file:l.relative_path,line:g,column:R}),S.add(R),f+=1}x+=v[0].length-1;continue}let C=b[x];if(C==="{"){let R=s.test(b.slice(0,x));m+=1,R&&p.push(m);continue}if(C==="}")for(m=Math.max(0,m-1);p.length>0&&p[p.length-1]>m;)p.pop()}for(gy.lastIndex=0;y=gy.exec(b);){let x=y.index+9;if(!S.has(x))return null}}if(f===0)return null}return ga(c)}function qD(e,t){return e.get("SELECT 1 AS present FROM mentions WHERE symbol_id = ? AND role = 1 LIMIT 1",t)?.present===1}function GD(e){let t=/impl#\[([^\]]+)\]\[Default\]default\(\)\./.exec(e)?.[1]??null;return!t||!HD.test(t)?null:t}function zD(e,t,n){if(n.has(t))return n.get(t)??null;let r=e.get("SELECT text FROM documents WHERE relative_path = ?",t),i=typeof r?.text=="string"?r.text:KD(e,t);return n.set(t,i),i}function KD(e,t){try{return Ye(e.config.projectRoot,t,{inputKind:"indexed Rust source file"})}catch(n){if(!Je(n))throw n;return null}}var WD="typescript-import-usage-v1",VD="typescript-signatures-v1",Du=ge("semantic-prefetched-callees",{clearGroups:["whole-project","source-file","semantic-provider"]}),yy=Ji({kind:"semantic-import-usage",invalidation:$e("semantic-import-usage"),serialize:e=>JSON.stringify(e),deserialize:Py}),by=Ji({kind:"semantic-signatures",invalidation:$e("semantic-signatures"),serialize:e=>JSON.stringify(e),deserialize:rM}),Sy=dt({kind:"typescript-import-usage",invalidation:$e("typescript-import-usage"),serialize:e=>JSON.stringify(e),deserialize:Py}),vy=dt({kind:"typescript-signatures",invalidation:$e("typescript-signatures"),serialize:e=>JSON.stringify(e),deserialize:iM});function st(e){let t=new Map,n=new Set;return{capability:(r,i)=>Dy(e,r,i),importUsage:r=>JD(e,r),references:r=>Ry(e,r),materializeReferences:(r,i)=>Iy(e,r,t,n,i),callerMap:r=>XD(e,r,t,n),calleeMap:r=>eM(e,r),signature:r=>tM(e,r)}}function YD(e,t){if(t.size===0)return;let n=Du.get(e,()=>new Map);for(let[r,i]of t)n.set(r,[...i])}function xy(e,t){if(!Du.has(e))return{hits:[],misses:[...t]};let n=Du.get(e,()=>new Map),r=[],i=[];for(let o of t)n.has(o.symbolId)?r.push({definition:o,callees:n.get(o.symbolId)??[]}):i.push(o);return{hits:r,misses:i}}function Po(e,t){return st(e).importUsage(t)}function JD(e,t){if(He(t)==="typescript"){let o="fallback",s=0,a=0,c=0,l=0;return N("typescript.import-usage.materialize",()=>{let u=to(e,t,WD);if(u?.key){s=1;let m=Sy.read(e,t,u.key);if(m)return o="hit",a=1,m;c=1;let p=Yt(e,t);if(!p)return o="unavailable",[];let f=p.importUsage(t);return Sy.write(e,t,u.key,f),o="computed",f}l=1;let d=Yt(e,t);return d?(o="direct-fallback",d.importUsage(t)):(o="unavailable",[])},()=>({state:o,eligible:s,cacheHits:a,cacheMisses:c,fallbacks:l}))}let n=Ly(e,"semantic-import-usage",t);if(n){let o=yy.read(e,t,n);if(o)return o}let r=Yt(e,t);if(!r)return[];let i=r.importUsage(t);return n&&yy.write(e,t,n,i),i}function Ia(e,t){return st(e).references(t)}function Ry(e,t){let n=Pu(e,t);if(n)return n;let r=rh(e,t);if(r)return r;let i=Yt(e,t.relativePath);return i?i.referencesFor(t):[]}function Jn(e,t){return st(e).callerMap(t)}function Ey(e,t){let n=new Map,r=[];for(let i of t){if(He(i.relativePath)==="typescript"){r.push(i);continue}Mu(e,n,i,Ry(e,i))}if(r.length>0){let o=Il(e,r,s=>Dr(e,s))?.references;if(!o){let s=Yt(e,r[0].relativePath);o=s?s.referencesForDefinitions?s.referencesForDefinitions(r,{exact:!0}):new Map(r.map(a=>[a.symbolId,s.referencesFor(a)])):new Map,s&&be()&&El(e,r,o,a=>Dr(e,a))}for(let s of r)Mu(e,n,s,o.get(s.symbolId)??[])}return n}function XD(e,t,n=new Map,r=new Set){let i=new Map,o=Iy(e,t,n,r),s=0;return N("semantic.callers.from-references",()=>{for(let a of t)s+=Mu(e,i,a,n.get(a.symbolId)??[])},()=>({definitions:t.length,materialized:o.definitions,inMemoryHits:o.inMemoryHits,incompleteInMemoryHits:o.incompleteInMemoryHits,resultRows:i.size,callerFiles:s})),i}function Iy(e,t,n,r,i={}){let o=mn(e),s=[],a=[],c=[],l=0,u=0,d=0,m=0,p=0,f=0,g=0,h=0,b=0,S=0,y=0,x=0,v=[],C=new Map,R=t.filter(w=>He(w.relativePath)==="typescript"&&!n.has(w.symbolId)&&!r.has(w.symbolId)),E=Il(e,R,w=>Dr(e,w));if(E){b=R.length,S=E.cacheHits,y=E.cacheMisses,x=E.computedFiles;for(let w of R)n.set(w.symbolId,E.references.get(w.symbolId)??[])}if(N("semantic.references.cache-scan",()=>{for(let[w,I]of ma(t)){let k=[];for(let L of I)n.has(L.symbolId)?u+=1:r.has(L.symbolId)?h+=1:k.push(L);if(k.length===0){g+=1;continue}let D=QD(e,o,w);if(!D){for(let L of k)He(L.relativePath)||(l+=1),c.push(L);continue}f+=1;let F=tf(e,w,D);for(let L of k){let A=F.get(L.symbol)??null;if(A!==null){let P=ZD(A);if(P){d+=1,n.set(L.symbolId,P);continue}m+=1}a.push({definition:L,cacheFingerprint:D})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:l,cacheHits:d,parseFailures:m,misses:a.length,unkeyed:c.length,inMemoryHits:u,incompleteInMemoryHits:h,fullyInMemoryFiles:g,cacheReadFiles:f})),a.length>0||c.length>0){v=[...c,...a.map(w=>w.definition)],C=N("semantic.references.compute-misses",()=>{let w=Tu(e,v,i);return p=w.size,w},()=>({definitions:v.length,misses:a.length,unkeyed:c.length,rows:p}));for(let w of v)C.has(w.symbolId)?(n.set(w.symbolId,C.get(w.symbolId)??[]),r.delete(w.symbolId)):r.add(w.symbolId);for(let{definition:w,cacheFingerprint:I}of a)C.has(w.symbolId)&&Dy(e,"semantic-references",w.relativePath).available&&s.push({relativePath:w.relativePath,symbol:w.symbol,projectFingerprint:I,payload:JSON.stringify(C.get(w.symbolId)??[])})}return s.length>0&&N("semantic.references.cache-write",()=>nf(e,s),()=>({entries:s.length})),C.size>0&&El(e,v,C,w=>Dr(e,w)),{definitions:t.length,inMemoryHits:u,incompleteInMemoryHits:h,cacheHits:d,misses:a.length,unkeyed:c.length,skippedUnsupportedLanguage:l,parseFailures:m,computed:p,incomplete:r.size,cacheWrites:s.length,fragmentDefinitions:b,fragmentCacheHits:S,fragmentCacheMisses:y,fragmentComputedFiles:x}}function QD(e,t,n){if(!t)return null;let r=He(n);return r==="typescript"?t:r==="rust"?qt(JSON.stringify({kind:"semantic-references",language:r,engine:wr(e.config.projectRoot),projectFingerprint:t})):null}function Tu(e,t,n={}){let r=be(),i=new Map,o=0,s=0,a=0,c=0,l=0,u=0,d=0,m=0,p=0;return N("semantic.references.provider-loop",()=>{let f=hy(e,t),g=nh(e,t),h=new Map,b=n.prefetchCallees?new Map:null,S=[];for(let x of t){let v,C=()=>(v??=Yt(e,x.relativePath),v);if(b){let I=C();if(I?.referencesAndCalleesForDefinitions){let k=b.get(I);k?k.push(x):b.set(I,[x]),p+=1}}let R=f.get(x.symbolId);if(R){a+=1,c+=R.length,Lo(i,x.symbolId,R,r,I=>{d+=1,m+=I});continue}let E=g.get(x.symbolId);if(E){l+=1,u+=E.length,Lo(i,x.symbolId,E,r,I=>{d+=1,m+=I});continue}let w=C();if(!w){r&&(s+=1);continue}if(r&&(o+=1),w.referencesForDefinitions){let I=h.get(w);I?I.push(x):h.set(w,[x])}else S.push({provider:w,definition:x})}let y=new Set;if(b)for(let[x,v]of b){if(!x.referencesAndCalleesForDefinitions)continue;let C=h.get(x)??[],R=x.referencesAndCalleesForDefinitions(C,v);y.add(x),YD(e,R.callees);for(let E of C){if(!R.references.has(E.symbolId))continue;let w=R.references.get(E.symbolId)??[];Lo(i,E.symbolId,w,r,I=>{d+=1,m+=I})}}for(let[x,v]of h){if(y.has(x))continue;let C=x.referencesForDefinitions(v);for(let R of v){if(!C.has(R.symbolId))continue;let E=C.get(R.symbolId)??[];Lo(i,R.symbolId,E,r,w=>{d+=1,m+=w})}}for(let{provider:x,definition:v}of S){let C=x.referencesFor(v);Lo(i,v.symbolId,C,r,R=>{d+=1,m+=R})}return i},()=>({definitions:t.length,providerHits:o,providerMisses:s,rustDefaultFastPathRows:a,rustDefaultFastPathReferences:c,rustScipOccurrenceFastPathRows:l,rustScipOccurrenceFastPathReferences:u,prefetchCalleeDefinitions:p,definitionsWithReferences:d,referenceCount:m,rows:i.size}))}function Lo(e,t,n,r,i){e.set(t,n),r&&n.length>0&&i(n.length)}function Mu(e,t,n,r){let i=0;for(let o of r){if(o.file===n.relativePath||e.isIgnored(o.file))continue;let s=t.get(n.symbolId);s||(s=new Set,t.set(n.symbolId,s));let a=s.size;s.add(o.file),s.size!==a&&(i+=1)}return i}function ZD(e){try{return JSON.parse(e)}catch{return null}}function wa(e,t){return st(e).calleeMap(t)}function eM(e,t){let n=be(),r=new Map,i=0,o=0,s=0,a=0;return N("semantic.callees.provider-loop",()=>{let c=new Map,l=[];for(let u of t){let d=Yt(e,u.relativePath);if(!d){n&&(o+=1);continue}n&&(i+=1);let m=u;if(d.calleesForDefinitions){let p=c.get(d);p?p.push(m):c.set(d,[m])}else l.push({provider:d,definition:m})}for(let[u,d]of c){let m=u.calleesForDefinitions(d);for(let p of d){let f=m.get(p.symbolId)??[];Cy(r,p.symbolId,f,n,g=>{s+=1,a+=g})}}for(let{provider:u,definition:d}of l){let m=u.calleesFor(d);Cy(r,d.symbolId,m,n,p=>{s+=1,a+=p})}return r},()=>({definitions:t.length,providerHits:i,providerMisses:o,definitionsWithCallees:s,calleeCount:a,rows:r.size}))}function Cy(e,t,n,r,i){n.length>0&&(e.set(t,n),r&&i(n.length))}function wy(e,t){return st(e).signature(t)}function tM(e,t){if(He(t.relativePath)==="typescript"){let s="fallback",a=0,c=0,l=0,u=0;return N("typescript.signature.materialize",()=>{let d=to(e,t.relativePath,VD);if(d?.key){a=1;let p=vy.read(e,t.relativePath,d.key)??{};if(Object.prototype.hasOwnProperty.call(p,t.symbol))return s="hit",c=1,p[t.symbol]??null;l=1;let f=Yt(e,t.relativePath);if(!f)return s="unavailable",null;let g=f.signatureFor(t);return vy.write(e,t.relativePath,d.key,{...p,[t.symbol]:g}),s="computed",g}u=1;let m=Yt(e,t.relativePath);return m?(s="direct-fallback",m.signatureFor(t)):(s="unavailable",null)},()=>({state:s,eligible:a,cacheHits:c,cacheMisses:l,fallbacks:u}))}let n=Ly(e,"semantic-signatures",t.relativePath),r=nM(t);if(n){let s=by.read(e,r,n);if(s)return s.signature}let i=Yt(e,t.relativePath);if(!i)return null;let o=i.signatureFor(t);return n&&by.write(e,r,n,{signature:o}),o}function Ly(e,t,n){let r=mn(e);if(!r)return null;let i=He(n);return i!=="rust"?null:qt(JSON.stringify({kind:t,language:i,engine:wr(e.config.projectRoot),projectFingerprint:r}))}function nM(e){return`${e.relativePath}\0${e.symbol}`}function Py(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:null}catch{return null}}function rM(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t.signature;return n!==null&&typeof n!="string"?null:{signature:n}}catch{return null}}function iM(e){try{let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return null;for(let n of Object.values(t))if(n!==null&&typeof n!="string")return null;return t}catch{return null}}function Dy(e,t,n){let r=He(n);if(!r)return{slot:t,language:"typescript",available:!1,reason:"semantic evidence is only available for TypeScript or Rust files"};try{return{slot:t,language:r,...Dr(e,n).availability()}}catch(i){return{slot:t,language:r,available:!1,reason:i instanceof Error?i.message:String(i)}}}function Yt(e,t){if(!He(t))return null;let n=Dr(e,t);return n.availability().available?n:null}var re={references:Ia,referenceMap:Tu,callerMap:(e,t)=>st(e).callerMap(t),calleeMap:ku};function ku(e,t){let n=be(),r=new Map,i=xy(e,t),o=[],s=[],a=0,c=0,l=0,u=0,d=0,m=0,p=0;for(let{definition:y,callees:x}of i.hits)d+=1,x.length>0&&(m+=1,p+=x.length,r.set(y.symbolId,x));let f=oM(e,i.hits);if(f.entries.length>0&&N("semantic.callees.prefetch-cache-write",()=>bl(e,f.entries),()=>({entries:f.entries.length,sourceMissing:f.sourceMissing,skippedUnsupportedLanguage:f.skippedUnsupportedLanguage})),N("semantic.callees.cache-scan",()=>{for(let[y,x]of ma(i.misses)){if(!He(y)){n&&(a+=x.length);continue}let v=W(e,y);if(!v){n&&(c+=x.length),s.push(...x);continue}let C=Rt(e,y,v),R=My(e,y);if(!R){s.push(...x);continue}let E=ef(e,y,C,R);for(let w of x){let I=E.get(w.symbol)??null;if(I!==null){let k=aM(I);if(k){n&&(l+=1),k.length>0&&r.set(w.symbolId,k);continue}n&&(u+=1)}o.push({def:w,contentHash:C,depsDigest:R})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:a,sourceMissing:c,cacheHits:l,parseFailures:u,misses:o.length,unkeyed:s.length,inMemoryHits:d,inMemoryRows:m,inMemoryCalleeCount:p,resultRows:r.size})),o.length===0&&s.length===0)return r;let g=[...s,...o.map(y=>y.def)],h=0,b=N("semantic.callees.compute-misses",()=>{let y=wa(e,g);return h=y.size,y},()=>({definitions:g.length,misses:o.length,unkeyed:s.length,rows:h}));for(let[y,x]of b)r.set(y,x);let S=o.filter(y=>st(e).capability("semantic-callees",y.def.relativePath).available).map(y=>({relativePath:y.def.relativePath,symbol:y.def.symbol,contentHash:y.contentHash,depsDigest:y.depsDigest,payload:JSON.stringify(b.get(y.def.symbolId)??[])}));return S.length>0?N("semantic.callees.cache-write",()=>bl(e,S),()=>({entries:S.length})):N("semantic.callees.cache-write-skip",()=>{},()=>({reason:"provider-unavailable",misses:o.length})),r}function oM(e,t){let n=[],r=new Map,i=0,o=0;for(let{definition:s,callees:a}of t){if(!He(s.relativePath)){o+=1;continue}if(!r.has(s.relativePath)){let l=W(e,s.relativePath),u=l?My(e,s.relativePath):null;r.set(s.relativePath,l&&u?{contentHash:Rt(e,s.relativePath,l),depsDigest:u}:null)}let c=r.get(s.relativePath);if(!c){i+=1;continue}n.push({relativePath:s.relativePath,symbol:s.symbol,contentHash:c.contentHash,depsDigest:c.depsDigest,payload:JSON.stringify(a)})}return{entries:n,sourceMissing:i,skippedUnsupportedLanguage:o}}var sM="typescript-callees-v2-callsite-line";function My(e,t){let n=He(t);if(n==="typescript")return to(e,t,sM)?.key??null;let r=lM(e,t);return n==="rust"?qt(JSON.stringify({kind:"semantic-callees",language:n,engine:wr(e.config.projectRoot),positionMapping:"nearby-leaf-v2-callsite-line",depsDigest:r})):r}function aM(e){try{return JSON.parse(e)}catch{return null}}var cM=Fn("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function lM(e,t){return cM.get(e,t,()=>{let r=[...Me(e).get(t)??[]].sort().map(i=>`${i}:${Rt(e,i,W(e,i))}`);return qt(r.join("|"))})}function o8(e,t,n={}){let r=ne(e,t);if(!r)return[];let o=!Se(r.symbol)&&!e.isIgnored(r.relativePath)?[{relativePath:r.relativePath,line:r.startLine}]:[],s=jn(e,r,{semantic:n.semantic,semanticEvidence:re}).map(u=>({relativePath:u.file,line:u.line})),a=uM(e,r),c=new Set,l=[];for(let u of[...o,...s,...a]){let d=`${u.relativePath}:${u.line}`;c.has(d)||(c.add(d),l.push(u))}return l}function uM(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=dM(t.symbol);if(n.length===0)return[];let r=[];for(let i of Z(e,{extensions:[".rb"],includeIgnored:!1})){let o=W(e,i);if(!o)continue;let s=o.split(`
52
- `);for(let a=0;a<s.length;a++){let c=s[a]??"";n.some(l=>new RegExp(`@${l}\\b|\\b${l}:`).test(c))&&r.push({relativePath:i,line:a})}}return r}function dM(e){let n=(e.split(":").pop()??e).replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),r=n.split("_").filter(Boolean),i=new Set;return n&&i.add(n),r.length>=1&&i.add(r[r.length-1]),r.length>=2&&i.add(r.slice(-2).join("_")),[...i]}import{existsSync as zu,statSync as jT}from"fs";import{join as HT}from"path";import{existsSync as Ri}from"fs";import{randomUUID as Wy}from"crypto";import{isAbsolute as qM,join as vn,relative as GM,resolve as zM}from"path";var Xn=1,Qn=2,mM="./node_modules/scip-query/docs/schemas/project-config.schema.json";function Au(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(!Q(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?Xn:n;if(r!==Xn&&r!==Qn)return{kind:"unsupported",schemaVersion:r,direction:r<Xn?"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=La(t),s=r!==Qn||typeof t.$schema!="string";return r===Xn?{kind:"legacy",sourceVersion:Xn,config:o,needsMigration:s}:{kind:"supported",sourceVersion:Qn,config:o,needsMigration:s}}function La(e){let t=e,{$schema:n,schemaVersion:r,...i}=t;return{$schema:typeof n=="string"&&n.trim()!==""?n:mM,schemaVersion:Qn,...i}}function xi(e){return`${JSON.stringify(La(e),null,2)}
53
- `}import{createHash as pM}from"crypto";var Xt=1,er=2,Ny=1,Ou=1,_u="sha256",fM=1;function Tr(e,t,n){if(!Nt(e)||!Ms(t))throw new Error("Observation identity requires a bounded projection name and positive projection version.");return{schemaVersion:Ny,canonicalizationVersion:Ou,hashAlgorithm:_u,projection:{name:e,version:t},digest:pM(_u).update(gM(e,t,n)).digest("hex")}}function gM(e,t,n){return`{"canonicalizationVersion":${Ou},"projection":${JSON.stringify(e)},"projectionVersion":${t},"value":${JSON.stringify(n)}}`}function hM(e){if(!Q(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===Xt)return RM(e)?{kind:"legacy",schemaVersion:Xt,receipt:e}:{kind:"malformed",reason:"observation receipt v1 fields are malformed or contradictory"};if(t===er)return EM(e)?{kind:"supported",schemaVersion:er,receipt:e}:{kind:"malformed",reason:"observation receipt v2 facts are malformed or contradictory"};let n=t;return{kind:"unsupported",schemaVersion:n,direction:n<Xt?"older":"future"}}function Pa(e){let t=hM(e);return t.kind==="legacy"||t.kind==="supported"}function yM(e,t){return{collaborationDomain:Mr(Jt(e,n=>n.facts.collaborationDomain),Jt(t,n=>n.facts.collaborationDomain)),repositoryLineage:Mr(Jt(e,n=>n.facts.repositoryLineage),Jt(t,n=>n.facts.repositoryLineage)),workspaceInstance:Mr(Jt(e,n=>n.facts.workspaceInstance),Jt(t,n=>n.facts.workspaceInstance)),wholeContent:Mr(Jt(e,n=>n.facts.wholeContent),Jt(t,n=>n.facts.wholeContent)),relevantInputs:bM(e,t),indexInput:Mr(Jt(e,n=>n.facts.index?.inputs),Jt(t,n=>n.facts.index?.inputs)),indexGeneration:SM(e,t),observationStability:CM(e,t)}}function d8(e,t,n=yM(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=xM(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:fM,authority:i.length===0?"completion":o?"none":"advisory",requiredRelationships:["collaborationDomain","wholeContent","observationStability"],reasons:i}}function bM(e,t){let n=Ty(e),r=Ty(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,l=s?.identity.projection.name??a?.identity.projection.name??o;return{subject:c,projection:l,judgment:Mr(s?.identity,a?.identity)}})}function Ty(e){return e.schemaVersion!==er?new Map:new Map((e.facts.relevantInputs??[]).map(t=>[`${t.subject}\0${t.identity.projection.name}`,t]))}function SM(e,t){return e.schemaVersion===Xt&&t.schemaVersion===Xt?vM(e.index?.generationIdentity,t.index?.generationIdentity):e.schemaVersion===Xt||t.schemaVersion===Xt?Sn("unknown",["legacy-fact-not-comparable"],Ay(e),Ay(t)):Mr(e.facts.index?.generation,t.facts.index?.generation)}function vM(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?_y(n,r):Sn(e===t?"established":"disproven",[e===t?"identities-equal":"identities-different"],n,r)}function Mr(e,t){let n=e?[{kind:"identity",identity:e}]:[],r=t?[{kind:"identity",identity:t}]:[];return!e||!t?_y(n,r):Bu(e,t)?Sn(e.digest===t.digest?"established":"disproven",[e.digest===t.digest?"identities-equal":"identities-different"],n,r):Sn("unknown",["identity-projections-not-comparable"],n,r)}function CM(e,t){if(e.schemaVersion===Xt||t.schemaVersion===Xt)return Sn("unknown",["legacy-fact-not-comparable"],[],[]);let n=Fy(e),r=Fy(t),i=ky(e),o=ky(t);return i==="invalidated"||o==="invalidated"?Sn("disproven",[...i==="invalidated"?["left-observation-invalidated"]:[],...o==="invalidated"?["right-observation-invalidated"]:[]],n,r):i!=="fixed"||o!=="fixed"?Sn("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):Sn("established",["all-observed-sources-fixed"],n,r)}function ky(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 xM(e){if(e.schemaVersion!==er)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=>Bu(r.identity,t))?.identity;return n?n.digest===t.digest?"established":"disproven":"unknown"}function Jt(e,t){return e.schemaVersion===er?t(e):void 0}function Ay(e){return e.schemaVersion===Xt&&e.index?[{kind:"legacy-index-generation",value:e.index.generationIdentity}]:e.schemaVersion===er&&e.facts.index?[{kind:"identity",identity:e.facts.index.generation}]:[]}function Fy(e){return e.stabilityProofs.map(t=>({kind:"stability",proof:t}))}function _y(e,t){let n=e.length===0&&t.length===0?"both-facts-missing":e.length===0?"left-fact-missing":"right-fact-missing";return Sn("unknown",[n],e,t)}function Sn(e,t,n,r){return{state:e,reasons:t,facts:{left:n,right:r}}}function Bu(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 RM(e){if(!Q(e))return!1;let t=e.index,n=e.worktree;return By(e.observedAt)&&Nt(e.projectIdentity)&&TM(e.authorityKind)&&(t===void 0||Q(t)&&Nt(t.generationIdentity)&&(t.source==="immutable"||t.source==="legacy")&&(t.alignment==="not-certified"||t.alignment==="leased"))&&(n===void 0||Q(n)&&Nt(n.identity)&&typeof n.clean=="boolean"&&(n.headCommit===void 0||Nt(n.headCommit))&&(n.treeOid===void 0||Nt(n.treeOid)))&&MM(e.authorityKind,t,n)}function EM(e){if(!Q(e))return!1;let t=e.facts,n=e.observedSources,r=e.stabilityProofs;if(!By(e.observedAt)||!Q(t)||!Array.isArray(n)||n.length===0||!n.every(wM)||!Nu(n,c=>c.kind)||!Array.isArray(r)||!r.every(LM)||!Nu(r,c=>c.source)||r.some(c=>!n.some(l=>l.kind===c.source))||!r.every(c=>DM(c,t))||["collaborationDomain","repositoryLineage","workspaceInstance","wholeContent"].some(c=>t[c]!==void 0&&!Zn(t[c])))return!1;let o=t.relevantInputs;if(o!==void 0&&(!Array.isArray(o)||!o.every(IM)||!Nu(o,c=>`${c.subject}\0${c.identity.projection.name}`)))return!1;let s=t.index;if(s!==void 0&&(!Q(s)||!Zn(s.generation)||s.inputs!==void 0&&!Zn(s.inputs)||s.source!=="immutable"&&s.source!=="legacy"))return!1;let a=e.diagnostics;return(a===void 0||Q(a)&&(a.clean===void 0||typeof a.clean=="boolean")&&(a.headCommit===void 0||Nt(a.headCommit))&&(a.treeOid===void 0||Nt(a.treeOid)))&&PM(t,n)}function Zn(e){return!Q(e)||!Q(e.projection)?!1:e.schemaVersion===Ny&&e.canonicalizationVersion===Ou&&e.hashAlgorithm===_u&&Nt(e.projection.name)&&Ms(e.projection.version)&&Zr(e.digest)}function IM(e){return Q(e)&&Nt(e.subject)&&Zn(e.identity)}function wM(e){return Q(e)&&Oy(e.kind)&&(e.identity===void 0||Zn(e.identity))}function LM(e){return Q(e)&&Oy(e.source)&&(e.kind==="immutable"||e.kind==="fixed-snapshot"||e.kind==="bracketed"||e.kind==="not-established"||e.kind==="invalidated")}function PM(e,t){let n=e.index,r=t.find(c=>c.kind==="index-generation");if(r){if(!Q(n)||!Zn(n.generation)||r.identity&&!Fu(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&&(!Zn(i)||!Fu(o.identity,i)))return!1;let s=e.wholeContent,a=t.find(c=>c.kind==="repository-snapshot");return!(a?.identity&&(!Zn(s)||!Fu(a.identity,s)))}function DM(e,t){return e.kind==="not-established"||e.kind==="invalidated"?!0:e.source==="index-generation"?e.kind==="immutable"&&Q(t.index)&&t.index.source==="immutable":e.source==="repository-snapshot"?e.kind==="fixed-snapshot":e.source==="live-workspace"?e.kind==="bracketed":!1}function Fu(e,t){return Bu(e,t)&&e.digest===t.digest}function MM(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 TM(e){return e==="index-worktree"||e==="index-only"||e==="worktree-only"||e==="process-local"}function Oy(e){return e==="index-generation"||e==="repository-snapshot"||e==="live-workspace"||e==="process"}function By(e){return typeof e=="string"&&!Number.isNaN(Date.parse(e))}function Nu(e,t){return new Set(e.map(t)).size===e.length}function Da(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.kind==="automated-adjudication"&&t.policyVersion===1&&(t.decidedBy==="agent"||t.decidedBy==="human")&&Xp.includes(t.reasonCode)&&Array.isArray(t.evidence)&&t.evidence.length>0&&t.evidence.every(kM)&&(t.observation===void 0||Pa(t.observation))&&!!t.invalidateOn&&typeof t.invalidateOn=="object"&&typeof t.invalidateOn.targetContentChange=="boolean"&&typeof t.invalidateOn.detectorMajorChange=="boolean"}function kM(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return(t.kind==="source"||t.kind==="config"||t.kind==="test"||t.kind==="graph")&&typeof t.referent=="string"&&t.referent.trim()!==""&&typeof t.claim=="string"&&t.claim.trim()!==""&&(t.contentHash===void 0||/^[a-f0-9]{64}$/u.test(t.contentHash))&&(t.generation===void 0||typeof t.generation=="string"&&t.generation.length>0)}var Ma=class extends Error{constructor(n,r,i){super(`${n} is ${r} characters; the safety limit is ${i} characters`);this.inputKind=n;this.observedCharacters=r;this.limitCharacters=i;this.name="RegExpPatternBudgetError"}inputKind;observedCharacters;limitCharacters;code="SCIP_QUERY_REGEXP_PATTERN_BUDGET"};function kr(e,t,n,r=4096){if(!Number.isSafeInteger(r)||r<0)throw new RangeError(`maxCharacters must be a non-negative safe integer; received ${r}`);if(e.length>r)throw new Ma(t,e.length,r);return new RegExp(e,n)}import{createHash as $y}from"crypto";import{closeSync as AM,fstatSync as jy,openSync as FM,rmSync as NM}from"fs";import{dirname as _M}from"path";var OM=2e3,BM=10,$M=3,ka=class extends Error{constructor(n,r,i){super(`Concurrent edit detected for ${n}; expected revision ${Uy(r)}, but found ${Uy(i)}. The latest file was left untouched.`);this.path=n;this.original=r;this.latest=i;this.name="FileRevisionConflictError"}path;original;latest},Do=class extends Error{constructor(n,r){super(`Concurrent edit detected for ${n}: ${r} changed since it was read. The latest file was left untouched; reload it and retry.`);this.path=n;this.field=r;this.name="FileContentConflictError"}path;field};function Mo(e,t,n={}){let r=jM(e,n.lockTimeoutMs??OM,n.monotonicNow??Lt);try{let i=Math.max(0,Math.floor(n.maxRetries??$M));for(let o=0;;o+=1){let s=Ta(e),a=t(s,o);if(a.kind==="unchanged")return{changed:!1,attempts:o+1,previous:s,current:s};n.onBeforeCommit?.({attempt:o,snapshot:s,mutation:a});let c=Ta(e);if(!UM(s.revision,c.revision)){if(o<i)continue;throw new ka(e,s.revision,c.revision)}try{HM(e,a,s.revision)}catch(l){if(l.code==="EEXIST"){let u=Ta(e);if(o<i)continue;throw new ka(e,s.revision,u.revision)}throw l}return{changed:!0,attempts:o+1,previous:s,current:Ta(e)}}}finally{r.release()}}function Ta(e){for(let t=0;t<4;t+=1){let n;try{n=FM(e,"r");let r=Hy(jy(n)),i=Bp(n,{maxBytes:dn,inputKind:"revisioned text file"}),o=Hy(jy(n));if(!qy(r,o))continue;return{path:e,text:i,revision:{exists:!0,hash:$y("sha256").update(i).digest("hex"),identity:o}}}catch(r){if(r.code==="ENOENT")return{path:e,text:"",revision:{exists:!1,hash:$y("sha256").update("").digest("hex")}};throw r}finally{n!==void 0&&AM(n)}}throw new Error(`Could not read a stable revision of ${e}; the file is changing continuously.`)}function jM(e,t,n){let r=`${e}.scip-query-write.lock`,i=n()+Math.max(0,t);for(;;){let o=ui(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,BM)}}function HM(e,t,n){if(t.kind==="delete"){if(!n.exists)return;NM(e),Gp(_M(e));return}let r=t.mode??n.identity?.mode;n.exists?Ff(e,t.text,{durability:"durable",mode:r}):Nf(e,t.text,{durability:"durable",mode:r})}function UM(e,t){return e.exists===t.exists&&e.hash===t.hash&&(e.identity===void 0?t.identity===void 0:t.identity!==void 0&&qy(e.identity,t.identity))}function Hy(e){return{dev:e.dev,ino:e.ino,size:e.size,mtimeMs:e.mtimeMs,mode:e.mode&511}}function qy(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.size===t.size&&e.mtimeMs===t.mtimeMs&&e.mode===t.mode}function Uy(e){return e.exists?e.hash.slice(0,12):"<absent>"}var tr=".scipquery.json",Vy=2e3,Aa=5e3,$u=Aa,Yy=15*6e4,ju={enabled:!0,windowMs:15*6e4,maxRebuilds:2,maxEstimatedWriteBytes:1024*1024*1024},KM={enabled:!1,autoStart:!1,allowExpensiveRebuild:!1,debounceMs:Vy,cooldownMs:$u,gitPollMs:2e3,idleTimeoutMs:Yy,autoRefresh:!0,ignore:[],resourceBudget:ju};var WM=new Set(["$schema","schemaVersion","collaborationDomainId","languages","indexerConcurrency","watch","indexer","dbPath","entryRoots","semantic","suppressions","declaredCouplings","locality","architecture","coverageContracts","docs"]),VM=new Set(["enabled","autoStart","allowExpensiveRebuild","debounceMs","cooldownMs","gitPollMs","idleTimeoutMs","autoRefresh","ignore","resourceBudget"]),YM=new Set(["enabled","windowMs","maxRebuilds","maxEstimatedWriteBytes"]),JM=new Set(["pathPrefixes","files","symbolPatterns","qualifiedVars"]),XM=new Set(["typescript","rust"]),QM=new Set(["tsconfigs"]),ZM=new Set(["rustAnalyzerPath"]),Gy=new Set(yl),eT=new Set(["pnpmWorkspaces","projectMode","projects","configPath","maxWarmSessions","workerIdleMs","workerSoftMemoryMb","workerHeapMb","maxHeapMb"]),tT=new Set(["architecturalBoundarySegments"]),nT=new Set(["boundaries","allowedDependencies","requireCompletePolicy","requireCompleteCoverage","requireAcyclic","requireResolvedBoundaries","requireMinimalPolicy","maxBoundaryFanOut","maxBoundaryFiles","testPaths"]),rT=new Set(["name","paths","subUnits","maxFiles"]),iT=new Set(["snapshotPaths"]),oT=new Set(["name","files","reason"]),sT=new Set(["id","check","file","reason","expiresAt","createdAt","decision"]),aT=new Set(["kind","reasonCode","decidedBy","policyVersion","observation","evidence","invalidateOn"]),cT=new Set(["kind","referent","claim","contentHash","generation"]),lT=new Set(["targetContentChange","detectorMajorChange"]),uT=new Set(["name","file","keys","mustEqual","allowExtra"]),dT=new Set(["type","identifier","marker"]),mT=new Set(["type","path","pattern"]),pT=new Set(["object-literal-keys","string-array","markdown-list"]),fT=new Set(["top-level-dirs","file-glob","registered-commands","builtin-skills"]);function Jy(e){let t=vn(e,tr);if(!Ri(t))return{};let n;try{n=vt(t,{maxBytes:Ls,inputKind:"scip-query project config"})}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`unable to read ${tr} at ${t}: ${i}`,{cause:r})}return Qy(Au(n),t,"read").config}function B8(e,t={}){let n=[];return IT(e,n),gT(e,n),hT(e,n),yT(e,n,t),bT(e,n),CT(e,n),ST(e,n,t),vT(e,n,t),ET(e,n,t),RT(e,n),n}function zy(e,t,n,r,i){if(!r)return;let o=zM(r,n),s=GM(r,o);if(s.startsWith("..")||qM(s)){e.push({level:"error",path:t,message:i.outside});return}Ri(o)||e.push({level:"warning",path:t,message:i.missing})}function gT(e,t){let n=e;n.schemaVersion!==void 0&&n.schemaVersion!==Qn&&t.push({level:"error",path:"schemaVersion",message:`Must be ${Qn}; unversioned and v${Xn} files are migrated while loading.`}),n.$schema!==void 0&&(typeof n.$schema!="string"||n.$schema.trim()==="")&&t.push({level:"error",path:"$schema",message:"Must be a non-empty string."}),e.collaborationDomainId!==void 0&&!/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(e.collaborationDomainId)&&t.push({level:"error",path:"collaborationDomainId",message:"Must be a lowercase or uppercase UUID v4 generated for this collaboration domain."});let r=new Set(yl);for(let[i,o]of(e.languages??[]).entries())r.has(o)||t.push({level:"error",path:`languages[${i}]`,message:`Unsupported language: ${o}`});for(let[i,o]of(e.entryRoots?.symbolPatterns??[]).entries())try{kr(o,`entryRoots.symbolPatterns[${i}]`)}catch(s){t.push({level:"error",path:`entryRoots.symbolPatterns[${i}]`,message:s instanceof Error?s.message:String(s)})}e.indexerConcurrency!==void 0&&(!Number.isInteger(e.indexerConcurrency)||e.indexerConcurrency<=0)&&t.push({level:"error",path:"indexerConcurrency",message:"Must be a positive integer."})}function hT(e,t){e.watch?.debounceMs!==void 0&&e.watch.debounceMs<=0&&t.push({level:"error",path:"watch.debounceMs",message:"Must be greater than 0."}),e.watch?.cooldownMs!==void 0&&(!Number.isInteger(e.watch.cooldownMs)||e.watch.cooldownMs<0)?t.push({level:"error",path:"watch.cooldownMs",message:"Must be a non-negative integer."}):e.watch?.cooldownMs!==void 0&&e.watch.cooldownMs<Aa&&t.push({level:"warning",path:"watch.cooldownMs",message:`Values below ${Aa}ms are raised to the safety floor at runtime.`}),e.watch?.gitPollMs!==void 0&&e.watch.gitPollMs<=0&&t.push({level:"error",path:"watch.gitPollMs",message:"Must be greater than 0."}),e.watch?.idleTimeoutMs!==void 0&&(!Number.isInteger(e.watch.idleTimeoutMs)||e.watch.idleTimeoutMs<0)&&t.push({level:"error",path:"watch.idleTimeoutMs",message:"Must be a non-negative integer; 0 disables idle shutdown."}),e.watch?.autoStart!==void 0&&typeof e.watch.autoStart!="boolean"&&t.push({level:"error",path:"watch.autoStart",message:"Must be a boolean."}),e.watch?.allowExpensiveRebuild!==void 0&&typeof e.watch.allowExpensiveRebuild!="boolean"&&t.push({level:"error",path:"watch.allowExpensiveRebuild",message:"Must be a boolean."}),e.watch?.autoRefresh!==void 0&&typeof e.watch.autoRefresh!="boolean"&&t.push({level:"error",path:"watch.autoRefresh",message:"Must be a boolean."});let n=e.watch?.resourceBudget;n?.enabled!==void 0&&typeof n.enabled!="boolean"&&t.push({level:"error",path:"watch.resourceBudget.enabled",message:"Must be a boolean."});for(let[r,i]of[["windowMs",n?.windowMs],["maxRebuilds",n?.maxRebuilds],["maxEstimatedWriteBytes",n?.maxEstimatedWriteBytes]])i!==void 0&&(!Number.isSafeInteger(i)||i<=0)&&t.push({level:"error",path:`watch.resourceBudget.${r}`,message:"Must be a positive safe integer."})}function yT(e,t,n){let r=e.indexer?.typescript;if(r?.projectMode!==void 0&&r.projectMode!=="single"&&r.projectMode!=="workspace"&&t.push({level:"error",path:"indexer.typescript.projectMode",message:'Must be "single" or "workspace".'}),r?.projects!==void 0)if(!Array.isArray(r.projects))t.push({level:"error",path:"indexer.typescript.projects",message:"Must be an array."});else for(let[s,a]of r.projects.entries()){let c=`indexer.typescript.projects[${s}]`;typeof a!="string"||a.trim()===""?t.push({level:"error",path:c,message:"Project path must be a non-empty string."}):zy(t,c,a,n.projectRoot,{outside:"Project path must stay inside the project root.",missing:`TypeScript project path does not exist: ${a}`})}r?.projectMode==="workspace"&&r.pnpmWorkspaces===!0&&t.push({level:"warning",path:"indexer.typescript.pnpmWorkspaces",message:'Ignored when projectMode is "workspace"; explicit TypeScript projects are indexed directly.'});for(let[s,a]of[["maxWarmSessions",r?.maxWarmSessions],["workerSoftMemoryMb",r?.workerSoftMemoryMb],["workerHeapMb",r?.workerHeapMb],["maxHeapMb",r?.maxHeapMb]])a!==void 0&&(!Number.isInteger(a)||a<=0)&&t.push({level:"error",path:`indexer.typescript.${s}`,message:"Must be a positive integer."});r?.workerIdleMs!==void 0&&(!Number.isInteger(r.workerIdleMs)||r.workerIdleMs<0)&&t.push({level:"error",path:"indexer.typescript.workerIdleMs",message:"Must be a non-negative integer."});let i=e.semantic?.rust;i?.rustAnalyzerPath!==void 0&&(typeof i.rustAnalyzerPath!="string"||i.rustAnalyzerPath.trim()==="")&&t.push({level:"error",path:"semantic.rust.rustAnalyzerPath",message:"Rust analyzer path must be a non-empty string."});let o=e.indexer?.clojure;if(o?.configPath!==void 0){let s="indexer.clojure.configPath";typeof o.configPath!="string"||o.configPath.trim()===""?t.push({level:"error",path:s,message:"Config path must be a non-empty string."}):zy(t,s,o.configPath,n.projectRoot,{outside:"Config path must stay inside the project root.",missing:`Clojure indexer config path does not exist: ${o.configPath}`})}}function bT(e,t){if(e.locality===void 0)return;if(!Q(e.locality)){t.push({level:"error",path:"locality",message:"Must be an object."});return}let n=e.locality.architecturalBoundarySegments;if(n!==void 0){if(!Array.isArray(n)){t.push({level:"error",path:"locality.architecturalBoundarySegments",message:"Must be an array."});return}for(let[r,i]of n.entries()){let o=`locality.architecturalBoundarySegments[${r}]`;typeof i!="string"||i.trim()===""?t.push({level:"error",path:o,message:"Boundary segment must be a non-empty string."}):(i.includes("/")||i.includes("\\"))&&t.push({level:"error",path:o,message:"Boundary segment must be a single folder name, not a path."})}}}function ST(e,t,n){if(e.declaredCouplings!==void 0&&!Array.isArray(e.declaredCouplings)){t.push({level:"error",path:"declaredCouplings",message:"Must be an array."});return}for(let[r,i]of(e.declaredCouplings??[]).entries()){let o=`declaredCouplings[${r}]`;if((!i.name||i.name.trim()==="")&&t.push({level:"error",path:`${o}.name`,message:"Declared coupling name is required."}),!Array.isArray(i.files)||i.files.length<2)t.push({level:"error",path:`${o}.files`,message:"Declared coupling needs at least two files."});else for(let[s,a]of i.files.entries())!a||a.trim()===""?t.push({level:"error",path:`${o}.files[${s}]`,message:"Declared coupling file path is required."}):n.projectRoot&&!Ri(vn(n.projectRoot,a))&&t.push({level:"warning",path:`${o}.files[${s}]`,message:`Declared coupling file does not exist: ${a}`});i.reason!==void 0&&i.reason.trim()===""&&t.push({level:"error",path:`${o}.reason`,message:"Declared coupling reason cannot be blank."})}}function vT(e,t,n){let r=n.now??new Date;e.suppressions!==void 0&&!Array.isArray(e.suppressions)&&t.push({level:"error",path:"suppressions",message:"Must be an array."});for(let[i,o]of(Array.isArray(e.suppressions)?e.suppressions:[]).entries()){let s=`suppressions[${i}]`;if(!Q(o)){t.push({level:"error",path:s,message:"Suppression must be an object."});continue}if((!o.reason||o.reason.trim()==="")&&t.push({level:"error",path:`${s}.reason`,message:"Suppression reason is required."}),o.id!==void 0&&o.id.trim()===""&&t.push({level:"error",path:`${s}.id`,message:"Suppression id cannot be blank."}),o.check!==void 0&&o.check.trim()===""&&t.push({level:"error",path:`${s}.check`,message:"Suppression check cannot be blank."}),!o.id&&(!o.check||!o.file)?t.push({level:"error",path:s,message:"Suppression must include id or both check and file."}):!o.id&&o.check&&o.file&&t.push({level:"warning",path:s,message:"Check+file suppressions waive every matching finding in that file; prefer a stable id when available."}),o.file!==void 0&&(o.file.trim()===""?t.push({level:"error",path:`${s}.file`,message:"Suppression file path cannot be blank."}):n.projectRoot&&!Ri(vn(n.projectRoot,o.file))&&t.push({level:"warning",path:`${s}.file`,message:`Suppression file does not exist: ${o.file}`})),o.expiresAt){let a=Date.parse(o.expiresAt);Number.isNaN(a)?t.push({level:"error",path:`${s}.expiresAt`,message:"Must be an ISO date string."}):a<=r.getTime()&&t.push({level:"warning",path:`${s}.expiresAt`,message:"Suppression has expired."})}if(o.decision!==void 0&&!Da(o.decision))t.push({level:"error",path:`${s}.decision`,message:"Must be a valid automated-adjudication decision with reason code, evidence, and invalidation rules."});else if(o.decision&&n.projectRoot)for(let[a,c]of o.decision.evidence.entries())c.kind!=="graph"&&!Ri(vn(n.projectRoot,c.referent))&&t.push({level:"error",path:`${s}.decision.evidence[${a}].referent`,message:`Suppression counterevidence does not exist: ${c.referent}`})}}function CT(e,t){if(e.architecture===void 0)return;if(!Q(e.architecture)){t.push({level:"error",path:"architecture",message:"Must be an object."});return}let n=e.architecture.boundaries;if(!Array.isArray(n)||n.length===0){t.push({level:"error",path:"architecture.boundaries",message:"Must be a non-empty array."});return}let r=new Set,i=new Set;for(let[a,c]of n.entries()){let l=`architecture.boundaries[${a}]`;if(!Q(c)){t.push({level:"error",path:l,message:"Architecture boundary must be an object."});continue}let u=c.name;typeof u!="string"||u.trim()===""?t.push({level:"error",path:`${l}.name`,message:"Boundary name is required."}):r.has(u)?t.push({level:"error",path:`${l}.name`,message:`Duplicate boundary name: ${u}`}):r.add(u);let d=c.subUnits;d!==void 0&&d!=="directory"&&d!=="file"&&t.push({level:"error",path:`${l}.subUnits`,message:"Must be 'directory' or 'file'."});let m=c.maxFiles;m!==void 0&&(typeof m!="number"||!Number.isInteger(m)||m<0)&&t.push({level:"error",path:`${l}.maxFiles`,message:"Must be a non-negative integer."});let p=c.paths;if(!Array.isArray(p)||p.length===0){t.push({level:"error",path:`${l}.paths`,message:"Boundary paths must be a non-empty array."});continue}for(let[f,g]of p.entries()){let h=`${l}.paths[${f}]`;if(typeof g!="string"||g.trim()===""){t.push({level:"error",path:h,message:"Boundary path must be a non-empty string."});continue}xT(g)||t.push({level:"error",path:h,message:"Boundary path must be project-relative and may use only one trailing /* or /** glob."}),i.has(g)?t.push({level:"error",path:h,message:`Duplicate boundary path: ${g}`}):i.add(g)}}let o=e.architecture.allowedDependencies;if(o!==void 0&&!Q(o))t.push({level:"error",path:"architecture.allowedDependencies",message:"Must be an object keyed by boundary name."});else if(Q(o))for(let[a,c]of Object.entries(o)){let l=`architecture.allowedDependencies.${a}`;if(r.has(a)||t.push({level:"error",path:l,message:`Unknown source boundary: ${a}`}),!Array.isArray(c)){t.push({level:"error",path:l,message:"Dependency row must be an array."});continue}let u=new Set;for(let[d,m]of c.entries()){let p=`${l}[${d}]`;typeof m!="string"||m.trim()===""?t.push({level:"error",path:p,message:"Target boundary name is required."}):r.has(m)?u.has(m)?t.push({level:"error",path:p,message:`Duplicate target boundary: ${m}`}):u.add(m):t.push({level:"error",path:p,message:`Unknown target boundary: ${m}`})}}e.architecture.requireAcyclic!==void 0&&typeof e.architecture.requireAcyclic!="boolean"&&t.push({level:"error",path:"architecture.requireAcyclic",message:"Must be a boolean."});for(let a of["requireCompleteCoverage","requireResolvedBoundaries","requireMinimalPolicy"])e.architecture[a]!==void 0&&typeof e.architecture[a]!="boolean"&&t.push({level:"error",path:`architecture.${a}`,message:"Must be a boolean."});for(let a of["maxBoundaryFanOut","maxBoundaryFiles"]){let c=e.architecture[a];c!==void 0&&(typeof c!="number"||!Number.isInteger(c)||c<0)&&t.push({level:"error",path:`architecture.${a}`,message:"Must be a non-negative integer."})}let s=e.architecture.testPaths;if(s!==void 0&&(!Array.isArray(s)||s.some(a=>typeof a!="string"))&&t.push({level:"error",path:"architecture.testPaths",message:"Must be an array of strings."}),e.architecture.requireCompletePolicy!==void 0&&typeof e.architecture.requireCompletePolicy!="boolean")t.push({level:"error",path:"architecture.requireCompletePolicy",message:"Must be a boolean."});else if(e.architecture.requireCompletePolicy===!0){let a=Q(o)?o:{};for(let c of[...r].sort())Object.hasOwn(a,c)||t.push({level:"error",path:`architecture.allowedDependencies.${c}`,message:"A dependency row is required by architecture.requireCompletePolicy."})}}function xT(e){let t=e.replace(/\\/g,"/");if(t.startsWith("/")||t==="."||t===".."||t.split("/").includes(".."))return!1;let n=t.replace(/\/\*\*?$/,"");return n.length>0&&!/[*?[\]]/.test(n)}function RT(e,t){let n=e.docs?.snapshotPaths;if(n!==void 0){if(!Array.isArray(n)){t.push({level:"error",path:"docs.snapshotPaths",message:"Must be an array."});return}for(let[r,i]of n.entries())(typeof i!="string"||i.trim()==="")&&t.push({level:"error",path:`docs.snapshotPaths[${r}]`,message:"Snapshot path glob must be a non-empty string."})}}function ET(e,t,n){if(e.coverageContracts!==void 0){if(!Array.isArray(e.coverageContracts)){t.push({level:"error",path:"coverageContracts",message:"Must be an array."});return}for(let[r,i]of e.coverageContracts.entries()){let o=`coverageContracts[${r}]`;if(!Q(i)){t.push({level:"error",path:o,message:"Coverage contract must be an object."});continue}(typeof i.name!="string"||i.name.trim()==="")&&t.push({level:"error",path:`${o}.name`,message:"Coverage contract name is required."}),typeof i.file!="string"||i.file.trim()===""?t.push({level:"error",path:`${o}.file`,message:"Coverage contract file is required."}):n.projectRoot&&!Ri(vn(n.projectRoot,i.file))&&t.push({level:"warning",path:`${o}.file`,message:`Coverage contract file does not exist: ${i.file}`}),Ky(t,i.keys,`${o}.keys`,pT,"Unknown coverage-contract key extractor type."),Ky(t,i.mustEqual,`${o}.mustEqual`,fT,"Unknown coverage-contract ground-truth source type."),i.allowExtra!==void 0&&typeof i.allowExtra!="boolean"&&t.push({level:"error",path:`${o}.allowExtra`,message:"Must be a boolean."})}}}function Ky(e,t,n,r,i){if(!Q(t)){e.push({level:"error",path:n,message:'Must be an object with a "type" field.'});return}if(typeof t.type!="string"||!r.has(t.type)){e.push({level:"error",path:`${n}.type`,message:`${i} Got: ${String(t.type)}`});return}let o={"object-literal-keys":["identifier"],"string-array":["identifier"],"markdown-list":["marker"],"top-level-dirs":["path"],"file-glob":["pattern"],"registered-commands":[],"builtin-skills":[]};for(let s of o[t.type]??[])(typeof t[s]!="string"||t[s].length===0)&&e.push({level:"error",path:`${n}.${s}`,message:`"${t.type}" requires a non-empty string "${s}".`})}function $8(e){return{...KM,...e.watch,cooldownMs:Math.max(Aa,e.watch?.cooldownMs??$u),resourceBudget:{...ju,...e.watch?.resourceBudget}}}function j8(e,t){let n=vn(e,tr),r=Wy(),i={collaborationDomainId:r,languages:t,watch:{enabled:!0,debounceMs:Vy,cooldownMs:$u,gitPollMs:2e3,idleTimeoutMs:Yy,autoRefresh:!0,resourceBudget:{...ju}}},o=Mo(n,s=>{if(!s.revision.exists)return{kind:"write",text:xi(i)};let a=Na(s,i);return a.config.collaborationDomainId?{kind:"unchanged"}:{kind:"write",text:xi({...a.config,collaborationDomainId:r})}});return{configPath:n,changed:o.changed}}function H8(e,t,n=Wy()){let r=vn(e,tr),i=t,o=Mo(r,s=>{let a=Na(s,t);if(a.config.collaborationDomainId)return i=a.config,{kind:"unchanged"};let c={...a.config,collaborationDomainId:n};return i=c,{kind:"write",text:xi(c)}});return{configPath:r,config:i,changed:o.changed}}function U8(e,t,n){let r=vn(e,tr),i=[...n],o=t,s=Mo(r,a=>{let c=Na(a,t);if(Xy(t.languages,c.config.languages,i))throw new Do(r,"languages");let l={...c.config,languages:i};return o=l,a.revision.exists&&!c.needsMigration&&Fa(l,c.config)?{kind:"unchanged"}:{kind:"write",text:xi(l)}});return{configPath:r,config:o,changed:s.changed}}function q8(e,t,n){let r=vn(e,tr),i=t,o=Mo(r,s=>{let a=Na(s,t);if(Xy(t.watch?.enabled,a.config.watch?.enabled,n))throw new Do(r,"watch.enabled");let c={...a.config,watch:{...a.config.watch,enabled:n,...n&&a.config.watch?.autoRefresh===void 0?{autoRefresh:!0}:{}}};return i=c,s.revision.exists&&!a.needsMigration&&Fa(c,a.config)?{kind:"unchanged"}:{kind:"write",text:xi(c)}});return{configPath:r,config:i,changed:o.changed}}function Na(e,t){if(!e.revision.exists)return{config:La(t),needsMigration:!0};let n=Qy(Au(e.text),e.path,"update");return{config:n.config,needsMigration:n.needsMigration}}function Fa(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Xy(e,t,n){return!Fa(e,t)&&!Fa(t,n)}function Qy(e,t,n){if(e.kind==="legacy"||e.kind==="supported")return e;if(e.kind==="malformed"){let i=n==="read"?`invalid ${tr} 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 ${tr} 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${Xn} and current v${Qn}). Upgrade scip-query before retrying; the file was left untouched.`)}function IT(e,t){if(!Q(e))return;let n=e;if(Re(t,n,"",WM),Re(t,n.watch,"watch",VM),Re(t,n.watch?.resourceBudget,"watch.resourceBudget",YM),Re(t,n.entryRoots,"entryRoots",JM),Re(t,n.semantic,"semantic",XM),Re(t,n.semantic?.typescript,"semantic.typescript",QM),Re(t,n.semantic?.rust,"semantic.rust",ZM),Re(t,n.locality,"locality",tT),Re(t,n.architecture,"architecture",nT),Re(t,n.docs,"docs",iT),Array.isArray(n.architecture?.boundaries))for(let[r,i]of n.architecture.boundaries.entries())Re(t,i,`architecture.boundaries[${r}]`,rT);if(Q(n.indexer)){Re(t,n.indexer,"indexer",Gy);for(let[r,i]of Object.entries(n.indexer))Gy.has(r)&&Re(t,i,`indexer.${r}`,eT)}if(Array.isArray(n.declaredCouplings))for(let[r,i]of n.declaredCouplings.entries())Re(t,i,`declaredCouplings[${r}]`,oT);if(Array.isArray(n.suppressions)){for(let[r,i]of n.suppressions.entries())if(Re(t,i,`suppressions[${r}]`,sT),Q(i.decision)){if(Re(t,i.decision,`suppressions[${r}].decision`,aT),Array.isArray(i.decision.evidence))for(let[o,s]of i.decision.evidence.entries())Re(t,s,`suppressions[${r}].decision.evidence[${o}]`,cT);Re(t,i.decision.invalidateOn,`suppressions[${r}].decision.invalidateOn`,lT)}}if(Array.isArray(n.coverageContracts))for(let[r,i]of n.coverageContracts.entries()){let o=`coverageContracts[${r}]`;Re(t,i,o,uT),Q(i)&&(Re(t,i.keys,`${o}.keys`,dT),Re(t,i.mustEqual,`${o}.mustEqual`,mT))}}function Re(e,t,n,r){if(Q(t))for(let i of Object.keys(t))r.has(i)||e.push({level:"warning",path:n?`${n}.${i}`:i,message:"Unknown config key."})}import{existsSync as _a,lstatSync as wT}from"fs";import{resolve as LT}from"path";function i9(e){return e.state==="fresh"?!0:e.state!=="stale"?!1:!e.reason.startsWith("SQLite generation requires repair")}function Zy(e,t,n,r={}){let i=new Date().toISOString();if(!_a(n.dbPath))return{state:"missing",checkedAt:i,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!_a(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=yr(Ve(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??Wf(e),c=s.fingerprint,l=n.cacheDir&&r.gitContext&&Pl(r.gitContext,n.cacheDir,c)?c:void 0,u=n.cacheDir&&r.gitContext&&l&&DT(l,a,t)&&MT(e,l,t)?r.gitObservation?.context===r.gitContext?r.gitContext:jp(r.gitContext):void 0,d=r.gitObservation&&r.gitObservation.context===r.gitContext?r.gitObservation.projectFileInventorySequence:void 0,m=u?.clean&&Hp(e,void 0,{cachedInventoryAfterSequence:d})?u:void 0,p=n.cacheDir&&m&&l&&Pl(m,n.cacheDir,l)?l:PT(e,a,t),f=[...s.indexedLanguages??[]].sort(),g=o.capabilities.publishableGeneration&&_p(Wi(s.fingerprint),p)&&JSON.stringify(f)===JSON.stringify(p.languages),h=Ll(n.dbPath,n.metaPath),b=h.state==="invalid"||h.state==="drifted",S=g?Vf(n.dbPath,p,f):void 0,y=S?.state==="incomplete",x=g&&!b&&!y;return{state:x?"fresh":"stale",checkedAt:i,metaPath:n.metaPath,updatedAt:s.updatedAt,lastRefresh:s.lastRefresh,reason:b?`SQLite generation requires repair: ${h.reason}`:y?`SQLite generation is missing ${S.missingDocumentCount} indexed source document(s): ${S.missingPaths.join(", ")}`:g?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:x?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 o9(e){let t=new Date().toISOString();if(!_a(e.dbPath))return{state:"missing",checkedAt:t,metaPath:e.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!_a(e.metaPath))return{state:"unknown",checkedAt:t,metaPath:e.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let n=yr(Ve(e.metaPath,"reindex metadata"));if(n.kind==="unsupported")return{state:"unknown",checkedAt:t,metaPath:e.metaPath,reason:`Reindex metadata version ${n.version} is unsupported by this scip-query build.`,remedy:"Upgrade scip-query or run: scip-query reindex"};if(n.kind==="malformed")return{state:"unknown",checkedAt:t,metaPath:e.metaPath,reason:`Could not decode reindex metadata: ${n.reason}`,remedy:"Run: scip-query reindex"};let r=n.metadata,i=[...r.indexedLanguages??[]].sort(),o=Wi(r.fingerprint),s=[...o?.languages??[]].sort(),a=n.capabilities.publishableGeneration&&o!==null&&JSON.stringify(i)===JSON.stringify(s),c=Ll(e.dbPath,e.metaPath),l=c.state==="invalid"||c.state==="drifted",u=a&&!l;return{state:u?"fresh":"stale",checkedAt:t,metaPath:e.metaPath,updatedAt:r.updatedAt,lastRefresh:r.lastRefresh,reason:l?`SQLite generation requires repair: ${c.reason}`:a?"Watcher accepted the newly published index generation with no later changes pending.":"Published index metadata is not a complete queryable generation.",remedy:u?void 0:"Run: scip-query reindex"}}catch(n){return{state:"unknown",checkedAt:t,metaPath:e.metaPath,reason:`Could not read reindex metadata: ${n instanceof Error?n.message:String(n)}`,remedy:"Run: scip-query reindex"}}}function PT(e,t,n){return Yp(e,t,{pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:n.indexer?.typescript?.projectMode,typescriptProjects:n.indexer?.typescript?.projects,clojureConfigPath:n.indexer?.clojure?.configPath})}function DT(e,t,n){let r=TT(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 MT(e,t,n){if(!(t.languages.includes("typescript")||!!t.clojureConfigPath))return!0;let i=Ds(e);if(t.clojureConfigPath){let o=un(t.clojureConfigPath);if(!i.includes(o))return!1;try{if(!wT(LT(e,o)).isFile())return!1}catch{return!1}}return!t.languages.includes("typescript")||qp(e,n.indexer?.typescript?.projectMode,n.indexer?.typescript?.projects??[],i)}function TT(e,t){return Jp(e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}import{existsSync as kT,readdirSync as AT}from"fs";import{createHash as FT}from"crypto";import{join as qu}from"path";function Uu(e){let t=0,n=0,r=0,i=0,o=0,s=[];for(let l of e)switch(l.state){case"legacy":t+=1;break;case"current":n+=1;break;case"unsupported-older":r+=1,s.push(Hu(l));break;case"unsupported-future":i+=1,s.push(Hu(l));break;case"malformed":o+=1,s.push(Hu(l));break}let a=t+n,c=r+i+o;return{complete:c===0,total:e.length,accepted:a,legacy:t,current:n,unsupportedOlder:r,unsupportedFuture:i,malformed:o,omitted:c,issues:s}}function Hu(e){if(e.state==="legacy"||e.state==="current")throw new Error(`accepted record ${e.path} cannot become a compatibility issue`);return{path:e.path,state:e.state,reason:e.reason??e.state}}var nb=qu(".scipquery","suppressions"),eb="scip-query-suppression",tb=1,Oa=2;function NT(e){return qu(e,nb)}function _T(e){if(e.id&&e.id.trim()!=="")return`${e.id.trim()}.json`;let t=`${e.check??""}\0${e.file??""}`;return`CHECK-${FT("sha256").update(t).digest("hex").slice(0,12).toUpperCase()}.json`}function OT(e){return _T(e).slice(0,-5)}function BT(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return{state:"malformed",error:"not a suppression object"};let n=e;if(n.schemaVersion===void 0&&(n.kind!==void 0||n.suppressionIdentity!==void 0||n.writer!==void 0))return{state:"malformed",error:"suppression envelope metadata requires schemaVersion"};if(n.schemaVersion!==void 0){if(!Number.isSafeInteger(n.schemaVersion))return{state:"malformed",error:"schemaVersion must be a positive safe integer"};if(n.schemaVersion!==tb&&n.schemaVersion!==Oa)return{state:n.schemaVersion>Oa?"unsupported-future":"unsupported-older",error:`unsupported schemaVersion ${String(n.schemaVersion)}`};if(n.kind!==void 0&&n.kind!==eb)return{state:"malformed",error:`kind must be ${eb}`}}if(n.schemaVersion===tb&&n.decision!==void 0)return{state:"malformed",error:"schemaVersion 1 cannot carry automated adjudication metadata"};if(n.schemaVersion===Oa&&!Da(n.decision))return{state:"malformed",error:"schemaVersion 2 requires a valid automated adjudication decision"};if(typeof n.reason!="string"||n.reason.trim()==="")return{state:"malformed",error:"missing reason"};if(!n.id&&!n.check)return{state:"malformed",error:"needs an id or a check"};let r=$T(n);if(n.schemaVersion===void 0)return{state:"legacy",suppression:r,record:n,schemaVersion:0};let i=OT(r);return n.suppressionIdentity!==i||t!==void 0&&n.suppressionIdentity!==t?{state:"malformed",error:"suppressionIdentity does not match the suppression target or filename"}:!n.writer||n.writer.tool!=="scip-query"||typeof n.writer.version!="string"||n.writer.version.trim()===""?{state:"malformed",error:"missing valid writer metadata"}:typeof n.createdAt!="string"||!Number.isFinite(Date.parse(n.createdAt))?{state:"malformed",error:"missing valid createdAt timestamp"}:n.updatedAt!==void 0&&(typeof n.updatedAt!="string"||!Number.isFinite(Date.parse(n.updatedAt)))?{state:"malformed",error:"invalid updatedAt timestamp"}:{state:n.schemaVersion===Oa?"current":"legacy",suppression:r,record:n,schemaVersion:n.schemaVersion}}function rb(e){let t=NT(e);if(!kT(t))return{suppressions:[],compatibility:Uu([]),warnings:[]};let n=[],r=[];for(let o of AT(t).sort()){if(!o.endsWith(".json"))continue;let s=qu(t,o),a=`${nb}/${o}`,c;try{c=JSON.parse(Ve(s,"suppression record"))}catch{r.push({path:a,state:"malformed",reason:"malformed JSON"});continue}let l=BT(c,o.slice(0,-5));if("error"in l){r.push({path:a,state:l.state,reason:l.error});continue}r.push({path:a,state:l.state}),n.push(l.suppression)}let i=Uu(r);return{suppressions:n,compatibility:i,warnings:i.issues.map(o=>`${o.path}: ${o.reason} \u2014 ignored`)}}function $T(e){return{...typeof e.id=="string"?{id:e.id}:{},...typeof e.check=="string"?{check:e.check}:{},...typeof e.file=="string"?{file:e.file}:{},reason:e.reason,...typeof e.expiresAt=="string"?{expiresAt:e.expiresAt}:{},...typeof e.createdAt=="string"?{createdAt:e.createdAt}:{},...e.decision?{decision:e.decision}:{}}}function $a(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var Gu,Ba;function w9(e){Gu=e}function ja(){return Ba}function ib(e=$a(),t=void 0){if(t===void 0&&Gu?.projectRoot===e)return Gu;let n=Jy(e),r=zp(e,n),i=process.env.SCIP_QUERY_INDEX_DB;if(i)return{projectRoot:e,config:n,paths:r,dbPath:i,dbPathSource:"env",gitContext:t};if(zu(r.dbPath))return{projectRoot:e,config:n,paths:r,dbPath:r.dbPath,dbPathSource:"configured",gitContext:t};let o=HT(e,"index.db");return{projectRoot:e,config:n,paths:r,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:zT(o,r.dbPath),gitContext:t}}function L9(e){return ib(e).dbPath}function P9(e,t,n,r={}){if(zu(n.dbPath)&&r.gitContext?.clean===!1&&r.watcherGeneration!==void 0&&Gf(n.dbPath)===r.watcherGeneration)return Xf(e,t,n,r.gitContext);let i=Zy(e,t,n,{gitContext:r.gitContext,gitObservation:r.gitObservation});return i.state==="fresh"?{kind:"local-fresh",freshness:i}:Jf(e,t,n,r.gitContext)}function D9(e){return!e.startsWith("__")&&!UT.has(e)}function M9(e){return e==="search"||e==="code"}var UT=new Set(["capabilities","check-deps","config-validate","continue","doctor","init","install-skills","reindex","setup","setup-agent","status","suppress","uninstall","watch"]);function qT(){try{return GT($a(),{warnOnRootFallback:!0})}catch(e){console.error(`error: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}function GT(e,t={}){let{config:n,paths:r,dbPath:i,dbPathSource:o,rootFallbackWarning:s,gitContext:a}=ib(e);if(!zu(i))throw new Error("No index.db found. Run: scip-query reindex");t.warnOnRootFallback&&o==="root-fallback"&&s&&console.error(s);let c=rb(e).suppressions,l={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??r.indexPath,projectRoot:e,collaborationDomainId:n.collaborationDomainId,sharedEvidenceDbPath:Yf(e,n,a),entryRoots:n.entryRoots,semantic:n.semantic,suppressions:[...n.suppressions??[],...c],declaredCouplings:n.declaredCouplings,locality:n.locality,architecture:n.architecture,coverageContracts:n.coverageContracts,docs:n.docs},u=Kf(e);return new zf(l,u)}function zT(e,t){let n="unknown time";try{n=jT(e).mtime.toISOString()}catch{}return`warning: using legacy project-root index.db (${e}, modified ${n}) because the configured index was not found at ${t}. This fallback may be stale; run 'scip-query reindex' to refresh the configured index.`}function Ku(e){return $p(()=>{let t=qT(),n=Ba;Ba=t;try{return e(t)}finally{Ba=n,t.close()}})}function T9(e,t){return t.concat([e])}function Wu(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(0)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function k9(e){switch(e.state){case"idle":return"Watching (idle)";case"waiting":{let t=Math.round((e.reindexAt-Date.now())/1e3);return`${e.changedFiles} file(s) changed, reindexing in ${t}s...`}case"indexing":return`Reindexing... (${Math.round((Date.now()-e.startedAt)/1e3)}s)`;case"cooldown":return`Cooldown (${Math.round((e.until-Date.now())/1e3)}s)${e.dirty?" \u2014 changes pending":""}`;case"budget-paused":return`Automatic reindex paused by resource budget (${Math.max(0,Math.round((e.until-Date.now())/1e3))}s; ${e.reason}; ${e.rebuilt} rebuilds, ${Wu(e.estimatedWriteBytes)} estimated writes)${e.dirty?" \u2014 changes pending":""}`;case"draining":return`Stopping safely \u2014 ${e.reason}`;default:return KT(e)}}function KT(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}var WT=new Map([[8,"\u2408"],[9,"\u2409"],[10,"\u2424"],[13,"\u240D"]]),F9=6500,N9=8e3,_9=6500,O9=3500;function ob(e,t={}){let n=t.allowNewlines??!0,r=t.allowTabs??!0,i="";for(let o=0;o<e.length;){let s=e.charCodeAt(o);if(s===27){o=VT(e,o);continue}if(s===155){o=sb(e,o+1);continue}if(s===144||s===152||s===157||s===158||s===159){o=ab(e,o+1);continue}if(XT(s)){s===10&&n?i+=`
54
- `:s===9&&r?i+=" ":i+=WT.get(s)??"\uFFFD",o+=1;continue}if(QT(s)){i+="\uFFFD",o+=1;continue}i+=e[o],o+=1}return i}function Mt(e){return ob(e,{allowNewlines:!1,allowTabs:!1})}function Yu(e,t=n=>process.stdout.write(n)){t(`${e}
55
- `)}function B9(e=console){let t={log:e.log.bind(e),error:e.error.bind(e),warn:e.warn.bind(e)};return e.log=(...n)=>t.log(...n.map(Vu)),e.error=(...n)=>t.error(...n.map(Vu)),e.warn=(...n)=>t.warn(...n.map(Vu)),()=>{e.log=t.log,e.error=t.error,e.warn=t.warn}}function Vu(e){return typeof e=="string"?ob(e):e}function VT(e,t){let n=e.charCodeAt(t+1);if(Number.isNaN(n))return e.length;if(n===91)return sb(e,t+2);if(n===80||n===88||n===93||n===94||n===95)return ab(e,t+2);let r=t+1;for(;r<e.length&&YT(e.charCodeAt(r));)r+=1;return r<e.length&&JT(e.charCodeAt(r))?r+1:t+1}function sb(e,t){let n=t;for(;n<e.length;){let r=e.charCodeAt(n);if(n+=1,r>=64&&r<=126)return n}return e.length}function ab(e,t){let n=t;for(;n<e.length;){let r=e.charCodeAt(n);if(r===7||r===156)return n+1;if(r===27&&e.charCodeAt(n+1)===92)return n+2;n+=1}return e.length}function YT(e){return e>=32&&e<=47}function JT(e){return e>=48&&e<=126}function XT(e){return e<=31||e>=127&&e<=159}function QT(e){return e===1564||e===8206||e===8207||e>=8234&&e<=8238||e>=8294&&e<=8297}function Ha(e){return e+1}function ZT(e,t){return`${Ha(e)}-${Ha(t)}`}function Ju(e,t,n){return`${Mt(e)}:${ZT(t,n)}`}function H9(e,t=180){let n=Mt(e).replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var Xu={empty(e){console.log(Mt(e))},list(e,t){for(let n of e)console.log(Mt(t(n)))},groupedByFile(e,t,n=r=>r.relativePath){let r="";for(let i of e){let o=n(i);o!==r&&(r&&console.log(""),console.log(Mt(o)),r=o),console.log(Mt(t(i)))}},sectionedReport(e){let t=!0;for(let n of e)if(!(n.skipIfEmpty&&n.rows.length===0)){t||console.log(""),t=!1,n.title!==void 0&&console.log(`\u2550\u2550\u2550 ${Mt(n.title)} \u2550\u2550\u2550`),n.explanation!==void 0&&console.log(Mt(n.explanation));for(let r of n.rows){let i=n.preserveRowNewlines?r.split(`
56
- `):[r];for(let o of i)console.log(Mt(o))}}},table(e,t,n){console.log(` ${e.map(Mt).join(" ")}`);let r=n??e.map(i=>i.length);console.log(` ${r.map(i=>"\u2500".repeat(i)).join(" ")}`);for(let i of t)console.log(Mt(i))}};import{availableParallelism as d5}from"os";import{fileURLToPath as ol}from"url";import{getHeapStatistics as m5}from"v8";import{existsSync as Ua,readdirSync as ub}from"fs";import{join as To}from"path";var ek={files:new Set,pathPrefixes:[]},tk={reasonsByFile:new Map},Qu=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,nk=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,db=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],rk=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),ik=4,ok=ge("package-surface",{clearGroups:["whole-project"]}),sk=ge("package-operational-surface",{clearGroups:["whole-project"]});function mb(e){return ok.get(e,()=>ck(e.config.projectRoot))}function xn(e,t){let n=mb(e);return n.files.has(t)?!0:n.pathPrefixes.some(r=>t.startsWith(r))}function pb(e,t){return mb(e).files.has(t)}function ak(e){return sk.get(e,()=>lk(e.config.projectRoot))}function fb(e,t){return ak(e).reasonsByFile.get(t)??[]}function ck(e){let t=new Set,n=[];for(let{manifest:r,packageRoot:i}of gb(e))for(let o of uk(r))Sb(e,i,o,t,n);return t.size===0&&n.length===0?ek:{files:t,pathPrefixes:n}}function lk(e){let t=new Map;for(let{manifest:n,packageRoot:r}of gb(e)){let i=dk(n);for(let s of i)cb(e,r,s,"package binary",t);let o=n.scripts;if(!(!o||typeof o!="object")){for(let[s,a]of Object.entries(o))if(typeof a=="string")for(let c of mk(a))cb(e,r,c,`package script "${s}"`,t)}}return t.size===0?tk:{reasonsByFile:t}}function gb(e){let t=[],n=yb(e,"");return n&&t.push({manifest:n,packageRoot:""}),hb(e,"",t,0),t}function hb(e,t,n,r){if(r>=ik)return;let i=To(e,t);if(Ua(i))for(let o of ub(i,{withFileTypes:!0})){if(!o.isDirectory()||rk.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=yb(e,s);a&&n.push({manifest:a,packageRoot:s}),hb(e,s,n,r+1)}}function yb(e,t){let n;try{n=Ye(e,To(t,"package.json"),{maxBytes:8*1024*1024,inputKind:"package manifest"})}catch(r){if(!Je(r))throw r;return null}try{let r=JSON.parse(n);return r&&typeof r=="object"?r:null}catch{return null}}function uk(e){let t=[];for(let r of["main","module","types","browser"])typeof e[r]=="string"&&t.push(e[r]);let n=e.bin;if(typeof n=="string")t.push(n);else if(n&&typeof n=="object")for(let r of Object.values(n))typeof r=="string"&&t.push(r);return bb(e.exports,t),t}function dk(e){let t=e.bin;return typeof t=="string"?[t]:!t||typeof t!="object"?[]:Object.values(t).filter(n=>typeof n=="string")}function mk(e){let t=[],n=/(?:^|&&|\|\||;)\s*(?:(?:cross-env|env)(?:\s+[A-Za-z_][A-Za-z0-9_]*=\S+)*\s+)?(?:node|bun|tsx|ts-node|vite-node|python3?|deno\s+run)\s+(?:(?:--?[A-Za-z0-9-]+(?:=\S+)?)\s+)*["']?([^"'`\s]+\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs|py))["']?/g;for(let r of e.matchAll(n)){let i=r[1];i&&!i.startsWith("node_modules/")&&!i.startsWith("./node_modules/")&&t.push(i)}return t}function cb(e,t,n,r,i){let o=new Set;Sb(e,t,n,o,[]);for(let s of o){let a=i.get(s)??[];a.includes(r)||a.push(r),i.set(s,a)}}function bb(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))bb(n,t)}function Sb(e,t,n,r,i){let o=n.replace(/\\/g,"/").replace(/^\.\//,"");if(o===""||o.startsWith(".."))return;let s=o.indexOf("*");if(s>=0){let c=o.slice(0,s);for(let l of lb(c))l!==""&&i.push(Cn(t,l));return}let a=o.replace(nk,"");for(let c of lb(a)){c===a&&c===o&&r.add(Cn(t,o));for(let l of db)pk(e,r,t,c+l)}r.add(Cn(t,o))}function lb(e){let t=[e];return Qu.test(e)&&(t.push(e.replace(Qu,"src/")),t.push(e.replace(Qu,""))),t}function pk(e,t,n,r){let i=Cn(n,r);if(t.add(i),!r.startsWith("src/")||Ua(To(e,i)))return;let o=db.find(u=>r.endsWith(u));if(!o)return;let s=r.slice(0,-o.length);fk(e,t,n,s,o);let a=s.lastIndexOf("/");if(a<=4)return;let c=s.slice(0,a),l=s.slice(a+1);for(let u of vb(e,n,c,`${l}${o}`))t.add(u)}function fk(e,t,n,r,i){let o=Cn(n,`${r}/index${i}`);Ua(To(e,o))&&t.add(o)}function vb(e,t,n,r){let i=To(e,t,n);if(!Ua(i))return[];let o=[];for(let s of ub(i,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...vb(e,t,a,r)):s.isFile()&&s.name===r&&o.push(Cn(t,a))}return o}function Cn(e,t){return e?`${e}/${t}`:t}import{existsSync as Zu,readdirSync as gk}from"fs";import{dirname as hk,join as ed}from"path";var yk={rootFiles:new Set,sourcePrefixes:[]},bk=new Set([".git",".scipquery","node_modules","target"]),Sk=6,vk=ge("rust-library-surface",{clearGroups:["whole-project"]});function Cb(e,t,n){if(!n.endsWith(".rs")||!Rk(Ck(e),n))return!1;let r=U(e,n).find(i=>i.symbol===t);return r?Ek(V(e,n)[r.startLine]??""):!1}function Ck(e){return vk.get(e,()=>xk(e.config.projectRoot))}function xk(e){let t=new Set,n=new Set;for(let r of Ik(e)){let i=Ye(e,ed(r,"Cargo.toml"),{maxBytes:8388608,inputKind:"Cargo manifest"}),o=wk(i),s=Cn(r,"src/lib.rs"),a=o?Cn(r,o):!Lk(i)&&Ct(e,s)?s:null;if(!a)continue;t.add(a);let c=hk(a).replaceAll("\\","/");n.add(c==="."?"":`${c}/`)}return t.size===0?yk:{rootFiles:t,sourcePrefixes:[...n].sort()}}function Rk(e,t){return t.endsWith(".rs")?e.rootFiles.has(t)?!0:Pk(t)?!1:e.sourcePrefixes.some(n=>t.startsWith(n)):!1}function Ek(e){return/^\s*pub\s+(?!\()/.test(e)}function Ik(e){if(!Zu(e))return[];let t=[];return xb(e,"",t,0),t}function xb(e,t,n,r){let i=ed(e,t);if(Zu(i)&&(Zu(ed(i,"Cargo.toml"))&&n.push(t),!(r>=Sk)))for(let o of gk(i,{withFileTypes:!0})){if(!o.isDirectory()||bk.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name;xb(e,s,n,r+1)}}function wk(e){let t=!1;for(let n of e.split(`
57
- `)){let r=n.replace(/\s+#.*$/,"").trim(),i=/^\[([^\]]+)\]$/.exec(r);if(i){t=i[1]==="lib";continue}if(!t)continue;let o=/^path\s*=\s*["']([^"']+)["']/.exec(r)?.[1];if(o)return o.replaceAll("\\","/").replace(/^\.\//,"")}return null}function Lk(e){let t=!1;for(let n of e.split(`
58
- `)){let r=n.replace(/\s+#.*$/,"").trim(),i=/^\[([^\]]+)\]$/.exec(r);if(i){t=i[1]==="package";continue}if(t&&/^autolib\s*=\s*false\b/.test(r))return!0}return!1}function Pk(e){return/(?:^|\/)src\/main\.rs$/.test(e)||/(?:^|\/)src\/bin\//.test(e)||/(?:^|\/)(?:examples|tests|benches)\//.test(e)}function Ei(e){return q(e)==="barrel"}function Eb(e){return Dk.get(e,()=>{let n=Z(e,{includeIgnored:!1}).filter(s=>{let a=q(s);return a==="entry"||a==="worker"});if(n.length===0)return new Set;let r=Me(e),i=new Set,o=new Set;for(;n.length>0;){let s=n.shift();if(!i.has(s)){i.add(s),q(s)==="barrel"&&o.add(s);for(let a of r.get(s)??[])i.has(a)||n.push(a)}}return o})}var Dk=ge("live-barrels",{clearGroups:["whole-project"]});function td(e,t){return Eb(e).has(it(t))}function Ib(e){let t=Eb(e);return Z(e,{includeIgnored:!1}).filter(n=>Ei(n)&&!t.has(n)&&!Mk(e,n))}function Mk(e,t){let n=it(t),r=fn(e).forFile(n,{facts:!0}).facts?.callables;return r&&r.length>0?!0:(e.get(`SELECT COUNT(*) AS n
59
- FROM defn_enclosing_ranges der
60
- JOIN documents d ON d.id = der.document_id
61
- WHERE d.relative_path = ?
62
- AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function Ue(e,t){let n=it(t),r=q(t);return r==="entry"||r==="worker"||nd(n)||td(e,n)}function Ii(e,t,n){let r=it(n),i=[];xn(e,r)&&i.push("package-surface-file"),Ak(e,t,r)&&i.push("transitive-package-surface"),Cb(e,t,r)&&i.push("rust-public-library"),Kk(t,r)&&i.push("framework-entrypoint");let o=e.config.entryRoots;return o&&(o.files?.some(s=>it(s)===r)&&i.push("configured-file"),o.pathPrefixes?.some(s=>r.startsWith(it(s)))&&i.push("configured-path-prefix"),o.qualifiedVars?.some(s=>Vk(t,s))&&i.push("configured-qualified-var"),o.symbolPatterns?.some(s=>{try{return kr(s,"entryRoots.symbolPatterns entry").test(t)}catch{return!1}})&&i.push("configured-symbol-pattern")),i}function Te(e,t,n){return Ii(e,t,n).length>0}var Tk=ge("package-surface-reachability",{clearGroups:["whole-project"]}),kk=ge("explicit-package-surface-reachability",{clearGroups:["whole-project"]});function Ak(e,t,n){let r=Fk(e).get(n);return r===void 0?!1:r===null||r.has(z(t))}function wb(e,t,n){let r=Nk(e).get(n);return r===void 0?!1:r===null||r.has(z(t))}function Fk(e){return Tk.get(e,()=>Lb(e,t=>xn(e,t)))}function Nk(e){return kk.get(e,()=>Lb(e,t=>pb(e,t)))}function Lb(e,t){let n=new Map,r=[];for(let i of Z(e,{includeIgnored:!1}))t(i)&&(n.set(i,null),r.push(i));for(;r.length>0;){let i=r.shift(),o=n.get(i);if(o!==void 0)for(let s of Qi(e,i)){if(!s.sourcePath||e.isIgnored(s.sourcePath))continue;let a=_k(o,s);a!==void 0&&Ok(n,s.sourcePath,a)&&r.push(s.sourcePath)}}return n}function _k(e,t){if(e===null)return t.kind==="named"?new Set(t.names):null;if(t.kind==="star")return new Set(e);if(t.kind==="star-as")return t.names.some(r=>e.has(r))?null:void 0;let n=t.names.filter(r=>e.has(r));return n.length>0?new Set(n):void 0}function Ok(e,t,n){if(!e.has(t))return e.set(t,n),!0;let r=e.get(t);if(r===void 0)return!1;if(r===null||n===null)return r===null?!1:(e.set(t,null),!0);let i=!1;for(let o of n)r.has(o)||(r.add(o),i=!0);return i}var Pb=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),Bk=new Set(["default","generateMetadata","generateStaticParams"]),$k=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),jk=new Set(["default","middleware","config"]),Hk=new Set(["register","onRequestError"]),Uk=new Set(["onRouterTransitionStart"]),qk=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),Gk=new Set(["load","actions","entries",...Pb]),zk=new Set(["default"]);function Kk(e,t){let n=z(e);return n===""?!1:Db(t)?Pb.has(n):Mb(t)?Bk.has(n):Tb(t)?$k.has(n):kb(t)?jk.has(n):Ab(t)?Hk.has(n):Fb(t)?Uk.has(n):Nb(t)?qk.has(n):_b(t)?Gk.has(n):Wk(t)?zk.has(n):!1}function nd(e){return Db(e)||Mb(e)||Tb(e)||kb(e)||Ab(e)||Fb(e)||Nb(e)||_b(e)}function Db(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Mb(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Tb(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function kb(e){return rd(e,"(?:middleware|proxy)\\.(?:ts|js|mts|mjs)")}function Ab(e){return rd(e,"instrumentation\\.(?:ts|js|mts|mjs)")}function Fb(e){return rd(e,"instrumentation-client\\.(?:ts|js|mts|mjs)")}function rd(e,t){return new RegExp(`^(?:src/)?${t}$`).test(e)||new RegExp(`(?:^|/)src/${t}$`).test(e)||new RegExp(`(?:^|/)(?:apps|services|packages)/[^/]+/(?:src/)?${t}$`).test(e)}function Nb(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function _b(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function Wk(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function Vk(e,t){let n=t.lastIndexOf("/");if(n<0)return!1;let r=t.slice(0,n),i=t.slice(n+1);return e.includes(Rb(r)+"/")&&e.includes(Rb(i)+".")}function Rb(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function Ob(e,t,n={}){let r=new Map;if(t&&t.length===0)return r;let i=Z(e,{includeIgnored:!1}),o=zt(e),s=t??Le(e),a=new Set(s.map(l=>l.symbolId)),c=tA(s);return Yk(e,r,i,o,a,c),Jk(e,r,s,a),eA(e,r,i,o,a,c),n.semantic!==!1&&n.semanticEvidence&&rA(r,n.semanticEvidence.callerMap(e,nA(s))),r}function Yk(e,t,n,r,i,o){for(let s of n){if(!se(s))continue;let a=Gt(e,s);if(a)for(let c of a){if(o&&!o.has(c.calleeLeaf))continue;let l=_t(s,r.get(c.calleeLeaf)??[]);if(!l||l.length===0)continue;let u=$n(e,s,l,c.memberAccess,c.calleeQualifier);u&&i.has(u.symbolId)&&u.file!==s&&id(t,u.symbolId,s)}}}function Jk(e,t,n,r){let i=Qk(n);for(let o of Xk(e,r))e.isIgnored(o.relative_path)||Zk(o,i.get(o.symbol_id))||id(t,o.symbol_id,o.relative_path)}function Xk(e,t){return Us(e,t?[...t]:void 0)}function Qk(e){let t=new Map;for(let n of e)t.set(n.symbolId,{docId:n.documentId,startLine:n.startLine,endLine:n.endLine});return t}function Zk(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function eA(e,t,n,r,i,o){for(let s of n){if(se(s)!=="rust")continue;let a=ni(e,s,{includeRustAttributeNames:!0});if(a.length!==0)for(let{name:c}of a){if(o&&!o.has(c))continue;let l=r.get(c);if(l)for(let u of l)i.has(u.symbolId)&&u.file!==s&&id(t,u.symbolId,s)}}}function id(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function tA(e){let t=new Set;for(let n of e){let r="leaf"in n&&typeof n.leaf=="string"?n.leaf:"symbol"in n&&typeof n.symbol=="string"?z(n.symbol):"";r&&t.add(r)}return t.size>0?t:null}function nA(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function rA(e,t){for(let[n,r]of t){let i=e.get(n);i||(i=new Set,e.set(n,i));for(let o of r)i.add(o)}}function od(e,t,n={}){return Ob(e,t,n)}function ko(e,t,n={}){return Df(e,t,n)}function Bb(e,t,n={}){let r=od(e,t,{semantic:n.semantic,semanticEvidence:n.semanticEvidence});return n.sourceFallback===!1?r:Rn(r,ko(e,t))}function Rn(e,t){let n=new Map;for(let[r,i]of e)n.set(r,new Set(i));for(let[r,i]of t){let o=n.get(r)??new Set;for(let s of i)o.add(s);n.set(r,o)}return n}function $b(e,t,n){let r=t.identifierResolution==="strict"?xl:Pf,i=t.candidateNames?If(t.candidateNames):null,o=0,s=0,a=0,c=0,l="";for(let u of t.paths)if(o+=1,l=u,!(!se(u)&&!(t.includeVueSfc&&uf(u)))&&!e.isIgnored(u)&&!t.skipPath?.(u))try{if(i&&!wf(W(e,u),i))continue;s+=1;let m=(f,g,h,b)=>{if(t.candidateNames&&!t.candidateNames.has(f))return;a+=1;let S=t.resolveTargets?t.resolveTargets({sourceFile:u,name:f,kind:g,defaultTargets:b}):b();for(let y of S)c+=1,n({sourceFile:u,name:f,target:y,occurrences:h,kind:g})},p=ai(e,u);for(let[f,g]of p)m(f,"identifier",g.length,()=>r(e,u,f));for(let f of ni(e,u,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let g=f.kind==="cross-language-dispatch"?()=>xl(e,u,f.name):()=>r(e,u,f.name);m(f.name,f.kind,f.occurrences,g)}}finally{t.afterPath?.(u),o%10===0&&N("source-reference-scan.progress",()=>{},()=>({scannedPaths:o,currentPath:l,candidateMatchedPaths:s,visitedNames:a,visitedHits:c}))}}function ee(e){return e.endLine-e.startLine+1}function jb(e,t={}){let{scope:n,files:r,minLoc:i=1,maxLoc:o=Number.POSITIVE_INFINITY,excludeSymbol:s,excludeEntrySurfaces:a=!1,excludeTypesFiles:c=!1,excludeRootedSymbols:l=!1,requireFunctionLikeSymbol:u=!1,requireCallableSymbol:d=!1,excludeRustTraitImplMembers:m=!1,includeSuppressed:p=!1,sortByLocDesc:f=!1}=t,g=[],h=iA(e,{scope:n,files:r,requireFunctionLikeSymbol:u,requireCallableSymbol:d}),b=new Map,S=new Map,y=v=>{let C=b.get(v);if(C!==void 0)return C;let R=Ue(e,v);return b.set(v,R),R},x=v=>{let C=S.get(v);if(C!==void 0)return C;let R=q(v);return S.set(v,R),R};for(let v of h){let C=v.relativePath;if(e.isIgnored(C)||a&&y(C)||!oA(v,{requireFunctionLikeSymbol:u,requireCallableSymbol:d})||s!==void 0&&v.symbol===s)continue;let R=ee(v);R<i||R>o||c&&sA(C)||l&&Te(e,v.symbol,C)||m&&je(v.symbol)||x(C)!=="test"&&(ii(v.symbol)||!p&&As(e,C,v.startLine)||g.push(v))}return f?g.sort((v,C)=>ee(C)-ee(v)):g}function iA(e,t){return t.files!==void 0?[...new Set(t.files.map(r=>r.replace(/\\/g,"/")))].sort().filter(r=>!t.scope||r.includes(t.scope)).flatMap(r=>U(e,r)):t.requireCallableSymbol?Zi(e,{scope:t.scope,symbolMatches:Xe,sqlPrefilter:"callable"}):t.requireFunctionLikeSymbol?Zi(e,{scope:t.scope,symbolMatches:Se,sqlPrefilter:"function-like"}):Sf(e,t.scope)}function oA(e,t){return t.requireCallableSymbol?Xe(e.symbol):t.requireFunctionLikeSymbol?Se(e.symbol):e.isFunctionLike}function sA(e){return(e.split("/").pop()??"").includes("types")}var H=class{constructor(t){this.db=t}db;scopedDefinitions(t){return bf(this.db,t)}definitionsForFile(t){return U(this.db,t)}productionCallableDefinitions(t={}){return jb(this.db,t)}calleeMap(t,n={}){return Er(this.db,t,{...n,semanticEvidence:re})}crossFileCallerMap(t,n={}){return od(this.db,t,{...n,semanticEvidence:re})}sourceFallbackCallerFiles(t,n={}){return ko(this.db,t,n)}callerFileMap(t,n={}){return Bb(this.db,t,{...n,semanticEvidence:re})}frameworkReferencedSymbolIds(t){let n=new Map;for(let i of t){if(!i.leaf)continue;let o=n.get(i.leaf)??[];o.push(i.symbolId),n.set(i.leaf,o)}let r=new Set;for(let i of Z(this.db,{includeIgnored:!1}))if(se(i)==="rust")for(let{name:o}of ni(this.db,i,{includeRustAttributeNames:!0}))for(let s of n.get(o)??[])r.add(s);return r}symbolsWithNonSelfCallees(t,n={}){if(t.length===0)return new Set;let r=new Map(t.map(o=>[o.symbolId,o.symbol])),i=this.calleeMap(t,n);return new Set([...i.entries()].filter(([o,s])=>{let a=r.get(o);return s.some(c=>c.symbol!==a)}).map(([o])=>o))}fileDependencyGraph(t){return Me(this.db,t)}fileKind(t){return q(t)}hasSuppressionComment(t){return As(this.db,t.relativePath,t.startLine)}sourceFiles(){return ti(this.db)}scanSourceReferences(t,n){$b(this.db,t,n)}callableSignature(t){let n=fn(this.db).forFile(t.relativePath,{facts:!0}).facts?.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};import{statSync as aA}from"fs";function Ar(e){let t=e.get("SELECT COUNT(*) as c FROM documents").c,n=e.get("SELECT COUNT(*) as c FROM global_symbols").c,r=e.get("SELECT COUNT(*) as c FROM mentions WHERE role = 1").c,i=e.get("SELECT COUNT(*) as c FROM mentions WHERE role != 1").c;return{documents:t,symbols:n,definitions:r,references:i,...cA(e.generation.databasePath)}}function cA(e){try{let t=aA(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function lA(e,t){return Tl(e).filter(n=>uA({pattern:t,relativePath:n})).map(n=>({relativePath:n}))}function uA(e,t){let n=typeof e=="string"?{pattern:e,relativePath:t}:e;if(typeof n.pattern!="string"||typeof n.relativePath!="string")throw new TypeError("pathMatchesGlob requires pattern and relativePath.");let r=un(n.pattern),i=un(n.relativePath);if(!/[*?]/.test(r))return i.includes(r);let o=r.includes("/")?r:`**/${r}`;return qa(o.split("/"),i.split("/"))}function qa(e,t){if(e.length===0)return t.length===0;let[n,...r]=e;return n==="**"?qa(r,t)||t.length>0&&qa(e,t.slice(1)):t.length===0||!dA(n??"",t[0]??"")?!1:qa(r,t.slice(1))}function dA(e,t){let n="^";for(let r of e)r==="*"?n+="[^/]*":r==="?"?n+="[^/]":n+=mA(r);return n+="$",new RegExp(n).test(t)}function mA(e){return/[\\^$.*+?()[\]{}|]/.test(e)?`\\${e}`:e}function Ub(e,t,n){let r=[],i=[],o=new Map;for(let s of[...e].sort(n)){let a=s.channel??"default",c=t[a]??Number.MAX_SAFE_INTEGER,l=o.get(a)??0;if(l>=c){i.push(s);continue}r.push(s),o.set(a,l+1)}return{selected:r,omitted:i}}function Ga(e,t,n,r,i=!1){let o=[...e],s=[],a=new Set,c=0;for(;o.length>0&&s.length<t;){let l=o.filter(m=>c+m.evidenceCharacters<=n||i&&s.length===0);if(l.length===0)break;let u=l.filter(m=>m.roles.includes("location")||m.roles.includes("definition")).sort(r);l.sort((m,p)=>Hb(p,a)-Hb(m,a)||r(m,p));let d=u[0]??l[0];s.push(d),c+=d.evidenceCharacters;for(let m of qb(d))a.add(m.key);o.splice(o.indexOf(d),1)}return{selected:s,omitted:o.sort(r)}}function Hb(e,t){let n=qb(e).reduce((o,s)=>o+(t.has(s.key)?0:s.weight),0),r=Math.max(0,8-e.priority)*20,i=Math.min(500,Math.ceil(e.evidenceCharacters/160));return n+r-i}function qb(e){return[...e.reasons.map(pA),...e.roles.map(t=>({key:`role:${t}`,weight:fA(t)})),{key:`file:${e.relativePath}`,weight:180},{key:`scope:${gA(e.relativePath)}`,weight:120},{key:`kind:${e.fileKind}`,weight:40},...e.symbols.map(t=>({key:`symbol:${t}`,weight:100})),...e.behaviorSignals.map(t=>({key:`behavior:${t}`,weight:70}))]}function pA(e){let t=e.indexOf(":"),n=t<0?e:e.slice(0,t);return n==="dependency"||n==="consumer"?{key:`reason:${n}`,weight:220}:{key:`reason:${e}`,weight:n==="location"||n==="definition"?1400:800}}function fA(e){switch(e){case"location":return 1200;case"definition":return 1100;case"reference":return 600;case"caller":case"callee":return 550;case"dependency":case"consumer":return 500;case"search":return 400;default:return 300}}function gA(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}var Gb=64,zb=12;function za(e,t,n={}){if(t.length===0)return[];let r=n.context??6;if(!Number.isSafeInteger(r)||r<0)throw new RangeError(`context must be a non-negative safe integer; received ${r}`);let i=n.limit??12;if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`limit must be a positive safe integer; received ${i}`);let o=t.map(s=>{if(s.length===0)throw new Error("The source search pattern must not be empty.");return{pattern:s,regexp:n.regexp?kr(s,"source search pattern",n.ignoreCase?"iu":"u"):null,literal:n.ignoreCase?s.toLocaleLowerCase():s,identities:[],fileCoverage:[],textByPath:new Map}});if(!n.regexp&&!n.ignoreCase){let s=o.map(c=>Buffer.from(c.pattern,"utf8")),a=Qs(e,{scope:n.scope,literalBytes:s.length===1?s[0]:s},(c,l)=>{let u=Nn(c.text);if(u.length!==0)for(let d of l){let m=o[d];m&&Kb(e,m,c,u,n)}});return o.map(c=>Wb(c,a,r,i,n))}return o.map(s=>{let a=Qs(e,{scope:n.scope},c=>{let l=Nn(c.text);l.length>0&&Kb(e,s,c,l,n)});return Wb(s,a,r,i,n)})}function Kb(e,t,n,r,i){let o=[];for(let l=0;l<r.length;l+=1){let u=r[l]??"",d=u.endsWith("\r")?u.slice(0,-1):u;(t.regexp?t.regexp.test(d):(i.ignoreCase?d.toLocaleLowerCase():d).includes(t.literal))&&o.push(l)}if(o.length===0)return;let s=n.relativePath;t.textByPath.set(s,n.text);let a=n.freshness.semantic.state!=="stale"&&n.freshness.semantic.basis!=="no-compiler-document"?U(e,s):[],c=K(e,s)?.callables??[];for(let l of o){let u=Ne(a,l),d=_n(c,l),m=u&&!me(u.symbol)?u:null,p=m?.startLine??d?.startLine??u?.startLine??l,f=m?.endLine??d?.endLine??u?.endLine??l,g=po(e,s,l,p,f);t.identities.push({relativePath:s,focusLine:l,ownerSymbol:m?.symbol??null,ownerShort:m?T(m.symbol):d?.name??(u?T(u.symbol):null),ownerStartLine:g.startLine,ownerEndLine:g.endLine,fileKind:q(s),freshness:n.freshness})}t.fileCoverage.push({relativePath:s,matchingLines:o.length,returnedMatches:0,freshness:n.freshness})}function Wb(e,t,n,r,i){e.identities.sort(Yb);let o=e.identities.length>Gb?Vb(e.identities,Gb):e.identities,a=(r===Number.MAX_SAFE_INTEGER?e.identities:i.ranking?Vb(e.identities,r):e.identities.slice(0,r)).flatMap(u=>{let d=e.textByPath.get(u.relativePath),m=d===void 0?null:hA(u.relativePath,d,u.focusLine,n);return m?[{...m,...u}]:[]}),c=new Map;for(let u of a)c.set(u.relativePath,(c.get(u.relativePath)??0)+1);for(let u of e.fileCoverage)u.returnedMatches=c.get(u.relativePath)??0;let l=yA(e.fileCoverage);return{pattern:e.pattern,mode:i.regexp?"regexp":"literal",identities:e.identities,...o.length<e.identities.length?{identityManifest:o}:{},identityCoverage:{mode:o.length===e.identities.length?"complete":"bounded",returned:o.length,total:e.identities.length,omitted:e.identities.length-o.length},matches:a,matchingLines:e.identities.length,matchingFiles:e.fileCoverage.length,omittedMatches:Math.max(0,e.identities.length-a.length),fileCoverage:e.fileCoverage,scopeHints:l.slice(0,zb),omittedScopeHints:Math.max(0,l.length-zb),scannedFiles:t.scannedTextFiles,textCoverage:{basis:"current-project-text-files",candidateFiles:t.candidateFiles,scannedTextFiles:t.scannedTextFiles,scannedBytes:t.scannedBytes,skippedBinaryPaths:t.skippedBinaryPaths,skippedUnreadablePaths:t.skippedUnreadablePaths,skippedOversizedPaths:t.skippedOversizedPaths,semanticFiles:t.semanticFiles}}}function hA(e,t,n,r){let i=t.split(`
63
- `),o=t.endsWith(`
64
- `)?i.length-1:i.length;if(n<0||n>=o)return null;let s=Math.max(0,n-r),a=Math.min(o-1,n+r);return{relativePath:e,startLine:s,endLine:a,focusLine:n,source:i.slice(s,a+1).join(`
65
- `)}}function yA(e){let t=new Map;for(let n of e){let r=bA(n.relativePath),i=t.get(r)??{matchingLines:0,matchingFiles:0};i.matchingLines+=n.matchingLines,i.matchingFiles+=1,t.set(r,i)}return[...t.entries()].map(([n,r])=>({scope:n,...r})).sort((n,r)=>r.matchingLines-n.matchingLines||r.matchingFiles-n.matchingFiles||n.scope.localeCompare(r.scope))}function bA(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}function Vb(e,t){let n=e.map((i,o)=>({...i,priority:xe(i.fileKind),sequence:o,evidenceCharacters:1,roles:["search"],reasons:["search"],symbols:i.ownerSymbol?[i.ownerSymbol]:[],behaviorSignals:[]})),r=[];for(let i of[0,1,2]){let o=t-r.length;if(o===0)break;let s=n.filter(a=>xe(a.fileKind)===i);r.push(...Ga(s,o,Number.MAX_SAFE_INTEGER,Yb).selected)}return r.map(({priority:i,sequence:o,evidenceCharacters:s,roles:a,reasons:c,symbols:l,behaviorSignals:u,...d})=>d)}function Yb(e,t){return xe(e.fileKind)-xe(t.fileKind)||+(t.ownerSymbol!==null)-+(e.ownerSymbol!==null)||e.relativePath.localeCompare(t.relativePath)||e.focusLine-t.focusLine}function SA(e,t,n={}){if(t.length===0)throw new Error("The source search pattern must not be empty.");return za(e,[t],n)[0]}function Ka(e,t){return ee(e)-ee(t)||e.relativePath.localeCompare(t.relativePath)}function he(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function wi(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}`;t.has(i)||(t.add(i),n.push(r))}return n}function ke(e){return[...new Set((e??[]).map(t=>t.trim()).filter(Boolean))]}function qe(e){return e.replace(/^#/u,"").replace(/\(\)$/u,"")}var Jb=new WeakMap,Xb=new WeakMap,Qb=new WeakMap,Zb=new WeakMap,eS=new WeakMap;function tS(e,t){let n=Xb.get(e);n||(n=new Map,Xb.set(e,n));let r=n.get(t);if(r)return r;let i=J(e,t)?.rootNode;if(!i)return n.set(t,[]),[];let o=new Set;Qt(i,l=>{if(l.type!=="call_expression")return;let u=l.childForFieldName("function")??l.namedChild(0),d=/^([A-Za-z_$][\w$]*(?:\.Service)?)\.of$/u.exec(u?.text.replace(/\s+/gu,"")??"");d&&o.add(d[1])});let s=ae(e,t).filter(l=>!!l.sourcePath),a=new Set;for(let l of o){let u=/^([A-Za-z_$][\w$]*)\.Service$/u.exec(l);if(u){for(let d of s)d.localName===u[1]&&a.add(d.sourcePath);continue}if(l==="Service"){U(e,t).some(d=>d.leaf==="Service")&&a.add(t);for(let d of s)(d.localName??d.importedName)==="Service"&&a.add(d.sourcePath)}}let c=cd([...a]).sort();return n.set(t,c),c}function nr(e,t,n={}){let i=Gt(e,t)?.filter(p=>!n.ranges||n.ranges.some(f=>p.line>=f.startLine&&p.line<=f.endLine));if(!i)return{targets:[],unresolvedCallsites:0};let o=ae(e,t).filter(p=>!!p.sourcePath),s=_A(W(e,t)??""),a=J(e,t)?.rootNode??null,c=a?CA(a):nS(),l=new Map,u=zt(e),d=[],m=0;for(let p of i){if(!p.memberAccess)continue;let f=_t(t,u.get(p.calleeLeaf)??[]);if(n.excludeIndexedTargets!==!1&&$n(e,t,f,!0,p.calleeQualifier))continue;let g=p.calleeQualifier,h=FA(e,t,p,o);if(h){d.push(h);continue}let b=vA(e,t,p,o,xA(c,p.calleeQualifier,p.line));if(b.length>0){d.push(...b);continue}let S=RA(e,t,p);if(S.length>0){d.push(...S);continue}let y=g?s.get(g)??g:null,v=(y?cd(o.filter(R=>(R.localName??R.importedName)===y).map(R=>R.sourcePath)):[]).flatMap(R=>{let E=l.get(R);return E||(E=Et(e,R)??[],l.set(R,E)),E.filter(w=>w.name===p.calleeLeaf).map(w=>({file:R,callable:w}))});if(v.length!==1){m+=1;continue}let C=v[0];d.push({calleeLeaf:p.calleeLeaf,line:p.line,sourceFile:t,targetFile:C.file,targetStartLine:C.callable.startLine,targetEndLine:C.callable.endLine,resolution:"direct-import-receiver",strength:"candidate"})}return{targets:d,unresolvedCallsites:m}}function vA(e,t,n,r,i){let o=n.calleeQualifier;if(!o||!/^[A-Za-z_$][\w$]*$/u.test(o))return[];if(i.size!==1)return[];let s=[...i][0],a=cd(r.filter(u=>u.localName===s||u.importedName===s).map(u=>u.sourcePath));if(a.length!==1)return[];let c=a[0],l=LA(e,c,n.calleeLeaf);return l.map(u=>({calleeLeaf:u.name,line:n.line,sourceFile:t,targetFile:u.file,targetStartLine:u.startLine,targetEndLine:u.endLine,serviceFile:c,resolutionAlternativeCount:l.length,resolution:"imported-service-object-member",strength:"candidate"}))}function nS(){return{declarations:new Map,callbacks:[]}}function CA(e){let t=nS();return Qt(e,n=>{if(n.type==="variable_declarator"){let c=n.childForFieldName("name")??n.namedChild(0),l=n.childForFieldName("value")??n.namedChild(1);if(c?.type!=="identifier"||!l)return;let u=new Set;if(Qt(l,d=>{if(d.type!=="member_expression")return;let m=d.childForFieldName("object")??d.namedChild(0),p=d.childForFieldName("property")??d.namedChild(1);m?.type==="identifier"&&p?.text==="Service"&&u.add(m.text)}),u.size===1){let d=t.declarations.get(c.text)??[];d.push({line:n.startPosition.row,alias:[...u][0]}),t.declarations.set(c.text,d)}return}if(!["arrow_function","function_expression","generator_function"].includes(n.type))return;let r=n.childForFieldName("parameters")??n.childForFieldName("parameter");if(!r)return;let i=n.parent;for(;i&&i.type!=="call_expression";)i=i.parent;if(!i)return;let o=i.childForFieldName("function")??i.namedChild(0),s=/^([A-Za-z_$][\w$]*)\.Service\.use$/u.exec(o?.text??"");if(!s)return;let a=new Set;Qt(r,c=>{c.type==="identifier"&&a.add(c.text)}),a.size!==0&&t.callbacks.push({startLine:n.startPosition.row,endLine:n.endPosition.row,receivers:a,alias:s[1]})}),t}function xA(e,t,n){if(!t||!/^[A-Za-z_$][\w$]*$/u.test(t))return new Set;let r=new Set((e.declarations.get(t)??[]).filter(i=>i.line<=n).map(i=>i.alias));for(let i of e.callbacks)i.startLine<=n&&i.endLine>=n&&i.receivers.has(t)&&r.add(i.alias);return r}function RA(e,t,n){let r=n.calleeQualifier;if(!r||!/^[A-Za-z_$][\w$]*$/u.test(r))return[];let i=J(e,t)?.rootNode;if(!i)return[];let o=EA(e,t,i,n.line,n.calleeLeaf,r),s=o?wA(o,r):null;if(!s)return[];if(!IA(s))return[];let a=(Et(e,t)??[]).filter(p=>p.startLine<=s.startPosition.row&&p.endLine>=s.endPosition.row).sort((p,f)=>p.endLine-p.startLine-(f.endLine-f.startLine))[0];if(!a)return[];let c=U(e,t).filter(p=>p.isFunctionLike&&p.leaf===a.name);if(c.length!==1)return[];let l=c[0],u=Zb.get(e);u||(u=new Map,Zb.set(e,u));let d=`${l.symbol}\0${n.calleeLeaf}`,m=u.get(d);if(!m){let p=[];for(let f of eo(e,l)){let g=J(e,f.file)?.rootNode;if(!g)continue;let h=Ns(g,"call_expression").filter(y=>y.startPosition.row>f.line||y.endPosition.row<f.line?!1:(y.childForFieldName("function")??y.namedChild(0))?.text.replace(/\s+/gu,"").replace(/<[^<>]*>$/u,"").match(/[A-Za-z_$][\w$]*$/u)?.[0]===l.leaf);if(h.length!==1)continue;let S=h[0].childForFieldName("arguments")?.namedChildren.find(y=>Fr(y).type==="object");if(S)for(let y of Fr(S).namedChildren){if(y.type==="shorthand_property_identifier"&&y.text===n.calleeLeaf){p.push(...Wa(e,f.file,n.calleeLeaf,y,y));continue}if(y.type!=="pair")continue;let x=y.childForFieldName("key")??y.namedChild(0),v=y.childForFieldName("value")??y.namedChild(1);Va(x?.text)!==n.calleeLeaf||!v||p.push(...Wa(e,f.file,n.calleeLeaf,v,y))}}m=p.filter((f,g,h)=>h.findIndex(b=>b.file===f.file&&b.startLine===f.startLine&&b.endLine===f.endLine&&b.name===f.name)===g),u.set(d,m)}return m.map(p=>({calleeLeaf:p.name,line:n.line,sourceFile:t,targetFile:p.file,targetStartLine:p.startLine,targetEndLine:p.endLine,resolutionAlternativeCount:m.length,resolution:"factory-callback-member",strength:m.length===1?"exact":"candidate"}))}function EA(e,t,n,r,i,o){let s=Qb.get(e);s||(s=new Map,Qb.set(e,s));let a=s.get(t);if(!a){a=new Map;for(let c of Ns(n,"call_expression")){let l=c.childForFieldName("function")??c.namedChild(0),u=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(l?.text.replace(/\s+/gu,"")??"");if(u)for(let d=c.startPosition.row;d<=c.endPosition.row;d+=1){let m=`${d}\0${u[1]}\0${u[2]}`,p=a.get(m);(!p||c.endIndex-c.startIndex<p.endIndex-p.startIndex)&&a.set(m,c)}}s.set(t,a)}return a.get(`${r}\0${o}\0${i}`)??null}function IA(e){return e.descendantsOfType("return_statement").some(t=>{let n=t.childForFieldName("argument")??t.namedChild(0);return!!(n&&Fr(n).type==="object")})}function wA(e,t){let n=e.parent;for(;n;){if(/(?:function|method|lambda)/u.test(n.type)||n.type==="arrow_function"){let r=n.childForFieldName("parameters")??n.childForFieldName("parameter"),i=!1;if(r&&Qt(r,o=>{o.type==="identifier"&&o.text===t&&(i=!0)}),i)return n}n=n.parent}return null}function Wa(e,t,n,r,i){if(r.type==="identifier")return(Et(e,t)??[]).filter(c=>c.name===r.text).map(c=>({...c,file:t}));let o=sd(e,t,r.text);if(o.length>0)return o;if(!ad(r))return[];let a=(Et(e,t)??[]).filter(c=>c.startLine>=i.startPosition.row&&c.endLine<=i.endPosition.row&&(c.name===n||c.name.startsWith("source@"))).sort((c,l)=>c.endLine-c.startLine-(l.endLine-l.startLine))[0];return[a?{...a,file:t}:{name:n,file:t,startLine:i.startPosition.row,endLine:i.endPosition.row}]}function LA(e,t,n){let r=eS.get(e);r||(r=new Map,eS.set(e,r));let i=`${t}\0${n}`,o=r.get(i);if(o)return o;let s=MA(e,t).flatMap(a=>PA(e,a,t,n));return r.set(i,s),s}function PA(e,t,n,r){let i=J(e,t)?.rootNode,o=Et(e,t)??[];if(!i)return[];let s=TA(e,t,n);if(s.size===0)return[];let a=new Set,c=[],l=[],u=[];return Qt(i,m=>{if(DA(m,s)){if(m.type==="pair"){let p=m.childForFieldName("key")??m.namedChild(0),f=m.childForFieldName("value")??m.namedChild(1);if(Va(p?.text)!==r||!f)return;if(f.type==="identifier")a.add(f.text);else if(ad(f))c.push({name:r,startLine:m.startPosition.row,endLine:m.endPosition.row});else{let g=kA(e,t,f.text),h=sd(e,t,f.text);if(g.length>0)u.push(...g);else if(h.length>0)u.push(...h);else{let b=AA(m);b&&l.push(b)}}return}m.type==="shorthand_property_identifier"&&m.text===r&&a.add(r)}}),[...o.filter(m=>a.has(m.name)).map(m=>({...m,file:t})),...c.map(m=>({...m,file:t})),...l.map(m=>({...m,file:t})),...u].filter((m,p,f)=>f.findIndex(g=>g.file===m.file&&g.name===m.name&&g.startLine===m.startLine&&g.endLine===m.endLine)===p)}function DA(e,t){let n=e,r=null;for(;n;){if(n.type==="object"&&(r=n),n.type==="call_expression"){if(!r)return!1;let i=n.childForFieldName("function")??n.namedChild(0);return i?t.has(i.text.replace(/\.of$/u,""))&&i.text.endsWith(".of"):!1}n=n.parent}return!1}function MA(e,t){let n=Jb.get(e);n||(n=new Map,Jb.set(e,n));let r=n.get(t);if(r)return r;let i=new Set([t]),o=U(e,t).filter(a=>a.leaf==="Service"&&a.isTypeLike);for(let a of o)for(let c of eo(e,a))i.add(c.file);let s=[...i].sort();return n.set(t,s),s}function TA(e,t,n){let r=new Set;Fe(t,n)&&r.add("Service");for(let i of ae(e,t)){if(!i.sourcePath||!Fe(i.sourcePath,n))continue;if(i.kind==="namespace"&&i.localName){r.add(`${i.localName}.Service`);continue}(i.importedName==="default"?i.localName:i.importedName)==="Service"?r.add(i.localName??i.importedName):i.localName&&i.importedName!=="default"&&r.add(`${i.localName}.Service`)}return r}function sd(e,t,n){let r=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(n.replace(/\s+/gu,""));if(!r)return[];let i=J(e,t)?.rootNode;if(!i)return[];let o=rS(i,r[1]),s=o?iS(o):null;if(!s)return[];let a=s.childForFieldName("function")??s.namedChild(0),c=a?oS(e,t,a.text):[];if(c.length!==1)return[];let l=c[0],u=J(e,l.relativePath)?.rootNode;if(!u)return[];let d=Cl(u,l.startLine,l.endLine);if(!d)return[];let m=[];for(let p of d.descendantsOfType("return_statement")){let f=p.childForFieldName("argument")??p.namedChild(0);if(!f)continue;let g=Fr(f);if(g.type==="object")for(let h of g.namedChildren){if(h.type==="shorthand_property_identifier"&&h.text===r[2]){for(let y of Et(e,l.relativePath)??[])y.name===r[2]&&m.push({...y,file:l.relativePath});continue}if(h.type!=="pair")continue;let b=h.childForFieldName("key")??h.namedChild(0),S=h.childForFieldName("value")??h.namedChild(1);if(!(Va(b?.text)!==r[2]||!S))if(S.type==="identifier")for(let y of Et(e,l.relativePath)??[])y.name===S.text&&m.push({...y,file:l.relativePath});else ad(S)&&m.push({name:r[2],startLine:h.startPosition.row,endLine:h.endPosition.row,file:l.relativePath})}}return m.filter((p,f,g)=>g.findIndex(h=>h.file===p.file&&h.name===p.name&&h.startLine===p.startLine&&h.endLine===p.endLine)===f)}function kA(e,t,n){let r=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(n.replace(/\s+/gu,""));if(!r)return[];let i=J(e,t)?.rootNode;if(!i)return[];let o=rS(i,r[1]),s=o?iS(o):null,a=s?.childForFieldName("function")??s?.namedChild(0),c=a?oS(e,t,a.text):[];if(c.length!==1||!s)return[];let l=c[0],u=J(e,l.relativePath)?.rootNode;if(!u)return[];let d=Cl(u,l.startLine,l.endLine);if(!d)return[];let m=new Set,p=d.childForFieldName("parameters")??d.childForFieldName("parameter");if(p&&Qt(p,R=>{R.type==="identifier"&&m.add(R.text)}),m.size===0)return[];let f=sd(e,t,n);if(f.length===0)return[];let g=(Et(e,l.relativePath)??[]).filter(R=>R.startLine>=l.startLine&&R.endLine<=l.endLine),h=(Gt(e,l.relativePath)??[]).filter(R=>R.line>=l.startLine&&R.line<=l.endLine),b=new Set,S=f.map(R=>({name:R.name,startLine:R.startLine,endLine:R.endLine})),y=new Set;for(;S.length>0&&y.size<32;){let R=S.shift(),E=`${R.name}\0${R.startLine}\0${R.endLine}`;if(!y.has(E)){y.add(E);for(let w of h.filter(I=>I.line>=R.startLine&&I.line<=R.endLine)){if(w.memberAccess&&w.calleeQualifier&&m.has(w.calleeQualifier)){b.add(w.calleeLeaf);continue}if(w.memberAccess)continue;let I=g.filter(k=>k.name===w.calleeLeaf);I.length===1&&S.push(I[0])}}}if(b.size===0)return[];let v=s.childForFieldName("arguments")?.namedChildren.find(R=>Fr(R).type==="object");if(!v)return[];let C=[];for(let R of Fr(v).namedChildren){if(R.type==="shorthand_property_identifier"&&b.has(R.text)){C.push(...Wa(e,t,R.text,R,R));continue}if(R.type!=="pair")continue;let E=R.childForFieldName("key")??R.namedChild(0),w=R.childForFieldName("value")??R.namedChild(1),I=Va(E?.text);!I||!b.has(I)||!w||C.push(...Wa(e,t,I,w,R))}return C.filter((R,E,w)=>w.findIndex(I=>I.file===R.file&&I.name===R.name&&I.startLine===R.startLine&&I.endLine===R.endLine)===E)}function rS(e,t){for(let n of Ns(e,"variable_declarator"))if((n.childForFieldName("name")??n.namedChild(0))?.text===t)return n.childForFieldName("value")??n.namedChild(1);return null}function iS(e){return e.type==="call_expression"?e:e.descendantsOfType("call_expression")[0]??null}function oS(e,t,n){let r=n.replace(/\s+/gu,"").replace(/<[^<>]*>$/u,""),i=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(r);if(i){let d=ae(e,t).filter(f=>f.localName===i[1]&&f.sourcePath);if(d.length!==1||!d[0].sourcePath)return[];let m=d[0].sourcePath,p=qn(e,m,i[2]).filter(f=>f.isFunctionLike);return p.length>0?p:(Et(e,m)??[]).filter(f=>f.name===i[2]).map(f=>({...f,relativePath:m}))}if(!/^[A-Za-z_$][\w$]*$/u.test(r))return[];let o=U(e,t).filter(d=>d.leaf===r&&d.isFunctionLike);if(o.length>0)return o;let s=(Et(e,t)??[]).filter(d=>d.name===r).map(d=>({...d,relativePath:t}));if(s.length>0)return s;let a=ae(e,t).filter(d=>d.localName===r&&d.sourcePath&&d.kind!=="namespace");if(a.length!==1||!a[0].sourcePath)return[];let c=a[0].sourcePath,l=a[0].importedName==="default"?r:a[0].importedName,u=qn(e,c,l).filter(d=>d.isFunctionLike);return u.length>0?u:(Et(e,c)??[]).filter(d=>d.name===l).map(d=>({...d,relativePath:c}))}function ad(e){return["arrow_function","function_expression","generator_function"].includes(e.type)||e.descendantsOfType(["arrow_function","function_expression","generator_function"]).length>0}function AA(e){let t=e.parent;for(;t;){if(t.type==="variable_declarator"){let n=t.childForFieldName("name")??t.namedChild(0);if(n?.type==="identifier")return{name:n.text,startLine:t.startPosition.row,endLine:t.endPosition.row}}t=t.parent}return null}function Va(e){return e?e.replace(/^(?:['"])(.*)(?:['"])$/u,"$1"):null}function FA(e,t,n,r){let i=/^this\.([A-Za-z_$][\w$]*)$/u.exec(n.calleeQualifier??"");if(!i)return null;let o=J(e,t)?.rootNode;if(!o)return null;let s=NA(o,n.line);if(!s)return null;let a=new Set;if(Qt(s,g=>{if(g.type!=="assignment_expression")return;let h=g.childForFieldName("left")??g.namedChild(0),b=g.childForFieldName("right")??g.namedChild(g.namedChildCount-1);if(h?.text.replace(/\s+/gu,"")!==`this.${i[1]}`||!b)return;let S=Fr(b);if(S.type!=="new_expression")return;let x=(S.childForFieldName("constructor")??S.namedChild(0))?.text.match(/[A-Za-z_$][\w$]*$/u)?.[0];x&&a.add(x)}),a.size!==1)return null;let c=[...a][0],l=r.filter(g=>g.localName===c);if(l.length!==1)return null;let u=l[0].importedName==="default"?c:l[0].importedName,d=l[0].importedName==="default"?qn(e,l[0].sourcePath,c):[],m=d.length===1?d[0].leaf:u,p=U(e,l[0].sourcePath).filter(g=>g.isFunctionLike&&g.leaf===n.calleeLeaf&&ff(g.symbol)===m);if(p.length!==1)return null;let f=p[0];return{calleeLeaf:n.calleeLeaf,line:n.line,sourceFile:t,targetFile:f.relativePath,targetStartLine:f.startLine,targetEndLine:f.endLine,targetSymbol:f.symbol,resolution:"constructed-member-receiver",strength:"exact"}}function NA(e,t){let n=[];return Qt(e,r=>{["class","class_declaration","class_definition"].includes(r.type)&&r.startPosition.row<=t&&r.endPosition.row>=t&&n.push(r)}),n.sort((r,i)=>r.endPosition.row-r.startPosition.row-(i.endPosition.row-i.startPosition.row))[0]??null}function Fr(e){let t=e;for(;["parenthesized_expression","as_expression","type_assertion","satisfies_expression"].includes(t.type)&&t.namedChildCount===1;)t=t.namedChild(0);return t}function Qt(e,t){t(e);for(let n of e.namedChildren)Qt(n,t)}function _A(e){let t=new Map,n=/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*([A-Za-z_$][\w$]*)\s*;/gu;for(let r of e.matchAll(n)){let i=r[1],o=r[2];i&&o&&t.set(i,o)}return t}function cd(e){let t=[];for(let n of e)t.some(r=>Fe(r,n))||t.push(n);return t}import{existsSync as BA}from"fs";import{SymbolRole as $A}from"@c4312/scip";import{deserializeSCIP as OA}from"@c4312/scip";function sS(e,t){return OA(Qr(e,{inputKind:t,maxBytes:Xr}))}var ld=new WeakMap;function En(e,t,n,r){let i=K(e,t),o=(i?.callSites??[]).filter(p=>p.line>=n&&p.line<=r);if(!i||o.length===0)return{available:!!i,targets:[],resolvedCallsites:0,unresolvedCallsites:0};let s=dd(e);if(!s)return{available:!1,targets:[],resolvedCallsites:0,unresolvedCallsites:o.length};let a=(s.byFile.get(t)??[]).filter(p=>p.sourceLine>=n&&p.sourceLine<=r).map(p=>({...p,calleeLeaf:p.definition.leaf})),c=aS(o.map(p=>({line:p.line,leaf:p.calleeLeaf}))),l=aS(a.map(p=>({line:p.sourceLine,leaf:p.calleeLeaf}))),u=new Set([...c].flatMap(([p,f])=>l.get(p)===f?[p]:[])),d=a.filter(p=>u.has(lS(p.sourceLine,p.calleeLeaf))),m=[...u].reduce((p,f)=>p+(c.get(f)??0),0);return{available:!0,targets:d,resolvedCallsites:m,unresolvedCallsites:Math.max(0,o.length-m)}}function ud(e,t,n,r){let i=dd(e);return i?{available:!0,targets:(i.byFile.get(t)??[]).filter(o=>o.sourceLine>=n&&o.sourceLine<=r)}:{available:!1,targets:[]}}function cS(e,t,n,r){let i=dd(e);return i?{available:!0,targets:(i.byFile.get(t)??[]).filter(o=>o.sourceLine>=n&&o.sourceLine<=r&&Ya(e,o.definition)).map(o=>({...o,calleeLeaf:o.definition.leaf}))}:{available:!1,targets:[]}}function dd(e){if(ld.has(e))return ld.get(e)??null;let t=jA(e);return ld.set(e,t),t}function jA(e){if(!e.generation.indexPath||!BA(e.generation.indexPath))return null;try{let t=Le(e),n=new Map(t.map(o=>[o.symbol,o])),r=sS(e.generation.indexPath,"SCIP source-range call-target index"),i=new Map;for(let o of r.documents??[]){let s=o.relativePath;if(!s||e.isIgnored(s))continue;let a=[];for(let c of o.occurrences??[]){if(!c.symbol||(c.symbolRoles&$A.Definition)!==0)continue;let l=n.get(c.symbol),u=c.range?.[0];!l||!Number.isInteger(u)||a.push({sourceLine:u,definition:l})}i.set(s,a)}return{byFile:i}}catch{return null}}function Ya(e,t){if(!t.isFunctionLike)return!1;let n=K(e,t.relativePath);return!n||n.callables.some(r=>r.name===t.leaf&&r.startLine===t.startLine&&r.endLine===t.endLine)?!0:HA(t)}function HA(e){let t=e.documentation;if(!t)return!1;let n=e.leaf.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`\\bfunction\\s+${n}\\s*(?:<[^>]*>)?\\s*\\(`,"u").test(t)||new RegExp(`\\b(?:const|let|var)\\s+${n}\\s*:\\s*(?:<[^>]*>\\s*)?\\([^\\n]*\\)\\s*=>`,"u").test(t)}function aS(e){let t=new Map;for(let n of e){let r=lS(n.line,n.leaf);t.set(r,(t.get(r)??0)+1)}return t}function lS(e,t){return`${e}\0${t}`}var UA=16,qA=4,md=3e3,GA=800,zA=new Set(["assignment","const_declaration","const_item","field_declaration","lexical_declaration","local_declaration_statement","local_variable_declaration","static_item","variable_declaration"]);function gS(e,t,n={}){let r=n.maxSteps??UA;if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`maxSteps must be a positive safe integer; received ${r}`);let i=new Map(t.nodes.map(M=>[M.id,M])),o=QA(n.focusLocations??[]),s=new Set,a=new Map(t.edges.map(M=>[M.id,M])),c=In(t.paths.flatMap(M=>M.nodeIds)),l=In(t.anchors.filter(M=>M.status==="matched").flatMap(M=>M.nodeIds)),u=t.nodes.filter(M=>M.disposition==="emitted"&&M.attributes.upstreamCausalPath===!0).sort((M,$)=>Number($.attributes.upstreamCausalDistance??0)-Number(M.attributes.upstreamCausalDistance??0)||M.id.localeCompare($.id)).map(M=>M.id),d=new Set(u),m=Math.max(0,r-l.length),f=KA(t,l,o,m).slice(0,m),g=new Set(f),h=new Set(f),b=new Set([...c,...u,...l]),S=t.edges.filter(M=>M.disposition==="emitted"&&M.kind!=="structural-membership"),y=t.edges.filter(M=>M.disposition!=="excluded"&&M.disposition!=="unsupported"&&M.kind!=="structural-membership"),x=new Set([...t.paths.flatMap(M=>M.edgeIds),...S.filter(M=>d.has(M.fromNodeId)&&d.has(M.toNodeId)).map(M=>M.id)]),v=t.paths.some(M=>M.edgeIds.length>0),C=new Set(l);for(let M of f)C.add(M);for(let M of t.paths){let $=M.nodeIds[0],Y=a.get(M.edgeIds[0]??""),oe=M.nodeIds[1];$&&oe&&Y?.fromNodeId===$&&Y.toNodeId===oe&&C.add($)}if(t.paths.every(M=>M.nodeIds.length===0))for(let M of t.anchors)for(let $ of M.nodeIds)C.add($);let R=rF(l,y,i,qA),E=In(S.filter(M=>M.kind==="call"&&l.includes(M.fromNodeId)).map(M=>M.toNodeId)),w=new Set(In([...R,...v?[]:E]));for(let M of w)C.add(M);let I=In(S.flatMap(M=>b.has(M.fromNodeId)||b.has(M.toNodeId)?[M.fromNodeId,M.toNodeId]:[])),k=t.nodes.filter(M=>M.disposition==="emitted"&&M.kind!=="structural-region"&&S.some($=>$.fromNodeId===M.id||$.toNodeId===M.id)).map(M=>M.id),D=In([...u,...c,...l,...f,...w,...I,...k]).filter(M=>i.has(M)),F=[];for(let M of D)v&&!b.has(M)&&!g.has(M)&&!w.has(M)||F.length>=r&&!b.has(M)||F.push(M);let L=new Set(F),A=new Map(F.map(M=>[M,oF(M)])),P=new Set([...c,...u]),j=new Set(t.anchors.flatMap(M=>M.nodeIds)),B=F.map((M,$)=>{let Y=i.get(M),oe=XA(Y,o);for(let Ae of oe)s.add(Li(Y.location.file,Ae));return{id:A.get(M),nodeId:M,order:$,role:j.has(M)?"anchor":P.has(M)?"connector":"junction",kind:Y.kind,label:Y.label,location:Y.location,behavior:WA(e,Y,j.has(M),[...new Set([...oe,...JA(e,Y,y,i,x,C)])],oe,C.has(Y.id)&&(oe.length===0||j.has(Y.id)),w.has(Y.id),h.has(Y.id)&&oe.length===0)}}),X=new Map;for(let M of t.paths)for(let $=0;$<M.edgeIds.length;$+=1){let Y=a.get(M.edgeIds[$]),oe=M.nodeIds[$],Ae=M.nodeIds[$+1];!Y||!oe||!Ae||X.set(Y.id,Y.fromNodeId===oe&&Y.toNodeId===Ae?"forward":"reverse")}let O=y.filter(M=>L.has(M.fromNodeId)&&L.has(M.toNodeId)).sort((M,$)=>iF(M,$,t)).map((M,$)=>({id:sF(M.id),edgeId:M.id,order:$,kind:M.kind,fromStepId:A.get(M.fromNodeId),toStepId:A.get(M.toNodeId),directed:!0,pathTraversal:X.get(M.id)??"adjacent",evidence:M.evidence})),te=new Map(O.map(M=>[M.edgeId,M.id])),ie=t.paths.map(M=>({id:M.id,status:M.status,stepIds:M.nodeIds.flatMap($=>{let Y=A.get($);return Y?[Y]:[]}),transitionIds:M.edgeIds.flatMap($=>{let Y=te.get($);return Y?[Y]:[]})})),we=B.flatMap(M=>M.location?[`${M.location.file}:${M.location.line+1}`]:[]),De=t.anchors.some(M=>M.status==="ambiguous"),Ft=ie.some(M=>M.status==="connected"||M.status==="candidate"),tt=ie.some(M=>M.status==="partial");return{status:B.length===0?"unavailable":De?"ambiguous":Ft&&!tt?"connected":tt?"partial":"connected",steps:B,transitions:O,paths:ie,coverage:{candidateNodes:D.length,returnedNodes:F.length,omittedNodeIds:D.filter(M=>!L.has(M)),returnedTransitions:O.length,withheldStatements:B.reduce((M,$)=>M+($.behavior?.coverage.omittedStatements??0),0),requestedFocusLocations:o,matchedFocusLocations:o.filter(M=>s.has(Li(M.file,M.line))),unmatchedFocusLocations:o.filter(M=>!s.has(Li(M.file,M.line)))},behaviorCommand:fS(we,"behavior"),exactSourceCommand:fS(we,"source")}}function KA(e,t,n,r){if(r<=0||n.length===0)return[];let i=new Set(t),o=new Set(n.map(s=>Li(s.file,s.line)));return In(e.edges.filter(s=>s.disposition!=="excluded"&&s.disposition!=="unsupported"&&["call","runtime-boundary"].includes(s.kind)&&i.has(s.fromNodeId)&&s.evidence.some(a=>!["candidate","unknown"].includes(a.strength)&&a.location&&o.has(Li(a.location.file,a.location.line)))).sort((s,a)=>{let c=s.evidence.find(u=>u.location)?.location,l=a.evidence.find(u=>u.location)?.location;return(c?.file??"").localeCompare(l?.file??"")||(c?.line??Number.MAX_SAFE_INTEGER)-(l?.line??Number.MAX_SAFE_INTEGER)||s.id.localeCompare(a.id)}).map(s=>s.toNodeId)).slice(0,r)}function WA(e,t,n,r,i,o,s,a){if(!t.location||!["symbol","source-construct","runtime-boundary-participant"].includes(t.kind))return null;let c=t.location.endLine??t.location.line,l=V(e,t.location.file),u=r.length>0?r:[t.location.line],d=t.kind==="runtime-boundary-participant"?ot(e,t.location.file,0,Math.max(0,l.length-1),[t.location.line]):ot(e,t.location.file,t.location.line,c,u),m=r.filter(w=>w>=d.startLine&&w<=d.endLine),p=mi(e,t.location.file,d.startLine,d.endLine,m),f=p??(m.length>0?mi(e,t.location.file,d.startLine,d.endLine,m,{requireSavings:!1}):null),g=m.length>0?ZA(e,t,d.startLine,d.endLine,m,f,o):null,h=l.slice(d.startLine,d.endLine+1).join(`
66
- `).length,b=bn(e,t.location.file,d.startLine,d.endLine),S=l.slice(d.startLine,d.endLine+1).some((w,I)=>w.length>GA&&(b.get(d.startLine+I)??[]).some(k=>["binding","branch","loop","call","return","throw","mutation"].includes(k))),y=w=>VA(e,t,d.startLine,d.endLine,i.filter(I=>I>=d.startLine&&I<=d.endLine),w),x=(s||t.kind==="runtime-boundary-participant"||t.anchorIds.length>0)&&h<=md,v=n&&(m.length===0||x);if(p&&(a||v))return y(uS(p));if(!a&&!v&&g&&!S&&!x&&g.renderedCharacters<(f?.outlineCharacters??h))return y(g);if(p)return y(uS(p));let C=l.slice(d.startLine,d.endLine+1),R=C.join(`
67
- `),E=bn(e,t.location.file,d.startLine,d.endLine);return y({kind:"source",constructKind:"source construct",signature:C.find(w=>w.trim().length>0)?.trim()??t.label,lines:C.map((w,I)=>({line:d.startLine+I,endLine:d.startLine+I,depth:0,signals:E.get(d.startLine+I)??[],text:w,copied:!0})),coverage:{sourceStatements:C.length,representedStatements:C.length,copiedStatements:C.length,omittedStatements:0},rawCharacters:R.length,renderedCharacters:R.length})}function VA(e,t,n,r,i,o){if(!t.location)return o;let s=ud(e,t.location.file,n,r);if(!s.available)return o;let a=bn(e,t.location.file,n,r),c=V(e,t.location.file),l=new Set(i);for(let S of i){let y=Ja(c[S]??"");if(!y)continue;let x=gn(e,t.location.file,y).find(v=>v>S&&v<=r);x!==void 0&&l.add(x)}let u=[...new Map(s.targets.flatMap(S=>{let y=S.definition,x=y.relativePath===t.location.file&&y.startLine<=r&&y.endLine>=n;if(y.isTypeLike||x)return[];let v=Ya(e,y),C=i.length>0&&v&&a.get(S.sourceLine)?.includes("return"),R=v&&l.has(S.sourceLine);return v&&!C&&!R?[]:[[y.symbol,{definition:y,kind:C?"return-value-transformer":R?"focused-causal-target":"compiler-referenced-declaration"}]]})).values()].sort((S,y)=>S.definition.relativePath.localeCompare(y.definition.relativePath)||S.definition.startLine-y.definition.startLine||S.definition.symbol.localeCompare(y.definition.symbol)),d=[],m=u.filter(({kind:S})=>S!=="compiler-referenced-declaration").map(({definition:S})=>({owner:S,depth:1})),p=new Set,f=new Set(u.map(({definition:S})=>S.symbol));for(;m.length>0;){let S=m.shift();if(!S||p.has(S.owner.symbol))continue;p.add(S.owner.symbol);let{owner:y,depth:x}=S,v=ud(e,y.relativePath,y.startLine,y.endLine);if(!v.available)continue;let C=bn(e,y.relativePath,y.startLine,y.endLine),R=V(e,y.relativePath);for(let E of v.targets){let w=E.definition,I=w.relativePath===y.relativePath&&w.startLine<=y.endLine&&w.endLine>=y.startLine;if(w.isTypeLike||I)continue;let k=Ya(e,w),D=Ja(R[E.sourceLine]??""),F=k&&D!==null&&gn(e,y.relativePath,D).some(A=>A>E.sourceLine&&A<=y.endLine&&(C.get(A)??[]).some(P=>["branch","return","throw"].includes(P))),L=k&&((C.get(E.sourceLine)??[]).some(A=>["branch","return","throw"].includes(A))||F);k&&!L||(f.has(w.symbol)||(f.add(w.symbol),d.push({definition:w,kind:k?"focused-causal-target":"compiler-referenced-declaration"})),k&&x<2&&m.push({owner:w,depth:x+1}))}}let g=[...new Map([...u,...d].map(S=>[S.definition.symbol,S])).values()].sort((S,y)=>S.definition.relativePath.localeCompare(y.definition.relativePath)||S.definition.startLine-y.definition.startLine||S.definition.symbol.localeCompare(y.definition.symbol)),h=[],b=[];for(let{definition:S,kind:y}of g){let x=y==="compiler-referenced-declaration"?YA(e,S.relativePath,S.startLine,S.endLine):{startLine:S.startLine,endLine:S.endLine},v=V(e,S.relativePath).slice(x.startLine,x.endLine+1).join(`
68
- `),C=y==="compiler-referenced-declaration"?null:mi(e,S.relativePath,S.startLine,S.endLine,[]),R=C?[C.signature,...C.lines.map(D=>`${D.line+1}${D.signals.length>0?`[${D.signals.join(",")}]`:""} ${D.text}`)].join(" | "):null,E=R&&R.length<v.length?R:v,w={symbol:S.symbol,label:S.leaf,file:S.relativePath,line:x.startLine,endLine:x.endLine},I=y==="compiler-referenced-declaration"?1e3:8e3,k=y==="compiler-referenced-declaration"?12:120;if(E.length>I||x.endLine-x.startLine>k){b.push({...w,reason:"source-too-large"});continue}h.push({kind:y,...w,text:E})}return{...o,...h.length===0?{}:{supportingDeclarations:h},...b.length===0?{}:{omittedSupportingDeclarations:b}}}function YA(e,t,n,r){let i=J(e,t);if(!i)return{startLine:n,endLine:r};let o=[];hS(i.rootNode,a=>{zA.has(a.type)&&a.startPosition.row<=n&&a.endPosition.row>=r&&o.push(a)});let s=o.sort((a,c)=>a.endPosition.row-a.startPosition.row-(c.endPosition.row-c.startPosition.row)||a.endIndex-a.startIndex-(c.endIndex-c.startIndex))[0];return s?{startLine:s.startPosition.row,endLine:s.endPosition.row}:{startLine:n,endLine:r}}function hS(e,t){t(e);for(let n of e.namedChildren)hS(n,t)}function uS(e){return{kind:"outline",constructKind:e.constructKind,signature:e.signature,lines:e.lines,coverage:e.coverage,rawCharacters:e.rawCharacters,renderedCharacters:e.outlineCharacters}}function JA(e,t,n,r,i,o){if(!t.location||!["symbol","source-construct","runtime-boundary-participant"].includes(t.kind))return[];let s=new Set,a=new Set(K(e,t.location.file)?.callSites.map(c=>c.line)??[]);if(t.kind==="runtime-boundary-participant"&&s.add(t.location.line),o.has(t.id))for(let c of no(e,{files:[t.location.file]}))c.source.startLine>=t.location.line&&c.source.startLine<=(t.location.endLine??t.location.line)&&s.add(c.source.startLine);for(let c of n){if(c.fromNodeId!==t.id&&c.toNodeId!==t.id)continue;let l=r.get(c.fromNodeId===t.id?c.toNodeId:c.fromNodeId),u=o.has(t.id)&&["call","reference","runtime-boundary"].includes(c.kind)&&c.fromNodeId===t.id,d=(l?.anchorIds.length??0)>0;if(!i.has(c.id)&&!u&&!d)continue;let m=c.evidence.flatMap(b=>b.location?.file===t.location.file?[b.location.line]:[]),p=m.filter(b=>a.has(b));for(let b of p.length>0?p:m)s.add(b);let f=l?.attributes.leaf;if(typeof f!="string"||f.length===0)continue;let g=gn(e,t.location.file,f).filter(b=>b>=t.location.line&&b<=(t.location.endLine??t.location.line)),h=g.find(b=>a.has(b))??g[0];h!==void 0&&s.add(h)}return[...s].sort((c,l)=>c-l)}function XA(e,t){if(!e.location)return[];let n=e.location.endLine??e.location.line;return t.filter(r=>r.file===e.location.file&&r.line>=e.location.line&&r.line<=n).map(r=>r.line)}function QA(e){let t=new Map;for(let n of e){if(!n.file||!Number.isSafeInteger(n.line)||n.line<0)throw new RangeError(`Behavior focus locations require a repository file and non-negative line; received ${JSON.stringify(n)}.`);t.set(Li(n.file,n.line),{file:n.file,line:n.line})}return[...t.values()].sort((n,r)=>n.file.localeCompare(r.file)||n.line-r.line)}function Li(e,t){return`${e}\0${t}`}function ZA(e,t,n,r,i,o,s){if(!t.location)return null;let a=V(e,t.location.file),c=bn(e,t.location.file,n,r),l=[...c].filter(([,L])=>L.length>0).map(([L])=>L).sort((L,A)=>L-A),u=i.map(L=>(c.get(L)??[]).length>0?L:l.find(A=>A>L&&A-L<=8)??L),d=new Set([...i,...u]),m=s?Ol(e,t.location.file,n,r,{minimumBodyLines:0}):null,p=o?[...new Map(u.flatMap(L=>o.lines.filter(A=>A.text.length<=500&&A.signals.some(P=>["branch","loop","catch","finally"].includes(P))&&L>=A.line&&L<=A.endLine).sort((A,P)=>A.endLine-A.line-(P.endLine-P.line)||A.line-P.line).slice(0,2).map(A=>[`${A.line}\0${A.endLine}`,A]))).values()]:aa(e,t.location.file,n,r,u);for(let L of m?.lines??[])d.add(L.line);for(let L of p)d.add(L.line);for(let[L,A]of c)A.includes("call")&&A.includes("shape")&&d.add(L);let f=[];for(let L of u){let A=Ja(a[L]??"");if(!A)continue;let P=gn(e,t.location.file,A).filter(O=>O>L&&O<=r),j=P[0];j!==void 0&&d.add(j);let B=P.find(O=>(c.get(O)??[]).some(te=>te==="branch"||te==="loop"));if(B===void 0)continue;d.add(B);let X=(o?.lines??[]).find(O=>O.line===B)??{line:B,endLine:Math.min(r,B+40),depth:0,signals:c.get(B)??[],text:(a[B]??"").trim(),copied:!0},G=o?.lines??a.slice(X.line,X.endLine+1).map((O,te)=>{let ie=X.line+te;return{line:ie,endLine:ie,depth:0,signals:c.get(ie)??[],text:O.trim(),copied:!0}});f.push({focusLine:L,governingUse:B,lines:G.filter(O=>O.line>=X.line&&O.line<=X.endLine&&O.text.length<=500&&O.signals.some(te=>["binding","branch","call","mutation"].includes(te)))})}for(let L of f.sort((A,P)=>P.governingUse-P.focusLine-(A.governingUse-A.focusLine)||A.focusLine-P.focusLine).slice(0,2))for(let A of L.lines.slice(0,14))d.add(A.line);let g=new Set(["binding","branch","loop","call","return","throw","mutation"]);for(let L of p)for(let A of o?.lines??[])A.line<L.line||A.line>L.endLine||A.signals.some(P=>g.has(P))&&d.add(A.line);let h=a.slice(n,r+1).flatMap((L,A)=>{let P=Ja(L);return P?[{name:P,line:n+A}]:[]}),b=!0;for(;b;){b=!1;for(let L of h)if([...d].some(P=>tF(a[P]??"",L.name))){d.has(L.line)||(d.add(L.line),b=!0);for(let P of gn(e,t.location.file,L.name))P<n||P>r||d.has(P)||(c.get(P)??[]).some(j=>g.has(j))&&(d.add(P),b=!0)}}for(let L of o?.lines??[])if(L.signals.some(A=>["branch","loop","catch","finally"].includes(A))&&d.has(L.line))for(let A of o?.lines??[])A.line<L.line||A.line>L.endLine||A.signals.some(P=>g.has(P))&&d.add(A.line);let S=K(e,t.location.file),y=new Set(S?.callSites.map(L=>L.line)??[]),x=c,v=new Map([...o?.lines??[],...p].filter(L=>L.signals.some(A=>["branch","loop","catch","finally"].includes(A))).map(L=>[L.line,L])),C=new Map((o?.lines??[]).filter(L=>L.text.length<=500&&L.signals.includes("shape")&&(L.signals.includes("call")||L.signals.includes("mutation")||L.signals.includes("return"))).sort((L,A)=>L.endLine-L.line-(A.endLine-A.line)||L.line-A.line).map(L=>[L.line,L])),R=new Map((m?.lines??[]).map(L=>[L.line,L.signals.filter(A=>A!=="lifecycle")])),E=[...d].filter(L=>L>=n&&L<=r).sort((L,A)=>L-A).map(L=>{let A=v.get(L)??C.get(L);return{line:L,endLine:A?.endLine??L,depth:A?.depth??0,signals:eF([...x.get(L)??[],...o?.lines.filter(P=>L>=P.line&&L<=P.endLine).flatMap(P=>P.signals)??[],...R.get(L)??[],...i.includes(L)?["anchor"]:[],...y.has(L)?["call"]:[]]),text:A?.text??(a[L]??"").trim(),copied:A?.copied??!0}}).filter(L=>L.text.length>0);if(E.length===0)return null;let w=m?.candidateLines??Ol(e,t.location.file,n,r,{minimumBodyLines:0})?.candidateLines??0,I=Math.max(o?.coverage.sourceStatements??0,w,E.length),k=o?.signature??(a[n]??t.label).trim(),D=k.length+E.reduce((L,A)=>L+A.text.length+A.signals.join(",").length+12,0),F=a.slice(n,r+1).join(`
69
- `).length;return{kind:"connector-slice",constructKind:o?.constructKind??"source construct",signature:k,lines:E,coverage:{sourceStatements:I,representedStatements:E.length,copiedStatements:E.length,omittedStatements:Math.max(0,I-E.length)},rawCharacters:F,renderedCharacters:D}}function eF(e){let t=["anchor","signature","binding","branch","loop","call","await","return","throw","mutation","shape","spread","catch","finally"],n=new Set(e);return t.filter(r=>n.has(r))}function Ja(e){return/\b(?:const|let|var)\s+([\p{L}_$][\p{L}\p{N}_$]*)\s*(?:=|\bof\b|\bin\b)/u.exec(e)?.[1]??null}function tF(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`(?:^|[^\\p{L}\\p{N}_$])${n}(?:$|[^\\p{L}\\p{N}_$])`,"u").test(e)}function nF(e,t,n){return In(e.flatMap(r=>{let i=n.get(r),o=t.filter(s=>s.kind==="call"&&s.toNodeId===r).map(s=>({edge:s,node:n.get(s.fromNodeId)})).filter(s=>s.node!==void 0&&["symbol","source-construct","runtime-boundary-participant"].includes(s.node.kind)&&s.node.location!==null).sort((s,a)=>{let c=dS(a.edge)-dS(s.edge);if(c!==0)return c;let l=mS(s.node,i)?0:1,u=mS(a.node,i)?0:1,d=(s.node.location?.endLine??s.node.location?.line??0)-(s.node.location?.line??0),m=(a.node.location?.endLine??a.node.location?.line??0)-(a.node.location?.line??0);return l-u||d-m||s.node.label.localeCompare(a.node.label)});return o[0]?[o[0].node.id]:[]}))}function dS(e){let t={exact:4,mixed:3,derived:2,candidate:1,unknown:0};return Math.max(0,...e.evidence.map(n=>t[n.strength]))}function mS(e,t){return!e.location||!t?.location?!1:pS(e.location.file)===pS(t.location.file)}function pS(e){return e.split("/").filter(Boolean).slice(0,2).join("/")}function rF(e,t,n,r){let i=new Set(e),o=new Set,s=[],a=In(e);for(let c=0;c<r&&a.length>0;c+=1){let l=a.filter(d=>!o.has(d));for(let d of l)o.add(d);let u=nF(l,t,n);a=[];for(let d of u)!i.has(d)&&!s.includes(d)&&s.push(d),o.has(d)||a.push(d)}return s}function iF(e,t,n){let r=new Map(n.paths.flatMap(i=>i.edgeIds).map((i,o)=>[i,o]));return(r.get(e.id)??Number.MAX_SAFE_INTEGER)-(r.get(t.id)??Number.MAX_SAFE_INTEGER)||e.id.localeCompare(t.id)}function oF(e){return`step:${e}`}function sF(e){return`transition:${e}`}function fS(e,t){return e.length===0?null:`scip-query inspect ${e.map(n=>`--at ${aF(n)}`).join(" ")} --view ${t}`}function aF(e){return`'${e.replace(/'/gu,`'"'"'`)}'`}function In(e){return[...new Set(e)]}var yS=4,cF=3,lF=12,uF=48,dF=64,Or=10,Nr=6,mF=24,pF=320,pd=6,fF=12,gF=1,hF=4,yF=7,bF=12,bd="source-construct:",SF=96,vF=32,bS=4,CF=32,xF=8,SS=new Set(["a","an","and","are","as","at","be","become","becomes","by","can","does","for","from","how","in","into","is","it","its","of","on","or","that","the","their","then","this","through","to","what","when","where","which","with"]);function RF(e,t,n={}){let r=AS(t),i=c0(t);if(r.length===0)throw new Error("Anchor discovery requires at least one non-trivial repository term.");let o=n.limit??yS,s=n.full===!0;if(!Number.isSafeInteger(o)||o<=0)throw new RangeError(`anchor group limit must be a positive safe integer; received ${o}`);let a=new H(e),c=a.scopedDefinitions(n.scope).filter(O=>!me(O.symbol)),l=[...c],u=new Map(l.map(O=>[O.symbol,O])),d=new Map;for(let O of c)vS(d,O,r);let m=cg(e,{scope:n.scope});for(let O of m.files){let ie=U(e,O.relativePath).filter(De=>!me(De.symbol));if(ie.length===0)continue;let we=Nn(O.text);for(let De=0;De<we.length;De+=1){let Ft=at(we[De]??""),tt=r.filter($=>Ft.has($));if(tt.length===0)continue;let M=Ne(ie,De);if(!(!M||me(M.symbol)))for(let $ of tt)Ao(d,M,$,"source",O.relativePath,De)}}let p=CS(d),f=[...d.values()].map(O=>Xa(O,p,i)).sort(Ge),g=IF(m.files,f,r),h=-1;for(let O of g){let te=U(e,O.relativePath),ie=te.filter(M=>!me(M.symbol)),we=K(e,O.relativePath)?.callables??[],De=new Map,Ft=M=>{let $=`${M.startLine}\0${M.endLine}\0${M.name}`,Y=De.get($);if(Y)return Y;let oe=EF(O.relativePath,te,M,()=>h--);return oe?(De.set($,oe),l.push(oe),u.set(oe.symbol,oe),vS(d,oe,r),oe):null};for(let M of we){let $=at(M.name);r.some(Y=>$.has(Y))&&Ft(M)}if(we.length===0)continue;let tt=Nn(O.text);for(let M=0;M<tt.length;M+=1){let $=at(tt[M]??""),Y=r.filter(gr=>$.has(gr));if(Y.length===0)continue;let oe=_n(we,M),Ae=oe?Ft(oe):null;if(!Ae)continue;let Ut=xS(ie,M);if(xS(Ut?[Ut,Ae]:[Ae],M)?.symbol===Ae.symbol)for(let gr of Y)Ao(d,Ae,gr,"source",O.relativePath,M)}}let b=CS(d),S=new Map(m.files.map(O=>[O.relativePath,O.text.split(/\r?\n/u)]));for(let O of d.values()){let te=S.get(O.definition.relativePath);te&&(O.sourceCharacters=te.slice(O.definition.startLine,O.definition.endLine+1).join(`
70
- `).length)}let y=[...d.values()].map(O=>Xa(O,b,i)).sort(Ge),x=Math.min(y.length,Math.max(lF,o*cF)),v=s?y:Pi([...y.slice(0,x),...[...y].sort(gd).slice(0,Math.max(uF,x)),...t0(y,r),...n0(y,r,b)]),C=v.length,R=v.map(O=>u.get(O.symbol)).filter(O=>O?.isFunctionLike===!0),E=wF(l),w=LF(e,a,v,R,u,E,new Set(d.keys()),n.semantic!==!1),I=MF(w,v,d,b,u),k=TF(I,b,r),D=zF(e,a,w,d,b,l,u,n.semantic!==!1),L=[...AF(e,a,I,u,b,n.semantic!==!1),...k,...I,...D].map(O=>({...O,queryPathMatches:i0(O)})).sort((O,te)=>_r(O,te,b)),A=s?L:o0(L,o,b),P=r.filter(O=>b.has(O)),j=r.filter(O=>!b.has(O)),B=Math.max(0,y.length-C),X=Math.max(0,L.length-A.length)+B,G=s?y.length:Math.min(y.length,o+yS);return{query:t,queryPathFragments:i,normalizedTerms:r,matchedTerms:P,unmatchedTerms:j,groups:A,candidateRoots:y,candidateRootCount:y.length,analyzedRootCount:C,omittedRootCount:B,omittedGroupCount:X,scannedFiles:m.files.length,scannedBytes:m.scannedBytes,recoveryCommand:X===0?null:`scip-query anchors ${tc(t)}${n.scope?` --scope ${tc(n.scope)}`:""} --limit ${G}`}}function AS(e){let t=nc(e).filter(n=>!SS.has(n.toLocaleLowerCase())).map(Sd).filter(n=>n.length>=3&&!SS.has(n));return[...new Set(t)]}function vS(e,t,n){let r=at(t.leaf),i=at(t.relativePath),o=at(t.documentation??"");for(let a of n)r.has(a)&&Ao(e,t,a,"symbol"),i.has(a)&&Ao(e,t,a,"path"),o.has(a)&&Ao(e,t,a,"documentation");let s=e.get(t.symbol);s&&(s.symbolPhraseLength=u0(t.leaf,n))}function Ao(e,t,n,r,i,o){let s=e.get(t.symbol)??{definition:t,matches:new Map,symbolPhraseLength:0},a=s.matches.get(n)??{sources:new Set,locations:new Map};a.sources.add(r),i!==void 0&&o!==void 0&&a.locations.set(`${i}\0${o}`,{file:i,line:o}),s.matches.set(n,a),e.set(t.symbol,s)}function CS(e){let t=new Map;for(let n of e.values())for(let r of n.matches.keys())t.set(r,(t.get(r)??0)+1);return t}function EF(e,t,n,r){let i=t[0]?.documentId;if(i===void 0||t.find(a=>a.isFunctionLike&&a.leaf===n.name&&a.startLine===n.startLine&&a.endLine===n.endLine))return null;let s=r();return{documentId:i,symbolId:s,symbol:`${bd}${e}:${n.startLine}:${n.endLine}:${n.name}`,relativePath:e,startLine:n.startLine,startChar:0,endLine:n.endLine,endChar:0,leaf:n.name,parentTypeName:null,isFunctionLike:!0,isTypeLike:!1,kind:null,documentation:null,enclosingSymbol:null}}function IF(e,t,n){let r=new Set(t.slice(0,SF).map(s=>s.file)),i=new Set(n),o=e.map(s=>{let a=at(s.relativePath),c=s.relativePath.slice(s.relativePath.lastIndexOf("/")+1).replace(/\.[^.]+$/u,""),l=at(c),u=[...a].filter(m=>i.has(m)).length,d=[...l].filter(m=>i.has(m)).length;return{file:s,score:d*4+u}}).filter(s=>s.score>0).sort((s,a)=>a.score-s.score||xe(q(s.file.relativePath))-xe(q(a.file.relativePath))||s.file.relativePath.localeCompare(a.file.relativePath)).slice(0,vF);for(let s of o)r.add(s.file.relativePath);return e.filter(s=>r.has(s.relativePath))}function wF(e){let t=new Map;for(let n of e){if(!Zt(n))continue;let r=`${n.relativePath}\0${qe(n.leaf)}`,i=t.get(r)??[];i.push(n),t.set(r,i)}return t}function xS(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,r)=>n.endLine-n.startLine-(r.endLine-r.startLine)||Number(Zt(r))-Number(Zt(n))||n.startLine-r.startLine||n.symbol.localeCompare(r.symbol))[0]}function Zt(e){return e.symbol.startsWith(bd)}function rr(e){return Zt(e)?e.leaf:T(e.symbol)}function Xa(e,t,n=[]){let r=e.definition,i=[...e.matches.entries()].map(([l,u])=>({term:l,sources:[...u.sources].sort(d0),locations:[...u.locations.values()].sort(OS).slice(0,3)})).sort((l,u)=>l.term.localeCompare(u.term)),o=i.filter(l=>l.sources.some(u=>u!=="source")).map(l=>l.term),s=i.filter(l=>l.sources.includes("symbol")).map(l=>l.term),a=i.reduce((l,u)=>l+1/Math.max(1,t.get(u.term)??1),0),c=i.filter(l=>l.sources.includes("symbol")).reduce((l,u)=>l+1/Math.max(1,t.get(u.term)??1),0);return{symbol:r.symbol,label:rr(r),leaf:r.leaf,file:r.relativePath,line:r.startLine,endLine:r.endLine,kind:r.isFunctionLike?"callable":r.isTypeLike?"type":"symbol",fileKind:q(r.relativePath),matches:i,focusLocations:f0(e,t),matchedTerms:i.map(l=>l.term),symbolMatchedTerms:s,symbolPhraseLength:e.symbolPhraseLength,identityMatchedTerms:o,rarity:a,symbolRarity:c,queryPathMatches:l0(r.relativePath,n),...e.sourceCharacters===void 0?{}:{sourceCharacters:e.sourceCharacters}}}function LF(e,t,n,r,i,o,s,a){let c=r.filter(g=>!Zt(g)),l=t.calleeMap(c,{additive:!1,semantic:a}),u=new Map,d=new Map;for(let g of n){let h=i.get(g.symbol),b=h?Zt(h)?RS(e,h,i,o,1):Qa(e,h,l.get(h.symbolId)??[],i,1,s):[];u.set(g.symbol,b);for(let S of b){let y=i.get(S.toSymbol);y?.isFunctionLike&&(!h||!Zt(h)||Zt(y))&&d.set(y.symbol,y)}}let m=[...d.values()],p=t.calleeMap(m.filter(g=>!Zt(g)),{additive:!1,semantic:a}),f=new Map;for(let g of m)f.set(g.symbol,Zt(g)?RS(e,g,i,o,2):Qa(e,g,p.get(g.symbolId)??[],i,2,s));return n.map(g=>{let h=u.get(g.symbol)??[],b=h.flatMap(y=>f.get(y.toSymbol)??[]),S=wn([...h,...b]);return{root:g,relations:S,nodeSymbols:new Set([g.symbol,...S.flatMap(y=>[y.fromSymbol,y.toSymbol])])}})}function Qa(e,t,n,r,i,o=new Set){let s=new Map;for(let a of n){let c=r.get(a.symbol);if(!c?.isFunctionLike||c.symbol===t.symbol||a.source==="ast-callsite"&&!DF(e,t,c,a.callsiteLine))continue;let l=s.get(c.symbol);(!l||a0(a,l)<0)&&s.set(c.symbol,a)}return[...s.entries()].map(([a,c])=>{let l=r.get(a);return{kind:"call",fromSymbol:t.symbol,fromLabel:T(t.symbol),fromFile:t.relativePath,toSymbol:l.symbol,toLabel:T(l.symbol),toFile:l.relativePath,depth:i,strength:yd(c.source),evidence:c.source,callsiteLine:c.callsiteLine??PF(e,t,l)}}).sort((a,c)=>Number(o.has(c.toSymbol))-Number(o.has(a.toSymbol))||en(a,c)).slice(0,dF)}function RS(e,t,n,r,i){let o=En(e,t.relativePath,t.startLine,t.endLine).targets.flatMap(s=>{let a=n.get(s.definition.symbol)??s.definition;return!a.isFunctionLike||a.symbol===t.symbol?[]:[{kind:"call",fromSymbol:t.symbol,fromLabel:rr(t),fromFile:t.relativePath,toSymbol:a.symbol,toLabel:rr(a),toFile:a.relativePath,depth:i,strength:"exact",evidence:"scip-occurrence-callsite",callsiteLine:s.sourceLine}]});for(let s of nr(e,t.relativePath,{ranges:[{startLine:t.startLine,endLine:t.endLine}],excludeIndexedTargets:!1}).targets){let a=[...r.get(`${s.targetFile}\0${qe(s.calleeLeaf)}`)??[],...U(e,s.targetFile).filter(c=>c.isFunctionLike&&qe(c.leaf)===s.calleeLeaf)].find(c=>c.startLine===s.targetStartLine&&c.endLine===s.targetEndLine);!a||a.symbol===t.symbol||o.push({kind:"call",fromSymbol:t.symbol,fromLabel:rr(t),fromFile:t.relativePath,toSymbol:a.symbol,toLabel:rr(a),toFile:a.relativePath,depth:i,strength:s.strength==="exact"?"exact":"derived",evidence:"ast-member-import-candidate",callsiteLine:s.line})}for(let s of K(e,t.relativePath)?.callSites??[]){if(s.line<t.startLine||s.line>t.endLine||s.memberAccess)continue;let a=(r.get(`${t.relativePath}\0${qe(s.calleeLeaf)}`)??[]).filter(l=>l.symbol!==t.symbol);if(a.length!==1)continue;let c=a[0];o.push({kind:"call",fromSymbol:t.symbol,fromLabel:rr(t),fromFile:t.relativePath,toSymbol:c.symbol,toLabel:rr(c),toFile:c.relativePath,depth:i,strength:"derived",evidence:"ast-callsite",callsiteLine:s.line})}return wn(o).sort(en)}function PF(e,t,n){let r=qe(n.leaf);return K(e,t.relativePath)?.callSites.find(i=>i.line>=t.startLine&&i.line<=t.endLine&&qe(i.calleeLeaf)===r)?.line??null}function DF(e,t,n,r){if(r===void 0)return!1;let i=qe(n.leaf);return K(e,t.relativePath)?.callSites.some(o=>{if(o.line!==r)return!1;if(qe(o.calleeLeaf)===i)return!0;let s=ri(e,t.relativePath,o.calleeLeaf);return s!==null&&qe(s.importedName)===i&&Fe(s.sourcePath,n.relativePath)})??!1}function MF(e,t,n,r,i){let o=new Map(t.map((u,d)=>[u.symbol,d])),s=t.map((u,d)=>d),a=u=>{let d=u;for(;s[d]!==d;)d=s[d];for(;s[u]!==u;){let m=s[u];s[u]=d,u=m}return d},c=(u,d)=>{let m=a(u),p=a(d);m!==p&&(s[p]=m)};for(let u of e){let d=o.get(u.root.symbol);if(d!==void 0)for(let m of u.nodeSymbols){let p=o.get(m);p!==void 0&&c(d,p)}}let l=new Map;for(let u=0;u<t.length;u+=1){let d=a(u),m=l.get(d)??[];m.push(t[u]),l.set(d,m)}return[...l.values()].map((u,d)=>{let m=new Set(u.map(y=>y.symbol)),p=wn(e.filter(y=>m.has(y.root.symbol)).flatMap(y=>y.relations)).sort(en),f=new Map(u.map(y=>[y.symbol,y]));for(let y of new Set(p.flatMap(x=>[x.fromSymbol,x.toSymbol]))){let x=n.get(y);if(x)f.has(y)||f.set(y,Xa(x,r));else{let v=i.get(y);v&&f.set(y,NS(v))}}let g=QF(u,p,f),h=u.filter(y=>p.some(x=>x.fromSymbol===y.symbol)).length,b=[...new Set(u.flatMap(y=>y.matchedTerms))].sort(),S=XF(p,g,m,f);return{id:`anchor-set:${d+1}:${No(u[0])}`,kind:"connected-flow",roots:[...u].sort(Ge),keyAnchors:g,candidateOwnerCount:g.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:[],matchedTerms:b,relations:S,relationCount:p.length,orchestrationRootCount:h,omittedRelations:Math.max(0,p.length-Or),systemMapCommand:Oo(g,p,b)}})}function TF(e,t,n){let r=new Map(n.map((o,s)=>[o,s])),i=[];for(let o=0;o<e.length;o+=1){let s=e[o],a=ES(s);if(a.size!==0)for(let c=o+1;c<e.length;c+=1){let l=e[c],u=ES(l),d=[...a].filter(v=>u.has(v));if(d.length===0||![...a].some(v=>!u.has(v))||![...u].some(v=>!a.has(v)))continue;let m=kF(s,l);if(m.length<2)continue;let p=wn([...s.relations,...l.relations]).sort(en),f=p.slice(0,Or),g=Pi([...s.roots,...l.roots]).sort(Ge),h=[...new Set([...s.matchedTerms,...l.matchedTerms])].sort(),b=d.sort((v,C)=>(r.get(v)??Number.MAX_SAFE_INTEGER)-(r.get(C)??Number.MAX_SAFE_INTEGER)||v.localeCompare(C)),S=+(s.relationCount>0)+ +(l.relationCount>0),y=+((s.orchestrationRootCount??0)>0)+ +((l.orchestrationRootCount??0)>0),x=Math.min(...b.map(v=>t.get(v)??Number.MAX_SAFE_INTEGER));i.push({sharedOrder:Math.min(...b.map(v=>r.get(v)??Number.MAX_SAFE_INTEGER)),sharedFrequency:x,connectedSides:S,orchestrationSides:y,group:{id:`parallel-paths:${No(s.roots[0])}:${No(l.roots[0])}`,kind:"parallel-paths",roots:g,keyAnchors:m,candidateOwnerCount:m.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:[...s.upstreamEntries,...l.upstreamEntries],matchedTerms:h,relations:f,relationCount:p.length,parallelConnectedSides:S,parallelOrchestrationSides:y,parallelSharedPathTerms:b,parallelSharedPathFrequency:x,orchestrationRootCount:(s.orchestrationRootCount??0)+(l.orchestrationRootCount??0),omittedRelations:Math.max(0,p.length-f.length),systemMapCommand:Oo(m,p,h)}})}}return i.sort((o,s)=>o.sharedFrequency-s.sharedFrequency||s.orchestrationSides-o.orchestrationSides||s.connectedSides-o.connectedSides||o.sharedOrder-s.sharedOrder||s.group.matchedTerms.length-o.group.matchedTerms.length||_r(o.group,s.group,t)).slice(0,bF).map(o=>o.group)}function ES(e){return new Set(e.roots.flatMap(t=>t.matches.filter(n=>n.sources.includes("path")).map(n=>n.term)))}function kF(e,t){return Pi([IS(e),IS(t)].filter(n=>n!==void 0))}function IS(e){let t=new Set(e.keyAnchors.map(r=>r.symbol)),n=new Map;for(let r of e.relations)!t.has(r.fromSymbol)||!t.has(r.toSymbol)||n.set(r.fromSymbol,(n.get(r.fromSymbol)??0)+1);return[...e.keyAnchors].sort((r,i)=>+((n.get(i.symbol)??0)>0)-+((n.get(r.symbol)??0)>0)||wS(i)-wS(r)||i.identityMatchedTerms.length-r.identityMatchedTerms.length||i.symbolMatchedTerms.length-r.symbolMatchedTerms.length||(n.get(i.symbol)??0)-(n.get(r.symbol)??0)||Ge(r,i))[0]}function wS(e){return e.matchedTerms.length+e.identityMatchedTerms.length*2+(e.queryPathMatches?.length??0)*4}function AF(e,t,n,r,i,o){let s=Js(e);if(!s||s.links.length===0||n.length<2)return[];let a=new Map(s.observations.map(p=>[p.id,p])),c=new Map,l=new Map,u=[...n].sort((p,f)=>_r(p,f,i)).slice(0,fF),d=s.links.filter(p=>p.strength!=="candidate").sort((p,f)=>ir(f.strength)-ir(p.strength)||f.matchedKeyParts.length-p.matchedKeyParts.length||p.id.localeCompare(f.id));for(let p of u)for(let f of d){let g=a.get(f.from),h=a.get(f.to);if(!g||!h||!FF(p,g,r))continue;let b=NF(p,g,r);if(!b)continue;let S=c.get(h.id)??BF(e,t,h,r,o,hF);if(c.set(h.id,S),S.reachedSymbols.size===0)continue;let y=n.filter(L=>L.id!==p.id&&_F(L).some(A=>S.reachedSymbols.has(A))&&fd(b,L)>=2).sort((L,A)=>fd(b,A)-fd(b,L)||_r(L,A,i)).slice(0,gF);if(y.length===0)continue;let x=[p.id,g.id,...y.map(L=>L.id).sort()].join("\0");if(l.has(x))continue;let v=new Set(y.flatMap(_o)),C=qF(Fo(h),v,S.relations);if(C.length===0)continue;let R=UF(g,h,f.joinRule,f.matchedKeyParts,f.strength),E=wn([R,...S.relations,...p.relations,...y.flatMap(L=>L.relations)]),w=GF([R,...C],E,p,y),I=Pi([b,...y.flatMap(L=>L.roots)]).sort(Ge),k=Pi([b,...y.flatMap(L=>L.keyAnchors)]).slice(0,yF),D=[...new Set([...b.matchedTerms,...y.flatMap(L=>L.matchedTerms)])].sort(),F=OF(e,t,b,r,o);I.length===0||k.length<2||l.set(x,{id:`cross-boundary-set:${No(b)}:${l.size+1}`,kind:"cross-boundary-flow",roots:I,keyAnchors:k,candidateOwnerCount:k.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:F,matchedTerms:D,relations:w,relationCount:E.length,omittedRelations:Math.max(0,E.length-w.length),systemMapCommand:Oo(k,E,D)})}let m=new Map;for(let[p,f]of l){let g=p.slice(0,p.indexOf("\0")),h=m.get(g);(!h||_r(f,h,i)<0)&&m.set(g,f)}return[...m.values()]}function FF(e,t,n){let r=new Set(_o(e));return t.owner.symbol&&r.has(t.owner.symbol)?!0:[...r].map(i=>n.get(i)).some(i=>i?.relativePath===t.source.file&&i.startLine<=t.source.startLine&&i.endLine>=t.source.endLine)}function NF(e,t,n){let r=Pi([...e.roots,...e.keyAnchors]);if(t.owner.symbol){let i=r.find(o=>o.symbol===t.owner.symbol);if(i)return i}return r.find(i=>{let o=n.get(i.symbol);return o?.relativePath===t.source.file&&o.startLine<=t.source.startLine&&o.endLine>=t.source.endLine})??null}function _o(e){return[...new Set([...e.roots.map(t=>t.symbol),...e.keyAnchors.map(t=>t.symbol),...e.relations.flatMap(t=>[t.fromSymbol,t.toSymbol])])]}function _F(e){return[...new Set([...e.roots,...e.keyAnchors].map(t=>t.symbol))]}function fd(e,t){let n=at(e.leaf),r=[...t.roots,...t.keyAnchors].map(o=>at(o.leaf)),i=0;for(let o of r){let s=0;for(let a of n)o.has(a)&&(s+=1);i=Math.max(i,s)}return i}function OF(e,t,n,r,i){let o=r.get(n.symbol);if(!o?.isFunctionLike)return[];let s=t.callerFileMap([o],{semantic:i,sourceFallback:!0}).get(o.symbolId);if(!s)return[];let a=at(n.leaf);return[...s].filter(c=>c!==n.file&&q(c)!=="test").flatMap(c=>{let l=K(e,c);return(l?.callSites??[]).filter(u=>qe(u.calleeLeaf)===qe(n.leaf)).flatMap(u=>{let d=(l?.callables??[]).filter(p=>p.startLine<=u.line&&p.endLine>=u.line).sort((p,f)=>p.endLine-p.startLine-(f.endLine-f.startLine)||p.startLine-f.startLine)[0];if(!d)return[];let m=[...at(d.name)].filter(p=>a.has(p)).length;return m>=2?[{name:d.name,file:c,line:d.startLine,endLine:d.endLine,callsiteLine:u.line,overlap:m}]:[]})}).sort((c,l)=>l.overlap-c.overlap||c.file.localeCompare(l.file)||c.line-l.line).slice(0,1).map(({name:c,file:l,line:u,endLine:d,callsiteLine:m})=>({name:c,file:l,line:u,endLine:d,callsiteLine:m}))}function BF(e,t,n,r,i,o){let s=$F(e,n,r),a=s.map(({definition:m,evidence:p,line:f})=>({kind:"call",fromSymbol:Fo(n),fromLabel:Za(n),fromFile:n.source.file,toSymbol:m.symbol,toLabel:T(m.symbol),toFile:m.relativePath,depth:1,strength:p==="scip-occurrence-callsite"?"exact":"derived",evidence:p,callsiteLine:f})),c=jF(e,n);a.push(...c.relations);let l=FS([...s.map(m=>m.definition),...c.definitions]),u=l,d=new Set(u.map(m=>m.symbol));for(let m=2;m<=o+1&&u.length>0;m+=1){let p=t.calleeMap(u,{additive:!1,semantic:i}),f=new Map;for(let g of u){let h=Qa(e,g,p.get(g.symbolId)??[],r,m);a.push(...h);for(let b of h){let S=r.get(b.toSymbol);S?.isFunctionLike&&!d.has(S.symbol)&&f.set(S.symbol,S)}}u=[...f.values()];for(let g of u)d.add(g.symbol)}return{entryDefinitions:l,relations:wn(a),reachedSymbols:new Set([...l.map(m=>m.symbol),...a.flatMap(m=>[m.fromSymbol,m.toSymbol])])}}function $F(e,t,n){let r=t.owner.symbol?n.get(t.owner.symbol):void 0;if(r?.isFunctionLike&&!me(r.symbol))return[{definition:r,evidence:"scip-occurrence-callsite",line:t.source.startLine}];let i=V(e,t.source.file),o=ot(e,t.source.file,0,Math.max(0,i.length-1),[t.source.startLine]),s=En(e,t.source.file,o.startLine,o.endLine).targets.map(u=>({definition:u.definition,evidence:"scip-occurrence-callsite",line:u.sourceLine})),a=K(e,t.source.file),c=zt(e),l=(a?.callSites??[]).flatMap(u=>{if(u.line<o.startLine||u.line>o.endLine)return[];let d=_t(t.source.file,c.get(u.calleeLeaf)??[]),m=$n(e,t.source.file,d,u.memberAccess,u.calleeQualifier),p=m?n.get(m.symbol):void 0;return p?.isFunctionLike?[{definition:p,evidence:"ast-callsite",line:u.line}]:[]});return HF([...s,...l])}function jF(e,t){let n=V(e,t.source.file),r=ot(e,t.source.file,0,Math.max(0,n.length-1),[t.source.startLine]),i=nr(e,t.source.file,{ranges:[r],excludeIndexedTargets:!1}).targets,o=[],s=[];for(let a of i){let c=`source-construct:${a.targetFile}:${a.targetStartLine}:${a.targetEndLine}:${a.calleeLeaf}`;s.push({kind:"call",fromSymbol:Fo(t),fromLabel:Za(t),fromFile:t.source.file,toSymbol:c,toLabel:a.calleeLeaf,toFile:a.targetFile,depth:1,strength:"derived",evidence:"ast-member-import-candidate",callsiteLine:a.line});let l=En(e,a.targetFile,a.targetStartLine,a.targetEndLine).targets;for(let u of l)o.push(u.definition),s.push({kind:"call",fromSymbol:c,fromLabel:a.calleeLeaf,fromFile:a.targetFile,toSymbol:u.definition.symbol,toLabel:T(u.definition.symbol),toFile:u.definition.relativePath,depth:2,strength:"exact",evidence:"scip-occurrence-callsite",callsiteLine:u.sourceLine})}return{definitions:FS(o),relations:wn(s)}}function HF(e){return[...new Map(e.map(t=>[t.definition.symbol,t])).values()]}function FS(e){return[...new Map(e.map(t=>[t.symbol,t])).values()]}function Fo(e){return e.owner.symbol??e.id}function Za(e){return e.owner.name??`${e.source.file}:${e.source.startLine+1}`}function UF(e,t,n,r,i){return{kind:"runtime-boundary",fromSymbol:Fo(e),fromLabel:Za(e),fromFile:e.source.file,toSymbol:Fo(t),toLabel:Za(t),toFile:t.source.file,depth:1,strength:i,evidence:`runtime-boundary:${n}`,callsiteLine:e.source.startLine,runtimeBoundaryKey:r.map(o=>`${o.name}=${o.value}`).join(" ")}}function qF(e,t,n){let r=new Map;for(let s of n){let a=r.get(s.fromSymbol)??[];a.push(s),r.set(s.fromSymbol,a)}let i=[{symbol:e,path:[]}],o=new Set([e]);for(;i.length>0;){let s=i.shift();if(s.path.length>0&&t.has(s.symbol))return s.path;for(let a of(r.get(s.symbol)??[]).sort(en))o.has(a.toSymbol)||(o.add(a.toSymbol),i.push({symbol:a.toSymbol,path:[...s.path,a]}))}return[]}function GF(e,t,n,r){let i=wn(e),o=new Set([n,...r].flatMap(s=>[..._o(s),...s.keyAnchors.map(a=>a.symbol)]));for(let s of t){if(i.length>=Or)break;!o.has(s.fromSymbol)&&!o.has(s.toSymbol)||i.some(a=>a.fromSymbol===s.fromSymbol&&a.toSymbol===s.toSymbol)||i.push(s)}return i.slice(0,Or)}function zF(e,t,n,r,i,o,s,a){let c=n.filter(u=>!u.root.symbol.startsWith(bd)).map(u=>({root:u.root,relations:u.relations.filter(d=>d.depth===1&&d.fromSymbol===u.root.symbol)}));return KF(c).flatMap((u,d)=>{let m=new Set(u.map(P=>P.root.symbol)),p=new Map;for(let P of u)for(let j of new Set(P.relations.map(B=>B.toSymbol)))p.set(j,(p.get(j)??0)+1);let f=[...p].filter(([,P])=>P>=2).sort(([P,j],[B,X])=>X-j||WF(P,B,r,i,s)).map(([P])=>s.get(P)).filter(P=>P?.isFunctionLike===!0).slice(0,mF);if(f.length===0)return[];let g=t.callerFileMap(f,{semantic:a,sourceFallback:!0}),h=new Set;for(let P of f){h.add(P.relativePath);for(let j of g.get(P.symbolId)??[])h.add(j)}let b=o.filter(P=>P.isFunctionLike&&h.has(P.relativePath)).sort(VF).slice(0,pF),S=t.calleeMap(b,{additive:!1,semantic:a}),y=new Set(f.map(P=>P.symbol)),x=wn(b.flatMap(P=>Qa(e,P,S.get(P.symbolId)??[],s,1,y).filter(j=>y.has(j.toSymbol)))),v=new Map;for(let P of x){let j=v.get(P.fromSymbol)??new Set;j.add(P.toSymbol),v.set(P.fromSymbol,j)}let C=new Set([...v].filter(([P,j])=>j.size>=2||m.has(P)).map(([P])=>P)),R=x.filter(P=>C.has(P.fromSymbol));if(C.size<2||R.length===0)return[];let w=[...new Set(R.map(P=>P.toSymbol))].map(P=>ec(P,r,i,s)).filter(P=>P!==null).sort(Ge),I=[...C].map(P=>ec(P,r,i,s)).filter(P=>P!==null),k=YF(I,R),D=k.slice(0,pd),F=k.slice(pd);if(w.length===0||D.length===0)return[];let L=[...new Set([...w.flatMap(P=>P.matchedTerms),...u.flatMap(P=>P.root.matchedTerms)])].sort(),A=JF(R,D);return[{id:`effect-owner-set:${d+1}:${No(w[0])}`,kind:"shared-callee-owners",roots:w,keyAnchors:D,candidateOwnerCount:k.length,omittedCandidateOwners:F,ownerRecoveryCommands:g0(F,pd),upstreamEntries:[],matchedTerms:L,relations:A,relationCount:R.length,omittedRelations:Math.max(0,R.length-A.length),systemMapCommand:Oo(D,R,L)}]})}function KF(e){let t=e.map((s,a)=>a),n=s=>{for(;t[s]!==s;)t[s]=t[t[s]],s=t[s];return s},r=(s,a)=>{let c=n(s),l=n(a);c!==l&&(t[l]=c)},i=e.map(s=>new Set(s.relations.map(a=>a.toSymbol)));for(let s=0;s<e.length;s+=1)for(let a=s+1;a<e.length;a+=1){let c=0;for(let l of i[s]??[])if((i[a]??new Set).has(l)&&(c+=1),c>=2)break;c>=2&&r(s,a)}let o=new Map;for(let s=0;s<e.length;s+=1){let a=n(s),c=o.get(a)??[];c.push(e[s]),o.set(a,c)}return[...o.values()].filter(s=>s.length>=2)}function WF(e,t,n,r,i){let o=ec(e,n,r,i),s=ec(t,n,r,i);return o?s?Ge(o,s):-1:s?1:e.localeCompare(t)}function VF(e,t){return xe(q(e.relativePath))-xe(q(t.relativePath))||e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine}function ec(e,t,n,r){let i=t.get(e);if(i)return Xa(i,n);let o=r.get(e);return o?NS(o):null}function YF(e,t){let n=new Map;for(let i of t){let o=n.get(i.toSymbol)??new Set;o.add(i.fromSymbol),n.set(i.toSymbol,o)}let r=new Map;for(let i of t){let o=n.get(i.toSymbol)?.size??1;r.set(i.fromSymbol,(r.get(i.fromSymbol)??0)+o*o)}return[...e].sort((i,o)=>Number(i.leaf.startsWith("#"))-Number(o.leaf.startsWith("#"))||o.identityMatchedTerms.length-i.identityMatchedTerms.length||(r.get(o.symbol)??0)-(r.get(i.symbol)??0)||Ge(i,o))}function JF(e,t){let n=new Map(t.map((s,a)=>[s.symbol,a])),r=t.map(s=>e.filter(a=>a.fromSymbol===s.symbol).sort(en)),i=[],o=0;for(;i.length<Or&&r.some(s=>o<s.length);){for(let s of r){let a=s[o];if(a&&i.push(a),i.length>=Or)break}o+=1}return i.sort((s,a)=>n.get(s.fromSymbol)-n.get(a.fromSymbol)||en(s,a))}function XF(e,t,n,r){let i=new Map(t.map((a,c)=>[a.symbol,c])),o=new Map;for(let a of e)o.set(a.fromSymbol,(o.get(a.fromSymbol)??0)+1);return[...e].sort((a,c)=>{let l=u=>{let d=0;return i.has(u.fromSymbol)&&(d+=100),n.has(u.toSymbol)&&(d+=60),d+=Math.min(40,(o.get(u.toSymbol)??0)*8),(r.get(u.toSymbol)?.matchedTerms.length??0)>0&&(d+=25),u.fromFile!==u.toFile&&(d+=15),u.strength==="exact"&&(d+=5),d};return l(c)-l(a)||en(a,c)}).slice(0,Or).sort((a,c)=>(i.get(a.fromSymbol)??Nr)-(i.get(c.fromSymbol)??Nr)||a.depth-c.depth||(a.callsiteLine??Number.MAX_SAFE_INTEGER)-(c.callsiteLine??Number.MAX_SAFE_INTEGER)||en(a,c))}function NS(e){return{symbol:e.symbol,label:rr(e),leaf:e.leaf,file:e.relativePath,line:e.startLine,endLine:e.endLine,kind:e.isFunctionLike?"callable":e.isTypeLike?"type":"symbol",fileKind:q(e.relativePath),matches:[],focusLocations:[],matchedTerms:[],symbolMatchedTerms:[],symbolPhraseLength:0,identityMatchedTerms:[],rarity:0,symbolRarity:0}}function QF(e,t,n){let r=[...e].sort(Ge),i=[],o=new Map;for(let u of t)o.set(u.fromSymbol,(o.get(u.fromSymbol)??0)+1);let s=new Set,a=new Set,c=u=>{if(!(!u||i.some(d=>d.symbol===u.symbol))){i.push(u);for(let d of u.matchedTerms)s.add(d);for(let d of u.symbolMatchedTerms)a.add(d)}},l=r.filter(u=>u.symbolPhraseLength>=2&&(o.get(u.symbol)??0)>=2);for(;i.length<Math.min(2,Nr);){let u=l.filter(d=>!i.some(m=>m.symbol===d.symbol)).sort((d,m)=>m.symbolMatchedTerms.filter(p=>!a.has(p)).length-d.symbolMatchedTerms.filter(p=>!a.has(p)).length||m.symbolPhraseLength-d.symbolPhraseLength||(o.get(m.symbol)??0)-(o.get(d.symbol)??0)||gd(d,m))[0];if(!u||i.length>0&&u.symbolMatchedTerms.every(d=>a.has(d)))break;c(u)}if(c(r[0]),i.length>=2){let u=ZF(i[0].symbol,i[1].symbol,t,n);for(let d of u?.slice(1,-1)??[]){if(i.length>=Nr)break;c(n.get(d))}if(i.length<Nr){let d=new Set(i.map(f=>f.symbol)),m=new Set(t.filter(f=>f.depth===1&&d.has(f.fromSymbol)&&d.has(f.toSymbol)).map(f=>f.fromSymbol)),p=t.filter(f=>f.depth===1&&m.has(f.fromSymbol)&&!d.has(f.toSymbol)).map(f=>({relation:f,candidate:n.get(f.toSymbol)})).filter(f=>f.candidate!==void 0&&f.candidate.symbolPhraseLength>=2&&f.candidate.symbolMatchedTerms.length>=2).sort((f,g)=>(o.get(f.relation.fromSymbol)??0)-(o.get(g.relation.fromSymbol)??0)||gd(f.candidate,g.candidate))[0]?.candidate;c(p)}}else for(;i.length<Math.min(3,Nr);){let u=r.filter(d=>!i.some(m=>m.symbol===d.symbol)).sort((d,m)=>m.matchedTerms.filter(p=>!s.has(p)).length-d.matchedTerms.filter(p=>!s.has(p)).length||Ge(d,m))[0];if(!u||u.matchedTerms.every(d=>s.has(d)))break;c(u)}for(;i.length>=2&&i.length<Nr;){let u=new Set(i.map(m=>m.symbol)),d=[...n.values()].filter(m=>!u.has(m.symbol)&&(o.get(m.symbol)??0)>0&&t.some(p=>u.has(p.fromSymbol)&&p.toSymbol===m.symbol)).sort((m,p)=>p.identityMatchedTerms.length-m.identityMatchedTerms.length||p.symbolMatchedTerms.length-m.symbolMatchedTerms.length||p.matchedTerms.length-m.matchedTerms.length||(o.get(p.symbol)??0)-(o.get(m.symbol)??0)||Ge(m,p))[0];if(!d)break;c(d)}if(i.length<2){let u=i[0],d=u?r.filter(m=>m.symbol!==u.symbol).map(m=>({root:m,path:e0(m.symbol,u.symbol,t)})).filter(m=>m.path!==null).sort((m,p)=>+(p.root.file!==u.file)-+(m.root.file!==u.file)||m.path.length-p.path.length||Ge(m.root,p.root))[0]?.root:void 0;c(d)}return i}function ZF(e,t,n,r){let i=new Map;for(let a of n){let c=i.get(a.fromSymbol)??new Set;c.add(a.toSymbol),i.set(a.fromSymbol,c);let l=i.get(a.toSymbol)??new Set;l.add(a.fromSymbol),i.set(a.toSymbol,l)}let o=[{path:[e],cost:0}],s=new Map([[e,0]]);for(;o.length>0;){o.sort((u,d)=>u.cost-d.cost||u.path.length-d.path.length);let{path:a,cost:c}=o.shift(),l=a.at(-1);if(l===t)return a;for(let u of i.get(l)??[]){let d=r.get(u),m=u===t?1:!d||d.matchedTerms.length===0?9:d.symbolPhraseLength>=2?1:d.identityMatchedTerms.length>=2?2:4,p=c+m;p>=(s.get(u)??Number.POSITIVE_INFINITY)||(s.set(u,p),o.push({path:[...a,u],cost:p}))}}return null}function e0(e,t,n){let r=new Map;for(let s of n){let a=r.get(s.fromSymbol)??[];a.push(s.toSymbol),r.set(s.fromSymbol,a)}let i=[[e]],o=new Set([e]);for(;i.length>0;){let s=i.shift(),a=s.at(-1);if(a===t)return s;for(let c of r.get(a)??[])o.has(c)||(o.add(c),i.push([...s,c]))}return null}function Ge(e,t){return(t.queryPathMatches?.length??0)-(e.queryPathMatches?.length??0)||t.identityMatchedTerms.length-e.identityMatchedTerms.length||t.matchedTerms.length-e.matchedTerms.length||t.rarity-e.rarity||Di(e.kind)-Di(t.kind)||xe(e.fileKind)-xe(t.fileKind)||e.file.localeCompare(t.file)||e.line-t.line}function gd(e,t){return t.symbolPhraseLength-e.symbolPhraseLength||t.symbolMatchedTerms.length-e.symbolMatchedTerms.length||Di(e.kind)-Di(t.kind)||t.symbolRarity-e.symbolRarity||Ge(e,t)}function t0(e,t){return t.flatMap(n=>{let r=e.filter(s=>s.matchedTerms.includes(n)).sort((s,a)=>r0(s,a,n)),i=[],o=new Set;for(let s of r)if(!o.has(s.file)&&(i.push(s),o.add(s.file),i.length>=bS))return i;for(let s of r)if(!i.some(a=>a.symbol===s.symbol)&&(i.push(s),i.length>=bS))break;return i})}function n0(e,t,n){let r=new Set(t),i=new Map;for(let o of e){if(o.kind!=="callable")continue;let s=o.file.slice(o.file.lastIndexOf("/")+1).replace(/\.[^.]+$/u,"");if(![...at(s)].some(c=>r.has(c)))continue;let a=i.get(o.file)??[];a.push(o),i.set(o.file,a)}return[...i.entries()].map(([o,s])=>{let a=o.slice(o.lastIndexOf("/")+1).replace(/\.[^.]+$/u,""),c=[...at(a)].filter(l=>r.has(l));return{file:o,fileCandidates:s,sharedFrequency:Math.min(...c.map(l=>n.get(l)??Number.MAX_SAFE_INTEGER))}}).sort((o,s)=>xe(o.fileCandidates[0].fileKind)-xe(s.fileCandidates[0].fileKind)||o.sharedFrequency-s.sharedFrequency||o.file.localeCompare(s.file)).flatMap(({fileCandidates:o})=>[...o].sort(Ge).slice(0,xF)).slice(0,CF)}function r0(e,t,n){return LS(e,n)-LS(t,n)||xe(e.fileKind)-xe(t.fileKind)||t.symbolPhraseLength-e.symbolPhraseLength||Di(e.kind)-Di(t.kind)||Ge(e,t)}function LS(e,t){let n=e.matches.find(r=>r.term===t)?.sources??[];return Math.min(...n.map(hd),Number.MAX_SAFE_INTEGER)}function Pi(e){return[...new Map(e.map(t=>[t.symbol,t])).values()]}function _r(e,t,n){let r=new Set(e.roots.flatMap(o=>o.symbolMatchedTerms)),i=new Set(t.roots.flatMap(o=>o.symbolMatchedTerms));return(t.queryPathMatches?.length??0)-(e.queryPathMatches?.length??0)||TS(e.kind)-TS(t.kind)||DS(e)-DS(t)||MS(e)-MS(t)||(e.kind==="parallel-paths"&&t.kind==="parallel-paths"?(e.parallelSharedPathFrequency??Number.MAX_SAFE_INTEGER)-(t.parallelSharedPathFrequency??Number.MAX_SAFE_INTEGER)||(t.parallelOrchestrationSides??0)-(e.parallelOrchestrationSides??0)||(t.parallelSharedPathTerms?.length??0)-(e.parallelSharedPathTerms?.length??0):0)||PS(t,n)-PS(e,n)||t.matchedTerms.length-e.matchedTerms.length||Math.max(...t.roots.map(o=>o.symbolPhraseLength))-Math.max(...e.roots.map(o=>o.symbolPhraseLength))||i.size-r.size||Ge(e.roots[0],t.roots[0])||t.roots.length-e.roots.length||e.relationCount-t.relationCount||e.id.localeCompare(t.id)}function PS(e,t){return e.matchedTerms.reduce((n,r)=>n+1/Math.max(1,t.get(r)??1),0)}function i0(e){return[...new Set(e.roots.flatMap(t=>t.queryPathMatches??[]))].sort()}function DS(e){let t=e.keyAnchors.length>0?e.keyAnchors:e.roots;return Math.max(...t.map(n=>xe(n.fileKind)))}function MS(e){return e.kind==="parallel-paths"?2-(e.parallelConnectedSides??0):e.kind!=="connected-flow"||e.relationCount>0?0:1}function o0(e,t,n){let r=e.slice(0,t);if(t<2||r.some(o=>o.kind==="shared-callee-owners"))return r;let i=e.filter(o=>o.kind==="shared-callee-owners");for(let o of r){if(o.kind==="shared-callee-owners"||o.kind==="parallel-paths")continue;let s=new Set(_o(o)),a=i.map(l=>({group:l,overlap:s0(l,s)})).filter(({overlap:l})=>l>0).sort(({group:l,overlap:u},{group:d,overlap:m})=>m-u||_r(l,d,n))[0]?.group;if(!a)continue;let c=r.length-1;for(;c>=0&&r[c]===o;)c-=1;return c<0?r:(r[c]=a,[...r].sort((l,u)=>_r(l,u,n)))}return r}function s0(e,t){return _o(e).filter(n=>t.has(n)).length}function TS(e){switch(e){case"cross-boundary-flow":return 0;case"parallel-paths":case"connected-flow":return 1;case"shared-callee-owners":return 2}}function en(e,t){return e.depth-t.depth||ir(t.strength)-ir(e.strength)||e.fromLabel.localeCompare(t.fromLabel)||e.toLabel.localeCompare(t.toLabel)||(e.callsiteLine??Number.MAX_SAFE_INTEGER)-(t.callsiteLine??Number.MAX_SAFE_INTEGER)}function a0(e,t){return ir(yd(t.source))-ir(yd(e.source))||(e.callsiteLine??Number.MAX_SAFE_INTEGER)-(t.callsiteLine??Number.MAX_SAFE_INTEGER)||e.symbol.localeCompare(t.symbol)}function wn(e){let t=new Map;for(let n of e){let r=`${n.fromSymbol}\0${n.toSymbol}`,i=t.get(r);(!i||en(n,i)<0)&&t.set(r,n)}return[...t.values()]}function nc(e){return e.replace(/([\p{Ll}\d])([\p{Lu}])/gu,"$1 $2").replace(/([\p{Lu}]+)([\p{Lu}][\p{Ll}])/gu,"$1 $2").match(/[\p{L}\d]+/gu)??[]}function c0(e){let t=e.match(/[\p{L}\d_.-]+(?:\/[\p{L}\d_.-]+)+/gu)??[];return[...new Set(t.map(n=>n.replace(/[.;:!?]+$/gu,"").toLocaleLowerCase()))]}function l0(e,t){let n=e.replace(/\\/gu,"/").toLocaleLowerCase();return t.filter(r=>{let i=n.indexOf(r);if(i<0)return!1;let o=i===0?"/":n[i-1],s=n[i+r.length];return o==="/"&&(s===void 0||s==="/")})}function u0(e,t){let n=nc(e).map(Sd),r=0;for(let i=0;i<n.length;i+=1)for(let o=0;o<t.length;o+=1){let s=0;for(;i+s<n.length&&o+s<t.length&&n[i+s]===t[o+s];)s+=1;r=Math.max(r,s)}return r}function at(e){return new Set(nc(e).flatMap(_S).filter(t=>t.length>=3))}function _S(e){let t=Sd(e);return t.length>4&&t.endsWith("e")?[t,t.slice(0,-1)]:[t]}function Sd(e){let t=e.toLocaleLowerCase();return t.length>5&&t.endsWith("ies")?`${t.slice(0,-3)}y`:t.length>4&&t.endsWith("ied")?`${t.slice(0,-3)}y`:t.length>4&&t.endsWith("ed")?kS(t.slice(0,-2)):t.length>5&&t.endsWith("ing")?kS(t.slice(0,-3)):t.length>4&&t.endsWith("ers")||t.length>3&&t.endsWith("s")&&!t.endsWith("ss")?t.slice(0,-1):t}function kS(e){if(e.length<2)return e;let t=e.at(-1),n=e.at(-2);return t===n&&!"aeiou".includes(t)?e.slice(0,-1):e}function d0(e,t){return hd(e)-hd(t)}function hd(e){switch(e){case"symbol":return 0;case"path":return 1;case"documentation":return 2;case"source":return 3}}function Di(e){return e==="callable"?0:e==="type"?1:2}function yd(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function ir(e){return e==="exact"?2:1}function OS(e,t){return e.file.localeCompare(t.file)||e.line-t.line}function No(e){return`${e.file}:${e.line+1}`}function Oo(e,t=[],n=[]){let r=e.map(s=>`--symbol ${tc(`${s.file}:${s.line+1}-${s.endLine+1}`)}`),i=new Set(e.map(s=>s.symbol)),o=e.flatMap(s=>(s.sourceCharacters??0)>md?m0(s,t,n,i).map(a=>`--focus-at ${tc(`${a.file}:${a.line+1}`)}`):[]);return`scip-query system-map ${[...r,...o,"--relation call","--relation runtime-boundary"].join(" ")}`}function m0(e,t,n,r){let i=new Set(n),o=t.filter(l=>l.fromSymbol===e.symbol&&l.callsiteLine!==null&&l.callsiteLine>=e.line&&l.callsiteLine<=e.endLine).map(l=>({file:e.file,line:l.callsiteLine,connectsAnchor:r.has(l.toSymbol),overlap:new Set(nc(p0(l.toLabel)).flatMap(_S).filter(u=>i.has(u))).size,strength:l.strength})).filter(l=>l.overlap>0).sort((l,u)=>Number(u.connectsAnchor)-Number(l.connectsAnchor)||u.overlap-l.overlap||l.line-u.line||ir(u.strength)-ir(l.strength)),s=o.filter(l=>l.connectsAnchor),a=[...s.length>0?s:o,...s.length>0?[]:e.focusLocations.map(l=>({...l,connectsAnchor:!1,overlap:0,strength:"derived"}))],c=[];for(let l of a)if(!c.some(u=>u.file===l.file&&u.line===l.line)&&(c.push({file:l.file,line:l.line}),c.length>=3))break;return c}function p0(e){return e.slice(Math.max(e.lastIndexOf(":"),e.lastIndexOf("."))+1)}function f0(e,t){let n=new Map;for(let[o,s]of e.matches)for(let a of s.locations.values()){if(a.file!==e.definition.relativePath||a.line<e.definition.startLine||a.line>e.definition.endLine)continue;let c=`${a.file}\0${a.line}`,l=n.get(c)??{...a,matchedTerms:new Set};l.matchedTerms.add(o),n.set(c,l)}let r=[...n.values()].sort((o,s)=>s.matchedTerms.size-o.matchedTerms.size||[...s.matchedTerms].reduce((a,c)=>a+1/Math.max(1,t.get(c)??1),0)-[...o.matchedTerms].reduce((a,c)=>a+1/Math.max(1,t.get(c)??1),0)||OS(o,s)),i=[];for(let o of r)if(!i.some(s=>s.file===o.file&&Math.abs(s.line-o.line)<8)&&(i.push(o),i.length>=3))break;return i.map(o=>({file:o.file,line:o.line,matchedTerms:[...o.matchedTerms].sort()}))}function g0(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(Oo(e.slice(r,r+t)));return n}function tc(e){return`'${e.replaceAll("'",`'"'"'`)}'`}import{createHash as ov}from"crypto";function Bo(e,t,n={}){let r=ne(e,t);if(!r)return null;let i=n.semantic!==!1,o=Gn(e,r,{semantic:i,semanticEvidence:re}).filter(l=>Se(l.symbol)).slice(0,50),s=wi(Pt(e,r,{limit:50,additive:!0,callableOnly:!0,semantic:i,semanticEvidence:re})),a=o.map(l=>({symbol:l.symbol,shortName:T(l.symbol),file:l.file,relationship:l.source!=="caller-map-inversion"?"reference-candidate":l.callEvidence==="scip-chunk"?"chunk-candidate":"resolved-call",evidenceStrength:l.source==="caller-map-inversion"&&l.callEvidence!=="scip-chunk"?"exact":"candidate",evidenceSource:l.callEvidence??l.source})),c=s.map(l=>({symbol:l.symbol,shortName:T(l.symbol),file:l.file,relationship:l.source==="scip-chunk"?"chunk-candidate":"resolved-call",evidenceStrength:l.source==="scip-chunk"?"candidate":"exact",evidenceSource:l.source}));return{symbol:r.symbol,shortName:T(r.symbol),callers:a.map(({symbol:l,shortName:u,file:d})=>({symbol:l,shortName:u,file:d})),callees:c.map(({symbol:l,shortName:u,file:d})=>({symbol:l,shortName:u,file:d})),callerEvidence:a,calleeEvidence:c,coverage:{scope:"indexed-static-call-graph",blindSpots:["unresolved dynamic dispatch and reflection","external or unindexed callees without a resolved symbol identity","SCIP chunk co-occurrence is retained only as candidate call evidence"]}}}function $o(e,t){let n=mt(e,t);return n?On(e,"forward",[n]).filter(i=>!e.isIgnored(i)).map(i=>({relativePath:i,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):[]}function jo(e,t){let n=mt(e,t);return n?On(e,"reverse",[n]).filter(i=>!e.isIgnored(i)).map(i=>({relativePath:i,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):[]}function vd(e,t,n={}){let r=rc(e,t,n);return{definitions:r.definitions,referencedBy:r.referencedBy}}function rc(e,t,n={}){let r=ne(e,t);if(!r)return{definitions:[],referencedBy:[],referenceEvidence:[],claimSupport:null};let i=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",r.symbolId),o=si(i?.documentation??null),s=e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,signature:C0(o,i?.display_name??null,r.symbol),source:v0(e,r.relativePath,r.startLine,r.endLine)}],a=n.referenceContext??2,c=Tf(e,r,{semantic:n.semantic,semanticEvidence:re}).map(u=>{let d=Og(e,u.file,u.line,a,z(r.symbol));return{relativePath:u.file,line:u.line,enclosingSymbol:u.enclosingSymbol,enclosingShort:u.enclosingSymbol?T(u.enclosingSymbol):"(top-level)",provenance:u.provenance,sourceStartLine:d?.startLine??null,sourceEndLine:d?.endLine??null,source:d?.source??null,sourceKind:d?.kind??"unavailable"}}),l=c.map(h0);return{definitions:s,referencedBy:l,referenceEvidence:c.map(u=>({relativePath:u.relativePath,line:u.line,provenance:u.provenance,sourceKind:u.sourceKind})),claimSupport:y0(c)}}function h0(e){return{relativePath:e.relativePath,line:e.line,enclosingSymbol:e.enclosingSymbol,enclosingShort:e.enclosingShort,sourceStartLine:e.sourceStartLine,sourceEndLine:e.sourceEndLine,source:e.source}}function y0(e){let t="resolved source-attributed or SCIP-indexed references to this exact symbol",n=["Dynamic dispatch, reflection, generated calls, and unindexed source are outside this scope."],r=e.filter(o=>o.sourceKind!=="complete-call-expression"&&o.sourceKind!=="non-call-reference"),i="direct, statically visible call expressions among the resolved reference sites";return{referenceAbsence:{status:"eligible",scope:t,limitations:n},callsitePredicates:r.length===0?{status:"eligible",scope:i,limitations:n}:{status:"ineligible",scope:i,reason:`${r.length} reference site(s) lack one unambiguous complete call expression.`,followup:b0(r)}}}function b0(e){let t=[...new Set(e.map(n=>`${n.relativePath}:${n.line+1}`))];return t.length===0||t.length>24?null:`scip-query inspect ${t.map(n=>`--at ${S0(n)}`).join(" ")} --view behavior`}function S0(e){return`'${e.replaceAll("'","'\\''")}'`}function v0(e,t,n,r){let i=W(e,t);if(!i)return null;let s=i.split(`
71
- `).slice(n,r+1).join(`
72
- `).trimEnd();return s.length>0?s:null}function C0(e,t,n){let r=oi(e);if(r&&!x0(r))return r;let i=(t??"").trim();return i?Se(n)&&!i.endsWith("()")?`${i}()`:i:T(n)}function x0(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function Cd(e,t,n={}){let r=jS(e,t,n);if(r.kind!=="matched")return r;let{referenceEvidence:i,claimSupport:o,...s}=r;return s}function jS(e,t,n={}){let r=Qe(e,t);if(!r.match)return{kind:"missing",query:t};if(r.total>1)return{kind:"ambiguous",query:t,total:r.total,candidates:[{symbol:r.match.symbol,shortName:T(r.match.symbol),relativePath:r.match.relativePath,startLine:r.match.startLine},...r.candidates]};let i=r.match,o=E0(n.parts),s=o.includes("definition")||o.includes("references")?rc(e,i.symbol,{semantic:n.semantic,referenceContext:n.referenceContext}):{definitions:[],referencedBy:[],referenceEvidence:[],claimSupport:null},a=o.includes("callers")||o.includes("callees")?Bo(e,i.symbol,{semantic:n.semantic}):null,c=n.relatedSourceLines??80;return{kind:"matched",query:t,symbol:i.symbol,shortName:T(i.symbol),file:i.relativePath,parts:o,definition:o.includes("definition")?Hg(e,i.symbol):null,referenceWindows:o.includes("references")?R0(e,s.referencedBy):[],callers:o.includes("callers")?$S(e,a?.callers??[],c):[],callees:o.includes("callees")?$S(e,a?.callees??[],c):[],dependencies:o.includes("dependencies")?$o(e,i.relativePath):[],consumers:o.includes("consumers")?jo(e,i.relativePath):[],referenceEvidence:s.referenceEvidence,claimSupport:s.claimSupport}}function R0(e,t){let n=t.filter(i=>i.sourceStartLine!==null&&i.sourceEndLine!==null&&i.source!==null).sort((i,o)=>i.relativePath.localeCompare(o.relativePath)||i.sourceStartLine-o.sourceStartLine||i.line-o.line),r=[];for(let i of n){let o=r[r.length-1];if(o&&o.relativePath===i.relativePath&&i.sourceStartLine<=o.endLine+1){o.endLine=Math.max(o.endLine,i.sourceEndLine),o.references.push(BS(i)),o.source=V(e,o.relativePath).slice(o.startLine,o.endLine+1).join(`
73
- `);continue}r.push({relativePath:i.relativePath,startLine:i.sourceStartLine,endLine:i.sourceEndLine,source:i.source,references:[BS(i)]})}return r}function BS(e){return{line:e.line,enclosingSymbol:e.enclosingSymbol,enclosingShort:e.enclosingShort}}function E0(e){let t=e&&e.length>0?e:["definition","references"];return[...new Set(t)]}function $S(e,t,n){let r=[],i=new Set;for(let o of t){if(i.has(o.symbol))continue;i.add(o.symbol);let s=(o.file?U(e,o.file).find(c=>c.symbol===o.symbol):void 0)??Qe(e,o.symbol).match;if(!s)continue;let a=Bg(e,s.relativePath,s.startLine,s.endLine,n);a&&r.push({...a,symbol:o.symbol,shortName:o.shortName,omittedLines:Math.max(0,s.endLine-a.endLine)})}return r}var zS=6;function HS(e,t,n){return`${e}\0${t}\0${n??t}`}function KS(e,t,n,r={}){let i=r.limit??zS;if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`next-anchor limit must be a positive safe integer; received ${i}`);let o=r.sourceAllowed??(()=>!0),s=new Map(t.nodes.map(E=>[E.id,E])),a=new Set(n.steps.map(E=>E.nodeId)),c=new Set(n.steps.flatMap(E=>{let w=Rd(s.get(E.nodeId));return w?[w]:[]})),l=new Set;for(let E of n.steps)for(let w of E.behavior?.supportingDeclarations??[])c.add(w.symbol),l.add(HS(w.file,w.line,w.endLine));let u=E=>E.symbol!==null&&c.has(E.symbol)||l.has(HS(E.file,E.line,E.endLine)),d=new Map(n.steps.flatMap(E=>{if(!E.location)return[];let w=Rd(s.get(E.nodeId));if(!w)return[];let I=U(e,E.location.file).find(k=>k.symbol===w);return I?[[E.id,I]]:[]})),m=new H(e).calleeMap([...d.values()],{additive:!1,semantic:!0}),p=[],f=new Set,g=new Set,h=0,b=0,S=0,y=0,x=0,v=0,C=0,R=0;for(let E of n.steps){if(!E.location||!E.behavior)continue;let w=I0(E,{db:e,topology:t,nodeById:s,returnedNodeIds:a,sourceAllowed:o,alternativeAlreadyReturned:u});p.push(...w.candidates),v+=w.upstreamCandidates,R+=w.runtimeCandidates,C+=w.resultCandidates;let I=w0(E,{db:e,topology:t,nodeById:s,returnedNodeIds:a,sourceAllowed:o,alternativeAlreadyReturned:u},f);p.push(...I);let k=L0(E,{db:e,topology:t,nodeById:s,returnedNodeIds:a,sourceAllowed:o,alternativeAlreadyReturned:u},{evidencedCallsiteKeys:f,consideredCandidateKeys:g,calleeMap:m,stepDefinition:d.get(E.id)});p.push(...k.candidates),h+=k.scannedBehaviorSteps,b+=k.visibleCallsites,S+=k.identityCandidateCallsites,y+=k.ambiguousCallsites,x+=k.unresolvedCallsites}return JS(e,p,n.steps,i,{scannedBehaviorSteps:h,visibleCallsites:b,graphEvidencedCallsites:f.size,identityCandidateCallsites:S,ambiguousCallsites:y,unresolvedCallsites:x,upstreamCandidates:v,resultCandidates:C,runtimeCandidates:R},r.selectionTerms)}function I0(e,t){let n=[],r=0,i=0,o=0;if(!e.location||!e.behavior)return{candidates:n,upstreamCandidates:r,resultCandidates:i,runtimeCandidates:o};let s=t.topology.edges.filter(c=>["call","runtime-boundary"].includes(c.kind)&&(c.fromNodeId===e.nodeId||c.toNodeId===e.nodeId)&&c.disposition!=="excluded"&&c.disposition!=="unsupported");for(let c of s){let l=c.toNodeId===e.nodeId,u=l?c.fromNodeId:c.toNodeId;if(t.returnedNodeIds.has(u))continue;let d=t.nodeById.get(u);if(!d?.location||!t.sourceAllowed(d.location.file))continue;let m=c.kind==="call"?Ed(t.db,d):Ld(d);if(!m||t.alternativeAlreadyReturned(m))continue;let p=Id(c,d.location.file)??d.location,f=V(t.db,p.file)[p.line]?.trim(),g=l?"upstream":"downstream",h=c.kind==="runtime-boundary"?l?"runtime-producer":"runtime-consumer":l?"caller":"callee",b=wd(c.evidence),S=Uo(d);n.push({anchor:{id:or(e.id,p.line,d.id),status:b,source:"graph-relation",direction:g,causalRole:h,relationKind:c.kind,fromStepId:e.id,fromLabel:e.label,callsite:{file:p.file,line:p.line,endLine:p.endLine??p.line,text:f||`${d.label} \u2192 ${e.label}`,signals:["call"],calleeLeaf:S},alternatives:[m],alternativeCount:1,evidence:c.evidence}}),l&&(r+=1),c.kind==="runtime-boundary"&&(o+=1)}let a=t.topology.edges.filter(c=>c.kind==="reference"&&c.fromNodeId===e.nodeId&&c.disposition!=="excluded"&&c.disposition!=="unsupported"&&!t.returnedNodeIds.has(c.toNodeId));for(let c of a){let l=t.nodeById.get(c.toNodeId);if(!l?.location||!t.sourceAllowed(l.location.file))continue;let u=Ed(t.db,l);if(!u||t.alternativeAlreadyReturned(u))continue;let d=Uo(l),m=Id(c,e.location.file)?.line,p=e.behavior.lines.find(h=>(m===void 0||m>=h.line&&m<=h.endLine)&&h.text.includes(d));if(!p)continue;let f=VS(p.signals),g=wd(c.evidence);n.push({anchor:{id:or(e.id,p.line,l.id),status:g,source:"graph-relation",direction:"downstream",causalRole:f,relationKind:"reference",fromStepId:e.id,fromLabel:e.label,callsite:{file:e.location.file,line:p.line,endLine:p.endLine,text:p.text,signals:p.signals,calleeLeaf:d},alternatives:[u],alternativeCount:1,evidence:c.evidence}}),f==="result-callback"&&(i+=1)}return{candidates:n,upstreamCandidates:r,resultCandidates:i,runtimeCandidates:o}}function w0(e,t,n){let r=[];if(!e.location)return r;let i=En(t.db,e.location.file,e.location.line,e.location.endLine??e.location.line),o=V(t.db,e.location.file),s=bn(t.db,e.location.file,e.location.line,e.location.endLine??e.location.line);for(let a of i.targets){if(!t.sourceAllowed(a.definition.relativePath))continue;let c=Br(e.location.file,a.sourceLine,a.calleeLeaf);if(n.has(c))continue;n.add(c);let l=xd(s.get(a.sourceLine)),u={symbol:a.definition.symbol,label:a.definition.leaf,file:a.definition.relativePath,line:a.definition.startLine,endLine:a.definition.endLine};t.alternativeAlreadyReturned(u)||r.push({anchor:{id:or(e.id,a.sourceLine,a.definition.symbol),status:"exact",source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:e.id,fromLabel:e.label,callsite:{file:e.location.file,line:a.sourceLine,endLine:a.sourceLine,text:o[a.sourceLine]?.trim()||`${a.calleeLeaf}()`,signals:l,calleeLeaf:a.calleeLeaf},alternatives:[u],alternativeCount:1,evidence:[{method:"scip-occurrence-callsite",strength:"exact",identity:a.definition.symbol,location:{file:e.location.file,line:a.sourceLine}}]}})}return r}function L0(e,t,n){let r={candidates:[],scannedBehaviorSteps:0,visibleCallsites:0,identityCandidateCallsites:0,ambiguousCallsites:0,unresolvedCallsites:0};if(!e.location||!e.behavior)return r;let i=e.behavior.lines.filter(f=>f.signals.includes("call"));if(i.length===0)return r;let o=[],s=0,a=0,c=0,l=(K(t.db,e.location.file)?.callSites??[]).filter(f=>i.some(g=>f.line>=g.line&&f.line<=g.endLine)),u=t.topology.edges.filter(f=>f.kind==="call"&&f.fromNodeId===e.nodeId&&f.disposition!=="excluded"&&f.disposition!=="unsupported"),d=new Map;for(let f of u){let g=t.nodeById.get(f.toNodeId);if(!g)continue;let h=Uo(g);d.set(h,(d.get(h)??0)+1)}let m=D0(t.db,n.stepDefinition?n.calleeMap.get(n.stepDefinition.symbolId)??[]:[]),p=M0(m);for(let f of m){if(!t.sourceAllowed(f.alternative.file)||t.alternativeAlreadyReturned(f.alternative))continue;let g=qe(f.alternative.label),h=qS(l,i,g,f.row.callsiteLine,p.get(g)===1);if(!h)continue;let b=Ho(i,h.line,g);if(!b)continue;let S=Br(e.location.file,h.line,g);if(n.evidencedCallsiteKeys.has(S))continue;n.evidencedCallsiteKeys.add(S);let y=QS(f.row.source);o.push({anchor:{id:or(e.id,h.line,f.alternative.symbol??f.alternative.file),status:y,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:e.id,fromLabel:e.label,callsite:{file:e.location.file,line:b.line,endLine:b.endLine,text:b.text,signals:b.signals,calleeLeaf:g},alternatives:[f.alternative],alternativeCount:1,evidence:[{method:f.row.source,strength:y,identity:f.row.symbol,location:{file:e.location.file,line:h.line}}]}})}for(let f of u){if(t.returnedNodeIds.has(f.toNodeId))continue;let g=t.nodeById.get(f.toNodeId);if(!g?.location||!t.sourceAllowed(g.location.file))continue;let h=Uo(g),b=f.evidence.find(R=>{let E=R.location;return E!==null&&E.file===e.location?.file&&E.line>=0})?.location?.line,S=qS(l,i,h,b,d.get(h)===1);if(!S)continue;let y=Ho(i,S.line,h);if(!y)continue;let x=Br(e.location.file,S.line,h);if(n.evidencedCallsiteKeys.has(x))continue;n.evidencedCallsiteKeys.add(x);let v=Ld(g);if(!v||t.alternativeAlreadyReturned(v))continue;let C=wd(f.evidence);o.push({anchor:{id:or(e.id,S.line,g.id),status:C,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:e.id,fromLabel:e.label,callsite:{file:e.location.file,line:y.line,endLine:y.endLine,text:y.text,signals:y.signals,calleeLeaf:h},alternatives:[v],alternativeCount:1,evidence:f.evidence}})}for(let f of l){let g=Br(e.location.file,f.line,f.calleeLeaf);if(n.evidencedCallsiteKeys.has(g))continue;let h=Ho(i,f.line,f.calleeLeaf);if(!h)continue;let b=_t(e.location.file,zt(t.db).get(f.calleeLeaf)??[]).flatMap(v=>U(t.db,v.file).filter(C=>C.symbol===v.symbol&&C.isFunctionLike)).filter(v=>t.sourceAllowed(v.relativePath)&&!t.alternativeAlreadyReturned({symbol:v.symbol,label:v.leaf,file:v.relativePath,line:v.startLine,endLine:v.endLine})),S=oc(b.map(v=>({symbol:v.symbol,label:v.leaf??f.calleeLeaf,file:v.relativePath,line:v.startLine,endLine:v.endLine})));if(S.length===0){c+=1;continue}let y=`${e.id}\0${f.line}\0${f.calleeLeaf}`;if(n.consideredCandidateKeys.has(y))continue;n.consideredCandidateKeys.add(y);let x=S.length>1;x?a+=1:s+=1,o.push({anchor:{id:or(e.id,f.line,f.calleeLeaf),status:x?"ambiguous":"candidate",source:"leaf-identity-candidate",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:e.id,fromLabel:e.label,callsite:{file:e.location.file,line:h.line,endLine:h.endLine,text:h.text,signals:h.signals,calleeLeaf:f.calleeLeaf},alternatives:S.slice(0,3),alternativeCount:S.length,evidence:[]}})}return{candidates:o,scannedBehaviorSteps:1,visibleCallsites:l.length,identityCandidateCallsites:s,ambiguousCallsites:a,unresolvedCallsites:c}}function WS(e,t,n){let r=new Map(t.nodes.map(i=>[i.id,i]));for(let i of n.steps)if(!(!i.behavior||!i.location))for(let o of t.edges){if(o.kind!=="reference"||o.fromNodeId!==i.nodeId||o.disposition==="excluded"||o.disposition==="unsupported")continue;let s=r.get(o.toNodeId);if(!s?.location||!Ed(e,s))continue;let a=Uo(s),c=Id(o,i.location.file)?.line,l=i.behavior.lines.find(u=>(c===void 0||c>=u.line&&c<=u.endLine)&&u.text.includes(a));!l||VS(l.signals)!=="result-callback"||o.semantics?.some(({family:u,subtype:d})=>u==="control"&&d==="result-callback")||(o.semantics=[...o.semantics??[],{family:"control",subtype:"result-callback",attributes:{evidenceRole:"result-producing-callable-reference"}}])}}function VS(e){return e.includes("call")&&e.some(t=>["return","mutation","shape","spread","binding"].includes(t))?"result-callback":"callable-reference"}function YS(e,t,n={}){let r=n.limit??zS;if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`next-anchor limit must be a positive safe integer; received ${r}`);let i=n.sourceAllowed??(()=>!0),o=[],s=t.map((p,f)=>({id:p.id,nodeId:p.id,order:f,role:"anchor",kind:"source-construct",label:p.label,location:{file:p.file,line:p.startLine,endLine:p.endLine},behavior:null})),a=t.map(p=>({file:p.file,startLine:p.startLine,endLine:p.endLine})),c=0,l=0,u=0,d=0,m=0;for(let p of t){let f=V(e,p.file),h=(K(e,p.file)?.callSites??[]).filter(C=>C.line>=p.startLine&&C.line<=p.endLine);c+=h.length;let b=bn(e,p.file,p.startLine,p.endLine),S=En(e,p.file,p.startLine,p.endLine),y=new Set;for(let C of S.targets){if(!i(C.definition.relativePath)||a.some(I=>I.file===C.definition.relativePath&&I.startLine<=C.definition.startLine&&I.endLine>=C.definition.endLine))continue;let R=Br(p.file,C.sourceLine,C.calleeLeaf);y.add(R);let E=xd(b.get(C.sourceLine)),w={symbol:C.definition.symbol,label:C.definition.leaf,file:C.definition.relativePath,line:C.definition.startLine,endLine:C.definition.endLine};o.push({anchor:{id:or(p.id,C.sourceLine,C.definition.symbol),status:"exact",source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:p.id,fromLabel:p.label,callsite:{file:p.file,line:C.sourceLine,endLine:C.sourceLine,text:f[C.sourceLine]?.trim()||`${C.calleeLeaf}()`,signals:E,calleeLeaf:C.calleeLeaf},alternatives:[w],alternativeCount:1,evidence:[{method:"scip-occurrence-callsite",strength:"exact",identity:C.definition.symbol,location:{file:p.file,line:C.sourceLine}}]}})}l+=S.resolvedCallsites;let x=nr(e,p.file,{ranges:[{startLine:p.startLine,endLine:p.endLine}]}),v=new Map;for(let C of x.targets){let R=h.find(I=>I.line===C.line)?.calleeLeaf??C.calleeLeaf,E=Br(p.file,C.line,R),w=v.get(E)??[];w.push(C),v.set(E,w)}for(let[C,R]of v){if(y.has(C))continue;y.add(C);let E=R.filter(L=>i(L.targetFile)&&!a.some(A=>A.file===L.targetFile&&A.startLine<=L.targetStartLine&&A.endLine>=L.targetEndLine));if(E.length===0)continue;let w=E[0],I=h.find(L=>L.line===w.line)?.calleeLeaf??w.calleeLeaf,k=xd(b.get(w.line)),D=oc(E.map(L=>({symbol:L.targetSymbol??null,label:L.calleeLeaf,file:L.targetFile,line:L.targetStartLine,endLine:L.targetEndLine}))),F=E.some(L=>(L.resolutionAlternativeCount??0)>1)?"candidate":E.every(L=>L.strength==="exact")?"exact":"derived";o.push({anchor:{id:or(p.id,w.line,D.map(L=>`${L.file}:${L.line}`).join("|")),status:D.length>1?"ambiguous":F,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:p.id,fromLabel:p.label,callsite:{file:p.file,line:w.line,endLine:w.line,text:f[w.line]?.trim()||`${w.calleeLeaf}()`,signals:k,calleeLeaf:I},alternatives:D.slice(0,3),alternativeCount:D.length,evidence:E.map(L=>({method:L.resolution==="constructed-member-receiver"?"ast-constructed-member-callsite":L.resolution==="factory-callback-member"?"ast-factory-callback-callsite":L.resolution==="imported-service-object-member"?"ast-service-member-callsite":"ast-import-member-callsite",strength:F,identity:L.targetSymbol??`${L.targetFile}:${L.targetStartLine}-${L.targetEndLine}`,location:{file:p.file,line:w.line}}))}})}l+=v.size;for(let C of h){let R=Br(p.file,C.line,C.calleeLeaf);y.has(R)||(m+=1)}}return JS(e,o,s,r,{scannedBehaviorSteps:t.length,visibleCallsites:c,graphEvidencedCallsites:l,identityCandidateCallsites:u,ambiguousCallsites:d,unresolvedCallsites:m,upstreamCandidates:0,resultCandidates:0,runtimeCandidates:0})}function JS(e,t,n,r,i,o=[]){let s=T0(t).sort(XS),a=s.filter(f=>P0(e,f)).slice(0,r),c=new Set(a.map(f=>f.anchor.id)),l=s.filter(f=>!c.has(f.anchor.id)),u=a.map(f=>f.anchor),d=l.map(f=>f.anchor),m=oc(u.flatMap(f=>f.alternativeCount===1?f.alternatives:[])),p=oc(d.flatMap(f=>f.alternativeCount===1?f.alternatives:[]));return{anchors:u,withheldAnchors:d,candidateAnchors:s.length,omittedAnchors:Math.max(0,s.length-u.length),...i,inspectCommand:m.length===0?null:`scip-query inspect ${m.map(GS).join(" ")} --view behavior`,remainingInspectCommands:A0(p,8).map(f=>`scip-query inspect ${f.map(GS).join(" ")} --view behavior`)}}function XS(e,t){let n=e.anchor.alternatives[0],r=t.anchor.alternatives[0];return ic(e.anchor.status)-ic(t.anchor.status)||(e.anchor.direction??"").localeCompare(t.anchor.direction??"")||(e.anchor.relationKind??"").localeCompare(t.anchor.relationKind??"")||(e.anchor.causalRole??"").localeCompare(t.anchor.causalRole??"")||e.anchor.fromStepId.localeCompare(t.anchor.fromStepId)||e.anchor.callsite.file.localeCompare(t.anchor.callsite.file)||e.anchor.callsite.line-t.anchor.callsite.line||(n?.file??"").localeCompare(r?.file??"")||(n?.line??0)-(r?.line??0)||e.anchor.id.localeCompare(t.anchor.id)}function P0(e,t){if(t.anchor.alternativeCount!==1)return!0;let n=t.anchor.alternatives[0],r=n.endLine??n.line;return V(e,n.file).slice(n.line,r+1).join(`
74
- `).length<=2e4}function xd(e){return e?.includes("call")?[...e]:["call",...e??[]]}function D0(e,t){let n=new Map;for(let r of t){let i=U(e,r.file).find(a=>a.symbol===r.symbol&&a.isFunctionLike);if(!i)continue;let o={symbol:i.symbol,label:i.leaf,file:i.relativePath,line:i.startLine,endLine:i.endLine},s=n.get(i.symbol);!s||US(r.source)>US(s.row.source)?n.set(i.symbol,{row:{...r,...r.callsiteLine===void 0&&s?.row.callsiteLine!==void 0?{callsiteLine:s.row.callsiteLine}:{}},alternative:o}):s.row.callsiteLine===void 0&&r.callsiteLine!==void 0&&n.set(i.symbol,{...s,row:{...s.row,callsiteLine:r.callsiteLine}})}return[...n.values()]}function M0(e){let t=new Map;for(let n of e){let r=qe(n.alternative.label);t.set(r,(t.get(r)??0)+1)}return t}function QS(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function US(e){return QS(e)==="exact"?2:1}function Ho(e,t,n){return e.find(r=>t>=r.line&&t<=r.endLine&&r.text.includes(n))??e.find(r=>t>=r.line&&t<=r.endLine)??null}function qS(e,t,n,r,i){if(r!==void 0)return e.find(s=>s.line===r&&s.calleeLeaf===n&&Ho(t,s.line,n)!==null)??null;let o=e.filter(s=>s.calleeLeaf===n&&Ho(t,s.line,s.calleeLeaf)!==null);return i&&o.length===1?o[0]:null}function Uo(e){let t=e.attributes.leaf;if(typeof t=="string"&&t.length>0)return qe(t);let n=e.label.slice(e.label.lastIndexOf(":")+1);return qe(n)}function Rd(e){if(e?.kind!=="symbol"||!e.id.startsWith("symbol:"))return null;try{return decodeURIComponent(e.id.slice(7))}catch{return null}}function Ld(e){return e.location?{symbol:Rd(e),label:e.label,file:e.location.file,line:e.location.line,endLine:e.location.endLine??null}:null}function Ed(e,t){let n=Ld(t);return n?.symbol&&U(e,n.file).some(i=>i.symbol===n.symbol&&i.isFunctionLike)?n:null}function Id(e,t){return e.evidence.find(n=>n.location?.file===t)?.location??e.evidence.find(n=>n.location!==null)?.location??null}function wd(e){let t={exact:5,derived:4,mixed:3,candidate:2,unknown:1};return e.reduce((n,r)=>t[r.strength]>t[n]?r.strength:n,"unknown")}function T0(e){let t=new Map;for(let n of e){let i=n.anchor.alternatives[0]?.symbol??`${n.anchor.callsite.file}:${n.anchor.callsite.line}:${n.anchor.callsite.calleeLeaf}`,o=t.get(i);(!o||k0(n,o)<0)&&t.set(i,n)}return[...t.values()]}function k0(e,t){return ic(e.anchor.status)-ic(t.anchor.status)||e.anchor.alternativeCount-t.anchor.alternativeCount||XS(e,t)}function ic(e){return{exact:0,derived:1,mixed:2,candidate:3,unknown:4,ambiguous:5}[e]}function oc(e){let t=new Map;for(let n of e)t.set(n.symbol??`${n.file}:${n.line}`,n);return[...t.values()].sort((n,r)=>n.file.localeCompare(r.file)||n.line-r.line||n.label.localeCompare(r.label))}function GS(e){return`--at ${F0(`${e.file}:${e.line+1}`)}`}function A0(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function F0(e){return`'${e.replaceAll("'","'\\''")}'`}function Br(e,t,n){return`${e}\0${t}\0${n}`}function or(e,t,n){return["next-anchor",e,String(t),n].map(encodeURIComponent).join(":")}var sv=6,N0=12,_0=48,O0=2e4,ZS=12,$r=Number.MAX_SAFE_INTEGER,B0=["definition","callers","callees"],Td={search:12,"exact-source":24,definition:24,caller:8,callee:8,"production-reference":6,"test-reference":2,dependency:6,consumer:6};function $0(e,t){if(t.cursor)throw new Error("Inspect no longer accepts semantic packet cursors. Run the original inspect selectors again.");let n=H0(t),r=G0(e,n),i=r.candidates.sort((D,F)=>Pd(D,F));n.view==="behavior"&&W0(e,i),V0(e,i),n.view==="behavior"&&z0(e,i);let o=Ub(i.map(D=>Dd(D,n.view)),n.evidenceBudgets,(D,F)=>Pd(D.candidate,F.candidate)),{selected:s,omitted:a}=Ga(o.selected,n.maxUnits,n.maxCharacters,(D,F)=>Pd(D.candidate,F.candidate),n.view==="source"),c=s.map(D=>D.candidate),l=[...o.omitted,...a].map(D=>D.candidate),u=c.map(rN),d=ea(c.map(D=>D.kind==="source"?D.bindingClosure:void 0),c.filter(D=>D.kind==="source").map(D=>({relativePath:D.relativePath,startLine:D.startLine,endLine:D.endLine}))),m=u.reduce((D,F)=>D+(F.kind==="source"?sN(F.source):0),0),p=u.reduce((D,F)=>D+(F.kind==="source"?F.source.length:0),0),f=u.reduce((D,F)=>D+lv(F,n.view),0),g=u.filter(D=>D.kind==="source"&&(D.roles.includes("search")||D.roles.includes("location"))).map(iN),h=i.filter(D=>D.kind==="source"&&(D.roles.includes("search")||D.roles.includes("location"))).length,b=u.filter(D=>D.kind==="source"&&(D.roles.includes("search")||D.roles.includes("location"))).length,S=r.searches.map(D=>X0(D,i,c)),y=Q0(l),x=r.locations.every(D=>D.matched)&&r.evidence.every(D=>D.kind==="matched")&&r.searches.every(D=>eN(D.textCoverage))&&l.every(D=>!D.roles.some(F=>F==="location"||F==="definition")),v=S.reduce((D,F)=>D+F.omittedMatches,0),C=l.length===0&&v===0,R=C?void 0:cv(n,!0),E=Y0(n,l),w=j0(C,x,l.length+v,E,S,R),I=i.filter(D=>n.view==="behavior"&&D.kind==="source"&&D.roles.some(F=>F==="location"||F==="definition"||F==="search")).map(D=>({id:`inspect:${D.relativePath}:${D.startLine}-${D.endLine}`,label:D.ownerShort??`${D.relativePath}:${D.startLine+1}`,file:D.relativePath,startLine:D.startLine,endLine:D.endLine})),k=I.length>0?YS(e,I):void 0;return{searches:S,evidence:r.evidence,locations:r.locations,slices:g,candidateSlices:h,omittedSlices:h-b,maxSlices:h,maxTotalLines:m,units:u,candidateUnits:i.length,omittedUnits:l.length,maxUnits:n.maxUnits,maxCharacters:n.maxCharacters,returnedLines:m,returnedCharacters:p,returnedViewCharacters:f,view:n.view,omissionGroups:E,packetCoverage:{mode:C?"complete":"bounded",candidateUnits:i.length,returnedUnits:u.length,omittedUnits:l.length,omittedByRole:y,exactSelectorsComplete:x,maxUnits:n.maxUnits,maxCharacters:n.maxCharacters,channels:Z0(i,c,n.evidenceBudgets,n.view),...R?{expansionCommand:R}:{}},stoppingSummary:w,...k&&k.candidateAnchors>0?{causalFrontier:k}:{},bindingClosure:d,continuation:null}}function j0(e,t,n,r,i,o){let s=ct([...r.map(a=>a.drillCommand),...i.flatMap(a=>a.exactFollowup?[a.exactFollowup]:[]),...o?[o]:[]]);return e&&t?{queryStatus:"selection-complete",status:"stop-ready",openEvidence:0,guidance:"All evidence requested by this inspect query was materialized.",drillCommands:[]}:t?{queryStatus:"frontier-accounted",status:"relevance-check-required",openEvidence:n,guidance:"Withheld evidence is accounted for by recoverable groups; drill the groups relevant to the current decision.",drillCommands:s}:{queryStatus:"coverage-incomplete",status:"exact-evidence-withheld",openEvidence:n,guidance:"A requested identity, exact source unit, or current-text coverage requirement is unresolved; drill before relying on it.",drillCommands:s}}function H0(e){let t=ke(e.searches),n=ke(e.symbols),r=ke(e.locations),i=t.length+n.length+r.length;if(i===0)throw new Error("inspect requires at least one --search, --symbol, or --at selector.");if(i>24)throw new RangeError(`inspect accepts at most ${24} selectors; received ${i}.`);let o=e.evidence??{};if(e.unitLines!==void 0&&sr(e.unitLines,"unitLines"),e.totalLines!==void 0&&sr(e.totalLines,"totalLines"),e.sliceLimit!==void 0&&sr(e.sliceLimit,"sliceLimit"),e.maxCharacters!==void 0&&sr(e.maxCharacters,"maxCharacters"),e.maxUnits!==void 0&&sr(e.maxUnits,"maxUnits"),e.view!==void 0&&e.view!=="source"&&e.view!=="behavior")throw new Error(`Unknown inspect view: ${String(e.view)}. Use source or behavior.`);if(e.full&&(e.searchLimit!==void 0||e.maxUnits!==void 0||e.maxCharacters!==void 0||e.evidenceBudgets!==void 0))throw new Error("full inspect cannot be combined with searchLimit, maxUnits, maxCharacters, or evidenceBudgets.");let s=e.full??!1;return{searches:t,symbols:n,locations:r,...e.scope?.trim()?{scope:e.scope.trim()}:{},context:iv(e.context??sv,"context"),searchLimit:sr(e.searchLimit??(s?$r:N0),"searchLimit"),maxUnits:sr(s?$r:e.maxUnits??_0,"maxUnits"),maxCharacters:sr(s?$r:e.maxCharacters??O0,"maxCharacters"),evidenceBudgets:s?q0():U0(e.evidenceBudgets??Td),view:e.view??"source",evidence:{...o.parts?{parts:[...o.parts]}:n.length>0?{parts:[...B0]}:{},...o.referenceContext!==void 0?{referenceContext:iv(o.referenceContext,"referenceContext")}:{},relatedSourceLines:o.relatedSourceLines??60,...o.semantic!==void 0?{semantic:o.semantic}:{}}}}function U0(e){let t={...Td};for(let[n,r]of Object.entries(e)){if(!(n in t))throw new Error(`Unknown inspect evidence channel: ${n}.`);if(!Number.isSafeInteger(r)||(r??-1)<0)throw new RangeError(`Evidence budget ${n} must be a non-negative safe integer; received ${r}.`);t[n]=r}return t}function q0(){return Object.fromEntries(Object.keys(Td).map(e=>[e,$r]))}function G0(e,t){let n=[],r=0,i=za(e,t.searches,{scope:t.scope,context:0,limit:t.searchLimit,ranking:"structural"}).map((l,u)=>({pattern:t.searches[u],result:l,matches:l.matches})),o=Math.max(0,...i.map(l=>l.matches.length));for(let l=0;l<o;l+=1)for(let u of i){let d=u.matches[l];if(!d)continue;let m=Kn(e,d.relativePath,d.focusLine,$r,t.context);m&&Mi(e,n,m,"search",`search:${u.pattern}`,d.ownerSymbol,d.ownerShort,1,r++)}let s=i.map(({pattern:l,result:u})=>{let d=u.omittedMatches>0?av(l,t.scope):void 0,m=u.fileCoverage??[],p=tN(l,m,t.scope);return{pattern:l,matchingLines:u.matchingLines,returnedMatches:u.matches.length,omittedMatches:u.omittedMatches,matchingFiles:m.length,returnedFiles:m.filter(f=>f.returnedMatches>0).length,omittedFiles:m.filter(f=>f.returnedMatches===0).length,candidateUnits:0,selectedUnits:0,omittedUnits:0,scopeHints:p.slice(0,ZS),omittedScopeHints:Math.max(0,p.length-ZS),textCoverage:u.textCoverage,...d?{exactFollowup:d}:{}}}),a=t.locations.map(l=>{let u=oN(l),d=u?rg(e,u.path):null,m=d?Kn(e,d,u.line-1,$r,t.context):null;return m&&Mi(e,n,m,"location",`at:${l}`,null,null,0,r++),{target:l,matched:m!==null}}),c=t.symbols.map(l=>Cd(e,l,t.evidence));for(let l of c)if(l.kind==="matched"){if(l.definition){let u=Kn(e,l.definition.relativePath,l.definition.startLine,$r,t.context);u&&Mi(e,n,u,"definition",`definition:${l.shortName}`,l.symbol,l.shortName,0,r++)}for(let u of l.referenceWindows){let d=u.references[0];Mi(e,n,{...u,focusLine:d?.line??u.startLine,unitType:null,unitStartLine:u.startLine,unitEndLine:u.endLine,omittedLines:0},"reference",`reference:${l.shortName}`,d?.enclosingSymbol??null,d?.enclosingShort??null,q(u.relativePath)==="test"?5:4,r++,u.references.map(m=>m.line),l.symbol)}for(let u of l.callers)ev(e,n,u,"caller",l,2,r++);for(let u of l.callees)ev(e,n,u,"callee",l,3,r++);for(let u of l.dependencies)tv(e,n,"dependency",l.file,u.relativePath,l.symbol,t.context,6,r++);for(let u of l.consumers)tv(e,n,"consumer",u.relativePath,l.file,l.symbol,t.context,7,r++)}return{searches:s,evidence:c,locations:a,candidates:n}}function Pd(e,t){return e.priority-t.priority||t.roles.length-e.roles.length||t.reasons.length-e.reasons.length||xe(q(e.relativePath))-xe(q(t.relativePath))||e.sequence-t.sequence}function Dd(e,t){return{candidate:e,priority:e.priority,sequence:e.sequence,relativePath:e.relativePath,fileKind:q(e.relativePath),evidenceCharacters:lv(e,t),roles:e.roles,reasons:e.reasons,symbols:e.symbols,behaviorSignals:e.kind==="source"?e.behavior?.signals??[]:[],channel:Md(e)}}function Md(e){let t=e.roles;return t.includes("location")?"exact-source":t.includes("definition")?"definition":t.includes("caller")?"caller":t.includes("callee")?"callee":t.includes("reference")?q(e.relativePath)==="test"?"test-reference":"production-reference":t.includes("dependency")?"dependency":t.includes("consumer")?"consumer":"search"}function z0(e,t){let n=t.filter(i=>i.kind==="source"),r=no(e,{files:ct(n.map(i=>i.relativePath))});for(let i of n){i.behavior=mi(e,i.relativePath,i.startLine,i.endLine,i.focusLines)??void 0;let o=r.filter(a=>a.source.file===i.relativePath&&a.source.startLine<=i.endLine&&a.source.endLine>=i.startLine),s=o.filter(a=>!K0(a,o)).map(a=>({observationId:a.id,protocol:a.protocol,action:a.action,role:a.role,strength:a.strength,resolution:a.resolution,line:a.source.startLine,endLine:a.source.endLine,keyParts:a.keyParts.map(c=>({name:c.name,value:c.value,evidence:c.evidence})),derivation:{kind:a.derivation.kind,rule:a.derivation.rule,sourceSpans:a.derivation.sourceSpans.length}}));i.runtimeFacts=s.length>0?s:void 0}}function K0(e,t){if(e.strength!=="candidate"||e.protocol!=="http")return!1;let n=e.keyParts.find(i=>i.name==="path")?.value,r=e.keyParts.find(i=>i.name==="method")?.value;return n?t.some(i=>{if(i===e||i.action!==e.action||i.role!==e.role||i.source.startLine!==e.source.startLine||i.derivation.rule!=="http.mount-prefix")return!1;let o=i.keyParts.find(a=>a.name==="path")?.value,s=i.keyParts.find(a=>a.name==="method")?.value;return!!(o&&o!==n&&o.endsWith(n)&&(!r||r===s))}):!1}function W0(e,t){for(let n of t){if(n.kind!=="source")continue;let r=ot(e,n.relativePath,n.startLine,n.endLine,n.focusLines);r.startLine===n.startLine&&r.endLine===n.endLine||(n.startLine=r.startLine,n.endLine=r.endLine,n.source=V(e,n.relativePath).slice(r.startLine,r.endLine+1).join(`
75
- `),n.unitStartLine=r.startLine,n.unitEndLine=r.endLine,n.omittedLines=0)}}function V0(e,t){for(let n of t)n.kind==="source"&&(n.bindingClosure=di(e,n.relativePath,n.startLine,n.endLine))}function Y0(e,t){let n=new Map;for(let r of t){let i=sc(r.relativePath),o=Md(r),s=[...r.roles].sort().join(","),a=r.kind==="path"?r.relationship:"",c=`${i}|${o}|${s}|${a}`,l=n.get(c)??[];l.push(r),n.set(c,l)}return[...n.entries()].map(([r,i])=>{let o=i[0],s=ct(i.flatMap(c=>[...c.roles])).sort(),a=ct(i.flatMap(c=>c.kind==="source"?c.behavior?.signals??[]:[])).sort();return{id:`g-${ov("sha256").update(r).digest("hex").slice(0,8)}`,scope:sc(o.relativePath),channel:Md(o),roles:s,behaviorSignals:a,candidateUnits:i.length,sourceCharacters:i.reduce((c,l)=>c+(l.kind==="source"?l.source.length:0),0),anchors:i.map(c=>({relativePath:c.relativePath,line:c.kind==="source"?c.focusLine:0,ownerShort:c.kind==="source"?c.ownerShort:null,roles:[...c.roles],behaviorSignals:c.kind==="source"?[...c.behavior?.signals??[]]:[]})),drillCommand:J0(e,i)}}).sort((r,i)=>i.candidateUnits-r.candidateUnits||i.sourceCharacters-r.sourceCharacters||r.scope.localeCompare(i.scope)||r.id.localeCompare(i.id))}function J0(e,t){let n=ct(t.flatMap(o=>o.reasons.filter(s=>s.startsWith("search:")).map(s=>s.slice(7)))),r=sc(t[0].relativePath);if(n.length>0&&t.every(o=>o.kind==="source"&&o.roles.includes("search"))){let o=["scip-query inspect"];for(let s of n)o.push(`--search ${Tt(s)}`);return o.push(`--scope ${Tt(r)}`,"--full"),e.view==="behavior"&&o.push("--view behavior"),o.join(" ")}let i=t.filter(o=>o.kind==="source");if(i.length>0&&i.length<=24){let o=["scip-query inspect"];for(let s of i)o.push(`--at ${Tt(`${s.relativePath}:${s.focusLine+1}`)}`);return e.view==="behavior"&&o.push("--view behavior"),o.join(" ")}return t.length===1&&t[0].kind==="path"?t[0].exactFollowup:cv(e,!0)}function X0(e,t,n){let r=`search:${e.pattern}`,i=t.filter(a=>a.reasons.includes(r)).length,o=new Set(n),s=t.filter(a=>a.reasons.includes(r)&&o.has(a)).length;return{...e,candidateUnits:i,selectedUnits:s,omittedUnits:i-s}}function Q0(e){let t={};for(let n of e)for(let r of n.roles)t[r]=(t[r]??0)+1;return t}function Z0(e,t,n,r){let i=e.map(s=>Dd(s,r).channel),o=t.map(s=>Dd(s,r).channel);return Object.fromEntries(Object.keys(n).map(s=>{let a=i.filter(l=>l===s).length,c=o.filter(l=>l===s).length;return[s,{candidateUnits:a,returnedUnits:c,omittedUnits:a-c,maxUnits:n[s]}]}))}function eN(e){return!!(e&&e.skippedUnreadablePaths.length===0&&e.skippedOversizedPaths.length===0)}function tN(e,t,n){let r=new Map;for(let i of t){let o=sc(i.relativePath),s=r.get(o)??{matchingLines:0,returnedMatches:0};s.matchingLines+=i.matchingLines,s.returnedMatches+=i.returnedMatches,r.set(o,s)}return[...r.entries()].map(([i,o])=>({scope:i,...o,exactFollowup:av(e,i||n)})).sort((i,o)=>o.matchingLines-i.matchingLines||o.returnedMatches-i.returnedMatches||i.scope.localeCompare(o.scope))}function sc(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}function av(e,t){return`scip-query inspect --search ${Tt(e)}${t?` --scope ${Tt(t)}`:""} --full`}function cv(e,t){let n=["scip-query inspect"];for(let r of e.searches)n.push(`--search ${Tt(r)}`);for(let r of e.symbols)n.push(`--symbol ${Tt(r)}`);for(let r of e.locations)n.push(`--at ${Tt(r)}`);return e.scope&&n.push(`--scope ${Tt(e.scope)}`),e.context!==sv&&n.push(`--context ${e.context}`),e.evidence.parts&&n.push(`--include ${Tt(e.evidence.parts.join(","))}`),t&&n.push("--full"),e.view==="behavior"&&n.push("--view behavior"),n.join(" ")}function ev(e,t,n,r,i,o,s){Mi(e,t,{...n,unitType:null,unitStartLine:n.startLine,unitEndLine:n.endLine+n.omittedLines},r,`${r}:${i.shortName}`,n.symbol,n.shortName,o,s,[n.focusLine],i.symbol)}function tv(e,t,n,r,i,o,s,a,c){let l=`${r} -> ${i}`,u=ae(e,r).filter(h=>h.sourcePath===i),d=V(e,r),m=nN(d,u,i),p=m===null?null:ua(e,r,m,Math.min(s,4));if(p){Mi(e,t,{...p,unitType:null,unitStartLine:p.startLine,unitEndLine:p.endLine,omittedLines:0},n,`${n}:${l}`,null,null,a,c,[p.focusLine],o);return}let f=`scip-query inspect --search ${Tt(uv(i))} --scope ${Tt(r)}`,g=t.find(h=>h.kind==="path"&&h.relativePath===r&&h.relationship===l);if(g){g.roles=ct([...g.roles,n]),g.reasons=ct([...g.reasons,`${n}:${l}`]),g.symbols=ct([...g.symbols,o]),g.priority=Math.min(g.priority,a);return}t.push({kind:"path",roles:[n],relativePath:r,relationship:l,reasons:[`${n}:${l}`],symbols:[o],exactFollowup:f,priority:a,sequence:c})}function nN(e,t,n){let r=ct(t.flatMap(c=>[c.importedName,c.localName??""]).filter(c=>c.length>1)),i=uv(n).replace(/\.[^.]+$/u,""),o=ct([...r,i]).filter(Boolean),s=/\b(?:from|import|include|require|use)\b/u,a=e.findIndex(c=>s.test(c)&&o.some(l=>c.includes(l)));return a>=0?a:null}function Mi(e,t,n,r,i,o,s,a,c,l=[n.focusLine],u){let d=t.find(m=>m.kind==="source"&&m.relativePath===n.relativePath&&m.startLine<=n.endLine&&n.startLine<=m.endLine);if(d){let m=Math.min(d.startLine,n.startLine),p=Math.max(d.endLine,n.endLine);d.startLine=m,d.endLine=p,d.source=V(e,n.relativePath).slice(m,p+1).join(`
76
- `),d.focusLine=Math.min(d.focusLine,n.focusLine),d.focusLines=rv([...d.focusLines,...l]),d.unitStartLine=Math.min(d.unitStartLine,n.unitStartLine),d.unitEndLine=Math.max(d.unitEndLine,n.unitEndLine),d.omittedLines=Math.max(d.omittedLines,n.omittedLines),d.reasons=ct([...d.reasons,i]),d.roles=ct([...d.roles,r]),d.symbols=ct([...d.symbols,...u?[u]:[]]),!d.ownerSymbol&&o&&(d.ownerSymbol=o),!d.ownerShort&&s&&(d.ownerShort=s),d.priority=Math.min(d.priority,a);return}t.push({kind:"source",...n,reasons:[i],focusLines:rv(l),ownerSymbol:o,ownerShort:s,roles:[r],symbols:u?[u]:[],priority:a,sequence:c})}function rN(e){if(e.kind==="path"){let{priority:o,sequence:s,...a}=e;return{...a,id:nv(a)}}let{priority:t,sequence:n,bindingClosure:r,...i}=e;return{...i,id:nv(i),omittedCharacters:0}}function iN(e){let{kind:t,id:n,roles:r,symbols:i,omittedCharacters:o,behavior:s,runtimeFacts:a,...c}=e;return c}function nv(e){return ov("sha256").update(JSON.stringify(e)).digest("hex").slice(0,16)}function oN(e){let t=e.match(/^(.+\.\w+):(\d+)$/u);if(!t)return null;let n=Number(t[2]);return Number.isSafeInteger(n)&&n>0?{path:t[1],line:n}:null}function ct(e){return[...new Set(e)]}function rv(e){return ct(e).sort((t,n)=>t-n)}function sN(e){return e.length===0?0:e.split(`
77
- `).length}function lv(e,t){if(e.kind==="path")return e.relationship.length+e.exactFollowup.length;let n="bindingClosure"in e?bg(e.bindingClosure):0,r=(e.runtimeFacts??[]).reduce((i,o)=>i+o.action.length+o.derivation.rule.length+o.keyParts.reduce((s,a)=>s+a.name.length+a.value.length+4,0)+24,0);return t!=="behavior"?e.source.length+n:e.behavior?e.behavior.lines.reduce((i,o)=>i+o.text.length+o.signals.join(",").length+12,0)+e.behavior.testCases.reduce((i,o)=>i+o.length+2,0)+r+n:e.source.length+n+r}function uv(e){return e.split("/").at(-1)??e}function Tt(e){return`'${e.replaceAll("'","'\\''")}'`}function sr(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new RangeError(`${t} must be a positive safe integer; received ${e}`);return e}function iv(e,t){if(!Number.isSafeInteger(e)||e<0)throw new RangeError(`${t} must be a non-negative safe integer; received ${e}`);return e}import{basename as aN}from"path";function cN(e,t){let n=t.className,r=Qe(e,n);return r.match?r.total>1?{kind:"ambiguous",query:n,total:r.total,candidates:[dv(r.match),...r.candidates]}:{kind:"matched",query:n,owner:uN(r.match),methods:lN(e,r.match)}:{kind:"missing",query:n,suggestions:Hs(e,n,5)}}function lN(e,t){let n=z(t.symbol),i=new H(e).definitionsForFile(t.relativePath).filter(c=>Xe(c.symbol)),o=i.filter(c=>c.parentTypeName===n||c.symbol.includes(n)),a=(o.length>0?o:dN(aN(t.relativePath))===n?i.filter(c=>c.symbol.includes("<invalid-global-code>")):[]).map(c=>({startLine:c.startLine,endLine:c.endLine,name:z(c.symbol)}));return se(t.relativePath)!=="clojure"?a:pN(a,mN(e,t))}function dv(e){return{symbol:e.symbol,shortName:T(e.symbol),relativePath:e.relativePath,startLine:e.startLine}}function uN(e){return{...dv(e),endLine:e.endLine}}function dN(e){return e.replace(/\.[^.]+$/,"")}function mN(e,t){let n=z(t.symbol);return n?(K(e,t.relativePath)?.clojureMembers??[]).filter(r=>r.ownerName===n).map(r=>({startLine:r.startLine,endLine:r.endLine,name:r.memberName})):[]}function pN(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.name}:${r.startLine}:${r.endLine}`,r);return[...n.values()].sort((r,i)=>r.startLine-i.startLine||r.endLine-i.endLine)}import{createHash as PB}from"crypto";var vne={exact:"Direct compiler or source evidence establishes this relationship within the provider's reported coverage.",derived:"A deterministic analysis computed this relationship from reported input facts; it was not directly observed.",candidate:"Ambiguous or heuristic evidence identifies a lead that requires exact graph or source confirmation.",mixed:"The relationship combines evidence of different strengths; its constituent methods and strengths remain disclosed.",unknown:"The relationship has no calibrated evidence strength and cannot support a stronger claim than its raw observation."},fN=[{id:"general-interprocedural-value-flow",families:["dataflow"],capability:"Whole-program definition-use flow through arbitrary calls and returns is unavailable.",consequence:"Missing dataflow edges cannot establish that a value never crosses an unmodeled call.",recoverWith:["value-flow","dependence-slice","inspect","code"]},{id:"heap-aliasing",families:["dataflow","state"],capability:"Heap points-to and cross-instance alias analysis are unavailable.",consequence:"Missing field or state edges cannot establish that two references never reach the same object.",recoverWith:["value-flow","dependence-slice","inspect","code"]},{id:"exceptional-flow",families:["execution","dataflow","temporal"],capability:"Interprocedural exception propagation and finally completion flow are unavailable.",consequence:"Normal-path reachability and ordering do not establish behavior after a throw or rejection.",recoverWith:["dependence-slice","inspect","code"]},{id:"reflection",families:["execution","runtime","identity","dependencies"],capability:"Reflective lookup, dynamic loading, and name-computed invocation are unavailable without exact evidence.",consequence:"Missing static edges cannot establish that a construct is unreachable through reflection.",recoverWith:["search","inspect","code"]},{id:"generated-dispatch",families:["execution","runtime","identity"],capability:"Dispatch tables or names created only by generated or unavailable source are unavailable.",consequence:"Missing dispatch edges cannot establish that no generated consumer exists.",recoverWith:["search","inspect","code"]},{id:"unsupported-framework-adapters",families:["runtime","dataflow","state","temporal"],capability:"Framework runtime crossings without a registered source adapter are unavailable.",consequence:"Missing boundary edges cannot establish that no producer, consumer, state effect, or ordering exists.",recoverWith:["search","inspect","code"]}];function gN(e){let t=new Set(e);return fN.filter(n=>n.families.some(r=>t.has(r)))}function mv(e){return gN(e).map(t=>`[${t.id}] ${t.capability} ${t.consequence} Recover selected paths with: ${t.recoverWith.map(n=>`scip-query ${n}`).join(", ")}.`)}var hN=["incoming","outgoing","both"];function fe(e,t,n,r={}){return{family:e,subtype:t,...r.match?{match:r.match}:{},directions:hN,evidenceStrengths:r.strengths??["exact","derived","mixed"],supportCeiling:r.supportCeiling??"partial",establishes:n,nonClaims:r.nonClaims??[],recoverWith:r.recoverWith??["inspect","code"]}}var yN=["predicate-consequence","predicate-alternative","predicate-fallthrough","predicate-case","predicate-default","predicate-return","predicate-throw","loop-iteration","loop-exit","exception-handler","finally-cleanup","handler-return","handler-throw"],bN=["captured-value-to-state","constant-to-state","expression-to-state","property-to-state","return-to-state","value-to-state"],SN=["await-completion-before","awaits-completion","inside-lock-scope","lexical-successor"],vN=[{id:"indexed-program-identity",label:"SCIP/compiler identity and source ownership",requirements:["indexed-graph"],relations:[fe("execution","call","The source construct may call the resolved target.",{strengths:["exact","derived","candidate","mixed"],nonClaims:["Static may-call reachability does not prove that an invocation occurred at runtime."],recoverWith:["call-graph","inspect","code"]}),fe("execution","result-callback","The referenced callable can produce the result consumed by this path.",{nonClaims:["A callback relationship does not prove invocation order or runtime selection."],recoverWith:["call-graph","inspect","code"]}),fe("contract","uses-contract-symbol","The source construct refers to the identified contract symbol.",{supportCeiling:"exact",nonClaims:["Contract identity does not prove runtime invocation or behavioral conformance."],recoverWith:["hierarchy","inspect","code"]}),fe("identity","references","The occurrence resolves to the identified compiler-owned symbol.",{supportCeiling:"exact",nonClaims:["A reference does not establish execution or value transfer."],recoverWith:["refs","trace","inspect"]}),fe("ownership","contains","The owner contains the identified program construct.",{supportCeiling:"exact",nonClaims:["Structural containment does not establish runtime lifetime or sharing scope."],recoverWith:["outline","inspect"]}),fe("ownership","contains-","The owner contains the identified program construct.",{match:"prefix",supportCeiling:"exact",nonClaims:["Structural containment does not establish runtime lifetime or sharing scope."],recoverWith:["outline","inspect"]}),fe("ownership","owns-","The owner owns the identified source or runtime observation.",{match:"prefix",supportCeiling:"exact",nonClaims:["Observation ownership does not establish singleton lifetime or exclusive ownership."],recoverWith:["inspect","code"]}),fe("dependencies","imports","The source file or module statically imports the indexed target.",{nonClaims:["An import does not establish that imported code executes."],recoverWith:["imports","deps","code"]}),fe("dependencies","imports-external","The source region statically imports an external package.",{nonClaims:["An external import does not establish which package behavior executes."],recoverWith:["imports","code"]})]},{id:"runtime-boundary-join",label:"source-grounded runtime-boundary joins",requirements:["indexed-graph","source-facts"],relations:[fe("runtime","runtime-handoff","A producer and consumer share a source-grounded runtime rendezvous.",{strengths:["exact","derived","candidate","mixed"],nonClaims:["A candidate or unresolved join does not prove a runtime handoff."],recoverWith:["evidence","inspect","code"]}),fe("runtime","discriminator-dispatch","A serialized discriminator selects the reported consumer.",{strengths:["exact","derived","mixed"],nonClaims:["The dispatch edge does not prove delivery, retry, or successful handling."],recoverWith:["evidence","inspect","code"]}),fe("dataflow","serialized-discriminator-transfer","The producer serializes the discriminator consumed by dispatch.",{strengths:["exact","derived","mixed"],nonClaims:["This edge does not establish the flow of every payload field."],recoverWith:["value-flow","inspect","code"]}),fe("temporal","enqueue-before-consume","The reported enqueue precedes a possible consume through the queue.",{strengths:["exact","derived","mixed"],nonClaims:["Queue order does not establish delivery time, uniqueness, retry count, or durability."],recoverWith:["evidence","inspect","code"]})]},{id:"parser-control-dependence",label:"parser-proved intraprocedural control dependence",requirements:["indexed-graph","source-facts"],relations:[...yN.map(e=>fe("execution",e,"The outcome is control-dependent on the reported predicate or handler.",{strengths:["exact"],nonClaims:["Local control dependence does not establish that the containing function executes."],recoverWith:["dependence-slice","inspect","code"]})),fe("execution","returns","The selected construct contains the reported return terminal.",{strengths:["exact"],nonClaims:["A local return terminal does not establish that the containing callable executes."],recoverWith:["inspect","code"]}),fe("execution","throws","The selected construct contains the reported throw terminal.",{strengths:["exact"],nonClaims:["A local throw terminal does not establish propagation, handling, or callable execution."],recoverWith:["inspect","code"]})]},{id:"bounded-static-value-flow",label:"compiler callsites and bounded static value evaluation",requirements:["indexed-graph","source-facts"],relations:["argument-to-parameter","constant-to-parameter","property-to-parameter","return-to-parameter","return-to-call-result"].map(e=>fe("dataflow",e,"The reported value may reach the target through the evidenced callsite transfer.",{strengths:["exact","derived","mixed"],nonClaims:["This provider does not establish general local definition-use, alias, field, or heap flow."],recoverWith:["value-flow","dependence-slice","inspect","code"]}))},{id:"typescript-local-dependence",label:"TypeScript compiler identities, control-flow graph, and reaching definitions",requirements:["typescript-semantic"],relations:[fe("dataflow","definition-to-use","The definition reaches the reported read on a feasible local control-flow path.",{strengths:["exact"],nonClaims:["Local reaching definitions do not establish heap aliasing, exceptional flow, or the runtime order of closure invocation."],recoverWith:["value-flow","dependence-slice","inspect","code"]}),fe("dataflow","value-to-definition","The reported right-hand-side read supplies the assigned local definition.",{strengths:["exact"],nonClaims:["A local assignment edge does not establish field or heap points-to flow."],recoverWith:["value-flow","dependence-slice","inspect","code"]}),fe("dataflow","closure-capture","The nested callable reads the reported binding from an enclosing callable.",{strengths:["candidate"],supportCeiling:"candidate",nonClaims:["Closure capture does not establish whether or when the nested callable executes."],recoverWith:["call-graph","inspect","code"]}),fe("dataflow","field-definition-to-use","The reported same-owner field definition can reach the field read.",{strengths:["exact","candidate"],nonClaims:["Field-name identity does not establish whole-program heap aliasing or cross-instance flow."],recoverWith:["value-flow","dependence-slice","inspect","code"]}),fe("execution","control-dependence","Execution of the reported statement depends on the outcome of the predicate.",{strengths:["exact"],nonClaims:["Intraprocedural control dependence does not establish that the containing callable executes."],recoverWith:["dependence-slice","inspect","code"]})]},{id:"parser-state-temporal",label:"parser-proved local state and temporal facts",requirements:["indexed-graph","source-facts"],relations:[...bN.map(e=>fe("dataflow",e,"The reported source value is assigned into the identified state resource.",{strengths:["exact"],nonClaims:["The edge does not establish alias, heap, or later read flow."],recoverWith:["value-flow","inspect","code"]})),...["writes-resource","deletes-resource","reads-resource","enqueues-resource","consumes-resource"].map(e=>fe("state",e,"The reported construct performs the named operation on the identified resource.",{strengths:["exact"],nonClaims:["A state operation does not establish transactionality, durability, or exclusive ownership."],recoverWith:["evidence","inspect","code"]})),...SN.map(e=>fe("temporal",e,"The reported source constructs have the named local ordering relationship.",{strengths:["exact"],nonClaims:["Local source order does not establish cross-process happens-before or durable completion."],recoverWith:["evidence","inspect","code"]}))]}];function ac(e,t){let n=vN.flatMap(r=>r.relations.filter(i=>i.family===e&&(i.match==="prefix"?t.startsWith(i.subtype):t===i.subtype)).map(i=>({provider:r,relation:i})));if(n.length>1)throw new Error(`Ambiguous graph relation provider for ${e}/${t}: ${n.map(r=>r.provider.id).join(", ")}`);return n[0]??null}var Bt=["execution","runtime","dataflow","state","temporal","contract","identity","ownership","dependencies"];function _e(e,t){let n=new Map;for(let r of e){let i=t(r),o=n.get(i)??[];o.push(r),n.set(i,o)}return n}function Ti(e){return e.includes("symbol-anchor")?0:e.includes("literal-owner")?1:e.some(t=>t.startsWith("boundary-import:"))?2:e.includes("reference-owner")?3:4}function pv(e,t){return Ti(e.origins)-Ti(t.origins)||e.depth-t.depth||e.startLine-t.startLine||e.shortName.localeCompare(t.shortName)}var fv=["call","contract-symbol","import","reference","runtime-boundary"],CN={call:[{family:"control",subtype:"call"}],"contract-symbol":[{family:"contract",subtype:"uses-contract-symbol"}],import:[{family:"identity",subtype:"imports"}],reference:[{family:"identity",subtype:"references"}]},xN={"structural-membership":[{family:"identity",subtype:"contains"}],"boundary-observation":[{family:"identity",subtype:"owns-runtime-observation"}],"external-import":[{family:"identity",subtype:"imports-external"}]};function gv(e){if(e.kind!=="runtime-boundary")return hv(CN[e.kind]);let t=e.fromBoundaryParticipant?.protocol??e.toBoundaryParticipant?.protocol,n={crossesRuntimeBoundary:!0,...t?{protocol:t}:{},...e.runtimeBoundaryKey?{runtimeKey:e.runtimeBoundaryKey}:{}},r=[{family:"control",subtype:"runtime-handoff",context:n}];return e.evidence==="runtime-boundary:carrier.discriminator"&&(r.push({family:"control",subtype:"discriminator-dispatch",context:{...n},attributes:{joinRule:"carrier.discriminator",...e.fromBoundaryParticipant?.action?{producerAction:e.fromBoundaryParticipant.action}:{},...e.toBoundaryParticipant?.action?{consumerAction:e.toBoundaryParticipant.action}:{}}}),r.push({family:"data",subtype:"serialized-discriminator-transfer",context:{...n},attributes:{joinRule:"carrier.discriminator"}})),e.evidence==="runtime-boundary:queue.address"&&e.fromBoundaryParticipant?.action==="queue.send"&&e.toBoundaryParticipant?.action==="queue.consume"&&r.push({family:"temporal",subtype:"enqueue-before-consume",context:{...n},attributes:{producerAction:e.fromBoundaryParticipant.action,consumerAction:e.toBoundaryParticipant.action,retryPolicy:"unknown"}}),r}function cc(e){return hv(xN[e])}function hv(e){return e.map(t=>({...t,...t.context?{context:{...t.context}}:{},...t.attributes?{attributes:{...t.attributes}}:{}}))}import{join as VN}from"path";import{createRequire as RN}from"module";import{resolve as Go}from"path";var EN=RN(import.meta.url),qo;function bv(e,t,n){let r=IN();if(!r)return kd("The TypeScript compiler runtime is unavailable.");let i=wN(r,e,t),o=i.getSourceFile(Go(t))??i.getSourceFile(t);if(!o)return kd(`The TypeScript compiler did not materialize ${t}.`);let s={ts:r,sourceFile:o,checker:i.getTypeChecker(),points:new Map,edges:new Map,unsupported:new Set,nextCfgId:0},a=PN(r,o,n);if(a.length===0)return kd("No function-like construct intersects the selected source range.");let c=new Map(a.map(d=>[d,DN(o,d)])),l=a.map(d=>TN(s,d,MN(r,d,c),c.get(d)));for(let d of l)kN(s,d),_N(s,d),$N(s,d);HN(s,l);let u=[...s.unsupported].sort();return{points:[...s.points.values()].map(({node:d,...m})=>m).sort(WN),edges:[...s.edges.values()].sort((d,m)=>d.id.localeCompare(m.id)),coverage:{status:u.length===0?"complete":"partial",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:u}}}function IN(){if(qo!==void 0)return qo;try{qo=EN("typescript")}catch{qo=Vs()?.ts??null}return qo}function wN(e,t,n){let r=Go(n),i={target:e.ScriptTarget.ESNext,module:e.ModuleKind.NodeNext,moduleResolution:e.ModuleResolutionKind.NodeNext,skipLibCheck:!0,noResolve:!0},o=e.createSourceFile(r,t,i.target,!0,LN(e,r)),s=e.createCompilerHost(i,!0),a=s.getSourceFile.bind(s),c=s.readFile.bind(s),l=s.fileExists.bind(s);return s.getSourceFile=(u,d,m,p)=>Go(u)===r?o:a(u,d,m,p),s.readFile=u=>Go(u)===r?t:c(u),s.fileExists=u=>Go(u)===r||l(u),e.createProgram([r],i,s)}function LN(e,t){return/\.tsx$/iu.test(t)?e.ScriptKind.TSX:/\.[cm]?js$/iu.test(t)?e.ScriptKind.JS:/\.jsx$/iu.test(t)?e.ScriptKind.JSX:e.ScriptKind.TS}function PN(e,t,n){let r=[],i=o=>{if(Sv(e,o)){let s=t.getLineAndCharacterOfPosition(o.getStart(t)).line,a=t.getLineAndCharacterOfPosition(o.getEnd()).line;(!n||s<=n.endLine&&a>=n.startLine)&&r.push(o)}o.forEachChild(i)};return t.forEachChild(i),r.sort((o,s)=>o.getStart(t)-s.getStart(t))}function Sv(e,t){return e.isFunctionLike(t)&&"body"in t&&t.body!==void 0}function DN(e,t){return`callable:${encodeURIComponent(e.fileName)}:${t.getStart(e)}:${t.getEnd()}`}function MN(e,t,n){for(let r=t.parent;r;r=r.parent)if(Sv(e,r)&&n.has(r))return n.get(r);return null}function TN(e,t,n,r){let i=new Map,o=ze(e,i,"exit",null),s=t.body,a=o.id;if(s&&e.ts.isBlock(s))a=Ad(e,i,[...s.statements],o.id,{breakTarget:null,continueTarget:null});else if(s){let l=ze(e,i,"statement",s);ve(i,l.id,o.id),a=l.id}let c=ze(e,i,"entry",t);return ve(i,c.id,a),{id:r,node:t,parentId:n,cfg:i,entryId:c.id,exitId:o.id}}function Ad(e,t,n,r,i){let o=r;for(let s=n.length-1;s>=0;s-=1)o=jr(e,t,n[s],o,i);return o}function jr(e,t,n,r,i){let o=e.ts;if(o.isBlock(n))return Ad(e,t,[...n.statements],r,i);if(o.isIfStatement(n)){let a=ze(e,t,"predicate",n.expression),c=jr(e,t,n.thenStatement,r,i),l=n.elseStatement?jr(e,t,n.elseStatement,r,i):r;return ve(t,a.id,c),ve(t,a.id,l),a.id}if(o.isWhileStatement(n)){let a=ze(e,t,"predicate",n.expression),c=jr(e,t,n.statement,a.id,{breakTarget:r,continueTarget:a.id});return ve(t,a.id,c),ve(t,a.id,r),a.id}if(o.isDoStatement(n)){let a=ze(e,t,"predicate",n.expression),c=jr(e,t,n.statement,a.id,{breakTarget:r,continueTarget:a.id});return ve(t,a.id,c),ve(t,a.id,r),c}if(o.isForStatement(n)){let a=ze(e,t,"predicate",n.condition??n),c=n.incrementor?ze(e,t,"statement",n.incrementor):null;c&&ve(t,c.id,a.id);let l=c?.id??a.id,u=jr(e,t,n.statement,l,{breakTarget:r,continueTarget:l});if(ve(t,a.id,u),n.condition&&ve(t,a.id,r),!n.initializer)return a.id;let d=ze(e,t,"statement",n.initializer);return ve(t,d.id,a.id),d.id}if(o.isForInStatement(n)||o.isForOfStatement(n)){e.unsupported.add("for-in/for-of iterator assignment is conservatively represented without iterable element flow.");let a=ze(e,t,"predicate",n.expression),c=ze(e,t,"statement",n.initializer),l=jr(e,t,n.statement,a.id,{breakTarget:r,continueTarget:a.id});return ve(t,a.id,c.id),ve(t,a.id,r),ve(t,c.id,l),a.id}if(o.isSwitchStatement(n)){e.unsupported.add("switch fallthrough is represented conservatively; discriminant-to-case value refinement is unsupported.");let a=ze(e,t,"predicate",n.expression),c=r,l=[];for(let u=n.caseBlock.clauses.length-1;u>=0;u-=1){let d=n.caseBlock.clauses[u];c=Ad(e,t,[...d.statements],c,{...i,breakTarget:r}),l.push(c)}for(let u of l)ve(t,a.id,u);return ve(t,a.id,r),a.id}if(o.isReturnStatement(n)||o.isThrowStatement(n)){let a=ze(e,t,"statement",n),c=[...t.values()].find(l=>l.kind==="exit");return ve(t,a.id,c.id),a.id}if(o.isBreakStatement(n)){let a=ze(e,t,"statement",n);return i.breakTarget||e.unsupported.add("A break statement could not be attached to a structured target."),ve(t,a.id,i.breakTarget??r),a.id}if(o.isContinueStatement(n)){let a=ze(e,t,"statement",n);return i.continueTarget||e.unsupported.add("A continue statement could not be attached to a structured target."),ve(t,a.id,i.continueTarget??r),a.id}if(o.isTryStatement(n)){e.unsupported.add("Exceptional control-flow and finally completion are not included in the local compiler CFG.");let a=ze(e,t,"statement",n);return a.invalidatesAllDefinitions=!0,ve(t,a.id,r),a.id}let s=ze(e,t,"statement",n);return ve(t,s.id,r),s.id}function ze(e,t,n,r){let i={id:`cfg:${e.nextCfgId++}`,kind:n,ast:r,successors:new Set,predecessors:new Set,definitions:[],uses:[],displayPoint:null,invalidatesAllDefinitions:!1};return t.set(i.id,i),i}function ve(e,t,n){e.get(t).successors.add(n),e.get(n).predecessors.add(t)}function kN(e,t){let n=t.cfg.get(t.entryId);for(let r of t.node.parameters){let i=Hr(e,r.name);if(!i){e.unsupported.add("Destructured parameter definition-use is not implemented.");continue}n.definitions.push({point:Ur(e,i.node,"parameter-definition",i.symbolKey,i.name,t.id),rhsUseIds:[]})}for(let r of t.cfg.values())!r.ast||r.kind==="entry"||r.kind==="exit"||(r.kind==="predicate"&&(r.displayPoint=Ur(e,r.ast,"predicate",null,"predicate",t.id)),AN(e,t,r,r.ast),!r.displayPoint&&r.definitions.length===0&&r.uses.length===0&&(r.displayPoint=Ur(e,r.ast,"statement",null,qN(e,r.ast),t.id)))}function AN(e,t,n,r){let i=e.ts;if(i.isTryStatement(r))return;let o=s=>{if(!(s!==r&&i.isFunctionLike(s))){if(i.isVariableDeclaration(s)){let a=s.initializer?lc(e,t.id,s.initializer,n):[];n.uses.push(...a);let c=Hr(e,s.name);c?n.definitions.push({point:Ur(e,c.node,"definition",c.symbolKey,c.name,t.id),rhsUseIds:a.map(l=>l.point.id)}):(n.invalidatesAllDefinitions=!0,e.unsupported.add("Destructured variable reaching definitions are not implemented."));return}if(i.isBinaryExpression(s)&&xv(i,s.operatorToken.kind)){let a=lc(e,t.id,s.right,n);s.operatorToken.kind!==i.SyntaxKind.EqualsToken&&a.push(...lc(e,t.id,s.left,n)),n.uses.push(...a);let c=Hr(e,s.left);c?n.definitions.push({point:Ur(e,c.node,"definition",c.symbolKey,c.name,t.id),rhsUseIds:a.map(l=>l.point.id)}):(n.invalidatesAllDefinitions=!0,e.unsupported.add("Dynamic or destructured assignment targets are not included in reaching definitions."));return}if((i.isPrefixUnaryExpression(s)||i.isPostfixUnaryExpression(s))&&(s.operator===i.SyntaxKind.PlusPlusToken||s.operator===i.SyntaxKind.MinusMinusToken)){let a=lc(e,t.id,s.operand,n);n.uses.push(...a);let c=Hr(e,s.operand);c&&n.definitions.push({point:Ur(e,c.node,"definition",c.symbolKey,c.name,t.id),rhsUseIds:a.map(l=>l.point.id)});return}if(!(i.isFunctionDeclaration(s)||i.isClassDeclaration(s)||i.isInterfaceDeclaration(s))){if(vv(e,s)){let a=Cv(e,t.id,s);a&&n.uses.push(a),i.isPropertyAccessExpression(s)&&o(s.expression);return}s.forEachChild(o)}}};o(r),n.uses=Rv(n.uses)}function lc(e,t,n,r){let i=[],o=s=>{if(!e.ts.isFunctionLike(s)){if(e.ts.isBinaryExpression(s)&&xv(e.ts,s.operatorToken.kind)){r.invalidatesAllDefinitions=!0,e.unsupported.add("Nested assignment expressions are not included in ordered local definition-use flow."),s.operatorToken.kind!==e.ts.SyntaxKind.EqualsToken&&o(s.left),o(s.right);return}if(vv(e,s)){let a=Cv(e,t,s);a&&i.push(a),e.ts.isPropertyAccessExpression(s)&&o(s.expression);return}s.forEachChild(o)}};return o(n),Rv(i)}function vv(e,t){if(e.ts.isPropertyAccessExpression(t))return!0;if(!e.ts.isIdentifier(t))return!1;let n=t.parent;return!(e.ts.isPropertyAccessExpression(n)&&n.name===t||"name"in n&&n.name===t&&FN(e.ts,n)||e.ts.isPropertyAssignment(n)&&n.name===t||e.ts.isBindingElement(n)&&n.propertyName===t||e.ts.isLabeledStatement(n)||e.ts.isBreakOrContinueStatement(n)||NN(e.ts,t))}function FN(e,t){return e.isVariableDeclaration(t)||e.isParameter(t)||e.isFunctionDeclaration(t)||e.isFunctionExpression(t)||e.isClassDeclaration(t)||e.isMethodDeclaration(t)||e.isPropertyDeclaration(t)||e.isInterfaceDeclaration(t)||e.isTypeAliasDeclaration(t)||e.isImportSpecifier(t)||e.isImportClause(t)||e.isNamespaceImport(t)}function NN(e,t){for(let n=t.parent;n;n=n.parent){if(e.isExpression(n)||e.isStatement(n)||e.isSourceFile(n))return!1;if(e.isTypeNode(n))return!0}return!1}function Cv(e,t,n){let r=Hr(e,n);return r?{point:Ur(e,r.node,"use",r.symbolKey,r.name,t),property:e.ts.isPropertyAccessExpression(n)}:null}function Hr(e,t){let n=e.ts;if(n.isIdentifier(t)){let r=yv(e,t);return r?{node:t,symbolKey:r,name:t.text}:null}if(n.isPropertyAccessExpression(t)){let r=yv(e,t.name);return r?{node:t,symbolKey:r,name:t.getText(e.sourceFile)}:null}return n.isParenthesizedExpression(t)||n.isAsExpression(t)||n.isTypeAssertionExpression(t)||n.isNonNullExpression(t)?Hr(e,t.expression):((n.isArrayLiteralExpression(t)||n.isObjectLiteralExpression(t))&&e.unsupported.add("Heap aggregate identity and destructured assignment are not included in local points-to flow."),null)}function yv(e,t){let n=e.checker.getSymbolAtLocation(t);if(!n)return null;if((n.flags&e.ts.SymbolFlags.Alias)!==0)try{n=e.checker.getAliasedSymbol(n)}catch{}let r=n.valueDeclaration??n.declarations?.[0];return r?`symbol:${encodeURIComponent(r.getSourceFile().fileName)}:${r.getStart()}:${n.getName()}`:`symbol:${n.getName()}`}function Ur(e,t,n,r,i,o){let s=t.getStart(e.sourceFile),a=t.getEnd(),c=e.sourceFile.getLineAndCharacterOfPosition(s),l=`flow-point:${encodeURIComponent(e.sourceFile.fileName)}:${s}:${a}:${n}:${encodeURIComponent(r??i)}`,u=e.points.get(l);if(u)return u;let d={id:l,kind:n,name:i,symbolKey:r,callableId:o,start:s,end:a,line:c.line,column:c.character,node:t};return e.points.set(l,d),d}function _N(e,t){let n=[...t.cfg.values()].flatMap(c=>c.definitions),r=new Map(n.map(c=>[c.point.id,c])),i=ON(n),o=new Map,s=new Map;for(let c of t.cfg.values())o.set(c.id,new Set),s.set(c.id,new Set);let a=!0;for(;a;){a=!1;for(let c of t.cfg.values()){let l=zN([...c.predecessors].map(m=>s.get(m))),u=new Set(l);c.invalidatesAllDefinitions&&u.clear();let d=BN(c.definitions);for(let m of d){for(let p of i.get(m.point.symbolKey)??[])u.delete(p.point.id);u.add(m.point.id)}Fd(o.get(c.id),l)||(o.set(c.id,l),a=!0),Fd(s.get(c.id),u)||(s.set(c.id,u),a=!0)}}for(let c of t.cfg.values()){let l=o.get(c.id);for(let u of c.uses){let d=c.definitions.filter(p=>p.point.symbolKey===u.point.symbolKey&&p.point.start<u.point.start&&!p.rhsUseIds.includes(u.point.id)).sort((p,f)=>f.point.start-p.point.start)[0],m=d?[d.point.id]:l;for(let p of m){let f=r.get(p);f.point.symbolKey===u.point.symbolKey&&zo(e,"reaching-definition",f.point.id,u.point.id,"exact","A CFG path reaches this use without an intervening definition.")}}for(let u of c.definitions)for(let d of u.rhsUseIds)zo(e,"value-source",d,u.point.id,"exact","This right-hand-side use supplies the new definition.")}}function ON(e){let t=new Map;for(let n of e){if(!n.point.symbolKey)continue;let r=t.get(n.point.symbolKey)??[];r.push(n),t.set(n.point.symbolKey,r)}return t}function BN(e){let t=new Map;for(let n of e)n.point.symbolKey&&t.set(n.point.symbolKey,n);return[...t.values()]}function $N(e,t){let n=jN(t);for(let r of t.cfg.values()){if(r.successors.size<2||!r.displayPoint)continue;let i=n.get(r.id);for(let o of r.successors)for(let s of n.get(o)??[]){if(i.has(s)||s===t.exitId)continue;let a=t.cfg.get(s),c=[...a.definitions.map(l=>l.point),...a.uses.map(l=>l.point),...a.displayPoint?[a.displayPoint]:[]];for(let l of GN(c))zo(e,"control-dependence",r.displayPoint.id,l.id,"exact","The target postdominates a branch successor but does not postdominate the predicate.")}}}function jN(e){let t=[...e.cfg.keys()],n=new Set(t),r=new Map;for(let o of t)r.set(o,o===e.exitId?new Set([o]):new Set(n));let i=!0;for(;i;){i=!1;for(let o of e.cfg.values()){if(o.id===e.exitId)continue;let s=[...o.successors].map(c=>r.get(c)),a=new Set([o.id,...KN(s)]);Fd(r.get(o.id),a)||(r.set(o.id,a),i=!0)}}return r}function HN(e,t){let n=new Map(t.map(s=>[s.id,s.parentId])),r=t.flatMap(s=>[...s.cfg.values()].flatMap(a=>a.definitions.map(c=>c.point))),i=new Map;for(let s of r){if(!s.symbolKey)continue;let a=i.get(s.symbolKey)??[];a.push(s),i.set(s.symbolKey,a)}let o=new Set([...e.edges.values()].filter(s=>s.kind==="reaching-definition").map(s=>s.toPointId));for(let s of t)for(let a of[...s.cfg.values()].flatMap(c=>c.uses)){if(!a.point.symbolKey||o.has(a.point.id))continue;let c=i.get(a.point.symbolKey)??[];for(let l of c)UN(l.callableId,a.point.callableId,n)?zo(e,"closure-capture",l.id,a.point.id,"candidate","Compiler identity proves the captured binding, but invocation order can select among outer definitions."):a.property&&zo(e,"field-definition-to-use",l.id,a.point.id,"candidate","Compiler identity matches the field; cross-callable receiver and execution order remain unresolved.")}[...e.edges.values()].some(s=>s.kind==="closure-capture")&&e.unsupported.add("Closure capture identity is known, but invocation order and intervening writes remain candidate flow."),[...e.edges.values()].some(s=>s.kind==="field-definition-to-use")&&e.unsupported.add("Cross-callable field flow lacks receiver points-to and invocation-order analysis.")}function UN(e,t,n){for(let r=n.get(t)??null;r;r=n.get(r)??null)if(r===e)return!0;return!1}function zo(e,t,n,r,i,o){let s=`local-flow-edge:${t}:${encodeURIComponent(n)}:${encodeURIComponent(r)}`;e.edges.set(s,{id:s,kind:t,fromPointId:n,toPointId:r,strength:i,reason:o})}function xv(e,t){return t>=e.SyntaxKind.FirstAssignment&&t<=e.SyntaxKind.LastAssignment}function qN(e,t){let n=t.getText(e.sourceFile).replace(/\s+/gu," ").trim();return n.length>80?`${n.slice(0,77)}...`:n||e.ts.SyntaxKind[t.kind]||"statement"}function Rv(e){return[...new Map(e.map(t=>[t.point.id,t])).values()]}function GN(e){return[...new Map(e.map(t=>[t.id,t])).values()]}function zN(e){return new Set(e.flatMap(t=>[...t]))}function KN(e){return e.length===0?new Set:new Set([...e[0]].filter(t=>e.slice(1).every(n=>n.has(t))))}function Fd(e,t){return e.size===t.size&&[...e].every(n=>t.has(n))}function WN(e,t){return e.start-t.start||e.kind.localeCompare(t.kind)||e.id.localeCompare(t.id)}function kd(e){return{points:[],edges:[],coverage:{status:"unsupported",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:[e]}}}var YN=Fn("typescript-local-flow",{clearGroups:["whole-project","source-file","semantic-provider"]});function Nd(e,t,n,r){if(!Un(t))return null;let i=`${t}\0${n}\0${r}`;return YN.get(e,i,()=>{let o=W(e,t);return o?bv(o,VN(e.config.projectRoot,t),{startLine:n,endLine:r}):{points:[],edges:[],coverage:{status:"unsupported",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:[`Current source is unavailable for ${t}.`]}}})}function JN(e,t=new Map){let n=new Map,r=new Map,i=[];for(let o of e.transfers){if(!e.caller)continue;let s=uc(e.caller,o.callerPosition),a=uc(e.callee,o.calleePosition);Ko(n,s),Ko(n,a),Od(r,e.caller,s),Od(r,e.callee,a);let c=nt("edge","data-transfer",o.proof.file,String(o.proof.startLine),String(o.callerPosition),String(o.calleePosition));r.set(c,{id:c,kind:"data-transfer",fromNodeId:s.id,toNodeId:a.id,directed:!0,disposition:"folded",semantics:[{family:"data",subtype:"argument-to-parameter",attributes:{argumentText:o.argumentText,callerPosition:o.callerPosition,calleePosition:o.calleePosition}}],evidence:[{method:"compiler-callsite-direct-parameter-transfer",strength:"exact",identity:`${e.caller.symbol}:${o.callerPosition} -> ${e.callee.symbol}:${o.calleePosition}`,location:{file:o.proof.file,line:o.proof.startLine,endLine:o.proof.endLine}}]})}return e.unknown.forEach((o,s)=>{let a=uc(e.callee,o.calleePosition);Ko(n,a),Od(r,e.callee,a);let c=t.get(o.calleePosition);if(c&&a_(c)){s_(r,n,e,o.calleePosition,o.argumentText,c);return}let l=i_(e,o.calleePosition,o.argumentText);Ko(n,l);let u=nt("edge","data-transfer-unsupported",o.proof.file,String(o.proof.startLine),String(o.calleePosition),String(s));r.set(u,{id:u,kind:"data-transfer",fromNodeId:l.id,toNodeId:a.id,directed:!0,disposition:"unsupported",semantics:[{family:"data",subtype:"argument-to-parameter",attributes:{argumentText:o.argumentText,calleePosition:o.calleePosition}}],evidence:[{method:"compiler-callsite-argument-expression",strength:"exact",identity:o.argumentText,location:{file:o.proof.file,line:o.proof.startLine,endLine:o.proof.endLine}}]}),i.push({id:nt("frontier","data-transfer",u),kind:"data-transfer",direction:"unresolved",fromNodeIds:[l.id],edgeIds:[u],memberNodeIds:[a.id],memberCount:1,disposition:"unsupported",reason:c?.derivation.rule??o.reason,expansion:null})}),{nodes:[...n.values()],edges:[...r.values()],frontiers:i,blindSpots:[]}}function Iv(e,t,n=[]){let r=wv(),i=new Map,o=new Set;for(let s of t){if(s.kind!=="call"||!s.fromSymbol||!s.toSymbol||s.line===null)continue;let a=r_(i,e,s.toFile,s.toSymbol);if(!a)continue;let c=Uf(e,a),l=c.sites.filter(g=>g.file===s.fromFile&&g.startLine<=s.line&&g.endLine>=s.line&&g.caller?.symbol===s.fromSymbol);if(l.length!==1){let g=c.unresolved.find(h=>h.file===s.fromFile&&h.line===s.line);g&&r.blindSpots.push(`Parameter flow unresolved at ${s.fromFile}:${s.line+1}: ${g.reason}.`);continue}let u=l[0],d=`${u.file}\0${u.callNode.startIndex}\0${u.callNode.endIndex}\0${a.symbol}`;if(o.has(d))continue;o.add(d);let m=qf(e,u),p=J(e,u.file)?.rootNode,f=new Map;if(p)for(let g of m.unknown){let h=Hf({db:e,file:u.file,root:p},u.arguments[g.calleePosition]);h&&f.set(g.calleePosition,h)}Ev(r,JN(m,f)),m.caller&&t_(u.callNode)&&n_(r,m,u.callNode)}for(let s of n){if(!s.location||!["source-construct","symbol"].includes(s.kind))continue;let a=s.location.endLine??s.location.line,c=Nd(e,s.location.file,s.location.line,a);if(c){Ev(r,XN(s,c.points,c.edges));for(let l of c.coverage.unsupported)r.blindSpots.push(`TypeScript local flow is partial for ${s.location.file}:${s.location.line+1}-${a+1}: ${l} Recover with: scip-query inspect --at '${s.location.file}:${s.location.line+1}-${a+1}' --view behavior.`)}}return r.blindSpots=[...new Set(r.blindSpots)].sort(),r}function XN(e,t,n){let r=wv(),i=new Map,o=new Map,s=new Map,a=e.location.file;for(let c of t){let l=QN(e,a,c);s.set(c.id,l.id),i.set(l.id,l),ZN(o,e,l)}for(let c of n){let l=s.get(c.fromPointId),u=s.get(c.toPointId);if(!l||!u)continue;let d=e_(c),m=nt("edge","typescript-local-flow",a,c.id);o.set(m,{id:m,kind:c.kind==="control-dependence"?"control-dependence":"data-transfer",fromNodeId:l,toNodeId:u,directed:!0,disposition:"folded",semantics:[d],evidence:[{method:"typescript-compiler-cfg-reaching-definitions",strength:c.strength,identity:c.reason,location:i.get(l)?.location??e.location}]})}return r.nodes=[...i.values()],r.edges=[...o.values()],r}function QN(e,t,n){return{id:nt("local-flow-point",t,String(n.start),String(n.end),n.kind,n.symbolKey??n.name),kind:n.kind==="parameter-definition"||n.kind==="definition"?"local-definition":n.kind==="use"?"local-use":n.kind==="predicate"?"control-predicate":"local-statement",label:n.name,disposition:"folded",location:{file:t,line:n.line,endLine:n.line},anchorIds:[],attributes:{ownerNodeId:e.id,pointKind:n.kind,callableId:n.callableId,symbolKey:n.symbolKey,column:n.column}}}function ZN(e,t,n){let r=nt("edge","local-flow-owner",t.id,n.id);e.has(r)||e.set(r,{id:r,kind:"local-flow-owner",fromNodeId:t.id,toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:"contains"}],evidence:[{method:"typescript-compiler-local-flow-owner",strength:"exact",identity:t.id,location:n.location}]})}function e_(e){switch(e.kind){case"reaching-definition":return{family:"data",subtype:"definition-to-use"};case"value-source":return{family:"data",subtype:"value-to-definition"};case"closure-capture":return{family:"data",subtype:"closure-capture"};case"field-definition-to-use":return{family:"data",subtype:"field-definition-to-use"};case"control-dependence":return{family:"control",subtype:"control-dependence"}}}function t_(e){let t=e;for(;t.parent&&["await_expression","yield_expression","parenthesized_expression","as_expression","type_assertion"].includes(t.parent.type);)t=t.parent;return t.parent!==null&&t.parent.type!=="expression_statement"}function n_(e,t,n){if(!t.caller)return;let r={id:nt("call-result",t.call.file,String(n.startIndex),String(n.endIndex),t.callee.symbol),kind:"call-result",label:`result of ${t.callee.leaf}`,disposition:"folded",location:{file:t.call.file,line:t.call.startLine,endLine:t.call.endLine},anchorIds:[],attributes:{calleeSymbol:t.callee.symbol,callerSymbol:t.caller.symbol}},i=nt("edge","return-to-call-result",t.callee.symbol,r.id),o=nt("edge","call-result-owner",t.caller.symbol,r.id);e.nodes.push(r),e.edges.push({id:i,kind:"data-transfer",fromNodeId:Bd(t.callee.symbol),toNodeId:r.id,directed:!0,disposition:"folded",semantics:[{family:"data",subtype:"return-to-call-result"}],evidence:[{method:"compiler-callsite-used-result",strength:"exact",identity:`${t.callee.symbol} -> ${t.caller.symbol}`,location:r.location}]},{id:o,kind:"call-result-owner",fromNodeId:Bd(t.caller.symbol),toNodeId:r.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:"contains-call-result"}],evidence:[{method:"compiler-call-result-owner",strength:"exact",identity:t.caller.symbol,location:r.location}]})}function wv(){return{nodes:[],edges:[],frontiers:[],blindSpots:[]}}function Ev(e,t){_d(e.nodes,t.nodes),_d(e.edges,t.edges),_d(e.frontiers,t.frontiers),e.blindSpots.push(...t.blindSpots)}function _d(e,t){let n=new Set(e.map(r=>r.id));for(let r of t)n.has(r.id)||(n.add(r.id),e.push(r))}function r_(e,t,n,r){let i=`${n}\0${r}`,o=e.get(i);if(o!==void 0)return o;let s=U(t,n).find(a=>a.symbol===r)??null;return e.set(i,s),s}function uc(e,t){return{id:u_(e.symbol,t),kind:"parameter",label:`${e.leaf} parameter ${t}`,disposition:"folded",location:{file:e.relativePath,line:e.startLine,endLine:e.endLine},anchorIds:[],attributes:{ownerSymbol:e.symbol,position:t}}}function i_(e,t,n){return{id:nt("argument-expression",e.call.file,String(e.call.startLine),String(e.call.endLine),String(t)),kind:"argument-expression",label:n,disposition:"unsupported",location:{file:e.call.file,line:e.call.startLine,endLine:e.call.endLine},anchorIds:[],attributes:{calleeSymbol:e.callee.symbol,position:t}}}function o_(e,t,n){return{id:nt("static-value",e.call.file,String(e.call.startLine),String(e.call.endLine),String(t)),kind:"static-value",label:n.value,disposition:"folded",location:{file:e.call.file,line:e.call.startLine,endLine:e.call.endLine},anchorIds:[],attributes:{value:n.value,precision:n.precision,evidence:n.evidence,termKind:n.term.kind,derivationRule:n.derivation.rule}}}function s_(e,t,n,r,i,o){let s=o_(n,r,o),a=uc(n.callee,r);Ko(t,s);let c=nt("edge","static-value-transfer",n.call.file,String(n.call.startLine),String(r));e.set(c,{id:c,kind:"data-transfer",fromNodeId:s.id,toNodeId:a.id,directed:!0,disposition:"folded",semantics:[{family:"data",subtype:c_(o),attributes:{argumentText:i,calleePosition:r,value:o.value,precision:o.precision,derivationRule:o.derivation.rule}}],evidence:l_(o,n)})}function a_(e){return e.derivation.kind!=="heuristic"&&e.precision!=="symbolic"&&e.precision!=="unknown"}function c_(e){return e.derivation.rule==="bounded-call-return"?"return-to-parameter":e.derivation.rule==="member-constant"||e.term.kind==="property"?"property-to-parameter":"constant-to-parameter"}function l_(e,t){return(e.derivation.sourceSpans.length>0?e.derivation.sourceSpans:[t.call]).map(r=>({method:`static-value:${e.derivation.rule}`,strength:e.derivation.kind==="direct"?"exact":"derived",identity:e.derivation.inputFactIds.join(",")||e.value,location:{file:r.file,line:r.startLine,endLine:r.endLine}}))}function Ko(e,t){e.has(t.id)||e.set(t.id,t)}function Od(e,t,n){let r=nt("edge","parameter-owner",t.symbol,n.id);e.has(r)||e.set(r,{id:r,kind:"parameter-owner",fromNodeId:Bd(t.symbol),toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:"contains"}],evidence:[{method:"compiler-parameter-owner",strength:"exact",identity:t.symbol,location:{file:t.relativePath,line:t.startLine,endLine:t.endLine}}]})}function u_(e,t){return nt("parameter",e,String(t))}function Bd(e){return nt("symbol",e)}function nt(...e){return e.map(t=>encodeURIComponent(t)).join(":")}function Lv(e,t){let n=new Map,r=new Map,i=new Map,o=new Set;for(let s of t){if(!s.location||!["source-construct","symbol"].includes(s.kind))continue;let a=s.location.endLine??s.location.line,c=Ig(e,s.location.file,s.location.line,a);if(!c){o.add(`Control dependence unavailable for ${s.location.file}:${s.location.line+1}-${a+1}: no supported syntax tree or covering construct.`);continue}for(let l of c.facts){let u=$d(s,l.controller),d=$d(s,l.outcome);n.set(u.id,u),n.set(d.id,d),d_(r,s,u);let m=qr("edge","control-dependence",u.id,d.id,l.subtype);r.set(m,{id:m,kind:"control-dependence",fromNodeId:u.id,toNodeId:d.id,directed:!0,disposition:"folded",semantics:[{family:"control",subtype:l.subtype,attributes:{...l.attributes}}],evidence:[{method:"parser-control-dependence",strength:"exact",identity:`${s.location.file}:${l.controller.startLine+1}-${l.outcome.startLine+1}`,location:{file:s.location.file,line:l.controller.startLine,endLine:l.controller.endLine}}]})}for(let l of c.terminals){let u=$d(s,l);n.set(u.id,u);let d=l.label.startsWith("throw")||l.label.startsWith("raise")?"throw":"return",m=qr("edge","control-terminal",s.id,u.id,d);r.set(m,{id:m,kind:"control-terminal",fromNodeId:s.id,toNodeId:u.id,directed:!0,disposition:"folded",semantics:[{family:"control",subtype:d==="throw"?"throws":"returns"}],evidence:[{method:"parser-terminal-statement",strength:"exact",identity:l.label,location:{file:s.location.file,line:l.startLine,endLine:l.endLine}}]})}for(let l of c.unsupported){let u=qr("control-unsupported",s.location.file,String(l.startLine),String(l.endLine),l.reason);n.set(u,{id:u,kind:"control-unsupported",label:l.reason,disposition:"unsupported",location:{file:s.location.file,line:l.startLine,endLine:l.endLine},anchorIds:[],attributes:{ownerNodeId:s.id}});let d=qr("edge","control-unsupported",s.id,u);r.set(d,{id:d,kind:"control-dependence",fromNodeId:s.id,toNodeId:u,directed:!0,disposition:"unsupported",semantics:[{family:"control",subtype:"unresolved-control-construct"}],evidence:[{method:"parser-control-construct",strength:"exact",identity:l.reason,location:{file:s.location.file,line:l.startLine,endLine:l.endLine}}]});let m=qr("frontier","control-dependence",u);i.set(m,{id:m,kind:"control-dependence",direction:"unresolved",fromNodeIds:[s.id],edgeIds:[d],memberNodeIds:[u],memberCount:1,disposition:"unsupported",reason:l.reason,expansion:null})}}return{nodes:[...n.values()],edges:[...r.values()],frontiers:[...i.values()],blindSpots:[...o].sort()}}function $d(e,t){let n=e.location.file;return{id:qr(`control-${t.kind}`,n,String(t.startLine),String(t.endLine),t.label),kind:`control-${t.kind}`,label:t.label,disposition:"folded",location:{file:n,line:t.startLine,endLine:t.endLine},anchorIds:[],attributes:{ownerNodeId:e.id,constructKind:t.kind,implicit:t.implicit}}}function d_(e,t,n){let r=qr("edge","control-owner",t.id,n.id);e.has(r)||e.set(r,{id:r,kind:"control-owner",fromNodeId:t.id,toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:"contains-control"}],evidence:[{method:"parser-control-owner",strength:"exact",identity:t.id,location:t.location}]})}function qr(...e){return e.map(t=>encodeURIComponent(t)).join(":")}var dc=new Set(["arrow_function","constructor_declaration","function_declaration","function_definition","function_expression","generator_function","generator_function_declaration","function_item","lambda","lambda_expression","method","method_declaration","method_definition"]),Vo=new Set(["block","body","compound_statement","declaration_list","statement_block"]),m_=new Set(["assignment","assignment_expression","augmented_assignment_expression"]),Hd=new Set(["update_expression"]),Tv=new Set(["array_access","element_access_expression","subscript_expression"]),kv=new Set(["attribute","field_access","field_expression","member_access_expression","member_expression","selector_expression"]),p_=new Set(["false","null","null_literal","number","number_literal","string","string_literal","template_string","true"]),f_=new Set(["call_expression","method_invocation","object_creation_expression"]),g_=new Set(["comment","else_clause","formal_parameters","parameters","type_parameters"]);function Av(e,t,n,r){let i=J(e,t);if(!i)return null;let o=R_(i.rootNode,n,r);if(!o)return null;let s=[],a=[],c=[];return Gr(o,l=>{if(m_.has(l.type)||Hd.has(l.type)||Nv(l)){let u=h_(l);u?s.push(u):c.push({family:"state",startLine:l.startPosition.row,endLine:l.endPosition.row,reason:`Mutation target ${tn(l.text)} could not be resolved to an exact source resource.`})}}),Gr(o,l=>{if(!Vo.has(l.type))return;let u=C_(l);for(let d=0;d<u.length-1;d+=1)a.push({from:Wo(u[d]),to:Wo(u[d+1]),subtype:"lexical-successor",synchronizationScope:null,attributes:{sameScope:!0,executionConditional:!0}});for(let d=0;d<u.length;d+=1){let m=u[d],p=I_(m).filter(f=>f.type==="await_expression");for(let f of p){let g=Yo("event",`await ${tn(f.text.replace(/^await\s+/u,""))}`,f);a.push({from:Wo(m),to:g,subtype:"awaits-completion",synchronizationScope:null,attributes:{completionRequired:!0}});let h=u[d+1];h&&a.push({from:g,to:Wo(h),subtype:"await-completion-before",synchronizationScope:null,attributes:{continuationOnly:!0}})}}}),Gr(o,l=>{if(l.type!=="synchronized_statement")return;let u=l.childForFieldName("object")??l.childForFieldName("condition")??l.namedChildren.find(g=>!Vo.has(g.type)),d=l.childForFieldName("body")??l.namedChildren.find(g=>Vo.has(g.type));if(!u||!d){c.push({family:"temporal",startLine:l.startPosition.row,endLine:l.endPosition.row,reason:"Synchronized scope has no structurally resolved monitor or body."});return}let m=tn(u.text).replace(/^\(|\)$/gu,""),p=Yo("lock",m,u),f=E_(d).filter(g=>g.parent!==null&&_v(g));for(let g of x_(f))a.push({from:p,to:Wo(g),subtype:"inside-lock-scope",synchronizationScope:m,attributes:{syntaxNative:!0}})}),{mutations:s,temporal:a,unsupported:c}}function h_(e){let t=Nv(e),n=e.childForFieldName("left")??e.childForFieldName("argument")??(t?e.namedChildren.at(-1)??null:e.namedChildren[0]??null);if(!n)return null;let r=y_(n);if(!r)return null;let i=t?"delete":Hd.has(e.type)||!v_(e,n).startsWith("=")?"update":"assign",o=t||Hd.has(e.type)?null:e.childForFieldName("right");return{event:Yo("event",tn(e.text),e),resource:{kind:"resource",label:r.name,startLine:n.startPosition.row,endLine:n.endPosition.row},operation:i,durabilityClass:"in-memory",recordIdentity:r.recordIdentity,value:o?Yo("value",tn(o.text),o):null,dataSubtype:o?b_(o,e):null}}function y_(e){if(Tv.has(e.type)){let t=e.childForFieldName("object")??e.childForFieldName("array")??e.namedChildren[0]??null,n=e.childForFieldName("index")??e.childForFieldName("subscript")??e.namedChildren[1]??null;return!t||!n?null:{name:`${tn(t.text)}[]`,recordIdentity:tn(n.text)}}return kv.has(e.type)?{name:tn(e.text),recordIdentity:null}:/^(?:identifier|property_identifier|field_identifier)$/u.test(e.type)?{name:tn(e.text),recordIdentity:null}:null}function b_(e,t){return p_.has(e.type)||/(?:integer|float|decimal|boolean|character)_literal$/u.test(e.type)?"constant-to-state":f_.has(e.type)?"return-to-state":kv.has(e.type)||Tv.has(e.type)?"property-to-state":/identifier$/u.test(e.type)?S_(e.text,t)?"captured-value-to-state":"value-to-state":"expression-to-state"}function S_(e,t){let n=jd(t.parent);if(!n||Pv(n,e))return!1;let r=jd(n.parent);for(;r;){if(Pv(r,e))return!0;r=jd(r.parent)}return!1}function jd(e){let t=e;for(;t;){if(dc.has(t.type))return t;t=t.parent}return null}function Pv(e,t){let n=e.childForFieldName("parameters")??e.namedChildren.find(o=>["formal_parameters","parameters"].includes(o.type));if(n&&Dv(n,t))return!0;let r=e.childForFieldName("body")??e.namedChildren.find(o=>Vo.has(o.type));if(!r)return!1;let i=!1;return Fv(r,e,o=>{if(i||!/(?:declarator|declaration|parameter)$/u.test(o.type))return;let s=o.childForFieldName("name")??o.childForFieldName("pattern")??o.namedChildren[0];s&&Dv(s,t)&&(i=!0)}),i}function Dv(e,t){let n=!1;return Gr(e,r=>{/identifier$/u.test(r.type)&&r.text===t&&(n=!0)}),n}function Fv(e,t,n){n(e);for(let r of e.namedChildren)r!==t&&dc.has(r.type)||Fv(r,t,n)}function v_(e,t){let n=e.childForFieldName("right"),r=Math.max(0,t.endIndex-e.startIndex),i=n?Math.max(r,n.startIndex-e.startIndex):e.text.length;return e.text.slice(r,i).trim()}function Nv(e){return(e.type==="delete_expression"||e.type==="unary_expression")&&/^delete\b/u.test(e.text.trim())}function C_(e){return e.namedChildren.filter(t=>_v(t))}function _v(e){return g_.has(e.type)||Vo.has(e.type)?!1:/(?:statement|declaration)$/u.test(e.type)||e.type==="expression_statement"||e.type==="local_variable_declaration"}function x_(e){let t=new Set(e);return e.filter(n=>{let r=n.parent;for(;r;){if(t.has(r))return!1;r=r.parent}return!0})}function Wo(e){return Yo("event",tn(e.text),e)}function Yo(e,t,n){return{kind:e,label:t,startLine:n.startPosition.row,endLine:n.endPosition.row}}function R_(e,t,n){let r=[];return Gr(e,o=>{o.startPosition.row<=t&&o.endPosition.row>=n&&r.push(o)}),r.filter(o=>dc.has(o.type)).sort(Mv)[0]??r.sort(Mv)[0]??null}function Mv(e,t){return e.endIndex-e.startIndex-(t.endIndex-t.startIndex)||e.startIndex-t.startIndex}function E_(e){let t=[];return Gr(e,n=>t.push(n)),t}function I_(e){let t=[],n=r=>{t.push(r);for(let i of r.namedChildren)i!==e&&dc.has(i.type)||n(i)};return n(e),t}function Gr(e,t){t(e);for(let n of e.namedChildren)Gr(n,t)}function tn(e){return e.trim().replace(/\s+/gu," ")}function $v(e,t,n=[]){let r=new Map,i=new Map,o=new Map,s=new Set;for(let a of t){if(!a.location||!["source-construct","symbol"].includes(a.kind))continue;let c=a.location.endLine??a.location.line,l=Av(e,a.location.file,a.location.line,c);if(!l){s.add(`State and temporal analysis unavailable for ${a.location.file}:${a.location.line+1}-${c+1}: no supported syntax tree or covering construct.`);continue}for(let u of l.mutations){let d=pc(a,u.event),m=T_(a,u.resource,u.durabilityClass);if(r.set(d.id,d),r.set(m.id,m),fc(i,a,d,"contains-state-effect"),gc(i,{kind:"state-resource",from:d,to:m,semantics:[{family:"state",subtype:u.operation==="delete"?"deletes-resource":"writes-resource",attributes:{operation:u.operation,durabilityClass:u.durabilityClass,resource:u.resource.label,recordIdentity:u.recordIdentity,transactionMembership:"unknown"}}],method:"parser-state-mutation",identity:u.event.label}),u.value&&u.dataSubtype){let p=pc(a,u.value);r.set(p.id,p),gc(i,{kind:"data-to-state",from:p,to:m,semantics:[{family:"data",subtype:u.dataSubtype,attributes:{operation:u.operation,resource:u.resource.label,recordIdentity:u.recordIdentity,value:u.value.label}}],method:"parser-assignment-value",identity:`${u.value.label} -> ${u.resource.label}`})}}for(let u of l.temporal){let d=pc(a,u.from),m=pc(a,u.to);r.set(d.id,d),r.set(m.id,m),fc(i,a,d,u.from.kind==="lock"?"contains-lock-scope":"contains-event"),fc(i,a,m,"contains-event"),gc(i,{kind:"temporal-order",from:d,to:m,semantics:[{family:"temporal",subtype:u.subtype,context:u.synchronizationScope?{synchronizationScope:u.synchronizationScope}:void 0,attributes:{...u.attributes}}],method:u.subtype==="inside-lock-scope"?"parser-synchronized-scope":"parser-program-order",identity:`${u.from.label} -> ${u.to.label}`})}for(let u of l.unsupported){let d=Ln(`${u.family}-unsupported`,a.location.file,String(u.startLine),String(u.endLine),u.reason);r.set(d,{id:d,kind:`${u.family}-unsupported`,label:u.reason,disposition:"unsupported",location:{file:a.location.file,line:u.startLine,endLine:u.endLine},anchorIds:[],attributes:{ownerNodeId:a.id}});let m=Ln("edge",`${u.family}-unsupported`,a.id,d);i.set(m,{id:m,kind:`${u.family}-unsupported`,fromNodeId:a.id,toNodeId:d,directed:!0,disposition:"unsupported",semantics:[{family:u.family,subtype:`unresolved-${u.family}-construct`}],evidence:[{method:`parser-${u.family}-construct`,strength:"exact",identity:u.reason,location:{file:a.location.file,line:u.startLine,endLine:u.endLine}}]});let p=Ln("frontier",u.family,d);o.set(p,{id:p,kind:u.family,direction:"unresolved",fromNodeIds:[a.id],edgeIds:[m],memberNodeIds:[d],memberCount:1,disposition:"unsupported",reason:u.reason,expansion:null})}}for(let a of t.filter(c=>c.kind==="runtime-boundary-participant")){let c=mc(a,"protocol"),l=mc(a,"action"),u=mc(a,"address")??a.label;!c||!l||!Bv(c,l)||Ov(r,i,a,{observationId:a.id,action:l,strength:"exact",file:a.location?.file??"",line:a.location?.line??0,address:u,protocol:c,role:mc(a,"role")??void 0,resolution:"locally-linked"})}for(let a of n){if(!a.protocol||!Bv(a.protocol,a.action))continue;let c=D_(t,a.file,a.line,a.ownerShortName??null);if(!c){s.add(`State observation ${a.observationId} at ${a.file}:${a.line+1} has no materialized owner node.`);continue}Ov(r,i,c,a)}return{nodes:[...r.values()],edges:[...i.values()],frontiers:[...o.values()],blindSpots:[...s].sort()}}function Ov(e,t,n,r){let i=L_(r),s={id:Ln("runtime-state-event",r.observationId),kind:"runtime-state-event",label:`${r.action} ${i}`,disposition:"folded",location:{file:r.file,line:r.line},anchorIds:[],attributes:{action:r.action,protocol:r.protocol??null,modality:r.modality??null,resolution:r.resolution??null}},a=r.protocol==="database"?"external-durable-intent":"external",c={id:Ln("runtime-state-resource",r.protocol??"unknown",i),kind:"runtime-state-resource",label:i,disposition:"folded",location:{file:r.file,line:r.line},anchorIds:[],attributes:{protocol:r.protocol??null,durabilityClass:a}};e.set(s.id,s),e.set(c.id,c),fc(t,n,s,"contains-runtime-state-effect");let l=w_(r.action);gc(t,{kind:"runtime-state-resource",from:s,to:c,semantics:[{family:"state",subtype:l,context:{crossesRuntimeBoundary:!0,protocol:r.protocol},attributes:{operation:r.action,durabilityClass:a,resource:i,recordIdentity:P_(r),modality:r.modality??null,resolution:r.resolution??null,transactionMembership:"unknown",commitState:r.protocol==="database"?"unknown":null}}],method:`runtime-boundary-${r.strength}`,identity:r.observationId})}function w_(e){return e==="database.read"?"reads-resource":e==="queue.send"?"enqueues-resource":e==="queue.consume"?"consumes-resource":"writes-resource"}function L_(e){return(e.keyParts?.find(n=>["address","resource"].includes(n.name))?.value??e.address)||e.observationId}function P_(e){return e.keyParts?.find(n=>/^(?:id|key|record)$/u.test(n.name))?.value??null}function Bv(e,t){return e==="database"&&["database.read","database.write"].includes(t)||e==="queue"&&["queue.consume","queue.send"].includes(t)}function mc(e,t){let n=e.attributes[t];return typeof n=="string"?n:null}function D_(e,t,n,r){let i=e.filter(s=>s.location?.file===t&&["source-construct","symbol"].includes(s.kind)),o=i.filter(s=>s.location.line<=n&&(s.location.endLine??s.location.line)>=n).sort(M_)[0];if(o)return o;if(r){let s=i.find(a=>a.label===r||a.label.endsWith(`.${r}`)||a.label.includes(r));if(s)return s}return i.length===1?i[0]:null}function M_(e,t){let n=(e.location?.endLine??e.location?.line??0)-(e.location?.line??0),r=(t.location?.endLine??t.location?.line??0)-(t.location?.line??0);return n-r}function pc(e,t){let n=e.location.file;return{id:Ln(`program-${t.kind}`,n,String(t.startLine),String(t.endLine),t.label),kind:`program-${t.kind}`,label:t.label,disposition:"folded",location:{file:n,line:t.startLine,endLine:t.endLine},anchorIds:[],attributes:{ownerNodeId:e.id,constructKind:t.kind}}}function T_(e,t,n){let r=e.location.file;return{id:Ln("program-resource",r,e.id,t.label,n),kind:"program-resource",label:t.label,disposition:"folded",location:{file:r,line:t.startLine,endLine:t.endLine},anchorIds:[],attributes:{ownerNodeId:e.id,durabilityClass:n}}}function fc(e,t,n,r){let i=Ln("edge","program-owner",t.id,n.id,r);e.has(i)||e.set(i,{id:i,kind:"program-owner",fromNodeId:t.id,toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:r}],evidence:[{method:"parser-program-owner",strength:"exact",identity:t.id,location:n.location}]})}function gc(e,t){let n=Ln("edge",t.kind,t.from.id,t.to.id,t.semantics[0].subtype);e.set(n,{id:n,kind:t.kind,fromNodeId:t.from.id,toNodeId:t.to.id,directed:!0,disposition:"folded",semantics:t.semantics,evidence:[{method:t.method,strength:"exact",identity:t.identity,location:t.from.location}]})}function Ln(...e){return e.map(t=>encodeURIComponent(t)).join(":")}var k_=new Set(["control","data","state","temporal"]),hc=new Set(["contains-control","contains-event","contains-lock-scope","contains-state-effect","contains-runtime-state-effect","contains","owns-parameter","owns-runtime-observation"]),qv=new Set(["discriminator-dispatch","result-callback","returns","runtime-handoff","throws"]);function Gv(e,t={}){let n=new Map(e.nodes.map(E=>[E.id,E])),r=$_(e.nodes,t.focusLocations),i=j_(e.edges,t.focusLocations),o=H_(e.edges,i),s=new Set(e.paths.flatMap(E=>E.edgeIds)),a=Pn(e.anchors.filter(E=>E.status==="matched").flatMap(E=>E.nodeIds)),l=e.edges.filter(Uv).filter(E=>A_(E,r,i,s)),u=l.filter(E=>O_(E,r,i,o,n,s)),d=jv(a,u,"forward"),m=__(d,u),p=jv(m,u,"backward"),f=new Set([...d].filter(E=>p.has(E)));for(let E of a)f.add(E);let g=new Set(u.filter(E=>f.has(E.fromNodeId)&&f.has(E.toNodeId)).map(E=>E.id)),h=new Set(f),b=new Set(g);F_(l,h,b,r,i);let S=e.frontiers.filter(E=>q_(E,h)),y=Pn(S.filter(E=>E.disposition==="unsupported").map(E=>E.id)),x=Pn(e.edges.filter(E=>!Uv(E)&&Kv(E)&&U_(E,h)).map(E=>E.id)),v=Pn(S.map(E=>E.id)),C=[];a.length===0&&C.push("No matched anchor node starts the corridor."),m.length===0&&C.push("No proved mechanical outcome is reachable from a matched anchor."),y.length>0&&C.push(`${y.length} unsupported frontier(s) touch the protected corridor.`),x.length>0&&C.push(`${x.length} candidate or unknown edge(s) touch the protected corridor.`);let R=C.length===0?"complete":"incomplete";return{schemaVersion:1,status:R,startNodeIds:a,outcomeNodeIds:m,baseNodeIds:Pn([...f]),baseEdgeIds:Pn([...g]),nodeIds:Pn([...h]),edgeIds:Pn([...b]),accountedFrontierIds:v,unresolvedFrontierIds:y,unresolvedEdgeIds:x,coverage:{protectedNodes:h.size,protectedEdges:b.size,baseNodes:f.size,baseEdges:g.size,accountedFrontiers:v.length,unresolvedFrontiers:y.length,unresolvedEdges:x.length},explanation:R==="complete"?"Every proved anchor-to-outcome path is closed over its material causal facts within reported coverage.":C.join(" ")}}function A_(e,t,n,r){return t===null||e.disposition==="emitted"||r.has(e.id)||n?.has(e.id)===!0?!0:(e.semantics??[]).some(i=>{if(i.family==="identity"&&hc.has(i.subtype))return t.has(e.toNodeId);if(i.family==="contract")return t.has(e.fromNodeId)&&t.has(e.toNodeId);if(i.family==="state")return t.has(e.fromNodeId);if(i.family==="data"||i.family==="temporal")return t.has(e.fromNodeId)||t.has(e.toNodeId);if(i.family==="control"){if(Wv(i))return t.has(e.fromNodeId);if(["returns","throws"].includes(i.subtype))return t.has(e.toNodeId);if(i.subtype==="completion-callback")return t.has(e.fromNodeId)||t.has(e.toNodeId)}return!1})}function F_(e,t,n,r,i){let o=!0;for(;o;){o=!1;for(let s of e)N_(s,t,r,i)&&(n.has(s.id)||(n.add(s.id),o=!0),t.has(s.fromNodeId)||(t.add(s.fromNodeId),o=!0),t.has(s.toNodeId)||(t.add(s.toNodeId),o=!0))}}function N_(e,t,n,r){let i=t.has(e.fromNodeId),o=t.has(e.toNodeId);return!i&&!o?!1:(e.semantics??[]).some(s=>s.family==="identity"?hc.has(s.subtype)&&(o||n===null||n.has(e.toNodeId)):s.family==="contract"?!0:s.family==="state"?i&&(n===null||n.has(e.fromNodeId)):s.family==="temporal"?s.subtype==="lexical-successor"?i&&o:!0:s.family==="data"?o&&(i||n===null||n.has(e.fromNodeId)||r?.has(e.id)===!0):s.family==="control"?zv(s)||["returns","throws"].includes(s.subtype)&&!o&&n!==null&&!n.has(e.toNodeId)?!1:qv.has(s.subtype)||Wv(s)||s.subtype==="completion-callback":!1)}function __(e,t){let n=new Set,r=new Map,i=new Map;for(let o of t)!e.has(o.fromNodeId)||!e.has(o.toNodeId)||(r.set(o.fromNodeId,(r.get(o.fromNodeId)??0)+1),i.set(o.toNodeId,(i.get(o.toNodeId)??0)+1),(o.semantics??[]).some(s=>s.family==="state"||s.family==="control"&&qv.has(s.subtype))&&n.add(o.toNodeId));for(let o of e)(i.get(o)??0)>0&&(r.get(o)??0)===0&&n.add(o);return Pn([...n])}function jv(e,t,n){let r=new Map;for(let s of t){let a=n==="forward"?s.fromNodeId:s.toNodeId,c=n==="forward"?s.toNodeId:s.fromNodeId,l=r.get(a)??[];l.push(c),r.set(a,l)}let i=new Set(e),o=[...e];for(;o.length>0;){let s=o.shift();for(let a of r.get(s)??[])i.has(a)||(i.add(a),o.push(a))}return i}function O_(e,t,n,r,i,o){return(e.semantics??[]).some(s=>e.disposition==="emitted"||o.has(e.id)?!0:s.family==="identity"&&hc.has(s.subtype)?t===null||t.has(e.toNodeId)||r?.has(e.toNodeId)===!0:!k_.has(s.family)||zv(s)?!1:s.family==="control"&&["returns","throws"].includes(s.subtype)&&t!==null?t.has(e.toNodeId):t===null?!0:s.family==="state"?t.has(e.fromNodeId):s.family==="data"?t.has(e.fromNodeId)||t.has(e.toNodeId)||n?.has(e.id)===!0:s.family==="temporal"?s.subtype==="lexical-successor"?t.has(e.fromNodeId)&&t.has(e.toNodeId):t.has(e.fromNodeId)||t.has(e.toNodeId):s.family==="control"?B_(e,i)&&(t.has(e.fromNodeId)||t.has(e.toNodeId)):!1)}function zv(e){return e.family==="control"&&["call","discriminator-dispatch","result-callback","runtime-handoff"].includes(e.subtype)}function B_(e,t){let n=t.get(e.fromNodeId),r=t.get(e.toNodeId);if(!n||!r)return!1;let i=Hv(n,"ownerNodeId")??(n.kind==="symbol"?n.id:null),o=Hv(r,"ownerNodeId")??(r.kind==="symbol"?r.id:null);return i!==null&&i===o}function $_(e,t){if(!t)return null;let n=new Map;for(let r of t){let i=n.get(r.file)??[];i.push(r.line),n.set(r.file,i)}return new Set(e.filter(r=>{if(!r.location||r.kind==="parameter")return!1;let i=n.get(r.location.file)??[],o=r.location.endLine??r.location.line;return i.some(s=>s>=r.location.line&&s<=o)}).map(r=>r.id))}function j_(e,t){if(!t)return null;let n=new Map;for(let r of t){let i=n.get(r.file)??[];i.push(r.line),n.set(r.file,i)}return new Set(e.filter(r=>r.evidence.some(i=>{if(!i.location)return!1;let o=n.get(i.location.file)??[],s=i.location.endLine??i.location.line;return o.some(a=>a>=i.location.line&&a<=s)})).map(r=>r.id))}function H_(e,t){return t===null?null:new Set(e.filter(n=>t.has(n.id)).flatMap(n=>[n.fromNodeId,n.toNodeId]))}function Hv(e,t){let n=e.attributes[t];return typeof n=="string"?n:null}function Uv(e){return e.disposition==="excluded"||e.disposition==="unsupported"||!Kv(e)?!1:e.evidence.some(t=>t.strength==="exact"||t.strength==="derived")}function Kv(e){return(e.semantics??[]).some(t=>t.family!=="identity"||hc.has(t.subtype))}function Wv(e){return e.subtype.startsWith("predicate-")||e.subtype.startsWith("loop-")||e.subtype.startsWith("exception-")||e.subtype.startsWith("finally-")||e.subtype.startsWith("handler-")}function U_(e,t){return t.has(e.fromNodeId)||t.has(e.toNodeId)}function q_(e,t){return[...e.fromNodeIds,...e.memberNodeIds].some(n=>t.has(n))}function Pn(e){return[...new Set(e)].sort()}import{createHash as G_}from"crypto";var yc=["identity","contract","control","data","state","temporal"],z_=new Set(yc);function Sc(e){let t=Ai(e.anchors,"anchor"),n=Ai(e.nodes,"node"),r=Ai(e.edges,"edge"),i=Ai(e.paths??[],"path"),o=Ai(e.frontiers??[],"frontier"),s=new Set(t.map(p=>p.id)),a=new Set(n.map(p=>p.id)),c=new Set(r.map(p=>p.id)),l=e.routeCatalog?{...e.routeCatalog,routes:Ai(e.routeCatalog.routes,"route"),selectedRouteIds:lt(e.routeCatalog.selectedRouteIds)}:void 0;for(let p of t)gt(`anchor ${p.id}`,[...p.nodeIds,...p.candidateNodeIds],a,"node");for(let p of n)gt(`node ${p.id}`,p.anchorIds,s,"anchor");for(let p of r){if(gt(`edge ${p.id}`,[p.fromNodeId,p.toNodeId],a,"node"),p.evidence.length===0)throw new Error(`Exploration edge ${p.id} has no evidence source.`);V_(p)}for(let p of i)gt(`path ${p.id}`,[p.fromAnchorId,p.toAnchorId],s,"anchor"),gt(`path ${p.id}`,p.nodeIds,a,"node"),gt(`path ${p.id}`,p.edgeIds,c,"edge");for(let p of o)if(gt(`frontier ${p.id}`,p.fromNodeIds,a,"node"),gt(`frontier ${p.id}`,p.edgeIds,c,"edge"),gt(`frontier ${p.id}`,p.memberNodeIds,a,"node"),p.memberCount!==p.memberNodeIds.length)throw new Error(`Exploration frontier ${p.id} reports ${p.memberCount} member(s) but identifies ${p.memberNodeIds.length}.`);for(let p of l?.routes??[])gt(`route ${p.id}`,p.nodeIds,a,"node"),gt(`route ${p.id}`,p.edgeIds,c,"edge"),gt(`route ${p.id}`,[p.anchorNodeId,p.endpointNodeId],a,"node");l&&gt("route catalog selection",l.selectedRouteIds,new Set(l.routes.map(p=>p.id)),"route");let u=lt(e.incompleteReasons??[]),d=u.length===0?"accounted":"incomplete",m=t.reduce((p,f)=>p+f.omittedCandidates,0);return{schemaVersion:1,anchors:t,nodes:n,edges:r,paths:i,frontiers:o,coverage:{status:d,scope:e.scope,nodes:nC(n),edges:nC(r),matchedAnchors:t.filter(p=>p.status==="matched").length,ambiguousAnchors:t.filter(p=>p.status==="ambiguous").length,missingAnchors:t.filter(p=>p.status==="missing").length,omittedCandidates:m,frontierGroups:o.length,programEdges:W_(r),blindSpots:lt(e.blindSpots??[]),explanation:d==="accounted"?"Every node and edge discovered within the declared query scope is emitted, folded with recoverable identity, explicitly excluded, or reported unsupported.":`The declared query scope is not fully accounted for: ${u.join("; ")}`},completion:X_(d,i,e.scope),...l?{routeCatalog:l}:{}}}function K_(e){return e.flatMap(t=>Y_(t.semantics??[]).map(n=>({id:J_(t.id,n),sourceEdgeId:t.id,sourceKind:t.kind,fromNodeId:t.fromNodeId,toNodeId:t.toNodeId,directed:!0,disposition:t.disposition,evidence:[...t.evidence],family:n.family,subtype:n.subtype,...n.context?{context:{...n.context}}:{},...n.attributes?{attributes:{...n.attributes}}:{}}))).sort((t,n)=>t.id.localeCompare(n.id))}function W_(e){let t=K_(e),n=new Set(t.map(s=>s.sourceEdgeId)),r=new Map(yc.map(s=>[s,new Set])),i=new Map(yc.map(s=>[s,new Set])),o=new Map(yc.map(s=>[s,0]));for(let s of t)r.get(s.family).add(s.sourceEdgeId),i.get(s.family).add(s.subtype),o.set(s.family,o.get(s.family)+1);return{sourceEdges:e.length,mappedSourceEdges:n.size,projectedEdges:t.length,unmappedSourceEdges:e.length-n.size,unsupportedSourceEdges:e.filter(s=>s.disposition==="unsupported").length,unmappedKinds:lt(e.filter(s=>!n.has(s.id)).map(s=>s.kind)),families:{identity:ki("identity",r,o,i),contract:ki("contract",r,o,i),control:ki("control",r,o,i),data:ki("data",r,o,i),state:ki("state",r,o,i),temporal:ki("temporal",r,o,i)}}}function ki(e,t,n,r){return{sourceEdges:t.get(e)?.size??0,projectedEdges:n.get(e)??0,subtypes:[...r.get(e)??[]].sort()}}function V_(e){let t=new Set;for(let n of e.semantics??[]){if(!z_.has(n.family))throw new Error(`Exploration edge ${e.id} has unknown program edge family: ${n.family}.`);if(n.subtype.trim().length===0)throw new Error(`Exploration edge ${e.id} has an empty program edge subtype.`);let r=Ud(n);if(t.has(r))throw new Error(`Exploration edge ${e.id} repeats program edge semantic ${r}.`);t.add(r)}}function Y_(e){return[...e].sort((t,n)=>Ud(t).localeCompare(Ud(n)))}function Ud(e){return`${e.family}:${e.subtype}`}function J_(e,t){return`program:${encodeURIComponent(e)}:${t.family}:${encodeURIComponent(t.subtype)}`}function X_(e,t,n){return e==="incomplete"||t.some(r=>r.status!=="connected")?{status:"coverage-incomplete",scope:n,explanation:"The declared graph query has an ambiguous, missing, candidate-only, or disconnected anchor relationship."}:t.length>0?{status:"connector-complete",scope:n,explanation:"Every requested anchor pair has a selected path supported by proved repository relationships."}:{status:"frontier-accounted",scope:n,explanation:"Every discovered direction in the declared graph query is emitted or represented by an exact frontier."}}function rC(e,t={}){let n=t.maxSelectedNodes??24;if(!Number.isSafeInteger(n)||n<=0)throw new RangeError(`maxSelectedNodes must be a positive safe integer; received ${n}`);let r=new Set(e.anchors.flatMap(I=>[...I.nodeIds,...I.candidateNodeIds])),i=[],o=e.anchors.filter(I=>I.status!=="missing"&&I.nodeIds.length+I.candidateNodeIds.length>0);for(let I=0;I<o.length;I+=1)for(let k=I+1;k<o.length;k+=1){let D=o[I],F=o[k],L=Qv(e,D,F,!1),P=L??Qv(e,D,F,!0);P?(P.nodeIds.forEach(j=>r.add(j)),i.push({id:bc("path",D.id,F.id),fromAnchorId:D.id,toAnchorId:F.id,status:!L||D.status==="ambiguous"||F.status==="ambiguous"?"candidate":"connected",nodeIds:P.nodeIds,edgeIds:P.edgeIds})):i.push({id:bc("path",D.id,F.id),fromAnchorId:D.id,toAnchorId:F.id,status:"partial",nodeIds:[],edgeIds:[]})}let s=lt(t.routeIds??[]),a=Q_(e,s),c=new Set(a.routes.map(I=>I.id)),l=s.filter(I=>!c.has(I));if(l.length>0)throw new Error(`Unknown exploration route id(s): ${l.join(", ")}`);let d=a.routes.filter(I=>s.includes(I.id)).map(I=>({anchorNodeId:I.anchorNodeId,endpointNodeId:I.endpointNodeId,endpointKind:I.endpointKind,endpointPriority:2,nodeIds:[...I.nodeIds].reverse(),edgeIds:[...I.edgeIds].reverse()}));for(let I of d)I.nodeIds.forEach(k=>r.add(k));let m=i.length===0||i.some(I=>I.edgeIds.length>0);m&&eC(e,r,n);let p=tC(e,r),f=new Set(t.expandedFrontierIds??[]),g=new Set(p.map(I=>I.id)),h=[...f].filter(I=>!g.has(I)).sort();if(h.length>0)throw new Error(`Unknown exploration frontier id(s): ${h.join(", ")}`);for(let I of p)f.has(I.id)&&I.memberNodeIds.forEach(k=>r.add(k));m&&eC(e,r,n);let b=new Map(d.map(I=>[I.endpointNodeId,I.endpointKind])),S=new Set(d.flatMap(I=>I.nodeIds)),y=new Map;for(let I of d)for(let k=0;k<I.nodeIds.length;k+=1){let D=I.nodeIds[k],F=k;y.set(D,Math.max(y.get(D)??0,F))}let x=e.nodes.map(I=>{let k=b.get(I.id),D=S.has(I.id)?{upstreamCausalPath:!0,upstreamCausalDistance:y.get(I.id)??0,...k?{upstreamCausalEndpoint:k}:{}}:{};return{...I,attributes:{...I.attributes,...D},disposition:I.disposition==="excluded"||I.disposition==="unsupported"?I.disposition:r.has(I.id)?"emitted":"folded"}}),v=new Set([...i.flatMap(I=>I.edgeIds),...d.flatMap(I=>I.edgeIds)]),C=e.edges.map(I=>({...I,disposition:I.disposition==="excluded"||I.disposition==="unsupported"?I.disposition:v.has(I.id)||r.has(I.fromNodeId)&&r.has(I.toNodeId)?"emitted":"folded"})),R=Sc({anchors:e.anchors,nodes:x,edges:C,paths:i,frontiers:[...e.frontiers.filter(I=>I.disposition!=="folded"),...tC({...e,nodes:x,edges:C},r)],scope:e.coverage.scope,blindSpots:e.coverage.blindSpots,incompleteReasons:e.coverage.status==="incomplete"?[e.coverage.explanation]:[],routeCatalog:a}),E=new Set(R.frontiers.flatMap(I=>I.edgeIds)),w=R.edges.filter(I=>I.disposition==="folded"&&!E.has(I.id)).map(I=>I.id);if(w.length>0)throw new Error(`Folded exploration edge(s) are not frontier-accounted: ${w.sort().join(", ")}`);return R}var Vv=10;function Q_(e,t=[]){let n=new Map(e.nodes.map(h=>[h.id,h])),r=new Map(e.edges.map(h=>[h.id,h])),i=new Map;for(let h of e.edges){if(!Z_(h))continue;let b=i.get(h.toNodeId)??[];b.push(h),i.set(h.toNodeId,b)}for(let h of i.values())h.sort((b,S)=>Number(Jo(S))-Number(Jo(b))||Xv(S)-Xv(b)||b.fromNodeId.localeCompare(S.fromNodeId)||b.id.localeCompare(S.id));let o=lt(e.anchors.filter(h=>h.status==="matched").flatMap(h=>h.nodeIds)),s=new Map,a=new Set,c=(h,b,S)=>{let y=b.nodeIds[b.nodeIds.length-1],x=n.get(y),v=n.get(h);if(!x?.location||!v)return;let C=[...b.nodeIds].reverse(),R=[...b.edgeIds].reverse(),E=new Set(C),w=R.flatMap(L=>{let A=r.get(L);return A?[A]:[]}),I=e.edges.filter(L=>L.disposition!=="excluded"&&L.disposition!=="unsupported"&&(E.has(L.fromNodeId)||E.has(L.toNodeId))),k={id:bc("route",h,y,S,...R),status:"proved",anchorNodeId:h,anchorLabel:v.label,endpointNodeId:y,endpointLabel:x.label,endpointLocation:{...x.location},endpointKind:S,nodeIds:C,edgeIds:R,evidenceStrengths:lt(w.flatMap(L=>L.evidence.map(A=>A.strength))),spineEdgeFamilies:Yv(w,!0),relatedEdgeFamilies:Yv(I,!1),crossesRuntimeBoundary:w.some(Jo)},D=`${h}\0${y}\0${S}`,F=s.get(D);(!F||Jv(k,F)<0)&&s.set(D,k)};for(let h of o){n.get(h)?.attributes.publicEntry===!0&&c(h,{nodeIds:[h],edgeIds:[]},"public-entry");let b=[{nodeIds:[h],edgeIds:[]}],S=new Map([[h,0]]);for(let y=0;y<b.length;y+=1){let x=b[y],v=x.nodeIds[x.nodeIds.length-1];x.edgeIds.length>0&&n.get(v)?.location&&n.get(v)?.attributes.publicEntry===!0&&c(h,x,"public-entry");let C=i.get(v)??[];if(x.edgeIds.length>=Vv){C.some(R=>!x.nodeIds.includes(R.fromNodeId))&&a.add(h);continue}for(let R of C){if(x.nodeIds.includes(R.fromNodeId))continue;let E=x.edgeIds.length+1,w=S.get(R.fromNodeId);if(w!==void 0&&w<=E)continue;let I={nodeIds:[...x.nodeIds,R.fromNodeId],edgeIds:[...x.edgeIds,R.id]};if(S.set(R.fromNodeId,E),Jo(R)&&n.get(R.fromNodeId)?.location){c(h,I,"runtime-boundary");continue}b.push(I)}}}let l=[...s.values()].sort(Jv),u=new Set(l.map(h=>h.id)),d=lt(t.filter(h=>u.has(h))),m=lt(l.map(h=>h.anchorNodeId)),p=o.filter(h=>!m.includes(h)),f=[...a].sort(),g=e.coverage.status==="accounted"&&f.length===0?"accounted":"incomplete";return{schemaVersion:1,routes:l,selectedRouteIds:d,coverage:{status:g,scope:"Distinct proved public-entry and runtime-boundary endpoints reachable upstream in the supplied topology.",enumeration:"one-shortest-proved-path-per-endpoint",maximumDepth:Vv,anchorNodeIds:o,anchorsWithRoutes:m,anchorsWithoutRoutes:p,depthLimitedAnchorNodeIds:f,routeCount:l.length,explanation:g==="accounted"?"Every distinct proved upstream public/runtime endpoint in the supplied topology has one stable shortest route.":"Route enumeration is incomplete because the supplied topology has incomplete coverage or a traversal reached the route-depth bound."}}}function Yv(e,t){let n=e.flatMap(r=>r.semantics?.map(i=>i.family)??[]);return t&&e.length>0&&n.length===0&&n.push("control"),lt(n)}function Jv(e,t){return e.anchorNodeId.localeCompare(t.anchorNodeId)||e.edgeIds.length-t.edgeIds.length||e.endpointKind.localeCompare(t.endpointKind)||e.endpointNodeId.localeCompare(t.endpointNodeId)||e.id.localeCompare(t.id)}function Z_(e){return e.disposition!=="excluded"&&e.disposition!=="unsupported"&&eO(e)&&e.evidence.some(t=>["exact","derived","mixed"].includes(t.strength))}function eO(e){return Jo(e)||e.kind==="boundary-observation"||e.kind==="call"||e.kind==="compiler:call"}function Jo(e){return e.kind==="runtime-boundary"||e.kind.startsWith("runtime:")}function Xv(e){let t={exact:5,derived:4,mixed:3,candidate:1,unknown:0};return Math.max(0,...e.evidence.map(n=>t[n.strength]))}function Qv(e,t,n,r){return Zv(e,t,n,r)??Zv(e,n,t,r)}function Zv(e,t,n,r){let i=[...t.nodeIds,...t.candidateNodeIds].sort(),o=new Set([...n.nodeIds,...n.candidateNodeIds]);if(i.some(u=>o.has(u)))return{nodeIds:[i.find(d=>o.has(d))],edgeIds:[]};let s=new Set(e.nodes.filter(u=>u.kind==="structural-region").map(u=>u.id)),a=new Map;for(let u of e.edges)u.disposition==="excluded"||u.disposition==="unsupported"||u.kind==="structural-membership"||s.has(u.fromNodeId)||s.has(u.toNodeId)||u.evidence.every(m=>["candidate","unknown"].includes(m.strength))&&!r||tO(a,u.fromNodeId,u.toNodeId,u.id);for(let u of a.values())u.sort((d,m)=>d.nodeId.localeCompare(m.nodeId)||d.edgeId.localeCompare(m.edgeId));let c=i.map(u=>({nodeId:u,nodeIds:[u],edgeIds:[]})),l=new Set(i);for(let u=0;u<c.length;u+=1){let d=c[u];for(let m of a.get(d.nodeId)??[]){if(l.has(m.nodeId))continue;let p={nodeId:m.nodeId,nodeIds:[...d.nodeIds,m.nodeId],edgeIds:[...d.edgeIds,m.edgeId]};if(o.has(m.nodeId))return p;l.add(m.nodeId),c.push(p)}}return null}function tO(e,t,n,r){let i=e.get(t)??[];i.push({nodeId:n,edgeId:r}),e.set(t,i)}function nO(e,t,n){let r=new Map;for(let a of e.edges){let c=r.get(a.fromNodeId)??{incoming:0,outgoing:0},l=r.get(a.toNodeId)??{incoming:0,outgoing:0};c.outgoing+=1,l.incoming+=1,r.set(a.fromNodeId,c),r.set(a.toNodeId,l)}let i=new Set,o=new Map;for(let a of e.edges){let c=t.has(a.fromNodeId),l=t.has(a.toNodeId);if(c===l)continue;let u=c?a.toNodeId:a.fromNodeId,d=c?a.fromNodeId:a.toNodeId,m=e.nodes.find(g=>g.id===u);if(m?.kind==="structural-region")continue;let p=o.get(u)??new Set;p.add(d),o.set(u,p),(/(?:runtime-boundary|external)/u.test(a.kind)||m&&/(?:frontier|external)/u.test(m.kind))&&i.add(u)}let s=[...o].filter(([a,c])=>{if(i.has(a))return!0;let l=r.get(a)??{incoming:0,outgoing:0};return(l.incoming>1||l.outgoing>1)&&c.size>1}).sort(([a,c],[l,u])=>Number(i.has(l))-Number(i.has(a))||u.size-c.size||a.localeCompare(l)).map(([a])=>a);for(let a of s){if(t.size>=n)break;t.add(a)}}function eC(e,t,n){let r=-1;for(;t.size!==r&&t.size<n;)r=t.size,nO(e,t,n)}function tC(e,t){let n=new Set(e.nodes.filter(s=>!t.has(s.id)&&s.disposition!=="excluded"&&s.disposition!=="unsupported").map(s=>s.id)),r=new Map;for(let s of e.edges){if(!n.has(s.fromNodeId)||!n.has(s.toNodeId))continue;let a=r.get(s.fromNodeId)??new Set,c=r.get(s.toNodeId)??new Set;a.add(s.toNodeId),c.add(s.fromNodeId),r.set(s.fromNodeId,a),r.set(s.toNodeId,c)}let i=[],o=new Set;for(let s of[...n].sort()){if(o.has(s))continue;let a=[],c=[s];o.add(s);for(let l=0;l<c.length;l+=1){let u=c[l];a.push(u);for(let d of[...r.get(u)??[]].sort())o.has(d)||(o.add(d),c.push(d))}i.push(a.sort())}return i.map(s=>{let a=new Set(s),c=e.edges.filter(f=>a.has(f.fromNodeId)||a.has(f.toNodeId)),l=c.filter(f=>a.has(f.fromNodeId)!==a.has(f.toNodeId)),u=lt(l.map(f=>a.has(f.fromNodeId)?f.toNodeId:f.fromNodeId)),d=new Set(l.map(f=>a.has(f.toNodeId)?"outgoing":"incoming")),m=lt(c.map(f=>f.id)),p=lt(l.map(f=>f.kind));return{id:bc("frontier",...s,...m),kind:p.join("+")||"disconnected",direction:d.size===1?[...d][0]:"undirected",fromNodeIds:u,edgeIds:m,memberNodeIds:s,memberCount:s.length,disposition:"folded",reason:l.length>0?"Connected evidence is folded beyond the first edge leaving the selected connector graph.":"Discovered evidence is disconnected from every selected anchor connector under the declared relation scope.",expansion:null}})}function bc(e,...t){let n=G_("sha256").update(t.join("\0")).digest("hex").slice(0,16);return`${e}:${n}`}function Ai(e,t){let n=[...e].sort((r,i)=>r.id.localeCompare(i.id));for(let r=1;r<n.length;r+=1)if(n[r-1].id===n[r].id)throw new Error(`Duplicate exploration ${t} id: ${n[r].id}`);return n}function gt(e,t,n,r){let i=lt(t.filter(o=>!n.has(o)));if(i.length>0)throw new Error(`Exploration ${e} references missing ${r}(s): ${i.join(", ")}`)}function nC(e){return{total:e.length,emitted:e.filter(t=>t.disposition==="emitted").length,folded:e.filter(t=>t.disposition==="folded").length,excluded:e.filter(t=>t.disposition==="excluded").length,unsupported:e.filter(t=>t.disposition==="unsupported").length}}function lt(e){return[...new Set(e)].sort()}var rO=5,iO=12,oO=8,sO=3,iC=8,aO=6,cO=12,oC=12,lO=12,uO=2,dO=new Set(["branch","loop","call","await","return","throw","mutation","catch","finally"]),mO=9e3,sC=fv,aC=new WeakMap;function pO(e,t){return bC(e,t,"full")}function yC(e,t){return bC(e,t,"topology")}function fO(e,t,n,r,i,o=!1){let s=e.get(t);if(s)return s.depth=Math.min(s.depth,n),s.primary||=i,s.promoteBoundaryImports||=o,s.origins.add(r),s;let a={file:t,depth:n,primary:i,promoteBoundaryImports:o,origins:new Set([r]),processed:!1};return e.set(t,a),a}function gO(e,t,n,r,i,o,s="none",a=!1){let c=e.get(n.symbol);if(c)return c.depth=Math.min(c.depth,r),c.origins.add(i),o&&c.anchorQueries.add(o),c.referenceScope=pB(c.referenceScope,s),t(n.relativePath,r,i,!0,a),c;let l={definition:n,depth:r,origins:new Set([i]),anchorQueries:new Set(o?[o]:[]),referenceScope:s,processed:!1};return e.set(n.symbol,l),t(n.relativePath,r,i,!0,a),l}function hO(e,t,n,r,i,o,s=!1,a=!0){let c=nn(n),l=e.get(c);if(l)return l.depth=Math.min(l.depth,r),l.origins.add(i),o&&l.anchorQueries.add(o),l.reverseCallExpansion||=s,l.traversalEligible||=a,t(n.file,r,i,l.traversalEligible,!0),l;let u={...n,depth:r,origins:new Set([i]),anchorQueries:new Set(o?[o]:[]),reverseCallExpansion:s,traversalEligible:a};return e.set(c,u),t(n.file,r,i,a,!0),u}function yO(e){let{db:t,index:n,pendingRelations:r,addFile:i,addSymbol:o,addSourceConstruct:s,observation:a,depth:c,origin:l}=e;i(a.source.file,c,l,!0,!0),a.owner.file!==a.source.file&&i(a.owner.file,c,`${l}:owner`,!0,!0);let u=U(t,a.owner.file),d=a.owner.symbol?cr(t,n,a.owner.symbol).matches.find(f=>f.relativePath===a.owner.file):null,m=(d&&!me(d.symbol)?d:null)??Ne(u,a.source.startLine);if(m&&!me(m.symbol))return o(m,c,l,void 0,"none",!0),m.symbol;a.owner.name&&s({file:a.owner.file,name:a.owner.name,startLine:a.owner.startLine,endLine:a.owner.endLine},c,`${l}:source-owner`,void 0,!0);let p=e.index.definitionsForFile(a.source.file).filter(f=>!!f.leaf&&gn(t,a.source.file,f.leaf).some(g=>g>=a.source.startLine&&g<=a.source.endLine));if(p.length===1){let f=p[0];o(f,c,`${l}:handler-identifier`,void 0,"none",!0),bt(r,{kind:"runtime-boundary",evidence:"runtime-boundary:handler-identifier",fromFile:a.source.file,fromSymbol:null,toFile:f.relativePath,toSymbol:f.symbol,fromBoundaryParticipant:Ni(a),line:a.source.startLine,strength:"derived"})}return null}function bO(e){let t=0,n=0,r=0;for(let i of e.searches){let o=JO(e.db,e.index,i,e.boundaryObservationLocations),s=o.filter(u=>tB(u,e.sourceAllowed)),a=!e.opts.fullLiteralTraversal&&(o.length>iO||s.length>oO),c=a?[]:o,l=new Set((a?[]:e.opts.fullLiteralTraversal?s:[...s].sort(XO).slice(0,sO)).map(mC));a&&(n+=1,r+=o.length);for(let u of c){let d=l.has(mC(u)),m=d&&!u.ownerSymbol&&u.ownerStartLine!==null&&u.ownerEndLine!==null;if(e.addFile(u.relativePath,0,`${d?"literal-anchor":"literal-match"}:${i}`,m,m),m&&e.addSourceConstruct({file:u.relativePath,name:u.ownerShortName??`${u.relativePath}:${u.ownerStartLine+1}`,startLine:u.ownerStartLine,endLine:u.ownerEndLine},0,`literal-source-owner:${i}`,i,!0),d&&u.ownerSymbol){let p=cr(e.db,e.index,u.ownerSymbol).matches[0];p&&!me(p.symbol)&&e.addSymbol(p,0,"literal-owner",i,"all",!0)}e.literalHits.push({query:i,file:u.relativePath,line:u.line,ownerSymbol:u.ownerSymbol,ownerShortName:u.ownerShortName,ownerStartLine:u.ownerStartLine,ownerEndLine:u.ownerEndLine,sourceLine:u.sourceLine.trim(),matchKind:u.matchKind,traversalSeed:d})}e.anchors.push({kind:"literal",query:i,status:o.length>0?"matched":"missing",matchedRegionIds:[],matchingLines:o.length,seedMatchingLines:a?0:l.size,matchOnlyLines:o.length-l.size,eligibleSeedMatchingLines:s.length,materializedMatchingLines:c.length,withheldMatchingLines:a?o.length:0,literalTraversal:a?"withheld-broad":"materialized",representativeMatches:a?nB(i,o):void 0,narrowingCommands:a?iB(i,o):void 0,exhaustiveTraversalCommand:a||l.size<s.length?`scip-query system-map --search ${ye(i)} --full-literal-traversal`:void 0,seedRegionIds:[],matchOnlyRegionIds:[]})}for(let i of e.symbolQueries){let o=cr(e.db,e.index,i);t+=o.omitted;let s=QO(e.db,i),a=o.matches.filter(m=>!me(m.symbol)),c=s!==null&&a.length===0;c&&e.addSourceConstruct(s,0,"source-construct-anchor",i,!0);let l=c?a:o.matches;for(let m of l)e.addSymbol(m,0,"symbol-anchor",i,"all",!0);let u=c?ZO(s):null,d=c?1:o.total;e.anchors.push({kind:"symbol",query:i,status:d===0?"missing":d===1?"matched":"ambiguous",matchedRegionIds:[],symbolCandidates:[...u?[u]:[],...l.map(lB)],totalSymbolCandidates:d,omittedSymbolCandidates:o.omitted})}return{omittedSymbolCandidates:t,broadLiteralAnchors:n,withheldLiteralMatches:r}}function SO(e){let{db:t,opts:n,mode:r,searches:i,symbolQueries:o,maxDepth:s,maxTopologyCharacters:a,requestedRelationKinds:c,evidenceFloor:l,includedSourceScopes:u,workspaces:d,runtimeBoundaries:m,boundaryObservations:p,representedBoundaryLinkIds:f,files:g,symbols:h,sourceConstructs:b,literalHits:S,pendingRelations:y,externalImports:x,anchors:v,omittedSymbolCandidates:C,broadLiteralAnchors:R,withheldLiteralMatches:E,filteredUnverifiedCallEdges:w,memberCallCandidateEdges:I,unresolvedMemberCallsites:k,sourceAllowed:D}=e,F=new Set(c),L=new Map;for(let _ of g.keys())L.set(_,Xo(_,d));let A=[...y.values()].filter(_=>L.has(_.fromFile)&&L.has(_.toFile)).map(_=>({..._,fromRegionId:L.get(_.fromFile).id,toRegionId:L.get(_.toFile).id})).sort(xC),P=xB(A),j=new Set(n.expand??[]),B=bB(g,h,S,A,P,L,j),X=new Set([...g.values()].filter(_=>[..._.origins].some(ce=>ce.startsWith("literal-anchor:")||ce==="literal-owner"||ce==="symbol-anchor")).map(_=>L.get(_.file).id)),G=WO(B),O=new Set(B.map(_=>_.id)),te=[...j].filter(_=>!O.has(_)).sort();for(let _ of v)if(_.matchedRegionIds=EB(_,S,h,L),_.kind==="literal"){let ce=S.filter(Be=>Be.query===_.query);_.seedRegionIds=pe(ce.filter(Be=>Be.traversalSeed).map(Be=>L.get(Be.file).id)),_.matchOnlyRegionIds=pe(ce.filter(Be=>!Be.traversalSeed).map(Be=>L.get(Be.file).id))}let ie=[...h.values()].filter(_=>!_.processed).length,we=[...g.values()].filter(_=>_.primary&&!_.processed).length,De=[...g.values()].filter(_=>!_.primary&&!_.processed).length,Ft=[...h.values()].filter(_=>_.processed),tt=(m?.frontiers??[]).flatMap(_=>{let ce=p.get(_.observationId);return!ce&&_.source&&_.action&&_.strength?!F.has("runtime-boundary")||!D(_.source.file)||l==="exact"||!g.has(_.source.file)?[]:[{observationId:_.observationId,action:_.action,strength:_.strength,file:_.source.file,line:_.source.startLine,ownerShortName:_.ownerShortName??null,address:_.address??_.missingKeyParts.join(", "),reason:_.reason}]:!F.has("runtime-boundary")||!ce||!D(ce.source.file)||l==="exact"&&ce.strength!=="exact"||!g.has(ce.source.file)?[]:[{observationId:ce.id,action:ce.action,strength:ce.strength,file:ce.source.file,line:ce.source.startLine,ownerShortName:ce.owner.name,address:CC(ce),reason:_.reason,protocol:ce.protocol,role:ce.role,modality:ce.modality,resolution:ce.resolution,sourceScope:ce.sourceScope,keyParts:ce.keyParts.map(Be=>({name:Be.name,value:Be.value,evidence:Be.evidence}))}]}).sort((_,ce)=>_.file.localeCompare(ce.file)||_.line-ce.line),M=(m?.links??[]).filter(_=>{if(!F.has("runtime-boundary")||l==="exact"&&_.strength!=="exact")return!1;let ce=p.get(_.from),Be=p.get(_.to);return!!(ce&&Be&&D(ce.source.file)&&D(Be.source.file)&&(g.has(ce.source.file)||g.has(Be.source.file)))}),$=M.filter(_=>_.strength==="exact").length,Y=M.filter(_=>_.strength==="derived").length,oe=M.filter(_=>_.strength==="candidate").length,Ae=m?.links.filter(_=>_.strength==="exact").length??0,Ut=m?.links.filter(_=>_.strength==="derived").length??0,Jr=m?.links.filter(_=>_.strength==="candidate").length??0,gr=RB(x,L),ul=C===0?"accounted":"incomplete",kp=[...R>0?[`${R} broad literal anchor(s) withheld ${E} exact match(es) before graph traversal; representative identities and scoped search commands preserve recovery without treating every textual occurrence as relevant.`]:[],`Literal matches outside the included source scopes (${u.join(", ")}) remain visible as match-only evidence and do not seed traversal.`,m?"Built-in runtime-boundary extractors traverse direct and replayably derived links; heuristic candidates, unsupported frameworks, reflection, generated names, and dependency wiring not recoverable from compiler occurrences or constructor assignments remain disclosed frontiers.":"Runtime-boundary evidence is unavailable for this index; run scip-query reindex with this build to extract supported HTTP, event, registry, and persistence observations.","Reverse references do not recursively expand from discovered callers or callees.","Member calls use compiler occurrences, exact constructor-assigned fields, bounded unique service providers, direct factory-return members, and compiler-resolved object-literal callbacks when available. Ambiguous providers remain candidate frontiers; callback values routed through mutation, reflection, or unsupported dependency containers remain unrepresented.","Literal traversal is bounded to the smallest parser-delimited source construct; parser gaps may reduce an owner to one source line and leave its continuation untraversed.","Schema consumers stay within forward-flow regions; cross-workspace contracts may discover consumers in other workspaces. Add an explicit symbol anchor to widen either scope.",`Traversal stops after depth ${s}; nonzero frontier counts identify evidence that was discovered but not traversed.`,"Region labels are structural path groupings, not inferred runtime or architectural boundaries."],St=_O({db:t,anchors:v,regions:B,symbolStates:h,sourceConstructStates:b,literalHits:S,relations:A,externalBoundaries:gr,boundaryFrontiers:tt,regionForFile:L,closureStatus:ul,omittedSymbolCandidates:C,maxDepth:s,requestedRelationKinds:c,evidenceFloor:l,includedSourceScopes:u,blindSpots:kp,topologyFrontiers:n.topologyFrontiers??[],routeIds:n.routeIds??[],expandedRegionIds:[...j],maxTopologyCharacters:a,fullLiteralTraversal:n.fullLiteralTraversal??!1});if(r==="topology")return St;let Ap=(n.behaviorFocusLocations?.length??0)>0?new Set([...St.anchors.flatMap(_=>_.nodeIds),...St.paths.flatMap(_=>_.nodeIds)]).size:void 0,Is=gS(t,St,{focusLocations:n.behaviorFocusLocations,...Ap?{maxSteps:Ap}:{}});WS(t,St,Is);let ZI=EO(t,St,Is,n.behaviorFocusLocations??[]);St.corridor=Gv(St,{focusLocations:ZI});let Fp=KS(t,St,Is,{sourceAllowed:D,selectionTerms:n.selectionTerms}),Np=HO(St),ew=zO(i,o,s,c,l,u,n.fullLiteralTraversal??!1,a,B,P,X,j,Np),tw=GO(i,o,s,B.filter(_=>Np.has(_.id)),X,c,l,u,n.fullLiteralTraversal??!1,a);return{anchors:v,regions:B,regionRelations:P,externalBoundaries:gr,boundaryFrontiers:tt,unmatchedExpansions:te,expansion:tw,drilldown:G,presentation:ew,topology:St,behavior:Is,nextAnchors:Fp,closure:{status:ul,emitted:{regions:B.length,relations:A.length,runtimeLinks:f.size},withheld:{symbols:ie,files:we+De,regions:St.nodes.filter(_=>_.kind==="structural-region"&&_.disposition==="folded").length,drillAnchors:(G?.omittedAnchors??0)+Fp.omittedAnchors,literalMatches:E},ambiguous:{anchors:v.filter(_=>_.status==="ambiguous").length,omittedSymbolCandidates:C},external:gr.length,unresolved:tt.length,explanation:ul==="accounted"?"Every fact reached under the declared anchors, relations, depth, evidence floor, source scopes, and installed analyzers is accounted for as emitted, withheld, ambiguous, external, or unresolved.":"Some ambiguous symbol candidates were not identified, so the declared query is not fully accounted for."},coverage:{explicitAnchorCount:v.length,requestedRelationKinds:c,evidenceFloor:l,includedSourceScopes:u,matchedAnchorCount:v.filter(_=>_.status!=="missing").length,literalSearchesComplete:!0,broadLiteralAnchors:R,withheldLiteralMatches:E,symbolCandidateSetsComplete:C===0,omittedSymbolCandidates:C,maxTraversalDepth:s,frontierSymbols:ie,frontierFiles:we,supportFilesNotTraversed:De,filteredUnverifiedCallEdges:w,memberCallCandidateEdges:I,unresolvedMemberCallsites:k,runtimeBoundaryEvidenceAvailable:m!==null,runtimeBoundaryObservations:m?.observations.length??0,runtimeBoundaryExactLinks:$,runtimeBoundaryDerivedLinks:Y,runtimeBoundaryCandidateLinks:oe,repositoryRuntimeBoundaryExactLinks:Ae,repositoryRuntimeBoundaryDerivedLinks:Ut,repositoryRuntimeBoundaryCandidateLinks:Jr,runtimeBoundaryTraversedLinks:f.size,runtimeBoundaryFrontiers:tt.length,referenceExpansionEligibleSymbols:Ft.filter(_=>_.referenceScope!=="none").length,referenceExpansionSkippedSymbols:Ft.filter(_=>_.referenceScope==="none").length,dynamicDispatchRepresented:m?.links.some(_=>_.joinRule==="carrier.discriminator"&&f.has(_.id))??!1,runtimeGeneratedLinksRepresented:m!==null,regionBoundariesAreStructural:!0,relationFamilies:{"literal-anchor":{evidence:"exact-source",scope:"all indexed documents for each explicit literal",completeWithinScope:!0},reference:{evidence:"compiler-graph",scope:"all cross-file indexed/source-attributed sites for explicit anchors and promoted non-module boundary symbols",completeWithinScope:!0},call:{evidence:"mixed",scope:"static callees plus exact SCIP call occurrences in traversed source ranges, exact constructor-assigned member receivers, and uniquely attributed direct-import member candidates",completeWithinScope:!0},"contract-symbol":{evidence:"compiler-graph",scope:"compiler-resolved symbol identities referenced across inferred workspace boundaries",completeWithinScope:!0},import:{evidence:"compiler-graph",scope:"all indexed or source-resolved imports of traversed primary files",completeWithinScope:!0},"runtime-boundary":{evidence:"exact-source",scope:"direct and mechanically derived links produced by grounded runtime adapters and factorized relation groups",completeWithinScope:!0}},blindSpots:kp}}}function vO(e,t){let{db:n,relationPolicy:r,sourceConstructs:i,reverseExpandedSourceConstructs:o,pendingRelations:s,reverseFileGraph:a,serviceCallerFilesBySourceConstruct:c,sourceAllowed:l,memberCallTargetsForWholeFile:u,addSymbol:d,addSourceConstruct:m}=e;if(r.has("call")){let p=[...i.values()].filter(f=>f.traversalEligible&&f.reverseCallExpansion&&f.depth<=t&&!o.has(nn(f)));for(let f of p){o.add(nn(f));let g=K(n,f.file);if((g?.callables??[]).filter(S=>S.name===f.name&&S.startLine<=f.endLine&&S.endLine>=f.startLine).length===1){let S=(g?.callSites??[]).filter(y=>y.calleeLeaf===f.name&&!y.memberAccess);for(let y of S){let x=t+1,v=Ne(U(n,f.file),y.line),C=null,R=null;if(v&&!me(v.symbol)){if(v.relativePath===f.file&&v.startLine<=f.endLine&&v.endLine>=f.startLine)continue;d(v,x,"reverse-local-call-owner",void 0,"forward-regions",!0),C=v.symbol}else{let E=qd(n,f.file,y.line);E&&nn(E)!==nn(f)&&(R=m(E,x,"reverse-local-call-source-owner",void 0,!0))}!C&&!R||bt(s,{kind:"call",evidence:"ast-callsite",fromFile:f.file,fromSymbol:C,toFile:f.file,toSymbol:null,fromSourceConstruct:R?ut(R):void 0,toSourceConstruct:ut(f),line:y.line,strength:"derived"})}}let b=new Set([...a.get(f.file)??[],...c.get(nn(f))??[],...tS(n,f.file).flatMap(S=>[...a.get(S)??[]])]);for(let S of b){if(!l(S))continue;let x=u(S).targets.filter(v=>v.targetFile===f.file&&v.targetStartLine<=f.endLine&&v.targetEndLine>=f.startLine);for(let v of x){let C=t+1,R=Ne(U(n,S),v.line),E=null,w=null;if(R&&!me(R.symbol))d(R,C,"reverse-member-call-owner",void 0,"cross-workspace-or-forward",!0),E=R.symbol;else{let I=qd(n,S,v.line);I&&(w=m(I,C,"reverse-member-call-source-owner",void 0,!0))}!E&&!w||bt(s,{kind:"call",evidence:"ast-service-member-callsite",fromFile:S,fromSymbol:E,toFile:f.file,toSymbol:null,fromSourceConstruct:w?ut(w):void 0,toSourceConstruct:ut(f),line:v.line,strength:v.strength==="exact"?"exact":"derived"})}}}}}function CO(e,t){let{db:n,index:r,relationPolicy:i,symbols:o,sourceAllowed:s,files:a,workspaces:c,addFile:l,addSymbol:u,addSourceConstruct:d,pendingRelations:m,fileGraph:p,traversalMetrics:f}=e,g=[...o.values()].filter(b=>!b.processed&&b.depth<=t),h=i.has("call")?r.calleeMap(g.map(b=>b.definition),{additive:!1,semantic:!1}):new Map;for(let b of g){b.processed=!0;let S=b.definition;if(b.referenceScope!=="none"&&(i.has("call")||i.has("reference")||i.has("contract-symbol"))){let y=sB(n,r,S).filter(v=>s(v.file)&&mB(b,v.file,a,c)),x=new Set(y.flatMap(v=>{if(!(i.has("call")&&K(n,v.file)?.callSites.some(E=>E.line===v.line&&cC(n,v.file,E,S))===!0)||!v.enclosingSymbol)return[];let R=cr(n,r,v.enclosingSymbol).matches[0];return R&&!me(R.symbol)?[{owner:R,site:v}]:[]}).sort((v,C)=>{let R=ht(S.relativePath,c).relativeDir,E=ht(v.owner.relativePath,c).relativeDir===R,w=ht(C.owner.relativePath,c).relativeDir===R,I=lC(n,v.owner),k=lC(n,C.owner),D=v.owner.endLine-v.owner.startLine,F=C.owner.endLine-C.owner.startLine;return Number(w)-Number(E)||k-I||D-F||v.owner.symbol.localeCompare(C.owner.symbol)}).filter((v,C,R)=>R.findIndex(E=>E.owner.symbol===v.owner.symbol)===C).reduce((v,C)=>{if(v.length>=uO)return v;let R=ht(C.owner.relativePath,c).relativeDir;return v.some(E=>E.workspace===R)||v.push({symbol:C.owner.symbol,workspace:R}),v},[]).map(v=>v.symbol));for(let v of y){let C=t+1;l(v.file,C,`reference:${T(S.symbol)}`,!0);let R=i.has("call")&&K(n,v.file)?.callSites.some(I=>I.line===v.line&&cC(n,v.file,I,S))===!0,E=null,w=null;if(v.enclosingSymbol){let I=cr(n,r,v.enclosingSymbol).matches[0];I&&!me(I.symbol)&&(u(I,C,"reference-owner",void 0,R&&x.has(I.symbol)?b.referenceScope:"none"),E=I.symbol)}if(!E&&v.line!==null){let I=qd(n,v.file,v.line);I&&(w=d(I,C,"reference-source-owner",void 0,R))}i.has("reference")&&bt(m,{kind:"reference",evidence:"indexed-or-source-reference",fromFile:v.file,fromSymbol:E,toFile:S.relativePath,toSymbol:S.symbol,fromSourceConstruct:w?ut(w):void 0,line:v.line,strength:"mixed"}),R&&bt(m,{kind:"call",evidence:"ast-callsite",fromFile:v.file,fromSymbol:E,toFile:S.relativePath,toSymbol:S.symbol,fromSourceConstruct:w?ut(w):void 0,line:v.line,strength:"derived"}),i.has("contract-symbol")&&ht(v.file,c).relativeDir!==ht(S.relativePath,c).relativeDir&&bt(m,{kind:"contract-symbol",evidence:"compiler-cross-workspace-symbol",fromFile:v.file,fromSymbol:E,toFile:S.relativePath,toSymbol:S.symbol,fromSourceConstruct:w?ut(w):void 0,line:v.line,strength:"exact"})}}for(let y of h.get(S.symbolId)??[]){let x=cr(n,r,y.symbol).matches.find(C=>C.relativePath===y.file);if(!x||!s(x.relativePath))continue;if(!(x.relativePath===S.relativePath||(p.get(S.relativePath)??new Set).has(x.relativePath))){f.filteredUnverifiedCallEdges+=1;continue}u(x,t+1,`call:${T(S.symbol)}`,void 0,"none",!0),bt(m,{kind:"call",evidence:y.source,fromFile:S.relativePath,fromSymbol:S.symbol,toFile:x.relativePath,toSymbol:x.symbol,line:null,strength:qO(y.source)})}}}function xO(e,t){let{db:n,index:r,relationPolicy:i,files:o,sourceConstructs:s,symbols:a,boundaryObservations:c,boundaryObservationDepths:l,sourceAllowed:u,addSymbol:d,pendingRelations:m,traversalMetrics:p,addSourceConstruct:f,serviceCallerFilesBySourceConstruct:g,reverseFileGraph:h,externalImports:b,addFile:S,workspaces:y}=e,x=[...o.values()].filter(v=>!v.processed&&v.primary&&v.depth<=t);for(let v of x){v.processed=!0;let C=[...s.values()].filter(P=>P.traversalEligible&&P.file===v.file&&P.depth<=t),R=[...a.values()].filter(P=>P.definition.relativePath===v.file&&P.depth<=t).map(P=>{let j=fi(n,v.file,P.definition.startLine);return{startLine:j?.startLine??P.definition.startLine,endLine:j?.endLine??P.definition.endLine}}),E=P=>[...a.values()].filter(j=>j.definition.relativePath===v.file&&j.definition.startLine<=P&&j.definition.endLine>=P).sort((j,B)=>j.definition.endLine-j.definition.startLine-(B.definition.endLine-B.definition.startLine)||j.definition.startLine-B.definition.startLine)[0],w=[...c.values()].filter(P=>P.source.file===v.file&&l.has(P.id)),I=[...C.map(P=>({startLine:P.startLine,endLine:P.endLine})),...w.map(P=>({...vc(n,P)}))],k=[...R,...I],D=(K(n,v.file)?.callSites??[]).filter(P=>k.some(j=>P.line>=j.startLine&&P.line<=j.endLine)),F=new Set;if(i.has("call"))for(let P of k){let j=En(n,v.file,P.startLine,P.endLine);for(let B of j.targets){if(!u(B.definition.relativePath))continue;let X=E(B.sourceLine),G=C.find(te=>te.startLine<=B.sourceLine&&te.endLine>=B.sourceLine),O=w.find(te=>{let ie=vc(n,te);return ie.startLine<=B.sourceLine&&ie.endLine>=B.sourceLine});d(B.definition,t+1,`scip-occurrence-call:${v.file}:${B.sourceLine+1}`,void 0,"none",!0),bt(m,{kind:"call",evidence:"scip-occurrence-callsite",fromFile:v.file,fromSymbol:X?.definition.symbol??null,toFile:B.definition.relativePath,toSymbol:B.definition.symbol,fromBoundaryParticipant:O?Ni(O):void 0,fromSourceConstruct:G?ut(G):void 0,line:B.sourceLine,strength:"exact"}),F.add(`${B.sourceLine}\0${B.calleeLeaf}`)}}if(i.has("reference"))for(let P of k){let j=cS(n,v.file,P.startLine,P.endLine);for(let B of j.targets){if(!u(B.definition.relativePath)||F.has(`${B.sourceLine}\0${B.calleeLeaf}`))continue;let X=E(B.sourceLine);if(X?.definition.symbol===B.definition.symbol)continue;let G=C.find(te=>te.startLine<=B.sourceLine&&te.endLine>=B.sourceLine),O=w.find(te=>{let ie=vc(n,te);return ie.startLine<=B.sourceLine&&ie.endLine>=B.sourceLine});d(B.definition,t+1,`scip-occurrence-reference:${v.file}:${B.sourceLine+1}`,void 0,"none",!0),bt(m,{kind:"reference",evidence:"scip-occurrence-reference",fromFile:v.file,fromSymbol:X?.definition.symbol??null,toFile:B.definition.relativePath,toSymbol:B.definition.symbol,fromBoundaryParticipant:O?Ni(O):void 0,fromSourceConstruct:G?ut(G):void 0,line:B.sourceLine,strength:"exact"})}}let L=i.has("call")?nr(n,v.file,{ranges:k,excludeIndexedTargets:!1}):{targets:[],unresolvedCallsites:0};p.unresolvedMemberCallsites+=L.unresolvedCallsites;let A=L.targets.filter(P=>!F.has(`${P.line}\0${P.calleeLeaf}`));p.memberCallCandidateEdges+=A.filter(P=>P.strength!=="exact"&&(P.resolution!=="imported-service-object-member"||(P.resolutionAlternativeCount??0)>1)).length;for(let P of A){let j=(P.resolutionAlternativeCount??1)===1,B=P.targetSymbol?U(n,P.targetFile).find(ie=>ie.symbol===P.targetSymbol):void 0,X=B?null:f({file:P.targetFile,name:P.calleeLeaf,startLine:P.targetStartLine,endLine:P.targetEndLine},t+1,`member-call:${v.file}`,void 0,P.resolution==="imported-service-object-member"&&j,j);if(X&&P.serviceFile){let ie=nn(X),we=g.get(ie)??new Set;for(let De of h.get(P.serviceFile)??[])we.add(De);g.set(ie,we)}B&&d(B,t+1,`member-call:${v.file}`,void 0,"none",!0);let G=C.find(ie=>ie.startLine<=P.line&&ie.endLine>=P.line),O=E(P.line),te=w.find(ie=>{let we=vc(n,ie);return we.startLine<=P.line&&we.endLine>=P.line});bt(m,{kind:"call",evidence:P.resolution==="constructed-member-receiver"?"ast-constructed-member-callsite":P.resolution==="factory-callback-member"?"ast-factory-callback-callsite":P.resolution==="imported-service-object-member"?"ast-service-member-callsite":"ast-member-import-candidate",fromFile:v.file,fromSymbol:O?.definition.symbol??null,toFile:P.targetFile,toSymbol:B?.symbol??null,fromBoundaryParticipant:te?Ni(te):void 0,fromSourceConstruct:G?ut(G):void 0,toSourceConstruct:X?ut(X):void 0,line:P.line,strength:P.resolution==="imported-service-object-member"?(P.resolutionAlternativeCount??0)===1?"derived":"candidate":P.strength??"candidate"})}for(let P of i.has("import")||i.has("call")?aB(n,v.file):[]){if(!P.fromFile){if(i.has("import")){let B=b.get(P.shortName)??{name:P.shortName,fromFiles:new Set};B.fromFiles.add(v.file),b.set(P.shortName,B)}continue}if(!u(P.fromFile))continue;if(i.has("import")&&(S(P.fromFile,t+1,`import:${v.file}`,!1),bt(m,{kind:"import",evidence:"indexed-or-source-import",fromFile:v.file,fromSymbol:null,toFile:P.fromFile,toSymbol:P.symbol,line:null,strength:"mixed"})),i.has("call")&&D.length>0){let B=(P.source==="compiler"?cr(n,r,P.symbol).matches:qn(n,P.fromFile,P.importedName)).filter(X=>!me(X.symbol));for(let X of B){let G=D.filter(O=>O.calleeLeaf===P.localName).map(O=>O.line);if(G.length!==0){d(X,t+1,`source-call:${v.file}`,void 0,"none",!0);for(let O of G)bt(m,{kind:"call",evidence:"ast-callsite",fromFile:v.file,fromSymbol:null,toFile:X.relativePath,toSymbol:X.symbol,line:O,strength:"derived"})}}}if(!v.promoteBoundaryImports||!uB(v.file,P.fromFile,y))continue;let j=cr(n,r,P.symbol);for(let B of j.matches)if(dB(B.relativePath,P.fromFile,y)&&!me(B.symbol)){let X=ht(v.file,y).relativeDir!==ht(B.relativePath,y).relativeDir;d(B,t+1,`boundary-import:${v.file}`,void 0,X?"cross-workspace-or-forward":"forward-regions")}}}}function RO(e,t){let{relationPolicy:n,runtimeBoundaries:r,evidenceFloor:i,representedBoundaryLinkIds:o,boundaryObservations:s,sourceAllowed:a,boundaryObservationDepths:c,symbols:l,sourceConstructs:u,addBoundaryObservation:d,pendingRelations:m}=e;for(let p of n.has("runtime-boundary")?r?.links??[]:[]){if(p.strength==="candidate"||i==="exact"&&p.strength!=="exact"||o.has(p.id))continue;let f=s.get(p.from),g=s.get(p.to);if(!f||!g||!a(f.source.file)||!a(g.source.file))continue;let h=gC(f,t,c,l,u),b=gC(g,t,c,l,u);if(h===null&&b===null)continue;let S=t+1,y=d(f,h??S,`runtime-boundary:${p.joinRule}`),x=d(g,b??S,`runtime-boundary:${p.joinRule}`),v=y?null:fC(u,f),C=x?null:fC(u,g);c.set(f.id,h??S),c.set(g.id,b??S),bt(m,{kind:"runtime-boundary",evidence:`runtime-boundary:${p.joinRule}`,fromFile:f.source.file,fromSymbol:y,toFile:g.source.file,toSymbol:x,fromBoundaryParticipant:Ni(f),toBoundaryParticipant:Ni(g),fromSourceConstruct:v?ut(v):void 0,toSourceConstruct:C?ut(C):void 0,runtimeBoundaryKey:p.matchedKeyParts.map(R=>`${R.name}=${R.value}`).join(" "),line:f.source.startLine,strength:p.strength}),o.add(p.id)}}function bC(e,t,n){let r=ke(t.searches??[]),i=ke(t.symbols??[]),o=ke(t.relations&&t.relations.length>0?t.relations:sC),s=o.filter($=>!sC.includes($));if(s.length>0)throw new Error(`Unsupported system-map relation kind(s): ${s.join(", ")}`);let a=new Set(o),c=t.evidenceFloor??"derived";if(c!=="exact"&&c!=="derived")throw new Error(`Unsupported system-map evidence floor: ${c}`);let l=ke(t.sourceScopes&&t.sourceScopes.length>0?t.sourceScopes:["production"]),u=["production","test","fixture","example","generated","script","unknown"],d=l.filter($=>!u.includes($));if(d.length>0)throw new Error(`Unsupported system-map source scope(s): ${d.join(", ")}`);let m=new Set(l),p=$=>m.has(wl($));if(r.length===0&&i.length===0)throw new Error("system-map requires at least one --search or --symbol anchor.");let f=t.maxDepth??rO;if(!Number.isSafeInteger(f)||f<0)throw new RangeError(`maxDepth must be a non-negative safe integer; received ${f}`);let g=t.maxTopologyCharacters??mO;if(!Number.isSafeInteger(g)||g<=0)throw new RangeError(`maxTopologyCharacters must be a positive safe integer; received ${g}`);let h=new H(e),{fileGraph:b,reverseFileGraph:S,workspaces:y,runtimeBoundaries:x}=fB(e,h),v=new Map((x?.observations??[]).map($=>[$.id,$])),C=new Set((x?.observations??[]).map($=>`${$.source.file}\0${$.source.startLine}`)),R=new Set,E=new Map,w=new Map,I=new Map,k=new Map,D=[],F=new Map,L=new Map,A=[],P={filteredUnverifiedCallEdges:0,memberCallCandidateEdges:0,unresolvedMemberCallsites:0},j=new Set,B=new Map,X=new Map,G=$=>{let Y=X.get($);if(Y)return Y;let oe=nr(e,$,{excludeIndexedTargets:!1});return X.set($,oe),oe},O=($,Y,oe,Ae,Ut=!1)=>fO(w,$,Y,oe,Ae,Ut),te=($,Y,oe,Ae,Ut="none",Jr=!1)=>gO(I,O,$,Y,oe,Ae,Ut,Jr),ie=($,Y,oe,Ae,Ut=!1,Jr=!0)=>hO(k,O,$,Y,oe,Ae,Ut,Jr),we=($,Y,oe)=>yO({db:e,index:h,pendingRelations:F,addFile:O,addSymbol:te,addSourceConstruct:ie,observation:$,depth:Y,origin:oe}),{omittedSymbolCandidates:De,broadLiteralAnchors:Ft,withheldLiteralMatches:tt}=bO({db:e,index:h,searches:r,symbolQueries:i,opts:t,boundaryObservationLocations:C,sourceAllowed:p,addFile:O,addSymbol:te,addSourceConstruct:ie,literalHits:D,anchors:A}),M={db:e,index:h,relationPolicy:a,evidenceFloor:c,sourceAllowed:p,fileGraph:b,reverseFileGraph:S,workspaces:y,runtimeBoundaries:x,boundaryObservations:v,boundaryObservationDepths:E,representedBoundaryLinkIds:R,files:w,symbols:I,sourceConstructs:k,pendingRelations:F,externalImports:L,reverseExpandedSourceConstructs:j,serviceCallerFilesBySourceConstruct:B,traversalMetrics:P,memberCallTargetsForWholeFile:G,addFile:O,addSymbol:te,addSourceConstruct:ie,addBoundaryObservation:we};for(let $=0;$<f;$+=1)vO(M,$),CO(M,$),xO(M,$),RO(M,$);return SO({db:e,opts:t,mode:n,searches:r,symbolQueries:i,maxDepth:f,maxTopologyCharacters:g,requestedRelationKinds:o,evidenceFloor:c,includedSourceScopes:l,workspaces:y,runtimeBoundaries:x,boundaryObservations:v,representedBoundaryLinkIds:R,files:w,symbols:I,sourceConstructs:k,literalHits:D,pendingRelations:F,externalImports:L,anchors:A,omittedSymbolCandidates:De,broadLiteralAnchors:Ft,withheldLiteralMatches:tt,filteredUnverifiedCallEdges:P.filteredUnverifiedCallEdges,memberCallCandidateEdges:P.memberCallCandidateEdges,unresolvedMemberCallsites:P.unresolvedMemberCallsites,sourceAllowed:p})}function EO(e,t,n,r){let i=new Map,o=c=>{i.set(`${c.file}\0${c.line}`,c)};for(let c of r)o(c);let s=new Set(t.anchors.filter(c=>c.status==="matched").flatMap(c=>c.nodeIds));for(let c of n.steps)if(!(!c.location||!s.has(c.nodeId)||(c.behavior?.rawCharacters??1/0)>3e3))for(let l of c.behavior?.lines??[])l.signals.some(u=>dO.has(u))&&o({file:c.location.file,line:l.line,endLine:l.endLine});let a=t.edges.filter(c=>c.disposition==="emitted").flatMap(c=>c.evidence.flatMap(l=>l.location?[l.location]:[]));for(let c of a){o(c);let l=t.nodes.filter(d=>d.location?.file===c.file&&["symbol","source-construct","runtime-boundary-participant"].includes(d.kind)&&d.location.line<=c.line&&(d.location.endLine??d.location.line)>=c.line).sort((d,m)=>(d.location.endLine??d.location.line)-d.location.line-((m.location.endLine??m.location.line)-m.location.line)||d.id.localeCompare(m.id))[0];if(!l?.location)continue;let u=aa(e,c.file,l.location.line,l.location.endLine??l.location.line,[c.line]);for(let d of u)o({file:c.file,line:d.line,endLine:d.endLine})}return[...i.values()].sort((c,l)=>c.file.localeCompare(l.file)||c.line-l.line)}function IO(e){if(e.ownerStartLine===null||e.ownerStartLine===void 0)throw new Error(`Literal hit ${e.file}:${e.line+1} has no source-owner start line.`);if(e.ownerEndLine===null||e.ownerEndLine===void 0)throw new Error(`Literal hit ${e.file}:${e.line+1} has no source-owner end line.`);return{file:e.file,name:e.ownerShortName??`${e.file}:${e.ownerStartLine+1}`,startLine:e.ownerStartLine,endLine:e.ownerEndLine}}function nn(e){return`${e.file}\0${e.startLine}\0${e.endLine}\0${e.name}`}function ut(e){return{file:e.file,name:e.name,startLine:e.startLine,endLine:e.endLine}}function cC(e,t,n,r){if(n.calleeLeaf===r.leaf)return!0;let i=ri(e,t,n.calleeLeaf);return i!==null&&i.importedName===r.leaf&&i.sourcePath!==null&&Fe(i.sourcePath,r.relativePath)}function Cc(e,t){let n=_n(K(e,t.file)?.callables??[],t.startLine);if(n&&n.endLine>=t.endLine)return{file:t.file,name:/^source@\d+$/u.test(n.name)&&!/^source@\d+$/u.test(t.name)?t.name:n.name,startLine:n.startLine,endLine:n.endLine};let r=vC(e,t.file,t.startLine);return r&&r.endLine>=t.endLine?{file:t.file,name:r.name,startLine:r.startLine,endLine:r.endLine}:ut(t)}function Fi(e){return yt("source-construct",e.file,String(e.startLine),String(e.endLine),e.name)}function xc(e,t){let n=Ii(e,t.symbol,t.relativePath),r=new Set(["package-surface-file","transitive-package-surface"]),i=n.filter(s=>!r.has(s)||pt(e,t)),o=i.some(s=>!r.has(s));return{evidence:i,priority:o||wb(e,t.symbol,t.relativePath)?2:1}}function lC(e,t){let n=xc(e,t);return n.evidence.length>0?n.priority:0}function wO(e,t){let n=U(e,t.file),r=n.filter(i=>i.startLine<=t.startLine&&i.endLine>=t.startLine).sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine)||i.startLine-o.startLine);for(let i of r){let o=xc(e,i);if(o.evidence.length>0)return o}for(let i of LO(e,t.file,t.startLine)){let o=n.filter(s=>s.leaf===i.name).sort((s,a)=>Math.abs(s.startLine-i.startLine)-Math.abs(a.startLine-i.startLine)||s.symbol.localeCompare(a.symbol));for(let s of o){let a=xc(e,s);if(a.evidence.length>0)return a}return{evidence:[],priority:0}}return{evidence:[],priority:0}}function LO(e,t,n){let r=J(e,t)?.rootNode;if(!r||r.startPosition.row>n||r.endPosition.row<n)return[];let i=[],o=Kd(r,n);for(;o;){if(o.type==="variable_declarator"||o.type==="function_declaration"||o.type==="generator_function_declaration"||o.type==="class_declaration"){let s=o.childForFieldName("name")??o.namedChild(0);(s?.type==="identifier"||s?.type==="type_identifier")&&i.push({name:s.text,startLine:o.startPosition.row})}o=o.parent}return i}function PO(e){return[...new Map([...e.sourceConstructStates.values()].map(t=>Cc(e.db,t)).map(t=>[nn(t),t])).values()].sort((t,n)=>t.file.localeCompare(n.file)||t.startLine-n.startLine||t.endLine-n.endLine)}function DO(e,t){return e.anchors.map((n,r)=>{let i=yt("anchor",String(r),n.kind,n.query),o=[...e.symbolStates.values()].filter(u=>u.anchorQueries.has(n.query)).flatMap(u=>{if(!me(u.definition.symbol))return[ar(u.definition.symbol)];let d=t.filter(m=>m.file===u.definition.relativePath).map(m=>Fi(m));return d.length>0?d:[ar(u.definition.symbol)]}),s=[...e.sourceConstructStates.values()].filter(u=>u.anchorQueries.has(n.query)).map(u=>Fi(Cc(e.db,u))),a=e.literalHits.filter(u=>u.query===n.query&&u.traversalSeed===!0&&u.ownerSymbol&&e.symbolStates.has(u.ownerSymbol)).map(u=>ar(u.ownerSymbol)),c=e.literalHits.filter(u=>u.query===n.query&&u.traversalSeed===!0&&!u.ownerSymbol&&u.ownerStartLine!==null&&u.ownerStartLine!==void 0&&u.ownerEndLine!==null&&u.ownerEndLine!==void 0).map(u=>Fi(Cc(e.db,IO(u)))),l=pe(n.kind==="symbol"?[...o,...s]:a.length+c.length>0?[...a,...c]:n.seedRegionIds??[]);return{id:i,kind:n.kind,query:n.query,status:n.status,nodeIds:n.status==="ambiguous"?[]:l,candidateNodeIds:n.status==="ambiguous"?l:[],omittedCandidates:n.omittedSymbolCandidates??0}})}function MO(e){let t=new Map;for(let n of e)for(let r of[...n.nodeIds,...n.candidateNodeIds]){let i=t.get(r)??[];i.push(n.id),t.set(r,i)}return t}function TO(e,t,n){let r=e.relations.flatMap(s=>[s.fromBoundaryParticipant,s.toBoundaryParticipant].flatMap(a=>a?.ownerName?[a]:[])),i=e.regions.map(s=>({id:s.id,kind:"structural-region",label:s.label,disposition:"folded",location:null,anchorIds:pe(n.get(s.id)??[]),attributes:{workspace:s.workspace,structuralPath:s.structuralPath,minimumDepth:s.minDepth,files:s.fileCount,symbols:s.symbolCount,expanded:s.expanded}}));for(let s of e.symbolStates.values()){let a=e.regionForFile.get(s.definition.relativePath)?.id;if(!a)throw new Error(`System-map symbol ${s.definition.symbol} has no structural region.`);let c=ar(s.definition.symbol),l=xc(e.db,s.definition);i.push({id:c,kind:"symbol",label:T(s.definition.symbol),disposition:(n.get(c)?.length??0)>0?"emitted":"folded",location:{file:s.definition.relativePath,line:s.definition.startLine,endLine:s.definition.endLine},anchorIds:pe(n.get(c)??[]),attributes:{regionId:a,depth:s.depth,leaf:s.definition.leaf??T(s.definition.symbol),referenceScope:s.referenceScope,...l.evidence.length>0?{publicEntry:!0,publicEntryPriority:l.priority,publicEntryEvidence:l.evidence.join(",")}:{}}})}for(let s of t){let a=e.regionForFile.get(s.file)?.id;if(!a)throw new Error(`Source construct ${s.name} has no structural region.`);let c=Fi(s),u=r.find(m=>m.file===s.file&&m.line>=s.startLine&&m.line<=s.endLine)?.ownerName??s.name,d=wO(e.db,s);i.push({id:c,kind:"source-construct",label:u,disposition:(n.get(c)?.length??0)>0?"emitted":"folded",location:{file:s.file,line:s.startLine,endLine:s.endLine},anchorIds:pe(n.get(c)??[]),attributes:{regionId:a,leaf:u,sourceOwned:!0,...d.evidence.length>0?{publicEntry:!0,publicEntryPriority:d.priority,publicEntryEvidence:d.evidence.join(",")}:{}}})}let o=new Map;for(let s of e.relations)s.fromBoundaryParticipant&&o.set(s.fromBoundaryParticipant.observationId,s.fromBoundaryParticipant),s.toBoundaryParticipant&&o.set(s.toBoundaryParticipant.observationId,s.toBoundaryParticipant);for(let s of[...o.values()].sort((a,c)=>a.observationId.localeCompare(c.observationId))){let a=e.regionForFile.get(s.file)?.id;if(!a)throw new Error(`Runtime-boundary participant ${s.observationId} has no structural region.`);i.push({id:Wd(s.observationId),kind:"runtime-boundary-participant",label:s.address||s.ownerName||`${s.role} ${s.action}`,disposition:"folded",location:{file:s.file,line:s.line,endLine:s.endLine},anchorIds:[],attributes:{regionId:a,action:s.action,protocol:s.protocol,role:s.role,...s.address?{address:s.address}:{},ownerSymbol:s.ownerSymbol}})}return i}function kO(e,t,n,r,i,o,s,a,c,l=!1){let u=r?ar(r):null;if(u&&t.has(u)&&!me(r))return u;let d=i?Wd(i.observationId):null;if(l&&d&&t.has(d))return d;let m=o?Fi(Cc(e,o)):null;if(m&&t.has(m))return m;if(d&&t.has(d))return d;let p=c===null?null:(n.get(a)??[]).filter(f=>f.startLine<=c&&f.endLine>=c).sort((f,g)=>f.endLine-f.startLine-(g.endLine-g.startLine)||f.startLine-g.startLine)[0]??null;return p?Fi(p):u&&t.has(u)?u:s}function AO(e,t,n){let r=new Set(t.map(l=>l.id)),i=_e(n,l=>l.file),o=(l,u,d,m,p,f,g=!1)=>kO(e.db,r,i,l,u,d,m,p,f,g),s=[];for(let l of e.symbolStates.values()){let u=e.regionForFile.get(l.definition.relativePath)?.id;if(!u)continue;let d=ar(l.definition.symbol);s.push({id:yt("edge","structural-membership",u,d),kind:"structural-membership",fromNodeId:u,toNodeId:d,directed:!0,disposition:"folded",semantics:cc("structural-membership"),evidence:[{method:"indexed-definition-file",strength:"exact",identity:l.definition.symbol,location:{file:l.definition.relativePath,line:l.definition.startLine,endLine:l.definition.endLine}}]})}let a=_e(e.relations,l=>`${o(l.fromSymbol,l.fromBoundaryParticipant,l.fromSourceConstruct,l.fromRegionId,l.fromFile,l.line,l.kind==="runtime-boundary")}\0${o(l.toSymbol,l.toBoundaryParticipant,l.toSourceConstruct,l.toRegionId,l.toFile,null)}\0${l.kind}`),c=new Set;for(let l of a.values()){let u=l[0],d=o(u.fromSymbol,u.fromBoundaryParticipant,u.fromSourceConstruct,u.fromRegionId,u.fromFile,u.line,u.kind==="runtime-boundary"),m=o(u.toSymbol,u.toBoundaryParticipant,u.toSourceConstruct,u.toRegionId,u.toFile,null);if(u.kind==="runtime-boundary"&&u.fromBoundaryParticipant){let f=Wd(u.fromBoundaryParticipant.observationId),g=o(u.fromSymbol,void 0,u.fromSourceConstruct,u.fromRegionId,u.fromFile,u.line);g!==f&&!c.has(f)&&(c.add(f),s.push({id:yt("edge","boundary-observation",g,f),kind:"boundary-observation",fromNodeId:g,toNodeId:f,directed:!0,disposition:"folded",semantics:cc("boundary-observation"),evidence:[{method:"runtime-boundary-observation-owner",strength:u.strength??"unknown",identity:u.fromBoundaryParticipant.observationId,location:{file:u.fromBoundaryParticipant.file,line:u.fromBoundaryParticipant.line,endLine:u.fromBoundaryParticipant.endLine}}]}))}(d===m?t.find(f=>f.id===d):null)?.kind!=="structural-region"&&s.push({id:yt("edge",u.kind,d,m),kind:u.kind,fromNodeId:d,toNodeId:m,directed:!0,disposition:"folded",semantics:gv(u),evidence:UO(l.map(f=>({method:f.evidence,strength:f.strength??"unknown",identity:f.kind==="runtime-boundary"&&f.runtimeBoundaryKey?f.runtimeBoundaryKey:`${f.fromSymbol??f.fromFile} -> ${f.toSymbol??f.toFile}`,location:f.line===null?null:{file:f.fromFile,line:f.line}})))})}return s}function FO(e,t,n){for(let i of e.externalBoundaries){let o=yt("external",i.kind,i.name),s=pe(i.fromRegionIds);t.push({id:o,kind:i.kind,label:i.name,disposition:"folded",location:null,anchorIds:[],attributes:{}});for(let a of s)n.push({id:yt("edge",i.kind,a,o),kind:i.kind,fromNodeId:a,toNodeId:o,directed:!0,disposition:"folded",semantics:cc("external-import"),evidence:[{method:"indexed-or-source-import",strength:"mixed",identity:`${a} -> ${i.name}`,location:null}]})}let r=[];return e.boundaryFrontiers.forEach((i,o)=>{let s=e.regionForFile.get(i.file)?.id;if(!s)throw new Error(`Runtime-boundary frontier ${i.observationId} has no system-map region.`);let a=yt("unsupported","runtime-boundary",i.observationId,String(o)),c=yt("edge","runtime-boundary-frontier",s,a);t.push({id:a,kind:"runtime-boundary-frontier",label:i.address,disposition:"unsupported",location:{file:i.file,line:i.line},anchorIds:[],attributes:{action:i.action,strength:i.strength,owner:i.ownerShortName}}),n.push({id:c,kind:"runtime-boundary-frontier",fromNodeId:s,toNodeId:a,directed:!0,disposition:"unsupported",evidence:[{method:"runtime-boundary-extractor",strength:i.strength,identity:i.observationId,location:{file:i.file,line:i.line}}]}),r.push({id:yt("frontier","runtime-boundary",i.observationId,String(o)),kind:"runtime-boundary",direction:"unresolved",fromNodeIds:[s],edgeIds:[c],memberNodeIds:[a],memberCount:1,disposition:"unsupported",reason:i.reason,expansion:null})}),r}function NO(e,t){let n=t.topologyFrontiers.some(f=>f==="frontier:program-facts"),r=rC(e,{expandedFrontierIds:t.topologyFrontiers.filter(f=>f!=="frontier:program-facts"),routeIds:t.routeIds}),i=r.nodes.filter(f=>f.disposition==="emitted"||r.anchors.some(g=>g.status==="matched"&&g.nodeIds.includes(f.id))),o=t.relations.filter(f=>i.some(g=>OO(f,g))),s=t.boundaryFrontiers.filter(f=>i.some(g=>BO(f,g))),a=Iv(t.db,o,i),c=Lv(t.db,i),l=$v(t.db,i,s),u=[...a.nodes,...c.nodes,...l.nodes].map(f=>n&&f.disposition==="folded"?{...f,disposition:"emitted"}:f),d=[...a.edges,...c.edges,...l.edges].map(f=>n&&f.disposition==="folded"?{...f,disposition:"emitted"}:f),m=n?null:$O(i,u,d),p=Sc({anchors:r.anchors,nodes:[...r.nodes,...u],edges:[...r.edges,...d],paths:r.paths,frontiers:[...r.frontiers,...a.frontiers,...c.frontiers,...l.frontiers,...m?[m]:[]],scope:r.coverage.scope,blindSpots:[...r.coverage.blindSpots,...a.blindSpots,...c.blindSpots,...l.blindSpots],incompleteReasons:r.coverage.status==="incomplete"?[r.coverage.explanation]:[],...r.routeCatalog?{routeCatalog:r.routeCatalog}:{}});p.completion=r.completion;for(let f of p.frontiers)f.disposition==="folded"&&(f.id.startsWith("frontier:program-facts:")||(f.expansion=jO(t,f.id)));return p}function _O(e){let t=PO(e),n=DO(e,t),r=TO(e,t,MO(n)),i=AO(e,r,t),o=FO(e,r,i);return NO(Sc({anchors:n,nodes:r,edges:i,paths:[],frontiers:o,scope:`explicit anchors; relations ${e.requestedRelationKinds.join(", ")}; depth ${e.maxDepth}; evidence floor ${e.evidenceFloor}; source scopes ${e.includedSourceScopes.join(", ")}`,blindSpots:[...e.blindSpots],incompleteReasons:e.closureStatus==="incomplete"?[`${e.omittedSymbolCandidates} ambiguous symbol candidate(s) were omitted`]:[]}),e)}function OO(e,t){if(e.fromSymbol&&t.id===ar(e.fromSymbol)||e.toSymbol&&t.id===ar(e.toSymbol))return!0;if(!t.location)return!1;let n=t.location.endLine??t.location.line;return t.location.file===e.fromFile&&e.line!==null&&e.line>=t.location.line&&e.line<=n||t.location.file===e.toFile}function BO(e,t){if(!t.location||t.location.file!==e.file)return!1;let n=t.location.endLine??t.location.line;return e.line>=t.location.line&&e.line<=n||t.label===e.ownerShortName||typeof e.ownerShortName=="string"&&t.label.includes(e.ownerShortName)}function $O(e,t,n){let r=pe(t.filter(o=>o.disposition==="folded").map(o=>o.id)),i=pe(n.filter(o=>o.disposition==="folded").map(o=>o.id));return r.length===0&&i.length===0?null:{id:yt("frontier","program-facts"),kind:"program-facts",direction:"outgoing",fromNodeIds:pe(e.map(o=>o.id)),edgeIds:i,memberNodeIds:r,memberCount:r.length,disposition:"folded",reason:"Control, data, state, and temporal facts are folded beneath the selected high-level owners.",expansion:null}}function jO(e,t){return`scip-query system-map ${[...e.anchors.flatMap(r=>r.kind==="literal"?[`--search ${ye(r.query)}`]:[`--symbol ${ye(r.query)}`]),`--depth ${e.maxDepth}`,...e.requestedRelationKinds.map(r=>`--relation ${ye(r)}`),`--evidence-floor ${ye(e.evidenceFloor)}`,...e.includedSourceScopes.map(r=>`--source-scope ${ye(r)}`),...e.fullLiteralTraversal?["--full-literal-traversal"]:[],`--topology-characters ${e.maxTopologyCharacters}`,...e.expandedRegionIds.map(r=>`--expand ${ye(r)}`),...e.topologyFrontiers.map(r=>`--frontier ${ye(r)}`),...e.routeIds.map(r=>`--route ${ye(r)}`),`--frontier ${ye(t)}`].join(" ")}`}function HO(e){let t=new Set;for(let n of e.nodes){if(n.disposition!=="emitted")continue;n.kind==="structural-region"&&t.add(n.id);let r=n.attributes.regionId;typeof r=="string"&&t.add(r)}return t}function UO(e){let t=new Map;for(let n of e){let r=n.location?`${n.location.file}:${n.location.line}`:"";t.set(`${n.method}\0${n.strength}\0${n.identity??""}\0${r}`,n)}return[...t.values()].sort((n,r)=>n.method.localeCompare(r.method)||(n.identity??"").localeCompare(r.identity??"")||(n.location?.file??"").localeCompare(r.location?.file??"")||(n.location?.line??0)-(r.location?.line??0))}function yt(...e){return e.map(t=>encodeURIComponent(t)).join(":")}function ar(e){return yt("symbol",e)}function qO(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function GO(e,t,n,r,i,o,s,a,c,l){let u=[...r].sort((g,h)=>SC(g,h,i)),m=u.slice(0,oC).map(g=>g.id),p=u.slice(oC).map(g=>g.id),f=[...e.map(g=>`--search ${ye(g)}`),...t.map(g=>`--symbol ${ye(g)}`),`--depth ${n}`,...o.map(g=>`--relation ${ye(g)}`),`--evidence-floor ${ye(s)}`,...a.map(g=>`--source-scope ${ye(g)}`),...c?["--full-literal-traversal"]:[],`--topology-characters ${l}`,...m.map(g=>`--expand ${ye(g)}`)];return{command:m.length===0?null:`scip-query system-map ${f.join(" ")}`,regionCount:m.length,regionIds:m,candidateRegionCount:r.length,omittedRegionIds:p}}function zO(e,t,n,r,i,o,s,a,c,l,u,d,m){let p=[...c].sort((I,k)=>SC(I,k,u)).filter(I=>!m||m.has(I.id)||d.has(I.id)),f=l.length>0?Math.floor(a*.4):0,g=a-f,h=new Set,b=0;for(let I of p){let k=uC(I);!d.has(I.id)&&h.size>0&&b+k>g||(h.add(I.id),b+=k)}let S=l.filter(I=>h.has(I.fromRegionId)&&h.has(I.toRegionId)).sort(KO),y=[];for(let I of S){let k=dC(I);y.length>0&&b+k>a||(y.push(Rc(I)),b+=k)}let x=c.filter(I=>!h.has(I.id)).map(I=>I.id).sort(),v=new Set(y),C=l.filter(I=>!v.has(Rc(I))).length,R=c.reduce((I,k)=>I+uC(k),0)+l.reduce((I,k)=>I+dC(k),0),E=p.every(I=>h.has(I.id))&&y.length===S.length,w=[...e.map(I=>`--search ${ye(I)}`),...t.map(I=>`--symbol ${ye(I)}`),`--depth ${n}`,...r.map(I=>`--relation ${ye(I)}`),`--evidence-floor ${ye(i)}`,...o.map(I=>`--source-scope ${ye(I)}`),...s?["--full-literal-traversal"]:[],`--topology-characters ${Math.max(a,R)}`];return{maxCharacters:a,estimatedCharacters:b,totalEstimatedCharacters:R,regionIds:[...h],omittedRegionIds:x,relationKeys:y,omittedRelations:C,complete:E,expansionCommand:E?null:`scip-query system-map ${w.join(" ")}`}}function uC(e){return 120+e.id.length+e.anchorQueries.join(",").length+e.relationKinds.join(",").length+e.notableSymbols.slice(0,2).reduce((t,n)=>t+n.shortName.length+n.file.length,0)}function dC(e){return 70+e.fromRegionId.length+e.toRegionId.length+e.kinds.join(",").length+e.evidence.join(",").length}function KO(e,t){let n=r=>r.kinds.includes("runtime-boundary")?0:r.kinds.includes("contract-symbol")?1:2;return n(e)-n(t)||t.relationCount-e.relationCount||Rc(e).localeCompare(Rc(t))}function Rc(e){return`${e.fromRegionId}\0${e.toRegionId}`}function SC(e,t,n){let r=a=>n.has(a.id)?0:1,i=a=>a.sourceFileCount===0?1:0,o=a=>a.symbolCount+a.literalHitCount>0?0:1,s=a=>[...a.incomingRegionIds,...a.outgoingRegionIds].filter(c=>n.has(c)).length;return r(e)-r(t)||o(e)-o(t)||i(e)-i(t)||e.minDepth-t.minDepth||s(t)-s(e)||t.literalHitCount-e.literalHitCount||e.testFileCount-t.testFileCount||e.label.localeCompare(t.label)}function WO(e){let t=[],n=new Set;for(let i of e.filter(o=>o.expanded)){for(let c of i.symbols)c.origins.includes("symbol-anchor")&&n.add(c.file);let o=_e(i.symbols,c=>c.file),s=_e(i.literalHits,c=>c.file),a=[...i.files].sort((c,l)=>YO(c,l,o,s));for(let c of a){let l=(o.get(c.file)??[]).sort(pv)[0];if(l){t.push({kind:"symbol",regionId:i.id,file:l.file,line:l.startLine,endLine:l.endLine,label:l.shortName});continue}let u=(s.get(c.file)??[]).sort(RC)[0];u&&t.push({kind:"literal",regionId:i.id,file:u.file,line:u.line,endLine:null,label:u.ownerShortName??u.query})}}let r=VO(t,n);return{command:r.length===0?null:`scip-query inspect ${r.map(i=>`--at ${ye(`${i.file}:${i.line+1}`)}`).join(" ")} --view behavior`,definitionCommand:null,candidateAnchors:t.length,selectedAnchors:r.length,omittedAnchors:t.length-r.length,anchors:r}}function VO(e,t){let n=[..._e(e,s=>s.regionId).values()],r=[],i=new Set,o=Math.min(lO,24);for(let s of e)if(!(!t.has(s.file)||i.has(s.file))&&(r.push(s),i.add(s.file),r.length===o))return r;for(let s=0;r.length<o;s+=1){let a=!1;for(let c of n){let l=c[s];if(l&&(a=!0,!i.has(l.file)&&(r.push(l),i.add(l.file),r.length===o)))break}if(!a)break}return r}function YO(e,t,n,r){let i=a=>a.kind==="test"?2:a.kind==="barrel"?1:0,o=a=>(r.get(a.file)??[]).some(c=>c.traversalSeed)?0:1,s=a=>{let c=n.get(a.file)??[];return Math.min(5,...c.map(l=>Ti(l.origins)))};return i(e)-i(t)||o(e)-o(t)||s(e)-s(t)||e.depth-t.depth||e.file.localeCompare(t.file)}function ye(e){return`'${e.replaceAll("'","'\\''")}'`}function JO(e,t,n,r){let i=[];for(let o of Z(e,{includeIgnored:!1})){let s=V(e,o);if(s.length===0)continue;let a=[];for(let u=0;u<s.length;u+=1){let d=s[u]??"";d.includes(n)&&a.push({line:u,sourceLine:d})}if(a.length===0)continue;let c=t.definitionsForFile(o),l=K(e,o)?.callables??[];for(let{line:u,sourceLine:d}of a){let m=Ne(c,u),p=_n(l,u),f=m&&!me(m.symbol)?m:null,g=f?.startLine??p?.startLine??m?.startLine??u,h=f?.endLine??p?.endLine??m?.endLine??u,b=po(e,o,u,g,h),S=r.has(`${o}\0${u}`),y=!!(f?.isFunctionLike||p);i.push({relativePath:o,line:u,sourceLine:d,ownerSymbol:f?.symbol??null,ownerShortName:f?T(f.symbol):p?.name??(m?T(m.symbol):null),ownerStartLine:b.startLine,ownerEndLine:b.endLine,matchKind:eB(d,n),seedPriority:S?0:y?1:2})}}return i}function XO(e,t){let n={"exact-value":0,boundary:1,embedded:2};return e.seedPriority-t.seedPriority||n[e.matchKind]-n[t.matchKind]||e.relativePath.localeCompare(t.relativePath)||e.line-t.line}function mC(e){return`${e.relativePath}\0${e.line}`}function qd(e,t,n){let i=_n(K(e,t)?.callables??[],n)??vC(e,t,n);if(!i)return null;let o=po(e,t,n,i.startLine,i.endLine);return{file:t,name:i.name,startLine:o.startLine,endLine:o.endLine}}function vC(e,t,n){let r=J(e,t)?.rootNode;if(!r||r.startPosition.row>n||r.endPosition.row<n)return null;let i=Kd(r,n);for(;i;){if(i.type==="variable_declarator"){let s=i.childForFieldName("name")??i.namedChild(0),a=i.childForFieldName("value")??i.namedChild(1);if(s?.type==="identifier"&&a&&Gd(a,n))return{name:s.text,startLine:i.startPosition.row,endLine:i.endPosition.row}}if(i.type==="pair"){let s=i.childForFieldName("key")??i.namedChild(0),a=i.childForFieldName("value")??i.namedChild(1),c=s?.text.replace(/^(?:['"])(.*)(?:['"])$/u,"$1");if(c&&a&&/^[A-Za-z_$][\w$]*$/u.test(c)&&Gd(a,n))return{name:c,startLine:i.startPosition.row,endLine:i.endPosition.row}}i=i.parent}let o=fi(e,t,n);return o?{name:`source@${n+1}`,startLine:o.startLine,endLine:o.endLine}:null}function Gd(e,t){return["arrow_function","function_expression","generator_function","generator_function_declaration"].includes(e.type)&&e.startPosition.row<=t&&e.endPosition.row>=t?!0:e.namedChildren.some(n=>n.startPosition.row<=t&&n.endPosition.row>=t&&Gd(n,t))}function Kd(e,t){let n=e.namedChildren.filter(r=>r.startPosition.row<=t&&r.endPosition.row>=t).sort((r,i)=>r.endIndex-r.startIndex-(i.endIndex-i.startIndex)||r.startPosition.row-i.startPosition.row)[0];return n?Kd(n,t):e}function QO(e,t){let n=t.match(/^(.+):(\d+)(?:-(\d+))?$/u);if(!n)return null;let r=ei(e,n[1],{allowMultiple:!1})[0]?.relativePath;if(!r)return null;let i=Math.max(0,Number.parseInt(n[2],10)-1),o=n[3]?Math.max(i,Number.parseInt(n[3],10)-1):i,s=(K(e,r)?.callables??[]).filter(a=>a.startLine<=i&&a.endLine>=o).sort((a,c)=>a.endLine-a.startLine-(c.endLine-c.startLine)||a.startLine-c.startLine)[0];return s?{file:r,name:s.name,startLine:s.startLine,endLine:s.endLine}:null}function ZO(e){return{symbol:`source-construct:${e.file}:${e.startLine}:${e.endLine}:${e.name}`,shortName:e.name,relativePath:e.file,startLine:e.startLine,endLine:e.endLine}}function eB(e,t){let n=/[\p{L}\p{N}_$]/u,r=e.indexOf(t);for(;r>=0;){let i=e[r-1]??"",o=e[r+t.length]??"";if((i==="'"||i==='"'||i==="`")&&o===i)return"exact-value";if(!n.test(i)&&!n.test(o))return"boundary";r=e.indexOf(t,r+Math.max(1,t.length))}return"embedded"}function zd(e){return q(e)==="test"?!1:!/(?:^|[/._-])(?:fixtures?|mocks?|previews?|demos?|examples?|stories)(?:[/._-]|$)/iu.test(e)}function tB(e,t){return e.matchKind!=="embedded"&&t(e.relativePath)&&(wl(e.relativePath)!=="production"||zd(e.relativePath))}function nB(e,t){let n=[...t].sort(rB),r=[],i=new Set;for(let o of n)if(!i.has(o.relativePath)&&(r.push(o),i.add(o.relativePath),r.length>=iC))break;for(let o of n){if(r.length>=iC)break;r.includes(o)||r.push(o)}return r.map(o=>({query:e,file:o.relativePath,line:o.line,ownerSymbol:o.ownerSymbol,ownerShortName:o.ownerShortName,ownerStartLine:o.ownerStartLine,ownerEndLine:o.ownerEndLine,sourceLine:o.sourceLine.trim(),matchKind:o.matchKind,traversalSeed:!1}))}function rB(e,t){let n={"exact-value":0,boundary:1,embedded:2};return n[e.matchKind]-n[t.matchKind]||+(t.ownerSymbol!==null)-+(e.ownerSymbol!==null)||+!zd(e.relativePath)-+!zd(t.relativePath)||e.relativePath.localeCompare(t.relativePath)||e.line-t.line}function iB(e,t){let n=new Map;for(let r of t){let i=oB(r.relativePath);n.set(i,(n.get(i)??0)+1)}return[...n].sort(([r,i],[o,s])=>s-i||r.localeCompare(o)).slice(0,aO).map(([r])=>`scip-query search ${ye(e)} --scope ${ye(r)}`)}function oB(e){let t=e.split("/").filter(Boolean);if(t.length<=1)return e;let n=t.slice(0,-1),r=n.lastIndexOf("src");return r>=0?n.slice(0,Math.min(n.length,r+3)).join("/"):n.slice(0,Math.min(n.length,3)).join("/")}function sB(e,t,n){let r=t.callerFileMap([n],{semantic:!1}).get(n.symbolId)??new Set,i=[];for(let o of[...r].sort()){let s=ae(e,o).filter(u=>u.importedName===n.leaf&&u.sourcePath!==null&&Fe(u.sourcePath,n.relativePath)),a=new Set;if(s.length>0)for(let u of s)a.add(u.localName??u.importedName);else n.leaf&&a.add(n.leaf);let c=[...new Set([...a].flatMap(u=>gn(e,o,u)))].sort((u,d)=>u-d);if(c.length===0){i.push({file:o,line:null,enclosingSymbol:null});continue}let l=t.definitionsForFile(o);for(let u of c)i.push({file:o,line:u,enclosingSymbol:Ne(l,u)?.symbol??null})}return i}function aB(e,t){let n=e.all(`SELECT DISTINCT gs.symbol, def_d.relative_path AS from_file
78
- FROM mentions m
79
- JOIN chunks c ON m.chunk_id = c.id
80
- JOIN documents imp_d ON c.document_id = imp_d.id
81
- JOIN global_symbols gs ON m.symbol_id = gs.id
82
- LEFT JOIN (
83
- SELECT m2.symbol_id, c2.document_id
84
- FROM mentions m2
85
- JOIN chunks c2 ON m2.chunk_id = c2.id
86
- WHERE m2.role = 1
87
- GROUP BY m2.symbol_id
88
- ) sym_def ON sym_def.symbol_id = gs.id
89
- LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
90
- WHERE imp_d.relative_path = ? AND m.role = 2
91
- ORDER BY def_d.relative_path, gs.symbol`,t);return n.length>0?n.map(r=>({symbol:r.symbol,shortName:T(r.symbol),importedName:pC(T(r.symbol)),localName:pC(T(r.symbol)),fromFile:r.from_file,source:"compiler"})):ae(e,t).map(r=>{let i=cB(r.importedName,r.localName,r.kind),o=r.localName??r.importedName,s=r.importedName==="default"?o:r.importedName;return{symbol:i,shortName:i,importedName:s,localName:o,fromFile:r.sourcePath,source:"parsed-source"}})}function pC(e){return e.slice(e.lastIndexOf(":")+1).replace(/\(\)$/u,"")||e}function cB(e,t,n){return n==="namespace"&&e==="*"&&t?`* as ${t}`:n==="default"&&t?`default as ${t}`:n==="side-effect"?"(side effect import)":t&&t!==e?`${e} as ${t}`:e}function cr(e,t,n){let r=Qe(e,n);if(!r.match)return{matches:[],total:0,omitted:0};let i=[r.match,...r.candidates.map(s=>Qe(e,s.symbol).match)].filter(s=>s!==null),o=new Map;for(let s of i){let a=t.definitionsForFile(s.relativePath).find(c=>c.symbol===s.symbol);a&&o.set(a.symbol,a)}return{matches:[...o.values()],total:r.total,omitted:Math.max(0,r.total-o.size)}}function lB(e){return{symbol:e.symbol,shortName:T(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine}}function bt(e,t){let n=[t.kind,t.fromFile,t.fromSymbol??"",t.toFile,t.toSymbol??"",t.fromBoundaryParticipant?.observationId??"",t.toBoundaryParticipant?.observationId??"",t.fromSourceConstruct?nn(t.fromSourceConstruct):"",t.toSourceConstruct?nn(t.toSourceConstruct):"",t.runtimeBoundaryKey??"",t.line??""].join("\0");e.set(n,t)}function Ni(e){return{observationId:e.id,action:e.action,protocol:e.protocol,role:e.role,address:CC(e),file:e.source.file,line:e.source.startLine,endLine:e.source.endLine,ownerName:e.owner.name,ownerSymbol:e.owner.symbol}}function vc(e,t){let n=V(e,t.source.file);return ot(e,t.source.file,0,Math.max(0,n.length-1),[t.source.startLine])}function fC(e,t){let n=[...e.values()];for(let r of[t.owner,t.source]){let i=n.filter(o=>o.file===r.file&&o.startLine<=r.startLine&&o.endLine>=r.startLine).sort((o,s)=>o.endLine-o.startLine-(s.endLine-s.startLine)||o.startLine-s.startLine)[0];if(i)return i}return null}function gC(e,t,n,r,i){let o=[],s=n.get(e.id);s!==void 0&&s<=t&&o.push(s);for(let a of r.values()){if(a.depth>t)continue;let c=a.definition;hC(c,e)&&o.push(a.depth)}for(let a of i.values())a.depth>t||hC(a,e)&&o.push(a.depth);return o.length>0?Math.min(...o):null}function hC(e,t){let n=e.relativePath??e.file;return[t.owner,t.source].some(r=>n===r.file&&e.startLine<=r.startLine&&e.endLine>=r.startLine)}function Wd(e){return yt("runtime-boundary-participant",e)}function uB(e,t,n){let r=ht(e,n),i=ht(t,n);return r.relativeDir!==i.relativeDir?!0:/(?:^|\/)(?:contracts?|schemas?|db\/schema)(?:\/|$)/u.test(t)}function dB(e,t,n){return Xo(e,n).id===Xo(t,n).id}function mB(e,t,n,r){if(e.referenceScope==="all")return!0;let i=Xo(t,r).id;return[...n.values()].some(s=>s.promoteBoundaryImports&&Xo(s.file,r).id===i)?!0:e.referenceScope!=="cross-workspace-or-forward"?!1:ht(t,r).relativeDir!==ht(e.definition.relativePath,r).relativeDir}function pB(e,t){let n={none:0,"forward-regions":1,"cross-workspace-or-forward":2,all:3};return n[e]>=n[t]?e:t}function fB(e,t){let n=aC.get(e);if(n)return n;let r=t.fileDependencyGraph(),i={fileGraph:r,reverseFileGraph:gB(r),workspaces:hB(t.sourceFiles()),runtimeBoundaries:Js(e)};return aC.set(e,i),i}function gB(e){let t=new Map;for(let[n,r]of e)for(let i of r){let o=t.get(i)??new Set;o.add(n),t.set(i,o)}return t}function ht(e,t){return t.find(n=>e===n.relativeDir||e.startsWith(`${n.relativeDir}/`))??{name:"root",relativeDir:""}}function hB(e){let t=new Set(["apps","packages","services","crates","libs","tools"]),n=new Map;for(let r of e){let i=r.split("/").filter(Boolean);if(i.length<3||!t.has(i[0]))continue;let o=`${i[0]}/${i[1]}`;n.set(o,{name:i[1],relativeDir:o})}return[...n.values()].sort((r,i)=>i.relativeDir.length-r.relativeDir.length)}function Xo(e,t){let n=ht(e,t),i=(n.relativeDir?e.slice(n.relativeDir.length+1):e).split("/").filter(Boolean);i[0]==="src"&&i.shift();let o=yB(i);return{id:`region:${n.relativeDir||"root"}:${o}`,label:`${n.name}:${o}`,workspace:n.name,structuralPath:o}}function yB(e){if(e.length<=1)return"root";let t=e[0],n=e[1];return["components","features","modules"].includes(t)?`${t}/${n}`:t==="db"?`${t}/${n}`:["contracts","routes","services"].includes(t)?t:t==="tests"||t==="__tests__"?"tests":t}function bB(e,t,n,r,i,o,s){let a=_e([...e.values()],p=>o.get(p.file).id),c=_e([...t.values()],p=>o.get(p.definition.relativePath).id),l=_e(n,p=>o.get(p.file).id),u=new Map;for(let p of r)for(let f of new Set([p.fromRegionId,p.toRegionId])){let g=u.get(f)??[];g.push(p),u.set(f,g)}let d=_e(i,p=>p.toRegionId),m=_e(i,p=>p.fromRegionId);return[...a.entries()].map(([p,f])=>{let g=o.get(f[0].file),h=c.get(p)??[],b=l.get(p)??[],S=u.get(p)??[],y=s.has(p),x=h.map(CB).sort(IB).slice(0,cO),v=f.filter(C=>q(C.file)==="test").length;return{id:p,label:g.label,workspace:g.workspace,structuralPath:g.structuralPath,minDepth:Math.min(...f.map(C=>C.depth)),fileCount:f.length,sourceFileCount:f.length-v,testFileCount:v,symbolCount:h.length,literalHitCount:b.length,anchorQueries:pe([...b.map(C=>C.query),...h.flatMap(C=>[...C.anchorQueries])]),relationKinds:pe(S.map(C=>C.kind)),incomingRegionIds:pe((d.get(p)??[]).map(C=>C.fromRegionId)),outgoingRegionIds:pe((m.get(p)??[]).map(C=>C.toRegionId)),memberCallCandidateRelationCount:S.filter(C=>C.evidence==="ast-member-import-candidate").length,notableSymbols:x,omittedNotableSymbols:Math.max(0,h.length-x.length),expanded:y,files:y?f.map(SB).sort(wB):[],symbols:y?h.map(vB).sort(LB):[],literalHits:y?[...b].sort(RC):[],relations:y?[...S].sort(xC):[]}}).sort((p,f)=>p.minDepth-f.minDepth||p.label.localeCompare(f.label))}function SB(e){return{file:e.file,kind:q(e.file),depth:e.depth,origins:pe([...e.origins])}}function vB(e){return{symbol:e.definition.symbol,shortName:T(e.definition.symbol),file:e.definition.relativePath,startLine:e.definition.startLine,endLine:e.definition.endLine,depth:e.depth,origins:pe([...e.origins]),anchorQueries:pe([...e.anchorQueries]),referenceExpansion:e.referenceScope!=="none",referenceScope:e.referenceScope}}function CB(e){return{shortName:T(e.definition.symbol),file:e.definition.relativePath,origins:pe([...e.origins])}}function xB(e){return[..._e(e.filter(n=>n.fromRegionId!==n.toRegionId),n=>`${n.fromRegionId}\0${n.toRegionId}`).values()].map(n=>({fromRegionId:n[0].fromRegionId,toRegionId:n[0].toRegionId,kinds:pe(n.map(r=>r.kind)),relationCount:n.length,fromFiles:pe(n.map(r=>r.fromFile)),toFiles:pe(n.map(r=>r.toFile)),fromSymbols:pe(n.flatMap(r=>r.fromSymbol?[T(r.fromSymbol)]:[])),toSymbols:pe(n.flatMap(r=>r.toSymbol?[T(r.toSymbol)]:[])),evidence:pe(n.map(r=>r.evidence)),strengths:pe(n.map(r=>r.strength??"unknown"))})).sort((n,r)=>n.fromRegionId.localeCompare(r.fromRegionId)||n.toRegionId.localeCompare(r.toRegionId))}function RB(e,t){return[...e.values()].map(n=>({kind:"external-import",name:n.name,fromRegionIds:pe([...n.fromFiles].flatMap(r=>{let i=t.get(r);return i?[i.id]:[]})),fromFiles:pe([...n.fromFiles])})).sort((n,r)=>n.name.localeCompare(r.name))}function EB(e,t,n,r){let i=e.kind==="literal"?t.filter(o=>o.query===e.query).map(o=>o.file):[...n.values()].filter(o=>o.anchorQueries.has(e.query)).map(o=>o.definition.relativePath);return pe(i.map(o=>r.get(o)?.id).filter(o=>!!o))}function CC(e){return e.keyParts.map(t=>`${t.name}=${t.value}`).join(" ")}function pe(e){return[...new Set(e)].sort()}function xC(e,t){return e.fromRegionId.localeCompare(t.fromRegionId)||e.toRegionId.localeCompare(t.toRegionId)||e.kind.localeCompare(t.kind)||e.fromFile.localeCompare(t.fromFile)||e.toFile.localeCompare(t.toFile)||(e.line??-1)-(t.line??-1)}function IB(e,t){return Ti(e.origins)-Ti(t.origins)||e.shortName.localeCompare(t.shortName)}function wB(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)}function LB(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)||e.symbol.localeCompare(t.symbol)}function RC(e,t){return e.file.localeCompare(t.file)||e.line-t.line||e.query.localeCompare(t.query)}var DB=["causal","structure","complete"],MB={causal:["execution","runtime","dataflow","state","temporal"],structure:["contract","identity","ownership","dependencies"],complete:Bt},TB=2,kB=48,EC=64,AB=5e4;function Qo(e,t,n={}){let r=ke([...t.symbols??[],...t.locations??[]]),i=ke(t.searches??[]);if(r.length===0&&i.length===0)throw new Error("evidence requires at least one positional symbol, --symbol, --at, or --search selector.");let o=n.view??"causal",s=FB(n.families,o),a=n.direction??"both",c=ke(n.subtypes??[]),l=n.connecting??!1,u=n.inventoryOnly??!1,d=ke(n.foldIds??[]),m=n.maxDepth??TB,p=n.maxEdges??kB;if(!Number.isSafeInteger(m)||m<0)throw new RangeError(`Evidence depth must be a non-negative safe integer; received ${m}.`);if(!Number.isSafeInteger(p)||p<=0)throw new RangeError(`Evidence max edges must be a positive safe integer; received ${p}.`);if(!["incoming","outgoing","both"].includes(a))throw new Error(`Unsupported graph evidence direction: ${a}.`);if(u&&d.length>0)throw new Error("Evidence fold materialization cannot be combined with --inventory-only.");let f=yC(e,{symbols:r,searches:i,maxDepth:m,maxTopologyCharacters:AB,relations:NB(s)}),g=new Map(f.nodes.map(G=>[G.id,G])),h=f.edges.filter(G=>G.disposition==="emitted"||G.disposition==="folded").flatMap(G=>_B(G,g)),b=h.filter(G=>s.includes(G.family)).filter(G=>c.length===0||c.includes(G.subtype)),S=new Set(f.anchors.flatMap(G=>G.nodeIds));if(l&&S.size<2)throw new Error("Connecting evidence requires at least two resolved root nodes.");let y=new Set(b.map(G=>G.id)),x=Vd(h,S,"incoming").filter(G=>y.has(G.id)),v=Vd(h,S,"outgoing").filter(G=>y.has(G.id)),C=Vd(h,S,"both").filter(G=>y.has(G.id)),R=HB(s,c,x,v,C),E=a==="incoming"?x:a==="outgoing"?v:C,w=l?VB(E,[...S],a):E,I=JB(w,S,a),k=[...w].sort((G,O)=>XB(G,O,I)),D=UB(k,p),F=GB(D,d),L=u?[]:d.length>0?k.filter(G=>F.has(G.id)):k,A=d.length>0?L:L.slice(0,p),P=d.length>0||u?[]:D,j=Math.max(0,L.length-A.length),B=f.frontiers.filter(G=>G.disposition==="unsupported").length,X=f.coverage.status==="incomplete"?"incomplete":j>0?"bounded":"accounted";return{kind:"graph",view:n.families&&n.families.length>0?"custom":o,families:s,selection:{direction:a,subtypes:c,connecting:l,inventoryOnly:u,foldIds:d},targets:f.anchors.map(G=>({kind:G.kind,query:G.query,status:G.status,nodeIds:[...G.nodeIds],omittedCandidates:G.omittedCandidates})),inventory:R,edges:A,folds:P,coverage:{status:X,topologyStatus:f.coverage.status,scope:f.coverage.scope,maxDepth:m,maxEdges:p,matchedEdges:k.length,eligibleEdges:L.length,returnedEdges:A.length,omittedEdges:j,frontierGroups:f.frontiers.length,unsupportedFrontiers:B,blindSpots:ke([...f.coverage.blindSpots,...mv(s)]),explanation:u?`${k.length} relationship(s) match the explicit projection; only exact inventory counts were requested.`:d.length>0?`Every relationship in ${d.length} explicitly selected recoverable fold(s) was emitted.`:X==="accounted"?"Every selected relationship in the bounded topology was emitted.":X==="bounded"?`${j} selected relationship(s) were withheld by the explicit edge budget.`:f.coverage.explanation}}}function FB(e,t){let n=e&&e.length>0?e:MB[t],r=n.filter(i=>!Bt.includes(i));if(r.length>0)throw new Error(`Unsupported graph evidence family: ${r.join(", ")}.`);return ke(n)}function NB(e){return["call","contract-symbol","import","reference","runtime-boundary"]}function _B(e,t){let n=t.get(e.fromNodeId),r=t.get(e.toNodeId);return!n||!r?[]:(e.semantics??[]).flatMap((i,o)=>{let s=BB(i);if(!s)return[];let a=ac(s,i.subtype);if(!a)throw new Error(`No graph relation provider contract is registered for ${s}/${i.subtype}.`);let c=jB(e);return a.relation.evidenceStrengths.includes(c)?[{id:`${e.id}:${o}:${s}`,family:s,semanticFamily:i.family,subtype:i.subtype,from:IC(n),to:IC(r),sourceKind:e.kind,providerId:a.provider.id,supportCeiling:a.relation.supportCeiling,establishes:a.relation.establishes,nonClaims:[...a.relation.nonClaims],recoverWith:[...a.relation.recoverWith],evidenceStrength:c,evidenceMethods:ke(e.evidence.map(l=>l.method)),evidenceConstituents:OB(e.evidence),context:i.context?{...i.context}:null,attributes:i.attributes?{...i.attributes}:null}]:[]})}function OB(e){let t=new Map;for(let n of e)t.set(`${n.method}\0${n.strength}`,n);return[...t.values()].map(({method:n,strength:r})=>({method:n,strength:r}))}function BB(e){switch(e.family){case"control":return e.context?.crossesRuntimeBoundary===!0||e.subtype==="runtime-handoff"?"runtime":"execution";case"data":return"dataflow";case"state":return"state";case"temporal":return"temporal";case"contract":return"contract";case"identity":return e.subtype.startsWith("contains")||e.subtype.startsWith("owns-")?"ownership":e.subtype.startsWith("import")?"dependencies":"identity"}}function IC(e){let t=$B(e);return{id:e.id,kind:e.kind,label:t?T(t):e.label,symbol:t,location:e.location?{...e.location}:null}}function $B(e){return e.kind!=="symbol"||!e.id.startsWith("symbol:")?null:decodeURIComponent(e.id.slice(7))}function jB(e){let t=ke(e.evidence.map(n=>n.strength));return t.length===1?t[0]:t.includes("exact")&&t.every(n=>n==="exact"||n==="derived")?"mixed":t.includes("candidate")?"candidate":t.includes("unknown")||t.length===0?"unknown":"mixed"}function Vd(e,t,n){let r=Yd(e,n),i=new Map,o=new Map,s=[...t].sort();for(let a of s)o.set(a,0);for(let a=0;a<s.length;a+=1){let c=s[a],l=o.get(c);for(let u of r.get(c)??[])i.set(u.edge.id,u.edge),!o.has(u.next)&&(o.set(u.next,l+1),s.push(u.next))}return[...i.values()]}function Yd(e,t){let n=new Map,r=(i,o,s)=>{let a=n.get(i)??[];a.push({edge:s,next:o}),n.set(i,a)};for(let i of e)t!=="incoming"&&r(i.from.id,i.to.id,i),t!=="outgoing"&&r(i.to.id,i.from.id,i);for(let i of n.values())i.sort((o,s)=>o.edge.id.localeCompare(s.edge.id)||o.next.localeCompare(s.next));return n}function HB(e,t,n,r,i){let o=new Set;for(let u of[...n,...r,...i])o.add(`${u.family}\0${u.subtype}`);if(t.length>0)for(let u of e)for(let d of t)o.add(`${u}\0${d}`);let s=u=>{let d=new Map;for(let m of u){let p=`${m.family}\0${m.subtype}`;d.set(p,(d.get(p)??0)+1)}return d},a=s(n),c=s(r),l=s(i);return[...o].map(u=>{let[d,m]=u.split("\0");return{family:d,subtype:m,incoming:a.get(u)??0,outgoing:c.get(u)??0,both:l.get(u)??0}}).sort((u,d)=>Bt.indexOf(u.family)-Bt.indexOf(d.family)||u.subtype.localeCompare(d.subtype))}function UB(e,t){let n=e.slice(t),r=new Map;for(let s of n){let a=qB(s),c=`${s.family}\0${a}`,l=r.get(c)??[];l.push(s),r.set(c,l)}let i=new Map(e.map((s,a)=>[s.id,a+1])),o=[];for(let[s,a]of[...r].sort(([c],[l])=>c.localeCompare(l))){let[c,l]=s.split("\0"),u=[...a].sort((d,m)=>d.id.localeCompare(m.id));for(let d=0;d<u.length;d+=EC){let m=u.slice(d,d+EC),p=m.map(b=>b.id),f=ke(m.map(b=>b.subtype)).sort(),g=f.length===1?f[0]:"mixed",h=[...new Set(m.flatMap(b=>[b.from.id,b.to.id]))].sort();o.push({id:WB(c,f.join("\0"),p),mode:zB(m),family:c,subtype:g,subtypes:f,region:l,edgeCount:p.length,edgeIds:p,nodeIds:h,minimumMaxEdges:Math.max(...p.map(b=>i.get(b)??e.length))})}}return o.sort((s,a)=>Bt.indexOf(s.family)-Bt.indexOf(a.family)||(s.region??"").localeCompare(a.region??"")||s.id.localeCompare(a.id))}function qB(e){let t=e.from.location?.file??`kind:${e.from.kind}`,n=e.to.location?.file??`kind:${e.to.kind}`;return t===n?t:`${t} -> ${n}`}function GB(e,t){if(t.length===0)return new Set;let n=new Map(e.map(i=>[i.id,i])),r=t.filter(i=>!n.has(i));if(r.length>0){let i=e.map(o=>o.id).sort();throw new Error(`Unknown evidence fold ${r.join(", ")} for this projection. Available folds: ${i.join(", ")||"(none)"}.`)}return new Set(t.flatMap(i=>n.get(i).edgeIds))}function zB(e){let t=new Map,n=new Map,r=new Set;for(let o of e){r.add(o.from.id),r.add(o.to.id);let s=t.get(o.from.id)??new Set;s.add(o.to.id),t.set(o.from.id,s);let a=n.get(o.to.id)??new Set;a.add(o.from.id),n.set(o.to.id,a)}return KB(r,t)?"scc":[...r].every(o=>(n.get(o)?.size??0)<=1&&(t.get(o)?.size??0)<=1)?"linear":"topology"}function KB(e,t){let n=new Set,r=new Set,i=o=>{if(n.has(o))return!0;if(r.has(o))return!1;n.add(o);for(let s of t.get(o)??[])if(i(s))return!0;return n.delete(o),r.add(o),!1};return[...e].some(i)}function WB(e,t,n){return`fold:${PB("sha256").update([e,t,...n].join("\0")).digest("hex").slice(0,16)}`}function VB(e,t,n){let r=new Map,i=[...new Set(t)].sort();for(let o=0;o<i.length;o+=1)for(let s=o+1;s<i.length;s+=1)for(let a of YB(e,i[o],i[s],n))r.set(a.id,a);return[...r.values()]}function YB(e,t,n,r){let i=Yd(e,r),o=new Map([[t,0]]),s=new Map,a=[t];for(let l=0;l<a.length;l+=1){let u=a[l],d=o.get(u);if(u!==n)for(let m of i.get(u)??[])o.has(m.next)||(o.set(m.next,d+1),s.set(m.next,{node:u,edge:m.edge}),a.push(m.next))}if(!o.has(n))return[];let c=[];for(let l=n;l!==t;){let u=s.get(l);if(!u)return[];c.push(u.edge),l=u.node}return c.reverse()}function JB(e,t,n){let r=Yd(e,n),i=new Map,o=[...t];for(let s of t)i.set(s,0);for(let s=0;s<o.length;s+=1){let a=o[s],c=i.get(a);for(let{next:l}of r.get(a)??[])i.has(l)||(i.set(l,c+1),o.push(l))}return i}function XB(e,t,n){return wC(e,n)-wC(t,n)||LC(e)-LC(t)||PC(e.evidenceStrength)-PC(t.evidenceStrength)||Bt.indexOf(e.family)-Bt.indexOf(t.family)||e.from.label.localeCompare(t.from.label)||e.to.label.localeCompare(t.to.label)||e.subtype.localeCompare(t.subtype)||e.id.localeCompare(t.id)}function wC(e,t){return Math.min(t.get(e.from.id)??Number.MAX_SAFE_INTEGER,t.get(e.to.id)??Number.MAX_SAFE_INTEGER)}function LC(e){let t=[e.from,e.to].filter(n=>n.kind==="structural-region").length;return t===2?2:t}function PC(e){switch(e){case"exact":return 0;case"mixed":return 1;case"derived":return 2;case"candidate":return 3;case"unknown":return 4}}function Jd(e,t){let n=Rr(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let r=n.map(()=>"?").join(", "),o=e.all(`SELECT relative_path FROM documents
92
- WHERE relative_path IN (${r})
93
- ORDER BY relative_path`,...n).map(l=>l.relative_path).filter(l=>!e.isIgnored(l)),s=$s(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:l,...u})=>u),a=On(e,"forward",n).filter(l=>!e.isIgnored(l)),c=On(e,"reverse",n).filter(l=>!e.isIgnored(l));return{files:o,symbols:s,dependsOn:a,dependedOnBy:c}}function Xd(e,t){let n=Rr(e,t);return n.length===0?[]:MC([...DC(e,n),...ZB(e,n)]).filter(r=>!e.isIgnored(r.relative_path)).map(TC)}function QB(e,t){let n=Rr(e,t);return n.length===0?[]:MC(DC(e,n)).filter(r=>!e.isIgnored(r.relative_path)).map(r=>({...TC(r),basis:"external-reference"}))}function DC(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
94
- FROM mentions m
95
- JOIN chunks c ON m.chunk_id = c.id
96
- JOIN documents d1 ON c.document_id = d1.id
97
- JOIN global_symbols gs ON m.symbol_id = gs.id
98
- WHERE d1.relative_path NOT IN (${n})
99
- AND (
100
- EXISTS (
101
- SELECT 1
102
- FROM defn_enclosing_ranges der
103
- JOIN documents d2 ON der.document_id = d2.id
104
- WHERE der.symbol_id = gs.id
105
- AND d2.relative_path IN (${n})
106
- )
107
- OR EXISTS (
108
- SELECT 1
109
- FROM mentions def_m
110
- JOIN chunks def_c ON def_m.chunk_id = def_c.id
111
- JOIN documents d2 ON def_c.document_id = d2.id
112
- WHERE def_m.symbol_id = gs.id
113
- AND def_m.role = 1
114
- AND d2.relative_path IN (${n})
115
- )
116
- )
117
- AND m.role != 1
118
- AND ${e.localSymbolPredicate}
119
- ${e.pathExclusionsFor("d1")}
120
- ORDER BY d1.relative_path`,...t,...t,...t)}function ZB(e,t){let n=new H(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>Xe(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function MC(e){let t=new Set;return e.filter(n=>{let r=`${n.relative_path}|${n.symbol}`;return t.has(r)?!1:(t.add(r),!0)})}function TC(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:T(e.symbol)}}var Zo=new WeakMap,kC=dt({kind:"definition-exclusions",invalidation:$e("definition-exclusions"),serialize:e=>JSON.stringify(e),deserialize:e$});function FC(e,t){let n=se(t);if(!(n==="rust"||n==="typescript"||n==="tsx"||n==="javascript"))return[];let i=W(e,t);if(!i)return[];let o=Rt(e,t,i),s=kC.read(e,t,o);if(s)return s;let a=n==="rust"?c$(e,t):i$(e,t);return kC.write(e,t,o,a),a}function e$(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=t.map(t$);return n.some(r=>r===null)?null:n}catch{return null}}function t$(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.startLine!="number"||!Number.isFinite(t.startLine)||typeof t.endLine!="number"||!Number.isFinite(t.endLine)||typeof t.reason!="string"||t.containerName!==void 0&&typeof t.containerName!="string")return null;let n=t.disposition===void 0?v$(t.reason):t.disposition;return n!=="exclude"&&n!=="implicit-usage"?null:{startLine:t.startLine,endLine:t.endLine,reason:t.reason,disposition:n,...t.containerName?{containerName:t.containerName}:{}}}var NC=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]),n$=/\b(?:describe|it|test|fdescribe|fit|xdescribe|xit|beforeEach|afterEach|beforeAll|afterAll|before|after|suite|bench|benchmark)\s*\(/,r$=/\b(?:export\s+)?(?:async\s+)?function\s+use[A-Z][A-Za-z0-9_$]*\b|\b(?:const|let|var)\s+use[A-Z][A-Za-z0-9_$]*\s*(?::[^=;]+)?=\s*(?:async\s*)?(?:function\b|(?:<[^=;{]+>\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>)/;function i$(e,t){let n=W(e,t);if(!n||!o$(n))return[];let r=J(e,t);if(!r)return[];let i=Zo.get(r);if(i)return i;let o=!1,s=r.rootNode;for(let c of s.namedChildren){if(c.type!=="expression_statement")continue;let l=c.namedChild(0);if(!l||l.type!=="call_expression")continue;let u=l.namedChild(0);if(!u)continue;let d=u.type==="member_expression"?u.namedChild(u.namedChildCount-1)?.text:u.text;if(d&&NC.has(d)){o=!0;break}}let a=[];o&&a.push({startLine:0,endLine:s.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)",disposition:"exclude"});for(let c of s.namedChildren){let l=null,u=null;if(c.type==="function_declaration")l=c.namedChild(0)?.text??null,u=c;else if(c.type==="export_statement"){let d=c.namedChild(0);d?.type==="function_declaration"&&(l=d.namedChild(0)?.text??null,u=d)}else if(c.type==="lexical_declaration"){let d=c.namedChild(0);if(d?.type==="variable_declarator"){let m=d.namedChild(0)?.text,p=d.namedChild(1);m&&(p?.type==="arrow_function"||p?.type==="function_expression")&&(l=m,u=d)}}l&&/^use[A-Z]/.test(l)&&u&&a.push({startLine:u.startPosition.row,endLine:u.endPosition.row,reason:"React custom hook (use*)",disposition:"exclude"})}return a.push(..._C(r,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),Zo.set(r,a),a}function o$(e){if(e.includes("scip-query"))return!0;let t=!1;for(let n of NC)if(e.includes(n)){t=!0;break}return t&&n$.test(e)?!0:e.includes("use")&&r$.test(e)}var s$=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function a$(e){return s$.test(e)}function _C(e,t,n){let r=[],i=o=>{if(t.has(o.type)&&o.parent){let a=o.parent.children,c=-1;for(let l=0;l<a.length;l+=1)if(a[l].startIndex===o.startIndex&&a[l].type===o.type){c=l;break}if(c>0)for(let l=c-1;l>=0;l-=1){let u=a[l];if(n.has(u.type)){if(a$(u.text)){r.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"scip-query suppression comment",disposition:"exclude"});break}continue}if(!(u.type==="attribute_item"||u.type==="inner_attribute_item"))break}}for(let s of o.namedChildren)i(s)};return i(e.rootNode),r}function c$(e,t){let n=J(e,t);if(!n)return[];let r=Zo.get(n);if(r)return r;let i=[],o=l$(n);return o?(Zo.set(n,o),o):(OC(n.rootNode,i,!1,!1),i.push(..._C(n,new Set(["function_item","function_signature_item","struct_item","enum_item","union_item","impl_item","mod_item","static_item","const_item"]),new Set(["line_comment","block_comment"]))),i.push(...b$(n.rootNode)),Zo.set(n,i),i)}function l$(e){return C$(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)",disposition:"exclude"}]:null}function OC(e,t,n,r){let i=n,o=r;e.type==="trait_item"&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait declaration body (dynamic dispatch)",disposition:"implicit-usage"}),e.type==="impl_item"&&e.childForFieldName("trait")&&(o=!0,t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl block (dynamic dispatch)",disposition:"implicit-usage"})),e.type==="function_item"||e.type==="function_signature_item"?u$(e,t,n,r):r&&y$(e)?t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl associated item (dynamic dispatch)",disposition:"implicit-usage"}):e.type==="struct_item"||e.type==="enum_item"||e.type==="union_item"?d$(e,t,n):e.type==="mod_item"&&Qd(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(i=!0);for(let s of e.namedChildren)OC(s,t,i,o)}function u$(e,t,n,r){let i=Qd(e),o=null;r?o={reason:"trait impl method (dynamic dispatch)",disposition:"implicit-usage"}:n&&(o={reason:"inside #[cfg(test)] mod",disposition:"exclude"});for(let s of i){if(BC(s)){o={reason:"#[allow(dead_code)]",disposition:"exclude"};break}let a=g$(s);if(a){o=a;break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o.reason,disposition:o.disposition})}function d$(e,t,n){let r=Qd(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(h$)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(...)] - generated impl may access fields",disposition:"implicit-usage",containerName:i}),r.some(BC)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",disposition:"exclude",containerName:i}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",disposition:"exclude",containerName:i})}function Qd(e){let t=e.parent;if(!t)return[];let n=t.children,r=-1;for(let o=0;o<n.length;o+=1)if(n[o].startIndex===e.startIndex&&n[o].type===e.type){r=o;break}if(r<=0)return[];let i=[];for(let o=r-1;o>=0;o-=1){let s=n[o];if(s.type==="attribute_item"||s.type==="inner_attribute_item")i.push(s.text);else{if(s.type==="line_comment"||s.type==="block_comment")continue;break}}return i}var m$=new Set(["test","bench","tokio::test","async_std::test"]),p$=new Set(["no_mangle","export_name","link_name","used","macro_export","proc_macro","proc_macro_derive","proc_macro_attribute"]),f$=new Set(["allow","warn","deny","forbid","cfg","cfg_attr","doc","inline","cold","must_use","deprecated","repr","derive","automatically_derived","non_exhaustive","path","link","link_section","global_allocator","panic_handler"]);function g$(e){if(/#\[\s*cfg\s*\(\s*test\s*\)/.test(e))return{reason:"#[cfg(test)]",disposition:"exclude"};let t=S$(e);return t?m$.has(t)?{reason:`#[${t}]`,disposition:"exclude"}:p$.has(t)?{reason:`Rust ABI/export attribute #[${t}]`,disposition:"implicit-usage"}:f$.has(t)?null:{reason:`Rust attribute macro #[${t}]`,disposition:"implicit-usage"}:null}function h$(e){return/#\[\s*derive\s*\(/.test(e)}function BC(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function y$(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function b$(e){let t=x$(e);if(t.size===0)return[];let n=[];for(let r of e.descendantsOfType("mod_item")){let i=r.childForFieldName("name")?.text;i&&t.has(i)&&n.push({startLine:r.startPosition.row,endLine:r.endPosition.row,reason:'attribute `with = "..."` module - body may be invoked via reflection',disposition:"implicit-usage",containerName:i})}return n}function S$(e){let t=/^#!?\[\s*([A-Za-z_][A-Za-z0-9_]*(?:\s*::\s*[A-Za-z_][A-Za-z0-9_]*)*)/.exec(e);return t?t[1].replace(/\s+/g,""):null}function v$(e){return e==="#[tauri::command]"||e==="#[command]"||e==="#[wasm_bindgen]"||e==="#[no_mangle]"||e==="#[napi]"||e==="#[pyfunction]"||e==="#[pymethod]"||e==="#[pyo3]"||e==="#[doc(hidden)]"||e.startsWith("trait ")||e.startsWith("#[derive(<reflective>)]")||e.startsWith("#[derive(...)]")||e.startsWith('serde `with = "')||e.startsWith('attribute `with = "')||e.startsWith("Rust attribute macro #[")||e.startsWith("Rust ABI/export attribute #[")?"implicit-usage":"exclude"}function C$(e){for(let t=0;t<Math.min(e.namedChildCount,12);t+=1){let n=e.namedChild(t);if(!n||n.type!=="line_comment"&&n.type!=="block_comment")break;if(/@generated\b/.test(n.text)||/This file is .*generated\b/i.test(n.text)||/Code generated by/i.test(n.text)||/Generated by:\s*https?:\/\/openapi-generator/i.test(n.text)||/openapi-generator/i.test(n.text)&&/Generated by/i.test(n.text))return!0}return!1}var AC=/\bwith\s*=\s*"([^"]+)"/g;function x$(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){AC.lastIndex=0;let r;for(;(r=AC.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}function $C(e){let t=Zd(e);return(n,r,i,o)=>t(n,r,i,o)?.disposition==="exclude"}function Zd(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=FC(e,r),s=new Map;for(let a of o){if(!a.containerName)continue;let c=s.get(a.containerName)??[];c.push(a),s.set(a.containerName,c)}return i={ranges:o,containers:s},t.set(r,i),i};return(r,i,o,s)=>{let a=n(r),c=[];for(let u of a.ranges)i>=u.startLine&&i<=u.endLine&&c.push(u);let l=new Set;s&&l.add(s);for(let u of js(o))l.add(u);for(let u of l){let d=a.containers.get(u);d&&c.push(...d)}return R$(c)}}function R$(e){if(e.length===0)return null;let n=e.find(r=>r.disposition==="exclude")??e[0];return{disposition:n.disposition,reason:n.reason}}function em(e,t={}){Vi(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function jC(e,t,n={}){Vi(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function HC(e,t){if(t.isIgnoredPath(e.relativePath))return rt("ignored-file");if(me(e.symbol))return rt("module-like-symbol");if(!Ec(e.symbol))return rt("non-value-symbol");if(!e.isFunctionLike&&e.enclosingSymbol&&Ec(e.enclosingSymbol))return rt("nested-non-callable-value");if(!t.includeTests&&!E$(e.relativePath))return rt("test-file");if(!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName))return rt("excluded-file-region");let n=z(e.symbol);if(n==="<constructor>")return rt("implicit-constructor");if(e.symbol.startsWith("scip-python ")){if(n==="__all__")return rt("python-runtime-metadata");if(/^__[^_].*__$/.test(n))return rt("python-protocol-member")}return t.isDeclarationOnlyCallable()?rt("declaration-only-callable"):t.isFrameworkContractCallable()?rt("framework-contract-member"):je(e.symbol)?rt("rust-trait-impl-member"):ii(e.symbol)?rt("rust-test-module"):!t.includeMembers&&!I$(e)?rt("member"):e.endLine-e.startLine+1<t.minLoc?rt("below-min-loc"):{accepted:!0}}function E$(e){return q(e)!=="test"}function rt(e){return{accepted:!1,rejectionReason:e}}function Ec(e){return Se(e)||e.endsWith("().")||e.endsWith(".")}function I$(e){return Xe(e.symbol)||js(e.symbol).length===0}function UC(){return new Map}function qC(e,t,n){let r=new Map;for(let i of xf(e,n))e.isIgnored(i.relative_path)||t.has(i.relative_path)||wc(r,i.symbol_id,i.relative_path,i.ref_count,"scip-mention");return r}function GC(e,t,n,r={}){let i=new Set;if(r.conservative||n.size===0){for(let o of Ef(e,t))i.add(o.symbol_id);return i}for(let o of Rf(e,t))e.isIgnored(o.relative_path)||n.has(o.relative_path)||i.add(o.symbol_id);return i}function tm(e,t){let n=e.get(t);if(!n)return!1;for(let r of n.values())if(r.occurrences>0)return!0;return!1}function Ic(e,t,n){let r=e.get(t);if(!r)return!1;for(let[i,o]of r)if(i!==n&&o.occurrences>0)return!0;return!1}function zC(e){return e?.occurrences??0}function wc(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=WC(e,t,n);o.occurrences+=r,o.sources.add(i)}function KC(e,t,n,r,i){if(r<=0)return;let o=WC(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function WC(e,t,n){let r=e.get(t);r||(r=new Map,e.set(t,r));let i=r.get(n);return i||(i={occurrences:0,sources:new Set},r.set(n,i)),i}var w$=new Set(["componentDidCatch","componentDidMount","componentDidUpdate","componentWillUnmount","getDerivedStateFromError","getDerivedStateFromProps","getSnapshotBeforeUpdate","render","shouldComponentUpdate","UNSAFE_componentWillMount","UNSAFE_componentWillReceiveProps","UNSAFE_componentWillUpdate"]);function _i(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=J(e,t.relativePath);if(!n)return!1;let r=n.rootNode.descendantsOfType("method_definition").find(s=>s.startPosition.row<=t.startLine&&s.endPosition.row>=t.endLine);if(!r)return!1;if(/\boverride\b/.test(r.text.slice(0,Math.max(0,r.text.indexOf("{")))))return!0;let i=r.parent;for(;i&&i.type!=="class_declaration"&&i.type!=="class";)i=i.parent;if(!i)return!1;let o=i.text.slice(0,Math.max(0,i.text.indexOf("{")));return/\bimplements\b/.test(o)||/\bextends\b/.test(o)?!0:w$.has(t.leaf)&&/\bextends\s+(?:React\.)?(?:Component|PureComponent)\b/.test(o)}var L$=64,P$=300;function zr(e,t={}){let{scope:n,minLoc:r=1,includeTests:i=!1,skipBarrels:o=!1,includeMembers:s=!1,deadCodeOnly:a=!1,scanLimit:c,semantic:l=!0}=t,u=0,d=N("dead.candidates",()=>{let v=he(D$(e,{scope:n,minLoc:r,includeTests:i,includeMembers:s}),c);return u=v.length,v},()=>({definitions:u})),m=0,p=o?N("dead.inactive-barrels",()=>{let v=new Set(Ib(e));return m=v.size,v},()=>({paths:m})):new Set,f=0,g=a?UC():N("dead.mention-reference-counts",()=>{let v=qC(e,p,d.map(C=>C.symbolId));return f=v.size,v},()=>({definitions:d.length,symbolsWithReferences:f})),h=0,b=a?N("dead.mentioned-symbol-ids",()=>{let v=GC(e,d.map(C=>C.symbolId),p,{conservative:p.size===0});return h=v.size,v},()=>({definitions:d.length,referencedSymbols:h})):new Set,S=a?d.filter(v=>!b.has(v.symbolId)):d.filter(v=>!Ic(g,v.symbolId,v.relativePath));a?N("dead.source-fallback.dead-code-only",()=>_$(e,S,g,{inactiveBarrelPaths:p}),()=>({definitions:S.length,testReferencesIncluded:!0})):N("dead.source-fallback.ast",()=>N$(e,S,g,{inactiveBarrelPaths:p}),()=>({definitions:S.length,testReferencesIncluded:!0}));let y=a?S.filter(v=>!tm(g,v.symbolId)):S.filter(v=>!Ic(g,v.symbolId,v.relativePath));N("dead.caller-map-supplement",()=>j$(e,y,g,{inactiveBarrelPaths:p,includeSemantic:!a&&l}),()=>({definitions:y.length,semantic:!a&&l}));let x=a?S.filter(v=>!tm(g,v.symbolId)):d;return F$(e,k$(x,g))}function D$(e,t){let n=$C(e),r=[];for(let i of Zi(e,{scope:t.scope,symbolMatches:Ec,sqlPrefilter:"function-like"}))HC(i,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:s=>e.isIgnored(s),isExcludedRegion:n,isDeclarationOnlyCallable:()=>T$(e,i),isFrameworkContractCallable:()=>_i(e,i)}).accepted&&r.push(i);return r}var M$=["method_signature","abstract_method_signature","call_signature","construct_signature"];function T$(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=J(e,t.relativePath);if(n)return n.rootNode.descendantsOfType([...M$]).some(i=>i.startPosition.row<=t.startLine&&i.endPosition.row>=t.endLine);let r=V(e,t.relativePath).slice(t.startLine,t.endLine+1).join(`
121
- `).trim();return r.endsWith(";")&&!r.includes("=>")&&!r.includes("{")}function k$(e,t){return e.map(n=>A$(n,t)).filter(n=>n.cross_file_refs===0).sort((n,r)=>r.loc-n.loc||n.relative_path.localeCompare(r.relative_path)||n.start_line-r.start_line)}function A$(e,t){let n=t.get(e.symbolId)??new Map,r=zC(n.get(e.relativePath)),i=0;for(let[o,s]of n)o!==e.relativePath&&(i+=s.occurrences);return{relative_path:e.relativePath,start_line:e.startLine,end_line:e.endLine,loc:e.endLine-e.startLine+1,symbol:e.symbol,parent_type_name:e.parentTypeName,same_file_refs:r,cross_file_refs:i}}function F$(e,t){let n=Zd(e),r=[],i=0,o=0,s=0,a=0,c=0,l=0;for(let u of t){if(e.isIgnored(u.relative_path))continue;if(Ue(e,u.relative_path)){a++;continue}if(Te(e,u.symbol,u.relative_path)){c++;continue}let d=n(u.relative_path,u.start_line,u.symbol,u.parent_type_name),m=d?.disposition==="implicit-usage"?d.reason:void 0,p=m?"implicit-usage":u.same_file_refs===0?"dead-code":"file-internal";p==="dead-code"?i++:p==="file-internal"?o++:s++,l+=u.loc,r.push({relativePath:u.relative_path,startLine:u.start_line,endLine:u.end_line,loc:u.loc,symbol:u.symbol,shortName:T(u.symbol),sameFileRefs:u.same_file_refs,kind:p,...m?{implicitUsageReason:m}:{}})}return{symbols:r,counts:{total:r.length,deadCode:i,fileInternal:o,implicitUsage:s,loc:l},applicability:{entrySurfaceExcluded:a,externalRootExcluded:c,implicitUsageSignals:s},totalCount:r.length,deadCodeCount:i,fileInternalCount:o,implicitUsageCount:s,totalLoc:l}}function N$(e,t,n,r){if(t.length===0)return;let i=new H(e),o=new Set(t.map(c=>c.symbolId)),s=new Set(t.map(c=>c.leaf).filter(Boolean)),a=new Set(i.sourceFiles());for(let c of Z(e))a.add(c);i.scanSourceReferences({paths:a,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:s,skipPath:c=>r.inactiveBarrelPaths.has(c)},c=>{o.has(c.target.symbolId)&&(B$(e,c)||wc(n,c.target.symbolId,c.sourceFile,$$(c),"source-fallback"))})}function _$(e,t,n,r){if(t.length===0)return;let i=new H(e),o=yf(t),s=new Set(i.sourceFiles());for(let u of Z(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let d=c.get(u);return d||(d=Lf(e,u),c.set(u,d)),d};i.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:u=>r.inactiveBarrelPaths.has(u),resolveTargets:({sourceFile:u,name:d,kind:m})=>{let p=o.get(d);return p?O$(u,d,p,()=>l(u),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),jC(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&VC(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||wc(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function O$(e,t,n,r,i){let o=n.filter(l=>l.relativePath===e);if(o.length>0)return o;if(!i.permissive&&n.length===1)return[...n];let s=r(),a=s.get(t);if(a)for(let l of a){let u=n.filter(d=>Fe(l,d.relativePath));if(u.length>0)return u}let c=new Set;for(let l of s.values())for(let u of l)c.add(u);for(let l of c){let u=n.filter(d=>Fe(l,d.relativePath));if(u.length>0&&u.length===n.length)return u}return i.permissive?[...n]:[]}function B$(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&VC(e,t)}function $$(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function VC(e,t){return t.occurrences>1?!1:ae(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function j$(e,t,n,r){let i=r.includeSemantic!==!1,o=i&&t.length>=L$&&Z(e).length>=P$,s=(u,d)=>{d===u.relativePath||e.isIgnored(d)||r.inactiveBarrelPaths.has(d)||KC(n,u.symbolId,d,1,"caller-map")};if(o?N("dead.caller-map.per-symbol-non-semantic",()=>{let u=yn(e,t,{semantic:!1,semanticEvidence:re});for(let d of t){let m=u.get(d.symbolId)??[];for(let p of m)s(d,p.file)}},()=>({definitions:t.length,semantic:!1,batched:!0})):N("dead.caller-map.per-symbol",()=>{for(let u of t){let d=Gn(e,u,{semantic:i,semanticEvidence:re});if(d.length!==0)for(let m of d)s(u,m.file)}},()=>({definitions:t.length,semantic:i})),!o)return;let a=0,c=N("dead.caller-map.semantic-candidates",()=>{let u=t.filter(d=>!Ic(n,d.symbolId,d.relativePath));return a=u.length,u},()=>({definitions:t.length,semanticCandidates:a}));if(c.length===0)return;let l=Ey(e,c);for(let u of c){let d=l.get(u.symbolId);if(d)for(let m of d)s(u,m)}}function H$(e,t={}){let{limit:n=30,scope:r}=t,i=r?"AND def_d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[],a=e.all(`SELECT
122
- gs.symbol,
123
- COUNT(*) AS ref_count,
124
- COUNT(DISTINCT ref_d.id) AS file_count,
125
- def_d.relative_path AS defined_in
126
- FROM mentions m
127
- JOIN chunks c ON m.chunk_id = c.id
128
- JOIN documents ref_d ON c.document_id = ref_d.id
129
- JOIN global_symbols gs ON m.symbol_id = gs.id
130
- JOIN (
131
- SELECT m2.symbol_id, c2.document_id
132
- FROM mentions m2
133
- JOIN chunks c2 ON m2.chunk_id = c2.id
134
- WHERE m2.role = 1
135
- GROUP BY m2.symbol_id
136
- ) sym_def ON sym_def.symbol_id = gs.id
137
- JOIN documents def_d ON sym_def.document_id = def_d.id
138
- WHERE m.role != 1
139
- AND def_d.id != ref_d.id
140
- ${e.pathExclusionsFor("def_d")}
141
- ${e.symbolNoiseFor("gs")}
142
- ${i}
143
- GROUP BY gs.id
144
- ORDER BY ref_count DESC
145
- LIMIT ?`,...o,n).filter(c=>!e.isIgnored(c.defined_in)).map(c=>({symbol:c.symbol,shortName:T(c.symbol),refCount:c.ref_count,fileCount:c.file_count,definedIn:c.defined_in,basis:"scip-cross-file-mentions",countUnit:"reference-occurrences"}));return a.length>0?a:U$(e,r,n)}function U$(e,t,n){return Le(e,{scope:t}).filter(r=>!e.isIgnored(r.relativePath)).map(r=>q$(e,r)).filter(r=>r.refCount>0).sort((r,i)=>i.refCount-r.refCount||i.fileCount-r.fileCount).slice(0,n)}function q$(e,t){let r=Gn(e,t,{limit:500,semanticEvidence:re}).filter(i=>i.file!==t.relativePath);return{symbol:t.symbol,shortName:T(t.symbol),refCount:r.length,fileCount:new Set(r.map(i=>i.file)).size,definedIn:t.relativePath,basis:"source-backed-incoming-evidence",countUnit:"distinct-incoming-evidence-rows"}}function G$(e,t,n={}){return ej(e,t,n)?.map(r=>({symbol:r.symbol,shortName:r.shortName,fromFile:r.fromFile}))??[]}function z$(e,t){let n=ne(e,t),r=V$(e,t);if(r.length>0&&!J$(n))return r;let i=Y$(e,t,n);return nm(t)&&i.length>0?i:X$([...r,...i])}function K$(e,t,n={}){let r=mt(e,t);if(!r)return[];let i=JC(e,r),o=n.semantic===!1?null:YC(e,r);return(o?W$(o,i):i).filter(a=>!a.used).map(a=>({symbol:a.symbol,shortName:a.shortName,importedIn:a.importer}))}function W$(e,t){let n=new Map;for(let i of t){let o=n.get(i.shortName);o?o.push(i):n.set(i.shortName,[i])}let r=e.map(i=>{let o=n.get(i.shortName),s=o?.shift();return o?.length===0&&n.delete(i.shortName),s?{...i,used:i.used||s.used}:i});return r.push(...[...n.values()].flat()),r}function V$(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
146
- FROM mentions m
147
- JOIN chunks c ON m.chunk_id = c.id
148
- JOIN documents d ON c.document_id = d.id
149
- JOIN global_symbols gs ON m.symbol_id = gs.id
150
- WHERE gs.symbol LIKE ?
151
- AND m.role = 2
152
- ORDER BY d.relative_path`,`%${t}%`).filter(r=>!e.isIgnored(r.importer)).map(r=>({symbol:r.symbol,shortName:T(r.symbol),fromFile:r.importer}))}function Y$(e,t,n=ne(e,t)){let r=n?.relativePath??null,i=n?z(n.symbol):t.replace(/\(\)$/,""),o=n?me(n.symbol):!1,s=new Set;for(let c of Z(e,{includeIgnored:!1}))for(let l of ae(e,c))Q$(l,c,{targetFile:r,targetLeaf:i,targetIsModule:o,targetPattern:t})&&s.add(c);let a=nm(t)?t.trim():null;return[...s].sort().map(c=>({symbol:a??n?.symbol??i,shortName:a??(n?T(n.symbol):i),fromFile:c}))}function J$(e){return!!(e&&(e.symbol.startsWith("scip-clojure ")||se(e.relativePath)==="clojure"))}function X$(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.fromFile}`;t.has(i)||(t.add(i),n.push(r))}return n.sort((r,i)=>r.fromFile.localeCompare(i.fromFile)||r.shortName.localeCompare(i.shortName))}function Q$(e,t,n){return!e.sourcePath||n.targetFile&&it(e.sourcePath)!==it(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&ij(t)||e.kind==="namespace"&&Z$(e,n.targetPattern)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function Z$(e,t){let n=t.trim().replace(/\(\)$/,"");return nm(n)?e.importedName===n||e.localName===n:!1}function nm(e){let t=e.trim().replace(/\(\)$/,"");return t.includes(".")&&!t.includes("/")&&!t.includes(":")}function ej(e,t,n={}){let r=mt(e,t);return r?tj(e,r,n)??(n.semantic===!1?null:YC(e,r))??JC(e,r):null}function tj(e,t,n){let i=e.all(`SELECT DISTINCT
153
- gs.symbol,
154
- def_d.relative_path AS from_file,
155
- imp_d.relative_path AS importer,
156
- EXISTS (
157
- SELECT 1
158
- FROM mentions ref_m
159
- JOIN chunks ref_c ON ref_m.chunk_id = ref_c.id
160
- WHERE ref_m.symbol_id = gs.id
161
- AND ref_m.role != 1
162
- AND ref_c.document_id = imp_d.id
163
- ) AS used
164
- FROM mentions m
165
- JOIN chunks c ON m.chunk_id = c.id
166
- JOIN documents imp_d ON c.document_id = imp_d.id
167
- JOIN global_symbols gs ON m.symbol_id = gs.id
168
- LEFT JOIN (
169
- SELECT m2.symbol_id, c2.document_id
170
- FROM mentions m2
171
- JOIN chunks c2 ON m2.chunk_id = c2.id
172
- WHERE m2.role = 1
173
- GROUP BY m2.symbol_id
174
- ) sym_def ON sym_def.symbol_id = gs.id
175
- LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
176
- WHERE imp_d.relative_path = ?
177
- AND m.role = 2
178
- ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(i.length>0){let o=n.semantic===!1?[]:Po(e,t);return i.map(s=>({symbol:s.symbol,shortName:T(s.symbol),fromFile:s.from_file??"(external)",importer:s.importer,used:s.used!==0||o.some(a=>a.isUsed&&a.sourcePath===s.from_file)}))}return null}function YC(e,t){let n=Po(e,t);return n.length>0?n.map(r=>{let i=XC(r.importedName,r.localName,r.kind);return{symbol:i,shortName:i,fromFile:r.sourcePath??"(external)",importer:t,used:r.kind==="side-effect"?!0:r.isUsed}}):null}function JC(e,t){let n=nj(t,W(e,t));return ae(e,t).map(r=>{let i=XC(r.importedName,r.localName,r.kind),o=r.kind==="side-effect"||rj(t,r)||n.has(r.localName??r.importedName)?!0:r.used;return{symbol:i,shortName:i,fromFile:r.sourcePath??"(external)",importer:t,used:o}})}function nj(e,t){let n=new Set;if(se(e)!=="python")return n;let r=/(?:^|\n)\s*__all__\s*(?:\+?=)\s*[[(]([\s\S]*?)[\])]/g;for(let i of t.matchAll(r)){let o=i[1]??"";for(let s of o.matchAll(/(['"])([A-Za-z_]\w*)\1/g))n.add(s[2])}return n}function rj(e,t){if(se(e)!=="rust"||t.used||t.kind==="side-effect")return!1;let n=t.localName??t.importedName;return n==="_"||/^[A-Z]/.test(n)}function XC(e,t,n){return n==="namespace"&&e==="*"&&t?`* as ${t}`:n==="default"&&t?`default as ${t}`:n==="side-effect"?"(side effect import)":t&&t!==e?`${e} as ${t}`:e}function ij(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function oj(e,t){let n=ne(e,t);if(!n)return[];let i=new H(e).definitionsForFile(n.relativePath).filter(o=>o.symbol!==n.symbol).filter(o=>gf(n.symbol,o.symbol)).sort((o,s)=>o.startLine-s.startLine||o.endLine-s.endLine).map(o=>({symbol:o.symbol,shortName:T(o.symbol),startLine:o.startLine,endLine:o.endLine,kind:wt(o.symbol)??"unknown"}));return se(n.relativePath)!=="clojure"?i:aj(i,sj(e,n))}function sj(e,t){let n=z(t.symbol);if(!n)return[];let r=T(t.symbol);return(K(e,t.relativePath)?.clojureMembers??[]).filter(i=>i.ownerName===n).map(i=>({symbol:`${t.symbol}${i.memberName}().`,shortName:`${r}:${i.memberName}()`,startLine:i.startLine,endLine:i.endLine,kind:i.memberKind}))}function aj(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.shortName}:${r.startLine}:${r.endLine}`,r);return[...n.values()].sort((r,i)=>r.startLine-i.startLine||r.endLine-i.endLine)}function cj(e,t){let n=ne(e,t);if(!n)return[];let r=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
179
- FROM mentions m
180
- JOIN chunks c ON m.chunk_id = c.id
181
- JOIN (
182
- SELECT m2.symbol_id, c2.document_id
183
- FROM mentions m2
184
- JOIN chunks c2 ON m2.chunk_id = c2.id
185
- WHERE m2.role = 1
186
- GROUP BY m2.symbol_id
187
- ) sym_def ON sym_def.symbol_id = m.symbol_id
188
- WHERE m.symbol_id = ?
189
- AND m.role != 1
190
- AND sym_def.document_id != c.document_id`,n.symbolId);return[{name:T(n.symbol),count:r?.file_count??0,symbol:n.symbol,definedIn:n.relativePath}]}function lj(e,t){let n=mt(e,t);return n?e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
191
- FROM mentions m
192
- JOIN chunks c ON m.chunk_id = c.id
193
- JOIN documents d ON c.document_id = d.id
194
- JOIN global_symbols gs ON m.symbol_id = gs.id
195
- JOIN (
196
- SELECT m2.symbol_id, c2.document_id
197
- FROM mentions m2
198
- JOIN chunks c2 ON m2.chunk_id = c2.id
199
- WHERE m2.role = 1
200
- GROUP BY m2.symbol_id
201
- ) sym_def ON sym_def.symbol_id = gs.id
202
- JOIN documents def_d ON sym_def.document_id = def_d.id
203
- WHERE d.relative_path = ?
204
- AND m.role != 1
205
- AND def_d.id != d.id
206
- GROUP BY d.id
207
- ORDER BY symbol_count DESC`,n).filter(o=>!e.isIgnored(o.relative_path)).map(o=>({name:o.relative_path,count:o.symbol_count,file:o.relative_path,basis:"external-symbol-references"})):[]}function uj(e,t={}){return dj(e,t).map(n=>({name:T(n.symbol),count:n.file_count,symbol:n.symbol,definedIn:n.defined_in}))}function dj(e,t){let{limit:n=30,scope:r}=t,i=r?"AND def_d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[];return e.all(`SELECT gs.symbol,
208
- COUNT(DISTINCT c.document_id) AS file_count,
209
- def_d.relative_path AS defined_in
210
- FROM mentions m
211
- JOIN chunks c ON m.chunk_id = c.id
212
- JOIN global_symbols gs ON m.symbol_id = gs.id
213
- JOIN (
214
- SELECT m2.symbol_id, c2.document_id
215
- FROM mentions m2
216
- JOIN chunks c2 ON m2.chunk_id = c2.id
217
- WHERE m2.role = 1
218
- GROUP BY m2.symbol_id
219
- ) sym_def ON sym_def.symbol_id = gs.id
220
- JOIN documents def_d ON sym_def.document_id = def_d.id
221
- WHERE m.role != 1
222
- AND def_d.id != c.document_id
223
- ${e.pathExclusionsFor("def_d")}
224
- ${e.symbolNoiseFor("gs")}
225
- ${i}
226
- GROUP BY gs.id
227
- HAVING file_count > 1
228
- ORDER BY file_count DESC
229
- LIMIT ?`,...o,n)}function mj(e,t={}){let{limit:n=30,scope:r}=t,i=r?"AND d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[];return e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
230
- FROM mentions m
231
- JOIN chunks c ON m.chunk_id = c.id
232
- JOIN documents d ON c.document_id = d.id
233
- JOIN global_symbols gs ON m.symbol_id = gs.id
234
- JOIN (
235
- SELECT m2.symbol_id, c2.document_id
236
- FROM mentions m2
237
- JOIN chunks c2 ON m2.chunk_id = c2.id
238
- WHERE m2.role = 1
239
- GROUP BY m2.symbol_id
240
- ) sym_def ON sym_def.symbol_id = gs.id
241
- JOIN documents def_d ON sym_def.document_id = def_d.id
242
- WHERE m.role != 1
243
- AND def_d.id != d.id
244
- ${e.pathExclusionsFor("d")}
245
- ${e.symbolNoiseFor("gs")}
246
- ${i}
247
- GROUP BY d.id
248
- ORDER BY symbol_count DESC
249
- LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}))}var QC=`SELECT COUNT(*) AS shared
250
- FROM (
251
- SELECT definition_m.symbol_id
252
- FROM documents definition_d
253
- JOIN chunks definition_c ON definition_c.document_id = definition_d.id
254
- JOIN mentions definition_m ON definition_m.chunk_id = definition_c.id
255
- AND definition_m.role = 1
256
- JOIN mentions reference_m ON reference_m.symbol_id = definition_m.symbol_id
257
- AND reference_m.role != 1
258
- JOIN chunks reference_c ON reference_c.id = reference_m.chunk_id
259
- JOIN documents reference_d ON reference_d.id = reference_c.document_id
260
- WHERE definition_d.relative_path = ?
261
- AND reference_d.relative_path = ?
262
- UNION
263
- SELECT definition_m.symbol_id
264
- FROM documents definition_d
265
- JOIN chunks definition_c ON definition_c.document_id = definition_d.id
266
- JOIN mentions definition_m ON definition_m.chunk_id = definition_c.id
267
- AND definition_m.role = 1
268
- JOIN mentions reference_m ON reference_m.symbol_id = definition_m.symbol_id
269
- AND reference_m.role != 1
270
- JOIN chunks reference_c ON reference_c.id = reference_m.chunk_id
271
- JOIN documents reference_d ON reference_d.id = reference_c.document_id
272
- WHERE definition_d.relative_path = ?
273
- AND reference_d.relative_path = ?
274
- )`;function pj(e,t,n){let r=mt(e,t)??t,i=mt(e,n)??n,o=e.get(QC,r,i,i,r);return{...ZC(r,i,o?.shared??0)}}function fj(e,t={}){let{limit:n=20,scope:r}=t,i=r?"AND def_d.relative_path LIKE ? AND ref_d.relative_path LIKE ?":"",o=r?[`%${r}%`,`%${r}%`]:[];return e.all(`SELECT
275
- CASE WHEN def_d.relative_path < ref_d.relative_path THEN def_d.relative_path ELSE ref_d.relative_path END AS file1,
276
- CASE WHEN def_d.relative_path < ref_d.relative_path THEN ref_d.relative_path ELSE def_d.relative_path END AS file2,
277
- COUNT(DISTINCT gs.id) AS shared
278
- FROM mentions m
279
- JOIN chunks c ON m.chunk_id = c.id
280
- JOIN documents ref_d ON c.document_id = ref_d.id
281
- JOIN global_symbols gs ON m.symbol_id = gs.id
282
- JOIN (
283
- SELECT m2.symbol_id, c2.document_id
284
- FROM mentions m2
285
- JOIN chunks c2 ON m2.chunk_id = c2.id
286
- WHERE m2.role = 1
287
- GROUP BY m2.symbol_id
288
- ) sym_def ON sym_def.symbol_id = gs.id
289
- JOIN documents def_d ON sym_def.document_id = def_d.id
290
- WHERE m.role != 1
291
- AND def_d.id != ref_d.id
292
- ${e.pathExclusionsFor("def_d","ref_d")}
293
- ${i}
294
- GROUP BY file1, file2
295
- ORDER BY shared DESC, file1, file2
296
- LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.file1)&&!e.isIgnored(a.file2)).map(a=>ZC(a.file1,a.file2,a.shared))}function ZC(e,t,n){return{file1:e,file2:t,sharedSymbols:n,actionTier:"signal",couplingKind:"shared-symbol-coupling",evidenceReasons:[`${n} symbol(s) are defined in one file and referenced by the other`],recommendation:"Review whether the shared symbol surface is an intentional boundary or hidden coordination pressure before moving code."}}function Kr(e){let t=new Map,n=[],r=new Map,i=new Map,o=new Set,s=[],a=0,c=l=>(e.get(l)??[]).values();for(let l of e.keys()){if(r.has(l))continue;let u=[];for(r.set(l,a),i.set(l,a),a+=1,s.push(l),o.add(l),u.push({node:l,iter:c(l),pendingChild:null});u.length>0;){let d=u[u.length-1];if(d.pendingChild!==null){let f=d.pendingChild;d.pendingChild=null,i.set(d.node,Math.min(i.get(d.node),i.get(f)))}let m=d.iter.next();if(m.done){if(i.get(d.node)===r.get(d.node)){let f=[];for(;;){let g=s.pop();if(o.delete(g),f.push(g),t.set(g,n.length),g===d.node)break}n.push(f)}u.pop();continue}let p=m.value;r.has(p)?o.has(p)&&i.set(d.node,Math.min(i.get(d.node),r.get(p))):(r.set(p,a),i.set(p,a),a+=1,s.push(p),o.add(p),d.pendingChild=p,u.push({node:p,iter:c(p),pendingChild:null}))}}return{components:n,componentOf:t}}function es(e,t={}){return nx(e,t).cycles}function nx(e,t={}){return rx(e,t)}function rx(e,t={}){let{scope:n,maxDepth:r=10,edgeBasis:i="symbol-references"}=t,o=Me(e,n,i==="imports"?{scipEdges:"imports-only",sourceEdges:"imports-only"}:void 0),{components:s}=Kr(o),a=s.filter(c=>gj(o,c)).map(c=>{let l=[...c].sort(),u=hj(o,l),d=bj(u);return{path:u,component:l,edgeBasis:i,witness:!0,classification:d==="real"?"dependency-cycle":"module-structure-candidate",kind:d}});return a.sort((c,l)=>c.kind!==l.kind?c.kind==="real"?-1:1:c.path.length-l.path.length),{cycles:a,truncated:!1,edgeBasis:i,maxDepth:r}}function gj(e,t){if(t.length>1)return!0;let n=t[0];return n!==void 0&&e.get(n)?.has(n)===!0}function hj(e,t){let n=t[0];if(!n)return[];let r=new Set(t);for(let i of[...e.get(n)??[]].filter(o=>r.has(o)).sort()){if(i===n)return[n,n];let o=yj(e,i,n,r);if(o)return[n,...o]}throw new Error(`Cyclic component did not contain a witness path from ${n}.`)}function yj(e,t,n,r){let i=[t],o=new Map([[t,null]]);for(let s=0;s<i.length;s+=1){let a=i[s];if(a===n){let c=[];for(let l=a;l!==null;l=o.get(l)??null)c.push(l);return c.reverse()}for(let c of[...e.get(a)??[]].filter(l=>r.has(l)).sort())o.has(c)||(o.set(c,a),i.push(c))}return null}function bj(e){for(let r of e){let i=q(r);if(i==="test"||i==="barrel"||i==="entry")return"module-hierarchy"}if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":Ei(t)||Ei(n)||ex(t,n)||ex(n,t)||tx(t,n)||tx(n,t)||q(t)==="entry"||q(n)==="entry"?"module-hierarchy":"real"}function ex(e,t){if(!e.endsWith(".rs")||!t.endsWith(".rs"))return!1;let n=t.replace(/\.rs$/,"/");return e.startsWith(n)?!e.slice(n.length).includes("/"):!1}function tx(e,t){if(!e.endsWith(".rs")||!t.endsWith(".rs"))return!1;let n=e.replace(/\.rs$/,""),r=t.replace(/\.rs$/,"");if(n===r+"_tests"||n===r+"/tests")return!0;let i=e.split("/"),o=t.split("/");if(i.length===o.length&&i.includes("tests")&&o.includes("src")){let s=i[i.length-1],a=o[o.length-1];if(s&&s===a)return!0}return!1}function lr(e,t){let n=ix(e),r=ix(t);if(n.endsWith("/**")){let i=n.slice(0,-3);return r===i||r.startsWith(`${i}/`)}if(n.endsWith("/*")){let i=n.slice(0,-2);if(!r.startsWith(`${i}/`))return!1;let o=r.slice(i.length+1);return o.length>0&&!o.includes("/")}return n==="**"?!0:n==="*"?r.length>0&&!r.includes("/"):n===r}function ix(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}import{readdirSync as Sj}from"fs";import{join as ox}from"path";function vj(e){return sx(e).replace(/\/\*\*?$/,"")}function Lc(e,t){let n=sx(t),r=vj(n),i=n.endsWith("/**"),o=[],s=(a,c)=>{let l;try{l=Sj(a,{withFileTypes:!0})}catch{return}for(let u of l){if(u.name.startsWith("."))continue;let d=c?`${c}/${u.name}`:u.name;lr(n,d)&&o.push(d),i&&u.isDirectory()&&s(ox(a,u.name),d)}};return s(ox(e,r),r),o.sort()}function sx(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}var Cj=/\.(test|spec)\.(ts|tsx|js|jsx|mts|cts)$/,ax=new Map;function cx(e,t,n,r){if(!t?.testPaths?.length)return[];let i=xj(t),o=[];for(let s of Rj(e,t.testPaths)){let a=Ej(e,s,r),c=a?n(a):null;if(c)for(let l of ae(e,s)){let u=l.sourcePath;if(!u)continue;let d=n(u);d&&d!==c&&(i.get(c)?.has(d)||o.push({testFile:s,ownerBoundary:c,importedFile:u,importedBoundary:d,reason:"outside-owner-policy"}))}}return Ij(o)}function xj(e){let t=e.allowedDependencies??{},n=e.boundaries.map(s=>s.name),r=new Map,i=(s,a)=>{for(let c of t[s]??[])a.has(c)||(a.add(c),i(c,a))};for(let s of n){let a=new Set;i(s,a),r.set(s,a)}let o=new Map;for(let s of n){let a=new Set(r.get(s));for(let c of n)c!==s&&r.get(c)?.has(s)&&a.add(c);o.set(s,a)}return o}function Rj(e,t){let n=`${e.config.projectRoot}\0${t.join("\0")}`,r=ax.get(n);if(r)return r;let i=new Set;for(let s of t)for(let a of Lc(e.config.projectRoot,s))Cj.test(a)&&i.add(a);let o=[...i].sort();return ax.set(n,o),o}function Ej(e,t,n){let r=t.replace(/^tests\//,"src/").replace(/\.(test|spec)\.(\w+)$/,".$2");if(r!==t&&n(r))return r;let i=t.split("/").pop().replace(/\.(test|spec)\.(\w+)$/,".$2"),o=ae(e,t).map(s=>s.sourcePath).filter(s=>!!s&&n(s)&&s.split("/").pop()===i);return o.length===1?o[0]:null}function Ij(e){let t=new Map;for(let n of e){let r=`${n.testFile}\0${n.importedBoundary}`;t.has(r)||t.set(r,n)}return[...t.values()].sort((n,r)=>n.testFile.localeCompare(r.testFile)||n.importedBoundary.localeCompare(r.importedBoundary))}function lx(e,t){let n=(e?.boundaries??[]).filter(r=>r.paths.some(i=>lr(i,t)));return n.length===1?n[0].name:null}var Dn="architecture:";function ux(e,t,n,r={}){let i=Lj(e,t);if(!n||n.boundaries.length===0)return{configured:!1,boundaries:[],edges:[],forbiddenEdges:[],reciprocalPairs:[],cycles:[],coarseBoundaries:[],staleAllowances:[],boundaryLimits:[],fragileEdges:[],testBoundaryViolations:[],coverage:{totalFiles:i.length,mappedFiles:0,unmappedFiles:[],ambiguousFiles:[]},policyCoverage:{declaredRows:0,totalBoundaries:0,missingRows:[],requiresCompletePolicy:!1,requiresCompleteCoverage:!1,requiresMinimalPolicy:!1}};let o=new Map,s=new Map(n.boundaries.map(y=>[y.name,new Set])),a=[],c=[];for(let y of i){let x=n.boundaries.filter(v=>v.paths.some(C=>lr(C,y))).map(v=>v.name).sort();if(x.length===0)a.push(y);else if(x.length>1)c.push({file:y,boundaries:x});else{let v=x[0];o.set(y,v),s.get(v).add(y)}}let l=new Map;for(let[y,x]of e){let v=o.get(y);if(v)for(let C of x){let R=o.get(C);if(!R||v===R)continue;let E=Oi(v,R),w=l.get(E);w||(w={from:v,to:R,fileEdges:[],importers:new Set,importedFiles:new Set},l.set(E,w)),w.fileEdges.push({fromFile:y,toFile:C}),w.importers.add(y),w.importedFiles.add(C)}}let u=[...l.values()].map(y=>Pj(y,n)).sort(_j),d=u,m=new Map(d.map(y=>[Oi(y.from,y.to),y])),p=new Map(n.boundaries.map(y=>[y.name,new Set]));for(let y of d)p.get(y.from).add(y.to);let f=[];for(let y of d){if(y.from>=y.to)continue;let x=m.get(Oi(y.to,y.from));x&&f.push({boundaries:[y.from,y.to],forward:y,reverse:x})}let{components:g}=Kr(p),h=g.filter(y=>y.length>1).map(y=>Mj(y,d,n.requireAcyclic===!0)).sort((y,x)=>x.boundaries.length-y.boundaries.length||y.boundaries.join("/").localeCompare(x.boundaries.join("/"))),b=n.allowedDependencies??{},S=n.boundaries.map(y=>y.name).filter(y=>!Object.hasOwn(b,y)).sort();return{configured:!0,boundaries:n.boundaries.map(y=>({name:y.name,paths:[...y.paths],fileCount:s.get(y.name).size,dependencyPolicyDeclared:Object.hasOwn(b,y.name)})).sort((y,x)=>y.name.localeCompare(x.name)),edges:u,forbiddenEdges:d.filter(y=>y.policyStatus==="forbidden"),reciprocalPairs:f,cycles:h,staleAllowances:kj(n,d),boundaryLimits:Aj(n,d,s),fragileEdges:d.filter(y=>y.fragile),testBoundaryViolations:r.testBoundaryViolations??[],coarseBoundaries:Tj(e,s,r.isModuleHierarchyFile,n.requireResolvedBoundaries===!0,y=>n.boundaries.find(x=>x.name===y)?.subUnits??"directory"),coverage:{totalFiles:i.length,mappedFiles:o.size,unmappedFiles:a,ambiguousFiles:c},policyCoverage:{declaredRows:n.boundaries.length-S.length,totalBoundaries:n.boundaries.length,missingRows:S,requiresCompletePolicy:n.requireCompletePolicy===!0,requiresCompleteCoverage:n.requireCompleteCoverage===!0,requiresMinimalPolicy:n.requireMinimalPolicy===!0}}}function ts(e,t={}){let n=Me(e,t.scope,{scipEdges:"imports-only",sourceEdges:"imports-and-reexports"}),r=Z(e,{includeIgnored:!1}).filter(o=>!t.scope||o.includes(t.scope)),i=new Set(r);return ux(n,r,e.config.architecture,{isModuleHierarchyFile:o=>wj(e,o),testBoundaryViolations:cx(e,e.config.architecture,o=>lx(e.config.architecture,o),o=>i.has(o))})}function wj(e,t){let n=q(t);return n==="test"||n==="entry"?!0:n!=="barrel"?!1:U(e,t).length===0}function rm(e){let t=e.forbiddenEdges.map(r=>`${Dn}forbidden-edge:${encodeURIComponent(r.from)}:${encodeURIComponent(r.to)}`);if(e.policyCoverage.requiresCompletePolicy)for(let r of e.policyCoverage.missingRows)t.push(`${Dn}missing-policy-row:${encodeURIComponent(r)}`);if(e.policyCoverage.requiresCompleteCoverage){for(let r of e.coverage.unmappedFiles)t.push(`${Dn}unmapped-file:${encodeURIComponent(r)}`);for(let r of e.coverage.ambiguousFiles)t.push(`${Dn}ambiguous-file:${encodeURIComponent(r.file)}:${r.boundaries.map(i=>encodeURIComponent(i)).sort().join("|")}`)}if(e.policyCoverage.requiresMinimalPolicy)for(let r of e.staleAllowances)t.push(`${Dn}stale-allowance:${encodeURIComponent(r.from)}:${encodeURIComponent(r.to)}`);for(let r of e.testBoundaryViolations)t.push(`${Dn}test-boundary:${encodeURIComponent(r.testFile)}:${encodeURIComponent(r.importedBoundary)}`);for(let r of e.boundaryLimits)t.push(`${Dn}boundary-limit:${r.kind}:${encodeURIComponent(r.boundary)}`);let n=new Map;for(let r of e.coarseBoundaries)r.violatesPolicy&&n.set(r.boundary,(n.get(r.boundary)??0)+1);for(let[r,i]of n){let o=`${Dn}coarse-boundary:${encodeURIComponent(r)}`;t.push(o);for(let s=2;s<=i;s+=1)t.push(`${o}:component:${s}`)}for(let r of e.cycles)r.violatesPolicy&&t.push(`${Dn}cycle:${r.boundaries.map(i=>encodeURIComponent(i)).sort().join("|")}`);return[...new Set(t)].sort()}function Lj(e,t){let n=new Set(t);for(let[r,i]of e){n.add(r);for(let o of i)n.add(o)}return[...n].sort()}function Pj(e,t){let n=[...e.fileEdges].sort((r,i)=>r.fromFile.localeCompare(i.fromFile)||r.toFile.localeCompare(i.toFile));return{from:e.from,to:e.to,policyStatus:Dj(t,e.from,e.to),fileEdgeCount:n.length,importerCount:e.importers.size,importedFileCount:e.importedFiles.size,examples:n.slice(0,5),fragile:n.length===1}}function Dj(e,t,n){return!e.allowedDependencies||!Object.hasOwn(e.allowedDependencies,t)?"undeclared":e.allowedDependencies[t].includes(n)?"allowed":"forbidden"}function Mj(e,t,n){let r=[...e].sort(),i=new Set(r),o=t.filter(a=>i.has(a.from)&&i.has(a.to)),s=Math.min(...o.map(a=>a.fileEdgeCount));return{boundaries:r,internalEdges:o,narrowestEdges:o.filter(a=>a.fileEdgeCount===s),violatesPolicy:n}}function Tj(e,t,n=Fj,r=!1,i=()=>"directory"){let o=[];for(let[s,a]of t){let c=i(s)==="file"?f=>f:Nj,l=[...a].filter(f=>!n(f));if(l.length<2)continue;let u=new Set(l),d=new Map,m=new Map;for(let f of l)m.set(c(f),new Set);for(let f of l)for(let g of e.get(f)??[]){if(!u.has(g))continue;let h=c(f),b=c(g);if(h===b)continue;let S=Oi(h,b),y=d.get(S);y||(y={from:h,to:b,fileEdges:[]},d.set(S,y)),y.fileEdges.push({fromFile:f,toFile:g}),m.get(h).add(b)}let{components:p}=Kr(m);for(let f of p){if(f.length<2)continue;let g=new Set(f),h=[...d.values()].filter(S=>g.has(S.from)&&g.has(S.to)).map(S=>({from:S.from,to:S.to,fileEdgeCount:S.fileEdges.length,examples:S.fileEdges.slice(0,5)})).sort((S,y)=>S.from.localeCompare(y.from)||S.to.localeCompare(y.to)),b=Math.min(...h.map(S=>S.fileEdgeCount));o.push({boundary:s,violatesPolicy:r,subUnits:[...f].sort(),internalEdges:h,narrowestEdges:h.filter(S=>S.fileEdgeCount===b)})}}return o.sort((s,a)=>a.subUnits.length-s.subUnits.length||s.boundary.localeCompare(a.boundary))}function kj(e,t){let n=new Set(t.map(s=>Oi(s.from,s.to))),r=e.allowedDependencies??{},i=new Set(e.boundaries.map(s=>s.name)),o=[];for(let[s,a]of Object.entries(r))if(i.has(s))for(let c of a)!i.has(c)||n.has(Oi(s,c))||o.push({from:s,to:c});return o.sort((s,a)=>s.from.localeCompare(a.from)||s.to.localeCompare(a.to))}function Aj(e,t,n){let r=[],i=new Map;for(let o of t)i.set(o.from,(i.get(o.from)??0)+1);for(let o of e.boundaries){if(e.maxBoundaryFanOut!==void 0){let a=i.get(o.name)??0;a>e.maxBoundaryFanOut&&r.push({boundary:o.name,kind:"fan-out",observed:a,limit:e.maxBoundaryFanOut})}let s=o.maxFiles??e.maxBoundaryFiles;if(s!==void 0){let a=n.get(o.name)?.size??0;a>s&&r.push({boundary:o.name,kind:"files",observed:a,limit:s})}}return r.sort((o,s)=>o.boundary.localeCompare(s.boundary)||o.kind.localeCompare(s.kind))}function Fj(e){let t=q(e);return t==="test"||t==="entry"}function Nj(e){let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)}function Oi(e,t){return`${e}\0${t}`}function _j(e,t){return e.from.localeCompare(t.from)||e.to.localeCompare(t.to)}function Oj(e,t={}){let{limit:n=20,scope:r,minFanIn:i=2,minFanOut:o=2,scanLimit:s}=t,a=new H(e),c=he(a.productionCallableDefinitions({scope:r,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s),l=t.semantic!==!1,u=yn(e,c,{limit:500,semantic:l,semanticEvidence:re});return c.map(m=>Bj(e,m,l,u.get(m.symbolId)??[])).filter(m=>m.fanIn>=i&&m.fanOut>=o).sort((m,p)=>p.score-m.score||p.fanIn-m.fanIn).slice(0,n)}function Bj(e,t,n,r){let i=[...new Set(r.map(m=>m.file))].sort(),o=[...new Set(r.filter(m=>m.source!=="caller-map-inversion"||m.callEvidence==="scip-chunk").map(m=>m.file))].sort(),s=new Map;for(let m of Pt(e,t,{limit:500,semantic:n,semanticEvidence:re})){if(m.file===t.relativePath)continue;let p=`${m.symbol}|${m.file}`;s.has(p)||s.set(p,{symbol:m.symbol,shortName:T(m.symbol),file:m.file,evidenceStrength:m.source==="scip-chunk"?"candidate":"exact",evidenceSource:m.source})}let a=[...s.values()].sort((m,p)=>m.file.localeCompare(p.file)||m.symbol.localeCompare(p.symbol)),c=i.length,l=a.length,u=c*l,d=a.filter(m=>m.evidenceStrength==="candidate").map(m=>m.symbol);return{symbol:t.symbol,shortName:T(t.symbol),fanIn:c,fanOut:l,callerFiles:i,candidateCallerFiles:o,externalCallees:a.map(({symbol:m,shortName:p,file:f})=>({symbol:m,shortName:p,file:f})),externalCalleeEvidence:a,candidateExternalCallees:d,inputBasis:"mixed-static-call-or-reference-evidence",score:u,definedIn:t.relativePath,actionTier:"signal",riskKind:"coordination-hotspot",evidenceReasons:[`${c} incoming file(s) reference this symbol`,`${l} distinct cross-file callee symbol(s) are reached from it`,`centrality score is ${u} (fan-in * fan-out)`,`${o.length} incoming file(s) and ${d.length} outgoing target(s) rely on candidate rather than exact call evidence`],recommendation:"Review ownership, API stability, and caller groups before changing this central symbol; do not refactor solely from graph centrality."}}function ns(e,t={}){let{scope:n,minLoc:r=3,scanLimit:i}=t,o=new H(e),s=t.semantic!==!1,a=0,c=N("isolated.candidates",()=>{let C=he(o.productionCallableDefinitions({scope:n,minLoc:r,excludeEntrySurfaces:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:typeof i=="number"&&i>0}),i).filter(R=>!_i(e,R));return a=C.length,C},()=>({definitions:a})),l=0,u=N("isolated.strict-callees",()=>{let v=o.symbolsWithNonSelfCallees(c,{additive:!1,semantic:!1});return l=v.size,v},()=>({definitions:c.length,symbols:l})),d=c.filter(v=>!u.has(v.symbolId)),m=0,p=N("isolated.scip-callers",()=>{let v=o.crossFileCallerMap(d,{semantic:!1});return m=v.size,v},()=>({definitions:d.length,symbols:m})),f=new Set(p.keys());for(let v of o.frameworkReferencedSymbolIds(d))f.add(v);let g=d.filter(v=>!f.has(v.symbolId));if(s&&g.length>0){for(let v of Jn(e,g).keys())f.add(v);for(let v of o.symbolsWithNonSelfCallees(g,{additive:!1,semantic:!0}))u.add(v);g=g.filter(v=>!f.has(v.symbolId)).filter(v=>!u.has(v.symbolId))}let h=0,b=N("isolated.source-fallback-callers",()=>{let v=o.sourceFallbackCallerFiles(g,{skipPath:C=>q(C)==="test"});return h=v.size,v},()=>({definitions:g.length,symbols:h}));for(let v of b.keys())f.add(v);let S=g.filter(v=>!f.has(v.symbolId)),y=0,x=N("isolated.additive-callees",()=>{let v=o.symbolsWithNonSelfCallees(S,{additive:!0,semantic:s});return y=v.size,v},()=>({definitions:S.length,symbols:y}));for(let v of x)u.add(v);return S.filter(v=>!u.has(v.symbolId)).sort((v,C)=>ee(C)-ee(v)||v.relativePath.localeCompare(C.relativePath)||v.startLine-C.startLine).map(v=>({symbol:v.symbol,shortName:T(v.symbol),relativePath:v.relativePath,startLine:v.startLine,endLine:v.endLine,loc:ee(v)}))}import{SymbolInformation_Kind as Ke}from"@c4312/scip";var dx=500;function $j(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),r=fg.get(n);if(r!==void 0)return r;for(let[i,o]of Zs)if(o.toLowerCase().includes(n))return i;return null}function jj(e,t,n={}){let{scope:r,limit:i=100}=n,o=$j(t);return o===null?[]:Uj(e,r).map(a=>({row:a,resolvedKind:px(a)})).filter(a=>a.resolvedKind===o).slice(0,i).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:T(a.symbol),kind:c,kindName:ro(c),relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function Hj(e,t={}){let n=qj(e,t.scope);for(let r of Gj(e,t.scope)){let i=px(r);i===null||i===0||n.set(i,(n.get(i)??0)+1)}return[...n.entries()].sort((r,i)=>i[1]-r[1]||r[0]-i[0]).map(([r,i])=>({kind:r,kindName:ro(r),count:i}))}function Uj(e,t){return Le(e,{scope:t}).map(zj)}function qj(e,t){let n=new Map;for(let r of mx(Z(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", "),o=e.all(`SELECT gs.kind AS kind, COUNT(*) AS count
297
- FROM defn_enclosing_ranges der
298
- JOIN global_symbols gs ON der.symbol_id = gs.id
299
- JOIN documents d ON der.document_id = d.id
300
- WHERE gs.kind IS NOT NULL
301
- AND gs.kind != 0
302
- AND gs.symbol NOT LIKE '%#'
303
- AND d.relative_path IN (${i})
304
- GROUP BY gs.kind`,...r);for(let s of o)n.set(s.kind,(n.get(s.kind)??0)+s.count)}return n}function Gj(e,t){let n=[];for(let r of mx(Z(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", ");n.push(...e.all(`SELECT gs.symbol,
305
- gs.kind,
306
- gs.documentation,
307
- gs.enclosing_symbol,
308
- d.relative_path,
309
- der.start_line,
310
- der.end_line
311
- FROM defn_enclosing_ranges der
312
- JOIN global_symbols gs ON der.symbol_id = gs.id
313
- JOIN documents d ON der.document_id = d.id
314
- WHERE (gs.kind IS NULL OR gs.kind = 0 OR gs.symbol LIKE '%#')
315
- ${e.symbolNoiseFor("gs")}
316
- AND d.relative_path IN (${i})
317
- ORDER BY d.relative_path, der.start_line, der.end_line, gs.symbol`,...r))}return n}function mx(e){let t=[];for(let n=0;n<e.length;n+=dx)t.push(e.slice(n,n+dx));return t}function zj(e){return{symbol:e.symbol,kind:e.kind,documentation:e.documentation,enclosing_symbol:e.enclosingSymbol,relative_path:e.relativePath,start_line:e.startLine,end_line:e.endLine}}function px(e){return e.kind!==null&&e.kind!==0?Kj(e.kind,e.symbol,e.documentation):Wj(e.symbol,e.documentation,e.enclosing_symbol)}function Kj(e,t,n){let r=(n??"").toLowerCase();if(wt(t)==="type"){if(r.includes("type "))return Ke.TypeAlias;if(r.includes("interface "))return Ke.Interface;if(r.includes("struct "))return Ke.Struct;if(r.includes("trait "))return Ke.Trait;if(r.includes("class "))return Ke.Class}return e}function Wj(e,t,n){let r=Bn(e);if("kind"in r)return null;let i=r.descriptors,o=i[i.length-2]??null,s=wt(e),a=(t??"").toLowerCase();return s==="type"?a.includes("type ")?Ke.TypeAlias:a.includes("interface ")?Ke.Interface:a.includes("struct ")?Ke.Struct:a.includes("trait ")?Ke.Trait:a.includes("class ")?Ke.Class:Ke.Class:s==="method"?o?.suffix==="type"?Ke.Method:Ke.Function:s==="namespace"?Ke.Module:s!=="term"?null:a.includes("async def ")||a.includes("def ")?Ke.Function:(n?wt(n):o?.suffix??null)==="type"?Ke.Field:Ke.Variable}function Vj(e,t={}){let{limit:n=10,scope:r,minDepth:i=3,edgeBasis:o="symbol-references"}=t,s=Me(e,r,o==="imports"?{scipEdges:"imports-only",sourceEdges:"imports-only"}:void 0),{components:a,componentOf:c}=Kr(s),l=new Map;for(let h=0;h<a.length;h++)l.set(h,new Set);for(let[h,b]of s){let S=c.get(h);for(let y of b){let x=c.get(y);x!==S&&l.get(S).add(x)}}let u=new Array(a.length),d=new Array(a.length);for(let h=0;h<a.length;h++){let b=[],S=0;for(let y of[...l.get(h)].sort((x,v)=>x-v)){let x=d[y];(x>S||x===S&&Yj(u[y],b,a)<0)&&(S=x,b=u[y])}u[h]=[h,...b],d[h]=1+S}function m(h){return u[h]}let p=a.map(h=>[...h].sort()),f=new Set,g=[];for(let h=0;h<a.length;h++){let S=m(h).map(v=>p[v]),y=S.map(v=>v[0]);if(S.length<i)continue;let x=y.join(" ");f.has(x)||(f.add(x),g.push(Jj(y,S,o)))}return g.sort((h,b)=>b.depth-h.depth||h.chain.join("\0").localeCompare(b.chain.join("\0"))),Xj(g).slice(0,n)}function Yj(e,t,n){if(t.length===0)return-1;let r=e.map(o=>[...n[o]].sort()[0]??"").join("\0"),i=t.map(o=>[...n[o]].sort()[0]??"").join("\0");return r.localeCompare(i)}function Jj(e,t,n){let r=t.reduce((o,s)=>o+s.length,0),i=t.filter(o=>o.length>1).length;return{chain:e,components:t,depth:t.length,fileCount:r,edgeBasis:n,actionTier:"signal",chainKind:"transitive-dependency-depth",evidenceReasons:[`${t.length} condensed dependency component(s) form the representative transitive path`,`${r} file(s) are represented; ${i} component(s) contain a dependency cycle`,`edge basis: ${n==="imports"?"resolved file imports":"cross-file symbol references plus resolved source imports"}`,"cycles count once toward depth and retain their full membership separately"],recommendation:"Review whether the chain crosses ownership or layer boundaries; shorten it only when the dependency direction is accidental."}}function Xj(e){let t=[];for(let n of e)t.some(r=>Qj(n.chain,r.chain))||t.push(n);return t}function Qj(e,t){if(e.length>=t.length)return!1;let n=t.length-e.length;for(let r=0;r<e.length;r++)if(e[r]!==t[n+r])return!1;return!0}function Zj(e,t){let n=ne(e,t);if(!n)return[];let r=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
318
- WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:T(r.symbol),depth:0}],o=r.enclosing_symbol,s=1,a=new Set([r.symbol]);for(;o&&!a.has(o)&&s<20;){a.add(o);let d=e.get("SELECT symbol, enclosing_symbol FROM global_symbols WHERE symbol = ?",o);if(!d)break;i.push({symbol:d.symbol,shortName:T(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(i.length>1)return i;let c=Bn(r.symbol);if("kind"in c)return i;let l=c.descriptors;if(l.length<=1)return i;let u=[i[0]];for(let d=l.length-2,m=1;d>=0;d--,m++){let f=l.slice(0,d+1).map(g=>g.suffix==="method"?`${g.name}()`:g.name.replace(/\.(ts|tsx|js|jsx|mjs|cjs|py|pyi|rs|java|scala|kt|kts|rb|go|cs|vb|dart|php|c|cc|cpp|cxx|h|hpp)$/,"")).join(":");u.push({symbol:f,shortName:f,depth:m})}return u}function e1(e,t={}){let r=new H(e).productionCallableDefinitions({scope:t.scope,requireCallableSymbol:!0,includeSuppressed:!0}),i=yx(e,r),o=t.search?.trim().toLocaleLowerCase();return r.map(s=>bx(e,s,i.get(s.symbolId)??[])).filter(s=>s!==null).map(s=>s.result).filter(s=>!o||r1(s).includes(o)).sort(i1)}function t1(e,t,n={}){let r=Qe(e,t);if(!r.match)return{kind:"missing",query:t};if(r.total>1)return{kind:"ambiguous",query:t,total:r.total,candidates:[{symbol:r.match.symbol,shortName:T(r.match.symbol),relativePath:r.match.relativePath,startLine:r.match.startLine},...r.candidates]};let i=new H(e),o=i.definitionsForFile(r.match.relativePath).find(p=>p.symbol===r.match.symbol);if(!o?.isFunctionLike)return{kind:"not-entry",query:t,symbol:r.match.symbol,shortName:T(r.match.symbol),file:r.match.relativePath,reason:"The resolved symbol is not a callable definition."};let s=yx(e,[o]),a=bx(e,o,s.get(o.symbolId)??[]);if(!a)return{kind:"not-entry",query:t,symbol:o.symbol,shortName:T(o.symbol),file:o.relativePath,reason:"The callable is neither an external root nor an uncalled callable on a detected entry surface."};let c=o1(e,i,o),l=new Set(n.expand??[]),u=l1(c,l),d=new Set(u.regions.filter(p=>p.expanded).map(p=>p.id)),m=[...l].filter(p=>!d.has(p)).sort();return{kind:"matched",query:t,entry:a.result,regions:u.regions,regionEdges:u.regionEdges,unmatchedExpansions:m,coverage:{completeWithinIndexedStaticCallEdges:!0,completeWithinSelectedStaticEvidence:!0,candidateReachabilityIncluded:c.edges.some(p=>p.evidenceStrength==="candidate"),dynamicDispatchRepresented:!1,symbolCount:c.symbols.length,symbolEdgeCount:c.edges.length,exactSymbolEdgeCount:c.edges.filter(p=>p.evidenceStrength==="exact").length,candidateSymbolEdgeCount:c.edges.filter(p=>p.evidenceStrength==="candidate").length,regionCount:u.regions.length,regionEdgeCount:u.regionEdges.length,externalCallCount:c.externalCalls.length}}}function yx(e,t){let n=t.filter(r=>Sx(e,r.relativePath)||Ii(e,r.symbol,r.relativePath).length>0);return yn(e,n,{semantic:!1,semanticEvidence:re})}function bx(e,t,n){let r=n1(e,t),i=r.length>0,o=Sx(e,t.relativePath)&&n.length===0;if(!i&&!o)return null;let s=[...r];return o&&s.push("entry-surface-without-indexed-caller"),{definition:t,result:{symbol:t.symbol,shortName:T(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,documentation:t.documentation,confidence:i?"root":"candidate",evidence:s,indexedCallerCount:n.length}}}function Sx(e,t){return Ue(e,t)||/(?:^|\/)entry\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(t)}function n1(e,t){let n=Ii(e,t.symbol,t.relativePath),r=[];return fx(n,["package-surface-file","transitive-package-surface"])&&pt(e,t)&&r.push("package-public-export"),n.includes("rust-public-library")&&r.push("rust-public-library"),n.includes("framework-entrypoint")&&r.push("framework-dispatched-export"),fx(n,["configured-file","configured-path-prefix","configured-qualified-var","configured-symbol-pattern"])&&r.push("configured-entry-root"),r}function fx(e,t){return t.some(n=>e.includes(n))}function r1(e){return[e.symbol,e.shortName,e.file,e.documentation??"",...e.evidence].join(`
319
- `).toLocaleLowerCase()}function i1(e,t){return gx(e.confidence)-gx(t.confidence)||e.file.localeCompare(t.file)||e.startLine-t.startLine||e.symbol.localeCompare(t.symbol)}function gx(e){return e==="root"?0:1}function o1(e,t,n){let r=new Map([[n.symbol,0]]),i=new Map,o=new Map([[n.symbol,n]]),s=new Map,a=new Map,c=[n];for(;c.length>0;){let l=t.calleeMap(c,{additive:!1,semantic:!1}),u=[];for(let d of c){let m=r.get(d.symbol)??0;i.set(d.symbol,hx(d,m));for(let p of l.get(d.symbolId)??[]){let f=s1(t,p,o);if(!f){let S=c1(d,p);a.set(m1(S),S);continue}let g=m+1,h=r.get(f.symbol);(h===void 0||g<h)&&r.set(f.symbol,g),i.set(f.symbol,hx(f,Math.min(g,h??g)));let b=a1(d,f,p);s.set(d1(b),b),h===void 0&&u.push(f)}}c=u}return{symbols:[...i.values()].sort(p1),edges:[...s.values()].sort(f1),externalCalls:[...a.values()].sort(g1)}}function s1(e,t,n){let r=n.get(t.symbol);if(r)return r;let i=e.definitionsForFile(t.file).find(o=>o.symbol===t.symbol)??null;return i&&n.set(i.symbol,i),i}function hx(e,t){return{symbol:e.symbol,shortName:T(e.symbol),file:e.relativePath,depth:t}}function a1(e,t,n){return{fromSymbol:e.symbol,fromShortName:T(e.symbol),fromFile:e.relativePath,toSymbol:t.symbol,toShortName:T(t.symbol),toFile:t.relativePath,source:n.source,evidenceStrength:n.source==="scip-chunk"?"candidate":"exact"}}function c1(e,t){return{fromSymbol:e.symbol,fromShortName:T(e.symbol),fromFile:e.relativePath,toSymbol:t.symbol,toShortName:T(t.symbol),reportedFile:t.file,source:t.source,evidenceStrength:t.source==="scip-chunk"?"candidate":"exact"}}function l1(e,t){let n=_e(e.symbols,l=>l.file),r=_e(e.edges.filter(l=>l.fromFile===l.toFile),l=>l.fromFile),i=_e(e.externalCalls,l=>l.fromFile),o=u1(e.edges.filter(l=>l.fromFile!==l.toFile)),s=_e(o,l=>l.toRegionId),a=_e(o,l=>l.fromRegionId);return{regions:[...n.entries()].map(([l,u])=>{let d=im(l),m=t.has(d),p=r.get(l)??[],f=i.get(l)??[];return{id:d,file:l,minDepth:Math.min(...u.map(g=>g.depth)),symbolCount:u.length,internalEdgeCount:p.length,externalCallCount:f.length,incomingRegionIds:rs((s.get(d)??[]).map(g=>g.fromRegionId)),outgoingRegionIds:rs((a.get(d)??[]).map(g=>g.toRegionId)),expanded:m,symbols:m?u:[],internalEdges:m?p:[],externalCalls:m?f:[]}}).sort((l,u)=>l.minDepth-u.minDepth||l.file.localeCompare(u.file)),regionEdges:o}}function u1(e){let t=new Map;for(let n of e){let r=`${n.fromFile}\0${n.toFile}`,i=t.get(r)??[];i.push(n),t.set(r,i)}return[...t.values()].map(n=>{let r=n[0];return{fromRegionId:im(r.fromFile),fromFile:r.fromFile,toRegionId:im(r.toFile),toFile:r.toFile,callCount:n.length,exactCallCount:n.filter(i=>i.evidenceStrength==="exact").length,candidateCallCount:n.filter(i=>i.evidenceStrength==="candidate").length,fromSymbols:rs(n.map(i=>i.fromShortName)),toSymbols:rs(n.map(i=>i.toShortName)),evidence:rs(n.map(i=>i.source))}}).sort((n,r)=>n.fromFile.localeCompare(r.fromFile)||n.toFile.localeCompare(r.toFile))}function im(e){return`file:${e}`}function rs(e){return[...new Set(e)].sort()}function d1(e){return`${e.fromSymbol}\0${e.toSymbol}`}function m1(e){return`${e.fromSymbol}\0${e.toSymbol}`}function p1(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)||e.symbol.localeCompare(t.symbol)}function f1(e,t){return e.fromFile.localeCompare(t.fromFile)||e.fromSymbol.localeCompare(t.fromSymbol)||e.toSymbol.localeCompare(t.toSymbol)}function g1(e,t){return e.fromFile.localeCompare(t.fromFile)||e.fromSymbol.localeCompare(t.fromSymbol)||e.toSymbol.localeCompare(t.toSymbol)}function kt(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function We(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function ur(e,t){if(e.size===0&&t.size===0)return 0;let n=0;for(let i of e)t.has(i)&&(n+=1);let r=e.size+t.size-n;return r===0?0:n/r}function vx(e,t){if(e.size===0)return 0;let n=0;for(let r of e)t.has(r)&&(n+=1);return n/e.size}function om(e,t){if(t<=0)return new Map;let n=new Map;for(let[r,i]of e)i>0&&n.set(r,Math.log(t/i));return n}function Bi(e){let t=[...e.values()].sort((r,i)=>r-i);if(t.length===0)return 0;let n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function $i(e,t){let n=0;for(let r of e){let i=t.get(r)??0;n+=i*i}return Math.sqrt(n)}function Cx(e,t,n,r={}){let i=0,o=0,s=0,a=r.medianIdf??Bi(n),c=[],l=[];for(let m of e){let p=n.get(m)??0;o+=p*p,t.has(m)&&(i+=p*p,p>=a?c.push(m):l.push(m))}if(c.length===0&&l.length===0)return{similarity:0,significantShared:[],trivialShared:[]};for(let m of t){let p=n.get(m)??0;s+=p*p}let u=Math.sqrt(o)*Math.sqrt(s),d=u>0?i/u:0;return c.sort((m,p)=>(n.get(p)??0)-(n.get(m)??0)),{similarity:d,significantShared:c,trivialShared:l}}function xx(e,t,n,r){let i=0,o=r.medianIdf??Bi(n),s=[],a=[];for(let u of e){if(!t.has(u))continue;let d=n.get(u)??0;i+=d*d,d>=o?s.push(u):a.push(u)}if(s.length===0&&a.length===0)return{similarity:0,significantShared:[],trivialShared:[]};let c=r.magnitudeA*r.magnitudeB,l=c>0?i/c:0;return s.sort((u,d)=>(n.get(d)??0)-(n.get(u)??0)),{similarity:l,significantShared:s,trivialShared:a}}function is(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=E1(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!Se(o.symbol))return[];if(o.callees.size===0)return Rx(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"});let s=y1(e,o,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,i):Rx(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"})}function lm(e,t,n,r={}){let i=ne(e,t),o=ne(e,n);if(!i||!o)return null;let s=is(e,i.symbol,{minSimilarity:0,limit:Number.POSITIVE_INFINITY,semantic:r.semantic,scanLimit:r.scanLimit}).find(l=>l.symbolB===o.symbol||l.symbolA===o.symbol);if(!s)return null;let a=i.endLine-i.startLine+1,c=o.endLine-o.startLine+1;return{symbolA:{symbol:i.symbol,shortName:T(i.symbol),file:i.relativePath,loc:a},symbolB:{symbol:o.symbol,shortName:T(o.symbol),file:o.relativePath,loc:c},similarity:s.similarity,similarityBasis:s.similarityBasis??"callees",sharedEvidence:s.sharedCallees,uniqueToA:s.uniqueToA,uniqueToB:s.uniqueToB,evidenceClass:s.evidenceClass,actionTier:s.actionTier,recommendation:s.recommendation,consolidationStrategy:h1(s)}}function h1(e){let t=e.similarityBasis==="source-tokens"?"source-token":"tracked callee";return e.sharedCallees.length===0?`No shared ${t} evidence survived similar's weighting. Inspect the source before attempting consolidation.`:e.uniqueToA.length===0&&e.uniqueToB.length===0?`The functions have identical ${t} evidence under similar's weighting. Verify signatures, guards, and return values before consolidating.`:e.uniqueToA.length===0?`A's ${t} evidence is a subset of B's. B may subsume part of A's structure, but verify signatures, guards, and non-call logic first.`:e.uniqueToB.length===0?`B's ${t} evidence is a subset of A's. A may subsume part of B's structure, but verify signatures, guards, and non-call logic first.`:e.uniqueToA.length<=2&&e.uniqueToB.length<=2?`Create a shared helper around the ${e.sharedCallees.length} shared ${t}(s). Pass the ${e.uniqueToA.length+e.uniqueToB.length} divergent point(s) as parameters or callbacks.`:`Extract the ${e.sharedCallees.length} shared ${t}(s) into a common helper. Keep each function's unique logic outside that helper (${e.uniqueToA.length} item(s) in A, ${e.uniqueToB.length} in B).`}function y1(e,t,n,r){let i=ji(e).calleeIndex({minCallees:3,scanLimit:r.scanLimit,semantic:r.semantic}),o=k1(t,i.corpus),s=D1(o,i),a=b1(o,i),c=Bi(a),l=$i(o.callees,a),u=[];for(let d of s){if(d.callees.size<3)continue;let m=$i(d.callees,a),p=Lx(o,d,a,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0,medianIdf:c,magnitudeA:l,magnitudeB:m});p&&u.push(p)}return u.sort((d,m)=>m.similarity-d.similarity),u}function b1(e,t){let n=new Map(t.docFreq);for(let r of e.callees)n.set(r,(n.get(r)??0)+1);return om(n,t.corpus.length+1)}function Lx(e,t,n,r){let i=v1(e,t,n,r);if(!C1(i,r))return null;let{similarity:o,significantShared:s,trivialShared:a}=i,c=s.length>0?s:a,l=kx(c,"callees");return{symbolA:e.symbol,shortNameA:T(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:T(t.symbol),fileB:t.file,similarity:o,similarityBasis:"callees",sharedCallees:c.map(T),uniqueToA:[...We(e.callees,t.callees)].map(T),uniqueToB:[...We(t.callees,e.callees)].map(T),...l}}function S1(e,t,n,r){let i=r.magnitudeA??$i(e.callees,n),o=r.magnitudeB??$i(t.callees,n),s=0,a=0,c=0,l=r.medianIdf??Bi(n);for(let m of e.callees){if(!t.callees.has(m))continue;let p=n.get(m)??0;s+=p*p,c+=1,p>=l&&(a+=1)}if(c===0)return!1;let u=i*o;return(u>0?s/u:0)<r.minSimilarity?!1:a>=r.requireSignificantShared||c>=r.requireSharedCount}function v1(e,t,n,r){return r.magnitudeA===void 0||r.magnitudeB===void 0?Cx(e.callees,t.callees,n,{medianIdf:r.medianIdf}):xx(e.callees,t.callees,n,{medianIdf:r.medianIdf,magnitudeA:r.magnitudeA,magnitudeB:r.magnitudeB})}function C1(e,t){if(e.similarity<t.minSimilarity)return!1;let n=e.significantShared.length+e.trivialShared.length;return e.significantShared.length>=t.requireSignificantShared||n>=t.requireSharedCount}function os(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=t.semantic!==!1,l=be(),u=0,d=0,m=0,p=0,f=0,g=0,h=0;return N("similar.all",()=>{let S=ji(e).calleeIndex({minCallees:o,scope:i,scanLimit:a,semantic:c}),y=S.corpus;u=y.length;let x=t.focusFiles,v=[],C=0;return N("similar.all.pair-scan",()=>{for(let R=0;R<y.length;R+=1){let E=y[R],w=x?.has(E.file)??!1,I=S.weightedMagnitudes[R],k=new Set;for(let D of E.callees){let F=S.candidateIndexesByCallee.get(D);if(F)for(let L of F)L<=R||x&&!w&&!x.has(y[L].file)||k.add(L)}l&&(m+=k.size,k.size>0&&(d+=1));for(let D of k){let F=y[D];if(s&&E.file===F.file){l&&(f+=1);continue}if(Px(E,F)){l&&(g+=1);continue}l&&(p+=1);let L=Lx(E,F,S.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:S.medianIdf,magnitudeA:I,magnitudeB:S.weightedMagnitudes[D]});L&&(x1(v,L,r,C),l&&(h+=1),C+=1)}}},()=>({corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:p,crossFileSkips:f,signatureSkips:g,insertedResults:h,topResults:v.length})),N("similar.all.sort-project",()=>(v.sort((R,E)=>E.result.similarity-R.result.similarity||R.order-E.order),v.map(R=>R.result)),()=>({topResults:v.length}))},()=>({minSimilarity:n,limit:r,scope:i,minCallees:o,crossFileOnly:s,scanLimit:a,semantic:c,corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:p,crossFileSkips:f,signatureSkips:g,insertedResults:h}))}function um(e,t={}){let{minSimilarity:n=.5,scope:r,minCallees:i=4,crossFileOnly:o=!1,scanLimit:s}=t,a=t.semantic!==!1,c=be(),l=0,u=0,d=0,m=0,p=0,f=0,g=0;return N("similar.all-count",()=>{let b=ji(e).calleeIndex({minCallees:i,scope:r,scanLimit:s,semantic:a}),S=b.corpus;l=S.length;let y=t.focusFiles;return N("similar.all-count.pair-scan",()=>{for(let x=0;x<S.length;x+=1){let v=S[x],C=y?.has(v.file)??!1,R=b.weightedMagnitudes[x],E=new Set;for(let w of v.callees){let I=b.candidateIndexesByCallee.get(w);if(I)for(let k of I)k<=x||y&&!C&&!y.has(S[k].file)||E.add(k)}c&&(d+=E.size,E.size>0&&(u+=1));for(let w of E){let I=S[w];if(o&&v.file===I.file){c&&(p+=1);continue}if(Px(v,I)){c&&(f+=1);continue}c&&(m+=1),S1(v,I,b.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:b.medianIdf,magnitudeA:R,magnitudeB:b.weightedMagnitudes[w]})&&(g+=1)}}},()=>({corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:p,signatureSkips:f,insertedResults:g})),g},()=>({minSimilarity:n,scope:r,minCallees:i,crossFileOnly:o,scanLimit:s,semantic:a,corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:p,signatureSkips:f,insertedResults:g}))}function Px(e,t){if(e.paramCount<0||t.paramCount<0)return!1;let n=Math.abs(e.paramCount-t.paramCount),r=Math.max(2,Math.ceil(Math.max(e.paramCount,t.paramCount)*.5));return n>r}var Dx=dt({kind:"source-fingerprints",invalidation:$e("source-fingerprints"),serialize:Q1,deserialize:X1});function x1(e,t,n,r){if(n<=0)return;if(e.length<n){e.push({result:t,order:r});return}let i=0;for(let s=1;s<e.length;s+=1){let a=e[s],c=e[i];(a.result.similarity<c.result.similarity||a.result.similarity===c.result.similarity&&a.order>c.order)&&(i=s)}let o=e[i];t.similarity<=o.result.similarity||(e[i]={result:t,order:r})}var R1=["ScipDatabase#all","ScipDatabase#get","ScipDatabase#prepare","ScipDatabase#pathExclusionsFor","ScipDatabase#isIgnored","ScipDatabase#symbolNoiseFor","PerDbValue#get","PerDbValue#has",":storage:db:ScipDatabase:all",":storage:db:ScipDatabase:get",":storage:db:ScipDatabase:prepare",":storage:db:ScipDatabase:pathExclusionsFor",":storage:db:ScipDatabase:isIgnored",":storage:db:ScipDatabase:symbolNoiseFor",":storage:per-db-cache:PerDbValue:get",":storage:per-db-cache:PerDbValue:has"];function E1(e,t,n){let r=ne(e,t);if(!r||!Se(r.symbol))return null;let i=new H(e),o=Pt(e,r,{semantic:n.semantic,semanticEvidence:re});return{symbol:r.symbol,file:r.relativePath,callees:Pc(o.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}var I1=ge("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),w1=ge("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function Mx(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:o}=t,s=t.semantic!==!1,a=I1.get(e,()=>new Map),c=`${n}|${r??""}|${o??""}|${s}`,l=!0,u=0,d=0;return N("similar.callee-fingerprints.resolve",()=>{let m=a.get(c);if(l=m!==void 0,m||(m=M1(e,{minCallees:n,scope:r,scanLimit:o,semantic:s}),a.set(c,m)),u=m.length,i===void 0)return m;let p=m.filter(f=>f.symbol!==i);return d=m.length-p.length,p},()=>({minCallees:n,scope:r,scanLimit:o,semantic:s,cacheHit:l,corpusSize:u,excludeSymbol:i!==void 0,excludedSymbols:d}))}function L1(e,t){let{minCallees:n,scope:r,scanLimit:i}=t,o=t.semantic!==!1,s=w1.get(e,()=>new Map),a=`${n}|${r??""}|${i??""}|${o}`,c=!0,l=0,u=0,d=0;return N("similar.callee-index.resolve",()=>{let m=s.get(a);return c=m!==void 0,m||(m=P1(Mx(e,{minCallees:n,scope:r,scanLimit:i,semantic:o})),s.set(a,m)),l=m.corpus.length,u=m.docFreq.size,d=m.candidateIndexesByCallee.size,m},()=>({minCallees:n,scope:r,scanLimit:i,semantic:o,cacheHit:c,corpusSize:l,indexedCallees:u,candidateBuckets:d}))}function ji(e){return{calleeCorpus:t=>Mx(e,t),calleeIndex:t=>L1(e,t),sourceCorpus:(t={})=>Ox(e,t),sourceIndex:(t={})=>wx(e,t),sourceCandidates:(t,n)=>(n.candidateMode??"full")==="target-pruned"?q1(e,t,{minSimilarity:n.minSimilarity,scanLimit:n.scanLimit}):U1(t,wx(e,{scanLimit:n.scanLimit}))}}function P1(e){let t=be(),n=0,r=N("similar.callee-index.doc-frequency",()=>{let m=new Map;for(let p of e)for(let f of p.callees)m.set(f,(m.get(f)??0)+1);return n=m.size,m},()=>({corpusSize:e.length,uniqueCallees:n})),i=Math.max(8,Math.ceil(Math.sqrt(e.length))),o=N("similar.callee-index.idf-weights",()=>om(r,e.length),()=>({corpusSize:e.length,uniqueCallees:r.size})),s=N("similar.callee-index.weighted-magnitudes",()=>e.map(m=>$i(m.callees,o)),()=>({corpusSize:e.length})),a=0,c=0,l=0,u=N("similar.callee-index.candidate-buckets",()=>{let m=new Map;for(let p=0;p<e.length;p+=1){let f=e[p];for(let g of f.callees){if((r.get(g)??0)>i){t&&(c+=1);continue}let h=m.get(g);h||(h=[],m.set(g,h)),h.push(p),t&&(a+=1)}}return t&&(l=m.size),m},()=>({corpusSize:e.length,buckets:l,candidateRefs:a,ubiquitousSkips:c,ubiquityThreshold:i})),d=N("similar.callee-index.median-idf",()=>Bi(o),()=>({uniqueCallees:o.size}));return{corpus:e,candidateIndexesByCallee:u,docFreq:r,idfWeights:o,weightedMagnitudes:s,medianIdf:d,ubiquityThreshold:i}}function D1(e,t){let n=new Map;for(let r of e.callees)for(let i of t.candidateIndexesByCallee.get(r)??[]){let o=t.corpus[i];o.symbol!==e.symbol&&n.set(o.symbol,o)}return n.size>0?[...n.values()]:t.corpus.filter(r=>r.symbol!==e.symbol)}function M1(e,t){let{minCallees:n,scope:r,scanLimit:i,semantic:o}=t,s=be(),a=new H(e),c=0,l=N("similar.callee-fingerprints.candidates",()=>{let g=he(a.productionCallableDefinitions({scope:r,minLoc:5,sortByLocDesc:typeof i=="number"&&i>0}),i);return c=g.length,g},()=>({scope:r,scanLimit:i,candidateCount:c})),u=0,d=N("similar.callee-fingerprints.callee-map",()=>{let g=a.calleeMap(l,{semantic:o});if(s)for(let h of g.values())u+=h.length;return g},()=>({candidateCount:c,semantic:o,calleeEdges:u})),m=0,p=0,f=0;return N("similar.callee-fingerprints.shape",()=>{let g=l.map(S=>({symbol:S.symbol,file:S.relativePath,callees:Pc((d.get(S.symbolId)??[]).map(y=>y.symbol)),paramCount:a.callableSignature(S)?.paramCount??-1})),h=T1(g);s&&(f=h.filter((S,y)=>S.callees.size!==g[y].callees.size).length);let b=h.filter(S=>S.callees.size>=n);return m=b.length,s&&(p=b.reduce((S,y)=>S+y.callees.size,0)),b},()=>({candidateCount:c,fingerprintCount:m,retainedCalleeCount:p,minCallees:n,siblingSaturatedFingerprints:f}))}var Tx=5;function T1(e){let t=new Map;for(let n of e){let r=t.get(n.file);r||(r=new Map,t.set(n.file,r));for(let i of n.callees)r.set(i,(r.get(i)??0)+1)}return e.map(n=>{let r=t.get(n.file);if(!r)return n;let i=[...n.callees].filter(s=>(r.get(s)??0)>=Tx);if(i.length===0)return n;let o=new Set(n.callees);for(let s of i)o.delete(s);return{...n,callees:o}})}function k1(e,t){let n=new Map;for(let o of t)if(!(o.file!==e.file||o.symbol===e.symbol))for(let s of o.callees)n.set(s,(n.get(s)??0)+1);let r=[...e.callees].filter(o=>(n.get(o)??0)+1>=Tx);if(r.length===0)return e;let i=new Set(e.callees);for(let o of r)i.delete(o);return{...e,callees:i}}function Pc(e){return new Set([...e].filter(t=>!A1(t)))}function A1(e){return R1.some(t=>e.includes(t))}function Rx(e,t,n){let r=O1(e,t);if(!r||r.tokens.size<3)return[];let i=n.minSimilarity>=.5?n.minSimilarity:.3,o=[],s=n.candidateMode??"full",a=0,c=0,l=0,u=0;return N("similar.source-shape",()=>{let m=ji(e).sourceCandidates(r,{minSimilarity:i,scanLimit:n.scanLimit,candidateMode:s});a=m.length;for(let p of m){if(p.symbol===r.symbol||p.tokens.size<3)continue;c+=1;let f=kt(r.tokens,p.tokens);if(f.size<2){l+=1;continue}let g=new Set([...r.tokens,...p.tokens]),h=g.size>0?f.size/g.size:0;if(h<i){u+=1;continue}o.push({symbolA:r.symbol,shortNameA:T(r.symbol),fileA:r.file,symbolB:p.symbol,shortNameB:T(p.symbol),fileB:p.file,similarity:h,similarityBasis:"source-tokens",sharedCallees:[...f].sort(),uniqueToA:[...We(r.tokens,p.tokens)].sort(),uniqueToB:[...We(p.tokens,r.tokens)].sort(),...kx([...f],"source-tokens")})}return o.sort((p,f)=>f.similarity-p.similarity||p.shortNameB.localeCompare(f.shortNameB)),o.slice(0,n.limit)},()=>({symbol:r.symbol,file:r.file,targetTokens:r.tokens.size,candidateMode:s,candidates:a,comparedPairs:c,sharedSkips:l,similaritySkips:u,results:o.length}))}function kx(e,t){let n=e.flatMap(am),r=e.flatMap(h=>Ex(h,t)),i=sm(n,Ax),o=sm(n,Fx),s=sm(r,cm),a=[...new Set(r.filter(Ix))],c=e.filter(h=>{let b=Ex(h,t);return b.some(S=>cm.has(S))&&b.some(Ix)}).length,l=[];i.length>0&&l.push(`access/query scaffolding: ${i.slice(0,5).join(", ")}`),o.length>0&&l.push(`framework/generic scaffolding: ${o.slice(0,5).join(", ")}`),s.length>0&&l.push(`domain behavior verbs: ${s.slice(0,5).join(", ")}`),s.length>0&&a.length>0&&l.push(`domain-specific terms: ${a.slice(0,5).join(", ")}`);let u=t==="source-tokens"&&n.length>0&&n.every(h=>Nx.has(h));u&&l.push("shared source tokens are generic scaffolding");let d=s.length>0&&a.length>0,m=i.length+o.length>0,p=t==="callees"&&d&&e.length>=4&&a.length>=4&&c>=2,f=p?"domain-behavior":d?m?"mixed":"domain-behavior":i.length>0?"access-query-scaffolding":o.length>0||u?"framework-scaffolding":"structural-overlap";f==="structural-overlap"&&e.length>0&&l.push(`shared ${t} overlap has no recognized domain or scaffolding category`);let g=f==="domain-behavior"&&(e.length>=3||p)?"direct":"signal";return{evidenceClass:f,actionTier:g,evidenceClassReasons:l,recommendation:F1(f,g)}}function F1(e,t){return t==="direct"?"Shared domain behavior looks concrete; review for an extract/reuse opportunity.":e==="mixed"?"Shared evidence mixes domain behavior with scaffolding; review semantics before extracting anything.":e==="access-query-scaffolding"?"Shared evidence is mostly access/query scaffolding; compare product semantics before reusing code.":e==="structural-overlap"?"Shared structure has no domain or scaffolding classification; inspect names and behavior before reusing code.":"Shared evidence is mostly framework or generic scaffolding; treat as a contextual signal."}function sm(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function am(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function Ex(e,t){if(t==="source-tokens")return am(e);let n=z(e);return am(n.length>0?n:N1(e))}function N1(e){return e.replace(/[()`]/g," ").replace(/\.[a-z][a-z0-9]+(?=\s|$)/gi," ").split(/[:/\\\s]+/).map(r=>r.trim()).filter(r=>/[A-Za-z]/.test(r)).at(-1)?.replace(/\.$/,"")??e}function Ix(e){return e.length>3&&!cm.has(e)&&!Ax.has(e)&&!Fx.has(e)&&!Nx.has(e)&&!_1.has(e)}var cm=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),Ax=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),Fx=new Set(["bytes","computed","crypto","describe","effect","expect","fetch","filter","hex","hook","json","map","mounted","on","promise","random","react","reduce","ref","render","state","test","token","trim","uuid","vue","watch"]),Nx=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),_1=new Set(["best","backend","conflict","database","effect","effects","error","errors","frontend","found","helpers","javascript","module","modules","scip","shared","source","typescript","utils","with","workflow","workflows"]);function O1(e,t){let n=ne(e,t);if(!n||!Se(n.symbol))return null;let r=B1(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function B1(e,t){let n=z(t.symbol),r=V1(e,t.relativePath,t.startLine,t.endLine,n),i=jx(r,n);return i.size>0?i:null}var $1=ge("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),j1=ge("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function _x(e){return`${e.scanLimit??""}`}function Ox(e,t={}){let n=$1.get(e,()=>new Map),r=_x(t),i=n.get(r);return i||(i=W1(e,t),n.set(r,i)),i}function wx(e,t={}){let n=j1.get(e,()=>new Map),r=_x(t),i=n.get(r);return i||(i=H1(Ox(e,t)),n.set(r,i)),i}function H1(e){let t=new Map;for(let i of e)for(let o of i.tokens)t.set(o,(t.get(o)??0)+1);let n=Math.max(8,Math.ceil(Math.sqrt(e.length))),r=new Map;for(let i of e)for(let o of i.tokens){if((t.get(o)??0)>n)continue;let s=r.get(o);s||(s=[],r.set(o,s)),s.push(i)}return{corpus:e,candidateByToken:r,docFreq:t,ubiquityThreshold:n}}function U1(e,t){let n=new Map;for(let r of e.tokens)for(let i of t.candidateByToken.get(r)??[])i.symbol!==e.symbol&&n.set(i.symbol,i);return n.size>0?[...n.values()]:t.corpus.filter(r=>r.symbol!==e.symbol)}function q1(e,t,n){let r=be(),i=new H(e),o=G1(t.tokens.size,n.minSimilarity),s=0,a=0,c=0,l=N("similar.source-shape.target-files",()=>{let f=[...t.tokens],g=[];for(let h of Z(e,{includeIgnored:!1})){s+=1;let b=W(e,h);b&&(a+=1,z1(b,f,o)&&g.push(h))}return c=g.length,g},()=>({symbol:t.symbol,targetTokens:t.tokens.size,requiredSharedTokens:o,scannedFiles:s,readableFiles:a,candidateFiles:c})),u=0,d=N("similar.source-shape.target-definitions",()=>{let f=he(i.productionCallableDefinitions({files:l,sortByLocDesc:typeof n.scanLimit=="number"&&n.scanLimit>0}),n.scanLimit);return u=f.length,f},()=>({symbol:t.symbol,candidateFiles:c,scanLimit:n.scanLimit,definitionCount:u})),m=0;return N("similar.source-shape.target-fingerprints",()=>{let f=Bx(e,d);return r&&(m=f.length),f},()=>({symbol:t.symbol,definitionCount:u,fingerprintCount:m})).filter(f=>f.symbol!==t.symbol)}function G1(e,t){return Math.max(2,Math.ceil(e*t))}function z1(e,t,n){if(t.length<n)return!1;let r=e.toLowerCase(),i=0;for(let o of t)if(K1(r,o)&&(i+=1,i>=n))return!0;return!1}function K1(e,t){return t==="num"?/\b\d+\b/.test(e):e.includes(t)}function W1(e,t={}){let n=new H(e),{scanLimit:r}=t,i=he(n.productionCallableDefinitions({sortByLocDesc:typeof r=="number"&&r>0}),r);return Bx(e,i)}function Bx(e,t){let n=new Map;for(let i of t){let o=n.get(i.relativePath)??[];o.push(i),n.set(i.relativePath,o)}let r=new Map;for(let[i,o]of n){let s=W(e,i);if(!s)continue;let a=Rt(e,i,s),c=J1(e,i,a),l=!1,u=null;for(let d of o){let m=Y1(d),p=c.get(m),f=p?new Set(p.tokens):null;f||(u??=V(e,i),f=jx($x(u,d.startLine,d.endLine,d.leaf),d.leaf),c.set(m,{key:m,symbol:d.symbol,startLine:d.startLine,endLine:d.endLine,leaf:d.leaf,tokens:[...f].sort()}),l=!0),f.size>0&&r.set(d.symbol,{symbol:d.symbol,file:d.relativePath,tokens:f})}l&&Z1(e,i,a,c)}return t.map(i=>r.get(i.symbol)).filter(i=>!!i)}function V1(e,t,n,r,i){let o=V(e,t);return o.length===0?"":$x(o,n,r,i)}function $x(e,t,n,r){if(n>=t&&n-t<=12)return e.slice(t,n+1).join(`
320
- `);let i=[new RegExp(`\\bdef\\s+${Ce(r)}\\b`),new RegExp(`\\bfun\\s+${Ce(r)}\\b`),new RegExp(`\\bfn\\s+${Ce(r)}\\b`),new RegExp(`\\bfunction\\s+${Ce(r)}\\b`),new RegExp(`\\b${Ce(r)}\\s*\\(`)],o=e.findIndex(s=>i.some(a=>a.test(s)));if(o>=0){let s=o;for(let a=o+1;a<e.length&&a<=o+8;a++){let c=e[a]??"";if(a>o&&tH(c)||(s=a,c.trim()===""&&a>o+1))break}return e.slice(o,s+1).join(`
321
- `)}return e.slice(t,Math.min(e.length,t+8)).join(`
322
- `)}function Y1(e){return`${e.symbol}\0${e.startLine}\0${e.endLine}\0${e.leaf}`}function J1(e,t,n){return Dx.read(e,t,n)??new Map}function X1(e){try{let t=JSON.parse(e);if(!Array.isArray(t.entries))return null;let n=new Map;for(let r of t.entries){if(!r||typeof r.key!="string"||typeof r.symbol!="string"||typeof r.startLine!="number"||typeof r.endLine!="number"||typeof r.leaf!="string"||!Array.isArray(r.tokens)||!r.tokens.every(i=>typeof i=="string"))return null;n.set(r.key,r)}return n}catch{return null}}function Q1(e){let t={entries:[...e.values()].sort((n,r)=>n.key.localeCompare(r.key))};return JSON.stringify(t)}function Z1(e,t,n,r){Dx.write(e,t,n,new Map(r))}function jx(e,t){if(!e)return new Set;let n=new Set(["public","private","protected","final","static","class","def","fun","fn","function","return","string","bool","boolean","void","unit","self","this","new","const","let","var","end","pub"]),r=eH(t),o=e.replace(/["'`]/g," ").replace(/\b\d+\b/g," NUM ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[^A-Za-z0-9_]+/g," ").replace(/_/g," ").toLowerCase().split(/\s+/).map(s=>s.trim()).filter(s=>s.length>1).filter(s=>!n.has(s)).filter(s=>!r.has(s));return new Set(o)}function eH(e){return new Set(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9_]+|_/).map(t=>t.toLowerCase()).filter(t=>t.length>1))}function tH(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function rn(e,t){let n=new Map;return e.forEach((r,i)=>{let o=new Set;for(let s of t(r)){if(o.has(s))continue;o.add(s);let a=n.get(s);a?a.push(i):n.set(s,[i])}}),{candidatesFor:(r,i)=>{let o=new Set;for(let s of t(r)){let a=n.get(s);if(a)for(let c of a)c!==i&&o.add(c)}return[...o].sort((s,a)=>s-a)}}}function on(e){let t=Hx(e.profile?.name),n=()=>{let r=[];t=Hx(e.profile?.name,e);let i=(s,a)=>{let c=e.profiles[s],l=e.profiles[a];t.candidatePairs+=1,t.comparedPairs+=1;let u=e.compare(c,l);u&&r.push(u)};if(e.filePattern){let s=e.profiles.findIndex(a=>a.file.includes(e.filePattern));if(s>=0){let a=e.profiles[s];for(let c of nH(e,s)){let l=e.profiles[c];e.focusFiles&&!e.focusFiles.has(a.file)&&!e.focusFiles.has(l.file)||i(s,c)}}}else if(e.focusFiles?.size!==0){let s=typeof e.overrunFactor=="number"&&Number.isFinite(e.limit)?e.limit*e.overrunFactor:Number.POSITIVE_INFINITY;for(let a=0;a<e.profiles.length;a+=1){let c=e.profiles[a],l=e.focusFiles?.has(c.file)??!1;for(let u of rH(e,a))e.focusFiles&&!l&&!e.focusFiles.has(e.profiles[u].file)||i(a,u);if(r.length>s){t.overrunApplied=!0;break}}}r.sort(e.sort??((s,a)=>a.similarity-s.similarity)),t.matchedResults=r.length;let o=r.slice(0,e.limit);return t.emittedResults=o.length,e.onProfile?.({...t}),o};return e.profile?N(`pairwise-profile:${e.profile.name}`,n,()=>({...iH(e.profile?.metadata),...t})):n()}function nH(e,t){if(e.candidateIndex)return Ux(e,t,-1);let n=[];for(let r=0;r<e.profiles.length;r+=1)r!==t&&n.push(r);return n}function rH(e,t){if(e.candidateIndex)return Ux(e,t,t);let n=[];for(let r=t+1;r<e.profiles.length;r+=1)n.push(r);return n}function Ux(e,t,n){let r=e.profiles[t],i=new Set;for(let o of e.candidateIndex?.candidatesFor(r,t,e.profiles)??[])o<=n||o!==t&&(o<0||o>=e.profiles.length||i.add(o));return[...i].sort((o,s)=>o-s)}function Hx(e,t){return{pipeline:e,profileCount:t?.profiles.length??0,focusedProfileCount:t?.focusFiles?t.profiles.filter(n=>t.focusFiles.has(n.file)).length:0,candidatePairs:0,comparedPairs:0,matchedResults:0,emittedResults:0,candidateIndexApplied:t?.candidateIndex!==void 0,focusApplied:t?.focusFiles!==void 0,filePatternApplied:t?.filePattern!==void 0,overrunApplied:!1}}function iH(e){return typeof e=="function"?e():e??{}}function oH(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=sH(e,{scope:i,minDeps:s}),l=rn(a,u=>u.deps);return on({profiles:a,limit:r,filePattern:o,overrunFactor:5,candidateIndex:l,profile:{name:"similar-files"},compare:(u,d)=>cH(u,d,n,c)})}function sH(e,t){let{scope:n,minDeps:r}=t,i=Me(e,n),{universalDeps:o,distinctiveDeps:s}=aH(i),a=[];for(let[c,l]of i)l.size>=r&&a.push({file:c,deps:new Set([...l].filter(u=>!o.has(u)))});return{profiles:a,distinctiveDeps:s}}function aH(e){let t=new Set,n=new Set,r=e.size;if(r===0)return{universalDeps:t,distinctiveDeps:n};let i=new Map;for(let s of e.values())for(let a of s)i.set(a,(i.get(a)??0)+1);let o=Math.max(3,Math.ceil(r*.03));for(let[s,a]of i)a>=5&&a/r>.3?t.add(s):a<=o&&n.add(s);return{universalDeps:t,distinctiveDeps:n}}function cH(e,t,n,r){let i=new Set;for(let l of e.deps)t.deps.has(l)&&i.add(l);if(i.size<3||e.deps.size<4||t.deps.size<4)return null;let o=0;for(let l of i)r.has(l)&&o++;if(o<2)return null;let s=ur(e.deps,t.deps);if(s<n)return null;let a=[];for(let l of e.deps)t.deps.has(l)||a.push(l);let c=[];for(let l of t.deps)e.deps.has(l)||c.push(l);return{fileA:e.file,fileB:t.file,similarity:s,sharedDeps:[...i],uniqueToA:a,uniqueToB:c}}function dr(e){let t=[],n=[],r=[];for(let l of e.primitiveGroups)l.values.length!==0&&qx(l.bucket,n,r).push(`${l.reasonPrefix}: ${l.values.join(", ")}`);for(let l of e.nameGroups)lH(l.names,l.label,e.genericWords,e.stripPrefixes??[],t,qx(l.fallbackBucket,n,r));let i=t.length>0,o=n.length>0,s=r.length>0,a=i?o||s?"mixed":"domain-behavior":s?"shared-abstraction":"generic-workflow-scaffolding";return{actionTier:a==="domain-behavior"||a==="mixed"?"signal":"support",evidenceClass:a,reasons:[...t,...r,...n].slice(0,6),recommendation:e.recommendation(a)}}function Dc(e,t){if(e.size===0||t.size===0)return 0;let i=kt(e,t).size/Math.min(e.size,t.size)*Math.min(1,Math.min(e.size,t.size)/(.35*Math.max(e.size,t.size)));return Math.max(ur(e,t),i)}function mr(e,t){let n=Object.fromEntries(e.map(r=>[r.name,r.count]));for(let r of t)if(Object.entries(r.min).every(([o,s])=>(n[o]??0)>=s))return{pass:!0,reason:r.reason,counts:n};return{pass:!1,reason:"shared tokens did not meet calibrated overlap thresholds",counts:n}}function Mc(e,t,n){let r=t.map(c=>{let l=c.value(e),u=c.weightedValue?c.weightedValue(e,l):l;return{axis:c,value:l,weighted:u,qualifies:c.qualifies?c.qualifies(e,l):l>0}}),i=r.filter(c=>c.qualifies&&c.axis.reason).map(c=>c.axis.reason(e,c.value)),o=r.filter(c=>c.qualifies&&c.axis.dominantEligible!==!1).sort((c,l)=>l.weighted-c.weighted)[0],s=o&&o.weighted>0?o.axis.axis:n,a=[...new Set(r.filter(c=>c.qualifies).map(c=>c.axis.axis).concat(i.length>0?[]:[s]))];return{dominantPressure:s,pressureKinds:a,reasons:i}}function de(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function et(e){return[...e].sort()}function lH(e,t,n,r,i,o){let s=[],a=[];for(let c of e)uH(c,r).filter(u=>!n.has(u)).length>0?s.push(c):a.push(c);s.length&&i.push(`${t} has domain term(s): ${s.slice(0,6).join(", ")}`),a.length&&o.push(`${t} is generic workflow: ${a.slice(0,6).join(", ")}`)}function uH(e,t){let n=e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2");for(let r of t)n=n.replace(r,"");return n.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function qx(e,t,n){return e==="generic"?t:n}function ss(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=It(e).reactProfiles({scope:o,minJsxTokens:r,scanLimit:s}).filter(d=>d.kind==="component").map(d=>({file:d.file,component:d.name,tokens:d.jsxTokens,profile:d})),u=rn(l,d=>d.tokens);return on({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-component-duplicates"},compare:(d,m)=>dH(d,m,n),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.componentA.localeCompare(m.componentA)||d.fileB.localeCompare(m.fileB)||d.componentB.localeCompare(m.componentB)})}function dH(e,t,n){let r=kt(e.tokens,t.tokens);if(r.size<6||!mH(r))return null;let i=ur(e.tokens,t.tokens);if(i<n)return null;let o=de(r,"component:"),s=de(r,"native:"),a=de(r,"prop:"),c=de(r,"event:"),l=de(r,"binding:"),u=pH({sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:c,sharedBindings:l});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:i,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:et(r),sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:c,sharedBindings:l,evidenceClass:u.evidenceClass,actionTier:u.actionTier,evidenceClassReasons:u.reasons,recommendation:u.recommendation,uniqueToA:et(We(e.tokens,t.tokens)).slice(0,25),uniqueToB:et(We(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function mH(e){let t=0,n=0;for(let r of e)r.startsWith("component:")&&(t+=1),(r.startsWith("prop:")||r.startsWith("event:")||r.startsWith("native:")||r.startsWith("jsx:"))&&(n+=1);return mr([{name:"component",count:t},{name:"shape",count:n}],[{min:{component:1},reason:"shared custom component"},{min:{shape:4},reason:"shared JSX structure"}]).pass}function pH(e){return dr({genericWords:gH,primitiveGroups:[{values:e.sharedNativeTags,reasonPrefix:"shared native tags",bucket:"generic"},{values:e.sharedProps,reasonPrefix:"shared props",bucket:"generic"},{values:e.sharedEvents,reasonPrefix:"shared events",bucket:"generic"}],nameGroups:[{names:e.sharedComponents,label:"shared component",fallbackBucket:"generic"},{names:e.sharedBindings,label:"shared binding",fallbackBucket:"generic"}],recommendation:fH})}function fH(e){switch(e){case"domain-behavior":case"mixed":return"Review for a shared component or feature-specific UI primitive around the named domain structure.";case"shared-abstraction":return"Review the existing shared component usage first; extract only if duplicated structure remains outside it.";case"generic-workflow-scaffolding":return"Generic structural overlap \u2014 verify intent before consolidating."}}var gH=new Set(["actions","app","button","card","children","content","container","dialog","field","form","header","input","item","label","layout","list","modal","page","panel","row","section","shell","table","text","toolbar","ui","value","view","wrapper"]);function as(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=It(e).reactProfiles({scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(d=>({file:d.file,component:d.name,tokens:d.behaviorTokens,profile:d})),u=rn(l,d=>d.tokens);return on({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-hook-candidates"},compare:(d,m)=>hH(d,m,n,r),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.componentA.localeCompare(m.componentA)||d.fileB.localeCompare(m.fileB)||d.componentB.localeCompare(m.componentB)})}function hH(e,t,n,r){let i=kt(e.tokens,t.tokens);if(i.size<r||!SH(i))return null;let o=Dc(e.tokens,t.tokens);if(o<n)return null;let s=de(i,"hook:"),a=de(i,"react-hook:"),c=de(i,"effect:"),l=de(i,"state:"),u=de(i,"request:"),d=de(i,"handler:"),m=de(i,"handler-verb:"),p=yH({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:o,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:et(i),sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m,evidenceClass:p.evidenceClass,actionTier:p.actionTier,evidenceClassReasons:p.reasons,recommendation:p.recommendation,uniqueToA:et(We(e.tokens,t.tokens)).slice(0,25),uniqueToB:et(We(t.tokens,e.tokens)).slice(0,25),reason:vH({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m}),locA:e.profile.loc,locB:t.profile.loc}}function yH(e){return dr({genericWords:CH,stripPrefixes:xH,primitiveGroups:[{values:e.sharedReactHooks,reasonPrefix:"shared React primitives",bucket:"generic"},{values:e.sharedEffects,reasonPrefix:"shared lifecycle primitive",bucket:"generic"}],nameGroups:[{names:e.sharedHooks,label:"shared hook",fallbackBucket:"shared-abstraction"},{names:e.sharedRequests,label:"shared request",fallbackBucket:"generic"},{names:e.sharedState,label:"shared state",fallbackBucket:"generic"},{names:e.sharedHandlers,label:"shared handler",fallbackBucket:"generic"},{names:e.sharedHandlerVerbs,label:"shared action verb",fallbackBucket:"generic"}],recommendation:bH})}function bH(e){switch(e){case"domain-behavior":return"Review for a shared hook, controller, or feature module around the named domain behavior.";case"mixed":return"Separate generic React mechanics from domain-specific behavior before extracting a shared hook.";case"shared-abstraction":return"Review the existing shared hook usage first; extract only if duplicated behavior remains outside it.";case"generic-workflow-scaffolding":return"Treat as support evidence for a repeated workflow shape, not direct hook-extraction evidence."}}function SH(e){let t=0,n=0,r=0,i=0,o=0,s=0,a=0;for(let u of e)u.startsWith("hook:")?t+=1:u.startsWith("react-hook:")?n+=1:u.startsWith("effect:")?r+=1:u.startsWith("request:")?i+=1:u.startsWith("handler:")||u.startsWith("handler-verb:")?o+=1:u.startsWith("state:")?s+=1:u.startsWith("state-hook:")&&(a+=1);let c=s+a,l=t+n+r+i+o+c;return mr([{name:"requests",count:i},{name:"customHooks",count:t},{name:"namedStates",count:s},{name:"handlers",count:o},{name:"effects",count:r},{name:"reactHooks",count:n},{name:"namedBehavior",count:l}],[{min:{requests:1,namedBehavior:4},reason:"shared request workflow"},{min:{customHooks:1,requests:1,namedBehavior:5},reason:"shared custom hook and request workflow"},{min:{customHooks:1,namedStates:1,namedBehavior:5},reason:"shared custom hook and state"},{min:{customHooks:1,handlers:2,namedBehavior:5},reason:"shared custom hook and handlers"},{min:{namedStates:1,handlers:2,effects:1,namedBehavior:5},reason:"shared stateful effects"},{min:{namedStates:1,handlers:2,reactHooks:2,namedBehavior:5},reason:"shared stateful React primitives"}]).pass}function vH(e){let t=[];return e.sharedHooks.length&&t.push(`shared hooks: ${e.sharedHooks.join(", ")}`),e.sharedReactHooks.length&&t.push(`shared React hooks: ${e.sharedReactHooks.join(", ")}`),e.sharedEffects.length&&t.push(`shared effects: ${e.sharedEffects.join(", ")}`),e.sharedState.length&&t.push(`shared state: ${e.sharedState.join(", ")}`),e.sharedRequests.length&&t.push(`shared requests: ${e.sharedRequests.join(", ")}`),e.sharedHandlers.length&&t.push(`shared handlers: ${e.sharedHandlers.slice(0,6).join(", ")}`),e.sharedHandlerVerbs.length&&t.push(`shared action verbs: ${e.sharedHandlerVerbs.slice(0,6).join(", ")}`),t.join("; ")||"shared React behavior profile"}var CH=new Set(["add","apply","async","callback","cancel","change","clear","close","create","data","delete","draft","edit","effect","error","fetch","filter","form","handle","has","is","item","items","load","loader","loading","memo","name","open","reducer","refresh","ref","remove","request","reset","resource","row","rows","save","saving","search","select","selected","state","store","submit","toggle","update","use","value"]),xH=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function dm(e,t={}){let{minComponentLines:n=300,minFileLines:r=800,minJsxTokens:i=80,minBehaviorTokens:o=40,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return It(e).reactProfiles({scope:a,scanLimit:c}).filter(d=>d.kind==="component").filter(d=>!l||d.file.includes(l)||d.name.includes(l)).map(d=>RH(d,{minComponentLines:n,minFileLines:r,minJsxTokens:i,minBehaviorTokens:o})).filter(d=>d!==null).sort((d,m)=>m.componentLines-d.componentLines||m.fileLines-d.fileLines||d.file.localeCompare(m.file)).slice(0,s)}function RH(e,t){let n=Math.max(80,Math.floor(t.minComponentLines/2)),r=Mc(e,EH({minComponentLines:t.minComponentLines,minFileLines:t.minFileLines,minJsxTokens:t.minJsxTokens,minBehaviorTokens:t.minBehaviorTokens,substantialComponentLines:n}),"component"),{reasons:i}=r;if(i.length===0)return null;let o=r.dominantPressure,s=r.pressureKinds,a=IH(e),c=wH(o,s,a);return{file:e.file,component:e.name,componentLines:e.loc,fileLines:e.fileLines,jsxTokens:e.jsxTokens.size,behaviorTokens:e.behaviorTokens.size,dominantPressure:o,pressureKinds:s,contextKind:a,recommendationKind:c,recommendation:LH(c,a),reasons:i,loc:e.loc}}function EH(e){return[{axis:"component",value:t=>t.loc,qualifies:(t,n)=>n>=e.minComponentLines,reason:(t,n)=>`${n} component line(s)`},{axis:"file",value:t=>t.fileLines,qualifies:(t,n)=>n>=e.minFileLines&&t.loc>=e.substantialComponentLines,reason:(t,n)=>`${n} file line(s)`},{axis:"jsx-structure",value:t=>t.jsxTokens.size,weightedValue:(t,n)=>n*3,qualifies:(t,n)=>n>=e.minJsxTokens,reason:(t,n)=>`${n} JSX structure token(s)`},{axis:"hook-behavior",value:t=>t.behaviorTokens.size,weightedValue:(t,n)=>n*4,qualifies:(t,n)=>n>=e.minBehaviorTokens,reason:(t,n)=>`${n} behavior token(s)`}]}function IH(e){let t=e.file.split(/[\\/]+/).filter(Boolean),n=t.slice(0,-1).map(m=>m.toLowerCase()),r=(t.at(-1)??e.name).replace(/\.[^.]+$/,""),o=n.findIndex(m=>DH.has(m))>=0,s=n.some(m=>PH.has(m));if(Gx(r)||Gx(e.name))return"component";let c=MH.has(r.toLowerCase()),l=/(?:Page|Route|Screen)$/.test(e.name),u=o&&/View$/.test(e.name),d=!s&&r.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()===e.name.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()&&/(?:Page|Route|Screen|View)$/.test(r);return c||l||u||d?"route-page":"component"}function Gx(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&zx.has(t.at(-1))?!0:[...zx].some(n=>e.endsWith(TH(n)))}function wH(e,t,n){return e==="hook-behavior"?"behavior-extraction":n==="route-page"?"route-page-decomposition":t.includes("hook-behavior")?"behavior-extraction":t.includes("jsx-structure")?"jsx-decomposition":t.includes("file")?"file-decomposition":e==="jsx-structure"?"jsx-decomposition":e==="file"&&!t.includes("component")?"file-decomposition":"component-decomposition"}function LH(e,t){switch(e){case"behavior-extraction":return"Extract independent state, effects, requests, or handlers into hooks, controllers, or feature modules.";case"route-page-decomposition":return"Split route/page orchestration from reusable panels and feature controllers.";case"jsx-decomposition":return t==="route-page"?"Split page JSX into named layout sections before extracting behavior.":"Split repeated JSX sections into named presentational components.";case"file-decomposition":return"Review file-level decomposition; split colocated panels or helpers before changing behavior.";case"component-decomposition":return"Review component boundaries around props, state ownership, and independently changing UI sections."}}var PH=new Set(["component","components","panel","panels","partial","partials"]),zx=new Set(["banner","button","card","dialog","drawer","filter","form","grid","header","item","list","menu","modal","nav","panel","picker","rail","row","section","selector","shell","sidebar","table","toolbar"]),DH=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),MH=new Set(["page","route","screen"]);function TH(e){return e.charAt(0).toUpperCase()+e.slice(1)}function cs(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=kH(e,{scope:o,minTokens:r,scanLimit:s}),u=rn(l,d=>d.tokens);return on({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-component-duplicates"},compare:(d,m)=>FH(d,m,n),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function kH(e,t){return It(e).vueProfiles({scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:AH(n)}))}function AH(e){return e.totalLines}function FH(e,t,n){let r=kt(e.tokens,t.tokens);if(r.size<6||!NH(r))return null;let i=ur(e.tokens,t.tokens);if(i<n)return null;let o=de(r,"component:"),s=de(r,"prop:"),a=de(r,"event:"),c=de(r,"directive:"),l=de(r,"slot:"),u=de(r,"id:"),d=_H({sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:c,sharedSlots:l,sharedIdentifiers:u});return{fileA:e.file,fileB:t.file,similarity:i,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:et(r),sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:c,sharedSlots:l,sharedIdentifiers:u,evidenceClass:d.evidenceClass,actionTier:d.actionTier,evidenceClassReasons:d.reasons,recommendation:d.recommendation,uniqueToA:et(We(e.tokens,t.tokens)).slice(0,25),uniqueToB:et(We(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function NH(e){let t=0,n=0;for(let r of e)r.startsWith("component:")&&(t+=1),(r.startsWith("prop:")||r.startsWith("event:")||r.startsWith("directive:")||r.startsWith("slot:"))&&(n+=1);return mr([{name:"component",count:t},{name:"behavior",count:n}],[{min:{component:1},reason:"shared custom component"},{min:{behavior:3},reason:"shared Vue template structure"}]).pass}function _H(e){return dr({genericWords:BH,primitiveGroups:[{values:e.sharedProps,reasonPrefix:"shared props",bucket:"generic"},{values:e.sharedEvents,reasonPrefix:"shared events",bucket:"generic"},{values:e.sharedDirectives,reasonPrefix:"shared directives",bucket:"generic"},{values:e.sharedSlots,reasonPrefix:"shared slots",bucket:"generic"}],nameGroups:[{names:e.sharedComponents,label:"shared component",fallbackBucket:"generic"},{names:e.sharedIdentifiers,label:"shared identifier",fallbackBucket:"generic"}],recommendation:OH})}function OH(e){switch(e){case"domain-behavior":case"mixed":return"Review for a shared component or feature-specific Vue primitive around the named domain structure.";case"shared-abstraction":return"Review the existing shared component usage first; extract only if duplicated structure remains outside it.";case"generic-workflow-scaffolding":return"Generic structural overlap \u2014 verify intent before consolidating."}}var BH=new Set(["actions","app","button","card","content","container","dialog","field","form","header","input","item","label","layout","list","modal","page","panel","row","section","shell","table","text","toolbar","ui","value","view","wrapper"]);function ls(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=It(e).vueProfiles({scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(d=>({file:d.file,tokens:d.behaviorTokens,profile:d})),u=rn(l,d=>d.tokens);return on({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-composable-candidates"},compare:(d,m)=>$H(d,m,n,r),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function $H(e,t,n,r){let i=kt(e.tokens,t.tokens);if(i.size<r||!UH(i))return null;let o=Dc(e.tokens,t.tokens);if(o<n)return null;let s=de(i,"composable:"),a=de(i,"store:"),c=de(i,"reactivity:"),l=de(i,"lifecycle:"),u=de(i,"request:"),d=de(i,"function:"),m=de(i,"function-verb:"),p=de(i,"template-binding:"),f=de(i,"template-event:"),g=jH({sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p,sharedTemplateEvents:f});return{fileA:e.file,fileB:t.file,similarity:o,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:et(i),sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p,sharedTemplateEvents:f,evidenceClass:g.evidenceClass,actionTier:g.actionTier,evidenceClassReasons:g.reasons,recommendation:g.recommendation,uniqueToA:et(We(e.tokens,t.tokens)).slice(0,25),uniqueToB:et(We(t.tokens,e.tokens)).slice(0,25),reason:qH({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:l,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function jH(e){return dr({genericWords:GH,primitiveGroups:[{values:e.sharedReactivity,reasonPrefix:"shared reactivity primitive",bucket:"generic"},{values:e.sharedLifecycle,reasonPrefix:"shared lifecycle primitive",bucket:"generic"}],nameGroups:[{names:e.sharedComposables,label:"shared composable",fallbackBucket:"shared-abstraction"},{names:e.sharedStores,label:"shared store",fallbackBucket:"shared-abstraction"},{names:e.sharedRequests,label:"shared request",fallbackBucket:"generic"},{names:e.sharedFunctions,label:"shared function",fallbackBucket:"generic"},{names:e.sharedFunctionVerbs,label:"shared action verb",fallbackBucket:"generic"},{names:e.sharedBindings,label:"shared binding",fallbackBucket:"generic"},{names:e.sharedTemplateEvents,label:"shared template event",fallbackBucket:"generic"}],recommendation:HH})}function HH(e){switch(e){case"domain-behavior":return"Review for a shared composable, store, or feature module around the named domain behavior.";case"mixed":return"Separate generic Vue mechanics from domain-specific behavior before extracting a composable.";case"shared-abstraction":return"Review the existing composable/store usage first; extract only if duplicated behavior remains outside it.";case"generic-workflow-scaffolding":return"Treat as support evidence for a repeated workflow shape, not direct composable-extraction evidence."}}function UH(e){let t=0,n=0,r=0,i=0,o=0,s=0,a=0;for(let u of e)u.startsWith("composable:")?t+=1:u.startsWith("store:")?n+=1:u.startsWith("request:")?r+=1:u.startsWith("lifecycle:")?i+=1:u.startsWith("function:")?o+=1:u.startsWith("reactivity:")?s+=1:(u.startsWith("function-verb:")||u.startsWith("template-binding:")||u.startsWith("template-event:"))&&(a+=1);let c=t+n,l=c+r+i+o+a;return mr([{name:"requests",count:r},{name:"lifecycle",count:i},{name:"functions",count:o},{name:"reusableHooks",count:c},{name:"reactivity",count:s},{name:"namedBehavior",count:l}],[{min:{requests:1,namedBehavior:4},reason:"shared request workflow"},{min:{lifecycle:1,functions:2,namedBehavior:4},reason:"shared lifecycle workflow"},{min:{reusableHooks:2,requests:1,namedBehavior:5},reason:"shared reusable Vue hooks and requests"},{min:{reusableHooks:2,functions:2,namedBehavior:5},reason:"shared reusable Vue hooks and functions"},{min:{functions:2,reactivity:1,namedBehavior:4},reason:"shared reactive functions"}]).pass}function qH(e){let t=[];return e.sharedComposables.length&&t.push(`shared composables: ${e.sharedComposables.join(", ")}`),e.sharedStores.length&&t.push(`shared stores: ${e.sharedStores.join(", ")}`),e.sharedRequests.length&&t.push(`shared request helpers: ${e.sharedRequests.join(", ")}`),e.sharedLifecycle.length&&t.push(`shared lifecycle: ${e.sharedLifecycle.join(", ")}`),e.sharedFunctions.length&&t.push(`shared functions: ${e.sharedFunctions.slice(0,6).join(", ")}`),e.sharedFunctionVerbs.length&&t.push(`shared action verbs: ${e.sharedFunctionVerbs.slice(0,6).join(", ")}`),e.sharedBindings.length&&t.push(`shared template bindings: ${e.sharedBindings.slice(0,6).join(", ")}`),t.join("; ")||"shared Vue behavior profile"}var GH=new Set(["add","apply","cancel","change","clear","close","composable","create","data","delete","draft","edit","error","fetch","filter","form","item","items","load","loading","name","open","reactive","ref","refresh","remove","request","reset","resource","row","rows","save","saving","search","select","selected","store","submit","toggle","update","use","value","watch"]);function mm(e,t={}){let{minTotalLines:n=800,minTemplateLines:r=300,minScriptLines:i=300,minStyleLines:o=500,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return It(e).vueProfiles({scope:a,scanLimit:c}).filter(d=>!l||d.file.includes(l)).map(d=>zH(d,{minTotalLines:n,minTemplateLines:r,minScriptLines:i,minStyleLines:o})).filter(d=>d!==null).sort((d,m)=>m.totalLines-d.totalLines||d.file.localeCompare(m.file)).slice(0,s)}function zH(e,t){let n=Mc(e,KH(t),"total"),{reasons:r}=n;if(r.length===0)return null;let i=n.dominantPressure,o=n.pressureKinds.includes("total")?[...new Set([...n.pressureKinds,i])]:n.pressureKinds,s=WH(e.file),a=VH(i,s),c=e.totalLines+e.delegatedComposableLines;return{file:e.file,totalLines:c,sfcLines:e.sfcLines,templateLines:e.templateLines,scriptLines:e.scriptLines,styleLines:e.styleLines,externalScriptLines:e.externalScriptLines,externalScriptPaths:e.externalScriptPaths,customBlockLines:e.customBlockLines,delegatedComposableLines:e.delegatedComposableLines,delegatedComposablePaths:e.delegatedComposablePaths,dominantPressure:i,pressureKinds:o,contextKind:s,recommendationKind:a,recommendation:YH(a,s),reasons:r,loc:c}}function KH(e){return[{axis:"total",value:t=>t.totalLines+t.delegatedComposableLines,qualifies:(t,n)=>n>=e.minTotalLines,reason:(t,n)=>t.delegatedComposableLines>0?`${n} total line(s) (${t.totalLines} component + ${t.delegatedComposableLines} delegated composable line(s) across ${t.delegatedComposablePaths.length} file(s))`:`${n} total component line(s)`,dominantEligible:!1},{axis:"template",value:t=>t.templateLines,qualifies:(t,n)=>n>=e.minTemplateLines,reason:(t,n)=>`${n} template line(s)`},{axis:"script",value:t=>t.scriptLines-t.externalScriptLines,qualifies:t=>t.scriptLines>=e.minScriptLines,reason:t=>`${t.scriptLines} script line(s)`},{axis:"style",value:t=>t.styleLines,qualifies:(t,n)=>n>=e.minStyleLines,reason:(t,n)=>`${n} style line(s)`},{axis:"external-script",value:t=>t.externalScriptLines,qualifies:(t,n)=>n>=e.minScriptLines},{axis:"custom-block",value:t=>t.customBlockLines,qualifies:()=>!1}]}function WH(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(r=>JH.has(r))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function VH(e,t){return e==="style"?"style-decomposition":e==="template"?"template-decomposition":e==="external-script"?"external-script-boundary":e==="custom-block"?"custom-block-review":t==="route-page"?"route-page-decomposition":e==="script"?"script-behavior-extraction":"total-size-review"}function YH(e,t){switch(e){case"template-decomposition":return t==="route-page"?"Split route template sections into named panels before extracting script behavior.":"Split repeated template sections into named presentational components.";case"script-behavior-extraction":return"Extract independent script behavior into composables, controllers, or feature modules.";case"style-decomposition":return"Review UI/style decomposition; move repeated styling to component or style primitives, not composables.";case"external-script-boundary":return"Review the external script boundary and split controller/composable modules by workflow.";case"custom-block-review":return"Review custom block ownership before splitting template or script code.";case"route-page-decomposition":return"Split route/page orchestration from reusable panels and feature controllers.";case"total-size-review":return"Review the largest block first, then split by the dominant reason to change."}}var JH=new Set(["landing","page","pages","route","routes","view","views"]);function XH(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:o=3,maxChainLength:s=8}=t,a=Me(e,i),c=oU(a,o,s);if(c.length===0)return[];let l=QH(c);return l.length<2?[]:iU(tU(l,n,r),r)}function QH(e){let t=ZH(e),n=[];for(let r of e){let i=r.filter(o=>!t.has(o));i.length>=2&&n.push({original:r,filtered:i})}return n}function ZH(e){let{nodeFreq:t,tailFreq:n}=eU(e),r=e.length*.9,i=e.length*.8,o=new Set;for(let[a,c]of t)c>r&&o.add(a);for(let[a,c]of n)c>i&&o.add(a);let s=["index.ts","index.js","cli.ts","main.ts","health.ts","health.js"];for(let a of t.keys()){let c=a.split("/").pop()??"";s.includes(c)&&o.add(a)}return o}function eU(e){let t=new Map,n=new Map;for(let r of e){let i=new Set;for(let o of r)i.has(o)||(t.set(o,(t.get(o)??0)+1),i.add(o));for(let o=Math.max(0,r.length-2);o<r.length;o++)n.set(r[o],(n.get(r[o])??0)+1)}return{nodeFreq:t,tailFreq:n}}function tU(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let o=i+1;o<e.length;o++){let s=nU(e[i],e[o],t);s&&r.push(s)}if(r.length>n*10)break}return r.sort((i,o)=>Math.abs(o.similarity-i.similarity)>.01?o.similarity-i.similarity:i.divergencePoints.length-o.divergencePoints.length),r}function nU(e,t,n){if(!rU(e.filtered,t.filtered))return null;let{distance:r,ops:i}=sU(e.filtered,t.filtered),o=Math.max(e.filtered.length,t.filtered.length);if(o===0)return null;let s=1-r/o;if(s<n||r===0)return null;let a=i.filter(l=>l.type==="substitute").map(l=>({index:l.indexA,nodeA:e.filtered[l.indexA],nodeB:t.filtered[l.indexB]}));return a.length===0||i.filter(l=>l.type==="match").length<2?null:{chainA:e.original,chainB:t.original,similarity:s,editDistance:r,divergencePoints:a,commonPrefix:aU(e.original,t.original),commonSuffix:cU(e.original,t.original)}}function rU(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function iU(e,t){let n=[];for(let r of e)if(n.some(o=>Kx(r.chainA,o.chainA)&&Kx(r.chainB,o.chainB))||n.push(r),n.length>=t)break;return n}function oU(e,t,n){let r=[];for(let o of e.keys()){if(r.length>=500)break;Wx(e,o,[o],new Set([o]),t,n,r,500)}return r}function Wx(e,t,n,r,i,o,s,a){if(s.length>=a)return;if(n.length>=o){n.length>=i&&s.push([...n]);return}let c=e.get(t);if(!c||c.size===0){n.length>=i&&s.push([...n]);return}let l=!1;for(let u of c)if(!r.has(u)&&(r.add(u),n.push(u),Wx(e,u,n,r,i,o,s,a),n.pop(),r.delete(u),l=!0,s.length>=a))return;!l&&n.length>=i&&s.push([...n])}function sU(e,t){let n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let c=0;c<=n;c++)i[c][0]=c;for(let c=0;c<=r;c++)i[0][c]=c;for(let c=1;c<=n;c++)for(let l=1;l<=r;l++)e[c-1]===t[l-1]?i[c][l]=i[c-1][l-1]:i[c][l]=1+Math.min(i[c-1][l],i[c][l-1],i[c-1][l-1]);let o=[],s=n,a=r;for(;s>0||a>0;)s>0&&a>0&&e[s-1]===t[a-1]?(o.unshift({type:"match",indexA:s-1,indexB:a-1}),s--,a--):s>0&&a>0&&i[s][a]===i[s-1][a-1]+1?(o.unshift({type:"substitute",indexA:s-1,indexB:a-1}),s--,a--):a>0&&i[s][a]===i[s][a-1]+1?(o.unshift({type:"insert",indexA:s,indexB:a-1}),a--):(o.unshift({type:"delete",indexA:s-1,indexB:a}),s--);return{distance:i[n][r],ops:o}}function aU(e,t){let n=[];for(let r=0;r<Math.min(e.length,t.length)&&e[r]===t[r];r++)n.push(e[r]);return n}function cU(e,t){let n=[],r=e.length-1,i=t.length-1;for(;r>=0&&i>=0&&e[r]===t[i];)n.unshift(e[r]),r--,i--;return n}function Kx(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),r=e.join("\u2192");return n.includes(r)}function At(e){let t=lU(e.profile?.name),n=()=>{let r=e.candidates(),i=e.filterCandidate?r.filter(e.filterCandidate):r,o=e.orderCandidates?[...i].sort(e.orderCandidates):i,s=he(o,e.scanLimit);t={pipeline:e.profile?.name,loadedCandidates:r.length,filteredCandidates:i.length,scannedCandidates:s.length,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:s.length<i.length,resultLimitApplied:!1};let a=e.prepare?.(s)??void 0,c=[];for(let u of s){t.evaluatedCandidates+=1;let d=e.evaluate(u,a);d&&c.push(d)}t.matchedResults=c.length,e.orderResults&&c.sort(e.orderResults);let l=typeof e.limit=="number"?c.slice(0,e.limit):c;return t.emittedResults=l.length,t.resultLimitApplied=l.length<c.length,e.onProfile?.({...t}),l};return e.profile?N(`candidate-pipeline:${e.profile.name}`,n,()=>({...uU(e.profile?.metadata),...t})):n()}function lU(e){return{pipeline:e,loadedCandidates:0,filteredCandidates:0,scannedCandidates:0,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:!1,resultLimitApplied:!1}}function uU(e){return typeof e=="function"?e():e??{}}function us(e,t={}){let{scope:n,minLoc:r=10,minCallees:i=6,limit:o=20,scanLimit:s}=t,a=new H(e);return At({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:r,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:s,profile:{name:"extract-candidates"},prepare:c=>a.calleeMap(c,{semantic:t.semantic!==!1}),evaluate:(c,l)=>dU(c,l.get(c.symbolId)??[],i),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function dU(e,t,n){let r=new Set(t.map(l=>l.symbol));if(r.size<n)return null;let i=hU(r,t),o=yU(r,i);if(o.length<2)return null;let s=bU(o,i);if(s.length===0)return null;let a=T(e.symbol),c=mU(a,r.size,o.length,s);return{symbol:e.symbol,shortName:a,relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:ee(e),totalCallees:r.size,extractionKind:c.extractionKind,actionTier:"signal",evidenceReasons:c.evidenceReasons,recommendation:c.recommendation,clusters:s}}function mU(e,t,n,r){let i=Math.max(...r.map(c=>c.callees.length)),o=Math.max(...r.map(c=>c.isolation)),s=[`${t} distinct callees across ${n} co-occurrence cluster(s)`,`${r.length} extractable cluster(s) passed size and isolation thresholds`,`largest extractable cluster has ${i} callees at ${Math.round(o*100)}% isolation`],a=pU(e,t,n);return a!==null?{extractionKind:"workflow-orchestration",evidenceReasons:[...s,a],recommendation:"Review the isolated helper group as a possible private or feature-local helper, but keep the orchestration sequence together when it preserves the workflow."}:i>=6?{extractionKind:"broad-helper-cluster",evidenceReasons:[...s,"one isolated helper group is broad enough to deserve a named review"],recommendation:"Review whether the broad helper cluster has a stable concept name before extracting it; avoid creating a bag-of-helpers abstraction."}:{extractionKind:"cohesive-helper-cluster",evidenceReasons:s,recommendation:"Review the isolated callee group as a possible same-file or feature-local helper; extract only if the new name preserves the current behavior."}}function pU(e,t,n){if(t>=10)return`callee breadth suggests orchestration: ${t} callees`;if(n>=4)return`multiple disconnected callee groups suggest orchestration: ${n} groups`;let r=fU(e);return gU.has(r)?`caller verb suggests orchestration: ${r}`:null}function fU(e){return e.split(":").pop()?.replace(/\(\)$/,"").replace(/[^A-Za-z0-9_]/g,"").replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\s-]+/).filter(Boolean)[0]?.toLowerCase()??""}var gU=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function hU(e,t){let n=new Map;for(let i of e)n.set(i,new Set);let r=new Map;for(let i of t){let o=r.get(i.chunkId);o||(o=new Set,r.set(i.chunkId,o)),o.add(i.symbol)}for(let i of r.values()){let o=[...i];for(let s=0;s<o.length;s++)for(let a=s+1;a<o.length;a++)n.get(o[s]).add(o[a]),n.get(o[a]).add(o[s])}return n}function yU(e,t){let n=new Set,r=[];for(let i of e){if(n.has(i))continue;let o=new Set,s=[i];for(;s.length>0;){let a=s.pop();if(!n.has(a)){n.add(a),o.add(a);for(let c of t.get(a)??[])n.has(c)||s.push(c)}}r.push(o)}return r}function bU(e,t){return e.filter(n=>n.size>=3).map(n=>SU(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function SU(e,t,n){let r=new Set;for(let a of t)if(a!==e)for(let c of a)r.add(c);let i=0;for(let a of e)for(let c of n.get(a)??[])r.has(c)&&i++;let o=e.size*r.size,s=o>0?1-i/o:1;return{callees:[...e].map(T),isolation:s}}import{posix as Hi}from"path";import{spawnSync as vU}from"child_process";import{createHash as CU}from"crypto";import{existsSync as xU}from"fs";import{dirname as Vx,join as RU}from"path";import{fileURLToPath as EU}from"url";var Xx=Fn("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]}),Yx=dt({kind:"consumer-file-usage",invalidation:$e("consumer-file-usage"),serialize:NU,deserialize:_U});function Mn(e,t){return{forDefinitions(n,r){return IU(e,t,n,r)}}}function Tn(e){let t=new Map;for(let[n,r]of e)t.set(n,new Set(r.files.map(i=>i.file)));return t}function kc(e,t,n){return Zx(e,t,n).partition}function IU(e,t,n,r){let i=Qx(n.length),o=be()?mn(e):null,s=o?wU(n,r,o):void 0,a=s?{workIdentity:s,workOutcome:"computed"}:{};return N("consumer-evidence.product",()=>{let c=N("consumer-evidence.provenance",()=>LU(e,t,n,r),()=>({...a,definitions:n.length,semantic:r.semantic,sourceFallback:r.sourceFallback!==!1})),l=new Map;i={...i,...c.counters};let u=PU(n,c.sources);return N("consumer-evidence.classify",()=>{let d=DU(e,n,c.sources,u);for(let m of n){let p=d.get(m.symbolId)??TU();i.realFiles+=p.partition.realConsumers.length,i.reexportOnlyFiles+=p.partition.barrelConsumers,i.importOnlyFiles+=p.partition.importOnlyConsumers,l.set(m.symbolId,{definition:m,files:p.files,...p.partition})}},()=>({...a,...u,realFiles:i.realFiles,reexportOnlyFiles:i.reexportOnlyFiles,importOnlyFiles:i.importOnlyFiles})),l},()=>({...a,...i}))}function wU(e,t,n){let r=CU("sha256").update("consumer-evidence-v1\0").update(n).update("\0").update(t.semantic?"semantic\0":"indexed\0").update(t.sourceFallback===!1?"no-source-fallback":"source-fallback");for(let i of e.map(o=>o.symbol).sort())r.update("\0").update(i);return r.digest("hex").slice(0,24)}function Qx(e){return{definitions:e,indexedFiles:0,semanticFiles:0,fallbackFiles:0,totalFiles:0,realFiles:0,reexportOnlyFiles:0,importOnlyFiles:0}}function LU(e,t,n,r){let i=Qx(n.length),o=new Map;return pm(o,i,"indexed",t.crossFileCallerMap(n,{semantic:!1})),r.semantic&&pm(o,i,"semantic",Jn(e,n)),r.sourceFallback!==!1&&pm(o,i,"source-fallback",t.sourceFallbackCallerFiles(n)),i.totalFiles=[...o.values()].reduce((s,a)=>s+a.size,0),{sources:o,counters:i}}function PU(e,t){return{definitions:e.length,consumerFiles:[...t.values()].reduce((n,r)=>n+r.size,0),nativeAttempted:!1,nativeUsed:!1,nativeReason:"not-attempted"}}function pm(e,t,n,r){let i=0;for(let[o,s]of r){let a=e.get(o);a||(a=new Map,e.set(o,a));for(let c of s){i++;let l=a.get(c)??new Set;l.add(n),a.set(c,l)}}n==="indexed"?t.indexedFiles+=i:n==="semantic"?t.semanticFiles+=i:t.fallbackFiles+=i}function DU(e,t,n,r){let i=qU(e,t,n,r);return i||MU(e,t,n)}function MU(e,t,n){let r=new Map;for(let i of t){let o=n.get(i.symbolId)??new Map;r.set(i.symbolId,Zx(e,i,[...o.keys()],o))}return r}function Zx(e,t,n,r=new Map){let i=[],o=0,s=0,a=z(t.symbol),c=[];for(let l of n){let u;OU(e,l,t.relativePath,a)?(o++,u="reexport-only"):fm(e,l,a)?(s++,u="import-only"):(i.push(l),u="real"),c.push({file:l,sources:[...r.get(l)??[]],classification:u})}return{partition:{realConsumers:i,barrelConsumers:o,importOnlyConsumers:s},files:c}}function TU(){return{partition:{realConsumers:[],barrelConsumers:0,importOnlyConsumers:0},files:[]}}function fm(e,t,n){if(!n)return!1;let r=se(t);if(!r)return!1;let i=Xx.get(e,t,()=>eR(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function eR(e,t,n){let r=fn(e).forFile(t,{text:!0}).text;if(!r)return FU();let i=Rt(e,t,r),o=Yx.read(e,t,i);if(o)return o;let s=AU(fn(e).forFile(t,{ast:!0}).ast,n);return Yx.write(e,t,i,s),s}var kU=new Set(["identifier","type_identifier","property_identifier","field_identifier"]);function AU(e,t){let n=new Set,r=new Set;if(!e)return{importedLeaves:n,usedLeaves:r};let i=t==="rust"?new Set(["use_declaration"]):t==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),o=e.walk(),s=0,a=!1;for(;!a;){let c=o.nodeType,l=i.has(c);if(l&&(s+=1),kU.has(c)&&(s>0?n:r).add(o.nodeText),!o.gotoFirstChild())for(l&&(s-=1);!o.gotoNextSibling();){if(!o.gotoParent()){a=!0;break}i.has(o.nodeType)&&(s-=1)}}return{importedLeaves:n,usedLeaves:r}}function FU(){return{importedLeaves:new Set,usedLeaves:new Set}}function NU(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function _U(e){try{let t=JSON.parse(e);return!Array.isArray(t.importedLeaves)||!Array.isArray(t.usedLeaves)?null:{importedLeaves:new Set(t.importedLeaves.filter(n=>typeof n=="string")),usedLeaves:new Set(t.usedLeaves.filter(n=>typeof n=="string"))}}catch{return null}}function OU(e,t,n,r){if(!r)return!1;let i=fn(e).forFile(t,{lines:!0,reexports:!0}),o=i.lines??[];if(o.length===0)return!1;let s=i.reexports??[];return tR(o,s,r)}function tR(e,t,n){if(e.length===0||t.length===0)return!1;let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\b${r}\\b`),o=0;for(let s=0;s<e.length;s++){if(!i.test(e[s]??""))continue;if(o++,!t.find(c=>c.startLine<=s&&s<=c.endLine))return!1}return o>0}var BU="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY",$U="SCIP_QUERY_NATIVE_KERNELS_BIN",jU="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY_MIN_FILES",Jx=1e3,HU=5e3,UU=64*1024*1024,Tc;function qU(e,t,n,r){let i=process.env[BU]?.toLowerCase();if(i!=="1"&&i!=="true")return r.nativeReason=i==="0"||i==="false"?"disabled":"opt-in-required",null;if(r.consumerFiles<JU())return r.nativeReason="below-threshold",null;let o=XU();if(!o)return r.nativeReason="binary-missing",null;r.nativeAttempted=!0;let s=GU(e,t,n),a=vU(o,["consumer-classify"],{input:JSON.stringify(s),encoding:"utf8",timeout:HU,maxBuffer:UU});if(a.status!==0||a.error)return r.nativeReason=a.error?`spawn-error:${a.error.message}`:`exit-${a.status??"null"}`,null;try{let c=JSON.parse(a.stdout),l=KU(c,t);return l?(r.nativeUsed=!0,r.nativeReason="used",l):(r.nativeReason="invalid-response",null)}catch{return r.nativeReason="invalid-json",null}}function GU(e,t,n){let r=new Map,i=[];for(let a of t){let c=z(a.symbol),u=[...(n.get(a.symbolId)??new Map).entries()].map(([d,m])=>{let p=r.get(d)??new Set;return c&&p.add(c),r.set(d,p),{file:d,sources:[...m]}});i.push({symbol_id:a.symbolId,leaf:c,consumer_files:u})}let o={},s={};for(let[a,c]of r){let l=se(a);if(l){let d=Xx.get(e,a,()=>eR(e,a,l));o[a]={imported_leaves:[...d.importedLeaves],used_leaves:[...d.usedLeaves]}}let u=zU(e,a,c);u.length>0&&(s[a]=u)}return{definitions:i,file_usages:o,reexport_only_leaves:s}}function zU(e,t,n){if(n.size===0)return[];let r=fn(e).forFile(t,{lines:!0,reexports:!0}),i=r.lines??[],o=r.reexports??[];return i.length===0||o.length===0?[]:[...n].filter(s=>tR(i,o,s))}function KU(e,t){if(!Array.isArray(e.entries)||e.entries.length!==t.length)return null;let n=new Set(t.map(i=>i.symbolId)),r=new Map;for(let i of e.entries){let o=WU(i);if(!o||!n.has(o.symbol_id))return null;r.set(o.symbol_id,{partition:{realConsumers:o.real_consumers,barrelConsumers:o.barrel_consumers,importOnlyConsumers:o.import_only_consumers},files:o.files})}for(let i of n)if(!r.has(i))return null;return r}function WU(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.symbol_id!="number"||!Array.isArray(t.real_consumers)||typeof t.barrel_consumers!="number"||typeof t.import_only_consumers!="number"||!Array.isArray(t.files)||!t.real_consumers.every(r=>typeof r=="string"))return null;let n=[];for(let r of t.files){if(!r||typeof r!="object")return null;let i=r;if(typeof i.file!="string"||!Array.isArray(i.sources)||!i.sources.every(VU)||!YU(i.classification))return null;n.push({file:i.file,sources:i.sources,classification:i.classification})}return{symbol_id:t.symbol_id,real_consumers:t.real_consumers,barrel_consumers:t.barrel_consumers,import_only_consumers:t.import_only_consumers,files:n}}function VU(e){return e==="indexed"||e==="semantic"||e==="source-fallback"}function YU(e){return e==="real"||e==="reexport-only"||e==="import-only"}function JU(){let e=process.env[jU];if(!e)return Jx;let t=Number(e);return Number.isFinite(t)&&t>=0?t:Jx}function XU(){if(Tc!==void 0)return Tc;let e=process.env[$U],t=process.platform==="win32"?"scip-query-kernels.exe":"scip-query-kernels";return Tc=[...e?[e]:[],...QU().map(r=>RU(r,"target","release",t))].find(r=>xU(r))??null,Tc}function QU(){let e=new Set,t=Vx(EU(import.meta.url));for(let n=0;n<5;n++)e.add(t),t=Vx(t);return[...e]}var ZU=20,eq=1,tq=new Map([["app","app"],["apps","app"],["component","component"],["components","component"],["composable","composable"],["composables","composable"],["contract","contract"],["contracts","contract"],["domain","domain"],["domains","domain"],["feature","feature"],["features","feature"],["hook","hook"],["hooks","hook"],["lib","library"],["module","module"],["modules","module"],["package","package"],["packages","package"],["page","page"],["pages","page"],["route","route"],["routes","route"],["screen","screen"],["screens","screen"],["service","service"],["services","service"],["shared","shared"],["src","source-root"],["store","state"],["stores","state"],["test","test"],["tests","test"],["util","utility"],["utils","utility"],["view","view"],["views","view"]]),nq=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),rq=new Set(["access","api","auth","config","db","effect","errors","hooks","lib","middleware","permissions","routes","schemas","servicetasks","services","startup","store","stores","test-utils","repository","repositories","tests","types","ui","utils","workflow","workflows"]);function iq(e,t={}){let n=ym(t.limit,ZU),r=ym(t.minConsumers,eq),i=new H(e),o=i.fileDependencyGraph(t.scope),s=Eq(Z(e,{includeIgnored:!1})),a=Lq(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?oq(e,i,t.target):sq(e,t.scope,t.scanLimit)).map(u=>aq(e,i,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=r||t.target).sort(Rq).slice(0,n)}function oq(e,t,n){let r=uq(e,n);if(r)return[sR(r)];let i=ne(e,n);if(!i)return[];let o=t.definitionsForFile(i.relativePath).find(s=>s.symbolId===i.symbolId);return o?[dq(o)]:[{unit:{kind:"symbol",file:i.relativePath,shortName:T(i.symbol),symbol:i.symbol,startLine:i.startLine,endLine:i.endLine}}]}function sq(e,t,n){let r=Z(e,{scope:t,includeIgnored:!1}),i=ym(n,r.length);return r.slice(0,i).map(o=>sR(o))}function aq(e,t,n,r,i,o,s){let a=r.definition?cq(e,t,r.definition,i.semantic):lq(n,r.unit.file),c=r.definition?a.length>0?"exact":"none":a.length>0?"file-level":"none",l=r.unit.file,u=$t(Hi.dirname(l)),d=pq(a),m=mq(u),p=Sm([...nR(u),...d?nR(d):[]]),f=fq(r.unit,u,d,a),g=gq(f,r.unit,u,d,a,o,s),h=vq(r.unit,c,d,a,u,g.whyNoSuggestedHome),b=Cq(r.unit,u,d,a,g.suggestedHome,g.whyNoSuggestedHome);return{actionTier:"signal",sourceUnit:r.unit,candidatePath:l,currentDirectory:u,directoryAncestry:m,consumerFiles:a,consumerCoverage:c,nearestCommonOwner:d,boundaryMarkers:p,recommendedTier:f,suggestedHome:g.suggestedHome,destinationConfidence:g.confidence,whyNoSuggestedHome:g.whyNoSuggestedHome,counterevidence:h,reasons:b,recommendation:xq(f,g.suggestedHome,c)}}function cq(e,t,n,r){let i=Tn(Mn(e,t).forDefinitions([n],{semantic:r!==!1,sourceFallback:!0}));return dR(i.get(n.symbolId)??[])}function lq(e,t){let n=[];for(let[r,i]of e.entries())r!==t&&i.has(t)&&n.push(r);return dR(n)}function uq(e,t){let n=ws(t),r=Z(e,{includeIgnored:!1}),i=r.find(s=>s===n);if(i)return i;let o=r.find(s=>s.endsWith(`/${n}`));return o||(r.find(s=>s.includes(n))??null)}function dq(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:T(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function sR(e){return{unit:{kind:"file",file:e,shortName:Hi.basename(e)}}}function mq(e){if(e===".")return[{path:".",depth:0,markers:[]}];let t=[],n=e.split("/").filter(Boolean);for(let r=0;r<n.length;r+=1){let i=n.slice(0,r+1).join("/");t.push({path:i,depth:r,markers:bm(i)})}return t}function nR(e){return e==="."?[]:aR(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function bm(e){return Sm(aR(e).map(({marker:t})=>t))}function aR(e){let t=e.split("/").filter(Boolean),n=[];for(let r=0;r<t.length;r+=1){let i=tq.get(t[r]);i&&n.push({marker:i,prefix:t.slice(0,r+1).join("/")})}return n}function pq(e){if(e.length===0)return null;let t=e.map(r=>$t(Hi.dirname(r))),n=t[0].split("/").filter(Boolean);for(let r of t.slice(1)){let i=r.split("/").filter(Boolean),o=[],s=Math.min(n.length,i.length);for(let a=0;a<s&&n[a]===i[a];a+=1)o.push(n[a]);n=o}return n.length===0?".":n.join("/")}function fq(e,t,n,r){return n?e.kind==="symbol"&&r.length===1?r[0]===e.file?"same-file":"sibling-folder":n==="."||n==="src"?"repository-level-review":iR(n,"package")?"package-level-shared":iR(n,"app")?"app-level-shared":oR(n,["feature","domain","module"])||oR(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function gq(e,t,n,r,i,o,s){let a=hq(e,r);if(a)return pr(a);let c=Iq(t.file),l=yq(e,n,c,i,s);if(l)return l;let u=r;if($t(n)===$t(u))return pr(`${n} is already the nearest common owner for its consumers.`);let d=bq(u,n,c,s);return d||Sq(u,n,c,o,s)}function hq(e,t){return t?e==="no-exact-consumers"||e==="repository-level-review"?"The inferred owner is too broad or unsupported for an exact destination.":null:"No consumer owner could be inferred from the current index."}function yq(e,t,n,r,i){if(e==="same-file"){let o=r[0]??null;return o?gm(o):pr("No same-file consumer path was available.")}if(e==="sibling-folder"&&r.length===1){let o=$t(Hi.dirname(r[0])),s=uR(t,n,o,i);return s?pr(s):gm(o)}return null}function bq(e,t,n,r){return Dq(e)?cR(e,t,n,r,`Nearest shared owner ${e} is outside source root ${n}.`):null}function Sq(e,t,n,r,i){if(e===".")return pr("The nearest common owner is the repository root.");let o=`${e}/shared`,s=cR(o,t,n,i,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||r.has(o)?s:pr(`${o} does not exist in the indexed project.`)}function cR(e,t,n,r,i){if(!lR(e,n))return pr(i);let o=uR(t,n,e,r);return o?pr(o):gm(e)}function gm(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function pr(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function vq(e,t,n,r,i,o){let s=["Report-only signal; review ownership before moving files."];return t==="none"&&s.push("No consumers were found in the current index."),t==="file-level"&&s.push("File-level import evidence can hide which exported unit is actually used."),(n==="."||n==="src")&&s.push("Nearest common owner is broad, so this is not enough evidence for automatic placement."),r.length===1&&s.push("Only one consumer was found; inlining or same-folder placement may be better than shared extraction."),e.kind==="file"&&s.push("File targets describe module locality, not symbol-level usage."),n&&i.startsWith(`${n}/`)&&s.push("Candidate already lives under the nearest common owner."),o&&s.push(`No exact suggested home: ${o}`),s}function Cq(e,t,n,r,i,o){let s=[];return s.push(`${e.shortName} currently lives in ${t}.`),n?s.push(`${r.length} consumer file(s) share ${n} as their nearest common owner.`):s.push("No consumer owner could be inferred from the current index."),i?s.push(`Suggested home is ${i}.`):o&&s.push(`No exact suggested home: ${o}`),s}function xq(e,t,n){return e==="no-exact-consumers"?"Review references before moving; no consumers were found.":e==="repository-level-review"?"Keep this as a broad locality signal; the inferred owner is too general for automatic relocation.":t?`Review whether ${n==="exact"?"symbol usage":"module import"} supports moving or extracting toward ${t}.`:"Review ownership manually before changing structure."}function Rq(e,t){return rR(t)-rR(e)||e.candidatePath.localeCompare(t.candidatePath)}function rR(e){let t=e.consumerFiles.length*10;return e.consumerCoverage==="exact"&&(t+=5),e.suggestedHome&&(t+=3),e.recommendedTier==="repository-level-review"&&(t*=.1),e.recommendedTier==="no-exact-consumers"&&(t*=.05),t}function Eq(e){let t=new Set(["."]);for(let n of e){let r=$t(Hi.dirname(n));for(;!t.has(r)&&(t.add(r),r!==".");)r=$t(Hi.dirname(r))}return t}function Iq(e){let t=hm(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function lR(e,t){let n=$t(e),r=$t(t);return r==="."||n===r||n.startsWith(`${r}/`)}function wq(e,t,n){let r=hm(e),i=hm(t);return(lR(e,t)?r.slice(i.length):r).some(s=>n.has(s.toLowerCase()))}function uR(e,t,n,r){return $t(e)===$t(n)||!wq(e,t,r)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function Lq(...e){let t=new Set(rq);for(let n of e)for(let r of n??[]){let i=Pq(r);i&&t.add(i)}return t}function Pq(e){let t=e.trim().toLowerCase();return t===""?null:t}function iR(e,t){return bm(e).includes(t)}function oR(e,t){let n=bm(e);return t.some(r=>n.includes(r))}function Dq(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?nq.has(n):!1}function $t(e){let t=ws(e);return t===""?".":t}function hm(e){let t=ws(e);return t==="."?[]:t.split("/").filter(Boolean)}function ym(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function dR(e){return Sm([...e]).sort((t,n)=>t.localeCompare(n))}function Sm(e){return[...new Set(e)]}function vm(e,t,n={}){return mR(e,t,n).rows}function Mq(e,t,n={}){return mR(e,t,n)}function mR(e,t,n){let{maxDepth:r=5,scope:i}=n,o=r===Number.MAX_SAFE_INTEGER,s=o?null:500,a=ne(e,t);if(!a)return{rows:[],coverage:{status:"incomplete",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:r,reachedDepth:0,perSymbolEvidenceLimit:s,remainingFrontierSymbols:0,reasons:["The requested symbol could not be resolved."]}};let c=[],l=new Set([a.symbolId]),u=new Set,d=[a],m=0,p=!1;for(let h=1;h<=r&&d.length!==0;h++){m=h;let b=[],S=yn(e,d,{...o?{}:{limit:s+1},semanticEvidence:re});for(let y of d){let x=S.get(y.symbolId)??[];s!==null&&x.length>s&&(p=!0);let v=s===null?x:x.slice(0,s);for(let C of Tq(e,y,i,v)){let R=`${C.file}|${C.shortName}`;if(C.symbolId!==null){if(l.has(C.symbolId))continue;l.add(C.symbolId)}else if(u.has(R))continue;u.add(R),c.push({symbol:C.symbol,shortName:C.shortName,file:C.file,depth:h}),C.symbolId!==null&&C.symbolMatch&&b.push(C.symbolMatch)}}d=b}c.sort((h,b)=>h.depth-b.depth||h.file.localeCompare(b.file));let f=d.length>0,g=[];return f&&g.push(`${d.length} symbol(s) remain eligible beyond depth ${r}.`),p&&g.push(`At least one symbol had more than ${s} incoming evidence row(s).`),g.length===0&&g.push("The discovered reverse evidence frontier was exhausted."),{rows:c,coverage:{status:f||p?"bounded":"accounted",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:r,reachedDepth:m,perSymbolEvidenceLimit:s,remainingFrontierSymbols:d.length,reasons:g}}}function Tq(e,t,n,r){let i=r.filter(u=>!e.isIgnored(u.file)).filter(u=>!n||u.file.includes(n)),o=new Set(i.map(u=>u.file)),s=[];for(let u of kq(e,t,n)){if(o.has(u))continue;let d=U(e,u),m=d.length>0?Ne(d,d[0].startLine):null;s.push({symbol:m?.symbol??u,file:u})}let a=[...i,...s],c=[],l=new Set;for(let u of a){let d=Sr(e,u.symbol);if(!d){let p=`${u.file}|${u.symbol}`;if(l.has(p))continue;l.add(p),c.push({symbolId:null,symbol:u.symbol,shortName:T(u.symbol),file:u.file,symbolMatch:null});continue}if(d.symbolId===t.symbolId||e.isIgnored(d.relativePath)||!Aq(d))continue;let m=`${d.symbolId}|${d.relativePath}`;l.has(m)||(l.add(m),c.push({symbolId:d.symbolId,symbol:d.symbol,shortName:T(d.symbol),file:d.relativePath,symbolMatch:d}))}return c}function kq(e,t,n){let r=n?"AND consumer_d.relative_path LIKE ?":"",i=[t.symbolId,t.documentId];return n&&i.push(`%${n}%`),new Set(e.all(`SELECT DISTINCT consumer_d.relative_path
323
- FROM mentions m
324
- JOIN chunks c ON m.chunk_id = c.id
325
- JOIN documents consumer_d ON consumer_d.id = c.document_id
326
- WHERE m.symbol_id = ?
327
- AND m.role != 1
328
- AND c.document_id != ?
329
- ${e.pathExclusionsFor("consumer_d")}
330
- ${r}`,...i).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function Aq(e){if(e.symbol.startsWith("scip-clojure ")||se(e.relativePath)==="clojure")return!0;let t=wt(e.symbol);return t==="method"||t==="type"||e.symbol.endsWith("().")}function fR(e,t){let n=it(t),r=[],i="complete",o=q(n);o==="entry"&&kn(r,"operational-root","structural entrypoint path"),o==="worker"&&kn(r,"operational-root","worker launch convention"),nd(n)&&kn(r,"operational-root","framework-discovered entrypoint"),Fq(e,n)&&kn(r,"operational-root","configured entry root");let s=!1;try{s=xn(e,n),s&&kn(r,"published-api","package manifest export");for(let a of fb(e,n))kn(r,"operational-root",a)}catch(a){i="partial",kn(r,"metadata-unavailable",`package metadata unavailable: ${pR(a)}`)}try{let a=Ye(e.config.projectRoot,n,{maxBytes:8388608,inputKind:"change-surface source"});Nq(a)&&kn(r,"operational-root","module contains a direct-execution process guard")}catch(a){i="partial",kn(r,"metadata-unavailable",Je(a)?"indexed source file is unavailable on disk":`source metadata unavailable: ${pR(a)}`)}return{operationalRoot:r.some(a=>a.kind==="operational-root"),publishedApi:s,coverage:i,reasons:r}}function Fq(e,t){let n=e.config.entryRoots;return n?n.files?.some(r=>it(r)===t)?!0:n.pathPrefixes?.some(r=>t.startsWith(it(r)))??!1:!1}function Nq(e){return e.includes("import.meta.url")&&/process\.argv\s*\[\s*1\s*\]/.test(e)||/require\.main\s*===\s*module/.test(e)||/__name__\s*==\s*['"]__main__['"]/.test(e)}function kn(e,t,n){e.some(r=>r.kind===t&&r.detail===n)||e.push({kind:t,detail:n})}function pR(e){return e instanceof Error?e.message:String(e)}function Cm(e,t,n={}){let r=mt(e,t);if(!r)return null;let i=_q(e,r);if(!i||e.isIgnored(i.relative_path))return null;let o=[],s=0,a=Oq(e,i.relative_path),c=fR(e,i.relative_path),l=n.semantic===!1?new Map:Jn(e,a);for(let u of a){let d=Bq(e,i,u,l.get(u.symbolId)??new Set);s+=d;let m=$q(d),p=[...c.reasons,...d>0?[{kind:"external-consumers",detail:`${d} external consumer${d===1?"":"s"}`}]:[]];o.push({symbol:u.symbol,shortName:T(u.symbol),startLine:u.startLine,endLine:u.endLine,externalConsumers:d,externalConsumerRiskLevel:m,riskLevel:jq(m,c),riskReasons:p})}return{file:i.relative_path,symbols:o,totalExternalConsumers:s,fileRisk:c}}function _q(e,t){return e.get(`SELECT id, relative_path FROM documents
331
- WHERE relative_path = ?
332
- ${e.pathExclusionsFor("documents")}
333
- LIMIT 1`,t)??null}function Oq(e,t){return new H(e).definitionsForFile(t).sort((n,r)=>n.startLine-r.startLine||n.endLine-r.endLine)}function Bq(e,t,n,r){let i=e.all(`SELECT DISTINCT consumer_d.relative_path
334
- FROM mentions m
335
- JOIN chunks c ON m.chunk_id = c.id
336
- JOIN documents consumer_d ON consumer_d.id = c.document_id
337
- WHERE m.symbol_id = ?
338
- AND m.role != 1
339
- AND c.document_id != ?`,n.symbolId,t.id);return new Set([...i.map(o=>o.relative_path),...[...r].filter(o=>o!==t.relative_path)]).size}function $q(e){return e>10?"high":e>0?"medium":"low"}function jq(e,t){return e==="high"?"high":e==="medium"||t.operationalRoot||t.publishedApi||t.coverage==="partial"?"medium":"low"}function Hq(e,t={}){let{scope:n,minLoc:r=1,maxDepth:i=5,scanLimit:o}=t,s=new H(e),a=Uq(e,n,r,o),c=new xm;for(let g of a)c.add(g);let l=[],u=[];a.length>0&&l.push(gR(e,0,a,c));let d=a.map(g=>g.definition).filter(g=>g!==null),m=new Set(a.map(g=>g.symbol));for(let g=1;g<=i&&d.length>0;g++){let h=s.calleeMap(d,{semantic:!1}),b=new Set;for(let y of d)for(let x of h.get(y.symbolId)??[])m.has(x.symbol)||b.add(x.symbol);let S=[];for(let y of b){m.add(y);let x=hR(e,y);if(!x||e.isIgnored(x.relativePath)||Ue(e,x.relativePath)||Te(e,x.symbol,x.relativePath)||s.fileKind(x.relativePath)==="test"||s.hasSuppressionComment(x))continue;let v=Gq(e,x,c);v.removable?S.push(qq(x,"cascade")):v.blockingFiles.length>0&&u.push({shortName:T(x.symbol),file:x.relativePath,blockingFiles:v.blockingFiles.slice(0,3)})}if(S.length===0)break;for(let y of S)c.add(y);l.push(gR(e,g,S,c)),d=S.map(y=>y.definition).filter(y=>y!==null)}let p=l.reduce((g,h)=>g+h.loc,0),f=l.reduce((g,h)=>g+h.entries.length,0);return{batches:l,totalSymbols:f,totalLoc:p,blocked:u}}function Uq(e,t,n,r){let i=zr(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:r,semantic:!1}),o=[];for(let s of i.symbols)s.kind==="dead-code"&&(Ue(e,s.relativePath)||Te(e,s.symbol,s.relativePath)||o.push({symbol:s.symbol,shortName:s.shortName,file:s.relativePath,startLine:s.startLine,endLine:s.endLine,loc:s.loc,evidence:"graph-fact",definition:hR(e,s.symbol)}));return o}function qq(e,t){return{symbol:e.symbol,shortName:T(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function hR(e,t){let n=e.get(`SELECT d.relative_path
340
- FROM global_symbols gs
341
- JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
342
- JOIN documents d ON d.id = der.document_id
343
- WHERE gs.symbol = ?
344
- LIMIT 1`,t);return n?U(e,n.relative_path).find(r=>r.symbol===t)??null:null}function Gq(e,t,n){let r=eo(e,t);if(r.length===0)return{removable:!1,blockingFiles:[]};let i=new Set;for(let o of r)o.file===t.relativePath&&o.line>=t.startLine&&o.line<=t.endLine||n.contains(o.file,o.line)||i.add(o.file);return{removable:i.size===0,blockingFiles:[...i]}}function gR(e,t,n,r){let i=[...n].sort((a,c)=>a.file.localeCompare(c.file)||a.startLine-c.startLine),o=new Set(i.map(a=>a.file)),s=[];for(let a of o){let c=U(e,a);c.length>0&&c.every(l=>r.contains(a,l.startLine))&&s.push(a)}return{depth:t,entries:i.map(({definition:a,...c})=>c),loc:i.reduce((a,c)=>a+c.loc,0),filesEmptied:s.sort()}}var xm=class{ranges=new Map;add(t){let n=this.ranges.get(t.file)??[];n.push({start:t.startLine,end:t.endLine}),this.ranges.set(t.file,n)}contains(t,n){let r=this.ranges.get(t);return r?r.some(i=>n>=i.start&&n<=i.end):!1}};import{execFileSync as Ui}from"child_process";import{existsSync as zq}from"fs";import{basename as yR}from"path";function Ac(e){let t=new Map;for(let n of e){let r=t.get(n.file);r||(r=[],t.set(n.file,r)),r.push(n)}return t}var Lm="Unable to compute git diff.",Kq={semanticConsumers:Jn,sourceFallbackConsumers:ko},Pm={resolveCommit:ml,readBatch({projectRoot:e,resolvedBase:t,relativePaths:n}){let r=n.map(i=>`${t}:./${i}
345
- `).join("");return Ui("git",["cat-file","--batch"],{cwd:e,input:r,maxBuffer:256*1024*1024,timeout:1e4,stdio:["pipe","pipe","ignore"]})}};function Fc(e,t={}){let n=t.plan??qi(e,t);return n.note?Wq(n.note,n.changedFileLines):n.changedFiles.length===0?Vq(n.changedFileLines):Nc(n.changedFiles,[CR(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function qi(e,t={}){let{base:n="HEAD"}=t;try{let r=ml(e.config.projectRoot,n),i=Yq(e.config.projectRoot,r),o=i.changedFileLines,s=tG(e,o),a=nG(e,i.changedRanges);return{changedFileLines:o,changedFiles:s,changedRanges:a,renamedFiles:Qq(e.config.projectRoot,r,s,i),note:o.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:Lm}}}function CR(e,t,n,r=[],i={}){let o=i.evidenceRuntime??Kq,s=new H(e),a=new Set(n),c=Ac(r),l=[],u=new Map,d=t.flatMap(E=>s.definitionsForFile(E)).filter(bG),m=d.filter(E=>iG(E,c)),p=sG(e,d,m,c),f=lG([...m,...p.definitions]).sort((E,w)=>E.relativePath.localeCompare(w.relativePath)||E.startLine-w.startLine),g=f.map(E=>E.symbolId),h=gG(e,g),b=hG(e,g,n),S=f.filter(E=>(h.get(E.symbolId)??0)===0),y=vR("semantic-consumers",S.length,()=>o.semanticConsumers(e,S)),x=y.values,v=S.filter(E=>(x.get(E.symbolId)?.size??0)===0),C=vR("source-fallback-consumers",v.length,()=>o.sourceFallbackConsumers(e,v)),R=C.values;for(let E of f)mG(e,E,a,l,u,x.get(E.symbolId)??new Set,R.get(E.symbolId)??new Set,h.get(E.symbolId)??0,b.get(E.symbolId)??new Set);return{changedSymbols:l,consumerEntries:[...u.entries()].map(([E,w])=>({file:E,symbols:[...w].sort()})),attributionNotes:p.notes,evidenceTiers:[y.status,C.status]}}function Nc(e,t){let n=new Map,r=t.flatMap(a=>a.changedSymbols),i=t.flatMap(a=>a.attributionNotes??[]),o=pG(t);for(let a of t)for(let c of a.consumerEntries){let l=n.get(c.file);l||(l=new Set,n.set(c.file,l));for(let u of c.symbols)l.add(u)}let s=yG(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:s,attributionNotes:i,evidenceTiers:o,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:s.length}}}function Wq(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:PR(),summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function Vq(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:PR(),summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function Yq(e,t){let n=Ui("git",["diff","--name-status","--find-renames",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864}),r=Ui("git",["diff","--name-status","--find-renames","--cached",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),i=Ui("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),o=Ui("git",["diff","--unified=0",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),s=Ui("git",["diff","--unified=0","--cached",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),a=Zq([n,r]);return{changedFileLines:[...new Set([...a.changedFiles,...ER(i)])],changedRanges:wR([...SR(o),...SR(s)]),renamedFiles:a.renamedFiles,deletedFiles:a.deletedFiles}}function Jq(e,t,n){let r=typeof e=="string"?{projectRoot:e,base:t,relativePath:n}:e;if(typeof r.projectRoot!="string"||typeof r.base!="string"||typeof r.relativePath!="string")throw new TypeError("fileContentAtBase requires projectRoot, base, and relativePath.");let i={projectRoot:r.projectRoot,base:r.base,relativePath:r.relativePath},{relativePath:o}=i,s=Dm(i);if(s.state==="unavailable")throw new Error(`Base content unavailable for ${o}: ${s.reason}`);return s.state==="present"?s.content:null}function Dm(e,t=Pm){return RR(e.relativePath),Mm({projectRoot:e.projectRoot,base:e.base,relativePaths:[e.relativePath]},t).get(e.relativePath)??{state:"unavailable",reason:`Base-content lookup omitted ${e.relativePath}.`}}function Mm(e,t=Pm){for(let s of e.relativePaths)RR(s);let n=[...new Set(e.relativePaths)];if(n.length===0)return new Map;let r;try{r=t.resolveCommit(e.projectRoot,e.base)}catch(s){return Rm(n,Em(s))}let i;try{i=t.readBatch({projectRoot:e.projectRoot,resolvedBase:r,relativePaths:n})}catch(s){return Rm(n,Em(s))}let o;try{o=Xq(i,n)}catch(s){return Rm(n,`Malformed git cat-file batch output: ${Em(s)}`)}return new Map(n.map(s=>{let a=o.get(s)??null;return[s,a===null?{state:"absent"}:{state:"present",content:a}]}))}function Tm(e,t=Pm){let n=Mm({projectRoot:e.projectRoot,base:e.base,relativePaths:e.preloadPaths??[]},t);return r=>(n.has(r)||n.set(r,Dm({projectRoot:e.projectRoot,base:e.base,relativePath:r},t)),n.get(r)??{state:"unavailable",reason:`Base-content reader omitted ${r}.`})}function xR(e,t=e.changedFiles){let n=new Map(e.renamedFiles.map(r=>[r.to,r.from]));return[...new Set(t.map(r=>n.get(r)??r))]}function RR(e){un(e)}function Rm(e,t){return new Map(e.map(n=>[n,{state:"unavailable",reason:t}]))}function Em(e){let n=(e instanceof Error?e.message:String(e)).replaceAll(/\s+/g," ").trim().slice(0,500);return n===""?"Git base-content lookup failed without a reason.":n}function Xq(e,t){let n=new Map,r=0;for(let i of t){let o=e.indexOf(10,r);if(o<0)throw new Error("git cat-file batch output ended before object header");let s=e.subarray(r,o).toString("utf-8");if(r=o+1,s.endsWith(" missing")){n.set(i,null);continue}let a=/^[0-9a-f]+ ([^ ]+) (\d+)$/.exec(s);if(!a)throw new Error(`unexpected git cat-file batch header: ${s}`);let[,c,l]=a,u=Number(l);if(!Number.isFinite(u)||u<0)throw new Error(`unexpected git cat-file batch size: ${s}`);if(r+u>e.length)throw new Error("git cat-file batch output ended before blob payload");let d=e.subarray(r,r+u);n.set(i,c==="blob"?d.toString("utf-8"):null),r+=u,e[r]===10&&(r+=1)}return n}function Qq(e,t,n,r){if(n.length===0)return[];let i=new Map,o=new Set;for(let a of r.renamedFiles)n.includes(a.to)&&(i.set(a.to,a),o.add(a.from));let s=r.deletedFiles;if(s.length===0)return[...i.values()].sort((a,c)=>a.to.localeCompare(c.to));for(let a of n){if(i.has(a)||!zq(`${e}/${a}`))continue;let c=s.filter(d=>!o.has(d)).filter(d=>yR(d)===yR(a));if(c.length===0)continue;let l=Ye(e,a),u=c.map(d=>({from:d,to:a,similarity:eG(Jq({projectRoot:e,base:t,relativePath:d})??"",l)})).sort((d,m)=>m.similarity-d.similarity)[0];u&&u.similarity>=.45&&(i.set(a,u),o.add(u.from))}return[...i.values()].sort((a,c)=>a.to.localeCompare(c.to))}function Zq(e){let t=new Set,n=new Map,r=new Set;for(let i of e.flatMap(o=>ER(o))){let[o,s,a]=i.split(" ");if(!(!o||!s)){if(o.startsWith("R")&&a){t.add(a),n.set(a,{from:s,to:a,similarity:Number(o.slice(1))/100});continue}t.add(s),o.startsWith("D")&&r.add(s)}}return{changedFiles:[...t],renamedFiles:[...n.values()],deletedFiles:[...r]}}function eG(e,t){let n=new Set(bR(e)),r=new Set(bR(t));if(n.size===0&&r.size===0)return 1;if(n.size===0||r.size===0)return 0;let i=0;for(let o of n)r.has(o)&&(i+=1);return 2*i/(n.size+r.size)}function bR(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function ER(e){return e.split(`
346
- `).map(t=>t.trim()).filter(t=>t.length>0)}function tG(e,t){let n=IR(e),r=[];for(let i of t){let o=n(i);o&&!e.isIgnored(o)&&r.push(o)}return r}function nG(e,t){let n=IR(e),r=[];for(let i of t){let o=n(i.file);o&&!e.isIgnored(o)&&r.push({...i,file:o})}return wR(r)}function IR(e){let t=e.all(`SELECT relative_path FROM documents
347
- ORDER BY id`).map(r=>r.relative_path),n=new Map(t.map(r=>[r,r]));return r=>{let i=r.replace(/\\/g,"/"),o=n.get(i);return o||(t.find(s=>s.endsWith(i))??null)}}function SR(e){let t=[],n=null;for(let r of e.split(`
348
- `)){if(r.startsWith("+++ ")){n=rG(r.slice(4).trim());continue}if(!n||!r.startsWith("@@ "))continue;let i=/@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(r);if(!i)continue;let o=Math.max(0,Number(i[1])-1),s=i[2]===void 0?1:Number(i[2]);t.push({file:n,startLine:o,endLine:Math.max(o,o+Math.max(s,1)-1)})}return t}function rG(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function wR(e){let t=new Set,n=[];for(let r of e){let i=`${r.file}:${r.startLine}:${r.endLine}`;t.has(i)||(t.add(i),n.push(r))}return n}function iG(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(r=>km(e.startLine,e.endLine,r.startLine,r.endLine))}function oG(e,t,n){let r=new Map,i=[],o=LR(e),s=uG(n);for(let a of t){let c=o.get(a.file)??[];if(c.some(d=>km(d.startLine,d.endLine,a.startLine,a.endLine)))continue;let l=s.get(a.file)??[],u=dG(l,a);if(u){let d=c.find(m=>m.startLine>=u.startLine&&m.startLine<=u.endLine);if(d){r.set(d.symbolId,d),i.push(Im(a,"ast-widened"));continue}}if(l.length===0){let d=[...c].filter(m=>m.startLine<=a.startLine).sort((m,p)=>p.startLine-m.startLine||m.endLine-p.endLine)[0];if(d){r.set(d.symbolId,d),i.push(Im(a,"nearest-preceding"));continue}}i.push(Im(a,"unattributed"))}return{definitions:[...r.values()],notes:i}}function sG(e,t,n,r){let i=LR(n),o=[],s=[],a=[...new Set(t.map(c=>c.relativePath))];for(let c of a){let l=r.get(c)??[];if(l.length===0)continue;let u=i.get(c)??[];for(let d of l)u.some(m=>km(m.startLine,m.endLine,d.startLine,d.endLine))||o.push(d);o.some(d=>d.file===c)&&s.push(...aG(e,c))}return oG(t,o,s)}function aG(e,t){let n=J(e,t);return n?n.rootNode.namedChildren.filter(cG).map(r=>({file:t,startLine:r.startPosition.row,endLine:r.endPosition.row})).filter(r=>r.endLine>=r.startLine):[]}function cG(e){return e.endPosition.row<e.startPosition.row?!1:!new Set(["import_statement","comment"]).has(e.type)}function lG(e){let t=new Map;for(let n of e)t.set(n.symbolId,n);return[...t.values()]}function LR(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath)??[];r.push(n),t.set(n.relativePath,r)}return t}function uG(e){let t=new Map;for(let n of e){let r=t.get(n.file)??[];r.push(n),t.set(n.file,r)}return t}function dG(e,t){return e.filter(n=>n.startLine<=t.startLine&&n.endLine>=t.endLine).sort((n,r)=>n.endLine-n.startLine-(r.endLine-r.startLine))[0]}function Im(e,t){return{file:e.file,startLine:e.startLine,endLine:e.endLine,method:t}}function km(e,t,n,r){return e<=r&&n<=t}function mG(e,t,n,r,i,o,s,a,c){let l=Math.max(a,o.size,s.size);if(!SG(t,l))return;let u=T(t.symbol);r.push({symbol:t.symbol,shortName:u,file:t.relativePath,startLine:t.startLine,endLine:t.endLine,fanIn:l});for(let d of c)wm(e,n,i,d,u);for(let d of o)wm(e,n,i,d,u);for(let d of s)wm(e,n,i,d,u)}function vR(e,t,n){try{return{values:n(),status:{tier:e,state:"complete",attemptedSymbols:t}}}catch(r){return{values:new Map,status:{tier:e,state:"failed",attemptedSymbols:t,reason:fG(r)}}}}function pG(e){return["semantic-consumers","source-fallback-consumers"].map(t=>{let n=e.map(o=>o.evidenceTiers?.find(s=>s.tier===t)??{tier:t,state:"failed",attemptedSymbols:0,reason:"isolated diff-impact batch omitted its evidence-tier status"}),r=n.reduce((o,s)=>o+s.attemptedSymbols,0),i=[...new Set(n.filter(o=>o.state==="failed").map(o=>o.reason))];return i.length===0?{tier:t,state:"complete",attemptedSymbols:r}:{tier:t,state:"failed",attemptedSymbols:r,reason:i.join("; ").slice(0,500)}})}function PR(){return[{tier:"semantic-consumers",state:"complete",attemptedSymbols:0},{tier:"source-fallback-consumers",state:"complete",attemptedSymbols:0}]}function fG(e){let n=(e instanceof Error?e.message:String(e)).replaceAll(/\s+/g," ").trim().slice(0,500);return n===""?"evidence provider failed without a reason":n}function gG(e,t){if(t.length===0)return new Map;let n=e.all(`SELECT m.symbol_id, COUNT(DISTINCT c.document_id) AS fan_in
349
- FROM mentions m
350
- JOIN chunks c ON m.chunk_id = c.id
351
- WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
352
- AND m.role != 1
353
- GROUP BY m.symbol_id`,...t);return new Map(n.map(r=>[r.symbol_id,r.fan_in]))}function hG(e,t,n){if(t.length===0||n.length===0)return new Map;let r=e.all(`SELECT DISTINCT m.symbol_id, ref_d.relative_path
354
- FROM mentions m
355
- JOIN chunks c ON m.chunk_id = c.id
356
- JOIN documents ref_d ON c.document_id = ref_d.id
357
- WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
358
- AND m.role != 1
359
- AND ref_d.relative_path NOT IN (${n.map(()=>"?").join(",")})
360
- ${e.pathExclusionsFor("ref_d")}`,...t,...n),i=new Map;for(let o of r){let s=i.get(o.symbol_id);s||(s=new Set,i.set(o.symbol_id,s)),s.add(o.relative_path)}return i}function wm(e,t,n,r,i){if(e.isIgnored(r)||t.has(r))return;let o=n.get(r);o||(o=new Set,n.set(r,o)),o.add(i)}function yG(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function bG(e){return!(me(e.symbol)||e.parentTypeName!==null&&!Xe(e.symbol))}function SG(e,t){return Xe(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}var vG=5;function CG(e,t={}){let{base:n="HEAD",minContainment:r=.7,minCallees:i=3,minSiteCoverage:o=.4,maxHelpers:s=Number.POSITIVE_INFINITY,limit:a=20,scanLimit:c}=t,l=t.semantic!==!1,u=t.diffPlan??qi(e,{base:n}),d={available:u.note!==Lm,base:n,changedFiles:u.changedFiles,helpersChecked:0,skipped:[],findings:[],...u.note?{note:u.note}:{}};if(!d.available||u.changedFiles.length===0)return d;let m=new H(e),p=new Set(u.changedFiles),f=new Map(u.renamedFiles.map(R=>[R.to,R.from]));if(t.baseContentAt&&t.baseContentResultAt)throw new Error("Specify only one of baseContentAt or baseContentResultAt.");let g=t.baseContentResultAt?t.baseContentResultAt:t.baseContentAt?PG(t.baseContentAt):Tm({projectRoot:e.config.projectRoot,base:n,preloadPaths:xR(u)}),h=LG(m,p,f,g);if(h.unavailable)return d.available=!1,d.note=`Base content unavailable: ${h.unavailable.reason}`,d;if(h.definitions.length===0)return d;let b=h.definitions.slice(0,s);h.definitions.length>s&&(d.note=`helper scoring capped at ${s} of ${h.definitions.length} new symbols`);let S=m.calleeMap(b,{semantic:l}),y=b.map(R=>({def:R,callees:Pc((S.get(R.symbolId)??[]).map(E=>E.symbol))})),x=ji(e),v,C=()=>(v??=x.calleeIndex({minCallees:Math.min(3,i),scanLimit:c,semantic:l}),v);for(let{def:R,callees:E}of y){let w=T(R.symbol);if(E.size<i){d.skipped.push({helperShortName:w,helperFile:R.relativePath,reason:`fewer than ${i} meaningful callees \u2014 too small to score`});continue}let I=C(),k=wG(E,I);if(k===0){d.skipped.push({helperShortName:w,helperFile:R.relativePath,reason:"helper callee pattern is all project-wide infrastructure \u2014 too generic to score"});continue}let D=DG(e,R.symbolId);if(D.length===0){d.skipped.push({helperShortName:w,helperFile:R.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}d.helpersChecked+=1;let F=xG({candidateIndex:I,changed:p,helperCallees:E,helperFile:R.relativePath,helperSymbol:R.symbol,minContainment:r,minSiteCoverage:o,migratedFiles:D});F.length!==0&&(F.sort((L,A)=>DR(A.migrationScope)-DR(L.migrationScope)||A.containment-L.containment||A.siteCoverage-L.siteCoverage||L.file.localeCompare(A.file)),d.findings.push({helperSymbol:R.symbol,helperShortName:w,helperFile:R.relativePath,helperShape:"specific-callee-cluster",helperCalleeCount:E.size,specificHelperCalleeCount:k,migratedFiles:D.sort(),leftovers:F.slice(0,vG)}))}return d.findings.sort((R,E)=>(E.leftovers[0]?.containment??0)-(R.leftovers[0]?.containment??0)||R.helperFile.localeCompare(E.helperFile)),d.findings=d.findings.slice(0,a),d}function xG(e){let t=[],n=RG(e.helperSymbol,e.helperFile,e.migratedFiles),r=new Set;for(let i of e.helperCallees)for(let o of e.candidateIndex.candidateIndexesByCallee.get(i)??[])r.add(o);for(let i of r){let o=e.candidateIndex.corpus[i];if(o.symbol===e.helperSymbol||e.changed.has(o.file)||o.callees.has(e.helperSymbol))continue;let s=vx(e.helperCallees,o.callees);if(s<e.minContainment)continue;let a=[...e.helperCallees].filter(u=>o.callees.has(u)),c=o.callees.size===0?0:a.length/o.callees.size;if(c<e.minSiteCoverage||!a.some(u=>(e.candidateIndex.docFreq.get(u)??0)<=e.candidateIndex.ubiquityThreshold))continue;let l=EG(n,o.symbol,o.file);t.push({symbol:o.symbol,shortName:T(o.symbol),file:o.file,...l,containment:s,siteCoverage:c,uniqueSiteCalleeCount:Math.max(0,o.callees.size-a.length),sharedCallees:a.map(T).sort()})}return t}function DR(e){return e==="same-scope"?2:e==="unknown"?1:0}function RG(e,t,n){let r=new Set([...Am(t),...Fm(z(e))]);for(let i of n)for(let o of Am(i))r.add(o);return r}function EG(e,t,n){let r=new Set([...Am(n),...Fm(z(t))]);if(e.size===0||r.size===0)return{migrationScope:"unknown",migrationScopeReasons:["insufficient path/name tokens to infer migration scope"]};let i=[...r].filter(o=>e.has(o)).sort();return i.length>0?{migrationScope:"same-scope",migrationScopeReasons:[`shares migration-scope token(s): ${i.slice(0,5).join(", ")}`]}:{migrationScope:"possible-subtype",migrationScopeReasons:["no path/name tokens shared with the helper or already migrated files"]}}var IG=new Set(["app","apps","common","component","components","helper","helpers","index","lib","package","packages","page","pages","route","routes","service","services","shared","spec","src","test","tests","util","utils"]);function Am(e){return Fm(e.replace(/\.[^.]+$/,""))}function Fm(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!IG.has(t))}function wG(e,t){let n=0;for(let r of e)(t.docFreq.get(r)??0)<=t.ubiquityThreshold&&(n+=1);return n}function LG(e,t,n,r){let i=[];for(let o of e.productionCallableDefinitions({files:[...t],requireFunctionLikeSymbol:!0})){if(!t.has(o.relativePath))continue;let s=n.get(o.relativePath)??o.relativePath,a=r(s);if(a.state==="unavailable")return{definitions:[],unavailable:a};(a.state==="absent"||!new RegExp(`\\b${Ce(o.leaf)}\\b`).test(a.content))&&i.push(o)}return{definitions:i}}function PG(e){return t=>{let n=e(t);return n===null?{state:"absent"}:{state:"present",content:n}}}function DG(e,t){return e.all(`SELECT DISTINCT ref_d.relative_path
361
- FROM mentions m
362
- JOIN chunks c ON m.chunk_id = c.id
363
- JOIN documents ref_d ON c.document_id = ref_d.id
364
- WHERE m.symbol_id = ?
365
- AND m.role != 1
366
- ${e.pathExclusionsFor("ref_d")}`,t).map(r=>r.relative_path)}import{execFileSync as MG}from"child_process";var FR=2e3,_c=50,TG=64,kG=8,AG=3,FG=2160*60*60,NG=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,_G=3,OG=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,BG=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function $G(e){let t=ge(e,{clearGroups:["whole-project"]});return(n,r,i)=>{let o=i??Nm(n.config.projectRoot);if(!o)return null;let s=t.has(n)?t.get(n,()=>({head:"",value:null})):null;return s&&s.head===o?s.value:(t.invalidate(n),t.get(n,()=>({head:o,value:r(n.config.projectRoot,o)})).value)}}function Oc(e){let t=ge(e,{clearGroups:["whole-project"]});return(n,r,i,o)=>{let s=o??Nm(n.config.projectRoot);if(!s)return null;let a=t.has(n)?t.get(n,()=>({head:"",values:new Map})):null;(!a||a.head!==s)&&t.invalidate(n);let c=t.get(n,()=>({head:s,values:new Map}));if(c.values.has(r))return c.values.get(r)??null;let l=i(n.config.projectRoot,s);return c.values.set(r,l),l}}var jG=Oc("git-commit-history");function jt(e,t={}){let n=t.historyMode??"bounded",r=t.head;return{capability:i=>HG(e,i,r),commitHistory:()=>ds(e,n,r),fileChurn:()=>GG(e,n,r),changeAmplification:()=>zG(e,n,r),trackedFiles:()=>WG(e,r),fileAddRecords:()=>YG(e,n,r),coChangePairs:(i={})=>nz(e,i,n,r),coChangePairsForFiles:(i,o={})=>OR(e,i,o,n,r),directionalCoChangePairsForFiles:(i,o={})=>rz(e,i,o,n,r)}}function ds(e,t="bounded",n){return jG(e,Gi(t),(r,i)=>UG(r,i,t),n)}function HG(e,t,n){let r=n??Nm(e.config.projectRoot);return r?{slot:t,available:!0,head:r}:{slot:t,available:!1,head:null,reason:"git history is unavailable for this project"}}function Nm(e){try{return sn(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function sn(e,t){return MG("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"})}function UG(e,t,n){let r;try{r=sn(e,["log","--no-merges","--name-only",...Bc(n),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}return{head:t,...Bm(r,_c)}}function qG(e){return NG.test(e.subject)}function GG(e,t,n){let r=ds(e,t,n);if(!r)return null;let i=new Map;for(let o of r.commits){let s=qG(o);for(let a of o.files){let c=i.get(a)??{changes:0,fixChanges:0,lastChangedAt:0};c.changes+=1,s&&(c.fixChanges+=1),o.timestamp>c.lastChangedAt&&(c.lastChangedAt=o.timestamp),i.set(a,c)}}return i}function zG(e,t,n){let r=ds(e,t,n);if(!r||r.commits.length===0)return null;let i=r.commits.map(o=>o.files.length).filter(o=>o>0).sort((o,s)=>o-s);return i.length===0?null:{medianFilesPerCommit:MR(i,.5),p90FilesPerCommit:MR(i,.9),commitsAnalyzed:i.length}}function MR(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var KG=$G("git-tracked-files");function WG(e,t){return KG(e,n=>{try{let r=sn(n,["ls-files"]);return new Set(r.split(`
367
- `).map(i=>i.trim()).filter(i=>i!==""))}catch{return null}},t)}var VG=Oc("git-file-adds"),TR="__git__/file-adds",kR=dt({kind:"git-file-adds",invalidation:$e("git-file-adds"),serialize:XG,deserialize:QG});function NR(e){return jt(e).fileAddRecords()}function YG(e,t,n){let r=Gi(t);return VG(e,r,(i,o)=>JG(e,i,o,t),n)}function JG(e,t,n,r){let i=kR.read(e,AR(r),n);if(i)return i;let o=ZG(t,r);return o&&kR.write(e,AR(r),n,o),o}function XG(e){return JSON.stringify([...e.entries()])}function QG(e){if(!e)return null;try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=new Map;for(let r of t){if(!Array.isArray(r)||r.length!==2||typeof r[0]!="string")return null;let i=r[1];if(!i||typeof i.commitsAgo!="number"||!Number.isFinite(i.commitsAgo)||typeof i.addedAt!="number"||!Number.isFinite(i.addedAt))return null;n.set(r[0],{commitsAgo:i.commitsAgo,addedAt:i.addedAt})}return n}catch{return null}}function ZG(e,t){let n;try{n=sn(e,["log","--no-merges","--find-renames","--name-status",...Bc(t),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let r=new Map,i=new Map,o=-1;for(let s of n.split("")){if(s.trim()==="")continue;o+=1;let a=s.indexOf(`
368
- `),c=a>=0?s.slice(0,a):s,[,l]=c.split("\0"),u=Number(l)||0;if(!(a<0))for(let d of s.slice(a+1).split(`
369
- `)){let m=ez(d);if(!m)continue;if(m.status==="R"&&m.from&&m.to){let f=i.get(m.to)??new Set([m.to]);i.set(m.from,f);continue}if(m.status!=="A"||!m.to)continue;let p={commitsAgo:o,addedAt:u};r.set(m.to,p);for(let f of i.get(m.to)??[])r.set(f,p)}}return r}function ez(e){let t=e.trim().split(" "),n=t[0]??"";if(!n)return null;let r=n[0]??"";if(r==="R"){let o=t[1],s=t[2];return o&&s?{status:r,from:o,to:s}:null}let i=t[1];return i?{status:r,to:i}:null}var _R=Oc("git-co-change-pairs"),tz=Oc("git-directional-co-change-pairs");function nz(e,t,n,r){let i=`all\0${Gi(n)}\0${_m(t)}`,o=_R(e,i,()=>{let s=ds(e,n,r);return s?Om(s,t):null},r);return o&&[...o]}function OR(e,t,n,r,i){if(t.size===0)return[];let o=`files\0${Gi(r)}\0${BR(t)}\0${_m(n)}`,s=_R(e,o,()=>{let a=ds(e,r,i);return a?Om(a,n,t):null},i);return s&&[...s]}function rz(e,t,n,r,i){if(t.size===0)return[];let o=n.maxFilesPerCommit??_c;if(t.size>TG)return OR(e,t,n,r,i);let s=`directional\0${Gi(r)}\0${BR(t)}\0${_m({...n,maxFilesPerCommit:o})}`,a=tz(e,s,(c,l)=>{let u=iz(c,l,t,o,r);return u?Om(u,n,t):null},i);return a&&[...a]}function _m(e){let t=e.minTogether??4,n=e.minConfidence??.6,r=e.maxFilesPerCommit??_c;return`${t}\0${n}\0${r}`}function BR(e){return[...e].sort().join("\0")}function Om(e,t,n){let{minTogether:r=4,minConfidence:i=.6,maxFilesPerCommit:o=_c}=t,s=new Map,a=new Map,c=e.newestAnalyzedAt??0;for(let d of e.commits){let m=[...new Set(d.files)].sort();if(m.length>o)continue;e.newestAnalyzedAt===void 0&&d.timestamp>c&&(c=d.timestamp);let p=az(m),f=n===void 0||m.some(g=>n.has(g));for(let g of m)s.set(g,(s.get(g)??0)+1);if(f)for(let g=0;g<m.length;g++)for(let h=g+1;h<m.length;h++){if(n&&!n.has(m[g])&&!n.has(m[h]))continue;let b=`${m[g]}\0${m[h]}`,S=a.get(b)??{together:0,focusedTogether:0,broadTogether:0,lastTogetherAt:0,timestamps:[],subjects:[]};S.together+=1,p?S.broadTogether+=1:S.focusedTogether+=1,d.timestamp>S.lastTogetherAt&&(S.lastTogetherAt=d.timestamp),S.timestamps.push(d.timestamp),S.subjects.push(d.subject),a.set(b,S)}}let l=[],u=c-FG;for(let[d,m]of a){let p=m.together;if(p<r)continue;let[f,g]=d.split("\0"),h=s.get(f)??p,b=s.get(g)??p,S=Math.max(p/h,p/b);if(S<i)continue;let y=m.broadTogether/p,x=m.timestamps.filter(v=>v>=u).length;l.push({fileA:f,fileB:g,together:p,confidence:S,changesA:h,changesB:b,focusedTogether:m.focusedTogether,broadTogether:m.broadTogether,broadCommitRatio:y,lastTogetherAt:m.lastTogetherAt,recentTogether:x,commitScope:lz(m.broadTogether,p),recency:x>0?"recent":"stale",subjectContext:uz(m.subjects)})}return l.sort((d,m)=>m.together-d.together||m.confidence-d.confidence||d.fileA.localeCompare(m.fileA)),l}function iz(e,t,n,r,i){let o;try{o=oz(e,i)}catch{return null}if(o.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:0};let s;try{s=sn(e,["log","--no-merges","--format=%H",...Bc(i),"--",...[...n].sort()])}catch{return null}let a=new Set(o.map(m=>m.hash)),c=s.split(`
370
- `).map(m=>m.trim()).filter(m=>m!==""&&a.has(m)),l=sz(e,o,r);if(c.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:l};let u;try{u=sn(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...c])}catch{return null}let d=Bm(u,r);return{head:t,...d,newestAnalyzedAt:l}}function oz(e,t){return sn(e,["log","--no-merges","--format=%H%x00%ct",...Bc(t)]).split(`
371
- `).map(r=>r.trim()).filter(r=>r!=="").map(r=>{let[i,o]=r.split("\0");return{hash:i??"",timestamp:Number(o)||0}}).filter(r=>r.hash!=="")}function Bc(e){return e==="full"?[]:["-n",String($R())]}function $R(){return Vn(process.env.SCIP_QUERY_GIT_HISTORY_MAX_COMMITS)??FR}function Gi(e){return e==="full"?"full":`bounded:${$R()}`}function AR(e){let t=Gi(e);return t===`bounded:${FR}`?TR:`${TR}:${t}`}function sz(e,t,n){for(let i=0;i<t.length;i+=20){let o=t.slice(i,i+20),s;try{s=sn(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...o.map(c=>c.hash)])}catch{return t[0]?.timestamp??0}let a=Bm(s,n);if(a.commits.length>0)return a.commits[0].timestamp}return 0}function Bm(e,t){let n=[],r=0;for(let i of e.split("")){if(i.trim()==="")continue;let o=i.indexOf(`
372
- `),s=o>=0?i.slice(0,o):i,[a,c,l]=s.split("\0");if(!a||!c)continue;let u=o>=0?i.slice(o+1).split(`
373
- `).map(d=>d.trim()).filter(d=>d!==""):[];if(u.length>t){r+=1;continue}n.push({hash:a,timestamp:Number(c)||0,subject:l??"",files:u})}return{commits:n,skippedBulkCommits:r}}function az(e){return e.length>=kG?!0:cz(e).size>=AG}function cz(e){let t=new Set;for(let n of e){let r=n.indexOf("/");t.add(r>=0?n.slice(0,r):".")}return t}function lz(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function uz(e){let t=new Set,n=[],r=[];for(let i of e){!r.includes(i)&&r.length<_G&&r.push(i);for(let o of dz(i))t.add(o);for(let o of i.match(OG)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:r,externalIssueLabelStatus:"unavailable"}}function dz(e){let t=new Set,n=BG.exec(e)?.[1]?.toLowerCase();return n&&t.add(mz(n)),/\b(?:feat|feature)\b/i.test(e)&&t.add("feature"),/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i.test(e)&&t.add("fix"),/\b(?:docs?|documentation|guide|readme)\b/i.test(e)&&t.add("docs"),/\brefactor(?:ing|ed)?\b/i.test(e)&&t.add("refactor"),/\btests?\b/i.test(e)&&t.add("test"),/\b(?:release|version|v\d+\.\d+)\b/i.test(e)&&t.add("release"),/\bchore\b/i.test(e)&&t.add("chore"),/\bbuild\b/i.test(e)&&t.add("build"),/\bci\b/i.test(e)&&t.add("ci"),/\bperf(?:ormance)?\b/i.test(e)&&t.add("perf"),[...t]}function mz(e){return e==="feat"?"feature":e}var jR=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|uv\.lock|poetry\.lock|Pipfile\.lock|bun\.lockb?|\.SRCINFO|CHANGELOG(?:\.[a-z]+)?|.*\.(?:map|tsbuildinfo))$|(?:^|\/)(?:dist|build|out|node_modules|docs\/plans)\//i;function ms(e,t,n={}){let{minTogether:r=4,minConfidence:i=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=jt(e,{historyMode:n.historyMode,...n.head?{head:n.head}:{}}),c=a.commitHistory(),l=t!==void 0,u=a.coChangePairs({minTogether:l?Math.min(r,2):r,minConfidence:l?0:i,maxFilesPerCommit:s});if(!c||!u)return{available:!1,commitsAnalyzed:0,findings:[]};let d=typeof n.scanLimit=="number"?u.slice(0,n.scanLimit):u,m=Me(e),p=zR(e),f=gz(e,m,p),g=n.includeLinked===!0||l,h=[];for(let b of d){if(jR.test(b.fileA)||jR.test(b.fileB)||!HR(e,b.fileA)||!HR(e,b.fileB)||l&&!b.fileA.includes(t)&&!b.fileB.includes(t)||!l&&(q(b.fileA)==="test"||q(b.fileB)==="test"||Sz(b.fileA,b.fileB)||yz(b.fileA,b.fileB)))continue;let S=f(b.fileA,b.fileB);if(!g&&S)continue;let y=pz(b.fileA,b.fileB),x=fz(b,y,S);if(h.push({...b,structurallyLinked:S,partnerClass:y.partnerClass,partnerClassReasons:y.reasons,...x?{declaredCouplingSuggestion:x}:{}}),h.length>=o)break}return{available:!0,commitsAnalyzed:c.commits.length,findings:h}}function HR(e,t){return Ct(e.config.projectRoot,t)}function pz(e,t){let n=qR(e),r=qR(t),i=[],o=c=>{i.includes(c)||i.push(c)},s=(c,l)=>n.tags.has(c)&&r.tags.has(l)||n.tags.has(l)&&r.tags.has(c);if(s("doc","code"))return o("one side is documentation and the other is executable source"),{partnerClass:"doc-code",reasons:i};if(n.tags.has("test")||r.tags.has("test"))return o("one side is classified as a test file"),{partnerClass:"test-code",reasons:i};if(s("schema","script"))return o("schema or contract file changes with a script or generated-code path"),{partnerClass:"schema-script",reasons:i};if(s("model","view"))return o("model or state path changes with a view or component path"),{partnerClass:"model-view",reasons:i};if(s("config","code"))return o("configuration file changes with executable source"),{partnerClass:"config-code",reasons:i};let a=Mz(n.tokens,r.tokens).filter(c=>!Pz.has(c));return GR(e,t)||a.length>=2?(o(GR(e,t)?"both files live in the same directory":`files share feature tokens: ${a.slice(0,4).join(", ")}`),{partnerClass:"same-feature",reasons:i}):(o("no specific relationship pattern matched"),{partnerClass:"unknown",reasons:i})}function fz(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!Lz.has(t.partnerClass))return;let r=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${Tz(r)}`,files:r,reason:`${t.partnerClass} pair changed together ${e.together}x with ${Math.round(e.confidence*100)}% confidence; declare it if future edits should require both sides.`}}function gz(e,t=Me(e),n=zR(e)){return(r,i)=>vz(t,n,r,i)}var hz=/(?:^|\/)(?:locales|i18n)\//i;function UR(e){return hz.test(e)}function yz(e,t){return UR(e)&&UR(t)?!0:bz(e,t)}function bz(e,t){if(!e.endsWith(".json")||!t.endsWith(".json"))return!1;let n=e.lastIndexOf("/"),r=t.lastIndexOf("/");if(n<0||r<0)return!1;let i=e.slice(0,n),o=t.slice(0,r);if(i===o)return!1;let s=e.slice(n+1),a=t.slice(r+1);if(s!==a)return!1;let c=i.lastIndexOf("/"),l=o.lastIndexOf("/"),u=c>=0?i.slice(0,c):"",d=l>=0?o.slice(0,l):"";return u===d}function Sz(e,t){let n=e.lastIndexOf("/"),r=t.lastIndexOf("/");if(e.slice(0,n)!==t.slice(0,r))return!1;let i=e.slice(n+1).split(".")[0],o=t.slice(r+1).split(".")[0];return i!==""&&i===o}function zR(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function vz(e,t,n,r){return e.get(n)?.has(r)===!0||e.get(r)?.has(n)===!0?!0:t.some(i=>i.has(n)&&i.has(r))}var Cz=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,xz=/(?:^|\/)(?:\.[a-z0-9-]+rc|config|configs|settings|\.github)(?:\/|$)|(?:^|\/)(?:package\.json|tsconfig(?:\.[^.]+)?\.json|vite\.config\.[cm]?[jt]s|rollup\.config\.[cm]?[jt]s|eslint\.config\.[cm]?[jt]s)$|\.(?:json|ya?ml|toml|ini|env)$/i,Rz=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,Ez=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,Iz=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,wz=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,Lz=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),Pz=new Set(["src","lib","app","apps","packages","frontend","backend","examples","python","typescript","javascript","test","tests","spec","index","main","utils","util","types","type","config","docs","doc","package","requirements","ts","tsx","js","jsx","mjs","cjs","vue","py","md","mdx","json","yaml","yml","toml","txt"]);function qR(e){let t=e.replace(/\\/g,"/"),n=new Set;return Cz.test(t)&&n.add("doc"),xz.test(t)&&n.add("config"),Rz.test(t)&&n.add("schema"),Ez.test(t)&&n.add("script"),Iz.test(t)&&n.add("model"),wz.test(t)&&n.add("view"),q(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:Dz(t)}}function GR(e,t){let n=e.lastIndexOf("/"),r=t.lastIndexOf("/"),i=n>=0?e.slice(0,n):"",o=r>=0?t.slice(0,r):"";return i!==""&&i===o}function Dz(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).map(t=>t.toLowerCase()).filter(t=>t.length>=2)}function Mz(e,t){let n=new Set(t);return[...new Set(e.filter(r=>n.has(r)))].sort()}function Tz(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}function Hc(e,t){let n=kz(e,t)??Az(e,t)??Fz(e,t)??Nz(e,t);return _z(e,n,t)}function kz(e,t){let n=-1,r=null;for(let i=0;i<=t;i+=1){let o=$m(e[i]??"");o&&(r===null?(r=o,n=i):o===r&&(r=null,n=-1))}if(r===null||n<0)return null;for(let i=t+1;i<e.length;i+=1)if($m(e[i]??"")===r)return{start:n,end:i+1};return{start:n,end:e.length}}function $m(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function Az(e,t){if(!$c(e[t]??""))return null;let n=t;for(;n>0&&$c(e[n-1]??"");)n-=1;let r=t+1;for(;r<e.length&&$c(e[r]??"");)r+=1;return{start:n,end:r}}function $c(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function Fz(e,t){let n=t;for(;n>=0;){let o=e[n]??"";if(jc(o)!==null)break;if(jm(o)!==null)return null;n-=1}if(n<0)return null;let r=jc(e[n]??"");if(r===null)return null;let i=n+1;for(;i<e.length;){let o=e[i]??"",s=jc(o);if(s!==null){if(s<=r)break;i+=1;continue}if(jm(o)!==null)break;i+=1}return{start:n,end:i}}function jc(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function Nz(e,t){let n=e[t]??"";if(WR(n)||n.trim().length===0)return{start:t,end:t+1};let r=t;for(;r>0&&KR(e[r-1]??"");)r-=1;let i=t+1;for(;i<e.length&&KR(e[i]??"");)i+=1;return{start:r,end:i}}function KR(e){return jm(e)===null}function jm(e){return e.trim().length===0?"blank":WR(e)?"heading":$m(e)?"fence":$c(e)?"table":jc(e)!==null?"list":null}function WR(e){return/^#{1,6}\s+/.test(e.trim())}function _z(e,t,n){let{start:r,end:i}=t;if(i-r>40){let s=Math.floor(20);r=Math.max(r,n-s),i=Math.min(i,r+40),r=Math.max(t.start,i-40)}let o=e.slice(r,i).join(`
374
- `).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}function Wr(e,t){return t.filter(n=>e.includes(n))}var Oz=/<!--\s*scip-query:\s*snapshot\s*-->/i;function VR(e,t){if((e.config.docs?.snapshotPaths??[]).some(i=>lr(i,t)))return!0;let r=W(e,t);return r.length>0&&Oz.test(r)}var YR={classifyCitation:$z,citationContexts:jz,citationKindLabel:Uz,citationRemediation:qz,referenceTargets:Gz,hasLineAnchoredCitation:Bz};function Bz(e){return e.some(t=>(t.lineReferences?.length??0)>0)}function $z(e){let t=e.join(`
375
- `).toLowerCase(),n=[],r=Wr(t,[".scipquery","declaredcouplings","suppression","suppressions","config","configuration","json"]);if(r.length>0)return n.push(`configuration/example terms near citation: ${r.join(", ")}`),{citationKind:"configuration-example",actionTier:"support",reasons:n};let i=Wr(t,["accepted","intentional","intentionally","retained","historical"]);if(i.length>0)return n.push(`intentional-record terms near citation: ${i.join(", ")}`),{citationKind:"intentional-record",actionTier:"support",reasons:n};let o=Wr(t,["command","cli","usage","example","run","workflow"]);return o.length>0?(n.push(`guide/reference terms near citation: ${o.join(", ")}`),{citationKind:"guide-reference",actionTier:"signal",reasons:n}):(n.push(e.length>0?"citation appears in prose without config or guide markers":"citation context unavailable"),{citationKind:"behavioral-claim",actionTier:"direct",reasons:n})}function jz(e,t,n){let r=W(e,t);if(!r&&!Ct(e.config.projectRoot,t))return[];let i=r.split(/\r?\n/),o=n.flatMap(Hz),s=[];for(let a=0;a<i.length;a+=1){let c=i[a]??"";o.some(l=>c.includes(l))&&s.push(Hc(i,a))}return s}function Hz(e){let t=e.split("/");return[e,`./${e}`,t.slice(-3).join("/"),t.slice(-2).join("/")].filter((n,r,i)=>n.length>0&&i.indexOf(n)===r)}function Uz(e){switch(e){case"behavioral-claim":return"a behavioral doc claim";case"configuration-example":return"a configuration example";case"guide-reference":return"a guide reference";case"intentional-record":return"an intentional record"}}function qz(e,t){switch(e){case"behavioral-claim":return`Re-read ${t} and update the behavioral claim or citation.`;case"configuration-example":return`Verify the configuration example in ${t} still points at the intended file; update only if the example target changed.`;case"guide-reference":return`Verify the guide reference in ${t} still sends readers to the right implementation or command surface.`;case"intentional-record":return`Verify the intentional citation in ${t} is still meant to name this file.`}}function Gz(e,t,n){let r=Ac(n),i=new Set;for(let o of t)zz(e,o,r.get(o)??[])&&i.add(o);return i}function zz(e,t,n){if(!Kz.test(t)||!Ct(e.config.projectRoot,t))return!0;if(n.length===0)return!1;let r=Ye(e.config.projectRoot,t,{inputKind:"changed source file"}).split(/\r?\n/),i=Wz(r);for(let o of n)for(let s=o.startLine;s<=o.endLine;s+=1)if((r[s]??"").trim()!==""&&!i.has(s))return!0;return!1}var Kz=/\.(?:[cm]?[jt]sx?)$/i;function Wz(e){let t=new Set,n=!1;for(let r=0;r<e.length;r+=1){let i=e[r].trim();!n&&Vz(i)&&(n=!0),n&&(t.add(r),i.endsWith(";")&&(n=!1))}return t}function Vz(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}var JR=dt({kind:"doc-path-evidence",invalidation:$e("doc-path-evidence"),serialize:cK,deserialize:lK}),ps=/\.(?:md|mdx|rst|txt)$/i;function Yz(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var Jz=3,Xz=/([A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6})(?::([1-9][0-9]*))?\b/g;function Qz(e,t={}){let{doc:n,limit:r=20,minCoupling:i=Jz,includeSnapshotExcluded:o=!1}=t,s=nK(e,t.historyMode??"bounded");if(!s)return{available:!1,commitsAnalyzed:0,docsScanned:0,findings:[]};let a=[];for(let c of s.docFiles){if(n!==void 0&&!c.includes(n)||n===void 0&&!rK(e,c)||n!==void 0&&!Ct(e.config.projectRoot,c))continue;let l=VR(e,c);if(l&&!o)continue;let{value:u,estimated:d}=Zz(e,c,s.changeTimes.get(c)),m=eK(e,c),p=new Map,{resolved:f,broken:g,citations:h}=oK(e,c,s.tracked,s.trackedBySuffix,s.everSeenInHistory),b=new Map(h.map(y=>[y.file,y]));for(let y of f){if(y===c||ps.test(y))continue;let x=(s.changeTimes.get(y)??[]).filter(C=>C>u).length;if(x===0)continue;let v=b.get(y);p.set(y,{file:y,evidence:"reference",coChanges:0,changesSinceDocUpdate:x,...Hm("reference",m,v?.contexts),citationContexts:v?.contexts,citedLines:v?.lineReferences})}for(let[y,x]of s.coupling.get(c)??[]){if(x<i||!s.tracked.has(y))continue;let v=(s.changeTimes.get(y)??[]).filter(R=>R>u).length;if(v===0)continue;let C=p.get(y);C?(C.evidence="both",C.coChanges=x,Object.assign(C,Hm("both",m,C.citationContexts))):p.set(y,{file:y,evidence:"co-change",coChanges:x,changesSinceDocUpdate:v,...Hm("co-change",m)})}if(p.size===0&&g.length===0)continue;let S=[...p.values()].sort((y,x)=>x.changesSinceDocUpdate-y.changesSinceDocUpdate);a.push({doc:c,docLastChangedAt:u,staleness:S.reduce((y,x)=>y+x.changesSinceDocUpdate,0)+g.length*10,subjects:S.slice(0,8),brokenReferences:g,...l?{snapshotExcluded:!0}:{},...d?{docLastChangedAtEstimated:!0}:{}})}return a.sort((c,l)=>l.staleness-c.staleness),{available:!0,commitsAnalyzed:s.historyCommitCount,docsScanned:s.docFiles.length,findings:a.slice(0,r)}}function Zz(e,t,n){if(n&&n.length>0)return{value:Math.max(...n),estimated:!1};try{return{value:Math.floor(Ps(e.config.projectRoot,t).mtimeMs/1e3),estimated:!0}}catch(r){if(Ct(e.config.projectRoot,t))throw r;return{value:0,estimated:!1}}}function eK(e,t){let n=W(e,t).slice(0,6e3);if(!n)return{docIntent:"unknown",reasons:["doc text unavailable"]};let r=`${t}
376
- ${n}`.toLowerCase(),i=Wr(r,["historical note","historical record","history note","retrospective","postmortem","post-mortem","archived","archive","previously","legacy","recorded","record of","snapshot","as of","migration note","decision record"]);if(i.length>0)return{docIntent:"historical-note",reasons:[`historical-note terms: ${i.join(", ")}`]};let o=Wr(r,["current","standard","standards","must","should","policy","guide","guidance","workflow","contract","invariant","source of truth"]);return o.length>0?{docIntent:"current-guidance",reasons:[`current-guidance terms: ${o.join(", ")}`]}:{docIntent:"unknown",reasons:["no current-guidance or historical-note markers found"]}}function Hm(e,t,n=[]){let r=e==="co-change"||n.length===0?null:YR.classifyCitation(n);return{actionTier:tK(e,t.docIntent,r?.actionTier),docIntent:t.docIntent,docIntentReasons:t.reasons,...r?{citationKind:r.citationKind,citationKindReasons:r.reasons}:{}}}function tK(e,t,n){return t==="historical-note"?"support":n||(e==="co-change"?"signal":"direct")}function nK(e,t){let n=jt(e,{historyMode:t}),r=n.commitHistory();if(!r)return null;let i=n.trackedFiles()??new Set,o=new Map,s=new Map,a=new Set;for(let c of r.commits){let l=[...new Set(c.files)],u=l.filter(m=>ps.test(m)),d=l.filter(m=>!ps.test(m));for(let m of l){a.add(m);let p=o.get(m)??[];p.push(c.timestamp),o.set(m,p)}for(let m of u){let p=s.get(m);p||(p=new Map,s.set(m,p));for(let f of d)p.set(f,(p.get(f)??0)+1)}}return{changeTimes:o,coupling:s,docFiles:[...i].filter(c=>ps.test(c)),everSeenInHistory:a,historyCommitCount:r.commits.length,tracked:i,trackedBySuffix:iK(i)}}function rK(e,t){return ps.test(t)&&!Yz(t)&&Ct(e.config.projectRoot,t)}function iK(e){let t=new Map;for(let n of e){let r=n.split("/");for(let i of[2,3]){if(r.length<i)continue;let o=r.slice(-i).join("/"),s=t.get(o)??[];s.push(n),t.set(o,s)}}return t}function oK(e,t,n,r,i){let o=new Set,s=new Set,a=sK(e,t);if(!a)return{resolved:o,broken:[],citations:[]};let c=a.candidates,l=a.contextsByCandidate,u=a.lineReferencesByCandidate,d=new Map,m=new Map,p=(f,g)=>{let h=l.get(g);if(h&&h.length>0){let S=d.get(f)??[];S.push(...h),d.set(f,XR(S).slice(0,3))}let b=u.get(g);b&&b.length>0&&m.set(f,Um([...m.get(f)??[],...b]))};for(let f of c){if(n.has(f)){o.add(f),p(f,f);continue}let g=r.get(f);if(g&&g.length===1){o.add(g[0]),p(g[0],f);continue}g&&g.length>1||i.has(f)&&s.add(f)}return{resolved:o,broken:[...s],citations:[...d].map(([f,g])=>({file:f,contexts:g,lineReferences:m.get(f)}))}}function sK(e,t,n){let r=n;if(r===void 0&&(r=W(e,t),!r&&!Ct(e.config.projectRoot,t)))return null;let i=Rt(e,t,r),o=JR.read(e,t,i);if(o)return o;let s=aK(r);return JR.write(e,t,i,s),s}function aK(e){let t=e.split(/\r?\n/),n=new Set,r=new Map,i=new Map;for(let o=0;o<t.length;o+=1){let s=t[o]??"";for(let a of s.matchAll(Xz)){let c=(a[1]??"").replace(/^\.?\//,"");if(c.length===0)continue;n.add(c);let l=a[2]?Number(a[2]):null;l!==null&&Number.isSafeInteger(l)&&i.set(c,Um([...i.get(c)??[],l]));let u=Hc(t,o);if(u.length===0)continue;let d=r.get(c)??[];d.push(u),r.set(c,XR(d).slice(0,3))}}return{candidates:[...n],contextsByCandidate:r,lineReferencesByCandidate:i}}function cK(e){let t={candidates:e.candidates,contextsByCandidate:[...e.contextsByCandidate.entries()],lineReferencesByCandidate:[...e.lineReferencesByCandidate.entries()]};return JSON.stringify(t)}function lK(e){try{let t=JSON.parse(e);if(!sf(t))return null;let n=Yi(t.candidates),r=dK(t.contextsByCandidate),i=uK(t.lineReferencesByCandidate);return!n||!r?null:{candidates:n,contextsByCandidate:new Map(r),lineReferencesByCandidate:new Map(i??[])}}catch{return null}}function uK(e){if(e===void 0)return[];if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string"||!Array.isArray(n[1]))return null;let r=[];for(let i of n[1]){if(typeof i!="number"||!Number.isSafeInteger(i))return null;r.push(i)}t.push([n[0],Um(r)])}return t}function dK(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string")return null;let r=Yi(n[1]);if(!r)return null;t.push([n[0],r])}return t}function XR(e){let t=[];for(let n of new Set(e))t.some(r=>mK(r,n))||t.push(n);return t}function Um(e){return[...new Set(e)].sort((t,n)=>t-n)}function mK(e,t){if(e===t)return!0;let n=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),r=t.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),i=Math.min(n.length,r.length);if(i===0)return!1;if(i<3)return e.includes(t)||t.includes(e);let o=new Set(r),s=n.filter(a=>o.has(a)).length;return s>=3&&s/i>=.6}import{createHash as pK}from"crypto";var fK=3;function fs(e,t={}){let{scope:n,maxLoc:r=15,minLoc:i=fK,limit:o,scanLimit:s}=t,a=NR(e),c=gK(e,{scope:n,maxLoc:r,scanLimit:s}).map(u=>hK(e,u,a,i)).filter(u=>u!==null),l=eE(c);return o?l.slice(0,o):l}function ZR(e){let t=an(e);return pn(t).replace(/\s+/g,"")}function eE(e){let t=new Map;for(let r of e){if(r.normalizedBody.length<8)continue;let i=bK(r.normalizedBody),o=t.get(i)??[];o.push(r),t.set(i,o)}let n=[];for(let[r,i]of t){let o=new Set(i.map(a=>a.file));if(i.length<2||o.size<2)continue;let s=[...i].sort(SK).map(({normalizedBody:a,...c})=>c);n.push({hash:r,canonical:s[0],functions:s})}return n.sort((r,i)=>{let o=i.functions.length-r.functions.length;if(o!==0)return o;let s=QR(i)-QR(r);return s!==0?s:r.canonical.file.localeCompare(i.canonical.file)}),n}function gK(e,t){let n=Le(e,{scope:t.scope}).filter(r=>r.isFunctionLike&&!e.isIgnored(r.relativePath)).filter(r=>!Fs(e,r.relativePath,r.startLine,"similar")).filter(r=>ee(r)<=t.maxLoc);return n.sort((r,i)=>ee(i)-ee(r)||r.relativePath.localeCompare(i.relativePath)),he(n,t.scanLimit)}function hK(e,t,n,r){let i=Ht(e,t);if(!i||yK(i)<r)return null;let o=qm(e,t);return o?{symbol:t.symbol,shortName:T(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:ee(t),ageCommits:n?.get(t.relativePath)?.commitsAgo??null,normalizedBody:o}:null}function qm(e,t){let n=Ht(e,t);return n&&ZR(n)||null}function Ht(e,t){let n=V(e,t.relativePath);return n.length===0?null:n.slice(t.startLine,t.endLine+1).join(`
377
- `)}function an(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(t>=0&&n>t)return e.slice(t+1,n);let r=e.indexOf("=>");return r>=0?e.slice(r+2).replace(/;+\s*$/,""):e}function yK(e){return an(e).split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0).length}function bK(e){return pK("sha256").update(e).digest("hex").slice(0,16)}function SK(e,t){let n=e.ageCommits??-1;return(t.ageCommits??-1)-n||e.file.localeCompare(t.file)||e.startLine-t.startLine}function QR(e){return e.functions.reduce((t,n)=>t+n.loc,0)}var vK=new Set(Kt());function CK(e,t={}){let{includeHomonyms:n=!1,limit:r}=t,i=Uc(e,t).filter(o=>o.relationship==="divergent"||n&&o.relationship==="homonym");return r?i.slice(0,r):i}function Uc(e,t={}){let{scope:n,minSimilarity:r=.3,scanLimit:i}=t,o=EK(e,{scope:n,scanLimit:i});return rE(o,{minSimilarity:r,isDelegatePair:KK(e)}).filter(s=>!s.members.some(a=>Fs(e,a.file,a.startLine,"twin")))}function rE(e,t={}){let n=t.minSimilarity??.3,r=t.isDelegatePair,i=e.filter(l=>!uE(l.leaf)&&!NK(l.leaf)&&q(l.file)!=="test"&&!je(l.symbol)&&!oE(l.symbol)&&!sE(l.symbol,l.leaf)),{recordsByLeaf:o,recordOrder:s}=N("twin-drift.group-by-leaf",()=>xK(i),()=>({records:i.length})),a=N("twin-drift.cluster-leaf-names",()=>iE([...o.keys()]),()=>({leaves:o.size}));return N("twin-drift.compare-clusters",()=>{let l=[];for(let u of a){let d=RK(u,o,s);if(d.length<2||new Set(d.map(S=>S.file)).size<2)continue;let m=null,p=!1,f=!1,g=new Set;for(let S=0;S<d.length;S+=1)for(let y=S+1;y<d.length;y+=1){let x=d[S],v=d[y];if(x.file===v.file||!$K(x,v)||r?.(x,v,d)||r?.(v,x,d))continue;if(p=!0,g.add(x.symbol),g.add(v.symbol),x.normalizedBody===v.normalizedBody){f=!0;continue}let C=TK(x.tokens,v.tokens);(!m||C>m.similarity)&&(m={a:x,b:v,similarity:C})}if(!p)continue;let h=d.filter(S=>g.has(S.symbol)).sort((S,y)=>S.file.localeCompare(y.file)||S.startLine-y.startLine).map(MK);if(!m){l.push({leaf:nE(u),relationship:f?"identical":"homonym",maxDivergence:0,members:h});continue}let b=m.similarity>=n?"divergent":"homonym";l.push({leaf:nE(u),relationship:b,maxDivergence:Math.round((1-m.similarity)*1e3)/1e3,members:h,...b==="divergent"?{firstDivergentTokens:kK(m.a.tokens,m.b.tokens)}:{}})}return l},()=>({clusters:a.length,records:i.length})).sort((l,u)=>u.members.length-l.members.length||u.maxDivergence-l.maxDivergence||l.leaf.localeCompare(u.leaf))}function xK(e){let t=new Map,n=new Map;for(let[r,i]of e.entries()){let o=t.get(i.leaf)??[];o.push(i),t.set(i.leaf,o),n.set(i,r)}return{recordsByLeaf:t,recordOrder:n}}function RK(e,t,n){let r=[...e].flatMap(i=>t.get(i)??[]);return e.size>1&&r.sort((i,o)=>(n.get(i)??0)-(n.get(o)??0)),r}function EK(e,t){let n=N("twin-drift.load-definitions",()=>Le(e,{scope:t.scope}).filter(o=>IK(o)&&!e.isIgnored(o.relativePath)).filter(o=>!Ei(o.relativePath)));N("twin-drift.sort-definitions",()=>n.sort((o,s)=>o.relativePath.localeCompare(s.relativePath)||o.startLine-s.startLine),()=>({definitions:n.length}));let r=he(n,t.scanLimit),i=N("twin-drift.select-candidates",()=>wK(r),()=>({scanned:r.length}));return N("twin-drift.build-records",()=>{let o=[];for(let s of i){let a=LK(e,s);a&&o.push(a)}return o},()=>({candidates:i.length,scanned:r.length}))}function IK(e){return e.isFunctionLike?e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&vK.has(e.kind):!0:!1}function wK(e){let t=e.filter(o=>o.leaf&&!uE(o.leaf)&&!je(o.symbol)&&!oE(o.symbol)&&!sE(o.symbol,o.leaf)),n=new Map;for(let o of t){let s=n.get(o.leaf)??[];s.push(o),n.set(o.leaf,s)}let r=iE([...n.keys()]),i=new Set;for(let o of r){let s=[...o].flatMap(a=>n.get(a)??[]);if(!(s.length<2)&&!(new Set(s.map(a=>a.relativePath)).size<2)&&!s.every(a=>q(a.relativePath)==="test"))for(let a of s)i.add(a)}return e.filter(o=>i.has(o))}function LK(e,t){if(!t.leaf)return null;let n=Ht(e,t);if(!n||!Xe(t.symbol)&&!PK(n,t.leaf))return null;let r=pn(an(n)),i=r.replace(/\s+/g,"");if(!i||i.length<8)return null;let o=r.match(DK)??[];return o.length===0?null:{leaf:t.leaf,symbol:t.symbol,shortName:T(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:ee(t),normalizedBody:i,tokens:o,isThinForwarder:cE(r)}}function PK(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`\\b(?:const|let|var)\\s+${n}(?:\\s*:[^=]+)?\\s*=\\s*(?:async\\s*)?(?:\\([^)]*\\)|[A-Za-z_$][\\w$]*)\\s*=>`,"s").test(e)}var DK=/[A-Za-z_$][A-Za-z0-9_$]*|\d+(?:\.\d+)?|[^\sA-Za-z0-9_$]/g;function MK(e){return{symbol:e.symbol,shortName:e.shortName,file:e.file,startLine:e.startLine,endLine:e.endLine,loc:e.loc}}function TK(e,t){let n=new Set(e),r=new Set(t);if(n.size===0&&r.size===0)return 1;if(n.size===0||r.size===0)return 0;let i=0;for(let s of n)r.has(s)&&(i+=1);let o=n.size+r.size-i;return o===0?0:i/o}function kK(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;let i=e.slice(r,r+6).join(" "),o=t.slice(r,r+6).join(" ");return!i&&!o?"(bodies differ only in trailing length)":`A: ${i||"(end)"} | B: ${o||"(end)"}`}function iE(e){let t=new Map;for(let s of e)t.set(s,s);let n=s=>{let a=s;for(;t.get(a)!==a;)a=t.get(a);let c=s;for(;t.get(c)!==a;){let l=t.get(c);t.set(c,a),c=l}return a},r=(s,a)=>{let c=n(s),l=n(a);c!==l&&t.set(c,l)},i=new Map;for(let s of e){let a=s.slice(0,2).toLowerCase(),c=i.get(a)??[];c.push(s),i.set(a,c)}for(let s of i.values())for(let a=0;a<s.length;a+=1)for(let c=a+1;c<s.length;c+=1)AK(s[a],s[c])&&r(s[a],s[c]);let o=new Map;for(let s of e){let a=n(s),c=o.get(a)??new Set;c.add(s),o.set(a,c)}return[...o.values()]}function AK(e,t){return e===t||e.toLowerCase()===t.toLowerCase()?!0:e.length<8||t.length<8||Math.abs(e.length-t.length)>2||FK(e.toLowerCase(),t.toLowerCase())/Math.max(e.length,t.length)<.8?!1:jK(e.toLowerCase(),t.toLowerCase(),2)}function FK(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;return r}function NK(e){return/^[A-Z][A-Z0-9_]*$/.test(e)||/^__[^_].*__$/.test(e)||_K.has(e.toLowerCase())}var _K=new Set(["main","row"]),OK=new Set(["app","component","components","feature","features","impl","index","lib","route","routes","shared","src","tsx","typescript","ui"]);function oE(e){return e.startsWith("rust-analyzer ")&&/\/(?:tests?|benches?)\//.test(e)}var BK=new Set(["default","new","reset"]);function sE(e,t){return e.startsWith("rust-analyzer ")&&BK.has(t.toLowerCase())}function $K(e,t){if(e.leaf.toLowerCase()!==t.leaf.toLowerCase()||e.leaf.length>4)return!0;let n=tE(e);return[...tE(t)].some(r=>n.has(r))}function tE(e){let t=e.leaf.toLowerCase();return new Set(`${e.file}/${e.shortName}`.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(n=>n.length>2&&n!==t&&!OK.has(n)))}function jK(e,t,n){if(Math.abs(e.length-t.length)>n)return!1;let r=Array.from({length:t.length+1},(i,o)=>o);for(let i=1;i<=e.length;i+=1){let o=[i],s=o[0];for(let a=1;a<=t.length;a+=1){let c=e[i-1]===t[a-1]?0:1,l=Math.min(r[a]+1,o[a-1]+1,r[a-1]+c);o.push(l),s=Math.min(s,l)}if(s>n)return!1;r=o}return r[t.length]<=n}function aE(e){return cE(pn(an(e)))}function cE(e){let t=e.trim();if(!t||HK.test(t))return!1;let n=GK(t);return n.length===0||n.length>2?!1:qK(n[n.length-1])}var HK=/\b(?:if|else|for|while|switch|try|catch|do)\b/,UK=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^[\]]*\])*\((?:[^()]|\([^()]*\))*\)$/;function qK(e){let t=e.trim().replace(/^return\s+/,"").replace(/^await\s+/,"").replace(/;\s*$/,"").trim();return UK.test(t)}function GK(e){let t=[],n=0,r="";for(let i of e){if(i==="("||i==="["||i==="{"?n+=1:(i===")"||i==="]"||i==="}")&&(n=Math.max(0,n-1)),i===";"&&n===0){t.push(r),r="";continue}r+=i}return r.trim()&&t.push(r),t.map(i=>i.trim()).filter(i=>i.length>0)}var zK=3;function KK(e){let t=new Map;return(n,r,i)=>{if(!n.isThinForwarder)return!1;let o=`${n.symbol}\0${r.symbol}`,s=t.get(o);if(s!==void 0)return s;let a=lE(e,n,r,i,zK,new Set);return t.set(o,a),a}}function lE(e,t,n,r,i,o){if(i<=0||o.has(t.symbol)||(o.add(t.symbol),(Gt(e,t.file)??[]).filter(c=>c.line>=t.startLine&&c.line<=t.endLine&&c.calleeLeaf===n.leaf).length===0))return!1;let a=new Set(ae(e,t.file).filter(c=>c.sourcePath&&(c.kind!=="namespace"||c.usedMembers.includes(n.leaf))).map(c=>c.sourcePath));if([...a].some(c=>Fe(c,n.file)))return!0;for(let c of r)if(!(c.symbol===t.symbol||c.symbol===n.symbol||!c.isThinForwarder)&&[...a].some(l=>Fe(l,c.file))&&lE(e,c,n,r,i-1,o))return!0;return!1}function uE(e){return e.startsWith("<")&&e.endsWith(">")}function nE(e){return[...e].sort()[0]}import{dirname as aW,isAbsolute as cW,relative as lW,resolve as uW}from"path";import{basename as dE,extname as mE}from"path";function qc(e,t,n,r,i,o){let s=new Set;VK(e,t,n,r)&&s.add(i);for(let a of o)a.value&&WK(s,a.label,a.value);return[...s].slice(0,6)}function WK(e,t,n){let r=YK(n);t.endsWith("name")&&JK(r)&&e.add(`${t} has type-guard boundary shape`);for(let i of r){let o=XK.get(i);o&&e.add(`${t} has ${o} term: ${i}`)}}function VK(e,t,n,r){if(n<=0)return!1;let i=V(e,t);if(i.length===0)return!1;for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(i[o]??"").trim();if(s!==""){if(ks(s)===r)return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function YK(e){return e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function JK(e){return e.some(t=>QK.has(t))&&e.some(t=>ZK.has(t))}var XK=new Map([["access","access policy"],["accessible","access policy"],["adapter","adapter"],["adapters","adapter"],["allow","access policy"],["allowed","access policy"],["animation","animation calculation"],["api","api surface"],["apply","settings/application"],["audit","side-effect boundary"],["auth","authorization"],["authorize","authorization"],["audio","audio side-effect"],["can","access policy"],["capabilities","capability boundary"],["capability","capability boundary"],["boundary","boundary"],["begin","lifecycle"],["bridge","bridge"],["bridges","bridge"],["cache","state cache"],["chase","gameplay action"],["command","command boundary"],["context","context policy"],["cooldown","temporal state"],["cooldowns","temporal state"],["controller","controller"],["controllers","controller"],["diagnostic","diagnostics"],["diagnostics","diagnostics"],["effect","side-effect boundary"],["effects","side-effect boundary"],["energy","gameplay calculation"],["expired","temporal state"],["facade","facade"],["facades","facade"],["fire","gameplay action"],["gateway","gateway"],["gateways","gateway"],["guard","guard"],["guards","guard"],["haptic","haptic side-effect"],["haptics","haptic side-effect"],["head","sequence boundary"],["history","state history"],["input","input boundary"],["jump","gameplay action"],["keyboard","input boundary"],["log","side-effect boundary"],["logger","side-effect boundary"],["lock","coordination boundary"],["middleware","middleware"],["multiplier","gameplay calculation"],["mute","audio side-effect"],["normalize","normalization"],["normalise","normalization"],["normalizer","normalization"],["oscillate","animation calculation"],["oscillation","animation calculation"],["overlap","collision predicate"],["performance","diagnostics"],["permission","access policy"],["permissions","access policy"],["policy","policy"],["pool","state pool"],["pooled","state pool"],["pools","state pool"],["predict","prediction"],["presenter","presenter"],["presenters","presenter"],["projectile","gameplay entity"],["provider","provider boundary"],["providers","provider boundary"],["public","public surface"],["quality","settings/application"],["rate","calculation"],["register","registry"],["registry","registry"],["relay","relay"],["relays","relay"],["reseed","state lifecycle"],["reset","state lifecycle"],["respond","response boundary"],["response","response boundary"],["resolve","resolution"],["resolver","resolution"],["route","route boundary"],["routes","route boundary"],["run","lifecycle"],["sample","diagnostics"],["score","gameplay calculation"],["scope","scope policy"],["scroll","position state"],["scrolled","position state"],["seed","state lifecycle"],["seeded","state lifecycle"],["segment","segment boundary"],["segments","segment boundary"],["setting","settings/application"],["settings","settings/application"],["spawn","gameplay lifecycle"],["spawning","gameplay lifecycle"],["speed","gameplay calculation"],["surface","public surface"],["tail","sequence boundary"],["tick","temporal state"],["transaction","transaction"],["transactional","transaction"],["transform","transformation"],["transformer","transformation"],["translate","translation"],["translator","translation"],["try","fallible action"],["validate","validation"],["validation","validation"],["validator","validation"],["visual","diagnostics"],["window","settings/application"],["socket","transport boundary"],["websocket","transport boundary"]]),QK=new Set(["can","has","is","should"]),ZK=new Set(["access","api","auth","collision","expired","input","keyboard","overlap","permission","permissions","policy","projectile","response","route","routes","scope"]);function gs(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new H(e);return At({candidates:()=>sW(e,s,n,r),orderCandidates:Ka,scanLimit:o,profile:{name:"passthrough-candidates"},prepare:a=>s.calleeMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,c)=>eW(e,a,c.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:i})}function eW(e,t,n){let r=oW(n);if(r.size!==1||!df(e,t.relativePath,t.startLine,t.endLine))return null;let[,i]=[...r.entries()][0],o=tW(e,t,i),s=rW(e,t),a=o.length>0||s.length>0?"signal":"direct";return{symbol:t.symbol,shortName:T(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:ee(t),forwardsTo:i.symbol,forwardsToShort:T(i.symbol),forwardsToFile:i.file,actionTier:a,boundaryEvidence:o,publicFacadeEvidence:s,recommendation:nW(a,o,s)}}function tW(e,t,n){return qc(e,t.relativePath,t.startLine,"passthrough","explicit ignore-passthrough comment",[{label:"passthrough name",value:T(t.symbol)},{label:"callee name",value:T(n.symbol)},{label:"passthrough module",value:dE(t.relativePath,mE(t.relativePath))},{label:"callee module",value:dE(n.file,mE(n.file))}])}function nW(e,t,n){if(e==="signal"){if(n.length>0)return`Review the public API before inlining; public-facade evidence: ${n.slice(0,2).join("; ")}.`;let r=t.filter(iW);return r.length>0?`Review the public API before inlining; public-surface evidence: ${r.slice(0,2).join("; ")}.`:`Review the boundary before inlining; boundary evidence: ${t.slice(0,2).join("; ")}.`}return"Inline or remove this passthrough unless an external API or runtime registration depends on the forwarding name."}function rW(e,t){return pt(e,t)?xn(e,t.relativePath)?["exported passthrough is declared on the package public surface"]:Te(e,t.symbol,t.relativePath)?["exported passthrough matches configured or framework public entry surface"]:[]:[]}function iW(e){return e.includes("public surface")}function oW(e){let t=e.some(r=>Se(r.symbol))?e.filter(r=>Se(r.symbol)):e,n=new Map;for(let r of t)n.has(r.symbol)||n.set(r.symbol,r);return n}function sW(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:3,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0}).filter(i=>!_s(e,i))}var dW=new Set(Kt());function mW(e,t){return`tests/generated/twin-ab/${pE(e)}-vs-${pE(t)}.test.ts`}function pE(e){return(e.split(/[/#]/).pop()||e).replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"symbol"}function pW(e,t,n,r){let{refA:i,refB:o,outFile:s}=typeof t=="string"?{refA:t,refB:n,outFile:r}:t;if(typeof i!="string"||typeof o!="string"||typeof s!="string")throw new TypeError("twinAb requires refA, refB, and outFile.");if(!cW(s))throw new TypeError("twinAb outFile must be an absolute path.");let a=fE(e,i);if(!a.ok)return a;let c=fE(e,o);if(!c.ok)return c;let l=a.symbol.paramCount===null||c.symbol.paramCount===null?null:a.symbol.paramCount===c.symbol.paramCount,u=gW(a.symbol,c.symbol,e.config.projectRoot,s,l);return{ok:!0,a:a.symbol,b:c.symbol,signatureCompatible:l,testSource:u}}function fE(e,t){let r=Qe(e,t).match;if(!r)return{ok:!1,reason:`${t} does not resolve to an indexed symbol.`};let o=e.get("SELECT kind FROM global_symbols WHERE id = ?",r.symbolId)?.kind??null;if(!(o!==null?dW.has(o):Se(r.symbol)))return{ok:!1,reason:`${t} resolves to ${T(r.symbol)}${o!==null?` with SCIP kind ${ro(o)}`:""} \u2014 twin-ab compares call outputs, so both referents must be functions or methods.`};if(!pt(e,r))return{ok:!1,reason:`${t} (${T(r.symbol)} at ${r.relativePath}:${r.startLine+1}) is not exported \u2014 twin-ab needs an importable named binding for both twins.`};let a=e.get("SELECT documentation FROM global_symbols WHERE id = ?",r.symbolId),c=oi(si(a?.documentation??null));return{ok:!0,symbol:{ref:t,symbol:r.symbol,shortName:z(r.symbol)||T(r.symbol),file:r.relativePath,startLine:r.startLine,signature:c,paramCount:c?fW(c):null}}}function fW(e){let t=e.indexOf("(");if(t===-1)return null;let n=0,r=-1;for(let a=t;a<e.length;a+=1){let c=e[a];if(c==="(")n+=1;else if(c===")"&&(n-=1,n===0)){r=a;break}}if(r===-1)return null;let i=e.slice(t+1,r).trim();if(!i)return 0;let o=1,s=0;for(let a of i)a==="("||a==="["||a==="{"?s+=1:a===")"||a==="]"||a==="}"?s=Math.max(0,s-1):a===","&&s===0&&(o+=1);return o}function gE(e,t,n){let r=aW(t),i=uW(e,n),s=lW(r,i).replace(/\\/g,"/").replace(/\.tsx?$/,".js");return s.startsWith(".")?s:`./${s}`}function gW(e,t,n,r,i){let o=gE(n,r,e.file),s=gE(n,r,t.file),a=i===null?"Signature comparison: unknown (one or both signatures unavailable in the index) \u2014 check by hand.":i?"Signature comparison: param counts match.":"Signature comparison: param counts DIFFER \u2014 twins may not be directly comparable; check by hand.";return`/**
378
- * Generated by 'scip-query twin-ab'. Cleanup integrity scenario.
379
- * ("cross-examine same-concept twins"): where one concept is computed in
380
- * more than one place, feed both the same input and require the same
381
- * answer. Disagreement between twins means at least one is wrong \u2014
382
- * determine which before consolidating.
383
- *
384
- * Twin A: ${e.shortName} (${e.file}:${e.startLine+1})
385
- * ${e.signature??"(signature unavailable)"}
386
- * Twin B: ${t.shortName} (${t.file}:${t.startLine+1})
387
- * ${t.signature??"(signature unavailable)"}
388
- * ${a}
389
- *
390
- * Fill in the TODO input table below with inputs both twins should agree
391
- * on, then run this file with vitest.
392
- */
393
- import { describe, expect, it } from 'vitest';
394
- import { ${e.shortName} as twinA } from '${o}';
395
- import { ${t.shortName} as twinB } from '${s}';
396
-
397
- // TODO: fill in shared inputs both twins should agree on \u2014 one arg array per call.
398
- const inputs: any[][] = [
399
- // [/* arg1, arg2, ... */],
400
- ];
401
-
402
- // Cast to a variadic signature so the input table can hold any arg shape \u2014
403
- // the real twins have fixed, non-rest parameter lists, and TS rejects
404
- // spreading a generic args array into those (TS2556) even when the array
405
- // itself is 'any'; casting the callee's signature, not the args, satisfies
406
- // the checker without weakening the twins' real exported types elsewhere.
407
- const callA = twinA as (...callArgs: any[]) => any;
408
- const callB = twinB as (...callArgs: any[]) => any;
409
-
410
- describe.skipIf(inputs.length === 0)('twin-ab: ${e.shortName} vs ${t.shortName}', () => {
411
- it.each(inputs)('agrees on input %#', (...args) => {
412
- expect(callA(...args)).toEqual(callB(...args));
413
- });
414
- });
415
- `}var hE={caller:3,"entry-surface":2,rooted:1},hW=/not\s*yet\s*implement|not\s*implement|unimplement|\bnyi\b|\btodo\b|\bstub\b|not\s*supported|coming\s*soon/i,yW=/^throw\s+new\s+[\w.]*Error\s*\(([\s\S]*)\)\s*;?$/,bW=/^return(\s+(null|undefined|false|0|''|""|``|\[\]|\{\}))?\s*;?$/,SW=/\/\/\s*TODO\b|\/\*\s*TODO\b/i,vW=/(?:=>|\))\s*(?::\s*[^{;=]+)?\s*\{\s*\}\s*;?\s*$/;function CW(e,t={}){let{scope:n,limit:r=30,scanLimit:i,semantic:o=!0}=t,s=new H(e),a=he(s.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),c=[];for(let p of a){let f=RW(e,p);f&&c.push(f)}if(c.length===0)return[];let l=LW(e,c,a),u=c.filter(p=>!l.has(p.def.symbol));if(u.length===0)return[];let d=Mn(e,s).forDefinitions(u.map(p=>p.def),{semantic:o}),m=[];for(let p of u){let g=d.get(p.def.symbolId)?.realConsumers.length??0,h=xW(e,p.def,g);h&&m.push({symbol:p.def.symbol,shortName:T(p.def.symbol),file:p.def.relativePath,startLine:p.def.startLine,endLine:p.def.endLine,loc:ee(p.def),stubKind:p.stubKind,reachability:h,callerFanIn:g,stubText:p.stubText})}return m.sort((p,f)=>hE[f.reachability]-hE[p.reachability]||f.callerFanIn-p.callerFanIn||p.file.localeCompare(f.file)||p.startLine-f.startLine),r?m.slice(0,r):m}function xW(e,t,n){return n>0?"caller":Te(e,t.symbol,t.relativePath)?"rooted":Ue(e,t.relativePath)?"entry-surface":null}function RW(e,t){let n=Ht(e,t);if(!n)return null;let r=an(n),i=r.trim();if(i==="")return!wW(n)||!pt(e,t)?null:{def:t,stubKind:"empty-body",stubText:"(empty body)"};let o=Xi(r),s=pn(r),a=EW(o,s);if(a.length!==1)return null;let c=a[0];return IW(c)?{def:t,stubKind:"throw-stub",stubText:c.trim()}:SW.test(r)&&bW.test(c.trim())?{def:t,stubKind:"todo-return-default",stubText:i}:null}function EW(e,t){let n=[],r=0,i="";for(let o=0;o<t.length;o+=1){let s=t[o];if(s==="("||s==="["||s==="{"?r+=1:(s===")"||s==="]"||s==="}")&&(r=Math.max(0,r-1)),s===";"&&r===0){n.push(i),i="";continue}i+=e[o]??""}return i.trim()&&n.push(i),n.map(o=>o.trim()).filter(o=>o.length>0)}function IW(e){let t=yW.exec(e.trim());return t?hW.test(t[1]??""):!1}function wW(e){return vW.test(e.trimEnd())}function LW(e,t,n){let r=new Set,i=new Set(t.map(a=>a.def.parentTypeName).filter(a=>a!==null));if(i.size===0)return r;let o=DW(e,i),s=new Map;for(let a of n){if(!a.parentTypeName)continue;let c=s.get(a.leaf)??new Set;c.add(a.parentTypeName),s.set(a.leaf,c)}for(let a of t){let c=a.def.parentTypeName;if(!c)continue;let l=o.get(c);if(!l||l.size===0)continue;let u=s.get(a.def.leaf)??new Set;[...l].every(m=>u.has(m))&&r.add(a.def.symbol)}return r}var PW=/\bclass\s+([A-Za-z_$][\w$]*)\s+extends\s+([A-Za-z_$][\w$]*)/g;function DW(e,t){let n=new Map;for(let r of Z(e,{includeIgnored:!1})){let i=W(e,r);if(i)for(let o of i.matchAll(PW)){let s=o[1],a=o[2];if(!s||!a||!t.has(a))continue;let c=n.get(a)??new Set;c.add(s),n.set(a,c)}}return n}var MW=/^(?:validate|verify|check|assert)(?:[A-Z].*)?$/,TW=/^(?:is|has)(?:[A-Z].*)?$/,kW=/[{,]\s*(?:ok|success|valid|isValid)\s*:\s*false\b/,Gm=/\breturn\b/g,AW=/\bfunction\b|=>|\)\s*(?::\s*[^{;=]+)?\s*\{/,FW=/\.(?:addIssue|push)\s*\(/;function NW(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new H(e),s=he(o.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),a=[];for(let c of s){let l=OW(e,c);l&&a.push({symbol:c.symbol,shortName:T(c.symbol),file:c.relativePath,startLine:c.startLine,endLine:c.endLine,loc:ee(c),...l})}return a.sort((c,l)=>c.file.localeCompare(l.file)||c.startLine-l.startLine||c.loc-l.loc),r?a.slice(0,r):a}function _W(e){return MW.test(e)?"imperative":TW.test(e)?"predicate":null}function OW(e,t){let n=_W(t.leaf);if(!n||_i(e,t))return null;let r=Ht(e,t);if(!r||!AW.test(r))return null;let i=K(e,t.relativePath)?.callables.find(s=>s.startLine===t.startLine&&s.endLine===t.endLine);if(n==="predicate"&&i?.paramCount===0)return null;if(aE(r)){let s=jW(e,t);return!s||SE(s.body,bE(s.snippet))||yE(s.body)?null:{nameKind:n,resolvedVia:"one-hop-delegate",delegateTarget:s.shortName}}let o=an(r);return SE(o,bE(r))||yE(o)?null:{nameKind:n,resolvedVia:"direct"}}var BW=new Set(["if","for","while","switch","catch","function"]);function yE(e){let t=Xi(e);for(let n of t.matchAll(/\b([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(/g))if(!BW.has(n[1]))return!0;return!1}function bE(e){let t=e.indexOf("=>");return t===-1?!1:!/^\s*\{/.test(e.slice(t+2))}function SE(e,t){let n=Xi(e);if(/\bthrow\b/.test(n)||/\.reject\s*\(/.test(n)||kW.test(n)||FW.test(n))return!0;let r=$W(n);if(t&&r.length===0){let i=n.trim();return i!==""&&i!=="true"}for(let i of r)if(i!==""&&i!=="true")return!0;return!1}function $W(e){let t=[];Gm.lastIndex=0;let n;for(;n=Gm.exec(e);){let r=n.index+n[0].length,i=0,o=e.length;for(let s=r;s<e.length;s+=1){let a=e[s];if(a==="("||a==="["||a==="{")i+=1;else if(a===")"||a==="]"||a==="}"){if(i===0){o=s;break}i-=1}else if(a===";"&&i===0){o=s;break}}t.push(e.slice(r,o).trim()),Gm.lastIndex=o}return t}function jW(e,t){let n=Pt(e,t,{callableOnly:!0,limit:3,semanticEvidence:re}),r=[...new Set(n.map(c=>c.symbol))].filter(c=>c!==t.symbol);if(r.length!==1)return null;let o=Qe(e,r[0]).match;if(!o)return null;let s=U(e,o.relativePath).find(c=>c.symbolId===o.symbolId);if(!s)return null;let a=Ht(e,s);return a?{body:an(a),snippet:a,shortName:T(s.symbol)}:null}var HW=60;function UW(e,t={}){let{scope:n,limit:r=30,scanLimit:i,rotDays:o=HW}=t,s=he(ti(e,{extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs"]}).filter(u=>q(u)==="test").filter(u=>!n||u.includes(n)).filter(u=>!e.isIgnored(u)).sort(),i),a=[],c=[],l=[];for(let u of s){let d=W(e,u);if(!d)continue;let m=cf(d),p=zW(d);for(let g of YW(m,p))p.add(g);let f=qW(m);for(let g of f){if(g.skip){c.push(nV(e,u,g,o));continue}if(g.kind==="describe")continue;let h=CE(d,g.argsStart),b=m.slice(g.argsStart,g.callEnd),S=d.slice(g.argsStart,g.callEnd);xE(b,p)||a.push({file:u,startLine:hs(d,g.callStart),endLine:hs(d,g.callEnd),title:h,severity:/\bawait\b/.test(b)?"low":"high"});let y=ZW(b,S);y&&l.push({file:u,startLine:hs(d,g.callStart),endLine:hs(d,g.callEnd),title:h,echoedValue:y})}}return{assertionFree:r?a.slice(0,r):a,skipped:r?c.slice(0,r):c,mockEcho:r?l.slice(0,r):l}}var zm=/(?<!\.)\b(?:x(it|test|describe)|(it|test|describe)(?:\.\s*(skip|only|todo|each\s*\([^)]*\)))?)\s*\(/g;function qW(e){let t=[];zm.lastIndex=0;let n;for(;n=zm.exec(e);){let r=n[1],i=r??n[2];if(!i)continue;let o=n[3]?.split(/\s*\(/)[0],s=n.index,a=n.index+n[0].length-1,c=ys(e,a);zm.lastIndex=a+1,o!=="each"&&t.push({kind:i,skip:r!==void 0||o==="skip"||o==="todo",skipKind:o==="todo"?"todo":"skip",callStart:s,argsStart:a+1,callEnd:c+1})}return t}function ys(e,t){let n=0;for(let r=t;r<e.length;r+=1){let i=e[r];if(i==="(")n+=1;else if(i===")"&&(n-=1,n===0))return r}return e.length-1}function hs(e,t){let n=0;for(let r=0;r<t&&r<e.length;r+=1)e[r]===`
416
- `&&(n+=1);return n}function CE(e,t){let n=e.slice(t,t+400),r=/^\s*(['"`])((?:\\.|(?!\1)[\s\S])*)\1/.exec(n);return r?r[2]:"(anonymous)"}var GW=new Set(["vitest","chai","jest","@jest/globals","assert","node:assert","node:assert/strict","assert/strict","uvu/assert","expect","chai-as-promised"]),vE=/import\s+(?:\*\s+as\s+(\w+)|\{([^}]*)\}|(\w+))\s+from\s+['"]([^'"]+)['"]/g;function zW(e){let t=new Set(["expect","assert"]);vE.lastIndex=0;let n;for(;n=vE.exec(e);){let[,r,i,o,s]=n;if(!(!s||!GW.has(s))&&(r&&t.add(r),o&&t.add(o),i))for(let a of i.split(",")){let c=a.trim().replace(/^type\s+/,"");if(!c)continue;let l=/^(\w+)\s+as\s+(\w+)$/.exec(c);t.add(l?l[2]:c)}}return t}function xE(e,t){if(/\.should\b/.test(e)||/\bawait\s+(?:[\w$.]+\.)?findBy[A-Z]\w*\s*\(/.test(e)||/\bawait\s+\w*waitFor(?:Text|Value|Condition|Result|Event)\s*\(/.test(e)||/\bthrow\b/.test(e))return!0;for(let n of t){let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`\\b${r}\\s*(?:<[^<>]*>)?\\s*[.(]`).test(e))return!0}return!1}var KW=/\bfunction\s+(\w+)\s*\(/g,WW=/\b(?:const|let)\s+(\w+)\s*=\s*(?:async\s*)?\(/g,VW=60;function YW(e,t){let n=new Set;for(let r of[KW,WW]){r.lastIndex=0;let i;for(;i=r.exec(e);){let o=i[1],s=i.index+i[0].length-1,a=ys(e,s),c=e.indexOf("{",a+1);if(c===-1||c-a>VW)continue;let l=JW(e,c),u=e.slice(c+1,l);xE(u,t)&&n.add(o)}}return n}function JW(e,t){let n=0;for(let r=t;r<e.length;r+=1){let i=e[r];if(i==="{")n+=1;else if(i==="}"&&(n-=1,n===0))return r}return e.length-1}var XW=/\bmock(?:ReturnValue|ResolvedValue)(?:Once)?\s*\(/g,Km=/\bexpect\s*\(/g,QW=/^\s*\.\s*(?:toBe|toEqual|toStrictEqual)\s*\(/,RE=/^(?:-?\d+(?:\.\d+)?|(['"`]).+\1)$/;function ZW(e,t){let n=eV(e,t,XW);if(n.length===0)return null;let r=tV(e,t);for(let i of r)if(n.includes(i))return i;return null}function eV(e,t,n){let r=[];n.lastIndex=0;let i;for(;i=n.exec(e);){let o=i.index+i[0].length-1,s=ys(e,o),a=t.slice(o+1,s).trim();RE.test(a)&&r.push(a),n.lastIndex=s+1}return r}function tV(e,t){let n=[];Km.lastIndex=0;let r;for(;r=Km.exec(e);){let i=r.index+r[0].length-1,o=ys(e,i),s=e.slice(o+1),a=QW.exec(s);if(Km.lastIndex=o+1,!a)continue;let c=o+1+a[0].length-1,l=ys(e,c),u=t.slice(c+1,l).trim();RE.test(u)&&n.push(u)}return n}function nV(e,t,n,r){let i=W(e,t),o=CE(i,n.argsStart),s=hs(i,n.callStart),a=rV(e.config.projectRoot,t,s),c=a===null?"unknown":a>=r?"rot":"workflow";return{file:t,startLine:s,title:o,skipKind:n.skipKind,blockKind:n.kind,ageDays:a,rot:c}}function rV(e,t,n){let r=n+1;try{let i=sn(e,["blame","-L",`${r},${r}`,"--porcelain","--",t]),o=/^author-time (\d+)$/m.exec(i);if(!o)return null;let s=Number(o[1]);return Number.isFinite(s)?Math.max(0,Math.round((Date.now()/1e3-s)/86400)):null}catch{return null}}var iV=.7,EE=.62,IE=.45;function oV(e,t={}){let{windowCommits:n=100,limit:r=30,scope:i,scanLimit:o}=t,s=jt(e,{historyMode:t.historyMode}).fileAddRecords();if(!s)return{available:!1,windowCommits:n,findings:[]};if(r<=0)return{available:!0,windowCommits:n,findings:[]};let a=fV(s,n);if(a.size===0)return{available:!0,windowCommits:n,findings:[]};let l=sV(e,{limit:r,minSimilarity:t.minSimilarity,scanLimit:o,scope:i,semantic:t.semantic,focusFiles:Number.isFinite(r)?void 0:a}).map(d=>gV(d,s,n)).filter(d=>d!==null);l.sort((d,m)=>(d.kind===m.kind?0:d.kind==="echo"?-1:1)||m.similarity-d.similarity||d.echoFile.localeCompare(m.echoFile)||d.echoSymbol.localeCompare(m.echoSymbol)||d.domain.localeCompare(m.domain));let u=l.slice(0,r).map(hV);return{available:!0,windowCommits:n,findings:u,rootCauseGroups:yV(u)}}function sV(e,t){let n=SV(t.limit),r=[...aV(e,{scope:t.scope,minSimilarity:t.minSimilarity??iV,limit:n,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles})],i=Os(e,{scope:t.scope});return i.react&&r.push(...cV(e,{scope:t.scope,minSimilarity:t.minSimilarity??EE,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...lV(e,{scope:t.scope,minSimilarity:t.minSimilarity??IE,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),i.vue&&r.push(...mV(e,{scope:t.scope,minSimilarity:t.minSimilarity??EE,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...pV(e,{scope:t.scope,minSimilarity:t.minSimilarity??IE,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),r}function aV(e,t){return os(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles}).filter(n=>!je(n.symbolA)&&!je(n.symbolB)).map(n=>({domain:"callable",basis:n.similarityBasis??"callees",symbolA:n.shortNameA,fileA:n.fileA,symbolB:n.shortNameB,fileB:n.fileB,similarity:n.similarity,sharedEvidence:n.sharedCallees,sharedCallees:n.sharedCallees}))}function cV(e,t){return zc(e,t,{query:ss,domain:"react-component",basis:"jsx-structure",symbolA:n=>n.componentA,symbolB:n=>n.componentB,evidenceBuckets:n=>[["component",n.sharedComponents],["tag",n.sharedNativeTags],["prop",n.sharedProps],["event",n.sharedEvents],["binding",n.sharedBindings]]})}function zc(e,t,n){return n.query(e,t).filter(r=>r.fileA!==r.fileB).filter(r=>n.acceptPair?.(r)??!0).map(r=>({domain:n.domain,basis:n.basis,symbolA:n.symbolA(r),fileA:r.fileA,symbolB:n.symbolB(r),fileB:r.fileB,similarity:r.similarity,sharedEvidence:vV(...n.evidenceBuckets(r)),sharedCallees:[]}))}function lV(e,t){return zc(e,t,{query:as,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,acceptPair:dV,evidenceBuckets:n=>[["hook",n.sharedHooks],["react-hook",n.sharedReactHooks],["effect",n.sharedEffects],["state",n.sharedState],["request",n.sharedRequests],["handler",n.sharedHandlers],["action",n.sharedHandlerVerbs]]})}var uV=new Set(["useCallback","useEffect","useLayoutEffect","useMemo","useMutation","useQueries","useQuery","useQueryClient","useReducer","useRef","useState"]);function dV(e){return e.sharedHooks.some(t=>!uV.has(t))||e.sharedState.length>0||e.sharedHandlers.length>0||e.sharedHandlerVerbs.length>=2}function mV(e,t){return zc(e,t,{query:cs,domain:"vue-component",basis:"vue-template",symbolA:n=>Gc(n.fileA),symbolB:n=>Gc(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function pV(e,t){return zc(e,t,{query:ls,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>Gc(n.fileA),symbolB:n=>Gc(n.fileB),evidenceBuckets:n=>[["composable",n.sharedComposables],["store",n.sharedStores],["reactivity",n.sharedReactivity],["lifecycle",n.sharedLifecycle],["request",n.sharedRequests],["function",n.sharedFunctions],["action",n.sharedFunctionVerbs],["binding",n.sharedBindings],["template-event",n.sharedTemplateEvents]]})}function fV(e,t){let n=new Set;for(let[r,i]of e)i.commitsAgo<=t&&n.add(r);return n}function gV(e,t,n){let r=t.get(e.fileA)?.commitsAgo??null,i=t.get(e.fileB)?.commitsAgo??null,o=r!==null&&r<=n,s=i!==null&&i<=n;if(!o&&!s)return null;if(o&&s){let a=(r??0)<=(i??0);return{kind:"twin",domain:e.domain,basis:e.basis,echoSymbol:a?e.symbolA:e.symbolB,echoFile:a?e.fileA:e.fileB,echoAgeCommits:(a?r:i)??0,establishedSymbol:a?e.symbolB:e.symbolA,establishedFile:a?e.fileB:e.fileA,establishedAgeCommits:a?i:r,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}return{kind:"echo",domain:e.domain,basis:e.basis,echoSymbol:o?e.symbolA:e.symbolB,echoFile:o?e.fileA:e.fileB,echoAgeCommits:(o?r:i)??0,establishedSymbol:o?e.symbolB:e.symbolA,establishedFile:o?e.fileB:e.fileA,establishedAgeCommits:o?i:r,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}function hV(e){let t=wE(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function wE(e){if(e.kind==="echo")return["echo",e.domain,e.basis,e.establishedSymbol].join(":");let t=e.sharedEvidence.slice().sort().join("|"),n=[e.echoSymbol,e.establishedSymbol].sort().join("|");return["twin",e.domain,e.basis,t||n].join(":")}function yV(e){let t=new Map;for(let[n,r]of e.entries()){let i=r.rootCauseKey??wE(r),o=r.groupKey??`recent-duplicate:${i}`,s=t.get(o);s||(s={groupKey:o,rootCauseKey:i,kind:r.kind,domain:r.domain,basis:r.basis,count:0,maxSimilarity:r.similarity,findingIndexes:[],echoFiles:new Set,establishedFile:r.kind==="echo"?r.establishedFile:void 0,establishedSymbol:r.kind==="echo"?r.establishedSymbol:void 0,relatedFiles:new Set,sharedEvidence:new Set,recommendation:bV(r)},t.set(o,s)),s.count+=1,s.maxSimilarity=Math.max(s.maxSimilarity,r.similarity),s.findingIndexes.push(n),s.echoFiles.add(r.echoFile),s.relatedFiles.add(r.echoFile),s.relatedFiles.add(r.establishedFile);for(let a of r.sharedEvidence)s.sharedEvidence.add(a)}return[...t.values()].map(n=>({...n,echoFiles:[...n.echoFiles].sort(),relatedFiles:[...n.relatedFiles].sort(),sharedEvidence:[...n.sharedEvidence].sort().slice(0,16)})).sort((n,r)=>r.count-n.count||r.maxSimilarity-n.maxSimilarity||n.groupKey.localeCompare(r.groupKey))}function bV(e){return e.kind==="echo"?"Review the established side once, then migrate or delete every echo in this group.":"Pick one owner for the new twins and consolidate the group before the copies diverge."}function SV(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function vV(...e){let t=[],n=new Set;for(let[r,i]of e)for(let o of i){let s=`${r}:${o}`;n.has(s)||(n.add(s),t.push(s))}return t}function Gc(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var CV=ge("suppression-inventory",{clearGroups:["whole-project"]});function Kc(e){return CV.get(e,()=>xV(e))}function xV(e){let t={dead:0,stale:0,wrapper:0,passthrough:0,drift:0,extract:0,similar:0,twin:0,uncategorized:0},n=new Map,r=0;for(let i of ti(e)){let o=W(e,i);if(!(!o||!o.includes("scip-query")))for(let s of o.split(/\r?\n/)){let a=ks(s);if(a===null)continue;r+=1,n.set(i,(n.get(i)??0)+1);let c=LE(a);t[c]+=1}}for(let i of e.config.suppressions??[])i.expiresAt&&Date.parse(i.expiresAt)<=Date.now()||(r+=1,i.file&&n.set(i.file,(n.get(i.file)??0)+1),t[LE(i.check)]+=1);return{total:r,byCategory:t,byFile:n}}function LE(e){if(!e)return"uncategorized";let t=e.toLowerCase();return t==="dead-code"||t==="new-dead"?"dead":t.includes("twin")?"twin":t.includes("similar")||t.includes("duplicate")?"similar":t.includes("wrapper")?"wrapper":t.includes("passthrough")?"passthrough":t.includes("drift")?"drift":t.includes("extract")?"extract":t.includes("stale")?"stale":"uncategorized"}function Wm(e,t,n={}){let r=ne(e,t);if(!r)return null;let i=new H(e),o=RV(e,r),s=r.endLine-r.startLine+1,c=i.calleeMap([r],{additive:!0,semantic:n.semantic}).get(r.symbolId)??[],l=new Set(c.map(u=>u.symbol));return{symbol:r.symbol,shortName:T(r.symbol),relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,loc:s,branches:o.branches,estimateBasis:o.estimateBasis,cyclomaticEstimate:o.branches+1,calleeCount:l.size,fanIn:IV(e,r.symbolId),fanOut:wV(c,r.relativePath)}}function RV(e,t){let n=J(e,t.relativePath);if(n){let r=br(n.rootNode,t.startLine,t.endLine);if(r)return{branches:LV(r),estimateBasis:"ast"}}return{branches:kE(ME(e,t.relativePath,t.startLine,t.endLine),DE(e,t.relativePath)),estimateBasis:"regex-fallback"}}function PE(e,t){let n=new Map,r=new Map;for(let i of t){let o=r.get(i.relativePath)??[];o.push(i),r.set(i.relativePath,o)}for(let[i,o]of r){let s=J(e,i),a=s===null?[]:o.filter(l=>s.rootNode.startPosition.row<=l.startLine&&s.rootNode.endPosition.row>=l.endLine),c=new Set(a.map(l=>l.symbolId));if(s&&a.length>0){for(let l of a)n.set(l.symbolId,{branches:0,estimateBasis:"ast"});PV(s.rootNode,a,n)}for(let l of o)c.has(l.symbolId)||n.set(l.symbolId,EV(e,l))}return n}function EV(e,t){return{branches:kE(ME(e,t.relativePath,t.startLine,t.endLine),DE(e,t.relativePath)),estimateBasis:"regex-fallback"}}function DE(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function ME(e,t,n,r){try{return Ye(e.config.projectRoot,t,{inputKind:"indexed source file"}).split(`
417
- `).slice(n,r+1).join(`
418
- `)}catch(i){if(!Je(i))throw i;return""}}function IV(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
419
- FROM mentions m
420
- JOIN chunks c ON m.chunk_id = c.id
421
- JOIN (
422
- SELECT m2.symbol_id, c2.document_id
423
- FROM mentions m2
424
- JOIN chunks c2 ON m2.chunk_id = c2.id
425
- WHERE m2.role = 1
426
- GROUP BY m2.symbol_id
427
- ) sym_def ON sym_def.symbol_id = m.symbol_id
428
- WHERE m.symbol_id = ?
429
- AND m.role != 1
430
- AND sym_def.document_id != c.document_id`,t)?.c??0}function wV(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function LV(e){let t=0;return vl(e,n=>{t+=TE(n)}),t}function PV(e,t,n){let r=[...t].sort((i,o)=>i.startLine-o.startLine||o.endLine-i.endLine);vl(e,i=>{let o=TE(i);if(o===0)return;let s=i.startPosition.row,a=i.endPosition.row;for(let c of r){if(c.startLine>s)break;if(c.endLine<a)continue;let l=n.get(c.symbolId);l&&(l.branches+=o)}})}var DV=new Set(["if_statement","conditional_expression","ternary_expression","for_statement","for_in_statement","for_of_statement","while_statement","do_statement","switch_case","case_statement","catch_clause","except_clause","elif_clause","match_arm"]);function TE(e){return DV.has(e.type)?1:e.type==="binary_expression"&&e.parent?.type!=="binary_expression"&&(e.text.includes("&&")||e.text.includes("||"))?MV(e.text):0}function MV(e){return(e.match(/&&|\|\|/g)??[]).length}function kE(e,t){let n=pn(e),r=0,i=[/\bif\b/g,/\belse\s+if\b/g,/\belse\b/g,/\bfor\b/g,/\bwhile\b/g,/\bswitch\b/g,/\bcase\b/g,/\bcatch\b/g,/\?\s*[^?]/g,/&&/g,/\|\|/g];for(let o of i){let s=n.match(o);s&&(r+=s.length)}if(t==="python"){let o=[/\belif\b/g,/\bexcept\b/g,/\bfinally\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="rust"){let o=[/\bmatch\b/g,/=>/g,/\bloop\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="ruby"){let o=[/\belsif\b/g,/\bunless\b/g,/\brescue\b/g,/\bwhen\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="go"){let o=[/\bselect\b/g,/\bdefer\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}return r}function AE(e,t,n={}){let r=ne(e,t);if(!r)return null;let i=[{file:r.relativePath,line:r.startLine}],o=jn(e,r,{semantic:n.semantic,semanticEvidence:re}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?T(c.enclosingSymbol):"(top-level)"})),{outgoingCalls:s,incomingCalls:a}=TV(e,r,o,{semantic:n.semantic!==!1});return{symbol:r.symbol,shortName:T(r.symbol),relativePath:r.relativePath,definitionSites:i.filter(c=>!e.isIgnored(c.file)),referenceSites:o,outgoingCalls:s.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:T(c.symbol),file:c.file})),incomingCalls:a.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:c.symbol===c.file?"(top-level)":T(c.symbol),file:c.file}))}}function Vm(e,t,n={}){let r=AE(e,t,n);return r?{symbol:r.symbol,shortName:r.shortName,relativePath:r.relativePath,definitionSites:r.definitionSites,usageSites:r.referenceSites,producers:r.outgoingCalls,consumers:r.incomingCalls}:null}function TV(e,t,n,r){let i=wi(Pt(e,t,{limit:30,semantic:r.semantic,semanticEvidence:re}).map(a=>({symbol:a.symbol,file:a.file}))),o=wi(Gn(e,t,{limit:30,semantic:r.semantic,semanticEvidence:re})),s=o.length>0?o:wi(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{outgoingCalls:i,incomingCalls:s}}function FE(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,o=ne(e,t);return o?r==="backward"?kV(e,o,i,{semantic:n.semantic!==!1}):AV(e,o,{semantic:n.semantic!==!1}):null}function Wc(e,t,n={}){return FE(e,t,n)}function kV(e,t,n,r){let i=[],o=new Set([t.symbol]),s=[t];for(let a=1;a<=n&&s.length!==0;a++){let c=[];for(let l of s){let u=Pt(e,l,{semantic:r.semantic,semanticEvidence:re});for(let d of u){if(o.has(d.symbol))continue;o.add(d.symbol),i.push({symbol:d.symbol,shortName:T(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let m=Sr(e,d.symbol);m&&!e.isIgnored(m.relativePath)&&c.push(m)}}s=c}return{symbol:t.symbol,shortName:T(t.symbol),direction:"backward",connectedSymbols:i}}function AV(e,t,n){let r=new Set,i=[],o=new H(e);for(let s of jn(e,t,{semantic:n.semantic,semanticEvidence:re})){if(i.length>=30)break;let a=s.enclosingSymbol??Ne(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=Sr(e,a);!c||e.isIgnored(c.relativePath)||r.has(c.symbol)||(r.add(c.symbol),i.push({symbol:c.symbol,shortName:T(c.symbol),file:c.relativePath,relationship:`references target at ${s.file}:${s.line+1}`}))}return i.sort((s,a)=>s.file.localeCompare(a.file)),{symbol:t.symbol,shortName:T(t.symbol),direction:"forward",connectedSymbols:i}}function NE(e){let t=new Set(e.filter(n=>n.definition?.isFunctionLike).map(n=>`${n.role}:${n.definition.relativePath}`));return e.flatMap(n=>n.definition?!n.definition.isFunctionLike&&t.has(`${n.role}:${n.definition.relativePath}`)?[]:[{definition:n.definition,role:n.role}]:[])}var HE=6,Yc=10,Jm=3,Xm=8,FV=.7,_E=24,Ym=200,UE=12,OE=80,BE=600;function NV(e,t,n={}){let r=n.impactDepth??3,i=n.sliceDepth??3,o=n.semantic,s=KV(t)?BV(e,t):null,a=s?s.primary?.symbol??null:t,{traceResult:c,callGraphResult:l,complexityResult:u,dataflowResult:d,backwardSliceResult:m,forwardSliceResult:p,affectedResults:f,reuseCandidates:g,targetSymbol:h,affectedConsumerReuse:b}=_V(e,a,n,r,i),S=Oe("change-surface",t,()=>Cm(e,t,{semantic:o}),D=>({symbols:D?.symbols.length??0,externalConsumers:D?.totalExternalConsumers??0})),y=Oe("system",t,()=>Jd(e,t),D=>({files:D.files.length,symbols:D.symbols.length})),x=y.files.length===1,v=Oe("deps",t,()=>x?y.dependsOn.map(D=>({relativePath:D,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):$o(e,t),D=>({files:D.length,reusedSystem:x})),C=Oe("rdeps",t,()=>x?y.dependedOnBy.map(D=>({relativePath:D,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):jo(e,t),D=>({files:D.length,reusedSystem:x})),R=Oe("surface",t,()=>Xd(e,t),D=>({consumers:D.length})),E={symbol:c.definitions.length>0||c.referencedBy.length>0||l!==null||u!==null||d!==null||m!==null||p!==null||f.length>0,file:S!==null||v.length>0||C.length>0,module:y.files.length>0||y.symbols.length>0||R.length>0},w=[];s&&!s.primary&&s.callableCount>1&&w.push(`File target has ${s.callableCount} callable symbols; use one callable name for compiler-resolved flow.`);let I=[...new Set(c.referencedBy.map(D=>D.relativePath))];I.length>0&&I.every(D=>q(D)==="test")&&w.push("Only test references were found for this target. For replacement or retirement work, map the currently wired owner or one production entry point before planning; this target does not describe the live affected surface."),!E.symbol&&!E.file&&!E.module&&w.push("No symbol, file, or module matched target.");let k=S?.file??c.definitions[0]?.relativePath??null;return{target:t,...s?.primary?{primaryCallable:{symbol:s.primary.symbol,shortName:z(s.primary.symbol),file:s.primary.relativePath}}:{},matched:E,history:Oe("history",k??t,()=>zV(e,k,n.gitHead)),trace:OV(c),callGraph:l,complexity:u,dataflow:d,backwardSlice:m,forwardSlice:p,affected:f,changeSurface:S,deps:v,rdeps:C,system:y,surface:R,reuseCandidates:g,affectedConsumerReuse:b,sourcePacket:$V(e,h,c,b,g),warnings:w}}function _V(e,t,n,r,i){let o=n.semantic,s=t?Oe("trace",t,()=>vd(e,t,{semantic:o,referenceContext:UE}),h=>({definitions:h.definitions.length,references:h.referencedBy.length})):{definitions:[],referencedBy:[],claimSupport:null},a=t?Oe("call-graph",t,()=>Bo(e,t,{semantic:o}),h=>({callers:h?.callers.length??0,callees:h?.callees.length??0})):null,c=t?Oe("complexity",t,()=>Wm(e,t,{semantic:o}),h=>({callees:h?.calleeCount??0})):null,l=t?Oe("dataflow",t,()=>Vm(e,t,{semantic:o}),h=>({references:h?.usageSites.length??0,producers:h?.producers.length??0,consumers:h?.consumers.length??0})):null,u=t?Oe("backward-slice",t,()=>Wc(e,t,{direction:"backward",maxDepth:i,semantic:o}),h=>({maxDepth:i,connectedSymbols:h?.connectedSymbols.length??0})):null,d=t?Oe("forward-slice",t,()=>Wc(e,t,{direction:"forward",maxDepth:i,semantic:o}),h=>({maxDepth:i,connectedSymbols:h?.connectedSymbols.length??0})):null,m=t?Oe("affected",t,()=>vm(e,t,{maxDepth:r,scope:n.scope}),h=>({maxDepth:r,affectedSymbols:h.length})):[],p=t?Oe("reuse-candidates",t,()=>is(e,t,{minSimilarity:.4,limit:5,semantic:o,sourceCandidateMode:"target-pruned"}),h=>({candidates:h.length,direct:h.filter(b=>b.actionTier==="direct").length})):[],f=t?ne(e,t)?.symbol??null:null,g=t?Oe("affected-consumer-reuse",t,()=>jV(s,f,h=>is(e,h,{minSimilarity:.4,limit:Yc,semantic:o,sourceCandidateMode:"target-pruned"}),{consumerLimit:HE,perConsumerSearchLimit:Yc,perConsumerCandidateLimit:Jm,candidateLimit:Xm}),h=>({totalConsumers:h.coverage.totalConsumers,analyzedConsumers:h.coverage.analyzedConsumers,candidates:h.candidates.length})):GV();return{traceResult:s,callGraphResult:a,complexityResult:c,dataflowResult:l,backwardSliceResult:u,forwardSliceResult:d,affectedResults:m,reuseCandidates:p,targetSymbol:f,affectedConsumerReuse:g}}function OV(e){return{definitions:e.definitions,referencedBy:e.referencedBy.map(t=>({relativePath:t.relativePath,line:t.line,enclosingSymbol:t.enclosingSymbol,enclosingShort:t.enclosingShort}))}}function BV(e,t){let n=Rr(e,t);if(n.length!==1)return{primary:null,callableCount:0};let r=U(e,n[0]).filter(s=>s.isFunctionLike),i=r.filter(s=>s.enclosingSymbol===null),o=i.length>0?i:r;return{primary:o.length===1?o[0]:null,callableCount:o.length}}function $V(e,t,n,r,i){let o=[...t?[{definition:$E(e,t),role:"target"}]:[],...[...r.candidates.map(d=>d.candidate),...i].map(d=>({definition:$E(e,d.symbolB),role:"reuse-candidate"}))],s=new Map;for(let d of NE(o)){if(s.has(d.definition.symbol))continue;let m=d.role==="target"?Ym:OE,p=d.definition.endLine<=d.definition.startLine?Kn(e,d.definition.relativePath,d.definition.startLine,m):null,f=p?.unitType?p.source:Ht(e,d.definition);if(!f)continue;let g=f.split(`
431
- `),h=Math.min(g.length,m),b=p?.unitType?p.startLine:d.definition.startLine;s.set(d.definition.symbol,{role:d.role,symbol:d.definition.symbol,shortName:z(d.definition.symbol),file:d.definition.relativePath,startLine:b,endLine:b+h-1,source:g.slice(0,h).join(`
432
- `),omittedLines:(p?.unitType?p.omittedLines:0)+Math.max(0,g.length-h)})}let a=new Map;for(let d of n.referencedBy){if(d.source===void 0||d.source===null||d.sourceStartLine===void 0||d.sourceStartLine===null||d.sourceEndLine===void 0||d.sourceEndLine===null)continue;let m=`${d.relativePath}:${d.sourceStartLine}-${d.sourceEndLine}`,p=a.get(m);if(p){p.focusLines=[...new Set([...p.focusLines??[],d.line])].sort((f,g)=>f-g);continue}a.set(m,{role:"consumer",symbol:d.enclosingSymbol??`${d.relativePath}:${d.line}`,shortName:d.enclosingShort,file:d.relativePath,startLine:d.sourceStartLine,endLine:d.sourceEndLine,source:d.source,omittedLines:0,focusLines:[d.line]})}let c=[...[...s.values()].filter(d=>d.role==="target"),...a.values(),...[...s.values()].filter(d=>d.role==="reuse-candidate")],l=[],u=BE;for(let d of c){if(l.length>=_E||u<=0)break;let m=d.source.split(`
433
- `),p=Math.min(m.length,u);l.push({...d,endLine:d.startLine+p-1,source:m.slice(0,p).join(`
434
- `),omittedLines:d.omittedLines+Math.max(0,m.length-p),...d.focusLines?{focusLines:d.focusLines.filter(f=>f<=d.startLine+p-1)}:{}}),u-=p}return{slices:l,candidateSlices:c.length,omittedSlices:Math.max(0,c.length-l.length),maxSlices:_E,maxLinesPerSlice:Ym,maxTotalLines:BE,targetLineLimit:Ym,consumerContextLines:UE,reuseLineLimit:OE}}function $E(e,t){let n=Sr(e,t);return n?U(e,n.relativePath).find(r=>r.symbol===t)??null:null}function jV(e,t,n,r={}){let i=Vc(r.consumerLimit,HE),o=Vc(r.perConsumerSearchLimit,Yc),s=Vc(r.perConsumerCandidateLimit,Jm),a=Vc(r.candidateLimit,Xm),c=HV(e),l=c.slice(0,i),u=new Set(c.map(p=>p.symbol));t&&u.add(t);let d=new Map;for(let p of l){let f=n(p.symbol).slice(0,o),g=0;for(let h of f){let b=UV(h,p.symbol);if(!b||u.has(b.symbolB))continue;let S=d.get(b.symbolB);if(S?(S.consumers.some(y=>y.symbol===p.symbol)||S.consumers.push(p),b.similarity>S.candidate.similarity&&(S.candidate=b)):d.set(b.symbolB,{candidate:b,consumers:[p]}),g+=1,g>=s)break}}let m=[...d.values()].filter(p=>p.candidate.actionTier==="direct"||p.candidate.similarity>=FV||p.consumers.length>1).sort(qV).slice(0,a);return{candidates:m,coverage:{totalConsumers:c.length,analyzedConsumers:l.length,omittedConsumers:Math.max(0,c.length-l.length),perConsumerSearchLimit:o,perConsumerCandidateLimit:s,candidateLimit:a,returnedCandidates:m.length}}}function HV(e){let t=new Map;for(let n of e.referencedBy){if(!n.enclosingSymbol)continue;let r=t.get(n.enclosingSymbol);if(r){r.referenceCount+=1;continue}t.set(n.enclosingSymbol,{symbol:n.enclosingSymbol,shortName:z(n.enclosingSymbol)||n.enclosingShort,file:n.relativePath,referenceCount:1})}return[...t.values()].sort((n,r)=>r.referenceCount-n.referenceCount||n.symbol.localeCompare(r.symbol))}function UV(e,t){return e.symbolA===t?e:e.symbolB!==t?null:{...e,symbolA:e.symbolB,shortNameA:e.shortNameB,fileA:e.fileB,symbolB:e.symbolA,shortNameB:e.shortNameA,fileB:e.fileA,uniqueToA:e.uniqueToB,uniqueToB:e.uniqueToA}}function qV(e,t){let n=jE(t.candidate.actionTier)-jE(e.candidate.actionTier);if(n!==0)return n;let r=t.consumers.length-e.consumers.length;if(r!==0)return r;let i=t.candidate.similarity-e.candidate.similarity;return i!==0?i:e.candidate.symbolB.localeCompare(t.candidate.symbolB)}function jE(e){return e==="direct"?1:0}function Vc(e,t){return typeof e=="number"&&Number.isFinite(e)?Math.max(1,Math.floor(e)):t}function GV(){return{candidates:[],coverage:{totalConsumers:0,analyzedConsumers:0,omittedConsumers:0,perConsumerSearchLimit:Yc,perConsumerCandidateLimit:Jm,candidateLimit:Xm,returnedCandidates:0}}}function Oe(e,t,n,r=()=>({})){let i;return N(`context.${e}`,()=>(i=n(),i),()=>({target:t,...r(i)}))}function zV(e,t,n){let r={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return r;let i=jt(e,n?{head:n}:{}),o=Oe("history.churn",t,()=>i.fileChurn(),c=>({files:c?.size??0}));if(!o)return r;let s=Oe("history.co-change",t,()=>ms(e,t,{limit:5,...n?{head:n}:{}}),c=>({commits:c.commitsAnalyzed,partners:c.findings.length})),a=Oe("history.suppressions",t,()=>Kc(e).byFile.get(t)??0,c=>({suppressions:c}));return{available:!0,file:t,churn:o.get(t)??{changes:0,fixChanges:0,lastChangedAt:0},coChangePartners:s.findings.map(c=>({file:c.fileA===t?c.fileB:c.fileA,together:c.together,confidence:c.confidence,subjectContext:c.subjectContext})),suppressionsInFile:a}}function KV(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}var Ee={dead:{minLoc:1,skipBarrels:!1,deadCodeOnly:!1},isolated:{minLoc:3},similar:{minSimilarity:.6,limit:50,minCallees:4},duplicateBodies:{maxLoc:15,limit:50},extract:{minLoc:15,minCallees:5,limit:50},wrappers:{maxLoc:15,limit:50},passthroughs:{maxLoc:15,limit:50},stale:{minLoc:3,limit:50},drift:{},twinDrift:{minSimilarity:.3}};import{existsSync as WV}from"fs";import{isAbsolute as VV,join as YV}from"path";var JV=".scipquery-baseline.json";function Qm(e){if(e.startsWith("similar:")){let t=e.slice(8).split("|");return t.length!==2?e:`similar:${t.map(T).sort().join("|")}`}if(e.startsWith("duplicate-bodies:")){let t=e.slice(17),n=t.indexOf(":");if(n<0)return e;let r=t.slice(0,n),i=t.slice(n+1).split("|");return i.length<2?e:`duplicate-bodies:${r}:${i.map(T).sort().join("|")}`}return e}function Zm(e,t){return t&&VV(t)?t:YV(e.config.projectRoot,t??JV)}function qE(e,t,n={}){let r=Zm(e,n.path);if(!WV(r))throw new Error(`No baseline found at ${r}. Create one with: scip-query health --write-baseline`);let o=(JSON.parse(Ve(r,"health baseline")).findings??[]).map(Qm),s=new Set(n.accept?o.filter(n.accept):o),a=new Set(t);return{baselinePath:r,baselineCount:s.size,current:[...t],newFindings:t.filter(c=>!s.has(c)),fixedFindings:[...s].filter(c=>!a.has(c))}}import bs from"path";function vs(e,t){let{scope:n,minDeviation:r=5,limit:i=50}=t??{},o=t?.semantic!==!1,s=t?.includePatternDeviations===!0,c=new H(e).fileDependencyGraph(n),l=ts(e,{scope:n}),u=t2([...XV(e,c,{scope:n,semantic:o}),...ZV(l.forbiddenEdges),...s?e2(c,r):[]]);return t?.includeArchitecture===!0&&(u.architecture=l),i<=0||u.results.length<=i?u:{...u,results:u.results.slice(0,i),totalResults:u.results.length}}function XV(e,t,n){let r=i2(e,n.scope),i=[],o=new Set;for(let[a,c]of t){if(Ss(a))continue;let l=r.get(a)??new Set;for(let u of c)Ss(u)||l.has(u)||QV(e,a,u,n)||(i.push({file:a,dep:u}),o.add(a))}o.size>0&&a2(e,r,{paths:[...o]});let s=[];for(let{file:a,dep:c}of i)(r.get(a)??new Set).has(c)||s.push({file:a,kind:"unused-import",description:`Depends on ${c} but references none of its symbols`,dep:c,actionTier:"direct",evidenceReasons:[`dependency edge exists from ${a} to ${c}`,"no semantic, source, type-only, side-effect, or Vue-template usage survived the conservative skip gates"],recommendation:"Remove the unused import or dependency edge after running the project checks."});return s}function QV(e,t,n,r){return u2(e,t,n)||d2(e,t,n)||c2(n)||p2(e,t,n)||m2(n)?!0:r.semantic&&l2(e,t,n)}function ZV(e){return e.flatMap(t=>{let n=t.examples[0];return n?[{file:n.fromFile,kind:"architecture-violation",description:`${t.from} depends on forbidden boundary ${t.to} through ${t.fileEdgeCount} file edge(s)`,dep:n.toFile,detail:`${t.from} may not depend on ${t.to}`,actionTier:"direct",policyBasis:"explicit",architecture:{fromBoundary:t.from,toBoundary:t.to,fileEdgeCount:t.fileEdgeCount,importerCount:t.importerCount,importedFileCount:t.importedFileCount,examples:t.examples},evidenceReasons:[`configured dependency row for ${t.from} does not allow ${t.to}`,`${t.fileEdgeCount} file edge(s) connect ${t.importerCount} importer(s) to ${t.importedFileCount} imported file(s)`,...t.examples.map(r=>`${r.fromFile} imports ${r.toFile}`)],recommendation:"Move the dependency behind an allowed boundary, reverse the dependency through an owned interface, or deliberately update the project architecture rule."}]:[]})}function e2(e,t){let n=[];for(let[r,i]of n2(e)){let o=i.filter(a=>!Ss(a));if(o.length<t)continue;let s=r2(e,o);for(let a of o)for(let c of e.get(a)??[])Ss(c)||(s.get(c)??0)===1&&bs.dirname(c)!==r&&bs.dirname(c)!==bs.dirname(r)&&n.push({file:a,kind:"pattern-deviation",description:`Only file in ${r}/ that depends on ${c}`,dep:c,actionTier:"signal",evidenceReasons:[`${o.length} sibling file(s) in ${r}/ were compared`,`${a} is the only non-skipped sibling depending on ${c}`],recommendation:"Review sibling ownership before changing this import; unique dependency shape can be intentional specialization."})}return n}function t2(e){let t=e.filter(n=>n.kind==="architecture-violation").length;return{results:e,unusedImports:e.filter(n=>n.kind==="unused-import").length,architectureViolations:t,layerViolations:t,patternDeviations:e.filter(n=>n.kind==="pattern-deviation").length}}function n2(e){let t=new Map;for(let n of e.keys()){let r=bs.dirname(n),i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function r2(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])Ss(i)||n.set(i,(n.get(i)??0)+1);return n}function i2(e,t){let n=new Map;return o2(e,n,t),n}function o2(e,t,n){for(let r of s2(e,n))GE(e,t,r.from_file,r.to_file)}function s2(e,t){let n=t?"AND d1.relative_path LIKE ?":"",r=t?[`%${t}%`]:[];return e.all(`SELECT DISTINCT d1.relative_path AS from_file, d2.relative_path AS to_file
435
- FROM mentions m
436
- JOIN chunks c ON m.chunk_id = c.id
437
- JOIN documents d1 ON c.document_id = d1.id
438
- JOIN global_symbols gs ON m.symbol_id = gs.id
439
- JOIN (
440
- SELECT m2.symbol_id, c2.document_id
441
- FROM mentions m2
442
- JOIN chunks c2 ON m2.chunk_id = c2.id
443
- WHERE m2.role = 1
444
- GROUP BY m2.symbol_id
445
- ) sym_def ON sym_def.symbol_id = gs.id
446
- JOIN documents d2 ON sym_def.document_id = d2.id
447
- WHERE d1.id != d2.id
448
- AND m.role != 1
449
- ${e.pathExclusionsFor("d1","d2")}
450
- ${n}`,...r)}function a2(e,t,n={}){new H(e).scanSourceReferences({paths:n.paths??Z(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},i=>{i.target.relativePath!==i.sourceFile&&(e.isIgnored(i.target.relativePath)||GE(e,t,i.sourceFile,i.target.relativePath))})}function GE(e,t,n,r){if(e.isIgnored(n)||e.isIgnored(r))return;let i=t.get(n);i||(i=new Set,t.set(n,i)),i.add(r)}function c2(e){return e.includes("types")||e.endsWith(".d.ts")}function l2(e,t,n){return Po(e,t).filter(i=>i.sourcePath===n).some(i=>i.isUsed)}function u2(e,t,n){return ae(e,t).filter(i=>i.sourcePath===n).some(i=>i.used)}function d2(e,t,n){let r=ae(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.every(i=>i.isTypeOnly===!0)}function m2(e){return e.endsWith(".vue")}function p2(e,t,n){let r=ae(e,t).filter(i=>i.sourcePath===n);return r.length===0?!1:r.every(i=>i.kind==="side-effect"||i.kind==="namespace"&&i.usedMembers.length===0&&!i.used)}function Ss(e){let t=q(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||f2(bs.basename(e)))}function f2(e){return!!(e==="index.ts"||e==="index.js"||e==="cli.ts"||e==="main.ts"||e==="main.rs"||e.includes("worker.")||e.includes("postinstall.")||e==="health.ts"||e==="health.js")}function Cs(e,t){let{scope:n,minLoc:r=3,maxLoc:i=80,limit:o=30,includeLowConfidence:s=!1,scanLimit:a}=t??{},c=t?.semantic!==!1,l=new H(e),u=l.scopedDefinitions(n),d=w2(l,n),m={high:0,medium:1,low:2};return At({candidates:()=>g2(e,l,u,{minLoc:r,maxLoc:i}),orderCandidates:(p,f)=>ee(f)-ee(p)||p.relativePath.localeCompare(f.relativePath),scanLimit:a,profile:{name:"stale-abstractions"},prepare:p=>{let f=y2(p),g=h2(e,l,p,f,{semantic:c}),h=p.filter(b=>{if(l.hasSuppressionComment(b))return!1;let S=Jc(e,b,g,f);return S.realConsumers.length<=1&&!S.transitivelyReachable&&zE(b,S.realConsumers.length,d)});return{consumerFileMap:g,singletonBackedClassIds:v2(e,l,u,h,{semantic:c}),candidateIndex:f}},evaluate:(p,f)=>{if(l.hasSuppressionComment(p)||f.singletonBackedClassIds.has(p.symbolId))return null;let g=Jc(e,p,f.consumerFileMap,f.candidateIndex);if(g.transitivelyReachable||g.realConsumers.length>1||g.realConsumers.length===0&&g.barrelConsumers>0||!zE(g.definition,g.realConsumers.length,d))return null;let h=b2(e,g);return!s&&h.confidence==="low"?null:h},orderResults:(p,f)=>m[p.confidence]-m[f.confidence]||f.loc-p.loc||p.file.localeCompare(f.file)||p.startLine-f.startLine,limit:o})}function g2(e,t,n,r){return n.filter(i=>i.isTypeLike&&ee(i)>=r.minLoc).filter(i=>ee(i)<=r.maxLoc).filter(i=>!e.isIgnored(i.relativePath)).filter(i=>!i.relativePath.endsWith(".d.ts")).filter(i=>q(i.relativePath)!=="test").filter(i=>!Te(e,i.symbol,i.relativePath)).filter(i=>!L2(i.symbol))}function ep(e,t,n,r){return Tn(Mn(e,t).forDefinitions(n,{semantic:r.semantic,sourceFallback:r.sourceFallback}))}function h2(e,t,n,r,i){let o=ep(e,t,n,{semantic:!1,sourceFallback:!1}),s=n.filter(l=>{let u=Jc(e,l,o,r);return u.realConsumers.length<=1&&!(u.realConsumers.length>0&&tp(l.relativePath))}),a=i.semantic&&s.length>0?Rn(o,ep(e,t,s,{semantic:!0,sourceFallback:!1})):o,c=s.filter(l=>Jc(e,l,a,r).realConsumers.length<=1);return Rn(a,ep(e,t,c,{semantic:!1,sourceFallback:!0}))}function y2(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);r||(r=new Map,t.set(n.relativePath,r));let i=z(n.symbol);i&&r.set(i,n)}return t}function Jc(e,t,n,r){let o=[...n.get(t.symbolId)??new Set].filter(u=>u!==t.relativePath&&!e.isIgnored(u)),{realConsumers:s,barrelConsumers:a,importOnlyConsumers:c}=kc(e,t,o),l=P2(e,t,n,r);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:l}}function b2(e,t){let n=WE(e,t.definition.relativePath,t.definition.startLine),r=tp(t.definition.relativePath)?!0:D2(e,t.definition),{confidence:i,reason:o}=M2(t.realConsumers.length,n,r),s=S2(t.realConsumers.length,n,r);return{symbol:t.definition.symbol,shortName:T(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:ee(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:r,confidence:i,reason:o,actionTier:s.actionTier,stalenessKind:s.stalenessKind,recommendation:s.recommendation}}function S2(e,t,n){return e===0?{actionTier:"direct",stalenessKind:"unused-abstraction",recommendation:"Delete the abstraction or wire the missing consumer after checking public/package surfaces."}:t==="class"?{actionTier:"signal",stalenessKind:"one-to-one-class-encapsulation",recommendation:"Treat as weak signal: a one-consumer class may be intentional encapsulation, so inline only after reviewing ownership and state boundaries."}:n?{actionTier:"signal",stalenessKind:"single-consumer-abstraction",recommendation:"Review whether this single-consumer abstraction earns its name or should be folded into the owning feature."}:{actionTier:"signal",stalenessKind:"misplaced-single-consumer-type",recommendation:"Review moving or co-locating the type with its only real consumer; keep it here only if this file owns the public contract."}}function v2(e,t,n,r,i){let o=x2(e,C2(n),r),s=o.map(l=>l.singleton);if(o.length===0)return new Set;let a=Tn(Mn(e,t).forDefinitions(s,{semantic:i.semantic,sourceFallback:!0})),c=new Set;for(let{singleton:l,classId:u}of o)E2(e,l,a)&&c.add(u);return c}function C2(e){let t=new Map;for(let n of e){let r=z(n.symbol);r&&t.set(KE(n.relativePath,r),n)}return t}function x2(e,t,n){let r=[];for(let i of n){let o=R2(e,t,i);o&&r.push({singleton:o,classId:i.symbolId})}return r}function R2(e,t,n){if(WE(e,n.relativePath,n.startLine)!=="class")return null;let r=z(n.symbol);if(!r)return null;let i=I2(e,n.relativePath,r);return i?t.get(KE(n.relativePath,i))??null:null}function E2(e,t,n){let r=z(t.symbol),i=n.get(t.symbolId);return!r||!i?!1:[...i].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!fm(e,o,r))}function KE(e,t){return`${e}\0${t}`}function I2(e,t,n){let r=W(e,t);if(!r)return null;let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\bexport\\s+const\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*new\\s+${i}\\s*\\(`);return r.match(o)?.[1]??null}function w2(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function L2(e){let t=Bn(e);if("kind"in t)return!1;let n=t.descriptors;if(n.length<2)return!1;let r=n[n.length-1],i=n[n.length-2];return r?.suffix==="type"&&i?.suffix==="type"}function tp(e){let n=(e.split("/").pop()??"").replace(/\.[^.]+$/,"");return!!(n==="types"||n.endsWith("-types")||n==="models"||n==="schema"||n==="common"||n==="protocol"||n==="proto"||n==="dto"||n==="mod"||n==="contracts"||/(^|\/)types(\/|\.)/.test(e)||/(^|\/)models?(\/|\.)/.test(e)||/(^|\/)proto(?:col)?(\/|\.)/.test(e)||/(^|\/)schema(\/|\.)/.test(e)||/(^|\/)contracts?(\/|\.)/.test(e))}function zE(e,t,n){return!(tp(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function P2(e,t,n,r){let i=mf(e,t.relativePath),o=z(t.symbol);if(!o)return!1;let s=r.get(t.relativePath);if(!s)return!1;let a=[...i.get(o)??[]],c=new Set;for(;a.length>0;){let l=a.pop();if(c.has(l))continue;c.add(l);let u=s.get(l);if(!u)continue;let d=n.get(u.symbolId);if(d){for(let m of d)if(m!==t.relativePath&&!e.isIgnored(m))return!0}for(let m of i.get(l)??[])a.push(m)}return!1}function WE(e,t,n){let r=W(e,t);if(!r)return"other";let i=r.split(`
451
- `),o=Math.max(0,n-2),s=Math.min(i.length-1,n+2);for(let a=o;a<=s;a++){let l=(i[a]??"").replace(/^\s*\/\/.*$/g,"");if(/\b(?:export\s+)?(?:abstract\s+)?class\s+\w/.test(l))return"class";if(/\b(?:export\s+)?interface\s+\w/.test(l))return"interface";if(/\b(?:export\s+)?type\s+\w/.test(l))return"type";if(/\b(?:export\s+)?(?:const\s+)?enum\s+\w/.test(l))return"enum"}return"other"}function D2(e,t){let n=W(e,t.relativePath);if(!n)return!1;let r=z(t.symbol);if(!r)return!1;let i=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${i}\\b`),s=n.split(`
452
- `);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function M2(e,t,n){return e===0?{confidence:"high",reason:"unused \u2014 no consumers and defining file has no real usage"}:e===1&&t==="class"?{confidence:"low",reason:"1 consumer + class kind \u2014 likely 1:1 encapsulation, not over-abstraction"}:e===1&&!n?{confidence:"high",reason:"1 consumer + defining file never uses it \u2014 type belongs with its consumer"}:{confidence:"medium",reason:"1 consumer \u2014 single-use abstraction"}}import{basename as zi,extname as Xc}from"path";function xs(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new H(e),a=_2(s.fileDependencyGraph(n));return At({candidates:()=>A2(e,s,n,r),orderCandidates:Ka,scanLimit:o,profile:{name:"wrapper-candidates"},prepare:c=>({callerFileMap:T2(e,s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>k2(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:i})}function T2(e,t,n,r){let i=Mn(e,t),o=Tn(i.forDefinitions(n,{semantic:!1,sourceFallback:!1})),s=[];r.semantic&&N("wrapper.semantic-candidates",()=>{s=n.filter(m=>np(e,t,m,o).length<=1)},()=>({symbols:n.length,semanticCandidates:s.length}));let a=s.length===0?new Map:Tn(i.forDefinitions(s,{semantic:!0,sourceFallback:!1})),c=a.size===0?o:Rn(o,a),l=new Map(n.map(m=>[m.symbolId,m])),u=new Map;for(let m of n){let p=np(e,t,m,c);if(p.length>1||(u.set(m.symbolId,m),p.length!==1))continue;let f=p[0],g=VE(e,m.symbolId,f);if(!g)continue;let h=YE(t,e,f,m.symbol,g);h?.isFunctionLike&&l.has(h.symbolId)&&u.set(h.symbolId,l.get(h.symbolId))}let d=[...u.values()];return d.length===0?c:Rn(c,Tn(i.forDefinitions(d,{semantic:!1,sourceFallback:!0})))}function k2(e,t,n,r){let i=np(e,t,n,r.callerFileMap);if(i.length!==1)return null;let o=i[0],s=VE(e,n.symbolId,o);if(!s)return null;let a=YE(t,e,o,n.symbol,s);if(a&&ii(a.symbol))return null;let{fanIn:c,source:l}=F2(r.callerFileMap,r.reverseFanIn,o,a);if(l==="function"?c<=3:c<=5)return null;let u=B2(e,n,o,a);return{symbol:n.symbol,shortName:T(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:ee(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?T(a.symbol):zi(o),callerFanIn:c,actionTier:u.length>0?"signal":"direct",boundaryEvidence:u}}function A2(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:2,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0}).filter(i=>!_s(e,i))}function np(e,t,n,r){let i=zi(n.relativePath,Xc(n.relativePath)),o=[...r.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>zi(s,Xc(s))!==i).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return kc(e,n,o).realConsumers}function VE(e,t,n){return e.get(`SELECT c.start_line, c.end_line
453
- FROM mentions m
454
- JOIN chunks c ON m.chunk_id = c.id
455
- JOIN documents d ON c.document_id = d.id
456
- WHERE m.symbol_id = ? AND m.role != 1 AND d.relative_path = ?
457
- LIMIT 1`,t,n)}function YE(e,t,n,r,i){let o=e.definitionsForFile(n),s=N2(t,n,r,i.start_line,i.end_line);return Ne(o,s)}function F2(e,t,n,r){if(r?.isFunctionLike){let i=[...e.get(r.symbolId)??[]].filter(o=>o!==r.relativePath);if(i.length>0)return{fanIn:i.length,source:"function"}}return{fanIn:O2(t,n),source:"file"}}function N2(e,t,n,r,i){let o=z(n);if(!o)return r;let s=ai(e,t).get(o);if(!s||s.length===0)return r;for(let a of s)if(a>=r&&a<=i)return a;return r}function _2(e){let t=new Map;for(let[n,r]of e){t.has(n)||t.set(n,t.get(n)??0);for(let i of r)t.set(i,(t.get(i)??0)+1)}return t}function O2(e,t){let n=e.get(t)??0;if(n>0)return n;let r=zi(t,Xc(t)),i=0;for(let[o,s]of e)o!==t&&zi(o,Xc(o))===r&&s>i&&(i=s);return i}function B2(e,t,n,r){return qc(e,t.relativePath,t.startLine,"wrapper","explicit ignore-wrapper comment",[{label:"wrapper name",value:T(t.symbol)},{label:"caller name",value:r?.symbol?T(r.symbol):zi(n)},{label:"wrapper path",value:t.relativePath},{label:"caller path",value:n}])}var $2=25e3,j2=2500,H2=2500;function U2(e){let t=Ar(e);return t.symbols>=$2||t.documents>=j2?H2:void 0}function rp(e,t={}){let{scope:n}=t,r=U2(e),i=[],o=zr(e,{scope:n,...Ee.dead,scanLimit:r});for(let s of o.symbols)Ue(e,s.relativePath)||Te(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&i.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of ns(e,{scope:n,...Ee.isolated,scanLimit:r}))Ue(e,s.relativePath)||Te(e,s.symbol,s.relativePath)||i.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of es(e,{scope:n}))s.kind==="real"&&i.push(`cycle:${q2(s.path)}`);for(let s of os(e,{scope:n,...Ee.similar,scanLimit:r}))i.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of fs(e,{scope:n,...Ee.duplicateBodies,scanLimit:r}))i.push(`duplicate-bodies:${s.hash}:${s.functions.map(a=>a.symbol).sort().join("|")}`);for(let s of us(e,{scope:n,...Ee.extract,scanLimit:r}))i.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of xs(e,{scope:n,...Ee.wrappers,scanLimit:r}))i.push(`wrapper:${s.file}:${s.shortName}`);for(let s of gs(e,{scope:n,...Ee.passthroughs,scanLimit:r}))i.push(`passthrough:${s.file}:${s.shortName}`);for(let s of Cs(e,{scope:n,...Ee.stale,scanLimit:r}))i.push(`stale:${s.file}:${s.shortName}`);for(let s of vs(e,{scope:n,...Ee.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY}).results)s.kind!=="architecture-violation"&&i.push(`drift:${s.kind}:${s.file}:${s.dep}`);return i.push(...rm(ts(e,{scope:n}))),[...new Set(i.map(Qm))].sort()}function q2(e){if(e.length===0)return"";let t=0;for(let n=1;n<e.length;n++)e[n]<e[t]&&(t=n);return[...e.slice(t),...e.slice(0,t)].join(">")}function G2(e,t={}){let n=rp(e,{scope:t.scope}),r=Zm(e,t.path);return _f(r,{version:1,findings:n},{spacing:2,trailingNewline:!0}),{path:r,findingCount:n.length}}function z2(e,t={}){return qE(e,rp(e,{scope:t.scope}),{path:t.path})}function K2(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new H(e);return At({candidates:()=>o.productionCallableDefinitions({scope:n,files:t.files,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}),filterCandidate:s=>W2(s.relativePath),scanLimit:i,profile:{name:"unused-params"},evaluate:s=>{let a=K(e,s.relativePath)?.callables.find(u=>u.startLine===s.startLine&&u.endLine===s.endLine);if(!a||a.params.length===0||a.params.some(u=>!u.simple)||a.paramsEndLine>=a.endLine)return null;let c=ai(e,s.relativePath),l=[];for(let u=a.params.length-1;u>=0;u--){let d=a.params[u];if(d.name===""||d.name.startsWith("_")||V2(c.get(d.name),a.paramsEndLine,a.endLine))break;l.unshift(d.name)}return l.length===0?null:{symbol:s.symbol,shortName:T(s.symbol),file:s.relativePath,startLine:s.startLine,endLine:s.endLine,paramCount:a.paramCount,unusedTrailing:l}},orderResults:(s,a)=>a.unusedTrailing.length-s.unusedTrailing.length||s.file.localeCompare(a.file)||s.startLine-a.startLine,limit:r})}function W2(e){let t=se(e);return t==="typescript"||t==="tsx"||t==="javascript"}function V2(e,t,n){return e?e.some(r=>r>t&&r<=n):!1}var Y2=new Set(Kt());function ip(e,t){let{scope:n,minLoc:r=10,limit:i=30,scanLimit:o}=t??{},s=new H(e);return At({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:r,requireFunctionLikeSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,filterCandidate:J2,profile:{name:"complexity-hotspots"},prepare:a=>{let c=Q2(e,a),l=t?.semantic!==!1,u=l?st(e):null;u?.materializeReferences(a,{prefetchCallees:!0});let d=s.crossFileCallerMap(a,{semantic:!1});return{callerMap:u?Rn(d,u.callerMap(a)):d,calleeMap:s.calleeMap(a,{semantic:l}),languageByFile:c,clojureCallableIds:Z2(e,a,c),branchEstimates:PE(e,a)}},evaluate:(a,c)=>X2(a,c,r),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:i})}function J2(e){return e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&Y2.has(e.kind):!0}function X2(e,t,n){if(t.languageByFile.get(e.relativePath)==="clojure"&&!t.clojureCallableIds.has(e.symbolId))return null;let r=e.endLine-e.startLine+1;if(r<n)return null;let i=t.callerMap.get(e.symbolId)?.size??0,o=t.calleeMap.get(e.symbolId)??[],s=new Set,a=new Set;for(let m of o){let p=`${m.symbol}|${m.file}`;s.add(p),m.file!==e.relativePath&&a.add(p)}let c=a.size,l=s.size,u=t.branchEstimates.get(e.symbolId)??{branches:0,estimateBasis:"regex-fallback"},d=u.branches+1;return{symbol:e.symbol,shortName:T(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:r,fanIn:i,fanOut:c,calleeCount:l,branches:u.branches,estimateBasis:u.estimateBasis,score:Math.round(r/50*(i/5)*Math.max(c/5,1)*Math.max(d/5,1)*100)/100}}function Q2(e,t){let n=[...new Set(t.map(o=>o.relativePath))];if(n.length===0)return new Map;let r=n.map(()=>"?").join(", "),i=e.all(`SELECT relative_path, language
458
- FROM documents
459
- WHERE relative_path IN (${r})`,...n);return new Map(i.map(o=>[o.relative_path,o.language?.toLowerCase()??null]))}function Z2(e,t,n){let r=new Set,i=new Map;for(let o of t){if(n.get(o.relativePath)!=="clojure")continue;let s=i.get(o.relativePath);s||(s=new Set((K(e,o.relativePath)?.callables??[]).map(a=>`${a.name}:${a.startLine}`)),i.set(o.relativePath,s)),s.has(`${o.leaf}:${o.startLine}`)&&r.add(o.symbolId)}return r}import{readdirSync as eY}from"fs";import{basename as tY,join as JE}from"path";function nY(e,t,n={}){let r=new Set(e),i=new Set(t),o=[...i].filter(a=>!r.has(a)).sort(),s=n.allowExtra?[]:[...r].filter(a=>!i.has(a)).sort();return{missing:o,extra:s}}function rY(e,t){let n=iY(e,t.file,t.keys);if(!n.ok)return{name:t.name,file:t.file,status:"unavailable",missing:[],extra:[],unavailableReason:n.reason};let r=uY(e.config.projectRoot,t.mustEqual),i=nY(n.keys,r,{allowExtra:t.allowExtra??!1}),o=i.missing.length>0||i.extra.length>0?"violated":"ok";return{name:t.name,file:t.file,status:o,missing:i.missing,extra:i.extra}}function QE(e,t){return t.map(n=>rY(e,n))}function iY(e,t,n){return n.type==="markdown-list"?lY(e,t,n.marker):oY(e,t,n)}function oY(e,t,n){if(!W(e,t))return{ok:!1,reason:`file not found: ${t}`};let i=se(t);if(!i)return{ok:!1,reason:`unsupported file type for ${n.type} extraction: ${t}`};let o=J(e,t);if(!o)return{ok:!1,reason:`tree-sitter parser unavailable for ${i} (${t}) \u2014 contract skipped, not silently passed`,disclosedUnavailable:{language:i,reason:"parser-unavailable"}};let s=n.type==="object-literal-keys"?sY(o,n.identifier):cY(o,n.identifier);return s===null?{ok:!1,reason:`no ${n.type==="object-literal-keys"?"object literal":"string array"} named "${n.identifier}" found in ${t}`}:{ok:!0,keys:s}}function ZE(e){let t=e.childForFieldName("value");return t?t.type==="as_expression"||t.type==="satisfies_expression"?t.namedChild(0):t:null}function sY(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=ZE(n);if(i?.type==="object")return aY(i)}return null}function aY(e){let t=new Set;for(let n of e.namedChildren)if(n.type==="pair"){let r=n.childForFieldName("key");r&&t.add(eI(r.text))}else n.type==="shorthand_property_identifier"&&t.add(n.text);return[...t].sort()}function cY(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=ZE(n);if(i?.type!=="array")continue;let o=new Set;for(let s of i.namedChildren)s.type==="string"&&o.add(eI(s.text));return[...o].sort()}return null}function eI(e){return e.length>=2&&(e[0]==="'"&&e.endsWith("'")||e[0]==='"'&&e.endsWith('"'))?e.slice(1,-1):e}function lY(e,t,n){let r=W(e,t);if(!r)return{ok:!1,reason:`file not found: ${t}`};let i=tI(r,n);return i===null?{ok:!1,reason:`no <!-- BEGIN GENERATED ${n} --> ... <!-- END GENERATED ${n} --> block in ${t}`}:{ok:!0,keys:nI(i)}}function tI(e,t){let n=Ce(t),i=new RegExp(`<!--\\s*BEGIN GENERATED ${n}\\s*-->([\\s\\S]*?)<!--\\s*END GENERATED ${n}\\s*-->`).exec(e);return i?i[1]:null}function nI(e){let t=new Set;for(let n of e.matchAll(/`([a-z][a-z0-9-]*)`/g))t.add(n[1]);for(let n of e.matchAll(/\[([a-z][a-z0-9-]*)\]\([^)]*\)/g))t.add(n[1]);return[...t].sort()}function uY(e,t){switch(t.type){case"top-level-dirs":return XE(JE(e,t.path));case"file-glob":return[...new Set(Lc(e,t.pattern).map(n=>tY(n)))].sort();case"registered-commands":return dY(e);case"builtin-skills":return XE(JE(e,"skills"))}}function XE(e){let t;try{t=eY(e,{withFileTypes:!0})}catch{return[]}return t.filter(n=>n.isDirectory()&&!n.name.startsWith(".")).map(n=>n.name).sort()}function dY(e){let t;try{t=Ye(e,"docs/COMMAND_REFERENCE.md",{maxBytes:8*1024*1024,inputKind:"generated command reference"})}catch(r){if(!Je(r))throw r;return[]}let n=tI(t,"COMMAND REFERENCE");return n?nI(n):[]}function An(e){return e.scoreCount??e.count}function oI(e){let t=gY(e),{breakdown:n,pressure:r}=hY(e),i=iI(n,"risk"),o=iI(n,"hygiene");return{score:Math.min(i,o),riskScore:i,hygieneScore:o,scoreBreakdown:n,overview:{documents:e.statsResult.documents,symbols:e.statsResult.symbols,indexSizeBytes:e.statsResult.indexSizeBytes},findings:{deadSymbols:e.dead.count,deadLoc:e.dead.loc,isolatedSymbols:e.isolated.count,isolatedLoc:e.isolated.loc,cycles:e.realCycleCount,similarPairs:e.similarCount,duplicateBodyGroups:e.duplicateBodies.count,duplicateBodyLoc:e.duplicateBodies.loc,twinDriftGroups:e.twinDrift.count,twinDriftLoc:e.twinDrift.loc,reactComponentDuplicatePairs:e.reactComponentDuplicates.count,reactHookCandidatePairs:e.reactHookCandidates.count,reactHookCandidateScoreCount:An(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:An(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:An(e.wrappers),passthroughs:e.passthroughs.count,staleTypes:e.stale.count,driftedFiles:e.drift.count,complexityHotspotCount:e.complexity.extremeCount,hiddenCouplingPairs:e.gitEvidence?.hiddenCoupling.pairCount??null,hiddenCouplingScoreCount:e.gitEvidence?.hiddenCoupling.scoreCount??null,coverageContractViolations:e.coverageContracts.count},axes:mY(e),validation:fY(e),suppressions:e.suppressions,actions:t,pressure:r,topComplexity:e.complexity.top,detectorEvidence:e.detectorEvidence,warnings:e.warnings.length>0?e.warnings:void 0}}function mY(e){return{deletable:{loc:e.dead.loc+e.isolated.loc,symbols:e.dead.count+e.isolated.count},cycles:{count:e.realCycleCount},changeAmplification:e.gitEvidence?.amplification??null,hiddenCoupling:e.gitEvidence?.hiddenCoupling??null,churnWeightedComplexity:pY(e),evidenceQuality:{graphFindings:e.dead.count+e.isolated.count+e.realCycleCount,heuristicFindings:e.similarCount+e.duplicateBodies.count+e.twinDrift.count+e.reactComponentDuplicates.count+e.reactHookCandidates.count+e.reactLargeComponentPressure.count+e.vueComponentDuplicates.count+e.vueComposableCandidates.count+e.vueLargeViewPressure.count+e.extractCount+e.wrappers.count+e.passthroughs.count+e.stale.count+e.drift.count,userSuppressed:e.suppressions?.total??0}}}function pY(e){let t=e.gitEvidence?.fileStats;return t?e.complexity.top.map(n=>{let r=n.file?t[n.file]?.changes??0:0;return{...n,changes:r,weighted:cn(n.score*Math.log2(1+r))}}).sort((n,r)=>r.weighted-n.weighted):null}function fY(e){let t=e.gitEvidence?.fileStats;if(!t)return null;let n={dead:e.dead.files??[],isolated:e.isolated.files??[],twinDrift:e.twinDrift.files??[],wrappers:e.wrappers.files??[],passthroughs:e.passthroughs.files??[],stale:e.stale.files??[],reactComponents:e.reactComponentDuplicates.files??[],reactHooks:e.reactHookCandidates.files??[],reactLargeComponents:e.reactLargeComponentPressure.files??[],vueComponents:e.vueComponentDuplicates.files??[],vueComposables:e.vueComposableCandidates.files??[],vueLargeViews:e.vueLargeViewPressure.files??[]},r=new Set(Object.values(n).flat()),i=0,o=0,s=0;for(let[u,d]of Object.entries(t))r.has(u)?i+=d.fixChanges:(o+=d.fixChanges,s+=1);let a=r.size>0?cn(i/r.size):0,c=s>0?cn(o/s):0,l={};for(let[u,d]of Object.entries(n)){let m=new Set(d);if(m.size===0)continue;let p=0;for(let g of m)p+=t[g]?.fixChanges??0;let f=cn(p/m.size);l[u]={flaggedFiles:m.size,fixDensity:f,lift:c>0?cn(f/c):null}}return{flaggedFiles:r.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:r.size>0&&c>0?cn(a/c):null,byCategory:l,validationBasis:{method:"subject-regex",commitsScanned:e.gitEvidence?.commitsScanned??0}}}function cn(e){return Math.round(e*100)/100}function sI(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function Qc(e,t="existing shared infrastructure discount"){let n=An(e);return Math.abs(n-e.count)<.01?"":` (${sI(n)} score-weighted after ${t})`}function Rs(e,t){let n=An(e),r=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?r:`${r} (${sI(n)} score-weighted)`}function gY(e){let t=[];if(e.dead.count>0&&t.push({category:"Dead code",evidence:"graph-fact",evidenceContractId:"dead-visible-references",description:`${e.dead.count} indexed symbols with no visible repository references \u2014 review runtime/framework roots and the capability disclosure, then verify any deletion with cleanup-plan --verify`,effort:"low",impact:"high",count:e.dead.count,locRecoverable:e.dead.loc}),e.isolated.count>0&&t.push({category:"Isolated symbols",evidence:"graph-fact",evidenceContractId:"isolated-visible-connectivity",description:`${e.isolated.count} symbols with no visible indexed or source-supported caller/callee after root exclusions \u2014 runtime reflection and generated dispatch remain disclosed blind spots`,effort:"low",impact:"medium",count:e.isolated.count,locRecoverable:e.isolated.loc}),e.realCycleCount>0&&t.push({category:"Circular dependencies",evidence:"graph-fact",description:`${e.realCycleCount} indexed dependency cycle(s) \u2014 inspect ownership and runtime order before choosing whether or how to break them`,effort:"medium",impact:"high",count:e.realCycleCount,locRecoverable:0}),e.similarCount>0&&t.push({category:"Similar functions",evidence:"heuristic",evidenceContractId:"duplicate-structural-candidate",description:`${e.similarCount} pairs share disclosed call or source-token evidence beyond imports \u2014 review domain identity before considering consolidation`,effort:"medium",impact:"medium",count:e.similarCount,locRecoverable:0}),e.duplicateBodies.count>0&&t.push({category:"Duplicate function bodies",evidence:"heuristic",evidenceContractId:"duplicate-structural-candidate",description:`${e.duplicateBodies.count} exact small-body group(s) across files \u2014 consolidate only when the domain concept matches`,effort:"low",impact:"medium",count:e.duplicateBodies.count,locRecoverable:e.duplicateBodies.loc}),e.twinDrift.count>0&&t.push({category:"Drifted twin implementations",evidence:"heuristic",description:`${e.twinDrift.count} same-name (or near-name) function group(s) across files with diverged or identical bodies \u2014 determine whether they represent the same concept before acting`,effort:"medium",impact:"medium",count:e.twinDrift.count,locRecoverable:0}),e.reactComponentDuplicates.count>0&&t.push({category:"Duplicated React components",evidence:"heuristic",description:`${e.reactComponentDuplicates.count} React component pair(s) share JSX structure \u2014 review whether local product intent justifies reuse`,effort:"medium",impact:"medium",count:e.reactComponentDuplicates.count,locRecoverable:e.reactComponentDuplicates.loc}),e.reactHookCandidates.count>0&&t.push({category:"Duplicated React hook behavior",evidence:"heuristic",description:`${e.reactHookCandidates.count} React component pair(s) share state/effect/request behavior${Qc(e.reactHookCandidates)} \u2014 review whether a common hook would preserve ownership and lifecycle semantics`,effort:"medium",impact:"medium",count:e.reactHookCandidates.count,locRecoverable:e.reactHookCandidates.loc}),e.reactLargeComponentPressure.count>0&&t.push({category:"Large React components",evidence:"heuristic",description:`${e.reactLargeComponentPressure.count} React component(s) concentrate JSX/behavior pressure \u2014 split by reason to change`,effort:"medium",impact:"medium",count:e.reactLargeComponentPressure.count,locRecoverable:0}),e.vueComponentDuplicates.count>0&&t.push({category:"Duplicated Vue components",evidence:"heuristic",description:`${e.vueComponentDuplicates.count} Vue component pair(s) share template structure \u2014 review whether local product intent justifies reuse`,effort:"medium",impact:"medium",count:e.vueComponentDuplicates.count,locRecoverable:e.vueComponentDuplicates.loc}),e.vueComposableCandidates.count>0&&t.push({category:"Duplicated Vue behavior",evidence:"heuristic",description:`${e.vueComposableCandidates.count} Vue component pair(s) share state/effect/request behavior${Qc(e.vueComposableCandidates)} \u2014 review whether a common composable would preserve ownership and lifecycle semantics`,effort:"medium",impact:"medium",count:e.vueComposableCandidates.count,locRecoverable:e.vueComposableCandidates.loc}),e.vueLargeViewPressure.count>0&&t.push({category:"Large Vue views",evidence:"heuristic",description:`${e.vueLargeViewPressure.count} Vue file(s) concentrate template/script/style pressure \u2014 split by reason to change`,effort:"medium",impact:"medium",count:e.vueLargeViewPressure.count,locRecoverable:0}),e.extractCount>0&&t.push({category:"Extraction candidates",evidence:"heuristic",description:`${e.extractCount} large functions with isolated callee clusters \u2014 review same-file or feature-local extraction seams`,effort:"medium",impact:"medium",count:e.extractCount,locRecoverable:0}),e.wrappers.count>0&&t.push({category:"Wrapper functions",evidence:"heuristic",evidenceContractId:"wrapper-indirection-candidate",description:`${e.wrappers.count} single-consumer symbols${Qc(e.wrappers,"boundary-evidence discount")} \u2014 inspect whether each is indirection or an intentional API, framework, or ownership boundary`,effort:"low",impact:"low",count:e.wrappers.count,locRecoverable:e.wrappers.loc}),e.passthroughs.count>0&&t.push({category:"Passthrough functions",evidence:"heuristic",evidenceContractId:"passthrough-forwarding-candidate",description:`${e.passthroughs.count} functions that literally forward to one callee \u2014 inspect whether each is unnecessary indirection or an intentional boundary`,effort:"low",impact:"low",count:e.passthroughs.count,locRecoverable:e.passthroughs.loc}),e.stale.count>0){let i=[];e.stale.unused>0&&i.push(`${e.stale.unused} unused`),e.stale.singleUse>0&&i.push(`${e.stale.singleUse} single-consumer (not in types file)`),t.push({category:"Stale abstractions",evidence:"heuristic",evidenceContractId:"stale-abstraction-candidate",description:`${i.join(", ")} \u2014 review public, runtime-registration, and ownership evidence before removing, moving, or inlining`,effort:"low",impact:"medium",count:e.stale.count,locRecoverable:e.stale.loc})}if(e.drift.count>0){let i=[];e.drift.unusedImports>0&&i.push(`${e.drift.unusedImports} unused imports`),e.drift.architectureViolations>0&&i.push(`${e.drift.architectureViolations} declared architecture violations`),t.push({category:"Structural drift",evidence:"heuristic",description:`${i.join(", ")} \u2014 repair direct dependency-rule breaks; inspect boundary signals with \`drift --architecture\``,effort:e.drift.architectureViolations>0?"medium":"low",impact:e.drift.architectureViolations>0?"medium":"low",count:e.drift.count,locRecoverable:0})}if(e.coverageContracts.count>0&&t.push({category:"Coverage contract drift",evidence:"graph-fact",description:`${e.coverageContracts.count} configured coverage contract(s) drifted from their ground-truth source (enumeration rot) \u2014 run \`scip-query health --json\` for the missing/extra keys`,effort:"low",impact:"medium",count:e.coverageContracts.count,locRecoverable:0}),e.gitEvidence&&e.gitEvidence.hiddenCoupling.pairCount>0){let i=e.gitEvidence.hiddenCoupling.top[0];t.push({category:"Hidden coupling",evidence:"change-graph",description:`${e.gitEvidence.hiddenCoupling.pairCount} file pair(s) co-change without a structural link`+Qc({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:e.gitEvidence.hiddenCoupling.scoreCount},"broad/stale-history discount")+(i?` (e.g. ${i.fileA} \u2194 ${i.fileB})`:"")+" \u2014 inspect whether a shared concept, generated artifact, or coordinated contract explains the history",effort:"medium",impact:"high",count:e.gitEvidence.hiddenCoupling.pairCount,locRecoverable:0})}let n={high:3,medium:2,low:1},r={low:3,medium:2,high:1};return t.sort((i,o)=>{let s=n[i.impact]*r[i.effort];return n[o.impact]*r[o.effort]-s}),t}var rI={"dead-code":"risk",isolated:"risk",cycles:"risk",complexity:"risk","hidden-coupling":"risk","cycles-pressure":"risk","complexity-pressure":"risk","hidden-coupling-pressure":"risk",similar:"hygiene","duplicate-bodies":"hygiene","twin-drift":"hygiene","react-component-duplicates":"hygiene","react-hook-candidates":"hygiene","react-large-component-pressure":"hygiene","vue-component-duplicates":"hygiene","vue-composable-candidates":"hygiene","vue-large-view-pressure":"hygiene",extract:"hygiene",wrappers:"hygiene",passthroughs:"hygiene","stale-abstractions":"hygiene",drift:"hygiene","similar-pressure":"hygiene","duplicate-bodies-pressure":"hygiene","twin-drift-pressure":"hygiene","react-component-duplicates-pressure":"hygiene","react-hook-candidates-pressure":"hygiene","react-large-component-pressure-pressure":"hygiene","vue-component-duplicates-pressure":"hygiene","vue-composable-candidates-pressure":"hygiene","vue-large-view-pressure-pressure":"hygiene","extract-pressure":"hygiene","wrappers-pressure":"hygiene","passthroughs-pressure":"hygiene","stale-abstractions-pressure":"hygiene","drift-pressure":"hygiene"};function iI(e,t){let n=e.filter(r=>r.kind===t).reduce((r,i)=>r+i.points,0);return Math.max(0,Math.min(100,100-n))}function hY(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),r=[],i=[],o=(R,E,w)=>{E>0&&r.push({axis:R,points:E,detail:w,kind:rI[R]??"hygiene"})},s=(R,E,w,I,k,D,F)=>{let L=Math.max(I,1);if(w<=L)return;let A=w/L,P=Math.min(k,Math.ceil(Math.log2(A)*D));if(P<=0)return;let j=rI[R]??"hygiene";i.push({axis:R,category:E,kind:j,count:w,threshold:cn(L),ratio:cn(A),extraPenalty:P}),o(R,P,`${w} ${F} exceed pressure threshold ${cn(L)} (${cn(A)}x)`)},a=e.dead.count/n;o("dead-code",Math.min(20,Math.round(a*200)),`${e.dead.count} dead symbols (${e.dead.loc} LOC deletable)`);let c=e.isolated.count/n;o("isolated",Math.min(10,Math.round(c*200)),`${e.isolated.count} isolated symbols (${e.isolated.loc} LOC deletable)`),o("cycles",Math.min(15,e.realCycleCount*5),`${e.realCycleCount} real dependency cycle(s)`);let l=e.similarCount/n*1e3;o("similar",Math.min(10,Math.round(l)),`${e.similarCount} similar function pair(s)`);let u=e.duplicateBodies.count/n*1e3;o("duplicate-bodies",Math.min(10,Math.round(u*2)),`${e.duplicateBodies.count} exact duplicate small-body group(s) (${e.duplicateBodies.loc} duplicate LOC)`);let d=e.twinDrift.count/n*1e3;o("twin-drift",Math.min(10,Math.round(d*2)),`${e.twinDrift.count} drifted twin implementation group(s) (same or near-same name, diverged or identical bodies)`);let m=e.reactComponentDuplicates.count/t*1e3;o("react-component-duplicates",Math.min(10,Math.round(m)),`${e.reactComponentDuplicates.count} duplicated React component pair(s)`);let p=An(e.reactHookCandidates),f=p/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(f)),Rs(e.reactHookCandidates,"duplicated React behavior pair(s)"));let g=e.reactLargeComponentPressure.count/t*1e3;o("react-large-component-pressure",Math.min(5,Math.round(g/2)),`${e.reactLargeComponentPressure.count} large React component pressure file(s)`);let h=e.vueComponentDuplicates.count/t*1e3;o("vue-component-duplicates",Math.min(10,Math.round(h)),`${e.vueComponentDuplicates.count} duplicated Vue component pair(s)`);let b=An(e.vueComposableCandidates),S=b/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(S)),Rs(e.vueComposableCandidates,"duplicated Vue behavior pair(s)"));let y=e.vueLargeViewPressure.count/t*1e3;o("vue-large-view-pressure",Math.min(5,Math.round(y/2)),`${e.vueLargeViewPressure.count} large Vue view pressure file(s)`);let x=An(e.wrappers);o("wrappers",Math.min(3,x),Rs(e.wrappers,"wrapper candidate(s)"));let v=An(e.passthroughs);o("passthroughs",Math.min(3,v),Rs(e.passthroughs,"passthrough candidate(s)")),o("stale-abstractions",Math.min(8,e.stale.unused),`${e.stale.unused} unused stale abstraction(s); ${e.stale.singleUse} single-consumer signal(s)`);let C=e.drift.direct/t;if(o("drift",Math.min(5,Math.round(C*50)),`${e.drift.direct} direct drift finding(s); ${e.drift.signal} signal drift finding(s)`),o("complexity",Math.min(5,e.complexity.extremeCount*2),`${e.complexity.extremeCount} extreme complexity hotspot(s)`),e.gitEvidence){let R=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(R/10)),Rs({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:R},"co-changing pair(s) without a structural link"))}if(s("cycles-pressure","Circular dependencies",e.realCycleCount,3,10,3,"cycle(s)"),s("complexity-pressure","Extreme complexity",e.complexity.extremeCount,3,5,2,"extreme complexity hotspot(s)"),e.gitEvidence){let R=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",R,50,10,4,"score-weighted co-changing pair(s)")}return s("similar-pressure","Similar functions",e.similarCount,Math.max(50,n*.01),8,4,"similar function pair(s)"),s("duplicate-bodies-pressure","Duplicate function bodies",e.duplicateBodies.count,Math.max(20,n*.005),8,4,"exact duplicate small-body group(s)"),s("twin-drift-pressure","Drifted twin implementations",e.twinDrift.count,Math.max(20,n*.005),8,4,"drifted twin implementation group(s)"),s("react-component-duplicates-pressure","Duplicated React components",e.reactComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated React component pair(s)"),s("react-hook-candidates-pressure","Duplicated React hook behavior",p,Math.max(10,t*.01),8,4,"duplicated React behavior pair(s)"),s("react-large-component-pressure-pressure","Large React components",e.reactLargeComponentPressure.count,Math.max(10,t*.01),4,2,"large React component pressure file(s)"),s("vue-component-duplicates-pressure","Duplicated Vue components",e.vueComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated Vue component pair(s)"),s("vue-composable-candidates-pressure","Duplicated Vue behavior",b,Math.max(10,t*.01),8,4,"duplicated Vue behavior pair(s)"),s("vue-large-view-pressure-pressure","Large Vue views",e.vueLargeViewPressure.count,Math.max(10,t*.01),4,2,"large Vue view pressure file(s)"),s("extract-pressure","Extraction candidates",e.extractCount,Math.max(50,n*.01),4,2,"extraction candidate(s)"),s("wrappers-pressure","Wrapper functions",x,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",v,50,4,2,"passthrough candidate(s)"),s("stale-abstractions-pressure","Single-consumer stale abstraction signals",e.stale.singleUse,Math.max(50,n*.02),4,2,"single-consumer stale abstraction signal(s)"),s("drift-pressure","Structural drift signals",e.drift.signal,Math.max(10,t*.1),4,2,"signal drift finding(s)"),{breakdown:r,pressure:i}}import{getHeapStatistics as yY}from"v8";var bY=64*1024*1024;function op(){let e=globalThis.gc;if(!e)return;let t=yY();t.heap_size_limit-t.used_heap_size<bY||e()}var SY=[{id:"dead-visible-references",detector:"dead",claim:"The symbol has no visible repository reference after entry, framework, and rooted-symbol exclusions.",relationRequirements:[{family:"identity",subtype:"references",minimumStrength:"exact"},{family:"execution",subtype:"call",minimumStrength:"exact"}],structuralEvidence:["entry-surface exclusions","framework/source fallback references","rooted-symbol exclusions"],calibration:"mixed",providerCoverage:"partial",nonClaims:["Absence of visible references does not prove absence of reflection, generated dispatch, or external use."],recoverWith:"scip-query evidence --symbol <symbol> --edge execution --edge runtime --edge identity --direction both --depth 2 --max-edges 100"},{id:"isolated-visible-connectivity",detector:"isolated",claim:"The callable has no visible non-self caller or callee after entry, framework, and rooted-symbol exclusions.",relationRequirements:[{family:"execution",subtype:"call",minimumStrength:"exact"},{family:"identity",subtype:"references",minimumStrength:"exact"}],structuralEvidence:["entry-surface exclusions","framework contract exclusions","source fallback callers"],calibration:"mixed",providerCoverage:"partial",nonClaims:["Visible graph isolation does not establish runtime unreachability through reflection or generated dispatch."],recoverWith:"scip-query evidence --symbol <symbol> --edge execution --edge runtime --edge identity --direction both --depth 2 --max-edges 100"},{id:"wrapper-indirection-candidate",detector:"wrapper-candidates",claim:"A small callable has one visible consumer and wrapper-shaped delegation, after boundary evidence is disclosed.",relationRequirements:[{family:"execution",subtype:"call",minimumStrength:"exact"},{family:"ownership",subtype:"contains",minimumStrength:"exact"}],structuralEvidence:["callable body shape","public and runtime-boundary signals","consumer fan-in"],calibration:"candidate",providerCoverage:"partial",nonClaims:["Wrapper shape does not prove that an API, ownership, observability, or compatibility boundary is unnecessary."],recoverWith:"scip-query inspect --symbol <symbol> --view behavior"},{id:"passthrough-forwarding-candidate",detector:"passthrough-candidates",claim:"A small callable visibly forwards to one callee, with public-facade and boundary signals disclosed.",relationRequirements:[{family:"execution",subtype:"call",minimumStrength:"exact"},{family:"contract",subtype:"uses-contract-symbol",minimumStrength:"exact"}],structuralEvidence:["statement-complete forwarding shape","public facade evidence","runtime-boundary signals"],calibration:"mixed",providerCoverage:"partial",nonClaims:["Literal forwarding does not prove the callable has no contract, naming, policy, or compatibility role."],recoverWith:"scip-query inspect --symbol <symbol> --view behavior"},{id:"stale-abstraction-candidate",detector:"stale-abstractions",claim:"A type-like abstraction has zero or one visible real consumer after re-export and ownership distinctions.",relationRequirements:[{family:"identity",subtype:"references",minimumStrength:"exact"},{family:"ownership",subtype:"contains",minimumStrength:"exact"}],structuralEvidence:["definition kind","barrel-only consumer distinction","defining-file usage"],calibration:"mixed",providerCoverage:"partial",nonClaims:["Low visible consumer count does not prove a public contract or runtime-registered type is obsolete."],recoverWith:"scip-query evidence --symbol <symbol> --edge identity --edge ownership --edge contract --direction both --depth 2 --max-edges 100"},{id:"complexity-control-pressure",detector:"complexity-hotspots",claim:"A callable concentrates local branch/control pressure and graph fan-in or fan-out.",relationRequirements:[{family:"execution",subtype:"predicate-consequence",minimumStrength:"exact"},{family:"execution",subtype:"call",minimumStrength:"exact"}],structuralEvidence:["AST branch count or disclosed regex fallback","call fan-in","callee count"],calibration:"mixed",providerCoverage:"partial",nonClaims:["Structural complexity does not establish runtime frequency, latency, defect density, or a required refactor."],recoverWith:"scip-query inspect --symbol <symbol> --view behavior"},{id:"decorative-checker-terminal-behavior",detector:"decorative-checkers",claim:"A checker-shaped callable lacks a visible failure terminal directly or through one resolved delegate.",relationRequirements:[{family:"execution",subtype:"returns",minimumStrength:"exact"},{family:"execution",subtype:"throws",minimumStrength:"exact"}],structuralEvidence:["checker naming shape","direct terminal behavior","one-hop delegate body"],calibration:"mixed",providerCoverage:"partial",nonClaims:["No visible terminal does not prove the checker cannot fail through an opaque call, exception, or process exit."],recoverWith:"scip-query inspect --symbol <symbol> --view behavior"},{id:"duplicate-structural-candidate",detector:"duplicate and similarity detectors",claim:"Two source units share the detector-specific structural or token pattern.",relationRequirements:[],structuralEvidence:["normalized source/token/JSX/template similarity"],calibration:"candidate",providerCoverage:"partial",nonClaims:["Structural similarity does not establish shared domain identity or justify consolidation."],recoverWith:"scip-query inspect --symbol <symbol-a> --symbol <symbol-b> --view behavior"}];function aI(e=new Set(["indexed-graph","source-facts"])){return SY.map(t=>{let n=t.relationRequirements.map(i=>{let o=ac(i.family,i.subtype);if(!o)throw new Error(`Detector ${t.id} names an unregistered relation ${i.family}/${i.subtype}`);if(!o.relation.evidenceStrengths.includes(i.minimumStrength))throw new Error(`Detector ${t.id} requires unsupported strength ${i.minimumStrength} for ${i.family}/${i.subtype}`);return o.provider}),r=[...new Set(n.flatMap(i=>i.requirements))].filter(i=>!e.has(i));return{...t,status:r.length>0?"unsupported":t.calibration,providerIds:[...new Set(n.map(i=>i.id))],unavailableRequirements:r}})}var vY=50,CY=25e3,xY=2500,cI=2500,lI=50,RY=10,Zc=["overview","dead","isolated","cycles","similar","duplicate-bodies","twin-drift","react-component-duplicates","react-hook-candidates","react-large-component-pressure","vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure","extract-candidates","wrapper-candidates","passthrough-candidates","stale-abstractions","drift","complexity-hotspots","git-evidence","suppressions","coverage-contracts"],EY={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:PY(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:DY(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:MY(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:TY(e,t,n)}),"duplicate-bodies":(e,t,n)=>({phase:"duplicate-bodies",duplicateBodies:AY(e,t,n)}),"twin-drift":(e,t,n)=>({phase:"twin-drift",twinDrift:FY(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:NY(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:_Y(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:OY(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:BY(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:$Y(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:jY(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:kY(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:HY(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:UY(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:qY(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:WY(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:VY(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:GY(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:zY(e,n)}),"coverage-contracts":(e,t,n)=>({phase:"coverage-contracts",coverageContracts:KY(e,n)})};function sp(e,t,n={}){return IY(e,[t],n)[0]}function IY(e,t,n={}){return wY(e,n.full!==!1,(r,i)=>{let o={...i,releaseCachesBetweenPhases:!1};return t.map(s=>EY[s](e,n.scope,o,r))})}function wY(e,t,n){let r=Ar(e),i=YY(r,t);try{return n(r,i)}finally{em(e,{semanticProvider:!0}),op()}}function ap(e){return oI(LY(e))}function LY(e){let t=Pe(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,detectorEvidence:aI(),dead:Pe(e,"dead").dead,isolated:Pe(e,"isolated").isolated,realCycleCount:Pe(e,"cycles").realCycleCount,similarCount:Pe(e,"similar").similarCount,duplicateBodies:Pe(e,"duplicate-bodies").duplicateBodies,twinDrift:Pe(e,"twin-drift").twinDrift,reactComponentDuplicates:Pe(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:Pe(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:Pe(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:Pe(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:Pe(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:Pe(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:Pe(e,"extract-candidates").extractCount,wrappers:Pe(e,"wrapper-candidates").wrappers,passthroughs:Pe(e,"passthrough-candidates").passthroughs,stale:Pe(e,"stale-abstractions").stale,drift:Pe(e,"drift").drift,complexity:Pe(e,"complexity-hotspots").complexity,gitEvidence:uI(e,"git-evidence")?.gitEvidence??null,suppressions:uI(e,"suppressions")?.suppressions??null,coverageContracts:Pe(e,"coverage-contracts").coverageContracts}}function uI(e,t){return e.find(n=>n.phase===t)}function Pe(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function PY(e,t,n){return Ie(e,n,"dead",()=>{let r=zr(e,{scope:t,...Ee.dead,scanLimit:n.candidateScanLimit,semantic:n.semantic});return el(QY(e,r.symbols))})}function DY(e,t,n){return Ie(e,n,"isolated",()=>{let r=ns(e,{scope:t,...Ee.isolated,scanLimit:n.candidateScanLimit,semantic:n.semantic});return el(ZY(e,r))})}function MY(e,t,n){return Ie(e,n,"cycles",()=>es(e,{scope:t}).filter(i=>i.kind==="real").length)}function TY(e,t,n){let r=Ie(e,n,"similar",()=>um(e,{scope:t,...Ee.similar,scanLimit:n.candidateScanLimit,semantic:n.semantic}));return Math.min(r,n.candidateResultLimit)}function kY(e,t,n){return Ie(e,n,"extract-candidates",()=>us(e,{scope:t,...Ee.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}).length)}function AY(e,t,n){return Ie(e,n,"duplicate-bodies",()=>{let r=fs(e,{scope:t,...Ee.duplicateBodies,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),i=new Set,o=0;for(let s of r)for(let a of s.functions.slice(1))i.add(a.file),o+=a.loc;return{count:r.length,loc:o,files:[...i]}})}function FY(e,t,n){return Ie(e,n,"twin-drift",()=>{let r=Uc(e,{scope:t,...Ee.twinDrift,scanLimit:n.candidateScanLimit}).filter(s=>s.relationship==="divergent"||s.relationship==="identical"),i=new Set,o=0;for(let s of r)for(let a of s.members)i.add(a.file),o+=a.loc;return{count:r.length,loc:o,files:[...i].sort()}})}function NY(e,t,n){return Ie(e,n,"react-component-duplicates",()=>{let r=ss(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return cp(r)})}function _Y(e,t,n){return Ie(e,n,"react-hook-candidates",()=>{let r=as(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return pI(r,tJ)})}function OY(e,t,n){return Ie(e,n,"react-large-component-pressure",()=>{let r=dm(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return eJ(r)})}function BY(e,t,n){return Ie(e,n,"vue-component-duplicates",()=>{let r=cs(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return cp(r)})}function $Y(e,t,n){return Ie(e,n,"vue-composable-candidates",()=>{let r=ls(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return pI(r,nJ)})}function jY(e,t,n){return Ie(e,n,"vue-large-view-pressure",()=>{let r=mm(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return el(r)})}function HY(e,t,n){return Ie(e,n,"wrapper-candidates",()=>{let r=xs(e,{scope:t,...Ee.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return mI(r,rJ)})}function UY(e,t,n){return Ie(e,n,"passthrough-candidates",()=>{let r=gs(e,{scope:t,...Ee.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return mI(r,iJ)})}function qY(e,t,n){return Ie(e,n,"stale-abstractions",()=>{let r=Cs(e,{scope:t,...Ee.stale,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}),i=r.filter(o=>o.consumers===0).length;return{count:r.length,loc:r.reduce((o,s)=>o+s.loc,0),files:[...new Set(r.map(o=>o.file))],unused:i,singleUse:r.length-i}})}function GY(e,t){return Ie(e,t,"git-evidence",()=>{let n=jt(e,{historyMode:t.gitHistoryMode}),r=n.fileChurn();if(!r)return null;let i=n.commitHistory(),o=ms(e,void 0,{limit:t.candidateResultLimit,historyMode:t.gitHistoryMode}),s={};for(let[a,c]of r)s[a]={changes:c.changes,fixChanges:c.fixChanges};return{amplification:n.changeAmplification(),hiddenCoupling:{pairCount:o.findings.length,scoreCount:lp(o.findings.reduce((a,c)=>a+dI(c),0)),top:o.findings.slice(0,5).map(a=>({fileA:a.fileA,fileB:a.fileB,together:a.together,confidence:a.confidence,focusedTogether:a.focusedTogether,broadTogether:a.broadTogether,broadCommitRatio:a.broadCommitRatio,lastTogetherAt:a.lastTogetherAt,recentTogether:a.recentTogether,commitScope:a.commitScope,recency:a.recency,scoreWeight:dI(a),subjectContext:a.subjectContext}))},fileStats:s,commitsScanned:i?.commits.length??0}})}function zY(e,t){return Ie(e,t,"suppressions",()=>{let n=Kc(e);return{total:n.total,byCategory:{...n.byCategory}}})}function KY(e,t){return Ie(e,t,"coverage-contracts",()=>{let n=e.config.coverageContracts??[],i=QE(e,n).filter(o=>o.status!=="ok");return{count:i.length,loc:0,files:[...new Set(i.map(o=>o.file))].sort()}})}function WY(e,t,n){return Ie(e,n,"drift",()=>{let r=vs(e,{scope:t,...Ee.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY,semantic:n.semantic}),i=r.results.filter(a=>a.kind!=="pattern-deviation"),o=i.filter(a=>a.actionTier==="direct").length,s=i.length-o;return{count:i.length,unusedImports:r.unusedImports,architectureViolations:r.architectureViolations,layerViolations:r.layerViolations,direct:o,signal:s}})}function VY(e,t,n){return Ie(e,n,"complexity-hotspots",()=>{let r=ip(e,{scope:t,minLoc:10,limit:n.complexityResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return{top:r.slice(0,5).map(i=>({symbol:i.shortName,score:i.score,file:i.file})),extremeCount:r.filter(i=>i.score>vY).length}})}function YY(e,t){let n=e.symbols>=CY||e.documents>=xY,r=t?Number.POSITIVE_INFINITY:lI,i=t?Number.POSITIVE_INFINITY:RY;return!n||t?{candidateScanLimit:void 0,candidateResultLimit:r,complexityResultLimit:i,semantic:!0,gitHistoryMode:t?"full":"bounded",releaseCachesBetweenPhases:!0,warnings:t&&n?["Large index detected; running health without candidate scan or result caps because full mode is enabled."]:[]}:{candidateScanLimit:cI,candidateResultLimit:r,complexityResultLimit:i,semantic:!1,gitHistoryMode:"bounded",releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${cI} symbols and reported their top ${lI} findings. Enable full mode for unbounded candidate counts.`]}}function JY(e,t){t.releaseCachesBetweenPhases&&(em(e),op())}function Ie(e,t,n,r){XY(n);try{return r()}finally{JY(e,t)}}function XY(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function QY(e,t){return t.filter(n=>!Ue(e,n.relativePath)&&!Te(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function ZY(e,t){return t.filter(n=>!Ue(e,n.relativePath)&&!Te(e,n.symbol,n.relativePath))}function el(e){let t=new Set;for(let n of e){let r=n.relativePath??n.file;r&&t.add(r)}return{count:e.length,loc:e.reduce((n,r)=>n+r.loc,0),files:[...t]}}function mI(e,t){return{...el(e),scoreCount:lp(e.reduce((r,i)=>r+t(i),0))}}function eJ(e){let t=new Map;for(let n of e)t.set(n.file,Math.max(t.get(n.file)??0,n.loc));return{count:t.size,loc:[...t.values()].reduce((n,r)=>n+r,0),files:[...t.keys()]}}function cp(e){let t=new Map;for(let n of e)t.set(n.fileA,Math.max(t.get(n.fileA)??0,n.locA)),t.set(n.fileB,Math.max(t.get(n.fileB)??0,n.locB));return{count:e.length,loc:[...t.values()].reduce((n,r)=>n+r,0),files:[...t.keys()]}}function pI(e,t){return{...cp(e),scoreCount:lp(e.reduce((r,i)=>r+t(i),0))}}function tJ(e){let t=e.sharedHooks.length>0,n=fI({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:gI(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function nJ(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=fI({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:gI(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function fI(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!yI.has(hI(t))).length+Math.min(e.functions.length,3)}function gI(e,t,n){let r=[...e,...t,...n].map(hI);return r.length>0&&r.every(i=>yI.has(i))}function hI(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function rJ(e){return e.actionTier==="signal"?.25:1}function iJ(e){return e.actionTier==="signal"?.25:1}function dI(e){return e.commitScope==="broad-sweep"?e.recency==="recent"?.25:0:e.commitScope==="mixed"?e.recency==="recent"?.5:.25:e.recency==="recent"?1:.5}function lp(e){return Math.round(e*100)/100}var yI=new Set(["add","apply","cancel","change","clear","close","create","delete","draft","edit","error","filter","form","load","loading","name","open","refresh","remove","reset","save","saving","search","select","selected","submit","toggle","update","value"]);function oJ(e,t,n,r={}){let i=lm(e,t,n,r);return i?{symbolA:i.symbolA,symbolB:i.symbolB,similarity:i.similarity,sharedCallees:i.sharedEvidence,uniqueToA:i.uniqueToA,uniqueToB:i.uniqueToB,consolidationStrategy:i.consolidationStrategy}:null}function sJ(e,t,n={}){let r=Qo(e,t,{families:["dataflow"],...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.maxEdges!==void 0?{maxEdges:n.maxEdges}:{}});return{kind:"value-flow",targets:r.targets,edges:r.edges,coverage:{status:r.coverage.status,basis:"proved-bounded-static-value-flow",analysisBasis:"partial-system-definition-use",providers:["bounded-static-value-flow","typescript-local-dependence"],supportedRelations:["compiler-identified local definitions reaching local reads through a TypeScript control-flow graph","right-hand-side local reads supplying assignments and declarations","candidate closure captures and bounded same-owner field flow with explicit evidence strength","direct argument-to-parameter forwarding at compiler-resolved calls","bounded mechanically derived static arguments","callee return value to a consumed compiler-resolved call result"],unsupportedRelations:["general heap alias and cross-instance field points-to flow","exceptional control and value flow","closure invocation order","downstream local definition-use after a call result","dynamic calls not resolved by the semantic provider"],graph:r.coverage}}}var aJ=/:\d+(?:-\d+)?$/u;function cJ(e,t,n={}){let r=n.direction??"backward",i=n.maxDepth??3;if(!Number.isSafeInteger(i)||i<0)throw new RangeError(`Dependence-slice depth must be a non-negative safe integer; received ${i}.`);let o=aJ.test(t),s=Qo(e,o?{locations:[t]}:{symbols:[t]},{families:["execution","runtime","dataflow","ownership"],maxDepth:i+1,maxEdges:n.maxEdges??200}),a=new Set(s.targets.flatMap(d=>d.nodeIds)),c=new Set(a),l=new Map;bI(s.edges,c,l,0);for(let d=1;d<=i;d+=1){let m=[];for(let p of s.edges)if(r==="backward"?c.has(p.to.id):c.has(p.from.id)){let f=r==="backward"?p.from.id:p.to.id;if(c.has(f))continue;m.push(f),l.set(p.id,d)}if(m.length===0)break;for(let p of m)c.add(p);bI(s.edges,c,l,d)}let u=s.edges.filter(d=>c.has(d.from.id)&&c.has(d.to.id)).filter(d=>l.has(d.id)||d.family==="ownership").map(d=>({...d,traversalDepth:l.get(d.id)??0,supporting:d.family!=="dataflow"&&!lJ(d)})).sort((d,m)=>d.traversalDepth-m.traversalDepth||d.family.localeCompare(m.family)||d.from.label.localeCompare(m.from.label)||d.to.label.localeCompare(m.to.label));return{kind:"dependence-slice",direction:r,criterion:t,targets:s.targets,nodeIds:[...c].sort(),edges:u,coverage:{status:s.coverage.status,criterionKind:o?"source-location-summary":"symbol-summary",basis:"partial-system-dependence-graph",analysisBasis:"typescript-cfg-reaching-definitions-plus-system-edges",providers:["typescript-local-dependence","bounded-static-value-flow"],graph:s.coverage,unsupportedRelations:["general heap alias and cross-instance field points-to flow","exceptional control and value flow","closure invocation order","downstream local definition-use after a call result","unresolved dynamic dispatch"]}}}function bI(e,t,n,r){let i=!0;for(;i;){i=!1;for(let o of e)o.family!=="ownership"||!t.has(o.from.id)||t.has(o.to.id)||(t.add(o.to.id),n.set(o.id,r),i=!0)}}function lJ(e){return e.semanticFamily==="control"&&e.sourceKind==="control-dependence"}function uJ(e,t={}){let{scope:n,limit:r}=t,i=new H(e),o=SJ([...dJ(e,n),...fJ(e,i,n)]);return vJ(o),r?o.slice(0,r):o}function dJ(e,t){let n=[];for(let r of mJ(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||td(e,r.barrel_path)||W(e,r.barrel_path)&&Bs(e,r.barrel_path).length===0)continue;let i=pJ(e,r),o=i?.barrel_consumers??0,s=i?.direct_consumers??0;o!==0||s!==0||n.push({barrelFile:r.barrel_path,symbol:r.symbol,shortName:T(r.symbol),originalFile:r.original_path,barrelConsumers:o,directConsumers:s,...vI(e,r.barrel_path)})}return n}function mJ(e,t){let n=t?"AND barrel_d.relative_path LIKE ?":"",r=t?[`%${t}%`]:[];return e.all(`WITH barrel_refs AS MATERIALIZED (
460
- SELECT DISTINCT
461
- barrel_d.id AS barrel_doc_id,
462
- barrel_d.relative_path AS barrel_path,
463
- m.symbol_id
464
- FROM documents barrel_d
465
- JOIN chunks c ON c.document_id = barrel_d.id
466
- JOIN mentions m ON m.chunk_id = c.id
467
- WHERE m.role != 1
468
- AND (barrel_d.relative_path LIKE '%/index.ts'
469
- OR barrel_d.relative_path LIKE '%/index.js'
470
- OR barrel_d.relative_path = 'index.ts'
471
- OR barrel_d.relative_path = 'index.js')
472
- ${e.pathExclusionsFor("barrel_d")}
473
- ${n}
474
- ),
475
- sym_def AS MATERIALIZED (
476
- SELECT m2.symbol_id, c2.document_id
477
- FROM barrel_refs br
478
- -- Keep the bounded barrel-symbol set on the outer side. An ordinary
479
- -- JOIN lets SQLite scan every definition mention before applying the
480
- -- barrel-symbol bloom filter on large indexes.
481
- CROSS JOIN mentions m2 ON m2.symbol_id = br.symbol_id
482
- AND m2.role = 1
483
- JOIN chunks c2 ON m2.chunk_id = c2.id
484
- GROUP BY m2.symbol_id
485
- )
486
- SELECT DISTINCT
487
- br.barrel_doc_id,
488
- br.barrel_path,
489
- gs.id AS symbol_id,
490
- gs.symbol AS symbol,
491
- orig_d.id AS original_doc_id,
492
- orig_d.relative_path AS original_path
493
- FROM barrel_refs br
494
- JOIN global_symbols gs ON br.symbol_id = gs.id
495
- JOIN sym_def ON sym_def.symbol_id = gs.id
496
- JOIN documents orig_d ON sym_def.document_id = orig_d.id
497
- WHERE orig_d.id != br.barrel_doc_id
498
- ${e.pathExclusionsFor("orig_d")}
499
- ${e.symbolNoiseFor("gs")}
500
- -- Only function-level symbols (ending with ().), not module-level
501
- AND gs.symbol LIKE '%().'
502
- ORDER BY br.barrel_path, gs.symbol`,...r)}function pJ(e,t){return e.get(`SELECT
503
- SUM(CASE WHEN uses_barrel = 1 THEN 1 ELSE 0 END) AS barrel_consumers,
504
- SUM(CASE WHEN uses_barrel = 0 THEN 1 ELSE 0 END) AS direct_consumers
505
- FROM (
506
- SELECT
507
- consumer_d.id AS consumer_doc_id,
508
- MAX(CASE WHEN EXISTS (
509
- SELECT 1
510
- FROM mentions barrel_m
511
- JOIN chunks barrel_c ON barrel_m.chunk_id = barrel_c.id
512
- WHERE barrel_c.document_id = consumer_d.id
513
- AND barrel_m.role != 1
514
- AND barrel_m.symbol_id IN (
515
- SELECT m2.symbol_id
516
- FROM mentions m2
517
- JOIN chunks c2 ON m2.chunk_id = c2.id
518
- WHERE c2.document_id = ?
519
- AND m2.role != 1
520
- )
521
- ) THEN 1 ELSE 0 END) AS uses_barrel
522
- FROM mentions ref_m
523
- JOIN chunks ref_c ON ref_m.chunk_id = ref_c.id
524
- JOIN documents consumer_d ON ref_c.document_id = consumer_d.id
525
- WHERE ref_m.symbol_id = ?
526
- AND ref_m.role != 1
527
- AND consumer_d.id != ?
528
- AND consumer_d.id != ?
529
- ${e.pathExclusionsFor("consumer_d")}
530
- GROUP BY consumer_d.id
531
- )`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function fJ(e,t,n){let r=[],i=bJ(e);for(let o of gJ(e,n))CI(i,o,o)>0||r.push(...hJ(e,t,o,i));return r}function gJ(e,t){return Z(e,{scope:t,includeIgnored:!1}).filter(n=>Bs(e,n).length>0||Qi(e,n).length>0)}function hJ(e,t,n,r){let i=Bs(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>SI(e,t,n,s.sourcePath,r,[yJ(s.specifier)])),o=Qi(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>SI(e,t,n,s.sourcePath,r,s.kind==="named"&&s.names.length>0?s.names:[s.kind==="star"?`* from ${s.sourcePath}`:`* namespace from ${s.sourcePath}`]));return[...i,...o]}function SI(e,t,n,r,i,o){let s=t.definitionsForFile(r);return o.map(a=>{let c=s.find(l=>l.leaf===a);return{barrelFile:n,symbol:c?.symbol??`source-reexport:${n}:${a}`,shortName:c?T(c.symbol):a,originalFile:r,barrelConsumers:0,directConsumers:CI(i,r,n),...vI(e,n)}})}function yJ(e){return e.split("::").at(-1)?.split("/").at(-1)?.replace(/\.[^.]+$/,"")??e}function vI(e,t){return xn(e,t)?{actionTier:"signal",surfaceEvidence:["barrel file is declared on the package public surface"],recommendation:"Review the package API before removing this re-export; local consumers are zero, but external consumers may import through the public barrel."}:{actionTier:"direct",surfaceEvidence:[],recommendation:"Remove this unused re-export when the barrel is not part of an external API surface."}}function bJ(e){let t=new Map;for(let n of Z(e,{includeIgnored:!1}))for(let r of ae(e,n)){if(!r.sourcePath)continue;let i=t.get(r.sourcePath)??new Set;i.add(n),t.set(r.sourcePath,i)}return t}function CI(e,t,n){let r=e.get(t);return r?r.size-(r.has(n)?1:0):0}function SJ(e){let t=new Set,n=[];for(let r of e){let i=`${r.barrelFile}|${r.symbol}|${r.originalFile}`;t.has(i)||(t.add(i),n.push(r))}return n}function vJ(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function CJ(e,t={}){let{samples:n=50,scope:r,maxDisagreements:i=5}=t,o=new H(e),s=xJ(o.productionCallableDefinitions({scope:r,minLoc:2,requireFunctionLikeSymbol:!0}),n),a=RJ(e,s);if(s.length===0||!a)return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let c={references:xI(),callees:xI()},l=[],u=0,d=a==="semantic"?wa(e,s):new Map,m=a==="source"?wJ(e,o,s):null;for(let p of s){let f=tl(p,a==="semantic"?Ia(e,p).map(x=>x.file):[...m?.referencesBySymbolId.get(p.symbolId)??[]]),g=tl(p,a==="semantic"?(d.get(p.symbolId)??[]).map(x=>x.file):[...m?.calleesBySymbolId.get(p.symbolId)??[]]);u+=1;let h=tl(p,jn(e,p,{semanticEvidence:re}).map(x=>x.file)),b=tl(p,(o.calleeMap([p],{semantic:!1}).get(p.symbolId)??[]).map(x=>x.file)),S=up(a,"references"),y=up(a,"callees");RI(c.references,p,"references",h,f,S,l),RI(c.callees,p,"callees",b,g,y,l)}return l.sort((p,f)=>f.cheapOnly.length+f.oracleOnly.length-(p.cheapOnly.length+p.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?mp(u/s.length):0,oracleKind:a,scores:["references","callees"].map(p=>IJ(p,c[p],a)),topDisagreements:l.slice(0,i)}}function xI(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0,skippedOraclePartial:0}}function xJ(e,t){let n=[...e].sort((o,s)=>o.symbolId-s.symbolId);if(n.length<=t)return n;let r=n.length/t,i=[];for(let o=0;o<t;o++)i.push(n[Math.floor(o*r)]);return i}function RJ(e,t){let n=t[0];if(!n)return null;if(dp(e,n))return"source";try{if(st(e).capability("semantic-references",n.relativePath).available)return"semantic"}catch{}return t.some(r=>dp(e,r))?"source":null}function tl(e,t){let n=new Set;for(let r of t)r!==e.relativePath&&n.add(r);return n}function RI(e,t,n,r,i,o,s){if(!o&&i.size===0){e.skippedOraclePartial+=1;return}e.comparedSymbols+=1,e.cheapTotal+=r.size,e.oracleTotal+=i.size;let a=[],c=[];for(let l of r)i.has(l)?e.agreed+=1:a.push(l);for(let l of i)r.has(l)||c.push(l);(a.length>0||c.length>0)&&s.push({symbol:T(t.symbol),question:n,cheapOnly:a,oracleOnly:c})}var EJ={references:!0,callees:!1};function IJ(e,t,n){let r=t.oracleTotal>0?t.agreed/t.oracleTotal:1,i=t.cheapTotal-t.agreed,o=up(n,e);return{question:e,comparedSymbols:t.comparedSymbols,precision:o&&t.cheapTotal>0?mp(t.agreed/t.cheapTotal):null,recall:mp(r),unverified:i,skippedOraclePartial:t.skippedOraclePartial}}function up(e,t){return e==="semantic"?EJ[t]:!1}function dp(e,t){return se(t.relativePath)==="clojure"&&K(e,t.relativePath)!==null}function wJ(e,t,n){let r=new Map,i=new Map,o=n.filter(c=>dp(e,c)),s=new Map;for(let c of o){let l=s.get(c.leaf)??[];l.push(c),s.set(c.leaf,l)}for(let c of t.sourceFiles()){if(se(c)!=="clojure")continue;let l=K(e,c);if(l)for(let u of l.fileIdentifiers)for(let d of s.get(u)??[])EI(r,d.symbolId,c)}let a=new Map;for(let c of t.scopedDefinitions()){if(se(c.relativePath)!=="clojure")continue;let l=a.get(c.leaf)??[];l.push(c),a.set(c.leaf,l)}for(let c of o){let l=K(e,c.relativePath);if(l){for(let u of l.callSites)if(!(u.line<c.startLine||u.line>c.endLine))for(let d of a.get(u.calleeLeaf)??[])EI(i,c.symbolId,d.relativePath)}}return{referencesBySymbolId:r,calleesBySymbolId:i}}function EI(e,t,n){let r=e.get(t);if(r){r.add(n);return}e.set(t,new Set([n]))}function mp(e){return Math.round(e*1e3)/1e3}var LJ=new Set(Kt());function PJ(e,t={}){let{scope:n,minLoc:r=1,limit:i,scanLimit:o,maxShapeFrequency:s=12}=t,a=t.semantic!==!1,c=TJ(e,DJ(e,{scope:n,minLoc:r,scanLimit:o}),{semantic:a,maxShapeFrequency:s}),l=AJ(c);return i?l.slice(0,i):l}function DJ(e,t){let n=Le(e,{scope:t.scope}).filter(r=>MJ(r)&&!e.isIgnored(r.relativePath)).filter(r=>ee(r)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((r,i)=>ee(i)-ee(r)||r.relativePath.localeCompare(i.relativePath)),he(n,t.scanLimit)}function MJ(e){return!e.isFunctionLike||je(e.symbol)?!1:e.kind===null||LJ.has(e.kind)}function TJ(e,t,n){let r=[];for(let s of t){let a=NJ(e,s,n);a&&r.push({signature:a,definition:s,fn:kJ(s)})}let i=new Map;for(let s of r)i.set(s.signature,(i.get(s.signature)??0)+1);let o=new Map;for(let s of r){let a=FJ(s.fn.loc),c=(i.get(s.signature)??0)>n.maxShapeFrequency,l=c?qm(e,s.definition):null;if(c&&!l)continue;let u=c?`${s.signature}\0body\0${l}`:`${s.signature}\0band\0${a}`,d=o.get(u)??{signature:s.signature,locBand:a,exactBody:c,functions:[]};d.functions.push(s.fn),o.set(u,d)}return[...o.values()]}function kJ(e){return{symbol:e.symbol,shortName:T(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:ee(e)}}function AJ(e){let t=[];for(let n of e)n.functions.length>=2&&t.push(n);return t.sort((n,r)=>{let i=r.functions.length-n.functions.length;if(i!==0)return i;let o=n.functions.reduce((a,c)=>a+c.loc,0);return r.functions.reduce((a,c)=>a+c.loc,0)-o}),t}function FJ(e){return e<=5?"<=5":e<=20?"6-20":">20"}function NJ(e,t,n){if(n.semantic){let o=wy(e,t);if(o)return o}let r=_J(t.documentation),i=r?$J(r):null;return i||jJ(OJ(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function _J(e){return oi(si(e))}function OJ(e,t,n,r,i){let o=W(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=UJ(s,n,r,i);for(let c of a){let l=Math.min(s.length-1,Math.max(c,c+4)),u="";for(let d=c;d<=l;d+=1){let m=s[d]?.trim();if(m&&(u=u?`${u} ${m}`:m,BJ(u)))return u}if(u&&u.includes("("))return u}return null}function BJ(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||lf(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function $J(e){if(!e||!e.trim())return null;let t=e.replace(/^```\w*\s*/,"").replace(/\s*```$/,"").replace(/^\(method\)\s*/,"").replace(/^\(property\)\s*/,"").replace(/^\(function\)\s*/,"").replace(/^\(class\)\s*/,"").replace(/^\(interface\)\s*/,"").replace(/^\(enum\)\s*/,"").replace(/^\(type alias\)\s*/,"").replace(/^\(const\)\s*/,"").replace(/^\(var\)\s*/,"").trim(),n=t.indexOf("(");return n===-1||(t=t.slice(n),t=t.replace(/\s+/g,"").toLowerCase(),t.length<3)?null:t}function jJ(e,t){if(!e||!e.trim())return null;let n=e.replace(/\s+/g," ").trim(),r=n.indexOf("(");if(r===-1)return null;let i=n.slice(0,r),s=new RegExp(`\\b${Ce(t)}\\b`,"i").exec(i);s&&typeof s.index=="number"&&(i=i.slice(0,s.index)),i=i.replace(/\b(public|private|protected|internal|final|static|abstract|sealed|virtual|override|async|suspend|inline|constexpr|consteval|constinit|const|pub|fn|function|def|sub|friend|shared|readonly|new|open|partial|export)\b/gi," ").replace(/\s+/g," ").trim();let a=HJ(n.slice(r)).replace(/\)\s*=\s*[\s\S]*$/,")").replace(/\s+throws\s+[^={]+$/i,"").replace(/\s+where\s+.+$/i,"").replace(/\s+/g," ").trim();if(!a.startsWith("("))return null;let c=`${i?`${i} `:""}${a}`.replace(/\s+/g,"").toLowerCase();return c.length>=3?c:null}function HJ(e){let t=0,n=0,r=0,i=0,o=null,s=!1;for(let a=0;a<e.length;a+=1){let c=e[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c===o&&(o=null);continue}if(c==='"'||c==="'"||c==="`"){o=c;continue}if(c==="(")t+=1;else if(c===")")t=Math.max(0,t-1);else if(c==="[")r+=1;else if(c==="]")r=Math.max(0,r-1);else if(c==="<")i+=1;else if(c===">")i=Math.max(0,i-1);else if(c==="{"){if(t===0&&r===0&&i===0)return e.slice(0,a);n+=1}else if(c==="}")n=Math.max(0,n-1);else if(c==="="&&e[a+1]===">"&&t===0&&n===0&&r===0&&i===0)return e.slice(0,a)}return e}function UJ(e,t,n,r){let i=Ce(r),o=new RegExp(`\\b${i}\\b\\s*\\(`,"i"),s=new RegExp(`\\bdef\\s+${i}\\b`,"i"),a=[],c=new Set,l=Math.max(0,Math.min(t,e.length-1)),u=Math.max(l,Math.min(e.length-1,Math.max(n,t+4)));for(let d=l;d<=u;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!c.has(d)&&(c.add(d),a.push(d))}for(let d=0;d<e.length;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!c.has(d)&&(c.add(d),a.push(d))}return a}import{spawnSync as Phe}from"child_process";import{execFileSync as Zge}from"child_process";import{createHash as the}from"crypto";import{lstatSync as rhe,readlinkSync as ihe,readdirSync as ohe,realpathSync as she,statSync as ahe}from"fs";import{dirname as lhe,isAbsolute as uhe,join as dhe,posix as mhe,relative as phe,resolve as fhe,sep as ghe}from"path";var yhe=512*1024*1024;function II(e){return vr({version:e.version,...e.base?{base:e.base}:{},files:[...e.files].sort((t,n)=>t.path.localeCompare(n.path))})}function pp(e){return JSON.stringify({...e.clojureConfigPath?{clojureConfigPath:e.clojureConfigPath}:{},files:[...e.files].sort((t,n)=>t.path.localeCompare(n.path)).map(t=>({hash:t.hash,path:t.path,size:t.size})),languages:[...e.languages].sort(),pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),version:e.version})}var GJ="scip-query:collaboration-domain",zJ="scip-query:workspace-instance",KJ="scip-query:index-generation",WJ="scip-query:repository-content",wI="scip-query:index-inputs",VJ="scip-query:index-inputs";function Vr(e){let t=e.snapshot,n=e.observedSourceKinds?new Set(e.observedSourceKinds):void 0,r=e.gitContext??t?.gitContext??(n?.has("live-workspace")?pl(e.projectRoot):void 0),i=e.collaborationDomainId??e.db?.config.collaborationDomainId,o=i?Tr(GJ,1,i):void 0,s=r?Tr(zJ,1,r.worktreeId):void 0,a=t?Tr(WJ,1,II(t.repositoryContent)):void 0,c=t?Tr(wI,t.indexInputs.version,pp(t.indexInputs)):void 0,l=e.db&&t?JJ(e.db.generation.metadataRaw):void 0,u=e.db?{generation:Tr(KJ,1,e.db.generation.identity),...l?{inputs:l}:{},source:e.db.generation.source}:void 0,d=n??new Set([...u?["index-generation"]:[],...a?["repository-snapshot"]:s?["live-workspace"]:[]]),m=[...u&&d.has("index-generation")?[{kind:"index-generation",identity:u.generation}]:[],...a&&d.has("repository-snapshot")?[{kind:"repository-snapshot",identity:a}]:[],...s&&d.has("live-workspace")?[{kind:"live-workspace",identity:s}]:[],...d.has("process")?[{kind:"process"}]:[]],p=[...u&&d.has("index-generation")?[{source:"index-generation",kind:u.source==="immutable"?"immutable":"not-established"}]:[],...a&&d.has("repository-snapshot")?[{source:"repository-snapshot",kind:"fixed-snapshot"}]:[],...s&&d.has("live-workspace")?[{source:"live-workspace",kind:"not-established"}]:[],...d.has("process")?[{source:"process",kind:"not-established"}]:[]];return m.length===0&&(m.push({kind:"process"}),p.push({source:"process",kind:"not-established"})),{schemaVersion:er,observedAt:(e.observedAt??(t?new Date(t.capturedAt):new Date)).toISOString(),facts:{...o?{collaborationDomain:o}:{},...s?{workspaceInstance:s}:{},...a?{wholeContent:a}:{},...c?{relevantInputs:[{subject:VJ,identity:c}]}:{},...u?{index:u}:{}},observedSources:m,stabilityProofs:p,...r?{diagnostics:{clean:r.clean,...r.headCommit?{headCommit:r.headCommit}:{},...r.treeOid?{treeOid:r.treeOid}:{}}}:{}}}function YJ(e){return Vr({projectRoot:e.projectRoot,db:e.db,...e.gitContext?{gitContext:e.gitContext}:{},...e.observedAt?{observedAt:e.observedAt}:{},observedSourceKinds:["index-generation"]})}function Ihe(){let e=ja();if(!e)return Vr({projectRoot:$a(),observedSourceKinds:["process"]});let t=e.config.projectRoot,n=pl(t);return YJ({projectRoot:t,db:e,...n?{gitContext:n}:{}})}function JJ(e){if(!e)return;let t=yr(e);if(t.kind!=="legacy"&&t.kind!=="supported")return;let n=Wi(t.metadata.fingerprint);return n&&Number.isSafeInteger(n.version)&&n.version>0?Tr(wI,n.version,pp(n)):void 0}var gp="scip-query-isolated-analysis",hp=1;function XJ(e){let t=[...e??[]];return t.includes("--json")?t:["--json",...t]}var ln=class extends Error{constructor(n,r,i=!0){super(`${n} timed out after ${r}ms.`);this.label=n;this.timeoutMs=r;this.reaped=i;this.name="IsolatedProcessTimeoutError"}label;timeoutMs;reaped;timedOut=!0};function _he(e,t){let n=ja(),r={protocol:gp,schemaVersion:hp,producer:{name:"scip-query",version:hr},command:e,result:t,...n?{observationReceipt:Vr({projectRoot:n.config.projectRoot,db:n,observedSourceKinds:["index-generation"]})}:{}};Yu(JSON.stringify(r))}function LI(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Es(e){let t=e.timeoutMs??Qf.analysis,n=e.maxBuffer??10*1024*1024;return eg({command:process.execPath,args:[...process.execArgv,e.cliPath,e.command,...XJ(e.args)],cwd:process.cwd(),env:e.env??process.env,label:e.label,timeoutMs:t,maxStdoutBytes:n,maxStderrBytes:n}).catch(r=>{throw r instanceof Zf&&r.kind==="timeout"?new ln(e.label,t,r.reaped):r}).then(r=>{let i=r.stderr.trim();if(r.status!==0)throw new Error(`${e.label} failed${i?`:
532
- ${i}`:""}`);return QJ(r.stdout,e)})}function QJ(e,t){let n;try{n=JSON.parse(e)}catch(i){throw new Error(`${t.label} returned invalid JSON: ${i instanceof Error?i.message:i}`,{cause:i})}if(!Q(n))throw new Error(`${t.label} returned a non-object isolated-analysis message.`);if(n.protocol!==gp)throw new Error(`${t.label} returned protocol ${fp(n.protocol)}; expected ${gp}.`);if(n.schemaVersion!==hp)throw new Error(`${t.label} returned unsupported isolated-analysis schemaVersion ${fp(n.schemaVersion)}; expected ${hp}.`);if(!ZJ(n.producer))throw new Error(`${t.label} did not identify a scip-query producer version.`);if(n.command!==t.command)throw new Error(`${t.label} returned result for command ${fp(n.command)}; expected ${t.command}.`);if(!Object.hasOwn(n,"result"))throw new Error(`${t.label} omitted the isolated-analysis result.`);let r=n.observationReceipt;if(r!==void 0&&(!Pa(r)||r.schemaVersion!==2))throw new Error(`${t.label} returned an invalid observation receipt.`);return{result:n.result,...r?{observationReceipt:r}:{}}}function ZJ(e){return Q(e)&&e.name==="scip-query"&&typeof e.version=="string"&&e.version.length>0}function fp(e){return typeof e=="string"?JSON.stringify(e):String(e)}async function yp(e,t,n){let r=new Array(e.length),i=0;async function o(){for(;i<e.length;){let s=i++;r[s]=await n(e[s])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),r}function PI(e,t){let n=new Set,r=[];for(let i of e){if(n.has(i))continue;let o=t.find(a=>a.has(i));if(!o){n.add(i),r.push([i]);continue}let s=e.filter(a=>o.has(a));s.forEach(a=>n.add(a)),r.push(s)}return r}import{spawnSync as e5}from"child_process";import{existsSync as t5,mkdirSync as n5,renameSync as r5,writeFileSync as i5}from"fs";import{dirname as DI,join as o5}from"path";var nl=5,s5="health-report-cache.json";function bp(e,t,n,r=u5()){let i=mn(e);return i?{version:nl,projectFingerprint:i,cliVersion:n,scope:t.scope??null,full:t.full===!0,phaseTimeoutMs:t.phaseTimeoutMs??null,gitHead:r.gitHead(e.config.projectRoot)}:null}function MI(e,t,n=FI()){let r=kI(e),i=AI(t),o=!1;return N("health.report-cache.read",()=>{if(!n.existsSync(r))return null;try{let s=JSON.parse(n.readFile(r));return!a5(s)||s.keyHash!==i?null:(o=!0,s.report)}catch{return null}},()=>({available:!0,hit:o,keyHash:i}))}function TI(e,t,n,r=FI()){let i=kI(e),o={version:nl,keyHash:AI(t),key:t,writtenAt:r.nowIso(),report:n};r.mkdirSync(DI(i),{recursive:!0});let s=`${i}.${process.pid}.${Date.now()}.tmp`;r.writeFileSync(s,JSON.stringify(o)),r.renameSync(s,i)}function kI(e){return o5(DI(e.config.dbPath),s5)}function AI(e){return qt(JSON.stringify(e))}function a5(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===nl&&typeof t.keyHash=="string"&&c5(t.key)&&typeof t.writtenAt=="string"&&l5(t.report)}function c5(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===nl&&typeof t.projectFingerprint=="string"&&typeof t.cliVersion=="string"&&(t.scope===null||typeof t.scope=="string")&&typeof t.full=="boolean"&&(t.phaseTimeoutMs===null||typeof t.phaseTimeoutMs=="number")&&(t.gitHead===null||typeof t.gitHead=="string")}function l5(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.score=="number"&&typeof t.riskScore=="number"&&typeof t.hygieneScore=="number"&&typeof t.overview=="object"&&typeof t.findings=="object"&&Array.isArray(t.scoreBreakdown)&&Array.isArray(t.actions)&&Array.isArray(t.pressure)&&Array.isArray(t.topComplexity)&&Array.isArray(t.detectorEvidence)}function u5(){return{gitHead(e){let t=e5("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",timeout:3e4,killSignal:"SIGKILL"});return t.status===0?t.stdout.trim():null}}}function FI(){return{existsSync:t5,mkdirSync:n5,readFile:e=>Ve(e,"health report cache"),renameSync:r5,writeFileSync:i5,nowIso:()=>new Date().toISOString()}}var OI="__health-phase",p5="__health-semantic-prewarm",f5="__diff-impact-batch",g5=128,h5=1,y5=1,b5=25e3,S5=2500,Sp=2500,v5=4,C5=12,NI=1,x5=6144,R5=10*6e4,E5=3e4,I5=8192,w5=10*6e4,BI=new Set(["react-component-duplicates","react-hook-candidates","react-large-component-pressure"]),$I=new Set(["vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure"]),L5=new Set([...$I,"suppressions"]),P5=new Set(["similar","extract-candidates"]),rl=2,_I=Ji({kind:"health-semantic-prewarm",invalidation:$e("health-semantic-prewarm"),serialize:e=>JSON.stringify(e),deserialize:D5});function D5(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return n.version!==rl||typeof n.definitions!="number"||!Number.isFinite(n.definitions)||typeof n.referenceCacheWrites!="number"||!Number.isFinite(n.referenceCacheWrites)||typeof n.referenceIncomplete!="number"||!Number.isFinite(n.referenceIncomplete)||typeof n.calleeRows!="number"||!Number.isFinite(n.calleeRows)||typeof n.warmedAt!="number"||!Number.isFinite(n.warmedAt)?null:{version:rl,definitions:n.definitions,referenceCacheWrites:n.referenceCacheWrites,referenceIncomplete:n.referenceIncomplete,calleeRows:n.calleeRows,warmedAt:n.warmedAt}}catch{return null}}function uye(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
533
- `)}function M5(e){let t=Ar(e);return t.symbols>=b5||t.documents>=S5}function dye(e,t,n,r={}){if(!M5(e))return{semantic:!0};if(n)return t==="dead"?(r.quiet||console.error("Large index detected; dead is scanning all candidates with semantic enrichment disabled to keep memory bounded."),{semantic:!1}):(r.quiet||console.error(`Large index detected; ${t} is running the unbounded semantic pass because --full was supplied.`),{semantic:!0});if(!r.quiet){let i=t==="inspect"?"Use --full only when every omitted semantic candidate can change the decision; it does not override source or behavior materialization ceilings.":t==="dead"?'Run "scip-query dead --full" for an unbounded candidate scan; semantic enrichment remains disabled on large indexes to keep memory bounded.':`Run "scip-query ${t} --full" for the unbounded semantic pass.`;console.error(`Large index detected; ${t} is using its bounded default analysis with semantic enrichment disabled. Candidate scans, when this command uses one, are capped at ${Sp}. `+i)}return{scanLimit:Sp,semantic:!1,analysisBudget:{scanLimit:Sp,semanticEnrichment:!1,reason:t==="dead"?"large index default budget; pass --full for an unbounded memory-safe candidate scan":"large index default budget; pass --full for unbounded semantic analysis"}}}var T5={env:process.env,projectFingerprint:mn,semanticEngineFingerprint:O5,readMarker:(e,t,n)=>_I.read(e,t,n),writeMarker:(e,t,n,r)=>_I.write(e,t,n,r),candidateDefinitions:(e,t)=>new H(e).scopedDefinitions(t.scope).filter(n=>He(n.relativePath)!==null),materializeReferences:(e,t,n)=>st(e).materializeReferences(t,n),materializeCallees:ku,releaseSemanticMemory:e=>Vi(e,{groups:["semantic-provider"]}),heapUsedFraction:()=>{let e=m5();return e.heap_size_limit>0?e.used_heap_size/e.heap_size_limit:0}},k5=256,A5=.6;function F5(e,t=k5){if(!Number.isSafeInteger(t)||t<1)throw new Error(`Callee prewarm batch size must be a positive safe integer; received ${t}.`);let n=new Map;for(let s of e){let a=n.get(s.relativePath);a?a.push(s):n.set(s.relativePath,[s])}let r=[],i=[],o=0;for(let s of n.values())o>=t&&(r.push(i),i=[],o=0),i.push(...s),o+=1;return i.length>0&&r.push(i),r}function mye(e,t,n=T5){if(t.full!==!0)return fr("default-mode");if((n.env??process.env).SCIP_QUERY_HEALTH_SEMANTIC_PREWARM==="0")return fr("disabled");let r=fr("error");return N("health.semantic-prewarm",()=>{try{r=N5(e,t,n)}catch(i){r=fr("error",{error:i instanceof Error?i.message:String(i)})}return r},()=>B5(r))}function N5(e,t,n){let r=n.projectFingerprint(e);if(!r)return fr("missing-project-fingerprint");let i=_5(t,n.semanticEngineFingerprint(e)),o=n.readMarker(e,i,r);if(o&&o.referenceIncomplete===0)return fr("cache-hit");let s=[];if(s=N("health.semantic-prewarm.candidate-definitions",()=>(s=n.candidateDefinitions(e,t),s),()=>({definitions:s.length})),s.length===0)return fr("no-semantic-definitions");let a=0,c=N("health.semantic-prewarm.references",()=>{let m=n.materializeReferences(e,s,{prefetchCallees:!1});return a=m.cacheHits+m.cacheWrites+m.inMemoryHits,m},()=>({definitions:s.length,rows:a}));if(c.cacheHits+c.cacheWrites+c.inMemoryHits===0&&c.misses+c.unkeyed>0)return fr("provider-unavailable",{definitions:s.length,referenceMisses:c.misses});N("health.semantic-prewarm.release-reference-memory",()=>n.releaseSemanticMemory?.(e));let u=0,d=0;return N("health.semantic-prewarm.callees",()=>{for(let m of F5(s))u+=n.materializeCallees(e,m).size,(n.heapUsedFraction?.()??0)>=A5&&(n.releaseSemanticMemory?.(e),d+=1)},()=>({definitions:s.length,rows:u,releases:d})),c.incomplete>0?{status:"partial",reason:"incomplete-references",definitions:s.length,referenceCacheHits:c.cacheHits,referenceCacheWrites:c.cacheWrites,referenceMisses:c.misses,referenceIncomplete:c.incomplete,calleeRows:u}:(N("health.semantic-prewarm.marker-write",()=>n.writeMarker(e,i,r,{version:rl,definitions:s.length,referenceCacheWrites:c.cacheWrites,referenceIncomplete:c.incomplete,calleeRows:u,warmedAt:Date.now()})),{status:"warmed",reason:"cache-miss",definitions:s.length,referenceCacheHits:c.cacheHits,referenceCacheWrites:c.cacheWrites,referenceMisses:c.misses,referenceIncomplete:c.incomplete,calleeRows:u})}function _5(e,t){return JSON.stringify({version:rl,cliVersion:hr,semanticEngineFingerprint:t,scope:e.scope??null})}function O5(e){return qt(JSON.stringify({kind:"health-semantic-prewarm-engine",rust:wr(e.config.projectRoot)}))}function fr(e,t={}){return{status:"skipped",reason:e,definitions:0,referenceCacheHits:0,referenceCacheWrites:0,referenceMisses:0,referenceIncomplete:0,calleeRows:0,...t}}function B5(e){return{status:e.status,reason:e.reason,definitions:e.definitions,referenceCacheHits:e.referenceCacheHits,referenceCacheWrites:e.referenceCacheWrites,referenceMisses:e.referenceMisses,referenceIncomplete:e.referenceIncomplete,calleeRows:e.calleeRows,error:e.error}}function Cp(e){return Ku(t=>{let n=Vr({projectRoot:t.config.projectRoot,db:t,observedSourceKinds:["index-generation"]});return{value:e(t),anchor:{database:{config:t.config,generation:t.generation},generationDigest:n.facts.index.generation.digest}}})}function il(e,t,n){let r=e[0];if(!r)throw new Error("An evidence-bound analysis requires at least one index observation anchor.");let i=r.generationDigest,o=e.every(a=>a.generationDigest===i),s=t.every(a=>a?.facts.index?.generation.digest===i);return Vr({projectRoot:r.database.config.projectRoot,...o&&s?{db:r.database}:{},observedSourceKinds:n})}async function pye(e){return(await $5(e)).result}async function $5(e){let t=Y5(e),n={...e,phaseTimeoutMs:t??null},r=Cp(b=>{let S=bp(b,n,hr);if(!S)return null;let y=MI(b,S);return y||null});if(r.value)return{result:r.value,observationReceipt:il([r.anchor],[],["index-generation","live-workspace"])};let i=Cp(b=>({applicability:G5(b,e),overview:sp(b,"overview",e)})),{applicability:o,overview:s}=i.value,a=[r.anchor,i.anchor],c=new Map;c.set("overview",s);let l=Zc.filter(b=>b==="overview"?!1:z5(b,o)?!0:(c.set(b,Yr(b)),!1)),u=K5(l),d=[],m;if(e.full)try{m=await j5(e)}catch(b){d.push(`Health semantic prewarm omitted: ${xp(b)}.`)}let p=e.full?X5(u.length):J5(u.length),f=await yp(u,p,b=>W5(b,e,t));if(f.flatMap(b=>b.result).forEach(b=>{b.healthPhaseMeta&&d.push(e.full?`Health phase "${b.phase}" omitted after a bounded worker failure: ${b.healthPhaseMeta.reason}.`:`Health phase "${b.phase}" deferred: ${b.healthPhaseMeta.reason}. Run health --full for exhaustive analysis.`),c.set(b.phase,b)}),d.length>0){let b=c.get("overview");c.set("overview",{...b,warnings:[...b.warnings,...d]})}let h=ap(Zc.map(b=>c.get(b)));return Ku(b=>{let S=bp(b,n,hr);S&&TI(b,S,h)}),{result:h,observationReceipt:il(a,[m?.observationReceipt,...f.map(b=>b.observationReceipt)],["index-generation","live-workspace"])}}function j5(e){let t=process.argv[1]??ol(import.meta.url),n=["--full"];return e.scope&&n.push("--scope",e.scope),Es({cliPath:t,command:p5,args:n,env:{...process.env,NODE_OPTIONS:`--max-old-space-size=${H5()}`},label:"Health semantic prewarm",timeoutMs:U5()})}function H5(e=process.env){let t=Number.parseInt(e.SCIP_QUERY_HEALTH_SEMANTIC_PREWARM_HEAP_MB??"",10);return Number.isSafeInteger(t)&&t>0?t:I5}function U5(e=process.env){let t=Number.parseInt(e.SCIP_QUERY_HEALTH_SEMANTIC_PREWARM_TIMEOUT_MS??"",10);return Number.isSafeInteger(t)&&t>0?t:w5}function q5(e=process.env){let t=Number.parseInt(e.SCIP_QUERY_HEALTH_FULL_PHASE_HEAP_MB??"",10);return Number.isSafeInteger(t)&&t>0?t:x5}function G5(e,t){return Os(e,{scope:t.scope})}function z5(e,t){return BI.has(e)?t.react:$I.has(e)?t.vue:!0}function K5(e){return PI(e,[BI,L5,P5])}function Yr(e){switch(e){case"react-component-duplicates":return{phase:e,reactComponentDuplicates:{count:0,loc:0,files:[]}};case"react-hook-candidates":return{phase:e,reactHookCandidates:{count:0,loc:0,files:[]}};case"react-large-component-pressure":return{phase:e,reactLargeComponentPressure:{count:0,loc:0,files:[]}};case"vue-component-duplicates":return{phase:e,vueComponentDuplicates:{count:0,loc:0,files:[]}};case"vue-composable-candidates":return{phase:e,vueComposableCandidates:{count:0,loc:0,files:[]}};case"vue-large-view-pressure":return{phase:e,vueLargeViewPressure:{count:0,loc:0,files:[]}};default:throw new Error(`Health phase "${e}" cannot be synthesized.`)}}function W5(e,t,n){if(e.length===1)return V5(e[0],t,n).then(s=>({result:[s.result],...s.observationReceipt?{observationReceipt:s.observationReceipt}:{}}));let r=e.join(","),i=process.argv[1]??ol(import.meta.url),o=[r];return t.scope&&o.push("--scope",t.scope),t.full&&o.push("--full"),Es({cliPath:i,command:OI,args:o,...t.full?{env:jI()}:{},label:`Health phases "${r}"`,timeoutMs:n}).catch(s=>{if(!t.full&&!(s instanceof ln))throw s;let a=s instanceof ln?s.timeoutMs:n??0;return{result:e.map(c=>HI(c,a,s instanceof ln?`timed out after ${s.timeoutMs}ms`:xp(s)))}})}function V5(e,t,n){let r=process.argv[1]??ol(import.meta.url),i=[e];return t.scope&&i.push("--scope",t.scope),t.full&&i.push("--full"),Es({cliPath:r,command:OI,args:i,...t.full?{env:jI()}:{},label:`Health phase "${e}"`,timeoutMs:n}).catch(o=>{if(!t.full&&!(o instanceof ln))throw o;let s=o instanceof ln?o.timeoutMs:n??0;return{result:HI(e,s,o instanceof ln?`timed out after ${o.timeoutMs}ms`:xp(o))}})}function xp(e){let t=e instanceof Error?e.message:String(e);if(/heap out of memory|reaching memory limit/i.test(t))return"exceeded its isolated memory limit";let n=t.split(/\r?\n/,1)[0]?.trim()||"isolated worker failed";return n.length<=240?n:`${n.slice(0,237)}...`}function jI(e=process.env){return{...e,NODE_OPTIONS:`--max-old-space-size=${q5(e)}`}}function Y5(e,t=process.env){let n=e.full?R5:E5,r=t.SCIP_QUERY_HEALTH_PHASE_TIMEOUT_MS;if(!r)return n;let i=parseInt(r,10);return!Number.isFinite(i)||i<0?n:i===0?void 0:i}function HI(e,t,n){let r={healthPhaseMeta:{status:"deferred",reason:n,timeoutMs:t}};switch(e){case"overview":throw new Error("Overview health phase cannot be deferred.");case"dead":return{phase:e,dead:{count:0,loc:0,files:[]},...r};case"isolated":return{phase:e,isolated:{count:0,loc:0,files:[]},...r};case"cycles":return{phase:e,realCycleCount:0,...r};case"similar":return{phase:e,similarCount:0,...r};case"duplicate-bodies":return{phase:e,duplicateBodies:{count:0,loc:0,files:[]},...r};case"twin-drift":return{phase:e,twinDrift:{count:0,loc:0,files:[]},...r};case"react-component-duplicates":return{...Yr(e),...r};case"react-hook-candidates":return{...Yr(e),...r};case"react-large-component-pressure":return{...Yr(e),...r};case"vue-component-duplicates":return{...Yr(e),...r};case"vue-composable-candidates":return{...Yr(e),...r};case"vue-large-view-pressure":return{...Yr(e),...r};case"extract-candidates":return{phase:e,extractCount:0,...r};case"wrapper-candidates":return{phase:e,wrappers:{count:0,loc:0,files:[]},...r};case"passthrough-candidates":return{phase:e,passthroughs:{count:0,loc:0,files:[]},...r};case"stale-abstractions":return{phase:e,stale:{count:0,loc:0,files:[],unused:0,singleUse:0},...r};case"drift":return{phase:e,drift:{count:0,unusedImports:0,architectureViolations:0,layerViolations:0,direct:0,signal:0},...r};case"complexity-hotspots":return{phase:e,complexity:{top:[],extremeCount:0},...r};case"git-evidence":return{phase:e,gitEvidence:null,...r};case"suppressions":return{phase:e,suppressions:{total:0,byCategory:{}},...r};case"coverage-contracts":return{phase:e,coverageContracts:{count:0,loc:0,files:[]},...r}}}var J5=Rp({envKey:"SCIP_QUERY_HEALTH_CONCURRENCY",defaultMinimum:v5,defaultMaximum:C5}),X5=Rp({envKey:"SCIP_QUERY_HEALTH_FULL_CONCURRENCY",defaultMinimum:NI,defaultMaximum:NI});function fye(e){if(console.log(`
534
- Codebase Health Score: ${e.score}/100`),console.log(` Risk: ${e.riskScore}/100 (risk-oriented graph facts + change graph)`),console.log(` Hygiene: ${e.hygieneScore}/100 (tidiness candidates)
535
- `),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${Wu(e.overview.indexSizeBytes)}
536
- `),e.warnings&&e.warnings.length>0){console.log(" Warnings:");for(let n of e.warnings)console.log(` ${n}`);console.log("")}console.log(" Findings:");let t=e.findings;if(t.deadSymbols>0&&console.log(` Dead code: ${t.deadSymbols} symbols (${t.deadLoc} LOC)`),t.isolatedSymbols>0&&console.log(` Isolated symbols: ${t.isolatedSymbols} (${t.isolatedLoc} LOC)`),t.cycles>0&&console.log(` Circular deps: ${t.cycles}`),t.similarPairs>0&&console.log(` Similar pairs: ${t.similarPairs}`),t.twinDriftGroups>0&&console.log(` Drifted twins: ${t.twinDriftGroups} group(s)`),t.reactComponentDuplicatePairs>0&&console.log(` React components: ${t.reactComponentDuplicatePairs} duplicate pair(s)`),t.reactHookCandidatePairs>0&&console.log(` React hook reuse: ${vp(t.reactHookCandidatePairs,t.reactHookCandidateScoreCount)} candidate pair(s)`),t.reactLargeComponentPressureFiles>0&&console.log(` React large comps: ${t.reactLargeComponentPressureFiles} component(s)`),t.vueComponentDuplicatePairs>0&&console.log(` Vue components: ${t.vueComponentDuplicatePairs} duplicate pair(s)`),t.vueComposableCandidatePairs>0&&console.log(` Vue composables: ${vp(t.vueComposableCandidatePairs,t.vueComposableCandidateScoreCount)} candidate pair(s)`),t.vueLargeViewPressureFiles>0&&console.log(` Vue large views: ${t.vueLargeViewPressureFiles} file(s)`),t.extractionCandidates>0&&console.log(` Extract candidates: ${t.extractionCandidates}`),t.wrappers>0&&console.log(` Wrapper functions: ${vp(t.wrappers,t.wrapperScoreCount)}`),t.passthroughs>0&&console.log(` Passthroughs: ${t.passthroughs}`),t.staleTypes>0&&console.log(` Stale abstractions: ${t.staleTypes}`),t.driftedFiles>0&&console.log(` Pattern drift: ${t.driftedFiles} files`),t.complexityHotspotCount>0&&console.log(` Complexity hotspots: ${t.complexityHotspotCount}`),e.actions.length>0){console.log(`
537
- Prioritized Actions (highest impact + lowest effort first):`);for(let n=0;n<e.actions.length;n++){let r=e.actions[n],i=r.locRecoverable>0?` (~${r.locRecoverable} LOC involved)`:"";console.log(` ${n+1}. [${r.effort} effort / ${r.impact} impact] ${r.description}${i}`)}}if(e.topComplexity.length>0){console.log(`
538
- Top Complexity Hotspots:`);for(let n of e.topComplexity)console.log(` ${n.score.toFixed(1).padStart(6)} ${n.symbol}`)}if(e.detectorEvidence.length>0){console.log(`
539
- Detector Evidence Calibration:`);for(let n of e.detectorEvidence){let r=n.unavailableRequirements.length>0?`; unavailable: ${n.unavailableRequirements.join(", ")}`:"";console.log(` ${n.detector}: ${n.status}/${n.providerCoverage}${r}`)}console.log(" Full claims, non-claims, providers, and recovery commands are available in health --json.")}if(eX(e),Z5(e),e.scoreBreakdown.length>0){console.log(`
540
- Score Breakdown (100 minus the following):`);for(let n of e.scoreBreakdown)console.log(` -${String(n.points).padStart(2)} ${n.axis}: ${n.detail}`)}e.actions.length===0&&console.log(e.warnings&&e.warnings.length>0?`
541
- No findings from completed analyses. Review warnings before interpreting this result as clean.`:`
542
- No issues found. Codebase is clean.`)}function vp(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${Q5(t)} score-weighted)`}function Q5(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function Z5(e){if(e.pressure.length!==0){console.log(`
543
- Maintenance Pressure:`);for(let t of e.pressure)console.log(` ${t.category}: ${t.count} / ${t.threshold} threshold (${t.ratio}x, -${t.extraPenalty} ${t.kind})`)}}function eX(e){let t=e.axes;if(console.log(`
544
- Axes:`),console.log(` Zero-reference candidates: ${t.deletable.loc} LOC across ${t.deletable.symbols} symbols`),t.changeAmplification){let r=t.changeAmplification;console.log(` Change amplification: ${r.medianFilesPerCommit} files/commit median, ${r.p90FilesPerCommit} p90 (${r.commitsAnalyzed} commits)`)}if(t.hiddenCoupling&&t.hiddenCoupling.pairCount>0){console.log(` Hidden coupling: ${t.hiddenCoupling.pairCount} co-changing pair(s) without a dependency edge`);for(let r of t.hiddenCoupling.top.slice(0,3))console.log(` ${r.fileA} <-> ${r.fileB} (${r.together}x together, ${Math.round(r.confidence*100)}%)`)}if(t.churnWeightedComplexity&&t.churnWeightedComplexity.length>0){let r=t.churnWeightedComplexity[0];r.weighted>0&&console.log(` Churn x complexity: hottest is ${r.symbol} (${r.changes} changes, weighted ${r.weighted})`)}let n=t.evidenceQuality;if(console.log(` Evidence quality: ${n.graphFindings} graph-fact finding(s), ${n.heuristicFindings} heuristic finding(s), ${n.userSuppressed} user-suppressed`),e.validation&&e.validation.flaggedFiles>0){let r=e.validation,i=r.ratio===null?"n/a":`${r.ratio}x`;console.log(` Validation: flagged files fix-density ${r.flaggedFixDensity} vs baseline ${r.baselineFixDensity} (${i})`),console.log(` fix-commit signal: subject-keyword heuristic over ${r.validationBasis.commitsScanned} commits`)}}async function gye(e){let t=Cp(o=>{let s=qi(o,{base:e.base});return s.note?{kind:"complete",result:Fc(o,{base:e.base})}:s.changedFiles.length===0?{kind:"complete",result:Fc(o,{base:e.base})}:{kind:"batched",plan:s}}),n=t.value;if(n.kind==="complete")return{result:n.result,observationReceipt:il([t.anchor],[],["index-generation","live-workspace"])};let r=nX(n.plan.changedFiles),i=await yp(r,tX(r.length),o=>oX(o,e));return{result:Nc(n.plan.changedFiles,i.map(o=>o.result)),observationReceipt:il([t.anchor],i.map(o=>o.observationReceipt),["index-generation","live-workspace"])}}var tX=Rp({envKey:"SCIP_QUERY_DIFF_IMPACT_CONCURRENCY",defaultMinimum:h5,defaultMaximum:y5});function nX(e){return LI(e,g5)}function Rp(e){return(t,n=process.env,r=d5)=>rX(t,n,r,e)}function rX(e,t,n,r){let i=t[r.envKey],o=iX(n,r),s=i?parseInt(i,10):o;return!Number.isFinite(s)||s<1?Math.min(o,e):Math.min(s,e)}function iX(e,t){let n=e(),r=Number.isFinite(n)?Math.max(t.defaultMinimum,n-1):0;return Math.min(t.defaultMaximum,Math.max(t.defaultMinimum,r))}function oX(e,t){let n=process.argv[1]??ol(import.meta.url),r=[];return t.base&&r.push("--base",t.base),Es({cliPath:n,command:f5,args:r,env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch"})}function hye(e){console.log(`Changed files: ${e.summary.totalChangedFiles}`),console.log(`Changed symbols: ${e.summary.totalChangedSymbols}`),console.log(`Affected consumer files: ${e.summary.totalAffectedFiles}`),e.summary.note&&console.log(`Note: ${e.summary.note}`);for(let n of e.evidenceTiers.filter(r=>r.state==="failed"))console.log(`WARNING: ${n.tier} evidence failed for ${n.attemptedSymbols} candidate symbol(s): ${n.reason}`);let t=e.attributionNotes.filter(n=>n.method==="unattributed");if(t.length>0){let n=[...new Set(t.map(r=>r.file))];for(let r of n){let i=t.filter(o=>o.file===r).length;console.log(`note: ${i} changed line-range(s) in ${r} belong to no indexed symbol`)}}console.log(""),e.changedSymbols.length>0&&(console.log("Changed symbols:"),Xu.list(e.changedSymbols,n=>` ${n.file} ${n.shortName} (fan-in: ${n.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
545
- Affected consumer files:`),Xu.list(e.affectedConsumers,n=>` ${n.file} (${n.consumedSymbols} symbol(s))`))}import{AsyncLocalStorage as sX}from"async_hooks";import{createHash as Ip}from"crypto";import{existsSync as aX,mkdirSync as cX}from"fs";import{tmpdir as lX}from"os";import{isAbsolute as uX,join as GI,resolve as zI}from"path";var Ep=2,dX="SCIP_QUERY_SESSION",UI="SCIP_QUERY_SESSION_DIR",mX=128,Ki=new sX;function Dye(e,t){let n=e.sessionEnabled===!1||e.json?void 0:wX(),r={enabled:n!==void 0,reemit:e.reemit===!0,command:e.command,projectRoot:zI(e.cwd),sessionIdentity:n,staged:[],stagedEvidence:[],finalized:!1};return Ki.run(r,t)}function Mye(e){let t=Ki.getStore();!t||t.finalized||(t.generationIdentity=e)}function Tye(e){let t=Ki.getStore();if(!t||t.finalized)return;t.finalized=!0;let n=t.state;if(!n){t.staged.length=0,t.stagedEvidence.length=0;return}try{if(e&&(t.staged.length>0||t.stagedEvidence.length>0)){let r=n.ledger.nextOrdinal,i=CX(t.staged).map(s=>({...s,ordinal:r,command:t.command})),o=RX(t.stagedEvidence).map(s=>({...s,ordinal:r,command:t.command}));n.ledger.ranges.push(...i),n.ledger.evidence.push(...o),n.ledger.nextOrdinal+=1,n.ledger.updatedAt=new Date().toISOString(),Cr(n.ledgerPath,n.ledger,{spacing:2,trailingNewline:!0})}}catch{}finally{n.lock.release(),t.state=null,t.staged.length=0,t.stagedEvidence.length=0}}function kye(e){let t=e.source.split(`
546
- `);if(t.length===0)return"";let n=pX(e.relativePath,e.startLine,t,e.ownerSymbol,e.sessionPolicy??"exact-unit"),r=e.indent??" ",i=e.sourceIndent??" ",o=e.focusLines??new Set;return n.map(s=>{let a=Ju(e.relativePath,s.startLine,s.endLine);if(s.kind==="covered"){let u=s.ordinal===null?"this command":`session #${s.ordinal} via ${s.command}`;return[`${r}${a} [source previously emitted: ${u}; not repeated]`,...e.afterHeader??[]].join(`
547
- `)}let c=e.headerSuffix??"",l=s.lines.map((u,d)=>{let m=s.startLine+d,p=e.showFocusMarker===!1?"":o.has(m)?">":" ",f=e.lineNumberWidth??5;return`${i}${p}${String(Ha(m)).padStart(f)} ${u}`});return[`${r}${a}${c}`,...e.blankAfterHeader?[""]:[],...e.afterHeader??[],...l].join(`
548
- `)}).join(`
549
- `)}function Aye(e){let t=Ki.getStore();if(!t||!t.enabled)return e.content;let n=wp(t);if(!n)return e.content;let r=KI(e.content),i=sl(n.ledger.evidence,o=>o.kind===e.kind&&o.identity===e.identity&&o.contentHash===r);if(i&&!t.reemit){let o=e.label?`; ${qI(e.label)}`:"";return`${e.indent??""}[${e.kind} evidence previously emitted: receipt ${i.receiptId}; session #${i.ordinal} via ${i.command}${o}; not repeated]`}return t.stagedEvidence.push({kind:e.kind,identity:e.identity,contentHash:r,receiptId:LX(e.kind,e.identity,r),...e.label?{label:qI(e.label)}:{}}),e.content}function Fye(e=!1){let t=Ki.getStore();if(!t?.enabled)return{enabled:!1,reason:"No explicit SCIP_QUERY_SESSION is active; source packets render independently.",uniqueLines:0,evidenceItems:0,emissions:0,rows:[]};let n=wp(t);if(!n)return{enabled:!1,reason:"The exploration-session ledger was unavailable or contended; evidence output is fail-open for this command.",uniqueLines:0,evidenceItems:0,emissions:0,rows:[]};if(e){n.ledger.ranges=[],n.ledger.evidence=[],n.ledger.nextOrdinal=1,n.ledger.updatedAt=new Date().toISOString();try{Cr(n.ledgerPath,n.ledger,{spacing:2,trailingNewline:!0})}catch{return{enabled:!1,reason:"The exploration-session ledger could not be reset; evidence output remains fail-open.",uniqueLines:0,evidenceItems:0,emissions:0,rows:[]}}}let r=new Map;for(let a of n.ledger.ranges){let c=r.get(a.ordinal)??[];c.push(a),r.set(a.ordinal,c)}let i=new Map;for(let a of n.ledger.evidence){let c=i.get(a.ordinal)??[];c.push(a),i.set(a.ordinal,c)}let s=[...new Set([...r.keys(),...i.keys()])].sort((a,c)=>a-c).map(a=>{let c=r.get(a)??[],l=i.get(a)??[],u=c[0]?.command??l[0]?.command??"unknown",d=c.length===0?null:(()=>{let f=c.slice(0,8).map(h=>Ju(h.relativePath,h.startLine,h.endLine)).join(", "),g=c.length>8?`, ... ${c.length-8} more range(s)`:"";return` #${a} ${u}: ${f}${g}`})();if(l.length===0)return d;let m=l.slice(0,8).map(f=>`${f.receiptId} ${f.kind}${f.label?` ${f.label}`:""}`).join(", "),p=l.length>8?`, ... ${l.length-8} more item(s)`:"";return d?`${d}
550
- evidence: ${m}${p}`:` #${a} ${u}: ${m}${p}`});return{enabled:!0,uniqueLines:EX(n.ledger.ranges),evidenceItems:n.ledger.evidence.length,emissions:new Set([...r.keys(),...i.keys()]).size,rows:s}}function pX(e,t,n,r,i){let o=Ki.getStore(),s=t+n.length-1;if(!o)return[{kind:"source",startLine:t,endLine:s,lines:[...n]}];let c=(o.enabled?wp(o):null)?.ledger.ranges??[],l=n.map(KI),u=i==="exact-unit"&&!o.reemit?sl(c,h=>h.policy==="exact-unit"&&h.relativePath===e&&h.startLine===t&&h.endLine===s&&h.ownerSymbol===r&&PX(h.lineHashes,l)):void 0;if(u)return[{kind:"covered",startLine:t,endLine:s,ordinal:u.ordinal,command:u.command}];let d=i==="exact-unit"&&!o.reemit?gX(c,e,t,s,l):void 0;if(d)return[{kind:"covered",startLine:t,endLine:s,ordinal:d.ordinal,command:d.command}];let m=n.map((h,b)=>fX(c,e,t+b,l[b]));if(!(i==="preview"&&!o.reemit&&m.every(h=>h!==void 0)))return o.staged.push({relativePath:e,startLine:t,endLine:s,ownerSymbol:r,policy:i,lineHashes:l}),[{kind:"source",startLine:t,endLine:s,lines:[...n]}];let f=[],g=0;for(;g<n.length;){let h=m[g],b=g;for(;b+1<n.length&&hX(h,m[b+1]);)b+=1;let S=t+g,y=t+b;f.push({kind:"covered",startLine:S,endLine:y,ordinal:h.ordinal,command:h.command}),g=b+1}return f}function fX(e,t,n,r){let i=sl(e,o=>o.relativePath===t&&o.startLine<=n&&n<=o.endLine&&o.lineHashes[n-o.startLine]===r);if(i)return{ordinal:i.ordinal,command:i.command}}function gX(e,t,n,r,i){let o=sl(e,s=>s.policy==="exact-unit"&&s.relativePath===t&&s.startLine<=n&&s.endLine>=r&&i.every((a,c)=>s.lineHashes[n-s.startLine+c]===a));return o?{ordinal:o.ordinal,command:o.command}:void 0}function hX(e,t){return!e||!t?e===t:e.ordinal===t.ordinal&&e.command===t.command}function wp(e){if(e.state!==void 0)return e.state;if(!e.sessionIdentity||!e.generationIdentity)return e.state=null,null;try{let t=IX();cX(t,{recursive:!0,mode:448});let n=Ip("sha256").update(e.projectRoot).update("\0").update(e.generationIdentity).update("\0").update(e.sessionIdentity).digest("hex"),r=GI(t,`${n}.json`),i=ui(`${r}.lock`,{kind:"source-emission-session",detail:{session:n.slice(0,12)}});if(i.kind!=="acquired")return e.state=null,null;let o;try{o=aX(r)?bX(JSON.parse(Ve(r,"source emission session ledger")),{projectRoot:e.projectRoot,generationIdentity:e.generationIdentity,sessionIdentity:e.sessionIdentity}):yX(e)}catch{return i.lock.release(),e.state=null,null}return e.state={ledgerPath:r,lock:i.lock,ledger:o},e.state}catch{return e.state=null,null}}function yX(e){return{version:Ep,projectRoot:e.projectRoot,generationIdentity:e.generationIdentity,sessionIdentity:e.sessionIdentity,nextOrdinal:1,updatedAt:new Date().toISOString(),ranges:[],evidence:[]}}function bX(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid source emission ledger.");let n=e;if(e.version===1&&n.projectRoot===t.projectRoot&&n.generationIdentity===t.generationIdentity&&n.sessionIdentity===t.sessionIdentity&&Number.isSafeInteger(n.nextOrdinal)&&(n.nextOrdinal??0)>0)return{version:Ep,projectRoot:t.projectRoot,generationIdentity:t.generationIdentity,sessionIdentity:t.sessionIdentity,nextOrdinal:n.nextOrdinal,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:new Date().toISOString(),ranges:[],evidence:[]};if(n.version!==Ep||n.projectRoot!==t.projectRoot||n.generationIdentity!==t.generationIdentity||n.sessionIdentity!==t.sessionIdentity||!Number.isSafeInteger(n.nextOrdinal)||(n.nextOrdinal??0)<=0||!Array.isArray(n.ranges)||!n.ranges.every(SX)||!Array.isArray(n.evidence)||!n.evidence.every(vX))throw new Error("Invalid source emission ledger.");return n}function SX(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.relativePath=="string"&&t.relativePath!==""&&Number.isSafeInteger(t.startLine)&&(t.startLine??-1)>=0&&Number.isSafeInteger(t.endLine)&&(t.endLine??-1)>=(t.startLine??0)&&Number.isSafeInteger(t.ordinal)&&(t.ordinal??0)>0&&typeof t.command=="string"&&t.command!==""&&(t.policy==="exact-unit"||t.policy==="preview")&&Array.isArray(t.lineHashes)&&t.lineHashes.length===(t.endLine??0)-(t.startLine??0)+1&&t.lineHashes.every(Zr)&&(t.ownerSymbol===void 0||typeof t.ownerSymbol=="string")}function vX(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return(t.kind==="unit"||t.kind==="edge")&&typeof t.identity=="string"&&t.identity!==""&&typeof t.contentHash=="string"&&Zr(t.contentHash)&&typeof t.receiptId=="string"&&/^ev-[0-9a-f]{12}$/u.test(t.receiptId)&&Number.isSafeInteger(t.ordinal)&&(t.ordinal??0)>0&&typeof t.command=="string"&&t.command!==""&&(t.label===void 0||typeof t.label=="string")}function CX(e){let t=[...e].sort((r,i)=>r.relativePath.localeCompare(i.relativePath)||r.startLine-i.startLine||r.endLine-i.endLine),n=[];for(let r of t){let i=n[n.length-1];if(i&&i.relativePath===r.relativePath&&i.ownerSymbol===r.ownerSymbol&&i.policy===r.policy&&r.startLine<=i.endLine+1&&xX(i,r)){let o=r.startLine-i.startLine;for(let s=0;s<r.lineHashes.length;s+=1)i.lineHashes[o+s]??=r.lineHashes[s];i.endLine=Math.max(i.endLine,r.endLine)}else n.push({...r,lineHashes:[...r.lineHashes]})}return n}function xX(e,t){let n=Math.max(e.startLine,t.startLine),r=Math.min(e.endLine,t.endLine);for(let i=n;i<=r;i+=1)if(e.lineHashes[i-e.startLine]!==t.lineHashes[i-t.startLine])return!1;return!0}function RX(e){let t=new Set,n=[];for(let r of e){let i=`${r.kind}\0${r.identity}\0${r.contentHash}`;t.has(i)||(t.add(i),n.push(r))}return n}function EX(e){let t=new Map;for(let r of e){let i=t.get(r.relativePath)??[];i.push(r),t.set(r.relativePath,i)}let n=0;for(let r of t.values()){r.sort((s,a)=>s.startLine-a.startLine||s.endLine-a.endLine);let i=-1,o=-1;for(let s of r)i<0?(i=s.startLine,o=s.endLine):s.startLine<=o+1?o=Math.max(o,s.endLine):(n+=o-i+1,i=s.startLine,o=s.endLine);i>=0&&(n+=o-i+1)}return n}function IX(){let e=process.env[UI];if(!e)return GI(lX(),`scip-query-source-sessions-${process.getuid?.()??"user"}`);if(!uX(e))throw new Error(`${UI} must be an absolute path.`);return zI(e)}function wX(){let e=process.env[dX]?.trim();if(e&&!(e.length>mX||!/^[A-Za-z0-9._:-]+$/.test(e)))return`explicit:${e}`}function LX(e,t,n){return`ev-${Ip("sha256").update(e).update("\0").update(t).update("\0").update(n).digest("hex").slice(0,12)}`}function qI(e){let t=e.replace(/[\r\n\t]+/gu," ").replace(/\s+/gu," ").trim();return t.length<=160?t:`${t.slice(0,157)}...`}function KI(e){return Ip("sha256").update(e).digest("hex")}function PX(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function sl(e,t){for(let n=e.length-1;n>=0;n-=1){let r=e[n];if(t(r))return r}}import{createHash as DX}from"crypto";import{existsSync as Pp,mkdirSync as MX,rmSync as TX}from"fs";import{tmpdir as kX}from"os";import{isAbsolute as AX,join as VI,resolve as al}from"path";var YI=1,FX="SCIP_QUERY_SESSION",WI="SCIP_QUERY_SESSION_DIR",NX=128,JI=8,XI=32768,cl=new Map;function qye(e,t,n=!0){if(!n)return;let r=ll();if(!r)return;let i=Tp(e),o=t.map(a=>a.trim()).filter(a=>a.startsWith("scip-query system-map ")&&a.length<=XI).slice(0,JI),s=QI(i,r);o.length===0?cl.delete(s):cl.set(s,o)}function Gye(e,t,n,r=!0,i){if(!r||e!=="anchors"&&e!=="system-map")return;let o=ll();if(!o)return;let s=Tp(t),a=Mp(s,o);if(e==="system-map"){n?TX(a,{force:!0}):Pp(a)&&i&&Lp(a,()=>{let c=Dp(a,s,o);c&&Cr(a,{...c,pendingMapContinuation:i,mapExecution:void 0,updatedAt:new Date().toISOString()},{spacing:2,trailingNewline:!0})});return}Lp(a,()=>{let c=_X(s,o),l={version:YI,projectRoot:s,sessionIdentity:o,mapRequired:!0,...c.length>0?{recommendedMapCommands:c}:{},updatedAt:new Date().toISOString()};Cr(a,l,{spacing:2,trailingNewline:!0})})}function zye(e,t=!0){if(!t)return;let n=ll();if(!n)return;let r=Tp(e),i=Mp(r,n);Pp(i)&&Lp(i,()=>{let o=Dp(i,r,n);if(o){if(o.pendingMapContinuation)throw new Error(["MAP TRANSPORT INCOMPLETE","The selected system map has already been computed. Restarting it would repeat the same repository work.",`Continue exactly: ${o.pendingMapContinuation}`].join(`
551
- `));if(o.mapExecution&&OX(o.mapExecution.processId))throw new Error(["NAVIGATION MAP ALREADY RUNNING","A selected system map is already computing in this SCIP_QUERY_SESSION.","Poll the existing terminal execution. Do not launch a duplicate map or inspect in parallel."].join(`
552
- `));Cr(i,{...o,mapExecution:{processId:process.pid,startedAt:new Date().toISOString()},updatedAt:new Date().toISOString()},{spacing:2,trailingNewline:!0})}})}function Kye(e,t,n=!0){if(!n)return;let r=ll();if(!r)return;let i=Mp(al(e),r);if(!Pp(i))return;let o=Dp(i,al(e),r);if(!o?.mapRequired)return;let s=o.recommendedMapCommands?.length?["This refusal is a recoverable protocol step, not evidence that the requested code cannot be explored.","Run exactly one of the ranked map commands below, then finish every emitted continuation:",...o.recommendedMapCommands.map((a,c)=>` [${c+1}] ${a}`)]:[`Do not retry ${t}. Run one printed next-abstraction system-map command and finish every emitted continuation first.`];throw new Error(["NAVIGATION MAP REQUIRED","An anchors locator completed in this SCIP_QUERY_SESSION, but its selected system map has not reached transport completion.",`Do not retry ${t}.`,...s,"The map must complete before the agent can choose source detail; map and detail exploration cannot run concurrently."].join(`
553
- `))}function Dp(e,t,n){try{let r=JSON.parse(Ve(e,"navigation session state"));return r.version===YI&&r.projectRoot===t&&r.sessionIdentity===n&&r.mapRequired===!0&&(r.recommendedMapCommands===void 0||Array.isArray(r.recommendedMapCommands)&&r.recommendedMapCommands.length<=JI&&r.recommendedMapCommands.every(i=>typeof i=="string"&&i.startsWith("scip-query system-map ")&&i.length<=XI))&&(r.pendingMapContinuation===void 0||typeof r.pendingMapContinuation=="string")&&(r.mapExecution===void 0||typeof r.mapExecution=="object"&&r.mapExecution!==null&&Number.isSafeInteger(r.mapExecution.processId)&&typeof r.mapExecution.startedAt=="string")?r:null}catch{return null}}function _X(e,t){let n=QI(e,t),r=cl.get(n)??[];return cl.delete(n),r}function QI(e,t){return`${e}\0${t}`}function OX(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function Mp(e,t){let n=BX();MX(n,{recursive:!0,mode:448});let r=DX("sha256").update(e).update("\0").update(t).digest("hex");return VI(n,`navigation-${r}.json`)}function BX(){let e=process.env[WI];if(!e)return VI(kX(),`scip-query-source-sessions-${process.getuid?.()??"user"}`);if(!AX(e))throw new Error(`${WI} must be an absolute path.`);return al(e)}function Tp(e){let t=process.env.SCIP_QUERY_PROJECT_ROOT?.trim();return al(t||e)}function ll(){let e=process.env[FX]?.trim();if(e&&!(e.length>NX||!/^[A-Za-z0-9._:-]+$/u.test(e)))return`explicit:${e}`}function Lp(e,t){let n=ui(`${e}.lock`,{kind:"navigation-session",detail:{state:e.slice(-17,-5)}});if(n.kind!=="acquired")throw new Error("Navigation session state is busy. Retry the completed command.");try{t()}finally{n.lock.release()}}export{kr as a,ro as b,Kt as c,gg as d,a4 as e,fa as f,kQ as g,dD as h,Ci as i,ly as j,X6 as k,Ar as l,lA as m,SA as n,RF as o,Bo as p,og as q,Z4 as r,$o as s,jo as t,rc as u,jS as v,$0 as w,cN as x,o8 as y,vne as z,fN as A,vN as B,Bt as C,_e as D,pv as E,pO as F,DB as G,Qo as H,Jd as I,QB as J,zr as K,H$ as L,G$ as M,z$ as N,K$ as O,oj as P,cj as Q,lj as R,uj as S,mj as T,pj as U,fj as V,rx as W,ts as X,rm as Y,Oj as Z,ns as _,jj as $,Hj as aa,Vj as ba,Zj as ca,e1 as da,t1 as ea,is as fa,lm as ga,os as ha,oH as ia,ss as ja,as as ka,dm as la,cs as ma,ls as na,mm as oa,XH as pa,us as qa,iq as ra,Mq as sa,Cm as ta,Hq as ua,qi as va,CR as wa,CG as xa,ms as ya,Qz as za,fs as Aa,CK as Ba,gs as Ca,mW as Da,pW as Ea,CW as Fa,NW as Ga,UW as Ha,oV as Ia,Wm as Ja,AE as Ka,Vm as La,FE as Ma,Wc as Na,NV as Oa,vs as Pa,Cs as Qa,xs as Ra,G2 as Sa,z2 as Ta,K2 as Ua,ip as Va,Zc as Wa,sp as Xa,IY as Ya,oJ as Za,sJ as _a,cJ as $a,uJ as ab,CJ as bb,PJ as cb,hM as db,d8 as eb,Da as fb,Mo as gb,Jy as hb,B8 as ib,$8 as jb,j8 as kb,H8 as lb,U8 as mb,q8 as nb,i9 as ob,Zy as pb,o9 as qb,eb as rb,tb as sb,Oa as tb,NT as ub,_T as vb,OT as wb,BT as xb,rb as yb,$a as zb,w9 as Ab,ja as Bb,ib as Cb,L9 as Db,P9 as Eb,D9 as Fb,M9 as Gb,GT as Hb,Ku as Ib,T9 as Jb,Wu as Kb,k9 as Lb,F9 as Mb,N9 as Nb,_9 as Ob,O9 as Pb,ob as Qb,Mt as Rb,Yu as Sb,B9 as Tb,Vr as Ub,Ihe as Vb,_he as Wb,Ha as Xb,ZT as Yb,Ju as Zb,H9 as _b,Xu as $b,OI as ac,p5 as bc,f5 as cc,uye as dc,dye as ec,mye as fc,pye as gc,$5 as hc,fye as ic,gye as jc,hye as kc,Dye as lc,Mye as mc,Tye as nc,kye as oc,Aye as pc,Fye as qc,qye as rc,Gye as sc,zye as tc,Kye as uc};
554
- //# sourceMappingURL=chunk-V4NG5OMS.js.map