codebaseiq 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (403) hide show
  1. package/CHANGELOG.md +59 -2
  2. package/README.md +1 -1
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/{chunk-WH5SYOMD.js → chunk-2E6OUPCF.js} +2 -2
  5. package/dist/chunk-2I2UHZET.js +2 -0
  6. package/dist/{chunk-CSZOQ7YO.js → chunk-2OMXFE64.js} +2 -2
  7. package/dist/{chunk-57KFVPVZ.js → chunk-2XBJRZEM.js} +2 -2
  8. package/dist/{chunk-PFPHS4NO.js → chunk-2Z7K66D7.js} +2 -2
  9. package/dist/{chunk-5WXOEJ4G.js → chunk-356EZBIP.js} +2 -2
  10. package/dist/{chunk-DLC6JDN7.js → chunk-3H2H5ODK.js} +2 -2
  11. package/dist/{chunk-HBQGKMM3.js → chunk-3LQJRS4I.js} +2 -2
  12. package/dist/{chunk-H3CKAL6P.js → chunk-3ON3A2QV.js} +2 -2
  13. package/dist/{chunk-MTMF4N7F.js → chunk-3VJ3OCRE.js} +2 -2
  14. package/dist/{chunk-QMGWSEPL.js → chunk-4GWN76B2.js} +2 -2
  15. package/dist/{chunk-IBM3F2BJ.js → chunk-4LK5OIPW.js} +2 -2
  16. package/dist/{chunk-6SDEQTVY.js → chunk-53ELMZRF.js} +2 -2
  17. package/dist/{chunk-OJFLPVBP.js → chunk-57OPIQFM.js} +2 -2
  18. package/dist/{chunk-2E6BTWER.js → chunk-5CR4U5X2.js} +2 -2
  19. package/dist/{chunk-IYBIBMPF.js → chunk-5FWR5HLG.js} +2 -2
  20. package/dist/{chunk-HHBBGWES.js → chunk-5LL4KEHO.js} +2 -2
  21. package/dist/{chunk-NTRW52UR.js → chunk-5MPBSFZH.js} +2 -2
  22. package/dist/chunk-5T44HG5Y.js +88 -0
  23. package/dist/chunk-5TZNHP4T.js +8 -0
  24. package/dist/{chunk-L3YSDLNB.js → chunk-5YBDBY5L.js} +2 -2
  25. package/dist/{chunk-YFQPWKHR.js → chunk-5ZI2PPI7.js} +2 -2
  26. package/dist/{chunk-WO47BIPY.js → chunk-6EYESTJM.js} +2 -2
  27. package/dist/{chunk-PHPQ24UG.js → chunk-6FXXYYQM.js} +2 -2
  28. package/dist/chunk-6O3KXIDL.js +2 -0
  29. package/dist/{chunk-PLZXWZHY.js → chunk-7GAK2F3H.js} +2 -2
  30. package/dist/{chunk-W3FK73MD.js → chunk-7UCDGXRW.js} +2 -2
  31. package/dist/{chunk-U2XX3BT4.js → chunk-AGGR2BKS.js} +2 -2
  32. package/dist/{chunk-ZB3V5QM7.js → chunk-ALOEHWJS.js} +2 -2
  33. package/dist/{chunk-NDGTJHQN.js → chunk-AXQCHG77.js} +2 -2
  34. package/dist/{chunk-X5I2BQGX.js → chunk-BFANZRQ5.js} +2 -2
  35. package/dist/{chunk-VVCBMH5O.js → chunk-BGGB5N53.js} +2 -2
  36. package/dist/{chunk-PARCKE3Q.js → chunk-BGYRF5YX.js} +2 -2
  37. package/dist/{chunk-CIVYHK7U.js → chunk-BIADXGC3.js} +2 -2
  38. package/dist/{chunk-NK76RSB6.js → chunk-BPKNP3KZ.js} +2 -2
  39. package/dist/{chunk-ZOEDRCR4.js → chunk-BRQL7AFJ.js} +2 -2
  40. package/dist/{chunk-KDYQQJ6X.js → chunk-BWL3PMPT.js} +2 -2
  41. package/dist/{chunk-M7LAIM77.js → chunk-C6WKPKCF.js} +2 -2
  42. package/dist/{chunk-37TKC6MB.js → chunk-CB5AVJMM.js} +2 -2
  43. package/dist/{chunk-BX2U3QQV.js → chunk-CCIYWXX6.js} +2 -2
  44. package/dist/{chunk-3AC56WAR.js → chunk-CIYA2KZN.js} +2 -2
  45. package/dist/{chunk-6OVNYYY4.js → chunk-CJTKGAGH.js} +2 -2
  46. package/dist/{chunk-FIXYHQ3W.js → chunk-CLPCFGRT.js} +2 -2
  47. package/dist/{chunk-LY2NB5XR.js → chunk-CSPDQLLU.js} +2 -2
  48. package/dist/{chunk-CMXW7MFV.js → chunk-CYJS33YX.js} +2 -2
  49. package/dist/{chunk-ACZDU5GK.js → chunk-D7DOB27N.js} +7 -7
  50. package/dist/{chunk-XUJM6474.js → chunk-DDRA3QKN.js} +2 -2
  51. package/dist/{chunk-3NUZVLR7.js → chunk-DECN422G.js} +2 -2
  52. package/dist/{chunk-RRPK327J.js → chunk-DJKOXMNG.js} +2 -2
  53. package/dist/{chunk-SJZQ2PTZ.js → chunk-DWBAESVW.js} +2 -2
  54. package/dist/{chunk-S5SKXCND.js → chunk-EHPOTEQX.js} +2 -2
  55. package/dist/chunk-EIBGSU2R.js +2 -0
  56. package/dist/{chunk-DVYG3JTA.js → chunk-ELYMY5S2.js} +2 -2
  57. package/dist/chunk-EOKVZXNF.js +355 -0
  58. package/dist/chunk-EQNMD62X.js +51 -0
  59. package/dist/{chunk-YIOQJ45A.js → chunk-F3QSL4W2.js} +2 -2
  60. package/dist/{chunk-VG55NFXF.js → chunk-F5CJO5JN.js} +2 -2
  61. package/dist/{chunk-JOALNFY3.js → chunk-F74LZWCE.js} +2 -2
  62. package/dist/chunk-G7GVV2TV.js +27 -0
  63. package/dist/{chunk-U24M5RQM.js → chunk-GQLDYCWS.js} +2 -2
  64. package/dist/{chunk-B2E3HZ2A.js → chunk-GV2CEZCW.js} +2 -2
  65. package/dist/{chunk-AM5SUGHF.js → chunk-GVAF222T.js} +2 -2
  66. package/dist/{chunk-T3YFIJ5P.js → chunk-HJTM3C4Y.js} +2 -2
  67. package/dist/{chunk-FY5V4V4F.js → chunk-HNXRVGMY.js} +2 -2
  68. package/dist/{chunk-UWB5WMC2.js → chunk-I3OK27P7.js} +2 -2
  69. package/dist/{chunk-RVYLJDXC.js → chunk-ICUL7XRT.js} +2 -2
  70. package/dist/{chunk-QVHZB75Z.js → chunk-IHSLIIL3.js} +2 -2
  71. package/dist/chunk-ILGTMRMZ.js +2 -0
  72. package/dist/{chunk-XNUWRTYM.js → chunk-IZDPGOZR.js} +2 -2
  73. package/dist/{chunk-BH5CE4LN.js → chunk-J7AMBVWF.js} +2 -2
  74. package/dist/chunk-JAFDMV5I.js +2 -0
  75. package/dist/{chunk-YXJ4IAHH.js → chunk-JCMFBF4Z.js} +2 -2
  76. package/dist/{chunk-BLKYYQ7C.js → chunk-JNXI6NQ7.js} +95 -95
  77. package/dist/{chunk-DKJXK3HA.js → chunk-JSB43EX6.js} +2 -2
  78. package/dist/chunk-JYRJYXUV.js +2 -0
  79. package/dist/chunk-K4S2VH42.js +82 -0
  80. package/dist/{chunk-QLTFXVUI.js → chunk-K6FNTQQW.js} +2 -2
  81. package/dist/{chunk-JYX5UZSZ.js → chunk-KEJ2HLRW.js} +2 -2
  82. package/dist/{chunk-VCWAJPXQ.js → chunk-KFTHI2R6.js} +2 -2
  83. package/dist/chunk-KLX6NSWT.js +3 -0
  84. package/dist/{chunk-DFPAZXLU.js → chunk-KPZGTB2O.js} +2 -2
  85. package/dist/{chunk-T55YPJGB.js → chunk-KUKKLWJD.js} +2 -2
  86. package/dist/{chunk-RWKEXCHU.js → chunk-KUKWHP4R.js} +2 -2
  87. package/dist/{chunk-ZJZQ7Q2Q.js → chunk-KWRQVLPX.js} +2 -2
  88. package/dist/{chunk-FQA3KIFX.js → chunk-L37EQYAX.js} +2 -2
  89. package/dist/{chunk-PNVZIJ57.js → chunk-LCW3PSGL.js} +2 -2
  90. package/dist/{chunk-7Z7HCZ7J.js → chunk-LKUTSP4G.js} +2 -2
  91. package/dist/{chunk-HIEXRDJF.js → chunk-LMTSB3TB.js} +2 -2
  92. package/dist/{chunk-SF34QLK2.js → chunk-LQHYYIOB.js} +2 -2
  93. package/dist/{chunk-EXMVF3JR.js → chunk-LSZYMN2A.js} +3 -3
  94. package/dist/{chunk-RCPZOPV6.js → chunk-M2Y6PCFE.js} +2 -2
  95. package/dist/chunk-MC46AL7B.js +343 -0
  96. package/dist/{chunk-SRY26ITJ.js → chunk-MDFT325O.js} +2 -2
  97. package/dist/{chunk-WJOQC4P7.js → chunk-MEUHIDI3.js} +2 -2
  98. package/dist/{chunk-FLLXYUOL.js → chunk-MQW6SJ4P.js} +2 -2
  99. package/dist/{chunk-57KEZDPT.js → chunk-MSI3K7PJ.js} +2 -2
  100. package/dist/{chunk-27PHVDKL.js → chunk-MZNMASFM.js} +2 -2
  101. package/dist/{chunk-VYZQZ4ZN.js → chunk-N2XDMNVI.js} +2 -2
  102. package/dist/{chunk-JN5LIBT3.js → chunk-NDKOVQFG.js} +2 -2
  103. package/dist/{chunk-W6C6QTXJ.js → chunk-NEWHKGVD.js} +2 -2
  104. package/dist/chunk-NNG6M6XD.js +3 -0
  105. package/dist/chunk-O2KWU34K.js +278 -0
  106. package/dist/{chunk-HBXZAGY6.js → chunk-O2M3VNDY.js} +2 -2
  107. package/dist/{chunk-FPDL2TUB.js → chunk-OBC7HSSO.js} +2 -2
  108. package/dist/{chunk-J24VICI5.js → chunk-OKAF4OQS.js} +2 -2
  109. package/dist/{chunk-I5FCDTK2.js → chunk-OP6BUIV6.js} +2 -2
  110. package/dist/{chunk-2DMVFAY7.js → chunk-OQ3DK7FW.js} +2 -2
  111. package/dist/{chunk-FEBLLMTL.js → chunk-OQUCBKOI.js} +2 -2
  112. package/dist/chunk-OT5ISJSR.js +2 -0
  113. package/dist/{chunk-N3Q3AWGW.js → chunk-OWJWOEDU.js} +96 -96
  114. package/dist/{chunk-M4EVGA5S.js → chunk-PIFYOWS4.js} +3 -3
  115. package/dist/{chunk-35YYZD3D.js → chunk-PTR3EOXC.js} +2 -2
  116. package/dist/{chunk-5XEVXVTK.js → chunk-PUVNH4PO.js} +2 -2
  117. package/dist/{chunk-I645ZF75.js → chunk-QEOWONKY.js} +2 -2
  118. package/dist/{chunk-JXHLB7TP.js → chunk-QMOZZ2VX.js} +2 -2
  119. package/dist/{chunk-NIO346UL.js → chunk-QY7QB7I6.js} +2 -2
  120. package/dist/{chunk-YYFV32WR.js → chunk-R4OJGTMP.js} +2 -2
  121. package/dist/{chunk-2VKB5CMA.js → chunk-RCIGX23V.js} +2 -2
  122. package/dist/{chunk-TUTSO7UZ.js → chunk-RIO3JXHM.js} +2 -2
  123. package/dist/{chunk-4IFISPQW.js → chunk-SA7G6GJX.js} +2 -2
  124. package/dist/{chunk-OMBRP7BB.js → chunk-SB53KPWA.js} +2 -2
  125. package/dist/chunk-SB7NASHU.js +2 -0
  126. package/dist/{chunk-3XFJUWJE.js → chunk-SGMNWYTH.js} +2 -2
  127. package/dist/{chunk-A7XQT7MH.js → chunk-SUE7SHZL.js} +2 -2
  128. package/dist/{chunk-IOVPAZWP.js → chunk-SX72EVMY.js} +2 -2
  129. package/dist/{chunk-OVKZM2XI.js → chunk-SZ4P7MF7.js} +2 -2
  130. package/dist/{chunk-EM5UHLAM.js → chunk-T2M5HWBQ.js} +2 -2
  131. package/dist/{chunk-CZEIHYMP.js → chunk-T6MQNNAC.js} +2 -2
  132. package/dist/chunk-T75DS2E6.js +21 -0
  133. package/dist/{chunk-57GCCPLS.js → chunk-TEANKHUU.js} +2 -2
  134. package/dist/{chunk-MT5W4DUG.js → chunk-TEMM2FEL.js} +2 -2
  135. package/dist/{chunk-I2KP4AGR.js → chunk-TJWVT4DO.js} +2 -2
  136. package/dist/{chunk-77GHPR2R.js → chunk-TLTSESB4.js} +2 -2
  137. package/dist/{chunk-KM4QRWI5.js → chunk-TNJGTQWO.js} +2 -2
  138. package/dist/{chunk-EFFMFK7C.js → chunk-TOTWJZIX.js} +2 -2
  139. package/dist/{chunk-54K6556S.js → chunk-U33PMPNW.js} +2 -2
  140. package/dist/{chunk-GXVDTHFC.js → chunk-U7NUXDQO.js} +2 -2
  141. package/dist/chunk-UC2FD2PS.js +4 -0
  142. package/dist/{chunk-MRGTCMDK.js → chunk-UIAUPFBJ.js} +2 -2
  143. package/dist/{chunk-LAGDJXFY.js → chunk-UJIXCI3L.js} +2 -2
  144. package/dist/{chunk-IVJJNVSX.js → chunk-UMEPSVKT.js} +2 -2
  145. package/dist/{chunk-4O52YNKL.js → chunk-UQYQBLJX.js} +2 -2
  146. package/dist/{chunk-JUO3Z644.js → chunk-UW6KD57C.js} +2 -2
  147. package/dist/{chunk-TAJ6UGCO.js → chunk-V4NGDIEA.js} +3 -3
  148. package/dist/{chunk-VLTUX4IF.js → chunk-VGWZ4MOY.js} +2 -2
  149. package/dist/{chunk-KNV5VFDV.js → chunk-VSGOIZMQ.js} +2 -2
  150. package/dist/{chunk-K5G7SPAG.js → chunk-W7QDASTN.js} +4 -4
  151. package/dist/{chunk-IWAMYGPN.js → chunk-W7YLRXZE.js} +2 -2
  152. package/dist/{chunk-QKVTWODE.js → chunk-WK2IQJPK.js} +2 -2
  153. package/dist/{chunk-HYKSLTAR.js → chunk-WO6OFKUC.js} +2 -2
  154. package/dist/{chunk-S64NCE2Z.js → chunk-WWCV4E6J.js} +2 -2
  155. package/dist/{chunk-2F5ERMNI.js → chunk-XJBK3QDV.js} +2 -2
  156. package/dist/{chunk-IGYAZPRX.js → chunk-XN3EKMLI.js} +2 -2
  157. package/dist/{chunk-FWY2PRIF.js → chunk-XQAVQVIL.js} +2 -2
  158. package/dist/{chunk-NJA4MMBD.js → chunk-XUPFA6GH.js} +2 -2
  159. package/dist/{chunk-4AOOSCZ7.js → chunk-YHPG3S2U.js} +2 -2
  160. package/dist/{chunk-CDWSLAPN.js → chunk-YPBKBYPS.js} +2 -2
  161. package/dist/{chunk-5BDK6QC3.js → chunk-YRKP7PM7.js} +2 -2
  162. package/dist/{chunk-4NHWNAWQ.js → chunk-YT4DVWUV.js} +2 -2
  163. package/dist/{chunk-5NJPH3QZ.js → chunk-YTJHCGYB.js} +2 -2
  164. package/dist/{chunk-ZNQCR656.js → chunk-Z66XYVLZ.js} +2 -2
  165. package/dist/{chunk-A67HT5FR.js → chunk-ZB4C5TTR.js} +2 -2
  166. package/dist/chunk-ZMA5HWXY.js +3 -0
  167. package/dist/{chunk-CWMHWD56.js → chunk-ZNH33XIB.js} +2 -2
  168. package/dist/{cli-context-XEPPF4RX.js → cli-context-FJL2JHOE.js} +2 -2
  169. package/dist/{cli-context-TSADTXLB.js → cli-context-PQNWHMCQ.js} +2 -2
  170. package/dist/{cli-program-KJGQEM72.js → cli-program-SCHOHOQE.js} +2 -2
  171. package/dist/cli.js +1 -1
  172. package/dist/{code-CDe-mIjx.d.ts → code-DfX3xeWy.d.ts} +1 -1
  173. package/dist/{code-viewer-ZCTHXQ5C.js → code-viewer-AMRXV444.js} +2 -2
  174. package/dist/{code-viewer-YGDON6SY.js → code-viewer-EXI5SFFR.js} +2 -2
  175. package/dist/{command-descriptors-5VAB2MZX.js → command-descriptors-H6A4UY72.js} +129 -129
  176. package/dist/{command-descriptors-EAHKIRAG.js → command-descriptors-ROIOTCCW.js} +130 -130
  177. package/dist/{db-DmRNdCtm.d.ts → db-BoG_PWYH.d.ts} +1 -1
  178. package/dist/direct-navigation-3JOYP2MO.js +3 -0
  179. package/dist/direct-navigation-SJMJLBY7.js +2 -0
  180. package/dist/{graph-evidence-Bs54NWws.d.ts → graph-evidence-D1jx1Cql.d.ts} +1 -1
  181. package/dist/{health-BnzbSLCE.d.ts → health-DkYBS5BI.d.ts} +1 -1
  182. package/dist/index.d.ts +1 -1
  183. package/dist/index.js +1 -1
  184. package/dist/invocation-command-descriptors-GMZX3UAD.js +2 -0
  185. package/dist/invocation-command-descriptors-HNMKDEF6.js +3 -0
  186. package/dist/{scip-cli-BRFKkHQn.d.ts → maintenance-types-CdL5eQii.d.ts} +1 -20
  187. package/dist/output-continuation-command-5NWVDQT7.js +2 -0
  188. package/dist/output-continuation-command-RNEHNYPU.js +3 -0
  189. package/dist/postinstall.js +1 -1
  190. package/dist/project-reindex-MIW5CYEG.js +3 -0
  191. package/dist/project-reindex-VQ23LWDA.js +2 -0
  192. package/dist/queries/affected.d.ts +1 -1
  193. package/dist/queries/affected.js +1 -1
  194. package/dist/queries/anchors.d.ts +1 -1
  195. package/dist/queries/anchors.js +1 -1
  196. package/dist/queries/architecture.d.ts +1 -1
  197. package/dist/queries/architecture.js +1 -1
  198. package/dist/queries/bottlenecks.d.ts +1 -1
  199. package/dist/queries/bottlenecks.js +1 -1
  200. package/dist/queries/by-kind.d.ts +1 -1
  201. package/dist/queries/by-kind.js +1 -1
  202. package/dist/queries/call-graph.d.ts +1 -1
  203. package/dist/queries/call-graph.js +1 -1
  204. package/dist/queries/change-surface.d.ts +1 -1
  205. package/dist/queries/change-surface.js +1 -1
  206. package/dist/queries/cleanup-plan.d.ts +1 -1
  207. package/dist/queries/cleanup-plan.js +1 -1
  208. package/dist/queries/co-change.d.ts +1 -1
  209. package/dist/queries/co-change.js +1 -1
  210. package/dist/queries/code.d.ts +2 -2
  211. package/dist/queries/code.js +1 -1
  212. package/dist/queries/complexity-hotspots.d.ts +1 -1
  213. package/dist/queries/complexity-hotspots.js +1 -1
  214. package/dist/queries/complexity.d.ts +1 -1
  215. package/dist/queries/complexity.js +1 -1
  216. package/dist/queries/context.d.ts +1 -1
  217. package/dist/queries/context.js +1 -1
  218. package/dist/queries/convergence.d.ts +1 -1
  219. package/dist/queries/convergence.js +1 -1
  220. package/dist/queries/coupling.d.ts +1 -1
  221. package/dist/queries/coupling.js +1 -1
  222. package/dist/queries/cycles.d.ts +1 -1
  223. package/dist/queries/cycles.js +1 -1
  224. package/dist/queries/dataflow.d.ts +1 -1
  225. package/dist/queries/dataflow.js +1 -1
  226. package/dist/queries/dead.d.ts +1 -1
  227. package/dist/queries/dead.js +1 -1
  228. package/dist/queries/decorative-checkers.d.ts +1 -1
  229. package/dist/queries/decorative-checkers.js +1 -1
  230. package/dist/queries/deep-chains.d.ts +1 -1
  231. package/dist/queries/deep-chains.js +1 -1
  232. package/dist/queries/dependence-slice.d.ts +2 -2
  233. package/dist/queries/dependence-slice.js +1 -1
  234. package/dist/queries/dependency-depth.d.ts +1 -1
  235. package/dist/queries/dependency-depth.js +1 -1
  236. package/dist/queries/deps.d.ts +1 -1
  237. package/dist/queries/deps.js +1 -1
  238. package/dist/queries/diff-impact.d.ts +1 -1
  239. package/dist/queries/diff-impact.js +1 -1
  240. package/dist/queries/doc-drift.d.ts +1 -1
  241. package/dist/queries/doc-drift.js +1 -1
  242. package/dist/queries/drift.d.ts +1 -1
  243. package/dist/queries/drift.js +1 -1
  244. package/dist/queries/duplicate-bodies.d.ts +1 -1
  245. package/dist/queries/duplicate-bodies.js +1 -1
  246. package/dist/queries/entry-map.d.ts +1 -1
  247. package/dist/queries/entry-map.js +1 -1
  248. package/dist/queries/evidence.d.ts +2 -2
  249. package/dist/queries/evidence.js +1 -1
  250. package/dist/queries/extract-candidates.d.ts +1 -1
  251. package/dist/queries/extract-candidates.js +1 -1
  252. package/dist/queries/fan.d.ts +1 -1
  253. package/dist/queries/fan.js +1 -1
  254. package/dist/queries/files.d.ts +1 -1
  255. package/dist/queries/files.js +1 -1
  256. package/dist/queries/health.d.ts +2 -2
  257. package/dist/queries/health.js +1 -1
  258. package/dist/queries/hierarchy.d.ts +1 -1
  259. package/dist/queries/hierarchy.js +1 -1
  260. package/dist/queries/hotspots.d.ts +1 -1
  261. package/dist/queries/hotspots.js +1 -1
  262. package/dist/queries/imports.d.ts +1 -1
  263. package/dist/queries/imports.js +1 -1
  264. package/dist/queries/incomplete-migration.d.ts +1 -1
  265. package/dist/queries/incomplete-migration.js +1 -1
  266. package/dist/queries/index.d.ts +4 -4
  267. package/dist/queries/index.js +1 -1
  268. package/dist/queries/isolated.d.ts +1 -1
  269. package/dist/queries/isolated.js +1 -1
  270. package/dist/queries/locality-candidates.d.ts +1 -1
  271. package/dist/queries/locality-candidates.js +1 -1
  272. package/dist/queries/members.d.ts +1 -1
  273. package/dist/queries/members.js +1 -1
  274. package/dist/queries/methods.d.ts +1 -1
  275. package/dist/queries/methods.js +1 -1
  276. package/dist/queries/not-implemented.d.ts +1 -1
  277. package/dist/queries/not-implemented.js +1 -1
  278. package/dist/queries/outline.d.ts +1 -1
  279. package/dist/queries/outline.js +1 -1
  280. package/dist/queries/passthrough-candidates.d.ts +1 -1
  281. package/dist/queries/passthrough-candidates.js +1 -1
  282. package/dist/queries/plan-context.d.ts +1 -1
  283. package/dist/queries/plan-context.js +1 -1
  284. package/dist/queries/react-component-duplicates.d.ts +1 -1
  285. package/dist/queries/react-component-duplicates.js +1 -1
  286. package/dist/queries/react-hook-candidates.d.ts +1 -1
  287. package/dist/queries/react-hook-candidates.js +1 -1
  288. package/dist/queries/react-large-component-pressure.d.ts +1 -1
  289. package/dist/queries/react-large-component-pressure.js +1 -1
  290. package/dist/queries/recent-duplicates.d.ts +1 -1
  291. package/dist/queries/recent-duplicates.js +1 -1
  292. package/dist/queries/redundant-reexports.d.ts +1 -1
  293. package/dist/queries/redundant-reexports.js +1 -1
  294. package/dist/queries/reference-neighborhood.d.ts +1 -1
  295. package/dist/queries/reference-neighborhood.js +1 -1
  296. package/dist/queries/reference-reachability.d.ts +1 -1
  297. package/dist/queries/reference-reachability.js +1 -1
  298. package/dist/queries/refs.d.ts +1 -1
  299. package/dist/queries/refs.js +1 -1
  300. package/dist/queries/self-audit.d.ts +1 -1
  301. package/dist/queries/self-audit.js +1 -1
  302. package/dist/queries/similar-chains.d.ts +1 -1
  303. package/dist/queries/similar-chains.js +1 -1
  304. package/dist/queries/similar-files.d.ts +1 -1
  305. package/dist/queries/similar-files.js +1 -1
  306. package/dist/queries/similar-signatures.d.ts +1 -1
  307. package/dist/queries/similar-signatures.js +1 -1
  308. package/dist/queries/similar.d.ts +1 -1
  309. package/dist/queries/similar.js +1 -1
  310. package/dist/queries/slice.d.ts +1 -1
  311. package/dist/queries/slice.js +1 -1
  312. package/dist/queries/source-inspection.d.ts +3 -3
  313. package/dist/queries/source-inspection.js +1 -1
  314. package/dist/queries/source-search.d.ts +1 -1
  315. package/dist/queries/source-search.js +1 -1
  316. package/dist/queries/stale-abstractions.d.ts +1 -1
  317. package/dist/queries/stale-abstractions.js +1 -1
  318. package/dist/queries/stats.d.ts +1 -1
  319. package/dist/queries/surface.d.ts +1 -1
  320. package/dist/queries/surface.js +1 -1
  321. package/dist/queries/symbols.d.ts +1 -1
  322. package/dist/queries/symbols.js +1 -1
  323. package/dist/queries/system-map.d.ts +1 -1
  324. package/dist/queries/system-map.js +1 -1
  325. package/dist/queries/system.d.ts +1 -1
  326. package/dist/queries/system.js +1 -1
  327. package/dist/queries/test-quality.d.ts +1 -1
  328. package/dist/queries/test-quality.js +1 -1
  329. package/dist/queries/trace.d.ts +1 -1
  330. package/dist/queries/trace.js +1 -1
  331. package/dist/queries/twin-ab.d.ts +1 -1
  332. package/dist/queries/twin-ab.js +1 -1
  333. package/dist/queries/twin-drift.d.ts +1 -1
  334. package/dist/queries/twin-drift.js +1 -1
  335. package/dist/queries/unused-imports.d.ts +1 -1
  336. package/dist/queries/unused-imports.js +1 -1
  337. package/dist/queries/unused-params.d.ts +1 -1
  338. package/dist/queries/unused-params.js +1 -1
  339. package/dist/queries/value-flow.d.ts +2 -2
  340. package/dist/queries/value-flow.js +1 -1
  341. package/dist/queries/vue-component-duplicates.d.ts +1 -1
  342. package/dist/queries/vue-component-duplicates.js +1 -1
  343. package/dist/queries/vue-composable-candidates.d.ts +1 -1
  344. package/dist/queries/vue-composable-candidates.js +1 -1
  345. package/dist/queries/vue-large-view-pressure.d.ts +1 -1
  346. package/dist/queries/vue-large-view-pressure.js +1 -1
  347. package/dist/queries/wrapper-candidates.d.ts +1 -1
  348. package/dist/queries/wrapper-candidates.js +1 -1
  349. package/dist/reindex-worker.js +2 -2
  350. package/dist/reindex.d.ts +2 -4
  351. package/dist/reindex.js +71 -32
  352. package/dist/runtime.d.ts +1 -2
  353. package/dist/runtime.js +3 -3
  354. package/dist/rust-semantic-session-server.js +1 -1
  355. package/dist/rust-semantic-session-worker.js +1 -1
  356. package/dist/rust-semantic-worker.js +1 -1
  357. package/dist/sentinel-ensure-command-H66AZ3VE.js +2 -0
  358. package/dist/sentinel-ensure-command-R4YAUCJB.js +3 -0
  359. package/dist/sentinel-worker.js +1 -1
  360. package/dist/typescript-mailbox-worker.js +1 -1
  361. package/dist/watch-server.js +2 -2
  362. package/docs/INDEX_GENERATIONS.md +2 -2
  363. package/docs/NPM_RELEASE.md +323 -0
  364. package/docs/schemas/npm-release-state.schema.json +4 -13
  365. package/package.json +3 -11
  366. package/dist/chunk-2Q2LW5JW.js +0 -14
  367. package/dist/chunk-327YK6TB.js +0 -4
  368. package/dist/chunk-347TXATM.js +0 -2
  369. package/dist/chunk-36WRYYTE.js +0 -3
  370. package/dist/chunk-5IO2APSS.js +0 -2
  371. package/dist/chunk-6OAHRI2D.js +0 -6
  372. package/dist/chunk-6URCE5QY.js +0 -2
  373. package/dist/chunk-6ZV5EDUT.js +0 -5
  374. package/dist/chunk-7R64XY4Y.js +0 -12
  375. package/dist/chunk-CANBLFVQ.js +0 -15
  376. package/dist/chunk-CCRZLRWJ.js +0 -2
  377. package/dist/chunk-G2XUZCF2.js +0 -88
  378. package/dist/chunk-H5QXP63L.js +0 -2
  379. package/dist/chunk-HCMQZPEO.js +0 -2
  380. package/dist/chunk-IEL6Q5W3.js +0 -308
  381. package/dist/chunk-IGQQUENU.js +0 -109
  382. package/dist/chunk-K2O7SBAU.js +0 -2
  383. package/dist/chunk-QVWDQTMG.js +0 -2
  384. package/dist/chunk-RJWAB4VR.js +0 -345
  385. package/dist/chunk-VCL7FK3E.js +0 -3
  386. package/dist/chunk-WOOTEWQT.js +0 -239
  387. package/dist/chunk-XYLV727H.js +0 -21
  388. package/dist/chunk-YMGZZEW4.js +0 -2
  389. package/dist/direct-navigation-B3SGOOBW.js +0 -2
  390. package/dist/direct-navigation-ZL362KXF.js +0 -3
  391. package/dist/invocation-command-descriptors-CSUGUHTT.js +0 -2
  392. package/dist/invocation-command-descriptors-PPVZOIE5.js +0 -3
  393. package/dist/output-continuation-command-FTVVBVSN.js +0 -2
  394. package/dist/output-continuation-command-ITPRC3YV.js +0 -3
  395. package/dist/project-reindex-7HZSLLLY.js +0 -3
  396. package/dist/project-reindex-NGM3DYBN.js +0 -2
  397. package/dist/sentinel-ensure-command-KYYULCFU.js +0 -2
  398. package/dist/sentinel-ensure-command-RIZA3RY7.js +0 -3
  399. package/docs/WINDOWS_SIDECAR_RELEASE.md +0 -424
  400. package/docs/schemas/windows-sidecar-provenance.schema.json +0 -137
  401. package/scripts/build-codebaseiq-windows.mjs +0 -197
  402. package/scripts/codebaseiq-windows-provenance.mjs +0 -364
  403. package/scripts/verify-codebaseiq-windows.mjs +0 -29
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import{c as tp,e as np,f as qt}from"./chunk-B2OB55RR.js";import{b as kt,c as ec}from"./chunk-XZEE23VG.js";import{Q as Es,R as gf,_ as hf,aa as ws,ka as Zl,ma as yf,q as lf,r as yi,s as cf,v as Cs}from"./chunk-W3FK73MD.js";import{$ as Hr,$a as Kn,A as xn,Aa as Ke,Ab as sc,B as jr,Ba as As,Bb as Wn,C as Rf,Ca as J,Cb as Qf,D as If,Da as Rn,Db as Zf,E as ye,Ea as nr,Eb as ep,F as Ef,Fa as _f,Ga as pe,Ha as at,I as ae,Ia as Si,Ib as Kr,Ja as _s,Jb as Hs,Ka as Bf,Kb as ip,La as Of,Lb as rp,Ma as $f,Mb as op,N as te,Na as Bs,O as wf,Oa as nn,P as Ts,Pa as qn,Q as At,Qa as rn,R as tn,Ra as jf,S as Lf,Sa as Hf,Ta as Uf,Ua as ic,V as Xi,Va as zf,W as Fs,X as _t,Y as Qi,Ya as qf,Z as Df,Za as zr,_a as Kf,a as Hn,aa as Ce,ab as Gf,b as Fe,ba as ks,c as zt,ca as $e,d as Nt,da as Un,e as Cn,ea as zn,fa as Mf,fb as Wf,g as bf,ga as A,h as Sf,ha as Y,i as tc,ia as Bt,j as vf,ja as st,k as me,ka as _e,l as Ls,la as De,ma as Xe,n as Cf,na as Zi,nb as Vf,o as xf,oa as Pf,ob as Jf,pa as Tf,pb as Os,q as nc,qa as er,qb as Gn,r as Ct,ra as tr,rb as $s,s as $r,sa as Ff,sb as Yf,t as Ye,ta as W,tb as js,u as se,ua as Ue,ub as Xf,v as re,va as kf,w as Ds,wa as Nf,wb as qr,x as Ms,xa as Ur,y as Ps,ya as Ns,yb as rc,z as Oe,za as Af,zb as oc}from"./chunk-RJWAB4VR.js";import{d as tf,e as Vl}from"./chunk-D62CTZX6.js";import{A as sf,Ba as ff,Ca as Ql,Da as bi,E as vs,Ea as Yi,Fa as pf,Ga as Br,Ha as Or,Ia as Is,J as en,Y as af,aa as Ae,f as nf,g as Ss,ga as uf,h as ht,ha as B,i as Tt,ja as xs,k as vn,l as hi,la as Yl,na as Rs,oa as Xl,pa as rt,qa as ot,ra as Ft,sa as df,ta as mf,w as rf,x as of,y as Jl}from"./chunk-G2XUZCF2.js";import{B as jn,D as Pt,c as Kl,d as Gl,i as Zm,j as Gi,k as ef,l as pi,m as Wi,p as Vi,q as Zt,r as gi,v as Wl,w as ys,x as bs,y as Ji}from"./chunk-DUKHVPU5.js";function sp(e){return e+1}function bI(e,t){return`${sp(e)}-${sp(t)}`}function K2(e,t,n){return`${kt(e)}:${bI(t,n)}`}function G2(e,t=180){let n=kt(e).replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var ac={empty(e){console.log(kt(e))},list(e,t){for(let n of e)console.log(kt(t(n)))},groupedByFile(e,t,n=i=>i.relativePath){let i="";for(let r of e){let o=n(r);o!==i&&(i&&console.log(""),console.log(kt(o)),i=o),console.log(kt(t(r)))}},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 ${kt(n.title)} \u2550\u2550\u2550`),n.explanation!==void 0&&console.log(kt(n.explanation));for(let i of n.rows)console.log(kt(i))}},table(e,t,n){console.log(` ${e.map(kt).join(" ")}`);let i=n??e.map(r=>r.length);console.log(` ${i.map(r=>"\u2500".repeat(r)).join(" ")}`);for(let r of t)console.log(kt(r))}};import{SymbolInformation_Kind as Ie}from"@c4312/scip";var Us=new Map(Object.entries(Ie).filter(([e,t])=>Number.isInteger(Number(e))&&typeof t=="string").map(([e,t])=>[Number(e),t])),ap=new Map([...Us.entries()].map(([e,t])=>[t.toLowerCase(),e]));function Gr(e){return Us.get(e)??"Unknown"}function on(){return[Ie.Function,Ie.Method,Ie.Macro,Ie.Constructor,Ie.Getter,Ie.Setter,Ie.StaticMethod,Ie.SingletonMethod,Ie.AbstractMethod,Ie.ProtocolMethod,Ie.TraitMethod]}function lp(){return[Ie.Class,Ie.Interface,Ie.Struct,Ie.Trait,Ie.Type,Ie.TypeAlias,Ie.Enum,Ie.Union,Ie.Protocol]}function J2(){return[Ie.Constant,Ie.Variable,Ie.Value,Ie.Field,Ie.Property,Ie.StaticDataMember,Ie.StaticField,Ie.StaticProperty,Ie.StaticVariable,Ie.EnumMember]}import{existsSync as SI}from"fs";import{isAbsolute as vI,join as CI}from"path";function dt(e,t){let n=up(e,t,{allowMultiple:!1})[0]?.relativePath;return n||cp(e,t)}function In(e,t){return up(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function cp(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),i=vI(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,r=CI(e.config.projectRoot,i);return SI(r)?i:null}function up(e,t,n){let i=Ls(e,t,n);if(i.length===0){if(cp(e,t))return[];let r=pe(e,t);return!r||e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,score:700}]}return i}function lc(e,t){let n=In(e,t),i=Ns(e,n,{sort:!0});if(i.length===0)return[];let r=i.map(a=>({symbol:a.symbol,shortName:a.shortName,startLine:a.startLine,endLine:a.endLine,signature:a.signature,children:[]})),o=new Map;for(let a of r)o.set(a.symbol,a);let s=[];for(let a=0;a<i.length;a++){let l=i[a],c=r[a];if(l.enclosingSymbol&&o.has(l.enclosingSymbol)){o.get(l.enclosingSymbol).children.push(c);continue}let u=null,d=1/0;for(let m of r)if(m!==c&&m.startLine<=c.startLine&&m.endLine>=c.endLine){if(m.startLine===c.startLine&&m.endLine===c.endLine&&!Tf(m.symbol,c.symbol))continue;let p=m.endLine-m.startLine;p<d&&(d=p,u=m)}u?u.children.push(c):s.push(c)}return s}import{basename as ME,extname as $p}from"path";function xt(e,t){let n=re(e,t.relativePath);if(n.length===0)return!1;let i=Y(t.symbol);if(!i)return!1;let r=n.slice(Math.max(0,t.startLine-2),t.startLine+1).join(`
3
- `),o=Oe(i);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(r)?!0:xI(n,i)}function xI(e,t){if(!t)return!1;let n=new RegExp(`^\\s*export\\s*\\{[^}\\n]*\\b${Oe(t)}\\b`);return e.some(i=>n.test(i))}import{createHash as RI}from"crypto";import{TextDecoder as II}from"util";var EI=new II("utf-8",{fatal:!0});function cc(e){return df(e.config.projectRoot)}function zs(e,t){let n=vn(t),i;try{i=Xl(e.config.projectRoot,n,{inputKind:"repository text file"})}catch(o){if(ot(o)||o instanceof Yl)return null;throw o}let r=gp(i);return r===null?null:mp(n,i,r,pp(e),fp(e))}function qs(e,t={}){let n=cc(e).filter(u=>!t.scope||u.includes(t.scope)),i=pp(e),r=fp(e),o=[],s=[],a=[],l=[],c=0;for(let u of n){let d;try{d=Xl(e.config.projectRoot,u,{inputKind:"repository text file"})}catch(f){if(f instanceof Yl){l.push(u);continue}if(ot(f))continue;a.push(u);continue}let m=gp(d);if(m===null){s.push(u);continue}c+=d.byteLength,o.push(mp(u,d,m,i,r))}return{files:o,candidateFiles:n.length,scannedBytes:c,skippedBinaryPaths:s,skippedUnreadablePaths:a,skippedOversizedPaths:l}}function mp(e,t,n,i,r){let o=RI("sha256").update(t).digest("hex");return{relativePath:e,text:n,bytes:t.byteLength,freshness:{exactText:{state:"current",basis:"working-tree-read",sha256:o},semantic:wI(e,o,i,r)}}}function wI(e,t,n,i){if(!i.has(e))return{state:"unavailable",basis:"no-compiler-document"};let r=n.get(e);return r?{state:r===t?"aligned":"stale",basis:"indexed-input-fingerprint"}:{state:"unavailable",basis:"fingerprint-unavailable"}}function fp(e){return new Set(e.all(`SELECT documents.relative_path FROM documents WHERE 1 = 1 ${e.pathExclusionsFor("documents")}`).map(t=>t.relative_path))}function pp(e){let t=new Map;if(!e.generation.metadataRaw)return t;let n=vs(e.generation.metadataRaw);if(n.kind!=="legacy"&&n.kind!=="supported")return t;let i=n.metadata.fingerprint;if(!dp(i)||!Array.isArray(i.files))return t;for(let r of i.files)!dp(r)||typeof r.path!="string"||typeof r.hash!="string"||t.set(r.path,r.hash);return t}function gp(e){if(e.includes(0))return null;try{return EI.decode(e)}catch{return null}}function dp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ks(e,t,n={}){return vi(e,t,n).rows}function vi(e,t,n={}){let i=Wr(e,[t],{additive:n.additive,semantic:n.semantic,semanticEvidence:n.semanticEvidence}),r=n.callableOnly?(i.rows.get(t.symbolId)??[]).filter(o=>st(o.symbol)||o.source==="ast-callsite"):i.rows.get(t.symbolId)??[];return{rows:typeof n.limit=="number"?r.slice(0,n.limit):r,semanticIncomplete:i.incompleteSymbolIds.has(t.symbolId),semanticUnavailable:i.unavailableSymbolIds.has(t.symbolId)}}function Gs(e,t,n){return dc(e,t,n).rows}function dc(e,t,n){let i=sn(e,[t],n);return{rows:i.rows.get(t.symbolId)??[],semanticIncomplete:i.incompleteSymbolIds.has(t.symbolId),semanticUnavailable:i.unavailableSymbolIds.has(t.symbolId)}}function yp(e,t,n){return sn(e,t,n).rows}function sn(e,t,n){let i=TI(e)?kI(e,t,{semantic:n.semantic!==!1,semanticEvidence:n.semanticEvidence}):FI(e,n.semanticEvidence,{semantic:n.semantic!==!1});return{rows:new Map(t.map(o=>[o.symbolId,typeof n.limit=="number"?(i.rows.get(o.symbolId)??[]).slice(0,n.limit):i.rows.get(o.symbolId)??[]])),incompleteSymbolIds:new Set(t.filter(o=>i.incompleteSymbolIds.has(o.symbolId)).map(o=>o.symbolId)),unavailableSymbolIds:new Set(t.filter(o=>i.unavailableSymbolIds.has(o.symbolId)).map(o=>o.symbolId))}}var LI=Fe("caller-rows",{clearGroups:["whole-project"]}),DI=Fe("caller-rows-non-semantic",{clearGroups:["whole-project"]}),MI=Fe("targeted-caller-strategy",{clearGroups:["whole-project"]}),PI=2e4;function TI(e){return MI.get(e,()=>(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>PI)}function FI(e,t,n={}){return(n.semantic===!1?DI:LI).get(e,()=>{let r=Ue(e),o=Wr(e,r,{semantic:n.semantic!==!1,semanticEvidence:t}),s=new Map;for(let c of r)s.set(c.symbol,c.symbolId);let a=new Map,l=new Map;for(let c of r){let u=o.rows.get(c.symbolId);if(!(!u||u.length===0))for(let d of u){let m=s.get(d.symbol);if(m===void 0||m===c.symbolId)continue;let f=a.get(m);f||(f=[],a.set(m,f),l.set(m,new Set));let p=`${c.symbol}|${c.relativePath}`;l.get(m).has(p)||(l.get(m).add(p),f.push({symbol:c.symbol,file:c.relativePath,source:"caller-map-inversion",callEvidence:d.source}))}}return{rows:a,incompleteSymbolIds:o.incompleteSymbolIds.size===0?new Set:new Set(r.map(c=>c.symbolId)),unavailableSymbolIds:o.unavailableSymbolIds.size===0?new Set:new Set(r.map(c=>c.symbolId))}})}function kI(e,t,n){let i=n.semantic&&n.semanticEvidence?t.flatMap(u=>{let d=NI(e,u);return d?[d]:[]}):[],r=new Map(i.map(u=>[u.symbolId,u])),o=n.semantic&&n.semanticEvidence?n.semanticEvidence.referenceEvidenceMap(e,i):{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set},s=Kf(e,t),a=new Map;for(let u of t){let d=[],m=new Set,f=g=>{if(g.symbol===u.symbol)return;let h=`${g.symbol}|${g.file}`;m.has(h)||(m.add(h),d.push(g))};for(let g of s.get(u.symbolId)??[])g.file!==u.relativePath&&f({symbol:g.enclosingSymbol??g.file,file:g.file,source:"resolved-reference"});let p=r.get(u.symbolId);if(p)for(let g of o.rows.get(p.symbolId)??[]){if(g.file===u.relativePath||e.isIgnored(g.file))continue;let h=Ke(W(e,g.file),g.line);f({symbol:h?.symbol??g.file,file:g.file,source:"semantic-reference"})}a.set(u.symbolId,d)}let l=new Set(o.incompleteSymbolIds),c=new Set(o.unavailableSymbolIds);if(n.semantic)for(let u of t)r.has(u.symbolId)||l.add(u.symbolId);return{rows:a,incompleteSymbolIds:l,unavailableSymbolIds:c}}function NI(e,t){let n=on().join(", "),i=lp().join(", ");return e.get(`SELECT
2
+ import{c as Qf,e as Zf,f as qt}from"./chunk-B2OB55RR.js";import{b as kt,c as Zl}from"./chunk-XZEE23VG.js";import{Q as Rs,R as df,_ as mf,aa as Is,ka as Ql,ma as ff,q as rf,r as yi,s as of,v as Ss}from"./chunk-7UCDGXRW.js";import{$ as $r,$a as Kn,A as xn,Aa as Ke,Ab as Ur,B as Or,Ba as ks,C as Sf,Ca as J,Cb as ic,D as vf,Da as Rn,Db as rc,E as ye,Ea as er,Eb as oc,F as Cf,Fa as Ff,Fb as Wn,Ga as pe,Gb as Jf,Ha as at,Hb as Yf,I as ae,Ia as Si,Ib as Xf,Ja as Ns,Ka as kf,La as Nf,Ma as Af,Mb as zr,N as te,Na as As,Nb as js,O as xf,Oa as nn,Ob as ep,P as Ms,Pa as qn,Pb as tp,Q as At,Qa as rn,Qb as np,R as tn,Ra as _f,S as Rf,Sa as Bf,Ta as Of,Ua as nc,V as Ji,Va as $f,W as Ps,X as _t,Y as Yi,Ya as jf,Z as If,Za as Hr,_a as Hf,a as Hn,aa as Ce,ab as Uf,b as Fe,ba as Ts,c as zt,ca as $e,d as Nt,da as Un,e as Cn,ea as zn,fa as Ef,fb as zf,g as pf,ga as A,h as gf,ha as Y,i as ec,ia as Bt,j as hf,ja as st,k as me,ka as _e,l as Es,la as De,ma as Xe,n as yf,na as Xi,nb as qf,o as bf,oa as wf,pa as Lf,q as tc,qa as Qi,qb as _s,r as Ct,ra as Zi,rb as Kf,s as Br,sa as Df,sb as Gf,t as Ye,ta as W,tb as Bs,u as se,ua as Ue,ub as Gn,v as re,va as Mf,vb as Os,w as ws,wa as Pf,wb as Wf,x as Ls,xa as jr,xb as $s,y as Ds,ya as Fs,yb as Vf,z as Oe,za as Tf}from"./chunk-EOKVZXNF.js";import{d as Xm,e as Wl}from"./chunk-D62CTZX6.js";import{A as tf,Ba as cf,Ca as Xl,Da as bi,E as bs,Ea as Vi,Fa as uf,Ga as Ar,Ha as _r,Ia as xs,J as en,Y as nf,aa as Ae,f as Qm,g as ys,ga as sf,h as ht,ha as B,i as Tt,ja as vs,k as vn,l as hi,la as Jl,na as Cs,oa as Yl,pa as rt,qa as ot,ra as Ft,sa as af,ta as lf,w as Zm,x as ef,y as Vl}from"./chunk-5T44HG5Y.js";import{B as jn,D as Pt,c as ql,d as Kl,i as Jm,j as Gi,k as Ym,l as pi,q as Zt,r as gi,v as Gl,w as gs,x as hs,y as Wi}from"./chunk-DUKHVPU5.js";function ip(e){return e+1}function hI(e,t){return`${ip(e)}-${ip(t)}`}function A2(e,t,n){return`${kt(e)}:${hI(t,n)}`}function _2(e,t=180){let n=kt(e).replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var sc={empty(e){console.log(kt(e))},list(e,t){for(let n of e)console.log(kt(t(n)))},groupedByFile(e,t,n=i=>i.relativePath){let i="";for(let r of e){let o=n(r);o!==i&&(i&&console.log(""),console.log(kt(o)),i=o),console.log(kt(t(r)))}},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 ${kt(n.title)} \u2550\u2550\u2550`),n.explanation!==void 0&&console.log(kt(n.explanation));for(let i of n.rows)console.log(kt(i))}},table(e,t,n){console.log(` ${e.map(kt).join(" ")}`);let i=n??e.map(r=>r.length);console.log(` ${i.map(r=>"\u2500".repeat(r)).join(" ")}`);for(let r of t)console.log(kt(r))}};import{SymbolInformation_Kind as Ie}from"@c4312/scip";var Hs=new Map(Object.entries(Ie).filter(([e,t])=>Number.isInteger(Number(e))&&typeof t=="string").map(([e,t])=>[Number(e),t])),rp=new Map([...Hs.entries()].map(([e,t])=>[t.toLowerCase(),e]));function qr(e){return Hs.get(e)??"Unknown"}function on(){return[Ie.Function,Ie.Method,Ie.Macro,Ie.Constructor,Ie.Getter,Ie.Setter,Ie.StaticMethod,Ie.SingletonMethod,Ie.AbstractMethod,Ie.ProtocolMethod,Ie.TraitMethod]}function op(){return[Ie.Class,Ie.Interface,Ie.Struct,Ie.Trait,Ie.Type,Ie.TypeAlias,Ie.Enum,Ie.Union,Ie.Protocol]}function $2(){return[Ie.Constant,Ie.Variable,Ie.Value,Ie.Field,Ie.Property,Ie.StaticDataMember,Ie.StaticField,Ie.StaticProperty,Ie.StaticVariable,Ie.EnumMember]}import{existsSync as yI}from"fs";import{isAbsolute as bI,join as SI}from"path";function dt(e,t){let n=ap(e,t,{allowMultiple:!1})[0]?.relativePath;return n||sp(e,t)}function In(e,t){return ap(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function sp(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),i=bI(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,r=SI(e.config.projectRoot,i);return yI(r)?i:null}function ap(e,t,n){let i=Es(e,t,n);if(i.length===0){if(sp(e,t))return[];let r=pe(e,t);return!r||e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,score:700}]}return i}function ac(e,t){let n=In(e,t),i=Fs(e,n,{sort:!0});if(i.length===0)return[];let r=i.map(a=>({symbol:a.symbol,shortName:a.shortName,startLine:a.startLine,endLine:a.endLine,signature:a.signature,children:[]})),o=new Map;for(let a of r)o.set(a.symbol,a);let s=[];for(let a=0;a<i.length;a++){let l=i[a],c=r[a];if(l.enclosingSymbol&&o.has(l.enclosingSymbol)){o.get(l.enclosingSymbol).children.push(c);continue}let u=null,d=1/0;for(let m of r)if(m!==c&&m.startLine<=c.startLine&&m.endLine>=c.endLine){if(m.startLine===c.startLine&&m.endLine===c.endLine&&!Lf(m.symbol,c.symbol))continue;let p=m.endLine-m.startLine;p<d&&(d=p,u=m)}u?u.children.push(c):s.push(c)}return s}import{basename as LE,extname as _p}from"path";function xt(e,t){let n=re(e,t.relativePath);if(n.length===0)return!1;let i=Y(t.symbol);if(!i)return!1;let r=n.slice(Math.max(0,t.startLine-2),t.startLine+1).join(`
3
+ `),o=Oe(i);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(r)?!0:vI(n,i)}function vI(e,t){if(!t)return!1;let n=new RegExp(`^\\s*export\\s*\\{[^}\\n]*\\b${Oe(t)}\\b`);return e.some(i=>n.test(i))}import{createHash as CI}from"crypto";import{TextDecoder as xI}from"util";var RI=new xI("utf-8",{fatal:!0});function lc(e){return af(e.config.projectRoot)}function Us(e,t){let n=vn(t),i;try{i=Yl(e.config.projectRoot,n,{inputKind:"repository text file"})}catch(o){if(ot(o)||o instanceof Jl)return null;throw o}let r=mp(i);return r===null?null:cp(n,i,r,dp(e),up(e))}function zs(e,t={}){let n=lc(e).filter(u=>!t.scope||u.includes(t.scope)),i=dp(e),r=up(e),o=[],s=[],a=[],l=[],c=0;for(let u of n){let d;try{d=Yl(e.config.projectRoot,u,{inputKind:"repository text file"})}catch(f){if(f instanceof Jl){l.push(u);continue}if(ot(f))continue;a.push(u);continue}let m=mp(d);if(m===null){s.push(u);continue}c+=d.byteLength,o.push(cp(u,d,m,i,r))}return{files:o,candidateFiles:n.length,scannedBytes:c,skippedBinaryPaths:s,skippedUnreadablePaths:a,skippedOversizedPaths:l}}function cp(e,t,n,i,r){let o=CI("sha256").update(t).digest("hex");return{relativePath:e,text:n,bytes:t.byteLength,freshness:{exactText:{state:"current",basis:"working-tree-read",sha256:o},semantic:II(e,o,i,r)}}}function II(e,t,n,i){if(!i.has(e))return{state:"unavailable",basis:"no-compiler-document"};let r=n.get(e);return r?{state:r===t?"aligned":"stale",basis:"indexed-input-fingerprint"}:{state:"unavailable",basis:"fingerprint-unavailable"}}function up(e){return new Set(e.all(`SELECT documents.relative_path FROM documents WHERE 1 = 1 ${e.pathExclusionsFor("documents")}`).map(t=>t.relative_path))}function dp(e){let t=new Map;if(!e.generation.metadataRaw)return t;let n=bs(e.generation.metadataRaw);if(n.kind!=="legacy"&&n.kind!=="supported")return t;let i=n.metadata.fingerprint;if(!lp(i)||!Array.isArray(i.files))return t;for(let r of i.files)!lp(r)||typeof r.path!="string"||typeof r.hash!="string"||t.set(r.path,r.hash);return t}function mp(e){if(e.includes(0))return null;try{return RI.decode(e)}catch{return null}}function lp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qs(e,t,n={}){return vi(e,t,n).rows}function vi(e,t,n={}){let i=Kr(e,[t],{additive:n.additive,semantic:n.semantic,semanticEvidence:n.semanticEvidence}),r=n.callableOnly?(i.rows.get(t.symbolId)??[]).filter(o=>st(o.symbol)||o.source==="ast-callsite"):i.rows.get(t.symbolId)??[];return{rows:typeof n.limit=="number"?r.slice(0,n.limit):r,semanticIncomplete:i.incompleteSymbolIds.has(t.symbolId),semanticUnavailable:i.unavailableSymbolIds.has(t.symbolId)}}function Ks(e,t,n){return uc(e,t,n).rows}function uc(e,t,n){let i=sn(e,[t],n);return{rows:i.rows.get(t.symbolId)??[],semanticIncomplete:i.incompleteSymbolIds.has(t.symbolId),semanticUnavailable:i.unavailableSymbolIds.has(t.symbolId)}}function pp(e,t,n){return sn(e,t,n).rows}function sn(e,t,n){let i=MI(e)?TI(e,t,{semantic:n.semantic!==!1,semanticEvidence:n.semanticEvidence}):PI(e,n.semanticEvidence,{semantic:n.semantic!==!1});return{rows:new Map(t.map(o=>[o.symbolId,typeof n.limit=="number"?(i.rows.get(o.symbolId)??[]).slice(0,n.limit):i.rows.get(o.symbolId)??[]])),incompleteSymbolIds:new Set(t.filter(o=>i.incompleteSymbolIds.has(o.symbolId)).map(o=>o.symbolId)),unavailableSymbolIds:new Set(t.filter(o=>i.unavailableSymbolIds.has(o.symbolId)).map(o=>o.symbolId))}}var EI=Fe("caller-rows",{clearGroups:["whole-project"]}),wI=Fe("caller-rows-non-semantic",{clearGroups:["whole-project"]}),LI=Fe("targeted-caller-strategy",{clearGroups:["whole-project"]}),DI=2e4;function MI(e){return LI.get(e,()=>(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>DI)}function PI(e,t,n={}){return(n.semantic===!1?wI:EI).get(e,()=>{let r=Ue(e),o=Kr(e,r,{semantic:n.semantic!==!1,semanticEvidence:t}),s=new Map;for(let c of r)s.set(c.symbol,c.symbolId);let a=new Map,l=new Map;for(let c of r){let u=o.rows.get(c.symbolId);if(!(!u||u.length===0))for(let d of u){let m=s.get(d.symbol);if(m===void 0||m===c.symbolId)continue;let f=a.get(m);f||(f=[],a.set(m,f),l.set(m,new Set));let p=`${c.symbol}|${c.relativePath}`;l.get(m).has(p)||(l.get(m).add(p),f.push({symbol:c.symbol,file:c.relativePath,source:"caller-map-inversion",callEvidence:d.source}))}}return{rows:a,incompleteSymbolIds:o.incompleteSymbolIds.size===0?new Set:new Set(r.map(c=>c.symbolId)),unavailableSymbolIds:o.unavailableSymbolIds.size===0?new Set:new Set(r.map(c=>c.symbolId))}})}function TI(e,t,n){let i=n.semantic&&n.semanticEvidence?t.flatMap(u=>{let d=FI(e,u);return d?[d]:[]}):[],r=new Map(i.map(u=>[u.symbolId,u])),o=n.semantic&&n.semanticEvidence?n.semanticEvidence.referenceEvidenceMap(e,i):{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set},s=Hf(e,t),a=new Map;for(let u of t){let d=[],m=new Set,f=g=>{if(g.symbol===u.symbol)return;let h=`${g.symbol}|${g.file}`;m.has(h)||(m.add(h),d.push(g))};for(let g of s.get(u.symbolId)??[])g.file!==u.relativePath&&f({symbol:g.enclosingSymbol??g.file,file:g.file,source:"resolved-reference"});let p=r.get(u.symbolId);if(p)for(let g of o.rows.get(p.symbolId)??[]){if(g.file===u.relativePath||e.isIgnored(g.file))continue;let h=Ke(W(e,g.file),g.line);f({symbol:h?.symbol??g.file,file:g.file,source:"semantic-reference"})}a.set(u.symbolId,d)}let l=new Set(o.incompleteSymbolIds),c=new Set(o.unavailableSymbolIds);if(n.semantic)for(let u of t)r.has(u.symbolId)||l.add(u.symbolId);return{rows:a,incompleteSymbolIds:l,unavailableSymbolIds:c}}function FI(e,t){let n=on().join(", "),i=op().join(", ");return e.get(`SELECT
4
4
  d.id AS documentId,
5
5
  gs.id AS symbolId,
6
6
  gs.symbol,
@@ -19,11 +19,11 @@ import{c as tp,e as np,f as qt}from"./chunk-B2OB55RR.js";import{b as kt,c as ec}
19
19
  LEFT JOIN chunks c ON c.document_id = der.document_id
20
20
  JOIN documents d ON d.id = COALESCE(der.document_id, c.document_id)
21
21
  WHERE gs.id = ?
22
- LIMIT 1`,t.symbolId)??null}function mc(e,t,n={}){return Wr(e,t,n).rows}function Wr(e,t,n={}){if(t.length===0)return{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set};let i=n.additive??!1,r=[],o=[];for(let m of t)ye(m.relativePath)&&tn(e,m.relativePath)!==null?r.push(m):o.push(m);let s=new Map,a=new Map,l=m=>{for(let[f,p]of m){let g=s.get(f);g||(g=[],s.set(f,g));let h=a.get(f);h||(h=new Set,a.set(f,h));for(let b of p){let v=`${b.symbol}|${b.chunkId}`;h.has(v)||(h.add(v),g.push(b))}}};r.length>0&&l(AI(e,r));let c=new Set,u=new Set;if(n.semantic!==!1&&n.semanticEvidence){let m=n.semanticEvidence.calleeEvidenceMap(e,t);l(HI(m.rows));for(let f of m.incompleteSymbolIds)c.add(f);for(let f of m.unavailableSymbolIds)u.add(f)}else if(n.semantic!==!1)for(let m of t)u.add(m.symbolId);let d=i?t:o;return d.length>0&&l($I(e,d)),{rows:s,incompleteSymbolIds:c,unavailableSymbolIds:u}}function AI(e,t){let n=new Map,i=_I(t,n),r=rn(e);for(let[o,s]of i){let a=tn(e,o);if(!a)continue;let l=Af(s);for(let c of a){let u=l.get(c.line);if(!u)continue;let d=BI(e,o,r,c);d&&d.symbol!==u.symbol&&n.get(u.symbolId).push({symbol:d.symbol,file:d.file,chunkId:c.line,source:"ast-callsite",callsiteLine:c.line})}}return n}function _I(e,t){let n=new Map;for(let i of e){let r=n.get(i.relativePath);r?r.push(i):n.set(i.relativePath,[i]),t.set(i.symbolId,[])}for(let i of n.values())i.sort((r,o)=>r.endLine-r.startLine-(o.endLine-o.startLine));return n}function BI(e,t,n,i){let r=nn(t,n.get(i.calleeLeaf)??[]);if(r.length===0)return null;let o=OI(e,t,r,i.calleeQualifier);return o||qn(e,t,r,i.memberAccess,i.calleeQualifier)}function OI(e,t,n,i){if(!i||ye(t)!=="clojure")return null;let o=Ce(e,t).filter(s=>s.kind==="namespace"&&s.localName===i&&s.sourcePath).map(s=>s.sourcePath);for(let s of o){let a=n.find(l=>Tt(s,l.file));if(a)return a}return n.find(s=>/`([^`]+)`\//.exec(s.symbol)?.[1]===i)??null}function $I(e,t){if(t.length===0)return new Map;let i=uc(t.map(f=>f.documentId)).flatMap(f=>e.all(`SELECT c.document_id, c.id AS chunk_id, c.start_line, c.end_line, m.symbol_id
22
+ LIMIT 1`,t.symbolId)??null}function dc(e,t,n={}){return Kr(e,t,n).rows}function Kr(e,t,n={}){if(t.length===0)return{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set};let i=n.additive??!1,r=[],o=[];for(let m of t)ye(m.relativePath)&&tn(e,m.relativePath)!==null?r.push(m):o.push(m);let s=new Map,a=new Map,l=m=>{for(let[f,p]of m){let g=s.get(f);g||(g=[],s.set(f,g));let h=a.get(f);h||(h=new Set,a.set(f,h));for(let b of p){let v=`${b.symbol}|${b.chunkId}`;h.has(v)||(h.add(v),g.push(b))}}};r.length>0&&l(kI(e,r));let c=new Set,u=new Set;if(n.semantic!==!1&&n.semanticEvidence){let m=n.semanticEvidence.calleeEvidenceMap(e,t);l($I(m.rows));for(let f of m.incompleteSymbolIds)c.add(f);for(let f of m.unavailableSymbolIds)u.add(f)}else if(n.semantic!==!1)for(let m of t)u.add(m.symbolId);let d=i?t:o;return d.length>0&&l(BI(e,d)),{rows:s,incompleteSymbolIds:c,unavailableSymbolIds:u}}function kI(e,t){let n=new Map,i=NI(t,n),r=rn(e);for(let[o,s]of i){let a=tn(e,o);if(!a)continue;let l=Tf(s);for(let c of a){let u=l.get(c.line);if(!u)continue;let d=AI(e,o,r,c);d&&d.symbol!==u.symbol&&n.get(u.symbolId).push({symbol:d.symbol,file:d.file,chunkId:c.line,source:"ast-callsite",callsiteLine:c.line})}}return n}function NI(e,t){let n=new Map;for(let i of e){let r=n.get(i.relativePath);r?r.push(i):n.set(i.relativePath,[i]),t.set(i.symbolId,[])}for(let i of n.values())i.sort((r,o)=>r.endLine-r.startLine-(o.endLine-o.startLine));return n}function AI(e,t,n,i){let r=nn(t,n.get(i.calleeLeaf)??[]);if(r.length===0)return null;let o=_I(e,t,r,i.calleeQualifier);return o||qn(e,t,r,i.memberAccess,i.calleeQualifier)}function _I(e,t,n,i){if(!i||ye(t)!=="clojure")return null;let o=Ce(e,t).filter(s=>s.kind==="namespace"&&s.localName===i&&s.sourcePath).map(s=>s.sourcePath);for(let s of o){let a=n.find(l=>Tt(s,l.file));if(a)return a}return n.find(s=>/`([^`]+)`\//.exec(s.symbol)?.[1]===i)??null}function BI(e,t){if(t.length===0)return new Map;let i=cc(t.map(f=>f.documentId)).flatMap(f=>e.all(`SELECT c.document_id, c.id AS chunk_id, c.start_line, c.end_line, m.symbol_id
23
23
  FROM mentions m
24
24
  JOIN chunks c ON m.chunk_id = c.id
25
25
  WHERE m.role != 1
26
- AND c.document_id IN (${f.map(()=>"?").join(",")})`,...f)),r=new Map;for(let f of i)r.has(f.document_id)||r.set(f.document_id,[]),r.get(f.document_id).push(f);let s=uc(i.map(f=>f.symbol_id)).flatMap(f=>e.all(`SELECT gs.id AS symbol_id, gs.symbol,
26
+ AND c.document_id IN (${f.map(()=>"?").join(",")})`,...f)),r=new Map;for(let f of i)r.has(f.document_id)||r.set(f.document_id,[]),r.get(f.document_id).push(f);let s=cc(i.map(f=>f.symbol_id)).flatMap(f=>e.all(`SELECT gs.id AS symbol_id, gs.symbol,
27
27
  COALESCE(der.document_id, def_chunk.document_id) AS document_id
28
28
  FROM global_symbols gs
29
29
  LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
@@ -35,46 +35,46 @@ import{c as tp,e as np,f as qt}from"./chunk-B2OB55RR.js";import{b as kt,c as ec}
35
35
  AND m.symbol_id IN (${f.map(()=>"?").join(",")})
36
36
  GROUP BY m.symbol_id
37
37
  ) def_chunk ON def_chunk.symbol_id = gs.id
38
- WHERE gs.id IN (${f.map(()=>"?").join(",")})`,...f,...f)),a=uc([...t.map(f=>f.documentId),...s.flatMap(f=>f.document_id===null?[]:[f.document_id])]),l=new Map(a.flatMap(f=>e.all(`SELECT id, relative_path FROM documents
39
- WHERE id IN (${f.map(()=>"?").join(",")})`,...f).map(p=>[p.id,p.relative_path]))),c=new Map;for(let f of s)c.has(f.symbol_id)||c.set(f.symbol_id,{symbol:f.symbol,file:f.document_id!==null?l.get(f.document_id)??"":""});let u=new Map,d=l,m=jI(t);for(let[f,p]of m){let h=[...r.get(f)??[]].sort((I,E)=>I.start_line-E.start_line||I.end_line-E.end_line),b=[...p].sort((I,E)=>I.startLine-E.startLine||I.endLine-E.endLine),v=new Set,y=0;for(let I of b){for(;y<h.length&&h[y].start_line<=I.endLine;)v.add(h[y]),y+=1;for(let L of v)L.end_line<I.startLine&&v.delete(L);let E=new Set,S=[],x=null,C=()=>{if(x)return x;let L=d.get(I.documentId)??"",w=new Set;if(L){let R=_f(e,L),M=Math.max(0,I.startLine),_=Math.min(R.length-1,I.endLine);for(let D=M;D<=_;D+=1)for(let P of R[D])w.add(P)}return x=w,w};for(let L of v){if(L.symbol_id===I.symbolId)continue;let w=c.get(L.symbol_id);if(!w)continue;if(!(L.start_line>=I.startLine&&L.end_line<=I.endLine)){if(!(L.start_line<=I.endLine&&L.end_line>=I.startLine))continue;let D=Y(w.symbol);if(!D||!C().has(D))continue}let M=`${w.symbol}|${L.chunk_id}`;E.has(M)||(E.add(M),S.push({...w,chunkId:L.chunk_id,source:"scip-chunk"}))}u.set(I.symbolId,S)}}return u}var hp=500;function uc(e){let t=[...new Set(e)],n=[];for(let i=0;i<t.length;i+=hp)n.push(t.slice(i,i+hp));return n}function jI(e){let t=new Map;for(let n of e){let i=t.get(n.documentId);i?i.push(n):t.set(n.documentId,[n])}return t}function HI(e){let t=new Map;for(let[n,i]of e){let r=[];for(let o of i)r.push({symbol:o.symbol,file:o.file,chunkId:-1,source:"semantic-callee",...o.callsiteLine===void 0?{}:{callsiteLine:o.callsiteLine}});t.set(n,r)}return t}var UI=12,zI=280;function ir(e,t,n,i){let r=qI(e,t,n,i);if(r.size===0)return VI();let o=[],s=new Set,a=(c,u,d,m)=>{if(u===t&&d<=i&&m>=n)return;let f=`${u}:${d}:${m}:${c}`;s.has(f)||(s.add(f),o.push({name:c,relativePath:u,startLine:d,endLine:m}))};for(let c of W(e,t))r.has(c.leaf)&&a(c.leaf,c.relativePath,c.startLine,c.endLine);for(let c of Ce(e,t)){let u=c.localName;if(!u||!r.has(u)||!c.sourcePath||c.kind==="namespace")continue;let d=c.importedName==="default"?u:c.importedName;for(let m of Wn(e,c.sourcePath,d,{maxReexportDepth:3}))a(u,m.relativePath,m.startLine,m.endLine)}o.sort(Sp);let l=o.map(c=>{let u=KI(e,c);return u?{...c,source:u}:null}).filter(c=>c!==null).slice(0,UI);return fc(l)}function Ws(e,t=[]){return fc(GI(e.flatMap(n=>n?.inline??[]),t))}function bp(e){return e?e.inline.reduce((t,n)=>t+n.name.length+n.source.length+32,0):0}function qI(e,t,n,i){let r=te(e,t),o=new Set;if(!r)return o;for(let s=n;s<=i;s+=1)for(let a of r.identifiersByLine[s]??[])o.add(a);return o}function KI(e,t){if(t.startLine!==t.endLine)return null;let n=(re(e,t.relativePath)[t.startLine]??"").trim();if(!n||n.length>zI)return null;let i=n.indexOf("=");if(i<0||n[i+1]===">")return null;let r=n.slice(i+1).replace(/(?:\/\/|#).*$/u,"").trim();if(!r||r.includes("${")||/\b(?:function|class|struct|interface|trait|enum|lambda)\b/u.test(r))return null;let s=r.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(c=>!a.has(c))?null:n}function GI(e,t){let n=new Map;for(let i of e){if(WI(i,t))continue;let r=`${i.relativePath}:${i.startLine}:${i.endLine}:${i.name}`;n.has(r)||n.set(r,{...i})}return[...n.values()].sort(Sp)}function WI(e,t){return t.some(n=>n.relativePath===e.relativePath&&n.startLine<=e.startLine&&n.endLine>=e.endLine)}function Sp(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||e.name.localeCompare(t.name)}function fc(e){return{coverage:"indexed-project-literal-values",inline:e}}function VI(){return fc([])}var JI=12,YI=20,gc=200,hc=800,XI=.9,Cp={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"},Zs=["anchor","signature","binding","branch","loop","call","await","return","throw","mutation","shape","spread","catch","finally"],xp=[...Zs,"lifecycle"],Rp=["loop","await","throw","mutation","spread","catch","finally","lifecycle"],QI=new Set(["onBeforeMount","onBeforeUnmount","onMounted","onUnmounted","useEffect","useInsertionEffect","useLayoutEffect"]);var Ip=new Set(["object","object_pattern","dictionary","field_declaration_list","struct_expression","struct_pattern"]);function rr(e,t,n,i,r=[],o={}){let s=ae(e,t);if(!s)return null;let a=re(e,t),l=yt(e,t,n,i,r),c=na(e,t,l.startLine,l.endLine),u=c?.startLine??n,d=c?.endLine??i,m=(c?or(s.rootNode,l.startLine,l.endLine):null)??to(s.rootNode,u,d);if(!m)return null;let f=Mp(m,a,u,d,r);if(!f||f.lines.length===0||f.lines.some(b=>b.text.length>hc))return null;let p=hE(a,u,d),g=yE(f);if((o.requireSavings??!0)&&g>=p*XI)return null;let h=Zs.filter(b=>f.lines.some(v=>v.signals.includes(b)));return{...c?{callable:{name:c.name,startLine:c.startLine,endLine:c.endLine}}:{},representation:"outline",constructKind:f.constructKind,signature:f.signature,lines:f.lines,signals:h,testCases:J(t)==="test"?xE(a,u,d):[],coverage:{sourceStatements:f.sourceStatements,representedStatements:f.sourceStatements,copiedStatements:f.copiedStatements,omittedStatements:0},rawCharacters:p,outlineCharacters:g,candidateLines:f.sourceStatements,omittedLines:0}}function ea(e,t,n,i,r){if(r.length===0)return[];let o=ae(e,t);if(!o)return[];let s=re(e,t),a=yt(e,t,n,i,r),l=na(e,t,a.startLine,a.endLine),c=l?.startLine??n,u=l?.endLine??i,d=(l?or(o.rootNode,a.startLine,a.endLine):null)??to(o.rootNode,c,u);if(!d)return[];let m=Mp(d,s,c,u,r);return m?m.lines.filter(f=>f.text.length<=hc&&f.signals.some(p=>["branch","loop","catch","finally"].includes(p))&&r.some(p=>p>=f.line&&p<=f.endLine)):[]}function Ep(e,t,n,i){let r=ae(e,t);if(!r)return null;let o=or(r.rootNode,n,i)??to(r.rootNode,n,i);if(!o)return null;let s=[],a=Sc(o),l=[];return vc(o,o,c=>{if(Jr.has(c.type)||ZI.has(c.type)){tE(s,l,c);return}if(ta.has(c.type)){nE(s,l,c);return}if(Zr.has(c.type)){iE(s,l,c);return}eo.has(c.type)&&rE(s,c)}),{facts:cE(s),terminals:Dp(a),unsupported:l}}function yt(e,t,n,i,r=[]){let o=r.filter(d=>d>=n&&d<=i),s=ae(e,t);if(o.length>0&&s){let d=[];Ci(s.rootNode,f=>{uE(f)&&f.startPosition.row>=n&&f.endPosition.row<=i&&o.every(p=>f.startPosition.row<=p&&f.endPosition.row>=p)&&d.push(f)});let m=d.sort((f,p)=>f.endPosition.row-f.startPosition.row-(p.endPosition.row-p.startPosition.row)||f.startPosition.row-p.startPosition.row)[0];if(m)return{startLine:m.startPosition.row,endLine:m.endPosition.row}}let a=na(e,t,n,i);if(a)return{startLine:a.startLine,endLine:a.endLine};if(o.length===0)return{startLine:n,endLine:i};let l=(te(e,t)?.callables??[]).filter(d=>d.startLine>=n&&d.endLine<=i&&o.every(m=>d.startLine<=m&&d.endLine>=m)).sort((d,m)=>d.endLine-d.startLine-(m.endLine-m.startLine)||d.startLine-m.startLine)[0];if(!s)return l?{startLine:l.startLine,endLine:l.endLine}:{startLine:n,endLine:i};let c=[];Ci(s.rootNode,d=>{Vn.has(d.type)&&d.startPosition.row>=n&&d.endPosition.row<=i&&o.every(m=>d.startPosition.row<=m&&d.endPosition.row>=m)&&c.push(d)});let u=c.sort((d,m)=>d.endPosition.row-d.startPosition.row-(m.endPosition.row-m.startPosition.row)||d.startPosition.row-m.startPosition.row)[0];return u?{startLine:u.startPosition.row,endLine:u.endPosition.row}:l?{startLine:l.startLine,endLine:l.endLine}:{startLine:n,endLine:i}}function yc(e,t,n,i,r={}){if(i-n+1<(r.minimumBodyLines??YI))return null;let s=Tp(e,t,n,i,[],!1);if(!s)return null;let a=s.candidates.map(b=>({...b,signals:b.signals.filter(v=>v!=="anchor"&&v!=="signature")})).filter(b=>b.signals.length>0);if(a.length===0)return null;let l=vE(a),c=a.filter(b=>b.text.length<=gc);if(c.length===0)return null;let u=Rp.filter(b=>(l[b]??0)>0),d=u.filter(b=>b!=="await"),m=s.shapes.reduce((b,v)=>b+v.fields.length,0);if(d.length===0&&!((l.await??0)>0&&m>0)&&m<3)return null;let f=CE(c,l),p=new Map;for(let b of u){let v=f.find(y=>y.signals.includes(b));v&&p.set(v.line,v)}if(p.size===0){let b=f.find(v=>v.signals.includes("branch"));b&&p.set(b.line,b)}let g=Math.min(10,Math.max(1,r.maxLines??p.size)),h=new Map;for(let b of p.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:i,lines:[...h.values()].sort((b,v)=>b.line-v.line),shapes:s.shapes,signalCounts:l,candidateLines:a.length,omittedLines:a.length-h.size}}function En(e,t,n,i){let r=Tp(e,t,n,i,[],!1);return r?new Map(r.candidates.map(o=>[o.line,o.signals.filter(s=>s!=="lifecycle")])):new Map}var Vn=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"]),Rt=new Set(["block","body","compound_statement","declaration_list","statement_block"]),Jr=new Set(["if_expression","if_statement","unless","unless_statement"]),ZI=new Set(["conditional_expression","ternary_expression"]),ta=new Set(["do_statement","enhanced_for_statement","for_expression","for_in_statement","for_of_statement","for_statement","loop_expression","while_statement"]),Zr=new Set(["match_expression","match_statement","switch_expression","switch_statement"]),wp=new Set(["case_statement","match_arm","switch_case","switch_default"]),eo=new Set(["try_expression","try_statement"]),Ys=new Set(["catch_clause","except_clause","rescue"]),Xr=new Set(["ensure","finally_clause"]),Yr=new Set(["else","else_clause"]),Lp=new Set(["raise_statement","return_statement","throw_statement"]),eE=new Set(["block_comment","comment","line_comment"]);function tE(e,t,n){let i=n.childForFieldName("condition")??xc(n),r=n.childForFieldName("consequence")??n.childForFieldName("body")??n.namedChildren.find(l=>Rt.has(l.type)),o=n.childForFieldName("alternative")??n.namedChildren.find(l=>Yr.has(l.type));if(!i||!r){t.push(Cc(n,"conditional-fields-unresolved"));return}let s=ln(i,"predicate",i.text),a=ln(r,vp(r),"consequence");if(an(e,s,a,"predicate-consequence",{branchRole:"consequence"}),Xs(e,s,r,"consequence"),o){let l=ln(o,vp(o),"alternative");an(e,s,l,"predicate-alternative",{branchRole:"alternative"}),Xs(e,s,o,"alternative");return}an(e,s,bc(s,"otherwise continue"),"predicate-fallthrough",{branchRole:"fallthrough"})}function nE(e,t,n){let i=n.childForFieldName("body")??n.namedChildren.find(s=>Rt.has(s.type));if(!i){t.push(Cc(n,"loop-body-unresolved"));return}let r=n.childForFieldName("condition"),o=ln(r??n,"predicate",r?.text??Kt(n,i));an(e,o,ln(i,"outcome","iteration"),"loop-iteration",{branchRole:"iteration"}),Xs(e,o,i,"iteration"),an(e,o,bc(o,"loop exits"),"loop-exit",{branchRole:"exit"})}function iE(e,t,n){let i=n.childForFieldName("body")??n.namedChildren.find(l=>Rt.has(l.type)),r=n.childForFieldName("value")??n.childForFieldName("condition")??n.childForFieldName("subject")??xc(n),o=sE(i??n);if(!r||o.length===0){t.push(Cc(n,"switch-cases-unresolved"));return}let s=ln(r,"predicate",r.text),a=!1;for(let l of o){let c=lE(l);a||=c;let u=Kt(l,l.namedChildren.find(d=>Qs(d)));an(e,s,ln(l,"outcome",u||(c?"default":"case")),c?"predicate-default":"predicate-case",{branchRole:c?"default":"case"}),Xs(e,s,l,c?"default":"case")}a||an(e,s,bc(s,"no case matched"),"predicate-fallthrough",{branchRole:"fallthrough"})}function rE(e,t){let n=ln(t,"scope","try");for(let i of aE(t)){let r=Xr.has(i.type),o=ln(i,"handler",r?"finally":Kt(i,Vs(i)));an(e,n,o,r?"finally-cleanup":"exception-handler",{branchRole:r?"finally":"catch"}),oE(e,o,i,r?"finally":"catch")}}function oE(e,t,n,i){for(let r of Sc(n)){let o=r.label.startsWith("throw")||r.label.startsWith("raise")?"throw":"return";an(e,t,r,o==="throw"?"handler-throw":"handler-return",{branchRole:i,terminalKind:o})}}function Xs(e,t,n,i){for(let r of Sc(n)){let o=r.label.startsWith("throw")||r.label.startsWith("raise")?"throw":"return";an(e,t,r,o==="throw"?"predicate-throw":"predicate-return",{branchRole:i,terminalKind:o})}}function an(e,t,n,i,r){e.push({controller:t,outcome:n,subtype:i,attributes:r})}function ln(e,t,n){return{kind:t,label:Qr(n).slice(0,hc),startLine:e.startPosition.row,endLine:e.endPosition.row,implicit:!1}}function bc(e,t){return{...e,kind:"outcome",label:t,implicit:!0}}function vp(e){return Lp.has(e.type)?"terminal":"outcome"}function Sc(e){let t=[];return vc(e,e,n=>{Lp.has(n.type)&&t.push(ln(n,"terminal",n.text))}),Dp(t)}function vc(e,t,n){n(t);for(let i of t.namedChildren)i!==e&&Vn.has(i.type)||vc(e,i,n)}function sE(e){let t=[],n=i=>{for(let r of i.namedChildren)Zr.has(r.type)||(wp.has(r.type)?t.push(r):n(r))};return n(e),t}function aE(e){let t=[],n=i=>{for(let r of i.namedChildren)eo.has(r.type)||(Ys.has(r.type)||Xr.has(r.type)?t.push(r):Vn.has(r.type)||n(r))};return n(e),t}function lE(e){let t=Kt(e,e.namedChildren.find(n=>Qs(n))).trim();return e.type==="switch_default"||/^(?:default\b|_\s*=>)/u.test(t)}function Cc(e,t){return{startLine:e.startPosition.row,endLine:e.endPosition.row,reason:t}}function cE(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 Dp(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 uE(e){return Vn.has(e.type)||ta.has(e.type)||Zr.has(e.type)||eo.has(e.type)||Ys.has(e.type)||Xr.has(e.type)}function Mp(e,t,n,i,r){let s=or(e,n,i)??e,a=Vs(s),l=[],c=0,u=0,d=(S,x,C,L,w=!1,R=!0)=>{let M=w?C.trim():Qr(C);if(!M)return;let _=Math.max(n,S.startPosition.row),D=Math.min(i,S.endPosition.row);l.push({line:_,endLine:Math.max(_,D),depth:x,signals:Zs.filter(P=>L.includes(P)||P==="anchor"&&r.some(k=>k>=_&&k<=D)),text:M,copied:w}),R&&(c+=1,w&&(u+=1))},m=(S,x)=>{for(let C of S.namedChildren)E(C,x)},f=(S,x)=>{if(Jr.has(S.type)){p(S,x,"else if");return}if(Yr.has(S.type)){let C=S.namedChildren.find(w=>Jr.has(w.type));if(C){p(C,x,"else if");return}d(S,x,"else",["branch"],!1,!1);let L=Vs(S)??S.namedChildren.find(w=>Rt.has(w.type));if(L)E(L,x+1);else for(let w of S.namedChildren)E(w,x+1);return}d(S,x,"else",["branch"],!1,!1),E(S,x+1)},p=(S,x,C=S.type.startsWith("unless")?"unless":"if")=>{let L=S.childForFieldName("condition")??xc(S),w=S.childForFieldName("consequence")??S.childForFieldName("body")??S.namedChildren.find(_=>Rt.has(_.type)),R=S.childForFieldName("alternative")??S.namedChildren.find(_=>Yr.has(_.type)),M=L?L.text:Kt(S,w);d(S,x,`${C} ${pE(M)}`,Vr(L,["branch"])),w&&E(w,x+1),R&&f(R,x)},g=(S,x)=>{let C=S.childForFieldName("body")??S.namedChildren.find(L=>Rt.has(L.type));d(S,x,Kt(S,C),Vr(S,["loop"])),C&&E(C,x+1)},h=(S,x)=>{let C=S.childForFieldName("body")??S.namedChildren.find(L=>Rt.has(L.type));d(S,x,Kt(S,C),Vr(S,["branch"])),C&&E(C,x+1)},b=(S,x)=>{let C=S.namedChildren.find(L=>Qs(L));d(S,x,Kt(S,C),["branch"],!1,!1);for(let L of S.namedChildren)(L===C||Qs(L))&&E(L,x+1)},v=(S,x)=>{d(S,x,"try",[],!1);for(let C of S.namedChildren)Rt.has(C.type)?E(C,x+1):(Ys.has(C.type)||Xr.has(C.type))&&E(C,x)},y=(S,x,C)=>{let L=S.childForFieldName("body")??S.namedChildren.find(R=>Rt.has(R.type)),w=C==="finally"?"finally":Kt(S,L);d(S,x,w,[C],!1,!1),L&&E(L,x+1)},I=(S,x)=>{let C=Vs(S);d(S,x,Kt(S,C),Vr(S,["binding"])),C&&E(C,x+1)},E=(S,x)=>{if(S.startPosition.row>i||S.endPosition.row<n||eE.has(S.type)||S.type==="empty_statement")return;if(Rt.has(S.type)){m(S,x);return}if(Jr.has(S.type)){p(S,x);return}if(ta.has(S.type)){g(S,x);return}if(Zr.has(S.type)){h(S,x);return}if(wp.has(S.type)){b(S,x);return}if(eo.has(S.type)){v(S,x);return}if(Ys.has(S.type)){y(S,x,"catch");return}if(Xr.has(S.type)){y(S,x,"finally");return}if(Yr.has(S.type)){f(S,x);return}if(Vn.has(S.type)){I(S,x);return}let L=!Pp(S)||gE(S);d(S,x,S.text,Vr(S),L)};return E(a&&a!==s?a:s,0),c===0?null:{constructKind:fE(s),signature:mE(s,a,t,n),lines:l,sourceStatements:c,copiedStatements:u}}function or(e,t,n){let i=e.namedChildren.filter(r=>r.startPosition.row<=t&&r.endPosition.row>=n);for(let r of i.sort(dE)){let o=or(r,t,n);if(o)return o}return Vn.has(e.type)&&e.startPosition.row<=t&&e.endPosition.row>=n?e:null}function dE(e,t){return e.endPosition.row-e.startPosition.row-(t.endPosition.row-t.startPosition.row)||e.startPosition.row-t.startPosition.row}function Vs(e){return e.childForFieldName("body")??e.childForFieldName("consequence")??e.namedChildren.find(t=>Rt.has(t.type))??null}function mE(e,t,n,i){let r=Kt(e,t);return r||(n[i]??e.text).trim()}function fE(e){return e.type.includes("constructor")?"constructor":e.type.includes("method")||e.type==="method"?pc(e,new Set(["class_body","class_declaration","class_definition"]))?"class method":"object method":e.type==="arrow_function"||e.type==="function_expression"||e.type==="lambda"?pc(e,new Set(["object","pair"]))?"object member":"function value":e.type.includes("function")?pc(e,Vn)?"nested function":"module function":"source construct"}function pc(e,t){let n=e.parent;for(;n;){if(t.has(n.type))return!0;n=n.parent}return!1}function xc(e){return e.namedChildren.find(t=>!Rt.has(t.type)&&!Yr.has(t.type))??null}function Kt(e,t){if(!t)return Qr(e.text);let n=Math.max(0,t.startIndex-e.startIndex);return Qr(e.text.slice(0,n)).replace(/[:{]\s*$/u,"").trim()}function pE(e){let t=Qr(e);return t.startsWith("(")&&t.endsWith(")")?t.slice(1,-1).trim():t}function Qr(e){return e.trim().replace(/\r?\n[\t ]*/gu," ")}function Vr(e,t=[]){let n=new Set(t);return e&&Ci(e,i=>{let r=Cp[i.type];r&&n.add(r),i.type==="call_expression"&&(n.add("call"),Fp(i)&&n.add("shape")),Rc.has(i.type)&&n.add("binding")}),Zs.filter(i=>n.has(i))}function gE(e){let t=!1;return Ci(e,n=>{t||!n.text.includes(`
40
- `)||/(?:string|template|heredoc|raw_string)/u.test(n.type)&&(t=!0)}),t}function Qs(e){return Rt.has(e.type)||Jr.has(e.type)||ta.has(e.type)||Zr.has(e.type)||eo.has(e.type)||Vn.has(e.type)||Pp(e)}function Pp(e){return/(?:statement|declaration|expression|assignment|return|throw|raise|break|continue|yield|with_item)$/u.test(e.type)||Rc.has(e.type)}function hE(e,t,n){let i=0;for(let r=t;r<=n;r+=1)i+=(e[r]?.length??0)+10;return i}function yE(e){return e.constructKind.length+e.signature.length+80+e.lines.reduce((t,n)=>t+n.text.length+n.depth*2+10,0)}function Tp(e,t,n,i,r,o){let s=ae(e,t);if(!s)return null;let a=re(e,t),l=na(e,t,n,i),c=o?l?.startLine??n:n,u=o?l?.endLine??i:i,m=(l?.startLine===c&&l.endLine===u?or(s.rootNode,c,u):null)??to(s.rootNode,c,u);if(!m)return null;let f=new Map,p=new Map,g=new Map,h=(y,I)=>{if(y<c||y>u)return;let E=f.get(y)??new Set;E.add(I),f.set(y,E)};l&&h(l.startLine,"signature");for(let y of r)h(y,"anchor");Ci(m,y=>{let I=Cp[y.type];if(I&&h(y.startPosition.row,I),I==="shape"&&bE(p,y,m,c,u),y.type==="call_expression"){let S=(y.childForFieldName("function")??y.namedChild(0))?.text.split(".").at(-1);if(Fp(y)){h(y.startPosition.row,"shape");let x=Js(y.text);x.length<=gc&&g.set(y.startPosition.row,x)}if(S&&QI.has(S)){h(y.startPosition.row,"lifecycle");let x=Js(y.text);x.length<=gc&&g.set(y.startPosition.row,x)}}Rc.has(y.type)&&h(y.startPosition.row,"binding")});let b=te(e,t);for(let y of b?.callSites??[])y.line<c||y.line>u||(h(y.line,"call"),y.calleeLeaf==="catch"&&h(y.line,"catch"));let v=[...f.entries()].sort(([y],[I])=>y-I).map(([y,I])=>({line:y,signals:xp.filter(E=>I.has(E)),text:g.get(y)??Js(a[y]??"")})).filter(y=>y.text.length>0||y.signals.includes("anchor"));return{...l?{callable:l}:{},rangeStart:c,rangeEnd:u,sourceLines:a,candidates:v,shapes:[...p.values()].sort((y,I)=>y.startLine-I.startLine)}}function bE(e,t,n,i,r){if(t.startPosition.row<i||t.endPosition.row>r)return;let o=t.childForFieldName("key")??t.childForFieldName("name")??t.namedChild(0),s=Js(o?.text??"");if(!s||s.includes(`
41
- `)||s.length>60)return;let a=SE(t,n);if(a.startPosition.row<i||a.endPosition.row>r)return;let l=`${a.startPosition.row}:${a.endPosition.row}`,c=e.get(l)??{startLine:a.startPosition.row,endLine:a.endPosition.row,fields:[]};c.fields.some(u=>u.name===s&&u.line===t.startPosition.row)||c.fields.push({name:s,line:t.startPosition.row}),e.set(l,c)}function SE(e,t){let n=e.parent;for(;n&&n!==t.parent;){if(Ip.has(n.type))return n;if(n===t)break;n=n.parent}return e.parent??e}function na(e,t,n,i){return te(e,t)?.callables.filter(r=>r.startLine<=n&&r.endLine>=i).sort((r,o)=>r.endLine-r.startLine-(o.endLine-o.startLine)||r.startLine-o.startLine)[0]}function to(e,t,n){if(e.startPosition.row>t||e.endPosition.row<n)return null;for(let i of e.namedChildren){let r=to(i,t,n);if(r)return r}return e}function Ci(e,t){t(e);for(let n of e.namedChildren)Ci(n,t)}function Js(e){return e.trim().replace(/\s+/gu," ")}function Fp(e){if(e.type!=="call_expression")return!1;let t=e.childForFieldName("arguments")??e.namedChildren.find(i=>i.type==="arguments"||i.type==="argument_list");if(!t)return!1;let n=!1;return Ci(t,i=>{Ip.has(i.type)&&(n=!0)}),n}function vE(e){let t={};for(let n of xp){let i=e.filter(r=>r.signals.includes(n)).length;i>0&&(t[n]=i)}return t}function CE(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 i=new Set(Rp),r=o=>{let s=n.get(o.signals.join(","))??1,a=Math.min(...o.signals.map(u=>t[u]??1)),l=o.signals.some(u=>i.has(u))?3:1,c=Math.max(0,o.signals.length-1)*1e3;return l*(1e3/s+1e3/a)+c};return[...e].sort((o,s)=>r(s)-r(o)||s.line-o.line)}var Rc=new Set(["lexical_declaration","variable_declarator","const_item","static_item","let_declaration","assignment"]);function xE(e,t,n){let i=[],r=/\b(?:describe|it|test)(?:\.(?:only|skip|todo))?\s*\(\s*(['"`])([^'"`]+)\1/u;for(let o=t;o<=n;o+=1){let s=r.exec(e[o]??"")?.[2];if(!(!s||i.includes(s))&&(i.push(s),i.length>=JI))break}return i}var RE=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 sr(e,t,n){let i=ae(e,t)?.rootNode??null,r=IE(i,n);if(!r)return null;let o=re(e,t);if(o.length===0)return null;let s=Math.max(0,r.startPosition.row),a=r.endPosition.column===0?r.endPosition.row-1:r.endPosition.row;return{type:r.type,startLine:s,endLine:Math.min(o.length-1,Math.max(s,a))}}function no(e,t,n,i,r){let o=yt(e,t,i,r,[n]),s=o.startLine===o.endLine&&/(?:=>|\(|\{|\[|,)\s*$/u.test(re(e,t)[o.startLine]??"");if(!s&&(o.startLine>i||o.endLine<r))return o;let a=sr(e,t,n);return s&&a?{startLine:a.startLine,endLine:a.endLine}:a&&a.startLine>=i&&a.endLine<=r?{startLine:a.startLine,endLine:a.endLine}:{startLine:i,endLine:r}}function IE(e,t){if(!e||!Ap(e,t))return null;let n=Np(e,t);for(;n;){if(RE.has(n.type))return n;n=n.parent}return null}function Np(e,t){let n=e.namedChildren.filter(i=>Ap(i,t)).sort((i,r)=>kp(i)-kp(r));return n.length>0?Np(n[0],t):e}function Ap(e,t){return e.startPosition.row<=t&&e.endPosition.row>=t}function kp(e){return e.endIndex-e.startIndex}var EE=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 ia(e,t,n,i){if(!Number.isSafeInteger(n)||n<0)return null;if(!Number.isSafeInteger(i)||i<0)throw new RangeError(`contextLines must be a non-negative safe integer; received ${i}`);let r=re(e,t);if(r.length===0||n>=r.length)return null;let o=Math.max(0,n-i),s=Math.min(r.length-1,n+i);return{relativePath:t,startLine:o,endLine:s,focusLine:n,source:r.slice(o,s+1).join(`
42
- `)}}function _p(e,t,n,i,r){let o=ia(e,t,n,i);if(!o)return null;let s=ae(e,t)?.rootNode??null;if(!s)return{...o,kind:"bounded-context"};let a=wE(s,n,r);if(a.length!==1)return{...o,kind:a.length===0?"non-call-reference":"bounded-context"};let l=a[0],c=re(e,t),u=Math.max(0,l.startPosition.row),d=l.endPosition.column===0?l.endPosition.row-1:l.endPosition.row,m=Math.min(c.length-1,Math.max(u,d));return{relativePath:t,startLine:u,endLine:m,focusLine:n,source:c.slice(u,m+1).join(`
43
- `),kind:"complete-call-expression"}}function Bp(e,t,n,i,r){if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`maxLines must be a positive safe integer; received ${r}`);let o=re(e,t);if(o.length===0||n<0||n>=o.length)return null;let s=Math.min(o.length-1,i,n+r-1);return{relativePath:t,startLine:n,endLine:s,focusLine:n,source:o.slice(n,s+1).join(`
44
- `)}}function Jn(e,t,n,i,r=6){if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`maxLines must be a positive safe integer; received ${i}`);let o=re(e,t);if(o.length===0||n<0||n>=o.length)return null;let s=sr(e,t,n);if(!s){let g=ia(e,t,n,r);return g?{...g,unitType:null,unitStartLine:g.startLine,unitEndLine:g.endLine,omittedLines:0}:null}let a=s.startLine,l=s.endLine,c=l-a+1,u=Math.min(c,i),d=n-a-Math.floor(u/2),m=Math.max(0,Math.min(c-u,d)),f=a+m,p=f+u-1;return{relativePath:t,startLine:f,endLine:p,focusLine:n,source:o.slice(f,p+1).join(`
45
- `),unitType:s.type,unitStartLine:a,unitEndLine:l,omittedLines:c-u}}function wE(e,t,n){let i=[];return Op(e,t,n,i),i.filter(r=>!i.some(o=>o!==r&&o.startIndex>=r.startIndex&&o.endIndex<=r.endIndex))}function Op(e,t,n,i){if(DE(e,t)){EE.has(e.type)&&LE(e)===n&&i.push(e);for(let r of e.namedChildren)Op(r,t,n,i)}}function LE(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 DE(e,t){return e.startPosition.row<=t&&e.endPosition.row>=t}function wc(e,t,n={}){let{context:i=0}=n,r=Jp(t);if(r)return Yp(e,r.filePath,r.startLine,r.endLine,i);let o=Wp(e,t);if(o)return qp(e,o);let s=pe(e,t);return s?io(e,s,i):null}function PE(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 i=n.context??0,r=n.members??"exported",o=t.map(l=>TE(e,l,i,r)),s=o.flatMap(l=>l.results),a=s.map(l=>({relativePath:l.relativePath,startLine:l.startLine,endLine:l.endLine}));return{requested:t.length,matched:o.filter(l=>l.status==="matched").length,ambiguous:o.filter(l=>l.status==="ambiguous").length,missing:o.filter(l=>l.status==="missing").length,entries:o,bindingClosure:Ws(s.map(l=>l.bindingClosure),a)}}function TE(e,t,n,i){let r=Jp(t);if(r){let u=Yp(e,r.filePath,r.startLine,r.endLine,n);return u?FE(e,t,u,n):Ic(e,t,"definition-source-unreadable")}let o=Wp(e,t);if(o)return NE(e,t,o,n,i);let s=at(e,t);if(!s.match)return Ic(e,t,"definition-not-found");let a=zE(e,s),l=a.map(Vp);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=io(e,d,n);return m?[m]:[]}):[],definitions:[],candidates:l,omittedCandidates:Math.max(0,s.total-l.length),suggestions:[]}}let c=io(e,s.match,n);return c?UE(t,c):Ic(e,t,"definition-source-unreadable")}function FE(e,t,n,i){let r=W(e,n.relativePath).filter(c=>!jp(c,n.relativePath)),o=kE(e,n,r),s=zp(o.map(c=>io(e,c,i)).filter(c=>c!==null)).filter(c=>!Gp(n,c)),a=new Set(s.map(c=>c.symbol)),l=o.filter(c=>!a.has(c.symbol)&&!(n.startLine<=c.startLine&&n.endLine>=c.endLine)).map(Vp);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-l.length,returnedBodies:s.length,omittedDefinitions:l.length,omittedLedger:l}}}function kE(e,t,n){if(!ro(t.freshness))return[];if(n.length===0)return[];let i=mc(e,n,{additive:!1,semantic:!1}),r=new Map;for(let s of n){let a=r.get(s.symbol)??[];a.push(s),r.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 i.get(s.symbolId)??[])if(a.file===t.relativePath&&!(a.source==="ast-callsite"&&(a.chunkId<t.startLine||a.chunkId>t.endLine)))for(let l of r.get(a.symbol)??[])o.set(l.symbolId,l)}return Up(e,[...o.values()],n)}function NE(e,t,n,i,r){let o=n.relativePath,s=_E(e,o),a=ro(n.freshness)?W(e,o).filter(g=>!jp(g,o)):[],l=a.filter(g=>xt(e,g)),c=l.length>0?l:AE(s,a),u=r==="all"?[]:Up(e,c,a),d=r==="all"||a.length===0?[qp(e,n)]:zp(u.map(g=>io(e,g,i)).filter(g=>g!==null)),m=OE(s,d),f=$E(o,s,d),p=jE(s);return{selector:t,status:"matched",kind:"file-source",totalCandidates:1,results:d,definitions:[],candidates:[],omittedCandidates:0,suggestions:[],fileCoverage:{members:r,basis:r==="all"||a.length===0?"complete-file-source":l.length>0?"explicit-exports-and-same-file-reference-closure":"top-level-and-same-file-reference-closure",totalDefinitions:p,returnedDefinitions:m,returnedBodies:d.length,omittedDefinitions:Math.max(0,p-m),omittedLedger:f}}}function AE(e,t){let n=new Set(e.map(i=>i.symbol));return t.filter(i=>n.has(i.symbol))}function _E(e,t){return lc(e,t).flatMap(n=>BE(n,t)?n.children:[n])}function jp(e,t){return Hp(t).has(e.leaf)}function BE(e,t){return Hp(t).has(Y(e.symbol))}function Hp(e){let t=ME(e);return new Set([t,t.slice(0,Math.max(0,t.length-$p(t).length))])}function Up(e,t,n){if(t.length===0)return[];let i=mc(e,n,{additive:!0,semantic:!1}),r=new Map;for(let a of n){let l=r.get(a.symbol)??[];l.push(a),r.set(a.symbol,l)}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 l of i.get(a.symbolId)??[])for(let c of r.get(l.symbol)??[])o.has(c.symbolId)||s.push(c)}}return[...o.values()].sort(HE)}function zp(e){let t=[...e].sort((i,r)=>i.relativePath.localeCompare(r.relativePath)||i.startLine-r.startLine||r.endLine-i.endLine),n=[];for(let i of t)n.some(r=>Gp(r,i))||n.push(i);return n}function qp(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??Lc(t.relativePath),source:t.text,freshness:t.freshness,...ro(t.freshness)?{bindingClosure:ir(e,t.relativePath,0,Math.max(0,n.length-1))}:{}}}function OE(e,t){return ra(e).filter(n=>t.some(i=>Ec(n,i))).length}function $E(e,t,n){let i=[];return Kp(i,e,t,n,0),i}function Kp(e,t,n,i,r){for(let o of n){if(i.some(a=>Ec(o,a)))continue;let s=ra(o.children).filter(a=>!i.some(l=>Ec(a,l))).length;e.push({symbol:o.symbol,shortName:o.shortName,relativePath:t,startLine:o.startLine,endLine:o.endLine,signature:o.signature,depth:r,nestedDefinitions:s}),Kp(e,t,o.children,i,r+1)}}function ra(e){return e.flatMap(t=>[t,...ra(t.children)])}function jE(e){return ra(e).length}function Ec(e,t){return t.startLine<=e.startLine&&t.endLine>=e.endLine}function Gp(e,t){return e.relativePath===t.relativePath&&e.startLine<=t.startLine&&e.endLine>=t.endLine}function HE(e,t){return e.startLine-t.startLine||t.endLine-e.endLine||e.symbol.localeCompare(t.symbol)}function UE(e,t){return{selector:e,status:"matched",kind:"source",totalCandidates:1,results:[t],definitions:[],candidates:[],omittedCandidates:0,suggestions:[]}}function Ic(e,t,n){return{selector:t,status:"missing",kind:"source",totalCandidates:0,results:[],definitions:[],candidates:[],omittedCandidates:0,suggestions:_s(e,t,5),reason:n}}function Wp(e,t){try{return zs(e,t)}catch(n){if(n instanceof nf)return null;throw n}}function zE(e,t){if(!t.match)return[];let n=[t.match];for(let r of t.candidates){let o=W(e,r.relativePath).find(s=>s.symbol===r.symbol&&s.startLine===r.startLine);o&&n.push(o)}let i=new Set;return n.filter(r=>{let o=`${r.relativePath}:${r.startLine}:${r.endLine}:${r.symbol}`;return i.has(o)?!1:(i.add(o),!0)})}function Vp(e){return{symbol:e.symbol,shortName:A(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine}}function Jp(e){let t=e.match(/^(.+):(\d+)-(\d+)$/);if(!t)return null;let n=Number(t[2]),i=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(i)||i<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:i}}function io(e,t,n){let i=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),r=zs(e,t.relativePath);if(!r)return null;let s=r.text.split(`
38
+ WHERE gs.id IN (${f.map(()=>"?").join(",")})`,...f,...f)),a=cc([...t.map(f=>f.documentId),...s.flatMap(f=>f.document_id===null?[]:[f.document_id])]),l=new Map(a.flatMap(f=>e.all(`SELECT id, relative_path FROM documents
39
+ WHERE id IN (${f.map(()=>"?").join(",")})`,...f).map(p=>[p.id,p.relative_path]))),c=new Map;for(let f of s)c.has(f.symbol_id)||c.set(f.symbol_id,{symbol:f.symbol,file:f.document_id!==null?l.get(f.document_id)??"":""});let u=new Map,d=l,m=OI(t);for(let[f,p]of m){let h=[...r.get(f)??[]].sort((I,E)=>I.start_line-E.start_line||I.end_line-E.end_line),b=[...p].sort((I,E)=>I.startLine-E.startLine||I.endLine-E.endLine),v=new Set,y=0;for(let I of b){for(;y<h.length&&h[y].start_line<=I.endLine;)v.add(h[y]),y+=1;for(let L of v)L.end_line<I.startLine&&v.delete(L);let E=new Set,S=[],x=null,C=()=>{if(x)return x;let L=d.get(I.documentId)??"",w=new Set;if(L){let R=Ff(e,L),M=Math.max(0,I.startLine),_=Math.min(R.length-1,I.endLine);for(let D=M;D<=_;D+=1)for(let P of R[D])w.add(P)}return x=w,w};for(let L of v){if(L.symbol_id===I.symbolId)continue;let w=c.get(L.symbol_id);if(!w)continue;if(!(L.start_line>=I.startLine&&L.end_line<=I.endLine)){if(!(L.start_line<=I.endLine&&L.end_line>=I.startLine))continue;let D=Y(w.symbol);if(!D||!C().has(D))continue}let M=`${w.symbol}|${L.chunk_id}`;E.has(M)||(E.add(M),S.push({...w,chunkId:L.chunk_id,source:"scip-chunk"}))}u.set(I.symbolId,S)}}return u}var fp=500;function cc(e){let t=[...new Set(e)],n=[];for(let i=0;i<t.length;i+=fp)n.push(t.slice(i,i+fp));return n}function OI(e){let t=new Map;for(let n of e){let i=t.get(n.documentId);i?i.push(n):t.set(n.documentId,[n])}return t}function $I(e){let t=new Map;for(let[n,i]of e){let r=[];for(let o of i)r.push({symbol:o.symbol,file:o.file,chunkId:-1,source:"semantic-callee",...o.callsiteLine===void 0?{}:{callsiteLine:o.callsiteLine}});t.set(n,r)}return t}var jI=12,HI=280;function tr(e,t,n,i){let r=UI(e,t,n,i);if(r.size===0)return GI();let o=[],s=new Set,a=(c,u,d,m)=>{if(u===t&&d<=i&&m>=n)return;let f=`${u}:${d}:${m}:${c}`;s.has(f)||(s.add(f),o.push({name:c,relativePath:u,startLine:d,endLine:m}))};for(let c of W(e,t))r.has(c.leaf)&&a(c.leaf,c.relativePath,c.startLine,c.endLine);for(let c of Ce(e,t)){let u=c.localName;if(!u||!r.has(u)||!c.sourcePath||c.kind==="namespace")continue;let d=c.importedName==="default"?u:c.importedName;for(let m of Wn(e,c.sourcePath,d,{maxReexportDepth:3}))a(u,m.relativePath,m.startLine,m.endLine)}o.sort(hp);let l=o.map(c=>{let u=zI(e,c);return u?{...c,source:u}:null}).filter(c=>c!==null).slice(0,jI);return mc(l)}function Gs(e,t=[]){return mc(qI(e.flatMap(n=>n?.inline??[]),t))}function gp(e){return e?e.inline.reduce((t,n)=>t+n.name.length+n.source.length+32,0):0}function UI(e,t,n,i){let r=te(e,t),o=new Set;if(!r)return o;for(let s=n;s<=i;s+=1)for(let a of r.identifiersByLine[s]??[])o.add(a);return o}function zI(e,t){if(t.startLine!==t.endLine)return null;let n=(re(e,t.relativePath)[t.startLine]??"").trim();if(!n||n.length>HI)return null;let i=n.indexOf("=");if(i<0||n[i+1]===">")return null;let r=n.slice(i+1).replace(/(?:\/\/|#).*$/u,"").trim();if(!r||r.includes("${")||/\b(?:function|class|struct|interface|trait|enum|lambda)\b/u.test(r))return null;let s=r.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(c=>!a.has(c))?null:n}function qI(e,t){let n=new Map;for(let i of e){if(KI(i,t))continue;let r=`${i.relativePath}:${i.startLine}:${i.endLine}:${i.name}`;n.has(r)||n.set(r,{...i})}return[...n.values()].sort(hp)}function KI(e,t){return t.some(n=>n.relativePath===e.relativePath&&n.startLine<=e.startLine&&n.endLine>=e.endLine)}function hp(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||e.name.localeCompare(t.name)}function mc(e){return{coverage:"indexed-project-literal-values",inline:e}}function GI(){return mc([])}var WI=12,VI=20,pc=200,gc=800,JI=.9,bp={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"},Qs=["anchor","signature","binding","branch","loop","call","await","return","throw","mutation","shape","spread","catch","finally"],Sp=[...Qs,"lifecycle"],vp=["loop","await","throw","mutation","spread","catch","finally","lifecycle"],YI=new Set(["onBeforeMount","onBeforeUnmount","onMounted","onUnmounted","useEffect","useInsertionEffect","useLayoutEffect"]);var Cp=new Set(["object","object_pattern","dictionary","field_declaration_list","struct_expression","struct_pattern"]);function nr(e,t,n,i,r=[],o={}){let s=ae(e,t);if(!s)return null;let a=re(e,t),l=yt(e,t,n,i,r),c=ta(e,t,l.startLine,l.endLine),u=c?.startLine??n,d=c?.endLine??i,m=(c?ir(s.rootNode,l.startLine,l.endLine):null)??Zr(s.rootNode,u,d);if(!m)return null;let f=wp(m,a,u,d,r);if(!f||f.lines.length===0||f.lines.some(b=>b.text.length>gc))return null;let p=pE(a,u,d),g=gE(f);if((o.requireSavings??!0)&&g>=p*JI)return null;let h=Qs.filter(b=>f.lines.some(v=>v.signals.includes(b)));return{...c?{callable:{name:c.name,startLine:c.startLine,endLine:c.endLine}}:{},representation:"outline",constructKind:f.constructKind,signature:f.signature,lines:f.lines,signals:h,testCases:J(t)==="test"?vE(a,u,d):[],coverage:{sourceStatements:f.sourceStatements,representedStatements:f.sourceStatements,copiedStatements:f.copiedStatements,omittedStatements:0},rawCharacters:p,outlineCharacters:g,candidateLines:f.sourceStatements,omittedLines:0}}function Zs(e,t,n,i,r){if(r.length===0)return[];let o=ae(e,t);if(!o)return[];let s=re(e,t),a=yt(e,t,n,i,r),l=ta(e,t,a.startLine,a.endLine),c=l?.startLine??n,u=l?.endLine??i,d=(l?ir(o.rootNode,a.startLine,a.endLine):null)??Zr(o.rootNode,c,u);if(!d)return[];let m=wp(d,s,c,u,r);return m?m.lines.filter(f=>f.text.length<=gc&&f.signals.some(p=>["branch","loop","catch","finally"].includes(p))&&r.some(p=>p>=f.line&&p<=f.endLine)):[]}function xp(e,t,n,i){let r=ae(e,t);if(!r)return null;let o=ir(r.rootNode,n,i)??Zr(r.rootNode,n,i);if(!o)return null;let s=[],a=bc(o),l=[];return Sc(o,o,c=>{if(Wr.has(c.type)||XI.has(c.type)){ZI(s,l,c);return}if(ea.has(c.type)){eE(s,l,c);return}if(Xr.has(c.type)){tE(s,l,c);return}Qr.has(c.type)&&nE(s,c)}),{facts:aE(s),terminals:Ep(a),unsupported:l}}function yt(e,t,n,i,r=[]){let o=r.filter(d=>d>=n&&d<=i),s=ae(e,t);if(o.length>0&&s){let d=[];Ci(s.rootNode,f=>{lE(f)&&f.startPosition.row>=n&&f.endPosition.row<=i&&o.every(p=>f.startPosition.row<=p&&f.endPosition.row>=p)&&d.push(f)});let m=d.sort((f,p)=>f.endPosition.row-f.startPosition.row-(p.endPosition.row-p.startPosition.row)||f.startPosition.row-p.startPosition.row)[0];if(m)return{startLine:m.startPosition.row,endLine:m.endPosition.row}}let a=ta(e,t,n,i);if(a)return{startLine:a.startLine,endLine:a.endLine};if(o.length===0)return{startLine:n,endLine:i};let l=(te(e,t)?.callables??[]).filter(d=>d.startLine>=n&&d.endLine<=i&&o.every(m=>d.startLine<=m&&d.endLine>=m)).sort((d,m)=>d.endLine-d.startLine-(m.endLine-m.startLine)||d.startLine-m.startLine)[0];if(!s)return l?{startLine:l.startLine,endLine:l.endLine}:{startLine:n,endLine:i};let c=[];Ci(s.rootNode,d=>{Vn.has(d.type)&&d.startPosition.row>=n&&d.endPosition.row<=i&&o.every(m=>d.startPosition.row<=m&&d.endPosition.row>=m)&&c.push(d)});let u=c.sort((d,m)=>d.endPosition.row-d.startPosition.row-(m.endPosition.row-m.startPosition.row)||d.startPosition.row-m.startPosition.row)[0];return u?{startLine:u.startPosition.row,endLine:u.endPosition.row}:l?{startLine:l.startLine,endLine:l.endLine}:{startLine:n,endLine:i}}function hc(e,t,n,i,r={}){if(i-n+1<(r.minimumBodyLines??VI))return null;let s=Dp(e,t,n,i,[],!1);if(!s)return null;let a=s.candidates.map(b=>({...b,signals:b.signals.filter(v=>v!=="anchor"&&v!=="signature")})).filter(b=>b.signals.length>0);if(a.length===0)return null;let l=bE(a),c=a.filter(b=>b.text.length<=pc);if(c.length===0)return null;let u=vp.filter(b=>(l[b]??0)>0),d=u.filter(b=>b!=="await"),m=s.shapes.reduce((b,v)=>b+v.fields.length,0);if(d.length===0&&!((l.await??0)>0&&m>0)&&m<3)return null;let f=SE(c,l),p=new Map;for(let b of u){let v=f.find(y=>y.signals.includes(b));v&&p.set(v.line,v)}if(p.size===0){let b=f.find(v=>v.signals.includes("branch"));b&&p.set(b.line,b)}let g=Math.min(10,Math.max(1,r.maxLines??p.size)),h=new Map;for(let b of p.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:i,lines:[...h.values()].sort((b,v)=>b.line-v.line),shapes:s.shapes,signalCounts:l,candidateLines:a.length,omittedLines:a.length-h.size}}function En(e,t,n,i){let r=Dp(e,t,n,i,[],!1);return r?new Map(r.candidates.map(o=>[o.line,o.signals.filter(s=>s!=="lifecycle")])):new Map}var Vn=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"]),Rt=new Set(["block","body","compound_statement","declaration_list","statement_block"]),Wr=new Set(["if_expression","if_statement","unless","unless_statement"]),XI=new Set(["conditional_expression","ternary_expression"]),ea=new Set(["do_statement","enhanced_for_statement","for_expression","for_in_statement","for_of_statement","for_statement","loop_expression","while_statement"]),Xr=new Set(["match_expression","match_statement","switch_expression","switch_statement"]),Rp=new Set(["case_statement","match_arm","switch_case","switch_default"]),Qr=new Set(["try_expression","try_statement"]),Js=new Set(["catch_clause","except_clause","rescue"]),Jr=new Set(["ensure","finally_clause"]),Vr=new Set(["else","else_clause"]),Ip=new Set(["raise_statement","return_statement","throw_statement"]),QI=new Set(["block_comment","comment","line_comment"]);function ZI(e,t,n){let i=n.childForFieldName("condition")??Cc(n),r=n.childForFieldName("consequence")??n.childForFieldName("body")??n.namedChildren.find(l=>Rt.has(l.type)),o=n.childForFieldName("alternative")??n.namedChildren.find(l=>Vr.has(l.type));if(!i||!r){t.push(vc(n,"conditional-fields-unresolved"));return}let s=ln(i,"predicate",i.text),a=ln(r,yp(r),"consequence");if(an(e,s,a,"predicate-consequence",{branchRole:"consequence"}),Ys(e,s,r,"consequence"),o){let l=ln(o,yp(o),"alternative");an(e,s,l,"predicate-alternative",{branchRole:"alternative"}),Ys(e,s,o,"alternative");return}an(e,s,yc(s,"otherwise continue"),"predicate-fallthrough",{branchRole:"fallthrough"})}function eE(e,t,n){let i=n.childForFieldName("body")??n.namedChildren.find(s=>Rt.has(s.type));if(!i){t.push(vc(n,"loop-body-unresolved"));return}let r=n.childForFieldName("condition"),o=ln(r??n,"predicate",r?.text??Kt(n,i));an(e,o,ln(i,"outcome","iteration"),"loop-iteration",{branchRole:"iteration"}),Ys(e,o,i,"iteration"),an(e,o,yc(o,"loop exits"),"loop-exit",{branchRole:"exit"})}function tE(e,t,n){let i=n.childForFieldName("body")??n.namedChildren.find(l=>Rt.has(l.type)),r=n.childForFieldName("value")??n.childForFieldName("condition")??n.childForFieldName("subject")??Cc(n),o=rE(i??n);if(!r||o.length===0){t.push(vc(n,"switch-cases-unresolved"));return}let s=ln(r,"predicate",r.text),a=!1;for(let l of o){let c=sE(l);a||=c;let u=Kt(l,l.namedChildren.find(d=>Xs(d)));an(e,s,ln(l,"outcome",u||(c?"default":"case")),c?"predicate-default":"predicate-case",{branchRole:c?"default":"case"}),Ys(e,s,l,c?"default":"case")}a||an(e,s,yc(s,"no case matched"),"predicate-fallthrough",{branchRole:"fallthrough"})}function nE(e,t){let n=ln(t,"scope","try");for(let i of oE(t)){let r=Jr.has(i.type),o=ln(i,"handler",r?"finally":Kt(i,Ws(i)));an(e,n,o,r?"finally-cleanup":"exception-handler",{branchRole:r?"finally":"catch"}),iE(e,o,i,r?"finally":"catch")}}function iE(e,t,n,i){for(let r of bc(n)){let o=r.label.startsWith("throw")||r.label.startsWith("raise")?"throw":"return";an(e,t,r,o==="throw"?"handler-throw":"handler-return",{branchRole:i,terminalKind:o})}}function Ys(e,t,n,i){for(let r of bc(n)){let o=r.label.startsWith("throw")||r.label.startsWith("raise")?"throw":"return";an(e,t,r,o==="throw"?"predicate-throw":"predicate-return",{branchRole:i,terminalKind:o})}}function an(e,t,n,i,r){e.push({controller:t,outcome:n,subtype:i,attributes:r})}function ln(e,t,n){return{kind:t,label:Yr(n).slice(0,gc),startLine:e.startPosition.row,endLine:e.endPosition.row,implicit:!1}}function yc(e,t){return{...e,kind:"outcome",label:t,implicit:!0}}function yp(e){return Ip.has(e.type)?"terminal":"outcome"}function bc(e){let t=[];return Sc(e,e,n=>{Ip.has(n.type)&&t.push(ln(n,"terminal",n.text))}),Ep(t)}function Sc(e,t,n){n(t);for(let i of t.namedChildren)i!==e&&Vn.has(i.type)||Sc(e,i,n)}function rE(e){let t=[],n=i=>{for(let r of i.namedChildren)Xr.has(r.type)||(Rp.has(r.type)?t.push(r):n(r))};return n(e),t}function oE(e){let t=[],n=i=>{for(let r of i.namedChildren)Qr.has(r.type)||(Js.has(r.type)||Jr.has(r.type)?t.push(r):Vn.has(r.type)||n(r))};return n(e),t}function sE(e){let t=Kt(e,e.namedChildren.find(n=>Xs(n))).trim();return e.type==="switch_default"||/^(?:default\b|_\s*=>)/u.test(t)}function vc(e,t){return{startLine:e.startPosition.row,endLine:e.endPosition.row,reason:t}}function aE(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 Ep(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 lE(e){return Vn.has(e.type)||ea.has(e.type)||Xr.has(e.type)||Qr.has(e.type)||Js.has(e.type)||Jr.has(e.type)}function wp(e,t,n,i,r){let s=ir(e,n,i)??e,a=Ws(s),l=[],c=0,u=0,d=(S,x,C,L,w=!1,R=!0)=>{let M=w?C.trim():Yr(C);if(!M)return;let _=Math.max(n,S.startPosition.row),D=Math.min(i,S.endPosition.row);l.push({line:_,endLine:Math.max(_,D),depth:x,signals:Qs.filter(P=>L.includes(P)||P==="anchor"&&r.some(k=>k>=_&&k<=D)),text:M,copied:w}),R&&(c+=1,w&&(u+=1))},m=(S,x)=>{for(let C of S.namedChildren)E(C,x)},f=(S,x)=>{if(Wr.has(S.type)){p(S,x,"else if");return}if(Vr.has(S.type)){let C=S.namedChildren.find(w=>Wr.has(w.type));if(C){p(C,x,"else if");return}d(S,x,"else",["branch"],!1,!1);let L=Ws(S)??S.namedChildren.find(w=>Rt.has(w.type));if(L)E(L,x+1);else for(let w of S.namedChildren)E(w,x+1);return}d(S,x,"else",["branch"],!1,!1),E(S,x+1)},p=(S,x,C=S.type.startsWith("unless")?"unless":"if")=>{let L=S.childForFieldName("condition")??Cc(S),w=S.childForFieldName("consequence")??S.childForFieldName("body")??S.namedChildren.find(_=>Rt.has(_.type)),R=S.childForFieldName("alternative")??S.namedChildren.find(_=>Vr.has(_.type)),M=L?L.text:Kt(S,w);d(S,x,`${C} ${mE(M)}`,Gr(L,["branch"])),w&&E(w,x+1),R&&f(R,x)},g=(S,x)=>{let C=S.childForFieldName("body")??S.namedChildren.find(L=>Rt.has(L.type));d(S,x,Kt(S,C),Gr(S,["loop"])),C&&E(C,x+1)},h=(S,x)=>{let C=S.childForFieldName("body")??S.namedChildren.find(L=>Rt.has(L.type));d(S,x,Kt(S,C),Gr(S,["branch"])),C&&E(C,x+1)},b=(S,x)=>{let C=S.namedChildren.find(L=>Xs(L));d(S,x,Kt(S,C),["branch"],!1,!1);for(let L of S.namedChildren)(L===C||Xs(L))&&E(L,x+1)},v=(S,x)=>{d(S,x,"try",[],!1);for(let C of S.namedChildren)Rt.has(C.type)?E(C,x+1):(Js.has(C.type)||Jr.has(C.type))&&E(C,x)},y=(S,x,C)=>{let L=S.childForFieldName("body")??S.namedChildren.find(R=>Rt.has(R.type)),w=C==="finally"?"finally":Kt(S,L);d(S,x,w,[C],!1,!1),L&&E(L,x+1)},I=(S,x)=>{let C=Ws(S);d(S,x,Kt(S,C),Gr(S,["binding"])),C&&E(C,x+1)},E=(S,x)=>{if(S.startPosition.row>i||S.endPosition.row<n||QI.has(S.type)||S.type==="empty_statement")return;if(Rt.has(S.type)){m(S,x);return}if(Wr.has(S.type)){p(S,x);return}if(ea.has(S.type)){g(S,x);return}if(Xr.has(S.type)){h(S,x);return}if(Rp.has(S.type)){b(S,x);return}if(Qr.has(S.type)){v(S,x);return}if(Js.has(S.type)){y(S,x,"catch");return}if(Jr.has(S.type)){y(S,x,"finally");return}if(Vr.has(S.type)){f(S,x);return}if(Vn.has(S.type)){I(S,x);return}let L=!Lp(S)||fE(S);d(S,x,S.text,Gr(S),L)};return E(a&&a!==s?a:s,0),c===0?null:{constructKind:dE(s),signature:uE(s,a,t,n),lines:l,sourceStatements:c,copiedStatements:u}}function ir(e,t,n){let i=e.namedChildren.filter(r=>r.startPosition.row<=t&&r.endPosition.row>=n);for(let r of i.sort(cE)){let o=ir(r,t,n);if(o)return o}return Vn.has(e.type)&&e.startPosition.row<=t&&e.endPosition.row>=n?e:null}function cE(e,t){return e.endPosition.row-e.startPosition.row-(t.endPosition.row-t.startPosition.row)||e.startPosition.row-t.startPosition.row}function Ws(e){return e.childForFieldName("body")??e.childForFieldName("consequence")??e.namedChildren.find(t=>Rt.has(t.type))??null}function uE(e,t,n,i){let r=Kt(e,t);return r||(n[i]??e.text).trim()}function dE(e){return e.type.includes("constructor")?"constructor":e.type.includes("method")||e.type==="method"?fc(e,new Set(["class_body","class_declaration","class_definition"]))?"class method":"object method":e.type==="arrow_function"||e.type==="function_expression"||e.type==="lambda"?fc(e,new Set(["object","pair"]))?"object member":"function value":e.type.includes("function")?fc(e,Vn)?"nested function":"module function":"source construct"}function fc(e,t){let n=e.parent;for(;n;){if(t.has(n.type))return!0;n=n.parent}return!1}function Cc(e){return e.namedChildren.find(t=>!Rt.has(t.type)&&!Vr.has(t.type))??null}function Kt(e,t){if(!t)return Yr(e.text);let n=Math.max(0,t.startIndex-e.startIndex);return Yr(e.text.slice(0,n)).replace(/[:{]\s*$/u,"").trim()}function mE(e){let t=Yr(e);return t.startsWith("(")&&t.endsWith(")")?t.slice(1,-1).trim():t}function Yr(e){return e.trim().replace(/\r?\n[\t ]*/gu," ")}function Gr(e,t=[]){let n=new Set(t);return e&&Ci(e,i=>{let r=bp[i.type];r&&n.add(r),i.type==="call_expression"&&(n.add("call"),Mp(i)&&n.add("shape")),xc.has(i.type)&&n.add("binding")}),Qs.filter(i=>n.has(i))}function fE(e){let t=!1;return Ci(e,n=>{t||!n.text.includes(`
40
+ `)||/(?:string|template|heredoc|raw_string)/u.test(n.type)&&(t=!0)}),t}function Xs(e){return Rt.has(e.type)||Wr.has(e.type)||ea.has(e.type)||Xr.has(e.type)||Qr.has(e.type)||Vn.has(e.type)||Lp(e)}function Lp(e){return/(?:statement|declaration|expression|assignment|return|throw|raise|break|continue|yield|with_item)$/u.test(e.type)||xc.has(e.type)}function pE(e,t,n){let i=0;for(let r=t;r<=n;r+=1)i+=(e[r]?.length??0)+10;return i}function gE(e){return e.constructKind.length+e.signature.length+80+e.lines.reduce((t,n)=>t+n.text.length+n.depth*2+10,0)}function Dp(e,t,n,i,r,o){let s=ae(e,t);if(!s)return null;let a=re(e,t),l=ta(e,t,n,i),c=o?l?.startLine??n:n,u=o?l?.endLine??i:i,m=(l?.startLine===c&&l.endLine===u?ir(s.rootNode,c,u):null)??Zr(s.rootNode,c,u);if(!m)return null;let f=new Map,p=new Map,g=new Map,h=(y,I)=>{if(y<c||y>u)return;let E=f.get(y)??new Set;E.add(I),f.set(y,E)};l&&h(l.startLine,"signature");for(let y of r)h(y,"anchor");Ci(m,y=>{let I=bp[y.type];if(I&&h(y.startPosition.row,I),I==="shape"&&hE(p,y,m,c,u),y.type==="call_expression"){let S=(y.childForFieldName("function")??y.namedChild(0))?.text.split(".").at(-1);if(Mp(y)){h(y.startPosition.row,"shape");let x=Vs(y.text);x.length<=pc&&g.set(y.startPosition.row,x)}if(S&&YI.has(S)){h(y.startPosition.row,"lifecycle");let x=Vs(y.text);x.length<=pc&&g.set(y.startPosition.row,x)}}xc.has(y.type)&&h(y.startPosition.row,"binding")});let b=te(e,t);for(let y of b?.callSites??[])y.line<c||y.line>u||(h(y.line,"call"),y.calleeLeaf==="catch"&&h(y.line,"catch"));let v=[...f.entries()].sort(([y],[I])=>y-I).map(([y,I])=>({line:y,signals:Sp.filter(E=>I.has(E)),text:g.get(y)??Vs(a[y]??"")})).filter(y=>y.text.length>0||y.signals.includes("anchor"));return{...l?{callable:l}:{},rangeStart:c,rangeEnd:u,sourceLines:a,candidates:v,shapes:[...p.values()].sort((y,I)=>y.startLine-I.startLine)}}function hE(e,t,n,i,r){if(t.startPosition.row<i||t.endPosition.row>r)return;let o=t.childForFieldName("key")??t.childForFieldName("name")??t.namedChild(0),s=Vs(o?.text??"");if(!s||s.includes(`
41
+ `)||s.length>60)return;let a=yE(t,n);if(a.startPosition.row<i||a.endPosition.row>r)return;let l=`${a.startPosition.row}:${a.endPosition.row}`,c=e.get(l)??{startLine:a.startPosition.row,endLine:a.endPosition.row,fields:[]};c.fields.some(u=>u.name===s&&u.line===t.startPosition.row)||c.fields.push({name:s,line:t.startPosition.row}),e.set(l,c)}function yE(e,t){let n=e.parent;for(;n&&n!==t.parent;){if(Cp.has(n.type))return n;if(n===t)break;n=n.parent}return e.parent??e}function ta(e,t,n,i){return te(e,t)?.callables.filter(r=>r.startLine<=n&&r.endLine>=i).sort((r,o)=>r.endLine-r.startLine-(o.endLine-o.startLine)||r.startLine-o.startLine)[0]}function Zr(e,t,n){if(e.startPosition.row>t||e.endPosition.row<n)return null;for(let i of e.namedChildren){let r=Zr(i,t,n);if(r)return r}return e}function Ci(e,t){t(e);for(let n of e.namedChildren)Ci(n,t)}function Vs(e){return e.trim().replace(/\s+/gu," ")}function Mp(e){if(e.type!=="call_expression")return!1;let t=e.childForFieldName("arguments")??e.namedChildren.find(i=>i.type==="arguments"||i.type==="argument_list");if(!t)return!1;let n=!1;return Ci(t,i=>{Cp.has(i.type)&&(n=!0)}),n}function bE(e){let t={};for(let n of Sp){let i=e.filter(r=>r.signals.includes(n)).length;i>0&&(t[n]=i)}return t}function SE(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 i=new Set(vp),r=o=>{let s=n.get(o.signals.join(","))??1,a=Math.min(...o.signals.map(u=>t[u]??1)),l=o.signals.some(u=>i.has(u))?3:1,c=Math.max(0,o.signals.length-1)*1e3;return l*(1e3/s+1e3/a)+c};return[...e].sort((o,s)=>r(s)-r(o)||s.line-o.line)}var xc=new Set(["lexical_declaration","variable_declarator","const_item","static_item","let_declaration","assignment"]);function vE(e,t,n){let i=[],r=/\b(?:describe|it|test)(?:\.(?:only|skip|todo))?\s*\(\s*(['"`])([^'"`]+)\1/u;for(let o=t;o<=n;o+=1){let s=r.exec(e[o]??"")?.[2];if(!(!s||i.includes(s))&&(i.push(s),i.length>=WI))break}return i}var CE=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 rr(e,t,n){let i=ae(e,t)?.rootNode??null,r=xE(i,n);if(!r)return null;let o=re(e,t);if(o.length===0)return null;let s=Math.max(0,r.startPosition.row),a=r.endPosition.column===0?r.endPosition.row-1:r.endPosition.row;return{type:r.type,startLine:s,endLine:Math.min(o.length-1,Math.max(s,a))}}function eo(e,t,n,i,r){let o=yt(e,t,i,r,[n]),s=o.startLine===o.endLine&&/(?:=>|\(|\{|\[|,)\s*$/u.test(re(e,t)[o.startLine]??"");if(!s&&(o.startLine>i||o.endLine<r))return o;let a=rr(e,t,n);return s&&a?{startLine:a.startLine,endLine:a.endLine}:a&&a.startLine>=i&&a.endLine<=r?{startLine:a.startLine,endLine:a.endLine}:{startLine:i,endLine:r}}function xE(e,t){if(!e||!Fp(e,t))return null;let n=Tp(e,t);for(;n;){if(CE.has(n.type))return n;n=n.parent}return null}function Tp(e,t){let n=e.namedChildren.filter(i=>Fp(i,t)).sort((i,r)=>Pp(i)-Pp(r));return n.length>0?Tp(n[0],t):e}function Fp(e,t){return e.startPosition.row<=t&&e.endPosition.row>=t}function Pp(e){return e.endIndex-e.startIndex}var RE=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 na(e,t,n,i){if(!Number.isSafeInteger(n)||n<0)return null;if(!Number.isSafeInteger(i)||i<0)throw new RangeError(`contextLines must be a non-negative safe integer; received ${i}`);let r=re(e,t);if(r.length===0||n>=r.length)return null;let o=Math.max(0,n-i),s=Math.min(r.length-1,n+i);return{relativePath:t,startLine:o,endLine:s,focusLine:n,source:r.slice(o,s+1).join(`
42
+ `)}}function kp(e,t,n,i,r){let o=na(e,t,n,i);if(!o)return null;let s=ae(e,t)?.rootNode??null;if(!s)return{...o,kind:"bounded-context"};let a=IE(s,n,r);if(a.length!==1)return{...o,kind:a.length===0?"non-call-reference":"bounded-context"};let l=a[0],c=re(e,t),u=Math.max(0,l.startPosition.row),d=l.endPosition.column===0?l.endPosition.row-1:l.endPosition.row,m=Math.min(c.length-1,Math.max(u,d));return{relativePath:t,startLine:u,endLine:m,focusLine:n,source:c.slice(u,m+1).join(`
43
+ `),kind:"complete-call-expression"}}function Np(e,t,n,i,r){if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`maxLines must be a positive safe integer; received ${r}`);let o=re(e,t);if(o.length===0||n<0||n>=o.length)return null;let s=Math.min(o.length-1,i,n+r-1);return{relativePath:t,startLine:n,endLine:s,focusLine:n,source:o.slice(n,s+1).join(`
44
+ `)}}function Jn(e,t,n,i,r=6){if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`maxLines must be a positive safe integer; received ${i}`);let o=re(e,t);if(o.length===0||n<0||n>=o.length)return null;let s=rr(e,t,n);if(!s){let g=na(e,t,n,r);return g?{...g,unitType:null,unitStartLine:g.startLine,unitEndLine:g.endLine,omittedLines:0}:null}let a=s.startLine,l=s.endLine,c=l-a+1,u=Math.min(c,i),d=n-a-Math.floor(u/2),m=Math.max(0,Math.min(c-u,d)),f=a+m,p=f+u-1;return{relativePath:t,startLine:f,endLine:p,focusLine:n,source:o.slice(f,p+1).join(`
45
+ `),unitType:s.type,unitStartLine:a,unitEndLine:l,omittedLines:c-u}}function IE(e,t,n){let i=[];return Ap(e,t,n,i),i.filter(r=>!i.some(o=>o!==r&&o.startIndex>=r.startIndex&&o.endIndex<=r.endIndex))}function Ap(e,t,n,i){if(wE(e,t)){RE.has(e.type)&&EE(e)===n&&i.push(e);for(let r of e.namedChildren)Ap(r,t,n,i)}}function EE(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 wE(e,t){return e.startPosition.row<=t&&e.endPosition.row>=t}function Ec(e,t,n={}){let{context:i=0}=n,r=Gp(t);if(r)return Wp(e,r.filePath,r.startLine,r.endLine,i);let o=qp(e,t);if(o)return Hp(e,o);let s=pe(e,t);return s?to(e,s,i):null}function DE(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 i=n.context??0,r=n.members??"exported",o=t.map(l=>ME(e,l,i,r)),s=o.flatMap(l=>l.results),a=s.map(l=>({relativePath:l.relativePath,startLine:l.startLine,endLine:l.endLine}));return{requested:t.length,matched:o.filter(l=>l.status==="matched").length,ambiguous:o.filter(l=>l.status==="ambiguous").length,missing:o.filter(l=>l.status==="missing").length,entries:o,bindingClosure:Gs(s.map(l=>l.bindingClosure),a)}}function ME(e,t,n,i){let r=Gp(t);if(r){let u=Wp(e,r.filePath,r.startLine,r.endLine,n);return u?PE(e,t,u,n):Rc(e,t,"definition-source-unreadable")}let o=qp(e,t);if(o)return FE(e,t,o,n,i);let s=at(e,t);if(!s.match)return Rc(e,t,"definition-not-found");let a=HE(e,s),l=a.map(Kp);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=to(e,d,n);return m?[m]:[]}):[],definitions:[],candidates:l,omittedCandidates:Math.max(0,s.total-l.length),suggestions:[]}}let c=to(e,s.match,n);return c?jE(t,c):Rc(e,t,"definition-source-unreadable")}function PE(e,t,n,i){let r=W(e,n.relativePath).filter(c=>!Bp(c,n.relativePath)),o=TE(e,n,r),s=jp(o.map(c=>to(e,c,i)).filter(c=>c!==null)).filter(c=>!zp(n,c)),a=new Set(s.map(c=>c.symbol)),l=o.filter(c=>!a.has(c.symbol)&&!(n.startLine<=c.startLine&&n.endLine>=c.endLine)).map(Kp);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-l.length,returnedBodies:s.length,omittedDefinitions:l.length,omittedLedger:l}}}function TE(e,t,n){if(!no(t.freshness))return[];if(n.length===0)return[];let i=dc(e,n,{additive:!1,semantic:!1}),r=new Map;for(let s of n){let a=r.get(s.symbol)??[];a.push(s),r.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 i.get(s.symbolId)??[])if(a.file===t.relativePath&&!(a.source==="ast-callsite"&&(a.chunkId<t.startLine||a.chunkId>t.endLine)))for(let l of r.get(a.symbol)??[])o.set(l.symbolId,l)}return $p(e,[...o.values()],n)}function FE(e,t,n,i,r){let o=n.relativePath,s=NE(e,o),a=no(n.freshness)?W(e,o).filter(g=>!Bp(g,o)):[],l=a.filter(g=>xt(e,g)),c=l.length>0?l:kE(s,a),u=r==="all"?[]:$p(e,c,a),d=r==="all"||a.length===0?[Hp(e,n)]:jp(u.map(g=>to(e,g,i)).filter(g=>g!==null)),m=_E(s,d),f=BE(o,s,d),p=OE(s);return{selector:t,status:"matched",kind:"file-source",totalCandidates:1,results:d,definitions:[],candidates:[],omittedCandidates:0,suggestions:[],fileCoverage:{members:r,basis:r==="all"||a.length===0?"complete-file-source":l.length>0?"explicit-exports-and-same-file-reference-closure":"top-level-and-same-file-reference-closure",totalDefinitions:p,returnedDefinitions:m,returnedBodies:d.length,omittedDefinitions:Math.max(0,p-m),omittedLedger:f}}}function kE(e,t){let n=new Set(e.map(i=>i.symbol));return t.filter(i=>n.has(i.symbol))}function NE(e,t){return ac(e,t).flatMap(n=>AE(n,t)?n.children:[n])}function Bp(e,t){return Op(t).has(e.leaf)}function AE(e,t){return Op(t).has(Y(e.symbol))}function Op(e){let t=LE(e);return new Set([t,t.slice(0,Math.max(0,t.length-_p(t).length))])}function $p(e,t,n){if(t.length===0)return[];let i=dc(e,n,{additive:!0,semantic:!1}),r=new Map;for(let a of n){let l=r.get(a.symbol)??[];l.push(a),r.set(a.symbol,l)}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 l of i.get(a.symbolId)??[])for(let c of r.get(l.symbol)??[])o.has(c.symbolId)||s.push(c)}}return[...o.values()].sort($E)}function jp(e){let t=[...e].sort((i,r)=>i.relativePath.localeCompare(r.relativePath)||i.startLine-r.startLine||r.endLine-i.endLine),n=[];for(let i of t)n.some(r=>zp(r,i))||n.push(i);return n}function Hp(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??wc(t.relativePath),source:t.text,freshness:t.freshness,...no(t.freshness)?{bindingClosure:tr(e,t.relativePath,0,Math.max(0,n.length-1))}:{}}}function _E(e,t){return ia(e).filter(n=>t.some(i=>Ic(n,i))).length}function BE(e,t,n){let i=[];return Up(i,e,t,n,0),i}function Up(e,t,n,i,r){for(let o of n){if(i.some(a=>Ic(o,a)))continue;let s=ia(o.children).filter(a=>!i.some(l=>Ic(a,l))).length;e.push({symbol:o.symbol,shortName:o.shortName,relativePath:t,startLine:o.startLine,endLine:o.endLine,signature:o.signature,depth:r,nestedDefinitions:s}),Up(e,t,o.children,i,r+1)}}function ia(e){return e.flatMap(t=>[t,...ia(t.children)])}function OE(e){return ia(e).length}function Ic(e,t){return t.startLine<=e.startLine&&t.endLine>=e.endLine}function zp(e,t){return e.relativePath===t.relativePath&&e.startLine<=t.startLine&&e.endLine>=t.endLine}function $E(e,t){return e.startLine-t.startLine||t.endLine-e.endLine||e.symbol.localeCompare(t.symbol)}function jE(e,t){return{selector:e,status:"matched",kind:"source",totalCandidates:1,results:[t],definitions:[],candidates:[],omittedCandidates:0,suggestions:[]}}function Rc(e,t,n){return{selector:t,status:"missing",kind:"source",totalCandidates:0,results:[],definitions:[],candidates:[],omittedCandidates:0,suggestions:Ns(e,t,5),reason:n}}function qp(e,t){try{return Us(e,t)}catch(n){if(n instanceof Qm)return null;throw n}}function HE(e,t){if(!t.match)return[];let n=[t.match];for(let r of t.candidates){let o=W(e,r.relativePath).find(s=>s.symbol===r.symbol&&s.startLine===r.startLine);o&&n.push(o)}let i=new Set;return n.filter(r=>{let o=`${r.relativePath}:${r.startLine}:${r.endLine}:${r.symbol}`;return i.has(o)?!1:(i.add(o),!0)})}function Kp(e){return{symbol:e.symbol,shortName:A(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine}}function Gp(e){let t=e.match(/^(.+):(\d+)-(\d+)$/);if(!t)return null;let n=Number(t[2]),i=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(i)||i<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:i}}function to(e,t,n){let i=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),r=Us(e,t.relativePath);if(!r)return null;let s=r.text.split(`
47
47
  `),a=t.endLine<=t.startLine?Jn(e,t.relativePath,t.startLine,Number.MAX_SAFE_INTEGER):null,l=a?.unitType?a.unitStartLine:t.startLine,c=a?.unitType?a.unitEndLine:t.endLine,u=Math.max(0,l-n),d=Math.min(s.length-1,c+n),m=s.slice(u,d+1).join(`
48
- `);return{symbol:t.symbol,shortName:A(t.symbol),relativePath:t.relativePath,startLine:u,endLine:d,language:i?.language??Lc(t.relativePath),source:m,freshness:r.freshness,...ro(r.freshness)?{bindingClosure:ir(e,t.relativePath,u,d)}:{}}}function Yp(e,t,n,i,r){let o=zs(e,t);if(!o)return null;let s=e.get("SELECT language FROM documents WHERE relative_path = ?",o.relativePath),l=o.text.split(`
48
+ `);return{symbol:t.symbol,shortName:A(t.symbol),relativePath:t.relativePath,startLine:u,endLine:d,language:i?.language??wc(t.relativePath),source:m,freshness:r.freshness,...no(r.freshness)?{bindingClosure:tr(e,t.relativePath,u,d)}:{}}}function Wp(e,t,n,i,r){let o=Us(e,t);if(!o)return null;let s=e.get("SELECT language FROM documents WHERE relative_path = ?",o.relativePath),l=o.text.split(`
49
49
  `);if(n>l.length)return null;let c=Math.max(0,n-1-r),u=Math.min(l.length-1,i-1+r),d=l.slice(c,u+1).join(`
50
- `);return{symbol:`${o.relativePath}:${n}-${i}`,shortName:`${o.relativePath}:${n}-${i}`,relativePath:o.relativePath,startLine:c,endLine:u,language:s?.language??Lc(o.relativePath),source:d,freshness:o.freshness,...ro(o.freshness)?{bindingClosure:ir(e,o.relativePath,c,u)}:{}}}function ro(e){return!!(e&&e.semantic.state!=="stale"&&e.semantic.basis!=="no-compiler-document")}function Lc(e){switch($p(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 oa(e){let t=new Map;for(let n of e){let i=t.get(n.relativePath)??[];i.push(n),t.set(n.relativePath,i)}return t}function Xp(e){let t=new Map,n=KE(e),i=new Map;return r=>{let o=qE(r),s=i.get(o);if(s!==void 0)return s;if(!n.has(r.file))return i.set(o,r.symbol),r.symbol;let a=t.get(r.file);a||(a=GE(W(e,r.file)),t.set(r.file,a));let l=WE(a,r);return i.set(o,l),l}}function qE(e){return`${e.file}\0${e.symbol}\0${e.line}`}function KE(e){return new Set(e.all("SELECT relative_path FROM documents").map(t=>t.relative_path))}function GE(e){let t=new Map,n=new Map;for(let i of e){let r=t.get(i.leaf);r?r.push(i):t.set(i.leaf,[i]);let o=n.get(i.startLine);o?o.push(i):n.set(i.startLine,[i])}return{definitions:e,byLeaf:t,byStartLine:n}}function WE(e,t){if(e.definitions.length===0)return t.symbol;let n=YE(t.symbol),i=VE(e.byLeaf,n),r=JE(i,t.line);if(r)return r.symbol;let o=e.byStartLine.get(t.line)??[];return o.length===1?o[0].symbol:t.symbol}function VE(e,t){let n=[],i=new Set;for(let r of t)for(let o of e.get(r)??[])i.has(o.symbolId)||(i.add(o.symbolId),n.push(o));return n}function JE(e,t){let n=null;for(let i of e)if(!(i.startLine>t||i.endLine<t)){if(i.startLine===t)return i;(!n||i.endLine-i.startLine<n.endLine-n.startLine)&&(n=i)}return n}function YE(e){let t=new Set([e]),i=e.split(/::|\.|#/).filter(Boolean).at(-1);return i&&t.add(i),t}function Qp(e,t){let i=Ce(e,t).map(r=>QE(t,r));return{usage:i,positions:ZE(e,t,i)}}function Zp(e,t){return{importUsage(n){let i=e.importUsageFacts(n);if(!t||i.positions.length===0)return i.usage;let r=t.importDefinitionsForFile(n,i.positions);return r.available?XE(i.usage,r.sourcePaths):i.usage}}}function XE(e,t){return e.map((n,i)=>{let r=t.get(String(i));return r?{...n,sourcePath:r}:n})}function QE(e,t){let n=t.isTypeOnly===!0,i=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:i,isTypeUsed:n,isValueUsed:t.kind==="side-effect"||!n&&t.used,references:[]}}function ZE(e,t,n){let i=ae(e,t);if(!i)return[];let r=ew(i.rootNode),o=new Map;for(let a of r){let l=o.get(Mc(a.importedName,a.localName));l?l.push(a.position):o.set(Mc(a.importedName,a.localName),[a.position])}let s=[];return n.forEach((a,l)=>{let c=o.get(Mc(a.importedName,a.localName??a.importedName))?.shift();c&&s.push({...c,id:String(l),file:t})}),s}function ew(e){let t=[];for(let n of e.descendantsOfType("use_declaration")){let i=n.namedChildren.find(r=>r.type!=="visibility_modifier");i&&t.push(...sa(i,""))}return t.filter(n=>n.importedName!=="*")}function sa(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":return[{importedName:e.text,localName:e.text,position:Dc(e,e.text)}];case"scoped_identifier":{let n=e.text.split("::").pop()??e.text;return[{importedName:n,localName:n,position:Dc(e,n)}]}case"scoped_use_list":{let n=e.namedChild(0),i=e.namedChild(1);if(!n||!i)return[];let r=Df(t,n.text);return i.namedChildren.flatMap(o=>sa(o,r))}case"use_list":return e.namedChildren.flatMap(n=>sa(n,t));case"use_as_clause":{let n=e.namedChild(0),i=e.namedChild(1);return!n||!i?[]:sa(n,t).map(r=>({...r,localName:i.text}))}case"use_wildcard":{let n=e.namedChild(0),i="*";return[{importedName:i,localName:i,position:Dc(n??e,i)}]}default:return[]}}function Dc(e,t){let n=Math.max(0,e.text.lastIndexOf(t));return{id:"",file:"",line:e.startPosition.row,column:e.startPosition.column+n+tw(t)}}function tw(e){return Math.max(0,Math.min(e.length-1,1))}function Mc(e,t){return`${e}\0${t}`}import{spawnSync as Hc}from"child_process";import{existsSync as Uc}from"fs";import{fileURLToPath as tL}from"url";function Xn(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function aa(e){let t=Vf(Wf,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 jw,mkdtempSync as xg,rmSync as Ac}from"fs";import{tmpdir as Oc}from"os";import{join as _c}from"path";import{fileURLToPath as mo,pathToFileURL as Hw}from"url";import{SHARE_ENV as Uw,Worker as zw}from"worker_threads";function Qn(e,t,n=new Set){let i=new Map;for(let r of e)n.has(r.symbolId)||i.set(r.symbolId,t.get(r.symbolId)??[]);return i}function xi(e,t,n){let i=Xn(process.env.SCIP_RUST_SEMANTIC_BATCH_TIMEOUT_MS)??0;if(i>0)return i;let r=Math.max(1,Math.ceil(e/Math.max(1,n)));return Math.max(12e4,3e4+r*t)}import{spawn as vw}from"child_process";import{createHash as Cw,randomUUID as xw}from"crypto";import{existsSync as pg,realpathSync as Rw,rmSync as Iw}from"fs";import{tmpdir as Ew}from"os";import{resolve as lr}from"path";import{execFileSync as cw}from"child_process";import{existsSync as nw}from"fs";import{deserializeSCIP as iw,SymbolRole as rw}from"@c4312/scip";import{realpathSync as yJ}from"fs";import{basename as SJ,dirname as vJ,join as CJ,relative as xJ,sep as RJ}from"path";import{fileURLToPath as EJ,pathToFileURL as wJ}from"url";function la(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,i)=>{let r=n.file.localeCompare(i.file);return r!==0?r:n.line!==i.line?n.line-i.line:n.column-i.column})}var Pc=new WeakMap,ow="SCIP_RUST_SCIP_OCCURRENCE_REFERENCE_MODE";function eg(e,t){let n=new Map,i=ca(),r=t.filter(s=>ig(s,i));if(r.length===0)return n;let o=rg(e);if(!o)return n;for(let s of r){let a=ng(o,s);a!==null&&n.set(s.symbolId,a)}return n}function tg(e,t){if(!ig(t,ca()))return null;let n=rg(e);return n?ng(n,t):null}function ng(e,t){return e.referencesBySymbol.get(t.symbol)??[]}function ig(e,t="safe"){if(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||Xe(e.symbol)||/impl#\[[^\]]+\]\[Default\]default\(\)\.$/.test(e.symbol))return!1;if(t==="all")return!0;let n=Bt(e.symbol);if(n==="method")return!0;if(n!=="term")return!1;let i=zn(e.symbol);return"kind"in i?!1:!sw(i)}function sw(e){for(let t=0;t<e.descriptors.length-1;t+=1)if(e.descriptors[t]?.suffix==="type")return!0;return!1}function rg(e){if(Pc.has(e))return Pc.get(e)??null;let t=aw(e);return Pc.set(e,t),t}function aw(e){if(!e.generation.indexPath||!nw(e.generation.indexPath))return null;try{let t=iw(Vi(e.generation.indexPath,{inputKind:"SCIP occurrence-reference index",maxBytes:Wi})),n=new Map;for(let i of t.documents??[]){let r=i.relativePath;if(!(!r||e.isIgnored(r)))for(let o of i.occurrences??[]){if(!o.symbol||(o.symbolRoles&rw.Definition)!==0)continue;let s=lw(r,o.range);if(!s)continue;let a=n.get(o.symbol)??[];a.push(s),n.set(o.symbol,a)}}for(let[i,r]of n)n.set(i,la(r));return{referencesBySymbol:n}}catch{return null}}function lw(e,t){if(t.length<3)return null;let n=t[0],i=t[1];return!Number.isInteger(n)||!Number.isInteger(i)?null:{file:e,line:n,column:i}}function ca(){return process.env[ow]==="all"?"all":"safe"}var og=new Map;function Tc(e){let n=aa(e).resolvedBinary??null;return{engine:"rust-analyzer",resolvedBinary:n,version:n?uw(e,n):"unavailable"}}function Ri(e){return{...Tc(e),scipOccurrenceReferenceMode:ca()}}function uw(e,t){let n=`${e}\0${t}`,i=og.get(n);if(i)return i;let r;try{r=cw(t,["--version"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:2e3}).trim()}catch{r="unknown"}return og.set(n,r),r}import{createHash as dw}from"crypto";var mw=new Set(["Cargo.lock","Cargo.toml","rust-project.json","rust-toolchain","rust-toolchain.toml"]);function sg(e){let t=mf(e,{includePath:fw});return dw("sha256").update(JSON.stringify(t)).digest("hex")}function fw(e){let t=e.replaceAll("\\","/"),n=t.split("/").at(-1)??t;return t.endsWith(".rs")||mw.has(n)?!0:t===".cargo/config"||t===".cargo/config.toml"||t.endsWith("/.cargo/config")||t.endsWith("/.cargo/config.toml")}import{createHash as pw}from"crypto";import{resolve as gw}from"path";var ar=3;function kc(e){return pw("sha256").update(bi({kind:"codebaseiq-durable-rust-mailbox",protocolVersion:ar,sessionDir:gw(e)})).digest("hex")}function cg(e,t){return jn(e)?e.protocolVersion!==ar?lg(e.protocolVersion===void 0?"helper wrote a prior uncorrelated response protocol":`helper wrote unsupported response protocol ${String(e.protocolVersion)}`):e.mailboxVersion!==Yi||e.id!==t.requestId||e.operationKey!==t.operationKey||e.sessionIdentity!==t.sessionIdentity||e.deadlineAtMs!==t.deadlineAtMs?lg("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"||!Sw(e.errorCode)?Fc("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"||!hw(e.response,t.requestKind)?Fc("helper wrote an invalid success response"):{ok:!0,session:e.session,response:e.response}:Fc("helper wrote an invalid response object")}function hw(e,t){return!jn(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")):ag(e.references,yw)&&(e.incompleteReferenceSymbolIds===void 0||Array.isArray(e.incompleteReferenceSymbolIds)&&e.incompleteReferenceSymbolIds.every(n=>Number.isSafeInteger(n)))&&(e.callees===void 0||ag(e.callees,bw))&&(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 ag(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 yw(e){return jn(e)&&typeof e.file=="string"&&Pt(e.line)&&Pt(e.column)}function bw(e){return jn(e)&&typeof e.symbol=="string"&&typeof e.file=="string"&&Pt(e.line)&&(e.callsiteLine===void 0||Pt(e.callsiteLine))}function Sw(e){return e==="unsupported-protocol"||e==="malformed-request"||e==="expired-request"||e==="handler-error"}function Fc(e){return{ok:!1,code:"malformed-response",error:e}}function lg(e){return{ok:!1,code:"incompatible-response",error:e}}var ww=5e3,gg=10,Lw=3e4;function ug(e,t,n,i=Sg){let r=i.engineIdentity(e),o={protocolVersion:ar,projectRoot:i.canonicalProjectRoot(e),projectFingerprint:i.projectFingerprint(e),engine:{engine:r.engine,resolvedBinary:r.resolvedBinary,version:r.version},workerFingerprint:i.fileFingerprint(t),environment:hg(i.environment())};return{key:vg(bi(o)),...o}}function oo(e,t,n,i){if(e.protocolVersion!==ar||!n(e.pid))return!1;if(!e.processIdentity)return!0;let r=i?.(e.pid);return r!=null&&bs(e.processIdentity,r)}function Nc(e,t,n){let i;try{i=Wl(t,{maxBytes:pi,inputKind:"Rust semantic engine artifact"})}catch{i="missing"}let r=vg(bi({projectRoot:lr(e),serverPath:lr(t),serverFingerprint:i})).slice(0,20);return lr(n,`codebaseiq-rust-session-${r}`)}function dg(e){let t=e===void 0?Number.NaN:Number(e);return Number.isInteger(t)&&t>=0?t:0}function hg(e){return Object.fromEntries(Object.entries(e).filter(([t])=>bg(t)).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,n??null]))}function yg(e,t){let n=t.runtime??kw,i=t.identityRuntime??Sg,r=Nc(e,t.serverPath,t.tempRoot??Ew()),o=!1,s=(a,l)=>{if(o)throw new Error("Durable Rust semantic session was already disposed.");return Mw(r,t.serverPath,t.semanticWorkerPath,a,l,n,t.mailboxLimits)};return{requestSemantic(a,l){let c=ug(e,t.semanticWorkerPath,a,i),{readinessDeadlineMs:u,...d}=a;return s({kind:"semantic",identityKey:c.key,workerEnvironment:fg(),request:{...d,referenceRetryTimeoutMs:Dw(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,a.referenceRetryTimeoutMs),settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:dg(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:l},l)},requestImportDefinitions(a,l){let c=ug(e,t.semanticWorkerPath,a,i),{readinessDeadlineMs:u,...d}=a;return s({kind:"import-definitions",identityKey:c.key,workerEnvironment:fg(),request:{...d,settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:dg(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:l},l)},shutdown(){o=!0}}}function Dw(e,t){return t!==void 0?t:e===void 0?Lw:void 0}function Mw(e,t,n,i,r,o,s={}){let a=o.now(),l=a+r,c=(o.monotonicNow??en)(),u=c+r,d=Br("rust-semantic-v3",i),m=Or(d),f=pf(e),p=kc(e),g=Is(f,{mailboxVersion:Yi,protocolVersion:ar,id:m,operationKey:d,clientId:o.randomId(),enqueuedAtMs:a,deadlineAtMs:l,sessionIdentity:p,request:i},{nowMs:a,limits:s});for(mg(e,t,n,u,o);(o.monotonicNow??en)()<=u;){if(pg(g.responsePath)){let b=Pw(Zt(g.responsePath,{maxBytes:s.maxItemBytes??pi,inputKind:"durable Rust semantic mailbox response"}),{requestId:m,operationKey:d,sessionIdentity:p,deadlineAtMs:g.authoritativeDeadlineAtMs,requestKind:i.kind,nowMs:o.now()});if(!b.ok)throw new Error(b.error);return Ae()&&xs({type:"span",name:"rust.semantic.durable-session.request",durationMs:(o.monotonicNow??en)()-c,ok:!0,session:b.session,kind:i.kind}),b.response}let h=so(e);(!h||!oo(h,o.now(),o.isProcessAlive,o.readProcessIdentity))&&mg(e,t,n,u,o),o.sleep(gg)}throw new Error(`Durable Rust semantic session timed out after ${(r/1e3).toFixed(0)}s.`)}function mg(e,t,n,i,r){let o=so(e);if(o&&oo(o,r.now(),r.isProcessAlive,r.readProcessIdentity))return;Iw(lr(e,"server.json"),{force:!0}),r.spawnServer(t,e,n);let s=r.monotonicNow??en,a=Math.min(i,s()+ww);for(;s()<=a;){let l=so(e);if(l&&oo(l,r.now(),r.isProcessAlive,r.readProcessIdentity))return;r.sleep(gg)}throw new Error("Durable Rust semantic session helper did not become ready within 5s.")}function so(e){try{let t=JSON.parse(Zt(lr(e,"server.json"),{maxBytes:ef,inputKind:"durable Rust session state"}));if(typeof t.protocolVersion!="number"||t.sessionIdentity!==void 0&&(typeof t.sessionIdentity!="string"||t.sessionIdentity!==kc(e))||typeof t.pid!="number"||typeof t.heartbeatAtMs!="number"||t.busyUntilMs!==void 0&&typeof t.busyUntilMs!="number"||t.mailbox!==void 0&&!Tw(t.mailbox))return null;let n=t.processIdentity===void 0?null:ys(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 Pw(e,t){try{return cg(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 Tw(e){if(!e||typeof e!="object")return!1;let t=e;return Pt(t.pending)&&Pt(t.inflight)&&Pt(t.responses)&&Pt(t.deadLetters)&&Pt(t.invalid)&&Pt(t.totalItems)&&typeof t.totalBytes=="number"&&Number.isFinite(t.totalBytes)&&t.totalBytes>=0&&(t.oldestPendingAt===void 0||Number.isFinite(Date.parse(t.oldestPendingAt)))}function fg(){return Object.fromEntries(Object.entries(process.env).filter(([e])=>Fw(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t??null]))}function bg(e){return e==="HOME"||e==="PATH"||e.startsWith("CARGO_")||e.startsWith("RA_")||e.startsWith("RUST")}function Fw(e){return bg(e)||e.startsWith("SCIP_RUST_")||e==="CODEBASEIQ_PROFILE"||e==="CODEBASEIQ_PROFILE_CACHE_STATE"||e==="CODEBASEIQ_PROFILE_COMMAND"||e==="CODEBASEIQ_PROFILE_OUT"||e==="CODEBASEIQ_PROFILE_RUN_ID"||e==="CODEBASEIQ_PROFILE_WORKLOAD_IDENTITY"||e==="CODEBASEIQ_PROFILE_WORKLOAD_IDENTITY_KIND"||e==="CODEBASEIQ_PROFILE_MIN_MS"}var Sg={canonicalProjectRoot(e){try{return Rw(e)}catch{return lr(e)}},projectFingerprint(e){return sg(e)},engineIdentity:Tc,fileFingerprint(e){return Wl(e,{maxBytes:pi,inputKind:"Rust semantic engine artifact"})},environment(){return hg(process.env)}},kw={now:Date.now,monotonicNow:en,randomId:xw,isProcessAlive:Gi,readProcessIdentity:Ji,spawnServer(e,t,n){if(!pg(e))throw new Error(`Durable Rust semantic session helper was not found at ${e}. Run npm run build first.`);vw(process.execPath,[e,t,n],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)}};function vg(e){return Cw("sha256").update(e).digest("hex")}import{randomUUID as gY}from"crypto";import{readdirSync as Nw,rmSync as yY,writeFileSync as bY}from"fs";import{join as Aw}from"path";var _w="rust-analyzer-owner-",Bw=".json",Ow=16*1024;async function Cg(e,t){if(!e)return[];let n;try{n=Nw(e)}catch{return[]}let i=n.filter(s=>s.startsWith(_w)&&s.endsWith(Bw)).map(s=>Aw(e,s)),r=[],o=[];for(let s of i){let a=$w(s);a?o.push(a):r.push({reaped:!1,reason:"identity-unavailable",detail:`Rust analyzer ownership record ${s} could not be validated.`})}return r.push(...await Promise.all(o.map(s=>Jf(s,t)))),r}function $w(e){try{let t=Zt(e,{maxBytes:Ow,inputKind:"rust-analyzer process ownership record"}),n=JSON.parse(t),i=ys(n.rootIdentity);return n.version!==1||!i||typeof n.ownsProcessGroup!="boolean"?null:{rootPid:i.pid,rootIdentity:i,ownsProcessGroup:n.ownsProcessGroup,knownMembers:new Map([[i.pid,i]])}}catch{return null}}var Rg=15e3,Ig=8,wg=5e3,qw=64,Kw=96,$c=class{constructor(t,n,i={}){this.projectRoot=t;this.status=n;this.opts=i;this.requester=i.requester??Vw(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:lo(n),references:co(t)};try{let i=this.requestSession(n.resolvedBinary,t,{includeReferences:!0});return{...ao(i),resolvedBinary:n.resolvedBinary,references:Qn(t,new Map(i.references),new Set(i.incompleteReferenceSymbolIds??[]))}}catch(i){return this.opts.fallbackReferenceResolver?.referencesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:i instanceof Error?i.message:String(i),references:co(t)}}}calleesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:lo(n),callees:uo(t)};try{let i=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!0});return{...ao(i),resolvedBinary:n.resolvedBinary,callees:Bc(t,new Map(i.callees??[]))}}catch(i){return this.opts.fallbackCalleeResolver?.calleesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:i instanceof Error?i.message:String(i),callees:uo(t)}}}referencesAndCalleesForDefinitions(t,n){let i=this.status(this.projectRoot);if(!i.available||!i.resolvedBinary)return{available:!1,resolvedBinary:i.resolvedBinary,reason:lo(i),references:co(t),callees:uo(n)};let r=[...t,...n];try{let o=this.requestSession(i.resolvedBinary,r,{includeReferences:t.length>0,includeCallees:n.length>0,referenceDefinitions:t,calleeDefinitions:n});return{...ao(o),resolvedBinary:i.resolvedBinary,references:Qn(t,new Map(o.references),new Set(o.incompleteReferenceSymbolIds??[])),callees:Bc(n,new Map(o.callees??[]))}}catch(o){return this.fallbackReferencesAndCallees(i,t,n,o)}}signaturesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:lo(n),signatures:Eg(t)};try{let i=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!1,includeSignatures:!0});return{...ao(i),resolvedBinary:n.resolvedBinary,signatures:Zw(t,new Map(i.signatures??[]))}}catch(i){return this.opts.fallbackSignatureResolver?.signaturesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:i instanceof Error?i.message:String(i),signatures:Eg(t)}}}importDefinitionsForFile(t,n){let i=this.status(this.projectRoot);if(n.length===0)return i.available?{available:!0,resolvedBinary:i.resolvedBinary,sourcePaths:new Map}:{available:!1,reason:i.reason,resolvedBinary:i.resolvedBinary,sourcePaths:new Map};if(!i.available||!i.resolvedBinary)return{available:!1,resolvedBinary:i.resolvedBinary,reason:lo(i),sourcePaths:new Map(n.map(r=>[r.id,null]))};try{let r=this.requestImportDefinitions(i.resolvedBinary,t,n);return{...ao(r),resolvedBinary:i.resolvedBinary,sourcePaths:new Map(r.sourcePaths)}}catch(r){return{available:!1,resolvedBinary:i.resolvedBinary,reason:r instanceof Error?r.message:String(r),sourcePaths:new Map(n.map(o=>[o.id,null]))}}}dispose(){this.requester.shutdown()}requestSession(t,n,i){let r=ua(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Rg),o=da(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),s=ua(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Ig),a=da(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(r,1e4)),l=i.referenceDefinitions?[...i.referenceDefinitions]:void 0,c=i.calleeDefinitions?[...i.calleeDefinitions]:void 0,u=i.signatureDefinitions?[...i.signatureDefinitions]:void 0,d=fo(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,...i}),m={projectRoot:this.projectRoot,rustAnalyzerBinary:t,definitions:[...n],...l?{referenceDefinitions:l}:{},...c?{calleeDefinitions:c}:{},...u?{signatureDefinitions:u}:{},requestTimeoutMs:r,...i.includeReferences!==!1&&o>0?{referenceRetryTimeoutMs:o}:{},diagnosticsTimeoutMs:a,settleDelayMs:d,concurrency:s,includeReferences:i.includeReferences,includeCallees:i.includeCallees,includeSignatures:i.includeSignatures},f=eL(m);return B("rust.semantic.session.request",()=>this.requester.requestSemantic(m,xi(f,jc(r,m.referenceRetryTimeoutMs),s)),()=>({definitions:n.length,operationDefinitions:f,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,i,r){let o=n.length===0?{available:!0,resolvedBinary:t.resolvedBinary,references:co(n)}:this.opts.fallbackReferenceResolver?.referencesForDefinitions(n),s=i.length===0?{available:!0,resolvedBinary:t.resolvedBinary,callees:uo(i)}:this.opts.fallbackCalleeResolver?.calleesForDefinitions(i);if(o&&s){let a={resolvedBinary:o.resolvedBinary??s.resolvedBinary??t.resolvedBinary,references:Qn(n,o.references),callees:Bc(i,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:r instanceof Error?r.message:String(r),references:co(n),callees:uo(i)}}requestImportDefinitions(t,n,i){let r=ua(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Rg),o=ua(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Ig),s=da(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(r,1e4)),a=da(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,wg),l={projectRoot:this.projectRoot,rustAnalyzerBinary:t,file:n,positions:[...i],requestTimeoutMs:r,diagnosticsTimeoutMs:s,settleDelayMs:a,concurrency:o};return B("rust.semantic.import-definitions.session.request",()=>this.requester.requestImportDefinitions(l,xi(i.length,r,o)),()=>({file:n,positions:i.length}))}};function ao(e){return e.available?{available:!0}:{available:!1,reason:e.reason}}function lo(e){return e.available?"rust-analyzer binary path is unavailable.":e.reason}function Lg(e,t,n={}){return new $c(e,t,n)}function fo(e,t){let n=Tg(e);if(n!==null)return n;let i=t.includeReferences!==!1;return i&&t.includeCallees!==!0&&t.includeSignatures!==!0&&t.definitionCount<=qw||i&&t.includeCallees===!0&&t.includeSignatures!==!0&&t.definitionCount<=Kw?0:wg}function Dg(e){let t=e?.trim().toLowerCase(),n=t==="0"||t==="false"||t==="off"||t==="worker",i=t==="1"||t==="true"||t==="on"||t==="durable",r=t===void 0||t==="";return{transport:n||!r&&!i?"worker":"durable",source:r?"default":"environment",fallback:"worker",valid:r||n||i,optOut:"SCIP_RUST_SEMANTIC_DURABLE_SESSION=0"}}function Gw(e){return Dg(e).transport}function BY(e,t){let n=Dg(t);if(n.transport==="worker")return{...n,state:"per-command"};let i=mo(Pg()),r=Nc(e,i,Oc()),o=so(r);return o?{...n,state:oo(o,Date.now(),Gi,Ji)?"live":"stale",pid:o.pid,heartbeatAtMs:o.heartbeatAtMs,...o.busyUntilMs===void 0?{}:{busyUntilMs:o.busyUntilMs}}:{...n,state:"stopped"}}function Ww(e,t){let n=null,i=!1,r=!1,o=!1,s=()=>n??=t(),a=()=>{r||(e.shutdown(),r=!0)},l=(u,d,m)=>{let f=Qw(u);i=!0;try{a()}catch{}Ae()&&xs({type:"span",name:"rust.semantic.durable-session.request",durationMs:m,ok:!1,kind:d,session:"worker-fallback",reason:f})},c=(u,d,m)=>{if(o)throw new Error("Rust semantic failover session was already disposed.");if(i)return m(s());let f=performance.now();try{return d(e)}catch(p){l(p,u,performance.now()-f)}return m(s())};return{requestSemantic(u,d){return c("semantic",m=>m.requestSemantic(u,d),m=>m.requestSemantic(u,d))},requestImportDefinitions(u,d){return c("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 Vw(e,t,n={worker:()=>Jw(),durable:()=>yg(e,{serverPath:mo(Pg()),semanticWorkerPath:mo(Mg())})}){return Gw(t)==="durable"?Ww(n.durable(),n.worker):n.worker()}function Jw(e={}){let t=null,n=null,i=1,r=!1,o=null,s=null,a=d=>{d&&Ac(d,{recursive:!0,force:!0})},l=()=>{if(o)return;let d=t,m=n;t=null,n=null;let f=d?d.terminate():Promise.resolve(0);o=Promise.allSettled([f,Cg(m,{gracefulMs:1e3,forceMs:1e3})]).then(([p,g])=>{let b=(g.status==="fulfilled"?g.value:[{reaped:!1,detail:String(g.reason)}]).filter(v=>!v.reaped);if(p.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})},c=()=>{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?Hw(e.semanticWorkerPath):Mg();if(!jw(mo(d)))throw new Error(`Rust semantic session worker was not found at ${mo(d)}. Run npm run build before using built semantic Rust queries.`);return n=xg(_c(Oc(),"codebaseiq-rust-session-")),t=new zw(d,e.shareEnvironment?{env:Uw}:void 0),t.unref(),t},u=()=>{let d=n??xg(_c(Oc(),"codebaseiq-rust-session-"));return n=d,_c(d,`${i++}.json`)};return{requestSemantic(d,m){if(r)throw new Error("Rust semantic session was already disposed.");let f=c(),p=u(),g=new SharedArrayBuffer(4),h=new Int32Array(g);if(f.postMessage({kind:"semantic",request:d,responsePath:p,sharedBuffer:g}),Atomics.wait(h,0,0,m)==="timed-out")throw l(),new Error(`Rust semantic session worker timed out after ${(m/1e3).toFixed(0)}s`);try{let v=Yw(Zt(p,{maxBytes:pi,inputKind:"Rust semantic worker response"}));if(!v.ok)throw new Error(v.error);return v.response}finally{Ac(p,{force:!0})}},requestImportDefinitions(d,m){if(r)throw new Error("Rust semantic session was already disposed.");let f=c(),p=u(),g=new SharedArrayBuffer(4),h=new Int32Array(g);if(f.postMessage({kind:"import-definitions",request:d,responsePath:p,sharedBuffer:g}),Atomics.wait(h,0,0,m)==="timed-out")throw l(),new Error(`Rust semantic import-definition session worker timed out after ${(m/1e3).toFixed(0)}s`);try{let v=Xw(Zt(p,{maxBytes:pi,inputKind:"Rust import-definition worker response"}));if(!v.ok)throw new Error(v.error);return v.response}finally{Ac(p,{force:!0})}},shutdown(){if(r)return;if(r=!0,!t){a(n),n=null;return}let d=u(),m=new SharedArrayBuffer(4),f=new Int32Array(m);t.postMessage({kind:"shutdown",responsePath:d,sharedBuffer:m}),Atomics.wait(f,0,0,5e3),l()}}}function Yw(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 Xw(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 Qw(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 co(e){return new Map(e.map(t=>[t.symbolId,[]]))}function uo(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Eg(e){return new Map(e.map(t=>[t.symbolId,null]))}function Bc(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??[]]))}function Zw(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function eL(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 jc(e,t){return t&&t>0?Math.max(e,t):e}function Mg(){return new URL("./rust-semantic-session-worker.js",import.meta.url)}function Pg(){return new URL("./rust-semantic-session-server.js",import.meta.url)}function ua(e,t){return Xn(e)??t}function da(e,t){return Tg(e)??t}function Tg(e){if(!e)return null;let t=Number(e);return Number.isInteger(t)&&t>=0?t:null}var zc=15e3,qc=8;function Ag(e,t={}){let n=t.status??aa,i=rL(e,n),r=oL(e,n),o=sL(e,n),s=t.referenceResolver||t.calleeResolver||t.signatureResolver||!nL(t)?null:Lg(e,n,{fallbackReferenceResolver:i,fallbackCalleeResolver:r,fallbackSignatureResolver:o}),a=t.referenceResolver??s??i,l=t.calleeResolver??s??r,c=t.signatureResolver??s??o,u=t.importUsageResolver??Zp(t.sourceImportUsageResolver??iL(),t.importDefinitionResolver??s),d=t.calleeSymbolResolver,m=t.sourceZeroCalleeOracle,f=t.scipOccurrenceCalleeOracle,p=new Map,g=new Map,h=null,b=null,v=()=>(h??=n(e),h),y=()=>{let C=v();return C.dependencyAvailable?b??C:C},I=C=>{if(C.length===0)return new Map;let L=go(C);try{let w=a.referencesForDefinitions(L),R=v();return b=ma(R,w),w.available?new Map(w.references):Qn(L,w.references)}catch(w){let R=v();return b=po(R,w),Ii(L)}},E=C=>{if(C.length===0)return new Map;let L=go(C),w=L.filter(Fg);if(w.length===0)return Ei(L);let R=new Map,M=Ng(w,f),_=[];for(let D of w)g.has(D.symbolId)?R.set(D.symbolId,g.get(D.symbolId)??[]):M.has(D.symbolId)?R.set(D.symbolId,M.get(D.symbolId)??[]):kg(D,m)?R.set(D.symbolId,[]):_.push(D);if(_.length===0)return cr(L,R,void 0);try{let D=l.calleesForDefinitions(_),P=v();b=ma(P,D);let k=cr(_,D.callees,d);for(let[V,le]of k)R.set(V,le);return cr(L,R,void 0)}catch(D){let P=v();return b=po(P,D),Ei(L)}},S=(C,L)=>{let w=go(C),R=go(L),M=R.filter(Fg),_=new Map,D=Ng(M,f),P=[];for(let k of M)D.has(k.symbolId)?_.set(k.symbolId,D.get(k.symbolId)??[]):kg(k,m)?_.set(k.symbolId,[]):P.push(k);if(w.length===0&&P.length===0)return{references:Ii(w),callees:cr(R,_,void 0)};try{let k=s?s.referencesAndCalleesForDefinitions(w,P):uL(a,l,{referenceDefinitions:w,calleeDefinitions:P}),V=v();b=ma(V,k);let le=k.available?new Map(k.references):Qn(w,k.references);for(let[X,N]of k.callees)_.set(X,N);let G=cr(R,_,d);for(let[X,N]of G)g.set(X,N);return{references:le,callees:G}}catch(k){let V=v();return b=po(V,k),{references:Ii(w),callees:Ei(R)}}},x=C=>{if(C.length===0)return new Map;let L=go(C);try{let w=c.signaturesForDefinitions(L),R=v();return b=ma(R,w),_g(L,w.signatures)}catch(w){let R=v();return b=po(R,w),fa(L)}};return{language:"rust",availability:y,dispose:()=>{s?.dispose()},importUsage:C=>{let L=p.get(C);if(L)return L;try{let w=u.importUsage(C);return p.set(C,w),w}catch(w){let R=v();return b=po(R,w),[]}},referencesFor:C=>I([C]).get(C.symbolId)??[],referencesForDefinitions:I,referencesAndCalleesForDefinitions:S,calleesFor:C=>E([C]).get(C.symbolId)??[],calleesForDefinitions:E,signatureFor:C=>x([C]).get(C.symbolId)??null}}function ma(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 po(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 nL(e){if(e.usePersistentSession!==void 0)return e.usePersistentSession;let t=process.env.SCIP_RUST_SEMANTIC_SESSION;return t!=="0"&&t!=="false"}function iL(){return{importUsageFacts:()=>({usage:[],positions:[]})}}function go(e){return e.map(t=>{let n=t;return{...t,leaf:typeof n.leaf=="string"?n.leaf:Y(t.symbol),parentTypeName:n.parentTypeName??null,isFunctionLike:typeof n.isFunctionLike=="boolean"?n.isFunctionLike:_e(t.symbol),isTypeLike:n.isTypeLike??!1,kind:n.kind??null,documentation:n.documentation??null,enclosingSymbol:n.enclosingSymbol??null}})}function Fg(e){return e.isFunctionLike}function kg(e,t){if(!t)return!1;try{return t(e)}catch{return!1}}function Ng(e,t){if(!t||e.length===0)return new Map;try{return t(e)}catch{return new Map}}function rL(e,t){return{referencesForDefinitions:n=>aL(e,t,n)}}function oL(e,t){return{calleesForDefinitions:n=>lL(e,t,n)}}function sL(e,t){return{signaturesForDefinitions:n=>cL(e,t,n)}}function aL(e,t,n){let i=t(e);if(!i.available||!i.resolvedBinary)return{available:!1,resolvedBinary:i.resolvedBinary,reason:Wc(i),references:Ii(n)};let r=Kc();if(!Uc(r))return{available:!1,resolvedBinary:i.resolvedBinary,reason:`Rust semantic worker was not found at ${r}. Run npm run build before using built semantic Rust queries.`,references:Ii(n)};let o=ur(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,zc),s=pa(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),a=ur(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,qc),l=pa(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=fo(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!0}),u={projectRoot:e,rustAnalyzerBinary:i.resolvedBinary,definitions:[...n],requestTimeoutMs:o,...s>0?{referenceRetryTimeoutMs:s}:{},diagnosticsTimeoutMs:l,settleDelayMs:c,concurrency:a},d=Hc(process.execPath,[r],{cwd:e,input:JSON.stringify(u),encoding:"utf8",maxBuffer:50*1024*1024,windowsHide:!0,timeout:xi(n.length,jc(o,u.referenceRetryTimeoutMs),a)}),m=Vc(d.stdout);if(m)return{...Gc(m),resolvedBinary:i.resolvedBinary,references:Qn(n,new Map(m.references),new Set(m.incompleteReferenceSymbolIds??[]))};let f=d.error instanceof Error?d.error.message:d.stderr.trim()||`Rust semantic worker exited with status ${d.status??"unknown"}.`;return{available:!1,resolvedBinary:i.resolvedBinary,reason:f,references:Ii(n)}}function lL(e,t,n){let i=t(e);if(!i.available||!i.resolvedBinary)return{available:!1,resolvedBinary:i.resolvedBinary,reason:Wc(i),callees:Ei(n)};let r=Kc();if(!Uc(r))return{available:!1,resolvedBinary:i.resolvedBinary,reason:`Rust semantic worker was not found at ${r}. Run npm run build before using built semantic Rust queries.`,callees:Ei(n)};let o=ur(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,zc),s=ur(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,qc),a=pa(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),l=fo(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!0}),c={projectRoot:e,rustAnalyzerBinary:i.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:l,concurrency:s,includeReferences:!1,includeCallees:!0},u=Hc(process.execPath,[r],{cwd:e,input:JSON.stringify(c),encoding:"utf8",maxBuffer:50*1024*1024,windowsHide:!0,timeout:xi(n.length,o,s)}),d=Vc(u.stdout);if(d)return{...Gc(d),resolvedBinary:i.resolvedBinary,callees:cr(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:i.resolvedBinary,reason:m,callees:Ei(n)}}function cL(e,t,n){let i=t(e);if(!i.available||!i.resolvedBinary)return{available:!1,resolvedBinary:i.resolvedBinary,reason:Wc(i),signatures:fa(n)};let r=Kc();if(!Uc(r))return{available:!1,resolvedBinary:i.resolvedBinary,reason:`Rust semantic worker was not found at ${r}. Run npm run build before using built semantic Rust queries.`,signatures:fa(n)};let o=ur(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,zc),s=ur(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,qc),a=pa(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),l=fo(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!1,includeSignatures:!0}),c={projectRoot:e,rustAnalyzerBinary:i.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:l,concurrency:s,includeReferences:!1,includeCallees:!1,includeSignatures:!0},u=Hc(process.execPath,[r],{cwd:e,input:JSON.stringify(c),encoding:"utf8",maxBuffer:50*1024*1024,windowsHide:!0,timeout:xi(n.length,o,s)}),d=Vc(u.stdout);if(d)return{...Gc(d),resolvedBinary:i.resolvedBinary,signatures:_g(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:i.resolvedBinary,reason:m,signatures:fa(n)}}function uL(e,t,n){let i=n.referenceDefinitions.length>0?e.referencesForDefinitions(n.referenceDefinitions):{available:!0,references:Ii(n.referenceDefinitions)},r=n.calleeDefinitions.length>0?t.calleesForDefinitions(n.calleeDefinitions):{available:!0,callees:Ei(n.calleeDefinitions)},o={resolvedBinary:i.resolvedBinary??r.resolvedBinary,references:i.references,callees:r.callees};return i.available&&r.available?{available:!0,...o}:{available:!1,reason:(i.available?void 0:i.reason)??(r.available?void 0:r.reason)??"Rust semantic resolution was unavailable.",...o}}function Ii(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Ei(e){return new Map(e.map(t=>[t.symbolId,[]]))}function fa(e){return new Map(e.map(t=>[t.symbolId,null]))}function cr(e,t,n){let i=0,r=0;return B("rust.semantic.callees.complete-map",()=>{let o=new Map;for(let s of e){let a=t.get(s.symbolId)??[];a.length>0&&(i+=1),r+=a.length,o.set(s.symbolId,a.map(l=>({...l,symbol:n?n(l):l.symbol})))}return o},()=>({definitions:e.length,rows:i,callees:r,resolveSymbols:!!n}))}function _g(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function Kc(){return tL(new URL("./rust-semantic-worker.js",import.meta.url))}function Gc(e){return e.available?{available:!0}:{available:!1,reason:e.reason}}function Wc(e){return e.available?"rust-analyzer binary path is unavailable.":e.reason}function Vc(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 i={references:n.references,incompleteReferenceSymbolIds:Array.isArray(n.incompleteReferenceSymbolIds)?n.incompleteReferenceSymbolIds.filter(r=>typeof r=="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,...i}:{available:!1,reason:String(n.reason),...i}}catch{return null}}function ur(e,t){return Xn(e)??t}function pa(e,t){if(!e)return t;let n=Number(e);return Number.isInteger(n)&&n>=0?n:t}import{existsSync as dL}from"fs";import{deserializeSCIP as mL,SymbolRole as fL}from"@c4312/scip";var Jc=new WeakMap;function Og(e,t){let n=t.filter(pL);if(n.length===0)return new Map;let i=!1,r=0,o=0;return B("rust.scip-occurrence.callees",()=>{let s=yL(e);if(i=!!s,!s)return new Map;let a=new Map;for(let l of n){let c=gL(e,s,l);c!==null&&(a.set(l.symbolId,c),r+=1,o+=c.length)}return a},()=>({definitions:t.length,candidates:n.length,indexAvailable:i,resolvedDefinitions:r,resolvedCallees:o}))}function pL(e){return!(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||!e.isFunctionLike||e.leaf==="main"||Xe(e.symbol))}function gL(e,t,n){let i=te(e,n.relativePath);if(!i||i.language!=="rust")return null;let r=i.callables.find(c=>c.startLine!==n.startLine||c.endLine!==n.endLine?!1:c.name===n.leaf||n.leaf.endsWith(c.name)||c.name.endsWith(n.leaf));if(!r)return null;let o=i.callSites.filter(c=>c.line>=r.startLine&&c.line<=r.endLine);if(o.length===0)return null;let s=(t.occurrencesByFile.get(n.relativePath)??[]).filter(c=>c.line>=r.startLine&&c.line<=r.endLine&&c.callee.symbol!==n.symbol);if(s.some(c=>c.traitImplMember)||!hL(o,s))return null;let a=[],l=new Set;for(let c of s){let u=`${c.callee.symbol}\0${c.callee.file}\0${c.callee.line}`;l.has(u)||(l.add(u),a.push(c.callee))}return a}function hL(e,t){let n=Bg(e),i=Bg(t);if(n.size!==i.size)return!1;for(let[r,o]of n)if(i.get(r)!==o)return!1;return!0}function Bg(e){let t=new Map;for(let n of e){let i=n.calleeLeaf??n.leaf;if(!i)continue;let r=`${n.line}\0${i}`;t.set(r,(t.get(r)??0)+1)}return t}function yL(e){if(Jc.has(e))return Jc.get(e)??null;let t=bL(e);return Jc.set(e,t),t}function bL(e){if(!e.generation.indexPath||!dL(e.generation.indexPath))return null;try{let t=Ue(e).filter(o=>o.symbol.startsWith("rust-analyzer ")&&o.relativePath.endsWith(".rs")&&o.isFunctionLike),n=new Map(t.map(o=>[o.symbol,o])),i=mL(Vi(e.generation.indexPath,{inputKind:"SCIP occurrence-callee index",maxBytes:Wi})),r=new Map;for(let o of i.documents??[]){let s=o.relativePath;if(!s||!s.endsWith(".rs")||e.isIgnored(s))continue;let a=[];for(let l of o.occurrences??[]){if(!l.symbol||(l.symbolRoles&fL.Definition)!==0)continue;let c=n.get(l.symbol);if(!c)continue;let u=l.range?.[0];Number.isInteger(u)&&a.push({line:u,leaf:c.leaf,traitImplMember:Xe(c.symbol),callee:{symbol:c.symbol,file:c.relativePath,line:c.startLine,callsiteLine:u}})}r.set(s,a)}return{occurrencesByFile:r}}catch{return null}}var ga=class{sessions=new WeakMap;getOrCreate(t,n,i){let r=SL(t,n),o=this.sessions.get(t);o||(o=new Map,this.sessions.set(t,o));let s=o.get(r);if(s)return s.hits+=1,s.lastUsedAtMs=Date.now(),s.provider;let a=Date.now(),l=i();return o.set(r,{key:r,language:n,projectRoot:t.config.projectRoot,provider:l,createdAtMs:a,lastUsedAtMs:a,hits:1}),l}sessionsFor(t){return[...this.sessions.get(t)?.values()??[]]}clear(t){let n=this.sessions.get(t);if(n)for(let i of n.values())i.provider.dispose?.();this.sessions.delete(t)}};function SL(e,t){return`${e.config.projectRoot}:${t}-workspace`}import{randomUUID as zL}from"crypto";import{existsSync as qL}from"fs";import{dirname as KL}from"path";function $g(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 xe}from"perf_hooks";function Gt(e,t,n){if(e.has(t))return e.get(t);let i=n();return e.set(t,i),i}import Ug from"path";import{realpathSync as jg}from"fs";function vL(e,t){return e.getReferences().map(n=>{let i=n.getNode();return ha(i,t)})}function CL(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function zg(e,t,n,i){let r=[];for(let o of CL(e))for(let s of vL(o,i))s.file===t.relativePath&&s.line>=t.startLine&&s.line<=t.endLine||r.push(s);for(let o of n)r.push(o);return dr(r)}function qg(e,t,n,i){let r=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();mr(i,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||r.push({location:ha(a,i),node:a}))}return r}function ha(e,t){let n=e.getSourceFile(),i=n.getLineAndColumnAtPos(e.getStart());return{file:mr(t,n.getFilePath())??n.getBaseName(),line:i.line-1,column:i.column-1}}function Yc(e,t,n){let i=e.getSourceFile(),r=Qc(i,e),o=e.getText(),s=new RegExp(`\\b${Oe(o)}\\b`,"g"),a=i.getFullText().split(`
51
- `),l=[];for(let c=0;c<a.length;c++){if(c===r)continue;let u=a[c]??"";s.lastIndex=0;let d;for(;(d=s.exec(u))!==null;)l.push({file:t,line:c,column:d.index})}return dr(l.filter(c=>mr(n,Ug.join(n,c.file))===t))}function Xc(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 Qc(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function dr(e){let t=new Set,n=[];for(let i of e){let r=`${i.file}:${i.line}:${i.column}`;t.has(r)||(t.add(r),n.push(i))}return n}function mr(e,t){let n=e||process.cwd(),i=Hg(n,t);if(i)return i;try{return Hg(jg(n),jg(t))}catch{return null}}function Hg(e,t){let n=Ug.relative(e,t).replace(/\\/g,"/");return!n||n===".."||n.startsWith("../")?null:n}function Kg(e,t,n,i){let r=xL(t,i);return r.size===0?new Map:RL(e,n,r)}function xL(e,t){let n=new Map;for(let i of W(e,t)){let r=Y(i.symbol)??i.leaf;if(!r)continue;let o=n.get(r);o||(o=[],n.set(r,o)),o.push(i)}return n}function RL(e,t,n){let i=new Map,r=new Map;return t.forEachDescendant(o=>{for(let s of IL(e,o)){let a=n.get(s);if(!a)continue;let l=Qc(t,o);for(let c of a){if(l<c.startLine-1||l>c.endLine+1)continue;let u=Math.abs(l-c.startLine),d=r.get(c.symbolId);d!==void 0&&d<=u||(r.set(c.symbolId,u),i.set(c.symbolId,o))}}}),i}function IL(e,t){let n=[],i=r=>{r&&!n.includes(r)&&n.push(r)};if("getNameNode"in t&&typeof t.getNameNode=="function"){let r=t.getNameNode();i(r?.getText())}if("getName"in t&&typeof t.getName=="function"){let r=t.getName();i(r)}return e.Node.isIdentifier(t)&&i(t.getText()),n}var EL=Hn("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function Gg(e,t,n,i){let r=tu(e,t),o=Zc(r.get(i)??[],n);if(o)return o;let s=[];for(let a of r.values())for(let l of a)((l.leaf||Y(l.symbol)||"").includes(i)||l.symbol.includes(i))&&s.push(l);return Zc(s,n)}function eu(e,t,n,i){return Zc(tu(e,t).get(i)??[],n)}function Wg(e,t){let n=new Map;for(let[i,r]of tu(e,t)){let o=r[0];o&&n.set(i,o)}return n}function tu(e,t){return EL.get(e,t,()=>{let n=new Map;for(let i of W(e,t)){let r=i.leaf||Y(i.symbol);if(!r)continue;let o=n.get(r);o||(o=[],n.set(r,o)),o.push({...i,leaf:r})}for(let i of n.values())i.sort((r,o)=>r.startLine-o.startLine||r.endLine-o.endLine||r.symbolId-o.symbolId);return n})}function Zc(e,t){let n=null,i=Number.POSITIVE_INFINITY;for(let r of e){let o=Math.abs(r.startLine-t);(o<i||o===i&&n&&r.startLine<n.startLine)&&(n=r,i=o)}return n}import wL from"path";import{realpathSync as LL}from"fs";function Vg(e,t){let n=new Map,i=null,r=null,o=()=>(r??=me(e,{extensions:Os}),r),s=()=>(i??=B("typescript.source-file-index",()=>DL(e.config.projectRoot,t,o()),()=>({projects:t.length,indexedDocuments:o().length})),i),a=l=>Gn(l)?Gt(n,l,()=>{let c=Jg(e.config.projectRoot,l);if(!c)return null;for(let{project:u,sourceFiles:d}of s()){let m=d.get(c)??null;if(m||(m=u.addSourceFileAtPathIfExists(c)??null,m&&nu(d,m)),m)return{project:u,sourceFile:m}}return null}):null;return{sourceFile:l=>a(l)?.sourceFile??null,sourceFileMatch:a,indexedTypeScriptLikeDocuments:o}}function DL(e,t,n){let i=t.map(({project:r})=>{let o=new Map;for(let s of r.getSourceFiles())nu(o,s);return{project:r,sourceFiles:o}});for(let r of n){let o=Jg(e,r);if(o)for(let s of i){if(s.sourceFiles.has(o))break;let a=s.project.addSourceFileAtPathIfExists(o)??null;if(a){nu(s.sourceFiles,a);break}}}return i}function nu(e,t){let n=iu(t.getFilePath());e.set(n,t);try{e.set(iu(LL(n)),t)}catch(i){if(!ot(i))throw i}}function Jg(e,t){try{return iu(Rs(e,t,{inputKind:"indexed TypeScript source file"}).absolutePath)}catch(n){if(!ot(n))throw n;return null}}function iu(e){return wL.resolve(e)}function ru(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function Yg(e){let t=`${e.relativeDir}/src`;return[`${t}/index.ts`,`${t}/index.tsx`,`${t}/index.mts`,`${t}/index.cts`]}import{existsSync as ho}from"fs";import lt from"path";var ou=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function su(e,t){let i=t?lt.dirname(lt.join(e,t)):e,r=lt.resolve(e);for(;i.startsWith(r);){for(let s of ou){let a=lt.join(i,s);if(ho(a))return a}let o=lt.dirname(i);if(o===i)break;i=o}for(let o of ou){let s=lt.join(e,o);if(ho(s))return s}return null}function Xg(e){let t=e.config.projectRoot,n=new Set(ML(t,e.config.semantic?.typescript?.tsconfigs)),i=me(e,{includeIgnored:!1,extensions:Os});for(let r of i){let o=su(t,r);o&&n.add(lt.resolve(o))}if(n.size===0){let r=su(t);r&&n.add(lt.resolve(r))}return[...n].filter(r=>!Qg(t,r)).sort((r,o)=>r.localeCompare(o))}function ML(e,t=[]){let n=new Set;for(let i of t){let r=lt.isAbsolute(i)?i:lt.join(e,i);ho(r)&&n.add(lt.resolve(r))}for(let i of PL(e))for(let r of ou){let o=lt.join(i,r);ho(o)&&n.add(lt.resolve(o))}if(n.size===0){let i=su(e);i&&n.add(lt.resolve(i))}return[...n].filter(i=>!Qg(e,i)).sort((i,r)=>i.localeCompare(r))}function PL(e){let t=lt.join(e,"package.json");if(!ho(t))return[];let n;try{n=JSON.parse(gi(t,"project package manifest"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(r=>xf(e,r))}function Qg(e,t){let n=lt.relative(e,t).replace(/\\/g,"/");return n.startsWith("..")||n.includes("/node_modules/")||n.startsWith("node_modules/")||n.includes("/dist/")||n.startsWith("dist/")}function au(e,t){try{return e()}catch{t?.();return}}var TL=32;function rh(e,t){let n=B("typescript.provider.load",()=>$s());if(!n)return js("ts-morph is not installed");let i=B("typescript.provider.tsconfig-discovery",()=>Xg(e));if(i.length===0)return js("no tsconfig found");try{let r=B("typescript.provider.project-bundles",()=>Yf(n,i),()=>({tsconfigs:i.length}));return FL(e,n,r)}catch(r){return js(r instanceof Error?r.message:String(r),i[0],i)}}function FL(e,t,n,i={}){return B("typescript.provider.construct",()=>new lu(e,t,n),()=>({tsconfigs:n.length,reusedProjects:i.reusedProjects===!0}))}var lu=class{constructor(t,n,i){this.db=t;this.tsMorph=n;this.projects=i;this.workspacePackages=Cf(t.config.projectRoot),this.sourceFiles=Vg(t,i)}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 Gt(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let i=NL();return B("typescript.import-usage.file",()=>this.importUsageForSourceFile(t,n,i),()=>({file:t,...i}))})}referencesFor(t){return Gt(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);return this.referencesForDefinitionNode(t,n)})}referencesForDefinitions(t,n={}){let i=new Map,r=Ae(),o=[];for(let u of t){let d=this.referencesCache.get(u.symbolId);d?i.set(u.symbolId,d):o.push(u)}if(o.length===0)return i;let s=o,a=n.exact?[]:o.filter(u=>!eh(u));if(a.length>=TL){let u=this.referencesForDefinitionsBySymbolScan(a);if(u.incompleteFiles.size===0)for(let d of a){let m=u.references.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,m),i.set(d.symbolId,m)}if(s=o.filter(d=>eh(d)),s.length===0)return i}let l=new Map;for(let u of s){let d=l.get(u.relativePath);d?d.push(u):l.set(u.relativePath,[u])}let c=[];for(let[u,d]of l){let m=th();B("typescript.references-map.file",()=>{let f=this.definitionNodesForFile(u);for(let p of d){r&&(m.cacheMisses+=1);let g=f.get(p.symbolId)??null;r&&(g?m.nodeHits+=1:m.nodeMisses+=1);try{let h=this.referencesForDefinitionNode(p,g,r?m:void 0);this.referencesCache.set(p.symbolId,h),i.set(p.symbolId,h)}catch{m.preciseSearchFailures+=1,c.push(p)}}},()=>({relativePath:u,definitions:d.length,...nh(m)}))}if(c.length>0){let u=this.referencesForDefinitionsBySymbolScan(c);if(u.incompleteFiles.size===0)for(let d of c){let m=u.references.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,m),i.set(d.symbolId,m)}}return i}referenceFragmentsForFiles(t){let n=Ue(this.db).filter(s=>Gn(s.relativePath)),i=t.filter(s=>this.sourceFiles.sourceFile(s)!==null),r=this.referencesForDefinitionsBySymbolScan(n,i),o=i.filter(s=>!r.incompleteFiles.has(s));return Xf(n,r.references,o)}referencesForDefinitionsBySymbolScan(t,n){let i=Ae(),r=th(),o=new Map,s=new Set,a=new Set(t.map(c=>c.symbolId)),l=new Map(t.map(c=>[c.symbolId,c]));for(let c of t)o.set(c.symbolId,[]);return B("typescript.references-map.inverted-scan",()=>{let c=i?xe.now():0,u=n?this.packageImportReferencesForFiles(n):this.packageImportReferences();for(let b of t){let v=u.get(b.symbolId)??[];if(v.length>0){let y=o.get(b.symbolId)??[];y.push(...v),o.set(b.symbolId,y)}i&&(r.packageReferenceCount+=v.length)}i&&(r.packageRefsMs+=xe.now()-c);let d=new Map,m=new Map,f=this.hierarchyTargetsForDefinitions(t),p=new Set(t.map(b=>b.leaf).filter(Boolean)),g=i?xe.now():0;for(let b of n??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(b))continue;let v=this.sourceFiles.sourceFile(b);if(!v)continue;i&&(r.scanFiles+=1),this.addReferencesFromSourceFileScan(v,b,a,l,f,p,d,m,o,i?r:void 0)||s.add(b)}i&&(r.scanMs+=xe.now()-g);let h=i?xe.now():0;this.addHierarchyMemberReferences(t,o,i?r:void 0),i&&(r.hierarchyMs+=xe.now()-h);for(let[b,v]of o){let y=dr(v);o.set(b,y),i&&(r.referenceCount+=y.length)}},()=>({definitions:t.length,...nh(r)})),{references:o,incompleteFiles:s}}addReferencesFromSourceFileScan(t,n,i,r,o,s,a,l,c,u){let d=this.compilerCheckerForSourceFile(t),m=t.compilerNode,f=BL(t),p=!0,g=h=>{if(this.tsMorph.ts.isIdentifier(h)){if(u&&(u.identifiers+=1),!s.has(h.text)&&!f.has(h.text)){this.tsMorph.ts.forEachChild(h,g);return}let b=this.compilerReferenceSymbol(d,h,u,()=>{p=!1});if(b){let v;a.has(b)?v=a.get(b)??null:(v=this.referenceDefinitionFromCompilerSymbol(b),a.set(b,v)),u&&(v?u.targetHits+=1:u.targetMisses+=1);let y=Gt(l,b,()=>this.compilerSymbolKeys(b)),I=null,E=null,S=v&&i.has(v.symbolId)?r.get(v.symbolId):void 0;if(S&&(I=ya(m,h),!Zg(S,n,I))){let x=m.getLineAndCharacterOfPosition(h.getStart(m));E={file:n,line:x.line,column:x.character};let C=c.get(S.symbolId)??[];C.push(E),c.set(S.symbolId,C),u&&(u.requestedHits+=1)}for(let x of y)for(let C of o.get(x)?.values()??[]){if(I??=ya(m,h),Zg(C,n,I))continue;if(!E){let w=m.getLineAndCharacterOfPosition(h.getStart(m));E={file:n,line:w.line,column:w.character}}let L=c.get(C.symbolId)??[];L.push(E),c.set(C.symbolId,L),u&&(u.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(h,g)};return g(m),p}hierarchyTargetsForDefinitions(t){let n=new Map;for(let i of t){let r=this.nodeForDefinition(i),o=r?.compilerNode;if(!o||!this.isHierarchyMethod(o))continue;let s=o.parent;if(!this.isHierarchyContainer(s))continue;let a=this.compilerCheckerForSourceFile(r.getSourceFile()),l=a.getSymbolAtLocation(o.name);if(l)for(let c of this.hierarchyMemberSymbols(a,s,l))for(let u of this.compilerSymbolKeys(c)){let d=n.get(u)??new Map;d.set(i.symbolId,i),n.set(u,d)}}return n}hierarchyMemberSymbols(t,n,i){let r=new Set,o=new Set,s=(a,l,c)=>{if(!o.has(a)){o.add(a),r.add(l);for(let u of c){let d=u.getProperty(i.name);d&&s(u,d,this.hierarchyAncestorTypesForType(t,u))}}};return s(t.getTypeAtLocation(n),i,this.hierarchyAncestorTypes(t,n)),r}addHierarchyMemberReferences(t,n,i){let r=new Map;for(let o of t){let s=this.nodeForDefinition(o),a=s?.compilerNode;if(!a||!this.isHierarchyMethod(a))continue;let l=a.parent;if(!this.isHierarchyContainer(l))continue;let c=this.compilerCheckerForSourceFile(s.getSourceFile()),u=c.getSymbolAtLocation(a.name);if(!u)continue;let d=a.getSourceFile(),m=d.getLineAndCharacterOfPosition(a.name.getStart(d)),f={definition:o,location:{file:o.relativePath,line:m.line,column:m.character}},p=n.get(o.symbolId)??[];for(let h of this.hierarchyMemberSymbols(c,l,u))if(h!==u)for(let b of this.compilerSymbolLocations(h))p.push(b),i&&(i.hierarchyReferences+=1);n.set(o.symbolId,p);let g=this.hierarchyRootMemberSymbols(c,l,u);for(let h of g){let b=r.get(h)??new Map;b.set(o.symbolId,f),r.set(h,b)}i&&(i.hierarchyDefinitions+=1)}for(let o of r.values())if(!(o.size<2)){i&&(i.hierarchyFamilies+=1);for(let{definition:s}of o.values()){let a=n.get(s.symbolId)??[];for(let l of o.values())l.definition.symbolId!==s.symbolId&&(a.push(l.location),i&&(i.hierarchyReferences+=1));n.set(s.symbolId,a)}}}hierarchyRootMemberSymbols(t,n,i){let r=new Set,o=new Set,s=(a,l,c)=>{if(o.has(a))return;o.add(a);let u=!1;for(let d of c){let m=d.getProperty(i.name);m&&(u=!0,s(d,m,this.hierarchyAncestorTypesForType(t,d)))}if(!u)for(let d of this.compilerSymbolKeys(l))r.add(d)};return s(t.getTypeAtLocation(n),i,this.hierarchyAncestorTypes(t,n)),r}compilerSymbolKeys(t){return(t.declarations??[]).map(n=>{let i=n.getSourceFile();return`${i.fileName}\0${n.getStart(i)}\0${t.name}`})}compilerSymbolLocations(t){let n=[];for(let i of t.declarations??[]){let r=i.getSourceFile(),o=mr(this.db.config.projectRoot,r.fileName);if(!o)continue;let s=i.name,a=r.getLineAndCharacterOfPosition((s??i).getStart(r));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 i=new Set(this.hierarchyAncestorTypesForType(t,t.getTypeAtLocation(n)));for(let r of n.heritageClauses??[])for(let o of r.types)i.add(t.getTypeAtLocation(o));return[...i]}hierarchyAncestorTypesForType(t,n){let i=new Set(this.baseTypes(t,n));for(let r of n.getSymbol()?.declarations??[])if(this.isHierarchyContainer(r))for(let o of r.heritageClauses??[])for(let s of o.types)i.add(t.getTypeAtLocation(s));return[...i]}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,i,r){i&&(i.symbolLookups+=1);let o=au(()=>t.getSymbolAtLocation(n),r);if(o){if((o.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return o;try{return i&&(i.aliasResolutions+=1),t.getAliasedSymbol(o)}catch{return r?.(),o}}}calleesFor(t){if(this.calleesCache.has(t.symbolId))return this.calleesCache.get(t.symbolId)??[];let n=Gt(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath));if(n.incompleteSymbolIds.has(t.symbolId))throw new Error(`TypeScript callee evidence is incomplete for ${t.symbol}.`);let i=n.callees.get(t.symbolId)??[];return this.calleesCache.set(t.symbolId,i),i}calleesForDefinitions(t){let n=new Map,i=new Map;for(let r of t){if(this.calleesCache.has(r.symbolId)){n.set(r.symbolId,this.calleesCache.get(r.symbolId)??[]);continue}let o=i.get(r.relativePath);o?o.push(r):i.set(r.relativePath,[r])}for(let[r,o]of i){let s=this.fileCalleesCache.get(r),a=new Set(o.map(c=>c.symbolId)),l=s??this.calleeMapForFile(r,a);for(let c of o){if(l.incompleteSymbolIds.has(c.symbolId))continue;let u=l.callees.get(c.symbolId)??[];this.calleesCache.set(c.symbolId,u),n.set(c.symbolId,u)}}return n}referencesForDefinitionNode(t,n,i){let r=i?xe.now():0,o=this.packageImportReferencesForDefinition(t);if(i&&(i.packageRefsMs+=xe.now()-r,i.packageReferenceCount+=o.length),!n)return o;let s=i?xe.now():0,a=zg(n,t,o,this.db.config.projectRoot);return i&&(i.semanticRefsMs+=xe.now()-s,i.referenceCount+=a.length),a}signatureFor(t){return Gt(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 i=n.getType().getCallSignatures()[0];if(!i)return null;let r=i.getParameters().map(s=>{let a=s.getDeclarations()[0],l=a?s.getTypeAtLocation(a).getText(a):s.getValueDeclaration()?.getType().getText()??"unknown";return ih(l)}),o=i.getReturnType().getText(n);return`(${r.join(",")})=>${ih(o)}`})}importUsageForSourceFile(t,n,i){let r=[],o=new Map;for(let s of n.getImportDeclarations()){i.declarations+=1;let a=nc(this.db,t,s.getModuleSpecifierValue()),l=s.getImportClause()?.isTypeOnly()??!1;for(let c of cu(s)){i.entries+=1;let u=l?null:c.identifier?.getSymbol()?.compilerSymbol??null;!l&&c.identifier&&(u?i.bindingSymbols+=1:i.missingBindingSymbols+=1);let d={sourcePath:a,entry:c,typeOnlyDeclaration:l,bindingSymbol:u,references:[]};if(r.push(d),l||!c.localName||!u)continue;let m=o.get(c.localName);m?m.push(d):o.set(c.localName,[d])}}return o.size>0&&n.forEachDescendant(s=>{if(s.getKindName()!=="Identifier")return;let a=o.get(s.getText());if(!a||AL(s))return;i.scannedIdentifiers+=1;let l=s.getSymbol()?.compilerSymbol;if(i.symbolLookups+=1,!!l){for(let c of a)if(c.bindingSymbol===l){c.references.push({location:ha(s,this.db.config.projectRoot),node:s}),i.matchedReferences+=1;break}}}),r.map(s=>s.typeOnlyDeclaration?kL(t,s.sourcePath,s.entry):s.entry.identifier&&!s.bindingSymbol?(i.fallbackEntries+=1,this.valueImportUsageForEntry(t,s.sourcePath,s.entry)):this.valueImportUsageFromLocations(t,s.sourcePath,s.entry,s.references))}valueImportUsageForEntry(t,n,i){let r;try{r=i.identifier?i.identifier.findReferences():[]}catch{let s=i.identifier?Yc(i.identifier,t,this.db.config.projectRoot):[];return{importer:t,sourcePath:n,importedName:i.importedName,localName:i.localName,kind:i.kind,isTypeOnly:i.isTypeOnly,isUsed:i.isTypeOnly||s.length>0,isTypeUsed:i.isTypeOnly,isValueUsed:!i.isTypeOnly&&s.length>0,references:s}}let o=[];for(let s of r)for(let a of qg(s,t,i.identifier,this.db.config.projectRoot))o.push(a);return this.valueImportUsageFromLocations(t,n,i,o)}valueImportUsageFromLocations(t,n,i,r){let o=r.some(l=>!Xc(l.node)),s=r.some(l=>Xc(l.node)),a=i.isTypeOnly;return{importer:t,sourcePath:n,importedName:i.importedName,localName:i.localName,kind:i.kind,isTypeOnly:a,isUsed:a||r.length>0,isTypeUsed:a||s,isValueUsed:o,references:r.map(l=>l.location)}}packageImportReferencesForDefinition(t){return this.packageImportReferences().get(t.symbolId)??[]}packageImportReferencesForFiles(t){let n=new Map,i=new Set;for(let o of t){let s=this.sourceFiles.sourceFile(o);if(s)for(let a of s.getImportDeclarations()){let l=ru(this.workspacePackages,a.getModuleSpecifierValue());l&&i.add(l)}}if(i.size===0)return n;let r=this.packageExportsForNames(i);for(let o of t)this.addPackageImportReferencesForDocument(n,r,o);for(let[o,s]of n)n.set(o,dr(s));return n}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let t=new Map,n=this.packageExports();for(let i of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(t,n,i);for(let[i,r]of t)t.set(i,dr(r));return this.packageImportReferenceIndex=t,t}addPackageImportReferencesForDocument(t,n,i){if(this.db.isIgnored(i))return;let r=this.sourceFiles.sourceFileMatch(i);if(r)for(let o of r.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(t,n,i,o)}addPackageImportReferencesForDeclaration(t,n,i,r){let o=ru(this.workspacePackages,r.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of cu(r)){if(a.kind!=="named"||!a.identifier)continue;let l=s.get(a.importedName);if(!l||l.size===0)continue;let c=Yc(a.identifier,i,this.db.config.projectRoot);c.length>0&&HL(t,l,c)}}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 i of this.workspacePackages){if(!t.has(i.name))continue;let r=new Map;for(let o of Yg(i))this.collectPackageExports(i,o,r,new Set);r.size>0&&n.set(i.name,r)}return n}collectPackageExports(t,n,i,r){if(r.has(n))return;r.add(n);let o=this.sourceFiles.sourceFile(n);if(o)for(let s of o.getExportDeclarations()){let a=s.getModuleSpecifierValue(),l=a?nc(this.db,n,a):n;if(!l||!l.startsWith(`${t.relativeDir}/src/`))continue;let c=s.getNamedExports();if(c.length===0){if(s.isNamespaceExport())continue;this.collectPackageExports(t,l,i,r);continue}for(let u of c){let d=u.getNameNode().getText(),m=u.getAliasNode()?.getText()??d,f=this.indexedDefinitionByLeaf(l,d);if(!f)continue;let p=i.get(m);p||(p=new Set,i.set(m,p)),p.add(f.symbolId)}}}indexedDefinitionByLeaf(t,n){return Gt(this.indexedDefinitionLeafCache,t,()=>Wg(this.db,t)).get(n)??null}nodeForDefinition(t){return Gt(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return Gt(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?Kg(this.tsMorph,this.db,n,t):new Map})}referenceDefinitionFromCompilerSymbol(t){return this.definitionFromCompilerSymbol(t,void 0,!0)}definitionFromCompilerSymbol(t,n,i=!1){let r=t.name,o=n?xe.now():0,s=t.declarations??[];n&&(n.declarationsMs+=xe.now()-o,n.declarationChecks+=s.length);for(let a of s){let l=n?xe.now():0,c=a.getSourceFile(),u=mr(this.db.config.projectRoot,c.fileName),d=c.getLineAndCharacterOfPosition(a.getStart(c)).line;if(n&&(n.declarationLocationMs+=xe.now()-l),!u||this.db.isIgnored(u))continue;let m=n?xe.now():0,f=this.compilerDeclarationName(a),p=i?eu(this.db,u,d,r)??(f&&f!==r?eu(this.db,u,d,f):null):Gg(this.db,u,d,r);if(n&&(n.indexedLookupMs+=xe.now()-m),p)return{symbolId:p.symbolId,symbol:p.symbol,file:p.relativePath,line:p.startLine}}return null}compilerDeclarationName(t){let n=t.name;return n&&this.tsMorph.ts.isIdentifier(n)?n.text:null}calleeMapForFile(t,n){let i=Ae(),r=0,o=0,s=0,a=0,l=0,c=0,u=0,d=0,m=i?$L():void 0;return B("typescript.callee-map.file",()=>{let f=i?xe.now():0,p=this.sourceFiles.sourceFile(t);if(i&&(l=Math.round(xe.now()-f)),!p)return{callees:new Map,incompleteSymbolIds:new Set};let g=i?xe.now():0,h=W(this.db,t).sort((L,w)=>L.startLine-w.startLine||w.endLine-L.endLine);if(i&&(c=Math.round(xe.now()-g)),r=h.length,h.length===0)return{callees:new Map,incompleteSymbolIds:new Set};let b=new Map,v=new Set,y=i?xe.now():0,I=this.compilerCheckerForSourceFile(p),E=p.compilerNode;i&&(u=Math.round(xe.now()-y));let S=new Map,x=L=>{if(this.tsMorph.ts.isCallExpression(L)||this.tsMorph.ts.isNewExpression(L)){i&&(o+=1);let w=this.semanticCalleeForCallNode(I,E,h,L,S,n,v,m);w&&(i&&(s+=1),_L(b,w.callerId,w.target))}this.tsMorph.ts.forEachChild(L,x)},C=i?xe.now():0;x(E),i&&(d=Math.round(xe.now()-C));for(let[L,w]of b)b.set(L,UL(w));return a=b.size,{callees:b,incompleteSymbolIds:v}},()=>({relativePath:t,definitions:r,callNodes:o,resolvedCallees:s,outputRows:a,requestedDefinitions:n?.size??r,sourceFileLookupMs:l,definitionsLoadMs:c,checkerLookupMs:u,traversalMs:d,...m?jL(m):{}}))}semanticCalleeForCallNode(t,n,i,r,o,s,a,l){let c=l?xe.now():0,u=OL(i,ya(n,r));if(l&&(l.callerLookupMs+=xe.now()-c),!u)return null;if(s&&!s.has(u.symbolId))return l&&(l.skippedUnrequestedCallers+=1),null;let d=r.expression,m=this.compilerSymbolForExpression(t,d,l);m.incomplete&&a?.add(u.symbolId);let f=m.symbol,p=null;if(f)if(l&&(l.targetSymbolHits+=1),o.has(f))l&&(l.compilerSymbolCacheHits+=1),p=o.get(f)??null;else{l&&(l.compilerSymbolCacheMisses+=1);let g=l?xe.now():0;p=this.definitionFromCompilerSymbol(f,l),l&&(l.targetLookupMs+=xe.now()-g),o.set(f,p)}else l&&(l.targetMisses+=1);return p?{callerId:u.symbolId,target:{symbol:p.symbol,file:p.file,line:p.line,callsiteLine:ya(n,r)}}:null}compilerSymbolForExpression(t,n,i){let r=!1,o=i?xe.now():0,s=au(()=>t.getSymbolAtLocation(n),()=>{r=!0});if(i&&(i.expressionSymbolMs+=xe.now()-o),s)return{symbol:s,incomplete:!1};i&&(i.typeFallbacks+=1);let a=!1,l=i?xe.now():0,c=au(()=>t.getTypeAtLocation(n).getSymbol(),()=>{a=!0});return i&&(i.typeSymbolMs+=xe.now()-l),{symbol:c,incomplete:!c&&(r||a)}}compilerCheckerForSourceFile(t){let n=t.getProject(),i=this.compilerCheckerCache.get(n);return i||(i=n.getTypeChecker().compilerObject,this.compilerCheckerCache.set(n,i)),i}};function cu(e){let t=[],n=e.getDefaultImport();n&&t.push({identifier:n,importedName:"default",localName:n.getText(),kind:"default",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});let i=e.getNamespaceImport();i&&t.push({identifier:i,importedName:"*",localName:i.getText(),kind:"namespace",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});for(let r of e.getNamedImports()){let o=r.getNameNode(),a=r.getAliasNode()??(o.getKindName()==="Identifier"?o:null);t.push({identifier:a,importedName:o.getText(),localName:a?.getText()??o.getText(),kind:"named",isTypeOnly:r.isTypeOnly()||(e.getImportClause()?.isTypeOnly()??!1)})}return t.length===0&&t.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),t}function kL(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 NL(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function AL(e){for(let t=e;t;t=t.getParent())if(t.getKindName()==="ImportDeclaration")return!0;return!1}function _L(e,t,n){let i=e.get(t);i||(i=[],e.set(t,i)),i.push(n)}function BL(e){let t=new Set;for(let n of e.getImportDeclarations())for(let i of cu(n))i.localName&&t.add(i.localName);return t}function OL(e,t){let n=null;for(let i of e)t<i.startLine||t>i.endLine||(!n||i.startLine>=n.startLine)&&(n=i);return n}function ya(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line}function Zg(e,t,n){return t===e.relativePath&&n>=e.startLine&&n<=e.endLine}function eh(e){return e.symbol.includes("#")?Bt(e.symbol)==="type"&&e.relativePath.endsWith(".d.ts"):!1}function $L(){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 jL(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 th(){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 nh(e){return{...e,scanMs:Math.round(e.scanMs),packageRefsMs:Math.round(e.packageRefsMs),semanticRefsMs:Math.round(e.semanticRefsMs),hierarchyMs:Math.round(e.hierarchyMs)}}function HL(e,t,n){for(let i of t){let r=e.get(i)??[];r.push(...n),e.set(i,r)}}function UL(e){let t=new Set,n=[];for(let i of e){let r=`${i.symbol}|${i.file}|${i.line}|${i.callsiteLine??""}`;t.has(r)||(t.add(r),n.push(i))}return n}function ih(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var GL=12e4,WL=5;function lh(e,t,n={}){let i=new uu(e,n),r=null,o=null,s=process.env.CODEBASEIQ_SKIP_WATCH_SERVICE==="1",a=()=>(r??=rh(e,t),r),l=(d,m,f)=>{if(s)return f();try{return m(i.request(d))}catch{return s=!0,f()}},c=(d,m)=>l({kind:"references",definitions:[...d],...m?.exact?{exact:!0}:{}},f=>ah(f),()=>a().referencesForDefinitions?.(d,m)??new Map(d.map(f=>[f.symbolId,a().referencesFor(f)]))),u=d=>l({kind:"callees",definitions:[...d]},m=>ah(m),()=>a().calleesForDefinitions?.(d)??new Map(d.map(m=>[m.symbolId,a().calleesFor(m)])));return{language:"typescript",availability:()=>(o??=l({kind:"availability"},YL,()=>a().availability()),o),importUsage:d=>l({kind:"import-usage",file:d},m=>m,()=>a().importUsage(d)),referencesFor:d=>oh(c([d]),d,"reference"),referencesForDefinitions:c,referenceFragmentsForFiles:d=>l({kind:"reference-fragments",files:[...d]},m=>JL(m),()=>a().referenceFragmentsForFiles?.(d)??new Map),calleesFor:d=>oh(u([d]),d,"callee"),calleesForDefinitions:u,signatureFor:d=>l({kind:"signature",definition:d},XL,()=>a().signatureFor(d)),dispose:()=>r?.dispose?.()}}function oh(e,t,n){if(!e.has(t.symbolId))throw new Error(`TypeScript ${n} evidence is incomplete for ${t.symbol}.`);return e.get(t.symbolId)}var uu=class{constructor(t,n={}){this.db=t;this.runtime=n.runtime??ZL,this.timeoutMs=n.timeoutMs??QL(),this.mailboxLimits=n.mailboxLimits??{},this.cacheDir=KL(t.config.dbPath),this.projectRoot=Zm(t.config.projectRoot)}db;runtime;timeoutMs;cacheDir;projectRoot;mailboxLimits;request(t){let n=tf(this.cacheDir),i=gf(this.cacheDir),r=Vl(n.statePath);if(!sh(r,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,l=(this.runtime.monotonicNow??en)()+this.timeoutMs,c=uf(),u=Br("typescript-semantic-v4",{generation:o,profileEnvironment:c,request:t}),d=Or(u),m=Is(i,{mailboxVersion:Yi,operationKey:u,clientId:this.runtime.randomId(),enqueuedAtMs:s,deadlineAtMs:a,protocolVersion:Es,id:d,generation:o,profileEnvironment:c,request:t},{nowMs:s,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??en)()<=l;){if(qL(m.responsePath))return VL(Zt(m.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript semantic mailbox response"}),d,o,u);let f=Vl(n.statePath);if(!sh(f,this.projectRoot,this.runtime))throw new Error("TypeScript semantic service stopped while processing a request.");this.runtime.sleep(WL)}throw new Error(`TypeScript semantic service timed out after ${this.timeoutMs}ms.`)}};function sh(e,t,n){let i=e?.processIdentity?n.readProcessIdentity?.(e.pid):null;return e!==null&&e.projectRoot===t&&e.typescriptSemantic?.protocolVersion===Es&&n.isProcessAlive(e.pid)&&(!e.processIdentity||i!=null&&bs(e.processIdentity,i))}function VL(e,t,n,i){let r=JSON.parse(e);if(r.protocolVersion!==Es||r.id!==t||r.operationKey!==i||r.ok===!0&&r.generation!==n)throw new Error("TypeScript semantic service wrote an incompatible response.");if(r.ok===!0)return r.response;throw new Error(typeof r.error=="string"?r.error:"TypeScript semantic service request failed.")}function ah(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid numeric map.");return new Map(e)}function JL(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid string map.");return new Map(e)}function YL(e){let t=$g(e);if(!t)throw new Error("TypeScript semantic service wrote invalid availability.");return t}function XL(e){if(e!==null&&typeof e!="string")throw new Error("TypeScript semantic service wrote an invalid signature.");return e}function QL(){let e=Number(process.env.SCIP_TYPESCRIPT_SEMANTIC_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:GL}var ZL={now:Date.now,monotonicNow:en,randomId:zL,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:Gi,readProcessIdentity:Ji};var du=new ga;rf({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>du.clear(e)});of({name:"semantic-provider",close:e=>du.clear(e)});function wi(e,t){let n=Ge(t)??"typescript";return du.getOrCreate(e,n,()=>n==="rust"?Ag(e.config.projectRoot,{sourceImportUsageResolver:{importUsageFacts:i=>Qp(e,i)},calleeSymbolResolver:Xp(e),sourceZeroCalleeOracle:i=>eD(e,i),scipOccurrenceCalleeOracle:i=>Og(e,i)}):lh(e,t))}function Ge(e){return e?ye(e)==="rust"?"rust":Gn(e)?"typescript":null:"typescript"}function eD(e,t){let n=te(e,t.relativePath);if(!n||n.language!=="rust")return!1;let i=n.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine&&r.name===t.leaf)??n.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine);return i?!n.callSites.some(r=>r.line>=i.startLine&&r.line<=i.endLine):!1}var tD=/^[A-Za-z_][A-Za-z0-9_]*$/,ch=/\bDefault::default\b/g,nD=/^\.\.\s*Default::default\b/;function uh(e,t){let n=new Map,i=new Map;for(let r of t){let o=mu(e,r,i);o!==null&&n.set(r.symbolId,o)}return n}function mu(e,t,n=new Map){let i=rD(t.symbol);if(!i)return null;let r=Bs(e,[t.symbolId]);if(r.length===0)return null;let o=new RegExp(`(^|[^A-Za-z0-9_])${Oe(i)}::default\\b`,"g"),s=new RegExp(`(^|[^A-Za-z0-9_])${Oe(i)}\\s*$`),a=iD(e,t.symbolId),l=[];for(let c of r){let u=oD(e,c.relative_path,n);if(u===null)return null;let d=u.split(/\r?\n/),m=0,f=[],p=0;for(let g=c.chunk_start;g<=c.chunk_end&&g<d.length;g+=1){let b=d[g]??"",v=new Set;o.lastIndex=0;let y;for(;y=o.exec(b);)l.push({file:c.relative_path,line:g,column:y.index+y[1].length+i.length+2}),p+=1;for(let I=0;I<b.length;I+=1){let E=nD.exec(b.slice(I));if(E){if(a&&f.includes(m)){let x=I+E[0].lastIndexOf("default");l.push({file:c.relative_path,line:g,column:x}),v.add(x),p+=1}I+=E[0].length-1;continue}let S=b[I];if(S==="{"){let x=s.test(b.slice(0,I));m+=1,x&&f.push(m);continue}if(S==="}")for(m=Math.max(0,m-1);f.length>0&&f[f.length-1]>m;)f.pop()}for(ch.lastIndex=0;y=ch.exec(b);){let I=y.index+9;if(!v.has(I))return null}}if(p===0)return null}return la(l)}function iD(e,t){return e.get("SELECT 1 AS present FROM mentions WHERE symbol_id = ? AND role = 1 LIMIT 1",t)?.present===1}function rD(e){let t=/impl#\[([^\]]+)\]\[Default\]default\(\)\./.exec(e)?.[1]??null;return!t||!tD.test(t)?null:t}function oD(e,t,n){if(n.has(t))return n.get(t)??null;let i=e.get("SELECT text FROM documents WHERE relative_path = ?",t),r=typeof i?.text=="string"?i.text:sD(e,t);return n.set(t,r),r}function sD(e,t){try{return rt(e.config.projectRoot,t,{inputKind:"indexed Rust source file"})}catch(n){if(!ot(n))throw n;return null}}var ba=new WeakMap;function hh(e){ba.delete(e)}function yh(e){let t=ba.get(e);return{incompleteSymbolIds:new Set(t?.incompleteSymbolIds),unavailableSymbolIds:new Set(t?.unavailableSymbolIds)}}function gu(e,t){if(t.incompleteSymbolIds.size===0&&t.unavailableSymbolIds.size===0)return;let n=ba.get(e)??{incompleteSymbolIds:new Set,unavailableSymbolIds:new Set};for(let i of t.incompleteSymbolIds)n.incompleteSymbolIds.add(i);for(let i of t.unavailableSymbolIds)n.unavailableSymbolIds.add(i);ba.set(e,n)}var aD="typescript-import-usage-v1",lD="typescript-signatures-v1",fu=Fe("semantic-prefetched-callees",{clearGroups:["whole-project","source-file","semantic-provider"]}),dh=$r({kind:"semantic-import-usage",invalidation:Ye("semantic-import-usage"),serialize:e=>JSON.stringify(e),deserialize:Lh}),mh=$r({kind:"semantic-signatures",invalidation:Ye("semantic-signatures"),serialize:e=>JSON.stringify(e),deserialize:hD}),fh=Ct({kind:"typescript-import-usage",invalidation:Ye("typescript-import-usage"),serialize:e=>JSON.stringify(e),deserialize:Lh}),ph=Ct({kind:"typescript-signatures",invalidation:Ye("typescript-signatures"),serialize:e=>JSON.stringify(e),deserialize:yD});function Ot(e){let t=new Map,n=new Set;return{capability:(i,r)=>Dh(e,i,r),importUsage:i=>uD(e,i),references:i=>vh(e,i),materializeReferences:(i,r)=>xh(e,i,t,n,r),callerMap:i=>dD(e,i,t,n),calleeMap:i=>Ih(e,i),signature:i=>pD(e,i)}}function cD(e,t){if(t.size===0)return;let n=fu.get(e,()=>new Map);for(let[i,r]of t)n.set(i,[...r])}function bh(e,t){if(!fu.has(e))return{hits:[],misses:[...t]};let n=fu.get(e,()=>new Map),i=[],r=[];for(let o of t)n.has(o.symbolId)?i.push({definition:o,callees:n.get(o.symbolId)??[]}):r.push(o);return{hits:i,misses:r}}function bo(e,t){return Ot(e).importUsage(t)}function uD(e,t){if(Ge(t)==="typescript"){let o="fallback",s=0,a=0,l=0,c=0;return B("typescript.import-usage.materialize",()=>{let u=qr(e,t,aD);if(u?.key){s=1;let m=fh.read(e,t,u.key);if(m)return o="hit",a=1,m;l=1;let f=wn(e,t);if(!f)return o="unavailable",[];let p=f.importUsage(t);return fh.write(e,t,u.key,p),o="computed",p}c=1;let d=wn(e,t);return d?(o="direct-fallback",d.importUsage(t)):(o="unavailable",[])},()=>({state:o,eligible:s,cacheHits:a,cacheMisses:l,fallbacks:c}))}let n=wh(e,"semantic-import-usage",t);if(n){let o=dh.read(e,t,n);if(o)return o}let i=wn(e,t);if(!i)return[];let r=i.importUsage(t);return n&&dh.write(e,t,n,r),r}function Sh(e,t){return Ot(e).references(t)}function vh(e,t){let n=mu(e,t);if(n)return n;let i=tg(e,t);if(i)return i;let r=wn(e,t.relativePath);return r?r.referencesFor(t):[]}function Ch(e,t){let n=Ln(e,t),i=n.incompleteSymbolIds.size+n.unavailableSymbolIds.size;if(i>0)throw new Error(`Exact semantic caller evidence is incomplete for ${i} definition(s).`);return n.callers}function Ln(e,t,n=i=>wi(e,i)){let i=new Map,r=new Set,o=new Set,s=new Map;for(let l of t){let c=Ge(l.relativePath);if(!c)continue;let u;try{u=n(l.relativePath)}catch{o.add(l.symbolId);continue}if(!u.availability().available){o.add(l.symbolId);continue}if(c==="typescript"){let d=s.get(u)??[];d.push(l),s.set(u,d);continue}pu(e,i,l,vh(e,l))}for(let[l,c]of s){let u=oc(e,c,n),d=u?.references??(l.referencesForDefinitions?l.referencesForDefinitions(c,{exact:!0}):new Map(c.map(m=>[m.symbolId,l.referencesFor(m)])));!u&&Ae()&&rc(e,c,d,n);for(let m of c){if(!d.has(m.symbolId)){r.add(m.symbolId);continue}pu(e,i,m,d.get(m.symbolId)??[])}}let a={callers:i,incompleteSymbolIds:r,unavailableSymbolIds:o};return gu(e,a),a}function dD(e,t,n=new Map,i=new Set){let r=new Map,o=xh(e,t,n,i),s=0;return B("semantic.callers.from-references",()=>{for(let a of t)s+=pu(e,r,a,n.get(a.symbolId)??[])},()=>({definitions:t.length,materialized:o.definitions,inMemoryHits:o.inMemoryHits,incompleteInMemoryHits:o.incompleteInMemoryHits,resultRows:r.size,callerFiles:s})),r}function xh(e,t,n,i,r={}){let o=Cn(e),s=[],a=[],l=[],c=0,u=0,d=0,m=0,f=0,p=0,g=0,h=0,b=0,v=0,y=0,I=0,E=[],S=new Map,x=t.filter(L=>Ge(L.relativePath)==="typescript"&&!n.has(L.symbolId)&&!i.has(L.symbolId)),C=oc(e,x,L=>wi(e,L));if(C){b=x.length,v=C.cacheHits,y=C.cacheMisses,I=C.computedFiles;for(let L of x)n.set(L.symbolId,C.references.get(L.symbolId)??[])}if(B("semantic.references.cache-scan",()=>{for(let[L,w]of oa(t)){let R=[];for(let D of w)n.has(D.symbolId)?u+=1:i.has(D.symbolId)?h+=1:R.push(D);if(R.length===0){g+=1;continue}let M=mD(e,o,L);if(!M){for(let D of R)Ge(D.relativePath)||(c+=1),l.push(D);continue}p+=1;let _=Sf(e,L,M);for(let D of R){let P=_.get(D.symbol)??null;if(P!==null){let k=fD(P);if(k){d+=1,n.set(D.symbolId,k);continue}m+=1}a.push({definition:D,cacheFingerprint:M})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:c,cacheHits:d,parseFailures:m,misses:a.length,unkeyed:l.length,inMemoryHits:u,incompleteInMemoryHits:h,fullyInMemoryFiles:g,cacheReadFiles:p})),a.length>0||l.length>0){E=[...l,...a.map(L=>L.definition)],S=B("semantic.references.compute-misses",()=>{let L=Sa(e,E,r);return f=L.size,L},()=>({definitions:E.length,misses:a.length,unkeyed:l.length,rows:f}));for(let L of E)S.has(L.symbolId)?(n.set(L.symbolId,S.get(L.symbolId)??[]),i.delete(L.symbolId)):i.add(L.symbolId);for(let{definition:L,cacheFingerprint:w}of a)S.has(L.symbolId)&&Dh(e,"semantic-references",L.relativePath).available&&s.push({relativePath:L.relativePath,symbol:L.symbol,projectFingerprint:w,payload:JSON.stringify(S.get(L.symbolId)??[])})}return s.length>0&&B("semantic.references.cache-write",()=>vf(e,s),()=>({entries:s.length})),S.size>0&&rc(e,E,S,L=>wi(e,L)),{definitions:t.length,inMemoryHits:u,incompleteInMemoryHits:h,cacheHits:d,misses:a.length,unkeyed:l.length,skippedUnsupportedLanguage:c,parseFailures:m,computed:f,incomplete:i.size,cacheWrites:s.length,fragmentDefinitions:b,fragmentCacheHits:v,fragmentCacheMisses:y,fragmentComputedFiles:I}}function mD(e,t,n){if(!t)return null;let i=Ge(n);return i==="typescript"?zt(JSON.stringify({kind:"semantic-references",language:i,schema:"typescript-references-v2-incomplete-scan",projectFingerprint:t})):i==="rust"?zt(JSON.stringify({kind:"semantic-references",language:i,engine:Ri(e.config.projectRoot),projectFingerprint:t})):null}function Sa(e,t,n={}){let i=Ae(),r=new Map,o=0,s=0,a=0,l=0,c=0,u=0,d=0,m=0,f=0;return B("semantic.references.provider-loop",()=>{let p=uh(e,t),g=eg(e,t),h=new Map,b=n.prefetchCallees?new Map:null,v=[];for(let I of t){let E,S=()=>(E??=wn(e,I.relativePath),E);if(b){let w=S();if(w?.referencesAndCalleesForDefinitions){let R=b.get(w);R?R.push(I):b.set(w,[I]),f+=1}}let x=p.get(I.symbolId);if(x){a+=1,l+=x.length,yo(r,I.symbolId,x,i,w=>{d+=1,m+=w});continue}let C=g.get(I.symbolId);if(C){c+=1,u+=C.length,yo(r,I.symbolId,C,i,w=>{d+=1,m+=w});continue}let L=S();if(!L){i&&(s+=1);continue}if(i&&(o+=1),L.referencesForDefinitions){let w=h.get(L);w?w.push(I):h.set(L,[I])}else v.push({provider:L,definition:I})}let y=new Set;if(b)for(let[I,E]of b){if(!I.referencesAndCalleesForDefinitions)continue;let S=h.get(I)??[],x=I.referencesAndCalleesForDefinitions(S,E);y.add(I),cD(e,x.callees);for(let C of S){if(!x.references.has(C.symbolId))continue;let L=x.references.get(C.symbolId)??[];yo(r,C.symbolId,L,i,w=>{d+=1,m+=w})}}for(let[I,E]of h){if(y.has(I))continue;let S=I.referencesForDefinitions(E);for(let x of E){if(!S.has(x.symbolId))continue;let C=S.get(x.symbolId)??[];yo(r,x.symbolId,C,i,L=>{d+=1,m+=L})}}for(let{provider:I,definition:E}of v){let S=I.referencesFor(E);yo(r,E.symbolId,S,i,x=>{d+=1,m+=x})}return r},()=>({definitions:t.length,providerHits:o,providerMisses:s,rustDefaultFastPathRows:a,rustDefaultFastPathReferences:l,rustScipOccurrenceFastPathRows:c,rustScipOccurrenceFastPathReferences:u,prefetchCalleeDefinitions:f,definitionsWithReferences:d,referenceCount:m,rows:r.size}))}function va(e,t,n={}){let i=Sa(e,t,n),r=Rh(e,t,i);return gu(e,r),{rows:i,...r}}function yo(e,t,n,i,r){e.set(t,n),i&&n.length>0&&r(n.length)}function pu(e,t,n,i){let r=0;for(let o of i){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&&(r+=1)}return r}function fD(e){try{return JSON.parse(e)}catch{return null}}function Ca(e,t,n){let i=Ih(e,t,n),r=Rh(e,t,i,n);return gu(e,r),{rows:i,...r}}function Rh(e,t,n,i){let r=new Set,o=new Set;for(let s of t)if(!(n.has(s.symbolId)||!Ge(s.relativePath)))try{(i?i(s.relativePath):wi(e,s.relativePath)).availability().available?r.add(s.symbolId):o.add(s.symbolId)}catch{o.add(s.symbolId)}return{incompleteSymbolIds:r,unavailableSymbolIds:o}}function Ih(e,t,n){let i=Ae(),r=new Map,o=0,s=0,a=0,l=0;return B("semantic.callees.provider-loop",()=>{let c=new Map,u=[];for(let d of t){let m=n?n(d.relativePath):wn(e,d.relativePath);if(m&&!m.availability().available){i&&(s+=1);continue}if(!m){i&&(s+=1);continue}i&&(o+=1);let f=d;if(m.calleesForDefinitions){let p=c.get(m);p?p.push(f):c.set(m,[f])}else u.push({provider:m,definition:f})}for(let[d,m]of c){let f=d.calleesForDefinitions(m);for(let p of m){if(!f.has(p.symbolId))continue;let g=f.get(p.symbolId)??[];gh(r,p.symbolId,g,i,h=>{a+=1,l+=h})}}for(let{provider:d,definition:m}of u){let f=d.calleesFor(m);gh(r,m.symbolId,f,i,p=>{a+=1,l+=p})}return r},()=>({definitions:t.length,providerHits:o,providerMisses:s,definitionsWithCallees:a,calleeCount:l,rows:r.size}))}function gh(e,t,n,i,r){e.set(t,n),i&&n.length>0&&r(n.length)}function Eh(e,t){return Ot(e).signature(t)}function pD(e,t){if(Ge(t.relativePath)==="typescript"){let s="fallback",a=0,l=0,c=0,u=0;return B("typescript.signature.materialize",()=>{let d=qr(e,t.relativePath,lD);if(d?.key){a=1;let f=ph.read(e,t.relativePath,d.key)??{};if(Object.prototype.hasOwnProperty.call(f,t.symbol))return s="hit",l=1,f[t.symbol]??null;c=1;let p=wn(e,t.relativePath);if(!p)return s="unavailable",null;let g=p.signatureFor(t);return ph.write(e,t.relativePath,d.key,{...f,[t.symbol]:g}),s="computed",g}u=1;let m=wn(e,t.relativePath);return m?(s="direct-fallback",m.signatureFor(t)):(s="unavailable",null)},()=>({state:s,eligible:a,cacheHits:l,cacheMisses:c,fallbacks:u}))}let n=wh(e,"semantic-signatures",t.relativePath),i=gD(t);if(n){let s=mh.read(e,i,n);if(s)return s.signature}let r=wn(e,t.relativePath);if(!r)return null;let o=r.signatureFor(t);return n&&mh.write(e,i,n,{signature:o}),o}function wh(e,t,n){let i=Cn(e);if(!i)return null;let r=Ge(n);return r!=="rust"?null:zt(JSON.stringify({kind:t,language:r,engine:Ri(e.config.projectRoot),projectFingerprint:i}))}function gD(e){return`${e.relativePath}\0${e.symbol}`}function Lh(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:null}catch{return null}}function hD(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 yD(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 Dh(e,t,n){let i=Ge(n);if(!i)return{slot:t,language:"typescript",available:!1,reason:"semantic evidence is only available for TypeScript or Rust files"};try{return{slot:t,language:i,...wi(e,n).availability()}}catch(r){return{slot:t,language:i,available:!1,reason:r instanceof Error?r.message:String(r)}}}function wn(e,t){if(!Ge(t))return null;let n=wi(e,t);return n.availability().available?n:null}var ge={references:Sh,referenceMap:Sa,referenceEvidenceMap:va,callerMap:(e,t)=>Ot(e).callerMap(t),calleeMap:hu,calleeEvidenceMap:Mh};function hu(e,t,n={}){return Mh(e,t,n).rows}function Mh(e,t,n={}){let i=Ae(),r=new Map,o=bh(e,t),s=[],a=[],l=0,c=0,u=0,d=0,m=0,f=0,p=0,g=new Set,h=new Set;for(let{definition:S,callees:x}of o.hits)m+=1,r.set(S.symbolId,x),x.length>0&&(f+=1,p+=x.length);let b=bD(e,o.hits);if(b.entries.length>0&&B("semantic.callees.prefetch-cache-write",()=>tc(e,b.entries),()=>({entries:b.entries.length,sourceMissing:b.sourceMissing,skippedUnsupportedLanguage:b.skippedUnsupportedLanguage})),B("semantic.callees.cache-scan",()=>{for(let[S,x]of oa(o.misses)){if(!Ge(S)){i&&(l+=x.length);continue}let C=se(e,S);if(!C){i&&(c+=x.length),a.push(...x);continue}let L=Nt(e,S,C),w=Ph(e,S);if(!w){a.push(...x);continue}let R=bf(e,S,L,w);for(let M of x){let _=R.get(M.symbol)??null;if(_!==null){let D=vD(_);if(D){i&&(u+=1),r.set(M.symbolId,D);continue}i&&(d+=1)}s.push({def:M,contentHash:L,depsDigest:w})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:l,sourceMissing:c,cacheHits:u,parseFailures:d,misses:s.length,unkeyed:a.length,inMemoryHits:m,inMemoryRows:f,inMemoryCalleeCount:p,resultRows:r.size})),s.length===0&&a.length===0)return{rows:r,incompleteSymbolIds:g,unavailableSymbolIds:h};let v=[...a,...s.map(S=>S.def)],y=0,I=B("semantic.callees.compute-misses",()=>{let S=Ca(e,v,n.resolveProvider);for(let x of S.incompleteSymbolIds)g.add(x);for(let x of S.unavailableSymbolIds)h.add(x);return y=S.rows.size,S.rows},()=>({definitions:v.length,misses:s.length,unkeyed:a.length,rows:y}));for(let[S,x]of I)r.set(S,x);let E=s.filter(S=>I.has(S.def.symbolId)&&Ot(e).capability("semantic-callees",S.def.relativePath).available).map(S=>({relativePath:S.def.relativePath,symbol:S.def.symbol,contentHash:S.contentHash,depsDigest:S.depsDigest,payload:JSON.stringify(I.get(S.def.symbolId)??[])}));return E.length>0?B("semantic.callees.cache-write",()=>tc(e,E),()=>({entries:E.length})):B("semantic.callees.cache-write-skip",()=>{},()=>({reason:"provider-unavailable",misses:s.length})),{rows:r,incompleteSymbolIds:g,unavailableSymbolIds:h}}function bD(e,t){let n=[],i=new Map,r=0,o=0;for(let{definition:s,callees:a}of t){if(!Ge(s.relativePath)){o+=1;continue}if(!i.has(s.relativePath)){let c=se(e,s.relativePath),u=c?Ph(e,s.relativePath):null;i.set(s.relativePath,c&&u?{contentHash:Nt(e,s.relativePath,c),depsDigest:u}:null)}let l=i.get(s.relativePath);if(!l){r+=1;continue}n.push({relativePath:s.relativePath,symbol:s.symbol,contentHash:l.contentHash,depsDigest:l.depsDigest,payload:JSON.stringify(a)})}return{entries:n,sourceMissing:r,skippedUnsupportedLanguage:o}}var SD="typescript-callees-v3-incomplete-scan";function Ph(e,t){let n=Ge(t);if(n==="typescript")return qr(e,t,SD)?.key??null;let i=xD(e,t);return n==="rust"?zt(JSON.stringify({kind:"semantic-callees",language:n,engine:Ri(e.config.projectRoot),positionMapping:"nearby-leaf-v2-callsite-line",depsDigest:i})):i}function vD(e){try{return JSON.parse(e)}catch{return null}}var CD=Hn("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function xD(e,t){return CD.get(e,t,()=>{let i=[...$e(e).get(t)??[]].sort().map(r=>`${r}:${Nt(e,r,se(e,r))}`);return zt(i.join("|"))})}function r3(e,t,n={}){let i=pe(e,t);if(!i)return[];let o=!_e(i.symbol)&&!e.isIgnored(i.relativePath)?[{relativePath:i.relativePath,line:i.startLine}]:[],s=Kn(e,i,{semantic:n.semantic,semanticEvidence:ge}).map(u=>({relativePath:u.file,line:u.line})),a=RD(e,i),l=new Set,c=[];for(let u of[...o,...s,...a]){let d=`${u.relativePath}:${u.line}`;l.has(d)||(l.add(d),c.push(u))}return c}function RD(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=ID(t.symbol);if(n.length===0)return[];let i=[];for(let r of me(e,{extensions:[".rb"],includeIgnored:!1})){let o=se(e,r);if(!o)continue;let s=o.split(`
52
- `);for(let a=0;a<s.length;a++){let l=s[a]??"";n.some(c=>new RegExp(`@${c}\\b|\\b${c}:`).test(l))&&i.push({relativePath:r,line:a})}}return i}function ID(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,""),i=n.split("_").filter(Boolean),r=new Set;return n&&r.add(n),i.length>=1&&r.add(i[i.length-1]),i.length>=2&&r.add(i.slice(-2).join("_")),[...r]}import{statSync as ED}from"fs";function Li(e){let t=e.get("SELECT COUNT(*) as c FROM documents").c,n=e.get("SELECT COUNT(*) as c FROM global_symbols").c,i=e.get("SELECT COUNT(*) as c FROM mentions WHERE role = 1").c,r=e.get("SELECT COUNT(*) as c FROM mentions WHERE role != 1").c;return{documents:t,symbols:n,definitions:i,references:r,...wD(e.generation.databasePath)}}function wD(e){try{let t=ED(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function LD(e,t){return cc(e).filter(n=>DD({pattern:t,relativePath:n})).map(n=>({relativePath:n}))}function DD(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 i=vn(n.pattern),r=vn(n.relativePath);if(!/[*?]/.test(i))return r.includes(i);let o=i.includes("/")?i:`**/${i}`;return xa(o.split("/"),r.split("/"))}function xa(e,t){if(e.length===0)return t.length===0;let[n,...i]=e;return n==="**"?xa(i,t)||t.length>0&&xa(e,t.slice(1)):t.length===0||!MD(n??"",t[0]??"")?!1:xa(i,t.slice(1))}function MD(e,t){let n="^";for(let i of e)i==="*"?n+="[^/]*":i==="?"?n+="[^/]":n+=PD(i);return n+="$",new RegExp(n).test(t)}function PD(e){return/[\\^$.*+?()[\]{}|]/.test(e)?`\\${e}`:e}function Fh(e,t,n){let i=[],r=[],o=new Map;for(let s of[...e].sort(n)){let a=s.channel??"default",l=t[a]??Number.MAX_SAFE_INTEGER,c=o.get(a)??0;if(c>=l){r.push(s);continue}i.push(s),o.set(a,c+1)}return{selected:i,omitted:r}}function Ra(e,t,n,i,r=!1){let o=[...e],s=[],a=new Set,l=0;for(;o.length>0&&s.length<t;){let c=o.filter(m=>l+m.evidenceCharacters<=n||r&&s.length===0);if(c.length===0)break;let u=c.filter(m=>m.roles.includes("location")||m.roles.includes("definition")).sort(i);c.sort((m,f)=>Th(f,a)-Th(m,a)||i(m,f));let d=u[0]??c[0];s.push(d),l+=d.evidenceCharacters;for(let m of kh(d))a.add(m.key);o.splice(o.indexOf(d),1)}return{selected:s,omitted:o.sort(i)}}function Th(e,t){let n=kh(e).reduce((o,s)=>o+(t.has(s.key)?0:s.weight),0),i=Math.max(0,8-e.priority)*20,r=Math.min(500,Math.ceil(e.evidenceCharacters/160));return n+i-r}function kh(e){return[...e.reasons.map(TD),...e.roles.map(t=>({key:`role:${t}`,weight:FD(t)})),{key:`file:${e.relativePath}`,weight:180},{key:`scope:${kD(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 TD(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 FD(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 kD(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}var Nh=64,Ah=12;function yu(e,t,n={}){if(t.length===0)throw new Error("The source search pattern must not be empty.");let i=n.context??6;if(!Number.isSafeInteger(i)||i<0)throw new RangeError(`context must be a non-negative safe integer; received ${i}`);let r=n.limit??12;if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`limit must be a positive safe integer; received ${r}`);let o=n.regexp?Cs(t,"source search pattern",n.ignoreCase?"iu":"u"):null,s=n.ignoreCase?t.toLocaleLowerCase():t,a=qs(e,{scope:n.scope}),l=[],c=[];for(let h of a.files){let b=h.relativePath,v=_D(h.text);if(v.length===0)continue;let y=h.freshness.semantic.state!=="stale"&&h.freshness.semantic.basis!=="no-compiler-document"?W(e,b):[],I=te(e,b)?.callables??[],E=0;for(let S=0;S<v.length;S+=1){let x=v[S]??"",C=x.endsWith("\r")?x.slice(0,-1):x;if(!(o?o.test(C):(n.ignoreCase?C.toLocaleLowerCase():C).includes(s)))continue;E+=1;let w=Ke(y,S),R=ND(I,S),M=w&&!De(w.symbol)?w:null,_=M?.startLine??R?.startLine??w?.startLine??S,D=M?.endLine??R?.endLine??w?.endLine??S,P=no(e,b,S,_,D);l.push({relativePath:b,focusLine:S,ownerSymbol:M?.symbol??null,ownerShort:M?A(M.symbol):R?.name??(w?A(w.symbol):null),ownerStartLine:P.startLine,ownerEndLine:P.endLine,fileKind:J(b),freshness:h.freshness})}E>0&&c.push({relativePath:b,matchingLines:E,returnedMatches:0,freshness:h.freshness})}l.sort(Bh);let u=l.length>Nh?_h(l,Nh):l,d=r===Number.MAX_SAFE_INTEGER?l:n.ranking?_h(l,r):l.slice(0,r),m=new Map(a.files.map(h=>[h.relativePath,h.text])),f=d.flatMap(h=>{let b=m.get(h.relativePath),v=b===void 0?null:AD(h.relativePath,b,h.focusLine,i);return v?[{...v,...h}]:[]}),p=new Map;for(let h of f)p.set(h.relativePath,(p.get(h.relativePath)??0)+1);for(let h of c)h.returnedMatches=p.get(h.relativePath)??0;let g=BD(c);return{pattern:t,mode:n.regexp?"regexp":"literal",identities:l,...u.length<l.length?{identityManifest:u}:{},identityCoverage:{mode:u.length===l.length?"complete":"bounded",returned:u.length,total:l.length,omitted:l.length-u.length},matches:f,matchingLines:l.length,matchingFiles:c.length,omittedMatches:Math.max(0,l.length-f.length),fileCoverage:c,scopeHints:g.slice(0,Ah),omittedScopeHints:Math.max(0,g.length-Ah),scannedFiles:a.files.length,textCoverage:{basis:"current-project-text-files",candidateFiles:a.candidateFiles,scannedTextFiles:a.files.length,scannedBytes:a.scannedBytes,skippedBinaryPaths:a.skippedBinaryPaths,skippedUnreadablePaths:a.skippedUnreadablePaths,skippedOversizedPaths:a.skippedOversizedPaths,semanticFiles:{aligned:a.files.filter(h=>h.freshness.semantic.state==="aligned").length,stale:a.files.filter(h=>h.freshness.semantic.state==="stale").length,unavailable:a.files.filter(h=>h.freshness.semantic.state==="unavailable").length}}}}function ND(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,i)=>n.endLine-n.startLine-(i.endLine-i.startLine)||n.startLine-i.startLine)[0]??null}function AD(e,t,n,i){let r=t.split(`
50
+ `);return{symbol:`${o.relativePath}:${n}-${i}`,shortName:`${o.relativePath}:${n}-${i}`,relativePath:o.relativePath,startLine:c,endLine:u,language:s?.language??wc(o.relativePath),source:d,freshness:o.freshness,...no(o.freshness)?{bindingClosure:tr(e,o.relativePath,c,u)}:{}}}function no(e){return!!(e&&e.semantic.state!=="stale"&&e.semantic.basis!=="no-compiler-document")}function wc(e){switch(_p(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 ra(e){let t=new Map;for(let n of e){let i=t.get(n.relativePath)??[];i.push(n),t.set(n.relativePath,i)}return t}function Vp(e){let t=new Map,n=zE(e),i=new Map;return r=>{let o=UE(r),s=i.get(o);if(s!==void 0)return s;if(!n.has(r.file))return i.set(o,r.symbol),r.symbol;let a=t.get(r.file);a||(a=qE(W(e,r.file)),t.set(r.file,a));let l=KE(a,r);return i.set(o,l),l}}function UE(e){return`${e.file}\0${e.symbol}\0${e.line}`}function zE(e){return new Set(e.all("SELECT relative_path FROM documents").map(t=>t.relative_path))}function qE(e){let t=new Map,n=new Map;for(let i of e){let r=t.get(i.leaf);r?r.push(i):t.set(i.leaf,[i]);let o=n.get(i.startLine);o?o.push(i):n.set(i.startLine,[i])}return{definitions:e,byLeaf:t,byStartLine:n}}function KE(e,t){if(e.definitions.length===0)return t.symbol;let n=VE(t.symbol),i=GE(e.byLeaf,n),r=WE(i,t.line);if(r)return r.symbol;let o=e.byStartLine.get(t.line)??[];return o.length===1?o[0].symbol:t.symbol}function GE(e,t){let n=[],i=new Set;for(let r of t)for(let o of e.get(r)??[])i.has(o.symbolId)||(i.add(o.symbolId),n.push(o));return n}function WE(e,t){let n=null;for(let i of e)if(!(i.startLine>t||i.endLine<t)){if(i.startLine===t)return i;(!n||i.endLine-i.startLine<n.endLine-n.startLine)&&(n=i)}return n}function VE(e){let t=new Set([e]),i=e.split(/::|\.|#/).filter(Boolean).at(-1);return i&&t.add(i),t}function Jp(e,t){let i=Ce(e,t).map(r=>YE(t,r));return{usage:i,positions:XE(e,t,i)}}function Yp(e,t){return{importUsage(n){let i=e.importUsageFacts(n);if(!t||i.positions.length===0)return i.usage;let r=t.importDefinitionsForFile(n,i.positions);return r.available?JE(i.usage,r.sourcePaths):i.usage}}}function JE(e,t){return e.map((n,i)=>{let r=t.get(String(i));return r?{...n,sourcePath:r}:n})}function YE(e,t){let n=t.isTypeOnly===!0,i=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:i,isTypeUsed:n,isValueUsed:t.kind==="side-effect"||!n&&t.used,references:[]}}function XE(e,t,n){let i=ae(e,t);if(!i)return[];let r=QE(i.rootNode),o=new Map;for(let a of r){let l=o.get(Dc(a.importedName,a.localName));l?l.push(a.position):o.set(Dc(a.importedName,a.localName),[a.position])}let s=[];return n.forEach((a,l)=>{let c=o.get(Dc(a.importedName,a.localName??a.importedName))?.shift();c&&s.push({...c,id:String(l),file:t})}),s}function QE(e){let t=[];for(let n of e.descendantsOfType("use_declaration")){let i=n.namedChildren.find(r=>r.type!=="visibility_modifier");i&&t.push(...oa(i,""))}return t.filter(n=>n.importedName!=="*")}function oa(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":return[{importedName:e.text,localName:e.text,position:Lc(e,e.text)}];case"scoped_identifier":{let n=e.text.split("::").pop()??e.text;return[{importedName:n,localName:n,position:Lc(e,n)}]}case"scoped_use_list":{let n=e.namedChild(0),i=e.namedChild(1);if(!n||!i)return[];let r=If(t,n.text);return i.namedChildren.flatMap(o=>oa(o,r))}case"use_list":return e.namedChildren.flatMap(n=>oa(n,t));case"use_as_clause":{let n=e.namedChild(0),i=e.namedChild(1);return!n||!i?[]:oa(n,t).map(r=>({...r,localName:i.text}))}case"use_wildcard":{let n=e.namedChild(0),i="*";return[{importedName:i,localName:i,position:Lc(n??e,i)}]}default:return[]}}function Lc(e,t){let n=Math.max(0,e.text.lastIndexOf(t));return{id:"",file:"",line:e.startPosition.row,column:e.startPosition.column+n+ZE(t)}}function ZE(e){return Math.max(0,Math.min(e.length-1,1))}function Dc(e,t){return`${e}\0${t}`}import{spawnSync as $c}from"child_process";import{existsSync as jc}from"fs";import{fileURLToPath as Vw}from"url";function Xn(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function sa(e){let t=qf(zf,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 kw,mkdtempSync as Sg,rmSync as kc}from"fs";import{tmpdir as _c}from"os";import{join as Nc}from"path";import{fileURLToPath as co,pathToFileURL as Nw}from"url";import{SHARE_ENV as Aw,Worker as _w}from"worker_threads";function Qn(e,t,n=new Set){let i=new Map;for(let r of e)n.has(r.symbolId)||i.set(r.symbolId,t.get(r.symbolId)??[]);return i}function xi(e,t,n){let i=Xn(process.env.SCIP_RUST_SEMANTIC_BATCH_TIMEOUT_MS)??0;if(i>0)return i;let r=Math.max(1,Math.ceil(e/Math.max(1,n)));return Math.max(12e4,3e4+r*t)}import{spawn as fw}from"child_process";import{createHash as pw,randomUUID as gw}from"crypto";import{existsSync as dg,realpathSync as hw,rmSync as yw}from"fs";import{tmpdir as bw}from"os";import{resolve as sr}from"path";import{execFileSync as nw}from"child_process";import{realpathSync as aJ}from"fs";import{basename as cJ,dirname as uJ,join as dJ,relative as mJ,sep as fJ}from"path";import{fileURLToPath as gJ,pathToFileURL as hJ}from"url";function aa(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,i)=>{let r=n.file.localeCompare(i.file);return r!==0?r:n.line!==i.line?n.line-i.line:n.column-i.column})}var Xp=new WeakMap,ew="SCIP_RUST_SCIP_OCCURRENCE_REFERENCE_MODE";function Qp(e,t){let n=new Map,i=la(),r=t.filter(s=>eg(s,i));if(r.length===0)return n;let o=tg(e,r.map(s=>s.symbol));for(let s of r){let a=o.get(s.symbol);a&&n.set(s.symbolId,a)}return n}function Zp(e,t){return eg(t,la())?tg(e,[t.symbol]).get(t.symbol)??null:null}function eg(e,t="safe"){if(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||Xe(e.symbol)||/impl#\[[^\]]+\]\[Default\]default\(\)\.$/.test(e.symbol))return!1;if(t==="all")return!0;let n=Bt(e.symbol);if(n==="method")return!0;if(n!=="term")return!1;let i=zn(e.symbol);return"kind"in i?!1:!tw(i)}function tw(e){for(let t=0;t<e.descriptors.length-1;t+=1)if(e.descriptors[t]?.suffix==="type")return!0;return!1}function tg(e,t){let n=Xp.get(e);n||(n=new Map,Xp.set(e,n));let i=[...new Set(t)].filter(r=>!n.has(r));if(i.length>0){let r=Kf(e,i);for(let o of i){let s=r?.get(o);n.set(o,s?aa(s.filter(({relativePath:a})=>!e.isIgnored(a)).map(({relativePath:a,occurrence:l})=>({file:a,line:l.range[0],column:l.range[1]}))):null)}}return new Map(t.map(r=>[r,n.get(r)??null]))}function la(){return process.env[ew]==="all"?"all":"safe"}var ng=new Map;function Mc(e){let n=sa(e).resolvedBinary??null;return{engine:"rust-analyzer",resolvedBinary:n,version:n?iw(e,n):"unavailable"}}function Ri(e){return{...Mc(e),scipOccurrenceReferenceMode:la()}}function iw(e,t){let n=`${e}\0${t}`,i=ng.get(n);if(i)return i;let r;try{r=nw(t,["--version"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:2e3}).trim()}catch{r="unknown"}return ng.set(n,r),r}import{createHash as rw}from"crypto";var ow=new Set(["Cargo.lock","Cargo.toml","rust-project.json","rust-toolchain","rust-toolchain.toml"]);function ig(e){let t=lf(e,{includePath:sw});return rw("sha256").update(JSON.stringify(t)).digest("hex")}function sw(e){let t=e.replaceAll("\\","/"),n=t.split("/").at(-1)??t;return t.endsWith(".rs")||ow.has(n)?!0:t===".cargo/config"||t===".cargo/config.toml"||t.endsWith("/.cargo/config")||t.endsWith("/.cargo/config.toml")}import{createHash as aw}from"crypto";import{resolve as lw}from"path";var or=3;function Tc(e){return aw("sha256").update(bi({kind:"codebaseiq-durable-rust-mailbox",protocolVersion:or,sessionDir:lw(e)})).digest("hex")}function sg(e,t){return jn(e)?e.protocolVersion!==or?og(e.protocolVersion===void 0?"helper wrote a prior uncorrelated response protocol":`helper wrote unsupported response protocol ${String(e.protocolVersion)}`):e.mailboxVersion!==Vi||e.id!==t.requestId||e.operationKey!==t.operationKey||e.sessionIdentity!==t.sessionIdentity||e.deadlineAtMs!==t.deadlineAtMs?og("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"||!mw(e.errorCode)?Pc("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"||!cw(e.response,t.requestKind)?Pc("helper wrote an invalid success response"):{ok:!0,session:e.session,response:e.response}:Pc("helper wrote an invalid response object")}function cw(e,t){return!jn(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")):rg(e.references,uw)&&(e.incompleteReferenceSymbolIds===void 0||Array.isArray(e.incompleteReferenceSymbolIds)&&e.incompleteReferenceSymbolIds.every(n=>Number.isSafeInteger(n)))&&(e.callees===void 0||rg(e.callees,dw))&&(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 rg(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 uw(e){return jn(e)&&typeof e.file=="string"&&Pt(e.line)&&Pt(e.column)}function dw(e){return jn(e)&&typeof e.symbol=="string"&&typeof e.file=="string"&&Pt(e.line)&&(e.callsiteLine===void 0||Pt(e.callsiteLine))}function mw(e){return e==="unsupported-protocol"||e==="malformed-request"||e==="expired-request"||e==="handler-error"}function Pc(e){return{ok:!1,code:"malformed-response",error:e}}function og(e){return{ok:!1,code:"incompatible-response",error:e}}var Sw=5e3,mg=10,vw=3e4;function ag(e,t,n,i=hg){let r=i.engineIdentity(e),o={protocolVersion:or,projectRoot:i.canonicalProjectRoot(e),projectFingerprint:i.projectFingerprint(e),engine:{engine:r.engine,resolvedBinary:r.resolvedBinary,version:r.version},workerFingerprint:i.fileFingerprint(t),environment:fg(i.environment())};return{key:yg(bi(o)),...o}}function io(e,t,n,i){if(e.protocolVersion!==or||!n(e.pid))return!1;if(!e.processIdentity)return!0;let r=i?.(e.pid);return r!=null&&hs(e.processIdentity,r)}function Fc(e,t,n){let i;try{i=Gl(t,{maxBytes:pi,inputKind:"Rust semantic engine artifact"})}catch{i="missing"}let r=yg(bi({projectRoot:sr(e),serverPath:sr(t),serverFingerprint:i})).slice(0,20);return sr(n,`codebaseiq-rust-session-${r}`)}function lg(e){let t=e===void 0?Number.NaN:Number(e);return Number.isInteger(t)&&t>=0?t:0}function fg(e){return Object.fromEntries(Object.entries(e).filter(([t])=>gg(t)).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,n??null]))}function pg(e,t){let n=t.runtime??ww,i=t.identityRuntime??hg,r=Fc(e,t.serverPath,t.tempRoot??bw()),o=!1,s=(a,l)=>{if(o)throw new Error("Durable Rust semantic session was already disposed.");return xw(r,t.serverPath,t.semanticWorkerPath,a,l,n,t.mailboxLimits)};return{requestSemantic(a,l){let c=ag(e,t.semanticWorkerPath,a,i),{readinessDeadlineMs:u,...d}=a;return s({kind:"semantic",identityKey:c.key,workerEnvironment:ug(),request:{...d,referenceRetryTimeoutMs:Cw(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,a.referenceRetryTimeoutMs),settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:lg(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:l},l)},requestImportDefinitions(a,l){let c=ag(e,t.semanticWorkerPath,a,i),{readinessDeadlineMs:u,...d}=a;return s({kind:"import-definitions",identityKey:c.key,workerEnvironment:ug(),request:{...d,settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:lg(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:l},l)},shutdown(){o=!0}}}function Cw(e,t){return t!==void 0?t:e===void 0?vw:void 0}function xw(e,t,n,i,r,o,s={}){let a=o.now(),l=a+r,c=(o.monotonicNow??en)(),u=c+r,d=Ar("rust-semantic-v3",i),m=_r(d),f=uf(e),p=Tc(e),g=xs(f,{mailboxVersion:Vi,protocolVersion:or,id:m,operationKey:d,clientId:o.randomId(),enqueuedAtMs:a,deadlineAtMs:l,sessionIdentity:p,request:i},{nowMs:a,limits:s});for(cg(e,t,n,u,o);(o.monotonicNow??en)()<=u;){if(dg(g.responsePath)){let b=Rw(Zt(g.responsePath,{maxBytes:s.maxItemBytes??pi,inputKind:"durable Rust semantic mailbox response"}),{requestId:m,operationKey:d,sessionIdentity:p,deadlineAtMs:g.authoritativeDeadlineAtMs,requestKind:i.kind,nowMs:o.now()});if(!b.ok)throw new Error(b.error);return Ae()&&vs({type:"span",name:"rust.semantic.durable-session.request",durationMs:(o.monotonicNow??en)()-c,ok:!0,session:b.session,kind:i.kind}),b.response}let h=ro(e);(!h||!io(h,o.now(),o.isProcessAlive,o.readProcessIdentity))&&cg(e,t,n,u,o),o.sleep(mg)}throw new Error(`Durable Rust semantic session timed out after ${(r/1e3).toFixed(0)}s.`)}function cg(e,t,n,i,r){let o=ro(e);if(o&&io(o,r.now(),r.isProcessAlive,r.readProcessIdentity))return;yw(sr(e,"server.json"),{force:!0}),r.spawnServer(t,e,n);let s=r.monotonicNow??en,a=Math.min(i,s()+Sw);for(;s()<=a;){let l=ro(e);if(l&&io(l,r.now(),r.isProcessAlive,r.readProcessIdentity))return;r.sleep(mg)}throw new Error("Durable Rust semantic session helper did not become ready within 5s.")}function ro(e){try{let t=JSON.parse(Zt(sr(e,"server.json"),{maxBytes:Ym,inputKind:"durable Rust session state"}));if(typeof t.protocolVersion!="number"||t.sessionIdentity!==void 0&&(typeof t.sessionIdentity!="string"||t.sessionIdentity!==Tc(e))||typeof t.pid!="number"||typeof t.heartbeatAtMs!="number"||t.busyUntilMs!==void 0&&typeof t.busyUntilMs!="number"||t.mailbox!==void 0&&!Iw(t.mailbox))return null;let n=t.processIdentity===void 0?null:gs(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 Rw(e,t){try{return sg(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 Iw(e){if(!e||typeof e!="object")return!1;let t=e;return Pt(t.pending)&&Pt(t.inflight)&&Pt(t.responses)&&Pt(t.deadLetters)&&Pt(t.invalid)&&Pt(t.totalItems)&&typeof t.totalBytes=="number"&&Number.isFinite(t.totalBytes)&&t.totalBytes>=0&&(t.oldestPendingAt===void 0||Number.isFinite(Date.parse(t.oldestPendingAt)))}function ug(){return Object.fromEntries(Object.entries(process.env).filter(([e])=>Ew(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t??null]))}function gg(e){return e==="HOME"||e==="PATH"||e.startsWith("CARGO_")||e.startsWith("RA_")||e.startsWith("RUST")}function Ew(e){return gg(e)||e.startsWith("SCIP_RUST_")||e==="CODEBASEIQ_PROFILE"||e==="CODEBASEIQ_PROFILE_CACHE_STATE"||e==="CODEBASEIQ_PROFILE_COMMAND"||e==="CODEBASEIQ_PROFILE_OUT"||e==="CODEBASEIQ_PROFILE_RUN_ID"||e==="CODEBASEIQ_PROFILE_WORKLOAD_IDENTITY"||e==="CODEBASEIQ_PROFILE_WORKLOAD_IDENTITY_KIND"||e==="CODEBASEIQ_PROFILE_MIN_MS"}var hg={canonicalProjectRoot(e){try{return hw(e)}catch{return sr(e)}},projectFingerprint(e){return ig(e)},engineIdentity:Mc,fileFingerprint(e){return Gl(e,{maxBytes:pi,inputKind:"Rust semantic engine artifact"})},environment(){return fg(process.env)}},ww={now:Date.now,monotonicNow:en,randomId:gw,isProcessAlive:Gi,readProcessIdentity:Wi,spawnServer(e,t,n){if(!dg(e))throw new Error(`Durable Rust semantic session helper was not found at ${e}. Run npm run build first.`);fw(process.execPath,[e,t,n],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)}};function yg(e){return pw("sha256").update(e).digest("hex")}import{randomUUID as iY}from"crypto";import{readdirSync as Lw,rmSync as oY,writeFileSync as sY}from"fs";import{join as Dw}from"path";var Mw="rust-analyzer-owner-",Pw=".json",Tw=16*1024;async function bg(e,t){if(!e)return[];let n;try{n=Lw(e)}catch{return[]}let i=n.filter(s=>s.startsWith(Mw)&&s.endsWith(Pw)).map(s=>Dw(e,s)),r=[],o=[];for(let s of i){let a=Fw(s);a?o.push(a):r.push({reaped:!1,reason:"identity-unavailable",detail:`Rust analyzer ownership record ${s} could not be validated.`})}return r.push(...await Promise.all(o.map(s=>Gf(s,t)))),r}function Fw(e){try{let t=Zt(e,{maxBytes:Tw,inputKind:"rust-analyzer process ownership record"}),n=JSON.parse(t),i=gs(n.rootIdentity);return n.version!==1||!i||typeof n.ownsProcessGroup!="boolean"?null:{rootPid:i.pid,rootIdentity:i,ownsProcessGroup:n.ownsProcessGroup,knownMembers:new Map([[i.pid,i]])}}catch{return null}}var vg=15e3,Cg=8,Rg=5e3,Bw=64,Ow=96,Bc=class{constructor(t,n,i={}){this.projectRoot=t;this.status=n;this.opts=i;this.requester=i.requester??Hw(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:ao(t)};try{let i=this.requestSession(n.resolvedBinary,t,{includeReferences:!0});return{...oo(i),resolvedBinary:n.resolvedBinary,references:Qn(t,new Map(i.references),new Set(i.incompleteReferenceSymbolIds??[]))}}catch(i){return this.opts.fallbackReferenceResolver?.referencesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:i instanceof Error?i.message:String(i),references:ao(t)}}}calleesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:so(n),callees:lo(t)};try{let i=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!0});return{...oo(i),resolvedBinary:n.resolvedBinary,callees:Ac(t,new Map(i.callees??[]))}}catch(i){return this.opts.fallbackCalleeResolver?.calleesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:i instanceof Error?i.message:String(i),callees:lo(t)}}}referencesAndCalleesForDefinitions(t,n){let i=this.status(this.projectRoot);if(!i.available||!i.resolvedBinary)return{available:!1,resolvedBinary:i.resolvedBinary,reason:so(i),references:ao(t),callees:lo(n)};let r=[...t,...n];try{let o=this.requestSession(i.resolvedBinary,r,{includeReferences:t.length>0,includeCallees:n.length>0,referenceDefinitions:t,calleeDefinitions:n});return{...oo(o),resolvedBinary:i.resolvedBinary,references:Qn(t,new Map(o.references),new Set(o.incompleteReferenceSymbolIds??[])),callees:Ac(n,new Map(o.callees??[]))}}catch(o){return this.fallbackReferencesAndCallees(i,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:xg(t)};try{let i=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!1,includeSignatures:!0});return{...oo(i),resolvedBinary:n.resolvedBinary,signatures:Gw(t,new Map(i.signatures??[]))}}catch(i){return this.opts.fallbackSignatureResolver?.signaturesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:i instanceof Error?i.message:String(i),signatures:xg(t)}}}importDefinitionsForFile(t,n){let i=this.status(this.projectRoot);if(n.length===0)return i.available?{available:!0,resolvedBinary:i.resolvedBinary,sourcePaths:new Map}:{available:!1,reason:i.reason,resolvedBinary:i.resolvedBinary,sourcePaths:new Map};if(!i.available||!i.resolvedBinary)return{available:!1,resolvedBinary:i.resolvedBinary,reason:so(i),sourcePaths:new Map(n.map(r=>[r.id,null]))};try{let r=this.requestImportDefinitions(i.resolvedBinary,t,n);return{...oo(r),resolvedBinary:i.resolvedBinary,sourcePaths:new Map(r.sourcePaths)}}catch(r){return{available:!1,resolvedBinary:i.resolvedBinary,reason:r instanceof Error?r.message:String(r),sourcePaths:new Map(n.map(o=>[o.id,null]))}}}dispose(){this.requester.shutdown()}requestSession(t,n,i){let r=ca(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,vg),o=ua(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),s=ca(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Cg),a=ua(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(r,1e4)),l=i.referenceDefinitions?[...i.referenceDefinitions]:void 0,c=i.calleeDefinitions?[...i.calleeDefinitions]:void 0,u=i.signatureDefinitions?[...i.signatureDefinitions]:void 0,d=uo(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,...i}),m={projectRoot:this.projectRoot,rustAnalyzerBinary:t,definitions:[...n],...l?{referenceDefinitions:l}:{},...c?{calleeDefinitions:c}:{},...u?{signatureDefinitions:u}:{},requestTimeoutMs:r,...i.includeReferences!==!1&&o>0?{referenceRetryTimeoutMs:o}:{},diagnosticsTimeoutMs:a,settleDelayMs:d,concurrency:s,includeReferences:i.includeReferences,includeCallees:i.includeCallees,includeSignatures:i.includeSignatures},f=Ww(m);return B("rust.semantic.session.request",()=>this.requester.requestSemantic(m,xi(f,Oc(r,m.referenceRetryTimeoutMs),s)),()=>({definitions:n.length,operationDefinitions:f,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,i,r){let o=n.length===0?{available:!0,resolvedBinary:t.resolvedBinary,references:ao(n)}:this.opts.fallbackReferenceResolver?.referencesForDefinitions(n),s=i.length===0?{available:!0,resolvedBinary:t.resolvedBinary,callees:lo(i)}:this.opts.fallbackCalleeResolver?.calleesForDefinitions(i);if(o&&s){let a={resolvedBinary:o.resolvedBinary??s.resolvedBinary??t.resolvedBinary,references:Qn(n,o.references),callees:Ac(i,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:r instanceof Error?r.message:String(r),references:ao(n),callees:lo(i)}}requestImportDefinitions(t,n,i){let r=ca(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,vg),o=ca(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Cg),s=ua(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(r,1e4)),a=ua(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,Rg),l={projectRoot:this.projectRoot,rustAnalyzerBinary:t,file:n,positions:[...i],requestTimeoutMs:r,diagnosticsTimeoutMs:s,settleDelayMs:a,concurrency:o};return B("rust.semantic.import-definitions.session.request",()=>this.requester.requestImportDefinitions(l,xi(i.length,r,o)),()=>({file:n,positions:i.length}))}};function oo(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 Ig(e,t,n={}){return new Bc(e,t,n)}function uo(e,t){let n=Dg(e);if(n!==null)return n;let i=t.includeReferences!==!1;return i&&t.includeCallees!==!0&&t.includeSignatures!==!0&&t.definitionCount<=Bw||i&&t.includeCallees===!0&&t.includeSignatures!==!0&&t.definitionCount<=Ow?0:Rg}function Eg(e){let t=e?.trim().toLowerCase(),n=t==="0"||t==="false"||t==="off"||t==="worker",i=t==="1"||t==="true"||t==="on"||t==="durable",r=t===void 0||t==="";return{transport:n||!r&&!i?"worker":"durable",source:r?"default":"environment",fallback:"worker",valid:r||n||i,optOut:"SCIP_RUST_SEMANTIC_DURABLE_SESSION=0"}}function $w(e){return Eg(e).transport}function EY(e,t){let n=Eg(t);if(n.transport==="worker")return{...n,state:"per-command"};let i=co(Lg()),r=Fc(e,i,_c()),o=ro(r);return o?{...n,state:io(o,Date.now(),Gi,Wi)?"live":"stale",pid:o.pid,heartbeatAtMs:o.heartbeatAtMs,...o.busyUntilMs===void 0?{}:{busyUntilMs:o.busyUntilMs}}:{...n,state:"stopped"}}function jw(e,t){let n=null,i=!1,r=!1,o=!1,s=()=>n??=t(),a=()=>{r||(e.shutdown(),r=!0)},l=(u,d,m)=>{let f=Kw(u);i=!0;try{a()}catch{}Ae()&&vs({type:"span",name:"rust.semantic.durable-session.request",durationMs:m,ok:!1,kind:d,session:"worker-fallback",reason:f})},c=(u,d,m)=>{if(o)throw new Error("Rust semantic failover session was already disposed.");if(i)return m(s());let f=performance.now();try{return d(e)}catch(p){l(p,u,performance.now()-f)}return m(s())};return{requestSemantic(u,d){return c("semantic",m=>m.requestSemantic(u,d),m=>m.requestSemantic(u,d))},requestImportDefinitions(u,d){return c("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 Hw(e,t,n={worker:()=>Uw(),durable:()=>pg(e,{serverPath:co(Lg()),semanticWorkerPath:co(wg())})}){return $w(t)==="durable"?jw(n.durable(),n.worker):n.worker()}function Uw(e={}){let t=null,n=null,i=1,r=!1,o=null,s=null,a=d=>{d&&kc(d,{recursive:!0,force:!0})},l=()=>{if(o)return;let d=t,m=n;t=null,n=null;let f=d?d.terminate():Promise.resolve(0);o=Promise.allSettled([f,bg(m,{gracefulMs:1e3,forceMs:1e3})]).then(([p,g])=>{let b=(g.status==="fulfilled"?g.value:[{reaped:!1,detail:String(g.reason)}]).filter(v=>!v.reaped);if(p.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})},c=()=>{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?Nw(e.semanticWorkerPath):wg();if(!kw(co(d)))throw new Error(`Rust semantic session worker was not found at ${co(d)}. Run npm run build before using built semantic Rust queries.`);return n=Sg(Nc(_c(),"codebaseiq-rust-session-")),t=new _w(d,e.shareEnvironment?{env:Aw}:void 0),t.unref(),t},u=()=>{let d=n??Sg(Nc(_c(),"codebaseiq-rust-session-"));return n=d,Nc(d,`${i++}.json`)};return{requestSemantic(d,m){if(r)throw new Error("Rust semantic session was already disposed.");let f=c(),p=u(),g=new SharedArrayBuffer(4),h=new Int32Array(g);if(f.postMessage({kind:"semantic",request:d,responsePath:p,sharedBuffer:g}),Atomics.wait(h,0,0,m)==="timed-out")throw l(),new Error(`Rust semantic session worker timed out after ${(m/1e3).toFixed(0)}s`);try{let v=zw(Zt(p,{maxBytes:pi,inputKind:"Rust semantic worker response"}));if(!v.ok)throw new Error(v.error);return v.response}finally{kc(p,{force:!0})}},requestImportDefinitions(d,m){if(r)throw new Error("Rust semantic session was already disposed.");let f=c(),p=u(),g=new SharedArrayBuffer(4),h=new Int32Array(g);if(f.postMessage({kind:"import-definitions",request:d,responsePath:p,sharedBuffer:g}),Atomics.wait(h,0,0,m)==="timed-out")throw l(),new Error(`Rust semantic import-definition session worker timed out after ${(m/1e3).toFixed(0)}s`);try{let v=qw(Zt(p,{maxBytes:pi,inputKind:"Rust import-definition worker response"}));if(!v.ok)throw new Error(v.error);return v.response}finally{kc(p,{force:!0})}},shutdown(){if(r)return;if(r=!0,!t){a(n),n=null;return}let d=u(),m=new SharedArrayBuffer(4),f=new Int32Array(m);t.postMessage({kind:"shutdown",responsePath:d,sharedBuffer:m}),Atomics.wait(f,0,0,5e3),l()}}}function zw(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 qw(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 Kw(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 ao(e){return new Map(e.map(t=>[t.symbolId,[]]))}function lo(e){return new Map(e.map(t=>[t.symbolId,[]]))}function xg(e){return new Map(e.map(t=>[t.symbolId,null]))}function Ac(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??[]]))}function Gw(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function Ww(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 Oc(e,t){return t&&t>0?Math.max(e,t):e}function wg(){return new URL("./rust-semantic-session-worker.js",import.meta.url)}function Lg(){return new URL("./rust-semantic-session-server.js",import.meta.url)}function ca(e,t){return Xn(e)??t}function ua(e,t){return Dg(e)??t}function Dg(e){if(!e)return null;let t=Number(e);return Number.isInteger(t)&&t>=0?t:null}var Hc=15e3,Uc=8;function Fg(e,t={}){let n=t.status??sa,i=Xw(e,n),r=Qw(e,n),o=Zw(e,n),s=t.referenceResolver||t.calleeResolver||t.signatureResolver||!Jw(t)?null:Ig(e,n,{fallbackReferenceResolver:i,fallbackCalleeResolver:r,fallbackSignatureResolver:o}),a=t.referenceResolver??s??i,l=t.calleeResolver??s??r,c=t.signatureResolver??s??o,u=t.importUsageResolver??Yp(t.sourceImportUsageResolver??Yw(),t.importDefinitionResolver??s),d=t.calleeSymbolResolver,m=t.sourceZeroCalleeOracle,f=t.scipOccurrenceCalleeOracle,p=new Map,g=new Map,h=null,b=null,v=()=>(h??=n(e),h),y=()=>{let C=v();return C.dependencyAvailable?b??C:C},I=C=>{if(C.length===0)return new Map;let L=fo(C);try{let w=a.referencesForDefinitions(L),R=v();return b=da(R,w),w.available?new Map(w.references):Qn(L,w.references)}catch(w){let R=v();return b=mo(R,w),Ii(L)}},E=C=>{if(C.length===0)return new Map;let L=fo(C),w=L.filter(Mg);if(w.length===0)return Ei(L);let R=new Map,M=Tg(w,f),_=[];for(let D of w)g.has(D.symbolId)?R.set(D.symbolId,g.get(D.symbolId)??[]):M.has(D.symbolId)?R.set(D.symbolId,M.get(D.symbolId)??[]):Pg(D,m)?R.set(D.symbolId,[]):_.push(D);if(_.length===0)return ar(L,R,void 0);try{let D=l.calleesForDefinitions(_),P=v();b=da(P,D);let k=ar(_,D.callees,d);for(let[V,le]of k)R.set(V,le);return ar(L,R,void 0)}catch(D){let P=v();return b=mo(P,D),Ei(L)}},S=(C,L)=>{let w=fo(C),R=fo(L),M=R.filter(Mg),_=new Map,D=Tg(M,f),P=[];for(let k of M)D.has(k.symbolId)?_.set(k.symbolId,D.get(k.symbolId)??[]):Pg(k,m)?_.set(k.symbolId,[]):P.push(k);if(w.length===0&&P.length===0)return{references:Ii(w),callees:ar(R,_,void 0)};try{let k=s?s.referencesAndCalleesForDefinitions(w,P):iL(a,l,{referenceDefinitions:w,calleeDefinitions:P}),V=v();b=da(V,k);let le=k.available?new Map(k.references):Qn(w,k.references);for(let[X,N]of k.callees)_.set(X,N);let G=ar(R,_,d);for(let[X,N]of G)g.set(X,N);return{references:le,callees:G}}catch(k){let V=v();return b=mo(V,k),{references:Ii(w),callees:Ei(R)}}},x=C=>{if(C.length===0)return new Map;let L=fo(C);try{let w=c.signaturesForDefinitions(L),R=v();return b=da(R,w),kg(L,w.signatures)}catch(w){let R=v();return b=mo(R,w),ma(L)}};return{language:"rust",availability:y,dispose:()=>{s?.dispose()},importUsage:C=>{let L=p.get(C);if(L)return L;try{let w=u.importUsage(C);return p.set(C,w),w}catch(w){let R=v();return b=mo(R,w),[]}},referencesFor:C=>I([C]).get(C.symbolId)??[],referencesForDefinitions:I,referencesAndCalleesForDefinitions:S,calleesFor:C=>E([C]).get(C.symbolId)??[],calleesForDefinitions:E,signatureFor:C=>x([C]).get(C.symbolId)??null}}function da(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 mo(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 Jw(e){if(e.usePersistentSession!==void 0)return e.usePersistentSession;let t=process.env.SCIP_RUST_SEMANTIC_SESSION;return t!=="0"&&t!=="false"}function Yw(){return{importUsageFacts:()=>({usage:[],positions:[]})}}function fo(e){return e.map(t=>{let n=t;return{...t,leaf:typeof n.leaf=="string"?n.leaf:Y(t.symbol),parentTypeName:n.parentTypeName??null,isFunctionLike:typeof n.isFunctionLike=="boolean"?n.isFunctionLike:_e(t.symbol),isTypeLike:n.isTypeLike??!1,kind:n.kind??null,documentation:n.documentation??null,enclosingSymbol:n.enclosingSymbol??null}})}function Mg(e){return e.isFunctionLike}function Pg(e,t){if(!t)return!1;try{return t(e)}catch{return!1}}function Tg(e,t){if(!t||e.length===0)return new Map;try{return t(e)}catch{return new Map}}function Xw(e,t){return{referencesForDefinitions:n=>eL(e,t,n)}}function Qw(e,t){return{calleesForDefinitions:n=>tL(e,t,n)}}function Zw(e,t){return{signaturesForDefinitions:n=>nL(e,t,n)}}function eL(e,t,n){let i=t(e);if(!i.available||!i.resolvedBinary)return{available:!1,resolvedBinary:i.resolvedBinary,reason:Kc(i),references:Ii(n)};let r=zc();if(!jc(r))return{available:!1,resolvedBinary:i.resolvedBinary,reason:`Rust semantic worker was not found at ${r}. Run npm run build before using built semantic Rust queries.`,references:Ii(n)};let o=lr(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Hc),s=fa(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),a=lr(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Uc),l=fa(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=uo(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!0}),u={projectRoot:e,rustAnalyzerBinary:i.resolvedBinary,definitions:[...n],requestTimeoutMs:o,...s>0?{referenceRetryTimeoutMs:s}:{},diagnosticsTimeoutMs:l,settleDelayMs:c,concurrency:a},d=$c(process.execPath,[r],{cwd:e,input:JSON.stringify(u),encoding:"utf8",maxBuffer:50*1024*1024,windowsHide:!0,timeout:xi(n.length,Oc(o,u.referenceRetryTimeoutMs),a)}),m=Gc(d.stdout);if(m)return{...qc(m),resolvedBinary:i.resolvedBinary,references:Qn(n,new Map(m.references),new Set(m.incompleteReferenceSymbolIds??[]))};let f=d.error instanceof Error?d.error.message:d.stderr.trim()||`Rust semantic worker exited with status ${d.status??"unknown"}.`;return{available:!1,resolvedBinary:i.resolvedBinary,reason:f,references:Ii(n)}}function tL(e,t,n){let i=t(e);if(!i.available||!i.resolvedBinary)return{available:!1,resolvedBinary:i.resolvedBinary,reason:Kc(i),callees:Ei(n)};let r=zc();if(!jc(r))return{available:!1,resolvedBinary:i.resolvedBinary,reason:`Rust semantic worker was not found at ${r}. Run npm run build before using built semantic Rust queries.`,callees:Ei(n)};let o=lr(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Hc),s=lr(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Uc),a=fa(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),l=uo(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!0}),c={projectRoot:e,rustAnalyzerBinary:i.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:l,concurrency:s,includeReferences:!1,includeCallees:!0},u=$c(process.execPath,[r],{cwd:e,input:JSON.stringify(c),encoding:"utf8",maxBuffer:50*1024*1024,windowsHide:!0,timeout:xi(n.length,o,s)}),d=Gc(u.stdout);if(d)return{...qc(d),resolvedBinary:i.resolvedBinary,callees:ar(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:i.resolvedBinary,reason:m,callees:Ei(n)}}function nL(e,t,n){let i=t(e);if(!i.available||!i.resolvedBinary)return{available:!1,resolvedBinary:i.resolvedBinary,reason:Kc(i),signatures:ma(n)};let r=zc();if(!jc(r))return{available:!1,resolvedBinary:i.resolvedBinary,reason:`Rust semantic worker was not found at ${r}. Run npm run build before using built semantic Rust queries.`,signatures:ma(n)};let o=lr(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Hc),s=lr(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Uc),a=fa(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),l=uo(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!1,includeSignatures:!0}),c={projectRoot:e,rustAnalyzerBinary:i.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:l,concurrency:s,includeReferences:!1,includeCallees:!1,includeSignatures:!0},u=$c(process.execPath,[r],{cwd:e,input:JSON.stringify(c),encoding:"utf8",maxBuffer:50*1024*1024,windowsHide:!0,timeout:xi(n.length,o,s)}),d=Gc(u.stdout);if(d)return{...qc(d),resolvedBinary:i.resolvedBinary,signatures:kg(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:i.resolvedBinary,reason:m,signatures:ma(n)}}function iL(e,t,n){let i=n.referenceDefinitions.length>0?e.referencesForDefinitions(n.referenceDefinitions):{available:!0,references:Ii(n.referenceDefinitions)},r=n.calleeDefinitions.length>0?t.calleesForDefinitions(n.calleeDefinitions):{available:!0,callees:Ei(n.calleeDefinitions)},o={resolvedBinary:i.resolvedBinary??r.resolvedBinary,references:i.references,callees:r.callees};return i.available&&r.available?{available:!0,...o}:{available:!1,reason:(i.available?void 0:i.reason)??(r.available?void 0:r.reason)??"Rust semantic resolution was unavailable.",...o}}function Ii(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Ei(e){return new Map(e.map(t=>[t.symbolId,[]]))}function ma(e){return new Map(e.map(t=>[t.symbolId,null]))}function ar(e,t,n){let i=0,r=0;return B("rust.semantic.callees.complete-map",()=>{let o=new Map;for(let s of e){let a=t.get(s.symbolId)??[];a.length>0&&(i+=1),r+=a.length,o.set(s.symbolId,a.map(l=>({...l,symbol:n?n(l):l.symbol})))}return o},()=>({definitions:e.length,rows:i,callees:r,resolveSymbols:!!n}))}function kg(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function zc(){return Vw(new URL("./rust-semantic-worker.js",import.meta.url))}function qc(e){return e.available?{available:!0}:{available:!1,reason:e.reason}}function Kc(e){return e.available?"rust-analyzer binary path is unavailable.":e.reason}function Gc(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 i={references:n.references,incompleteReferenceSymbolIds:Array.isArray(n.incompleteReferenceSymbolIds)?n.incompleteReferenceSymbolIds.filter(r=>typeof r=="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,...i}:{available:!1,reason:String(n.reason),...i}}catch{return null}}function lr(e,t){return Xn(e)??t}function fa(e,t){if(!e)return t;let n=Number(e);return Number.isInteger(n)&&n>=0?n:t}var Ng=new WeakMap;function _g(e,t){let n=t.filter(oL);if(n.length===0)return new Map;let i=0,r=0;return B("rust.scip-occurrence.callees",()=>{let o=lL(e),s=new Map;for(let a of n){let l=sL(e,o,a);l!==null&&(s.set(a.symbolId,l),i+=1,r+=l.length)}return s},()=>({definitions:t.length,candidates:n.length,resolvedDefinitions:i,resolvedCallees:r}))}function oL(e){return!(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||!e.isFunctionLike||e.leaf==="main"||Xe(e.symbol))}function sL(e,t,n){let i=te(e,n.relativePath);if(!i||i.language!=="rust")return null;let r=i.callables.find(u=>u.startLine!==n.startLine||u.endLine!==n.endLine?!1:u.name===n.leaf||n.leaf.endsWith(u.name)||u.name.endsWith(n.leaf));if(!r)return null;let o=i.callSites.filter(u=>u.line>=r.startLine&&u.line<=r.endLine);if(o.length===0)return null;let s=cL(e,t,n.relativePath);if(!s)return null;let a=s.filter(u=>u.line>=r.startLine&&u.line<=r.endLine&&u.callee.symbol!==n.symbol);if(a.some(u=>u.traitImplMember)||!aL(o,a))return null;let l=[],c=new Set;for(let u of a){let d=`${u.callee.symbol}\0${u.callee.file}\0${u.callee.line}`;c.has(d)||(c.add(d),l.push(u.callee))}return l}function aL(e,t){let n=Ag(e),i=Ag(t);if(n.size!==i.size)return!1;for(let[r,o]of n)if(i.get(r)!==o)return!1;return!0}function Ag(e){let t=new Map;for(let n of e){let i=n.calleeLeaf??n.leaf;if(!i)continue;let r=`${n.line}\0${i}`;t.set(r,(t.get(r)??0)+1)}return t}function lL(e){let t=Ng.get(e);if(!t){let n=Ue(e).filter(i=>i.symbol.startsWith("rust-analyzer ")&&i.relativePath.endsWith(".rs")&&i.isFunctionLike);t={definitionBySymbol:new Map(n.map(i=>[i.symbol,i])),occurrencesByFile:new Map},Ng.set(e,t)}return t}function cL(e,t,n){return t.occurrencesByFile.has(n)||t.occurrencesByFile.set(n,uL(e,t,n)),t.occurrencesByFile.get(n)??null}function uL(e,t,n){if(!n.endsWith(".rs")||e.isIgnored(n))return[];let i=_s(e,n);if(!i)return null;let r=[];for(let o of i){if((o.roles&1)!==0)continue;let s=t.definitionBySymbol.get(o.symbol);if(!s)continue;let a=o.range[0];r.push({line:a,leaf:s.leaf,traitImplMember:Xe(s.symbol),callee:{symbol:s.symbol,file:s.relativePath,line:s.startLine,callsiteLine:a}})}return r}var pa=class{sessions=new WeakMap;getOrCreate(t,n,i){let r=dL(t,n),o=this.sessions.get(t);o||(o=new Map,this.sessions.set(t,o));let s=o.get(r);if(s)return s.hits+=1,s.lastUsedAtMs=Date.now(),s.provider;let a=Date.now(),l=i();return o.set(r,{key:r,language:n,projectRoot:t.config.projectRoot,provider:l,createdAtMs:a,lastUsedAtMs:a,hits:1}),l}sessionsFor(t){return[...this.sessions.get(t)?.values()??[]]}clear(t){let n=this.sessions.get(t);if(n)for(let i of n.values())i.provider.dispose?.();this.sessions.delete(t)}};function dL(e,t){return`${e.config.projectRoot}:${t}-workspace`}import{randomUUID as AL}from"crypto";import{existsSync as _L}from"fs";import{dirname as BL}from"path";function Bg(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 xe}from"perf_hooks";function Gt(e,t,n){if(e.has(t))return e.get(t);let i=n();return e.set(t,i),i}import jg from"path";import{realpathSync as Og}from"fs";function mL(e,t){return e.getReferences().map(n=>{let i=n.getNode();return ga(i,t)})}function fL(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function Hg(e,t,n,i){let r=[];for(let o of fL(e))for(let s of mL(o,i))s.file===t.relativePath&&s.line>=t.startLine&&s.line<=t.endLine||r.push(s);for(let o of n)r.push(o);return cr(r)}function Ug(e,t,n,i){let r=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();ur(i,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||r.push({location:ga(a,i),node:a}))}return r}function ga(e,t){let n=e.getSourceFile(),i=n.getLineAndColumnAtPos(e.getStart());return{file:ur(t,n.getFilePath())??n.getBaseName(),line:i.line-1,column:i.column-1}}function Wc(e,t,n){let i=e.getSourceFile(),r=Jc(i,e),o=e.getText(),s=new RegExp(`\\b${Oe(o)}\\b`,"g"),a=i.getFullText().split(`
51
+ `),l=[];for(let c=0;c<a.length;c++){if(c===r)continue;let u=a[c]??"";s.lastIndex=0;let d;for(;(d=s.exec(u))!==null;)l.push({file:t,line:c,column:d.index})}return cr(l.filter(c=>ur(n,jg.join(n,c.file))===t))}function Vc(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 Jc(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function cr(e){let t=new Set,n=[];for(let i of e){let r=`${i.file}:${i.line}:${i.column}`;t.has(r)||(t.add(r),n.push(i))}return n}function ur(e,t){let n=e||process.cwd(),i=$g(n,t);if(i)return i;try{return $g(Og(n),Og(t))}catch{return null}}function $g(e,t){let n=jg.relative(e,t).replace(/\\/g,"/");return!n||n===".."||n.startsWith("../")?null:n}function zg(e,t,n,i){let r=pL(t,i);return r.size===0?new Map:gL(e,n,r)}function pL(e,t){let n=new Map;for(let i of W(e,t)){let r=Y(i.symbol)??i.leaf;if(!r)continue;let o=n.get(r);o||(o=[],n.set(r,o)),o.push(i)}return n}function gL(e,t,n){let i=new Map,r=new Map;return t.forEachDescendant(o=>{for(let s of hL(e,o)){let a=n.get(s);if(!a)continue;let l=Jc(t,o);for(let c of a){if(l<c.startLine-1||l>c.endLine+1)continue;let u=Math.abs(l-c.startLine),d=r.get(c.symbolId);d!==void 0&&d<=u||(r.set(c.symbolId,u),i.set(c.symbolId,o))}}}),i}function hL(e,t){let n=[],i=r=>{r&&!n.includes(r)&&n.push(r)};if("getNameNode"in t&&typeof t.getNameNode=="function"){let r=t.getNameNode();i(r?.getText())}if("getName"in t&&typeof t.getName=="function"){let r=t.getName();i(r)}return e.Node.isIdentifier(t)&&i(t.getText()),n}var yL=Hn("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function qg(e,t,n,i){let r=Qc(e,t),o=Yc(r.get(i)??[],n);if(o)return o;let s=[];for(let a of r.values())for(let l of a)((l.leaf||Y(l.symbol)||"").includes(i)||l.symbol.includes(i))&&s.push(l);return Yc(s,n)}function Xc(e,t,n,i){return Yc(Qc(e,t).get(i)??[],n)}function Kg(e,t){let n=new Map;for(let[i,r]of Qc(e,t)){let o=r[0];o&&n.set(i,o)}return n}function Qc(e,t){return yL.get(e,t,()=>{let n=new Map;for(let i of W(e,t)){let r=i.leaf||Y(i.symbol);if(!r)continue;let o=n.get(r);o||(o=[],n.set(r,o)),o.push({...i,leaf:r})}for(let i of n.values())i.sort((r,o)=>r.startLine-o.startLine||r.endLine-o.endLine||r.symbolId-o.symbolId);return n})}function Yc(e,t){let n=null,i=Number.POSITIVE_INFINITY;for(let r of e){let o=Math.abs(r.startLine-t);(o<i||o===i&&n&&r.startLine<n.startLine)&&(n=r,i=o)}return n}import bL from"path";import{realpathSync as SL}from"fs";function Gg(e,t){let n=new Map,i=null,r=null,o=()=>(r??=me(e,{extensions:Bs}),r),s=()=>(i??=B("typescript.source-file-index",()=>vL(e.config.projectRoot,t,o()),()=>({projects:t.length,indexedDocuments:o().length})),i),a=l=>Gn(l)?Gt(n,l,()=>{let c=Wg(e.config.projectRoot,l);if(!c)return null;for(let{project:u,sourceFiles:d}of s()){let m=d.get(c)??null;if(m||(m=u.addSourceFileAtPathIfExists(c)??null,m&&Zc(d,m)),m)return{project:u,sourceFile:m}}return null}):null;return{sourceFile:l=>a(l)?.sourceFile??null,sourceFileMatch:a,indexedTypeScriptLikeDocuments:o}}function vL(e,t,n){let i=t.map(({project:r})=>{let o=new Map;for(let s of r.getSourceFiles())Zc(o,s);return{project:r,sourceFiles:o}});for(let r of n){let o=Wg(e,r);if(o)for(let s of i){if(s.sourceFiles.has(o))break;let a=s.project.addSourceFileAtPathIfExists(o)??null;if(a){Zc(s.sourceFiles,a);break}}}return i}function Zc(e,t){let n=eu(t.getFilePath());e.set(n,t);try{e.set(eu(SL(n)),t)}catch(i){if(!ot(i))throw i}}function Wg(e,t){try{return eu(Cs(e,t,{inputKind:"indexed TypeScript source file"}).absolutePath)}catch(n){if(!ot(n))throw n;return null}}function eu(e){return bL.resolve(e)}function tu(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function Vg(e){let t=`${e.relativeDir}/src`;return[`${t}/index.ts`,`${t}/index.tsx`,`${t}/index.mts`,`${t}/index.cts`]}import{existsSync as po}from"fs";import lt from"path";var nu=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function iu(e,t){let i=t?lt.dirname(lt.join(e,t)):e,r=lt.resolve(e);for(;i.startsWith(r);){for(let s of nu){let a=lt.join(i,s);if(po(a))return a}let o=lt.dirname(i);if(o===i)break;i=o}for(let o of nu){let s=lt.join(e,o);if(po(s))return s}return null}function Jg(e){let t=e.config.projectRoot,n=new Set(CL(t,e.config.semantic?.typescript?.tsconfigs)),i=me(e,{includeIgnored:!1,extensions:Bs});for(let r of i){let o=iu(t,r);o&&n.add(lt.resolve(o))}if(n.size===0){let r=iu(t);r&&n.add(lt.resolve(r))}return[...n].filter(r=>!Yg(t,r)).sort((r,o)=>r.localeCompare(o))}function CL(e,t=[]){let n=new Set;for(let i of t){let r=lt.isAbsolute(i)?i:lt.join(e,i);po(r)&&n.add(lt.resolve(r))}for(let i of xL(e))for(let r of nu){let o=lt.join(i,r);po(o)&&n.add(lt.resolve(o))}if(n.size===0){let i=iu(e);i&&n.add(lt.resolve(i))}return[...n].filter(i=>!Yg(e,i)).sort((i,r)=>i.localeCompare(r))}function xL(e){let t=lt.join(e,"package.json");if(!po(t))return[];let n;try{n=JSON.parse(gi(t,"project package manifest"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(r=>bf(e,r))}function Yg(e,t){let n=lt.relative(e,t).replace(/\\/g,"/");return n.startsWith("..")||n.includes("/node_modules/")||n.startsWith("node_modules/")||n.includes("/dist/")||n.startsWith("dist/")}function ru(e,t){try{return e()}catch{t?.();return}}var RL=32;function nh(e,t){let n=B("typescript.provider.load",()=>Os());if(!n)return $s("ts-morph is not installed");let i=B("typescript.provider.tsconfig-discovery",()=>Jg(e));if(i.length===0)return $s("no tsconfig found");try{let r=B("typescript.provider.project-bundles",()=>Wf(n,i),()=>({tsconfigs:i.length}));return IL(e,n,r)}catch(r){return $s(r instanceof Error?r.message:String(r),i[0],i)}}function IL(e,t,n,i={}){return B("typescript.provider.construct",()=>new ou(e,t,n),()=>({tsconfigs:n.length,reusedProjects:i.reusedProjects===!0}))}var ou=class{constructor(t,n,i){this.db=t;this.tsMorph=n;this.projects=i;this.workspacePackages=yf(t.config.projectRoot),this.sourceFiles=Gg(t,i)}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 Gt(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let i=wL();return B("typescript.import-usage.file",()=>this.importUsageForSourceFile(t,n,i),()=>({file:t,...i}))})}referencesFor(t){return Gt(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);return this.referencesForDefinitionNode(t,n)})}referencesForDefinitions(t,n={}){let i=new Map,r=Ae(),o=[];for(let u of t){let d=this.referencesCache.get(u.symbolId);d?i.set(u.symbolId,d):o.push(u)}if(o.length===0)return i;let s=o,a=n.exact?[]:o.filter(u=>!Qg(u));if(a.length>=RL){let u=this.referencesForDefinitionsBySymbolScan(a);if(u.incompleteFiles.size===0)for(let d of a){let m=u.references.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,m),i.set(d.symbolId,m)}if(s=o.filter(d=>Qg(d)),s.length===0)return i}let l=new Map;for(let u of s){let d=l.get(u.relativePath);d?d.push(u):l.set(u.relativePath,[u])}let c=[];for(let[u,d]of l){let m=Zg();B("typescript.references-map.file",()=>{let f=this.definitionNodesForFile(u);for(let p of d){r&&(m.cacheMisses+=1);let g=f.get(p.symbolId)??null;r&&(g?m.nodeHits+=1:m.nodeMisses+=1);try{let h=this.referencesForDefinitionNode(p,g,r?m:void 0);this.referencesCache.set(p.symbolId,h),i.set(p.symbolId,h)}catch{m.preciseSearchFailures+=1,c.push(p)}}},()=>({relativePath:u,definitions:d.length,...eh(m)}))}if(c.length>0){let u=this.referencesForDefinitionsBySymbolScan(c);if(u.incompleteFiles.size===0)for(let d of c){let m=u.references.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,m),i.set(d.symbolId,m)}}return i}referenceFragmentsForFiles(t){let n=Ue(this.db).filter(s=>Gn(s.relativePath)),i=t.filter(s=>this.sourceFiles.sourceFile(s)!==null),r=this.referencesForDefinitionsBySymbolScan(n,i),o=i.filter(s=>!r.incompleteFiles.has(s));return Vf(n,r.references,o)}referencesForDefinitionsBySymbolScan(t,n){let i=Ae(),r=Zg(),o=new Map,s=new Set,a=new Set(t.map(c=>c.symbolId)),l=new Map(t.map(c=>[c.symbolId,c]));for(let c of t)o.set(c.symbolId,[]);return B("typescript.references-map.inverted-scan",()=>{let c=i?xe.now():0,u=n?this.packageImportReferencesForFiles(n):this.packageImportReferences();for(let b of t){let v=u.get(b.symbolId)??[];if(v.length>0){let y=o.get(b.symbolId)??[];y.push(...v),o.set(b.symbolId,y)}i&&(r.packageReferenceCount+=v.length)}i&&(r.packageRefsMs+=xe.now()-c);let d=new Map,m=new Map,f=this.hierarchyTargetsForDefinitions(t),p=new Set(t.map(b=>b.leaf).filter(Boolean)),g=i?xe.now():0;for(let b of n??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(b))continue;let v=this.sourceFiles.sourceFile(b);if(!v)continue;i&&(r.scanFiles+=1),this.addReferencesFromSourceFileScan(v,b,a,l,f,p,d,m,o,i?r:void 0)||s.add(b)}i&&(r.scanMs+=xe.now()-g);let h=i?xe.now():0;this.addHierarchyMemberReferences(t,o,i?r:void 0),i&&(r.hierarchyMs+=xe.now()-h);for(let[b,v]of o){let y=cr(v);o.set(b,y),i&&(r.referenceCount+=y.length)}},()=>({definitions:t.length,...eh(r)})),{references:o,incompleteFiles:s}}addReferencesFromSourceFileScan(t,n,i,r,o,s,a,l,c,u){let d=this.compilerCheckerForSourceFile(t),m=t.compilerNode,f=ML(t),p=!0,g=h=>{if(this.tsMorph.ts.isIdentifier(h)){if(u&&(u.identifiers+=1),!s.has(h.text)&&!f.has(h.text)){this.tsMorph.ts.forEachChild(h,g);return}let b=this.compilerReferenceSymbol(d,h,u,()=>{p=!1});if(b){let v;a.has(b)?v=a.get(b)??null:(v=this.referenceDefinitionFromCompilerSymbol(b),a.set(b,v)),u&&(v?u.targetHits+=1:u.targetMisses+=1);let y=Gt(l,b,()=>this.compilerSymbolKeys(b)),I=null,E=null,S=v&&i.has(v.symbolId)?r.get(v.symbolId):void 0;if(S&&(I=ha(m,h),!Xg(S,n,I))){let x=m.getLineAndCharacterOfPosition(h.getStart(m));E={file:n,line:x.line,column:x.character};let C=c.get(S.symbolId)??[];C.push(E),c.set(S.symbolId,C),u&&(u.requestedHits+=1)}for(let x of y)for(let C of o.get(x)?.values()??[]){if(I??=ha(m,h),Xg(C,n,I))continue;if(!E){let w=m.getLineAndCharacterOfPosition(h.getStart(m));E={file:n,line:w.line,column:w.character}}let L=c.get(C.symbolId)??[];L.push(E),c.set(C.symbolId,L),u&&(u.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(h,g)};return g(m),p}hierarchyTargetsForDefinitions(t){let n=new Map;for(let i of t){let r=this.nodeForDefinition(i),o=r?.compilerNode;if(!o||!this.isHierarchyMethod(o))continue;let s=o.parent;if(!this.isHierarchyContainer(s))continue;let a=this.compilerCheckerForSourceFile(r.getSourceFile()),l=a.getSymbolAtLocation(o.name);if(l)for(let c of this.hierarchyMemberSymbols(a,s,l))for(let u of this.compilerSymbolKeys(c)){let d=n.get(u)??new Map;d.set(i.symbolId,i),n.set(u,d)}}return n}hierarchyMemberSymbols(t,n,i){let r=new Set,o=new Set,s=(a,l,c)=>{if(!o.has(a)){o.add(a),r.add(l);for(let u of c){let d=u.getProperty(i.name);d&&s(u,d,this.hierarchyAncestorTypesForType(t,u))}}};return s(t.getTypeAtLocation(n),i,this.hierarchyAncestorTypes(t,n)),r}addHierarchyMemberReferences(t,n,i){let r=new Map;for(let o of t){let s=this.nodeForDefinition(o),a=s?.compilerNode;if(!a||!this.isHierarchyMethod(a))continue;let l=a.parent;if(!this.isHierarchyContainer(l))continue;let c=this.compilerCheckerForSourceFile(s.getSourceFile()),u=c.getSymbolAtLocation(a.name);if(!u)continue;let d=a.getSourceFile(),m=d.getLineAndCharacterOfPosition(a.name.getStart(d)),f={definition:o,location:{file:o.relativePath,line:m.line,column:m.character}},p=n.get(o.symbolId)??[];for(let h of this.hierarchyMemberSymbols(c,l,u))if(h!==u)for(let b of this.compilerSymbolLocations(h))p.push(b),i&&(i.hierarchyReferences+=1);n.set(o.symbolId,p);let g=this.hierarchyRootMemberSymbols(c,l,u);for(let h of g){let b=r.get(h)??new Map;b.set(o.symbolId,f),r.set(h,b)}i&&(i.hierarchyDefinitions+=1)}for(let o of r.values())if(!(o.size<2)){i&&(i.hierarchyFamilies+=1);for(let{definition:s}of o.values()){let a=n.get(s.symbolId)??[];for(let l of o.values())l.definition.symbolId!==s.symbolId&&(a.push(l.location),i&&(i.hierarchyReferences+=1));n.set(s.symbolId,a)}}}hierarchyRootMemberSymbols(t,n,i){let r=new Set,o=new Set,s=(a,l,c)=>{if(o.has(a))return;o.add(a);let u=!1;for(let d of c){let m=d.getProperty(i.name);m&&(u=!0,s(d,m,this.hierarchyAncestorTypesForType(t,d)))}if(!u)for(let d of this.compilerSymbolKeys(l))r.add(d)};return s(t.getTypeAtLocation(n),i,this.hierarchyAncestorTypes(t,n)),r}compilerSymbolKeys(t){return(t.declarations??[]).map(n=>{let i=n.getSourceFile();return`${i.fileName}\0${n.getStart(i)}\0${t.name}`})}compilerSymbolLocations(t){let n=[];for(let i of t.declarations??[]){let r=i.getSourceFile(),o=ur(this.db.config.projectRoot,r.fileName);if(!o)continue;let s=i.name,a=r.getLineAndCharacterOfPosition((s??i).getStart(r));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 i=new Set(this.hierarchyAncestorTypesForType(t,t.getTypeAtLocation(n)));for(let r of n.heritageClauses??[])for(let o of r.types)i.add(t.getTypeAtLocation(o));return[...i]}hierarchyAncestorTypesForType(t,n){let i=new Set(this.baseTypes(t,n));for(let r of n.getSymbol()?.declarations??[])if(this.isHierarchyContainer(r))for(let o of r.heritageClauses??[])for(let s of o.types)i.add(t.getTypeAtLocation(s));return[...i]}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,i,r){i&&(i.symbolLookups+=1);let o=ru(()=>t.getSymbolAtLocation(n),r);if(o){if((o.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return o;try{return i&&(i.aliasResolutions+=1),t.getAliasedSymbol(o)}catch{return r?.(),o}}}calleesFor(t){if(this.calleesCache.has(t.symbolId))return this.calleesCache.get(t.symbolId)??[];let n=Gt(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath));if(n.incompleteSymbolIds.has(t.symbolId))throw new Error(`TypeScript callee evidence is incomplete for ${t.symbol}.`);let i=n.callees.get(t.symbolId)??[];return this.calleesCache.set(t.symbolId,i),i}calleesForDefinitions(t){let n=new Map,i=new Map;for(let r of t){if(this.calleesCache.has(r.symbolId)){n.set(r.symbolId,this.calleesCache.get(r.symbolId)??[]);continue}let o=i.get(r.relativePath);o?o.push(r):i.set(r.relativePath,[r])}for(let[r,o]of i){let s=this.fileCalleesCache.get(r),a=new Set(o.map(c=>c.symbolId)),l=s??this.calleeMapForFile(r,a);for(let c of o){if(l.incompleteSymbolIds.has(c.symbolId))continue;let u=l.callees.get(c.symbolId)??[];this.calleesCache.set(c.symbolId,u),n.set(c.symbolId,u)}}return n}referencesForDefinitionNode(t,n,i){let r=i?xe.now():0,o=this.packageImportReferencesForDefinition(t);if(i&&(i.packageRefsMs+=xe.now()-r,i.packageReferenceCount+=o.length),!n)return o;let s=i?xe.now():0,a=Hg(n,t,o,this.db.config.projectRoot);return i&&(i.semanticRefsMs+=xe.now()-s,i.referenceCount+=a.length),a}signatureFor(t){return Gt(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 i=n.getType().getCallSignatures()[0];if(!i)return null;let r=i.getParameters().map(s=>{let a=s.getDeclarations()[0],l=a?s.getTypeAtLocation(a).getText(a):s.getValueDeclaration()?.getType().getText()??"unknown";return th(l)}),o=i.getReturnType().getText(n);return`(${r.join(",")})=>${th(o)}`})}importUsageForSourceFile(t,n,i){let r=[],o=new Map;for(let s of n.getImportDeclarations()){i.declarations+=1;let a=tc(this.db,t,s.getModuleSpecifierValue()),l=s.getImportClause()?.isTypeOnly()??!1;for(let c of su(s)){i.entries+=1;let u=l?null:c.identifier?.getSymbol()?.compilerSymbol??null;!l&&c.identifier&&(u?i.bindingSymbols+=1:i.missingBindingSymbols+=1);let d={sourcePath:a,entry:c,typeOnlyDeclaration:l,bindingSymbol:u,references:[]};if(r.push(d),l||!c.localName||!u)continue;let m=o.get(c.localName);m?m.push(d):o.set(c.localName,[d])}}return o.size>0&&n.forEachDescendant(s=>{if(s.getKindName()!=="Identifier")return;let a=o.get(s.getText());if(!a||LL(s))return;i.scannedIdentifiers+=1;let l=s.getSymbol()?.compilerSymbol;if(i.symbolLookups+=1,!!l){for(let c of a)if(c.bindingSymbol===l){c.references.push({location:ga(s,this.db.config.projectRoot),node:s}),i.matchedReferences+=1;break}}}),r.map(s=>s.typeOnlyDeclaration?EL(t,s.sourcePath,s.entry):s.entry.identifier&&!s.bindingSymbol?(i.fallbackEntries+=1,this.valueImportUsageForEntry(t,s.sourcePath,s.entry)):this.valueImportUsageFromLocations(t,s.sourcePath,s.entry,s.references))}valueImportUsageForEntry(t,n,i){let r;try{r=i.identifier?i.identifier.findReferences():[]}catch{let s=i.identifier?Wc(i.identifier,t,this.db.config.projectRoot):[];return{importer:t,sourcePath:n,importedName:i.importedName,localName:i.localName,kind:i.kind,isTypeOnly:i.isTypeOnly,isUsed:i.isTypeOnly||s.length>0,isTypeUsed:i.isTypeOnly,isValueUsed:!i.isTypeOnly&&s.length>0,references:s}}let o=[];for(let s of r)for(let a of Ug(s,t,i.identifier,this.db.config.projectRoot))o.push(a);return this.valueImportUsageFromLocations(t,n,i,o)}valueImportUsageFromLocations(t,n,i,r){let o=r.some(l=>!Vc(l.node)),s=r.some(l=>Vc(l.node)),a=i.isTypeOnly;return{importer:t,sourcePath:n,importedName:i.importedName,localName:i.localName,kind:i.kind,isTypeOnly:a,isUsed:a||r.length>0,isTypeUsed:a||s,isValueUsed:o,references:r.map(l=>l.location)}}packageImportReferencesForDefinition(t){return this.packageImportReferences().get(t.symbolId)??[]}packageImportReferencesForFiles(t){let n=new Map,i=new Set;for(let o of t){let s=this.sourceFiles.sourceFile(o);if(s)for(let a of s.getImportDeclarations()){let l=tu(this.workspacePackages,a.getModuleSpecifierValue());l&&i.add(l)}}if(i.size===0)return n;let r=this.packageExportsForNames(i);for(let o of t)this.addPackageImportReferencesForDocument(n,r,o);for(let[o,s]of n)n.set(o,cr(s));return n}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let t=new Map,n=this.packageExports();for(let i of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(t,n,i);for(let[i,r]of t)t.set(i,cr(r));return this.packageImportReferenceIndex=t,t}addPackageImportReferencesForDocument(t,n,i){if(this.db.isIgnored(i))return;let r=this.sourceFiles.sourceFileMatch(i);if(r)for(let o of r.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(t,n,i,o)}addPackageImportReferencesForDeclaration(t,n,i,r){let o=tu(this.workspacePackages,r.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of su(r)){if(a.kind!=="named"||!a.identifier)continue;let l=s.get(a.importedName);if(!l||l.size===0)continue;let c=Wc(a.identifier,i,this.db.config.projectRoot);c.length>0&&kL(t,l,c)}}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 i of this.workspacePackages){if(!t.has(i.name))continue;let r=new Map;for(let o of Vg(i))this.collectPackageExports(i,o,r,new Set);r.size>0&&n.set(i.name,r)}return n}collectPackageExports(t,n,i,r){if(r.has(n))return;r.add(n);let o=this.sourceFiles.sourceFile(n);if(o)for(let s of o.getExportDeclarations()){let a=s.getModuleSpecifierValue(),l=a?tc(this.db,n,a):n;if(!l||!l.startsWith(`${t.relativeDir}/src/`))continue;let c=s.getNamedExports();if(c.length===0){if(s.isNamespaceExport())continue;this.collectPackageExports(t,l,i,r);continue}for(let u of c){let d=u.getNameNode().getText(),m=u.getAliasNode()?.getText()??d,f=this.indexedDefinitionByLeaf(l,d);if(!f)continue;let p=i.get(m);p||(p=new Set,i.set(m,p)),p.add(f.symbolId)}}}indexedDefinitionByLeaf(t,n){return Gt(this.indexedDefinitionLeafCache,t,()=>Kg(this.db,t)).get(n)??null}nodeForDefinition(t){return Gt(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return Gt(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?zg(this.tsMorph,this.db,n,t):new Map})}referenceDefinitionFromCompilerSymbol(t){return this.definitionFromCompilerSymbol(t,void 0,!0)}definitionFromCompilerSymbol(t,n,i=!1){let r=t.name,o=n?xe.now():0,s=t.declarations??[];n&&(n.declarationsMs+=xe.now()-o,n.declarationChecks+=s.length);for(let a of s){let l=n?xe.now():0,c=a.getSourceFile(),u=ur(this.db.config.projectRoot,c.fileName),d=c.getLineAndCharacterOfPosition(a.getStart(c)).line;if(n&&(n.declarationLocationMs+=xe.now()-l),!u||this.db.isIgnored(u))continue;let m=n?xe.now():0,f=this.compilerDeclarationName(a),p=i?Xc(this.db,u,d,r)??(f&&f!==r?Xc(this.db,u,d,f):null):qg(this.db,u,d,r);if(n&&(n.indexedLookupMs+=xe.now()-m),p)return{symbolId:p.symbolId,symbol:p.symbol,file:p.relativePath,line:p.startLine}}return null}compilerDeclarationName(t){let n=t.name;return n&&this.tsMorph.ts.isIdentifier(n)?n.text:null}calleeMapForFile(t,n){let i=Ae(),r=0,o=0,s=0,a=0,l=0,c=0,u=0,d=0,m=i?TL():void 0;return B("typescript.callee-map.file",()=>{let f=i?xe.now():0,p=this.sourceFiles.sourceFile(t);if(i&&(l=Math.round(xe.now()-f)),!p)return{callees:new Map,incompleteSymbolIds:new Set};let g=i?xe.now():0,h=W(this.db,t).sort((L,w)=>L.startLine-w.startLine||w.endLine-L.endLine);if(i&&(c=Math.round(xe.now()-g)),r=h.length,h.length===0)return{callees:new Map,incompleteSymbolIds:new Set};let b=new Map,v=new Set,y=i?xe.now():0,I=this.compilerCheckerForSourceFile(p),E=p.compilerNode;i&&(u=Math.round(xe.now()-y));let S=new Map,x=L=>{if(this.tsMorph.ts.isCallExpression(L)||this.tsMorph.ts.isNewExpression(L)){i&&(o+=1);let w=this.semanticCalleeForCallNode(I,E,h,L,S,n,v,m);w&&(i&&(s+=1),DL(b,w.callerId,w.target))}this.tsMorph.ts.forEachChild(L,x)},C=i?xe.now():0;x(E),i&&(d=Math.round(xe.now()-C));for(let[L,w]of b)b.set(L,NL(w));return a=b.size,{callees:b,incompleteSymbolIds:v}},()=>({relativePath:t,definitions:r,callNodes:o,resolvedCallees:s,outputRows:a,requestedDefinitions:n?.size??r,sourceFileLookupMs:l,definitionsLoadMs:c,checkerLookupMs:u,traversalMs:d,...m?FL(m):{}}))}semanticCalleeForCallNode(t,n,i,r,o,s,a,l){let c=l?xe.now():0,u=PL(i,ha(n,r));if(l&&(l.callerLookupMs+=xe.now()-c),!u)return null;if(s&&!s.has(u.symbolId))return l&&(l.skippedUnrequestedCallers+=1),null;let d=r.expression,m=this.compilerSymbolForExpression(t,d,l);m.incomplete&&a?.add(u.symbolId);let f=m.symbol,p=null;if(f)if(l&&(l.targetSymbolHits+=1),o.has(f))l&&(l.compilerSymbolCacheHits+=1),p=o.get(f)??null;else{l&&(l.compilerSymbolCacheMisses+=1);let g=l?xe.now():0;p=this.definitionFromCompilerSymbol(f,l),l&&(l.targetLookupMs+=xe.now()-g),o.set(f,p)}else l&&(l.targetMisses+=1);return p?{callerId:u.symbolId,target:{symbol:p.symbol,file:p.file,line:p.line,callsiteLine:ha(n,r)}}:null}compilerSymbolForExpression(t,n,i){let r=!1,o=i?xe.now():0,s=ru(()=>t.getSymbolAtLocation(n),()=>{r=!0});if(i&&(i.expressionSymbolMs+=xe.now()-o),s)return{symbol:s,incomplete:!1};i&&(i.typeFallbacks+=1);let a=!1,l=i?xe.now():0,c=ru(()=>t.getTypeAtLocation(n).getSymbol(),()=>{a=!0});return i&&(i.typeSymbolMs+=xe.now()-l),{symbol:c,incomplete:!c&&(r||a)}}compilerCheckerForSourceFile(t){let n=t.getProject(),i=this.compilerCheckerCache.get(n);return i||(i=n.getTypeChecker().compilerObject,this.compilerCheckerCache.set(n,i)),i}};function su(e){let t=[],n=e.getDefaultImport();n&&t.push({identifier:n,importedName:"default",localName:n.getText(),kind:"default",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});let i=e.getNamespaceImport();i&&t.push({identifier:i,importedName:"*",localName:i.getText(),kind:"namespace",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});for(let r of e.getNamedImports()){let o=r.getNameNode(),a=r.getAliasNode()??(o.getKindName()==="Identifier"?o:null);t.push({identifier:a,importedName:o.getText(),localName:a?.getText()??o.getText(),kind:"named",isTypeOnly:r.isTypeOnly()||(e.getImportClause()?.isTypeOnly()??!1)})}return t.length===0&&t.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),t}function EL(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 wL(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function LL(e){for(let t=e;t;t=t.getParent())if(t.getKindName()==="ImportDeclaration")return!0;return!1}function DL(e,t,n){let i=e.get(t);i||(i=[],e.set(t,i)),i.push(n)}function ML(e){let t=new Set;for(let n of e.getImportDeclarations())for(let i of su(n))i.localName&&t.add(i.localName);return t}function PL(e,t){let n=null;for(let i of e)t<i.startLine||t>i.endLine||(!n||i.startLine>=n.startLine)&&(n=i);return n}function ha(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line}function Xg(e,t,n){return t===e.relativePath&&n>=e.startLine&&n<=e.endLine}function Qg(e){return e.symbol.includes("#")?Bt(e.symbol)==="type"&&e.relativePath.endsWith(".d.ts"):!1}function TL(){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 FL(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 Zg(){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 eh(e){return{...e,scanMs:Math.round(e.scanMs),packageRefsMs:Math.round(e.packageRefsMs),semanticRefsMs:Math.round(e.semanticRefsMs),hierarchyMs:Math.round(e.hierarchyMs)}}function kL(e,t,n){for(let i of t){let r=e.get(i)??[];r.push(...n),e.set(i,r)}}function NL(e){let t=new Set,n=[];for(let i of e){let r=`${i.symbol}|${i.file}|${i.line}|${i.callsiteLine??""}`;t.has(r)||(t.add(r),n.push(i))}return n}function th(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var OL=12e4,$L=5;function sh(e,t,n={}){let i=new au(e,n),r=null,o=null,s=process.env.CODEBASEIQ_SKIP_WATCH_SERVICE==="1",a=()=>(r??=nh(e,t),r),l=(d,m,f)=>{if(s)return f();try{return m(i.request(d))}catch{return s=!0,f()}},c=(d,m)=>l({kind:"references",definitions:[...d],...m?.exact?{exact:!0}:{}},f=>oh(f),()=>a().referencesForDefinitions?.(d,m)??new Map(d.map(f=>[f.symbolId,a().referencesFor(f)]))),u=d=>l({kind:"callees",definitions:[...d]},m=>oh(m),()=>a().calleesForDefinitions?.(d)??new Map(d.map(m=>[m.symbolId,a().calleesFor(m)])));return{language:"typescript",availability:()=>(o??=l({kind:"availability"},UL,()=>a().availability()),o),importUsage:d=>l({kind:"import-usage",file:d},m=>m,()=>a().importUsage(d)),referencesFor:d=>ih(c([d]),d,"reference"),referencesForDefinitions:c,referenceFragmentsForFiles:d=>l({kind:"reference-fragments",files:[...d]},m=>HL(m),()=>a().referenceFragmentsForFiles?.(d)??new Map),calleesFor:d=>ih(u([d]),d,"callee"),calleesForDefinitions:u,signatureFor:d=>l({kind:"signature",definition:d},zL,()=>a().signatureFor(d)),dispose:()=>r?.dispose?.()}}function ih(e,t,n){if(!e.has(t.symbolId))throw new Error(`TypeScript ${n} evidence is incomplete for ${t.symbol}.`);return e.get(t.symbolId)}var au=class{constructor(t,n={}){this.db=t;this.runtime=n.runtime??KL,this.timeoutMs=n.timeoutMs??qL(),this.mailboxLimits=n.mailboxLimits??{},this.cacheDir=BL(t.config.dbPath),this.projectRoot=Jm(t.config.projectRoot)}db;runtime;timeoutMs;cacheDir;projectRoot;mailboxLimits;request(t){let n=Xm(this.cacheDir),i=df(this.cacheDir),r=Wl(n.statePath);if(!rh(r,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,l=(this.runtime.monotonicNow??en)()+this.timeoutMs,c=sf(),u=Ar("typescript-semantic-v4",{generation:o,profileEnvironment:c,request:t}),d=_r(u),m=xs(i,{mailboxVersion:Vi,operationKey:u,clientId:this.runtime.randomId(),enqueuedAtMs:s,deadlineAtMs:a,protocolVersion:Rs,id:d,generation:o,profileEnvironment:c,request:t},{nowMs:s,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??en)()<=l;){if(_L(m.responsePath))return jL(Zt(m.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript semantic mailbox response"}),d,o,u);let f=Wl(n.statePath);if(!rh(f,this.projectRoot,this.runtime))throw new Error("TypeScript semantic service stopped while processing a request.");this.runtime.sleep($L)}throw new Error(`TypeScript semantic service timed out after ${this.timeoutMs}ms.`)}};function rh(e,t,n){let i=e?.processIdentity?n.readProcessIdentity?.(e.pid):null;return e!==null&&e.projectRoot===t&&e.typescriptSemantic?.protocolVersion===Rs&&n.isProcessAlive(e.pid)&&(!e.processIdentity||i!=null&&hs(e.processIdentity,i))}function jL(e,t,n,i){let r=JSON.parse(e);if(r.protocolVersion!==Rs||r.id!==t||r.operationKey!==i||r.ok===!0&&r.generation!==n)throw new Error("TypeScript semantic service wrote an incompatible response.");if(r.ok===!0)return r.response;throw new Error(typeof r.error=="string"?r.error:"TypeScript semantic service request failed.")}function oh(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid numeric map.");return new Map(e)}function HL(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid string map.");return new Map(e)}function UL(e){let t=Bg(e);if(!t)throw new Error("TypeScript semantic service wrote invalid availability.");return t}function zL(e){if(e!==null&&typeof e!="string")throw new Error("TypeScript semantic service wrote an invalid signature.");return e}function qL(){let e=Number(process.env.SCIP_TYPESCRIPT_SEMANTIC_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:OL}var KL={now:Date.now,monotonicNow:en,randomId:AL,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:Gi,readProcessIdentity:Wi};var lu=new pa;Zm({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>lu.clear(e)});ef({name:"semantic-provider",close:e=>lu.clear(e)});function wi(e,t){let n=Ge(t)??"typescript";return lu.getOrCreate(e,n,()=>n==="rust"?Fg(e.config.projectRoot,{sourceImportUsageResolver:{importUsageFacts:i=>Jp(e,i)},calleeSymbolResolver:Vp(e),sourceZeroCalleeOracle:i=>GL(e,i),scipOccurrenceCalleeOracle:i=>_g(e,i)}):sh(e,t))}function Ge(e){return e?ye(e)==="rust"?"rust":Gn(e)?"typescript":null:"typescript"}function GL(e,t){let n=te(e,t.relativePath);if(!n||n.language!=="rust")return!1;let i=n.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine&&r.name===t.leaf)??n.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine);return i?!n.callSites.some(r=>r.line>=i.startLine&&r.line<=i.endLine):!1}var WL=/^[A-Za-z_][A-Za-z0-9_]*$/,ah=/\bDefault::default\b/g,VL=/^\.\.\s*Default::default\b/;function lh(e,t){let n=new Map,i=new Map;for(let r of t){let o=cu(e,r,i);o!==null&&n.set(r.symbolId,o)}return n}function cu(e,t,n=new Map){let i=YL(t.symbol);if(!i)return null;let r=As(e,[t.symbolId]);if(r.length===0)return null;let o=new RegExp(`(^|[^A-Za-z0-9_])${Oe(i)}::default\\b`,"g"),s=new RegExp(`(^|[^A-Za-z0-9_])${Oe(i)}\\s*$`),a=JL(e,t.symbolId),l=[];for(let c of r){let u=XL(e,c.relative_path,n);if(u===null)return null;let d=u.split(/\r?\n/),m=0,f=[],p=0;for(let g=c.chunk_start;g<=c.chunk_end&&g<d.length;g+=1){let b=d[g]??"",v=new Set;o.lastIndex=0;let y;for(;y=o.exec(b);)l.push({file:c.relative_path,line:g,column:y.index+y[1].length+i.length+2}),p+=1;for(let I=0;I<b.length;I+=1){let E=VL.exec(b.slice(I));if(E){if(a&&f.includes(m)){let x=I+E[0].lastIndexOf("default");l.push({file:c.relative_path,line:g,column:x}),v.add(x),p+=1}I+=E[0].length-1;continue}let S=b[I];if(S==="{"){let x=s.test(b.slice(0,I));m+=1,x&&f.push(m);continue}if(S==="}")for(m=Math.max(0,m-1);f.length>0&&f[f.length-1]>m;)f.pop()}for(ah.lastIndex=0;y=ah.exec(b);){let I=y.index+9;if(!v.has(I))return null}}if(p===0)return null}return aa(l)}function JL(e,t){return e.get("SELECT 1 AS present FROM mentions WHERE symbol_id = ? AND role = 1 LIMIT 1",t)?.present===1}function YL(e){let t=/impl#\[([^\]]+)\]\[Default\]default\(\)\./.exec(e)?.[1]??null;return!t||!WL.test(t)?null:t}function XL(e,t,n){if(n.has(t))return n.get(t)??null;let i=e.get("SELECT text FROM documents WHERE relative_path = ?",t),r=typeof i?.text=="string"?i.text:QL(e,t);return n.set(t,r),r}function QL(e,t){try{return rt(e.config.projectRoot,t,{inputKind:"indexed Rust source file"})}catch(n){if(!ot(n))throw n;return null}}var ya=new WeakMap;function ph(e){ya.delete(e)}function gh(e){let t=ya.get(e);return{incompleteSymbolIds:new Set(t?.incompleteSymbolIds),unavailableSymbolIds:new Set(t?.unavailableSymbolIds)}}function mu(e,t){if(t.incompleteSymbolIds.size===0&&t.unavailableSymbolIds.size===0)return;let n=ya.get(e)??{incompleteSymbolIds:new Set,unavailableSymbolIds:new Set};for(let i of t.incompleteSymbolIds)n.incompleteSymbolIds.add(i);for(let i of t.unavailableSymbolIds)n.unavailableSymbolIds.add(i);ya.set(e,n)}var ZL="typescript-import-usage-v1",eD="typescript-signatures-v1",uu=Fe("semantic-prefetched-callees",{clearGroups:["whole-project","source-file","semantic-provider"]}),ch=Br({kind:"semantic-import-usage",invalidation:Ye("semantic-import-usage"),serialize:e=>JSON.stringify(e),deserialize:Eh}),uh=Br({kind:"semantic-signatures",invalidation:Ye("semantic-signatures"),serialize:e=>JSON.stringify(e),deserialize:lD}),dh=Ct({kind:"typescript-import-usage",invalidation:Ye("typescript-import-usage"),serialize:e=>JSON.stringify(e),deserialize:Eh}),mh=Ct({kind:"typescript-signatures",invalidation:Ye("typescript-signatures"),serialize:e=>JSON.stringify(e),deserialize:cD});function Ot(e){let t=new Map,n=new Set;return{capability:(i,r)=>wh(e,i,r),importUsage:i=>nD(e,i),references:i=>bh(e,i),materializeReferences:(i,r)=>vh(e,i,t,n,r),callerMap:i=>iD(e,i,t,n),calleeMap:i=>xh(e,i),signature:i=>sD(e,i)}}function tD(e,t){if(t.size===0)return;let n=uu.get(e,()=>new Map);for(let[i,r]of t)n.set(i,[...r])}function hh(e,t){if(!uu.has(e))return{hits:[],misses:[...t]};let n=uu.get(e,()=>new Map),i=[],r=[];for(let o of t)n.has(o.symbolId)?i.push({definition:o,callees:n.get(o.symbolId)??[]}):r.push(o);return{hits:i,misses:r}}function ho(e,t){return Ot(e).importUsage(t)}function nD(e,t){if(Ge(t)==="typescript"){let o="fallback",s=0,a=0,l=0,c=0;return B("typescript.import-usage.materialize",()=>{let u=Ur(e,t,ZL);if(u?.key){s=1;let m=dh.read(e,t,u.key);if(m)return o="hit",a=1,m;l=1;let f=wn(e,t);if(!f)return o="unavailable",[];let p=f.importUsage(t);return dh.write(e,t,u.key,p),o="computed",p}c=1;let d=wn(e,t);return d?(o="direct-fallback",d.importUsage(t)):(o="unavailable",[])},()=>({state:o,eligible:s,cacheHits:a,cacheMisses:l,fallbacks:c}))}let n=Ih(e,"semantic-import-usage",t);if(n){let o=ch.read(e,t,n);if(o)return o}let i=wn(e,t);if(!i)return[];let r=i.importUsage(t);return n&&ch.write(e,t,n,r),r}function yh(e,t){return Ot(e).references(t)}function bh(e,t){let n=cu(e,t);if(n)return n;let i=Zp(e,t);if(i)return i;let r=wn(e,t.relativePath);return r?r.referencesFor(t):[]}function Sh(e,t){let n=Ln(e,t),i=n.incompleteSymbolIds.size+n.unavailableSymbolIds.size;if(i>0)throw new Error(`Exact semantic caller evidence is incomplete for ${i} definition(s).`);return n.callers}function Ln(e,t,n=i=>wi(e,i)){let i=new Map,r=new Set,o=new Set,s=new Map;for(let l of t){let c=Ge(l.relativePath);if(!c)continue;let u;try{u=n(l.relativePath)}catch{o.add(l.symbolId);continue}if(!u.availability().available){o.add(l.symbolId);continue}if(c==="typescript"){let d=s.get(u)??[];d.push(l),s.set(u,d);continue}du(e,i,l,bh(e,l))}for(let[l,c]of s){let u=rc(e,c,n),d=u?.references??(l.referencesForDefinitions?l.referencesForDefinitions(c,{exact:!0}):new Map(c.map(m=>[m.symbolId,l.referencesFor(m)])));!u&&Ae()&&ic(e,c,d,n);for(let m of c){if(!d.has(m.symbolId)){r.add(m.symbolId);continue}du(e,i,m,d.get(m.symbolId)??[])}}let a={callers:i,incompleteSymbolIds:r,unavailableSymbolIds:o};return mu(e,a),a}function iD(e,t,n=new Map,i=new Set){let r=new Map,o=vh(e,t,n,i),s=0;return B("semantic.callers.from-references",()=>{for(let a of t)s+=du(e,r,a,n.get(a.symbolId)??[])},()=>({definitions:t.length,materialized:o.definitions,inMemoryHits:o.inMemoryHits,incompleteInMemoryHits:o.incompleteInMemoryHits,resultRows:r.size,callerFiles:s})),r}function vh(e,t,n,i,r={}){let o=Cn(e),s=[],a=[],l=[],c=0,u=0,d=0,m=0,f=0,p=0,g=0,h=0,b=0,v=0,y=0,I=0,E=[],S=new Map,x=t.filter(L=>Ge(L.relativePath)==="typescript"&&!n.has(L.symbolId)&&!i.has(L.symbolId)),C=rc(e,x,L=>wi(e,L));if(C){b=x.length,v=C.cacheHits,y=C.cacheMisses,I=C.computedFiles;for(let L of x)n.set(L.symbolId,C.references.get(L.symbolId)??[])}if(B("semantic.references.cache-scan",()=>{for(let[L,w]of ra(t)){let R=[];for(let D of w)n.has(D.symbolId)?u+=1:i.has(D.symbolId)?h+=1:R.push(D);if(R.length===0){g+=1;continue}let M=rD(e,o,L);if(!M){for(let D of R)Ge(D.relativePath)||(c+=1),l.push(D);continue}p+=1;let _=gf(e,L,M);for(let D of R){let P=_.get(D.symbol)??null;if(P!==null){let k=oD(P);if(k){d+=1,n.set(D.symbolId,k);continue}m+=1}a.push({definition:D,cacheFingerprint:M})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:c,cacheHits:d,parseFailures:m,misses:a.length,unkeyed:l.length,inMemoryHits:u,incompleteInMemoryHits:h,fullyInMemoryFiles:g,cacheReadFiles:p})),a.length>0||l.length>0){E=[...l,...a.map(L=>L.definition)],S=B("semantic.references.compute-misses",()=>{let L=ba(e,E,r);return f=L.size,L},()=>({definitions:E.length,misses:a.length,unkeyed:l.length,rows:f}));for(let L of E)S.has(L.symbolId)?(n.set(L.symbolId,S.get(L.symbolId)??[]),i.delete(L.symbolId)):i.add(L.symbolId);for(let{definition:L,cacheFingerprint:w}of a)S.has(L.symbolId)&&wh(e,"semantic-references",L.relativePath).available&&s.push({relativePath:L.relativePath,symbol:L.symbol,projectFingerprint:w,payload:JSON.stringify(S.get(L.symbolId)??[])})}return s.length>0&&B("semantic.references.cache-write",()=>hf(e,s),()=>({entries:s.length})),S.size>0&&ic(e,E,S,L=>wi(e,L)),{definitions:t.length,inMemoryHits:u,incompleteInMemoryHits:h,cacheHits:d,misses:a.length,unkeyed:l.length,skippedUnsupportedLanguage:c,parseFailures:m,computed:f,incomplete:i.size,cacheWrites:s.length,fragmentDefinitions:b,fragmentCacheHits:v,fragmentCacheMisses:y,fragmentComputedFiles:I}}function rD(e,t,n){if(!t)return null;let i=Ge(n);return i==="typescript"?zt(JSON.stringify({kind:"semantic-references",language:i,schema:"typescript-references-v2-incomplete-scan",projectFingerprint:t})):i==="rust"?zt(JSON.stringify({kind:"semantic-references",language:i,engine:Ri(e.config.projectRoot),projectFingerprint:t})):null}function ba(e,t,n={}){let i=Ae(),r=new Map,o=0,s=0,a=0,l=0,c=0,u=0,d=0,m=0,f=0;return B("semantic.references.provider-loop",()=>{let p=lh(e,t),g=Qp(e,t),h=new Map,b=n.prefetchCallees?new Map:null,v=[];for(let I of t){let E,S=()=>(E??=wn(e,I.relativePath),E);if(b){let w=S();if(w?.referencesAndCalleesForDefinitions){let R=b.get(w);R?R.push(I):b.set(w,[I]),f+=1}}let x=p.get(I.symbolId);if(x){a+=1,l+=x.length,go(r,I.symbolId,x,i,w=>{d+=1,m+=w});continue}let C=g.get(I.symbolId);if(C){c+=1,u+=C.length,go(r,I.symbolId,C,i,w=>{d+=1,m+=w});continue}let L=S();if(!L){i&&(s+=1);continue}if(i&&(o+=1),L.referencesForDefinitions){let w=h.get(L);w?w.push(I):h.set(L,[I])}else v.push({provider:L,definition:I})}let y=new Set;if(b)for(let[I,E]of b){if(!I.referencesAndCalleesForDefinitions)continue;let S=h.get(I)??[],x=I.referencesAndCalleesForDefinitions(S,E);y.add(I),tD(e,x.callees);for(let C of S){if(!x.references.has(C.symbolId))continue;let L=x.references.get(C.symbolId)??[];go(r,C.symbolId,L,i,w=>{d+=1,m+=w})}}for(let[I,E]of h){if(y.has(I))continue;let S=I.referencesForDefinitions(E);for(let x of E){if(!S.has(x.symbolId))continue;let C=S.get(x.symbolId)??[];go(r,x.symbolId,C,i,L=>{d+=1,m+=L})}}for(let{provider:I,definition:E}of v){let S=I.referencesFor(E);go(r,E.symbolId,S,i,x=>{d+=1,m+=x})}return r},()=>({definitions:t.length,providerHits:o,providerMisses:s,rustDefaultFastPathRows:a,rustDefaultFastPathReferences:l,rustScipOccurrenceFastPathRows:c,rustScipOccurrenceFastPathReferences:u,prefetchCalleeDefinitions:f,definitionsWithReferences:d,referenceCount:m,rows:r.size}))}function Sa(e,t,n={}){let i=ba(e,t,n),r=Ch(e,t,i);return mu(e,r),{rows:i,...r}}function go(e,t,n,i,r){e.set(t,n),i&&n.length>0&&r(n.length)}function du(e,t,n,i){let r=0;for(let o of i){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&&(r+=1)}return r}function oD(e){try{return JSON.parse(e)}catch{return null}}function va(e,t,n){let i=xh(e,t,n),r=Ch(e,t,i,n);return mu(e,r),{rows:i,...r}}function Ch(e,t,n,i){let r=new Set,o=new Set;for(let s of t)if(!(n.has(s.symbolId)||!Ge(s.relativePath)))try{(i?i(s.relativePath):wi(e,s.relativePath)).availability().available?r.add(s.symbolId):o.add(s.symbolId)}catch{o.add(s.symbolId)}return{incompleteSymbolIds:r,unavailableSymbolIds:o}}function xh(e,t,n){let i=Ae(),r=new Map,o=0,s=0,a=0,l=0;return B("semantic.callees.provider-loop",()=>{let c=new Map,u=[];for(let d of t){let m=n?n(d.relativePath):wn(e,d.relativePath);if(m&&!m.availability().available){i&&(s+=1);continue}if(!m){i&&(s+=1);continue}i&&(o+=1);let f=d;if(m.calleesForDefinitions){let p=c.get(m);p?p.push(f):c.set(m,[f])}else u.push({provider:m,definition:f})}for(let[d,m]of c){let f=d.calleesForDefinitions(m);for(let p of m){if(!f.has(p.symbolId))continue;let g=f.get(p.symbolId)??[];fh(r,p.symbolId,g,i,h=>{a+=1,l+=h})}}for(let{provider:d,definition:m}of u){let f=d.calleesFor(m);fh(r,m.symbolId,f,i,p=>{a+=1,l+=p})}return r},()=>({definitions:t.length,providerHits:o,providerMisses:s,definitionsWithCallees:a,calleeCount:l,rows:r.size}))}function fh(e,t,n,i,r){e.set(t,n),i&&n.length>0&&r(n.length)}function Rh(e,t){return Ot(e).signature(t)}function sD(e,t){if(Ge(t.relativePath)==="typescript"){let s="fallback",a=0,l=0,c=0,u=0;return B("typescript.signature.materialize",()=>{let d=Ur(e,t.relativePath,eD);if(d?.key){a=1;let f=mh.read(e,t.relativePath,d.key)??{};if(Object.prototype.hasOwnProperty.call(f,t.symbol))return s="hit",l=1,f[t.symbol]??null;c=1;let p=wn(e,t.relativePath);if(!p)return s="unavailable",null;let g=p.signatureFor(t);return mh.write(e,t.relativePath,d.key,{...f,[t.symbol]:g}),s="computed",g}u=1;let m=wn(e,t.relativePath);return m?(s="direct-fallback",m.signatureFor(t)):(s="unavailable",null)},()=>({state:s,eligible:a,cacheHits:l,cacheMisses:c,fallbacks:u}))}let n=Ih(e,"semantic-signatures",t.relativePath),i=aD(t);if(n){let s=uh.read(e,i,n);if(s)return s.signature}let r=wn(e,t.relativePath);if(!r)return null;let o=r.signatureFor(t);return n&&uh.write(e,i,n,{signature:o}),o}function Ih(e,t,n){let i=Cn(e);if(!i)return null;let r=Ge(n);return r!=="rust"?null:zt(JSON.stringify({kind:t,language:r,engine:Ri(e.config.projectRoot),projectFingerprint:i}))}function aD(e){return`${e.relativePath}\0${e.symbol}`}function Eh(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:null}catch{return null}}function lD(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 cD(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 wh(e,t,n){let i=Ge(n);if(!i)return{slot:t,language:"typescript",available:!1,reason:"semantic evidence is only available for TypeScript or Rust files"};try{return{slot:t,language:i,...wi(e,n).availability()}}catch(r){return{slot:t,language:i,available:!1,reason:r instanceof Error?r.message:String(r)}}}function wn(e,t){if(!Ge(t))return null;let n=wi(e,t);return n.availability().available?n:null}var ge={references:yh,referenceMap:ba,referenceEvidenceMap:Sa,callerMap:(e,t)=>Ot(e).callerMap(t),calleeMap:fu,calleeEvidenceMap:Lh};function fu(e,t,n={}){return Lh(e,t,n).rows}function Lh(e,t,n={}){let i=Ae(),r=new Map,o=hh(e,t),s=[],a=[],l=0,c=0,u=0,d=0,m=0,f=0,p=0,g=new Set,h=new Set;for(let{definition:S,callees:x}of o.hits)m+=1,r.set(S.symbolId,x),x.length>0&&(f+=1,p+=x.length);let b=uD(e,o.hits);if(b.entries.length>0&&B("semantic.callees.prefetch-cache-write",()=>ec(e,b.entries),()=>({entries:b.entries.length,sourceMissing:b.sourceMissing,skippedUnsupportedLanguage:b.skippedUnsupportedLanguage})),B("semantic.callees.cache-scan",()=>{for(let[S,x]of ra(o.misses)){if(!Ge(S)){i&&(l+=x.length);continue}let C=se(e,S);if(!C){i&&(c+=x.length),a.push(...x);continue}let L=Nt(e,S,C),w=Dh(e,S);if(!w){a.push(...x);continue}let R=pf(e,S,L,w);for(let M of x){let _=R.get(M.symbol)??null;if(_!==null){let D=mD(_);if(D){i&&(u+=1),r.set(M.symbolId,D);continue}i&&(d+=1)}s.push({def:M,contentHash:L,depsDigest:w})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:l,sourceMissing:c,cacheHits:u,parseFailures:d,misses:s.length,unkeyed:a.length,inMemoryHits:m,inMemoryRows:f,inMemoryCalleeCount:p,resultRows:r.size})),s.length===0&&a.length===0)return{rows:r,incompleteSymbolIds:g,unavailableSymbolIds:h};let v=[...a,...s.map(S=>S.def)],y=0,I=B("semantic.callees.compute-misses",()=>{let S=va(e,v,n.resolveProvider);for(let x of S.incompleteSymbolIds)g.add(x);for(let x of S.unavailableSymbolIds)h.add(x);return y=S.rows.size,S.rows},()=>({definitions:v.length,misses:s.length,unkeyed:a.length,rows:y}));for(let[S,x]of I)r.set(S,x);let E=s.filter(S=>I.has(S.def.symbolId)&&Ot(e).capability("semantic-callees",S.def.relativePath).available).map(S=>({relativePath:S.def.relativePath,symbol:S.def.symbol,contentHash:S.contentHash,depsDigest:S.depsDigest,payload:JSON.stringify(I.get(S.def.symbolId)??[])}));return E.length>0?B("semantic.callees.cache-write",()=>ec(e,E),()=>({entries:E.length})):B("semantic.callees.cache-write-skip",()=>{},()=>({reason:"provider-unavailable",misses:s.length})),{rows:r,incompleteSymbolIds:g,unavailableSymbolIds:h}}function uD(e,t){let n=[],i=new Map,r=0,o=0;for(let{definition:s,callees:a}of t){if(!Ge(s.relativePath)){o+=1;continue}if(!i.has(s.relativePath)){let c=se(e,s.relativePath),u=c?Dh(e,s.relativePath):null;i.set(s.relativePath,c&&u?{contentHash:Nt(e,s.relativePath,c),depsDigest:u}:null)}let l=i.get(s.relativePath);if(!l){r+=1;continue}n.push({relativePath:s.relativePath,symbol:s.symbol,contentHash:l.contentHash,depsDigest:l.depsDigest,payload:JSON.stringify(a)})}return{entries:n,sourceMissing:r,skippedUnsupportedLanguage:o}}var dD="typescript-callees-v3-incomplete-scan";function Dh(e,t){let n=Ge(t);if(n==="typescript")return Ur(e,t,dD)?.key??null;let i=pD(e,t);return n==="rust"?zt(JSON.stringify({kind:"semantic-callees",language:n,engine:Ri(e.config.projectRoot),positionMapping:"nearby-leaf-v2-callsite-line",depsDigest:i})):i}function mD(e){try{return JSON.parse(e)}catch{return null}}var fD=Hn("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function pD(e,t){return fD.get(e,t,()=>{let i=[...$e(e).get(t)??[]].sort().map(r=>`${r}:${Nt(e,r,se(e,r))}`);return zt(i.join("|"))})}function qX(e,t,n={}){let i=pe(e,t);if(!i)return[];let o=!_e(i.symbol)&&!e.isIgnored(i.relativePath)?[{relativePath:i.relativePath,line:i.startLine}]:[],s=Kn(e,i,{semantic:n.semantic,semanticEvidence:ge}).map(u=>({relativePath:u.file,line:u.line})),a=gD(e,i),l=new Set,c=[];for(let u of[...o,...s,...a]){let d=`${u.relativePath}:${u.line}`;l.has(d)||(l.add(d),c.push(u))}return c}function gD(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=hD(t.symbol);if(n.length===0)return[];let i=[];for(let r of me(e,{extensions:[".rb"],includeIgnored:!1})){let o=se(e,r);if(!o)continue;let s=o.split(`
52
+ `);for(let a=0;a<s.length;a++){let l=s[a]??"";n.some(c=>new RegExp(`@${c}\\b|\\b${c}:`).test(l))&&i.push({relativePath:r,line:a})}}return i}function hD(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,""),i=n.split("_").filter(Boolean),r=new Set;return n&&r.add(n),i.length>=1&&r.add(i[i.length-1]),i.length>=2&&r.add(i.slice(-2).join("_")),[...r]}import{statSync as yD}from"fs";function Li(e){let t=e.get("SELECT COUNT(*) as c FROM documents").c,n=e.get("SELECT COUNT(*) as c FROM global_symbols").c,i=e.get("SELECT COUNT(*) as c FROM mentions WHERE role = 1").c,r=e.get("SELECT COUNT(*) as c FROM mentions WHERE role != 1").c;return{documents:t,symbols:n,definitions:i,references:r,...bD(e.generation.databasePath)}}function bD(e){try{let t=yD(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function SD(e,t){return lc(e).filter(n=>vD({pattern:t,relativePath:n})).map(n=>({relativePath:n}))}function vD(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 i=vn(n.pattern),r=vn(n.relativePath);if(!/[*?]/.test(i))return r.includes(i);let o=i.includes("/")?i:`**/${i}`;return Ca(o.split("/"),r.split("/"))}function Ca(e,t){if(e.length===0)return t.length===0;let[n,...i]=e;return n==="**"?Ca(i,t)||t.length>0&&Ca(e,t.slice(1)):t.length===0||!CD(n??"",t[0]??"")?!1:Ca(i,t.slice(1))}function CD(e,t){let n="^";for(let i of e)i==="*"?n+="[^/]*":i==="?"?n+="[^/]":n+=xD(i);return n+="$",new RegExp(n).test(t)}function xD(e){return/[\\^$.*+?()[\]{}|]/.test(e)?`\\${e}`:e}function Ph(e,t,n){let i=[],r=[],o=new Map;for(let s of[...e].sort(n)){let a=s.channel??"default",l=t[a]??Number.MAX_SAFE_INTEGER,c=o.get(a)??0;if(c>=l){r.push(s);continue}i.push(s),o.set(a,c+1)}return{selected:i,omitted:r}}function xa(e,t,n,i,r=!1){let o=[...e],s=[],a=new Set,l=0;for(;o.length>0&&s.length<t;){let c=o.filter(m=>l+m.evidenceCharacters<=n||r&&s.length===0);if(c.length===0)break;let u=c.filter(m=>m.roles.includes("location")||m.roles.includes("definition")).sort(i);c.sort((m,f)=>Mh(f,a)-Mh(m,a)||i(m,f));let d=u[0]??c[0];s.push(d),l+=d.evidenceCharacters;for(let m of Th(d))a.add(m.key);o.splice(o.indexOf(d),1)}return{selected:s,omitted:o.sort(i)}}function Mh(e,t){let n=Th(e).reduce((o,s)=>o+(t.has(s.key)?0:s.weight),0),i=Math.max(0,8-e.priority)*20,r=Math.min(500,Math.ceil(e.evidenceCharacters/160));return n+i-r}function Th(e){return[...e.reasons.map(RD),...e.roles.map(t=>({key:`role:${t}`,weight:ID(t)})),{key:`file:${e.relativePath}`,weight:180},{key:`scope:${ED(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 RD(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 ID(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 ED(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}var Fh=64,kh=12;function pu(e,t,n={}){if(t.length===0)throw new Error("The source search pattern must not be empty.");let i=n.context??6;if(!Number.isSafeInteger(i)||i<0)throw new RangeError(`context must be a non-negative safe integer; received ${i}`);let r=n.limit??12;if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`limit must be a positive safe integer; received ${r}`);let o=n.regexp?Ss(t,"source search pattern",n.ignoreCase?"iu":"u"):null,s=n.ignoreCase?t.toLocaleLowerCase():t,a=zs(e,{scope:n.scope}),l=[],c=[];for(let h of a.files){let b=h.relativePath,v=DD(h.text);if(v.length===0)continue;let y=h.freshness.semantic.state!=="stale"&&h.freshness.semantic.basis!=="no-compiler-document"?W(e,b):[],I=te(e,b)?.callables??[],E=0;for(let S=0;S<v.length;S+=1){let x=v[S]??"",C=x.endsWith("\r")?x.slice(0,-1):x;if(!(o?o.test(C):(n.ignoreCase?C.toLocaleLowerCase():C).includes(s)))continue;E+=1;let w=Ke(y,S),R=wD(I,S),M=w&&!De(w.symbol)?w:null,_=M?.startLine??R?.startLine??w?.startLine??S,D=M?.endLine??R?.endLine??w?.endLine??S,P=eo(e,b,S,_,D);l.push({relativePath:b,focusLine:S,ownerSymbol:M?.symbol??null,ownerShort:M?A(M.symbol):R?.name??(w?A(w.symbol):null),ownerStartLine:P.startLine,ownerEndLine:P.endLine,fileKind:J(b),freshness:h.freshness})}E>0&&c.push({relativePath:b,matchingLines:E,returnedMatches:0,freshness:h.freshness})}l.sort(Ah);let u=l.length>Fh?Nh(l,Fh):l,d=r===Number.MAX_SAFE_INTEGER?l:n.ranking?Nh(l,r):l.slice(0,r),m=new Map(a.files.map(h=>[h.relativePath,h.text])),f=d.flatMap(h=>{let b=m.get(h.relativePath),v=b===void 0?null:LD(h.relativePath,b,h.focusLine,i);return v?[{...v,...h}]:[]}),p=new Map;for(let h of f)p.set(h.relativePath,(p.get(h.relativePath)??0)+1);for(let h of c)h.returnedMatches=p.get(h.relativePath)??0;let g=MD(c);return{pattern:t,mode:n.regexp?"regexp":"literal",identities:l,...u.length<l.length?{identityManifest:u}:{},identityCoverage:{mode:u.length===l.length?"complete":"bounded",returned:u.length,total:l.length,omitted:l.length-u.length},matches:f,matchingLines:l.length,matchingFiles:c.length,omittedMatches:Math.max(0,l.length-f.length),fileCoverage:c,scopeHints:g.slice(0,kh),omittedScopeHints:Math.max(0,g.length-kh),scannedFiles:a.files.length,textCoverage:{basis:"current-project-text-files",candidateFiles:a.candidateFiles,scannedTextFiles:a.files.length,scannedBytes:a.scannedBytes,skippedBinaryPaths:a.skippedBinaryPaths,skippedUnreadablePaths:a.skippedUnreadablePaths,skippedOversizedPaths:a.skippedOversizedPaths,semanticFiles:{aligned:a.files.filter(h=>h.freshness.semantic.state==="aligned").length,stale:a.files.filter(h=>h.freshness.semantic.state==="stale").length,unavailable:a.files.filter(h=>h.freshness.semantic.state==="unavailable").length}}}}function wD(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,i)=>n.endLine-n.startLine-(i.endLine-i.startLine)||n.startLine-i.startLine)[0]??null}function LD(e,t,n,i){let r=t.split(`
53
53
  `),o=t.endsWith(`
54
54
  `)?r.length-1:r.length;if(n<0||n>=o)return null;let s=Math.max(0,n-i),a=Math.min(o-1,n+i);return{relativePath:e,startLine:s,endLine:a,focusLine:n,source:r.slice(s,a+1).join(`
55
- `)}}function _D(e){if(e.length===0)return[];let t=e.split(`
55
+ `)}}function DD(e){if(e.length===0)return[];let t=e.split(`
56
56
  `);return e.endsWith(`
57
- `)&&t.pop(),t}function BD(e){let t=new Map;for(let n of e){let i=OD(n.relativePath),r=t.get(i)??{matchingLines:0,matchingFiles:0};r.matchingLines+=n.matchingLines,r.matchingFiles+=1,t.set(i,r)}return[...t.entries()].map(([n,i])=>({scope:n,...i})).sort((n,i)=>i.matchingLines-n.matchingLines||i.matchingFiles-n.matchingFiles||n.scope.localeCompare(i.scope))}function OD(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}function _h(e,t){let n=e.map((r,o)=>({...r,priority:Ia(r.fileKind),sequence:o,evidenceCharacters:1,roles:["search"],reasons:["search"],symbols:r.ownerSymbol?[r.ownerSymbol]:[],behaviorSignals:[]})),i=[];for(let r of[0,1,2]){let o=t-i.length;if(o===0)break;let s=n.filter(a=>Ia(a.fileKind)===r);i.push(...Ra(s,o,Number.MAX_SAFE_INTEGER,Bh).selected)}return i.map(({priority:r,sequence:o,evidenceCharacters:s,roles:a,reasons:l,symbols:c,behaviorSignals:u,...d})=>d)}function Bh(e,t){return Ia(e.fileKind)-Ia(t.fileKind)||+(t.ownerSymbol!==null)-+(e.ownerSymbol!==null)||e.relativePath.localeCompare(t.relativePath)||e.focusLine-t.focusLine}function Ia(e){switch(e){case"entry":case"source":case"worker":return 0;case"barrel":return 1;case"test":return 2}}var bu=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 So(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 mt(e){return new Set(So(e).flatMap(Su).filter(t=>t.length>=3))}function Su(e){let t=Ea(e);return t.length>4&&t.endsWith("e")?[t,t.slice(0,-1)]:[t]}function Ea(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")?Oh(t.slice(0,-2)):t.length>5&&t.endsWith("ing")?Oh(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 Oh(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}var $h=new WeakMap,jh=new WeakMap,Hh=new WeakMap,Uh=new WeakMap,zh=new WeakMap;function qh(e,t){let n=jh.get(e);n||(n=new Map,jh.set(e,n));let i=n.get(t);if(i)return i;let r=ae(e,t)?.rootNode;if(!r)return n.set(t,[]),[];let o=new Set;Wt(r,c=>{if(c.type!=="call_expression")return;let u=c.childForFieldName("function")??c.namedChild(0),d=/^([A-Za-z_$][\w$]*(?:\.Service)?)\.of$/u.exec(u?.text.replace(/\s+/gu,"")??"");d&&o.add(d[1])});let s=Ce(e,t).filter(c=>!!c.sourcePath),a=new Set;for(let c of o){let u=/^([A-Za-z_$][\w$]*)\.Service$/u.exec(c);if(u){for(let d of s)d.localName===u[1]&&a.add(d.sourcePath);continue}if(c==="Service"){W(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 l=xu([...a]).sort();return n.set(t,l),l}function Zn(e,t,n={}){let r=tn(e,t)?.filter(f=>!n.ranges||n.ranges.some(p=>f.line>=p.startLine&&f.line<=p.endLine));if(!r)return{targets:[],unresolvedCallsites:0};let o=Ce(e,t).filter(f=>!!f.sourcePath),s=tM(se(e,t)??""),a=ae(e,t)?.rootNode??null,l=a?jD(a):Kh(),c=new Map,u=rn(e),d=[],m=0;for(let f of r){if(!f.memberAccess)continue;let p=nn(t,u.get(f.calleeLeaf)??[]);if(n.excludeIndexedTargets!==!1&&qn(e,t,p,!0,f.calleeQualifier))continue;let g=f.calleeQualifier,h=ZD(e,t,f,o);if(h){d.push(h);continue}let b=$D(e,t,f,o,HD(l,f.calleeQualifier,f.line));if(b.length>0){d.push(...b);continue}let v=UD(e,t,f);if(v.length>0){d.push(...v);continue}let y=g?s.get(g)??g:null,E=(y?xu(o.filter(x=>(x.localName??x.importedName)===y).map(x=>x.sourcePath)):[]).flatMap(x=>{let C=c.get(x);return C||(C=At(e,x)??[],c.set(x,C)),C.filter(L=>L.name===f.calleeLeaf).map(L=>({file:x,callable:L}))});if(E.length!==1){m+=1;continue}let S=E[0];d.push({calleeLeaf:f.calleeLeaf,line:f.line,sourceFile:t,targetFile:S.file,targetStartLine:S.callable.startLine,targetEndLine:S.callable.endLine,resolution:"direct-import-receiver",strength:"candidate"})}return{targets:d,unresolvedCallsites:m}}function $D(e,t,n,i,r){let o=n.calleeQualifier;if(!o||!/^[A-Za-z_$][\w$]*$/u.test(o))return[];if(r.size!==1)return[];let s=[...r][0],a=xu(i.filter(u=>u.localName===s||u.importedName===s).map(u=>u.sourcePath));if(a.length!==1)return[];let l=a[0],c=GD(e,l,n.calleeLeaf);return c.map(u=>({calleeLeaf:u.name,line:n.line,sourceFile:t,targetFile:u.file,targetStartLine:u.startLine,targetEndLine:u.endLine,serviceFile:l,resolutionAlternativeCount:c.length,resolution:"imported-service-object-member",strength:"candidate"}))}function Kh(){return{declarations:new Map,callbacks:[]}}function jD(e){let t=Kh();return Wt(e,n=>{if(n.type==="variable_declarator"){let l=n.childForFieldName("name")??n.namedChild(0),c=n.childForFieldName("value")??n.namedChild(1);if(l?.type!=="identifier"||!c)return;let u=new Set;if(Wt(c,d=>{if(d.type!=="member_expression")return;let m=d.childForFieldName("object")??d.namedChild(0),f=d.childForFieldName("property")??d.namedChild(1);m?.type==="identifier"&&f?.text==="Service"&&u.add(m.text)}),u.size===1){let d=t.declarations.get(l.text)??[];d.push({line:n.startPosition.row,alias:[...u][0]}),t.declarations.set(l.text,d)}return}if(!["arrow_function","function_expression","generator_function"].includes(n.type))return;let i=n.childForFieldName("parameters")??n.childForFieldName("parameter");if(!i)return;let r=n.parent;for(;r&&r.type!=="call_expression";)r=r.parent;if(!r)return;let o=r.childForFieldName("function")??r.namedChild(0),s=/^([A-Za-z_$][\w$]*)\.Service\.use$/u.exec(o?.text??"");if(!s)return;let a=new Set;Wt(i,l=>{l.type==="identifier"&&a.add(l.text)}),a.size!==0&&t.callbacks.push({startLine:n.startPosition.row,endLine:n.endPosition.row,receivers:a,alias:s[1]})}),t}function HD(e,t,n){if(!t||!/^[A-Za-z_$][\w$]*$/u.test(t))return new Set;let i=new Set((e.declarations.get(t)??[]).filter(r=>r.line<=n).map(r=>r.alias));for(let r of e.callbacks)r.startLine<=n&&r.endLine>=n&&r.receivers.has(t)&&i.add(r.alias);return i}function UD(e,t,n){let i=n.calleeQualifier;if(!i||!/^[A-Za-z_$][\w$]*$/u.test(i))return[];let r=ae(e,t)?.rootNode;if(!r)return[];let o=zD(e,t,r,n.line,n.calleeLeaf,i),s=o?KD(o,i):null;if(!s)return[];if(!qD(s))return[];let a=(At(e,t)??[]).filter(f=>f.startLine<=s.startPosition.row&&f.endLine>=s.endPosition.row).sort((f,p)=>f.endLine-f.startLine-(p.endLine-p.startLine))[0];if(!a)return[];let l=W(e,t).filter(f=>f.isFunctionLike&&f.leaf===a.name);if(l.length!==1)return[];let c=l[0],u=Uh.get(e);u||(u=new Map,Uh.set(e,u));let d=`${c.symbol}\0${n.calleeLeaf}`,m=u.get(d);if(!m){let f=[];for(let p of zr(e,c)){let g=ae(e,p.file)?.rootNode;if(!g)continue;let h=g.descendantsOfType("call_expression").filter(y=>y.startPosition.row>p.line||y.endPosition.row<p.line?!1:(y.childForFieldName("function")??y.namedChild(0))?.text.replace(/\s+/gu,"").replace(/<[^<>]*>$/u,"").match(/[A-Za-z_$][\w$]*$/u)?.[0]===c.leaf);if(h.length!==1)continue;let v=h[0].childForFieldName("arguments")?.namedChildren.find(y=>Di(y).type==="object");if(v)for(let y of Di(v).namedChildren){if(y.type==="shorthand_property_identifier"&&y.text===n.calleeLeaf){f.push(...wa(e,p.file,n.calleeLeaf,y,y));continue}if(y.type!=="pair")continue;let I=y.childForFieldName("key")??y.namedChild(0),E=y.childForFieldName("value")??y.namedChild(1);La(I?.text)!==n.calleeLeaf||!E||f.push(...wa(e,p.file,n.calleeLeaf,E,y))}}m=f.filter((p,g,h)=>h.findIndex(b=>b.file===p.file&&b.startLine===p.startLine&&b.endLine===p.endLine&&b.name===p.name)===g),u.set(d,m)}return m.map(f=>({calleeLeaf:f.name,line:n.line,sourceFile:t,targetFile:f.file,targetStartLine:f.startLine,targetEndLine:f.endLine,resolutionAlternativeCount:m.length,resolution:"factory-callback-member",strength:m.length===1?"exact":"candidate"}))}function zD(e,t,n,i,r,o){let s=Hh.get(e);s||(s=new Map,Hh.set(e,s));let a=s.get(t);if(!a){a=new Map;for(let l of n.descendantsOfType("call_expression")){let c=l.childForFieldName("function")??l.namedChild(0),u=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(c?.text.replace(/\s+/gu,"")??"");if(u)for(let d=l.startPosition.row;d<=l.endPosition.row;d+=1){let m=`${d}\0${u[1]}\0${u[2]}`,f=a.get(m);(!f||l.endIndex-l.startIndex<f.endIndex-f.startIndex)&&a.set(m,l)}}s.set(t,a)}return a.get(`${i}\0${o}\0${r}`)??null}function qD(e){return e.descendantsOfType("return_statement").some(t=>{let n=t.childForFieldName("argument")??t.namedChild(0);return!!(n&&Di(n).type==="object")})}function KD(e,t){let n=e.parent;for(;n;){if(/(?:function|method|lambda)/u.test(n.type)||n.type==="arrow_function"){let i=n.childForFieldName("parameters")??n.childForFieldName("parameter"),r=!1;if(i&&Wt(i,o=>{o.type==="identifier"&&o.text===t&&(r=!0)}),r)return n}n=n.parent}return null}function wa(e,t,n,i,r){if(i.type==="identifier")return(At(e,t)??[]).filter(l=>l.name===i.text).map(l=>({...l,file:t}));let o=vu(e,t,i.text);if(o.length>0)return o;if(!Cu(i))return[];let a=(At(e,t)??[]).filter(l=>l.startLine>=r.startPosition.row&&l.endLine<=r.endPosition.row&&(l.name===n||l.name.startsWith("source@"))).sort((l,c)=>l.endLine-l.startLine-(c.endLine-c.startLine))[0];return[a?{...a,file:t}:{name:n,file:t,startLine:r.startPosition.row,endLine:r.endPosition.row}]}function GD(e,t,n){let i=zh.get(e);i||(i=new Map,zh.set(e,i));let r=`${t}\0${n}`,o=i.get(r);if(o)return o;let s=JD(e,t).flatMap(a=>WD(e,a,t,n));return i.set(r,s),s}function WD(e,t,n,i){let r=ae(e,t)?.rootNode,o=At(e,t)??[];if(!r)return[];let s=YD(e,t,n);if(s.size===0)return[];let a=new Set,l=[],c=[],u=[];return Wt(r,m=>{if(VD(m,s)){if(m.type==="pair"){let f=m.childForFieldName("key")??m.namedChild(0),p=m.childForFieldName("value")??m.namedChild(1);if(La(f?.text)!==i||!p)return;if(p.type==="identifier")a.add(p.text);else if(Cu(p))l.push({name:i,startLine:m.startPosition.row,endLine:m.endPosition.row});else{let g=XD(e,t,p.text),h=vu(e,t,p.text);if(g.length>0)u.push(...g);else if(h.length>0)u.push(...h);else{let b=QD(m);b&&c.push(b)}}return}m.type==="shorthand_property_identifier"&&m.text===i&&a.add(i)}}),[...o.filter(m=>a.has(m.name)).map(m=>({...m,file:t})),...l.map(m=>({...m,file:t})),...c.map(m=>({...m,file:t})),...u].filter((m,f,p)=>p.findIndex(g=>g.file===m.file&&g.name===m.name&&g.startLine===m.startLine&&g.endLine===m.endLine)===f)}function VD(e,t){let n=e,i=null;for(;n;){if(n.type==="object"&&(i=n),n.type==="call_expression"){if(!i)return!1;let r=n.childForFieldName("function")??n.namedChild(0);return r?t.has(r.text.replace(/\.of$/u,""))&&r.text.endsWith(".of"):!1}n=n.parent}return!1}function JD(e,t){let n=$h.get(e);n||(n=new Map,$h.set(e,n));let i=n.get(t);if(i)return i;let r=new Set([t]),o=W(e,t).filter(a=>a.leaf==="Service"&&a.isTypeLike);for(let a of o)for(let l of zr(e,a))r.add(l.file);let s=[...r].sort();return n.set(t,s),s}function YD(e,t,n){let i=new Set;Tt(t,n)&&i.add("Service");for(let r of Ce(e,t)){if(!r.sourcePath||!Tt(r.sourcePath,n))continue;if(r.kind==="namespace"&&r.localName){i.add(`${r.localName}.Service`);continue}(r.importedName==="default"?r.localName:r.importedName)==="Service"?i.add(r.localName??r.importedName):r.localName&&r.importedName!=="default"&&i.add(`${r.localName}.Service`)}return i}function vu(e,t,n){let i=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(n.replace(/\s+/gu,""));if(!i)return[];let r=ae(e,t)?.rootNode;if(!r)return[];let o=Gh(r,i[1]),s=o?Wh(o):null;if(!s)return[];let a=s.childForFieldName("function")??s.namedChild(0),l=a?Vh(e,t,a.text):[];if(l.length!==1)return[];let c=l[0],u=ae(e,c.relativePath)?.rootNode;if(!u)return[];let d=Jh(u,c.startLine,c.endLine);if(!d)return[];let m=[];for(let f of d.descendantsOfType("return_statement")){let p=f.childForFieldName("argument")??f.namedChild(0);if(!p)continue;let g=Di(p);if(g.type==="object")for(let h of g.namedChildren){if(h.type==="shorthand_property_identifier"&&h.text===i[2]){for(let y of At(e,c.relativePath)??[])y.name===i[2]&&m.push({...y,file:c.relativePath});continue}if(h.type!=="pair")continue;let b=h.childForFieldName("key")??h.namedChild(0),v=h.childForFieldName("value")??h.namedChild(1);if(!(La(b?.text)!==i[2]||!v))if(v.type==="identifier")for(let y of At(e,c.relativePath)??[])y.name===v.text&&m.push({...y,file:c.relativePath});else Cu(v)&&m.push({name:i[2],startLine:h.startPosition.row,endLine:h.endPosition.row,file:c.relativePath})}}return m.filter((f,p,g)=>g.findIndex(h=>h.file===f.file&&h.name===f.name&&h.startLine===f.startLine&&h.endLine===f.endLine)===p)}function XD(e,t,n){let i=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(n.replace(/\s+/gu,""));if(!i)return[];let r=ae(e,t)?.rootNode;if(!r)return[];let o=Gh(r,i[1]),s=o?Wh(o):null,a=s?.childForFieldName("function")??s?.namedChild(0),l=a?Vh(e,t,a.text):[];if(l.length!==1||!s)return[];let c=l[0],u=ae(e,c.relativePath)?.rootNode;if(!u)return[];let d=Jh(u,c.startLine,c.endLine);if(!d)return[];let m=new Set,f=d.childForFieldName("parameters")??d.childForFieldName("parameter");if(f&&Wt(f,x=>{x.type==="identifier"&&m.add(x.text)}),m.size===0)return[];let p=vu(e,t,n);if(p.length===0)return[];let g=(At(e,c.relativePath)??[]).filter(x=>x.startLine>=c.startLine&&x.endLine<=c.endLine),h=(tn(e,c.relativePath)??[]).filter(x=>x.line>=c.startLine&&x.line<=c.endLine),b=new Set,v=p.map(x=>({name:x.name,startLine:x.startLine,endLine:x.endLine})),y=new Set;for(;v.length>0&&y.size<32;){let x=v.shift(),C=`${x.name}\0${x.startLine}\0${x.endLine}`;if(!y.has(C)){y.add(C);for(let L of h.filter(w=>w.line>=x.startLine&&w.line<=x.endLine)){if(L.memberAccess&&L.calleeQualifier&&m.has(L.calleeQualifier)){b.add(L.calleeLeaf);continue}if(L.memberAccess)continue;let w=g.filter(R=>R.name===L.calleeLeaf);w.length===1&&v.push(w[0])}}}if(b.size===0)return[];let E=s.childForFieldName("arguments")?.namedChildren.find(x=>Di(x).type==="object");if(!E)return[];let S=[];for(let x of Di(E).namedChildren){if(x.type==="shorthand_property_identifier"&&b.has(x.text)){S.push(...wa(e,t,x.text,x,x));continue}if(x.type!=="pair")continue;let C=x.childForFieldName("key")??x.namedChild(0),L=x.childForFieldName("value")??x.namedChild(1),w=La(C?.text);!w||!b.has(w)||!L||S.push(...wa(e,t,w,L,x))}return S.filter((x,C,L)=>L.findIndex(w=>w.file===x.file&&w.name===x.name&&w.startLine===x.startLine&&w.endLine===x.endLine)===C)}function Gh(e,t){for(let n of e.descendantsOfType("variable_declarator"))if((n.childForFieldName("name")??n.namedChild(0))?.text===t)return n.childForFieldName("value")??n.namedChild(1);return null}function Wh(e){return e.type==="call_expression"?e:e.descendantsOfType("call_expression")[0]??null}function Vh(e,t,n){let i=n.replace(/\s+/gu,"").replace(/<[^<>]*>$/u,""),r=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(i);if(r){let d=Ce(e,t).filter(p=>p.localName===r[1]&&p.sourcePath);if(d.length!==1||!d[0].sourcePath)return[];let m=d[0].sourcePath,f=Wn(e,m,r[2]).filter(p=>p.isFunctionLike);return f.length>0?f:(At(e,m)??[]).filter(p=>p.name===r[2]).map(p=>({...p,relativePath:m}))}if(!/^[A-Za-z_$][\w$]*$/u.test(i))return[];let o=W(e,t).filter(d=>d.leaf===i&&d.isFunctionLike);if(o.length>0)return o;let s=(At(e,t)??[]).filter(d=>d.name===i).map(d=>({...d,relativePath:t}));if(s.length>0)return s;let a=Ce(e,t).filter(d=>d.localName===i&&d.sourcePath&&d.kind!=="namespace");if(a.length!==1||!a[0].sourcePath)return[];let l=a[0].sourcePath,c=a[0].importedName==="default"?i:a[0].importedName,u=Wn(e,l,c).filter(d=>d.isFunctionLike);return u.length>0?u:(At(e,l)??[]).filter(d=>d.name===c).map(d=>({...d,relativePath:l}))}function Jh(e,t,n){let i=null;return Wt(e,r=>{!/(?:function|method|lambda)/u.test(r.type)&&r.type!=="arrow_function"||r.startPosition.row>t||r.endPosition.row<n||(!i||r.endIndex-r.startIndex<i.endIndex-i.startIndex)&&(i=r)}),i}function Cu(e){return["arrow_function","function_expression","generator_function"].includes(e.type)||e.descendantsOfType(["arrow_function","function_expression","generator_function"]).length>0}function QD(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 La(e){return e?e.replace(/^(?:['"])(.*)(?:['"])$/u,"$1"):null}function ZD(e,t,n,i){let r=/^this\.([A-Za-z_$][\w$]*)$/u.exec(n.calleeQualifier??"");if(!r)return null;let o=ae(e,t)?.rootNode;if(!o)return null;let s=eM(o,n.line);if(!s)return null;let a=new Set;if(Wt(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.${r[1]}`||!b)return;let v=Di(b);if(v.type!=="new_expression")return;let I=(v.childForFieldName("constructor")??v.namedChild(0))?.text.match(/[A-Za-z_$][\w$]*$/u)?.[0];I&&a.add(I)}),a.size!==1)return null;let l=[...a][0],c=i.filter(g=>g.localName===l);if(c.length!==1)return null;let u=c[0].importedName==="default"?l:c[0].importedName,d=c[0].importedName==="default"?Wn(e,c[0].sourcePath,l):[],m=d.length===1?d[0].leaf:u,f=W(e,c[0].sourcePath).filter(g=>g.isFunctionLike&&g.leaf===n.calleeLeaf&&Mf(g.symbol)===m);if(f.length!==1)return null;let p=f[0];return{calleeLeaf:n.calleeLeaf,line:n.line,sourceFile:t,targetFile:p.relativePath,targetStartLine:p.startLine,targetEndLine:p.endLine,targetSymbol:p.symbol,resolution:"constructed-member-receiver",strength:"exact"}}function eM(e,t){let n=[];return Wt(e,i=>{["class","class_declaration","class_definition"].includes(i.type)&&i.startPosition.row<=t&&i.endPosition.row>=t&&n.push(i)}),n.sort((i,r)=>i.endPosition.row-i.startPosition.row-(r.endPosition.row-r.startPosition.row))[0]??null}function Di(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 Wt(e,t){t(e);for(let n of e.namedChildren)Wt(n,t)}function tM(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 i of e.matchAll(n)){let r=i[1],o=i[2];r&&o&&t.set(r,o)}return t}function xu(e){let t=[];for(let n of e)t.some(i=>Tt(i,n))||t.push(n);return t}import{existsSync as iM}from"fs";import{SymbolRole as rM}from"@c4312/scip";import{deserializeSCIP as nM}from"@c4312/scip";function Yh(e,t){return nM(Vi(e,{inputKind:t,maxBytes:Wi}))}var Ru=new WeakMap;function Dn(e,t,n,i){let r=te(e,t),o=(r?.callSites??[]).filter(f=>f.line>=n&&f.line<=i);if(!r||o.length===0)return{available:!!r,targets:[],resolvedCallsites:0,unresolvedCallsites:0};let s=Eu(e);if(!s)return{available:!1,targets:[],resolvedCallsites:0,unresolvedCallsites:o.length};let a=(s.byFile.get(t)??[]).filter(f=>f.sourceLine>=n&&f.sourceLine<=i).map(f=>({...f,calleeLeaf:f.definition.leaf})),l=Xh(o.map(f=>({line:f.line,leaf:f.calleeLeaf}))),c=Xh(a.map(f=>({line:f.sourceLine,leaf:f.calleeLeaf}))),u=new Set([...l].flatMap(([f,p])=>c.get(f)===p?[f]:[])),d=a.filter(f=>u.has(Zh(f.sourceLine,f.calleeLeaf))),m=[...u].reduce((f,p)=>f+(l.get(p)??0),0);return{available:!0,targets:d,resolvedCallsites:m,unresolvedCallsites:Math.max(0,o.length-m)}}function Iu(e,t,n,i){let r=Eu(e);return r?{available:!0,targets:(r.byFile.get(t)??[]).filter(o=>o.sourceLine>=n&&o.sourceLine<=i)}:{available:!1,targets:[]}}function Qh(e,t,n,i){let r=Eu(e);return r?{available:!0,targets:(r.byFile.get(t)??[]).filter(o=>o.sourceLine>=n&&o.sourceLine<=i&&Da(e,o.definition)).map(o=>({...o,calleeLeaf:o.definition.leaf}))}:{available:!1,targets:[]}}function Eu(e){if(Ru.has(e))return Ru.get(e)??null;let t=oM(e);return Ru.set(e,t),t}function oM(e){if(!e.generation.indexPath||!iM(e.generation.indexPath))return null;try{let t=Ue(e),n=new Map(t.map(o=>[o.symbol,o])),i=Yh(e.generation.indexPath,"SCIP source-range call-target index"),r=new Map;for(let o of i.documents??[]){let s=o.relativePath;if(!s||e.isIgnored(s))continue;let a=[];for(let l of o.occurrences??[]){if(!l.symbol||(l.symbolRoles&rM.Definition)!==0)continue;let c=n.get(l.symbol),u=l.range?.[0];!c||!Number.isInteger(u)||a.push({sourceLine:u,definition:c})}r.set(s,a)}return{byFile:r}}catch{return null}}function Da(e,t){if(!t.isFunctionLike)return!1;let n=te(e,t.relativePath);return!n||n.callables.some(i=>i.name===t.leaf&&i.startLine===t.startLine&&i.endLine===t.endLine)?!0:sM(t)}function sM(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 Xh(e){let t=new Map;for(let n of e){let i=Zh(n.line,n.leaf);t.set(i,(t.get(i)??0)+1)}return t}function Zh(e,t){return`${e}\0${t}`}import{existsSync as Ma,readdirSync as ny}from"fs";import{join as vo}from"path";var aM={files:new Set,pathPrefixes:[]},lM={reasonsByFile:new Map},wu=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,cM=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,iy=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],uM=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),dM=4,mM=Fe("package-surface",{clearGroups:["whole-project"]}),fM=Fe("package-operational-surface",{clearGroups:["whole-project"]});function ry(e){return mM.get(e,()=>gM(e.config.projectRoot))}function Pn(e,t){let n=ry(e);return n.files.has(t)?!0:n.pathPrefixes.some(i=>t.startsWith(i))}function oy(e,t){return ry(e).files.has(t)}function pM(e){return fM.get(e,()=>hM(e.config.projectRoot))}function sy(e,t){return pM(e).reasonsByFile.get(t)??[]}function gM(e){let t=new Set,n=[];for(let{manifest:i,packageRoot:r}of ay(e))for(let o of yM(i))dy(e,r,o,t,n);return t.size===0&&n.length===0?aM:{files:t,pathPrefixes:n}}function hM(e){let t=new Map;for(let{manifest:n,packageRoot:i}of ay(e)){let r=bM(n);for(let s of r)ey(e,i,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 l of SM(a))ey(e,i,l,`package script "${s}"`,t)}}return t.size===0?lM:{reasonsByFile:t}}function ay(e){let t=[],n=cy(e,"");return n&&t.push({manifest:n,packageRoot:""}),ly(e,"",t,0),t}function ly(e,t,n,i){if(i>=dM)return;let r=vo(e,t);if(Ma(r))for(let o of ny(r,{withFileTypes:!0})){if(!o.isDirectory()||uM.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=cy(e,s);a&&n.push({manifest:a,packageRoot:s}),ly(e,s,n,i+1)}}function cy(e,t){let n;try{n=rt(e,vo(t,"package.json"),{maxBytes:8*1024*1024,inputKind:"package manifest"})}catch(i){if(!ot(i))throw i;return null}try{let i=JSON.parse(n);return i&&typeof i=="object"?i:null}catch{return null}}function yM(e){let t=[];for(let i of["main","module","types","browser"])typeof e[i]=="string"&&t.push(e[i]);let n=e.bin;if(typeof n=="string")t.push(n);else if(n&&typeof n=="object")for(let i of Object.values(n))typeof i=="string"&&t.push(i);return uy(e.exports,t),t}function bM(e){let t=e.bin;return typeof t=="string"?[t]:!t||typeof t!="object"?[]:Object.values(t).filter(n=>typeof n=="string")}function SM(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 i of e.matchAll(n)){let r=i[1];r&&!r.startsWith("node_modules/")&&!r.startsWith("./node_modules/")&&t.push(r)}return t}function ey(e,t,n,i,r){let o=new Set;dy(e,t,n,o,[]);for(let s of o){let a=r.get(s)??[];a.includes(i)||a.push(i),r.set(s,a)}}function uy(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))uy(n,t)}function dy(e,t,n,i,r){let o=n.replace(/\\/g,"/").replace(/^\.\//,"");if(o===""||o.startsWith(".."))return;let s=o.indexOf("*");if(s>=0){let l=o.slice(0,s);for(let c of ty(l))c!==""&&r.push(Mn(t,c));return}let a=o.replace(cM,"");for(let l of ty(a)){l===a&&l===o&&i.add(Mn(t,o));for(let c of iy)vM(e,i,t,l+c)}i.add(Mn(t,o))}function ty(e){let t=[e];return wu.test(e)&&(t.push(e.replace(wu,"src/")),t.push(e.replace(wu,""))),t}function vM(e,t,n,i){let r=Mn(n,i);if(t.add(r),!i.startsWith("src/")||Ma(vo(e,r)))return;let o=iy.find(u=>i.endsWith(u));if(!o)return;let s=i.slice(0,-o.length);CM(e,t,n,s,o);let a=s.lastIndexOf("/");if(a<=4)return;let l=s.slice(0,a),c=s.slice(a+1);for(let u of my(e,n,l,`${c}${o}`))t.add(u)}function CM(e,t,n,i,r){let o=Mn(n,`${i}/index${r}`);Ma(vo(e,o))&&t.add(o)}function my(e,t,n,i){let r=vo(e,t,n);if(!Ma(r))return[];let o=[];for(let s of ny(r,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...my(e,t,a,i)):s.isFile()&&s.name===i&&o.push(Mn(t,a))}return o}function Mn(e,t){return e?`${e}/${t}`:t}import{existsSync as Lu,readdirSync as xM}from"fs";import{dirname as RM,join as Du}from"path";var IM={rootFiles:new Set,sourcePrefixes:[]},EM=new Set([".git",".codebaseiq","node_modules","target"]),wM=6,LM=Fe("rust-library-surface",{clearGroups:["whole-project"]});function fy(e,t,n){if(!n.endsWith(".rs")||!PM(DM(e),n))return!1;let i=W(e,n).find(r=>r.symbol===t);return i?TM(re(e,n)[i.startLine]??""):!1}function DM(e){return LM.get(e,()=>MM(e.config.projectRoot))}function MM(e){let t=new Set,n=new Set;for(let i of FM(e)){let r=rt(e,Du(i,"Cargo.toml"),{maxBytes:8388608,inputKind:"Cargo manifest"}),o=kM(r),s=Mn(i,"src/lib.rs"),a=o?Mn(i,o):!NM(r)&&Ft(e,s)?s:null;if(!a)continue;t.add(a);let l=RM(a).replaceAll("\\","/");n.add(l==="."?"":`${l}/`)}return t.size===0?IM:{rootFiles:t,sourcePrefixes:[...n].sort()}}function PM(e,t){return t.endsWith(".rs")?e.rootFiles.has(t)?!0:AM(t)?!1:e.sourcePrefixes.some(n=>t.startsWith(n)):!1}function TM(e){return/^\s*pub\s+(?!\()/.test(e)}function FM(e){if(!Lu(e))return[];let t=[];return py(e,"",t,0),t}function py(e,t,n,i){let r=Du(e,t);if(Lu(r)&&(Lu(Du(r,"Cargo.toml"))&&n.push(t),!(i>=wM)))for(let o of xM(r,{withFileTypes:!0})){if(!o.isDirectory()||EM.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name;py(e,s,n,i+1)}}function kM(e){let t=!1;for(let n of e.split(`
58
- `)){let i=n.replace(/\s+#.*$/,"").trim(),r=/^\[([^\]]+)\]$/.exec(i);if(r){t=r[1]==="lib";continue}if(!t)continue;let o=/^path\s*=\s*["']([^"']+)["']/.exec(i)?.[1];if(o)return o.replaceAll("\\","/").replace(/^\.\//,"")}return null}function NM(e){let t=!1;for(let n of e.split(`
59
- `)){let i=n.replace(/\s+#.*$/,"").trim(),r=/^\[([^\]]+)\]$/.exec(i);if(r){t=r[1]==="package";continue}if(t&&/^autolib\s*=\s*false\b/.test(i))return!0}return!1}function AM(e){return/(?:^|\/)src\/main\.rs$/.test(e)||/(?:^|\/)src\/bin\//.test(e)||/(?:^|\/)(?:examples|tests|benches)\//.test(e)}function fr(e){return J(e)==="barrel"}function hy(e){return _M.get(e,()=>{let n=me(e,{includeIgnored:!1}).filter(s=>{let a=J(s);return a==="entry"||a==="worker"});if(n.length===0)return new Set;let i=$e(e),r=new Set,o=new Set;for(;n.length>0;){let s=n.shift();if(!r.has(s)){r.add(s),J(s)==="barrel"&&o.add(s);for(let a of i.get(s)??[])r.has(a)||n.push(a)}}return o})}var _M=Fe("live-barrels",{clearGroups:["whole-project"]});function Mu(e,t){return hy(e).has(ht(t))}function yy(e){let t=hy(e);return me(e,{includeIgnored:!1}).filter(n=>fr(n)&&!t.has(n)&&!BM(e,n))}function BM(e,t){let n=ht(t),i=Un(e).forFile(n,{facts:!0}).facts?.callables;return i&&i.length>0?!0:(e.get(`SELECT COUNT(*) AS n
57
+ `)&&t.pop(),t}function MD(e){let t=new Map;for(let n of e){let i=PD(n.relativePath),r=t.get(i)??{matchingLines:0,matchingFiles:0};r.matchingLines+=n.matchingLines,r.matchingFiles+=1,t.set(i,r)}return[...t.entries()].map(([n,i])=>({scope:n,...i})).sort((n,i)=>i.matchingLines-n.matchingLines||i.matchingFiles-n.matchingFiles||n.scope.localeCompare(i.scope))}function PD(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}function Nh(e,t){let n=e.map((r,o)=>({...r,priority:Ra(r.fileKind),sequence:o,evidenceCharacters:1,roles:["search"],reasons:["search"],symbols:r.ownerSymbol?[r.ownerSymbol]:[],behaviorSignals:[]})),i=[];for(let r of[0,1,2]){let o=t-i.length;if(o===0)break;let s=n.filter(a=>Ra(a.fileKind)===r);i.push(...xa(s,o,Number.MAX_SAFE_INTEGER,Ah).selected)}return i.map(({priority:r,sequence:o,evidenceCharacters:s,roles:a,reasons:l,symbols:c,behaviorSignals:u,...d})=>d)}function Ah(e,t){return Ra(e.fileKind)-Ra(t.fileKind)||+(t.ownerSymbol!==null)-+(e.ownerSymbol!==null)||e.relativePath.localeCompare(t.relativePath)||e.focusLine-t.focusLine}function Ra(e){switch(e){case"entry":case"source":case"worker":return 0;case"barrel":return 1;case"test":return 2}}var gu=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 yo(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 mt(e){return new Set(yo(e).flatMap(hu).filter(t=>t.length>=3))}function hu(e){let t=Ia(e);return t.length>4&&t.endsWith("e")?[t,t.slice(0,-1)]:[t]}function Ia(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")?_h(t.slice(0,-2)):t.length>5&&t.endsWith("ing")?_h(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 _h(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}var Bh=new WeakMap,Oh=new WeakMap,$h=new WeakMap,jh=new WeakMap,Hh=new WeakMap;function Uh(e,t){let n=Oh.get(e);n||(n=new Map,Oh.set(e,n));let i=n.get(t);if(i)return i;let r=ae(e,t)?.rootNode;if(!r)return n.set(t,[]),[];let o=new Set;Wt(r,c=>{if(c.type!=="call_expression")return;let u=c.childForFieldName("function")??c.namedChild(0),d=/^([A-Za-z_$][\w$]*(?:\.Service)?)\.of$/u.exec(u?.text.replace(/\s+/gu,"")??"");d&&o.add(d[1])});let s=Ce(e,t).filter(c=>!!c.sourcePath),a=new Set;for(let c of o){let u=/^([A-Za-z_$][\w$]*)\.Service$/u.exec(c);if(u){for(let d of s)d.localName===u[1]&&a.add(d.sourcePath);continue}if(c==="Service"){W(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 l=Su([...a]).sort();return n.set(t,l),l}function Zn(e,t,n={}){let r=tn(e,t)?.filter(f=>!n.ranges||n.ranges.some(p=>f.line>=p.startLine&&f.line<=p.endLine));if(!r)return{targets:[],unresolvedCallsites:0};let o=Ce(e,t).filter(f=>!!f.sourcePath),s=WD(se(e,t)??""),a=ae(e,t)?.rootNode??null,l=a?FD(a):zh(),c=new Map,u=rn(e),d=[],m=0;for(let f of r){if(!f.memberAccess)continue;let p=nn(t,u.get(f.calleeLeaf)??[]);if(n.excludeIndexedTargets!==!1&&qn(e,t,p,!0,f.calleeQualifier))continue;let g=f.calleeQualifier,h=KD(e,t,f,o);if(h){d.push(h);continue}let b=TD(e,t,f,o,kD(l,f.calleeQualifier,f.line));if(b.length>0){d.push(...b);continue}let v=ND(e,t,f);if(v.length>0){d.push(...v);continue}let y=g?s.get(g)??g:null,E=(y?Su(o.filter(x=>(x.localName??x.importedName)===y).map(x=>x.sourcePath)):[]).flatMap(x=>{let C=c.get(x);return C||(C=At(e,x)??[],c.set(x,C)),C.filter(L=>L.name===f.calleeLeaf).map(L=>({file:x,callable:L}))});if(E.length!==1){m+=1;continue}let S=E[0];d.push({calleeLeaf:f.calleeLeaf,line:f.line,sourceFile:t,targetFile:S.file,targetStartLine:S.callable.startLine,targetEndLine:S.callable.endLine,resolution:"direct-import-receiver",strength:"candidate"})}return{targets:d,unresolvedCallsites:m}}function TD(e,t,n,i,r){let o=n.calleeQualifier;if(!o||!/^[A-Za-z_$][\w$]*$/u.test(o))return[];if(r.size!==1)return[];let s=[...r][0],a=Su(i.filter(u=>u.localName===s||u.importedName===s).map(u=>u.sourcePath));if(a.length!==1)return[];let l=a[0],c=OD(e,l,n.calleeLeaf);return c.map(u=>({calleeLeaf:u.name,line:n.line,sourceFile:t,targetFile:u.file,targetStartLine:u.startLine,targetEndLine:u.endLine,serviceFile:l,resolutionAlternativeCount:c.length,resolution:"imported-service-object-member",strength:"candidate"}))}function zh(){return{declarations:new Map,callbacks:[]}}function FD(e){let t=zh();return Wt(e,n=>{if(n.type==="variable_declarator"){let l=n.childForFieldName("name")??n.namedChild(0),c=n.childForFieldName("value")??n.namedChild(1);if(l?.type!=="identifier"||!c)return;let u=new Set;if(Wt(c,d=>{if(d.type!=="member_expression")return;let m=d.childForFieldName("object")??d.namedChild(0),f=d.childForFieldName("property")??d.namedChild(1);m?.type==="identifier"&&f?.text==="Service"&&u.add(m.text)}),u.size===1){let d=t.declarations.get(l.text)??[];d.push({line:n.startPosition.row,alias:[...u][0]}),t.declarations.set(l.text,d)}return}if(!["arrow_function","function_expression","generator_function"].includes(n.type))return;let i=n.childForFieldName("parameters")??n.childForFieldName("parameter");if(!i)return;let r=n.parent;for(;r&&r.type!=="call_expression";)r=r.parent;if(!r)return;let o=r.childForFieldName("function")??r.namedChild(0),s=/^([A-Za-z_$][\w$]*)\.Service\.use$/u.exec(o?.text??"");if(!s)return;let a=new Set;Wt(i,l=>{l.type==="identifier"&&a.add(l.text)}),a.size!==0&&t.callbacks.push({startLine:n.startPosition.row,endLine:n.endPosition.row,receivers:a,alias:s[1]})}),t}function kD(e,t,n){if(!t||!/^[A-Za-z_$][\w$]*$/u.test(t))return new Set;let i=new Set((e.declarations.get(t)??[]).filter(r=>r.line<=n).map(r=>r.alias));for(let r of e.callbacks)r.startLine<=n&&r.endLine>=n&&r.receivers.has(t)&&i.add(r.alias);return i}function ND(e,t,n){let i=n.calleeQualifier;if(!i||!/^[A-Za-z_$][\w$]*$/u.test(i))return[];let r=ae(e,t)?.rootNode;if(!r)return[];let o=AD(e,t,r,n.line,n.calleeLeaf,i),s=o?BD(o,i):null;if(!s)return[];if(!_D(s))return[];let a=(At(e,t)??[]).filter(f=>f.startLine<=s.startPosition.row&&f.endLine>=s.endPosition.row).sort((f,p)=>f.endLine-f.startLine-(p.endLine-p.startLine))[0];if(!a)return[];let l=W(e,t).filter(f=>f.isFunctionLike&&f.leaf===a.name);if(l.length!==1)return[];let c=l[0],u=jh.get(e);u||(u=new Map,jh.set(e,u));let d=`${c.symbol}\0${n.calleeLeaf}`,m=u.get(d);if(!m){let f=[];for(let p of Hr(e,c)){let g=ae(e,p.file)?.rootNode;if(!g)continue;let h=g.descendantsOfType("call_expression").filter(y=>y.startPosition.row>p.line||y.endPosition.row<p.line?!1:(y.childForFieldName("function")??y.namedChild(0))?.text.replace(/\s+/gu,"").replace(/<[^<>]*>$/u,"").match(/[A-Za-z_$][\w$]*$/u)?.[0]===c.leaf);if(h.length!==1)continue;let v=h[0].childForFieldName("arguments")?.namedChildren.find(y=>Di(y).type==="object");if(v)for(let y of Di(v).namedChildren){if(y.type==="shorthand_property_identifier"&&y.text===n.calleeLeaf){f.push(...Ea(e,p.file,n.calleeLeaf,y,y));continue}if(y.type!=="pair")continue;let I=y.childForFieldName("key")??y.namedChild(0),E=y.childForFieldName("value")??y.namedChild(1);wa(I?.text)!==n.calleeLeaf||!E||f.push(...Ea(e,p.file,n.calleeLeaf,E,y))}}m=f.filter((p,g,h)=>h.findIndex(b=>b.file===p.file&&b.startLine===p.startLine&&b.endLine===p.endLine&&b.name===p.name)===g),u.set(d,m)}return m.map(f=>({calleeLeaf:f.name,line:n.line,sourceFile:t,targetFile:f.file,targetStartLine:f.startLine,targetEndLine:f.endLine,resolutionAlternativeCount:m.length,resolution:"factory-callback-member",strength:m.length===1?"exact":"candidate"}))}function AD(e,t,n,i,r,o){let s=$h.get(e);s||(s=new Map,$h.set(e,s));let a=s.get(t);if(!a){a=new Map;for(let l of n.descendantsOfType("call_expression")){let c=l.childForFieldName("function")??l.namedChild(0),u=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(c?.text.replace(/\s+/gu,"")??"");if(u)for(let d=l.startPosition.row;d<=l.endPosition.row;d+=1){let m=`${d}\0${u[1]}\0${u[2]}`,f=a.get(m);(!f||l.endIndex-l.startIndex<f.endIndex-f.startIndex)&&a.set(m,l)}}s.set(t,a)}return a.get(`${i}\0${o}\0${r}`)??null}function _D(e){return e.descendantsOfType("return_statement").some(t=>{let n=t.childForFieldName("argument")??t.namedChild(0);return!!(n&&Di(n).type==="object")})}function BD(e,t){let n=e.parent;for(;n;){if(/(?:function|method|lambda)/u.test(n.type)||n.type==="arrow_function"){let i=n.childForFieldName("parameters")??n.childForFieldName("parameter"),r=!1;if(i&&Wt(i,o=>{o.type==="identifier"&&o.text===t&&(r=!0)}),r)return n}n=n.parent}return null}function Ea(e,t,n,i,r){if(i.type==="identifier")return(At(e,t)??[]).filter(l=>l.name===i.text).map(l=>({...l,file:t}));let o=yu(e,t,i.text);if(o.length>0)return o;if(!bu(i))return[];let a=(At(e,t)??[]).filter(l=>l.startLine>=r.startPosition.row&&l.endLine<=r.endPosition.row&&(l.name===n||l.name.startsWith("source@"))).sort((l,c)=>l.endLine-l.startLine-(c.endLine-c.startLine))[0];return[a?{...a,file:t}:{name:n,file:t,startLine:r.startPosition.row,endLine:r.endPosition.row}]}function OD(e,t,n){let i=Hh.get(e);i||(i=new Map,Hh.set(e,i));let r=`${t}\0${n}`,o=i.get(r);if(o)return o;let s=HD(e,t).flatMap(a=>$D(e,a,t,n));return i.set(r,s),s}function $D(e,t,n,i){let r=ae(e,t)?.rootNode,o=At(e,t)??[];if(!r)return[];let s=UD(e,t,n);if(s.size===0)return[];let a=new Set,l=[],c=[],u=[];return Wt(r,m=>{if(jD(m,s)){if(m.type==="pair"){let f=m.childForFieldName("key")??m.namedChild(0),p=m.childForFieldName("value")??m.namedChild(1);if(wa(f?.text)!==i||!p)return;if(p.type==="identifier")a.add(p.text);else if(bu(p))l.push({name:i,startLine:m.startPosition.row,endLine:m.endPosition.row});else{let g=zD(e,t,p.text),h=yu(e,t,p.text);if(g.length>0)u.push(...g);else if(h.length>0)u.push(...h);else{let b=qD(m);b&&c.push(b)}}return}m.type==="shorthand_property_identifier"&&m.text===i&&a.add(i)}}),[...o.filter(m=>a.has(m.name)).map(m=>({...m,file:t})),...l.map(m=>({...m,file:t})),...c.map(m=>({...m,file:t})),...u].filter((m,f,p)=>p.findIndex(g=>g.file===m.file&&g.name===m.name&&g.startLine===m.startLine&&g.endLine===m.endLine)===f)}function jD(e,t){let n=e,i=null;for(;n;){if(n.type==="object"&&(i=n),n.type==="call_expression"){if(!i)return!1;let r=n.childForFieldName("function")??n.namedChild(0);return r?t.has(r.text.replace(/\.of$/u,""))&&r.text.endsWith(".of"):!1}n=n.parent}return!1}function HD(e,t){let n=Bh.get(e);n||(n=new Map,Bh.set(e,n));let i=n.get(t);if(i)return i;let r=new Set([t]),o=W(e,t).filter(a=>a.leaf==="Service"&&a.isTypeLike);for(let a of o)for(let l of Hr(e,a))r.add(l.file);let s=[...r].sort();return n.set(t,s),s}function UD(e,t,n){let i=new Set;Tt(t,n)&&i.add("Service");for(let r of Ce(e,t)){if(!r.sourcePath||!Tt(r.sourcePath,n))continue;if(r.kind==="namespace"&&r.localName){i.add(`${r.localName}.Service`);continue}(r.importedName==="default"?r.localName:r.importedName)==="Service"?i.add(r.localName??r.importedName):r.localName&&r.importedName!=="default"&&i.add(`${r.localName}.Service`)}return i}function yu(e,t,n){let i=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(n.replace(/\s+/gu,""));if(!i)return[];let r=ae(e,t)?.rootNode;if(!r)return[];let o=qh(r,i[1]),s=o?Kh(o):null;if(!s)return[];let a=s.childForFieldName("function")??s.namedChild(0),l=a?Gh(e,t,a.text):[];if(l.length!==1)return[];let c=l[0],u=ae(e,c.relativePath)?.rootNode;if(!u)return[];let d=Wh(u,c.startLine,c.endLine);if(!d)return[];let m=[];for(let f of d.descendantsOfType("return_statement")){let p=f.childForFieldName("argument")??f.namedChild(0);if(!p)continue;let g=Di(p);if(g.type==="object")for(let h of g.namedChildren){if(h.type==="shorthand_property_identifier"&&h.text===i[2]){for(let y of At(e,c.relativePath)??[])y.name===i[2]&&m.push({...y,file:c.relativePath});continue}if(h.type!=="pair")continue;let b=h.childForFieldName("key")??h.namedChild(0),v=h.childForFieldName("value")??h.namedChild(1);if(!(wa(b?.text)!==i[2]||!v))if(v.type==="identifier")for(let y of At(e,c.relativePath)??[])y.name===v.text&&m.push({...y,file:c.relativePath});else bu(v)&&m.push({name:i[2],startLine:h.startPosition.row,endLine:h.endPosition.row,file:c.relativePath})}}return m.filter((f,p,g)=>g.findIndex(h=>h.file===f.file&&h.name===f.name&&h.startLine===f.startLine&&h.endLine===f.endLine)===p)}function zD(e,t,n){let i=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(n.replace(/\s+/gu,""));if(!i)return[];let r=ae(e,t)?.rootNode;if(!r)return[];let o=qh(r,i[1]),s=o?Kh(o):null,a=s?.childForFieldName("function")??s?.namedChild(0),l=a?Gh(e,t,a.text):[];if(l.length!==1||!s)return[];let c=l[0],u=ae(e,c.relativePath)?.rootNode;if(!u)return[];let d=Wh(u,c.startLine,c.endLine);if(!d)return[];let m=new Set,f=d.childForFieldName("parameters")??d.childForFieldName("parameter");if(f&&Wt(f,x=>{x.type==="identifier"&&m.add(x.text)}),m.size===0)return[];let p=yu(e,t,n);if(p.length===0)return[];let g=(At(e,c.relativePath)??[]).filter(x=>x.startLine>=c.startLine&&x.endLine<=c.endLine),h=(tn(e,c.relativePath)??[]).filter(x=>x.line>=c.startLine&&x.line<=c.endLine),b=new Set,v=p.map(x=>({name:x.name,startLine:x.startLine,endLine:x.endLine})),y=new Set;for(;v.length>0&&y.size<32;){let x=v.shift(),C=`${x.name}\0${x.startLine}\0${x.endLine}`;if(!y.has(C)){y.add(C);for(let L of h.filter(w=>w.line>=x.startLine&&w.line<=x.endLine)){if(L.memberAccess&&L.calleeQualifier&&m.has(L.calleeQualifier)){b.add(L.calleeLeaf);continue}if(L.memberAccess)continue;let w=g.filter(R=>R.name===L.calleeLeaf);w.length===1&&v.push(w[0])}}}if(b.size===0)return[];let E=s.childForFieldName("arguments")?.namedChildren.find(x=>Di(x).type==="object");if(!E)return[];let S=[];for(let x of Di(E).namedChildren){if(x.type==="shorthand_property_identifier"&&b.has(x.text)){S.push(...Ea(e,t,x.text,x,x));continue}if(x.type!=="pair")continue;let C=x.childForFieldName("key")??x.namedChild(0),L=x.childForFieldName("value")??x.namedChild(1),w=wa(C?.text);!w||!b.has(w)||!L||S.push(...Ea(e,t,w,L,x))}return S.filter((x,C,L)=>L.findIndex(w=>w.file===x.file&&w.name===x.name&&w.startLine===x.startLine&&w.endLine===x.endLine)===C)}function qh(e,t){for(let n of e.descendantsOfType("variable_declarator"))if((n.childForFieldName("name")??n.namedChild(0))?.text===t)return n.childForFieldName("value")??n.namedChild(1);return null}function Kh(e){return e.type==="call_expression"?e:e.descendantsOfType("call_expression")[0]??null}function Gh(e,t,n){let i=n.replace(/\s+/gu,"").replace(/<[^<>]*>$/u,""),r=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(i);if(r){let d=Ce(e,t).filter(p=>p.localName===r[1]&&p.sourcePath);if(d.length!==1||!d[0].sourcePath)return[];let m=d[0].sourcePath,f=Wn(e,m,r[2]).filter(p=>p.isFunctionLike);return f.length>0?f:(At(e,m)??[]).filter(p=>p.name===r[2]).map(p=>({...p,relativePath:m}))}if(!/^[A-Za-z_$][\w$]*$/u.test(i))return[];let o=W(e,t).filter(d=>d.leaf===i&&d.isFunctionLike);if(o.length>0)return o;let s=(At(e,t)??[]).filter(d=>d.name===i).map(d=>({...d,relativePath:t}));if(s.length>0)return s;let a=Ce(e,t).filter(d=>d.localName===i&&d.sourcePath&&d.kind!=="namespace");if(a.length!==1||!a[0].sourcePath)return[];let l=a[0].sourcePath,c=a[0].importedName==="default"?i:a[0].importedName,u=Wn(e,l,c).filter(d=>d.isFunctionLike);return u.length>0?u:(At(e,l)??[]).filter(d=>d.name===c).map(d=>({...d,relativePath:l}))}function Wh(e,t,n){let i=null;return Wt(e,r=>{!/(?:function|method|lambda)/u.test(r.type)&&r.type!=="arrow_function"||r.startPosition.row>t||r.endPosition.row<n||(!i||r.endIndex-r.startIndex<i.endIndex-i.startIndex)&&(i=r)}),i}function bu(e){return["arrow_function","function_expression","generator_function"].includes(e.type)||e.descendantsOfType(["arrow_function","function_expression","generator_function"]).length>0}function qD(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 wa(e){return e?e.replace(/^(?:['"])(.*)(?:['"])$/u,"$1"):null}function KD(e,t,n,i){let r=/^this\.([A-Za-z_$][\w$]*)$/u.exec(n.calleeQualifier??"");if(!r)return null;let o=ae(e,t)?.rootNode;if(!o)return null;let s=GD(o,n.line);if(!s)return null;let a=new Set;if(Wt(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.${r[1]}`||!b)return;let v=Di(b);if(v.type!=="new_expression")return;let I=(v.childForFieldName("constructor")??v.namedChild(0))?.text.match(/[A-Za-z_$][\w$]*$/u)?.[0];I&&a.add(I)}),a.size!==1)return null;let l=[...a][0],c=i.filter(g=>g.localName===l);if(c.length!==1)return null;let u=c[0].importedName==="default"?l:c[0].importedName,d=c[0].importedName==="default"?Wn(e,c[0].sourcePath,l):[],m=d.length===1?d[0].leaf:u,f=W(e,c[0].sourcePath).filter(g=>g.isFunctionLike&&g.leaf===n.calleeLeaf&&Ef(g.symbol)===m);if(f.length!==1)return null;let p=f[0];return{calleeLeaf:n.calleeLeaf,line:n.line,sourceFile:t,targetFile:p.relativePath,targetStartLine:p.startLine,targetEndLine:p.endLine,targetSymbol:p.symbol,resolution:"constructed-member-receiver",strength:"exact"}}function GD(e,t){let n=[];return Wt(e,i=>{["class","class_declaration","class_definition"].includes(i.type)&&i.startPosition.row<=t&&i.endPosition.row>=t&&n.push(i)}),n.sort((i,r)=>i.endPosition.row-i.startPosition.row-(r.endPosition.row-r.startPosition.row))[0]??null}function Di(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 Wt(e,t){t(e);for(let n of e.namedChildren)Wt(n,t)}function WD(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 i of e.matchAll(n)){let r=i[1],o=i[2];r&&o&&t.set(r,o)}return t}function Su(e){let t=[];for(let n of e)t.some(i=>Tt(i,n))||t.push(n);return t}var Vh=new WeakMap;function Dn(e,t,n,i){let r=te(e,t),o=(r?.callSites??[]).filter(f=>f.line>=n&&f.line<=i);if(!r||o.length===0)return{available:!!r,targets:[],resolvedCallsites:0,unresolvedCallsites:0};let s=Cu(e,t);if(!s)return{available:!1,targets:[],resolvedCallsites:0,unresolvedCallsites:o.length};let a=s.filter(f=>f.sourceLine>=n&&f.sourceLine<=i).map(f=>({...f,calleeLeaf:f.definition.leaf})),l=Jh(o.map(f=>({line:f.line,leaf:f.calleeLeaf}))),c=Jh(a.map(f=>({line:f.sourceLine,leaf:f.calleeLeaf}))),u=new Set([...l].flatMap(([f,p])=>c.get(f)===p?[f]:[])),d=a.filter(f=>u.has(Xh(f.sourceLine,f.calleeLeaf))),m=[...u].reduce((f,p)=>f+(l.get(p)??0),0);return{available:!0,targets:d,resolvedCallsites:m,unresolvedCallsites:Math.max(0,o.length-m)}}function vu(e,t,n,i){let r=Cu(e,t);return r?{available:!0,targets:r.filter(o=>o.sourceLine>=n&&o.sourceLine<=i)}:{available:!1,targets:[]}}function Yh(e,t,n,i){let r=Cu(e,t);return r?{available:!0,targets:r.filter(o=>o.sourceLine>=n&&o.sourceLine<=i&&La(e,o.definition)).map(o=>({...o,calleeLeaf:o.definition.leaf}))}:{available:!1,targets:[]}}function Cu(e,t){let n=VD(e);return n.byFile.has(t)||n.byFile.set(t,JD(e,n,t)),n.byFile.get(t)??null}function VD(e){let t=Vh.get(e);if(!t){let n=Ue(e);t={definitionBySymbol:new Map(n.map(i=>[i.symbol,i])),byFile:new Map},Vh.set(e,t)}return t}function JD(e,t,n){if(e.isIgnored(n))return[];let i=_s(e,n);if(!i)return null;let r=[];for(let o of i){if((o.roles&1)!==0)continue;let s=t.definitionBySymbol.get(o.symbol);s&&r.push({sourceLine:o.range[0],definition:s})}return r}function La(e,t){if(!t.isFunctionLike)return!1;let n=te(e,t.relativePath);return!n||n.callables.some(i=>i.name===t.leaf&&i.startLine===t.startLine&&i.endLine===t.endLine)?!0:YD(t)}function YD(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 Jh(e){let t=new Map;for(let n of e){let i=Xh(n.line,n.leaf);t.set(i,(t.get(i)??0)+1)}return t}function Xh(e,t){return`${e}\0${t}`}import{existsSync as Da,readdirSync as ey}from"fs";import{join as bo}from"path";var XD={files:new Set,pathPrefixes:[]},QD={reasonsByFile:new Map},xu=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,ZD=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,ty=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],eM=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),tM=4,nM=Fe("package-surface",{clearGroups:["whole-project"]}),iM=Fe("package-operational-surface",{clearGroups:["whole-project"]});function ny(e){return nM.get(e,()=>oM(e.config.projectRoot))}function Pn(e,t){let n=ny(e);return n.files.has(t)?!0:n.pathPrefixes.some(i=>t.startsWith(i))}function iy(e,t){return ny(e).files.has(t)}function rM(e){return iM.get(e,()=>sM(e.config.projectRoot))}function ry(e,t){return rM(e).reasonsByFile.get(t)??[]}function oM(e){let t=new Set,n=[];for(let{manifest:i,packageRoot:r}of oy(e))for(let o of aM(i))cy(e,r,o,t,n);return t.size===0&&n.length===0?XD:{files:t,pathPrefixes:n}}function sM(e){let t=new Map;for(let{manifest:n,packageRoot:i}of oy(e)){let r=lM(n);for(let s of r)Qh(e,i,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 l of cM(a))Qh(e,i,l,`package script "${s}"`,t)}}return t.size===0?QD:{reasonsByFile:t}}function oy(e){let t=[],n=ay(e,"");return n&&t.push({manifest:n,packageRoot:""}),sy(e,"",t,0),t}function sy(e,t,n,i){if(i>=tM)return;let r=bo(e,t);if(Da(r))for(let o of ey(r,{withFileTypes:!0})){if(!o.isDirectory()||eM.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=ay(e,s);a&&n.push({manifest:a,packageRoot:s}),sy(e,s,n,i+1)}}function ay(e,t){let n;try{n=rt(e,bo(t,"package.json"),{maxBytes:8*1024*1024,inputKind:"package manifest"})}catch(i){if(!ot(i))throw i;return null}try{let i=JSON.parse(n);return i&&typeof i=="object"?i:null}catch{return null}}function aM(e){let t=[];for(let i of["main","module","types","browser"])typeof e[i]=="string"&&t.push(e[i]);let n=e.bin;if(typeof n=="string")t.push(n);else if(n&&typeof n=="object")for(let i of Object.values(n))typeof i=="string"&&t.push(i);return ly(e.exports,t),t}function lM(e){let t=e.bin;return typeof t=="string"?[t]:!t||typeof t!="object"?[]:Object.values(t).filter(n=>typeof n=="string")}function cM(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 i of e.matchAll(n)){let r=i[1];r&&!r.startsWith("node_modules/")&&!r.startsWith("./node_modules/")&&t.push(r)}return t}function Qh(e,t,n,i,r){let o=new Set;cy(e,t,n,o,[]);for(let s of o){let a=r.get(s)??[];a.includes(i)||a.push(i),r.set(s,a)}}function ly(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))ly(n,t)}function cy(e,t,n,i,r){let o=n.replace(/\\/g,"/").replace(/^\.\//,"");if(o===""||o.startsWith(".."))return;let s=o.indexOf("*");if(s>=0){let l=o.slice(0,s);for(let c of Zh(l))c!==""&&r.push(Mn(t,c));return}let a=o.replace(ZD,"");for(let l of Zh(a)){l===a&&l===o&&i.add(Mn(t,o));for(let c of ty)uM(e,i,t,l+c)}i.add(Mn(t,o))}function Zh(e){let t=[e];return xu.test(e)&&(t.push(e.replace(xu,"src/")),t.push(e.replace(xu,""))),t}function uM(e,t,n,i){let r=Mn(n,i);if(t.add(r),!i.startsWith("src/")||Da(bo(e,r)))return;let o=ty.find(u=>i.endsWith(u));if(!o)return;let s=i.slice(0,-o.length);dM(e,t,n,s,o);let a=s.lastIndexOf("/");if(a<=4)return;let l=s.slice(0,a),c=s.slice(a+1);for(let u of uy(e,n,l,`${c}${o}`))t.add(u)}function dM(e,t,n,i,r){let o=Mn(n,`${i}/index${r}`);Da(bo(e,o))&&t.add(o)}function uy(e,t,n,i){let r=bo(e,t,n);if(!Da(r))return[];let o=[];for(let s of ey(r,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...uy(e,t,a,i)):s.isFile()&&s.name===i&&o.push(Mn(t,a))}return o}function Mn(e,t){return e?`${e}/${t}`:t}import{existsSync as Ru,readdirSync as mM}from"fs";import{dirname as fM,join as Iu}from"path";var pM={rootFiles:new Set,sourcePrefixes:[]},gM=new Set([".git",".codebaseiq","node_modules","target"]),hM=6,yM=Fe("rust-library-surface",{clearGroups:["whole-project"]});function dy(e,t,n){if(!n.endsWith(".rs")||!vM(bM(e),n))return!1;let i=W(e,n).find(r=>r.symbol===t);return i?CM(re(e,n)[i.startLine]??""):!1}function bM(e){return yM.get(e,()=>SM(e.config.projectRoot))}function SM(e){let t=new Set,n=new Set;for(let i of xM(e)){let r=rt(e,Iu(i,"Cargo.toml"),{maxBytes:8388608,inputKind:"Cargo manifest"}),o=RM(r),s=Mn(i,"src/lib.rs"),a=o?Mn(i,o):!IM(r)&&Ft(e,s)?s:null;if(!a)continue;t.add(a);let l=fM(a).replaceAll("\\","/");n.add(l==="."?"":`${l}/`)}return t.size===0?pM:{rootFiles:t,sourcePrefixes:[...n].sort()}}function vM(e,t){return t.endsWith(".rs")?e.rootFiles.has(t)?!0:EM(t)?!1:e.sourcePrefixes.some(n=>t.startsWith(n)):!1}function CM(e){return/^\s*pub\s+(?!\()/.test(e)}function xM(e){if(!Ru(e))return[];let t=[];return my(e,"",t,0),t}function my(e,t,n,i){let r=Iu(e,t);if(Ru(r)&&(Ru(Iu(r,"Cargo.toml"))&&n.push(t),!(i>=hM)))for(let o of mM(r,{withFileTypes:!0})){if(!o.isDirectory()||gM.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name;my(e,s,n,i+1)}}function RM(e){let t=!1;for(let n of e.split(`
58
+ `)){let i=n.replace(/\s+#.*$/,"").trim(),r=/^\[([^\]]+)\]$/.exec(i);if(r){t=r[1]==="lib";continue}if(!t)continue;let o=/^path\s*=\s*["']([^"']+)["']/.exec(i)?.[1];if(o)return o.replaceAll("\\","/").replace(/^\.\//,"")}return null}function IM(e){let t=!1;for(let n of e.split(`
59
+ `)){let i=n.replace(/\s+#.*$/,"").trim(),r=/^\[([^\]]+)\]$/.exec(i);if(r){t=r[1]==="package";continue}if(t&&/^autolib\s*=\s*false\b/.test(i))return!0}return!1}function EM(e){return/(?:^|\/)src\/main\.rs$/.test(e)||/(?:^|\/)src\/bin\//.test(e)||/(?:^|\/)(?:examples|tests|benches)\//.test(e)}function dr(e){return J(e)==="barrel"}function py(e){return wM.get(e,()=>{let n=me(e,{includeIgnored:!1}).filter(s=>{let a=J(s);return a==="entry"||a==="worker"});if(n.length===0)return new Set;let i=$e(e),r=new Set,o=new Set;for(;n.length>0;){let s=n.shift();if(!r.has(s)){r.add(s),J(s)==="barrel"&&o.add(s);for(let a of i.get(s)??[])r.has(a)||n.push(a)}}return o})}var wM=Fe("live-barrels",{clearGroups:["whole-project"]});function Eu(e,t){return py(e).has(ht(t))}function gy(e){let t=py(e);return me(e,{includeIgnored:!1}).filter(n=>dr(n)&&!t.has(n)&&!LM(e,n))}function LM(e,t){let n=ht(t),i=Un(e).forFile(n,{facts:!0}).facts?.callables;return i&&i.length>0?!0:(e.get(`SELECT COUNT(*) AS n
60
60
  FROM defn_enclosing_ranges der
61
61
  JOIN documents d ON d.id = der.document_id
62
62
  WHERE d.relative_path = ?
63
- AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function Qe(e,t){let n=ht(t),i=J(t);return i==="entry"||i==="worker"||Pu(n)||Mu(e,n)}function pr(e,t,n){let i=ht(n),r=[];Pn(e,i)&&r.push("package-surface-file"),jM(e,t,i)&&r.push("transitive-package-surface"),fy(e,t,i)&&r.push("rust-public-library"),YM(t,i)&&r.push("framework-entrypoint");let o=e.config.entryRoots;return o&&(o.files?.some(s=>ht(s)===i)&&r.push("configured-file"),o.pathPrefixes?.some(s=>i.startsWith(ht(s)))&&r.push("configured-path-prefix"),o.qualifiedVars?.some(s=>ZM(t,s))&&r.push("configured-qualified-var"),o.symbolPatterns?.some(s=>{try{return Cs(s,"entryRoots.symbolPatterns entry").test(t)}catch{return!1}})&&r.push("configured-symbol-pattern")),r}function qe(e,t,n){return pr(e,t,n).length>0}var OM=Fe("package-surface-reachability",{clearGroups:["whole-project"]}),$M=Fe("explicit-package-surface-reachability",{clearGroups:["whole-project"]});function jM(e,t,n){let i=HM(e).get(n);return i===void 0?!1:i===null||i.has(Y(t))}function by(e,t,n){let i=UM(e).get(n);return i===void 0?!1:i===null||i.has(Y(t))}function HM(e){return OM.get(e,()=>Sy(e,t=>Pn(e,t)))}function UM(e){return $M.get(e,()=>Sy(e,t=>oy(e,t)))}function Sy(e,t){let n=new Map,i=[];for(let r of me(e,{includeIgnored:!1}))t(r)&&(n.set(r,null),i.push(r));for(;i.length>0;){let r=i.shift(),o=n.get(r);if(o!==void 0)for(let s of Hr(e,r)){if(!s.sourcePath||e.isIgnored(s.sourcePath))continue;let a=zM(o,s);a!==void 0&&qM(n,s.sourcePath,a)&&i.push(s.sourcePath)}}return n}function zM(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(i=>e.has(i))?null:void 0;let n=t.names.filter(i=>e.has(i));return n.length>0?new Set(n):void 0}function qM(e,t,n){if(!e.has(t))return e.set(t,n),!0;let i=e.get(t);if(i===void 0)return!1;if(i===null||n===null)return i===null?!1:(e.set(t,null),!0);let r=!1;for(let o of n)i.has(o)||(i.add(o),r=!0);return r}var vy=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),KM=new Set(["default","generateMetadata","generateStaticParams"]),GM=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),WM=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),VM=new Set(["load","actions","entries",...vy]),JM=new Set(["default"]);function YM(e,t){let n=Y(e);return n===""?!1:Cy(t)?vy.has(n):xy(t)?KM.has(n):Ry(t)?GM.has(n):Iy(t)?WM.has(n):Ey(t)?VM.has(n):QM(t)?JM.has(n):!1}function Pu(e){return Cy(e)||xy(e)||Ry(e)||XM(e)||Iy(e)||Ey(e)}function Cy(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function xy(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Ry(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function XM(e){let t="(?:middleware|proxy|instrumentation)\\.(?:ts|js|mts|mjs)";return new RegExp(`^(?:src/)?${t}$`).test(e)||new RegExp(`(?:^|/)src/${t}$`).test(e)||new RegExp(`(?:^|/)(?:apps|services|packages)/[^/]+/(?:src/)?${t}$`).test(e)}function Iy(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Ey(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function QM(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function ZM(e,t){let n=t.lastIndexOf("/");if(n<0)return!1;let i=t.slice(0,n),r=t.slice(n+1);return e.includes(gy(i)+"/")&&e.includes(gy(r)+".")}function gy(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function wy(e,t,n={}){let i=new Map;if(t&&t.length===0)return i;let r=me(e,{includeIgnored:!1}),o=rn(e),s=t??Ue(e),a=new Set(s.map(c=>c.symbolId)),l=sP(s);return eP(e,i,r,o,a,l),tP(e,i,s,a),oP(e,i,r,o,a,l),n.semantic!==!1&&n.semanticEvidence&&lP(i,n.semanticEvidence.callerMap(e,aP(s))),i}function eP(e,t,n,i,r,o){for(let s of n){if(!ye(s))continue;let a=tn(e,s);if(a)for(let l of a){if(o&&!o.has(l.calleeLeaf))continue;let c=nn(s,i.get(l.calleeLeaf)??[]);if(!c||c.length===0)continue;let u=qn(e,s,c,l.memberAccess,l.calleeQualifier);u&&r.has(u.symbolId)&&u.file!==s&&Tu(t,u.symbolId,s)}}}function tP(e,t,n,i){let r=iP(n);for(let o of nP(e,i))e.isIgnored(o.relative_path)||rP(o,r.get(o.symbol_id))||Tu(t,o.symbol_id,o.relative_path)}function nP(e,t){return Bs(e,t?[...t]:void 0)}function iP(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 rP(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function oP(e,t,n,i,r,o){for(let s of n){if(ye(s)!=="rust")continue;let a=Qi(e,s,{includeRustAttributeNames:!0});if(a.length!==0)for(let{name:l}of a){if(o&&!o.has(l))continue;let c=i.get(l);if(c)for(let u of c)r.has(u.symbolId)&&u.file!==s&&Tu(t,u.symbolId,s)}}}function Tu(e,t,n){let i=e.get(t);i||(i=new Set,e.set(t,i)),i.add(n)}function sP(e){let t=new Set;for(let n of e){let i="leaf"in n&&typeof n.leaf=="string"?n.leaf:"symbol"in n&&typeof n.symbol=="string"?Y(n.symbol):"";i&&t.add(i)}return t.size>0?t:null}function aP(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function lP(e,t){for(let[n,i]of t){let r=e.get(n);r||(r=new Set,e.set(n,r));for(let o of i)r.add(o)}}function Fu(e,t,n={}){return wy(e,t,n)}function Co(e,t,n={}){return qf(e,t,n)}function Ly(e,t,n={}){let i=Fu(e,t,{semantic:n.semantic,semanticEvidence:n.semanticEvidence});return n.sourceFallback===!1?i:Mi(i,Co(e,t))}function Mi(e,t){let n=new Map;for(let[i,r]of e)n.set(i,new Set(r));for(let[i,r]of t){let o=n.get(i)??new Set;for(let s of r)o.add(s);n.set(i,o)}return n}function Dy(e,t,n){let i=t.identifierResolution==="strict"?ic:zf,r=t.candidateNames?jf(t.candidateNames):null,o=0,s=0,a=0,l=0,c="";for(let u of t.paths)if(o+=1,c=u,!(!ye(u)&&!(t.includeVueSfc&&Ef(u)))&&!e.isIgnored(u)&&!t.skipPath?.(u))try{if(r&&!Hf(se(e,u),r))continue;s+=1;let m=(p,g,h,b)=>{if(t.candidateNames&&!t.candidateNames.has(p))return;a+=1;let v=t.resolveTargets?t.resolveTargets({sourceFile:u,name:p,kind:g,defaultTargets:b}):b();for(let y of v)l+=1,n({sourceFile:u,name:p,target:y,occurrences:h,kind:g})},f=nr(e,u);for(let[p,g]of f)m(p,"identifier",g.length,()=>i(e,u,p));for(let p of Qi(e,u,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let g=p.kind==="cross-language-dispatch"?()=>ic(e,u,p.name):()=>i(e,u,p.name);m(p.name,p.kind,p.occurrences,g)}}finally{t.afterPath?.(u),o%10===0&&B("source-reference-scan.progress",()=>{},()=>({scannedPaths:o,currentPath:c,candidateMatchedPaths:s,visitedNames:a,visitedHits:l}))}}function de(e){return e.endLine-e.startLine+1}function My(e,t={}){let{scope:n,files:i,minLoc:r=1,maxLoc:o=Number.POSITIVE_INFINITY,excludeSymbol:s,excludeEntrySurfaces:a=!1,excludeTypesFiles:l=!1,excludeRootedSymbols:c=!1,requireFunctionLikeSymbol:u=!1,requireCallableSymbol:d=!1,excludeRustTraitImplMembers:m=!1,includeSuppressed:f=!1,sortByLocDesc:p=!1}=t,g=[],h=cP(e,{scope:n,files:i,requireFunctionLikeSymbol:u,requireCallableSymbol:d}),b=new Map,v=new Map,y=E=>{let S=b.get(E);if(S!==void 0)return S;let x=Qe(e,E);return b.set(E,x),x},I=E=>{let S=v.get(E);if(S!==void 0)return S;let x=J(E);return v.set(E,x),x};for(let E of h){let S=E.relativePath;if(e.isIgnored(S)||a&&y(S)||!uP(E,{requireFunctionLikeSymbol:u,requireCallableSymbol:d})||s!==void 0&&E.symbol===s)continue;let x=de(E);x<r||x>o||l&&dP(S)||c&&qe(e,E.symbol,S)||m&&Xe(E.symbol)||I(S)!=="test"&&(Zi(E.symbol)||!f&&Ms(e,S,E.startLine)||g.push(E))}return p?g.sort((E,S)=>de(S)-de(E)):g}function cP(e,t){return t.files!==void 0?[...new Set(t.files.map(i=>i.replace(/\\/g,"/")))].sort().filter(i=>!t.scope||i.includes(t.scope)).flatMap(i=>W(e,i)):t.requireCallableSymbol?Ur(e,{scope:t.scope,symbolMatches:st,sqlPrefilter:"callable"}):t.requireFunctionLikeSymbol?Ur(e,{scope:t.scope,symbolMatches:_e,sqlPrefilter:"function-like"}):Nf(e,t.scope)}function uP(e,t){return t.requireCallableSymbol?st(e.symbol):t.requireFunctionLikeSymbol?_e(e.symbol):e.isFunctionLike}function dP(e){return(e.split("/").pop()??"").includes("types")}var U=class{constructor(t){this.db=t}db;scopedDefinitions(t){return kf(this.db,t)}definitionsForFile(t){return W(this.db,t)}productionCallableDefinitions(t={}){return My(this.db,t)}calleeMap(t,n={}){return this.calleeEvidenceMap(t,n).rows}calleeEvidenceMap(t,n={}){return Wr(this.db,t,{...n,semanticEvidence:ge})}crossFileCallerMap(t,n={}){return Fu(this.db,t,{...n,semanticEvidence:ge})}sourceFallbackCallerFiles(t,n={}){return Co(this.db,t,n)}callerFileMap(t,n={}){return Ly(this.db,t,{...n,semanticEvidence:ge})}frameworkReferencedSymbolIds(t){let n=new Map;for(let r of t){if(!r.leaf)continue;let o=n.get(r.leaf)??[];o.push(r.symbolId),n.set(r.leaf,o)}let i=new Set;for(let r of me(this.db,{includeIgnored:!1}))if(ye(r)==="rust")for(let{name:o}of Qi(this.db,r,{includeRustAttributeNames:!0}))for(let s of n.get(o)??[])i.add(s);return i}symbolsWithNonSelfCallees(t,n={}){if(t.length===0)return new Set;let i=new Map(t.map(s=>[s.symbolId,s.symbol])),r=this.calleeEvidenceMap(t,n),o=new Set([...r.rows.entries()].filter(([s,a])=>{let l=i.get(s);return a.some(c=>c.symbol!==l)}).map(([s])=>s));for(let s of r.incompleteSymbolIds)o.add(s);for(let s of r.unavailableSymbolIds)o.add(s);return o}fileDependencyGraph(t){return $e(this.db,t)}fileKind(t){return J(t)}hasSuppressionComment(t){return Ms(this.db,t.relativePath,t.startLine)}sourceFiles(){return Xi(this.db)}scanSourceReferences(t,n){Dy(this.db,t,n)}callableSignature(t){let n=Un(this.db).forFile(t.relativePath,{facts:!0}).facts?.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};var mP=16,fP=4,ku=3e3,pP=800,gP=new Set(["assignment","const_declaration","const_item","field_declaration","lexical_declaration","local_declaration_statement","local_variable_declaration","static_item","variable_declaration"]);function Ay(e,t,n={}){let i=n.maxSteps??mP;if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`maxSteps must be a positive safe integer; received ${i}`);let r=new Map(t.nodes.map(T=>[T.id,T])),o=xP(n.focusLocations??[]),s=new Set,a=new Map(t.edges.map(T=>[T.id,T])),l=Tn(t.paths.flatMap(T=>T.nodeIds)),c=Tn(t.anchors.filter(T=>T.status==="matched").flatMap(T=>T.nodeIds)),u=t.nodes.filter(T=>T.disposition==="emitted"&&T.attributes.upstreamCausalPath===!0).sort((T,Z)=>Number(Z.attributes.upstreamCausalDistance??0)-Number(T.attributes.upstreamCausalDistance??0)||T.id.localeCompare(Z.id)).map(T=>T.id),d=new Set(u),m=Math.max(0,i-c.length),p=hP(t,c,o,m).slice(0,m),g=new Set(p),h=new Set(p),b=new Set([...l,...u,...c]),v=t.edges.filter(T=>T.disposition==="emitted"&&T.kind!=="structural-membership"),y=t.edges.filter(T=>T.disposition!=="excluded"&&T.disposition!=="unsupported"&&T.kind!=="structural-membership"),I=new Set([...t.paths.flatMap(T=>T.edgeIds),...v.filter(T=>d.has(T.fromNodeId)&&d.has(T.toNodeId)).map(T=>T.id)]),E=t.paths.some(T=>T.edgeIds.length>0),S=new Set(c);for(let T of p)S.add(T);for(let T of t.paths){let Z=T.nodeIds[0],Q=a.get(T.edgeIds[0]??""),Se=T.nodeIds[1];Z&&Se&&Q?.fromNodeId===Z&&Q.toNodeId===Se&&S.add(Z)}if(t.paths.every(T=>T.nodeIds.length===0))for(let T of t.anchors)for(let Z of T.nodeIds)S.add(Z);let x=LP(c,y,r,fP),C=Tn(v.filter(T=>T.kind==="call"&&c.includes(T.fromNodeId)).map(T=>T.toNodeId)),L=new Set(Tn([...x,...E?[]:C]));for(let T of L)S.add(T);let w=Tn(v.flatMap(T=>b.has(T.fromNodeId)||b.has(T.toNodeId)?[T.fromNodeId,T.toNodeId]:[])),R=t.nodes.filter(T=>T.disposition==="emitted"&&T.kind!=="structural-region"&&v.some(Z=>Z.fromNodeId===T.id||Z.toNodeId===T.id)).map(T=>T.id),M=Tn([...u,...l,...c,...p,...L,...w,...R]).filter(T=>r.has(T)),_=[];for(let T of M)E&&!b.has(T)&&!g.has(T)&&!L.has(T)||_.length>=i&&!b.has(T)||_.push(T);let D=new Set(_),P=new Map(_.map(T=>[T,MP(T)])),k=new Set([...l,...u]),V=new Set(t.anchors.flatMap(T=>T.nodeIds)),le=_.map((T,Z)=>{let Q=r.get(T),Se=CP(Q,o);for(let it of Se)s.add(gr(Q.location.file,it));return{id:P.get(T),nodeId:T,order:Z,role:V.has(T)?"anchor":k.has(T)?"connector":"junction",kind:Q.kind,label:Q.label,location:Q.location,behavior:yP(e,Q,V.has(T),[...new Set([...Se,...vP(e,Q,y,r,I,S)])],Se,S.has(Q.id)&&(Se.length===0||V.has(Q.id)),L.has(Q.id),h.has(Q.id)&&Se.length===0)}}),G=new Map;for(let T of t.paths)for(let Z=0;Z<T.edgeIds.length;Z+=1){let Q=a.get(T.edgeIds[Z]),Se=T.nodeIds[Z],it=T.nodeIds[Z+1];!Q||!Se||!it||G.set(Q.id,Q.fromNodeId===Se&&Q.toNodeId===it?"forward":"reverse")}let N=y.filter(T=>D.has(T.fromNodeId)&&D.has(T.toNodeId)).sort((T,Z)=>DP(T,Z,t)).map((T,Z)=>({id:PP(T.id),edgeId:T.id,order:Z,kind:T.kind,fromStepId:P.get(T.fromNodeId),toStepId:P.get(T.toNodeId),directed:!0,pathTraversal:G.get(T.id)??"adjacent",evidence:T.evidence})),K=new Map(N.map(T=>[T.edgeId,T.id])),ne=t.paths.map(T=>({id:T.id,status:T.status,stepIds:T.nodeIds.flatMap(Z=>{let Q=P.get(Z);return Q?[Q]:[]}),transitionIds:T.edgeIds.flatMap(Z=>{let Q=K.get(Z);return Q?[Q]:[]})})),fe=le.flatMap(T=>T.location?[`${T.location.file}:${T.location.line+1}`]:[]),he=t.anchors.some(T=>T.status==="ambiguous"),ce=ne.some(T=>T.status==="connected"||T.status==="candidate"),be=ne.some(T=>T.status==="partial");return{status:le.length===0?"unavailable":he?"ambiguous":ce&&!be?"connected":be?"partial":"connected",steps:le,transitions:N,paths:ne,coverage:{candidateNodes:M.length,returnedNodes:_.length,omittedNodeIds:M.filter(T=>!D.has(T)),returnedTransitions:N.length,withheldStatements:le.reduce((T,Z)=>T+(Z.behavior?.coverage.omittedStatements??0),0),requestedFocusLocations:o,matchedFocusLocations:o.filter(T=>s.has(gr(T.file,T.line))),unmatchedFocusLocations:o.filter(T=>!s.has(gr(T.file,T.line)))},behaviorCommand:Ny(fe,"behavior"),exactSourceCommand:Ny(fe,"source")}}function hP(e,t,n,i){if(i<=0||n.length===0)return[];let r=new Set(t),o=new Set(n.map(s=>gr(s.file,s.line)));return Tn(e.edges.filter(s=>s.disposition!=="excluded"&&s.disposition!=="unsupported"&&["call","runtime-boundary"].includes(s.kind)&&r.has(s.fromNodeId)&&s.evidence.some(a=>!["candidate","unknown"].includes(a.strength)&&a.location&&o.has(gr(a.location.file,a.location.line)))).sort((s,a)=>{let l=s.evidence.find(u=>u.location)?.location,c=a.evidence.find(u=>u.location)?.location;return(l?.file??"").localeCompare(c?.file??"")||(l?.line??Number.MAX_SAFE_INTEGER)-(c?.line??Number.MAX_SAFE_INTEGER)||s.id.localeCompare(a.id)}).map(s=>s.toNodeId)).slice(0,i)}function yP(e,t,n,i,r,o,s,a){if(!t.location||!["symbol","source-construct","runtime-boundary-participant"].includes(t.kind))return null;let l=t.location.endLine??t.location.line,c=re(e,t.location.file),u=i.length>0?i:[t.location.line],d=t.kind==="runtime-boundary-participant"?yt(e,t.location.file,0,Math.max(0,c.length-1),[t.location.line]):yt(e,t.location.file,t.location.line,l,u),m=i.filter(L=>L>=d.startLine&&L<=d.endLine),f=rr(e,t.location.file,d.startLine,d.endLine,m),p=f??(m.length>0?rr(e,t.location.file,d.startLine,d.endLine,m,{requireSavings:!1}):null),g=m.length>0?RP(e,t,d.startLine,d.endLine,m,p,o):null,h=c.slice(d.startLine,d.endLine+1).join(`
64
- `).length,b=En(e,t.location.file,d.startLine,d.endLine),v=c.slice(d.startLine,d.endLine+1).some((L,w)=>L.length>pP&&(b.get(d.startLine+w)??[]).some(R=>["binding","branch","loop","call","return","throw","mutation"].includes(R))),y=L=>bP(e,t,d.startLine,d.endLine,r.filter(w=>w>=d.startLine&&w<=d.endLine),L),I=(s||t.kind==="runtime-boundary-participant"||t.anchorIds.length>0)&&h<=ku,E=n&&(m.length===0||I);if(f&&(a||E))return y(Py(f));if(!a&&!E&&g&&!v&&!I&&g.renderedCharacters<(p?.outlineCharacters??h))return y(g);if(f)return y(Py(f));let S=c.slice(d.startLine,d.endLine+1),x=S.join(`
65
- `),C=En(e,t.location.file,d.startLine,d.endLine);return y({kind:"source",constructKind:"source construct",signature:S.find(L=>L.trim().length>0)?.trim()??t.label,lines:S.map((L,w)=>({line:d.startLine+w,endLine:d.startLine+w,depth:0,signals:C.get(d.startLine+w)??[],text:L,copied:!0})),coverage:{sourceStatements:S.length,representedStatements:S.length,copiedStatements:S.length,omittedStatements:0},rawCharacters:x.length,renderedCharacters:x.length})}function bP(e,t,n,i,r,o){if(!t.location)return o;let s=Iu(e,t.location.file,n,i);if(!s.available)return o;let a=En(e,t.location.file,n,i),l=re(e,t.location.file),c=new Set(r);for(let v of r){let y=Pa(l[v]??"");if(!y)continue;let I=Rn(e,t.location.file,y).find(E=>E>v&&E<=i);I!==void 0&&c.add(I)}let u=[...new Map(s.targets.flatMap(v=>{let y=v.definition,I=y.relativePath===t.location.file&&y.startLine<=i&&y.endLine>=n;if(y.isTypeLike||I)return[];let E=Da(e,y),S=r.length>0&&E&&a.get(v.sourceLine)?.includes("return"),x=E&&c.has(v.sourceLine);return E&&!S&&!x?[]:[[y.symbol,{definition:y,kind:S?"return-value-transformer":x?"focused-causal-target":"compiler-referenced-declaration"}]]})).values()].sort((v,y)=>v.definition.relativePath.localeCompare(y.definition.relativePath)||v.definition.startLine-y.definition.startLine||v.definition.symbol.localeCompare(y.definition.symbol)),d=[],m=u.filter(({kind:v})=>v!=="compiler-referenced-declaration").map(({definition:v})=>({owner:v,depth:1})),f=new Set,p=new Set(u.map(({definition:v})=>v.symbol));for(;m.length>0;){let v=m.shift();if(!v||f.has(v.owner.symbol))continue;f.add(v.owner.symbol);let{owner:y,depth:I}=v,E=Iu(e,y.relativePath,y.startLine,y.endLine);if(!E.available)continue;let S=En(e,y.relativePath,y.startLine,y.endLine),x=re(e,y.relativePath);for(let C of E.targets){let L=C.definition,w=L.relativePath===y.relativePath&&L.startLine<=y.endLine&&L.endLine>=y.startLine;if(L.isTypeLike||w)continue;let R=Da(e,L),M=Pa(x[C.sourceLine]??""),_=R&&M!==null&&Rn(e,y.relativePath,M).some(P=>P>C.sourceLine&&P<=y.endLine&&(S.get(P)??[]).some(k=>["branch","return","throw"].includes(k))),D=R&&((S.get(C.sourceLine)??[]).some(P=>["branch","return","throw"].includes(P))||_);R&&!D||(p.has(L.symbol)||(p.add(L.symbol),d.push({definition:L,kind:R?"focused-causal-target":"compiler-referenced-declaration"})),R&&I<2&&m.push({owner:L,depth:I+1}))}}let g=[...new Map([...u,...d].map(v=>[v.definition.symbol,v])).values()].sort((v,y)=>v.definition.relativePath.localeCompare(y.definition.relativePath)||v.definition.startLine-y.definition.startLine||v.definition.symbol.localeCompare(y.definition.symbol)),h=[],b=[];for(let{definition:v,kind:y}of g){let I=y==="compiler-referenced-declaration"?SP(e,v.relativePath,v.startLine,v.endLine):{startLine:v.startLine,endLine:v.endLine},E=re(e,v.relativePath).slice(I.startLine,I.endLine+1).join(`
66
- `),S=y==="compiler-referenced-declaration"?null:rr(e,v.relativePath,v.startLine,v.endLine,[]),x=S?[S.signature,...S.lines.map(M=>`${M.line+1}${M.signals.length>0?`[${M.signals.join(",")}]`:""} ${M.text}`)].join(" | "):null,C=x&&x.length<E.length?x:E,L={symbol:v.symbol,label:v.leaf,file:v.relativePath,line:I.startLine,endLine:I.endLine},w=y==="compiler-referenced-declaration"?1e3:8e3,R=y==="compiler-referenced-declaration"?12:120;if(C.length>w||I.endLine-I.startLine>R){b.push({...L,reason:"source-too-large"});continue}h.push({kind:y,...L,text:C})}return{...o,...h.length===0?{}:{supportingDeclarations:h},...b.length===0?{}:{omittedSupportingDeclarations:b}}}function SP(e,t,n,i){let r=ae(e,t);if(!r)return{startLine:n,endLine:i};let o=[];_y(r.rootNode,a=>{gP.has(a.type)&&a.startPosition.row<=n&&a.endPosition.row>=i&&o.push(a)});let s=o.sort((a,l)=>a.endPosition.row-a.startPosition.row-(l.endPosition.row-l.startPosition.row)||a.endIndex-a.startIndex-(l.endIndex-l.startIndex))[0];return s?{startLine:s.startPosition.row,endLine:s.endPosition.row}:{startLine:n,endLine:i}}function _y(e,t){t(e);for(let n of e.namedChildren)_y(n,t)}function Py(e){return{kind:"outline",constructKind:e.constructKind,signature:e.signature,lines:e.lines,coverage:e.coverage,rawCharacters:e.rawCharacters,renderedCharacters:e.outlineCharacters}}function vP(e,t,n,i,r,o){if(!t.location||!["symbol","source-construct","runtime-boundary-participant"].includes(t.kind))return[];let s=new Set,a=new Set(te(e,t.location.file)?.callSites.map(l=>l.line)??[]);if(t.kind==="runtime-boundary-participant"&&s.add(t.location.line),o.has(t.id))for(let l of Kr(e,{files:[t.location.file]}))l.source.startLine>=t.location.line&&l.source.startLine<=(t.location.endLine??t.location.line)&&s.add(l.source.startLine);for(let l of n){if(l.fromNodeId!==t.id&&l.toNodeId!==t.id)continue;let c=i.get(l.fromNodeId===t.id?l.toNodeId:l.fromNodeId),u=o.has(t.id)&&["call","reference","runtime-boundary"].includes(l.kind)&&l.fromNodeId===t.id,d=(c?.anchorIds.length??0)>0;if(!r.has(l.id)&&!u&&!d)continue;let m=l.evidence.flatMap(b=>b.location?.file===t.location.file?[b.location.line]:[]),f=m.filter(b=>a.has(b));for(let b of f.length>0?f:m)s.add(b);let p=c?.attributes.leaf;if(typeof p!="string"||p.length===0)continue;let g=Rn(e,t.location.file,p).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((l,c)=>l-c)}function CP(e,t){if(!e.location)return[];let n=e.location.endLine??e.location.line;return t.filter(i=>i.file===e.location.file&&i.line>=e.location.line&&i.line<=n).map(i=>i.line)}function xP(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(gr(n.file,n.line),{file:n.file,line:n.line})}return[...t.values()].sort((n,i)=>n.file.localeCompare(i.file)||n.line-i.line)}function gr(e,t){return`${e}\0${t}`}function RP(e,t,n,i,r,o,s){if(!t.location)return null;let a=re(e,t.location.file),l=En(e,t.location.file,n,i),c=[...l].filter(([,D])=>D.length>0).map(([D])=>D).sort((D,P)=>D-P),u=r.map(D=>(l.get(D)??[]).length>0?D:c.find(P=>P>D&&P-D<=8)??D),d=new Set([...r,...u]),m=s?yc(e,t.location.file,n,i,{minimumBodyLines:0}):null,f=o?[...new Map(u.flatMap(D=>o.lines.filter(P=>P.text.length<=500&&P.signals.some(k=>["branch","loop","catch","finally"].includes(k))&&D>=P.line&&D<=P.endLine).sort((P,k)=>P.endLine-P.line-(k.endLine-k.line)||P.line-k.line).slice(0,2).map(P=>[`${P.line}\0${P.endLine}`,P]))).values()]:ea(e,t.location.file,n,i,u);for(let D of m?.lines??[])d.add(D.line);for(let D of f)d.add(D.line);for(let[D,P]of l)P.includes("call")&&P.includes("shape")&&d.add(D);let p=[];for(let D of u){let P=Pa(a[D]??"");if(!P)continue;let k=Rn(e,t.location.file,P).filter(N=>N>D&&N<=i),V=k[0];V!==void 0&&d.add(V);let le=k.find(N=>(l.get(N)??[]).some(K=>K==="branch"||K==="loop"));if(le===void 0)continue;d.add(le);let G=(o?.lines??[]).find(N=>N.line===le)??{line:le,endLine:Math.min(i,le+40),depth:0,signals:l.get(le)??[],text:(a[le]??"").trim(),copied:!0},X=o?.lines??a.slice(G.line,G.endLine+1).map((N,K)=>{let ne=G.line+K;return{line:ne,endLine:ne,depth:0,signals:l.get(ne)??[],text:N.trim(),copied:!0}});p.push({focusLine:D,governingUse:le,lines:X.filter(N=>N.line>=G.line&&N.line<=G.endLine&&N.text.length<=500&&N.signals.some(K=>["binding","branch","call","mutation"].includes(K)))})}for(let D of p.sort((P,k)=>k.governingUse-k.focusLine-(P.governingUse-P.focusLine)||P.focusLine-k.focusLine).slice(0,2))for(let P of D.lines.slice(0,14))d.add(P.line);let g=new Set(["binding","branch","loop","call","return","throw","mutation"]);for(let D of f)for(let P of o?.lines??[])P.line<D.line||P.line>D.endLine||P.signals.some(k=>g.has(k))&&d.add(P.line);let h=a.slice(n,i+1).flatMap((D,P)=>{let k=Pa(D);return k?[{name:k,line:n+P}]:[]}),b=!0;for(;b;){b=!1;for(let D of h)if([...d].some(k=>EP(a[k]??"",D.name))){d.has(D.line)||(d.add(D.line),b=!0);for(let k of Rn(e,t.location.file,D.name))k<n||k>i||d.has(k)||(l.get(k)??[]).some(V=>g.has(V))&&(d.add(k),b=!0)}}for(let D of o?.lines??[])if(D.signals.some(P=>["branch","loop","catch","finally"].includes(P))&&d.has(D.line))for(let P of o?.lines??[])P.line<D.line||P.line>D.endLine||P.signals.some(k=>g.has(k))&&d.add(P.line);let v=te(e,t.location.file),y=new Set(v?.callSites.map(D=>D.line)??[]),I=l,E=new Map([...o?.lines??[],...f].filter(D=>D.signals.some(P=>["branch","loop","catch","finally"].includes(P))).map(D=>[D.line,D])),S=new Map((o?.lines??[]).filter(D=>D.text.length<=500&&D.signals.includes("shape")&&(D.signals.includes("call")||D.signals.includes("mutation")||D.signals.includes("return"))).sort((D,P)=>D.endLine-D.line-(P.endLine-P.line)||D.line-P.line).map(D=>[D.line,D])),x=new Map((m?.lines??[]).map(D=>[D.line,D.signals.filter(P=>P!=="lifecycle")])),C=[...d].filter(D=>D>=n&&D<=i).sort((D,P)=>D-P).map(D=>{let P=E.get(D)??S.get(D);return{line:D,endLine:P?.endLine??D,depth:P?.depth??0,signals:IP([...I.get(D)??[],...o?.lines.filter(k=>D>=k.line&&D<=k.endLine).flatMap(k=>k.signals)??[],...x.get(D)??[],...r.includes(D)?["anchor"]:[],...y.has(D)?["call"]:[]]),text:P?.text??(a[D]??"").trim(),copied:P?.copied??!0}}).filter(D=>D.text.length>0);if(C.length===0)return null;let L=m?.candidateLines??yc(e,t.location.file,n,i,{minimumBodyLines:0})?.candidateLines??0,w=Math.max(o?.coverage.sourceStatements??0,L,C.length),R=o?.signature??(a[n]??t.label).trim(),M=R.length+C.reduce((D,P)=>D+P.text.length+P.signals.join(",").length+12,0),_=a.slice(n,i+1).join(`
67
- `).length;return{kind:"connector-slice",constructKind:o?.constructKind??"source construct",signature:R,lines:C,coverage:{sourceStatements:w,representedStatements:C.length,copiedStatements:C.length,omittedStatements:Math.max(0,w-C.length)},rawCharacters:_,renderedCharacters:M}}function IP(e){let t=["anchor","signature","binding","branch","loop","call","await","return","throw","mutation","shape","spread","catch","finally"],n=new Set(e);return t.filter(i=>n.has(i))}function Pa(e){return/\b(?:const|let|var)\s+([\p{L}_$][\p{L}\p{N}_$]*)\s*(?:=|\bof\b|\bin\b)/u.exec(e)?.[1]??null}function EP(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`(?:^|[^\\p{L}\\p{N}_$])${n}(?:$|[^\\p{L}\\p{N}_$])`,"u").test(e)}function wP(e,t,n){return Tn(e.flatMap(i=>{let r=n.get(i),o=t.filter(s=>s.kind==="call"&&s.toNodeId===i).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 l=Ty(a.edge)-Ty(s.edge);if(l!==0)return l;let c=Fy(s.node,r)?0:1,u=Fy(a.node,r)?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 c-u||d-m||s.node.label.localeCompare(a.node.label)});return o[0]?[o[0].node.id]:[]}))}function Ty(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 Fy(e,t){return!e.location||!t?.location?!1:ky(e.location.file)===ky(t.location.file)}function ky(e){return e.split("/").filter(Boolean).slice(0,2).join("/")}function LP(e,t,n,i){let r=new Set(e),o=new Set,s=[],a=Tn(e);for(let l=0;l<i&&a.length>0;l+=1){let c=a.filter(d=>!o.has(d));for(let d of c)o.add(d);let u=wP(c,t,n);a=[];for(let d of u)!r.has(d)&&!s.includes(d)&&s.push(d),o.has(d)||a.push(d)}return s}function DP(e,t,n){let i=new Map(n.paths.flatMap(r=>r.edgeIds).map((r,o)=>[r,o]));return(i.get(e.id)??Number.MAX_SAFE_INTEGER)-(i.get(t.id)??Number.MAX_SAFE_INTEGER)||e.id.localeCompare(t.id)}function MP(e){return`step:${e}`}function PP(e){return`transition:${e}`}function Ny(e,t){return e.length===0?null:`codebaseiq inspect ${e.map(n=>`--at ${TP(n)}`).join(" ")} --view ${t}`}function TP(e){return`'${e.replace(/'/gu,`'"'"'`)}'`}function Tn(e){return[...new Set(e)]}var By=4,FP=3,kP=12,NP=48,AP=64,Fi=10,Pi=6,_P=24,BP=320,Nu=6,OP=12,$P=1,jP=4,HP=7,UP=12,$u="source-construct:",zP=96,qP=32,Oy=4,KP=32,GP=8;function WP(e,t,n={}){let i=Qy(t),r=kT(t);if(i.length===0)throw new Error("Anchor discovery requires at least one non-trivial repository term.");let o=n.limit??By,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 U(e),l=a.scopedDefinitions(n.scope).filter(N=>!De(N.symbol)),c=[...l],u=new Map(c.map(N=>[N.symbol,N])),d=new Map;for(let N of l)$y(d,N,i);let m=qs(e,{scope:n.scope});for(let N of m.files){let ne=W(e,N.relativePath).filter(he=>!De(he.symbol));if(ne.length===0)continue;let fe=Xy(N.text);for(let he=0;he<fe.length;he+=1){let ce=mt(fe[he]??""),be=i.filter(Z=>ce.has(Z));if(be.length===0)continue;let T=Ke(ne,he);if(!(!T||De(T.symbol)))for(let Z of be)xo(d,T,Z,"source",N.relativePath,he)}}let f=jy(d),p=[...d.values()].map(N=>Ta(N,f,r)).sort(Ze),g=JP(m.files,p,i),h=-1;for(let N of g){let K=W(e,N.relativePath),ne=K.filter(T=>!De(T.symbol)),fe=te(e,N.relativePath)?.callables??[],he=new Map,ce=T=>{let Z=`${T.startLine}\0${T.endLine}\0${T.name}`,Q=he.get(Z);if(Q)return Q;let Se=VP(N.relativePath,K,T,()=>h--);return Se?(he.set(Z,Se),c.push(Se),u.set(Se.symbol,Se),$y(d,Se,i),Se):null};for(let T of fe){let Z=mt(T.name);i.some(Q=>Z.has(Q))&&ce(T)}if(fe.length===0)continue;let be=Xy(N.text);for(let T=0;T<be.length;T+=1){let Z=mt(be[T]??""),Q=i.filter(Ki=>Z.has(Ki));if(Q.length===0)continue;let Se=YP(fe,T),it=Se?ce(Se):null;if(!it)continue;let fi=Hy(ne,T);if(Hy(fi?[fi,it]:[it],T)?.symbol===it.symbol)for(let Ki of Q)xo(d,it,Ki,"source",N.relativePath,T)}}let b=jy(d),v=new Map(m.files.map(N=>[N.relativePath,N.text.split(/\r?\n/u)]));for(let N of d.values()){let K=v.get(N.definition.relativePath);K&&(N.sourceCharacters=K.slice(N.definition.startLine,N.definition.endLine+1).join(`
68
- `).length)}let y=[...d.values()].map(N=>Ta(N,b,r)).sort(Ze),I=Math.min(y.length,Math.max(kP,o*FP)),E=s?y:hr([...y.slice(0,I),...[...y].sort(_u).slice(0,Math.max(NP,I)),...wT(y,i),...LT(y,i,b)]),S=E.length,x=E.map(N=>u.get(N.symbol)).filter(N=>N?.isFunctionLike===!0),C=XP(c),L=QP(e,a,E,x,u,C,new Set(d.keys()),n.semantic!==!1),w=tT(L,E,d,b,u),R=nT(w,b,i),M=hT(e,a,L,d,b,c,u,n.semantic!==!1),D=[...rT(e,a,w,u,b,n.semantic!==!1),...R,...w,...M].map(N=>({...N,queryPathMatches:MT(N)})).sort((N,K)=>Ti(N,K,b)),P=s?D:PT(D,o,b),k=i.filter(N=>b.has(N)),V=i.filter(N=>!b.has(N)),le=Math.max(0,y.length-S),G=Math.max(0,D.length-P.length)+le,X=s?y.length:Math.min(y.length,o+By);return{query:t,queryPathFragments:r,normalizedTerms:i,matchedTerms:k,unmatchedTerms:V,groups:P,candidateRoots:y,candidateRootCount:y.length,analyzedRootCount:S,omittedRootCount:le,omittedGroupCount:G,scannedFiles:m.files.length,scannedBytes:m.scannedBytes,recoveryCommand:G===0?null:`codebaseiq anchors ${Aa(t)}${n.scope?` --scope ${Aa(n.scope)}`:""} --limit ${X}`}}function Qy(e){let t=So(e).filter(n=>!bu.has(n.toLocaleLowerCase())).map(Ea).filter(n=>n.length>=3&&!bu.has(n));return[...new Set(t)]}function $y(e,t,n){let i=mt(t.leaf),r=mt(t.relativePath),o=mt(t.documentation??"");for(let a of n)i.has(a)&&xo(e,t,a,"symbol"),r.has(a)&&xo(e,t,a,"path"),o.has(a)&&xo(e,t,a,"documentation");let s=e.get(t.symbol);s&&(s.symbolPhraseLength=AT(t.leaf,n))}function xo(e,t,n,i,r,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(i),r!==void 0&&o!==void 0&&a.locations.set(`${r}\0${o}`,{file:r,line:o}),s.matches.set(n,a),e.set(t.symbol,s)}function jy(e){let t=new Map;for(let n of e.values())for(let i of n.matches.keys())t.set(i,(t.get(i)??0)+1);return t}function VP(e,t,n,i){let r=t[0]?.documentId;if(r===void 0||t.find(a=>a.isFunctionLike&&a.leaf===n.name&&a.startLine===n.startLine&&a.endLine===n.endLine))return null;let s=i();return{documentId:r,symbolId:s,symbol:`${$u}${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 JP(e,t,n){let i=new Set(t.slice(0,zP).map(s=>s.file)),r=new Set(n),o=e.map(s=>{let a=mt(s.relativePath),l=s.relativePath.slice(s.relativePath.lastIndexOf("/")+1).replace(/\.[^.]+$/u,""),c=mt(l),u=[...a].filter(m=>r.has(m)).length,d=[...c].filter(m=>r.has(m)).length;return{file:s,score:d*4+u}}).filter(s=>s.score>0).sort((s,a)=>a.score-s.score||Vt(J(s.file.relativePath))-Vt(J(a.file.relativePath))||s.file.relativePath.localeCompare(a.file.relativePath)).slice(0,qP);for(let s of o)i.add(s.file.relativePath);return e.filter(s=>i.has(s.relativePath))}function YP(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,i)=>n.endLine-n.startLine-(i.endLine-i.startLine)||n.startLine-i.startLine)[0]}function XP(e){let t=new Map;for(let n of e){if(!cn(n))continue;let i=`${n.relativePath}\0${un(n.leaf)}`,r=t.get(i)??[];r.push(n),t.set(i,r)}return t}function Hy(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,i)=>n.endLine-n.startLine-(i.endLine-i.startLine)||Number(cn(i))-Number(cn(n))||n.startLine-i.startLine||n.symbol.localeCompare(i.symbol))[0]}function cn(e){return e.symbol.startsWith($u)}function ei(e){return cn(e)?e.leaf:A(e.symbol)}function Ta(e,t,n=[]){let i=e.definition,r=[...e.matches.entries()].map(([c,u])=>({term:c,sources:[...u.sources].sort(_T),locations:[...u.locations.values()].sort(tb).slice(0,3)})).sort((c,u)=>c.term.localeCompare(u.term)),o=r.filter(c=>c.sources.some(u=>u!=="source")).map(c=>c.term),s=r.filter(c=>c.sources.includes("symbol")).map(c=>c.term),a=r.reduce((c,u)=>c+1/Math.max(1,t.get(u.term)??1),0),l=r.filter(c=>c.sources.includes("symbol")).reduce((c,u)=>c+1/Math.max(1,t.get(u.term)??1),0);return{symbol:i.symbol,label:ei(i),leaf:i.leaf,file:i.relativePath,line:i.startLine,endLine:i.endLine,kind:i.isFunctionLike?"callable":i.isTypeLike?"type":"symbol",fileKind:J(i.relativePath),matches:r,focusLocations:$T(e,t),matchedTerms:r.map(c=>c.term),symbolMatchedTerms:s,symbolPhraseLength:e.symbolPhraseLength,identityMatchedTerms:o,rarity:a,symbolRarity:l,queryPathMatches:NT(i.relativePath,n),...e.sourceCharacters===void 0?{}:{sourceCharacters:e.sourceCharacters}}}function QP(e,t,n,i,r,o,s,a){let l=i.filter(g=>!cn(g)),c=t.calleeMap(l,{additive:!1,semantic:a}),u=new Map,d=new Map;for(let g of n){let h=r.get(g.symbol),b=h?cn(h)?Uy(e,h,r,o,1):Fa(e,h,c.get(h.symbolId)??[],r,1,s):[];u.set(g.symbol,b);for(let v of b){let y=r.get(v.toSymbol);y?.isFunctionLike&&(!h||!cn(h)||cn(y))&&d.set(y.symbol,y)}}let m=[...d.values()],f=t.calleeMap(m.filter(g=>!cn(g)),{additive:!1,semantic:a}),p=new Map;for(let g of m)p.set(g.symbol,cn(g)?Uy(e,g,r,o,2):Fa(e,g,f.get(g.symbolId)??[],r,2,s));return n.map(g=>{let h=u.get(g.symbol)??[],b=h.flatMap(y=>p.get(y.toSymbol)??[]),v=Fn([...h,...b]);return{root:g,relations:v,nodeSymbols:new Set([g.symbol,...v.flatMap(y=>[y.fromSymbol,y.toSymbol])])}})}function Fa(e,t,n,i,r,o=new Set){let s=new Map;for(let a of n){let l=i.get(a.symbol);if(!l?.isFunctionLike||l.symbol===t.symbol||a.source==="ast-callsite"&&!eT(e,t,l,a.callsiteLine))continue;let c=s.get(l.symbol);(!c||FT(a,c)<0)&&s.set(l.symbol,a)}return[...s.entries()].map(([a,l])=>{let c=i.get(a);return{kind:"call",fromSymbol:t.symbol,fromLabel:A(t.symbol),fromFile:t.relativePath,toSymbol:c.symbol,toLabel:A(c.symbol),toFile:c.relativePath,depth:r,strength:Ou(l.source),evidence:l.source,callsiteLine:l.callsiteLine??ZP(e,t,c)}}).sort((a,l)=>Number(o.has(l.toSymbol))-Number(o.has(a.toSymbol))||dn(a,l)).slice(0,AP)}function Uy(e,t,n,i,r){let o=Dn(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:ei(t),fromFile:t.relativePath,toSymbol:a.symbol,toLabel:ei(a),toFile:a.relativePath,depth:r,strength:"exact",evidence:"scip-occurrence-callsite",callsiteLine:s.sourceLine}]});for(let s of Zn(e,t.relativePath,{ranges:[{startLine:t.startLine,endLine:t.endLine}],excludeIndexedTargets:!1}).targets){let a=[...i.get(`${s.targetFile}\0${un(s.calleeLeaf)}`)??[],...W(e,s.targetFile).filter(l=>l.isFunctionLike&&un(l.leaf)===s.calleeLeaf)].find(l=>l.startLine===s.targetStartLine&&l.endLine===s.targetEndLine);!a||a.symbol===t.symbol||o.push({kind:"call",fromSymbol:t.symbol,fromLabel:ei(t),fromFile:t.relativePath,toSymbol:a.symbol,toLabel:ei(a),toFile:a.relativePath,depth:r,strength:s.strength==="exact"?"exact":"derived",evidence:"ast-member-import-candidate",callsiteLine:s.line})}for(let s of te(e,t.relativePath)?.callSites??[]){if(s.line<t.startLine||s.line>t.endLine||s.memberAccess)continue;let a=(i.get(`${t.relativePath}\0${un(s.calleeLeaf)}`)??[]).filter(c=>c.symbol!==t.symbol);if(a.length!==1)continue;let l=a[0];o.push({kind:"call",fromSymbol:t.symbol,fromLabel:ei(t),fromFile:t.relativePath,toSymbol:l.symbol,toLabel:ei(l),toFile:l.relativePath,depth:r,strength:"derived",evidence:"ast-callsite",callsiteLine:s.line})}return Fn(o).sort(dn)}function ZP(e,t,n){let i=un(n.leaf);return te(e,t.relativePath)?.callSites.find(r=>r.line>=t.startLine&&r.line<=t.endLine&&un(r.calleeLeaf)===i)?.line??null}function eT(e,t,n,i){if(i===void 0)return!1;let r=un(n.leaf);return te(e,t.relativePath)?.callSites.some(o=>o.line===i&&un(o.calleeLeaf)===r)??!1}function un(e){return e.replace(/^#/u,"").replace(/\(\)$/u,"")}function tT(e,t,n,i,r){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},l=(u,d)=>{let m=a(u),f=a(d);m!==f&&(s[f]=m)};for(let u of e){let d=o.get(u.root.symbol);if(d!==void 0)for(let m of u.nodeSymbols){let f=o.get(m);f!==void 0&&l(d,f)}}let c=new Map;for(let u=0;u<t.length;u+=1){let d=a(u),m=c.get(d)??[];m.push(t[u]),c.set(d,m)}return[...c.values()].map((u,d)=>{let m=new Set(u.map(y=>y.symbol)),f=Fn(e.filter(y=>m.has(y.root.symbol)).flatMap(y=>y.relations)).sort(dn),p=new Map(u.map(y=>[y.symbol,y]));for(let y of new Set(f.flatMap(I=>[I.fromSymbol,I.toSymbol]))){let I=n.get(y);if(I)p.has(y)||p.set(y,Ta(I,i));else{let E=r.get(y);E&&p.set(y,eb(E))}}let g=RT(u,f,p),h=u.filter(y=>f.some(I=>I.fromSymbol===y.symbol)).length,b=[...new Set(u.flatMap(y=>y.matchedTerms))].sort(),v=xT(f,g,m,p);return{id:`anchor-set:${d+1}:${Io(u[0])}`,kind:"connected-flow",roots:[...u].sort(Ze),keyAnchors:g,candidateOwnerCount:g.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:[],matchedTerms:b,relations:v,relationCount:f.length,orchestrationRootCount:h,omittedRelations:Math.max(0,f.length-Fi),systemMapCommand:wo(g,f,b)}})}function nT(e,t,n){let i=new Map(n.map((o,s)=>[o,s])),r=[];for(let o=0;o<e.length;o+=1){let s=e[o],a=zy(s);if(a.size!==0)for(let l=o+1;l<e.length;l+=1){let c=e[l],u=zy(c),d=[...a].filter(E=>u.has(E));if(d.length===0||![...a].some(E=>!u.has(E))||![...u].some(E=>!a.has(E)))continue;let m=iT(s,c);if(m.length<2)continue;let f=Fn([...s.relations,...c.relations]).sort(dn),p=f.slice(0,Fi),g=hr([...s.roots,...c.roots]).sort(Ze),h=[...new Set([...s.matchedTerms,...c.matchedTerms])].sort(),b=d.sort((E,S)=>(i.get(E)??Number.MAX_SAFE_INTEGER)-(i.get(S)??Number.MAX_SAFE_INTEGER)||E.localeCompare(S)),v=+(s.relationCount>0)+ +(c.relationCount>0),y=+((s.orchestrationRootCount??0)>0)+ +((c.orchestrationRootCount??0)>0),I=Math.min(...b.map(E=>t.get(E)??Number.MAX_SAFE_INTEGER));r.push({sharedOrder:Math.min(...b.map(E=>i.get(E)??Number.MAX_SAFE_INTEGER)),sharedFrequency:I,connectedSides:v,orchestrationSides:y,group:{id:`parallel-paths:${Io(s.roots[0])}:${Io(c.roots[0])}`,kind:"parallel-paths",roots:g,keyAnchors:m,candidateOwnerCount:m.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:[...s.upstreamEntries,...c.upstreamEntries],matchedTerms:h,relations:p,relationCount:f.length,parallelConnectedSides:v,parallelOrchestrationSides:y,parallelSharedPathTerms:b,parallelSharedPathFrequency:I,orchestrationRootCount:(s.orchestrationRootCount??0)+(c.orchestrationRootCount??0),omittedRelations:Math.max(0,f.length-p.length),systemMapCommand:wo(m,f,h)}})}}return r.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||Ti(o.group,s.group,t)).slice(0,UP).map(o=>o.group)}function zy(e){return new Set(e.roots.flatMap(t=>t.matches.filter(n=>n.sources.includes("path")).map(n=>n.term)))}function iT(e,t){return hr([qy(e),qy(t)].filter(n=>n!==void 0))}function qy(e){let t=new Set(e.keyAnchors.map(i=>i.symbol)),n=new Map;for(let i of e.relations)!t.has(i.fromSymbol)||!t.has(i.toSymbol)||n.set(i.fromSymbol,(n.get(i.fromSymbol)??0)+1);return[...e.keyAnchors].sort((i,r)=>+((n.get(r.symbol)??0)>0)-+((n.get(i.symbol)??0)>0)||Ky(r)-Ky(i)||r.identityMatchedTerms.length-i.identityMatchedTerms.length||r.symbolMatchedTerms.length-i.symbolMatchedTerms.length||(n.get(r.symbol)??0)-(n.get(i.symbol)??0)||Ze(i,r))[0]}function Ky(e){return e.matchedTerms.length+e.identityMatchedTerms.length*2+(e.queryPathMatches?.length??0)*4}function rT(e,t,n,i,r,o){let s=Hs(e);if(!s||s.links.length===0||n.length<2)return[];let a=new Map(s.observations.map(f=>[f.id,f])),l=new Map,c=new Map,u=[...n].sort((f,p)=>Ti(f,p,r)).slice(0,OP),d=s.links.filter(f=>f.strength!=="candidate").sort((f,p)=>ti(p.strength)-ti(f.strength)||p.matchedKeyParts.length-f.matchedKeyParts.length||f.id.localeCompare(p.id));for(let f of u)for(let p of d){let g=a.get(p.from),h=a.get(p.to);if(!g||!h||!oT(f,g,i))continue;let b=sT(f,g,i);if(!b)continue;let v=l.get(h.id)??cT(e,t,h,i,o,jP);if(l.set(h.id,v),v.reachedSymbols.size===0)continue;let y=n.filter(D=>D.id!==f.id&&aT(D).some(P=>v.reachedSymbols.has(P))&&Au(b,D)>=2).sort((D,P)=>Au(b,P)-Au(b,D)||Ti(D,P,r)).slice(0,$P);if(y.length===0)continue;let I=[f.id,g.id,...y.map(D=>D.id).sort()].join("\0");if(c.has(I))continue;let E=new Set(y.flatMap(Eo)),S=pT(Ro(h),E,v.relations);if(S.length===0)continue;let x=fT(g,h,p.joinRule,p.matchedKeyParts,p.strength),C=Fn([x,...v.relations,...f.relations,...y.flatMap(D=>D.relations)]),L=gT([x,...S],C,f,y),w=hr([b,...y.flatMap(D=>D.roots)]).sort(Ze),R=hr([b,...y.flatMap(D=>D.keyAnchors)]).slice(0,HP),M=[...new Set([...b.matchedTerms,...y.flatMap(D=>D.matchedTerms)])].sort(),_=lT(e,t,b,i,o);w.length===0||R.length<2||c.set(I,{id:`cross-boundary-set:${Io(b)}:${c.size+1}`,kind:"cross-boundary-flow",roots:w,keyAnchors:R,candidateOwnerCount:R.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:_,matchedTerms:M,relations:L,relationCount:C.length,omittedRelations:Math.max(0,C.length-L.length),systemMapCommand:wo(R,C,M)})}let m=new Map;for(let[f,p]of c){let g=f.slice(0,f.indexOf("\0")),h=m.get(g);(!h||Ti(p,h,r)<0)&&m.set(g,p)}return[...m.values()]}function oT(e,t,n){let i=new Set(Eo(e));return t.owner.symbol&&i.has(t.owner.symbol)?!0:[...i].map(r=>n.get(r)).some(r=>r?.relativePath===t.source.file&&r.startLine<=t.source.startLine&&r.endLine>=t.source.endLine)}function sT(e,t,n){let i=hr([...e.roots,...e.keyAnchors]);if(t.owner.symbol){let r=i.find(o=>o.symbol===t.owner.symbol);if(r)return r}return i.find(r=>{let o=n.get(r.symbol);return o?.relativePath===t.source.file&&o.startLine<=t.source.startLine&&o.endLine>=t.source.endLine})??null}function Eo(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 aT(e){return[...new Set([...e.roots,...e.keyAnchors].map(t=>t.symbol))]}function Au(e,t){let n=mt(e.leaf),i=[...t.roots,...t.keyAnchors].map(o=>mt(o.leaf)),r=0;for(let o of i){let s=0;for(let a of n)o.has(a)&&(s+=1);r=Math.max(r,s)}return r}function lT(e,t,n,i,r){let o=i.get(n.symbol);if(!o?.isFunctionLike)return[];let s=t.callerFileMap([o],{semantic:r,sourceFallback:!0}).get(o.symbolId);if(!s)return[];let a=mt(n.leaf);return[...s].filter(l=>l!==n.file&&J(l)!=="test").flatMap(l=>{let c=te(e,l);return(c?.callSites??[]).filter(u=>un(u.calleeLeaf)===un(n.leaf)).flatMap(u=>{let d=(c?.callables??[]).filter(f=>f.startLine<=u.line&&f.endLine>=u.line).sort((f,p)=>f.endLine-f.startLine-(p.endLine-p.startLine)||f.startLine-p.startLine)[0];if(!d)return[];let m=[...mt(d.name)].filter(f=>a.has(f)).length;return m>=2?[{name:d.name,file:l,line:d.startLine,endLine:d.endLine,callsiteLine:u.line,overlap:m}]:[]})}).sort((l,c)=>c.overlap-l.overlap||l.file.localeCompare(c.file)||l.line-c.line).slice(0,1).map(({name:l,file:c,line:u,endLine:d,callsiteLine:m})=>({name:l,file:c,line:u,endLine:d,callsiteLine:m}))}function cT(e,t,n,i,r,o){let s=uT(e,n,i),a=s.map(({definition:m,evidence:f,line:p})=>({kind:"call",fromSymbol:Ro(n),fromLabel:ka(n),fromFile:n.source.file,toSymbol:m.symbol,toLabel:A(m.symbol),toFile:m.relativePath,depth:1,strength:f==="scip-occurrence-callsite"?"exact":"derived",evidence:f,callsiteLine:p})),l=dT(e,n);a.push(...l.relations);let c=Zy([...s.map(m=>m.definition),...l.definitions]),u=c,d=new Set(u.map(m=>m.symbol));for(let m=2;m<=o+1&&u.length>0;m+=1){let f=t.calleeMap(u,{additive:!1,semantic:r}),p=new Map;for(let g of u){let h=Fa(e,g,f.get(g.symbolId)??[],i,m);a.push(...h);for(let b of h){let v=i.get(b.toSymbol);v?.isFunctionLike&&!d.has(v.symbol)&&p.set(v.symbol,v)}}u=[...p.values()];for(let g of u)d.add(g.symbol)}return{entryDefinitions:c,relations:Fn(a),reachedSymbols:new Set([...c.map(m=>m.symbol),...a.flatMap(m=>[m.fromSymbol,m.toSymbol])])}}function uT(e,t,n){let i=t.owner.symbol?n.get(t.owner.symbol):void 0;if(i?.isFunctionLike&&!De(i.symbol))return[{definition:i,evidence:"scip-occurrence-callsite",line:t.source.startLine}];let r=re(e,t.source.file),o=yt(e,t.source.file,0,Math.max(0,r.length-1),[t.source.startLine]),s=Dn(e,t.source.file,o.startLine,o.endLine).targets.map(u=>({definition:u.definition,evidence:"scip-occurrence-callsite",line:u.sourceLine})),a=te(e,t.source.file),l=rn(e),c=(a?.callSites??[]).flatMap(u=>{if(u.line<o.startLine||u.line>o.endLine)return[];let d=nn(t.source.file,l.get(u.calleeLeaf)??[]),m=qn(e,t.source.file,d,u.memberAccess,u.calleeQualifier),f=m?n.get(m.symbol):void 0;return f?.isFunctionLike?[{definition:f,evidence:"ast-callsite",line:u.line}]:[]});return mT([...s,...c])}function dT(e,t){let n=re(e,t.source.file),i=yt(e,t.source.file,0,Math.max(0,n.length-1),[t.source.startLine]),r=Zn(e,t.source.file,{ranges:[i],excludeIndexedTargets:!1}).targets,o=[],s=[];for(let a of r){let l=`source-construct:${a.targetFile}:${a.targetStartLine}:${a.targetEndLine}:${a.calleeLeaf}`;s.push({kind:"call",fromSymbol:Ro(t),fromLabel:ka(t),fromFile:t.source.file,toSymbol:l,toLabel:a.calleeLeaf,toFile:a.targetFile,depth:1,strength:"derived",evidence:"ast-member-import-candidate",callsiteLine:a.line});let c=Dn(e,a.targetFile,a.targetStartLine,a.targetEndLine).targets;for(let u of c)o.push(u.definition),s.push({kind:"call",fromSymbol:l,fromLabel:a.calleeLeaf,fromFile:a.targetFile,toSymbol:u.definition.symbol,toLabel:A(u.definition.symbol),toFile:u.definition.relativePath,depth:2,strength:"exact",evidence:"scip-occurrence-callsite",callsiteLine:u.sourceLine})}return{definitions:Zy(o),relations:Fn(s)}}function mT(e){return[...new Map(e.map(t=>[t.definition.symbol,t])).values()]}function Zy(e){return[...new Map(e.map(t=>[t.symbol,t])).values()]}function Ro(e){return e.owner.symbol??e.id}function ka(e){return e.owner.name??`${e.source.file}:${e.source.startLine+1}`}function fT(e,t,n,i,r){return{kind:"runtime-boundary",fromSymbol:Ro(e),fromLabel:ka(e),fromFile:e.source.file,toSymbol:Ro(t),toLabel:ka(t),toFile:t.source.file,depth:1,strength:r,evidence:`runtime-boundary:${n}`,callsiteLine:e.source.startLine,runtimeBoundaryKey:i.map(o=>`${o.name}=${o.value}`).join(" ")}}function pT(e,t,n){let i=new Map;for(let s of n){let a=i.get(s.fromSymbol)??[];a.push(s),i.set(s.fromSymbol,a)}let r=[{symbol:e,path:[]}],o=new Set([e]);for(;r.length>0;){let s=r.shift();if(s.path.length>0&&t.has(s.symbol))return s.path;for(let a of(i.get(s.symbol)??[]).sort(dn))o.has(a.toSymbol)||(o.add(a.toSymbol),r.push({symbol:a.toSymbol,path:[...s.path,a]}))}return[]}function gT(e,t,n,i){let r=Fn(e),o=new Set([n,...i].flatMap(s=>[...Eo(s),...s.keyAnchors.map(a=>a.symbol)]));for(let s of t){if(r.length>=Fi)break;!o.has(s.fromSymbol)&&!o.has(s.toSymbol)||r.some(a=>a.fromSymbol===s.fromSymbol&&a.toSymbol===s.toSymbol)||r.push(s)}return r.slice(0,Fi)}function hT(e,t,n,i,r,o,s,a){let l=n.filter(u=>!u.root.symbol.startsWith($u)).map(u=>({root:u.root,relations:u.relations.filter(d=>d.depth===1&&d.fromSymbol===u.root.symbol)}));return yT(l).flatMap((u,d)=>{let m=new Set(u.map(k=>k.root.symbol)),f=new Map;for(let k of u)for(let V of new Set(k.relations.map(le=>le.toSymbol)))f.set(V,(f.get(V)??0)+1);let p=[...f].filter(([,k])=>k>=2).sort(([k,V],[le,G])=>G-V||bT(k,le,i,r,s)).map(([k])=>s.get(k)).filter(k=>k?.isFunctionLike===!0).slice(0,_P);if(p.length===0)return[];let g=t.callerFileMap(p,{semantic:a,sourceFallback:!0}),h=new Set;for(let k of p){h.add(k.relativePath);for(let V of g.get(k.symbolId)??[])h.add(V)}let b=o.filter(k=>k.isFunctionLike&&h.has(k.relativePath)).sort(ST).slice(0,BP),v=t.calleeMap(b,{additive:!1,semantic:a}),y=new Set(p.map(k=>k.symbol)),I=Fn(b.flatMap(k=>Fa(e,k,v.get(k.symbolId)??[],s,1,y).filter(V=>y.has(V.toSymbol)))),E=new Map;for(let k of I){let V=E.get(k.fromSymbol)??new Set;V.add(k.toSymbol),E.set(k.fromSymbol,V)}let S=new Set([...E].filter(([k,V])=>V.size>=2||m.has(k)).map(([k])=>k)),x=I.filter(k=>S.has(k.fromSymbol));if(S.size<2||x.length===0)return[];let L=[...new Set(x.map(k=>k.toSymbol))].map(k=>Na(k,i,r,s)).filter(k=>k!==null).sort(Ze),w=[...S].map(k=>Na(k,i,r,s)).filter(k=>k!==null),R=vT(w,x),M=R.slice(0,Nu),_=R.slice(Nu);if(L.length===0||M.length===0)return[];let D=[...new Set([...L.flatMap(k=>k.matchedTerms),...u.flatMap(k=>k.root.matchedTerms)])].sort(),P=CT(x,M);return[{id:`effect-owner-set:${d+1}:${Io(L[0])}`,kind:"shared-callee-owners",roots:L,keyAnchors:M,candidateOwnerCount:R.length,omittedCandidateOwners:_,ownerRecoveryCommands:jT(_,Nu),upstreamEntries:[],matchedTerms:D,relations:P,relationCount:x.length,omittedRelations:Math.max(0,x.length-P.length),systemMapCommand:wo(M,x,D)}]})}function yT(e){let t=e.map((s,a)=>a),n=s=>{for(;t[s]!==s;)t[s]=t[t[s]],s=t[s];return s},i=(s,a)=>{let l=n(s),c=n(a);l!==c&&(t[c]=l)},r=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 l=0;for(let c of r[s]??[])if((r[a]??new Set).has(c)&&(l+=1),l>=2)break;l>=2&&i(s,a)}let o=new Map;for(let s=0;s<e.length;s+=1){let a=n(s),l=o.get(a)??[];l.push(e[s]),o.set(a,l)}return[...o.values()].filter(s=>s.length>=2)}function bT(e,t,n,i,r){let o=Na(e,n,i,r),s=Na(t,n,i,r);return o?s?Ze(o,s):-1:s?1:e.localeCompare(t)}function ST(e,t){return Vt(J(e.relativePath))-Vt(J(t.relativePath))||e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine}function Na(e,t,n,i){let r=t.get(e);if(r)return Ta(r,n);let o=i.get(e);return o?eb(o):null}function vT(e,t){let n=new Map;for(let r of t){let o=n.get(r.toSymbol)??new Set;o.add(r.fromSymbol),n.set(r.toSymbol,o)}let i=new Map;for(let r of t){let o=n.get(r.toSymbol)?.size??1;i.set(r.fromSymbol,(i.get(r.fromSymbol)??0)+o*o)}return[...e].sort((r,o)=>Number(r.leaf.startsWith("#"))-Number(o.leaf.startsWith("#"))||o.identityMatchedTerms.length-r.identityMatchedTerms.length||(i.get(o.symbol)??0)-(i.get(r.symbol)??0)||Ze(r,o))}function CT(e,t){let n=new Map(t.map((s,a)=>[s.symbol,a])),i=t.map(s=>e.filter(a=>a.fromSymbol===s.symbol).sort(dn)),r=[],o=0;for(;r.length<Fi&&i.some(s=>o<s.length);){for(let s of i){let a=s[o];if(a&&r.push(a),r.length>=Fi)break}o+=1}return r.sort((s,a)=>n.get(s.fromSymbol)-n.get(a.fromSymbol)||dn(s,a))}function xT(e,t,n,i){let r=new Map(t.map((a,l)=>[a.symbol,l])),o=new Map;for(let a of e)o.set(a.fromSymbol,(o.get(a.fromSymbol)??0)+1);return[...e].sort((a,l)=>{let c=u=>{let d=0;return r.has(u.fromSymbol)&&(d+=100),n.has(u.toSymbol)&&(d+=60),d+=Math.min(40,(o.get(u.toSymbol)??0)*8),(i.get(u.toSymbol)?.matchedTerms.length??0)>0&&(d+=25),u.fromFile!==u.toFile&&(d+=15),u.strength==="exact"&&(d+=5),d};return c(l)-c(a)||dn(a,l)}).slice(0,Fi).sort((a,l)=>(r.get(a.fromSymbol)??Pi)-(r.get(l.fromSymbol)??Pi)||a.depth-l.depth||(a.callsiteLine??Number.MAX_SAFE_INTEGER)-(l.callsiteLine??Number.MAX_SAFE_INTEGER)||dn(a,l))}function eb(e){return{symbol:e.symbol,label:ei(e),leaf:e.leaf,file:e.relativePath,line:e.startLine,endLine:e.endLine,kind:e.isFunctionLike?"callable":e.isTypeLike?"type":"symbol",fileKind:J(e.relativePath),matches:[],focusLocations:[],matchedTerms:[],symbolMatchedTerms:[],symbolPhraseLength:0,identityMatchedTerms:[],rarity:0,symbolRarity:0}}function RT(e,t,n){let i=[...e].sort(Ze),r=[],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,l=u=>{if(!(!u||r.some(d=>d.symbol===u.symbol))){r.push(u);for(let d of u.matchedTerms)s.add(d);for(let d of u.symbolMatchedTerms)a.add(d)}},c=i.filter(u=>u.symbolPhraseLength>=2&&(o.get(u.symbol)??0)>=2);for(;r.length<Math.min(2,Pi);){let u=c.filter(d=>!r.some(m=>m.symbol===d.symbol)).sort((d,m)=>m.symbolMatchedTerms.filter(f=>!a.has(f)).length-d.symbolMatchedTerms.filter(f=>!a.has(f)).length||m.symbolPhraseLength-d.symbolPhraseLength||(o.get(m.symbol)??0)-(o.get(d.symbol)??0)||_u(d,m))[0];if(!u||r.length>0&&u.symbolMatchedTerms.every(d=>a.has(d)))break;l(u)}if(l(i[0]),r.length>=2){let u=IT(r[0].symbol,r[1].symbol,t,n);for(let d of u?.slice(1,-1)??[]){if(r.length>=Pi)break;l(n.get(d))}if(r.length<Pi){let d=new Set(r.map(p=>p.symbol)),m=new Set(t.filter(p=>p.depth===1&&d.has(p.fromSymbol)&&d.has(p.toSymbol)).map(p=>p.fromSymbol)),f=t.filter(p=>p.depth===1&&m.has(p.fromSymbol)&&!d.has(p.toSymbol)).map(p=>({relation:p,candidate:n.get(p.toSymbol)})).filter(p=>p.candidate!==void 0&&p.candidate.symbolPhraseLength>=2&&p.candidate.symbolMatchedTerms.length>=2).sort((p,g)=>(o.get(p.relation.fromSymbol)??0)-(o.get(g.relation.fromSymbol)??0)||_u(p.candidate,g.candidate))[0]?.candidate;l(f)}}else for(;r.length<Math.min(3,Pi);){let u=i.filter(d=>!r.some(m=>m.symbol===d.symbol)).sort((d,m)=>m.matchedTerms.filter(f=>!s.has(f)).length-d.matchedTerms.filter(f=>!s.has(f)).length||Ze(d,m))[0];if(!u||u.matchedTerms.every(d=>s.has(d)))break;l(u)}for(;r.length>=2&&r.length<Pi;){let u=new Set(r.map(m=>m.symbol)),d=[...n.values()].filter(m=>!u.has(m.symbol)&&(o.get(m.symbol)??0)>0&&t.some(f=>u.has(f.fromSymbol)&&f.toSymbol===m.symbol)).sort((m,f)=>f.identityMatchedTerms.length-m.identityMatchedTerms.length||f.symbolMatchedTerms.length-m.symbolMatchedTerms.length||f.matchedTerms.length-m.matchedTerms.length||(o.get(f.symbol)??0)-(o.get(m.symbol)??0)||Ze(m,f))[0];if(!d)break;l(d)}if(r.length<2){let u=r[0],d=u?i.filter(m=>m.symbol!==u.symbol).map(m=>({root:m,path:ET(m.symbol,u.symbol,t)})).filter(m=>m.path!==null).sort((m,f)=>+(f.root.file!==u.file)-+(m.root.file!==u.file)||m.path.length-f.path.length||Ze(m.root,f.root))[0]?.root:void 0;l(d)}return r}function IT(e,t,n,i){let r=new Map;for(let a of n){let l=r.get(a.fromSymbol)??new Set;l.add(a.toSymbol),r.set(a.fromSymbol,l);let c=r.get(a.toSymbol)??new Set;c.add(a.fromSymbol),r.set(a.toSymbol,c)}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:l}=o.shift(),c=a.at(-1);if(c===t)return a;for(let u of r.get(c)??[]){let d=i.get(u),m=u===t?1:!d||d.matchedTerms.length===0?9:d.symbolPhraseLength>=2?1:d.identityMatchedTerms.length>=2?2:4,f=l+m;f>=(s.get(u)??Number.POSITIVE_INFINITY)||(s.set(u,f),o.push({path:[...a,u],cost:f}))}}return null}function ET(e,t,n){let i=new Map;for(let s of n){let a=i.get(s.fromSymbol)??[];a.push(s.toSymbol),i.set(s.fromSymbol,a)}let r=[[e]],o=new Set([e]);for(;r.length>0;){let s=r.shift(),a=s.at(-1);if(a===t)return s;for(let l of i.get(a)??[])o.has(l)||(o.add(l),r.push([...s,l]))}return null}function Ze(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||yr(e.kind)-yr(t.kind)||Vt(e.fileKind)-Vt(t.fileKind)||e.file.localeCompare(t.file)||e.line-t.line}function _u(e,t){return t.symbolPhraseLength-e.symbolPhraseLength||t.symbolMatchedTerms.length-e.symbolMatchedTerms.length||yr(e.kind)-yr(t.kind)||t.symbolRarity-e.symbolRarity||Ze(e,t)}function wT(e,t){return t.flatMap(n=>{let i=e.filter(s=>s.matchedTerms.includes(n)).sort((s,a)=>DT(s,a,n)),r=[],o=new Set;for(let s of i)if(!o.has(s.file)&&(r.push(s),o.add(s.file),r.length>=Oy))return r;for(let s of i)if(!r.some(a=>a.symbol===s.symbol)&&(r.push(s),r.length>=Oy))break;return r})}function LT(e,t,n){let i=new Set(t),r=new Map;for(let o of e){if(o.kind!=="callable")continue;let s=o.file.slice(o.file.lastIndexOf("/")+1).replace(/\.[^.]+$/u,"");if(![...mt(s)].some(l=>i.has(l)))continue;let a=r.get(o.file)??[];a.push(o),r.set(o.file,a)}return[...r.entries()].map(([o,s])=>{let a=o.slice(o.lastIndexOf("/")+1).replace(/\.[^.]+$/u,""),l=[...mt(a)].filter(c=>i.has(c));return{file:o,fileCandidates:s,sharedFrequency:Math.min(...l.map(c=>n.get(c)??Number.MAX_SAFE_INTEGER))}}).sort((o,s)=>Vt(o.fileCandidates[0].fileKind)-Vt(s.fileCandidates[0].fileKind)||o.sharedFrequency-s.sharedFrequency||o.file.localeCompare(s.file)).flatMap(({fileCandidates:o})=>[...o].sort(Ze).slice(0,GP)).slice(0,KP)}function DT(e,t,n){return Gy(e,n)-Gy(t,n)||Vt(e.fileKind)-Vt(t.fileKind)||t.symbolPhraseLength-e.symbolPhraseLength||yr(e.kind)-yr(t.kind)||Ze(e,t)}function Gy(e,t){let n=e.matches.find(i=>i.term===t)?.sources??[];return Math.min(...n.map(Bu),Number.MAX_SAFE_INTEGER)}function hr(e){return[...new Map(e.map(t=>[t.symbol,t])).values()]}function Ti(e,t,n){let i=new Set(e.roots.flatMap(o=>o.symbolMatchedTerms)),r=new Set(t.roots.flatMap(o=>o.symbolMatchedTerms));return(t.queryPathMatches?.length??0)-(e.queryPathMatches?.length??0)||Yy(e.kind)-Yy(t.kind)||Vy(e)-Vy(t)||Jy(e)-Jy(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)||Wy(t,n)-Wy(e,n)||t.matchedTerms.length-e.matchedTerms.length||Math.max(...t.roots.map(o=>o.symbolPhraseLength))-Math.max(...e.roots.map(o=>o.symbolPhraseLength))||r.size-i.size||Ze(e.roots[0],t.roots[0])||t.roots.length-e.roots.length||e.relationCount-t.relationCount||e.id.localeCompare(t.id)}function Wy(e,t){return e.matchedTerms.reduce((n,i)=>n+1/Math.max(1,t.get(i)??1),0)}function MT(e){return[...new Set(e.roots.flatMap(t=>t.queryPathMatches??[]))].sort()}function Vy(e){let t=e.keyAnchors.length>0?e.keyAnchors:e.roots;return Math.max(...t.map(n=>Vt(n.fileKind)))}function Jy(e){return e.kind==="parallel-paths"?2-(e.parallelConnectedSides??0):e.kind!=="connected-flow"||e.relationCount>0?0:1}function PT(e,t,n){let i=e.slice(0,t);if(t<2||i.some(o=>o.kind==="shared-callee-owners"))return i;let r=e.filter(o=>o.kind==="shared-callee-owners");for(let o of i){if(o.kind==="shared-callee-owners"||o.kind==="parallel-paths")continue;let s=new Set(Eo(o)),a=r.map(c=>({group:c,overlap:TT(c,s)})).filter(({overlap:c})=>c>0).sort(({group:c,overlap:u},{group:d,overlap:m})=>m-u||Ti(c,d,n))[0]?.group;if(!a)continue;let l=i.length-1;for(;l>=0&&i[l]===o;)l-=1;return l<0?i:(i[l]=a,[...i].sort((c,u)=>Ti(c,u,n)))}return i}function TT(e,t){return Eo(e).filter(n=>t.has(n)).length}function Yy(e){switch(e){case"cross-boundary-flow":return 0;case"parallel-paths":case"connected-flow":return 1;case"shared-callee-owners":return 2}}function dn(e,t){return e.depth-t.depth||ti(t.strength)-ti(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 FT(e,t){return ti(Ou(t.source))-ti(Ou(e.source))||(e.callsiteLine??Number.MAX_SAFE_INTEGER)-(t.callsiteLine??Number.MAX_SAFE_INTEGER)||e.symbol.localeCompare(t.symbol)}function Fn(e){let t=new Map;for(let n of e){let i=`${n.fromSymbol}\0${n.toSymbol}`,r=t.get(i);(!r||dn(n,r)<0)&&t.set(i,n)}return[...t.values()]}function kT(e){let t=e.match(/[\p{L}\d_.-]+(?:\/[\p{L}\d_.-]+)+/gu)??[];return[...new Set(t.map(n=>n.replace(/[.;:!?]+$/gu,"").toLocaleLowerCase()))]}function NT(e,t){let n=e.replace(/\\/gu,"/").toLocaleLowerCase();return t.filter(i=>{let r=n.indexOf(i);if(r<0)return!1;let o=r===0?"/":n[r-1],s=n[r+i.length];return o==="/"&&(s===void 0||s==="/")})}function AT(e,t){let n=So(e).map(Ea),i=0;for(let r=0;r<n.length;r+=1)for(let o=0;o<t.length;o+=1){let s=0;for(;r+s<n.length&&o+s<t.length&&n[r+s]===t[o+s];)s+=1;i=Math.max(i,s)}return i}function Xy(e){if(e.length===0)return[];let t=e.split(`
63
+ AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function Qe(e,t){let n=ht(t),i=J(t);return i==="entry"||i==="worker"||wu(n)||Eu(e,n)}function mr(e,t,n){let i=ht(n),r=[];Pn(e,i)&&r.push("package-surface-file"),PM(e,t,i)&&r.push("transitive-package-surface"),dy(e,t,i)&&r.push("rust-public-library"),jM(t,i)&&r.push("framework-entrypoint");let o=e.config.entryRoots;return o&&(o.files?.some(s=>ht(s)===i)&&r.push("configured-file"),o.pathPrefixes?.some(s=>i.startsWith(ht(s)))&&r.push("configured-path-prefix"),o.qualifiedVars?.some(s=>zM(t,s))&&r.push("configured-qualified-var"),o.symbolPatterns?.some(s=>{try{return Ss(s,"entryRoots.symbolPatterns entry").test(t)}catch{return!1}})&&r.push("configured-symbol-pattern")),r}function qe(e,t,n){return mr(e,t,n).length>0}var DM=Fe("package-surface-reachability",{clearGroups:["whole-project"]}),MM=Fe("explicit-package-surface-reachability",{clearGroups:["whole-project"]});function PM(e,t,n){let i=TM(e).get(n);return i===void 0?!1:i===null||i.has(Y(t))}function hy(e,t,n){let i=FM(e).get(n);return i===void 0?!1:i===null||i.has(Y(t))}function TM(e){return DM.get(e,()=>yy(e,t=>Pn(e,t)))}function FM(e){return MM.get(e,()=>yy(e,t=>iy(e,t)))}function yy(e,t){let n=new Map,i=[];for(let r of me(e,{includeIgnored:!1}))t(r)&&(n.set(r,null),i.push(r));for(;i.length>0;){let r=i.shift(),o=n.get(r);if(o!==void 0)for(let s of $r(e,r)){if(!s.sourcePath||e.isIgnored(s.sourcePath))continue;let a=kM(o,s);a!==void 0&&NM(n,s.sourcePath,a)&&i.push(s.sourcePath)}}return n}function kM(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(i=>e.has(i))?null:void 0;let n=t.names.filter(i=>e.has(i));return n.length>0?new Set(n):void 0}function NM(e,t,n){if(!e.has(t))return e.set(t,n),!0;let i=e.get(t);if(i===void 0)return!1;if(i===null||n===null)return i===null?!1:(e.set(t,null),!0);let r=!1;for(let o of n)i.has(o)||(i.add(o),r=!0);return r}var by=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),AM=new Set(["default","generateMetadata","generateStaticParams"]),_M=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),BM=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),OM=new Set(["load","actions","entries",...by]),$M=new Set(["default"]);function jM(e,t){let n=Y(e);return n===""?!1:Sy(t)?by.has(n):vy(t)?AM.has(n):Cy(t)?_M.has(n):xy(t)?BM.has(n):Ry(t)?OM.has(n):UM(t)?$M.has(n):!1}function wu(e){return Sy(e)||vy(e)||Cy(e)||HM(e)||xy(e)||Ry(e)}function Sy(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function vy(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Cy(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function HM(e){let t="(?:middleware|proxy|instrumentation)\\.(?:ts|js|mts|mjs)";return new RegExp(`^(?:src/)?${t}$`).test(e)||new RegExp(`(?:^|/)src/${t}$`).test(e)||new RegExp(`(?:^|/)(?:apps|services|packages)/[^/]+/(?:src/)?${t}$`).test(e)}function xy(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Ry(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function UM(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function zM(e,t){let n=t.lastIndexOf("/");if(n<0)return!1;let i=t.slice(0,n),r=t.slice(n+1);return e.includes(fy(i)+"/")&&e.includes(fy(r)+".")}function fy(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function Iy(e,t,n={}){let i=new Map;if(t&&t.length===0)return i;let r=me(e,{includeIgnored:!1}),o=rn(e),s=t??Ue(e),a=new Set(s.map(c=>c.symbolId)),l=YM(s);return qM(e,i,r,o,a,l),KM(e,i,s,a),JM(e,i,r,o,a,l),n.semantic!==!1&&n.semanticEvidence&&QM(i,n.semanticEvidence.callerMap(e,XM(s))),i}function qM(e,t,n,i,r,o){for(let s of n){if(!ye(s))continue;let a=tn(e,s);if(a)for(let l of a){if(o&&!o.has(l.calleeLeaf))continue;let c=nn(s,i.get(l.calleeLeaf)??[]);if(!c||c.length===0)continue;let u=qn(e,s,c,l.memberAccess,l.calleeQualifier);u&&r.has(u.symbolId)&&u.file!==s&&Lu(t,u.symbolId,s)}}}function KM(e,t,n,i){let r=WM(n);for(let o of GM(e,i))e.isIgnored(o.relative_path)||VM(o,r.get(o.symbol_id))||Lu(t,o.symbol_id,o.relative_path)}function GM(e,t){return As(e,t?[...t]:void 0)}function WM(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 VM(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function JM(e,t,n,i,r,o){for(let s of n){if(ye(s)!=="rust")continue;let a=Yi(e,s,{includeRustAttributeNames:!0});if(a.length!==0)for(let{name:l}of a){if(o&&!o.has(l))continue;let c=i.get(l);if(c)for(let u of c)r.has(u.symbolId)&&u.file!==s&&Lu(t,u.symbolId,s)}}}function Lu(e,t,n){let i=e.get(t);i||(i=new Set,e.set(t,i)),i.add(n)}function YM(e){let t=new Set;for(let n of e){let i="leaf"in n&&typeof n.leaf=="string"?n.leaf:"symbol"in n&&typeof n.symbol=="string"?Y(n.symbol):"";i&&t.add(i)}return t.size>0?t:null}function XM(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function QM(e,t){for(let[n,i]of t){let r=e.get(n);r||(r=new Set,e.set(n,r));for(let o of i)r.add(o)}}function Du(e,t,n={}){return Iy(e,t,n)}function So(e,t,n={}){return jf(e,t,n)}function Ey(e,t,n={}){let i=Du(e,t,{semantic:n.semantic,semanticEvidence:n.semanticEvidence});return n.sourceFallback===!1?i:Mi(i,So(e,t))}function Mi(e,t){let n=new Map;for(let[i,r]of e)n.set(i,new Set(r));for(let[i,r]of t){let o=n.get(i)??new Set;for(let s of r)o.add(s);n.set(i,o)}return n}function wy(e,t,n){let i=t.identifierResolution==="strict"?nc:$f,r=t.candidateNames?_f(t.candidateNames):null,o=0,s=0,a=0,l=0,c="";for(let u of t.paths)if(o+=1,c=u,!(!ye(u)&&!(t.includeVueSfc&&Cf(u)))&&!e.isIgnored(u)&&!t.skipPath?.(u))try{if(r&&!Bf(se(e,u),r))continue;s+=1;let m=(p,g,h,b)=>{if(t.candidateNames&&!t.candidateNames.has(p))return;a+=1;let v=t.resolveTargets?t.resolveTargets({sourceFile:u,name:p,kind:g,defaultTargets:b}):b();for(let y of v)l+=1,n({sourceFile:u,name:p,target:y,occurrences:h,kind:g})},f=er(e,u);for(let[p,g]of f)m(p,"identifier",g.length,()=>i(e,u,p));for(let p of Yi(e,u,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let g=p.kind==="cross-language-dispatch"?()=>nc(e,u,p.name):()=>i(e,u,p.name);m(p.name,p.kind,p.occurrences,g)}}finally{t.afterPath?.(u),o%10===0&&B("source-reference-scan.progress",()=>{},()=>({scannedPaths:o,currentPath:c,candidateMatchedPaths:s,visitedNames:a,visitedHits:l}))}}function de(e){return e.endLine-e.startLine+1}function Ly(e,t={}){let{scope:n,files:i,minLoc:r=1,maxLoc:o=Number.POSITIVE_INFINITY,excludeSymbol:s,excludeEntrySurfaces:a=!1,excludeTypesFiles:l=!1,excludeRootedSymbols:c=!1,requireFunctionLikeSymbol:u=!1,requireCallableSymbol:d=!1,excludeRustTraitImplMembers:m=!1,includeSuppressed:f=!1,sortByLocDesc:p=!1}=t,g=[],h=ZM(e,{scope:n,files:i,requireFunctionLikeSymbol:u,requireCallableSymbol:d}),b=new Map,v=new Map,y=E=>{let S=b.get(E);if(S!==void 0)return S;let x=Qe(e,E);return b.set(E,x),x},I=E=>{let S=v.get(E);if(S!==void 0)return S;let x=J(E);return v.set(E,x),x};for(let E of h){let S=E.relativePath;if(e.isIgnored(S)||a&&y(S)||!eP(E,{requireFunctionLikeSymbol:u,requireCallableSymbol:d})||s!==void 0&&E.symbol===s)continue;let x=de(E);x<r||x>o||l&&tP(S)||c&&qe(e,E.symbol,S)||m&&Xe(E.symbol)||I(S)!=="test"&&(Xi(E.symbol)||!f&&Ls(e,S,E.startLine)||g.push(E))}return p?g.sort((E,S)=>de(S)-de(E)):g}function ZM(e,t){return t.files!==void 0?[...new Set(t.files.map(i=>i.replace(/\\/g,"/")))].sort().filter(i=>!t.scope||i.includes(t.scope)).flatMap(i=>W(e,i)):t.requireCallableSymbol?jr(e,{scope:t.scope,symbolMatches:st,sqlPrefilter:"callable"}):t.requireFunctionLikeSymbol?jr(e,{scope:t.scope,symbolMatches:_e,sqlPrefilter:"function-like"}):Pf(e,t.scope)}function eP(e,t){return t.requireCallableSymbol?st(e.symbol):t.requireFunctionLikeSymbol?_e(e.symbol):e.isFunctionLike}function tP(e){return(e.split("/").pop()??"").includes("types")}var U=class{constructor(t){this.db=t}db;scopedDefinitions(t){return Mf(this.db,t)}definitionsForFile(t){return W(this.db,t)}productionCallableDefinitions(t={}){return Ly(this.db,t)}calleeMap(t,n={}){return this.calleeEvidenceMap(t,n).rows}calleeEvidenceMap(t,n={}){return Kr(this.db,t,{...n,semanticEvidence:ge})}crossFileCallerMap(t,n={}){return Du(this.db,t,{...n,semanticEvidence:ge})}sourceFallbackCallerFiles(t,n={}){return So(this.db,t,n)}callerFileMap(t,n={}){return Ey(this.db,t,{...n,semanticEvidence:ge})}frameworkReferencedSymbolIds(t){let n=new Map;for(let r of t){if(!r.leaf)continue;let o=n.get(r.leaf)??[];o.push(r.symbolId),n.set(r.leaf,o)}let i=new Set;for(let r of me(this.db,{includeIgnored:!1}))if(ye(r)==="rust")for(let{name:o}of Yi(this.db,r,{includeRustAttributeNames:!0}))for(let s of n.get(o)??[])i.add(s);return i}symbolsWithNonSelfCallees(t,n={}){if(t.length===0)return new Set;let i=new Map(t.map(s=>[s.symbolId,s.symbol])),r=this.calleeEvidenceMap(t,n),o=new Set([...r.rows.entries()].filter(([s,a])=>{let l=i.get(s);return a.some(c=>c.symbol!==l)}).map(([s])=>s));for(let s of r.incompleteSymbolIds)o.add(s);for(let s of r.unavailableSymbolIds)o.add(s);return o}fileDependencyGraph(t){return $e(this.db,t)}fileKind(t){return J(t)}hasSuppressionComment(t){return Ls(this.db,t.relativePath,t.startLine)}sourceFiles(){return Ji(this.db)}scanSourceReferences(t,n){wy(this.db,t,n)}callableSignature(t){let n=Un(this.db).forFile(t.relativePath,{facts:!0}).facts?.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};var nP=16,iP=4,Mu=3e3,rP=800,oP=new Set(["assignment","const_declaration","const_item","field_declaration","lexical_declaration","local_declaration_statement","local_variable_declaration","static_item","variable_declaration"]);function ky(e,t,n={}){let i=n.maxSteps??nP;if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`maxSteps must be a positive safe integer; received ${i}`);let r=new Map(t.nodes.map(T=>[T.id,T])),o=mP(n.focusLocations??[]),s=new Set,a=new Map(t.edges.map(T=>[T.id,T])),l=Tn(t.paths.flatMap(T=>T.nodeIds)),c=Tn(t.anchors.filter(T=>T.status==="matched").flatMap(T=>T.nodeIds)),u=t.nodes.filter(T=>T.disposition==="emitted"&&T.attributes.upstreamCausalPath===!0).sort((T,Z)=>Number(Z.attributes.upstreamCausalDistance??0)-Number(T.attributes.upstreamCausalDistance??0)||T.id.localeCompare(Z.id)).map(T=>T.id),d=new Set(u),m=Math.max(0,i-c.length),p=sP(t,c,o,m).slice(0,m),g=new Set(p),h=new Set(p),b=new Set([...l,...u,...c]),v=t.edges.filter(T=>T.disposition==="emitted"&&T.kind!=="structural-membership"),y=t.edges.filter(T=>T.disposition!=="excluded"&&T.disposition!=="unsupported"&&T.kind!=="structural-membership"),I=new Set([...t.paths.flatMap(T=>T.edgeIds),...v.filter(T=>d.has(T.fromNodeId)&&d.has(T.toNodeId)).map(T=>T.id)]),E=t.paths.some(T=>T.edgeIds.length>0),S=new Set(c);for(let T of p)S.add(T);for(let T of t.paths){let Z=T.nodeIds[0],Q=a.get(T.edgeIds[0]??""),Se=T.nodeIds[1];Z&&Se&&Q?.fromNodeId===Z&&Q.toNodeId===Se&&S.add(Z)}if(t.paths.every(T=>T.nodeIds.length===0))for(let T of t.anchors)for(let Z of T.nodeIds)S.add(Z);let x=yP(c,y,r,iP),C=Tn(v.filter(T=>T.kind==="call"&&c.includes(T.fromNodeId)).map(T=>T.toNodeId)),L=new Set(Tn([...x,...E?[]:C]));for(let T of L)S.add(T);let w=Tn(v.flatMap(T=>b.has(T.fromNodeId)||b.has(T.toNodeId)?[T.fromNodeId,T.toNodeId]:[])),R=t.nodes.filter(T=>T.disposition==="emitted"&&T.kind!=="structural-region"&&v.some(Z=>Z.fromNodeId===T.id||Z.toNodeId===T.id)).map(T=>T.id),M=Tn([...u,...l,...c,...p,...L,...w,...R]).filter(T=>r.has(T)),_=[];for(let T of M)E&&!b.has(T)&&!g.has(T)&&!L.has(T)||_.length>=i&&!b.has(T)||_.push(T);let D=new Set(_),P=new Map(_.map(T=>[T,SP(T)])),k=new Set([...l,...u]),V=new Set(t.anchors.flatMap(T=>T.nodeIds)),le=_.map((T,Z)=>{let Q=r.get(T),Se=dP(Q,o);for(let it of Se)s.add(fr(Q.location.file,it));return{id:P.get(T),nodeId:T,order:Z,role:V.has(T)?"anchor":k.has(T)?"connector":"junction",kind:Q.kind,label:Q.label,location:Q.location,behavior:aP(e,Q,V.has(T),[...new Set([...Se,...uP(e,Q,y,r,I,S)])],Se,S.has(Q.id)&&(Se.length===0||V.has(Q.id)),L.has(Q.id),h.has(Q.id)&&Se.length===0)}}),G=new Map;for(let T of t.paths)for(let Z=0;Z<T.edgeIds.length;Z+=1){let Q=a.get(T.edgeIds[Z]),Se=T.nodeIds[Z],it=T.nodeIds[Z+1];!Q||!Se||!it||G.set(Q.id,Q.fromNodeId===Se&&Q.toNodeId===it?"forward":"reverse")}let N=y.filter(T=>D.has(T.fromNodeId)&&D.has(T.toNodeId)).sort((T,Z)=>bP(T,Z,t)).map((T,Z)=>({id:vP(T.id),edgeId:T.id,order:Z,kind:T.kind,fromStepId:P.get(T.fromNodeId),toStepId:P.get(T.toNodeId),directed:!0,pathTraversal:G.get(T.id)??"adjacent",evidence:T.evidence})),K=new Map(N.map(T=>[T.edgeId,T.id])),ne=t.paths.map(T=>({id:T.id,status:T.status,stepIds:T.nodeIds.flatMap(Z=>{let Q=P.get(Z);return Q?[Q]:[]}),transitionIds:T.edgeIds.flatMap(Z=>{let Q=K.get(Z);return Q?[Q]:[]})})),fe=le.flatMap(T=>T.location?[`${T.location.file}:${T.location.line+1}`]:[]),he=t.anchors.some(T=>T.status==="ambiguous"),ce=ne.some(T=>T.status==="connected"||T.status==="candidate"),be=ne.some(T=>T.status==="partial");return{status:le.length===0?"unavailable":he?"ambiguous":ce&&!be?"connected":be?"partial":"connected",steps:le,transitions:N,paths:ne,coverage:{candidateNodes:M.length,returnedNodes:_.length,omittedNodeIds:M.filter(T=>!D.has(T)),returnedTransitions:N.length,withheldStatements:le.reduce((T,Z)=>T+(Z.behavior?.coverage.omittedStatements??0),0),requestedFocusLocations:o,matchedFocusLocations:o.filter(T=>s.has(fr(T.file,T.line))),unmatchedFocusLocations:o.filter(T=>!s.has(fr(T.file,T.line)))},behaviorCommand:Fy(fe,"behavior"),exactSourceCommand:Fy(fe,"source")}}function sP(e,t,n,i){if(i<=0||n.length===0)return[];let r=new Set(t),o=new Set(n.map(s=>fr(s.file,s.line)));return Tn(e.edges.filter(s=>s.disposition!=="excluded"&&s.disposition!=="unsupported"&&["call","runtime-boundary"].includes(s.kind)&&r.has(s.fromNodeId)&&s.evidence.some(a=>!["candidate","unknown"].includes(a.strength)&&a.location&&o.has(fr(a.location.file,a.location.line)))).sort((s,a)=>{let l=s.evidence.find(u=>u.location)?.location,c=a.evidence.find(u=>u.location)?.location;return(l?.file??"").localeCompare(c?.file??"")||(l?.line??Number.MAX_SAFE_INTEGER)-(c?.line??Number.MAX_SAFE_INTEGER)||s.id.localeCompare(a.id)}).map(s=>s.toNodeId)).slice(0,i)}function aP(e,t,n,i,r,o,s,a){if(!t.location||!["symbol","source-construct","runtime-boundary-participant"].includes(t.kind))return null;let l=t.location.endLine??t.location.line,c=re(e,t.location.file),u=i.length>0?i:[t.location.line],d=t.kind==="runtime-boundary-participant"?yt(e,t.location.file,0,Math.max(0,c.length-1),[t.location.line]):yt(e,t.location.file,t.location.line,l,u),m=i.filter(L=>L>=d.startLine&&L<=d.endLine),f=nr(e,t.location.file,d.startLine,d.endLine,m),p=f??(m.length>0?nr(e,t.location.file,d.startLine,d.endLine,m,{requireSavings:!1}):null),g=m.length>0?fP(e,t,d.startLine,d.endLine,m,p,o):null,h=c.slice(d.startLine,d.endLine+1).join(`
64
+ `).length,b=En(e,t.location.file,d.startLine,d.endLine),v=c.slice(d.startLine,d.endLine+1).some((L,w)=>L.length>rP&&(b.get(d.startLine+w)??[]).some(R=>["binding","branch","loop","call","return","throw","mutation"].includes(R))),y=L=>lP(e,t,d.startLine,d.endLine,r.filter(w=>w>=d.startLine&&w<=d.endLine),L),I=(s||t.kind==="runtime-boundary-participant"||t.anchorIds.length>0)&&h<=Mu,E=n&&(m.length===0||I);if(f&&(a||E))return y(Dy(f));if(!a&&!E&&g&&!v&&!I&&g.renderedCharacters<(p?.outlineCharacters??h))return y(g);if(f)return y(Dy(f));let S=c.slice(d.startLine,d.endLine+1),x=S.join(`
65
+ `),C=En(e,t.location.file,d.startLine,d.endLine);return y({kind:"source",constructKind:"source construct",signature:S.find(L=>L.trim().length>0)?.trim()??t.label,lines:S.map((L,w)=>({line:d.startLine+w,endLine:d.startLine+w,depth:0,signals:C.get(d.startLine+w)??[],text:L,copied:!0})),coverage:{sourceStatements:S.length,representedStatements:S.length,copiedStatements:S.length,omittedStatements:0},rawCharacters:x.length,renderedCharacters:x.length})}function lP(e,t,n,i,r,o){if(!t.location)return o;let s=vu(e,t.location.file,n,i);if(!s.available)return o;let a=En(e,t.location.file,n,i),l=re(e,t.location.file),c=new Set(r);for(let v of r){let y=Ma(l[v]??"");if(!y)continue;let I=Rn(e,t.location.file,y).find(E=>E>v&&E<=i);I!==void 0&&c.add(I)}let u=[...new Map(s.targets.flatMap(v=>{let y=v.definition,I=y.relativePath===t.location.file&&y.startLine<=i&&y.endLine>=n;if(y.isTypeLike||I)return[];let E=La(e,y),S=r.length>0&&E&&a.get(v.sourceLine)?.includes("return"),x=E&&c.has(v.sourceLine);return E&&!S&&!x?[]:[[y.symbol,{definition:y,kind:S?"return-value-transformer":x?"focused-causal-target":"compiler-referenced-declaration"}]]})).values()].sort((v,y)=>v.definition.relativePath.localeCompare(y.definition.relativePath)||v.definition.startLine-y.definition.startLine||v.definition.symbol.localeCompare(y.definition.symbol)),d=[],m=u.filter(({kind:v})=>v!=="compiler-referenced-declaration").map(({definition:v})=>({owner:v,depth:1})),f=new Set,p=new Set(u.map(({definition:v})=>v.symbol));for(;m.length>0;){let v=m.shift();if(!v||f.has(v.owner.symbol))continue;f.add(v.owner.symbol);let{owner:y,depth:I}=v,E=vu(e,y.relativePath,y.startLine,y.endLine);if(!E.available)continue;let S=En(e,y.relativePath,y.startLine,y.endLine),x=re(e,y.relativePath);for(let C of E.targets){let L=C.definition,w=L.relativePath===y.relativePath&&L.startLine<=y.endLine&&L.endLine>=y.startLine;if(L.isTypeLike||w)continue;let R=La(e,L),M=Ma(x[C.sourceLine]??""),_=R&&M!==null&&Rn(e,y.relativePath,M).some(P=>P>C.sourceLine&&P<=y.endLine&&(S.get(P)??[]).some(k=>["branch","return","throw"].includes(k))),D=R&&((S.get(C.sourceLine)??[]).some(P=>["branch","return","throw"].includes(P))||_);R&&!D||(p.has(L.symbol)||(p.add(L.symbol),d.push({definition:L,kind:R?"focused-causal-target":"compiler-referenced-declaration"})),R&&I<2&&m.push({owner:L,depth:I+1}))}}let g=[...new Map([...u,...d].map(v=>[v.definition.symbol,v])).values()].sort((v,y)=>v.definition.relativePath.localeCompare(y.definition.relativePath)||v.definition.startLine-y.definition.startLine||v.definition.symbol.localeCompare(y.definition.symbol)),h=[],b=[];for(let{definition:v,kind:y}of g){let I=y==="compiler-referenced-declaration"?cP(e,v.relativePath,v.startLine,v.endLine):{startLine:v.startLine,endLine:v.endLine},E=re(e,v.relativePath).slice(I.startLine,I.endLine+1).join(`
66
+ `),S=y==="compiler-referenced-declaration"?null:nr(e,v.relativePath,v.startLine,v.endLine,[]),x=S?[S.signature,...S.lines.map(M=>`${M.line+1}${M.signals.length>0?`[${M.signals.join(",")}]`:""} ${M.text}`)].join(" | "):null,C=x&&x.length<E.length?x:E,L={symbol:v.symbol,label:v.leaf,file:v.relativePath,line:I.startLine,endLine:I.endLine},w=y==="compiler-referenced-declaration"?1e3:8e3,R=y==="compiler-referenced-declaration"?12:120;if(C.length>w||I.endLine-I.startLine>R){b.push({...L,reason:"source-too-large"});continue}h.push({kind:y,...L,text:C})}return{...o,...h.length===0?{}:{supportingDeclarations:h},...b.length===0?{}:{omittedSupportingDeclarations:b}}}function cP(e,t,n,i){let r=ae(e,t);if(!r)return{startLine:n,endLine:i};let o=[];Ny(r.rootNode,a=>{oP.has(a.type)&&a.startPosition.row<=n&&a.endPosition.row>=i&&o.push(a)});let s=o.sort((a,l)=>a.endPosition.row-a.startPosition.row-(l.endPosition.row-l.startPosition.row)||a.endIndex-a.startIndex-(l.endIndex-l.startIndex))[0];return s?{startLine:s.startPosition.row,endLine:s.endPosition.row}:{startLine:n,endLine:i}}function Ny(e,t){t(e);for(let n of e.namedChildren)Ny(n,t)}function Dy(e){return{kind:"outline",constructKind:e.constructKind,signature:e.signature,lines:e.lines,coverage:e.coverage,rawCharacters:e.rawCharacters,renderedCharacters:e.outlineCharacters}}function uP(e,t,n,i,r,o){if(!t.location||!["symbol","source-construct","runtime-boundary-participant"].includes(t.kind))return[];let s=new Set,a=new Set(te(e,t.location.file)?.callSites.map(l=>l.line)??[]);if(t.kind==="runtime-boundary-participant"&&s.add(t.location.line),o.has(t.id))for(let l of zr(e,{files:[t.location.file]}))l.source.startLine>=t.location.line&&l.source.startLine<=(t.location.endLine??t.location.line)&&s.add(l.source.startLine);for(let l of n){if(l.fromNodeId!==t.id&&l.toNodeId!==t.id)continue;let c=i.get(l.fromNodeId===t.id?l.toNodeId:l.fromNodeId),u=o.has(t.id)&&["call","reference","runtime-boundary"].includes(l.kind)&&l.fromNodeId===t.id,d=(c?.anchorIds.length??0)>0;if(!r.has(l.id)&&!u&&!d)continue;let m=l.evidence.flatMap(b=>b.location?.file===t.location.file?[b.location.line]:[]),f=m.filter(b=>a.has(b));for(let b of f.length>0?f:m)s.add(b);let p=c?.attributes.leaf;if(typeof p!="string"||p.length===0)continue;let g=Rn(e,t.location.file,p).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((l,c)=>l-c)}function dP(e,t){if(!e.location)return[];let n=e.location.endLine??e.location.line;return t.filter(i=>i.file===e.location.file&&i.line>=e.location.line&&i.line<=n).map(i=>i.line)}function mP(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(fr(n.file,n.line),{file:n.file,line:n.line})}return[...t.values()].sort((n,i)=>n.file.localeCompare(i.file)||n.line-i.line)}function fr(e,t){return`${e}\0${t}`}function fP(e,t,n,i,r,o,s){if(!t.location)return null;let a=re(e,t.location.file),l=En(e,t.location.file,n,i),c=[...l].filter(([,D])=>D.length>0).map(([D])=>D).sort((D,P)=>D-P),u=r.map(D=>(l.get(D)??[]).length>0?D:c.find(P=>P>D&&P-D<=8)??D),d=new Set([...r,...u]),m=s?hc(e,t.location.file,n,i,{minimumBodyLines:0}):null,f=o?[...new Map(u.flatMap(D=>o.lines.filter(P=>P.text.length<=500&&P.signals.some(k=>["branch","loop","catch","finally"].includes(k))&&D>=P.line&&D<=P.endLine).sort((P,k)=>P.endLine-P.line-(k.endLine-k.line)||P.line-k.line).slice(0,2).map(P=>[`${P.line}\0${P.endLine}`,P]))).values()]:Zs(e,t.location.file,n,i,u);for(let D of m?.lines??[])d.add(D.line);for(let D of f)d.add(D.line);for(let[D,P]of l)P.includes("call")&&P.includes("shape")&&d.add(D);let p=[];for(let D of u){let P=Ma(a[D]??"");if(!P)continue;let k=Rn(e,t.location.file,P).filter(N=>N>D&&N<=i),V=k[0];V!==void 0&&d.add(V);let le=k.find(N=>(l.get(N)??[]).some(K=>K==="branch"||K==="loop"));if(le===void 0)continue;d.add(le);let G=(o?.lines??[]).find(N=>N.line===le)??{line:le,endLine:Math.min(i,le+40),depth:0,signals:l.get(le)??[],text:(a[le]??"").trim(),copied:!0},X=o?.lines??a.slice(G.line,G.endLine+1).map((N,K)=>{let ne=G.line+K;return{line:ne,endLine:ne,depth:0,signals:l.get(ne)??[],text:N.trim(),copied:!0}});p.push({focusLine:D,governingUse:le,lines:X.filter(N=>N.line>=G.line&&N.line<=G.endLine&&N.text.length<=500&&N.signals.some(K=>["binding","branch","call","mutation"].includes(K)))})}for(let D of p.sort((P,k)=>k.governingUse-k.focusLine-(P.governingUse-P.focusLine)||P.focusLine-k.focusLine).slice(0,2))for(let P of D.lines.slice(0,14))d.add(P.line);let g=new Set(["binding","branch","loop","call","return","throw","mutation"]);for(let D of f)for(let P of o?.lines??[])P.line<D.line||P.line>D.endLine||P.signals.some(k=>g.has(k))&&d.add(P.line);let h=a.slice(n,i+1).flatMap((D,P)=>{let k=Ma(D);return k?[{name:k,line:n+P}]:[]}),b=!0;for(;b;){b=!1;for(let D of h)if([...d].some(k=>gP(a[k]??"",D.name))){d.has(D.line)||(d.add(D.line),b=!0);for(let k of Rn(e,t.location.file,D.name))k<n||k>i||d.has(k)||(l.get(k)??[]).some(V=>g.has(V))&&(d.add(k),b=!0)}}for(let D of o?.lines??[])if(D.signals.some(P=>["branch","loop","catch","finally"].includes(P))&&d.has(D.line))for(let P of o?.lines??[])P.line<D.line||P.line>D.endLine||P.signals.some(k=>g.has(k))&&d.add(P.line);let v=te(e,t.location.file),y=new Set(v?.callSites.map(D=>D.line)??[]),I=l,E=new Map([...o?.lines??[],...f].filter(D=>D.signals.some(P=>["branch","loop","catch","finally"].includes(P))).map(D=>[D.line,D])),S=new Map((o?.lines??[]).filter(D=>D.text.length<=500&&D.signals.includes("shape")&&(D.signals.includes("call")||D.signals.includes("mutation")||D.signals.includes("return"))).sort((D,P)=>D.endLine-D.line-(P.endLine-P.line)||D.line-P.line).map(D=>[D.line,D])),x=new Map((m?.lines??[]).map(D=>[D.line,D.signals.filter(P=>P!=="lifecycle")])),C=[...d].filter(D=>D>=n&&D<=i).sort((D,P)=>D-P).map(D=>{let P=E.get(D)??S.get(D);return{line:D,endLine:P?.endLine??D,depth:P?.depth??0,signals:pP([...I.get(D)??[],...o?.lines.filter(k=>D>=k.line&&D<=k.endLine).flatMap(k=>k.signals)??[],...x.get(D)??[],...r.includes(D)?["anchor"]:[],...y.has(D)?["call"]:[]]),text:P?.text??(a[D]??"").trim(),copied:P?.copied??!0}}).filter(D=>D.text.length>0);if(C.length===0)return null;let L=m?.candidateLines??hc(e,t.location.file,n,i,{minimumBodyLines:0})?.candidateLines??0,w=Math.max(o?.coverage.sourceStatements??0,L,C.length),R=o?.signature??(a[n]??t.label).trim(),M=R.length+C.reduce((D,P)=>D+P.text.length+P.signals.join(",").length+12,0),_=a.slice(n,i+1).join(`
67
+ `).length;return{kind:"connector-slice",constructKind:o?.constructKind??"source construct",signature:R,lines:C,coverage:{sourceStatements:w,representedStatements:C.length,copiedStatements:C.length,omittedStatements:Math.max(0,w-C.length)},rawCharacters:_,renderedCharacters:M}}function pP(e){let t=["anchor","signature","binding","branch","loop","call","await","return","throw","mutation","shape","spread","catch","finally"],n=new Set(e);return t.filter(i=>n.has(i))}function Ma(e){return/\b(?:const|let|var)\s+([\p{L}_$][\p{L}\p{N}_$]*)\s*(?:=|\bof\b|\bin\b)/u.exec(e)?.[1]??null}function gP(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`(?:^|[^\\p{L}\\p{N}_$])${n}(?:$|[^\\p{L}\\p{N}_$])`,"u").test(e)}function hP(e,t,n){return Tn(e.flatMap(i=>{let r=n.get(i),o=t.filter(s=>s.kind==="call"&&s.toNodeId===i).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 l=My(a.edge)-My(s.edge);if(l!==0)return l;let c=Py(s.node,r)?0:1,u=Py(a.node,r)?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 c-u||d-m||s.node.label.localeCompare(a.node.label)});return o[0]?[o[0].node.id]:[]}))}function My(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 Py(e,t){return!e.location||!t?.location?!1:Ty(e.location.file)===Ty(t.location.file)}function Ty(e){return e.split("/").filter(Boolean).slice(0,2).join("/")}function yP(e,t,n,i){let r=new Set(e),o=new Set,s=[],a=Tn(e);for(let l=0;l<i&&a.length>0;l+=1){let c=a.filter(d=>!o.has(d));for(let d of c)o.add(d);let u=hP(c,t,n);a=[];for(let d of u)!r.has(d)&&!s.includes(d)&&s.push(d),o.has(d)||a.push(d)}return s}function bP(e,t,n){let i=new Map(n.paths.flatMap(r=>r.edgeIds).map((r,o)=>[r,o]));return(i.get(e.id)??Number.MAX_SAFE_INTEGER)-(i.get(t.id)??Number.MAX_SAFE_INTEGER)||e.id.localeCompare(t.id)}function SP(e){return`step:${e}`}function vP(e){return`transition:${e}`}function Fy(e,t){return e.length===0?null:`codebaseiq inspect ${e.map(n=>`--at ${CP(n)}`).join(" ")} --view ${t}`}function CP(e){return`'${e.replace(/'/gu,`'"'"'`)}'`}function Tn(e){return[...new Set(e)]}var Ay=4,xP=3,RP=12,IP=48,EP=64,Fi=10,Pi=6,wP=24,LP=320,Pu=6,DP=12,MP=1,PP=4,TP=7,FP=12,Au="source-construct:",kP=96,NP=32,_y=4,AP=32,_P=8;function BP(e,t,n={}){let i=Yy(t),r=RT(t);if(i.length===0)throw new Error("Anchor discovery requires at least one non-trivial repository term.");let o=n.limit??Ay,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 U(e),l=a.scopedDefinitions(n.scope).filter(N=>!De(N.symbol)),c=[...l],u=new Map(c.map(N=>[N.symbol,N])),d=new Map;for(let N of l)By(d,N,i);let m=zs(e,{scope:n.scope});for(let N of m.files){let ne=W(e,N.relativePath).filter(he=>!De(he.symbol));if(ne.length===0)continue;let fe=Jy(N.text);for(let he=0;he<fe.length;he+=1){let ce=mt(fe[he]??""),be=i.filter(Z=>ce.has(Z));if(be.length===0)continue;let T=Ke(ne,he);if(!(!T||De(T.symbol)))for(let Z of be)vo(d,T,Z,"source",N.relativePath,he)}}let f=Oy(d),p=[...d.values()].map(N=>Pa(N,f,r)).sort(Ze),g=$P(m.files,p,i),h=-1;for(let N of g){let K=W(e,N.relativePath),ne=K.filter(T=>!De(T.symbol)),fe=te(e,N.relativePath)?.callables??[],he=new Map,ce=T=>{let Z=`${T.startLine}\0${T.endLine}\0${T.name}`,Q=he.get(Z);if(Q)return Q;let Se=OP(N.relativePath,K,T,()=>h--);return Se?(he.set(Z,Se),c.push(Se),u.set(Se.symbol,Se),By(d,Se,i),Se):null};for(let T of fe){let Z=mt(T.name);i.some(Q=>Z.has(Q))&&ce(T)}if(fe.length===0)continue;let be=Jy(N.text);for(let T=0;T<be.length;T+=1){let Z=mt(be[T]??""),Q=i.filter(Ki=>Z.has(Ki));if(Q.length===0)continue;let Se=jP(fe,T),it=Se?ce(Se):null;if(!it)continue;let fi=$y(ne,T);if($y(fi?[fi,it]:[it],T)?.symbol===it.symbol)for(let Ki of Q)vo(d,it,Ki,"source",N.relativePath,T)}}let b=Oy(d),v=new Map(m.files.map(N=>[N.relativePath,N.text.split(/\r?\n/u)]));for(let N of d.values()){let K=v.get(N.definition.relativePath);K&&(N.sourceCharacters=K.slice(N.definition.startLine,N.definition.endLine+1).join(`
68
+ `).length)}let y=[...d.values()].map(N=>Pa(N,b,r)).sort(Ze),I=Math.min(y.length,Math.max(RP,o*xP)),E=s?y:pr([...y.slice(0,I),...[...y].sort(Fu).slice(0,Math.max(IP,I)),...hT(y,i),...yT(y,i,b)]),S=E.length,x=E.map(N=>u.get(N.symbol)).filter(N=>N?.isFunctionLike===!0),C=HP(c),L=UP(e,a,E,x,u,C,new Set(d.keys()),n.semantic!==!1),w=KP(L,E,d,b,u),R=GP(w,b,i),M=sT(e,a,L,d,b,c,u,n.semantic!==!1),D=[...VP(e,a,w,u,b,n.semantic!==!1),...R,...w,...M].map(N=>({...N,queryPathMatches:ST(N)})).sort((N,K)=>Ti(N,K,b)),P=s?D:vT(D,o,b),k=i.filter(N=>b.has(N)),V=i.filter(N=>!b.has(N)),le=Math.max(0,y.length-S),G=Math.max(0,D.length-P.length)+le,X=s?y.length:Math.min(y.length,o+Ay);return{query:t,queryPathFragments:r,normalizedTerms:i,matchedTerms:k,unmatchedTerms:V,groups:P,candidateRoots:y,candidateRootCount:y.length,analyzedRootCount:S,omittedRootCount:le,omittedGroupCount:G,scannedFiles:m.files.length,scannedBytes:m.scannedBytes,recoveryCommand:G===0?null:`codebaseiq anchors ${Na(t)}${n.scope?` --scope ${Na(n.scope)}`:""} --limit ${X}`}}function Yy(e){let t=yo(e).filter(n=>!gu.has(n.toLocaleLowerCase())).map(Ia).filter(n=>n.length>=3&&!gu.has(n));return[...new Set(t)]}function By(e,t,n){let i=mt(t.leaf),r=mt(t.relativePath),o=mt(t.documentation??"");for(let a of n)i.has(a)&&vo(e,t,a,"symbol"),r.has(a)&&vo(e,t,a,"path"),o.has(a)&&vo(e,t,a,"documentation");let s=e.get(t.symbol);s&&(s.symbolPhraseLength=ET(t.leaf,n))}function vo(e,t,n,i,r,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(i),r!==void 0&&o!==void 0&&a.locations.set(`${r}\0${o}`,{file:r,line:o}),s.matches.set(n,a),e.set(t.symbol,s)}function Oy(e){let t=new Map;for(let n of e.values())for(let i of n.matches.keys())t.set(i,(t.get(i)??0)+1);return t}function OP(e,t,n,i){let r=t[0]?.documentId;if(r===void 0||t.find(a=>a.isFunctionLike&&a.leaf===n.name&&a.startLine===n.startLine&&a.endLine===n.endLine))return null;let s=i();return{documentId:r,symbolId:s,symbol:`${Au}${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 $P(e,t,n){let i=new Set(t.slice(0,kP).map(s=>s.file)),r=new Set(n),o=e.map(s=>{let a=mt(s.relativePath),l=s.relativePath.slice(s.relativePath.lastIndexOf("/")+1).replace(/\.[^.]+$/u,""),c=mt(l),u=[...a].filter(m=>r.has(m)).length,d=[...c].filter(m=>r.has(m)).length;return{file:s,score:d*4+u}}).filter(s=>s.score>0).sort((s,a)=>a.score-s.score||Vt(J(s.file.relativePath))-Vt(J(a.file.relativePath))||s.file.relativePath.localeCompare(a.file.relativePath)).slice(0,NP);for(let s of o)i.add(s.file.relativePath);return e.filter(s=>i.has(s.relativePath))}function jP(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,i)=>n.endLine-n.startLine-(i.endLine-i.startLine)||n.startLine-i.startLine)[0]}function HP(e){let t=new Map;for(let n of e){if(!cn(n))continue;let i=`${n.relativePath}\0${un(n.leaf)}`,r=t.get(i)??[];r.push(n),t.set(i,r)}return t}function $y(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,i)=>n.endLine-n.startLine-(i.endLine-i.startLine)||Number(cn(i))-Number(cn(n))||n.startLine-i.startLine||n.symbol.localeCompare(i.symbol))[0]}function cn(e){return e.symbol.startsWith(Au)}function ei(e){return cn(e)?e.leaf:A(e.symbol)}function Pa(e,t,n=[]){let i=e.definition,r=[...e.matches.entries()].map(([c,u])=>({term:c,sources:[...u.sources].sort(wT),locations:[...u.locations.values()].sort(Zy).slice(0,3)})).sort((c,u)=>c.term.localeCompare(u.term)),o=r.filter(c=>c.sources.some(u=>u!=="source")).map(c=>c.term),s=r.filter(c=>c.sources.includes("symbol")).map(c=>c.term),a=r.reduce((c,u)=>c+1/Math.max(1,t.get(u.term)??1),0),l=r.filter(c=>c.sources.includes("symbol")).reduce((c,u)=>c+1/Math.max(1,t.get(u.term)??1),0);return{symbol:i.symbol,label:ei(i),leaf:i.leaf,file:i.relativePath,line:i.startLine,endLine:i.endLine,kind:i.isFunctionLike?"callable":i.isTypeLike?"type":"symbol",fileKind:J(i.relativePath),matches:r,focusLocations:MT(e,t),matchedTerms:r.map(c=>c.term),symbolMatchedTerms:s,symbolPhraseLength:e.symbolPhraseLength,identityMatchedTerms:o,rarity:a,symbolRarity:l,queryPathMatches:IT(i.relativePath,n),...e.sourceCharacters===void 0?{}:{sourceCharacters:e.sourceCharacters}}}function UP(e,t,n,i,r,o,s,a){let l=i.filter(g=>!cn(g)),c=t.calleeMap(l,{additive:!1,semantic:a}),u=new Map,d=new Map;for(let g of n){let h=r.get(g.symbol),b=h?cn(h)?jy(e,h,r,o,1):Ta(e,h,c.get(h.symbolId)??[],r,1,s):[];u.set(g.symbol,b);for(let v of b){let y=r.get(v.toSymbol);y?.isFunctionLike&&(!h||!cn(h)||cn(y))&&d.set(y.symbol,y)}}let m=[...d.values()],f=t.calleeMap(m.filter(g=>!cn(g)),{additive:!1,semantic:a}),p=new Map;for(let g of m)p.set(g.symbol,cn(g)?jy(e,g,r,o,2):Ta(e,g,f.get(g.symbolId)??[],r,2,s));return n.map(g=>{let h=u.get(g.symbol)??[],b=h.flatMap(y=>p.get(y.toSymbol)??[]),v=Fn([...h,...b]);return{root:g,relations:v,nodeSymbols:new Set([g.symbol,...v.flatMap(y=>[y.fromSymbol,y.toSymbol])])}})}function Ta(e,t,n,i,r,o=new Set){let s=new Map;for(let a of n){let l=i.get(a.symbol);if(!l?.isFunctionLike||l.symbol===t.symbol||a.source==="ast-callsite"&&!qP(e,t,l,a.callsiteLine))continue;let c=s.get(l.symbol);(!c||xT(a,c)<0)&&s.set(l.symbol,a)}return[...s.entries()].map(([a,l])=>{let c=i.get(a);return{kind:"call",fromSymbol:t.symbol,fromLabel:A(t.symbol),fromFile:t.relativePath,toSymbol:c.symbol,toLabel:A(c.symbol),toFile:c.relativePath,depth:r,strength:Nu(l.source),evidence:l.source,callsiteLine:l.callsiteLine??zP(e,t,c)}}).sort((a,l)=>Number(o.has(l.toSymbol))-Number(o.has(a.toSymbol))||dn(a,l)).slice(0,EP)}function jy(e,t,n,i,r){let o=Dn(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:ei(t),fromFile:t.relativePath,toSymbol:a.symbol,toLabel:ei(a),toFile:a.relativePath,depth:r,strength:"exact",evidence:"scip-occurrence-callsite",callsiteLine:s.sourceLine}]});for(let s of Zn(e,t.relativePath,{ranges:[{startLine:t.startLine,endLine:t.endLine}],excludeIndexedTargets:!1}).targets){let a=[...i.get(`${s.targetFile}\0${un(s.calleeLeaf)}`)??[],...W(e,s.targetFile).filter(l=>l.isFunctionLike&&un(l.leaf)===s.calleeLeaf)].find(l=>l.startLine===s.targetStartLine&&l.endLine===s.targetEndLine);!a||a.symbol===t.symbol||o.push({kind:"call",fromSymbol:t.symbol,fromLabel:ei(t),fromFile:t.relativePath,toSymbol:a.symbol,toLabel:ei(a),toFile:a.relativePath,depth:r,strength:s.strength==="exact"?"exact":"derived",evidence:"ast-member-import-candidate",callsiteLine:s.line})}for(let s of te(e,t.relativePath)?.callSites??[]){if(s.line<t.startLine||s.line>t.endLine||s.memberAccess)continue;let a=(i.get(`${t.relativePath}\0${un(s.calleeLeaf)}`)??[]).filter(c=>c.symbol!==t.symbol);if(a.length!==1)continue;let l=a[0];o.push({kind:"call",fromSymbol:t.symbol,fromLabel:ei(t),fromFile:t.relativePath,toSymbol:l.symbol,toLabel:ei(l),toFile:l.relativePath,depth:r,strength:"derived",evidence:"ast-callsite",callsiteLine:s.line})}return Fn(o).sort(dn)}function zP(e,t,n){let i=un(n.leaf);return te(e,t.relativePath)?.callSites.find(r=>r.line>=t.startLine&&r.line<=t.endLine&&un(r.calleeLeaf)===i)?.line??null}function qP(e,t,n,i){if(i===void 0)return!1;let r=un(n.leaf);return te(e,t.relativePath)?.callSites.some(o=>o.line===i&&un(o.calleeLeaf)===r)??!1}function un(e){return e.replace(/^#/u,"").replace(/\(\)$/u,"")}function KP(e,t,n,i,r){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},l=(u,d)=>{let m=a(u),f=a(d);m!==f&&(s[f]=m)};for(let u of e){let d=o.get(u.root.symbol);if(d!==void 0)for(let m of u.nodeSymbols){let f=o.get(m);f!==void 0&&l(d,f)}}let c=new Map;for(let u=0;u<t.length;u+=1){let d=a(u),m=c.get(d)??[];m.push(t[u]),c.set(d,m)}return[...c.values()].map((u,d)=>{let m=new Set(u.map(y=>y.symbol)),f=Fn(e.filter(y=>m.has(y.root.symbol)).flatMap(y=>y.relations)).sort(dn),p=new Map(u.map(y=>[y.symbol,y]));for(let y of new Set(f.flatMap(I=>[I.fromSymbol,I.toSymbol]))){let I=n.get(y);if(I)p.has(y)||p.set(y,Pa(I,i));else{let E=r.get(y);E&&p.set(y,Qy(E))}}let g=fT(u,f,p),h=u.filter(y=>f.some(I=>I.fromSymbol===y.symbol)).length,b=[...new Set(u.flatMap(y=>y.matchedTerms))].sort(),v=mT(f,g,m,p);return{id:`anchor-set:${d+1}:${xo(u[0])}`,kind:"connected-flow",roots:[...u].sort(Ze),keyAnchors:g,candidateOwnerCount:g.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:[],matchedTerms:b,relations:v,relationCount:f.length,orchestrationRootCount:h,omittedRelations:Math.max(0,f.length-Fi),systemMapCommand:Io(g,f,b)}})}function GP(e,t,n){let i=new Map(n.map((o,s)=>[o,s])),r=[];for(let o=0;o<e.length;o+=1){let s=e[o],a=Hy(s);if(a.size!==0)for(let l=o+1;l<e.length;l+=1){let c=e[l],u=Hy(c),d=[...a].filter(E=>u.has(E));if(d.length===0||![...a].some(E=>!u.has(E))||![...u].some(E=>!a.has(E)))continue;let m=WP(s,c);if(m.length<2)continue;let f=Fn([...s.relations,...c.relations]).sort(dn),p=f.slice(0,Fi),g=pr([...s.roots,...c.roots]).sort(Ze),h=[...new Set([...s.matchedTerms,...c.matchedTerms])].sort(),b=d.sort((E,S)=>(i.get(E)??Number.MAX_SAFE_INTEGER)-(i.get(S)??Number.MAX_SAFE_INTEGER)||E.localeCompare(S)),v=+(s.relationCount>0)+ +(c.relationCount>0),y=+((s.orchestrationRootCount??0)>0)+ +((c.orchestrationRootCount??0)>0),I=Math.min(...b.map(E=>t.get(E)??Number.MAX_SAFE_INTEGER));r.push({sharedOrder:Math.min(...b.map(E=>i.get(E)??Number.MAX_SAFE_INTEGER)),sharedFrequency:I,connectedSides:v,orchestrationSides:y,group:{id:`parallel-paths:${xo(s.roots[0])}:${xo(c.roots[0])}`,kind:"parallel-paths",roots:g,keyAnchors:m,candidateOwnerCount:m.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:[...s.upstreamEntries,...c.upstreamEntries],matchedTerms:h,relations:p,relationCount:f.length,parallelConnectedSides:v,parallelOrchestrationSides:y,parallelSharedPathTerms:b,parallelSharedPathFrequency:I,orchestrationRootCount:(s.orchestrationRootCount??0)+(c.orchestrationRootCount??0),omittedRelations:Math.max(0,f.length-p.length),systemMapCommand:Io(m,f,h)}})}}return r.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||Ti(o.group,s.group,t)).slice(0,FP).map(o=>o.group)}function Hy(e){return new Set(e.roots.flatMap(t=>t.matches.filter(n=>n.sources.includes("path")).map(n=>n.term)))}function WP(e,t){return pr([Uy(e),Uy(t)].filter(n=>n!==void 0))}function Uy(e){let t=new Set(e.keyAnchors.map(i=>i.symbol)),n=new Map;for(let i of e.relations)!t.has(i.fromSymbol)||!t.has(i.toSymbol)||n.set(i.fromSymbol,(n.get(i.fromSymbol)??0)+1);return[...e.keyAnchors].sort((i,r)=>+((n.get(r.symbol)??0)>0)-+((n.get(i.symbol)??0)>0)||zy(r)-zy(i)||r.identityMatchedTerms.length-i.identityMatchedTerms.length||r.symbolMatchedTerms.length-i.symbolMatchedTerms.length||(n.get(r.symbol)??0)-(n.get(i.symbol)??0)||Ze(i,r))[0]}function zy(e){return e.matchedTerms.length+e.identityMatchedTerms.length*2+(e.queryPathMatches?.length??0)*4}function VP(e,t,n,i,r,o){let s=js(e);if(!s||s.links.length===0||n.length<2)return[];let a=new Map(s.observations.map(f=>[f.id,f])),l=new Map,c=new Map,u=[...n].sort((f,p)=>Ti(f,p,r)).slice(0,DP),d=s.links.filter(f=>f.strength!=="candidate").sort((f,p)=>ti(p.strength)-ti(f.strength)||p.matchedKeyParts.length-f.matchedKeyParts.length||f.id.localeCompare(p.id));for(let f of u)for(let p of d){let g=a.get(p.from),h=a.get(p.to);if(!g||!h||!JP(f,g,i))continue;let b=YP(f,g,i);if(!b)continue;let v=l.get(h.id)??ZP(e,t,h,i,o,PP);if(l.set(h.id,v),v.reachedSymbols.size===0)continue;let y=n.filter(D=>D.id!==f.id&&XP(D).some(P=>v.reachedSymbols.has(P))&&Tu(b,D)>=2).sort((D,P)=>Tu(b,P)-Tu(b,D)||Ti(D,P,r)).slice(0,MP);if(y.length===0)continue;let I=[f.id,g.id,...y.map(D=>D.id).sort()].join("\0");if(c.has(I))continue;let E=new Set(y.flatMap(Ro)),S=rT(Co(h),E,v.relations);if(S.length===0)continue;let x=iT(g,h,p.joinRule,p.matchedKeyParts,p.strength),C=Fn([x,...v.relations,...f.relations,...y.flatMap(D=>D.relations)]),L=oT([x,...S],C,f,y),w=pr([b,...y.flatMap(D=>D.roots)]).sort(Ze),R=pr([b,...y.flatMap(D=>D.keyAnchors)]).slice(0,TP),M=[...new Set([...b.matchedTerms,...y.flatMap(D=>D.matchedTerms)])].sort(),_=QP(e,t,b,i,o);w.length===0||R.length<2||c.set(I,{id:`cross-boundary-set:${xo(b)}:${c.size+1}`,kind:"cross-boundary-flow",roots:w,keyAnchors:R,candidateOwnerCount:R.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:_,matchedTerms:M,relations:L,relationCount:C.length,omittedRelations:Math.max(0,C.length-L.length),systemMapCommand:Io(R,C,M)})}let m=new Map;for(let[f,p]of c){let g=f.slice(0,f.indexOf("\0")),h=m.get(g);(!h||Ti(p,h,r)<0)&&m.set(g,p)}return[...m.values()]}function JP(e,t,n){let i=new Set(Ro(e));return t.owner.symbol&&i.has(t.owner.symbol)?!0:[...i].map(r=>n.get(r)).some(r=>r?.relativePath===t.source.file&&r.startLine<=t.source.startLine&&r.endLine>=t.source.endLine)}function YP(e,t,n){let i=pr([...e.roots,...e.keyAnchors]);if(t.owner.symbol){let r=i.find(o=>o.symbol===t.owner.symbol);if(r)return r}return i.find(r=>{let o=n.get(r.symbol);return o?.relativePath===t.source.file&&o.startLine<=t.source.startLine&&o.endLine>=t.source.endLine})??null}function Ro(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 XP(e){return[...new Set([...e.roots,...e.keyAnchors].map(t=>t.symbol))]}function Tu(e,t){let n=mt(e.leaf),i=[...t.roots,...t.keyAnchors].map(o=>mt(o.leaf)),r=0;for(let o of i){let s=0;for(let a of n)o.has(a)&&(s+=1);r=Math.max(r,s)}return r}function QP(e,t,n,i,r){let o=i.get(n.symbol);if(!o?.isFunctionLike)return[];let s=t.callerFileMap([o],{semantic:r,sourceFallback:!0}).get(o.symbolId);if(!s)return[];let a=mt(n.leaf);return[...s].filter(l=>l!==n.file&&J(l)!=="test").flatMap(l=>{let c=te(e,l);return(c?.callSites??[]).filter(u=>un(u.calleeLeaf)===un(n.leaf)).flatMap(u=>{let d=(c?.callables??[]).filter(f=>f.startLine<=u.line&&f.endLine>=u.line).sort((f,p)=>f.endLine-f.startLine-(p.endLine-p.startLine)||f.startLine-p.startLine)[0];if(!d)return[];let m=[...mt(d.name)].filter(f=>a.has(f)).length;return m>=2?[{name:d.name,file:l,line:d.startLine,endLine:d.endLine,callsiteLine:u.line,overlap:m}]:[]})}).sort((l,c)=>c.overlap-l.overlap||l.file.localeCompare(c.file)||l.line-c.line).slice(0,1).map(({name:l,file:c,line:u,endLine:d,callsiteLine:m})=>({name:l,file:c,line:u,endLine:d,callsiteLine:m}))}function ZP(e,t,n,i,r,o){let s=eT(e,n,i),a=s.map(({definition:m,evidence:f,line:p})=>({kind:"call",fromSymbol:Co(n),fromLabel:Fa(n),fromFile:n.source.file,toSymbol:m.symbol,toLabel:A(m.symbol),toFile:m.relativePath,depth:1,strength:f==="scip-occurrence-callsite"?"exact":"derived",evidence:f,callsiteLine:p})),l=tT(e,n);a.push(...l.relations);let c=Xy([...s.map(m=>m.definition),...l.definitions]),u=c,d=new Set(u.map(m=>m.symbol));for(let m=2;m<=o+1&&u.length>0;m+=1){let f=t.calleeMap(u,{additive:!1,semantic:r}),p=new Map;for(let g of u){let h=Ta(e,g,f.get(g.symbolId)??[],i,m);a.push(...h);for(let b of h){let v=i.get(b.toSymbol);v?.isFunctionLike&&!d.has(v.symbol)&&p.set(v.symbol,v)}}u=[...p.values()];for(let g of u)d.add(g.symbol)}return{entryDefinitions:c,relations:Fn(a),reachedSymbols:new Set([...c.map(m=>m.symbol),...a.flatMap(m=>[m.fromSymbol,m.toSymbol])])}}function eT(e,t,n){let i=t.owner.symbol?n.get(t.owner.symbol):void 0;if(i?.isFunctionLike&&!De(i.symbol))return[{definition:i,evidence:"scip-occurrence-callsite",line:t.source.startLine}];let r=re(e,t.source.file),o=yt(e,t.source.file,0,Math.max(0,r.length-1),[t.source.startLine]),s=Dn(e,t.source.file,o.startLine,o.endLine).targets.map(u=>({definition:u.definition,evidence:"scip-occurrence-callsite",line:u.sourceLine})),a=te(e,t.source.file),l=rn(e),c=(a?.callSites??[]).flatMap(u=>{if(u.line<o.startLine||u.line>o.endLine)return[];let d=nn(t.source.file,l.get(u.calleeLeaf)??[]),m=qn(e,t.source.file,d,u.memberAccess,u.calleeQualifier),f=m?n.get(m.symbol):void 0;return f?.isFunctionLike?[{definition:f,evidence:"ast-callsite",line:u.line}]:[]});return nT([...s,...c])}function tT(e,t){let n=re(e,t.source.file),i=yt(e,t.source.file,0,Math.max(0,n.length-1),[t.source.startLine]),r=Zn(e,t.source.file,{ranges:[i],excludeIndexedTargets:!1}).targets,o=[],s=[];for(let a of r){let l=`source-construct:${a.targetFile}:${a.targetStartLine}:${a.targetEndLine}:${a.calleeLeaf}`;s.push({kind:"call",fromSymbol:Co(t),fromLabel:Fa(t),fromFile:t.source.file,toSymbol:l,toLabel:a.calleeLeaf,toFile:a.targetFile,depth:1,strength:"derived",evidence:"ast-member-import-candidate",callsiteLine:a.line});let c=Dn(e,a.targetFile,a.targetStartLine,a.targetEndLine).targets;for(let u of c)o.push(u.definition),s.push({kind:"call",fromSymbol:l,fromLabel:a.calleeLeaf,fromFile:a.targetFile,toSymbol:u.definition.symbol,toLabel:A(u.definition.symbol),toFile:u.definition.relativePath,depth:2,strength:"exact",evidence:"scip-occurrence-callsite",callsiteLine:u.sourceLine})}return{definitions:Xy(o),relations:Fn(s)}}function nT(e){return[...new Map(e.map(t=>[t.definition.symbol,t])).values()]}function Xy(e){return[...new Map(e.map(t=>[t.symbol,t])).values()]}function Co(e){return e.owner.symbol??e.id}function Fa(e){return e.owner.name??`${e.source.file}:${e.source.startLine+1}`}function iT(e,t,n,i,r){return{kind:"runtime-boundary",fromSymbol:Co(e),fromLabel:Fa(e),fromFile:e.source.file,toSymbol:Co(t),toLabel:Fa(t),toFile:t.source.file,depth:1,strength:r,evidence:`runtime-boundary:${n}`,callsiteLine:e.source.startLine,runtimeBoundaryKey:i.map(o=>`${o.name}=${o.value}`).join(" ")}}function rT(e,t,n){let i=new Map;for(let s of n){let a=i.get(s.fromSymbol)??[];a.push(s),i.set(s.fromSymbol,a)}let r=[{symbol:e,path:[]}],o=new Set([e]);for(;r.length>0;){let s=r.shift();if(s.path.length>0&&t.has(s.symbol))return s.path;for(let a of(i.get(s.symbol)??[]).sort(dn))o.has(a.toSymbol)||(o.add(a.toSymbol),r.push({symbol:a.toSymbol,path:[...s.path,a]}))}return[]}function oT(e,t,n,i){let r=Fn(e),o=new Set([n,...i].flatMap(s=>[...Ro(s),...s.keyAnchors.map(a=>a.symbol)]));for(let s of t){if(r.length>=Fi)break;!o.has(s.fromSymbol)&&!o.has(s.toSymbol)||r.some(a=>a.fromSymbol===s.fromSymbol&&a.toSymbol===s.toSymbol)||r.push(s)}return r.slice(0,Fi)}function sT(e,t,n,i,r,o,s,a){let l=n.filter(u=>!u.root.symbol.startsWith(Au)).map(u=>({root:u.root,relations:u.relations.filter(d=>d.depth===1&&d.fromSymbol===u.root.symbol)}));return aT(l).flatMap((u,d)=>{let m=new Set(u.map(k=>k.root.symbol)),f=new Map;for(let k of u)for(let V of new Set(k.relations.map(le=>le.toSymbol)))f.set(V,(f.get(V)??0)+1);let p=[...f].filter(([,k])=>k>=2).sort(([k,V],[le,G])=>G-V||lT(k,le,i,r,s)).map(([k])=>s.get(k)).filter(k=>k?.isFunctionLike===!0).slice(0,wP);if(p.length===0)return[];let g=t.callerFileMap(p,{semantic:a,sourceFallback:!0}),h=new Set;for(let k of p){h.add(k.relativePath);for(let V of g.get(k.symbolId)??[])h.add(V)}let b=o.filter(k=>k.isFunctionLike&&h.has(k.relativePath)).sort(cT).slice(0,LP),v=t.calleeMap(b,{additive:!1,semantic:a}),y=new Set(p.map(k=>k.symbol)),I=Fn(b.flatMap(k=>Ta(e,k,v.get(k.symbolId)??[],s,1,y).filter(V=>y.has(V.toSymbol)))),E=new Map;for(let k of I){let V=E.get(k.fromSymbol)??new Set;V.add(k.toSymbol),E.set(k.fromSymbol,V)}let S=new Set([...E].filter(([k,V])=>V.size>=2||m.has(k)).map(([k])=>k)),x=I.filter(k=>S.has(k.fromSymbol));if(S.size<2||x.length===0)return[];let L=[...new Set(x.map(k=>k.toSymbol))].map(k=>ka(k,i,r,s)).filter(k=>k!==null).sort(Ze),w=[...S].map(k=>ka(k,i,r,s)).filter(k=>k!==null),R=uT(w,x),M=R.slice(0,Pu),_=R.slice(Pu);if(L.length===0||M.length===0)return[];let D=[...new Set([...L.flatMap(k=>k.matchedTerms),...u.flatMap(k=>k.root.matchedTerms)])].sort(),P=dT(x,M);return[{id:`effect-owner-set:${d+1}:${xo(L[0])}`,kind:"shared-callee-owners",roots:L,keyAnchors:M,candidateOwnerCount:R.length,omittedCandidateOwners:_,ownerRecoveryCommands:PT(_,Pu),upstreamEntries:[],matchedTerms:D,relations:P,relationCount:x.length,omittedRelations:Math.max(0,x.length-P.length),systemMapCommand:Io(M,x,D)}]})}function aT(e){let t=e.map((s,a)=>a),n=s=>{for(;t[s]!==s;)t[s]=t[t[s]],s=t[s];return s},i=(s,a)=>{let l=n(s),c=n(a);l!==c&&(t[c]=l)},r=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 l=0;for(let c of r[s]??[])if((r[a]??new Set).has(c)&&(l+=1),l>=2)break;l>=2&&i(s,a)}let o=new Map;for(let s=0;s<e.length;s+=1){let a=n(s),l=o.get(a)??[];l.push(e[s]),o.set(a,l)}return[...o.values()].filter(s=>s.length>=2)}function lT(e,t,n,i,r){let o=ka(e,n,i,r),s=ka(t,n,i,r);return o?s?Ze(o,s):-1:s?1:e.localeCompare(t)}function cT(e,t){return Vt(J(e.relativePath))-Vt(J(t.relativePath))||e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine}function ka(e,t,n,i){let r=t.get(e);if(r)return Pa(r,n);let o=i.get(e);return o?Qy(o):null}function uT(e,t){let n=new Map;for(let r of t){let o=n.get(r.toSymbol)??new Set;o.add(r.fromSymbol),n.set(r.toSymbol,o)}let i=new Map;for(let r of t){let o=n.get(r.toSymbol)?.size??1;i.set(r.fromSymbol,(i.get(r.fromSymbol)??0)+o*o)}return[...e].sort((r,o)=>Number(r.leaf.startsWith("#"))-Number(o.leaf.startsWith("#"))||o.identityMatchedTerms.length-r.identityMatchedTerms.length||(i.get(o.symbol)??0)-(i.get(r.symbol)??0)||Ze(r,o))}function dT(e,t){let n=new Map(t.map((s,a)=>[s.symbol,a])),i=t.map(s=>e.filter(a=>a.fromSymbol===s.symbol).sort(dn)),r=[],o=0;for(;r.length<Fi&&i.some(s=>o<s.length);){for(let s of i){let a=s[o];if(a&&r.push(a),r.length>=Fi)break}o+=1}return r.sort((s,a)=>n.get(s.fromSymbol)-n.get(a.fromSymbol)||dn(s,a))}function mT(e,t,n,i){let r=new Map(t.map((a,l)=>[a.symbol,l])),o=new Map;for(let a of e)o.set(a.fromSymbol,(o.get(a.fromSymbol)??0)+1);return[...e].sort((a,l)=>{let c=u=>{let d=0;return r.has(u.fromSymbol)&&(d+=100),n.has(u.toSymbol)&&(d+=60),d+=Math.min(40,(o.get(u.toSymbol)??0)*8),(i.get(u.toSymbol)?.matchedTerms.length??0)>0&&(d+=25),u.fromFile!==u.toFile&&(d+=15),u.strength==="exact"&&(d+=5),d};return c(l)-c(a)||dn(a,l)}).slice(0,Fi).sort((a,l)=>(r.get(a.fromSymbol)??Pi)-(r.get(l.fromSymbol)??Pi)||a.depth-l.depth||(a.callsiteLine??Number.MAX_SAFE_INTEGER)-(l.callsiteLine??Number.MAX_SAFE_INTEGER)||dn(a,l))}function Qy(e){return{symbol:e.symbol,label:ei(e),leaf:e.leaf,file:e.relativePath,line:e.startLine,endLine:e.endLine,kind:e.isFunctionLike?"callable":e.isTypeLike?"type":"symbol",fileKind:J(e.relativePath),matches:[],focusLocations:[],matchedTerms:[],symbolMatchedTerms:[],symbolPhraseLength:0,identityMatchedTerms:[],rarity:0,symbolRarity:0}}function fT(e,t,n){let i=[...e].sort(Ze),r=[],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,l=u=>{if(!(!u||r.some(d=>d.symbol===u.symbol))){r.push(u);for(let d of u.matchedTerms)s.add(d);for(let d of u.symbolMatchedTerms)a.add(d)}},c=i.filter(u=>u.symbolPhraseLength>=2&&(o.get(u.symbol)??0)>=2);for(;r.length<Math.min(2,Pi);){let u=c.filter(d=>!r.some(m=>m.symbol===d.symbol)).sort((d,m)=>m.symbolMatchedTerms.filter(f=>!a.has(f)).length-d.symbolMatchedTerms.filter(f=>!a.has(f)).length||m.symbolPhraseLength-d.symbolPhraseLength||(o.get(m.symbol)??0)-(o.get(d.symbol)??0)||Fu(d,m))[0];if(!u||r.length>0&&u.symbolMatchedTerms.every(d=>a.has(d)))break;l(u)}if(l(i[0]),r.length>=2){let u=pT(r[0].symbol,r[1].symbol,t,n);for(let d of u?.slice(1,-1)??[]){if(r.length>=Pi)break;l(n.get(d))}if(r.length<Pi){let d=new Set(r.map(p=>p.symbol)),m=new Set(t.filter(p=>p.depth===1&&d.has(p.fromSymbol)&&d.has(p.toSymbol)).map(p=>p.fromSymbol)),f=t.filter(p=>p.depth===1&&m.has(p.fromSymbol)&&!d.has(p.toSymbol)).map(p=>({relation:p,candidate:n.get(p.toSymbol)})).filter(p=>p.candidate!==void 0&&p.candidate.symbolPhraseLength>=2&&p.candidate.symbolMatchedTerms.length>=2).sort((p,g)=>(o.get(p.relation.fromSymbol)??0)-(o.get(g.relation.fromSymbol)??0)||Fu(p.candidate,g.candidate))[0]?.candidate;l(f)}}else for(;r.length<Math.min(3,Pi);){let u=i.filter(d=>!r.some(m=>m.symbol===d.symbol)).sort((d,m)=>m.matchedTerms.filter(f=>!s.has(f)).length-d.matchedTerms.filter(f=>!s.has(f)).length||Ze(d,m))[0];if(!u||u.matchedTerms.every(d=>s.has(d)))break;l(u)}for(;r.length>=2&&r.length<Pi;){let u=new Set(r.map(m=>m.symbol)),d=[...n.values()].filter(m=>!u.has(m.symbol)&&(o.get(m.symbol)??0)>0&&t.some(f=>u.has(f.fromSymbol)&&f.toSymbol===m.symbol)).sort((m,f)=>f.identityMatchedTerms.length-m.identityMatchedTerms.length||f.symbolMatchedTerms.length-m.symbolMatchedTerms.length||f.matchedTerms.length-m.matchedTerms.length||(o.get(f.symbol)??0)-(o.get(m.symbol)??0)||Ze(m,f))[0];if(!d)break;l(d)}if(r.length<2){let u=r[0],d=u?i.filter(m=>m.symbol!==u.symbol).map(m=>({root:m,path:gT(m.symbol,u.symbol,t)})).filter(m=>m.path!==null).sort((m,f)=>+(f.root.file!==u.file)-+(m.root.file!==u.file)||m.path.length-f.path.length||Ze(m.root,f.root))[0]?.root:void 0;l(d)}return r}function pT(e,t,n,i){let r=new Map;for(let a of n){let l=r.get(a.fromSymbol)??new Set;l.add(a.toSymbol),r.set(a.fromSymbol,l);let c=r.get(a.toSymbol)??new Set;c.add(a.fromSymbol),r.set(a.toSymbol,c)}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:l}=o.shift(),c=a.at(-1);if(c===t)return a;for(let u of r.get(c)??[]){let d=i.get(u),m=u===t?1:!d||d.matchedTerms.length===0?9:d.symbolPhraseLength>=2?1:d.identityMatchedTerms.length>=2?2:4,f=l+m;f>=(s.get(u)??Number.POSITIVE_INFINITY)||(s.set(u,f),o.push({path:[...a,u],cost:f}))}}return null}function gT(e,t,n){let i=new Map;for(let s of n){let a=i.get(s.fromSymbol)??[];a.push(s.toSymbol),i.set(s.fromSymbol,a)}let r=[[e]],o=new Set([e]);for(;r.length>0;){let s=r.shift(),a=s.at(-1);if(a===t)return s;for(let l of i.get(a)??[])o.has(l)||(o.add(l),r.push([...s,l]))}return null}function Ze(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||gr(e.kind)-gr(t.kind)||Vt(e.fileKind)-Vt(t.fileKind)||e.file.localeCompare(t.file)||e.line-t.line}function Fu(e,t){return t.symbolPhraseLength-e.symbolPhraseLength||t.symbolMatchedTerms.length-e.symbolMatchedTerms.length||gr(e.kind)-gr(t.kind)||t.symbolRarity-e.symbolRarity||Ze(e,t)}function hT(e,t){return t.flatMap(n=>{let i=e.filter(s=>s.matchedTerms.includes(n)).sort((s,a)=>bT(s,a,n)),r=[],o=new Set;for(let s of i)if(!o.has(s.file)&&(r.push(s),o.add(s.file),r.length>=_y))return r;for(let s of i)if(!r.some(a=>a.symbol===s.symbol)&&(r.push(s),r.length>=_y))break;return r})}function yT(e,t,n){let i=new Set(t),r=new Map;for(let o of e){if(o.kind!=="callable")continue;let s=o.file.slice(o.file.lastIndexOf("/")+1).replace(/\.[^.]+$/u,"");if(![...mt(s)].some(l=>i.has(l)))continue;let a=r.get(o.file)??[];a.push(o),r.set(o.file,a)}return[...r.entries()].map(([o,s])=>{let a=o.slice(o.lastIndexOf("/")+1).replace(/\.[^.]+$/u,""),l=[...mt(a)].filter(c=>i.has(c));return{file:o,fileCandidates:s,sharedFrequency:Math.min(...l.map(c=>n.get(c)??Number.MAX_SAFE_INTEGER))}}).sort((o,s)=>Vt(o.fileCandidates[0].fileKind)-Vt(s.fileCandidates[0].fileKind)||o.sharedFrequency-s.sharedFrequency||o.file.localeCompare(s.file)).flatMap(({fileCandidates:o})=>[...o].sort(Ze).slice(0,_P)).slice(0,AP)}function bT(e,t,n){return qy(e,n)-qy(t,n)||Vt(e.fileKind)-Vt(t.fileKind)||t.symbolPhraseLength-e.symbolPhraseLength||gr(e.kind)-gr(t.kind)||Ze(e,t)}function qy(e,t){let n=e.matches.find(i=>i.term===t)?.sources??[];return Math.min(...n.map(ku),Number.MAX_SAFE_INTEGER)}function pr(e){return[...new Map(e.map(t=>[t.symbol,t])).values()]}function Ti(e,t,n){let i=new Set(e.roots.flatMap(o=>o.symbolMatchedTerms)),r=new Set(t.roots.flatMap(o=>o.symbolMatchedTerms));return(t.queryPathMatches?.length??0)-(e.queryPathMatches?.length??0)||Vy(e.kind)-Vy(t.kind)||Gy(e)-Gy(t)||Wy(e)-Wy(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)||Ky(t,n)-Ky(e,n)||t.matchedTerms.length-e.matchedTerms.length||Math.max(...t.roots.map(o=>o.symbolPhraseLength))-Math.max(...e.roots.map(o=>o.symbolPhraseLength))||r.size-i.size||Ze(e.roots[0],t.roots[0])||t.roots.length-e.roots.length||e.relationCount-t.relationCount||e.id.localeCompare(t.id)}function Ky(e,t){return e.matchedTerms.reduce((n,i)=>n+1/Math.max(1,t.get(i)??1),0)}function ST(e){return[...new Set(e.roots.flatMap(t=>t.queryPathMatches??[]))].sort()}function Gy(e){let t=e.keyAnchors.length>0?e.keyAnchors:e.roots;return Math.max(...t.map(n=>Vt(n.fileKind)))}function Wy(e){return e.kind==="parallel-paths"?2-(e.parallelConnectedSides??0):e.kind!=="connected-flow"||e.relationCount>0?0:1}function vT(e,t,n){let i=e.slice(0,t);if(t<2||i.some(o=>o.kind==="shared-callee-owners"))return i;let r=e.filter(o=>o.kind==="shared-callee-owners");for(let o of i){if(o.kind==="shared-callee-owners"||o.kind==="parallel-paths")continue;let s=new Set(Ro(o)),a=r.map(c=>({group:c,overlap:CT(c,s)})).filter(({overlap:c})=>c>0).sort(({group:c,overlap:u},{group:d,overlap:m})=>m-u||Ti(c,d,n))[0]?.group;if(!a)continue;let l=i.length-1;for(;l>=0&&i[l]===o;)l-=1;return l<0?i:(i[l]=a,[...i].sort((c,u)=>Ti(c,u,n)))}return i}function CT(e,t){return Ro(e).filter(n=>t.has(n)).length}function Vy(e){switch(e){case"cross-boundary-flow":return 0;case"parallel-paths":case"connected-flow":return 1;case"shared-callee-owners":return 2}}function dn(e,t){return e.depth-t.depth||ti(t.strength)-ti(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 xT(e,t){return ti(Nu(t.source))-ti(Nu(e.source))||(e.callsiteLine??Number.MAX_SAFE_INTEGER)-(t.callsiteLine??Number.MAX_SAFE_INTEGER)||e.symbol.localeCompare(t.symbol)}function Fn(e){let t=new Map;for(let n of e){let i=`${n.fromSymbol}\0${n.toSymbol}`,r=t.get(i);(!r||dn(n,r)<0)&&t.set(i,n)}return[...t.values()]}function RT(e){let t=e.match(/[\p{L}\d_.-]+(?:\/[\p{L}\d_.-]+)+/gu)??[];return[...new Set(t.map(n=>n.replace(/[.;:!?]+$/gu,"").toLocaleLowerCase()))]}function IT(e,t){let n=e.replace(/\\/gu,"/").toLocaleLowerCase();return t.filter(i=>{let r=n.indexOf(i);if(r<0)return!1;let o=r===0?"/":n[r-1],s=n[r+i.length];return o==="/"&&(s===void 0||s==="/")})}function ET(e,t){let n=yo(e).map(Ia),i=0;for(let r=0;r<n.length;r+=1)for(let o=0;o<t.length;o+=1){let s=0;for(;r+s<n.length&&o+s<t.length&&n[r+s]===t[o+s];)s+=1;i=Math.max(i,s)}return i}function Jy(e){if(e.length===0)return[];let t=e.split(`
69
69
  `);return e.endsWith(`
70
- `)&&t.pop(),t}function _T(e,t){return Bu(e)-Bu(t)}function Bu(e){switch(e){case"symbol":return 0;case"path":return 1;case"documentation":return 2;case"source":return 3}}function yr(e){return e==="callable"?0:e==="type"?1:2}function Vt(e){switch(e){case"entry":case"source":case"worker":return 0;case"barrel":return 1;case"test":return 2}}function Ou(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function ti(e){return e==="exact"?2:1}function tb(e,t){return e.file.localeCompare(t.file)||e.line-t.line}function Io(e){return`${e.file}:${e.line+1}`}function wo(e,t=[],n=[]){let i=e.map(s=>`--symbol ${Aa(`${s.file}:${s.line+1}-${s.endLine+1}`)}`),r=new Set(e.map(s=>s.symbol)),o=e.flatMap(s=>(s.sourceCharacters??0)>ku?BT(s,t,n,r).map(a=>`--focus-at ${Aa(`${a.file}:${a.line+1}`)}`):[]);return`codebaseiq system-map ${[...i,...o,"--relation call","--relation runtime-boundary"].join(" ")}`}function BT(e,t,n,i){let r=new Set(n),o=t.filter(c=>c.fromSymbol===e.symbol&&c.callsiteLine!==null&&c.callsiteLine>=e.line&&c.callsiteLine<=e.endLine).map(c=>({file:e.file,line:c.callsiteLine,connectsAnchor:i.has(c.toSymbol),overlap:new Set(So(OT(c.toLabel)).flatMap(Su).filter(u=>r.has(u))).size,strength:c.strength})).filter(c=>c.overlap>0).sort((c,u)=>Number(u.connectsAnchor)-Number(c.connectsAnchor)||u.overlap-c.overlap||c.line-u.line||ti(u.strength)-ti(c.strength)),s=o.filter(c=>c.connectsAnchor),a=[...s.length>0?s:o,...s.length>0?[]:e.focusLocations.map(c=>({...c,connectsAnchor:!1,overlap:0,strength:"derived"}))],l=[];for(let c of a)if(!l.some(u=>u.file===c.file&&u.line===c.line)&&(l.push({file:c.file,line:c.line}),l.length>=3))break;return l}function OT(e){return e.slice(Math.max(e.lastIndexOf(":"),e.lastIndexOf("."))+1)}function $T(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 l=`${a.file}\0${a.line}`,c=n.get(l)??{...a,matchedTerms:new Set};c.matchedTerms.add(o),n.set(l,c)}let i=[...n.values()].sort((o,s)=>s.matchedTerms.size-o.matchedTerms.size||[...s.matchedTerms].reduce((a,l)=>a+1/Math.max(1,t.get(l)??1),0)-[...o.matchedTerms].reduce((a,l)=>a+1/Math.max(1,t.get(l)??1),0)||tb(o,s)),r=[];for(let o of i)if(!r.some(s=>s.file===o.file&&Math.abs(s.line-o.line)<8)&&(r.push(o),r.length>=3))break;return r.map(o=>({file:o.file,line:o.line,matchedTerms:[...o.matchedTerms].sort()}))}function jT(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(wo(e.slice(i,i+t)));return n}function Aa(e){return`'${e.replaceAll("'",`'"'"'`)}'`}import{createHash as Eb}from"crypto";function _a(e,t){return de(e)-de(t)||e.relativePath.localeCompare(t.relativePath)}function ke(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function br(e){let t=new Set,n=[];for(let i of e){let r=`${i.symbol}|${i.file}`;t.has(r)||(t.add(r),n.push(i))}return n}function Lo(e,t,n={}){let i=pe(e,t);if(!i)return null;let r=n.semantic!==!1,o=dc(e,i,{semantic:r,semanticEvidence:ge}),s=o.rows.filter(d=>_e(d.symbol)).slice(0,50),a=vi(e,i,{limit:50,additive:!0,callableOnly:!0,semantic:r,semanticEvidence:ge}),l=br(a.rows),c=s.map(d=>({symbol:d.symbol,shortName:A(d.symbol),file:d.file,relationship:d.source!=="caller-map-inversion"?"reference-candidate":d.callEvidence==="scip-chunk"?"chunk-candidate":"resolved-call",evidenceStrength:d.source==="caller-map-inversion"&&d.callEvidence!=="scip-chunk"?"exact":"candidate",evidenceSource:d.callEvidence??d.source})),u=l.map(d=>({symbol:d.symbol,shortName:A(d.symbol),file:d.file,relationship:d.source==="scip-chunk"?"chunk-candidate":"resolved-call",evidenceStrength:d.source==="scip-chunk"?"candidate":"exact",evidenceSource:d.source}));return{symbol:i.symbol,shortName:A(i.symbol),callers:c.map(({symbol:d,shortName:m,file:f})=>({symbol:d,shortName:m,file:f})),callees:u.map(({symbol:d,shortName:m,file:f})=>({symbol:d,shortName:m,file:f})),callerEvidence:c,calleeEvidence:u,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",...o.semanticIncomplete?["compiler-resolved incoming evidence was incomplete; known callers are retained"]:[],...o.semanticUnavailable?["compiler-resolved incoming evidence was unavailable; known callers are retained"]:[],...a.semanticIncomplete?["compiler-resolved outgoing evidence was incomplete; known callees are retained"]:[],...a.semanticUnavailable?["compiler-resolved outgoing evidence was unavailable; known callees are retained"]:[]],semanticEvidence:{enabled:r,incoming:nb(r,o),outgoing:nb(r,a)}}}}function nb(e,t){return e?t.semanticIncomplete&&t.semanticUnavailable?"incomplete-and-unavailable":t.semanticIncomplete?"incomplete":t.semanticUnavailable?"unavailable":"complete":"disabled"}function Sr(e,t,n){if(n.length===0)return[];let i=new Set(n),r=$e(e),o=new Set;if(t==="forward")for(let s of i)for(let a of r.get(s)??[])i.has(a)||o.add(a);else for(let[s,a]of r)if(!i.has(s))for(let l of i)a.has(l)&&o.add(s);return[...o].sort()}function Do(e,t){let n=dt(e,t);return n?Sr(e,"forward",[n]).filter(r=>!e.isIgnored(r)).map(r=>({relativePath:r,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):[]}function Mo(e,t){let n=dt(e,t);return n?Sr(e,"reverse",[n]).filter(r=>!e.isIgnored(r)).map(r=>({relativePath:r,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):[]}function ju(e,t,n={}){let i=Ba(e,t,n);return{definitions:i.definitions,referencedBy:i.referencedBy}}function Ba(e,t,n={}){let i=pe(e,t);if(!i)return{definitions:[],referencedBy:[],referenceEvidence:[],claimSupport:null};let r=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",i.symbolId),o=tr(r?.documentation??null),s=e.isIgnored(i.relativePath)?[]:[{relativePath:i.relativePath,startLine:i.startLine,endLine:i.endLine,signature:GT(o,r?.display_name??null,i.symbol),source:KT(e,i.relativePath,i.startLine,i.endLine)}],a=n.referenceContext??2,l=Gf(e,i,{semantic:n.semantic,semanticEvidence:ge}).map(u=>{let d=_p(e,u.file,u.line,a,Y(i.symbol));return{relativePath:u.file,line:u.line,enclosingSymbol:u.enclosingSymbol,enclosingShort:u.enclosingSymbol?A(u.enclosingSymbol):"(top-level)",provenance:u.provenance,sourceStartLine:d?.startLine??null,sourceEndLine:d?.endLine??null,source:d?.source??null,sourceKind:d?.kind??"unavailable"}}),c=l.map(HT);return{definitions:s,referencedBy:c,referenceEvidence:l.map(u=>({relativePath:u.relativePath,line:u.line,provenance:u.provenance,sourceKind:u.sourceKind})),claimSupport:UT(l)}}function HT(e){return{relativePath:e.relativePath,line:e.line,enclosingSymbol:e.enclosingSymbol,enclosingShort:e.enclosingShort,sourceStartLine:e.sourceStartLine,sourceEndLine:e.sourceEndLine,source:e.source}}function UT(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."],i=e.filter(o=>o.sourceKind!=="complete-call-expression"&&o.sourceKind!=="non-call-reference"),r="direct, statically visible call expressions among the resolved reference sites";return{referenceAbsence:{status:"eligible",scope:t,limitations:n},callsitePredicates:i.length===0?{status:"eligible",scope:r,limitations:n}:{status:"ineligible",scope:r,reason:`${i.length} reference site(s) lack one unambiguous complete call expression.`,followup:zT(i)}}}function zT(e){let t=[...new Set(e.map(n=>`${n.relativePath}:${n.line+1}`))];return t.length===0||t.length>24?null:`codebaseiq inspect ${t.map(n=>`--at ${qT(n)}`).join(" ")} --view behavior`}function qT(e){return`'${e.replaceAll("'","'\\''")}'`}function KT(e,t,n,i){let r=se(e,t);if(!r)return null;let s=r.split(`
70
+ `)&&t.pop(),t}function wT(e,t){return ku(e)-ku(t)}function ku(e){switch(e){case"symbol":return 0;case"path":return 1;case"documentation":return 2;case"source":return 3}}function gr(e){return e==="callable"?0:e==="type"?1:2}function Vt(e){switch(e){case"entry":case"source":case"worker":return 0;case"barrel":return 1;case"test":return 2}}function Nu(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function ti(e){return e==="exact"?2:1}function Zy(e,t){return e.file.localeCompare(t.file)||e.line-t.line}function xo(e){return`${e.file}:${e.line+1}`}function Io(e,t=[],n=[]){let i=e.map(s=>`--symbol ${Na(`${s.file}:${s.line+1}-${s.endLine+1}`)}`),r=new Set(e.map(s=>s.symbol)),o=e.flatMap(s=>(s.sourceCharacters??0)>Mu?LT(s,t,n,r).map(a=>`--focus-at ${Na(`${a.file}:${a.line+1}`)}`):[]);return`codebaseiq system-map ${[...i,...o,"--relation call","--relation runtime-boundary"].join(" ")}`}function LT(e,t,n,i){let r=new Set(n),o=t.filter(c=>c.fromSymbol===e.symbol&&c.callsiteLine!==null&&c.callsiteLine>=e.line&&c.callsiteLine<=e.endLine).map(c=>({file:e.file,line:c.callsiteLine,connectsAnchor:i.has(c.toSymbol),overlap:new Set(yo(DT(c.toLabel)).flatMap(hu).filter(u=>r.has(u))).size,strength:c.strength})).filter(c=>c.overlap>0).sort((c,u)=>Number(u.connectsAnchor)-Number(c.connectsAnchor)||u.overlap-c.overlap||c.line-u.line||ti(u.strength)-ti(c.strength)),s=o.filter(c=>c.connectsAnchor),a=[...s.length>0?s:o,...s.length>0?[]:e.focusLocations.map(c=>({...c,connectsAnchor:!1,overlap:0,strength:"derived"}))],l=[];for(let c of a)if(!l.some(u=>u.file===c.file&&u.line===c.line)&&(l.push({file:c.file,line:c.line}),l.length>=3))break;return l}function DT(e){return e.slice(Math.max(e.lastIndexOf(":"),e.lastIndexOf("."))+1)}function MT(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 l=`${a.file}\0${a.line}`,c=n.get(l)??{...a,matchedTerms:new Set};c.matchedTerms.add(o),n.set(l,c)}let i=[...n.values()].sort((o,s)=>s.matchedTerms.size-o.matchedTerms.size||[...s.matchedTerms].reduce((a,l)=>a+1/Math.max(1,t.get(l)??1),0)-[...o.matchedTerms].reduce((a,l)=>a+1/Math.max(1,t.get(l)??1),0)||Zy(o,s)),r=[];for(let o of i)if(!r.some(s=>s.file===o.file&&Math.abs(s.line-o.line)<8)&&(r.push(o),r.length>=3))break;return r.map(o=>({file:o.file,line:o.line,matchedTerms:[...o.matchedTerms].sort()}))}function PT(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(Io(e.slice(i,i+t)));return n}function Na(e){return`'${e.replaceAll("'",`'"'"'`)}'`}import{createHash as Rb}from"crypto";function Aa(e,t){return de(e)-de(t)||e.relativePath.localeCompare(t.relativePath)}function ke(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function hr(e){let t=new Set,n=[];for(let i of e){let r=`${i.symbol}|${i.file}`;t.has(r)||(t.add(r),n.push(i))}return n}function Eo(e,t,n={}){let i=pe(e,t);if(!i)return null;let r=n.semantic!==!1,o=uc(e,i,{semantic:r,semanticEvidence:ge}),s=o.rows.filter(d=>_e(d.symbol)).slice(0,50),a=vi(e,i,{limit:50,additive:!0,callableOnly:!0,semantic:r,semanticEvidence:ge}),l=hr(a.rows),c=s.map(d=>({symbol:d.symbol,shortName:A(d.symbol),file:d.file,relationship:d.source!=="caller-map-inversion"?"reference-candidate":d.callEvidence==="scip-chunk"?"chunk-candidate":"resolved-call",evidenceStrength:d.source==="caller-map-inversion"&&d.callEvidence!=="scip-chunk"?"exact":"candidate",evidenceSource:d.callEvidence??d.source})),u=l.map(d=>({symbol:d.symbol,shortName:A(d.symbol),file:d.file,relationship:d.source==="scip-chunk"?"chunk-candidate":"resolved-call",evidenceStrength:d.source==="scip-chunk"?"candidate":"exact",evidenceSource:d.source}));return{symbol:i.symbol,shortName:A(i.symbol),callers:c.map(({symbol:d,shortName:m,file:f})=>({symbol:d,shortName:m,file:f})),callees:u.map(({symbol:d,shortName:m,file:f})=>({symbol:d,shortName:m,file:f})),callerEvidence:c,calleeEvidence:u,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",...o.semanticIncomplete?["compiler-resolved incoming evidence was incomplete; known callers are retained"]:[],...o.semanticUnavailable?["compiler-resolved incoming evidence was unavailable; known callers are retained"]:[],...a.semanticIncomplete?["compiler-resolved outgoing evidence was incomplete; known callees are retained"]:[],...a.semanticUnavailable?["compiler-resolved outgoing evidence was unavailable; known callees are retained"]:[]],semanticEvidence:{enabled:r,incoming:eb(r,o),outgoing:eb(r,a)}}}}function eb(e,t){return e?t.semanticIncomplete&&t.semanticUnavailable?"incomplete-and-unavailable":t.semanticIncomplete?"incomplete":t.semanticUnavailable?"unavailable":"complete":"disabled"}function yr(e,t,n){if(n.length===0)return[];let i=new Set(n),r=$e(e),o=new Set;if(t==="forward")for(let s of i)for(let a of r.get(s)??[])i.has(a)||o.add(a);else for(let[s,a]of r)if(!i.has(s))for(let l of i)a.has(l)&&o.add(s);return[...o].sort()}function wo(e,t){let n=dt(e,t);return n?yr(e,"forward",[n]).filter(r=>!e.isIgnored(r)).map(r=>({relativePath:r,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):[]}function Lo(e,t){let n=dt(e,t);return n?yr(e,"reverse",[n]).filter(r=>!e.isIgnored(r)).map(r=>({relativePath:r,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):[]}function _u(e,t,n={}){let i=_a(e,t,n);return{definitions:i.definitions,referencedBy:i.referencedBy}}function _a(e,t,n={}){let i=pe(e,t);if(!i)return{definitions:[],referencedBy:[],referenceEvidence:[],claimSupport:null};let r=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",i.symbolId),o=Zi(r?.documentation??null),s=e.isIgnored(i.relativePath)?[]:[{relativePath:i.relativePath,startLine:i.startLine,endLine:i.endLine,signature:_T(o,r?.display_name??null,i.symbol),source:AT(e,i.relativePath,i.startLine,i.endLine)}],a=n.referenceContext??2,l=Uf(e,i,{semantic:n.semantic,semanticEvidence:ge}).map(u=>{let d=kp(e,u.file,u.line,a,Y(i.symbol));return{relativePath:u.file,line:u.line,enclosingSymbol:u.enclosingSymbol,enclosingShort:u.enclosingSymbol?A(u.enclosingSymbol):"(top-level)",provenance:u.provenance,sourceStartLine:d?.startLine??null,sourceEndLine:d?.endLine??null,source:d?.source??null,sourceKind:d?.kind??"unavailable"}}),c=l.map(TT);return{definitions:s,referencedBy:c,referenceEvidence:l.map(u=>({relativePath:u.relativePath,line:u.line,provenance:u.provenance,sourceKind:u.sourceKind})),claimSupport:FT(l)}}function TT(e){return{relativePath:e.relativePath,line:e.line,enclosingSymbol:e.enclosingSymbol,enclosingShort:e.enclosingShort,sourceStartLine:e.sourceStartLine,sourceEndLine:e.sourceEndLine,source:e.source}}function FT(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."],i=e.filter(o=>o.sourceKind!=="complete-call-expression"&&o.sourceKind!=="non-call-reference"),r="direct, statically visible call expressions among the resolved reference sites";return{referenceAbsence:{status:"eligible",scope:t,limitations:n},callsitePredicates:i.length===0?{status:"eligible",scope:r,limitations:n}:{status:"ineligible",scope:r,reason:`${i.length} reference site(s) lack one unambiguous complete call expression.`,followup:kT(i)}}}function kT(e){let t=[...new Set(e.map(n=>`${n.relativePath}:${n.line+1}`))];return t.length===0||t.length>24?null:`codebaseiq inspect ${t.map(n=>`--at ${NT(n)}`).join(" ")} --view behavior`}function NT(e){return`'${e.replaceAll("'","'\\''")}'`}function AT(e,t,n,i){let r=se(e,t);if(!r)return null;let s=r.split(`
71
71
  `).slice(n,i+1).join(`
72
- `).trimEnd();return s.length>0?s:null}function GT(e,t,n){let i=er(e);if(i&&!WT(i))return i;let r=(t??"").trim();return r?_e(n)&&!r.endsWith("()")?`${r}()`:r:A(n)}function WT(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function Hu(e,t,n={}){let i=ob(e,t,n);if(i.kind!=="matched")return i;let{referenceEvidence:r,claimSupport:o,...s}=i;return s}function ob(e,t,n={}){let i=at(e,t);if(!i.match)return{kind:"missing",query:t};if(i.total>1)return{kind:"ambiguous",query:t,total:i.total,candidates:[{symbol:i.match.symbol,shortName:A(i.match.symbol),relativePath:i.match.relativePath,startLine:i.match.startLine},...i.candidates]};let r=i.match,o=JT(n.parts),s=o.includes("definition")||o.includes("references")?Ba(e,r.symbol,{semantic:n.semantic,referenceContext:n.referenceContext}):{definitions:[],referencedBy:[],referenceEvidence:[],claimSupport:null},a=o.includes("callers")||o.includes("callees")?Lo(e,r.symbol,{semantic:n.semantic}):null,l=n.relatedSourceLines??80;return{kind:"matched",query:t,symbol:r.symbol,shortName:A(r.symbol),file:r.relativePath,parts:o,definition:o.includes("definition")?wc(e,r.symbol):null,referenceWindows:o.includes("references")?VT(e,s.referencedBy):[],callers:o.includes("callers")?rb(e,a?.callers??[],l):[],callees:o.includes("callees")?rb(e,a?.callees??[],l):[],dependencies:o.includes("dependencies")?Do(e,r.relativePath):[],consumers:o.includes("consumers")?Mo(e,r.relativePath):[],referenceEvidence:s.referenceEvidence,claimSupport:s.claimSupport}}function VT(e,t){let n=t.filter(r=>r.sourceStartLine!==null&&r.sourceEndLine!==null&&r.source!==null).sort((r,o)=>r.relativePath.localeCompare(o.relativePath)||r.sourceStartLine-o.sourceStartLine||r.line-o.line),i=[];for(let r of n){let o=i[i.length-1];if(o&&o.relativePath===r.relativePath&&r.sourceStartLine<=o.endLine+1){o.endLine=Math.max(o.endLine,r.sourceEndLine),o.references.push(ib(r)),o.source=re(e,o.relativePath).slice(o.startLine,o.endLine+1).join(`
73
- `);continue}i.push({relativePath:r.relativePath,startLine:r.sourceStartLine,endLine:r.sourceEndLine,source:r.source,references:[ib(r)]})}return i}function ib(e){return{line:e.line,enclosingSymbol:e.enclosingSymbol,enclosingShort:e.enclosingShort}}function JT(e){let t=e&&e.length>0?e:["definition","references"];return[...new Set(t)]}function rb(e,t,n){let i=[],r=new Set;for(let o of t){if(r.has(o.symbol))continue;r.add(o.symbol);let s=(o.file?W(e,o.file).find(l=>l.symbol===o.symbol):void 0)??at(e,o.symbol).match;if(!s)continue;let a=Bp(e,s.relativePath,s.startLine,s.endLine,n);a&&i.push({...a,symbol:o.symbol,shortName:o.shortName,omittedLines:Math.max(0,s.endLine-a.endLine)})}return i}var ub=6;function sb(e,t,n){return`${e}\0${t}\0${n??t}`}function db(e,t,n,i={}){let r=i.limit??ub;if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`next-anchor limit must be a positive safe integer; received ${r}`);let o=i.sourceAllowed??(()=>!0),s=new Map(t.nodes.map(C=>[C.id,C])),a=new Set(n.steps.map(C=>C.nodeId)),l=new Set(n.steps.flatMap(C=>{let L=qu(s.get(C.nodeId));return L?[L]:[]})),c=new Set;for(let C of n.steps)for(let L of C.behavior?.supportingDeclarations??[])l.add(L.symbol),c.add(sb(L.file,L.line,L.endLine));let u=C=>C.symbol!==null&&l.has(C.symbol)||c.has(sb(C.file,C.line,C.endLine)),d=new Map(n.steps.flatMap(C=>{if(!C.location)return[];let L=qu(s.get(C.nodeId));if(!L)return[];let w=W(e,C.location.file).find(R=>R.symbol===L);return w?[[C.id,w]]:[]})),m=new U(e).calleeMap([...d.values()],{additive:!1,semantic:!0}),f=[],p=new Set,g=new Set,h=0,b=0,v=0,y=0,I=0,E=0,S=0,x=0;for(let C of n.steps){if(!C.location||!C.behavior)continue;let L=t.edges.filter(N=>["call","runtime-boundary"].includes(N.kind)&&(N.fromNodeId===C.nodeId||N.toNodeId===C.nodeId)&&N.disposition!=="excluded"&&N.disposition!=="unsupported");for(let N of L){let K=N.toNodeId===C.nodeId,ne=K?N.fromNodeId:N.toNodeId;if(a.has(ne))continue;let fe=s.get(ne);if(!fe?.location||!o(fe.location.file))continue;let he=N.kind==="call"?Gu(e,fe):Ku(fe);if(!he||u(he))continue;let ce=Wu(N,fe.location.file)??fe.location,be=re(e,ce.file)[ce.line]?.trim(),T=K?"upstream":"downstream",Z=N.kind==="runtime-boundary"?K?"runtime-producer":"runtime-consumer":K?"caller":"callee",Q=["call"],Se=Uu(N.evidence),it=Po(fe);f.push({anchor:{id:ni(C.id,ce.line,fe.id),status:Se,source:"graph-relation",direction:T,causalRole:Z,relationKind:N.kind,fromStepId:C.id,fromLabel:C.label,callsite:{file:ce.file,line:ce.line,endLine:ce.endLine??ce.line,text:be||`${fe.label} \u2192 ${C.label}`,signals:Q,calleeLeaf:it},alternatives:[he],alternativeCount:1,evidence:N.evidence}}),K&&(E+=1),N.kind==="runtime-boundary"&&(x+=1)}let w=t.edges.filter(N=>N.kind==="reference"&&N.fromNodeId===C.nodeId&&N.disposition!=="excluded"&&N.disposition!=="unsupported"&&!a.has(N.toNodeId));for(let N of w){let K=s.get(N.toNodeId);if(!K?.location||!o(K.location.file))continue;let ne=Gu(e,K);if(!ne||u(ne))continue;let fe=Po(K),he=Wu(N,C.location.file)?.line,ce=C.behavior.lines.find(Q=>(he===void 0||he>=Q.line&&he<=Q.endLine)&&Q.text.includes(fe));if(!ce)continue;let be=fb(ce.signals),T=be==="result-callback",Z=Uu(N.evidence);f.push({anchor:{id:ni(C.id,ce.line,K.id),status:Z,source:"graph-relation",direction:"downstream",causalRole:be,relationKind:"reference",fromStepId:C.id,fromLabel:C.label,callsite:{file:C.location.file,line:ce.line,endLine:ce.endLine,text:ce.text,signals:ce.signals,calleeLeaf:fe},alternatives:[ne],alternativeCount:1,evidence:N.evidence}}),T&&(S+=1)}let R=Dn(e,C.location.file,C.location.line,C.location.endLine??C.location.line),M=re(e,C.location.file),_=En(e,C.location.file,C.location.line,C.location.endLine??C.location.line);for(let N of R.targets){if(!o(N.definition.relativePath))continue;let K=ki(C.location.file,N.sourceLine,N.calleeLeaf);if(p.has(K))continue;p.add(K);let ne=zu(_.get(N.sourceLine)),fe={symbol:N.definition.symbol,label:N.definition.leaf,file:N.definition.relativePath,line:N.definition.startLine,endLine:N.definition.endLine};u(fe)||f.push({anchor:{id:ni(C.id,N.sourceLine,N.definition.symbol),status:"exact",source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:C.id,fromLabel:C.label,callsite:{file:C.location.file,line:N.sourceLine,endLine:N.sourceLine,text:M[N.sourceLine]?.trim()||`${N.calleeLeaf}()`,signals:ne,calleeLeaf:N.calleeLeaf},alternatives:[fe],alternativeCount:1,evidence:[{method:"scip-occurrence-callsite",strength:"exact",identity:N.definition.symbol,location:{file:C.location.file,line:N.sourceLine}}]}})}let D=C.behavior.lines.filter(N=>N.signals.includes("call"));if(D.length===0)continue;h+=1;let P=(te(e,C.location.file)?.callSites??[]).filter(N=>D.some(K=>N.line>=K.line&&N.line<=K.endLine));b+=P.length;let k=t.edges.filter(N=>N.kind==="call"&&N.fromNodeId===C.nodeId&&N.disposition!=="excluded"&&N.disposition!=="unsupported"),V=new Map;for(let N of k){let K=s.get(N.toNodeId);if(!K)continue;let ne=Po(K);V.set(ne,(V.get(ne)??0)+1)}let le=d.get(C.id),G=XT(e,le?m.get(le.symbolId)??[]:[]),X=QT(G);for(let N of G){if(!o(N.alternative.file)||u(N.alternative))continue;let K=Oa(N.alternative.label),ne=lb(P,D,K,N.row.callsiteLine,X.get(K)===1);if(!ne)continue;let fe=To(D,ne.line,K);if(!fe)continue;let he=ki(C.location.file,ne.line,K);if(p.has(he))continue;p.add(he);let ce=yb(N.row.source);f.push({anchor:{id:ni(C.id,ne.line,N.alternative.symbol??N.alternative.file),status:ce,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:C.id,fromLabel:C.label,callsite:{file:C.location.file,line:fe.line,endLine:fe.endLine,text:fe.text,signals:fe.signals,calleeLeaf:K},alternatives:[N.alternative],alternativeCount:1,evidence:[{method:N.row.source,strength:ce,identity:N.row.symbol,location:{file:C.location.file,line:ne.line}}]}})}for(let N of k){if(a.has(N.toNodeId))continue;let K=s.get(N.toNodeId);if(!K?.location||!o(K.location.file))continue;let ne=Po(K),fe=N.evidence.find(Q=>{let Se=Q.location;return Se!==null&&Se.file===C.location?.file&&Se.line>=0})?.location?.line,he=lb(P,D,ne,fe,V.get(ne)===1);if(!he)continue;let ce=To(D,he.line,ne);if(!ce)continue;let be=ki(C.location.file,he.line,ne);if(p.has(be))continue;p.add(be);let T=Ku(K);if(!T||u(T))continue;let Z=Uu(N.evidence);f.push({anchor:{id:ni(C.id,he.line,K.id),status:Z,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:C.id,fromLabel:C.label,callsite:{file:C.location.file,line:ce.line,endLine:ce.endLine,text:ce.text,signals:ce.signals,calleeLeaf:ne},alternatives:[T],alternativeCount:1,evidence:N.evidence}})}for(let N of P){let K=ki(C.location.file,N.line,N.calleeLeaf);if(p.has(K))continue;let ne=To(D,N.line,N.calleeLeaf);if(!ne)continue;let fe=nn(C.location.file,rn(e).get(N.calleeLeaf)??[]).flatMap(T=>W(e,T.file).filter(Z=>Z.symbol===T.symbol&&Z.isFunctionLike)).filter(T=>o(T.relativePath)&&!u({symbol:T.symbol,label:T.leaf,file:T.relativePath,line:T.startLine,endLine:T.endLine})),he=ja(fe.map(T=>({symbol:T.symbol,label:T.leaf??N.calleeLeaf,file:T.relativePath,line:T.startLine,endLine:T.endLine})));if(he.length===0){I+=1;continue}let ce=`${C.id}\0${N.line}\0${N.calleeLeaf}`;if(g.has(ce))continue;g.add(ce);let be=he.length>1;be?y+=1:v+=1,f.push({anchor:{id:ni(C.id,N.line,N.calleeLeaf),status:be?"ambiguous":"candidate",source:"leaf-identity-candidate",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:C.id,fromLabel:C.label,callsite:{file:C.location.file,line:ne.line,endLine:ne.endLine,text:ne.text,signals:ne.signals,calleeLeaf:N.calleeLeaf},alternatives:he.slice(0,3),alternativeCount:he.length,evidence:[]}})}}return gb(e,f,n.steps,r,{scannedBehaviorSteps:h,visibleCallsites:b,graphEvidencedCallsites:p.size,identityCandidateCallsites:v,ambiguousCallsites:y,unresolvedCallsites:I,upstreamCandidates:E,resultCandidates:S,runtimeCandidates:x},i.selectionTerms)}function mb(e,t,n){let i=new Map(t.nodes.map(r=>[r.id,r]));for(let r of n.steps)if(!(!r.behavior||!r.location))for(let o of t.edges){if(o.kind!=="reference"||o.fromNodeId!==r.nodeId||o.disposition==="excluded"||o.disposition==="unsupported")continue;let s=i.get(o.toNodeId);if(!s?.location||!Gu(e,s))continue;let a=Po(s),l=Wu(o,r.location.file)?.line,c=r.behavior.lines.find(u=>(l===void 0||l>=u.line&&l<=u.endLine)&&u.text.includes(a));!c||fb(c.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 fb(e){return e.includes("call")&&e.some(t=>["return","mutation","shape","spread","binding"].includes(t))?"result-callback":"callable-reference"}function pb(e,t,n={}){let i=n.limit??ub;if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`next-anchor limit must be a positive safe integer; received ${i}`);let r=n.sourceAllowed??(()=>!0),o=[],s=t.map((f,p)=>({id:f.id,nodeId:f.id,order:p,role:"anchor",kind:"source-construct",label:f.label,location:{file:f.file,line:f.startLine,endLine:f.endLine},behavior:null})),a=t.map(f=>({file:f.file,startLine:f.startLine,endLine:f.endLine})),l=0,c=0,u=0,d=0,m=0;for(let f of t){let p=re(e,f.file),h=(te(e,f.file)?.callSites??[]).filter(S=>S.line>=f.startLine&&S.line<=f.endLine);l+=h.length;let b=En(e,f.file,f.startLine,f.endLine),v=Dn(e,f.file,f.startLine,f.endLine),y=new Set;for(let S of v.targets){if(!r(S.definition.relativePath)||a.some(w=>w.file===S.definition.relativePath&&w.startLine<=S.definition.startLine&&w.endLine>=S.definition.endLine))continue;let x=ki(f.file,S.sourceLine,S.calleeLeaf);y.add(x);let C=zu(b.get(S.sourceLine)),L={symbol:S.definition.symbol,label:S.definition.leaf,file:S.definition.relativePath,line:S.definition.startLine,endLine:S.definition.endLine};o.push({anchor:{id:ni(f.id,S.sourceLine,S.definition.symbol),status:"exact",source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:f.id,fromLabel:f.label,callsite:{file:f.file,line:S.sourceLine,endLine:S.sourceLine,text:p[S.sourceLine]?.trim()||`${S.calleeLeaf}()`,signals:C,calleeLeaf:S.calleeLeaf},alternatives:[L],alternativeCount:1,evidence:[{method:"scip-occurrence-callsite",strength:"exact",identity:S.definition.symbol,location:{file:f.file,line:S.sourceLine}}]}})}c+=v.resolvedCallsites;let I=Zn(e,f.file,{ranges:[{startLine:f.startLine,endLine:f.endLine}]}),E=new Map;for(let S of I.targets){let x=h.find(w=>w.line===S.line)?.calleeLeaf??S.calleeLeaf,C=ki(f.file,S.line,x),L=E.get(C)??[];L.push(S),E.set(C,L)}for(let[S,x]of E){if(y.has(S))continue;y.add(S);let C=x.filter(D=>r(D.targetFile)&&!a.some(P=>P.file===D.targetFile&&P.startLine<=D.targetStartLine&&P.endLine>=D.targetEndLine));if(C.length===0)continue;let L=C[0],w=h.find(D=>D.line===L.line)?.calleeLeaf??L.calleeLeaf,R=zu(b.get(L.line)),M=ja(C.map(D=>({symbol:D.targetSymbol??null,label:D.calleeLeaf,file:D.targetFile,line:D.targetStartLine,endLine:D.targetEndLine}))),_=C.some(D=>(D.resolutionAlternativeCount??0)>1)?"candidate":C.every(D=>D.strength==="exact")?"exact":"derived";o.push({anchor:{id:ni(f.id,L.line,M.map(D=>`${D.file}:${D.line}`).join("|")),status:M.length>1?"ambiguous":_,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:f.id,fromLabel:f.label,callsite:{file:f.file,line:L.line,endLine:L.line,text:p[L.line]?.trim()||`${L.calleeLeaf}()`,signals:R,calleeLeaf:w},alternatives:M.slice(0,3),alternativeCount:M.length,evidence:C.map(D=>({method:D.resolution==="constructed-member-receiver"?"ast-constructed-member-callsite":D.resolution==="factory-callback-member"?"ast-factory-callback-callsite":D.resolution==="imported-service-object-member"?"ast-service-member-callsite":"ast-import-member-callsite",strength:_,identity:D.targetSymbol??`${D.targetFile}:${D.targetStartLine}-${D.targetEndLine}`,location:{file:f.file,line:L.line}}))}})}c+=E.size;for(let S of h){let x=ki(f.file,S.line,S.calleeLeaf);y.has(x)||(m+=1)}}return gb(e,o,s,i,{scannedBehaviorSteps:t.length,visibleCallsites:l,graphEvidencedCallsites:c,identityCandidateCallsites:u,ambiguousCallsites:d,unresolvedCallsites:m,upstreamCandidates:0,resultCandidates:0,runtimeCandidates:0})}function gb(e,t,n,i,r,o=[]){let s=ZT(t).sort(hb),a=s.filter(p=>YT(e,p)).slice(0,i),l=new Set(a.map(p=>p.anchor.id)),c=s.filter(p=>!l.has(p.anchor.id)),u=a.map(p=>p.anchor),d=c.map(p=>p.anchor),m=ja(u.flatMap(p=>p.alternativeCount===1?p.alternatives:[])),f=ja(d.flatMap(p=>p.alternativeCount===1?p.alternatives:[]));return{anchors:u,withheldAnchors:d,candidateAnchors:s.length,omittedAnchors:Math.max(0,s.length-u.length),...r,inspectCommand:m.length===0?null:`codebaseiq inspect ${m.map(cb).join(" ")} --view behavior`,remainingInspectCommands:tF(f,8).map(p=>`codebaseiq inspect ${p.map(cb).join(" ")} --view behavior`)}}function hb(e,t){let n=e.anchor.alternatives[0],i=t.anchor.alternatives[0];return $a(e.anchor.status)-$a(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(i?.file??"")||(n?.line??0)-(i?.line??0)||e.anchor.id.localeCompare(t.anchor.id)}function YT(e,t){if(t.anchor.alternativeCount!==1)return!0;let n=t.anchor.alternatives[0],i=n.endLine??n.line;return re(e,n.file).slice(n.line,i+1).join(`
74
- `).length<=2e4}function zu(e){return e?.includes("call")?[...e]:["call",...e??[]]}function XT(e,t){let n=new Map;for(let i of t){let r=W(e,i.file).find(a=>a.symbol===i.symbol&&a.isFunctionLike);if(!r)continue;let o={symbol:r.symbol,label:r.leaf,file:r.relativePath,line:r.startLine,endLine:r.endLine},s=n.get(r.symbol);!s||ab(i.source)>ab(s.row.source)?n.set(r.symbol,{row:{...i,...i.callsiteLine===void 0&&s?.row.callsiteLine!==void 0?{callsiteLine:s.row.callsiteLine}:{}},alternative:o}):s.row.callsiteLine===void 0&&i.callsiteLine!==void 0&&n.set(r.symbol,{...s,row:{...s.row,callsiteLine:i.callsiteLine}})}return[...n.values()]}function QT(e){let t=new Map;for(let n of e){let i=Oa(n.alternative.label);t.set(i,(t.get(i)??0)+1)}return t}function yb(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function ab(e){return yb(e)==="exact"?2:1}function To(e,t,n){return e.find(i=>t>=i.line&&t<=i.endLine&&i.text.includes(n))??e.find(i=>t>=i.line&&t<=i.endLine)??null}function lb(e,t,n,i,r){if(i!==void 0)return e.find(s=>s.line===i&&s.calleeLeaf===n&&To(t,s.line,n)!==null)??null;let o=e.filter(s=>s.calleeLeaf===n&&To(t,s.line,s.calleeLeaf)!==null);return r&&o.length===1?o[0]:null}function Po(e){let t=e.attributes.leaf;if(typeof t=="string"&&t.length>0)return Oa(t);let n=e.label.slice(e.label.lastIndexOf(":")+1);return Oa(n)}function Oa(e){return e.replace(/\(\)$/u,"").replace(/^#/u,"")}function qu(e){if(e?.kind!=="symbol"||!e.id.startsWith("symbol:"))return null;try{return decodeURIComponent(e.id.slice(7))}catch{return null}}function Ku(e){return e.location?{symbol:qu(e),label:e.label,file:e.location.file,line:e.location.line,endLine:e.location.endLine??null}:null}function Gu(e,t){let n=Ku(t);return n?.symbol&&W(e,n.file).some(r=>r.symbol===n.symbol&&r.isFunctionLike)?n:null}function Wu(e,t){return e.evidence.find(n=>n.location?.file===t)?.location??e.evidence.find(n=>n.location!==null)?.location??null}function Uu(e){let t={exact:5,derived:4,mixed:3,candidate:2,unknown:1};return e.reduce((n,i)=>t[i.strength]>t[n]?i.strength:n,"unknown")}function ZT(e){let t=new Map;for(let n of e){let r=n.anchor.alternatives[0]?.symbol??`${n.anchor.callsite.file}:${n.anchor.callsite.line}:${n.anchor.callsite.calleeLeaf}`,o=t.get(r);(!o||eF(n,o)<0)&&t.set(r,n)}return[...t.values()]}function eF(e,t){return $a(e.anchor.status)-$a(t.anchor.status)||e.anchor.alternativeCount-t.anchor.alternativeCount||hb(e,t)}function $a(e){return{exact:0,derived:1,mixed:2,candidate:3,unknown:4,ambiguous:5}[e]}function ja(e){let t=new Map;for(let n of e)t.set(n.symbol??`${n.file}:${n.line}`,n);return[...t.values()].sort((n,i)=>n.file.localeCompare(i.file)||n.line-i.line||n.label.localeCompare(i.label))}function cb(e){return`--at ${nF(`${e.file}:${e.line+1}`)}`}function tF(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}function nF(e){return`'${e.replaceAll("'","'\\''")}'`}function ki(e,t,n){return`${e}\0${t}\0${n}`}function ni(e,t,n){return["next-anchor",e,String(t),n].map(encodeURIComponent).join(":")}var wb=6,iF=12,rF=48,oF=2e4,bb=12,Ni=Number.MAX_SAFE_INTEGER,sF=["definition","callers","callees"],Qu={search:12,"exact-source":24,definition:24,caller:8,callee:8,"production-reference":6,"test-reference":2,dependency:6,consumer:6};function aF(e,t){if(t.cursor)throw new Error("Inspect no longer accepts semantic packet cursors. Run the original inspect selectors again.");let n=cF(t),i=mF(e,n),r=i.candidates.sort((M,_)=>Vu(M,_));n.view==="behavior"&&gF(e,r),hF(e,r),n.view==="behavior"&&fF(e,r);let o=Fh(r.map(M=>Yu(M,n.view)),n.evidenceBudgets,(M,_)=>Vu(M.candidate,_.candidate)),{selected:s,omitted:a}=Ra(o.selected,n.maxUnits,n.maxCharacters,(M,_)=>Vu(M.candidate,_.candidate),n.view==="source"),l=s.map(M=>M.candidate),c=[...o.omitted,...a].map(M=>M.candidate),u=l.map(EF),d=Ws(l.map(M=>M.kind==="source"?M.bindingClosure:void 0),l.filter(M=>M.kind==="source").map(M=>({relativePath:M.relativePath,startLine:M.startLine,endLine:M.endLine}))),m=u.reduce((M,_)=>M+(_.kind==="source"?DF(_.source):0),0),f=u.reduce((M,_)=>M+(_.kind==="source"?_.source.length:0),0),p=u.reduce((M,_)=>M+Mb(_,n.view),0),g=u.filter(M=>M.kind==="source"&&(M.roles.includes("search")||M.roles.includes("location"))).map(wF),h=r.filter(M=>M.kind==="source"&&(M.roles.includes("search")||M.roles.includes("location"))).length,b=u.filter(M=>M.kind==="source"&&(M.roles.includes("search")||M.roles.includes("location"))).length,v=i.searches.map(M=>SF(M,r,l)),y=vF(c),I=i.locations.every(M=>M.matched)&&i.evidence.every(M=>M.kind==="matched")&&i.searches.every(M=>xF(M.textCoverage))&&c.every(M=>!M.roles.some(_=>_==="location"||_==="definition")),E=v.reduce((M,_)=>M+_.omittedMatches,0),S=c.length===0&&E===0,x=S?void 0:Db(n,!0),C=yF(n,c),L=lF(S,I,c.length+E,C,v,x),w=r.filter(M=>n.view==="behavior"&&M.kind==="source"&&M.roles.some(_=>_==="location"||_==="definition"||_==="search")).map(M=>({id:`inspect:${M.relativePath}:${M.startLine}-${M.endLine}`,label:M.ownerShort??`${M.relativePath}:${M.startLine+1}`,file:M.relativePath,startLine:M.startLine,endLine:M.endLine})),R=w.length>0?pb(e,w):void 0;return{searches:v,evidence:i.evidence,locations:i.locations,slices:g,candidateSlices:h,omittedSlices:h-b,maxSlices:h,maxTotalLines:m,units:u,candidateUnits:r.length,omittedUnits:c.length,maxUnits:n.maxUnits,maxCharacters:n.maxCharacters,returnedLines:m,returnedCharacters:f,returnedViewCharacters:p,view:n.view,omissionGroups:C,packetCoverage:{mode:S?"complete":"bounded",candidateUnits:r.length,returnedUnits:u.length,omittedUnits:c.length,omittedByRole:y,exactSelectorsComplete:I,maxUnits:n.maxUnits,maxCharacters:n.maxCharacters,channels:CF(r,l,n.evidenceBudgets,n.view),...x?{expansionCommand:x}:{}},stoppingSummary:L,...R&&R.candidateAnchors>0?{causalFrontier:R}:{},bindingClosure:d,continuation:null}}function lF(e,t,n,i,r,o){let s=ft([...i.map(a=>a.drillCommand),...r.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 cF(e){let t=Ju(e.searches),n=Ju(e.symbols),i=Ju(e.locations),r=t.length+n.length+i.length;if(r===0)throw new Error("inspect requires at least one --search, --symbol, or --at selector.");if(r>24)throw new RangeError(`inspect accepts at most ${24} selectors; received ${r}.`);let o=e.evidence??{};if(e.unitLines!==void 0&&ii(e.unitLines,"unitLines"),e.totalLines!==void 0&&ii(e.totalLines,"totalLines"),e.sliceLimit!==void 0&&ii(e.sliceLimit,"sliceLimit"),e.maxCharacters!==void 0&&ii(e.maxCharacters,"maxCharacters"),e.maxUnits!==void 0&&ii(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:i,...e.scope?.trim()?{scope:e.scope.trim()}:{},context:Ib(e.context??wb,"context"),searchLimit:ii(e.searchLimit??(s?Ni:iF),"searchLimit"),maxUnits:ii(s?Ni:e.maxUnits??rF,"maxUnits"),maxCharacters:ii(s?Ni:e.maxCharacters??oF,"maxCharacters"),evidenceBudgets:s?dF():uF(e.evidenceBudgets??Qu),view:e.view??"source",evidence:{...o.parts?{parts:[...o.parts]}:n.length>0?{parts:[...sF]}:{},...o.referenceContext!==void 0?{referenceContext:Ib(o.referenceContext,"referenceContext")}:{},relatedSourceLines:o.relatedSourceLines??60,...o.semantic!==void 0?{semantic:o.semantic}:{}}}}function uF(e){let t={...Qu};for(let[n,i]of Object.entries(e)){if(!(n in t))throw new Error(`Unknown inspect evidence channel: ${n}.`);if(!Number.isSafeInteger(i)||(i??-1)<0)throw new RangeError(`Evidence budget ${n} must be a non-negative safe integer; received ${i}.`);t[n]=i}return t}function dF(){return Object.fromEntries(Object.keys(Qu).map(e=>[e,Ni]))}function mF(e,t){let n=[],i=0,r=t.searches.map(c=>{let u=yu(e,c,{scope:t.scope,context:0,limit:t.searchLimit,ranking:"structural"});return{pattern:c,result:u,matches:u.matches}}),o=Math.max(0,...r.map(c=>c.matches.length));for(let c=0;c<o;c+=1)for(let u of r){let d=u.matches[c];if(!d)continue;let m=Jn(e,d.relativePath,d.focusLine,Ni,t.context);m&&vr(e,n,m,"search",`search:${u.pattern}`,d.ownerSymbol,d.ownerShort,1,i++)}let s=r.map(({pattern:c,result:u})=>{let d=u.omittedMatches>0?Lb(c,t.scope):void 0,m=u.fileCoverage??[],f=RF(c,m,t.scope);return{pattern:c,matchingLines:u.matchingLines,returnedMatches:u.matches.length,omittedMatches:u.omittedMatches,matchingFiles:m.length,returnedFiles:m.filter(p=>p.returnedMatches>0).length,omittedFiles:m.filter(p=>p.returnedMatches===0).length,candidateUnits:0,selectedUnits:0,omittedUnits:0,scopeHints:f.slice(0,bb),omittedScopeHints:Math.max(0,f.length-bb),textCoverage:u.textCoverage,...d?{exactFollowup:d}:{}}}),a=t.locations.map(c=>{let u=LF(c),d=u?dt(e,u.path):null,m=d?Jn(e,d,u.line-1,Ni,t.context):null;return m&&vr(e,n,m,"location",`at:${c}`,null,null,0,i++),{target:c,matched:m!==null}}),l=t.symbols.map(c=>Hu(e,c,t.evidence));for(let c of l)if(c.kind==="matched"){if(c.definition){let u=Jn(e,c.definition.relativePath,c.definition.startLine,Ni,t.context);u&&vr(e,n,u,"definition",`definition:${c.shortName}`,c.symbol,c.shortName,0,i++)}for(let u of c.referenceWindows){let d=u.references[0];vr(e,n,{...u,focusLine:d?.line??u.startLine,unitType:null,unitStartLine:u.startLine,unitEndLine:u.endLine,omittedLines:0},"reference",`reference:${c.shortName}`,d?.enclosingSymbol??null,d?.enclosingShort??null,J(u.relativePath)==="test"?5:4,i++,u.references.map(m=>m.line),c.symbol)}for(let u of c.callers)vb(e,n,u,"caller",c,2,i++);for(let u of c.callees)vb(e,n,u,"callee",c,3,i++);for(let u of c.dependencies)Cb(e,n,"dependency",c.file,u.relativePath,c.symbol,t.context,6,i++);for(let u of c.consumers)Cb(e,n,"consumer",u.relativePath,c.file,c.symbol,t.context,7,i++)}return{searches:s,evidence:l,locations:a,candidates:n}}function Vu(e,t){return e.priority-t.priority||t.roles.length-e.roles.length||t.reasons.length-e.reasons.length||Sb(J(e.relativePath))-Sb(J(t.relativePath))||e.sequence-t.sequence}function Sb(e){switch(e){case"entry":case"source":case"worker":return 0;case"barrel":return 1;case"test":return 2}}function Yu(e,t){return{candidate:e,priority:e.priority,sequence:e.sequence,relativePath:e.relativePath,fileKind:J(e.relativePath),evidenceCharacters:Mb(e,t),roles:e.roles,reasons:e.reasons,symbols:e.symbols,behaviorSignals:e.kind==="source"?e.behavior?.signals??[]:[],channel:Xu(e)}}function Xu(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")?J(e.relativePath)==="test"?"test-reference":"production-reference":t.includes("dependency")?"dependency":t.includes("consumer")?"consumer":"search"}function fF(e,t){let n=t.filter(r=>r.kind==="source"),i=Kr(e,{files:ft(n.map(r=>r.relativePath))});for(let r of n){r.behavior=rr(e,r.relativePath,r.startLine,r.endLine,r.focusLines)??void 0;let o=i.filter(a=>a.source.file===r.relativePath&&a.source.startLine<=r.endLine&&a.source.endLine>=r.startLine),s=o.filter(a=>!pF(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(l=>({name:l.name,value:l.value,evidence:l.evidence})),derivation:{kind:a.derivation.kind,rule:a.derivation.rule,sourceSpans:a.derivation.sourceSpans.length}}));r.runtimeFacts=s.length>0?s:void 0}}function pF(e,t){if(e.strength!=="candidate"||e.protocol!=="http")return!1;let n=e.keyParts.find(r=>r.name==="path")?.value,i=e.keyParts.find(r=>r.name==="method")?.value;return n?t.some(r=>{if(r===e||r.action!==e.action||r.role!==e.role||r.source.startLine!==e.source.startLine||r.derivation.rule!=="http.mount-prefix")return!1;let o=r.keyParts.find(a=>a.name==="path")?.value,s=r.keyParts.find(a=>a.name==="method")?.value;return!!(o&&o!==n&&o.endsWith(n)&&(!i||i===s))}):!1}function gF(e,t){for(let n of t){if(n.kind!=="source")continue;let i=yt(e,n.relativePath,n.startLine,n.endLine,n.focusLines);i.startLine===n.startLine&&i.endLine===n.endLine||(n.startLine=i.startLine,n.endLine=i.endLine,n.source=re(e,n.relativePath).slice(i.startLine,i.endLine+1).join(`
75
- `),n.unitStartLine=i.startLine,n.unitEndLine=i.endLine,n.omittedLines=0)}}function hF(e,t){for(let n of t)n.kind==="source"&&(n.bindingClosure=ir(e,n.relativePath,n.startLine,n.endLine))}function yF(e,t){let n=new Map;for(let i of t){let r=Ha(i.relativePath),o=Xu(i),s=[...i.roles].sort().join(","),a=i.kind==="path"?i.relationship:"",l=`${r}|${o}|${s}|${a}`,c=n.get(l)??[];c.push(i),n.set(l,c)}return[...n.entries()].map(([i,r])=>{let o=r[0],s=ft(r.flatMap(l=>[...l.roles])).sort(),a=ft(r.flatMap(l=>l.kind==="source"?l.behavior?.signals??[]:[])).sort();return{id:`g-${Eb("sha256").update(i).digest("hex").slice(0,8)}`,scope:Ha(o.relativePath),channel:Xu(o),roles:s,behaviorSignals:a,candidateUnits:r.length,sourceCharacters:r.reduce((l,c)=>l+(c.kind==="source"?c.source.length:0),0),anchors:r.map(l=>({relativePath:l.relativePath,line:l.kind==="source"?l.focusLine:0,ownerShort:l.kind==="source"?l.ownerShort:null,roles:[...l.roles],behaviorSignals:l.kind==="source"?[...l.behavior?.signals??[]]:[]})),drillCommand:bF(e,r)}}).sort((i,r)=>r.candidateUnits-i.candidateUnits||r.sourceCharacters-i.sourceCharacters||i.scope.localeCompare(r.scope)||i.id.localeCompare(r.id))}function bF(e,t){let n=ft(t.flatMap(o=>o.reasons.filter(s=>s.startsWith("search:")).map(s=>s.slice(7)))),i=Ha(t[0].relativePath);if(n.length>0&&t.every(o=>o.kind==="source"&&o.roles.includes("search"))){let o=["codebaseiq inspect"];for(let s of n)o.push(`--search ${$t(s)}`);return o.push(`--scope ${$t(i)}`,"--full"),e.view==="behavior"&&o.push("--view behavior"),o.join(" ")}let r=t.filter(o=>o.kind==="source");if(r.length>0&&r.length<=24){let o=["codebaseiq inspect"];for(let s of r)o.push(`--at ${$t(`${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:Db(e,!0)}function SF(e,t,n){let i=`search:${e.pattern}`,r=t.filter(a=>a.reasons.includes(i)).length,o=new Set(n),s=t.filter(a=>a.reasons.includes(i)&&o.has(a)).length;return{...e,candidateUnits:r,selectedUnits:s,omittedUnits:r-s}}function vF(e){let t={};for(let n of e)for(let i of n.roles)t[i]=(t[i]??0)+1;return t}function CF(e,t,n,i){let r=e.map(s=>Yu(s,i).channel),o=t.map(s=>Yu(s,i).channel);return Object.fromEntries(Object.keys(n).map(s=>{let a=r.filter(c=>c===s).length,l=o.filter(c=>c===s).length;return[s,{candidateUnits:a,returnedUnits:l,omittedUnits:a-l,maxUnits:n[s]}]}))}function xF(e){return!!(e&&e.skippedUnreadablePaths.length===0&&e.skippedOversizedPaths.length===0)}function RF(e,t,n){let i=new Map;for(let r of t){let o=Ha(r.relativePath),s=i.get(o)??{matchingLines:0,returnedMatches:0};s.matchingLines+=r.matchingLines,s.returnedMatches+=r.returnedMatches,i.set(o,s)}return[...i.entries()].map(([r,o])=>({scope:r,...o,exactFollowup:Lb(e,r||n)})).sort((r,o)=>o.matchingLines-r.matchingLines||o.returnedMatches-r.returnedMatches||r.scope.localeCompare(o.scope))}function Ha(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}function Lb(e,t){return`codebaseiq inspect --search ${$t(e)}${t?` --scope ${$t(t)}`:""} --full`}function Db(e,t){let n=["codebaseiq inspect"];for(let i of e.searches)n.push(`--search ${$t(i)}`);for(let i of e.symbols)n.push(`--symbol ${$t(i)}`);for(let i of e.locations)n.push(`--at ${$t(i)}`);return e.scope&&n.push(`--scope ${$t(e.scope)}`),e.context!==wb&&n.push(`--context ${e.context}`),e.evidence.parts&&n.push(`--include ${$t(e.evidence.parts.join(","))}`),t&&n.push("--full"),e.view==="behavior"&&n.push("--view behavior"),n.join(" ")}function vb(e,t,n,i,r,o,s){vr(e,t,{...n,unitType:null,unitStartLine:n.startLine,unitEndLine:n.endLine+n.omittedLines},i,`${i}:${r.shortName}`,n.symbol,n.shortName,o,s,[n.focusLine],r.symbol)}function Cb(e,t,n,i,r,o,s,a,l){let c=`${i} -> ${r}`,u=Ce(e,i).filter(h=>h.sourcePath===r),d=re(e,i),m=IF(d,u,r),f=m===null?null:ia(e,i,m,Math.min(s,4));if(f){vr(e,t,{...f,unitType:null,unitStartLine:f.startLine,unitEndLine:f.endLine,omittedLines:0},n,`${n}:${c}`,null,null,a,l,[f.focusLine],o);return}let p=`codebaseiq inspect --search ${$t(Pb(r))} --scope ${$t(i)}`,g=t.find(h=>h.kind==="path"&&h.relativePath===i&&h.relationship===c);if(g){g.roles=ft([...g.roles,n]),g.reasons=ft([...g.reasons,`${n}:${c}`]),g.symbols=ft([...g.symbols,o]),g.priority=Math.min(g.priority,a);return}t.push({kind:"path",roles:[n],relativePath:i,relationship:c,reasons:[`${n}:${c}`],symbols:[o],exactFollowup:p,priority:a,sequence:l})}function IF(e,t,n){let i=ft(t.flatMap(l=>[l.importedName,l.localName??""]).filter(l=>l.length>1)),r=Pb(n).replace(/\.[^.]+$/u,""),o=ft([...i,r]).filter(Boolean),s=/\b(?:from|import|include|require|use)\b/u,a=e.findIndex(l=>s.test(l)&&o.some(c=>l.includes(c)));return a>=0?a:null}function vr(e,t,n,i,r,o,s,a,l,c=[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),f=Math.max(d.endLine,n.endLine);d.startLine=m,d.endLine=f,d.source=re(e,n.relativePath).slice(m,f+1).join(`
76
- `),d.focusLine=Math.min(d.focusLine,n.focusLine),d.focusLines=Rb([...d.focusLines,...c]),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=ft([...d.reasons,r]),d.roles=ft([...d.roles,i]),d.symbols=ft([...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:[r],focusLines:Rb(c),ownerSymbol:o,ownerShort:s,roles:[i],symbols:u?[u]:[],priority:a,sequence:l})}function EF(e){if(e.kind==="path"){let{priority:o,sequence:s,...a}=e;return{...a,id:xb(a)}}let{priority:t,sequence:n,bindingClosure:i,...r}=e;return{...r,id:xb(r),omittedCharacters:0}}function wF(e){let{kind:t,id:n,roles:i,symbols:r,omittedCharacters:o,behavior:s,runtimeFacts:a,...l}=e;return l}function xb(e){return Eb("sha256").update(JSON.stringify(e)).digest("hex").slice(0,16)}function LF(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 Ju(e){return ft((e??[]).map(t=>t.trim()).filter(Boolean))}function ft(e){return[...new Set(e)]}function Rb(e){return ft(e).sort((t,n)=>t-n)}function DF(e){return e.length===0?0:e.split(`
77
- `).length}function Mb(e,t){if(e.kind==="path")return e.relationship.length+e.exactFollowup.length;let n="bindingClosure"in e?bp(e.bindingClosure):0,i=(e.runtimeFacts??[]).reduce((r,o)=>r+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((r,o)=>r+o.text.length+o.signals.join(",").length+12,0)+e.behavior.testCases.reduce((r,o)=>r+o.length+2,0)+i+n:e.source.length+n+i}function Pb(e){return e.split("/").at(-1)??e}function $t(e){return`'${e.replaceAll("'","'\\''")}'`}function ii(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new RangeError(`${t} must be a positive safe integer; received ${e}`);return e}function Ib(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 MF}from"path";function PF(e,t){let n=t.className,i=at(e,n);return i.match?i.total>1?{kind:"ambiguous",query:n,total:i.total,candidates:[Tb(i.match),...i.candidates]}:{kind:"matched",query:n,owner:FF(i.match),methods:TF(e,i.match)}:{kind:"missing",query:n,suggestions:_s(e,n,5)}}function TF(e,t){let n=Y(t.symbol),r=new U(e).definitionsForFile(t.relativePath).filter(l=>st(l.symbol)),o=r.filter(l=>l.parentTypeName===n||l.symbol.includes(n)),a=(o.length>0?o:kF(MF(t.relativePath))===n?r.filter(l=>l.symbol.includes("<invalid-global-code>")):[]).map(l=>({startLine:l.startLine,endLine:l.endLine,name:Y(l.symbol)}));return ye(t.relativePath)!=="clojure"?a:AF(a,NF(e,t))}function Tb(e){return{symbol:e.symbol,shortName:A(e.symbol),relativePath:e.relativePath,startLine:e.startLine}}function FF(e){return{...Tb(e),endLine:e.endLine}}function kF(e){return e.replace(/\.[^.]+$/,"")}function NF(e,t){let n=Y(t.symbol);return n?(te(e,t.relativePath)?.clojureMembers??[]).filter(i=>i.ownerName===n).map(i=>({startLine:i.startLine,endLine:i.endLine,name:i.memberName})):[]}function AF(e,t){let n=new Map;for(let i of[...e,...t])n.set(`${i.name}:${i.startLine}:${i.endLine}`,i);return[...n.values()].sort((i,r)=>i.startLine-r.startLine||i.endLine-r.endLine)}import{createHash as EN}from"crypto";var Fb=["call","contract-symbol","import","reference","runtime-boundary"],_F={call:[{family:"control",subtype:"call"}],"contract-symbol":[{family:"contract",subtype:"uses-contract-symbol"}],import:[{family:"identity",subtype:"imports"}],reference:[{family:"identity",subtype:"references"}]},BF={"structural-membership":[{family:"identity",subtype:"contains"}],"boundary-observation":[{family:"identity",subtype:"owns-runtime-observation"}],"external-import":[{family:"identity",subtype:"imports-external"}]};function kb(e){if(e.kind!=="runtime-boundary")return Nb(_F[e.kind]);let t=e.fromBoundaryParticipant?.protocol??e.toBoundaryParticipant?.protocol,n={crossesRuntimeBoundary:!0,...t?{protocol:t}:{},...e.runtimeBoundaryKey?{runtimeKey:e.runtimeBoundaryKey}:{}},i=[{family:"control",subtype:"runtime-handoff",context:n}];return e.evidence==="runtime-boundary:carrier.discriminator"&&(i.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}:{}}}),i.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"&&i.push({family:"temporal",subtype:"enqueue-before-consume",context:{...n},attributes:{producerAction:e.fromBoundaryParticipant.action,consumerAction:e.toBoundaryParticipant.action,retryPolicy:"unknown"}}),i}function Ua(e){return Nb(BF[e])}function Nb(e){return e.map(t=>({...t,...t.context?{context:{...t.context}}:{},...t.attributes?{attributes:{...t.attributes}}:{}}))}import{join as ck}from"path";import{createRequire as OF}from"module";import{resolve as ko}from"path";var $F=OF(import.meta.url),Fo;function _b(e,t,n){let i=jF();if(!i)return Zu("The TypeScript compiler runtime is unavailable.");let r=HF(i,e,t),o=r.getSourceFile(ko(t))??r.getSourceFile(t);if(!o)return Zu(`The TypeScript compiler did not materialize ${t}.`);let s={ts:i,sourceFile:o,checker:r.getTypeChecker(),points:new Map,edges:new Map,unsupported:new Set,nextCfgId:0},a=zF(i,o,n);if(a.length===0)return Zu("No function-like construct intersects the selected source range.");let l=new Map(a.map(d=>[d,qF(o,d)])),c=a.map(d=>GF(s,d,KF(i,d,l),l.get(d)));for(let d of c)WF(s,d),XF(s,d),ek(s,d);nk(s,c);let u=[...s.unsupported].sort();return{points:[...s.points.values()].map(({node:d,...m})=>m).sort(lk),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 jF(){if(Fo!==void 0)return Fo;try{Fo=$F("typescript")}catch{Fo=$s()?.ts??null}return Fo}function HF(e,t,n){let i=ko(n),r={target:e.ScriptTarget.ESNext,module:e.ModuleKind.NodeNext,moduleResolution:e.ModuleResolutionKind.NodeNext,skipLibCheck:!0,noResolve:!0},o=e.createSourceFile(i,t,r.target,!0,UF(e,i)),s=e.createCompilerHost(r,!0),a=s.getSourceFile.bind(s),l=s.readFile.bind(s),c=s.fileExists.bind(s);return s.getSourceFile=(u,d,m,f)=>ko(u)===i?o:a(u,d,m,f),s.readFile=u=>ko(u)===i?t:l(u),s.fileExists=u=>ko(u)===i||c(u),e.createProgram([i],r,s)}function UF(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 zF(e,t,n){let i=[],r=o=>{if(Bb(e,o)){let s=t.getLineAndCharacterOfPosition(o.getStart(t)).line,a=t.getLineAndCharacterOfPosition(o.getEnd()).line;(!n||s<=n.endLine&&a>=n.startLine)&&i.push(o)}o.forEachChild(r)};return t.forEachChild(r),i.sort((o,s)=>o.getStart(t)-s.getStart(t))}function Bb(e,t){return e.isFunctionLike(t)&&"body"in t&&t.body!==void 0}function qF(e,t){return`callable:${encodeURIComponent(e.fileName)}:${t.getStart(e)}:${t.getEnd()}`}function KF(e,t,n){for(let i=t.parent;i;i=i.parent)if(Bb(e,i)&&n.has(i))return n.get(i);return null}function GF(e,t,n,i){let r=new Map,o=et(e,r,"exit",null),s=t.body,a=o.id;if(s&&e.ts.isBlock(s))a=ed(e,r,[...s.statements],o.id,{breakTarget:null,continueTarget:null});else if(s){let c=et(e,r,"statement",s);Be(r,c.id,o.id),a=c.id}let l=et(e,r,"entry",t);return Be(r,l.id,a),{id:i,node:t,parentId:n,cfg:r,entryId:l.id,exitId:o.id}}function ed(e,t,n,i,r){let o=i;for(let s=n.length-1;s>=0;s-=1)o=Ai(e,t,n[s],o,r);return o}function Ai(e,t,n,i,r){let o=e.ts;if(o.isBlock(n))return ed(e,t,[...n.statements],i,r);if(o.isIfStatement(n)){let a=et(e,t,"predicate",n.expression),l=Ai(e,t,n.thenStatement,i,r),c=n.elseStatement?Ai(e,t,n.elseStatement,i,r):i;return Be(t,a.id,l),Be(t,a.id,c),a.id}if(o.isWhileStatement(n)){let a=et(e,t,"predicate",n.expression),l=Ai(e,t,n.statement,a.id,{breakTarget:i,continueTarget:a.id});return Be(t,a.id,l),Be(t,a.id,i),a.id}if(o.isDoStatement(n)){let a=et(e,t,"predicate",n.expression),l=Ai(e,t,n.statement,a.id,{breakTarget:i,continueTarget:a.id});return Be(t,a.id,l),Be(t,a.id,i),l}if(o.isForStatement(n)){let a=et(e,t,"predicate",n.condition??n),l=n.incrementor?et(e,t,"statement",n.incrementor):null;l&&Be(t,l.id,a.id);let c=l?.id??a.id,u=Ai(e,t,n.statement,c,{breakTarget:i,continueTarget:c});if(Be(t,a.id,u),n.condition&&Be(t,a.id,i),!n.initializer)return a.id;let d=et(e,t,"statement",n.initializer);return Be(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=et(e,t,"predicate",n.expression),l=et(e,t,"statement",n.initializer),c=Ai(e,t,n.statement,a.id,{breakTarget:i,continueTarget:a.id});return Be(t,a.id,l.id),Be(t,a.id,i),Be(t,l.id,c),a.id}if(o.isSwitchStatement(n)){e.unsupported.add("switch fallthrough is represented conservatively; discriminant-to-case value refinement is unsupported.");let a=et(e,t,"predicate",n.expression),l=i,c=[];for(let u=n.caseBlock.clauses.length-1;u>=0;u-=1){let d=n.caseBlock.clauses[u];l=ed(e,t,[...d.statements],l,{...r,breakTarget:i}),c.push(l)}for(let u of c)Be(t,a.id,u);return Be(t,a.id,i),a.id}if(o.isReturnStatement(n)||o.isThrowStatement(n)){let a=et(e,t,"statement",n),l=[...t.values()].find(c=>c.kind==="exit");return Be(t,a.id,l.id),a.id}if(o.isBreakStatement(n)){let a=et(e,t,"statement",n);return r.breakTarget||e.unsupported.add("A break statement could not be attached to a structured target."),Be(t,a.id,r.breakTarget??i),a.id}if(o.isContinueStatement(n)){let a=et(e,t,"statement",n);return r.continueTarget||e.unsupported.add("A continue statement could not be attached to a structured target."),Be(t,a.id,r.continueTarget??i),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=et(e,t,"statement",n);return a.invalidatesAllDefinitions=!0,Be(t,a.id,i),a.id}let s=et(e,t,"statement",n);return Be(t,s.id,i),s.id}function et(e,t,n,i){let r={id:`cfg:${e.nextCfgId++}`,kind:n,ast:i,successors:new Set,predecessors:new Set,definitions:[],uses:[],displayPoint:null,invalidatesAllDefinitions:!1};return t.set(r.id,r),r}function Be(e,t,n){e.get(t).successors.add(n),e.get(n).predecessors.add(t)}function WF(e,t){let n=t.cfg.get(t.entryId);for(let i of t.node.parameters){let r=_i(e,i.name);if(!r){e.unsupported.add("Destructured parameter definition-use is not implemented.");continue}n.definitions.push({point:Bi(e,r.node,"parameter-definition",r.symbolKey,r.name,t.id),rhsUseIds:[]})}for(let i of t.cfg.values())!i.ast||i.kind==="entry"||i.kind==="exit"||(i.kind==="predicate"&&(i.displayPoint=Bi(e,i.ast,"predicate",null,"predicate",t.id)),VF(e,t,i,i.ast),!i.displayPoint&&i.definitions.length===0&&i.uses.length===0&&(i.displayPoint=Bi(e,i.ast,"statement",null,rk(e,i.ast),t.id)))}function VF(e,t,n,i){let r=e.ts;if(r.isTryStatement(i))return;let o=s=>{if(!(s!==i&&r.isFunctionLike(s))){if(r.isVariableDeclaration(s)){let a=s.initializer?za(e,t.id,s.initializer,n):[];n.uses.push(...a);let l=_i(e,s.name);l?n.definitions.push({point:Bi(e,l.node,"definition",l.symbolKey,l.name,t.id),rhsUseIds:a.map(c=>c.point.id)}):(n.invalidatesAllDefinitions=!0,e.unsupported.add("Destructured variable reaching definitions are not implemented."));return}if(r.isBinaryExpression(s)&&jb(r,s.operatorToken.kind)){let a=za(e,t.id,s.right,n);s.operatorToken.kind!==r.SyntaxKind.EqualsToken&&a.push(...za(e,t.id,s.left,n)),n.uses.push(...a);let l=_i(e,s.left);l?n.definitions.push({point:Bi(e,l.node,"definition",l.symbolKey,l.name,t.id),rhsUseIds:a.map(c=>c.point.id)}):(n.invalidatesAllDefinitions=!0,e.unsupported.add("Dynamic or destructured assignment targets are not included in reaching definitions."));return}if((r.isPrefixUnaryExpression(s)||r.isPostfixUnaryExpression(s))&&(s.operator===r.SyntaxKind.PlusPlusToken||s.operator===r.SyntaxKind.MinusMinusToken)){let a=za(e,t.id,s.operand,n);n.uses.push(...a);let l=_i(e,s.operand);l&&n.definitions.push({point:Bi(e,l.node,"definition",l.symbolKey,l.name,t.id),rhsUseIds:a.map(c=>c.point.id)});return}if(!(r.isFunctionDeclaration(s)||r.isClassDeclaration(s)||r.isInterfaceDeclaration(s))){if(Ob(e,s)){let a=$b(e,t.id,s);a&&n.uses.push(a),r.isPropertyAccessExpression(s)&&o(s.expression);return}s.forEachChild(o)}}};o(i),n.uses=Hb(n.uses)}function za(e,t,n,i){let r=[],o=s=>{if(!e.ts.isFunctionLike(s)){if(e.ts.isBinaryExpression(s)&&jb(e.ts,s.operatorToken.kind)){i.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(Ob(e,s)){let a=$b(e,t,s);a&&r.push(a),e.ts.isPropertyAccessExpression(s)&&o(s.expression);return}s.forEachChild(o)}};return o(n),Hb(r)}function Ob(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&&JF(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)||YF(e.ts,t))}function JF(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 YF(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 $b(e,t,n){let i=_i(e,n);return i?{point:Bi(e,i.node,"use",i.symbolKey,i.name,t),property:e.ts.isPropertyAccessExpression(n)}:null}function _i(e,t){let n=e.ts;if(n.isIdentifier(t)){let i=Ab(e,t);return i?{node:t,symbolKey:i,name:t.text}:null}if(n.isPropertyAccessExpression(t)){let i=Ab(e,t.name);return i?{node:t,symbolKey:i,name:t.getText(e.sourceFile)}:null}return n.isParenthesizedExpression(t)||n.isAsExpression(t)||n.isTypeAssertionExpression(t)||n.isNonNullExpression(t)?_i(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 Ab(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 i=n.valueDeclaration??n.declarations?.[0];return i?`symbol:${encodeURIComponent(i.getSourceFile().fileName)}:${i.getStart()}:${n.getName()}`:`symbol:${n.getName()}`}function Bi(e,t,n,i,r,o){let s=t.getStart(e.sourceFile),a=t.getEnd(),l=e.sourceFile.getLineAndCharacterOfPosition(s),c=`flow-point:${encodeURIComponent(e.sourceFile.fileName)}:${s}:${a}:${n}:${encodeURIComponent(i??r)}`,u=e.points.get(c);if(u)return u;let d={id:c,kind:n,name:r,symbolKey:i,callableId:o,start:s,end:a,line:l.line,column:l.character,node:t};return e.points.set(c,d),d}function XF(e,t){let n=[...t.cfg.values()].flatMap(l=>l.definitions),i=new Map(n.map(l=>[l.point.id,l])),r=QF(n),o=new Map,s=new Map;for(let l of t.cfg.values())o.set(l.id,new Set),s.set(l.id,new Set);let a=!0;for(;a;){a=!1;for(let l of t.cfg.values()){let c=sk([...l.predecessors].map(m=>s.get(m))),u=new Set(c);l.invalidatesAllDefinitions&&u.clear();let d=ZF(l.definitions);for(let m of d){for(let f of r.get(m.point.symbolKey)??[])u.delete(f.point.id);u.add(m.point.id)}td(o.get(l.id),c)||(o.set(l.id,c),a=!0),td(s.get(l.id),u)||(s.set(l.id,u),a=!0)}}for(let l of t.cfg.values()){let c=o.get(l.id);for(let u of l.uses){let d=l.definitions.filter(f=>f.point.symbolKey===u.point.symbolKey&&f.point.start<u.point.start&&!f.rhsUseIds.includes(u.point.id)).sort((f,p)=>p.point.start-f.point.start)[0],m=d?[d.point.id]:c;for(let f of m){let p=i.get(f);p.point.symbolKey===u.point.symbolKey&&No(e,"reaching-definition",p.point.id,u.point.id,"exact","A CFG path reaches this use without an intervening definition.")}}for(let u of l.definitions)for(let d of u.rhsUseIds)No(e,"value-source",d,u.point.id,"exact","This right-hand-side use supplies the new definition.")}}function QF(e){let t=new Map;for(let n of e){if(!n.point.symbolKey)continue;let i=t.get(n.point.symbolKey)??[];i.push(n),t.set(n.point.symbolKey,i)}return t}function ZF(e){let t=new Map;for(let n of e)n.point.symbolKey&&t.set(n.point.symbolKey,n);return[...t.values()]}function ek(e,t){let n=tk(t);for(let i of t.cfg.values()){if(i.successors.size<2||!i.displayPoint)continue;let r=n.get(i.id);for(let o of i.successors)for(let s of n.get(o)??[]){if(r.has(s)||s===t.exitId)continue;let a=t.cfg.get(s),l=[...a.definitions.map(c=>c.point),...a.uses.map(c=>c.point),...a.displayPoint?[a.displayPoint]:[]];for(let c of ok(l))No(e,"control-dependence",i.displayPoint.id,c.id,"exact","The target postdominates a branch successor but does not postdominate the predicate.")}}}function tk(e){let t=[...e.cfg.keys()],n=new Set(t),i=new Map;for(let o of t)i.set(o,o===e.exitId?new Set([o]):new Set(n));let r=!0;for(;r;){r=!1;for(let o of e.cfg.values()){if(o.id===e.exitId)continue;let s=[...o.successors].map(l=>i.get(l)),a=new Set([o.id,...ak(s)]);td(i.get(o.id),a)||(i.set(o.id,a),r=!0)}}return i}function nk(e,t){let n=new Map(t.map(s=>[s.id,s.parentId])),i=t.flatMap(s=>[...s.cfg.values()].flatMap(a=>a.definitions.map(l=>l.point))),r=new Map;for(let s of i){if(!s.symbolKey)continue;let a=r.get(s.symbolKey)??[];a.push(s),r.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(l=>l.uses)){if(!a.point.symbolKey||o.has(a.point.id))continue;let l=r.get(a.point.symbolKey)??[];for(let c of l)ik(c.callableId,a.point.callableId,n)?No(e,"closure-capture",c.id,a.point.id,"candidate","Compiler identity proves the captured binding, but invocation order can select among outer definitions."):a.property&&No(e,"field-definition-to-use",c.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 ik(e,t,n){for(let i=n.get(t)??null;i;i=n.get(i)??null)if(i===e)return!0;return!1}function No(e,t,n,i,r,o){let s=`local-flow-edge:${t}:${encodeURIComponent(n)}:${encodeURIComponent(i)}`;e.edges.set(s,{id:s,kind:t,fromPointId:n,toPointId:i,strength:r,reason:o})}function jb(e,t){return t>=e.SyntaxKind.FirstAssignment&&t<=e.SyntaxKind.LastAssignment}function rk(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 Hb(e){return[...new Map(e.map(t=>[t.point.id,t])).values()]}function ok(e){return[...new Map(e.map(t=>[t.id,t])).values()]}function sk(e){return new Set(e.flatMap(t=>[...t]))}function ak(e){return e.length===0?new Set:new Set([...e[0]].filter(t=>e.slice(1).every(n=>n.has(t))))}function td(e,t){return e.size===t.size&&[...e].every(n=>t.has(n))}function lk(e,t){return e.start-t.start||e.kind.localeCompare(t.kind)||e.id.localeCompare(t.id)}function Zu(e){return{points:[],edges:[],coverage:{status:"unsupported",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:[e]}}}var uk=Hn("typescript-local-flow",{clearGroups:["whole-project","source-file","semantic-provider"]});function nd(e,t,n,i){if(!Gn(t))return null;let r=`${t}\0${n}\0${i}`;return uk.get(e,r,()=>{let o=se(e,t);return o?_b(o,ck(e.config.projectRoot,t),{startLine:n,endLine:i}):{points:[],edges:[],coverage:{status:"unsupported",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:[`Current source is unavailable for ${t}.`]}}})}function dk(e,t=new Map){let n=new Map,i=new Map,r=[];for(let o of e.transfers){if(!e.caller)continue;let s=qa(e.caller,o.callerPosition),a=qa(e.callee,o.calleePosition);Ao(n,s),Ao(n,a),rd(i,e.caller,s),rd(i,e.callee,a);let l=pt("edge","data-transfer",o.proof.file,String(o.proof.startLine),String(o.callerPosition),String(o.calleePosition));i.set(l,{id:l,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=qa(e.callee,o.calleePosition);Ao(n,a),rd(i,e.callee,a);let l=t.get(o.calleePosition);if(l&&xk(l)){Ck(i,n,e,o.calleePosition,o.argumentText,l);return}let c=Sk(e,o.calleePosition,o.argumentText);Ao(n,c);let u=pt("edge","data-transfer-unsupported",o.proof.file,String(o.proof.startLine),String(o.calleePosition),String(s));i.set(u,{id:u,kind:"data-transfer",fromNodeId:c.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}}]}),r.push({id:pt("frontier","data-transfer",u),kind:"data-transfer",direction:"unresolved",fromNodeIds:[c.id],edgeIds:[u],memberNodeIds:[a.id],memberCount:1,disposition:"unsupported",reason:l?.derivation.rule??o.reason,expansion:null})}),{nodes:[...n.values()],edges:[...i.values()],frontiers:r,blindSpots:[]}}function zb(e,t,n=[]){let i=qb(),r=new Map,o=new Set;for(let s of t){if(s.kind!=="call"||!s.fromSymbol||!s.toSymbol||s.line===null)continue;let a=bk(r,e,s.toFile,s.toSymbol);if(!a)continue;let l=Zf(e,a),c=l.sites.filter(g=>g.file===s.fromFile&&g.startLine<=s.line&&g.endLine>=s.line&&g.caller?.symbol===s.fromSymbol);if(c.length!==1){let g=l.unresolved.find(h=>h.file===s.fromFile&&h.line===s.line);g&&i.blindSpots.push(`Parameter flow unresolved at ${s.fromFile}:${s.line+1}: ${g.reason}.`);continue}let u=c[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=ep(e,u),f=ae(e,u.file)?.rootNode,p=new Map;if(f)for(let g of m.unknown){let h=Qf({db:e,file:u.file,root:f},u.arguments[g.calleePosition]);h&&p.set(g.calleePosition,h)}Ub(i,dk(m,p)),m.caller&&hk(u.callNode)&&yk(i,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,l=nd(e,s.location.file,s.location.line,a);if(l){Ub(i,mk(s,l.points,l.edges));for(let c of l.coverage.unsupported)i.blindSpots.push(`TypeScript local flow is partial for ${s.location.file}:${s.location.line+1}-${a+1}: ${c} Recover with: codebaseiq inspect --at '${s.location.file}:${s.location.line+1}-${a+1}' --view behavior.`)}}return i.blindSpots=[...new Set(i.blindSpots)].sort(),i}function mk(e,t,n){let i=qb(),r=new Map,o=new Map,s=new Map,a=e.location.file;for(let l of t){let c=fk(e,a,l);s.set(l.id,c.id),r.set(c.id,c),pk(o,e,c)}for(let l of n){let c=s.get(l.fromPointId),u=s.get(l.toPointId);if(!c||!u)continue;let d=gk(l),m=pt("edge","typescript-local-flow",a,l.id);o.set(m,{id:m,kind:l.kind==="control-dependence"?"control-dependence":"data-transfer",fromNodeId:c,toNodeId:u,directed:!0,disposition:"folded",semantics:[d],evidence:[{method:"typescript-compiler-cfg-reaching-definitions",strength:l.strength,identity:l.reason,location:r.get(c)?.location??e.location}]})}return i.nodes=[...r.values()],i.edges=[...o.values()],i}function fk(e,t,n){return{id:pt("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 pk(e,t,n){let i=pt("edge","local-flow-owner",t.id,n.id);e.has(i)||e.set(i,{id:i,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 gk(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 hk(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 yk(e,t,n){if(!t.caller)return;let i={id:pt("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}},r=pt("edge","return-to-call-result",t.callee.symbol,i.id),o=pt("edge","call-result-owner",t.caller.symbol,i.id);e.nodes.push(i),e.edges.push({id:r,kind:"data-transfer",fromNodeId:od(t.callee.symbol),toNodeId:i.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:i.location}]},{id:o,kind:"call-result-owner",fromNodeId:od(t.caller.symbol),toNodeId:i.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:i.location}]})}function qb(){return{nodes:[],edges:[],frontiers:[],blindSpots:[]}}function Ub(e,t){id(e.nodes,t.nodes),id(e.edges,t.edges),id(e.frontiers,t.frontiers),e.blindSpots.push(...t.blindSpots)}function id(e,t){let n=new Set(e.map(i=>i.id));for(let i of t)n.has(i.id)||(n.add(i.id),e.push(i))}function bk(e,t,n,i){let r=`${n}\0${i}`,o=e.get(r);if(o!==void 0)return o;let s=W(t,n).find(a=>a.symbol===i)??null;return e.set(r,s),s}function qa(e,t){return{id:Ek(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 Sk(e,t,n){return{id:pt("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 vk(e,t,n){return{id:pt("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 Ck(e,t,n,i,r,o){let s=vk(n,i,o),a=qa(n.callee,i);Ao(t,s);let l=pt("edge","static-value-transfer",n.call.file,String(n.call.startLine),String(i));e.set(l,{id:l,kind:"data-transfer",fromNodeId:s.id,toNodeId:a.id,directed:!0,disposition:"folded",semantics:[{family:"data",subtype:Rk(o),attributes:{argumentText:r,calleePosition:i,value:o.value,precision:o.precision,derivationRule:o.derivation.rule}}],evidence:Ik(o,n)})}function xk(e){return e.derivation.kind!=="heuristic"&&e.precision!=="symbolic"&&e.precision!=="unknown"}function Rk(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 Ik(e,t){return(e.derivation.sourceSpans.length>0?e.derivation.sourceSpans:[t.call]).map(i=>({method:`static-value:${e.derivation.rule}`,strength:e.derivation.kind==="direct"?"exact":"derived",identity:e.derivation.inputFactIds.join(",")||e.value,location:{file:i.file,line:i.startLine,endLine:i.endLine}}))}function Ao(e,t){e.has(t.id)||e.set(t.id,t)}function rd(e,t,n){let i=pt("edge","parameter-owner",t.symbol,n.id);e.has(i)||e.set(i,{id:i,kind:"parameter-owner",fromNodeId:od(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 Ek(e,t){return pt("parameter",e,String(t))}function od(e){return pt("symbol",e)}function pt(...e){return e.map(t=>encodeURIComponent(t)).join(":")}function Kb(e,t){let n=new Map,i=new Map,r=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,l=Ep(e,s.location.file,s.location.line,a);if(!l){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 c of l.facts){let u=sd(s,c.controller),d=sd(s,c.outcome);n.set(u.id,u),n.set(d.id,d),wk(i,s,u);let m=Oi("edge","control-dependence",u.id,d.id,c.subtype);i.set(m,{id:m,kind:"control-dependence",fromNodeId:u.id,toNodeId:d.id,directed:!0,disposition:"folded",semantics:[{family:"control",subtype:c.subtype,attributes:{...c.attributes}}],evidence:[{method:"parser-control-dependence",strength:"exact",identity:`${s.location.file}:${c.controller.startLine+1}-${c.outcome.startLine+1}`,location:{file:s.location.file,line:c.controller.startLine,endLine:c.controller.endLine}}]})}for(let c of l.terminals){let u=sd(s,c);n.set(u.id,u);let d=c.label.startsWith("throw")||c.label.startsWith("raise")?"throw":"return",m=Oi("edge","control-terminal",s.id,u.id,d);i.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:c.label,location:{file:s.location.file,line:c.startLine,endLine:c.endLine}}]})}for(let c of l.unsupported){let u=Oi("control-unsupported",s.location.file,String(c.startLine),String(c.endLine),c.reason);n.set(u,{id:u,kind:"control-unsupported",label:c.reason,disposition:"unsupported",location:{file:s.location.file,line:c.startLine,endLine:c.endLine},anchorIds:[],attributes:{ownerNodeId:s.id}});let d=Oi("edge","control-unsupported",s.id,u);i.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:c.reason,location:{file:s.location.file,line:c.startLine,endLine:c.endLine}}]});let m=Oi("frontier","control-dependence",u);r.set(m,{id:m,kind:"control-dependence",direction:"unresolved",fromNodeIds:[s.id],edgeIds:[d],memberNodeIds:[u],memberCount:1,disposition:"unsupported",reason:c.reason,expansion:null})}}return{nodes:[...n.values()],edges:[...i.values()],frontiers:[...r.values()],blindSpots:[...o].sort()}}function sd(e,t){let n=e.location.file;return{id:Oi(`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 wk(e,t,n){let i=Oi("edge","control-owner",t.id,n.id);e.has(i)||e.set(i,{id:i,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 Oi(...e){return e.map(t=>encodeURIComponent(t)).join(":")}var Ka=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"]),Bo=new Set(["block","body","compound_statement","declaration_list","statement_block"]),Lk=new Set(["assignment","assignment_expression","augmented_assignment_expression"]),ld=new Set(["update_expression"]),Jb=new Set(["array_access","element_access_expression","subscript_expression"]),Yb=new Set(["attribute","field_access","field_expression","member_access_expression","member_expression","selector_expression"]),Dk=new Set(["false","null","null_literal","number","number_literal","string","string_literal","template_string","true"]),Mk=new Set(["call_expression","method_invocation","object_creation_expression"]),Pk=new Set(["comment","else_clause","formal_parameters","parameters","type_parameters"]);function Xb(e,t,n,i){let r=ae(e,t);if(!r)return null;let o=Ok(r.rootNode,n,i);if(!o)return null;let s=[],a=[],l=[];return $i(o,c=>{if(Lk.has(c.type)||ld.has(c.type)||Zb(c)){let u=Tk(c);u?s.push(u):l.push({family:"state",startLine:c.startPosition.row,endLine:c.endPosition.row,reason:`Mutation target ${mn(c.text)} could not be resolved to an exact source resource.`})}}),$i(o,c=>{if(!Bo.has(c.type))return;let u=_k(c);for(let d=0;d<u.length-1;d+=1)a.push({from:_o(u[d]),to:_o(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],f=jk(m).filter(p=>p.type==="await_expression");for(let p of f){let g=Oo("event",`await ${mn(p.text.replace(/^await\s+/u,""))}`,p);a.push({from:_o(m),to:g,subtype:"awaits-completion",synchronizationScope:null,attributes:{completionRequired:!0}});let h=u[d+1];h&&a.push({from:g,to:_o(h),subtype:"await-completion-before",synchronizationScope:null,attributes:{continuationOnly:!0}})}}}),$i(o,c=>{if(c.type!=="synchronized_statement")return;let u=c.childForFieldName("object")??c.childForFieldName("condition")??c.namedChildren.find(g=>!Bo.has(g.type)),d=c.childForFieldName("body")??c.namedChildren.find(g=>Bo.has(g.type));if(!u||!d){l.push({family:"temporal",startLine:c.startPosition.row,endLine:c.endPosition.row,reason:"Synchronized scope has no structurally resolved monitor or body."});return}let m=mn(u.text).replace(/^\(|\)$/gu,""),f=Oo("lock",m,u),p=$k(d).filter(g=>g.parent!==null&&eS(g));for(let g of Bk(p))a.push({from:f,to:_o(g),subtype:"inside-lock-scope",synchronizationScope:m,attributes:{syntaxNative:!0}})}),{mutations:s,temporal:a,unsupported:l}}function Tk(e){let t=Zb(e),n=e.childForFieldName("left")??e.childForFieldName("argument")??(t?e.namedChildren.at(-1)??null:e.namedChildren[0]??null);if(!n)return null;let i=Fk(n);if(!i)return null;let r=t?"delete":ld.has(e.type)||!Ak(e,n).startsWith("=")?"update":"assign",o=t||ld.has(e.type)?null:e.childForFieldName("right");return{event:Oo("event",mn(e.text),e),resource:{kind:"resource",label:i.name,startLine:n.startPosition.row,endLine:n.endPosition.row},operation:r,durabilityClass:"in-memory",recordIdentity:i.recordIdentity,value:o?Oo("value",mn(o.text),o):null,dataSubtype:o?kk(o,e):null}}function Fk(e){if(Jb.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:`${mn(t.text)}[]`,recordIdentity:mn(n.text)}}return Yb.has(e.type)?{name:mn(e.text),recordIdentity:null}:/^(?:identifier|property_identifier|field_identifier)$/u.test(e.type)?{name:mn(e.text),recordIdentity:null}:null}function kk(e,t){return Dk.has(e.type)||/(?:integer|float|decimal|boolean|character)_literal$/u.test(e.type)?"constant-to-state":Mk.has(e.type)?"return-to-state":Yb.has(e.type)||Jb.has(e.type)?"property-to-state":/identifier$/u.test(e.type)?Nk(e.text,t)?"captured-value-to-state":"value-to-state":"expression-to-state"}function Nk(e,t){let n=ad(t.parent);if(!n||Gb(n,e))return!1;let i=ad(n.parent);for(;i;){if(Gb(i,e))return!0;i=ad(i.parent)}return!1}function ad(e){let t=e;for(;t;){if(Ka.has(t.type))return t;t=t.parent}return null}function Gb(e,t){let n=e.childForFieldName("parameters")??e.namedChildren.find(o=>["formal_parameters","parameters"].includes(o.type));if(n&&Wb(n,t))return!0;let i=e.childForFieldName("body")??e.namedChildren.find(o=>Bo.has(o.type));if(!i)return!1;let r=!1;return Qb(i,e,o=>{if(r||!/(?:declarator|declaration|parameter)$/u.test(o.type))return;let s=o.childForFieldName("name")??o.childForFieldName("pattern")??o.namedChildren[0];s&&Wb(s,t)&&(r=!0)}),r}function Wb(e,t){let n=!1;return $i(e,i=>{/identifier$/u.test(i.type)&&i.text===t&&(n=!0)}),n}function Qb(e,t,n){n(e);for(let i of e.namedChildren)i!==t&&Ka.has(i.type)||Qb(i,t,n)}function Ak(e,t){let n=e.childForFieldName("right"),i=Math.max(0,t.endIndex-e.startIndex),r=n?Math.max(i,n.startIndex-e.startIndex):e.text.length;return e.text.slice(i,r).trim()}function Zb(e){return(e.type==="delete_expression"||e.type==="unary_expression")&&/^delete\b/u.test(e.text.trim())}function _k(e){return e.namedChildren.filter(t=>eS(t))}function eS(e){return Pk.has(e.type)||Bo.has(e.type)?!1:/(?:statement|declaration)$/u.test(e.type)||e.type==="expression_statement"||e.type==="local_variable_declaration"}function Bk(e){let t=new Set(e);return e.filter(n=>{let i=n.parent;for(;i;){if(t.has(i))return!1;i=i.parent}return!0})}function _o(e){return Oo("event",mn(e.text),e)}function Oo(e,t,n){return{kind:e,label:t,startLine:n.startPosition.row,endLine:n.endPosition.row}}function Ok(e,t,n){let i=[];return $i(e,o=>{o.startPosition.row<=t&&o.endPosition.row>=n&&i.push(o)}),i.filter(o=>Ka.has(o.type)).sort(Vb)[0]??i.sort(Vb)[0]??null}function Vb(e,t){return e.endIndex-e.startIndex-(t.endIndex-t.startIndex)||e.startIndex-t.startIndex}function $k(e){let t=[];return $i(e,n=>t.push(n)),t}function jk(e){let t=[],n=i=>{t.push(i);for(let r of i.namedChildren)r!==e&&Ka.has(r.type)||n(r)};return n(e),t}function $i(e,t){t(e);for(let n of e.namedChildren)$i(n,t)}function mn(e){return e.trim().replace(/\s+/gu," ")}function iS(e,t,n=[]){let i=new Map,r=new Map,o=new Map,s=new Set;for(let a of t){if(!a.location||!["source-construct","symbol"].includes(a.kind))continue;let l=a.location.endLine??a.location.line,c=Xb(e,a.location.file,a.location.line,l);if(!c){s.add(`State and temporal analysis unavailable for ${a.location.file}:${a.location.line+1}-${l+1}: no supported syntax tree or covering construct.`);continue}for(let u of c.mutations){let d=Wa(a,u.event),m=Gk(a,u.resource,u.durabilityClass);if(i.set(d.id,d),i.set(m.id,m),Va(r,a,d,"contains-state-effect"),Ja(r,{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 f=Wa(a,u.value);i.set(f.id,f),Ja(r,{kind:"data-to-state",from:f,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 c.temporal){let d=Wa(a,u.from),m=Wa(a,u.to);i.set(d.id,d),i.set(m.id,m),Va(r,a,d,u.from.kind==="lock"?"contains-lock-scope":"contains-event"),Va(r,a,m,"contains-event"),Ja(r,{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 c.unsupported){let d=kn(`${u.family}-unsupported`,a.location.file,String(u.startLine),String(u.endLine),u.reason);i.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=kn("edge",`${u.family}-unsupported`,a.id,d);r.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 f=kn("frontier",u.family,d);o.set(f,{id:f,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(l=>l.kind==="runtime-boundary-participant")){let l=Ga(a,"protocol"),c=Ga(a,"action"),u=Ga(a,"address")??a.label;!l||!c||!nS(l,c)||tS(i,r,a,{observationId:a.id,action:c,strength:"exact",file:a.location?.file??"",line:a.location?.line??0,address:u,protocol:l,role:Ga(a,"role")??void 0,resolution:"locally-linked"})}for(let a of n){if(!a.protocol||!nS(a.protocol,a.action))continue;let l=qk(t,a.file,a.line,a.ownerShortName??null);if(!l){s.add(`State observation ${a.observationId} at ${a.file}:${a.line+1} has no materialized owner node.`);continue}tS(i,r,l,a)}return{nodes:[...i.values()],edges:[...r.values()],frontiers:[...o.values()],blindSpots:[...s].sort()}}function tS(e,t,n,i){let r=Uk(i),s={id:kn("runtime-state-event",i.observationId),kind:"runtime-state-event",label:`${i.action} ${r}`,disposition:"folded",location:{file:i.file,line:i.line},anchorIds:[],attributes:{action:i.action,protocol:i.protocol??null,modality:i.modality??null,resolution:i.resolution??null}},a=i.protocol==="database"?"external-durable-intent":"external",l={id:kn("runtime-state-resource",i.protocol??"unknown",r),kind:"runtime-state-resource",label:r,disposition:"folded",location:{file:i.file,line:i.line},anchorIds:[],attributes:{protocol:i.protocol??null,durabilityClass:a}};e.set(s.id,s),e.set(l.id,l),Va(t,n,s,"contains-runtime-state-effect");let c=Hk(i.action);Ja(t,{kind:"runtime-state-resource",from:s,to:l,semantics:[{family:"state",subtype:c,context:{crossesRuntimeBoundary:!0,protocol:i.protocol},attributes:{operation:i.action,durabilityClass:a,resource:r,recordIdentity:zk(i),modality:i.modality??null,resolution:i.resolution??null,transactionMembership:"unknown",commitState:i.protocol==="database"?"unknown":null}}],method:`runtime-boundary-${i.strength}`,identity:i.observationId})}function Hk(e){return e==="database.read"?"reads-resource":e==="queue.send"?"enqueues-resource":e==="queue.consume"?"consumes-resource":"writes-resource"}function Uk(e){return(e.keyParts?.find(n=>["address","resource"].includes(n.name))?.value??e.address)||e.observationId}function zk(e){return e.keyParts?.find(n=>/^(?:id|key|record)$/u.test(n.name))?.value??null}function nS(e,t){return e==="database"&&["database.read","database.write"].includes(t)||e==="queue"&&["queue.consume","queue.send"].includes(t)}function Ga(e,t){let n=e.attributes[t];return typeof n=="string"?n:null}function qk(e,t,n,i){let r=e.filter(s=>s.location?.file===t&&["source-construct","symbol"].includes(s.kind)),o=r.filter(s=>s.location.line<=n&&(s.location.endLine??s.location.line)>=n).sort(Kk)[0];if(o)return o;if(i){let s=r.find(a=>a.label===i||a.label.endsWith(`.${i}`)||a.label.includes(i));if(s)return s}return r.length===1?r[0]:null}function Kk(e,t){let n=(e.location?.endLine??e.location?.line??0)-(e.location?.line??0),i=(t.location?.endLine??t.location?.line??0)-(t.location?.line??0);return n-i}function Wa(e,t){let n=e.location.file;return{id:kn(`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 Gk(e,t,n){let i=e.location.file;return{id:kn("program-resource",i,e.id,t.label,n),kind:"program-resource",label:t.label,disposition:"folded",location:{file:i,line:t.startLine,endLine:t.endLine},anchorIds:[],attributes:{ownerNodeId:e.id,durabilityClass:n}}}function Va(e,t,n,i){let r=kn("edge","program-owner",t.id,n.id,i);e.has(r)||e.set(r,{id:r,kind:"program-owner",fromNodeId:t.id,toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:i}],evidence:[{method:"parser-program-owner",strength:"exact",identity:t.id,location:n.location}]})}function Ja(e,t){let n=kn("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 kn(...e){return e.map(t=>encodeURIComponent(t)).join(":")}var Wk=new Set(["control","data","state","temporal"]),Ya=new Set(["contains-control","contains-event","contains-lock-scope","contains-state-effect","contains-runtime-state-effect","contains","owns-parameter","owns-runtime-observation"]),aS=new Set(["discriminator-dispatch","result-callback","returns","runtime-handoff","throws"]);function lS(e,t={}){let n=new Map(e.nodes.map(C=>[C.id,C])),i=e0(e.nodes,t.focusLocations),r=t0(e.edges,t.focusLocations),o=n0(e.edges,r),s=new Set(e.paths.flatMap(C=>C.edgeIds)),a=Nn(e.anchors.filter(C=>C.status==="matched").flatMap(C=>C.nodeIds)),c=e.edges.filter(sS).filter(C=>Vk(C,i,r,s)),u=c.filter(C=>Qk(C,i,r,o,n,s)),d=rS(a,u,"forward"),m=Xk(d,u),f=rS(m,u,"backward"),p=new Set([...d].filter(C=>f.has(C)));for(let C of a)p.add(C);let g=new Set(u.filter(C=>p.has(C.fromNodeId)&&p.has(C.toNodeId)).map(C=>C.id)),h=new Set(p),b=new Set(g);Jk(c,h,b,i,r);let v=e.frontiers.filter(C=>r0(C,h)),y=Nn(v.filter(C=>C.disposition==="unsupported").map(C=>C.id)),I=Nn(e.edges.filter(C=>!sS(C)&&uS(C)&&i0(C,h)).map(C=>C.id)),E=Nn(v.map(C=>C.id)),S=[];a.length===0&&S.push("No matched anchor node starts the corridor."),m.length===0&&S.push("No proved mechanical outcome is reachable from a matched anchor."),y.length>0&&S.push(`${y.length} unsupported frontier(s) touch the protected corridor.`),I.length>0&&S.push(`${I.length} candidate or unknown edge(s) touch the protected corridor.`);let x=S.length===0?"complete":"incomplete";return{schemaVersion:1,status:x,startNodeIds:a,outcomeNodeIds:m,baseNodeIds:Nn([...p]),baseEdgeIds:Nn([...g]),nodeIds:Nn([...h]),edgeIds:Nn([...b]),accountedFrontierIds:E,unresolvedFrontierIds:y,unresolvedEdgeIds:I,coverage:{protectedNodes:h.size,protectedEdges:b.size,baseNodes:p.size,baseEdges:g.size,accountedFrontiers:E.length,unresolvedFrontiers:y.length,unresolvedEdges:I.length},explanation:x==="complete"?"Every proved anchor-to-outcome path is closed over its material causal facts within reported coverage.":S.join(" ")}}function Vk(e,t,n,i){return t===null||e.disposition==="emitted"||i.has(e.id)||n?.has(e.id)===!0?!0:(e.semantics??[]).some(r=>{if(r.family==="identity"&&Ya.has(r.subtype))return t.has(e.toNodeId);if(r.family==="contract")return t.has(e.fromNodeId)&&t.has(e.toNodeId);if(r.family==="state")return t.has(e.fromNodeId);if(r.family==="data"||r.family==="temporal")return t.has(e.fromNodeId)||t.has(e.toNodeId);if(r.family==="control"){if(dS(r))return t.has(e.fromNodeId);if(["returns","throws"].includes(r.subtype))return t.has(e.toNodeId);if(r.subtype==="completion-callback")return t.has(e.fromNodeId)||t.has(e.toNodeId)}return!1})}function Jk(e,t,n,i,r){let o=!0;for(;o;){o=!1;for(let s of e)Yk(s,t,i,r)&&(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 Yk(e,t,n,i){let r=t.has(e.fromNodeId),o=t.has(e.toNodeId);return!r&&!o?!1:(e.semantics??[]).some(s=>s.family==="identity"?Ya.has(s.subtype)&&(o||n===null||n.has(e.toNodeId)):s.family==="contract"?!0:s.family==="state"?r&&(n===null||n.has(e.fromNodeId)):s.family==="temporal"?s.subtype==="lexical-successor"?r&&o:!0:s.family==="data"?o&&(r||n===null||n.has(e.fromNodeId)||i?.has(e.id)===!0):s.family==="control"?cS(s)||["returns","throws"].includes(s.subtype)&&!o&&n!==null&&!n.has(e.toNodeId)?!1:aS.has(s.subtype)||dS(s)||s.subtype==="completion-callback":!1)}function Xk(e,t){let n=new Set,i=new Map,r=new Map;for(let o of t)!e.has(o.fromNodeId)||!e.has(o.toNodeId)||(i.set(o.fromNodeId,(i.get(o.fromNodeId)??0)+1),r.set(o.toNodeId,(r.get(o.toNodeId)??0)+1),(o.semantics??[]).some(s=>s.family==="state"||s.family==="control"&&aS.has(s.subtype))&&n.add(o.toNodeId));for(let o of e)(r.get(o)??0)>0&&(i.get(o)??0)===0&&n.add(o);return Nn([...n])}function rS(e,t,n){let i=new Map;for(let s of t){let a=n==="forward"?s.fromNodeId:s.toNodeId,l=n==="forward"?s.toNodeId:s.fromNodeId,c=i.get(a)??[];c.push(l),i.set(a,c)}let r=new Set(e),o=[...e];for(;o.length>0;){let s=o.shift();for(let a of i.get(s)??[])r.has(a)||(r.add(a),o.push(a))}return r}function Qk(e,t,n,i,r,o){return(e.semantics??[]).some(s=>e.disposition==="emitted"||o.has(e.id)?!0:s.family==="identity"&&Ya.has(s.subtype)?t===null||t.has(e.toNodeId)||i?.has(e.toNodeId)===!0:!Wk.has(s.family)||cS(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"?Zk(e,r)&&(t.has(e.fromNodeId)||t.has(e.toNodeId)):!1)}function cS(e){return e.family==="control"&&["call","discriminator-dispatch","result-callback","runtime-handoff"].includes(e.subtype)}function Zk(e,t){let n=t.get(e.fromNodeId),i=t.get(e.toNodeId);if(!n||!i)return!1;let r=oS(n,"ownerNodeId")??(n.kind==="symbol"?n.id:null),o=oS(i,"ownerNodeId")??(i.kind==="symbol"?i.id:null);return r!==null&&r===o}function e0(e,t){if(!t)return null;let n=new Map;for(let i of t){let r=n.get(i.file)??[];r.push(i.line),n.set(i.file,r)}return new Set(e.filter(i=>{if(!i.location||i.kind==="parameter")return!1;let r=n.get(i.location.file)??[],o=i.location.endLine??i.location.line;return r.some(s=>s>=i.location.line&&s<=o)}).map(i=>i.id))}function t0(e,t){if(!t)return null;let n=new Map;for(let i of t){let r=n.get(i.file)??[];r.push(i.line),n.set(i.file,r)}return new Set(e.filter(i=>i.evidence.some(r=>{if(!r.location)return!1;let o=n.get(r.location.file)??[],s=r.location.endLine??r.location.line;return o.some(a=>a>=r.location.line&&a<=s)})).map(i=>i.id))}function n0(e,t){return t===null?null:new Set(e.filter(n=>t.has(n.id)).flatMap(n=>[n.fromNodeId,n.toNodeId]))}function oS(e,t){let n=e.attributes[t];return typeof n=="string"?n:null}function sS(e){return e.disposition==="excluded"||e.disposition==="unsupported"||!uS(e)?!1:e.evidence.some(t=>t.strength==="exact"||t.strength==="derived")}function uS(e){return(e.semantics??[]).some(t=>t.family!=="identity"||Ya.has(t.subtype))}function dS(e){return e.subtype.startsWith("predicate-")||e.subtype.startsWith("loop-")||e.subtype.startsWith("exception-")||e.subtype.startsWith("finally-")||e.subtype.startsWith("handler-")}function i0(e,t){return t.has(e.fromNodeId)||t.has(e.toNodeId)}function r0(e,t){return[...e.fromNodeIds,...e.memberNodeIds].some(n=>t.has(n))}function Nn(e){return[...new Set(e)].sort()}import{createHash as o0}from"crypto";var Xa=["identity","contract","control","data","state","temporal"],s0=new Set(Xa);function Za(e){let t=xr(e.anchors,"anchor"),n=xr(e.nodes,"node"),i=xr(e.edges,"edge"),r=xr(e.paths??[],"path"),o=xr(e.frontiers??[],"frontier"),s=new Set(t.map(f=>f.id)),a=new Set(n.map(f=>f.id)),l=new Set(i.map(f=>f.id)),c=e.routeCatalog?{...e.routeCatalog,routes:xr(e.routeCatalog.routes,"route"),selectedRouteIds:bt(e.routeCatalog.selectedRouteIds)}:void 0;for(let f of t)It(`anchor ${f.id}`,[...f.nodeIds,...f.candidateNodeIds],a,"node");for(let f of n)It(`node ${f.id}`,f.anchorIds,s,"anchor");for(let f of i){if(It(`edge ${f.id}`,[f.fromNodeId,f.toNodeId],a,"node"),f.evidence.length===0)throw new Error(`Exploration edge ${f.id} has no evidence source.`);c0(f)}for(let f of r)It(`path ${f.id}`,[f.fromAnchorId,f.toAnchorId],s,"anchor"),It(`path ${f.id}`,f.nodeIds,a,"node"),It(`path ${f.id}`,f.edgeIds,l,"edge");for(let f of o)if(It(`frontier ${f.id}`,f.fromNodeIds,a,"node"),It(`frontier ${f.id}`,f.edgeIds,l,"edge"),It(`frontier ${f.id}`,f.memberNodeIds,a,"node"),f.memberCount!==f.memberNodeIds.length)throw new Error(`Exploration frontier ${f.id} reports ${f.memberCount} member(s) but identifies ${f.memberNodeIds.length}.`);for(let f of c?.routes??[])It(`route ${f.id}`,f.nodeIds,a,"node"),It(`route ${f.id}`,f.edgeIds,l,"edge"),It(`route ${f.id}`,[f.anchorNodeId,f.endpointNodeId],a,"node");c&&It("route catalog selection",c.selectedRouteIds,new Set(c.routes.map(f=>f.id)),"route");let u=bt(e.incompleteReasons??[]),d=u.length===0?"accounted":"incomplete",m=t.reduce((f,p)=>f+p.omittedCandidates,0);return{schemaVersion:1,anchors:t,nodes:n,edges:i,paths:r,frontiers:o,coverage:{status:d,scope:e.scope,nodes:vS(n),edges:vS(i),matchedAnchors:t.filter(f=>f.status==="matched").length,ambiguousAnchors:t.filter(f=>f.status==="ambiguous").length,missingAnchors:t.filter(f=>f.status==="missing").length,omittedCandidates:m,frontierGroups:o.length,programEdges:l0(i),blindSpots:bt(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:m0(d,r,e.scope),...c?{routeCatalog:c}:{}}}function a0(e){return e.flatMap(t=>u0(t.semantics??[]).map(n=>({id:d0(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 l0(e){let t=a0(e),n=new Set(t.map(s=>s.sourceEdgeId)),i=new Map(Xa.map(s=>[s,new Set])),r=new Map(Xa.map(s=>[s,new Set])),o=new Map(Xa.map(s=>[s,0]));for(let s of t)i.get(s.family).add(s.sourceEdgeId),r.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:bt(e.filter(s=>!n.has(s.id)).map(s=>s.kind)),families:{identity:Cr("identity",i,o,r),contract:Cr("contract",i,o,r),control:Cr("control",i,o,r),data:Cr("data",i,o,r),state:Cr("state",i,o,r),temporal:Cr("temporal",i,o,r)}}}function Cr(e,t,n,i){return{sourceEdges:t.get(e)?.size??0,projectedEdges:n.get(e)??0,subtypes:[...i.get(e)??[]].sort()}}function c0(e){let t=new Set;for(let n of e.semantics??[]){if(!s0.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 i=cd(n);if(t.has(i))throw new Error(`Exploration edge ${e.id} repeats program edge semantic ${i}.`);t.add(i)}}function u0(e){return[...e].sort((t,n)=>cd(t).localeCompare(cd(n)))}function cd(e){return`${e.family}:${e.subtype}`}function d0(e,t){return`program:${encodeURIComponent(e)}:${t.family}:${encodeURIComponent(t.subtype)}`}function m0(e,t,n){return e==="incomplete"||t.some(i=>i.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 CS(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 i=new Set(e.anchors.flatMap(w=>[...w.nodeIds,...w.candidateNodeIds])),r=[],o=e.anchors.filter(w=>w.status!=="missing"&&w.nodeIds.length+w.candidateNodeIds.length>0);for(let w=0;w<o.length;w+=1)for(let R=w+1;R<o.length;R+=1){let M=o[w],_=o[R],D=hS(e,M,_,!1),k=D??hS(e,M,_,!0);k?(k.nodeIds.forEach(V=>i.add(V)),r.push({id:Qa("path",M.id,_.id),fromAnchorId:M.id,toAnchorId:_.id,status:!D||M.status==="ambiguous"||_.status==="ambiguous"?"candidate":"connected",nodeIds:k.nodeIds,edgeIds:k.edgeIds})):r.push({id:Qa("path",M.id,_.id),fromAnchorId:M.id,toAnchorId:_.id,status:"partial",nodeIds:[],edgeIds:[]})}let s=bt(t.routeIds??[]),a=f0(e,s),l=new Set(a.routes.map(w=>w.id)),c=s.filter(w=>!l.has(w));if(c.length>0)throw new Error(`Unknown exploration route id(s): ${c.join(", ")}`);let d=a.routes.filter(w=>s.includes(w.id)).map(w=>({anchorNodeId:w.anchorNodeId,endpointNodeId:w.endpointNodeId,endpointKind:w.endpointKind,endpointPriority:2,nodeIds:[...w.nodeIds].reverse(),edgeIds:[...w.edgeIds].reverse()}));for(let w of d)w.nodeIds.forEach(R=>i.add(R));let m=r.length===0||r.some(w=>w.edgeIds.length>0);m&&bS(e,i,n);let f=SS(e,i),p=new Set(t.expandedFrontierIds??[]),g=new Set(f.map(w=>w.id)),h=[...p].filter(w=>!g.has(w)).sort();if(h.length>0)throw new Error(`Unknown exploration frontier id(s): ${h.join(", ")}`);for(let w of f)p.has(w.id)&&w.memberNodeIds.forEach(R=>i.add(R));m&&bS(e,i,n);let b=new Map(d.map(w=>[w.endpointNodeId,w.endpointKind])),v=new Set(d.flatMap(w=>w.nodeIds)),y=new Map;for(let w of d)for(let R=0;R<w.nodeIds.length;R+=1){let M=w.nodeIds[R],_=R;y.set(M,Math.max(y.get(M)??0,_))}let I=e.nodes.map(w=>{let R=b.get(w.id),M=v.has(w.id)?{upstreamCausalPath:!0,upstreamCausalDistance:y.get(w.id)??0,...R?{upstreamCausalEndpoint:R}:{}}:{};return{...w,attributes:{...w.attributes,...M},disposition:w.disposition==="excluded"||w.disposition==="unsupported"?w.disposition:i.has(w.id)?"emitted":"folded"}}),E=new Set([...r.flatMap(w=>w.edgeIds),...d.flatMap(w=>w.edgeIds)]),S=e.edges.map(w=>({...w,disposition:w.disposition==="excluded"||w.disposition==="unsupported"?w.disposition:E.has(w.id)||i.has(w.fromNodeId)&&i.has(w.toNodeId)?"emitted":"folded"})),x=Za({anchors:e.anchors,nodes:I,edges:S,paths:r,frontiers:[...e.frontiers.filter(w=>w.disposition!=="folded"),...SS({...e,nodes:I,edges:S},i)],scope:e.coverage.scope,blindSpots:e.coverage.blindSpots,incompleteReasons:e.coverage.status==="incomplete"?[e.coverage.explanation]:[],routeCatalog:a}),C=new Set(x.frontiers.flatMap(w=>w.edgeIds)),L=x.edges.filter(w=>w.disposition==="folded"&&!C.has(w.id)).map(w=>w.id);if(L.length>0)throw new Error(`Folded exploration edge(s) are not frontier-accounted: ${L.sort().join(", ")}`);return x}var mS=10;function f0(e,t=[]){let n=new Map(e.nodes.map(h=>[h.id,h])),i=new Map(e.edges.map(h=>[h.id,h])),r=new Map;for(let h of e.edges){if(!p0(h))continue;let b=r.get(h.toNodeId)??[];b.push(h),r.set(h.toNodeId,b)}for(let h of r.values())h.sort((b,v)=>Number($o(v))-Number($o(b))||gS(v)-gS(b)||b.fromNodeId.localeCompare(v.fromNodeId)||b.id.localeCompare(v.id));let o=bt(e.anchors.filter(h=>h.status==="matched").flatMap(h=>h.nodeIds)),s=new Map,a=new Set,l=(h,b,v)=>{let y=b.nodeIds[b.nodeIds.length-1],I=n.get(y),E=n.get(h);if(!I?.location||!E)return;let S=[...b.nodeIds].reverse(),x=[...b.edgeIds].reverse(),C=new Set(S),L=x.flatMap(D=>{let P=i.get(D);return P?[P]:[]}),w=e.edges.filter(D=>D.disposition!=="excluded"&&D.disposition!=="unsupported"&&(C.has(D.fromNodeId)||C.has(D.toNodeId))),R={id:Qa("route",h,y,v,...x),status:"proved",anchorNodeId:h,anchorLabel:E.label,endpointNodeId:y,endpointLabel:I.label,endpointLocation:{...I.location},endpointKind:v,nodeIds:S,edgeIds:x,evidenceStrengths:bt(L.flatMap(D=>D.evidence.map(P=>P.strength))),spineEdgeFamilies:fS(L,!0),relatedEdgeFamilies:fS(w,!1),crossesRuntimeBoundary:L.some($o)},M=`${h}\0${y}\0${v}`,_=s.get(M);(!_||pS(R,_)<0)&&s.set(M,R)};for(let h of o){n.get(h)?.attributes.publicEntry===!0&&l(h,{nodeIds:[h],edgeIds:[]},"public-entry");let b=[{nodeIds:[h],edgeIds:[]}],v=new Map([[h,0]]);for(let y=0;y<b.length;y+=1){let I=b[y],E=I.nodeIds[I.nodeIds.length-1];I.edgeIds.length>0&&n.get(E)?.location&&n.get(E)?.attributes.publicEntry===!0&&l(h,I,"public-entry");let S=r.get(E)??[];if(I.edgeIds.length>=mS){S.some(x=>!I.nodeIds.includes(x.fromNodeId))&&a.add(h);continue}for(let x of S){if(I.nodeIds.includes(x.fromNodeId))continue;let C=I.edgeIds.length+1,L=v.get(x.fromNodeId);if(L!==void 0&&L<=C)continue;let w={nodeIds:[...I.nodeIds,x.fromNodeId],edgeIds:[...I.edgeIds,x.id]};if(v.set(x.fromNodeId,C),$o(x)&&n.get(x.fromNodeId)?.location){l(h,w,"runtime-boundary");continue}b.push(w)}}}let c=[...s.values()].sort(pS),u=new Set(c.map(h=>h.id)),d=bt(t.filter(h=>u.has(h))),m=bt(c.map(h=>h.anchorNodeId)),f=o.filter(h=>!m.includes(h)),p=[...a].sort(),g=e.coverage.status==="accounted"&&p.length===0?"accounted":"incomplete";return{schemaVersion:1,routes:c,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:mS,anchorNodeIds:o,anchorsWithRoutes:m,anchorsWithoutRoutes:f,depthLimitedAnchorNodeIds:p,routeCount:c.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 fS(e,t){let n=e.flatMap(i=>i.semantics?.map(r=>r.family)??[]);return t&&e.length>0&&n.length===0&&n.push("control"),bt(n)}function pS(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 p0(e){return e.disposition!=="excluded"&&e.disposition!=="unsupported"&&g0(e)&&e.evidence.some(t=>["exact","derived","mixed"].includes(t.strength))}function g0(e){return $o(e)||e.kind==="boundary-observation"||e.kind==="call"||e.kind==="compiler:call"}function $o(e){return e.kind==="runtime-boundary"||e.kind.startsWith("runtime:")}function gS(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 hS(e,t,n,i){return yS(e,t,n,i)??yS(e,n,t,i)}function yS(e,t,n,i){let r=[...t.nodeIds,...t.candidateNodeIds].sort(),o=new Set([...n.nodeIds,...n.candidateNodeIds]);if(r.some(u=>o.has(u)))return{nodeIds:[r.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))&&!i||h0(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 l=r.map(u=>({nodeId:u,nodeIds:[u],edgeIds:[]})),c=new Set(r);for(let u=0;u<l.length;u+=1){let d=l[u];for(let m of a.get(d.nodeId)??[]){if(c.has(m.nodeId))continue;let f={nodeId:m.nodeId,nodeIds:[...d.nodeIds,m.nodeId],edgeIds:[...d.edgeIds,m.edgeId]};if(o.has(m.nodeId))return f;c.add(m.nodeId),l.push(f)}}return null}function h0(e,t,n,i){let r=e.get(t)??[];r.push({nodeId:n,edgeId:i}),e.set(t,r)}function y0(e,t,n){let i=new Map;for(let a of e.edges){let l=i.get(a.fromNodeId)??{incoming:0,outgoing:0},c=i.get(a.toNodeId)??{incoming:0,outgoing:0};l.outgoing+=1,c.incoming+=1,i.set(a.fromNodeId,l),i.set(a.toNodeId,c)}let r=new Set,o=new Map;for(let a of e.edges){let l=t.has(a.fromNodeId),c=t.has(a.toNodeId);if(l===c)continue;let u=l?a.toNodeId:a.fromNodeId,d=l?a.fromNodeId:a.toNodeId,m=e.nodes.find(g=>g.id===u);if(m?.kind==="structural-region")continue;let f=o.get(u)??new Set;f.add(d),o.set(u,f),(/(?:runtime-boundary|external)/u.test(a.kind)||m&&/(?:frontier|external)/u.test(m.kind))&&r.add(u)}let s=[...o].filter(([a,l])=>{if(r.has(a))return!0;let c=i.get(a)??{incoming:0,outgoing:0};return(c.incoming>1||c.outgoing>1)&&l.size>1}).sort(([a,l],[c,u])=>Number(r.has(c))-Number(r.has(a))||u.size-l.size||a.localeCompare(c)).map(([a])=>a);for(let a of s){if(t.size>=n)break;t.add(a)}}function bS(e,t,n){let i=-1;for(;t.size!==i&&t.size<n;)i=t.size,y0(e,t,n)}function SS(e,t){let n=new Set(e.nodes.filter(s=>!t.has(s.id)&&s.disposition!=="excluded"&&s.disposition!=="unsupported").map(s=>s.id)),i=new Map;for(let s of e.edges){if(!n.has(s.fromNodeId)||!n.has(s.toNodeId))continue;let a=i.get(s.fromNodeId)??new Set,l=i.get(s.toNodeId)??new Set;a.add(s.toNodeId),l.add(s.fromNodeId),i.set(s.fromNodeId,a),i.set(s.toNodeId,l)}let r=[],o=new Set;for(let s of[...n].sort()){if(o.has(s))continue;let a=[],l=[s];o.add(s);for(let c=0;c<l.length;c+=1){let u=l[c];a.push(u);for(let d of[...i.get(u)??[]].sort())o.has(d)||(o.add(d),l.push(d))}r.push(a.sort())}return r.map(s=>{let a=new Set(s),l=e.edges.filter(p=>a.has(p.fromNodeId)||a.has(p.toNodeId)),c=l.filter(p=>a.has(p.fromNodeId)!==a.has(p.toNodeId)),u=bt(c.map(p=>a.has(p.fromNodeId)?p.toNodeId:p.fromNodeId)),d=new Set(c.map(p=>a.has(p.toNodeId)?"outgoing":"incoming")),m=bt(l.map(p=>p.id)),f=bt(c.map(p=>p.kind));return{id:Qa("frontier",...s,...m),kind:f.join("+")||"disconnected",direction:d.size===1?[...d][0]:"undirected",fromNodeIds:u,edgeIds:m,memberNodeIds:s,memberCount:s.length,disposition:"folded",reason:c.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 Qa(e,...t){let n=o0("sha256").update(t.join("\0")).digest("hex").slice(0,16);return`${e}:${n}`}function xr(e,t){let n=[...e].sort((i,r)=>i.id.localeCompare(r.id));for(let i=1;i<n.length;i+=1)if(n[i-1].id===n[i].id)throw new Error(`Duplicate exploration ${t} id: ${n[i].id}`);return n}function It(e,t,n,i){let r=bt(t.filter(o=>!n.has(o)));if(r.length>0)throw new Error(`Exploration ${e} references missing ${i}(s): ${r.join(", ")}`)}function vS(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 bt(e){return[...new Set(e)].sort()}var b0=5,S0=12,v0=8,C0=3,xS=8,x0=6,R0=12,RS=12,I0=12,E0=2,w0=new Set(["branch","loop","call","await","return","throw","mutation","catch","finally"]),L0=9e3,IS=Fb;function D0(e,t){return NS(e,t,"full")}function kS(e,t){return NS(e,t,"topology")}function NS(e,t,n){let i=nl(t.searches??[]),r=nl(t.symbols??[]),o=nl(t.relations&&t.relations.length>0?t.relations:IS),s=o.filter(F=>!IS.includes(F));if(s.length>0)throw new Error(`Unsupported system-map relation kind(s): ${s.join(", ")}`);let a=new Set(o),l=t.evidenceFloor??"derived";if(l!=="exact"&&l!=="derived")throw new Error(`Unsupported system-map evidence floor: ${l}`);let c=nl(t.sourceScopes&&t.sourceScopes.length>0?t.sourceScopes:["production"]),u=["production","test","fixture","example","generated","script","unknown"],d=c.filter(F=>!u.includes(F));if(d.length>0)throw new Error(`Unsupported system-map source scope(s): ${d.join(", ")}`);let m=new Set(c),f=F=>m.has(sc(F));if(i.length===0&&r.length===0)throw new Error("system-map requires at least one --search or --symbol anchor.");let p=t.maxDepth??b0;if(!Number.isSafeInteger(p)||p<0)throw new RangeError(`maxDepth must be a non-negative safe integer; received ${p}`);let g=t.maxTopologyCharacters??L0;if(!Number.isSafeInteger(g)||g<=0)throw new RangeError(`maxTopologyCharacters must be a positive safe integer; received ${g}`);let h=new U(e),b=h.fileDependencyGraph(),v=mN(b),y=fN(h.sourceFiles()),I=Hs(e),E=new Map((I?.observations??[]).map(F=>[F.id,F])),S=new Set((I?.observations??[]).map(F=>`${F.source.file}\0${F.source.startLine}`)),x=new Set,C=new Map,L=new Map,w=new Map,R=new Map,M=[],_=new Map,D=new Map,P=[],k=0,V=0,le=0,G=0,X=0,N=0,K=new Set,ne=new Map,fe=new Map,he=F=>{let H=fe.get(F);if(H)return H;let ee=Zn(e,F,{excludeIndexedTargets:!1});return fe.set(F,ee),ee},ce=(F,H,ee,we,j=!1)=>{let O=L.get(F);if(O)return O.depth=Math.min(O.depth,H),O.primary||=we,O.promoteBoundaryImports||=j,O.origins.add(ee),O;let q={file:F,depth:H,primary:we,promoteBoundaryImports:j,origins:new Set([ee]),processed:!1};return L.set(F,q),q},be=(F,H,ee,we,j="none",O=!1)=>{let q=w.get(F.symbol);if(q)return q.depth=Math.min(q.depth,H),q.origins.add(ee),we&&q.anchorQueries.add(we),q.referenceScope=dN(q.referenceScope,j),ce(F.relativePath,H,ee,!0,O),q;let oe={definition:F,depth:H,origins:new Set([ee]),anchorQueries:new Set(we?[we]:[]),referenceScope:j,processed:!1};return w.set(F.symbol,oe),ce(F.relativePath,H,ee,!0,O),oe},T=(F,H,ee,we,j=!1,O=!0)=>{let q=fn(F),oe=R.get(q);if(oe)return oe.depth=Math.min(oe.depth,H),oe.origins.add(ee),we&&oe.anchorQueries.add(we),oe.reverseCallExpansion||=j,oe.traversalEligible||=O,ce(F.file,H,ee,oe.traversalEligible,!0),oe;let z={...F,depth:H,origins:new Set([ee]),anchorQueries:new Set(we?[we]:[]),reverseCallExpansion:j,traversalEligible:O};return R.set(q,z),ce(F.file,H,ee,O,!0),z},Z=(F,H,ee)=>{ce(F.source.file,H,ee,!0,!0),F.owner.file!==F.source.file&&ce(F.owner.file,H,`${ee}:owner`,!0,!0);let we=W(e,F.owner.file),j=F.owner.symbol?ri(e,h,F.owner.symbol).matches.find(oe=>oe.relativePath===F.owner.file):null,O=(j&&!De(j.symbol)?j:null)??Ke(we,F.source.startLine);if(O&&!De(O.symbol))return be(O,H,ee,void 0,"none",!0),O.symbol;F.owner.name&&T({file:F.owner.file,name:F.owner.name,startLine:F.owner.startLine,endLine:F.owner.endLine},H,`${ee}:source-owner`,void 0,!0);let q=h.definitionsForFile(F.source.file).filter(oe=>!!oe.leaf&&Rn(e,F.source.file,oe.leaf).some(z=>z>=F.source.startLine&&z<=F.source.endLine));if(q.length===1){let oe=q[0];be(oe,H,`${ee}:handler-identifier`,void 0,"none",!0),Et(_,{kind:"runtime-boundary",evidence:"runtime-boundary:handler-identifier",fromFile:F.source.file,fromSymbol:null,toFile:oe.relativePath,toSymbol:oe.symbol,fromBoundaryParticipant:Ir(F),line:F.source.startLine,strength:"derived"})}return null};for(let F of i){let H=V0(e,h,F,S),ee=H.filter(q=>Z0(q,f)),we=!t.fullLiteralTraversal&&(H.length>S0||ee.length>v0),j=we?[]:H,O=new Set((we?[]:t.fullLiteralTraversal?ee:[...ee].sort(J0).slice(0,C0)).map(DS));we&&(V+=1,le+=H.length);for(let q of j){let oe=O.has(DS(q)),z=oe&&!q.ownerSymbol&&q.ownerStartLine!==null&&q.ownerEndLine!==null;if(ce(q.relativePath,0,`${oe?"literal-anchor":"literal-match"}:${F}`,z,z),z&&T({file:q.relativePath,name:q.ownerShortName??`${q.relativePath}:${q.ownerStartLine+1}`,startLine:q.ownerStartLine,endLine:q.ownerEndLine},0,`literal-source-owner:${F}`,F,!0),oe&&q.ownerSymbol){let ue=ri(e,h,q.ownerSymbol).matches[0];ue&&!De(ue.symbol)&&be(ue,0,"literal-owner",F,"all",!0)}M.push({query:F,file:q.relativePath,line:q.line,ownerSymbol:q.ownerSymbol,ownerShortName:q.ownerShortName,ownerStartLine:q.ownerStartLine,ownerEndLine:q.ownerEndLine,sourceLine:q.sourceLine.trim(),matchKind:q.matchKind,traversalSeed:oe})}P.push({kind:"literal",query:F,status:H.length>0?"matched":"missing",matchedRegionIds:[],matchingLines:H.length,seedMatchingLines:we?0:O.size,matchOnlyLines:H.length-O.size,eligibleSeedMatchingLines:ee.length,materializedMatchingLines:j.length,withheldMatchingLines:we?H.length:0,literalTraversal:we?"withheld-broad":"materialized",representativeMatches:we?eN(F,H):void 0,narrowingCommands:we?nN(F,H):void 0,exhaustiveTraversalCommand:we||O.size<ee.length?`codebaseiq system-map --search ${Ne(F)} --full-literal-traversal`:void 0,seedRegionIds:[],matchOnlyRegionIds:[]})}for(let F of r){let H=ri(e,h,F);k+=H.omitted;let ee=Y0(e,F),we=H.matches.filter(z=>!De(z.symbol)),j=ee!==null&&we.length===0;j&&T(ee,0,"source-construct-anchor",F,!0);let O=j?we:H.matches;for(let z of O)be(z,0,"symbol-anchor",F,"all",!0);let q=j?X0(ee):null,oe=j?1:H.total;P.push({kind:"symbol",query:F,status:oe===0?"missing":oe===1?"matched":"ambiguous",matchedRegionIds:[],symbolCandidates:[...q?[q]:[],...O.map(aN)],totalSymbolCandidates:oe,omittedSymbolCandidates:H.omitted})}for(let F=0;F<p;F+=1){if(a.has("call")){let j=[...R.values()].filter(O=>O.traversalEligible&&O.reverseCallExpansion&&O.depth<=F&&!K.has(fn(O)));for(let O of j){K.add(fn(O));let q=te(e,O.file);if((q?.callables??[]).filter(ue=>ue.name===O.name&&ue.startLine<=O.endLine&&ue.endLine>=O.startLine).length===1){let ue=(q?.callSites??[]).filter(Re=>Re.calleeLeaf===O.name&&!Re.memberAccess);for(let Re of ue){let Te=F+1,ve=Ke(W(e,O.file),Re.line),Pe=null,Ve=null;if(ve&&!De(ve.symbol)){if(ve.relativePath===O.file&&ve.startLine<=O.endLine&&ve.endLine>=O.startLine)continue;be(ve,Te,"reverse-local-call-owner",void 0,"forward-regions",!0),Pe=ve.symbol}else{let $=ud(e,O.file,Re.line);$&&fn($)!==fn(O)&&(Ve=T($,Te,"reverse-local-call-source-owner",void 0,!0))}!Pe&&!Ve||Et(_,{kind:"call",evidence:"ast-callsite",fromFile:O.file,fromSymbol:Pe,toFile:O.file,toSymbol:null,fromSourceConstruct:Ve?St(Ve):void 0,toSourceConstruct:St(O),line:Re.line,strength:"derived"})}}let z=new Set([...v.get(O.file)??[],...ne.get(fn(O))??[],...qh(e,O.file).flatMap(ue=>[...v.get(ue)??[]])]);for(let ue of z){if(!f(ue))continue;let Te=he(ue).targets.filter(ve=>ve.targetFile===O.file&&ve.targetStartLine<=O.endLine&&ve.targetEndLine>=O.startLine);for(let ve of Te){let Pe=F+1,Ve=Ke(W(e,ue),ve.line),$=null,Le=null;if(Ve&&!De(Ve.symbol))be(Ve,Pe,"reverse-member-call-owner",void 0,"cross-workspace-or-forward",!0),$=Ve.symbol;else{let ie=ud(e,ue,ve.line);ie&&(Le=T(ie,Pe,"reverse-member-call-source-owner",void 0,!0))}!$&&!Le||Et(_,{kind:"call",evidence:"ast-service-member-callsite",fromFile:ue,fromSymbol:$,toFile:O.file,toSymbol:null,fromSourceConstruct:Le?St(Le):void 0,toSourceConstruct:St(O),line:ve.line,strength:ve.strength==="exact"?"exact":"derived"})}}}}let H=[...w.values()].filter(j=>!j.processed&&j.depth<=F),ee=a.has("call")?h.calleeMap(H.map(j=>j.definition),{additive:!1,semantic:!1}):new Map;for(let j of H){j.processed=!0;let O=j.definition;if(j.referenceScope!=="none"&&(a.has("call")||a.has("reference")||a.has("contract-symbol"))){let q=rN(e,h,O).filter(z=>f(z.file)&&uN(j,z.file,L,y)),oe=new Set(q.flatMap(z=>{if(!(a.has("call")&&te(e,z.file)?.callSites.some(Te=>Te.line===z.line&&Te.calleeLeaf===O.leaf)===!0)||!z.enclosingSymbol)return[];let Re=ri(e,h,z.enclosingSymbol).matches[0];return Re&&!De(Re.symbol)?[{owner:Re,site:z}]:[]}).sort((z,ue)=>{let Re=Lt(O.relativePath,y).relativeDir,Te=Lt(z.owner.relativePath,y).relativeDir===Re,ve=Lt(ue.owner.relativePath,y).relativeDir===Re,Pe=ES(e,z.owner),Ve=ES(e,ue.owner),$=z.owner.endLine-z.owner.startLine,Le=ue.owner.endLine-ue.owner.startLine;return Number(ve)-Number(Te)||Ve-Pe||$-Le||z.owner.symbol.localeCompare(ue.owner.symbol)}).filter((z,ue,Re)=>Re.findIndex(Te=>Te.owner.symbol===z.owner.symbol)===ue).reduce((z,ue)=>{if(z.length>=E0)return z;let Re=Lt(ue.owner.relativePath,y).relativeDir;return z.some(Te=>Te.workspace===Re)||z.push({symbol:ue.owner.symbol,workspace:Re}),z},[]).map(z=>z.symbol));for(let z of q){let ue=F+1;ce(z.file,ue,`reference:${A(O.symbol)}`,!0);let Re=a.has("call")&&te(e,z.file)?.callSites.some(Pe=>Pe.line===z.line&&Pe.calleeLeaf===O.leaf)===!0,Te=null,ve=null;if(z.enclosingSymbol){let Pe=ri(e,h,z.enclosingSymbol).matches[0];Pe&&!De(Pe.symbol)&&(be(Pe,ue,"reference-owner",void 0,Re&&oe.has(Pe.symbol)?j.referenceScope:"none"),Te=Pe.symbol)}if(!Te&&z.line!==null){let Pe=ud(e,z.file,z.line);Pe&&(ve=T(Pe,ue,"reference-source-owner",void 0,Re))}a.has("reference")&&Et(_,{kind:"reference",evidence:"indexed-or-source-reference",fromFile:z.file,fromSymbol:Te,toFile:O.relativePath,toSymbol:O.symbol,fromSourceConstruct:ve?St(ve):void 0,line:z.line,strength:"mixed"}),Re&&Et(_,{kind:"call",evidence:"ast-callsite",fromFile:z.file,fromSymbol:Te,toFile:O.relativePath,toSymbol:O.symbol,fromSourceConstruct:ve?St(ve):void 0,line:z.line,strength:"derived"}),a.has("contract-symbol")&&Lt(z.file,y).relativeDir!==Lt(O.relativePath,y).relativeDir&&Et(_,{kind:"contract-symbol",evidence:"compiler-cross-workspace-symbol",fromFile:z.file,fromSymbol:Te,toFile:O.relativePath,toSymbol:O.symbol,fromSourceConstruct:ve?St(ve):void 0,line:z.line,strength:"exact"})}}for(let q of ee.get(O.symbolId)??[]){let oe=ri(e,h,q.symbol).matches.find(ue=>ue.relativePath===q.file);if(!oe||!f(oe.relativePath))continue;if(!(oe.relativePath===O.relativePath||(b.get(O.relativePath)??new Set).has(oe.relativePath))){G+=1;continue}be(oe,F+1,`call:${A(O.symbol)}`,void 0,"none",!0),Et(_,{kind:"call",evidence:q.source,fromFile:O.relativePath,fromSymbol:O.symbol,toFile:oe.relativePath,toSymbol:oe.symbol,line:null,strength:j0(q.source)})}}let we=[...L.values()].filter(j=>!j.processed&&j.primary&&j.depth<=F);for(let j of we){j.processed=!0;let O=[...R.values()].filter($=>$.traversalEligible&&$.file===j.file&&$.depth<=F),q=[...w.values()].filter($=>$.definition.relativePath===j.file&&$.depth<=F).map($=>{let Le=sr(e,j.file,$.definition.startLine);return{startLine:Le?.startLine??$.definition.startLine,endLine:Le?.endLine??$.definition.endLine}}),oe=$=>[...w.values()].filter(Le=>Le.definition.relativePath===j.file&&Le.definition.startLine<=$&&Le.definition.endLine>=$).sort((Le,ie)=>Le.definition.endLine-Le.definition.startLine-(ie.definition.endLine-ie.definition.startLine)||Le.definition.startLine-ie.definition.startLine)[0],z=[...E.values()].filter($=>$.source.file===j.file&&C.has($.id)),ue=[...O.map($=>({startLine:$.startLine,endLine:$.endLine})),...z.map($=>({...tl(e,$)}))],Re=[...q,...ue],Te=(te(e,j.file)?.callSites??[]).filter($=>Re.some(Le=>$.line>=Le.startLine&&$.line<=Le.endLine)),ve=new Set;if(a.has("call"))for(let $ of Re){let Le=Dn(e,j.file,$.startLine,$.endLine);for(let ie of Le.targets){if(!f(ie.definition.relativePath))continue;let Je=oe(ie.sourceLine),Ut=O.find(Mt=>Mt.startLine<=ie.sourceLine&&Mt.endLine>=ie.sourceLine),vt=z.find(Mt=>{let ut=tl(e,Mt);return ut.startLine<=ie.sourceLine&&ut.endLine>=ie.sourceLine});be(ie.definition,F+1,`scip-occurrence-call:${j.file}:${ie.sourceLine+1}`,void 0,"none",!0),Et(_,{kind:"call",evidence:"scip-occurrence-callsite",fromFile:j.file,fromSymbol:Je?.definition.symbol??null,toFile:ie.definition.relativePath,toSymbol:ie.definition.symbol,fromBoundaryParticipant:vt?Ir(vt):void 0,fromSourceConstruct:Ut?St(Ut):void 0,line:ie.sourceLine,strength:"exact"}),ve.add(`${ie.sourceLine}\0${ie.calleeLeaf}`)}}if(a.has("reference"))for(let $ of Re){let Le=Qh(e,j.file,$.startLine,$.endLine);for(let ie of Le.targets){if(!f(ie.definition.relativePath)||ve.has(`${ie.sourceLine}\0${ie.calleeLeaf}`))continue;let Je=oe(ie.sourceLine);if(Je?.definition.symbol===ie.definition.symbol)continue;let Ut=O.find(Mt=>Mt.startLine<=ie.sourceLine&&Mt.endLine>=ie.sourceLine),vt=z.find(Mt=>{let ut=tl(e,Mt);return ut.startLine<=ie.sourceLine&&ut.endLine>=ie.sourceLine});be(ie.definition,F+1,`scip-occurrence-reference:${j.file}:${ie.sourceLine+1}`,void 0,"none",!0),Et(_,{kind:"reference",evidence:"scip-occurrence-reference",fromFile:j.file,fromSymbol:Je?.definition.symbol??null,toFile:ie.definition.relativePath,toSymbol:ie.definition.symbol,fromBoundaryParticipant:vt?Ir(vt):void 0,fromSourceConstruct:Ut?St(Ut):void 0,line:ie.sourceLine,strength:"exact"})}}let Pe=a.has("call")?Zn(e,j.file,{ranges:Re,excludeIndexedTargets:!1}):{targets:[],unresolvedCallsites:0};N+=Pe.unresolvedCallsites;let Ve=Pe.targets.filter($=>!ve.has(`${$.line}\0${$.calleeLeaf}`));X+=Ve.filter($=>$.strength!=="exact"&&($.resolution!=="imported-service-object-member"||($.resolutionAlternativeCount??0)>1)).length;for(let $ of Ve){let Le=($.resolutionAlternativeCount??1)===1,ie=$.targetSymbol?W(e,$.targetFile).find(ut=>ut.symbol===$.targetSymbol):void 0,Je=ie?null:T({file:$.targetFile,name:$.calleeLeaf,startLine:$.targetStartLine,endLine:$.targetEndLine},F+1,`member-call:${j.file}`,void 0,$.resolution==="imported-service-object-member"&&Le,Le);if(Je&&$.serviceFile){let ut=fn(Je),_r=ne.get(ut)??new Set;for(let yI of v.get($.serviceFile)??[])_r.add(yI);ne.set(ut,_r)}ie&&be(ie,F+1,`member-call:${j.file}`,void 0,"none",!0);let Ut=O.find(ut=>ut.startLine<=$.line&&ut.endLine>=$.line),vt=oe($.line),Mt=z.find(ut=>{let _r=tl(e,ut);return _r.startLine<=$.line&&_r.endLine>=$.line});Et(_,{kind:"call",evidence:$.resolution==="constructed-member-receiver"?"ast-constructed-member-callsite":$.resolution==="factory-callback-member"?"ast-factory-callback-callsite":$.resolution==="imported-service-object-member"?"ast-service-member-callsite":"ast-member-import-candidate",fromFile:j.file,fromSymbol:vt?.definition.symbol??null,toFile:$.targetFile,toSymbol:ie?.symbol??null,fromBoundaryParticipant:Mt?Ir(Mt):void 0,fromSourceConstruct:Ut?St(Ut):void 0,toSourceConstruct:Je?St(Je):void 0,line:$.line,strength:$.resolution==="imported-service-object-member"?($.resolutionAlternativeCount??0)===1?"derived":"candidate":$.strength??"candidate"})}for(let $ of a.has("import")||a.has("call")?oN(e,j.file):[]){if(!$.fromFile){if(a.has("import")){let ie=D.get($.shortName)??{name:$.shortName,fromFiles:new Set};ie.fromFiles.add(j.file),D.set($.shortName,ie)}continue}if(!f($.fromFile))continue;if(a.has("import")&&(ce($.fromFile,F+1,`import:${j.file}`,!1),Et(_,{kind:"import",evidence:"indexed-or-source-import",fromFile:j.file,fromSymbol:null,toFile:$.fromFile,toSymbol:$.symbol,line:null,strength:"mixed"})),a.has("call")&&Te.length>0){let ie=($.source==="compiler"?ri(e,h,$.symbol).matches:Wn(e,$.fromFile,$.importedName)).filter(Je=>!De(Je.symbol));for(let Je of ie){let Ut=Te.filter(vt=>vt.calleeLeaf===$.localName).map(vt=>vt.line);if(Ut.length!==0){be(Je,F+1,`source-call:${j.file}`,void 0,"none",!0);for(let vt of Ut)Et(_,{kind:"call",evidence:"ast-callsite",fromFile:j.file,fromSymbol:null,toFile:Je.relativePath,toSymbol:Je.symbol,line:vt,strength:"derived"})}}}if(!j.promoteBoundaryImports||!lN(j.file,$.fromFile,y))continue;let Le=ri(e,h,$.symbol);for(let ie of Le.matches)if(cN(ie.relativePath,$.fromFile,y)&&!De(ie.symbol)){let Je=Lt(j.file,y).relativeDir!==Lt(ie.relativePath,y).relativeDir;be(ie,F+1,`boundary-import:${j.file}`,void 0,Je?"cross-workspace-or-forward":"forward-regions")}}}for(let j of a.has("runtime-boundary")?I?.links??[]:[]){if(j.strength==="candidate"||l==="exact"&&j.strength!=="exact"||x.has(j.id))continue;let O=E.get(j.from),q=E.get(j.to);if(!O||!q||!f(O.source.file)||!f(q.source.file))continue;let oe=TS(O,F,C,w,R),z=TS(q,F,C,w,R);if(oe===null&&z===null)continue;let ue=F+1,Re=Z(O,oe??ue,`runtime-boundary:${j.joinRule}`),Te=Z(q,z??ue,`runtime-boundary:${j.joinRule}`),ve=Re?null:PS(R,O),Pe=Te?null:PS(R,q);C.set(O.id,oe??ue),C.set(q.id,z??ue),Et(_,{kind:"runtime-boundary",evidence:`runtime-boundary:${j.joinRule}`,fromFile:O.source.file,fromSymbol:Re,toFile:q.source.file,toSymbol:Te,fromBoundaryParticipant:Ir(O),toBoundaryParticipant:Ir(q),fromSourceConstruct:ve?St(ve):void 0,toSourceConstruct:Pe?St(Pe):void 0,runtimeBoundaryKey:j.matchedKeyParts.map(Ve=>`${Ve.name}=${Ve.value}`).join(" "),line:O.source.startLine,strength:j.strength}),x.add(j.id)}}let Q=new Map;for(let F of L.keys())Q.set(F,jo(F,y));let Se=[..._.values()].filter(F=>Q.has(F.fromFile)&&Q.has(F.toFile)).map(F=>({...F,fromRegionId:Q.get(F.fromFile).id,toRegionId:Q.get(F.toFile).id})).sort(OS),it=SN(Se),fi=new Set(t.expand??[]),$n=gN(L,w,M,Se,it,Q,fi),Ki=new Set([...L.values()].filter(F=>[...F.origins].some(H=>H.startsWith("literal-anchor:")||H==="literal-owner"||H==="symbol-anchor")).map(F=>Q.get(F.file).id)),qm=q0($n),sI=new Set($n.map(F=>F.id)),aI=[...fi].filter(F=>!sI.has(F)).sort();for(let F of P)if(F.matchedRegionIds=CN(F,M,w,Q),F.kind==="literal"){let H=M.filter(ee=>ee.query===F.query);F.seedRegionIds=Me(H.filter(ee=>ee.traversalSeed).map(ee=>Q.get(ee.file).id)),F.matchOnlyRegionIds=Me(H.filter(ee=>!ee.traversalSeed).map(ee=>Q.get(ee.file).id))}let Km=[...w.values()].filter(F=>!F.processed).length,Gm=[...L.values()].filter(F=>F.primary&&!F.processed).length,Wm=[...L.values()].filter(F=>!F.primary&&!F.processed).length,Vm=[...w.values()].filter(F=>F.processed),gs=(I?.frontiers??[]).flatMap(F=>{let H=E.get(F.observationId);return!H&&F.source&&F.action&&F.strength?!a.has("runtime-boundary")||!f(F.source.file)||l==="exact"||!L.has(F.source.file)?[]:[{observationId:F.observationId,action:F.action,strength:F.strength,file:F.source.file,line:F.source.startLine,ownerShortName:F.ownerShortName??null,address:F.address??F.missingKeyParts.join(", "),reason:F.reason}]:!a.has("runtime-boundary")||!H||!f(H.source.file)||l==="exact"&&H.strength!=="exact"||!L.has(H.source.file)?[]:[{observationId:H.id,action:H.action,strength:H.strength,file:H.source.file,line:H.source.startLine,ownerShortName:H.owner.name,address:BS(H),reason:F.reason,protocol:H.protocol,role:H.role,modality:H.modality,resolution:H.resolution,sourceScope:H.sourceScope,keyParts:H.keyParts.map(ee=>({name:ee.name,value:ee.value,evidence:ee.evidence}))}]}).sort((F,H)=>F.file.localeCompare(H.file)||F.line-H.line),Ul=(I?.links??[]).filter(F=>{if(!a.has("runtime-boundary")||l==="exact"&&F.strength!=="exact")return!1;let H=E.get(F.from),ee=E.get(F.to);return!!(H&&ee&&f(H.source.file)&&f(ee.source.file)&&(L.has(H.source.file)||L.has(ee.source.file)))}),lI=Ul.filter(F=>F.strength==="exact").length,cI=Ul.filter(F=>F.strength==="derived").length,uI=Ul.filter(F=>F.strength==="candidate").length,dI=I?.links.filter(F=>F.strength==="exact").length??0,mI=I?.links.filter(F=>F.strength==="derived").length??0,fI=I?.links.filter(F=>F.strength==="candidate").length??0,zl=vN(D,Q),ql=k===0?"accounted":"incomplete",Jm=[...V>0?[`${V} broad literal anchor(s) withheld ${le} 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 (${c.join(", ")}) remain visible as match-only evidence and do not seed traversal.`,I?"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 codebaseiq 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 ${p}; nonzero frontier counts identify evidence that was discovered but not traversed.`,"Region labels are structural path groupings, not inferred runtime or architectural boundaries."],Dt=k0({db:e,anchors:P,regions:$n,symbolStates:w,sourceConstructStates:R,literalHits:M,relations:Se,externalBoundaries:zl,boundaryFrontiers:gs,regionForFile:Q,closureStatus:ql,omittedSymbolCandidates:k,maxDepth:p,requestedRelationKinds:o,evidenceFloor:l,includedSourceScopes:c,blindSpots:Jm,topologyFrontiers:t.topologyFrontiers??[],routeIds:t.routeIds??[],expandedRegionIds:[...fi],maxTopologyCharacters:g,fullLiteralTraversal:t.fullLiteralTraversal??!1});if(n==="topology")return Dt;let Ym=(t.behaviorFocusLocations?.length??0)>0?new Set([...Dt.anchors.flatMap(F=>F.nodeIds),...Dt.paths.flatMap(F=>F.nodeIds)]).size:void 0,hs=Ay(e,Dt,{focusLocations:t.behaviorFocusLocations,...Ym?{maxSteps:Ym}:{}});mb(e,Dt,hs);let pI=M0(e,Dt,hs,t.behaviorFocusLocations??[]);Dt.corridor=lS(Dt,{focusLocations:pI});let Xm=db(e,Dt,hs,{sourceAllowed:f,selectionTerms:t.selectionTerms}),Qm=O0(Dt),gI=U0(i,r,p,o,l,c,t.fullLiteralTraversal??!1,g,$n,it,Ki,fi,Qm),hI=H0(i,r,p,$n.filter(F=>Qm.has(F.id)),Ki,o,l,c,t.fullLiteralTraversal??!1,g);return{anchors:P,regions:$n,regionRelations:it,externalBoundaries:zl,boundaryFrontiers:gs,unmatchedExpansions:aI,expansion:hI,drilldown:qm,presentation:gI,topology:Dt,behavior:hs,nextAnchors:Xm,closure:{status:ql,emitted:{regions:$n.length,relations:Se.length,runtimeLinks:x.size},withheld:{symbols:Km,files:Gm+Wm,regions:Dt.nodes.filter(F=>F.kind==="structural-region"&&F.disposition==="folded").length,drillAnchors:(qm?.omittedAnchors??0)+Xm.omittedAnchors,literalMatches:le},ambiguous:{anchors:P.filter(F=>F.status==="ambiguous").length,omittedSymbolCandidates:k},external:zl.length,unresolved:gs.length,explanation:ql==="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:P.length,requestedRelationKinds:o,evidenceFloor:l,includedSourceScopes:c,matchedAnchorCount:P.filter(F=>F.status!=="missing").length,literalSearchesComplete:!0,broadLiteralAnchors:V,withheldLiteralMatches:le,symbolCandidateSetsComplete:k===0,omittedSymbolCandidates:k,maxTraversalDepth:p,frontierSymbols:Km,frontierFiles:Gm,supportFilesNotTraversed:Wm,filteredUnverifiedCallEdges:G,memberCallCandidateEdges:X,unresolvedMemberCallsites:N,runtimeBoundaryEvidenceAvailable:I!==null,runtimeBoundaryObservations:I?.observations.length??0,runtimeBoundaryExactLinks:lI,runtimeBoundaryDerivedLinks:cI,runtimeBoundaryCandidateLinks:uI,repositoryRuntimeBoundaryExactLinks:dI,repositoryRuntimeBoundaryDerivedLinks:mI,repositoryRuntimeBoundaryCandidateLinks:fI,runtimeBoundaryTraversedLinks:x.size,runtimeBoundaryFrontiers:gs.length,referenceExpansionEligibleSymbols:Vm.filter(F=>F.referenceScope!=="none").length,referenceExpansionSkippedSymbols:Vm.filter(F=>F.referenceScope==="none").length,dynamicDispatchRepresented:I?.links.some(F=>F.joinRule==="carrier.discriminator"&&x.has(F.id))??!1,runtimeGeneratedLinksRepresented:I!==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:Jm}}}function M0(e,t,n,i){let r=new Map,o=l=>{r.set(`${l.file}\0${l.line}`,l)};for(let l of i)o(l);let s=new Set(t.anchors.filter(l=>l.status==="matched").flatMap(l=>l.nodeIds));for(let l of n.steps)if(!(!l.location||!s.has(l.nodeId)||(l.behavior?.rawCharacters??1/0)>3e3))for(let c of l.behavior?.lines??[])c.signals.some(u=>w0.has(u))&&o({file:l.location.file,line:c.line,endLine:c.endLine});let a=t.edges.filter(l=>l.disposition==="emitted").flatMap(l=>l.evidence.flatMap(c=>c.location?[c.location]:[]));for(let l of a){o(l);let c=t.nodes.filter(d=>d.location?.file===l.file&&["symbol","source-construct","runtime-boundary-participant"].includes(d.kind)&&d.location.line<=l.line&&(d.location.endLine??d.location.line)>=l.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(!c?.location)continue;let u=ea(e,l.file,c.location.line,c.location.endLine??c.location.line,[l.line]);for(let d of u)o({file:l.file,line:d.line,endLine:d.endLine})}return[...r.values()].sort((l,c)=>l.file.localeCompare(c.file)||l.line-c.line)}function P0(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 fn(e){return`${e.file}\0${e.startLine}\0${e.endLine}\0${e.name}`}function St(e){return{file:e.file,name:e.name,startLine:e.startLine,endLine:e.endLine}}function el(e,t){let n=pd(te(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 i=_S(e,t.file,t.startLine);return i&&i.endLine>=t.endLine?{file:t.file,name:i.name,startLine:i.startLine,endLine:i.endLine}:St(t)}function Rr(e){return wt("source-construct",e.file,String(e.startLine),String(e.endLine),e.name)}function il(e,t){let n=pr(e,t.symbol,t.relativePath),i=new Set(["package-surface-file","transitive-package-surface"]),r=n.filter(s=>!i.has(s)||xt(e,t)),o=r.some(s=>!i.has(s));return{evidence:r,priority:o||by(e,t.symbol,t.relativePath)?2:1}}function ES(e,t){let n=il(e,t);return n.evidence.length>0?n.priority:0}function T0(e,t){let n=W(e,t.file),i=n.filter(r=>r.startLine<=t.startLine&&r.endLine>=t.startLine).sort((r,o)=>r.endLine-r.startLine-(o.endLine-o.startLine)||r.startLine-o.startLine);for(let r of i){let o=il(e,r);if(o.evidence.length>0)return o}for(let r of F0(e,t.file,t.startLine)){let o=n.filter(s=>s.leaf===r.name).sort((s,a)=>Math.abs(s.startLine-r.startLine)-Math.abs(a.startLine-r.startLine)||s.symbol.localeCompare(a.symbol));for(let s of o){let a=il(e,s);if(a.evidence.length>0)return a}return{evidence:[],priority:0}}return{evidence:[],priority:0}}function F0(e,t,n){let i=ae(e,t)?.rootNode;if(!i||i.startPosition.row>n||i.endPosition.row<n)return[];let r=[],o=gd(i,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")&&r.push({name:s.text,startLine:o.startPosition.row})}o=o.parent}return r}function k0(e){let t=[...new Map([...e.sourceConstructStates.values()].map(R=>el(e.db,R)).map(R=>[fn(R),R])).values()].sort((R,M)=>R.file.localeCompare(M.file)||R.startLine-M.startLine||R.endLine-M.endLine),n=e.anchors.map((R,M)=>{let _=wt("anchor",String(M),R.kind,R.query),D=[...e.symbolStates.values()].filter(G=>G.anchorQueries.has(R.query)).flatMap(G=>{if(!De(G.definition.symbol))return[oi(G.definition.symbol)];let X=t.filter(N=>N.file===G.definition.relativePath).map(N=>Rr(N));return X.length>0?X:[oi(G.definition.symbol)]}),P=[...e.sourceConstructStates.values()].filter(G=>G.anchorQueries.has(R.query)).map(G=>Rr(el(e.db,G))),k=e.literalHits.filter(G=>G.query===R.query&&G.traversalSeed===!0&&G.ownerSymbol&&e.symbolStates.has(G.ownerSymbol)).map(G=>oi(G.ownerSymbol)),V=e.literalHits.filter(G=>G.query===R.query&&G.traversalSeed===!0&&!G.ownerSymbol&&G.ownerStartLine!==null&&G.ownerStartLine!==void 0&&G.ownerEndLine!==null&&G.ownerEndLine!==void 0).map(G=>Rr(el(e.db,P0(G)))),le=Me(R.kind==="symbol"?[...D,...P]:k.length+V.length>0?[...k,...V]:R.seedRegionIds??[]);return{id:_,kind:R.kind,query:R.query,status:R.status,nodeIds:R.status==="ambiguous"?[]:le,candidateNodeIds:R.status==="ambiguous"?le:[],omittedCandidates:R.omittedSymbolCandidates??0}}),i=new Map;for(let R of n)for(let M of[...R.nodeIds,...R.candidateNodeIds]){let _=i.get(M)??[];_.push(R.id),i.set(M,_)}let r=e.relations.flatMap(R=>[R.fromBoundaryParticipant,R.toBoundaryParticipant].flatMap(M=>M?.ownerName?[M]:[])),o=e.regions.map(R=>({id:R.id,kind:"structural-region",label:R.label,disposition:"folded",location:null,anchorIds:Me(i.get(R.id)??[]),attributes:{workspace:R.workspace,structuralPath:R.structuralPath,minimumDepth:R.minDepth,files:R.fileCount,symbols:R.symbolCount,expanded:R.expanded}}));for(let R of e.symbolStates.values()){let M=e.regionForFile.get(R.definition.relativePath)?.id;if(!M)throw new Error(`System-map symbol ${R.definition.symbol} has no structural region.`);let _=oi(R.definition.symbol),D=il(e.db,R.definition);o.push({id:_,kind:"symbol",label:A(R.definition.symbol),disposition:(i.get(_)?.length??0)>0?"emitted":"folded",location:{file:R.definition.relativePath,line:R.definition.startLine,endLine:R.definition.endLine},anchorIds:Me(i.get(_)??[]),attributes:{regionId:M,depth:R.depth,leaf:R.definition.leaf??A(R.definition.symbol),referenceScope:R.referenceScope,...D.evidence.length>0?{publicEntry:!0,publicEntryPriority:D.priority,publicEntryEvidence:D.evidence.join(",")}:{}}})}for(let R of t){let M=e.regionForFile.get(R.file)?.id;if(!M)throw new Error(`Source construct ${R.name} has no structural region.`);let _=Rr(R),P=r.find(V=>V.file===R.file&&V.line>=R.startLine&&V.line<=R.endLine)?.ownerName??R.name,k=T0(e.db,R);o.push({id:_,kind:"source-construct",label:P,disposition:(i.get(_)?.length??0)>0?"emitted":"folded",location:{file:R.file,line:R.startLine,endLine:R.endLine},anchorIds:Me(i.get(_)??[]),attributes:{regionId:M,leaf:P,sourceOwned:!0,...k.evidence.length>0?{publicEntry:!0,publicEntryPriority:k.priority,publicEntryEvidence:k.evidence.join(",")}:{}}})}let s=new Map;for(let R of e.relations)R.fromBoundaryParticipant&&s.set(R.fromBoundaryParticipant.observationId,R.fromBoundaryParticipant),R.toBoundaryParticipant&&s.set(R.toBoundaryParticipant.observationId,R.toBoundaryParticipant);for(let R of[...s.values()].sort((M,_)=>M.observationId.localeCompare(_.observationId))){let M=e.regionForFile.get(R.file)?.id;if(!M)throw new Error(`Runtime-boundary participant ${R.observationId} has no structural region.`);o.push({id:dd(R.observationId),kind:"runtime-boundary-participant",label:R.address||R.ownerName||`${R.role} ${R.action}`,disposition:"folded",location:{file:R.file,line:R.line,endLine:R.endLine},anchorIds:[],attributes:{regionId:M,action:R.action,protocol:R.protocol,role:R.role,...R.address?{address:R.address}:{},ownerSymbol:R.ownerSymbol}})}let a=new Set(o.map(R=>R.id)),l=Jt(t,R=>R.file),c=(R,M,_,D,P,k,V=!1)=>{let le=R?oi(R):null;if(le&&a.has(le)&&!De(R))return le;let G=M?dd(M.observationId):null;if(V&&G&&a.has(G))return G;let X=_?Rr(el(e.db,_)):null;if(X&&a.has(X))return X;if(G&&a.has(G))return G;let N=k===null?null:(l.get(P)??[]).filter(K=>K.startLine<=k&&K.endLine>=k).sort((K,ne)=>K.endLine-K.startLine-(ne.endLine-ne.startLine)||K.startLine-ne.startLine)[0]??null;return N?Rr(N):le&&a.has(le)?le:D},u=[];for(let R of e.symbolStates.values()){let M=e.regionForFile.get(R.definition.relativePath)?.id;if(!M)continue;let _=oi(R.definition.symbol);u.push({id:wt("edge","structural-membership",M,_),kind:"structural-membership",fromNodeId:M,toNodeId:_,directed:!0,disposition:"folded",semantics:Ua("structural-membership"),evidence:[{method:"indexed-definition-file",strength:"exact",identity:R.definition.symbol,location:{file:R.definition.relativePath,line:R.definition.startLine,endLine:R.definition.endLine}}]})}let d=Jt(e.relations,R=>`${c(R.fromSymbol,R.fromBoundaryParticipant,R.fromSourceConstruct,R.fromRegionId,R.fromFile,R.line,R.kind==="runtime-boundary")}\0${c(R.toSymbol,R.toBoundaryParticipant,R.toSourceConstruct,R.toRegionId,R.toFile,null)}\0${R.kind}`),m=new Set;for(let R of d.values()){let M=R[0],_=c(M.fromSymbol,M.fromBoundaryParticipant,M.fromSourceConstruct,M.fromRegionId,M.fromFile,M.line,M.kind==="runtime-boundary"),D=c(M.toSymbol,M.toBoundaryParticipant,M.toSourceConstruct,M.toRegionId,M.toFile,null);if(M.kind==="runtime-boundary"&&M.fromBoundaryParticipant){let k=dd(M.fromBoundaryParticipant.observationId),V=c(M.fromSymbol,void 0,M.fromSourceConstruct,M.fromRegionId,M.fromFile,M.line);V!==k&&!m.has(k)&&(m.add(k),u.push({id:wt("edge","boundary-observation",V,k),kind:"boundary-observation",fromNodeId:V,toNodeId:k,directed:!0,disposition:"folded",semantics:Ua("boundary-observation"),evidence:[{method:"runtime-boundary-observation-owner",strength:M.strength??"unknown",identity:M.fromBoundaryParticipant.observationId,location:{file:M.fromBoundaryParticipant.file,line:M.fromBoundaryParticipant.line,endLine:M.fromBoundaryParticipant.endLine}}]}))}(_===D?o.find(k=>k.id===_):null)?.kind!=="structural-region"&&u.push({id:wt("edge",M.kind,_,D),kind:M.kind,fromNodeId:_,toNodeId:D,directed:!0,disposition:"folded",semantics:kb(M),evidence:$0(R.map(k=>({method:k.evidence,strength:k.strength??"unknown",identity:k.kind==="runtime-boundary"&&k.runtimeBoundaryKey?k.runtimeBoundaryKey:`${k.fromSymbol??k.fromFile} -> ${k.toSymbol??k.toFile}`,location:k.line===null?null:{file:k.fromFile,line:k.line}})))})}for(let R of e.externalBoundaries){let M=wt("external",R.kind,R.name),_=Me(R.fromRegionIds);o.push({id:M,kind:R.kind,label:R.name,disposition:"folded",location:null,anchorIds:[],attributes:{}});for(let D of _)u.push({id:wt("edge",R.kind,D,M),kind:R.kind,fromNodeId:D,toNodeId:M,directed:!0,disposition:"folded",semantics:Ua("external-import"),evidence:[{method:"indexed-or-source-import",strength:"mixed",identity:`${D} -> ${R.name}`,location:null}]})}let f=[];e.boundaryFrontiers.forEach((R,M)=>{let _=e.regionForFile.get(R.file)?.id;if(!_)throw new Error(`Runtime-boundary frontier ${R.observationId} has no system-map region.`);let D=wt("unsupported","runtime-boundary",R.observationId,String(M)),P=wt("edge","runtime-boundary-frontier",_,D);o.push({id:D,kind:"runtime-boundary-frontier",label:R.address,disposition:"unsupported",location:{file:R.file,line:R.line},anchorIds:[],attributes:{action:R.action,strength:R.strength,owner:R.ownerShortName}}),u.push({id:P,kind:"runtime-boundary-frontier",fromNodeId:_,toNodeId:D,directed:!0,disposition:"unsupported",evidence:[{method:"runtime-boundary-extractor",strength:R.strength,identity:R.observationId,location:{file:R.file,line:R.line}}]}),f.push({id:wt("frontier","runtime-boundary",R.observationId,String(M)),kind:"runtime-boundary",direction:"unresolved",fromNodeIds:[_],edgeIds:[P],memberNodeIds:[D],memberCount:1,disposition:"unsupported",reason:R.reason,expansion:null})});let p=Za({anchors:n,nodes:o,edges:u,paths:[],frontiers:f,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`]:[]}),g=e.topologyFrontiers.some(R=>R==="frontier:program-facts"),h=CS(p,{expandedFrontierIds:e.topologyFrontiers.filter(R=>R!=="frontier:program-facts"),routeIds:e.routeIds}),b=h.nodes.filter(R=>R.disposition==="emitted"||h.anchors.some(M=>M.status==="matched"&&M.nodeIds.includes(R.id))),v=e.relations.filter(R=>b.some(M=>N0(R,M))),y=e.boundaryFrontiers.filter(R=>b.some(M=>A0(R,M))),I=zb(e.db,v,b),E=Kb(e.db,b),S=iS(e.db,b,y),x=[...I.nodes,...E.nodes,...S.nodes].map(R=>g&&R.disposition==="folded"?{...R,disposition:"emitted"}:R),C=[...I.edges,...E.edges,...S.edges].map(R=>g&&R.disposition==="folded"?{...R,disposition:"emitted"}:R),L=g?null:_0(b,x,C),w=Za({anchors:h.anchors,nodes:[...h.nodes,...x],edges:[...h.edges,...C],paths:h.paths,frontiers:[...h.frontiers,...I.frontiers,...E.frontiers,...S.frontiers,...L?[L]:[]],scope:h.coverage.scope,blindSpots:[...h.coverage.blindSpots,...I.blindSpots,...E.blindSpots,...S.blindSpots],incompleteReasons:h.coverage.status==="incomplete"?[h.coverage.explanation]:[],...h.routeCatalog?{routeCatalog:h.routeCatalog}:{}});w.completion=h.completion;for(let R of w.frontiers)R.disposition==="folded"&&(R.id.startsWith("frontier:program-facts:")||(R.expansion=B0(e,R.id)));return w}function N0(e,t){if(e.fromSymbol&&t.id===oi(e.fromSymbol)||e.toSymbol&&t.id===oi(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 A0(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 _0(e,t,n){let i=Me(t.filter(o=>o.disposition==="folded").map(o=>o.id)),r=Me(n.filter(o=>o.disposition==="folded").map(o=>o.id));return i.length===0&&r.length===0?null:{id:wt("frontier","program-facts"),kind:"program-facts",direction:"outgoing",fromNodeIds:Me(e.map(o=>o.id)),edgeIds:r,memberNodeIds:i,memberCount:i.length,disposition:"folded",reason:"Control, data, state, and temporal facts are folded beneath the selected high-level owners.",expansion:null}}function B0(e,t){return`codebaseiq system-map ${[...e.anchors.flatMap(i=>i.kind==="literal"?[`--search ${Ne(i.query)}`]:[`--symbol ${Ne(i.query)}`]),`--depth ${e.maxDepth}`,...e.requestedRelationKinds.map(i=>`--relation ${Ne(i)}`),`--evidence-floor ${Ne(e.evidenceFloor)}`,...e.includedSourceScopes.map(i=>`--source-scope ${Ne(i)}`),...e.fullLiteralTraversal?["--full-literal-traversal"]:[],`--topology-characters ${e.maxTopologyCharacters}`,...e.expandedRegionIds.map(i=>`--expand ${Ne(i)}`),...e.topologyFrontiers.map(i=>`--frontier ${Ne(i)}`),...e.routeIds.map(i=>`--route ${Ne(i)}`),`--frontier ${Ne(t)}`].join(" ")}`}function O0(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 i=n.attributes.regionId;typeof i=="string"&&t.add(i)}return t}function $0(e){let t=new Map;for(let n of e){let i=n.location?`${n.location.file}:${n.location.line}`:"";t.set(`${n.method}\0${n.strength}\0${n.identity??""}\0${i}`,n)}return[...t.values()].sort((n,i)=>n.method.localeCompare(i.method)||(n.identity??"").localeCompare(i.identity??"")||(n.location?.file??"").localeCompare(i.location?.file??"")||(n.location?.line??0)-(i.location?.line??0))}function wt(...e){return e.map(t=>encodeURIComponent(t)).join(":")}function oi(e){return wt("symbol",e)}function j0(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function H0(e,t,n,i,r,o,s,a,l,c){let u=[...i].sort((g,h)=>AS(g,h,r)),m=u.slice(0,RS).map(g=>g.id),f=u.slice(RS).map(g=>g.id),p=[...e.map(g=>`--search ${Ne(g)}`),...t.map(g=>`--symbol ${Ne(g)}`),`--depth ${n}`,...o.map(g=>`--relation ${Ne(g)}`),`--evidence-floor ${Ne(s)}`,...a.map(g=>`--source-scope ${Ne(g)}`),...l?["--full-literal-traversal"]:[],`--topology-characters ${c}`,...m.map(g=>`--expand ${Ne(g)}`)];return{command:m.length===0?null:`codebaseiq system-map ${p.join(" ")}`,regionCount:m.length,regionIds:m,candidateRegionCount:i.length,omittedRegionIds:f}}function U0(e,t,n,i,r,o,s,a,l,c,u,d,m){let f=[...l].sort((w,R)=>AS(w,R,u)).filter(w=>!m||m.has(w.id)||d.has(w.id)),p=c.length>0?Math.floor(a*.4):0,g=a-p,h=new Set,b=0;for(let w of f){let R=wS(w);!d.has(w.id)&&h.size>0&&b+R>g||(h.add(w.id),b+=R)}let v=c.filter(w=>h.has(w.fromRegionId)&&h.has(w.toRegionId)).sort(z0),y=[];for(let w of v){let R=LS(w);y.length>0&&b+R>a||(y.push(rl(w)),b+=R)}let I=l.filter(w=>!h.has(w.id)).map(w=>w.id).sort(),E=new Set(y),S=c.filter(w=>!E.has(rl(w))).length,x=l.reduce((w,R)=>w+wS(R),0)+c.reduce((w,R)=>w+LS(R),0),C=f.every(w=>h.has(w.id))&&y.length===v.length,L=[...e.map(w=>`--search ${Ne(w)}`),...t.map(w=>`--symbol ${Ne(w)}`),`--depth ${n}`,...i.map(w=>`--relation ${Ne(w)}`),`--evidence-floor ${Ne(r)}`,...o.map(w=>`--source-scope ${Ne(w)}`),...s?["--full-literal-traversal"]:[],`--topology-characters ${Math.max(a,x)}`];return{maxCharacters:a,estimatedCharacters:b,totalEstimatedCharacters:x,regionIds:[...h],omittedRegionIds:I,relationKeys:y,omittedRelations:S,complete:C,expansionCommand:C?null:`codebaseiq system-map ${L.join(" ")}`}}function wS(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 LS(e){return 70+e.fromRegionId.length+e.toRegionId.length+e.kinds.join(",").length+e.evidence.join(",").length}function z0(e,t){let n=i=>i.kinds.includes("runtime-boundary")?0:i.kinds.includes("contract-symbol")?1:2;return n(e)-n(t)||t.relationCount-e.relationCount||rl(e).localeCompare(rl(t))}function rl(e){return`${e.fromRegionId}\0${e.toRegionId}`}function AS(e,t,n){let i=a=>n.has(a.id)?0:1,r=a=>a.sourceFileCount===0?1:0,o=a=>a.symbolCount+a.literalHitCount>0?0:1,s=a=>[...a.incomingRegionIds,...a.outgoingRegionIds].filter(l=>n.has(l)).length;return i(e)-i(t)||o(e)-o(t)||r(e)-r(t)||e.minDepth-t.minDepth||s(t)-s(e)||t.literalHitCount-e.literalHitCount||e.testFileCount-t.testFileCount||e.label.localeCompare(t.label)}function q0(e){let t=[],n=new Set;for(let r of e.filter(o=>o.expanded)){for(let l of r.symbols)l.origins.includes("symbol-anchor")&&n.add(l.file);let o=Jt(r.symbols,l=>l.file),s=Jt(r.literalHits,l=>l.file),a=[...r.files].sort((l,c)=>G0(l,c,o,s));for(let l of a){let c=(o.get(l.file)??[]).sort(W0)[0];if(c){t.push({kind:"symbol",regionId:r.id,file:c.file,line:c.startLine,endLine:c.endLine,label:c.shortName});continue}let u=(s.get(l.file)??[]).sort($S)[0];u&&t.push({kind:"literal",regionId:r.id,file:u.file,line:u.line,endLine:null,label:u.ownerShortName??u.query})}}let i=K0(t,n);return{command:i.length===0?null:`codebaseiq inspect ${i.map(r=>`--at ${Ne(`${r.file}:${r.line+1}`)}`).join(" ")} --view behavior`,definitionCommand:null,candidateAnchors:t.length,selectedAnchors:i.length,omittedAnchors:t.length-i.length,anchors:i}}function K0(e,t){let n=[...Jt(e,s=>s.regionId).values()],i=[],r=new Set,o=Math.min(I0,24);for(let s of e)if(!(!t.has(s.file)||r.has(s.file))&&(i.push(s),r.add(s.file),i.length===o))return i;for(let s=0;i.length<o;s+=1){let a=!1;for(let l of n){let c=l[s];if(c&&(a=!0,!r.has(c.file)&&(i.push(c),r.add(c.file),i.length===o)))break}if(!a)break}return i}function G0(e,t,n,i){let r=a=>a.kind==="test"?2:a.kind==="barrel"?1:0,o=a=>(i.get(a.file)??[]).some(l=>l.traversalSeed)?0:1,s=a=>{let l=n.get(a.file)??[];return Math.min(5,...l.map(c=>Ho(c.origins)))};return r(e)-r(t)||o(e)-o(t)||s(e)-s(t)||e.depth-t.depth||e.file.localeCompare(t.file)}function W0(e,t){return Ho(e.origins)-Ho(t.origins)||e.depth-t.depth||e.startLine-t.startLine||e.shortName.localeCompare(t.shortName)}function Ne(e){return`'${e.replaceAll("'","'\\''")}'`}function V0(e,t,n,i){let r=[];for(let o of me(e,{includeIgnored:!1})){let s=re(e,o);if(s.length===0)continue;let a=t.definitionsForFile(o),l=te(e,o)?.callables??[];for(let c=0;c<s.length;c+=1){let u=s[c]??"";if(!u.includes(n))continue;let d=Ke(a,c),m=pd(l,c),f=d&&!De(d.symbol)?d:null,p=f?.startLine??m?.startLine??d?.startLine??c,g=f?.endLine??m?.endLine??d?.endLine??c,h=no(e,o,c,p,g),b=i.has(`${o}\0${c}`),v=!!(f?.isFunctionLike||m);r.push({relativePath:o,line:c,sourceLine:u,ownerSymbol:f?.symbol??null,ownerShortName:f?A(f.symbol):m?.name??(d?A(d.symbol):null),ownerStartLine:h.startLine,ownerEndLine:h.endLine,matchKind:Q0(u,n),seedPriority:b?0:v?1:2})}}return r}function J0(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 DS(e){return`${e.relativePath}\0${e.line}`}function pd(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,i)=>n.endLine-n.startLine-(i.endLine-i.startLine)||n.startLine-i.startLine)[0]??null}function ud(e,t,n){let r=pd(te(e,t)?.callables??[],n)??_S(e,t,n);if(!r)return null;let o=no(e,t,n,r.startLine,r.endLine);return{file:t,name:r.name,startLine:o.startLine,endLine:o.endLine}}function _S(e,t,n){let i=ae(e,t)?.rootNode;if(!i||i.startPosition.row>n||i.endPosition.row<n)return null;let r=gd(i,n);for(;r;){if(r.type==="variable_declarator"){let s=r.childForFieldName("name")??r.namedChild(0),a=r.childForFieldName("value")??r.namedChild(1);if(s?.type==="identifier"&&a&&md(a,n))return{name:s.text,startLine:r.startPosition.row,endLine:r.endPosition.row}}if(r.type==="pair"){let s=r.childForFieldName("key")??r.namedChild(0),a=r.childForFieldName("value")??r.namedChild(1),l=s?.text.replace(/^(?:['"])(.*)(?:['"])$/u,"$1");if(l&&a&&/^[A-Za-z_$][\w$]*$/u.test(l)&&md(a,n))return{name:l,startLine:r.startPosition.row,endLine:r.endPosition.row}}r=r.parent}let o=sr(e,t,n);return o?{name:`source@${n+1}`,startLine:o.startLine,endLine:o.endLine}:null}function md(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&&md(n,t))}function gd(e,t){let n=e.namedChildren.filter(i=>i.startPosition.row<=t&&i.endPosition.row>=t).sort((i,r)=>i.endIndex-i.startIndex-(r.endIndex-r.startIndex)||i.startPosition.row-r.startPosition.row)[0];return n?gd(n,t):e}function Y0(e,t){let n=t.match(/^(.+):(\d+)(?:-(\d+))?$/u);if(!n)return null;let i=Ls(e,n[1],{allowMultiple:!1})[0]?.relativePath;if(!i)return null;let r=Math.max(0,Number.parseInt(n[2],10)-1),o=n[3]?Math.max(r,Number.parseInt(n[3],10)-1):r,s=(te(e,i)?.callables??[]).filter(a=>a.startLine<=r&&a.endLine>=o).sort((a,l)=>a.endLine-a.startLine-(l.endLine-l.startLine)||a.startLine-l.startLine)[0];return s?{file:i,name:s.name,startLine:s.startLine,endLine:s.endLine}:null}function X0(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 Q0(e,t){let n=/[\p{L}\p{N}_$]/u,i=e.indexOf(t);for(;i>=0;){let r=e[i-1]??"",o=e[i+t.length]??"";if((r==="'"||r==='"'||r==="`")&&o===r)return"exact-value";if(!n.test(r)&&!n.test(o))return"boundary";i=e.indexOf(t,i+Math.max(1,t.length))}return"embedded"}function fd(e){return J(e)==="test"?!1:!/(?:^|[/._-])(?:fixtures?|mocks?|previews?|demos?|examples?|stories)(?:[/._-]|$)/iu.test(e)}function Z0(e,t){return e.matchKind!=="embedded"&&t(e.relativePath)&&(sc(e.relativePath)!=="production"||fd(e.relativePath))}function eN(e,t){let n=[...t].sort(tN),i=[],r=new Set;for(let o of n)if(!r.has(o.relativePath)&&(i.push(o),r.add(o.relativePath),i.length>=xS))break;for(let o of n){if(i.length>=xS)break;i.includes(o)||i.push(o)}return i.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 tN(e,t){let n={"exact-value":0,boundary:1,embedded:2};return n[e.matchKind]-n[t.matchKind]||+(t.ownerSymbol!==null)-+(e.ownerSymbol!==null)||+!fd(e.relativePath)-+!fd(t.relativePath)||e.relativePath.localeCompare(t.relativePath)||e.line-t.line}function nN(e,t){let n=new Map;for(let i of t){let r=iN(i.relativePath);n.set(r,(n.get(r)??0)+1)}return[...n].sort(([i,r],[o,s])=>s-r||i.localeCompare(o)).slice(0,x0).map(([i])=>`codebaseiq search ${Ne(e)} --scope ${Ne(i)}`)}function iN(e){let t=e.split("/").filter(Boolean);if(t.length<=1)return e;let n=t.slice(0,-1),i=n.lastIndexOf("src");return i>=0?n.slice(0,Math.min(n.length,i+3)).join("/"):n.slice(0,Math.min(n.length,3)).join("/")}function rN(e,t,n){let i=t.callerFileMap([n],{semantic:!1}).get(n.symbolId)??new Set,r=[];for(let o of[...i].sort()){let s=n.leaf?Rn(e,o,n.leaf):[];if(s.length===0){r.push({file:o,line:null,enclosingSymbol:null});continue}let a=t.definitionsForFile(o);for(let l of s)r.push({file:o,line:l,enclosingSymbol:Ke(a,l)?.symbol??null})}return r}function oN(e,t){let n=e.all(`SELECT DISTINCT gs.symbol, def_d.relative_path AS from_file
72
+ `).trimEnd();return s.length>0?s:null}function _T(e,t,n){let i=Qi(e);if(i&&!BT(i))return i;let r=(t??"").trim();return r?_e(n)&&!r.endsWith("()")?`${r}()`:r:A(n)}function BT(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function Bu(e,t,n={}){let i=ib(e,t,n);if(i.kind!=="matched")return i;let{referenceEvidence:r,claimSupport:o,...s}=i;return s}function ib(e,t,n={}){let i=at(e,t);if(!i.match)return{kind:"missing",query:t};if(i.total>1)return{kind:"ambiguous",query:t,total:i.total,candidates:[{symbol:i.match.symbol,shortName:A(i.match.symbol),relativePath:i.match.relativePath,startLine:i.match.startLine},...i.candidates]};let r=i.match,o=$T(n.parts),s=o.includes("definition")||o.includes("references")?_a(e,r.symbol,{semantic:n.semantic,referenceContext:n.referenceContext}):{definitions:[],referencedBy:[],referenceEvidence:[],claimSupport:null},a=o.includes("callers")||o.includes("callees")?Eo(e,r.symbol,{semantic:n.semantic}):null,l=n.relatedSourceLines??80;return{kind:"matched",query:t,symbol:r.symbol,shortName:A(r.symbol),file:r.relativePath,parts:o,definition:o.includes("definition")?Ec(e,r.symbol):null,referenceWindows:o.includes("references")?OT(e,s.referencedBy):[],callers:o.includes("callers")?nb(e,a?.callers??[],l):[],callees:o.includes("callees")?nb(e,a?.callees??[],l):[],dependencies:o.includes("dependencies")?wo(e,r.relativePath):[],consumers:o.includes("consumers")?Lo(e,r.relativePath):[],referenceEvidence:s.referenceEvidence,claimSupport:s.claimSupport}}function OT(e,t){let n=t.filter(r=>r.sourceStartLine!==null&&r.sourceEndLine!==null&&r.source!==null).sort((r,o)=>r.relativePath.localeCompare(o.relativePath)||r.sourceStartLine-o.sourceStartLine||r.line-o.line),i=[];for(let r of n){let o=i[i.length-1];if(o&&o.relativePath===r.relativePath&&r.sourceStartLine<=o.endLine+1){o.endLine=Math.max(o.endLine,r.sourceEndLine),o.references.push(tb(r)),o.source=re(e,o.relativePath).slice(o.startLine,o.endLine+1).join(`
73
+ `);continue}i.push({relativePath:r.relativePath,startLine:r.sourceStartLine,endLine:r.sourceEndLine,source:r.source,references:[tb(r)]})}return i}function tb(e){return{line:e.line,enclosingSymbol:e.enclosingSymbol,enclosingShort:e.enclosingShort}}function $T(e){let t=e&&e.length>0?e:["definition","references"];return[...new Set(t)]}function nb(e,t,n){let i=[],r=new Set;for(let o of t){if(r.has(o.symbol))continue;r.add(o.symbol);let s=(o.file?W(e,o.file).find(l=>l.symbol===o.symbol):void 0)??at(e,o.symbol).match;if(!s)continue;let a=Np(e,s.relativePath,s.startLine,s.endLine,n);a&&i.push({...a,symbol:o.symbol,shortName:o.shortName,omittedLines:Math.max(0,s.endLine-a.endLine)})}return i}var lb=6;function rb(e,t,n){return`${e}\0${t}\0${n??t}`}function cb(e,t,n,i={}){let r=i.limit??lb;if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`next-anchor limit must be a positive safe integer; received ${r}`);let o=i.sourceAllowed??(()=>!0),s=new Map(t.nodes.map(C=>[C.id,C])),a=new Set(n.steps.map(C=>C.nodeId)),l=new Set(n.steps.flatMap(C=>{let L=ju(s.get(C.nodeId));return L?[L]:[]})),c=new Set;for(let C of n.steps)for(let L of C.behavior?.supportingDeclarations??[])l.add(L.symbol),c.add(rb(L.file,L.line,L.endLine));let u=C=>C.symbol!==null&&l.has(C.symbol)||c.has(rb(C.file,C.line,C.endLine)),d=new Map(n.steps.flatMap(C=>{if(!C.location)return[];let L=ju(s.get(C.nodeId));if(!L)return[];let w=W(e,C.location.file).find(R=>R.symbol===L);return w?[[C.id,w]]:[]})),m=new U(e).calleeMap([...d.values()],{additive:!1,semantic:!0}),f=[],p=new Set,g=new Set,h=0,b=0,v=0,y=0,I=0,E=0,S=0,x=0;for(let C of n.steps){if(!C.location||!C.behavior)continue;let L=t.edges.filter(N=>["call","runtime-boundary"].includes(N.kind)&&(N.fromNodeId===C.nodeId||N.toNodeId===C.nodeId)&&N.disposition!=="excluded"&&N.disposition!=="unsupported");for(let N of L){let K=N.toNodeId===C.nodeId,ne=K?N.fromNodeId:N.toNodeId;if(a.has(ne))continue;let fe=s.get(ne);if(!fe?.location||!o(fe.location.file))continue;let he=N.kind==="call"?Uu(e,fe):Hu(fe);if(!he||u(he))continue;let ce=zu(N,fe.location.file)??fe.location,be=re(e,ce.file)[ce.line]?.trim(),T=K?"upstream":"downstream",Z=N.kind==="runtime-boundary"?K?"runtime-producer":"runtime-consumer":K?"caller":"callee",Q=["call"],Se=Ou(N.evidence),it=Do(fe);f.push({anchor:{id:ni(C.id,ce.line,fe.id),status:Se,source:"graph-relation",direction:T,causalRole:Z,relationKind:N.kind,fromStepId:C.id,fromLabel:C.label,callsite:{file:ce.file,line:ce.line,endLine:ce.endLine??ce.line,text:be||`${fe.label} \u2192 ${C.label}`,signals:Q,calleeLeaf:it},alternatives:[he],alternativeCount:1,evidence:N.evidence}}),K&&(E+=1),N.kind==="runtime-boundary"&&(x+=1)}let w=t.edges.filter(N=>N.kind==="reference"&&N.fromNodeId===C.nodeId&&N.disposition!=="excluded"&&N.disposition!=="unsupported"&&!a.has(N.toNodeId));for(let N of w){let K=s.get(N.toNodeId);if(!K?.location||!o(K.location.file))continue;let ne=Uu(e,K);if(!ne||u(ne))continue;let fe=Do(K),he=zu(N,C.location.file)?.line,ce=C.behavior.lines.find(Q=>(he===void 0||he>=Q.line&&he<=Q.endLine)&&Q.text.includes(fe));if(!ce)continue;let be=db(ce.signals),T=be==="result-callback",Z=Ou(N.evidence);f.push({anchor:{id:ni(C.id,ce.line,K.id),status:Z,source:"graph-relation",direction:"downstream",causalRole:be,relationKind:"reference",fromStepId:C.id,fromLabel:C.label,callsite:{file:C.location.file,line:ce.line,endLine:ce.endLine,text:ce.text,signals:ce.signals,calleeLeaf:fe},alternatives:[ne],alternativeCount:1,evidence:N.evidence}}),T&&(S+=1)}let R=Dn(e,C.location.file,C.location.line,C.location.endLine??C.location.line),M=re(e,C.location.file),_=En(e,C.location.file,C.location.line,C.location.endLine??C.location.line);for(let N of R.targets){if(!o(N.definition.relativePath))continue;let K=ki(C.location.file,N.sourceLine,N.calleeLeaf);if(p.has(K))continue;p.add(K);let ne=$u(_.get(N.sourceLine)),fe={symbol:N.definition.symbol,label:N.definition.leaf,file:N.definition.relativePath,line:N.definition.startLine,endLine:N.definition.endLine};u(fe)||f.push({anchor:{id:ni(C.id,N.sourceLine,N.definition.symbol),status:"exact",source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:C.id,fromLabel:C.label,callsite:{file:C.location.file,line:N.sourceLine,endLine:N.sourceLine,text:M[N.sourceLine]?.trim()||`${N.calleeLeaf}()`,signals:ne,calleeLeaf:N.calleeLeaf},alternatives:[fe],alternativeCount:1,evidence:[{method:"scip-occurrence-callsite",strength:"exact",identity:N.definition.symbol,location:{file:C.location.file,line:N.sourceLine}}]}})}let D=C.behavior.lines.filter(N=>N.signals.includes("call"));if(D.length===0)continue;h+=1;let P=(te(e,C.location.file)?.callSites??[]).filter(N=>D.some(K=>N.line>=K.line&&N.line<=K.endLine));b+=P.length;let k=t.edges.filter(N=>N.kind==="call"&&N.fromNodeId===C.nodeId&&N.disposition!=="excluded"&&N.disposition!=="unsupported"),V=new Map;for(let N of k){let K=s.get(N.toNodeId);if(!K)continue;let ne=Do(K);V.set(ne,(V.get(ne)??0)+1)}let le=d.get(C.id),G=HT(e,le?m.get(le.symbolId)??[]:[]),X=UT(G);for(let N of G){if(!o(N.alternative.file)||u(N.alternative))continue;let K=Ba(N.alternative.label),ne=sb(P,D,K,N.row.callsiteLine,X.get(K)===1);if(!ne)continue;let fe=Mo(D,ne.line,K);if(!fe)continue;let he=ki(C.location.file,ne.line,K);if(p.has(he))continue;p.add(he);let ce=gb(N.row.source);f.push({anchor:{id:ni(C.id,ne.line,N.alternative.symbol??N.alternative.file),status:ce,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:C.id,fromLabel:C.label,callsite:{file:C.location.file,line:fe.line,endLine:fe.endLine,text:fe.text,signals:fe.signals,calleeLeaf:K},alternatives:[N.alternative],alternativeCount:1,evidence:[{method:N.row.source,strength:ce,identity:N.row.symbol,location:{file:C.location.file,line:ne.line}}]}})}for(let N of k){if(a.has(N.toNodeId))continue;let K=s.get(N.toNodeId);if(!K?.location||!o(K.location.file))continue;let ne=Do(K),fe=N.evidence.find(Q=>{let Se=Q.location;return Se!==null&&Se.file===C.location?.file&&Se.line>=0})?.location?.line,he=sb(P,D,ne,fe,V.get(ne)===1);if(!he)continue;let ce=Mo(D,he.line,ne);if(!ce)continue;let be=ki(C.location.file,he.line,ne);if(p.has(be))continue;p.add(be);let T=Hu(K);if(!T||u(T))continue;let Z=Ou(N.evidence);f.push({anchor:{id:ni(C.id,he.line,K.id),status:Z,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:C.id,fromLabel:C.label,callsite:{file:C.location.file,line:ce.line,endLine:ce.endLine,text:ce.text,signals:ce.signals,calleeLeaf:ne},alternatives:[T],alternativeCount:1,evidence:N.evidence}})}for(let N of P){let K=ki(C.location.file,N.line,N.calleeLeaf);if(p.has(K))continue;let ne=Mo(D,N.line,N.calleeLeaf);if(!ne)continue;let fe=nn(C.location.file,rn(e).get(N.calleeLeaf)??[]).flatMap(T=>W(e,T.file).filter(Z=>Z.symbol===T.symbol&&Z.isFunctionLike)).filter(T=>o(T.relativePath)&&!u({symbol:T.symbol,label:T.leaf,file:T.relativePath,line:T.startLine,endLine:T.endLine})),he=$a(fe.map(T=>({symbol:T.symbol,label:T.leaf??N.calleeLeaf,file:T.relativePath,line:T.startLine,endLine:T.endLine})));if(he.length===0){I+=1;continue}let ce=`${C.id}\0${N.line}\0${N.calleeLeaf}`;if(g.has(ce))continue;g.add(ce);let be=he.length>1;be?y+=1:v+=1,f.push({anchor:{id:ni(C.id,N.line,N.calleeLeaf),status:be?"ambiguous":"candidate",source:"leaf-identity-candidate",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:C.id,fromLabel:C.label,callsite:{file:C.location.file,line:ne.line,endLine:ne.endLine,text:ne.text,signals:ne.signals,calleeLeaf:N.calleeLeaf},alternatives:he.slice(0,3),alternativeCount:he.length,evidence:[]}})}}return fb(e,f,n.steps,r,{scannedBehaviorSteps:h,visibleCallsites:b,graphEvidencedCallsites:p.size,identityCandidateCallsites:v,ambiguousCallsites:y,unresolvedCallsites:I,upstreamCandidates:E,resultCandidates:S,runtimeCandidates:x},i.selectionTerms)}function ub(e,t,n){let i=new Map(t.nodes.map(r=>[r.id,r]));for(let r of n.steps)if(!(!r.behavior||!r.location))for(let o of t.edges){if(o.kind!=="reference"||o.fromNodeId!==r.nodeId||o.disposition==="excluded"||o.disposition==="unsupported")continue;let s=i.get(o.toNodeId);if(!s?.location||!Uu(e,s))continue;let a=Do(s),l=zu(o,r.location.file)?.line,c=r.behavior.lines.find(u=>(l===void 0||l>=u.line&&l<=u.endLine)&&u.text.includes(a));!c||db(c.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 db(e){return e.includes("call")&&e.some(t=>["return","mutation","shape","spread","binding"].includes(t))?"result-callback":"callable-reference"}function mb(e,t,n={}){let i=n.limit??lb;if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`next-anchor limit must be a positive safe integer; received ${i}`);let r=n.sourceAllowed??(()=>!0),o=[],s=t.map((f,p)=>({id:f.id,nodeId:f.id,order:p,role:"anchor",kind:"source-construct",label:f.label,location:{file:f.file,line:f.startLine,endLine:f.endLine},behavior:null})),a=t.map(f=>({file:f.file,startLine:f.startLine,endLine:f.endLine})),l=0,c=0,u=0,d=0,m=0;for(let f of t){let p=re(e,f.file),h=(te(e,f.file)?.callSites??[]).filter(S=>S.line>=f.startLine&&S.line<=f.endLine);l+=h.length;let b=En(e,f.file,f.startLine,f.endLine),v=Dn(e,f.file,f.startLine,f.endLine),y=new Set;for(let S of v.targets){if(!r(S.definition.relativePath)||a.some(w=>w.file===S.definition.relativePath&&w.startLine<=S.definition.startLine&&w.endLine>=S.definition.endLine))continue;let x=ki(f.file,S.sourceLine,S.calleeLeaf);y.add(x);let C=$u(b.get(S.sourceLine)),L={symbol:S.definition.symbol,label:S.definition.leaf,file:S.definition.relativePath,line:S.definition.startLine,endLine:S.definition.endLine};o.push({anchor:{id:ni(f.id,S.sourceLine,S.definition.symbol),status:"exact",source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:f.id,fromLabel:f.label,callsite:{file:f.file,line:S.sourceLine,endLine:S.sourceLine,text:p[S.sourceLine]?.trim()||`${S.calleeLeaf}()`,signals:C,calleeLeaf:S.calleeLeaf},alternatives:[L],alternativeCount:1,evidence:[{method:"scip-occurrence-callsite",strength:"exact",identity:S.definition.symbol,location:{file:f.file,line:S.sourceLine}}]}})}c+=v.resolvedCallsites;let I=Zn(e,f.file,{ranges:[{startLine:f.startLine,endLine:f.endLine}]}),E=new Map;for(let S of I.targets){let x=h.find(w=>w.line===S.line)?.calleeLeaf??S.calleeLeaf,C=ki(f.file,S.line,x),L=E.get(C)??[];L.push(S),E.set(C,L)}for(let[S,x]of E){if(y.has(S))continue;y.add(S);let C=x.filter(D=>r(D.targetFile)&&!a.some(P=>P.file===D.targetFile&&P.startLine<=D.targetStartLine&&P.endLine>=D.targetEndLine));if(C.length===0)continue;let L=C[0],w=h.find(D=>D.line===L.line)?.calleeLeaf??L.calleeLeaf,R=$u(b.get(L.line)),M=$a(C.map(D=>({symbol:D.targetSymbol??null,label:D.calleeLeaf,file:D.targetFile,line:D.targetStartLine,endLine:D.targetEndLine}))),_=C.some(D=>(D.resolutionAlternativeCount??0)>1)?"candidate":C.every(D=>D.strength==="exact")?"exact":"derived";o.push({anchor:{id:ni(f.id,L.line,M.map(D=>`${D.file}:${D.line}`).join("|")),status:M.length>1?"ambiguous":_,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:f.id,fromLabel:f.label,callsite:{file:f.file,line:L.line,endLine:L.line,text:p[L.line]?.trim()||`${L.calleeLeaf}()`,signals:R,calleeLeaf:w},alternatives:M.slice(0,3),alternativeCount:M.length,evidence:C.map(D=>({method:D.resolution==="constructed-member-receiver"?"ast-constructed-member-callsite":D.resolution==="factory-callback-member"?"ast-factory-callback-callsite":D.resolution==="imported-service-object-member"?"ast-service-member-callsite":"ast-import-member-callsite",strength:_,identity:D.targetSymbol??`${D.targetFile}:${D.targetStartLine}-${D.targetEndLine}`,location:{file:f.file,line:L.line}}))}})}c+=E.size;for(let S of h){let x=ki(f.file,S.line,S.calleeLeaf);y.has(x)||(m+=1)}}return fb(e,o,s,i,{scannedBehaviorSteps:t.length,visibleCallsites:l,graphEvidencedCallsites:c,identityCandidateCallsites:u,ambiguousCallsites:d,unresolvedCallsites:m,upstreamCandidates:0,resultCandidates:0,runtimeCandidates:0})}function fb(e,t,n,i,r,o=[]){let s=zT(t).sort(pb),a=s.filter(p=>jT(e,p)).slice(0,i),l=new Set(a.map(p=>p.anchor.id)),c=s.filter(p=>!l.has(p.anchor.id)),u=a.map(p=>p.anchor),d=c.map(p=>p.anchor),m=$a(u.flatMap(p=>p.alternativeCount===1?p.alternatives:[])),f=$a(d.flatMap(p=>p.alternativeCount===1?p.alternatives:[]));return{anchors:u,withheldAnchors:d,candidateAnchors:s.length,omittedAnchors:Math.max(0,s.length-u.length),...r,inspectCommand:m.length===0?null:`codebaseiq inspect ${m.map(ab).join(" ")} --view behavior`,remainingInspectCommands:KT(f,8).map(p=>`codebaseiq inspect ${p.map(ab).join(" ")} --view behavior`)}}function pb(e,t){let n=e.anchor.alternatives[0],i=t.anchor.alternatives[0];return Oa(e.anchor.status)-Oa(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(i?.file??"")||(n?.line??0)-(i?.line??0)||e.anchor.id.localeCompare(t.anchor.id)}function jT(e,t){if(t.anchor.alternativeCount!==1)return!0;let n=t.anchor.alternatives[0],i=n.endLine??n.line;return re(e,n.file).slice(n.line,i+1).join(`
74
+ `).length<=2e4}function $u(e){return e?.includes("call")?[...e]:["call",...e??[]]}function HT(e,t){let n=new Map;for(let i of t){let r=W(e,i.file).find(a=>a.symbol===i.symbol&&a.isFunctionLike);if(!r)continue;let o={symbol:r.symbol,label:r.leaf,file:r.relativePath,line:r.startLine,endLine:r.endLine},s=n.get(r.symbol);!s||ob(i.source)>ob(s.row.source)?n.set(r.symbol,{row:{...i,...i.callsiteLine===void 0&&s?.row.callsiteLine!==void 0?{callsiteLine:s.row.callsiteLine}:{}},alternative:o}):s.row.callsiteLine===void 0&&i.callsiteLine!==void 0&&n.set(r.symbol,{...s,row:{...s.row,callsiteLine:i.callsiteLine}})}return[...n.values()]}function UT(e){let t=new Map;for(let n of e){let i=Ba(n.alternative.label);t.set(i,(t.get(i)??0)+1)}return t}function gb(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function ob(e){return gb(e)==="exact"?2:1}function Mo(e,t,n){return e.find(i=>t>=i.line&&t<=i.endLine&&i.text.includes(n))??e.find(i=>t>=i.line&&t<=i.endLine)??null}function sb(e,t,n,i,r){if(i!==void 0)return e.find(s=>s.line===i&&s.calleeLeaf===n&&Mo(t,s.line,n)!==null)??null;let o=e.filter(s=>s.calleeLeaf===n&&Mo(t,s.line,s.calleeLeaf)!==null);return r&&o.length===1?o[0]:null}function Do(e){let t=e.attributes.leaf;if(typeof t=="string"&&t.length>0)return Ba(t);let n=e.label.slice(e.label.lastIndexOf(":")+1);return Ba(n)}function Ba(e){return e.replace(/\(\)$/u,"").replace(/^#/u,"")}function ju(e){if(e?.kind!=="symbol"||!e.id.startsWith("symbol:"))return null;try{return decodeURIComponent(e.id.slice(7))}catch{return null}}function Hu(e){return e.location?{symbol:ju(e),label:e.label,file:e.location.file,line:e.location.line,endLine:e.location.endLine??null}:null}function Uu(e,t){let n=Hu(t);return n?.symbol&&W(e,n.file).some(r=>r.symbol===n.symbol&&r.isFunctionLike)?n:null}function zu(e,t){return e.evidence.find(n=>n.location?.file===t)?.location??e.evidence.find(n=>n.location!==null)?.location??null}function Ou(e){let t={exact:5,derived:4,mixed:3,candidate:2,unknown:1};return e.reduce((n,i)=>t[i.strength]>t[n]?i.strength:n,"unknown")}function zT(e){let t=new Map;for(let n of e){let r=n.anchor.alternatives[0]?.symbol??`${n.anchor.callsite.file}:${n.anchor.callsite.line}:${n.anchor.callsite.calleeLeaf}`,o=t.get(r);(!o||qT(n,o)<0)&&t.set(r,n)}return[...t.values()]}function qT(e,t){return Oa(e.anchor.status)-Oa(t.anchor.status)||e.anchor.alternativeCount-t.anchor.alternativeCount||pb(e,t)}function Oa(e){return{exact:0,derived:1,mixed:2,candidate:3,unknown:4,ambiguous:5}[e]}function $a(e){let t=new Map;for(let n of e)t.set(n.symbol??`${n.file}:${n.line}`,n);return[...t.values()].sort((n,i)=>n.file.localeCompare(i.file)||n.line-i.line||n.label.localeCompare(i.label))}function ab(e){return`--at ${GT(`${e.file}:${e.line+1}`)}`}function KT(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}function GT(e){return`'${e.replaceAll("'","'\\''")}'`}function ki(e,t,n){return`${e}\0${t}\0${n}`}function ni(e,t,n){return["next-anchor",e,String(t),n].map(encodeURIComponent).join(":")}var Ib=6,WT=12,VT=48,JT=2e4,hb=12,Ni=Number.MAX_SAFE_INTEGER,YT=["definition","callers","callees"],Vu={search:12,"exact-source":24,definition:24,caller:8,callee:8,"production-reference":6,"test-reference":2,dependency:6,consumer:6};function XT(e,t){if(t.cursor)throw new Error("Inspect no longer accepts semantic packet cursors. Run the original inspect selectors again.");let n=ZT(t),i=nF(e,n),r=i.candidates.sort((M,_)=>qu(M,_));n.view==="behavior"&&oF(e,r),sF(e,r),n.view==="behavior"&&iF(e,r);let o=Ph(r.map(M=>Gu(M,n.view)),n.evidenceBudgets,(M,_)=>qu(M.candidate,_.candidate)),{selected:s,omitted:a}=xa(o.selected,n.maxUnits,n.maxCharacters,(M,_)=>qu(M.candidate,_.candidate),n.view==="source"),l=s.map(M=>M.candidate),c=[...o.omitted,...a].map(M=>M.candidate),u=l.map(gF),d=Gs(l.map(M=>M.kind==="source"?M.bindingClosure:void 0),l.filter(M=>M.kind==="source").map(M=>({relativePath:M.relativePath,startLine:M.startLine,endLine:M.endLine}))),m=u.reduce((M,_)=>M+(_.kind==="source"?bF(_.source):0),0),f=u.reduce((M,_)=>M+(_.kind==="source"?_.source.length:0),0),p=u.reduce((M,_)=>M+Lb(_,n.view),0),g=u.filter(M=>M.kind==="source"&&(M.roles.includes("search")||M.roles.includes("location"))).map(hF),h=r.filter(M=>M.kind==="source"&&(M.roles.includes("search")||M.roles.includes("location"))).length,b=u.filter(M=>M.kind==="source"&&(M.roles.includes("search")||M.roles.includes("location"))).length,v=i.searches.map(M=>cF(M,r,l)),y=uF(c),I=i.locations.every(M=>M.matched)&&i.evidence.every(M=>M.kind==="matched")&&i.searches.every(M=>mF(M.textCoverage))&&c.every(M=>!M.roles.some(_=>_==="location"||_==="definition")),E=v.reduce((M,_)=>M+_.omittedMatches,0),S=c.length===0&&E===0,x=S?void 0:wb(n,!0),C=aF(n,c),L=QT(S,I,c.length+E,C,v,x),w=r.filter(M=>n.view==="behavior"&&M.kind==="source"&&M.roles.some(_=>_==="location"||_==="definition"||_==="search")).map(M=>({id:`inspect:${M.relativePath}:${M.startLine}-${M.endLine}`,label:M.ownerShort??`${M.relativePath}:${M.startLine+1}`,file:M.relativePath,startLine:M.startLine,endLine:M.endLine})),R=w.length>0?mb(e,w):void 0;return{searches:v,evidence:i.evidence,locations:i.locations,slices:g,candidateSlices:h,omittedSlices:h-b,maxSlices:h,maxTotalLines:m,units:u,candidateUnits:r.length,omittedUnits:c.length,maxUnits:n.maxUnits,maxCharacters:n.maxCharacters,returnedLines:m,returnedCharacters:f,returnedViewCharacters:p,view:n.view,omissionGroups:C,packetCoverage:{mode:S?"complete":"bounded",candidateUnits:r.length,returnedUnits:u.length,omittedUnits:c.length,omittedByRole:y,exactSelectorsComplete:I,maxUnits:n.maxUnits,maxCharacters:n.maxCharacters,channels:dF(r,l,n.evidenceBudgets,n.view),...x?{expansionCommand:x}:{}},stoppingSummary:L,...R&&R.candidateAnchors>0?{causalFrontier:R}:{},bindingClosure:d,continuation:null}}function QT(e,t,n,i,r,o){let s=ft([...i.map(a=>a.drillCommand),...r.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 ZT(e){let t=Ku(e.searches),n=Ku(e.symbols),i=Ku(e.locations),r=t.length+n.length+i.length;if(r===0)throw new Error("inspect requires at least one --search, --symbol, or --at selector.");if(r>24)throw new RangeError(`inspect accepts at most ${24} selectors; received ${r}.`);let o=e.evidence??{};if(e.unitLines!==void 0&&ii(e.unitLines,"unitLines"),e.totalLines!==void 0&&ii(e.totalLines,"totalLines"),e.sliceLimit!==void 0&&ii(e.sliceLimit,"sliceLimit"),e.maxCharacters!==void 0&&ii(e.maxCharacters,"maxCharacters"),e.maxUnits!==void 0&&ii(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:i,...e.scope?.trim()?{scope:e.scope.trim()}:{},context:xb(e.context??Ib,"context"),searchLimit:ii(e.searchLimit??(s?Ni:WT),"searchLimit"),maxUnits:ii(s?Ni:e.maxUnits??VT,"maxUnits"),maxCharacters:ii(s?Ni:e.maxCharacters??JT,"maxCharacters"),evidenceBudgets:s?tF():eF(e.evidenceBudgets??Vu),view:e.view??"source",evidence:{...o.parts?{parts:[...o.parts]}:n.length>0?{parts:[...YT]}:{},...o.referenceContext!==void 0?{referenceContext:xb(o.referenceContext,"referenceContext")}:{},relatedSourceLines:o.relatedSourceLines??60,...o.semantic!==void 0?{semantic:o.semantic}:{}}}}function eF(e){let t={...Vu};for(let[n,i]of Object.entries(e)){if(!(n in t))throw new Error(`Unknown inspect evidence channel: ${n}.`);if(!Number.isSafeInteger(i)||(i??-1)<0)throw new RangeError(`Evidence budget ${n} must be a non-negative safe integer; received ${i}.`);t[n]=i}return t}function tF(){return Object.fromEntries(Object.keys(Vu).map(e=>[e,Ni]))}function nF(e,t){let n=[],i=0,r=t.searches.map(c=>{let u=pu(e,c,{scope:t.scope,context:0,limit:t.searchLimit,ranking:"structural"});return{pattern:c,result:u,matches:u.matches}}),o=Math.max(0,...r.map(c=>c.matches.length));for(let c=0;c<o;c+=1)for(let u of r){let d=u.matches[c];if(!d)continue;let m=Jn(e,d.relativePath,d.focusLine,Ni,t.context);m&&br(e,n,m,"search",`search:${u.pattern}`,d.ownerSymbol,d.ownerShort,1,i++)}let s=r.map(({pattern:c,result:u})=>{let d=u.omittedMatches>0?Eb(c,t.scope):void 0,m=u.fileCoverage??[],f=fF(c,m,t.scope);return{pattern:c,matchingLines:u.matchingLines,returnedMatches:u.matches.length,omittedMatches:u.omittedMatches,matchingFiles:m.length,returnedFiles:m.filter(p=>p.returnedMatches>0).length,omittedFiles:m.filter(p=>p.returnedMatches===0).length,candidateUnits:0,selectedUnits:0,omittedUnits:0,scopeHints:f.slice(0,hb),omittedScopeHints:Math.max(0,f.length-hb),textCoverage:u.textCoverage,...d?{exactFollowup:d}:{}}}),a=t.locations.map(c=>{let u=yF(c),d=u?dt(e,u.path):null,m=d?Jn(e,d,u.line-1,Ni,t.context):null;return m&&br(e,n,m,"location",`at:${c}`,null,null,0,i++),{target:c,matched:m!==null}}),l=t.symbols.map(c=>Bu(e,c,t.evidence));for(let c of l)if(c.kind==="matched"){if(c.definition){let u=Jn(e,c.definition.relativePath,c.definition.startLine,Ni,t.context);u&&br(e,n,u,"definition",`definition:${c.shortName}`,c.symbol,c.shortName,0,i++)}for(let u of c.referenceWindows){let d=u.references[0];br(e,n,{...u,focusLine:d?.line??u.startLine,unitType:null,unitStartLine:u.startLine,unitEndLine:u.endLine,omittedLines:0},"reference",`reference:${c.shortName}`,d?.enclosingSymbol??null,d?.enclosingShort??null,J(u.relativePath)==="test"?5:4,i++,u.references.map(m=>m.line),c.symbol)}for(let u of c.callers)bb(e,n,u,"caller",c,2,i++);for(let u of c.callees)bb(e,n,u,"callee",c,3,i++);for(let u of c.dependencies)Sb(e,n,"dependency",c.file,u.relativePath,c.symbol,t.context,6,i++);for(let u of c.consumers)Sb(e,n,"consumer",u.relativePath,c.file,c.symbol,t.context,7,i++)}return{searches:s,evidence:l,locations:a,candidates:n}}function qu(e,t){return e.priority-t.priority||t.roles.length-e.roles.length||t.reasons.length-e.reasons.length||yb(J(e.relativePath))-yb(J(t.relativePath))||e.sequence-t.sequence}function yb(e){switch(e){case"entry":case"source":case"worker":return 0;case"barrel":return 1;case"test":return 2}}function Gu(e,t){return{candidate:e,priority:e.priority,sequence:e.sequence,relativePath:e.relativePath,fileKind:J(e.relativePath),evidenceCharacters:Lb(e,t),roles:e.roles,reasons:e.reasons,symbols:e.symbols,behaviorSignals:e.kind==="source"?e.behavior?.signals??[]:[],channel:Wu(e)}}function Wu(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")?J(e.relativePath)==="test"?"test-reference":"production-reference":t.includes("dependency")?"dependency":t.includes("consumer")?"consumer":"search"}function iF(e,t){let n=t.filter(r=>r.kind==="source"),i=zr(e,{files:ft(n.map(r=>r.relativePath))});for(let r of n){r.behavior=nr(e,r.relativePath,r.startLine,r.endLine,r.focusLines)??void 0;let o=i.filter(a=>a.source.file===r.relativePath&&a.source.startLine<=r.endLine&&a.source.endLine>=r.startLine),s=o.filter(a=>!rF(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(l=>({name:l.name,value:l.value,evidence:l.evidence})),derivation:{kind:a.derivation.kind,rule:a.derivation.rule,sourceSpans:a.derivation.sourceSpans.length}}));r.runtimeFacts=s.length>0?s:void 0}}function rF(e,t){if(e.strength!=="candidate"||e.protocol!=="http")return!1;let n=e.keyParts.find(r=>r.name==="path")?.value,i=e.keyParts.find(r=>r.name==="method")?.value;return n?t.some(r=>{if(r===e||r.action!==e.action||r.role!==e.role||r.source.startLine!==e.source.startLine||r.derivation.rule!=="http.mount-prefix")return!1;let o=r.keyParts.find(a=>a.name==="path")?.value,s=r.keyParts.find(a=>a.name==="method")?.value;return!!(o&&o!==n&&o.endsWith(n)&&(!i||i===s))}):!1}function oF(e,t){for(let n of t){if(n.kind!=="source")continue;let i=yt(e,n.relativePath,n.startLine,n.endLine,n.focusLines);i.startLine===n.startLine&&i.endLine===n.endLine||(n.startLine=i.startLine,n.endLine=i.endLine,n.source=re(e,n.relativePath).slice(i.startLine,i.endLine+1).join(`
75
+ `),n.unitStartLine=i.startLine,n.unitEndLine=i.endLine,n.omittedLines=0)}}function sF(e,t){for(let n of t)n.kind==="source"&&(n.bindingClosure=tr(e,n.relativePath,n.startLine,n.endLine))}function aF(e,t){let n=new Map;for(let i of t){let r=ja(i.relativePath),o=Wu(i),s=[...i.roles].sort().join(","),a=i.kind==="path"?i.relationship:"",l=`${r}|${o}|${s}|${a}`,c=n.get(l)??[];c.push(i),n.set(l,c)}return[...n.entries()].map(([i,r])=>{let o=r[0],s=ft(r.flatMap(l=>[...l.roles])).sort(),a=ft(r.flatMap(l=>l.kind==="source"?l.behavior?.signals??[]:[])).sort();return{id:`g-${Rb("sha256").update(i).digest("hex").slice(0,8)}`,scope:ja(o.relativePath),channel:Wu(o),roles:s,behaviorSignals:a,candidateUnits:r.length,sourceCharacters:r.reduce((l,c)=>l+(c.kind==="source"?c.source.length:0),0),anchors:r.map(l=>({relativePath:l.relativePath,line:l.kind==="source"?l.focusLine:0,ownerShort:l.kind==="source"?l.ownerShort:null,roles:[...l.roles],behaviorSignals:l.kind==="source"?[...l.behavior?.signals??[]]:[]})),drillCommand:lF(e,r)}}).sort((i,r)=>r.candidateUnits-i.candidateUnits||r.sourceCharacters-i.sourceCharacters||i.scope.localeCompare(r.scope)||i.id.localeCompare(r.id))}function lF(e,t){let n=ft(t.flatMap(o=>o.reasons.filter(s=>s.startsWith("search:")).map(s=>s.slice(7)))),i=ja(t[0].relativePath);if(n.length>0&&t.every(o=>o.kind==="source"&&o.roles.includes("search"))){let o=["codebaseiq inspect"];for(let s of n)o.push(`--search ${$t(s)}`);return o.push(`--scope ${$t(i)}`,"--full"),e.view==="behavior"&&o.push("--view behavior"),o.join(" ")}let r=t.filter(o=>o.kind==="source");if(r.length>0&&r.length<=24){let o=["codebaseiq inspect"];for(let s of r)o.push(`--at ${$t(`${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:wb(e,!0)}function cF(e,t,n){let i=`search:${e.pattern}`,r=t.filter(a=>a.reasons.includes(i)).length,o=new Set(n),s=t.filter(a=>a.reasons.includes(i)&&o.has(a)).length;return{...e,candidateUnits:r,selectedUnits:s,omittedUnits:r-s}}function uF(e){let t={};for(let n of e)for(let i of n.roles)t[i]=(t[i]??0)+1;return t}function dF(e,t,n,i){let r=e.map(s=>Gu(s,i).channel),o=t.map(s=>Gu(s,i).channel);return Object.fromEntries(Object.keys(n).map(s=>{let a=r.filter(c=>c===s).length,l=o.filter(c=>c===s).length;return[s,{candidateUnits:a,returnedUnits:l,omittedUnits:a-l,maxUnits:n[s]}]}))}function mF(e){return!!(e&&e.skippedUnreadablePaths.length===0&&e.skippedOversizedPaths.length===0)}function fF(e,t,n){let i=new Map;for(let r of t){let o=ja(r.relativePath),s=i.get(o)??{matchingLines:0,returnedMatches:0};s.matchingLines+=r.matchingLines,s.returnedMatches+=r.returnedMatches,i.set(o,s)}return[...i.entries()].map(([r,o])=>({scope:r,...o,exactFollowup:Eb(e,r||n)})).sort((r,o)=>o.matchingLines-r.matchingLines||o.returnedMatches-r.returnedMatches||r.scope.localeCompare(o.scope))}function ja(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}function Eb(e,t){return`codebaseiq inspect --search ${$t(e)}${t?` --scope ${$t(t)}`:""} --full`}function wb(e,t){let n=["codebaseiq inspect"];for(let i of e.searches)n.push(`--search ${$t(i)}`);for(let i of e.symbols)n.push(`--symbol ${$t(i)}`);for(let i of e.locations)n.push(`--at ${$t(i)}`);return e.scope&&n.push(`--scope ${$t(e.scope)}`),e.context!==Ib&&n.push(`--context ${e.context}`),e.evidence.parts&&n.push(`--include ${$t(e.evidence.parts.join(","))}`),t&&n.push("--full"),e.view==="behavior"&&n.push("--view behavior"),n.join(" ")}function bb(e,t,n,i,r,o,s){br(e,t,{...n,unitType:null,unitStartLine:n.startLine,unitEndLine:n.endLine+n.omittedLines},i,`${i}:${r.shortName}`,n.symbol,n.shortName,o,s,[n.focusLine],r.symbol)}function Sb(e,t,n,i,r,o,s,a,l){let c=`${i} -> ${r}`,u=Ce(e,i).filter(h=>h.sourcePath===r),d=re(e,i),m=pF(d,u,r),f=m===null?null:na(e,i,m,Math.min(s,4));if(f){br(e,t,{...f,unitType:null,unitStartLine:f.startLine,unitEndLine:f.endLine,omittedLines:0},n,`${n}:${c}`,null,null,a,l,[f.focusLine],o);return}let p=`codebaseiq inspect --search ${$t(Db(r))} --scope ${$t(i)}`,g=t.find(h=>h.kind==="path"&&h.relativePath===i&&h.relationship===c);if(g){g.roles=ft([...g.roles,n]),g.reasons=ft([...g.reasons,`${n}:${c}`]),g.symbols=ft([...g.symbols,o]),g.priority=Math.min(g.priority,a);return}t.push({kind:"path",roles:[n],relativePath:i,relationship:c,reasons:[`${n}:${c}`],symbols:[o],exactFollowup:p,priority:a,sequence:l})}function pF(e,t,n){let i=ft(t.flatMap(l=>[l.importedName,l.localName??""]).filter(l=>l.length>1)),r=Db(n).replace(/\.[^.]+$/u,""),o=ft([...i,r]).filter(Boolean),s=/\b(?:from|import|include|require|use)\b/u,a=e.findIndex(l=>s.test(l)&&o.some(c=>l.includes(c)));return a>=0?a:null}function br(e,t,n,i,r,o,s,a,l,c=[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),f=Math.max(d.endLine,n.endLine);d.startLine=m,d.endLine=f,d.source=re(e,n.relativePath).slice(m,f+1).join(`
76
+ `),d.focusLine=Math.min(d.focusLine,n.focusLine),d.focusLines=Cb([...d.focusLines,...c]),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=ft([...d.reasons,r]),d.roles=ft([...d.roles,i]),d.symbols=ft([...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:[r],focusLines:Cb(c),ownerSymbol:o,ownerShort:s,roles:[i],symbols:u?[u]:[],priority:a,sequence:l})}function gF(e){if(e.kind==="path"){let{priority:o,sequence:s,...a}=e;return{...a,id:vb(a)}}let{priority:t,sequence:n,bindingClosure:i,...r}=e;return{...r,id:vb(r),omittedCharacters:0}}function hF(e){let{kind:t,id:n,roles:i,symbols:r,omittedCharacters:o,behavior:s,runtimeFacts:a,...l}=e;return l}function vb(e){return Rb("sha256").update(JSON.stringify(e)).digest("hex").slice(0,16)}function yF(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 Ku(e){return ft((e??[]).map(t=>t.trim()).filter(Boolean))}function ft(e){return[...new Set(e)]}function Cb(e){return ft(e).sort((t,n)=>t-n)}function bF(e){return e.length===0?0:e.split(`
77
+ `).length}function Lb(e,t){if(e.kind==="path")return e.relationship.length+e.exactFollowup.length;let n="bindingClosure"in e?gp(e.bindingClosure):0,i=(e.runtimeFacts??[]).reduce((r,o)=>r+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((r,o)=>r+o.text.length+o.signals.join(",").length+12,0)+e.behavior.testCases.reduce((r,o)=>r+o.length+2,0)+i+n:e.source.length+n+i}function Db(e){return e.split("/").at(-1)??e}function $t(e){return`'${e.replaceAll("'","'\\''")}'`}function ii(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new RangeError(`${t} must be a positive safe integer; received ${e}`);return e}function xb(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 SF}from"path";function vF(e,t){let n=t.className,i=at(e,n);return i.match?i.total>1?{kind:"ambiguous",query:n,total:i.total,candidates:[Mb(i.match),...i.candidates]}:{kind:"matched",query:n,owner:xF(i.match),methods:CF(e,i.match)}:{kind:"missing",query:n,suggestions:Ns(e,n,5)}}function CF(e,t){let n=Y(t.symbol),r=new U(e).definitionsForFile(t.relativePath).filter(l=>st(l.symbol)),o=r.filter(l=>l.parentTypeName===n||l.symbol.includes(n)),a=(o.length>0?o:RF(SF(t.relativePath))===n?r.filter(l=>l.symbol.includes("<invalid-global-code>")):[]).map(l=>({startLine:l.startLine,endLine:l.endLine,name:Y(l.symbol)}));return ye(t.relativePath)!=="clojure"?a:EF(a,IF(e,t))}function Mb(e){return{symbol:e.symbol,shortName:A(e.symbol),relativePath:e.relativePath,startLine:e.startLine}}function xF(e){return{...Mb(e),endLine:e.endLine}}function RF(e){return e.replace(/\.[^.]+$/,"")}function IF(e,t){let n=Y(t.symbol);return n?(te(e,t.relativePath)?.clojureMembers??[]).filter(i=>i.ownerName===n).map(i=>({startLine:i.startLine,endLine:i.endLine,name:i.memberName})):[]}function EF(e,t){let n=new Map;for(let i of[...e,...t])n.set(`${i.name}:${i.startLine}:${i.endLine}`,i);return[...n.values()].sort((i,r)=>i.startLine-r.startLine||i.endLine-r.endLine)}import{createHash as gN}from"crypto";var Pb=["call","contract-symbol","import","reference","runtime-boundary"],wF={call:[{family:"control",subtype:"call"}],"contract-symbol":[{family:"contract",subtype:"uses-contract-symbol"}],import:[{family:"identity",subtype:"imports"}],reference:[{family:"identity",subtype:"references"}]},LF={"structural-membership":[{family:"identity",subtype:"contains"}],"boundary-observation":[{family:"identity",subtype:"owns-runtime-observation"}],"external-import":[{family:"identity",subtype:"imports-external"}]};function Tb(e){if(e.kind!=="runtime-boundary")return Fb(wF[e.kind]);let t=e.fromBoundaryParticipant?.protocol??e.toBoundaryParticipant?.protocol,n={crossesRuntimeBoundary:!0,...t?{protocol:t}:{},...e.runtimeBoundaryKey?{runtimeKey:e.runtimeBoundaryKey}:{}},i=[{family:"control",subtype:"runtime-handoff",context:n}];return e.evidence==="runtime-boundary:carrier.discriminator"&&(i.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}:{}}}),i.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"&&i.push({family:"temporal",subtype:"enqueue-before-consume",context:{...n},attributes:{producerAction:e.fromBoundaryParticipant.action,consumerAction:e.toBoundaryParticipant.action,retryPolicy:"unknown"}}),i}function Ha(e){return Fb(LF[e])}function Fb(e){return e.map(t=>({...t,...t.context?{context:{...t.context}}:{},...t.attributes?{attributes:{...t.attributes}}:{}}))}import{join as ZF}from"path";import{createRequire as DF}from"module";import{resolve as To}from"path";var MF=DF(import.meta.url),Po;function Nb(e,t,n){let i=PF();if(!i)return Ju("The TypeScript compiler runtime is unavailable.");let r=TF(i,e,t),o=r.getSourceFile(To(t))??r.getSourceFile(t);if(!o)return Ju(`The TypeScript compiler did not materialize ${t}.`);let s={ts:i,sourceFile:o,checker:r.getTypeChecker(),points:new Map,edges:new Map,unsupported:new Set,nextCfgId:0},a=kF(i,o,n);if(a.length===0)return Ju("No function-like construct intersects the selected source range.");let l=new Map(a.map(d=>[d,NF(o,d)])),c=a.map(d=>_F(s,d,AF(i,d,l),l.get(d)));for(let d of c)BF(s,d),HF(s,d),qF(s,d);GF(s,c);let u=[...s.unsupported].sort();return{points:[...s.points.values()].map(({node:d,...m})=>m).sort(QF),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 PF(){if(Po!==void 0)return Po;try{Po=MF("typescript")}catch{Po=Os()?.ts??null}return Po}function TF(e,t,n){let i=To(n),r={target:e.ScriptTarget.ESNext,module:e.ModuleKind.NodeNext,moduleResolution:e.ModuleResolutionKind.NodeNext,skipLibCheck:!0,noResolve:!0},o=e.createSourceFile(i,t,r.target,!0,FF(e,i)),s=e.createCompilerHost(r,!0),a=s.getSourceFile.bind(s),l=s.readFile.bind(s),c=s.fileExists.bind(s);return s.getSourceFile=(u,d,m,f)=>To(u)===i?o:a(u,d,m,f),s.readFile=u=>To(u)===i?t:l(u),s.fileExists=u=>To(u)===i||c(u),e.createProgram([i],r,s)}function FF(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 kF(e,t,n){let i=[],r=o=>{if(Ab(e,o)){let s=t.getLineAndCharacterOfPosition(o.getStart(t)).line,a=t.getLineAndCharacterOfPosition(o.getEnd()).line;(!n||s<=n.endLine&&a>=n.startLine)&&i.push(o)}o.forEachChild(r)};return t.forEachChild(r),i.sort((o,s)=>o.getStart(t)-s.getStart(t))}function Ab(e,t){return e.isFunctionLike(t)&&"body"in t&&t.body!==void 0}function NF(e,t){return`callable:${encodeURIComponent(e.fileName)}:${t.getStart(e)}:${t.getEnd()}`}function AF(e,t,n){for(let i=t.parent;i;i=i.parent)if(Ab(e,i)&&n.has(i))return n.get(i);return null}function _F(e,t,n,i){let r=new Map,o=et(e,r,"exit",null),s=t.body,a=o.id;if(s&&e.ts.isBlock(s))a=Yu(e,r,[...s.statements],o.id,{breakTarget:null,continueTarget:null});else if(s){let c=et(e,r,"statement",s);Be(r,c.id,o.id),a=c.id}let l=et(e,r,"entry",t);return Be(r,l.id,a),{id:i,node:t,parentId:n,cfg:r,entryId:l.id,exitId:o.id}}function Yu(e,t,n,i,r){let o=i;for(let s=n.length-1;s>=0;s-=1)o=Ai(e,t,n[s],o,r);return o}function Ai(e,t,n,i,r){let o=e.ts;if(o.isBlock(n))return Yu(e,t,[...n.statements],i,r);if(o.isIfStatement(n)){let a=et(e,t,"predicate",n.expression),l=Ai(e,t,n.thenStatement,i,r),c=n.elseStatement?Ai(e,t,n.elseStatement,i,r):i;return Be(t,a.id,l),Be(t,a.id,c),a.id}if(o.isWhileStatement(n)){let a=et(e,t,"predicate",n.expression),l=Ai(e,t,n.statement,a.id,{breakTarget:i,continueTarget:a.id});return Be(t,a.id,l),Be(t,a.id,i),a.id}if(o.isDoStatement(n)){let a=et(e,t,"predicate",n.expression),l=Ai(e,t,n.statement,a.id,{breakTarget:i,continueTarget:a.id});return Be(t,a.id,l),Be(t,a.id,i),l}if(o.isForStatement(n)){let a=et(e,t,"predicate",n.condition??n),l=n.incrementor?et(e,t,"statement",n.incrementor):null;l&&Be(t,l.id,a.id);let c=l?.id??a.id,u=Ai(e,t,n.statement,c,{breakTarget:i,continueTarget:c});if(Be(t,a.id,u),n.condition&&Be(t,a.id,i),!n.initializer)return a.id;let d=et(e,t,"statement",n.initializer);return Be(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=et(e,t,"predicate",n.expression),l=et(e,t,"statement",n.initializer),c=Ai(e,t,n.statement,a.id,{breakTarget:i,continueTarget:a.id});return Be(t,a.id,l.id),Be(t,a.id,i),Be(t,l.id,c),a.id}if(o.isSwitchStatement(n)){e.unsupported.add("switch fallthrough is represented conservatively; discriminant-to-case value refinement is unsupported.");let a=et(e,t,"predicate",n.expression),l=i,c=[];for(let u=n.caseBlock.clauses.length-1;u>=0;u-=1){let d=n.caseBlock.clauses[u];l=Yu(e,t,[...d.statements],l,{...r,breakTarget:i}),c.push(l)}for(let u of c)Be(t,a.id,u);return Be(t,a.id,i),a.id}if(o.isReturnStatement(n)||o.isThrowStatement(n)){let a=et(e,t,"statement",n),l=[...t.values()].find(c=>c.kind==="exit");return Be(t,a.id,l.id),a.id}if(o.isBreakStatement(n)){let a=et(e,t,"statement",n);return r.breakTarget||e.unsupported.add("A break statement could not be attached to a structured target."),Be(t,a.id,r.breakTarget??i),a.id}if(o.isContinueStatement(n)){let a=et(e,t,"statement",n);return r.continueTarget||e.unsupported.add("A continue statement could not be attached to a structured target."),Be(t,a.id,r.continueTarget??i),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=et(e,t,"statement",n);return a.invalidatesAllDefinitions=!0,Be(t,a.id,i),a.id}let s=et(e,t,"statement",n);return Be(t,s.id,i),s.id}function et(e,t,n,i){let r={id:`cfg:${e.nextCfgId++}`,kind:n,ast:i,successors:new Set,predecessors:new Set,definitions:[],uses:[],displayPoint:null,invalidatesAllDefinitions:!1};return t.set(r.id,r),r}function Be(e,t,n){e.get(t).successors.add(n),e.get(n).predecessors.add(t)}function BF(e,t){let n=t.cfg.get(t.entryId);for(let i of t.node.parameters){let r=_i(e,i.name);if(!r){e.unsupported.add("Destructured parameter definition-use is not implemented.");continue}n.definitions.push({point:Bi(e,r.node,"parameter-definition",r.symbolKey,r.name,t.id),rhsUseIds:[]})}for(let i of t.cfg.values())!i.ast||i.kind==="entry"||i.kind==="exit"||(i.kind==="predicate"&&(i.displayPoint=Bi(e,i.ast,"predicate",null,"predicate",t.id)),OF(e,t,i,i.ast),!i.displayPoint&&i.definitions.length===0&&i.uses.length===0&&(i.displayPoint=Bi(e,i.ast,"statement",null,VF(e,i.ast),t.id)))}function OF(e,t,n,i){let r=e.ts;if(r.isTryStatement(i))return;let o=s=>{if(!(s!==i&&r.isFunctionLike(s))){if(r.isVariableDeclaration(s)){let a=s.initializer?Ua(e,t.id,s.initializer,n):[];n.uses.push(...a);let l=_i(e,s.name);l?n.definitions.push({point:Bi(e,l.node,"definition",l.symbolKey,l.name,t.id),rhsUseIds:a.map(c=>c.point.id)}):(n.invalidatesAllDefinitions=!0,e.unsupported.add("Destructured variable reaching definitions are not implemented."));return}if(r.isBinaryExpression(s)&&Ob(r,s.operatorToken.kind)){let a=Ua(e,t.id,s.right,n);s.operatorToken.kind!==r.SyntaxKind.EqualsToken&&a.push(...Ua(e,t.id,s.left,n)),n.uses.push(...a);let l=_i(e,s.left);l?n.definitions.push({point:Bi(e,l.node,"definition",l.symbolKey,l.name,t.id),rhsUseIds:a.map(c=>c.point.id)}):(n.invalidatesAllDefinitions=!0,e.unsupported.add("Dynamic or destructured assignment targets are not included in reaching definitions."));return}if((r.isPrefixUnaryExpression(s)||r.isPostfixUnaryExpression(s))&&(s.operator===r.SyntaxKind.PlusPlusToken||s.operator===r.SyntaxKind.MinusMinusToken)){let a=Ua(e,t.id,s.operand,n);n.uses.push(...a);let l=_i(e,s.operand);l&&n.definitions.push({point:Bi(e,l.node,"definition",l.symbolKey,l.name,t.id),rhsUseIds:a.map(c=>c.point.id)});return}if(!(r.isFunctionDeclaration(s)||r.isClassDeclaration(s)||r.isInterfaceDeclaration(s))){if(_b(e,s)){let a=Bb(e,t.id,s);a&&n.uses.push(a),r.isPropertyAccessExpression(s)&&o(s.expression);return}s.forEachChild(o)}}};o(i),n.uses=$b(n.uses)}function Ua(e,t,n,i){let r=[],o=s=>{if(!e.ts.isFunctionLike(s)){if(e.ts.isBinaryExpression(s)&&Ob(e.ts,s.operatorToken.kind)){i.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(_b(e,s)){let a=Bb(e,t,s);a&&r.push(a),e.ts.isPropertyAccessExpression(s)&&o(s.expression);return}s.forEachChild(o)}};return o(n),$b(r)}function _b(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&&$F(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)||jF(e.ts,t))}function $F(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 jF(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 Bb(e,t,n){let i=_i(e,n);return i?{point:Bi(e,i.node,"use",i.symbolKey,i.name,t),property:e.ts.isPropertyAccessExpression(n)}:null}function _i(e,t){let n=e.ts;if(n.isIdentifier(t)){let i=kb(e,t);return i?{node:t,symbolKey:i,name:t.text}:null}if(n.isPropertyAccessExpression(t)){let i=kb(e,t.name);return i?{node:t,symbolKey:i,name:t.getText(e.sourceFile)}:null}return n.isParenthesizedExpression(t)||n.isAsExpression(t)||n.isTypeAssertionExpression(t)||n.isNonNullExpression(t)?_i(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 kb(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 i=n.valueDeclaration??n.declarations?.[0];return i?`symbol:${encodeURIComponent(i.getSourceFile().fileName)}:${i.getStart()}:${n.getName()}`:`symbol:${n.getName()}`}function Bi(e,t,n,i,r,o){let s=t.getStart(e.sourceFile),a=t.getEnd(),l=e.sourceFile.getLineAndCharacterOfPosition(s),c=`flow-point:${encodeURIComponent(e.sourceFile.fileName)}:${s}:${a}:${n}:${encodeURIComponent(i??r)}`,u=e.points.get(c);if(u)return u;let d={id:c,kind:n,name:r,symbolKey:i,callableId:o,start:s,end:a,line:l.line,column:l.character,node:t};return e.points.set(c,d),d}function HF(e,t){let n=[...t.cfg.values()].flatMap(l=>l.definitions),i=new Map(n.map(l=>[l.point.id,l])),r=UF(n),o=new Map,s=new Map;for(let l of t.cfg.values())o.set(l.id,new Set),s.set(l.id,new Set);let a=!0;for(;a;){a=!1;for(let l of t.cfg.values()){let c=YF([...l.predecessors].map(m=>s.get(m))),u=new Set(c);l.invalidatesAllDefinitions&&u.clear();let d=zF(l.definitions);for(let m of d){for(let f of r.get(m.point.symbolKey)??[])u.delete(f.point.id);u.add(m.point.id)}Xu(o.get(l.id),c)||(o.set(l.id,c),a=!0),Xu(s.get(l.id),u)||(s.set(l.id,u),a=!0)}}for(let l of t.cfg.values()){let c=o.get(l.id);for(let u of l.uses){let d=l.definitions.filter(f=>f.point.symbolKey===u.point.symbolKey&&f.point.start<u.point.start&&!f.rhsUseIds.includes(u.point.id)).sort((f,p)=>p.point.start-f.point.start)[0],m=d?[d.point.id]:c;for(let f of m){let p=i.get(f);p.point.symbolKey===u.point.symbolKey&&Fo(e,"reaching-definition",p.point.id,u.point.id,"exact","A CFG path reaches this use without an intervening definition.")}}for(let u of l.definitions)for(let d of u.rhsUseIds)Fo(e,"value-source",d,u.point.id,"exact","This right-hand-side use supplies the new definition.")}}function UF(e){let t=new Map;for(let n of e){if(!n.point.symbolKey)continue;let i=t.get(n.point.symbolKey)??[];i.push(n),t.set(n.point.symbolKey,i)}return t}function zF(e){let t=new Map;for(let n of e)n.point.symbolKey&&t.set(n.point.symbolKey,n);return[...t.values()]}function qF(e,t){let n=KF(t);for(let i of t.cfg.values()){if(i.successors.size<2||!i.displayPoint)continue;let r=n.get(i.id);for(let o of i.successors)for(let s of n.get(o)??[]){if(r.has(s)||s===t.exitId)continue;let a=t.cfg.get(s),l=[...a.definitions.map(c=>c.point),...a.uses.map(c=>c.point),...a.displayPoint?[a.displayPoint]:[]];for(let c of JF(l))Fo(e,"control-dependence",i.displayPoint.id,c.id,"exact","The target postdominates a branch successor but does not postdominate the predicate.")}}}function KF(e){let t=[...e.cfg.keys()],n=new Set(t),i=new Map;for(let o of t)i.set(o,o===e.exitId?new Set([o]):new Set(n));let r=!0;for(;r;){r=!1;for(let o of e.cfg.values()){if(o.id===e.exitId)continue;let s=[...o.successors].map(l=>i.get(l)),a=new Set([o.id,...XF(s)]);Xu(i.get(o.id),a)||(i.set(o.id,a),r=!0)}}return i}function GF(e,t){let n=new Map(t.map(s=>[s.id,s.parentId])),i=t.flatMap(s=>[...s.cfg.values()].flatMap(a=>a.definitions.map(l=>l.point))),r=new Map;for(let s of i){if(!s.symbolKey)continue;let a=r.get(s.symbolKey)??[];a.push(s),r.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(l=>l.uses)){if(!a.point.symbolKey||o.has(a.point.id))continue;let l=r.get(a.point.symbolKey)??[];for(let c of l)WF(c.callableId,a.point.callableId,n)?Fo(e,"closure-capture",c.id,a.point.id,"candidate","Compiler identity proves the captured binding, but invocation order can select among outer definitions."):a.property&&Fo(e,"field-definition-to-use",c.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 WF(e,t,n){for(let i=n.get(t)??null;i;i=n.get(i)??null)if(i===e)return!0;return!1}function Fo(e,t,n,i,r,o){let s=`local-flow-edge:${t}:${encodeURIComponent(n)}:${encodeURIComponent(i)}`;e.edges.set(s,{id:s,kind:t,fromPointId:n,toPointId:i,strength:r,reason:o})}function Ob(e,t){return t>=e.SyntaxKind.FirstAssignment&&t<=e.SyntaxKind.LastAssignment}function VF(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 $b(e){return[...new Map(e.map(t=>[t.point.id,t])).values()]}function JF(e){return[...new Map(e.map(t=>[t.id,t])).values()]}function YF(e){return new Set(e.flatMap(t=>[...t]))}function XF(e){return e.length===0?new Set:new Set([...e[0]].filter(t=>e.slice(1).every(n=>n.has(t))))}function Xu(e,t){return e.size===t.size&&[...e].every(n=>t.has(n))}function QF(e,t){return e.start-t.start||e.kind.localeCompare(t.kind)||e.id.localeCompare(t.id)}function Ju(e){return{points:[],edges:[],coverage:{status:"unsupported",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:[e]}}}var ek=Hn("typescript-local-flow",{clearGroups:["whole-project","source-file","semantic-provider"]});function Qu(e,t,n,i){if(!Gn(t))return null;let r=`${t}\0${n}\0${i}`;return ek.get(e,r,()=>{let o=se(e,t);return o?Nb(o,ZF(e.config.projectRoot,t),{startLine:n,endLine:i}):{points:[],edges:[],coverage:{status:"unsupported",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:[`Current source is unavailable for ${t}.`]}}})}function tk(e,t=new Map){let n=new Map,i=new Map,r=[];for(let o of e.transfers){if(!e.caller)continue;let s=za(e.caller,o.callerPosition),a=za(e.callee,o.calleePosition);ko(n,s),ko(n,a),ed(i,e.caller,s),ed(i,e.callee,a);let l=pt("edge","data-transfer",o.proof.file,String(o.proof.startLine),String(o.callerPosition),String(o.calleePosition));i.set(l,{id:l,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=za(e.callee,o.calleePosition);ko(n,a),ed(i,e.callee,a);let l=t.get(o.calleePosition);if(l&&mk(l)){dk(i,n,e,o.calleePosition,o.argumentText,l);return}let c=ck(e,o.calleePosition,o.argumentText);ko(n,c);let u=pt("edge","data-transfer-unsupported",o.proof.file,String(o.proof.startLine),String(o.calleePosition),String(s));i.set(u,{id:u,kind:"data-transfer",fromNodeId:c.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}}]}),r.push({id:pt("frontier","data-transfer",u),kind:"data-transfer",direction:"unresolved",fromNodeIds:[c.id],edgeIds:[u],memberNodeIds:[a.id],memberCount:1,disposition:"unsupported",reason:l?.derivation.rule??o.reason,expansion:null})}),{nodes:[...n.values()],edges:[...i.values()],frontiers:r,blindSpots:[]}}function Hb(e,t,n=[]){let i=Ub(),r=new Map,o=new Set;for(let s of t){if(s.kind!=="call"||!s.fromSymbol||!s.toSymbol||s.line===null)continue;let a=lk(r,e,s.toFile,s.toSymbol);if(!a)continue;let l=Yf(e,a),c=l.sites.filter(g=>g.file===s.fromFile&&g.startLine<=s.line&&g.endLine>=s.line&&g.caller?.symbol===s.fromSymbol);if(c.length!==1){let g=l.unresolved.find(h=>h.file===s.fromFile&&h.line===s.line);g&&i.blindSpots.push(`Parameter flow unresolved at ${s.fromFile}:${s.line+1}: ${g.reason}.`);continue}let u=c[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=Xf(e,u),f=ae(e,u.file)?.rootNode,p=new Map;if(f)for(let g of m.unknown){let h=Jf({db:e,file:u.file,root:f},u.arguments[g.calleePosition]);h&&p.set(g.calleePosition,h)}jb(i,tk(m,p)),m.caller&&sk(u.callNode)&&ak(i,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,l=Qu(e,s.location.file,s.location.line,a);if(l){jb(i,nk(s,l.points,l.edges));for(let c of l.coverage.unsupported)i.blindSpots.push(`TypeScript local flow is partial for ${s.location.file}:${s.location.line+1}-${a+1}: ${c} Recover with: codebaseiq inspect --at '${s.location.file}:${s.location.line+1}-${a+1}' --view behavior.`)}}return i.blindSpots=[...new Set(i.blindSpots)].sort(),i}function nk(e,t,n){let i=Ub(),r=new Map,o=new Map,s=new Map,a=e.location.file;for(let l of t){let c=ik(e,a,l);s.set(l.id,c.id),r.set(c.id,c),rk(o,e,c)}for(let l of n){let c=s.get(l.fromPointId),u=s.get(l.toPointId);if(!c||!u)continue;let d=ok(l),m=pt("edge","typescript-local-flow",a,l.id);o.set(m,{id:m,kind:l.kind==="control-dependence"?"control-dependence":"data-transfer",fromNodeId:c,toNodeId:u,directed:!0,disposition:"folded",semantics:[d],evidence:[{method:"typescript-compiler-cfg-reaching-definitions",strength:l.strength,identity:l.reason,location:r.get(c)?.location??e.location}]})}return i.nodes=[...r.values()],i.edges=[...o.values()],i}function ik(e,t,n){return{id:pt("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 rk(e,t,n){let i=pt("edge","local-flow-owner",t.id,n.id);e.has(i)||e.set(i,{id:i,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 ok(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 sk(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 ak(e,t,n){if(!t.caller)return;let i={id:pt("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}},r=pt("edge","return-to-call-result",t.callee.symbol,i.id),o=pt("edge","call-result-owner",t.caller.symbol,i.id);e.nodes.push(i),e.edges.push({id:r,kind:"data-transfer",fromNodeId:td(t.callee.symbol),toNodeId:i.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:i.location}]},{id:o,kind:"call-result-owner",fromNodeId:td(t.caller.symbol),toNodeId:i.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:i.location}]})}function Ub(){return{nodes:[],edges:[],frontiers:[],blindSpots:[]}}function jb(e,t){Zu(e.nodes,t.nodes),Zu(e.edges,t.edges),Zu(e.frontiers,t.frontiers),e.blindSpots.push(...t.blindSpots)}function Zu(e,t){let n=new Set(e.map(i=>i.id));for(let i of t)n.has(i.id)||(n.add(i.id),e.push(i))}function lk(e,t,n,i){let r=`${n}\0${i}`,o=e.get(r);if(o!==void 0)return o;let s=W(t,n).find(a=>a.symbol===i)??null;return e.set(r,s),s}function za(e,t){return{id:gk(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 ck(e,t,n){return{id:pt("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 uk(e,t,n){return{id:pt("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 dk(e,t,n,i,r,o){let s=uk(n,i,o),a=za(n.callee,i);ko(t,s);let l=pt("edge","static-value-transfer",n.call.file,String(n.call.startLine),String(i));e.set(l,{id:l,kind:"data-transfer",fromNodeId:s.id,toNodeId:a.id,directed:!0,disposition:"folded",semantics:[{family:"data",subtype:fk(o),attributes:{argumentText:r,calleePosition:i,value:o.value,precision:o.precision,derivationRule:o.derivation.rule}}],evidence:pk(o,n)})}function mk(e){return e.derivation.kind!=="heuristic"&&e.precision!=="symbolic"&&e.precision!=="unknown"}function fk(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 pk(e,t){return(e.derivation.sourceSpans.length>0?e.derivation.sourceSpans:[t.call]).map(i=>({method:`static-value:${e.derivation.rule}`,strength:e.derivation.kind==="direct"?"exact":"derived",identity:e.derivation.inputFactIds.join(",")||e.value,location:{file:i.file,line:i.startLine,endLine:i.endLine}}))}function ko(e,t){e.has(t.id)||e.set(t.id,t)}function ed(e,t,n){let i=pt("edge","parameter-owner",t.symbol,n.id);e.has(i)||e.set(i,{id:i,kind:"parameter-owner",fromNodeId:td(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 gk(e,t){return pt("parameter",e,String(t))}function td(e){return pt("symbol",e)}function pt(...e){return e.map(t=>encodeURIComponent(t)).join(":")}function zb(e,t){let n=new Map,i=new Map,r=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,l=xp(e,s.location.file,s.location.line,a);if(!l){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 c of l.facts){let u=nd(s,c.controller),d=nd(s,c.outcome);n.set(u.id,u),n.set(d.id,d),hk(i,s,u);let m=Oi("edge","control-dependence",u.id,d.id,c.subtype);i.set(m,{id:m,kind:"control-dependence",fromNodeId:u.id,toNodeId:d.id,directed:!0,disposition:"folded",semantics:[{family:"control",subtype:c.subtype,attributes:{...c.attributes}}],evidence:[{method:"parser-control-dependence",strength:"exact",identity:`${s.location.file}:${c.controller.startLine+1}-${c.outcome.startLine+1}`,location:{file:s.location.file,line:c.controller.startLine,endLine:c.controller.endLine}}]})}for(let c of l.terminals){let u=nd(s,c);n.set(u.id,u);let d=c.label.startsWith("throw")||c.label.startsWith("raise")?"throw":"return",m=Oi("edge","control-terminal",s.id,u.id,d);i.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:c.label,location:{file:s.location.file,line:c.startLine,endLine:c.endLine}}]})}for(let c of l.unsupported){let u=Oi("control-unsupported",s.location.file,String(c.startLine),String(c.endLine),c.reason);n.set(u,{id:u,kind:"control-unsupported",label:c.reason,disposition:"unsupported",location:{file:s.location.file,line:c.startLine,endLine:c.endLine},anchorIds:[],attributes:{ownerNodeId:s.id}});let d=Oi("edge","control-unsupported",s.id,u);i.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:c.reason,location:{file:s.location.file,line:c.startLine,endLine:c.endLine}}]});let m=Oi("frontier","control-dependence",u);r.set(m,{id:m,kind:"control-dependence",direction:"unresolved",fromNodeIds:[s.id],edgeIds:[d],memberNodeIds:[u],memberCount:1,disposition:"unsupported",reason:c.reason,expansion:null})}}return{nodes:[...n.values()],edges:[...i.values()],frontiers:[...r.values()],blindSpots:[...o].sort()}}function nd(e,t){let n=e.location.file;return{id:Oi(`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 hk(e,t,n){let i=Oi("edge","control-owner",t.id,n.id);e.has(i)||e.set(i,{id:i,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 Oi(...e){return e.map(t=>encodeURIComponent(t)).join(":")}var qa=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"]),Ao=new Set(["block","body","compound_statement","declaration_list","statement_block"]),yk=new Set(["assignment","assignment_expression","augmented_assignment_expression"]),rd=new Set(["update_expression"]),Wb=new Set(["array_access","element_access_expression","subscript_expression"]),Vb=new Set(["attribute","field_access","field_expression","member_access_expression","member_expression","selector_expression"]),bk=new Set(["false","null","null_literal","number","number_literal","string","string_literal","template_string","true"]),Sk=new Set(["call_expression","method_invocation","object_creation_expression"]),vk=new Set(["comment","else_clause","formal_parameters","parameters","type_parameters"]);function Jb(e,t,n,i){let r=ae(e,t);if(!r)return null;let o=Dk(r.rootNode,n,i);if(!o)return null;let s=[],a=[],l=[];return $i(o,c=>{if(yk.has(c.type)||rd.has(c.type)||Xb(c)){let u=Ck(c);u?s.push(u):l.push({family:"state",startLine:c.startPosition.row,endLine:c.endPosition.row,reason:`Mutation target ${mn(c.text)} could not be resolved to an exact source resource.`})}}),$i(o,c=>{if(!Ao.has(c.type))return;let u=wk(c);for(let d=0;d<u.length-1;d+=1)a.push({from:No(u[d]),to:No(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],f=Pk(m).filter(p=>p.type==="await_expression");for(let p of f){let g=_o("event",`await ${mn(p.text.replace(/^await\s+/u,""))}`,p);a.push({from:No(m),to:g,subtype:"awaits-completion",synchronizationScope:null,attributes:{completionRequired:!0}});let h=u[d+1];h&&a.push({from:g,to:No(h),subtype:"await-completion-before",synchronizationScope:null,attributes:{continuationOnly:!0}})}}}),$i(o,c=>{if(c.type!=="synchronized_statement")return;let u=c.childForFieldName("object")??c.childForFieldName("condition")??c.namedChildren.find(g=>!Ao.has(g.type)),d=c.childForFieldName("body")??c.namedChildren.find(g=>Ao.has(g.type));if(!u||!d){l.push({family:"temporal",startLine:c.startPosition.row,endLine:c.endPosition.row,reason:"Synchronized scope has no structurally resolved monitor or body."});return}let m=mn(u.text).replace(/^\(|\)$/gu,""),f=_o("lock",m,u),p=Mk(d).filter(g=>g.parent!==null&&Qb(g));for(let g of Lk(p))a.push({from:f,to:No(g),subtype:"inside-lock-scope",synchronizationScope:m,attributes:{syntaxNative:!0}})}),{mutations:s,temporal:a,unsupported:l}}function Ck(e){let t=Xb(e),n=e.childForFieldName("left")??e.childForFieldName("argument")??(t?e.namedChildren.at(-1)??null:e.namedChildren[0]??null);if(!n)return null;let i=xk(n);if(!i)return null;let r=t?"delete":rd.has(e.type)||!Ek(e,n).startsWith("=")?"update":"assign",o=t||rd.has(e.type)?null:e.childForFieldName("right");return{event:_o("event",mn(e.text),e),resource:{kind:"resource",label:i.name,startLine:n.startPosition.row,endLine:n.endPosition.row},operation:r,durabilityClass:"in-memory",recordIdentity:i.recordIdentity,value:o?_o("value",mn(o.text),o):null,dataSubtype:o?Rk(o,e):null}}function xk(e){if(Wb.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:`${mn(t.text)}[]`,recordIdentity:mn(n.text)}}return Vb.has(e.type)?{name:mn(e.text),recordIdentity:null}:/^(?:identifier|property_identifier|field_identifier)$/u.test(e.type)?{name:mn(e.text),recordIdentity:null}:null}function Rk(e,t){return bk.has(e.type)||/(?:integer|float|decimal|boolean|character)_literal$/u.test(e.type)?"constant-to-state":Sk.has(e.type)?"return-to-state":Vb.has(e.type)||Wb.has(e.type)?"property-to-state":/identifier$/u.test(e.type)?Ik(e.text,t)?"captured-value-to-state":"value-to-state":"expression-to-state"}function Ik(e,t){let n=id(t.parent);if(!n||qb(n,e))return!1;let i=id(n.parent);for(;i;){if(qb(i,e))return!0;i=id(i.parent)}return!1}function id(e){let t=e;for(;t;){if(qa.has(t.type))return t;t=t.parent}return null}function qb(e,t){let n=e.childForFieldName("parameters")??e.namedChildren.find(o=>["formal_parameters","parameters"].includes(o.type));if(n&&Kb(n,t))return!0;let i=e.childForFieldName("body")??e.namedChildren.find(o=>Ao.has(o.type));if(!i)return!1;let r=!1;return Yb(i,e,o=>{if(r||!/(?:declarator|declaration|parameter)$/u.test(o.type))return;let s=o.childForFieldName("name")??o.childForFieldName("pattern")??o.namedChildren[0];s&&Kb(s,t)&&(r=!0)}),r}function Kb(e,t){let n=!1;return $i(e,i=>{/identifier$/u.test(i.type)&&i.text===t&&(n=!0)}),n}function Yb(e,t,n){n(e);for(let i of e.namedChildren)i!==t&&qa.has(i.type)||Yb(i,t,n)}function Ek(e,t){let n=e.childForFieldName("right"),i=Math.max(0,t.endIndex-e.startIndex),r=n?Math.max(i,n.startIndex-e.startIndex):e.text.length;return e.text.slice(i,r).trim()}function Xb(e){return(e.type==="delete_expression"||e.type==="unary_expression")&&/^delete\b/u.test(e.text.trim())}function wk(e){return e.namedChildren.filter(t=>Qb(t))}function Qb(e){return vk.has(e.type)||Ao.has(e.type)?!1:/(?:statement|declaration)$/u.test(e.type)||e.type==="expression_statement"||e.type==="local_variable_declaration"}function Lk(e){let t=new Set(e);return e.filter(n=>{let i=n.parent;for(;i;){if(t.has(i))return!1;i=i.parent}return!0})}function No(e){return _o("event",mn(e.text),e)}function _o(e,t,n){return{kind:e,label:t,startLine:n.startPosition.row,endLine:n.endPosition.row}}function Dk(e,t,n){let i=[];return $i(e,o=>{o.startPosition.row<=t&&o.endPosition.row>=n&&i.push(o)}),i.filter(o=>qa.has(o.type)).sort(Gb)[0]??i.sort(Gb)[0]??null}function Gb(e,t){return e.endIndex-e.startIndex-(t.endIndex-t.startIndex)||e.startIndex-t.startIndex}function Mk(e){let t=[];return $i(e,n=>t.push(n)),t}function Pk(e){let t=[],n=i=>{t.push(i);for(let r of i.namedChildren)r!==e&&qa.has(r.type)||n(r)};return n(e),t}function $i(e,t){t(e);for(let n of e.namedChildren)$i(n,t)}function mn(e){return e.trim().replace(/\s+/gu," ")}function tS(e,t,n=[]){let i=new Map,r=new Map,o=new Map,s=new Set;for(let a of t){if(!a.location||!["source-construct","symbol"].includes(a.kind))continue;let l=a.location.endLine??a.location.line,c=Jb(e,a.location.file,a.location.line,l);if(!c){s.add(`State and temporal analysis unavailable for ${a.location.file}:${a.location.line+1}-${l+1}: no supported syntax tree or covering construct.`);continue}for(let u of c.mutations){let d=Ga(a,u.event),m=_k(a,u.resource,u.durabilityClass);if(i.set(d.id,d),i.set(m.id,m),Wa(r,a,d,"contains-state-effect"),Va(r,{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 f=Ga(a,u.value);i.set(f.id,f),Va(r,{kind:"data-to-state",from:f,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 c.temporal){let d=Ga(a,u.from),m=Ga(a,u.to);i.set(d.id,d),i.set(m.id,m),Wa(r,a,d,u.from.kind==="lock"?"contains-lock-scope":"contains-event"),Wa(r,a,m,"contains-event"),Va(r,{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 c.unsupported){let d=kn(`${u.family}-unsupported`,a.location.file,String(u.startLine),String(u.endLine),u.reason);i.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=kn("edge",`${u.family}-unsupported`,a.id,d);r.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 f=kn("frontier",u.family,d);o.set(f,{id:f,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(l=>l.kind==="runtime-boundary-participant")){let l=Ka(a,"protocol"),c=Ka(a,"action"),u=Ka(a,"address")??a.label;!l||!c||!eS(l,c)||Zb(i,r,a,{observationId:a.id,action:c,strength:"exact",file:a.location?.file??"",line:a.location?.line??0,address:u,protocol:l,role:Ka(a,"role")??void 0,resolution:"locally-linked"})}for(let a of n){if(!a.protocol||!eS(a.protocol,a.action))continue;let l=Nk(t,a.file,a.line,a.ownerShortName??null);if(!l){s.add(`State observation ${a.observationId} at ${a.file}:${a.line+1} has no materialized owner node.`);continue}Zb(i,r,l,a)}return{nodes:[...i.values()],edges:[...r.values()],frontiers:[...o.values()],blindSpots:[...s].sort()}}function Zb(e,t,n,i){let r=Fk(i),s={id:kn("runtime-state-event",i.observationId),kind:"runtime-state-event",label:`${i.action} ${r}`,disposition:"folded",location:{file:i.file,line:i.line},anchorIds:[],attributes:{action:i.action,protocol:i.protocol??null,modality:i.modality??null,resolution:i.resolution??null}},a=i.protocol==="database"?"external-durable-intent":"external",l={id:kn("runtime-state-resource",i.protocol??"unknown",r),kind:"runtime-state-resource",label:r,disposition:"folded",location:{file:i.file,line:i.line},anchorIds:[],attributes:{protocol:i.protocol??null,durabilityClass:a}};e.set(s.id,s),e.set(l.id,l),Wa(t,n,s,"contains-runtime-state-effect");let c=Tk(i.action);Va(t,{kind:"runtime-state-resource",from:s,to:l,semantics:[{family:"state",subtype:c,context:{crossesRuntimeBoundary:!0,protocol:i.protocol},attributes:{operation:i.action,durabilityClass:a,resource:r,recordIdentity:kk(i),modality:i.modality??null,resolution:i.resolution??null,transactionMembership:"unknown",commitState:i.protocol==="database"?"unknown":null}}],method:`runtime-boundary-${i.strength}`,identity:i.observationId})}function Tk(e){return e==="database.read"?"reads-resource":e==="queue.send"?"enqueues-resource":e==="queue.consume"?"consumes-resource":"writes-resource"}function Fk(e){return(e.keyParts?.find(n=>["address","resource"].includes(n.name))?.value??e.address)||e.observationId}function kk(e){return e.keyParts?.find(n=>/^(?:id|key|record)$/u.test(n.name))?.value??null}function eS(e,t){return e==="database"&&["database.read","database.write"].includes(t)||e==="queue"&&["queue.consume","queue.send"].includes(t)}function Ka(e,t){let n=e.attributes[t];return typeof n=="string"?n:null}function Nk(e,t,n,i){let r=e.filter(s=>s.location?.file===t&&["source-construct","symbol"].includes(s.kind)),o=r.filter(s=>s.location.line<=n&&(s.location.endLine??s.location.line)>=n).sort(Ak)[0];if(o)return o;if(i){let s=r.find(a=>a.label===i||a.label.endsWith(`.${i}`)||a.label.includes(i));if(s)return s}return r.length===1?r[0]:null}function Ak(e,t){let n=(e.location?.endLine??e.location?.line??0)-(e.location?.line??0),i=(t.location?.endLine??t.location?.line??0)-(t.location?.line??0);return n-i}function Ga(e,t){let n=e.location.file;return{id:kn(`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 _k(e,t,n){let i=e.location.file;return{id:kn("program-resource",i,e.id,t.label,n),kind:"program-resource",label:t.label,disposition:"folded",location:{file:i,line:t.startLine,endLine:t.endLine},anchorIds:[],attributes:{ownerNodeId:e.id,durabilityClass:n}}}function Wa(e,t,n,i){let r=kn("edge","program-owner",t.id,n.id,i);e.has(r)||e.set(r,{id:r,kind:"program-owner",fromNodeId:t.id,toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:i}],evidence:[{method:"parser-program-owner",strength:"exact",identity:t.id,location:n.location}]})}function Va(e,t){let n=kn("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 kn(...e){return e.map(t=>encodeURIComponent(t)).join(":")}var Bk=new Set(["control","data","state","temporal"]),Ja=new Set(["contains-control","contains-event","contains-lock-scope","contains-state-effect","contains-runtime-state-effect","contains","owns-parameter","owns-runtime-observation"]),oS=new Set(["discriminator-dispatch","result-callback","returns","runtime-handoff","throws"]);function sS(e,t={}){let n=new Map(e.nodes.map(C=>[C.id,C])),i=qk(e.nodes,t.focusLocations),r=Kk(e.edges,t.focusLocations),o=Gk(e.edges,r),s=new Set(e.paths.flatMap(C=>C.edgeIds)),a=Nn(e.anchors.filter(C=>C.status==="matched").flatMap(C=>C.nodeIds)),c=e.edges.filter(rS).filter(C=>Ok(C,i,r,s)),u=c.filter(C=>Uk(C,i,r,o,n,s)),d=nS(a,u,"forward"),m=Hk(d,u),f=nS(m,u,"backward"),p=new Set([...d].filter(C=>f.has(C)));for(let C of a)p.add(C);let g=new Set(u.filter(C=>p.has(C.fromNodeId)&&p.has(C.toNodeId)).map(C=>C.id)),h=new Set(p),b=new Set(g);$k(c,h,b,i,r);let v=e.frontiers.filter(C=>Vk(C,h)),y=Nn(v.filter(C=>C.disposition==="unsupported").map(C=>C.id)),I=Nn(e.edges.filter(C=>!rS(C)&&lS(C)&&Wk(C,h)).map(C=>C.id)),E=Nn(v.map(C=>C.id)),S=[];a.length===0&&S.push("No matched anchor node starts the corridor."),m.length===0&&S.push("No proved mechanical outcome is reachable from a matched anchor."),y.length>0&&S.push(`${y.length} unsupported frontier(s) touch the protected corridor.`),I.length>0&&S.push(`${I.length} candidate or unknown edge(s) touch the protected corridor.`);let x=S.length===0?"complete":"incomplete";return{schemaVersion:1,status:x,startNodeIds:a,outcomeNodeIds:m,baseNodeIds:Nn([...p]),baseEdgeIds:Nn([...g]),nodeIds:Nn([...h]),edgeIds:Nn([...b]),accountedFrontierIds:E,unresolvedFrontierIds:y,unresolvedEdgeIds:I,coverage:{protectedNodes:h.size,protectedEdges:b.size,baseNodes:p.size,baseEdges:g.size,accountedFrontiers:E.length,unresolvedFrontiers:y.length,unresolvedEdges:I.length},explanation:x==="complete"?"Every proved anchor-to-outcome path is closed over its material causal facts within reported coverage.":S.join(" ")}}function Ok(e,t,n,i){return t===null||e.disposition==="emitted"||i.has(e.id)||n?.has(e.id)===!0?!0:(e.semantics??[]).some(r=>{if(r.family==="identity"&&Ja.has(r.subtype))return t.has(e.toNodeId);if(r.family==="contract")return t.has(e.fromNodeId)&&t.has(e.toNodeId);if(r.family==="state")return t.has(e.fromNodeId);if(r.family==="data"||r.family==="temporal")return t.has(e.fromNodeId)||t.has(e.toNodeId);if(r.family==="control"){if(cS(r))return t.has(e.fromNodeId);if(["returns","throws"].includes(r.subtype))return t.has(e.toNodeId);if(r.subtype==="completion-callback")return t.has(e.fromNodeId)||t.has(e.toNodeId)}return!1})}function $k(e,t,n,i,r){let o=!0;for(;o;){o=!1;for(let s of e)jk(s,t,i,r)&&(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 jk(e,t,n,i){let r=t.has(e.fromNodeId),o=t.has(e.toNodeId);return!r&&!o?!1:(e.semantics??[]).some(s=>s.family==="identity"?Ja.has(s.subtype)&&(o||n===null||n.has(e.toNodeId)):s.family==="contract"?!0:s.family==="state"?r&&(n===null||n.has(e.fromNodeId)):s.family==="temporal"?s.subtype==="lexical-successor"?r&&o:!0:s.family==="data"?o&&(r||n===null||n.has(e.fromNodeId)||i?.has(e.id)===!0):s.family==="control"?aS(s)||["returns","throws"].includes(s.subtype)&&!o&&n!==null&&!n.has(e.toNodeId)?!1:oS.has(s.subtype)||cS(s)||s.subtype==="completion-callback":!1)}function Hk(e,t){let n=new Set,i=new Map,r=new Map;for(let o of t)!e.has(o.fromNodeId)||!e.has(o.toNodeId)||(i.set(o.fromNodeId,(i.get(o.fromNodeId)??0)+1),r.set(o.toNodeId,(r.get(o.toNodeId)??0)+1),(o.semantics??[]).some(s=>s.family==="state"||s.family==="control"&&oS.has(s.subtype))&&n.add(o.toNodeId));for(let o of e)(r.get(o)??0)>0&&(i.get(o)??0)===0&&n.add(o);return Nn([...n])}function nS(e,t,n){let i=new Map;for(let s of t){let a=n==="forward"?s.fromNodeId:s.toNodeId,l=n==="forward"?s.toNodeId:s.fromNodeId,c=i.get(a)??[];c.push(l),i.set(a,c)}let r=new Set(e),o=[...e];for(;o.length>0;){let s=o.shift();for(let a of i.get(s)??[])r.has(a)||(r.add(a),o.push(a))}return r}function Uk(e,t,n,i,r,o){return(e.semantics??[]).some(s=>e.disposition==="emitted"||o.has(e.id)?!0:s.family==="identity"&&Ja.has(s.subtype)?t===null||t.has(e.toNodeId)||i?.has(e.toNodeId)===!0:!Bk.has(s.family)||aS(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"?zk(e,r)&&(t.has(e.fromNodeId)||t.has(e.toNodeId)):!1)}function aS(e){return e.family==="control"&&["call","discriminator-dispatch","result-callback","runtime-handoff"].includes(e.subtype)}function zk(e,t){let n=t.get(e.fromNodeId),i=t.get(e.toNodeId);if(!n||!i)return!1;let r=iS(n,"ownerNodeId")??(n.kind==="symbol"?n.id:null),o=iS(i,"ownerNodeId")??(i.kind==="symbol"?i.id:null);return r!==null&&r===o}function qk(e,t){if(!t)return null;let n=new Map;for(let i of t){let r=n.get(i.file)??[];r.push(i.line),n.set(i.file,r)}return new Set(e.filter(i=>{if(!i.location||i.kind==="parameter")return!1;let r=n.get(i.location.file)??[],o=i.location.endLine??i.location.line;return r.some(s=>s>=i.location.line&&s<=o)}).map(i=>i.id))}function Kk(e,t){if(!t)return null;let n=new Map;for(let i of t){let r=n.get(i.file)??[];r.push(i.line),n.set(i.file,r)}return new Set(e.filter(i=>i.evidence.some(r=>{if(!r.location)return!1;let o=n.get(r.location.file)??[],s=r.location.endLine??r.location.line;return o.some(a=>a>=r.location.line&&a<=s)})).map(i=>i.id))}function Gk(e,t){return t===null?null:new Set(e.filter(n=>t.has(n.id)).flatMap(n=>[n.fromNodeId,n.toNodeId]))}function iS(e,t){let n=e.attributes[t];return typeof n=="string"?n:null}function rS(e){return e.disposition==="excluded"||e.disposition==="unsupported"||!lS(e)?!1:e.evidence.some(t=>t.strength==="exact"||t.strength==="derived")}function lS(e){return(e.semantics??[]).some(t=>t.family!=="identity"||Ja.has(t.subtype))}function cS(e){return e.subtype.startsWith("predicate-")||e.subtype.startsWith("loop-")||e.subtype.startsWith("exception-")||e.subtype.startsWith("finally-")||e.subtype.startsWith("handler-")}function Wk(e,t){return t.has(e.fromNodeId)||t.has(e.toNodeId)}function Vk(e,t){return[...e.fromNodeIds,...e.memberNodeIds].some(n=>t.has(n))}function Nn(e){return[...new Set(e)].sort()}import{createHash as Jk}from"crypto";var Ya=["identity","contract","control","data","state","temporal"],Yk=new Set(Ya);function Qa(e){let t=vr(e.anchors,"anchor"),n=vr(e.nodes,"node"),i=vr(e.edges,"edge"),r=vr(e.paths??[],"path"),o=vr(e.frontiers??[],"frontier"),s=new Set(t.map(f=>f.id)),a=new Set(n.map(f=>f.id)),l=new Set(i.map(f=>f.id)),c=e.routeCatalog?{...e.routeCatalog,routes:vr(e.routeCatalog.routes,"route"),selectedRouteIds:bt(e.routeCatalog.selectedRouteIds)}:void 0;for(let f of t)It(`anchor ${f.id}`,[...f.nodeIds,...f.candidateNodeIds],a,"node");for(let f of n)It(`node ${f.id}`,f.anchorIds,s,"anchor");for(let f of i){if(It(`edge ${f.id}`,[f.fromNodeId,f.toNodeId],a,"node"),f.evidence.length===0)throw new Error(`Exploration edge ${f.id} has no evidence source.`);Zk(f)}for(let f of r)It(`path ${f.id}`,[f.fromAnchorId,f.toAnchorId],s,"anchor"),It(`path ${f.id}`,f.nodeIds,a,"node"),It(`path ${f.id}`,f.edgeIds,l,"edge");for(let f of o)if(It(`frontier ${f.id}`,f.fromNodeIds,a,"node"),It(`frontier ${f.id}`,f.edgeIds,l,"edge"),It(`frontier ${f.id}`,f.memberNodeIds,a,"node"),f.memberCount!==f.memberNodeIds.length)throw new Error(`Exploration frontier ${f.id} reports ${f.memberCount} member(s) but identifies ${f.memberNodeIds.length}.`);for(let f of c?.routes??[])It(`route ${f.id}`,f.nodeIds,a,"node"),It(`route ${f.id}`,f.edgeIds,l,"edge"),It(`route ${f.id}`,[f.anchorNodeId,f.endpointNodeId],a,"node");c&&It("route catalog selection",c.selectedRouteIds,new Set(c.routes.map(f=>f.id)),"route");let u=bt(e.incompleteReasons??[]),d=u.length===0?"accounted":"incomplete",m=t.reduce((f,p)=>f+p.omittedCandidates,0);return{schemaVersion:1,anchors:t,nodes:n,edges:i,paths:r,frontiers:o,coverage:{status:d,scope:e.scope,nodes:bS(n),edges:bS(i),matchedAnchors:t.filter(f=>f.status==="matched").length,ambiguousAnchors:t.filter(f=>f.status==="ambiguous").length,missingAnchors:t.filter(f=>f.status==="missing").length,omittedCandidates:m,frontierGroups:o.length,programEdges:Qk(i),blindSpots:bt(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:n0(d,r,e.scope),...c?{routeCatalog:c}:{}}}function Xk(e){return e.flatMap(t=>e0(t.semantics??[]).map(n=>({id:t0(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 Qk(e){let t=Xk(e),n=new Set(t.map(s=>s.sourceEdgeId)),i=new Map(Ya.map(s=>[s,new Set])),r=new Map(Ya.map(s=>[s,new Set])),o=new Map(Ya.map(s=>[s,0]));for(let s of t)i.get(s.family).add(s.sourceEdgeId),r.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:bt(e.filter(s=>!n.has(s.id)).map(s=>s.kind)),families:{identity:Sr("identity",i,o,r),contract:Sr("contract",i,o,r),control:Sr("control",i,o,r),data:Sr("data",i,o,r),state:Sr("state",i,o,r),temporal:Sr("temporal",i,o,r)}}}function Sr(e,t,n,i){return{sourceEdges:t.get(e)?.size??0,projectedEdges:n.get(e)??0,subtypes:[...i.get(e)??[]].sort()}}function Zk(e){let t=new Set;for(let n of e.semantics??[]){if(!Yk.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 i=od(n);if(t.has(i))throw new Error(`Exploration edge ${e.id} repeats program edge semantic ${i}.`);t.add(i)}}function e0(e){return[...e].sort((t,n)=>od(t).localeCompare(od(n)))}function od(e){return`${e.family}:${e.subtype}`}function t0(e,t){return`program:${encodeURIComponent(e)}:${t.family}:${encodeURIComponent(t.subtype)}`}function n0(e,t,n){return e==="incomplete"||t.some(i=>i.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 SS(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 i=new Set(e.anchors.flatMap(w=>[...w.nodeIds,...w.candidateNodeIds])),r=[],o=e.anchors.filter(w=>w.status!=="missing"&&w.nodeIds.length+w.candidateNodeIds.length>0);for(let w=0;w<o.length;w+=1)for(let R=w+1;R<o.length;R+=1){let M=o[w],_=o[R],D=pS(e,M,_,!1),k=D??pS(e,M,_,!0);k?(k.nodeIds.forEach(V=>i.add(V)),r.push({id:Xa("path",M.id,_.id),fromAnchorId:M.id,toAnchorId:_.id,status:!D||M.status==="ambiguous"||_.status==="ambiguous"?"candidate":"connected",nodeIds:k.nodeIds,edgeIds:k.edgeIds})):r.push({id:Xa("path",M.id,_.id),fromAnchorId:M.id,toAnchorId:_.id,status:"partial",nodeIds:[],edgeIds:[]})}let s=bt(t.routeIds??[]),a=i0(e,s),l=new Set(a.routes.map(w=>w.id)),c=s.filter(w=>!l.has(w));if(c.length>0)throw new Error(`Unknown exploration route id(s): ${c.join(", ")}`);let d=a.routes.filter(w=>s.includes(w.id)).map(w=>({anchorNodeId:w.anchorNodeId,endpointNodeId:w.endpointNodeId,endpointKind:w.endpointKind,endpointPriority:2,nodeIds:[...w.nodeIds].reverse(),edgeIds:[...w.edgeIds].reverse()}));for(let w of d)w.nodeIds.forEach(R=>i.add(R));let m=r.length===0||r.some(w=>w.edgeIds.length>0);m&&hS(e,i,n);let f=yS(e,i),p=new Set(t.expandedFrontierIds??[]),g=new Set(f.map(w=>w.id)),h=[...p].filter(w=>!g.has(w)).sort();if(h.length>0)throw new Error(`Unknown exploration frontier id(s): ${h.join(", ")}`);for(let w of f)p.has(w.id)&&w.memberNodeIds.forEach(R=>i.add(R));m&&hS(e,i,n);let b=new Map(d.map(w=>[w.endpointNodeId,w.endpointKind])),v=new Set(d.flatMap(w=>w.nodeIds)),y=new Map;for(let w of d)for(let R=0;R<w.nodeIds.length;R+=1){let M=w.nodeIds[R],_=R;y.set(M,Math.max(y.get(M)??0,_))}let I=e.nodes.map(w=>{let R=b.get(w.id),M=v.has(w.id)?{upstreamCausalPath:!0,upstreamCausalDistance:y.get(w.id)??0,...R?{upstreamCausalEndpoint:R}:{}}:{};return{...w,attributes:{...w.attributes,...M},disposition:w.disposition==="excluded"||w.disposition==="unsupported"?w.disposition:i.has(w.id)?"emitted":"folded"}}),E=new Set([...r.flatMap(w=>w.edgeIds),...d.flatMap(w=>w.edgeIds)]),S=e.edges.map(w=>({...w,disposition:w.disposition==="excluded"||w.disposition==="unsupported"?w.disposition:E.has(w.id)||i.has(w.fromNodeId)&&i.has(w.toNodeId)?"emitted":"folded"})),x=Qa({anchors:e.anchors,nodes:I,edges:S,paths:r,frontiers:[...e.frontiers.filter(w=>w.disposition!=="folded"),...yS({...e,nodes:I,edges:S},i)],scope:e.coverage.scope,blindSpots:e.coverage.blindSpots,incompleteReasons:e.coverage.status==="incomplete"?[e.coverage.explanation]:[],routeCatalog:a}),C=new Set(x.frontiers.flatMap(w=>w.edgeIds)),L=x.edges.filter(w=>w.disposition==="folded"&&!C.has(w.id)).map(w=>w.id);if(L.length>0)throw new Error(`Folded exploration edge(s) are not frontier-accounted: ${L.sort().join(", ")}`);return x}var uS=10;function i0(e,t=[]){let n=new Map(e.nodes.map(h=>[h.id,h])),i=new Map(e.edges.map(h=>[h.id,h])),r=new Map;for(let h of e.edges){if(!r0(h))continue;let b=r.get(h.toNodeId)??[];b.push(h),r.set(h.toNodeId,b)}for(let h of r.values())h.sort((b,v)=>Number(Bo(v))-Number(Bo(b))||fS(v)-fS(b)||b.fromNodeId.localeCompare(v.fromNodeId)||b.id.localeCompare(v.id));let o=bt(e.anchors.filter(h=>h.status==="matched").flatMap(h=>h.nodeIds)),s=new Map,a=new Set,l=(h,b,v)=>{let y=b.nodeIds[b.nodeIds.length-1],I=n.get(y),E=n.get(h);if(!I?.location||!E)return;let S=[...b.nodeIds].reverse(),x=[...b.edgeIds].reverse(),C=new Set(S),L=x.flatMap(D=>{let P=i.get(D);return P?[P]:[]}),w=e.edges.filter(D=>D.disposition!=="excluded"&&D.disposition!=="unsupported"&&(C.has(D.fromNodeId)||C.has(D.toNodeId))),R={id:Xa("route",h,y,v,...x),status:"proved",anchorNodeId:h,anchorLabel:E.label,endpointNodeId:y,endpointLabel:I.label,endpointLocation:{...I.location},endpointKind:v,nodeIds:S,edgeIds:x,evidenceStrengths:bt(L.flatMap(D=>D.evidence.map(P=>P.strength))),spineEdgeFamilies:dS(L,!0),relatedEdgeFamilies:dS(w,!1),crossesRuntimeBoundary:L.some(Bo)},M=`${h}\0${y}\0${v}`,_=s.get(M);(!_||mS(R,_)<0)&&s.set(M,R)};for(let h of o){n.get(h)?.attributes.publicEntry===!0&&l(h,{nodeIds:[h],edgeIds:[]},"public-entry");let b=[{nodeIds:[h],edgeIds:[]}],v=new Map([[h,0]]);for(let y=0;y<b.length;y+=1){let I=b[y],E=I.nodeIds[I.nodeIds.length-1];I.edgeIds.length>0&&n.get(E)?.location&&n.get(E)?.attributes.publicEntry===!0&&l(h,I,"public-entry");let S=r.get(E)??[];if(I.edgeIds.length>=uS){S.some(x=>!I.nodeIds.includes(x.fromNodeId))&&a.add(h);continue}for(let x of S){if(I.nodeIds.includes(x.fromNodeId))continue;let C=I.edgeIds.length+1,L=v.get(x.fromNodeId);if(L!==void 0&&L<=C)continue;let w={nodeIds:[...I.nodeIds,x.fromNodeId],edgeIds:[...I.edgeIds,x.id]};if(v.set(x.fromNodeId,C),Bo(x)&&n.get(x.fromNodeId)?.location){l(h,w,"runtime-boundary");continue}b.push(w)}}}let c=[...s.values()].sort(mS),u=new Set(c.map(h=>h.id)),d=bt(t.filter(h=>u.has(h))),m=bt(c.map(h=>h.anchorNodeId)),f=o.filter(h=>!m.includes(h)),p=[...a].sort(),g=e.coverage.status==="accounted"&&p.length===0?"accounted":"incomplete";return{schemaVersion:1,routes:c,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:uS,anchorNodeIds:o,anchorsWithRoutes:m,anchorsWithoutRoutes:f,depthLimitedAnchorNodeIds:p,routeCount:c.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 dS(e,t){let n=e.flatMap(i=>i.semantics?.map(r=>r.family)??[]);return t&&e.length>0&&n.length===0&&n.push("control"),bt(n)}function mS(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 r0(e){return e.disposition!=="excluded"&&e.disposition!=="unsupported"&&o0(e)&&e.evidence.some(t=>["exact","derived","mixed"].includes(t.strength))}function o0(e){return Bo(e)||e.kind==="boundary-observation"||e.kind==="call"||e.kind==="compiler:call"}function Bo(e){return e.kind==="runtime-boundary"||e.kind.startsWith("runtime:")}function fS(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 pS(e,t,n,i){return gS(e,t,n,i)??gS(e,n,t,i)}function gS(e,t,n,i){let r=[...t.nodeIds,...t.candidateNodeIds].sort(),o=new Set([...n.nodeIds,...n.candidateNodeIds]);if(r.some(u=>o.has(u)))return{nodeIds:[r.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))&&!i||s0(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 l=r.map(u=>({nodeId:u,nodeIds:[u],edgeIds:[]})),c=new Set(r);for(let u=0;u<l.length;u+=1){let d=l[u];for(let m of a.get(d.nodeId)??[]){if(c.has(m.nodeId))continue;let f={nodeId:m.nodeId,nodeIds:[...d.nodeIds,m.nodeId],edgeIds:[...d.edgeIds,m.edgeId]};if(o.has(m.nodeId))return f;c.add(m.nodeId),l.push(f)}}return null}function s0(e,t,n,i){let r=e.get(t)??[];r.push({nodeId:n,edgeId:i}),e.set(t,r)}function a0(e,t,n){let i=new Map;for(let a of e.edges){let l=i.get(a.fromNodeId)??{incoming:0,outgoing:0},c=i.get(a.toNodeId)??{incoming:0,outgoing:0};l.outgoing+=1,c.incoming+=1,i.set(a.fromNodeId,l),i.set(a.toNodeId,c)}let r=new Set,o=new Map;for(let a of e.edges){let l=t.has(a.fromNodeId),c=t.has(a.toNodeId);if(l===c)continue;let u=l?a.toNodeId:a.fromNodeId,d=l?a.fromNodeId:a.toNodeId,m=e.nodes.find(g=>g.id===u);if(m?.kind==="structural-region")continue;let f=o.get(u)??new Set;f.add(d),o.set(u,f),(/(?:runtime-boundary|external)/u.test(a.kind)||m&&/(?:frontier|external)/u.test(m.kind))&&r.add(u)}let s=[...o].filter(([a,l])=>{if(r.has(a))return!0;let c=i.get(a)??{incoming:0,outgoing:0};return(c.incoming>1||c.outgoing>1)&&l.size>1}).sort(([a,l],[c,u])=>Number(r.has(c))-Number(r.has(a))||u.size-l.size||a.localeCompare(c)).map(([a])=>a);for(let a of s){if(t.size>=n)break;t.add(a)}}function hS(e,t,n){let i=-1;for(;t.size!==i&&t.size<n;)i=t.size,a0(e,t,n)}function yS(e,t){let n=new Set(e.nodes.filter(s=>!t.has(s.id)&&s.disposition!=="excluded"&&s.disposition!=="unsupported").map(s=>s.id)),i=new Map;for(let s of e.edges){if(!n.has(s.fromNodeId)||!n.has(s.toNodeId))continue;let a=i.get(s.fromNodeId)??new Set,l=i.get(s.toNodeId)??new Set;a.add(s.toNodeId),l.add(s.fromNodeId),i.set(s.fromNodeId,a),i.set(s.toNodeId,l)}let r=[],o=new Set;for(let s of[...n].sort()){if(o.has(s))continue;let a=[],l=[s];o.add(s);for(let c=0;c<l.length;c+=1){let u=l[c];a.push(u);for(let d of[...i.get(u)??[]].sort())o.has(d)||(o.add(d),l.push(d))}r.push(a.sort())}return r.map(s=>{let a=new Set(s),l=e.edges.filter(p=>a.has(p.fromNodeId)||a.has(p.toNodeId)),c=l.filter(p=>a.has(p.fromNodeId)!==a.has(p.toNodeId)),u=bt(c.map(p=>a.has(p.fromNodeId)?p.toNodeId:p.fromNodeId)),d=new Set(c.map(p=>a.has(p.toNodeId)?"outgoing":"incoming")),m=bt(l.map(p=>p.id)),f=bt(c.map(p=>p.kind));return{id:Xa("frontier",...s,...m),kind:f.join("+")||"disconnected",direction:d.size===1?[...d][0]:"undirected",fromNodeIds:u,edgeIds:m,memberNodeIds:s,memberCount:s.length,disposition:"folded",reason:c.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 Xa(e,...t){let n=Jk("sha256").update(t.join("\0")).digest("hex").slice(0,16);return`${e}:${n}`}function vr(e,t){let n=[...e].sort((i,r)=>i.id.localeCompare(r.id));for(let i=1;i<n.length;i+=1)if(n[i-1].id===n[i].id)throw new Error(`Duplicate exploration ${t} id: ${n[i].id}`);return n}function It(e,t,n,i){let r=bt(t.filter(o=>!n.has(o)));if(r.length>0)throw new Error(`Exploration ${e} references missing ${i}(s): ${r.join(", ")}`)}function bS(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 bt(e){return[...new Set(e)].sort()}var l0=5,c0=12,u0=8,d0=3,vS=8,m0=6,f0=12,CS=12,p0=12,g0=2,h0=new Set(["branch","loop","call","await","return","throw","mutation","catch","finally"]),y0=9e3,xS=Pb;function b0(e,t){return FS(e,t,"full")}function TS(e,t){return FS(e,t,"topology")}function FS(e,t,n){let i=tl(t.searches??[]),r=tl(t.symbols??[]),o=tl(t.relations&&t.relations.length>0?t.relations:xS),s=o.filter(F=>!xS.includes(F));if(s.length>0)throw new Error(`Unsupported system-map relation kind(s): ${s.join(", ")}`);let a=new Set(o),l=t.evidenceFloor??"derived";if(l!=="exact"&&l!=="derived")throw new Error(`Unsupported system-map evidence floor: ${l}`);let c=tl(t.sourceScopes&&t.sourceScopes.length>0?t.sourceScopes:["production"]),u=["production","test","fixture","example","generated","script","unknown"],d=c.filter(F=>!u.includes(F));if(d.length>0)throw new Error(`Unsupported system-map source scope(s): ${d.join(", ")}`);let m=new Set(c),f=F=>m.has(oc(F));if(i.length===0&&r.length===0)throw new Error("system-map requires at least one --search or --symbol anchor.");let p=t.maxDepth??l0;if(!Number.isSafeInteger(p)||p<0)throw new RangeError(`maxDepth must be a non-negative safe integer; received ${p}`);let g=t.maxTopologyCharacters??y0;if(!Number.isSafeInteger(g)||g<=0)throw new RangeError(`maxTopologyCharacters must be a positive safe integer; received ${g}`);let h=new U(e),b=h.fileDependencyGraph(),v=nN(b),y=iN(h.sourceFiles()),I=js(e),E=new Map((I?.observations??[]).map(F=>[F.id,F])),S=new Set((I?.observations??[]).map(F=>`${F.source.file}\0${F.source.startLine}`)),x=new Set,C=new Map,L=new Map,w=new Map,R=new Map,M=[],_=new Map,D=new Map,P=[],k=0,V=0,le=0,G=0,X=0,N=0,K=new Set,ne=new Map,fe=new Map,he=F=>{let H=fe.get(F);if(H)return H;let ee=Zn(e,F,{excludeIndexedTargets:!1});return fe.set(F,ee),ee},ce=(F,H,ee,we,j=!1)=>{let O=L.get(F);if(O)return O.depth=Math.min(O.depth,H),O.primary||=we,O.promoteBoundaryImports||=j,O.origins.add(ee),O;let q={file:F,depth:H,primary:we,promoteBoundaryImports:j,origins:new Set([ee]),processed:!1};return L.set(F,q),q},be=(F,H,ee,we,j="none",O=!1)=>{let q=w.get(F.symbol);if(q)return q.depth=Math.min(q.depth,H),q.origins.add(ee),we&&q.anchorQueries.add(we),q.referenceScope=tN(q.referenceScope,j),ce(F.relativePath,H,ee,!0,O),q;let oe={definition:F,depth:H,origins:new Set([ee]),anchorQueries:new Set(we?[we]:[]),referenceScope:j,processed:!1};return w.set(F.symbol,oe),ce(F.relativePath,H,ee,!0,O),oe},T=(F,H,ee,we,j=!1,O=!0)=>{let q=fn(F),oe=R.get(q);if(oe)return oe.depth=Math.min(oe.depth,H),oe.origins.add(ee),we&&oe.anchorQueries.add(we),oe.reverseCallExpansion||=j,oe.traversalEligible||=O,ce(F.file,H,ee,oe.traversalEligible,!0),oe;let z={...F,depth:H,origins:new Set([ee]),anchorQueries:new Set(we?[we]:[]),reverseCallExpansion:j,traversalEligible:O};return R.set(q,z),ce(F.file,H,ee,O,!0),z},Z=(F,H,ee)=>{ce(F.source.file,H,ee,!0,!0),F.owner.file!==F.source.file&&ce(F.owner.file,H,`${ee}:owner`,!0,!0);let we=W(e,F.owner.file),j=F.owner.symbol?ri(e,h,F.owner.symbol).matches.find(oe=>oe.relativePath===F.owner.file):null,O=(j&&!De(j.symbol)?j:null)??Ke(we,F.source.startLine);if(O&&!De(O.symbol))return be(O,H,ee,void 0,"none",!0),O.symbol;F.owner.name&&T({file:F.owner.file,name:F.owner.name,startLine:F.owner.startLine,endLine:F.owner.endLine},H,`${ee}:source-owner`,void 0,!0);let q=h.definitionsForFile(F.source.file).filter(oe=>!!oe.leaf&&Rn(e,F.source.file,oe.leaf).some(z=>z>=F.source.startLine&&z<=F.source.endLine));if(q.length===1){let oe=q[0];be(oe,H,`${ee}:handler-identifier`,void 0,"none",!0),Et(_,{kind:"runtime-boundary",evidence:"runtime-boundary:handler-identifier",fromFile:F.source.file,fromSymbol:null,toFile:oe.relativePath,toSymbol:oe.symbol,fromBoundaryParticipant:xr(F),line:F.source.startLine,strength:"derived"})}return null};for(let F of i){let H=O0(e,h,F,S),ee=H.filter(q=>z0(q,f)),we=!t.fullLiteralTraversal&&(H.length>c0||ee.length>u0),j=we?[]:H,O=new Set((we?[]:t.fullLiteralTraversal?ee:[...ee].sort($0).slice(0,d0)).map(wS));we&&(V+=1,le+=H.length);for(let q of j){let oe=O.has(wS(q)),z=oe&&!q.ownerSymbol&&q.ownerStartLine!==null&&q.ownerEndLine!==null;if(ce(q.relativePath,0,`${oe?"literal-anchor":"literal-match"}:${F}`,z,z),z&&T({file:q.relativePath,name:q.ownerShortName??`${q.relativePath}:${q.ownerStartLine+1}`,startLine:q.ownerStartLine,endLine:q.ownerEndLine},0,`literal-source-owner:${F}`,F,!0),oe&&q.ownerSymbol){let ue=ri(e,h,q.ownerSymbol).matches[0];ue&&!De(ue.symbol)&&be(ue,0,"literal-owner",F,"all",!0)}M.push({query:F,file:q.relativePath,line:q.line,ownerSymbol:q.ownerSymbol,ownerShortName:q.ownerShortName,ownerStartLine:q.ownerStartLine,ownerEndLine:q.ownerEndLine,sourceLine:q.sourceLine.trim(),matchKind:q.matchKind,traversalSeed:oe})}P.push({kind:"literal",query:F,status:H.length>0?"matched":"missing",matchedRegionIds:[],matchingLines:H.length,seedMatchingLines:we?0:O.size,matchOnlyLines:H.length-O.size,eligibleSeedMatchingLines:ee.length,materializedMatchingLines:j.length,withheldMatchingLines:we?H.length:0,literalTraversal:we?"withheld-broad":"materialized",representativeMatches:we?q0(F,H):void 0,narrowingCommands:we?G0(F,H):void 0,exhaustiveTraversalCommand:we||O.size<ee.length?`codebaseiq system-map --search ${Ne(F)} --full-literal-traversal`:void 0,seedRegionIds:[],matchOnlyRegionIds:[]})}for(let F of r){let H=ri(e,h,F);k+=H.omitted;let ee=j0(e,F),we=H.matches.filter(z=>!De(z.symbol)),j=ee!==null&&we.length===0;j&&T(ee,0,"source-construct-anchor",F,!0);let O=j?we:H.matches;for(let z of O)be(z,0,"symbol-anchor",F,"all",!0);let q=j?H0(ee):null,oe=j?1:H.total;P.push({kind:"symbol",query:F,status:oe===0?"missing":oe===1?"matched":"ambiguous",matchedRegionIds:[],symbolCandidates:[...q?[q]:[],...O.map(X0)],totalSymbolCandidates:oe,omittedSymbolCandidates:H.omitted})}for(let F=0;F<p;F+=1){if(a.has("call")){let j=[...R.values()].filter(O=>O.traversalEligible&&O.reverseCallExpansion&&O.depth<=F&&!K.has(fn(O)));for(let O of j){K.add(fn(O));let q=te(e,O.file);if((q?.callables??[]).filter(ue=>ue.name===O.name&&ue.startLine<=O.endLine&&ue.endLine>=O.startLine).length===1){let ue=(q?.callSites??[]).filter(Re=>Re.calleeLeaf===O.name&&!Re.memberAccess);for(let Re of ue){let Te=F+1,ve=Ke(W(e,O.file),Re.line),Pe=null,Ve=null;if(ve&&!De(ve.symbol)){if(ve.relativePath===O.file&&ve.startLine<=O.endLine&&ve.endLine>=O.startLine)continue;be(ve,Te,"reverse-local-call-owner",void 0,"forward-regions",!0),Pe=ve.symbol}else{let $=sd(e,O.file,Re.line);$&&fn($)!==fn(O)&&(Ve=T($,Te,"reverse-local-call-source-owner",void 0,!0))}!Pe&&!Ve||Et(_,{kind:"call",evidence:"ast-callsite",fromFile:O.file,fromSymbol:Pe,toFile:O.file,toSymbol:null,fromSourceConstruct:Ve?St(Ve):void 0,toSourceConstruct:St(O),line:Re.line,strength:"derived"})}}let z=new Set([...v.get(O.file)??[],...ne.get(fn(O))??[],...Uh(e,O.file).flatMap(ue=>[...v.get(ue)??[]])]);for(let ue of z){if(!f(ue))continue;let Te=he(ue).targets.filter(ve=>ve.targetFile===O.file&&ve.targetStartLine<=O.endLine&&ve.targetEndLine>=O.startLine);for(let ve of Te){let Pe=F+1,Ve=Ke(W(e,ue),ve.line),$=null,Le=null;if(Ve&&!De(Ve.symbol))be(Ve,Pe,"reverse-member-call-owner",void 0,"cross-workspace-or-forward",!0),$=Ve.symbol;else{let ie=sd(e,ue,ve.line);ie&&(Le=T(ie,Pe,"reverse-member-call-source-owner",void 0,!0))}!$&&!Le||Et(_,{kind:"call",evidence:"ast-service-member-callsite",fromFile:ue,fromSymbol:$,toFile:O.file,toSymbol:null,fromSourceConstruct:Le?St(Le):void 0,toSourceConstruct:St(O),line:ve.line,strength:ve.strength==="exact"?"exact":"derived"})}}}}let H=[...w.values()].filter(j=>!j.processed&&j.depth<=F),ee=a.has("call")?h.calleeMap(H.map(j=>j.definition),{additive:!1,semantic:!1}):new Map;for(let j of H){j.processed=!0;let O=j.definition;if(j.referenceScope!=="none"&&(a.has("call")||a.has("reference")||a.has("contract-symbol"))){let q=V0(e,h,O).filter(z=>f(z.file)&&eN(j,z.file,L,y)),oe=new Set(q.flatMap(z=>{if(!(a.has("call")&&te(e,z.file)?.callSites.some(Te=>Te.line===z.line&&Te.calleeLeaf===O.leaf)===!0)||!z.enclosingSymbol)return[];let Re=ri(e,h,z.enclosingSymbol).matches[0];return Re&&!De(Re.symbol)?[{owner:Re,site:z}]:[]}).sort((z,ue)=>{let Re=Lt(O.relativePath,y).relativeDir,Te=Lt(z.owner.relativePath,y).relativeDir===Re,ve=Lt(ue.owner.relativePath,y).relativeDir===Re,Pe=RS(e,z.owner),Ve=RS(e,ue.owner),$=z.owner.endLine-z.owner.startLine,Le=ue.owner.endLine-ue.owner.startLine;return Number(ve)-Number(Te)||Ve-Pe||$-Le||z.owner.symbol.localeCompare(ue.owner.symbol)}).filter((z,ue,Re)=>Re.findIndex(Te=>Te.owner.symbol===z.owner.symbol)===ue).reduce((z,ue)=>{if(z.length>=g0)return z;let Re=Lt(ue.owner.relativePath,y).relativeDir;return z.some(Te=>Te.workspace===Re)||z.push({symbol:ue.owner.symbol,workspace:Re}),z},[]).map(z=>z.symbol));for(let z of q){let ue=F+1;ce(z.file,ue,`reference:${A(O.symbol)}`,!0);let Re=a.has("call")&&te(e,z.file)?.callSites.some(Pe=>Pe.line===z.line&&Pe.calleeLeaf===O.leaf)===!0,Te=null,ve=null;if(z.enclosingSymbol){let Pe=ri(e,h,z.enclosingSymbol).matches[0];Pe&&!De(Pe.symbol)&&(be(Pe,ue,"reference-owner",void 0,Re&&oe.has(Pe.symbol)?j.referenceScope:"none"),Te=Pe.symbol)}if(!Te&&z.line!==null){let Pe=sd(e,z.file,z.line);Pe&&(ve=T(Pe,ue,"reference-source-owner",void 0,Re))}a.has("reference")&&Et(_,{kind:"reference",evidence:"indexed-or-source-reference",fromFile:z.file,fromSymbol:Te,toFile:O.relativePath,toSymbol:O.symbol,fromSourceConstruct:ve?St(ve):void 0,line:z.line,strength:"mixed"}),Re&&Et(_,{kind:"call",evidence:"ast-callsite",fromFile:z.file,fromSymbol:Te,toFile:O.relativePath,toSymbol:O.symbol,fromSourceConstruct:ve?St(ve):void 0,line:z.line,strength:"derived"}),a.has("contract-symbol")&&Lt(z.file,y).relativeDir!==Lt(O.relativePath,y).relativeDir&&Et(_,{kind:"contract-symbol",evidence:"compiler-cross-workspace-symbol",fromFile:z.file,fromSymbol:Te,toFile:O.relativePath,toSymbol:O.symbol,fromSourceConstruct:ve?St(ve):void 0,line:z.line,strength:"exact"})}}for(let q of ee.get(O.symbolId)??[]){let oe=ri(e,h,q.symbol).matches.find(ue=>ue.relativePath===q.file);if(!oe||!f(oe.relativePath))continue;if(!(oe.relativePath===O.relativePath||(b.get(O.relativePath)??new Set).has(oe.relativePath))){G+=1;continue}be(oe,F+1,`call:${A(O.symbol)}`,void 0,"none",!0),Et(_,{kind:"call",evidence:q.source,fromFile:O.relativePath,fromSymbol:O.symbol,toFile:oe.relativePath,toSymbol:oe.symbol,line:null,strength:P0(q.source)})}}let we=[...L.values()].filter(j=>!j.processed&&j.primary&&j.depth<=F);for(let j of we){j.processed=!0;let O=[...R.values()].filter($=>$.traversalEligible&&$.file===j.file&&$.depth<=F),q=[...w.values()].filter($=>$.definition.relativePath===j.file&&$.depth<=F).map($=>{let Le=rr(e,j.file,$.definition.startLine);return{startLine:Le?.startLine??$.definition.startLine,endLine:Le?.endLine??$.definition.endLine}}),oe=$=>[...w.values()].filter(Le=>Le.definition.relativePath===j.file&&Le.definition.startLine<=$&&Le.definition.endLine>=$).sort((Le,ie)=>Le.definition.endLine-Le.definition.startLine-(ie.definition.endLine-ie.definition.startLine)||Le.definition.startLine-ie.definition.startLine)[0],z=[...E.values()].filter($=>$.source.file===j.file&&C.has($.id)),ue=[...O.map($=>({startLine:$.startLine,endLine:$.endLine})),...z.map($=>({...el(e,$)}))],Re=[...q,...ue],Te=(te(e,j.file)?.callSites??[]).filter($=>Re.some(Le=>$.line>=Le.startLine&&$.line<=Le.endLine)),ve=new Set;if(a.has("call"))for(let $ of Re){let Le=Dn(e,j.file,$.startLine,$.endLine);for(let ie of Le.targets){if(!f(ie.definition.relativePath))continue;let Je=oe(ie.sourceLine),Ut=O.find(Mt=>Mt.startLine<=ie.sourceLine&&Mt.endLine>=ie.sourceLine),vt=z.find(Mt=>{let ut=el(e,Mt);return ut.startLine<=ie.sourceLine&&ut.endLine>=ie.sourceLine});be(ie.definition,F+1,`scip-occurrence-call:${j.file}:${ie.sourceLine+1}`,void 0,"none",!0),Et(_,{kind:"call",evidence:"scip-occurrence-callsite",fromFile:j.file,fromSymbol:Je?.definition.symbol??null,toFile:ie.definition.relativePath,toSymbol:ie.definition.symbol,fromBoundaryParticipant:vt?xr(vt):void 0,fromSourceConstruct:Ut?St(Ut):void 0,line:ie.sourceLine,strength:"exact"}),ve.add(`${ie.sourceLine}\0${ie.calleeLeaf}`)}}if(a.has("reference"))for(let $ of Re){let Le=Yh(e,j.file,$.startLine,$.endLine);for(let ie of Le.targets){if(!f(ie.definition.relativePath)||ve.has(`${ie.sourceLine}\0${ie.calleeLeaf}`))continue;let Je=oe(ie.sourceLine);if(Je?.definition.symbol===ie.definition.symbol)continue;let Ut=O.find(Mt=>Mt.startLine<=ie.sourceLine&&Mt.endLine>=ie.sourceLine),vt=z.find(Mt=>{let ut=el(e,Mt);return ut.startLine<=ie.sourceLine&&ut.endLine>=ie.sourceLine});be(ie.definition,F+1,`scip-occurrence-reference:${j.file}:${ie.sourceLine+1}`,void 0,"none",!0),Et(_,{kind:"reference",evidence:"scip-occurrence-reference",fromFile:j.file,fromSymbol:Je?.definition.symbol??null,toFile:ie.definition.relativePath,toSymbol:ie.definition.symbol,fromBoundaryParticipant:vt?xr(vt):void 0,fromSourceConstruct:Ut?St(Ut):void 0,line:ie.sourceLine,strength:"exact"})}}let Pe=a.has("call")?Zn(e,j.file,{ranges:Re,excludeIndexedTargets:!1}):{targets:[],unresolvedCallsites:0};N+=Pe.unresolvedCallsites;let Ve=Pe.targets.filter($=>!ve.has(`${$.line}\0${$.calleeLeaf}`));X+=Ve.filter($=>$.strength!=="exact"&&($.resolution!=="imported-service-object-member"||($.resolutionAlternativeCount??0)>1)).length;for(let $ of Ve){let Le=($.resolutionAlternativeCount??1)===1,ie=$.targetSymbol?W(e,$.targetFile).find(ut=>ut.symbol===$.targetSymbol):void 0,Je=ie?null:T({file:$.targetFile,name:$.calleeLeaf,startLine:$.targetStartLine,endLine:$.targetEndLine},F+1,`member-call:${j.file}`,void 0,$.resolution==="imported-service-object-member"&&Le,Le);if(Je&&$.serviceFile){let ut=fn(Je),Nr=ne.get(ut)??new Set;for(let gI of v.get($.serviceFile)??[])Nr.add(gI);ne.set(ut,Nr)}ie&&be(ie,F+1,`member-call:${j.file}`,void 0,"none",!0);let Ut=O.find(ut=>ut.startLine<=$.line&&ut.endLine>=$.line),vt=oe($.line),Mt=z.find(ut=>{let Nr=el(e,ut);return Nr.startLine<=$.line&&Nr.endLine>=$.line});Et(_,{kind:"call",evidence:$.resolution==="constructed-member-receiver"?"ast-constructed-member-callsite":$.resolution==="factory-callback-member"?"ast-factory-callback-callsite":$.resolution==="imported-service-object-member"?"ast-service-member-callsite":"ast-member-import-candidate",fromFile:j.file,fromSymbol:vt?.definition.symbol??null,toFile:$.targetFile,toSymbol:ie?.symbol??null,fromBoundaryParticipant:Mt?xr(Mt):void 0,fromSourceConstruct:Ut?St(Ut):void 0,toSourceConstruct:Je?St(Je):void 0,line:$.line,strength:$.resolution==="imported-service-object-member"?($.resolutionAlternativeCount??0)===1?"derived":"candidate":$.strength??"candidate"})}for(let $ of a.has("import")||a.has("call")?J0(e,j.file):[]){if(!$.fromFile){if(a.has("import")){let ie=D.get($.shortName)??{name:$.shortName,fromFiles:new Set};ie.fromFiles.add(j.file),D.set($.shortName,ie)}continue}if(!f($.fromFile))continue;if(a.has("import")&&(ce($.fromFile,F+1,`import:${j.file}`,!1),Et(_,{kind:"import",evidence:"indexed-or-source-import",fromFile:j.file,fromSymbol:null,toFile:$.fromFile,toSymbol:$.symbol,line:null,strength:"mixed"})),a.has("call")&&Te.length>0){let ie=($.source==="compiler"?ri(e,h,$.symbol).matches:Wn(e,$.fromFile,$.importedName)).filter(Je=>!De(Je.symbol));for(let Je of ie){let Ut=Te.filter(vt=>vt.calleeLeaf===$.localName).map(vt=>vt.line);if(Ut.length!==0){be(Je,F+1,`source-call:${j.file}`,void 0,"none",!0);for(let vt of Ut)Et(_,{kind:"call",evidence:"ast-callsite",fromFile:j.file,fromSymbol:null,toFile:Je.relativePath,toSymbol:Je.symbol,line:vt,strength:"derived"})}}}if(!j.promoteBoundaryImports||!Q0(j.file,$.fromFile,y))continue;let Le=ri(e,h,$.symbol);for(let ie of Le.matches)if(Z0(ie.relativePath,$.fromFile,y)&&!De(ie.symbol)){let Je=Lt(j.file,y).relativeDir!==Lt(ie.relativePath,y).relativeDir;be(ie,F+1,`boundary-import:${j.file}`,void 0,Je?"cross-workspace-or-forward":"forward-regions")}}}for(let j of a.has("runtime-boundary")?I?.links??[]:[]){if(j.strength==="candidate"||l==="exact"&&j.strength!=="exact"||x.has(j.id))continue;let O=E.get(j.from),q=E.get(j.to);if(!O||!q||!f(O.source.file)||!f(q.source.file))continue;let oe=MS(O,F,C,w,R),z=MS(q,F,C,w,R);if(oe===null&&z===null)continue;let ue=F+1,Re=Z(O,oe??ue,`runtime-boundary:${j.joinRule}`),Te=Z(q,z??ue,`runtime-boundary:${j.joinRule}`),ve=Re?null:DS(R,O),Pe=Te?null:DS(R,q);C.set(O.id,oe??ue),C.set(q.id,z??ue),Et(_,{kind:"runtime-boundary",evidence:`runtime-boundary:${j.joinRule}`,fromFile:O.source.file,fromSymbol:Re,toFile:q.source.file,toSymbol:Te,fromBoundaryParticipant:xr(O),toBoundaryParticipant:xr(q),fromSourceConstruct:ve?St(ve):void 0,toSourceConstruct:Pe?St(Pe):void 0,runtimeBoundaryKey:j.matchedKeyParts.map(Ve=>`${Ve.name}=${Ve.value}`).join(" "),line:O.source.startLine,strength:j.strength}),x.add(j.id)}}let Q=new Map;for(let F of L.keys())Q.set(F,Oo(F,y));let Se=[..._.values()].filter(F=>Q.has(F.fromFile)&&Q.has(F.toFile)).map(F=>({...F,fromRegionId:Q.get(F.fromFile).id,toRegionId:Q.get(F.toFile).id})).sort(_S),it=cN(Se),fi=new Set(t.expand??[]),$n=oN(L,w,M,Se,it,Q,fi),Ki=new Set([...L.values()].filter(F=>[...F.origins].some(H=>H.startsWith("literal-anchor:")||H==="literal-owner"||H==="symbol-anchor")).map(F=>Q.get(F.file).id)),jm=N0($n),rI=new Set($n.map(F=>F.id)),oI=[...fi].filter(F=>!rI.has(F)).sort();for(let F of P)if(F.matchedRegionIds=dN(F,M,w,Q),F.kind==="literal"){let H=M.filter(ee=>ee.query===F.query);F.seedRegionIds=Me(H.filter(ee=>ee.traversalSeed).map(ee=>Q.get(ee.file).id)),F.matchOnlyRegionIds=Me(H.filter(ee=>!ee.traversalSeed).map(ee=>Q.get(ee.file).id))}let Hm=[...w.values()].filter(F=>!F.processed).length,Um=[...L.values()].filter(F=>F.primary&&!F.processed).length,zm=[...L.values()].filter(F=>!F.primary&&!F.processed).length,qm=[...w.values()].filter(F=>F.processed),fs=(I?.frontiers??[]).flatMap(F=>{let H=E.get(F.observationId);return!H&&F.source&&F.action&&F.strength?!a.has("runtime-boundary")||!f(F.source.file)||l==="exact"||!L.has(F.source.file)?[]:[{observationId:F.observationId,action:F.action,strength:F.strength,file:F.source.file,line:F.source.startLine,ownerShortName:F.ownerShortName??null,address:F.address??F.missingKeyParts.join(", "),reason:F.reason}]:!a.has("runtime-boundary")||!H||!f(H.source.file)||l==="exact"&&H.strength!=="exact"||!L.has(H.source.file)?[]:[{observationId:H.id,action:H.action,strength:H.strength,file:H.source.file,line:H.source.startLine,ownerShortName:H.owner.name,address:AS(H),reason:F.reason,protocol:H.protocol,role:H.role,modality:H.modality,resolution:H.resolution,sourceScope:H.sourceScope,keyParts:H.keyParts.map(ee=>({name:ee.name,value:ee.value,evidence:ee.evidence}))}]}).sort((F,H)=>F.file.localeCompare(H.file)||F.line-H.line),Hl=(I?.links??[]).filter(F=>{if(!a.has("runtime-boundary")||l==="exact"&&F.strength!=="exact")return!1;let H=E.get(F.from),ee=E.get(F.to);return!!(H&&ee&&f(H.source.file)&&f(ee.source.file)&&(L.has(H.source.file)||L.has(ee.source.file)))}),sI=Hl.filter(F=>F.strength==="exact").length,aI=Hl.filter(F=>F.strength==="derived").length,lI=Hl.filter(F=>F.strength==="candidate").length,cI=I?.links.filter(F=>F.strength==="exact").length??0,uI=I?.links.filter(F=>F.strength==="derived").length??0,dI=I?.links.filter(F=>F.strength==="candidate").length??0,Ul=uN(D,Q),zl=k===0?"accounted":"incomplete",Km=[...V>0?[`${V} broad literal anchor(s) withheld ${le} 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 (${c.join(", ")}) remain visible as match-only evidence and do not seed traversal.`,I?"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 codebaseiq 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 ${p}; nonzero frontier counts identify evidence that was discovered but not traversed.`,"Region labels are structural path groupings, not inferred runtime or architectural boundaries."],Dt=R0({db:e,anchors:P,regions:$n,symbolStates:w,sourceConstructStates:R,literalHits:M,relations:Se,externalBoundaries:Ul,boundaryFrontiers:fs,regionForFile:Q,closureStatus:zl,omittedSymbolCandidates:k,maxDepth:p,requestedRelationKinds:o,evidenceFloor:l,includedSourceScopes:c,blindSpots:Km,topologyFrontiers:t.topologyFrontiers??[],routeIds:t.routeIds??[],expandedRegionIds:[...fi],maxTopologyCharacters:g,fullLiteralTraversal:t.fullLiteralTraversal??!1});if(n==="topology")return Dt;let Gm=(t.behaviorFocusLocations?.length??0)>0?new Set([...Dt.anchors.flatMap(F=>F.nodeIds),...Dt.paths.flatMap(F=>F.nodeIds)]).size:void 0,ps=ky(e,Dt,{focusLocations:t.behaviorFocusLocations,...Gm?{maxSteps:Gm}:{}});ub(e,Dt,ps);let mI=S0(e,Dt,ps,t.behaviorFocusLocations??[]);Dt.corridor=sS(Dt,{focusLocations:mI});let Wm=cb(e,Dt,ps,{sourceAllowed:f,selectionTerms:t.selectionTerms}),Vm=D0(Dt),fI=F0(i,r,p,o,l,c,t.fullLiteralTraversal??!1,g,$n,it,Ki,fi,Vm),pI=T0(i,r,p,$n.filter(F=>Vm.has(F.id)),Ki,o,l,c,t.fullLiteralTraversal??!1,g);return{anchors:P,regions:$n,regionRelations:it,externalBoundaries:Ul,boundaryFrontiers:fs,unmatchedExpansions:oI,expansion:pI,drilldown:jm,presentation:fI,topology:Dt,behavior:ps,nextAnchors:Wm,closure:{status:zl,emitted:{regions:$n.length,relations:Se.length,runtimeLinks:x.size},withheld:{symbols:Hm,files:Um+zm,regions:Dt.nodes.filter(F=>F.kind==="structural-region"&&F.disposition==="folded").length,drillAnchors:(jm?.omittedAnchors??0)+Wm.omittedAnchors,literalMatches:le},ambiguous:{anchors:P.filter(F=>F.status==="ambiguous").length,omittedSymbolCandidates:k},external:Ul.length,unresolved:fs.length,explanation:zl==="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:P.length,requestedRelationKinds:o,evidenceFloor:l,includedSourceScopes:c,matchedAnchorCount:P.filter(F=>F.status!=="missing").length,literalSearchesComplete:!0,broadLiteralAnchors:V,withheldLiteralMatches:le,symbolCandidateSetsComplete:k===0,omittedSymbolCandidates:k,maxTraversalDepth:p,frontierSymbols:Hm,frontierFiles:Um,supportFilesNotTraversed:zm,filteredUnverifiedCallEdges:G,memberCallCandidateEdges:X,unresolvedMemberCallsites:N,runtimeBoundaryEvidenceAvailable:I!==null,runtimeBoundaryObservations:I?.observations.length??0,runtimeBoundaryExactLinks:sI,runtimeBoundaryDerivedLinks:aI,runtimeBoundaryCandidateLinks:lI,repositoryRuntimeBoundaryExactLinks:cI,repositoryRuntimeBoundaryDerivedLinks:uI,repositoryRuntimeBoundaryCandidateLinks:dI,runtimeBoundaryTraversedLinks:x.size,runtimeBoundaryFrontiers:fs.length,referenceExpansionEligibleSymbols:qm.filter(F=>F.referenceScope!=="none").length,referenceExpansionSkippedSymbols:qm.filter(F=>F.referenceScope==="none").length,dynamicDispatchRepresented:I?.links.some(F=>F.joinRule==="carrier.discriminator"&&x.has(F.id))??!1,runtimeGeneratedLinksRepresented:I!==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:Km}}}function S0(e,t,n,i){let r=new Map,o=l=>{r.set(`${l.file}\0${l.line}`,l)};for(let l of i)o(l);let s=new Set(t.anchors.filter(l=>l.status==="matched").flatMap(l=>l.nodeIds));for(let l of n.steps)if(!(!l.location||!s.has(l.nodeId)||(l.behavior?.rawCharacters??1/0)>3e3))for(let c of l.behavior?.lines??[])c.signals.some(u=>h0.has(u))&&o({file:l.location.file,line:c.line,endLine:c.endLine});let a=t.edges.filter(l=>l.disposition==="emitted").flatMap(l=>l.evidence.flatMap(c=>c.location?[c.location]:[]));for(let l of a){o(l);let c=t.nodes.filter(d=>d.location?.file===l.file&&["symbol","source-construct","runtime-boundary-participant"].includes(d.kind)&&d.location.line<=l.line&&(d.location.endLine??d.location.line)>=l.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(!c?.location)continue;let u=Zs(e,l.file,c.location.line,c.location.endLine??c.location.line,[l.line]);for(let d of u)o({file:l.file,line:d.line,endLine:d.endLine})}return[...r.values()].sort((l,c)=>l.file.localeCompare(c.file)||l.line-c.line)}function v0(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 fn(e){return`${e.file}\0${e.startLine}\0${e.endLine}\0${e.name}`}function St(e){return{file:e.file,name:e.name,startLine:e.startLine,endLine:e.endLine}}function Za(e,t){let n=ud(te(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 i=NS(e,t.file,t.startLine);return i&&i.endLine>=t.endLine?{file:t.file,name:i.name,startLine:i.startLine,endLine:i.endLine}:St(t)}function Cr(e){return wt("source-construct",e.file,String(e.startLine),String(e.endLine),e.name)}function nl(e,t){let n=mr(e,t.symbol,t.relativePath),i=new Set(["package-surface-file","transitive-package-surface"]),r=n.filter(s=>!i.has(s)||xt(e,t)),o=r.some(s=>!i.has(s));return{evidence:r,priority:o||hy(e,t.symbol,t.relativePath)?2:1}}function RS(e,t){let n=nl(e,t);return n.evidence.length>0?n.priority:0}function C0(e,t){let n=W(e,t.file),i=n.filter(r=>r.startLine<=t.startLine&&r.endLine>=t.startLine).sort((r,o)=>r.endLine-r.startLine-(o.endLine-o.startLine)||r.startLine-o.startLine);for(let r of i){let o=nl(e,r);if(o.evidence.length>0)return o}for(let r of x0(e,t.file,t.startLine)){let o=n.filter(s=>s.leaf===r.name).sort((s,a)=>Math.abs(s.startLine-r.startLine)-Math.abs(a.startLine-r.startLine)||s.symbol.localeCompare(a.symbol));for(let s of o){let a=nl(e,s);if(a.evidence.length>0)return a}return{evidence:[],priority:0}}return{evidence:[],priority:0}}function x0(e,t,n){let i=ae(e,t)?.rootNode;if(!i||i.startPosition.row>n||i.endPosition.row<n)return[];let r=[],o=dd(i,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")&&r.push({name:s.text,startLine:o.startPosition.row})}o=o.parent}return r}function R0(e){let t=[...new Map([...e.sourceConstructStates.values()].map(R=>Za(e.db,R)).map(R=>[fn(R),R])).values()].sort((R,M)=>R.file.localeCompare(M.file)||R.startLine-M.startLine||R.endLine-M.endLine),n=e.anchors.map((R,M)=>{let _=wt("anchor",String(M),R.kind,R.query),D=[...e.symbolStates.values()].filter(G=>G.anchorQueries.has(R.query)).flatMap(G=>{if(!De(G.definition.symbol))return[oi(G.definition.symbol)];let X=t.filter(N=>N.file===G.definition.relativePath).map(N=>Cr(N));return X.length>0?X:[oi(G.definition.symbol)]}),P=[...e.sourceConstructStates.values()].filter(G=>G.anchorQueries.has(R.query)).map(G=>Cr(Za(e.db,G))),k=e.literalHits.filter(G=>G.query===R.query&&G.traversalSeed===!0&&G.ownerSymbol&&e.symbolStates.has(G.ownerSymbol)).map(G=>oi(G.ownerSymbol)),V=e.literalHits.filter(G=>G.query===R.query&&G.traversalSeed===!0&&!G.ownerSymbol&&G.ownerStartLine!==null&&G.ownerStartLine!==void 0&&G.ownerEndLine!==null&&G.ownerEndLine!==void 0).map(G=>Cr(Za(e.db,v0(G)))),le=Me(R.kind==="symbol"?[...D,...P]:k.length+V.length>0?[...k,...V]:R.seedRegionIds??[]);return{id:_,kind:R.kind,query:R.query,status:R.status,nodeIds:R.status==="ambiguous"?[]:le,candidateNodeIds:R.status==="ambiguous"?le:[],omittedCandidates:R.omittedSymbolCandidates??0}}),i=new Map;for(let R of n)for(let M of[...R.nodeIds,...R.candidateNodeIds]){let _=i.get(M)??[];_.push(R.id),i.set(M,_)}let r=e.relations.flatMap(R=>[R.fromBoundaryParticipant,R.toBoundaryParticipant].flatMap(M=>M?.ownerName?[M]:[])),o=e.regions.map(R=>({id:R.id,kind:"structural-region",label:R.label,disposition:"folded",location:null,anchorIds:Me(i.get(R.id)??[]),attributes:{workspace:R.workspace,structuralPath:R.structuralPath,minimumDepth:R.minDepth,files:R.fileCount,symbols:R.symbolCount,expanded:R.expanded}}));for(let R of e.symbolStates.values()){let M=e.regionForFile.get(R.definition.relativePath)?.id;if(!M)throw new Error(`System-map symbol ${R.definition.symbol} has no structural region.`);let _=oi(R.definition.symbol),D=nl(e.db,R.definition);o.push({id:_,kind:"symbol",label:A(R.definition.symbol),disposition:(i.get(_)?.length??0)>0?"emitted":"folded",location:{file:R.definition.relativePath,line:R.definition.startLine,endLine:R.definition.endLine},anchorIds:Me(i.get(_)??[]),attributes:{regionId:M,depth:R.depth,leaf:R.definition.leaf??A(R.definition.symbol),referenceScope:R.referenceScope,...D.evidence.length>0?{publicEntry:!0,publicEntryPriority:D.priority,publicEntryEvidence:D.evidence.join(",")}:{}}})}for(let R of t){let M=e.regionForFile.get(R.file)?.id;if(!M)throw new Error(`Source construct ${R.name} has no structural region.`);let _=Cr(R),P=r.find(V=>V.file===R.file&&V.line>=R.startLine&&V.line<=R.endLine)?.ownerName??R.name,k=C0(e.db,R);o.push({id:_,kind:"source-construct",label:P,disposition:(i.get(_)?.length??0)>0?"emitted":"folded",location:{file:R.file,line:R.startLine,endLine:R.endLine},anchorIds:Me(i.get(_)??[]),attributes:{regionId:M,leaf:P,sourceOwned:!0,...k.evidence.length>0?{publicEntry:!0,publicEntryPriority:k.priority,publicEntryEvidence:k.evidence.join(",")}:{}}})}let s=new Map;for(let R of e.relations)R.fromBoundaryParticipant&&s.set(R.fromBoundaryParticipant.observationId,R.fromBoundaryParticipant),R.toBoundaryParticipant&&s.set(R.toBoundaryParticipant.observationId,R.toBoundaryParticipant);for(let R of[...s.values()].sort((M,_)=>M.observationId.localeCompare(_.observationId))){let M=e.regionForFile.get(R.file)?.id;if(!M)throw new Error(`Runtime-boundary participant ${R.observationId} has no structural region.`);o.push({id:ad(R.observationId),kind:"runtime-boundary-participant",label:R.address||R.ownerName||`${R.role} ${R.action}`,disposition:"folded",location:{file:R.file,line:R.line,endLine:R.endLine},anchorIds:[],attributes:{regionId:M,action:R.action,protocol:R.protocol,role:R.role,...R.address?{address:R.address}:{},ownerSymbol:R.ownerSymbol}})}let a=new Set(o.map(R=>R.id)),l=Jt(t,R=>R.file),c=(R,M,_,D,P,k,V=!1)=>{let le=R?oi(R):null;if(le&&a.has(le)&&!De(R))return le;let G=M?ad(M.observationId):null;if(V&&G&&a.has(G))return G;let X=_?Cr(Za(e.db,_)):null;if(X&&a.has(X))return X;if(G&&a.has(G))return G;let N=k===null?null:(l.get(P)??[]).filter(K=>K.startLine<=k&&K.endLine>=k).sort((K,ne)=>K.endLine-K.startLine-(ne.endLine-ne.startLine)||K.startLine-ne.startLine)[0]??null;return N?Cr(N):le&&a.has(le)?le:D},u=[];for(let R of e.symbolStates.values()){let M=e.regionForFile.get(R.definition.relativePath)?.id;if(!M)continue;let _=oi(R.definition.symbol);u.push({id:wt("edge","structural-membership",M,_),kind:"structural-membership",fromNodeId:M,toNodeId:_,directed:!0,disposition:"folded",semantics:Ha("structural-membership"),evidence:[{method:"indexed-definition-file",strength:"exact",identity:R.definition.symbol,location:{file:R.definition.relativePath,line:R.definition.startLine,endLine:R.definition.endLine}}]})}let d=Jt(e.relations,R=>`${c(R.fromSymbol,R.fromBoundaryParticipant,R.fromSourceConstruct,R.fromRegionId,R.fromFile,R.line,R.kind==="runtime-boundary")}\0${c(R.toSymbol,R.toBoundaryParticipant,R.toSourceConstruct,R.toRegionId,R.toFile,null)}\0${R.kind}`),m=new Set;for(let R of d.values()){let M=R[0],_=c(M.fromSymbol,M.fromBoundaryParticipant,M.fromSourceConstruct,M.fromRegionId,M.fromFile,M.line,M.kind==="runtime-boundary"),D=c(M.toSymbol,M.toBoundaryParticipant,M.toSourceConstruct,M.toRegionId,M.toFile,null);if(M.kind==="runtime-boundary"&&M.fromBoundaryParticipant){let k=ad(M.fromBoundaryParticipant.observationId),V=c(M.fromSymbol,void 0,M.fromSourceConstruct,M.fromRegionId,M.fromFile,M.line);V!==k&&!m.has(k)&&(m.add(k),u.push({id:wt("edge","boundary-observation",V,k),kind:"boundary-observation",fromNodeId:V,toNodeId:k,directed:!0,disposition:"folded",semantics:Ha("boundary-observation"),evidence:[{method:"runtime-boundary-observation-owner",strength:M.strength??"unknown",identity:M.fromBoundaryParticipant.observationId,location:{file:M.fromBoundaryParticipant.file,line:M.fromBoundaryParticipant.line,endLine:M.fromBoundaryParticipant.endLine}}]}))}(_===D?o.find(k=>k.id===_):null)?.kind!=="structural-region"&&u.push({id:wt("edge",M.kind,_,D),kind:M.kind,fromNodeId:_,toNodeId:D,directed:!0,disposition:"folded",semantics:Tb(M),evidence:M0(R.map(k=>({method:k.evidence,strength:k.strength??"unknown",identity:k.kind==="runtime-boundary"&&k.runtimeBoundaryKey?k.runtimeBoundaryKey:`${k.fromSymbol??k.fromFile} -> ${k.toSymbol??k.toFile}`,location:k.line===null?null:{file:k.fromFile,line:k.line}})))})}for(let R of e.externalBoundaries){let M=wt("external",R.kind,R.name),_=Me(R.fromRegionIds);o.push({id:M,kind:R.kind,label:R.name,disposition:"folded",location:null,anchorIds:[],attributes:{}});for(let D of _)u.push({id:wt("edge",R.kind,D,M),kind:R.kind,fromNodeId:D,toNodeId:M,directed:!0,disposition:"folded",semantics:Ha("external-import"),evidence:[{method:"indexed-or-source-import",strength:"mixed",identity:`${D} -> ${R.name}`,location:null}]})}let f=[];e.boundaryFrontiers.forEach((R,M)=>{let _=e.regionForFile.get(R.file)?.id;if(!_)throw new Error(`Runtime-boundary frontier ${R.observationId} has no system-map region.`);let D=wt("unsupported","runtime-boundary",R.observationId,String(M)),P=wt("edge","runtime-boundary-frontier",_,D);o.push({id:D,kind:"runtime-boundary-frontier",label:R.address,disposition:"unsupported",location:{file:R.file,line:R.line},anchorIds:[],attributes:{action:R.action,strength:R.strength,owner:R.ownerShortName}}),u.push({id:P,kind:"runtime-boundary-frontier",fromNodeId:_,toNodeId:D,directed:!0,disposition:"unsupported",evidence:[{method:"runtime-boundary-extractor",strength:R.strength,identity:R.observationId,location:{file:R.file,line:R.line}}]}),f.push({id:wt("frontier","runtime-boundary",R.observationId,String(M)),kind:"runtime-boundary",direction:"unresolved",fromNodeIds:[_],edgeIds:[P],memberNodeIds:[D],memberCount:1,disposition:"unsupported",reason:R.reason,expansion:null})});let p=Qa({anchors:n,nodes:o,edges:u,paths:[],frontiers:f,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`]:[]}),g=e.topologyFrontiers.some(R=>R==="frontier:program-facts"),h=SS(p,{expandedFrontierIds:e.topologyFrontiers.filter(R=>R!=="frontier:program-facts"),routeIds:e.routeIds}),b=h.nodes.filter(R=>R.disposition==="emitted"||h.anchors.some(M=>M.status==="matched"&&M.nodeIds.includes(R.id))),v=e.relations.filter(R=>b.some(M=>I0(R,M))),y=e.boundaryFrontiers.filter(R=>b.some(M=>E0(R,M))),I=Hb(e.db,v,b),E=zb(e.db,b),S=tS(e.db,b,y),x=[...I.nodes,...E.nodes,...S.nodes].map(R=>g&&R.disposition==="folded"?{...R,disposition:"emitted"}:R),C=[...I.edges,...E.edges,...S.edges].map(R=>g&&R.disposition==="folded"?{...R,disposition:"emitted"}:R),L=g?null:w0(b,x,C),w=Qa({anchors:h.anchors,nodes:[...h.nodes,...x],edges:[...h.edges,...C],paths:h.paths,frontiers:[...h.frontiers,...I.frontiers,...E.frontiers,...S.frontiers,...L?[L]:[]],scope:h.coverage.scope,blindSpots:[...h.coverage.blindSpots,...I.blindSpots,...E.blindSpots,...S.blindSpots],incompleteReasons:h.coverage.status==="incomplete"?[h.coverage.explanation]:[],...h.routeCatalog?{routeCatalog:h.routeCatalog}:{}});w.completion=h.completion;for(let R of w.frontiers)R.disposition==="folded"&&(R.id.startsWith("frontier:program-facts:")||(R.expansion=L0(e,R.id)));return w}function I0(e,t){if(e.fromSymbol&&t.id===oi(e.fromSymbol)||e.toSymbol&&t.id===oi(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 E0(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 w0(e,t,n){let i=Me(t.filter(o=>o.disposition==="folded").map(o=>o.id)),r=Me(n.filter(o=>o.disposition==="folded").map(o=>o.id));return i.length===0&&r.length===0?null:{id:wt("frontier","program-facts"),kind:"program-facts",direction:"outgoing",fromNodeIds:Me(e.map(o=>o.id)),edgeIds:r,memberNodeIds:i,memberCount:i.length,disposition:"folded",reason:"Control, data, state, and temporal facts are folded beneath the selected high-level owners.",expansion:null}}function L0(e,t){return`codebaseiq system-map ${[...e.anchors.flatMap(i=>i.kind==="literal"?[`--search ${Ne(i.query)}`]:[`--symbol ${Ne(i.query)}`]),`--depth ${e.maxDepth}`,...e.requestedRelationKinds.map(i=>`--relation ${Ne(i)}`),`--evidence-floor ${Ne(e.evidenceFloor)}`,...e.includedSourceScopes.map(i=>`--source-scope ${Ne(i)}`),...e.fullLiteralTraversal?["--full-literal-traversal"]:[],`--topology-characters ${e.maxTopologyCharacters}`,...e.expandedRegionIds.map(i=>`--expand ${Ne(i)}`),...e.topologyFrontiers.map(i=>`--frontier ${Ne(i)}`),...e.routeIds.map(i=>`--route ${Ne(i)}`),`--frontier ${Ne(t)}`].join(" ")}`}function D0(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 i=n.attributes.regionId;typeof i=="string"&&t.add(i)}return t}function M0(e){let t=new Map;for(let n of e){let i=n.location?`${n.location.file}:${n.location.line}`:"";t.set(`${n.method}\0${n.strength}\0${n.identity??""}\0${i}`,n)}return[...t.values()].sort((n,i)=>n.method.localeCompare(i.method)||(n.identity??"").localeCompare(i.identity??"")||(n.location?.file??"").localeCompare(i.location?.file??"")||(n.location?.line??0)-(i.location?.line??0))}function wt(...e){return e.map(t=>encodeURIComponent(t)).join(":")}function oi(e){return wt("symbol",e)}function P0(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function T0(e,t,n,i,r,o,s,a,l,c){let u=[...i].sort((g,h)=>kS(g,h,r)),m=u.slice(0,CS).map(g=>g.id),f=u.slice(CS).map(g=>g.id),p=[...e.map(g=>`--search ${Ne(g)}`),...t.map(g=>`--symbol ${Ne(g)}`),`--depth ${n}`,...o.map(g=>`--relation ${Ne(g)}`),`--evidence-floor ${Ne(s)}`,...a.map(g=>`--source-scope ${Ne(g)}`),...l?["--full-literal-traversal"]:[],`--topology-characters ${c}`,...m.map(g=>`--expand ${Ne(g)}`)];return{command:m.length===0?null:`codebaseiq system-map ${p.join(" ")}`,regionCount:m.length,regionIds:m,candidateRegionCount:i.length,omittedRegionIds:f}}function F0(e,t,n,i,r,o,s,a,l,c,u,d,m){let f=[...l].sort((w,R)=>kS(w,R,u)).filter(w=>!m||m.has(w.id)||d.has(w.id)),p=c.length>0?Math.floor(a*.4):0,g=a-p,h=new Set,b=0;for(let w of f){let R=IS(w);!d.has(w.id)&&h.size>0&&b+R>g||(h.add(w.id),b+=R)}let v=c.filter(w=>h.has(w.fromRegionId)&&h.has(w.toRegionId)).sort(k0),y=[];for(let w of v){let R=ES(w);y.length>0&&b+R>a||(y.push(il(w)),b+=R)}let I=l.filter(w=>!h.has(w.id)).map(w=>w.id).sort(),E=new Set(y),S=c.filter(w=>!E.has(il(w))).length,x=l.reduce((w,R)=>w+IS(R),0)+c.reduce((w,R)=>w+ES(R),0),C=f.every(w=>h.has(w.id))&&y.length===v.length,L=[...e.map(w=>`--search ${Ne(w)}`),...t.map(w=>`--symbol ${Ne(w)}`),`--depth ${n}`,...i.map(w=>`--relation ${Ne(w)}`),`--evidence-floor ${Ne(r)}`,...o.map(w=>`--source-scope ${Ne(w)}`),...s?["--full-literal-traversal"]:[],`--topology-characters ${Math.max(a,x)}`];return{maxCharacters:a,estimatedCharacters:b,totalEstimatedCharacters:x,regionIds:[...h],omittedRegionIds:I,relationKeys:y,omittedRelations:S,complete:C,expansionCommand:C?null:`codebaseiq system-map ${L.join(" ")}`}}function IS(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 ES(e){return 70+e.fromRegionId.length+e.toRegionId.length+e.kinds.join(",").length+e.evidence.join(",").length}function k0(e,t){let n=i=>i.kinds.includes("runtime-boundary")?0:i.kinds.includes("contract-symbol")?1:2;return n(e)-n(t)||t.relationCount-e.relationCount||il(e).localeCompare(il(t))}function il(e){return`${e.fromRegionId}\0${e.toRegionId}`}function kS(e,t,n){let i=a=>n.has(a.id)?0:1,r=a=>a.sourceFileCount===0?1:0,o=a=>a.symbolCount+a.literalHitCount>0?0:1,s=a=>[...a.incomingRegionIds,...a.outgoingRegionIds].filter(l=>n.has(l)).length;return i(e)-i(t)||o(e)-o(t)||r(e)-r(t)||e.minDepth-t.minDepth||s(t)-s(e)||t.literalHitCount-e.literalHitCount||e.testFileCount-t.testFileCount||e.label.localeCompare(t.label)}function N0(e){let t=[],n=new Set;for(let r of e.filter(o=>o.expanded)){for(let l of r.symbols)l.origins.includes("symbol-anchor")&&n.add(l.file);let o=Jt(r.symbols,l=>l.file),s=Jt(r.literalHits,l=>l.file),a=[...r.files].sort((l,c)=>_0(l,c,o,s));for(let l of a){let c=(o.get(l.file)??[]).sort(B0)[0];if(c){t.push({kind:"symbol",regionId:r.id,file:c.file,line:c.startLine,endLine:c.endLine,label:c.shortName});continue}let u=(s.get(l.file)??[]).sort(BS)[0];u&&t.push({kind:"literal",regionId:r.id,file:u.file,line:u.line,endLine:null,label:u.ownerShortName??u.query})}}let i=A0(t,n);return{command:i.length===0?null:`codebaseiq inspect ${i.map(r=>`--at ${Ne(`${r.file}:${r.line+1}`)}`).join(" ")} --view behavior`,definitionCommand:null,candidateAnchors:t.length,selectedAnchors:i.length,omittedAnchors:t.length-i.length,anchors:i}}function A0(e,t){let n=[...Jt(e,s=>s.regionId).values()],i=[],r=new Set,o=Math.min(p0,24);for(let s of e)if(!(!t.has(s.file)||r.has(s.file))&&(i.push(s),r.add(s.file),i.length===o))return i;for(let s=0;i.length<o;s+=1){let a=!1;for(let l of n){let c=l[s];if(c&&(a=!0,!r.has(c.file)&&(i.push(c),r.add(c.file),i.length===o)))break}if(!a)break}return i}function _0(e,t,n,i){let r=a=>a.kind==="test"?2:a.kind==="barrel"?1:0,o=a=>(i.get(a.file)??[]).some(l=>l.traversalSeed)?0:1,s=a=>{let l=n.get(a.file)??[];return Math.min(5,...l.map(c=>$o(c.origins)))};return r(e)-r(t)||o(e)-o(t)||s(e)-s(t)||e.depth-t.depth||e.file.localeCompare(t.file)}function B0(e,t){return $o(e.origins)-$o(t.origins)||e.depth-t.depth||e.startLine-t.startLine||e.shortName.localeCompare(t.shortName)}function Ne(e){return`'${e.replaceAll("'","'\\''")}'`}function O0(e,t,n,i){let r=[];for(let o of me(e,{includeIgnored:!1})){let s=re(e,o);if(s.length===0)continue;let a=t.definitionsForFile(o),l=te(e,o)?.callables??[];for(let c=0;c<s.length;c+=1){let u=s[c]??"";if(!u.includes(n))continue;let d=Ke(a,c),m=ud(l,c),f=d&&!De(d.symbol)?d:null,p=f?.startLine??m?.startLine??d?.startLine??c,g=f?.endLine??m?.endLine??d?.endLine??c,h=eo(e,o,c,p,g),b=i.has(`${o}\0${c}`),v=!!(f?.isFunctionLike||m);r.push({relativePath:o,line:c,sourceLine:u,ownerSymbol:f?.symbol??null,ownerShortName:f?A(f.symbol):m?.name??(d?A(d.symbol):null),ownerStartLine:h.startLine,ownerEndLine:h.endLine,matchKind:U0(u,n),seedPriority:b?0:v?1:2})}}return r}function $0(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 wS(e){return`${e.relativePath}\0${e.line}`}function ud(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,i)=>n.endLine-n.startLine-(i.endLine-i.startLine)||n.startLine-i.startLine)[0]??null}function sd(e,t,n){let r=ud(te(e,t)?.callables??[],n)??NS(e,t,n);if(!r)return null;let o=eo(e,t,n,r.startLine,r.endLine);return{file:t,name:r.name,startLine:o.startLine,endLine:o.endLine}}function NS(e,t,n){let i=ae(e,t)?.rootNode;if(!i||i.startPosition.row>n||i.endPosition.row<n)return null;let r=dd(i,n);for(;r;){if(r.type==="variable_declarator"){let s=r.childForFieldName("name")??r.namedChild(0),a=r.childForFieldName("value")??r.namedChild(1);if(s?.type==="identifier"&&a&&ld(a,n))return{name:s.text,startLine:r.startPosition.row,endLine:r.endPosition.row}}if(r.type==="pair"){let s=r.childForFieldName("key")??r.namedChild(0),a=r.childForFieldName("value")??r.namedChild(1),l=s?.text.replace(/^(?:['"])(.*)(?:['"])$/u,"$1");if(l&&a&&/^[A-Za-z_$][\w$]*$/u.test(l)&&ld(a,n))return{name:l,startLine:r.startPosition.row,endLine:r.endPosition.row}}r=r.parent}let o=rr(e,t,n);return o?{name:`source@${n+1}`,startLine:o.startLine,endLine:o.endLine}:null}function ld(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&&ld(n,t))}function dd(e,t){let n=e.namedChildren.filter(i=>i.startPosition.row<=t&&i.endPosition.row>=t).sort((i,r)=>i.endIndex-i.startIndex-(r.endIndex-r.startIndex)||i.startPosition.row-r.startPosition.row)[0];return n?dd(n,t):e}function j0(e,t){let n=t.match(/^(.+):(\d+)(?:-(\d+))?$/u);if(!n)return null;let i=Es(e,n[1],{allowMultiple:!1})[0]?.relativePath;if(!i)return null;let r=Math.max(0,Number.parseInt(n[2],10)-1),o=n[3]?Math.max(r,Number.parseInt(n[3],10)-1):r,s=(te(e,i)?.callables??[]).filter(a=>a.startLine<=r&&a.endLine>=o).sort((a,l)=>a.endLine-a.startLine-(l.endLine-l.startLine)||a.startLine-l.startLine)[0];return s?{file:i,name:s.name,startLine:s.startLine,endLine:s.endLine}:null}function H0(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 U0(e,t){let n=/[\p{L}\p{N}_$]/u,i=e.indexOf(t);for(;i>=0;){let r=e[i-1]??"",o=e[i+t.length]??"";if((r==="'"||r==='"'||r==="`")&&o===r)return"exact-value";if(!n.test(r)&&!n.test(o))return"boundary";i=e.indexOf(t,i+Math.max(1,t.length))}return"embedded"}function cd(e){return J(e)==="test"?!1:!/(?:^|[/._-])(?:fixtures?|mocks?|previews?|demos?|examples?|stories)(?:[/._-]|$)/iu.test(e)}function z0(e,t){return e.matchKind!=="embedded"&&t(e.relativePath)&&(oc(e.relativePath)!=="production"||cd(e.relativePath))}function q0(e,t){let n=[...t].sort(K0),i=[],r=new Set;for(let o of n)if(!r.has(o.relativePath)&&(i.push(o),r.add(o.relativePath),i.length>=vS))break;for(let o of n){if(i.length>=vS)break;i.includes(o)||i.push(o)}return i.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 K0(e,t){let n={"exact-value":0,boundary:1,embedded:2};return n[e.matchKind]-n[t.matchKind]||+(t.ownerSymbol!==null)-+(e.ownerSymbol!==null)||+!cd(e.relativePath)-+!cd(t.relativePath)||e.relativePath.localeCompare(t.relativePath)||e.line-t.line}function G0(e,t){let n=new Map;for(let i of t){let r=W0(i.relativePath);n.set(r,(n.get(r)??0)+1)}return[...n].sort(([i,r],[o,s])=>s-r||i.localeCompare(o)).slice(0,m0).map(([i])=>`codebaseiq search ${Ne(e)} --scope ${Ne(i)}`)}function W0(e){let t=e.split("/").filter(Boolean);if(t.length<=1)return e;let n=t.slice(0,-1),i=n.lastIndexOf("src");return i>=0?n.slice(0,Math.min(n.length,i+3)).join("/"):n.slice(0,Math.min(n.length,3)).join("/")}function V0(e,t,n){let i=t.callerFileMap([n],{semantic:!1}).get(n.symbolId)??new Set,r=[];for(let o of[...i].sort()){let s=n.leaf?Rn(e,o,n.leaf):[];if(s.length===0){r.push({file:o,line:null,enclosingSymbol:null});continue}let a=t.definitionsForFile(o);for(let l of s)r.push({file:o,line:l,enclosingSymbol:Ke(a,l)?.symbol??null})}return r}function J0(e,t){let n=e.all(`SELECT DISTINCT gs.symbol, def_d.relative_path AS from_file
78
78
  FROM mentions m
79
79
  JOIN chunks c ON m.chunk_id = c.id
80
80
  JOIN documents imp_d ON c.document_id = imp_d.id
@@ -88,9 +88,9 @@ import{c as tp,e as np,f as qt}from"./chunk-B2OB55RR.js";import{b as kt,c as ec}
88
88
  ) sym_def ON sym_def.symbol_id = gs.id
89
89
  LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
90
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(i=>({symbol:i.symbol,shortName:A(i.symbol),importedName:MS(A(i.symbol)),localName:MS(A(i.symbol)),fromFile:i.from_file,source:"compiler"})):Ce(e,t).map(i=>{let r=sN(i.importedName,i.localName,i.kind),o=i.localName??i.importedName,s=i.importedName==="default"?o:i.importedName;return{symbol:r,shortName:r,importedName:s,localName:o,fromFile:i.sourcePath,source:"parsed-source"}})}function MS(e){return e.slice(e.lastIndexOf(":")+1).replace(/\(\)$/u,"")||e}function sN(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 ri(e,t,n){let i=at(e,n);if(!i.match)return{matches:[],total:0,omitted:0};let r=[i.match,...i.candidates.map(s=>at(e,s.symbol).match)].filter(s=>s!==null),o=new Map;for(let s of r){let a=t.definitionsForFile(s.relativePath).find(l=>l.symbol===s.symbol);a&&o.set(a.symbol,a)}return{matches:[...o.values()],total:i.total,omitted:Math.max(0,i.total-o.size)}}function aN(e){return{symbol:e.symbol,shortName:A(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine}}function Et(e,t){let n=[t.kind,t.fromFile,t.fromSymbol??"",t.toFile,t.toSymbol??"",t.fromBoundaryParticipant?.observationId??"",t.toBoundaryParticipant?.observationId??"",t.fromSourceConstruct?fn(t.fromSourceConstruct):"",t.toSourceConstruct?fn(t.toSourceConstruct):"",t.runtimeBoundaryKey??"",t.line??""].join("\0");e.set(n,t)}function Ir(e){return{observationId:e.id,action:e.action,protocol:e.protocol,role:e.role,address:BS(e),file:e.source.file,line:e.source.startLine,endLine:e.source.endLine,ownerName:e.owner.name,ownerSymbol:e.owner.symbol}}function tl(e,t){let n=re(e,t.source.file);return yt(e,t.source.file,0,Math.max(0,n.length-1),[t.source.startLine])}function PS(e,t){let n=[...e.values()];for(let i of[t.owner,t.source]){let r=n.filter(o=>o.file===i.file&&o.startLine<=i.startLine&&o.endLine>=i.startLine).sort((o,s)=>o.endLine-o.startLine-(s.endLine-s.startLine)||o.startLine-s.startLine)[0];if(r)return r}return null}function TS(e,t,n,i,r){let o=[],s=n.get(e.id);s!==void 0&&s<=t&&o.push(s);for(let a of i.values()){if(a.depth>t)continue;let l=a.definition;FS(l,e)&&o.push(a.depth)}for(let a of r.values())a.depth>t||FS(a,e)&&o.push(a.depth);return o.length>0?Math.min(...o):null}function FS(e,t){let n=e.relativePath??e.file;return[t.owner,t.source].some(i=>n===i.file&&e.startLine<=i.startLine&&e.endLine>=i.startLine)}function dd(e){return wt("runtime-boundary-participant",e)}function lN(e,t,n){let i=Lt(e,n),r=Lt(t,n);return i.relativeDir!==r.relativeDir?!0:/(?:^|\/)(?:contracts?|schemas?|db\/schema)(?:\/|$)/u.test(t)}function cN(e,t,n){return jo(e,n).id===jo(t,n).id}function uN(e,t,n,i){if(e.referenceScope==="all")return!0;let r=jo(t,i).id;return[...n.values()].some(s=>s.promoteBoundaryImports&&jo(s.file,i).id===r)?!0:e.referenceScope!=="cross-workspace-or-forward"?!1:Lt(t,i).relativeDir!==Lt(e.definition.relativePath,i).relativeDir}function dN(e,t){let n={none:0,"forward-regions":1,"cross-workspace-or-forward":2,all:3};return n[e]>=n[t]?e:t}function mN(e){let t=new Map;for(let[n,i]of e)for(let r of i){let o=t.get(r)??new Set;o.add(n),t.set(r,o)}return t}function Lt(e,t){return t.find(n=>e===n.relativeDir||e.startsWith(`${n.relativeDir}/`))??{name:"root",relativeDir:""}}function fN(e){let t=new Set(["apps","packages","services","crates","libs","tools"]),n=new Map;for(let i of e){let r=i.split("/").filter(Boolean);if(r.length<3||!t.has(r[0]))continue;let o=`${r[0]}/${r[1]}`;n.set(o,{name:r[1],relativeDir:o})}return[...n.values()].sort((i,r)=>r.relativeDir.length-i.relativeDir.length)}function jo(e,t){let n=Lt(e,t),r=(n.relativeDir?e.slice(n.relativeDir.length+1):e).split("/").filter(Boolean);r[0]==="src"&&r.shift();let o=pN(r);return{id:`region:${n.relativeDir||"root"}:${o}`,label:`${n.name}:${o}`,workspace:n.name,structuralPath:o}}function pN(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 gN(e,t,n,i,r,o,s){let a=Jt([...e.values()],f=>o.get(f.file).id),l=Jt([...t.values()],f=>o.get(f.definition.relativePath).id),c=Jt(n,f=>o.get(f.file).id),u=new Map;for(let f of i)for(let p of new Set([f.fromRegionId,f.toRegionId])){let g=u.get(p)??[];g.push(f),u.set(p,g)}let d=Jt(r,f=>f.toRegionId),m=Jt(r,f=>f.fromRegionId);return[...a.entries()].map(([f,p])=>{let g=o.get(p[0].file),h=l.get(f)??[],b=c.get(f)??[],v=u.get(f)??[],y=s.has(f),I=h.map(bN).sort(xN).slice(0,R0),E=p.filter(S=>J(S.file)==="test").length;return{id:f,label:g.label,workspace:g.workspace,structuralPath:g.structuralPath,minDepth:Math.min(...p.map(S=>S.depth)),fileCount:p.length,sourceFileCount:p.length-E,testFileCount:E,symbolCount:h.length,literalHitCount:b.length,anchorQueries:Me([...b.map(S=>S.query),...h.flatMap(S=>[...S.anchorQueries])]),relationKinds:Me(v.map(S=>S.kind)),incomingRegionIds:Me((d.get(f)??[]).map(S=>S.fromRegionId)),outgoingRegionIds:Me((m.get(f)??[]).map(S=>S.toRegionId)),memberCallCandidateRelationCount:v.filter(S=>S.evidence==="ast-member-import-candidate").length,notableSymbols:I,omittedNotableSymbols:Math.max(0,h.length-I.length),expanded:y,files:y?p.map(hN).sort(RN):[],symbols:y?h.map(yN).sort(IN):[],literalHits:y?[...b].sort($S):[],relations:y?[...v].sort(OS):[]}}).sort((f,p)=>f.minDepth-p.minDepth||f.label.localeCompare(p.label))}function hN(e){return{file:e.file,kind:J(e.file),depth:e.depth,origins:Me([...e.origins])}}function yN(e){return{symbol:e.definition.symbol,shortName:A(e.definition.symbol),file:e.definition.relativePath,startLine:e.definition.startLine,endLine:e.definition.endLine,depth:e.depth,origins:Me([...e.origins]),anchorQueries:Me([...e.anchorQueries]),referenceExpansion:e.referenceScope!=="none",referenceScope:e.referenceScope}}function bN(e){return{shortName:A(e.definition.symbol),file:e.definition.relativePath,origins:Me([...e.origins])}}function SN(e){return[...Jt(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:Me(n.map(i=>i.kind)),relationCount:n.length,fromFiles:Me(n.map(i=>i.fromFile)),toFiles:Me(n.map(i=>i.toFile)),fromSymbols:Me(n.flatMap(i=>i.fromSymbol?[A(i.fromSymbol)]:[])),toSymbols:Me(n.flatMap(i=>i.toSymbol?[A(i.toSymbol)]:[])),evidence:Me(n.map(i=>i.evidence)),strengths:Me(n.map(i=>i.strength??"unknown"))})).sort((n,i)=>n.fromRegionId.localeCompare(i.fromRegionId)||n.toRegionId.localeCompare(i.toRegionId))}function vN(e,t){return[...e.values()].map(n=>({kind:"external-import",name:n.name,fromRegionIds:Me([...n.fromFiles].flatMap(i=>{let r=t.get(i);return r?[r.id]:[]})),fromFiles:Me([...n.fromFiles])})).sort((n,i)=>n.name.localeCompare(i.name))}function CN(e,t,n,i){let r=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 Me(r.map(o=>i.get(o)?.id).filter(o=>!!o))}function BS(e){return e.keyParts.map(t=>`${t.name}=${t.value}`).join(" ")}function nl(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))]}function Me(e){return[...new Set(e)].sort()}function Jt(e,t){let n=new Map;for(let i of e){let r=t(i),o=n.get(r)??[];o.push(i),n.set(r,o)}return n}function OS(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 xN(e,t){return Ho(e.origins)-Ho(t.origins)||e.shortName.localeCompare(t.shortName)}function Ho(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 RN(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)}function IN(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)||e.symbol.localeCompare(t.symbol)}function $S(e,t){return e.file.localeCompare(t.file)||e.line-t.line||e.query.localeCompare(t.query)}var wN=["causal","structure","complete"],LN={causal:["execution","runtime","dataflow","state","temporal"],structure:["contract","identity","ownership","dependencies"],complete:qt},DN=2,MN=48,jS=64,PN=5e4;function Uo(e,t,n={}){let i=An([...t.symbols??[],...t.locations??[]]),r=An(t.searches??[]);if(i.length===0&&r.length===0)throw new Error("evidence requires at least one positional symbol, --symbol, --at, or --search selector.");let o=n.view??"causal",s=TN(n.families,o),a=n.direction??"both",l=An(n.subtypes??[]),c=n.connecting??!1,u=n.inventoryOnly??!1,d=An(n.foldIds??[]),m=n.maxDepth??DN,f=n.maxEdges??MN;if(!Number.isSafeInteger(m)||m<0)throw new RangeError(`Evidence depth must be a non-negative safe integer; received ${m}.`);if(!Number.isSafeInteger(f)||f<=0)throw new RangeError(`Evidence max edges must be a positive safe integer; received ${f}.`);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 p=kS(e,{symbols:i,searches:r,maxDepth:m,maxTopologyCharacters:PN,relations:FN(s)}),g=new Map(p.nodes.map(X=>[X.id,X])),h=p.edges.filter(X=>X.disposition==="emitted"||X.disposition==="folded").flatMap(X=>kN(X,g)),b=h.filter(X=>s.includes(X.family)).filter(X=>l.length===0||l.includes(X.subtype)),v=new Set(p.anchors.flatMap(X=>X.nodeIds));if(c&&v.size<2)throw new Error("Connecting evidence requires at least two resolved root nodes.");let y=new Set(b.map(X=>X.id)),I=hd(h,v,"incoming").filter(X=>y.has(X.id)),E=hd(h,v,"outgoing").filter(X=>y.has(X.id)),S=hd(h,v,"both").filter(X=>y.has(X.id)),x=ON(s,l,I,E,S),C=a==="incoming"?I:a==="outgoing"?E:S,L=c?KN(C,[...v],a):C,w=WN(L,v,a),R=[...L].sort((X,N)=>VN(X,N,w)),M=$N(R,f),_=HN(M,d),D=u?[]:d.length>0?R.filter(X=>_.has(X.id)):R,P=d.length>0?D:D.slice(0,f),k=d.length>0||u?[]:M,V=Math.max(0,D.length-P.length),le=p.frontiers.filter(X=>X.disposition==="unsupported").length,G=p.coverage.status==="incomplete"?"incomplete":V>0?"bounded":"accounted";return{kind:"graph",view:n.families&&n.families.length>0?"custom":o,families:s,selection:{direction:a,subtypes:l,connecting:c,inventoryOnly:u,foldIds:d},targets:p.anchors.map(X=>({kind:X.kind,query:X.query,status:X.status,nodeIds:[...X.nodeIds],omittedCandidates:X.omittedCandidates})),inventory:x,edges:P,folds:k,coverage:{status:G,topologyStatus:p.coverage.status,scope:p.coverage.scope,maxDepth:m,maxEdges:f,matchedEdges:R.length,eligibleEdges:D.length,returnedEdges:P.length,omittedEdges:V,frontierGroups:p.frontiers.length,unsupportedFrontiers:le,blindSpots:An([...p.coverage.blindSpots,...tp(s)]),explanation:u?`${R.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.`:G==="accounted"?"Every selected relationship in the bounded topology was emitted.":G==="bounded"?`${V} selected relationship(s) were withheld by the explicit edge budget.`:p.coverage.explanation}}}function TN(e,t){let n=e&&e.length>0?e:LN[t],i=n.filter(r=>!qt.includes(r));if(i.length>0)throw new Error(`Unsupported graph evidence family: ${i.join(", ")}.`);return An(n)}function FN(e){return["call","contract-symbol","import","reference","runtime-boundary"]}function kN(e,t){let n=t.get(e.fromNodeId),i=t.get(e.toNodeId);return!n||!i?[]:(e.semantics??[]).flatMap((r,o)=>{let s=AN(r);if(!s)return[];let a=np(s,r.subtype);if(!a)throw new Error(`No graph relation provider contract is registered for ${s}/${r.subtype}.`);let l=BN(e);if(!a.relation.evidenceStrengths.includes(l))throw new Error(`Graph relation provider ${a.provider.id} does not admit ${l} evidence for ${s}/${r.subtype}.`);return[{id:`${e.id}:${o}:${s}`,family:s,semanticFamily:r.family,subtype:r.subtype,from:HS(n),to:HS(i),sourceKind:e.kind,providerId:a.provider.id,supportCeiling:a.relation.supportCeiling,establishes:a.relation.establishes,nonClaims:[...a.relation.nonClaims],recoverWith:[...a.relation.recoverWith],evidenceStrength:l,evidenceMethods:An(e.evidence.map(c=>c.method)),evidenceConstituents:NN(e.evidence),context:r.context?{...r.context}:null,attributes:r.attributes?{...r.attributes}:null}]})}function NN(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:i})=>({method:n,strength:i}))}function AN(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 HS(e){let t=_N(e);return{id:e.id,kind:e.kind,label:t?A(t):e.label,symbol:t,location:e.location?{...e.location}:null}}function _N(e){return e.kind!=="symbol"||!e.id.startsWith("symbol:")?null:decodeURIComponent(e.id.slice(7))}function BN(e){let t=An(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 hd(e,t,n){let i=yd(e,n),r=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 l=s[a],c=o.get(l);for(let u of i.get(l)??[])r.set(u.edge.id,u.edge),!o.has(u.next)&&(o.set(u.next,c+1),s.push(u.next))}return[...r.values()]}function yd(e,t){let n=new Map,i=(r,o,s)=>{let a=n.get(r)??[];a.push({edge:s,next:o}),n.set(r,a)};for(let r of e)t!=="incoming"&&i(r.from.id,r.to.id,r),t!=="outgoing"&&i(r.to.id,r.from.id,r);for(let r of n.values())r.sort((o,s)=>o.edge.id.localeCompare(s.edge.id)||o.next.localeCompare(s.next));return n}function ON(e,t,n,i,r){let o=new Set;for(let u of[...n,...i,...r])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 f=`${m.family}\0${m.subtype}`;d.set(f,(d.get(f)??0)+1)}return d},a=s(n),l=s(i),c=s(r);return[...o].map(u=>{let[d,m]=u.split("\0");return{family:d,subtype:m,incoming:a.get(u)??0,outgoing:l.get(u)??0,both:c.get(u)??0}}).sort((u,d)=>qt.indexOf(u.family)-qt.indexOf(d.family)||u.subtype.localeCompare(d.subtype))}function $N(e,t){let n=e.slice(t),i=new Map;for(let s of n){let a=jN(s),l=`${s.family}\0${a}`,c=i.get(l)??[];c.push(s),i.set(l,c)}let r=new Map(e.map((s,a)=>[s.id,a+1])),o=[];for(let[s,a]of[...i].sort(([l],[c])=>l.localeCompare(c))){let[l,c]=s.split("\0"),u=[...a].sort((d,m)=>d.id.localeCompare(m.id));for(let d=0;d<u.length;d+=jS){let m=u.slice(d,d+jS),f=m.map(b=>b.id),p=An(m.map(b=>b.subtype)).sort(),g=p.length===1?p[0]:"mixed",h=[...new Set(m.flatMap(b=>[b.from.id,b.to.id]))].sort();o.push({id:qN(l,p.join("\0"),f),mode:UN(m),family:l,subtype:g,subtypes:p,region:c,edgeCount:f.length,edgeIds:f,nodeIds:h,minimumMaxEdges:Math.max(...f.map(b=>r.get(b)??e.length))})}}return o.sort((s,a)=>qt.indexOf(s.family)-qt.indexOf(a.family)||(s.region??"").localeCompare(a.region??"")||s.id.localeCompare(a.id))}function jN(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 HN(e,t){if(t.length===0)return new Set;let n=new Map(e.map(r=>[r.id,r])),i=t.filter(r=>!n.has(r));if(i.length>0){let r=e.map(o=>o.id).sort();throw new Error(`Unknown evidence fold ${i.join(", ")} for this projection. Available folds: ${r.join(", ")||"(none)"}.`)}return new Set(t.flatMap(r=>n.get(r).edgeIds))}function UN(e){let t=new Map,n=new Map,i=new Set;for(let o of e){i.add(o.from.id),i.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 zN(i,t)?"scc":[...i].every(o=>(n.get(o)?.size??0)<=1&&(t.get(o)?.size??0)<=1)?"linear":"topology"}function zN(e,t){let n=new Set,i=new Set,r=o=>{if(n.has(o))return!0;if(i.has(o))return!1;n.add(o);for(let s of t.get(o)??[])if(r(s))return!0;return n.delete(o),i.add(o),!1};return[...e].some(r)}function qN(e,t,n){return`fold:${EN("sha256").update([e,t,...n].join("\0")).digest("hex").slice(0,16)}`}function KN(e,t,n){let i=new Map,r=[...new Set(t)].sort();for(let o=0;o<r.length;o+=1)for(let s=o+1;s<r.length;s+=1)for(let a of GN(e,r[o],r[s],n))i.set(a.id,a);return[...i.values()]}function GN(e,t,n,i){let r=yd(e,i),o=new Map([[t,0]]),s=new Map,a=[t];for(let c=0;c<a.length;c+=1){let u=a[c],d=o.get(u);if(u!==n)for(let m of r.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 l=[];for(let c=n;c!==t;){let u=s.get(c);if(!u)return[];l.push(u.edge),c=u.node}return l.reverse()}function WN(e,t,n){let i=yd(e,n),r=new Map,o=[...t];for(let s of t)r.set(s,0);for(let s=0;s<o.length;s+=1){let a=o[s],l=r.get(a);for(let{next:c}of i.get(a)??[])r.has(c)||(r.set(c,l+1),o.push(c))}return r}function VN(e,t,n){return US(e,n)-US(t,n)||zS(e)-zS(t)||qS(e.evidenceStrength)-qS(t.evidenceStrength)||qt.indexOf(e.family)-qt.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 US(e,t){return Math.min(t.get(e.from.id)??Number.MAX_SAFE_INTEGER,t.get(e.to.id)??Number.MAX_SAFE_INTEGER)}function zS(e){let t=[e.from,e.to].filter(n=>n.kind==="structural-region").length;return t===2?2:t}function qS(e){switch(e){case"exact":return 0;case"mixed":return 1;case"derived":return 2;case"candidate":return 3;case"unknown":return 4}}function An(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))]}function bd(e,t){let n=In(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let i=n.map(()=>"?").join(", "),o=e.all(`SELECT relative_path FROM documents
91
+ ORDER BY def_d.relative_path, gs.symbol`,t);return n.length>0?n.map(i=>({symbol:i.symbol,shortName:A(i.symbol),importedName:LS(A(i.symbol)),localName:LS(A(i.symbol)),fromFile:i.from_file,source:"compiler"})):Ce(e,t).map(i=>{let r=Y0(i.importedName,i.localName,i.kind),o=i.localName??i.importedName,s=i.importedName==="default"?o:i.importedName;return{symbol:r,shortName:r,importedName:s,localName:o,fromFile:i.sourcePath,source:"parsed-source"}})}function LS(e){return e.slice(e.lastIndexOf(":")+1).replace(/\(\)$/u,"")||e}function Y0(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 ri(e,t,n){let i=at(e,n);if(!i.match)return{matches:[],total:0,omitted:0};let r=[i.match,...i.candidates.map(s=>at(e,s.symbol).match)].filter(s=>s!==null),o=new Map;for(let s of r){let a=t.definitionsForFile(s.relativePath).find(l=>l.symbol===s.symbol);a&&o.set(a.symbol,a)}return{matches:[...o.values()],total:i.total,omitted:Math.max(0,i.total-o.size)}}function X0(e){return{symbol:e.symbol,shortName:A(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine}}function Et(e,t){let n=[t.kind,t.fromFile,t.fromSymbol??"",t.toFile,t.toSymbol??"",t.fromBoundaryParticipant?.observationId??"",t.toBoundaryParticipant?.observationId??"",t.fromSourceConstruct?fn(t.fromSourceConstruct):"",t.toSourceConstruct?fn(t.toSourceConstruct):"",t.runtimeBoundaryKey??"",t.line??""].join("\0");e.set(n,t)}function xr(e){return{observationId:e.id,action:e.action,protocol:e.protocol,role:e.role,address:AS(e),file:e.source.file,line:e.source.startLine,endLine:e.source.endLine,ownerName:e.owner.name,ownerSymbol:e.owner.symbol}}function el(e,t){let n=re(e,t.source.file);return yt(e,t.source.file,0,Math.max(0,n.length-1),[t.source.startLine])}function DS(e,t){let n=[...e.values()];for(let i of[t.owner,t.source]){let r=n.filter(o=>o.file===i.file&&o.startLine<=i.startLine&&o.endLine>=i.startLine).sort((o,s)=>o.endLine-o.startLine-(s.endLine-s.startLine)||o.startLine-s.startLine)[0];if(r)return r}return null}function MS(e,t,n,i,r){let o=[],s=n.get(e.id);s!==void 0&&s<=t&&o.push(s);for(let a of i.values()){if(a.depth>t)continue;let l=a.definition;PS(l,e)&&o.push(a.depth)}for(let a of r.values())a.depth>t||PS(a,e)&&o.push(a.depth);return o.length>0?Math.min(...o):null}function PS(e,t){let n=e.relativePath??e.file;return[t.owner,t.source].some(i=>n===i.file&&e.startLine<=i.startLine&&e.endLine>=i.startLine)}function ad(e){return wt("runtime-boundary-participant",e)}function Q0(e,t,n){let i=Lt(e,n),r=Lt(t,n);return i.relativeDir!==r.relativeDir?!0:/(?:^|\/)(?:contracts?|schemas?|db\/schema)(?:\/|$)/u.test(t)}function Z0(e,t,n){return Oo(e,n).id===Oo(t,n).id}function eN(e,t,n,i){if(e.referenceScope==="all")return!0;let r=Oo(t,i).id;return[...n.values()].some(s=>s.promoteBoundaryImports&&Oo(s.file,i).id===r)?!0:e.referenceScope!=="cross-workspace-or-forward"?!1:Lt(t,i).relativeDir!==Lt(e.definition.relativePath,i).relativeDir}function tN(e,t){let n={none:0,"forward-regions":1,"cross-workspace-or-forward":2,all:3};return n[e]>=n[t]?e:t}function nN(e){let t=new Map;for(let[n,i]of e)for(let r of i){let o=t.get(r)??new Set;o.add(n),t.set(r,o)}return t}function Lt(e,t){return t.find(n=>e===n.relativeDir||e.startsWith(`${n.relativeDir}/`))??{name:"root",relativeDir:""}}function iN(e){let t=new Set(["apps","packages","services","crates","libs","tools"]),n=new Map;for(let i of e){let r=i.split("/").filter(Boolean);if(r.length<3||!t.has(r[0]))continue;let o=`${r[0]}/${r[1]}`;n.set(o,{name:r[1],relativeDir:o})}return[...n.values()].sort((i,r)=>r.relativeDir.length-i.relativeDir.length)}function Oo(e,t){let n=Lt(e,t),r=(n.relativeDir?e.slice(n.relativeDir.length+1):e).split("/").filter(Boolean);r[0]==="src"&&r.shift();let o=rN(r);return{id:`region:${n.relativeDir||"root"}:${o}`,label:`${n.name}:${o}`,workspace:n.name,structuralPath:o}}function rN(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 oN(e,t,n,i,r,o,s){let a=Jt([...e.values()],f=>o.get(f.file).id),l=Jt([...t.values()],f=>o.get(f.definition.relativePath).id),c=Jt(n,f=>o.get(f.file).id),u=new Map;for(let f of i)for(let p of new Set([f.fromRegionId,f.toRegionId])){let g=u.get(p)??[];g.push(f),u.set(p,g)}let d=Jt(r,f=>f.toRegionId),m=Jt(r,f=>f.fromRegionId);return[...a.entries()].map(([f,p])=>{let g=o.get(p[0].file),h=l.get(f)??[],b=c.get(f)??[],v=u.get(f)??[],y=s.has(f),I=h.map(lN).sort(mN).slice(0,f0),E=p.filter(S=>J(S.file)==="test").length;return{id:f,label:g.label,workspace:g.workspace,structuralPath:g.structuralPath,minDepth:Math.min(...p.map(S=>S.depth)),fileCount:p.length,sourceFileCount:p.length-E,testFileCount:E,symbolCount:h.length,literalHitCount:b.length,anchorQueries:Me([...b.map(S=>S.query),...h.flatMap(S=>[...S.anchorQueries])]),relationKinds:Me(v.map(S=>S.kind)),incomingRegionIds:Me((d.get(f)??[]).map(S=>S.fromRegionId)),outgoingRegionIds:Me((m.get(f)??[]).map(S=>S.toRegionId)),memberCallCandidateRelationCount:v.filter(S=>S.evidence==="ast-member-import-candidate").length,notableSymbols:I,omittedNotableSymbols:Math.max(0,h.length-I.length),expanded:y,files:y?p.map(sN).sort(fN):[],symbols:y?h.map(aN).sort(pN):[],literalHits:y?[...b].sort(BS):[],relations:y?[...v].sort(_S):[]}}).sort((f,p)=>f.minDepth-p.minDepth||f.label.localeCompare(p.label))}function sN(e){return{file:e.file,kind:J(e.file),depth:e.depth,origins:Me([...e.origins])}}function aN(e){return{symbol:e.definition.symbol,shortName:A(e.definition.symbol),file:e.definition.relativePath,startLine:e.definition.startLine,endLine:e.definition.endLine,depth:e.depth,origins:Me([...e.origins]),anchorQueries:Me([...e.anchorQueries]),referenceExpansion:e.referenceScope!=="none",referenceScope:e.referenceScope}}function lN(e){return{shortName:A(e.definition.symbol),file:e.definition.relativePath,origins:Me([...e.origins])}}function cN(e){return[...Jt(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:Me(n.map(i=>i.kind)),relationCount:n.length,fromFiles:Me(n.map(i=>i.fromFile)),toFiles:Me(n.map(i=>i.toFile)),fromSymbols:Me(n.flatMap(i=>i.fromSymbol?[A(i.fromSymbol)]:[])),toSymbols:Me(n.flatMap(i=>i.toSymbol?[A(i.toSymbol)]:[])),evidence:Me(n.map(i=>i.evidence)),strengths:Me(n.map(i=>i.strength??"unknown"))})).sort((n,i)=>n.fromRegionId.localeCompare(i.fromRegionId)||n.toRegionId.localeCompare(i.toRegionId))}function uN(e,t){return[...e.values()].map(n=>({kind:"external-import",name:n.name,fromRegionIds:Me([...n.fromFiles].flatMap(i=>{let r=t.get(i);return r?[r.id]:[]})),fromFiles:Me([...n.fromFiles])})).sort((n,i)=>n.name.localeCompare(i.name))}function dN(e,t,n,i){let r=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 Me(r.map(o=>i.get(o)?.id).filter(o=>!!o))}function AS(e){return e.keyParts.map(t=>`${t.name}=${t.value}`).join(" ")}function tl(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))]}function Me(e){return[...new Set(e)].sort()}function Jt(e,t){let n=new Map;for(let i of e){let r=t(i),o=n.get(r)??[];o.push(i),n.set(r,o)}return n}function _S(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 mN(e,t){return $o(e.origins)-$o(t.origins)||e.shortName.localeCompare(t.shortName)}function $o(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 fN(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)}function pN(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)||e.symbol.localeCompare(t.symbol)}function BS(e,t){return e.file.localeCompare(t.file)||e.line-t.line||e.query.localeCompare(t.query)}var hN=["causal","structure","complete"],yN={causal:["execution","runtime","dataflow","state","temporal"],structure:["contract","identity","ownership","dependencies"],complete:qt},bN=2,SN=48,OS=64,vN=5e4;function jo(e,t,n={}){let i=An([...t.symbols??[],...t.locations??[]]),r=An(t.searches??[]);if(i.length===0&&r.length===0)throw new Error("evidence requires at least one positional symbol, --symbol, --at, or --search selector.");let o=n.view??"causal",s=CN(n.families,o),a=n.direction??"both",l=An(n.subtypes??[]),c=n.connecting??!1,u=n.inventoryOnly??!1,d=An(n.foldIds??[]),m=n.maxDepth??bN,f=n.maxEdges??SN;if(!Number.isSafeInteger(m)||m<0)throw new RangeError(`Evidence depth must be a non-negative safe integer; received ${m}.`);if(!Number.isSafeInteger(f)||f<=0)throw new RangeError(`Evidence max edges must be a positive safe integer; received ${f}.`);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 p=TS(e,{symbols:i,searches:r,maxDepth:m,maxTopologyCharacters:vN,relations:xN(s)}),g=new Map(p.nodes.map(X=>[X.id,X])),h=p.edges.filter(X=>X.disposition==="emitted"||X.disposition==="folded").flatMap(X=>RN(X,g)),b=h.filter(X=>s.includes(X.family)).filter(X=>l.length===0||l.includes(X.subtype)),v=new Set(p.anchors.flatMap(X=>X.nodeIds));if(c&&v.size<2)throw new Error("Connecting evidence requires at least two resolved root nodes.");let y=new Set(b.map(X=>X.id)),I=md(h,v,"incoming").filter(X=>y.has(X.id)),E=md(h,v,"outgoing").filter(X=>y.has(X.id)),S=md(h,v,"both").filter(X=>y.has(X.id)),x=DN(s,l,I,E,S),C=a==="incoming"?I:a==="outgoing"?E:S,L=c?AN(C,[...v],a):C,w=BN(L,v,a),R=[...L].sort((X,N)=>ON(X,N,w)),M=MN(R,f),_=TN(M,d),D=u?[]:d.length>0?R.filter(X=>_.has(X.id)):R,P=d.length>0?D:D.slice(0,f),k=d.length>0||u?[]:M,V=Math.max(0,D.length-P.length),le=p.frontiers.filter(X=>X.disposition==="unsupported").length,G=p.coverage.status==="incomplete"?"incomplete":V>0?"bounded":"accounted";return{kind:"graph",view:n.families&&n.families.length>0?"custom":o,families:s,selection:{direction:a,subtypes:l,connecting:c,inventoryOnly:u,foldIds:d},targets:p.anchors.map(X=>({kind:X.kind,query:X.query,status:X.status,nodeIds:[...X.nodeIds],omittedCandidates:X.omittedCandidates})),inventory:x,edges:P,folds:k,coverage:{status:G,topologyStatus:p.coverage.status,scope:p.coverage.scope,maxDepth:m,maxEdges:f,matchedEdges:R.length,eligibleEdges:D.length,returnedEdges:P.length,omittedEdges:V,frontierGroups:p.frontiers.length,unsupportedFrontiers:le,blindSpots:An([...p.coverage.blindSpots,...Qf(s)]),explanation:u?`${R.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.`:G==="accounted"?"Every selected relationship in the bounded topology was emitted.":G==="bounded"?`${V} selected relationship(s) were withheld by the explicit edge budget.`:p.coverage.explanation}}}function CN(e,t){let n=e&&e.length>0?e:yN[t],i=n.filter(r=>!qt.includes(r));if(i.length>0)throw new Error(`Unsupported graph evidence family: ${i.join(", ")}.`);return An(n)}function xN(e){return["call","contract-symbol","import","reference","runtime-boundary"]}function RN(e,t){let n=t.get(e.fromNodeId),i=t.get(e.toNodeId);return!n||!i?[]:(e.semantics??[]).flatMap((r,o)=>{let s=EN(r);if(!s)return[];let a=Zf(s,r.subtype);if(!a)throw new Error(`No graph relation provider contract is registered for ${s}/${r.subtype}.`);let l=LN(e);if(!a.relation.evidenceStrengths.includes(l))throw new Error(`Graph relation provider ${a.provider.id} does not admit ${l} evidence for ${s}/${r.subtype}.`);return[{id:`${e.id}:${o}:${s}`,family:s,semanticFamily:r.family,subtype:r.subtype,from:$S(n),to:$S(i),sourceKind:e.kind,providerId:a.provider.id,supportCeiling:a.relation.supportCeiling,establishes:a.relation.establishes,nonClaims:[...a.relation.nonClaims],recoverWith:[...a.relation.recoverWith],evidenceStrength:l,evidenceMethods:An(e.evidence.map(c=>c.method)),evidenceConstituents:IN(e.evidence),context:r.context?{...r.context}:null,attributes:r.attributes?{...r.attributes}:null}]})}function IN(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:i})=>({method:n,strength:i}))}function EN(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 $S(e){let t=wN(e);return{id:e.id,kind:e.kind,label:t?A(t):e.label,symbol:t,location:e.location?{...e.location}:null}}function wN(e){return e.kind!=="symbol"||!e.id.startsWith("symbol:")?null:decodeURIComponent(e.id.slice(7))}function LN(e){let t=An(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 md(e,t,n){let i=fd(e,n),r=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 l=s[a],c=o.get(l);for(let u of i.get(l)??[])r.set(u.edge.id,u.edge),!o.has(u.next)&&(o.set(u.next,c+1),s.push(u.next))}return[...r.values()]}function fd(e,t){let n=new Map,i=(r,o,s)=>{let a=n.get(r)??[];a.push({edge:s,next:o}),n.set(r,a)};for(let r of e)t!=="incoming"&&i(r.from.id,r.to.id,r),t!=="outgoing"&&i(r.to.id,r.from.id,r);for(let r of n.values())r.sort((o,s)=>o.edge.id.localeCompare(s.edge.id)||o.next.localeCompare(s.next));return n}function DN(e,t,n,i,r){let o=new Set;for(let u of[...n,...i,...r])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 f=`${m.family}\0${m.subtype}`;d.set(f,(d.get(f)??0)+1)}return d},a=s(n),l=s(i),c=s(r);return[...o].map(u=>{let[d,m]=u.split("\0");return{family:d,subtype:m,incoming:a.get(u)??0,outgoing:l.get(u)??0,both:c.get(u)??0}}).sort((u,d)=>qt.indexOf(u.family)-qt.indexOf(d.family)||u.subtype.localeCompare(d.subtype))}function MN(e,t){let n=e.slice(t),i=new Map;for(let s of n){let a=PN(s),l=`${s.family}\0${a}`,c=i.get(l)??[];c.push(s),i.set(l,c)}let r=new Map(e.map((s,a)=>[s.id,a+1])),o=[];for(let[s,a]of[...i].sort(([l],[c])=>l.localeCompare(c))){let[l,c]=s.split("\0"),u=[...a].sort((d,m)=>d.id.localeCompare(m.id));for(let d=0;d<u.length;d+=OS){let m=u.slice(d,d+OS),f=m.map(b=>b.id),p=An(m.map(b=>b.subtype)).sort(),g=p.length===1?p[0]:"mixed",h=[...new Set(m.flatMap(b=>[b.from.id,b.to.id]))].sort();o.push({id:NN(l,p.join("\0"),f),mode:FN(m),family:l,subtype:g,subtypes:p,region:c,edgeCount:f.length,edgeIds:f,nodeIds:h,minimumMaxEdges:Math.max(...f.map(b=>r.get(b)??e.length))})}}return o.sort((s,a)=>qt.indexOf(s.family)-qt.indexOf(a.family)||(s.region??"").localeCompare(a.region??"")||s.id.localeCompare(a.id))}function PN(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 TN(e,t){if(t.length===0)return new Set;let n=new Map(e.map(r=>[r.id,r])),i=t.filter(r=>!n.has(r));if(i.length>0){let r=e.map(o=>o.id).sort();throw new Error(`Unknown evidence fold ${i.join(", ")} for this projection. Available folds: ${r.join(", ")||"(none)"}.`)}return new Set(t.flatMap(r=>n.get(r).edgeIds))}function FN(e){let t=new Map,n=new Map,i=new Set;for(let o of e){i.add(o.from.id),i.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 kN(i,t)?"scc":[...i].every(o=>(n.get(o)?.size??0)<=1&&(t.get(o)?.size??0)<=1)?"linear":"topology"}function kN(e,t){let n=new Set,i=new Set,r=o=>{if(n.has(o))return!0;if(i.has(o))return!1;n.add(o);for(let s of t.get(o)??[])if(r(s))return!0;return n.delete(o),i.add(o),!1};return[...e].some(r)}function NN(e,t,n){return`fold:${gN("sha256").update([e,t,...n].join("\0")).digest("hex").slice(0,16)}`}function AN(e,t,n){let i=new Map,r=[...new Set(t)].sort();for(let o=0;o<r.length;o+=1)for(let s=o+1;s<r.length;s+=1)for(let a of _N(e,r[o],r[s],n))i.set(a.id,a);return[...i.values()]}function _N(e,t,n,i){let r=fd(e,i),o=new Map([[t,0]]),s=new Map,a=[t];for(let c=0;c<a.length;c+=1){let u=a[c],d=o.get(u);if(u!==n)for(let m of r.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 l=[];for(let c=n;c!==t;){let u=s.get(c);if(!u)return[];l.push(u.edge),c=u.node}return l.reverse()}function BN(e,t,n){let i=fd(e,n),r=new Map,o=[...t];for(let s of t)r.set(s,0);for(let s=0;s<o.length;s+=1){let a=o[s],l=r.get(a);for(let{next:c}of i.get(a)??[])r.has(c)||(r.set(c,l+1),o.push(c))}return r}function ON(e,t,n){return jS(e,n)-jS(t,n)||HS(e)-HS(t)||US(e.evidenceStrength)-US(t.evidenceStrength)||qt.indexOf(e.family)-qt.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 jS(e,t){return Math.min(t.get(e.from.id)??Number.MAX_SAFE_INTEGER,t.get(e.to.id)??Number.MAX_SAFE_INTEGER)}function HS(e){let t=[e.from,e.to].filter(n=>n.kind==="structural-region").length;return t===2?2:t}function US(e){switch(e){case"exact":return 0;case"mixed":return 1;case"derived":return 2;case"candidate":return 3;case"unknown":return 4}}function An(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))]}function pd(e,t){let n=In(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let i=n.map(()=>"?").join(", "),o=e.all(`SELECT relative_path FROM documents
92
92
  WHERE relative_path IN (${i})
93
- ORDER BY relative_path`,...n).map(c=>c.relative_path).filter(c=>!e.isIgnored(c)),s=Ns(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:c,...u})=>u),a=Sr(e,"forward",n).filter(c=>!e.isIgnored(c)),l=Sr(e,"reverse",n).filter(c=>!e.isIgnored(c));return{files:o,symbols:s,dependsOn:a,dependedOnBy:l}}function Sd(e,t){let n=In(e,t);return n.length===0?[]:GS([...KS(e,n),...YN(e,n)]).filter(i=>!e.isIgnored(i.relative_path)).map(WS)}function JN(e,t){let n=In(e,t);return n.length===0?[]:GS(KS(e,n)).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({...WS(i),basis:"external-reference"}))}function KS(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
93
+ ORDER BY relative_path`,...n).map(c=>c.relative_path).filter(c=>!e.isIgnored(c)),s=Fs(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:c,...u})=>u),a=yr(e,"forward",n).filter(c=>!e.isIgnored(c)),l=yr(e,"reverse",n).filter(c=>!e.isIgnored(c));return{files:o,symbols:s,dependsOn:a,dependedOnBy:l}}function gd(e,t){let n=In(e,t);return n.length===0?[]:qS([...zS(e,n),...jN(e,n)]).filter(i=>!e.isIgnored(i.relative_path)).map(KS)}function $N(e,t){let n=In(e,t);return n.length===0?[]:qS(zS(e,n)).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({...KS(i),basis:"external-reference"}))}function zS(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
94
94
  FROM mentions m
95
95
  JOIN chunks c ON m.chunk_id = c.id
96
96
  JOIN documents d1 ON c.document_id = d1.id
@@ -117,8 +117,8 @@ import{c as tp,e as np,f as qt}from"./chunk-B2OB55RR.js";import{b as kt,c as ec}
117
117
  AND m.role != 1
118
118
  AND ${e.localSymbolPredicate}
119
119
  ${e.pathExclusionsFor("d1")}
120
- ORDER BY d1.relative_path`,...t,...t,...t)}function YN(e,t){let n=new U(e);return t.flatMap(i=>n.definitionsForFile(i).filter(r=>st(r.symbol)).map(r=>({relative_path:i,symbol:r.symbol})))}function GS(e){let t=new Set;return e.filter(n=>{let i=`${n.relative_path}|${n.symbol}`;return t.has(i)?!1:(t.add(i),!0)})}function WS(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:A(e.symbol)}}var zo=new WeakMap,VS=Ct({kind:"definition-exclusions",invalidation:Ye("definition-exclusions"),serialize:e=>JSON.stringify(e),deserialize:XN});function YS(e,t){let n=ye(t);if(!(n==="rust"||n==="typescript"||n==="tsx"||n==="javascript"))return[];let r=se(e,t);if(!r)return[];let o=Nt(e,t,r),s=VS.read(e,t,o);if(s)return s;let a=n==="rust"?oA(e,t):tA(e,t);return VS.write(e,t,o,a),a}function XN(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=t.map(QN);return n.some(i=>i===null)?null:n}catch{return null}}function QN(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?yA(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 XS=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]),ZN=/\b(?:describe|it|test|fdescribe|fit|xdescribe|xit|beforeEach|afterEach|beforeAll|afterAll|before|after|suite|bench|benchmark)\s*\(/,eA=/\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 tA(e,t){let n=se(e,t);if(!n||!nA(n))return[];let i=ae(e,t);if(!i)return[];let r=zo.get(i);if(r)return r;let o=!1,s=i.rootNode;for(let l of s.namedChildren){if(l.type!=="expression_statement")continue;let c=l.namedChild(0);if(!c||c.type!=="call_expression")continue;let u=c.namedChild(0);if(!u)continue;let d=u.type==="member_expression"?u.namedChild(u.namedChildCount-1)?.text:u.text;if(d&&XS.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 l of s.namedChildren){let c=null,u=null;if(l.type==="function_declaration")c=l.namedChild(0)?.text??null,u=l;else if(l.type==="export_statement"){let d=l.namedChild(0);d?.type==="function_declaration"&&(c=d.namedChild(0)?.text??null,u=d)}else if(l.type==="lexical_declaration"){let d=l.namedChild(0);if(d?.type==="variable_declarator"){let m=d.namedChild(0)?.text,f=d.namedChild(1);m&&(f?.type==="arrow_function"||f?.type==="function_expression")&&(c=m,u=d)}}c&&/^use[A-Z]/.test(c)&&u&&a.push({startLine:u.startPosition.row,endLine:u.endPosition.row,reason:"React custom hook (use*)",disposition:"exclude"})}return a.push(...QS(i,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),zo.set(i,a),a}function nA(e){if(e.includes("codebaseiq"))return!0;let t=!1;for(let n of XS)if(e.includes(n)){t=!0;break}return t&&ZN.test(e)?!0:e.includes("use")&&eA.test(e)}var iA=/codebaseiq[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function rA(e){return iA.test(e)}function QS(e,t,n){let i=[],r=o=>{if(t.has(o.type)&&o.parent){let a=o.parent.children,l=-1;for(let c=0;c<a.length;c+=1)if(a[c].startIndex===o.startIndex&&a[c].type===o.type){l=c;break}if(l>0)for(let c=l-1;c>=0;c-=1){let u=a[c];if(n.has(u.type)){if(rA(u.text)){i.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"codebaseiq suppression comment",disposition:"exclude"});break}continue}if(!(u.type==="attribute_item"||u.type==="inner_attribute_item"))break}}for(let s of o.namedChildren)r(s)};return r(e.rootNode),i}function oA(e,t){let n=ae(e,t);if(!n)return[];let i=zo.get(n);if(i)return i;let r=[],o=sA(n);return o?(zo.set(n,o),o):(ZS(n.rootNode,r,!1,!1),r.push(...QS(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"]))),r.push(...gA(n.rootNode)),zo.set(n,r),r)}function sA(e){return bA(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)",disposition:"exclude"}]:null}function ZS(e,t,n,i){let r=n,o=i;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"?aA(e,t,n,i):i&&pA(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"?lA(e,t,n):e.type==="mod_item"&&vd(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(r=!0);for(let s of e.namedChildren)ZS(s,t,r,o)}function aA(e,t,n,i){let r=vd(e),o=null;i?o={reason:"trait impl method (dynamic dispatch)",disposition:"implicit-usage"}:n&&(o={reason:"inside #[cfg(test)] mod",disposition:"exclude"});for(let s of r){if(ev(s)){o={reason:"#[allow(dead_code)]",disposition:"exclude"};break}let a=mA(s);if(a){o=a;break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o.reason,disposition:o.disposition})}function lA(e,t,n){let i=vd(e),r=e.namedChildren.find(o=>o.type==="type_identifier")?.text;i.some(fA)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(...)] - generated impl may access fields",disposition:"implicit-usage",containerName:r}),i.some(ev)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",disposition:"exclude",containerName:r}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",disposition:"exclude",containerName:r})}function vd(e){let t=e.parent;if(!t)return[];let n=t.children,i=-1;for(let o=0;o<n.length;o+=1)if(n[o].startIndex===e.startIndex&&n[o].type===e.type){i=o;break}if(i<=0)return[];let r=[];for(let o=i-1;o>=0;o-=1){let s=n[o];if(s.type==="attribute_item"||s.type==="inner_attribute_item")r.push(s.text);else{if(s.type==="line_comment"||s.type==="block_comment")continue;break}}return r}var cA=new Set(["test","bench","tokio::test","async_std::test"]),uA=new Set(["no_mangle","export_name","link_name","used","macro_export","proc_macro","proc_macro_derive","proc_macro_attribute"]),dA=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 mA(e){if(/#\[\s*cfg\s*\(\s*test\s*\)/.test(e))return{reason:"#[cfg(test)]",disposition:"exclude"};let t=hA(e);return t?cA.has(t)?{reason:`#[${t}]`,disposition:"exclude"}:uA.has(t)?{reason:`Rust ABI/export attribute #[${t}]`,disposition:"implicit-usage"}:dA.has(t)?null:{reason:`Rust attribute macro #[${t}]`,disposition:"implicit-usage"}:null}function fA(e){return/#\[\s*derive\s*\(/.test(e)}function ev(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function pA(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function gA(e){let t=SA(e);if(t.size===0)return[];let n=[];for(let i of e.descendantsOfType("mod_item")){let r=i.childForFieldName("name")?.text;r&&t.has(r)&&n.push({startLine:i.startPosition.row,endLine:i.endPosition.row,reason:'attribute `with = "..."` module - body may be invoked via reflection',disposition:"implicit-usage",containerName:r})}return n}function hA(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 yA(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 bA(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 JS=/\bwith\s*=\s*"([^"]+)"/g;function SA(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){JS.lastIndex=0;let i;for(;(i=JS.exec(n.text))!==null;){let r=i[1],o=r.split("::").pop()??r;o&&t.add(o)}}return t}function tv(e){let t=Cd(e);return(n,i,r,o)=>t(n,i,r,o)?.disposition==="exclude"}function Cd(e){let t=new Map,n=i=>{let r=t.get(i);if(r)return r;let o=YS(e,i),s=new Map;for(let a of o){if(!a.containerName)continue;let l=s.get(a.containerName)??[];l.push(a),s.set(a.containerName,l)}return r={ranges:o,containers:s},t.set(i,r),r};return(i,r,o,s)=>{let a=n(i),l=[];for(let u of a.ranges)r>=u.startLine&&r<=u.endLine&&l.push(u);let c=new Set;s&&c.add(s);for(let u of As(o))c.add(u);for(let u of c){let d=a.containers.get(u);d&&l.push(...d)}return vA(l)}}function vA(e){if(e.length===0)return null;let n=e.find(i=>i.disposition==="exclude")??e[0];return{disposition:n.disposition,reason:n.reason}}function xd(e,t={}){Jl(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function nv(e,t,n={}){Jl(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function iv(e,t){if(t.isIgnoredPath(e.relativePath))return gt("ignored-file");if(De(e.symbol))return gt("module-like-symbol");if(!ol(e.symbol))return gt("non-value-symbol");if(!e.isFunctionLike&&e.enclosingSymbol&&ol(e.enclosingSymbol))return gt("nested-non-callable-value");if(!t.includeTests&&!CA(e.relativePath))return gt("test-file");if(!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName))return gt("excluded-file-region");let n=Y(e.symbol);if(n==="<constructor>")return gt("implicit-constructor");if(e.symbol.startsWith("scip-python ")){if(n==="__all__")return gt("python-runtime-metadata");if(/^__[^_].*__$/.test(n))return gt("python-protocol-member")}return t.isDeclarationOnlyCallable()?gt("declaration-only-callable"):t.isFrameworkContractCallable()?gt("framework-contract-member"):Xe(e.symbol)?gt("rust-trait-impl-member"):Zi(e.symbol)?gt("rust-test-module"):!t.includeMembers&&!xA(e)?gt("member"):e.endLine-e.startLine+1<t.minLoc?gt("below-min-loc"):{accepted:!0}}function CA(e){return J(e)!=="test"}function gt(e){return{accepted:!1,rejectionReason:e}}function ol(e){return _e(e)||e.endsWith("().")||e.endsWith(".")}function xA(e){return st(e.symbol)||As(e.symbol).length===0}function rv(){return new Map}function ov(e,t,n){let i=new Map;for(let r of Bf(e,n))e.isIgnored(r.relative_path)||t.has(r.relative_path)||al(i,r.symbol_id,r.relative_path,r.ref_count,"scip-mention");return i}function sv(e,t,n,i={}){let r=new Set;if(i.conservative||n.size===0){for(let o of $f(e,t))r.add(o.symbol_id);return r}for(let o of Of(e,t))e.isIgnored(o.relative_path)||n.has(o.relative_path)||r.add(o.symbol_id);return r}function Rd(e,t){let n=e.get(t);if(!n)return!1;for(let i of n.values())if(i.occurrences>0)return!0;return!1}function sl(e,t,n){let i=e.get(t);if(!i)return!1;for(let[r,o]of i)if(r!==n&&o.occurrences>0)return!0;return!1}function av(e){return e?.occurrences??0}function al(e,t,n,i,r="source-fallback"){if(i<=0)return;let o=cv(e,t,n);o.occurrences+=i,o.sources.add(r)}function lv(e,t,n,i,r){if(i<=0)return;let o=cv(e,t,n);o.occurrences=Math.max(i,o.occurrences),o.sources.add(r)}function cv(e,t,n){let i=e.get(t);i||(i=new Map,e.set(t,i));let r=i.get(n);return r||(r={occurrences:0,sources:new Set},i.set(n,r)),r}var RA=new Set(["componentDidCatch","componentDidMount","componentDidUpdate","componentWillUnmount","getDerivedStateFromError","getDerivedStateFromProps","getSnapshotBeforeUpdate","render","shouldComponentUpdate","UNSAFE_componentWillMount","UNSAFE_componentWillReceiveProps","UNSAFE_componentWillUpdate"]);function Er(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=ae(e,t.relativePath);if(!n)return!1;let i=n.rootNode.descendantsOfType("method_definition").find(s=>s.startPosition.row<=t.startLine&&s.endPosition.row>=t.endLine);if(!i)return!1;if(/\boverride\b/.test(i.text.slice(0,Math.max(0,i.text.indexOf("{")))))return!0;let r=i.parent;for(;r&&r.type!=="class_declaration"&&r.type!=="class";)r=r.parent;if(!r)return!1;let o=r.text.slice(0,Math.max(0,r.text.indexOf("{")));return/\bimplements\b/.test(o)||/\bextends\b/.test(o)?!0:RA.has(t.leaf)&&/\bextends\s+(?:React\.)?(?:Component|PureComponent)\b/.test(o)}function ji(e,t={}){let{scope:n,minLoc:i=1,includeTests:r=!1,skipBarrels:o=!1,includeMembers:s=!1,deadCodeOnly:a=!1,scanLimit:l,semantic:c=!0}=t,u=0,d=B("dead.candidates",()=>{let S=ke(IA(e,{scope:n,minLoc:i,includeTests:r,includeMembers:s}),l);return u=S.length,S},()=>({definitions:u})),m=0,f=o?B("dead.inactive-barrels",()=>{let S=new Set(yy(e));return m=S.size,S},()=>({paths:m})):new Set,p=0,g=a?rv():B("dead.mention-reference-counts",()=>{let S=ov(e,f,d.map(x=>x.symbolId));return p=S.size,S},()=>({definitions:d.length,symbolsWithReferences:p})),h=0,b=a?B("dead.mentioned-symbol-ids",()=>{let S=sv(e,d.map(x=>x.symbolId),f,{conservative:f.size===0});return h=S.size,S},()=>({definitions:d.length,referencedSymbols:h})):new Set,v=a?d.filter(S=>!b.has(S.symbolId)):d.filter(S=>!sl(g,S.symbolId,S.relativePath));a?B("dead.source-fallback.dead-code-only",()=>TA(e,v,g,{inactiveBarrelPaths:f}),()=>({definitions:v.length,testReferencesIncluded:!0})):B("dead.source-fallback.ast",()=>PA(e,v,g,{inactiveBarrelPaths:f}),()=>({definitions:v.length,testReferencesIncluded:!0}));let y=a?v.filter(S=>!Rd(g,S.symbolId)):v.filter(S=>!sl(g,S.symbolId,S.relativePath)),I=new Set;B("dead.caller-map-supplement",()=>{I=AA(e,y,g,{inactiveBarrelPaths:f,includeSemantic:!a&&c})},()=>({definitions:y.length,semantic:!a&&c}));let E=a?v.filter(S=>!Rd(g,S.symbolId)):d.filter(S=>!I.has(S.symbolId));return MA(e,LA(E,g))}function IA(e,t){let n=tv(e),i=[];for(let r of Ur(e,{scope:t.scope,symbolMatches:ol,sqlPrefilter:"function-like"}))iv(r,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:s=>e.isIgnored(s),isExcludedRegion:n,isDeclarationOnlyCallable:()=>wA(e,r),isFrameworkContractCallable:()=>Er(e,r)}).accepted&&i.push(r);return i}var EA=["method_signature","abstract_method_signature","call_signature","construct_signature"];function wA(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=ae(e,t.relativePath);if(n)return n.rootNode.descendantsOfType([...EA]).some(r=>r.startPosition.row<=t.startLine&&r.endPosition.row>=t.endLine);let i=re(e,t.relativePath).slice(t.startLine,t.endLine+1).join(`
121
- `).trim();return i.endsWith(";")&&!i.includes("=>")&&!i.includes("{")}function LA(e,t){return e.map(n=>DA(n,t)).filter(n=>n.cross_file_refs===0).sort((n,i)=>i.loc-n.loc||n.relative_path.localeCompare(i.relative_path)||n.start_line-i.start_line)}function DA(e,t){let n=t.get(e.symbolId)??new Map,i=av(n.get(e.relativePath)),r=0;for(let[o,s]of n)o!==e.relativePath&&(r+=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:i,cross_file_refs:r}}function MA(e,t){let n=Cd(e),i=[],r=0,o=0,s=0,a=0,l=0,c=0;for(let u of t){if(e.isIgnored(u.relative_path))continue;if(Qe(e,u.relative_path)){a++;continue}if(qe(e,u.symbol,u.relative_path)){l++;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,f=m?"implicit-usage":u.same_file_refs===0?"dead-code":"file-internal";f==="dead-code"?r++:f==="file-internal"?o++:s++,c+=u.loc,i.push({relativePath:u.relative_path,startLine:u.start_line,endLine:u.end_line,loc:u.loc,symbol:u.symbol,shortName:A(u.symbol),sameFileRefs:u.same_file_refs,kind:f,...m?{implicitUsageReason:m}:{}})}return{symbols:i,counts:{total:i.length,deadCode:r,fileInternal:o,implicitUsage:s,loc:c},applicability:{entrySurfaceExcluded:a,externalRootExcluded:l,implicitUsageSignals:s},totalCount:i.length,deadCodeCount:r,fileInternalCount:o,implicitUsageCount:s,totalLoc:c}}function PA(e,t,n,i){if(t.length===0)return;let r=new U(e),o=new Set(t.map(l=>l.symbolId)),s=new Set(t.map(l=>l.leaf).filter(Boolean)),a=new Set(r.sourceFiles());for(let l of me(e))a.add(l);r.scanSourceReferences({paths:a,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:s,skipPath:l=>i.inactiveBarrelPaths.has(l)},l=>{o.has(l.target.symbolId)&&(kA(e,l)||al(n,l.target.symbolId,l.sourceFile,NA(l),"source-fallback"))})}function TA(e,t,n,i){if(t.length===0)return;let r=new U(e),o=Ff(t),s=new Set(r.sourceFiles());for(let u of me(e))s.add(u);let a=new Set(o.keys()),l=new Map,c=u=>{let d=l.get(u);return d||(d=Uf(e,u),l.set(u,d)),d};r.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:u=>i.inactiveBarrelPaths.has(u),resolveTargets:({sourceFile:u,name:d,kind:m})=>{let f=o.get(d);return f?FA(u,d,f,()=>c(u),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:u=>{l.delete(u),nv(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&uv(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||al(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function FA(e,t,n,i,r){let o=n.filter(c=>c.relativePath===e);if(o.length>0)return o;if(!r.permissive&&n.length===1)return[...n];let s=i(),a=s.get(t);if(a)for(let c of a){let u=n.filter(d=>Tt(c,d.relativePath));if(u.length>0)return u}let l=new Set;for(let c of s.values())for(let u of c)l.add(u);for(let c of l){let u=n.filter(d=>Tt(c,d.relativePath));if(u.length>0&&u.length===n.length)return u}return r.permissive?[...n]:[]}function kA(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&uv(e,t)}function NA(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function uv(e,t){return t.occurrences>1?!1:Ce(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function AA(e,t,n,i){let r=new Set,o=i.includeSemantic!==!1,s=(u,d)=>{d===u.relativePath||e.isIgnored(d)||i.inactiveBarrelPaths.has(d)||lv(n,u.symbolId,d,1,"caller-map")};if(B("dead.caller-map.per-symbol-non-semantic",()=>{for(let u of t){let d=Gs(e,u,{semantic:!1,semanticEvidence:ge});for(let m of d)s(u,m.file)}},()=>({definitions:t.length,semantic:!1})),!o)return r;let a=0,l=B("dead.caller-map.semantic-candidates",()=>{let u=t.filter(d=>!sl(n,d.symbolId,d.relativePath));return a=u.length,u},()=>({definitions:t.length,semanticCandidates:a}));if(l.length===0)return r;let c=Ln(e,l);for(let u of c.incompleteSymbolIds)r.add(u);for(let u of c.unavailableSymbolIds)r.add(u);for(let u of l){let d=c.callers.get(u.symbolId);if(d)for(let m of d)s(u,m)}return r}function _A(e,t={}){let{limit:n=30,scope:i}=t,r=i?"AND def_d.relative_path LIKE ?":"",o=i?[`%${i}%`]:[],a=e.all(`SELECT
120
+ ORDER BY d1.relative_path`,...t,...t,...t)}function jN(e,t){let n=new U(e);return t.flatMap(i=>n.definitionsForFile(i).filter(r=>st(r.symbol)).map(r=>({relative_path:i,symbol:r.symbol})))}function qS(e){let t=new Set;return e.filter(n=>{let i=`${n.relative_path}|${n.symbol}`;return t.has(i)?!1:(t.add(i),!0)})}function KS(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:A(e.symbol)}}var Ho=new WeakMap,GS=Ct({kind:"definition-exclusions",invalidation:Ye("definition-exclusions"),serialize:e=>JSON.stringify(e),deserialize:HN});function VS(e,t){let n=ye(t);if(!(n==="rust"||n==="typescript"||n==="tsx"||n==="javascript"))return[];let r=se(e,t);if(!r)return[];let o=Nt(e,t,r),s=GS.read(e,t,o);if(s)return s;let a=n==="rust"?JN(e,t):KN(e,t);return GS.write(e,t,o,a),a}function HN(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=t.map(UN);return n.some(i=>i===null)?null:n}catch{return null}}function UN(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?aA(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 JS=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]),zN=/\b(?:describe|it|test|fdescribe|fit|xdescribe|xit|beforeEach|afterEach|beforeAll|afterAll|before|after|suite|bench|benchmark)\s*\(/,qN=/\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 KN(e,t){let n=se(e,t);if(!n||!GN(n))return[];let i=ae(e,t);if(!i)return[];let r=Ho.get(i);if(r)return r;let o=!1,s=i.rootNode;for(let l of s.namedChildren){if(l.type!=="expression_statement")continue;let c=l.namedChild(0);if(!c||c.type!=="call_expression")continue;let u=c.namedChild(0);if(!u)continue;let d=u.type==="member_expression"?u.namedChild(u.namedChildCount-1)?.text:u.text;if(d&&JS.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 l of s.namedChildren){let c=null,u=null;if(l.type==="function_declaration")c=l.namedChild(0)?.text??null,u=l;else if(l.type==="export_statement"){let d=l.namedChild(0);d?.type==="function_declaration"&&(c=d.namedChild(0)?.text??null,u=d)}else if(l.type==="lexical_declaration"){let d=l.namedChild(0);if(d?.type==="variable_declarator"){let m=d.namedChild(0)?.text,f=d.namedChild(1);m&&(f?.type==="arrow_function"||f?.type==="function_expression")&&(c=m,u=d)}}c&&/^use[A-Z]/.test(c)&&u&&a.push({startLine:u.startPosition.row,endLine:u.endPosition.row,reason:"React custom hook (use*)",disposition:"exclude"})}return a.push(...YS(i,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),Ho.set(i,a),a}function GN(e){if(e.includes("codebaseiq"))return!0;let t=!1;for(let n of JS)if(e.includes(n)){t=!0;break}return t&&zN.test(e)?!0:e.includes("use")&&qN.test(e)}var WN=/codebaseiq[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function VN(e){return WN.test(e)}function YS(e,t,n){let i=[],r=o=>{if(t.has(o.type)&&o.parent){let a=o.parent.children,l=-1;for(let c=0;c<a.length;c+=1)if(a[c].startIndex===o.startIndex&&a[c].type===o.type){l=c;break}if(l>0)for(let c=l-1;c>=0;c-=1){let u=a[c];if(n.has(u.type)){if(VN(u.text)){i.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"codebaseiq suppression comment",disposition:"exclude"});break}continue}if(!(u.type==="attribute_item"||u.type==="inner_attribute_item"))break}}for(let s of o.namedChildren)r(s)};return r(e.rootNode),i}function JN(e,t){let n=ae(e,t);if(!n)return[];let i=Ho.get(n);if(i)return i;let r=[],o=YN(n);return o?(Ho.set(n,o),o):(XS(n.rootNode,r,!1,!1),r.push(...YS(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"]))),r.push(...oA(n.rootNode)),Ho.set(n,r),r)}function YN(e){return lA(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)",disposition:"exclude"}]:null}function XS(e,t,n,i){let r=n,o=i;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"?XN(e,t,n,i):i&&rA(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"?QN(e,t,n):e.type==="mod_item"&&hd(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(r=!0);for(let s of e.namedChildren)XS(s,t,r,o)}function XN(e,t,n,i){let r=hd(e),o=null;i?o={reason:"trait impl method (dynamic dispatch)",disposition:"implicit-usage"}:n&&(o={reason:"inside #[cfg(test)] mod",disposition:"exclude"});for(let s of r){if(QS(s)){o={reason:"#[allow(dead_code)]",disposition:"exclude"};break}let a=nA(s);if(a){o=a;break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o.reason,disposition:o.disposition})}function QN(e,t,n){let i=hd(e),r=e.namedChildren.find(o=>o.type==="type_identifier")?.text;i.some(iA)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(...)] - generated impl may access fields",disposition:"implicit-usage",containerName:r}),i.some(QS)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",disposition:"exclude",containerName:r}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",disposition:"exclude",containerName:r})}function hd(e){let t=e.parent;if(!t)return[];let n=t.children,i=-1;for(let o=0;o<n.length;o+=1)if(n[o].startIndex===e.startIndex&&n[o].type===e.type){i=o;break}if(i<=0)return[];let r=[];for(let o=i-1;o>=0;o-=1){let s=n[o];if(s.type==="attribute_item"||s.type==="inner_attribute_item")r.push(s.text);else{if(s.type==="line_comment"||s.type==="block_comment")continue;break}}return r}var ZN=new Set(["test","bench","tokio::test","async_std::test"]),eA=new Set(["no_mangle","export_name","link_name","used","macro_export","proc_macro","proc_macro_derive","proc_macro_attribute"]),tA=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 nA(e){if(/#\[\s*cfg\s*\(\s*test\s*\)/.test(e))return{reason:"#[cfg(test)]",disposition:"exclude"};let t=sA(e);return t?ZN.has(t)?{reason:`#[${t}]`,disposition:"exclude"}:eA.has(t)?{reason:`Rust ABI/export attribute #[${t}]`,disposition:"implicit-usage"}:tA.has(t)?null:{reason:`Rust attribute macro #[${t}]`,disposition:"implicit-usage"}:null}function iA(e){return/#\[\s*derive\s*\(/.test(e)}function QS(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function rA(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function oA(e){let t=cA(e);if(t.size===0)return[];let n=[];for(let i of e.descendantsOfType("mod_item")){let r=i.childForFieldName("name")?.text;r&&t.has(r)&&n.push({startLine:i.startPosition.row,endLine:i.endPosition.row,reason:'attribute `with = "..."` module - body may be invoked via reflection',disposition:"implicit-usage",containerName:r})}return n}function sA(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 aA(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 lA(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 WS=/\bwith\s*=\s*"([^"]+)"/g;function cA(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){WS.lastIndex=0;let i;for(;(i=WS.exec(n.text))!==null;){let r=i[1],o=r.split("::").pop()??r;o&&t.add(o)}}return t}function ZS(e){let t=yd(e);return(n,i,r,o)=>t(n,i,r,o)?.disposition==="exclude"}function yd(e){let t=new Map,n=i=>{let r=t.get(i);if(r)return r;let o=VS(e,i),s=new Map;for(let a of o){if(!a.containerName)continue;let l=s.get(a.containerName)??[];l.push(a),s.set(a.containerName,l)}return r={ranges:o,containers:s},t.set(i,r),r};return(i,r,o,s)=>{let a=n(i),l=[];for(let u of a.ranges)r>=u.startLine&&r<=u.endLine&&l.push(u);let c=new Set;s&&c.add(s);for(let u of ks(o))c.add(u);for(let u of c){let d=a.containers.get(u);d&&l.push(...d)}return uA(l)}}function uA(e){if(e.length===0)return null;let n=e.find(i=>i.disposition==="exclude")??e[0];return{disposition:n.disposition,reason:n.reason}}function bd(e,t={}){Vl(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function ev(e,t,n={}){Vl(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function tv(e,t){if(t.isIgnoredPath(e.relativePath))return gt("ignored-file");if(De(e.symbol))return gt("module-like-symbol");if(!rl(e.symbol))return gt("non-value-symbol");if(!e.isFunctionLike&&e.enclosingSymbol&&rl(e.enclosingSymbol))return gt("nested-non-callable-value");if(!t.includeTests&&!dA(e.relativePath))return gt("test-file");if(!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName))return gt("excluded-file-region");let n=Y(e.symbol);if(n==="<constructor>")return gt("implicit-constructor");if(e.symbol.startsWith("scip-python ")){if(n==="__all__")return gt("python-runtime-metadata");if(/^__[^_].*__$/.test(n))return gt("python-protocol-member")}return t.isDeclarationOnlyCallable()?gt("declaration-only-callable"):t.isFrameworkContractCallable()?gt("framework-contract-member"):Xe(e.symbol)?gt("rust-trait-impl-member"):Xi(e.symbol)?gt("rust-test-module"):!t.includeMembers&&!mA(e)?gt("member"):e.endLine-e.startLine+1<t.minLoc?gt("below-min-loc"):{accepted:!0}}function dA(e){return J(e)!=="test"}function gt(e){return{accepted:!1,rejectionReason:e}}function rl(e){return _e(e)||e.endsWith("().")||e.endsWith(".")}function mA(e){return st(e.symbol)||ks(e.symbol).length===0}function nv(){return new Map}function iv(e,t,n){let i=new Map;for(let r of kf(e,n))e.isIgnored(r.relative_path)||t.has(r.relative_path)||sl(i,r.symbol_id,r.relative_path,r.ref_count,"scip-mention");return i}function rv(e,t,n,i={}){let r=new Set;if(i.conservative||n.size===0){for(let o of Af(e,t))r.add(o.symbol_id);return r}for(let o of Nf(e,t))e.isIgnored(o.relative_path)||n.has(o.relative_path)||r.add(o.symbol_id);return r}function Sd(e,t){let n=e.get(t);if(!n)return!1;for(let i of n.values())if(i.occurrences>0)return!0;return!1}function ol(e,t,n){let i=e.get(t);if(!i)return!1;for(let[r,o]of i)if(r!==n&&o.occurrences>0)return!0;return!1}function ov(e){return e?.occurrences??0}function sl(e,t,n,i,r="source-fallback"){if(i<=0)return;let o=av(e,t,n);o.occurrences+=i,o.sources.add(r)}function sv(e,t,n,i,r){if(i<=0)return;let o=av(e,t,n);o.occurrences=Math.max(i,o.occurrences),o.sources.add(r)}function av(e,t,n){let i=e.get(t);i||(i=new Map,e.set(t,i));let r=i.get(n);return r||(r={occurrences:0,sources:new Set},i.set(n,r)),r}var fA=new Set(["componentDidCatch","componentDidMount","componentDidUpdate","componentWillUnmount","getDerivedStateFromError","getDerivedStateFromProps","getSnapshotBeforeUpdate","render","shouldComponentUpdate","UNSAFE_componentWillMount","UNSAFE_componentWillReceiveProps","UNSAFE_componentWillUpdate"]);function Rr(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=ae(e,t.relativePath);if(!n)return!1;let i=n.rootNode.descendantsOfType("method_definition").find(s=>s.startPosition.row<=t.startLine&&s.endPosition.row>=t.endLine);if(!i)return!1;if(/\boverride\b/.test(i.text.slice(0,Math.max(0,i.text.indexOf("{")))))return!0;let r=i.parent;for(;r&&r.type!=="class_declaration"&&r.type!=="class";)r=r.parent;if(!r)return!1;let o=r.text.slice(0,Math.max(0,r.text.indexOf("{")));return/\bimplements\b/.test(o)||/\bextends\b/.test(o)?!0:fA.has(t.leaf)&&/\bextends\s+(?:React\.)?(?:Component|PureComponent)\b/.test(o)}function ji(e,t={}){let{scope:n,minLoc:i=1,includeTests:r=!1,skipBarrels:o=!1,includeMembers:s=!1,deadCodeOnly:a=!1,scanLimit:l,semantic:c=!0}=t,u=0,d=B("dead.candidates",()=>{let S=ke(pA(e,{scope:n,minLoc:i,includeTests:r,includeMembers:s}),l);return u=S.length,S},()=>({definitions:u})),m=0,f=o?B("dead.inactive-barrels",()=>{let S=new Set(gy(e));return m=S.size,S},()=>({paths:m})):new Set,p=0,g=a?nv():B("dead.mention-reference-counts",()=>{let S=iv(e,f,d.map(x=>x.symbolId));return p=S.size,S},()=>({definitions:d.length,symbolsWithReferences:p})),h=0,b=a?B("dead.mentioned-symbol-ids",()=>{let S=rv(e,d.map(x=>x.symbolId),f,{conservative:f.size===0});return h=S.size,S},()=>({definitions:d.length,referencedSymbols:h})):new Set,v=a?d.filter(S=>!b.has(S.symbolId)):d.filter(S=>!ol(g,S.symbolId,S.relativePath));a?B("dead.source-fallback.dead-code-only",()=>CA(e,v,g,{inactiveBarrelPaths:f}),()=>({definitions:v.length,testReferencesIncluded:!0})):B("dead.source-fallback.ast",()=>vA(e,v,g,{inactiveBarrelPaths:f}),()=>({definitions:v.length,testReferencesIncluded:!0}));let y=a?v.filter(S=>!Sd(g,S.symbolId)):v.filter(S=>!ol(g,S.symbolId,S.relativePath)),I=new Set;B("dead.caller-map-supplement",()=>{I=EA(e,y,g,{inactiveBarrelPaths:f,includeSemantic:!a&&c})},()=>({definitions:y.length,semantic:!a&&c}));let E=a?v.filter(S=>!Sd(g,S.symbolId)):d.filter(S=>!I.has(S.symbolId));return SA(e,yA(E,g))}function pA(e,t){let n=ZS(e),i=[];for(let r of jr(e,{scope:t.scope,symbolMatches:rl,sqlPrefilter:"function-like"}))tv(r,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:s=>e.isIgnored(s),isExcludedRegion:n,isDeclarationOnlyCallable:()=>hA(e,r),isFrameworkContractCallable:()=>Rr(e,r)}).accepted&&i.push(r);return i}var gA=["method_signature","abstract_method_signature","call_signature","construct_signature"];function hA(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=ae(e,t.relativePath);if(n)return n.rootNode.descendantsOfType([...gA]).some(r=>r.startPosition.row<=t.startLine&&r.endPosition.row>=t.endLine);let i=re(e,t.relativePath).slice(t.startLine,t.endLine+1).join(`
121
+ `).trim();return i.endsWith(";")&&!i.includes("=>")&&!i.includes("{")}function yA(e,t){return e.map(n=>bA(n,t)).filter(n=>n.cross_file_refs===0).sort((n,i)=>i.loc-n.loc||n.relative_path.localeCompare(i.relative_path)||n.start_line-i.start_line)}function bA(e,t){let n=t.get(e.symbolId)??new Map,i=ov(n.get(e.relativePath)),r=0;for(let[o,s]of n)o!==e.relativePath&&(r+=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:i,cross_file_refs:r}}function SA(e,t){let n=yd(e),i=[],r=0,o=0,s=0,a=0,l=0,c=0;for(let u of t){if(e.isIgnored(u.relative_path))continue;if(Qe(e,u.relative_path)){a++;continue}if(qe(e,u.symbol,u.relative_path)){l++;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,f=m?"implicit-usage":u.same_file_refs===0?"dead-code":"file-internal";f==="dead-code"?r++:f==="file-internal"?o++:s++,c+=u.loc,i.push({relativePath:u.relative_path,startLine:u.start_line,endLine:u.end_line,loc:u.loc,symbol:u.symbol,shortName:A(u.symbol),sameFileRefs:u.same_file_refs,kind:f,...m?{implicitUsageReason:m}:{}})}return{symbols:i,counts:{total:i.length,deadCode:r,fileInternal:o,implicitUsage:s,loc:c},applicability:{entrySurfaceExcluded:a,externalRootExcluded:l,implicitUsageSignals:s},totalCount:i.length,deadCodeCount:r,fileInternalCount:o,implicitUsageCount:s,totalLoc:c}}function vA(e,t,n,i){if(t.length===0)return;let r=new U(e),o=new Set(t.map(l=>l.symbolId)),s=new Set(t.map(l=>l.leaf).filter(Boolean)),a=new Set(r.sourceFiles());for(let l of me(e))a.add(l);r.scanSourceReferences({paths:a,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:s,skipPath:l=>i.inactiveBarrelPaths.has(l)},l=>{o.has(l.target.symbolId)&&(RA(e,l)||sl(n,l.target.symbolId,l.sourceFile,IA(l),"source-fallback"))})}function CA(e,t,n,i){if(t.length===0)return;let r=new U(e),o=Df(t),s=new Set(r.sourceFiles());for(let u of me(e))s.add(u);let a=new Set(o.keys()),l=new Map,c=u=>{let d=l.get(u);return d||(d=Of(e,u),l.set(u,d)),d};r.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:u=>i.inactiveBarrelPaths.has(u),resolveTargets:({sourceFile:u,name:d,kind:m})=>{let f=o.get(d);return f?xA(u,d,f,()=>c(u),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:u=>{l.delete(u),ev(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&lv(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||sl(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function xA(e,t,n,i,r){let o=n.filter(c=>c.relativePath===e);if(o.length>0)return o;if(!r.permissive&&n.length===1)return[...n];let s=i(),a=s.get(t);if(a)for(let c of a){let u=n.filter(d=>Tt(c,d.relativePath));if(u.length>0)return u}let l=new Set;for(let c of s.values())for(let u of c)l.add(u);for(let c of l){let u=n.filter(d=>Tt(c,d.relativePath));if(u.length>0&&u.length===n.length)return u}return r.permissive?[...n]:[]}function RA(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&lv(e,t)}function IA(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function lv(e,t){return t.occurrences>1?!1:Ce(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function EA(e,t,n,i){let r=new Set,o=i.includeSemantic!==!1,s=(u,d)=>{d===u.relativePath||e.isIgnored(d)||i.inactiveBarrelPaths.has(d)||sv(n,u.symbolId,d,1,"caller-map")};if(B("dead.caller-map.per-symbol-non-semantic",()=>{for(let u of t){let d=Ks(e,u,{semantic:!1,semanticEvidence:ge});for(let m of d)s(u,m.file)}},()=>({definitions:t.length,semantic:!1})),!o)return r;let a=0,l=B("dead.caller-map.semantic-candidates",()=>{let u=t.filter(d=>!ol(n,d.symbolId,d.relativePath));return a=u.length,u},()=>({definitions:t.length,semanticCandidates:a}));if(l.length===0)return r;let c=Ln(e,l);for(let u of c.incompleteSymbolIds)r.add(u);for(let u of c.unavailableSymbolIds)r.add(u);for(let u of l){let d=c.callers.get(u.symbolId);if(d)for(let m of d)s(u,m)}return r}function wA(e,t={}){let{limit:n=30,scope:i}=t,r=i?"AND def_d.relative_path LIKE ?":"",o=i?[`%${i}%`]:[],a=e.all(`SELECT
122
122
  gs.symbol,
123
123
  COUNT(*) AS ref_count,
124
124
  COUNT(DISTINCT ref_d.id) AS file_count,
@@ -142,14 +142,14 @@ import{c as tp,e as np,f as qt}from"./chunk-B2OB55RR.js";import{b as kt,c as ec}
142
142
  ${r}
143
143
  GROUP BY gs.id
144
144
  ORDER BY ref_count DESC
145
- LIMIT ?`,...o,n).filter(l=>!e.isIgnored(l.defined_in)).map(l=>({symbol:l.symbol,shortName:A(l.symbol),refCount:l.ref_count,fileCount:l.file_count,definedIn:l.defined_in,basis:"scip-cross-file-mentions",countUnit:"reference-occurrences"}));return a.length>0?{rows:a,coverage:{semanticEvidence:{enabled:!1,status:"disabled",incompleteSymbolCount:0,unavailableSymbolCount:0}}}:BA(e,i,n)}function BA(e,t,n){let i=Ue(e,{scope:t}).filter(a=>!e.isIgnored(a.relativePath)),r=sn(e,i,{limit:500,semanticEvidence:ge}),o=i.filter(a=>!r.incompleteSymbolIds.has(a.symbolId)&&!r.unavailableSymbolIds.has(a.symbolId)).map(a=>OA(a,r.rows.get(a.symbolId)??[])).filter(a=>a.refCount>0).sort((a,l)=>l.refCount-a.refCount||l.fileCount-a.fileCount).slice(0,n),s=r.incompleteSymbolIds.size>0&&r.unavailableSymbolIds.size>0?"incomplete-and-unavailable":r.incompleteSymbolIds.size>0?"incomplete":r.unavailableSymbolIds.size>0?"unavailable":"complete";return{rows:o,coverage:{semanticEvidence:{enabled:!0,status:s,incompleteSymbolCount:r.incompleteSymbolIds.size,unavailableSymbolCount:r.unavailableSymbolIds.size}}}}function OA(e,t){let n=t.filter(i=>i.file!==e.relativePath);return{symbol:e.symbol,shortName:A(e.symbol),refCount:n.length,fileCount:new Set(n.map(i=>i.file)).size,definedIn:e.relativePath,basis:"source-backed-incoming-evidence",countUnit:"distinct-incoming-evidence-rows"}}function $A(e,t,n={}){return JA(e,t,n)?.map(i=>({symbol:i.symbol,shortName:i.shortName,fromFile:i.fromFile}))??[]}function jA(e,t){let n=pe(e,t),i=zA(e,t);if(i.length>0&&!KA(n))return i;let r=qA(e,t,n);return Id(t)&&r.length>0?r:GA([...i,...r])}function HA(e,t,n={}){let i=dt(e,t);if(!i)return[];let r=mv(e,i),o=n.semantic===!1?null:dv(e,i);return(o?UA(o,r):r).filter(a=>!a.used).map(a=>({symbol:a.symbol,shortName:a.shortName,importedIn:a.importer}))}function UA(e,t){let n=new Map;for(let r of t){let o=n.get(r.shortName);o?o.push(r):n.set(r.shortName,[r])}let i=e.map(r=>{let o=n.get(r.shortName),s=o?.shift();return o?.length===0&&n.delete(r.shortName),s?{...r,used:r.used||s.used}:r});return i.push(...[...n.values()].flat()),i}function zA(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
145
+ LIMIT ?`,...o,n).filter(l=>!e.isIgnored(l.defined_in)).map(l=>({symbol:l.symbol,shortName:A(l.symbol),refCount:l.ref_count,fileCount:l.file_count,definedIn:l.defined_in,basis:"scip-cross-file-mentions",countUnit:"reference-occurrences"}));return a.length>0?{rows:a,coverage:{semanticEvidence:{enabled:!1,status:"disabled",incompleteSymbolCount:0,unavailableSymbolCount:0}}}:LA(e,i,n)}function LA(e,t,n){let i=Ue(e,{scope:t}).filter(a=>!e.isIgnored(a.relativePath)),r=sn(e,i,{limit:500,semanticEvidence:ge}),o=i.filter(a=>!r.incompleteSymbolIds.has(a.symbolId)&&!r.unavailableSymbolIds.has(a.symbolId)).map(a=>DA(a,r.rows.get(a.symbolId)??[])).filter(a=>a.refCount>0).sort((a,l)=>l.refCount-a.refCount||l.fileCount-a.fileCount).slice(0,n),s=r.incompleteSymbolIds.size>0&&r.unavailableSymbolIds.size>0?"incomplete-and-unavailable":r.incompleteSymbolIds.size>0?"incomplete":r.unavailableSymbolIds.size>0?"unavailable":"complete";return{rows:o,coverage:{semanticEvidence:{enabled:!0,status:s,incompleteSymbolCount:r.incompleteSymbolIds.size,unavailableSymbolCount:r.unavailableSymbolIds.size}}}}function DA(e,t){let n=t.filter(i=>i.file!==e.relativePath);return{symbol:e.symbol,shortName:A(e.symbol),refCount:n.length,fileCount:new Set(n.map(i=>i.file)).size,definedIn:e.relativePath,basis:"source-backed-incoming-evidence",countUnit:"distinct-incoming-evidence-rows"}}function MA(e,t,n={}){return $A(e,t,n)?.map(i=>({symbol:i.symbol,shortName:i.shortName,fromFile:i.fromFile}))??[]}function PA(e,t){let n=pe(e,t),i=kA(e,t);if(i.length>0&&!AA(n))return i;let r=NA(e,t,n);return vd(t)&&r.length>0?r:_A([...i,...r])}function TA(e,t,n={}){let i=dt(e,t);if(!i)return[];let r=uv(e,i),o=n.semantic===!1?null:cv(e,i);return(o?FA(o,r):r).filter(a=>!a.used).map(a=>({symbol:a.symbol,shortName:a.shortName,importedIn:a.importer}))}function FA(e,t){let n=new Map;for(let r of t){let o=n.get(r.shortName);o?o.push(r):n.set(r.shortName,[r])}let i=e.map(r=>{let o=n.get(r.shortName),s=o?.shift();return o?.length===0&&n.delete(r.shortName),s?{...r,used:r.used||s.used}:r});return i.push(...[...n.values()].flat()),i}function kA(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
146
146
  FROM mentions m
147
147
  JOIN chunks c ON m.chunk_id = c.id
148
148
  JOIN documents d ON c.document_id = d.id
149
149
  JOIN global_symbols gs ON m.symbol_id = gs.id
150
150
  WHERE gs.symbol LIKE ?
151
151
  AND m.role = 2
152
- ORDER BY d.relative_path`,`%${t}%`).filter(i=>!e.isIgnored(i.importer)).map(i=>({symbol:i.symbol,shortName:A(i.symbol),fromFile:i.importer}))}function qA(e,t,n=pe(e,t)){let i=n?.relativePath??null,r=n?Y(n.symbol):t.replace(/\(\)$/,""),o=n?De(n.symbol):!1,s=new Set;for(let l of me(e,{includeIgnored:!1}))for(let c of Ce(e,l))WA(c,l,{targetFile:i,targetLeaf:r,targetIsModule:o,targetPattern:t})&&s.add(l);let a=Id(t)?t.trim():null;return[...s].sort().map(l=>({symbol:a??n?.symbol??r,shortName:a??(n?A(n.symbol):r),fromFile:l}))}function KA(e){return!!(e&&(e.symbol.startsWith("scip-clojure ")||ye(e.relativePath)==="clojure"))}function GA(e){let t=new Set,n=[];for(let i of e){let r=`${i.symbol}|${i.fromFile}`;t.has(r)||(t.add(r),n.push(i))}return n.sort((i,r)=>i.fromFile.localeCompare(r.fromFile)||i.shortName.localeCompare(r.shortName))}function WA(e,t,n){return!e.sourcePath||n.targetFile&&ht(e.sourcePath)!==ht(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&ZA(t)||e.kind==="namespace"&&VA(e,n.targetPattern)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function VA(e,t){let n=t.trim().replace(/\(\)$/,"");return Id(n)?e.importedName===n||e.localName===n:!1}function Id(e){let t=e.trim().replace(/\(\)$/,"");return t.includes(".")&&!t.includes("/")&&!t.includes(":")}function JA(e,t,n={}){let i=dt(e,t);return i?YA(e,i,n)??(n.semantic===!1?null:dv(e,i))??mv(e,i):null}function YA(e,t,n){let r=e.all(`SELECT DISTINCT
152
+ ORDER BY d.relative_path`,`%${t}%`).filter(i=>!e.isIgnored(i.importer)).map(i=>({symbol:i.symbol,shortName:A(i.symbol),fromFile:i.importer}))}function NA(e,t,n=pe(e,t)){let i=n?.relativePath??null,r=n?Y(n.symbol):t.replace(/\(\)$/,""),o=n?De(n.symbol):!1,s=new Set;for(let l of me(e,{includeIgnored:!1}))for(let c of Ce(e,l))BA(c,l,{targetFile:i,targetLeaf:r,targetIsModule:o,targetPattern:t})&&s.add(l);let a=vd(t)?t.trim():null;return[...s].sort().map(l=>({symbol:a??n?.symbol??r,shortName:a??(n?A(n.symbol):r),fromFile:l}))}function AA(e){return!!(e&&(e.symbol.startsWith("scip-clojure ")||ye(e.relativePath)==="clojure"))}function _A(e){let t=new Set,n=[];for(let i of e){let r=`${i.symbol}|${i.fromFile}`;t.has(r)||(t.add(r),n.push(i))}return n.sort((i,r)=>i.fromFile.localeCompare(r.fromFile)||i.shortName.localeCompare(r.shortName))}function BA(e,t,n){return!e.sourcePath||n.targetFile&&ht(e.sourcePath)!==ht(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&zA(t)||e.kind==="namespace"&&OA(e,n.targetPattern)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function OA(e,t){let n=t.trim().replace(/\(\)$/,"");return vd(n)?e.importedName===n||e.localName===n:!1}function vd(e){let t=e.trim().replace(/\(\)$/,"");return t.includes(".")&&!t.includes("/")&&!t.includes(":")}function $A(e,t,n={}){let i=dt(e,t);return i?jA(e,i,n)??(n.semantic===!1?null:cv(e,i))??uv(e,i):null}function jA(e,t,n){let r=e.all(`SELECT DISTINCT
153
153
  gs.symbol,
154
154
  def_d.relative_path AS from_file,
155
155
  imp_d.relative_path AS importer,
@@ -175,7 +175,7 @@ import{c as tp,e as np,f as qt}from"./chunk-B2OB55RR.js";import{b as kt,c as ec}
175
175
  LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
176
176
  WHERE imp_d.relative_path = ?
177
177
  AND m.role = 2
178
- ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(r.length>0){let o=n.semantic===!1?[]:bo(e,t);return r.map(s=>({symbol:s.symbol,shortName:A(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 dv(e,t){let n=bo(e,t);return n.length>0?n.map(i=>{let r=fv(i.importedName,i.localName,i.kind);return{symbol:r,shortName:r,fromFile:i.sourcePath??"(external)",importer:t,used:i.kind==="side-effect"?!0:i.isUsed}}):null}function mv(e,t){let n=XA(t,se(e,t));return Ce(e,t).map(i=>{let r=fv(i.importedName,i.localName,i.kind),o=i.kind==="side-effect"||QA(t,i)||n.has(i.localName??i.importedName)?!0:i.used;return{symbol:r,shortName:r,fromFile:i.sourcePath??"(external)",importer:t,used:o}})}function XA(e,t){let n=new Set;if(ye(e)!=="python")return n;let i=/(?:^|\n)\s*__all__\s*(?:\+?=)\s*[[(]([\s\S]*?)[\])]/g;for(let r of t.matchAll(i)){let o=r[1]??"";for(let s of o.matchAll(/(['"])([A-Za-z_]\w*)\1/g))n.add(s[2])}return n}function QA(e,t){if(ye(e)!=="rust"||t.used||t.kind==="side-effect")return!1;let n=t.localName??t.importedName;return n==="_"||/^[A-Z]/.test(n)}function fv(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 ZA(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function e_(e,t){let n=pe(e,t);if(!n)return[];let r=new U(e).definitionsForFile(n.relativePath).filter(o=>o.symbol!==n.symbol).filter(o=>Pf(n.symbol,o.symbol)).sort((o,s)=>o.startLine-s.startLine||o.endLine-s.endLine).map(o=>({symbol:o.symbol,shortName:A(o.symbol),startLine:o.startLine,endLine:o.endLine,kind:Bt(o.symbol)??"unknown"}));return ye(n.relativePath)!=="clojure"?r:n_(r,t_(e,n))}function t_(e,t){let n=Y(t.symbol);if(!n)return[];let i=A(t.symbol);return(te(e,t.relativePath)?.clojureMembers??[]).filter(r=>r.ownerName===n).map(r=>({symbol:`${t.symbol}${r.memberName}().`,shortName:`${i}:${r.memberName}()`,startLine:r.startLine,endLine:r.endLine,kind:r.memberKind}))}function n_(e,t){let n=new Map;for(let i of[...e,...t])n.set(`${i.shortName}:${i.startLine}:${i.endLine}`,i);return[...n.values()].sort((i,r)=>i.startLine-r.startLine||i.endLine-r.endLine)}function i_(e,t){let n=pe(e,t);if(!n)return[];let i=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
178
+ ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(r.length>0){let o=n.semantic===!1?[]:ho(e,t);return r.map(s=>({symbol:s.symbol,shortName:A(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 cv(e,t){let n=ho(e,t);return n.length>0?n.map(i=>{let r=dv(i.importedName,i.localName,i.kind);return{symbol:r,shortName:r,fromFile:i.sourcePath??"(external)",importer:t,used:i.kind==="side-effect"?!0:i.isUsed}}):null}function uv(e,t){let n=HA(t,se(e,t));return Ce(e,t).map(i=>{let r=dv(i.importedName,i.localName,i.kind),o=i.kind==="side-effect"||UA(t,i)||n.has(i.localName??i.importedName)?!0:i.used;return{symbol:r,shortName:r,fromFile:i.sourcePath??"(external)",importer:t,used:o}})}function HA(e,t){let n=new Set;if(ye(e)!=="python")return n;let i=/(?:^|\n)\s*__all__\s*(?:\+?=)\s*[[(]([\s\S]*?)[\])]/g;for(let r of t.matchAll(i)){let o=r[1]??"";for(let s of o.matchAll(/(['"])([A-Za-z_]\w*)\1/g))n.add(s[2])}return n}function UA(e,t){if(ye(e)!=="rust"||t.used||t.kind==="side-effect")return!1;let n=t.localName??t.importedName;return n==="_"||/^[A-Z]/.test(n)}function dv(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 zA(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function qA(e,t){let n=pe(e,t);if(!n)return[];let r=new U(e).definitionsForFile(n.relativePath).filter(o=>o.symbol!==n.symbol).filter(o=>wf(n.symbol,o.symbol)).sort((o,s)=>o.startLine-s.startLine||o.endLine-s.endLine).map(o=>({symbol:o.symbol,shortName:A(o.symbol),startLine:o.startLine,endLine:o.endLine,kind:Bt(o.symbol)??"unknown"}));return ye(n.relativePath)!=="clojure"?r:GA(r,KA(e,n))}function KA(e,t){let n=Y(t.symbol);if(!n)return[];let i=A(t.symbol);return(te(e,t.relativePath)?.clojureMembers??[]).filter(r=>r.ownerName===n).map(r=>({symbol:`${t.symbol}${r.memberName}().`,shortName:`${i}:${r.memberName}()`,startLine:r.startLine,endLine:r.endLine,kind:r.memberKind}))}function GA(e,t){let n=new Map;for(let i of[...e,...t])n.set(`${i.shortName}:${i.startLine}:${i.endLine}`,i);return[...n.values()].sort((i,r)=>i.startLine-r.startLine||i.endLine-r.endLine)}function WA(e,t){let n=pe(e,t);if(!n)return[];let i=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
179
179
  FROM mentions m
180
180
  JOIN chunks c ON m.chunk_id = c.id
181
181
  JOIN (
@@ -187,7 +187,7 @@ import{c as tp,e as np,f as qt}from"./chunk-B2OB55RR.js";import{b as kt,c as ec}
187
187
  ) sym_def ON sym_def.symbol_id = m.symbol_id
188
188
  WHERE m.symbol_id = ?
189
189
  AND m.role != 1
190
- AND sym_def.document_id != c.document_id`,n.symbolId);return[{name:A(n.symbol),count:i?.file_count??0,symbol:n.symbol,definedIn:n.relativePath}]}function r_(e,t){let n=dt(e,t);return n?e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
190
+ AND sym_def.document_id != c.document_id`,n.symbolId);return[{name:A(n.symbol),count:i?.file_count??0,symbol:n.symbol,definedIn:n.relativePath}]}function VA(e,t){let n=dt(e,t);return n?e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
191
191
  FROM mentions m
192
192
  JOIN chunks c ON m.chunk_id = c.id
193
193
  JOIN documents d ON c.document_id = d.id
@@ -204,7 +204,7 @@ import{c as tp,e as np,f as qt}from"./chunk-B2OB55RR.js";import{b as kt,c as ec}
204
204
  AND m.role != 1
205
205
  AND def_d.id != d.id
206
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 o_(e,t={}){return s_(e,t).map(n=>({name:A(n.symbol),count:n.file_count,symbol:n.symbol,definedIn:n.defined_in}))}function s_(e,t){let{limit:n=30,scope:i}=t,r=i?"AND def_d.relative_path LIKE ?":"",o=i?[`%${i}%`]:[];return e.all(`SELECT gs.symbol,
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 JA(e,t={}){return YA(e,t).map(n=>({name:A(n.symbol),count:n.file_count,symbol:n.symbol,definedIn:n.defined_in}))}function YA(e,t){let{limit:n=30,scope:i}=t,r=i?"AND def_d.relative_path LIKE ?":"",o=i?[`%${i}%`]:[];return e.all(`SELECT gs.symbol,
208
208
  COUNT(DISTINCT c.document_id) AS file_count,
209
209
  def_d.relative_path AS defined_in
210
210
  FROM mentions m
@@ -226,7 +226,7 @@ import{c as tp,e as np,f as qt}from"./chunk-B2OB55RR.js";import{b as kt,c as ec}
226
226
  GROUP BY gs.id
227
227
  HAVING file_count > 1
228
228
  ORDER BY file_count DESC
229
- LIMIT ?`,...o,n)}function a_(e,t={}){let{limit:n=30,scope:i}=t,r=i?"AND d.relative_path LIKE ?":"",o=i?[`%${i}%`]:[];return e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
229
+ LIMIT ?`,...o,n)}function XA(e,t={}){let{limit:n=30,scope:i}=t,r=i?"AND d.relative_path LIKE ?":"",o=i?[`%${i}%`]:[];return e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
230
230
  FROM mentions m
231
231
  JOIN chunks c ON m.chunk_id = c.id
232
232
  JOIN documents d ON c.document_id = d.id
@@ -246,7 +246,7 @@ import{c as tp,e as np,f as qt}from"./chunk-B2OB55RR.js";import{b as kt,c as ec}
246
246
  ${r}
247
247
  GROUP BY d.id
248
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 pv=`SELECT COUNT(*) AS shared
249
+ LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}))}var mv=`SELECT COUNT(*) AS shared
250
250
  FROM (
251
251
  SELECT definition_m.symbol_id
252
252
  FROM documents definition_d
@@ -271,7 +271,7 @@ import{c as tp,e as np,f as qt}from"./chunk-B2OB55RR.js";import{b as kt,c as ec}
271
271
  JOIN documents reference_d ON reference_d.id = reference_c.document_id
272
272
  WHERE definition_d.relative_path = ?
273
273
  AND reference_d.relative_path = ?
274
- )`;function l_(e,t,n){let i=dt(e,t)??t,r=dt(e,n)??n,o=e.get(pv,i,r,r,i);return{...gv(i,r,o?.shared??0)}}function c_(e,t={}){let{limit:n=20,scope:i}=t,r=i?"AND def_d.relative_path LIKE ? AND ref_d.relative_path LIKE ?":"",o=i?[`%${i}%`,`%${i}%`]:[];return e.all(`SELECT
274
+ )`;function QA(e,t,n){let i=dt(e,t)??t,r=dt(e,n)??n,o=e.get(mv,i,r,r,i);return{...fv(i,r,o?.shared??0)}}function ZA(e,t={}){let{limit:n=20,scope:i}=t,r=i?"AND def_d.relative_path LIKE ? AND ref_d.relative_path LIKE ?":"",o=i?[`%${i}%`,`%${i}%`]:[];return e.all(`SELECT
275
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
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
277
  COUNT(DISTINCT gs.id) AS shared
@@ -293,7 +293,7 @@ import{c as tp,e as np,f as qt}from"./chunk-B2OB55RR.js";import{b as kt,c as ec}
293
293
  ${r}
294
294
  GROUP BY file1, file2
295
295
  ORDER BY shared DESC, file1, file2
296
- LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.file1)&&!e.isIgnored(a.file2)).map(a=>gv(a.file1,a.file2,a.shared))}function gv(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 Hi(e){let t=new Map,n=[],i=new Map,r=new Map,o=new Set,s=[],a=0,l=c=>(e.get(c)??[]).values();for(let c of e.keys()){if(i.has(c))continue;let u=[];for(i.set(c,a),r.set(c,a),a+=1,s.push(c),o.add(c),u.push({node:c,iter:l(c),pendingChild:null});u.length>0;){let d=u[u.length-1];if(d.pendingChild!==null){let p=d.pendingChild;d.pendingChild=null,r.set(d.node,Math.min(r.get(d.node),r.get(p)))}let m=d.iter.next();if(m.done){if(r.get(d.node)===i.get(d.node)){let p=[];for(;;){let g=s.pop();if(o.delete(g),p.push(g),t.set(g,n.length),g===d.node)break}n.push(p)}u.pop();continue}let f=m.value;i.has(f)?o.has(f)&&r.set(d.node,Math.min(r.get(d.node),i.get(f))):(i.set(f,a),r.set(f,a),a+=1,s.push(f),o.add(f),d.pendingChild=f,u.push({node:f,iter:l(f),pendingChild:null}))}}return{components:n,componentOf:t}}function qo(e,t={}){return bv(e,t).cycles}function bv(e,t={}){return Sv(e,t)}function Sv(e,t={}){let{scope:n,maxDepth:i=10,edgeBasis:r="symbol-references"}=t,o=$e(e,n,r==="imports"?{scipEdges:"imports-only",sourceEdges:"imports-only"}:void 0),{components:s}=Hi(o),a=s.filter(l=>u_(o,l)).map(l=>{let c=[...l].sort(),u=d_(o,c),d=f_(u);return{path:u,component:c,edgeBasis:r,witness:!0,classification:d==="real"?"dependency-cycle":"module-structure-candidate",kind:d}});return a.sort((l,c)=>l.kind!==c.kind?l.kind==="real"?-1:1:l.path.length-c.path.length),{cycles:a,truncated:!1,edgeBasis:r,maxDepth:i}}function u_(e,t){if(t.length>1)return!0;let n=t[0];return n!==void 0&&e.get(n)?.has(n)===!0}function d_(e,t){let n=t[0];if(!n)return[];let i=new Set(t);for(let r of[...e.get(n)??[]].filter(o=>i.has(o)).sort()){if(r===n)return[n,n];let o=m_(e,r,n,i);if(o)return[n,...o]}throw new Error(`Cyclic component did not contain a witness path from ${n}.`)}function m_(e,t,n,i){let r=[t],o=new Map([[t,null]]);for(let s=0;s<r.length;s+=1){let a=r[s];if(a===n){let l=[];for(let c=a;c!==null;c=o.get(c)??null)l.push(c);return l.reverse()}for(let l of[...e.get(a)??[]].filter(c=>i.has(c)).sort())o.has(l)||(o.set(l,a),r.push(l))}return null}function f_(e){for(let i of e){let r=J(i);if(r==="test"||r==="barrel"||r==="entry")return"module-hierarchy"}if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":fr(t)||fr(n)||hv(t,n)||hv(n,t)||yv(t,n)||yv(n,t)||J(t)==="entry"||J(n)==="entry"?"module-hierarchy":"real"}function hv(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=t.replace(/\.rs$/,"/");return e.startsWith(n)?!e.slice(n.length).includes("/"):!1}function yv(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=e.replace(/\.rs$/,""),i=t.replace(/\.rs$/,"");if(n===i+"_tests"||n===i+"/tests")return!0;let r=e.split("/"),o=t.split("/");if(r.length===o.length&&r.includes("tests")&&o.includes("src")){let s=r[r.length-1],a=o[o.length-1];if(s&&s===a)return!0}return!1}import{readdirSync as p_}from"fs";import{join as xv}from"path";function Cv(e,t){let n=vv(e),i=vv(t);if(n.endsWith("/**")){let r=n.slice(0,-3);return i===r||i.startsWith(`${r}/`)}if(n.endsWith("/*")){let r=n.slice(0,-2);if(!i.startsWith(`${r}/`))return!1;let o=i.slice(r.length+1);return o.length>0&&!o.includes("/")}return n==="**"?!0:n==="*"?i.length>0&&!i.includes("/"):n===i}function vv(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}function si(e,t){return Cv(e,t)}function g_(e){return Rv(e).replace(/\/\*\*?$/,"")}function ll(e,t){let n=Rv(t),i=g_(n),r=n.endsWith("/**"),o=[],s=(a,l)=>{let c;try{c=p_(a,{withFileTypes:!0})}catch{return}for(let u of c){if(u.name.startsWith("."))continue;let d=l?`${l}/${u.name}`:u.name;si(n,d)&&o.push(d),r&&u.isDirectory()&&s(xv(a,u.name),d)}};return s(xv(e,i),i),o.sort()}function Rv(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}var h_=/\.(test|spec)\.(ts|tsx|js|jsx|mts|cts)$/,Iv=new Map;function Ev(e,t,n,i){if(!t?.testPaths?.length)return[];let r=y_(t),o=[];for(let s of b_(e,t.testPaths)){let a=S_(e,s,i),l=a?n(a):null;if(l)for(let c of Ce(e,s)){let u=c.sourcePath;if(!u)continue;let d=n(u);d&&d!==l&&(r.get(l)?.has(d)||o.push({testFile:s,ownerBoundary:l,importedFile:u,importedBoundary:d,reason:"outside-owner-policy"}))}}return v_(o)}function y_(e){let t=e.allowedDependencies??{},n=e.boundaries.map(s=>s.name),i=new Map,r=(s,a)=>{for(let l of t[s]??[])a.has(l)||(a.add(l),r(l,a))};for(let s of n){let a=new Set;r(s,a),i.set(s,a)}let o=new Map;for(let s of n){let a=new Set(i.get(s));for(let l of n)l!==s&&i.get(l)?.has(s)&&a.add(l);o.set(s,a)}return o}function b_(e,t){let n=`${e.config.projectRoot}\0${t.join("\0")}`,i=Iv.get(n);if(i)return i;let r=new Set;for(let s of t)for(let a of ll(e.config.projectRoot,s))h_.test(a)&&r.add(a);let o=[...r].sort();return Iv.set(n,o),o}function S_(e,t,n){let i=t.replace(/^tests\//,"src/").replace(/\.(test|spec)\.(\w+)$/,".$2");if(i!==t&&n(i))return i;let r=t.split("/").pop().replace(/\.(test|spec)\.(\w+)$/,".$2"),o=Ce(e,t).map(s=>s.sourcePath).filter(s=>!!s&&n(s)&&s.split("/").pop()===r);return o.length===1?o[0]:null}function v_(e){let t=new Map;for(let n of e){let i=`${n.testFile}\0${n.importedBoundary}`;t.has(i)||t.set(i,n)}return[...t.values()].sort((n,i)=>n.testFile.localeCompare(i.testFile)||n.importedBoundary.localeCompare(i.importedBoundary))}function wv(e,t){let n=(e?.boundaries??[]).filter(i=>i.paths.some(r=>si(r,t)));return n.length===1?n[0].name:null}var _n="architecture:";function Lv(e,t,n,i={}){let r=x_(e,t);if(!n||n.boundaries.length===0)return{configured:!1,boundaries:[],edges:[],forbiddenEdges:[],reciprocalPairs:[],cycles:[],coarseBoundaries:[],staleAllowances:[],boundaryLimits:[],fragileEdges:[],testBoundaryViolations:[],coverage:{totalFiles:r.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=[],l=[];for(let y of r){let I=n.boundaries.filter(E=>E.paths.some(S=>si(S,y))).map(E=>E.name).sort();if(I.length===0)a.push(y);else if(I.length>1)l.push({file:y,boundaries:I});else{let E=I[0];o.set(y,E),s.get(E).add(y)}}let c=new Map;for(let[y,I]of e){let E=o.get(y);if(E)for(let S of I){let x=o.get(S);if(!x||E===x)continue;let C=wr(E,x),L=c.get(C);L||(L={from:E,to:x,fileEdges:[],importers:new Set,importedFiles:new Set},c.set(C,L)),L.fileEdges.push({fromFile:y,toFile:S}),L.importers.add(y),L.importedFiles.add(S)}}let u=[...c.values()].map(y=>R_(y,n)).sort(T_),d=u,m=new Map(d.map(y=>[wr(y.from,y.to),y])),f=new Map(n.boundaries.map(y=>[y.name,new Set]));for(let y of d)f.get(y.from).add(y.to);let p=[];for(let y of d){if(y.from>=y.to)continue;let I=m.get(wr(y.to,y.from));I&&p.push({boundaries:[y.from,y.to],forward:y,reverse:I})}let{components:g}=Hi(f),h=g.filter(y=>y.length>1).map(y=>E_(y,d,n.requireAcyclic===!0)).sort((y,I)=>I.boundaries.length-y.boundaries.length||y.boundaries.join("/").localeCompare(I.boundaries.join("/"))),b=n.allowedDependencies??{},v=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,I)=>y.name.localeCompare(I.name)),edges:u,forbiddenEdges:d.filter(y=>y.policyStatus==="forbidden"),reciprocalPairs:p,cycles:h,staleAllowances:L_(n,d),boundaryLimits:D_(n,d,s),fragileEdges:d.filter(y=>y.fragile),testBoundaryViolations:i.testBoundaryViolations??[],coarseBoundaries:w_(e,s,i.isModuleHierarchyFile,n.requireResolvedBoundaries===!0,y=>n.boundaries.find(I=>I.name===y)?.subUnits??"directory"),coverage:{totalFiles:r.length,mappedFiles:o.size,unmappedFiles:a,ambiguousFiles:l},policyCoverage:{declaredRows:n.boundaries.length-v.length,totalBoundaries:n.boundaries.length,missingRows:v,requiresCompletePolicy:n.requireCompletePolicy===!0,requiresCompleteCoverage:n.requireCompleteCoverage===!0,requiresMinimalPolicy:n.requireMinimalPolicy===!0}}}function Ko(e,t={}){let n=$e(e,t.scope,{scipEdges:"imports-only",sourceEdges:"imports-and-reexports"}),i=me(e,{includeIgnored:!1}).filter(o=>!t.scope||o.includes(t.scope)),r=new Set(i);return Lv(n,i,e.config.architecture,{isModuleHierarchyFile:o=>C_(e,o),testBoundaryViolations:Ev(e,e.config.architecture,o=>wv(e.config.architecture,o),o=>r.has(o))})}function C_(e,t){let n=J(t);return n==="test"||n==="entry"?!0:n!=="barrel"?!1:W(e,t).length===0}function Ed(e){let t=e.forbiddenEdges.map(i=>`${_n}forbidden-edge:${encodeURIComponent(i.from)}:${encodeURIComponent(i.to)}`);if(e.policyCoverage.requiresCompletePolicy)for(let i of e.policyCoverage.missingRows)t.push(`${_n}missing-policy-row:${encodeURIComponent(i)}`);if(e.policyCoverage.requiresCompleteCoverage){for(let i of e.coverage.unmappedFiles)t.push(`${_n}unmapped-file:${encodeURIComponent(i)}`);for(let i of e.coverage.ambiguousFiles)t.push(`${_n}ambiguous-file:${encodeURIComponent(i.file)}:${i.boundaries.map(r=>encodeURIComponent(r)).sort().join("|")}`)}if(e.policyCoverage.requiresMinimalPolicy)for(let i of e.staleAllowances)t.push(`${_n}stale-allowance:${encodeURIComponent(i.from)}:${encodeURIComponent(i.to)}`);for(let i of e.testBoundaryViolations)t.push(`${_n}test-boundary:${encodeURIComponent(i.testFile)}:${encodeURIComponent(i.importedBoundary)}`);for(let i of e.boundaryLimits)t.push(`${_n}boundary-limit:${i.kind}:${encodeURIComponent(i.boundary)}`);let n=new Map;for(let i of e.coarseBoundaries)i.violatesPolicy&&n.set(i.boundary,(n.get(i.boundary)??0)+1);for(let[i,r]of n){let o=`${_n}coarse-boundary:${encodeURIComponent(i)}`;t.push(o);for(let s=2;s<=r;s+=1)t.push(`${o}:component:${s}`)}for(let i of e.cycles)i.violatesPolicy&&t.push(`${_n}cycle:${i.boundaries.map(r=>encodeURIComponent(r)).sort().join("|")}`);return[...new Set(t)].sort()}function x_(e,t){let n=new Set(t);for(let[i,r]of e){n.add(i);for(let o of r)n.add(o)}return[...n].sort()}function R_(e,t){let n=[...e.fileEdges].sort((i,r)=>i.fromFile.localeCompare(r.fromFile)||i.toFile.localeCompare(r.toFile));return{from:e.from,to:e.to,policyStatus:I_(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 I_(e,t,n){return!e.allowedDependencies||!Object.hasOwn(e.allowedDependencies,t)?"undeclared":e.allowedDependencies[t].includes(n)?"allowed":"forbidden"}function E_(e,t,n){let i=[...e].sort(),r=new Set(i),o=t.filter(a=>r.has(a.from)&&r.has(a.to)),s=Math.min(...o.map(a=>a.fileEdgeCount));return{boundaries:i,internalEdges:o,narrowestEdges:o.filter(a=>a.fileEdgeCount===s),violatesPolicy:n}}function w_(e,t,n=M_,i=!1,r=()=>"directory"){let o=[];for(let[s,a]of t){let l=r(s)==="file"?p=>p:P_,c=[...a].filter(p=>!n(p));if(c.length<2)continue;let u=new Set(c),d=new Map,m=new Map;for(let p of c)m.set(l(p),new Set);for(let p of c)for(let g of e.get(p)??[]){if(!u.has(g))continue;let h=l(p),b=l(g);if(h===b)continue;let v=wr(h,b),y=d.get(v);y||(y={from:h,to:b,fileEdges:[]},d.set(v,y)),y.fileEdges.push({fromFile:p,toFile:g}),m.get(h).add(b)}let{components:f}=Hi(m);for(let p of f){if(p.length<2)continue;let g=new Set(p),h=[...d.values()].filter(v=>g.has(v.from)&&g.has(v.to)).map(v=>({from:v.from,to:v.to,fileEdgeCount:v.fileEdges.length,examples:v.fileEdges.slice(0,5)})).sort((v,y)=>v.from.localeCompare(y.from)||v.to.localeCompare(y.to)),b=Math.min(...h.map(v=>v.fileEdgeCount));o.push({boundary:s,violatesPolicy:i,subUnits:[...p].sort(),internalEdges:h,narrowestEdges:h.filter(v=>v.fileEdgeCount===b)})}}return o.sort((s,a)=>a.subUnits.length-s.subUnits.length||s.boundary.localeCompare(a.boundary))}function L_(e,t){let n=new Set(t.map(s=>wr(s.from,s.to))),i=e.allowedDependencies??{},r=new Set(e.boundaries.map(s=>s.name)),o=[];for(let[s,a]of Object.entries(i))if(r.has(s))for(let l of a)!r.has(l)||n.has(wr(s,l))||o.push({from:s,to:l});return o.sort((s,a)=>s.from.localeCompare(a.from)||s.to.localeCompare(a.to))}function D_(e,t,n){let i=[],r=new Map;for(let o of t)r.set(o.from,(r.get(o.from)??0)+1);for(let o of e.boundaries){if(e.maxBoundaryFanOut!==void 0){let a=r.get(o.name)??0;a>e.maxBoundaryFanOut&&i.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&&i.push({boundary:o.name,kind:"files",observed:a,limit:s})}}return i.sort((o,s)=>o.boundary.localeCompare(s.boundary)||o.kind.localeCompare(s.kind))}function M_(e){let t=J(e);return t==="test"||t==="entry"}function P_(e){let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)}function wr(e,t){return`${e}\0${t}`}function T_(e,t){return e.from.localeCompare(t.from)||e.to.localeCompare(t.to)}function F_(e,t={}){let{limit:n=20,scope:i,minFanIn:r=2,minFanOut:o=2,scanLimit:s}=t,a=new U(e),l=ke(a.productionCallableDefinitions({scope:i,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s),c=t.semantic!==!1,u=sn(e,l,{limit:500,semantic:c,semanticEvidence:ge}),d=a.calleeEvidenceMap(l,{semantic:c}),m=new Set([...u.incompleteSymbolIds,...d.incompleteSymbolIds]),f=new Set([...u.unavailableSymbolIds,...d.unavailableSymbolIds]);return{rows:l.filter(g=>!m.has(g.symbolId)&&!f.has(g.symbolId)).map(g=>N_(g,u.rows.get(g.symbolId)??[],d.rows.get(g.symbolId)??[])).filter(g=>g.fanIn>=r&&g.fanOut>=o).sort((g,h)=>h.score-g.score||h.fanIn-g.fanIn).slice(0,n),coverage:k_(c,m,f)}}function k_(e,t,n){let i=e?t.size>0&&n.size>0?"incomplete-and-unavailable":t.size>0?"incomplete":n.size>0?"unavailable":"complete":"disabled";return{semanticEvidence:{enabled:e,status:i,incompleteSymbolCount:t.size,unavailableSymbolCount:n.size,excludedSymbolCount:new Set([...t,...n]).size}}}function N_(e,t,n){let i=[...new Set(t.map(d=>d.file))].sort(),r=[...new Set(t.filter(d=>d.source!=="caller-map-inversion"||d.callEvidence==="scip-chunk").map(d=>d.file))].sort(),o=new Map;for(let d of n.slice(0,500)){if(d.file===e.relativePath)continue;let m=`${d.symbol}|${d.file}`;o.has(m)||o.set(m,{symbol:d.symbol,shortName:A(d.symbol),file:d.file,evidenceStrength:d.source==="scip-chunk"?"candidate":"exact",evidenceSource:d.source})}let s=[...o.values()].sort((d,m)=>d.file.localeCompare(m.file)||d.symbol.localeCompare(m.symbol)),a=i.length,l=s.length,c=a*l,u=s.filter(d=>d.evidenceStrength==="candidate").map(d=>d.symbol);return{symbol:e.symbol,shortName:A(e.symbol),fanIn:a,fanOut:l,callerFiles:i,candidateCallerFiles:r,externalCallees:s.map(({symbol:d,shortName:m,file:f})=>({symbol:d,shortName:m,file:f})),externalCalleeEvidence:s,candidateExternalCallees:u,inputBasis:"mixed-static-call-or-reference-evidence",score:c,definedIn:e.relativePath,actionTier:"signal",riskKind:"coordination-hotspot",evidenceReasons:[`${a} incoming file(s) reference this symbol`,`${l} distinct cross-file callee symbol(s) are reached from it`,`centrality score is ${c} (fan-in * fan-out)`,`${r.length} incoming file(s) and ${u.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 Go(e,t={}){let{scope:n,minLoc:i=3,scanLimit:r}=t,o=new U(e),s=t.semantic!==!1,a=0,l=B("isolated.candidates",()=>{let S=ke(o.productionCallableDefinitions({scope:n,minLoc:i,excludeEntrySurfaces:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:typeof r=="number"&&r>0}),r).filter(x=>!Er(e,x));return a=S.length,S},()=>({definitions:a})),c=0,u=B("isolated.strict-callees",()=>{let E=o.symbolsWithNonSelfCallees(l,{additive:!1,semantic:!1});return c=E.size,E},()=>({definitions:l.length,symbols:c})),d=l.filter(E=>!u.has(E.symbolId)),m=0,f=B("isolated.scip-callers",()=>{let E=o.crossFileCallerMap(d,{semantic:!1});return m=E.size,E},()=>({definitions:d.length,symbols:m})),p=new Set(f.keys());for(let E of o.frameworkReferencedSymbolIds(d))p.add(E);let g=d.filter(E=>!p.has(E.symbolId));if(s&&g.length>0){let E=Ln(e,g);for(let S of E.callers.keys())p.add(S);for(let S of E.incompleteSymbolIds)p.add(S);for(let S of E.unavailableSymbolIds)p.add(S);for(let S of o.symbolsWithNonSelfCallees(g,{additive:!1,semantic:!0}))u.add(S);g=g.filter(S=>!p.has(S.symbolId)).filter(S=>!u.has(S.symbolId))}let h=0,b=B("isolated.source-fallback-callers",()=>{let E=o.sourceFallbackCallerFiles(g,{skipPath:S=>J(S)==="test"});return h=E.size,E},()=>({definitions:g.length,symbols:h}));for(let E of b.keys())p.add(E);let v=g.filter(E=>!p.has(E.symbolId)),y=0,I=B("isolated.additive-callees",()=>{let E=o.symbolsWithNonSelfCallees(v,{additive:!0,semantic:s});return y=E.size,E},()=>({definitions:v.length,symbols:y}));for(let E of I)u.add(E);return v.filter(E=>!u.has(E.symbolId)).sort((E,S)=>de(S)-de(E)||E.relativePath.localeCompare(S.relativePath)||E.startLine-S.startLine).map(E=>({symbol:E.symbol,shortName:A(E.symbol),relativePath:E.relativePath,startLine:E.startLine,endLine:E.endLine,loc:de(E)}))}import{SymbolInformation_Kind as tt}from"@c4312/scip";var Dv=500;function A_(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),i=ap.get(n);if(i!==void 0)return i;for(let[r,o]of Us)if(o.toLowerCase().includes(n))return r;return null}function __(e,t,n={}){let{scope:i,limit:r=100}=n,o=A_(t);return o===null?[]:O_(e,i).map(a=>({row:a,resolvedKind:Pv(a)})).filter(a=>a.resolvedKind===o).slice(0,r).map(({row:a,resolvedKind:l})=>({symbol:a.symbol,shortName:A(a.symbol),kind:l,kindName:Gr(l),relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function B_(e,t={}){let n=$_(e,t.scope);for(let i of j_(e,t.scope)){let r=Pv(i);r===null||r===0||n.set(r,(n.get(r)??0)+1)}return[...n.entries()].sort((i,r)=>r[1]-i[1]||i[0]-r[0]).map(([i,r])=>({kind:i,kindName:Gr(i),count:r}))}function O_(e,t){return Ue(e,{scope:t}).map(H_)}function $_(e,t){let n=new Map;for(let i of Mv(me(e,{scope:t,includeIgnored:!1}))){let r=i.map(()=>"?").join(", "),o=e.all(`SELECT gs.kind AS kind, COUNT(*) AS count
296
+ LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.file1)&&!e.isIgnored(a.file2)).map(a=>fv(a.file1,a.file2,a.shared))}function fv(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 Hi(e){let t=new Map,n=[],i=new Map,r=new Map,o=new Set,s=[],a=0,l=c=>(e.get(c)??[]).values();for(let c of e.keys()){if(i.has(c))continue;let u=[];for(i.set(c,a),r.set(c,a),a+=1,s.push(c),o.add(c),u.push({node:c,iter:l(c),pendingChild:null});u.length>0;){let d=u[u.length-1];if(d.pendingChild!==null){let p=d.pendingChild;d.pendingChild=null,r.set(d.node,Math.min(r.get(d.node),r.get(p)))}let m=d.iter.next();if(m.done){if(r.get(d.node)===i.get(d.node)){let p=[];for(;;){let g=s.pop();if(o.delete(g),p.push(g),t.set(g,n.length),g===d.node)break}n.push(p)}u.pop();continue}let f=m.value;i.has(f)?o.has(f)&&r.set(d.node,Math.min(r.get(d.node),i.get(f))):(i.set(f,a),r.set(f,a),a+=1,s.push(f),o.add(f),d.pendingChild=f,u.push({node:f,iter:l(f),pendingChild:null}))}}return{components:n,componentOf:t}}function Uo(e,t={}){return hv(e,t).cycles}function hv(e,t={}){return yv(e,t)}function yv(e,t={}){let{scope:n,maxDepth:i=10,edgeBasis:r="symbol-references"}=t,o=$e(e,n,r==="imports"?{scipEdges:"imports-only",sourceEdges:"imports-only"}:void 0),{components:s}=Hi(o),a=s.filter(l=>e_(o,l)).map(l=>{let c=[...l].sort(),u=t_(o,c),d=i_(u);return{path:u,component:c,edgeBasis:r,witness:!0,classification:d==="real"?"dependency-cycle":"module-structure-candidate",kind:d}});return a.sort((l,c)=>l.kind!==c.kind?l.kind==="real"?-1:1:l.path.length-c.path.length),{cycles:a,truncated:!1,edgeBasis:r,maxDepth:i}}function e_(e,t){if(t.length>1)return!0;let n=t[0];return n!==void 0&&e.get(n)?.has(n)===!0}function t_(e,t){let n=t[0];if(!n)return[];let i=new Set(t);for(let r of[...e.get(n)??[]].filter(o=>i.has(o)).sort()){if(r===n)return[n,n];let o=n_(e,r,n,i);if(o)return[n,...o]}throw new Error(`Cyclic component did not contain a witness path from ${n}.`)}function n_(e,t,n,i){let r=[t],o=new Map([[t,null]]);for(let s=0;s<r.length;s+=1){let a=r[s];if(a===n){let l=[];for(let c=a;c!==null;c=o.get(c)??null)l.push(c);return l.reverse()}for(let l of[...e.get(a)??[]].filter(c=>i.has(c)).sort())o.has(l)||(o.set(l,a),r.push(l))}return null}function i_(e){for(let i of e){let r=J(i);if(r==="test"||r==="barrel"||r==="entry")return"module-hierarchy"}if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":dr(t)||dr(n)||pv(t,n)||pv(n,t)||gv(t,n)||gv(n,t)||J(t)==="entry"||J(n)==="entry"?"module-hierarchy":"real"}function pv(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=t.replace(/\.rs$/,"/");return e.startsWith(n)?!e.slice(n.length).includes("/"):!1}function gv(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=e.replace(/\.rs$/,""),i=t.replace(/\.rs$/,"");if(n===i+"_tests"||n===i+"/tests")return!0;let r=e.split("/"),o=t.split("/");if(r.length===o.length&&r.includes("tests")&&o.includes("src")){let s=r[r.length-1],a=o[o.length-1];if(s&&s===a)return!0}return!1}import{readdirSync as r_}from"fs";import{join as vv}from"path";function Sv(e,t){let n=bv(e),i=bv(t);if(n.endsWith("/**")){let r=n.slice(0,-3);return i===r||i.startsWith(`${r}/`)}if(n.endsWith("/*")){let r=n.slice(0,-2);if(!i.startsWith(`${r}/`))return!1;let o=i.slice(r.length+1);return o.length>0&&!o.includes("/")}return n==="**"?!0:n==="*"?i.length>0&&!i.includes("/"):n===i}function bv(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}function si(e,t){return Sv(e,t)}function o_(e){return Cv(e).replace(/\/\*\*?$/,"")}function al(e,t){let n=Cv(t),i=o_(n),r=n.endsWith("/**"),o=[],s=(a,l)=>{let c;try{c=r_(a,{withFileTypes:!0})}catch{return}for(let u of c){if(u.name.startsWith("."))continue;let d=l?`${l}/${u.name}`:u.name;si(n,d)&&o.push(d),r&&u.isDirectory()&&s(vv(a,u.name),d)}};return s(vv(e,i),i),o.sort()}function Cv(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}var s_=/\.(test|spec)\.(ts|tsx|js|jsx|mts|cts)$/,xv=new Map;function Rv(e,t,n,i){if(!t?.testPaths?.length)return[];let r=a_(t),o=[];for(let s of l_(e,t.testPaths)){let a=c_(e,s,i),l=a?n(a):null;if(l)for(let c of Ce(e,s)){let u=c.sourcePath;if(!u)continue;let d=n(u);d&&d!==l&&(r.get(l)?.has(d)||o.push({testFile:s,ownerBoundary:l,importedFile:u,importedBoundary:d,reason:"outside-owner-policy"}))}}return u_(o)}function a_(e){let t=e.allowedDependencies??{},n=e.boundaries.map(s=>s.name),i=new Map,r=(s,a)=>{for(let l of t[s]??[])a.has(l)||(a.add(l),r(l,a))};for(let s of n){let a=new Set;r(s,a),i.set(s,a)}let o=new Map;for(let s of n){let a=new Set(i.get(s));for(let l of n)l!==s&&i.get(l)?.has(s)&&a.add(l);o.set(s,a)}return o}function l_(e,t){let n=`${e.config.projectRoot}\0${t.join("\0")}`,i=xv.get(n);if(i)return i;let r=new Set;for(let s of t)for(let a of al(e.config.projectRoot,s))s_.test(a)&&r.add(a);let o=[...r].sort();return xv.set(n,o),o}function c_(e,t,n){let i=t.replace(/^tests\//,"src/").replace(/\.(test|spec)\.(\w+)$/,".$2");if(i!==t&&n(i))return i;let r=t.split("/").pop().replace(/\.(test|spec)\.(\w+)$/,".$2"),o=Ce(e,t).map(s=>s.sourcePath).filter(s=>!!s&&n(s)&&s.split("/").pop()===r);return o.length===1?o[0]:null}function u_(e){let t=new Map;for(let n of e){let i=`${n.testFile}\0${n.importedBoundary}`;t.has(i)||t.set(i,n)}return[...t.values()].sort((n,i)=>n.testFile.localeCompare(i.testFile)||n.importedBoundary.localeCompare(i.importedBoundary))}function Iv(e,t){let n=(e?.boundaries??[]).filter(i=>i.paths.some(r=>si(r,t)));return n.length===1?n[0].name:null}var _n="architecture:";function Ev(e,t,n,i={}){let r=m_(e,t);if(!n||n.boundaries.length===0)return{configured:!1,boundaries:[],edges:[],forbiddenEdges:[],reciprocalPairs:[],cycles:[],coarseBoundaries:[],staleAllowances:[],boundaryLimits:[],fragileEdges:[],testBoundaryViolations:[],coverage:{totalFiles:r.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=[],l=[];for(let y of r){let I=n.boundaries.filter(E=>E.paths.some(S=>si(S,y))).map(E=>E.name).sort();if(I.length===0)a.push(y);else if(I.length>1)l.push({file:y,boundaries:I});else{let E=I[0];o.set(y,E),s.get(E).add(y)}}let c=new Map;for(let[y,I]of e){let E=o.get(y);if(E)for(let S of I){let x=o.get(S);if(!x||E===x)continue;let C=Ir(E,x),L=c.get(C);L||(L={from:E,to:x,fileEdges:[],importers:new Set,importedFiles:new Set},c.set(C,L)),L.fileEdges.push({fromFile:y,toFile:S}),L.importers.add(y),L.importedFiles.add(S)}}let u=[...c.values()].map(y=>f_(y,n)).sort(C_),d=u,m=new Map(d.map(y=>[Ir(y.from,y.to),y])),f=new Map(n.boundaries.map(y=>[y.name,new Set]));for(let y of d)f.get(y.from).add(y.to);let p=[];for(let y of d){if(y.from>=y.to)continue;let I=m.get(Ir(y.to,y.from));I&&p.push({boundaries:[y.from,y.to],forward:y,reverse:I})}let{components:g}=Hi(f),h=g.filter(y=>y.length>1).map(y=>g_(y,d,n.requireAcyclic===!0)).sort((y,I)=>I.boundaries.length-y.boundaries.length||y.boundaries.join("/").localeCompare(I.boundaries.join("/"))),b=n.allowedDependencies??{},v=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,I)=>y.name.localeCompare(I.name)),edges:u,forbiddenEdges:d.filter(y=>y.policyStatus==="forbidden"),reciprocalPairs:p,cycles:h,staleAllowances:y_(n,d),boundaryLimits:b_(n,d,s),fragileEdges:d.filter(y=>y.fragile),testBoundaryViolations:i.testBoundaryViolations??[],coarseBoundaries:h_(e,s,i.isModuleHierarchyFile,n.requireResolvedBoundaries===!0,y=>n.boundaries.find(I=>I.name===y)?.subUnits??"directory"),coverage:{totalFiles:r.length,mappedFiles:o.size,unmappedFiles:a,ambiguousFiles:l},policyCoverage:{declaredRows:n.boundaries.length-v.length,totalBoundaries:n.boundaries.length,missingRows:v,requiresCompletePolicy:n.requireCompletePolicy===!0,requiresCompleteCoverage:n.requireCompleteCoverage===!0,requiresMinimalPolicy:n.requireMinimalPolicy===!0}}}function zo(e,t={}){let n=$e(e,t.scope,{scipEdges:"imports-only",sourceEdges:"imports-and-reexports"}),i=me(e,{includeIgnored:!1}).filter(o=>!t.scope||o.includes(t.scope)),r=new Set(i);return Ev(n,i,e.config.architecture,{isModuleHierarchyFile:o=>d_(e,o),testBoundaryViolations:Rv(e,e.config.architecture,o=>Iv(e.config.architecture,o),o=>r.has(o))})}function d_(e,t){let n=J(t);return n==="test"||n==="entry"?!0:n!=="barrel"?!1:W(e,t).length===0}function Cd(e){let t=e.forbiddenEdges.map(i=>`${_n}forbidden-edge:${encodeURIComponent(i.from)}:${encodeURIComponent(i.to)}`);if(e.policyCoverage.requiresCompletePolicy)for(let i of e.policyCoverage.missingRows)t.push(`${_n}missing-policy-row:${encodeURIComponent(i)}`);if(e.policyCoverage.requiresCompleteCoverage){for(let i of e.coverage.unmappedFiles)t.push(`${_n}unmapped-file:${encodeURIComponent(i)}`);for(let i of e.coverage.ambiguousFiles)t.push(`${_n}ambiguous-file:${encodeURIComponent(i.file)}:${i.boundaries.map(r=>encodeURIComponent(r)).sort().join("|")}`)}if(e.policyCoverage.requiresMinimalPolicy)for(let i of e.staleAllowances)t.push(`${_n}stale-allowance:${encodeURIComponent(i.from)}:${encodeURIComponent(i.to)}`);for(let i of e.testBoundaryViolations)t.push(`${_n}test-boundary:${encodeURIComponent(i.testFile)}:${encodeURIComponent(i.importedBoundary)}`);for(let i of e.boundaryLimits)t.push(`${_n}boundary-limit:${i.kind}:${encodeURIComponent(i.boundary)}`);let n=new Map;for(let i of e.coarseBoundaries)i.violatesPolicy&&n.set(i.boundary,(n.get(i.boundary)??0)+1);for(let[i,r]of n){let o=`${_n}coarse-boundary:${encodeURIComponent(i)}`;t.push(o);for(let s=2;s<=r;s+=1)t.push(`${o}:component:${s}`)}for(let i of e.cycles)i.violatesPolicy&&t.push(`${_n}cycle:${i.boundaries.map(r=>encodeURIComponent(r)).sort().join("|")}`);return[...new Set(t)].sort()}function m_(e,t){let n=new Set(t);for(let[i,r]of e){n.add(i);for(let o of r)n.add(o)}return[...n].sort()}function f_(e,t){let n=[...e.fileEdges].sort((i,r)=>i.fromFile.localeCompare(r.fromFile)||i.toFile.localeCompare(r.toFile));return{from:e.from,to:e.to,policyStatus:p_(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 p_(e,t,n){return!e.allowedDependencies||!Object.hasOwn(e.allowedDependencies,t)?"undeclared":e.allowedDependencies[t].includes(n)?"allowed":"forbidden"}function g_(e,t,n){let i=[...e].sort(),r=new Set(i),o=t.filter(a=>r.has(a.from)&&r.has(a.to)),s=Math.min(...o.map(a=>a.fileEdgeCount));return{boundaries:i,internalEdges:o,narrowestEdges:o.filter(a=>a.fileEdgeCount===s),violatesPolicy:n}}function h_(e,t,n=S_,i=!1,r=()=>"directory"){let o=[];for(let[s,a]of t){let l=r(s)==="file"?p=>p:v_,c=[...a].filter(p=>!n(p));if(c.length<2)continue;let u=new Set(c),d=new Map,m=new Map;for(let p of c)m.set(l(p),new Set);for(let p of c)for(let g of e.get(p)??[]){if(!u.has(g))continue;let h=l(p),b=l(g);if(h===b)continue;let v=Ir(h,b),y=d.get(v);y||(y={from:h,to:b,fileEdges:[]},d.set(v,y)),y.fileEdges.push({fromFile:p,toFile:g}),m.get(h).add(b)}let{components:f}=Hi(m);for(let p of f){if(p.length<2)continue;let g=new Set(p),h=[...d.values()].filter(v=>g.has(v.from)&&g.has(v.to)).map(v=>({from:v.from,to:v.to,fileEdgeCount:v.fileEdges.length,examples:v.fileEdges.slice(0,5)})).sort((v,y)=>v.from.localeCompare(y.from)||v.to.localeCompare(y.to)),b=Math.min(...h.map(v=>v.fileEdgeCount));o.push({boundary:s,violatesPolicy:i,subUnits:[...p].sort(),internalEdges:h,narrowestEdges:h.filter(v=>v.fileEdgeCount===b)})}}return o.sort((s,a)=>a.subUnits.length-s.subUnits.length||s.boundary.localeCompare(a.boundary))}function y_(e,t){let n=new Set(t.map(s=>Ir(s.from,s.to))),i=e.allowedDependencies??{},r=new Set(e.boundaries.map(s=>s.name)),o=[];for(let[s,a]of Object.entries(i))if(r.has(s))for(let l of a)!r.has(l)||n.has(Ir(s,l))||o.push({from:s,to:l});return o.sort((s,a)=>s.from.localeCompare(a.from)||s.to.localeCompare(a.to))}function b_(e,t,n){let i=[],r=new Map;for(let o of t)r.set(o.from,(r.get(o.from)??0)+1);for(let o of e.boundaries){if(e.maxBoundaryFanOut!==void 0){let a=r.get(o.name)??0;a>e.maxBoundaryFanOut&&i.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&&i.push({boundary:o.name,kind:"files",observed:a,limit:s})}}return i.sort((o,s)=>o.boundary.localeCompare(s.boundary)||o.kind.localeCompare(s.kind))}function S_(e){let t=J(e);return t==="test"||t==="entry"}function v_(e){let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)}function Ir(e,t){return`${e}\0${t}`}function C_(e,t){return e.from.localeCompare(t.from)||e.to.localeCompare(t.to)}function x_(e,t={}){let{limit:n=20,scope:i,minFanIn:r=2,minFanOut:o=2,scanLimit:s}=t,a=new U(e),l=ke(a.productionCallableDefinitions({scope:i,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s),c=t.semantic!==!1,u=sn(e,l,{limit:500,semantic:c,semanticEvidence:ge}),d=a.calleeEvidenceMap(l,{semantic:c}),m=new Set([...u.incompleteSymbolIds,...d.incompleteSymbolIds]),f=new Set([...u.unavailableSymbolIds,...d.unavailableSymbolIds]);return{rows:l.filter(g=>!m.has(g.symbolId)&&!f.has(g.symbolId)).map(g=>I_(g,u.rows.get(g.symbolId)??[],d.rows.get(g.symbolId)??[])).filter(g=>g.fanIn>=r&&g.fanOut>=o).sort((g,h)=>h.score-g.score||h.fanIn-g.fanIn).slice(0,n),coverage:R_(c,m,f)}}function R_(e,t,n){let i=e?t.size>0&&n.size>0?"incomplete-and-unavailable":t.size>0?"incomplete":n.size>0?"unavailable":"complete":"disabled";return{semanticEvidence:{enabled:e,status:i,incompleteSymbolCount:t.size,unavailableSymbolCount:n.size,excludedSymbolCount:new Set([...t,...n]).size}}}function I_(e,t,n){let i=[...new Set(t.map(d=>d.file))].sort(),r=[...new Set(t.filter(d=>d.source!=="caller-map-inversion"||d.callEvidence==="scip-chunk").map(d=>d.file))].sort(),o=new Map;for(let d of n.slice(0,500)){if(d.file===e.relativePath)continue;let m=`${d.symbol}|${d.file}`;o.has(m)||o.set(m,{symbol:d.symbol,shortName:A(d.symbol),file:d.file,evidenceStrength:d.source==="scip-chunk"?"candidate":"exact",evidenceSource:d.source})}let s=[...o.values()].sort((d,m)=>d.file.localeCompare(m.file)||d.symbol.localeCompare(m.symbol)),a=i.length,l=s.length,c=a*l,u=s.filter(d=>d.evidenceStrength==="candidate").map(d=>d.symbol);return{symbol:e.symbol,shortName:A(e.symbol),fanIn:a,fanOut:l,callerFiles:i,candidateCallerFiles:r,externalCallees:s.map(({symbol:d,shortName:m,file:f})=>({symbol:d,shortName:m,file:f})),externalCalleeEvidence:s,candidateExternalCallees:u,inputBasis:"mixed-static-call-or-reference-evidence",score:c,definedIn:e.relativePath,actionTier:"signal",riskKind:"coordination-hotspot",evidenceReasons:[`${a} incoming file(s) reference this symbol`,`${l} distinct cross-file callee symbol(s) are reached from it`,`centrality score is ${c} (fan-in * fan-out)`,`${r.length} incoming file(s) and ${u.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 qo(e,t={}){let{scope:n,minLoc:i=3,scanLimit:r}=t,o=new U(e),s=t.semantic!==!1,a=0,l=B("isolated.candidates",()=>{let S=ke(o.productionCallableDefinitions({scope:n,minLoc:i,excludeEntrySurfaces:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:typeof r=="number"&&r>0}),r).filter(x=>!Rr(e,x));return a=S.length,S},()=>({definitions:a})),c=0,u=B("isolated.strict-callees",()=>{let E=o.symbolsWithNonSelfCallees(l,{additive:!1,semantic:!1});return c=E.size,E},()=>({definitions:l.length,symbols:c})),d=l.filter(E=>!u.has(E.symbolId)),m=0,f=B("isolated.scip-callers",()=>{let E=o.crossFileCallerMap(d,{semantic:!1});return m=E.size,E},()=>({definitions:d.length,symbols:m})),p=new Set(f.keys());for(let E of o.frameworkReferencedSymbolIds(d))p.add(E);let g=d.filter(E=>!p.has(E.symbolId));if(s&&g.length>0){let E=Ln(e,g);for(let S of E.callers.keys())p.add(S);for(let S of E.incompleteSymbolIds)p.add(S);for(let S of E.unavailableSymbolIds)p.add(S);for(let S of o.symbolsWithNonSelfCallees(g,{additive:!1,semantic:!0}))u.add(S);g=g.filter(S=>!p.has(S.symbolId)).filter(S=>!u.has(S.symbolId))}let h=0,b=B("isolated.source-fallback-callers",()=>{let E=o.sourceFallbackCallerFiles(g,{skipPath:S=>J(S)==="test"});return h=E.size,E},()=>({definitions:g.length,symbols:h}));for(let E of b.keys())p.add(E);let v=g.filter(E=>!p.has(E.symbolId)),y=0,I=B("isolated.additive-callees",()=>{let E=o.symbolsWithNonSelfCallees(v,{additive:!0,semantic:s});return y=E.size,E},()=>({definitions:v.length,symbols:y}));for(let E of I)u.add(E);return v.filter(E=>!u.has(E.symbolId)).sort((E,S)=>de(S)-de(E)||E.relativePath.localeCompare(S.relativePath)||E.startLine-S.startLine).map(E=>({symbol:E.symbol,shortName:A(E.symbol),relativePath:E.relativePath,startLine:E.startLine,endLine:E.endLine,loc:de(E)}))}import{SymbolInformation_Kind as tt}from"@c4312/scip";var wv=500;function E_(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),i=rp.get(n);if(i!==void 0)return i;for(let[r,o]of Hs)if(o.toLowerCase().includes(n))return r;return null}function w_(e,t,n={}){let{scope:i,limit:r=100}=n,o=E_(t);return o===null?[]:D_(e,i).map(a=>({row:a,resolvedKind:Dv(a)})).filter(a=>a.resolvedKind===o).slice(0,r).map(({row:a,resolvedKind:l})=>({symbol:a.symbol,shortName:A(a.symbol),kind:l,kindName:qr(l),relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function L_(e,t={}){let n=M_(e,t.scope);for(let i of P_(e,t.scope)){let r=Dv(i);r===null||r===0||n.set(r,(n.get(r)??0)+1)}return[...n.entries()].sort((i,r)=>r[1]-i[1]||i[0]-r[0]).map(([i,r])=>({kind:i,kindName:qr(i),count:r}))}function D_(e,t){return Ue(e,{scope:t}).map(T_)}function M_(e,t){let n=new Map;for(let i of Lv(me(e,{scope:t,includeIgnored:!1}))){let r=i.map(()=>"?").join(", "),o=e.all(`SELECT gs.kind AS kind, COUNT(*) AS count
297
297
  FROM defn_enclosing_ranges der
298
298
  JOIN global_symbols gs ON der.symbol_id = gs.id
299
299
  JOIN documents d ON der.document_id = d.id
@@ -301,7 +301,7 @@ import{c as tp,e as np,f as qt}from"./chunk-B2OB55RR.js";import{b as kt,c as ec}
301
301
  AND gs.kind != 0
302
302
  AND gs.symbol NOT LIKE '%#'
303
303
  AND d.relative_path IN (${r})
304
- GROUP BY gs.kind`,...i);for(let s of o)n.set(s.kind,(n.get(s.kind)??0)+s.count)}return n}function j_(e,t){let n=[];for(let i of Mv(me(e,{scope:t,includeIgnored:!1}))){let r=i.map(()=>"?").join(", ");n.push(...e.all(`SELECT gs.symbol,
304
+ GROUP BY gs.kind`,...i);for(let s of o)n.set(s.kind,(n.get(s.kind)??0)+s.count)}return n}function P_(e,t){let n=[];for(let i of Lv(me(e,{scope:t,includeIgnored:!1}))){let r=i.map(()=>"?").join(", ");n.push(...e.all(`SELECT gs.symbol,
305
305
  gs.kind,
306
306
  gs.documentation,
307
307
  gs.enclosing_symbol,
@@ -314,12 +314,12 @@ import{c as tp,e as np,f as qt}from"./chunk-B2OB55RR.js";import{b as kt,c as ec}
314
314
  WHERE (gs.kind IS NULL OR gs.kind = 0 OR gs.symbol LIKE '%#')
315
315
  ${e.symbolNoiseFor("gs")}
316
316
  AND d.relative_path IN (${r})
317
- ORDER BY d.relative_path, der.start_line, der.end_line, gs.symbol`,...i))}return n}function Mv(e){let t=[];for(let n=0;n<e.length;n+=Dv)t.push(e.slice(n,n+Dv));return t}function H_(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 Pv(e){return e.kind!==null&&e.kind!==0?U_(e.kind,e.symbol,e.documentation):z_(e.symbol,e.documentation,e.enclosing_symbol)}function U_(e,t,n){let i=(n??"").toLowerCase();if(Bt(t)==="type"){if(i.includes("type "))return tt.TypeAlias;if(i.includes("interface "))return tt.Interface;if(i.includes("struct "))return tt.Struct;if(i.includes("trait "))return tt.Trait;if(i.includes("class "))return tt.Class}return e}function z_(e,t,n){let i=zn(e);if("kind"in i)return null;let r=i.descriptors,o=r[r.length-2]??null,s=Bt(e),a=(t??"").toLowerCase();return s==="type"?a.includes("type ")?tt.TypeAlias:a.includes("interface ")?tt.Interface:a.includes("struct ")?tt.Struct:a.includes("trait ")?tt.Trait:a.includes("class ")?tt.Class:tt.Class:s==="method"?o?.suffix==="type"?tt.Method:tt.Function:s==="namespace"?tt.Module:s!=="term"?null:a.includes("async def ")||a.includes("def ")?tt.Function:(n?Bt(n):o?.suffix??null)==="type"?tt.Field:tt.Variable}function q_(e,t={}){let{limit:n=10,scope:i,minDepth:r=3,edgeBasis:o="symbol-references"}=t,s=$e(e,i,o==="imports"?{scipEdges:"imports-only",sourceEdges:"imports-only"}:void 0),{components:a,componentOf:l}=Hi(s),c=new Map;for(let h=0;h<a.length;h++)c.set(h,new Set);for(let[h,b]of s){let v=l.get(h);for(let y of b){let I=l.get(y);I!==v&&c.get(v).add(I)}}let u=new Array(a.length),d=new Array(a.length);for(let h=0;h<a.length;h++){let b=[],v=0;for(let y of[...c.get(h)].sort((I,E)=>I-E)){let I=d[y];(I>v||I===v&&K_(u[y],b,a)<0)&&(v=I,b=u[y])}u[h]=[h,...b],d[h]=1+v}function m(h){return u[h]}let f=a.map(h=>[...h].sort()),p=new Set,g=[];for(let h=0;h<a.length;h++){let v=m(h).map(E=>f[E]),y=v.map(E=>E[0]);if(v.length<r)continue;let I=y.join(" ");p.has(I)||(p.add(I),g.push(G_(y,v,o)))}return g.sort((h,b)=>b.depth-h.depth||h.chain.join("\0").localeCompare(b.chain.join("\0"))),W_(g).slice(0,n)}function K_(e,t,n){if(t.length===0)return-1;let i=e.map(o=>[...n[o]].sort()[0]??"").join("\0"),r=t.map(o=>[...n[o]].sort()[0]??"").join("\0");return i.localeCompare(r)}function G_(e,t,n){let i=t.reduce((o,s)=>o+s.length,0),r=t.filter(o=>o.length>1).length;return{chain:e,components:t,depth:t.length,fileCount:i,edgeBasis:n,actionTier:"signal",chainKind:"transitive-dependency-depth",evidenceReasons:[`${t.length} condensed dependency component(s) form the representative transitive path`,`${i} file(s) are represented; ${r} 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 W_(e){let t=[];for(let n of e)t.some(i=>V_(n.chain,i.chain))||t.push(n);return t}function V_(e,t){if(e.length>=t.length)return!1;let n=t.length-e.length;for(let i=0;i<e.length;i++)if(e[i]!==t[n+i])return!1;return!0}function J_(e,t){let n=pe(e,t);if(!n)return[];let i=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
318
- WHERE id = ? LIMIT 1`,n.symbolId);if(!i)return[];let r=[{symbol:i.symbol,shortName:A(i.symbol),depth:0}],o=i.enclosing_symbol,s=1,a=new Set([i.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;r.push({symbol:d.symbol,shortName:A(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(r.length>1)return r;let l=zn(i.symbol);if("kind"in l)return r;let c=l.descriptors;if(c.length<=1)return r;let u=[r[0]];for(let d=c.length-2,m=1;d>=0;d--,m++){let p=c.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:p,shortName:p,depth:m})}return u}function Y_(e,t={}){let i=new U(e).productionCallableDefinitions({scope:t.scope,requireCallableSymbol:!0,includeSuppressed:!0}),r=Nv(e,i),o=t.search?.trim().toLocaleLowerCase();return i.map(s=>Av(e,s,r.get(s.symbolId)??[])).filter(s=>s!==null).map(s=>s.result).filter(s=>!o||Z_(s).includes(o)).sort(eB)}function X_(e,t,n={}){let i=at(e,t);if(!i.match)return{kind:"missing",query:t};if(i.total>1)return{kind:"ambiguous",query:t,total:i.total,candidates:[{symbol:i.match.symbol,shortName:A(i.match.symbol),relativePath:i.match.relativePath,startLine:i.match.startLine},...i.candidates]};let r=new U(e),o=r.definitionsForFile(i.match.relativePath).find(f=>f.symbol===i.match.symbol);if(!o?.isFunctionLike)return{kind:"not-entry",query:t,symbol:i.match.symbol,shortName:A(i.match.symbol),file:i.match.relativePath,reason:"The resolved symbol is not a callable definition."};let s=Nv(e,[o]),a=Av(e,o,s.get(o.symbolId)??[]);if(!a)return{kind:"not-entry",query:t,symbol:o.symbol,shortName:A(o.symbol),file:o.relativePath,reason:"The callable is neither an external root nor an uncalled callable on a detected entry surface."};let l=tB(e,r,o),c=new Set(n.expand??[]),u=oB(l,c),d=new Set(u.regions.filter(f=>f.expanded).map(f=>f.id)),m=[...c].filter(f=>!d.has(f)).sort();return{kind:"matched",query:t,entry:a.result,regions:u.regions,regionEdges:u.regionEdges,unmatchedExpansions:m,coverage:{completeWithinIndexedStaticCallEdges:!0,completeWithinSelectedStaticEvidence:!0,candidateReachabilityIncluded:l.edges.some(f=>f.evidenceStrength==="candidate"),dynamicDispatchRepresented:!1,symbolCount:l.symbols.length,symbolEdgeCount:l.edges.length,exactSymbolEdgeCount:l.edges.filter(f=>f.evidenceStrength==="exact").length,candidateSymbolEdgeCount:l.edges.filter(f=>f.evidenceStrength==="candidate").length,regionCount:u.regions.length,regionEdgeCount:u.regionEdges.length,externalCallCount:l.externalCalls.length}}}function Nv(e,t){let n=t.filter(i=>_v(e,i.relativePath)||pr(e,i.symbol,i.relativePath).length>0);return yp(e,n,{semantic:!1,semanticEvidence:ge})}function Av(e,t,n){let i=Q_(e,t),r=i.length>0,o=_v(e,t.relativePath)&&n.length===0;if(!r&&!o)return null;let s=[...i];return o&&s.push("entry-surface-without-indexed-caller"),{definition:t,result:{symbol:t.symbol,shortName:A(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,documentation:t.documentation,confidence:r?"root":"candidate",evidence:s,indexedCallerCount:n.length}}}function _v(e,t){return Qe(e,t)||/(?:^|\/)entry\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(t)}function Q_(e,t){let n=pr(e,t.symbol,t.relativePath),i=[];return Tv(n,["package-surface-file","transitive-package-surface"])&&xt(e,t)&&i.push("package-public-export"),n.includes("rust-public-library")&&i.push("rust-public-library"),n.includes("framework-entrypoint")&&i.push("framework-dispatched-export"),Tv(n,["configured-file","configured-path-prefix","configured-qualified-var","configured-symbol-pattern"])&&i.push("configured-entry-root"),i}function Tv(e,t){return t.some(n=>e.includes(n))}function Z_(e){return[e.symbol,e.shortName,e.file,e.documentation??"",...e.evidence].join(`
319
- `).toLocaleLowerCase()}function eB(e,t){return Fv(e.confidence)-Fv(t.confidence)||e.file.localeCompare(t.file)||e.startLine-t.startLine||e.symbol.localeCompare(t.symbol)}function Fv(e){return e==="root"?0:1}function tB(e,t,n){let i=new Map([[n.symbol,0]]),r=new Map,o=new Map([[n.symbol,n]]),s=new Map,a=new Map,l=[n];for(;l.length>0;){let c=t.calleeMap(l,{additive:!1,semantic:!1}),u=[];for(let d of l){let m=i.get(d.symbol)??0;r.set(d.symbol,kv(d,m));for(let f of c.get(d.symbolId)??[]){let p=nB(t,f,o);if(!p){let v=rB(d,f);a.set(lB(v),v);continue}let g=m+1,h=i.get(p.symbol);(h===void 0||g<h)&&i.set(p.symbol,g),r.set(p.symbol,kv(p,Math.min(g,h??g)));let b=iB(d,p,f);s.set(aB(b),b),h===void 0&&u.push(p)}}l=u}return{symbols:[...r.values()].sort(cB),edges:[...s.values()].sort(uB),externalCalls:[...a.values()].sort(dB)}}function nB(e,t,n){let i=n.get(t.symbol);if(i)return i;let r=e.definitionsForFile(t.file).find(o=>o.symbol===t.symbol)??null;return r&&n.set(r.symbol,r),r}function kv(e,t){return{symbol:e.symbol,shortName:A(e.symbol),file:e.relativePath,depth:t}}function iB(e,t,n){return{fromSymbol:e.symbol,fromShortName:A(e.symbol),fromFile:e.relativePath,toSymbol:t.symbol,toShortName:A(t.symbol),toFile:t.relativePath,source:n.source,evidenceStrength:n.source==="scip-chunk"?"candidate":"exact"}}function rB(e,t){return{fromSymbol:e.symbol,fromShortName:A(e.symbol),fromFile:e.relativePath,toSymbol:t.symbol,toShortName:A(t.symbol),reportedFile:t.file,source:t.source,evidenceStrength:t.source==="scip-chunk"?"candidate":"exact"}}function oB(e,t){let n=Wo(e.symbols,c=>c.file),i=Wo(e.edges.filter(c=>c.fromFile===c.toFile),c=>c.fromFile),r=Wo(e.externalCalls,c=>c.fromFile),o=sB(e.edges.filter(c=>c.fromFile!==c.toFile)),s=Wo(o,c=>c.toRegionId),a=Wo(o,c=>c.fromRegionId);return{regions:[...n.entries()].map(([c,u])=>{let d=wd(c),m=t.has(d),f=i.get(c)??[],p=r.get(c)??[];return{id:d,file:c,minDepth:Math.min(...u.map(g=>g.depth)),symbolCount:u.length,internalEdgeCount:f.length,externalCallCount:p.length,incomingRegionIds:Vo((s.get(d)??[]).map(g=>g.fromRegionId)),outgoingRegionIds:Vo((a.get(d)??[]).map(g=>g.toRegionId)),expanded:m,symbols:m?u:[],internalEdges:m?f:[],externalCalls:m?p:[]}}).sort((c,u)=>c.minDepth-u.minDepth||c.file.localeCompare(u.file)),regionEdges:o}}function sB(e){let t=new Map;for(let n of e){let i=`${n.fromFile}\0${n.toFile}`,r=t.get(i)??[];r.push(n),t.set(i,r)}return[...t.values()].map(n=>{let i=n[0];return{fromRegionId:wd(i.fromFile),fromFile:i.fromFile,toRegionId:wd(i.toFile),toFile:i.toFile,callCount:n.length,exactCallCount:n.filter(r=>r.evidenceStrength==="exact").length,candidateCallCount:n.filter(r=>r.evidenceStrength==="candidate").length,fromSymbols:Vo(n.map(r=>r.fromShortName)),toSymbols:Vo(n.map(r=>r.toShortName)),evidence:Vo(n.map(r=>r.source))}}).sort((n,i)=>n.fromFile.localeCompare(i.fromFile)||n.toFile.localeCompare(i.toFile))}function Wo(e,t){let n=new Map;for(let i of e){let r=t(i),o=n.get(r)??[];o.push(i),n.set(r,o)}return n}function wd(e){return`file:${e}`}function Vo(e){return[...new Set(e)].sort()}function aB(e){return`${e.fromSymbol}\0${e.toSymbol}`}function lB(e){return`${e.fromSymbol}\0${e.toSymbol}`}function cB(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)||e.symbol.localeCompare(t.symbol)}function uB(e,t){return e.fromFile.localeCompare(t.fromFile)||e.fromSymbol.localeCompare(t.fromSymbol)||e.toSymbol.localeCompare(t.toSymbol)}function dB(e,t){return e.fromFile.localeCompare(t.fromFile)||e.fromSymbol.localeCompare(t.fromSymbol)||e.toSymbol.localeCompare(t.toSymbol)}function jt(e,t){let n=new Set;for(let i of e)t.has(i)&&n.add(i);return n}function nt(e,t){let n=new Set;for(let i of e)t.has(i)||n.add(i);return n}function ai(e,t){if(e.size===0&&t.size===0)return 0;let n=0;for(let r of e)t.has(r)&&(n+=1);let i=e.size+t.size-n;return i===0?0:n/i}function Bv(e,t){if(e.size===0)return 0;let n=0;for(let i of e)t.has(i)&&(n+=1);return n/e.size}function Ld(e,t){if(t<=0)return new Map;let n=new Map;for(let[i,r]of e)r>0&&n.set(i,Math.log(t/r));return n}function Lr(e){let t=[...e.values()].sort((i,r)=>i-r);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 Dr(e,t){let n=0;for(let i of e){let r=t.get(i)??0;n+=r*r}return Math.sqrt(n)}function Ov(e,t,n,i={}){let r=0,o=0,s=0,a=i.medianIdf??Lr(n),l=[],c=[];for(let m of e){let f=n.get(m)??0;o+=f*f,t.has(m)&&(r+=f*f,f>=a?l.push(m):c.push(m))}if(l.length===0&&c.length===0)return{similarity:0,significantShared:[],trivialShared:[]};for(let m of t){let f=n.get(m)??0;s+=f*f}let u=Math.sqrt(o)*Math.sqrt(s),d=u>0?r/u:0;return l.sort((m,f)=>(n.get(f)??0)-(n.get(m)??0)),{similarity:d,significantShared:l,trivialShared:c}}function $v(e,t,n,i){let r=0,o=i.medianIdf??Lr(n),s=[],a=[];for(let u of e){if(!t.has(u))continue;let d=n.get(u)??0;r+=d*d,d>=o?s.push(u):a.push(u)}if(s.length===0&&a.length===0)return{similarity:0,significantShared:[],trivialShared:[]};let l=i.magnitudeA*i.magnitudeB,c=l>0?r/l:0;return s.sort((u,d)=>(n.get(d)??0)-(n.get(u)??0)),{similarity:c,significantShared:s,trivialShared:a}}function Jo(e,t,n={}){let{minSimilarity:i=.4,limit:r=20}=n,o=()=>PB(e,t,{minSimilarity:i,limit:r,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"}),s=vB(e,t,{semantic:n.semantic!==!1});if(s.kind==="not-callable")return[];if(s.kind==="callee-evidence-unusable")return o();let a=s.target;if(!_e(a.symbol))return[];if(a.callees.size===0)return o();let l=fB(e,a,i,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return l.length>0?l.slice(0,r):o()}function Td(e,t,n,i={}){let r=pe(e,t),o=pe(e,n);if(!r||!o)return null;let s=Jo(e,r.symbol,{minSimilarity:0,limit:Number.POSITIVE_INFINITY,semantic:i.semantic,scanLimit:i.scanLimit}).find(c=>c.symbolB===o.symbol||c.symbolA===o.symbol);if(!s)return null;let a=r.endLine-r.startLine+1,l=o.endLine-o.startLine+1;return{symbolA:{symbol:r.symbol,shortName:A(r.symbol),file:r.relativePath,loc:a},symbolB:{symbol:o.symbol,shortName:A(o.symbol),file:o.relativePath,loc:l},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:mB(s)}}function mB(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 fB(e,t,n,i){let r=Mr(e).calleeIndex({minCallees:3,scanLimit:i.scanLimit,semantic:i.semantic}),o=DB(t,r.corpus),s=EB(o,r),a=pB(o,r),l=Lr(a),c=Dr(o.callees,a),u=[];for(let d of s){if(d.callees.size<3)continue;let m=Dr(d.callees,a),f=zv(o,d,a,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0,medianIdf:l,magnitudeA:c,magnitudeB:m});f&&u.push(f)}return u.sort((d,m)=>m.similarity-d.similarity),u}function pB(e,t){let n=new Map(t.docFreq);for(let i of e.callees)n.set(i,(n.get(i)??0)+1);return Ld(n,t.corpus.length+1)}function zv(e,t,n,i){let r=hB(e,t,n,i);if(!yB(r,i))return null;let{similarity:o,significantShared:s,trivialShared:a}=r,l=s.length>0?s:a,c=Vv(l,"callees");return{symbolA:e.symbol,shortNameA:A(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:A(t.symbol),fileB:t.file,similarity:o,similarityBasis:"callees",sharedCallees:l.map(A),uniqueToA:[...nt(e.callees,t.callees)].map(A),uniqueToB:[...nt(t.callees,e.callees)].map(A),...c}}function gB(e,t,n,i){let r=i.magnitudeA??Dr(e.callees,n),o=i.magnitudeB??Dr(t.callees,n),s=0,a=0,l=0,c=i.medianIdf??Lr(n);for(let m of e.callees){if(!t.callees.has(m))continue;let f=n.get(m)??0;s+=f*f,l+=1,f>=c&&(a+=1)}if(l===0)return!1;let u=r*o;return(u>0?s/u:0)<i.minSimilarity?!1:a>=i.requireSignificantShared||l>=i.requireSharedCount}function hB(e,t,n,i){return i.magnitudeA===void 0||i.magnitudeB===void 0?Ov(e.callees,t.callees,n,{medianIdf:i.medianIdf}):$v(e.callees,t.callees,n,{medianIdf:i.medianIdf,magnitudeA:i.magnitudeA,magnitudeB:i.magnitudeB})}function yB(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 Yo(e,t={}){let{minSimilarity:n=.5,limit:i=20,scope:r,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,l=t.semantic!==!1,c=Ae(),u=0,d=0,m=0,f=0,p=0,g=0,h=0;return B("similar.all",()=>{let v=Mr(e).calleeIndex({minCallees:o,scope:r,scanLimit:a,semantic:l}),y=v.corpus;u=y.length;let I=t.focusFiles,E=[],S=0;return B("similar.all.pair-scan",()=>{for(let x=0;x<y.length;x+=1){let C=y[x],L=I?.has(C.file)??!1,w=v.weightedMagnitudes[x],R=new Set;for(let M of C.callees){let _=v.candidateIndexesByCallee.get(M);if(_)for(let D of _)D<=x||I&&!L&&!I.has(y[D].file)||R.add(D)}c&&(m+=R.size,R.size>0&&(d+=1));for(let M of R){let _=y[M];if(s&&C.file===_.file){c&&(p+=1);continue}if(qv(C,_)){c&&(g+=1);continue}c&&(f+=1);let D=zv(C,_,v.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:v.medianIdf,magnitudeA:w,magnitudeB:v.weightedMagnitudes[M]});D&&(bB(E,D,i,S),c&&(h+=1),S+=1)}}},()=>({corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:f,crossFileSkips:p,signatureSkips:g,insertedResults:h,topResults:E.length})),B("similar.all.sort-project",()=>(E.sort((x,C)=>C.result.similarity-x.result.similarity||x.order-C.order),E.map(x=>x.result)),()=>({topResults:E.length}))},()=>({minSimilarity:n,limit:i,scope:r,minCallees:o,crossFileOnly:s,scanLimit:a,semantic:l,corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:f,crossFileSkips:p,signatureSkips:g,insertedResults:h}))}function Fd(e,t={}){let{minSimilarity:n=.5,scope:i,minCallees:r=4,crossFileOnly:o=!1,scanLimit:s}=t,a=t.semantic!==!1,l=Ae(),c=0,u=0,d=0,m=0,f=0,p=0,g=0;return B("similar.all-count",()=>{let b=Mr(e).calleeIndex({minCallees:r,scope:i,scanLimit:s,semantic:a}),v=b.corpus;c=v.length;let y=t.focusFiles;return B("similar.all-count.pair-scan",()=>{for(let I=0;I<v.length;I+=1){let E=v[I],S=y?.has(E.file)??!1,x=b.weightedMagnitudes[I],C=new Set;for(let L of E.callees){let w=b.candidateIndexesByCallee.get(L);if(w)for(let R of w)R<=I||y&&!S&&!y.has(v[R].file)||C.add(R)}l&&(d+=C.size,C.size>0&&(u+=1));for(let L of C){let w=v[L];if(o&&E.file===w.file){l&&(f+=1);continue}if(qv(E,w)){l&&(p+=1);continue}l&&(m+=1),gB(E,w,b.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:b.medianIdf,magnitudeA:x,magnitudeB:b.weightedMagnitudes[L]})&&(g+=1)}}},()=>({corpusSize:c,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:f,signatureSkips:p,insertedResults:g})),g},()=>({minSimilarity:n,scope:i,minCallees:r,crossFileOnly:o,scanLimit:s,semantic:a,corpusSize:c,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:f,signatureSkips:p,insertedResults:g}))}function qv(e,t){if(e.paramCount<0||t.paramCount<0)return!1;let n=Math.abs(e.paramCount-t.paramCount),i=Math.max(2,Math.ceil(Math.max(e.paramCount,t.paramCount)*.5));return n>i}var Kv=Ct({kind:"source-fingerprints",invalidation:Ye("source-fingerprints"),serialize:JB,deserialize:VB});function bB(e,t,n,i){if(n<=0)return;if(e.length<n){e.push({result:t,order:i});return}let r=0;for(let s=1;s<e.length;s+=1){let a=e[s],l=e[r];(a.result.similarity<l.result.similarity||a.result.similarity===l.result.similarity&&a.order>l.order)&&(r=s)}let o=e[r];t.similarity<=o.result.similarity||(e[r]={result:t,order:i})}var SB=["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 vB(e,t,n){let i=pe(e,t);if(!i)return{kind:"not-callable"};if(!_e(i.symbol))return{kind:"not-callable"};let r=new U(e),o=vi(e,i,{semantic:n.semantic,semanticEvidence:ge});return o.semanticIncomplete||o.semanticUnavailable?{kind:"callee-evidence-unusable"}:{kind:"resolved",target:{symbol:i.symbol,file:i.relativePath,callees:cl(o.rows.map(s=>s.symbol)),paramCount:r.callableSignature(i)?.paramCount??-1}}}var CB=Fe("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),xB=Fe("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function Gv(e,t){let{minCallees:n,scope:i,excludeSymbol:r,scanLimit:o}=t,s=t.semantic!==!1,a=CB.get(e,()=>new Map),l=`${n}|${i??""}|${o??""}|${s}`,c=!0,u=0,d=0;return B("similar.callee-fingerprints.resolve",()=>{let m=a.get(l);if(c=m!==void 0,m||(m=wB(e,{minCallees:n,scope:i,scanLimit:o,semantic:s}),a.set(l,m)),u=m.length,r===void 0)return m;let f=m.filter(p=>p.symbol!==r);return d=m.length-f.length,f},()=>({minCallees:n,scope:i,scanLimit:o,semantic:s,cacheHit:c,corpusSize:u,excludeSymbol:r!==void 0,excludedSymbols:d}))}function RB(e,t){let{minCallees:n,scope:i,scanLimit:r}=t,o=t.semantic!==!1,s=xB.get(e,()=>new Map),a=`${n}|${i??""}|${r??""}|${o}`,l=!0,c=0,u=0,d=0;return B("similar.callee-index.resolve",()=>{let m=s.get(a);return l=m!==void 0,m||(m=IB(Gv(e,{minCallees:n,scope:i,scanLimit:r,semantic:o})),s.set(a,m)),c=m.corpus.length,u=m.docFreq.size,d=m.candidateIndexesByCallee.size,m},()=>({minCallees:n,scope:i,scanLimit:r,semantic:o,cacheHit:l,corpusSize:c,indexedCallees:u,candidateBuckets:d}))}function Mr(e){return{calleeCorpus:t=>Gv(e,t),calleeIndex:t=>RB(e,t),sourceCorpus:(t={})=>Zv(e,t),sourceIndex:(t={})=>Uv(e,t),sourceCandidates:(t,n)=>(n.candidateMode??"full")==="target-pruned"?jB(e,t,{minSimilarity:n.minSimilarity,scanLimit:n.scanLimit}):$B(t,Uv(e,{scanLimit:n.scanLimit}))}}function IB(e){let t=Ae(),n=0,i=B("similar.callee-index.doc-frequency",()=>{let m=new Map;for(let f of e)for(let p of f.callees)m.set(p,(m.get(p)??0)+1);return n=m.size,m},()=>({corpusSize:e.length,uniqueCallees:n})),r=Math.max(8,Math.ceil(Math.sqrt(e.length))),o=B("similar.callee-index.idf-weights",()=>Ld(i,e.length),()=>({corpusSize:e.length,uniqueCallees:i.size})),s=B("similar.callee-index.weighted-magnitudes",()=>e.map(m=>Dr(m.callees,o)),()=>({corpusSize:e.length})),a=0,l=0,c=0,u=B("similar.callee-index.candidate-buckets",()=>{let m=new Map;for(let f=0;f<e.length;f+=1){let p=e[f];for(let g of p.callees){if((i.get(g)??0)>r){t&&(l+=1);continue}let h=m.get(g);h||(h=[],m.set(g,h)),h.push(f),t&&(a+=1)}}return t&&(c=m.size),m},()=>({corpusSize:e.length,buckets:c,candidateRefs:a,ubiquitousSkips:l,ubiquityThreshold:r})),d=B("similar.callee-index.median-idf",()=>Lr(o),()=>({uniqueCallees:o.size}));return{corpus:e,candidateIndexesByCallee:u,docFreq:i,idfWeights:o,weightedMagnitudes:s,medianIdf:d,ubiquityThreshold:r}}function EB(e,t){let n=new Map;for(let i of e.callees)for(let r of t.candidateIndexesByCallee.get(i)??[]){let o=t.corpus[r];o.symbol!==e.symbol&&n.set(o.symbol,o)}return n.size>0?[...n.values()]:t.corpus.filter(i=>i.symbol!==e.symbol)}function wB(e,t){let{minCallees:n,scope:i,scanLimit:r,semantic:o}=t,s=Ae(),a=new U(e),l=0,c=B("similar.callee-fingerprints.candidates",()=>{let g=ke(a.productionCallableDefinitions({scope:i,minLoc:5,sortByLocDesc:typeof r=="number"&&r>0}),r);return l=g.length,g},()=>({scope:i,scanLimit:r,candidateCount:l})),u=0,d=B("similar.callee-fingerprints.callee-map",()=>{let g=a.calleeEvidenceMap(c,{semantic:o});if(s)for(let h of g.rows.values())u+=h.length;return g},()=>({candidateCount:l,semantic:o,calleeEdges:u})),m=0,f=0,p=0;return B("similar.callee-fingerprints.shape",()=>{let h=c.filter(y=>!d.incompleteSymbolIds.has(y.symbolId)&&!d.unavailableSymbolIds.has(y.symbolId)).map(y=>({symbol:y.symbol,file:y.relativePath,callees:cl((d.rows.get(y.symbolId)??[]).map(I=>I.symbol)),paramCount:a.callableSignature(y)?.paramCount??-1})),b=LB(h);s&&(p=b.filter((y,I)=>y.callees.size!==h[I].callees.size).length);let v=b.filter(y=>y.callees.size>=n);return m=v.length,s&&(f=v.reduce((y,I)=>y+I.callees.size,0)),v},()=>({candidateCount:l,fingerprintCount:m,retainedCalleeCount:f,minCallees:n,siblingSaturatedFingerprints:p}))}var Wv=5;function LB(e){let t=new Map;for(let n of e){let i=t.get(n.file);i||(i=new Map,t.set(n.file,i));for(let r of n.callees)i.set(r,(i.get(r)??0)+1)}return e.map(n=>{let i=t.get(n.file);if(!i)return n;let r=[...n.callees].filter(s=>(i.get(s)??0)>=Wv);if(r.length===0)return n;let o=new Set(n.callees);for(let s of r)o.delete(s);return{...n,callees:o}})}function DB(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 i=[...e.callees].filter(o=>(n.get(o)??0)+1>=Wv);if(i.length===0)return e;let r=new Set(e.callees);for(let o of i)r.delete(o);return{...e,callees:r}}function cl(e){return new Set([...e].filter(t=>!MB(t)))}function MB(e){return SB.some(t=>e.includes(t))}function PB(e,t,n){let i=NB(e,t);if(!i||i.tokens.size<3)return[];let r=n.minSimilarity>=.5?n.minSimilarity:.3,o=[],s=n.candidateMode??"full",a=0,l=0,c=0,u=0;return B("similar.source-shape",()=>{let m=Mr(e).sourceCandidates(i,{minSimilarity:r,scanLimit:n.scanLimit,candidateMode:s});a=m.length;for(let f of m){if(f.symbol===i.symbol||f.tokens.size<3)continue;l+=1;let p=jt(i.tokens,f.tokens);if(p.size<2){c+=1;continue}let g=new Set([...i.tokens,...f.tokens]),h=g.size>0?p.size/g.size:0;if(h<r){u+=1;continue}o.push({symbolA:i.symbol,shortNameA:A(i.symbol),fileA:i.file,symbolB:f.symbol,shortNameB:A(f.symbol),fileB:f.file,similarity:h,similarityBasis:"source-tokens",sharedCallees:[...p].sort(),uniqueToA:[...nt(i.tokens,f.tokens)].sort(),uniqueToB:[...nt(f.tokens,i.tokens)].sort(),...Vv([...p],"source-tokens")})}return o.sort((f,p)=>p.similarity-f.similarity||f.shortNameB.localeCompare(p.shortNameB)),o.slice(0,n.limit)},()=>({symbol:i.symbol,file:i.file,targetTokens:i.tokens.size,candidateMode:s,candidates:a,comparedPairs:l,sharedSkips:c,similaritySkips:u,results:o.length}))}function Vv(e,t){let n=e.flatMap(Md),i=e.flatMap(h=>jv(h,t)),r=Dd(n,Jv),o=Dd(n,Yv),s=Dd(i,Pd),a=[...new Set(i.filter(Hv))],l=e.filter(h=>{let b=jv(h,t);return b.some(v=>Pd.has(v))&&b.some(Hv)}).length,c=[];r.length>0&&c.push(`access/query scaffolding: ${r.slice(0,5).join(", ")}`),o.length>0&&c.push(`framework/generic scaffolding: ${o.slice(0,5).join(", ")}`),s.length>0&&c.push(`domain behavior verbs: ${s.slice(0,5).join(", ")}`),s.length>0&&a.length>0&&c.push(`domain-specific terms: ${a.slice(0,5).join(", ")}`);let u=t==="source-tokens"&&n.length>0&&n.every(h=>Xv.has(h));u&&c.push("shared source tokens are generic scaffolding");let d=s.length>0&&a.length>0,m=r.length+o.length>0,f=t==="callees"&&d&&e.length>=4&&a.length>=4&&l>=2,p=f?"domain-behavior":d?m?"mixed":"domain-behavior":r.length>0?"access-query-scaffolding":o.length>0||u?"framework-scaffolding":"structural-overlap";p==="structural-overlap"&&e.length>0&&c.push(`shared ${t} overlap has no recognized domain or scaffolding category`);let g=p==="domain-behavior"&&(e.length>=3||f)?"direct":"signal";return{evidenceClass:p,actionTier:g,evidenceClassReasons:c,recommendation:TB(p,g)}}function TB(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 Dd(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function Md(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function jv(e,t){if(t==="source-tokens")return Md(e);let n=Y(e);return Md(n.length>0?n:FB(e))}function FB(e){return e.replace(/[()`]/g," ").replace(/\.[a-z][a-z0-9]+(?=\s|$)/gi," ").split(/[:/\\\s]+/).map(i=>i.trim()).filter(i=>/[A-Za-z]/.test(i)).at(-1)?.replace(/\.$/,"")??e}function Hv(e){return e.length>3&&!Pd.has(e)&&!Jv.has(e)&&!Yv.has(e)&&!Xv.has(e)&&!kB.has(e)}var Pd=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),Jv=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),Yv=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"]),Xv=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),kB=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 NB(e,t){let n=pe(e,t);if(!n||!_e(n.symbol))return null;let i=AB(e,n);return i?{symbol:n.symbol,file:n.relativePath,tokens:i}:null}function AB(e,t){let n=Y(t.symbol),i=KB(e,t.relativePath,t.startLine,t.endLine,n),r=nC(i,n);return r.size>0?r:null}var _B=Fe("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),BB=Fe("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function Qv(e){return`${e.scanLimit??""}`}function Zv(e,t={}){let n=_B.get(e,()=>new Map),i=Qv(t),r=n.get(i);return r||(r=qB(e,t),n.set(i,r)),r}function Uv(e,t={}){let n=BB.get(e,()=>new Map),i=Qv(t),r=n.get(i);return r||(r=OB(Zv(e,t)),n.set(i,r)),r}function OB(e){let t=new Map;for(let r of e)for(let o of r.tokens)t.set(o,(t.get(o)??0)+1);let n=Math.max(8,Math.ceil(Math.sqrt(e.length))),i=new Map;for(let r of e)for(let o of r.tokens){if((t.get(o)??0)>n)continue;let s=i.get(o);s||(s=[],i.set(o,s)),s.push(r)}return{corpus:e,candidateByToken:i,docFreq:t,ubiquityThreshold:n}}function $B(e,t){let n=new Map;for(let i of e.tokens)for(let r of t.candidateByToken.get(i)??[])r.symbol!==e.symbol&&n.set(r.symbol,r);return n.size>0?[...n.values()]:t.corpus.filter(i=>i.symbol!==e.symbol)}function jB(e,t,n){let i=Ae(),r=new U(e),o=HB(t.tokens.size,n.minSimilarity),s=0,a=0,l=0,c=B("similar.source-shape.target-files",()=>{let p=[...t.tokens],g=[];for(let h of me(e,{includeIgnored:!1})){s+=1;let b=se(e,h);b&&(a+=1,UB(b,p,o)&&g.push(h))}return l=g.length,g},()=>({symbol:t.symbol,targetTokens:t.tokens.size,requiredSharedTokens:o,scannedFiles:s,readableFiles:a,candidateFiles:l})),u=0,d=B("similar.source-shape.target-definitions",()=>{let p=ke(r.productionCallableDefinitions({files:c,sortByLocDesc:typeof n.scanLimit=="number"&&n.scanLimit>0}),n.scanLimit);return u=p.length,p},()=>({symbol:t.symbol,candidateFiles:l,scanLimit:n.scanLimit,definitionCount:u})),m=0;return B("similar.source-shape.target-fingerprints",()=>{let p=eC(e,d);return i&&(m=p.length),p},()=>({symbol:t.symbol,definitionCount:u,fingerprintCount:m})).filter(p=>p.symbol!==t.symbol)}function HB(e,t){return Math.max(2,Math.ceil(e*t))}function UB(e,t,n){if(t.length<n)return!1;let i=e.toLowerCase(),r=0;for(let o of t)if(zB(i,o)&&(r+=1,r>=n))return!0;return!1}function zB(e,t){return t==="num"?/\b\d+\b/.test(e):e.includes(t)}function qB(e,t={}){let n=new U(e),{scanLimit:i}=t,r=ke(n.productionCallableDefinitions({sortByLocDesc:typeof i=="number"&&i>0}),i);return eC(e,r)}function eC(e,t){let n=new Map;for(let r of t){let o=n.get(r.relativePath)??[];o.push(r),n.set(r.relativePath,o)}let i=new Map;for(let[r,o]of n){let s=se(e,r);if(!s)continue;let a=Nt(e,r,s),l=WB(e,r,a),c=!1,u=null;for(let d of o){let m=GB(d),f=l.get(m),p=f?new Set(f.tokens):null;p||(u??=re(e,r),p=nC(tC(u,d.startLine,d.endLine,d.leaf),d.leaf),l.set(m,{key:m,symbol:d.symbol,startLine:d.startLine,endLine:d.endLine,leaf:d.leaf,tokens:[...p].sort()}),c=!0),p.size>0&&i.set(d.symbol,{symbol:d.symbol,file:d.relativePath,tokens:p})}c&&YB(e,r,a,l)}return t.map(r=>i.get(r.symbol)).filter(r=>!!r)}function KB(e,t,n,i,r){let o=re(e,t);return o.length===0?"":tC(o,n,i,r)}function tC(e,t,n,i){if(n>=t&&n-t<=12)return e.slice(t,n+1).join(`
320
- `);let r=[new RegExp(`\\bdef\\s+${Oe(i)}\\b`),new RegExp(`\\bfun\\s+${Oe(i)}\\b`),new RegExp(`\\bfn\\s+${Oe(i)}\\b`),new RegExp(`\\bfunction\\s+${Oe(i)}\\b`),new RegExp(`\\b${Oe(i)}\\s*\\(`)],o=e.findIndex(s=>r.some(a=>a.test(s)));if(o>=0){let s=o;for(let a=o+1;a<e.length&&a<=o+8;a++){let l=e[a]??"";if(a>o&&QB(l)||(s=a,l.trim()===""&&a>o+1))break}return e.slice(o,s+1).join(`
317
+ ORDER BY d.relative_path, der.start_line, der.end_line, gs.symbol`,...i))}return n}function Lv(e){let t=[];for(let n=0;n<e.length;n+=wv)t.push(e.slice(n,n+wv));return t}function T_(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 Dv(e){return e.kind!==null&&e.kind!==0?F_(e.kind,e.symbol,e.documentation):k_(e.symbol,e.documentation,e.enclosing_symbol)}function F_(e,t,n){let i=(n??"").toLowerCase();if(Bt(t)==="type"){if(i.includes("type "))return tt.TypeAlias;if(i.includes("interface "))return tt.Interface;if(i.includes("struct "))return tt.Struct;if(i.includes("trait "))return tt.Trait;if(i.includes("class "))return tt.Class}return e}function k_(e,t,n){let i=zn(e);if("kind"in i)return null;let r=i.descriptors,o=r[r.length-2]??null,s=Bt(e),a=(t??"").toLowerCase();return s==="type"?a.includes("type ")?tt.TypeAlias:a.includes("interface ")?tt.Interface:a.includes("struct ")?tt.Struct:a.includes("trait ")?tt.Trait:a.includes("class ")?tt.Class:tt.Class:s==="method"?o?.suffix==="type"?tt.Method:tt.Function:s==="namespace"?tt.Module:s!=="term"?null:a.includes("async def ")||a.includes("def ")?tt.Function:(n?Bt(n):o?.suffix??null)==="type"?tt.Field:tt.Variable}function N_(e,t={}){let{limit:n=10,scope:i,minDepth:r=3,edgeBasis:o="symbol-references"}=t,s=$e(e,i,o==="imports"?{scipEdges:"imports-only",sourceEdges:"imports-only"}:void 0),{components:a,componentOf:l}=Hi(s),c=new Map;for(let h=0;h<a.length;h++)c.set(h,new Set);for(let[h,b]of s){let v=l.get(h);for(let y of b){let I=l.get(y);I!==v&&c.get(v).add(I)}}let u=new Array(a.length),d=new Array(a.length);for(let h=0;h<a.length;h++){let b=[],v=0;for(let y of[...c.get(h)].sort((I,E)=>I-E)){let I=d[y];(I>v||I===v&&A_(u[y],b,a)<0)&&(v=I,b=u[y])}u[h]=[h,...b],d[h]=1+v}function m(h){return u[h]}let f=a.map(h=>[...h].sort()),p=new Set,g=[];for(let h=0;h<a.length;h++){let v=m(h).map(E=>f[E]),y=v.map(E=>E[0]);if(v.length<r)continue;let I=y.join(" ");p.has(I)||(p.add(I),g.push(__(y,v,o)))}return g.sort((h,b)=>b.depth-h.depth||h.chain.join("\0").localeCompare(b.chain.join("\0"))),B_(g).slice(0,n)}function A_(e,t,n){if(t.length===0)return-1;let i=e.map(o=>[...n[o]].sort()[0]??"").join("\0"),r=t.map(o=>[...n[o]].sort()[0]??"").join("\0");return i.localeCompare(r)}function __(e,t,n){let i=t.reduce((o,s)=>o+s.length,0),r=t.filter(o=>o.length>1).length;return{chain:e,components:t,depth:t.length,fileCount:i,edgeBasis:n,actionTier:"signal",chainKind:"transitive-dependency-depth",evidenceReasons:[`${t.length} condensed dependency component(s) form the representative transitive path`,`${i} file(s) are represented; ${r} 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 B_(e){let t=[];for(let n of e)t.some(i=>O_(n.chain,i.chain))||t.push(n);return t}function O_(e,t){if(e.length>=t.length)return!1;let n=t.length-e.length;for(let i=0;i<e.length;i++)if(e[i]!==t[n+i])return!1;return!0}function $_(e,t){let n=pe(e,t);if(!n)return[];let i=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
318
+ WHERE id = ? LIMIT 1`,n.symbolId);if(!i)return[];let r=[{symbol:i.symbol,shortName:A(i.symbol),depth:0}],o=i.enclosing_symbol,s=1,a=new Set([i.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;r.push({symbol:d.symbol,shortName:A(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(r.length>1)return r;let l=zn(i.symbol);if("kind"in l)return r;let c=l.descriptors;if(c.length<=1)return r;let u=[r[0]];for(let d=c.length-2,m=1;d>=0;d--,m++){let p=c.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:p,shortName:p,depth:m})}return u}function j_(e,t={}){let i=new U(e).productionCallableDefinitions({scope:t.scope,requireCallableSymbol:!0,includeSuppressed:!0}),r=Fv(e,i),o=t.search?.trim().toLocaleLowerCase();return i.map(s=>kv(e,s,r.get(s.symbolId)??[])).filter(s=>s!==null).map(s=>s.result).filter(s=>!o||z_(s).includes(o)).sort(q_)}function H_(e,t,n={}){let i=at(e,t);if(!i.match)return{kind:"missing",query:t};if(i.total>1)return{kind:"ambiguous",query:t,total:i.total,candidates:[{symbol:i.match.symbol,shortName:A(i.match.symbol),relativePath:i.match.relativePath,startLine:i.match.startLine},...i.candidates]};let r=new U(e),o=r.definitionsForFile(i.match.relativePath).find(f=>f.symbol===i.match.symbol);if(!o?.isFunctionLike)return{kind:"not-entry",query:t,symbol:i.match.symbol,shortName:A(i.match.symbol),file:i.match.relativePath,reason:"The resolved symbol is not a callable definition."};let s=Fv(e,[o]),a=kv(e,o,s.get(o.symbolId)??[]);if(!a)return{kind:"not-entry",query:t,symbol:o.symbol,shortName:A(o.symbol),file:o.relativePath,reason:"The callable is neither an external root nor an uncalled callable on a detected entry surface."};let l=K_(e,r,o),c=new Set(n.expand??[]),u=J_(l,c),d=new Set(u.regions.filter(f=>f.expanded).map(f=>f.id)),m=[...c].filter(f=>!d.has(f)).sort();return{kind:"matched",query:t,entry:a.result,regions:u.regions,regionEdges:u.regionEdges,unmatchedExpansions:m,coverage:{completeWithinIndexedStaticCallEdges:!0,completeWithinSelectedStaticEvidence:!0,candidateReachabilityIncluded:l.edges.some(f=>f.evidenceStrength==="candidate"),dynamicDispatchRepresented:!1,symbolCount:l.symbols.length,symbolEdgeCount:l.edges.length,exactSymbolEdgeCount:l.edges.filter(f=>f.evidenceStrength==="exact").length,candidateSymbolEdgeCount:l.edges.filter(f=>f.evidenceStrength==="candidate").length,regionCount:u.regions.length,regionEdgeCount:u.regionEdges.length,externalCallCount:l.externalCalls.length}}}function Fv(e,t){let n=t.filter(i=>Nv(e,i.relativePath)||mr(e,i.symbol,i.relativePath).length>0);return pp(e,n,{semantic:!1,semanticEvidence:ge})}function kv(e,t,n){let i=U_(e,t),r=i.length>0,o=Nv(e,t.relativePath)&&n.length===0;if(!r&&!o)return null;let s=[...i];return o&&s.push("entry-surface-without-indexed-caller"),{definition:t,result:{symbol:t.symbol,shortName:A(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,documentation:t.documentation,confidence:r?"root":"candidate",evidence:s,indexedCallerCount:n.length}}}function Nv(e,t){return Qe(e,t)||/(?:^|\/)entry\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(t)}function U_(e,t){let n=mr(e,t.symbol,t.relativePath),i=[];return Mv(n,["package-surface-file","transitive-package-surface"])&&xt(e,t)&&i.push("package-public-export"),n.includes("rust-public-library")&&i.push("rust-public-library"),n.includes("framework-entrypoint")&&i.push("framework-dispatched-export"),Mv(n,["configured-file","configured-path-prefix","configured-qualified-var","configured-symbol-pattern"])&&i.push("configured-entry-root"),i}function Mv(e,t){return t.some(n=>e.includes(n))}function z_(e){return[e.symbol,e.shortName,e.file,e.documentation??"",...e.evidence].join(`
319
+ `).toLocaleLowerCase()}function q_(e,t){return Pv(e.confidence)-Pv(t.confidence)||e.file.localeCompare(t.file)||e.startLine-t.startLine||e.symbol.localeCompare(t.symbol)}function Pv(e){return e==="root"?0:1}function K_(e,t,n){let i=new Map([[n.symbol,0]]),r=new Map,o=new Map([[n.symbol,n]]),s=new Map,a=new Map,l=[n];for(;l.length>0;){let c=t.calleeMap(l,{additive:!1,semantic:!1}),u=[];for(let d of l){let m=i.get(d.symbol)??0;r.set(d.symbol,Tv(d,m));for(let f of c.get(d.symbolId)??[]){let p=G_(t,f,o);if(!p){let v=V_(d,f);a.set(Q_(v),v);continue}let g=m+1,h=i.get(p.symbol);(h===void 0||g<h)&&i.set(p.symbol,g),r.set(p.symbol,Tv(p,Math.min(g,h??g)));let b=W_(d,p,f);s.set(X_(b),b),h===void 0&&u.push(p)}}l=u}return{symbols:[...r.values()].sort(Z_),edges:[...s.values()].sort(eB),externalCalls:[...a.values()].sort(tB)}}function G_(e,t,n){let i=n.get(t.symbol);if(i)return i;let r=e.definitionsForFile(t.file).find(o=>o.symbol===t.symbol)??null;return r&&n.set(r.symbol,r),r}function Tv(e,t){return{symbol:e.symbol,shortName:A(e.symbol),file:e.relativePath,depth:t}}function W_(e,t,n){return{fromSymbol:e.symbol,fromShortName:A(e.symbol),fromFile:e.relativePath,toSymbol:t.symbol,toShortName:A(t.symbol),toFile:t.relativePath,source:n.source,evidenceStrength:n.source==="scip-chunk"?"candidate":"exact"}}function V_(e,t){return{fromSymbol:e.symbol,fromShortName:A(e.symbol),fromFile:e.relativePath,toSymbol:t.symbol,toShortName:A(t.symbol),reportedFile:t.file,source:t.source,evidenceStrength:t.source==="scip-chunk"?"candidate":"exact"}}function J_(e,t){let n=Ko(e.symbols,c=>c.file),i=Ko(e.edges.filter(c=>c.fromFile===c.toFile),c=>c.fromFile),r=Ko(e.externalCalls,c=>c.fromFile),o=Y_(e.edges.filter(c=>c.fromFile!==c.toFile)),s=Ko(o,c=>c.toRegionId),a=Ko(o,c=>c.fromRegionId);return{regions:[...n.entries()].map(([c,u])=>{let d=xd(c),m=t.has(d),f=i.get(c)??[],p=r.get(c)??[];return{id:d,file:c,minDepth:Math.min(...u.map(g=>g.depth)),symbolCount:u.length,internalEdgeCount:f.length,externalCallCount:p.length,incomingRegionIds:Go((s.get(d)??[]).map(g=>g.fromRegionId)),outgoingRegionIds:Go((a.get(d)??[]).map(g=>g.toRegionId)),expanded:m,symbols:m?u:[],internalEdges:m?f:[],externalCalls:m?p:[]}}).sort((c,u)=>c.minDepth-u.minDepth||c.file.localeCompare(u.file)),regionEdges:o}}function Y_(e){let t=new Map;for(let n of e){let i=`${n.fromFile}\0${n.toFile}`,r=t.get(i)??[];r.push(n),t.set(i,r)}return[...t.values()].map(n=>{let i=n[0];return{fromRegionId:xd(i.fromFile),fromFile:i.fromFile,toRegionId:xd(i.toFile),toFile:i.toFile,callCount:n.length,exactCallCount:n.filter(r=>r.evidenceStrength==="exact").length,candidateCallCount:n.filter(r=>r.evidenceStrength==="candidate").length,fromSymbols:Go(n.map(r=>r.fromShortName)),toSymbols:Go(n.map(r=>r.toShortName)),evidence:Go(n.map(r=>r.source))}}).sort((n,i)=>n.fromFile.localeCompare(i.fromFile)||n.toFile.localeCompare(i.toFile))}function Ko(e,t){let n=new Map;for(let i of e){let r=t(i),o=n.get(r)??[];o.push(i),n.set(r,o)}return n}function xd(e){return`file:${e}`}function Go(e){return[...new Set(e)].sort()}function X_(e){return`${e.fromSymbol}\0${e.toSymbol}`}function Q_(e){return`${e.fromSymbol}\0${e.toSymbol}`}function Z_(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)||e.symbol.localeCompare(t.symbol)}function eB(e,t){return e.fromFile.localeCompare(t.fromFile)||e.fromSymbol.localeCompare(t.fromSymbol)||e.toSymbol.localeCompare(t.toSymbol)}function tB(e,t){return e.fromFile.localeCompare(t.fromFile)||e.fromSymbol.localeCompare(t.fromSymbol)||e.toSymbol.localeCompare(t.toSymbol)}function jt(e,t){let n=new Set;for(let i of e)t.has(i)&&n.add(i);return n}function nt(e,t){let n=new Set;for(let i of e)t.has(i)||n.add(i);return n}function ai(e,t){if(e.size===0&&t.size===0)return 0;let n=0;for(let r of e)t.has(r)&&(n+=1);let i=e.size+t.size-n;return i===0?0:n/i}function Av(e,t){if(e.size===0)return 0;let n=0;for(let i of e)t.has(i)&&(n+=1);return n/e.size}function Rd(e,t){if(t<=0)return new Map;let n=new Map;for(let[i,r]of e)r>0&&n.set(i,Math.log(t/r));return n}function Er(e){let t=[...e.values()].sort((i,r)=>i-r);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 wr(e,t){let n=0;for(let i of e){let r=t.get(i)??0;n+=r*r}return Math.sqrt(n)}function _v(e,t,n,i={}){let r=0,o=0,s=0,a=i.medianIdf??Er(n),l=[],c=[];for(let m of e){let f=n.get(m)??0;o+=f*f,t.has(m)&&(r+=f*f,f>=a?l.push(m):c.push(m))}if(l.length===0&&c.length===0)return{similarity:0,significantShared:[],trivialShared:[]};for(let m of t){let f=n.get(m)??0;s+=f*f}let u=Math.sqrt(o)*Math.sqrt(s),d=u>0?r/u:0;return l.sort((m,f)=>(n.get(f)??0)-(n.get(m)??0)),{similarity:d,significantShared:l,trivialShared:c}}function Bv(e,t,n,i){let r=0,o=i.medianIdf??Er(n),s=[],a=[];for(let u of e){if(!t.has(u))continue;let d=n.get(u)??0;r+=d*d,d>=o?s.push(u):a.push(u)}if(s.length===0&&a.length===0)return{similarity:0,significantShared:[],trivialShared:[]};let l=i.magnitudeA*i.magnitudeB,c=l>0?r/l:0;return s.sort((u,d)=>(n.get(d)??0)-(n.get(u)??0)),{similarity:c,significantShared:s,trivialShared:a}}function Wo(e,t,n={}){let{minSimilarity:i=.4,limit:r=20}=n,o=()=>vB(e,t,{minSimilarity:i,limit:r,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"}),s=uB(e,t,{semantic:n.semantic!==!1});if(s.kind==="not-callable")return[];if(s.kind==="callee-evidence-unusable")return o();let a=s.target;if(!_e(a.symbol))return[];if(a.callees.size===0)return o();let l=iB(e,a,i,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return l.length>0?l.slice(0,r):o()}function Ld(e,t,n,i={}){let r=pe(e,t),o=pe(e,n);if(!r||!o)return null;let s=Wo(e,r.symbol,{minSimilarity:0,limit:Number.POSITIVE_INFINITY,semantic:i.semantic,scanLimit:i.scanLimit}).find(c=>c.symbolB===o.symbol||c.symbolA===o.symbol);if(!s)return null;let a=r.endLine-r.startLine+1,l=o.endLine-o.startLine+1;return{symbolA:{symbol:r.symbol,shortName:A(r.symbol),file:r.relativePath,loc:a},symbolB:{symbol:o.symbol,shortName:A(o.symbol),file:o.relativePath,loc:l},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:nB(s)}}function nB(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 iB(e,t,n,i){let r=Lr(e).calleeIndex({minCallees:3,scanLimit:i.scanLimit,semantic:i.semantic}),o=bB(t,r.corpus),s=gB(o,r),a=rB(o,r),l=Er(a),c=wr(o.callees,a),u=[];for(let d of s){if(d.callees.size<3)continue;let m=wr(d.callees,a),f=Hv(o,d,a,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0,medianIdf:l,magnitudeA:c,magnitudeB:m});f&&u.push(f)}return u.sort((d,m)=>m.similarity-d.similarity),u}function rB(e,t){let n=new Map(t.docFreq);for(let i of e.callees)n.set(i,(n.get(i)??0)+1);return Rd(n,t.corpus.length+1)}function Hv(e,t,n,i){let r=sB(e,t,n,i);if(!aB(r,i))return null;let{similarity:o,significantShared:s,trivialShared:a}=r,l=s.length>0?s:a,c=Gv(l,"callees");return{symbolA:e.symbol,shortNameA:A(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:A(t.symbol),fileB:t.file,similarity:o,similarityBasis:"callees",sharedCallees:l.map(A),uniqueToA:[...nt(e.callees,t.callees)].map(A),uniqueToB:[...nt(t.callees,e.callees)].map(A),...c}}function oB(e,t,n,i){let r=i.magnitudeA??wr(e.callees,n),o=i.magnitudeB??wr(t.callees,n),s=0,a=0,l=0,c=i.medianIdf??Er(n);for(let m of e.callees){if(!t.callees.has(m))continue;let f=n.get(m)??0;s+=f*f,l+=1,f>=c&&(a+=1)}if(l===0)return!1;let u=r*o;return(u>0?s/u:0)<i.minSimilarity?!1:a>=i.requireSignificantShared||l>=i.requireSharedCount}function sB(e,t,n,i){return i.magnitudeA===void 0||i.magnitudeB===void 0?_v(e.callees,t.callees,n,{medianIdf:i.medianIdf}):Bv(e.callees,t.callees,n,{medianIdf:i.medianIdf,magnitudeA:i.magnitudeA,magnitudeB:i.magnitudeB})}function aB(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 Vo(e,t={}){let{minSimilarity:n=.5,limit:i=20,scope:r,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,l=t.semantic!==!1,c=Ae(),u=0,d=0,m=0,f=0,p=0,g=0,h=0;return B("similar.all",()=>{let v=Lr(e).calleeIndex({minCallees:o,scope:r,scanLimit:a,semantic:l}),y=v.corpus;u=y.length;let I=t.focusFiles,E=[],S=0;return B("similar.all.pair-scan",()=>{for(let x=0;x<y.length;x+=1){let C=y[x],L=I?.has(C.file)??!1,w=v.weightedMagnitudes[x],R=new Set;for(let M of C.callees){let _=v.candidateIndexesByCallee.get(M);if(_)for(let D of _)D<=x||I&&!L&&!I.has(y[D].file)||R.add(D)}c&&(m+=R.size,R.size>0&&(d+=1));for(let M of R){let _=y[M];if(s&&C.file===_.file){c&&(p+=1);continue}if(Uv(C,_)){c&&(g+=1);continue}c&&(f+=1);let D=Hv(C,_,v.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:v.medianIdf,magnitudeA:w,magnitudeB:v.weightedMagnitudes[M]});D&&(lB(E,D,i,S),c&&(h+=1),S+=1)}}},()=>({corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:f,crossFileSkips:p,signatureSkips:g,insertedResults:h,topResults:E.length})),B("similar.all.sort-project",()=>(E.sort((x,C)=>C.result.similarity-x.result.similarity||x.order-C.order),E.map(x=>x.result)),()=>({topResults:E.length}))},()=>({minSimilarity:n,limit:i,scope:r,minCallees:o,crossFileOnly:s,scanLimit:a,semantic:l,corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:f,crossFileSkips:p,signatureSkips:g,insertedResults:h}))}function Dd(e,t={}){let{minSimilarity:n=.5,scope:i,minCallees:r=4,crossFileOnly:o=!1,scanLimit:s}=t,a=t.semantic!==!1,l=Ae(),c=0,u=0,d=0,m=0,f=0,p=0,g=0;return B("similar.all-count",()=>{let b=Lr(e).calleeIndex({minCallees:r,scope:i,scanLimit:s,semantic:a}),v=b.corpus;c=v.length;let y=t.focusFiles;return B("similar.all-count.pair-scan",()=>{for(let I=0;I<v.length;I+=1){let E=v[I],S=y?.has(E.file)??!1,x=b.weightedMagnitudes[I],C=new Set;for(let L of E.callees){let w=b.candidateIndexesByCallee.get(L);if(w)for(let R of w)R<=I||y&&!S&&!y.has(v[R].file)||C.add(R)}l&&(d+=C.size,C.size>0&&(u+=1));for(let L of C){let w=v[L];if(o&&E.file===w.file){l&&(f+=1);continue}if(Uv(E,w)){l&&(p+=1);continue}l&&(m+=1),oB(E,w,b.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:b.medianIdf,magnitudeA:x,magnitudeB:b.weightedMagnitudes[L]})&&(g+=1)}}},()=>({corpusSize:c,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:f,signatureSkips:p,insertedResults:g})),g},()=>({minSimilarity:n,scope:i,minCallees:r,crossFileOnly:o,scanLimit:s,semantic:a,corpusSize:c,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:f,signatureSkips:p,insertedResults:g}))}function Uv(e,t){if(e.paramCount<0||t.paramCount<0)return!1;let n=Math.abs(e.paramCount-t.paramCount),i=Math.max(2,Math.ceil(Math.max(e.paramCount,t.paramCount)*.5));return n>i}var zv=Ct({kind:"source-fingerprints",invalidation:Ye("source-fingerprints"),serialize:$B,deserialize:OB});function lB(e,t,n,i){if(n<=0)return;if(e.length<n){e.push({result:t,order:i});return}let r=0;for(let s=1;s<e.length;s+=1){let a=e[s],l=e[r];(a.result.similarity<l.result.similarity||a.result.similarity===l.result.similarity&&a.order>l.order)&&(r=s)}let o=e[r];t.similarity<=o.result.similarity||(e[r]={result:t,order:i})}var cB=["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 uB(e,t,n){let i=pe(e,t);if(!i)return{kind:"not-callable"};if(!_e(i.symbol))return{kind:"not-callable"};let r=new U(e),o=vi(e,i,{semantic:n.semantic,semanticEvidence:ge});return o.semanticIncomplete||o.semanticUnavailable?{kind:"callee-evidence-unusable"}:{kind:"resolved",target:{symbol:i.symbol,file:i.relativePath,callees:ll(o.rows.map(s=>s.symbol)),paramCount:r.callableSignature(i)?.paramCount??-1}}}var dB=Fe("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),mB=Fe("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function qv(e,t){let{minCallees:n,scope:i,excludeSymbol:r,scanLimit:o}=t,s=t.semantic!==!1,a=dB.get(e,()=>new Map),l=`${n}|${i??""}|${o??""}|${s}`,c=!0,u=0,d=0;return B("similar.callee-fingerprints.resolve",()=>{let m=a.get(l);if(c=m!==void 0,m||(m=hB(e,{minCallees:n,scope:i,scanLimit:o,semantic:s}),a.set(l,m)),u=m.length,r===void 0)return m;let f=m.filter(p=>p.symbol!==r);return d=m.length-f.length,f},()=>({minCallees:n,scope:i,scanLimit:o,semantic:s,cacheHit:c,corpusSize:u,excludeSymbol:r!==void 0,excludedSymbols:d}))}function fB(e,t){let{minCallees:n,scope:i,scanLimit:r}=t,o=t.semantic!==!1,s=mB.get(e,()=>new Map),a=`${n}|${i??""}|${r??""}|${o}`,l=!0,c=0,u=0,d=0;return B("similar.callee-index.resolve",()=>{let m=s.get(a);return l=m!==void 0,m||(m=pB(qv(e,{minCallees:n,scope:i,scanLimit:r,semantic:o})),s.set(a,m)),c=m.corpus.length,u=m.docFreq.size,d=m.candidateIndexesByCallee.size,m},()=>({minCallees:n,scope:i,scanLimit:r,semantic:o,cacheHit:l,corpusSize:c,indexedCallees:u,candidateBuckets:d}))}function Lr(e){return{calleeCorpus:t=>qv(e,t),calleeIndex:t=>fB(e,t),sourceCorpus:(t={})=>Xv(e,t),sourceIndex:(t={})=>jv(e,t),sourceCandidates:(t,n)=>(n.candidateMode??"full")==="target-pruned"?PB(e,t,{minSimilarity:n.minSimilarity,scanLimit:n.scanLimit}):MB(t,jv(e,{scanLimit:n.scanLimit}))}}function pB(e){let t=Ae(),n=0,i=B("similar.callee-index.doc-frequency",()=>{let m=new Map;for(let f of e)for(let p of f.callees)m.set(p,(m.get(p)??0)+1);return n=m.size,m},()=>({corpusSize:e.length,uniqueCallees:n})),r=Math.max(8,Math.ceil(Math.sqrt(e.length))),o=B("similar.callee-index.idf-weights",()=>Rd(i,e.length),()=>({corpusSize:e.length,uniqueCallees:i.size})),s=B("similar.callee-index.weighted-magnitudes",()=>e.map(m=>wr(m.callees,o)),()=>({corpusSize:e.length})),a=0,l=0,c=0,u=B("similar.callee-index.candidate-buckets",()=>{let m=new Map;for(let f=0;f<e.length;f+=1){let p=e[f];for(let g of p.callees){if((i.get(g)??0)>r){t&&(l+=1);continue}let h=m.get(g);h||(h=[],m.set(g,h)),h.push(f),t&&(a+=1)}}return t&&(c=m.size),m},()=>({corpusSize:e.length,buckets:c,candidateRefs:a,ubiquitousSkips:l,ubiquityThreshold:r})),d=B("similar.callee-index.median-idf",()=>Er(o),()=>({uniqueCallees:o.size}));return{corpus:e,candidateIndexesByCallee:u,docFreq:i,idfWeights:o,weightedMagnitudes:s,medianIdf:d,ubiquityThreshold:r}}function gB(e,t){let n=new Map;for(let i of e.callees)for(let r of t.candidateIndexesByCallee.get(i)??[]){let o=t.corpus[r];o.symbol!==e.symbol&&n.set(o.symbol,o)}return n.size>0?[...n.values()]:t.corpus.filter(i=>i.symbol!==e.symbol)}function hB(e,t){let{minCallees:n,scope:i,scanLimit:r,semantic:o}=t,s=Ae(),a=new U(e),l=0,c=B("similar.callee-fingerprints.candidates",()=>{let g=ke(a.productionCallableDefinitions({scope:i,minLoc:5,sortByLocDesc:typeof r=="number"&&r>0}),r);return l=g.length,g},()=>({scope:i,scanLimit:r,candidateCount:l})),u=0,d=B("similar.callee-fingerprints.callee-map",()=>{let g=a.calleeEvidenceMap(c,{semantic:o});if(s)for(let h of g.rows.values())u+=h.length;return g},()=>({candidateCount:l,semantic:o,calleeEdges:u})),m=0,f=0,p=0;return B("similar.callee-fingerprints.shape",()=>{let h=c.filter(y=>!d.incompleteSymbolIds.has(y.symbolId)&&!d.unavailableSymbolIds.has(y.symbolId)).map(y=>({symbol:y.symbol,file:y.relativePath,callees:ll((d.rows.get(y.symbolId)??[]).map(I=>I.symbol)),paramCount:a.callableSignature(y)?.paramCount??-1})),b=yB(h);s&&(p=b.filter((y,I)=>y.callees.size!==h[I].callees.size).length);let v=b.filter(y=>y.callees.size>=n);return m=v.length,s&&(f=v.reduce((y,I)=>y+I.callees.size,0)),v},()=>({candidateCount:l,fingerprintCount:m,retainedCalleeCount:f,minCallees:n,siblingSaturatedFingerprints:p}))}var Kv=5;function yB(e){let t=new Map;for(let n of e){let i=t.get(n.file);i||(i=new Map,t.set(n.file,i));for(let r of n.callees)i.set(r,(i.get(r)??0)+1)}return e.map(n=>{let i=t.get(n.file);if(!i)return n;let r=[...n.callees].filter(s=>(i.get(s)??0)>=Kv);if(r.length===0)return n;let o=new Set(n.callees);for(let s of r)o.delete(s);return{...n,callees:o}})}function bB(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 i=[...e.callees].filter(o=>(n.get(o)??0)+1>=Kv);if(i.length===0)return e;let r=new Set(e.callees);for(let o of i)r.delete(o);return{...e,callees:r}}function ll(e){return new Set([...e].filter(t=>!SB(t)))}function SB(e){return cB.some(t=>e.includes(t))}function vB(e,t,n){let i=IB(e,t);if(!i||i.tokens.size<3)return[];let r=n.minSimilarity>=.5?n.minSimilarity:.3,o=[],s=n.candidateMode??"full",a=0,l=0,c=0,u=0;return B("similar.source-shape",()=>{let m=Lr(e).sourceCandidates(i,{minSimilarity:r,scanLimit:n.scanLimit,candidateMode:s});a=m.length;for(let f of m){if(f.symbol===i.symbol||f.tokens.size<3)continue;l+=1;let p=jt(i.tokens,f.tokens);if(p.size<2){c+=1;continue}let g=new Set([...i.tokens,...f.tokens]),h=g.size>0?p.size/g.size:0;if(h<r){u+=1;continue}o.push({symbolA:i.symbol,shortNameA:A(i.symbol),fileA:i.file,symbolB:f.symbol,shortNameB:A(f.symbol),fileB:f.file,similarity:h,similarityBasis:"source-tokens",sharedCallees:[...p].sort(),uniqueToA:[...nt(i.tokens,f.tokens)].sort(),uniqueToB:[...nt(f.tokens,i.tokens)].sort(),...Gv([...p],"source-tokens")})}return o.sort((f,p)=>p.similarity-f.similarity||f.shortNameB.localeCompare(p.shortNameB)),o.slice(0,n.limit)},()=>({symbol:i.symbol,file:i.file,targetTokens:i.tokens.size,candidateMode:s,candidates:a,comparedPairs:l,sharedSkips:c,similaritySkips:u,results:o.length}))}function Gv(e,t){let n=e.flatMap(Ed),i=e.flatMap(h=>Ov(h,t)),r=Id(n,Wv),o=Id(n,Vv),s=Id(i,wd),a=[...new Set(i.filter($v))],l=e.filter(h=>{let b=Ov(h,t);return b.some(v=>wd.has(v))&&b.some($v)}).length,c=[];r.length>0&&c.push(`access/query scaffolding: ${r.slice(0,5).join(", ")}`),o.length>0&&c.push(`framework/generic scaffolding: ${o.slice(0,5).join(", ")}`),s.length>0&&c.push(`domain behavior verbs: ${s.slice(0,5).join(", ")}`),s.length>0&&a.length>0&&c.push(`domain-specific terms: ${a.slice(0,5).join(", ")}`);let u=t==="source-tokens"&&n.length>0&&n.every(h=>Jv.has(h));u&&c.push("shared source tokens are generic scaffolding");let d=s.length>0&&a.length>0,m=r.length+o.length>0,f=t==="callees"&&d&&e.length>=4&&a.length>=4&&l>=2,p=f?"domain-behavior":d?m?"mixed":"domain-behavior":r.length>0?"access-query-scaffolding":o.length>0||u?"framework-scaffolding":"structural-overlap";p==="structural-overlap"&&e.length>0&&c.push(`shared ${t} overlap has no recognized domain or scaffolding category`);let g=p==="domain-behavior"&&(e.length>=3||f)?"direct":"signal";return{evidenceClass:p,actionTier:g,evidenceClassReasons:c,recommendation:CB(p,g)}}function CB(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 Id(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function Ed(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function Ov(e,t){if(t==="source-tokens")return Ed(e);let n=Y(e);return Ed(n.length>0?n:xB(e))}function xB(e){return e.replace(/[()`]/g," ").replace(/\.[a-z][a-z0-9]+(?=\s|$)/gi," ").split(/[:/\\\s]+/).map(i=>i.trim()).filter(i=>/[A-Za-z]/.test(i)).at(-1)?.replace(/\.$/,"")??e}function $v(e){return e.length>3&&!wd.has(e)&&!Wv.has(e)&&!Vv.has(e)&&!Jv.has(e)&&!RB.has(e)}var wd=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),Wv=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),Vv=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"]),Jv=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),RB=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 IB(e,t){let n=pe(e,t);if(!n||!_e(n.symbol))return null;let i=EB(e,n);return i?{symbol:n.symbol,file:n.relativePath,tokens:i}:null}function EB(e,t){let n=Y(t.symbol),i=AB(e,t.relativePath,t.startLine,t.endLine,n),r=eC(i,n);return r.size>0?r:null}var wB=Fe("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),LB=Fe("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function Yv(e){return`${e.scanLimit??""}`}function Xv(e,t={}){let n=wB.get(e,()=>new Map),i=Yv(t),r=n.get(i);return r||(r=NB(e,t),n.set(i,r)),r}function jv(e,t={}){let n=LB.get(e,()=>new Map),i=Yv(t),r=n.get(i);return r||(r=DB(Xv(e,t)),n.set(i,r)),r}function DB(e){let t=new Map;for(let r of e)for(let o of r.tokens)t.set(o,(t.get(o)??0)+1);let n=Math.max(8,Math.ceil(Math.sqrt(e.length))),i=new Map;for(let r of e)for(let o of r.tokens){if((t.get(o)??0)>n)continue;let s=i.get(o);s||(s=[],i.set(o,s)),s.push(r)}return{corpus:e,candidateByToken:i,docFreq:t,ubiquityThreshold:n}}function MB(e,t){let n=new Map;for(let i of e.tokens)for(let r of t.candidateByToken.get(i)??[])r.symbol!==e.symbol&&n.set(r.symbol,r);return n.size>0?[...n.values()]:t.corpus.filter(i=>i.symbol!==e.symbol)}function PB(e,t,n){let i=Ae(),r=new U(e),o=TB(t.tokens.size,n.minSimilarity),s=0,a=0,l=0,c=B("similar.source-shape.target-files",()=>{let p=[...t.tokens],g=[];for(let h of me(e,{includeIgnored:!1})){s+=1;let b=se(e,h);b&&(a+=1,FB(b,p,o)&&g.push(h))}return l=g.length,g},()=>({symbol:t.symbol,targetTokens:t.tokens.size,requiredSharedTokens:o,scannedFiles:s,readableFiles:a,candidateFiles:l})),u=0,d=B("similar.source-shape.target-definitions",()=>{let p=ke(r.productionCallableDefinitions({files:c,sortByLocDesc:typeof n.scanLimit=="number"&&n.scanLimit>0}),n.scanLimit);return u=p.length,p},()=>({symbol:t.symbol,candidateFiles:l,scanLimit:n.scanLimit,definitionCount:u})),m=0;return B("similar.source-shape.target-fingerprints",()=>{let p=Qv(e,d);return i&&(m=p.length),p},()=>({symbol:t.symbol,definitionCount:u,fingerprintCount:m})).filter(p=>p.symbol!==t.symbol)}function TB(e,t){return Math.max(2,Math.ceil(e*t))}function FB(e,t,n){if(t.length<n)return!1;let i=e.toLowerCase(),r=0;for(let o of t)if(kB(i,o)&&(r+=1,r>=n))return!0;return!1}function kB(e,t){return t==="num"?/\b\d+\b/.test(e):e.includes(t)}function NB(e,t={}){let n=new U(e),{scanLimit:i}=t,r=ke(n.productionCallableDefinitions({sortByLocDesc:typeof i=="number"&&i>0}),i);return Qv(e,r)}function Qv(e,t){let n=new Map;for(let r of t){let o=n.get(r.relativePath)??[];o.push(r),n.set(r.relativePath,o)}let i=new Map;for(let[r,o]of n){let s=se(e,r);if(!s)continue;let a=Nt(e,r,s),l=BB(e,r,a),c=!1,u=null;for(let d of o){let m=_B(d),f=l.get(m),p=f?new Set(f.tokens):null;p||(u??=re(e,r),p=eC(Zv(u,d.startLine,d.endLine,d.leaf),d.leaf),l.set(m,{key:m,symbol:d.symbol,startLine:d.startLine,endLine:d.endLine,leaf:d.leaf,tokens:[...p].sort()}),c=!0),p.size>0&&i.set(d.symbol,{symbol:d.symbol,file:d.relativePath,tokens:p})}c&&jB(e,r,a,l)}return t.map(r=>i.get(r.symbol)).filter(r=>!!r)}function AB(e,t,n,i,r){let o=re(e,t);return o.length===0?"":Zv(o,n,i,r)}function Zv(e,t,n,i){if(n>=t&&n-t<=12)return e.slice(t,n+1).join(`
320
+ `);let r=[new RegExp(`\\bdef\\s+${Oe(i)}\\b`),new RegExp(`\\bfun\\s+${Oe(i)}\\b`),new RegExp(`\\bfn\\s+${Oe(i)}\\b`),new RegExp(`\\bfunction\\s+${Oe(i)}\\b`),new RegExp(`\\b${Oe(i)}\\s*\\(`)],o=e.findIndex(s=>r.some(a=>a.test(s)));if(o>=0){let s=o;for(let a=o+1;a<e.length&&a<=o+8;a++){let l=e[a]??"";if(a>o&&UB(l)||(s=a,l.trim()===""&&a>o+1))break}return e.slice(o,s+1).join(`
321
321
  `)}return e.slice(t,Math.min(e.length,t+8)).join(`
322
- `)}function GB(e){return`${e.symbol}\0${e.startLine}\0${e.endLine}\0${e.leaf}`}function WB(e,t,n){return Kv.read(e,t,n)??new Map}function VB(e){try{let t=JSON.parse(e);if(!Array.isArray(t.entries))return null;let n=new Map;for(let i of t.entries){if(!i||typeof i.key!="string"||typeof i.symbol!="string"||typeof i.startLine!="number"||typeof i.endLine!="number"||typeof i.leaf!="string"||!Array.isArray(i.tokens)||!i.tokens.every(r=>typeof r=="string"))return null;n.set(i.key,i)}return n}catch{return null}}function JB(e){let t={entries:[...e.values()].sort((n,i)=>n.key.localeCompare(i.key))};return JSON.stringify(t)}function YB(e,t,n,i){Kv.write(e,t,n,new Map(i))}function nC(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"]),i=XB(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=>!i.has(s));return new Set(o)}function XB(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 QB(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function pn(e,t){let n=new Map;return e.forEach((i,r)=>{let o=new Set;for(let s of t(i)){if(o.has(s))continue;o.add(s);let a=n.get(s);a?a.push(r):n.set(s,[r])}}),{candidatesFor:(i,r)=>{let o=new Set;for(let s of t(i)){let a=n.get(s);if(a)for(let l of a)l!==r&&o.add(l)}return[...o].sort((s,a)=>s-a)}}}function gn(e){let t=iC(e.profile?.name),n=()=>{let i=[];t=iC(e.profile?.name,e);let r=(s,a)=>{let l=e.profiles[s],c=e.profiles[a];t.candidatePairs+=1,t.comparedPairs+=1;let u=e.compare(l,c);u&&i.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 l of ZB(e,s)){let c=e.profiles[l];e.focusFiles&&!e.focusFiles.has(a.file)&&!e.focusFiles.has(c.file)||r(s,l)}}}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 l=e.profiles[a],c=e.focusFiles?.has(l.file)??!1;for(let u of eO(e,a))e.focusFiles&&!c&&!e.focusFiles.has(e.profiles[u].file)||r(a,u);if(i.length>s){t.overrunApplied=!0;break}}}i.sort(e.sort??((s,a)=>a.similarity-s.similarity)),t.matchedResults=i.length;let o=i.slice(0,e.limit);return t.emittedResults=o.length,e.onProfile?.({...t}),o};return e.profile?B(`pairwise-profile:${e.profile.name}`,n,()=>({...tO(e.profile?.metadata),...t})):n()}function ZB(e,t){if(e.candidateIndex)return rC(e,t,-1);let n=[];for(let i=0;i<e.profiles.length;i+=1)i!==t&&n.push(i);return n}function eO(e,t){if(e.candidateIndex)return rC(e,t,t);let n=[];for(let i=t+1;i<e.profiles.length;i+=1)n.push(i);return n}function rC(e,t,n){let i=e.profiles[t],r=new Set;for(let o of e.candidateIndex?.candidatesFor(i,t,e.profiles)??[])o<=n||o!==t&&(o<0||o>=e.profiles.length||r.add(o));return[...r].sort((o,s)=>o-s)}function iC(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 tO(e){return typeof e=="function"?e():e??{}}function nO(e,t={}){let{minSimilarity:n=.5,limit:i=20,scope:r,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:l}=iO(e,{scope:r,minDeps:s}),c=pn(a,u=>u.deps);return gn({profiles:a,limit:i,filePattern:o,overrunFactor:5,candidateIndex:c,profile:{name:"similar-files"},compare:(u,d)=>oO(u,d,n,l)})}function iO(e,t){let{scope:n,minDeps:i}=t,r=$e(e,n),{universalDeps:o,distinctiveDeps:s}=rO(r),a=[];for(let[l,c]of r)c.size>=i&&a.push({file:l,deps:new Set([...c].filter(u=>!o.has(u)))});return{profiles:a,distinctiveDeps:s}}function rO(e){let t=new Set,n=new Set,i=e.size;if(i===0)return{universalDeps:t,distinctiveDeps:n};let r=new Map;for(let s of e.values())for(let a of s)r.set(a,(r.get(a)??0)+1);let o=Math.max(3,Math.ceil(i*.03));for(let[s,a]of r)a>=5&&a/i>.3?t.add(s):a<=o&&n.add(s);return{universalDeps:t,distinctiveDeps:n}}function oO(e,t,n,i){let r=new Set;for(let c of e.deps)t.deps.has(c)&&r.add(c);if(r.size<3||e.deps.size<4||t.deps.size<4)return null;let o=0;for(let c of r)i.has(c)&&o++;if(o<2)return null;let s=ai(e.deps,t.deps);if(s<n)return null;let a=[];for(let c of e.deps)t.deps.has(c)||a.push(c);let l=[];for(let c of t.deps)e.deps.has(c)||l.push(c);return{fileA:e.file,fileB:t.file,similarity:s,sharedDeps:[...r],uniqueToA:a,uniqueToB:l}}function li(e){let t=[],n=[],i=[];for(let c of e.primitiveGroups)c.values.length!==0&&oC(c.bucket,n,i).push(`${c.reasonPrefix}: ${c.values.join(", ")}`);for(let c of e.nameGroups)sO(c.names,c.label,e.genericWords,e.stripPrefixes??[],t,oC(c.fallbackBucket,n,i));let r=t.length>0,o=n.length>0,s=i.length>0,a=r?o||s?"mixed":"domain-behavior":s?"shared-abstraction":"generic-workflow-scaffolding";return{actionTier:a==="domain-behavior"||a==="mixed"?"signal":"support",evidenceClass:a,reasons:[...t,...i,...n].slice(0,6),recommendation:e.recommendation(a)}}function ul(e,t){if(e.size===0||t.size===0)return 0;let r=jt(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(ai(e,t),r)}function ci(e,t){let n=Object.fromEntries(e.map(i=>[i.name,i.count]));for(let i of t)if(Object.entries(i.min).every(([o,s])=>(n[o]??0)>=s))return{pass:!0,reason:i.reason,counts:n};return{pass:!1,reason:"shared tokens did not meet calibrated overlap thresholds",counts:n}}function dl(e,t,n){let i=t.map(l=>{let c=l.value(e),u=l.weightedValue?l.weightedValue(e,c):c;return{axis:l,value:c,weighted:u,qualifies:l.qualifies?l.qualifies(e,c):c>0}}),r=i.filter(l=>l.qualifies&&l.axis.reason).map(l=>l.axis.reason(e,l.value)),o=i.filter(l=>l.qualifies&&l.axis.dominantEligible!==!1).sort((l,c)=>c.weighted-l.weighted)[0],s=o&&o.weighted>0?o.axis.axis:n,a=[...new Set(i.filter(l=>l.qualifies).map(l=>l.axis.axis).concat(r.length>0?[]:[s]))];return{dominantPressure:s,pressureKinds:a,reasons:r}}function Ee(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function ct(e){return[...e].sort()}function sO(e,t,n,i,r,o){let s=[],a=[];for(let l of e)aO(l,i).filter(u=>!n.has(u)).length>0?s.push(l):a.push(l);s.length&&r.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 aO(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 i of t)n=n.replace(i,"");return n.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function oC(e,t,n){return e==="generic"?t:n}function Xo(e,t={}){let{minSimilarity:n=.62,minTokens:i=8,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:l}=t,c=_t(e).reactProfiles({scope:o,minJsxTokens:i,scanLimit:s}).filter(d=>d.kind==="component").map(d=>({file:d.file,component:d.name,tokens:d.jsxTokens,profile:d})),u=pn(c,d=>d.tokens);return gn({profiles:c,limit:r,filePattern:a,focusFiles:l,candidateIndex:u,profile:{name:"react-component-duplicates"},compare:(d,m)=>lO(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 lO(e,t,n){let i=jt(e.tokens,t.tokens);if(i.size<6||!cO(i))return null;let r=ai(e.tokens,t.tokens);if(r<n)return null;let o=Ee(i,"component:"),s=Ee(i,"native:"),a=Ee(i,"prop:"),l=Ee(i,"event:"),c=Ee(i,"binding:"),u=uO({sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:l,sharedBindings:c});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:r,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:ct(i),sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:l,sharedBindings:c,evidenceClass:u.evidenceClass,actionTier:u.actionTier,evidenceClassReasons:u.reasons,recommendation:u.recommendation,uniqueToA:ct(nt(e.tokens,t.tokens)).slice(0,25),uniqueToB:ct(nt(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function cO(e){let t=0,n=0;for(let i of e)i.startsWith("component:")&&(t+=1),(i.startsWith("prop:")||i.startsWith("event:")||i.startsWith("native:")||i.startsWith("jsx:"))&&(n+=1);return ci([{name:"component",count:t},{name:"shape",count:n}],[{min:{component:1},reason:"shared custom component"},{min:{shape:4},reason:"shared JSX structure"}]).pass}function uO(e){return li({genericWords:mO,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:dO})}function dO(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 mO=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 Qo(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:i=6,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:l}=t,c=_t(e).reactProfiles({scope:o,minBehaviorTokens:Math.max(3,i),scanLimit:s}).map(d=>({file:d.file,component:d.name,tokens:d.behaviorTokens,profile:d})),u=pn(c,d=>d.tokens);return gn({profiles:c,limit:r,filePattern:a,focusFiles:l,candidateIndex:u,profile:{name:"react-hook-candidates"},compare:(d,m)=>fO(d,m,n,i),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 fO(e,t,n,i){let r=jt(e.tokens,t.tokens);if(r.size<i||!hO(r))return null;let o=ul(e.tokens,t.tokens);if(o<n)return null;let s=Ee(r,"hook:"),a=Ee(r,"react-hook:"),l=Ee(r,"effect:"),c=Ee(r,"state:"),u=Ee(r,"request:"),d=Ee(r,"handler:"),m=Ee(r,"handler-verb:"),f=pO({sharedHooks:s,sharedReactHooks:a,sharedEffects:l,sharedState:c,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:ct(r),sharedHooks:s,sharedReactHooks:a,sharedEffects:l,sharedState:c,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m,evidenceClass:f.evidenceClass,actionTier:f.actionTier,evidenceClassReasons:f.reasons,recommendation:f.recommendation,uniqueToA:ct(nt(e.tokens,t.tokens)).slice(0,25),uniqueToB:ct(nt(t.tokens,e.tokens)).slice(0,25),reason:yO({sharedHooks:s,sharedReactHooks:a,sharedEffects:l,sharedState:c,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m}),locA:e.profile.loc,locB:t.profile.loc}}function pO(e){return li({genericWords:bO,stripPrefixes:SO,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:gO})}function gO(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 hO(e){let t=0,n=0,i=0,r=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:")?i+=1:u.startsWith("request:")?r+=1:u.startsWith("handler:")||u.startsWith("handler-verb:")?o+=1:u.startsWith("state:")?s+=1:u.startsWith("state-hook:")&&(a+=1);let l=s+a,c=t+n+i+r+o+l;return ci([{name:"requests",count:r},{name:"customHooks",count:t},{name:"namedStates",count:s},{name:"handlers",count:o},{name:"effects",count:i},{name:"reactHooks",count:n},{name:"namedBehavior",count:c}],[{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 yO(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 bO=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"]),SO=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function kd(e,t={}){let{minComponentLines:n=300,minFileLines:i=800,minJsxTokens:r=80,minBehaviorTokens:o=40,limit:s=20,scope:a,scanLimit:l,filePattern:c}=t;return _t(e).reactProfiles({scope:a,scanLimit:l}).filter(d=>d.kind==="component").filter(d=>!c||d.file.includes(c)||d.name.includes(c)).map(d=>vO(d,{minComponentLines:n,minFileLines:i,minJsxTokens:r,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 vO(e,t){let n=Math.max(80,Math.floor(t.minComponentLines/2)),i=dl(e,CO({minComponentLines:t.minComponentLines,minFileLines:t.minFileLines,minJsxTokens:t.minJsxTokens,minBehaviorTokens:t.minBehaviorTokens,substantialComponentLines:n}),"component"),{reasons:r}=i;if(r.length===0)return null;let o=i.dominantPressure,s=i.pressureKinds,a=xO(e),l=RO(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:l,recommendation:IO(l,a),reasons:r,loc:e.loc}}function CO(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 xO(e){let t=e.file.split(/[\\/]+/).filter(Boolean),n=t.slice(0,-1).map(m=>m.toLowerCase()),i=(t.at(-1)??e.name).replace(/\.[^.]+$/,""),o=n.findIndex(m=>wO.has(m))>=0,s=n.some(m=>EO.has(m));if(sC(i)||sC(e.name))return"component";let l=LO.has(i.toLowerCase()),c=/(?:Page|Route|Screen)$/.test(e.name),u=o&&/View$/.test(e.name),d=!s&&i.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()===e.name.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()&&/(?:Page|Route|Screen|View)$/.test(i);return l||c||u||d?"route-page":"component"}function sC(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&aC.has(t.at(-1))?!0:[...aC].some(n=>e.endsWith(DO(n)))}function RO(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 IO(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 EO=new Set(["component","components","panel","panels","partial","partials"]),aC=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"]),wO=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),LO=new Set(["page","route","screen"]);function DO(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Zo(e,t={}){let{minSimilarity:n=.62,minTokens:i=8,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:l}=t,c=MO(e,{scope:o,minTokens:i,scanLimit:s}),u=pn(c,d=>d.tokens);return gn({profiles:c,limit:r,filePattern:a,focusFiles:l,candidateIndex:u,profile:{name:"vue-component-duplicates"},compare:(d,m)=>TO(d,m,n),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function MO(e,t){return _t(e).vueProfiles({scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:PO(n)}))}function PO(e){return e.totalLines}function TO(e,t,n){let i=jt(e.tokens,t.tokens);if(i.size<6||!FO(i))return null;let r=ai(e.tokens,t.tokens);if(r<n)return null;let o=Ee(i,"component:"),s=Ee(i,"prop:"),a=Ee(i,"event:"),l=Ee(i,"directive:"),c=Ee(i,"slot:"),u=Ee(i,"id:"),d=kO({sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:l,sharedSlots:c,sharedIdentifiers:u});return{fileA:e.file,fileB:t.file,similarity:r,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:ct(i),sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:l,sharedSlots:c,sharedIdentifiers:u,evidenceClass:d.evidenceClass,actionTier:d.actionTier,evidenceClassReasons:d.reasons,recommendation:d.recommendation,uniqueToA:ct(nt(e.tokens,t.tokens)).slice(0,25),uniqueToB:ct(nt(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function FO(e){let t=0,n=0;for(let i of e)i.startsWith("component:")&&(t+=1),(i.startsWith("prop:")||i.startsWith("event:")||i.startsWith("directive:")||i.startsWith("slot:"))&&(n+=1);return ci([{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 kO(e){return li({genericWords:AO,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:NO})}function NO(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 AO=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 es(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:i=6,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:l}=t,c=_t(e).vueProfiles({scope:o,minBehaviorTokens:Math.max(3,i),scanLimit:s}).map(d=>({file:d.file,tokens:d.behaviorTokens,profile:d})),u=pn(c,d=>d.tokens);return gn({profiles:c,limit:r,filePattern:a,focusFiles:l,candidateIndex:u,profile:{name:"vue-composable-candidates"},compare:(d,m)=>_O(d,m,n,i),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function _O(e,t,n,i){let r=jt(e.tokens,t.tokens);if(r.size<i||!$O(r))return null;let o=ul(e.tokens,t.tokens);if(o<n)return null;let s=Ee(r,"composable:"),a=Ee(r,"store:"),l=Ee(r,"reactivity:"),c=Ee(r,"lifecycle:"),u=Ee(r,"request:"),d=Ee(r,"function:"),m=Ee(r,"function-verb:"),f=Ee(r,"template-binding:"),p=Ee(r,"template-event:"),g=BO({sharedComposables:s,sharedStores:a,sharedReactivity:l,sharedLifecycle:c,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f,sharedTemplateEvents:p});return{fileA:e.file,fileB:t.file,similarity:o,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:ct(r),sharedComposables:s,sharedStores:a,sharedReactivity:l,sharedLifecycle:c,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f,sharedTemplateEvents:p,evidenceClass:g.evidenceClass,actionTier:g.actionTier,evidenceClassReasons:g.reasons,recommendation:g.recommendation,uniqueToA:ct(nt(e.tokens,t.tokens)).slice(0,25),uniqueToB:ct(nt(t.tokens,e.tokens)).slice(0,25),reason:jO({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:c,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function BO(e){return li({genericWords:HO,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:OO})}function OO(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 $O(e){let t=0,n=0,i=0,r=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:")?i+=1:u.startsWith("lifecycle:")?r+=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 l=t+n,c=l+i+r+o+a;return ci([{name:"requests",count:i},{name:"lifecycle",count:r},{name:"functions",count:o},{name:"reusableHooks",count:l},{name:"reactivity",count:s},{name:"namedBehavior",count:c}],[{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 jO(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 HO=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 Nd(e,t={}){let{minTotalLines:n=800,minTemplateLines:i=300,minScriptLines:r=300,minStyleLines:o=500,limit:s=20,scope:a,scanLimit:l,filePattern:c}=t;return _t(e).vueProfiles({scope:a,scanLimit:l}).filter(d=>!c||d.file.includes(c)).map(d=>UO(d,{minTotalLines:n,minTemplateLines:i,minScriptLines:r,minStyleLines:o})).filter(d=>d!==null).sort((d,m)=>m.totalLines-d.totalLines||d.file.localeCompare(m.file)).slice(0,s)}function UO(e,t){let n=dl(e,zO(t),"total"),{reasons:i}=n;if(i.length===0)return null;let r=n.dominantPressure,o=n.pressureKinds.includes("total")?[...new Set([...n.pressureKinds,r])]:n.pressureKinds,s=qO(e.file),a=KO(r,s),l=e.totalLines+e.delegatedComposableLines;return{file:e.file,totalLines:l,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:r,pressureKinds:o,contextKind:s,recommendationKind:a,recommendation:GO(a,s),reasons:i,loc:l}}function zO(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 qO(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(i=>WO.has(i))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function KO(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 GO(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 WO=new Set(["landing","page","pages","route","routes","view","views"]);function VO(e,t={}){let{minSimilarity:n=.5,limit:i=15,scope:r,minChainLength:o=3,maxChainLength:s=8}=t,a=$e(e,r),l=n$(a,o,s);if(l.length===0)return[];let c=JO(l);return c.length<2?[]:t$(QO(c,n,i),i)}function JO(e){let t=YO(e),n=[];for(let i of e){let r=i.filter(o=>!t.has(o));r.length>=2&&n.push({original:i,filtered:r})}return n}function YO(e){let{nodeFreq:t,tailFreq:n}=XO(e),i=e.length*.9,r=e.length*.8,o=new Set;for(let[a,l]of t)l>i&&o.add(a);for(let[a,l]of n)l>r&&o.add(a);let s=["index.ts","index.js","cli.ts","main.ts","health.ts","health.js"];for(let a of t.keys()){let l=a.split("/").pop()??"";s.includes(l)&&o.add(a)}return o}function XO(e){let t=new Map,n=new Map;for(let i of e){let r=new Set;for(let o of i)r.has(o)||(t.set(o,(t.get(o)??0)+1),r.add(o));for(let o=Math.max(0,i.length-2);o<i.length;o++)n.set(i[o],(n.get(i[o])??0)+1)}return{nodeFreq:t,tailFreq:n}}function QO(e,t,n){let i=[];for(let r=0;r<e.length;r++){for(let o=r+1;o<e.length;o++){let s=ZO(e[r],e[o],t);s&&i.push(s)}if(i.length>n*10)break}return i.sort((r,o)=>Math.abs(o.similarity-r.similarity)>.01?o.similarity-r.similarity:r.divergencePoints.length-o.divergencePoints.length),i}function ZO(e,t,n){if(!e$(e.filtered,t.filtered))return null;let{distance:i,ops:r}=i$(e.filtered,t.filtered),o=Math.max(e.filtered.length,t.filtered.length);if(o===0)return null;let s=1-i/o;if(s<n||i===0)return null;let a=r.filter(c=>c.type==="substitute").map(c=>({index:c.indexA,nodeA:e.filtered[c.indexA],nodeB:t.filtered[c.indexB]}));return a.length===0||r.filter(c=>c.type==="match").length<2?null:{chainA:e.original,chainB:t.original,similarity:s,editDistance:i,divergencePoints:a,commonPrefix:r$(e.original,t.original),commonSuffix:o$(e.original,t.original)}}function e$(e,t){let n=new Set(e);return t.some(i=>n.has(i))}function t$(e,t){let n=[];for(let i of e)if(n.some(o=>lC(i.chainA,o.chainA)&&lC(i.chainB,o.chainB))||n.push(i),n.length>=t)break;return n}function n$(e,t,n){let i=[];for(let o of e.keys()){if(i.length>=500)break;cC(e,o,[o],new Set([o]),t,n,i,500)}return i}function cC(e,t,n,i,r,o,s,a){if(s.length>=a)return;if(n.length>=o){n.length>=r&&s.push([...n]);return}let l=e.get(t);if(!l||l.size===0){n.length>=r&&s.push([...n]);return}let c=!1;for(let u of l)if(!i.has(u)&&(i.add(u),n.push(u),cC(e,u,n,i,r,o,s,a),n.pop(),i.delete(u),c=!0,s.length>=a))return;!c&&n.length>=r&&s.push([...n])}function i$(e,t){let n=e.length,i=t.length,r=Array.from({length:n+1},()=>Array(i+1).fill(0));for(let l=0;l<=n;l++)r[l][0]=l;for(let l=0;l<=i;l++)r[0][l]=l;for(let l=1;l<=n;l++)for(let c=1;c<=i;c++)e[l-1]===t[c-1]?r[l][c]=r[l-1][c-1]:r[l][c]=1+Math.min(r[l-1][c],r[l][c-1],r[l-1][c-1]);let o=[],s=n,a=i;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&&r[s][a]===r[s-1][a-1]+1?(o.unshift({type:"substitute",indexA:s-1,indexB:a-1}),s--,a--):a>0&&r[s][a]===r[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:r[n][i],ops:o}}function r$(e,t){let n=[];for(let i=0;i<Math.min(e.length,t.length)&&e[i]===t[i];i++)n.push(e[i]);return n}function o$(e,t){let n=[],i=e.length-1,r=t.length-1;for(;i>=0&&r>=0&&e[i]===t[r];)n.unshift(e[i]),i--,r--;return n}function lC(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),i=e.join("\u2192");return n.includes(i)}function Ht(e){let t=s$(e.profile?.name),n=()=>{let i=e.candidates(),r=e.filterCandidate?i.filter(e.filterCandidate):i,o=e.orderCandidates?[...r].sort(e.orderCandidates):r,s=ke(o,e.scanLimit);t={pipeline:e.profile?.name,loadedCandidates:i.length,filteredCandidates:r.length,scannedCandidates:s.length,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:s.length<r.length,resultLimitApplied:!1};let a=e.prepare?.(s)??void 0,l=[];for(let u of s){t.evaluatedCandidates+=1;let d=e.evaluate(u,a);d&&l.push(d)}t.matchedResults=l.length,e.orderResults&&l.sort(e.orderResults);let c=typeof e.limit=="number"?l.slice(0,e.limit):l;return t.emittedResults=c.length,t.resultLimitApplied=c.length<l.length,e.onProfile?.({...t}),c};return e.profile?B(`candidate-pipeline:${e.profile.name}`,n,()=>({...a$(e.profile?.metadata),...t})):n()}function s$(e){return{pipeline:e,loadedCandidates:0,filteredCandidates:0,scannedCandidates:0,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:!1,resultLimitApplied:!1}}function a$(e){return typeof e=="function"?e():e??{}}function ts(e,t={}){let{scope:n,minLoc:i=10,minCallees:r=6,limit:o=20,scanLimit:s}=t,a=new U(e);return Ht({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:i,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:s,profile:{name:"extract-candidates"},prepare:l=>a.calleeEvidenceMap(l,{semantic:t.semantic!==!1}),evaluate:(l,c)=>c.incompleteSymbolIds.has(l.symbolId)||c.unavailableSymbolIds.has(l.symbolId)?null:l$(l,c.rows.get(l.symbolId)??[],r),orderResults:(l,c)=>c.clusters.length-l.clusters.length||c.loc-l.loc,limit:o})}function l$(e,t,n){let i=new Set(t.map(c=>c.symbol));if(i.size<n)return null;let r=f$(i,t),o=p$(i,r);if(o.length<2)return null;let s=g$(o,r);if(s.length===0)return null;let a=A(e.symbol),l=c$(a,i.size,o.length,s);return{symbol:e.symbol,shortName:a,relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:de(e),totalCallees:i.size,extractionKind:l.extractionKind,actionTier:"signal",evidenceReasons:l.evidenceReasons,recommendation:l.recommendation,clusters:s}}function c$(e,t,n,i){let r=Math.max(...i.map(l=>l.callees.length)),o=Math.max(...i.map(l=>l.isolation)),s=[`${t} distinct callees across ${n} co-occurrence cluster(s)`,`${i.length} extractable cluster(s) passed size and isolation thresholds`,`largest extractable cluster has ${r} callees at ${Math.round(o*100)}% isolation`],a=u$(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."}:r>=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 u$(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 i=d$(e);return m$.has(i)?`caller verb suggests orchestration: ${i}`:null}function d$(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 m$=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function f$(e,t){let n=new Map;for(let r of e)n.set(r,new Set);let i=new Map;for(let r of t){let o=i.get(r.chunkId);o||(o=new Set,i.set(r.chunkId,o)),o.add(r.symbol)}for(let r of i.values()){let o=[...r];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 p$(e,t){let n=new Set,i=[];for(let r of e){if(n.has(r))continue;let o=new Set,s=[r];for(;s.length>0;){let a=s.pop();if(!n.has(a)){n.add(a),o.add(a);for(let l of t.get(a)??[])n.has(l)||s.push(l)}}i.push(o)}return i}function g$(e,t){return e.filter(n=>n.size>=3).map(n=>h$(n,e,t)).filter(n=>n.isolation>.5).sort((n,i)=>i.isolation-n.isolation)}function h$(e,t,n){let i=new Set;for(let a of t)if(a!==e)for(let l of a)i.add(l);let r=0;for(let a of e)for(let l of n.get(a)??[])i.has(l)&&r++;let o=e.size*i.size,s=o>0?1-r/o:1;return{callees:[...e].map(A),isolation:s}}import{posix as Pr}from"path";import{spawnSync as y$}from"child_process";import{createHash as b$}from"crypto";import{existsSync as S$}from"fs";import{dirname as uC,join as v$}from"path";import{fileURLToPath as C$}from"url";var fC=Hn("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]}),dC=Ct({kind:"consumer-file-usage",invalidation:Ye("consumer-file-usage"),serialize:T$,deserialize:F$});function hn(e,t){return{forDefinitions(n,i){return x$(e,t,n,i)}}}function ui(e){let t=new Map;for(let[n,i]of e)t.set(n,new Set(i.files.map(r=>r.file)));return t}function fl(e,t,n){return gC(e,t,n).partition}function x$(e,t,n,i){let r=pC(n.length),o=Ae()?Cn(e):null,s=o?R$(n,i,o):void 0,a=s?{workIdentity:s,workOutcome:"computed"}:{};return B("consumer-evidence.product",()=>{let l=B("consumer-evidence.provenance",()=>I$(e,t,n,i),()=>({...a,definitions:n.length,semantic:i.semantic,sourceFallback:i.sourceFallback!==!1})),c=new Map;r={...r,...l.counters};let u=E$(n,l.sources);return B("consumer-evidence.classify",()=>{let d=w$(e,n,l.sources,u);for(let m of n){let f=d.get(m.symbolId)??D$();r.realFiles+=f.partition.realConsumers.length,r.reexportOnlyFiles+=f.partition.barrelConsumers,r.importOnlyFiles+=f.partition.importOnlyConsumers,c.set(m.symbolId,{definition:m,files:f.files,semanticIncomplete:l.incompleteSymbolIds.has(m.symbolId),semanticUnavailable:l.unavailableSymbolIds.has(m.symbolId),...f.partition})}},()=>({...a,...u,realFiles:r.realFiles,reexportOnlyFiles:r.reexportOnlyFiles,importOnlyFiles:r.importOnlyFiles})),c},()=>({...a,...r}))}function R$(e,t,n){let i=b$("sha256").update("consumer-evidence-v3-calibrated-semantic\0").update(n).update("\0").update(t.semantic?"semantic\0":"indexed\0").update(t.sourceFallback===!1?"no-source-fallback":"source-fallback");for(let r of e.map(o=>o.symbol).sort())i.update("\0").update(r);return i.digest("hex").slice(0,24)}function pC(e){return{definitions:e,indexedFiles:0,semanticFiles:0,fallbackFiles:0,totalFiles:0,realFiles:0,reexportOnlyFiles:0,importOnlyFiles:0}}function I$(e,t,n,i){let r=pC(n.length),o=new Map,s=new Set,a=new Set;if(Ad(o,r,"indexed",t.crossFileCallerMap(n,{semantic:!1})),i.semantic){let l=Ln(e,n);Ad(o,r,"semantic",l.callers);for(let c of l.incompleteSymbolIds)s.add(c);for(let c of l.unavailableSymbolIds)a.add(c)}return i.sourceFallback!==!1&&Ad(o,r,"source-fallback",t.sourceFallbackCallerFiles(n)),r.totalFiles=[...o.values()].reduce((l,c)=>l+c.size,0),{sources:o,counters:r,incompleteSymbolIds:s,unavailableSymbolIds:a}}function E$(e,t){return{definitions:e.length,consumerFiles:[...t.values()].reduce((n,i)=>n+i.size,0),nativeAttempted:!1,nativeUsed:!1,nativeReason:"not-attempted"}}function Ad(e,t,n,i){let r=0;for(let[o,s]of i){let a=e.get(o);a||(a=new Map,e.set(o,a));for(let l of s){r++;let c=a.get(l)??new Set;c.add(n),a.set(l,c)}}n==="indexed"?t.indexedFiles+=r:n==="semantic"?t.semanticFiles+=r:t.fallbackFiles+=r}function w$(e,t,n,i){let r=$$(e,t,n,i);return r||L$(e,t,n)}function L$(e,t,n){let i=new Map;for(let r of t){let o=n.get(r.symbolId)??new Map;i.set(r.symbolId,gC(e,r,[...o.keys()],o))}return i}function gC(e,t,n,i=new Map){let r=[],o=0,s=0,a=Y(t.symbol),l=[];for(let c of n){let u;k$(e,c,t.relativePath,a)?(o++,u="reexport-only"):_d(e,c,a)?(s++,u="import-only"):(r.push(c),u="real"),l.push({file:c,sources:[...i.get(c)??[]],classification:u})}return{partition:{realConsumers:r,barrelConsumers:o,importOnlyConsumers:s},files:l}}function D$(){return{partition:{realConsumers:[],barrelConsumers:0,importOnlyConsumers:0},files:[]}}function _d(e,t,n){if(!n)return!1;let i=ye(t);if(!i)return!1;let r=fC.get(e,t,()=>hC(e,t,i));return r.importedLeaves.has(n)&&!r.usedLeaves.has(n)}function hC(e,t,n){let i=Un(e).forFile(t,{text:!0,ast:!0}),r=i.text;if(!r)return P$();let o=Nt(e,t,r),s=dC.read(e,t,o);if(s)return s;let a=M$(i.ast,n);return dC.write(e,t,o,a),a}function M$(e,t){let n=new Set,i=new Set;if(!e)return{importedLeaves:n,usedLeaves:i};let r=t==="rust"?new Set(["use_declaration"]):t==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),o=(s,a)=>{let l=a||r.has(s.type);(s.type==="identifier"||s.type==="type_identifier"||s.type==="property_identifier"||s.type==="field_identifier")&&(l?n.add(s.text):i.add(s.text));for(let c of s.children)o(c,l)};return o(e.rootNode,!1),{importedLeaves:n,usedLeaves:i}}function P$(){return{importedLeaves:new Set,usedLeaves:new Set}}function T$(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function F$(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 k$(e,t,n,i){if(!i)return!1;let r=Un(e).forFile(t,{lines:!0,reexports:!0}),o=r.lines??[];if(o.length===0)return!1;let s=r.reexports??[];return yC(o,s,i)}function yC(e,t,n){if(e.length===0||t.length===0)return!1;let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`\\b${i}\\b`),o=0;for(let s=0;s<e.length;s++){if(!r.test(e[s]??""))continue;if(o++,!t.find(l=>l.startLine<=s&&s<=l.endLine))return!1}return o>0}var N$="CODEBASEIQ_NATIVE_CONSUMER_CLASSIFY",A$="CODEBASEIQ_NATIVE_KERNELS_BIN",_$="CODEBASEIQ_NATIVE_CONSUMER_CLASSIFY_MIN_FILES",mC=1e3,B$=5e3,O$=64*1024*1024,ml;function $$(e,t,n,i){let r=process.env[N$]?.toLowerCase();if(r!=="1"&&r!=="true")return i.nativeReason=r==="0"||r==="false"?"disabled":"opt-in-required",null;if(i.consumerFiles<G$())return i.nativeReason="below-threshold",null;let o=W$();if(!o)return i.nativeReason="binary-missing",null;i.nativeAttempted=!0;let s=j$(e,t,n),a=y$(o,["consumer-classify"],{input:JSON.stringify(s),encoding:"utf8",timeout:B$,maxBuffer:O$,windowsHide:!0});if(a.status!==0||a.error)return i.nativeReason=a.error?`spawn-error:${a.error.message}`:`exit-${a.status??"null"}`,null;try{let l=JSON.parse(a.stdout),c=U$(l,t);return c?(i.nativeUsed=!0,i.nativeReason="used",c):(i.nativeReason="invalid-response",null)}catch{return i.nativeReason="invalid-json",null}}function j$(e,t,n){let i=new Map,r=[];for(let a of t){let l=Y(a.symbol),u=[...(n.get(a.symbolId)??new Map).entries()].map(([d,m])=>{let f=i.get(d)??new Set;return l&&f.add(l),i.set(d,f),{file:d,sources:[...m]}});r.push({symbol_id:a.symbolId,leaf:l,consumer_files:u})}let o={},s={};for(let[a,l]of i){let c=ye(a);if(c){let d=fC.get(e,a,()=>hC(e,a,c));o[a]={imported_leaves:[...d.importedLeaves],used_leaves:[...d.usedLeaves]}}let u=H$(e,a,l);u.length>0&&(s[a]=u)}return{definitions:r,file_usages:o,reexport_only_leaves:s}}function H$(e,t,n){if(n.size===0)return[];let i=Un(e).forFile(t,{lines:!0,reexports:!0}),r=i.lines??[],o=i.reexports??[];return r.length===0||o.length===0?[]:[...n].filter(s=>yC(r,o,s))}function U$(e,t){if(!Array.isArray(e.entries)||e.entries.length!==t.length)return null;let n=new Set(t.map(r=>r.symbolId)),i=new Map;for(let r of e.entries){let o=z$(r);if(!o||!n.has(o.symbol_id))return null;i.set(o.symbol_id,{partition:{realConsumers:o.real_consumers,barrelConsumers:o.barrel_consumers,importOnlyConsumers:o.import_only_consumers},files:o.files})}for(let r of n)if(!i.has(r))return null;return i}function z$(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(i=>typeof i=="string"))return null;let n=[];for(let i of t.files){if(!i||typeof i!="object")return null;let r=i;if(typeof r.file!="string"||!Array.isArray(r.sources)||!r.sources.every(q$)||!K$(r.classification))return null;n.push({file:r.file,sources:r.sources,classification:r.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 q$(e){return e==="indexed"||e==="semantic"||e==="source-fallback"}function K$(e){return e==="real"||e==="reexport-only"||e==="import-only"}function G$(){let e=process.env[_$];if(!e)return mC;let t=Number(e);return Number.isFinite(t)&&t>=0?t:mC}function W$(){if(ml!==void 0)return ml;let e=process.env[A$],t=process.platform==="win32"?"codebaseiq-kernels.exe":"codebaseiq-kernels";return ml=[...e?[e]:[],...V$().map(i=>v$(i,"target","release",t))].find(i=>S$(i))??null,ml}function V$(){let e=new Set,t=uC(C$(import.meta.url));for(let n=0;n<5;n++)e.add(t),t=uC(t);return[...e]}var J$=20,Y$=1,X$=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"]]),Q$=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),Z$=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 e1(e,t={}){let n=$d(t.limit,J$),i=$d(t.minConsumers,Y$),r=new U(e),o=r.fileDependencyGraph(t.scope),s=v1(me(e,{includeIgnored:!1})),a=R1(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?t1(e,r,t.target):n1(e,t.scope,t.scanLimit)).map(u=>i1(e,r,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=i||t.target).sort(S1).slice(0,n)}function t1(e,t,n){let i=s1(e,n);if(i)return[xC(i)];let r=pe(e,n);if(!r)return[];let o=t.definitionsForFile(r.relativePath).find(s=>s.symbolId===r.symbolId);return o?[a1(o)]:[{unit:{kind:"symbol",file:r.relativePath,shortName:A(r.symbol),symbol:r.symbol,startLine:r.startLine,endLine:r.endLine}}]}function n1(e,t,n){let i=me(e,{scope:t,includeIgnored:!1}),r=$d(n,i.length);return i.slice(0,r).map(o=>xC(o))}function i1(e,t,n,i,r,o,s){let a=i.definition?r1(e,t,i.definition,r.semantic):null,l=a?.files??o1(n,i.unit.file),c=i.definition?a.coverage==="complete"?l.length>0?"exact":"none":a.coverage:l.length>0?"file-level":"none",u=c==="incomplete"||c==="unavailable"||c==="incomplete-and-unavailable",d=i.unit.file,m=Yt(Pr.dirname(d)),f=c1(l),p=l1(m),g=Hd([...bC(m),...f?bC(f):[]]),h=u?"repository-level-review":u1(i.unit,m,f,l),b=u?{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:`Compiler-resolved consumer evidence is ${c}; no relocation destination is safe to score.`}:d1(h,i.unit,m,f,l,o,s),v=h1(i.unit,c,f,l,m,b.whyNoSuggestedHome),y=y1(i.unit,m,f,l,b.suggestedHome,b.whyNoSuggestedHome);return{actionTier:"signal",sourceUnit:i.unit,candidatePath:d,currentDirectory:m,directoryAncestry:p,consumerFiles:l,consumerCoverage:c,nearestCommonOwner:f,boundaryMarkers:g,recommendedTier:h,suggestedHome:b.suggestedHome,destinationConfidence:b.confidence,whyNoSuggestedHome:b.whyNoSuggestedHome,counterevidence:u?[...v,"Known consumer files are retained, but missing compiler evidence can hide additional owners."]:v,reasons:y,recommendation:u?"Retain the current location until compiler-resolved consumer evidence is complete.":b1(h,b.suggestedHome,c)}}function r1(e,t,n,i){let r=hn(e,t).forDefinitions([n],{semantic:i!==!1,sourceFallback:!0}).get(n.symbolId),o=r?.semanticIncomplete?r.semanticUnavailable?"incomplete-and-unavailable":"incomplete":r?.semanticUnavailable?"unavailable":"complete";return{files:LC(r?.files.map(s=>s.file)??[]),coverage:o}}function o1(e,t){let n=[];for(let[i,r]of e.entries())i!==t&&r.has(t)&&n.push(i);return LC(n)}function s1(e,t){let n=Ss(t),i=me(e,{includeIgnored:!1}),r=i.find(s=>s===n);if(r)return r;let o=i.find(s=>s.endsWith(`/${n}`));return o||(i.find(s=>s.includes(n))??null)}function a1(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:A(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function xC(e){return{unit:{kind:"file",file:e,shortName:Pr.basename(e)}}}function l1(e){if(e===".")return[{path:".",depth:0,markers:[]}];let t=[],n=e.split("/").filter(Boolean);for(let i=0;i<n.length;i+=1){let r=n.slice(0,i+1).join("/");t.push({path:r,depth:i,markers:jd(r)})}return t}function bC(e){return e==="."?[]:RC(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function jd(e){return Hd(RC(e).map(({marker:t})=>t))}function RC(e){let t=e.split("/").filter(Boolean),n=[];for(let i=0;i<t.length;i+=1){let r=X$.get(t[i]);r&&n.push({marker:r,prefix:t.slice(0,i+1).join("/")})}return n}function c1(e){if(e.length===0)return null;let t=e.map(i=>Yt(Pr.dirname(i))),n=t[0].split("/").filter(Boolean);for(let i of t.slice(1)){let r=i.split("/").filter(Boolean),o=[],s=Math.min(n.length,r.length);for(let a=0;a<s&&n[a]===r[a];a+=1)o.push(n[a]);n=o}return n.length===0?".":n.join("/")}function u1(e,t,n,i){return n?e.kind==="symbol"&&i.length===1?i[0]===e.file?"same-file":"sibling-folder":n==="."||n==="src"?"repository-level-review":vC(n,"package")?"package-level-shared":vC(n,"app")?"app-level-shared":CC(n,["feature","domain","module"])||CC(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function d1(e,t,n,i,r,o,s){let a=m1(e,i);if(a)return di(a);let l=C1(t.file),c=f1(e,n,l,r,s);if(c)return c;let u=i;if(Yt(n)===Yt(u))return di(`${n} is already the nearest common owner for its consumers.`);let d=p1(u,n,l,s);return d||g1(u,n,l,o,s)}function m1(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 f1(e,t,n,i,r){if(e==="same-file"){let o=i[0]??null;return o?Bd(o):di("No same-file consumer path was available.")}if(e==="sibling-folder"&&i.length===1){let o=Yt(Pr.dirname(i[0])),s=wC(t,n,o,r);return s?di(s):Bd(o)}return null}function p1(e,t,n,i){return E1(e)?IC(e,t,n,i,`Nearest shared owner ${e} is outside source root ${n}.`):null}function g1(e,t,n,i,r){if(e===".")return di("The nearest common owner is the repository root.");let o=`${e}/shared`,s=IC(o,t,n,r,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||i.has(o)?s:di(`${o} does not exist in the indexed project.`)}function IC(e,t,n,i,r){if(!EC(e,n))return di(r);let o=wC(t,n,e,i);return o?di(o):Bd(e)}function Bd(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function di(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function h1(e,t,n,i,r,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."),i.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&&r.startsWith(`${n}/`)&&s.push("Candidate already lives under the nearest common owner."),o&&s.push(`No exact suggested home: ${o}`),s}function y1(e,t,n,i,r,o){let s=[];return s.push(`${e.shortName} currently lives in ${t}.`),n?s.push(`${i.length} consumer file(s) share ${n} as their nearest common owner.`):s.push("No consumer owner could be inferred from the current index."),r?s.push(`Suggested home is ${r}.`):o&&s.push(`No exact suggested home: ${o}`),s}function b1(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 S1(e,t){return SC(t)-SC(e)||e.candidatePath.localeCompare(t.candidatePath)}function SC(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 v1(e){let t=new Set(["."]);for(let n of e){let i=Yt(Pr.dirname(n));for(;!t.has(i)&&(t.add(i),i!==".");)i=Yt(Pr.dirname(i))}return t}function C1(e){let t=Od(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function EC(e,t){let n=Yt(e),i=Yt(t);return i==="."||n===i||n.startsWith(`${i}/`)}function x1(e,t,n){let i=Od(e),r=Od(t);return(EC(e,t)?i.slice(r.length):i).some(s=>n.has(s.toLowerCase()))}function wC(e,t,n,i){return Yt(e)===Yt(n)||!x1(e,t,i)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function R1(...e){let t=new Set(Z$);for(let n of e)for(let i of n??[]){let r=I1(i);r&&t.add(r)}return t}function I1(e){let t=e.trim().toLowerCase();return t===""?null:t}function vC(e,t){return jd(e).includes(t)}function CC(e,t){let n=jd(e);return t.some(i=>n.includes(i))}function E1(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?Q$.has(n):!1}function Yt(e){let t=Ss(e);return t===""?".":t}function Od(e){let t=Ss(e);return t==="."?[]:t.split("/").filter(Boolean)}function $d(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function LC(e){return Hd([...e]).sort((t,n)=>t.localeCompare(n))}function Hd(e){return[...new Set(e)]}function Ud(e,t,n={}){return w1(e,t,n)}function w1(e,t,n){let{maxDepth:i=5,scope:r}=n,o=i===Number.MAX_SAFE_INTEGER,s=o?null:500,a=pe(e,t);if(!a)return{rows:[],coverage:{status:"incomplete",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:i,reachedDepth:0,perSymbolEvidenceLimit:s,remainingFrontierSymbols:0,reasons:["The requested symbol could not be resolved."],semanticEvidence:"incomplete"}};let l=[],c=new Set([a.symbolId]),u=new Set,d=[a],m=0,f=!1,p=!1,g=!1;for(let v=1;v<=i&&d.length!==0;v++){m=v;let y=[],I=sn(e,d,{...o?{}:{limit:s+1},semanticEvidence:ge});I.incompleteSymbolIds.size>0&&(p=!0),I.unavailableSymbolIds.size>0&&(g=!0);for(let E of d){let S=I.rows.get(E.symbolId)??[];s!==null&&S.length>s&&(f=!0);let x=s===null?S:S.slice(0,s);for(let C of L1(e,E,r,x)){let L=`${C.file}|${C.shortName}`;if(C.symbolId!==null){if(c.has(C.symbolId))continue;c.add(C.symbolId)}else if(u.has(L))continue;u.add(L),l.push({symbol:C.symbol,shortName:C.shortName,file:C.file,depth:v}),C.symbolId!==null&&C.symbolMatch&&y.push(C.symbolMatch)}}d=y}l.sort((v,y)=>v.depth-y.depth||v.file.localeCompare(y.file));let h=d.length>0,b=[];return h&&b.push(`${d.length} symbol(s) remain eligible beyond depth ${i}.`),f&&b.push(`At least one symbol had more than ${s} incoming evidence row(s).`),p&&b.push("Compiler-resolved incoming evidence was incomplete for at least one traversed symbol."),g&&b.push("Compiler-resolved incoming evidence was unavailable for at least one traversed symbol."),b.length===0&&b.push("The discovered reverse evidence frontier was exhausted."),{rows:l,coverage:{status:p||g?"incomplete":h||f?"bounded":"accounted",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:i,reachedDepth:m,perSymbolEvidenceLimit:s,remainingFrontierSymbols:d.length,reasons:b,semanticEvidence:p&&g?"incomplete-and-unavailable":p?"incomplete":g?"unavailable":"complete"}}}function L1(e,t,n,i){let r=i.filter(u=>!e.isIgnored(u.file)).filter(u=>!n||u.file.includes(n)),o=new Set(r.map(u=>u.file)),s=[];for(let u of D1(e,t,n)){if(o.has(u))continue;let d=W(e,u),m=d.length>0?Ke(d,d[0].startLine):null;s.push({symbol:m?.symbol??u,file:u})}let a=[...r,...s],l=[],c=new Set;for(let u of a){let d=Si(e,u.symbol);if(!d){let f=`${u.file}|${u.symbol}`;if(c.has(f))continue;c.add(f),l.push({symbolId:null,symbol:u.symbol,shortName:A(u.symbol),file:u.file,symbolMatch:null});continue}if(d.symbolId===t.symbolId||e.isIgnored(d.relativePath)||!M1(d))continue;let m=`${d.symbolId}|${d.relativePath}`;c.has(m)||(c.add(m),l.push({symbolId:d.symbolId,symbol:d.symbol,shortName:A(d.symbol),file:d.relativePath,symbolMatch:d}))}return l}function D1(e,t,n){let i=n?"AND consumer_d.relative_path LIKE ?":"",r=[t.symbolId,t.documentId];return n&&r.push(`%${n}%`),new Set(e.all(`SELECT DISTINCT consumer_d.relative_path
322
+ `)}function _B(e){return`${e.symbol}\0${e.startLine}\0${e.endLine}\0${e.leaf}`}function BB(e,t,n){return zv.read(e,t,n)??new Map}function OB(e){try{let t=JSON.parse(e);if(!Array.isArray(t.entries))return null;let n=new Map;for(let i of t.entries){if(!i||typeof i.key!="string"||typeof i.symbol!="string"||typeof i.startLine!="number"||typeof i.endLine!="number"||typeof i.leaf!="string"||!Array.isArray(i.tokens)||!i.tokens.every(r=>typeof r=="string"))return null;n.set(i.key,i)}return n}catch{return null}}function $B(e){let t={entries:[...e.values()].sort((n,i)=>n.key.localeCompare(i.key))};return JSON.stringify(t)}function jB(e,t,n,i){zv.write(e,t,n,new Map(i))}function eC(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"]),i=HB(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=>!i.has(s));return new Set(o)}function HB(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 UB(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function pn(e,t){let n=new Map;return e.forEach((i,r)=>{let o=new Set;for(let s of t(i)){if(o.has(s))continue;o.add(s);let a=n.get(s);a?a.push(r):n.set(s,[r])}}),{candidatesFor:(i,r)=>{let o=new Set;for(let s of t(i)){let a=n.get(s);if(a)for(let l of a)l!==r&&o.add(l)}return[...o].sort((s,a)=>s-a)}}}function gn(e){let t=tC(e.profile?.name),n=()=>{let i=[];t=tC(e.profile?.name,e);let r=(s,a)=>{let l=e.profiles[s],c=e.profiles[a];t.candidatePairs+=1,t.comparedPairs+=1;let u=e.compare(l,c);u&&i.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 l of zB(e,s)){let c=e.profiles[l];e.focusFiles&&!e.focusFiles.has(a.file)&&!e.focusFiles.has(c.file)||r(s,l)}}}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 l=e.profiles[a],c=e.focusFiles?.has(l.file)??!1;for(let u of qB(e,a))e.focusFiles&&!c&&!e.focusFiles.has(e.profiles[u].file)||r(a,u);if(i.length>s){t.overrunApplied=!0;break}}}i.sort(e.sort??((s,a)=>a.similarity-s.similarity)),t.matchedResults=i.length;let o=i.slice(0,e.limit);return t.emittedResults=o.length,e.onProfile?.({...t}),o};return e.profile?B(`pairwise-profile:${e.profile.name}`,n,()=>({...KB(e.profile?.metadata),...t})):n()}function zB(e,t){if(e.candidateIndex)return nC(e,t,-1);let n=[];for(let i=0;i<e.profiles.length;i+=1)i!==t&&n.push(i);return n}function qB(e,t){if(e.candidateIndex)return nC(e,t,t);let n=[];for(let i=t+1;i<e.profiles.length;i+=1)n.push(i);return n}function nC(e,t,n){let i=e.profiles[t],r=new Set;for(let o of e.candidateIndex?.candidatesFor(i,t,e.profiles)??[])o<=n||o!==t&&(o<0||o>=e.profiles.length||r.add(o));return[...r].sort((o,s)=>o-s)}function tC(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 KB(e){return typeof e=="function"?e():e??{}}function GB(e,t={}){let{minSimilarity:n=.5,limit:i=20,scope:r,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:l}=WB(e,{scope:r,minDeps:s}),c=pn(a,u=>u.deps);return gn({profiles:a,limit:i,filePattern:o,overrunFactor:5,candidateIndex:c,profile:{name:"similar-files"},compare:(u,d)=>JB(u,d,n,l)})}function WB(e,t){let{scope:n,minDeps:i}=t,r=$e(e,n),{universalDeps:o,distinctiveDeps:s}=VB(r),a=[];for(let[l,c]of r)c.size>=i&&a.push({file:l,deps:new Set([...c].filter(u=>!o.has(u)))});return{profiles:a,distinctiveDeps:s}}function VB(e){let t=new Set,n=new Set,i=e.size;if(i===0)return{universalDeps:t,distinctiveDeps:n};let r=new Map;for(let s of e.values())for(let a of s)r.set(a,(r.get(a)??0)+1);let o=Math.max(3,Math.ceil(i*.03));for(let[s,a]of r)a>=5&&a/i>.3?t.add(s):a<=o&&n.add(s);return{universalDeps:t,distinctiveDeps:n}}function JB(e,t,n,i){let r=new Set;for(let c of e.deps)t.deps.has(c)&&r.add(c);if(r.size<3||e.deps.size<4||t.deps.size<4)return null;let o=0;for(let c of r)i.has(c)&&o++;if(o<2)return null;let s=ai(e.deps,t.deps);if(s<n)return null;let a=[];for(let c of e.deps)t.deps.has(c)||a.push(c);let l=[];for(let c of t.deps)e.deps.has(c)||l.push(c);return{fileA:e.file,fileB:t.file,similarity:s,sharedDeps:[...r],uniqueToA:a,uniqueToB:l}}function li(e){let t=[],n=[],i=[];for(let c of e.primitiveGroups)c.values.length!==0&&iC(c.bucket,n,i).push(`${c.reasonPrefix}: ${c.values.join(", ")}`);for(let c of e.nameGroups)YB(c.names,c.label,e.genericWords,e.stripPrefixes??[],t,iC(c.fallbackBucket,n,i));let r=t.length>0,o=n.length>0,s=i.length>0,a=r?o||s?"mixed":"domain-behavior":s?"shared-abstraction":"generic-workflow-scaffolding";return{actionTier:a==="domain-behavior"||a==="mixed"?"signal":"support",evidenceClass:a,reasons:[...t,...i,...n].slice(0,6),recommendation:e.recommendation(a)}}function cl(e,t){if(e.size===0||t.size===0)return 0;let r=jt(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(ai(e,t),r)}function ci(e,t){let n=Object.fromEntries(e.map(i=>[i.name,i.count]));for(let i of t)if(Object.entries(i.min).every(([o,s])=>(n[o]??0)>=s))return{pass:!0,reason:i.reason,counts:n};return{pass:!1,reason:"shared tokens did not meet calibrated overlap thresholds",counts:n}}function ul(e,t,n){let i=t.map(l=>{let c=l.value(e),u=l.weightedValue?l.weightedValue(e,c):c;return{axis:l,value:c,weighted:u,qualifies:l.qualifies?l.qualifies(e,c):c>0}}),r=i.filter(l=>l.qualifies&&l.axis.reason).map(l=>l.axis.reason(e,l.value)),o=i.filter(l=>l.qualifies&&l.axis.dominantEligible!==!1).sort((l,c)=>c.weighted-l.weighted)[0],s=o&&o.weighted>0?o.axis.axis:n,a=[...new Set(i.filter(l=>l.qualifies).map(l=>l.axis.axis).concat(r.length>0?[]:[s]))];return{dominantPressure:s,pressureKinds:a,reasons:r}}function Ee(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function ct(e){return[...e].sort()}function YB(e,t,n,i,r,o){let s=[],a=[];for(let l of e)XB(l,i).filter(u=>!n.has(u)).length>0?s.push(l):a.push(l);s.length&&r.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 XB(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 i of t)n=n.replace(i,"");return n.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function iC(e,t,n){return e==="generic"?t:n}function Jo(e,t={}){let{minSimilarity:n=.62,minTokens:i=8,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:l}=t,c=_t(e).reactProfiles({scope:o,minJsxTokens:i,scanLimit:s}).filter(d=>d.kind==="component").map(d=>({file:d.file,component:d.name,tokens:d.jsxTokens,profile:d})),u=pn(c,d=>d.tokens);return gn({profiles:c,limit:r,filePattern:a,focusFiles:l,candidateIndex:u,profile:{name:"react-component-duplicates"},compare:(d,m)=>QB(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 QB(e,t,n){let i=jt(e.tokens,t.tokens);if(i.size<6||!ZB(i))return null;let r=ai(e.tokens,t.tokens);if(r<n)return null;let o=Ee(i,"component:"),s=Ee(i,"native:"),a=Ee(i,"prop:"),l=Ee(i,"event:"),c=Ee(i,"binding:"),u=eO({sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:l,sharedBindings:c});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:r,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:ct(i),sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:l,sharedBindings:c,evidenceClass:u.evidenceClass,actionTier:u.actionTier,evidenceClassReasons:u.reasons,recommendation:u.recommendation,uniqueToA:ct(nt(e.tokens,t.tokens)).slice(0,25),uniqueToB:ct(nt(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function ZB(e){let t=0,n=0;for(let i of e)i.startsWith("component:")&&(t+=1),(i.startsWith("prop:")||i.startsWith("event:")||i.startsWith("native:")||i.startsWith("jsx:"))&&(n+=1);return ci([{name:"component",count:t},{name:"shape",count:n}],[{min:{component:1},reason:"shared custom component"},{min:{shape:4},reason:"shared JSX structure"}]).pass}function eO(e){return li({genericWords:nO,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:tO})}function tO(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 nO=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 Yo(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:i=6,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:l}=t,c=_t(e).reactProfiles({scope:o,minBehaviorTokens:Math.max(3,i),scanLimit:s}).map(d=>({file:d.file,component:d.name,tokens:d.behaviorTokens,profile:d})),u=pn(c,d=>d.tokens);return gn({profiles:c,limit:r,filePattern:a,focusFiles:l,candidateIndex:u,profile:{name:"react-hook-candidates"},compare:(d,m)=>iO(d,m,n,i),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 iO(e,t,n,i){let r=jt(e.tokens,t.tokens);if(r.size<i||!sO(r))return null;let o=cl(e.tokens,t.tokens);if(o<n)return null;let s=Ee(r,"hook:"),a=Ee(r,"react-hook:"),l=Ee(r,"effect:"),c=Ee(r,"state:"),u=Ee(r,"request:"),d=Ee(r,"handler:"),m=Ee(r,"handler-verb:"),f=rO({sharedHooks:s,sharedReactHooks:a,sharedEffects:l,sharedState:c,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:ct(r),sharedHooks:s,sharedReactHooks:a,sharedEffects:l,sharedState:c,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m,evidenceClass:f.evidenceClass,actionTier:f.actionTier,evidenceClassReasons:f.reasons,recommendation:f.recommendation,uniqueToA:ct(nt(e.tokens,t.tokens)).slice(0,25),uniqueToB:ct(nt(t.tokens,e.tokens)).slice(0,25),reason:aO({sharedHooks:s,sharedReactHooks:a,sharedEffects:l,sharedState:c,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m}),locA:e.profile.loc,locB:t.profile.loc}}function rO(e){return li({genericWords:lO,stripPrefixes:cO,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:oO})}function oO(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 sO(e){let t=0,n=0,i=0,r=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:")?i+=1:u.startsWith("request:")?r+=1:u.startsWith("handler:")||u.startsWith("handler-verb:")?o+=1:u.startsWith("state:")?s+=1:u.startsWith("state-hook:")&&(a+=1);let l=s+a,c=t+n+i+r+o+l;return ci([{name:"requests",count:r},{name:"customHooks",count:t},{name:"namedStates",count:s},{name:"handlers",count:o},{name:"effects",count:i},{name:"reactHooks",count:n},{name:"namedBehavior",count:c}],[{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 aO(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 lO=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"]),cO=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function Md(e,t={}){let{minComponentLines:n=300,minFileLines:i=800,minJsxTokens:r=80,minBehaviorTokens:o=40,limit:s=20,scope:a,scanLimit:l,filePattern:c}=t;return _t(e).reactProfiles({scope:a,scanLimit:l}).filter(d=>d.kind==="component").filter(d=>!c||d.file.includes(c)||d.name.includes(c)).map(d=>uO(d,{minComponentLines:n,minFileLines:i,minJsxTokens:r,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 uO(e,t){let n=Math.max(80,Math.floor(t.minComponentLines/2)),i=ul(e,dO({minComponentLines:t.minComponentLines,minFileLines:t.minFileLines,minJsxTokens:t.minJsxTokens,minBehaviorTokens:t.minBehaviorTokens,substantialComponentLines:n}),"component"),{reasons:r}=i;if(r.length===0)return null;let o=i.dominantPressure,s=i.pressureKinds,a=mO(e),l=fO(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:l,recommendation:pO(l,a),reasons:r,loc:e.loc}}function dO(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 mO(e){let t=e.file.split(/[\\/]+/).filter(Boolean),n=t.slice(0,-1).map(m=>m.toLowerCase()),i=(t.at(-1)??e.name).replace(/\.[^.]+$/,""),o=n.findIndex(m=>hO.has(m))>=0,s=n.some(m=>gO.has(m));if(rC(i)||rC(e.name))return"component";let l=yO.has(i.toLowerCase()),c=/(?:Page|Route|Screen)$/.test(e.name),u=o&&/View$/.test(e.name),d=!s&&i.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()===e.name.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()&&/(?:Page|Route|Screen|View)$/.test(i);return l||c||u||d?"route-page":"component"}function rC(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&oC.has(t.at(-1))?!0:[...oC].some(n=>e.endsWith(bO(n)))}function fO(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 pO(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 gO=new Set(["component","components","panel","panels","partial","partials"]),oC=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"]),hO=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),yO=new Set(["page","route","screen"]);function bO(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Xo(e,t={}){let{minSimilarity:n=.62,minTokens:i=8,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:l}=t,c=SO(e,{scope:o,minTokens:i,scanLimit:s}),u=pn(c,d=>d.tokens);return gn({profiles:c,limit:r,filePattern:a,focusFiles:l,candidateIndex:u,profile:{name:"vue-component-duplicates"},compare:(d,m)=>CO(d,m,n),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function SO(e,t){return _t(e).vueProfiles({scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:vO(n)}))}function vO(e){return e.totalLines}function CO(e,t,n){let i=jt(e.tokens,t.tokens);if(i.size<6||!xO(i))return null;let r=ai(e.tokens,t.tokens);if(r<n)return null;let o=Ee(i,"component:"),s=Ee(i,"prop:"),a=Ee(i,"event:"),l=Ee(i,"directive:"),c=Ee(i,"slot:"),u=Ee(i,"id:"),d=RO({sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:l,sharedSlots:c,sharedIdentifiers:u});return{fileA:e.file,fileB:t.file,similarity:r,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:ct(i),sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:l,sharedSlots:c,sharedIdentifiers:u,evidenceClass:d.evidenceClass,actionTier:d.actionTier,evidenceClassReasons:d.reasons,recommendation:d.recommendation,uniqueToA:ct(nt(e.tokens,t.tokens)).slice(0,25),uniqueToB:ct(nt(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function xO(e){let t=0,n=0;for(let i of e)i.startsWith("component:")&&(t+=1),(i.startsWith("prop:")||i.startsWith("event:")||i.startsWith("directive:")||i.startsWith("slot:"))&&(n+=1);return ci([{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 RO(e){return li({genericWords:EO,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:IO})}function IO(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 EO=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 Qo(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:i=6,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:l}=t,c=_t(e).vueProfiles({scope:o,minBehaviorTokens:Math.max(3,i),scanLimit:s}).map(d=>({file:d.file,tokens:d.behaviorTokens,profile:d})),u=pn(c,d=>d.tokens);return gn({profiles:c,limit:r,filePattern:a,focusFiles:l,candidateIndex:u,profile:{name:"vue-composable-candidates"},compare:(d,m)=>wO(d,m,n,i),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function wO(e,t,n,i){let r=jt(e.tokens,t.tokens);if(r.size<i||!MO(r))return null;let o=cl(e.tokens,t.tokens);if(o<n)return null;let s=Ee(r,"composable:"),a=Ee(r,"store:"),l=Ee(r,"reactivity:"),c=Ee(r,"lifecycle:"),u=Ee(r,"request:"),d=Ee(r,"function:"),m=Ee(r,"function-verb:"),f=Ee(r,"template-binding:"),p=Ee(r,"template-event:"),g=LO({sharedComposables:s,sharedStores:a,sharedReactivity:l,sharedLifecycle:c,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f,sharedTemplateEvents:p});return{fileA:e.file,fileB:t.file,similarity:o,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:ct(r),sharedComposables:s,sharedStores:a,sharedReactivity:l,sharedLifecycle:c,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f,sharedTemplateEvents:p,evidenceClass:g.evidenceClass,actionTier:g.actionTier,evidenceClassReasons:g.reasons,recommendation:g.recommendation,uniqueToA:ct(nt(e.tokens,t.tokens)).slice(0,25),uniqueToB:ct(nt(t.tokens,e.tokens)).slice(0,25),reason:PO({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:c,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function LO(e){return li({genericWords:TO,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:DO})}function DO(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 MO(e){let t=0,n=0,i=0,r=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:")?i+=1:u.startsWith("lifecycle:")?r+=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 l=t+n,c=l+i+r+o+a;return ci([{name:"requests",count:i},{name:"lifecycle",count:r},{name:"functions",count:o},{name:"reusableHooks",count:l},{name:"reactivity",count:s},{name:"namedBehavior",count:c}],[{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 PO(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 TO=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 Pd(e,t={}){let{minTotalLines:n=800,minTemplateLines:i=300,minScriptLines:r=300,minStyleLines:o=500,limit:s=20,scope:a,scanLimit:l,filePattern:c}=t;return _t(e).vueProfiles({scope:a,scanLimit:l}).filter(d=>!c||d.file.includes(c)).map(d=>FO(d,{minTotalLines:n,minTemplateLines:i,minScriptLines:r,minStyleLines:o})).filter(d=>d!==null).sort((d,m)=>m.totalLines-d.totalLines||d.file.localeCompare(m.file)).slice(0,s)}function FO(e,t){let n=ul(e,kO(t),"total"),{reasons:i}=n;if(i.length===0)return null;let r=n.dominantPressure,o=n.pressureKinds.includes("total")?[...new Set([...n.pressureKinds,r])]:n.pressureKinds,s=NO(e.file),a=AO(r,s),l=e.totalLines+e.delegatedComposableLines;return{file:e.file,totalLines:l,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:r,pressureKinds:o,contextKind:s,recommendationKind:a,recommendation:_O(a,s),reasons:i,loc:l}}function kO(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 NO(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(i=>BO.has(i))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function AO(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 _O(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 BO=new Set(["landing","page","pages","route","routes","view","views"]);function OO(e,t={}){let{minSimilarity:n=.5,limit:i=15,scope:r,minChainLength:o=3,maxChainLength:s=8}=t,a=$e(e,r),l=GO(a,o,s);if(l.length===0)return[];let c=$O(l);return c.length<2?[]:KO(UO(c,n,i),i)}function $O(e){let t=jO(e),n=[];for(let i of e){let r=i.filter(o=>!t.has(o));r.length>=2&&n.push({original:i,filtered:r})}return n}function jO(e){let{nodeFreq:t,tailFreq:n}=HO(e),i=e.length*.9,r=e.length*.8,o=new Set;for(let[a,l]of t)l>i&&o.add(a);for(let[a,l]of n)l>r&&o.add(a);let s=["index.ts","index.js","cli.ts","main.ts","health.ts","health.js"];for(let a of t.keys()){let l=a.split("/").pop()??"";s.includes(l)&&o.add(a)}return o}function HO(e){let t=new Map,n=new Map;for(let i of e){let r=new Set;for(let o of i)r.has(o)||(t.set(o,(t.get(o)??0)+1),r.add(o));for(let o=Math.max(0,i.length-2);o<i.length;o++)n.set(i[o],(n.get(i[o])??0)+1)}return{nodeFreq:t,tailFreq:n}}function UO(e,t,n){let i=[];for(let r=0;r<e.length;r++){for(let o=r+1;o<e.length;o++){let s=zO(e[r],e[o],t);s&&i.push(s)}if(i.length>n*10)break}return i.sort((r,o)=>Math.abs(o.similarity-r.similarity)>.01?o.similarity-r.similarity:r.divergencePoints.length-o.divergencePoints.length),i}function zO(e,t,n){if(!qO(e.filtered,t.filtered))return null;let{distance:i,ops:r}=WO(e.filtered,t.filtered),o=Math.max(e.filtered.length,t.filtered.length);if(o===0)return null;let s=1-i/o;if(s<n||i===0)return null;let a=r.filter(c=>c.type==="substitute").map(c=>({index:c.indexA,nodeA:e.filtered[c.indexA],nodeB:t.filtered[c.indexB]}));return a.length===0||r.filter(c=>c.type==="match").length<2?null:{chainA:e.original,chainB:t.original,similarity:s,editDistance:i,divergencePoints:a,commonPrefix:VO(e.original,t.original),commonSuffix:JO(e.original,t.original)}}function qO(e,t){let n=new Set(e);return t.some(i=>n.has(i))}function KO(e,t){let n=[];for(let i of e)if(n.some(o=>sC(i.chainA,o.chainA)&&sC(i.chainB,o.chainB))||n.push(i),n.length>=t)break;return n}function GO(e,t,n){let i=[];for(let o of e.keys()){if(i.length>=500)break;aC(e,o,[o],new Set([o]),t,n,i,500)}return i}function aC(e,t,n,i,r,o,s,a){if(s.length>=a)return;if(n.length>=o){n.length>=r&&s.push([...n]);return}let l=e.get(t);if(!l||l.size===0){n.length>=r&&s.push([...n]);return}let c=!1;for(let u of l)if(!i.has(u)&&(i.add(u),n.push(u),aC(e,u,n,i,r,o,s,a),n.pop(),i.delete(u),c=!0,s.length>=a))return;!c&&n.length>=r&&s.push([...n])}function WO(e,t){let n=e.length,i=t.length,r=Array.from({length:n+1},()=>Array(i+1).fill(0));for(let l=0;l<=n;l++)r[l][0]=l;for(let l=0;l<=i;l++)r[0][l]=l;for(let l=1;l<=n;l++)for(let c=1;c<=i;c++)e[l-1]===t[c-1]?r[l][c]=r[l-1][c-1]:r[l][c]=1+Math.min(r[l-1][c],r[l][c-1],r[l-1][c-1]);let o=[],s=n,a=i;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&&r[s][a]===r[s-1][a-1]+1?(o.unshift({type:"substitute",indexA:s-1,indexB:a-1}),s--,a--):a>0&&r[s][a]===r[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:r[n][i],ops:o}}function VO(e,t){let n=[];for(let i=0;i<Math.min(e.length,t.length)&&e[i]===t[i];i++)n.push(e[i]);return n}function JO(e,t){let n=[],i=e.length-1,r=t.length-1;for(;i>=0&&r>=0&&e[i]===t[r];)n.unshift(e[i]),i--,r--;return n}function sC(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),i=e.join("\u2192");return n.includes(i)}function Ht(e){let t=YO(e.profile?.name),n=()=>{let i=e.candidates(),r=e.filterCandidate?i.filter(e.filterCandidate):i,o=e.orderCandidates?[...r].sort(e.orderCandidates):r,s=ke(o,e.scanLimit);t={pipeline:e.profile?.name,loadedCandidates:i.length,filteredCandidates:r.length,scannedCandidates:s.length,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:s.length<r.length,resultLimitApplied:!1};let a=e.prepare?.(s)??void 0,l=[];for(let u of s){t.evaluatedCandidates+=1;let d=e.evaluate(u,a);d&&l.push(d)}t.matchedResults=l.length,e.orderResults&&l.sort(e.orderResults);let c=typeof e.limit=="number"?l.slice(0,e.limit):l;return t.emittedResults=c.length,t.resultLimitApplied=c.length<l.length,e.onProfile?.({...t}),c};return e.profile?B(`candidate-pipeline:${e.profile.name}`,n,()=>({...XO(e.profile?.metadata),...t})):n()}function YO(e){return{pipeline:e,loadedCandidates:0,filteredCandidates:0,scannedCandidates:0,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:!1,resultLimitApplied:!1}}function XO(e){return typeof e=="function"?e():e??{}}function Zo(e,t={}){let{scope:n,minLoc:i=10,minCallees:r=6,limit:o=20,scanLimit:s}=t,a=new U(e);return Ht({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:i,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:s,profile:{name:"extract-candidates"},prepare:l=>a.calleeEvidenceMap(l,{semantic:t.semantic!==!1}),evaluate:(l,c)=>c.incompleteSymbolIds.has(l.symbolId)||c.unavailableSymbolIds.has(l.symbolId)?null:QO(l,c.rows.get(l.symbolId)??[],r),orderResults:(l,c)=>c.clusters.length-l.clusters.length||c.loc-l.loc,limit:o})}function QO(e,t,n){let i=new Set(t.map(c=>c.symbol));if(i.size<n)return null;let r=i$(i,t),o=r$(i,r);if(o.length<2)return null;let s=o$(o,r);if(s.length===0)return null;let a=A(e.symbol),l=ZO(a,i.size,o.length,s);return{symbol:e.symbol,shortName:a,relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:de(e),totalCallees:i.size,extractionKind:l.extractionKind,actionTier:"signal",evidenceReasons:l.evidenceReasons,recommendation:l.recommendation,clusters:s}}function ZO(e,t,n,i){let r=Math.max(...i.map(l=>l.callees.length)),o=Math.max(...i.map(l=>l.isolation)),s=[`${t} distinct callees across ${n} co-occurrence cluster(s)`,`${i.length} extractable cluster(s) passed size and isolation thresholds`,`largest extractable cluster has ${r} callees at ${Math.round(o*100)}% isolation`],a=e$(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."}:r>=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 e$(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 i=t$(e);return n$.has(i)?`caller verb suggests orchestration: ${i}`:null}function t$(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 n$=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function i$(e,t){let n=new Map;for(let r of e)n.set(r,new Set);let i=new Map;for(let r of t){let o=i.get(r.chunkId);o||(o=new Set,i.set(r.chunkId,o)),o.add(r.symbol)}for(let r of i.values()){let o=[...r];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 r$(e,t){let n=new Set,i=[];for(let r of e){if(n.has(r))continue;let o=new Set,s=[r];for(;s.length>0;){let a=s.pop();if(!n.has(a)){n.add(a),o.add(a);for(let l of t.get(a)??[])n.has(l)||s.push(l)}}i.push(o)}return i}function o$(e,t){return e.filter(n=>n.size>=3).map(n=>s$(n,e,t)).filter(n=>n.isolation>.5).sort((n,i)=>i.isolation-n.isolation)}function s$(e,t,n){let i=new Set;for(let a of t)if(a!==e)for(let l of a)i.add(l);let r=0;for(let a of e)for(let l of n.get(a)??[])i.has(l)&&r++;let o=e.size*i.size,s=o>0?1-r/o:1;return{callees:[...e].map(A),isolation:s}}import{posix as Dr}from"path";import{spawnSync as a$}from"child_process";import{createHash as l$}from"crypto";import{existsSync as c$}from"fs";import{dirname as lC,join as u$}from"path";import{fileURLToPath as d$}from"url";var dC=Hn("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]}),cC=Ct({kind:"consumer-file-usage",invalidation:Ye("consumer-file-usage"),serialize:C$,deserialize:x$});function hn(e,t){return{forDefinitions(n,i){return m$(e,t,n,i)}}}function ui(e){let t=new Map;for(let[n,i]of e)t.set(n,new Set(i.files.map(r=>r.file)));return t}function ml(e,t,n){return fC(e,t,n).partition}function m$(e,t,n,i){let r=mC(n.length),o=Ae()?Cn(e):null,s=o?f$(n,i,o):void 0,a=s?{workIdentity:s,workOutcome:"computed"}:{};return B("consumer-evidence.product",()=>{let l=B("consumer-evidence.provenance",()=>p$(e,t,n,i),()=>({...a,definitions:n.length,semantic:i.semantic,sourceFallback:i.sourceFallback!==!1})),c=new Map;r={...r,...l.counters};let u=g$(n,l.sources);return B("consumer-evidence.classify",()=>{let d=h$(e,n,l.sources,u);for(let m of n){let f=d.get(m.symbolId)??b$();r.realFiles+=f.partition.realConsumers.length,r.reexportOnlyFiles+=f.partition.barrelConsumers,r.importOnlyFiles+=f.partition.importOnlyConsumers,c.set(m.symbolId,{definition:m,files:f.files,semanticIncomplete:l.incompleteSymbolIds.has(m.symbolId),semanticUnavailable:l.unavailableSymbolIds.has(m.symbolId),...f.partition})}},()=>({...a,...u,realFiles:r.realFiles,reexportOnlyFiles:r.reexportOnlyFiles,importOnlyFiles:r.importOnlyFiles})),c},()=>({...a,...r}))}function f$(e,t,n){let i=l$("sha256").update("consumer-evidence-v3-calibrated-semantic\0").update(n).update("\0").update(t.semantic?"semantic\0":"indexed\0").update(t.sourceFallback===!1?"no-source-fallback":"source-fallback");for(let r of e.map(o=>o.symbol).sort())i.update("\0").update(r);return i.digest("hex").slice(0,24)}function mC(e){return{definitions:e,indexedFiles:0,semanticFiles:0,fallbackFiles:0,totalFiles:0,realFiles:0,reexportOnlyFiles:0,importOnlyFiles:0}}function p$(e,t,n,i){let r=mC(n.length),o=new Map,s=new Set,a=new Set;if(Td(o,r,"indexed",t.crossFileCallerMap(n,{semantic:!1})),i.semantic){let l=Ln(e,n);Td(o,r,"semantic",l.callers);for(let c of l.incompleteSymbolIds)s.add(c);for(let c of l.unavailableSymbolIds)a.add(c)}return i.sourceFallback!==!1&&Td(o,r,"source-fallback",t.sourceFallbackCallerFiles(n)),r.totalFiles=[...o.values()].reduce((l,c)=>l+c.size,0),{sources:o,counters:r,incompleteSymbolIds:s,unavailableSymbolIds:a}}function g$(e,t){return{definitions:e.length,consumerFiles:[...t.values()].reduce((n,i)=>n+i.size,0),nativeAttempted:!1,nativeUsed:!1,nativeReason:"not-attempted"}}function Td(e,t,n,i){let r=0;for(let[o,s]of i){let a=e.get(o);a||(a=new Map,e.set(o,a));for(let l of s){r++;let c=a.get(l)??new Set;c.add(n),a.set(l,c)}}n==="indexed"?t.indexedFiles+=r:n==="semantic"?t.semanticFiles+=r:t.fallbackFiles+=r}function h$(e,t,n,i){let r=M$(e,t,n,i);return r||y$(e,t,n)}function y$(e,t,n){let i=new Map;for(let r of t){let o=n.get(r.symbolId)??new Map;i.set(r.symbolId,fC(e,r,[...o.keys()],o))}return i}function fC(e,t,n,i=new Map){let r=[],o=0,s=0,a=Y(t.symbol),l=[];for(let c of n){let u;R$(e,c,t.relativePath,a)?(o++,u="reexport-only"):Fd(e,c,a)?(s++,u="import-only"):(r.push(c),u="real"),l.push({file:c,sources:[...i.get(c)??[]],classification:u})}return{partition:{realConsumers:r,barrelConsumers:o,importOnlyConsumers:s},files:l}}function b$(){return{partition:{realConsumers:[],barrelConsumers:0,importOnlyConsumers:0},files:[]}}function Fd(e,t,n){if(!n)return!1;let i=ye(t);if(!i)return!1;let r=dC.get(e,t,()=>pC(e,t,i));return r.importedLeaves.has(n)&&!r.usedLeaves.has(n)}function pC(e,t,n){let i=Un(e).forFile(t,{text:!0,ast:!0}),r=i.text;if(!r)return v$();let o=Nt(e,t,r),s=cC.read(e,t,o);if(s)return s;let a=S$(i.ast,n);return cC.write(e,t,o,a),a}function S$(e,t){let n=new Set,i=new Set;if(!e)return{importedLeaves:n,usedLeaves:i};let r=t==="rust"?new Set(["use_declaration"]):t==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),o=(s,a)=>{let l=a||r.has(s.type);(s.type==="identifier"||s.type==="type_identifier"||s.type==="property_identifier"||s.type==="field_identifier")&&(l?n.add(s.text):i.add(s.text));for(let c of s.children)o(c,l)};return o(e.rootNode,!1),{importedLeaves:n,usedLeaves:i}}function v$(){return{importedLeaves:new Set,usedLeaves:new Set}}function C$(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function x$(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 R$(e,t,n,i){if(!i)return!1;let r=Un(e).forFile(t,{lines:!0,reexports:!0}),o=r.lines??[];if(o.length===0)return!1;let s=r.reexports??[];return gC(o,s,i)}function gC(e,t,n){if(e.length===0||t.length===0)return!1;let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`\\b${i}\\b`),o=0;for(let s=0;s<e.length;s++){if(!r.test(e[s]??""))continue;if(o++,!t.find(l=>l.startLine<=s&&s<=l.endLine))return!1}return o>0}var I$="CODEBASEIQ_NATIVE_CONSUMER_CLASSIFY",E$="CODEBASEIQ_NATIVE_KERNELS_BIN",w$="CODEBASEIQ_NATIVE_CONSUMER_CLASSIFY_MIN_FILES",uC=1e3,L$=5e3,D$=64*1024*1024,dl;function M$(e,t,n,i){let r=process.env[I$]?.toLowerCase();if(r!=="1"&&r!=="true")return i.nativeReason=r==="0"||r==="false"?"disabled":"opt-in-required",null;if(i.consumerFiles<_$())return i.nativeReason="below-threshold",null;let o=B$();if(!o)return i.nativeReason="binary-missing",null;i.nativeAttempted=!0;let s=P$(e,t,n),a=a$(o,["consumer-classify"],{input:JSON.stringify(s),encoding:"utf8",timeout:L$,maxBuffer:D$,windowsHide:!0});if(a.status!==0||a.error)return i.nativeReason=a.error?`spawn-error:${a.error.message}`:`exit-${a.status??"null"}`,null;try{let l=JSON.parse(a.stdout),c=F$(l,t);return c?(i.nativeUsed=!0,i.nativeReason="used",c):(i.nativeReason="invalid-response",null)}catch{return i.nativeReason="invalid-json",null}}function P$(e,t,n){let i=new Map,r=[];for(let a of t){let l=Y(a.symbol),u=[...(n.get(a.symbolId)??new Map).entries()].map(([d,m])=>{let f=i.get(d)??new Set;return l&&f.add(l),i.set(d,f),{file:d,sources:[...m]}});r.push({symbol_id:a.symbolId,leaf:l,consumer_files:u})}let o={},s={};for(let[a,l]of i){let c=ye(a);if(c){let d=dC.get(e,a,()=>pC(e,a,c));o[a]={imported_leaves:[...d.importedLeaves],used_leaves:[...d.usedLeaves]}}let u=T$(e,a,l);u.length>0&&(s[a]=u)}return{definitions:r,file_usages:o,reexport_only_leaves:s}}function T$(e,t,n){if(n.size===0)return[];let i=Un(e).forFile(t,{lines:!0,reexports:!0}),r=i.lines??[],o=i.reexports??[];return r.length===0||o.length===0?[]:[...n].filter(s=>gC(r,o,s))}function F$(e,t){if(!Array.isArray(e.entries)||e.entries.length!==t.length)return null;let n=new Set(t.map(r=>r.symbolId)),i=new Map;for(let r of e.entries){let o=k$(r);if(!o||!n.has(o.symbol_id))return null;i.set(o.symbol_id,{partition:{realConsumers:o.real_consumers,barrelConsumers:o.barrel_consumers,importOnlyConsumers:o.import_only_consumers},files:o.files})}for(let r of n)if(!i.has(r))return null;return i}function k$(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(i=>typeof i=="string"))return null;let n=[];for(let i of t.files){if(!i||typeof i!="object")return null;let r=i;if(typeof r.file!="string"||!Array.isArray(r.sources)||!r.sources.every(N$)||!A$(r.classification))return null;n.push({file:r.file,sources:r.sources,classification:r.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 N$(e){return e==="indexed"||e==="semantic"||e==="source-fallback"}function A$(e){return e==="real"||e==="reexport-only"||e==="import-only"}function _$(){let e=process.env[w$];if(!e)return uC;let t=Number(e);return Number.isFinite(t)&&t>=0?t:uC}function B$(){if(dl!==void 0)return dl;let e=process.env[E$],t=process.platform==="win32"?"codebaseiq-kernels.exe":"codebaseiq-kernels";return dl=[...e?[e]:[],...O$().map(i=>u$(i,"target","release",t))].find(i=>c$(i))??null,dl}function O$(){let e=new Set,t=lC(d$(import.meta.url));for(let n=0;n<5;n++)e.add(t),t=lC(t);return[...e]}var $$=20,j$=1,H$=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"]]),U$=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),z$=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 q$(e,t={}){let n=Ad(t.limit,$$),i=Ad(t.minConsumers,j$),r=new U(e),o=r.fileDependencyGraph(t.scope),s=u1(me(e,{includeIgnored:!1})),a=f1(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?K$(e,r,t.target):G$(e,t.scope,t.scanLimit)).map(u=>W$(e,r,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=i||t.target).sort(c1).slice(0,n)}function K$(e,t,n){let i=Y$(e,n);if(i)return[vC(i)];let r=pe(e,n);if(!r)return[];let o=t.definitionsForFile(r.relativePath).find(s=>s.symbolId===r.symbolId);return o?[X$(o)]:[{unit:{kind:"symbol",file:r.relativePath,shortName:A(r.symbol),symbol:r.symbol,startLine:r.startLine,endLine:r.endLine}}]}function G$(e,t,n){let i=me(e,{scope:t,includeIgnored:!1}),r=Ad(n,i.length);return i.slice(0,r).map(o=>vC(o))}function W$(e,t,n,i,r,o,s){let a=i.definition?V$(e,t,i.definition,r.semantic):null,l=a?.files??J$(n,i.unit.file),c=i.definition?a.coverage==="complete"?l.length>0?"exact":"none":a.coverage:l.length>0?"file-level":"none",u=c==="incomplete"||c==="unavailable"||c==="incomplete-and-unavailable",d=i.unit.file,m=Yt(Dr.dirname(d)),f=Z$(l),p=Q$(m),g=Bd([...hC(m),...f?hC(f):[]]),h=u?"repository-level-review":e1(i.unit,m,f,l),b=u?{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:`Compiler-resolved consumer evidence is ${c}; no relocation destination is safe to score.`}:t1(h,i.unit,m,f,l,o,s),v=s1(i.unit,c,f,l,m,b.whyNoSuggestedHome),y=a1(i.unit,m,f,l,b.suggestedHome,b.whyNoSuggestedHome);return{actionTier:"signal",sourceUnit:i.unit,candidatePath:d,currentDirectory:m,directoryAncestry:p,consumerFiles:l,consumerCoverage:c,nearestCommonOwner:f,boundaryMarkers:g,recommendedTier:h,suggestedHome:b.suggestedHome,destinationConfidence:b.confidence,whyNoSuggestedHome:b.whyNoSuggestedHome,counterevidence:u?[...v,"Known consumer files are retained, but missing compiler evidence can hide additional owners."]:v,reasons:y,recommendation:u?"Retain the current location until compiler-resolved consumer evidence is complete.":l1(h,b.suggestedHome,c)}}function V$(e,t,n,i){let r=hn(e,t).forDefinitions([n],{semantic:i!==!1,sourceFallback:!0}).get(n.symbolId),o=r?.semanticIncomplete?r.semanticUnavailable?"incomplete-and-unavailable":"incomplete":r?.semanticUnavailable?"unavailable":"complete";return{files:EC(r?.files.map(s=>s.file)??[]),coverage:o}}function J$(e,t){let n=[];for(let[i,r]of e.entries())i!==t&&r.has(t)&&n.push(i);return EC(n)}function Y$(e,t){let n=ys(t),i=me(e,{includeIgnored:!1}),r=i.find(s=>s===n);if(r)return r;let o=i.find(s=>s.endsWith(`/${n}`));return o||(i.find(s=>s.includes(n))??null)}function X$(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:A(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function vC(e){return{unit:{kind:"file",file:e,shortName:Dr.basename(e)}}}function Q$(e){if(e===".")return[{path:".",depth:0,markers:[]}];let t=[],n=e.split("/").filter(Boolean);for(let i=0;i<n.length;i+=1){let r=n.slice(0,i+1).join("/");t.push({path:r,depth:i,markers:_d(r)})}return t}function hC(e){return e==="."?[]:CC(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function _d(e){return Bd(CC(e).map(({marker:t})=>t))}function CC(e){let t=e.split("/").filter(Boolean),n=[];for(let i=0;i<t.length;i+=1){let r=H$.get(t[i]);r&&n.push({marker:r,prefix:t.slice(0,i+1).join("/")})}return n}function Z$(e){if(e.length===0)return null;let t=e.map(i=>Yt(Dr.dirname(i))),n=t[0].split("/").filter(Boolean);for(let i of t.slice(1)){let r=i.split("/").filter(Boolean),o=[],s=Math.min(n.length,r.length);for(let a=0;a<s&&n[a]===r[a];a+=1)o.push(n[a]);n=o}return n.length===0?".":n.join("/")}function e1(e,t,n,i){return n?e.kind==="symbol"&&i.length===1?i[0]===e.file?"same-file":"sibling-folder":n==="."||n==="src"?"repository-level-review":bC(n,"package")?"package-level-shared":bC(n,"app")?"app-level-shared":SC(n,["feature","domain","module"])||SC(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function t1(e,t,n,i,r,o,s){let a=n1(e,i);if(a)return di(a);let l=d1(t.file),c=i1(e,n,l,r,s);if(c)return c;let u=i;if(Yt(n)===Yt(u))return di(`${n} is already the nearest common owner for its consumers.`);let d=r1(u,n,l,s);return d||o1(u,n,l,o,s)}function n1(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 i1(e,t,n,i,r){if(e==="same-file"){let o=i[0]??null;return o?kd(o):di("No same-file consumer path was available.")}if(e==="sibling-folder"&&i.length===1){let o=Yt(Dr.dirname(i[0])),s=IC(t,n,o,r);return s?di(s):kd(o)}return null}function r1(e,t,n,i){return g1(e)?xC(e,t,n,i,`Nearest shared owner ${e} is outside source root ${n}.`):null}function o1(e,t,n,i,r){if(e===".")return di("The nearest common owner is the repository root.");let o=`${e}/shared`,s=xC(o,t,n,r,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||i.has(o)?s:di(`${o} does not exist in the indexed project.`)}function xC(e,t,n,i,r){if(!RC(e,n))return di(r);let o=IC(t,n,e,i);return o?di(o):kd(e)}function kd(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function di(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function s1(e,t,n,i,r,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."),i.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&&r.startsWith(`${n}/`)&&s.push("Candidate already lives under the nearest common owner."),o&&s.push(`No exact suggested home: ${o}`),s}function a1(e,t,n,i,r,o){let s=[];return s.push(`${e.shortName} currently lives in ${t}.`),n?s.push(`${i.length} consumer file(s) share ${n} as their nearest common owner.`):s.push("No consumer owner could be inferred from the current index."),r?s.push(`Suggested home is ${r}.`):o&&s.push(`No exact suggested home: ${o}`),s}function l1(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 c1(e,t){return yC(t)-yC(e)||e.candidatePath.localeCompare(t.candidatePath)}function yC(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 u1(e){let t=new Set(["."]);for(let n of e){let i=Yt(Dr.dirname(n));for(;!t.has(i)&&(t.add(i),i!==".");)i=Yt(Dr.dirname(i))}return t}function d1(e){let t=Nd(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function RC(e,t){let n=Yt(e),i=Yt(t);return i==="."||n===i||n.startsWith(`${i}/`)}function m1(e,t,n){let i=Nd(e),r=Nd(t);return(RC(e,t)?i.slice(r.length):i).some(s=>n.has(s.toLowerCase()))}function IC(e,t,n,i){return Yt(e)===Yt(n)||!m1(e,t,i)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function f1(...e){let t=new Set(z$);for(let n of e)for(let i of n??[]){let r=p1(i);r&&t.add(r)}return t}function p1(e){let t=e.trim().toLowerCase();return t===""?null:t}function bC(e,t){return _d(e).includes(t)}function SC(e,t){let n=_d(e);return t.some(i=>n.includes(i))}function g1(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?U$.has(n):!1}function Yt(e){let t=ys(e);return t===""?".":t}function Nd(e){let t=ys(e);return t==="."?[]:t.split("/").filter(Boolean)}function Ad(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function EC(e){return Bd([...e]).sort((t,n)=>t.localeCompare(n))}function Bd(e){return[...new Set(e)]}function Od(e,t,n={}){return h1(e,t,n)}function h1(e,t,n){let{maxDepth:i=5,scope:r}=n,o=i===Number.MAX_SAFE_INTEGER,s=o?null:500,a=pe(e,t);if(!a)return{rows:[],coverage:{status:"incomplete",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:i,reachedDepth:0,perSymbolEvidenceLimit:s,remainingFrontierSymbols:0,reasons:["The requested symbol could not be resolved."],semanticEvidence:"incomplete"}};let l=[],c=new Set([a.symbolId]),u=new Set,d=[a],m=0,f=!1,p=!1,g=!1;for(let v=1;v<=i&&d.length!==0;v++){m=v;let y=[],I=sn(e,d,{...o?{}:{limit:s+1},semanticEvidence:ge});I.incompleteSymbolIds.size>0&&(p=!0),I.unavailableSymbolIds.size>0&&(g=!0);for(let E of d){let S=I.rows.get(E.symbolId)??[];s!==null&&S.length>s&&(f=!0);let x=s===null?S:S.slice(0,s);for(let C of y1(e,E,r,x)){let L=`${C.file}|${C.shortName}`;if(C.symbolId!==null){if(c.has(C.symbolId))continue;c.add(C.symbolId)}else if(u.has(L))continue;u.add(L),l.push({symbol:C.symbol,shortName:C.shortName,file:C.file,depth:v}),C.symbolId!==null&&C.symbolMatch&&y.push(C.symbolMatch)}}d=y}l.sort((v,y)=>v.depth-y.depth||v.file.localeCompare(y.file));let h=d.length>0,b=[];return h&&b.push(`${d.length} symbol(s) remain eligible beyond depth ${i}.`),f&&b.push(`At least one symbol had more than ${s} incoming evidence row(s).`),p&&b.push("Compiler-resolved incoming evidence was incomplete for at least one traversed symbol."),g&&b.push("Compiler-resolved incoming evidence was unavailable for at least one traversed symbol."),b.length===0&&b.push("The discovered reverse evidence frontier was exhausted."),{rows:l,coverage:{status:p||g?"incomplete":h||f?"bounded":"accounted",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:i,reachedDepth:m,perSymbolEvidenceLimit:s,remainingFrontierSymbols:d.length,reasons:b,semanticEvidence:p&&g?"incomplete-and-unavailable":p?"incomplete":g?"unavailable":"complete"}}}function y1(e,t,n,i){let r=i.filter(u=>!e.isIgnored(u.file)).filter(u=>!n||u.file.includes(n)),o=new Set(r.map(u=>u.file)),s=[];for(let u of b1(e,t,n)){if(o.has(u))continue;let d=W(e,u),m=d.length>0?Ke(d,d[0].startLine):null;s.push({symbol:m?.symbol??u,file:u})}let a=[...r,...s],l=[],c=new Set;for(let u of a){let d=Si(e,u.symbol);if(!d){let f=`${u.file}|${u.symbol}`;if(c.has(f))continue;c.add(f),l.push({symbolId:null,symbol:u.symbol,shortName:A(u.symbol),file:u.file,symbolMatch:null});continue}if(d.symbolId===t.symbolId||e.isIgnored(d.relativePath)||!S1(d))continue;let m=`${d.symbolId}|${d.relativePath}`;c.has(m)||(c.add(m),l.push({symbolId:d.symbolId,symbol:d.symbol,shortName:A(d.symbol),file:d.relativePath,symbolMatch:d}))}return l}function b1(e,t,n){let i=n?"AND consumer_d.relative_path LIKE ?":"",r=[t.symbolId,t.documentId];return n&&r.push(`%${n}%`),new Set(e.all(`SELECT DISTINCT consumer_d.relative_path
323
323
  FROM mentions m
324
324
  JOIN chunks c ON m.chunk_id = c.id
325
325
  JOIN documents consumer_d ON consumer_d.id = c.document_id
@@ -327,54 +327,54 @@ import{c as tp,e as np,f as qt}from"./chunk-B2OB55RR.js";import{b as kt,c as ec}
327
327
  AND m.role != 1
328
328
  AND c.document_id != ?
329
329
  ${e.pathExclusionsFor("consumer_d")}
330
- ${i}`,...r).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function M1(e){if(e.symbol.startsWith("scip-clojure ")||ye(e.relativePath)==="clojure")return!0;let t=Bt(e.symbol);return t==="method"||t==="type"||e.symbol.endsWith("().")}function MC(e,t){let n=ht(t),i=[],r="complete",o=J(n);o==="entry"&&Bn(i,"operational-root","structural entrypoint path"),o==="worker"&&Bn(i,"operational-root","worker launch convention"),Pu(n)&&Bn(i,"operational-root","framework-discovered entrypoint"),P1(e,n)&&Bn(i,"operational-root","configured entry root");let s=!1;try{s=Pn(e,n),s&&Bn(i,"published-api","package manifest export");for(let a of sy(e,n))Bn(i,"operational-root",a)}catch(a){r="partial",Bn(i,"metadata-unavailable",`package metadata unavailable: ${DC(a)}`)}try{let a=rt(e.config.projectRoot,n,{maxBytes:8388608,inputKind:"change-surface source"});T1(a)&&Bn(i,"operational-root","module contains a direct-execution process guard")}catch(a){r="partial",Bn(i,"metadata-unavailable",ot(a)?"indexed source file is unavailable on disk":`source metadata unavailable: ${DC(a)}`)}return{operationalRoot:i.some(a=>a.kind==="operational-root"),publishedApi:s,coverage:r,reasons:i}}function P1(e,t){let n=e.config.entryRoots;return n?n.files?.some(i=>ht(i)===t)?!0:n.pathPrefixes?.some(i=>t.startsWith(ht(i)))??!1:!1}function T1(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 Bn(e,t,n){e.some(i=>i.kind===t&&i.detail===n)||e.push({kind:t,detail:n})}function DC(e){return e instanceof Error?e.message:String(e)}function zd(e,t,n={}){let i=dt(e,t);if(!i)return null;let r=k1(e,i);if(!r||e.isIgnored(r.relative_path))return null;let o=[],s=0,a=!0,l=N1(e,r.relative_path),c=MC(e,r.relative_path),u=n.semantic===!1?{callers:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set}:Ln(e,l);for(let d of l){let m=A1(e,r,d,u.callers.get(d.symbolId)??new Set);s+=m;let f=F1(n.semantic!==!1,d.symbolId,u),p=f==="complete"||f==="disabled";p||(a=!1);let g=p?m:null,h=g===null?void 0:_1(g),b=[...c.reasons,...m>0?[{kind:"external-consumers",detail:`${m} known external consumer${m===1?"":"s"}`}]:[],...p?[]:[{kind:"semantic-consumer-coverage",detail:`compiler-resolved consumer evidence is ${f}`}]];o.push({symbol:d.symbol,shortName:A(d.symbol),startLine:d.startLine,endLine:d.endLine,externalConsumers:g,knownExternalConsumers:m,consumerCoverage:f,externalConsumerRiskLevel:h,riskLevel:B1(h,c,!p),riskReasons:b})}return{file:r.relative_path,symbols:o,totalExternalConsumers:a?s:null,knownTotalExternalConsumers:s,fileRisk:c}}function F1(e,t,n){if(!e)return"disabled";let i=n.incompleteSymbolIds.has(t),r=n.unavailableSymbolIds.has(t);return i&&r?"incomplete-and-unavailable":i?"incomplete":r?"unavailable":"complete"}function k1(e,t){return e.get(`SELECT id, relative_path FROM documents
330
+ ${i}`,...r).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function S1(e){if(e.symbol.startsWith("scip-clojure ")||ye(e.relativePath)==="clojure")return!0;let t=Bt(e.symbol);return t==="method"||t==="type"||e.symbol.endsWith("().")}function LC(e,t){let n=ht(t),i=[],r="complete",o=J(n);o==="entry"&&Bn(i,"operational-root","structural entrypoint path"),o==="worker"&&Bn(i,"operational-root","worker launch convention"),wu(n)&&Bn(i,"operational-root","framework-discovered entrypoint"),v1(e,n)&&Bn(i,"operational-root","configured entry root");let s=!1;try{s=Pn(e,n),s&&Bn(i,"published-api","package manifest export");for(let a of ry(e,n))Bn(i,"operational-root",a)}catch(a){r="partial",Bn(i,"metadata-unavailable",`package metadata unavailable: ${wC(a)}`)}try{let a=rt(e.config.projectRoot,n,{maxBytes:8388608,inputKind:"change-surface source"});C1(a)&&Bn(i,"operational-root","module contains a direct-execution process guard")}catch(a){r="partial",Bn(i,"metadata-unavailable",ot(a)?"indexed source file is unavailable on disk":`source metadata unavailable: ${wC(a)}`)}return{operationalRoot:i.some(a=>a.kind==="operational-root"),publishedApi:s,coverage:r,reasons:i}}function v1(e,t){let n=e.config.entryRoots;return n?n.files?.some(i=>ht(i)===t)?!0:n.pathPrefixes?.some(i=>t.startsWith(ht(i)))??!1:!1}function C1(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 Bn(e,t,n){e.some(i=>i.kind===t&&i.detail===n)||e.push({kind:t,detail:n})}function wC(e){return e instanceof Error?e.message:String(e)}function $d(e,t,n={}){let i=dt(e,t);if(!i)return null;let r=R1(e,i);if(!r||e.isIgnored(r.relative_path))return null;let o=[],s=0,a=!0,l=I1(e,r.relative_path),c=LC(e,r.relative_path),u=n.semantic===!1?{callers:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set}:Ln(e,l);for(let d of l){let m=E1(e,r,d,u.callers.get(d.symbolId)??new Set);s+=m;let f=x1(n.semantic!==!1,d.symbolId,u),p=f==="complete"||f==="disabled";p||(a=!1);let g=p?m:null,h=g===null?void 0:w1(g),b=[...c.reasons,...m>0?[{kind:"external-consumers",detail:`${m} known external consumer${m===1?"":"s"}`}]:[],...p?[]:[{kind:"semantic-consumer-coverage",detail:`compiler-resolved consumer evidence is ${f}`}]];o.push({symbol:d.symbol,shortName:A(d.symbol),startLine:d.startLine,endLine:d.endLine,externalConsumers:g,knownExternalConsumers:m,consumerCoverage:f,externalConsumerRiskLevel:h,riskLevel:L1(h,c,!p),riskReasons:b})}return{file:r.relative_path,symbols:o,totalExternalConsumers:a?s:null,knownTotalExternalConsumers:s,fileRisk:c}}function x1(e,t,n){if(!e)return"disabled";let i=n.incompleteSymbolIds.has(t),r=n.unavailableSymbolIds.has(t);return i&&r?"incomplete-and-unavailable":i?"incomplete":r?"unavailable":"complete"}function R1(e,t){return e.get(`SELECT id, relative_path FROM documents
331
331
  WHERE relative_path = ?
332
332
  ${e.pathExclusionsFor("documents")}
333
- LIMIT 1`,t)??null}function N1(e,t){return new U(e).definitionsForFile(t).sort((n,i)=>n.startLine-i.startLine||n.endLine-i.endLine)}function A1(e,t,n,i){let r=e.all(`SELECT DISTINCT consumer_d.relative_path
333
+ LIMIT 1`,t)??null}function I1(e,t){return new U(e).definitionsForFile(t).sort((n,i)=>n.startLine-i.startLine||n.endLine-i.endLine)}function E1(e,t,n,i){let r=e.all(`SELECT DISTINCT consumer_d.relative_path
334
334
  FROM mentions m
335
335
  JOIN chunks c ON m.chunk_id = c.id
336
336
  JOIN documents consumer_d ON consumer_d.id = c.document_id
337
337
  WHERE m.symbol_id = ?
338
338
  AND m.role != 1
339
- AND c.document_id != ?`,n.symbolId,t.id);return new Set([...r.map(o=>o.relative_path),...[...i].filter(o=>o!==t.relative_path)]).size}function _1(e){return e>10?"high":e>0?"medium":"low"}function B1(e,t,n){return e==="high"?"high":n||e==="medium"||t.operationalRoot||t.publishedApi||t.coverage==="partial"?"medium":"low"}function O1(e,t={}){let{scope:n,minLoc:i=1,maxDepth:r=5,scanLimit:o}=t,s=new U(e),a=$1(e,n,i,o),l=new qd;for(let g of a)l.add(g);let c=[],u=[];a.length>0&&c.push(PC(e,0,a,l));let d=a.map(g=>g.definition).filter(g=>g!==null),m=new Set(a.map(g=>g.symbol));for(let g=1;g<=r&&d.length>0;g++){let h=s.calleeMap(d,{semantic:!1}),b=new Set;for(let y of d)for(let I of h.get(y.symbolId)??[])m.has(I.symbol)||b.add(I.symbol);let v=[];for(let y of b){m.add(y);let I=TC(e,y);if(!I||e.isIgnored(I.relativePath)||Qe(e,I.relativePath)||qe(e,I.symbol,I.relativePath)||s.fileKind(I.relativePath)==="test"||s.hasSuppressionComment(I))continue;let E=H1(e,I,l);E.removable?v.push(j1(I,"cascade")):E.blockingFiles.length>0&&u.push({shortName:A(I.symbol),file:I.relativePath,blockingFiles:E.blockingFiles.slice(0,3)})}if(v.length===0)break;for(let y of v)l.add(y);c.push(PC(e,g,v,l)),d=v.map(y=>y.definition).filter(y=>y!==null)}let f=c.reduce((g,h)=>g+h.loc,0),p=c.reduce((g,h)=>g+h.entries.length,0);return{batches:c,totalSymbols:p,totalLoc:f,blocked:u}}function $1(e,t,n,i){let r=ji(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:i,semantic:!1}),o=[];for(let s of r.symbols)s.kind==="dead-code"&&(Qe(e,s.relativePath)||qe(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:TC(e,s.symbol)}));return o}function j1(e,t){return{symbol:e.symbol,shortName:A(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function TC(e,t){let n=e.get(`SELECT d.relative_path
339
+ AND c.document_id != ?`,n.symbolId,t.id);return new Set([...r.map(o=>o.relative_path),...[...i].filter(o=>o!==t.relative_path)]).size}function w1(e){return e>10?"high":e>0?"medium":"low"}function L1(e,t,n){return e==="high"?"high":n||e==="medium"||t.operationalRoot||t.publishedApi||t.coverage==="partial"?"medium":"low"}function D1(e,t={}){let{scope:n,minLoc:i=1,maxDepth:r=5,scanLimit:o}=t,s=new U(e),a=M1(e,n,i,o),l=new jd;for(let g of a)l.add(g);let c=[],u=[];a.length>0&&c.push(DC(e,0,a,l));let d=a.map(g=>g.definition).filter(g=>g!==null),m=new Set(a.map(g=>g.symbol));for(let g=1;g<=r&&d.length>0;g++){let h=s.calleeMap(d,{semantic:!1}),b=new Set;for(let y of d)for(let I of h.get(y.symbolId)??[])m.has(I.symbol)||b.add(I.symbol);let v=[];for(let y of b){m.add(y);let I=MC(e,y);if(!I||e.isIgnored(I.relativePath)||Qe(e,I.relativePath)||qe(e,I.symbol,I.relativePath)||s.fileKind(I.relativePath)==="test"||s.hasSuppressionComment(I))continue;let E=T1(e,I,l);E.removable?v.push(P1(I,"cascade")):E.blockingFiles.length>0&&u.push({shortName:A(I.symbol),file:I.relativePath,blockingFiles:E.blockingFiles.slice(0,3)})}if(v.length===0)break;for(let y of v)l.add(y);c.push(DC(e,g,v,l)),d=v.map(y=>y.definition).filter(y=>y!==null)}let f=c.reduce((g,h)=>g+h.loc,0),p=c.reduce((g,h)=>g+h.entries.length,0);return{batches:c,totalSymbols:p,totalLoc:f,blocked:u}}function M1(e,t,n,i){let r=ji(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:i,semantic:!1}),o=[];for(let s of r.symbols)s.kind==="dead-code"&&(Qe(e,s.relativePath)||qe(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:MC(e,s.symbol)}));return o}function P1(e,t){return{symbol:e.symbol,shortName:A(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function MC(e,t){let n=e.get(`SELECT d.relative_path
340
340
  FROM global_symbols gs
341
341
  JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
342
342
  JOIN documents d ON d.id = der.document_id
343
343
  WHERE gs.symbol = ?
344
- LIMIT 1`,t);return n?W(e,n.relative_path).find(i=>i.symbol===t)??null:null}function H1(e,t,n){let i=zr(e,t);if(i.length===0)return{removable:!1,blockingFiles:[]};let r=new Set;for(let o of i)o.file===t.relativePath&&o.line>=t.startLine&&o.line<=t.endLine||n.contains(o.file,o.line)||r.add(o.file);return{removable:r.size===0,blockingFiles:[...r]}}function PC(e,t,n,i){let r=[...n].sort((a,l)=>a.file.localeCompare(l.file)||a.startLine-l.startLine),o=new Set(r.map(a=>a.file)),s=[];for(let a of o){let l=W(e,a);l.length>0&&l.every(c=>i.contains(a,c.startLine))&&s.push(a)}return{depth:t,entries:r.map(({definition:a,...l})=>l),loc:r.reduce((a,l)=>a+l.loc,0),filesEmptied:s.sort()}}var qd=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 i=this.ranges.get(t);return i?i.some(r=>n>=r.start&&n<=r.end):!1}};import{execFileSync as Tr}from"child_process";import{existsSync as U1}from"fs";import{basename as FC}from"path";function pl(e){let t=new Map;for(let n of e){let i=t.get(n.file);i||(i=[],t.set(n.file,i)),i.push(n)}return t}var Jd="Unable to compute git diff.",z1={semanticConsumers:Ch,sourceFallbackConsumers:Co},Yd={resolveCommit:Kl,readBatch({projectRoot:e,resolvedBase:t,relativePaths:n}){let i=n.map(r=>`${t}:./${r}
345
- `).join("");return Tr("git",["cat-file","--batch"],{cwd:e,input:i,maxBuffer:256*1024*1024,timeout:1e4,stdio:["pipe","pipe","ignore"],windowsHide:!0})}};function gl(e,t={}){let n=t.plan??Fr(e,t);return n.note?q1(n.note,n.changedFileLines):n.changedFiles.length===0?K1(n.changedFileLines):hl(n.changedFiles,[_C(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function Fr(e,t={}){let{base:n="HEAD"}=t;try{let i=Kl(e.config.projectRoot,n),r=G1(e.config.projectRoot,i),o=r.changedFileLines,s=Q1(e,o),a=Z1(e,r.changedRanges);return{changedFileLines:o,changedFiles:s,changedRanges:a,renamedFiles:J1(e.config.projectRoot,i,s,r),note:o.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:Jd}}}function _C(e,t,n,i=[],r={}){let o=r.evidenceRuntime??z1,s=new U(e),a=new Set(n),l=pl(i),c=[],u=new Map,d=t.flatMap(C=>s.definitionsForFile(C)).filter(gj),m=d.filter(C=>tj(C,l)),f=ij(e,d,m,l),p=sj([...m,...f.definitions]).sort((C,L)=>C.relativePath.localeCompare(L.relativePath)||C.startLine-L.startLine),g=p.map(C=>C.symbolId),h=mj(e,g),b=fj(e,g,n),v=p.filter(C=>(h.get(C.symbolId)??0)===0),y=AC("semantic-consumers",v.length,()=>o.semanticConsumers(e,v)),I=y.values,E=v.filter(C=>(I.get(C.symbolId)?.size??0)===0),S=AC("source-fallback-consumers",E.length,()=>o.sourceFallbackConsumers(e,E)),x=S.values;for(let C of p)cj(e,C,a,c,u,I.get(C.symbolId)??new Set,x.get(C.symbolId)??new Set,h.get(C.symbolId)??0,b.get(C.symbolId)??new Set);return{changedSymbols:c,consumerEntries:[...u.entries()].map(([C,L])=>({file:C,symbols:[...L].sort()})),attributionNotes:f.notes,evidenceTiers:[y.status,S.status]}}function hl(e,t){let n=new Map,i=t.flatMap(a=>a.changedSymbols),r=t.flatMap(a=>a.attributionNotes??[]),o=uj(t);for(let a of t)for(let l of a.consumerEntries){let c=n.get(l.file);c||(c=new Set,n.set(l.file,c));for(let u of l.symbols)c.add(u)}let s=pj(n);return{changedFiles:[...e],changedSymbols:i,affectedConsumers:s,attributionNotes:r,evidenceTiers:o,summary:{totalChangedFiles:e.length,totalChangedSymbols:i.length,totalAffectedFiles:s.length}}}function q1(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:zC(),summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function K1(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:zC(),summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function G1(e,t){let n=Tr("git",["diff","--name-status","--find-renames",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864,windowsHide:!0}),i=Tr("git",["diff","--name-status","--find-renames","--cached",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024,windowsHide:!0}),r=Tr("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024,windowsHide:!0}),o=Tr("git",["diff","--unified=0",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024,windowsHide:!0}),s=Tr("git",["diff","--unified=0","--cached",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024,windowsHide:!0}),a=Y1([n,i]);return{changedFileLines:[...new Set([...a.changedFiles,...$C(r)])],changedRanges:HC([...NC(o),...NC(s)]),renamedFiles:a.renamedFiles,deletedFiles:a.deletedFiles}}function W1(e,t,n){let i=typeof e=="string"?{projectRoot:e,base:t,relativePath:n}:e;if(typeof i.projectRoot!="string"||typeof i.base!="string"||typeof i.relativePath!="string")throw new TypeError("fileContentAtBase requires projectRoot, base, and relativePath.");let r={projectRoot:i.projectRoot,base:i.base,relativePath:i.relativePath},{relativePath:o}=r,s=Xd(r);if(s.state==="unavailable")throw new Error(`Base content unavailable for ${o}: ${s.reason}`);return s.state==="present"?s.content:null}function Xd(e,t=Yd){return OC(e.relativePath),Qd({projectRoot:e.projectRoot,base:e.base,relativePaths:[e.relativePath]},t).get(e.relativePath)??{state:"unavailable",reason:`Base-content lookup omitted ${e.relativePath}.`}}function Qd(e,t=Yd){for(let s of e.relativePaths)OC(s);let n=[...new Set(e.relativePaths)];if(n.length===0)return new Map;let i;try{i=t.resolveCommit(e.projectRoot,e.base)}catch(s){return Kd(n,Gd(s))}let r;try{r=t.readBatch({projectRoot:e.projectRoot,resolvedBase:i,relativePaths:n})}catch(s){return Kd(n,Gd(s))}let o;try{o=V1(r,n)}catch(s){return Kd(n,`Malformed git cat-file batch output: ${Gd(s)}`)}return new Map(n.map(s=>{let a=o.get(s)??null;return[s,a===null?{state:"absent"}:{state:"present",content:a}]}))}function Zd(e,t=Yd){let n=Qd({projectRoot:e.projectRoot,base:e.base,relativePaths:e.preloadPaths??[]},t);return i=>(n.has(i)||n.set(i,Xd({projectRoot:e.projectRoot,base:e.base,relativePath:i},t)),n.get(i)??{state:"unavailable",reason:`Base-content reader omitted ${i}.`})}function BC(e,t=e.changedFiles){let n=new Map(e.renamedFiles.map(i=>[i.to,i.from]));return[...new Set(t.map(i=>n.get(i)??i))]}function OC(e){vn(e)}function Kd(e,t){return new Map(e.map(n=>[n,{state:"unavailable",reason:t}]))}function Gd(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 V1(e,t){let n=new Map,i=0;for(let r of t){let o=e.indexOf(10,i);if(o<0)throw new Error("git cat-file batch output ended before object header");let s=e.subarray(i,o).toString("utf-8");if(i=o+1,s.endsWith(" missing")){n.set(r,null);continue}let a=/^[0-9a-f]+ ([^ ]+) (\d+)$/.exec(s);if(!a)throw new Error(`unexpected git cat-file batch header: ${s}`);let[,l,c]=a,u=Number(c);if(!Number.isFinite(u)||u<0)throw new Error(`unexpected git cat-file batch size: ${s}`);if(i+u>e.length)throw new Error("git cat-file batch output ended before blob payload");let d=e.subarray(i,i+u);n.set(r,l==="blob"?d.toString("utf-8"):null),i+=u,e[i]===10&&(i+=1)}return n}function J1(e,t,n,i){if(n.length===0)return[];let r=new Map,o=new Set;for(let a of i.renamedFiles)n.includes(a.to)&&(r.set(a.to,a),o.add(a.from));let s=i.deletedFiles;if(s.length===0)return[...r.values()].sort((a,l)=>a.to.localeCompare(l.to));for(let a of n){if(r.has(a)||!U1(`${e}/${a}`))continue;let l=s.filter(d=>!o.has(d)).filter(d=>FC(d)===FC(a));if(l.length===0)continue;let c=rt(e,a),u=l.map(d=>({from:d,to:a,similarity:X1(W1({projectRoot:e,base:t,relativePath:d})??"",c)})).sort((d,m)=>m.similarity-d.similarity)[0];u&&u.similarity>=.45&&(r.set(a,u),o.add(u.from))}return[...r.values()].sort((a,l)=>a.to.localeCompare(l.to))}function Y1(e){let t=new Set,n=new Map,i=new Set;for(let r of e.flatMap(o=>$C(o))){let[o,s,a]=r.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")&&i.add(s)}}return{changedFiles:[...t],renamedFiles:[...n.values()],deletedFiles:[...i]}}function X1(e,t){let n=new Set(kC(e)),i=new Set(kC(t));if(n.size===0&&i.size===0)return 1;if(n.size===0||i.size===0)return 0;let r=0;for(let o of n)i.has(o)&&(r+=1);return 2*r/(n.size+i.size)}function kC(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function $C(e){return e.split(`
346
- `).map(t=>t.trim()).filter(t=>t.length>0)}function Q1(e,t){let n=jC(e),i=[];for(let r of t){let o=n(r);o&&!e.isIgnored(o)&&i.push(o)}return i}function Z1(e,t){let n=jC(e),i=[];for(let r of t){let o=n(r.file);o&&!e.isIgnored(o)&&i.push({...r,file:o})}return HC(i)}function jC(e){let n=e.all(`SELECT relative_path FROM documents
347
- ORDER BY id`).map(r=>r.relative_path).map(r=>({path:r,normalized:vn(r)})),i=new Map;for(let r of n){let o=i.get(r.normalized);i.set(r.normalized,o===void 0||o===r.path?r.path:null)}return r=>{let o=vn(r),s=i.get(o);if(s)return s;let a=n.filter(l=>l.normalized.endsWith(o));return a.length===1?a[0].path:null}}function NC(e){let t=[],n=null;for(let i of e.split(`
348
- `)){if(i.startsWith("+++ ")){n=ej(i.slice(4).trim());continue}if(!n||!i.startsWith("@@ "))continue;let r=/@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(i);if(!r)continue;let o=Math.max(0,Number(r[1])-1),s=r[2]===void 0?1:Number(r[2]);t.push({file:n,startLine:o,endLine:Math.max(o,o+Math.max(s,1)-1)})}return t}function ej(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function HC(e){let t=new Set,n=[];for(let i of e){let r=`${i.file}:${i.startLine}:${i.endLine}`;t.has(r)||(t.add(r),n.push(i))}return n}function tj(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(i=>em(e.startLine,e.endLine,i.startLine,i.endLine))}function nj(e,t,n){let i=new Map,r=[],o=UC(e),s=aj(n);for(let a of t){let l=o.get(a.file)??[];if(l.some(d=>em(d.startLine,d.endLine,a.startLine,a.endLine)))continue;let c=s.get(a.file)??[],u=lj(c,a);if(u){let d=l.find(m=>m.startLine>=u.startLine&&m.startLine<=u.endLine);if(d){i.set(d.symbolId,d),r.push(Wd(a,"ast-widened"));continue}}if(c.length===0){let d=[...l].filter(m=>m.startLine<=a.startLine).sort((m,f)=>f.startLine-m.startLine||m.endLine-f.endLine)[0];if(d){i.set(d.symbolId,d),r.push(Wd(a,"nearest-preceding"));continue}}r.push(Wd(a,"unattributed"))}return{definitions:[...i.values()],notes:r}}function ij(e,t,n,i){let r=UC(n),o=[],s=[],a=[...new Set(t.map(l=>l.relativePath))];for(let l of a){let c=i.get(l)??[];if(c.length===0)continue;let u=r.get(l)??[];for(let d of c)u.some(m=>em(m.startLine,m.endLine,d.startLine,d.endLine))||o.push(d);o.some(d=>d.file===l)&&s.push(...rj(e,l))}return nj(t,o,s)}function rj(e,t){let n=ae(e,t);return n?n.rootNode.namedChildren.filter(oj).map(i=>({file:t,startLine:i.startPosition.row,endLine:i.endPosition.row})).filter(i=>i.endLine>=i.startLine):[]}function oj(e){return e.endPosition.row<e.startPosition.row?!1:!new Set(["import_statement","comment"]).has(e.type)}function sj(e){let t=new Map;for(let n of e)t.set(n.symbolId,n);return[...t.values()]}function UC(e){let t=new Map;for(let n of e){let i=t.get(n.relativePath)??[];i.push(n),t.set(n.relativePath,i)}return t}function aj(e){let t=new Map;for(let n of e){let i=t.get(n.file)??[];i.push(n),t.set(n.file,i)}return t}function lj(e,t){return e.filter(n=>n.startLine<=t.startLine&&n.endLine>=t.endLine).sort((n,i)=>n.endLine-n.startLine-(i.endLine-i.startLine))[0]}function Wd(e,t){return{file:e.file,startLine:e.startLine,endLine:e.endLine,method:t}}function em(e,t,n,i){return e<=i&&n<=t}function cj(e,t,n,i,r,o,s,a,l){let c=Math.max(a,o.size,s.size);if(!hj(t,c))return;let u=A(t.symbol);i.push({symbol:t.symbol,shortName:u,file:t.relativePath,startLine:t.startLine,endLine:t.endLine,fanIn:c});for(let d of l)Vd(e,n,r,d,u);for(let d of o)Vd(e,n,r,d,u);for(let d of s)Vd(e,n,r,d,u)}function AC(e,t,n){try{return{values:n(),status:{tier:e,state:"complete",attemptedSymbols:t}}}catch(i){return{values:new Map,status:{tier:e,state:"failed",attemptedSymbols:t,reason:dj(i)}}}}function uj(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"}),i=n.reduce((o,s)=>o+s.attemptedSymbols,0),r=[...new Set(n.filter(o=>o.state==="failed").map(o=>o.reason))];return r.length===0?{tier:t,state:"complete",attemptedSymbols:i}:{tier:t,state:"failed",attemptedSymbols:i,reason:r.join("; ").slice(0,500)}})}function zC(){return[{tier:"semantic-consumers",state:"complete",attemptedSymbols:0},{tier:"source-fallback-consumers",state:"complete",attemptedSymbols:0}]}function dj(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 mj(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
344
+ LIMIT 1`,t);return n?W(e,n.relative_path).find(i=>i.symbol===t)??null:null}function T1(e,t,n){let i=Hr(e,t);if(i.length===0)return{removable:!1,blockingFiles:[]};let r=new Set;for(let o of i)o.file===t.relativePath&&o.line>=t.startLine&&o.line<=t.endLine||n.contains(o.file,o.line)||r.add(o.file);return{removable:r.size===0,blockingFiles:[...r]}}function DC(e,t,n,i){let r=[...n].sort((a,l)=>a.file.localeCompare(l.file)||a.startLine-l.startLine),o=new Set(r.map(a=>a.file)),s=[];for(let a of o){let l=W(e,a);l.length>0&&l.every(c=>i.contains(a,c.startLine))&&s.push(a)}return{depth:t,entries:r.map(({definition:a,...l})=>l),loc:r.reduce((a,l)=>a+l.loc,0),filesEmptied:s.sort()}}var jd=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 i=this.ranges.get(t);return i?i.some(r=>n>=r.start&&n<=r.end):!1}};import{execFileSync as Mr}from"child_process";import{existsSync as F1}from"fs";import{basename as PC}from"path";function fl(e){let t=new Map;for(let n of e){let i=t.get(n.file);i||(i=[],t.set(n.file,i)),i.push(n)}return t}var Kd="Unable to compute git diff.",k1={semanticConsumers:Sh,sourceFallbackConsumers:So},Gd={resolveCommit:ql,readBatch({projectRoot:e,resolvedBase:t,relativePaths:n}){let i=n.map(r=>`${t}:./${r}
345
+ `).join("");return Mr("git",["cat-file","--batch"],{cwd:e,input:i,maxBuffer:256*1024*1024,timeout:1e4,stdio:["pipe","pipe","ignore"],windowsHide:!0})}};function pl(e,t={}){let n=t.plan??Pr(e,t);return n.note?N1(n.note,n.changedFileLines):n.changedFiles.length===0?A1(n.changedFileLines):gl(n.changedFiles,[NC(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function Pr(e,t={}){let{base:n="HEAD"}=t;try{let i=ql(e.config.projectRoot,n),r=_1(e.config.projectRoot,i),o=r.changedFileLines,s=U1(e,o),a=z1(e,r.changedRanges);return{changedFileLines:o,changedFiles:s,changedRanges:a,renamedFiles:$1(e.config.projectRoot,i,s,r),note:o.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:Kd}}}function NC(e,t,n,i=[],r={}){let o=r.evidenceRuntime??k1,s=new U(e),a=new Set(n),l=fl(i),c=[],u=new Map,d=t.flatMap(C=>s.definitionsForFile(C)).filter(oj),m=d.filter(C=>K1(C,l)),f=W1(e,d,m,l),p=Y1([...m,...f.definitions]).sort((C,L)=>C.relativePath.localeCompare(L.relativePath)||C.startLine-L.startLine),g=p.map(C=>C.symbolId),h=nj(e,g),b=ij(e,g,n),v=p.filter(C=>(h.get(C.symbolId)??0)===0),y=kC("semantic-consumers",v.length,()=>o.semanticConsumers(e,v)),I=y.values,E=v.filter(C=>(I.get(C.symbolId)?.size??0)===0),S=kC("source-fallback-consumers",E.length,()=>o.sourceFallbackConsumers(e,E)),x=S.values;for(let C of p)Z1(e,C,a,c,u,I.get(C.symbolId)??new Set,x.get(C.symbolId)??new Set,h.get(C.symbolId)??0,b.get(C.symbolId)??new Set);return{changedSymbols:c,consumerEntries:[...u.entries()].map(([C,L])=>({file:C,symbols:[...L].sort()})),attributionNotes:f.notes,evidenceTiers:[y.status,S.status]}}function gl(e,t){let n=new Map,i=t.flatMap(a=>a.changedSymbols),r=t.flatMap(a=>a.attributionNotes??[]),o=ej(t);for(let a of t)for(let l of a.consumerEntries){let c=n.get(l.file);c||(c=new Set,n.set(l.file,c));for(let u of l.symbols)c.add(u)}let s=rj(n);return{changedFiles:[...e],changedSymbols:i,affectedConsumers:s,attributionNotes:r,evidenceTiers:o,summary:{totalChangedFiles:e.length,totalChangedSymbols:i.length,totalAffectedFiles:s.length}}}function N1(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:HC(),summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function A1(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:HC(),summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function _1(e,t){let n=Mr("git",["diff","--name-status","--find-renames",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864,windowsHide:!0}),i=Mr("git",["diff","--name-status","--find-renames","--cached",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024,windowsHide:!0}),r=Mr("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024,windowsHide:!0}),o=Mr("git",["diff","--unified=0",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024,windowsHide:!0}),s=Mr("git",["diff","--unified=0","--cached",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024,windowsHide:!0}),a=j1([n,i]);return{changedFileLines:[...new Set([...a.changedFiles,...BC(r)])],changedRanges:$C([...FC(o),...FC(s)]),renamedFiles:a.renamedFiles,deletedFiles:a.deletedFiles}}function B1(e,t,n){let i=typeof e=="string"?{projectRoot:e,base:t,relativePath:n}:e;if(typeof i.projectRoot!="string"||typeof i.base!="string"||typeof i.relativePath!="string")throw new TypeError("fileContentAtBase requires projectRoot, base, and relativePath.");let r={projectRoot:i.projectRoot,base:i.base,relativePath:i.relativePath},{relativePath:o}=r,s=Wd(r);if(s.state==="unavailable")throw new Error(`Base content unavailable for ${o}: ${s.reason}`);return s.state==="present"?s.content:null}function Wd(e,t=Gd){return _C(e.relativePath),Vd({projectRoot:e.projectRoot,base:e.base,relativePaths:[e.relativePath]},t).get(e.relativePath)??{state:"unavailable",reason:`Base-content lookup omitted ${e.relativePath}.`}}function Vd(e,t=Gd){for(let s of e.relativePaths)_C(s);let n=[...new Set(e.relativePaths)];if(n.length===0)return new Map;let i;try{i=t.resolveCommit(e.projectRoot,e.base)}catch(s){return Hd(n,Ud(s))}let r;try{r=t.readBatch({projectRoot:e.projectRoot,resolvedBase:i,relativePaths:n})}catch(s){return Hd(n,Ud(s))}let o;try{o=O1(r,n)}catch(s){return Hd(n,`Malformed git cat-file batch output: ${Ud(s)}`)}return new Map(n.map(s=>{let a=o.get(s)??null;return[s,a===null?{state:"absent"}:{state:"present",content:a}]}))}function Jd(e,t=Gd){let n=Vd({projectRoot:e.projectRoot,base:e.base,relativePaths:e.preloadPaths??[]},t);return i=>(n.has(i)||n.set(i,Wd({projectRoot:e.projectRoot,base:e.base,relativePath:i},t)),n.get(i)??{state:"unavailable",reason:`Base-content reader omitted ${i}.`})}function AC(e,t=e.changedFiles){let n=new Map(e.renamedFiles.map(i=>[i.to,i.from]));return[...new Set(t.map(i=>n.get(i)??i))]}function _C(e){vn(e)}function Hd(e,t){return new Map(e.map(n=>[n,{state:"unavailable",reason:t}]))}function Ud(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 O1(e,t){let n=new Map,i=0;for(let r of t){let o=e.indexOf(10,i);if(o<0)throw new Error("git cat-file batch output ended before object header");let s=e.subarray(i,o).toString("utf-8");if(i=o+1,s.endsWith(" missing")){n.set(r,null);continue}let a=/^[0-9a-f]+ ([^ ]+) (\d+)$/.exec(s);if(!a)throw new Error(`unexpected git cat-file batch header: ${s}`);let[,l,c]=a,u=Number(c);if(!Number.isFinite(u)||u<0)throw new Error(`unexpected git cat-file batch size: ${s}`);if(i+u>e.length)throw new Error("git cat-file batch output ended before blob payload");let d=e.subarray(i,i+u);n.set(r,l==="blob"?d.toString("utf-8"):null),i+=u,e[i]===10&&(i+=1)}return n}function $1(e,t,n,i){if(n.length===0)return[];let r=new Map,o=new Set;for(let a of i.renamedFiles)n.includes(a.to)&&(r.set(a.to,a),o.add(a.from));let s=i.deletedFiles;if(s.length===0)return[...r.values()].sort((a,l)=>a.to.localeCompare(l.to));for(let a of n){if(r.has(a)||!F1(`${e}/${a}`))continue;let l=s.filter(d=>!o.has(d)).filter(d=>PC(d)===PC(a));if(l.length===0)continue;let c=rt(e,a),u=l.map(d=>({from:d,to:a,similarity:H1(B1({projectRoot:e,base:t,relativePath:d})??"",c)})).sort((d,m)=>m.similarity-d.similarity)[0];u&&u.similarity>=.45&&(r.set(a,u),o.add(u.from))}return[...r.values()].sort((a,l)=>a.to.localeCompare(l.to))}function j1(e){let t=new Set,n=new Map,i=new Set;for(let r of e.flatMap(o=>BC(o))){let[o,s,a]=r.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")&&i.add(s)}}return{changedFiles:[...t],renamedFiles:[...n.values()],deletedFiles:[...i]}}function H1(e,t){let n=new Set(TC(e)),i=new Set(TC(t));if(n.size===0&&i.size===0)return 1;if(n.size===0||i.size===0)return 0;let r=0;for(let o of n)i.has(o)&&(r+=1);return 2*r/(n.size+i.size)}function TC(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function BC(e){return e.split(`
346
+ `).map(t=>t.trim()).filter(t=>t.length>0)}function U1(e,t){let n=OC(e),i=[];for(let r of t){let o=n(r);o&&!e.isIgnored(o)&&i.push(o)}return i}function z1(e,t){let n=OC(e),i=[];for(let r of t){let o=n(r.file);o&&!e.isIgnored(o)&&i.push({...r,file:o})}return $C(i)}function OC(e){let n=e.all(`SELECT relative_path FROM documents
347
+ ORDER BY id`).map(r=>r.relative_path).map(r=>({path:r,normalized:vn(r)})),i=new Map;for(let r of n){let o=i.get(r.normalized);i.set(r.normalized,o===void 0||o===r.path?r.path:null)}return r=>{let o=vn(r),s=i.get(o);if(s)return s;let a=n.filter(l=>l.normalized.endsWith(o));return a.length===1?a[0].path:null}}function FC(e){let t=[],n=null;for(let i of e.split(`
348
+ `)){if(i.startsWith("+++ ")){n=q1(i.slice(4).trim());continue}if(!n||!i.startsWith("@@ "))continue;let r=/@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(i);if(!r)continue;let o=Math.max(0,Number(r[1])-1),s=r[2]===void 0?1:Number(r[2]);t.push({file:n,startLine:o,endLine:Math.max(o,o+Math.max(s,1)-1)})}return t}function q1(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function $C(e){let t=new Set,n=[];for(let i of e){let r=`${i.file}:${i.startLine}:${i.endLine}`;t.has(r)||(t.add(r),n.push(i))}return n}function K1(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(i=>Yd(e.startLine,e.endLine,i.startLine,i.endLine))}function G1(e,t,n){let i=new Map,r=[],o=jC(e),s=X1(n);for(let a of t){let l=o.get(a.file)??[];if(l.some(d=>Yd(d.startLine,d.endLine,a.startLine,a.endLine)))continue;let c=s.get(a.file)??[],u=Q1(c,a);if(u){let d=l.find(m=>m.startLine>=u.startLine&&m.startLine<=u.endLine);if(d){i.set(d.symbolId,d),r.push(zd(a,"ast-widened"));continue}}if(c.length===0){let d=[...l].filter(m=>m.startLine<=a.startLine).sort((m,f)=>f.startLine-m.startLine||m.endLine-f.endLine)[0];if(d){i.set(d.symbolId,d),r.push(zd(a,"nearest-preceding"));continue}}r.push(zd(a,"unattributed"))}return{definitions:[...i.values()],notes:r}}function W1(e,t,n,i){let r=jC(n),o=[],s=[],a=[...new Set(t.map(l=>l.relativePath))];for(let l of a){let c=i.get(l)??[];if(c.length===0)continue;let u=r.get(l)??[];for(let d of c)u.some(m=>Yd(m.startLine,m.endLine,d.startLine,d.endLine))||o.push(d);o.some(d=>d.file===l)&&s.push(...V1(e,l))}return G1(t,o,s)}function V1(e,t){let n=ae(e,t);return n?n.rootNode.namedChildren.filter(J1).map(i=>({file:t,startLine:i.startPosition.row,endLine:i.endPosition.row})).filter(i=>i.endLine>=i.startLine):[]}function J1(e){return e.endPosition.row<e.startPosition.row?!1:!new Set(["import_statement","comment"]).has(e.type)}function Y1(e){let t=new Map;for(let n of e)t.set(n.symbolId,n);return[...t.values()]}function jC(e){let t=new Map;for(let n of e){let i=t.get(n.relativePath)??[];i.push(n),t.set(n.relativePath,i)}return t}function X1(e){let t=new Map;for(let n of e){let i=t.get(n.file)??[];i.push(n),t.set(n.file,i)}return t}function Q1(e,t){return e.filter(n=>n.startLine<=t.startLine&&n.endLine>=t.endLine).sort((n,i)=>n.endLine-n.startLine-(i.endLine-i.startLine))[0]}function zd(e,t){return{file:e.file,startLine:e.startLine,endLine:e.endLine,method:t}}function Yd(e,t,n,i){return e<=i&&n<=t}function Z1(e,t,n,i,r,o,s,a,l){let c=Math.max(a,o.size,s.size);if(!sj(t,c))return;let u=A(t.symbol);i.push({symbol:t.symbol,shortName:u,file:t.relativePath,startLine:t.startLine,endLine:t.endLine,fanIn:c});for(let d of l)qd(e,n,r,d,u);for(let d of o)qd(e,n,r,d,u);for(let d of s)qd(e,n,r,d,u)}function kC(e,t,n){try{return{values:n(),status:{tier:e,state:"complete",attemptedSymbols:t}}}catch(i){return{values:new Map,status:{tier:e,state:"failed",attemptedSymbols:t,reason:tj(i)}}}}function ej(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"}),i=n.reduce((o,s)=>o+s.attemptedSymbols,0),r=[...new Set(n.filter(o=>o.state==="failed").map(o=>o.reason))];return r.length===0?{tier:t,state:"complete",attemptedSymbols:i}:{tier:t,state:"failed",attemptedSymbols:i,reason:r.join("; ").slice(0,500)}})}function HC(){return[{tier:"semantic-consumers",state:"complete",attemptedSymbols:0},{tier:"source-fallback-consumers",state:"complete",attemptedSymbols:0}]}function tj(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 nj(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
349
  FROM mentions m
350
350
  JOIN chunks c ON m.chunk_id = c.id
351
351
  WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
352
352
  AND m.role != 1
353
- GROUP BY m.symbol_id`,...t);return new Map(n.map(i=>[i.symbol_id,i.fan_in]))}function fj(e,t,n){if(t.length===0||n.length===0)return new Map;let i=e.all(`SELECT DISTINCT m.symbol_id, ref_d.relative_path
353
+ GROUP BY m.symbol_id`,...t);return new Map(n.map(i=>[i.symbol_id,i.fan_in]))}function ij(e,t,n){if(t.length===0||n.length===0)return new Map;let i=e.all(`SELECT DISTINCT m.symbol_id, ref_d.relative_path
354
354
  FROM mentions m
355
355
  JOIN chunks c ON m.chunk_id = c.id
356
356
  JOIN documents ref_d ON c.document_id = ref_d.id
357
357
  WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
358
358
  AND m.role != 1
359
359
  AND ref_d.relative_path NOT IN (${n.map(()=>"?").join(",")})
360
- ${e.pathExclusionsFor("ref_d")}`,...t,...n),r=new Map;for(let o of i){let s=r.get(o.symbol_id);s||(s=new Set,r.set(o.symbol_id,s)),s.add(o.relative_path)}return r}function Vd(e,t,n,i,r){if(e.isIgnored(i)||t.has(i))return;let o=n.get(i);o||(o=new Set,n.set(i,o)),o.add(r)}function pj(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function gj(e){return!(De(e.symbol)||e.parentTypeName!==null&&!st(e.symbol))}function hj(e,t){return st(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}var yj=5;function bj(e,t={}){let{base:n="HEAD",minContainment:i=.7,minCallees:r=3,minSiteCoverage:o=.4,maxHelpers:s=Number.POSITIVE_INFINITY,limit:a=20,scanLimit:l}=t,c=t.semantic!==!1,u=t.diffPlan??Fr(e,{base:n}),d={available:u.note!==Jd,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 U(e),f=new Set(u.changedFiles),p=new Map(u.renamedFiles.map(x=>[x.to,x.from]));if(t.baseContentAt&&t.baseContentResultAt)throw new Error("Specify only one of baseContentAt or baseContentResultAt.");let g=t.baseContentResultAt?t.baseContentResultAt:t.baseContentAt?Ej(t.baseContentAt):Zd({projectRoot:e.config.projectRoot,base:n,preloadPaths:BC(u)}),h=Ij(m,f,p,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 v=m.calleeEvidenceMap(b,{semantic:c}),y=b.filter(x=>!v.incompleteSymbolIds.has(x.symbolId)&&!v.unavailableSymbolIds.has(x.symbolId)).map(x=>({def:x,callees:cl((v.rows.get(x.symbolId)??[]).map(C=>C.symbol))}));for(let x of b)!v.incompleteSymbolIds.has(x.symbolId)&&!v.unavailableSymbolIds.has(x.symbolId)||d.skipped.push({helperShortName:A(x.symbol),helperFile:x.relativePath,reason:"compiler-resolved callee evidence is incomplete or unavailable \u2014 unsafe to score"});let I=Mr(e),E,S=()=>(E??=I.calleeIndex({minCallees:Math.min(3,r),scanLimit:l,semantic:c}),E);for(let{def:x,callees:C}of y){let L=A(x.symbol);if(C.size<r){d.skipped.push({helperShortName:L,helperFile:x.relativePath,reason:`fewer than ${r} meaningful callees \u2014 too small to score`});continue}let w=S(),R=Rj(C,w);if(R===0){d.skipped.push({helperShortName:L,helperFile:x.relativePath,reason:"helper callee pattern is all project-wide infrastructure \u2014 too generic to score"});continue}let M=wj(e,x.symbolId);if(M.length===0){d.skipped.push({helperShortName:L,helperFile:x.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}d.helpersChecked+=1;let _=Sj({candidateIndex:w,changed:f,helperCallees:C,helperFile:x.relativePath,helperSymbol:x.symbol,minContainment:i,minSiteCoverage:o,migratedFiles:M});_.length!==0&&(_.sort((D,P)=>qC(P.migrationScope)-qC(D.migrationScope)||P.containment-D.containment||P.siteCoverage-D.siteCoverage||D.file.localeCompare(P.file)),d.findings.push({helperSymbol:x.symbol,helperShortName:L,helperFile:x.relativePath,helperShape:"specific-callee-cluster",helperCalleeCount:C.size,specificHelperCalleeCount:R,migratedFiles:M.sort(),leftovers:_.slice(0,yj)}))}return d.findings.sort((x,C)=>(C.leftovers[0]?.containment??0)-(x.leftovers[0]?.containment??0)||x.helperFile.localeCompare(C.helperFile)),d.findings=d.findings.slice(0,a),d}function Sj(e){let t=[],n=vj(e.helperSymbol,e.helperFile,e.migratedFiles),i=new Set;for(let r of e.helperCallees)for(let o of e.candidateIndex.candidateIndexesByCallee.get(r)??[])i.add(o);for(let r of i){let o=e.candidateIndex.corpus[r];if(o.symbol===e.helperSymbol||e.changed.has(o.file)||o.callees.has(e.helperSymbol))continue;let s=Bv(e.helperCallees,o.callees);if(s<e.minContainment)continue;let a=[...e.helperCallees].filter(u=>o.callees.has(u)),l=o.callees.size===0?0:a.length/o.callees.size;if(l<e.minSiteCoverage||!a.some(u=>(e.candidateIndex.docFreq.get(u)??0)<=e.candidateIndex.ubiquityThreshold))continue;let c=Cj(n,o.symbol,o.file);t.push({symbol:o.symbol,shortName:A(o.symbol),file:o.file,...c,containment:s,siteCoverage:l,uniqueSiteCalleeCount:Math.max(0,o.callees.size-a.length),sharedCallees:a.map(A).sort()})}return t}function qC(e){return e==="same-scope"?2:e==="unknown"?1:0}function vj(e,t,n){let i=new Set([...tm(t),...nm(Y(e))]);for(let r of n)for(let o of tm(r))i.add(o);return i}function Cj(e,t,n){let i=new Set([...tm(n),...nm(Y(t))]);if(e.size===0||i.size===0)return{migrationScope:"unknown",migrationScopeReasons:["insufficient path/name tokens to infer migration scope"]};let r=[...i].filter(o=>e.has(o)).sort();return r.length>0?{migrationScope:"same-scope",migrationScopeReasons:[`shares migration-scope token(s): ${r.slice(0,5).join(", ")}`]}:{migrationScope:"possible-subtype",migrationScopeReasons:["no path/name tokens shared with the helper or already migrated files"]}}var xj=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 tm(e){return nm(e.replace(/\.[^.]+$/,""))}function nm(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!xj.has(t))}function Rj(e,t){let n=0;for(let i of e)(t.docFreq.get(i)??0)<=t.ubiquityThreshold&&(n+=1);return n}function Ij(e,t,n,i){let r=[];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=i(s);if(a.state==="unavailable")return{definitions:[],unavailable:a};(a.state==="absent"||!new RegExp(`\\b${Oe(o.leaf)}\\b`).test(a.content))&&r.push(o)}return{definitions:r}}function Ej(e){return t=>{let n=e(t);return n===null?{state:"absent"}:{state:"present",content:n}}}function wj(e,t){return e.all(`SELECT DISTINCT ref_d.relative_path
360
+ ${e.pathExclusionsFor("ref_d")}`,...t,...n),r=new Map;for(let o of i){let s=r.get(o.symbol_id);s||(s=new Set,r.set(o.symbol_id,s)),s.add(o.relative_path)}return r}function qd(e,t,n,i,r){if(e.isIgnored(i)||t.has(i))return;let o=n.get(i);o||(o=new Set,n.set(i,o)),o.add(r)}function rj(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function oj(e){return!(De(e.symbol)||e.parentTypeName!==null&&!st(e.symbol))}function sj(e,t){return st(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}var aj=5;function lj(e,t={}){let{base:n="HEAD",minContainment:i=.7,minCallees:r=3,minSiteCoverage:o=.4,maxHelpers:s=Number.POSITIVE_INFINITY,limit:a=20,scanLimit:l}=t,c=t.semantic!==!1,u=t.diffPlan??Pr(e,{base:n}),d={available:u.note!==Kd,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 U(e),f=new Set(u.changedFiles),p=new Map(u.renamedFiles.map(x=>[x.to,x.from]));if(t.baseContentAt&&t.baseContentResultAt)throw new Error("Specify only one of baseContentAt or baseContentResultAt.");let g=t.baseContentResultAt?t.baseContentResultAt:t.baseContentAt?gj(t.baseContentAt):Jd({projectRoot:e.config.projectRoot,base:n,preloadPaths:AC(u)}),h=pj(m,f,p,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 v=m.calleeEvidenceMap(b,{semantic:c}),y=b.filter(x=>!v.incompleteSymbolIds.has(x.symbolId)&&!v.unavailableSymbolIds.has(x.symbolId)).map(x=>({def:x,callees:ll((v.rows.get(x.symbolId)??[]).map(C=>C.symbol))}));for(let x of b)!v.incompleteSymbolIds.has(x.symbolId)&&!v.unavailableSymbolIds.has(x.symbolId)||d.skipped.push({helperShortName:A(x.symbol),helperFile:x.relativePath,reason:"compiler-resolved callee evidence is incomplete or unavailable \u2014 unsafe to score"});let I=Lr(e),E,S=()=>(E??=I.calleeIndex({minCallees:Math.min(3,r),scanLimit:l,semantic:c}),E);for(let{def:x,callees:C}of y){let L=A(x.symbol);if(C.size<r){d.skipped.push({helperShortName:L,helperFile:x.relativePath,reason:`fewer than ${r} meaningful callees \u2014 too small to score`});continue}let w=S(),R=fj(C,w);if(R===0){d.skipped.push({helperShortName:L,helperFile:x.relativePath,reason:"helper callee pattern is all project-wide infrastructure \u2014 too generic to score"});continue}let M=hj(e,x.symbolId);if(M.length===0){d.skipped.push({helperShortName:L,helperFile:x.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}d.helpersChecked+=1;let _=cj({candidateIndex:w,changed:f,helperCallees:C,helperFile:x.relativePath,helperSymbol:x.symbol,minContainment:i,minSiteCoverage:o,migratedFiles:M});_.length!==0&&(_.sort((D,P)=>UC(P.migrationScope)-UC(D.migrationScope)||P.containment-D.containment||P.siteCoverage-D.siteCoverage||D.file.localeCompare(P.file)),d.findings.push({helperSymbol:x.symbol,helperShortName:L,helperFile:x.relativePath,helperShape:"specific-callee-cluster",helperCalleeCount:C.size,specificHelperCalleeCount:R,migratedFiles:M.sort(),leftovers:_.slice(0,aj)}))}return d.findings.sort((x,C)=>(C.leftovers[0]?.containment??0)-(x.leftovers[0]?.containment??0)||x.helperFile.localeCompare(C.helperFile)),d.findings=d.findings.slice(0,a),d}function cj(e){let t=[],n=uj(e.helperSymbol,e.helperFile,e.migratedFiles),i=new Set;for(let r of e.helperCallees)for(let o of e.candidateIndex.candidateIndexesByCallee.get(r)??[])i.add(o);for(let r of i){let o=e.candidateIndex.corpus[r];if(o.symbol===e.helperSymbol||e.changed.has(o.file)||o.callees.has(e.helperSymbol))continue;let s=Av(e.helperCallees,o.callees);if(s<e.minContainment)continue;let a=[...e.helperCallees].filter(u=>o.callees.has(u)),l=o.callees.size===0?0:a.length/o.callees.size;if(l<e.minSiteCoverage||!a.some(u=>(e.candidateIndex.docFreq.get(u)??0)<=e.candidateIndex.ubiquityThreshold))continue;let c=dj(n,o.symbol,o.file);t.push({symbol:o.symbol,shortName:A(o.symbol),file:o.file,...c,containment:s,siteCoverage:l,uniqueSiteCalleeCount:Math.max(0,o.callees.size-a.length),sharedCallees:a.map(A).sort()})}return t}function UC(e){return e==="same-scope"?2:e==="unknown"?1:0}function uj(e,t,n){let i=new Set([...Xd(t),...Qd(Y(e))]);for(let r of n)for(let o of Xd(r))i.add(o);return i}function dj(e,t,n){let i=new Set([...Xd(n),...Qd(Y(t))]);if(e.size===0||i.size===0)return{migrationScope:"unknown",migrationScopeReasons:["insufficient path/name tokens to infer migration scope"]};let r=[...i].filter(o=>e.has(o)).sort();return r.length>0?{migrationScope:"same-scope",migrationScopeReasons:[`shares migration-scope token(s): ${r.slice(0,5).join(", ")}`]}:{migrationScope:"possible-subtype",migrationScopeReasons:["no path/name tokens shared with the helper or already migrated files"]}}var mj=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 Xd(e){return Qd(e.replace(/\.[^.]+$/,""))}function Qd(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!mj.has(t))}function fj(e,t){let n=0;for(let i of e)(t.docFreq.get(i)??0)<=t.ubiquityThreshold&&(n+=1);return n}function pj(e,t,n,i){let r=[];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=i(s);if(a.state==="unavailable")return{definitions:[],unavailable:a};(a.state==="absent"||!new RegExp(`\\b${Oe(o.leaf)}\\b`).test(a.content))&&r.push(o)}return{definitions:r}}function gj(e){return t=>{let n=e(t);return n===null?{state:"absent"}:{state:"present",content:n}}}function hj(e,t){return e.all(`SELECT DISTINCT ref_d.relative_path
361
361
  FROM mentions m
362
362
  JOIN chunks c ON m.chunk_id = c.id
363
363
  JOIN documents ref_d ON c.document_id = ref_d.id
364
364
  WHERE m.symbol_id = ?
365
365
  AND m.role != 1
366
- ${e.pathExclusionsFor("ref_d")}`,t).map(i=>i.relative_path)}import{execFileSync as Lj}from"child_process";var JC=2e3,yl=50,Dj=64,Mj=8,Pj=3,Tj=2160*60*60,Fj=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,kj=3,Nj=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,Aj=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function _j(e){let t=Fe(e,{clearGroups:["whole-project"]});return(n,i,r)=>{let o=r??im(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:i(n.config.projectRoot,o)})).value)}}function bl(e){let t=Fe(e,{clearGroups:["whole-project"]});return(n,i,r,o)=>{let s=o??im(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 l=t.get(n,()=>({head:s,values:new Map}));if(l.values.has(i))return l.values.get(i)??null;let c=r(n.config.projectRoot,s);return l.values.set(i,c),c}}var Bj=bl("git-commit-history");function Xt(e,t={}){let n=t.historyMode??"bounded",i=t.head;return{capability:r=>Oj(e,r,i),commitHistory:()=>ns(e,n,i),fileChurn:()=>Hj(e,n,i),changeAmplification:()=>Uj(e,n,i),trackedFiles:()=>qj(e,i),fileAddRecords:()=>Gj(e,n,i),coChangePairs:(r={})=>Zj(e,r,n,i),coChangePairsForFiles:(r,o={})=>QC(e,r,o,n,i),directionalCoChangePairsForFiles:(r,o={})=>eH(e,r,o,n,i)}}function ns(e,t="bounded",n){return Bj(e,kr(t),(i,r)=>$j(i,r,t),n)}function Oj(e,t,n){let i=n??im(e.config.projectRoot);return i?{slot:t,available:!0,head:i}:{slot:t,available:!1,head:null,reason:"git history is unavailable for this project"}}function im(e){try{return yn(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function yn(e,t){return Lj("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:3e4,killSignal:"SIGKILL"})}function $j(e,t,n){let i;try{i=yn(e,["log","--no-merges","--name-only",...Sl(n),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}return{head:t,...sm(i,yl)}}function jj(e){return Fj.test(e.subject)}function Hj(e,t,n){let i=ns(e,t,n);if(!i)return null;let r=new Map;for(let o of i.commits){let s=jj(o);for(let a of o.files){let l=r.get(a)??{changes:0,fixChanges:0,lastChangedAt:0};l.changes+=1,s&&(l.fixChanges+=1),o.timestamp>l.lastChangedAt&&(l.lastChangedAt=o.timestamp),r.set(a,l)}}return r}function Uj(e,t,n){let i=ns(e,t,n);if(!i||i.commits.length===0)return null;let r=i.commits.map(o=>o.files.length).filter(o=>o>0).sort((o,s)=>o-s);return r.length===0?null:{medianFilesPerCommit:KC(r,.5),p90FilesPerCommit:KC(r,.9),commitsAnalyzed:r.length}}function KC(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var zj=_j("git-tracked-files");function qj(e,t){return zj(e,n=>{try{let i=yn(n,["ls-files"]);return new Set(i.split(`
367
- `).map(r=>r.trim()).filter(r=>r!==""))}catch{return null}},t)}var Kj=bl("git-file-adds"),GC="__git__/file-adds",WC=Ct({kind:"git-file-adds",invalidation:Ye("git-file-adds"),serialize:Vj,deserialize:Jj});function YC(e){return Xt(e).fileAddRecords()}function Gj(e,t,n){let i=kr(t);return Kj(e,i,(r,o)=>Wj(e,r,o,t),n)}function Wj(e,t,n,i){let r=WC.read(e,VC(i),n);if(r)return r;let o=Yj(t,i);return o&&WC.write(e,VC(i),n,o),o}function Vj(e){return JSON.stringify([...e.entries()])}function Jj(e){if(!e)return null;try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=new Map;for(let i of t){if(!Array.isArray(i)||i.length!==2||typeof i[0]!="string")return null;let r=i[1];if(!r||typeof r.commitsAgo!="number"||!Number.isFinite(r.commitsAgo)||typeof r.addedAt!="number"||!Number.isFinite(r.addedAt))return null;n.set(i[0],{commitsAgo:r.commitsAgo,addedAt:r.addedAt})}return n}catch{return null}}function Yj(e,t){let n;try{n=yn(e,["log","--no-merges","--find-renames","--name-status",...Sl(t),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let i=new Map,r=new Map,o=-1;for(let s of n.split("")){if(s.trim()==="")continue;o+=1;let a=s.indexOf(`
366
+ ${e.pathExclusionsFor("ref_d")}`,t).map(i=>i.relative_path)}import{execFileSync as yj}from"child_process";var WC=2e3,hl=50,bj=64,Sj=8,vj=3,Cj=2160*60*60,xj=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,Rj=3,Ij=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,Ej=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function wj(e){let t=Fe(e,{clearGroups:["whole-project"]});return(n,i,r)=>{let o=r??Zd(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:i(n.config.projectRoot,o)})).value)}}function yl(e){let t=Fe(e,{clearGroups:["whole-project"]});return(n,i,r,o)=>{let s=o??Zd(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 l=t.get(n,()=>({head:s,values:new Map}));if(l.values.has(i))return l.values.get(i)??null;let c=r(n.config.projectRoot,s);return l.values.set(i,c),c}}var Lj=yl("git-commit-history");function Xt(e,t={}){let n=t.historyMode??"bounded",i=t.head;return{capability:r=>Dj(e,r,i),commitHistory:()=>es(e,n,i),fileChurn:()=>Tj(e,n,i),changeAmplification:()=>Fj(e,n,i),trackedFiles:()=>Nj(e,i),fileAddRecords:()=>_j(e,n,i),coChangePairs:(r={})=>zj(e,r,n,i),coChangePairsForFiles:(r,o={})=>YC(e,r,o,n,i),directionalCoChangePairsForFiles:(r,o={})=>qj(e,r,o,n,i)}}function es(e,t="bounded",n){return Lj(e,Tr(t),(i,r)=>Mj(i,r,t),n)}function Dj(e,t,n){let i=n??Zd(e.config.projectRoot);return i?{slot:t,available:!0,head:i}:{slot:t,available:!1,head:null,reason:"git history is unavailable for this project"}}function Zd(e){try{return yn(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function yn(e,t){return yj("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:3e4,killSignal:"SIGKILL"})}function Mj(e,t,n){let i;try{i=yn(e,["log","--no-merges","--name-only",...bl(n),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}return{head:t,...nm(i,hl)}}function Pj(e){return xj.test(e.subject)}function Tj(e,t,n){let i=es(e,t,n);if(!i)return null;let r=new Map;for(let o of i.commits){let s=Pj(o);for(let a of o.files){let l=r.get(a)??{changes:0,fixChanges:0,lastChangedAt:0};l.changes+=1,s&&(l.fixChanges+=1),o.timestamp>l.lastChangedAt&&(l.lastChangedAt=o.timestamp),r.set(a,l)}}return r}function Fj(e,t,n){let i=es(e,t,n);if(!i||i.commits.length===0)return null;let r=i.commits.map(o=>o.files.length).filter(o=>o>0).sort((o,s)=>o-s);return r.length===0?null:{medianFilesPerCommit:zC(r,.5),p90FilesPerCommit:zC(r,.9),commitsAnalyzed:r.length}}function zC(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var kj=wj("git-tracked-files");function Nj(e,t){return kj(e,n=>{try{let i=yn(n,["ls-files"]);return new Set(i.split(`
367
+ `).map(r=>r.trim()).filter(r=>r!==""))}catch{return null}},t)}var Aj=yl("git-file-adds"),qC="__git__/file-adds",KC=Ct({kind:"git-file-adds",invalidation:Ye("git-file-adds"),serialize:Oj,deserialize:$j});function VC(e){return Xt(e).fileAddRecords()}function _j(e,t,n){let i=Tr(t);return Aj(e,i,(r,o)=>Bj(e,r,o,t),n)}function Bj(e,t,n,i){let r=KC.read(e,GC(i),n);if(r)return r;let o=jj(t,i);return o&&KC.write(e,GC(i),n,o),o}function Oj(e){return JSON.stringify([...e.entries()])}function $j(e){if(!e)return null;try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=new Map;for(let i of t){if(!Array.isArray(i)||i.length!==2||typeof i[0]!="string")return null;let r=i[1];if(!r||typeof r.commitsAgo!="number"||!Number.isFinite(r.commitsAgo)||typeof r.addedAt!="number"||!Number.isFinite(r.addedAt))return null;n.set(i[0],{commitsAgo:r.commitsAgo,addedAt:r.addedAt})}return n}catch{return null}}function jj(e,t){let n;try{n=yn(e,["log","--no-merges","--find-renames","--name-status",...bl(t),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let i=new Map,r=new Map,o=-1;for(let s of n.split("")){if(s.trim()==="")continue;o+=1;let a=s.indexOf(`
368
368
  `),l=a>=0?s.slice(0,a):s,[,c]=l.split("\0"),u=Number(c)||0;if(!(a<0))for(let d of s.slice(a+1).split(`
369
- `)){let m=Xj(d);if(!m)continue;if(m.status==="R"&&m.from&&m.to){let p=r.get(m.to)??new Set([m.to]);r.set(m.from,p);continue}if(m.status!=="A"||!m.to)continue;let f={commitsAgo:o,addedAt:u};i.set(m.to,f);for(let p of r.get(m.to)??[])i.set(p,f)}}return i}function Xj(e){let t=e.trim().split(" "),n=t[0]??"";if(!n)return null;let i=n[0]??"";if(i==="R"){let o=t[1],s=t[2];return o&&s?{status:i,from:o,to:s}:null}let r=t[1];return r?{status:i,to:r}:null}var XC=bl("git-co-change-pairs"),Qj=bl("git-directional-co-change-pairs");function Zj(e,t,n,i){let r=`all\0${kr(n)}\0${rm(t)}`,o=XC(e,r,()=>{let s=ns(e,n,i);return s?om(s,t):null},i);return o&&[...o]}function QC(e,t,n,i,r){if(t.size===0)return[];let o=`files\0${kr(i)}\0${ZC(t)}\0${rm(n)}`,s=XC(e,o,()=>{let a=ns(e,i,r);return a?om(a,n,t):null},r);return s&&[...s]}function eH(e,t,n,i,r){if(t.size===0)return[];let o=n.maxFilesPerCommit??yl;if(t.size>Dj)return QC(e,t,n,i,r);let s=`directional\0${kr(i)}\0${ZC(t)}\0${rm({...n,maxFilesPerCommit:o})}`,a=Qj(e,s,(l,c)=>{let u=tH(l,c,t,o,i);return u?om(u,n,t):null},r);return a&&[...a]}function rm(e){let t=e.minTogether??4,n=e.minConfidence??.6,i=e.maxFilesPerCommit??yl;return`${t}\0${n}\0${i}`}function ZC(e){return[...e].sort().join("\0")}function om(e,t,n){let{minTogether:i=4,minConfidence:r=.6,maxFilesPerCommit:o=yl}=t,s=new Map,a=new Map,l=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>l&&(l=d.timestamp);let f=rH(m),p=n===void 0||m.some(g=>n.has(g));for(let g of m)s.set(g,(s.get(g)??0)+1);if(p)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]}`,v=a.get(b)??{together:0,focusedTogether:0,broadTogether:0,lastTogetherAt:0,timestamps:[],subjects:[]};v.together+=1,f?v.broadTogether+=1:v.focusedTogether+=1,d.timestamp>v.lastTogetherAt&&(v.lastTogetherAt=d.timestamp),v.timestamps.push(d.timestamp),v.subjects.push(d.subject),a.set(b,v)}}let c=[],u=l-Tj;for(let[d,m]of a){let f=m.together;if(f<i)continue;let[p,g]=d.split("\0"),h=s.get(p)??f,b=s.get(g)??f,v=Math.max(f/h,f/b);if(v<r)continue;let y=m.broadTogether/f,I=m.timestamps.filter(E=>E>=u).length;c.push({fileA:p,fileB:g,together:f,confidence:v,changesA:h,changesB:b,focusedTogether:m.focusedTogether,broadTogether:m.broadTogether,broadCommitRatio:y,lastTogetherAt:m.lastTogetherAt,recentTogether:I,commitScope:sH(m.broadTogether,f),recency:I>0?"recent":"stale",subjectContext:aH(m.subjects)})}return c.sort((d,m)=>m.together-d.together||m.confidence-d.confidence||d.fileA.localeCompare(m.fileA)),c}function tH(e,t,n,i,r){let o;try{o=nH(e,r)}catch{return null}if(o.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:0};let s;try{s=yn(e,["log","--no-merges","--format=%H",...Sl(r),"--",...[...n].sort()])}catch{return null}let a=new Set(o.map(m=>m.hash)),l=s.split(`
370
- `).map(m=>m.trim()).filter(m=>m!==""&&a.has(m)),c=iH(e,o,i);if(l.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:c};let u;try{u=yn(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...l])}catch{return null}let d=sm(u,i);return{head:t,...d,newestAnalyzedAt:c}}function nH(e,t){return yn(e,["log","--no-merges","--format=%H%x00%ct",...Sl(t)]).split(`
371
- `).map(i=>i.trim()).filter(i=>i!=="").map(i=>{let[r,o]=i.split("\0");return{hash:r??"",timestamp:Number(o)||0}}).filter(i=>i.hash!=="")}function Sl(e){return e==="full"?[]:["-n",String(ex())]}function ex(){return Xn(process.env.CODEBASEIQ_GIT_HISTORY_MAX_COMMITS)??JC}function kr(e){return e==="full"?"full":`bounded:${ex()}`}function VC(e){let t=kr(e);return t===`bounded:${JC}`?GC:`${GC}:${t}`}function iH(e,t,n){for(let r=0;r<t.length;r+=20){let o=t.slice(r,r+20),s;try{s=yn(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...o.map(l=>l.hash)])}catch{return t[0]?.timestamp??0}let a=sm(s,n);if(a.commits.length>0)return a.commits[0].timestamp}return 0}function sm(e,t){let n=[],i=0;for(let r of e.split("")){if(r.trim()==="")continue;let o=r.indexOf(`
369
+ `)){let m=Hj(d);if(!m)continue;if(m.status==="R"&&m.from&&m.to){let p=r.get(m.to)??new Set([m.to]);r.set(m.from,p);continue}if(m.status!=="A"||!m.to)continue;let f={commitsAgo:o,addedAt:u};i.set(m.to,f);for(let p of r.get(m.to)??[])i.set(p,f)}}return i}function Hj(e){let t=e.trim().split(" "),n=t[0]??"";if(!n)return null;let i=n[0]??"";if(i==="R"){let o=t[1],s=t[2];return o&&s?{status:i,from:o,to:s}:null}let r=t[1];return r?{status:i,to:r}:null}var JC=yl("git-co-change-pairs"),Uj=yl("git-directional-co-change-pairs");function zj(e,t,n,i){let r=`all\0${Tr(n)}\0${em(t)}`,o=JC(e,r,()=>{let s=es(e,n,i);return s?tm(s,t):null},i);return o&&[...o]}function YC(e,t,n,i,r){if(t.size===0)return[];let o=`files\0${Tr(i)}\0${XC(t)}\0${em(n)}`,s=JC(e,o,()=>{let a=es(e,i,r);return a?tm(a,n,t):null},r);return s&&[...s]}function qj(e,t,n,i,r){if(t.size===0)return[];let o=n.maxFilesPerCommit??hl;if(t.size>bj)return YC(e,t,n,i,r);let s=`directional\0${Tr(i)}\0${XC(t)}\0${em({...n,maxFilesPerCommit:o})}`,a=Uj(e,s,(l,c)=>{let u=Kj(l,c,t,o,i);return u?tm(u,n,t):null},r);return a&&[...a]}function em(e){let t=e.minTogether??4,n=e.minConfidence??.6,i=e.maxFilesPerCommit??hl;return`${t}\0${n}\0${i}`}function XC(e){return[...e].sort().join("\0")}function tm(e,t,n){let{minTogether:i=4,minConfidence:r=.6,maxFilesPerCommit:o=hl}=t,s=new Map,a=new Map,l=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>l&&(l=d.timestamp);let f=Vj(m),p=n===void 0||m.some(g=>n.has(g));for(let g of m)s.set(g,(s.get(g)??0)+1);if(p)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]}`,v=a.get(b)??{together:0,focusedTogether:0,broadTogether:0,lastTogetherAt:0,timestamps:[],subjects:[]};v.together+=1,f?v.broadTogether+=1:v.focusedTogether+=1,d.timestamp>v.lastTogetherAt&&(v.lastTogetherAt=d.timestamp),v.timestamps.push(d.timestamp),v.subjects.push(d.subject),a.set(b,v)}}let c=[],u=l-Cj;for(let[d,m]of a){let f=m.together;if(f<i)continue;let[p,g]=d.split("\0"),h=s.get(p)??f,b=s.get(g)??f,v=Math.max(f/h,f/b);if(v<r)continue;let y=m.broadTogether/f,I=m.timestamps.filter(E=>E>=u).length;c.push({fileA:p,fileB:g,together:f,confidence:v,changesA:h,changesB:b,focusedTogether:m.focusedTogether,broadTogether:m.broadTogether,broadCommitRatio:y,lastTogetherAt:m.lastTogetherAt,recentTogether:I,commitScope:Yj(m.broadTogether,f),recency:I>0?"recent":"stale",subjectContext:Xj(m.subjects)})}return c.sort((d,m)=>m.together-d.together||m.confidence-d.confidence||d.fileA.localeCompare(m.fileA)),c}function Kj(e,t,n,i,r){let o;try{o=Gj(e,r)}catch{return null}if(o.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:0};let s;try{s=yn(e,["log","--no-merges","--format=%H",...bl(r),"--",...[...n].sort()])}catch{return null}let a=new Set(o.map(m=>m.hash)),l=s.split(`
370
+ `).map(m=>m.trim()).filter(m=>m!==""&&a.has(m)),c=Wj(e,o,i);if(l.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:c};let u;try{u=yn(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...l])}catch{return null}let d=nm(u,i);return{head:t,...d,newestAnalyzedAt:c}}function Gj(e,t){return yn(e,["log","--no-merges","--format=%H%x00%ct",...bl(t)]).split(`
371
+ `).map(i=>i.trim()).filter(i=>i!=="").map(i=>{let[r,o]=i.split("\0");return{hash:r??"",timestamp:Number(o)||0}}).filter(i=>i.hash!=="")}function bl(e){return e==="full"?[]:["-n",String(QC())]}function QC(){return Xn(process.env.CODEBASEIQ_GIT_HISTORY_MAX_COMMITS)??WC}function Tr(e){return e==="full"?"full":`bounded:${QC()}`}function GC(e){let t=Tr(e);return t===`bounded:${WC}`?qC:`${qC}:${t}`}function Wj(e,t,n){for(let r=0;r<t.length;r+=20){let o=t.slice(r,r+20),s;try{s=yn(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...o.map(l=>l.hash)])}catch{return t[0]?.timestamp??0}let a=nm(s,n);if(a.commits.length>0)return a.commits[0].timestamp}return 0}function nm(e,t){let n=[],i=0;for(let r of e.split("")){if(r.trim()==="")continue;let o=r.indexOf(`
372
372
  `),s=o>=0?r.slice(0,o):r,[a,l,c]=s.split("\0");if(!a||!l)continue;let u=o>=0?r.slice(o+1).split(`
373
- `).map(d=>d.trim()).filter(d=>d!==""):[];if(u.length>t){i+=1;continue}n.push({hash:a,timestamp:Number(l)||0,subject:c??"",files:u})}return{commits:n,skippedBulkCommits:i}}function rH(e){return e.length>=Mj?!0:oH(e).size>=Pj}function oH(e){let t=new Set;for(let n of e){let i=n.indexOf("/");t.add(i>=0?n.slice(0,i):".")}return t}function sH(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function aH(e){let t=new Set,n=[],i=[];for(let r of e){!i.includes(r)&&i.length<kj&&i.push(r);for(let o of lH(r))t.add(o);for(let o of r.match(Nj)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:i,externalIssueLabelStatus:"unavailable"}}function lH(e){let t=new Set,n=Aj.exec(e)?.[1]?.toLowerCase();return n&&t.add(cH(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 cH(e){return e==="feat"?"feature":e}var tx=/(?:^|\/)(?: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 is(e,t,n={}){let{minTogether:i=4,minConfidence:r=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=Xt(e,{historyMode:n.historyMode,...n.head?{head:n.head}:{}}),l=a.commitHistory(),c=t!==void 0,u=a.coChangePairs({minTogether:c?Math.min(i,2):i,minConfidence:c?0:r,maxFilesPerCommit:s});if(!l||!u)return{available:!1,commitsAnalyzed:0,findings:[]};let d=typeof n.scanLimit=="number"?u.slice(0,n.scanLimit):u,m=$e(e),f=sx(e),p=mH(e,m,f),g=n.includeLinked===!0||c,h=[];for(let b of d){if(tx.test(b.fileA)||tx.test(b.fileB)||!nx(e,b.fileA)||!nx(e,b.fileB)||c&&!b.fileA.includes(t)&&!b.fileB.includes(t)||!c&&(J(b.fileA)==="test"||J(b.fileB)==="test"||hH(b.fileA,b.fileB)||pH(b.fileA,b.fileB)))continue;let v=p(b.fileA,b.fileB);if(!g&&v)continue;let y=uH(b.fileA,b.fileB),I=dH(b,y,v);if(h.push({...b,structurallyLinked:v,partnerClass:y.partnerClass,partnerClassReasons:y.reasons,...I?{declaredCouplingSuggestion:I}:{}}),h.length>=o)break}return{available:!0,commitsAnalyzed:l.commits.length,findings:h}}function nx(e,t){return Ft(e.config.projectRoot,t)}function uH(e,t){let n=rx(e),i=rx(t),r=[],o=l=>{r.includes(l)||r.push(l)},s=(l,c)=>n.tags.has(l)&&i.tags.has(c)||n.tags.has(c)&&i.tags.has(l);if(s("doc","code"))return o("one side is documentation and the other is executable source"),{partnerClass:"doc-code",reasons:r};if(n.tags.has("test")||i.tags.has("test"))return o("one side is classified as a test file"),{partnerClass:"test-code",reasons:r};if(s("schema","script"))return o("schema or contract file changes with a script or generated-code path"),{partnerClass:"schema-script",reasons:r};if(s("model","view"))return o("model or state path changes with a view or component path"),{partnerClass:"model-view",reasons:r};if(s("config","code"))return o("configuration file changes with executable source"),{partnerClass:"config-code",reasons:r};let a=LH(n.tokens,i.tokens).filter(l=>!EH.has(l));return ox(e,t)||a.length>=2?(o(ox(e,t)?"both files live in the same directory":`files share feature tokens: ${a.slice(0,4).join(", ")}`),{partnerClass:"same-feature",reasons:r}):(o("no specific relationship pattern matched"),{partnerClass:"unknown",reasons:r})}function dH(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!IH.has(t.partnerClass))return;let i=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${DH(i)}`,files:i,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 mH(e,t=$e(e),n=sx(e)){return(i,r)=>yH(t,n,i,r)}var fH=/(?:^|\/)(?:locales|i18n)\//i;function ix(e){return fH.test(e)}function pH(e,t){return ix(e)&&ix(t)?!0:gH(e,t)}function gH(e,t){if(!e.endsWith(".json")||!t.endsWith(".json"))return!1;let n=e.lastIndexOf("/"),i=t.lastIndexOf("/");if(n<0||i<0)return!1;let r=e.slice(0,n),o=t.slice(0,i);if(r===o)return!1;let s=e.slice(n+1),a=t.slice(i+1);if(s!==a)return!1;let l=r.lastIndexOf("/"),c=o.lastIndexOf("/"),u=l>=0?r.slice(0,l):"",d=c>=0?o.slice(0,c):"";return u===d}function hH(e,t){let n=e.lastIndexOf("/"),i=t.lastIndexOf("/");if(e.slice(0,n)!==t.slice(0,i))return!1;let r=e.slice(n+1).split(".")[0],o=t.slice(i+1).split(".")[0];return r!==""&&r===o}function sx(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function yH(e,t,n,i){return e.get(n)?.has(i)===!0||e.get(i)?.has(n)===!0?!0:t.some(r=>r.has(n)&&r.has(i))}var bH=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,SH=/(?:^|\/)(?:\.[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,vH=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,CH=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,xH=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,RH=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,IH=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),EH=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 rx(e){let t=e.replace(/\\/g,"/"),n=new Set;return bH.test(t)&&n.add("doc"),SH.test(t)&&n.add("config"),vH.test(t)&&n.add("schema"),CH.test(t)&&n.add("script"),xH.test(t)&&n.add("model"),RH.test(t)&&n.add("view"),J(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:wH(t)}}function ox(e,t){let n=e.lastIndexOf("/"),i=t.lastIndexOf("/"),r=n>=0?e.slice(0,n):"",o=i>=0?t.slice(0,i):"";return r!==""&&r===o}function wH(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 LH(e,t){let n=new Set(t);return[...new Set(e.filter(i=>n.has(i)))].sort()}function DH(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}function xl(e,t){let n=MH(e,t)??PH(e,t)??TH(e,t)??FH(e,t);return kH(e,n,t)}function MH(e,t){let n=-1,i=null;for(let r=0;r<=t;r+=1){let o=am(e[r]??"");o&&(i===null?(i=o,n=r):o===i&&(i=null,n=-1))}if(i===null||n<0)return null;for(let r=t+1;r<e.length;r+=1)if(am(e[r]??"")===i)return{start:n,end:r+1};return{start:n,end:e.length}}function am(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function PH(e,t){if(!vl(e[t]??""))return null;let n=t;for(;n>0&&vl(e[n-1]??"");)n-=1;let i=t+1;for(;i<e.length&&vl(e[i]??"");)i+=1;return{start:n,end:i}}function vl(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function TH(e,t){let n=t;for(;n>=0;){let o=e[n]??"";if(Cl(o)!==null)break;if(lm(o)!==null)return null;n-=1}if(n<0)return null;let i=Cl(e[n]??"");if(i===null)return null;let r=n+1;for(;r<e.length;){let o=e[r]??"",s=Cl(o);if(s!==null){if(s<=i)break;r+=1;continue}if(lm(o)!==null)break;r+=1}return{start:n,end:r}}function Cl(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function FH(e,t){let n=e[t]??"";if(lx(n)||n.trim().length===0)return{start:t,end:t+1};let i=t;for(;i>0&&ax(e[i-1]??"");)i-=1;let r=t+1;for(;r<e.length&&ax(e[r]??"");)r+=1;return{start:i,end:r}}function ax(e){return lm(e)===null}function lm(e){return e.trim().length===0?"blank":lx(e)?"heading":am(e)?"fence":vl(e)?"table":Cl(e)!==null?"list":null}function lx(e){return/^#{1,6}\s+/.test(e.trim())}function kH(e,t,n){let{start:i,end:r}=t;if(r-i>40){let s=Math.floor(20);i=Math.max(i,n-s),r=Math.min(r,i+40),i=Math.max(t.start,r-40)}let o=e.slice(i,r).join(`
374
- `).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}function Ui(e,t){return t.filter(n=>e.includes(n))}var NH=/<!--\s*codebaseiq:\s*snapshot\s*-->/i;function cx(e,t){if((e.config.docs?.snapshotPaths??[]).some(r=>si(r,t)))return!0;let i=se(e,t);return i.length>0&&NH.test(i)}var ux={classifyCitation:_H,citationContexts:BH,citationKindLabel:$H,citationRemediation:jH,referenceTargets:HH,hasLineAnchoredCitation:AH};function AH(e){return e.some(t=>(t.lineReferences?.length??0)>0)}function _H(e){let t=e.join(`
375
- `).toLowerCase(),n=[],i=Ui(t,[".codebaseiq","declaredcouplings","suppression","suppressions","config","configuration","json"]);if(i.length>0)return n.push(`configuration/example terms near citation: ${i.join(", ")}`),{citationKind:"configuration-example",actionTier:"support",reasons:n};let r=Ui(t,["accepted","intentional","intentionally","retained","historical"]);if(r.length>0)return n.push(`intentional-record terms near citation: ${r.join(", ")}`),{citationKind:"intentional-record",actionTier:"support",reasons:n};let o=Ui(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 BH(e,t,n){let i=se(e,t);if(!i&&!Ft(e.config.projectRoot,t))return[];let r=i.split(/\r?\n/),o=n.flatMap(OH),s=[];for(let a=0;a<r.length;a+=1){let l=r[a]??"";o.some(c=>l.includes(c))&&s.push(xl(r,a))}return s}function OH(e){let t=e.split("/");return[e,`./${e}`,t.slice(-3).join("/"),t.slice(-2).join("/")].filter((n,i,r)=>n.length>0&&r.indexOf(n)===i)}function $H(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 jH(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 HH(e,t,n){let i=pl(n),r=new Set;for(let o of t)UH(e,o,i.get(o)??[])&&r.add(o);return r}function UH(e,t,n){if(!zH.test(t)||!Ft(e.config.projectRoot,t))return!0;if(n.length===0)return!1;let i=rt(e.config.projectRoot,t,{inputKind:"changed source file"}).split(/\r?\n/),r=qH(i);for(let o of n)for(let s=o.startLine;s<=o.endLine;s+=1)if((i[s]??"").trim()!==""&&!r.has(s))return!0;return!1}var zH=/\.(?:[cm]?[jt]sx?)$/i;function qH(e){let t=new Set,n=!1;for(let i=0;i<e.length;i+=1){let r=e[i].trim();!n&&KH(r)&&(n=!0),n&&(t.add(i),r.endsWith(";")&&(n=!1))}return t}function KH(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}var dx=Ct({kind:"doc-path-evidence",invalidation:Ye("doc-path-evidence"),serialize:oU,deserialize:sU}),rs=/\.(?:md|mdx|rst|txt)$/i;function GH(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var WH=3,VH=/([A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6})(?::([1-9][0-9]*))?\b/g;function JH(e,t={}){let{doc:n,limit:i=20,minCoupling:r=WH,includeSnapshotExcluded:o=!1}=t,s=ZH(e,t.historyMode??"bounded");if(!s)return{available:!1,commitsAnalyzed:0,docsScanned:0,findings:[]};let a=[];for(let l of s.docFiles){if(n!==void 0&&!l.includes(n)||n===void 0&&!eU(e,l)||n!==void 0&&!Ft(e.config.projectRoot,l))continue;let c=cx(e,l);if(c&&!o)continue;let{value:u,estimated:d}=YH(e,l,s.changeTimes.get(l)),m=XH(e,l),f=new Map,{resolved:p,broken:g,citations:h}=nU(e,l,s.tracked,s.trackedBySuffix,s.everSeenInHistory),b=new Map(h.map(y=>[y.file,y]));for(let y of p){if(y===l||rs.test(y))continue;let I=(s.changeTimes.get(y)??[]).filter(S=>S>u).length;if(I===0)continue;let E=b.get(y);f.set(y,{file:y,evidence:"reference",coChanges:0,changesSinceDocUpdate:I,...cm("reference",m,E?.contexts),citationContexts:E?.contexts,citedLines:E?.lineReferences})}for(let[y,I]of s.coupling.get(l)??[]){if(I<r||!s.tracked.has(y))continue;let E=(s.changeTimes.get(y)??[]).filter(x=>x>u).length;if(E===0)continue;let S=f.get(y);S?(S.evidence="both",S.coChanges=I,Object.assign(S,cm("both",m,S.citationContexts))):f.set(y,{file:y,evidence:"co-change",coChanges:I,changesSinceDocUpdate:E,...cm("co-change",m)})}if(f.size===0&&g.length===0)continue;let v=[...f.values()].sort((y,I)=>I.changesSinceDocUpdate-y.changesSinceDocUpdate);a.push({doc:l,docLastChangedAt:u,staleness:v.reduce((y,I)=>y+I.changesSinceDocUpdate,0)+g.length*10,subjects:v.slice(0,8),brokenReferences:g,...c?{snapshotExcluded:!0}:{},...d?{docLastChangedAtEstimated:!0}:{}})}return a.sort((l,c)=>c.staleness-l.staleness),{available:!0,commitsAnalyzed:s.historyCommitCount,docsScanned:s.docFiles.length,findings:a.slice(0,i)}}function YH(e,t,n){if(n&&n.length>0)return{value:Math.max(...n),estimated:!1};try{return{value:Math.floor(Rs(e.config.projectRoot,t).mtimeMs/1e3),estimated:!0}}catch(i){if(Ft(e.config.projectRoot,t))throw i;return{value:0,estimated:!1}}}function XH(e,t){let n=se(e,t).slice(0,6e3);if(!n)return{docIntent:"unknown",reasons:["doc text unavailable"]};let i=`${t}
376
- ${n}`.toLowerCase(),r=Ui(i,["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(r.length>0)return{docIntent:"historical-note",reasons:[`historical-note terms: ${r.join(", ")}`]};let o=Ui(i,["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 cm(e,t,n=[]){let i=e==="co-change"||n.length===0?null:ux.classifyCitation(n);return{actionTier:QH(e,t.docIntent,i?.actionTier),docIntent:t.docIntent,docIntentReasons:t.reasons,...i?{citationKind:i.citationKind,citationKindReasons:i.reasons}:{}}}function QH(e,t,n){return t==="historical-note"?"support":n||(e==="co-change"?"signal":"direct")}function ZH(e,t){let n=Xt(e,{historyMode:t}),i=n.commitHistory();if(!i)return null;let r=n.trackedFiles()??new Set,o=new Map,s=new Map,a=new Set;for(let l of i.commits){let c=[...new Set(l.files)],u=c.filter(m=>rs.test(m)),d=c.filter(m=>!rs.test(m));for(let m of c){a.add(m);let f=o.get(m)??[];f.push(l.timestamp),o.set(m,f)}for(let m of u){let f=s.get(m);f||(f=new Map,s.set(m,f));for(let p of d)f.set(p,(f.get(p)??0)+1)}}return{changeTimes:o,coupling:s,docFiles:[...r].filter(l=>rs.test(l)),everSeenInHistory:a,historyCommitCount:i.commits.length,tracked:r,trackedBySuffix:tU(r)}}function eU(e,t){return rs.test(t)&&!GH(t)&&Ft(e.config.projectRoot,t)}function tU(e){let t=new Map;for(let n of e){let i=n.split("/");for(let r of[2,3]){if(i.length<r)continue;let o=i.slice(-r).join("/"),s=t.get(o)??[];s.push(n),t.set(o,s)}}return t}function nU(e,t,n,i,r){let o=new Set,s=new Set,a=iU(e,t);if(!a)return{resolved:o,broken:[],citations:[]};let l=a.candidates,c=a.contextsByCandidate,u=a.lineReferencesByCandidate,d=new Map,m=new Map,f=(p,g)=>{let h=c.get(g);if(h&&h.length>0){let v=d.get(p)??[];v.push(...h),d.set(p,mx(v).slice(0,3))}let b=u.get(g);b&&b.length>0&&m.set(p,um([...m.get(p)??[],...b]))};for(let p of l){if(n.has(p)){o.add(p),f(p,p);continue}let g=i.get(p);if(g&&g.length===1){o.add(g[0]),f(g[0],p);continue}g&&g.length>1||r.has(p)&&s.add(p)}return{resolved:o,broken:[...s],citations:[...d].map(([p,g])=>({file:p,contexts:g,lineReferences:m.get(p)}))}}function iU(e,t,n){let i=n;if(i===void 0&&(i=se(e,t),!i&&!Ft(e.config.projectRoot,t)))return null;let r=Nt(e,t,i),o=dx.read(e,t,r);if(o)return o;let s=rU(i);return dx.write(e,t,r,s),s}function rU(e){let t=e.split(/\r?\n/),n=new Set,i=new Map,r=new Map;for(let o=0;o<t.length;o+=1){let s=t[o]??"";for(let a of s.matchAll(VH)){let l=(a[1]??"").replace(/^\.?\//,"");if(l.length===0)continue;n.add(l);let c=a[2]?Number(a[2]):null;c!==null&&Number.isSafeInteger(c)&&r.set(l,um([...r.get(l)??[],c]));let u=xl(t,o);if(u.length===0)continue;let d=i.get(l)??[];d.push(u),i.set(l,mx(d).slice(0,3))}}return{candidates:[...n],contextsByCandidate:i,lineReferencesByCandidate:r}}function oU(e){let t={candidates:e.candidates,contextsByCandidate:[...e.contextsByCandidate.entries()],lineReferencesByCandidate:[...e.lineReferencesByCandidate.entries()]};return JSON.stringify(t)}function sU(e){try{let t=JSON.parse(e);if(!ff(t))return null;let n=Ql(t.candidates),i=lU(t.contextsByCandidate),r=aU(t.lineReferencesByCandidate);return!n||!i?null:{candidates:n,contextsByCandidate:new Map(i),lineReferencesByCandidate:new Map(r??[])}}catch{return null}}function aU(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 i=[];for(let r of n[1]){if(typeof r!="number"||!Number.isSafeInteger(r))return null;i.push(r)}t.push([n[0],um(i)])}return t}function lU(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 i=Ql(n[1]);if(!i)return null;t.push([n[0],i])}return t}function mx(e){let t=[];for(let n of new Set(e))t.some(i=>cU(i,n))||t.push(n);return t}function um(e){return[...new Set(e)].sort((t,n)=>t-n)}function cU(e,t){if(e===t)return!0;let n=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),i=t.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),r=Math.min(n.length,i.length);if(r===0)return!1;if(r<3)return e.includes(t)||t.includes(e);let o=new Set(i),s=n.filter(a=>o.has(a)).length;return s>=3&&s/r>=.6}import{createHash as uU}from"crypto";var dU=3;function os(e,t={}){let{scope:n,maxLoc:i=15,minLoc:r=dU,limit:o,scanLimit:s}=t,a=YC(e),l=mU(e,{scope:n,maxLoc:i,scanLimit:s}).map(u=>fU(e,u,a,r)).filter(u=>u!==null),c=gx(l);return o?c.slice(0,o):c}function px(e){let t=bn(e);return xn(t).replace(/\s+/g,"")}function gx(e){let t=new Map;for(let i of e){if(i.normalizedBody.length<8)continue;let r=gU(i.normalizedBody),o=t.get(r)??[];o.push(i),t.set(r,o)}let n=[];for(let[i,r]of t){let o=new Set(r.map(a=>a.file));if(r.length<2||o.size<2)continue;let s=[...r].sort(hU).map(({normalizedBody:a,...l})=>l);n.push({hash:i,canonical:s[0],functions:s})}return n.sort((i,r)=>{let o=r.functions.length-i.functions.length;if(o!==0)return o;let s=fx(r)-fx(i);return s!==0?s:i.canonical.file.localeCompare(r.canonical.file)}),n}function mU(e,t){let n=Ue(e,{scope:t.scope}).filter(i=>i.isFunctionLike&&!e.isIgnored(i.relativePath)).filter(i=>!Ps(e,i.relativePath,i.startLine,"similar")).filter(i=>de(i)<=t.maxLoc);return n.sort((i,r)=>de(r)-de(i)||i.relativePath.localeCompare(r.relativePath)),ke(n,t.scanLimit)}function fU(e,t,n,i){let r=Qt(e,t);if(!r||pU(r)<i)return null;let o=dm(e,t);return o?{symbol:t.symbol,shortName:A(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:de(t),ageCommits:n?.get(t.relativePath)?.commitsAgo??null,normalizedBody:o}:null}function dm(e,t){let n=Qt(e,t);return n&&px(n)||null}function Qt(e,t){let n=re(e,t.relativePath);return n.length===0?null:n.slice(t.startLine,t.endLine+1).join(`
377
- `)}function bn(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(t>=0&&n>t)return e.slice(t+1,n);let i=e.indexOf("=>");return i>=0?e.slice(i+2).replace(/;+\s*$/,""):e}function pU(e){return bn(e).split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0).length}function gU(e){return uU("sha256").update(e).digest("hex").slice(0,16)}function hU(e,t){let n=e.ageCommits??-1;return(t.ageCommits??-1)-n||e.file.localeCompare(t.file)||e.startLine-t.startLine}function fx(e){return e.functions.reduce((t,n)=>t+n.loc,0)}var yU=new Set(on());function bU(e,t={}){let{includeHomonyms:n=!1,limit:i}=t,r=Rl(e,t).filter(o=>o.relationship==="divergent"||n&&o.relationship==="homonym");return i?r.slice(0,i):r}function Rl(e,t={}){let{scope:n,minSimilarity:i=.3,scanLimit:r}=t,o=CU(e,{scope:n,scanLimit:r});return bx(o,{minSimilarity:i,isDelegatePair:zU(e)}).filter(s=>!s.members.some(a=>Ps(e,a.file,a.startLine,"twin")))}function bx(e,t={}){let n=t.minSimilarity??.3,i=t.isDelegatePair,r=e.filter(c=>!Ex(c.leaf)&&!FU(c.leaf)&&J(c.file)!=="test"&&!Xe(c.symbol)&&!vx(c.symbol)&&!Cx(c.symbol,c.leaf)),{recordsByLeaf:o,recordOrder:s}=B("twin-drift.group-by-leaf",()=>SU(r),()=>({records:r.length})),a=B("twin-drift.cluster-leaf-names",()=>Sx([...o.keys()]),()=>({leaves:o.size}));return B("twin-drift.compare-clusters",()=>{let c=[];for(let u of a){let d=vU(u,o,s);if(d.length<2||new Set(d.map(v=>v.file)).size<2)continue;let m=null,f=!1,p=!1,g=new Set;for(let v=0;v<d.length;v+=1)for(let y=v+1;y<d.length;y+=1){let I=d[v],E=d[y];if(I.file===E.file||!_U(I,E)||i?.(I,E,d)||i?.(E,I,d))continue;if(f=!0,g.add(I.symbol),g.add(E.symbol),I.normalizedBody===E.normalizedBody){p=!0;continue}let S=DU(I.tokens,E.tokens);(!m||S>m.similarity)&&(m={a:I,b:E,similarity:S})}if(!f)continue;let h=d.filter(v=>g.has(v.symbol)).sort((v,y)=>v.file.localeCompare(y.file)||v.startLine-y.startLine).map(LU);if(!m){c.push({leaf:yx(u),relationship:p?"identical":"homonym",maxDivergence:0,members:h});continue}let b=m.similarity>=n?"divergent":"homonym";c.push({leaf:yx(u),relationship:b,maxDivergence:Math.round((1-m.similarity)*1e3)/1e3,members:h,...b==="divergent"?{firstDivergentTokens:MU(m.a.tokens,m.b.tokens)}:{}})}return c},()=>({clusters:a.length,records:r.length})).sort((c,u)=>u.members.length-c.members.length||u.maxDivergence-c.maxDivergence||c.leaf.localeCompare(u.leaf))}function SU(e){let t=new Map,n=new Map;for(let[i,r]of e.entries()){let o=t.get(r.leaf)??[];o.push(r),t.set(r.leaf,o),n.set(r,i)}return{recordsByLeaf:t,recordOrder:n}}function vU(e,t,n){let i=[...e].flatMap(r=>t.get(r)??[]);return e.size>1&&i.sort((r,o)=>(n.get(r)??0)-(n.get(o)??0)),i}function CU(e,t){let n=B("twin-drift.load-definitions",()=>Ue(e,{scope:t.scope}).filter(o=>xU(o)&&!e.isIgnored(o.relativePath)).filter(o=>!fr(o.relativePath)));B("twin-drift.sort-definitions",()=>n.sort((o,s)=>o.relativePath.localeCompare(s.relativePath)||o.startLine-s.startLine),()=>({definitions:n.length}));let i=ke(n,t.scanLimit),r=B("twin-drift.select-candidates",()=>RU(i),()=>({scanned:i.length}));return B("twin-drift.build-records",()=>{let o=[];for(let s of r){let a=IU(e,s);a&&o.push(a)}return o},()=>({candidates:r.length,scanned:i.length}))}function xU(e){return e.isFunctionLike?e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&yU.has(e.kind):!0:!1}function RU(e){let t=e.filter(o=>o.leaf&&!Ex(o.leaf)&&!Xe(o.symbol)&&!vx(o.symbol)&&!Cx(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 i=Sx([...n.keys()]),r=new Set;for(let o of i){let s=[...o].flatMap(a=>n.get(a)??[]);if(!(s.length<2)&&!(new Set(s.map(a=>a.relativePath)).size<2)&&!s.every(a=>J(a.relativePath)==="test"))for(let a of s)r.add(a)}return e.filter(o=>r.has(o))}function IU(e,t){if(!t.leaf)return null;let n=Qt(e,t);if(!n||!st(t.symbol)&&!EU(n,t.leaf))return null;let i=xn(bn(n)),r=i.replace(/\s+/g,"");if(!r||r.length<8)return null;let o=i.match(wU)??[];return o.length===0?null:{leaf:t.leaf,symbol:t.symbol,shortName:A(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:de(t),normalizedBody:r,tokens:o,isThinForwarder:Rx(i)}}function EU(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 wU=/[A-Za-z_$][A-Za-z0-9_$]*|\d+(?:\.\d+)?|[^\sA-Za-z0-9_$]/g;function LU(e){return{symbol:e.symbol,shortName:e.shortName,file:e.file,startLine:e.startLine,endLine:e.endLine,loc:e.loc}}function DU(e,t){let n=new Set(e),i=new Set(t);if(n.size===0&&i.size===0)return 1;if(n.size===0||i.size===0)return 0;let r=0;for(let s of n)i.has(s)&&(r+=1);let o=n.size+i.size-r;return o===0?0:r/o}function MU(e,t){let n=Math.min(e.length,t.length),i=0;for(;i<n&&e[i]===t[i];)i+=1;let r=e.slice(i,i+6).join(" "),o=t.slice(i,i+6).join(" ");return!r&&!o?"(bodies differ only in trailing length)":`A: ${r||"(end)"} | B: ${o||"(end)"}`}function Sx(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 l=s;for(;t.get(l)!==a;){let c=t.get(l);t.set(l,a),l=c}return a},i=(s,a)=>{let l=n(s),c=n(a);l!==c&&t.set(l,c)},r=new Map;for(let s of e){let a=s.slice(0,2).toLowerCase(),l=r.get(a)??[];l.push(s),r.set(a,l)}for(let s of r.values())for(let a=0;a<s.length;a+=1)for(let l=a+1;l<s.length;l+=1)PU(s[a],s[l])&&i(s[a],s[l]);let o=new Map;for(let s of e){let a=n(s),l=o.get(a)??new Set;l.add(s),o.set(a,l)}return[...o.values()]}function PU(e,t){return e===t||e.toLowerCase()===t.toLowerCase()?!0:e.length<8||t.length<8||Math.abs(e.length-t.length)>2||TU(e.toLowerCase(),t.toLowerCase())/Math.max(e.length,t.length)<.8?!1:BU(e.toLowerCase(),t.toLowerCase(),2)}function TU(e,t){let n=Math.min(e.length,t.length),i=0;for(;i<n&&e[i]===t[i];)i+=1;return i}function FU(e){return/^[A-Z][A-Z0-9_]*$/.test(e)||/^__[^_].*__$/.test(e)||kU.has(e.toLowerCase())}var kU=new Set(["main","row"]),NU=new Set(["app","component","components","feature","features","impl","index","lib","route","routes","shared","src","tsx","typescript","ui"]);function vx(e){return e.startsWith("rust-analyzer ")&&/\/(?:tests?|benches?)\//.test(e)}var AU=new Set(["default","new","reset"]);function Cx(e,t){return e.startsWith("rust-analyzer ")&&AU.has(t.toLowerCase())}function _U(e,t){if(e.leaf.toLowerCase()!==t.leaf.toLowerCase()||e.leaf.length>4)return!0;let n=hx(e);return[...hx(t)].some(i=>n.has(i))}function hx(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&&!NU.has(n)))}function BU(e,t,n){if(Math.abs(e.length-t.length)>n)return!1;let i=Array.from({length:t.length+1},(r,o)=>o);for(let r=1;r<=e.length;r+=1){let o=[r],s=o[0];for(let a=1;a<=t.length;a+=1){let l=e[r-1]===t[a-1]?0:1,c=Math.min(i[a]+1,o[a-1]+1,i[a-1]+l);o.push(c),s=Math.min(s,c)}if(s>n)return!1;i=o}return i[t.length]<=n}function xx(e){return Rx(xn(bn(e)))}function Rx(e){let t=e.trim();if(!t||OU.test(t))return!1;let n=HU(t);return n.length===0||n.length>2?!1:jU(n[n.length-1])}var OU=/\b(?:if|else|for|while|switch|try|catch|do)\b/,$U=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^[\]]*\])*\((?:[^()]|\([^()]*\))*\)$/;function jU(e){let t=e.trim().replace(/^return\s+/,"").replace(/^await\s+/,"").replace(/;\s*$/,"").trim();return $U.test(t)}function HU(e){let t=[],n=0,i="";for(let r of e){if(r==="("||r==="["||r==="{"?n+=1:(r===")"||r==="]"||r==="}")&&(n=Math.max(0,n-1)),r===";"&&n===0){t.push(i),i="";continue}i+=r}return i.trim()&&t.push(i),t.map(r=>r.trim()).filter(r=>r.length>0)}var UU=3;function zU(e){let t=new Map;return(n,i,r)=>{if(!n.isThinForwarder)return!1;let o=`${n.symbol}\0${i.symbol}`,s=t.get(o);if(s!==void 0)return s;let a=Ix(e,n,i,r,UU,new Set);return t.set(o,a),a}}function Ix(e,t,n,i,r,o){if(r<=0||o.has(t.symbol)||(o.add(t.symbol),(tn(e,t.file)??[]).filter(l=>l.line>=t.startLine&&l.line<=t.endLine&&l.calleeLeaf===n.leaf).length===0))return!1;let a=new Set(Ce(e,t.file).filter(l=>l.sourcePath&&(l.kind!=="namespace"||l.usedMembers.includes(n.leaf))).map(l=>l.sourcePath));if([...a].some(l=>Tt(l,n.file)))return!0;for(let l of i)if(!(l.symbol===t.symbol||l.symbol===n.symbol||!l.isThinForwarder)&&[...a].some(c=>Tt(c,l.file))&&Ix(e,l,n,i,r-1,o))return!0;return!1}function Ex(e){return e.startsWith("<")&&e.endsWith(">")}function yx(e){return[...e].sort()[0]}import{dirname as rz,isAbsolute as oz,relative as sz,resolve as az}from"path";import{basename as wx,extname as Lx}from"path";function Il(e,t,n,i,r,o){let s=new Set;KU(e,t,n,i)&&s.add(r);for(let a of o)a.value&&qU(s,a.label,a.value);return[...s].slice(0,6)}function qU(e,t,n){let i=GU(n);t.endsWith("name")&&WU(i)&&e.add(`${t} has type-guard boundary shape`);for(let r of i){let o=VU.get(r);o&&e.add(`${t} has ${o} term: ${r}`)}}function KU(e,t,n,i){if(n<=0)return!1;let r=re(e,t);if(r.length===0)return!1;for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(r[o]??"").trim();if(s!==""){if(Ds(s)===i)return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function GU(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 WU(e){return e.some(t=>JU.has(t))&&e.some(t=>YU.has(t))}var VU=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"]]),JU=new Set(["can","has","is","should"]),YU=new Set(["access","api","auth","collision","expired","input","keyboard","overlap","permission","permissions","policy","projectile","response","route","routes","scope"]);function ss(e,t){let{scope:n,maxLoc:i=15,limit:r=30,scanLimit:o}=t??{},s=new U(e);return Ht({candidates:()=>iz(e,s,n,i),orderCandidates:_a,scanLimit:o,profile:{name:"passthrough-candidates"},prepare:a=>s.calleeEvidenceMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,l)=>l.incompleteSymbolIds.has(a.symbolId)||l.unavailableSymbolIds.has(a.symbolId)?null:XU(e,a,l.rows.get(a.symbolId)??[]),orderResults:(a,l)=>a.loc-l.loc||a.file.localeCompare(l.file),limit:r})}function XU(e,t,n){let i=nz(n);if(i.size!==1||!wf(e,t.relativePath,t.startLine,t.endLine))return null;let[,r]=[...i.entries()][0],o=QU(e,t,r),s=ez(e,t),a=o.length>0||s.length>0?"signal":"direct";return{symbol:t.symbol,shortName:A(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:de(t),forwardsTo:r.symbol,forwardsToShort:A(r.symbol),forwardsToFile:r.file,actionTier:a,boundaryEvidence:o,publicFacadeEvidence:s,recommendation:ZU(a,o,s)}}function QU(e,t,n){return Il(e,t.relativePath,t.startLine,"passthrough","explicit ignore-passthrough comment",[{label:"passthrough name",value:A(t.symbol)},{label:"callee name",value:A(n.symbol)},{label:"passthrough module",value:wx(t.relativePath,Lx(t.relativePath))},{label:"callee module",value:wx(n.file,Lx(n.file))}])}function ZU(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 i=t.filter(tz);return i.length>0?`Review the public API before inlining; public-surface evidence: ${i.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 ez(e,t){return xt(e,t)?Pn(e,t.relativePath)?["exported passthrough is declared on the package public surface"]:qe(e,t.symbol,t.relativePath)?["exported passthrough matches configured or framework public entry surface"]:[]:[]}function tz(e){return e.includes("public surface")}function nz(e){let t=e.some(i=>_e(i.symbol))?e.filter(i=>_e(i.symbol)):e,n=new Map;for(let i of t)n.has(i.symbol)||n.set(i.symbol,i);return n}function iz(e,t,n,i){return t.productionCallableDefinitions({scope:n,minLoc:3,maxLoc:i,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0}).filter(r=>!Ts(e,r))}var lz=new Set(on());function cz(e,t){return`tests/generated/twin-ab/${Dx(e)}-vs-${Dx(t)}.test.ts`}function Dx(e){return(e.split(/[/#]/).pop()||e).replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"symbol"}function uz(e,t,n,i){let{refA:r,refB:o,outFile:s}=typeof t=="string"?{refA:t,refB:n,outFile:i}:t;if(typeof r!="string"||typeof o!="string"||typeof s!="string")throw new TypeError("twinAb requires refA, refB, and outFile.");if(!oz(s))throw new TypeError("twinAb outFile must be an absolute path.");let a=Mx(e,r);if(!a.ok)return a;let l=Mx(e,o);if(!l.ok)return l;let c=a.symbol.paramCount===null||l.symbol.paramCount===null?null:a.symbol.paramCount===l.symbol.paramCount,u=mz(a.symbol,l.symbol,e.config.projectRoot,s,c);return{ok:!0,a:a.symbol,b:l.symbol,signatureCompatible:c,testSource:u}}function Mx(e,t){let i=at(e,t).match;if(!i)return{ok:!1,reason:`${t} does not resolve to an indexed symbol.`};let o=e.get("SELECT kind FROM global_symbols WHERE id = ?",i.symbolId)?.kind??null;if(!(o!==null?lz.has(o):_e(i.symbol)))return{ok:!1,reason:`${t} resolves to ${A(i.symbol)}${o!==null?` with SCIP kind ${Gr(o)}`:""} \u2014 twin-ab compares call outputs, so both referents must be functions or methods.`};if(!xt(e,i))return{ok:!1,reason:`${t} (${A(i.symbol)} at ${i.relativePath}:${i.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 = ?",i.symbolId),l=er(tr(a?.documentation??null));return{ok:!0,symbol:{ref:t,symbol:i.symbol,shortName:Y(i.symbol)||A(i.symbol),file:i.relativePath,startLine:i.startLine,signature:l,paramCount:l?dz(l):null}}}function dz(e){let t=e.indexOf("(");if(t===-1)return null;let n=0,i=-1;for(let a=t;a<e.length;a+=1){let l=e[a];if(l==="(")n+=1;else if(l===")"&&(n-=1,n===0)){i=a;break}}if(i===-1)return null;let r=e.slice(t+1,i).trim();if(!r)return 0;let o=1,s=0;for(let a of r)a==="("||a==="["||a==="{"?s+=1:a===")"||a==="]"||a==="}"?s=Math.max(0,s-1):a===","&&s===0&&(o+=1);return o}function Px(e,t,n){let i=rz(t),r=az(e,n),s=sz(i,r).replace(/\\/g,"/").replace(/\.tsx?$/,".js");return s.startsWith(".")?s:`./${s}`}function mz(e,t,n,i,r){let o=Px(n,i,e.file),s=Px(n,i,t.file),a=r===null?"Signature comparison: unknown (one or both signatures unavailable in the index) \u2014 check by hand.":r?"Signature comparison: param counts match.":"Signature comparison: param counts DIFFER \u2014 twins may not be directly comparable; check by hand.";return`/**
373
+ `).map(d=>d.trim()).filter(d=>d!==""):[];if(u.length>t){i+=1;continue}n.push({hash:a,timestamp:Number(l)||0,subject:c??"",files:u})}return{commits:n,skippedBulkCommits:i}}function Vj(e){return e.length>=Sj?!0:Jj(e).size>=vj}function Jj(e){let t=new Set;for(let n of e){let i=n.indexOf("/");t.add(i>=0?n.slice(0,i):".")}return t}function Yj(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function Xj(e){let t=new Set,n=[],i=[];for(let r of e){!i.includes(r)&&i.length<Rj&&i.push(r);for(let o of Qj(r))t.add(o);for(let o of r.match(Ij)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:i,externalIssueLabelStatus:"unavailable"}}function Qj(e){let t=new Set,n=Ej.exec(e)?.[1]?.toLowerCase();return n&&t.add(Zj(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 Zj(e){return e==="feat"?"feature":e}var ZC=/(?:^|\/)(?: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 ts(e,t,n={}){let{minTogether:i=4,minConfidence:r=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=Xt(e,{historyMode:n.historyMode,...n.head?{head:n.head}:{}}),l=a.commitHistory(),c=t!==void 0,u=a.coChangePairs({minTogether:c?Math.min(i,2):i,minConfidence:c?0:r,maxFilesPerCommit:s});if(!l||!u)return{available:!1,commitsAnalyzed:0,findings:[]};let d=typeof n.scanLimit=="number"?u.slice(0,n.scanLimit):u,m=$e(e),f=rx(e),p=nH(e,m,f),g=n.includeLinked===!0||c,h=[];for(let b of d){if(ZC.test(b.fileA)||ZC.test(b.fileB)||!ex(e,b.fileA)||!ex(e,b.fileB)||c&&!b.fileA.includes(t)&&!b.fileB.includes(t)||!c&&(J(b.fileA)==="test"||J(b.fileB)==="test"||sH(b.fileA,b.fileB)||rH(b.fileA,b.fileB)))continue;let v=p(b.fileA,b.fileB);if(!g&&v)continue;let y=eH(b.fileA,b.fileB),I=tH(b,y,v);if(h.push({...b,structurallyLinked:v,partnerClass:y.partnerClass,partnerClassReasons:y.reasons,...I?{declaredCouplingSuggestion:I}:{}}),h.length>=o)break}return{available:!0,commitsAnalyzed:l.commits.length,findings:h}}function ex(e,t){return Ft(e.config.projectRoot,t)}function eH(e,t){let n=nx(e),i=nx(t),r=[],o=l=>{r.includes(l)||r.push(l)},s=(l,c)=>n.tags.has(l)&&i.tags.has(c)||n.tags.has(c)&&i.tags.has(l);if(s("doc","code"))return o("one side is documentation and the other is executable source"),{partnerClass:"doc-code",reasons:r};if(n.tags.has("test")||i.tags.has("test"))return o("one side is classified as a test file"),{partnerClass:"test-code",reasons:r};if(s("schema","script"))return o("schema or contract file changes with a script or generated-code path"),{partnerClass:"schema-script",reasons:r};if(s("model","view"))return o("model or state path changes with a view or component path"),{partnerClass:"model-view",reasons:r};if(s("config","code"))return o("configuration file changes with executable source"),{partnerClass:"config-code",reasons:r};let a=yH(n.tokens,i.tokens).filter(l=>!gH.has(l));return ix(e,t)||a.length>=2?(o(ix(e,t)?"both files live in the same directory":`files share feature tokens: ${a.slice(0,4).join(", ")}`),{partnerClass:"same-feature",reasons:r}):(o("no specific relationship pattern matched"),{partnerClass:"unknown",reasons:r})}function tH(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!pH.has(t.partnerClass))return;let i=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${bH(i)}`,files:i,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 nH(e,t=$e(e),n=rx(e)){return(i,r)=>aH(t,n,i,r)}var iH=/(?:^|\/)(?:locales|i18n)\//i;function tx(e){return iH.test(e)}function rH(e,t){return tx(e)&&tx(t)?!0:oH(e,t)}function oH(e,t){if(!e.endsWith(".json")||!t.endsWith(".json"))return!1;let n=e.lastIndexOf("/"),i=t.lastIndexOf("/");if(n<0||i<0)return!1;let r=e.slice(0,n),o=t.slice(0,i);if(r===o)return!1;let s=e.slice(n+1),a=t.slice(i+1);if(s!==a)return!1;let l=r.lastIndexOf("/"),c=o.lastIndexOf("/"),u=l>=0?r.slice(0,l):"",d=c>=0?o.slice(0,c):"";return u===d}function sH(e,t){let n=e.lastIndexOf("/"),i=t.lastIndexOf("/");if(e.slice(0,n)!==t.slice(0,i))return!1;let r=e.slice(n+1).split(".")[0],o=t.slice(i+1).split(".")[0];return r!==""&&r===o}function rx(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function aH(e,t,n,i){return e.get(n)?.has(i)===!0||e.get(i)?.has(n)===!0?!0:t.some(r=>r.has(n)&&r.has(i))}var lH=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,cH=/(?:^|\/)(?:\.[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,uH=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,dH=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,mH=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,fH=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,pH=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),gH=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 nx(e){let t=e.replace(/\\/g,"/"),n=new Set;return lH.test(t)&&n.add("doc"),cH.test(t)&&n.add("config"),uH.test(t)&&n.add("schema"),dH.test(t)&&n.add("script"),mH.test(t)&&n.add("model"),fH.test(t)&&n.add("view"),J(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:hH(t)}}function ix(e,t){let n=e.lastIndexOf("/"),i=t.lastIndexOf("/"),r=n>=0?e.slice(0,n):"",o=i>=0?t.slice(0,i):"";return r!==""&&r===o}function hH(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 yH(e,t){let n=new Set(t);return[...new Set(e.filter(i=>n.has(i)))].sort()}function bH(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}function Cl(e,t){let n=SH(e,t)??vH(e,t)??CH(e,t)??xH(e,t);return RH(e,n,t)}function SH(e,t){let n=-1,i=null;for(let r=0;r<=t;r+=1){let o=im(e[r]??"");o&&(i===null?(i=o,n=r):o===i&&(i=null,n=-1))}if(i===null||n<0)return null;for(let r=t+1;r<e.length;r+=1)if(im(e[r]??"")===i)return{start:n,end:r+1};return{start:n,end:e.length}}function im(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function vH(e,t){if(!Sl(e[t]??""))return null;let n=t;for(;n>0&&Sl(e[n-1]??"");)n-=1;let i=t+1;for(;i<e.length&&Sl(e[i]??"");)i+=1;return{start:n,end:i}}function Sl(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function CH(e,t){let n=t;for(;n>=0;){let o=e[n]??"";if(vl(o)!==null)break;if(rm(o)!==null)return null;n-=1}if(n<0)return null;let i=vl(e[n]??"");if(i===null)return null;let r=n+1;for(;r<e.length;){let o=e[r]??"",s=vl(o);if(s!==null){if(s<=i)break;r+=1;continue}if(rm(o)!==null)break;r+=1}return{start:n,end:r}}function vl(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function xH(e,t){let n=e[t]??"";if(sx(n)||n.trim().length===0)return{start:t,end:t+1};let i=t;for(;i>0&&ox(e[i-1]??"");)i-=1;let r=t+1;for(;r<e.length&&ox(e[r]??"");)r+=1;return{start:i,end:r}}function ox(e){return rm(e)===null}function rm(e){return e.trim().length===0?"blank":sx(e)?"heading":im(e)?"fence":Sl(e)?"table":vl(e)!==null?"list":null}function sx(e){return/^#{1,6}\s+/.test(e.trim())}function RH(e,t,n){let{start:i,end:r}=t;if(r-i>40){let s=Math.floor(20);i=Math.max(i,n-s),r=Math.min(r,i+40),i=Math.max(t.start,r-40)}let o=e.slice(i,r).join(`
374
+ `).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}function Ui(e,t){return t.filter(n=>e.includes(n))}var IH=/<!--\s*codebaseiq:\s*snapshot\s*-->/i;function ax(e,t){if((e.config.docs?.snapshotPaths??[]).some(r=>si(r,t)))return!0;let i=se(e,t);return i.length>0&&IH.test(i)}var lx={classifyCitation:wH,citationContexts:LH,citationKindLabel:MH,citationRemediation:PH,referenceTargets:TH,hasLineAnchoredCitation:EH};function EH(e){return e.some(t=>(t.lineReferences?.length??0)>0)}function wH(e){let t=e.join(`
375
+ `).toLowerCase(),n=[],i=Ui(t,[".codebaseiq","declaredcouplings","suppression","suppressions","config","configuration","json"]);if(i.length>0)return n.push(`configuration/example terms near citation: ${i.join(", ")}`),{citationKind:"configuration-example",actionTier:"support",reasons:n};let r=Ui(t,["accepted","intentional","intentionally","retained","historical"]);if(r.length>0)return n.push(`intentional-record terms near citation: ${r.join(", ")}`),{citationKind:"intentional-record",actionTier:"support",reasons:n};let o=Ui(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 LH(e,t,n){let i=se(e,t);if(!i&&!Ft(e.config.projectRoot,t))return[];let r=i.split(/\r?\n/),o=n.flatMap(DH),s=[];for(let a=0;a<r.length;a+=1){let l=r[a]??"";o.some(c=>l.includes(c))&&s.push(Cl(r,a))}return s}function DH(e){let t=e.split("/");return[e,`./${e}`,t.slice(-3).join("/"),t.slice(-2).join("/")].filter((n,i,r)=>n.length>0&&r.indexOf(n)===i)}function MH(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 PH(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 TH(e,t,n){let i=fl(n),r=new Set;for(let o of t)FH(e,o,i.get(o)??[])&&r.add(o);return r}function FH(e,t,n){if(!kH.test(t)||!Ft(e.config.projectRoot,t))return!0;if(n.length===0)return!1;let i=rt(e.config.projectRoot,t,{inputKind:"changed source file"}).split(/\r?\n/),r=NH(i);for(let o of n)for(let s=o.startLine;s<=o.endLine;s+=1)if((i[s]??"").trim()!==""&&!r.has(s))return!0;return!1}var kH=/\.(?:[cm]?[jt]sx?)$/i;function NH(e){let t=new Set,n=!1;for(let i=0;i<e.length;i+=1){let r=e[i].trim();!n&&AH(r)&&(n=!0),n&&(t.add(i),r.endsWith(";")&&(n=!1))}return t}function AH(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}var cx=Ct({kind:"doc-path-evidence",invalidation:Ye("doc-path-evidence"),serialize:JH,deserialize:YH}),ns=/\.(?:md|mdx|rst|txt)$/i;function _H(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var BH=3,OH=/([A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6})(?::([1-9][0-9]*))?\b/g;function $H(e,t={}){let{doc:n,limit:i=20,minCoupling:r=BH,includeSnapshotExcluded:o=!1}=t,s=zH(e,t.historyMode??"bounded");if(!s)return{available:!1,commitsAnalyzed:0,docsScanned:0,findings:[]};let a=[];for(let l of s.docFiles){if(n!==void 0&&!l.includes(n)||n===void 0&&!qH(e,l)||n!==void 0&&!Ft(e.config.projectRoot,l))continue;let c=ax(e,l);if(c&&!o)continue;let{value:u,estimated:d}=jH(e,l,s.changeTimes.get(l)),m=HH(e,l),f=new Map,{resolved:p,broken:g,citations:h}=GH(e,l,s.tracked,s.trackedBySuffix,s.everSeenInHistory),b=new Map(h.map(y=>[y.file,y]));for(let y of p){if(y===l||ns.test(y))continue;let I=(s.changeTimes.get(y)??[]).filter(S=>S>u).length;if(I===0)continue;let E=b.get(y);f.set(y,{file:y,evidence:"reference",coChanges:0,changesSinceDocUpdate:I,...om("reference",m,E?.contexts),citationContexts:E?.contexts,citedLines:E?.lineReferences})}for(let[y,I]of s.coupling.get(l)??[]){if(I<r||!s.tracked.has(y))continue;let E=(s.changeTimes.get(y)??[]).filter(x=>x>u).length;if(E===0)continue;let S=f.get(y);S?(S.evidence="both",S.coChanges=I,Object.assign(S,om("both",m,S.citationContexts))):f.set(y,{file:y,evidence:"co-change",coChanges:I,changesSinceDocUpdate:E,...om("co-change",m)})}if(f.size===0&&g.length===0)continue;let v=[...f.values()].sort((y,I)=>I.changesSinceDocUpdate-y.changesSinceDocUpdate);a.push({doc:l,docLastChangedAt:u,staleness:v.reduce((y,I)=>y+I.changesSinceDocUpdate,0)+g.length*10,subjects:v.slice(0,8),brokenReferences:g,...c?{snapshotExcluded:!0}:{},...d?{docLastChangedAtEstimated:!0}:{}})}return a.sort((l,c)=>c.staleness-l.staleness),{available:!0,commitsAnalyzed:s.historyCommitCount,docsScanned:s.docFiles.length,findings:a.slice(0,i)}}function jH(e,t,n){if(n&&n.length>0)return{value:Math.max(...n),estimated:!1};try{return{value:Math.floor(Cs(e.config.projectRoot,t).mtimeMs/1e3),estimated:!0}}catch(i){if(Ft(e.config.projectRoot,t))throw i;return{value:0,estimated:!1}}}function HH(e,t){let n=se(e,t).slice(0,6e3);if(!n)return{docIntent:"unknown",reasons:["doc text unavailable"]};let i=`${t}
376
+ ${n}`.toLowerCase(),r=Ui(i,["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(r.length>0)return{docIntent:"historical-note",reasons:[`historical-note terms: ${r.join(", ")}`]};let o=Ui(i,["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 om(e,t,n=[]){let i=e==="co-change"||n.length===0?null:lx.classifyCitation(n);return{actionTier:UH(e,t.docIntent,i?.actionTier),docIntent:t.docIntent,docIntentReasons:t.reasons,...i?{citationKind:i.citationKind,citationKindReasons:i.reasons}:{}}}function UH(e,t,n){return t==="historical-note"?"support":n||(e==="co-change"?"signal":"direct")}function zH(e,t){let n=Xt(e,{historyMode:t}),i=n.commitHistory();if(!i)return null;let r=n.trackedFiles()??new Set,o=new Map,s=new Map,a=new Set;for(let l of i.commits){let c=[...new Set(l.files)],u=c.filter(m=>ns.test(m)),d=c.filter(m=>!ns.test(m));for(let m of c){a.add(m);let f=o.get(m)??[];f.push(l.timestamp),o.set(m,f)}for(let m of u){let f=s.get(m);f||(f=new Map,s.set(m,f));for(let p of d)f.set(p,(f.get(p)??0)+1)}}return{changeTimes:o,coupling:s,docFiles:[...r].filter(l=>ns.test(l)),everSeenInHistory:a,historyCommitCount:i.commits.length,tracked:r,trackedBySuffix:KH(r)}}function qH(e,t){return ns.test(t)&&!_H(t)&&Ft(e.config.projectRoot,t)}function KH(e){let t=new Map;for(let n of e){let i=n.split("/");for(let r of[2,3]){if(i.length<r)continue;let o=i.slice(-r).join("/"),s=t.get(o)??[];s.push(n),t.set(o,s)}}return t}function GH(e,t,n,i,r){let o=new Set,s=new Set,a=WH(e,t);if(!a)return{resolved:o,broken:[],citations:[]};let l=a.candidates,c=a.contextsByCandidate,u=a.lineReferencesByCandidate,d=new Map,m=new Map,f=(p,g)=>{let h=c.get(g);if(h&&h.length>0){let v=d.get(p)??[];v.push(...h),d.set(p,ux(v).slice(0,3))}let b=u.get(g);b&&b.length>0&&m.set(p,sm([...m.get(p)??[],...b]))};for(let p of l){if(n.has(p)){o.add(p),f(p,p);continue}let g=i.get(p);if(g&&g.length===1){o.add(g[0]),f(g[0],p);continue}g&&g.length>1||r.has(p)&&s.add(p)}return{resolved:o,broken:[...s],citations:[...d].map(([p,g])=>({file:p,contexts:g,lineReferences:m.get(p)}))}}function WH(e,t,n){let i=n;if(i===void 0&&(i=se(e,t),!i&&!Ft(e.config.projectRoot,t)))return null;let r=Nt(e,t,i),o=cx.read(e,t,r);if(o)return o;let s=VH(i);return cx.write(e,t,r,s),s}function VH(e){let t=e.split(/\r?\n/),n=new Set,i=new Map,r=new Map;for(let o=0;o<t.length;o+=1){let s=t[o]??"";for(let a of s.matchAll(OH)){let l=(a[1]??"").replace(/^\.?\//,"");if(l.length===0)continue;n.add(l);let c=a[2]?Number(a[2]):null;c!==null&&Number.isSafeInteger(c)&&r.set(l,sm([...r.get(l)??[],c]));let u=Cl(t,o);if(u.length===0)continue;let d=i.get(l)??[];d.push(u),i.set(l,ux(d).slice(0,3))}}return{candidates:[...n],contextsByCandidate:i,lineReferencesByCandidate:r}}function JH(e){let t={candidates:e.candidates,contextsByCandidate:[...e.contextsByCandidate.entries()],lineReferencesByCandidate:[...e.lineReferencesByCandidate.entries()]};return JSON.stringify(t)}function YH(e){try{let t=JSON.parse(e);if(!cf(t))return null;let n=Xl(t.candidates),i=QH(t.contextsByCandidate),r=XH(t.lineReferencesByCandidate);return!n||!i?null:{candidates:n,contextsByCandidate:new Map(i),lineReferencesByCandidate:new Map(r??[])}}catch{return null}}function XH(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 i=[];for(let r of n[1]){if(typeof r!="number"||!Number.isSafeInteger(r))return null;i.push(r)}t.push([n[0],sm(i)])}return t}function QH(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 i=Xl(n[1]);if(!i)return null;t.push([n[0],i])}return t}function ux(e){let t=[];for(let n of new Set(e))t.some(i=>ZH(i,n))||t.push(n);return t}function sm(e){return[...new Set(e)].sort((t,n)=>t-n)}function ZH(e,t){if(e===t)return!0;let n=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),i=t.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),r=Math.min(n.length,i.length);if(r===0)return!1;if(r<3)return e.includes(t)||t.includes(e);let o=new Set(i),s=n.filter(a=>o.has(a)).length;return s>=3&&s/r>=.6}import{createHash as eU}from"crypto";var tU=3;function is(e,t={}){let{scope:n,maxLoc:i=15,minLoc:r=tU,limit:o,scanLimit:s}=t,a=VC(e),l=nU(e,{scope:n,maxLoc:i,scanLimit:s}).map(u=>iU(e,u,a,r)).filter(u=>u!==null),c=fx(l);return o?c.slice(0,o):c}function mx(e){let t=bn(e);return xn(t).replace(/\s+/g,"")}function fx(e){let t=new Map;for(let i of e){if(i.normalizedBody.length<8)continue;let r=oU(i.normalizedBody),o=t.get(r)??[];o.push(i),t.set(r,o)}let n=[];for(let[i,r]of t){let o=new Set(r.map(a=>a.file));if(r.length<2||o.size<2)continue;let s=[...r].sort(sU).map(({normalizedBody:a,...l})=>l);n.push({hash:i,canonical:s[0],functions:s})}return n.sort((i,r)=>{let o=r.functions.length-i.functions.length;if(o!==0)return o;let s=dx(r)-dx(i);return s!==0?s:i.canonical.file.localeCompare(r.canonical.file)}),n}function nU(e,t){let n=Ue(e,{scope:t.scope}).filter(i=>i.isFunctionLike&&!e.isIgnored(i.relativePath)).filter(i=>!Ds(e,i.relativePath,i.startLine,"similar")).filter(i=>de(i)<=t.maxLoc);return n.sort((i,r)=>de(r)-de(i)||i.relativePath.localeCompare(r.relativePath)),ke(n,t.scanLimit)}function iU(e,t,n,i){let r=Qt(e,t);if(!r||rU(r)<i)return null;let o=am(e,t);return o?{symbol:t.symbol,shortName:A(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:de(t),ageCommits:n?.get(t.relativePath)?.commitsAgo??null,normalizedBody:o}:null}function am(e,t){let n=Qt(e,t);return n&&mx(n)||null}function Qt(e,t){let n=re(e,t.relativePath);return n.length===0?null:n.slice(t.startLine,t.endLine+1).join(`
377
+ `)}function bn(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(t>=0&&n>t)return e.slice(t+1,n);let i=e.indexOf("=>");return i>=0?e.slice(i+2).replace(/;+\s*$/,""):e}function rU(e){return bn(e).split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0).length}function oU(e){return eU("sha256").update(e).digest("hex").slice(0,16)}function sU(e,t){let n=e.ageCommits??-1;return(t.ageCommits??-1)-n||e.file.localeCompare(t.file)||e.startLine-t.startLine}function dx(e){return e.functions.reduce((t,n)=>t+n.loc,0)}var aU=new Set(on());function lU(e,t={}){let{includeHomonyms:n=!1,limit:i}=t,r=xl(e,t).filter(o=>o.relationship==="divergent"||n&&o.relationship==="homonym");return i?r.slice(0,i):r}function xl(e,t={}){let{scope:n,minSimilarity:i=.3,scanLimit:r}=t,o=dU(e,{scope:n,scanLimit:r});return hx(o,{minSimilarity:i,isDelegatePair:kU(e)}).filter(s=>!s.members.some(a=>Ds(e,a.file,a.startLine,"twin")))}function hx(e,t={}){let n=t.minSimilarity??.3,i=t.isDelegatePair,r=e.filter(c=>!Rx(c.leaf)&&!xU(c.leaf)&&J(c.file)!=="test"&&!Xe(c.symbol)&&!bx(c.symbol)&&!Sx(c.symbol,c.leaf)),{recordsByLeaf:o,recordOrder:s}=B("twin-drift.group-by-leaf",()=>cU(r),()=>({records:r.length})),a=B("twin-drift.cluster-leaf-names",()=>yx([...o.keys()]),()=>({leaves:o.size}));return B("twin-drift.compare-clusters",()=>{let c=[];for(let u of a){let d=uU(u,o,s);if(d.length<2||new Set(d.map(v=>v.file)).size<2)continue;let m=null,f=!1,p=!1,g=new Set;for(let v=0;v<d.length;v+=1)for(let y=v+1;y<d.length;y+=1){let I=d[v],E=d[y];if(I.file===E.file||!wU(I,E)||i?.(I,E,d)||i?.(E,I,d))continue;if(f=!0,g.add(I.symbol),g.add(E.symbol),I.normalizedBody===E.normalizedBody){p=!0;continue}let S=bU(I.tokens,E.tokens);(!m||S>m.similarity)&&(m={a:I,b:E,similarity:S})}if(!f)continue;let h=d.filter(v=>g.has(v.symbol)).sort((v,y)=>v.file.localeCompare(y.file)||v.startLine-y.startLine).map(yU);if(!m){c.push({leaf:gx(u),relationship:p?"identical":"homonym",maxDivergence:0,members:h});continue}let b=m.similarity>=n?"divergent":"homonym";c.push({leaf:gx(u),relationship:b,maxDivergence:Math.round((1-m.similarity)*1e3)/1e3,members:h,...b==="divergent"?{firstDivergentTokens:SU(m.a.tokens,m.b.tokens)}:{}})}return c},()=>({clusters:a.length,records:r.length})).sort((c,u)=>u.members.length-c.members.length||u.maxDivergence-c.maxDivergence||c.leaf.localeCompare(u.leaf))}function cU(e){let t=new Map,n=new Map;for(let[i,r]of e.entries()){let o=t.get(r.leaf)??[];o.push(r),t.set(r.leaf,o),n.set(r,i)}return{recordsByLeaf:t,recordOrder:n}}function uU(e,t,n){let i=[...e].flatMap(r=>t.get(r)??[]);return e.size>1&&i.sort((r,o)=>(n.get(r)??0)-(n.get(o)??0)),i}function dU(e,t){let n=B("twin-drift.load-definitions",()=>Ue(e,{scope:t.scope}).filter(o=>mU(o)&&!e.isIgnored(o.relativePath)).filter(o=>!dr(o.relativePath)));B("twin-drift.sort-definitions",()=>n.sort((o,s)=>o.relativePath.localeCompare(s.relativePath)||o.startLine-s.startLine),()=>({definitions:n.length}));let i=ke(n,t.scanLimit),r=B("twin-drift.select-candidates",()=>fU(i),()=>({scanned:i.length}));return B("twin-drift.build-records",()=>{let o=[];for(let s of r){let a=pU(e,s);a&&o.push(a)}return o},()=>({candidates:r.length,scanned:i.length}))}function mU(e){return e.isFunctionLike?e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&aU.has(e.kind):!0:!1}function fU(e){let t=e.filter(o=>o.leaf&&!Rx(o.leaf)&&!Xe(o.symbol)&&!bx(o.symbol)&&!Sx(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 i=yx([...n.keys()]),r=new Set;for(let o of i){let s=[...o].flatMap(a=>n.get(a)??[]);if(!(s.length<2)&&!(new Set(s.map(a=>a.relativePath)).size<2)&&!s.every(a=>J(a.relativePath)==="test"))for(let a of s)r.add(a)}return e.filter(o=>r.has(o))}function pU(e,t){if(!t.leaf)return null;let n=Qt(e,t);if(!n||!st(t.symbol)&&!gU(n,t.leaf))return null;let i=xn(bn(n)),r=i.replace(/\s+/g,"");if(!r||r.length<8)return null;let o=i.match(hU)??[];return o.length===0?null:{leaf:t.leaf,symbol:t.symbol,shortName:A(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:de(t),normalizedBody:r,tokens:o,isThinForwarder:Cx(i)}}function gU(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 hU=/[A-Za-z_$][A-Za-z0-9_$]*|\d+(?:\.\d+)?|[^\sA-Za-z0-9_$]/g;function yU(e){return{symbol:e.symbol,shortName:e.shortName,file:e.file,startLine:e.startLine,endLine:e.endLine,loc:e.loc}}function bU(e,t){let n=new Set(e),i=new Set(t);if(n.size===0&&i.size===0)return 1;if(n.size===0||i.size===0)return 0;let r=0;for(let s of n)i.has(s)&&(r+=1);let o=n.size+i.size-r;return o===0?0:r/o}function SU(e,t){let n=Math.min(e.length,t.length),i=0;for(;i<n&&e[i]===t[i];)i+=1;let r=e.slice(i,i+6).join(" "),o=t.slice(i,i+6).join(" ");return!r&&!o?"(bodies differ only in trailing length)":`A: ${r||"(end)"} | B: ${o||"(end)"}`}function yx(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 l=s;for(;t.get(l)!==a;){let c=t.get(l);t.set(l,a),l=c}return a},i=(s,a)=>{let l=n(s),c=n(a);l!==c&&t.set(l,c)},r=new Map;for(let s of e){let a=s.slice(0,2).toLowerCase(),l=r.get(a)??[];l.push(s),r.set(a,l)}for(let s of r.values())for(let a=0;a<s.length;a+=1)for(let l=a+1;l<s.length;l+=1)vU(s[a],s[l])&&i(s[a],s[l]);let o=new Map;for(let s of e){let a=n(s),l=o.get(a)??new Set;l.add(s),o.set(a,l)}return[...o.values()]}function vU(e,t){return e===t||e.toLowerCase()===t.toLowerCase()?!0:e.length<8||t.length<8||Math.abs(e.length-t.length)>2||CU(e.toLowerCase(),t.toLowerCase())/Math.max(e.length,t.length)<.8?!1:LU(e.toLowerCase(),t.toLowerCase(),2)}function CU(e,t){let n=Math.min(e.length,t.length),i=0;for(;i<n&&e[i]===t[i];)i+=1;return i}function xU(e){return/^[A-Z][A-Z0-9_]*$/.test(e)||/^__[^_].*__$/.test(e)||RU.has(e.toLowerCase())}var RU=new Set(["main","row"]),IU=new Set(["app","component","components","feature","features","impl","index","lib","route","routes","shared","src","tsx","typescript","ui"]);function bx(e){return e.startsWith("rust-analyzer ")&&/\/(?:tests?|benches?)\//.test(e)}var EU=new Set(["default","new","reset"]);function Sx(e,t){return e.startsWith("rust-analyzer ")&&EU.has(t.toLowerCase())}function wU(e,t){if(e.leaf.toLowerCase()!==t.leaf.toLowerCase()||e.leaf.length>4)return!0;let n=px(e);return[...px(t)].some(i=>n.has(i))}function px(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&&!IU.has(n)))}function LU(e,t,n){if(Math.abs(e.length-t.length)>n)return!1;let i=Array.from({length:t.length+1},(r,o)=>o);for(let r=1;r<=e.length;r+=1){let o=[r],s=o[0];for(let a=1;a<=t.length;a+=1){let l=e[r-1]===t[a-1]?0:1,c=Math.min(i[a]+1,o[a-1]+1,i[a-1]+l);o.push(c),s=Math.min(s,c)}if(s>n)return!1;i=o}return i[t.length]<=n}function vx(e){return Cx(xn(bn(e)))}function Cx(e){let t=e.trim();if(!t||DU.test(t))return!1;let n=TU(t);return n.length===0||n.length>2?!1:PU(n[n.length-1])}var DU=/\b(?:if|else|for|while|switch|try|catch|do)\b/,MU=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^[\]]*\])*\((?:[^()]|\([^()]*\))*\)$/;function PU(e){let t=e.trim().replace(/^return\s+/,"").replace(/^await\s+/,"").replace(/;\s*$/,"").trim();return MU.test(t)}function TU(e){let t=[],n=0,i="";for(let r of e){if(r==="("||r==="["||r==="{"?n+=1:(r===")"||r==="]"||r==="}")&&(n=Math.max(0,n-1)),r===";"&&n===0){t.push(i),i="";continue}i+=r}return i.trim()&&t.push(i),t.map(r=>r.trim()).filter(r=>r.length>0)}var FU=3;function kU(e){let t=new Map;return(n,i,r)=>{if(!n.isThinForwarder)return!1;let o=`${n.symbol}\0${i.symbol}`,s=t.get(o);if(s!==void 0)return s;let a=xx(e,n,i,r,FU,new Set);return t.set(o,a),a}}function xx(e,t,n,i,r,o){if(r<=0||o.has(t.symbol)||(o.add(t.symbol),(tn(e,t.file)??[]).filter(l=>l.line>=t.startLine&&l.line<=t.endLine&&l.calleeLeaf===n.leaf).length===0))return!1;let a=new Set(Ce(e,t.file).filter(l=>l.sourcePath&&(l.kind!=="namespace"||l.usedMembers.includes(n.leaf))).map(l=>l.sourcePath));if([...a].some(l=>Tt(l,n.file)))return!0;for(let l of i)if(!(l.symbol===t.symbol||l.symbol===n.symbol||!l.isThinForwarder)&&[...a].some(c=>Tt(c,l.file))&&xx(e,l,n,i,r-1,o))return!0;return!1}function Rx(e){return e.startsWith("<")&&e.endsWith(">")}function gx(e){return[...e].sort()[0]}import{dirname as VU,isAbsolute as JU,relative as YU,resolve as XU}from"path";import{basename as Ix,extname as Ex}from"path";function Rl(e,t,n,i,r,o){let s=new Set;AU(e,t,n,i)&&s.add(r);for(let a of o)a.value&&NU(s,a.label,a.value);return[...s].slice(0,6)}function NU(e,t,n){let i=_U(n);t.endsWith("name")&&BU(i)&&e.add(`${t} has type-guard boundary shape`);for(let r of i){let o=OU.get(r);o&&e.add(`${t} has ${o} term: ${r}`)}}function AU(e,t,n,i){if(n<=0)return!1;let r=re(e,t);if(r.length===0)return!1;for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(r[o]??"").trim();if(s!==""){if(ws(s)===i)return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function _U(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 BU(e){return e.some(t=>$U.has(t))&&e.some(t=>jU.has(t))}var OU=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"]]),$U=new Set(["can","has","is","should"]),jU=new Set(["access","api","auth","collision","expired","input","keyboard","overlap","permission","permissions","policy","projectile","response","route","routes","scope"]);function rs(e,t){let{scope:n,maxLoc:i=15,limit:r=30,scanLimit:o}=t??{},s=new U(e);return Ht({candidates:()=>WU(e,s,n,i),orderCandidates:Aa,scanLimit:o,profile:{name:"passthrough-candidates"},prepare:a=>s.calleeEvidenceMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,l)=>l.incompleteSymbolIds.has(a.symbolId)||l.unavailableSymbolIds.has(a.symbolId)?null:HU(e,a,l.rows.get(a.symbolId)??[]),orderResults:(a,l)=>a.loc-l.loc||a.file.localeCompare(l.file),limit:r})}function HU(e,t,n){let i=GU(n);if(i.size!==1||!xf(e,t.relativePath,t.startLine,t.endLine))return null;let[,r]=[...i.entries()][0],o=UU(e,t,r),s=qU(e,t),a=o.length>0||s.length>0?"signal":"direct";return{symbol:t.symbol,shortName:A(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:de(t),forwardsTo:r.symbol,forwardsToShort:A(r.symbol),forwardsToFile:r.file,actionTier:a,boundaryEvidence:o,publicFacadeEvidence:s,recommendation:zU(a,o,s)}}function UU(e,t,n){return Rl(e,t.relativePath,t.startLine,"passthrough","explicit ignore-passthrough comment",[{label:"passthrough name",value:A(t.symbol)},{label:"callee name",value:A(n.symbol)},{label:"passthrough module",value:Ix(t.relativePath,Ex(t.relativePath))},{label:"callee module",value:Ix(n.file,Ex(n.file))}])}function zU(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 i=t.filter(KU);return i.length>0?`Review the public API before inlining; public-surface evidence: ${i.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 qU(e,t){return xt(e,t)?Pn(e,t.relativePath)?["exported passthrough is declared on the package public surface"]:qe(e,t.symbol,t.relativePath)?["exported passthrough matches configured or framework public entry surface"]:[]:[]}function KU(e){return e.includes("public surface")}function GU(e){let t=e.some(i=>_e(i.symbol))?e.filter(i=>_e(i.symbol)):e,n=new Map;for(let i of t)n.has(i.symbol)||n.set(i.symbol,i);return n}function WU(e,t,n,i){return t.productionCallableDefinitions({scope:n,minLoc:3,maxLoc:i,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0}).filter(r=>!Ms(e,r))}var QU=new Set(on());function ZU(e,t){return`tests/generated/twin-ab/${wx(e)}-vs-${wx(t)}.test.ts`}function wx(e){return(e.split(/[/#]/).pop()||e).replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"symbol"}function ez(e,t,n,i){let{refA:r,refB:o,outFile:s}=typeof t=="string"?{refA:t,refB:n,outFile:i}:t;if(typeof r!="string"||typeof o!="string"||typeof s!="string")throw new TypeError("twinAb requires refA, refB, and outFile.");if(!JU(s))throw new TypeError("twinAb outFile must be an absolute path.");let a=Lx(e,r);if(!a.ok)return a;let l=Lx(e,o);if(!l.ok)return l;let c=a.symbol.paramCount===null||l.symbol.paramCount===null?null:a.symbol.paramCount===l.symbol.paramCount,u=nz(a.symbol,l.symbol,e.config.projectRoot,s,c);return{ok:!0,a:a.symbol,b:l.symbol,signatureCompatible:c,testSource:u}}function Lx(e,t){let i=at(e,t).match;if(!i)return{ok:!1,reason:`${t} does not resolve to an indexed symbol.`};let o=e.get("SELECT kind FROM global_symbols WHERE id = ?",i.symbolId)?.kind??null;if(!(o!==null?QU.has(o):_e(i.symbol)))return{ok:!1,reason:`${t} resolves to ${A(i.symbol)}${o!==null?` with SCIP kind ${qr(o)}`:""} \u2014 twin-ab compares call outputs, so both referents must be functions or methods.`};if(!xt(e,i))return{ok:!1,reason:`${t} (${A(i.symbol)} at ${i.relativePath}:${i.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 = ?",i.symbolId),l=Qi(Zi(a?.documentation??null));return{ok:!0,symbol:{ref:t,symbol:i.symbol,shortName:Y(i.symbol)||A(i.symbol),file:i.relativePath,startLine:i.startLine,signature:l,paramCount:l?tz(l):null}}}function tz(e){let t=e.indexOf("(");if(t===-1)return null;let n=0,i=-1;for(let a=t;a<e.length;a+=1){let l=e[a];if(l==="(")n+=1;else if(l===")"&&(n-=1,n===0)){i=a;break}}if(i===-1)return null;let r=e.slice(t+1,i).trim();if(!r)return 0;let o=1,s=0;for(let a of r)a==="("||a==="["||a==="{"?s+=1:a===")"||a==="]"||a==="}"?s=Math.max(0,s-1):a===","&&s===0&&(o+=1);return o}function Dx(e,t,n){let i=VU(t),r=XU(e,n),s=YU(i,r).replace(/\\/g,"/").replace(/\.tsx?$/,".js");return s.startsWith(".")?s:`./${s}`}function nz(e,t,n,i,r){let o=Dx(n,i,e.file),s=Dx(n,i,t.file),a=r===null?"Signature comparison: unknown (one or both signatures unavailable in the index) \u2014 check by hand.":r?"Signature comparison: param counts match.":"Signature comparison: param counts DIFFER \u2014 twins may not be directly comparable; check by hand.";return`/**
378
378
  * Generated by 'codebaseiq twin-ab'. Cleanup integrity scenario.
379
379
  * ("cross-examine same-concept twins"): where one concept is computed in
380
380
  * more than one place, feed both the same input and require the same
@@ -412,10 +412,10 @@ describe.skipIf(inputs.length === 0)('twin-ab: ${e.shortName} vs ${t.shortName}'
412
412
  expect(callA(...args)).toEqual(callB(...args));
413
413
  });
414
414
  });
415
- `}var Tx={caller:3,"entry-surface":2,rooted:1},fz=/not\s*yet\s*implement|not\s*implement|unimplement|\bnyi\b|\btodo\b|\bstub\b|not\s*supported|coming\s*soon/i,pz=/^throw\s+new\s+[\w.]*Error\s*\(([\s\S]*)\)\s*;?$/,gz=/^return(\s+(null|undefined|false|0|''|""|``|\[\]|\{\}))?\s*;?$/,hz=/\/\/\s*TODO\b|\/\*\s*TODO\b/i,yz=/(?:=>|\))\s*(?::\s*[^{;=]+)?\s*\{\s*\}\s*;?\s*$/;function bz(e,t={}){let{scope:n,limit:i=30,scanLimit:r,semantic:o=!0}=t,s=new U(e),a=ke(s.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),r),l=[];for(let f of a){let p=vz(e,f);p&&l.push(p)}if(l.length===0)return[];let c=Iz(e,l,a),u=l.filter(f=>!c.has(f.def.symbol));if(u.length===0)return[];let d=hn(e,s).forDefinitions(u.map(f=>f.def),{semantic:o}),m=[];for(let f of u){let p=d.get(f.def.symbolId);if(p?.semanticIncomplete||p?.semanticUnavailable)continue;let g=p?.realConsumers.length??0,h=Sz(e,f.def,g);h&&m.push({symbol:f.def.symbol,shortName:A(f.def.symbol),file:f.def.relativePath,startLine:f.def.startLine,endLine:f.def.endLine,loc:de(f.def),stubKind:f.stubKind,reachability:h,callerFanIn:g,stubText:f.stubText})}return m.sort((f,p)=>Tx[p.reachability]-Tx[f.reachability]||p.callerFanIn-f.callerFanIn||f.file.localeCompare(p.file)||f.startLine-p.startLine),i?m.slice(0,i):m}function Sz(e,t,n){return n>0?"caller":qe(e,t.symbol,t.relativePath)?"rooted":Qe(e,t.relativePath)?"entry-surface":null}function vz(e,t){let n=Qt(e,t);if(!n)return null;let i=bn(n),r=i.trim();if(r==="")return!Rz(n)||!xt(e,t)?null:{def:t,stubKind:"empty-body",stubText:"(empty body)"};let o=jr(i),s=xn(i),a=Cz(o,s);if(a.length!==1)return null;let l=a[0];return xz(l)?{def:t,stubKind:"throw-stub",stubText:l.trim()}:hz.test(i)&&gz.test(l.trim())?{def:t,stubKind:"todo-return-default",stubText:r}:null}function Cz(e,t){let n=[],i=0,r="";for(let o=0;o<t.length;o+=1){let s=t[o];if(s==="("||s==="["||s==="{"?i+=1:(s===")"||s==="]"||s==="}")&&(i=Math.max(0,i-1)),s===";"&&i===0){n.push(r),r="";continue}r+=e[o]??""}return r.trim()&&n.push(r),n.map(o=>o.trim()).filter(o=>o.length>0)}function xz(e){let t=pz.exec(e.trim());return t?fz.test(t[1]??""):!1}function Rz(e){return yz.test(e.trimEnd())}function Iz(e,t,n){let i=new Set,r=new Set(t.map(a=>a.def.parentTypeName).filter(a=>a!==null));if(r.size===0)return i;let o=wz(e,r),s=new Map;for(let a of n){if(!a.parentTypeName)continue;let l=s.get(a.leaf)??new Set;l.add(a.parentTypeName),s.set(a.leaf,l)}for(let a of t){let l=a.def.parentTypeName;if(!l)continue;let c=o.get(l);if(!c||c.size===0)continue;let u=s.get(a.def.leaf)??new Set;[...c].every(m=>u.has(m))&&i.add(a.def.symbol)}return i}var Ez=/\bclass\s+([A-Za-z_$][\w$]*)\s+extends\s+([A-Za-z_$][\w$]*)/g;function wz(e,t){let n=new Map;for(let i of me(e,{includeIgnored:!1})){let r=se(e,i);if(r)for(let o of r.matchAll(Ez)){let s=o[1],a=o[2];if(!s||!a||!t.has(a))continue;let l=n.get(a)??new Set;l.add(s),n.set(a,l)}}return n}var Lz=/^(?:validate|verify|check|assert)(?:[A-Z].*)?$/,Dz=/^(?:is|has)(?:[A-Z].*)?$/,Mz=/[{,]\s*(?:ok|success|valid|isValid)\s*:\s*false\b/,mm=/\breturn\b/g,Pz=/\bfunction\b|=>|\)\s*(?::\s*[^{;=]+)?\s*\{/,Tz=/\.(?:addIssue|push)\s*\(/;function Fz(e,t={}){let{scope:n,limit:i=30,scanLimit:r}=t,o=new U(e),s=ke(o.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),r),a=[];for(let l of s){let c=Nz(e,l);c&&a.push({symbol:l.symbol,shortName:A(l.symbol),file:l.relativePath,startLine:l.startLine,endLine:l.endLine,loc:de(l),...c})}return a.sort((l,c)=>l.file.localeCompare(c.file)||l.startLine-c.startLine||l.loc-c.loc),i?a.slice(0,i):a}function kz(e){return Lz.test(e)?"imperative":Dz.test(e)?"predicate":null}function Nz(e,t){let n=kz(t.leaf);if(!n||Er(e,t))return null;let i=Qt(e,t);if(!i||!Pz.test(i))return null;let r=te(e,t.relativePath)?.callables.find(s=>s.startLine===t.startLine&&s.endLine===t.endLine);if(n==="predicate"&&r?.paramCount===0)return null;if(xx(i)){let s=Bz(e,t);return!s||Nx(s.body,kx(s.snippet))||Fx(s.body)?null:{nameKind:n,resolvedVia:"one-hop-delegate",delegateTarget:s.shortName}}let o=bn(i);return Nx(o,kx(i))||Fx(o)?null:{nameKind:n,resolvedVia:"direct"}}var Az=new Set(["if","for","while","switch","catch","function"]);function Fx(e){let t=jr(e);for(let n of t.matchAll(/\b([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(/g))if(!Az.has(n[1]))return!0;return!1}function kx(e){let t=e.indexOf("=>");return t===-1?!1:!/^\s*\{/.test(e.slice(t+2))}function Nx(e,t){let n=jr(e);if(/\bthrow\b/.test(n)||/\.reject\s*\(/.test(n)||Mz.test(n)||Tz.test(n))return!0;let i=_z(n);if(t&&i.length===0){let r=n.trim();return r!==""&&r!=="true"}for(let r of i)if(r!==""&&r!=="true")return!0;return!1}function _z(e){let t=[];mm.lastIndex=0;let n;for(;n=mm.exec(e);){let i=n.index+n[0].length,r=0,o=e.length;for(let s=i;s<e.length;s+=1){let a=e[s];if(a==="("||a==="["||a==="{")r+=1;else if(a===")"||a==="]"||a==="}"){if(r===0){o=s;break}r-=1}else if(a===";"&&r===0){o=s;break}}t.push(e.slice(i,o).trim()),mm.lastIndex=o}return t}function Bz(e,t){let n=vi(e,t,{callableOnly:!0,limit:3,semanticEvidence:ge});if(n.semanticIncomplete||n.semanticUnavailable)return null;let i=n.rows,r=[...new Set(i.map(c=>c.symbol))].filter(c=>c!==t.symbol);if(r.length!==1)return null;let s=at(e,r[0]).match;if(!s)return null;let a=W(e,s.relativePath).find(c=>c.symbolId===s.symbolId);if(!a)return null;let l=Qt(e,a);return l?{body:bn(l),snippet:l,shortName:A(a.symbol)}:null}var Oz=60;function $z(e,t={}){let{scope:n,limit:i=30,scanLimit:r,rotDays:o=Oz}=t,s=ke(Xi(e,{extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs"]}).filter(u=>J(u)==="test").filter(u=>!n||u.includes(n)).filter(u=>!e.isIgnored(u)).sort(),r),a=[],l=[],c=[];for(let u of s){let d=se(e,u);if(!d)continue;let m=Rf(d),f=Uz(d);for(let g of Gz(m,f))f.add(g);let p=jz(m);for(let g of p){if(g.skip){l.push(Zz(e,u,g,o));continue}if(g.kind==="describe")continue;let h=_x(d,g.argsStart),b=m.slice(g.argsStart,g.callEnd),v=d.slice(g.argsStart,g.callEnd);Bx(b,f)||a.push({file:u,startLine:as(d,g.callStart),endLine:as(d,g.callEnd),title:h,severity:/\bawait\b/.test(b)?"low":"high"});let y=Yz(b,v);y&&c.push({file:u,startLine:as(d,g.callStart),endLine:as(d,g.callEnd),title:h,echoedValue:y})}}return{assertionFree:i?a.slice(0,i):a,skipped:i?l.slice(0,i):l,mockEcho:i?c.slice(0,i):c}}var fm=/(?<!\.)\b(?:x(it|test|describe)|(it|test|describe)(?:\.\s*(skip|only|todo|each\s*\([^)]*\)))?)\s*\(/g;function jz(e){let t=[];fm.lastIndex=0;let n;for(;n=fm.exec(e);){let i=n[1],r=i??n[2];if(!r)continue;let o=n[3]?.split(/\s*\(/)[0],s=n.index,a=n.index+n[0].length-1,l=ls(e,a);fm.lastIndex=a+1,o!=="each"&&t.push({kind:r,skip:i!==void 0||o==="skip"||o==="todo",skipKind:o==="todo"?"todo":"skip",callStart:s,argsStart:a+1,callEnd:l+1})}return t}function ls(e,t){let n=0;for(let i=t;i<e.length;i+=1){let r=e[i];if(r==="(")n+=1;else if(r===")"&&(n-=1,n===0))return i}return e.length-1}function as(e,t){let n=0;for(let i=0;i<t&&i<e.length;i+=1)e[i]===`
416
- `&&(n+=1);return n}function _x(e,t){let n=e.slice(t,t+400),i=/^\s*(['"`])((?:\\.|(?!\1)[\s\S])*)\1/.exec(n);return i?i[2]:"(anonymous)"}var Hz=new Set(["vitest","chai","jest","@jest/globals","assert","node:assert","node:assert/strict","assert/strict","uvu/assert","expect","chai-as-promised"]),Ax=/import\s+(?:\*\s+as\s+(\w+)|\{([^}]*)\}|(\w+))\s+from\s+['"]([^'"]+)['"]/g;function Uz(e){let t=new Set(["expect","assert"]);Ax.lastIndex=0;let n;for(;n=Ax.exec(e);){let[,i,r,o,s]=n;if(!(!s||!Hz.has(s))&&(i&&t.add(i),o&&t.add(o),r))for(let a of r.split(",")){let l=a.trim().replace(/^type\s+/,"");if(!l)continue;let c=/^(\w+)\s+as\s+(\w+)$/.exec(l);t.add(c?c[2]:l)}}return t}function Bx(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 i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`\\b${i}\\s*(?:<[^<>]*>)?\\s*[.(]`).test(e))return!0}return!1}var zz=/\bfunction\s+(\w+)\s*\(/g,qz=/\b(?:const|let)\s+(\w+)\s*=\s*(?:async\s*)?\(/g,Kz=60;function Gz(e,t){let n=new Set;for(let i of[zz,qz]){i.lastIndex=0;let r;for(;r=i.exec(e);){let o=r[1],s=r.index+r[0].length-1,a=ls(e,s),l=e.indexOf("{",a+1);if(l===-1||l-a>Kz)continue;let c=Wz(e,l),u=e.slice(l+1,c);Bx(u,t)&&n.add(o)}}return n}function Wz(e,t){let n=0;for(let i=t;i<e.length;i+=1){let r=e[i];if(r==="{")n+=1;else if(r==="}"&&(n-=1,n===0))return i}return e.length-1}var Vz=/\bmock(?:ReturnValue|ResolvedValue)(?:Once)?\s*\(/g,pm=/\bexpect\s*\(/g,Jz=/^\s*\.\s*(?:toBe|toEqual|toStrictEqual)\s*\(/,Ox=/^(?:-?\d+(?:\.\d+)?|(['"`]).+\1)$/;function Yz(e,t){let n=Xz(e,t,Vz);if(n.length===0)return null;let i=Qz(e,t);for(let r of i)if(n.includes(r))return r;return null}function Xz(e,t,n){let i=[];n.lastIndex=0;let r;for(;r=n.exec(e);){let o=r.index+r[0].length-1,s=ls(e,o),a=t.slice(o+1,s).trim();Ox.test(a)&&i.push(a),n.lastIndex=s+1}return i}function Qz(e,t){let n=[];pm.lastIndex=0;let i;for(;i=pm.exec(e);){let r=i.index+i[0].length-1,o=ls(e,r),s=e.slice(o+1),a=Jz.exec(s);if(pm.lastIndex=o+1,!a)continue;let l=o+1+a[0].length-1,c=ls(e,l),u=t.slice(l+1,c).trim();Ox.test(u)&&n.push(u)}return n}function Zz(e,t,n,i){let r=se(e,t),o=_x(r,n.argsStart),s=as(r,n.callStart),a=eq(e.config.projectRoot,t,s),l=a===null?"unknown":a>=i?"rot":"workflow";return{file:t,startLine:s,title:o,skipKind:n.skipKind,blockKind:n.kind,ageDays:a,rot:l}}function eq(e,t,n){let i=n+1;try{let r=yn(e,["blame","-L",`${i},${i}`,"--porcelain","--",t]),o=/^author-time (\d+)$/m.exec(r);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 tq=.7,$x=.62,jx=.45;function nq(e,t={}){let{windowCommits:n=100,limit:i=30,scope:r,scanLimit:o}=t,s=Xt(e,{historyMode:t.historyMode}).fileAddRecords();if(!s)return{available:!1,windowCommits:n,findings:[]};if(i<=0)return{available:!0,windowCommits:n,findings:[]};let a=dq(s,n);if(a.size===0)return{available:!0,windowCommits:n,findings:[]};let c=iq(e,{limit:i,minSimilarity:t.minSimilarity,scanLimit:o,scope:r,semantic:t.semantic,focusFiles:Number.isFinite(i)?void 0:a}).map(d=>mq(d,s,n)).filter(d=>d!==null);c.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=c.slice(0,i).map(fq);return{available:!0,windowCommits:n,findings:u,rootCauseGroups:pq(u)}}function iq(e,t){let n=hq(t.limit),i=[...rq(e,{scope:t.scope,minSimilarity:t.minSimilarity??tq,limit:n,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles})],r=Fs(e,{scope:t.scope});return r.react&&i.push(...oq(e,{scope:t.scope,minSimilarity:t.minSimilarity??$x,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...sq(e,{scope:t.scope,minSimilarity:t.minSimilarity??jx,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),r.vue&&i.push(...cq(e,{scope:t.scope,minSimilarity:t.minSimilarity??$x,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...uq(e,{scope:t.scope,minSimilarity:t.minSimilarity??jx,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),i}function rq(e,t){return Yo(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles}).filter(n=>!Xe(n.symbolA)&&!Xe(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 oq(e,t){return wl(e,t,{query:Xo,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 wl(e,t,n){return n.query(e,t).filter(i=>i.fileA!==i.fileB).filter(i=>n.acceptPair?.(i)??!0).map(i=>({domain:n.domain,basis:n.basis,symbolA:n.symbolA(i),fileA:i.fileA,symbolB:n.symbolB(i),fileB:i.fileB,similarity:i.similarity,sharedEvidence:yq(...n.evidenceBuckets(i)),sharedCallees:[]}))}function sq(e,t){return wl(e,t,{query:Qo,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,acceptPair:lq,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 aq=new Set(["useCallback","useEffect","useLayoutEffect","useMemo","useMutation","useQueries","useQuery","useQueryClient","useReducer","useRef","useState"]);function lq(e){return e.sharedHooks.some(t=>!aq.has(t))||e.sharedState.length>0||e.sharedHandlers.length>0||e.sharedHandlerVerbs.length>=2}function cq(e,t){return wl(e,t,{query:Zo,domain:"vue-component",basis:"vue-template",symbolA:n=>El(n.fileA),symbolB:n=>El(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function uq(e,t){return wl(e,t,{query:es,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>El(n.fileA),symbolB:n=>El(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 dq(e,t){let n=new Set;for(let[i,r]of e)r.commitsAgo<=t&&n.add(i);return n}function mq(e,t,n){let i=t.get(e.fileA)?.commitsAgo??null,r=t.get(e.fileB)?.commitsAgo??null,o=i!==null&&i<=n,s=r!==null&&r<=n;if(!o&&!s)return null;if(o&&s){let a=(i??0)<=(r??0);return{kind:"twin",domain:e.domain,basis:e.basis,echoSymbol:a?e.symbolA:e.symbolB,echoFile:a?e.fileA:e.fileB,echoAgeCommits:(a?i:r)??0,establishedSymbol:a?e.symbolB:e.symbolA,establishedFile:a?e.fileB:e.fileA,establishedAgeCommits:a?r:i,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?i:r)??0,establishedSymbol:o?e.symbolB:e.symbolA,establishedFile:o?e.fileB:e.fileA,establishedAgeCommits:o?r:i,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}function fq(e){let t=Hx(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function Hx(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 pq(e){let t=new Map;for(let[n,i]of e.entries()){let r=i.rootCauseKey??Hx(i),o=i.groupKey??`recent-duplicate:${r}`,s=t.get(o);s||(s={groupKey:o,rootCauseKey:r,kind:i.kind,domain:i.domain,basis:i.basis,count:0,maxSimilarity:i.similarity,findingIndexes:[],echoFiles:new Set,establishedFile:i.kind==="echo"?i.establishedFile:void 0,establishedSymbol:i.kind==="echo"?i.establishedSymbol:void 0,relatedFiles:new Set,sharedEvidence:new Set,recommendation:gq(i)},t.set(o,s)),s.count+=1,s.maxSimilarity=Math.max(s.maxSimilarity,i.similarity),s.findingIndexes.push(n),s.echoFiles.add(i.echoFile),s.relatedFiles.add(i.echoFile),s.relatedFiles.add(i.establishedFile);for(let a of i.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,i)=>i.count-n.count||i.maxSimilarity-n.maxSimilarity||n.groupKey.localeCompare(i.groupKey))}function gq(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 hq(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function yq(...e){let t=[],n=new Set;for(let[i,r]of e)for(let o of r){let s=`${i}:${o}`;n.has(s)||(n.add(s),t.push(s))}return t}function El(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var bq=Fe("suppression-inventory",{clearGroups:["whole-project"]});function Ll(e){return bq.get(e,()=>Sq(e))}function Sq(e){let t={dead:0,stale:0,wrapper:0,passthrough:0,drift:0,extract:0,similar:0,twin:0,uncategorized:0},n=new Map,i=0;for(let r of Xi(e)){let o=se(e,r);if(!(!o||!o.includes("codebaseiq")))for(let s of o.split(/\r?\n/)){let a=Ds(s);if(a===null)continue;i+=1,n.set(r,(n.get(r)??0)+1);let l=Ux(a);t[l]+=1}}for(let r of e.config.suppressions??[])r.expiresAt&&Date.parse(r.expiresAt)<=Date.now()||(i+=1,r.file&&n.set(r.file,(n.get(r.file)??0)+1),t[Ux(r.check)]+=1);return{total:i,byCategory:t,byFile:n}}function Ux(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 gm(e,t,n={}){let i=pe(e,t);if(!i)return null;let r=new U(e),o=vq(e,i),s=i.endLine-i.startLine+1,a=r.calleeEvidenceMap([i],{additive:!0,semantic:n.semantic}),l=a.rows.get(i.symbolId)??[],c=new Set(l.map(p=>p.symbol)),u=a.incompleteSymbolIds.has(i.symbolId),d=a.unavailableSymbolIds.has(i.symbolId),m=n.semantic===!1?"disabled":u&&d?"incomplete-and-unavailable":u?"incomplete":d?"unavailable":"complete",f=!u&&!d;return{symbol:i.symbol,shortName:A(i.symbol),relativePath:i.relativePath,startLine:i.startLine,endLine:i.endLine,loc:s,branches:o.branches,estimateBasis:o.estimateBasis,cyclomaticEstimate:o.branches+1,calleeCount:f?c.size:null,fanIn:xq(e,i.symbolId),fanOut:f?Rq(l,i.relativePath):null,coverage:{semanticEvidence:m}}}function vq(e,t){let n=ae(e,t.relativePath);if(n){let i=Gx(n.rootNode,t.startLine,t.endLine);if(i)return{branches:Iq(i),estimateBasis:"ast"}}return{branches:Vx(Kx(e,t.relativePath,t.startLine,t.endLine),qx(e,t.relativePath)),estimateBasis:"regex-fallback"}}function zx(e,t){let n=new Map,i=new Map;for(let r of t){let o=i.get(r.relativePath)??[];o.push(r),i.set(r.relativePath,o)}for(let[r,o]of i){let s=ae(e,r),a=s===null?[]:o.filter(c=>s.rootNode.startPosition.row<=c.startLine&&s.rootNode.endPosition.row>=c.endLine),l=new Set(a.map(c=>c.symbolId));if(s&&a.length>0){for(let c of a)n.set(c.symbolId,{branches:0,estimateBasis:"ast"});Eq(s.rootNode,a,n)}for(let c of o)l.has(c.symbolId)||n.set(c.symbolId,Cq(e,c))}return n}function Cq(e,t){return{branches:Vx(Kx(e,t.relativePath,t.startLine,t.endLine),qx(e,t.relativePath)),estimateBasis:"regex-fallback"}}function qx(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function Kx(e,t,n,i){try{return rt(e.config.projectRoot,t,{inputKind:"indexed source file"}).split(`
415
+ `}var Mx={caller:3,"entry-surface":2,rooted:1},iz=/not\s*yet\s*implement|not\s*implement|unimplement|\bnyi\b|\btodo\b|\bstub\b|not\s*supported|coming\s*soon/i,rz=/^throw\s+new\s+[\w.]*Error\s*\(([\s\S]*)\)\s*;?$/,oz=/^return(\s+(null|undefined|false|0|''|""|``|\[\]|\{\}))?\s*;?$/,sz=/\/\/\s*TODO\b|\/\*\s*TODO\b/i,az=/(?:=>|\))\s*(?::\s*[^{;=]+)?\s*\{\s*\}\s*;?\s*$/;function lz(e,t={}){let{scope:n,limit:i=30,scanLimit:r,semantic:o=!0}=t,s=new U(e),a=ke(s.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),r),l=[];for(let f of a){let p=uz(e,f);p&&l.push(p)}if(l.length===0)return[];let c=pz(e,l,a),u=l.filter(f=>!c.has(f.def.symbol));if(u.length===0)return[];let d=hn(e,s).forDefinitions(u.map(f=>f.def),{semantic:o}),m=[];for(let f of u){let p=d.get(f.def.symbolId);if(p?.semanticIncomplete||p?.semanticUnavailable)continue;let g=p?.realConsumers.length??0,h=cz(e,f.def,g);h&&m.push({symbol:f.def.symbol,shortName:A(f.def.symbol),file:f.def.relativePath,startLine:f.def.startLine,endLine:f.def.endLine,loc:de(f.def),stubKind:f.stubKind,reachability:h,callerFanIn:g,stubText:f.stubText})}return m.sort((f,p)=>Mx[p.reachability]-Mx[f.reachability]||p.callerFanIn-f.callerFanIn||f.file.localeCompare(p.file)||f.startLine-p.startLine),i?m.slice(0,i):m}function cz(e,t,n){return n>0?"caller":qe(e,t.symbol,t.relativePath)?"rooted":Qe(e,t.relativePath)?"entry-surface":null}function uz(e,t){let n=Qt(e,t);if(!n)return null;let i=bn(n),r=i.trim();if(r==="")return!fz(n)||!xt(e,t)?null:{def:t,stubKind:"empty-body",stubText:"(empty body)"};let o=Or(i),s=xn(i),a=dz(o,s);if(a.length!==1)return null;let l=a[0];return mz(l)?{def:t,stubKind:"throw-stub",stubText:l.trim()}:sz.test(i)&&oz.test(l.trim())?{def:t,stubKind:"todo-return-default",stubText:r}:null}function dz(e,t){let n=[],i=0,r="";for(let o=0;o<t.length;o+=1){let s=t[o];if(s==="("||s==="["||s==="{"?i+=1:(s===")"||s==="]"||s==="}")&&(i=Math.max(0,i-1)),s===";"&&i===0){n.push(r),r="";continue}r+=e[o]??""}return r.trim()&&n.push(r),n.map(o=>o.trim()).filter(o=>o.length>0)}function mz(e){let t=rz.exec(e.trim());return t?iz.test(t[1]??""):!1}function fz(e){return az.test(e.trimEnd())}function pz(e,t,n){let i=new Set,r=new Set(t.map(a=>a.def.parentTypeName).filter(a=>a!==null));if(r.size===0)return i;let o=hz(e,r),s=new Map;for(let a of n){if(!a.parentTypeName)continue;let l=s.get(a.leaf)??new Set;l.add(a.parentTypeName),s.set(a.leaf,l)}for(let a of t){let l=a.def.parentTypeName;if(!l)continue;let c=o.get(l);if(!c||c.size===0)continue;let u=s.get(a.def.leaf)??new Set;[...c].every(m=>u.has(m))&&i.add(a.def.symbol)}return i}var gz=/\bclass\s+([A-Za-z_$][\w$]*)\s+extends\s+([A-Za-z_$][\w$]*)/g;function hz(e,t){let n=new Map;for(let i of me(e,{includeIgnored:!1})){let r=se(e,i);if(r)for(let o of r.matchAll(gz)){let s=o[1],a=o[2];if(!s||!a||!t.has(a))continue;let l=n.get(a)??new Set;l.add(s),n.set(a,l)}}return n}var yz=/^(?:validate|verify|check|assert)(?:[A-Z].*)?$/,bz=/^(?:is|has)(?:[A-Z].*)?$/,Sz=/[{,]\s*(?:ok|success|valid|isValid)\s*:\s*false\b/,lm=/\breturn\b/g,vz=/\bfunction\b|=>|\)\s*(?::\s*[^{;=]+)?\s*\{/,Cz=/\.(?:addIssue|push)\s*\(/;function xz(e,t={}){let{scope:n,limit:i=30,scanLimit:r}=t,o=new U(e),s=ke(o.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),r),a=[];for(let l of s){let c=Iz(e,l);c&&a.push({symbol:l.symbol,shortName:A(l.symbol),file:l.relativePath,startLine:l.startLine,endLine:l.endLine,loc:de(l),...c})}return a.sort((l,c)=>l.file.localeCompare(c.file)||l.startLine-c.startLine||l.loc-c.loc),i?a.slice(0,i):a}function Rz(e){return yz.test(e)?"imperative":bz.test(e)?"predicate":null}function Iz(e,t){let n=Rz(t.leaf);if(!n||Rr(e,t))return null;let i=Qt(e,t);if(!i||!vz.test(i))return null;let r=te(e,t.relativePath)?.callables.find(s=>s.startLine===t.startLine&&s.endLine===t.endLine);if(n==="predicate"&&r?.paramCount===0)return null;if(vx(i)){let s=Lz(e,t);return!s||Fx(s.body,Tx(s.snippet))||Px(s.body)?null:{nameKind:n,resolvedVia:"one-hop-delegate",delegateTarget:s.shortName}}let o=bn(i);return Fx(o,Tx(i))||Px(o)?null:{nameKind:n,resolvedVia:"direct"}}var Ez=new Set(["if","for","while","switch","catch","function"]);function Px(e){let t=Or(e);for(let n of t.matchAll(/\b([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(/g))if(!Ez.has(n[1]))return!0;return!1}function Tx(e){let t=e.indexOf("=>");return t===-1?!1:!/^\s*\{/.test(e.slice(t+2))}function Fx(e,t){let n=Or(e);if(/\bthrow\b/.test(n)||/\.reject\s*\(/.test(n)||Sz.test(n)||Cz.test(n))return!0;let i=wz(n);if(t&&i.length===0){let r=n.trim();return r!==""&&r!=="true"}for(let r of i)if(r!==""&&r!=="true")return!0;return!1}function wz(e){let t=[];lm.lastIndex=0;let n;for(;n=lm.exec(e);){let i=n.index+n[0].length,r=0,o=e.length;for(let s=i;s<e.length;s+=1){let a=e[s];if(a==="("||a==="["||a==="{")r+=1;else if(a===")"||a==="]"||a==="}"){if(r===0){o=s;break}r-=1}else if(a===";"&&r===0){o=s;break}}t.push(e.slice(i,o).trim()),lm.lastIndex=o}return t}function Lz(e,t){let n=vi(e,t,{callableOnly:!0,limit:3,semanticEvidence:ge});if(n.semanticIncomplete||n.semanticUnavailable)return null;let i=n.rows,r=[...new Set(i.map(c=>c.symbol))].filter(c=>c!==t.symbol);if(r.length!==1)return null;let s=at(e,r[0]).match;if(!s)return null;let a=W(e,s.relativePath).find(c=>c.symbolId===s.symbolId);if(!a)return null;let l=Qt(e,a);return l?{body:bn(l),snippet:l,shortName:A(a.symbol)}:null}var Dz=60;function Mz(e,t={}){let{scope:n,limit:i=30,scanLimit:r,rotDays:o=Dz}=t,s=ke(Ji(e,{extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs"]}).filter(u=>J(u)==="test").filter(u=>!n||u.includes(n)).filter(u=>!e.isIgnored(u)).sort(),r),a=[],l=[],c=[];for(let u of s){let d=se(e,u);if(!d)continue;let m=Sf(d),f=Fz(d);for(let g of _z(m,f))f.add(g);let p=Pz(m);for(let g of p){if(g.skip){l.push(zz(e,u,g,o));continue}if(g.kind==="describe")continue;let h=Nx(d,g.argsStart),b=m.slice(g.argsStart,g.callEnd),v=d.slice(g.argsStart,g.callEnd);Ax(b,f)||a.push({file:u,startLine:os(d,g.callStart),endLine:os(d,g.callEnd),title:h,severity:/\bawait\b/.test(b)?"low":"high"});let y=jz(b,v);y&&c.push({file:u,startLine:os(d,g.callStart),endLine:os(d,g.callEnd),title:h,echoedValue:y})}}return{assertionFree:i?a.slice(0,i):a,skipped:i?l.slice(0,i):l,mockEcho:i?c.slice(0,i):c}}var cm=/(?<!\.)\b(?:x(it|test|describe)|(it|test|describe)(?:\.\s*(skip|only|todo|each\s*\([^)]*\)))?)\s*\(/g;function Pz(e){let t=[];cm.lastIndex=0;let n;for(;n=cm.exec(e);){let i=n[1],r=i??n[2];if(!r)continue;let o=n[3]?.split(/\s*\(/)[0],s=n.index,a=n.index+n[0].length-1,l=ss(e,a);cm.lastIndex=a+1,o!=="each"&&t.push({kind:r,skip:i!==void 0||o==="skip"||o==="todo",skipKind:o==="todo"?"todo":"skip",callStart:s,argsStart:a+1,callEnd:l+1})}return t}function ss(e,t){let n=0;for(let i=t;i<e.length;i+=1){let r=e[i];if(r==="(")n+=1;else if(r===")"&&(n-=1,n===0))return i}return e.length-1}function os(e,t){let n=0;for(let i=0;i<t&&i<e.length;i+=1)e[i]===`
416
+ `&&(n+=1);return n}function Nx(e,t){let n=e.slice(t,t+400),i=/^\s*(['"`])((?:\\.|(?!\1)[\s\S])*)\1/.exec(n);return i?i[2]:"(anonymous)"}var Tz=new Set(["vitest","chai","jest","@jest/globals","assert","node:assert","node:assert/strict","assert/strict","uvu/assert","expect","chai-as-promised"]),kx=/import\s+(?:\*\s+as\s+(\w+)|\{([^}]*)\}|(\w+))\s+from\s+['"]([^'"]+)['"]/g;function Fz(e){let t=new Set(["expect","assert"]);kx.lastIndex=0;let n;for(;n=kx.exec(e);){let[,i,r,o,s]=n;if(!(!s||!Tz.has(s))&&(i&&t.add(i),o&&t.add(o),r))for(let a of r.split(",")){let l=a.trim().replace(/^type\s+/,"");if(!l)continue;let c=/^(\w+)\s+as\s+(\w+)$/.exec(l);t.add(c?c[2]:l)}}return t}function Ax(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 i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`\\b${i}\\s*(?:<[^<>]*>)?\\s*[.(]`).test(e))return!0}return!1}var kz=/\bfunction\s+(\w+)\s*\(/g,Nz=/\b(?:const|let)\s+(\w+)\s*=\s*(?:async\s*)?\(/g,Az=60;function _z(e,t){let n=new Set;for(let i of[kz,Nz]){i.lastIndex=0;let r;for(;r=i.exec(e);){let o=r[1],s=r.index+r[0].length-1,a=ss(e,s),l=e.indexOf("{",a+1);if(l===-1||l-a>Az)continue;let c=Bz(e,l),u=e.slice(l+1,c);Ax(u,t)&&n.add(o)}}return n}function Bz(e,t){let n=0;for(let i=t;i<e.length;i+=1){let r=e[i];if(r==="{")n+=1;else if(r==="}"&&(n-=1,n===0))return i}return e.length-1}var Oz=/\bmock(?:ReturnValue|ResolvedValue)(?:Once)?\s*\(/g,um=/\bexpect\s*\(/g,$z=/^\s*\.\s*(?:toBe|toEqual|toStrictEqual)\s*\(/,_x=/^(?:-?\d+(?:\.\d+)?|(['"`]).+\1)$/;function jz(e,t){let n=Hz(e,t,Oz);if(n.length===0)return null;let i=Uz(e,t);for(let r of i)if(n.includes(r))return r;return null}function Hz(e,t,n){let i=[];n.lastIndex=0;let r;for(;r=n.exec(e);){let o=r.index+r[0].length-1,s=ss(e,o),a=t.slice(o+1,s).trim();_x.test(a)&&i.push(a),n.lastIndex=s+1}return i}function Uz(e,t){let n=[];um.lastIndex=0;let i;for(;i=um.exec(e);){let r=i.index+i[0].length-1,o=ss(e,r),s=e.slice(o+1),a=$z.exec(s);if(um.lastIndex=o+1,!a)continue;let l=o+1+a[0].length-1,c=ss(e,l),u=t.slice(l+1,c).trim();_x.test(u)&&n.push(u)}return n}function zz(e,t,n,i){let r=se(e,t),o=Nx(r,n.argsStart),s=os(r,n.callStart),a=qz(e.config.projectRoot,t,s),l=a===null?"unknown":a>=i?"rot":"workflow";return{file:t,startLine:s,title:o,skipKind:n.skipKind,blockKind:n.kind,ageDays:a,rot:l}}function qz(e,t,n){let i=n+1;try{let r=yn(e,["blame","-L",`${i},${i}`,"--porcelain","--",t]),o=/^author-time (\d+)$/m.exec(r);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 Kz=.7,Bx=.62,Ox=.45;function Gz(e,t={}){let{windowCommits:n=100,limit:i=30,scope:r,scanLimit:o}=t,s=Xt(e,{historyMode:t.historyMode}).fileAddRecords();if(!s)return{available:!1,windowCommits:n,findings:[]};if(i<=0)return{available:!0,windowCommits:n,findings:[]};let a=tq(s,n);if(a.size===0)return{available:!0,windowCommits:n,findings:[]};let c=Wz(e,{limit:i,minSimilarity:t.minSimilarity,scanLimit:o,scope:r,semantic:t.semantic,focusFiles:Number.isFinite(i)?void 0:a}).map(d=>nq(d,s,n)).filter(d=>d!==null);c.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=c.slice(0,i).map(iq);return{available:!0,windowCommits:n,findings:u,rootCauseGroups:rq(u)}}function Wz(e,t){let n=sq(t.limit),i=[...Vz(e,{scope:t.scope,minSimilarity:t.minSimilarity??Kz,limit:n,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles})],r=Ps(e,{scope:t.scope});return r.react&&i.push(...Jz(e,{scope:t.scope,minSimilarity:t.minSimilarity??Bx,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...Yz(e,{scope:t.scope,minSimilarity:t.minSimilarity??Ox,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),r.vue&&i.push(...Zz(e,{scope:t.scope,minSimilarity:t.minSimilarity??Bx,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...eq(e,{scope:t.scope,minSimilarity:t.minSimilarity??Ox,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),i}function Vz(e,t){return Vo(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles}).filter(n=>!Xe(n.symbolA)&&!Xe(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 Jz(e,t){return El(e,t,{query:Jo,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 El(e,t,n){return n.query(e,t).filter(i=>i.fileA!==i.fileB).filter(i=>n.acceptPair?.(i)??!0).map(i=>({domain:n.domain,basis:n.basis,symbolA:n.symbolA(i),fileA:i.fileA,symbolB:n.symbolB(i),fileB:i.fileB,similarity:i.similarity,sharedEvidence:aq(...n.evidenceBuckets(i)),sharedCallees:[]}))}function Yz(e,t){return El(e,t,{query:Yo,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,acceptPair:Qz,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 Xz=new Set(["useCallback","useEffect","useLayoutEffect","useMemo","useMutation","useQueries","useQuery","useQueryClient","useReducer","useRef","useState"]);function Qz(e){return e.sharedHooks.some(t=>!Xz.has(t))||e.sharedState.length>0||e.sharedHandlers.length>0||e.sharedHandlerVerbs.length>=2}function Zz(e,t){return El(e,t,{query:Xo,domain:"vue-component",basis:"vue-template",symbolA:n=>Il(n.fileA),symbolB:n=>Il(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function eq(e,t){return El(e,t,{query:Qo,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>Il(n.fileA),symbolB:n=>Il(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 tq(e,t){let n=new Set;for(let[i,r]of e)r.commitsAgo<=t&&n.add(i);return n}function nq(e,t,n){let i=t.get(e.fileA)?.commitsAgo??null,r=t.get(e.fileB)?.commitsAgo??null,o=i!==null&&i<=n,s=r!==null&&r<=n;if(!o&&!s)return null;if(o&&s){let a=(i??0)<=(r??0);return{kind:"twin",domain:e.domain,basis:e.basis,echoSymbol:a?e.symbolA:e.symbolB,echoFile:a?e.fileA:e.fileB,echoAgeCommits:(a?i:r)??0,establishedSymbol:a?e.symbolB:e.symbolA,establishedFile:a?e.fileB:e.fileA,establishedAgeCommits:a?r:i,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?i:r)??0,establishedSymbol:o?e.symbolB:e.symbolA,establishedFile:o?e.fileB:e.fileA,establishedAgeCommits:o?r:i,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}function iq(e){let t=$x(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function $x(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 rq(e){let t=new Map;for(let[n,i]of e.entries()){let r=i.rootCauseKey??$x(i),o=i.groupKey??`recent-duplicate:${r}`,s=t.get(o);s||(s={groupKey:o,rootCauseKey:r,kind:i.kind,domain:i.domain,basis:i.basis,count:0,maxSimilarity:i.similarity,findingIndexes:[],echoFiles:new Set,establishedFile:i.kind==="echo"?i.establishedFile:void 0,establishedSymbol:i.kind==="echo"?i.establishedSymbol:void 0,relatedFiles:new Set,sharedEvidence:new Set,recommendation:oq(i)},t.set(o,s)),s.count+=1,s.maxSimilarity=Math.max(s.maxSimilarity,i.similarity),s.findingIndexes.push(n),s.echoFiles.add(i.echoFile),s.relatedFiles.add(i.echoFile),s.relatedFiles.add(i.establishedFile);for(let a of i.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,i)=>i.count-n.count||i.maxSimilarity-n.maxSimilarity||n.groupKey.localeCompare(i.groupKey))}function oq(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 sq(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function aq(...e){let t=[],n=new Set;for(let[i,r]of e)for(let o of r){let s=`${i}:${o}`;n.has(s)||(n.add(s),t.push(s))}return t}function Il(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var lq=Fe("suppression-inventory",{clearGroups:["whole-project"]});function wl(e){return lq.get(e,()=>cq(e))}function cq(e){let t={dead:0,stale:0,wrapper:0,passthrough:0,drift:0,extract:0,similar:0,twin:0,uncategorized:0},n=new Map,i=0;for(let r of Ji(e)){let o=se(e,r);if(!(!o||!o.includes("codebaseiq")))for(let s of o.split(/\r?\n/)){let a=ws(s);if(a===null)continue;i+=1,n.set(r,(n.get(r)??0)+1);let l=jx(a);t[l]+=1}}for(let r of e.config.suppressions??[])r.expiresAt&&Date.parse(r.expiresAt)<=Date.now()||(i+=1,r.file&&n.set(r.file,(n.get(r.file)??0)+1),t[jx(r.check)]+=1);return{total:i,byCategory:t,byFile:n}}function jx(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 dm(e,t,n={}){let i=pe(e,t);if(!i)return null;let r=new U(e),o=uq(e,i),s=i.endLine-i.startLine+1,a=r.calleeEvidenceMap([i],{additive:!0,semantic:n.semantic}),l=a.rows.get(i.symbolId)??[],c=new Set(l.map(p=>p.symbol)),u=a.incompleteSymbolIds.has(i.symbolId),d=a.unavailableSymbolIds.has(i.symbolId),m=n.semantic===!1?"disabled":u&&d?"incomplete-and-unavailable":u?"incomplete":d?"unavailable":"complete",f=!u&&!d;return{symbol:i.symbol,shortName:A(i.symbol),relativePath:i.relativePath,startLine:i.startLine,endLine:i.endLine,loc:s,branches:o.branches,estimateBasis:o.estimateBasis,cyclomaticEstimate:o.branches+1,calleeCount:f?c.size:null,fanIn:mq(e,i.symbolId),fanOut:f?fq(l,i.relativePath):null,coverage:{semanticEvidence:m}}}function uq(e,t){let n=ae(e,t.relativePath);if(n){let i=qx(n.rootNode,t.startLine,t.endLine);if(i)return{branches:pq(i),estimateBasis:"ast"}}return{branches:Gx(zx(e,t.relativePath,t.startLine,t.endLine),Ux(e,t.relativePath)),estimateBasis:"regex-fallback"}}function Hx(e,t){let n=new Map,i=new Map;for(let r of t){let o=i.get(r.relativePath)??[];o.push(r),i.set(r.relativePath,o)}for(let[r,o]of i){let s=ae(e,r),a=s===null?[]:o.filter(c=>s.rootNode.startPosition.row<=c.startLine&&s.rootNode.endPosition.row>=c.endLine),l=new Set(a.map(c=>c.symbolId));if(s&&a.length>0){for(let c of a)n.set(c.symbolId,{branches:0,estimateBasis:"ast"});gq(s.rootNode,a,n)}for(let c of o)l.has(c.symbolId)||n.set(c.symbolId,dq(e,c))}return n}function dq(e,t){return{branches:Gx(zx(e,t.relativePath,t.startLine,t.endLine),Ux(e,t.relativePath)),estimateBasis:"regex-fallback"}}function Ux(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function zx(e,t,n,i){try{return rt(e.config.projectRoot,t,{inputKind:"indexed source file"}).split(`
417
417
  `).slice(n,i+1).join(`
418
- `)}catch(r){if(!ot(r))throw r;return""}}function xq(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
418
+ `)}catch(r){if(!ot(r))throw r;return""}}function mq(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
419
419
  FROM mentions m
420
420
  JOIN chunks c ON m.chunk_id = c.id
421
421
  JOIN (
@@ -427,11 +427,11 @@ describe.skipIf(inputs.length === 0)('twin-ab: ${e.shortName} vs ${t.shortName}'
427
427
  ) sym_def ON sym_def.symbol_id = m.symbol_id
428
428
  WHERE m.symbol_id = ?
429
429
  AND m.role != 1
430
- AND sym_def.document_id != c.document_id`,t)?.c??0}function Rq(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function Iq(e){let t=0;return hm(e,n=>{t+=Wx(n)}),t}function Eq(e,t,n){let i=[...t].sort((r,o)=>r.startLine-o.startLine||o.endLine-r.endLine);hm(e,r=>{let o=Wx(r);if(o===0)return;let s=r.startPosition.row,a=r.endPosition.row;for(let l of i){if(l.startLine>s)break;if(l.endLine<a)continue;let c=n.get(l.symbolId);c&&(c.branches+=o)}})}function hm(e,t){t(e);for(let n of e.namedChildren)hm(n,t)}function Gx(e,t,n){if(e.startPosition.row>t||e.endPosition.row<n)return null;for(let i of e.namedChildren){let r=Gx(i,t,n);if(r)return r}return e}var wq=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 Wx(e){return wq.has(e.type)?1:e.type==="binary_expression"&&e.parent?.type!=="binary_expression"&&(e.text.includes("&&")||e.text.includes("||"))?Lq(e.text):0}function Lq(e){return(e.match(/&&|\|\|/g)??[]).length}function Vx(e,t){let n=xn(e),i=0,r=[/\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 r){let s=n.match(o);s&&(i+=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&&(i+=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&&(i+=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&&(i+=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&&(i+=a.length)}}return i}function Jx(e,t,n={}){let i=pe(e,t);if(!i)return null;let r=[{file:i.relativePath,line:i.startLine}],o=Kn(e,i,{semantic:n.semantic,semanticEvidence:ge}).map(l=>({file:l.file,line:l.line,enclosingSymbol:l.enclosingSymbol??"(top-level)",enclosingShort:l.enclosingSymbol?A(l.enclosingSymbol):"(top-level)"})),{outgoingCalls:s,incomingCalls:a}=Dq(e,i,o,{semantic:n.semantic!==!1});return{symbol:i.symbol,shortName:A(i.symbol),relativePath:i.relativePath,definitionSites:r.filter(l=>!e.isIgnored(l.file)),referenceSites:o,outgoingCalls:s.filter(l=>!e.isIgnored(l.file)).map(l=>({symbol:l.symbol,shortName:A(l.symbol),file:l.file})),incomingCalls:a.filter(l=>!e.isIgnored(l.file)).map(l=>({symbol:l.symbol,shortName:l.symbol===l.file?"(top-level)":A(l.symbol),file:l.file}))}}function ym(e,t,n={}){let i=Jx(e,t,n);return i?{symbol:i.symbol,shortName:i.shortName,relativePath:i.relativePath,definitionSites:i.definitionSites,usageSites:i.referenceSites,producers:i.outgoingCalls,consumers:i.incomingCalls}:null}function Dq(e,t,n,i){let r=br(Ks(e,t,{limit:30,semantic:i.semantic,semanticEvidence:ge}).map(a=>({symbol:a.symbol,file:a.file}))),o=br(Gs(e,t,{limit:30,semantic:i.semantic,semanticEvidence:ge})),s=o.length>0?o:br(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{outgoingCalls:r,incomingCalls:s}}function Yx(e,t,n={}){let{direction:i="backward",maxDepth:r=3}=n,o=pe(e,t);return o?i==="backward"?Mq(e,o,r,{semantic:n.semantic!==!1}):Pq(e,o,{semantic:n.semantic!==!1}):null}function Dl(e,t,n={}){return Yx(e,t,n)}function Mq(e,t,n,i){let r=[],o=new Set([t.symbol]),s=[t];for(let a=1;a<=n&&s.length!==0;a++){let l=[];for(let c of s){let u=Ks(e,c,{semantic:i.semantic,semanticEvidence:ge});for(let d of u){if(o.has(d.symbol))continue;o.add(d.symbol),r.push({symbol:d.symbol,shortName:A(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let m=Si(e,d.symbol);m&&!e.isIgnored(m.relativePath)&&l.push(m)}}s=l}return{symbol:t.symbol,shortName:A(t.symbol),direction:"backward",connectedSymbols:r}}function Pq(e,t,n){let i=new Set,r=[],o=new U(e);for(let s of Kn(e,t,{semantic:n.semantic,semanticEvidence:ge})){if(r.length>=30)break;let a=s.enclosingSymbol??Ke(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let l=Si(e,a);!l||e.isIgnored(l.relativePath)||i.has(l.symbol)||(i.add(l.symbol),r.push({symbol:l.symbol,shortName:A(l.symbol),file:l.relativePath,relationship:`references target at ${s.file}:${s.line+1}`}))}return r.sort((s,a)=>s.file.localeCompare(a.file)),{symbol:t.symbol,shortName:A(t.symbol),direction:"forward",connectedSymbols:r}}function Xx(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 iR=6,Pl=10,Sm=3,vm=8,Tq=.7,Qx=24,bm=200,rR=12,Zx=80,eR=600;function Fq(e,t,n={}){let i=n.impactDepth??3,r=n.sliceDepth??3,o=n.semantic,s=Uq(t)?Nq(e,t):null,a=s?s.primary?.symbol??null:t,l=a!==null,c=l?We("trace",a,()=>ju(e,a,{semantic:o,referenceContext:rR}),P=>({definitions:P.definitions.length,references:P.referencedBy.length})):{definitions:[],referencedBy:[],claimSupport:null},u=l?We("call-graph",a,()=>Lo(e,a,{semantic:o}),P=>({callers:P?.callers.length??0,callees:P?.callees.length??0})):null,d=l?We("complexity",a,()=>gm(e,a,{semantic:o}),P=>({callees:P?.calleeCount??0})):null,m=l?We("dataflow",a,()=>ym(e,a,{semantic:o}),P=>({references:P?.usageSites.length??0,producers:P?.producers.length??0,consumers:P?.consumers.length??0})):null,f=l?We("backward-slice",a,()=>Dl(e,a,{direction:"backward",maxDepth:r,semantic:o}),P=>({maxDepth:r,connectedSymbols:P?.connectedSymbols.length??0})):null,p=l?We("forward-slice",a,()=>Dl(e,a,{direction:"forward",maxDepth:r,semantic:o}),P=>({maxDepth:r,connectedSymbols:P?.connectedSymbols.length??0})):null,g=l?We("affected",a,()=>Ud(e,a,{maxDepth:i,scope:n.scope}),P=>({maxDepth:i,affectedSymbols:P.rows.length,coverage:P.coverage.status})):null,h=g?.rows??[],b=g?.coverage??null,v=l?We("reuse-candidates",a,()=>Jo(e,a,{minSimilarity:.4,limit:5,semantic:o,sourceCandidateMode:"target-pruned"}),P=>({candidates:P.length,direct:P.filter(k=>k.actionTier==="direct").length})):[],y=l?pe(e,a)?.symbol??null:null,I=l?We("affected-consumer-reuse",a,()=>_q(c,y,P=>Jo(e,P,{minSimilarity:.4,limit:Pl,semantic:o,sourceCandidateMode:"target-pruned"}),{consumerLimit:iR,perConsumerSearchLimit:Pl,perConsumerCandidateLimit:Sm,candidateLimit:vm}),P=>({totalConsumers:P.coverage.totalConsumers,analyzedConsumers:P.coverage.analyzedConsumers,candidates:P.candidates.length})):jq(),E=We("change-surface",t,()=>zd(e,t,{semantic:o}),P=>({symbols:P?.symbols.length??0,externalConsumers:P?.totalExternalConsumers??0})),S=We("system",t,()=>bd(e,t),P=>({files:P.files.length,symbols:P.symbols.length})),x=S.files.length===1,C=We("deps",t,()=>x?S.dependsOn.map(P=>({relativePath:P,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):Do(e,t),P=>({files:P.length,reusedSystem:x})),L=We("rdeps",t,()=>x?S.dependedOnBy.map(P=>({relativePath:P,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):Mo(e,t),P=>({files:P.length,reusedSystem:x})),w=We("surface",t,()=>Sd(e,t),P=>({consumers:P.length})),R={symbol:c.definitions.length>0||c.referencedBy.length>0||u!==null||d!==null||m!==null||f!==null||p!==null||h.length>0,file:E!==null||C.length>0||L.length>0,module:S.files.length>0||S.symbols.length>0||w.length>0},M=[];s&&!s.primary&&s.callableCount>1&&M.push(`File target has ${s.callableCount} callable symbols; use one callable name for compiler-resolved flow.`);let _=[...new Set(c.referencedBy.map(P=>P.relativePath))];_.length>0&&_.every(P=>J(P)==="test")&&M.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."),!R.symbol&&!R.file&&!R.module&&M.push("No symbol, file, or module matched target."),b&&b.status!=="accounted"&&M.push(`Possible-impact coverage is ${b.status}: ${b.reasons.join(" ")}`);let D=E?.file??c.definitions[0]?.relativePath??null;return{target:t,...s?.primary?{primaryCallable:{symbol:s.primary.symbol,shortName:Y(s.primary.symbol),file:s.primary.relativePath}}:{},matched:R,history:We("history",D??t,()=>Hq(e,D,n.gitHead)),trace:kq(c),callGraph:u,complexity:d,dataflow:m,backwardSlice:f,forwardSlice:p,affected:h,affectedCoverage:b,changeSurface:E,deps:C,rdeps:L,system:S,surface:w,reuseCandidates:v,affectedConsumerReuse:I,sourcePacket:Aq(e,y,c,I,v),warnings:M}}function kq(e){return{definitions:e.definitions,referencedBy:e.referencedBy.map(t=>({relativePath:t.relativePath,line:t.line,enclosingSymbol:t.enclosingSymbol,enclosingShort:t.enclosingShort}))}}function Nq(e,t){let n=In(e,t);if(n.length!==1)return{primary:null,callableCount:0};let i=W(e,n[0]).filter(s=>s.isFunctionLike),r=i.filter(s=>s.enclosingSymbol===null),o=r.length>0?r:i;return{primary:o.length===1?o[0]:null,callableCount:o.length}}function Aq(e,t,n,i,r){let o=[...t?[{definition:tR(e,t),role:"target"}]:[],...[...i.candidates.map(d=>d.candidate),...r].map(d=>({definition:tR(e,d.symbolB),role:"reuse-candidate"}))],s=new Map;for(let d of Xx(o)){if(s.has(d.definition.symbol))continue;let m=d.role==="target"?bm:Zx,f=d.definition.endLine<=d.definition.startLine?Jn(e,d.definition.relativePath,d.definition.startLine,m):null,p=f?.unitType?f.source:Qt(e,d.definition);if(!p)continue;let g=p.split(`
430
+ AND sym_def.document_id != c.document_id`,t)?.c??0}function fq(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function pq(e){let t=0;return mm(e,n=>{t+=Kx(n)}),t}function gq(e,t,n){let i=[...t].sort((r,o)=>r.startLine-o.startLine||o.endLine-r.endLine);mm(e,r=>{let o=Kx(r);if(o===0)return;let s=r.startPosition.row,a=r.endPosition.row;for(let l of i){if(l.startLine>s)break;if(l.endLine<a)continue;let c=n.get(l.symbolId);c&&(c.branches+=o)}})}function mm(e,t){t(e);for(let n of e.namedChildren)mm(n,t)}function qx(e,t,n){if(e.startPosition.row>t||e.endPosition.row<n)return null;for(let i of e.namedChildren){let r=qx(i,t,n);if(r)return r}return e}var hq=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 Kx(e){return hq.has(e.type)?1:e.type==="binary_expression"&&e.parent?.type!=="binary_expression"&&(e.text.includes("&&")||e.text.includes("||"))?yq(e.text):0}function yq(e){return(e.match(/&&|\|\|/g)??[]).length}function Gx(e,t){let n=xn(e),i=0,r=[/\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 r){let s=n.match(o);s&&(i+=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&&(i+=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&&(i+=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&&(i+=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&&(i+=a.length)}}return i}function Wx(e,t,n={}){let i=pe(e,t);if(!i)return null;let r=[{file:i.relativePath,line:i.startLine}],o=Kn(e,i,{semantic:n.semantic,semanticEvidence:ge}).map(l=>({file:l.file,line:l.line,enclosingSymbol:l.enclosingSymbol??"(top-level)",enclosingShort:l.enclosingSymbol?A(l.enclosingSymbol):"(top-level)"})),{outgoingCalls:s,incomingCalls:a}=bq(e,i,o,{semantic:n.semantic!==!1});return{symbol:i.symbol,shortName:A(i.symbol),relativePath:i.relativePath,definitionSites:r.filter(l=>!e.isIgnored(l.file)),referenceSites:o,outgoingCalls:s.filter(l=>!e.isIgnored(l.file)).map(l=>({symbol:l.symbol,shortName:A(l.symbol),file:l.file})),incomingCalls:a.filter(l=>!e.isIgnored(l.file)).map(l=>({symbol:l.symbol,shortName:l.symbol===l.file?"(top-level)":A(l.symbol),file:l.file}))}}function fm(e,t,n={}){let i=Wx(e,t,n);return i?{symbol:i.symbol,shortName:i.shortName,relativePath:i.relativePath,definitionSites:i.definitionSites,usageSites:i.referenceSites,producers:i.outgoingCalls,consumers:i.incomingCalls}:null}function bq(e,t,n,i){let r=hr(qs(e,t,{limit:30,semantic:i.semantic,semanticEvidence:ge}).map(a=>({symbol:a.symbol,file:a.file}))),o=hr(Ks(e,t,{limit:30,semantic:i.semantic,semanticEvidence:ge})),s=o.length>0?o:hr(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{outgoingCalls:r,incomingCalls:s}}function Vx(e,t,n={}){let{direction:i="backward",maxDepth:r=3}=n,o=pe(e,t);return o?i==="backward"?Sq(e,o,r,{semantic:n.semantic!==!1}):vq(e,o,{semantic:n.semantic!==!1}):null}function Ll(e,t,n={}){return Vx(e,t,n)}function Sq(e,t,n,i){let r=[],o=new Set([t.symbol]),s=[t];for(let a=1;a<=n&&s.length!==0;a++){let l=[];for(let c of s){let u=qs(e,c,{semantic:i.semantic,semanticEvidence:ge});for(let d of u){if(o.has(d.symbol))continue;o.add(d.symbol),r.push({symbol:d.symbol,shortName:A(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let m=Si(e,d.symbol);m&&!e.isIgnored(m.relativePath)&&l.push(m)}}s=l}return{symbol:t.symbol,shortName:A(t.symbol),direction:"backward",connectedSymbols:r}}function vq(e,t,n){let i=new Set,r=[],o=new U(e);for(let s of Kn(e,t,{semantic:n.semantic,semanticEvidence:ge})){if(r.length>=30)break;let a=s.enclosingSymbol??Ke(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let l=Si(e,a);!l||e.isIgnored(l.relativePath)||i.has(l.symbol)||(i.add(l.symbol),r.push({symbol:l.symbol,shortName:A(l.symbol),file:l.relativePath,relationship:`references target at ${s.file}:${s.line+1}`}))}return r.sort((s,a)=>s.file.localeCompare(a.file)),{symbol:t.symbol,shortName:A(t.symbol),direction:"forward",connectedSymbols:r}}function Jx(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 tR=6,Ml=10,gm=3,hm=8,Cq=.7,Yx=24,pm=200,nR=12,Xx=80,Qx=600;function xq(e,t,n={}){let i=n.impactDepth??3,r=n.sliceDepth??3,o=n.semantic,s=Fq(t)?Iq(e,t):null,a=s?s.primary?.symbol??null:t,l=a!==null,c=l?We("trace",a,()=>_u(e,a,{semantic:o,referenceContext:nR}),P=>({definitions:P.definitions.length,references:P.referencedBy.length})):{definitions:[],referencedBy:[],claimSupport:null},u=l?We("call-graph",a,()=>Eo(e,a,{semantic:o}),P=>({callers:P?.callers.length??0,callees:P?.callees.length??0})):null,d=l?We("complexity",a,()=>dm(e,a,{semantic:o}),P=>({callees:P?.calleeCount??0})):null,m=l?We("dataflow",a,()=>fm(e,a,{semantic:o}),P=>({references:P?.usageSites.length??0,producers:P?.producers.length??0,consumers:P?.consumers.length??0})):null,f=l?We("backward-slice",a,()=>Ll(e,a,{direction:"backward",maxDepth:r,semantic:o}),P=>({maxDepth:r,connectedSymbols:P?.connectedSymbols.length??0})):null,p=l?We("forward-slice",a,()=>Ll(e,a,{direction:"forward",maxDepth:r,semantic:o}),P=>({maxDepth:r,connectedSymbols:P?.connectedSymbols.length??0})):null,g=l?We("affected",a,()=>Od(e,a,{maxDepth:i,scope:n.scope}),P=>({maxDepth:i,affectedSymbols:P.rows.length,coverage:P.coverage.status})):null,h=g?.rows??[],b=g?.coverage??null,v=l?We("reuse-candidates",a,()=>Wo(e,a,{minSimilarity:.4,limit:5,semantic:o,sourceCandidateMode:"target-pruned"}),P=>({candidates:P.length,direct:P.filter(k=>k.actionTier==="direct").length})):[],y=l?pe(e,a)?.symbol??null:null,I=l?We("affected-consumer-reuse",a,()=>wq(c,y,P=>Wo(e,P,{minSimilarity:.4,limit:Ml,semantic:o,sourceCandidateMode:"target-pruned"}),{consumerLimit:tR,perConsumerSearchLimit:Ml,perConsumerCandidateLimit:gm,candidateLimit:hm}),P=>({totalConsumers:P.coverage.totalConsumers,analyzedConsumers:P.coverage.analyzedConsumers,candidates:P.candidates.length})):Pq(),E=We("change-surface",t,()=>$d(e,t,{semantic:o}),P=>({symbols:P?.symbols.length??0,externalConsumers:P?.totalExternalConsumers??0})),S=We("system",t,()=>pd(e,t),P=>({files:P.files.length,symbols:P.symbols.length})),x=S.files.length===1,C=We("deps",t,()=>x?S.dependsOn.map(P=>({relativePath:P,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):wo(e,t),P=>({files:P.length,reusedSystem:x})),L=We("rdeps",t,()=>x?S.dependedOnBy.map(P=>({relativePath:P,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):Lo(e,t),P=>({files:P.length,reusedSystem:x})),w=We("surface",t,()=>gd(e,t),P=>({consumers:P.length})),R={symbol:c.definitions.length>0||c.referencedBy.length>0||u!==null||d!==null||m!==null||f!==null||p!==null||h.length>0,file:E!==null||C.length>0||L.length>0,module:S.files.length>0||S.symbols.length>0||w.length>0},M=[];s&&!s.primary&&s.callableCount>1&&M.push(`File target has ${s.callableCount} callable symbols; use one callable name for compiler-resolved flow.`);let _=[...new Set(c.referencedBy.map(P=>P.relativePath))];_.length>0&&_.every(P=>J(P)==="test")&&M.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."),!R.symbol&&!R.file&&!R.module&&M.push("No symbol, file, or module matched target."),b&&b.status!=="accounted"&&M.push(`Possible-impact coverage is ${b.status}: ${b.reasons.join(" ")}`);let D=E?.file??c.definitions[0]?.relativePath??null;return{target:t,...s?.primary?{primaryCallable:{symbol:s.primary.symbol,shortName:Y(s.primary.symbol),file:s.primary.relativePath}}:{},matched:R,history:We("history",D??t,()=>Tq(e,D,n.gitHead)),trace:Rq(c),callGraph:u,complexity:d,dataflow:m,backwardSlice:f,forwardSlice:p,affected:h,affectedCoverage:b,changeSurface:E,deps:C,rdeps:L,system:S,surface:w,reuseCandidates:v,affectedConsumerReuse:I,sourcePacket:Eq(e,y,c,I,v),warnings:M}}function Rq(e){return{definitions:e.definitions,referencedBy:e.referencedBy.map(t=>({relativePath:t.relativePath,line:t.line,enclosingSymbol:t.enclosingSymbol,enclosingShort:t.enclosingShort}))}}function Iq(e,t){let n=In(e,t);if(n.length!==1)return{primary:null,callableCount:0};let i=W(e,n[0]).filter(s=>s.isFunctionLike),r=i.filter(s=>s.enclosingSymbol===null),o=r.length>0?r:i;return{primary:o.length===1?o[0]:null,callableCount:o.length}}function Eq(e,t,n,i,r){let o=[...t?[{definition:Zx(e,t),role:"target"}]:[],...[...i.candidates.map(d=>d.candidate),...r].map(d=>({definition:Zx(e,d.symbolB),role:"reuse-candidate"}))],s=new Map;for(let d of Jx(o)){if(s.has(d.definition.symbol))continue;let m=d.role==="target"?pm:Xx,f=d.definition.endLine<=d.definition.startLine?Jn(e,d.definition.relativePath,d.definition.startLine,m):null,p=f?.unitType?f.source:Qt(e,d.definition);if(!p)continue;let g=p.split(`
431
431
  `),h=Math.min(g.length,m),b=f?.unitType?f.startLine:d.definition.startLine;s.set(d.definition.symbol,{role:d.role,symbol:d.definition.symbol,shortName:Y(d.definition.symbol),file:d.definition.relativePath,startLine:b,endLine:b+h-1,source:g.slice(0,h).join(`
432
- `),omittedLines:(f?.unitType?f.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}`,f=a.get(m);if(f){f.focusLines=[...new Set([...f.focusLines??[],d.line])].sort((p,g)=>p-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 l=[...[...s.values()].filter(d=>d.role==="target"),...a.values(),...[...s.values()].filter(d=>d.role==="reuse-candidate")],c=[],u=eR;for(let d of l){if(c.length>=Qx||u<=0)break;let m=d.source.split(`
432
+ `),omittedLines:(f?.unitType?f.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}`,f=a.get(m);if(f){f.focusLines=[...new Set([...f.focusLines??[],d.line])].sort((p,g)=>p-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 l=[...[...s.values()].filter(d=>d.role==="target"),...a.values(),...[...s.values()].filter(d=>d.role==="reuse-candidate")],c=[],u=Qx;for(let d of l){if(c.length>=Yx||u<=0)break;let m=d.source.split(`
433
433
  `),f=Math.min(m.length,u);c.push({...d,endLine:d.startLine+f-1,source:m.slice(0,f).join(`
434
- `),omittedLines:d.omittedLines+Math.max(0,m.length-f),...d.focusLines?{focusLines:d.focusLines.filter(p=>p<=d.startLine+f-1)}:{}}),u-=f}return{slices:c,candidateSlices:l.length,omittedSlices:Math.max(0,l.length-c.length),maxSlices:Qx,maxLinesPerSlice:bm,maxTotalLines:eR,targetLineLimit:bm,consumerContextLines:rR,reuseLineLimit:Zx}}function tR(e,t){let n=Si(e,t);return n?W(e,n.relativePath).find(i=>i.symbol===t)??null:null}function _q(e,t,n,i={}){let r=Ml(i.consumerLimit,iR),o=Ml(i.perConsumerSearchLimit,Pl),s=Ml(i.perConsumerCandidateLimit,Sm),a=Ml(i.candidateLimit,vm),l=Bq(e),c=l.slice(0,r),u=new Set(l.map(f=>f.symbol));t&&u.add(t);let d=new Map;for(let f of c){let p=n(f.symbol).slice(0,o),g=0;for(let h of p){let b=Oq(h,f.symbol);if(!b||u.has(b.symbolB))continue;let v=d.get(b.symbolB);if(v?(v.consumers.some(y=>y.symbol===f.symbol)||v.consumers.push(f),b.similarity>v.candidate.similarity&&(v.candidate=b)):d.set(b.symbolB,{candidate:b,consumers:[f]}),g+=1,g>=s)break}}let m=[...d.values()].filter(f=>f.candidate.actionTier==="direct"||f.candidate.similarity>=Tq||f.consumers.length>1).sort($q).slice(0,a);return{candidates:m,coverage:{totalConsumers:l.length,analyzedConsumers:c.length,omittedConsumers:Math.max(0,l.length-c.length),perConsumerSearchLimit:o,perConsumerCandidateLimit:s,candidateLimit:a,returnedCandidates:m.length}}}function Bq(e){let t=new Map;for(let n of e.referencedBy){if(!n.enclosingSymbol)continue;let i=t.get(n.enclosingSymbol);if(i){i.referenceCount+=1;continue}t.set(n.enclosingSymbol,{symbol:n.enclosingSymbol,shortName:Y(n.enclosingSymbol)||n.enclosingShort,file:n.relativePath,referenceCount:1})}return[...t.values()].sort((n,i)=>i.referenceCount-n.referenceCount||n.symbol.localeCompare(i.symbol))}function Oq(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 $q(e,t){let n=nR(t.candidate.actionTier)-nR(e.candidate.actionTier);if(n!==0)return n;let i=t.consumers.length-e.consumers.length;if(i!==0)return i;let r=t.candidate.similarity-e.candidate.similarity;return r!==0?r:e.candidate.symbolB.localeCompare(t.candidate.symbolB)}function nR(e){return e==="direct"?1:0}function Ml(e,t){return typeof e=="number"&&Number.isFinite(e)?Math.max(1,Math.floor(e)):t}function jq(){return{candidates:[],coverage:{totalConsumers:0,analyzedConsumers:0,omittedConsumers:0,perConsumerSearchLimit:Pl,perConsumerCandidateLimit:Sm,candidateLimit:vm,returnedCandidates:0}}}function We(e,t,n,i=()=>({})){let r;return B(`context.${e}`,()=>(r=n(),r),()=>({target:t,...i(r)}))}function Hq(e,t,n){let i={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return i;let r=Xt(e,n?{head:n}:{}),o=We("history.churn",t,()=>r.fileChurn(),l=>({files:l?.size??0}));if(!o)return i;let s=We("history.co-change",t,()=>is(e,t,{limit:5,...n?{head:n}:{}}),l=>({commits:l.commitsAnalyzed,partners:l.findings.length})),a=We("history.suppressions",t,()=>Ll(e).byFile.get(t)??0,l=>({suppressions:l}));return{available:!0,file:t,churn:o.get(t)??{changes:0,fixChanges:0,lastChangedAt:0},coChangePartners:s.findings.map(l=>({file:l.fileA===t?l.fileB:l.fileA,together:l.together,confidence:l.confidence,subjectContext:l.subjectContext})),suppressionsInFile:a}}function Uq(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}var je={dead:{minLoc:3,skipBarrels:!0,deadCodeOnly:!0},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 zq}from"fs";import{isAbsolute as qq,join as Kq}from"path";var Gq=".codebaseiq-baseline.json";function Cm(e){if(e.startsWith("similar:")){let t=e.slice(8).split("|");return t.length!==2?e:`similar:${t.map(A).sort().join("|")}`}if(e.startsWith("duplicate-bodies:")){let t=e.slice(17),n=t.indexOf(":");if(n<0)return e;let i=t.slice(0,n),r=t.slice(n+1).split("|");return r.length<2?e:`duplicate-bodies:${i}:${r.map(A).sort().join("|")}`}return e}function xm(e,t){return t&&qq(t)?t:Kq(e.config.projectRoot,t??Gq)}function oR(e,t,n={}){let i=xm(e,n.path);if(!zq(i))throw new Error(`No baseline found at ${i}. Create one with: codebaseiq health --write-baseline`);let o=(JSON.parse(gi(i,"health baseline")).findings??[]).map(Cm),s=new Set(n.accept?o.filter(n.accept):o),a=new Set(t);return{baselinePath:i,baselineCount:s.size,current:[...t],newFindings:t.filter(l=>!s.has(l)),fixedFindings:[...s].filter(l=>!a.has(l))}}import cs from"path";function ds(e,t){let{scope:n,minDeviation:i=5,limit:r=50}=t??{},o=t?.semantic!==!1,s=t?.includePatternDeviations===!0,l=new U(e).fileDependencyGraph(n),c=Ko(e,{scope:n}),u=Xq([...Wq(e,l,{scope:n,semantic:o}),...Jq(c.forbiddenEdges),...s?Yq(l,i):[]]);return t?.includeArchitecture===!0&&(u.architecture=c),r<=0||u.results.length<=r?u:{...u,results:u.results.slice(0,r),totalResults:u.results.length}}function Wq(e,t,n){let i=eK(e,n.scope),r=[],o=new Set;for(let[a,l]of t){if(us(a))continue;let c=i.get(a)??new Set;for(let u of l)us(u)||c.has(u)||Vq(e,a,u,n)||(r.push({file:a,dep:u}),o.add(a))}o.size>0&&iK(e,i,{paths:[...o]});let s=[];for(let{file:a,dep:l}of r)(i.get(a)??new Set).has(l)||s.push({file:a,kind:"unused-import",description:`Depends on ${l} but references none of its symbols`,dep:l,actionTier:"direct",evidenceReasons:[`dependency edge exists from ${a} to ${l}`,"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 Vq(e,t,n,i){return sK(e,t,n)||aK(e,t,n)||rK(n)||cK(e,t,n)||lK(n)?!0:i.semantic&&oK(e,t,n)}function Jq(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(i=>`${i.fromFile} imports ${i.toFile}`)],recommendation:"Move the dependency behind an allowed boundary, reverse the dependency through an owned interface, or deliberately update the project architecture rule."}]:[]})}function Yq(e,t){let n=[];for(let[i,r]of Qq(e)){let o=r.filter(a=>!us(a));if(o.length<t)continue;let s=Zq(e,o);for(let a of o)for(let l of e.get(a)??[])us(l)||(s.get(l)??0)===1&&cs.dirname(l)!==i&&cs.dirname(l)!==cs.dirname(i)&&n.push({file:a,kind:"pattern-deviation",description:`Only file in ${i}/ that depends on ${l}`,dep:l,actionTier:"signal",evidenceReasons:[`${o.length} sibling file(s) in ${i}/ were compared`,`${a} is the only non-skipped sibling depending on ${l}`],recommendation:"Review sibling ownership before changing this import; unique dependency shape can be intentional specialization."})}return n}function Xq(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 Qq(e){let t=new Map;for(let n of e.keys()){let i=cs.dirname(n),r=t.get(i);r||(r=[],t.set(i,r)),r.push(n)}return t}function Zq(e,t){let n=new Map;for(let i of t)for(let r of e.get(i)??[])us(r)||n.set(r,(n.get(r)??0)+1);return n}function eK(e,t){let n=new Map;return tK(e,n,t),n}function tK(e,t,n){for(let i of nK(e,n))sR(e,t,i.from_file,i.to_file)}function nK(e,t){let n=t?"AND d1.relative_path LIKE ?":"",i=t?[`%${t}%`]:[];return e.all(`SELECT DISTINCT d1.relative_path AS from_file, d2.relative_path AS to_file
434
+ `),omittedLines:d.omittedLines+Math.max(0,m.length-f),...d.focusLines?{focusLines:d.focusLines.filter(p=>p<=d.startLine+f-1)}:{}}),u-=f}return{slices:c,candidateSlices:l.length,omittedSlices:Math.max(0,l.length-c.length),maxSlices:Yx,maxLinesPerSlice:pm,maxTotalLines:Qx,targetLineLimit:pm,consumerContextLines:nR,reuseLineLimit:Xx}}function Zx(e,t){let n=Si(e,t);return n?W(e,n.relativePath).find(i=>i.symbol===t)??null:null}function wq(e,t,n,i={}){let r=Dl(i.consumerLimit,tR),o=Dl(i.perConsumerSearchLimit,Ml),s=Dl(i.perConsumerCandidateLimit,gm),a=Dl(i.candidateLimit,hm),l=Lq(e),c=l.slice(0,r),u=new Set(l.map(f=>f.symbol));t&&u.add(t);let d=new Map;for(let f of c){let p=n(f.symbol).slice(0,o),g=0;for(let h of p){let b=Dq(h,f.symbol);if(!b||u.has(b.symbolB))continue;let v=d.get(b.symbolB);if(v?(v.consumers.some(y=>y.symbol===f.symbol)||v.consumers.push(f),b.similarity>v.candidate.similarity&&(v.candidate=b)):d.set(b.symbolB,{candidate:b,consumers:[f]}),g+=1,g>=s)break}}let m=[...d.values()].filter(f=>f.candidate.actionTier==="direct"||f.candidate.similarity>=Cq||f.consumers.length>1).sort(Mq).slice(0,a);return{candidates:m,coverage:{totalConsumers:l.length,analyzedConsumers:c.length,omittedConsumers:Math.max(0,l.length-c.length),perConsumerSearchLimit:o,perConsumerCandidateLimit:s,candidateLimit:a,returnedCandidates:m.length}}}function Lq(e){let t=new Map;for(let n of e.referencedBy){if(!n.enclosingSymbol)continue;let i=t.get(n.enclosingSymbol);if(i){i.referenceCount+=1;continue}t.set(n.enclosingSymbol,{symbol:n.enclosingSymbol,shortName:Y(n.enclosingSymbol)||n.enclosingShort,file:n.relativePath,referenceCount:1})}return[...t.values()].sort((n,i)=>i.referenceCount-n.referenceCount||n.symbol.localeCompare(i.symbol))}function Dq(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 Mq(e,t){let n=eR(t.candidate.actionTier)-eR(e.candidate.actionTier);if(n!==0)return n;let i=t.consumers.length-e.consumers.length;if(i!==0)return i;let r=t.candidate.similarity-e.candidate.similarity;return r!==0?r:e.candidate.symbolB.localeCompare(t.candidate.symbolB)}function eR(e){return e==="direct"?1:0}function Dl(e,t){return typeof e=="number"&&Number.isFinite(e)?Math.max(1,Math.floor(e)):t}function Pq(){return{candidates:[],coverage:{totalConsumers:0,analyzedConsumers:0,omittedConsumers:0,perConsumerSearchLimit:Ml,perConsumerCandidateLimit:gm,candidateLimit:hm,returnedCandidates:0}}}function We(e,t,n,i=()=>({})){let r;return B(`context.${e}`,()=>(r=n(),r),()=>({target:t,...i(r)}))}function Tq(e,t,n){let i={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return i;let r=Xt(e,n?{head:n}:{}),o=We("history.churn",t,()=>r.fileChurn(),l=>({files:l?.size??0}));if(!o)return i;let s=We("history.co-change",t,()=>ts(e,t,{limit:5,...n?{head:n}:{}}),l=>({commits:l.commitsAnalyzed,partners:l.findings.length})),a=We("history.suppressions",t,()=>wl(e).byFile.get(t)??0,l=>({suppressions:l}));return{available:!0,file:t,churn:o.get(t)??{changes:0,fixChanges:0,lastChangedAt:0},coChangePartners:s.findings.map(l=>({file:l.fileA===t?l.fileB:l.fileA,together:l.together,confidence:l.confidence,subjectContext:l.subjectContext})),suppressionsInFile:a}}function Fq(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}var je={dead:{minLoc:3,skipBarrels:!0,deadCodeOnly:!0},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 kq}from"fs";import{isAbsolute as Nq,join as Aq}from"path";var _q=".codebaseiq-baseline.json";function ym(e){if(e.startsWith("similar:")){let t=e.slice(8).split("|");return t.length!==2?e:`similar:${t.map(A).sort().join("|")}`}if(e.startsWith("duplicate-bodies:")){let t=e.slice(17),n=t.indexOf(":");if(n<0)return e;let i=t.slice(0,n),r=t.slice(n+1).split("|");return r.length<2?e:`duplicate-bodies:${i}:${r.map(A).sort().join("|")}`}return e}function bm(e,t){return t&&Nq(t)?t:Aq(e.config.projectRoot,t??_q)}function iR(e,t,n={}){let i=bm(e,n.path);if(!kq(i))throw new Error(`No baseline found at ${i}. Create one with: codebaseiq health --write-baseline`);let o=(JSON.parse(gi(i,"health baseline")).findings??[]).map(ym),s=new Set(n.accept?o.filter(n.accept):o),a=new Set(t);return{baselinePath:i,baselineCount:s.size,current:[...t],newFindings:t.filter(l=>!s.has(l)),fixedFindings:[...s].filter(l=>!a.has(l))}}import as from"path";function cs(e,t){let{scope:n,minDeviation:i=5,limit:r=50}=t??{},o=t?.semantic!==!1,s=t?.includePatternDeviations===!0,l=new U(e).fileDependencyGraph(n),c=zo(e,{scope:n}),u=Hq([...Bq(e,l,{scope:n,semantic:o}),...$q(c.forbiddenEdges),...s?jq(l,i):[]]);return t?.includeArchitecture===!0&&(u.architecture=c),r<=0||u.results.length<=r?u:{...u,results:u.results.slice(0,r),totalResults:u.results.length}}function Bq(e,t,n){let i=qq(e,n.scope),r=[],o=new Set;for(let[a,l]of t){if(ls(a))continue;let c=i.get(a)??new Set;for(let u of l)ls(u)||c.has(u)||Oq(e,a,u,n)||(r.push({file:a,dep:u}),o.add(a))}o.size>0&&Wq(e,i,{paths:[...o]});let s=[];for(let{file:a,dep:l}of r)(i.get(a)??new Set).has(l)||s.push({file:a,kind:"unused-import",description:`Depends on ${l} but references none of its symbols`,dep:l,actionTier:"direct",evidenceReasons:[`dependency edge exists from ${a} to ${l}`,"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 Oq(e,t,n,i){return Yq(e,t,n)||Xq(e,t,n)||Vq(n)||Zq(e,t,n)||Qq(n)?!0:i.semantic&&Jq(e,t,n)}function $q(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(i=>`${i.fromFile} imports ${i.toFile}`)],recommendation:"Move the dependency behind an allowed boundary, reverse the dependency through an owned interface, or deliberately update the project architecture rule."}]:[]})}function jq(e,t){let n=[];for(let[i,r]of Uq(e)){let o=r.filter(a=>!ls(a));if(o.length<t)continue;let s=zq(e,o);for(let a of o)for(let l of e.get(a)??[])ls(l)||(s.get(l)??0)===1&&as.dirname(l)!==i&&as.dirname(l)!==as.dirname(i)&&n.push({file:a,kind:"pattern-deviation",description:`Only file in ${i}/ that depends on ${l}`,dep:l,actionTier:"signal",evidenceReasons:[`${o.length} sibling file(s) in ${i}/ were compared`,`${a} is the only non-skipped sibling depending on ${l}`],recommendation:"Review sibling ownership before changing this import; unique dependency shape can be intentional specialization."})}return n}function Hq(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 Uq(e){let t=new Map;for(let n of e.keys()){let i=as.dirname(n),r=t.get(i);r||(r=[],t.set(i,r)),r.push(n)}return t}function zq(e,t){let n=new Map;for(let i of t)for(let r of e.get(i)??[])ls(r)||n.set(r,(n.get(r)??0)+1);return n}function qq(e,t){let n=new Map;return Kq(e,n,t),n}function Kq(e,t,n){for(let i of Gq(e,n))rR(e,t,i.from_file,i.to_file)}function Gq(e,t){let n=t?"AND d1.relative_path LIKE ?":"",i=t?[`%${t}%`]:[];return e.all(`SELECT DISTINCT d1.relative_path AS from_file, d2.relative_path AS to_file
435
435
  FROM mentions m
436
436
  JOIN chunks c ON m.chunk_id = c.id
437
437
  JOIN documents d1 ON c.document_id = d1.id
@@ -447,16 +447,16 @@ describe.skipIf(inputs.length === 0)('twin-ab: ${e.shortName} vs ${t.shortName}'
447
447
  WHERE d1.id != d2.id
448
448
  AND m.role != 1
449
449
  ${e.pathExclusionsFor("d1","d2")}
450
- ${n}`,...i)}function iK(e,t,n={}){new U(e).scanSourceReferences({paths:n.paths??me(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},r=>{r.target.relativePath!==r.sourceFile&&(e.isIgnored(r.target.relativePath)||sR(e,t,r.sourceFile,r.target.relativePath))})}function sR(e,t,n,i){if(e.isIgnored(n)||e.isIgnored(i))return;let r=t.get(n);r||(r=new Set,t.set(n,r)),r.add(i)}function rK(e){return e.includes("types")||e.endsWith(".d.ts")}function oK(e,t,n){let i=bo(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.some(r=>r.isUsed)}function sK(e,t,n){let i=Ce(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.some(r=>r.used)}function aK(e,t,n){let i=Ce(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.every(r=>r.isTypeOnly===!0)}function lK(e){return e.endsWith(".vue")}function cK(e,t,n){let i=Ce(e,t).filter(r=>r.sourcePath===n);return i.length===0?!1:i.every(r=>r.kind==="side-effect"||r.kind==="namespace"&&r.usedMembers.length===0&&!r.used)}function us(e){let t=J(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||uK(cs.basename(e)))}function uK(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 ms(e,t){let{scope:n,minLoc:i=3,maxLoc:r=80,limit:o=30,includeLowConfidence:s=!1,scanLimit:a}=t??{},l=t?.semantic!==!1,c=new U(e),u=c.scopedDefinitions(n),d=xK(c,n),m={high:0,medium:1,low:2};return Ht({candidates:()=>dK(e,c,u,{minLoc:i,maxLoc:r}),orderCandidates:(f,p)=>de(p)-de(f)||f.relativePath.localeCompare(p.relativePath),scanLimit:a,profile:{name:"stale-abstractions"},prepare:f=>{let p=fK(f),g=mK(e,c,f,p,{semantic:l}),h=f.filter(b=>{if(g.incompleteSymbolIds.has(b.symbolId)||g.unavailableSymbolIds.has(b.symbolId)||c.hasSuppressionComment(b))return!1;let v=Tl(e,b,g.consumerFileMap,p);return v.realConsumers.length<=1&&!v.transitivelyReachable&&lR(b,v.realConsumers.length,d)});return{...g,singletonBackedClassIds:hK(e,c,u,h,{semantic:l}),candidateIndex:p}},evaluate:(f,p)=>{if(p.incompleteSymbolIds.has(f.symbolId)||p.unavailableSymbolIds.has(f.symbolId)||c.hasSuppressionComment(f)||p.singletonBackedClassIds.has(f.symbolId))return null;let g=Tl(e,f,p.consumerFileMap,p.candidateIndex);if(g.transitivelyReachable||g.realConsumers.length>1||g.realConsumers.length===0&&g.barrelConsumers>0||!lR(g.definition,g.realConsumers.length,d))return null;let h=pK(e,g);return!s&&h.confidence==="low"?null:h},orderResults:(f,p)=>m[f.confidence]-m[p.confidence]||p.loc-f.loc||f.file.localeCompare(p.file)||f.startLine-p.startLine,limit:o})}function dK(e,t,n,i){return n.filter(r=>r.isTypeLike&&de(r)>=i.minLoc).filter(r=>de(r)<=i.maxLoc).filter(r=>!e.isIgnored(r.relativePath)).filter(r=>!r.relativePath.endsWith(".d.ts")).filter(r=>J(r.relativePath)!=="test").filter(r=>!qe(e,r.symbol,r.relativePath)).filter(r=>!RK(r.symbol))}function aR(e,t,n,i){return ui(hn(e,t).forDefinitions(n,{semantic:i.semantic,sourceFallback:i.sourceFallback}))}function mK(e,t,n,i,r){let o=aR(e,t,n,{semantic:!1,sourceFallback:!1}),s=n.filter(m=>{let f=Tl(e,m,o,i);return f.realConsumers.length<=1&&!(f.realConsumers.length>0&&Rm(m.relativePath))}),a=hn(e,t).forDefinitions(s,{semantic:r.semantic,sourceFallback:!1}),l=new Set([...a.values()].filter(m=>m.semanticIncomplete).map(m=>m.definition.symbolId)),c=new Set([...a.values()].filter(m=>m.semanticUnavailable).map(m=>m.definition.symbolId)),u=r.semantic&&s.length>0?Mi(o,ui(a)):o,d=s.filter(m=>Tl(e,m,u,i).realConsumers.length<=1);return{consumerFileMap:Mi(u,aR(e,t,d,{semantic:!1,sourceFallback:!0})),incompleteSymbolIds:l,unavailableSymbolIds:c}}function fK(e){let t=new Map;for(let n of e){let i=t.get(n.relativePath);i||(i=new Map,t.set(n.relativePath,i));let r=Y(n.symbol);r&&i.set(r,n)}return t}function Tl(e,t,n,i){let o=[...n.get(t.symbolId)??new Set].filter(u=>u!==t.relativePath&&!e.isIgnored(u)),{realConsumers:s,barrelConsumers:a,importOnlyConsumers:l}=fl(e,t,o),c=IK(e,t,n,i);return{definition:t,realConsumers:s,barrelConsumers:a+l,transitivelyReachable:c}}function pK(e,t){let n=uR(e,t.definition.relativePath,t.definition.startLine),i=Rm(t.definition.relativePath)?!0:EK(e,t.definition),{confidence:r,reason:o}=wK(t.realConsumers.length,n,i),s=gK(t.realConsumers.length,n,i);return{symbol:t.definition.symbol,shortName:A(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:de(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:i,confidence:r,reason:o,actionTier:s.actionTier,stalenessKind:s.stalenessKind,recommendation:s.recommendation}}function gK(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 hK(e,t,n,i,r){let o=bK(e,yK(n),i),s=o.map(u=>u.singleton);if(o.length===0)return new Set;let a=hn(e,t).forDefinitions(s,{semantic:r.semantic,sourceFallback:!0}),l=ui(a),c=new Set;for(let{singleton:u,classId:d}of o){let m=a.get(u.symbolId);(m?.semanticIncomplete||m?.semanticUnavailable||vK(e,u,l))&&c.add(d)}return c}function yK(e){let t=new Map;for(let n of e){let i=Y(n.symbol);i&&t.set(cR(n.relativePath,i),n)}return t}function bK(e,t,n){let i=[];for(let r of n){let o=SK(e,t,r);o&&i.push({singleton:o,classId:r.symbolId})}return i}function SK(e,t,n){if(uR(e,n.relativePath,n.startLine)!=="class")return null;let i=Y(n.symbol);if(!i)return null;let r=CK(e,n.relativePath,i);return r?t.get(cR(n.relativePath,r))??null:null}function vK(e,t,n){let i=Y(t.symbol),r=n.get(t.symbolId);return!i||!r?!1:[...r].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!_d(e,o,i))}function cR(e,t){return`${e}\0${t}`}function CK(e,t,n){let i=se(e,t);if(!i)return null;let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\bexport\\s+const\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*new\\s+${r}\\s*\\(`);return i.match(o)?.[1]??null}function xK(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function RK(e){let t=zn(e);if("kind"in t)return!1;let n=t.descriptors;if(n.length<2)return!1;let i=n[n.length-1],r=n[n.length-2];return i?.suffix==="type"&&r?.suffix==="type"}function Rm(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 lR(e,t,n){return!(Rm(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function IK(e,t,n,i){let r=Lf(e,t.relativePath),o=Y(t.symbol);if(!o)return!1;let s=i.get(t.relativePath);if(!s)return!1;let a=[...r.get(o)??[]],l=new Set;for(;a.length>0;){let c=a.pop();if(l.has(c))continue;l.add(c);let u=s.get(c);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 r.get(c)??[])a.push(m)}return!1}function uR(e,t,n){let i=se(e,t);if(!i)return"other";let r=i.split(`
451
- `),o=Math.max(0,n-2),s=Math.min(r.length-1,n+2);for(let a=o;a<=s;a++){let c=(r[a]??"").replace(/^\s*\/\/.*$/g,"");if(/\b(?:export\s+)?(?:abstract\s+)?class\s+\w/.test(c))return"class";if(/\b(?:export\s+)?interface\s+\w/.test(c))return"interface";if(/\b(?:export\s+)?type\s+\w/.test(c))return"type";if(/\b(?:export\s+)?(?:const\s+)?enum\s+\w/.test(c))return"enum"}return"other"}function EK(e,t){let n=se(e,t.relativePath);if(!n)return!1;let i=Y(t.symbol);if(!i)return!1;let r=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${r}\\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 wK(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 Nr,extname as Fl}from"path";function fs(e,t){let{scope:n,maxLoc:i=15,limit:r=30,scanLimit:o}=t??{},s=new U(e),a=FK(s.fileDependencyGraph(n));return Ht({candidates:()=>MK(e,s,n,i),orderCandidates:_a,scanLimit:o,profile:{name:"wrapper-candidates"},prepare:l=>({...LK(e,s,l,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(l,c)=>DK(e,s,l,c),orderResults:(l,c)=>c.callerFanIn-l.callerFanIn||c.loc-l.loc,limit:r})}function LK(e,t,n,i){let r=hn(e,t),o=ui(r.forDefinitions(n,{semantic:!1,sourceFallback:!1})),s=[];i.semantic&&B("wrapper.semantic-candidates",()=>{s=n.filter(h=>Im(e,t,h,o).length<=1)},()=>({symbols:n.length,semanticCandidates:s.length}));let a=r.forDefinitions(s,{semantic:!0,sourceFallback:!1}),l=ui(a),c=new Set([...a.values()].filter(h=>h.semanticIncomplete).map(h=>h.definition.symbolId)),u=new Set([...a.values()].filter(h=>h.semanticUnavailable).map(h=>h.definition.symbolId)),d=l.size===0?o:Mi(o,l),m=new Map(n.map(h=>[h.symbolId,h])),f=new Map;for(let h of n){let b=Im(e,t,h,d);if(b.length>1||(f.set(h.symbolId,h),b.length!==1))continue;let v=b[0],y=dR(e,h.symbolId,v);if(!y)continue;let I=mR(t,e,v,h.symbol,y);I?.isFunctionLike&&m.has(I.symbolId)&&f.set(I.symbolId,m.get(I.symbolId))}let p=[...f.values()];return{callerFileMap:p.length===0?d:Mi(d,ui(r.forDefinitions(p,{semantic:!1,sourceFallback:!0}))),incompleteSymbolIds:c,unavailableSymbolIds:u}}function DK(e,t,n,i){if(i.incompleteSymbolIds.has(n.symbolId)||i.unavailableSymbolIds.has(n.symbolId))return null;let r=Im(e,t,n,i.callerFileMap);if(r.length!==1)return null;let o=r[0],s=dR(e,n.symbolId,o);if(!s)return null;let a=mR(t,e,o,n.symbol,s);if(a&&Zi(a.symbol))return null;let{fanIn:l,source:c}=PK(i.callerFileMap,i.reverseFanIn,o,a);if(c==="function"?l<=3:l<=5)return null;let u=NK(e,n,o,a);return{symbol:n.symbol,shortName:A(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:de(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?A(a.symbol):Nr(o),callerFanIn:l,actionTier:u.length>0?"signal":"direct",boundaryEvidence:u}}function MK(e,t,n,i){return t.productionCallableDefinitions({scope:n,minLoc:2,maxLoc:i,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0}).filter(r=>!Ts(e,r))}function Im(e,t,n,i){let r=Nr(n.relativePath,Fl(n.relativePath)),o=[...i.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>Nr(s,Fl(s))!==r).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return fl(e,n,o).realConsumers}function dR(e,t,n){return e.get(`SELECT c.start_line, c.end_line
450
+ ${n}`,...i)}function Wq(e,t,n={}){new U(e).scanSourceReferences({paths:n.paths??me(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},r=>{r.target.relativePath!==r.sourceFile&&(e.isIgnored(r.target.relativePath)||rR(e,t,r.sourceFile,r.target.relativePath))})}function rR(e,t,n,i){if(e.isIgnored(n)||e.isIgnored(i))return;let r=t.get(n);r||(r=new Set,t.set(n,r)),r.add(i)}function Vq(e){return e.includes("types")||e.endsWith(".d.ts")}function Jq(e,t,n){let i=ho(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.some(r=>r.isUsed)}function Yq(e,t,n){let i=Ce(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.some(r=>r.used)}function Xq(e,t,n){let i=Ce(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.every(r=>r.isTypeOnly===!0)}function Qq(e){return e.endsWith(".vue")}function Zq(e,t,n){let i=Ce(e,t).filter(r=>r.sourcePath===n);return i.length===0?!1:i.every(r=>r.kind==="side-effect"||r.kind==="namespace"&&r.usedMembers.length===0&&!r.used)}function ls(e){let t=J(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||eK(as.basename(e)))}function eK(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 us(e,t){let{scope:n,minLoc:i=3,maxLoc:r=80,limit:o=30,includeLowConfidence:s=!1,scanLimit:a}=t??{},l=t?.semantic!==!1,c=new U(e),u=c.scopedDefinitions(n),d=mK(c,n),m={high:0,medium:1,low:2};return Ht({candidates:()=>tK(e,c,u,{minLoc:i,maxLoc:r}),orderCandidates:(f,p)=>de(p)-de(f)||f.relativePath.localeCompare(p.relativePath),scanLimit:a,profile:{name:"stale-abstractions"},prepare:f=>{let p=iK(f),g=nK(e,c,f,p,{semantic:l}),h=f.filter(b=>{if(g.incompleteSymbolIds.has(b.symbolId)||g.unavailableSymbolIds.has(b.symbolId)||c.hasSuppressionComment(b))return!1;let v=Pl(e,b,g.consumerFileMap,p);return v.realConsumers.length<=1&&!v.transitivelyReachable&&sR(b,v.realConsumers.length,d)});return{...g,singletonBackedClassIds:sK(e,c,u,h,{semantic:l}),candidateIndex:p}},evaluate:(f,p)=>{if(p.incompleteSymbolIds.has(f.symbolId)||p.unavailableSymbolIds.has(f.symbolId)||c.hasSuppressionComment(f)||p.singletonBackedClassIds.has(f.symbolId))return null;let g=Pl(e,f,p.consumerFileMap,p.candidateIndex);if(g.transitivelyReachable||g.realConsumers.length>1||g.realConsumers.length===0&&g.barrelConsumers>0||!sR(g.definition,g.realConsumers.length,d))return null;let h=rK(e,g);return!s&&h.confidence==="low"?null:h},orderResults:(f,p)=>m[f.confidence]-m[p.confidence]||p.loc-f.loc||f.file.localeCompare(p.file)||f.startLine-p.startLine,limit:o})}function tK(e,t,n,i){return n.filter(r=>r.isTypeLike&&de(r)>=i.minLoc).filter(r=>de(r)<=i.maxLoc).filter(r=>!e.isIgnored(r.relativePath)).filter(r=>!r.relativePath.endsWith(".d.ts")).filter(r=>J(r.relativePath)!=="test").filter(r=>!qe(e,r.symbol,r.relativePath)).filter(r=>!fK(r.symbol))}function oR(e,t,n,i){return ui(hn(e,t).forDefinitions(n,{semantic:i.semantic,sourceFallback:i.sourceFallback}))}function nK(e,t,n,i,r){let o=oR(e,t,n,{semantic:!1,sourceFallback:!1}),s=n.filter(m=>{let f=Pl(e,m,o,i);return f.realConsumers.length<=1&&!(f.realConsumers.length>0&&Sm(m.relativePath))}),a=hn(e,t).forDefinitions(s,{semantic:r.semantic,sourceFallback:!1}),l=new Set([...a.values()].filter(m=>m.semanticIncomplete).map(m=>m.definition.symbolId)),c=new Set([...a.values()].filter(m=>m.semanticUnavailable).map(m=>m.definition.symbolId)),u=r.semantic&&s.length>0?Mi(o,ui(a)):o,d=s.filter(m=>Pl(e,m,u,i).realConsumers.length<=1);return{consumerFileMap:Mi(u,oR(e,t,d,{semantic:!1,sourceFallback:!0})),incompleteSymbolIds:l,unavailableSymbolIds:c}}function iK(e){let t=new Map;for(let n of e){let i=t.get(n.relativePath);i||(i=new Map,t.set(n.relativePath,i));let r=Y(n.symbol);r&&i.set(r,n)}return t}function Pl(e,t,n,i){let o=[...n.get(t.symbolId)??new Set].filter(u=>u!==t.relativePath&&!e.isIgnored(u)),{realConsumers:s,barrelConsumers:a,importOnlyConsumers:l}=ml(e,t,o),c=pK(e,t,n,i);return{definition:t,realConsumers:s,barrelConsumers:a+l,transitivelyReachable:c}}function rK(e,t){let n=lR(e,t.definition.relativePath,t.definition.startLine),i=Sm(t.definition.relativePath)?!0:gK(e,t.definition),{confidence:r,reason:o}=hK(t.realConsumers.length,n,i),s=oK(t.realConsumers.length,n,i);return{symbol:t.definition.symbol,shortName:A(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:de(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:i,confidence:r,reason:o,actionTier:s.actionTier,stalenessKind:s.stalenessKind,recommendation:s.recommendation}}function oK(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 sK(e,t,n,i,r){let o=lK(e,aK(n),i),s=o.map(u=>u.singleton);if(o.length===0)return new Set;let a=hn(e,t).forDefinitions(s,{semantic:r.semantic,sourceFallback:!0}),l=ui(a),c=new Set;for(let{singleton:u,classId:d}of o){let m=a.get(u.symbolId);(m?.semanticIncomplete||m?.semanticUnavailable||uK(e,u,l))&&c.add(d)}return c}function aK(e){let t=new Map;for(let n of e){let i=Y(n.symbol);i&&t.set(aR(n.relativePath,i),n)}return t}function lK(e,t,n){let i=[];for(let r of n){let o=cK(e,t,r);o&&i.push({singleton:o,classId:r.symbolId})}return i}function cK(e,t,n){if(lR(e,n.relativePath,n.startLine)!=="class")return null;let i=Y(n.symbol);if(!i)return null;let r=dK(e,n.relativePath,i);return r?t.get(aR(n.relativePath,r))??null:null}function uK(e,t,n){let i=Y(t.symbol),r=n.get(t.symbolId);return!i||!r?!1:[...r].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!Fd(e,o,i))}function aR(e,t){return`${e}\0${t}`}function dK(e,t,n){let i=se(e,t);if(!i)return null;let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\bexport\\s+const\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*new\\s+${r}\\s*\\(`);return i.match(o)?.[1]??null}function mK(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function fK(e){let t=zn(e);if("kind"in t)return!1;let n=t.descriptors;if(n.length<2)return!1;let i=n[n.length-1],r=n[n.length-2];return i?.suffix==="type"&&r?.suffix==="type"}function Sm(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 sR(e,t,n){return!(Sm(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function pK(e,t,n,i){let r=Rf(e,t.relativePath),o=Y(t.symbol);if(!o)return!1;let s=i.get(t.relativePath);if(!s)return!1;let a=[...r.get(o)??[]],l=new Set;for(;a.length>0;){let c=a.pop();if(l.has(c))continue;l.add(c);let u=s.get(c);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 r.get(c)??[])a.push(m)}return!1}function lR(e,t,n){let i=se(e,t);if(!i)return"other";let r=i.split(`
451
+ `),o=Math.max(0,n-2),s=Math.min(r.length-1,n+2);for(let a=o;a<=s;a++){let c=(r[a]??"").replace(/^\s*\/\/.*$/g,"");if(/\b(?:export\s+)?(?:abstract\s+)?class\s+\w/.test(c))return"class";if(/\b(?:export\s+)?interface\s+\w/.test(c))return"interface";if(/\b(?:export\s+)?type\s+\w/.test(c))return"type";if(/\b(?:export\s+)?(?:const\s+)?enum\s+\w/.test(c))return"enum"}return"other"}function gK(e,t){let n=se(e,t.relativePath);if(!n)return!1;let i=Y(t.symbol);if(!i)return!1;let r=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${r}\\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 hK(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 Fr,extname as Tl}from"path";function ds(e,t){let{scope:n,maxLoc:i=15,limit:r=30,scanLimit:o}=t??{},s=new U(e),a=xK(s.fileDependencyGraph(n));return Ht({candidates:()=>SK(e,s,n,i),orderCandidates:Aa,scanLimit:o,profile:{name:"wrapper-candidates"},prepare:l=>({...yK(e,s,l,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(l,c)=>bK(e,s,l,c),orderResults:(l,c)=>c.callerFanIn-l.callerFanIn||c.loc-l.loc,limit:r})}function yK(e,t,n,i){let r=hn(e,t),o=ui(r.forDefinitions(n,{semantic:!1,sourceFallback:!1})),s=[];i.semantic&&B("wrapper.semantic-candidates",()=>{s=n.filter(h=>vm(e,t,h,o).length<=1)},()=>({symbols:n.length,semanticCandidates:s.length}));let a=r.forDefinitions(s,{semantic:!0,sourceFallback:!1}),l=ui(a),c=new Set([...a.values()].filter(h=>h.semanticIncomplete).map(h=>h.definition.symbolId)),u=new Set([...a.values()].filter(h=>h.semanticUnavailable).map(h=>h.definition.symbolId)),d=l.size===0?o:Mi(o,l),m=new Map(n.map(h=>[h.symbolId,h])),f=new Map;for(let h of n){let b=vm(e,t,h,d);if(b.length>1||(f.set(h.symbolId,h),b.length!==1))continue;let v=b[0],y=cR(e,h.symbolId,v);if(!y)continue;let I=uR(t,e,v,h.symbol,y);I?.isFunctionLike&&m.has(I.symbolId)&&f.set(I.symbolId,m.get(I.symbolId))}let p=[...f.values()];return{callerFileMap:p.length===0?d:Mi(d,ui(r.forDefinitions(p,{semantic:!1,sourceFallback:!0}))),incompleteSymbolIds:c,unavailableSymbolIds:u}}function bK(e,t,n,i){if(i.incompleteSymbolIds.has(n.symbolId)||i.unavailableSymbolIds.has(n.symbolId))return null;let r=vm(e,t,n,i.callerFileMap);if(r.length!==1)return null;let o=r[0],s=cR(e,n.symbolId,o);if(!s)return null;let a=uR(t,e,o,n.symbol,s);if(a&&Xi(a.symbol))return null;let{fanIn:l,source:c}=vK(i.callerFileMap,i.reverseFanIn,o,a);if(c==="function"?l<=3:l<=5)return null;let u=IK(e,n,o,a);return{symbol:n.symbol,shortName:A(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:de(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?A(a.symbol):Fr(o),callerFanIn:l,actionTier:u.length>0?"signal":"direct",boundaryEvidence:u}}function SK(e,t,n,i){return t.productionCallableDefinitions({scope:n,minLoc:2,maxLoc:i,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0}).filter(r=>!Ms(e,r))}function vm(e,t,n,i){let r=Fr(n.relativePath,Tl(n.relativePath)),o=[...i.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>Fr(s,Tl(s))!==r).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return ml(e,n,o).realConsumers}function cR(e,t,n){return e.get(`SELECT c.start_line, c.end_line
453
453
  FROM mentions m
454
454
  JOIN chunks c ON m.chunk_id = c.id
455
455
  JOIN documents d ON c.document_id = d.id
456
456
  WHERE m.symbol_id = ? AND m.role != 1 AND d.relative_path = ?
457
- LIMIT 1`,t,n)}function mR(e,t,n,i,r){let o=e.definitionsForFile(n),s=TK(t,n,i,r.start_line,r.end_line);return Ke(o,s)}function PK(e,t,n,i){if(i?.isFunctionLike){let r=[...e.get(i.symbolId)??[]].filter(o=>o!==i.relativePath);if(r.length>0)return{fanIn:r.length,source:"function"}}return{fanIn:kK(t,n),source:"file"}}function TK(e,t,n,i,r){let o=Y(n);if(!o)return i;let s=nr(e,t).get(o);if(!s||s.length===0)return i;for(let a of s)if(a>=i&&a<=r)return a;return i}function FK(e){let t=new Map;for(let[n,i]of e){t.has(n)||t.set(n,t.get(n)??0);for(let r of i)t.set(r,(t.get(r)??0)+1)}return t}function kK(e,t){let n=e.get(t)??0;if(n>0)return n;let i=Nr(t,Fl(t)),r=0;for(let[o,s]of e)o!==t&&Nr(o,Fl(o))===i&&s>r&&(r=s);return r}function NK(e,t,n,i){return Il(e,t.relativePath,t.startLine,"wrapper","explicit ignore-wrapper comment",[{label:"wrapper name",value:A(t.symbol)},{label:"caller name",value:i?.symbol?A(i.symbol):Nr(n)},{label:"wrapper path",value:t.relativePath},{label:"caller path",value:n}])}var AK=25e3,_K=2500,BK=2500;function OK(e){let t=Li(e);return t.symbols>=AK||t.documents>=_K?BK:void 0}function Em(e,t={}){let{scope:n}=t,i=OK(e),r=[],o=ji(e,{scope:n,...je.dead,scanLimit:i});for(let s of o.symbols)Qe(e,s.relativePath)||qe(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&r.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of Go(e,{scope:n,...je.isolated,scanLimit:i}))Qe(e,s.relativePath)||qe(e,s.symbol,s.relativePath)||r.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of qo(e,{scope:n}))s.kind==="real"&&r.push(`cycle:${$K(s.path)}`);for(let s of Yo(e,{scope:n,...je.similar,scanLimit:i}))r.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of os(e,{scope:n,...je.duplicateBodies,scanLimit:i}))r.push(`duplicate-bodies:${s.hash}:${s.functions.map(a=>a.symbol).sort().join("|")}`);for(let s of ts(e,{scope:n,...je.extract,scanLimit:i}))r.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of fs(e,{scope:n,...je.wrappers,scanLimit:i}))r.push(`wrapper:${s.file}:${s.shortName}`);for(let s of ss(e,{scope:n,...je.passthroughs,scanLimit:i}))r.push(`passthrough:${s.file}:${s.shortName}`);for(let s of ms(e,{scope:n,...je.stale,scanLimit:i}))r.push(`stale:${s.file}:${s.shortName}`);for(let s of ds(e,{scope:n,...je.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY}).results)s.kind!=="architecture-violation"&&r.push(`drift:${s.kind}:${s.file}:${s.dep}`);return r.push(...Ed(Ko(e,{scope:n}))),[...new Set(r.map(Cm))].sort()}function $K(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 jK(e,t={}){let n=Em(e,{scope:t.scope}),i=xm(e,t.path);return af(i,{version:1,findings:n},{spacing:2,trailingNewline:!0}),{path:i,findingCount:n.length}}function HK(e,t={}){return oR(e,Em(e,{scope:t.scope}),{path:t.path})}function UK(e,t={}){let{scope:n,limit:i=30,scanLimit:r}=t,o=new U(e);return Ht({candidates:()=>o.productionCallableDefinitions({scope:n,files:t.files,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}),filterCandidate:s=>zK(s.relativePath),scanLimit:r,profile:{name:"unused-params"},evaluate:s=>{let a=te(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 l=nr(e,s.relativePath),c=[];for(let u=a.params.length-1;u>=0;u--){let d=a.params[u];if(d.name===""||d.name.startsWith("_")||qK(l.get(d.name),a.paramsEndLine,a.endLine))break;c.unshift(d.name)}return c.length===0?null:{symbol:s.symbol,shortName:A(s.symbol),file:s.relativePath,startLine:s.startLine,endLine:s.endLine,paramCount:a.paramCount,unusedTrailing:c}},orderResults:(s,a)=>a.unusedTrailing.length-s.unusedTrailing.length||s.file.localeCompare(a.file)||s.startLine-a.startLine,limit:i})}function zK(e){let t=ye(e);return t==="typescript"||t==="tsx"||t==="javascript"}function qK(e,t,n){return e?e.some(i=>i>t&&i<=n):!1}var KK=new Set(on());function wm(e,t){let{scope:n,minLoc:i=10,limit:r=30,scanLimit:o}=t??{},s=new U(e),a=t?.semantic!==!1,l=fR(a,new Set,new Set);return{rows:Ht({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:i,requireFunctionLikeSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,filterCandidate:GK,profile:{name:"complexity-hotspots"},prepare:u=>{let d=VK(e,u);(a?Ot(e):null)?.materializeReferences(u,{prefetchCallees:!0});let f=sn(e,u,{semantic:a,semanticEvidence:ge}),p=s.calleeEvidenceMap(u,{semantic:a}),g=new Set([...f.incompleteSymbolIds,...p.incompleteSymbolIds]),h=new Set([...f.unavailableSymbolIds,...p.unavailableSymbolIds]);l=fR(a,g,h);let b=new Map(u.map(v=>[v.symbolId,v]));return{callerMap:new Map([...f.rows].map(([v,y])=>[v,new Set(y.filter(I=>I.file!==b.get(v)?.relativePath).map(I=>I.file))])),calleeMap:p.rows,incompleteSymbolIds:g,unavailableSymbolIds:h,languageByFile:d,clojureCallableIds:JK(e,u,d),branchEstimates:zx(e,u)}},evaluate:(u,d)=>d.incompleteSymbolIds.has(u.symbolId)||d.unavailableSymbolIds.has(u.symbolId)?null:WK(u,d,i),orderResults:(u,d)=>d.score-u.score||d.loc-u.loc,limit:r}),coverage:l}}function fR(e,t,n){let i=new Set([...t,...n]).size,r=e?t.size>0&&n.size>0?"incomplete-and-unavailable":t.size>0?"incomplete":n.size>0?"unavailable":"complete":"disabled";return{semanticEvidence:{enabled:e,status:r,incompleteSymbolCount:t.size,unavailableSymbolCount:n.size,excludedSymbolCount:i}}}function GK(e){return e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&KK.has(e.kind):!0}function WK(e,t,n){if(t.languageByFile.get(e.relativePath)==="clojure"&&!t.clojureCallableIds.has(e.symbolId))return null;let i=e.endLine-e.startLine+1;if(i<n)return null;let r=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 f=`${m.symbol}|${m.file}`;s.add(f),m.file!==e.relativePath&&a.add(f)}let l=a.size,c=s.size,u=t.branchEstimates.get(e.symbolId)??{branches:0,estimateBasis:"regex-fallback"},d=u.branches+1;return{symbol:e.symbol,shortName:A(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:i,fanIn:r,fanOut:l,calleeCount:c,branches:u.branches,estimateBasis:u.estimateBasis,score:Math.round(i/50*(r/5)*Math.max(l/5,1)*Math.max(d/5,1)*100)/100}}function VK(e,t){let n=[...new Set(t.map(o=>o.relativePath))];if(n.length===0)return new Map;let i=n.map(()=>"?").join(", "),r=e.all(`SELECT relative_path, language
457
+ LIMIT 1`,t,n)}function uR(e,t,n,i,r){let o=e.definitionsForFile(n),s=CK(t,n,i,r.start_line,r.end_line);return Ke(o,s)}function vK(e,t,n,i){if(i?.isFunctionLike){let r=[...e.get(i.symbolId)??[]].filter(o=>o!==i.relativePath);if(r.length>0)return{fanIn:r.length,source:"function"}}return{fanIn:RK(t,n),source:"file"}}function CK(e,t,n,i,r){let o=Y(n);if(!o)return i;let s=er(e,t).get(o);if(!s||s.length===0)return i;for(let a of s)if(a>=i&&a<=r)return a;return i}function xK(e){let t=new Map;for(let[n,i]of e){t.has(n)||t.set(n,t.get(n)??0);for(let r of i)t.set(r,(t.get(r)??0)+1)}return t}function RK(e,t){let n=e.get(t)??0;if(n>0)return n;let i=Fr(t,Tl(t)),r=0;for(let[o,s]of e)o!==t&&Fr(o,Tl(o))===i&&s>r&&(r=s);return r}function IK(e,t,n,i){return Rl(e,t.relativePath,t.startLine,"wrapper","explicit ignore-wrapper comment",[{label:"wrapper name",value:A(t.symbol)},{label:"caller name",value:i?.symbol?A(i.symbol):Fr(n)},{label:"wrapper path",value:t.relativePath},{label:"caller path",value:n}])}var EK=25e3,wK=2500,LK=2500;function DK(e){let t=Li(e);return t.symbols>=EK||t.documents>=wK?LK:void 0}function Cm(e,t={}){let{scope:n}=t,i=DK(e),r=[],o=ji(e,{scope:n,...je.dead,scanLimit:i});for(let s of o.symbols)Qe(e,s.relativePath)||qe(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&r.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of qo(e,{scope:n,...je.isolated,scanLimit:i}))Qe(e,s.relativePath)||qe(e,s.symbol,s.relativePath)||r.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of Uo(e,{scope:n}))s.kind==="real"&&r.push(`cycle:${MK(s.path)}`);for(let s of Vo(e,{scope:n,...je.similar,scanLimit:i}))r.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of is(e,{scope:n,...je.duplicateBodies,scanLimit:i}))r.push(`duplicate-bodies:${s.hash}:${s.functions.map(a=>a.symbol).sort().join("|")}`);for(let s of Zo(e,{scope:n,...je.extract,scanLimit:i}))r.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of ds(e,{scope:n,...je.wrappers,scanLimit:i}))r.push(`wrapper:${s.file}:${s.shortName}`);for(let s of rs(e,{scope:n,...je.passthroughs,scanLimit:i}))r.push(`passthrough:${s.file}:${s.shortName}`);for(let s of us(e,{scope:n,...je.stale,scanLimit:i}))r.push(`stale:${s.file}:${s.shortName}`);for(let s of cs(e,{scope:n,...je.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY}).results)s.kind!=="architecture-violation"&&r.push(`drift:${s.kind}:${s.file}:${s.dep}`);return r.push(...Cd(zo(e,{scope:n}))),[...new Set(r.map(ym))].sort()}function MK(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 PK(e,t={}){let n=Cm(e,{scope:t.scope}),i=bm(e,t.path);return nf(i,{version:1,findings:n},{spacing:2,trailingNewline:!0}),{path:i,findingCount:n.length}}function TK(e,t={}){return iR(e,Cm(e,{scope:t.scope}),{path:t.path})}function FK(e,t={}){let{scope:n,limit:i=30,scanLimit:r}=t,o=new U(e);return Ht({candidates:()=>o.productionCallableDefinitions({scope:n,files:t.files,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}),filterCandidate:s=>kK(s.relativePath),scanLimit:r,profile:{name:"unused-params"},evaluate:s=>{let a=te(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 l=er(e,s.relativePath),c=[];for(let u=a.params.length-1;u>=0;u--){let d=a.params[u];if(d.name===""||d.name.startsWith("_")||NK(l.get(d.name),a.paramsEndLine,a.endLine))break;c.unshift(d.name)}return c.length===0?null:{symbol:s.symbol,shortName:A(s.symbol),file:s.relativePath,startLine:s.startLine,endLine:s.endLine,paramCount:a.paramCount,unusedTrailing:c}},orderResults:(s,a)=>a.unusedTrailing.length-s.unusedTrailing.length||s.file.localeCompare(a.file)||s.startLine-a.startLine,limit:i})}function kK(e){let t=ye(e);return t==="typescript"||t==="tsx"||t==="javascript"}function NK(e,t,n){return e?e.some(i=>i>t&&i<=n):!1}var AK=new Set(on());function xm(e,t){let{scope:n,minLoc:i=10,limit:r=30,scanLimit:o}=t??{},s=new U(e),a=t?.semantic!==!1,l=dR(a,new Set,new Set);return{rows:Ht({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:i,requireFunctionLikeSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,filterCandidate:_K,profile:{name:"complexity-hotspots"},prepare:u=>{let d=OK(e,u);(a?Ot(e):null)?.materializeReferences(u,{prefetchCallees:!0});let f=sn(e,u,{semantic:a,semanticEvidence:ge}),p=s.calleeEvidenceMap(u,{semantic:a}),g=new Set([...f.incompleteSymbolIds,...p.incompleteSymbolIds]),h=new Set([...f.unavailableSymbolIds,...p.unavailableSymbolIds]);l=dR(a,g,h);let b=new Map(u.map(v=>[v.symbolId,v]));return{callerMap:new Map([...f.rows].map(([v,y])=>[v,new Set(y.filter(I=>I.file!==b.get(v)?.relativePath).map(I=>I.file))])),calleeMap:p.rows,incompleteSymbolIds:g,unavailableSymbolIds:h,languageByFile:d,clojureCallableIds:$K(e,u,d),branchEstimates:Hx(e,u)}},evaluate:(u,d)=>d.incompleteSymbolIds.has(u.symbolId)||d.unavailableSymbolIds.has(u.symbolId)?null:BK(u,d,i),orderResults:(u,d)=>d.score-u.score||d.loc-u.loc,limit:r}),coverage:l}}function dR(e,t,n){let i=new Set([...t,...n]).size,r=e?t.size>0&&n.size>0?"incomplete-and-unavailable":t.size>0?"incomplete":n.size>0?"unavailable":"complete":"disabled";return{semanticEvidence:{enabled:e,status:r,incompleteSymbolCount:t.size,unavailableSymbolCount:n.size,excludedSymbolCount:i}}}function _K(e){return e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&AK.has(e.kind):!0}function BK(e,t,n){if(t.languageByFile.get(e.relativePath)==="clojure"&&!t.clojureCallableIds.has(e.symbolId))return null;let i=e.endLine-e.startLine+1;if(i<n)return null;let r=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 f=`${m.symbol}|${m.file}`;s.add(f),m.file!==e.relativePath&&a.add(f)}let l=a.size,c=s.size,u=t.branchEstimates.get(e.symbolId)??{branches:0,estimateBasis:"regex-fallback"},d=u.branches+1;return{symbol:e.symbol,shortName:A(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:i,fanIn:r,fanOut:l,calleeCount:c,branches:u.branches,estimateBasis:u.estimateBasis,score:Math.round(i/50*(r/5)*Math.max(l/5,1)*Math.max(d/5,1)*100)/100}}function OK(e,t){let n=[...new Set(t.map(o=>o.relativePath))];if(n.length===0)return new Map;let i=n.map(()=>"?").join(", "),r=e.all(`SELECT relative_path, language
458
458
  FROM documents
459
- WHERE relative_path IN (${i})`,...n);return new Map(r.map(o=>[o.relative_path,o.language?.toLowerCase()??null]))}function JK(e,t,n){let i=new Set,r=new Map;for(let o of t){if(n.get(o.relativePath)!=="clojure")continue;let s=r.get(o.relativePath);s||(s=new Set((te(e,o.relativePath)?.callables??[]).map(a=>`${a.name}:${a.startLine}`)),r.set(o.relativePath,s)),s.has(`${o.leaf}:${o.startLine}`)&&i.add(o.symbolId)}return i}import{readdirSync as YK}from"fs";import{basename as XK,join as pR}from"path";function QK(e,t,n={}){let i=new Set(e),r=new Set(t),o=[...r].filter(a=>!i.has(a)).sort(),s=n.allowExtra?[]:[...i].filter(a=>!r.has(a)).sort();return{missing:o,extra:s}}function ZK(e,t){let n=eG(e,t.file,t.keys);if(!n.ok)return{name:t.name,file:t.file,status:"unavailable",missing:[],extra:[],unavailableReason:n.reason};let i=sG(e.config.projectRoot,t.mustEqual),r=QK(n.keys,i,{allowExtra:t.allowExtra??!1}),o=r.missing.length>0||r.extra.length>0?"violated":"ok";return{name:t.name,file:t.file,status:o,missing:r.missing,extra:r.extra}}function hR(e,t){return t.map(n=>ZK(e,n))}function eG(e,t,n){return n.type==="markdown-list"?oG(e,t,n.marker):tG(e,t,n)}function tG(e,t,n){if(!se(e,t))return{ok:!1,reason:`file not found: ${t}`};let r=ye(t);if(!r)return{ok:!1,reason:`unsupported file type for ${n.type} extraction: ${t}`};let o=ae(e,t);if(!o)return{ok:!1,reason:`tree-sitter parser unavailable for ${r} (${t}) \u2014 contract skipped, not silently passed`,disclosedUnavailable:{language:r,reason:"parser-unavailable"}};let s=n.type==="object-literal-keys"?nG(o,n.identifier):rG(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 yR(e){let t=e.childForFieldName("value");return t?t.type==="as_expression"||t.type==="satisfies_expression"?t.namedChild(0):t:null}function nG(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let r=yR(n);if(r?.type==="object")return iG(r)}return null}function iG(e){let t=new Set;for(let n of e.namedChildren)if(n.type==="pair"){let i=n.childForFieldName("key");i&&t.add(bR(i.text))}else n.type==="shorthand_property_identifier"&&t.add(n.text);return[...t].sort()}function rG(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let r=yR(n);if(r?.type!=="array")continue;let o=new Set;for(let s of r.namedChildren)s.type==="string"&&o.add(bR(s.text));return[...o].sort()}return null}function bR(e){return e.length>=2&&(e[0]==="'"&&e.endsWith("'")||e[0]==='"'&&e.endsWith('"'))?e.slice(1,-1):e}function oG(e,t,n){let i=se(e,t);if(!i)return{ok:!1,reason:`file not found: ${t}`};let r=SR(i,n);return r===null?{ok:!1,reason:`no <!-- BEGIN GENERATED ${n} --> ... <!-- END GENERATED ${n} --> block in ${t}`}:{ok:!0,keys:vR(r)}}function SR(e,t){let n=Oe(t),r=new RegExp(`<!--\\s*BEGIN GENERATED ${n}\\s*-->([\\s\\S]*?)<!--\\s*END GENERATED ${n}\\s*-->`).exec(e);return r?r[1]:null}function vR(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 sG(e,t){switch(t.type){case"top-level-dirs":return gR(pR(e,t.path));case"file-glob":return[...new Set(ll(e,t.pattern).map(n=>XK(n)))].sort();case"registered-commands":return aG(e);case"builtin-skills":return gR(pR(e,"skills"))}}function gR(e){let t;try{t=YK(e,{withFileTypes:!0})}catch{return[]}return t.filter(n=>n.isDirectory()&&!n.name.startsWith(".")).map(n=>n.name).sort()}function aG(e){let t;try{t=rt(e,"docs/COMMAND_REFERENCE.md",{maxBytes:8*1024*1024,inputKind:"generated command reference"})}catch(i){if(!ot(i))throw i;return[]}let n=SR(t,"COMMAND REFERENCE");return n?vR(n):[]}function On(e){return e.scoreCount??e.count}function RR(e){let t=mG(e),{breakdown:n,pressure:i}=fG(e),r=xR(n,"risk"),o=xR(n,"hygiene"),s=lG(e),a=[...e.warnings];e.complexity.coverage.semanticEvidence.excludedSymbolCount>0&&a.push(`Complexity scoring excluded ${e.complexity.coverage.semanticEvidence.excludedSymbolCount} symbol(s) with incomplete or unavailable compiler evidence.`);let l=e.evidenceCoverage.filter(c=>c.semanticEvidence.status!=="complete"&&c.semanticEvidence.status!=="disabled");return l.length>0&&a.push(`Compiler-resolved evidence was incomplete or unavailable in health phase(s): ${l.map(c=>c.phase).join(", ")}.`),{score:Math.min(r,o),riskScore:r,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:On(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:On(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:On(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:cG(e),validation:dG(e),suppressions:e.suppressions,actions:t,pressure:i,topComplexity:e.complexity.top,coverage:s,warnings:a.length>0?a:void 0}}function lG(e){let t=e.complexity.coverage.semanticEvidence.status;return{status:e.evidenceCoverage.some(i=>i.semanticEvidence.status!=="complete"&&i.semanticEvidence.status!=="disabled")?"incomplete":t==="disabled"?"semantic-disabled":t==="complete"?"complete":"incomplete",complexity:e.complexity.coverage,phases:e.evidenceCoverage}}function cG(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:uG(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 uG(e){let t=e.gitEvidence?.fileStats;return t?e.complexity.top.map(n=>{let i=n.file?t[n.file]?.changes??0:0;return{...n,changes:i,weighted:Sn(n.score*Math.log2(1+i))}}).sort((n,i)=>i.weighted-n.weighted):null}function dG(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??[]},i=new Set(Object.values(n).flat()),r=0,o=0,s=0;for(let[u,d]of Object.entries(t))i.has(u)?r+=d.fixChanges:(o+=d.fixChanges,s+=1);let a=i.size>0?Sn(r/i.size):0,l=s>0?Sn(o/s):0,c={};for(let[u,d]of Object.entries(n)){let m=new Set(d);if(m.size===0)continue;let f=0;for(let g of m)f+=t[g]?.fixChanges??0;let p=Sn(f/m.size);c[u]={flaggedFiles:m.size,fixDensity:p,lift:l>0?Sn(p/l):null}}return{flaggedFiles:i.size,flaggedFixDensity:a,baselineFixDensity:l,ratio:i.size>0&&l>0?Sn(a/l):null,byCategory:c,validationBasis:{method:"subject-regex",commitsScanned:e.gitEvidence?.commitsScanned??0}}}function Sn(e){return Math.round(e*100)/100}function IR(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function kl(e,t="existing shared infrastructure discount"){let n=On(e);return Math.abs(n-e.count)<.01?"":` (${IR(n)} score-weighted after ${t})`}function ps(e,t){let n=On(e),i=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?i:`${i} (${IR(n)} score-weighted)`}function mG(e){let t=[];if(e.dead.count>0&&t.push({category:"Dead code",evidence:"graph-fact",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",description:`${e.isolated.count} symbols completely disconnected from the codebase graph`,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",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",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${kl(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${kl(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",description:`${e.wrappers.count} single-consumer symbols${kl(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",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 r=[];e.stale.unused>0&&r.push(`${e.stale.unused} unused`),e.stale.singleUse>0&&r.push(`${e.stale.singleUse} single-consumer (not in types file)`),t.push({category:"Stale abstractions",evidence:"heuristic",description:`${r.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 r=[];e.drift.unusedImports>0&&r.push(`${e.drift.unusedImports} unused imports`),e.drift.architectureViolations>0&&r.push(`${e.drift.architectureViolations} declared architecture violations`),t.push({category:"Structural drift",evidence:"heuristic",description:`${r.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 \`codebaseiq 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 r=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`+kl({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:e.gitEvidence.hiddenCoupling.scoreCount},"broad/stale-history discount")+(r?` (e.g. ${r.fileA} \u2194 ${r.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},i={low:3,medium:2,high:1};return t.sort((r,o)=>{let s=n[r.impact]*i[r.effort];return n[o.impact]*i[o.effort]-s}),t}var CR={"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 xR(e,t){let n=e.filter(i=>i.kind===t).reduce((i,r)=>i+r.points,0);return Math.max(0,Math.min(100,100-n))}function fG(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),i=[],r=[],o=(x,C,L)=>{C>0&&i.push({axis:x,points:C,detail:L,kind:CR[x]??"hygiene"})},s=(x,C,L,w,R,M,_)=>{let D=Math.max(w,1);if(L<=D)return;let P=L/D,k=Math.min(R,Math.ceil(Math.log2(P)*M));if(k<=0)return;let V=CR[x]??"hygiene";r.push({axis:x,category:C,kind:V,count:L,threshold:Sn(D),ratio:Sn(P),extraPenalty:k}),o(x,k,`${L} ${_} exceed pressure threshold ${Sn(D)} (${Sn(P)}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 l=e.isolated.count/n;o("isolated",Math.min(10,Math.round(l*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 c=e.similarCount/n*1e3;o("similar",Math.min(10,Math.round(c)),`${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 f=On(e.reactHookCandidates),p=f/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(p)),ps(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=On(e.vueComposableCandidates),v=b/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(v)),ps(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 I=On(e.wrappers);o("wrappers",Math.min(3,I),ps(e.wrappers,"wrapper candidate(s)"));let E=On(e.passthroughs);o("passthroughs",Math.min(3,E),ps(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 S=e.drift.direct/t;if(o("drift",Math.min(5,Math.round(S*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 x=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(x/10)),ps({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:x},"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 x=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",x,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",f,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",I,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",E,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:i,pressure:r}}import{getHeapStatistics as pG}from"v8";var gG=64*1024*1024;function Lm(){let e=globalThis.gc;if(!e)return;let t=pG();t.heap_size_limit-t.used_heap_size<gG||e()}var hG=50,yG=25e3,bG=2500,ER=2500,wR=50,SG=10,Nl=["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"],vG={overview:(e,t,n,i)=>({phase:"overview",statsResult:i,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:EG(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:wG(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:LG(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:DG(e,t,n)}),"duplicate-bodies":(e,t,n)=>({phase:"duplicate-bodies",duplicateBodies:PG(e,t,n)}),"twin-drift":(e,t,n)=>({phase:"twin-drift",twinDrift:TG(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:FG(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:kG(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:NG(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:AG(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:_G(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:BG(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:MG(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:OG(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:$G(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:jG(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:qG(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:KG(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:HG(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:UG(e,n)}),"coverage-contracts":(e,t,n)=>({phase:"coverage-contracts",coverageContracts:zG(e,n)})};function Dm(e,t,n={}){return CG(e,[t],n)[0]}function CG(e,t,n={}){return xG(e,n.full!==!1,(i,r)=>{let o={...r,releaseCachesBetweenPhases:!1};return t.map(s=>IG(e,s,n.scope,o,i))})}function xG(e,t,n){let i=Li(e),r=GG(i,t);try{return n(i,r)}finally{xd(e,{semanticProvider:!0}),Lm()}}function Mm(e){return RR(RG(e))}function RG(e){let t=ze(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,evidenceCoverage:e.map(i=>({phase:i.phase,semanticEvidence:i.evidenceCoverage})),dead:ze(e,"dead").dead,isolated:ze(e,"isolated").isolated,realCycleCount:ze(e,"cycles").realCycleCount,similarCount:ze(e,"similar").similarCount,duplicateBodies:ze(e,"duplicate-bodies").duplicateBodies,twinDrift:ze(e,"twin-drift").twinDrift,reactComponentDuplicates:ze(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:ze(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:ze(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:ze(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:ze(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:ze(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:ze(e,"extract-candidates").extractCount,wrappers:ze(e,"wrapper-candidates").wrappers,passthroughs:ze(e,"passthrough-candidates").passthroughs,stale:ze(e,"stale-abstractions").stale,drift:ze(e,"drift").drift,complexity:ze(e,"complexity-hotspots").complexity,gitEvidence:LR(e,"git-evidence")?.gitEvidence??null,suppressions:LR(e,"suppressions")?.suppressions??null,coverageContracts:ze(e,"coverage-contracts").coverageContracts}}function LR(e,t){return e.find(n=>n.phase===t)}function ze(e,t){let n=e.find(i=>i.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function IG(e,t,n,i,r){hh(e);let o=vG[t](e,n,i,r),s=yh(e),a=s.incompleteSymbolIds.size,l=s.unavailableSymbolIds.size,c=i.semantic?a>0&&l>0?"incomplete-and-unavailable":a>0?"incomplete":l>0?"unavailable":"complete":"disabled";return{...o,evidenceCoverage:{enabled:i.semantic,status:c,incompleteSymbolCount:a,unavailableSymbolCount:l}}}function EG(e,t,n){return He(e,n,"dead",()=>{let i=ji(e,{scope:t,...je.dead,scanLimit:n.candidateScanLimit,semantic:n.semantic});return Al(JG(e,i.symbols))})}function wG(e,t,n){return He(e,n,"isolated",()=>{let i=Go(e,{scope:t,...je.isolated,scanLimit:n.candidateScanLimit,semantic:n.semantic});return Al(YG(e,i))})}function LG(e,t,n){return He(e,n,"cycles",()=>qo(e,{scope:t}).filter(r=>r.kind==="real").length)}function DG(e,t,n){let i=He(e,n,"similar",()=>Fd(e,{scope:t,...je.similar,scanLimit:n.candidateScanLimit,semantic:n.semantic}));return Math.min(i,n.candidateResultLimit)}function MG(e,t,n){return He(e,n,"extract-candidates",()=>ts(e,{scope:t,...je.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}).length)}function PG(e,t,n){return He(e,n,"duplicate-bodies",()=>{let i=os(e,{scope:t,...je.duplicateBodies,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),r=new Set,o=0;for(let s of i)for(let a of s.functions.slice(1))r.add(a.file),o+=a.loc;return{count:i.length,loc:o,files:[...r]}})}function TG(e,t,n){return He(e,n,"twin-drift",()=>{let i=Rl(e,{scope:t,...je.twinDrift,scanLimit:n.candidateScanLimit}).filter(s=>s.relationship==="divergent"||s.relationship==="identical"),r=new Set,o=0;for(let s of i)for(let a of s.members)r.add(a.file),o+=a.loc;return{count:i.length,loc:o,files:[...r].sort()}})}function FG(e,t,n){return He(e,n,"react-component-duplicates",()=>{let i=Xo(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Pm(i)})}function kG(e,t,n){return He(e,n,"react-hook-candidates",()=>{let i=Qo(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return PR(i,QG)})}function NG(e,t,n){return He(e,n,"react-large-component-pressure",()=>{let i=kd(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return XG(i)})}function AG(e,t,n){return He(e,n,"vue-component-duplicates",()=>{let i=Zo(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Pm(i)})}function _G(e,t,n){return He(e,n,"vue-composable-candidates",()=>{let i=es(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return PR(i,ZG)})}function BG(e,t,n){return He(e,n,"vue-large-view-pressure",()=>{let i=Nd(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Al(i)})}function OG(e,t,n){return He(e,n,"wrapper-candidates",()=>{let i=fs(e,{scope:t,...je.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return MR(i,eW)})}function $G(e,t,n){return He(e,n,"passthrough-candidates",()=>{let i=ss(e,{scope:t,...je.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return MR(i,tW)})}function jG(e,t,n){return He(e,n,"stale-abstractions",()=>{let i=ms(e,{scope:t,...je.stale,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}),r=i.filter(o=>o.consumers===0).length;return{count:i.length,loc:i.reduce((o,s)=>o+s.loc,0),files:[...new Set(i.map(o=>o.file))],unused:r,singleUse:i.length-r}})}function HG(e,t){return He(e,t,"git-evidence",()=>{let n=Xt(e,{historyMode:t.gitHistoryMode}),i=n.fileChurn();if(!i)return null;let r=n.commitHistory(),o=is(e,void 0,{limit:t.candidateResultLimit,historyMode:t.gitHistoryMode}),s={};for(let[a,l]of i)s[a]={changes:l.changes,fixChanges:l.fixChanges};return{amplification:n.changeAmplification(),hiddenCoupling:{pairCount:o.findings.length,scoreCount:Tm(o.findings.reduce((a,l)=>a+DR(l),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:DR(a),subjectContext:a.subjectContext}))},fileStats:s,commitsScanned:r?.commits.length??0}})}function UG(e,t){return He(e,t,"suppressions",()=>{let n=Ll(e);return{total:n.total,byCategory:{...n.byCategory}}})}function zG(e,t){return He(e,t,"coverage-contracts",()=>{let n=e.config.coverageContracts??[],r=hR(e,n).filter(o=>o.status!=="ok");return{count:r.length,loc:0,files:[...new Set(r.map(o=>o.file))].sort()}})}function qG(e,t,n){return He(e,n,"drift",()=>{let i=ds(e,{scope:t,...je.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY,semantic:n.semantic}),r=i.results.filter(a=>a.kind!=="pattern-deviation"),o=r.filter(a=>a.actionTier==="direct").length,s=r.length-o;return{count:r.length,unusedImports:i.unusedImports,architectureViolations:i.architectureViolations,layerViolations:i.layerViolations,direct:o,signal:s}})}function KG(e,t,n){return He(e,n,"complexity-hotspots",()=>{let i=wm(e,{scope:t,minLoc:10,limit:n.complexityResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return{top:i.rows.slice(0,5).map(r=>({symbol:r.shortName,score:r.score,file:r.file})),extremeCount:i.rows.filter(r=>r.score>hG).length,coverage:i.coverage}})}function GG(e,t){let n=e.symbols>=yG||e.documents>=bG,i=t?Number.POSITIVE_INFINITY:wR,r=t?Number.POSITIVE_INFINITY:SG;return!n||t?{candidateScanLimit:void 0,candidateResultLimit:i,complexityResultLimit:r,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:ER,candidateResultLimit:i,complexityResultLimit:r,semantic:!1,gitHistoryMode:"bounded",releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${ER} symbols and reported their top ${wR} findings. Enable full mode for unbounded candidate counts.`]}}function WG(e,t){t.releaseCachesBetweenPhases&&(xd(e),Lm())}function He(e,t,n,i){VG(n);try{return i()}finally{WG(e,t)}}function VG(e){process.env.CODEBASEIQ_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function JG(e,t){return t.filter(n=>!Qe(e,n.relativePath)&&!qe(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function YG(e,t){return t.filter(n=>!Qe(e,n.relativePath)&&!qe(e,n.symbol,n.relativePath))}function Al(e){let t=new Set;for(let n of e){let i=n.relativePath??n.file;i&&t.add(i)}return{count:e.length,loc:e.reduce((n,i)=>n+i.loc,0),files:[...t]}}function MR(e,t){return{...Al(e),scoreCount:Tm(e.reduce((i,r)=>i+t(r),0))}}function XG(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,i)=>n+i,0),files:[...t.keys()]}}function Pm(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,i)=>n+i,0),files:[...t.keys()]}}function PR(e,t){return{...Pm(e),scoreCount:Tm(e.reduce((i,r)=>i+t(r),0))}}function QG(e){let t=e.sharedHooks.length>0,n=TR({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:FR(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function ZG(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=TR({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:FR(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function TR(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!NR.has(kR(t))).length+Math.min(e.functions.length,3)}function FR(e,t,n){let i=[...e,...t,...n].map(kR);return i.length>0&&i.every(r=>NR.has(r))}function kR(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function eW(e){return e.actionTier==="signal"?.25:1}function tW(e){return e.actionTier==="signal"?.25:1}function DR(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 Tm(e){return Math.round(e*100)/100}var NR=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 nW(e,t,n,i={}){let r=Td(e,t,n,i);return r?{symbolA:r.symbolA,symbolB:r.symbolB,similarity:r.similarity,sharedCallees:r.sharedEvidence,uniqueToA:r.uniqueToA,uniqueToB:r.uniqueToB,consolidationStrategy:r.consolidationStrategy}:null}function iW(e,t,n={}){let i=Uo(e,t,{families:["dataflow"],...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.maxEdges!==void 0?{maxEdges:n.maxEdges}:{}});return{kind:"value-flow",targets:i.targets,edges:i.edges,coverage:{status:i.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:i.coverage}}}var rW=/:\d+(?:-\d+)?$/u;function oW(e,t,n={}){let i=n.direction??"backward",r=n.maxDepth??3;if(!Number.isSafeInteger(r)||r<0)throw new RangeError(`Dependence-slice depth must be a non-negative safe integer; received ${r}.`);let o=rW.test(t),s=Uo(e,o?{locations:[t]}:{symbols:[t]},{families:["execution","runtime","dataflow","ownership"],maxDepth:r+1,maxEdges:n.maxEdges??200}),a=new Set(s.targets.flatMap(d=>d.nodeIds)),l=new Set(a),c=new Map;AR(s.edges,l,c,0);for(let d=1;d<=r;d+=1){let m=[];for(let f of s.edges)if(i==="backward"?l.has(f.to.id):l.has(f.from.id)){let p=i==="backward"?f.from.id:f.to.id;if(l.has(p))continue;m.push(p),c.set(f.id,d)}if(m.length===0)break;for(let f of m)l.add(f);AR(s.edges,l,c,d)}let u=s.edges.filter(d=>l.has(d.from.id)&&l.has(d.to.id)).filter(d=>c.has(d.id)||d.family==="ownership").map(d=>({...d,traversalDepth:c.get(d.id)??0,supporting:d.family!=="dataflow"&&!sW(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:i,criterion:t,targets:s.targets,nodeIds:[...l].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 AR(e,t,n,i){let r=!0;for(;r;){r=!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,i),r=!0)}}function sW(e){return e.semanticFamily==="control"&&e.sourceKind==="control-dependence"}function aW(e,t={}){let{scope:n,limit:i}=t,r=new U(e),o=hW([...lW(e,n),...dW(e,r,n)]);return yW(o),i?o.slice(0,i):o}function lW(e,t){let n=[];for(let i of cW(e,t)){if(e.isIgnored(i.barrel_path)||e.isIgnored(i.original_path)||Mu(e,i.barrel_path)||se(e,i.barrel_path)&&ks(e,i.barrel_path).length===0)continue;let r=uW(e,i),o=r?.barrel_consumers??0,s=r?.direct_consumers??0;o!==0||s!==0||n.push({barrelFile:i.barrel_path,symbol:i.symbol,shortName:A(i.symbol),originalFile:i.original_path,barrelConsumers:o,directConsumers:s,...BR(e,i.barrel_path)})}return n}function cW(e,t){let n=t?"AND barrel_d.relative_path LIKE ?":"",i=t?[`%${t}%`]:[];return e.all(`WITH barrel_refs AS MATERIALIZED (
459
+ WHERE relative_path IN (${i})`,...n);return new Map(r.map(o=>[o.relative_path,o.language?.toLowerCase()??null]))}function $K(e,t,n){let i=new Set,r=new Map;for(let o of t){if(n.get(o.relativePath)!=="clojure")continue;let s=r.get(o.relativePath);s||(s=new Set((te(e,o.relativePath)?.callables??[]).map(a=>`${a.name}:${a.startLine}`)),r.set(o.relativePath,s)),s.has(`${o.leaf}:${o.startLine}`)&&i.add(o.symbolId)}return i}import{readdirSync as jK}from"fs";import{basename as HK,join as mR}from"path";function UK(e,t,n={}){let i=new Set(e),r=new Set(t),o=[...r].filter(a=>!i.has(a)).sort(),s=n.allowExtra?[]:[...i].filter(a=>!r.has(a)).sort();return{missing:o,extra:s}}function zK(e,t){let n=qK(e,t.file,t.keys);if(!n.ok)return{name:t.name,file:t.file,status:"unavailable",missing:[],extra:[],unavailableReason:n.reason};let i=YK(e.config.projectRoot,t.mustEqual),r=UK(n.keys,i,{allowExtra:t.allowExtra??!1}),o=r.missing.length>0||r.extra.length>0?"violated":"ok";return{name:t.name,file:t.file,status:o,missing:r.missing,extra:r.extra}}function pR(e,t){return t.map(n=>zK(e,n))}function qK(e,t,n){return n.type==="markdown-list"?JK(e,t,n.marker):KK(e,t,n)}function KK(e,t,n){if(!se(e,t))return{ok:!1,reason:`file not found: ${t}`};let r=ye(t);if(!r)return{ok:!1,reason:`unsupported file type for ${n.type} extraction: ${t}`};let o=ae(e,t);if(!o)return{ok:!1,reason:`tree-sitter parser unavailable for ${r} (${t}) \u2014 contract skipped, not silently passed`,disclosedUnavailable:{language:r,reason:"parser-unavailable"}};let s=n.type==="object-literal-keys"?GK(o,n.identifier):VK(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 gR(e){let t=e.childForFieldName("value");return t?t.type==="as_expression"||t.type==="satisfies_expression"?t.namedChild(0):t:null}function GK(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let r=gR(n);if(r?.type==="object")return WK(r)}return null}function WK(e){let t=new Set;for(let n of e.namedChildren)if(n.type==="pair"){let i=n.childForFieldName("key");i&&t.add(hR(i.text))}else n.type==="shorthand_property_identifier"&&t.add(n.text);return[...t].sort()}function VK(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let r=gR(n);if(r?.type!=="array")continue;let o=new Set;for(let s of r.namedChildren)s.type==="string"&&o.add(hR(s.text));return[...o].sort()}return null}function hR(e){return e.length>=2&&(e[0]==="'"&&e.endsWith("'")||e[0]==='"'&&e.endsWith('"'))?e.slice(1,-1):e}function JK(e,t,n){let i=se(e,t);if(!i)return{ok:!1,reason:`file not found: ${t}`};let r=yR(i,n);return r===null?{ok:!1,reason:`no <!-- BEGIN GENERATED ${n} --> ... <!-- END GENERATED ${n} --> block in ${t}`}:{ok:!0,keys:bR(r)}}function yR(e,t){let n=Oe(t),r=new RegExp(`<!--\\s*BEGIN GENERATED ${n}\\s*-->([\\s\\S]*?)<!--\\s*END GENERATED ${n}\\s*-->`).exec(e);return r?r[1]:null}function bR(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 YK(e,t){switch(t.type){case"top-level-dirs":return fR(mR(e,t.path));case"file-glob":return[...new Set(al(e,t.pattern).map(n=>HK(n)))].sort();case"registered-commands":return XK(e);case"builtin-skills":return fR(mR(e,"skills"))}}function fR(e){let t;try{t=jK(e,{withFileTypes:!0})}catch{return[]}return t.filter(n=>n.isDirectory()&&!n.name.startsWith(".")).map(n=>n.name).sort()}function XK(e){let t;try{t=rt(e,"docs/COMMAND_REFERENCE.md",{maxBytes:8*1024*1024,inputKind:"generated command reference"})}catch(i){if(!ot(i))throw i;return[]}let n=yR(t,"COMMAND REFERENCE");return n?bR(n):[]}function On(e){return e.scoreCount??e.count}function CR(e){let t=nG(e),{breakdown:n,pressure:i}=iG(e),r=vR(n,"risk"),o=vR(n,"hygiene"),s=QK(e),a=[...e.warnings];e.complexity.coverage.semanticEvidence.excludedSymbolCount>0&&a.push(`Complexity scoring excluded ${e.complexity.coverage.semanticEvidence.excludedSymbolCount} symbol(s) with incomplete or unavailable compiler evidence.`);let l=e.evidenceCoverage.filter(c=>c.semanticEvidence.status!=="complete"&&c.semanticEvidence.status!=="disabled");return l.length>0&&a.push(`Compiler-resolved evidence was incomplete or unavailable in health phase(s): ${l.map(c=>c.phase).join(", ")}.`),{score:Math.min(r,o),riskScore:r,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:On(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:On(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:On(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:ZK(e),validation:tG(e),suppressions:e.suppressions,actions:t,pressure:i,topComplexity:e.complexity.top,coverage:s,warnings:a.length>0?a:void 0}}function QK(e){let t=e.complexity.coverage.semanticEvidence.status;return{status:e.evidenceCoverage.some(i=>i.semanticEvidence.status!=="complete"&&i.semanticEvidence.status!=="disabled")?"incomplete":t==="disabled"?"semantic-disabled":t==="complete"?"complete":"incomplete",complexity:e.complexity.coverage,phases:e.evidenceCoverage}}function ZK(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:eG(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 eG(e){let t=e.gitEvidence?.fileStats;return t?e.complexity.top.map(n=>{let i=n.file?t[n.file]?.changes??0:0;return{...n,changes:i,weighted:Sn(n.score*Math.log2(1+i))}}).sort((n,i)=>i.weighted-n.weighted):null}function tG(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??[]},i=new Set(Object.values(n).flat()),r=0,o=0,s=0;for(let[u,d]of Object.entries(t))i.has(u)?r+=d.fixChanges:(o+=d.fixChanges,s+=1);let a=i.size>0?Sn(r/i.size):0,l=s>0?Sn(o/s):0,c={};for(let[u,d]of Object.entries(n)){let m=new Set(d);if(m.size===0)continue;let f=0;for(let g of m)f+=t[g]?.fixChanges??0;let p=Sn(f/m.size);c[u]={flaggedFiles:m.size,fixDensity:p,lift:l>0?Sn(p/l):null}}return{flaggedFiles:i.size,flaggedFixDensity:a,baselineFixDensity:l,ratio:i.size>0&&l>0?Sn(a/l):null,byCategory:c,validationBasis:{method:"subject-regex",commitsScanned:e.gitEvidence?.commitsScanned??0}}}function Sn(e){return Math.round(e*100)/100}function xR(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function Fl(e,t="existing shared infrastructure discount"){let n=On(e);return Math.abs(n-e.count)<.01?"":` (${xR(n)} score-weighted after ${t})`}function ms(e,t){let n=On(e),i=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?i:`${i} (${xR(n)} score-weighted)`}function nG(e){let t=[];if(e.dead.count>0&&t.push({category:"Dead code",evidence:"graph-fact",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",description:`${e.isolated.count} symbols completely disconnected from the codebase graph`,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",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",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${Fl(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${Fl(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",description:`${e.wrappers.count} single-consumer symbols${Fl(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",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 r=[];e.stale.unused>0&&r.push(`${e.stale.unused} unused`),e.stale.singleUse>0&&r.push(`${e.stale.singleUse} single-consumer (not in types file)`),t.push({category:"Stale abstractions",evidence:"heuristic",description:`${r.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 r=[];e.drift.unusedImports>0&&r.push(`${e.drift.unusedImports} unused imports`),e.drift.architectureViolations>0&&r.push(`${e.drift.architectureViolations} declared architecture violations`),t.push({category:"Structural drift",evidence:"heuristic",description:`${r.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 \`codebaseiq 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 r=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`+Fl({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:e.gitEvidence.hiddenCoupling.scoreCount},"broad/stale-history discount")+(r?` (e.g. ${r.fileA} \u2194 ${r.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},i={low:3,medium:2,high:1};return t.sort((r,o)=>{let s=n[r.impact]*i[r.effort];return n[o.impact]*i[o.effort]-s}),t}var SR={"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 vR(e,t){let n=e.filter(i=>i.kind===t).reduce((i,r)=>i+r.points,0);return Math.max(0,Math.min(100,100-n))}function iG(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),i=[],r=[],o=(x,C,L)=>{C>0&&i.push({axis:x,points:C,detail:L,kind:SR[x]??"hygiene"})},s=(x,C,L,w,R,M,_)=>{let D=Math.max(w,1);if(L<=D)return;let P=L/D,k=Math.min(R,Math.ceil(Math.log2(P)*M));if(k<=0)return;let V=SR[x]??"hygiene";r.push({axis:x,category:C,kind:V,count:L,threshold:Sn(D),ratio:Sn(P),extraPenalty:k}),o(x,k,`${L} ${_} exceed pressure threshold ${Sn(D)} (${Sn(P)}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 l=e.isolated.count/n;o("isolated",Math.min(10,Math.round(l*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 c=e.similarCount/n*1e3;o("similar",Math.min(10,Math.round(c)),`${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 f=On(e.reactHookCandidates),p=f/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(p)),ms(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=On(e.vueComposableCandidates),v=b/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(v)),ms(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 I=On(e.wrappers);o("wrappers",Math.min(3,I),ms(e.wrappers,"wrapper candidate(s)"));let E=On(e.passthroughs);o("passthroughs",Math.min(3,E),ms(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 S=e.drift.direct/t;if(o("drift",Math.min(5,Math.round(S*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 x=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(x/10)),ms({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:x},"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 x=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",x,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",f,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",I,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",E,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:i,pressure:r}}import{getHeapStatistics as rG}from"v8";var oG=64*1024*1024;function Rm(){let e=globalThis.gc;if(!e)return;let t=rG();t.heap_size_limit-t.used_heap_size<oG||e()}var sG=50,aG=25e3,lG=2500,RR=2500,IR=50,cG=10,kl=["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"],uG={overview:(e,t,n,i)=>({phase:"overview",statsResult:i,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:gG(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:hG(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:yG(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:bG(e,t,n)}),"duplicate-bodies":(e,t,n)=>({phase:"duplicate-bodies",duplicateBodies:vG(e,t,n)}),"twin-drift":(e,t,n)=>({phase:"twin-drift",twinDrift:CG(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:xG(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:RG(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:IG(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:EG(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:wG(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:LG(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:SG(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:DG(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:MG(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:PG(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:NG(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:AG(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:TG(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:FG(e,n)}),"coverage-contracts":(e,t,n)=>({phase:"coverage-contracts",coverageContracts:kG(e,n)})};function Im(e,t,n={}){return dG(e,[t],n)[0]}function dG(e,t,n={}){return mG(e,n.full!==!1,(i,r)=>{let o={...r,releaseCachesBetweenPhases:!1};return t.map(s=>pG(e,s,n.scope,o,i))})}function mG(e,t,n){let i=Li(e),r=_G(i,t);try{return n(i,r)}finally{bd(e,{semanticProvider:!0}),Rm()}}function Em(e){return CR(fG(e))}function fG(e){let t=ze(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,evidenceCoverage:e.map(i=>({phase:i.phase,semanticEvidence:i.evidenceCoverage})),dead:ze(e,"dead").dead,isolated:ze(e,"isolated").isolated,realCycleCount:ze(e,"cycles").realCycleCount,similarCount:ze(e,"similar").similarCount,duplicateBodies:ze(e,"duplicate-bodies").duplicateBodies,twinDrift:ze(e,"twin-drift").twinDrift,reactComponentDuplicates:ze(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:ze(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:ze(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:ze(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:ze(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:ze(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:ze(e,"extract-candidates").extractCount,wrappers:ze(e,"wrapper-candidates").wrappers,passthroughs:ze(e,"passthrough-candidates").passthroughs,stale:ze(e,"stale-abstractions").stale,drift:ze(e,"drift").drift,complexity:ze(e,"complexity-hotspots").complexity,gitEvidence:ER(e,"git-evidence")?.gitEvidence??null,suppressions:ER(e,"suppressions")?.suppressions??null,coverageContracts:ze(e,"coverage-contracts").coverageContracts}}function ER(e,t){return e.find(n=>n.phase===t)}function ze(e,t){let n=e.find(i=>i.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function pG(e,t,n,i,r){ph(e);let o=uG[t](e,n,i,r),s=gh(e),a=s.incompleteSymbolIds.size,l=s.unavailableSymbolIds.size,c=i.semantic?a>0&&l>0?"incomplete-and-unavailable":a>0?"incomplete":l>0?"unavailable":"complete":"disabled";return{...o,evidenceCoverage:{enabled:i.semantic,status:c,incompleteSymbolCount:a,unavailableSymbolCount:l}}}function gG(e,t,n){return He(e,n,"dead",()=>{let i=ji(e,{scope:t,...je.dead,scanLimit:n.candidateScanLimit,semantic:n.semantic});return Nl($G(e,i.symbols))})}function hG(e,t,n){return He(e,n,"isolated",()=>{let i=qo(e,{scope:t,...je.isolated,scanLimit:n.candidateScanLimit,semantic:n.semantic});return Nl(jG(e,i))})}function yG(e,t,n){return He(e,n,"cycles",()=>Uo(e,{scope:t}).filter(r=>r.kind==="real").length)}function bG(e,t,n){let i=He(e,n,"similar",()=>Dd(e,{scope:t,...je.similar,scanLimit:n.candidateScanLimit,semantic:n.semantic}));return Math.min(i,n.candidateResultLimit)}function SG(e,t,n){return He(e,n,"extract-candidates",()=>Zo(e,{scope:t,...je.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}).length)}function vG(e,t,n){return He(e,n,"duplicate-bodies",()=>{let i=is(e,{scope:t,...je.duplicateBodies,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),r=new Set,o=0;for(let s of i)for(let a of s.functions.slice(1))r.add(a.file),o+=a.loc;return{count:i.length,loc:o,files:[...r]}})}function CG(e,t,n){return He(e,n,"twin-drift",()=>{let i=xl(e,{scope:t,...je.twinDrift,scanLimit:n.candidateScanLimit}).filter(s=>s.relationship==="divergent"||s.relationship==="identical"),r=new Set,o=0;for(let s of i)for(let a of s.members)r.add(a.file),o+=a.loc;return{count:i.length,loc:o,files:[...r].sort()}})}function xG(e,t,n){return He(e,n,"react-component-duplicates",()=>{let i=Jo(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return wm(i)})}function RG(e,t,n){return He(e,n,"react-hook-candidates",()=>{let i=Yo(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return DR(i,UG)})}function IG(e,t,n){return He(e,n,"react-large-component-pressure",()=>{let i=Md(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return HG(i)})}function EG(e,t,n){return He(e,n,"vue-component-duplicates",()=>{let i=Xo(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return wm(i)})}function wG(e,t,n){return He(e,n,"vue-composable-candidates",()=>{let i=Qo(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return DR(i,zG)})}function LG(e,t,n){return He(e,n,"vue-large-view-pressure",()=>{let i=Pd(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Nl(i)})}function DG(e,t,n){return He(e,n,"wrapper-candidates",()=>{let i=ds(e,{scope:t,...je.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return LR(i,qG)})}function MG(e,t,n){return He(e,n,"passthrough-candidates",()=>{let i=rs(e,{scope:t,...je.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return LR(i,KG)})}function PG(e,t,n){return He(e,n,"stale-abstractions",()=>{let i=us(e,{scope:t,...je.stale,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}),r=i.filter(o=>o.consumers===0).length;return{count:i.length,loc:i.reduce((o,s)=>o+s.loc,0),files:[...new Set(i.map(o=>o.file))],unused:r,singleUse:i.length-r}})}function TG(e,t){return He(e,t,"git-evidence",()=>{let n=Xt(e,{historyMode:t.gitHistoryMode}),i=n.fileChurn();if(!i)return null;let r=n.commitHistory(),o=ts(e,void 0,{limit:t.candidateResultLimit,historyMode:t.gitHistoryMode}),s={};for(let[a,l]of i)s[a]={changes:l.changes,fixChanges:l.fixChanges};return{amplification:n.changeAmplification(),hiddenCoupling:{pairCount:o.findings.length,scoreCount:Lm(o.findings.reduce((a,l)=>a+wR(l),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:wR(a),subjectContext:a.subjectContext}))},fileStats:s,commitsScanned:r?.commits.length??0}})}function FG(e,t){return He(e,t,"suppressions",()=>{let n=wl(e);return{total:n.total,byCategory:{...n.byCategory}}})}function kG(e,t){return He(e,t,"coverage-contracts",()=>{let n=e.config.coverageContracts??[],r=pR(e,n).filter(o=>o.status!=="ok");return{count:r.length,loc:0,files:[...new Set(r.map(o=>o.file))].sort()}})}function NG(e,t,n){return He(e,n,"drift",()=>{let i=cs(e,{scope:t,...je.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY,semantic:n.semantic}),r=i.results.filter(a=>a.kind!=="pattern-deviation"),o=r.filter(a=>a.actionTier==="direct").length,s=r.length-o;return{count:r.length,unusedImports:i.unusedImports,architectureViolations:i.architectureViolations,layerViolations:i.layerViolations,direct:o,signal:s}})}function AG(e,t,n){return He(e,n,"complexity-hotspots",()=>{let i=xm(e,{scope:t,minLoc:10,limit:n.complexityResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return{top:i.rows.slice(0,5).map(r=>({symbol:r.shortName,score:r.score,file:r.file})),extremeCount:i.rows.filter(r=>r.score>sG).length,coverage:i.coverage}})}function _G(e,t){let n=e.symbols>=aG||e.documents>=lG,i=t?Number.POSITIVE_INFINITY:IR,r=t?Number.POSITIVE_INFINITY:cG;return!n||t?{candidateScanLimit:void 0,candidateResultLimit:i,complexityResultLimit:r,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:RR,candidateResultLimit:i,complexityResultLimit:r,semantic:!1,gitHistoryMode:"bounded",releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${RR} symbols and reported their top ${IR} findings. Enable full mode for unbounded candidate counts.`]}}function BG(e,t){t.releaseCachesBetweenPhases&&(bd(e),Rm())}function He(e,t,n,i){OG(n);try{return i()}finally{BG(e,t)}}function OG(e){process.env.CODEBASEIQ_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function $G(e,t){return t.filter(n=>!Qe(e,n.relativePath)&&!qe(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function jG(e,t){return t.filter(n=>!Qe(e,n.relativePath)&&!qe(e,n.symbol,n.relativePath))}function Nl(e){let t=new Set;for(let n of e){let i=n.relativePath??n.file;i&&t.add(i)}return{count:e.length,loc:e.reduce((n,i)=>n+i.loc,0),files:[...t]}}function LR(e,t){return{...Nl(e),scoreCount:Lm(e.reduce((i,r)=>i+t(r),0))}}function HG(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,i)=>n+i,0),files:[...t.keys()]}}function wm(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,i)=>n+i,0),files:[...t.keys()]}}function DR(e,t){return{...wm(e),scoreCount:Lm(e.reduce((i,r)=>i+t(r),0))}}function UG(e){let t=e.sharedHooks.length>0,n=MR({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:PR(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function zG(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=MR({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:PR(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function MR(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!FR.has(TR(t))).length+Math.min(e.functions.length,3)}function PR(e,t,n){let i=[...e,...t,...n].map(TR);return i.length>0&&i.every(r=>FR.has(r))}function TR(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function qG(e){return e.actionTier==="signal"?.25:1}function KG(e){return e.actionTier==="signal"?.25:1}function wR(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 Lm(e){return Math.round(e*100)/100}var FR=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 GG(e,t,n,i={}){let r=Ld(e,t,n,i);return r?{symbolA:r.symbolA,symbolB:r.symbolB,similarity:r.similarity,sharedCallees:r.sharedEvidence,uniqueToA:r.uniqueToA,uniqueToB:r.uniqueToB,consolidationStrategy:r.consolidationStrategy}:null}function WG(e,t,n={}){let i=jo(e,t,{families:["dataflow"],...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.maxEdges!==void 0?{maxEdges:n.maxEdges}:{}});return{kind:"value-flow",targets:i.targets,edges:i.edges,coverage:{status:i.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:i.coverage}}}var VG=/:\d+(?:-\d+)?$/u;function JG(e,t,n={}){let i=n.direction??"backward",r=n.maxDepth??3;if(!Number.isSafeInteger(r)||r<0)throw new RangeError(`Dependence-slice depth must be a non-negative safe integer; received ${r}.`);let o=VG.test(t),s=jo(e,o?{locations:[t]}:{symbols:[t]},{families:["execution","runtime","dataflow","ownership"],maxDepth:r+1,maxEdges:n.maxEdges??200}),a=new Set(s.targets.flatMap(d=>d.nodeIds)),l=new Set(a),c=new Map;kR(s.edges,l,c,0);for(let d=1;d<=r;d+=1){let m=[];for(let f of s.edges)if(i==="backward"?l.has(f.to.id):l.has(f.from.id)){let p=i==="backward"?f.from.id:f.to.id;if(l.has(p))continue;m.push(p),c.set(f.id,d)}if(m.length===0)break;for(let f of m)l.add(f);kR(s.edges,l,c,d)}let u=s.edges.filter(d=>l.has(d.from.id)&&l.has(d.to.id)).filter(d=>c.has(d.id)||d.family==="ownership").map(d=>({...d,traversalDepth:c.get(d.id)??0,supporting:d.family!=="dataflow"&&!YG(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:i,criterion:t,targets:s.targets,nodeIds:[...l].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 kR(e,t,n,i){let r=!0;for(;r;){r=!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,i),r=!0)}}function YG(e){return e.semanticFamily==="control"&&e.sourceKind==="control-dependence"}function XG(e,t={}){let{scope:n,limit:i}=t,r=new U(e),o=sW([...QG(e,n),...tW(e,r,n)]);return aW(o),i?o.slice(0,i):o}function QG(e,t){let n=[];for(let i of ZG(e,t)){if(e.isIgnored(i.barrel_path)||e.isIgnored(i.original_path)||Eu(e,i.barrel_path)||se(e,i.barrel_path)&&Ts(e,i.barrel_path).length===0)continue;let r=eW(e,i),o=r?.barrel_consumers??0,s=r?.direct_consumers??0;o!==0||s!==0||n.push({barrelFile:i.barrel_path,symbol:i.symbol,shortName:A(i.symbol),originalFile:i.original_path,barrelConsumers:o,directConsumers:s,...AR(e,i.barrel_path)})}return n}function ZG(e,t){let n=t?"AND barrel_d.relative_path LIKE ?":"",i=t?[`%${t}%`]:[];return e.all(`WITH barrel_refs AS MATERIALIZED (
460
460
  SELECT DISTINCT
461
461
  barrel_d.id AS barrel_doc_id,
462
462
  barrel_d.relative_path AS barrel_path,
@@ -499,7 +499,7 @@ describe.skipIf(inputs.length === 0)('twin-ab: ${e.shortName} vs ${t.shortName}'
499
499
  ${e.symbolNoiseFor("gs")}
500
500
  -- Only function-level symbols (ending with ().), not module-level
501
501
  AND gs.symbol LIKE '%().'
502
- ORDER BY br.barrel_path, gs.symbol`,...i)}function uW(e,t){return e.get(`SELECT
502
+ ORDER BY br.barrel_path, gs.symbol`,...i)}function eW(e,t){return e.get(`SELECT
503
503
  SUM(CASE WHEN uses_barrel = 1 THEN 1 ELSE 0 END) AS barrel_consumers,
504
504
  SUM(CASE WHEN uses_barrel = 0 THEN 1 ELSE 0 END) AS direct_consumers
505
505
  FROM (
@@ -528,18 +528,18 @@ describe.skipIf(inputs.length === 0)('twin-ab: ${e.shortName} vs ${t.shortName}'
528
528
  AND consumer_d.id != ?
529
529
  ${e.pathExclusionsFor("consumer_d")}
530
530
  GROUP BY consumer_d.id
531
- )`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function dW(e,t,n){let i=[],r=gW(e);for(let o of mW(e,n))OR(r,o,o)>0||i.push(...fW(e,t,o,r));return i}function mW(e,t){return me(e,{scope:t,includeIgnored:!1}).filter(n=>ks(e,n).length>0||Hr(e,n).length>0)}function fW(e,t,n,i){let r=ks(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>_R(e,t,n,s.sourcePath,i,[pW(s.specifier)])),o=Hr(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>_R(e,t,n,s.sourcePath,i,s.kind==="named"&&s.names.length>0?s.names:[s.kind==="star"?`* from ${s.sourcePath}`:`* namespace from ${s.sourcePath}`]));return[...r,...o]}function _R(e,t,n,i,r,o){let s=t.definitionsForFile(i);return o.map(a=>{let l=s.find(c=>c.leaf===a);return{barrelFile:n,symbol:l?.symbol??`source-reexport:${n}:${a}`,shortName:l?A(l.symbol):a,originalFile:i,barrelConsumers:0,directConsumers:OR(r,i,n),...BR(e,n)}})}function pW(e){return e.split("::").at(-1)?.split("/").at(-1)?.replace(/\.[^.]+$/,"")??e}function BR(e,t){return Pn(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 gW(e){let t=new Map;for(let n of me(e,{includeIgnored:!1}))for(let i of Ce(e,n)){if(!i.sourcePath)continue;let r=t.get(i.sourcePath)??new Set;r.add(n),t.set(i.sourcePath,r)}return t}function OR(e,t,n){let i=e.get(t);return i?i.size-(i.has(n)?1:0):0}function hW(e){let t=new Set,n=[];for(let i of e){let r=`${i.barrelFile}|${i.symbol}|${i.originalFile}`;t.has(r)||(t.add(r),n.push(i))}return n}function yW(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function bW(e,t={}){let{samples:n=50,scope:i,maxDisagreements:r=5}=t,o=new U(e),s=SW(o.productionCallableDefinitions({scope:i,minLoc:2,requireFunctionLikeSymbol:!0}),n),a=vW(e,s);if(s.length===0||!a)return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let l={references:$R(),callees:$R()},c=[],u=0,d=a==="semantic"?va(e,s):{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set},m=a==="semantic"?Ca(e,s):{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set},f=a==="source"?RW(e,o,s):null;for(let p of s){let g=_l(p,a==="semantic"?(d.rows.get(p.symbolId)??[]).map(x=>x.file):[...f?.referencesBySymbolId.get(p.symbolId)??[]]),h=_l(p,a==="semantic"?(m.rows.get(p.symbolId)??[]).map(x=>x.file):[...f?.calleesBySymbolId.get(p.symbolId)??[]]),b=a!=="semantic"||!d.incompleteSymbolIds.has(p.symbolId)&&!d.unavailableSymbolIds.has(p.symbolId),v=a!=="semantic"||!m.incompleteSymbolIds.has(p.symbolId)&&!m.unavailableSymbolIds.has(p.symbolId);b&&v&&(u+=1);let y=_l(p,Kn(e,p,{semanticEvidence:ge}).map(x=>x.file)),I=_l(p,(o.calleeMap([p],{semantic:!1}).get(p.symbolId)??[]).map(x=>x.file)),E=Fm(a,"references"),S=Fm(a,"callees");b?jR(l.references,p,"references",y,g,E,c):l.references.skippedOracleUnavailable+=1,v?jR(l.callees,p,"callees",I,h,S,c):l.callees.skippedOracleUnavailable+=1}return c.sort((p,g)=>g.cheapOnly.length+g.oracleOnly.length-(p.cheapOnly.length+p.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?Nm(u/s.length):0,oracleKind:a,scores:["references","callees"].map(p=>xW(p,l[p],a)),topDisagreements:c.slice(0,r)}}function $R(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0,skippedOraclePartial:0,skippedOracleUnavailable:0}}function SW(e,t){let n=[...e].sort((o,s)=>o.symbolId-s.symbolId);if(n.length<=t)return n;let i=n.length/t,r=[];for(let o=0;o<t;o++)r.push(n[Math.floor(o*i)]);return r}function vW(e,t){let n=t[0];if(!n)return null;if(km(e,n))return"source";try{if(Ot(e).capability("semantic-references",n.relativePath).available)return"semantic"}catch{}return t.some(i=>km(e,i))?"source":null}function _l(e,t){let n=new Set;for(let i of t)i!==e.relativePath&&n.add(i);return n}function jR(e,t,n,i,r,o,s){if(!o&&r.size===0){e.skippedOraclePartial+=1;return}e.comparedSymbols+=1,e.cheapTotal+=i.size,e.oracleTotal+=r.size;let a=[],l=[];for(let c of i)r.has(c)?e.agreed+=1:a.push(c);for(let c of r)i.has(c)||l.push(c);(a.length>0||l.length>0)&&s.push({symbol:A(t.symbol),question:n,cheapOnly:a,oracleOnly:l})}var CW={references:!0,callees:!1};function xW(e,t,n){let i=t.oracleTotal>0?t.agreed/t.oracleTotal:1,r=t.cheapTotal-t.agreed,o=Fm(n,e);return{question:e,comparedSymbols:t.comparedSymbols,precision:o&&t.cheapTotal>0?Nm(t.agreed/t.cheapTotal):null,recall:Nm(i),unverified:r,skippedOraclePartial:t.skippedOraclePartial,skippedOracleUnavailable:t.skippedOracleUnavailable}}function Fm(e,t){return e==="semantic"?CW[t]:!1}function km(e,t){return ye(t.relativePath)==="clojure"&&te(e,t.relativePath)!==null}function RW(e,t,n){let i=new Map,r=new Map,o=n.filter(l=>km(e,l)),s=new Map;for(let l of o){let c=s.get(l.leaf)??[];c.push(l),s.set(l.leaf,c)}for(let l of t.sourceFiles()){if(ye(l)!=="clojure")continue;let c=te(e,l);if(c)for(let u of c.fileIdentifiers)for(let d of s.get(u)??[])HR(i,d.symbolId,l)}let a=new Map;for(let l of t.scopedDefinitions()){if(ye(l.relativePath)!=="clojure")continue;let c=a.get(l.leaf)??[];c.push(l),a.set(l.leaf,c)}for(let l of o){let c=te(e,l.relativePath);if(c){for(let u of c.callSites)if(!(u.line<l.startLine||u.line>l.endLine))for(let d of a.get(u.calleeLeaf)??[])HR(r,l.symbolId,d.relativePath)}}return{referencesBySymbolId:i,calleesBySymbolId:r}}function HR(e,t,n){let i=e.get(t);if(i){i.add(n);return}e.set(t,new Set([n]))}function Nm(e){return Math.round(e*1e3)/1e3}var IW=new Set(on());function EW(e,t={}){let{scope:n,minLoc:i=1,limit:r,scanLimit:o,maxShapeFrequency:s=12}=t,a=t.semantic!==!1,l=DW(e,wW(e,{scope:n,minLoc:i,scanLimit:o}),{semantic:a,maxShapeFrequency:s}),c=PW(l);return r?c.slice(0,r):c}function wW(e,t){let n=Ue(e,{scope:t.scope}).filter(i=>LW(i)&&!e.isIgnored(i.relativePath)).filter(i=>de(i)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((i,r)=>de(r)-de(i)||i.relativePath.localeCompare(r.relativePath)),ke(n,t.scanLimit)}function LW(e){return!e.isFunctionLike||Xe(e.symbol)?!1:e.kind===null||IW.has(e.kind)}function DW(e,t,n){let i=[];for(let s of t){let a=FW(e,s,n);a&&i.push({signature:a,definition:s,fn:MW(s)})}let r=new Map;for(let s of i)r.set(s.signature,(r.get(s.signature)??0)+1);let o=new Map;for(let s of i){let a=TW(s.fn.loc),l=(r.get(s.signature)??0)>n.maxShapeFrequency,c=l?dm(e,s.definition):null;if(l&&!c)continue;let u=l?`${s.signature}\0body\0${c}`:`${s.signature}\0band\0${a}`,d=o.get(u)??{signature:s.signature,locBand:a,exactBody:l,functions:[]};d.functions.push(s.fn),o.set(u,d)}return[...o.values()]}function MW(e){return{symbol:e.symbol,shortName:A(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:de(e)}}function PW(e){let t=[];for(let n of e)n.functions.length>=2&&t.push(n);return t.sort((n,i)=>{let r=i.functions.length-n.functions.length;if(r!==0)return r;let o=n.functions.reduce((a,l)=>a+l.loc,0);return i.functions.reduce((a,l)=>a+l.loc,0)-o}),t}function TW(e){return e<=5?"<=5":e<=20?"6-20":">20"}function FW(e,t,n){if(n.semantic){let o=Eh(e,t);if(o)return o}let i=kW(t.documentation),r=i?_W(i):null;return r||BW(NW(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function kW(e){return er(tr(e))}function NW(e,t,n,i,r){let o=se(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=$W(s,n,i,r);for(let l of a){let c=Math.min(s.length-1,Math.max(l,l+4)),u="";for(let d=l;d<=c;d+=1){let m=s[d]?.trim();if(m&&(u=u?`${u} ${m}`:m,AW(u)))return u}if(u&&u.includes("("))return u}return null}function AW(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||If(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function _W(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 BW(e,t){if(!e||!e.trim())return null;let n=e.replace(/\s+/g," ").trim(),i=n.indexOf("(");if(i===-1)return null;let r=n.slice(0,i),s=new RegExp(`\\b${Oe(t)}\\b`,"i").exec(r);s&&typeof s.index=="number"&&(r=r.slice(0,s.index)),r=r.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=OW(n.slice(i)).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 l=`${r?`${r} `:""}${a}`.replace(/\s+/g,"").toLowerCase();return l.length>=3?l:null}function OW(e){let t=0,n=0,i=0,r=0,o=null,s=!1;for(let a=0;a<e.length;a+=1){let l=e[a];if(o){if(s){s=!1;continue}if(l==="\\"){s=!0;continue}l===o&&(o=null);continue}if(l==='"'||l==="'"||l==="`"){o=l;continue}if(l==="(")t+=1;else if(l===")")t=Math.max(0,t-1);else if(l==="[")i+=1;else if(l==="]")i=Math.max(0,i-1);else if(l==="<")r+=1;else if(l===">")r=Math.max(0,r-1);else if(l==="{"){if(t===0&&i===0&&r===0)return e.slice(0,a);n+=1}else if(l==="}")n=Math.max(0,n-1);else if(l==="="&&e[a+1]===">"&&t===0&&n===0&&i===0&&r===0)return e.slice(0,a)}return e}function $W(e,t,n,i){let r=Oe(i),o=new RegExp(`\\b${r}\\b\\s*\\(`,"i"),s=new RegExp(`\\bdef\\s+${r}\\b`,"i"),a=[],l=new Set,c=Math.max(0,Math.min(t,e.length-1)),u=Math.max(c,Math.min(e.length-1,Math.max(n,t+4)));for(let d=c;d<=u;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!l.has(d)&&(l.add(d),a.push(d))}for(let d=0;d<e.length;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!l.has(d)&&(l.add(d),a.push(d))}return a}import{availableParallelism as c2}from"os";import{fileURLToPath as zm}from"url";import{spawnSync as Fce}from"child_process";import{execFileSync as nce}from"child_process";import{createHash as rce}from"crypto";import{lstatSync as sce,readlinkSync as ace,readdirSync as lce,realpathSync as cce,statSync as uce}from"fs";import{dirname as mce,isAbsolute as fce,join as pce,posix as gce,relative as hce,resolve as yce,sep as bce}from"path";var vce=512*1024*1024;function UR(e){return bi({version:e.version,...e.base?{base:e.base}:{},files:[...e.files].sort((t,n)=>t.path.localeCompare(n.path))})}function Am(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 HW="codebaseiq:collaboration-domain",UW="codebaseiq:workspace-instance",zW="codebaseiq:index-generation",qW="codebaseiq:repository-content",zR="codebaseiq:index-inputs",KW="codebaseiq:index-inputs";function zi(e){let t=e.snapshot,n=e.observedSourceKinds?new Set(e.observedSourceKinds):void 0,i=e.gitContext??t?.gitContext??(n?.has("live-workspace")?Gl(e.projectRoot):void 0),r=e.collaborationDomainId??e.db?.config.collaborationDomainId,o=r?yi(HW,1,r):void 0,s=i?yi(UW,1,i.worktreeId):void 0,a=t?yi(qW,1,UR(t.repositoryContent)):void 0,l=t?yi(zR,t.indexInputs.version,Am(t.indexInputs)):void 0,c=e.db&&t?WW(e.db.generation.metadataRaw):void 0,u=e.db?{generation:yi(zW,1,e.db.generation.identity),...c?{inputs:c}:{},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"}]:[]],f=[...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"}),f.push({source:"process",kind:"not-established"})),{schemaVersion:lf,observedAt:(e.observedAt??(t?new Date(t.capturedAt):new Date)).toISOString(),facts:{...o?{collaborationDomain:o}:{},...s?{workspaceInstance:s}:{},...a?{wholeContent:a}:{},...l?{relevantInputs:[{subject:KW,identity:l}]}:{},...u?{index:u}:{}},observedSources:m,stabilityProofs:f,...i?{diagnostics:{clean:i.clean,...i.headCommit?{headCommit:i.headCommit}:{},...i.treeOid?{treeOid:i.treeOid}:{}}}:{}}}function GW(e){return zi({projectRoot:e.projectRoot,db:e.db,...e.gitContext?{gitContext:e.gitContext}:{},...e.observedAt?{observedAt:e.observedAt}:{},observedSourceKinds:["index-generation"]})}function Mce(){let e=ws();if(!e)return zi({projectRoot:hf(),observedSourceKinds:["process"]});let t=e.config.projectRoot,n=Gl(t);return GW({projectRoot:t,db:e,...n?{gitContext:n}:{}})}function WW(e){if(!e)return;let t=vs(e);if(t.kind!=="legacy"&&t.kind!=="supported")return;let n=sf(t.metadata.fingerprint);return n&&Number.isSafeInteger(n.version)&&n.version>0?yi(zR,n.version,Am(n)):void 0}var Bm="codebaseiq-isolated-analysis",Om=1;function VW(e){let t=[...e??[]];return t.includes("--json")?t:["--json",...t]}var Ar=class extends Error{constructor(n,i,r=!0){super(`${n} timed out after ${i}ms.`);this.label=n;this.timeoutMs=i;this.reaped=r;this.name="IsolatedProcessTimeoutError"}label;timeoutMs;reaped;timedOut=!0};function jce(e,t){let n=ws(),i={protocol:Bm,schemaVersion:Om,producer:{name:"codebaseiq",version:hi},command:e,result:t,...n?{observationReceipt:zi({projectRoot:n.config.projectRoot,db:n,observedSourceKinds:["index-generation"]})}:{}};ec(JSON.stringify(i))}function qR(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}function Bl(e){let t=e.timeoutMs??ip.analysis,n=e.maxBuffer??10*1024*1024;return op({command:process.execPath,args:[...process.execArgv,e.cliPath,e.command,...VW(e.args)],cwd:process.cwd(),env:e.env??process.env,label:e.label,timeoutMs:t,maxStdoutBytes:n,maxStderrBytes:n,signal:e.signal}).catch(i=>{throw i instanceof rp&&i.kind==="timeout"?new Ar(e.label,t,i.reaped):i}).then(i=>{let r=i.stderr.trim();if(i.status!==0)throw new Error(`${e.label} failed${r?`:
532
- ${r}`:""}`);return JW(i.stdout,e)})}function JW(e,t){let n;try{n=JSON.parse(e)}catch(r){throw new Error(`${t.label} returned invalid JSON: ${r instanceof Error?r.message:r}`,{cause:r})}if(!jn(n))throw new Error(`${t.label} returned a non-object isolated-analysis message.`);if(n.protocol!==Bm)throw new Error(`${t.label} returned protocol ${_m(n.protocol)}; expected ${Bm}.`);if(n.schemaVersion!==Om)throw new Error(`${t.label} returned unsupported isolated-analysis schemaVersion ${_m(n.schemaVersion)}; expected ${Om}.`);if(!YW(n.producer))throw new Error(`${t.label} did not identify a codebaseiq producer version.`);if(n.command!==t.command)throw new Error(`${t.label} returned result for command ${_m(n.command)}; expected ${t.command}.`);if(!Object.hasOwn(n,"result"))throw new Error(`${t.label} omitted the isolated-analysis result.`);let i=n.observationReceipt;if(i!==void 0&&(!cf(i)||i.schemaVersion!==2))throw new Error(`${t.label} returned an invalid observation receipt.`);return{result:n.result,...i?{observationReceipt:i}:{}}}function YW(e){return jn(e)&&e.name==="codebaseiq"&&typeof e.version=="string"&&e.version.length>0}function _m(e){return typeof e=="string"?JSON.stringify(e):String(e)}async function $m(e,t,n){let i=new Array(e.length),r=new AbortController,o=0,s,a=!1;async function l(){for(;!r.signal.aborted&&o<e.length;){let c=o++;try{i[c]=await n(e[c],r.signal)}catch(u){throw a||(a=!0,s=u,r.abort(u)),u}}}if(await Promise.allSettled(Array.from({length:Math.min(t,e.length)},()=>l())),a)throw s;return i}function KR(e,t){let n=new Set,i=[];for(let r of e){if(n.has(r))continue;let o=t.find(a=>a.has(r));if(!o){n.add(r),i.push([r]);continue}let s=e.filter(a=>o.has(a));s.forEach(a=>n.add(a)),i.push(s)}return i}import{spawnSync as XW}from"child_process";import{existsSync as QW,mkdirSync as ZW,renameSync as e2,writeFileSync as t2}from"fs";import{dirname as WR,join as n2}from"path";var Ol=6,i2="health-report-cache.json";function jm(e,t,n,i=l2()){let r=Cn(e);return r?{version:Ol,projectFingerprint:r,cliVersion:n,scope:t.scope??null,full:t.full===!0,phaseTimeoutMs:t.phaseTimeoutMs??null,gitHead:i.gitHead(e.config.projectRoot)}:null}function VR(e,t,n=QR()){let i=YR(e),r=XR(t),o=!1;return B("health.report-cache.read",()=>{if(!n.existsSync(i))return null;try{let s=JSON.parse(n.readFile(i));return!r2(s)||s.keyHash!==r?null:(o=!0,s.report)}catch{return null}},()=>({available:!0,hit:o,keyHash:r}))}function JR(e,t,n,i=QR()){let r=YR(e),o={version:Ol,keyHash:XR(t),key:t,writtenAt:i.nowIso(),report:n};i.mkdirSync(WR(r),{recursive:!0});let s=`${r}.${process.pid}.${Date.now()}.tmp`;i.writeFileSync(s,JSON.stringify(o)),i.renameSync(s,r)}function YR(e){return n2(WR(e.config.dbPath),i2)}function XR(e){return zt(JSON.stringify(e))}function r2(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===Ol&&typeof t.keyHash=="string"&&o2(t.key)&&typeof t.writtenAt=="string"&&s2(t.report)}function o2(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===Ol&&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 s2(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)&&a2(t.coverage)}function a2(e){if(!e||typeof e!="object")return!1;let t=e;if(t.status!=="complete"&&t.status!=="incomplete"&&t.status!=="semantic-disabled")return!1;let n=t.complexity?.semanticEvidence;return GR(n)&&typeof n.excludedSymbolCount=="number"&&Array.isArray(t.phases)&&t.phases.every(i=>!!i&&typeof i=="object"&&typeof i.phase=="string"&&GR(i.semanticEvidence))}function GR(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.enabled=="boolean"&&(t.status==="complete"||t.status==="incomplete"||t.status==="unavailable"||t.status==="incomplete-and-unavailable"||t.status==="disabled")&&typeof t.incompleteSymbolCount=="number"&&typeof t.unavailableSymbolCount=="number"}function l2(){return{gitHead(e){let t=XW("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",timeout:3e4,killSignal:"SIGKILL",windowsHide:!0});return t.status===0?t.stdout.trim():null}}}function QR(){return{existsSync:QW,mkdirSync:ZW,readFile:e=>gi(e,"health report cache"),renameSync:e2,writeFileSync:t2,nowIso:()=>new Date().toISOString()}}var tI="__health-phase",u2="__diff-impact-batch",d2=10,m2=4,f2=8,p2=25e3,g2=2500,Hm=2500,h2=4,y2=12,ZR=3e4,nI=new Set(["react-component-duplicates","react-hook-candidates","react-large-component-pressure"]),iI=new Set(["vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure"]),b2=new Set([...iI,"suppressions"]),S2=new Set(["similar","extract-candidates"]),jl=3,eI=$r({kind:"health-semantic-prewarm",invalidation:Ye("health-semantic-prewarm"),serialize:e=>JSON.stringify(e),deserialize:v2});function v2(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return n.version!==jl||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:jl,definitions:n.definitions,referenceCacheWrites:n.referenceCacheWrites,referenceIncomplete:n.referenceIncomplete,calleeRows:n.calleeRows,warmedAt:n.warmedAt}}catch{return null}}function mue(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
533
- `)}function C2(e){let t=Li(e);return t.symbols>=p2||t.documents>=g2}function fue(e,t,n,i={}){if(!C2(e))return{semantic:!0};if(n)return i.quiet||console.error(`Large index detected; ${t} is running the unbounded semantic pass because --full was supplied.`),{semantic:!0};if(!i.quiet){let r=t==="inspect"?"Use --full only when every omitted semantic candidate can change the decision; it does not override source or behavior materialization ceilings.":`Run "codebaseiq ${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 ${Hm}. `+r)}return{scanLimit:Hm,semantic:!1,analysisBudget:{scanLimit:Hm,semanticEnrichment:!1,reason:"large index default budget; pass --full for unbounded semantic analysis"}}}var x2={env:process.env,projectFingerprint:Cn,semanticEngineFingerprint:w2,readMarker:(e,t,n)=>eI.read(e,t,n),writeMarker:(e,t,n,i)=>eI.write(e,t,n,i),candidateDefinitions:(e,t)=>new U(e).scopedDefinitions(t.scope).filter(n=>Ge(n.relativePath)!==null),materializeReferences:(e,t,n)=>Ot(e).materializeReferences(t,n),materializeCallees:hu};function R2(e,t,n=x2){if(t.full!==!0)return mi("default-mode");if((n.env??process.env).CODEBASEIQ_HEALTH_SEMANTIC_PREWARM==="0")return mi("disabled");let i=mi("error");return B("health.semantic-prewarm",()=>{try{i=I2(e,t,n)}catch(r){i=mi("error",{error:r instanceof Error?r.message:String(r)})}return i},()=>L2(i))}function I2(e,t,n){let i=n.projectFingerprint(e);if(!i)return mi("missing-project-fingerprint");let r=E2(t,n.semanticEngineFingerprint(e)),o=n.readMarker(e,r,i);if(o&&o.referenceIncomplete===0)return mi("cache-hit");let s=[];if(s=B("health.semantic-prewarm.candidate-definitions",()=>(s=n.candidateDefinitions(e,t),s),()=>({definitions:s.length})),s.length===0)return mi("no-semantic-definitions");let a=0,l=B("health.semantic-prewarm.references",()=>{let m=n.materializeReferences(e,s,{prefetchCallees:!0});return a=m.cacheHits+m.cacheWrites+m.inMemoryHits,m},()=>({definitions:s.length,rows:a}));if(l.cacheHits+l.cacheWrites+l.inMemoryHits===0&&l.misses+l.unkeyed>0)return mi("provider-unavailable",{definitions:s.length,referenceMisses:l.misses});let u=0,d=B("health.semantic-prewarm.callees",()=>{let m=n.materializeCallees(e,s);return u=m.size,m},()=>({definitions:s.length,rows:u}));return l.incomplete>0?{status:"partial",reason:"incomplete-references",definitions:s.length,referenceCacheHits:l.cacheHits,referenceCacheWrites:l.cacheWrites,referenceMisses:l.misses,referenceIncomplete:l.incomplete,calleeRows:d.size}:(B("health.semantic-prewarm.marker-write",()=>n.writeMarker(e,r,i,{version:jl,definitions:s.length,referenceCacheWrites:l.cacheWrites,referenceIncomplete:l.incomplete,calleeRows:d.size,warmedAt:Date.now()})),{status:"warmed",reason:"cache-miss",definitions:s.length,referenceCacheHits:l.cacheHits,referenceCacheWrites:l.cacheWrites,referenceMisses:l.misses,referenceIncomplete:l.incomplete,calleeRows:d.size})}function E2(e,t){return JSON.stringify({version:jl,cliVersion:hi,semanticEngineFingerprint:t,scope:e.scope??null})}function w2(e){return zt(JSON.stringify({kind:"health-semantic-prewarm-engine",rust:Ri(e.config.projectRoot)}))}function mi(e,t={}){return{status:"skipped",reason:e,definitions:0,referenceCacheHits:0,referenceCacheWrites:0,referenceMisses:0,referenceIncomplete:0,calleeRows:0,...t}}function L2(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 $l(e){return Zl(t=>{let n=zi({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 Hl(e,t,n){let i=e[0];if(!i)throw new Error("An evidence-bound analysis requires at least one index observation anchor.");let r=i.generationDigest,o=e.every(a=>a.generationDigest===r),s=t.every(a=>a?.facts.index?.generation.digest===r);return zi({projectRoot:i.database.config.projectRoot,...o&&s?{db:i.database}:{},observedSourceKinds:n})}async function pue(e){return(await D2(e)).result}async function D2(e){let t=N2(e),n={...e,phaseTimeoutMs:t??null},i=$l(g=>{let h=jm(g,n,hi);if(!h)return null;let b=VR(g,h);return b||null});if(i.value)return{result:i.value,observationReceipt:Hl([i.anchor],[],["index-generation","live-workspace"])};let r=$l(g=>({applicability:M2(g,e),overview:Dm(g,"overview",e)})),{applicability:o,overview:s}=r.value,a=[i.anchor,r.anchor],l=new Map;l.set("overview",s);let c=Nl.filter(g=>g==="overview"?!1:P2(g,o)?!0:(l.set(g,qi(g)),!1)),u=T2(c);if(e.full){let g=$l(h=>R2(h,e));a.push(g.anchor)}let d=await $m(u,A2(u.length),(g,h)=>F2(g,e,t,h)),m=d.flatMap(g=>g.result),f=[];if(m.forEach(g=>{g.healthPhaseMeta&&f.push(`Health phase "${g.phase}" deferred: ${g.healthPhaseMeta.reason}. Run health --full for exhaustive analysis.`),l.set(g.phase,g)}),f.length>0){let g=l.get("overview");l.set("overview",{...g,warnings:[...g.warnings,...f]})}let p=Mm(Nl.map(g=>l.get(g)));return Zl(g=>{let h=jm(g,n,hi);h&&JR(g,h,p)}),{result:p,observationReceipt:Hl(a,d.map(g=>g.observationReceipt),["index-generation","live-workspace"])}}function M2(e,t){return Fs(e,{scope:t.scope})}function P2(e,t){return nI.has(e)?t.react:iI.has(e)?t.vue:!0}function T2(e){return KR(e,[nI,b2,S2])}function qi(e){let t={enabled:!0,status:"complete",incompleteSymbolCount:0,unavailableSymbolCount:0};switch(e){case"react-component-duplicates":return{phase:e,reactComponentDuplicates:{count:0,loc:0,files:[]},evidenceCoverage:t};case"react-hook-candidates":return{phase:e,reactHookCandidates:{count:0,loc:0,files:[]},evidenceCoverage:t};case"react-large-component-pressure":return{phase:e,reactLargeComponentPressure:{count:0,loc:0,files:[]},evidenceCoverage:t};case"vue-component-duplicates":return{phase:e,vueComponentDuplicates:{count:0,loc:0,files:[]},evidenceCoverage:t};case"vue-composable-candidates":return{phase:e,vueComposableCandidates:{count:0,loc:0,files:[]},evidenceCoverage:t};case"vue-large-view-pressure":return{phase:e,vueLargeViewPressure:{count:0,loc:0,files:[]},evidenceCoverage:t};default:throw new Error(`Health phase "${e}" cannot be synthesized.`)}}function F2(e,t,n,i){if(e.length===1)return k2(e[0],t,n,i).then(a=>({result:[a.result],...a.observationReceipt?{observationReceipt:a.observationReceipt}:{}}));let r=e.join(","),o=process.argv[1]??zm(import.meta.url),s=[r];return t.scope&&s.push("--scope",t.scope),t.full&&s.push("--full"),Bl({cliPath:o,command:tI,args:s,label:`Health phases "${r}"`,timeoutMs:n,signal:i}).catch(a=>{if(t.full||!(a instanceof Ar))throw a;return{result:e.map(l=>rI(l,a.timeoutMs,`timed out after ${a.timeoutMs}ms`))}})}function k2(e,t,n,i){let r=process.argv[1]??zm(import.meta.url),o=[e];return t.scope&&o.push("--scope",t.scope),t.full&&o.push("--full"),Bl({cliPath:r,command:tI,args:o,label:`Health phase "${e}"`,timeoutMs:n,signal:i}).catch(s=>{if(t.full||!(s instanceof Ar))throw s;return{result:rI(e,s.timeoutMs,`timed out after ${s.timeoutMs}ms`)}})}function N2(e,t=process.env){if(e.full)return;let n=t.CODEBASEIQ_HEALTH_PHASE_TIMEOUT_MS;if(!n)return ZR;let i=parseInt(n,10);return!Number.isFinite(i)||i<0?ZR:i===0?void 0:i}function rI(e,t,n){let i={evidenceCoverage:{enabled:!0,status:"unavailable",incompleteSymbolCount:0,unavailableSymbolCount:0},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:[]},...i};case"isolated":return{phase:e,isolated:{count:0,loc:0,files:[]},...i};case"cycles":return{phase:e,realCycleCount:0,...i};case"similar":return{phase:e,similarCount:0,...i};case"duplicate-bodies":return{phase:e,duplicateBodies:{count:0,loc:0,files:[]},...i};case"twin-drift":return{phase:e,twinDrift:{count:0,loc:0,files:[]},...i};case"react-component-duplicates":return{...qi(e),...i};case"react-hook-candidates":return{...qi(e),...i};case"react-large-component-pressure":return{...qi(e),...i};case"vue-component-duplicates":return{...qi(e),...i};case"vue-composable-candidates":return{...qi(e),...i};case"vue-large-view-pressure":return{...qi(e),...i};case"extract-candidates":return{phase:e,extractCount:0,...i};case"wrapper-candidates":return{phase:e,wrappers:{count:0,loc:0,files:[]},...i};case"passthrough-candidates":return{phase:e,passthroughs:{count:0,loc:0,files:[]},...i};case"stale-abstractions":return{phase:e,stale:{count:0,loc:0,files:[],unused:0,singleUse:0},...i};case"drift":return{phase:e,drift:{count:0,unusedImports:0,architectureViolations:0,layerViolations:0,direct:0,signal:0},...i};case"complexity-hotspots":return{phase:e,complexity:{top:[],extremeCount:0,coverage:{semanticEvidence:{enabled:!0,status:"unavailable",incompleteSymbolCount:0,unavailableSymbolCount:0,excludedSymbolCount:0}}},...i};case"git-evidence":return{phase:e,gitEvidence:null,...i};case"suppressions":return{phase:e,suppressions:{total:0,byCategory:{}},...i};case"coverage-contracts":return{phase:e,coverageContracts:{count:0,loc:0,files:[]},...i}}}var A2=oI({envKey:"CODEBASEIQ_HEALTH_CONCURRENCY",defaultMinimum:h2,defaultMaximum:y2});function gue(e){if(console.log(`
531
+ )`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function tW(e,t,n){let i=[],r=oW(e);for(let o of nW(e,n))_R(r,o,o)>0||i.push(...iW(e,t,o,r));return i}function nW(e,t){return me(e,{scope:t,includeIgnored:!1}).filter(n=>Ts(e,n).length>0||$r(e,n).length>0)}function iW(e,t,n,i){let r=Ts(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>NR(e,t,n,s.sourcePath,i,[rW(s.specifier)])),o=$r(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>NR(e,t,n,s.sourcePath,i,s.kind==="named"&&s.names.length>0?s.names:[s.kind==="star"?`* from ${s.sourcePath}`:`* namespace from ${s.sourcePath}`]));return[...r,...o]}function NR(e,t,n,i,r,o){let s=t.definitionsForFile(i);return o.map(a=>{let l=s.find(c=>c.leaf===a);return{barrelFile:n,symbol:l?.symbol??`source-reexport:${n}:${a}`,shortName:l?A(l.symbol):a,originalFile:i,barrelConsumers:0,directConsumers:_R(r,i,n),...AR(e,n)}})}function rW(e){return e.split("::").at(-1)?.split("/").at(-1)?.replace(/\.[^.]+$/,"")??e}function AR(e,t){return Pn(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 oW(e){let t=new Map;for(let n of me(e,{includeIgnored:!1}))for(let i of Ce(e,n)){if(!i.sourcePath)continue;let r=t.get(i.sourcePath)??new Set;r.add(n),t.set(i.sourcePath,r)}return t}function _R(e,t,n){let i=e.get(t);return i?i.size-(i.has(n)?1:0):0}function sW(e){let t=new Set,n=[];for(let i of e){let r=`${i.barrelFile}|${i.symbol}|${i.originalFile}`;t.has(r)||(t.add(r),n.push(i))}return n}function aW(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function lW(e,t={}){let{samples:n=50,scope:i,maxDisagreements:r=5}=t,o=new U(e),s=cW(o.productionCallableDefinitions({scope:i,minLoc:2,requireFunctionLikeSymbol:!0}),n),a=uW(e,s);if(s.length===0||!a)return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let l={references:BR(),callees:BR()},c=[],u=0,d=a==="semantic"?Sa(e,s):{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set},m=a==="semantic"?va(e,s):{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set},f=a==="source"?fW(e,o,s):null;for(let p of s){let g=Al(p,a==="semantic"?(d.rows.get(p.symbolId)??[]).map(x=>x.file):[...f?.referencesBySymbolId.get(p.symbolId)??[]]),h=Al(p,a==="semantic"?(m.rows.get(p.symbolId)??[]).map(x=>x.file):[...f?.calleesBySymbolId.get(p.symbolId)??[]]),b=a!=="semantic"||!d.incompleteSymbolIds.has(p.symbolId)&&!d.unavailableSymbolIds.has(p.symbolId),v=a!=="semantic"||!m.incompleteSymbolIds.has(p.symbolId)&&!m.unavailableSymbolIds.has(p.symbolId);b&&v&&(u+=1);let y=Al(p,Kn(e,p,{semanticEvidence:ge}).map(x=>x.file)),I=Al(p,(o.calleeMap([p],{semantic:!1}).get(p.symbolId)??[]).map(x=>x.file)),E=Dm(a,"references"),S=Dm(a,"callees");b?OR(l.references,p,"references",y,g,E,c):l.references.skippedOracleUnavailable+=1,v?OR(l.callees,p,"callees",I,h,S,c):l.callees.skippedOracleUnavailable+=1}return c.sort((p,g)=>g.cheapOnly.length+g.oracleOnly.length-(p.cheapOnly.length+p.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?Pm(u/s.length):0,oracleKind:a,scores:["references","callees"].map(p=>mW(p,l[p],a)),topDisagreements:c.slice(0,r)}}function BR(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0,skippedOraclePartial:0,skippedOracleUnavailable:0}}function cW(e,t){let n=[...e].sort((o,s)=>o.symbolId-s.symbolId);if(n.length<=t)return n;let i=n.length/t,r=[];for(let o=0;o<t;o++)r.push(n[Math.floor(o*i)]);return r}function uW(e,t){let n=t[0];if(!n)return null;if(Mm(e,n))return"source";try{if(Ot(e).capability("semantic-references",n.relativePath).available)return"semantic"}catch{}return t.some(i=>Mm(e,i))?"source":null}function Al(e,t){let n=new Set;for(let i of t)i!==e.relativePath&&n.add(i);return n}function OR(e,t,n,i,r,o,s){if(!o&&r.size===0){e.skippedOraclePartial+=1;return}e.comparedSymbols+=1,e.cheapTotal+=i.size,e.oracleTotal+=r.size;let a=[],l=[];for(let c of i)r.has(c)?e.agreed+=1:a.push(c);for(let c of r)i.has(c)||l.push(c);(a.length>0||l.length>0)&&s.push({symbol:A(t.symbol),question:n,cheapOnly:a,oracleOnly:l})}var dW={references:!0,callees:!1};function mW(e,t,n){let i=t.oracleTotal>0?t.agreed/t.oracleTotal:1,r=t.cheapTotal-t.agreed,o=Dm(n,e);return{question:e,comparedSymbols:t.comparedSymbols,precision:o&&t.cheapTotal>0?Pm(t.agreed/t.cheapTotal):null,recall:Pm(i),unverified:r,skippedOraclePartial:t.skippedOraclePartial,skippedOracleUnavailable:t.skippedOracleUnavailable}}function Dm(e,t){return e==="semantic"?dW[t]:!1}function Mm(e,t){return ye(t.relativePath)==="clojure"&&te(e,t.relativePath)!==null}function fW(e,t,n){let i=new Map,r=new Map,o=n.filter(l=>Mm(e,l)),s=new Map;for(let l of o){let c=s.get(l.leaf)??[];c.push(l),s.set(l.leaf,c)}for(let l of t.sourceFiles()){if(ye(l)!=="clojure")continue;let c=te(e,l);if(c)for(let u of c.fileIdentifiers)for(let d of s.get(u)??[])$R(i,d.symbolId,l)}let a=new Map;for(let l of t.scopedDefinitions()){if(ye(l.relativePath)!=="clojure")continue;let c=a.get(l.leaf)??[];c.push(l),a.set(l.leaf,c)}for(let l of o){let c=te(e,l.relativePath);if(c){for(let u of c.callSites)if(!(u.line<l.startLine||u.line>l.endLine))for(let d of a.get(u.calleeLeaf)??[])$R(r,l.symbolId,d.relativePath)}}return{referencesBySymbolId:i,calleesBySymbolId:r}}function $R(e,t,n){let i=e.get(t);if(i){i.add(n);return}e.set(t,new Set([n]))}function Pm(e){return Math.round(e*1e3)/1e3}var pW=new Set(on());function gW(e,t={}){let{scope:n,minLoc:i=1,limit:r,scanLimit:o,maxShapeFrequency:s=12}=t,a=t.semantic!==!1,l=bW(e,hW(e,{scope:n,minLoc:i,scanLimit:o}),{semantic:a,maxShapeFrequency:s}),c=vW(l);return r?c.slice(0,r):c}function hW(e,t){let n=Ue(e,{scope:t.scope}).filter(i=>yW(i)&&!e.isIgnored(i.relativePath)).filter(i=>de(i)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((i,r)=>de(r)-de(i)||i.relativePath.localeCompare(r.relativePath)),ke(n,t.scanLimit)}function yW(e){return!e.isFunctionLike||Xe(e.symbol)?!1:e.kind===null||pW.has(e.kind)}function bW(e,t,n){let i=[];for(let s of t){let a=xW(e,s,n);a&&i.push({signature:a,definition:s,fn:SW(s)})}let r=new Map;for(let s of i)r.set(s.signature,(r.get(s.signature)??0)+1);let o=new Map;for(let s of i){let a=CW(s.fn.loc),l=(r.get(s.signature)??0)>n.maxShapeFrequency,c=l?am(e,s.definition):null;if(l&&!c)continue;let u=l?`${s.signature}\0body\0${c}`:`${s.signature}\0band\0${a}`,d=o.get(u)??{signature:s.signature,locBand:a,exactBody:l,functions:[]};d.functions.push(s.fn),o.set(u,d)}return[...o.values()]}function SW(e){return{symbol:e.symbol,shortName:A(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:de(e)}}function vW(e){let t=[];for(let n of e)n.functions.length>=2&&t.push(n);return t.sort((n,i)=>{let r=i.functions.length-n.functions.length;if(r!==0)return r;let o=n.functions.reduce((a,l)=>a+l.loc,0);return i.functions.reduce((a,l)=>a+l.loc,0)-o}),t}function CW(e){return e<=5?"<=5":e<=20?"6-20":">20"}function xW(e,t,n){if(n.semantic){let o=Rh(e,t);if(o)return o}let i=RW(t.documentation),r=i?wW(i):null;return r||LW(IW(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function RW(e){return Qi(Zi(e))}function IW(e,t,n,i,r){let o=se(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=MW(s,n,i,r);for(let l of a){let c=Math.min(s.length-1,Math.max(l,l+4)),u="";for(let d=l;d<=c;d+=1){let m=s[d]?.trim();if(m&&(u=u?`${u} ${m}`:m,EW(u)))return u}if(u&&u.includes("("))return u}return null}function EW(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||vf(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function wW(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 LW(e,t){if(!e||!e.trim())return null;let n=e.replace(/\s+/g," ").trim(),i=n.indexOf("(");if(i===-1)return null;let r=n.slice(0,i),s=new RegExp(`\\b${Oe(t)}\\b`,"i").exec(r);s&&typeof s.index=="number"&&(r=r.slice(0,s.index)),r=r.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=DW(n.slice(i)).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 l=`${r?`${r} `:""}${a}`.replace(/\s+/g,"").toLowerCase();return l.length>=3?l:null}function DW(e){let t=0,n=0,i=0,r=0,o=null,s=!1;for(let a=0;a<e.length;a+=1){let l=e[a];if(o){if(s){s=!1;continue}if(l==="\\"){s=!0;continue}l===o&&(o=null);continue}if(l==='"'||l==="'"||l==="`"){o=l;continue}if(l==="(")t+=1;else if(l===")")t=Math.max(0,t-1);else if(l==="[")i+=1;else if(l==="]")i=Math.max(0,i-1);else if(l==="<")r+=1;else if(l===">")r=Math.max(0,r-1);else if(l==="{"){if(t===0&&i===0&&r===0)return e.slice(0,a);n+=1}else if(l==="}")n=Math.max(0,n-1);else if(l==="="&&e[a+1]===">"&&t===0&&n===0&&i===0&&r===0)return e.slice(0,a)}return e}function MW(e,t,n,i){let r=Oe(i),o=new RegExp(`\\b${r}\\b\\s*\\(`,"i"),s=new RegExp(`\\bdef\\s+${r}\\b`,"i"),a=[],l=new Set,c=Math.max(0,Math.min(t,e.length-1)),u=Math.max(c,Math.min(e.length-1,Math.max(n,t+4)));for(let d=c;d<=u;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!l.has(d)&&(l.add(d),a.push(d))}for(let d=0;d<e.length;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!l.has(d)&&(l.add(d),a.push(d))}return a}import{availableParallelism as ZW}from"os";import{fileURLToPath as $m}from"url";import{spawnSync as fce}from"child_process";import{execFileSync as Ble}from"child_process";import{createHash as $le}from"crypto";import{lstatSync as Hle,readlinkSync as Ule,readdirSync as zle,realpathSync as qle,statSync as Kle}from"fs";import{dirname as Wle,isAbsolute as Vle,join as Jle,posix as Yle,relative as Xle,resolve as Qle,sep as Zle}from"path";var tce=512*1024*1024;function jR(e){return bi({version:e.version,...e.base?{base:e.base}:{},files:[...e.files].sort((t,n)=>t.path.localeCompare(n.path))})}function Tm(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 TW="codebaseiq:collaboration-domain",FW="codebaseiq:workspace-instance",kW="codebaseiq:index-generation",NW="codebaseiq:repository-content",HR="codebaseiq:index-inputs",AW="codebaseiq:index-inputs";function zi(e){let t=e.snapshot,n=e.observedSourceKinds?new Set(e.observedSourceKinds):void 0,i=e.gitContext??t?.gitContext??(n?.has("live-workspace")?Kl(e.projectRoot):void 0),r=e.collaborationDomainId??e.db?.config.collaborationDomainId,o=r?yi(TW,1,r):void 0,s=i?yi(FW,1,i.worktreeId):void 0,a=t?yi(NW,1,jR(t.repositoryContent)):void 0,l=t?yi(HR,t.indexInputs.version,Tm(t.indexInputs)):void 0,c=e.db&&t?BW(e.db.generation.metadataRaw):void 0,u=e.db?{generation:yi(kW,1,e.db.generation.identity),...c?{inputs:c}:{},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"}]:[]],f=[...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"}),f.push({source:"process",kind:"not-established"})),{schemaVersion:rf,observedAt:(e.observedAt??(t?new Date(t.capturedAt):new Date)).toISOString(),facts:{...o?{collaborationDomain:o}:{},...s?{workspaceInstance:s}:{},...a?{wholeContent:a}:{},...l?{relevantInputs:[{subject:AW,identity:l}]}:{},...u?{index:u}:{}},observedSources:m,stabilityProofs:f,...i?{diagnostics:{clean:i.clean,...i.headCommit?{headCommit:i.headCommit}:{},...i.treeOid?{treeOid:i.treeOid}:{}}}:{}}}function _W(e){return zi({projectRoot:e.projectRoot,db:e.db,...e.gitContext?{gitContext:e.gitContext}:{},...e.observedAt?{observedAt:e.observedAt}:{},observedSourceKinds:["index-generation"]})}function uce(){let e=Is();if(!e)return zi({projectRoot:mf(),observedSourceKinds:["process"]});let t=e.config.projectRoot,n=Kl(t);return _W({projectRoot:t,db:e,...n?{gitContext:n}:{}})}function BW(e){if(!e)return;let t=bs(e);if(t.kind!=="legacy"&&t.kind!=="supported")return;let n=tf(t.metadata.fingerprint);return n&&Number.isSafeInteger(n.version)&&n.version>0?yi(HR,n.version,Tm(n)):void 0}var km="codebaseiq-isolated-analysis",Nm=1;function OW(e){let t=[...e??[]];return t.includes("--json")?t:["--json",...t]}var kr=class extends Error{constructor(n,i,r=!0){super(`${n} timed out after ${i}ms.`);this.label=n;this.timeoutMs=i;this.reaped=r;this.name="IsolatedProcessTimeoutError"}label;timeoutMs;reaped;timedOut=!0};function Cce(e,t){let n=Is(),i={protocol:km,schemaVersion:Nm,producer:{name:"codebaseiq",version:hi},command:e,result:t,...n?{observationReceipt:zi({projectRoot:n.config.projectRoot,db:n,observedSourceKinds:["index-generation"]})}:{}};Zl(JSON.stringify(i))}function UR(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}function _l(e){let t=e.timeoutMs??ep.analysis,n=e.maxBuffer??10*1024*1024;return np({command:process.execPath,args:[...process.execArgv,e.cliPath,e.command,...OW(e.args)],cwd:process.cwd(),env:e.env??process.env,label:e.label,timeoutMs:t,maxStdoutBytes:n,maxStderrBytes:n,signal:e.signal}).catch(i=>{throw i instanceof tp&&i.kind==="timeout"?new kr(e.label,t,i.reaped):i}).then(i=>{let r=i.stderr.trim();if(i.status!==0)throw new Error(`${e.label} failed${r?`:
532
+ ${r}`:""}`);return $W(i.stdout,e)})}function $W(e,t){let n;try{n=JSON.parse(e)}catch(r){throw new Error(`${t.label} returned invalid JSON: ${r instanceof Error?r.message:r}`,{cause:r})}if(!jn(n))throw new Error(`${t.label} returned a non-object isolated-analysis message.`);if(n.protocol!==km)throw new Error(`${t.label} returned protocol ${Fm(n.protocol)}; expected ${km}.`);if(n.schemaVersion!==Nm)throw new Error(`${t.label} returned unsupported isolated-analysis schemaVersion ${Fm(n.schemaVersion)}; expected ${Nm}.`);if(!jW(n.producer))throw new Error(`${t.label} did not identify a codebaseiq producer version.`);if(n.command!==t.command)throw new Error(`${t.label} returned result for command ${Fm(n.command)}; expected ${t.command}.`);if(!Object.hasOwn(n,"result"))throw new Error(`${t.label} omitted the isolated-analysis result.`);let i=n.observationReceipt;if(i!==void 0&&(!of(i)||i.schemaVersion!==2))throw new Error(`${t.label} returned an invalid observation receipt.`);return{result:n.result,...i?{observationReceipt:i}:{}}}function jW(e){return jn(e)&&e.name==="codebaseiq"&&typeof e.version=="string"&&e.version.length>0}function Fm(e){return typeof e=="string"?JSON.stringify(e):String(e)}async function Am(e,t,n){let i=new Array(e.length),r=new AbortController,o=0,s,a=!1;async function l(){for(;!r.signal.aborted&&o<e.length;){let c=o++;try{i[c]=await n(e[c],r.signal)}catch(u){throw a||(a=!0,s=u,r.abort(u)),u}}}if(await Promise.allSettled(Array.from({length:Math.min(t,e.length)},()=>l())),a)throw s;return i}function zR(e,t){let n=new Set,i=[];for(let r of e){if(n.has(r))continue;let o=t.find(a=>a.has(r));if(!o){n.add(r),i.push([r]);continue}let s=e.filter(a=>o.has(a));s.forEach(a=>n.add(a)),i.push(s)}return i}import{spawnSync as HW}from"child_process";import{existsSync as UW,mkdirSync as zW,renameSync as qW,writeFileSync as KW}from"fs";import{dirname as KR,join as GW}from"path";var Bl=6,WW="health-report-cache.json";function _m(e,t,n,i=QW()){let r=Cn(e);return r?{version:Bl,projectFingerprint:r,cliVersion:n,scope:t.scope??null,full:t.full===!0,phaseTimeoutMs:t.phaseTimeoutMs??null,gitHead:i.gitHead(e.config.projectRoot)}:null}function GR(e,t,n=YR()){let i=VR(e),r=JR(t),o=!1;return B("health.report-cache.read",()=>{if(!n.existsSync(i))return null;try{let s=JSON.parse(n.readFile(i));return!VW(s)||s.keyHash!==r?null:(o=!0,s.report)}catch{return null}},()=>({available:!0,hit:o,keyHash:r}))}function WR(e,t,n,i=YR()){let r=VR(e),o={version:Bl,keyHash:JR(t),key:t,writtenAt:i.nowIso(),report:n};i.mkdirSync(KR(r),{recursive:!0});let s=`${r}.${process.pid}.${Date.now()}.tmp`;i.writeFileSync(s,JSON.stringify(o)),i.renameSync(s,r)}function VR(e){return GW(KR(e.config.dbPath),WW)}function JR(e){return zt(JSON.stringify(e))}function VW(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===Bl&&typeof t.keyHash=="string"&&JW(t.key)&&typeof t.writtenAt=="string"&&YW(t.report)}function JW(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===Bl&&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 YW(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)&&XW(t.coverage)}function XW(e){if(!e||typeof e!="object")return!1;let t=e;if(t.status!=="complete"&&t.status!=="incomplete"&&t.status!=="semantic-disabled")return!1;let n=t.complexity?.semanticEvidence;return qR(n)&&typeof n.excludedSymbolCount=="number"&&Array.isArray(t.phases)&&t.phases.every(i=>!!i&&typeof i=="object"&&typeof i.phase=="string"&&qR(i.semanticEvidence))}function qR(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.enabled=="boolean"&&(t.status==="complete"||t.status==="incomplete"||t.status==="unavailable"||t.status==="incomplete-and-unavailable"||t.status==="disabled")&&typeof t.incompleteSymbolCount=="number"&&typeof t.unavailableSymbolCount=="number"}function QW(){return{gitHead(e){let t=HW("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",timeout:3e4,killSignal:"SIGKILL",windowsHide:!0});return t.status===0?t.stdout.trim():null}}}function YR(){return{existsSync:UW,mkdirSync:zW,readFile:e=>gi(e,"health report cache"),renameSync:qW,writeFileSync:KW,nowIso:()=>new Date().toISOString()}}var ZR="__health-phase",e2="__diff-impact-batch",t2=10,n2=4,i2=8,r2=25e3,o2=2500,Bm=2500,s2=4,a2=12,XR=3e4,eI=new Set(["react-component-duplicates","react-hook-candidates","react-large-component-pressure"]),tI=new Set(["vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure"]),l2=new Set([...tI,"suppressions"]),c2=new Set(["similar","extract-candidates"]),$l=3,QR=Br({kind:"health-semantic-prewarm",invalidation:Ye("health-semantic-prewarm"),serialize:e=>JSON.stringify(e),deserialize:u2});function u2(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return n.version!==$l||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:$l,definitions:n.definitions,referenceCacheWrites:n.referenceCacheWrites,referenceIncomplete:n.referenceIncomplete,calleeRows:n.calleeRows,warmedAt:n.warmedAt}}catch{return null}}function Wce(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
533
+ `)}function d2(e){let t=Li(e);return t.symbols>=r2||t.documents>=o2}function Vce(e,t,n,i={}){if(!d2(e))return{semantic:!0};if(n)return i.quiet||console.error(`Large index detected; ${t} is running the unbounded semantic pass because --full was supplied.`),{semantic:!0};if(!i.quiet){let r=t==="inspect"?"Use --full only when every omitted semantic candidate can change the decision; it does not override source or behavior materialization ceilings.":`Run "codebaseiq ${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 ${Bm}. `+r)}return{scanLimit:Bm,semantic:!1,analysisBudget:{scanLimit:Bm,semanticEnrichment:!1,reason:"large index default budget; pass --full for unbounded semantic analysis"}}}var m2={env:process.env,projectFingerprint:Cn,semanticEngineFingerprint:h2,readMarker:(e,t,n)=>QR.read(e,t,n),writeMarker:(e,t,n,i)=>QR.write(e,t,n,i),candidateDefinitions:(e,t)=>new U(e).scopedDefinitions(t.scope).filter(n=>Ge(n.relativePath)!==null),materializeReferences:(e,t,n)=>Ot(e).materializeReferences(t,n),materializeCallees:fu};function f2(e,t,n=m2){if(t.full!==!0)return mi("default-mode");if((n.env??process.env).CODEBASEIQ_HEALTH_SEMANTIC_PREWARM==="0")return mi("disabled");let i=mi("error");return B("health.semantic-prewarm",()=>{try{i=p2(e,t,n)}catch(r){i=mi("error",{error:r instanceof Error?r.message:String(r)})}return i},()=>y2(i))}function p2(e,t,n){let i=n.projectFingerprint(e);if(!i)return mi("missing-project-fingerprint");let r=g2(t,n.semanticEngineFingerprint(e)),o=n.readMarker(e,r,i);if(o&&o.referenceIncomplete===0)return mi("cache-hit");let s=[];if(s=B("health.semantic-prewarm.candidate-definitions",()=>(s=n.candidateDefinitions(e,t),s),()=>({definitions:s.length})),s.length===0)return mi("no-semantic-definitions");let a=0,l=B("health.semantic-prewarm.references",()=>{let m=n.materializeReferences(e,s,{prefetchCallees:!0});return a=m.cacheHits+m.cacheWrites+m.inMemoryHits,m},()=>({definitions:s.length,rows:a}));if(l.cacheHits+l.cacheWrites+l.inMemoryHits===0&&l.misses+l.unkeyed>0)return mi("provider-unavailable",{definitions:s.length,referenceMisses:l.misses});let u=0,d=B("health.semantic-prewarm.callees",()=>{let m=n.materializeCallees(e,s);return u=m.size,m},()=>({definitions:s.length,rows:u}));return l.incomplete>0?{status:"partial",reason:"incomplete-references",definitions:s.length,referenceCacheHits:l.cacheHits,referenceCacheWrites:l.cacheWrites,referenceMisses:l.misses,referenceIncomplete:l.incomplete,calleeRows:d.size}:(B("health.semantic-prewarm.marker-write",()=>n.writeMarker(e,r,i,{version:$l,definitions:s.length,referenceCacheWrites:l.cacheWrites,referenceIncomplete:l.incomplete,calleeRows:d.size,warmedAt:Date.now()})),{status:"warmed",reason:"cache-miss",definitions:s.length,referenceCacheHits:l.cacheHits,referenceCacheWrites:l.cacheWrites,referenceMisses:l.misses,referenceIncomplete:l.incomplete,calleeRows:d.size})}function g2(e,t){return JSON.stringify({version:$l,cliVersion:hi,semanticEngineFingerprint:t,scope:e.scope??null})}function h2(e){return zt(JSON.stringify({kind:"health-semantic-prewarm-engine",rust:Ri(e.config.projectRoot)}))}function mi(e,t={}){return{status:"skipped",reason:e,definitions:0,referenceCacheHits:0,referenceCacheWrites:0,referenceMisses:0,referenceIncomplete:0,calleeRows:0,...t}}function y2(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 Ol(e){return Ql(t=>{let n=zi({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 jl(e,t,n){let i=e[0];if(!i)throw new Error("An evidence-bound analysis requires at least one index observation anchor.");let r=i.generationDigest,o=e.every(a=>a.generationDigest===r),s=t.every(a=>a?.facts.index?.generation.digest===r);return zi({projectRoot:i.database.config.projectRoot,...o&&s?{db:i.database}:{},observedSourceKinds:n})}async function Jce(e){return(await b2(e)).result}async function b2(e){let t=I2(e),n={...e,phaseTimeoutMs:t??null},i=Ol(g=>{let h=_m(g,n,hi);if(!h)return null;let b=GR(g,h);return b||null});if(i.value)return{result:i.value,observationReceipt:jl([i.anchor],[],["index-generation","live-workspace"])};let r=Ol(g=>({applicability:S2(g,e),overview:Im(g,"overview",e)})),{applicability:o,overview:s}=r.value,a=[i.anchor,r.anchor],l=new Map;l.set("overview",s);let c=kl.filter(g=>g==="overview"?!1:v2(g,o)?!0:(l.set(g,qi(g)),!1)),u=C2(c);if(e.full){let g=Ol(h=>f2(h,e));a.push(g.anchor)}let d=await Am(u,E2(u.length),(g,h)=>x2(g,e,t,h)),m=d.flatMap(g=>g.result),f=[];if(m.forEach(g=>{g.healthPhaseMeta&&f.push(`Health phase "${g.phase}" deferred: ${g.healthPhaseMeta.reason}. Run health --full for exhaustive analysis.`),l.set(g.phase,g)}),f.length>0){let g=l.get("overview");l.set("overview",{...g,warnings:[...g.warnings,...f]})}let p=Em(kl.map(g=>l.get(g)));return Ql(g=>{let h=_m(g,n,hi);h&&WR(g,h,p)}),{result:p,observationReceipt:jl(a,d.map(g=>g.observationReceipt),["index-generation","live-workspace"])}}function S2(e,t){return Ps(e,{scope:t.scope})}function v2(e,t){return eI.has(e)?t.react:tI.has(e)?t.vue:!0}function C2(e){return zR(e,[eI,l2,c2])}function qi(e){let t={enabled:!0,status:"complete",incompleteSymbolCount:0,unavailableSymbolCount:0};switch(e){case"react-component-duplicates":return{phase:e,reactComponentDuplicates:{count:0,loc:0,files:[]},evidenceCoverage:t};case"react-hook-candidates":return{phase:e,reactHookCandidates:{count:0,loc:0,files:[]},evidenceCoverage:t};case"react-large-component-pressure":return{phase:e,reactLargeComponentPressure:{count:0,loc:0,files:[]},evidenceCoverage:t};case"vue-component-duplicates":return{phase:e,vueComponentDuplicates:{count:0,loc:0,files:[]},evidenceCoverage:t};case"vue-composable-candidates":return{phase:e,vueComposableCandidates:{count:0,loc:0,files:[]},evidenceCoverage:t};case"vue-large-view-pressure":return{phase:e,vueLargeViewPressure:{count:0,loc:0,files:[]},evidenceCoverage:t};default:throw new Error(`Health phase "${e}" cannot be synthesized.`)}}function x2(e,t,n,i){if(e.length===1)return R2(e[0],t,n,i).then(a=>({result:[a.result],...a.observationReceipt?{observationReceipt:a.observationReceipt}:{}}));let r=e.join(","),o=process.argv[1]??$m(import.meta.url),s=[r];return t.scope&&s.push("--scope",t.scope),t.full&&s.push("--full"),_l({cliPath:o,command:ZR,args:s,label:`Health phases "${r}"`,timeoutMs:n,signal:i}).catch(a=>{if(t.full||!(a instanceof kr))throw a;return{result:e.map(l=>nI(l,a.timeoutMs,`timed out after ${a.timeoutMs}ms`))}})}function R2(e,t,n,i){let r=process.argv[1]??$m(import.meta.url),o=[e];return t.scope&&o.push("--scope",t.scope),t.full&&o.push("--full"),_l({cliPath:r,command:ZR,args:o,label:`Health phase "${e}"`,timeoutMs:n,signal:i}).catch(s=>{if(t.full||!(s instanceof kr))throw s;return{result:nI(e,s.timeoutMs,`timed out after ${s.timeoutMs}ms`)}})}function I2(e,t=process.env){if(e.full)return;let n=t.CODEBASEIQ_HEALTH_PHASE_TIMEOUT_MS;if(!n)return XR;let i=parseInt(n,10);return!Number.isFinite(i)||i<0?XR:i===0?void 0:i}function nI(e,t,n){let i={evidenceCoverage:{enabled:!0,status:"unavailable",incompleteSymbolCount:0,unavailableSymbolCount:0},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:[]},...i};case"isolated":return{phase:e,isolated:{count:0,loc:0,files:[]},...i};case"cycles":return{phase:e,realCycleCount:0,...i};case"similar":return{phase:e,similarCount:0,...i};case"duplicate-bodies":return{phase:e,duplicateBodies:{count:0,loc:0,files:[]},...i};case"twin-drift":return{phase:e,twinDrift:{count:0,loc:0,files:[]},...i};case"react-component-duplicates":return{...qi(e),...i};case"react-hook-candidates":return{...qi(e),...i};case"react-large-component-pressure":return{...qi(e),...i};case"vue-component-duplicates":return{...qi(e),...i};case"vue-composable-candidates":return{...qi(e),...i};case"vue-large-view-pressure":return{...qi(e),...i};case"extract-candidates":return{phase:e,extractCount:0,...i};case"wrapper-candidates":return{phase:e,wrappers:{count:0,loc:0,files:[]},...i};case"passthrough-candidates":return{phase:e,passthroughs:{count:0,loc:0,files:[]},...i};case"stale-abstractions":return{phase:e,stale:{count:0,loc:0,files:[],unused:0,singleUse:0},...i};case"drift":return{phase:e,drift:{count:0,unusedImports:0,architectureViolations:0,layerViolations:0,direct:0,signal:0},...i};case"complexity-hotspots":return{phase:e,complexity:{top:[],extremeCount:0,coverage:{semanticEvidence:{enabled:!0,status:"unavailable",incompleteSymbolCount:0,unavailableSymbolCount:0,excludedSymbolCount:0}}},...i};case"git-evidence":return{phase:e,gitEvidence:null,...i};case"suppressions":return{phase:e,suppressions:{total:0,byCategory:{}},...i};case"coverage-contracts":return{phase:e,coverageContracts:{count:0,loc:0,files:[]},...i}}}var E2=iI({envKey:"CODEBASEIQ_HEALTH_CONCURRENCY",defaultMinimum:s2,defaultMaximum:a2});function Yce(e){if(console.log(`
534
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 | ${yf(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: ${Um(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: ${Um(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: ${Um(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(`
535
+ `),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${ff(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: ${Om(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: ${Om(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: ${Om(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
537
  Prioritized Actions (highest impact + lowest effort first):`);for(let n=0;n<e.actions.length;n++){let i=e.actions[n],r=i.locRecoverable>0?` (~${i.locRecoverable} LOC involved)`:"";console.log(` ${n+1}. [${i.effort} effort / ${i.impact} impact] ${i.description}${r}`)}}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(O2(e),B2(e),e.scoreBreakdown.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(D2(e),L2(e),e.scoreBreakdown.length>0){console.log(`
539
539
  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?`
540
540
  No findings from completed analyses. Review warnings before interpreting this result as clean.`:`
541
- No issues found. Codebase is clean.`)}function Um(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${_2(t)} score-weighted)`}function _2(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function B2(e){if(e.pressure.length!==0){console.log(`
542
- 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 O2(e){let t=e.axes;if(console.log(`
543
- Axes:`),console.log(` Zero-reference candidates: ${t.deletable.loc} LOC across ${t.deletable.symbols} symbols`),t.changeAmplification){let i=t.changeAmplification;console.log(` Change amplification: ${i.medianFilesPerCommit} files/commit median, ${i.p90FilesPerCommit} p90 (${i.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 i of t.hiddenCoupling.top.slice(0,3))console.log(` ${i.fileA} <-> ${i.fileB} (${i.together}x together, ${Math.round(i.confidence*100)}%)`)}if(t.churnWeightedComplexity&&t.churnWeightedComplexity.length>0){let i=t.churnWeightedComplexity[0];i.weighted>0&&console.log(` Churn x complexity: hottest is ${i.symbol} (${i.changes} changes, weighted ${i.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 i=e.validation,r=i.ratio===null?"n/a":`${i.ratio}x`;console.log(` Validation: flagged files fix-density ${i.flaggedFixDensity} vs baseline ${i.baselineFixDensity} (${r})`),console.log(` fix-commit signal: subject-keyword heuristic over ${i.validationBasis.commitsScanned} commits`)}}async function hue(e){let t=$l(o=>{let s=Fr(o,{base:e.base});return s.note?{kind:"complete",result:gl(o,{base:e.base})}:s.changedFiles.length===0?{kind:"complete",result:gl(o,{base:e.base})}:{kind:"batched",plan:s}}),n=t.value;if(n.kind==="complete")return{result:n.result,observationReceipt:Hl([t.anchor],[],["index-generation","live-workspace"])};let i=qR(n.plan.changedFiles,d2),r=await $m(i,$2(i.length),(o,s)=>z2(o,e,s));return{result:hl(n.plan.changedFiles,r.map(o=>o.result)),observationReceipt:Hl([t.anchor],r.map(o=>o.observationReceipt),["index-generation","live-workspace"])}}var $2=oI({envKey:"CODEBASEIQ_DIFF_IMPACT_CONCURRENCY",defaultMinimum:m2,defaultMaximum:f2});function oI(e){return(t,n=process.env,i=c2)=>j2(t,n,i,e)}function j2(e,t,n,i){let r=t[i.envKey],o=U2(n,i),s=r?parseInt(r,10):o,a=!Number.isFinite(s)||s<1?Math.min(o,e):Math.min(s,e),l=H2(t);return l===null?a:Math.min(l,a)}function H2(e){let t=e.CODEBASEIQ_MAX_CONCURRENCY;if(!t)return null;let n=parseInt(t,10);return Number.isFinite(n)&&n>=1?n:null}function U2(e,t){let n=e(),i=Number.isFinite(n)?Math.max(t.defaultMinimum,n-1):0;return Math.min(t.defaultMaximum,Math.max(t.defaultMinimum,i))}function z2(e,t,n){let i=process.argv[1]??zm(import.meta.url),r=[];return t.base&&r.push("--base",t.base),Bl({cliPath:i,command:u2,args:r,env:{...process.env,CODEBASEIQ_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch",signal:n})}function yue(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(i=>i.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(i=>i.file))];for(let i of n){let r=t.filter(o=>o.file===i).length;console.log(`note: ${r} changed line-range(s) in ${i} belong to no indexed symbol`)}}console.log(""),e.changedSymbols.length>0&&(console.log("Changed symbols:"),ac.list(e.changedSymbols,n=>` ${n.file} ${n.shortName} (fan-in: ${n.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
544
- Affected consumer files:`),ac.list(e.affectedConsumers,n=>` ${n.file} (${n.consumedSymbols} symbol(s))`))}export{sp as a,bI as b,K2 as c,G2 as d,ac as e,Gr as f,on as g,lp as h,J2 as i,aa as j,BY as k,ML as l,Li as m,LD as n,yu as o,bu as p,So as q,Su as r,Ea as s,WP as t,Lo as u,lc as v,wc as w,PE as x,Do as y,Mo as z,Ba as A,ob as B,aF as C,PF as D,r3 as E,D0 as F,wN as G,Uo as H,bd as I,JN as J,ov as K,ji as L,_A as M,$A as N,jA as O,HA as P,e_ as Q,i_ as R,r_ as S,o_ as T,a_ as U,l_ as V,c_ as W,Hi as X,Sv as Y,Ko as Z,Ed as _,F_ as $,Go as aa,__ as ba,B_ as ca,q_ as da,J_ as ea,Y_ as fa,X_ as ga,Jo as ha,Td as ia,Yo as ja,nO as ka,Xo as la,Qo as ma,kd as na,Zo as oa,es as pa,Nd as qa,VO as ra,ts as sa,e1 as ta,Ud as ua,zd as va,O1 as wa,Fr as xa,_C as ya,bj as za,is as Aa,JH as Ba,os as Ca,bU as Da,ss as Ea,cz as Fa,uz as Ga,bz as Ha,Fz as Ia,$z as Ja,nq as Ka,gm as La,Jx as Ma,ym as Na,Yx as Oa,Dl as Pa,Fq as Qa,ds as Ra,ms as Sa,fs as Ta,jK as Ua,HK as Va,UK as Wa,wm as Xa,Nl as Ya,Dm as Za,CG as _a,nW as $a,iW as ab,oW as bb,aW as cb,bW as db,EW as eb,zi as fb,Mce as gb,jce as hb,tI as ib,u2 as jb,mue as kb,fue as lb,pue as mb,D2 as nb,gue as ob,hue as pb,yue as qb};
545
- //# sourceMappingURL=chunk-N3Q3AWGW.js.map
541
+ No issues found. Codebase is clean.`)}function Om(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${w2(t)} score-weighted)`}function w2(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function L2(e){if(e.pressure.length!==0){console.log(`
542
+ 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 D2(e){let t=e.axes;if(console.log(`
543
+ Axes:`),console.log(` Zero-reference candidates: ${t.deletable.loc} LOC across ${t.deletable.symbols} symbols`),t.changeAmplification){let i=t.changeAmplification;console.log(` Change amplification: ${i.medianFilesPerCommit} files/commit median, ${i.p90FilesPerCommit} p90 (${i.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 i of t.hiddenCoupling.top.slice(0,3))console.log(` ${i.fileA} <-> ${i.fileB} (${i.together}x together, ${Math.round(i.confidence*100)}%)`)}if(t.churnWeightedComplexity&&t.churnWeightedComplexity.length>0){let i=t.churnWeightedComplexity[0];i.weighted>0&&console.log(` Churn x complexity: hottest is ${i.symbol} (${i.changes} changes, weighted ${i.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 i=e.validation,r=i.ratio===null?"n/a":`${i.ratio}x`;console.log(` Validation: flagged files fix-density ${i.flaggedFixDensity} vs baseline ${i.baselineFixDensity} (${r})`),console.log(` fix-commit signal: subject-keyword heuristic over ${i.validationBasis.commitsScanned} commits`)}}async function Xce(e){let t=Ol(o=>{let s=Pr(o,{base:e.base});return s.note?{kind:"complete",result:pl(o,{base:e.base})}:s.changedFiles.length===0?{kind:"complete",result:pl(o,{base:e.base})}:{kind:"batched",plan:s}}),n=t.value;if(n.kind==="complete")return{result:n.result,observationReceipt:jl([t.anchor],[],["index-generation","live-workspace"])};let i=UR(n.plan.changedFiles,t2),r=await Am(i,M2(i.length),(o,s)=>k2(o,e,s));return{result:gl(n.plan.changedFiles,r.map(o=>o.result)),observationReceipt:jl([t.anchor],r.map(o=>o.observationReceipt),["index-generation","live-workspace"])}}var M2=iI({envKey:"CODEBASEIQ_DIFF_IMPACT_CONCURRENCY",defaultMinimum:n2,defaultMaximum:i2});function iI(e){return(t,n=process.env,i=ZW)=>P2(t,n,i,e)}function P2(e,t,n,i){let r=t[i.envKey],o=F2(n,i),s=r?parseInt(r,10):o,a=!Number.isFinite(s)||s<1?Math.min(o,e):Math.min(s,e),l=T2(t);return l===null?a:Math.min(l,a)}function T2(e){let t=e.CODEBASEIQ_MAX_CONCURRENCY;if(!t)return null;let n=parseInt(t,10);return Number.isFinite(n)&&n>=1?n:null}function F2(e,t){let n=e(),i=Number.isFinite(n)?Math.max(t.defaultMinimum,n-1):0;return Math.min(t.defaultMaximum,Math.max(t.defaultMinimum,i))}function k2(e,t,n){let i=process.argv[1]??$m(import.meta.url),r=[];return t.base&&r.push("--base",t.base),_l({cliPath:i,command:e2,args:r,env:{...process.env,CODEBASEIQ_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch",signal:n})}function Qce(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(i=>i.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(i=>i.file))];for(let i of n){let r=t.filter(o=>o.file===i).length;console.log(`note: ${r} changed line-range(s) in ${i} belong to no indexed symbol`)}}console.log(""),e.changedSymbols.length>0&&(console.log("Changed symbols:"),sc.list(e.changedSymbols,n=>` ${n.file} ${n.shortName} (fan-in: ${n.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
544
+ Affected consumer files:`),sc.list(e.affectedConsumers,n=>` ${n.file} (${n.consumedSymbols} symbol(s))`))}export{ip as a,hI as b,A2 as c,_2 as d,sc as e,qr as f,on as g,op as h,$2 as i,sa as j,EY as k,CL as l,Li as m,SD as n,pu as o,gu as p,yo as q,hu as r,Ia as s,BP as t,Eo as u,ac as v,Ec as w,DE as x,wo as y,Lo as z,_a as A,ib as B,XT as C,vF as D,qX as E,b0 as F,hN as G,jo as H,pd as I,$N as J,iv as K,ji as L,wA as M,MA as N,PA as O,TA as P,qA as Q,WA as R,VA as S,JA as T,XA as U,QA as V,ZA as W,Hi as X,yv as Y,zo as Z,Cd as _,x_ as $,qo as aa,w_ as ba,L_ as ca,N_ as da,$_ as ea,j_ as fa,H_ as ga,Wo as ha,Ld as ia,Vo as ja,GB as ka,Jo as la,Yo as ma,Md as na,Xo as oa,Qo as pa,Pd as qa,OO as ra,Zo as sa,q$ as ta,Od as ua,$d as va,D1 as wa,Pr as xa,NC as ya,lj as za,ts as Aa,$H as Ba,is as Ca,lU as Da,rs as Ea,ZU as Fa,ez as Ga,lz as Ha,xz as Ia,Mz as Ja,Gz as Ka,dm as La,Wx as Ma,fm as Na,Vx as Oa,Ll as Pa,xq as Qa,cs as Ra,us as Sa,ds as Ta,PK as Ua,TK as Va,FK as Wa,xm as Xa,kl as Ya,Im as Za,dG as _a,GG as $a,WG as ab,JG as bb,XG as cb,lW as db,gW as eb,zi as fb,uce as gb,Cce as hb,ZR as ib,e2 as jb,Wce as kb,Vce as lb,Jce as mb,b2 as nb,Yce as ob,Xce as pb,Qce as qb};
545
+ //# sourceMappingURL=chunk-OWJWOEDU.js.map