scip-query 0.23.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (432) hide show
  1. package/CHANGELOG.md +244 -1
  2. package/README.md +2 -0
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/by-kind-H3P6BR5G.js +2 -0
  5. package/dist/call-graph-VTG2CUOQ.js +2 -0
  6. package/dist/call-graph-evidence-BociKRpF.d.ts +19 -0
  7. package/dist/chunk-2BMSSRBH.js +2 -0
  8. package/dist/{chunk-WIWY3CRX.js → chunk-2GJSD5GY.js} +2 -2
  9. package/dist/{chunk-W5OXRYGE.js → chunk-2M2LSIMY.js} +3 -3
  10. package/dist/{chunk-2LDBDR6J.js → chunk-2N6WBNDC.js} +2 -2
  11. package/dist/{chunk-HOENASQM.js → chunk-2USA3S3P.js} +2 -2
  12. package/dist/chunk-2VAHDDLM.js +133 -0
  13. package/dist/chunk-2XWIUW5Z.js +455 -0
  14. package/dist/chunk-3D4BOXW6.js +20 -0
  15. package/dist/{chunk-BBCIS4DX.js → chunk-3LO4FST5.js} +2 -2
  16. package/dist/chunk-3WTY4LP2.js +3 -0
  17. package/dist/{chunk-UXW33INU.js → chunk-3Z5AMSK6.js} +2 -2
  18. package/dist/{chunk-4ILJCCXV.js → chunk-44IETFOU.js} +2 -2
  19. package/dist/chunk-4FR6GQIT.js +2 -0
  20. package/dist/chunk-4KBTHJLP.js +2 -0
  21. package/dist/{chunk-SSK6LDPC.js → chunk-5BIKR67W.js} +2 -2
  22. package/dist/{chunk-IHGQTTVW.js → chunk-5PROPLHI.js} +2 -2
  23. package/dist/{chunk-TA3QKLLU.js → chunk-5V7EPTII.js} +2 -2
  24. package/dist/{chunk-JS4PGXMV.js → chunk-62LPZCBQ.js} +2 -2
  25. package/dist/{chunk-DBRSYFXR.js → chunk-64O2JHQA.js} +2 -2
  26. package/dist/chunk-6D4F5VWG.js +10 -0
  27. package/dist/{chunk-BHVUJOCQ.js → chunk-6ERFBC3X.js} +2 -2
  28. package/dist/{chunk-ILTDAWEF.js → chunk-6ILKOOGH.js} +2 -2
  29. package/dist/chunk-6MFXCMZC.js +2 -0
  30. package/dist/chunk-6O7FACKB.js +2 -0
  31. package/dist/{chunk-XDQMU3BT.js → chunk-6TS3KOXR.js} +2 -2
  32. package/dist/{chunk-YI2AWIHC.js → chunk-76QOU4PK.js} +2 -2
  33. package/dist/{chunk-7CYG22FH.js → chunk-7DUI77BN.js} +2 -2
  34. package/dist/{chunk-IDFEUFKS.js → chunk-7F7T6DCR.js} +2 -2
  35. package/dist/chunk-7H6VHWWJ.js +2 -0
  36. package/dist/chunk-7HXT6YLU.js +5 -0
  37. package/dist/{chunk-DIRJWYBM.js → chunk-7R4V5ES6.js} +4 -4
  38. package/dist/{chunk-SZHGTCPP.js → chunk-7RIRIADH.js} +2 -2
  39. package/dist/chunk-7ZLWLOGT.js +2 -0
  40. package/dist/{chunk-M2O5NY6W.js → chunk-A4WEAK35.js} +2 -2
  41. package/dist/chunk-AADQLOQ4.js +38 -0
  42. package/dist/{chunk-OLNV6I6U.js → chunk-AN76MGUE.js} +2 -2
  43. package/dist/chunk-ANLNLY66.js +2 -0
  44. package/dist/chunk-ATXPTSEI.js +81 -0
  45. package/dist/{chunk-YPWBKGFU.js → chunk-AX7IDVFT.js} +2 -2
  46. package/dist/chunk-B7MPDEAK.js +3 -0
  47. package/dist/chunk-BBB5FBX4.js +2 -0
  48. package/dist/{chunk-6I6L7Z62.js → chunk-BHKK5RJY.js} +2 -2
  49. package/dist/chunk-BJWFVAA5.js +2 -0
  50. package/dist/{chunk-UHFYCMZO.js → chunk-BKZYTLGE.js} +2 -2
  51. package/dist/chunk-BL6DCHQP.js +2 -0
  52. package/dist/{chunk-TEBQMNVI.js → chunk-BOW7SSQH.js} +2 -2
  53. package/dist/{chunk-OWOOWNJ5.js → chunk-C4RHHCKL.js} +2 -2
  54. package/dist/{chunk-N2ZSIIGR.js → chunk-C7C6AKAT.js} +6 -6
  55. package/dist/chunk-CD6M6LS2.js +16 -0
  56. package/dist/chunk-CFE6PSG6.js +2 -0
  57. package/dist/{chunk-6V5CNXL6.js → chunk-CFNIGQMT.js} +2 -2
  58. package/dist/{chunk-GUFSG5TX.js → chunk-CKBUBRYD.js} +2 -2
  59. package/dist/{chunk-4WNW27SX.js → chunk-CZW5MZ5B.js} +2 -2
  60. package/dist/chunk-DBBZ63ZX.js +2 -0
  61. package/dist/{chunk-HCXEQRFF.js → chunk-DBN7DMJB.js} +2 -2
  62. package/dist/{chunk-6PQNKL3G.js → chunk-DUULLZHZ.js} +2 -2
  63. package/dist/{chunk-Z4CDXYNQ.js → chunk-DV5Y5NOS.js} +2 -2
  64. package/dist/chunk-DZOIKCTM.js +3 -0
  65. package/dist/chunk-E4PKTOL3.js +2 -0
  66. package/dist/{chunk-EG2CPZMJ.js → chunk-E65ELFKU.js} +2 -2
  67. package/dist/{chunk-CNO7TOKL.js → chunk-E7QR35ST.js} +2 -2
  68. package/dist/{chunk-3D3QG236.js → chunk-EFSXAINW.js} +2 -2
  69. package/dist/{chunk-IL676XCC.js → chunk-EHVEIEQN.js} +2 -2
  70. package/dist/{chunk-BE7ZZTMC.js → chunk-EHYDXE3Z.js} +2 -2
  71. package/dist/{chunk-LXABEJX3.js → chunk-EP63Y6LD.js} +2 -2
  72. package/dist/{chunk-QU5XRYB5.js → chunk-EPX6NQN6.js} +2 -2
  73. package/dist/{chunk-FESCRNVV.js → chunk-ETC674NS.js} +2 -2
  74. package/dist/{chunk-OSSESPDX.js → chunk-F5GSBHC6.js} +2 -2
  75. package/dist/chunk-FH3DGXC6.js +2 -0
  76. package/dist/{chunk-YEN6CYC7.js → chunk-FI7VGOR4.js} +2 -2
  77. package/dist/chunk-FJF6VO2P.js +2 -0
  78. package/dist/{chunk-FRUSVINH.js → chunk-FLMTCX5R.js} +2 -2
  79. package/dist/chunk-FVFDOIM3.js +2 -0
  80. package/dist/{chunk-PJFGPYTU.js → chunk-G2HU5WRN.js} +2 -2
  81. package/dist/{chunk-FIQRSHVM.js → chunk-G4ALYS4J.js} +2 -2
  82. package/dist/{chunk-UVGEWT4Y.js → chunk-G56I7K4W.js} +2 -2
  83. package/dist/{chunk-WOIKCX6A.js → chunk-GC4DG2V5.js} +2 -2
  84. package/dist/chunk-GG45PK4S.js +4 -0
  85. package/dist/{chunk-XBGWL66K.js → chunk-GHNPACNP.js} +2 -2
  86. package/dist/{chunk-IICPE7B2.js → chunk-GINH3YQU.js} +2 -2
  87. package/dist/{chunk-HLZTEXRA.js → chunk-GTZZVLKJ.js} +2 -2
  88. package/dist/chunk-GXXW5ZHH.js +2 -0
  89. package/dist/{chunk-B5D7QPBE.js → chunk-HAXXKRTD.js} +2 -2
  90. package/dist/chunk-HEZWBAZY.js +2 -0
  91. package/dist/chunk-HMEWLMML.js +2 -0
  92. package/dist/{chunk-QUU5OBVK.js → chunk-HOBOVYPO.js} +2 -2
  93. package/dist/{chunk-XGZEP6GR.js → chunk-HRFQ6GW5.js} +2 -2
  94. package/dist/{chunk-MPQ4OTBM.js → chunk-HX4X7KG3.js} +2 -2
  95. package/dist/{chunk-FDLOBR6P.js → chunk-HYT2R7LX.js} +2 -2
  96. package/dist/chunk-IKQVBVQL.js +40 -0
  97. package/dist/chunk-J6GLBBRK.js +4 -0
  98. package/dist/{chunk-ZTI4SBFV.js → chunk-J7A4PWFX.js} +2 -2
  99. package/dist/{chunk-OSR2GEHQ.js → chunk-JCSAZ35V.js} +2 -2
  100. package/dist/{chunk-ESIQ66Z7.js → chunk-JDU2IV3A.js} +2 -2
  101. package/dist/chunk-JFMI5SGB.js +4 -0
  102. package/dist/{chunk-W6STWDQI.js → chunk-JJP37RGX.js} +2 -2
  103. package/dist/chunk-JZ2A7LDM.js +5 -0
  104. package/dist/chunk-KNLQGXVH.js +80 -0
  105. package/dist/chunk-KVQCECPR.js +2 -0
  106. package/dist/{chunk-SQXRS7BG.js → chunk-KXXORBZ2.js} +2 -2
  107. package/dist/{chunk-DIUFNHRJ.js → chunk-L5KYH6U3.js} +2 -2
  108. package/dist/chunk-L6XHYJPZ.js +21 -0
  109. package/dist/{chunk-2GRUZAQF.js → chunk-L7KTFEAV.js} +2 -2
  110. package/dist/{chunk-QBE3YX64.js → chunk-LDXHR5EL.js} +2 -2
  111. package/dist/{chunk-HEHOQQKH.js → chunk-MHGDSBFX.js} +2 -2
  112. package/dist/{chunk-PWWAJSKV.js → chunk-MLQVVDG3.js} +2 -2
  113. package/dist/chunk-MOKUWRHO.js +3 -0
  114. package/dist/{chunk-VQILFTEH.js → chunk-MPYAPMNE.js} +2 -2
  115. package/dist/{chunk-UICY4GTQ.js → chunk-MV6SPXCR.js} +2 -2
  116. package/dist/{chunk-HYO3NP5Q.js → chunk-MZPXPSUJ.js} +2 -2
  117. package/dist/{chunk-VZRNID6A.js → chunk-N55KIE46.js} +2 -2
  118. package/dist/{chunk-YF5IB2LF.js → chunk-NB4D3BNM.js} +2 -2
  119. package/dist/{chunk-VVZSBTSU.js → chunk-NGKBOT6G.js} +2 -2
  120. package/dist/{chunk-NJITK2GP.js → chunk-NJGKXKQF.js} +2 -2
  121. package/dist/chunk-NJQISBL4.js +8 -0
  122. package/dist/{chunk-T4N4P2K5.js → chunk-NJT3ZEKY.js} +2 -2
  123. package/dist/{chunk-FPYLNQPT.js → chunk-NKMKZP6A.js} +2 -2
  124. package/dist/chunk-NODFZ6ED.js +2 -0
  125. package/dist/{chunk-BRV7PIFF.js → chunk-NSM5IEVW.js} +2 -2
  126. package/dist/{chunk-3WR4E3A3.js → chunk-NTGUVNR2.js} +2 -2
  127. package/dist/{chunk-VUPHCS7Y.js → chunk-NU3KFF2O.js} +2 -2
  128. package/dist/chunk-NWLVNU66.js +557 -0
  129. package/dist/{chunk-D4N5SQ2M.js → chunk-NYKZMCRC.js} +2 -2
  130. package/dist/{chunk-VNLGKHS6.js → chunk-O6BUXZEH.js} +2 -2
  131. package/dist/chunk-ODPDP7A4.js +3 -0
  132. package/dist/{chunk-JTQVMR42.js → chunk-OHIV323X.js} +2 -2
  133. package/dist/chunk-OIAPEKMT.js +3 -0
  134. package/dist/chunk-OIOC5EHF.js +3 -0
  135. package/dist/{chunk-YBGKCQIS.js → chunk-ONPPQM4G.js} +2 -2
  136. package/dist/{chunk-64BFSI5I.js → chunk-OUHEZBYI.js} +2 -2
  137. package/dist/{chunk-L6PJPETJ.js → chunk-OVGYW7UD.js} +2 -2
  138. package/dist/{chunk-I55I7XXP.js → chunk-OYKU4B3Y.js} +2 -2
  139. package/dist/{chunk-J66VOFW6.js → chunk-POBJ6FR2.js} +2 -2
  140. package/dist/{chunk-CWFP7GM5.js → chunk-PSZPMMWN.js} +2 -2
  141. package/dist/chunk-PXTRBKRK.js +3 -0
  142. package/dist/{chunk-HKGFPJ4T.js → chunk-Q5JRIHT3.js} +2 -2
  143. package/dist/{chunk-P42EIXTA.js → chunk-Q7ATHARX.js} +2 -2
  144. package/dist/{chunk-JYR66JN5.js → chunk-Q7CSKIDM.js} +2 -2
  145. package/dist/{chunk-TRNAEQ6P.js → chunk-QBQE7ZJ5.js} +2 -2
  146. package/dist/{chunk-DULC3QFP.js → chunk-QH22UIXP.js} +2 -2
  147. package/dist/chunk-QXCKQTKR.js +60 -0
  148. package/dist/{chunk-ODDUPDP7.js → chunk-RBAD4GJ2.js} +5 -5
  149. package/dist/{chunk-IZDPJ2QI.js → chunk-RMDPFPNW.js} +2 -2
  150. package/dist/chunk-ROPJDEJZ.js +4 -0
  151. package/dist/{chunk-EKV5HX33.js → chunk-RVZC6TJE.js} +2 -2
  152. package/dist/{chunk-XFA4SSO3.js → chunk-S4QZBKSR.js} +2 -2
  153. package/dist/{chunk-D2DHWI3D.js → chunk-SCPMZ73U.js} +2 -2
  154. package/dist/{chunk-PZL5T7SU.js → chunk-SIAP5RGI.js} +2 -2
  155. package/dist/{chunk-7IWV2EG3.js → chunk-SIX4RFR3.js} +2 -2
  156. package/dist/{chunk-DYGHBZ2N.js → chunk-SKKXTABJ.js} +2 -2
  157. package/dist/{chunk-F7DY272B.js → chunk-SSRFUQBD.js} +2 -2
  158. package/dist/chunk-SYVJEEUJ.js +3 -0
  159. package/dist/{chunk-FGA2U4OR.js → chunk-T3CZAZSI.js} +2 -2
  160. package/dist/chunk-T3I6NHBH.js +2 -0
  161. package/dist/{chunk-EQHFIL6T.js → chunk-T6DWDI5E.js} +2 -2
  162. package/dist/chunk-T6HRIROJ.js +7 -0
  163. package/dist/{chunk-GSP44ENC.js → chunk-TAA7HXHE.js} +2 -2
  164. package/dist/{chunk-BQGB4HBD.js → chunk-TJ2JQYT3.js} +2 -2
  165. package/dist/{chunk-XPDPNWTQ.js → chunk-TULNMD5T.js} +19 -19
  166. package/dist/chunk-U2FPY5XA.js +3 -0
  167. package/dist/chunk-U3SXIMII.js +38 -0
  168. package/dist/{chunk-NOGJXYFO.js → chunk-U6KCHXJ4.js} +2 -2
  169. package/dist/chunk-UH3XSKS5.js +9 -0
  170. package/dist/{chunk-AFHTBORT.js → chunk-UIFUZVCC.js} +2 -2
  171. package/dist/{chunk-7BWFZPPZ.js → chunk-UXKURIVI.js} +2 -2
  172. package/dist/{chunk-2E7CX53V.js → chunk-V2RBODHL.js} +2 -2
  173. package/dist/{chunk-KLFEXGQA.js → chunk-VBKUWB6N.js} +2 -2
  174. package/dist/{chunk-WUN6KBHV.js → chunk-VBV6ALJE.js} +2 -2
  175. package/dist/{chunk-GZIUDL6G.js → chunk-VDGFWCQV.js} +2 -2
  176. package/dist/chunk-VDSDOEWF.js +2 -0
  177. package/dist/{chunk-WDNVY4E7.js → chunk-VZPWVCLN.js} +2 -2
  178. package/dist/chunk-WDSFQDPN.js +2 -0
  179. package/dist/{chunk-CIYLO6SI.js → chunk-WFA35BGR.js} +2 -2
  180. package/dist/{chunk-LMZ5PRUV.js → chunk-WLMP3OCW.js} +2 -2
  181. package/dist/{chunk-3SVF22I5.js → chunk-WSA52GOR.js} +2 -2
  182. package/dist/{chunk-VMPRET3I.js → chunk-X3YVZAKZ.js} +2 -2
  183. package/dist/{chunk-GYIZ4NXB.js → chunk-X6OGVFIT.js} +2 -2
  184. package/dist/{chunk-6HFCYNYE.js → chunk-XKXTR6ZI.js} +2 -2
  185. package/dist/{chunk-6VVV4WRR.js → chunk-Y5DFAW5W.js} +2 -2
  186. package/dist/chunk-YSYPDRD5.js +3 -0
  187. package/dist/{chunk-TQPCBMWT.js → chunk-ZFVPWH62.js} +2 -2
  188. package/dist/chunk-ZGIHTH27.js +2 -0
  189. package/dist/{chunk-OR2E3AGZ.js → chunk-ZGIQN2SX.js} +2 -2
  190. package/dist/{chunk-WNTFFKAX.js → chunk-ZHG4WAHR.js} +2 -2
  191. package/dist/{chunk-DTZCKZEU.js → chunk-ZKB2XUEN.js} +2 -2
  192. package/dist/chunk-ZLMXIQLC.js +21 -0
  193. package/dist/chunk-ZMCQIHI4.js +2 -0
  194. package/dist/cli-main.js +2 -2
  195. package/dist/code-TAVIKWJI.js +2 -0
  196. package/dist/code-result-json-5FEFQCAQ.js +2 -0
  197. package/dist/{command-descriptors-P34VABY5.js → command-descriptors-7BKH53Y3.js} +124 -124
  198. package/dist/dataflow-GFBTVDH3.js +2 -0
  199. package/dist/dependence-slice-GWGQCODG.js +2 -0
  200. package/dist/deps-4QHVDPYA.js +2 -0
  201. package/dist/direct-navigation-4UBC6HNW.js +3 -0
  202. package/dist/entry-map-QCTF4RVY.js +2 -0
  203. package/dist/files-M2UBF5HJ.js +2 -0
  204. package/dist/frontend-profile-roles-D7eCum8P.d.ts +10 -0
  205. package/dist/{health-CPp2Jf1Z.d.ts → health-BI2a9WPy.d.ts} +60 -2
  206. package/dist/hierarchy-2UIHRLW4.js +2 -0
  207. package/dist/imports-WIE3YZOB.js +2 -0
  208. package/dist/index.d.ts +1 -1
  209. package/dist/index.js +1 -1
  210. package/dist/members-YKD636DA.js +2 -0
  211. package/dist/methods-VDF4IMYG.js +2 -0
  212. package/dist/output-continuation-command-4UMDOOLO.js +3 -0
  213. package/dist/output-pagination-2GME6OPY.js +19 -0
  214. package/dist/postinstall.js +1 -1
  215. package/dist/project-reindex-XEQTRCV5.js +3 -0
  216. package/dist/queries/affected.js +1 -1
  217. package/dist/queries/anchors.d.ts +1 -1
  218. package/dist/queries/anchors.js +1 -1
  219. package/dist/queries/architecture.js +1 -1
  220. package/dist/queries/bottlenecks.js +1 -1
  221. package/dist/queries/by-kind.js +1 -1
  222. package/dist/queries/call-graph.d.ts +2 -0
  223. package/dist/queries/call-graph.js +1 -1
  224. package/dist/queries/change-surface.js +1 -1
  225. package/dist/queries/cleanup-plan.js +1 -1
  226. package/dist/queries/co-change.d.ts +20 -2
  227. package/dist/queries/co-change.js +1 -1
  228. package/dist/queries/code.js +1 -1
  229. package/dist/queries/complexity-hotspots.js +1 -1
  230. package/dist/queries/complexity.js +1 -1
  231. package/dist/queries/context.js +1 -1
  232. package/dist/queries/convergence.js +1 -1
  233. package/dist/queries/coupling.js +1 -1
  234. package/dist/queries/cycles.js +1 -1
  235. package/dist/queries/dataflow.js +1 -1
  236. package/dist/queries/dead.d.ts +2 -0
  237. package/dist/queries/dead.js +1 -1
  238. package/dist/queries/decorative-checkers.js +1 -1
  239. package/dist/queries/deep-chains.js +1 -1
  240. package/dist/queries/dependence-slice.js +1 -1
  241. package/dist/queries/dependency-depth.js +1 -1
  242. package/dist/queries/deps.js +1 -1
  243. package/dist/queries/diff-impact.js +1 -1
  244. package/dist/queries/doc-drift.js +1 -1
  245. package/dist/queries/drift.js +1 -1
  246. package/dist/queries/duplicate-bodies.d.ts +28 -1
  247. package/dist/queries/duplicate-bodies.js +1 -1
  248. package/dist/queries/entry-map.d.ts +1 -1
  249. package/dist/queries/entry-map.js +1 -1
  250. package/dist/queries/evidence.js +1 -1
  251. package/dist/queries/extract-candidates.d.ts +50 -23
  252. package/dist/queries/extract-candidates.js +1 -1
  253. package/dist/queries/fan.js +1 -1
  254. package/dist/queries/files.js +1 -1
  255. package/dist/queries/health.d.ts +1 -1
  256. package/dist/queries/health.js +1 -1
  257. package/dist/queries/hierarchy.js +1 -1
  258. package/dist/queries/hotspots.js +1 -1
  259. package/dist/queries/imports.js +1 -1
  260. package/dist/queries/incomplete-migration.js +1 -1
  261. package/dist/queries/index.d.ts +4 -3
  262. package/dist/queries/index.js +1 -1
  263. package/dist/queries/isolated.js +1 -1
  264. package/dist/queries/locality-candidates.js +1 -1
  265. package/dist/queries/members.js +1 -1
  266. package/dist/queries/methods.js +1 -1
  267. package/dist/queries/not-implemented.js +1 -1
  268. package/dist/queries/outline.js +1 -1
  269. package/dist/queries/passthrough-candidates.d.ts +9 -1
  270. package/dist/queries/passthrough-candidates.js +1 -1
  271. package/dist/queries/plan-context.js +1 -1
  272. package/dist/queries/react-component-duplicates.d.ts +19 -3
  273. package/dist/queries/react-component-duplicates.js +1 -1
  274. package/dist/queries/react-hook-candidates.d.ts +22 -3
  275. package/dist/queries/react-hook-candidates.js +1 -1
  276. package/dist/queries/react-large-component-pressure.d.ts +17 -3
  277. package/dist/queries/react-large-component-pressure.js +1 -1
  278. package/dist/queries/recent-duplicates.js +1 -1
  279. package/dist/queries/redundant-reexports.js +1 -1
  280. package/dist/queries/reference-neighborhood.js +1 -1
  281. package/dist/queries/reference-reachability.js +1 -1
  282. package/dist/queries/refs.js +1 -1
  283. package/dist/queries/self-audit.d.ts +7 -1
  284. package/dist/queries/self-audit.js +1 -1
  285. package/dist/queries/similar-chains.js +1 -1
  286. package/dist/queries/similar-files.js +1 -1
  287. package/dist/queries/similar-signatures.js +1 -1
  288. package/dist/queries/similar.js +1 -1
  289. package/dist/queries/slice.js +1 -1
  290. package/dist/queries/source-inspection.js +1 -1
  291. package/dist/queries/source-search.js +1 -1
  292. package/dist/queries/stale-abstractions.js +1 -1
  293. package/dist/queries/surface.js +1 -1
  294. package/dist/queries/symbols.js +1 -1
  295. package/dist/queries/system-map.d.ts +1 -1
  296. package/dist/queries/system-map.js +1 -1
  297. package/dist/queries/system.js +1 -1
  298. package/dist/queries/test-quality.js +1 -1
  299. package/dist/queries/trace.js +1 -1
  300. package/dist/queries/twin-ab.js +1 -1
  301. package/dist/queries/twin-drift.d.ts +22 -6
  302. package/dist/queries/twin-drift.js +1 -1
  303. package/dist/queries/unused-imports.js +1 -1
  304. package/dist/queries/unused-params.js +1 -1
  305. package/dist/queries/value-flow.js +1 -1
  306. package/dist/queries/vue-component-duplicates.js +1 -1
  307. package/dist/queries/vue-composable-candidates.js +1 -1
  308. package/dist/queries/vue-large-view-pressure.js +1 -1
  309. package/dist/queries/wrapper-candidates.d.ts +16 -1
  310. package/dist/queries/wrapper-candidates.js +1 -1
  311. package/dist/query-service-fastpath.js +5 -5
  312. package/dist/query-service-server.js +2 -2
  313. package/dist/refs-JNK5CLM7.js +2 -0
  314. package/dist/refs-pagination-6BLRYGMV.js +2 -0
  315. package/dist/reindex-worker.js +10 -10
  316. package/dist/reindex.js +18 -18
  317. package/dist/runtime.js +4 -4
  318. package/dist/rust-semantic-session-server.js +1 -1
  319. package/dist/rust-semantic-session-worker.js +1 -1
  320. package/dist/rust-semantic-worker.js +1 -1
  321. package/dist/slice-PHPVNCWX.js +2 -0
  322. package/dist/surface-MQX5MPIV.js +2 -0
  323. package/dist/{symbol-resolution-WD5EU5JE.js → symbol-resolution-DBLVXLBC.js} +2 -2
  324. package/dist/system-JOPKV4OG.js +2 -0
  325. package/dist/trace-I2P2YFH4.js +2 -0
  326. package/dist/typescript-mailbox-worker.js +1 -1
  327. package/dist/value-flow-JJVMF7NP.js +2 -0
  328. package/dist/watch-server.js +3 -3
  329. package/docs/COMMAND_REFERENCE.md +2 -2
  330. package/docs/DETECTOR_GUIDE.md +51 -12
  331. package/docs/accuracy-audit-checklist.md +36 -13
  332. package/docs/locality-analyzer-design.md +9 -9
  333. package/package.json +2 -2
  334. package/skills/conductor/SKILL.md +110 -0
  335. package/skills/conductor/agents/openai.yaml +4 -0
  336. package/skills/principal-maintainability-review/SKILL.md +273 -0
  337. package/skills/principal-maintainability-review/agents/openai.yaml +4 -0
  338. package/skills/scip-calibrate/SKILL.md +102 -0
  339. package/skills/scip-calibrate/agents/openai.yaml +4 -0
  340. package/skills/scip-claim-audit/SKILL.md +113 -0
  341. package/skills/scip-claim-audit/agents/openai.yaml +4 -0
  342. package/skills/scip-probe-reachability/SKILL.md +93 -0
  343. package/skills/scip-probe-reachability/agents/openai.yaml +4 -0
  344. package/skills/scip-root-cause/SKILL.md +160 -0
  345. package/skills/scip-root-cause/agents/openai.yaml +4 -0
  346. package/skills/scip-system-compression/SKILL.md +252 -0
  347. package/skills/scip-system-compression/agents/openai.yaml +4 -0
  348. package/skills/scip-system-compression/references/compression-atlas.md +116 -0
  349. package/skills/scip-system-compression/references/compression-patterns.md +87 -0
  350. package/skills/scip-twin-drift/SKILL.md +109 -0
  351. package/skills/scip-twin-drift/agents/openai.yaml +4 -0
  352. package/dist/by-kind-XI2CSWEY.js +0 -2
  353. package/dist/call-graph-UONR6JR5.js +0 -2
  354. package/dist/call-graph-evidence-lZa2dwQA.d.ts +0 -11
  355. package/dist/chunk-2R3V3PSD.js +0 -4
  356. package/dist/chunk-2WC2OEDO.js +0 -4
  357. package/dist/chunk-3FHOF22C.js +0 -21
  358. package/dist/chunk-3JKSW6LJ.js +0 -2
  359. package/dist/chunk-3L2ZBPEX.js +0 -133
  360. package/dist/chunk-3PJABJSU.js +0 -2
  361. package/dist/chunk-4FTZ4P5G.js +0 -2
  362. package/dist/chunk-4UX2F3JX.js +0 -2
  363. package/dist/chunk-5ENOG4VP.js +0 -61
  364. package/dist/chunk-66DVSJQG.js +0 -455
  365. package/dist/chunk-AVRYW5OZ.js +0 -2
  366. package/dist/chunk-BDUVI7TO.js +0 -3
  367. package/dist/chunk-CEEZJXEF.js +0 -2
  368. package/dist/chunk-CJZXN4NU.js +0 -2
  369. package/dist/chunk-COF23M5F.js +0 -2
  370. package/dist/chunk-DHUIOLDT.js +0 -2
  371. package/dist/chunk-DRENNWRG.js +0 -2
  372. package/dist/chunk-E5R6AQ73.js +0 -40
  373. package/dist/chunk-E73UNJTF.js +0 -38
  374. package/dist/chunk-EVFUMY4R.js +0 -3
  375. package/dist/chunk-FBN2FGXG.js +0 -2
  376. package/dist/chunk-FFRKR4EQ.js +0 -2
  377. package/dist/chunk-GAS2LJMP.js +0 -3
  378. package/dist/chunk-HVF5VBG6.js +0 -2
  379. package/dist/chunk-JGKUET5J.js +0 -3
  380. package/dist/chunk-JWTGMPIT.js +0 -80
  381. package/dist/chunk-KFOYCQAJ.js +0 -9
  382. package/dist/chunk-KYSDI3GE.js +0 -5
  383. package/dist/chunk-LDVT66YM.js +0 -2
  384. package/dist/chunk-LQRQN2XA.js +0 -2
  385. package/dist/chunk-MNV5FSBW.js +0 -3
  386. package/dist/chunk-MV3CDXPI.js +0 -38
  387. package/dist/chunk-N5B2NILC.js +0 -5
  388. package/dist/chunk-NOYBFVJA.js +0 -554
  389. package/dist/chunk-NWQXSFFU.js +0 -3
  390. package/dist/chunk-OLIWTZI3.js +0 -3
  391. package/dist/chunk-PP7KNN7L.js +0 -2
  392. package/dist/chunk-PU7T5QYQ.js +0 -2
  393. package/dist/chunk-QGVTFRY2.js +0 -7
  394. package/dist/chunk-QOJONDS7.js +0 -2
  395. package/dist/chunk-RBLQNW26.js +0 -20
  396. package/dist/chunk-RTQ7NEKG.js +0 -81
  397. package/dist/chunk-TPFHAQ2G.js +0 -2
  398. package/dist/chunk-TQZV7KV4.js +0 -2
  399. package/dist/chunk-TY7CRN3Z.js +0 -2
  400. package/dist/chunk-W7CXK74K.js +0 -2
  401. package/dist/chunk-WB3WYIRE.js +0 -4
  402. package/dist/chunk-WK46TNUM.js +0 -3
  403. package/dist/chunk-WYCTJDVR.js +0 -2
  404. package/dist/chunk-XRYABF57.js +0 -8
  405. package/dist/chunk-YPWHBBIS.js +0 -2
  406. package/dist/chunk-YSH6U3L4.js +0 -3
  407. package/dist/chunk-YU5DZUZI.js +0 -10
  408. package/dist/chunk-YWO5DDRC.js +0 -16
  409. package/dist/chunk-ZF5KHH7C.js +0 -2
  410. package/dist/chunk-ZOHS7AQV.js +0 -21
  411. package/dist/code-MI6F2TTU.js +0 -2
  412. package/dist/code-result-json-FXALY4HE.js +0 -2
  413. package/dist/dataflow-4KEMJPC6.js +0 -2
  414. package/dist/dependence-slice-R7FPWD5M.js +0 -2
  415. package/dist/deps-7EMQUYUT.js +0 -2
  416. package/dist/direct-navigation-6YO234F2.js +0 -3
  417. package/dist/entry-map-KOOLR26E.js +0 -2
  418. package/dist/files-OPIPJIGZ.js +0 -2
  419. package/dist/hierarchy-QPD2CAER.js +0 -2
  420. package/dist/imports-M6HUXRXC.js +0 -2
  421. package/dist/members-I5MEFOCT.js +0 -2
  422. package/dist/methods-5JYGGHXA.js +0 -2
  423. package/dist/output-continuation-command-UPQAAKBP.js +0 -3
  424. package/dist/output-pagination-3OFL2MJV.js +0 -19
  425. package/dist/project-reindex-UKKQ5PLS.js +0 -3
  426. package/dist/refs-PSU4JZZW.js +0 -2
  427. package/dist/refs-pagination-JG6CJMRC.js +0 -2
  428. package/dist/slice-HYRATV64.js +0 -2
  429. package/dist/surface-VTGDYWF5.js +0 -2
  430. package/dist/system-LRQNFOR2.js +0 -2
  431. package/dist/trace-F4B6OLL4.js +0 -2
  432. package/dist/value-flow-VRPZY72V.js +0 -2
@@ -1,554 +0,0 @@
1
- #!/usr/bin/env node
2
- import{$a as gf,$b as Hs,$c as ne,Aa as Rt,Ab as xe,Ac as ci,Ae as rg,B as vl,Ba as ks,Bb as fn,Bc as Df,C as Cl,Ca as ni,Cb as eo,Cc as Mf,Ce as na,Da as _t,Db as vf,Dc as li,Dd as Vf,E as Zp,Eb as Cf,Ec as ui,Fa as wl,Fb as se,Fc as Tf,G as ef,Ga as uf,Gb as xf,Gc as U,Ge as fi,Hb as $s,Hc as ve,Ia as br,Ib as Dl,Ic as Af,Jb as Ml,Jc as Ff,Kb as vr,Kc as no,Lb as to,Lc as qs,Ld as Yf,M as xl,Mc as kf,Md as mi,Me as ig,Na as df,Nc as Oe,Nd as Vs,Ne as og,Oa as Qi,Ob as J,Oc as Gs,Od as Ys,Oe as sg,Pa as Nn,Pb as On,Pc as Re,Pd as pi,Pe as ag,Qa as me,Qb as Tl,Qc as q,Qd as Pt,Qe as cg,Ra as mf,Rb as K,Rc as Al,Sb as Rf,Sc as jn,Sd as Rr,T as tf,Ta as Gt,Tb as Ef,Tc as Nf,Ua as Et,Ub as js,Uc as _f,Ud as Jf,Va as dt,Vb as It,Vc as Of,Vd as Xf,Wb as zt,Wc as Bf,Wd as Er,Xb as If,Xc as zs,Xd as Qf,Y as nf,Ya as pf,Yc as hn,Yd as yn,Za as ff,Zc as di,_ as yr,_a as Ll,_b as oi,_c as $f,_d as Js,ab as Q,ac as wt,ad as Qe,ae as qn,bb as ri,bc as si,bd as xr,be as Ir,c as Xi,cb as hf,cc as wf,cd as Ks,ce as Xs,da as rf,db as yf,dd as Ot,e as Vp,ec as Cr,ed as Hn,fb as Pl,fc as ae,fd as Kt,ff as Bl,gb as bf,gc as Lf,gd as jf,h as Yp,hb as Zi,hc as ai,hd as Hf,hf as $l,i as Ms,ia as Rl,ib as be,ic as Us,id as Uf,j as it,jc as Bn,jd as Fl,je as Zf,jf as lg,k as _e,ka as As,kc as Ae,kd as qf,la as El,m as mn,ma as of,me as Nl,n as Ts,na as sf,nb as Sf,nd as kl,ne as Qs,o as pn,oa as Ye,ob as N,od as ro,of as ug,p as ei,pa as Je,pb as ii,pd as Gf,pe as Zs,pf as dg,qa as xt,qb as Ns,qc as gn,qd as Un,qe as Gn,ra as Fs,rb as mt,rc as $n,rd as zf,re as ea,s as ti,sa as af,sb as Sr,sc as Pf,sd as Kf,se as eg,t as Ct,ta as cf,tb as Te,tc as T,td as Wf,te as ta,u as Ve,ub as W,uc as z,ue as tg,uf as mg,vb as _n,vc as Lt,ve as oo,vf as pg,w as Jp,wa as lf,wb as V,wc as Xe,wf as fg,x as Sl,xa as Z,xb as _s,xc as Se,xd as io,xe as _l,y as Xp,yb as Os,yc as pe,yd as Ws,ye as Ol,z as Qp,za as Il,zb as Bs,zc as He,ze as ng}from"./chunk-66DVSJQG.js";import{existsSync as Lw}from"fs";import{isAbsolute as gg,join as Pw}from"path";function pt(e,t){let n=jl(e,t,{allowMultiple:!1})[0]?.relativePath;return n||bg(e,t)}function wr(e,t){return jl(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function hg(e,t){let n=jl(e,t,{allowMultiple:!0});return n.length===1?n[0].relativePath:null}function yg(e,t){let n=ri(e,t,{allowMultiple:!0,requirePathMatch:!0});return n.length===1?n[0].relativePath:null}function bg(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=gg(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,i=Pw(e.config.projectRoot,r);return Lw(i)?r:null}function jl(e,t,n){let r=bg(e,t);if(r)return ri(e,r,n).filter(a=>a.relativePath===r);let i=t.replace(/\\/g,"/").replace(/^\.\//,""),o=gg(i)||i.includes("/"),s=ri(e,t,{...n,requirePathMatch:o});if(s.length===0){if(o)return[];let a=ne(e,t);return!a||e.isIgnored(a.relativePath)?[]:[{relativePath:a.relativePath,score:700}]}return s}function Sg(e,t){let n=hg(e,t);if(!n)return[];let r=qs(e,[n],{sort:!0});if(r.length===0)return[];let i=Math.max(0,_n(W(e,n)).length-1),o=r.map(c=>({symbol:c.symbol,shortName:c.shortName,startLine:c.startLine,endLine:Math.min(c.endLine,i),signature:c.signature,children:[]})),s=new Map;for(let c of o)s.set(c.symbol,c);let a=[];for(let c=0;c<r.length;c++){let l=r[c],u=o[c];if(l.enclosingSymbol&&s.has(l.enclosingSymbol)){s.get(l.enclosingSymbol).children.push(u);continue}let d=null,m=1/0;for(let p of o)if(p!==u&&p.startLine<=u.startLine&&p.endLine>=u.endLine){if(p.startLine===u.startLine&&p.endLine===u.endLine&&!Mf(p.symbol,u.symbol))continue;let g=p.endLine-p.startLine;g<m&&(m=g,d=p)}d?d.children.push(u):a.push(u)}return a}import{basename as OL,extname as eh}from"path";function ft(e,t){let n=V(e,t.relativePath);if(n.length===0)return!1;let r=z(t.symbol);if(!r)return!1;let i=n.slice(Math.max(0,t.startLine-2),t.startLine+1).join(`
3
- `),o=xe(r);return new RegExp(`^\\s*export\\s+(?:default\\s+)?(?:(?:async\\s+)?function\\s+${o}\\b|(?:abstract\\s+)?class\\s+${o}\\b|(?:interface|type|enum|namespace|module)\\s+${o}\\b|(?:const|let|var)\\s+${o}\\b)`,"m").test(i)?!0:Dw(n,r)}function Dw(e,t){if(!t)return!1;let n=new RegExp(`^\\s*export\\s*\\{[^}\\n]*\\b${xe(t)}\\b`);return e.some(r=>n.test(r))}import{createHash as Mw}from"crypto";import{isUtf8 as Tw}from"buffer";import{TextDecoder as Aw}from"util";var Cg=new Aw("utf-8",{fatal:!0});function Ul(e){return Fs(e.config.projectRoot)}function ra(e,t){let n=mn(t),r;try{r=El(e.config.projectRoot,n,{inputKind:"repository text file"})}catch(o){if(Je(o)||o instanceof Rl)return null;throw o}let i=Fw(r);return i===null?null:Rg(n,r,i,Ig(e),Eg(e))}function xg(e,t={}){let n=[],r=ia(e,t,i=>n.push(i));return{files:n,candidateFiles:r.candidateFiles,scannedBytes:r.scannedBytes,skippedBinaryPaths:r.skippedBinaryPaths,skippedUnreadablePaths:r.skippedUnreadablePaths,skippedOversizedPaths:r.skippedOversizedPaths}}function ia(e,t,n){let r=Ul(e).filter(f=>!t.scope||f.includes(t.scope)),i=Ig(e),o=Eg(e),s=[],a=[],c=[],l=0,u=0,d={aligned:0,stale:0,unavailable:0},m=t.literalBytes?Buffer.isBuffer(t.literalBytes)?[t.literalBytes]:[...t.literalBytes]:[],p=m.length>0?Buffer.allocUnsafe(1024*1024):void 0;for(let f of r){let g,h,b=[],S=o.has(f);try{if(m.length>0){let x=m.length===1?of(e.config.projectRoot,f,m[0],{inputKind:"repository text file",computeSha256:S,scratchBuffer:p}):sf(e.config.projectRoot,f,m,{inputKind:"repository text file",computeSha256:S,scratchBuffer:p});if(!x.isUtf8Text){s.push(f);continue}l+=x.byteLength,u+=1,h=x.sha256;let v=Hl(f,h,i,o);if(d[v.state]+=1,b="matchedLiteralIndexes"in x?x.matchedLiteralIndexes:x.includesLiteral?[0]:[],b.length===0||!x.bytes)continue;g=x.bytes}else g=El(e.config.projectRoot,f,{inputKind:"repository text file"})}catch(x){if(x instanceof Rl){c.push(f);continue}if(Je(x))continue;a.push(f);continue}if(m.length===0&&!wg(g)){s.push(f);continue}if(m.length===0){l+=g.byteLength,u+=1,h=S?Lg(g):void 0;let x=Hl(f,h,i,o);d[x.state]+=1}if(t.includeBytes&&!t.includeBytes(f,g))continue;let y=Cg.decode(g);n(Rg(f,g,y,i,o,h),b)}return{candidateFiles:r.length,scannedTextFiles:u,semanticFiles:d,scannedBytes:l,skippedBinaryPaths:s,skippedUnreadablePaths:a,skippedOversizedPaths:c}}function Rg(e,t,n,r,i,o){let s=o??Lg(t);return{relativePath:e,text:n,bytes:t.byteLength,freshness:{exactText:{state:"current",basis:"working-tree-read",sha256:s},semantic:Hl(e,s,r,i)}}}function Hl(e,t,n,r){if(!r.has(e))return{state:"unavailable",basis:"no-compiler-document"};let i=n.get(e);return!i||!t?{state:"unavailable",basis:"fingerprint-unavailable"}:{state:i===t?"aligned":"stale",basis:"indexed-input-fingerprint"}}function Eg(e){return new Set(e.all(`SELECT documents.relative_path FROM documents WHERE 1 = 1 ${e.pathExclusionsFor("documents")}`).map(t=>t.relative_path))}function Ig(e){let t=new Map;if(!e.generation.metadataRaw)return t;let n=br(e.generation.metadataRaw);if(n.kind!=="legacy"&&n.kind!=="supported")return t;let r=n.metadata.fingerprint;if(!vg(r)||!Array.isArray(r.files))return t;for(let i of r.files)!vg(i)||typeof i.path!="string"||typeof i.hash!="string"||t.set(i.path,i.hash);return t}function Fw(e){return wg(e)?Cg.decode(e):null}function wg(e){return!e.includes(0)&&Tw(e)}function Lg(e){return Mw("sha256").update(e).digest("hex")}function vg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{SymbolInformation_Kind as ue}from"@c4312/scip";var oa=new Map(Object.entries(ue).filter(([e,t])=>Number.isInteger(Number(e))&&typeof t=="string").map(([e,t])=>[Number(e),t])),Pg=new Map([...oa.entries()].map(([e,t])=>[t.toLowerCase(),e]));function so(e){return oa.get(e)??"Unknown"}function Wt(){return[ue.Function,ue.Method,ue.Macro,ue.Constructor,ue.Getter,ue.Setter,ue.StaticMethod,ue.SingletonMethod,ue.AbstractMethod,ue.ProtocolMethod,ue.TraitMethod]}function Dg(){return[ue.Class,ue.Interface,ue.Struct,ue.Trait,ue.Type,ue.TypeAlias,ue.Enum,ue.Union,ue.Protocol]}function e3(){return[ue.Constant,ue.Variable,ue.Value,ue.Field,ue.Property,ue.StaticDataMember,ue.StaticField,ue.StaticProperty,ue.StaticVariable,ue.EnumMember]}function Dt(e,t,n={}){let r=Lr(e,[t],{additive:n.additive,semantic:n.semantic,semanticEvidence:n.semanticEvidence}),i=n.callableOnly?(r.get(t.symbolId)??[]).filter(o=>Xe(o.symbol)||o.source==="ast-callsite"):r.get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}function zn(e,t,n){return bn(e,[t],n).get(t.symbolId)??[]}function bn(e,t,n){let r=Ow(e)?$w(e,t,{semantic:n.semantic!==!1,semanticEvidence:n.semanticEvidence}):Bw(e,n.semanticEvidence);return typeof n.limit!="number"?new Map(t.map(i=>[i.symbolId,r.get(i.symbolId)??[]])):new Map(t.map(i=>[i.symbolId,(r.get(i.symbolId)??[]).slice(0,n.limit)]))}var kw=me("caller-rows",{clearGroups:["whole-project"]}),Nw=me("targeted-caller-strategy",{clearGroups:["whole-project"]}),_w=2e4;function Ow(e){return Nw.get(e,()=>(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>_w)}function Bw(e,t){return kw.get(e,()=>{let n=ve(e),r=Lr(e,n,{semanticEvidence:t}),i=new Map;for(let a of n)i.set(a.symbol,a.symbolId);let o=new Map,s=new Map;for(let a of n){let c=r.get(a.symbolId);if(!(!c||c.length===0))for(let l of c){let u=i.get(l.symbol);if(u===void 0||u===a.symbolId)continue;let d=o.get(u);d||(d=[],o.set(u,d),s.set(u,new Set));let m=`${a.symbol}|${a.relativePath}`;s.get(u).has(m)||(s.get(u).add(m),d.push({symbol:a.symbol,file:a.relativePath,source:"caller-map-inversion",callEvidence:l.source}))}}return o})}function $w(e,t,n){let r=n.semantic&&n.semanticEvidence?t.flatMap(p=>{let f=jw(e,p);return f?[f]:[]}):[],i=new Map(r.map(p=>[p.symbolId,p])),o=n.semanticEvidence?.referenceMap(e,r)??new Map,s=Gf(e,t),a=new Set(t.map(p=>p.symbol)),l=[...new Set(t.flatMap(p=>Bn(e,"reverse",[p.relativePath])))].flatMap(p=>U(e,p)),u=new Map,d=Tg(e,l);for(let p of l)for(let f of d.get(p.symbolId)??[]){if(!a.has(f.symbol))continue;let g=u.get(f.symbol)??[];g.push({symbol:p.symbol,file:p.relativePath,source:"caller-map-inversion",callEvidence:f.source}),u.set(f.symbol,g)}let m=new Map;for(let p of t){let f=[],g=new Set,h=S=>{if(S.symbol===p.symbol)return;let y=`${S.symbol}|${S.file}`;g.has(y)||(g.add(y),f.push(S))};for(let S of u.get(p.symbol)??[])h(S);for(let S of s.get(p.symbolId)??[])S.file!==p.relativePath&&h({symbol:S.enclosingSymbol??S.file,file:S.file,source:"resolved-reference"});let b=i.get(p.symbolId);if(b)for(let S of o.get(b.symbolId)??[]){if(S.file===p.relativePath||e.isIgnored(S.file))continue;let y=Oe(U(e,S.file),S.line);h({symbol:y?.symbol??S.file,file:S.file,source:"semantic-reference"})}m.set(p.symbolId,f)}return m}function jw(e,t){let n=Wt().join(", "),r=Dg().join(", ");return e.get(`SELECT
4
- d.id AS documentId,
5
- gs.id AS symbolId,
6
- gs.symbol,
7
- d.relative_path AS relativePath,
8
- COALESCE(der.start_line, c.start_line) AS startLine,
9
- COALESCE(der.end_line, c.end_line) AS endLine,
10
- COALESCE(gs.display_name, '') AS leaf,
11
- NULL AS parentTypeName,
12
- CASE WHEN gs.kind IN (${n}) OR gs.symbol LIKE '%().' THEN 1 ELSE 0 END AS isFunctionLike,
13
- CASE WHEN gs.kind IN (${r}) THEN 1 ELSE 0 END AS isTypeLike,
14
- gs.kind AS kind,
15
- gs.documentation AS documentation,
16
- gs.enclosing_symbol AS enclosingSymbol
17
- FROM global_symbols gs
18
- LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
19
- LEFT JOIN chunks c ON c.document_id = der.document_id
20
- JOIN documents d ON d.id = COALESCE(der.document_id, c.document_id)
21
- WHERE gs.id = ?
22
- LIMIT 1`,t.symbolId)??null}function Lr(e,t,n={}){if(t.length===0)return new Map;let r=n.additive??!1,i=[],o=[];for(let u of t)se(u.relativePath)&&zt(e,u.relativePath)!==null?i.push(u):o.push(u);let s=new Map,a=new Map,c=u=>{for(let[d,m]of u){let p=s.get(d);p||(p=[],s.set(d,p));let f=a.get(d);f||(f=new Set,a.set(d,f));for(let g of m){let h=`${g.symbol}|${g.chunkId}`;f.has(h)||(f.add(h),p.push(g))}}};i.length>0&&c(Tg(e,i)),n.semantic!==!1&&n.semanticEvidence&&c(Kw(n.semanticEvidence.calleeMap(e,t)));let l=r?t:o;return l.length>0&&c(Gw(e,l)),s}function Tg(e,t){let n=new Map,r=Hw(t,n),i=Kt(e);for(let[o,s]of r){let a=zt(e,o);if(!a)continue;let c=kf(s);for(let l of a){let u=c.get(l.line);if(!u)continue;let d=Uw(e,o,i,l);d&&d.symbol!==u.symbol&&n.get(u.symbolId).push({symbol:d.symbol,file:d.file,chunkId:l.line,source:"ast-callsite",callsiteLine:l.line})}}return n}function Hw(e,t){let n=new Map;for(let r of e){let i=n.get(r.relativePath);i?i.push(r):n.set(r.relativePath,[r]),t.set(r.symbolId,[])}for(let r of n.values())r.sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine));return n}function Uw(e,t,n,r){let i=ai(e,t,r.calleeLeaf);if(i){let a=Ot(t,n.get(i.importedName)??[]).filter(c=>_e(i.sourcePath,c.file));return a.length===1?a[0]:null}let o=Ot(t,n.get(r.calleeLeaf)??[]);if(o.length===0)return null;let s=qw(e,t,o,r.calleeQualifier);return s||Hn(e,t,o,r.memberAccess,r.calleeQualifier)}function qw(e,t,n,r){if(!r||se(t)!=="clojure")return null;let o=ae(e,t).filter(s=>s.kind==="namespace"&&s.localName===r&&s.sourcePath).map(s=>s.sourcePath);for(let s of o){let a=n.find(c=>_e(s,c.file));if(a)return a}return n.find(s=>/`([^`]+)`\//.exec(s.symbol)?.[1]===r)??null}function Gw(e,t){if(t.length===0)return new Map;let r=ql(t.map(p=>p.documentId)).flatMap(p=>e.all(`SELECT c.document_id, c.id AS chunk_id, c.start_line, c.end_line, m.symbol_id
23
- FROM mentions m
24
- JOIN chunks c ON m.chunk_id = c.id
25
- WHERE m.role != 1
26
- AND c.document_id IN (${p.map(()=>"?").join(",")})`,...p)),i=new Map;for(let p of r)i.has(p.document_id)||i.set(p.document_id,[]),i.get(p.document_id).push(p);let s=ql(r.map(p=>p.symbol_id)).flatMap(p=>e.all(`SELECT gs.id AS symbol_id, gs.symbol,
27
- COALESCE(der.document_id, def_chunk.document_id) AS document_id
28
- FROM global_symbols gs
29
- LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
30
- LEFT JOIN (
31
- SELECT m.symbol_id, MIN(c.document_id) AS document_id
32
- FROM mentions m
33
- JOIN chunks c ON m.chunk_id = c.id
34
- WHERE m.role = 1
35
- AND m.symbol_id IN (${p.map(()=>"?").join(",")})
36
- GROUP BY m.symbol_id
37
- ) def_chunk ON def_chunk.symbol_id = gs.id
38
- WHERE gs.id IN (${p.map(()=>"?").join(",")})`,...p,...p)),a=ql([...t.map(p=>p.documentId),...s.flatMap(p=>p.document_id===null?[]:[p.document_id])]),c=new Map(a.flatMap(p=>e.all(`SELECT id, relative_path FROM documents
39
- WHERE id IN (${p.map(()=>"?").join(",")})`,...p).map(f=>[f.id,f.relative_path]))),l=new Map;for(let p of s)l.has(p.symbol_id)||l.set(p.symbol_id,{symbol:p.symbol,file:p.document_id!==null?c.get(p.document_id)??"":""});let u=new Map,d=c,m=zw(t);for(let[p,f]of m){let h=[...i.get(p)??[]].sort((x,v)=>x.start_line-v.start_line||x.end_line-v.end_line),b=[...f].sort((x,v)=>x.startLine-v.startLine||x.endLine-v.endLine),S=new Set,y=0;for(let x of b){for(;y<h.length&&h[y].start_line<=x.endLine;)S.add(h[y]),y+=1;for(let I of S)I.end_line<x.startLine&&S.delete(I);let v=new Set,C=[],R=null,E=()=>{if(R)return R;let I=d.get(x.documentId)??"",w=new Set;if(I){let A=$f(e,I),D=Math.max(0,x.startLine),k=Math.min(A.length-1,x.endLine);for(let L=D;L<=k;L+=1)for(let F of A[L])w.add(F)}return R=w,w};for(let I of S){if(I.symbol_id===x.symbolId)continue;let w=l.get(I.symbol_id);if(!w)continue;if(!(I.start_line>=x.startLine&&I.end_line<=x.endLine)){if(!(I.start_line<=x.endLine&&I.end_line>=x.startLine))continue;let L=z(w.symbol);if(!L||!E().has(L))continue}let D=`${w.symbol}|${I.chunk_id}`;v.has(D)||(v.add(D),C.push({...w,chunkId:I.chunk_id,source:"scip-chunk"}))}u.set(x.symbolId,C)}}return u}var Mg=500;function ql(e){let t=[...new Set(e)],n=[];for(let r=0;r<t.length;r+=Mg)n.push(t.slice(r,r+Mg));return n}function zw(e){let t=new Map;for(let n of e){let r=t.get(n.documentId);r?r.push(n):t.set(n.documentId,[n])}return t}function Kw(e){let t=new Map;for(let[n,r]of e){let i=[];for(let o of r)i.push({symbol:o.symbol,file:o.file,chunkId:-1,source:"semantic-callee",...o.callsiteLine===void 0?{}:{callsiteLine:o.callsiteLine}});t.set(n,i)}return t}var Ww=12,Vw=280;function gi(e,t,n,r){let i=Yw(e,t,n,r);if(i.size===0)return Zw();let o=[],s=new Set,a=(l,u,d,m)=>{if(u===t&&d<=r&&m>=n)return;let p=`${u}:${d}:${m}:${l}`;s.has(p)||(s.add(p),o.push({name:l,relativePath:u,startLine:d,endLine:m}))};for(let l of U(e,t))i.has(l.leaf)&&a(l.leaf,l.relativePath,l.startLine,l.endLine);for(let l of ae(e,t)){let u=l.localName;if(!u||!i.has(u)||!l.sourcePath||l.kind==="namespace")continue;let d=l.importedName==="default"?u:l.importedName;for(let m of jn(e,l.sourcePath,d,{maxReexportDepth:3}))a(u,m.relativePath,m.startLine,m.endLine)}o.sort(Fg);let c=o.map(l=>{let u=Jw(e,l);return u?{...l,source:u}:null}).filter(l=>l!==null).slice(0,Ww);return Gl(c)}function sa(e,t=[]){return Gl(Xw(e.flatMap(n=>n?.inline??[]),t))}function Ag(e){return e?e.inline.reduce((t,n)=>t+n.name.length+n.source.length+32,0):0}function Yw(e,t,n,r){let i=K(e,t),o=new Set;if(!i)return o;for(let s=n;s<=r;s+=1)for(let a of i.identifiersByLine[s]??[])o.add(a);return o}function Jw(e,t){if(t.startLine!==t.endLine)return null;let n=(V(e,t.relativePath)[t.startLine]??"").trim();if(!n||n.length>Vw)return null;let r=n.indexOf("=");if(r<0||n[r+1]===">")return null;let i=n.slice(r+1).replace(/(?:\/\/|#).*$/u,"").trim();if(!i||i.includes("${")||/\b(?:function|class|struct|interface|trait|enum|lambda)\b/u.test(i))return null;let s=i.replace(/(['"`])(?:\\.|(?!\1).)*\1/gu,"").replace(/\b(?:0[xX][\dA-Fa-f_]+|0[bB][01_]+|0[oO][0-7_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:[eE][+-]?\d+)?)n?\b/gu,""),a=new Set(["true","false","null","undefined","None","True","False"]);return(s.match(/[A-Za-z_][A-Za-z0-9_]*/gu)??[]).some(l=>!a.has(l))?null:n}function Xw(e,t){let n=new Map;for(let r of e){if(Qw(r,t))continue;let i=`${r.relativePath}:${r.startLine}:${r.endLine}:${r.name}`;n.has(i)||n.set(i,{...r})}return[...n.values()].sort(Fg)}function Qw(e,t){return t.some(n=>n.relativePath===e.relativePath&&n.startLine<=e.startLine&&n.endLine>=e.endLine)}function Fg(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||e.name.localeCompare(t.name)}function Gl(e){return{coverage:"indexed-project-literal-values",inline:e}}function Zw(){return Gl([])}var eL=12,tL=20,Kl=200,Wl=800,nL=.9,rL=64,iL=mf("behavior-construct-ranges"),Ng={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"},ma=["anchor","signature","binding","branch","loop","call","await","return","throw","mutation","shape","spread","catch","finally"],_g=[...ma,"lifecycle"],Og=["loop","await","throw","mutation","spread","catch","finally","lifecycle"],oL=new Set(["onBeforeMount","onBeforeUnmount","onMounted","onUnmounted","useEffect","useInsertionEffect","useLayoutEffect"]);var Bg=new Set(["object","object_pattern","dictionary","field_declaration_list","struct_expression","struct_pattern"]);function hi(e,t,n,r,i=[],o={}){let s=J(e,t);if(!s)return null;let a=V(e,t),c=ot(e,t,n,r,i),l=ga(e,t,c.startLine,c.endLine),u=l?.startLine??n,d=l?.endLine??r,m=(l?yi(s.rootNode,c.startLine,c.endLine):null)??vr(s.rootNode,u,d);if(!m)return null;let p=qg(m,a,u,d,i);if(!p||p.lines.length===0||p.lines.some(b=>b.text.length>Wl))return null;let f=EL(a,u,d),g=IL(p);if((o.requireSavings??!0)&&g>=f*nL)return null;let h=ma.filter(b=>p.lines.some(S=>S.signals.includes(b)));return{...l?{callable:{name:l.name,startLine:l.startLine,endLine:l.endLine}}:{},representation:"outline",constructKind:p.constructKind,signature:p.signature,lines:p.lines,signals:h,testCases:q(t)==="test"?ML(a,u,d):[],coverage:{sourceStatements:p.sourceStatements,representedStatements:p.sourceStatements,copiedStatements:p.copiedStatements,omittedStatements:0},rawCharacters:f,outlineCharacters:g,candidateLines:p.sourceStatements,omittedLines:0}}function pa(e,t,n,r,i){if(i.length===0)return[];let o=J(e,t);if(!o)return[];let s=V(e,t),a=ot(e,t,n,r,i),c=ga(e,t,a.startLine,a.endLine),l=c?.startLine??n,u=c?.endLine??r,d=(c?yi(o.rootNode,a.startLine,a.endLine):null)??vr(o.rootNode,l,u);if(!d)return[];let m=qg(d,s,l,u,i);return m?m.lines.filter(p=>p.text.length<=Wl&&p.signals.some(f=>["branch","loop","catch","finally"].includes(f))&&i.some(f=>f>=p.line&&f<=p.endLine)):[]}function $g(e,t,n,r){let i=J(e,t);if(!i)return null;let o=yi(i.rootNode,n,r)??vr(i.rootNode,n,r);if(!o)return null;let s=[],a=Jl(o),c=[];return Xl(o,o,l=>{if(co.has(l.type)||aL.has(l.type)){lL(s,c,l);return}if(fa.has(l.type)){uL(s,c,l);return}if(po.has(l.type)){dL(s,c,l);return}fo.has(l.type)&&mL(s,l)}),{facts:yL(s),terminals:Ug(a),unsupported:c}}function ot(e,t,n,r,i=[]){let o=i.filter(u=>u>=n&&u<=r),s=iL.get(e,t,W(e,t)??"",()=>new Map),a=`${n}:${r}:${o.join(",")}`,c=s.get(a);if(c)return s.delete(a),s.set(a,c),{startLine:c[0],endLine:c[1]};let l=sL(e,t,n,r,o);if(s.set(a,[l.startLine,l.endLine]),s.size>rL){let u=s.keys().next().value;u!==void 0&&s.delete(u)}return l}function sL(e,t,n,r,i){let o=J(e,t),s=[];if(i.length>0&&o){let u=[],d=i[0],m=d;for(let f of i)d=Math.min(d,f),m=Math.max(m,f);Kg(o.rootNode,d,m,f=>{bL(f)&&f.startPosition.row>=n&&f.endPosition.row<=r&&i.every(g=>f.startPosition.row<=g&&f.endPosition.row>=g)&&u.push(f),Kn.has(f.type)&&f.startPosition.row>=n&&f.endPosition.row<=r&&i.every(g=>f.startPosition.row<=g&&f.endPosition.row>=g)&&s.push(f)});let p=u.sort((f,g)=>f.endPosition.row-f.startPosition.row-(g.endPosition.row-g.startPosition.row)||f.startPosition.row-g.startPosition.row)[0];if(p)return{startLine:p.startPosition.row,endLine:p.endPosition.row}}let a=ga(e,t,n,r);if(a)return{startLine:a.startLine,endLine:a.endLine};if(i.length===0)return{startLine:n,endLine:r};let c=(K(e,t)?.callables??[]).filter(u=>u.startLine>=n&&u.endLine<=r&&i.every(d=>u.startLine<=d&&u.endLine>=d)).sort((u,d)=>u.endLine-u.startLine-(d.endLine-d.startLine)||u.startLine-d.startLine)[0];if(!o)return c?{startLine:c.startLine,endLine:c.endLine}:{startLine:n,endLine:r};let l=s.sort((u,d)=>u.endPosition.row-u.startPosition.row-(d.endPosition.row-d.startPosition.row)||u.startPosition.row-d.startPosition.row)[0];return l?{startLine:l.startPosition.row,endLine:l.endPosition.row}:c?{startLine:c.startLine,endLine:c.endLine}:{startLine:n,endLine:r}}function Vl(e,t,n,r,i={}){if(r-n+1<(i.minimumBodyLines??tL))return null;let s=zg(e,t,n,r,[],!1);if(!s)return null;let a=s.candidates.map(b=>({...b,signals:b.signals.filter(S=>S!=="anchor"&&S!=="signature")})).filter(b=>b.signals.length>0);if(a.length===0)return null;let c=PL(a),l=a.filter(b=>b.text.length<=Kl);if(l.length===0)return null;let u=Og.filter(b=>(c[b]??0)>0),d=u.filter(b=>b!=="await"),m=s.shapes.reduce((b,S)=>b+S.fields.length,0);if(d.length===0&&!((c.await??0)>0&&m>0)&&m<3)return null;let p=DL(l,c),f=new Map;for(let b of u){let S=p.find(y=>y.signals.includes(b));S&&f.set(S.line,S)}if(f.size===0){let b=p.find(S=>S.signals.includes("branch"));b&&f.set(b.line,b)}let g=Math.min(10,Math.max(1,i.maxLines??f.size)),h=new Map;for(let b of f.values()){if(h.size>=g)break;h.set(b.line,b)}return h.size>=a.length&&s.shapes.length===0?null:{owner:s.callable?.name??null,startLine:n,endLine:r,lines:[...h.values()].sort((b,S)=>b.line-S.line),shapes:s.shapes,signalCounts:c,candidateLines:a.length,omittedLines:a.length-h.size}}function Sn(e,t,n,r){let i=zg(e,t,n,r,[],!1);return i?new Map(i.candidates.map(o=>[o.line,o.signals.filter(s=>s!=="lifecycle")])):new Map}var Kn=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"]),gt=new Set(["block","body","compound_statement","declaration_list","statement_block"]),co=new Set(["if_expression","if_statement","unless","unless_statement"]),aL=new Set(["conditional_expression","ternary_expression"]),fa=new Set(["do_statement","enhanced_for_statement","for_expression","for_in_statement","for_of_statement","for_statement","loop_expression","while_statement"]),po=new Set(["match_expression","match_statement","switch_expression","switch_statement"]),jg=new Set(["case_statement","match_arm","switch_case","switch_default"]),fo=new Set(["try_expression","try_statement"]),la=new Set(["catch_clause","except_clause","rescue"]),uo=new Set(["ensure","finally_clause"]),lo=new Set(["else","else_clause"]),Hg=new Set(["raise_statement","return_statement","throw_statement"]),cL=new Set(["block_comment","comment","line_comment"]);function lL(e,t,n){let r=n.childForFieldName("condition")??Zl(n),i=n.childForFieldName("consequence")??n.childForFieldName("body")??n.namedChildren.find(c=>gt.has(c.type)),o=n.childForFieldName("alternative")??n.namedChildren.find(c=>lo.has(c.type));if(!r||!i){t.push(Ql(n,"conditional-fields-unresolved"));return}let s=Yt(r,"predicate",r.text),a=Yt(i,kg(i),"consequence");if(Vt(e,s,a,"predicate-consequence",{branchRole:"consequence"}),ua(e,s,i,"consequence"),o){let c=Yt(o,kg(o),"alternative");Vt(e,s,c,"predicate-alternative",{branchRole:"alternative"}),ua(e,s,o,"alternative");return}Vt(e,s,Yl(s,"otherwise continue"),"predicate-fallthrough",{branchRole:"fallthrough"})}function uL(e,t,n){let r=n.childForFieldName("body")??n.namedChildren.find(s=>gt.has(s.type));if(!r){t.push(Ql(n,"loop-body-unresolved"));return}let i=n.childForFieldName("condition"),o=Yt(i??n,"predicate",i?.text??Bt(n,r));Vt(e,o,Yt(r,"outcome","iteration"),"loop-iteration",{branchRole:"iteration"}),ua(e,o,r,"iteration"),Vt(e,o,Yl(o,"loop exits"),"loop-exit",{branchRole:"exit"})}function dL(e,t,n){let r=n.childForFieldName("body")??n.namedChildren.find(c=>gt.has(c.type)),i=n.childForFieldName("value")??n.childForFieldName("condition")??n.childForFieldName("subject")??Zl(n),o=fL(r??n);if(!i||o.length===0){t.push(Ql(n,"switch-cases-unresolved"));return}let s=Yt(i,"predicate",i.text),a=!1;for(let c of o){let l=hL(c);a||=l;let u=Bt(c,c.namedChildren.find(d=>da(d)));Vt(e,s,Yt(c,"outcome",u||(l?"default":"case")),l?"predicate-default":"predicate-case",{branchRole:l?"default":"case"}),ua(e,s,c,l?"default":"case")}a||Vt(e,s,Yl(s,"no case matched"),"predicate-fallthrough",{branchRole:"fallthrough"})}function mL(e,t){let n=Yt(t,"scope","try");for(let r of gL(t)){let i=uo.has(r.type),o=Yt(r,"handler",i?"finally":Bt(r,aa(r)));Vt(e,n,o,i?"finally-cleanup":"exception-handler",{branchRole:i?"finally":"catch"}),pL(e,o,r,i?"finally":"catch")}}function pL(e,t,n,r){for(let i of Jl(n)){let o=i.label.startsWith("throw")||i.label.startsWith("raise")?"throw":"return";Vt(e,t,i,o==="throw"?"handler-throw":"handler-return",{branchRole:r,terminalKind:o})}}function ua(e,t,n,r){for(let i of Jl(n)){let o=i.label.startsWith("throw")||i.label.startsWith("raise")?"throw":"return";Vt(e,t,i,o==="throw"?"predicate-throw":"predicate-return",{branchRole:r,terminalKind:o})}}function Vt(e,t,n,r,i){e.push({controller:t,outcome:n,subtype:r,attributes:i})}function Yt(e,t,n){return{kind:t,label:mo(n).slice(0,Wl),startLine:e.startPosition.row,endLine:e.endPosition.row,implicit:!1}}function Yl(e,t){return{...e,kind:"outcome",label:t,implicit:!0}}function kg(e){return Hg.has(e.type)?"terminal":"outcome"}function Jl(e){let t=[];return Xl(e,e,n=>{Hg.has(n.type)&&t.push(Yt(n,"terminal",n.text))}),Ug(t)}function Xl(e,t,n){n(t);for(let r of t.namedChildren)r!==e&&Kn.has(r.type)||Xl(e,r,n)}function fL(e){let t=[],n=r=>{for(let i of r.namedChildren)po.has(i.type)||(jg.has(i.type)?t.push(i):n(i))};return n(e),t}function gL(e){let t=[],n=r=>{for(let i of r.namedChildren)fo.has(i.type)||(la.has(i.type)||uo.has(i.type)?t.push(i):Kn.has(i.type)||n(i))};return n(e),t}function hL(e){let t=Bt(e,e.namedChildren.find(n=>da(n))).trim();return e.type==="switch_default"||/^(?:default\b|_\s*=>)/u.test(t)}function Ql(e,t){return{startLine:e.startPosition.row,endLine:e.endPosition.row,reason:t}}function yL(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 Ug(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 bL(e){return Kn.has(e.type)||fa.has(e.type)||po.has(e.type)||fo.has(e.type)||la.has(e.type)||uo.has(e.type)}function qg(e,t,n,r,i){let s=yi(e,n,r)??e,a=aa(s),c=[],l=0,u=0,d=(C,R,E,I,w=!1,A=!0)=>{let D=w?E.trim():mo(E);if(!D)return;let k=Math.max(n,C.startPosition.row),L=Math.min(r,C.endPosition.row);c.push({line:k,endLine:Math.max(k,L),depth:R,signals:ma.filter(F=>I.includes(F)||F==="anchor"&&i.some(P=>P>=k&&P<=L)),text:D,copied:w}),A&&(l+=1,w&&(u+=1))},m=(C,R)=>{for(let E of C.namedChildren)v(E,R)},p=(C,R)=>{if(co.has(C.type)){f(C,R,"else if");return}if(lo.has(C.type)){let E=C.namedChildren.find(w=>co.has(w.type));if(E){f(E,R,"else if");return}d(C,R,"else",["branch"],!1,!1);let I=aa(C)??C.namedChildren.find(w=>gt.has(w.type));if(I)v(I,R+1);else for(let w of C.namedChildren)v(w,R+1);return}d(C,R,"else",["branch"],!1,!1),v(C,R+1)},f=(C,R,E=C.type.startsWith("unless")?"unless":"if")=>{let I=C.childForFieldName("condition")??Zl(C),w=C.childForFieldName("consequence")??C.childForFieldName("body")??C.namedChildren.find(k=>gt.has(k.type)),A=C.childForFieldName("alternative")??C.namedChildren.find(k=>lo.has(k.type)),D=I?I.text:Bt(C,w);d(C,R,`${E} ${xL(D)}`,ao(I,["branch"])),w&&v(w,R+1),A&&p(A,R)},g=(C,R)=>{let E=C.childForFieldName("body")??C.namedChildren.find(I=>gt.has(I.type));d(C,R,Bt(C,E),ao(C,["loop"])),E&&v(E,R+1)},h=(C,R)=>{let E=C.childForFieldName("body")??C.namedChildren.find(I=>gt.has(I.type));d(C,R,Bt(C,E),ao(C,["branch"])),E&&v(E,R+1)},b=(C,R)=>{let E=C.namedChildren.find(I=>da(I));d(C,R,Bt(C,E),["branch"],!1,!1);for(let I of C.namedChildren)(I===E||da(I))&&v(I,R+1)},S=(C,R)=>{d(C,R,"try",[],!1);for(let E of C.namedChildren)gt.has(E.type)?v(E,R+1):(la.has(E.type)||uo.has(E.type))&&v(E,R)},y=(C,R,E)=>{let I=C.childForFieldName("body")??C.namedChildren.find(A=>gt.has(A.type)),w=E==="finally"?"finally":Bt(C,I);d(C,R,w,[E],!1,!1),I&&v(I,R+1)},x=(C,R)=>{let E=aa(C);d(C,R,Bt(C,E),ao(C,["binding"])),E&&v(E,R+1)},v=(C,R)=>{if(C.startPosition.row>r||C.endPosition.row<n||cL.has(C.type)||C.type==="empty_statement")return;if(gt.has(C.type)){m(C,R);return}if(co.has(C.type)){f(C,R);return}if(fa.has(C.type)){g(C,R);return}if(po.has(C.type)){h(C,R);return}if(jg.has(C.type)){b(C,R);return}if(fo.has(C.type)){S(C,R);return}if(la.has(C.type)){y(C,R,"catch");return}if(uo.has(C.type)){y(C,R,"finally");return}if(lo.has(C.type)){p(C,R);return}if(Kn.has(C.type)){x(C,R);return}let I=!Gg(C)||RL(C);d(C,R,C.text,ao(C),I)};return v(a&&a!==s?a:s,0),l===0?null:{constructKind:CL(s),signature:vL(s,a,t,n),lines:c,sourceStatements:l,copiedStatements:u}}function yi(e,t,n){let r=e.namedChildren.filter(i=>i.startPosition.row<=t&&i.endPosition.row>=n);for(let i of r.sort(SL)){let o=yi(i,t,n);if(o)return o}return Kn.has(e.type)&&e.startPosition.row<=t&&e.endPosition.row>=n?e:null}function SL(e,t){return e.endPosition.row-e.startPosition.row-(t.endPosition.row-t.startPosition.row)||e.startPosition.row-t.startPosition.row}function aa(e){return e.childForFieldName("body")??e.childForFieldName("consequence")??e.namedChildren.find(t=>gt.has(t.type))??null}function vL(e,t,n,r){let i=Bt(e,t);return i||(n[r]??e.text).trim()}function CL(e){return e.type.includes("constructor")?"constructor":e.type.includes("method")||e.type==="method"?zl(e,new Set(["class_body","class_declaration","class_definition"]))?"class method":"object method":e.type==="arrow_function"||e.type==="function_expression"||e.type==="lambda"?zl(e,new Set(["object","pair"]))?"object member":"function value":e.type.includes("function")?zl(e,Kn)?"nested function":"module function":"source construct"}function zl(e,t){let n=e.parent;for(;n;){if(t.has(n.type))return!0;n=n.parent}return!1}function Zl(e){return e.namedChildren.find(t=>!gt.has(t.type)&&!lo.has(t.type))??null}function Bt(e,t){if(!t)return mo(e.text);let n=Math.max(0,t.startIndex-e.startIndex);return mo(e.text.slice(0,n)).replace(/[:{]\s*$/u,"").trim()}function xL(e){let t=mo(e);return t.startsWith("(")&&t.endsWith(")")?t.slice(1,-1).trim():t}function mo(e){return e.trim().replace(/\r?\n[\t ]*/gu," ")}function ao(e,t=[]){let n=new Set(t);return e&&go(e,r=>{let i=Ng[r.type];i&&n.add(i),r.type==="call_expression"&&(n.add("call"),Wg(r)&&n.add("shape")),eu.has(r.type)&&n.add("binding")}),ma.filter(r=>n.has(r))}function RL(e){let t=!1;return go(e,n=>{t||!n.text.includes(`
40
- `)||/(?:string|template|heredoc|raw_string)/u.test(n.type)&&(t=!0)}),t}function da(e){return gt.has(e.type)||co.has(e.type)||fa.has(e.type)||po.has(e.type)||fo.has(e.type)||Kn.has(e.type)||Gg(e)}function Gg(e){return/(?:statement|declaration|expression|assignment|return|throw|raise|break|continue|yield|with_item)$/u.test(e.type)||eu.has(e.type)}function EL(e,t,n){let r=0;for(let i=t;i<=n;i+=1)r+=(e[i]?.length??0)+10;return r}function IL(e){return e.constructKind.length+e.signature.length+80+e.lines.reduce((t,n)=>t+n.text.length+n.depth*2+10,0)}function zg(e,t,n,r,i,o){let s=J(e,t);if(!s)return null;let a=V(e,t),c=ga(e,t,n,r),l=o?c?.startLine??n:n,u=o?c?.endLine??r:r,m=(c?.startLine===l&&c.endLine===u?yi(s.rootNode,l,u):null)??vr(s.rootNode,l,u);if(!m)return null;let p=new Map,f=new Map,g=new Map,h=(y,x)=>{if(y<l||y>u)return;let v=p.get(y)??new Set;v.add(x),p.set(y,v)};c&&h(c.startLine,"signature");for(let y of i)h(y,"anchor");go(m,y=>{let x=Ng[y.type];if(x&&h(y.startPosition.row,x),x==="shape"&&wL(f,y,m,l,u),y.type==="call_expression"){let C=(y.childForFieldName("function")??y.namedChild(0))?.text.split(".").at(-1);if(Wg(y)){h(y.startPosition.row,"shape");let R=ca(y.text);R.length<=Kl&&g.set(y.startPosition.row,R)}if(C&&oL.has(C)){h(y.startPosition.row,"lifecycle");let R=ca(y.text);R.length<=Kl&&g.set(y.startPosition.row,R)}}eu.has(y.type)&&h(y.startPosition.row,"binding")});let b=K(e,t);for(let y of b?.callSites??[])y.line<l||y.line>u||(h(y.line,"call"),y.calleeLeaf==="catch"&&h(y.line,"catch"));let S=[...p.entries()].sort(([y],[x])=>y-x).map(([y,x])=>({line:y,signals:_g.filter(v=>x.has(v)),text:g.get(y)??ca(a[y]??"")})).filter(y=>y.text.length>0||y.signals.includes("anchor"));return{...c?{callable:c}:{},rangeStart:l,rangeEnd:u,sourceLines:a,candidates:S,shapes:[...f.values()].sort((y,x)=>y.startLine-x.startLine)}}function wL(e,t,n,r,i){if(t.startPosition.row<r||t.endPosition.row>i)return;let o=t.childForFieldName("key")??t.childForFieldName("name")??t.namedChild(0),s=ca(o?.text??"");if(!s||s.includes(`
41
- `)||s.length>60)return;let a=LL(t,n);if(a.startPosition.row<r||a.endPosition.row>i)return;let c=`${a.startPosition.row}:${a.endPosition.row}`,l=e.get(c)??{startLine:a.startPosition.row,endLine:a.endPosition.row,fields:[]};l.fields.some(u=>u.name===s&&u.line===t.startPosition.row)||l.fields.push({name:s,line:t.startPosition.row}),e.set(c,l)}function LL(e,t){let n=e.parent;for(;n&&n!==t.parent;){if(Bg.has(n.type))return n;if(n===t)break;n=n.parent}return e.parent??e}function ga(e,t,n,r){return K(e,t)?.callables.filter(i=>i.startLine<=n&&i.endLine>=r).sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine)||i.startLine-o.startLine)[0]}function go(e,t){t(e);for(let n of e.namedChildren)go(n,t)}function Kg(e,t,n,r){r(e);for(let i of e.namedChildren)i.startPosition.row>t||i.endPosition.row<n||Kg(i,t,n,r)}function ca(e){return e.trim().replace(/\s+/gu," ")}function Wg(e){if(e.type!=="call_expression")return!1;let t=e.childForFieldName("arguments")??e.namedChildren.find(r=>r.type==="arguments"||r.type==="argument_list");if(!t)return!1;let n=!1;return go(t,r=>{Bg.has(r.type)&&(n=!0)}),n}function PL(e){let t={};for(let n of _g){let r=e.filter(i=>i.signals.includes(n)).length;r>0&&(t[n]=r)}return t}function DL(e,t){let n=new Map;for(let o of e){let s=o.signals.join(",");n.set(s,(n.get(s)??0)+1)}let r=new Set(Og),i=o=>{let s=n.get(o.signals.join(","))??1,a=Math.min(...o.signals.map(u=>t[u]??1)),c=o.signals.some(u=>r.has(u))?3:1,l=Math.max(0,o.signals.length-1)*1e3;return c*(1e3/s+1e3/a)+l};return[...e].sort((o,s)=>i(s)-i(o)||s.line-o.line)}var eu=new Set(["lexical_declaration","variable_declarator","const_item","static_item","let_declaration","assignment"]);function ML(e,t,n){let r=[],i=/\b(?:describe|it|test)(?:\.(?:only|skip|todo))?\s*\(\s*(['"`])([^'"`]+)\1/u;for(let o=t;o<=n;o+=1){let s=i.exec(e[o]??"")?.[2];if(!(!s||r.includes(s))&&(r.push(s),r.length>=eL))break}return r}var TL=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 bi(e,t,n){let r=J(e,t)?.rootNode??null,i=AL(r,n);if(!i)return null;let o=V(e,t);if(o.length===0)return null;let s=Math.max(0,i.startPosition.row),a=i.endPosition.column===0?i.endPosition.row-1:i.endPosition.row;return{type:i.type,startLine:s,endLine:Math.min(o.length-1,Math.max(s,a))}}function ho(e,t,n,r,i){let o=ot(e,t,r,i,[n]),s=o.startLine===o.endLine&&/(?:=>|\(|\{|\[|,)\s*$/u.test(V(e,t)[o.startLine]??"");if(!s&&(o.startLine>r||o.endLine<i))return o;let a=bi(e,t,n);return s&&a?{startLine:a.startLine,endLine:a.endLine}:a&&a.startLine>=r&&a.endLine<=i?{startLine:a.startLine,endLine:a.endLine}:{startLine:r,endLine:i}}function AL(e,t){if(!e||!Jg(e,t))return null;let n=Yg(e,t);for(;n;){if(TL.has(n.type))return n;n=n.parent}return null}function Yg(e,t){let n=e.namedChildren.filter(r=>Jg(r,t)).sort((r,i)=>Vg(r)-Vg(i));return n.length>0?Yg(n[0],t):e}function Jg(e,t){return e.startPosition.row<=t&&e.endPosition.row>=t}function Vg(e){return e.endIndex-e.startIndex}var FL=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 ha(e,t,n,r){if(!Number.isSafeInteger(n)||n<0)return null;if(!Number.isSafeInteger(r)||r<0)throw new RangeError(`contextLines must be a non-negative safe integer; received ${r}`);let i=V(e,t);if(i.length===0||n>=i.length)return null;let o=Math.max(0,n-r),s=Math.min(i.length-1,n+r);return{relativePath:t,startLine:o,endLine:s,focusLine:n,source:i.slice(o,s+1).join(`
42
- `)}}function Xg(e,t,n,r,i){let o=ha(e,t,n,r);if(!o)return null;let s=J(e,t)?.rootNode??null;if(!s)return{...o,kind:"bounded-context"};let a=kL(s,n,i);if(a.length!==1)return{...o,kind:a.length===0?"non-call-reference":"bounded-context"};let c=a[0],l=V(e,t),u=Math.max(0,c.startPosition.row),d=c.endPosition.column===0?c.endPosition.row-1:c.endPosition.row,m=Math.min(l.length-1,Math.max(u,d));return{relativePath:t,startLine:u,endLine:m,focusLine:n,source:l.slice(u,m+1).join(`
43
- `),kind:"complete-call-expression"}}function Qg(e,t,n,r,i){if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`maxLines must be a positive safe integer; received ${i}`);let o=V(e,t);if(o.length===0||n<0||n>=o.length)return null;let s=Math.min(o.length-1,r,n+i-1);return{relativePath:t,startLine:n,endLine:s,focusLine:n,source:o.slice(n,s+1).join(`
44
- `)}}function Wn(e,t,n,r,i=6){if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`maxLines must be a positive safe integer; received ${r}`);let o=V(e,t);if(o.length===0||n<0||n>=o.length)return null;let s=bi(e,t,n);if(!s){let g=ha(e,t,n,i);return g?{...g,unitType:null,unitStartLine:g.startLine,unitEndLine:g.endLine,omittedLines:0}:null}let a=s.startLine,c=s.endLine,l=c-a+1,u=Math.min(l,r),d=n-a-Math.floor(u/2),m=Math.max(0,Math.min(l-u,d)),p=a+m,f=p+u-1;return{relativePath:t,startLine:p,endLine:f,focusLine:n,source:o.slice(p,f+1).join(`
45
- `),unitType:s.type,unitStartLine:a,unitEndLine:c,omittedLines:l-u}}function kL(e,t,n){let r=[];return Zg(e,t,n,r),r.filter(i=>!r.some(o=>o!==i&&o.startIndex>=i.startIndex&&o.endIndex<=i.endIndex))}function Zg(e,t,n,r){if(_L(e,t)){FL.has(e.type)&&NL(e)===n&&r.push(e);for(let i of e.namedChildren)Zg(i,t,n,r)}}function NL(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 _L(e,t){return e.startPosition.row<=t&&e.endPosition.row>=t}function th(e,t,n={}){let{context:r=0}=n,i=dh(t);if(i)return mh(e,i.filePath,i.startLine,i.endLine,r);let o=lh(e,t);if(o)return sh(e,o);let s=ne(e,t);return s?yo(e,s,r):null}function K3(e,t,n={}){if(t.length===0)throw new RangeError("code requires at least one selector.");if(t.length>24)throw new RangeError(`code accepts at most ${24} selectors per complete packet; received ${t.length}.`);let r=n.context??0,i=n.members??"exported",o=t.map(c=>BL(e,c,r,i)),s=o.flatMap(c=>c.results),a=s.map(c=>({relativePath:c.relativePath,startLine:c.startLine,endLine:c.endLine}));return{requested:t.length,matched:o.filter(c=>c.status==="matched").length,ambiguous:o.filter(c=>c.status==="ambiguous").length,missing:o.filter(c=>c.status==="missing").length,entries:o,bindingClosure:sa(s.map(c=>c.bindingClosure),a)}}function BL(e,t,n,r){let i=dh(t);if(i){let u=mh(e,i.filePath,i.startLine,i.endLine,n);return u?$L(e,t,u,n):tu(e,t,"definition-source-unreadable")}let o=lh(e,t);if(o)return HL(e,t,o,n,r);let s=Qe(e,t);if(!s.match)return tu(e,t,"definition-not-found");let a=JL(e,s),c=a.map(uh);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=yo(e,d,n);return m?[m]:[]}):[],definitions:[],candidates:c,omittedCandidates:Math.max(0,s.total-c.length),suggestions:[]}}let l=yo(e,s.match,n);return l?YL(t,l):tu(e,t,"definition-source-unreadable")}function $L(e,t,n,r){let i=U(e,n.relativePath).filter(l=>!nh(l,n.relativePath)),o=jL(e,n,i),s=oh(o.map(l=>yo(e,l,r)).filter(l=>l!==null)).filter(l=>!ch(n,l)),a=new Set(s.map(l=>l.symbol)),c=o.filter(l=>!a.has(l.symbol)&&!(n.startLine<=l.startLine&&n.endLine>=l.endLine)).map(uh);return{selector:t,status:"matched",kind:"source",totalCandidates:1,results:[n,...s],definitions:[],candidates:[],omittedCandidates:0,suggestions:[],rangeCoverage:{basis:"requested-range-and-same-file-call-closure",referencedDefinitions:o.length,returnedDefinitions:o.length-c.length,returnedBodies:s.length,omittedDefinitions:c.length,omittedLedger:c}}}function jL(e,t,n){if(!bo(t.freshness))return[];if(n.length===0)return[];let r=Lr(e,n,{additive:!1,semantic:!1}),i=new Map;for(let s of n){let a=i.get(s.symbol)??[];a.push(s),i.set(s.symbol,a)}let o=new Map;for(let s of n)if(!(s.endLine<t.startLine||s.startLine>t.endLine)){for(let a of r.get(s.symbolId)??[])if(a.file===t.relativePath&&!(a.source==="ast-callsite"&&(a.chunkId<t.startLine||a.chunkId>t.endLine)))for(let c of i.get(a.symbol)??[])o.set(c.symbolId,c)}return ih(e,[...o.values()],n)}function HL(e,t,n,r,i){let o=n.relativePath,s=qL(e,o),a=bo(n.freshness)?U(e,o).filter(g=>!nh(g,o)):[],c=a.filter(g=>ft(e,g)),l=c.length>0?c:UL(s,a),u=i==="all"?[]:ih(e,l,a),d=i==="all"||a.length===0?[sh(e,n)]:oh(u.map(g=>yo(e,g,r)).filter(g=>g!==null)),m=zL(s,d),p=KL(o,s,d),f=WL(s);return{selector:t,status:"matched",kind:"file-source",totalCandidates:1,results:d,definitions:[],candidates:[],omittedCandidates:0,suggestions:[],fileCoverage:{members:i,basis:i==="all"||a.length===0?"complete-file-source":c.length>0?"explicit-exports-and-same-file-reference-closure":"top-level-and-same-file-reference-closure",totalDefinitions:f,returnedDefinitions:m,returnedBodies:d.length,omittedDefinitions:Math.max(0,f-m),omittedLedger:p}}}function UL(e,t){let n=new Set(e.map(r=>r.symbol));return t.filter(r=>n.has(r.symbol))}function qL(e,t){return Sg(e,t).flatMap(n=>GL(n,t)?n.children:[n])}function nh(e,t){return rh(t).has(e.leaf)}function GL(e,t){return rh(t).has(z(e.symbol))}function rh(e){let t=OL(e);return new Set([t,t.slice(0,Math.max(0,t.length-eh(t).length))])}function ih(e,t,n){if(t.length===0)return[];let r=Lr(e,n,{additive:!0,semantic:!1}),i=new Map;for(let a of n){let c=i.get(a.symbol)??[];c.push(a),i.set(a.symbol,c)}let o=new Map,s=[...t];for(;s.length>0;){let a=s.shift();if(!o.has(a.symbolId)){o.set(a.symbolId,a);for(let c of r.get(a.symbolId)??[])for(let l of i.get(c.symbol)??[])o.has(l.symbolId)||s.push(l)}}return[...o.values()].sort(VL)}function oh(e){let t=[...e].sort((r,i)=>r.relativePath.localeCompare(i.relativePath)||r.startLine-i.startLine||i.endLine-r.endLine),n=[];for(let r of t)n.some(i=>ch(i,r))||n.push(r);return n}function sh(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??ru(t.relativePath),source:t.text,freshness:t.freshness,...bo(t.freshness)?{bindingClosure:gi(e,t.relativePath,0,Math.max(0,n.length-1))}:{}}}function zL(e,t){return ya(e).filter(n=>t.some(r=>nu(n,r))).length}function KL(e,t,n){let r=[];return ah(r,e,t,n,0),r}function ah(e,t,n,r,i){for(let o of n){if(r.some(a=>nu(o,a)))continue;let s=ya(o.children).filter(a=>!r.some(c=>nu(a,c))).length;e.push({symbol:o.symbol,shortName:o.shortName,relativePath:t,startLine:o.startLine,endLine:o.endLine,signature:o.signature,depth:i,nestedDefinitions:s}),ah(e,t,o.children,r,i+1)}}function ya(e){return e.flatMap(t=>[t,...ya(t.children)])}function WL(e){return ya(e).length}function nu(e,t){return t.startLine<=e.startLine&&t.endLine>=e.endLine}function ch(e,t){return e.relativePath===t.relativePath&&e.startLine<=t.startLine&&e.endLine>=t.endLine}function VL(e,t){return e.startLine-t.startLine||t.endLine-e.endLine||e.symbol.localeCompare(t.symbol)}function YL(e,t){return{selector:e,status:"matched",kind:"source",totalCandidates:1,results:[t],definitions:[],candidates:[],omittedCandidates:0,suggestions:[]}}function tu(e,t,n){return{selector:t,status:"missing",kind:"source",totalCandidates:0,results:[],definitions:[],candidates:[],omittedCandidates:0,suggestions:Ks(e,t,5),reason:n}}function lh(e,t){try{return ra(e,t)}catch(n){if(n instanceof Yp)return null;throw n}}function JL(e,t){if(!t.match)return[];let n=[t.match];for(let i of t.candidates){let o=U(e,i.relativePath).find(s=>s.symbol===i.symbol&&s.startLine===i.startLine);o&&n.push(o)}let r=new Set;return n.filter(i=>{let o=`${i.relativePath}:${i.startLine}:${i.endLine}:${i.symbol}`;return r.has(o)?!1:(r.add(o),!0)})}function uh(e){return{symbol:e.symbol,shortName:T(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine}}function dh(e){let t=e.match(/^(.+):(\d+)-(\d+)$/);if(!t)return null;let n=Number(t[2]),r=Number(t[3]);if(!Number.isSafeInteger(n)||n<1)throw new RangeError(`Source range start line must be a positive integer, got "${t[2]}".`);if(!Number.isSafeInteger(r)||r<n)throw new RangeError(`Source range end line must be an integer at or after ${n}, got "${t[3]}".`);return{filePath:t[1],startLine:n,endLine:r}}function yo(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=ra(e,t.relativePath);if(!i)return null;let s=i.text.split(`
47
- `),a=t.endLine<=t.startLine?Wn(e,t.relativePath,t.startLine,Number.MAX_SAFE_INTEGER):null,c=a?.unitType?a.unitStartLine:t.startLine,l=a?.unitType?a.unitEndLine:t.endLine,u=Math.max(0,c-n),d=Math.min(s.length-1,l+n),m=s.slice(u,d+1).join(`
48
- `);return{symbol:t.symbol,shortName:T(t.symbol),relativePath:t.relativePath,startLine:u,endLine:d,language:r?.language??ru(t.relativePath),source:m,freshness:i.freshness,...bo(i.freshness)?{bindingClosure:gi(e,t.relativePath,u,d)}:{}}}function mh(e,t,n,r,i){let o=ra(e,t);if(!o)return null;let s=e.get("SELECT language FROM documents WHERE relative_path = ?",o.relativePath),c=o.text.split(`
49
- `);if(n>c.length)return null;let l=Math.max(0,n-1-i),u=Math.min(c.length-1,r-1+i),d=c.slice(l,u+1).join(`
50
- `);return{symbol:`${o.relativePath}:${n}-${r}`,shortName:`${o.relativePath}:${n}-${r}`,relativePath:o.relativePath,startLine:l,endLine:u,language:s?.language??ru(o.relativePath),source:d,freshness:o.freshness,...bo(o.freshness)?{bindingClosure:gi(e,o.relativePath,l,u)}:{}}}function bo(e){return!!(e&&e.semantic.state!=="stale"&&e.semantic.basis!=="no-compiler-document")}function ru(e){switch(eh(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 ba(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath)??[];r.push(n),t.set(n.relativePath,r)}return t}function ph(e){let t=new Map,n=QL(e),r=new Map;return i=>{let o=XL(i),s=r.get(o);if(s!==void 0)return s;if(!n.has(i.file))return r.set(o,i.symbol),i.symbol;let a=t.get(i.file);a||(a=ZL(U(e,i.file)),t.set(i.file,a));let c=eP(a,i);return r.set(o,c),c}}function XL(e){return`${e.file}\0${e.symbol}\0${e.line}`}function QL(e){return new Set(e.all("SELECT relative_path FROM documents").map(t=>t.relative_path))}function ZL(e){let t=new Map,n=new Map;for(let r of e){let i=t.get(r.leaf);i?i.push(r):t.set(r.leaf,[r]);let o=n.get(r.startLine);o?o.push(r):n.set(r.startLine,[r])}return{definitions:e,byLeaf:t,byStartLine:n}}function eP(e,t){if(e.definitions.length===0)return t.symbol;let n=rP(t.symbol),r=tP(e.byLeaf,n),i=nP(r,t.line);if(i)return i.symbol;let o=e.byStartLine.get(t.line)??[];return o.length===1?o[0].symbol:t.symbol}function tP(e,t){let n=[],r=new Set;for(let i of t)for(let o of e.get(i)??[])r.has(o.symbolId)||(r.add(o.symbolId),n.push(o));return n}function nP(e,t){let n=null;for(let r of e)if(!(r.startLine>t||r.endLine<t)){if(r.startLine===t)return r;(!n||r.endLine-r.startLine<n.endLine-n.startLine)&&(n=r)}return n}function rP(e){let t=new Set([e]),r=e.split(/::|\.|#/).filter(Boolean).at(-1);return r&&t.add(r),t}function fh(e,t){let r=ae(e,t).map(i=>oP(t,i));return{usage:r,positions:sP(e,t,r)}}function gh(e,t){return{importUsage(n){let r=e.importUsageFacts(n);if(!t||r.positions.length===0)return r.usage;let i=t.importDefinitionsForFile(n,r.positions);return i.available?iP(r.usage,i.sourcePaths):r.usage}}}function iP(e,t){return e.map((n,r)=>{let i=t.get(String(r));return i?{...n,sourcePath:i}:n})}function oP(e,t){let n=t.isTypeOnly===!0,r=t.kind==="side-effect"||n||t.used;return{importer:e,sourcePath:t.sourcePath,importedName:t.importedName,localName:t.localName,kind:t.kind,isTypeOnly:n,isUsed:r,isTypeUsed:n,isValueUsed:t.kind==="side-effect"||!n&&t.used,references:[]}}function sP(e,t,n){let r=J(e,t);if(!r)return[];let i=aP(r.rootNode),o=new Map;for(let a of i){let c=o.get(ou(a.importedName,a.localName));c?c.push(a.position):o.set(ou(a.importedName,a.localName),[a.position])}let s=[];return n.forEach((a,c)=>{let l=o.get(ou(a.importedName,a.localName??a.importedName))?.shift();l&&s.push({...l,id:String(c),file:t})}),s}function aP(e){let t=[];for(let n of e.descendantsOfType("use_declaration")){let r=n.namedChildren.find(i=>i.type!=="visibility_modifier");r&&t.push(...Sa(r,""))}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:iu(e,e.text)}];case"scoped_identifier":{let n=e.text.split("::").pop()??e.text;return[{importedName:n,localName:n,position:iu(e,n)}]}case"scoped_use_list":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=wf(t,n.text);return r.namedChildren.flatMap(o=>Sa(o,i))}case"use_list":return e.namedChildren.flatMap(n=>Sa(n,t));case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);return!n||!r?[]:Sa(n,t).map(i=>({...i,localName:r.text}))}case"use_wildcard":{let n=e.namedChild(0),r="*";return[{importedName:r,localName:r,position:iu(n??e,r)}]}default:return[]}}function iu(e,t){let n=Math.max(0,e.text.lastIndexOf(t));return{id:"",file:"",line:e.startPosition.row,column:e.startPosition.column+n+cP(t)}}function cP(e){return Math.max(0,Math.min(e.length-1,1))}function ou(e,t){return`${e}\0${t}`}import{spawnSync as yu}from"child_process";import{existsSync as bu}from"fs";import{fileURLToPath as cD}from"url";function Yn(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function va(e){let t=Yf(Vf,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 WP,mkdtempSync as Bh,rmSync as du}from"fs";import{tmpdir as fu}from"os";import{join as mu}from"path";import{fileURLToPath as Io,pathToFileURL as VP}from"url";import{SHARE_ENV as YP,Worker as JP}from"worker_threads";function Jn(e,t,n=new Set){let r=new Map;for(let i of e)n.has(i.symbolId)||r.set(i.symbolId,t.get(i.symbolId)??[]);return r}function Pr(e,t,n){let r=Yn(process.env.SCIP_RUST_SEMANTIC_BATCH_TIMEOUT_MS)??0;if(r>0)return r;let i=Math.max(1,Math.ceil(e/Math.max(1,n)));return Math.max(12e4,3e4+i*t)}import{spawn as LP}from"child_process";import{createHash as PP,randomUUID as DP}from"crypto";import{existsSync as Mh,realpathSync as MP,rmSync as TP}from"fs";import{tmpdir as AP}from"os";import{resolve as vi}from"path";import{execFileSync as hP}from"child_process";import{existsSync as lP}from"fs";import{deserializeSCIP as uP,SymbolRole as dP}from"@c4312/scip";import{realpathSync as aQ}from"fs";import{basename as lQ,dirname as uQ,join as dQ,relative as mQ,sep as pQ}from"path";import{fileURLToPath as gQ,pathToFileURL as hQ}from"url";function Ca(e){let t=new Map;for(let n of e)t.set(`${n.file}\0${n.line}\0${n.column}`,n);return[...t.values()].sort((n,r)=>{let i=n.file.localeCompare(r.file);return i!==0?i:n.line!==r.line?n.line-r.line:n.column-r.column})}var su=new WeakMap,mP="SCIP_RUST_SCIP_OCCURRENCE_REFERENCE_MODE";function hh(e,t){let n=new Map,r=xa(),i=t.filter(s=>Sh(s,r));if(i.length===0)return n;let o=vh(e);if(!o)return n;for(let s of i){let a=bh(o,s);a!==null&&n.set(s.symbolId,a)}return n}function yh(e,t){if(!Sh(t,xa()))return null;let n=vh(e);return n?bh(n,t):null}function bh(e,t){return e.referencesBySymbol.get(t.symbol)??[]}function Sh(e,t="safe"){if(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||He(e.symbol)||/impl#\[[^\]]+\]\[Default\]default\(\)\.$/.test(e.symbol))return!1;if(t==="all")return!0;let n=Lt(e.symbol);if(n==="method")return!0;if(n!=="term")return!1;let r=$n(e.symbol);return"kind"in r?!1:!pP(r)}function pP(e){for(let t=0;t<e.descriptors.length-1;t+=1)if(e.descriptors[t]?.suffix==="type")return!0;return!1}function vh(e){if(su.has(e))return su.get(e)??null;let t=fP(e);return su.set(e,t),t}function fP(e){if(!e.generation.indexPath||!lP(e.generation.indexPath))return null;try{let t=uP(ti(e.generation.indexPath,{inputKind:"SCIP occurrence-reference index",maxBytes:ei})),n=new Map;for(let r of t.documents??[]){let i=r.relativePath;if(!(!i||e.isIgnored(i)))for(let o of r.occurrences??[]){if(!o.symbol||(o.symbolRoles&dP.Definition)!==0)continue;let s=gP(i,o.range);if(!s)continue;let a=n.get(o.symbol)??[];a.push(s),n.set(o.symbol,a)}}for(let[r,i]of n)n.set(r,Ca(i));return{referencesBySymbol:n}}catch{return null}}function gP(e,t){if(t.length<3)return null;let n=t[0],r=t[1];return!Number.isInteger(n)||!Number.isInteger(r)?null:{file:e,line:n,column:r}}function xa(){return process.env[mP]==="all"?"all":"safe"}var Ch=new Map;function au(e){let n=va(e).resolvedBinary??null;return{engine:"rust-analyzer",resolvedBinary:n,version:n?yP(e,n):"unavailable"}}function Dr(e){return{...au(e),scipOccurrenceReferenceMode:xa()}}function yP(e,t){let n=`${e}\0${t}`,r=Ch.get(n);if(r)return r;let i;try{i=hP(t,["--version"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim()}catch{i="unknown"}return Ch.set(n,i),i}import{createHash as bP}from"crypto";var SP=new Set(["Cargo.lock","Cargo.toml","rust-project.json","rust-toolchain","rust-toolchain.toml"]);function xh(e){let t=af(e,{includePath:vP});return bP("sha256").update(JSON.stringify(t)).digest("hex")}function vP(e){let t=e.replaceAll("\\","/"),n=t.split("/").at(-1)??t;return t.endsWith(".rs")||SP.has(n)?!0:t===".cargo/config"||t===".cargo/config.toml"||t.endsWith("/.cargo/config")||t.endsWith("/.cargo/config.toml")}import{createHash as CP}from"crypto";import{resolve as xP}from"path";var Si=3;function lu(e){return CP("sha256").update(Rr({kind:"scip-query-durable-rust-mailbox",protocolVersion:Si,sessionDir:xP(e)})).digest("hex")}function Ih(e,t){return Z(e)?e.protocolVersion!==Si?Eh(e.protocolVersion===void 0?"helper wrote a prior uncorrelated response protocol":`helper wrote unsupported response protocol ${String(e.protocolVersion)}`):e.mailboxVersion!==yn||e.id!==t.requestId||e.operationKey!==t.operationKey||e.sessionIdentity!==t.sessionIdentity||e.deadlineAtMs!==t.deadlineAtMs?Eh("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"||!wP(e.errorCode)?cu("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"||!RP(e.response,t.requestKind)?cu("helper wrote an invalid success response"):{ok:!0,session:e.session,response:e.response}:cu("helper wrote an invalid response object")}function RP(e,t){return!Z(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")):Rh(e.references,EP)&&(e.incompleteReferenceSymbolIds===void 0||Array.isArray(e.incompleteReferenceSymbolIds)&&e.incompleteReferenceSymbolIds.every(n=>Number.isSafeInteger(n)))&&(e.callees===void 0||Rh(e.callees,IP))&&(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 Rh(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 EP(e){return Z(e)&&typeof e.file=="string"&&Rt(e.line)&&Rt(e.column)}function IP(e){return Z(e)&&typeof e.symbol=="string"&&typeof e.file=="string"&&Rt(e.line)&&(e.callsiteLine===void 0||Rt(e.callsiteLine))}function wP(e){return e==="unsupported-protocol"||e==="malformed-request"||e==="expired-request"||e==="handler-error"}function cu(e){return{ok:!1,code:"malformed-response",error:e}}function Eh(e){return{ok:!1,code:"incompatible-response",error:e}}var FP=5e3,Th=10,kP=3e4;function wh(e,t,n,r=Nh){let i=r.engineIdentity(e),o={protocolVersion:Si,projectRoot:r.canonicalProjectRoot(e),projectFingerprint:r.projectFingerprint(e),engine:{engine:i.engine,resolvedBinary:i.resolvedBinary,version:i.version},workerFingerprint:r.fileFingerprint(t),environment:Ah(r.environment())};return{key:_h(Rr(o)),...o}}function So(e,t,n,r){if(e.protocolVersion!==Si||!n(e.pid))return!1;if(!e.processIdentity)return!0;let i=r?.(e.pid);return i!=null&&Ys(e.processIdentity,i)}function uu(e,t,n){let r;try{r=Sl(t,{maxBytes:pn,inputKind:"Rust semantic engine artifact"})}catch{r="missing"}let i=_h(Rr({projectRoot:vi(e),serverPath:vi(t),serverFingerprint:r})).slice(0,20);return vi(n,`scip-query-rust-session-${i}`)}function Lh(e){let t=e===void 0?Number.NaN:Number(e);return Number.isInteger(t)&&t>=0?t:0}function Ah(e){return Object.fromEntries(Object.entries(e).filter(([t])=>kh(t)).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,n??null]))}function Fh(e,t){let n=t.runtime??jP,r=t.identityRuntime??Nh,i=uu(e,t.serverPath,t.tempRoot??AP()),o=!1,s=(a,c)=>{if(o)throw new Error("Durable Rust semantic session was already disposed.");return _P(i,t.serverPath,t.semanticWorkerPath,a,c,n,t.mailboxLimits)};return{requestSemantic(a,c){let l=wh(e,t.semanticWorkerPath,a,r),{readinessDeadlineMs:u,...d}=a;return s({kind:"semantic",identityKey:l.key,workerEnvironment:Dh(),request:{...d,referenceRetryTimeoutMs:NP(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,a.referenceRetryTimeoutMs),settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:Lh(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},requestImportDefinitions(a,c){let l=wh(e,t.semanticWorkerPath,a,r),{readinessDeadlineMs:u,...d}=a;return s({kind:"import-definitions",identityKey:l.key,workerEnvironment:Dh(),request:{...d,settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:Lh(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},shutdown(){o=!0}}}function NP(e,t){return t!==void 0?t:e===void 0?kP:void 0}function _P(e,t,n,r,i,o,s={}){let a=o.now(),c=a+i,l=(o.monotonicNow??Pt)(),u=l+i,d=qn("rust-semantic-v3",r),m=Ir(d),p=Js(e),f=lu(e),g=Xs(p,{mailboxVersion:yn,protocolVersion:Si,id:m,operationKey:d,clientId:o.randomId(),enqueuedAtMs:a,deadlineAtMs:c,sessionIdentity:f,request:r},{nowMs:a,limits:s});for(Ph(e,t,n,u,o);(o.monotonicNow??Pt)()<=u;){if(Mh(g.responsePath)){let b=OP(Ct(g.responsePath,{maxBytes:s.maxItemBytes??pn,inputKind:"durable Rust semantic mailbox response"}),{requestId:m,operationKey:d,sessionIdentity:f,deadlineAtMs:g.authoritativeDeadlineAtMs,requestKind:r.kind,nowMs:o.now()});if(!b.ok)throw new Error(b.error);return be()&&Ns({type:"span",name:"rust.semantic.durable-session.request",durationMs:(o.monotonicNow??Pt)()-l,ok:!0,session:b.session,kind:r.kind}),b.response}let h=vo(e);(!h||!So(h,o.now(),o.isProcessAlive,o.readProcessIdentity))&&Ph(e,t,n,u,o),o.sleep(Th)}throw new Error(`Durable Rust semantic session timed out after ${(i/1e3).toFixed(0)}s.`)}function Ph(e,t,n,r,i){let o=vo(e);if(o&&So(o,i.now(),i.isProcessAlive,i.readProcessIdentity))return;TP(vi(e,"server.json"),{force:!0}),i.spawnServer(t,e,n);let s=i.monotonicNow??Pt,a=Math.min(r,s()+FP);for(;s()<=a;){let c=vo(e);if(c&&So(c,i.now(),i.isProcessAlive,i.readProcessIdentity))return;i.sleep(Th)}throw new Error("Durable Rust semantic session helper did not become ready within 5s.")}function vo(e){try{let t=JSON.parse(Ct(vi(e,"server.json"),{maxBytes:Ts,inputKind:"durable Rust session state"}));if(typeof t.protocolVersion!="number"||t.sessionIdentity!==void 0&&(typeof t.sessionIdentity!="string"||t.sessionIdentity!==lu(e))||typeof t.pid!="number"||typeof t.heartbeatAtMs!="number"||t.busyUntilMs!==void 0&&typeof t.busyUntilMs!="number"||t.mailbox!==void 0&&!BP(t.mailbox))return null;let n=t.processIdentity===void 0?null:Vs(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 OP(e,t){try{return Ih(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 BP(e){if(!e||typeof e!="object")return!1;let t=e;return Rt(t.pending)&&Rt(t.inflight)&&Rt(t.responses)&&Rt(t.deadLetters)&&Rt(t.invalid)&&Rt(t.totalItems)&&typeof t.totalBytes=="number"&&Number.isFinite(t.totalBytes)&&t.totalBytes>=0&&(t.oldestPendingAt===void 0||Number.isFinite(Date.parse(t.oldestPendingAt)))}function Dh(){return Object.fromEntries(Object.entries(process.env).filter(([e])=>$P(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t??null]))}function kh(e){return e==="HOME"||e==="PATH"||e.startsWith("CARGO_")||e.startsWith("RA_")||e.startsWith("RUST")}function $P(e){return kh(e)||e.startsWith("SCIP_RUST_")||e==="SCIP_QUERY_PROFILE"||e==="SCIP_QUERY_PROFILE_CACHE_STATE"||e==="SCIP_QUERY_PROFILE_COMMAND"||e==="SCIP_QUERY_PROFILE_OUT"||e==="SCIP_QUERY_PROFILE_RUN_ID"||e==="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY"||e==="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY_KIND"||e==="SCIP_QUERY_PROFILE_MIN_MS"}var Nh={canonicalProjectRoot(e){try{return MP(e)}catch{return vi(e)}},projectFingerprint(e){return xh(e)},engineIdentity:au,fileFingerprint(e){return Sl(e,{maxBytes:pn,inputKind:"Rust semantic engine artifact"})},environment(){return Ah(process.env)}},jP={now:Date.now,monotonicNow:Pt,randomId:DP,isProcessAlive:mi,readProcessIdentity:pi,spawnServer(e,t,n){if(!Mh(e))throw new Error(`Durable Rust semantic session helper was not found at ${e}. Run npm run build first.`);LP(process.execPath,[e,t,n],{detached:!0,stdio:"ignore"}).unref()},sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)}};function _h(e){return PP("sha256").update(e).digest("hex")}import{randomUUID as r6}from"crypto";import{readdirSync as HP,rmSync as o6,writeFileSync as s6}from"fs";import{join as UP}from"path";var qP="rust-analyzer-owner-",GP=".json",zP=16*1024;async function Oh(e,t){if(!e)return[];let n;try{n=HP(e)}catch{return[]}let r=n.filter(s=>s.startsWith(qP)&&s.endsWith(GP)).map(s=>UP(e,s)),i=[],o=[];for(let s of r){let a=KP(s);a?o.push(a):i.push({reaped:!1,reason:"identity-unavailable",detail:`Rust analyzer ownership record ${s} could not be validated.`})}return i.push(...await Promise.all(o.map(s=>Zf(s,t)))),i}function KP(e){try{let t=Ct(e,{maxBytes:zP,inputKind:"rust-analyzer process ownership record"}),n=JSON.parse(t),r=Vs(n.rootIdentity);return n.version!==1||!r||typeof n.ownsProcessGroup!="boolean"?null:{rootPid:r.pid,rootIdentity:r,ownsProcessGroup:n.ownsProcessGroup,knownMembers:new Map([[r.pid,r]])}}catch{return null}}var $h=15e3,jh=8,Uh=5e3,XP=64,QP=96,gu=class{constructor(t,n,r={}){this.projectRoot=t;this.status=n;this.opts=r;this.requester=r.requester??tD(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:xo(n),references:Ro(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!0});return{...Co(r),resolvedBinary:n.resolvedBinary,references:Jn(t,new Map(r.references),new Set(r.incompleteReferenceSymbolIds??[]))}}catch(r){return this.opts.fallbackReferenceResolver?.referencesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),references:Ro(t)}}}calleesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:xo(n),callees:Eo(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!0});return{...Co(r),resolvedBinary:n.resolvedBinary,callees:pu(t,new Map(r.callees??[]))}}catch(r){return this.opts.fallbackCalleeResolver?.calleesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),callees:Eo(t)}}}referencesAndCalleesForDefinitions(t,n){let r=this.status(this.projectRoot);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:xo(r),references:Ro(t),callees:Eo(n)};let i=[...t,...n];try{let o=this.requestSession(r.resolvedBinary,i,{includeReferences:t.length>0,includeCallees:n.length>0,referenceDefinitions:t,calleeDefinitions:n});return{...Co(o),resolvedBinary:r.resolvedBinary,references:Jn(t,new Map(o.references),new Set(o.incompleteReferenceSymbolIds??[])),callees:pu(n,new Map(o.callees??[]))}}catch(o){return this.fallbackReferencesAndCallees(r,t,n,o)}}signaturesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:xo(n),signatures:Hh(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!1,includeSignatures:!0});return{...Co(r),resolvedBinary:n.resolvedBinary,signatures:sD(t,new Map(r.signatures??[]))}}catch(r){return this.opts.fallbackSignatureResolver?.signaturesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),signatures:Hh(t)}}}importDefinitionsForFile(t,n){let r=this.status(this.projectRoot);if(n.length===0)return r.available?{available:!0,resolvedBinary:r.resolvedBinary,sourcePaths:new Map}:{available:!1,reason:r.reason,resolvedBinary:r.resolvedBinary,sourcePaths:new Map};if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:xo(r),sourcePaths:new Map(n.map(i=>[i.id,null]))};try{let i=this.requestImportDefinitions(r.resolvedBinary,t,n);return{...Co(i),resolvedBinary:r.resolvedBinary,sourcePaths:new Map(i.sourcePaths)}}catch(i){return{available:!1,resolvedBinary:r.resolvedBinary,reason:i instanceof Error?i.message:String(i),sourcePaths:new Map(n.map(o=>[o.id,null]))}}}dispose(){this.requester.shutdown()}requestSession(t,n,r){let i=Ra(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,$h),o=Ea(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),s=Ra(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,jh),a=Ea(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),c=r.referenceDefinitions?[...r.referenceDefinitions]:void 0,l=r.calleeDefinitions?[...r.calleeDefinitions]:void 0,u=r.signatureDefinitions?[...r.signatureDefinitions]:void 0,d=wo(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,...r}),m={projectRoot:this.projectRoot,rustAnalyzerBinary:t,definitions:[...n],...c?{referenceDefinitions:c}:{},...l?{calleeDefinitions:l}:{},...u?{signatureDefinitions:u}:{},requestTimeoutMs:i,...r.includeReferences!==!1&&o>0?{referenceRetryTimeoutMs:o}:{},diagnosticsTimeoutMs:a,settleDelayMs:d,concurrency:s,includeReferences:r.includeReferences,includeCallees:r.includeCallees,includeSignatures:r.includeSignatures},p=aD(m);return N("rust.semantic.session.request",()=>this.requester.requestSemantic(m,Pr(p,hu(i,m.referenceRetryTimeoutMs),s)),()=>({definitions:n.length,operationDefinitions:p,referenceDefinitions:m.referenceDefinitions?.length,calleeDefinitions:m.calleeDefinitions?.length,signatureDefinitions:m.signatureDefinitions?.length,references:m.includeReferences!==!1,callees:m.includeCallees===!0,signatures:m.includeSignatures===!0,referenceRetryTimeoutMs:m.referenceRetryTimeoutMs}))}fallbackReferencesAndCallees(t,n,r,i){let o=n.length===0?{available:!0,resolvedBinary:t.resolvedBinary,references:Ro(n)}:this.opts.fallbackReferenceResolver?.referencesForDefinitions(n),s=r.length===0?{available:!0,resolvedBinary:t.resolvedBinary,callees:Eo(r)}:this.opts.fallbackCalleeResolver?.calleesForDefinitions(r);if(o&&s){let a={resolvedBinary:o.resolvedBinary??s.resolvedBinary??t.resolvedBinary,references:Jn(n,o.references),callees:pu(r,s.callees)};return o.available&&s.available?{available:!0,...a}:{available:!1,reason:(o.available?void 0:o.reason)??(s.available?void 0:s.reason)??"Rust semantic fallback was unavailable.",...a}}return{available:!1,resolvedBinary:t.resolvedBinary,reason:i instanceof Error?i.message:String(i),references:Ro(n),callees:Eo(r)}}requestImportDefinitions(t,n,r){let i=Ra(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,$h),o=Ra(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,jh),s=Ea(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),a=Ea(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,Uh),c={projectRoot:this.projectRoot,rustAnalyzerBinary:t,file:n,positions:[...r],requestTimeoutMs:i,diagnosticsTimeoutMs:s,settleDelayMs:a,concurrency:o};return N("rust.semantic.import-definitions.session.request",()=>this.requester.requestImportDefinitions(c,Pr(r.length,i,o)),()=>({file:n,positions:r.length}))}};function Co(e){return e.available?{available:!0}:{available:!1,reason:e.reason}}function xo(e){return e.available?"rust-analyzer binary path is unavailable.":e.reason}function qh(e,t,n={}){return new gu(e,t,n)}function wo(e,t){let n=Wh(e);if(n!==null)return n;let r=t.includeReferences!==!1;return r&&t.includeCallees!==!0&&t.includeSignatures!==!0&&t.definitionCount<=XP||r&&t.includeCallees===!0&&t.includeSignatures!==!0&&t.definitionCount<=QP?0:Uh}function Gh(e){let t=e?.trim().toLowerCase(),n=t==="0"||t==="false"||t==="off"||t==="worker",r=t==="1"||t==="true"||t==="on"||t==="durable",i=t===void 0||t==="";return{transport:n||!i&&!r?"worker":"durable",source:i?"default":"environment",fallback:"worker",valid:i||n||r,optOut:"SCIP_RUST_SEMANTIC_DURABLE_SESSION=0"}}function ZP(e){return Gh(e).transport}function I6(e,t){let n=Gh(t);if(n.transport==="worker")return{...n,state:"per-command"};let r=Io(Kh()),i=uu(e,r,fu()),o=vo(i);return o?{...n,state:So(o,Date.now(),mi,pi)?"live":"stale",pid:o.pid,heartbeatAtMs:o.heartbeatAtMs,...o.busyUntilMs===void 0?{}:{busyUntilMs:o.busyUntilMs}}:{...n,state:"stopped"}}function eD(e,t){let n=null,r=!1,i=!1,o=!1,s=()=>n??=t(),a=()=>{i||(e.shutdown(),i=!0)},c=(u,d,m)=>{let p=oD(u);r=!0;try{a()}catch{}be()&&Ns({type:"span",name:"rust.semantic.durable-session.request",durationMs:m,ok:!1,kind:d,session:"worker-fallback",reason:p})},l=(u,d,m)=>{if(o)throw new Error("Rust semantic failover session was already disposed.");if(r)return m(s());let p=performance.now();try{return d(e)}catch(f){c(f,u,performance.now()-p)}return m(s())};return{requestSemantic(u,d){return l("semantic",m=>m.requestSemantic(u,d),m=>m.requestSemantic(u,d))},requestImportDefinitions(u,d){return l("import-definitions",m=>m.requestImportDefinitions(u,d),m=>m.requestImportDefinitions(u,d))},shutdown(){if(o)return;o=!0;let u=[];try{a()}catch(d){u.push(d)}try{n?.shutdown()}catch(d){u.push(d)}if(u.length>0)throw u[0]}}}function tD(e,t,n={worker:()=>nD(),durable:()=>Fh(e,{serverPath:Io(Kh()),semanticWorkerPath:Io(zh())})}){return ZP(t)==="durable"?eD(n.durable(),n.worker):n.worker()}function nD(e={}){let t=null,n=null,r=1,i=!1,o=null,s=null,a=d=>{d&&du(d,{recursive:!0,force:!0})},c=()=>{if(o)return;let d=t,m=n;t=null,n=null;let p=d?d.terminate():Promise.resolve(0);o=Promise.allSettled([p,Oh(m,{gracefulMs:1e3,forceMs:1e3})]).then(([f,g])=>{let b=(g.status==="fulfilled"?g.value:[{reaped:!1,detail:String(g.reason)}]).filter(S=>!S.reaped);if(f.status==="rejected"||b.length>0){s=new Error(`Rust semantic worker cleanup did not complete; ownership evidence remains at ${m??"unknown"}.`);return}a(m)}).finally(()=>{o=null})},l=()=>{if(t)return t;if(o)throw new Error("The previous Rust semantic session worker is still terminating; retry the request.");if(s)throw s;let d=e.semanticWorkerPath?VP(e.semanticWorkerPath):zh();if(!WP(Io(d)))throw new Error(`Rust semantic session worker was not found at ${Io(d)}. Run npm run build before using built semantic Rust queries.`);return n=Bh(mu(fu(),"scip-query-rust-session-")),t=new JP(d,e.shareEnvironment?{env:YP}:void 0),t.unref(),t},u=()=>{let d=n??Bh(mu(fu(),"scip-query-rust-session-"));return n=d,mu(d,`${r++}.json`)};return{requestSemantic(d,m){if(i)throw new Error("Rust semantic session was already disposed.");let p=l(),f=u(),g=new SharedArrayBuffer(4),h=new Int32Array(g);if(p.postMessage({kind:"semantic",request:d,responsePath:f,sharedBuffer:g}),Atomics.wait(h,0,0,m)==="timed-out")throw c(),new Error(`Rust semantic session worker timed out after ${(m/1e3).toFixed(0)}s`);try{let S=rD(Ct(f,{maxBytes:pn,inputKind:"Rust semantic worker response"}));if(!S.ok)throw new Error(S.error);return S.response}finally{du(f,{force:!0})}},requestImportDefinitions(d,m){if(i)throw new Error("Rust semantic session was already disposed.");let p=l(),f=u(),g=new SharedArrayBuffer(4),h=new Int32Array(g);if(p.postMessage({kind:"import-definitions",request:d,responsePath:f,sharedBuffer:g}),Atomics.wait(h,0,0,m)==="timed-out")throw c(),new Error(`Rust semantic import-definition session worker timed out after ${(m/1e3).toFixed(0)}s`);try{let S=iD(Ct(f,{maxBytes:pn,inputKind:"Rust import-definition worker response"}));if(!S.ok)throw new Error(S.error);return S.response}finally{du(f,{force:!0})}},shutdown(){if(i)return;if(i=!0,!t){a(n),n=null;return}let d=u(),m=new SharedArrayBuffer(4),p=new Int32Array(m);t.postMessage({kind:"shutdown",responsePath:d,sharedBuffer:m}),Atomics.wait(p,0,0,5e3),c()}}}function rD(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 iD(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 oD(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 Ro(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Eo(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Hh(e){return new Map(e.map(t=>[t.symbolId,null]))}function pu(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??[]]))}function sD(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function aD(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 hu(e,t){return t&&t>0?Math.max(e,t):e}function zh(){return new URL("./rust-semantic-session-worker.js",import.meta.url)}function Kh(){return new URL("./rust-semantic-session-server.js",import.meta.url)}function Ra(e,t){return Yn(e)??t}function Ea(e,t){return Wh(e)??t}function Wh(e){if(!e)return null;let t=Number(e);return Number.isInteger(t)&&t>=0?t:null}var Su=15e3,vu=8;function Xh(e,t={}){let n=t.status??va,r=dD(e,n),i=mD(e,n),o=pD(e,n),s=t.referenceResolver||t.calleeResolver||t.signatureResolver||!lD(t)?null:qh(e,n,{fallbackReferenceResolver:r,fallbackCalleeResolver:i,fallbackSignatureResolver:o}),a=t.referenceResolver??s??r,c=t.calleeResolver??s??i,l=t.signatureResolver??s??o,u=t.importUsageResolver??gh(t.sourceImportUsageResolver??uD(),t.importDefinitionResolver??s),d=t.calleeSymbolResolver,m=t.sourceZeroCalleeOracle,p=t.scipOccurrenceCalleeOracle,f=new Map,g=new Map,h=null,b=null,S=()=>(h??=n(e),h),y=()=>{let E=S();return E.dependencyAvailable?b??E:E},x=E=>{if(E.length===0)return new Map;let I=Po(E);try{let w=a.referencesForDefinitions(I),A=S();return b=Ia(A,w),w.available?new Map(w.references):Jn(I,w.references)}catch(w){let A=S();return b=Lo(A,w),Mr(I)}},v=E=>{if(E.length===0)return new Map;let I=Po(E),w=I.filter(Vh);if(w.length===0)return Tr(I);let A=new Map,D=Jh(w,p),k=[];for(let L of w)g.has(L.symbolId)?A.set(L.symbolId,g.get(L.symbolId)??[]):D.has(L.symbolId)?A.set(L.symbolId,D.get(L.symbolId)??[]):Yh(L,m)?A.set(L.symbolId,[]):k.push(L);if(k.length===0)return Ci(I,A,void 0);try{let L=c.calleesForDefinitions(k),F=S();b=Ia(F,L);let P=Ci(k,L.callees,d);for(let[j,B]of P)A.set(j,B);return Ci(I,A,void 0)}catch(L){let F=S();return b=Lo(F,L),Tr(I)}},C=(E,I)=>{let w=Po(E),A=Po(I),D=A.filter(Vh),k=new Map,L=Jh(D,p),F=[];for(let P of D)L.has(P.symbolId)?k.set(P.symbolId,L.get(P.symbolId)??[]):Yh(P,m)?k.set(P.symbolId,[]):F.push(P);if(w.length===0&&F.length===0)return{references:Mr(w),callees:Ci(A,k,void 0)};try{let P=s?s.referencesAndCalleesForDefinitions(w,F):yD(a,c,{referenceDefinitions:w,calleeDefinitions:F}),j=S();b=Ia(j,P);let B=P.available?new Map(P.references):Jn(w,P.references);for(let[G,O]of P.callees)k.set(G,O);let X=Ci(A,k,d);for(let[G,O]of X)g.set(G,O);return{references:B,callees:X}}catch(P){let j=S();return b=Lo(j,P),{references:Mr(w),callees:Tr(A)}}},R=E=>{if(E.length===0)return new Map;let I=Po(E);try{let w=l.signaturesForDefinitions(I),A=S();return b=Ia(A,w),Qh(I,w.signatures)}catch(w){let A=S();return b=Lo(A,w),wa(I)}};return{language:"rust",availability:y,dispose:()=>{s?.dispose()},importUsage:E=>{let I=f.get(E);if(I)return I;try{let w=u.importUsage(E);return f.set(E,w),w}catch(w){let A=S();return b=Lo(A,w),[]}},referencesFor:E=>x([E]).get(E.symbolId)??[],referencesForDefinitions:x,referencesAndCalleesForDefinitions:C,calleesFor:E=>v([E]).get(E.symbolId)??[],calleesForDefinitions:v,signatureFor:E=>R([E]).get(E.symbolId)??null}}function Ia(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 Lo(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 lD(e){if(e.usePersistentSession!==void 0)return e.usePersistentSession;let t=process.env.SCIP_RUST_SEMANTIC_SESSION;return t!=="0"&&t!=="false"}function uD(){return{importUsageFacts:()=>({usage:[],positions:[]})}}function Po(e){return e.map(t=>{let n=t;return{...t,leaf:typeof n.leaf=="string"?n.leaf:z(t.symbol),parentTypeName:n.parentTypeName??null,isFunctionLike:typeof n.isFunctionLike=="boolean"?n.isFunctionLike:Se(t.symbol),isTypeLike:n.isTypeLike??!1,kind:n.kind??null,documentation:n.documentation??null,enclosingSymbol:n.enclosingSymbol??null}})}function Vh(e){return e.isFunctionLike}function Yh(e,t){if(!t)return!1;try{return t(e)}catch{return!1}}function Jh(e,t){if(!t||e.length===0)return new Map;try{return t(e)}catch{return new Map}}function dD(e,t){return{referencesForDefinitions:n=>fD(e,t,n)}}function mD(e,t){return{calleesForDefinitions:n=>gD(e,t,n)}}function pD(e,t){return{signaturesForDefinitions:n=>hD(e,t,n)}}function fD(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:Ru(r),references:Mr(n)};let i=Cu();if(!bu(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,references:Mr(n)};let o=xi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Su),s=La(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),a=xi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,vu),c=La(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),l=wo(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!0}),u={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,...s>0?{referenceRetryTimeoutMs:s}:{},diagnosticsTimeoutMs:c,settleDelayMs:l,concurrency:a},d=yu(process.execPath,[i],{cwd:e,input:JSON.stringify(u),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Pr(n.length,hu(o,u.referenceRetryTimeoutMs),a)}),m=Eu(d.stdout);if(m)return{...xu(m),resolvedBinary:r.resolvedBinary,references:Jn(n,new Map(m.references),new Set(m.incompleteReferenceSymbolIds??[]))};let p=d.error instanceof Error?d.error.message:d.stderr.trim()||`Rust semantic worker exited with status ${d.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:p,references:Mr(n)}}function gD(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:Ru(r),callees:Tr(n)};let i=Cu();if(!bu(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,callees:Tr(n)};let o=xi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Su),s=xi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,vu),a=La(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=wo(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!0}),l={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:c,concurrency:s,includeReferences:!1,includeCallees:!0},u=yu(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Pr(n.length,o,s)}),d=Eu(u.stdout);if(d)return{...xu(d),resolvedBinary:r.resolvedBinary,callees:Ci(n,new Map(d.callees??[]),void 0)};let m=u.error instanceof Error?u.error.message:u.stderr.trim()||`Rust semantic worker exited with status ${u.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:m,callees:Tr(n)}}function hD(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:Ru(r),signatures:wa(n)};let i=Cu();if(!bu(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,signatures:wa(n)};let o=xi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Su),s=xi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,vu),a=La(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=wo(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!1,includeSignatures:!0}),l={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:c,concurrency:s,includeReferences:!1,includeCallees:!1,includeSignatures:!0},u=yu(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Pr(n.length,o,s)}),d=Eu(u.stdout);if(d)return{...xu(d),resolvedBinary:r.resolvedBinary,signatures:Qh(n,new Map(d.signatures??[]))};let m=u.error instanceof Error?u.error.message:u.stderr.trim()||`Rust semantic worker exited with status ${u.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:m,signatures:wa(n)}}function yD(e,t,n){let r=n.referenceDefinitions.length>0?e.referencesForDefinitions(n.referenceDefinitions):{available:!0,references:Mr(n.referenceDefinitions)},i=n.calleeDefinitions.length>0?t.calleesForDefinitions(n.calleeDefinitions):{available:!0,callees:Tr(n.calleeDefinitions)},o={resolvedBinary:r.resolvedBinary??i.resolvedBinary,references:r.references,callees:i.callees};return r.available&&i.available?{available:!0,...o}:{available:!1,reason:(r.available?void 0:r.reason)??(i.available?void 0:i.reason)??"Rust semantic resolution was unavailable.",...o}}function Mr(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Tr(e){return new Map(e.map(t=>[t.symbolId,[]]))}function wa(e){return new Map(e.map(t=>[t.symbolId,null]))}function Ci(e,t,n){let r=0,i=0;return N("rust.semantic.callees.complete-map",()=>{let o=new Map;for(let s of e){let a=t.get(s.symbolId)??[];a.length>0&&(r+=1),i+=a.length,o.set(s.symbolId,a.map(c=>({...c,symbol:n?n(c):c.symbol})))}return o},()=>({definitions:e.length,rows:r,callees:i,resolveSymbols:!!n}))}function Qh(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function Cu(){return cD(new URL("./rust-semantic-worker.js",import.meta.url))}function xu(e){return e.available?{available:!0}:{available:!1,reason:e.reason}}function Ru(e){return e.available?"rust-analyzer binary path is unavailable.":e.reason}function Eu(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;if(typeof n.available!="boolean"||!Array.isArray(n.references)||n.available===!1&&typeof n.reason!="string"||n.available===!0&&n.reason!==void 0)return null;let r={references:n.references,incompleteReferenceSymbolIds:Array.isArray(n.incompleteReferenceSymbolIds)?n.incompleteReferenceSymbolIds.filter(i=>typeof i=="number"):void 0,callees:Array.isArray(n.callees)?n.callees:void 0,signatures:Array.isArray(n.signatures)?n.signatures:void 0};return n.available===!0?{available:!0,...r}:{available:!1,reason:String(n.reason),...r}}catch{return null}}function xi(e,t){return Yn(e)??t}function La(e,t){if(!e)return t;let n=Number(e);return Number.isInteger(n)&&n>=0?n:t}import{existsSync as bD}from"fs";import{deserializeSCIP as SD,SymbolRole as vD}from"@c4312/scip";var Iu=new WeakMap;function ey(e,t){let n=t.filter(CD);if(n.length===0)return new Map;let r=!1,i=0,o=0;return N("rust.scip-occurrence.callees",()=>{let s=ED(e);if(r=!!s,!s)return new Map;let a=new Map;for(let c of n){let l=xD(e,s,c);l!==null&&(a.set(c.symbolId,l),i+=1,o+=l.length)}return a},()=>({definitions:t.length,candidates:n.length,indexAvailable:r,resolvedDefinitions:i,resolvedCallees:o}))}function CD(e){return!(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||!e.isFunctionLike||e.leaf==="main"||He(e.symbol))}function xD(e,t,n){let r=K(e,n.relativePath);if(!r||r.language!=="rust")return null;let i=r.callables.find(l=>l.startLine!==n.startLine||l.endLine!==n.endLine?!1:l.name===n.leaf||n.leaf.endsWith(l.name)||l.name.endsWith(n.leaf));if(!i)return null;let o=r.callSites.filter(l=>l.line>=i.startLine&&l.line<=i.endLine);if(o.length===0)return null;let s=(t.occurrencesByFile.get(n.relativePath)??[]).filter(l=>l.line>=i.startLine&&l.line<=i.endLine&&l.callee.symbol!==n.symbol);if(s.some(l=>l.traitImplMember)||!RD(o,s))return null;let a=[],c=new Set;for(let l of s){let u=`${l.callee.symbol}\0${l.callee.file}\0${l.callee.line}`;c.has(u)||(c.add(u),a.push(l.callee))}return a}function RD(e,t){let n=Zh(e),r=Zh(t);if(n.size!==r.size)return!1;for(let[i,o]of n)if(r.get(i)!==o)return!1;return!0}function Zh(e){let t=new Map;for(let n of e){let r=n.calleeLeaf??n.leaf;if(!r)continue;let i=`${n.line}\0${r}`;t.set(i,(t.get(i)??0)+1)}return t}function ED(e){if(Iu.has(e))return Iu.get(e)??null;let t=ID(e);return Iu.set(e,t),t}function ID(e){if(!e.generation.indexPath||!bD(e.generation.indexPath))return null;try{let t=ve(e).filter(o=>o.symbol.startsWith("rust-analyzer ")&&o.relativePath.endsWith(".rs")&&o.isFunctionLike),n=new Map(t.map(o=>[o.symbol,o])),r=SD(ti(e.generation.indexPath,{inputKind:"SCIP occurrence-callee index",maxBytes:ei})),i=new Map;for(let o of r.documents??[]){let s=o.relativePath;if(!s||!s.endsWith(".rs")||e.isIgnored(s))continue;let a=[];for(let c of o.occurrences??[]){if(!c.symbol||(c.symbolRoles&vD.Definition)!==0)continue;let l=n.get(c.symbol);if(!l)continue;let u=c.range?.[0];Number.isInteger(u)&&a.push({line:u,leaf:l.leaf,traitImplMember:He(l.symbol),callee:{symbol:l.symbol,file:l.relativePath,line:l.startLine,callsiteLine:u}})}i.set(s,a)}return{occurrencesByFile:i}}catch{return null}}var Pa=class{sessions=new WeakMap;getOrCreate(t,n,r){let i=wD(t,n),o=this.sessions.get(t);o||(o=new Map,this.sessions.set(t,o));let s=o.get(i);if(s)return s.hits+=1,s.lastUsedAtMs=Date.now(),s.provider;let a=Date.now(),c=r();return o.set(i,{key:i,language:n,projectRoot:t.config.projectRoot,provider:c,createdAtMs:a,lastUsedAtMs:a,hits:1}),c}sessionsFor(t){return[...this.sessions.get(t)?.values()??[]]}clear(t){let n=this.sessions.get(t);if(n)for(let r of n.values())r.provider.dispose?.();this.sessions.delete(t)}};function wD(e,t){return`${e.config.projectRoot}:${t}-workspace`}import{randomUUID as nM}from"crypto";import{existsSync as rM}from"fs";import{dirname as Py}from"path";function ty(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(typeof t.available!="boolean"||t.dependencyAvailable!==void 0&&typeof t.dependencyAvailable!="boolean"||t.tsconfigPath!==void 0&&typeof t.tsconfigPath!="string"||t.tsconfigPaths!==void 0&&(!Array.isArray(t.tsconfigPaths)||!t.tsconfigPaths.every(n=>typeof n=="string"))||t.resolvedBinary!==void 0&&typeof t.resolvedBinary!="string"||t.note!==void 0&&typeof t.note!="string")return null;if(t.available===!0){if(t.reason!==void 0)return null}else if(typeof t.reason!="string"||t.reason.length===0)return null;return t}import{performance as le}from"perf_hooks";function Mt(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}import iy from"path";import{realpathSync as ny}from"fs";function LD(e,t){return e.getReferences().map(n=>{let r=n.getNode();return Da(r,t)})}function PD(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function oy(e,t,n,r){let i=[];for(let o of PD(e))for(let s of LD(o,r))s.file===t.relativePath&&s.line>=t.startLine&&s.line<=t.endLine||i.push(s);for(let o of n)i.push(o);return Ri(i)}function sy(e,t,n,r){let i=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();Ei(r,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||i.push({location:Da(a,r),node:a}))}return i}function Da(e,t){let n=e.getSourceFile(),r=n.getLineAndColumnAtPos(e.getStart());return{file:Ei(t,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function ay(e,t,n){let r=e.getSourceFile(),i=Lu(r,e),o=e.getText(),s=new RegExp(`\\b${xe(o)}\\b`,"g"),a=r.getFullText().split(`
51
- `),c=[];for(let l=0;l<a.length;l++){if(l===i)continue;let u=a[l]??"";s.lastIndex=0;let d;for(;(d=s.exec(u))!==null;)c.push({file:t,line:l,column:d.index})}return Ri(c.filter(l=>Ei(n,iy.join(n,l.file))===t))}function wu(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 Lu(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function Ri(e){let t=new Set,n=[];for(let r of e){let i=`${r.file}:${r.line}:${r.column}`;t.has(i)||(t.add(i),n.push(r))}return n}function Ei(e,t){let n=e||process.cwd(),r=ry(n,t);if(r)return r;try{return ry(ny(n),ny(t))}catch{return null}}function ry(e,t){let n=iy.relative(e,t).replace(/\\/g,"/");return!n||n===".."||n.startsWith("../")?null:n}function cy(e,t,n,r){let i=DD(t,r);return i.size===0?new Map:MD(e,n,i)}function DD(e,t){let n=new Map;for(let r of U(e,t)){let i=z(r.symbol)??r.leaf;if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push(r)}return n}function MD(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of TD(e,o)){let a=n.get(s);if(!a)continue;let c=Lu(t,o);for(let l of a){if(c<l.startLine-1||c>l.endLine+1)continue;let u=Math.abs(c-l.startLine),d=i.get(l.symbolId);d!==void 0&&d<=u||(i.set(l.symbolId,u),r.set(l.symbolId,o))}}}),r}function TD(e,t){let n=[],r=i=>{i&&!n.includes(i)&&n.push(i)};if("getNameNode"in t&&typeof t.getNameNode=="function"){let i=t.getNameNode();r(i?.getText())}if("getName"in t&&typeof t.getName=="function"){let i=t.getName();r(i)}return e.Node.isIdentifier(t)&&r(t.getText()),n}var AD=Nn("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function ly(e,t,n,r){let i=Mu(e,t),o=Pu(i.get(r)??[],n);if(o)return o;let s=[];for(let a of i.values())for(let c of a)((c.leaf||z(c.symbol)||"").includes(r)||c.symbol.includes(r))&&s.push(c);return Pu(s,n)}function Du(e,t,n,r){return Pu(Mu(e,t).get(r)??[],n)}function uy(e,t){let n=new Map;for(let[r,i]of Mu(e,t)){let o=i[0];o&&n.set(r,o)}return n}function Mu(e,t){return AD.get(e,t,()=>{let n=new Map;for(let r of U(e,t)){let i=r.leaf||z(r.symbol);if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push({...r,leaf:i})}for(let r of n.values())r.sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine||i.symbolId-o.symbolId);return n})}function Pu(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let i of e){let o=Math.abs(i.startLine-t);(o<r||o===r&&n&&i.startLine<n.startLine)&&(n=i,r=o)}return n}import FD from"path";import{realpathSync as kD}from"fs";function dy(e,t){let n=new Map,r=null,i=null,o=()=>(i??=Q(e,{extensions:Zs}),i),s=()=>(r??=N("typescript.source-file-index",()=>ND(e.config.projectRoot,t,o()),()=>({projects:t.length,indexedDocuments:o().length})),r),a=c=>Gn(c)?Mt(n,c,()=>{let l=my(e.config.projectRoot,c);if(!l)return null;for(let{project:u,sourceFiles:d}of s()){let m=d.get(l)??null;if(m||(m=u.addSourceFileAtPathIfExists(l)??null,m&&Tu(d,m)),m)return{project:u,sourceFile:m}}return null}):null;return{sourceFile:c=>a(c)?.sourceFile??null,sourceFileMatch:a,indexedTypeScriptLikeDocuments:o}}function ND(e,t,n){let r=t.map(({project:i})=>{let o=new Map;for(let s of i.getSourceFiles())Tu(o,s);return{project:i,sourceFiles:o}});for(let i of n){let o=my(e,i);if(o)for(let s of r){if(s.sourceFiles.has(o))break;let a=s.project.addSourceFileAtPathIfExists(o)??null;if(a){Tu(s.sourceFiles,a);break}}}return r}function Tu(e,t){let n=Au(t.getFilePath());e.set(n,t);try{e.set(Au(kD(n)),t)}catch(r){if(!Je(r))throw r}}function my(e,t){try{return Au(As(e,t,{inputKind:"indexed TypeScript source file"}).absolutePath)}catch(n){if(!Je(n))throw n;return null}}function Au(e){return FD.resolve(e)}function Fu(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function py(e){let t=`${e.relativeDir}/src`;return[`${t}/index.ts`,`${t}/index.tsx`,`${t}/index.mts`,`${t}/index.cts`]}import{existsSync as Do}from"fs";import Ze from"path";var ku=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Nu(e,t){let r=t?Ze.dirname(Ze.join(e,t)):e,i=Ze.resolve(e);for(;r.startsWith(i);){for(let s of ku){let a=Ze.join(r,s);if(Do(a))return a}let o=Ze.dirname(r);if(o===r)break;r=o}for(let o of ku){let s=Ze.join(e,o);if(Do(s))return s}return null}function fy(e){let t=e.config.projectRoot,n=new Set(_D(t,e.config.semantic?.typescript?.tsconfigs)),r=Q(e,{includeIgnored:!1,extensions:Zs});for(let i of r){let o=Nu(t,i);o&&n.add(Ze.resolve(o))}if(n.size===0){let i=Nu(t);i&&n.add(Ze.resolve(i))}return[...n].filter(i=>!gy(t,i)).sort((i,o)=>i.localeCompare(o))}function _D(e,t=[]){let n=new Set;for(let r of t){let i=Ze.isAbsolute(r)?r:Ze.join(e,r);Do(i)&&n.add(Ze.resolve(i))}for(let r of OD(e))for(let i of ku){let o=Ze.join(r,i);Do(o)&&n.add(Ze.resolve(o))}if(n.size===0){let r=Nu(e);r&&n.add(Ze.resolve(r))}return[...n].filter(r=>!gy(e,r)).sort((r,i)=>r.localeCompare(i))}function OD(e){let t=Ze.join(e,"package.json");if(!Do(t))return[];let n;try{n=JSON.parse(Ve(t,"project package manifest"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>yf(e,i))}function gy(e,t){let n=Ze.relative(e,t).replace(/\\/g,"/");return n.startsWith("..")||n.includes("/node_modules/")||n.startsWith("node_modules/")||n.includes("/dist/")||n.startsWith("dist/")}var BD=32;function xy(e,t){let n=N("typescript.provider.load",()=>ea());if(!n)return ta("ts-morph is not installed");let r=N("typescript.provider.tsconfig-discovery",()=>fy(e));if(r.length===0)return ta("no tsconfig found");try{let i=N("typescript.provider.project-bundles",()=>eg(n,r),()=>({tsconfigs:r.length}));return $D(e,n,i)}catch(i){return ta(i instanceof Error?i.message:String(i),r[0],r)}}function $D(e,t,n,r={}){return N("typescript.provider.construct",()=>new _u(e,t,n),()=>({tsconfigs:n.length,reusedProjects:r.reusedProjects===!0}))}var _u=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=hf(t.config.projectRoot),this.sourceFiles=dy(t,r)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;compilerCheckerCache=new WeakMap;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(t=>t.tsconfigPath)}}importUsage(t){return Mt(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let r=HD();return N("typescript.import-usage.file",()=>this.importUsageForSourceFile(t,n,r),()=>({file:t,...r}))})}referencesFor(t){return Mt(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);return this.referencesForDefinitionNode(t,n)})}referencesForDefinitions(t,n={}){let r=new Map,i=be(),o=[];for(let u of t){let d=this.referencesCache.get(u.symbolId);d?r.set(u.symbolId,d):o.push(u)}if(o.length===0)return r;let s=o,a=n.exact?[]:o.filter(u=>!yy(u));if(a.length>=BD){let u=this.referencesForDefinitionsBySymbolScan(a);for(let d of a){let m=u.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,m),r.set(d.symbolId,m)}if(s=o.filter(d=>yy(d)),s.length===0)return r}let c=new Map;for(let u of s){let d=c.get(u.relativePath);d?d.push(u):c.set(u.relativePath,[u])}let l=[];for(let[u,d]of c){let m=by();N("typescript.references-map.file",()=>{let p=this.definitionNodesForFile(u);for(let f of d){i&&(m.cacheMisses+=1);let g=p.get(f.symbolId)??null;i&&(g?m.nodeHits+=1:m.nodeMisses+=1);try{let h=this.referencesForDefinitionNode(f,g,i?m:void 0);this.referencesCache.set(f.symbolId,h),r.set(f.symbolId,h)}catch{m.preciseSearchFailures+=1,l.push(f)}}},()=>({relativePath:u,definitions:d.length,...vy(m)}))}if(l.length>0){let u=this.referencesForDefinitionsBySymbolScan(l);for(let d of l){let m=u.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,m),r.set(d.symbolId,m)}}return r}referenceFragmentsForFiles(t){let n=ve(this.db).filter(o=>Gn(o.relativePath)),r=t.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(n,r);return tg(n,i,r)}referencesForDefinitionsBySymbolScan(t,n){let r=be(),i=by(),o=new Map,s=new Set(t.map(c=>c.symbolId)),a=new Map(t.map(c=>[c.symbolId,c]));for(let c of t)o.set(c.symbolId,[]);return N("typescript.references-map.inverted-scan",()=>{let c=r?le.now():0,l=n?this.packageImportReferencesForFiles(n):this.packageImportReferences();for(let h of t){let b=l.get(h.symbolId)??[];if(b.length>0){let S=o.get(h.symbolId)??[];S.push(...b),o.set(h.symbolId,S)}r&&(i.packageReferenceCount+=b.length)}r&&(i.packageRefsMs+=le.now()-c);let u=new Map,d=new Map,m=this.hierarchyTargetsForDefinitions(t),p=new Set(t.map(h=>h.leaf).filter(Boolean)),f=r?le.now():0;for(let h of n??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(h))continue;let b=this.sourceFiles.sourceFile(h);b&&(r&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(b,h,s,a,m,p,u,d,o,r?i:void 0))}r&&(i.scanMs+=le.now()-f);let g=r?le.now():0;this.addHierarchyMemberReferences(t,o,r?i:void 0),r&&(i.hierarchyMs+=le.now()-g);for(let[h,b]of o){let S=Ri(b);o.set(h,S),r&&(i.referenceCount+=S.length)}},()=>({definitions:t.length,...vy(i)})),o}addReferencesFromSourceFileScan(t,n,r,i,o,s,a,c,l,u){let d=this.compilerCheckerForSourceFile(t),m=t.compilerNode,p=GD(t),f=g=>{if(this.tsMorph.ts.isIdentifier(g)){if(u&&(u.identifiers+=1),!s.has(g.text)&&!p.has(g.text)){this.tsMorph.ts.forEachChild(g,f);return}let h=this.compilerReferenceSymbol(d,g,u);if(h){let b;a.has(h)?b=a.get(h)??null:(b=this.referenceDefinitionFromCompilerSymbol(h),a.set(h,b)),u&&(b?u.targetHits+=1:u.targetMisses+=1);let S=Mt(c,h,()=>this.compilerSymbolKeys(h)),y=null,x=null,v=b&&r.has(b.symbolId)?i.get(b.symbolId):void 0;if(v&&(y=Ma(m,g),!hy(v,n,y))){let C=m.getLineAndCharacterOfPosition(g.getStart(m));x={file:n,line:C.line,column:C.character};let R=l.get(v.symbolId)??[];R.push(x),l.set(v.symbolId,R),u&&(u.requestedHits+=1)}for(let C of S)for(let R of o.get(C)?.values()??[]){if(y??=Ma(m,g),hy(R,n,y))continue;if(!x){let I=m.getLineAndCharacterOfPosition(g.getStart(m));x={file:n,line:I.line,column:I.character}}let E=l.get(R.symbolId)??[];E.push(x),l.set(R.symbolId,E),u&&(u.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(g,f)};f(m)}hierarchyTargetsMemo=null;hierarchyTargetsForDefinitions(t){let n=YD(t);if(this.hierarchyTargetsMemo?.key===n)return this.hierarchyTargetsMemo.targets;let r=dt(this.db),i=`definitions:${n}`,o=!1,s=N("typescript.references-map.hierarchy-targets",()=>{if(r){let c=Sy.read(this.db,i,r);if(c&&c.projectRoot===this.db.config.projectRoot)return o=!0,VD(c,t)}let a=this.computeHierarchyTargets(t);return r&&Sy.write(this.db,i,r,{version:Ry,projectRoot:this.db.config.projectRoot,entries:[...a].map(([c,l])=>[c,[...l.values()].map(u=>u.symbol)])}),a},()=>({definitions:t.length,hit:o}));return this.hierarchyTargetsMemo={key:n,targets:s},s}computeHierarchyTargets(t){let n=new Map;for(let r of t){let i=this.nodeForDefinition(r),o=i?.compilerNode;if(!o||!this.isHierarchyMethod(o))continue;let s=o.parent;if(!this.isHierarchyContainer(s))continue;let a=this.compilerCheckerForSourceFile(i.getSourceFile()),c=a.getSymbolAtLocation(o.name);if(c)for(let l of this.hierarchyMemberSymbols(a,s,c))for(let u of this.compilerSymbolKeys(l)){let d=n.get(u)??new Map;d.set(r.symbolId,r),n.set(u,d)}}return n}hierarchyMemberSymbols(t,n,r){let i=new Set,o=new Set,s=(a,c,l)=>{if(!o.has(a)){o.add(a),i.add(c);for(let u of l){let d=u.getProperty(r.name);d&&s(u,d,this.hierarchyAncestorTypesForType(t,u))}}};return s(t.getTypeAtLocation(n),r,this.hierarchyAncestorTypes(t,n)),i}addHierarchyMemberReferences(t,n,r){let i=new Map;for(let o of t){let s=this.nodeForDefinition(o),a=s?.compilerNode;if(!a||!this.isHierarchyMethod(a))continue;let c=a.parent;if(!this.isHierarchyContainer(c))continue;let l=this.compilerCheckerForSourceFile(s.getSourceFile()),u=l.getSymbolAtLocation(a.name);if(!u)continue;let d=a.getSourceFile(),m=d.getLineAndCharacterOfPosition(a.name.getStart(d)),p={definition:o,location:{file:o.relativePath,line:m.line,column:m.character}},f=n.get(o.symbolId)??[];for(let h of this.hierarchyMemberSymbols(l,c,u))if(h!==u)for(let b of this.compilerSymbolLocations(h))f.push(b),r&&(r.hierarchyReferences+=1);n.set(o.symbolId,f);let g=this.hierarchyRootMemberSymbols(l,c,u);for(let h of g){let b=i.get(h)??new Map;b.set(o.symbolId,p),i.set(h,b)}r&&(r.hierarchyDefinitions+=1)}for(let o of i.values())if(!(o.size<2)){r&&(r.hierarchyFamilies+=1);for(let{definition:s}of o.values()){let a=n.get(s.symbolId)??[];for(let c of o.values())c.definition.symbolId!==s.symbolId&&(a.push(c.location),r&&(r.hierarchyReferences+=1));n.set(s.symbolId,a)}}}hierarchyRootMemberSymbols(t,n,r){let i=new Set,o=new Set,s=(a,c,l)=>{if(o.has(a))return;o.add(a);let u=!1;for(let d of l){let m=d.getProperty(r.name);m&&(u=!0,s(d,m,this.hierarchyAncestorTypesForType(t,d)))}if(!u)for(let d of this.compilerSymbolKeys(c))i.add(d)};return s(t.getTypeAtLocation(n),r,this.hierarchyAncestorTypes(t,n)),i}compilerSymbolKeys(t){return(t.declarations??[]).map(n=>{let r=n.getSourceFile();return`${r.fileName}\0${n.getStart(r)}\0${t.name}`})}compilerSymbolLocations(t){let n=[];for(let r of t.declarations??[]){let i=r.getSourceFile(),o=Ei(this.db.config.projectRoot,i.fileName);if(!o)continue;let s=r.name,a=i.getLineAndCharacterOfPosition((s??r).getStart(i));n.push({file:o,line:a.line,column:a.character})}return n}baseTypes(t,n){try{return t.getBaseTypes(n)??[]}catch{return[]}}hierarchyAncestorTypes(t,n){let r=new Set(this.hierarchyAncestorTypesForType(t,t.getTypeAtLocation(n)));for(let i of n.heritageClauses??[])for(let o of i.types)r.add(t.getTypeAtLocation(o));return[...r]}hierarchyAncestorTypesForType(t,n){let r=new Set(this.baseTypes(t,n));for(let i of n.getSymbol()?.declarations??[])if(this.isHierarchyContainer(i))for(let o of i.heritageClauses??[])for(let s of o.types)r.add(t.getTypeAtLocation(s));return[...r]}isHierarchyMethod(t){return this.tsMorph.ts.isMethodDeclaration(t)||this.tsMorph.ts.isMethodSignature(t)}isHierarchyContainer(t){return this.tsMorph.ts.isClassDeclaration(t)||this.tsMorph.ts.isClassExpression(t)||this.tsMorph.ts.isInterfaceDeclaration(t)}compilerReferenceSymbol(t,n,r){r&&(r.symbolLookups+=1);let i=t.getSymbolAtLocation(n);if(i){if((i.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return i;try{return r&&(r.aliasResolutions+=1),t.getAliasedSymbol(i)}catch{return i}}}calleesFor(t){return Mt(this.calleesCache,t.symbolId,()=>Mt(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}calleesForDefinitions(t){let n=new Map,r=new Map;for(let i of t){let o=r.get(i.relativePath);o?o.push(i):r.set(i.relativePath,[i])}for(let[i,o]of r){let s=this.fileCalleesCache.get(i),a=new Set(o.map(l=>l.symbolId)),c=s??this.calleeMapForFile(i,a);for(let l of o){let u=c.get(l.symbolId)??[];this.calleesCache.set(l.symbolId,u),n.set(l.symbolId,u)}}return n}referencesForDefinitionNode(t,n,r){let i=r?le.now():0,o=this.packageImportReferencesForDefinition(t);if(r&&(r.packageRefsMs+=le.now()-i,r.packageReferenceCount+=o.length),!n)return o;let s=r?le.now():0,a=oy(n,t,o,this.db.config.projectRoot);return r&&(r.semanticRefsMs+=le.now()-s,r.referenceCount+=a.length),a}signatureFor(t){return Mt(this.signatureCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);if(!n||!this.tsMorph.Node.isFunctionDeclaration(n)&&!this.tsMorph.Node.isMethodDeclaration(n)&&!this.tsMorph.Node.isArrowFunction(n)&&!this.tsMorph.Node.isFunctionExpression(n)&&!this.tsMorph.Node.isConstructorDeclaration(n))return null;let r=n.getType().getCallSignatures()[0];if(!r)return null;let i=r.getParameters().map(s=>{let a=s.getDeclarations()[0],c=a?s.getTypeAtLocation(a).getText(a):s.getValueDeclaration()?.getType().getText()??"unknown";return Cy(c)}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${Cy(o)}`})}importUsageForSourceFile(t,n,r){let i=[],o=new Map;for(let s of n.getImportDeclarations()){r.declarations+=1;let a=Pl(this.db,t,s.getModuleSpecifierValue()),c=s.getImportClause()?.isTypeOnly()??!1;for(let l of Ou(s)){r.entries+=1;let u=c?null:l.identifier?.getSymbol()?.compilerSymbol??null;!c&&l.identifier&&(u?r.bindingSymbols+=1:r.missingBindingSymbols+=1);let d={sourcePath:a,entry:l,typeOnlyDeclaration:c,bindingSymbol:u,references:[]};if(i.push(d),c||!l.localName||!u)continue;let m=o.get(l.localName);m?m.push(d):o.set(l.localName,[d])}}return o.size>0&&n.forEachDescendant(s=>{if(s.getKindName()!=="Identifier")return;let a=o.get(s.getText());if(!a||UD(s))return;r.scannedIdentifiers+=1;let c=s.getSymbol()?.compilerSymbol;if(r.symbolLookups+=1,!!c){for(let l of a)if(l.bindingSymbol===c){l.references.push({location:Da(s,this.db.config.projectRoot),node:s}),r.matchedReferences+=1;break}}}),i.map(s=>s.typeOnlyDeclaration?jD(t,s.sourcePath,s.entry):s.entry.identifier&&!s.bindingSymbol?(r.fallbackEntries+=1,this.valueImportUsageForEntry(t,s.sourcePath,s.entry)):this.valueImportUsageFromLocations(t,s.sourcePath,s.entry,s.references))}valueImportUsageForEntry(t,n,r){let i=r.identifier?r.identifier.findReferences():[],o=[];for(let s of i)for(let a of sy(s,t,r.identifier,this.db.config.projectRoot))o.push(a);return this.valueImportUsageFromLocations(t,n,r,o)}valueImportUsageFromLocations(t,n,r,i){let o=i.some(c=>!wu(c.node)),s=i.some(c=>wu(c.node)),a=r.isTypeOnly;return{importer:t,sourcePath:n,importedName:r.importedName,localName:r.localName,kind:r.kind,isTypeOnly:a,isUsed:a||i.length>0,isTypeUsed:a||s,isValueUsed:o,references:i.map(c=>c.location)}}packageImportReferencesForDefinition(t){return this.packageImportReferences().get(t.symbolId)??[]}packageImportReferencesForFiles(t){let n=new Map,r=new Set;for(let o of t){let s=this.sourceFiles.sourceFile(o);if(s)for(let a of s.getImportDeclarations()){let c=Fu(this.workspacePackages,a.getModuleSpecifierValue());c&&r.add(c)}}if(r.size===0)return n;let i=this.packageExportsForNames(r);for(let o of t)this.addPackageImportReferencesForDocument(n,i,o);for(let[o,s]of n)n.set(o,Ri(s));return n}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let t=new Map,n=this.packageExports();for(let r of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(t,n,r);for(let[r,i]of t)t.set(r,Ri(i));return this.packageImportReferenceIndex=t,t}addPackageImportReferencesForDocument(t,n,r){if(this.db.isIgnored(r))return;let i=this.sourceFiles.sourceFileMatch(r);if(i)for(let o of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(t,n,r,o)}addPackageImportReferencesForDeclaration(t,n,r,i){let o=Fu(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of Ou(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=ay(a.identifier,r,this.db.config.projectRoot);l.length>0&&JD(t,c,l)}}packageExports(){return this.packageExportIndex?this.packageExportIndex:(this.packageExportIndex=this.packageExportsForNames(new Set(this.workspacePackages.map(t=>t.name))),this.packageExportIndex)}packageExportsForNames(t){let n=new Map;for(let r of this.workspacePackages){if(!t.has(r.name))continue;let i=new Map;for(let o of py(r))this.collectPackageExports(r,o,i,new Set);i.size>0&&n.set(r.name,i)}return n}collectPackageExports(t,n,r,i){if(i.has(n))return;i.add(n);let o=this.sourceFiles.sourceFile(n);if(o)for(let s of o.getExportDeclarations()){let a=s.getModuleSpecifierValue(),c=a?Pl(this.db,n,a):n;if(!c||!c.startsWith(`${t.relativeDir}/src/`))continue;let l=s.getNamedExports();if(l.length===0){if(s.isNamespaceExport())continue;this.collectPackageExports(t,c,r,i);continue}for(let u of l){let d=u.getNameNode().getText(),m=u.getAliasNode()?.getText()??d,p=this.indexedDefinitionByLeaf(c,d);if(!p)continue;let f=r.get(m);f||(f=new Set,r.set(m,f)),f.add(p.symbolId)}}}indexedDefinitionByLeaf(t,n){return Mt(this.indexedDefinitionLeafCache,t,()=>uy(this.db,t)).get(n)??null}nodeForDefinition(t){return Mt(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return Mt(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?cy(this.tsMorph,this.db,n,t):new Map})}referenceDefinitionFromCompilerSymbol(t){return this.definitionFromCompilerSymbol(t,void 0,!0)}definitionFromCompilerSymbol(t,n,r=!1){let i=t.name,o=n?le.now():0,s=t.declarations??[];n&&(n.declarationsMs+=le.now()-o,n.declarationChecks+=s.length);for(let a of s){let c=n?le.now():0,l=a.getSourceFile(),u=Ei(this.db.config.projectRoot,l.fileName),d=l.getLineAndCharacterOfPosition(a.getStart(l)).line;if(n&&(n.declarationLocationMs+=le.now()-c),!u||this.db.isIgnored(u))continue;let m=n?le.now():0,p=this.compilerDeclarationName(a),f=r?Du(this.db,u,d,i)??(p&&p!==i?Du(this.db,u,d,p):null):ly(this.db,u,d,i);if(n&&(n.indexedLookupMs+=le.now()-m),f)return{symbolId:f.symbolId,symbol:f.symbol,file:f.relativePath,line:f.startLine}}return null}compilerDeclarationName(t){let n=t.name;return n&&this.tsMorph.ts.isIdentifier(n)?n.text:null}calleeMapForFile(t,n){let r=be(),i=0,o=0,s=0,a=0,c=0,l=0,u=0,d=0,m=r?KD():void 0;return N("typescript.callee-map.file",()=>{let p=r?le.now():0,f=this.sourceFiles.sourceFile(t);if(r&&(c=Math.round(le.now()-p)),!f)return new Map;let g=r?le.now():0,h=U(this.db,t).sort((E,I)=>E.startLine-I.startLine||I.endLine-E.endLine);if(r&&(l=Math.round(le.now()-g)),i=h.length,h.length===0)return new Map;let b=new Map,S=r?le.now():0,y=this.compilerCheckerForSourceFile(f),x=f.compilerNode;r&&(u=Math.round(le.now()-S));let v=new Map,C=E=>{if(this.tsMorph.ts.isCallExpression(E)||this.tsMorph.ts.isNewExpression(E)){r&&(o+=1);let I=this.semanticCalleeForCallNode(y,x,h,E,v,n,m);I&&(r&&(s+=1),qD(b,I.callerId,I.target))}this.tsMorph.ts.forEachChild(E,C)},R=r?le.now():0;C(x),r&&(d=Math.round(le.now()-R));for(let[E,I]of b)b.set(E,XD(I));return a=b.size,b},()=>({relativePath:t,definitions:i,callNodes:o,resolvedCallees:s,outputRows:a,requestedDefinitions:n?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:u,traversalMs:d,...m?WD(m):{}}))}semanticCalleeForCallNode(t,n,r,i,o,s,a){let c=a?le.now():0,l=zD(r,Ma(n,i));if(a&&(a.callerLookupMs+=le.now()-c),!l)return null;if(s&&!s.has(l.symbolId))return a&&(a.skippedUnrequestedCallers+=1),null;let u=i.expression,d=this.compilerSymbolForExpression(t,u,a),m=null;if(d)if(a&&(a.targetSymbolHits+=1),o.has(d))a&&(a.compilerSymbolCacheHits+=1),m=o.get(d)??null;else{a&&(a.compilerSymbolCacheMisses+=1);let p=a?le.now():0;m=this.definitionFromCompilerSymbol(d,a),a&&(a.targetLookupMs+=le.now()-p),o.set(d,m)}else a&&(a.targetMisses+=1);return m?{callerId:l.symbolId,target:{symbol:m.symbol,file:m.file,line:m.line,callsiteLine:Ma(n,i)}}:null}compilerSymbolForExpression(t,n,r){let i=r?le.now():0,o=t.getSymbolAtLocation(n);if(r&&(r.expressionSymbolMs+=le.now()-i),o)return o;r&&(r.typeFallbacks+=1);let s=r?le.now():0,a=t.getTypeAtLocation(n).getSymbol();return r&&(r.typeSymbolMs+=le.now()-s),a}compilerCheckerForSourceFile(t){let n=t.getProject(),r=this.compilerCheckerCache.get(n);return r||(r=n.getTypeChecker().compilerObject,this.compilerCheckerCache.set(n,r)),r}};function Ou(e){let t=[],n=e.getDefaultImport();n&&t.push({identifier:n,importedName:"default",localName:n.getText(),kind:"default",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});let r=e.getNamespaceImport();r&&t.push({identifier:r,importedName:"*",localName:r.getText(),kind:"namespace",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});for(let i of e.getNamedImports()){let o=i.getNameNode(),a=i.getAliasNode()??(o.getKindName()==="Identifier"?o:null);t.push({identifier:a,importedName:o.getText(),localName:a?.getText()??o.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(e.getImportClause()?.isTypeOnly()??!1)})}return t.length===0&&t.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),t}function jD(e,t,n){return{importer:e,sourcePath:t,importedName:n.importedName,localName:n.localName,kind:n.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function HD(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function UD(e){for(let t=e;t;t=t.getParent())if(t.getKindName()==="ImportDeclaration")return!0;return!1}function qD(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function GD(e){let t=new Set;for(let n of e.getImportDeclarations())for(let r of Ou(n))r.localName&&t.add(r.localName);return t}function zD(e,t){let n=null;for(let r of e)t<r.startLine||t>r.endLine||(!n||r.startLine>=n.startLine)&&(n=r);return n}function Ma(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line}function hy(e,t,n){return t===e.relativePath&&n>=e.startLine&&n<=e.endLine}function yy(e){return e.symbol.includes("#")?Lt(e.symbol)==="type"&&e.relativePath.endsWith(".d.ts"):!1}function KD(){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 WD(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 by(){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}}var Ry=1,Sy=Sr({kind:"typescript-hierarchy-targets",invalidation:Te("typescript-hierarchy-targets"),serialize:e=>JSON.stringify(e),deserialize:e=>{try{let t=JSON.parse(e);return t.version!==Ry||typeof t.projectRoot!="string"||!Array.isArray(t.entries)?null:t}catch{return null}}});function VD(e,t){let n=new Map(t.map(i=>[i.symbol,i])),r=new Map;for(let[i,o]of e.entries){let s=new Map;for(let a of o){let c=n.get(a);c&&s.set(c.symbolId,c)}s.size>0&&r.set(i,s)}return r}function YD(e){let t=2166136261;for(let n of e)t^=n.symbolId,t=Math.imul(t,16777619)>>>0;return`${e.length}:${t.toString(16)}`}function vy(e){return{...e,scanMs:Math.round(e.scanMs),packageRefsMs:Math.round(e.packageRefsMs),semanticRefsMs:Math.round(e.semanticRefsMs),hierarchyMs:Math.round(e.hierarchyMs)}}function JD(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function XD(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}|${r.line}|${r.callsiteLine??""}`;t.has(i)||(t.add(i),n.push(r))}return n}function Cy(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}import{join as QD}from"path";var Ii=3,ZD=2,eM="typescript-semantic";function Iy(e){let t=QD(e,eM),n=Js(t);return{...n,requestDir:n.legacyRequestDir}}function KZ(e){let t=JSON.parse(e),n=t.protocolVersion,r=n===ZD;if(!r&&n!==Ii||typeof t.id!="string"||typeof t.generation!="string"||typeof t.deadlineAtMs!="number"||!Number.isFinite(t.deadlineAtMs)||t.profileEnvironment!==void 0&&!Il(t.profileEnvironment)||!t.request||!tM(t.request)||!r&&(t.mailboxVersion!==yn||typeof t.operationKey!="string"||!/^[a-f0-9]{64}$/.test(t.operationKey)||t.id!==Ir(t.operationKey)||typeof t.clientId!="string"||!t.clientId||typeof t.enqueuedAtMs!="number"||!Number.isFinite(t.enqueuedAtMs)||t.deadlineAtMs<t.enqueuedAtMs))throw new Error("TypeScript semantic service received an invalid mailbox request.");if(!r){let o=t,s=qn("typescript-semantic-v3",{generation:o.generation,profileEnvironment:o.profileEnvironment,request:o.request});if(o.operationKey!==s)throw new Error("TypeScript semantic service received a mismatched mailbox operation identity.");return o}let i=qn("typescript-semantic-v2",{id:t.id,generation:t.generation,request:t.request});return{protocolVersion:Ii,mailboxVersion:yn,id:t.id,operationKey:i,clientId:"legacy-v2",enqueuedAtMs:t.deadlineAtMs,deadlineAtMs:t.deadlineAtMs,generation:t.generation,...t.profileEnvironment?{profileEnvironment:t.profileEnvironment}:{},request:t.request}}function tM(e){if(!e||typeof e!="object"||!("kind"in e))return!1;let t=e;switch(t.kind){case"availability":return!0;case"import-usage":return typeof t.file=="string";case"reference-fragments":return Zi(t.files)!==null;case"references":return Ey(t.definitions)&&(t.exact===void 0||typeof t.exact=="boolean");case"callees":return Ey(t.definitions);case"signature":return wy(t.definition);default:return!1}}function Ey(e){return Array.isArray(e)&&e.every(wy)}function wy(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.symbolId=="number"&&typeof t.documentId=="number"&&typeof t.symbol=="string"&&typeof t.relativePath=="string"&&typeof t.leaf=="string"&&typeof t.startLine=="number"&&typeof t.endLine=="number"}var iM=12e4,oM=5;function Dy(e,t,n={}){let r=new Bu(e,n),i=null,o=null,s=process.env.SCIP_QUERY_SKIP_WATCH_SERVICE==="1",a=()=>(i??=xy(e,t),i),c=(d,m,p)=>{if(s)return p();try{return m(r.request(d))}catch{return s=!0,p()}},l=(d,m)=>c({kind:"references",definitions:[...d],...m?.exact?{exact:!0}:{}},p=>Ly(p),()=>a().referencesForDefinitions?.(d,m)??new Map(d.map(p=>[p.symbolId,a().referencesFor(p)]))),u=d=>c({kind:"callees",definitions:[...d]},m=>Ly(m),()=>a().calleesForDefinitions?.(d)??new Map(d.map(m=>[m.symbolId,a().calleesFor(m)])));return{language:"typescript",availability:()=>(o??=c({kind:"availability"},cM,()=>a().availability()),o),importUsage:d=>c({kind:"import-usage",file:d},m=>m,()=>a().importUsage(d)),referencesFor:d=>l([d]).get(d.symbolId)??[],referencesForDefinitions:l,referenceFragmentsForFiles:d=>c({kind:"reference-fragments",files:[...d]},m=>aM(m),()=>a().referenceFragmentsForFiles?.(d)??new Map),calleesFor:d=>u([d]).get(d.symbolId)??[],calleesForDefinitions:u,signatureFor:d=>c({kind:"signature",definition:d},lM,()=>a().signatureFor(d)),dispose:()=>i?.dispose?.()}}var Bu=class{constructor(t,n={}){this.db=t;this.runtime=n.runtime??Ty,this.timeoutMs=n.timeoutMs??uM(),this.mailboxLimits=n.mailboxLimits??{},this.cacheDir=Py(t.config.dbPath),this.projectRoot=xl(t.config.projectRoot)}db;runtime;timeoutMs;cacheDir;projectRoot;mailboxLimits;request(t){let n=Nl(this.cacheDir),r=Iy(this.cacheDir),i=Qs(n.statePath);if(!$u(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript semantic service is not running.");let o=this.db.generation.identity;if(!o)throw new Error("Published TypeScript generation identity is unavailable.");let s=this.runtime.now(),a=s+this.timeoutMs,c=(this.runtime.monotonicNow??Pt)()+this.timeoutMs,l=Sf(),u=qn("typescript-semantic-v3",{generation:o,profileEnvironment:l,request:t}),d=Ir(u),m=Xs(r,{mailboxVersion:yn,operationKey:u,clientId:this.runtime.randomId(),enqueuedAtMs:s,deadlineAtMs:a,protocolVersion:Ii,id:d,generation:o,profileEnvironment:l,request:t},{nowMs:s,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??Pt)()<=c;){if(rM(m.responsePath))return sM(Ct(m.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript semantic mailbox response"}),d,o,u);let p=Qs(n.statePath);if(!$u(p,this.projectRoot,this.runtime))throw new Error("TypeScript semantic service stopped while processing a request.");this.runtime.sleep(oM)}throw new Error(`TypeScript semantic service timed out after ${this.timeoutMs}ms.`)}};function My(e){if(process.env.SCIP_QUERY_SKIP_WATCH_SERVICE==="1")return!1;try{let t=Qs(Nl(Py(e.config.dbPath)).statePath);return $u(t,xl(e.config.projectRoot),Ty)}catch{return!1}}function $u(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null;return e!==null&&e.projectRoot===t&&e.typescriptSemantic?.protocolVersion===Ii&&n.isProcessAlive(e.pid)&&(!e.processIdentity||r!=null&&Ys(e.processIdentity,r))}function sM(e,t,n,r){let i=JSON.parse(e);if(i.protocolVersion!==Ii||i.id!==t||i.operationKey!==r||i.ok===!0&&i.generation!==n)throw new Error("TypeScript semantic service wrote an incompatible response.");if(i.ok===!0)return i.response;throw new Error(typeof i.error=="string"?i.error:"TypeScript semantic service request failed.")}function Ly(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid numeric map.");return new Map(e)}function aM(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid string map.");return new Map(e)}function cM(e){let t=ty(e);if(!t)throw new Error("TypeScript semantic service wrote invalid availability.");return t}function lM(e){if(e!==null&&typeof e!="string")throw new Error("TypeScript semantic service wrote an invalid signature.");return e}function uM(){let e=Number(process.env.SCIP_TYPESCRIPT_SEMANTIC_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:iM}var Ty={now:Date.now,monotonicNow:Pt,randomId:nM,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:mi,readProcessIdentity:pi};var Ay=new Pa;df({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>Ay.clear(e)});function vn(e,t){let n=Pe(t)??"typescript";return Ay.getOrCreate(e,n,()=>n==="rust"?Xh(e.config.projectRoot,{sourceImportUsageResolver:{importUsageFacts:r=>fh(e,r)},calleeSymbolResolver:ph(e),sourceZeroCalleeOracle:r=>dM(e,r),scipOccurrenceCalleeOracle:r=>ey(e,r)}):Dy(e,t))}function Pe(e){return e?se(e)==="rust"?"rust":Gn(e)?"typescript":null:"typescript"}function dM(e,t){let n=K(e,t.relativePath);if(!n||n.language!=="rust")return!1;let r=n.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine&&i.name===t.leaf)??n.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine);return r?!n.callSites.some(i=>i.line>=r.startLine&&i.line<=r.endLine):!1}var mM=/^[A-Za-z_][A-Za-z0-9_]*$/,Fy=/\bDefault::default\b/g,pM=/^\.\.\s*Default::default\b/;function ky(e,t){let n=new Map,r=new Map;for(let i of t){let o=ju(e,i,r);o!==null&&n.set(i.symbolId,o)}return n}function ju(e,t,n=new Map){let r=gM(t.symbol);if(!r)return null;let i=zs(e,[t.symbolId]);if(i.length===0)return null;let o=new RegExp(`(^|[^A-Za-z0-9_])${xe(r)}::default\\b`,"g"),s=new RegExp(`(^|[^A-Za-z0-9_])${xe(r)}\\s*$`),a=fM(e,t.symbolId),c=[];for(let l of i){let u=hM(e,l.relative_path,n);if(u===null)return null;let d=u.split(/\r?\n/),m=0,p=[],f=0;for(let g=l.chunk_start;g<=l.chunk_end&&g<d.length;g+=1){let b=d[g]??"",S=new Set;o.lastIndex=0;let y;for(;y=o.exec(b);)c.push({file:l.relative_path,line:g,column:y.index+y[1].length+r.length+2}),f+=1;for(let x=0;x<b.length;x+=1){let v=pM.exec(b.slice(x));if(v){if(a&&p.includes(m)){let R=x+v[0].lastIndexOf("default");c.push({file:l.relative_path,line:g,column:R}),S.add(R),f+=1}x+=v[0].length-1;continue}let C=b[x];if(C==="{"){let R=s.test(b.slice(0,x));m+=1,R&&p.push(m);continue}if(C==="}")for(m=Math.max(0,m-1);p.length>0&&p[p.length-1]>m;)p.pop()}for(Fy.lastIndex=0;y=Fy.exec(b);){let x=y.index+9;if(!S.has(x))return null}}if(f===0)return null}return Ca(c)}function fM(e,t){return e.get("SELECT 1 AS present FROM mentions WHERE symbol_id = ? AND role = 1 LIMIT 1",t)?.present===1}function gM(e){let t=/impl#\[([^\]]+)\]\[Default\]default\(\)\./.exec(e)?.[1]??null;return!t||!mM.test(t)?null:t}function hM(e,t,n){if(n.has(t))return n.get(t)??null;let r=e.get("SELECT text FROM documents WHERE relative_path = ?",t),i=typeof r?.text=="string"?r.text:yM(e,t);return n.set(t,i),i}function yM(e,t){try{return Ye(e.config.projectRoot,t,{inputKind:"indexed Rust source file"})}catch(n){if(!Je(n))throw n;return null}}var bM="typescript-import-usage-v1",SM="typescript-signatures-v1",Hu=me("semantic-prefetched-callees",{clearGroups:["whole-project","source-file","semantic-provider"]}),Ny=Sr({kind:"semantic-import-usage",invalidation:Te("semantic-import-usage"),serialize:e=>JSON.stringify(e),deserialize:Wy}),_y=Sr({kind:"semantic-signatures",invalidation:Te("semantic-signatures"),serialize:e=>JSON.stringify(e),deserialize:TM}),Oy=mt({kind:"typescript-import-usage",invalidation:Te("typescript-import-usage"),serialize:e=>JSON.stringify(e),deserialize:Wy}),By=mt({kind:"typescript-signatures",invalidation:Te("typescript-signatures"),serialize:e=>JSON.stringify(e),deserialize:AM}),vM=256;function jy(e,t={}){let n=t.coldFragmentLimit??vM,r=ng(e);return r===null||r.missing<=n?{ready:!0}:(t.serviceAvailable??My)(e)?{ready:!0}:{ready:!1,reason:`TypeScript reference fragments are cold for ${r.missing} of ${r.files} files and no watch service is running; run \`scip-query health --full\` once or start the service with \`scip-query watch --daemon\`, then re-run this command.`}}var CM=me("typescript-reference-map",{clearGroups:["whole-project"]});function xM(e){return CM.get(e,()=>{let t=dt(e);if(!t)return null;let n=ve(e).filter(i=>Pe(i.relativePath)==="typescript"),r=Ol(e,n,i=>vn(e,i));return r?{projectFingerprint:t,references:r.references,files:r.files,cacheHits:r.cacheHits,cacheMisses:r.cacheMisses,computedFiles:r.computedFiles}:null})}function st(e){let t=new Map,n=new Set;return{capability:(r,i)=>Vy(e,r,i),importUsage:r=>EM(e,r),references:r=>Uy(e,r),materializeReferences:(r,i)=>Gy(e,r,t,n,i),callerMap:r=>IM(e,r,t,n),calleeMap:r=>PM(e,r),signature:r=>DM(e,r)}}function RM(e,t){if(t.size===0)return;let n=Hu.get(e,()=>new Map);for(let[r,i]of t)n.set(r,[...i])}function Hy(e,t){if(!Hu.has(e))return{hits:[],misses:[...t]};let n=Hu.get(e,()=>new Map),r=[],i=[];for(let o of t)n.has(o.symbolId)?r.push({definition:o,callees:n.get(o.symbolId)??[]}):i.push(o);return{hits:r,misses:i}}function To(e,t){return st(e).importUsage(t)}function EM(e,t){if(Pe(t)==="typescript"){let o="fallback",s=0,a=0,c=0,l=0;return N("typescript.import-usage.materialize",()=>{let u=oo(e,t,bM);if(u?.key){s=1;let m=Oy.read(e,t,u.key);if(m)return o="hit",a=1,m;c=1;let p=Jt(e,t);if(!p)return o="unavailable",[];let f=p.importUsage(t);return Oy.write(e,t,u.key,f),o="computed",f}l=1;let d=Jt(e,t);return d?(o="direct-fallback",d.importUsage(t)):(o="unavailable",[])},()=>({state:o,eligible:s,cacheHits:a,cacheMisses:c,fallbacks:l}))}let n=Ky(e,"semantic-import-usage",t);if(n){let o=Ny.read(e,t,n);if(o)return o}let r=Jt(e,t);if(!r)return[];let i=r.importUsage(t);return n&&Ny.write(e,t,n,i),i}function Ta(e,t){return st(e).references(t)}function Uy(e,t){let n=ju(e,t);if(n)return n;let r=yh(e,t);if(r)return r;let i=Jt(e,t.relativePath);return i?i.referencesFor(t):[]}function Xn(e,t){return st(e).callerMap(t)}function qy(e,t){let n=new Map,r=[];for(let i of t){if(Pe(i.relativePath)==="typescript"){r.push(i);continue}Uu(e,n,i,Uy(e,i))}if(r.length>0){let o=Ol(e,r,s=>vn(e,s))?.references;if(!o){let s=Jt(e,r[0].relativePath);o=s?s.referencesForDefinitions?s.referencesForDefinitions(r,{exact:!0}):new Map(r.map(a=>[a.symbolId,s.referencesFor(a)])):new Map,s&&be()&&_l(e,r,o,a=>vn(e,a))}for(let s of r)Uu(e,n,s,o.get(s.symbolId)??[])}return n}function IM(e,t,n=new Map,r=new Set){let i=new Map,o=Gy(e,t,n,r),s=0;return N("semantic.callers.from-references",()=>{for(let a of t)s+=Uu(e,i,a,n.get(a.symbolId)??[])},()=>({definitions:t.length,materialized:o.definitions,inMemoryHits:o.inMemoryHits,incompleteInMemoryHits:o.incompleteInMemoryHits,resultRows:i.size,callerFiles:s})),i}function Gy(e,t,n,r,i={}){let o=dt(e),s=[],a=[],c=[],l=0,u=0,d=0,m=0,p=0,f=0,g=0,h=0,b=0,S=0,y=0,x=0,v=[],C=new Map,R=t.filter(I=>Pe(I.relativePath)==="typescript"&&!n.has(I.symbolId)&&!r.has(I.symbolId)),E=R.length>0?xM(e):null;if(E){b=R.length,S=E.cacheHits,y=E.cacheMisses,x=E.computedFiles;for(let I of R)n.set(I.symbolId,E.references.get(I.symbolId)??[])}if(N("semantic.references.cache-scan",()=>{for(let[I,w]of ba(t)){let A=[];for(let L of w)n.has(L.symbolId)?u+=1:r.has(L.symbolId)?h+=1:A.push(L);if(A.length===0){g+=1;continue}let D=wM(e,o,I);if(!D){for(let L of A)Pe(L.relativePath)||(l+=1),c.push(L);continue}f+=1;let k=ff(e,I,D);for(let L of A){let F=k.get(L.symbol)??null;if(F!==null){let P=LM(F);if(P){d+=1,n.set(L.symbolId,P);continue}m+=1}a.push({definition:L,cacheFingerprint:D})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:l,cacheHits:d,parseFailures:m,misses:a.length,unkeyed:c.length,inMemoryHits:u,incompleteInMemoryHits:h,fullyInMemoryFiles:g,cacheReadFiles:f})),a.length>0||c.length>0){v=[...c,...a.map(I=>I.definition)],C=N("semantic.references.compute-misses",()=>{let I=qu(e,v,i);return p=I.size,I},()=>({definitions:v.length,misses:a.length,unkeyed:c.length,rows:p}));for(let I of v)C.has(I.symbolId)?(n.set(I.symbolId,C.get(I.symbolId)??[]),r.delete(I.symbolId)):r.add(I.symbolId);for(let{definition:I,cacheFingerprint:w}of a)C.has(I.symbolId)&&Vy(e,"semantic-references",I.relativePath).available&&s.push({relativePath:I.relativePath,symbol:I.symbol,projectFingerprint:w,payload:JSON.stringify(C.get(I.symbolId)??[])})}return s.length>0&&N("semantic.references.cache-write",()=>gf(e,s),()=>({entries:s.length})),C.size>0&&_l(e,v,C,I=>vn(e,I)),{definitions:t.length,inMemoryHits:u,incompleteInMemoryHits:h,cacheHits:d,misses:a.length,unkeyed:c.length,skippedUnsupportedLanguage:l,parseFailures:m,computed:p,incomplete:r.size,cacheWrites:s.length,fragmentDefinitions:b,fragmentCacheHits:S,fragmentCacheMisses:y,fragmentComputedFiles:x}}function wM(e,t,n){if(!t)return null;let r=Pe(n);return r==="typescript"?t:r==="rust"?Gt(JSON.stringify({kind:"semantic-references",language:r,engine:Dr(e.config.projectRoot),projectFingerprint:t})):null}function qu(e,t,n={}){let r=be(),i=new Map,o=0,s=0,a=0,c=0,l=0,u=0,d=0,m=0,p=0;return N("semantic.references.provider-loop",()=>{let f=ky(e,t),g=hh(e,t),h=new Map,b=n.prefetchCallees?new Map:null,S=[];for(let x of t){let v,C=()=>(v??=Jt(e,x.relativePath),v);if(b){let w=C();if(w?.referencesAndCalleesForDefinitions){let A=b.get(w);A?A.push(x):b.set(w,[x]),p+=1}}let R=f.get(x.symbolId);if(R){a+=1,c+=R.length,Mo(i,x.symbolId,R,r,w=>{d+=1,m+=w});continue}let E=g.get(x.symbolId);if(E){l+=1,u+=E.length,Mo(i,x.symbolId,E,r,w=>{d+=1,m+=w});continue}let I=C();if(!I){r&&(s+=1);continue}if(r&&(o+=1),I.referencesForDefinitions){let w=h.get(I);w?w.push(x):h.set(I,[x])}else S.push({provider:I,definition:x})}let y=new Set;if(b)for(let[x,v]of b){if(!x.referencesAndCalleesForDefinitions)continue;let C=h.get(x)??[],R=x.referencesAndCalleesForDefinitions(C,v);y.add(x),RM(e,R.callees);for(let E of C){if(!R.references.has(E.symbolId))continue;let I=R.references.get(E.symbolId)??[];Mo(i,E.symbolId,I,r,w=>{d+=1,m+=w})}}for(let[x,v]of h){if(y.has(x))continue;let C=x.referencesForDefinitions(v);for(let R of v){if(!C.has(R.symbolId))continue;let E=C.get(R.symbolId)??[];Mo(i,R.symbolId,E,r,I=>{d+=1,m+=I})}}for(let{provider:x,definition:v}of S){let C=x.referencesFor(v);Mo(i,v.symbolId,C,r,R=>{d+=1,m+=R})}return i},()=>({definitions:t.length,providerHits:o,providerMisses:s,rustDefaultFastPathRows:a,rustDefaultFastPathReferences:c,rustScipOccurrenceFastPathRows:l,rustScipOccurrenceFastPathReferences:u,prefetchCalleeDefinitions:p,definitionsWithReferences:d,referenceCount:m,rows:i.size}))}function Mo(e,t,n,r,i){e.set(t,n),r&&n.length>0&&i(n.length)}function Uu(e,t,n,r){let i=0;for(let o of r){if(o.file===n.relativePath||e.isIgnored(o.file))continue;let s=t.get(n.symbolId);s||(s=new Set,t.set(n.symbolId,s));let a=s.size;s.add(o.file),s.size!==a&&(i+=1)}return i}function LM(e){try{return JSON.parse(e)}catch{return null}}function Aa(e,t){return st(e).calleeMap(t)}function PM(e,t){let n=be(),r=new Map,i=0,o=0,s=0,a=0;return N("semantic.callees.provider-loop",()=>{let c=new Map,l=[];for(let u of t){let d=Jt(e,u.relativePath);if(!d){n&&(o+=1);continue}n&&(i+=1);let m=u;if(d.calleesForDefinitions){let p=c.get(d);p?p.push(m):c.set(d,[m])}else l.push({provider:d,definition:m})}for(let[u,d]of c){let m=u.calleesForDefinitions(d);for(let p of d){let f=m.get(p.symbolId)??[];$y(r,p.symbolId,f,n,g=>{s+=1,a+=g})}}for(let{provider:u,definition:d}of l){let m=u.calleesFor(d);$y(r,d.symbolId,m,n,p=>{s+=1,a+=p})}return r},()=>({definitions:t.length,providerHits:i,providerMisses:o,definitionsWithCallees:s,calleeCount:a,rows:r.size}))}function $y(e,t,n,r,i){n.length>0&&(e.set(t,n),r&&i(n.length))}function zy(e,t){return st(e).signature(t)}function DM(e,t){if(Pe(t.relativePath)==="typescript"){let s="fallback",a=0,c=0,l=0,u=0;return N("typescript.signature.materialize",()=>{let d=oo(e,t.relativePath,SM);if(d?.key){a=1;let p=By.read(e,t.relativePath,d.key)??{};if(Object.prototype.hasOwnProperty.call(p,t.symbol))return s="hit",c=1,p[t.symbol]??null;l=1;let f=Jt(e,t.relativePath);if(!f)return s="unavailable",null;let g=f.signatureFor(t);return By.write(e,t.relativePath,d.key,{...p,[t.symbol]:g}),s="computed",g}u=1;let m=Jt(e,t.relativePath);return m?(s="direct-fallback",m.signatureFor(t)):(s="unavailable",null)},()=>({state:s,eligible:a,cacheHits:c,cacheMisses:l,fallbacks:u}))}let n=Ky(e,"semantic-signatures",t.relativePath),r=MM(t);if(n){let s=_y.read(e,r,n);if(s)return s.signature}let i=Jt(e,t.relativePath);if(!i)return null;let o=i.signatureFor(t);return n&&_y.write(e,r,n,{signature:o}),o}function Ky(e,t,n){let r=dt(e);if(!r)return null;let i=Pe(n);return i!=="rust"?null:Gt(JSON.stringify({kind:t,language:i,engine:Dr(e.config.projectRoot),projectFingerprint:r}))}function MM(e){return`${e.relativePath}\0${e.symbol}`}function Wy(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:null}catch{return null}}function TM(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 AM(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 Vy(e,t,n){let r=Pe(n);if(!r)return{slot:t,language:"typescript",available:!1,reason:"semantic evidence is only available for TypeScript or Rust files"};try{return{slot:t,language:r,...vn(e,n).availability()}}catch(i){return{slot:t,language:r,available:!1,reason:i instanceof Error?i.message:String(i)}}}function Jt(e,t){if(!Pe(t))return null;let n=vn(e,t);return n.availability().available?n:null}var re={references:Ta,referenceMap:qu,callerMap:(e,t)=>st(e).callerMap(t),calleeMap:Gu};function Gu(e,t){let n=be(),r=new Map,i=Hy(e,t),o=[],s=[],a=0,c=0,l=0,u=0,d=0,m=0,p=0;for(let{definition:y,callees:x}of i.hits)d+=1,x.length>0&&(m+=1,p+=x.length,r.set(y.symbolId,x));let f=FM(e,i.hits);if(f.entries.length>0&&N("semantic.callees.prefetch-cache-write",()=>Ll(e,f.entries),()=>({entries:f.entries.length,sourceMissing:f.sourceMissing,skippedUnsupportedLanguage:f.skippedUnsupportedLanguage})),N("semantic.callees.cache-scan",()=>{for(let[y,x]of ba(i.misses)){if(!Pe(y)){n&&(a+=x.length);continue}let v=W(e,y);if(!v){n&&(c+=x.length),s.push(...x);continue}let C=Et(e,y,v),R=Yy(e,y);if(!R){s.push(...x);continue}let E=pf(e,y,C,R);for(let I of x){let w=E.get(I.symbol)??null;if(w!==null){let A=NM(w);if(A){n&&(l+=1),A.length>0&&r.set(I.symbolId,A);continue}n&&(u+=1)}o.push({def:I,contentHash:C,depsDigest:R})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:a,sourceMissing:c,cacheHits:l,parseFailures:u,misses:o.length,unkeyed:s.length,inMemoryHits:d,inMemoryRows:m,inMemoryCalleeCount:p,resultRows:r.size,missSample:o.slice(0,8).map(y=>`${y.def.relativePath}#${y.def.symbol}`),unkeyedSample:s.slice(0,4).map(y=>`${y.relativePath}#${y.symbol}`)})),o.length===0&&s.length===0)return r;let g=[...s,...o.map(y=>y.def)],h=0,b=N("semantic.callees.compute-misses",()=>{let y=Aa(e,g);return h=y.size,y},()=>({definitions:g.length,misses:o.length,unkeyed:s.length,rows:h}));for(let[y,x]of b)r.set(y,x);let S=o.filter(y=>st(e).capability("semantic-callees",y.def.relativePath).available).map(y=>({relativePath:y.def.relativePath,symbol:y.def.symbol,contentHash:y.contentHash,depsDigest:y.depsDigest,payload:JSON.stringify(b.get(y.def.symbolId)??[])}));return S.length>0?N("semantic.callees.cache-write",()=>Ll(e,S),()=>({entries:S.length})):N("semantic.callees.cache-write-skip",()=>{},()=>({reason:"provider-unavailable",misses:o.length})),r}function FM(e,t){let n=[],r=new Map,i=0,o=0;for(let{definition:s,callees:a}of t){if(!Pe(s.relativePath)){o+=1;continue}if(!r.has(s.relativePath)){let l=W(e,s.relativePath),u=l?Yy(e,s.relativePath):null;r.set(s.relativePath,l&&u?{contentHash:Et(e,s.relativePath,l),depsDigest:u}:null)}let c=r.get(s.relativePath);if(!c){i+=1;continue}n.push({relativePath:s.relativePath,symbol:s.symbol,contentHash:c.contentHash,depsDigest:c.depsDigest,payload:JSON.stringify(a)})}return{entries:n,sourceMissing:i,skippedUnsupportedLanguage:o}}var kM="typescript-callees-v2-callsite-line";function Yy(e,t){let n=Pe(t);if(n==="typescript")return oo(e,t,kM)?.key??null;let r=OM(e,t);return n==="rust"?Gt(JSON.stringify({kind:"semantic-callees",language:n,engine:Dr(e.config.projectRoot),positionMapping:"nearby-leaf-v2-callsite-line",depsDigest:r})):r}function NM(e){try{return JSON.parse(e)}catch{return null}}var _M=Nn("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function OM(e,t){return _M.get(e,t,()=>{let r=[...Ae(e).get(t)??[]].sort().map(i=>`${i}:${Et(e,i,W(e,i))}`);return Gt(r.join("|"))})}function n9(e,t,n={}){let r=ne(e,t);if(!r)return[];let o=!Se(r.symbol)&&!e.isIgnored(r.relativePath)?[{relativePath:r.relativePath,line:r.startLine}]:[],s=Un(e,r,{semantic:n.semantic,semanticEvidence:re}).map(u=>({relativePath:u.file,line:u.line})),a=BM(e,r),c=new Set,l=[];for(let u of[...o,...s,...a]){let d=`${u.relativePath}:${u.line}`;c.has(d)||(c.add(d),l.push(u))}return l}function BM(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=$M(t.symbol);if(n.length===0)return[];let r=[];for(let i of Q(e,{extensions:[".rb"],includeIgnored:!1})){let o=W(e,i);if(!o)continue;let s=o.split(`
52
- `);for(let a=0;a<s.length;a++){let c=s[a]??"";n.some(l=>new RegExp(`@${l}\\b|\\b${l}:`).test(c))&&r.push({relativePath:i,line:a})}}return r}function $M(e){let n=(e.split(":").pop()??e).replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),r=n.split("_").filter(Boolean),i=new Set;return n&&i.add(n),r.length>=1&&i.add(r[r.length-1]),r.length>=2&&i.add(r.slice(-2).join("_")),[...i]}import{existsSync as rd,statSync as bA}from"fs";import{join as SA}from"path";import{existsSync as Li}from"fs";import{randomUUID as pb}from"crypto";import{isAbsolute as CT,join as xn,relative as xT,resolve as RT}from"path";var Qn=1,Zn=2,jM="./node_modules/scip-query/docs/schemas/project-config.schema.json";function zu(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(a){return{kind:"malformed",reason:`invalid JSON: ${a instanceof Error?a.message:String(a)}`}}if(!Z(t))return{kind:"malformed",reason:"project config must be a JSON object"};let n=t.schemaVersion;if(n!==void 0&&!Number.isInteger(n))return{kind:"malformed",reason:"schemaVersion must be an integer"};let r=n===void 0?Qn:n;if(r!==Qn&&r!==Zn)return{kind:"unsupported",schemaVersion:r,direction:r<Qn?"older":"future"};let i=t.$schema;if(i!==void 0&&(typeof i!="string"||i.trim()===""))return{kind:"malformed",reason:"$schema must be a non-empty string when present"};let o=Fa(t),s=r!==Zn||typeof t.$schema!="string";return r===Qn?{kind:"legacy",sourceVersion:Qn,config:o,needsMigration:s}:{kind:"supported",sourceVersion:Zn,config:o,needsMigration:s}}function Fa(e){let t=e,{$schema:n,schemaVersion:r,...i}=t;return{$schema:typeof n=="string"&&n.trim()!==""?n:jM,schemaVersion:Zn,...i}}function wi(e){return`${JSON.stringify(Fa(e),null,2)}
53
- `}import{createHash as HM}from"crypto";var Qt=1,tr=2,eb=1,Yu=1,Vu="sha256",UM=1;function Fr(e,t,n){if(!_t(e)||!ks(t))throw new Error("Observation identity requires a bounded projection name and positive projection version.");return{schemaVersion:eb,canonicalizationVersion:Yu,hashAlgorithm:Vu,projection:{name:e,version:t},digest:HM(Vu).update(qM(e,t,n)).digest("hex")}}function qM(e,t,n){return`{"canonicalizationVersion":${Yu},"projection":${JSON.stringify(e)},"projectionVersion":${t},"value":${JSON.stringify(n)}}`}function GM(e){if(!Z(e))return{kind:"malformed",reason:"observation receipt must be an object"};let t=e.schemaVersion;if(!Number.isInteger(t))return{kind:"malformed",reason:"observation receipt schemaVersion must be an integer"};if(t===Qt)return XM(e)?{kind:"legacy",schemaVersion:Qt,receipt:e}:{kind:"malformed",reason:"observation receipt v1 fields are malformed or contradictory"};if(t===tr)return QM(e)?{kind:"supported",schemaVersion:tr,receipt:e}:{kind:"malformed",reason:"observation receipt v2 facts are malformed or contradictory"};let n=t;return{kind:"unsupported",schemaVersion:n,direction:n<Qt?"older":"future"}}function ka(e){let t=GM(e);return t.kind==="legacy"||t.kind==="supported"}function zM(e,t){return{collaborationDomain:Ar(Xt(e,n=>n.facts.collaborationDomain),Xt(t,n=>n.facts.collaborationDomain)),repositoryLineage:Ar(Xt(e,n=>n.facts.repositoryLineage),Xt(t,n=>n.facts.repositoryLineage)),workspaceInstance:Ar(Xt(e,n=>n.facts.workspaceInstance),Xt(t,n=>n.facts.workspaceInstance)),wholeContent:Ar(Xt(e,n=>n.facts.wholeContent),Xt(t,n=>n.facts.wholeContent)),relevantInputs:KM(e,t),indexInput:Ar(Xt(e,n=>n.facts.index?.inputs),Xt(t,n=>n.facts.index?.inputs)),indexGeneration:WM(e,t),observationStability:YM(e,t)}}function c9(e,t,n=zM(e,t)){let r=[["collaborationDomain",n.collaborationDomain],["wholeContent",n.wholeContent],["observationStability",n.observationStability]],i=[];for(let[s,a]of r)a.state!=="established"&&i.push(`${s}:${a.state}`);for(let[s,a]of[["left",e],["right",t]]){let c=JM(a);c!=="not-applicable"&&c!=="established"&&i.push(`${s}IndexAlignment:${c}`)}let o=r.some(([,s])=>s.state==="disproven")||i.some(s=>s.endsWith(":disproven"));return{policyVersion:UM,authority:i.length===0?"completion":o?"none":"advisory",requiredRelationships:["collaborationDomain","wholeContent","observationStability"],reasons:i}}function KM(e,t){let n=Jy(e),r=Jy(t);return[...new Set([...n.keys(),...r.keys()])].sort().map(o=>{let s=n.get(o),a=r.get(o),c=s?.subject??a?.subject??o,l=s?.identity.projection.name??a?.identity.projection.name??o;return{subject:c,projection:l,judgment:Ar(s?.identity,a?.identity)}})}function Jy(e){return e.schemaVersion!==tr?new Map:new Map((e.facts.relevantInputs??[]).map(t=>[`${t.subject}\0${t.identity.projection.name}`,t]))}function WM(e,t){return e.schemaVersion===Qt&&t.schemaVersion===Qt?VM(e.index?.generationIdentity,t.index?.generationIdentity):e.schemaVersion===Qt||t.schemaVersion===Qt?Cn("unknown",["legacy-fact-not-comparable"],Qy(e),Qy(t)):Ar(e.facts.index?.generation,t.facts.index?.generation)}function VM(e,t){let n=e?[{kind:"legacy-index-generation",value:e}]:[],r=t?[{kind:"legacy-index-generation",value:t}]:[];return e===void 0||t===void 0?tb(n,r):Cn(e===t?"established":"disproven",[e===t?"identities-equal":"identities-different"],n,r)}function Ar(e,t){let n=e?[{kind:"identity",identity:e}]:[],r=t?[{kind:"identity",identity:t}]:[];return!e||!t?tb(n,r):Ju(e,t)?Cn(e.digest===t.digest?"established":"disproven",[e.digest===t.digest?"identities-equal":"identities-different"],n,r):Cn("unknown",["identity-projections-not-comparable"],n,r)}function YM(e,t){if(e.schemaVersion===Qt||t.schemaVersion===Qt)return Cn("unknown",["legacy-fact-not-comparable"],[],[]);let n=Zy(e),r=Zy(t),i=Xy(e),o=Xy(t);return i==="invalidated"||o==="invalidated"?Cn("disproven",[...i==="invalidated"?["left-observation-invalidated"]:[],...o==="invalidated"?["right-observation-invalidated"]:[]],n,r):i!=="fixed"||o!=="fixed"?Cn("unknown",[...i==="no-repository-source"?["left-observation-has-no-repository-source"]:i!=="fixed"?["left-observation-not-fixed"]:[],...o==="no-repository-source"?["right-observation-has-no-repository-source"]:o!=="fixed"?["right-observation-not-fixed"]:[]],n,r):Cn("established",["all-observed-sources-fixed"],n,r)}function Xy(e){let t=e.observedSources.filter(r=>r.kind!=="process");if(t.length===0)return"no-repository-source";let n=new Map(e.stabilityProofs.map(r=>[r.source,r.kind]));return t.some(r=>n.get(r.kind)==="invalidated")?"invalidated":t.every(r=>{let i=n.get(r.kind);return i==="immutable"||i==="fixed-snapshot"})?"fixed":"unknown"}function JM(e){if(e.schemaVersion!==tr)return e.index?"unknown":"not-applicable";if(!e.observedSources.some(r=>r.kind==="index-generation"))return"not-applicable";let t=e.facts.index?.inputs;if(!t)return"unknown";let n=(e.facts.relevantInputs??[]).find(r=>Ju(r.identity,t))?.identity;return n?n.digest===t.digest?"established":"disproven":"unknown"}function Xt(e,t){return e.schemaVersion===tr?t(e):void 0}function Qy(e){return e.schemaVersion===Qt&&e.index?[{kind:"legacy-index-generation",value:e.index.generationIdentity}]:e.schemaVersion===tr&&e.facts.index?[{kind:"identity",identity:e.facts.index.generation}]:[]}function Zy(e){return e.stabilityProofs.map(t=>({kind:"stability",proof:t}))}function tb(e,t){let n=e.length===0&&t.length===0?"both-facts-missing":e.length===0?"left-fact-missing":"right-fact-missing";return Cn("unknown",[n],e,t)}function Cn(e,t,n,r){return{state:e,reasons:t,facts:{left:n,right:r}}}function Ju(e,t){return e.schemaVersion===t.schemaVersion&&e.canonicalizationVersion===t.canonicalizationVersion&&e.hashAlgorithm===t.hashAlgorithm&&e.projection.name===t.projection.name&&e.projection.version===t.projection.version}function XM(e){if(!Z(e))return!1;let t=e.index,n=e.worktree;return rb(e.observedAt)&&_t(e.projectIdentity)&&oT(e.authorityKind)&&(t===void 0||Z(t)&&_t(t.generationIdentity)&&(t.source==="immutable"||t.source==="legacy")&&(t.alignment==="not-certified"||t.alignment==="leased"))&&(n===void 0||Z(n)&&_t(n.identity)&&typeof n.clean=="boolean"&&(n.headCommit===void 0||_t(n.headCommit))&&(n.treeOid===void 0||_t(n.treeOid)))&&iT(e.authorityKind,t,n)}function QM(e){if(!Z(e))return!1;let t=e.facts,n=e.observedSources,r=e.stabilityProofs;if(!rb(e.observedAt)||!Z(t)||!Array.isArray(n)||n.length===0||!n.every(eT)||!Wu(n,c=>c.kind)||!Array.isArray(r)||!r.every(tT)||!Wu(r,c=>c.source)||r.some(c=>!n.some(l=>l.kind===c.source))||!r.every(c=>rT(c,t))||["collaborationDomain","repositoryLineage","workspaceInstance","wholeContent"].some(c=>t[c]!==void 0&&!er(t[c])))return!1;let o=t.relevantInputs;if(o!==void 0&&(!Array.isArray(o)||!o.every(ZM)||!Wu(o,c=>`${c.subject}\0${c.identity.projection.name}`)))return!1;let s=t.index;if(s!==void 0&&(!Z(s)||!er(s.generation)||s.inputs!==void 0&&!er(s.inputs)||s.source!=="immutable"&&s.source!=="legacy"))return!1;let a=e.diagnostics;return(a===void 0||Z(a)&&(a.clean===void 0||typeof a.clean=="boolean")&&(a.headCommit===void 0||_t(a.headCommit))&&(a.treeOid===void 0||_t(a.treeOid)))&&nT(t,n)}function er(e){return!Z(e)||!Z(e.projection)?!1:e.schemaVersion===eb&&e.canonicalizationVersion===Yu&&e.hashAlgorithm===Vu&&_t(e.projection.name)&&ks(e.projection.version)&&ni(e.digest)}function ZM(e){return Z(e)&&_t(e.subject)&&er(e.identity)}function eT(e){return Z(e)&&nb(e.kind)&&(e.identity===void 0||er(e.identity))}function tT(e){return Z(e)&&nb(e.source)&&(e.kind==="immutable"||e.kind==="fixed-snapshot"||e.kind==="bracketed"||e.kind==="not-established"||e.kind==="invalidated")}function nT(e,t){let n=e.index,r=t.find(c=>c.kind==="index-generation");if(r){if(!Z(n)||!er(n.generation)||r.identity&&!Ku(r.identity,n.generation))return!1}else if(n!==void 0)return!1;let i=e.workspaceInstance,o=t.find(c=>c.kind==="live-workspace");if(o?.identity&&(!er(i)||!Ku(o.identity,i)))return!1;let s=e.wholeContent,a=t.find(c=>c.kind==="repository-snapshot");return!(a?.identity&&(!er(s)||!Ku(a.identity,s)))}function rT(e,t){return e.kind==="not-established"||e.kind==="invalidated"?!0:e.source==="index-generation"?e.kind==="immutable"&&Z(t.index)&&t.index.source==="immutable":e.source==="repository-snapshot"?e.kind==="fixed-snapshot":e.source==="live-workspace"?e.kind==="bracketed":!1}function Ku(e,t){return Ju(e,t)&&e.digest===t.digest}function iT(e,t,n){return e==="index-worktree"?t!==void 0&&n!==void 0:e==="index-only"?t!==void 0&&n===void 0:e==="worktree-only"?t===void 0&&n!==void 0:e==="process-local"&&t===void 0&&n===void 0}function oT(e){return e==="index-worktree"||e==="index-only"||e==="worktree-only"||e==="process-local"}function nb(e){return e==="index-generation"||e==="repository-snapshot"||e==="live-workspace"||e==="process"}function rb(e){return typeof e=="string"&&!Number.isNaN(Date.parse(e))}function Wu(e,t){return new Set(e.map(t)).size===e.length}function Na(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.kind==="automated-adjudication"&&t.policyVersion===1&&(t.decidedBy==="agent"||t.decidedBy==="human")&&uf.includes(t.reasonCode)&&Array.isArray(t.evidence)&&t.evidence.length>0&&t.evidence.every(sT)&&(t.observation===void 0||ka(t.observation))&&!!t.invalidateOn&&typeof t.invalidateOn=="object"&&typeof t.invalidateOn.targetContentChange=="boolean"&&typeof t.invalidateOn.detectorMajorChange=="boolean"}function sT(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return(t.kind==="source"||t.kind==="config"||t.kind==="test"||t.kind==="graph")&&typeof t.referent=="string"&&t.referent.trim()!==""&&typeof t.claim=="string"&&t.claim.trim()!==""&&(t.contentHash===void 0||/^[a-f0-9]{64}$/u.test(t.contentHash))&&(t.generation===void 0||typeof t.generation=="string"&&t.generation.length>0)}var _a=class extends Error{constructor(n,r,i){super(`${n} is ${r} characters; the safety limit is ${i} characters`);this.inputKind=n;this.observedCharacters=r;this.limitCharacters=i;this.name="RegExpPatternBudgetError"}inputKind;observedCharacters;limitCharacters;code="SCIP_QUERY_REGEXP_PATTERN_BUDGET"};function kr(e,t,n,r=4096){if(!Number.isSafeInteger(r)||r<0)throw new RangeError(`maxCharacters must be a non-negative safe integer; received ${r}`);if(e.length>r)throw new _a(t,e.length,r);return new RegExp(e,n)}import{createHash as ib}from"crypto";import{closeSync as aT,fstatSync as ob,lstatSync as cT,openSync as lT,readlinkSync as uT,realpathSync as dT,rmSync as mT}from"fs";import{dirname as cb,resolve as pT}from"path";var fT=2e3,gT=10,hT=3,Ba=class extends Error{constructor(n,r,i){super(`Concurrent edit detected for ${n}; expected revision ${ab(r)}, but found ${ab(i)}. The latest file was left untouched.`);this.path=n;this.original=r;this.latest=i;this.name="FileRevisionConflictError"}path;original;latest},Ao=class extends Error{constructor(n,r){super(`Concurrent edit detected for ${n}: ${r} changed since it was read. The latest file was left untouched; reload it and retry.`);this.path=n;this.field=r;this.name="FileContentConflictError"}path;field};function Fo(e,t,n={}){let r=yT(e),i=bT(r,n.lockTimeoutMs??fT,n.monotonicNow??Pt);try{let o=Math.max(0,Math.floor(n.maxRetries??hT));for(let s=0;;s+=1){let a=Oa(r),c=t(a,s);if(c.kind==="unchanged")return{changed:!1,attempts:s+1,previous:a,current:a};n.onBeforeCommit?.({attempt:s,snapshot:a,mutation:c});let l=Oa(r);if(!vT(a.revision,l.revision)){if(s<o)continue;throw new Ba(r,a.revision,l.revision)}try{ST(r,c,a.revision)}catch(u){if(u.code==="EEXIST"){let d=Oa(r);if(s<o)continue;throw new Ba(r,a.revision,d.revision)}throw u}return{changed:!0,attempts:s+1,previous:a,current:Oa(r)}}}finally{i.release()}}function yT(e){let t;try{if(!cT(e).isSymbolicLink())return e;t=uT(e)}catch{return e}try{return dT(e)}catch{return pT(cb(e),t)}}function Oa(e){for(let t=0;t<4;t+=1){let n;try{n=lT(e,"r");let r=sb(ob(n)),i=Jp(n,{maxBytes:pn,inputKind:"revisioned text file"}),o=sb(ob(n));if(!lb(r,o))continue;return{path:e,text:i,revision:{exists:!0,hash:ib("sha256").update(i).digest("hex"),identity:o}}}catch(r){if(r.code==="ENOENT")return{path:e,text:"",revision:{exists:!1,hash:ib("sha256").update("").digest("hex")}};throw r}finally{n!==void 0&&aT(n)}}throw new Error(`Could not read a stable revision of ${e}; the file is changing continuously.`)}function bT(e,t,n){let r=`${e}.scip-query-write.lock`,i=n()+Math.max(0,t);for(;;){let o=fi(r,{kind:"revisioned-file-mutation",detail:{target:e}});if(o.kind==="acquired")return o.lock;if(n()>=i)throw new Error(`Timed out after ${t}ms waiting to update ${e}; the file was left untouched.`);Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,gT)}}function ST(e,t,n){if(t.kind==="delete"){if(!n.exists)return;mT(e),nf(cb(e));return}let r=t.mode??n.identity?.mode;n.exists?Jf(e,t.text,{durability:"durable",mode:r}):Xf(e,t.text,{durability:"durable",mode:r})}function vT(e,t){return e.exists===t.exists&&e.hash===t.hash&&(e.identity===void 0?t.identity===void 0:t.identity!==void 0&&lb(e.identity,t.identity))}function sb(e){return{dev:e.dev,ino:e.ino,size:e.size,mtimeMs:e.mtimeMs,mode:e.mode&511}}function lb(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.size===t.size&&e.mtimeMs===t.mtimeMs&&e.mode===t.mode}function ab(e){return e.exists?e.hash.slice(0,12):"<absent>"}var nr=".scipquery.json",fb=2e3,$a=5e3,Xu=$a,gb=15*6e4,Qu={enabled:!0,windowMs:15*6e4,maxRebuilds:2,maxEstimatedWriteBytes:1024*1024*1024},ET={enabled:!1,autoStart:!1,allowExpensiveRebuild:!1,debounceMs:fb,cooldownMs:Xu,gitPollMs:2e3,idleTimeoutMs:gb,autoRefresh:!0,ignore:[],resourceBudget:Qu};var IT=new Set(["$schema","schemaVersion","collaborationDomainId","languages","indexerConcurrency","watch","indexer","dbPath","entryRoots","semantic","suppressions","declaredCouplings","locality","architecture","coverageContracts","docs"]),wT=new Set(["enabled","autoStart","allowExpensiveRebuild","debounceMs","cooldownMs","gitPollMs","idleTimeoutMs","autoRefresh","ignore","resourceBudget"]),LT=new Set(["enabled","windowMs","maxRebuilds","maxEstimatedWriteBytes"]),PT=new Set(["pathPrefixes","files","symbolPatterns","qualifiedVars"]),DT=new Set(["typescript","rust"]),MT=new Set(["tsconfigs"]),TT=new Set(["rustAnalyzerPath"]),ub=new Set(wl),AT=new Set(["pnpmWorkspaces","projectMode","projects","configPath","maxWarmSessions","workerIdleMs","workerSoftMemoryMb","workerHeapMb","maxHeapMb"]),FT=new Set(["architecturalBoundarySegments"]),kT=new Set(["boundaries","allowedDependencies","requireCompletePolicy","requireCompleteCoverage","requireAcyclic","requireResolvedBoundaries","requireMinimalPolicy","maxBoundaryFanOut","maxBoundaryFiles","testPaths"]),NT=new Set(["name","paths","subUnits","maxFiles"]),_T=new Set(["snapshotPaths"]),OT=new Set(["name","files","reason"]),BT=new Set(["id","check","file","reason","expiresAt","createdAt","decision"]),$T=new Set(["kind","reasonCode","decidedBy","policyVersion","observation","evidence","invalidateOn"]),jT=new Set(["kind","referent","claim","contentHash","generation"]),HT=new Set(["targetContentChange","detectorMajorChange"]),UT=new Set(["name","file","keys","mustEqual","allowExtra"]),qT=new Set(["type","identifier","marker"]),GT=new Set(["type","path","pattern"]),zT=new Set(["object-literal-keys","string-array","markdown-list"]),KT=new Set(["top-level-dirs","file-glob","registered-commands","builtin-skills"]);function hb(e){let t=xn(e,nr);if(!Li(t))return{};let n;try{n=Ct(t,{maxBytes:Ts,inputKind:"scip-query project config"})}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`unable to read ${nr} at ${t}: ${i}`,{cause:r})}return bb(zu(n),t,"read").config}function N9(e,t={}){let n=[];return rA(e,n),WT(e,n),VT(e,n),YT(e,n,t),JT(e,n),ZT(e,n),XT(e,n,t),QT(e,n,t),nA(e,n,t),tA(e,n),n}function db(e,t,n,r,i){if(!r)return;let o=RT(r,n),s=xT(r,o);if(s.startsWith("..")||CT(s)){e.push({level:"error",path:t,message:i.outside});return}Li(o)||e.push({level:"warning",path:t,message:i.missing})}function WT(e,t){let n=e;n.schemaVersion!==void 0&&n.schemaVersion!==Zn&&t.push({level:"error",path:"schemaVersion",message:`Must be ${Zn}; unversioned and v${Qn} files are migrated while loading.`}),n.$schema!==void 0&&(typeof n.$schema!="string"||n.$schema.trim()==="")&&t.push({level:"error",path:"$schema",message:"Must be a non-empty string."}),e.collaborationDomainId!==void 0&&!/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(e.collaborationDomainId)&&t.push({level:"error",path:"collaborationDomainId",message:"Must be a lowercase or uppercase UUID v4 generated for this collaboration domain."});let r=new Set(wl);for(let[i,o]of(e.languages??[]).entries())r.has(o)||t.push({level:"error",path:`languages[${i}]`,message:`Unsupported language: ${o}`});for(let[i,o]of(e.entryRoots?.symbolPatterns??[]).entries())try{kr(o,`entryRoots.symbolPatterns[${i}]`)}catch(s){t.push({level:"error",path:`entryRoots.symbolPatterns[${i}]`,message:s instanceof Error?s.message:String(s)})}e.indexerConcurrency!==void 0&&(!Number.isInteger(e.indexerConcurrency)||e.indexerConcurrency<=0)&&t.push({level:"error",path:"indexerConcurrency",message:"Must be a positive integer."})}function VT(e,t){e.watch?.debounceMs!==void 0&&e.watch.debounceMs<=0&&t.push({level:"error",path:"watch.debounceMs",message:"Must be greater than 0."}),e.watch?.cooldownMs!==void 0&&(!Number.isInteger(e.watch.cooldownMs)||e.watch.cooldownMs<0)?t.push({level:"error",path:"watch.cooldownMs",message:"Must be a non-negative integer."}):e.watch?.cooldownMs!==void 0&&e.watch.cooldownMs<$a&&t.push({level:"warning",path:"watch.cooldownMs",message:`Values below ${$a}ms are raised to the safety floor at runtime.`}),e.watch?.gitPollMs!==void 0&&e.watch.gitPollMs<=0&&t.push({level:"error",path:"watch.gitPollMs",message:"Must be greater than 0."}),e.watch?.idleTimeoutMs!==void 0&&(!Number.isInteger(e.watch.idleTimeoutMs)||e.watch.idleTimeoutMs<0)&&t.push({level:"error",path:"watch.idleTimeoutMs",message:"Must be a non-negative integer; 0 disables idle shutdown."}),e.watch?.autoStart!==void 0&&typeof e.watch.autoStart!="boolean"&&t.push({level:"error",path:"watch.autoStart",message:"Must be a boolean."}),e.watch?.allowExpensiveRebuild!==void 0&&typeof e.watch.allowExpensiveRebuild!="boolean"&&t.push({level:"error",path:"watch.allowExpensiveRebuild",message:"Must be a boolean."}),e.watch?.autoRefresh!==void 0&&typeof e.watch.autoRefresh!="boolean"&&t.push({level:"error",path:"watch.autoRefresh",message:"Must be a boolean."});let n=e.watch?.resourceBudget;n?.enabled!==void 0&&typeof n.enabled!="boolean"&&t.push({level:"error",path:"watch.resourceBudget.enabled",message:"Must be a boolean."});for(let[r,i]of[["windowMs",n?.windowMs],["maxRebuilds",n?.maxRebuilds],["maxEstimatedWriteBytes",n?.maxEstimatedWriteBytes]])i!==void 0&&(!Number.isSafeInteger(i)||i<=0)&&t.push({level:"error",path:`watch.resourceBudget.${r}`,message:"Must be a positive safe integer."})}function YT(e,t,n){let r=e.indexer?.typescript;if(r?.projectMode!==void 0&&r.projectMode!=="single"&&r.projectMode!=="workspace"&&t.push({level:"error",path:"indexer.typescript.projectMode",message:'Must be "single" or "workspace".'}),r?.projects!==void 0)if(!Array.isArray(r.projects))t.push({level:"error",path:"indexer.typescript.projects",message:"Must be an array."});else for(let[s,a]of r.projects.entries()){let c=`indexer.typescript.projects[${s}]`;typeof a!="string"||a.trim()===""?t.push({level:"error",path:c,message:"Project path must be a non-empty string."}):db(t,c,a,n.projectRoot,{outside:"Project path must stay inside the project root.",missing:`TypeScript project path does not exist: ${a}`})}r?.projectMode==="workspace"&&r.pnpmWorkspaces===!0&&t.push({level:"warning",path:"indexer.typescript.pnpmWorkspaces",message:'Ignored when projectMode is "workspace"; explicit TypeScript projects are indexed directly.'});for(let[s,a]of[["maxWarmSessions",r?.maxWarmSessions],["workerSoftMemoryMb",r?.workerSoftMemoryMb],["workerHeapMb",r?.workerHeapMb],["maxHeapMb",r?.maxHeapMb]])a!==void 0&&(!Number.isInteger(a)||a<=0)&&t.push({level:"error",path:`indexer.typescript.${s}`,message:"Must be a positive integer."});r?.workerIdleMs!==void 0&&(!Number.isInteger(r.workerIdleMs)||r.workerIdleMs<0)&&t.push({level:"error",path:"indexer.typescript.workerIdleMs",message:"Must be a non-negative integer."});let i=e.semantic?.rust;i?.rustAnalyzerPath!==void 0&&(typeof i.rustAnalyzerPath!="string"||i.rustAnalyzerPath.trim()==="")&&t.push({level:"error",path:"semantic.rust.rustAnalyzerPath",message:"Rust analyzer path must be a non-empty string."});let o=e.indexer?.clojure;if(o?.configPath!==void 0){let s="indexer.clojure.configPath";typeof o.configPath!="string"||o.configPath.trim()===""?t.push({level:"error",path:s,message:"Config path must be a non-empty string."}):db(t,s,o.configPath,n.projectRoot,{outside:"Config path must stay inside the project root.",missing:`Clojure indexer config path does not exist: ${o.configPath}`})}}function JT(e,t){if(e.locality===void 0)return;if(!Z(e.locality)){t.push({level:"error",path:"locality",message:"Must be an object."});return}let n=e.locality.architecturalBoundarySegments;if(n!==void 0){if(!Array.isArray(n)){t.push({level:"error",path:"locality.architecturalBoundarySegments",message:"Must be an array."});return}for(let[r,i]of n.entries()){let o=`locality.architecturalBoundarySegments[${r}]`;typeof i!="string"||i.trim()===""?t.push({level:"error",path:o,message:"Boundary segment must be a non-empty string."}):(i.includes("/")||i.includes("\\"))&&t.push({level:"error",path:o,message:"Boundary segment must be a single folder name, not a path."})}}}function XT(e,t,n){if(e.declaredCouplings!==void 0&&!Array.isArray(e.declaredCouplings)){t.push({level:"error",path:"declaredCouplings",message:"Must be an array."});return}for(let[r,i]of(e.declaredCouplings??[]).entries()){let o=`declaredCouplings[${r}]`;if((!i.name||i.name.trim()==="")&&t.push({level:"error",path:`${o}.name`,message:"Declared coupling name is required."}),!Array.isArray(i.files)||i.files.length<2)t.push({level:"error",path:`${o}.files`,message:"Declared coupling needs at least two files."});else for(let[s,a]of i.files.entries())!a||a.trim()===""?t.push({level:"error",path:`${o}.files[${s}]`,message:"Declared coupling file path is required."}):n.projectRoot&&!Li(xn(n.projectRoot,a))&&t.push({level:"warning",path:`${o}.files[${s}]`,message:`Declared coupling file does not exist: ${a}`});i.reason!==void 0&&i.reason.trim()===""&&t.push({level:"error",path:`${o}.reason`,message:"Declared coupling reason cannot be blank."})}}function QT(e,t,n){let r=n.now??new Date;e.suppressions!==void 0&&!Array.isArray(e.suppressions)&&t.push({level:"error",path:"suppressions",message:"Must be an array."});for(let[i,o]of(Array.isArray(e.suppressions)?e.suppressions:[]).entries()){let s=`suppressions[${i}]`;if(!Z(o)){t.push({level:"error",path:s,message:"Suppression must be an object."});continue}if((!o.reason||o.reason.trim()==="")&&t.push({level:"error",path:`${s}.reason`,message:"Suppression reason is required."}),o.id!==void 0&&o.id.trim()===""&&t.push({level:"error",path:`${s}.id`,message:"Suppression id cannot be blank."}),o.check!==void 0&&o.check.trim()===""&&t.push({level:"error",path:`${s}.check`,message:"Suppression check cannot be blank."}),!o.id&&(!o.check||!o.file)?t.push({level:"error",path:s,message:"Suppression must include id or both check and file."}):!o.id&&o.check&&o.file&&t.push({level:"warning",path:s,message:"Check+file suppressions waive every matching finding in that file; prefer a stable id when available."}),o.file!==void 0&&(o.file.trim()===""?t.push({level:"error",path:`${s}.file`,message:"Suppression file path cannot be blank."}):n.projectRoot&&!Li(xn(n.projectRoot,o.file))&&t.push({level:"warning",path:`${s}.file`,message:`Suppression file does not exist: ${o.file}`})),o.expiresAt){let a=Date.parse(o.expiresAt);Number.isNaN(a)?t.push({level:"error",path:`${s}.expiresAt`,message:"Must be an ISO date string."}):a<=r.getTime()&&t.push({level:"warning",path:`${s}.expiresAt`,message:"Suppression has expired."})}if(o.decision!==void 0&&!Na(o.decision))t.push({level:"error",path:`${s}.decision`,message:"Must be a valid automated-adjudication decision with reason code, evidence, and invalidation rules."});else if(o.decision&&n.projectRoot)for(let[a,c]of o.decision.evidence.entries())c.kind!=="graph"&&!Li(xn(n.projectRoot,c.referent))&&t.push({level:"error",path:`${s}.decision.evidence[${a}].referent`,message:`Suppression counterevidence does not exist: ${c.referent}`})}}function ZT(e,t){if(e.architecture===void 0)return;if(!Z(e.architecture)){t.push({level:"error",path:"architecture",message:"Must be an object."});return}let n=e.architecture.boundaries;if(!Array.isArray(n)||n.length===0){t.push({level:"error",path:"architecture.boundaries",message:"Must be a non-empty array."});return}let r=new Set,i=new Set;for(let[a,c]of n.entries()){let l=`architecture.boundaries[${a}]`;if(!Z(c)){t.push({level:"error",path:l,message:"Architecture boundary must be an object."});continue}let u=c.name;typeof u!="string"||u.trim()===""?t.push({level:"error",path:`${l}.name`,message:"Boundary name is required."}):r.has(u)?t.push({level:"error",path:`${l}.name`,message:`Duplicate boundary name: ${u}`}):r.add(u);let d=c.subUnits;d!==void 0&&d!=="directory"&&d!=="file"&&t.push({level:"error",path:`${l}.subUnits`,message:"Must be 'directory' or 'file'."});let m=c.maxFiles;m!==void 0&&(typeof m!="number"||!Number.isInteger(m)||m<0)&&t.push({level:"error",path:`${l}.maxFiles`,message:"Must be a non-negative integer."});let p=c.paths;if(!Array.isArray(p)||p.length===0){t.push({level:"error",path:`${l}.paths`,message:"Boundary paths must be a non-empty array."});continue}for(let[f,g]of p.entries()){let h=`${l}.paths[${f}]`;if(typeof g!="string"||g.trim()===""){t.push({level:"error",path:h,message:"Boundary path must be a non-empty string."});continue}eA(g)||t.push({level:"error",path:h,message:"Boundary path must be project-relative and may use only one trailing /* or /** glob."}),i.has(g)?t.push({level:"error",path:h,message:`Duplicate boundary path: ${g}`}):i.add(g)}}let o=e.architecture.allowedDependencies;if(o!==void 0&&!Z(o))t.push({level:"error",path:"architecture.allowedDependencies",message:"Must be an object keyed by boundary name."});else if(Z(o))for(let[a,c]of Object.entries(o)){let l=`architecture.allowedDependencies.${a}`;if(r.has(a)||t.push({level:"error",path:l,message:`Unknown source boundary: ${a}`}),!Array.isArray(c)){t.push({level:"error",path:l,message:"Dependency row must be an array."});continue}let u=new Set;for(let[d,m]of c.entries()){let p=`${l}[${d}]`;typeof m!="string"||m.trim()===""?t.push({level:"error",path:p,message:"Target boundary name is required."}):r.has(m)?u.has(m)?t.push({level:"error",path:p,message:`Duplicate target boundary: ${m}`}):u.add(m):t.push({level:"error",path:p,message:`Unknown target boundary: ${m}`})}}e.architecture.requireAcyclic!==void 0&&typeof e.architecture.requireAcyclic!="boolean"&&t.push({level:"error",path:"architecture.requireAcyclic",message:"Must be a boolean."});for(let a of["requireCompleteCoverage","requireResolvedBoundaries","requireMinimalPolicy"])e.architecture[a]!==void 0&&typeof e.architecture[a]!="boolean"&&t.push({level:"error",path:`architecture.${a}`,message:"Must be a boolean."});for(let a of["maxBoundaryFanOut","maxBoundaryFiles"]){let c=e.architecture[a];c!==void 0&&(typeof c!="number"||!Number.isInteger(c)||c<0)&&t.push({level:"error",path:`architecture.${a}`,message:"Must be a non-negative integer."})}let s=e.architecture.testPaths;if(s!==void 0&&(!Array.isArray(s)||s.some(a=>typeof a!="string"))&&t.push({level:"error",path:"architecture.testPaths",message:"Must be an array of strings."}),e.architecture.requireCompletePolicy!==void 0&&typeof e.architecture.requireCompletePolicy!="boolean")t.push({level:"error",path:"architecture.requireCompletePolicy",message:"Must be a boolean."});else if(e.architecture.requireCompletePolicy===!0){let a=Z(o)?o:{};for(let c of[...r].sort())Object.hasOwn(a,c)||t.push({level:"error",path:`architecture.allowedDependencies.${c}`,message:"A dependency row is required by architecture.requireCompletePolicy."})}}function eA(e){let t=e.replace(/\\/g,"/");if(t.startsWith("/")||t==="."||t===".."||t.split("/").includes(".."))return!1;let n=t.replace(/\/\*\*?$/,"");return n.length>0&&!/[*?[\]]/.test(n)}function tA(e,t){let n=e.docs?.snapshotPaths;if(n!==void 0){if(!Array.isArray(n)){t.push({level:"error",path:"docs.snapshotPaths",message:"Must be an array."});return}for(let[r,i]of n.entries())(typeof i!="string"||i.trim()==="")&&t.push({level:"error",path:`docs.snapshotPaths[${r}]`,message:"Snapshot path glob must be a non-empty string."})}}function nA(e,t,n){if(e.coverageContracts!==void 0){if(!Array.isArray(e.coverageContracts)){t.push({level:"error",path:"coverageContracts",message:"Must be an array."});return}for(let[r,i]of e.coverageContracts.entries()){let o=`coverageContracts[${r}]`;if(!Z(i)){t.push({level:"error",path:o,message:"Coverage contract must be an object."});continue}(typeof i.name!="string"||i.name.trim()==="")&&t.push({level:"error",path:`${o}.name`,message:"Coverage contract name is required."}),typeof i.file!="string"||i.file.trim()===""?t.push({level:"error",path:`${o}.file`,message:"Coverage contract file is required."}):n.projectRoot&&!Li(xn(n.projectRoot,i.file))&&t.push({level:"warning",path:`${o}.file`,message:`Coverage contract file does not exist: ${i.file}`}),mb(t,i.keys,`${o}.keys`,zT,"Unknown coverage-contract key extractor type."),mb(t,i.mustEqual,`${o}.mustEqual`,KT,"Unknown coverage-contract ground-truth source type."),i.allowExtra!==void 0&&typeof i.allowExtra!="boolean"&&t.push({level:"error",path:`${o}.allowExtra`,message:"Must be a boolean."})}}}function mb(e,t,n,r,i){if(!Z(t)){e.push({level:"error",path:n,message:'Must be an object with a "type" field.'});return}if(typeof t.type!="string"||!r.has(t.type)){e.push({level:"error",path:`${n}.type`,message:`${i} Got: ${String(t.type)}`});return}let o={"object-literal-keys":["identifier"],"string-array":["identifier"],"markdown-list":["marker"],"top-level-dirs":["path"],"file-glob":["pattern"],"registered-commands":[],"builtin-skills":[]};for(let s of o[t.type]??[])(typeof t[s]!="string"||t[s].length===0)&&e.push({level:"error",path:`${n}.${s}`,message:`"${t.type}" requires a non-empty string "${s}".`})}function _9(e){return{...ET,...e.watch,cooldownMs:Math.max($a,e.watch?.cooldownMs??Xu),resourceBudget:{...Qu,...e.watch?.resourceBudget}}}function O9(e,t){let n=xn(e,nr),r=pb(),i={collaborationDomainId:r,languages:t,watch:{enabled:!0,debounceMs:fb,cooldownMs:Xu,gitPollMs:2e3,idleTimeoutMs:gb,autoRefresh:!0,resourceBudget:{...Qu}}},o=Fo(n,s=>{if(!s.revision.exists)return{kind:"write",text:wi(i)};let a=Ha(s,i);return a.config.collaborationDomainId?{kind:"unchanged"}:{kind:"write",text:wi({...a.config,collaborationDomainId:r})}});return{configPath:n,changed:o.changed}}function B9(e,t,n=pb()){let r=xn(e,nr),i=t,o=Fo(r,s=>{let a=Ha(s,t);if(a.config.collaborationDomainId)return i=a.config,{kind:"unchanged"};let c={...a.config,collaborationDomainId:n};return i=c,{kind:"write",text:wi(c)}});return{configPath:r,config:i,changed:o.changed}}function $9(e,t,n){let r=xn(e,nr),i=[...n],o=t,s=Fo(r,a=>{let c=Ha(a,t);if(yb(t.languages,c.config.languages,i))throw new Ao(r,"languages");let l={...c.config,languages:i};return o=l,a.revision.exists&&!c.needsMigration&&ja(l,c.config)?{kind:"unchanged"}:{kind:"write",text:wi(l)}});return{configPath:r,config:o,changed:s.changed}}function j9(e,t,n){let r=xn(e,nr),i=t,o=Fo(r,s=>{let a=Ha(s,t);if(yb(t.watch?.enabled,a.config.watch?.enabled,n))throw new Ao(r,"watch.enabled");let c={...a.config,watch:{...a.config.watch,enabled:n,...n&&a.config.watch?.autoRefresh===void 0?{autoRefresh:!0}:{}}};return i=c,s.revision.exists&&!a.needsMigration&&ja(c,a.config)?{kind:"unchanged"}:{kind:"write",text:wi(c)}});return{configPath:r,config:i,changed:o.changed}}function Ha(e,t){if(!e.revision.exists)return{config:Fa(t),needsMigration:!0};let n=bb(zu(e.text),e.path,"update");return{config:n.config,needsMigration:n.needsMigration}}function ja(e,t){return JSON.stringify(e)===JSON.stringify(t)}function yb(e,t,n){return!ja(e,t)&&!ja(t,n)}function bb(e,t,n){if(e.kind==="legacy"||e.kind==="supported")return e;if(e.kind==="malformed"){let i=n==="read"?`invalid ${nr} at ${t}: ${e.reason}`:`Cannot update ${t}: the latest project config is ${e.reason}.`;throw new Error(`${i} The file was left untouched.`)}let r=n==="read"?`invalid ${nr} at ${t}`:`Cannot update ${t}: the latest project config is invalid`;throw new Error(`${r} (unsupported ${e.direction} schemaVersion ${e.schemaVersion}; this scip-query reads legacy v${Qn} and current v${Zn}). Upgrade scip-query before retrying; the file was left untouched.`)}function rA(e,t){if(!Z(e))return;let n=e;if(Ee(t,n,"",IT),Ee(t,n.watch,"watch",wT),Ee(t,n.watch?.resourceBudget,"watch.resourceBudget",LT),Ee(t,n.entryRoots,"entryRoots",PT),Ee(t,n.semantic,"semantic",DT),Ee(t,n.semantic?.typescript,"semantic.typescript",MT),Ee(t,n.semantic?.rust,"semantic.rust",TT),Ee(t,n.locality,"locality",FT),Ee(t,n.architecture,"architecture",kT),Ee(t,n.docs,"docs",_T),Array.isArray(n.architecture?.boundaries))for(let[r,i]of n.architecture.boundaries.entries())Ee(t,i,`architecture.boundaries[${r}]`,NT);if(Z(n.indexer)){Ee(t,n.indexer,"indexer",ub);for(let[r,i]of Object.entries(n.indexer))ub.has(r)&&Ee(t,i,`indexer.${r}`,AT)}if(Array.isArray(n.declaredCouplings))for(let[r,i]of n.declaredCouplings.entries())Ee(t,i,`declaredCouplings[${r}]`,OT);if(Array.isArray(n.suppressions)){for(let[r,i]of n.suppressions.entries())if(Ee(t,i,`suppressions[${r}]`,BT),Z(i.decision)){if(Ee(t,i.decision,`suppressions[${r}].decision`,$T),Array.isArray(i.decision.evidence))for(let[o,s]of i.decision.evidence.entries())Ee(t,s,`suppressions[${r}].decision.evidence[${o}]`,jT);Ee(t,i.decision.invalidateOn,`suppressions[${r}].decision.invalidateOn`,HT)}}if(Array.isArray(n.coverageContracts))for(let[r,i]of n.coverageContracts.entries()){let o=`coverageContracts[${r}]`;Ee(t,i,o,UT),Z(i)&&(Ee(t,i.keys,`${o}.keys`,qT),Ee(t,i.mustEqual,`${o}.mustEqual`,GT))}}function Ee(e,t,n,r){if(Z(t))for(let i of Object.keys(t))r.has(i)||e.push({level:"warning",path:n?`${n}.${i}`:i,message:"Unknown config key."})}import{existsSync as Ua,lstatSync as iA}from"fs";import{resolve as oA}from"path";function t7(e){return e.state==="fresh"?!0:e.state!=="stale"?!1:!e.reason.startsWith("SQLite generation requires repair")}function Sb(e,t,n,r={}){let i=new Date().toISOString();if(!Ua(n.dbPath))return{state:"missing",checkedAt:i,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!Ua(n.metaPath))return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let o=br(Ve(n.metaPath,"reindex metadata"));if(o.kind==="unsupported")return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Reindex metadata version ${o.version} is unsupported by this scip-query build.`,remedy:"Upgrade scip-query or run: scip-query reindex"};if(o.kind==="malformed")return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Could not decode reindex metadata: ${o.reason}`,remedy:"Run: scip-query reindex"};let s=o.metadata,a=t.languages??ag(e),c=s.fingerprint,l=n.cacheDir&&r.gitContext&&$l(r.gitContext,n.cacheDir,c)?c:void 0,u=n.cacheDir&&r.gitContext&&l&&aA(l,a,t)&&cA(e,l,t)?r.gitObservation?.context===r.gitContext?r.gitContext:Zp(r.gitContext):void 0,d=r.gitObservation&&r.gitObservation.context===r.gitContext?r.gitObservation.projectFileInventorySequence:void 0,m=u?.clean&&ef(e,void 0,{cachedInventoryAfterSequence:d})?u:void 0,p=n.cacheDir&&m&&l&&$l(m,n.cacheDir,l)?l:sA(e,a,t),f=[...s.indexedLanguages??[]].sort(),g=o.capabilities.publishableGeneration&&Vp(Xi(s.fingerprint),p)&&JSON.stringify(f)===JSON.stringify(p.languages),h=Bl(n.dbPath,n.metaPath),b=h.state==="invalid"||h.state==="drifted",S=g?cg(n.dbPath,p,f):void 0,y=S?.state==="incomplete",x=g&&!b&&!y;return{state:x?"fresh":"stale",checkedAt:i,metaPath:n.metaPath,updatedAt:s.updatedAt,lastRefresh:s.lastRefresh,reason:b?`SQLite generation requires repair: ${h.reason}`:y?`SQLite generation is missing ${S.missingDocumentCount} indexed source document(s): ${S.missingPaths.join(", ")}`:g?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:x?void 0:"Run: scip-query reindex"}}catch(o){return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Could not read reindex metadata: ${o instanceof Error?o.message:String(o)}`,remedy:"Run: scip-query reindex"}}}function n7(e){let t=new Date().toISOString();if(!Ua(e.dbPath))return{state:"missing",checkedAt:t,metaPath:e.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!Ua(e.metaPath))return{state:"unknown",checkedAt:t,metaPath:e.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let n=br(Ve(e.metaPath,"reindex metadata"));if(n.kind==="unsupported")return{state:"unknown",checkedAt:t,metaPath:e.metaPath,reason:`Reindex metadata version ${n.version} is unsupported by this scip-query build.`,remedy:"Upgrade scip-query or run: scip-query reindex"};if(n.kind==="malformed")return{state:"unknown",checkedAt:t,metaPath:e.metaPath,reason:`Could not decode reindex metadata: ${n.reason}`,remedy:"Run: scip-query reindex"};let r=n.metadata,i=[...r.indexedLanguages??[]].sort(),o=Xi(r.fingerprint),s=[...o?.languages??[]].sort(),a=n.capabilities.publishableGeneration&&o!==null&&JSON.stringify(i)===JSON.stringify(s),c=Bl(e.dbPath,e.metaPath),l=c.state==="invalid"||c.state==="drifted",u=a&&!l;return{state:u?"fresh":"stale",checkedAt:t,metaPath:e.metaPath,updatedAt:r.updatedAt,lastRefresh:r.lastRefresh,reason:l?`SQLite generation requires repair: ${c.reason}`:a?"Watcher accepted the newly published index generation with no later changes pending.":"Published index metadata is not a complete queryable generation.",remedy:u?void 0:"Run: scip-query reindex"}}catch(n){return{state:"unknown",checkedAt:t,metaPath:e.metaPath,reason:`Could not read reindex metadata: ${n instanceof Error?n.message:String(n)}`,remedy:"Run: scip-query reindex"}}}function sA(e,t,n){return cf(e,t,{pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:n.indexer?.typescript?.projectMode,typescriptProjects:n.indexer?.typescript?.projects,clojureConfigPath:n.indexer?.clojure?.configPath})}function aA(e,t,n){let r=lA(t,n);return e.version===r.version&&JSON.stringify([...e.languages].sort())===JSON.stringify(r.languages)&&e.pnpmWorkspaces===r.pnpmWorkspaces&&e.typescriptProjectMode===r.typescriptProjectMode&&JSON.stringify([...e.typescriptProjects].sort())===JSON.stringify(r.typescriptProjects)&&e.clojureConfigPath===r.clojureConfigPath}function cA(e,t,n){if(!(t.languages.includes("typescript")||!!t.clojureConfigPath))return!0;let i=Fs(e);if(t.clojureConfigPath){let o=mn(t.clojureConfigPath);if(!i.includes(o))return!1;try{if(!iA(oA(e,o)).isFile())return!1}catch{return!1}}return!t.languages.includes("typescript")||tf(e,n.indexer?.typescript?.projectMode,n.indexer?.typescript?.projects??[],i)}function lA(e,t){return lf(e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}import{existsSync as uA,readdirSync as dA}from"fs";import{createHash as mA}from"crypto";import{join as td}from"path";function ed(e){let t=0,n=0,r=0,i=0,o=0,s=[];for(let l of e)switch(l.state){case"legacy":t+=1;break;case"current":n+=1;break;case"unsupported-older":r+=1,s.push(Zu(l));break;case"unsupported-future":i+=1,s.push(Zu(l));break;case"malformed":o+=1,s.push(Zu(l));break}let a=t+n,c=r+i+o;return{complete:c===0,total:e.length,accepted:a,legacy:t,current:n,unsupportedOlder:r,unsupportedFuture:i,malformed:o,omitted:c,issues:s}}function Zu(e){if(e.state==="legacy"||e.state==="current")throw new Error(`accepted record ${e.path} cannot become a compatibility issue`);return{path:e.path,state:e.state,reason:e.reason??e.state}}var xb=td(".scipquery","suppressions"),vb="scip-query-suppression",Cb=1,qa=2;function pA(e){return td(e,xb)}function fA(e){if(e.id&&e.id.trim()!=="")return`${e.id.trim()}.json`;let t=`${e.check??""}\0${e.file??""}`;return`CHECK-${mA("sha256").update(t).digest("hex").slice(0,12).toUpperCase()}.json`}function gA(e){return fA(e).slice(0,-5)}function hA(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return{state:"malformed",error:"not a suppression object"};let n=e;if(n.schemaVersion===void 0&&(n.kind!==void 0||n.suppressionIdentity!==void 0||n.writer!==void 0))return{state:"malformed",error:"suppression envelope metadata requires schemaVersion"};if(n.schemaVersion!==void 0){if(!Number.isSafeInteger(n.schemaVersion))return{state:"malformed",error:"schemaVersion must be a positive safe integer"};if(n.schemaVersion!==Cb&&n.schemaVersion!==qa)return{state:n.schemaVersion>qa?"unsupported-future":"unsupported-older",error:`unsupported schemaVersion ${String(n.schemaVersion)}`};if(n.kind!==void 0&&n.kind!==vb)return{state:"malformed",error:`kind must be ${vb}`}}if(n.schemaVersion===Cb&&n.decision!==void 0)return{state:"malformed",error:"schemaVersion 1 cannot carry automated adjudication metadata"};if(n.schemaVersion===qa&&!Na(n.decision))return{state:"malformed",error:"schemaVersion 2 requires a valid automated adjudication decision"};if(typeof n.reason!="string"||n.reason.trim()==="")return{state:"malformed",error:"missing reason"};if(!n.id&&!n.check)return{state:"malformed",error:"needs an id or a check"};let r=yA(n);if(n.schemaVersion===void 0)return{state:"legacy",suppression:r,record:n,schemaVersion:0};let i=gA(r);return n.suppressionIdentity!==i||t!==void 0&&n.suppressionIdentity!==t?{state:"malformed",error:"suppressionIdentity does not match the suppression target or filename"}:!n.writer||n.writer.tool!=="scip-query"||typeof n.writer.version!="string"||n.writer.version.trim()===""?{state:"malformed",error:"missing valid writer metadata"}:typeof n.createdAt!="string"||!Number.isFinite(Date.parse(n.createdAt))?{state:"malformed",error:"missing valid createdAt timestamp"}:n.updatedAt!==void 0&&(typeof n.updatedAt!="string"||!Number.isFinite(Date.parse(n.updatedAt)))?{state:"malformed",error:"invalid updatedAt timestamp"}:{state:n.schemaVersion===qa?"current":"legacy",suppression:r,record:n,schemaVersion:n.schemaVersion}}function Rb(e){let t=pA(e);if(!uA(t))return{suppressions:[],compatibility:ed([]),warnings:[]};let n=[],r=[];for(let o of dA(t).sort()){if(!o.endsWith(".json"))continue;let s=td(t,o),a=`${xb}/${o}`,c;try{c=JSON.parse(Ve(s,"suppression record"))}catch{r.push({path:a,state:"malformed",reason:"malformed JSON"});continue}let l=hA(c,o.slice(0,-5));if("error"in l){r.push({path:a,state:l.state,reason:l.error});continue}r.push({path:a,state:l.state}),n.push(l.suppression)}let i=ed(r);return{suppressions:n,compatibility:i,warnings:i.issues.map(o=>`${o.path}: ${o.reason} \u2014 ignored`)}}function yA(e){return{...typeof e.id=="string"?{id:e.id}:{},...typeof e.check=="string"?{check:e.check}:{},...typeof e.file=="string"?{file:e.file}:{},reason:e.reason,...typeof e.expiresAt=="string"?{expiresAt:e.expiresAt}:{},...typeof e.createdAt=="string"?{createdAt:e.createdAt}:{},...e.decision?{decision:e.decision}:{}}}function Ga(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var nd,Nr;function R7(e){nd=e}function za(){return Nr}function Eb(e=Ga(),t=void 0){if(t===void 0&&nd?.projectRoot===e)return nd;let n=hb(e),r=rf(e,n),i=process.env.SCIP_QUERY_INDEX_DB;if(i)return{projectRoot:e,config:n,paths:r,dbPath:i,dbPathSource:"env",gitContext:t};if(rd(r.dbPath))return{projectRoot:e,config:n,paths:r,dbPath:r.dbPath,dbPathSource:"configured",gitContext:t};let o=SA(e,"index.db");return{projectRoot:e,config:n,paths:r,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:xA(o,r.dbPath),gitContext:t}}function E7(e){return Eb(e).dbPath}function I7(e,t,n,r={}){if(rd(n.dbPath)&&r.gitContext?.clean===!1&&r.watcherGeneration!==void 0&&ig(n.dbPath)===r.watcherGeneration)return dg(e,t,n,r.gitContext);let i=Sb(e,t,n,{gitContext:r.gitContext,gitObservation:r.gitObservation});return i.state==="fresh"?{kind:"local-fresh",freshness:i}:ug(e,t,n,r.gitContext)}function w7(e){return!e.startsWith("__")&&!vA.has(e)}function L7(e){return e==="search"||e==="code"}var vA=new Set(["capabilities","check-deps","config-validate","continue","doctor","init","install-skills","reindex","setup","setup-agent","status","suppress","uninstall","watch"]);function Ib(){try{return CA(Ga(),{warnOnRootFallback:!0})}catch(e){console.error(`error: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}function CA(e,t={}){let{config:n,paths:r,dbPath:i,dbPathSource:o,rootFallbackWarning:s,gitContext:a}=Eb(e);if(!rd(i))throw new Error("No index.db found. Run: scip-query reindex");t.warnOnRootFallback&&o==="root-fallback"&&s&&console.error(s);let c=Rb(e).suppressions,l={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??r.indexPath,projectRoot:e,collaborationDomainId:n.collaborationDomainId,sharedEvidenceDbPath:lg(e,n,a),entryRoots:n.entryRoots,semantic:n.semantic,suppressions:[...n.suppressions??[],...c],declaredCouplings:n.declaredCouplings,locality:n.locality,architecture:n.architecture,coverageContracts:n.coverageContracts,docs:n.docs},u=sg(e);return new og(l,u)}function xA(e,t){let n="unknown time";try{n=bA(e).mtime.toISOString()}catch{}return`warning: using legacy project-root index.db (${e}, modified ${n}) because the configured index was not found at ${t}. This fallback may be stale; run 'scip-query reindex' to refresh the configured index.`}function Ka(e){return Xp(()=>{let t=Ib(),n=Nr;Nr=t;try{return e(t)}finally{Nr=n,t.close()}})}async function P7(e){let t=Qp(),n=Ib(),r=Nr;Nr=n;try{return await e(n)}finally{Nr=r,n.close(),t()}}function D7(e,t){return t.concat([e])}function id(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(0)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function M7(e){switch(e.state){case"idle":return"Watching (idle)";case"waiting":{let t=Math.round((e.reindexAt-Date.now())/1e3);return`${e.changedFiles} file(s) changed, reindexing in ${t}s...`}case"indexing":return`Reindexing... (${Math.round((Date.now()-e.startedAt)/1e3)}s)`;case"cooldown":return`Cooldown (${Math.round((e.until-Date.now())/1e3)}s)${e.dirty?" \u2014 changes pending":""}`;case"budget-paused":return`Automatic reindex paused by resource budget (${Math.max(0,Math.round((e.until-Date.now())/1e3))}s; ${e.reason}; ${e.rebuilt} rebuilds, ${id(e.estimatedWriteBytes)} estimated writes)${e.dirty?" \u2014 changes pending":""}`;case"draining":return`Stopping safely \u2014 ${e.reason}`;default:return RA(e)}}function RA(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}var EA=new Map([[8,"\u2408"],[9,"\u2409"],[10,"\u2424"],[13,"\u240D"]]),A7=6500,F7=8e3,k7=6500,N7=3500;function wb(e,t={}){let n=t.allowNewlines??!0,r=t.allowTabs??!0,i="";for(let o=0;o<e.length;){let s=e.charCodeAt(o);if(s===27){o=IA(e,o);continue}if(s===155){o=Lb(e,o+1);continue}if(s===144||s===152||s===157||s===158||s===159){o=Pb(e,o+1);continue}if(PA(s)){s===10&&n?i+=`
54
- `:s===9&&r?i+=" ":i+=EA.get(s)??"\uFFFD",o+=1;continue}if(DA(s)){i+="\uFFFD",o+=1;continue}i+=e[o],o+=1}return i}function Tt(e){return wb(e,{allowNewlines:!1,allowTabs:!1})}function sd(e,t=n=>process.stdout.write(n)){t(`${e}
55
- `)}function _7(e=console){let t={log:e.log.bind(e),error:e.error.bind(e),warn:e.warn.bind(e)};return e.log=(...n)=>t.log(...n.map(od)),e.error=(...n)=>t.error(...n.map(od)),e.warn=(...n)=>t.warn(...n.map(od)),()=>{e.log=t.log,e.error=t.error,e.warn=t.warn}}function od(e){return typeof e=="string"?wb(e):e}function IA(e,t){let n=e.charCodeAt(t+1);if(Number.isNaN(n))return e.length;if(n===91)return Lb(e,t+2);if(n===80||n===88||n===93||n===94||n===95)return Pb(e,t+2);let r=t+1;for(;r<e.length&&wA(e.charCodeAt(r));)r+=1;return r<e.length&&LA(e.charCodeAt(r))?r+1:t+1}function Lb(e,t){let n=t;for(;n<e.length;){let r=e.charCodeAt(n);if(n+=1,r>=64&&r<=126)return n}return e.length}function Pb(e,t){let n=t;for(;n<e.length;){let r=e.charCodeAt(n);if(r===7||r===156)return n+1;if(r===27&&e.charCodeAt(n+1)===92)return n+2;n+=1}return e.length}function wA(e){return e>=32&&e<=47}function LA(e){return e>=48&&e<=126}function PA(e){return e<=31||e>=127&&e<=159}function DA(e){return e===1564||e===8206||e===8207||e>=8234&&e<=8238||e>=8294&&e<=8297}function Wa(e){return e+1}function MA(e,t){return`${Wa(e)}-${Wa(t)}`}function ad(e,t,n){return`${Tt(e)}:${MA(t,n)}`}function $7(e,t=180){let n=Tt(e).replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var cd={empty(e){console.log(Tt(e))},list(e,t){for(let n of e)console.log(Tt(t(n)))},groupedByFile(e,t,n=r=>r.relativePath){let r="";for(let i of e){let o=n(i);o!==r&&(r&&console.log(""),console.log(Tt(o)),r=o),console.log(Tt(t(i)))}},sectionedReport(e){let t=!0;for(let n of e)if(!(n.skipIfEmpty&&n.rows.length===0)){t||console.log(""),t=!1,n.title!==void 0&&console.log(`\u2550\u2550\u2550 ${Tt(n.title)} \u2550\u2550\u2550`),n.explanation!==void 0&&console.log(Tt(n.explanation));for(let r of n.rows){let i=n.preserveRowNewlines?r.split(`
56
- `):[r];for(let o of i)console.log(Tt(o))}}},table(e,t,n){console.log(` ${e.map(Tt).join(" ")}`);let r=n??e.map(i=>i.length);console.log(` ${r.map(i=>"\u2500".repeat(i)).join(" ")}`);for(let i of t)console.log(Tt(i))}};import{availableParallelism as iw,totalmem as ml}from"os";import{fileURLToPath as pl}from"url";import{getHeapStatistics as U5}from"v8";import{existsSync as Va,readdirSync as Tb}from"fs";import{join as ko}from"path";var TA={files:new Set,pathPrefixes:[]},AA={reasonsByFile:new Map},ld=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,FA=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,Ab=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],kA=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),NA=4,_A=me("package-surface",{clearGroups:["whole-project"]}),OA=me("package-operational-surface",{clearGroups:["whole-project"]});function Fb(e){return _A.get(e,()=>$A(e.config.projectRoot))}function En(e,t){let n=Fb(e);return n.files.has(t)?!0:n.pathPrefixes.some(r=>t.startsWith(r))}function kb(e,t){return Fb(e).files.has(t)}function BA(e){return OA.get(e,()=>jA(e.config.projectRoot))}function Nb(e,t){return BA(e).reasonsByFile.get(t)??[]}function $A(e){let t=new Set,n=[];for(let{manifest:r,packageRoot:i}of _b(e))for(let o of HA(r))jb(e,i,o,t,n);return t.size===0&&n.length===0?TA:{files:t,pathPrefixes:n}}function jA(e){let t=new Map;for(let{manifest:n,packageRoot:r}of _b(e)){let i=UA(n);for(let s of i)Db(e,r,s,"package binary",t);let o=n.scripts;if(!(!o||typeof o!="object")){for(let[s,a]of Object.entries(o))if(typeof a=="string")for(let c of qA(a))Db(e,r,c,`package script "${s}"`,t)}}return t.size===0?AA:{reasonsByFile:t}}function _b(e){let t=[],n=Bb(e,"");return n&&t.push({manifest:n,packageRoot:""}),Ob(e,"",t,0),t}function Ob(e,t,n,r){if(r>=NA)return;let i=ko(e,t);if(Va(i))for(let o of Tb(i,{withFileTypes:!0})){if(!o.isDirectory()||kA.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=Bb(e,s);a&&n.push({manifest:a,packageRoot:s}),Ob(e,s,n,r+1)}}function Bb(e,t){let n;try{n=Ye(e,ko(t,"package.json"),{maxBytes:8*1024*1024,inputKind:"package manifest"})}catch(r){if(!Je(r))throw r;return null}try{let r=JSON.parse(n);return r&&typeof r=="object"?r:null}catch{return null}}function HA(e){let t=[];for(let r of["main","module","types","browser"])typeof e[r]=="string"&&t.push(e[r]);let n=e.bin;if(typeof n=="string")t.push(n);else if(n&&typeof n=="object")for(let r of Object.values(n))typeof r=="string"&&t.push(r);return $b(e.exports,t),t}function UA(e){let t=e.bin;return typeof t=="string"?[t]:!t||typeof t!="object"?[]:Object.values(t).filter(n=>typeof n=="string")}function qA(e){let t=[],n=/(?:^|&&|\|\||;)\s*(?:(?:cross-env|env)(?:\s+[A-Za-z_][A-Za-z0-9_]*=\S+)*\s+)?(?:node|bun|tsx|ts-node|vite-node|python3?|deno\s+run)\s+(?:(?:--?[A-Za-z0-9-]+(?:=\S+)?)\s+)*["']?([^"'`\s]+\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs|py))["']?/g;for(let r of e.matchAll(n)){let i=r[1];i&&!i.startsWith("node_modules/")&&!i.startsWith("./node_modules/")&&t.push(i)}return t}function Db(e,t,n,r,i){let o=new Set;jb(e,t,n,o,[]);for(let s of o){let a=i.get(s)??[];a.includes(r)||a.push(r),i.set(s,a)}}function $b(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))$b(n,t)}function jb(e,t,n,r,i){let o=n.replace(/\\/g,"/").replace(/^\.\//,"");if(o===""||o.startsWith(".."))return;let s=o.indexOf("*");if(s>=0){let c=o.slice(0,s);for(let l of Mb(c))l!==""&&i.push(Rn(t,l));return}let a=o.replace(FA,"");for(let c of Mb(a)){c===a&&c===o&&r.add(Rn(t,o));for(let l of Ab)GA(e,r,t,c+l)}r.add(Rn(t,o))}function Mb(e){let t=[e];return ld.test(e)&&(t.push(e.replace(ld,"src/")),t.push(e.replace(ld,""))),t}function GA(e,t,n,r){let i=Rn(n,r);if(t.add(i),!r.startsWith("src/")||Va(ko(e,i)))return;let o=Ab.find(u=>r.endsWith(u));if(!o)return;let s=r.slice(0,-o.length);zA(e,t,n,s,o);let a=s.lastIndexOf("/");if(a<=4)return;let c=s.slice(0,a),l=s.slice(a+1);for(let u of Hb(e,n,c,`${l}${o}`))t.add(u)}function zA(e,t,n,r,i){let o=Rn(n,`${r}/index${i}`);Va(ko(e,o))&&t.add(o)}function Hb(e,t,n,r){let i=ko(e,t,n);if(!Va(i))return[];let o=[];for(let s of Tb(i,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...Hb(e,t,a,r)):s.isFile()&&s.name===r&&o.push(Rn(t,a))}return o}function Rn(e,t){return e?`${e}/${t}`:t}import{existsSync as ud,readdirSync as KA}from"fs";import{dirname as WA,join as dd}from"path";var VA={rootFiles:new Set,sourcePrefixes:[]},YA=new Set([".git",".scipquery","node_modules","target"]),JA=6,XA=me("rust-library-surface",{clearGroups:["whole-project"]});function Ub(e,t,n){if(!n.endsWith(".rs")||!eF(QA(e),n))return!1;let r=U(e,n).find(i=>i.symbol===t);return r?tF(V(e,n)[r.startLine]??""):!1}function QA(e){return XA.get(e,()=>ZA(e.config.projectRoot))}function ZA(e){let t=new Set,n=new Set;for(let r of nF(e)){let i=Ye(e,dd(r,"Cargo.toml"),{maxBytes:8388608,inputKind:"Cargo manifest"}),o=rF(i),s=Rn(r,"src/lib.rs"),a=o?Rn(r,o):!iF(i)&&xt(e,s)?s:null;if(!a)continue;t.add(a);let c=WA(a).replaceAll("\\","/");n.add(c==="."?"":`${c}/`)}return t.size===0?VA:{rootFiles:t,sourcePrefixes:[...n].sort()}}function eF(e,t){return t.endsWith(".rs")?e.rootFiles.has(t)?!0:oF(t)?!1:e.sourcePrefixes.some(n=>t.startsWith(n)):!1}function tF(e){return/^\s*pub\s+(?!\()/.test(e)}function nF(e){if(!ud(e))return[];let t=[];return qb(e,"",t,0),t}function qb(e,t,n,r){let i=dd(e,t);if(ud(i)&&(ud(dd(i,"Cargo.toml"))&&n.push(t),!(r>=JA)))for(let o of KA(i,{withFileTypes:!0})){if(!o.isDirectory()||YA.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name;qb(e,s,n,r+1)}}function rF(e){let t=!1;for(let n of e.split(`
57
- `)){let r=n.replace(/\s+#.*$/,"").trim(),i=/^\[([^\]]+)\]$/.exec(r);if(i){t=i[1]==="lib";continue}if(!t)continue;let o=/^path\s*=\s*["']([^"']+)["']/.exec(r)?.[1];if(o)return o.replaceAll("\\","/").replace(/^\.\//,"")}return null}function iF(e){let t=!1;for(let n of e.split(`
58
- `)){let r=n.replace(/\s+#.*$/,"").trim(),i=/^\[([^\]]+)\]$/.exec(r);if(i){t=i[1]==="package";continue}if(t&&/^autolib\s*=\s*false\b/.test(r))return!0}return!1}function oF(e){return/(?:^|\/)src\/main\.rs$/.test(e)||/(?:^|\/)src\/bin\//.test(e)||/(?:^|\/)(?:examples|tests|benches)\//.test(e)}function Pi(e){return q(e)==="barrel"}function zb(e){return sF.get(e,()=>{let n=Q(e,{includeIgnored:!1}).filter(s=>{let a=q(s);return a==="entry"||a==="worker"});if(n.length===0)return new Set;let r=Ae(e),i=new Set,o=new Set;for(;n.length>0;){let s=n.shift();if(!i.has(s)){i.add(s),q(s)==="barrel"&&o.add(s);for(let a of r.get(s)??[])i.has(a)||n.push(a)}}return o})}var sF=me("live-barrels",{clearGroups:["whole-project"]});function md(e,t){return zb(e).has(it(t))}function Kb(e){let t=zb(e);return Q(e,{includeIgnored:!1}).filter(n=>Pi(n)&&!t.has(n)&&!aF(e,n))}function aF(e,t){let n=it(t),r=gn(e).forFile(n,{facts:!0}).facts?.callables;return r&&r.length>0?!0:(e.get(`SELECT COUNT(*) AS n
59
- FROM defn_enclosing_ranges der
60
- JOIN documents d ON d.id = der.document_id
61
- WHERE d.relative_path = ?
62
- AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function Ue(e,t){let n=it(t),r=q(t);return r==="entry"||r==="worker"||pd(n)||md(e,n)}function Di(e,t,n){let r=it(n),i=[];En(e,r)&&i.push("package-surface-file"),uF(e,t,r)&&i.push("transitive-package-surface"),Ub(e,t,r)&&i.push("rust-public-library"),RF(t,r)&&i.push("framework-entrypoint");let o=e.config.entryRoots;return o&&(o.files?.some(s=>it(s)===r)&&i.push("configured-file"),o.pathPrefixes?.some(s=>r.startsWith(it(s)))&&i.push("configured-path-prefix"),o.qualifiedVars?.some(s=>IF(t,s))&&i.push("configured-qualified-var"),o.symbolPatterns?.some(s=>{try{return kr(s,"entryRoots.symbolPatterns entry").test(t)}catch{return!1}})&&i.push("configured-symbol-pattern")),i}function Fe(e,t,n){return Di(e,t,n).length>0}var cF=me("package-surface-reachability",{clearGroups:["whole-project"]}),lF=me("explicit-package-surface-reachability",{clearGroups:["whole-project"]});function uF(e,t,n){let r=dF(e).get(n);return r===void 0?!1:r===null||r.has(z(t))}function Wb(e,t,n){let r=mF(e).get(n);return r===void 0?!1:r===null||r.has(z(t))}function dF(e){return cF.get(e,()=>Vb(e,t=>En(e,t)))}function mF(e){return lF.get(e,()=>Vb(e,t=>kb(e,t)))}function Vb(e,t){let n=new Map,r=[];for(let i of Q(e,{includeIgnored:!1}))t(i)&&(n.set(i,null),r.push(i));for(;r.length>0;){let i=r.shift(),o=n.get(i);if(o!==void 0)for(let s of Cr(e,i)){if(!s.sourcePath||e.isIgnored(s.sourcePath))continue;let a=pF(o,s);a!==void 0&&fF(n,s.sourcePath,a)&&r.push(s.sourcePath)}}return n}function pF(e,t){if(e===null)return t.kind==="named"?new Set(t.names):null;if(t.kind==="star")return new Set(e);if(t.kind==="star-as")return t.names.some(r=>e.has(r))?null:void 0;let n=t.names.filter(r=>e.has(r));return n.length>0?new Set(n):void 0}function fF(e,t,n){if(!e.has(t))return e.set(t,n),!0;let r=e.get(t);if(r===void 0)return!1;if(r===null||n===null)return r===null?!1:(e.set(t,null),!0);let i=!1;for(let o of n)r.has(o)||(r.add(o),i=!0);return i}var Yb=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),gF=new Set(["default","generateMetadata","generateStaticParams"]),hF=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),yF=new Set(["default","middleware","config"]),bF=new Set(["register","onRequestError"]),SF=new Set(["onRouterTransitionStart"]),vF=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),CF=new Set(["load","actions","entries",...Yb]),xF=new Set(["default"]);function RF(e,t){let n=z(e);return n===""?!1:Jb(t)?Yb.has(n):Xb(t)?gF.has(n):Qb(t)?hF.has(n):Zb(t)?yF.has(n):eS(t)?bF.has(n):tS(t)?SF.has(n):nS(t)?vF.has(n):rS(t)?CF.has(n):EF(t)?xF.has(n):!1}function pd(e){return Jb(e)||Xb(e)||Qb(e)||Zb(e)||eS(e)||tS(e)||nS(e)||rS(e)}function Jb(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Xb(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Qb(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Zb(e){return fd(e,"(?:middleware|proxy)\\.(?:ts|js|mts|mjs)")}function eS(e){return fd(e,"instrumentation\\.(?:ts|js|mts|mjs)")}function tS(e){return fd(e,"instrumentation-client\\.(?:ts|js|mts|mjs)")}function fd(e,t){return new RegExp(`^(?:src/)?${t}$`).test(e)||new RegExp(`(?:^|/)src/${t}$`).test(e)||new RegExp(`(?:^|/)(?:apps|services|packages)/[^/]+/(?:src/)?${t}$`).test(e)}function nS(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function rS(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function EF(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function IF(e,t){let n=t.lastIndexOf("/");if(n<0)return!1;let r=t.slice(0,n),i=t.slice(n+1);return e.includes(Gb(r)+"/")&&e.includes(Gb(i)+".")}function Gb(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function ee(e){return e.endLine-e.startLine+1}function Ya(e,t={}){let{scope:n,files:r,minLoc:i=1,maxLoc:o=Number.POSITIVE_INFINITY,excludeSymbol:s,excludeEntrySurfaces:a=!1,excludeTypesFiles:c=!1,excludeRootedSymbols:l=!1,requireFunctionLikeSymbol:u=!1,requireCallableSymbol:d=!1,excludeRustTraitImplMembers:m=!1,includeSuppressed:p=!1,sortByLocDesc:f=!1}=t,g=[],h=wF(e,{scope:n,files:r,requireFunctionLikeSymbol:u,requireCallableSymbol:d}),b=new Map,S=new Map,y=v=>{let C=b.get(v);if(C!==void 0)return C;let R=Ue(e,v);return b.set(v,R),R},x=v=>{let C=S.get(v);if(C!==void 0)return C;let R=q(v);return S.set(v,R),R};for(let v of h){let C=v.relativePath;if(e.isIgnored(C)||a&&y(C)||!LF(v,{requireFunctionLikeSymbol:u,requireCallableSymbol:d})||s!==void 0&&v.symbol===s)continue;let R=ee(v);R<i||R>o||c&&PF(C)||l&&Fe(e,v.symbol,C)||m&&He(v.symbol)||x(C)!=="test"&&(ci(v.symbol)||!p&&Os(e,C,v.startLine)||g.push(v))}return f?g.sort((v,C)=>ee(C)-ee(v)):g}function wF(e,t){return t.files!==void 0?[...new Set(t.files.map(r=>r.replace(/\\/g,"/")))].sort().filter(r=>!t.scope||r.includes(t.scope)).flatMap(r=>U(e,r)):t.requireCallableSymbol?no(e,{scope:t.scope,symbolMatches:Xe,sqlPrefilter:"callable"}):t.requireFunctionLikeSymbol?no(e,{scope:t.scope,symbolMatches:Se,sqlPrefilter:"function-like"}):Ff(e,t.scope)}function LF(e,t){return t.requireCallableSymbol?Xe(e.symbol):t.requireFunctionLikeSymbol?Se(e.symbol):e.isFunctionLike}function PF(e){return(e.split("/").pop()??"").includes("types")}import{statSync as DF}from"fs";function _r(e){let t=e.get("SELECT COUNT(*) as c FROM documents").c,n=e.get("SELECT COUNT(*) as c FROM global_symbols").c,r=e.get("SELECT COUNT(*) as c FROM mentions WHERE role = 1").c,i=e.get("SELECT COUNT(*) as c FROM mentions WHERE role != 1").c;return{documents:t,symbols:n,definitions:r,references:i,...MF(e.generation.databasePath)}}function MF(e){try{let t=DF(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function TF(e,t){return Ul(e).filter(n=>AF({pattern:t,relativePath:n})).map(n=>({relativePath:n}))}function AF(e,t){let n=typeof e=="string"?{pattern:e,relativePath:t}:e;if(typeof n.pattern!="string"||typeof n.relativePath!="string")throw new TypeError("pathMatchesGlob requires pattern and relativePath.");let r=mn(n.pattern),i=mn(n.relativePath);if(!/[*?]/.test(r))return i.includes(r);let o=r.includes("/")?r:`**/${r}`;return Ja(o.split("/"),i.split("/"))}function Ja(e,t){if(e.length===0)return t.length===0;let[n,...r]=e;return n==="**"?Ja(r,t)||t.length>0&&Ja(e,t.slice(1)):t.length===0||!FF(n??"",t[0]??"")?!1:Ja(r,t.slice(1))}function FF(e,t){let n="^";for(let r of e)r==="*"?n+="[^/]*":r==="?"?n+="[^/]":n+=kF(r);return n+="$",new RegExp(n).test(t)}function kF(e){return/[\\^$.*+?()[\]{}|]/.test(e)?`\\${e}`:e}function oS(e,t,n){let r=[],i=[],o=new Map;for(let s of[...e].sort(n)){let a=s.channel??"default",c=t[a]??Number.MAX_SAFE_INTEGER,l=o.get(a)??0;if(l>=c){i.push(s);continue}r.push(s),o.set(a,l+1)}return{selected:r,omitted:i}}function Xa(e,t,n,r,i=!1){let o=[...e],s=[],a=new Set,c=0;for(;o.length>0&&s.length<t;){let l=o.filter(m=>c+m.evidenceCharacters<=n||i&&s.length===0);if(l.length===0)break;let u=l.filter(m=>m.roles.includes("location")||m.roles.includes("definition")).sort(r);l.sort((m,p)=>iS(p,a)-iS(m,a)||r(m,p));let d=u[0]??l[0];s.push(d),c+=d.evidenceCharacters;for(let m of sS(d))a.add(m.key);o.splice(o.indexOf(d),1)}return{selected:s,omitted:o.sort(r)}}function iS(e,t){let n=sS(e).reduce((o,s)=>o+(t.has(s.key)?0:s.weight),0),r=Math.max(0,8-e.priority)*20,i=Math.min(500,Math.ceil(e.evidenceCharacters/160));return n+r-i}function sS(e){return[...e.reasons.map(NF),...e.roles.map(t=>({key:`role:${t}`,weight:_F(t)})),{key:`file:${e.relativePath}`,weight:180},{key:`scope:${OF(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 NF(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 _F(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 OF(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}var aS=64,cS=12;function Qa(e,t,n={}){if(t.length===0)return[];let r=n.context??6;if(!Number.isSafeInteger(r)||r<0)throw new RangeError(`context must be a non-negative safe integer; received ${r}`);let i=n.limit??12;if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`limit must be a positive safe integer; received ${i}`);let o=t.map(s=>{if(s.length===0)throw new Error("The source search pattern must not be empty.");return{pattern:s,regexp:n.regexp?kr(s,"source search pattern",n.ignoreCase?"iu":"u"):null,literal:n.ignoreCase?s.toLocaleLowerCase():s,identities:[],fileCoverage:[],textByPath:new Map}});if(!n.regexp&&!n.ignoreCase){let s=o.map(c=>Buffer.from(c.pattern,"utf8")),a=ia(e,{scope:n.scope,literalBytes:s.length===1?s[0]:s},(c,l)=>{let u=_n(c.text);if(u.length!==0)for(let d of l){let m=o[d];m&&lS(e,m,c,u,n)}});return o.map(c=>uS(c,a,r,i,n))}return o.map(s=>{let a=ia(e,{scope:n.scope},c=>{let l=_n(c.text);l.length>0&&lS(e,s,c,l,n)});return uS(s,a,r,i,n)})}function lS(e,t,n,r,i){let o=[];for(let l=0;l<r.length;l+=1){let u=r[l]??"",d=u.endsWith("\r")?u.slice(0,-1):u;(t.regexp?t.regexp.test(d):(i.ignoreCase?d.toLocaleLowerCase():d).includes(t.literal))&&o.push(l)}if(o.length===0)return;let s=n.relativePath;t.textByPath.set(s,n.text);let a=n.freshness.semantic.state!=="stale"&&n.freshness.semantic.basis!=="no-compiler-document"?U(e,s):[],c=K(e,s)?.callables??[];for(let l of o){let u=Oe(a,l),d=On(c,l),m=u&&!pe(u.symbol)?u:null,p=m?.startLine??d?.startLine??u?.startLine??l,f=m?.endLine??d?.endLine??u?.endLine??l,g=ho(e,s,l,p,f);t.identities.push({relativePath:s,focusLine:l,ownerSymbol:m?.symbol??null,ownerShort:m?T(m.symbol):d?.name??(u?T(u.symbol):null),ownerStartLine:g.startLine,ownerEndLine:g.endLine,fileKind:q(s),freshness:n.freshness})}t.fileCoverage.push({relativePath:s,matchingLines:o.length,returnedMatches:0,freshness:n.freshness})}function uS(e,t,n,r,i){e.identities.sort(mS);let o=e.identities.length>aS?dS(e.identities,aS):e.identities,a=(r===Number.MAX_SAFE_INTEGER?e.identities:i.ranking?dS(e.identities,r):e.identities.slice(0,r)).flatMap(u=>{let d=e.textByPath.get(u.relativePath),m=d===void 0?null:BF(u.relativePath,d,u.focusLine,n);return m?[{...m,...u}]:[]}),c=new Map;for(let u of a)c.set(u.relativePath,(c.get(u.relativePath)??0)+1);for(let u of e.fileCoverage)u.returnedMatches=c.get(u.relativePath)??0;let l=$F(e.fileCoverage);return{pattern:e.pattern,mode:i.regexp?"regexp":"literal",identities:e.identities,...o.length<e.identities.length?{identityManifest:o}:{},identityCoverage:{mode:o.length===e.identities.length?"complete":"bounded",returned:o.length,total:e.identities.length,omitted:e.identities.length-o.length},matches:a,matchingLines:e.identities.length,matchingFiles:e.fileCoverage.length,omittedMatches:Math.max(0,e.identities.length-a.length),fileCoverage:e.fileCoverage,scopeHints:l.slice(0,cS),omittedScopeHints:Math.max(0,l.length-cS),scannedFiles:t.scannedTextFiles,textCoverage:{basis:"current-project-text-files",candidateFiles:t.candidateFiles,scannedTextFiles:t.scannedTextFiles,scannedBytes:t.scannedBytes,skippedBinaryPaths:t.skippedBinaryPaths,skippedUnreadablePaths:t.skippedUnreadablePaths,skippedOversizedPaths:t.skippedOversizedPaths,semanticFiles:t.semanticFiles}}}function BF(e,t,n,r){let i=t.split(`
63
- `),o=t.endsWith(`
64
- `)?i.length-1:i.length;if(n<0||n>=o)return null;let s=Math.max(0,n-r),a=Math.min(o-1,n+r);return{relativePath:e,startLine:s,endLine:a,focusLine:n,source:i.slice(s,a+1).join(`
65
- `)}}function $F(e){let t=new Map;for(let n of e){let r=jF(n.relativePath),i=t.get(r)??{matchingLines:0,matchingFiles:0};i.matchingLines+=n.matchingLines,i.matchingFiles+=1,t.set(r,i)}return[...t.entries()].map(([n,r])=>({scope:n,...r})).sort((n,r)=>r.matchingLines-n.matchingLines||r.matchingFiles-n.matchingFiles||n.scope.localeCompare(r.scope))}function jF(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}function dS(e,t){let n=e.map((i,o)=>({...i,priority:Re(i.fileKind),sequence:o,evidenceCharacters:1,roles:["search"],reasons:["search"],symbols:i.ownerSymbol?[i.ownerSymbol]:[],behaviorSignals:[]})),r=[];for(let i of[0,1,2]){let o=t-r.length;if(o===0)break;let s=n.filter(a=>Re(a.fileKind)===i);r.push(...Xa(s,o,Number.MAX_SAFE_INTEGER,mS).selected)}return r.map(({priority:i,sequence:o,evidenceCharacters:s,roles:a,reasons:c,symbols:l,behaviorSignals:u,...d})=>d)}function mS(e,t){return Re(e.fileKind)-Re(t.fileKind)||+(t.ownerSymbol!==null)-+(e.ownerSymbol!==null)||e.relativePath.localeCompare(t.relativePath)||e.focusLine-t.focusLine}function HF(e,t,n={}){if(t.length===0)throw new Error("The source search pattern must not be empty.");return Qa(e,[t],n)[0]}function Za(e,t){return ee(e)-ee(t)||e.relativePath.localeCompare(t.relativePath)}function he(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function Mi(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}`;t.has(i)||(t.add(i),n.push(r))}return n}function ke(e){return[...new Set((e??[]).map(t=>t.trim()).filter(Boolean))]}function qe(e){return e.replace(/^#/u,"").replace(/\(\)$/u,"")}var pS=new WeakMap,fS=new WeakMap,gS=new WeakMap,hS=new WeakMap,yS=new WeakMap;function bS(e,t){let n=fS.get(e);n||(n=new Map,fS.set(e,n));let r=n.get(t);if(r)return r;let i=J(e,t)?.rootNode;if(!i)return n.set(t,[]),[];let o=new Set;Zt(i,l=>{if(l.type!=="call_expression")return;let u=l.childForFieldName("function")??l.namedChild(0),d=/^([A-Za-z_$][\w$]*(?:\.Service)?)\.of$/u.exec(u?.text.replace(/\s+/gu,"")??"");d&&o.add(d[1])});let s=ae(e,t).filter(l=>!!l.sourcePath),a=new Set;for(let l of o){let u=/^([A-Za-z_$][\w$]*)\.Service$/u.exec(l);if(u){for(let d of s)d.localName===u[1]&&a.add(d.sourcePath);continue}if(l==="Service"){U(e,t).some(d=>d.leaf==="Service")&&a.add(t);for(let d of s)(d.localName??d.importedName)==="Service"&&a.add(d.sourcePath)}}let c=yd([...a]).sort();return n.set(t,c),c}function rr(e,t,n={}){let i=zt(e,t)?.filter(p=>!n.ranges||n.ranges.some(f=>p.line>=f.startLine&&p.line<=f.endLine));if(!i)return{targets:[],unresolvedCallsites:0};let o=ae(e,t).filter(p=>!!p.sourcePath),s=ik(W(e,t)??""),a=J(e,t)?.rootNode??null,c=a?qF(a):SS(),l=new Map,u=Kt(e),d=[],m=0;for(let p of i){if(!p.memberAccess)continue;let f=Ot(t,u.get(p.calleeLeaf)??[]);if(n.excludeIndexedTargets!==!1&&Hn(e,t,f,!0,p.calleeQualifier))continue;let g=p.calleeQualifier,h=nk(e,t,p,o);if(h){d.push(h);continue}let b=UF(e,t,p,o,GF(c,p.calleeQualifier,p.line));if(b.length>0){d.push(...b);continue}let S=zF(e,t,p);if(S.length>0){d.push(...S);continue}let y=g?s.get(g)??g:null,v=(y?yd(o.filter(R=>(R.localName??R.importedName)===y).map(R=>R.sourcePath)):[]).flatMap(R=>{let E=l.get(R);return E||(E=It(e,R)??[],l.set(R,E)),E.filter(I=>I.name===p.calleeLeaf).map(I=>({file:R,callable:I}))});if(v.length!==1){m+=1;continue}let C=v[0];d.push({calleeLeaf:p.calleeLeaf,line:p.line,sourceFile:t,targetFile:C.file,targetStartLine:C.callable.startLine,targetEndLine:C.callable.endLine,resolution:"direct-import-receiver",strength:"candidate"})}return{targets:d,unresolvedCallsites:m}}function UF(e,t,n,r,i){let o=n.calleeQualifier;if(!o||!/^[A-Za-z_$][\w$]*$/u.test(o))return[];if(i.size!==1)return[];let s=[...i][0],a=yd(r.filter(u=>u.localName===s||u.importedName===s).map(u=>u.sourcePath));if(a.length!==1)return[];let c=a[0],l=YF(e,c,n.calleeLeaf);return l.map(u=>({calleeLeaf:u.name,line:n.line,sourceFile:t,targetFile:u.file,targetStartLine:u.startLine,targetEndLine:u.endLine,serviceFile:c,resolutionAlternativeCount:l.length,resolution:"imported-service-object-member",strength:"candidate"}))}function SS(){return{declarations:new Map,callbacks:[]}}function qF(e){let t=SS();return Zt(e,n=>{if(n.type==="variable_declarator"){let c=n.childForFieldName("name")??n.namedChild(0),l=n.childForFieldName("value")??n.namedChild(1);if(c?.type!=="identifier"||!l)return;let u=new Set;if(Zt(l,d=>{if(d.type!=="member_expression")return;let m=d.childForFieldName("object")??d.namedChild(0),p=d.childForFieldName("property")??d.namedChild(1);m?.type==="identifier"&&p?.text==="Service"&&u.add(m.text)}),u.size===1){let d=t.declarations.get(c.text)??[];d.push({line:n.startPosition.row,alias:[...u][0]}),t.declarations.set(c.text,d)}return}if(!["arrow_function","function_expression","generator_function"].includes(n.type))return;let r=n.childForFieldName("parameters")??n.childForFieldName("parameter");if(!r)return;let i=n.parent;for(;i&&i.type!=="call_expression";)i=i.parent;if(!i)return;let o=i.childForFieldName("function")??i.namedChild(0),s=/^([A-Za-z_$][\w$]*)\.Service\.use$/u.exec(o?.text??"");if(!s)return;let a=new Set;Zt(r,c=>{c.type==="identifier"&&a.add(c.text)}),a.size!==0&&t.callbacks.push({startLine:n.startPosition.row,endLine:n.endPosition.row,receivers:a,alias:s[1]})}),t}function GF(e,t,n){if(!t||!/^[A-Za-z_$][\w$]*$/u.test(t))return new Set;let r=new Set((e.declarations.get(t)??[]).filter(i=>i.line<=n).map(i=>i.alias));for(let i of e.callbacks)i.startLine<=n&&i.endLine>=n&&i.receivers.has(t)&&r.add(i.alias);return r}function zF(e,t,n){let r=n.calleeQualifier;if(!r||!/^[A-Za-z_$][\w$]*$/u.test(r))return[];let i=J(e,t)?.rootNode;if(!i)return[];let o=KF(e,t,i,n.line,n.calleeLeaf,r),s=o?VF(o,r):null;if(!s)return[];if(!WF(s))return[];let a=(It(e,t)??[]).filter(p=>p.startLine<=s.startPosition.row&&p.endLine>=s.endPosition.row).sort((p,f)=>p.endLine-p.startLine-(f.endLine-f.startLine))[0];if(!a)return[];let c=U(e,t).filter(p=>p.isFunctionLike&&p.leaf===a.name);if(c.length!==1)return[];let l=c[0],u=hS.get(e);u||(u=new Map,hS.set(e,u));let d=`${l.symbol}\0${n.calleeLeaf}`,m=u.get(d);if(!m){let p=[];for(let f of ro(e,l)){let g=J(e,f.file)?.rootNode;if(!g)continue;let h=$s(g,"call_expression").filter(y=>y.startPosition.row>f.line||y.endPosition.row<f.line?!1:(y.childForFieldName("function")??y.namedChild(0))?.text.replace(/\s+/gu,"").replace(/<[^<>]*>$/u,"").match(/[A-Za-z_$][\w$]*$/u)?.[0]===l.leaf);if(h.length!==1)continue;let S=h[0].childForFieldName("arguments")?.namedChildren.find(y=>Or(y).type==="object");if(S)for(let y of Or(S).namedChildren){if(y.type==="shorthand_property_identifier"&&y.text===n.calleeLeaf){p.push(...ec(e,f.file,n.calleeLeaf,y,y));continue}if(y.type!=="pair")continue;let x=y.childForFieldName("key")??y.namedChild(0),v=y.childForFieldName("value")??y.namedChild(1);tc(x?.text)!==n.calleeLeaf||!v||p.push(...ec(e,f.file,n.calleeLeaf,v,y))}}m=p.filter((f,g,h)=>h.findIndex(b=>b.file===f.file&&b.startLine===f.startLine&&b.endLine===f.endLine&&b.name===f.name)===g),u.set(d,m)}return m.map(p=>({calleeLeaf:p.name,line:n.line,sourceFile:t,targetFile:p.file,targetStartLine:p.startLine,targetEndLine:p.endLine,resolutionAlternativeCount:m.length,resolution:"factory-callback-member",strength:m.length===1?"exact":"candidate"}))}function KF(e,t,n,r,i,o){let s=gS.get(e);s||(s=new Map,gS.set(e,s));let a=s.get(t);if(!a){a=new Map;for(let c of $s(n,"call_expression")){let l=c.childForFieldName("function")??c.namedChild(0),u=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(l?.text.replace(/\s+/gu,"")??"");if(u)for(let d=c.startPosition.row;d<=c.endPosition.row;d+=1){let m=`${d}\0${u[1]}\0${u[2]}`,p=a.get(m);(!p||c.endIndex-c.startIndex<p.endIndex-p.startIndex)&&a.set(m,c)}}s.set(t,a)}return a.get(`${r}\0${o}\0${i}`)??null}function WF(e){return e.descendantsOfType("return_statement").some(t=>{let n=t.childForFieldName("argument")??t.namedChild(0);return!!(n&&Or(n).type==="object")})}function VF(e,t){let n=e.parent;for(;n;){if(/(?:function|method|lambda)/u.test(n.type)||n.type==="arrow_function"){let r=n.childForFieldName("parameters")??n.childForFieldName("parameter"),i=!1;if(r&&Zt(r,o=>{o.type==="identifier"&&o.text===t&&(i=!0)}),i)return n}n=n.parent}return null}function ec(e,t,n,r,i){if(r.type==="identifier")return(It(e,t)??[]).filter(c=>c.name===r.text).map(c=>({...c,file:t}));let o=gd(e,t,r.text);if(o.length>0)return o;if(!hd(r))return[];let a=(It(e,t)??[]).filter(c=>c.startLine>=i.startPosition.row&&c.endLine<=i.endPosition.row&&(c.name===n||c.name.startsWith("source@"))).sort((c,l)=>c.endLine-c.startLine-(l.endLine-l.startLine))[0];return[a?{...a,file:t}:{name:n,file:t,startLine:i.startPosition.row,endLine:i.endPosition.row}]}function YF(e,t,n){let r=yS.get(e);r||(r=new Map,yS.set(e,r));let i=`${t}\0${n}`,o=r.get(i);if(o)return o;let s=QF(e,t).flatMap(a=>JF(e,a,t,n));return r.set(i,s),s}function JF(e,t,n,r){let i=J(e,t)?.rootNode,o=It(e,t)??[];if(!i)return[];let s=ZF(e,t,n);if(s.size===0)return[];let a=new Set,c=[],l=[],u=[];return Zt(i,m=>{if(XF(m,s)){if(m.type==="pair"){let p=m.childForFieldName("key")??m.namedChild(0),f=m.childForFieldName("value")??m.namedChild(1);if(tc(p?.text)!==r||!f)return;if(f.type==="identifier")a.add(f.text);else if(hd(f))c.push({name:r,startLine:m.startPosition.row,endLine:m.endPosition.row});else{let g=ek(e,t,f.text),h=gd(e,t,f.text);if(g.length>0)u.push(...g);else if(h.length>0)u.push(...h);else{let b=tk(m);b&&l.push(b)}}return}m.type==="shorthand_property_identifier"&&m.text===r&&a.add(r)}}),[...o.filter(m=>a.has(m.name)).map(m=>({...m,file:t})),...c.map(m=>({...m,file:t})),...l.map(m=>({...m,file:t})),...u].filter((m,p,f)=>f.findIndex(g=>g.file===m.file&&g.name===m.name&&g.startLine===m.startLine&&g.endLine===m.endLine)===p)}function XF(e,t){let n=e,r=null;for(;n;){if(n.type==="object"&&(r=n),n.type==="call_expression"){if(!r)return!1;let i=n.childForFieldName("function")??n.namedChild(0);return i?t.has(i.text.replace(/\.of$/u,""))&&i.text.endsWith(".of"):!1}n=n.parent}return!1}function QF(e,t){let n=pS.get(e);n||(n=new Map,pS.set(e,n));let r=n.get(t);if(r)return r;let i=new Set([t]),o=U(e,t).filter(a=>a.leaf==="Service"&&a.isTypeLike);for(let a of o)for(let c of ro(e,a))i.add(c.file);let s=[...i].sort();return n.set(t,s),s}function ZF(e,t,n){let r=new Set;_e(t,n)&&r.add("Service");for(let i of ae(e,t)){if(!i.sourcePath||!_e(i.sourcePath,n))continue;if(i.kind==="namespace"&&i.localName){r.add(`${i.localName}.Service`);continue}(i.importedName==="default"?i.localName:i.importedName)==="Service"?r.add(i.localName??i.importedName):i.localName&&i.importedName!=="default"&&r.add(`${i.localName}.Service`)}return r}function gd(e,t,n){let r=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(n.replace(/\s+/gu,""));if(!r)return[];let i=J(e,t)?.rootNode;if(!i)return[];let o=vS(i,r[1]),s=o?CS(o):null;if(!s)return[];let a=s.childForFieldName("function")??s.namedChild(0),c=a?xS(e,t,a.text):[];if(c.length!==1)return[];let l=c[0],u=J(e,l.relativePath)?.rootNode;if(!u)return[];let d=Ml(u,l.startLine,l.endLine);if(!d)return[];let m=[];for(let p of d.descendantsOfType("return_statement")){let f=p.childForFieldName("argument")??p.namedChild(0);if(!f)continue;let g=Or(f);if(g.type==="object")for(let h of g.namedChildren){if(h.type==="shorthand_property_identifier"&&h.text===r[2]){for(let y of It(e,l.relativePath)??[])y.name===r[2]&&m.push({...y,file:l.relativePath});continue}if(h.type!=="pair")continue;let b=h.childForFieldName("key")??h.namedChild(0),S=h.childForFieldName("value")??h.namedChild(1);if(!(tc(b?.text)!==r[2]||!S))if(S.type==="identifier")for(let y of It(e,l.relativePath)??[])y.name===S.text&&m.push({...y,file:l.relativePath});else hd(S)&&m.push({name:r[2],startLine:h.startPosition.row,endLine:h.endPosition.row,file:l.relativePath})}}return m.filter((p,f,g)=>g.findIndex(h=>h.file===p.file&&h.name===p.name&&h.startLine===p.startLine&&h.endLine===p.endLine)===f)}function ek(e,t,n){let r=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(n.replace(/\s+/gu,""));if(!r)return[];let i=J(e,t)?.rootNode;if(!i)return[];let o=vS(i,r[1]),s=o?CS(o):null,a=s?.childForFieldName("function")??s?.namedChild(0),c=a?xS(e,t,a.text):[];if(c.length!==1||!s)return[];let l=c[0],u=J(e,l.relativePath)?.rootNode;if(!u)return[];let d=Ml(u,l.startLine,l.endLine);if(!d)return[];let m=new Set,p=d.childForFieldName("parameters")??d.childForFieldName("parameter");if(p&&Zt(p,R=>{R.type==="identifier"&&m.add(R.text)}),m.size===0)return[];let f=gd(e,t,n);if(f.length===0)return[];let g=(It(e,l.relativePath)??[]).filter(R=>R.startLine>=l.startLine&&R.endLine<=l.endLine),h=(zt(e,l.relativePath)??[]).filter(R=>R.line>=l.startLine&&R.line<=l.endLine),b=new Set,S=f.map(R=>({name:R.name,startLine:R.startLine,endLine:R.endLine})),y=new Set;for(;S.length>0&&y.size<32;){let R=S.shift(),E=`${R.name}\0${R.startLine}\0${R.endLine}`;if(!y.has(E)){y.add(E);for(let I of h.filter(w=>w.line>=R.startLine&&w.line<=R.endLine)){if(I.memberAccess&&I.calleeQualifier&&m.has(I.calleeQualifier)){b.add(I.calleeLeaf);continue}if(I.memberAccess)continue;let w=g.filter(A=>A.name===I.calleeLeaf);w.length===1&&S.push(w[0])}}}if(b.size===0)return[];let v=s.childForFieldName("arguments")?.namedChildren.find(R=>Or(R).type==="object");if(!v)return[];let C=[];for(let R of Or(v).namedChildren){if(R.type==="shorthand_property_identifier"&&b.has(R.text)){C.push(...ec(e,t,R.text,R,R));continue}if(R.type!=="pair")continue;let E=R.childForFieldName("key")??R.namedChild(0),I=R.childForFieldName("value")??R.namedChild(1),w=tc(E?.text);!w||!b.has(w)||!I||C.push(...ec(e,t,w,I,R))}return C.filter((R,E,I)=>I.findIndex(w=>w.file===R.file&&w.name===R.name&&w.startLine===R.startLine&&w.endLine===R.endLine)===E)}function vS(e,t){for(let n of $s(e,"variable_declarator"))if((n.childForFieldName("name")??n.namedChild(0))?.text===t)return n.childForFieldName("value")??n.namedChild(1);return null}function CS(e){return e.type==="call_expression"?e:e.descendantsOfType("call_expression")[0]??null}function xS(e,t,n){let r=n.replace(/\s+/gu,"").replace(/<[^<>]*>$/u,""),i=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(r);if(i){let d=ae(e,t).filter(f=>f.localName===i[1]&&f.sourcePath);if(d.length!==1||!d[0].sourcePath)return[];let m=d[0].sourcePath,p=jn(e,m,i[2]).filter(f=>f.isFunctionLike);return p.length>0?p:(It(e,m)??[]).filter(f=>f.name===i[2]).map(f=>({...f,relativePath:m}))}if(!/^[A-Za-z_$][\w$]*$/u.test(r))return[];let o=U(e,t).filter(d=>d.leaf===r&&d.isFunctionLike);if(o.length>0)return o;let s=(It(e,t)??[]).filter(d=>d.name===r).map(d=>({...d,relativePath:t}));if(s.length>0)return s;let a=ae(e,t).filter(d=>d.localName===r&&d.sourcePath&&d.kind!=="namespace");if(a.length!==1||!a[0].sourcePath)return[];let c=a[0].sourcePath,l=a[0].importedName==="default"?r:a[0].importedName,u=jn(e,c,l).filter(d=>d.isFunctionLike);return u.length>0?u:(It(e,c)??[]).filter(d=>d.name===l).map(d=>({...d,relativePath:c}))}function hd(e){return["arrow_function","function_expression","generator_function"].includes(e.type)||e.descendantsOfType(["arrow_function","function_expression","generator_function"]).length>0}function tk(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 tc(e){return e?e.replace(/^(?:['"])(.*)(?:['"])$/u,"$1"):null}function nk(e,t,n,r){let i=/^this\.([A-Za-z_$][\w$]*)$/u.exec(n.calleeQualifier??"");if(!i)return null;let o=J(e,t)?.rootNode;if(!o)return null;let s=rk(o,n.line);if(!s)return null;let a=new Set;if(Zt(s,g=>{if(g.type!=="assignment_expression")return;let h=g.childForFieldName("left")??g.namedChild(0),b=g.childForFieldName("right")??g.namedChild(g.namedChildCount-1);if(h?.text.replace(/\s+/gu,"")!==`this.${i[1]}`||!b)return;let S=Or(b);if(S.type!=="new_expression")return;let x=(S.childForFieldName("constructor")??S.namedChild(0))?.text.match(/[A-Za-z_$][\w$]*$/u)?.[0];x&&a.add(x)}),a.size!==1)return null;let c=[...a][0],l=r.filter(g=>g.localName===c);if(l.length!==1)return null;let u=l[0].importedName==="default"?c:l[0].importedName,d=l[0].importedName==="default"?jn(e,l[0].sourcePath,c):[],m=d.length===1?d[0].leaf:u,p=U(e,l[0].sourcePath).filter(g=>g.isFunctionLike&&g.leaf===n.calleeLeaf&&Pf(g.symbol)===m);if(p.length!==1)return null;let f=p[0];return{calleeLeaf:n.calleeLeaf,line:n.line,sourceFile:t,targetFile:f.relativePath,targetStartLine:f.startLine,targetEndLine:f.endLine,targetSymbol:f.symbol,resolution:"constructed-member-receiver",strength:"exact"}}function rk(e,t){let n=[];return Zt(e,r=>{["class","class_declaration","class_definition"].includes(r.type)&&r.startPosition.row<=t&&r.endPosition.row>=t&&n.push(r)}),n.sort((r,i)=>r.endPosition.row-r.startPosition.row-(i.endPosition.row-i.startPosition.row))[0]??null}function Or(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 Zt(e,t){t(e);for(let n of e.namedChildren)Zt(n,t)}function ik(e){let t=new Map,n=/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*([A-Za-z_$][\w$]*)\s*;/gu;for(let r of e.matchAll(n)){let i=r[1],o=r[2];i&&o&&t.set(i,o)}return t}function yd(e){let t=[];for(let n of e)t.some(r=>_e(r,n))||t.push(n);return t}import{existsSync as sk}from"fs";import{SymbolRole as ak}from"@c4312/scip";import{deserializeSCIP as ok}from"@c4312/scip";function RS(e,t){return ok(ti(e,{inputKind:t,maxBytes:ei}))}var bd=new WeakMap;function In(e,t,n,r){let i=K(e,t),o=(i?.callSites??[]).filter(p=>p.line>=n&&p.line<=r);if(!i||o.length===0)return{available:!!i,targets:[],resolvedCallsites:0,unresolvedCallsites:0};let s=vd(e);if(!s)return{available:!1,targets:[],resolvedCallsites:0,unresolvedCallsites:o.length};let a=(s.byFile.get(t)??[]).filter(p=>p.sourceLine>=n&&p.sourceLine<=r).map(p=>({...p,calleeLeaf:p.definition.leaf})),c=ES(o.map(p=>({line:p.line,leaf:p.calleeLeaf}))),l=ES(a.map(p=>({line:p.sourceLine,leaf:p.calleeLeaf}))),u=new Set([...c].flatMap(([p,f])=>l.get(p)===f?[p]:[])),d=a.filter(p=>u.has(wS(p.sourceLine,p.calleeLeaf))),m=[...u].reduce((p,f)=>p+(c.get(f)??0),0);return{available:!0,targets:d,resolvedCallsites:m,unresolvedCallsites:Math.max(0,o.length-m)}}function Sd(e,t,n,r){let i=vd(e);return i?{available:!0,targets:(i.byFile.get(t)??[]).filter(o=>o.sourceLine>=n&&o.sourceLine<=r)}:{available:!1,targets:[]}}function IS(e,t,n,r){let i=vd(e);return i?{available:!0,targets:(i.byFile.get(t)??[]).filter(o=>o.sourceLine>=n&&o.sourceLine<=r&&nc(e,o.definition)).map(o=>({...o,calleeLeaf:o.definition.leaf}))}:{available:!1,targets:[]}}function vd(e){if(bd.has(e))return bd.get(e)??null;let t=ck(e);return bd.set(e,t),t}function ck(e){if(!e.generation.indexPath||!sk(e.generation.indexPath))return null;try{let t=ve(e),n=new Map(t.map(o=>[o.symbol,o])),r=RS(e.generation.indexPath,"SCIP source-range call-target index"),i=new Map;for(let o of r.documents??[]){let s=o.relativePath;if(!s||e.isIgnored(s))continue;let a=[];for(let c of o.occurrences??[]){if(!c.symbol||(c.symbolRoles&ak.Definition)!==0)continue;let l=n.get(c.symbol),u=c.range?.[0];!l||!Number.isInteger(u)||a.push({sourceLine:u,definition:l})}i.set(s,a)}return{byFile:i}}catch{return null}}function nc(e,t){if(!t.isFunctionLike)return!1;let n=K(e,t.relativePath);return!n||n.callables.some(r=>r.name===t.leaf&&r.startLine===t.startLine&&r.endLine===t.endLine)?!0:lk(t)}function lk(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 ES(e){let t=new Map;for(let n of e){let r=wS(n.line,n.leaf);t.set(r,(t.get(r)??0)+1)}return t}function wS(e,t){return`${e}\0${t}`}function Cd(e,t,n={}){let r=new Map;if(t&&t.length===0)return r;let i=Q(e,{includeIgnored:!1}),o=Kt(e),s=t??ve(e),a=new Set(s.map(l=>l.symbolId)),c=hk(s);return uk(e,r,i,o,a,c),dk(e,r,s,a),gk(e,r,i,o,a,c),n.semantic!==!1&&n.semanticEvidence&&bk(r,n.semanticEvidence.callerMap(e,yk(s))),r}function uk(e,t,n,r,i,o){for(let s of n){if(!se(s))continue;let a=zt(e,s);if(a)for(let c of a){if(o&&!o.has(c.calleeLeaf))continue;let l=Ot(s,r.get(c.calleeLeaf)??[]);if(!l||l.length===0)continue;let u=Hn(e,s,l,c.memberAccess,c.calleeQualifier);u&&i.has(u.symbolId)&&u.file!==s&&xd(t,u.symbolId,s)}}}function dk(e,t,n,r){let i=pk(n);for(let o of mk(e,r))e.isIgnored(o.relative_path)||fk(o,i.get(o.symbol_id))||xd(t,o.symbol_id,o.relative_path)}function mk(e,t){return zs(e,t?[...t]:void 0)}function pk(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 fk(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function gk(e,t,n,r,i,o){for(let s of n){if(se(s)!=="rust")continue;let a=si(e,s,{includeRustAttributeNames:!0});if(a.length!==0)for(let{name:c}of a){if(o&&!o.has(c))continue;let l=r.get(c);if(l)for(let u of l)i.has(u.symbolId)&&u.file!==s&&xd(t,u.symbolId,s)}}}function xd(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function hk(e){let t=new Set;for(let n of e){let r="leaf"in n&&typeof n.leaf=="string"?n.leaf:"symbol"in n&&typeof n.symbol=="string"?z(n.symbol):"";r&&t.add(r)}return t.size>0?t:null}function yk(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function bk(e,t){for(let[n,r]of t){let i=e.get(n);i||(i=new Set,e.set(n,i));for(let o of r)i.add(o)}}var Sk=me("cross-file-caller-files",{clearGroups:["whole-project","source-file"]}),vk=me("source-fallback-caller-files",{clearGroups:["whole-project","source-file"]});function LS(e,t,n){let r=t.filter(o=>!e.has(o.symbolId));if(r.length>0){let o=n(r);for(let s of r)e.set(s.symbolId,o.get(s.symbolId)??new Set)}let i=new Map;for(let o of t){let s=e.get(o.symbolId);s&&s.size>0&&i.set(o.symbolId,new Set(s))}return i}function Rd(e,t,n={}){if(t===void 0)return Cd(e,t,n);let r=LS(Sk.get(e,()=>new Map),t,i=>Cd(e,i,{semantic:!1}));return n.semantic===!1||!n.semanticEvidence?r:en(r,n.semanticEvidence.callerMap(e,t.filter(i=>"relativePath"in i&&"symbol"in i&&"leaf"in i)))}function No(e,t,n={}){return n.skipPath?kl(e,t,n):LS(vk.get(e,()=>new Map),t,r=>kl(e,r))}function PS(e,t,n={}){let r=Rd(e,t,{semantic:n.semantic,semanticEvidence:n.semanticEvidence});return n.sourceFallback===!1?r:en(r,No(e,t))}function en(e,t){let n=new Map;for(let[r,i]of e)n.set(r,new Set(i));for(let[r,i]of t){let o=n.get(r)??new Set;for(let s of i)o.add(s);n.set(r,o)}return n}function DS(e,t,n){let r=t.identifierResolution==="strict"?Fl:qf,i=t.candidateNames?jf(t.candidateNames):null,o=0,s=0,a=0,c=0,l="";for(let u of t.paths)if(o+=1,l=u,!(!se(u)&&!(t.includeVueSfc&&xf(u)))&&!e.isIgnored(u)&&!t.skipPath?.(u))try{if(i&&!Hf(W(e,u),i))continue;s+=1;let m=(f,g,h,b)=>{if(t.candidateNames&&!t.candidateNames.has(f))return;a+=1;let S=t.resolveTargets?t.resolveTargets({sourceFile:u,name:f,kind:g,defaultTargets:b}):b();for(let y of S)c+=1,n({sourceFile:u,name:f,target:y,occurrences:h,kind:g})},p=di(e,u);for(let[f,g]of p)m(f,"identifier",g.length,()=>r(e,u,f));for(let f of si(e,u,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let g=f.kind==="cross-language-dispatch"?()=>Fl(e,u,f.name):()=>r(e,u,f.name);m(f.name,f.kind,f.occurrences,g)}}finally{t.afterPath?.(u),o%10===0&&N("source-reference-scan.progress",()=>{},()=>({scannedPaths:o,currentPath:l,candidateMatchedPaths:s,visitedNames:a,visitedHits:c}))}}var H=class{constructor(t){this.db=t}db;scopedDefinitions(t){return Af(this.db,t)}definitionsForFile(t){return U(this.db,t)}productionCallableDefinitions(t={}){return Ya(this.db,t)}calleeMap(t,n={}){return Lr(this.db,t,{...n,semanticEvidence:re})}crossFileCallerMap(t,n={}){return Rd(this.db,t,{...n,semanticEvidence:re})}sourceFallbackCallerFiles(t,n={}){return No(this.db,t,n)}callerFileMap(t,n={}){return PS(this.db,t,{...n,semanticEvidence:re})}frameworkReferencedSymbolIds(t){let n=new Map;for(let i of t){if(!i.leaf)continue;let o=n.get(i.leaf)??[];o.push(i.symbolId),n.set(i.leaf,o)}let r=new Set;for(let i of Q(this.db,{includeIgnored:!1}))if(se(i)==="rust")for(let{name:o}of si(this.db,i,{includeRustAttributeNames:!0}))for(let s of n.get(o)??[])r.add(s);return r}symbolsWithNonSelfCallees(t,n={}){if(t.length===0)return new Set;let r=new Map(t.map(o=>[o.symbolId,o.symbol])),i=this.calleeMap(t,n);return new Set([...i.entries()].filter(([o,s])=>{let a=r.get(o);return s.some(c=>c.symbol!==a)}).map(([o])=>o))}fileDependencyGraph(t){return Ae(this.db,t)}fileKind(t){return q(t)}hasSuppressionComment(t){return Os(this.db,t.relativePath,t.startLine)}sourceFiles(){return oi(this.db)}scanSourceReferences(t,n){DS(this.db,t,n)}callableSignature(t){let n=gn(this.db).forFile(t.relativePath,{facts:!0}).facts?.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};var Ck=16,xk=4,Ed=3e3,Rk=800,Ek=new Set(["assignment","const_declaration","const_item","field_declaration","lexical_declaration","local_declaration_statement","local_variable_declaration","static_item","variable_declaration"]);function NS(e,t,n={}){let r=n.maxSteps??Ck;if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`maxSteps must be a positive safe integer; received ${r}`);let i=new Map(t.nodes.map(M=>[M.id,M])),o=Tk(n.focusLocations??[]),s=new Set,a=new Map(t.edges.map(M=>[M.id,M])),c=wn(t.paths.flatMap(M=>M.nodeIds)),l=wn(t.anchors.filter(M=>M.status==="matched").flatMap(M=>M.nodeIds)),u=t.nodes.filter(M=>M.disposition==="emitted"&&M.attributes.upstreamCausalPath===!0).sort((M,$)=>Number($.attributes.upstreamCausalDistance??0)-Number(M.attributes.upstreamCausalDistance??0)||M.id.localeCompare($.id)).map(M=>M.id),d=new Set(u),m=Math.max(0,r-l.length),f=Ik(t,l,o,m).slice(0,m),g=new Set(f),h=new Set(f),b=new Set([...c,...u,...l]),S=t.edges.filter(M=>M.disposition==="emitted"&&M.kind!=="structural-membership"),y=t.edges.filter(M=>M.disposition!=="excluded"&&M.disposition!=="unsupported"&&M.kind!=="structural-membership"),x=new Set([...t.paths.flatMap(M=>M.edgeIds),...S.filter(M=>d.has(M.fromNodeId)&&d.has(M.toNodeId)).map(M=>M.id)]),v=t.paths.some(M=>M.edgeIds.length>0),C=new Set(l);for(let M of f)C.add(M);for(let M of t.paths){let $=M.nodeIds[0],Y=a.get(M.edgeIds[0]??""),oe=M.nodeIds[1];$&&oe&&Y?.fromNodeId===$&&Y.toNodeId===oe&&C.add($)}if(t.paths.every(M=>M.nodeIds.length===0))for(let M of t.anchors)for(let $ of M.nodeIds)C.add($);let R=_k(l,y,i,xk),E=wn(S.filter(M=>M.kind==="call"&&l.includes(M.fromNodeId)).map(M=>M.toNodeId)),I=new Set(wn([...R,...v?[]:E]));for(let M of I)C.add(M);let w=wn(S.flatMap(M=>b.has(M.fromNodeId)||b.has(M.toNodeId)?[M.fromNodeId,M.toNodeId]:[])),A=t.nodes.filter(M=>M.disposition==="emitted"&&M.kind!=="structural-region"&&S.some($=>$.fromNodeId===M.id||$.toNodeId===M.id)).map(M=>M.id),D=wn([...u,...c,...l,...f,...I,...w,...A]).filter(M=>i.has(M)),k=[];for(let M of D)v&&!b.has(M)&&!g.has(M)&&!I.has(M)||k.length>=r&&!b.has(M)||k.push(M);let L=new Set(k),F=new Map(k.map(M=>[M,Bk(M)])),P=new Set([...c,...u]),j=new Set(t.anchors.flatMap(M=>M.nodeIds)),B=k.map((M,$)=>{let Y=i.get(M),oe=Mk(Y,o);for(let Ne of oe)s.add(Ti(Y.location.file,Ne));return{id:F.get(M),nodeId:M,order:$,role:j.has(M)?"anchor":P.has(M)?"connector":"junction",kind:Y.kind,label:Y.label,location:Y.location,behavior:wk(e,Y,j.has(M),[...new Set([...oe,...Dk(e,Y,y,i,x,C)])],oe,C.has(Y.id)&&(oe.length===0||j.has(Y.id)),I.has(Y.id),h.has(Y.id)&&oe.length===0)}}),X=new Map;for(let M of t.paths)for(let $=0;$<M.edgeIds.length;$+=1){let Y=a.get(M.edgeIds[$]),oe=M.nodeIds[$],Ne=M.nodeIds[$+1];!Y||!oe||!Ne||X.set(Y.id,Y.fromNodeId===oe&&Y.toNodeId===Ne?"forward":"reverse")}let O=y.filter(M=>L.has(M.fromNodeId)&&L.has(M.toNodeId)).sort((M,$)=>Ok(M,$,t)).map((M,$)=>({id:$k(M.id),edgeId:M.id,order:$,kind:M.kind,fromStepId:F.get(M.fromNodeId),toStepId:F.get(M.toNodeId),directed:!0,pathTraversal:X.get(M.id)??"adjacent",evidence:M.evidence})),te=new Map(O.map(M=>[M.edgeId,M.id])),ie=t.paths.map(M=>({id:M.id,status:M.status,stepIds:M.nodeIds.flatMap($=>{let Y=F.get($);return Y?[Y]:[]}),transitionIds:M.edgeIds.flatMap($=>{let Y=te.get($);return Y?[Y]:[]})})),Le=B.flatMap(M=>M.location?[`${M.location.file}:${M.location.line+1}`]:[]),Me=t.anchors.some(M=>M.status==="ambiguous"),Nt=ie.some(M=>M.status==="connected"||M.status==="candidate"),tt=ie.some(M=>M.status==="partial");return{status:B.length===0?"unavailable":Me?"ambiguous":Nt&&!tt?"connected":tt?"partial":"connected",steps:B,transitions:O,paths:ie,coverage:{candidateNodes:D.length,returnedNodes:k.length,omittedNodeIds:D.filter(M=>!L.has(M)),returnedTransitions:O.length,withheldStatements:B.reduce((M,$)=>M+($.behavior?.coverage.omittedStatements??0),0),requestedFocusLocations:o,matchedFocusLocations:o.filter(M=>s.has(Ti(M.file,M.line))),unmatchedFocusLocations:o.filter(M=>!s.has(Ti(M.file,M.line)))},behaviorCommand:kS(Le,"behavior"),exactSourceCommand:kS(Le,"source")}}function Ik(e,t,n,r){if(r<=0||n.length===0)return[];let i=new Set(t),o=new Set(n.map(s=>Ti(s.file,s.line)));return wn(e.edges.filter(s=>s.disposition!=="excluded"&&s.disposition!=="unsupported"&&["call","runtime-boundary"].includes(s.kind)&&i.has(s.fromNodeId)&&s.evidence.some(a=>!["candidate","unknown"].includes(a.strength)&&a.location&&o.has(Ti(a.location.file,a.location.line)))).sort((s,a)=>{let c=s.evidence.find(u=>u.location)?.location,l=a.evidence.find(u=>u.location)?.location;return(c?.file??"").localeCompare(l?.file??"")||(c?.line??Number.MAX_SAFE_INTEGER)-(l?.line??Number.MAX_SAFE_INTEGER)||s.id.localeCompare(a.id)}).map(s=>s.toNodeId)).slice(0,r)}function wk(e,t,n,r,i,o,s,a){if(!t.location||!["symbol","source-construct","runtime-boundary-participant"].includes(t.kind))return null;let c=t.location.endLine??t.location.line,l=V(e,t.location.file),u=r.length>0?r:[t.location.line],d=t.kind==="runtime-boundary-participant"?ot(e,t.location.file,0,Math.max(0,l.length-1),[t.location.line]):ot(e,t.location.file,t.location.line,c,u),m=r.filter(I=>I>=d.startLine&&I<=d.endLine),p=hi(e,t.location.file,d.startLine,d.endLine,m),f=p??(m.length>0?hi(e,t.location.file,d.startLine,d.endLine,m,{requireSavings:!1}):null),g=m.length>0?Ak(e,t,d.startLine,d.endLine,m,f,o):null,h=l.slice(d.startLine,d.endLine+1).join(`
66
- `).length,b=Sn(e,t.location.file,d.startLine,d.endLine),S=l.slice(d.startLine,d.endLine+1).some((I,w)=>I.length>Rk&&(b.get(d.startLine+w)??[]).some(A=>["binding","branch","loop","call","return","throw","mutation"].includes(A))),y=I=>Lk(e,t,d.startLine,d.endLine,i.filter(w=>w>=d.startLine&&w<=d.endLine),I),x=(s||t.kind==="runtime-boundary-participant"||t.anchorIds.length>0)&&h<=Ed,v=n&&(m.length===0||x);if(p&&(a||v))return y(MS(p));if(!a&&!v&&g&&!S&&!x&&g.renderedCharacters<(f?.outlineCharacters??h))return y(g);if(p)return y(MS(p));let C=l.slice(d.startLine,d.endLine+1),R=C.join(`
67
- `),E=Sn(e,t.location.file,d.startLine,d.endLine);return y({kind:"source",constructKind:"source construct",signature:C.find(I=>I.trim().length>0)?.trim()??t.label,lines:C.map((I,w)=>({line:d.startLine+w,endLine:d.startLine+w,depth:0,signals:E.get(d.startLine+w)??[],text:I,copied:!0})),coverage:{sourceStatements:C.length,representedStatements:C.length,copiedStatements:C.length,omittedStatements:0},rawCharacters:R.length,renderedCharacters:R.length})}function Lk(e,t,n,r,i,o){if(!t.location)return o;let s=Sd(e,t.location.file,n,r);if(!s.available)return o;let a=Sn(e,t.location.file,n,r),c=V(e,t.location.file),l=new Set(i);for(let S of i){let y=rc(c[S]??"");if(!y)continue;let x=hn(e,t.location.file,y).find(v=>v>S&&v<=r);x!==void 0&&l.add(x)}let u=[...new Map(s.targets.flatMap(S=>{let y=S.definition,x=y.relativePath===t.location.file&&y.startLine<=r&&y.endLine>=n;if(y.isTypeLike||x)return[];let v=nc(e,y),C=i.length>0&&v&&a.get(S.sourceLine)?.includes("return"),R=v&&l.has(S.sourceLine);return v&&!C&&!R?[]:[[y.symbol,{definition:y,kind:C?"return-value-transformer":R?"focused-causal-target":"compiler-referenced-declaration"}]]})).values()].sort((S,y)=>S.definition.relativePath.localeCompare(y.definition.relativePath)||S.definition.startLine-y.definition.startLine||S.definition.symbol.localeCompare(y.definition.symbol)),d=[],m=u.filter(({kind:S})=>S!=="compiler-referenced-declaration").map(({definition:S})=>({owner:S,depth:1})),p=new Set,f=new Set(u.map(({definition:S})=>S.symbol));for(;m.length>0;){let S=m.shift();if(!S||p.has(S.owner.symbol))continue;p.add(S.owner.symbol);let{owner:y,depth:x}=S,v=Sd(e,y.relativePath,y.startLine,y.endLine);if(!v.available)continue;let C=Sn(e,y.relativePath,y.startLine,y.endLine),R=V(e,y.relativePath);for(let E of v.targets){let I=E.definition,w=I.relativePath===y.relativePath&&I.startLine<=y.endLine&&I.endLine>=y.startLine;if(I.isTypeLike||w)continue;let A=nc(e,I),D=rc(R[E.sourceLine]??""),k=A&&D!==null&&hn(e,y.relativePath,D).some(F=>F>E.sourceLine&&F<=y.endLine&&(C.get(F)??[]).some(P=>["branch","return","throw"].includes(P))),L=A&&((C.get(E.sourceLine)??[]).some(F=>["branch","return","throw"].includes(F))||k);A&&!L||(f.has(I.symbol)||(f.add(I.symbol),d.push({definition:I,kind:A?"focused-causal-target":"compiler-referenced-declaration"})),A&&x<2&&m.push({owner:I,depth:x+1}))}}let g=[...new Map([...u,...d].map(S=>[S.definition.symbol,S])).values()].sort((S,y)=>S.definition.relativePath.localeCompare(y.definition.relativePath)||S.definition.startLine-y.definition.startLine||S.definition.symbol.localeCompare(y.definition.symbol)),h=[],b=[];for(let{definition:S,kind:y}of g){let x=y==="compiler-referenced-declaration"?Pk(e,S.relativePath,S.startLine,S.endLine):{startLine:S.startLine,endLine:S.endLine},v=V(e,S.relativePath).slice(x.startLine,x.endLine+1).join(`
68
- `),C=y==="compiler-referenced-declaration"?null:hi(e,S.relativePath,S.startLine,S.endLine,[]),R=C?[C.signature,...C.lines.map(D=>`${D.line+1}${D.signals.length>0?`[${D.signals.join(",")}]`:""} ${D.text}`)].join(" | "):null,E=R&&R.length<v.length?R:v,I={symbol:S.symbol,label:S.leaf,file:S.relativePath,line:x.startLine,endLine:x.endLine},w=y==="compiler-referenced-declaration"?1e3:8e3,A=y==="compiler-referenced-declaration"?12:120;if(E.length>w||x.endLine-x.startLine>A){b.push({...I,reason:"source-too-large"});continue}h.push({kind:y,...I,text:E})}return{...o,...h.length===0?{}:{supportingDeclarations:h},...b.length===0?{}:{omittedSupportingDeclarations:b}}}function Pk(e,t,n,r){let i=J(e,t);if(!i)return{startLine:n,endLine:r};let o=[];_S(i.rootNode,a=>{Ek.has(a.type)&&a.startPosition.row<=n&&a.endPosition.row>=r&&o.push(a)});let s=o.sort((a,c)=>a.endPosition.row-a.startPosition.row-(c.endPosition.row-c.startPosition.row)||a.endIndex-a.startIndex-(c.endIndex-c.startIndex))[0];return s?{startLine:s.startPosition.row,endLine:s.endPosition.row}:{startLine:n,endLine:r}}function _S(e,t){t(e);for(let n of e.namedChildren)_S(n,t)}function MS(e){return{kind:"outline",constructKind:e.constructKind,signature:e.signature,lines:e.lines,coverage:e.coverage,rawCharacters:e.rawCharacters,renderedCharacters:e.outlineCharacters}}function Dk(e,t,n,r,i,o){if(!t.location||!["symbol","source-construct","runtime-boundary-participant"].includes(t.kind))return[];let s=new Set,a=new Set(K(e,t.location.file)?.callSites.map(c=>c.line)??[]);if(t.kind==="runtime-boundary-participant"&&s.add(t.location.line),o.has(t.id))for(let c of io(e,{files:[t.location.file]}))c.source.startLine>=t.location.line&&c.source.startLine<=(t.location.endLine??t.location.line)&&s.add(c.source.startLine);for(let c of n){if(c.fromNodeId!==t.id&&c.toNodeId!==t.id)continue;let l=r.get(c.fromNodeId===t.id?c.toNodeId:c.fromNodeId),u=o.has(t.id)&&["call","reference","runtime-boundary"].includes(c.kind)&&c.fromNodeId===t.id,d=(l?.anchorIds.length??0)>0;if(!i.has(c.id)&&!u&&!d)continue;let m=c.evidence.flatMap(b=>b.location?.file===t.location.file?[b.location.line]:[]),p=m.filter(b=>a.has(b));for(let b of p.length>0?p:m)s.add(b);let f=l?.attributes.leaf;if(typeof f!="string"||f.length===0)continue;let g=hn(e,t.location.file,f).filter(b=>b>=t.location.line&&b<=(t.location.endLine??t.location.line)),h=g.find(b=>a.has(b))??g[0];h!==void 0&&s.add(h)}return[...s].sort((c,l)=>c-l)}function Mk(e,t){if(!e.location)return[];let n=e.location.endLine??e.location.line;return t.filter(r=>r.file===e.location.file&&r.line>=e.location.line&&r.line<=n).map(r=>r.line)}function Tk(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(Ti(n.file,n.line),{file:n.file,line:n.line})}return[...t.values()].sort((n,r)=>n.file.localeCompare(r.file)||n.line-r.line)}function Ti(e,t){return`${e}\0${t}`}function Ak(e,t,n,r,i,o,s){if(!t.location)return null;let a=V(e,t.location.file),c=Sn(e,t.location.file,n,r),l=[...c].filter(([,L])=>L.length>0).map(([L])=>L).sort((L,F)=>L-F),u=i.map(L=>(c.get(L)??[]).length>0?L:l.find(F=>F>L&&F-L<=8)??L),d=new Set([...i,...u]),m=s?Vl(e,t.location.file,n,r,{minimumBodyLines:0}):null,p=o?[...new Map(u.flatMap(L=>o.lines.filter(F=>F.text.length<=500&&F.signals.some(P=>["branch","loop","catch","finally"].includes(P))&&L>=F.line&&L<=F.endLine).sort((F,P)=>F.endLine-F.line-(P.endLine-P.line)||F.line-P.line).slice(0,2).map(F=>[`${F.line}\0${F.endLine}`,F]))).values()]:pa(e,t.location.file,n,r,u);for(let L of m?.lines??[])d.add(L.line);for(let L of p)d.add(L.line);for(let[L,F]of c)F.includes("call")&&F.includes("shape")&&d.add(L);let f=[];for(let L of u){let F=rc(a[L]??"");if(!F)continue;let P=hn(e,t.location.file,F).filter(O=>O>L&&O<=r),j=P[0];j!==void 0&&d.add(j);let B=P.find(O=>(c.get(O)??[]).some(te=>te==="branch"||te==="loop"));if(B===void 0)continue;d.add(B);let X=(o?.lines??[]).find(O=>O.line===B)??{line:B,endLine:Math.min(r,B+40),depth:0,signals:c.get(B)??[],text:(a[B]??"").trim(),copied:!0},G=o?.lines??a.slice(X.line,X.endLine+1).map((O,te)=>{let ie=X.line+te;return{line:ie,endLine:ie,depth:0,signals:c.get(ie)??[],text:O.trim(),copied:!0}});f.push({focusLine:L,governingUse:B,lines:G.filter(O=>O.line>=X.line&&O.line<=X.endLine&&O.text.length<=500&&O.signals.some(te=>["binding","branch","call","mutation"].includes(te)))})}for(let L of f.sort((F,P)=>P.governingUse-P.focusLine-(F.governingUse-F.focusLine)||F.focusLine-P.focusLine).slice(0,2))for(let F of L.lines.slice(0,14))d.add(F.line);let g=new Set(["binding","branch","loop","call","return","throw","mutation"]);for(let L of p)for(let F of o?.lines??[])F.line<L.line||F.line>L.endLine||F.signals.some(P=>g.has(P))&&d.add(F.line);let h=a.slice(n,r+1).flatMap((L,F)=>{let P=rc(L);return P?[{name:P,line:n+F}]:[]}),b=!0;for(;b;){b=!1;for(let L of h)if([...d].some(P=>kk(a[P]??"",L.name))){d.has(L.line)||(d.add(L.line),b=!0);for(let P of hn(e,t.location.file,L.name))P<n||P>r||d.has(P)||(c.get(P)??[]).some(j=>g.has(j))&&(d.add(P),b=!0)}}for(let L of o?.lines??[])if(L.signals.some(F=>["branch","loop","catch","finally"].includes(F))&&d.has(L.line))for(let F of o?.lines??[])F.line<L.line||F.line>L.endLine||F.signals.some(P=>g.has(P))&&d.add(F.line);let S=K(e,t.location.file),y=new Set(S?.callSites.map(L=>L.line)??[]),x=c,v=new Map([...o?.lines??[],...p].filter(L=>L.signals.some(F=>["branch","loop","catch","finally"].includes(F))).map(L=>[L.line,L])),C=new Map((o?.lines??[]).filter(L=>L.text.length<=500&&L.signals.includes("shape")&&(L.signals.includes("call")||L.signals.includes("mutation")||L.signals.includes("return"))).sort((L,F)=>L.endLine-L.line-(F.endLine-F.line)||L.line-F.line).map(L=>[L.line,L])),R=new Map((m?.lines??[]).map(L=>[L.line,L.signals.filter(F=>F!=="lifecycle")])),E=[...d].filter(L=>L>=n&&L<=r).sort((L,F)=>L-F).map(L=>{let F=v.get(L)??C.get(L);return{line:L,endLine:F?.endLine??L,depth:F?.depth??0,signals:Fk([...x.get(L)??[],...o?.lines.filter(P=>L>=P.line&&L<=P.endLine).flatMap(P=>P.signals)??[],...R.get(L)??[],...i.includes(L)?["anchor"]:[],...y.has(L)?["call"]:[]]),text:F?.text??(a[L]??"").trim(),copied:F?.copied??!0}}).filter(L=>L.text.length>0);if(E.length===0)return null;let I=m?.candidateLines??Vl(e,t.location.file,n,r,{minimumBodyLines:0})?.candidateLines??0,w=Math.max(o?.coverage.sourceStatements??0,I,E.length),A=o?.signature??(a[n]??t.label).trim(),D=A.length+E.reduce((L,F)=>L+F.text.length+F.signals.join(",").length+12,0),k=a.slice(n,r+1).join(`
69
- `).length;return{kind:"connector-slice",constructKind:o?.constructKind??"source construct",signature:A,lines:E,coverage:{sourceStatements:w,representedStatements:E.length,copiedStatements:E.length,omittedStatements:Math.max(0,w-E.length)},rawCharacters:k,renderedCharacters:D}}function Fk(e){let t=["anchor","signature","binding","branch","loop","call","await","return","throw","mutation","shape","spread","catch","finally"],n=new Set(e);return t.filter(r=>n.has(r))}function rc(e){return/\b(?:const|let|var)\s+([\p{L}_$][\p{L}\p{N}_$]*)\s*(?:=|\bof\b|\bin\b)/u.exec(e)?.[1]??null}function kk(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`(?:^|[^\\p{L}\\p{N}_$])${n}(?:$|[^\\p{L}\\p{N}_$])`,"u").test(e)}function Nk(e,t,n){return wn(e.flatMap(r=>{let i=n.get(r),o=t.filter(s=>s.kind==="call"&&s.toNodeId===r).map(s=>({edge:s,node:n.get(s.fromNodeId)})).filter(s=>s.node!==void 0&&["symbol","source-construct","runtime-boundary-participant"].includes(s.node.kind)&&s.node.location!==null).sort((s,a)=>{let c=TS(a.edge)-TS(s.edge);if(c!==0)return c;let l=AS(s.node,i)?0:1,u=AS(a.node,i)?0:1,d=(s.node.location?.endLine??s.node.location?.line??0)-(s.node.location?.line??0),m=(a.node.location?.endLine??a.node.location?.line??0)-(a.node.location?.line??0);return l-u||d-m||s.node.label.localeCompare(a.node.label)});return o[0]?[o[0].node.id]:[]}))}function TS(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 AS(e,t){return!e.location||!t?.location?!1:FS(e.location.file)===FS(t.location.file)}function FS(e){return e.split("/").filter(Boolean).slice(0,2).join("/")}function _k(e,t,n,r){let i=new Set(e),o=new Set,s=[],a=wn(e);for(let c=0;c<r&&a.length>0;c+=1){let l=a.filter(d=>!o.has(d));for(let d of l)o.add(d);let u=Nk(l,t,n);a=[];for(let d of u)!i.has(d)&&!s.includes(d)&&s.push(d),o.has(d)||a.push(d)}return s}function Ok(e,t,n){let r=new Map(n.paths.flatMap(i=>i.edgeIds).map((i,o)=>[i,o]));return(r.get(e.id)??Number.MAX_SAFE_INTEGER)-(r.get(t.id)??Number.MAX_SAFE_INTEGER)||e.id.localeCompare(t.id)}function Bk(e){return`step:${e}`}function $k(e){return`transition:${e}`}function kS(e,t){return e.length===0?null:`scip-query inspect ${e.map(n=>`--at ${jk(n)}`).join(" ")} --view ${t}`}function jk(e){return`'${e.replace(/'/gu,`'"'"'`)}'`}function wn(e){return[...new Set(e)]}var OS=4,Hk=3,Uk=12,qk=48,Gk=64,jr=10,Br=6,zk=24,Kk=320,Id=6,Wk=12,Vk=1,Yk=4,Jk=7,Xk=12,Md="source-construct:",Qk=96,Zk=32,BS=4,e0=32,t0=8,$S=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 n0(e,t,n={}){let r=ZS(t),i=H0(t);if(r.length===0)throw new Error("Anchor discovery requires at least one non-trivial repository term.");let o=n.limit??OS,s=n.full===!0;if(!Number.isSafeInteger(o)||o<=0)throw new RangeError(`anchor group limit must be a positive safe integer; received ${o}`);let a=new H(e),c=a.scopedDefinitions(n.scope).filter(O=>!pe(O.symbol)),l=[...c],u=new Map(l.map(O=>[O.symbol,O])),d=new Map;for(let O of c)jS(d,O,r);let m=xg(e,{scope:n.scope});for(let O of m.files){let ie=U(e,O.relativePath).filter(Me=>!pe(Me.symbol));if(ie.length===0)continue;let Le=_n(O.text);for(let Me=0;Me<Le.length;Me+=1){let Nt=at(Le[Me]??""),tt=r.filter($=>Nt.has($));if(tt.length===0)continue;let M=Oe(ie,Me);if(!(!M||pe(M.symbol)))for(let $ of tt)_o(d,M,$,"source",O.relativePath,Me)}}let p=HS(d),f=[...d.values()].map(O=>ic(O,p,i)).sort(Ge),g=i0(m.files,f,r),h=-1;for(let O of g){let te=U(e,O.relativePath),ie=te.filter(M=>!pe(M.symbol)),Le=K(e,O.relativePath)?.callables??[],Me=new Map,Nt=M=>{let $=`${M.startLine}\0${M.endLine}\0${M.name}`,Y=Me.get($);if(Y)return Y;let oe=r0(O.relativePath,te,M,()=>h--);return oe?(Me.set($,oe),l.push(oe),u.set(oe.symbol,oe),jS(d,oe,r),oe):null};for(let M of Le){let $=at(M.name);r.some(Y=>$.has(Y))&&Nt(M)}if(Le.length===0)continue;let tt=_n(O.text);for(let M=0;M<tt.length;M+=1){let $=at(tt[M]??""),Y=r.filter(hr=>$.has(hr));if(Y.length===0)continue;let oe=On(Le,M),Ne=oe?Nt(oe):null;if(!Ne)continue;let qt=US(ie,M);if(US(qt?[qt,Ne]:[Ne],M)?.symbol===Ne.symbol)for(let hr of Y)_o(d,Ne,hr,"source",O.relativePath,M)}}let b=HS(d),S=new Map(m.files.map(O=>[O.relativePath,O.text.split(/\r?\n/u)]));for(let O of d.values()){let te=S.get(O.definition.relativePath);te&&(O.sourceCharacters=te.slice(O.definition.startLine,O.definition.endLine+1).join(`
70
- `).length)}let y=[...d.values()].map(O=>ic(O,b,i)).sort(Ge),x=Math.min(y.length,Math.max(Uk,o*Hk)),v=s?y:Ai([...y.slice(0,x),...[...y].sort(Ld).slice(0,Math.max(qk,x)),...k0(y,r),...N0(y,r,b)]),C=v.length,R=v.map(O=>u.get(O.symbol)).filter(O=>O?.isFunctionLike===!0),E=o0(l),I=s0(e,a,v,R,u,E,new Set(d.keys()),n.semantic!==!1),w=l0(I,v,d,b,u),A=u0(w,b,r),D=E0(e,a,I,d,b,l,u,n.semantic!==!1),L=[...m0(e,a,w,u,b,n.semantic!==!1),...A,...w,...D].map(O=>({...O,queryPathMatches:O0(O)})).sort((O,te)=>$r(O,te,b)),F=s?L:B0(L,o,b),P=r.filter(O=>b.has(O)),j=r.filter(O=>!b.has(O)),B=Math.max(0,y.length-C),X=Math.max(0,L.length-F.length)+B,G=s?y.length:Math.min(y.length,o+OS);return{query:t,queryPathFragments:i,normalizedTerms:r,matchedTerms:P,unmatchedTerms:j,groups:F,candidateRoots:y,candidateRootCount:y.length,analyzedRootCount:C,omittedRootCount:B,omittedGroupCount:X,scannedFiles:m.files.length,scannedBytes:m.scannedBytes,recoveryCommand:X===0?null:`scip-query anchors ${cc(t)}${n.scope?` --scope ${cc(n.scope)}`:""} --limit ${G}`}}function ZS(e){let t=lc(e).filter(n=>!$S.has(n.toLocaleLowerCase())).map(Td).filter(n=>n.length>=3&&!$S.has(n));return[...new Set(t)]}function jS(e,t,n){let r=at(t.leaf),i=at(t.relativePath),o=at(t.documentation??"");for(let a of n)r.has(a)&&_o(e,t,a,"symbol"),i.has(a)&&_o(e,t,a,"path"),o.has(a)&&_o(e,t,a,"documentation");let s=e.get(t.symbol);s&&(s.symbolPhraseLength=q0(t.leaf,n))}function _o(e,t,n,r,i,o){let s=e.get(t.symbol)??{definition:t,matches:new Map,symbolPhraseLength:0},a=s.matches.get(n)??{sources:new Set,locations:new Map};a.sources.add(r),i!==void 0&&o!==void 0&&a.locations.set(`${i}\0${o}`,{file:i,line:o}),s.matches.set(n,a),e.set(t.symbol,s)}function HS(e){let t=new Map;for(let n of e.values())for(let r of n.matches.keys())t.set(r,(t.get(r)??0)+1);return t}function r0(e,t,n,r){let i=t[0]?.documentId;if(i===void 0||t.find(a=>a.isFunctionLike&&a.leaf===n.name&&a.startLine===n.startLine&&a.endLine===n.endLine))return null;let s=r();return{documentId:i,symbolId:s,symbol:`${Md}${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 i0(e,t,n){let r=new Set(t.slice(0,Qk).map(s=>s.file)),i=new Set(n),o=e.map(s=>{let a=at(s.relativePath),c=s.relativePath.slice(s.relativePath.lastIndexOf("/")+1).replace(/\.[^.]+$/u,""),l=at(c),u=[...a].filter(m=>i.has(m)).length,d=[...l].filter(m=>i.has(m)).length;return{file:s,score:d*4+u}}).filter(s=>s.score>0).sort((s,a)=>a.score-s.score||Re(q(s.file.relativePath))-Re(q(a.file.relativePath))||s.file.relativePath.localeCompare(a.file.relativePath)).slice(0,Zk);for(let s of o)r.add(s.file.relativePath);return e.filter(s=>r.has(s.relativePath))}function o0(e){let t=new Map;for(let n of e){if(!tn(n))continue;let r=`${n.relativePath}\0${qe(n.leaf)}`,i=t.get(r)??[];i.push(n),t.set(r,i)}return t}function US(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,r)=>n.endLine-n.startLine-(r.endLine-r.startLine)||Number(tn(r))-Number(tn(n))||n.startLine-r.startLine||n.symbol.localeCompare(r.symbol))[0]}function tn(e){return e.symbol.startsWith(Md)}function ir(e){return tn(e)?e.leaf:T(e.symbol)}function ic(e,t,n=[]){let r=e.definition,i=[...e.matches.entries()].map(([l,u])=>({term:l,sources:[...u.sources].sort(G0),locations:[...u.locations.values()].sort(rv).slice(0,3)})).sort((l,u)=>l.term.localeCompare(u.term)),o=i.filter(l=>l.sources.some(u=>u!=="source")).map(l=>l.term),s=i.filter(l=>l.sources.includes("symbol")).map(l=>l.term),a=i.reduce((l,u)=>l+1/Math.max(1,t.get(u.term)??1),0),c=i.filter(l=>l.sources.includes("symbol")).reduce((l,u)=>l+1/Math.max(1,t.get(u.term)??1),0);return{symbol:r.symbol,label:ir(r),leaf:r.leaf,file:r.relativePath,line:r.startLine,endLine:r.endLine,kind:r.isFunctionLike?"callable":r.isTypeLike?"type":"symbol",fileKind:q(r.relativePath),matches:i,focusLocations:W0(e,t),matchedTerms:i.map(l=>l.term),symbolMatchedTerms:s,symbolPhraseLength:e.symbolPhraseLength,identityMatchedTerms:o,rarity:a,symbolRarity:c,queryPathMatches:U0(r.relativePath,n),...e.sourceCharacters===void 0?{}:{sourceCharacters:e.sourceCharacters}}}function s0(e,t,n,r,i,o,s,a){let c=r.filter(g=>!tn(g)),l=t.calleeMap(c,{additive:!1,semantic:a}),u=new Map,d=new Map;for(let g of n){let h=i.get(g.symbol),b=h?tn(h)?qS(e,h,i,o,1):oc(e,h,l.get(h.symbolId)??[],i,1,s):[];u.set(g.symbol,b);for(let S of b){let y=i.get(S.toSymbol);y?.isFunctionLike&&(!h||!tn(h)||tn(y))&&d.set(y.symbol,y)}}let m=[...d.values()],p=t.calleeMap(m.filter(g=>!tn(g)),{additive:!1,semantic:a}),f=new Map;for(let g of m)f.set(g.symbol,tn(g)?qS(e,g,i,o,2):oc(e,g,p.get(g.symbolId)??[],i,2,s));return n.map(g=>{let h=u.get(g.symbol)??[],b=h.flatMap(y=>f.get(y.toSymbol)??[]),S=Ln([...h,...b]);return{root:g,relations:S,nodeSymbols:new Set([g.symbol,...S.flatMap(y=>[y.fromSymbol,y.toSymbol])])}})}function oc(e,t,n,r,i,o=new Set){let s=new Map;for(let a of n){let c=r.get(a.symbol);if(!c?.isFunctionLike||c.symbol===t.symbol||a.source==="ast-callsite"&&!c0(e,t,c,a.callsiteLine))continue;let l=s.get(c.symbol);(!l||j0(a,l)<0)&&s.set(c.symbol,a)}return[...s.entries()].map(([a,c])=>{let l=r.get(a);return{kind:"call",fromSymbol:t.symbol,fromLabel:T(t.symbol),fromFile:t.relativePath,toSymbol:l.symbol,toLabel:T(l.symbol),toFile:l.relativePath,depth:i,strength:Dd(c.source),evidence:c.source,callsiteLine:c.callsiteLine??a0(e,t,l)}}).sort((a,c)=>Number(o.has(c.toSymbol))-Number(o.has(a.toSymbol))||nn(a,c)).slice(0,Gk)}function qS(e,t,n,r,i){let o=In(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:ir(t),fromFile:t.relativePath,toSymbol:a.symbol,toLabel:ir(a),toFile:a.relativePath,depth:i,strength:"exact",evidence:"scip-occurrence-callsite",callsiteLine:s.sourceLine}]});for(let s of rr(e,t.relativePath,{ranges:[{startLine:t.startLine,endLine:t.endLine}],excludeIndexedTargets:!1}).targets){let a=[...r.get(`${s.targetFile}\0${qe(s.calleeLeaf)}`)??[],...U(e,s.targetFile).filter(c=>c.isFunctionLike&&qe(c.leaf)===s.calleeLeaf)].find(c=>c.startLine===s.targetStartLine&&c.endLine===s.targetEndLine);!a||a.symbol===t.symbol||o.push({kind:"call",fromSymbol:t.symbol,fromLabel:ir(t),fromFile:t.relativePath,toSymbol:a.symbol,toLabel:ir(a),toFile:a.relativePath,depth:i,strength:s.strength==="exact"?"exact":"derived",evidence:"ast-member-import-candidate",callsiteLine:s.line})}for(let s of K(e,t.relativePath)?.callSites??[]){if(s.line<t.startLine||s.line>t.endLine||s.memberAccess)continue;let a=(r.get(`${t.relativePath}\0${qe(s.calleeLeaf)}`)??[]).filter(l=>l.symbol!==t.symbol);if(a.length!==1)continue;let c=a[0];o.push({kind:"call",fromSymbol:t.symbol,fromLabel:ir(t),fromFile:t.relativePath,toSymbol:c.symbol,toLabel:ir(c),toFile:c.relativePath,depth:i,strength:"derived",evidence:"ast-callsite",callsiteLine:s.line})}return Ln(o).sort(nn)}function a0(e,t,n){let r=qe(n.leaf);return K(e,t.relativePath)?.callSites.find(i=>i.line>=t.startLine&&i.line<=t.endLine&&qe(i.calleeLeaf)===r)?.line??null}function c0(e,t,n,r){if(r===void 0)return!1;let i=qe(n.leaf);return K(e,t.relativePath)?.callSites.some(o=>{if(o.line!==r)return!1;if(qe(o.calleeLeaf)===i)return!0;let s=ai(e,t.relativePath,o.calleeLeaf);return s!==null&&qe(s.importedName)===i&&_e(s.sourcePath,n.relativePath)})??!1}function l0(e,t,n,r,i){let o=new Map(t.map((u,d)=>[u.symbol,d])),s=t.map((u,d)=>d),a=u=>{let d=u;for(;s[d]!==d;)d=s[d];for(;s[u]!==u;){let m=s[u];s[u]=d,u=m}return d},c=(u,d)=>{let m=a(u),p=a(d);m!==p&&(s[p]=m)};for(let u of e){let d=o.get(u.root.symbol);if(d!==void 0)for(let m of u.nodeSymbols){let p=o.get(m);p!==void 0&&c(d,p)}}let l=new Map;for(let u=0;u<t.length;u+=1){let d=a(u),m=l.get(d)??[];m.push(t[u]),l.set(d,m)}return[...l.values()].map((u,d)=>{let m=new Set(u.map(y=>y.symbol)),p=Ln(e.filter(y=>m.has(y.root.symbol)).flatMap(y=>y.relations)).sort(nn),f=new Map(u.map(y=>[y.symbol,y]));for(let y of new Set(p.flatMap(x=>[x.fromSymbol,x.toSymbol]))){let x=n.get(y);if(x)f.has(y)||f.set(y,ic(x,r));else{let v=i.get(y);v&&f.set(y,tv(v))}}let g=T0(u,p,f),h=u.filter(y=>p.some(x=>x.fromSymbol===y.symbol)).length,b=[...new Set(u.flatMap(y=>y.matchedTerms))].sort(),S=M0(p,g,m,f);return{id:`anchor-set:${d+1}:${Bo(u[0])}`,kind:"connected-flow",roots:[...u].sort(Ge),keyAnchors:g,candidateOwnerCount:g.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:[],matchedTerms:b,relations:S,relationCount:p.length,orchestrationRootCount:h,omittedRelations:Math.max(0,p.length-jr),systemMapCommand:jo(g,p,b)}})}function u0(e,t,n){let r=new Map(n.map((o,s)=>[o,s])),i=[];for(let o=0;o<e.length;o+=1){let s=e[o],a=GS(s);if(a.size!==0)for(let c=o+1;c<e.length;c+=1){let l=e[c],u=GS(l),d=[...a].filter(v=>u.has(v));if(d.length===0||![...a].some(v=>!u.has(v))||![...u].some(v=>!a.has(v)))continue;let m=d0(s,l);if(m.length<2)continue;let p=Ln([...s.relations,...l.relations]).sort(nn),f=p.slice(0,jr),g=Ai([...s.roots,...l.roots]).sort(Ge),h=[...new Set([...s.matchedTerms,...l.matchedTerms])].sort(),b=d.sort((v,C)=>(r.get(v)??Number.MAX_SAFE_INTEGER)-(r.get(C)??Number.MAX_SAFE_INTEGER)||v.localeCompare(C)),S=+(s.relationCount>0)+ +(l.relationCount>0),y=+((s.orchestrationRootCount??0)>0)+ +((l.orchestrationRootCount??0)>0),x=Math.min(...b.map(v=>t.get(v)??Number.MAX_SAFE_INTEGER));i.push({sharedOrder:Math.min(...b.map(v=>r.get(v)??Number.MAX_SAFE_INTEGER)),sharedFrequency:x,connectedSides:S,orchestrationSides:y,group:{id:`parallel-paths:${Bo(s.roots[0])}:${Bo(l.roots[0])}`,kind:"parallel-paths",roots:g,keyAnchors:m,candidateOwnerCount:m.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:[...s.upstreamEntries,...l.upstreamEntries],matchedTerms:h,relations:f,relationCount:p.length,parallelConnectedSides:S,parallelOrchestrationSides:y,parallelSharedPathTerms:b,parallelSharedPathFrequency:x,orchestrationRootCount:(s.orchestrationRootCount??0)+(l.orchestrationRootCount??0),omittedRelations:Math.max(0,p.length-f.length),systemMapCommand:jo(m,p,h)}})}}return i.sort((o,s)=>o.sharedFrequency-s.sharedFrequency||s.orchestrationSides-o.orchestrationSides||s.connectedSides-o.connectedSides||o.sharedOrder-s.sharedOrder||s.group.matchedTerms.length-o.group.matchedTerms.length||$r(o.group,s.group,t)).slice(0,Xk).map(o=>o.group)}function GS(e){return new Set(e.roots.flatMap(t=>t.matches.filter(n=>n.sources.includes("path")).map(n=>n.term)))}function d0(e,t){return Ai([zS(e),zS(t)].filter(n=>n!==void 0))}function zS(e){let t=new Set(e.keyAnchors.map(r=>r.symbol)),n=new Map;for(let r of e.relations)!t.has(r.fromSymbol)||!t.has(r.toSymbol)||n.set(r.fromSymbol,(n.get(r.fromSymbol)??0)+1);return[...e.keyAnchors].sort((r,i)=>+((n.get(i.symbol)??0)>0)-+((n.get(r.symbol)??0)>0)||KS(i)-KS(r)||i.identityMatchedTerms.length-r.identityMatchedTerms.length||i.symbolMatchedTerms.length-r.symbolMatchedTerms.length||(n.get(i.symbol)??0)-(n.get(r.symbol)??0)||Ge(r,i))[0]}function KS(e){return e.matchedTerms.length+e.identityMatchedTerms.length*2+(e.queryPathMatches?.length??0)*4}function m0(e,t,n,r,i,o){let s=Ws(e);if(!s||s.links.length===0||n.length<2)return[];let a=new Map(s.observations.map(p=>[p.id,p])),c=new Map,l=new Map,u=[...n].sort((p,f)=>$r(p,f,i)).slice(0,Wk),d=s.links.filter(p=>p.strength!=="candidate").sort((p,f)=>or(f.strength)-or(p.strength)||f.matchedKeyParts.length-p.matchedKeyParts.length||p.id.localeCompare(f.id));for(let p of u)for(let f of d){let g=a.get(f.from),h=a.get(f.to);if(!g||!h||!p0(p,g,r))continue;let b=f0(p,g,r);if(!b)continue;let S=c.get(h.id)??y0(e,t,h,r,o,Yk);if(c.set(h.id,S),S.reachedSymbols.size===0)continue;let y=n.filter(L=>L.id!==p.id&&g0(L).some(F=>S.reachedSymbols.has(F))&&wd(b,L)>=2).sort((L,F)=>wd(b,F)-wd(b,L)||$r(L,F,i)).slice(0,Vk);if(y.length===0)continue;let x=[p.id,g.id,...y.map(L=>L.id).sort()].join("\0");if(l.has(x))continue;let v=new Set(y.flatMap($o)),C=x0(Oo(h),v,S.relations);if(C.length===0)continue;let R=C0(g,h,f.joinRule,f.matchedKeyParts,f.strength),E=Ln([R,...S.relations,...p.relations,...y.flatMap(L=>L.relations)]),I=R0([R,...C],E,p,y),w=Ai([b,...y.flatMap(L=>L.roots)]).sort(Ge),A=Ai([b,...y.flatMap(L=>L.keyAnchors)]).slice(0,Jk),D=[...new Set([...b.matchedTerms,...y.flatMap(L=>L.matchedTerms)])].sort(),k=h0(e,t,b,r,o);w.length===0||A.length<2||l.set(x,{id:`cross-boundary-set:${Bo(b)}:${l.size+1}`,kind:"cross-boundary-flow",roots:w,keyAnchors:A,candidateOwnerCount:A.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:k,matchedTerms:D,relations:I,relationCount:E.length,omittedRelations:Math.max(0,E.length-I.length),systemMapCommand:jo(A,E,D)})}let m=new Map;for(let[p,f]of l){let g=p.slice(0,p.indexOf("\0")),h=m.get(g);(!h||$r(f,h,i)<0)&&m.set(g,f)}return[...m.values()]}function p0(e,t,n){let r=new Set($o(e));return t.owner.symbol&&r.has(t.owner.symbol)?!0:[...r].map(i=>n.get(i)).some(i=>i?.relativePath===t.source.file&&i.startLine<=t.source.startLine&&i.endLine>=t.source.endLine)}function f0(e,t,n){let r=Ai([...e.roots,...e.keyAnchors]);if(t.owner.symbol){let i=r.find(o=>o.symbol===t.owner.symbol);if(i)return i}return r.find(i=>{let o=n.get(i.symbol);return o?.relativePath===t.source.file&&o.startLine<=t.source.startLine&&o.endLine>=t.source.endLine})??null}function $o(e){return[...new Set([...e.roots.map(t=>t.symbol),...e.keyAnchors.map(t=>t.symbol),...e.relations.flatMap(t=>[t.fromSymbol,t.toSymbol])])]}function g0(e){return[...new Set([...e.roots,...e.keyAnchors].map(t=>t.symbol))]}function wd(e,t){let n=at(e.leaf),r=[...t.roots,...t.keyAnchors].map(o=>at(o.leaf)),i=0;for(let o of r){let s=0;for(let a of n)o.has(a)&&(s+=1);i=Math.max(i,s)}return i}function h0(e,t,n,r,i){let o=r.get(n.symbol);if(!o?.isFunctionLike)return[];let s=t.callerFileMap([o],{semantic:i,sourceFallback:!0}).get(o.symbolId);if(!s)return[];let a=at(n.leaf);return[...s].filter(c=>c!==n.file&&q(c)!=="test").flatMap(c=>{let l=K(e,c);return(l?.callSites??[]).filter(u=>qe(u.calleeLeaf)===qe(n.leaf)).flatMap(u=>{let d=(l?.callables??[]).filter(p=>p.startLine<=u.line&&p.endLine>=u.line).sort((p,f)=>p.endLine-p.startLine-(f.endLine-f.startLine)||p.startLine-f.startLine)[0];if(!d)return[];let m=[...at(d.name)].filter(p=>a.has(p)).length;return m>=2?[{name:d.name,file:c,line:d.startLine,endLine:d.endLine,callsiteLine:u.line,overlap:m}]:[]})}).sort((c,l)=>l.overlap-c.overlap||c.file.localeCompare(l.file)||c.line-l.line).slice(0,1).map(({name:c,file:l,line:u,endLine:d,callsiteLine:m})=>({name:c,file:l,line:u,endLine:d,callsiteLine:m}))}function y0(e,t,n,r,i,o){let s=b0(e,n,r),a=s.map(({definition:m,evidence:p,line:f})=>({kind:"call",fromSymbol:Oo(n),fromLabel:sc(n),fromFile:n.source.file,toSymbol:m.symbol,toLabel:T(m.symbol),toFile:m.relativePath,depth:1,strength:p==="scip-occurrence-callsite"?"exact":"derived",evidence:p,callsiteLine:f})),c=S0(e,n);a.push(...c.relations);let l=ev([...s.map(m=>m.definition),...c.definitions]),u=l,d=new Set(u.map(m=>m.symbol));for(let m=2;m<=o+1&&u.length>0;m+=1){let p=t.calleeMap(u,{additive:!1,semantic:i}),f=new Map;for(let g of u){let h=oc(e,g,p.get(g.symbolId)??[],r,m);a.push(...h);for(let b of h){let S=r.get(b.toSymbol);S?.isFunctionLike&&!d.has(S.symbol)&&f.set(S.symbol,S)}}u=[...f.values()];for(let g of u)d.add(g.symbol)}return{entryDefinitions:l,relations:Ln(a),reachedSymbols:new Set([...l.map(m=>m.symbol),...a.flatMap(m=>[m.fromSymbol,m.toSymbol])])}}function b0(e,t,n){let r=t.owner.symbol?n.get(t.owner.symbol):void 0;if(r?.isFunctionLike&&!pe(r.symbol))return[{definition:r,evidence:"scip-occurrence-callsite",line:t.source.startLine}];let i=V(e,t.source.file),o=ot(e,t.source.file,0,Math.max(0,i.length-1),[t.source.startLine]),s=In(e,t.source.file,o.startLine,o.endLine).targets.map(u=>({definition:u.definition,evidence:"scip-occurrence-callsite",line:u.sourceLine})),a=K(e,t.source.file),c=Kt(e),l=(a?.callSites??[]).flatMap(u=>{if(u.line<o.startLine||u.line>o.endLine)return[];let d=Ot(t.source.file,c.get(u.calleeLeaf)??[]),m=Hn(e,t.source.file,d,u.memberAccess,u.calleeQualifier),p=m?n.get(m.symbol):void 0;return p?.isFunctionLike?[{definition:p,evidence:"ast-callsite",line:u.line}]:[]});return v0([...s,...l])}function S0(e,t){let n=V(e,t.source.file),r=ot(e,t.source.file,0,Math.max(0,n.length-1),[t.source.startLine]),i=rr(e,t.source.file,{ranges:[r],excludeIndexedTargets:!1}).targets,o=[],s=[];for(let a of i){let c=`source-construct:${a.targetFile}:${a.targetStartLine}:${a.targetEndLine}:${a.calleeLeaf}`;s.push({kind:"call",fromSymbol:Oo(t),fromLabel:sc(t),fromFile:t.source.file,toSymbol:c,toLabel:a.calleeLeaf,toFile:a.targetFile,depth:1,strength:"derived",evidence:"ast-member-import-candidate",callsiteLine:a.line});let l=In(e,a.targetFile,a.targetStartLine,a.targetEndLine).targets;for(let u of l)o.push(u.definition),s.push({kind:"call",fromSymbol:c,fromLabel:a.calleeLeaf,fromFile:a.targetFile,toSymbol:u.definition.symbol,toLabel:T(u.definition.symbol),toFile:u.definition.relativePath,depth:2,strength:"exact",evidence:"scip-occurrence-callsite",callsiteLine:u.sourceLine})}return{definitions:ev(o),relations:Ln(s)}}function v0(e){return[...new Map(e.map(t=>[t.definition.symbol,t])).values()]}function ev(e){return[...new Map(e.map(t=>[t.symbol,t])).values()]}function Oo(e){return e.owner.symbol??e.id}function sc(e){return e.owner.name??`${e.source.file}:${e.source.startLine+1}`}function C0(e,t,n,r,i){return{kind:"runtime-boundary",fromSymbol:Oo(e),fromLabel:sc(e),fromFile:e.source.file,toSymbol:Oo(t),toLabel:sc(t),toFile:t.source.file,depth:1,strength:i,evidence:`runtime-boundary:${n}`,callsiteLine:e.source.startLine,runtimeBoundaryKey:r.map(o=>`${o.name}=${o.value}`).join(" ")}}function x0(e,t,n){let r=new Map;for(let s of n){let a=r.get(s.fromSymbol)??[];a.push(s),r.set(s.fromSymbol,a)}let i=[{symbol:e,path:[]}],o=new Set([e]);for(;i.length>0;){let s=i.shift();if(s.path.length>0&&t.has(s.symbol))return s.path;for(let a of(r.get(s.symbol)??[]).sort(nn))o.has(a.toSymbol)||(o.add(a.toSymbol),i.push({symbol:a.toSymbol,path:[...s.path,a]}))}return[]}function R0(e,t,n,r){let i=Ln(e),o=new Set([n,...r].flatMap(s=>[...$o(s),...s.keyAnchors.map(a=>a.symbol)]));for(let s of t){if(i.length>=jr)break;!o.has(s.fromSymbol)&&!o.has(s.toSymbol)||i.some(a=>a.fromSymbol===s.fromSymbol&&a.toSymbol===s.toSymbol)||i.push(s)}return i.slice(0,jr)}function E0(e,t,n,r,i,o,s,a){let c=n.filter(u=>!u.root.symbol.startsWith(Md)).map(u=>({root:u.root,relations:u.relations.filter(d=>d.depth===1&&d.fromSymbol===u.root.symbol)}));return I0(c).flatMap((u,d)=>{let m=new Set(u.map(P=>P.root.symbol)),p=new Map;for(let P of u)for(let j of new Set(P.relations.map(B=>B.toSymbol)))p.set(j,(p.get(j)??0)+1);let f=[...p].filter(([,P])=>P>=2).sort(([P,j],[B,X])=>X-j||w0(P,B,r,i,s)).map(([P])=>s.get(P)).filter(P=>P?.isFunctionLike===!0).slice(0,zk);if(f.length===0)return[];let g=t.callerFileMap(f,{semantic:a,sourceFallback:!0}),h=new Set;for(let P of f){h.add(P.relativePath);for(let j of g.get(P.symbolId)??[])h.add(j)}let b=o.filter(P=>P.isFunctionLike&&h.has(P.relativePath)).sort(L0).slice(0,Kk),S=t.calleeMap(b,{additive:!1,semantic:a}),y=new Set(f.map(P=>P.symbol)),x=Ln(b.flatMap(P=>oc(e,P,S.get(P.symbolId)??[],s,1,y).filter(j=>y.has(j.toSymbol)))),v=new Map;for(let P of x){let j=v.get(P.fromSymbol)??new Set;j.add(P.toSymbol),v.set(P.fromSymbol,j)}let C=new Set([...v].filter(([P,j])=>j.size>=2||m.has(P)).map(([P])=>P)),R=x.filter(P=>C.has(P.fromSymbol));if(C.size<2||R.length===0)return[];let I=[...new Set(R.map(P=>P.toSymbol))].map(P=>ac(P,r,i,s)).filter(P=>P!==null).sort(Ge),w=[...C].map(P=>ac(P,r,i,s)).filter(P=>P!==null),A=P0(w,R),D=A.slice(0,Id),k=A.slice(Id);if(I.length===0||D.length===0)return[];let L=[...new Set([...I.flatMap(P=>P.matchedTerms),...u.flatMap(P=>P.root.matchedTerms)])].sort(),F=D0(R,D);return[{id:`effect-owner-set:${d+1}:${Bo(I[0])}`,kind:"shared-callee-owners",roots:I,keyAnchors:D,candidateOwnerCount:A.length,omittedCandidateOwners:k,ownerRecoveryCommands:V0(k,Id),upstreamEntries:[],matchedTerms:L,relations:F,relationCount:R.length,omittedRelations:Math.max(0,R.length-F.length),systemMapCommand:jo(D,R,L)}]})}function I0(e){let t=e.map((s,a)=>a),n=s=>{for(;t[s]!==s;)t[s]=t[t[s]],s=t[s];return s},r=(s,a)=>{let c=n(s),l=n(a);c!==l&&(t[l]=c)},i=e.map(s=>new Set(s.relations.map(a=>a.toSymbol)));for(let s=0;s<e.length;s+=1)for(let a=s+1;a<e.length;a+=1){let c=0;for(let l of i[s]??[])if((i[a]??new Set).has(l)&&(c+=1),c>=2)break;c>=2&&r(s,a)}let o=new Map;for(let s=0;s<e.length;s+=1){let a=n(s),c=o.get(a)??[];c.push(e[s]),o.set(a,c)}return[...o.values()].filter(s=>s.length>=2)}function w0(e,t,n,r,i){let o=ac(e,n,r,i),s=ac(t,n,r,i);return o?s?Ge(o,s):-1:s?1:e.localeCompare(t)}function L0(e,t){return Re(q(e.relativePath))-Re(q(t.relativePath))||e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine}function ac(e,t,n,r){let i=t.get(e);if(i)return ic(i,n);let o=r.get(e);return o?tv(o):null}function P0(e,t){let n=new Map;for(let i of t){let o=n.get(i.toSymbol)??new Set;o.add(i.fromSymbol),n.set(i.toSymbol,o)}let r=new Map;for(let i of t){let o=n.get(i.toSymbol)?.size??1;r.set(i.fromSymbol,(r.get(i.fromSymbol)??0)+o*o)}return[...e].sort((i,o)=>Number(i.leaf.startsWith("#"))-Number(o.leaf.startsWith("#"))||o.identityMatchedTerms.length-i.identityMatchedTerms.length||(r.get(o.symbol)??0)-(r.get(i.symbol)??0)||Ge(i,o))}function D0(e,t){let n=new Map(t.map((s,a)=>[s.symbol,a])),r=t.map(s=>e.filter(a=>a.fromSymbol===s.symbol).sort(nn)),i=[],o=0;for(;i.length<jr&&r.some(s=>o<s.length);){for(let s of r){let a=s[o];if(a&&i.push(a),i.length>=jr)break}o+=1}return i.sort((s,a)=>n.get(s.fromSymbol)-n.get(a.fromSymbol)||nn(s,a))}function M0(e,t,n,r){let i=new Map(t.map((a,c)=>[a.symbol,c])),o=new Map;for(let a of e)o.set(a.fromSymbol,(o.get(a.fromSymbol)??0)+1);return[...e].sort((a,c)=>{let l=u=>{let d=0;return i.has(u.fromSymbol)&&(d+=100),n.has(u.toSymbol)&&(d+=60),d+=Math.min(40,(o.get(u.toSymbol)??0)*8),(r.get(u.toSymbol)?.matchedTerms.length??0)>0&&(d+=25),u.fromFile!==u.toFile&&(d+=15),u.strength==="exact"&&(d+=5),d};return l(c)-l(a)||nn(a,c)}).slice(0,jr).sort((a,c)=>(i.get(a.fromSymbol)??Br)-(i.get(c.fromSymbol)??Br)||a.depth-c.depth||(a.callsiteLine??Number.MAX_SAFE_INTEGER)-(c.callsiteLine??Number.MAX_SAFE_INTEGER)||nn(a,c))}function tv(e){return{symbol:e.symbol,label:ir(e),leaf:e.leaf,file:e.relativePath,line:e.startLine,endLine:e.endLine,kind:e.isFunctionLike?"callable":e.isTypeLike?"type":"symbol",fileKind:q(e.relativePath),matches:[],focusLocations:[],matchedTerms:[],symbolMatchedTerms:[],symbolPhraseLength:0,identityMatchedTerms:[],rarity:0,symbolRarity:0}}function T0(e,t,n){let r=[...e].sort(Ge),i=[],o=new Map;for(let u of t)o.set(u.fromSymbol,(o.get(u.fromSymbol)??0)+1);let s=new Set,a=new Set,c=u=>{if(!(!u||i.some(d=>d.symbol===u.symbol))){i.push(u);for(let d of u.matchedTerms)s.add(d);for(let d of u.symbolMatchedTerms)a.add(d)}},l=r.filter(u=>u.symbolPhraseLength>=2&&(o.get(u.symbol)??0)>=2);for(;i.length<Math.min(2,Br);){let u=l.filter(d=>!i.some(m=>m.symbol===d.symbol)).sort((d,m)=>m.symbolMatchedTerms.filter(p=>!a.has(p)).length-d.symbolMatchedTerms.filter(p=>!a.has(p)).length||m.symbolPhraseLength-d.symbolPhraseLength||(o.get(m.symbol)??0)-(o.get(d.symbol)??0)||Ld(d,m))[0];if(!u||i.length>0&&u.symbolMatchedTerms.every(d=>a.has(d)))break;c(u)}if(c(r[0]),i.length>=2){let u=A0(i[0].symbol,i[1].symbol,t,n);for(let d of u?.slice(1,-1)??[]){if(i.length>=Br)break;c(n.get(d))}if(i.length<Br){let d=new Set(i.map(f=>f.symbol)),m=new Set(t.filter(f=>f.depth===1&&d.has(f.fromSymbol)&&d.has(f.toSymbol)).map(f=>f.fromSymbol)),p=t.filter(f=>f.depth===1&&m.has(f.fromSymbol)&&!d.has(f.toSymbol)).map(f=>({relation:f,candidate:n.get(f.toSymbol)})).filter(f=>f.candidate!==void 0&&f.candidate.symbolPhraseLength>=2&&f.candidate.symbolMatchedTerms.length>=2).sort((f,g)=>(o.get(f.relation.fromSymbol)??0)-(o.get(g.relation.fromSymbol)??0)||Ld(f.candidate,g.candidate))[0]?.candidate;c(p)}}else for(;i.length<Math.min(3,Br);){let u=r.filter(d=>!i.some(m=>m.symbol===d.symbol)).sort((d,m)=>m.matchedTerms.filter(p=>!s.has(p)).length-d.matchedTerms.filter(p=>!s.has(p)).length||Ge(d,m))[0];if(!u||u.matchedTerms.every(d=>s.has(d)))break;c(u)}for(;i.length>=2&&i.length<Br;){let u=new Set(i.map(m=>m.symbol)),d=[...n.values()].filter(m=>!u.has(m.symbol)&&(o.get(m.symbol)??0)>0&&t.some(p=>u.has(p.fromSymbol)&&p.toSymbol===m.symbol)).sort((m,p)=>p.identityMatchedTerms.length-m.identityMatchedTerms.length||p.symbolMatchedTerms.length-m.symbolMatchedTerms.length||p.matchedTerms.length-m.matchedTerms.length||(o.get(p.symbol)??0)-(o.get(m.symbol)??0)||Ge(m,p))[0];if(!d)break;c(d)}if(i.length<2){let u=i[0],d=u?r.filter(m=>m.symbol!==u.symbol).map(m=>({root:m,path:F0(m.symbol,u.symbol,t)})).filter(m=>m.path!==null).sort((m,p)=>+(p.root.file!==u.file)-+(m.root.file!==u.file)||m.path.length-p.path.length||Ge(m.root,p.root))[0]?.root:void 0;c(d)}return i}function A0(e,t,n,r){let i=new Map;for(let a of n){let c=i.get(a.fromSymbol)??new Set;c.add(a.toSymbol),i.set(a.fromSymbol,c);let l=i.get(a.toSymbol)??new Set;l.add(a.fromSymbol),i.set(a.toSymbol,l)}let o=[{path:[e],cost:0}],s=new Map([[e,0]]);for(;o.length>0;){o.sort((u,d)=>u.cost-d.cost||u.path.length-d.path.length);let{path:a,cost:c}=o.shift(),l=a.at(-1);if(l===t)return a;for(let u of i.get(l)??[]){let d=r.get(u),m=u===t?1:!d||d.matchedTerms.length===0?9:d.symbolPhraseLength>=2?1:d.identityMatchedTerms.length>=2?2:4,p=c+m;p>=(s.get(u)??Number.POSITIVE_INFINITY)||(s.set(u,p),o.push({path:[...a,u],cost:p}))}}return null}function F0(e,t,n){let r=new Map;for(let s of n){let a=r.get(s.fromSymbol)??[];a.push(s.toSymbol),r.set(s.fromSymbol,a)}let i=[[e]],o=new Set([e]);for(;i.length>0;){let s=i.shift(),a=s.at(-1);if(a===t)return s;for(let c of r.get(a)??[])o.has(c)||(o.add(c),i.push([...s,c]))}return null}function Ge(e,t){return(t.queryPathMatches?.length??0)-(e.queryPathMatches?.length??0)||t.identityMatchedTerms.length-e.identityMatchedTerms.length||t.matchedTerms.length-e.matchedTerms.length||t.rarity-e.rarity||Fi(e.kind)-Fi(t.kind)||Re(e.fileKind)-Re(t.fileKind)||e.file.localeCompare(t.file)||e.line-t.line}function Ld(e,t){return t.symbolPhraseLength-e.symbolPhraseLength||t.symbolMatchedTerms.length-e.symbolMatchedTerms.length||Fi(e.kind)-Fi(t.kind)||t.symbolRarity-e.symbolRarity||Ge(e,t)}function k0(e,t){return t.flatMap(n=>{let r=e.filter(s=>s.matchedTerms.includes(n)).sort((s,a)=>_0(s,a,n)),i=[],o=new Set;for(let s of r)if(!o.has(s.file)&&(i.push(s),o.add(s.file),i.length>=BS))return i;for(let s of r)if(!i.some(a=>a.symbol===s.symbol)&&(i.push(s),i.length>=BS))break;return i})}function N0(e,t,n){let r=new Set(t),i=new Map;for(let o of e){if(o.kind!=="callable")continue;let s=o.file.slice(o.file.lastIndexOf("/")+1).replace(/\.[^.]+$/u,"");if(![...at(s)].some(c=>r.has(c)))continue;let a=i.get(o.file)??[];a.push(o),i.set(o.file,a)}return[...i.entries()].map(([o,s])=>{let a=o.slice(o.lastIndexOf("/")+1).replace(/\.[^.]+$/u,""),c=[...at(a)].filter(l=>r.has(l));return{file:o,fileCandidates:s,sharedFrequency:Math.min(...c.map(l=>n.get(l)??Number.MAX_SAFE_INTEGER))}}).sort((o,s)=>Re(o.fileCandidates[0].fileKind)-Re(s.fileCandidates[0].fileKind)||o.sharedFrequency-s.sharedFrequency||o.file.localeCompare(s.file)).flatMap(({fileCandidates:o})=>[...o].sort(Ge).slice(0,t0)).slice(0,e0)}function _0(e,t,n){return WS(e,n)-WS(t,n)||Re(e.fileKind)-Re(t.fileKind)||t.symbolPhraseLength-e.symbolPhraseLength||Fi(e.kind)-Fi(t.kind)||Ge(e,t)}function WS(e,t){let n=e.matches.find(r=>r.term===t)?.sources??[];return Math.min(...n.map(Pd),Number.MAX_SAFE_INTEGER)}function Ai(e){return[...new Map(e.map(t=>[t.symbol,t])).values()]}function $r(e,t,n){let r=new Set(e.roots.flatMap(o=>o.symbolMatchedTerms)),i=new Set(t.roots.flatMap(o=>o.symbolMatchedTerms));return(t.queryPathMatches?.length??0)-(e.queryPathMatches?.length??0)||XS(e.kind)-XS(t.kind)||YS(e)-YS(t)||JS(e)-JS(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)||VS(t,n)-VS(e,n)||t.matchedTerms.length-e.matchedTerms.length||Math.max(...t.roots.map(o=>o.symbolPhraseLength))-Math.max(...e.roots.map(o=>o.symbolPhraseLength))||i.size-r.size||Ge(e.roots[0],t.roots[0])||t.roots.length-e.roots.length||e.relationCount-t.relationCount||e.id.localeCompare(t.id)}function VS(e,t){return e.matchedTerms.reduce((n,r)=>n+1/Math.max(1,t.get(r)??1),0)}function O0(e){return[...new Set(e.roots.flatMap(t=>t.queryPathMatches??[]))].sort()}function YS(e){let t=e.keyAnchors.length>0?e.keyAnchors:e.roots;return Math.max(...t.map(n=>Re(n.fileKind)))}function JS(e){return e.kind==="parallel-paths"?2-(e.parallelConnectedSides??0):e.kind!=="connected-flow"||e.relationCount>0?0:1}function B0(e,t,n){let r=e.slice(0,t);if(t<2||r.some(o=>o.kind==="shared-callee-owners"))return r;let i=e.filter(o=>o.kind==="shared-callee-owners");for(let o of r){if(o.kind==="shared-callee-owners"||o.kind==="parallel-paths")continue;let s=new Set($o(o)),a=i.map(l=>({group:l,overlap:$0(l,s)})).filter(({overlap:l})=>l>0).sort(({group:l,overlap:u},{group:d,overlap:m})=>m-u||$r(l,d,n))[0]?.group;if(!a)continue;let c=r.length-1;for(;c>=0&&r[c]===o;)c-=1;return c<0?r:(r[c]=a,[...r].sort((l,u)=>$r(l,u,n)))}return r}function $0(e,t){return $o(e).filter(n=>t.has(n)).length}function XS(e){switch(e){case"cross-boundary-flow":return 0;case"parallel-paths":case"connected-flow":return 1;case"shared-callee-owners":return 2}}function nn(e,t){return e.depth-t.depth||or(t.strength)-or(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 j0(e,t){return or(Dd(t.source))-or(Dd(e.source))||(e.callsiteLine??Number.MAX_SAFE_INTEGER)-(t.callsiteLine??Number.MAX_SAFE_INTEGER)||e.symbol.localeCompare(t.symbol)}function Ln(e){let t=new Map;for(let n of e){let r=`${n.fromSymbol}\0${n.toSymbol}`,i=t.get(r);(!i||nn(n,i)<0)&&t.set(r,n)}return[...t.values()]}function lc(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 H0(e){let t=e.match(/[\p{L}\d_.-]+(?:\/[\p{L}\d_.-]+)+/gu)??[];return[...new Set(t.map(n=>n.replace(/[.;:!?]+$/gu,"").toLocaleLowerCase()))]}function U0(e,t){let n=e.replace(/\\/gu,"/").toLocaleLowerCase();return t.filter(r=>{let i=n.indexOf(r);if(i<0)return!1;let o=i===0?"/":n[i-1],s=n[i+r.length];return o==="/"&&(s===void 0||s==="/")})}function q0(e,t){let n=lc(e).map(Td),r=0;for(let i=0;i<n.length;i+=1)for(let o=0;o<t.length;o+=1){let s=0;for(;i+s<n.length&&o+s<t.length&&n[i+s]===t[o+s];)s+=1;r=Math.max(r,s)}return r}function at(e){return new Set(lc(e).flatMap(nv).filter(t=>t.length>=3))}function nv(e){let t=Td(e);return t.length>4&&t.endsWith("e")?[t,t.slice(0,-1)]:[t]}function Td(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")?QS(t.slice(0,-2)):t.length>5&&t.endsWith("ing")?QS(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 QS(e){if(e.length<2)return e;let t=e.at(-1),n=e.at(-2);return t===n&&!"aeiou".includes(t)?e.slice(0,-1):e}function G0(e,t){return Pd(e)-Pd(t)}function Pd(e){switch(e){case"symbol":return 0;case"path":return 1;case"documentation":return 2;case"source":return 3}}function Fi(e){return e==="callable"?0:e==="type"?1:2}function Dd(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function or(e){return e==="exact"?2:1}function rv(e,t){return e.file.localeCompare(t.file)||e.line-t.line}function Bo(e){return`${e.file}:${e.line+1}`}function jo(e,t=[],n=[]){let r=e.map(s=>`--symbol ${cc(`${s.file}:${s.line+1}-${s.endLine+1}`)}`),i=new Set(e.map(s=>s.symbol)),o=e.flatMap(s=>(s.sourceCharacters??0)>Ed?z0(s,t,n,i).map(a=>`--focus-at ${cc(`${a.file}:${a.line+1}`)}`):[]);return`scip-query system-map ${[...r,...o,"--relation call","--relation runtime-boundary"].join(" ")}`}function z0(e,t,n,r){let i=new Set(n),o=t.filter(l=>l.fromSymbol===e.symbol&&l.callsiteLine!==null&&l.callsiteLine>=e.line&&l.callsiteLine<=e.endLine).map(l=>({file:e.file,line:l.callsiteLine,connectsAnchor:r.has(l.toSymbol),overlap:new Set(lc(K0(l.toLabel)).flatMap(nv).filter(u=>i.has(u))).size,strength:l.strength})).filter(l=>l.overlap>0).sort((l,u)=>Number(u.connectsAnchor)-Number(l.connectsAnchor)||u.overlap-l.overlap||l.line-u.line||or(u.strength)-or(l.strength)),s=o.filter(l=>l.connectsAnchor),a=[...s.length>0?s:o,...s.length>0?[]:e.focusLocations.map(l=>({...l,connectsAnchor:!1,overlap:0,strength:"derived"}))],c=[];for(let l of a)if(!c.some(u=>u.file===l.file&&u.line===l.line)&&(c.push({file:l.file,line:l.line}),c.length>=3))break;return c}function K0(e){return e.slice(Math.max(e.lastIndexOf(":"),e.lastIndexOf("."))+1)}function W0(e,t){let n=new Map;for(let[o,s]of e.matches)for(let a of s.locations.values()){if(a.file!==e.definition.relativePath||a.line<e.definition.startLine||a.line>e.definition.endLine)continue;let c=`${a.file}\0${a.line}`,l=n.get(c)??{...a,matchedTerms:new Set};l.matchedTerms.add(o),n.set(c,l)}let r=[...n.values()].sort((o,s)=>s.matchedTerms.size-o.matchedTerms.size||[...s.matchedTerms].reduce((a,c)=>a+1/Math.max(1,t.get(c)??1),0)-[...o.matchedTerms].reduce((a,c)=>a+1/Math.max(1,t.get(c)??1),0)||rv(o,s)),i=[];for(let o of r)if(!i.some(s=>s.file===o.file&&Math.abs(s.line-o.line)<8)&&(i.push(o),i.length>=3))break;return i.map(o=>({file:o.file,line:o.line,matchedTerms:[...o.matchedTerms].sort()}))}function V0(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(jo(e.slice(r,r+t)));return n}function cc(e){return`'${e.replaceAll("'",`'"'"'`)}'`}import{createHash as Iv}from"crypto";function Ho(e,t,n={}){let r=ne(e,t);if(!r)return null;let i=n.semantic!==!1,o=zn(e,r,{semantic:i,semanticEvidence:re}).filter(l=>Se(l.symbol)).slice(0,50),s=Mi(Dt(e,r,{limit:50,additive:!0,callableOnly:!0,semantic:i,semanticEvidence:re})),a=o.map(l=>({symbol:l.symbol,shortName:T(l.symbol),file:l.file,relationship:l.source!=="caller-map-inversion"?"reference-candidate":l.callEvidence==="scip-chunk"?"chunk-candidate":"resolved-call",evidenceStrength:l.source==="caller-map-inversion"&&l.callEvidence!=="scip-chunk"?"exact":"candidate",evidenceSource:l.callEvidence??l.source})),c=s.map(l=>({symbol:l.symbol,shortName:T(l.symbol),file:l.file,relationship:l.source==="scip-chunk"?"chunk-candidate":"resolved-call",evidenceStrength:l.source==="scip-chunk"?"candidate":"exact",evidenceSource:l.source}));return{symbol:r.symbol,shortName:T(r.symbol),callers:a.map(({symbol:l,shortName:u,file:d})=>({symbol:l,shortName:u,file:d})),callees:c.map(({symbol:l,shortName:u,file:d})=>({symbol:l,shortName:u,file:d})),callerEvidence:a,calleeEvidence:c,coverage:{scope:"indexed-static-call-graph",blindSpots:["unresolved dynamic dispatch and reflection","external or unindexed callees without a resolved symbol identity","SCIP chunk co-occurrence is retained only as candidate call evidence"]}}}function Uo(e,t){let n=pt(e,t);return n?Bn(e,"forward",[n]).filter(i=>!e.isIgnored(i)).map(i=>({relativePath:i,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):[]}function qo(e,t){let n=pt(e,t);return n?Bn(e,"reverse",[n]).filter(i=>!e.isIgnored(i)).map(i=>({relativePath:i,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):[]}function Ad(e,t,n={}){let r=uc(e,t,n);return{definitions:r.definitions,referencedBy:r.referencedBy}}function uc(e,t,n={}){let r=ne(e,t);if(!r)return{definitions:[],referencedBy:[],referenceEvidence:[],claimSupport:null};let i=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",r.symbolId),o=ui(i?.documentation??null),s=e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,signature:eN(o,i?.display_name??null,r.symbol),source:Z0(e,r.relativePath,r.startLine,r.endLine)}],a=n.referenceContext??2,c=zf(e,r,{semantic:n.semantic,semanticEvidence:re}).map(u=>{let d=Xg(e,u.file,u.line,a,z(r.symbol));return{relativePath:u.file,line:u.line,enclosingSymbol:u.enclosingSymbol,enclosingShort:u.enclosingSymbol?T(u.enclosingSymbol):"(top-level)",provenance:u.provenance,sourceStartLine:d?.startLine??null,sourceEndLine:d?.endLine??null,source:d?.source??null,sourceKind:d?.kind??"unavailable"}}),l=c.map(Y0);return{definitions:s,referencedBy:l,referenceEvidence:c.map(u=>({relativePath:u.relativePath,line:u.line,provenance:u.provenance,sourceKind:u.sourceKind})),claimSupport:J0(c)}}function Y0(e){return{relativePath:e.relativePath,line:e.line,enclosingSymbol:e.enclosingSymbol,enclosingShort:e.enclosingShort,sourceStartLine:e.sourceStartLine,sourceEndLine:e.sourceEndLine,source:e.source}}function J0(e){let t="resolved source-attributed or SCIP-indexed references to this exact symbol",n=["Dynamic dispatch, reflection, generated calls, and unindexed source are outside this scope."],r=e.filter(o=>o.sourceKind!=="complete-call-expression"&&o.sourceKind!=="non-call-reference"),i="direct, statically visible call expressions among the resolved reference sites";return{referenceAbsence:{status:"eligible",scope:t,limitations:n},callsitePredicates:r.length===0?{status:"eligible",scope:i,limitations:n}:{status:"ineligible",scope:i,reason:`${r.length} reference site(s) lack one unambiguous complete call expression.`,followup:X0(r)}}}function X0(e){let t=[...new Set(e.map(n=>`${n.relativePath}:${n.line+1}`))];return t.length===0||t.length>24?null:`scip-query inspect ${t.map(n=>`--at ${Q0(n)}`).join(" ")} --view behavior`}function Q0(e){return`'${e.replaceAll("'","'\\''")}'`}function Z0(e,t,n,r){let i=W(e,t);if(!i)return null;let s=i.split(`
71
- `).slice(n,r+1).join(`
72
- `).trimEnd();return s.length>0?s:null}function eN(e,t,n){let r=li(e);if(r&&!tN(r))return r;let i=(t??"").trim();return i?Se(n)&&!i.endsWith("()")?`${i}()`:i:T(n)}function tN(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function Fd(e,t,n={}){let r=sv(e,t,n);if(r.kind!=="matched")return r;let{referenceEvidence:i,claimSupport:o,...s}=r;return s}function sv(e,t,n={}){let r=Qe(e,t);if(!r.match)return{kind:"missing",query:t};if(r.total>1)return{kind:"ambiguous",query:t,total:r.total,candidates:[{symbol:r.match.symbol,shortName:T(r.match.symbol),relativePath:r.match.relativePath,startLine:r.match.startLine},...r.candidates]};let i=r.match,o=rN(n.parts),s=o.includes("definition")||o.includes("references")?uc(e,i.symbol,{semantic:n.semantic,referenceContext:n.referenceContext}):{definitions:[],referencedBy:[],referenceEvidence:[],claimSupport:null},a=o.includes("callers")||o.includes("callees")?Ho(e,i.symbol,{semantic:n.semantic}):null,c=n.relatedSourceLines??80;return{kind:"matched",query:t,symbol:i.symbol,shortName:T(i.symbol),file:i.relativePath,parts:o,definition:o.includes("definition")?th(e,i.symbol):null,referenceWindows:o.includes("references")?nN(e,s.referencedBy):[],callers:o.includes("callers")?ov(e,a?.callers??[],c):[],callees:o.includes("callees")?ov(e,a?.callees??[],c):[],dependencies:o.includes("dependencies")?Uo(e,i.relativePath):[],consumers:o.includes("consumers")?qo(e,i.relativePath):[],referenceEvidence:s.referenceEvidence,claimSupport:s.claimSupport}}function nN(e,t){let n=t.filter(i=>i.sourceStartLine!==null&&i.sourceEndLine!==null&&i.source!==null).sort((i,o)=>i.relativePath.localeCompare(o.relativePath)||i.sourceStartLine-o.sourceStartLine||i.line-o.line),r=[];for(let i of n){let o=r[r.length-1];if(o&&o.relativePath===i.relativePath&&i.sourceStartLine<=o.endLine+1){o.endLine=Math.max(o.endLine,i.sourceEndLine),o.references.push(iv(i)),o.source=V(e,o.relativePath).slice(o.startLine,o.endLine+1).join(`
73
- `);continue}r.push({relativePath:i.relativePath,startLine:i.sourceStartLine,endLine:i.sourceEndLine,source:i.source,references:[iv(i)]})}return r}function iv(e){return{line:e.line,enclosingSymbol:e.enclosingSymbol,enclosingShort:e.enclosingShort}}function rN(e){let t=e&&e.length>0?e:["definition","references"];return[...new Set(t)]}function ov(e,t,n){let r=[],i=new Set;for(let o of t){if(i.has(o.symbol))continue;i.add(o.symbol);let s=(o.file?U(e,o.file).find(c=>c.symbol===o.symbol):void 0)??Qe(e,o.symbol).match;if(!s)continue;let a=Qg(e,s.relativePath,s.startLine,s.endLine,n);a&&r.push({...a,symbol:o.symbol,shortName:o.shortName,omittedLines:Math.max(0,s.endLine-a.endLine)})}return r}var dv=6;function av(e,t,n){return`${e}\0${t}\0${n??t}`}function mv(e,t,n,r={}){let i=r.limit??dv;if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`next-anchor limit must be a positive safe integer; received ${i}`);let o=r.sourceAllowed??(()=>!0),s=new Map(t.nodes.map(E=>[E.id,E])),a=new Set(n.steps.map(E=>E.nodeId)),c=new Set(n.steps.flatMap(E=>{let I=Nd(s.get(E.nodeId));return I?[I]:[]})),l=new Set;for(let E of n.steps)for(let I of E.behavior?.supportingDeclarations??[])c.add(I.symbol),l.add(av(I.file,I.line,I.endLine));let u=E=>E.symbol!==null&&c.has(E.symbol)||l.has(av(E.file,E.line,E.endLine)),d=new Map(n.steps.flatMap(E=>{if(!E.location)return[];let I=Nd(s.get(E.nodeId));if(!I)return[];let w=U(e,E.location.file).find(A=>A.symbol===I);return w?[[E.id,w]]:[]})),m=new H(e).calleeMap([...d.values()],{additive:!1,semantic:!0}),p=[],f=new Set,g=new Set,h=0,b=0,S=0,y=0,x=0,v=0,C=0,R=0;for(let E of n.steps){if(!E.location||!E.behavior)continue;let I=iN(E,{db:e,topology:t,nodeById:s,returnedNodeIds:a,sourceAllowed:o,alternativeAlreadyReturned:u});p.push(...I.candidates),v+=I.upstreamCandidates,R+=I.runtimeCandidates,C+=I.resultCandidates;let w=oN(E,{db:e,topology:t,nodeById:s,returnedNodeIds:a,sourceAllowed:o,alternativeAlreadyReturned:u},f);p.push(...w);let A=sN(E,{db:e,topology:t,nodeById:s,returnedNodeIds:a,sourceAllowed:o,alternativeAlreadyReturned:u},{evidencedCallsiteKeys:f,consideredCandidateKeys:g,calleeMap:m,stepDefinition:d.get(E.id)});p.push(...A.candidates),h+=A.scannedBehaviorSteps,b+=A.visibleCallsites,S+=A.identityCandidateCallsites,y+=A.ambiguousCallsites,x+=A.unresolvedCallsites}return hv(e,p,n.steps,i,{scannedBehaviorSteps:h,visibleCallsites:b,graphEvidencedCallsites:f.size,identityCandidateCallsites:S,ambiguousCallsites:y,unresolvedCallsites:x,upstreamCandidates:v,resultCandidates:C,runtimeCandidates:R},r.selectionTerms)}function iN(e,t){let n=[],r=0,i=0,o=0;if(!e.location||!e.behavior)return{candidates:n,upstreamCandidates:r,resultCandidates:i,runtimeCandidates:o};let s=t.topology.edges.filter(c=>["call","runtime-boundary"].includes(c.kind)&&(c.fromNodeId===e.nodeId||c.toNodeId===e.nodeId)&&c.disposition!=="excluded"&&c.disposition!=="unsupported");for(let c of s){let l=c.toNodeId===e.nodeId,u=l?c.fromNodeId:c.toNodeId;if(t.returnedNodeIds.has(u))continue;let d=t.nodeById.get(u);if(!d?.location||!t.sourceAllowed(d.location.file))continue;let m=c.kind==="call"?_d(t.db,d):$d(d);if(!m||t.alternativeAlreadyReturned(m))continue;let p=Od(c,d.location.file)??d.location,f=V(t.db,p.file)[p.line]?.trim(),g=l?"upstream":"downstream",h=c.kind==="runtime-boundary"?l?"runtime-producer":"runtime-consumer":l?"caller":"callee",b=Bd(c.evidence),S=zo(d);n.push({anchor:{id:sr(e.id,p.line,d.id),status:b,source:"graph-relation",direction:g,causalRole:h,relationKind:c.kind,fromStepId:e.id,fromLabel:e.label,callsite:{file:p.file,line:p.line,endLine:p.endLine??p.line,text:f||`${d.label} \u2192 ${e.label}`,signals:["call"],calleeLeaf:S},alternatives:[m],alternativeCount:1,evidence:c.evidence}}),l&&(r+=1),c.kind==="runtime-boundary"&&(o+=1)}let a=t.topology.edges.filter(c=>c.kind==="reference"&&c.fromNodeId===e.nodeId&&c.disposition!=="excluded"&&c.disposition!=="unsupported"&&!t.returnedNodeIds.has(c.toNodeId));for(let c of a){let l=t.nodeById.get(c.toNodeId);if(!l?.location||!t.sourceAllowed(l.location.file))continue;let u=_d(t.db,l);if(!u||t.alternativeAlreadyReturned(u))continue;let d=zo(l),m=Od(c,e.location.file)?.line,p=e.behavior.lines.find(h=>(m===void 0||m>=h.line&&m<=h.endLine)&&h.text.includes(d));if(!p)continue;let f=fv(p.signals),g=Bd(c.evidence);n.push({anchor:{id:sr(e.id,p.line,l.id),status:g,source:"graph-relation",direction:"downstream",causalRole:f,relationKind:"reference",fromStepId:e.id,fromLabel:e.label,callsite:{file:e.location.file,line:p.line,endLine:p.endLine,text:p.text,signals:p.signals,calleeLeaf:d},alternatives:[u],alternativeCount:1,evidence:c.evidence}}),f==="result-callback"&&(i+=1)}return{candidates:n,upstreamCandidates:r,resultCandidates:i,runtimeCandidates:o}}function oN(e,t,n){let r=[];if(!e.location)return r;let i=In(t.db,e.location.file,e.location.line,e.location.endLine??e.location.line),o=V(t.db,e.location.file),s=Sn(t.db,e.location.file,e.location.line,e.location.endLine??e.location.line);for(let a of i.targets){if(!t.sourceAllowed(a.definition.relativePath))continue;let c=Hr(e.location.file,a.sourceLine,a.calleeLeaf);if(n.has(c))continue;n.add(c);let l=kd(s.get(a.sourceLine)),u={symbol:a.definition.symbol,label:a.definition.leaf,file:a.definition.relativePath,line:a.definition.startLine,endLine:a.definition.endLine};t.alternativeAlreadyReturned(u)||r.push({anchor:{id:sr(e.id,a.sourceLine,a.definition.symbol),status:"exact",source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:e.id,fromLabel:e.label,callsite:{file:e.location.file,line:a.sourceLine,endLine:a.sourceLine,text:o[a.sourceLine]?.trim()||`${a.calleeLeaf}()`,signals:l,calleeLeaf:a.calleeLeaf},alternatives:[u],alternativeCount:1,evidence:[{method:"scip-occurrence-callsite",strength:"exact",identity:a.definition.symbol,location:{file:e.location.file,line:a.sourceLine}}]}})}return r}function sN(e,t,n){let r={candidates:[],scannedBehaviorSteps:0,visibleCallsites:0,identityCandidateCallsites:0,ambiguousCallsites:0,unresolvedCallsites:0};if(!e.location||!e.behavior)return r;let i=e.behavior.lines.filter(f=>f.signals.includes("call"));if(i.length===0)return r;let o=[],s=0,a=0,c=0,l=(K(t.db,e.location.file)?.callSites??[]).filter(f=>i.some(g=>f.line>=g.line&&f.line<=g.endLine)),u=t.topology.edges.filter(f=>f.kind==="call"&&f.fromNodeId===e.nodeId&&f.disposition!=="excluded"&&f.disposition!=="unsupported"),d=new Map;for(let f of u){let g=t.nodeById.get(f.toNodeId);if(!g)continue;let h=zo(g);d.set(h,(d.get(h)??0)+1)}let m=cN(t.db,n.stepDefinition?n.calleeMap.get(n.stepDefinition.symbolId)??[]:[]),p=lN(m);for(let f of m){if(!t.sourceAllowed(f.alternative.file)||t.alternativeAlreadyReturned(f.alternative))continue;let g=qe(f.alternative.label),h=lv(l,i,g,f.row.callsiteLine,p.get(g)===1);if(!h)continue;let b=Go(i,h.line,g);if(!b)continue;let S=Hr(e.location.file,h.line,g);if(n.evidencedCallsiteKeys.has(S))continue;n.evidencedCallsiteKeys.add(S);let y=bv(f.row.source);o.push({anchor:{id:sr(e.id,h.line,f.alternative.symbol??f.alternative.file),status:y,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:e.id,fromLabel:e.label,callsite:{file:e.location.file,line:b.line,endLine:b.endLine,text:b.text,signals:b.signals,calleeLeaf:g},alternatives:[f.alternative],alternativeCount:1,evidence:[{method:f.row.source,strength:y,identity:f.row.symbol,location:{file:e.location.file,line:h.line}}]}})}for(let f of u){if(t.returnedNodeIds.has(f.toNodeId))continue;let g=t.nodeById.get(f.toNodeId);if(!g?.location||!t.sourceAllowed(g.location.file))continue;let h=zo(g),b=f.evidence.find(R=>{let E=R.location;return E!==null&&E.file===e.location?.file&&E.line>=0})?.location?.line,S=lv(l,i,h,b,d.get(h)===1);if(!S)continue;let y=Go(i,S.line,h);if(!y)continue;let x=Hr(e.location.file,S.line,h);if(n.evidencedCallsiteKeys.has(x))continue;n.evidencedCallsiteKeys.add(x);let v=$d(g);if(!v||t.alternativeAlreadyReturned(v))continue;let C=Bd(f.evidence);o.push({anchor:{id:sr(e.id,S.line,g.id),status:C,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:e.id,fromLabel:e.label,callsite:{file:e.location.file,line:y.line,endLine:y.endLine,text:y.text,signals:y.signals,calleeLeaf:h},alternatives:[v],alternativeCount:1,evidence:f.evidence}})}for(let f of l){let g=Hr(e.location.file,f.line,f.calleeLeaf);if(n.evidencedCallsiteKeys.has(g))continue;let h=Go(i,f.line,f.calleeLeaf);if(!h)continue;let b=Ot(e.location.file,Kt(t.db).get(f.calleeLeaf)??[]).flatMap(v=>U(t.db,v.file).filter(C=>C.symbol===v.symbol&&C.isFunctionLike)).filter(v=>t.sourceAllowed(v.relativePath)&&!t.alternativeAlreadyReturned({symbol:v.symbol,label:v.leaf,file:v.relativePath,line:v.startLine,endLine:v.endLine})),S=mc(b.map(v=>({symbol:v.symbol,label:v.leaf??f.calleeLeaf,file:v.relativePath,line:v.startLine,endLine:v.endLine})));if(S.length===0){c+=1;continue}let y=`${e.id}\0${f.line}\0${f.calleeLeaf}`;if(n.consideredCandidateKeys.has(y))continue;n.consideredCandidateKeys.add(y);let x=S.length>1;x?a+=1:s+=1,o.push({anchor:{id:sr(e.id,f.line,f.calleeLeaf),status:x?"ambiguous":"candidate",source:"leaf-identity-candidate",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:e.id,fromLabel:e.label,callsite:{file:e.location.file,line:h.line,endLine:h.endLine,text:h.text,signals:h.signals,calleeLeaf:f.calleeLeaf},alternatives:S.slice(0,3),alternativeCount:S.length,evidence:[]}})}return{candidates:o,scannedBehaviorSteps:1,visibleCallsites:l.length,identityCandidateCallsites:s,ambiguousCallsites:a,unresolvedCallsites:c}}function pv(e,t,n){let r=new Map(t.nodes.map(i=>[i.id,i]));for(let i of n.steps)if(!(!i.behavior||!i.location))for(let o of t.edges){if(o.kind!=="reference"||o.fromNodeId!==i.nodeId||o.disposition==="excluded"||o.disposition==="unsupported")continue;let s=r.get(o.toNodeId);if(!s?.location||!_d(e,s))continue;let a=zo(s),c=Od(o,i.location.file)?.line,l=i.behavior.lines.find(u=>(c===void 0||c>=u.line&&c<=u.endLine)&&u.text.includes(a));!l||fv(l.signals)!=="result-callback"||o.semantics?.some(({family:u,subtype:d})=>u==="control"&&d==="result-callback")||(o.semantics=[...o.semantics??[],{family:"control",subtype:"result-callback",attributes:{evidenceRole:"result-producing-callable-reference"}}])}}function fv(e){return e.includes("call")&&e.some(t=>["return","mutation","shape","spread","binding"].includes(t))?"result-callback":"callable-reference"}function gv(e,t,n={}){let r=n.limit??dv;if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`next-anchor limit must be a positive safe integer; received ${r}`);let i=n.sourceAllowed??(()=>!0),o=[],s=t.map((p,f)=>({id:p.id,nodeId:p.id,order:f,role:"anchor",kind:"source-construct",label:p.label,location:{file:p.file,line:p.startLine,endLine:p.endLine},behavior:null})),a=t.map(p=>({file:p.file,startLine:p.startLine,endLine:p.endLine})),c=0,l=0,u=0,d=0,m=0;for(let p of t){let f=V(e,p.file),h=(K(e,p.file)?.callSites??[]).filter(C=>C.line>=p.startLine&&C.line<=p.endLine);c+=h.length;let b=Sn(e,p.file,p.startLine,p.endLine),S=In(e,p.file,p.startLine,p.endLine),y=new Set;for(let C of S.targets){if(!i(C.definition.relativePath)||a.some(w=>w.file===C.definition.relativePath&&w.startLine<=C.definition.startLine&&w.endLine>=C.definition.endLine))continue;let R=Hr(p.file,C.sourceLine,C.calleeLeaf);y.add(R);let E=kd(b.get(C.sourceLine)),I={symbol:C.definition.symbol,label:C.definition.leaf,file:C.definition.relativePath,line:C.definition.startLine,endLine:C.definition.endLine};o.push({anchor:{id:sr(p.id,C.sourceLine,C.definition.symbol),status:"exact",source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:p.id,fromLabel:p.label,callsite:{file:p.file,line:C.sourceLine,endLine:C.sourceLine,text:f[C.sourceLine]?.trim()||`${C.calleeLeaf}()`,signals:E,calleeLeaf:C.calleeLeaf},alternatives:[I],alternativeCount:1,evidence:[{method:"scip-occurrence-callsite",strength:"exact",identity:C.definition.symbol,location:{file:p.file,line:C.sourceLine}}]}})}l+=S.resolvedCallsites;let x=rr(e,p.file,{ranges:[{startLine:p.startLine,endLine:p.endLine}]}),v=new Map;for(let C of x.targets){let R=h.find(w=>w.line===C.line)?.calleeLeaf??C.calleeLeaf,E=Hr(p.file,C.line,R),I=v.get(E)??[];I.push(C),v.set(E,I)}for(let[C,R]of v){if(y.has(C))continue;y.add(C);let E=R.filter(L=>i(L.targetFile)&&!a.some(F=>F.file===L.targetFile&&F.startLine<=L.targetStartLine&&F.endLine>=L.targetEndLine));if(E.length===0)continue;let I=E[0],w=h.find(L=>L.line===I.line)?.calleeLeaf??I.calleeLeaf,A=kd(b.get(I.line)),D=mc(E.map(L=>({symbol:L.targetSymbol??null,label:L.calleeLeaf,file:L.targetFile,line:L.targetStartLine,endLine:L.targetEndLine}))),k=E.some(L=>(L.resolutionAlternativeCount??0)>1)?"candidate":E.every(L=>L.strength==="exact")?"exact":"derived";o.push({anchor:{id:sr(p.id,I.line,D.map(L=>`${L.file}:${L.line}`).join("|")),status:D.length>1?"ambiguous":k,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:p.id,fromLabel:p.label,callsite:{file:p.file,line:I.line,endLine:I.line,text:f[I.line]?.trim()||`${I.calleeLeaf}()`,signals:A,calleeLeaf:w},alternatives:D.slice(0,3),alternativeCount:D.length,evidence:E.map(L=>({method:L.resolution==="constructed-member-receiver"?"ast-constructed-member-callsite":L.resolution==="factory-callback-member"?"ast-factory-callback-callsite":L.resolution==="imported-service-object-member"?"ast-service-member-callsite":"ast-import-member-callsite",strength:k,identity:L.targetSymbol??`${L.targetFile}:${L.targetStartLine}-${L.targetEndLine}`,location:{file:p.file,line:I.line}}))}})}l+=v.size;for(let C of h){let R=Hr(p.file,C.line,C.calleeLeaf);y.has(R)||(m+=1)}}return hv(e,o,s,r,{scannedBehaviorSteps:t.length,visibleCallsites:c,graphEvidencedCallsites:l,identityCandidateCallsites:u,ambiguousCallsites:d,unresolvedCallsites:m,upstreamCandidates:0,resultCandidates:0,runtimeCandidates:0})}function hv(e,t,n,r,i,o=[]){let s=uN(t).sort(yv),a=s.filter(f=>aN(e,f)).slice(0,r),c=new Set(a.map(f=>f.anchor.id)),l=s.filter(f=>!c.has(f.anchor.id)),u=a.map(f=>f.anchor),d=l.map(f=>f.anchor),m=mc(u.flatMap(f=>f.alternativeCount===1?f.alternatives:[])),p=mc(d.flatMap(f=>f.alternativeCount===1?f.alternatives:[]));return{anchors:u,withheldAnchors:d,candidateAnchors:s.length,omittedAnchors:Math.max(0,s.length-u.length),...i,inspectCommand:m.length===0?null:`scip-query inspect ${m.map(uv).join(" ")} --view behavior`,remainingInspectCommands:mN(p,8).map(f=>`scip-query inspect ${f.map(uv).join(" ")} --view behavior`)}}function yv(e,t){let n=e.anchor.alternatives[0],r=t.anchor.alternatives[0];return dc(e.anchor.status)-dc(t.anchor.status)||(e.anchor.direction??"").localeCompare(t.anchor.direction??"")||(e.anchor.relationKind??"").localeCompare(t.anchor.relationKind??"")||(e.anchor.causalRole??"").localeCompare(t.anchor.causalRole??"")||e.anchor.fromStepId.localeCompare(t.anchor.fromStepId)||e.anchor.callsite.file.localeCompare(t.anchor.callsite.file)||e.anchor.callsite.line-t.anchor.callsite.line||(n?.file??"").localeCompare(r?.file??"")||(n?.line??0)-(r?.line??0)||e.anchor.id.localeCompare(t.anchor.id)}function aN(e,t){if(t.anchor.alternativeCount!==1)return!0;let n=t.anchor.alternatives[0],r=n.endLine??n.line;return V(e,n.file).slice(n.line,r+1).join(`
74
- `).length<=2e4}function kd(e){return e?.includes("call")?[...e]:["call",...e??[]]}function cN(e,t){let n=new Map;for(let r of t){let i=U(e,r.file).find(a=>a.symbol===r.symbol&&a.isFunctionLike);if(!i)continue;let o={symbol:i.symbol,label:i.leaf,file:i.relativePath,line:i.startLine,endLine:i.endLine},s=n.get(i.symbol);!s||cv(r.source)>cv(s.row.source)?n.set(i.symbol,{row:{...r,...r.callsiteLine===void 0&&s?.row.callsiteLine!==void 0?{callsiteLine:s.row.callsiteLine}:{}},alternative:o}):s.row.callsiteLine===void 0&&r.callsiteLine!==void 0&&n.set(i.symbol,{...s,row:{...s.row,callsiteLine:r.callsiteLine}})}return[...n.values()]}function lN(e){let t=new Map;for(let n of e){let r=qe(n.alternative.label);t.set(r,(t.get(r)??0)+1)}return t}function bv(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function cv(e){return bv(e)==="exact"?2:1}function Go(e,t,n){return e.find(r=>t>=r.line&&t<=r.endLine&&r.text.includes(n))??e.find(r=>t>=r.line&&t<=r.endLine)??null}function lv(e,t,n,r,i){if(r!==void 0)return e.find(s=>s.line===r&&s.calleeLeaf===n&&Go(t,s.line,n)!==null)??null;let o=e.filter(s=>s.calleeLeaf===n&&Go(t,s.line,s.calleeLeaf)!==null);return i&&o.length===1?o[0]:null}function zo(e){let t=e.attributes.leaf;if(typeof t=="string"&&t.length>0)return qe(t);let n=e.label.slice(e.label.lastIndexOf(":")+1);return qe(n)}function Nd(e){if(e?.kind!=="symbol"||!e.id.startsWith("symbol:"))return null;try{return decodeURIComponent(e.id.slice(7))}catch{return null}}function $d(e){return e.location?{symbol:Nd(e),label:e.label,file:e.location.file,line:e.location.line,endLine:e.location.endLine??null}:null}function _d(e,t){let n=$d(t);return n?.symbol&&U(e,n.file).some(i=>i.symbol===n.symbol&&i.isFunctionLike)?n:null}function Od(e,t){return e.evidence.find(n=>n.location?.file===t)?.location??e.evidence.find(n=>n.location!==null)?.location??null}function Bd(e){let t={exact:5,derived:4,mixed:3,candidate:2,unknown:1};return e.reduce((n,r)=>t[r.strength]>t[n]?r.strength:n,"unknown")}function uN(e){let t=new Map;for(let n of e){let i=n.anchor.alternatives[0]?.symbol??`${n.anchor.callsite.file}:${n.anchor.callsite.line}:${n.anchor.callsite.calleeLeaf}`,o=t.get(i);(!o||dN(n,o)<0)&&t.set(i,n)}return[...t.values()]}function dN(e,t){return dc(e.anchor.status)-dc(t.anchor.status)||e.anchor.alternativeCount-t.anchor.alternativeCount||yv(e,t)}function dc(e){return{exact:0,derived:1,mixed:2,candidate:3,unknown:4,ambiguous:5}[e]}function mc(e){let t=new Map;for(let n of e)t.set(n.symbol??`${n.file}:${n.line}`,n);return[...t.values()].sort((n,r)=>n.file.localeCompare(r.file)||n.line-r.line||n.label.localeCompare(r.label))}function uv(e){return`--at ${pN(`${e.file}:${e.line+1}`)}`}function mN(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function pN(e){return`'${e.replaceAll("'","'\\''")}'`}function Hr(e,t,n){return`${e}\0${t}\0${n}`}function sr(e,t,n){return["next-anchor",e,String(t),n].map(encodeURIComponent).join(":")}var wv=6,fN=12,gN=48,hN=2e4,Sv=12,Ur=Number.MAX_SAFE_INTEGER,yN=["definition","callers","callees"],qd={search:12,"exact-source":24,definition:24,caller:8,callee:8,"production-reference":6,"test-reference":2,dependency:6,consumer:6};function bN(e,t){if(t.cursor)throw new Error("Inspect no longer accepts semantic packet cursors. Run the original inspect selectors again.");let n=vN(t),r=RN(e,n),i=r.candidates.sort((D,k)=>jd(D,k));n.view==="behavior"&&wN(e,i),LN(e,i),n.view==="behavior"&&EN(e,i);let o=oS(i.map(D=>Hd(D,n.view)),n.evidenceBudgets,(D,k)=>jd(D.candidate,k.candidate)),{selected:s,omitted:a}=Xa(o.selected,n.maxUnits,n.maxCharacters,(D,k)=>jd(D.candidate,k.candidate),n.view==="source"),c=s.map(D=>D.candidate),l=[...o.omitted,...a].map(D=>D.candidate),u=c.map(_N),d=sa(c.map(D=>D.kind==="source"?D.bindingClosure:void 0),c.filter(D=>D.kind==="source").map(D=>({relativePath:D.relativePath,startLine:D.startLine,endLine:D.endLine}))),m=u.reduce((D,k)=>D+(k.kind==="source"?$N(k.source):0),0),p=u.reduce((D,k)=>D+(k.kind==="source"?k.source.length:0),0),f=u.reduce((D,k)=>D+Dv(k,n.view),0),g=u.filter(D=>D.kind==="source"&&(D.roles.includes("search")||D.roles.includes("location"))).map(ON),h=i.filter(D=>D.kind==="source"&&(D.roles.includes("search")||D.roles.includes("location"))).length,b=u.filter(D=>D.kind==="source"&&(D.roles.includes("search")||D.roles.includes("location"))).length,S=r.searches.map(D=>MN(D,i,c)),y=TN(l),x=r.locations.every(D=>D.matched)&&r.evidence.every(D=>D.kind==="matched")&&r.searches.every(D=>FN(D.textCoverage))&&l.every(D=>!D.roles.some(k=>k==="location"||k==="definition")),v=S.reduce((D,k)=>D+k.omittedMatches,0),C=l.length===0&&v===0,R=C?void 0:Pv(n,!0),E=PN(n,l),I=SN(C,x,l.length+v,E,S,R),w=i.filter(D=>n.view==="behavior"&&D.kind==="source"&&D.roles.some(k=>k==="location"||k==="definition"||k==="search")).map(D=>({id:`inspect:${D.relativePath}:${D.startLine}-${D.endLine}`,label:D.ownerShort??`${D.relativePath}:${D.startLine+1}`,file:D.relativePath,startLine:D.startLine,endLine:D.endLine})),A=w.length>0?gv(e,w):void 0;return{searches:S,evidence:r.evidence,locations:r.locations,slices:g,candidateSlices:h,omittedSlices:h-b,maxSlices:h,maxTotalLines:m,units:u,candidateUnits:i.length,omittedUnits:l.length,maxUnits:n.maxUnits,maxCharacters:n.maxCharacters,returnedLines:m,returnedCharacters:p,returnedViewCharacters:f,view:n.view,omissionGroups:E,packetCoverage:{mode:C?"complete":"bounded",candidateUnits:i.length,returnedUnits:u.length,omittedUnits:l.length,omittedByRole:y,exactSelectorsComplete:x,maxUnits:n.maxUnits,maxCharacters:n.maxCharacters,channels:AN(i,c,n.evidenceBudgets,n.view),...R?{expansionCommand:R}:{}},stoppingSummary:I,...A&&A.candidateAnchors>0?{causalFrontier:A}:{},bindingClosure:d,continuation:null}}function SN(e,t,n,r,i,o){let s=ct([...r.map(a=>a.drillCommand),...i.flatMap(a=>a.exactFollowup?[a.exactFollowup]:[]),...o?[o]:[]]);return e&&t?{queryStatus:"selection-complete",status:"stop-ready",openEvidence:0,guidance:"All evidence requested by this inspect query was materialized.",drillCommands:[]}:t?{queryStatus:"frontier-accounted",status:"relevance-check-required",openEvidence:n,guidance:"Withheld evidence is accounted for by recoverable groups; drill the groups relevant to the current decision.",drillCommands:s}:{queryStatus:"coverage-incomplete",status:"exact-evidence-withheld",openEvidence:n,guidance:"A requested identity, exact source unit, or current-text coverage requirement is unresolved; drill before relying on it.",drillCommands:s}}function vN(e){let t=ke(e.searches),n=ke(e.symbols),r=ke(e.locations),i=t.length+n.length+r.length;if(i===0)throw new Error("inspect requires at least one --search, --symbol, or --at selector.");if(i>24)throw new RangeError(`inspect accepts at most ${24} selectors; received ${i}.`);let o=e.evidence??{};if(e.unitLines!==void 0&&ar(e.unitLines,"unitLines"),e.totalLines!==void 0&&ar(e.totalLines,"totalLines"),e.sliceLimit!==void 0&&ar(e.sliceLimit,"sliceLimit"),e.maxCharacters!==void 0&&ar(e.maxCharacters,"maxCharacters"),e.maxUnits!==void 0&&ar(e.maxUnits,"maxUnits"),e.view!==void 0&&e.view!=="source"&&e.view!=="behavior")throw new Error(`Unknown inspect view: ${String(e.view)}. Use source or behavior.`);if(e.full&&(e.searchLimit!==void 0||e.maxUnits!==void 0||e.maxCharacters!==void 0||e.evidenceBudgets!==void 0))throw new Error("full inspect cannot be combined with searchLimit, maxUnits, maxCharacters, or evidenceBudgets.");let s=e.full??!1;return{searches:t,symbols:n,locations:r,...e.scope?.trim()?{scope:e.scope.trim()}:{},context:Ev(e.context??wv,"context"),searchLimit:ar(e.searchLimit??(s?Ur:fN),"searchLimit"),maxUnits:ar(s?Ur:e.maxUnits??gN,"maxUnits"),maxCharacters:ar(s?Ur:e.maxCharacters??hN,"maxCharacters"),evidenceBudgets:s?xN():CN(e.evidenceBudgets??qd),view:e.view??"source",evidence:{...o.parts?{parts:[...o.parts]}:n.length>0?{parts:[...yN]}:{},...o.referenceContext!==void 0?{referenceContext:Ev(o.referenceContext,"referenceContext")}:{},relatedSourceLines:o.relatedSourceLines??60,...o.semantic!==void 0?{semantic:o.semantic}:{}}}}function CN(e){let t={...qd};for(let[n,r]of Object.entries(e)){if(!(n in t))throw new Error(`Unknown inspect evidence channel: ${n}.`);if(!Number.isSafeInteger(r)||(r??-1)<0)throw new RangeError(`Evidence budget ${n} must be a non-negative safe integer; received ${r}.`);t[n]=r}return t}function xN(){return Object.fromEntries(Object.keys(qd).map(e=>[e,Ur]))}function RN(e,t){let n=[],r=0,i=Qa(e,t.searches,{scope:t.scope,context:0,limit:t.searchLimit,ranking:"structural"}).map((l,u)=>({pattern:t.searches[u],result:l,matches:l.matches})),o=Math.max(0,...i.map(l=>l.matches.length));for(let l=0;l<o;l+=1)for(let u of i){let d=u.matches[l];if(!d)continue;let m=Wn(e,d.relativePath,d.focusLine,Ur,t.context);m&&ki(e,n,m,"search",`search:${u.pattern}`,d.ownerSymbol,d.ownerShort,1,r++)}let s=i.map(({pattern:l,result:u})=>{let d=u.omittedMatches>0?Lv(l,t.scope):void 0,m=u.fileCoverage??[],p=kN(l,m,t.scope);return{pattern:l,matchingLines:u.matchingLines,returnedMatches:u.matches.length,omittedMatches:u.omittedMatches,matchingFiles:m.length,returnedFiles:m.filter(f=>f.returnedMatches>0).length,omittedFiles:m.filter(f=>f.returnedMatches===0).length,candidateUnits:0,selectedUnits:0,omittedUnits:0,scopeHints:p.slice(0,Sv),omittedScopeHints:Math.max(0,p.length-Sv),textCoverage:u.textCoverage,...d?{exactFollowup:d}:{}}}),a=t.locations.map(l=>{let u=BN(l),d=u?yg(e,u.path):null,m=d?Wn(e,d,u.line-1,Ur,t.context):null;return m&&ki(e,n,m,"location",`at:${l}`,null,null,0,r++),{target:l,matched:m!==null}}),c=t.symbols.map(l=>Fd(e,l,t.evidence));for(let l of c)if(l.kind==="matched"){if(l.definition){let u=Wn(e,l.definition.relativePath,l.definition.startLine,Ur,t.context);u&&ki(e,n,u,"definition",`definition:${l.shortName}`,l.symbol,l.shortName,0,r++)}for(let u of l.referenceWindows){let d=u.references[0];ki(e,n,{...u,focusLine:d?.line??u.startLine,unitType:null,unitStartLine:u.startLine,unitEndLine:u.endLine,omittedLines:0},"reference",`reference:${l.shortName}`,d?.enclosingSymbol??null,d?.enclosingShort??null,q(u.relativePath)==="test"?5:4,r++,u.references.map(m=>m.line),l.symbol)}for(let u of l.callers)vv(e,n,u,"caller",l,2,r++);for(let u of l.callees)vv(e,n,u,"callee",l,3,r++);for(let u of l.dependencies)Cv(e,n,"dependency",l.file,u.relativePath,l.symbol,t.context,6,r++);for(let u of l.consumers)Cv(e,n,"consumer",u.relativePath,l.file,l.symbol,t.context,7,r++)}return{searches:s,evidence:c,locations:a,candidates:n}}function jd(e,t){return e.priority-t.priority||t.roles.length-e.roles.length||t.reasons.length-e.reasons.length||Re(q(e.relativePath))-Re(q(t.relativePath))||e.sequence-t.sequence}function Hd(e,t){return{candidate:e,priority:e.priority,sequence:e.sequence,relativePath:e.relativePath,fileKind:q(e.relativePath),evidenceCharacters:Dv(e,t),roles:e.roles,reasons:e.reasons,symbols:e.symbols,behaviorSignals:e.kind==="source"?e.behavior?.signals??[]:[],channel:Ud(e)}}function Ud(e){let t=e.roles;return t.includes("location")?"exact-source":t.includes("definition")?"definition":t.includes("caller")?"caller":t.includes("callee")?"callee":t.includes("reference")?q(e.relativePath)==="test"?"test-reference":"production-reference":t.includes("dependency")?"dependency":t.includes("consumer")?"consumer":"search"}function EN(e,t){let n=t.filter(i=>i.kind==="source"),r=io(e,{files:ct(n.map(i=>i.relativePath))});for(let i of n){i.behavior=hi(e,i.relativePath,i.startLine,i.endLine,i.focusLines)??void 0;let o=r.filter(a=>a.source.file===i.relativePath&&a.source.startLine<=i.endLine&&a.source.endLine>=i.startLine),s=o.filter(a=>!IN(a,o)).map(a=>({observationId:a.id,protocol:a.protocol,action:a.action,role:a.role,strength:a.strength,resolution:a.resolution,line:a.source.startLine,endLine:a.source.endLine,keyParts:a.keyParts.map(c=>({name:c.name,value:c.value,evidence:c.evidence})),derivation:{kind:a.derivation.kind,rule:a.derivation.rule,sourceSpans:a.derivation.sourceSpans.length}}));i.runtimeFacts=s.length>0?s:void 0}}function IN(e,t){if(e.strength!=="candidate"||e.protocol!=="http")return!1;let n=e.keyParts.find(i=>i.name==="path")?.value,r=e.keyParts.find(i=>i.name==="method")?.value;return n?t.some(i=>{if(i===e||i.action!==e.action||i.role!==e.role||i.source.startLine!==e.source.startLine||i.derivation.rule!=="http.mount-prefix")return!1;let o=i.keyParts.find(a=>a.name==="path")?.value,s=i.keyParts.find(a=>a.name==="method")?.value;return!!(o&&o!==n&&o.endsWith(n)&&(!r||r===s))}):!1}function wN(e,t){for(let n of t){if(n.kind!=="source")continue;let r=ot(e,n.relativePath,n.startLine,n.endLine,n.focusLines);r.startLine===n.startLine&&r.endLine===n.endLine||(n.startLine=r.startLine,n.endLine=r.endLine,n.source=V(e,n.relativePath).slice(r.startLine,r.endLine+1).join(`
75
- `),n.unitStartLine=r.startLine,n.unitEndLine=r.endLine,n.omittedLines=0)}}function LN(e,t){for(let n of t)n.kind==="source"&&(n.bindingClosure=gi(e,n.relativePath,n.startLine,n.endLine))}function PN(e,t){let n=new Map;for(let r of t){let i=pc(r.relativePath),o=Ud(r),s=[...r.roles].sort().join(","),a=r.kind==="path"?r.relationship:"",c=`${i}|${o}|${s}|${a}`,l=n.get(c)??[];l.push(r),n.set(c,l)}return[...n.entries()].map(([r,i])=>{let o=i[0],s=ct(i.flatMap(c=>[...c.roles])).sort(),a=ct(i.flatMap(c=>c.kind==="source"?c.behavior?.signals??[]:[])).sort();return{id:`g-${Iv("sha256").update(r).digest("hex").slice(0,8)}`,scope:pc(o.relativePath),channel:Ud(o),roles:s,behaviorSignals:a,candidateUnits:i.length,sourceCharacters:i.reduce((c,l)=>c+(l.kind==="source"?l.source.length:0),0),anchors:i.map(c=>({relativePath:c.relativePath,line:c.kind==="source"?c.focusLine:0,ownerShort:c.kind==="source"?c.ownerShort:null,roles:[...c.roles],behaviorSignals:c.kind==="source"?[...c.behavior?.signals??[]]:[]})),drillCommand:DN(e,i)}}).sort((r,i)=>i.candidateUnits-r.candidateUnits||i.sourceCharacters-r.sourceCharacters||r.scope.localeCompare(i.scope)||r.id.localeCompare(i.id))}function DN(e,t){let n=ct(t.flatMap(o=>o.reasons.filter(s=>s.startsWith("search:")).map(s=>s.slice(7)))),r=pc(t[0].relativePath);if(n.length>0&&t.every(o=>o.kind==="source"&&o.roles.includes("search"))){let o=["scip-query inspect"];for(let s of n)o.push(`--search ${At(s)}`);return o.push(`--scope ${At(r)}`,"--full"),e.view==="behavior"&&o.push("--view behavior"),o.join(" ")}let i=t.filter(o=>o.kind==="source");if(i.length>0&&i.length<=24){let o=["scip-query inspect"];for(let s of i)o.push(`--at ${At(`${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:Pv(e,!0)}function MN(e,t,n){let r=`search:${e.pattern}`,i=t.filter(a=>a.reasons.includes(r)).length,o=new Set(n),s=t.filter(a=>a.reasons.includes(r)&&o.has(a)).length;return{...e,candidateUnits:i,selectedUnits:s,omittedUnits:i-s}}function TN(e){let t={};for(let n of e)for(let r of n.roles)t[r]=(t[r]??0)+1;return t}function AN(e,t,n,r){let i=e.map(s=>Hd(s,r).channel),o=t.map(s=>Hd(s,r).channel);return Object.fromEntries(Object.keys(n).map(s=>{let a=i.filter(l=>l===s).length,c=o.filter(l=>l===s).length;return[s,{candidateUnits:a,returnedUnits:c,omittedUnits:a-c,maxUnits:n[s]}]}))}function FN(e){return!!(e&&e.skippedUnreadablePaths.length===0&&e.skippedOversizedPaths.length===0)}function kN(e,t,n){let r=new Map;for(let i of t){let o=pc(i.relativePath),s=r.get(o)??{matchingLines:0,returnedMatches:0};s.matchingLines+=i.matchingLines,s.returnedMatches+=i.returnedMatches,r.set(o,s)}return[...r.entries()].map(([i,o])=>({scope:i,...o,exactFollowup:Lv(e,i||n)})).sort((i,o)=>o.matchingLines-i.matchingLines||o.returnedMatches-i.returnedMatches||i.scope.localeCompare(o.scope))}function pc(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}function Lv(e,t){return`scip-query inspect --search ${At(e)}${t?` --scope ${At(t)}`:""} --full`}function Pv(e,t){let n=["scip-query inspect"];for(let r of e.searches)n.push(`--search ${At(r)}`);for(let r of e.symbols)n.push(`--symbol ${At(r)}`);for(let r of e.locations)n.push(`--at ${At(r)}`);return e.scope&&n.push(`--scope ${At(e.scope)}`),e.context!==wv&&n.push(`--context ${e.context}`),e.evidence.parts&&n.push(`--include ${At(e.evidence.parts.join(","))}`),t&&n.push("--full"),e.view==="behavior"&&n.push("--view behavior"),n.join(" ")}function vv(e,t,n,r,i,o,s){ki(e,t,{...n,unitType:null,unitStartLine:n.startLine,unitEndLine:n.endLine+n.omittedLines},r,`${r}:${i.shortName}`,n.symbol,n.shortName,o,s,[n.focusLine],i.symbol)}function Cv(e,t,n,r,i,o,s,a,c){let l=`${r} -> ${i}`,u=ae(e,r).filter(h=>h.sourcePath===i),d=V(e,r),m=NN(d,u,i),p=m===null?null:ha(e,r,m,Math.min(s,4));if(p){ki(e,t,{...p,unitType:null,unitStartLine:p.startLine,unitEndLine:p.endLine,omittedLines:0},n,`${n}:${l}`,null,null,a,c,[p.focusLine],o);return}let f=`scip-query inspect --search ${At(Mv(i))} --scope ${At(r)}`,g=t.find(h=>h.kind==="path"&&h.relativePath===r&&h.relationship===l);if(g){g.roles=ct([...g.roles,n]),g.reasons=ct([...g.reasons,`${n}:${l}`]),g.symbols=ct([...g.symbols,o]),g.priority=Math.min(g.priority,a);return}t.push({kind:"path",roles:[n],relativePath:r,relationship:l,reasons:[`${n}:${l}`],symbols:[o],exactFollowup:f,priority:a,sequence:c})}function NN(e,t,n){let r=ct(t.flatMap(c=>[c.importedName,c.localName??""]).filter(c=>c.length>1)),i=Mv(n).replace(/\.[^.]+$/u,""),o=ct([...r,i]).filter(Boolean),s=/\b(?:from|import|include|require|use)\b/u,a=e.findIndex(c=>s.test(c)&&o.some(l=>c.includes(l)));return a>=0?a:null}function ki(e,t,n,r,i,o,s,a,c,l=[n.focusLine],u){let d=t.find(m=>m.kind==="source"&&m.relativePath===n.relativePath&&m.startLine<=n.endLine&&n.startLine<=m.endLine);if(d){let m=Math.min(d.startLine,n.startLine),p=Math.max(d.endLine,n.endLine);d.startLine=m,d.endLine=p,d.source=V(e,n.relativePath).slice(m,p+1).join(`
76
- `),d.focusLine=Math.min(d.focusLine,n.focusLine),d.focusLines=Rv([...d.focusLines,...l]),d.unitStartLine=Math.min(d.unitStartLine,n.unitStartLine),d.unitEndLine=Math.max(d.unitEndLine,n.unitEndLine),d.omittedLines=Math.max(d.omittedLines,n.omittedLines),d.reasons=ct([...d.reasons,i]),d.roles=ct([...d.roles,r]),d.symbols=ct([...d.symbols,...u?[u]:[]]),!d.ownerSymbol&&o&&(d.ownerSymbol=o),!d.ownerShort&&s&&(d.ownerShort=s),d.priority=Math.min(d.priority,a);return}t.push({kind:"source",...n,reasons:[i],focusLines:Rv(l),ownerSymbol:o,ownerShort:s,roles:[r],symbols:u?[u]:[],priority:a,sequence:c})}function _N(e){if(e.kind==="path"){let{priority:o,sequence:s,...a}=e;return{...a,id:xv(a)}}let{priority:t,sequence:n,bindingClosure:r,...i}=e;return{...i,id:xv(i),omittedCharacters:0}}function ON(e){let{kind:t,id:n,roles:r,symbols:i,omittedCharacters:o,behavior:s,runtimeFacts:a,...c}=e;return c}function xv(e){return Iv("sha256").update(JSON.stringify(e)).digest("hex").slice(0,16)}function BN(e){let t=e.match(/^(.+\.\w+):(\d+)$/u);if(!t)return null;let n=Number(t[2]);return Number.isSafeInteger(n)&&n>0?{path:t[1],line:n}:null}function ct(e){return[...new Set(e)]}function Rv(e){return ct(e).sort((t,n)=>t-n)}function $N(e){return e.length===0?0:e.split(`
77
- `).length}function Dv(e,t){if(e.kind==="path")return e.relationship.length+e.exactFollowup.length;let n="bindingClosure"in e?Ag(e.bindingClosure):0,r=(e.runtimeFacts??[]).reduce((i,o)=>i+o.action.length+o.derivation.rule.length+o.keyParts.reduce((s,a)=>s+a.name.length+a.value.length+4,0)+24,0);return t!=="behavior"?e.source.length+n:e.behavior?e.behavior.lines.reduce((i,o)=>i+o.text.length+o.signals.join(",").length+12,0)+e.behavior.testCases.reduce((i,o)=>i+o.length+2,0)+r+n:e.source.length+n+r}function Mv(e){return e.split("/").at(-1)??e}function At(e){return`'${e.replaceAll("'","'\\''")}'`}function ar(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new RangeError(`${t} must be a positive safe integer; received ${e}`);return e}function Ev(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 jN}from"path";function HN(e,t){let n=t.className,r=Qe(e,n);return r.match?r.total>1?{kind:"ambiguous",query:n,total:r.total,candidates:[Tv(r.match),...r.candidates]}:{kind:"matched",query:n,owner:qN(r.match),methods:UN(e,r.match)}:{kind:"missing",query:n,suggestions:Ks(e,n,5)}}function UN(e,t){let n=z(t.symbol),i=new H(e).definitionsForFile(t.relativePath).filter(c=>Xe(c.symbol)),o=i.filter(c=>c.parentTypeName===n||c.symbol.includes(n)),a=(o.length>0?o:GN(jN(t.relativePath))===n?i.filter(c=>c.symbol.includes("<invalid-global-code>")):[]).map(c=>({startLine:c.startLine,endLine:c.endLine,name:z(c.symbol)}));return se(t.relativePath)!=="clojure"?a:KN(a,zN(e,t))}function Tv(e){return{symbol:e.symbol,shortName:T(e.symbol),relativePath:e.relativePath,startLine:e.startLine}}function qN(e){return{...Tv(e),endLine:e.endLine}}function GN(e){return e.replace(/\.[^.]+$/,"")}function zN(e,t){let n=z(t.symbol);return n?(K(e,t.relativePath)?.clojureMembers??[]).filter(r=>r.ownerName===n).map(r=>({startLine:r.startLine,endLine:r.endLine,name:r.memberName})):[]}function KN(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.name}:${r.startLine}:${r.endLine}`,r);return[...n.values()].sort((r,i)=>r.startLine-i.startLine||r.endLine-i.endLine)}import{createHash as a$}from"crypto";var Sre={exact:"Direct compiler or source evidence establishes this relationship within the provider's reported coverage.",derived:"A deterministic analysis computed this relationship from reported input facts; it was not directly observed.",candidate:"Ambiguous or heuristic evidence identifies a lead that requires exact graph or source confirmation.",mixed:"The relationship combines evidence of different strengths; its constituent methods and strengths remain disclosed.",unknown:"The relationship has no calibrated evidence strength and cannot support a stronger claim than its raw observation."},WN=[{id:"general-interprocedural-value-flow",families:["dataflow"],capability:"Whole-program definition-use flow through arbitrary calls and returns is unavailable.",consequence:"Missing dataflow edges cannot establish that a value never crosses an unmodeled call.",recoverWith:["value-flow","dependence-slice","inspect","code"]},{id:"heap-aliasing",families:["dataflow","state"],capability:"Heap points-to and cross-instance alias analysis are unavailable.",consequence:"Missing field or state edges cannot establish that two references never reach the same object.",recoverWith:["value-flow","dependence-slice","inspect","code"]},{id:"exceptional-flow",families:["execution","dataflow","temporal"],capability:"Interprocedural exception propagation and finally completion flow are unavailable.",consequence:"Normal-path reachability and ordering do not establish behavior after a throw or rejection.",recoverWith:["dependence-slice","inspect","code"]},{id:"reflection",families:["execution","runtime","identity","dependencies"],capability:"Reflective lookup, dynamic loading, and name-computed invocation are unavailable without exact evidence.",consequence:"Missing static edges cannot establish that a construct is unreachable through reflection.",recoverWith:["search","inspect","code"]},{id:"generated-dispatch",families:["execution","runtime","identity"],capability:"Dispatch tables or names created only by generated or unavailable source are unavailable.",consequence:"Missing dispatch edges cannot establish that no generated consumer exists.",recoverWith:["search","inspect","code"]},{id:"unsupported-framework-adapters",families:["runtime","dataflow","state","temporal"],capability:"Framework runtime crossings without a registered source adapter are unavailable.",consequence:"Missing boundary edges cannot establish that no producer, consumer, state effect, or ordering exists.",recoverWith:["search","inspect","code"]}];function VN(e){let t=new Set(e);return WN.filter(n=>n.families.some(r=>t.has(r)))}function Av(e){return VN(e).map(t=>`[${t.id}] ${t.capability} ${t.consequence} Recover selected paths with: ${t.recoverWith.map(n=>`scip-query ${n}`).join(", ")}.`)}var YN=["incoming","outgoing","both"];function ge(e,t,n,r={}){return{family:e,subtype:t,...r.match?{match:r.match}:{},directions:YN,evidenceStrengths:r.strengths??["exact","derived","mixed"],supportCeiling:r.supportCeiling??"partial",establishes:n,nonClaims:r.nonClaims??[],recoverWith:r.recoverWith??["inspect","code"]}}var JN=["predicate-consequence","predicate-alternative","predicate-fallthrough","predicate-case","predicate-default","predicate-return","predicate-throw","loop-iteration","loop-exit","exception-handler","finally-cleanup","handler-return","handler-throw"],XN=["captured-value-to-state","constant-to-state","expression-to-state","property-to-state","return-to-state","value-to-state"],QN=["await-completion-before","awaits-completion","inside-lock-scope","lexical-successor"],ZN=[{id:"indexed-program-identity",label:"SCIP/compiler identity and source ownership",requirements:["indexed-graph"],relations:[ge("execution","call","The source construct may call the resolved target.",{strengths:["exact","derived","candidate","mixed"],nonClaims:["Static may-call reachability does not prove that an invocation occurred at runtime."],recoverWith:["call-graph","inspect","code"]}),ge("execution","result-callback","The referenced callable can produce the result consumed by this path.",{nonClaims:["A callback relationship does not prove invocation order or runtime selection."],recoverWith:["call-graph","inspect","code"]}),ge("contract","uses-contract-symbol","The source construct refers to the identified contract symbol.",{supportCeiling:"exact",nonClaims:["Contract identity does not prove runtime invocation or behavioral conformance."],recoverWith:["hierarchy","inspect","code"]}),ge("identity","references","The occurrence resolves to the identified compiler-owned symbol.",{supportCeiling:"exact",nonClaims:["A reference does not establish execution or value transfer."],recoverWith:["refs","trace","inspect"]}),ge("ownership","contains","The owner contains the identified program construct.",{supportCeiling:"exact",nonClaims:["Structural containment does not establish runtime lifetime or sharing scope."],recoverWith:["outline","inspect"]}),ge("ownership","contains-","The owner contains the identified program construct.",{match:"prefix",supportCeiling:"exact",nonClaims:["Structural containment does not establish runtime lifetime or sharing scope."],recoverWith:["outline","inspect"]}),ge("ownership","owns-","The owner owns the identified source or runtime observation.",{match:"prefix",supportCeiling:"exact",nonClaims:["Observation ownership does not establish singleton lifetime or exclusive ownership."],recoverWith:["inspect","code"]}),ge("dependencies","imports","The source file or module statically imports the indexed target.",{nonClaims:["An import does not establish that imported code executes."],recoverWith:["imports","deps","code"]}),ge("dependencies","imports-external","The source region statically imports an external package.",{nonClaims:["An external import does not establish which package behavior executes."],recoverWith:["imports","code"]})]},{id:"runtime-boundary-join",label:"source-grounded runtime-boundary joins",requirements:["indexed-graph","source-facts"],relations:[ge("runtime","runtime-handoff","A producer and consumer share a source-grounded runtime rendezvous.",{strengths:["exact","derived","candidate","mixed"],nonClaims:["A candidate or unresolved join does not prove a runtime handoff."],recoverWith:["evidence","inspect","code"]}),ge("runtime","discriminator-dispatch","A serialized discriminator selects the reported consumer.",{strengths:["exact","derived","mixed"],nonClaims:["The dispatch edge does not prove delivery, retry, or successful handling."],recoverWith:["evidence","inspect","code"]}),ge("dataflow","serialized-discriminator-transfer","The producer serializes the discriminator consumed by dispatch.",{strengths:["exact","derived","mixed"],nonClaims:["This edge does not establish the flow of every payload field."],recoverWith:["value-flow","inspect","code"]}),ge("temporal","enqueue-before-consume","The reported enqueue precedes a possible consume through the queue.",{strengths:["exact","derived","mixed"],nonClaims:["Queue order does not establish delivery time, uniqueness, retry count, or durability."],recoverWith:["evidence","inspect","code"]})]},{id:"parser-control-dependence",label:"parser-proved intraprocedural control dependence",requirements:["indexed-graph","source-facts"],relations:[...JN.map(e=>ge("execution",e,"The outcome is control-dependent on the reported predicate or handler.",{strengths:["exact"],nonClaims:["Local control dependence does not establish that the containing function executes."],recoverWith:["dependence-slice","inspect","code"]})),ge("execution","returns","The selected construct contains the reported return terminal.",{strengths:["exact"],nonClaims:["A local return terminal does not establish that the containing callable executes."],recoverWith:["inspect","code"]}),ge("execution","throws","The selected construct contains the reported throw terminal.",{strengths:["exact"],nonClaims:["A local throw terminal does not establish propagation, handling, or callable execution."],recoverWith:["inspect","code"]})]},{id:"bounded-static-value-flow",label:"compiler callsites and bounded static value evaluation",requirements:["indexed-graph","source-facts"],relations:["argument-to-parameter","constant-to-parameter","property-to-parameter","return-to-parameter","return-to-call-result"].map(e=>ge("dataflow",e,"The reported value may reach the target through the evidenced callsite transfer.",{strengths:["exact","derived","mixed"],nonClaims:["This provider does not establish general local definition-use, alias, field, or heap flow."],recoverWith:["value-flow","dependence-slice","inspect","code"]}))},{id:"typescript-local-dependence",label:"TypeScript compiler identities, control-flow graph, and reaching definitions",requirements:["typescript-semantic"],relations:[ge("dataflow","definition-to-use","The definition reaches the reported read on a feasible local control-flow path.",{strengths:["exact"],nonClaims:["Local reaching definitions do not establish heap aliasing, exceptional flow, or the runtime order of closure invocation."],recoverWith:["value-flow","dependence-slice","inspect","code"]}),ge("dataflow","value-to-definition","The reported right-hand-side read supplies the assigned local definition.",{strengths:["exact"],nonClaims:["A local assignment edge does not establish field or heap points-to flow."],recoverWith:["value-flow","dependence-slice","inspect","code"]}),ge("dataflow","closure-capture","The nested callable reads the reported binding from an enclosing callable.",{strengths:["candidate"],supportCeiling:"candidate",nonClaims:["Closure capture does not establish whether or when the nested callable executes."],recoverWith:["call-graph","inspect","code"]}),ge("dataflow","field-definition-to-use","The reported same-owner field definition can reach the field read.",{strengths:["exact","candidate"],nonClaims:["Field-name identity does not establish whole-program heap aliasing or cross-instance flow."],recoverWith:["value-flow","dependence-slice","inspect","code"]}),ge("execution","control-dependence","Execution of the reported statement depends on the outcome of the predicate.",{strengths:["exact"],nonClaims:["Intraprocedural control dependence does not establish that the containing callable executes."],recoverWith:["dependence-slice","inspect","code"]})]},{id:"parser-state-temporal",label:"parser-proved local state and temporal facts",requirements:["indexed-graph","source-facts"],relations:[...XN.map(e=>ge("dataflow",e,"The reported source value is assigned into the identified state resource.",{strengths:["exact"],nonClaims:["The edge does not establish alias, heap, or later read flow."],recoverWith:["value-flow","inspect","code"]})),...["writes-resource","deletes-resource","reads-resource","enqueues-resource","consumes-resource"].map(e=>ge("state",e,"The reported construct performs the named operation on the identified resource.",{strengths:["exact"],nonClaims:["A state operation does not establish transactionality, durability, or exclusive ownership."],recoverWith:["evidence","inspect","code"]})),...QN.map(e=>ge("temporal",e,"The reported source constructs have the named local ordering relationship.",{strengths:["exact"],nonClaims:["Local source order does not establish cross-process happens-before or durable completion."],recoverWith:["evidence","inspect","code"]}))]}];function fc(e,t){let n=ZN.flatMap(r=>r.relations.filter(i=>i.family===e&&(i.match==="prefix"?t.startsWith(i.subtype):t===i.subtype)).map(i=>({provider:r,relation:i})));if(n.length>1)throw new Error(`Ambiguous graph relation provider for ${e}/${t}: ${n.map(r=>r.provider.id).join(", ")}`);return n[0]??null}var $t=["execution","runtime","dataflow","state","temporal","contract","identity","ownership","dependencies"];function Be(e,t){let n=new Map;for(let r of e){let i=t(r),o=n.get(i)??[];o.push(r),n.set(i,o)}return n}function Ni(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 Fv(e,t){return Ni(e.origins)-Ni(t.origins)||e.depth-t.depth||e.startLine-t.startLine||e.shortName.localeCompare(t.shortName)}var kv=["call","contract-symbol","import","reference","runtime-boundary"],e_={call:[{family:"control",subtype:"call"}],"contract-symbol":[{family:"contract",subtype:"uses-contract-symbol"}],import:[{family:"identity",subtype:"imports"}],reference:[{family:"identity",subtype:"references"}]},t_={"structural-membership":[{family:"identity",subtype:"contains"}],"boundary-observation":[{family:"identity",subtype:"owns-runtime-observation"}],"external-import":[{family:"identity",subtype:"imports-external"}]};function Nv(e){if(e.kind!=="runtime-boundary")return _v(e_[e.kind]);let t=e.fromBoundaryParticipant?.protocol??e.toBoundaryParticipant?.protocol,n={crossesRuntimeBoundary:!0,...t?{protocol:t}:{},...e.runtimeBoundaryKey?{runtimeKey:e.runtimeBoundaryKey}:{}},r=[{family:"control",subtype:"runtime-handoff",context:n}];return e.evidence==="runtime-boundary:carrier.discriminator"&&(r.push({family:"control",subtype:"discriminator-dispatch",context:{...n},attributes:{joinRule:"carrier.discriminator",...e.fromBoundaryParticipant?.action?{producerAction:e.fromBoundaryParticipant.action}:{},...e.toBoundaryParticipant?.action?{consumerAction:e.toBoundaryParticipant.action}:{}}}),r.push({family:"data",subtype:"serialized-discriminator-transfer",context:{...n},attributes:{joinRule:"carrier.discriminator"}})),e.evidence==="runtime-boundary:queue.address"&&e.fromBoundaryParticipant?.action==="queue.send"&&e.toBoundaryParticipant?.action==="queue.consume"&&r.push({family:"temporal",subtype:"enqueue-before-consume",context:{...n},attributes:{producerAction:e.fromBoundaryParticipant.action,consumerAction:e.toBoundaryParticipant.action,retryPolicy:"unknown"}}),r}function gc(e){return _v(t_[e])}function _v(e){return e.map(t=>({...t,...t.context?{context:{...t.context}}:{},...t.attributes?{attributes:{...t.attributes}}:{}}))}import{join as L_}from"path";import{createRequire as n_}from"module";import{resolve as Wo}from"path";var r_=n_(import.meta.url),Ko;function Bv(e,t,n){let r=i_();if(!r)return Gd("The TypeScript compiler runtime is unavailable.");let i=o_(r,e,t),o=i.getSourceFile(Wo(t))??i.getSourceFile(t);if(!o)return Gd(`The TypeScript compiler did not materialize ${t}.`);let s={ts:r,sourceFile:o,checker:i.getTypeChecker(),points:new Map,edges:new Map,unsupported:new Set,nextCfgId:0},a=a_(r,o,n);if(a.length===0)return Gd("No function-like construct intersects the selected source range.");let c=new Map(a.map(d=>[d,c_(o,d)])),l=a.map(d=>u_(s,d,l_(r,d,c),c.get(d)));for(let d of l)d_(s,d),g_(s,d),b_(s,d);v_(s,l);let u=[...s.unsupported].sort();return{points:[...s.points.values()].map(({node:d,...m})=>m).sort(w_),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 i_(){if(Ko!==void 0)return Ko;try{Ko=r_("typescript")}catch{Ko=ea()?.ts??null}return Ko}function o_(e,t,n){let r=Wo(n),i={target:e.ScriptTarget.ESNext,module:e.ModuleKind.NodeNext,moduleResolution:e.ModuleResolutionKind.NodeNext,skipLibCheck:!0,noResolve:!0},o=e.createSourceFile(r,t,i.target,!0,s_(e,r)),s=e.createCompilerHost(i,!0),a=s.getSourceFile.bind(s),c=s.readFile.bind(s),l=s.fileExists.bind(s);return s.getSourceFile=(u,d,m,p)=>Wo(u)===r?o:a(u,d,m,p),s.readFile=u=>Wo(u)===r?t:c(u),s.fileExists=u=>Wo(u)===r||l(u),e.createProgram([r],i,s)}function s_(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 a_(e,t,n){let r=[],i=o=>{if($v(e,o)){let s=t.getLineAndCharacterOfPosition(o.getStart(t)).line,a=t.getLineAndCharacterOfPosition(o.getEnd()).line;(!n||s<=n.endLine&&a>=n.startLine)&&r.push(o)}o.forEachChild(i)};return t.forEachChild(i),r.sort((o,s)=>o.getStart(t)-s.getStart(t))}function $v(e,t){return e.isFunctionLike(t)&&"body"in t&&t.body!==void 0}function c_(e,t){return`callable:${encodeURIComponent(e.fileName)}:${t.getStart(e)}:${t.getEnd()}`}function l_(e,t,n){for(let r=t.parent;r;r=r.parent)if($v(e,r)&&n.has(r))return n.get(r);return null}function u_(e,t,n,r){let i=new Map,o=ze(e,i,"exit",null),s=t.body,a=o.id;if(s&&e.ts.isBlock(s))a=zd(e,i,[...s.statements],o.id,{breakTarget:null,continueTarget:null});else if(s){let l=ze(e,i,"statement",s);Ce(i,l.id,o.id),a=l.id}let c=ze(e,i,"entry",t);return Ce(i,c.id,a),{id:r,node:t,parentId:n,cfg:i,entryId:c.id,exitId:o.id}}function zd(e,t,n,r,i){let o=r;for(let s=n.length-1;s>=0;s-=1)o=qr(e,t,n[s],o,i);return o}function qr(e,t,n,r,i){let o=e.ts;if(o.isBlock(n))return zd(e,t,[...n.statements],r,i);if(o.isIfStatement(n)){let a=ze(e,t,"predicate",n.expression),c=qr(e,t,n.thenStatement,r,i),l=n.elseStatement?qr(e,t,n.elseStatement,r,i):r;return Ce(t,a.id,c),Ce(t,a.id,l),a.id}if(o.isWhileStatement(n)){let a=ze(e,t,"predicate",n.expression),c=qr(e,t,n.statement,a.id,{breakTarget:r,continueTarget:a.id});return Ce(t,a.id,c),Ce(t,a.id,r),a.id}if(o.isDoStatement(n)){let a=ze(e,t,"predicate",n.expression),c=qr(e,t,n.statement,a.id,{breakTarget:r,continueTarget:a.id});return Ce(t,a.id,c),Ce(t,a.id,r),c}if(o.isForStatement(n)){let a=ze(e,t,"predicate",n.condition??n),c=n.incrementor?ze(e,t,"statement",n.incrementor):null;c&&Ce(t,c.id,a.id);let l=c?.id??a.id,u=qr(e,t,n.statement,l,{breakTarget:r,continueTarget:l});if(Ce(t,a.id,u),n.condition&&Ce(t,a.id,r),!n.initializer)return a.id;let d=ze(e,t,"statement",n.initializer);return Ce(t,d.id,a.id),d.id}if(o.isForInStatement(n)||o.isForOfStatement(n)){e.unsupported.add("for-in/for-of iterator assignment is conservatively represented without iterable element flow.");let a=ze(e,t,"predicate",n.expression),c=ze(e,t,"statement",n.initializer),l=qr(e,t,n.statement,a.id,{breakTarget:r,continueTarget:a.id});return Ce(t,a.id,c.id),Ce(t,a.id,r),Ce(t,c.id,l),a.id}if(o.isSwitchStatement(n)){e.unsupported.add("switch fallthrough is represented conservatively; discriminant-to-case value refinement is unsupported.");let a=ze(e,t,"predicate",n.expression),c=r,l=[];for(let u=n.caseBlock.clauses.length-1;u>=0;u-=1){let d=n.caseBlock.clauses[u];c=zd(e,t,[...d.statements],c,{...i,breakTarget:r}),l.push(c)}for(let u of l)Ce(t,a.id,u);return Ce(t,a.id,r),a.id}if(o.isReturnStatement(n)||o.isThrowStatement(n)){let a=ze(e,t,"statement",n),c=[...t.values()].find(l=>l.kind==="exit");return Ce(t,a.id,c.id),a.id}if(o.isBreakStatement(n)){let a=ze(e,t,"statement",n);return i.breakTarget||e.unsupported.add("A break statement could not be attached to a structured target."),Ce(t,a.id,i.breakTarget??r),a.id}if(o.isContinueStatement(n)){let a=ze(e,t,"statement",n);return i.continueTarget||e.unsupported.add("A continue statement could not be attached to a structured target."),Ce(t,a.id,i.continueTarget??r),a.id}if(o.isTryStatement(n)){e.unsupported.add("Exceptional control-flow and finally completion are not included in the local compiler CFG.");let a=ze(e,t,"statement",n);return a.invalidatesAllDefinitions=!0,Ce(t,a.id,r),a.id}let s=ze(e,t,"statement",n);return Ce(t,s.id,r),s.id}function ze(e,t,n,r){let i={id:`cfg:${e.nextCfgId++}`,kind:n,ast:r,successors:new Set,predecessors:new Set,definitions:[],uses:[],displayPoint:null,invalidatesAllDefinitions:!1};return t.set(i.id,i),i}function Ce(e,t,n){e.get(t).successors.add(n),e.get(n).predecessors.add(t)}function d_(e,t){let n=t.cfg.get(t.entryId);for(let r of t.node.parameters){let i=Gr(e,r.name);if(!i){e.unsupported.add("Destructured parameter definition-use is not implemented.");continue}n.definitions.push({point:zr(e,i.node,"parameter-definition",i.symbolKey,i.name,t.id),rhsUseIds:[]})}for(let r of t.cfg.values())!r.ast||r.kind==="entry"||r.kind==="exit"||(r.kind==="predicate"&&(r.displayPoint=zr(e,r.ast,"predicate",null,"predicate",t.id)),m_(e,t,r,r.ast),!r.displayPoint&&r.definitions.length===0&&r.uses.length===0&&(r.displayPoint=zr(e,r.ast,"statement",null,x_(e,r.ast),t.id)))}function m_(e,t,n,r){let i=e.ts;if(i.isTryStatement(r))return;let o=s=>{if(!(s!==r&&i.isFunctionLike(s))){if(i.isVariableDeclaration(s)){let a=s.initializer?hc(e,t.id,s.initializer,n):[];n.uses.push(...a);let c=Gr(e,s.name);c?n.definitions.push({point:zr(e,c.node,"definition",c.symbolKey,c.name,t.id),rhsUseIds:a.map(l=>l.point.id)}):(n.invalidatesAllDefinitions=!0,e.unsupported.add("Destructured variable reaching definitions are not implemented."));return}if(i.isBinaryExpression(s)&&Uv(i,s.operatorToken.kind)){let a=hc(e,t.id,s.right,n);s.operatorToken.kind!==i.SyntaxKind.EqualsToken&&a.push(...hc(e,t.id,s.left,n)),n.uses.push(...a);let c=Gr(e,s.left);c?n.definitions.push({point:zr(e,c.node,"definition",c.symbolKey,c.name,t.id),rhsUseIds:a.map(l=>l.point.id)}):(n.invalidatesAllDefinitions=!0,e.unsupported.add("Dynamic or destructured assignment targets are not included in reaching definitions."));return}if((i.isPrefixUnaryExpression(s)||i.isPostfixUnaryExpression(s))&&(s.operator===i.SyntaxKind.PlusPlusToken||s.operator===i.SyntaxKind.MinusMinusToken)){let a=hc(e,t.id,s.operand,n);n.uses.push(...a);let c=Gr(e,s.operand);c&&n.definitions.push({point:zr(e,c.node,"definition",c.symbolKey,c.name,t.id),rhsUseIds:a.map(l=>l.point.id)});return}if(!(i.isFunctionDeclaration(s)||i.isClassDeclaration(s)||i.isInterfaceDeclaration(s))){if(jv(e,s)){let a=Hv(e,t.id,s);a&&n.uses.push(a),i.isPropertyAccessExpression(s)&&o(s.expression);return}s.forEachChild(o)}}};o(r),n.uses=qv(n.uses)}function hc(e,t,n,r){let i=[],o=s=>{if(!e.ts.isFunctionLike(s)){if(e.ts.isBinaryExpression(s)&&Uv(e.ts,s.operatorToken.kind)){r.invalidatesAllDefinitions=!0,e.unsupported.add("Nested assignment expressions are not included in ordered local definition-use flow."),s.operatorToken.kind!==e.ts.SyntaxKind.EqualsToken&&o(s.left),o(s.right);return}if(jv(e,s)){let a=Hv(e,t,s);a&&i.push(a),e.ts.isPropertyAccessExpression(s)&&o(s.expression);return}s.forEachChild(o)}};return o(n),qv(i)}function jv(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&&p_(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)||f_(e.ts,t))}function p_(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 f_(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 Hv(e,t,n){let r=Gr(e,n);return r?{point:zr(e,r.node,"use",r.symbolKey,r.name,t),property:e.ts.isPropertyAccessExpression(n)}:null}function Gr(e,t){let n=e.ts;if(n.isIdentifier(t)){let r=Ov(e,t);return r?{node:t,symbolKey:r,name:t.text}:null}if(n.isPropertyAccessExpression(t)){let r=Ov(e,t.name);return r?{node:t,symbolKey:r,name:t.getText(e.sourceFile)}:null}return n.isParenthesizedExpression(t)||n.isAsExpression(t)||n.isTypeAssertionExpression(t)||n.isNonNullExpression(t)?Gr(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 Ov(e,t){let n=e.checker.getSymbolAtLocation(t);if(!n)return null;if((n.flags&e.ts.SymbolFlags.Alias)!==0)try{n=e.checker.getAliasedSymbol(n)}catch{}let r=n.valueDeclaration??n.declarations?.[0];return r?`symbol:${encodeURIComponent(r.getSourceFile().fileName)}:${r.getStart()}:${n.getName()}`:`symbol:${n.getName()}`}function zr(e,t,n,r,i,o){let s=t.getStart(e.sourceFile),a=t.getEnd(),c=e.sourceFile.getLineAndCharacterOfPosition(s),l=`flow-point:${encodeURIComponent(e.sourceFile.fileName)}:${s}:${a}:${n}:${encodeURIComponent(r??i)}`,u=e.points.get(l);if(u)return u;let d={id:l,kind:n,name:i,symbolKey:r,callableId:o,start:s,end:a,line:c.line,column:c.character,node:t};return e.points.set(l,d),d}function g_(e,t){let n=[...t.cfg.values()].flatMap(c=>c.definitions),r=new Map(n.map(c=>[c.point.id,c])),i=h_(n),o=new Map,s=new Map;for(let c of t.cfg.values())o.set(c.id,new Set),s.set(c.id,new Set);let a=!0;for(;a;){a=!1;for(let c of t.cfg.values()){let l=E_([...c.predecessors].map(m=>s.get(m))),u=new Set(l);c.invalidatesAllDefinitions&&u.clear();let d=y_(c.definitions);for(let m of d){for(let p of i.get(m.point.symbolKey)??[])u.delete(p.point.id);u.add(m.point.id)}Kd(o.get(c.id),l)||(o.set(c.id,l),a=!0),Kd(s.get(c.id),u)||(s.set(c.id,u),a=!0)}}for(let c of t.cfg.values()){let l=o.get(c.id);for(let u of c.uses){let d=c.definitions.filter(p=>p.point.symbolKey===u.point.symbolKey&&p.point.start<u.point.start&&!p.rhsUseIds.includes(u.point.id)).sort((p,f)=>f.point.start-p.point.start)[0],m=d?[d.point.id]:l;for(let p of m){let f=r.get(p);f.point.symbolKey===u.point.symbolKey&&Vo(e,"reaching-definition",f.point.id,u.point.id,"exact","A CFG path reaches this use without an intervening definition.")}}for(let u of c.definitions)for(let d of u.rhsUseIds)Vo(e,"value-source",d,u.point.id,"exact","This right-hand-side use supplies the new definition.")}}function h_(e){let t=new Map;for(let n of e){if(!n.point.symbolKey)continue;let r=t.get(n.point.symbolKey)??[];r.push(n),t.set(n.point.symbolKey,r)}return t}function y_(e){let t=new Map;for(let n of e)n.point.symbolKey&&t.set(n.point.symbolKey,n);return[...t.values()]}function b_(e,t){let n=S_(t);for(let r of t.cfg.values()){if(r.successors.size<2||!r.displayPoint)continue;let i=n.get(r.id);for(let o of r.successors)for(let s of n.get(o)??[]){if(i.has(s)||s===t.exitId)continue;let a=t.cfg.get(s),c=[...a.definitions.map(l=>l.point),...a.uses.map(l=>l.point),...a.displayPoint?[a.displayPoint]:[]];for(let l of R_(c))Vo(e,"control-dependence",r.displayPoint.id,l.id,"exact","The target postdominates a branch successor but does not postdominate the predicate.")}}}function S_(e){let t=[...e.cfg.keys()],n=new Set(t),r=new Map;for(let o of t)r.set(o,o===e.exitId?new Set([o]):new Set(n));let i=!0;for(;i;){i=!1;for(let o of e.cfg.values()){if(o.id===e.exitId)continue;let s=[...o.successors].map(c=>r.get(c)),a=new Set([o.id,...I_(s)]);Kd(r.get(o.id),a)||(r.set(o.id,a),i=!0)}}return r}function v_(e,t){let n=new Map(t.map(s=>[s.id,s.parentId])),r=t.flatMap(s=>[...s.cfg.values()].flatMap(a=>a.definitions.map(c=>c.point))),i=new Map;for(let s of r){if(!s.symbolKey)continue;let a=i.get(s.symbolKey)??[];a.push(s),i.set(s.symbolKey,a)}let o=new Set([...e.edges.values()].filter(s=>s.kind==="reaching-definition").map(s=>s.toPointId));for(let s of t)for(let a of[...s.cfg.values()].flatMap(c=>c.uses)){if(!a.point.symbolKey||o.has(a.point.id))continue;let c=i.get(a.point.symbolKey)??[];for(let l of c)C_(l.callableId,a.point.callableId,n)?Vo(e,"closure-capture",l.id,a.point.id,"candidate","Compiler identity proves the captured binding, but invocation order can select among outer definitions."):a.property&&Vo(e,"field-definition-to-use",l.id,a.point.id,"candidate","Compiler identity matches the field; cross-callable receiver and execution order remain unresolved.")}[...e.edges.values()].some(s=>s.kind==="closure-capture")&&e.unsupported.add("Closure capture identity is known, but invocation order and intervening writes remain candidate flow."),[...e.edges.values()].some(s=>s.kind==="field-definition-to-use")&&e.unsupported.add("Cross-callable field flow lacks receiver points-to and invocation-order analysis.")}function C_(e,t,n){for(let r=n.get(t)??null;r;r=n.get(r)??null)if(r===e)return!0;return!1}function Vo(e,t,n,r,i,o){let s=`local-flow-edge:${t}:${encodeURIComponent(n)}:${encodeURIComponent(r)}`;e.edges.set(s,{id:s,kind:t,fromPointId:n,toPointId:r,strength:i,reason:o})}function Uv(e,t){return t>=e.SyntaxKind.FirstAssignment&&t<=e.SyntaxKind.LastAssignment}function x_(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 qv(e){return[...new Map(e.map(t=>[t.point.id,t])).values()]}function R_(e){return[...new Map(e.map(t=>[t.id,t])).values()]}function E_(e){return new Set(e.flatMap(t=>[...t]))}function I_(e){return e.length===0?new Set:new Set([...e[0]].filter(t=>e.slice(1).every(n=>n.has(t))))}function Kd(e,t){return e.size===t.size&&[...e].every(n=>t.has(n))}function w_(e,t){return e.start-t.start||e.kind.localeCompare(t.kind)||e.id.localeCompare(t.id)}function Gd(e){return{points:[],edges:[],coverage:{status:"unsupported",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:[e]}}}var P_=Nn("typescript-local-flow",{clearGroups:["whole-project","source-file","semantic-provider"]});function Wd(e,t,n,r){if(!Gn(t))return null;let i=`${t}\0${n}\0${r}`;return P_.get(e,i,()=>{let o=W(e,t);return o?Bv(o,L_(e.config.projectRoot,t),{startLine:n,endLine:r}):{points:[],edges:[],coverage:{status:"unsupported",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:[`Current source is unavailable for ${t}.`]}}})}function D_(e,t=new Map){let n=new Map,r=new Map,i=[];for(let o of e.transfers){if(!e.caller)continue;let s=yc(e.caller,o.callerPosition),a=yc(e.callee,o.calleePosition);Yo(n,s),Yo(n,a),Yd(r,e.caller,s),Yd(r,e.callee,a);let c=nt("edge","data-transfer",o.proof.file,String(o.proof.startLine),String(o.callerPosition),String(o.calleePosition));r.set(c,{id:c,kind:"data-transfer",fromNodeId:s.id,toNodeId:a.id,directed:!0,disposition:"folded",semantics:[{family:"data",subtype:"argument-to-parameter",attributes:{argumentText:o.argumentText,callerPosition:o.callerPosition,calleePosition:o.calleePosition}}],evidence:[{method:"compiler-callsite-direct-parameter-transfer",strength:"exact",identity:`${e.caller.symbol}:${o.callerPosition} -> ${e.callee.symbol}:${o.calleePosition}`,location:{file:o.proof.file,line:o.proof.startLine,endLine:o.proof.endLine}}]})}return e.unknown.forEach((o,s)=>{let a=yc(e.callee,o.calleePosition);Yo(n,a),Yd(r,e.callee,a);let c=t.get(o.calleePosition);if(c&&j_(c)){$_(r,n,e,o.calleePosition,o.argumentText,c);return}let l=O_(e,o.calleePosition,o.argumentText);Yo(n,l);let u=nt("edge","data-transfer-unsupported",o.proof.file,String(o.proof.startLine),String(o.calleePosition),String(s));r.set(u,{id:u,kind:"data-transfer",fromNodeId:l.id,toNodeId:a.id,directed:!0,disposition:"unsupported",semantics:[{family:"data",subtype:"argument-to-parameter",attributes:{argumentText:o.argumentText,calleePosition:o.calleePosition}}],evidence:[{method:"compiler-callsite-argument-expression",strength:"exact",identity:o.argumentText,location:{file:o.proof.file,line:o.proof.startLine,endLine:o.proof.endLine}}]}),i.push({id:nt("frontier","data-transfer",u),kind:"data-transfer",direction:"unresolved",fromNodeIds:[l.id],edgeIds:[u],memberNodeIds:[a.id],memberCount:1,disposition:"unsupported",reason:c?.derivation.rule??o.reason,expansion:null})}),{nodes:[...n.values()],edges:[...r.values()],frontiers:i,blindSpots:[]}}function zv(e,t,n=[]){let r=Kv(),i=new Map,o=new Set;for(let s of t){if(s.kind!=="call"||!s.fromSymbol||!s.toSymbol||s.line===null)continue;let a=__(i,e,s.toFile,s.toSymbol);if(!a)continue;let c=Kf(e,a),l=c.sites.filter(g=>g.file===s.fromFile&&g.startLine<=s.line&&g.endLine>=s.line&&g.caller?.symbol===s.fromSymbol);if(l.length!==1){let g=c.unresolved.find(h=>h.file===s.fromFile&&h.line===s.line);g&&r.blindSpots.push(`Parameter flow unresolved at ${s.fromFile}:${s.line+1}: ${g.reason}.`);continue}let u=l[0],d=`${u.file}\0${u.callNode.startIndex}\0${u.callNode.endIndex}\0${a.symbol}`;if(o.has(d))continue;o.add(d);let m=Wf(e,u),p=J(e,u.file)?.rootNode,f=new Map;if(p)for(let g of m.unknown){let h=Nf({db:e,file:u.file,root:p},u.arguments[g.calleePosition]);h&&f.set(g.calleePosition,h)}Gv(r,D_(m,f)),m.caller&&k_(u.callNode)&&N_(r,m,u.callNode)}for(let s of n){if(!s.location||!["source-construct","symbol"].includes(s.kind))continue;let a=s.location.endLine??s.location.line,c=Wd(e,s.location.file,s.location.line,a);if(c){Gv(r,M_(s,c.points,c.edges));for(let l of c.coverage.unsupported)r.blindSpots.push(`TypeScript local flow is partial for ${s.location.file}:${s.location.line+1}-${a+1}: ${l} Recover with: scip-query inspect --at '${s.location.file}:${s.location.line+1}-${a+1}' --view behavior.`)}}return r.blindSpots=[...new Set(r.blindSpots)].sort(),r}function M_(e,t,n){let r=Kv(),i=new Map,o=new Map,s=new Map,a=e.location.file;for(let c of t){let l=T_(e,a,c);s.set(c.id,l.id),i.set(l.id,l),A_(o,e,l)}for(let c of n){let l=s.get(c.fromPointId),u=s.get(c.toPointId);if(!l||!u)continue;let d=F_(c),m=nt("edge","typescript-local-flow",a,c.id);o.set(m,{id:m,kind:c.kind==="control-dependence"?"control-dependence":"data-transfer",fromNodeId:l,toNodeId:u,directed:!0,disposition:"folded",semantics:[d],evidence:[{method:"typescript-compiler-cfg-reaching-definitions",strength:c.strength,identity:c.reason,location:i.get(l)?.location??e.location}]})}return r.nodes=[...i.values()],r.edges=[...o.values()],r}function T_(e,t,n){return{id:nt("local-flow-point",t,String(n.start),String(n.end),n.kind,n.symbolKey??n.name),kind:n.kind==="parameter-definition"||n.kind==="definition"?"local-definition":n.kind==="use"?"local-use":n.kind==="predicate"?"control-predicate":"local-statement",label:n.name,disposition:"folded",location:{file:t,line:n.line,endLine:n.line},anchorIds:[],attributes:{ownerNodeId:e.id,pointKind:n.kind,callableId:n.callableId,symbolKey:n.symbolKey,column:n.column}}}function A_(e,t,n){let r=nt("edge","local-flow-owner",t.id,n.id);e.has(r)||e.set(r,{id:r,kind:"local-flow-owner",fromNodeId:t.id,toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:"contains"}],evidence:[{method:"typescript-compiler-local-flow-owner",strength:"exact",identity:t.id,location:n.location}]})}function F_(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 k_(e){let t=e;for(;t.parent&&["await_expression","yield_expression","parenthesized_expression","as_expression","type_assertion"].includes(t.parent.type);)t=t.parent;return t.parent!==null&&t.parent.type!=="expression_statement"}function N_(e,t,n){if(!t.caller)return;let r={id:nt("call-result",t.call.file,String(n.startIndex),String(n.endIndex),t.callee.symbol),kind:"call-result",label:`result of ${t.callee.leaf}`,disposition:"folded",location:{file:t.call.file,line:t.call.startLine,endLine:t.call.endLine},anchorIds:[],attributes:{calleeSymbol:t.callee.symbol,callerSymbol:t.caller.symbol}},i=nt("edge","return-to-call-result",t.callee.symbol,r.id),o=nt("edge","call-result-owner",t.caller.symbol,r.id);e.nodes.push(r),e.edges.push({id:i,kind:"data-transfer",fromNodeId:Jd(t.callee.symbol),toNodeId:r.id,directed:!0,disposition:"folded",semantics:[{family:"data",subtype:"return-to-call-result"}],evidence:[{method:"compiler-callsite-used-result",strength:"exact",identity:`${t.callee.symbol} -> ${t.caller.symbol}`,location:r.location}]},{id:o,kind:"call-result-owner",fromNodeId:Jd(t.caller.symbol),toNodeId:r.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:"contains-call-result"}],evidence:[{method:"compiler-call-result-owner",strength:"exact",identity:t.caller.symbol,location:r.location}]})}function Kv(){return{nodes:[],edges:[],frontiers:[],blindSpots:[]}}function Gv(e,t){Vd(e.nodes,t.nodes),Vd(e.edges,t.edges),Vd(e.frontiers,t.frontiers),e.blindSpots.push(...t.blindSpots)}function Vd(e,t){let n=new Set(e.map(r=>r.id));for(let r of t)n.has(r.id)||(n.add(r.id),e.push(r))}function __(e,t,n,r){let i=`${n}\0${r}`,o=e.get(i);if(o!==void 0)return o;let s=U(t,n).find(a=>a.symbol===r)??null;return e.set(i,s),s}function yc(e,t){return{id:q_(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 O_(e,t,n){return{id:nt("argument-expression",e.call.file,String(e.call.startLine),String(e.call.endLine),String(t)),kind:"argument-expression",label:n,disposition:"unsupported",location:{file:e.call.file,line:e.call.startLine,endLine:e.call.endLine},anchorIds:[],attributes:{calleeSymbol:e.callee.symbol,position:t}}}function B_(e,t,n){return{id:nt("static-value",e.call.file,String(e.call.startLine),String(e.call.endLine),String(t)),kind:"static-value",label:n.value,disposition:"folded",location:{file:e.call.file,line:e.call.startLine,endLine:e.call.endLine},anchorIds:[],attributes:{value:n.value,precision:n.precision,evidence:n.evidence,termKind:n.term.kind,derivationRule:n.derivation.rule}}}function $_(e,t,n,r,i,o){let s=B_(n,r,o),a=yc(n.callee,r);Yo(t,s);let c=nt("edge","static-value-transfer",n.call.file,String(n.call.startLine),String(r));e.set(c,{id:c,kind:"data-transfer",fromNodeId:s.id,toNodeId:a.id,directed:!0,disposition:"folded",semantics:[{family:"data",subtype:H_(o),attributes:{argumentText:i,calleePosition:r,value:o.value,precision:o.precision,derivationRule:o.derivation.rule}}],evidence:U_(o,n)})}function j_(e){return e.derivation.kind!=="heuristic"&&e.precision!=="symbolic"&&e.precision!=="unknown"}function H_(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 U_(e,t){return(e.derivation.sourceSpans.length>0?e.derivation.sourceSpans:[t.call]).map(r=>({method:`static-value:${e.derivation.rule}`,strength:e.derivation.kind==="direct"?"exact":"derived",identity:e.derivation.inputFactIds.join(",")||e.value,location:{file:r.file,line:r.startLine,endLine:r.endLine}}))}function Yo(e,t){e.has(t.id)||e.set(t.id,t)}function Yd(e,t,n){let r=nt("edge","parameter-owner",t.symbol,n.id);e.has(r)||e.set(r,{id:r,kind:"parameter-owner",fromNodeId:Jd(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 q_(e,t){return nt("parameter",e,String(t))}function Jd(e){return nt("symbol",e)}function nt(...e){return e.map(t=>encodeURIComponent(t)).join(":")}function Wv(e,t){let n=new Map,r=new Map,i=new Map,o=new Set;for(let s of t){if(!s.location||!["source-construct","symbol"].includes(s.kind))continue;let a=s.location.endLine??s.location.line,c=$g(e,s.location.file,s.location.line,a);if(!c){o.add(`Control dependence unavailable for ${s.location.file}:${s.location.line+1}-${a+1}: no supported syntax tree or covering construct.`);continue}for(let l of c.facts){let u=Xd(s,l.controller),d=Xd(s,l.outcome);n.set(u.id,u),n.set(d.id,d),G_(r,s,u);let m=Kr("edge","control-dependence",u.id,d.id,l.subtype);r.set(m,{id:m,kind:"control-dependence",fromNodeId:u.id,toNodeId:d.id,directed:!0,disposition:"folded",semantics:[{family:"control",subtype:l.subtype,attributes:{...l.attributes}}],evidence:[{method:"parser-control-dependence",strength:"exact",identity:`${s.location.file}:${l.controller.startLine+1}-${l.outcome.startLine+1}`,location:{file:s.location.file,line:l.controller.startLine,endLine:l.controller.endLine}}]})}for(let l of c.terminals){let u=Xd(s,l);n.set(u.id,u);let d=l.label.startsWith("throw")||l.label.startsWith("raise")?"throw":"return",m=Kr("edge","control-terminal",s.id,u.id,d);r.set(m,{id:m,kind:"control-terminal",fromNodeId:s.id,toNodeId:u.id,directed:!0,disposition:"folded",semantics:[{family:"control",subtype:d==="throw"?"throws":"returns"}],evidence:[{method:"parser-terminal-statement",strength:"exact",identity:l.label,location:{file:s.location.file,line:l.startLine,endLine:l.endLine}}]})}for(let l of c.unsupported){let u=Kr("control-unsupported",s.location.file,String(l.startLine),String(l.endLine),l.reason);n.set(u,{id:u,kind:"control-unsupported",label:l.reason,disposition:"unsupported",location:{file:s.location.file,line:l.startLine,endLine:l.endLine},anchorIds:[],attributes:{ownerNodeId:s.id}});let d=Kr("edge","control-unsupported",s.id,u);r.set(d,{id:d,kind:"control-dependence",fromNodeId:s.id,toNodeId:u,directed:!0,disposition:"unsupported",semantics:[{family:"control",subtype:"unresolved-control-construct"}],evidence:[{method:"parser-control-construct",strength:"exact",identity:l.reason,location:{file:s.location.file,line:l.startLine,endLine:l.endLine}}]});let m=Kr("frontier","control-dependence",u);i.set(m,{id:m,kind:"control-dependence",direction:"unresolved",fromNodeIds:[s.id],edgeIds:[d],memberNodeIds:[u],memberCount:1,disposition:"unsupported",reason:l.reason,expansion:null})}}return{nodes:[...n.values()],edges:[...r.values()],frontiers:[...i.values()],blindSpots:[...o].sort()}}function Xd(e,t){let n=e.location.file;return{id:Kr(`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 G_(e,t,n){let r=Kr("edge","control-owner",t.id,n.id);e.has(r)||e.set(r,{id:r,kind:"control-owner",fromNodeId:t.id,toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:"contains-control"}],evidence:[{method:"parser-control-owner",strength:"exact",identity:t.id,location:t.location}]})}function Kr(...e){return e.map(t=>encodeURIComponent(t)).join(":")}var bc=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"]),Xo=new Set(["block","body","compound_statement","declaration_list","statement_block"]),z_=new Set(["assignment","assignment_expression","augmented_assignment_expression"]),Zd=new Set(["update_expression"]),Xv=new Set(["array_access","element_access_expression","subscript_expression"]),Qv=new Set(["attribute","field_access","field_expression","member_access_expression","member_expression","selector_expression"]),K_=new Set(["false","null","null_literal","number","number_literal","string","string_literal","template_string","true"]),W_=new Set(["call_expression","method_invocation","object_creation_expression"]),V_=new Set(["comment","else_clause","formal_parameters","parameters","type_parameters"]);function Zv(e,t,n,r){let i=J(e,t);if(!i)return null;let o=nO(i.rootNode,n,r);if(!o)return null;let s=[],a=[],c=[];return Wr(o,l=>{if(z_.has(l.type)||Zd.has(l.type)||tC(l)){let u=Y_(l);u?s.push(u):c.push({family:"state",startLine:l.startPosition.row,endLine:l.endPosition.row,reason:`Mutation target ${rn(l.text)} could not be resolved to an exact source resource.`})}}),Wr(o,l=>{if(!Xo.has(l.type))return;let u=eO(l);for(let d=0;d<u.length-1;d+=1)a.push({from:Jo(u[d]),to:Jo(u[d+1]),subtype:"lexical-successor",synchronizationScope:null,attributes:{sameScope:!0,executionConditional:!0}});for(let d=0;d<u.length;d+=1){let m=u[d],p=iO(m).filter(f=>f.type==="await_expression");for(let f of p){let g=Qo("event",`await ${rn(f.text.replace(/^await\s+/u,""))}`,f);a.push({from:Jo(m),to:g,subtype:"awaits-completion",synchronizationScope:null,attributes:{completionRequired:!0}});let h=u[d+1];h&&a.push({from:g,to:Jo(h),subtype:"await-completion-before",synchronizationScope:null,attributes:{continuationOnly:!0}})}}}),Wr(o,l=>{if(l.type!=="synchronized_statement")return;let u=l.childForFieldName("object")??l.childForFieldName("condition")??l.namedChildren.find(g=>!Xo.has(g.type)),d=l.childForFieldName("body")??l.namedChildren.find(g=>Xo.has(g.type));if(!u||!d){c.push({family:"temporal",startLine:l.startPosition.row,endLine:l.endPosition.row,reason:"Synchronized scope has no structurally resolved monitor or body."});return}let m=rn(u.text).replace(/^\(|\)$/gu,""),p=Qo("lock",m,u),f=rO(d).filter(g=>g.parent!==null&&nC(g));for(let g of tO(f))a.push({from:p,to:Jo(g),subtype:"inside-lock-scope",synchronizationScope:m,attributes:{syntaxNative:!0}})}),{mutations:s,temporal:a,unsupported:c}}function Y_(e){let t=tC(e),n=e.childForFieldName("left")??e.childForFieldName("argument")??(t?e.namedChildren.at(-1)??null:e.namedChildren[0]??null);if(!n)return null;let r=J_(n);if(!r)return null;let i=t?"delete":Zd.has(e.type)||!Z_(e,n).startsWith("=")?"update":"assign",o=t||Zd.has(e.type)?null:e.childForFieldName("right");return{event:Qo("event",rn(e.text),e),resource:{kind:"resource",label:r.name,startLine:n.startPosition.row,endLine:n.endPosition.row},operation:i,durabilityClass:"in-memory",recordIdentity:r.recordIdentity,value:o?Qo("value",rn(o.text),o):null,dataSubtype:o?X_(o,e):null}}function J_(e){if(Xv.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:`${rn(t.text)}[]`,recordIdentity:rn(n.text)}}return Qv.has(e.type)?{name:rn(e.text),recordIdentity:null}:/^(?:identifier|property_identifier|field_identifier)$/u.test(e.type)?{name:rn(e.text),recordIdentity:null}:null}function X_(e,t){return K_.has(e.type)||/(?:integer|float|decimal|boolean|character)_literal$/u.test(e.type)?"constant-to-state":W_.has(e.type)?"return-to-state":Qv.has(e.type)||Xv.has(e.type)?"property-to-state":/identifier$/u.test(e.type)?Q_(e.text,t)?"captured-value-to-state":"value-to-state":"expression-to-state"}function Q_(e,t){let n=Qd(t.parent);if(!n||Vv(n,e))return!1;let r=Qd(n.parent);for(;r;){if(Vv(r,e))return!0;r=Qd(r.parent)}return!1}function Qd(e){let t=e;for(;t;){if(bc.has(t.type))return t;t=t.parent}return null}function Vv(e,t){let n=e.childForFieldName("parameters")??e.namedChildren.find(o=>["formal_parameters","parameters"].includes(o.type));if(n&&Yv(n,t))return!0;let r=e.childForFieldName("body")??e.namedChildren.find(o=>Xo.has(o.type));if(!r)return!1;let i=!1;return eC(r,e,o=>{if(i||!/(?:declarator|declaration|parameter)$/u.test(o.type))return;let s=o.childForFieldName("name")??o.childForFieldName("pattern")??o.namedChildren[0];s&&Yv(s,t)&&(i=!0)}),i}function Yv(e,t){let n=!1;return Wr(e,r=>{/identifier$/u.test(r.type)&&r.text===t&&(n=!0)}),n}function eC(e,t,n){n(e);for(let r of e.namedChildren)r!==t&&bc.has(r.type)||eC(r,t,n)}function Z_(e,t){let n=e.childForFieldName("right"),r=Math.max(0,t.endIndex-e.startIndex),i=n?Math.max(r,n.startIndex-e.startIndex):e.text.length;return e.text.slice(r,i).trim()}function tC(e){return(e.type==="delete_expression"||e.type==="unary_expression")&&/^delete\b/u.test(e.text.trim())}function eO(e){return e.namedChildren.filter(t=>nC(t))}function nC(e){return V_.has(e.type)||Xo.has(e.type)?!1:/(?:statement|declaration)$/u.test(e.type)||e.type==="expression_statement"||e.type==="local_variable_declaration"}function tO(e){let t=new Set(e);return e.filter(n=>{let r=n.parent;for(;r;){if(t.has(r))return!1;r=r.parent}return!0})}function Jo(e){return Qo("event",rn(e.text),e)}function Qo(e,t,n){return{kind:e,label:t,startLine:n.startPosition.row,endLine:n.endPosition.row}}function nO(e,t,n){let r=[];return Wr(e,o=>{o.startPosition.row<=t&&o.endPosition.row>=n&&r.push(o)}),r.filter(o=>bc.has(o.type)).sort(Jv)[0]??r.sort(Jv)[0]??null}function Jv(e,t){return e.endIndex-e.startIndex-(t.endIndex-t.startIndex)||e.startIndex-t.startIndex}function rO(e){let t=[];return Wr(e,n=>t.push(n)),t}function iO(e){let t=[],n=r=>{t.push(r);for(let i of r.namedChildren)i!==e&&bc.has(i.type)||n(i)};return n(e),t}function Wr(e,t){t(e);for(let n of e.namedChildren)Wr(n,t)}function rn(e){return e.trim().replace(/\s+/gu," ")}function oC(e,t,n=[]){let r=new Map,i=new Map,o=new Map,s=new Set;for(let a of t){if(!a.location||!["source-construct","symbol"].includes(a.kind))continue;let c=a.location.endLine??a.location.line,l=Zv(e,a.location.file,a.location.line,c);if(!l){s.add(`State and temporal analysis unavailable for ${a.location.file}:${a.location.line+1}-${c+1}: no supported syntax tree or covering construct.`);continue}for(let u of l.mutations){let d=vc(a,u.event),m=uO(a,u.resource,u.durabilityClass);if(r.set(d.id,d),r.set(m.id,m),Cc(i,a,d,"contains-state-effect"),xc(i,{kind:"state-resource",from:d,to:m,semantics:[{family:"state",subtype:u.operation==="delete"?"deletes-resource":"writes-resource",attributes:{operation:u.operation,durabilityClass:u.durabilityClass,resource:u.resource.label,recordIdentity:u.recordIdentity,transactionMembership:"unknown"}}],method:"parser-state-mutation",identity:u.event.label}),u.value&&u.dataSubtype){let p=vc(a,u.value);r.set(p.id,p),xc(i,{kind:"data-to-state",from:p,to:m,semantics:[{family:"data",subtype:u.dataSubtype,attributes:{operation:u.operation,resource:u.resource.label,recordIdentity:u.recordIdentity,value:u.value.label}}],method:"parser-assignment-value",identity:`${u.value.label} -> ${u.resource.label}`})}}for(let u of l.temporal){let d=vc(a,u.from),m=vc(a,u.to);r.set(d.id,d),r.set(m.id,m),Cc(i,a,d,u.from.kind==="lock"?"contains-lock-scope":"contains-event"),Cc(i,a,m,"contains-event"),xc(i,{kind:"temporal-order",from:d,to:m,semantics:[{family:"temporal",subtype:u.subtype,context:u.synchronizationScope?{synchronizationScope:u.synchronizationScope}:void 0,attributes:{...u.attributes}}],method:u.subtype==="inside-lock-scope"?"parser-synchronized-scope":"parser-program-order",identity:`${u.from.label} -> ${u.to.label}`})}for(let u of l.unsupported){let d=Pn(`${u.family}-unsupported`,a.location.file,String(u.startLine),String(u.endLine),u.reason);r.set(d,{id:d,kind:`${u.family}-unsupported`,label:u.reason,disposition:"unsupported",location:{file:a.location.file,line:u.startLine,endLine:u.endLine},anchorIds:[],attributes:{ownerNodeId:a.id}});let m=Pn("edge",`${u.family}-unsupported`,a.id,d);i.set(m,{id:m,kind:`${u.family}-unsupported`,fromNodeId:a.id,toNodeId:d,directed:!0,disposition:"unsupported",semantics:[{family:u.family,subtype:`unresolved-${u.family}-construct`}],evidence:[{method:`parser-${u.family}-construct`,strength:"exact",identity:u.reason,location:{file:a.location.file,line:u.startLine,endLine:u.endLine}}]});let p=Pn("frontier",u.family,d);o.set(p,{id:p,kind:u.family,direction:"unresolved",fromNodeIds:[a.id],edgeIds:[m],memberNodeIds:[d],memberCount:1,disposition:"unsupported",reason:u.reason,expansion:null})}}for(let a of t.filter(c=>c.kind==="runtime-boundary-participant")){let c=Sc(a,"protocol"),l=Sc(a,"action"),u=Sc(a,"address")??a.label;!c||!l||!iC(c,l)||rC(r,i,a,{observationId:a.id,action:l,strength:"exact",file:a.location?.file??"",line:a.location?.line??0,address:u,protocol:c,role:Sc(a,"role")??void 0,resolution:"locally-linked"})}for(let a of n){if(!a.protocol||!iC(a.protocol,a.action))continue;let c=cO(t,a.file,a.line,a.ownerShortName??null);if(!c){s.add(`State observation ${a.observationId} at ${a.file}:${a.line+1} has no materialized owner node.`);continue}rC(r,i,c,a)}return{nodes:[...r.values()],edges:[...i.values()],frontiers:[...o.values()],blindSpots:[...s].sort()}}function rC(e,t,n,r){let i=sO(r),s={id:Pn("runtime-state-event",r.observationId),kind:"runtime-state-event",label:`${r.action} ${i}`,disposition:"folded",location:{file:r.file,line:r.line},anchorIds:[],attributes:{action:r.action,protocol:r.protocol??null,modality:r.modality??null,resolution:r.resolution??null}},a=r.protocol==="database"?"external-durable-intent":"external",c={id:Pn("runtime-state-resource",r.protocol??"unknown",i),kind:"runtime-state-resource",label:i,disposition:"folded",location:{file:r.file,line:r.line},anchorIds:[],attributes:{protocol:r.protocol??null,durabilityClass:a}};e.set(s.id,s),e.set(c.id,c),Cc(t,n,s,"contains-runtime-state-effect");let l=oO(r.action);xc(t,{kind:"runtime-state-resource",from:s,to:c,semantics:[{family:"state",subtype:l,context:{crossesRuntimeBoundary:!0,protocol:r.protocol},attributes:{operation:r.action,durabilityClass:a,resource:i,recordIdentity:aO(r),modality:r.modality??null,resolution:r.resolution??null,transactionMembership:"unknown",commitState:r.protocol==="database"?"unknown":null}}],method:`runtime-boundary-${r.strength}`,identity:r.observationId})}function oO(e){return e==="database.read"?"reads-resource":e==="queue.send"?"enqueues-resource":e==="queue.consume"?"consumes-resource":"writes-resource"}function sO(e){return(e.keyParts?.find(n=>["address","resource"].includes(n.name))?.value??e.address)||e.observationId}function aO(e){return e.keyParts?.find(n=>/^(?:id|key|record)$/u.test(n.name))?.value??null}function iC(e,t){return e==="database"&&["database.read","database.write"].includes(t)||e==="queue"&&["queue.consume","queue.send"].includes(t)}function Sc(e,t){let n=e.attributes[t];return typeof n=="string"?n:null}function cO(e,t,n,r){let i=e.filter(s=>s.location?.file===t&&["source-construct","symbol"].includes(s.kind)),o=i.filter(s=>s.location.line<=n&&(s.location.endLine??s.location.line)>=n).sort(lO)[0];if(o)return o;if(r){let s=i.find(a=>a.label===r||a.label.endsWith(`.${r}`)||a.label.includes(r));if(s)return s}return i.length===1?i[0]:null}function lO(e,t){let n=(e.location?.endLine??e.location?.line??0)-(e.location?.line??0),r=(t.location?.endLine??t.location?.line??0)-(t.location?.line??0);return n-r}function vc(e,t){let n=e.location.file;return{id:Pn(`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 uO(e,t,n){let r=e.location.file;return{id:Pn("program-resource",r,e.id,t.label,n),kind:"program-resource",label:t.label,disposition:"folded",location:{file:r,line:t.startLine,endLine:t.endLine},anchorIds:[],attributes:{ownerNodeId:e.id,durabilityClass:n}}}function Cc(e,t,n,r){let i=Pn("edge","program-owner",t.id,n.id,r);e.has(i)||e.set(i,{id:i,kind:"program-owner",fromNodeId:t.id,toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:r}],evidence:[{method:"parser-program-owner",strength:"exact",identity:t.id,location:n.location}]})}function xc(e,t){let n=Pn("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 Pn(...e){return e.map(t=>encodeURIComponent(t)).join(":")}var dO=new Set(["control","data","state","temporal"]),Rc=new Set(["contains-control","contains-event","contains-lock-scope","contains-state-effect","contains-runtime-state-effect","contains","owns-parameter","owns-runtime-observation"]),lC=new Set(["discriminator-dispatch","result-callback","returns","runtime-handoff","throws"]);function uC(e,t={}){let n=new Map(e.nodes.map(E=>[E.id,E])),r=bO(e.nodes,t.focusLocations),i=SO(e.edges,t.focusLocations),o=vO(e.edges,i),s=new Set(e.paths.flatMap(E=>E.edgeIds)),a=Dn(e.anchors.filter(E=>E.status==="matched").flatMap(E=>E.nodeIds)),l=e.edges.filter(cC).filter(E=>mO(E,r,i,s)),u=l.filter(E=>hO(E,r,i,o,n,s)),d=sC(a,u,"forward"),m=gO(d,u),p=sC(m,u,"backward"),f=new Set([...d].filter(E=>p.has(E)));for(let E of a)f.add(E);let g=new Set(u.filter(E=>f.has(E.fromNodeId)&&f.has(E.toNodeId)).map(E=>E.id)),h=new Set(f),b=new Set(g);pO(l,h,b,r,i);let S=e.frontiers.filter(E=>xO(E,h)),y=Dn(S.filter(E=>E.disposition==="unsupported").map(E=>E.id)),x=Dn(e.edges.filter(E=>!cC(E)&&mC(E)&&CO(E,h)).map(E=>E.id)),v=Dn(S.map(E=>E.id)),C=[];a.length===0&&C.push("No matched anchor node starts the corridor."),m.length===0&&C.push("No proved mechanical outcome is reachable from a matched anchor."),y.length>0&&C.push(`${y.length} unsupported frontier(s) touch the protected corridor.`),x.length>0&&C.push(`${x.length} candidate or unknown edge(s) touch the protected corridor.`);let R=C.length===0?"complete":"incomplete";return{schemaVersion:1,status:R,startNodeIds:a,outcomeNodeIds:m,baseNodeIds:Dn([...f]),baseEdgeIds:Dn([...g]),nodeIds:Dn([...h]),edgeIds:Dn([...b]),accountedFrontierIds:v,unresolvedFrontierIds:y,unresolvedEdgeIds:x,coverage:{protectedNodes:h.size,protectedEdges:b.size,baseNodes:f.size,baseEdges:g.size,accountedFrontiers:v.length,unresolvedFrontiers:y.length,unresolvedEdges:x.length},explanation:R==="complete"?"Every proved anchor-to-outcome path is closed over its material causal facts within reported coverage.":C.join(" ")}}function mO(e,t,n,r){return t===null||e.disposition==="emitted"||r.has(e.id)||n?.has(e.id)===!0?!0:(e.semantics??[]).some(i=>{if(i.family==="identity"&&Rc.has(i.subtype))return t.has(e.toNodeId);if(i.family==="contract")return t.has(e.fromNodeId)&&t.has(e.toNodeId);if(i.family==="state")return t.has(e.fromNodeId);if(i.family==="data"||i.family==="temporal")return t.has(e.fromNodeId)||t.has(e.toNodeId);if(i.family==="control"){if(pC(i))return t.has(e.fromNodeId);if(["returns","throws"].includes(i.subtype))return t.has(e.toNodeId);if(i.subtype==="completion-callback")return t.has(e.fromNodeId)||t.has(e.toNodeId)}return!1})}function pO(e,t,n,r,i){let o=!0;for(;o;){o=!1;for(let s of e)fO(s,t,r,i)&&(n.has(s.id)||(n.add(s.id),o=!0),t.has(s.fromNodeId)||(t.add(s.fromNodeId),o=!0),t.has(s.toNodeId)||(t.add(s.toNodeId),o=!0))}}function fO(e,t,n,r){let i=t.has(e.fromNodeId),o=t.has(e.toNodeId);return!i&&!o?!1:(e.semantics??[]).some(s=>s.family==="identity"?Rc.has(s.subtype)&&(o||n===null||n.has(e.toNodeId)):s.family==="contract"?!0:s.family==="state"?i&&(n===null||n.has(e.fromNodeId)):s.family==="temporal"?s.subtype==="lexical-successor"?i&&o:!0:s.family==="data"?o&&(i||n===null||n.has(e.fromNodeId)||r?.has(e.id)===!0):s.family==="control"?dC(s)||["returns","throws"].includes(s.subtype)&&!o&&n!==null&&!n.has(e.toNodeId)?!1:lC.has(s.subtype)||pC(s)||s.subtype==="completion-callback":!1)}function gO(e,t){let n=new Set,r=new Map,i=new Map;for(let o of t)!e.has(o.fromNodeId)||!e.has(o.toNodeId)||(r.set(o.fromNodeId,(r.get(o.fromNodeId)??0)+1),i.set(o.toNodeId,(i.get(o.toNodeId)??0)+1),(o.semantics??[]).some(s=>s.family==="state"||s.family==="control"&&lC.has(s.subtype))&&n.add(o.toNodeId));for(let o of e)(i.get(o)??0)>0&&(r.get(o)??0)===0&&n.add(o);return Dn([...n])}function sC(e,t,n){let r=new Map;for(let s of t){let a=n==="forward"?s.fromNodeId:s.toNodeId,c=n==="forward"?s.toNodeId:s.fromNodeId,l=r.get(a)??[];l.push(c),r.set(a,l)}let i=new Set(e),o=[...e];for(;o.length>0;){let s=o.shift();for(let a of r.get(s)??[])i.has(a)||(i.add(a),o.push(a))}return i}function hO(e,t,n,r,i,o){return(e.semantics??[]).some(s=>e.disposition==="emitted"||o.has(e.id)?!0:s.family==="identity"&&Rc.has(s.subtype)?t===null||t.has(e.toNodeId)||r?.has(e.toNodeId)===!0:!dO.has(s.family)||dC(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"?yO(e,i)&&(t.has(e.fromNodeId)||t.has(e.toNodeId)):!1)}function dC(e){return e.family==="control"&&["call","discriminator-dispatch","result-callback","runtime-handoff"].includes(e.subtype)}function yO(e,t){let n=t.get(e.fromNodeId),r=t.get(e.toNodeId);if(!n||!r)return!1;let i=aC(n,"ownerNodeId")??(n.kind==="symbol"?n.id:null),o=aC(r,"ownerNodeId")??(r.kind==="symbol"?r.id:null);return i!==null&&i===o}function bO(e,t){if(!t)return null;let n=new Map;for(let r of t){let i=n.get(r.file)??[];i.push(r.line),n.set(r.file,i)}return new Set(e.filter(r=>{if(!r.location||r.kind==="parameter")return!1;let i=n.get(r.location.file)??[],o=r.location.endLine??r.location.line;return i.some(s=>s>=r.location.line&&s<=o)}).map(r=>r.id))}function SO(e,t){if(!t)return null;let n=new Map;for(let r of t){let i=n.get(r.file)??[];i.push(r.line),n.set(r.file,i)}return new Set(e.filter(r=>r.evidence.some(i=>{if(!i.location)return!1;let o=n.get(i.location.file)??[],s=i.location.endLine??i.location.line;return o.some(a=>a>=i.location.line&&a<=s)})).map(r=>r.id))}function vO(e,t){return t===null?null:new Set(e.filter(n=>t.has(n.id)).flatMap(n=>[n.fromNodeId,n.toNodeId]))}function aC(e,t){let n=e.attributes[t];return typeof n=="string"?n:null}function cC(e){return e.disposition==="excluded"||e.disposition==="unsupported"||!mC(e)?!1:e.evidence.some(t=>t.strength==="exact"||t.strength==="derived")}function mC(e){return(e.semantics??[]).some(t=>t.family!=="identity"||Rc.has(t.subtype))}function pC(e){return e.subtype.startsWith("predicate-")||e.subtype.startsWith("loop-")||e.subtype.startsWith("exception-")||e.subtype.startsWith("finally-")||e.subtype.startsWith("handler-")}function CO(e,t){return t.has(e.fromNodeId)||t.has(e.toNodeId)}function xO(e,t){return[...e.fromNodeIds,...e.memberNodeIds].some(n=>t.has(n))}function Dn(e){return[...new Set(e)].sort()}import{createHash as RO}from"crypto";var Ec=["identity","contract","control","data","state","temporal"],EO=new Set(Ec);function wc(e){let t=Oi(e.anchors,"anchor"),n=Oi(e.nodes,"node"),r=Oi(e.edges,"edge"),i=Oi(e.paths??[],"path"),o=Oi(e.frontiers??[],"frontier"),s=new Set(t.map(p=>p.id)),a=new Set(n.map(p=>p.id)),c=new Set(r.map(p=>p.id)),l=e.routeCatalog?{...e.routeCatalog,routes:Oi(e.routeCatalog.routes,"route"),selectedRouteIds:lt(e.routeCatalog.selectedRouteIds)}:void 0;for(let p of t)ht(`anchor ${p.id}`,[...p.nodeIds,...p.candidateNodeIds],a,"node");for(let p of n)ht(`node ${p.id}`,p.anchorIds,s,"anchor");for(let p of r){if(ht(`edge ${p.id}`,[p.fromNodeId,p.toNodeId],a,"node"),p.evidence.length===0)throw new Error(`Exploration edge ${p.id} has no evidence source.`);LO(p)}for(let p of i)ht(`path ${p.id}`,[p.fromAnchorId,p.toAnchorId],s,"anchor"),ht(`path ${p.id}`,p.nodeIds,a,"node"),ht(`path ${p.id}`,p.edgeIds,c,"edge");for(let p of o)if(ht(`frontier ${p.id}`,p.fromNodeIds,a,"node"),ht(`frontier ${p.id}`,p.edgeIds,c,"edge"),ht(`frontier ${p.id}`,p.memberNodeIds,a,"node"),p.memberCount!==p.memberNodeIds.length)throw new Error(`Exploration frontier ${p.id} reports ${p.memberCount} member(s) but identifies ${p.memberNodeIds.length}.`);for(let p of l?.routes??[])ht(`route ${p.id}`,p.nodeIds,a,"node"),ht(`route ${p.id}`,p.edgeIds,c,"edge"),ht(`route ${p.id}`,[p.anchorNodeId,p.endpointNodeId],a,"node");l&&ht("route catalog selection",l.selectedRouteIds,new Set(l.routes.map(p=>p.id)),"route");let u=lt(e.incompleteReasons??[]),d=u.length===0?"accounted":"incomplete",m=t.reduce((p,f)=>p+f.omittedCandidates,0);return{schemaVersion:1,anchors:t,nodes:n,edges:r,paths:i,frontiers:o,coverage:{status:d,scope:e.scope,nodes:xC(n),edges:xC(r),matchedAnchors:t.filter(p=>p.status==="matched").length,ambiguousAnchors:t.filter(p=>p.status==="ambiguous").length,missingAnchors:t.filter(p=>p.status==="missing").length,omittedCandidates:m,frontierGroups:o.length,programEdges:wO(r),blindSpots:lt(e.blindSpots??[]),explanation:d==="accounted"?"Every node and edge discovered within the declared query scope is emitted, folded with recoverable identity, explicitly excluded, or reported unsupported.":`The declared query scope is not fully accounted for: ${u.join("; ")}`},completion:MO(d,i,e.scope),...l?{routeCatalog:l}:{}}}function IO(e){return e.flatMap(t=>PO(t.semantics??[]).map(n=>({id:DO(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 wO(e){let t=IO(e),n=new Set(t.map(s=>s.sourceEdgeId)),r=new Map(Ec.map(s=>[s,new Set])),i=new Map(Ec.map(s=>[s,new Set])),o=new Map(Ec.map(s=>[s,0]));for(let s of t)r.get(s.family).add(s.sourceEdgeId),i.get(s.family).add(s.subtype),o.set(s.family,o.get(s.family)+1);return{sourceEdges:e.length,mappedSourceEdges:n.size,projectedEdges:t.length,unmappedSourceEdges:e.length-n.size,unsupportedSourceEdges:e.filter(s=>s.disposition==="unsupported").length,unmappedKinds:lt(e.filter(s=>!n.has(s.id)).map(s=>s.kind)),families:{identity:_i("identity",r,o,i),contract:_i("contract",r,o,i),control:_i("control",r,o,i),data:_i("data",r,o,i),state:_i("state",r,o,i),temporal:_i("temporal",r,o,i)}}}function _i(e,t,n,r){return{sourceEdges:t.get(e)?.size??0,projectedEdges:n.get(e)??0,subtypes:[...r.get(e)??[]].sort()}}function LO(e){let t=new Set;for(let n of e.semantics??[]){if(!EO.has(n.family))throw new Error(`Exploration edge ${e.id} has unknown program edge family: ${n.family}.`);if(n.subtype.trim().length===0)throw new Error(`Exploration edge ${e.id} has an empty program edge subtype.`);let r=em(n);if(t.has(r))throw new Error(`Exploration edge ${e.id} repeats program edge semantic ${r}.`);t.add(r)}}function PO(e){return[...e].sort((t,n)=>em(t).localeCompare(em(n)))}function em(e){return`${e.family}:${e.subtype}`}function DO(e,t){return`program:${encodeURIComponent(e)}:${t.family}:${encodeURIComponent(t.subtype)}`}function MO(e,t,n){return e==="incomplete"||t.some(r=>r.status!=="connected")?{status:"coverage-incomplete",scope:n,explanation:"The declared graph query has an ambiguous, missing, candidate-only, or disconnected anchor relationship."}:t.length>0?{status:"connector-complete",scope:n,explanation:"Every requested anchor pair has a selected path supported by proved repository relationships."}:{status:"frontier-accounted",scope:n,explanation:"Every discovered direction in the declared graph query is emitted or represented by an exact frontier."}}function RC(e,t={}){let n=t.maxSelectedNodes??24;if(!Number.isSafeInteger(n)||n<=0)throw new RangeError(`maxSelectedNodes must be a positive safe integer; received ${n}`);let r=new Set(e.anchors.flatMap(w=>[...w.nodeIds,...w.candidateNodeIds])),i=[],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 A=w+1;A<o.length;A+=1){let D=o[w],k=o[A],L=bC(e,D,k,!1),P=L??bC(e,D,k,!0);P?(P.nodeIds.forEach(j=>r.add(j)),i.push({id:Ic("path",D.id,k.id),fromAnchorId:D.id,toAnchorId:k.id,status:!L||D.status==="ambiguous"||k.status==="ambiguous"?"candidate":"connected",nodeIds:P.nodeIds,edgeIds:P.edgeIds})):i.push({id:Ic("path",D.id,k.id),fromAnchorId:D.id,toAnchorId:k.id,status:"partial",nodeIds:[],edgeIds:[]})}let s=lt(t.routeIds??[]),a=TO(e,s),c=new Set(a.routes.map(w=>w.id)),l=s.filter(w=>!c.has(w));if(l.length>0)throw new Error(`Unknown exploration route id(s): ${l.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(A=>r.add(A));let m=i.length===0||i.some(w=>w.edgeIds.length>0);m&&vC(e,r,n);let p=CC(e,r),f=new Set(t.expandedFrontierIds??[]),g=new Set(p.map(w=>w.id)),h=[...f].filter(w=>!g.has(w)).sort();if(h.length>0)throw new Error(`Unknown exploration frontier id(s): ${h.join(", ")}`);for(let w of p)f.has(w.id)&&w.memberNodeIds.forEach(A=>r.add(A));m&&vC(e,r,n);let b=new Map(d.map(w=>[w.endpointNodeId,w.endpointKind])),S=new Set(d.flatMap(w=>w.nodeIds)),y=new Map;for(let w of d)for(let A=0;A<w.nodeIds.length;A+=1){let D=w.nodeIds[A],k=A;y.set(D,Math.max(y.get(D)??0,k))}let x=e.nodes.map(w=>{let A=b.get(w.id),D=S.has(w.id)?{upstreamCausalPath:!0,upstreamCausalDistance:y.get(w.id)??0,...A?{upstreamCausalEndpoint:A}:{}}:{};return{...w,attributes:{...w.attributes,...D},disposition:w.disposition==="excluded"||w.disposition==="unsupported"?w.disposition:r.has(w.id)?"emitted":"folded"}}),v=new Set([...i.flatMap(w=>w.edgeIds),...d.flatMap(w=>w.edgeIds)]),C=e.edges.map(w=>({...w,disposition:w.disposition==="excluded"||w.disposition==="unsupported"?w.disposition:v.has(w.id)||r.has(w.fromNodeId)&&r.has(w.toNodeId)?"emitted":"folded"})),R=wc({anchors:e.anchors,nodes:x,edges:C,paths:i,frontiers:[...e.frontiers.filter(w=>w.disposition!=="folded"),...CC({...e,nodes:x,edges:C},r)],scope:e.coverage.scope,blindSpots:e.coverage.blindSpots,incompleteReasons:e.coverage.status==="incomplete"?[e.coverage.explanation]:[],routeCatalog:a}),E=new Set(R.frontiers.flatMap(w=>w.edgeIds)),I=R.edges.filter(w=>w.disposition==="folded"&&!E.has(w.id)).map(w=>w.id);if(I.length>0)throw new Error(`Folded exploration edge(s) are not frontier-accounted: ${I.sort().join(", ")}`);return R}var fC=10;function TO(e,t=[]){let n=new Map(e.nodes.map(h=>[h.id,h])),r=new Map(e.edges.map(h=>[h.id,h])),i=new Map;for(let h of e.edges){if(!AO(h))continue;let b=i.get(h.toNodeId)??[];b.push(h),i.set(h.toNodeId,b)}for(let h of i.values())h.sort((b,S)=>Number(Zo(S))-Number(Zo(b))||yC(S)-yC(b)||b.fromNodeId.localeCompare(S.fromNodeId)||b.id.localeCompare(S.id));let o=lt(e.anchors.filter(h=>h.status==="matched").flatMap(h=>h.nodeIds)),s=new Map,a=new Set,c=(h,b,S)=>{let y=b.nodeIds[b.nodeIds.length-1],x=n.get(y),v=n.get(h);if(!x?.location||!v)return;let C=[...b.nodeIds].reverse(),R=[...b.edgeIds].reverse(),E=new Set(C),I=R.flatMap(L=>{let F=r.get(L);return F?[F]:[]}),w=e.edges.filter(L=>L.disposition!=="excluded"&&L.disposition!=="unsupported"&&(E.has(L.fromNodeId)||E.has(L.toNodeId))),A={id:Ic("route",h,y,S,...R),status:"proved",anchorNodeId:h,anchorLabel:v.label,endpointNodeId:y,endpointLabel:x.label,endpointLocation:{...x.location},endpointKind:S,nodeIds:C,edgeIds:R,evidenceStrengths:lt(I.flatMap(L=>L.evidence.map(F=>F.strength))),spineEdgeFamilies:gC(I,!0),relatedEdgeFamilies:gC(w,!1),crossesRuntimeBoundary:I.some(Zo)},D=`${h}\0${y}\0${S}`,k=s.get(D);(!k||hC(A,k)<0)&&s.set(D,A)};for(let h of o){n.get(h)?.attributes.publicEntry===!0&&c(h,{nodeIds:[h],edgeIds:[]},"public-entry");let b=[{nodeIds:[h],edgeIds:[]}],S=new Map([[h,0]]);for(let y=0;y<b.length;y+=1){let x=b[y],v=x.nodeIds[x.nodeIds.length-1];x.edgeIds.length>0&&n.get(v)?.location&&n.get(v)?.attributes.publicEntry===!0&&c(h,x,"public-entry");let C=i.get(v)??[];if(x.edgeIds.length>=fC){C.some(R=>!x.nodeIds.includes(R.fromNodeId))&&a.add(h);continue}for(let R of C){if(x.nodeIds.includes(R.fromNodeId))continue;let E=x.edgeIds.length+1,I=S.get(R.fromNodeId);if(I!==void 0&&I<=E)continue;let w={nodeIds:[...x.nodeIds,R.fromNodeId],edgeIds:[...x.edgeIds,R.id]};if(S.set(R.fromNodeId,E),Zo(R)&&n.get(R.fromNodeId)?.location){c(h,w,"runtime-boundary");continue}b.push(w)}}}let l=[...s.values()].sort(hC),u=new Set(l.map(h=>h.id)),d=lt(t.filter(h=>u.has(h))),m=lt(l.map(h=>h.anchorNodeId)),p=o.filter(h=>!m.includes(h)),f=[...a].sort(),g=e.coverage.status==="accounted"&&f.length===0?"accounted":"incomplete";return{schemaVersion:1,routes:l,selectedRouteIds:d,coverage:{status:g,scope:"Distinct proved public-entry and runtime-boundary endpoints reachable upstream in the supplied topology.",enumeration:"one-shortest-proved-path-per-endpoint",maximumDepth:fC,anchorNodeIds:o,anchorsWithRoutes:m,anchorsWithoutRoutes:p,depthLimitedAnchorNodeIds:f,routeCount:l.length,explanation:g==="accounted"?"Every distinct proved upstream public/runtime endpoint in the supplied topology has one stable shortest route.":"Route enumeration is incomplete because the supplied topology has incomplete coverage or a traversal reached the route-depth bound."}}}function gC(e,t){let n=e.flatMap(r=>r.semantics?.map(i=>i.family)??[]);return t&&e.length>0&&n.length===0&&n.push("control"),lt(n)}function hC(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 AO(e){return e.disposition!=="excluded"&&e.disposition!=="unsupported"&&FO(e)&&e.evidence.some(t=>["exact","derived","mixed"].includes(t.strength))}function FO(e){return Zo(e)||e.kind==="boundary-observation"||e.kind==="call"||e.kind==="compiler:call"}function Zo(e){return e.kind==="runtime-boundary"||e.kind.startsWith("runtime:")}function yC(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 bC(e,t,n,r){return SC(e,t,n,r)??SC(e,n,t,r)}function SC(e,t,n,r){let i=[...t.nodeIds,...t.candidateNodeIds].sort(),o=new Set([...n.nodeIds,...n.candidateNodeIds]);if(i.some(u=>o.has(u)))return{nodeIds:[i.find(d=>o.has(d))],edgeIds:[]};let s=new Set(e.nodes.filter(u=>u.kind==="structural-region").map(u=>u.id)),a=new Map;for(let u of e.edges)u.disposition==="excluded"||u.disposition==="unsupported"||u.kind==="structural-membership"||s.has(u.fromNodeId)||s.has(u.toNodeId)||u.evidence.every(m=>["candidate","unknown"].includes(m.strength))&&!r||kO(a,u.fromNodeId,u.toNodeId,u.id);for(let u of a.values())u.sort((d,m)=>d.nodeId.localeCompare(m.nodeId)||d.edgeId.localeCompare(m.edgeId));let c=i.map(u=>({nodeId:u,nodeIds:[u],edgeIds:[]})),l=new Set(i);for(let u=0;u<c.length;u+=1){let d=c[u];for(let m of a.get(d.nodeId)??[]){if(l.has(m.nodeId))continue;let p={nodeId:m.nodeId,nodeIds:[...d.nodeIds,m.nodeId],edgeIds:[...d.edgeIds,m.edgeId]};if(o.has(m.nodeId))return p;l.add(m.nodeId),c.push(p)}}return null}function kO(e,t,n,r){let i=e.get(t)??[];i.push({nodeId:n,edgeId:r}),e.set(t,i)}function NO(e,t,n){let r=new Map;for(let a of e.edges){let c=r.get(a.fromNodeId)??{incoming:0,outgoing:0},l=r.get(a.toNodeId)??{incoming:0,outgoing:0};c.outgoing+=1,l.incoming+=1,r.set(a.fromNodeId,c),r.set(a.toNodeId,l)}let i=new Set,o=new Map;for(let a of e.edges){let c=t.has(a.fromNodeId),l=t.has(a.toNodeId);if(c===l)continue;let u=c?a.toNodeId:a.fromNodeId,d=c?a.fromNodeId:a.toNodeId,m=e.nodes.find(g=>g.id===u);if(m?.kind==="structural-region")continue;let p=o.get(u)??new Set;p.add(d),o.set(u,p),(/(?:runtime-boundary|external)/u.test(a.kind)||m&&/(?:frontier|external)/u.test(m.kind))&&i.add(u)}let s=[...o].filter(([a,c])=>{if(i.has(a))return!0;let l=r.get(a)??{incoming:0,outgoing:0};return(l.incoming>1||l.outgoing>1)&&c.size>1}).sort(([a,c],[l,u])=>Number(i.has(l))-Number(i.has(a))||u.size-c.size||a.localeCompare(l)).map(([a])=>a);for(let a of s){if(t.size>=n)break;t.add(a)}}function vC(e,t,n){let r=-1;for(;t.size!==r&&t.size<n;)r=t.size,NO(e,t,n)}function CC(e,t){let n=new Set(e.nodes.filter(s=>!t.has(s.id)&&s.disposition!=="excluded"&&s.disposition!=="unsupported").map(s=>s.id)),r=new Map;for(let s of e.edges){if(!n.has(s.fromNodeId)||!n.has(s.toNodeId))continue;let a=r.get(s.fromNodeId)??new Set,c=r.get(s.toNodeId)??new Set;a.add(s.toNodeId),c.add(s.fromNodeId),r.set(s.fromNodeId,a),r.set(s.toNodeId,c)}let i=[],o=new Set;for(let s of[...n].sort()){if(o.has(s))continue;let a=[],c=[s];o.add(s);for(let l=0;l<c.length;l+=1){let u=c[l];a.push(u);for(let d of[...r.get(u)??[]].sort())o.has(d)||(o.add(d),c.push(d))}i.push(a.sort())}return i.map(s=>{let a=new Set(s),c=e.edges.filter(f=>a.has(f.fromNodeId)||a.has(f.toNodeId)),l=c.filter(f=>a.has(f.fromNodeId)!==a.has(f.toNodeId)),u=lt(l.map(f=>a.has(f.fromNodeId)?f.toNodeId:f.fromNodeId)),d=new Set(l.map(f=>a.has(f.toNodeId)?"outgoing":"incoming")),m=lt(c.map(f=>f.id)),p=lt(l.map(f=>f.kind));return{id:Ic("frontier",...s,...m),kind:p.join("+")||"disconnected",direction:d.size===1?[...d][0]:"undirected",fromNodeIds:u,edgeIds:m,memberNodeIds:s,memberCount:s.length,disposition:"folded",reason:l.length>0?"Connected evidence is folded beyond the first edge leaving the selected connector graph.":"Discovered evidence is disconnected from every selected anchor connector under the declared relation scope.",expansion:null}})}function Ic(e,...t){let n=RO("sha256").update(t.join("\0")).digest("hex").slice(0,16);return`${e}:${n}`}function Oi(e,t){let n=[...e].sort((r,i)=>r.id.localeCompare(i.id));for(let r=1;r<n.length;r+=1)if(n[r-1].id===n[r].id)throw new Error(`Duplicate exploration ${t} id: ${n[r].id}`);return n}function ht(e,t,n,r){let i=lt(t.filter(o=>!n.has(o)));if(i.length>0)throw new Error(`Exploration ${e} references missing ${r}(s): ${i.join(", ")}`)}function xC(e){return{total:e.length,emitted:e.filter(t=>t.disposition==="emitted").length,folded:e.filter(t=>t.disposition==="folded").length,excluded:e.filter(t=>t.disposition==="excluded").length,unsupported:e.filter(t=>t.disposition==="unsupported").length}}function lt(e){return[...new Set(e)].sort()}var _O=5,OO=12,BO=8,$O=3,EC=8,jO=6,HO=12,IC=12,UO=12,qO=2,GO=new Set(["branch","loop","call","await","return","throw","mutation","catch","finally"]),zO=9e3,wC=kv,LC=new WeakMap;function KO(e,t){return BC(e,t,"full")}function OC(e,t){return BC(e,t,"topology")}function WO(e,t,n,r,i,o=!1){let s=e.get(t);if(s)return s.depth=Math.min(s.depth,n),s.primary||=i,s.promoteBoundaryImports||=o,s.origins.add(r),s;let a={file:t,depth:n,primary:i,promoteBoundaryImports:o,origins:new Set([r]),processed:!1};return e.set(t,a),a}function VO(e,t,n,r,i,o,s="none",a=!1){let c=e.get(n.symbol);if(c)return c.depth=Math.min(c.depth,r),c.origins.add(i),o&&c.anchorQueries.add(o),c.referenceScope=KB(c.referenceScope,s),t(n.relativePath,r,i,!0,a),c;let l={definition:n,depth:r,origins:new Set([i]),anchorQueries:new Set(o?[o]:[]),referenceScope:s,processed:!1};return e.set(n.symbol,l),t(n.relativePath,r,i,!0,a),l}function YO(e,t,n,r,i,o,s=!1,a=!0){let c=on(n),l=e.get(c);if(l)return l.depth=Math.min(l.depth,r),l.origins.add(i),o&&l.anchorQueries.add(o),l.reverseCallExpansion||=s,l.traversalEligible||=a,t(n.file,r,i,l.traversalEligible,!0),l;let u={...n,depth:r,origins:new Set([i]),anchorQueries:new Set(o?[o]:[]),reverseCallExpansion:s,traversalEligible:a};return e.set(c,u),t(n.file,r,i,a,!0),u}function JO(e){let{db:t,index:n,pendingRelations:r,addFile:i,addSymbol:o,addSourceConstruct:s,observation:a,depth:c,origin:l}=e;i(a.source.file,c,l,!0,!0),a.owner.file!==a.source.file&&i(a.owner.file,c,`${l}:owner`,!0,!0);let u=U(t,a.owner.file),d=a.owner.symbol?lr(t,n,a.owner.symbol).matches.find(f=>f.relativePath===a.owner.file):null,m=(d&&!pe(d.symbol)?d:null)??Oe(u,a.source.startLine);if(m&&!pe(m.symbol))return o(m,c,l,void 0,"none",!0),m.symbol;a.owner.name&&s({file:a.owner.file,name:a.owner.name,startLine:a.owner.startLine,endLine:a.owner.endLine},c,`${l}:source-owner`,void 0,!0);let p=e.index.definitionsForFile(a.source.file).filter(f=>!!f.leaf&&hn(t,a.source.file,f.leaf).some(g=>g>=a.source.startLine&&g<=a.source.endLine));if(p.length===1){let f=p[0];o(f,c,`${l}:handler-identifier`,void 0,"none",!0),St(r,{kind:"runtime-boundary",evidence:"runtime-boundary:handler-identifier",fromFile:a.source.file,fromSymbol:null,toFile:f.relativePath,toSymbol:f.symbol,fromBoundaryParticipant:$i(a),line:a.source.startLine,strength:"derived"})}return null}function XO(e){let t=0,n=0,r=0;for(let i of e.searches){let o=DB(e.db,e.index,i,e.boundaryObservationLocations),s=o.filter(u=>kB(u,e.sourceAllowed)),a=!e.opts.fullLiteralTraversal&&(o.length>OO||s.length>BO),c=a?[]:o,l=new Set((a?[]:e.opts.fullLiteralTraversal?s:[...s].sort(MB).slice(0,$O)).map(AC));a&&(n+=1,r+=o.length);for(let u of c){let d=l.has(AC(u)),m=d&&!u.ownerSymbol&&u.ownerStartLine!==null&&u.ownerEndLine!==null;if(e.addFile(u.relativePath,0,`${d?"literal-anchor":"literal-match"}:${i}`,m,m),m&&e.addSourceConstruct({file:u.relativePath,name:u.ownerShortName??`${u.relativePath}:${u.ownerStartLine+1}`,startLine:u.ownerStartLine,endLine:u.ownerEndLine},0,`literal-source-owner:${i}`,i,!0),d&&u.ownerSymbol){let p=lr(e.db,e.index,u.ownerSymbol).matches[0];p&&!pe(p.symbol)&&e.addSymbol(p,0,"literal-owner",i,"all",!0)}e.literalHits.push({query:i,file:u.relativePath,line:u.line,ownerSymbol:u.ownerSymbol,ownerShortName:u.ownerShortName,ownerStartLine:u.ownerStartLine,ownerEndLine:u.ownerEndLine,sourceLine:u.sourceLine.trim(),matchKind:u.matchKind,traversalSeed:d})}e.anchors.push({kind:"literal",query:i,status:o.length>0?"matched":"missing",matchedRegionIds:[],matchingLines:o.length,seedMatchingLines:a?0:l.size,matchOnlyLines:o.length-l.size,eligibleSeedMatchingLines:s.length,materializedMatchingLines:c.length,withheldMatchingLines:a?o.length:0,literalTraversal:a?"withheld-broad":"materialized",representativeMatches:a?NB(i,o):void 0,narrowingCommands:a?OB(i,o):void 0,exhaustiveTraversalCommand:a||l.size<s.length?`scip-query system-map --search ${ye(i)} --full-literal-traversal`:void 0,seedRegionIds:[],matchOnlyRegionIds:[]})}for(let i of e.symbolQueries){let o=lr(e.db,e.index,i);t+=o.omitted;let s=TB(e.db,i),a=o.matches.filter(m=>!pe(m.symbol)),c=s!==null&&a.length===0;c&&e.addSourceConstruct(s,0,"source-construct-anchor",i,!0);let l=c?a:o.matches;for(let m of l)e.addSymbol(m,0,"symbol-anchor",i,"all",!0);let u=c?AB(s):null,d=c?1:o.total;e.anchors.push({kind:"symbol",query:i,status:d===0?"missing":d===1?"matched":"ambiguous",matchedRegionIds:[],symbolCandidates:[...u?[u]:[],...l.map(UB)],totalSymbolCandidates:d,omittedSymbolCandidates:o.omitted})}return{omittedSymbolCandidates:t,broadLiteralAnchors:n,withheldLiteralMatches:r}}function QO(e){let{db:t,opts:n,mode:r,searches:i,symbolQueries:o,maxDepth:s,maxTopologyCharacters:a,requestedRelationKinds:c,evidenceFloor:l,includedSourceScopes:u,workspaces:d,runtimeBoundaries:m,boundaryObservations:p,representedBoundaryLinkIds:f,files:g,symbols:h,sourceConstructs:b,literalHits:S,pendingRelations:y,externalImports:x,anchors:v,omittedSymbolCandidates:C,broadLiteralAnchors:R,withheldLiteralMatches:E,filteredUnverifiedCallEdges:I,memberCallCandidateEdges:w,unresolvedMemberCallsites:A,sourceAllowed:D}=e,k=new Set(c),L=new Map;for(let _ of g.keys())L.set(_,es(_,d));let F=[...y.values()].filter(_=>L.has(_.fromFile)&&L.has(_.toFile)).map(_=>({..._,fromRegionId:L.get(_.fromFile).id,toRegionId:L.get(_.toFile).id})).sort(UC),P=t$(F),j=new Set(n.expand??[]),B=XB(g,h,S,F,P,L,j),X=new Set([...g.values()].filter(_=>[..._.origins].some(ce=>ce.startsWith("literal-anchor:")||ce==="literal-owner"||ce==="symbol-anchor")).map(_=>L.get(_.file).id)),G=wB(B),O=new Set(B.map(_=>_.id)),te=[...j].filter(_=>!O.has(_)).sort();for(let _ of v)if(_.matchedRegionIds=r$(_,S,h,L),_.kind==="literal"){let ce=S.filter(je=>je.query===_.query);_.seedRegionIds=fe(ce.filter(je=>je.traversalSeed).map(je=>L.get(je.file).id)),_.matchOnlyRegionIds=fe(ce.filter(je=>!je.traversalSeed).map(je=>L.get(je.file).id))}let ie=[...h.values()].filter(_=>!_.processed).length,Le=[...g.values()].filter(_=>_.primary&&!_.processed).length,Me=[...g.values()].filter(_=>!_.primary&&!_.processed).length,Nt=[...h.values()].filter(_=>_.processed),tt=(m?.frontiers??[]).flatMap(_=>{let ce=p.get(_.observationId);return!ce&&_.source&&_.action&&_.strength?!k.has("runtime-boundary")||!D(_.source.file)||l==="exact"||!g.has(_.source.file)?[]:[{observationId:_.observationId,action:_.action,strength:_.strength,file:_.source.file,line:_.source.startLine,ownerShortName:_.ownerShortName??null,address:_.address??_.missingKeyParts.join(", "),reason:_.reason}]:!k.has("runtime-boundary")||!ce||!D(ce.source.file)||l==="exact"&&ce.strength!=="exact"||!g.has(ce.source.file)?[]:[{observationId:ce.id,action:ce.action,strength:ce.strength,file:ce.source.file,line:ce.source.startLine,ownerShortName:ce.owner.name,address:HC(ce),reason:_.reason,protocol:ce.protocol,role:ce.role,modality:ce.modality,resolution:ce.resolution,sourceScope:ce.sourceScope,keyParts:ce.keyParts.map(je=>({name:je.name,value:je.value,evidence:je.evidence}))}]}).sort((_,ce)=>_.file.localeCompare(ce.file)||_.line-ce.line),M=(m?.links??[]).filter(_=>{if(!k.has("runtime-boundary")||l==="exact"&&_.strength!=="exact")return!1;let ce=p.get(_.from),je=p.get(_.to);return!!(ce&&je&&D(ce.source.file)&&D(je.source.file)&&(g.has(ce.source.file)||g.has(je.source.file)))}),$=M.filter(_=>_.strength==="exact").length,Y=M.filter(_=>_.strength==="derived").length,oe=M.filter(_=>_.strength==="candidate").length,Ne=m?.links.filter(_=>_.strength==="exact").length??0,qt=m?.links.filter(_=>_.strength==="derived").length??0,Zr=m?.links.filter(_=>_.strength==="candidate").length??0,hr=n$(x,L),bl=C===0?"accounted":"incomplete",Gp=[...R>0?[`${R} broad literal anchor(s) withheld ${E} exact match(es) before graph traversal; representative identities and scoped search commands preserve recovery without treating every textual occurrence as relevant.`]:[],`Literal matches outside the included source scopes (${u.join(", ")}) remain visible as match-only evidence and do not seed traversal.`,m?"Built-in runtime-boundary extractors traverse direct and replayably derived links; heuristic candidates, unsupported frameworks, reflection, generated names, and dependency wiring not recoverable from compiler occurrences or constructor assignments remain disclosed frontiers.":"Runtime-boundary evidence is unavailable for this index; run scip-query reindex with this build to extract supported HTTP, event, registry, and persistence observations.","Reverse references do not recursively expand from discovered callers or callees.","Member calls use compiler occurrences, exact constructor-assigned fields, bounded unique service providers, direct factory-return members, and compiler-resolved object-literal callbacks when available. Ambiguous providers remain candidate frontiers; callback values routed through mutation, reflection, or unsupported dependency containers remain unrepresented.","Literal traversal is bounded to the smallest parser-delimited source construct; parser gaps may reduce an owner to one source line and leave its continuation untraversed.","Schema consumers stay within forward-flow regions; cross-workspace contracts may discover consumers in other workspaces. Add an explicit symbol anchor to widen either scope.",`Traversal stops after depth ${s}; nonzero frontier counts identify evidence that was discovered but not traversed.`,"Region labels are structural path groupings, not inferred runtime or architectural boundaries."],vt=gB({db:t,anchors:v,regions:B,symbolStates:h,sourceConstructStates:b,literalHits:S,relations:F,externalBoundaries:hr,boundaryFrontiers:tt,regionForFile:L,closureStatus:bl,omittedSymbolCandidates:C,maxDepth:s,requestedRelationKinds:c,evidenceFloor:l,includedSourceScopes:u,blindSpots:Gp,topologyFrontiers:n.topologyFrontiers??[],routeIds:n.routeIds??[],expandedRegionIds:[...j],maxTopologyCharacters:a,fullLiteralTraversal:n.fullLiteralTraversal??!1});if(r==="topology")return vt;let zp=(n.behaviorFocusLocations?.length??0)>0?new Set([...vt.anchors.flatMap(_=>_.nodeIds),...vt.paths.flatMap(_=>_.nodeIds)]).size:void 0,Ds=NS(t,vt,{focusLocations:n.behaviorFocusLocations,...zp?{maxSteps:zp}:{}});pv(t,vt,Ds);let Ew=rB(t,vt,Ds,n.behaviorFocusLocations??[]);vt.corridor=uC(vt,{focusLocations:Ew});let Kp=mv(t,vt,Ds,{sourceAllowed:D,selectionTerms:n.selectionTerms}),Wp=vB(vt),Iw=EB(i,o,s,c,l,u,n.fullLiteralTraversal??!1,a,B,P,X,j,Wp),ww=RB(i,o,s,B.filter(_=>Wp.has(_.id)),X,c,l,u,n.fullLiteralTraversal??!1,a);return{anchors:v,regions:B,regionRelations:P,externalBoundaries:hr,boundaryFrontiers:tt,unmatchedExpansions:te,expansion:ww,drilldown:G,presentation:Iw,topology:vt,behavior:Ds,nextAnchors:Kp,closure:{status:bl,emitted:{regions:B.length,relations:F.length,runtimeLinks:f.size},withheld:{symbols:ie,files:Le+Me,regions:vt.nodes.filter(_=>_.kind==="structural-region"&&_.disposition==="folded").length,drillAnchors:(G?.omittedAnchors??0)+Kp.omittedAnchors,literalMatches:E},ambiguous:{anchors:v.filter(_=>_.status==="ambiguous").length,omittedSymbolCandidates:C},external:hr.length,unresolved:tt.length,explanation:bl==="accounted"?"Every fact reached under the declared anchors, relations, depth, evidence floor, source scopes, and installed analyzers is accounted for as emitted, withheld, ambiguous, external, or unresolved.":"Some ambiguous symbol candidates were not identified, so the declared query is not fully accounted for."},coverage:{explicitAnchorCount:v.length,requestedRelationKinds:c,evidenceFloor:l,includedSourceScopes:u,matchedAnchorCount:v.filter(_=>_.status!=="missing").length,literalSearchesComplete:!0,broadLiteralAnchors:R,withheldLiteralMatches:E,symbolCandidateSetsComplete:C===0,omittedSymbolCandidates:C,maxTraversalDepth:s,frontierSymbols:ie,frontierFiles:Le,supportFilesNotTraversed:Me,filteredUnverifiedCallEdges:I,memberCallCandidateEdges:w,unresolvedMemberCallsites:A,runtimeBoundaryEvidenceAvailable:m!==null,runtimeBoundaryObservations:m?.observations.length??0,runtimeBoundaryExactLinks:$,runtimeBoundaryDerivedLinks:Y,runtimeBoundaryCandidateLinks:oe,repositoryRuntimeBoundaryExactLinks:Ne,repositoryRuntimeBoundaryDerivedLinks:qt,repositoryRuntimeBoundaryCandidateLinks:Zr,runtimeBoundaryTraversedLinks:f.size,runtimeBoundaryFrontiers:tt.length,referenceExpansionEligibleSymbols:Nt.filter(_=>_.referenceScope!=="none").length,referenceExpansionSkippedSymbols:Nt.filter(_=>_.referenceScope==="none").length,dynamicDispatchRepresented:m?.links.some(_=>_.joinRule==="carrier.discriminator"&&f.has(_.id))??!1,runtimeGeneratedLinksRepresented:m!==null,regionBoundariesAreStructural:!0,relationFamilies:{"literal-anchor":{evidence:"exact-source",scope:"all indexed documents for each explicit literal",completeWithinScope:!0},reference:{evidence:"compiler-graph",scope:"all cross-file indexed/source-attributed sites for explicit anchors and promoted non-module boundary symbols",completeWithinScope:!0},call:{evidence:"mixed",scope:"static callees plus exact SCIP call occurrences in traversed source ranges, exact constructor-assigned member receivers, and uniquely attributed direct-import member candidates",completeWithinScope:!0},"contract-symbol":{evidence:"compiler-graph",scope:"compiler-resolved symbol identities referenced across inferred workspace boundaries",completeWithinScope:!0},import:{evidence:"compiler-graph",scope:"all indexed or source-resolved imports of traversed primary files",completeWithinScope:!0},"runtime-boundary":{evidence:"exact-source",scope:"direct and mechanically derived links produced by grounded runtime adapters and factorized relation groups",completeWithinScope:!0}},blindSpots:Gp}}}function ZO(e,t){let{db:n,relationPolicy:r,sourceConstructs:i,reverseExpandedSourceConstructs:o,pendingRelations:s,reverseFileGraph:a,serviceCallerFilesBySourceConstruct:c,sourceAllowed:l,memberCallTargetsForWholeFile:u,addSymbol:d,addSourceConstruct:m}=e;if(r.has("call")){let p=[...i.values()].filter(f=>f.traversalEligible&&f.reverseCallExpansion&&f.depth<=t&&!o.has(on(f)));for(let f of p){o.add(on(f));let g=K(n,f.file);if((g?.callables??[]).filter(S=>S.name===f.name&&S.startLine<=f.endLine&&S.endLine>=f.startLine).length===1){let S=(g?.callSites??[]).filter(y=>y.calleeLeaf===f.name&&!y.memberAccess);for(let y of S){let x=t+1,v=Oe(U(n,f.file),y.line),C=null,R=null;if(v&&!pe(v.symbol)){if(v.relativePath===f.file&&v.startLine<=f.endLine&&v.endLine>=f.startLine)continue;d(v,x,"reverse-local-call-owner",void 0,"forward-regions",!0),C=v.symbol}else{let E=tm(n,f.file,y.line);E&&on(E)!==on(f)&&(R=m(E,x,"reverse-local-call-source-owner",void 0,!0))}!C&&!R||St(s,{kind:"call",evidence:"ast-callsite",fromFile:f.file,fromSymbol:C,toFile:f.file,toSymbol:null,fromSourceConstruct:R?ut(R):void 0,toSourceConstruct:ut(f),line:y.line,strength:"derived"})}}let b=new Set([...a.get(f.file)??[],...c.get(on(f))??[],...bS(n,f.file).flatMap(S=>[...a.get(S)??[]])]);for(let S of b){if(!l(S))continue;let x=u(S).targets.filter(v=>v.targetFile===f.file&&v.targetStartLine<=f.endLine&&v.targetEndLine>=f.startLine);for(let v of x){let C=t+1,R=Oe(U(n,S),v.line),E=null,I=null;if(R&&!pe(R.symbol))d(R,C,"reverse-member-call-owner",void 0,"cross-workspace-or-forward",!0),E=R.symbol;else{let w=tm(n,S,v.line);w&&(I=m(w,C,"reverse-member-call-source-owner",void 0,!0))}!E&&!I||St(s,{kind:"call",evidence:"ast-service-member-callsite",fromFile:S,fromSymbol:E,toFile:f.file,toSymbol:null,fromSourceConstruct:I?ut(I):void 0,toSourceConstruct:ut(f),line:v.line,strength:v.strength==="exact"?"exact":"derived"})}}}}}function eB(e,t){let{db:n,index:r,relationPolicy:i,symbols:o,sourceAllowed:s,files:a,workspaces:c,addFile:l,addSymbol:u,addSourceConstruct:d,pendingRelations:m,fileGraph:p,traversalMetrics:f}=e,g=[...o.values()].filter(b=>!b.processed&&b.depth<=t),h=i.has("call")?r.calleeMap(g.map(b=>b.definition),{additive:!1,semantic:!1}):new Map;for(let b of g){b.processed=!0;let S=b.definition;if(b.referenceScope!=="none"&&(i.has("call")||i.has("reference")||i.has("contract-symbol"))){let y=$B(n,r,S).filter(v=>s(v.file)&&zB(b,v.file,a,c)),x=new Set(y.flatMap(v=>{if(!(i.has("call")&&K(n,v.file)?.callSites.some(E=>E.line===v.line&&PC(n,v.file,E,S))===!0)||!v.enclosingSymbol)return[];let R=lr(n,r,v.enclosingSymbol).matches[0];return R&&!pe(R.symbol)?[{owner:R,site:v}]:[]}).sort((v,C)=>{let R=yt(S.relativePath,c).relativeDir,E=yt(v.owner.relativePath,c).relativeDir===R,I=yt(C.owner.relativePath,c).relativeDir===R,w=DC(n,v.owner),A=DC(n,C.owner),D=v.owner.endLine-v.owner.startLine,k=C.owner.endLine-C.owner.startLine;return Number(I)-Number(E)||A-w||D-k||v.owner.symbol.localeCompare(C.owner.symbol)}).filter((v,C,R)=>R.findIndex(E=>E.owner.symbol===v.owner.symbol)===C).reduce((v,C)=>{if(v.length>=qO)return v;let R=yt(C.owner.relativePath,c).relativeDir;return v.some(E=>E.workspace===R)||v.push({symbol:C.owner.symbol,workspace:R}),v},[]).map(v=>v.symbol));for(let v of y){let C=t+1;l(v.file,C,`reference:${T(S.symbol)}`,!0);let R=i.has("call")&&K(n,v.file)?.callSites.some(w=>w.line===v.line&&PC(n,v.file,w,S))===!0,E=null,I=null;if(v.enclosingSymbol){let w=lr(n,r,v.enclosingSymbol).matches[0];w&&!pe(w.symbol)&&(u(w,C,"reference-owner",void 0,R&&x.has(w.symbol)?b.referenceScope:"none"),E=w.symbol)}if(!E&&v.line!==null){let w=tm(n,v.file,v.line);w&&(I=d(w,C,"reference-source-owner",void 0,R))}i.has("reference")&&St(m,{kind:"reference",evidence:"indexed-or-source-reference",fromFile:v.file,fromSymbol:E,toFile:S.relativePath,toSymbol:S.symbol,fromSourceConstruct:I?ut(I):void 0,line:v.line,strength:"mixed"}),R&&St(m,{kind:"call",evidence:"ast-callsite",fromFile:v.file,fromSymbol:E,toFile:S.relativePath,toSymbol:S.symbol,fromSourceConstruct:I?ut(I):void 0,line:v.line,strength:"derived"}),i.has("contract-symbol")&&yt(v.file,c).relativeDir!==yt(S.relativePath,c).relativeDir&&St(m,{kind:"contract-symbol",evidence:"compiler-cross-workspace-symbol",fromFile:v.file,fromSymbol:E,toFile:S.relativePath,toSymbol:S.symbol,fromSourceConstruct:I?ut(I):void 0,line:v.line,strength:"exact"})}}for(let y of h.get(S.symbolId)??[]){let x=lr(n,r,y.symbol).matches.find(C=>C.relativePath===y.file);if(!x||!s(x.relativePath))continue;if(!(x.relativePath===S.relativePath||(p.get(S.relativePath)??new Set).has(x.relativePath))){f.filteredUnverifiedCallEdges+=1;continue}u(x,t+1,`call:${T(S.symbol)}`,void 0,"none",!0),St(m,{kind:"call",evidence:y.source,fromFile:S.relativePath,fromSymbol:S.symbol,toFile:x.relativePath,toSymbol:x.symbol,line:null,strength:xB(y.source)})}}}function tB(e,t){let{db:n,index:r,relationPolicy:i,files:o,sourceConstructs:s,symbols:a,boundaryObservations:c,boundaryObservationDepths:l,sourceAllowed:u,addSymbol:d,pendingRelations:m,traversalMetrics:p,addSourceConstruct:f,serviceCallerFilesBySourceConstruct:g,reverseFileGraph:h,externalImports:b,addFile:S,workspaces:y}=e,x=[...o.values()].filter(v=>!v.processed&&v.primary&&v.depth<=t);for(let v of x){v.processed=!0;let C=[...s.values()].filter(P=>P.traversalEligible&&P.file===v.file&&P.depth<=t),R=[...a.values()].filter(P=>P.definition.relativePath===v.file&&P.depth<=t).map(P=>{let j=bi(n,v.file,P.definition.startLine);return{startLine:j?.startLine??P.definition.startLine,endLine:j?.endLine??P.definition.endLine}}),E=P=>[...a.values()].filter(j=>j.definition.relativePath===v.file&&j.definition.startLine<=P&&j.definition.endLine>=P).sort((j,B)=>j.definition.endLine-j.definition.startLine-(B.definition.endLine-B.definition.startLine)||j.definition.startLine-B.definition.startLine)[0],I=[...c.values()].filter(P=>P.source.file===v.file&&l.has(P.id)),w=[...C.map(P=>({startLine:P.startLine,endLine:P.endLine})),...I.map(P=>({...Lc(n,P)}))],A=[...R,...w],D=(K(n,v.file)?.callSites??[]).filter(P=>A.some(j=>P.line>=j.startLine&&P.line<=j.endLine)),k=new Set;if(i.has("call"))for(let P of A){let j=In(n,v.file,P.startLine,P.endLine);for(let B of j.targets){if(!u(B.definition.relativePath))continue;let X=E(B.sourceLine),G=C.find(te=>te.startLine<=B.sourceLine&&te.endLine>=B.sourceLine),O=I.find(te=>{let ie=Lc(n,te);return ie.startLine<=B.sourceLine&&ie.endLine>=B.sourceLine});d(B.definition,t+1,`scip-occurrence-call:${v.file}:${B.sourceLine+1}`,void 0,"none",!0),St(m,{kind:"call",evidence:"scip-occurrence-callsite",fromFile:v.file,fromSymbol:X?.definition.symbol??null,toFile:B.definition.relativePath,toSymbol:B.definition.symbol,fromBoundaryParticipant:O?$i(O):void 0,fromSourceConstruct:G?ut(G):void 0,line:B.sourceLine,strength:"exact"}),k.add(`${B.sourceLine}\0${B.calleeLeaf}`)}}if(i.has("reference"))for(let P of A){let j=IS(n,v.file,P.startLine,P.endLine);for(let B of j.targets){if(!u(B.definition.relativePath)||k.has(`${B.sourceLine}\0${B.calleeLeaf}`))continue;let X=E(B.sourceLine);if(X?.definition.symbol===B.definition.symbol)continue;let G=C.find(te=>te.startLine<=B.sourceLine&&te.endLine>=B.sourceLine),O=I.find(te=>{let ie=Lc(n,te);return ie.startLine<=B.sourceLine&&ie.endLine>=B.sourceLine});d(B.definition,t+1,`scip-occurrence-reference:${v.file}:${B.sourceLine+1}`,void 0,"none",!0),St(m,{kind:"reference",evidence:"scip-occurrence-reference",fromFile:v.file,fromSymbol:X?.definition.symbol??null,toFile:B.definition.relativePath,toSymbol:B.definition.symbol,fromBoundaryParticipant:O?$i(O):void 0,fromSourceConstruct:G?ut(G):void 0,line:B.sourceLine,strength:"exact"})}}let L=i.has("call")?rr(n,v.file,{ranges:A,excludeIndexedTargets:!1}):{targets:[],unresolvedCallsites:0};p.unresolvedMemberCallsites+=L.unresolvedCallsites;let F=L.targets.filter(P=>!k.has(`${P.line}\0${P.calleeLeaf}`));p.memberCallCandidateEdges+=F.filter(P=>P.strength!=="exact"&&(P.resolution!=="imported-service-object-member"||(P.resolutionAlternativeCount??0)>1)).length;for(let P of F){let j=(P.resolutionAlternativeCount??1)===1,B=P.targetSymbol?U(n,P.targetFile).find(ie=>ie.symbol===P.targetSymbol):void 0,X=B?null:f({file:P.targetFile,name:P.calleeLeaf,startLine:P.targetStartLine,endLine:P.targetEndLine},t+1,`member-call:${v.file}`,void 0,P.resolution==="imported-service-object-member"&&j,j);if(X&&P.serviceFile){let ie=on(X),Le=g.get(ie)??new Set;for(let Me of h.get(P.serviceFile)??[])Le.add(Me);g.set(ie,Le)}B&&d(B,t+1,`member-call:${v.file}`,void 0,"none",!0);let G=C.find(ie=>ie.startLine<=P.line&&ie.endLine>=P.line),O=E(P.line),te=I.find(ie=>{let Le=Lc(n,ie);return Le.startLine<=P.line&&Le.endLine>=P.line});St(m,{kind:"call",evidence:P.resolution==="constructed-member-receiver"?"ast-constructed-member-callsite":P.resolution==="factory-callback-member"?"ast-factory-callback-callsite":P.resolution==="imported-service-object-member"?"ast-service-member-callsite":"ast-member-import-candidate",fromFile:v.file,fromSymbol:O?.definition.symbol??null,toFile:P.targetFile,toSymbol:B?.symbol??null,fromBoundaryParticipant:te?$i(te):void 0,fromSourceConstruct:G?ut(G):void 0,toSourceConstruct:X?ut(X):void 0,line:P.line,strength:P.resolution==="imported-service-object-member"?(P.resolutionAlternativeCount??0)===1?"derived":"candidate":P.strength??"candidate"})}for(let P of i.has("import")||i.has("call")?jB(n,v.file):[]){if(!P.fromFile){if(i.has("import")){let B=b.get(P.shortName)??{name:P.shortName,fromFiles:new Set};B.fromFiles.add(v.file),b.set(P.shortName,B)}continue}if(!u(P.fromFile))continue;if(i.has("import")&&(S(P.fromFile,t+1,`import:${v.file}`,!1),St(m,{kind:"import",evidence:"indexed-or-source-import",fromFile:v.file,fromSymbol:null,toFile:P.fromFile,toSymbol:P.symbol,line:null,strength:"mixed"})),i.has("call")&&D.length>0){let B=(P.source==="compiler"?lr(n,r,P.symbol).matches:jn(n,P.fromFile,P.importedName)).filter(X=>!pe(X.symbol));for(let X of B){let G=D.filter(O=>O.calleeLeaf===P.localName).map(O=>O.line);if(G.length!==0){d(X,t+1,`source-call:${v.file}`,void 0,"none",!0);for(let O of G)St(m,{kind:"call",evidence:"ast-callsite",fromFile:v.file,fromSymbol:null,toFile:X.relativePath,toSymbol:X.symbol,line:O,strength:"derived"})}}}if(!v.promoteBoundaryImports||!qB(v.file,P.fromFile,y))continue;let j=lr(n,r,P.symbol);for(let B of j.matches)if(GB(B.relativePath,P.fromFile,y)&&!pe(B.symbol)){let X=yt(v.file,y).relativeDir!==yt(B.relativePath,y).relativeDir;d(B,t+1,`boundary-import:${v.file}`,void 0,X?"cross-workspace-or-forward":"forward-regions")}}}}function nB(e,t){let{relationPolicy:n,runtimeBoundaries:r,evidenceFloor:i,representedBoundaryLinkIds:o,boundaryObservations:s,sourceAllowed:a,boundaryObservationDepths:c,symbols:l,sourceConstructs:u,addBoundaryObservation:d,pendingRelations:m}=e;for(let p of n.has("runtime-boundary")?r?.links??[]:[]){if(p.strength==="candidate"||i==="exact"&&p.strength!=="exact"||o.has(p.id))continue;let f=s.get(p.from),g=s.get(p.to);if(!f||!g||!a(f.source.file)||!a(g.source.file))continue;let h=NC(f,t,c,l,u),b=NC(g,t,c,l,u);if(h===null&&b===null)continue;let S=t+1,y=d(f,h??S,`runtime-boundary:${p.joinRule}`),x=d(g,b??S,`runtime-boundary:${p.joinRule}`),v=y?null:kC(u,f),C=x?null:kC(u,g);c.set(f.id,h??S),c.set(g.id,b??S),St(m,{kind:"runtime-boundary",evidence:`runtime-boundary:${p.joinRule}`,fromFile:f.source.file,fromSymbol:y,toFile:g.source.file,toSymbol:x,fromBoundaryParticipant:$i(f),toBoundaryParticipant:$i(g),fromSourceConstruct:v?ut(v):void 0,toSourceConstruct:C?ut(C):void 0,runtimeBoundaryKey:p.matchedKeyParts.map(R=>`${R.name}=${R.value}`).join(" "),line:f.source.startLine,strength:p.strength}),o.add(p.id)}}function BC(e,t,n){let r=ke(t.searches??[]),i=ke(t.symbols??[]),o=ke(t.relations&&t.relations.length>0?t.relations:wC),s=o.filter($=>!wC.includes($));if(s.length>0)throw new Error(`Unsupported system-map relation kind(s): ${s.join(", ")}`);let a=new Set(o),c=t.evidenceFloor??"derived";if(c!=="exact"&&c!=="derived")throw new Error(`Unsupported system-map evidence floor: ${c}`);let l=ke(t.sourceScopes&&t.sourceScopes.length>0?t.sourceScopes:["production"]),u=["production","test","fixture","example","generated","script","unknown"],d=l.filter($=>!u.includes($));if(d.length>0)throw new Error(`Unsupported system-map source scope(s): ${d.join(", ")}`);let m=new Set(l),p=$=>m.has(Al($));if(r.length===0&&i.length===0)throw new Error("system-map requires at least one --search or --symbol anchor.");let f=t.maxDepth??_O;if(!Number.isSafeInteger(f)||f<0)throw new RangeError(`maxDepth must be a non-negative safe integer; received ${f}`);let g=t.maxTopologyCharacters??zO;if(!Number.isSafeInteger(g)||g<=0)throw new RangeError(`maxTopologyCharacters must be a positive safe integer; received ${g}`);let h=new H(e),{fileGraph:b,reverseFileGraph:S,workspaces:y,runtimeBoundaries:x}=WB(e,h),v=new Map((x?.observations??[]).map($=>[$.id,$])),C=new Set((x?.observations??[]).map($=>`${$.source.file}\0${$.source.startLine}`)),R=new Set,E=new Map,I=new Map,w=new Map,A=new Map,D=[],k=new Map,L=new Map,F=[],P={filteredUnverifiedCallEdges:0,memberCallCandidateEdges:0,unresolvedMemberCallsites:0},j=new Set,B=new Map,X=new Map,G=$=>{let Y=X.get($);if(Y)return Y;let oe=rr(e,$,{excludeIndexedTargets:!1});return X.set($,oe),oe},O=($,Y,oe,Ne,qt=!1)=>WO(I,$,Y,oe,Ne,qt),te=($,Y,oe,Ne,qt="none",Zr=!1)=>VO(w,O,$,Y,oe,Ne,qt,Zr),ie=($,Y,oe,Ne,qt=!1,Zr=!0)=>YO(A,O,$,Y,oe,Ne,qt,Zr),Le=($,Y,oe)=>JO({db:e,index:h,pendingRelations:k,addFile:O,addSymbol:te,addSourceConstruct:ie,observation:$,depth:Y,origin:oe}),{omittedSymbolCandidates:Me,broadLiteralAnchors:Nt,withheldLiteralMatches:tt}=XO({db:e,index:h,searches:r,symbolQueries:i,opts:t,boundaryObservationLocations:C,sourceAllowed:p,addFile:O,addSymbol:te,addSourceConstruct:ie,literalHits:D,anchors:F}),M={db:e,index:h,relationPolicy:a,evidenceFloor:c,sourceAllowed:p,fileGraph:b,reverseFileGraph:S,workspaces:y,runtimeBoundaries:x,boundaryObservations:v,boundaryObservationDepths:E,representedBoundaryLinkIds:R,files:I,symbols:w,sourceConstructs:A,pendingRelations:k,externalImports:L,reverseExpandedSourceConstructs:j,serviceCallerFilesBySourceConstruct:B,traversalMetrics:P,memberCallTargetsForWholeFile:G,addFile:O,addSymbol:te,addSourceConstruct:ie,addBoundaryObservation:Le};for(let $=0;$<f;$+=1)ZO(M,$),eB(M,$),tB(M,$),nB(M,$);return QO({db:e,opts:t,mode:n,searches:r,symbolQueries:i,maxDepth:f,maxTopologyCharacters:g,requestedRelationKinds:o,evidenceFloor:c,includedSourceScopes:l,workspaces:y,runtimeBoundaries:x,boundaryObservations:v,representedBoundaryLinkIds:R,files:I,symbols:w,sourceConstructs:A,literalHits:D,pendingRelations:k,externalImports:L,anchors:F,omittedSymbolCandidates:Me,broadLiteralAnchors:Nt,withheldLiteralMatches:tt,filteredUnverifiedCallEdges:P.filteredUnverifiedCallEdges,memberCallCandidateEdges:P.memberCallCandidateEdges,unresolvedMemberCallsites:P.unresolvedMemberCallsites,sourceAllowed:p})}function rB(e,t,n,r){let i=new Map,o=c=>{i.set(`${c.file}\0${c.line}`,c)};for(let c of r)o(c);let s=new Set(t.anchors.filter(c=>c.status==="matched").flatMap(c=>c.nodeIds));for(let c of n.steps)if(!(!c.location||!s.has(c.nodeId)||(c.behavior?.rawCharacters??1/0)>3e3))for(let l of c.behavior?.lines??[])l.signals.some(u=>GO.has(u))&&o({file:c.location.file,line:l.line,endLine:l.endLine});let a=t.edges.filter(c=>c.disposition==="emitted").flatMap(c=>c.evidence.flatMap(l=>l.location?[l.location]:[]));for(let c of a){o(c);let l=t.nodes.filter(d=>d.location?.file===c.file&&["symbol","source-construct","runtime-boundary-participant"].includes(d.kind)&&d.location.line<=c.line&&(d.location.endLine??d.location.line)>=c.line).sort((d,m)=>(d.location.endLine??d.location.line)-d.location.line-((m.location.endLine??m.location.line)-m.location.line)||d.id.localeCompare(m.id))[0];if(!l?.location)continue;let u=pa(e,c.file,l.location.line,l.location.endLine??l.location.line,[c.line]);for(let d of u)o({file:c.file,line:d.line,endLine:d.endLine})}return[...i.values()].sort((c,l)=>c.file.localeCompare(l.file)||c.line-l.line)}function iB(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 on(e){return`${e.file}\0${e.startLine}\0${e.endLine}\0${e.name}`}function ut(e){return{file:e.file,name:e.name,startLine:e.startLine,endLine:e.endLine}}function PC(e,t,n,r){if(n.calleeLeaf===r.leaf)return!0;let i=ai(e,t,n.calleeLeaf);return i!==null&&i.importedName===r.leaf&&i.sourcePath!==null&&_e(i.sourcePath,r.relativePath)}function Pc(e,t){let n=On(K(e,t.file)?.callables??[],t.startLine);if(n&&n.endLine>=t.endLine)return{file:t.file,name:/^source@\d+$/u.test(n.name)&&!/^source@\d+$/u.test(t.name)?t.name:n.name,startLine:n.startLine,endLine:n.endLine};let r=jC(e,t.file,t.startLine);return r&&r.endLine>=t.endLine?{file:t.file,name:r.name,startLine:r.startLine,endLine:r.endLine}:ut(t)}function Bi(e){return bt("source-construct",e.file,String(e.startLine),String(e.endLine),e.name)}function Dc(e,t){let n=Di(e,t.symbol,t.relativePath),r=new Set(["package-surface-file","transitive-package-surface"]),i=n.filter(s=>!r.has(s)||ft(e,t)),o=i.some(s=>!r.has(s));return{evidence:i,priority:o||Wb(e,t.symbol,t.relativePath)?2:1}}function DC(e,t){let n=Dc(e,t);return n.evidence.length>0?n.priority:0}function oB(e,t){let n=U(e,t.file),r=n.filter(i=>i.startLine<=t.startLine&&i.endLine>=t.startLine).sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine)||i.startLine-o.startLine);for(let i of r){let o=Dc(e,i);if(o.evidence.length>0)return o}for(let i of sB(e,t.file,t.startLine)){let o=n.filter(s=>s.leaf===i.name).sort((s,a)=>Math.abs(s.startLine-i.startLine)-Math.abs(a.startLine-i.startLine)||s.symbol.localeCompare(a.symbol));for(let s of o){let a=Dc(e,s);if(a.evidence.length>0)return a}return{evidence:[],priority:0}}return{evidence:[],priority:0}}function sB(e,t,n){let r=J(e,t)?.rootNode;if(!r||r.startPosition.row>n||r.endPosition.row<n)return[];let i=[],o=im(r,n);for(;o;){if(o.type==="variable_declarator"||o.type==="function_declaration"||o.type==="generator_function_declaration"||o.type==="class_declaration"){let s=o.childForFieldName("name")??o.namedChild(0);(s?.type==="identifier"||s?.type==="type_identifier")&&i.push({name:s.text,startLine:o.startPosition.row})}o=o.parent}return i}function aB(e){return[...new Map([...e.sourceConstructStates.values()].map(t=>Pc(e.db,t)).map(t=>[on(t),t])).values()].sort((t,n)=>t.file.localeCompare(n.file)||t.startLine-n.startLine||t.endLine-n.endLine)}function cB(e,t){return e.anchors.map((n,r)=>{let i=bt("anchor",String(r),n.kind,n.query),o=[...e.symbolStates.values()].filter(u=>u.anchorQueries.has(n.query)).flatMap(u=>{if(!pe(u.definition.symbol))return[cr(u.definition.symbol)];let d=t.filter(m=>m.file===u.definition.relativePath).map(m=>Bi(m));return d.length>0?d:[cr(u.definition.symbol)]}),s=[...e.sourceConstructStates.values()].filter(u=>u.anchorQueries.has(n.query)).map(u=>Bi(Pc(e.db,u))),a=e.literalHits.filter(u=>u.query===n.query&&u.traversalSeed===!0&&u.ownerSymbol&&e.symbolStates.has(u.ownerSymbol)).map(u=>cr(u.ownerSymbol)),c=e.literalHits.filter(u=>u.query===n.query&&u.traversalSeed===!0&&!u.ownerSymbol&&u.ownerStartLine!==null&&u.ownerStartLine!==void 0&&u.ownerEndLine!==null&&u.ownerEndLine!==void 0).map(u=>Bi(Pc(e.db,iB(u)))),l=fe(n.kind==="symbol"?[...o,...s]:a.length+c.length>0?[...a,...c]:n.seedRegionIds??[]);return{id:i,kind:n.kind,query:n.query,status:n.status,nodeIds:n.status==="ambiguous"?[]:l,candidateNodeIds:n.status==="ambiguous"?l:[],omittedCandidates:n.omittedSymbolCandidates??0}})}function lB(e){let t=new Map;for(let n of e)for(let r of[...n.nodeIds,...n.candidateNodeIds]){let i=t.get(r)??[];i.push(n.id),t.set(r,i)}return t}function uB(e,t,n){let r=e.relations.flatMap(s=>[s.fromBoundaryParticipant,s.toBoundaryParticipant].flatMap(a=>a?.ownerName?[a]:[])),i=e.regions.map(s=>({id:s.id,kind:"structural-region",label:s.label,disposition:"folded",location:null,anchorIds:fe(n.get(s.id)??[]),attributes:{workspace:s.workspace,structuralPath:s.structuralPath,minimumDepth:s.minDepth,files:s.fileCount,symbols:s.symbolCount,expanded:s.expanded}}));for(let s of e.symbolStates.values()){let a=e.regionForFile.get(s.definition.relativePath)?.id;if(!a)throw new Error(`System-map symbol ${s.definition.symbol} has no structural region.`);let c=cr(s.definition.symbol),l=Dc(e.db,s.definition);i.push({id:c,kind:"symbol",label:T(s.definition.symbol),disposition:(n.get(c)?.length??0)>0?"emitted":"folded",location:{file:s.definition.relativePath,line:s.definition.startLine,endLine:s.definition.endLine},anchorIds:fe(n.get(c)??[]),attributes:{regionId:a,depth:s.depth,leaf:s.definition.leaf??T(s.definition.symbol),referenceScope:s.referenceScope,...l.evidence.length>0?{publicEntry:!0,publicEntryPriority:l.priority,publicEntryEvidence:l.evidence.join(",")}:{}}})}for(let s of t){let a=e.regionForFile.get(s.file)?.id;if(!a)throw new Error(`Source construct ${s.name} has no structural region.`);let c=Bi(s),u=r.find(m=>m.file===s.file&&m.line>=s.startLine&&m.line<=s.endLine)?.ownerName??s.name,d=oB(e.db,s);i.push({id:c,kind:"source-construct",label:u,disposition:(n.get(c)?.length??0)>0?"emitted":"folded",location:{file:s.file,line:s.startLine,endLine:s.endLine},anchorIds:fe(n.get(c)??[]),attributes:{regionId:a,leaf:u,sourceOwned:!0,...d.evidence.length>0?{publicEntry:!0,publicEntryPriority:d.priority,publicEntryEvidence:d.evidence.join(",")}:{}}})}let o=new Map;for(let s of e.relations)s.fromBoundaryParticipant&&o.set(s.fromBoundaryParticipant.observationId,s.fromBoundaryParticipant),s.toBoundaryParticipant&&o.set(s.toBoundaryParticipant.observationId,s.toBoundaryParticipant);for(let s of[...o.values()].sort((a,c)=>a.observationId.localeCompare(c.observationId))){let a=e.regionForFile.get(s.file)?.id;if(!a)throw new Error(`Runtime-boundary participant ${s.observationId} has no structural region.`);i.push({id:om(s.observationId),kind:"runtime-boundary-participant",label:s.address||s.ownerName||`${s.role} ${s.action}`,disposition:"folded",location:{file:s.file,line:s.line,endLine:s.endLine},anchorIds:[],attributes:{regionId:a,action:s.action,protocol:s.protocol,role:s.role,...s.address?{address:s.address}:{},ownerSymbol:s.ownerSymbol}})}return i}function dB(e,t,n,r,i,o,s,a,c,l=!1){let u=r?cr(r):null;if(u&&t.has(u)&&!pe(r))return u;let d=i?om(i.observationId):null;if(l&&d&&t.has(d))return d;let m=o?Bi(Pc(e,o)):null;if(m&&t.has(m))return m;if(d&&t.has(d))return d;let p=c===null?null:(n.get(a)??[]).filter(f=>f.startLine<=c&&f.endLine>=c).sort((f,g)=>f.endLine-f.startLine-(g.endLine-g.startLine)||f.startLine-g.startLine)[0]??null;return p?Bi(p):u&&t.has(u)?u:s}function mB(e,t,n){let r=new Set(t.map(l=>l.id)),i=Be(n,l=>l.file),o=(l,u,d,m,p,f,g=!1)=>dB(e.db,r,i,l,u,d,m,p,f,g),s=[];for(let l of e.symbolStates.values()){let u=e.regionForFile.get(l.definition.relativePath)?.id;if(!u)continue;let d=cr(l.definition.symbol);s.push({id:bt("edge","structural-membership",u,d),kind:"structural-membership",fromNodeId:u,toNodeId:d,directed:!0,disposition:"folded",semantics:gc("structural-membership"),evidence:[{method:"indexed-definition-file",strength:"exact",identity:l.definition.symbol,location:{file:l.definition.relativePath,line:l.definition.startLine,endLine:l.definition.endLine}}]})}let a=Be(e.relations,l=>`${o(l.fromSymbol,l.fromBoundaryParticipant,l.fromSourceConstruct,l.fromRegionId,l.fromFile,l.line,l.kind==="runtime-boundary")}\0${o(l.toSymbol,l.toBoundaryParticipant,l.toSourceConstruct,l.toRegionId,l.toFile,null)}\0${l.kind}`),c=new Set;for(let l of a.values()){let u=l[0],d=o(u.fromSymbol,u.fromBoundaryParticipant,u.fromSourceConstruct,u.fromRegionId,u.fromFile,u.line,u.kind==="runtime-boundary"),m=o(u.toSymbol,u.toBoundaryParticipant,u.toSourceConstruct,u.toRegionId,u.toFile,null);if(u.kind==="runtime-boundary"&&u.fromBoundaryParticipant){let f=om(u.fromBoundaryParticipant.observationId),g=o(u.fromSymbol,void 0,u.fromSourceConstruct,u.fromRegionId,u.fromFile,u.line);g!==f&&!c.has(f)&&(c.add(f),s.push({id:bt("edge","boundary-observation",g,f),kind:"boundary-observation",fromNodeId:g,toNodeId:f,directed:!0,disposition:"folded",semantics:gc("boundary-observation"),evidence:[{method:"runtime-boundary-observation-owner",strength:u.strength??"unknown",identity:u.fromBoundaryParticipant.observationId,location:{file:u.fromBoundaryParticipant.file,line:u.fromBoundaryParticipant.line,endLine:u.fromBoundaryParticipant.endLine}}]}))}(d===m?t.find(f=>f.id===d):null)?.kind!=="structural-region"&&s.push({id:bt("edge",u.kind,d,m),kind:u.kind,fromNodeId:d,toNodeId:m,directed:!0,disposition:"folded",semantics:Nv(u),evidence:CB(l.map(f=>({method:f.evidence,strength:f.strength??"unknown",identity:f.kind==="runtime-boundary"&&f.runtimeBoundaryKey?f.runtimeBoundaryKey:`${f.fromSymbol??f.fromFile} -> ${f.toSymbol??f.toFile}`,location:f.line===null?null:{file:f.fromFile,line:f.line}})))})}return s}function pB(e,t,n){for(let i of e.externalBoundaries){let o=bt("external",i.kind,i.name),s=fe(i.fromRegionIds);t.push({id:o,kind:i.kind,label:i.name,disposition:"folded",location:null,anchorIds:[],attributes:{}});for(let a of s)n.push({id:bt("edge",i.kind,a,o),kind:i.kind,fromNodeId:a,toNodeId:o,directed:!0,disposition:"folded",semantics:gc("external-import"),evidence:[{method:"indexed-or-source-import",strength:"mixed",identity:`${a} -> ${i.name}`,location:null}]})}let r=[];return e.boundaryFrontiers.forEach((i,o)=>{let s=e.regionForFile.get(i.file)?.id;if(!s)throw new Error(`Runtime-boundary frontier ${i.observationId} has no system-map region.`);let a=bt("unsupported","runtime-boundary",i.observationId,String(o)),c=bt("edge","runtime-boundary-frontier",s,a);t.push({id:a,kind:"runtime-boundary-frontier",label:i.address,disposition:"unsupported",location:{file:i.file,line:i.line},anchorIds:[],attributes:{action:i.action,strength:i.strength,owner:i.ownerShortName}}),n.push({id:c,kind:"runtime-boundary-frontier",fromNodeId:s,toNodeId:a,directed:!0,disposition:"unsupported",evidence:[{method:"runtime-boundary-extractor",strength:i.strength,identity:i.observationId,location:{file:i.file,line:i.line}}]}),r.push({id:bt("frontier","runtime-boundary",i.observationId,String(o)),kind:"runtime-boundary",direction:"unresolved",fromNodeIds:[s],edgeIds:[c],memberNodeIds:[a],memberCount:1,disposition:"unsupported",reason:i.reason,expansion:null})}),r}function fB(e,t){let n=t.topologyFrontiers.some(f=>f==="frontier:program-facts"),r=RC(e,{expandedFrontierIds:t.topologyFrontiers.filter(f=>f!=="frontier:program-facts"),routeIds:t.routeIds}),i=r.nodes.filter(f=>f.disposition==="emitted"||r.anchors.some(g=>g.status==="matched"&&g.nodeIds.includes(f.id))),o=t.relations.filter(f=>i.some(g=>hB(f,g))),s=t.boundaryFrontiers.filter(f=>i.some(g=>yB(f,g))),a=zv(t.db,o,i),c=Wv(t.db,i),l=oC(t.db,i,s),u=[...a.nodes,...c.nodes,...l.nodes].map(f=>n&&f.disposition==="folded"?{...f,disposition:"emitted"}:f),d=[...a.edges,...c.edges,...l.edges].map(f=>n&&f.disposition==="folded"?{...f,disposition:"emitted"}:f),m=n?null:bB(i,u,d),p=wc({anchors:r.anchors,nodes:[...r.nodes,...u],edges:[...r.edges,...d],paths:r.paths,frontiers:[...r.frontiers,...a.frontiers,...c.frontiers,...l.frontiers,...m?[m]:[]],scope:r.coverage.scope,blindSpots:[...r.coverage.blindSpots,...a.blindSpots,...c.blindSpots,...l.blindSpots],incompleteReasons:r.coverage.status==="incomplete"?[r.coverage.explanation]:[],...r.routeCatalog?{routeCatalog:r.routeCatalog}:{}});p.completion=r.completion;for(let f of p.frontiers)f.disposition==="folded"&&(f.id.startsWith("frontier:program-facts:")||(f.expansion=SB(t,f.id)));return p}function gB(e){let t=aB(e),n=cB(e,t),r=uB(e,t,lB(n)),i=mB(e,r,t),o=pB(e,r,i);return fB(wc({anchors:n,nodes:r,edges:i,paths:[],frontiers:o,scope:`explicit anchors; relations ${e.requestedRelationKinds.join(", ")}; depth ${e.maxDepth}; evidence floor ${e.evidenceFloor}; source scopes ${e.includedSourceScopes.join(", ")}`,blindSpots:[...e.blindSpots],incompleteReasons:e.closureStatus==="incomplete"?[`${e.omittedSymbolCandidates} ambiguous symbol candidate(s) were omitted`]:[]}),e)}function hB(e,t){if(e.fromSymbol&&t.id===cr(e.fromSymbol)||e.toSymbol&&t.id===cr(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 yB(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 bB(e,t,n){let r=fe(t.filter(o=>o.disposition==="folded").map(o=>o.id)),i=fe(n.filter(o=>o.disposition==="folded").map(o=>o.id));return r.length===0&&i.length===0?null:{id:bt("frontier","program-facts"),kind:"program-facts",direction:"outgoing",fromNodeIds:fe(e.map(o=>o.id)),edgeIds:i,memberNodeIds:r,memberCount:r.length,disposition:"folded",reason:"Control, data, state, and temporal facts are folded beneath the selected high-level owners.",expansion:null}}function SB(e,t){return`scip-query system-map ${[...e.anchors.flatMap(r=>r.kind==="literal"?[`--search ${ye(r.query)}`]:[`--symbol ${ye(r.query)}`]),`--depth ${e.maxDepth}`,...e.requestedRelationKinds.map(r=>`--relation ${ye(r)}`),`--evidence-floor ${ye(e.evidenceFloor)}`,...e.includedSourceScopes.map(r=>`--source-scope ${ye(r)}`),...e.fullLiteralTraversal?["--full-literal-traversal"]:[],`--topology-characters ${e.maxTopologyCharacters}`,...e.expandedRegionIds.map(r=>`--expand ${ye(r)}`),...e.topologyFrontiers.map(r=>`--frontier ${ye(r)}`),...e.routeIds.map(r=>`--route ${ye(r)}`),`--frontier ${ye(t)}`].join(" ")}`}function vB(e){let t=new Set;for(let n of e.nodes){if(n.disposition!=="emitted")continue;n.kind==="structural-region"&&t.add(n.id);let r=n.attributes.regionId;typeof r=="string"&&t.add(r)}return t}function CB(e){let t=new Map;for(let n of e){let r=n.location?`${n.location.file}:${n.location.line}`:"";t.set(`${n.method}\0${n.strength}\0${n.identity??""}\0${r}`,n)}return[...t.values()].sort((n,r)=>n.method.localeCompare(r.method)||(n.identity??"").localeCompare(r.identity??"")||(n.location?.file??"").localeCompare(r.location?.file??"")||(n.location?.line??0)-(r.location?.line??0))}function bt(...e){return e.map(t=>encodeURIComponent(t)).join(":")}function cr(e){return bt("symbol",e)}function xB(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function RB(e,t,n,r,i,o,s,a,c,l){let u=[...r].sort((g,h)=>$C(g,h,i)),m=u.slice(0,IC).map(g=>g.id),p=u.slice(IC).map(g=>g.id),f=[...e.map(g=>`--search ${ye(g)}`),...t.map(g=>`--symbol ${ye(g)}`),`--depth ${n}`,...o.map(g=>`--relation ${ye(g)}`),`--evidence-floor ${ye(s)}`,...a.map(g=>`--source-scope ${ye(g)}`),...c?["--full-literal-traversal"]:[],`--topology-characters ${l}`,...m.map(g=>`--expand ${ye(g)}`)];return{command:m.length===0?null:`scip-query system-map ${f.join(" ")}`,regionCount:m.length,regionIds:m,candidateRegionCount:r.length,omittedRegionIds:p}}function EB(e,t,n,r,i,o,s,a,c,l,u,d,m){let p=[...c].sort((w,A)=>$C(w,A,u)).filter(w=>!m||m.has(w.id)||d.has(w.id)),f=l.length>0?Math.floor(a*.4):0,g=a-f,h=new Set,b=0;for(let w of p){let A=MC(w);!d.has(w.id)&&h.size>0&&b+A>g||(h.add(w.id),b+=A)}let S=l.filter(w=>h.has(w.fromRegionId)&&h.has(w.toRegionId)).sort(IB),y=[];for(let w of S){let A=TC(w);y.length>0&&b+A>a||(y.push(Mc(w)),b+=A)}let x=c.filter(w=>!h.has(w.id)).map(w=>w.id).sort(),v=new Set(y),C=l.filter(w=>!v.has(Mc(w))).length,R=c.reduce((w,A)=>w+MC(A),0)+l.reduce((w,A)=>w+TC(A),0),E=p.every(w=>h.has(w.id))&&y.length===S.length,I=[...e.map(w=>`--search ${ye(w)}`),...t.map(w=>`--symbol ${ye(w)}`),`--depth ${n}`,...r.map(w=>`--relation ${ye(w)}`),`--evidence-floor ${ye(i)}`,...o.map(w=>`--source-scope ${ye(w)}`),...s?["--full-literal-traversal"]:[],`--topology-characters ${Math.max(a,R)}`];return{maxCharacters:a,estimatedCharacters:b,totalEstimatedCharacters:R,regionIds:[...h],omittedRegionIds:x,relationKeys:y,omittedRelations:C,complete:E,expansionCommand:E?null:`scip-query system-map ${I.join(" ")}`}}function MC(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 TC(e){return 70+e.fromRegionId.length+e.toRegionId.length+e.kinds.join(",").length+e.evidence.join(",").length}function IB(e,t){let n=r=>r.kinds.includes("runtime-boundary")?0:r.kinds.includes("contract-symbol")?1:2;return n(e)-n(t)||t.relationCount-e.relationCount||Mc(e).localeCompare(Mc(t))}function Mc(e){return`${e.fromRegionId}\0${e.toRegionId}`}function $C(e,t,n){let r=a=>n.has(a.id)?0:1,i=a=>a.sourceFileCount===0?1:0,o=a=>a.symbolCount+a.literalHitCount>0?0:1,s=a=>[...a.incomingRegionIds,...a.outgoingRegionIds].filter(c=>n.has(c)).length;return r(e)-r(t)||o(e)-o(t)||i(e)-i(t)||e.minDepth-t.minDepth||s(t)-s(e)||t.literalHitCount-e.literalHitCount||e.testFileCount-t.testFileCount||e.label.localeCompare(t.label)}function wB(e){let t=[],n=new Set;for(let i of e.filter(o=>o.expanded)){for(let c of i.symbols)c.origins.includes("symbol-anchor")&&n.add(c.file);let o=Be(i.symbols,c=>c.file),s=Be(i.literalHits,c=>c.file),a=[...i.files].sort((c,l)=>PB(c,l,o,s));for(let c of a){let l=(o.get(c.file)??[]).sort(Fv)[0];if(l){t.push({kind:"symbol",regionId:i.id,file:l.file,line:l.startLine,endLine:l.endLine,label:l.shortName});continue}let u=(s.get(c.file)??[]).sort(qC)[0];u&&t.push({kind:"literal",regionId:i.id,file:u.file,line:u.line,endLine:null,label:u.ownerShortName??u.query})}}let r=LB(t,n);return{command:r.length===0?null:`scip-query inspect ${r.map(i=>`--at ${ye(`${i.file}:${i.line+1}`)}`).join(" ")} --view behavior`,definitionCommand:null,candidateAnchors:t.length,selectedAnchors:r.length,omittedAnchors:t.length-r.length,anchors:r}}function LB(e,t){let n=[...Be(e,s=>s.regionId).values()],r=[],i=new Set,o=Math.min(UO,24);for(let s of e)if(!(!t.has(s.file)||i.has(s.file))&&(r.push(s),i.add(s.file),r.length===o))return r;for(let s=0;r.length<o;s+=1){let a=!1;for(let c of n){let l=c[s];if(l&&(a=!0,!i.has(l.file)&&(r.push(l),i.add(l.file),r.length===o)))break}if(!a)break}return r}function PB(e,t,n,r){let i=a=>a.kind==="test"?2:a.kind==="barrel"?1:0,o=a=>(r.get(a.file)??[]).some(c=>c.traversalSeed)?0:1,s=a=>{let c=n.get(a.file)??[];return Math.min(5,...c.map(l=>Ni(l.origins)))};return i(e)-i(t)||o(e)-o(t)||s(e)-s(t)||e.depth-t.depth||e.file.localeCompare(t.file)}function ye(e){return`'${e.replaceAll("'","'\\''")}'`}function DB(e,t,n,r){let i=[];for(let o of Q(e,{includeIgnored:!1})){let s=V(e,o);if(s.length===0)continue;let a=[];for(let u=0;u<s.length;u+=1){let d=s[u]??"";d.includes(n)&&a.push({line:u,sourceLine:d})}if(a.length===0)continue;let c=t.definitionsForFile(o),l=K(e,o)?.callables??[];for(let{line:u,sourceLine:d}of a){let m=Oe(c,u),p=On(l,u),f=m&&!pe(m.symbol)?m:null,g=f?.startLine??p?.startLine??m?.startLine??u,h=f?.endLine??p?.endLine??m?.endLine??u,b=ho(e,o,u,g,h),S=r.has(`${o}\0${u}`),y=!!(f?.isFunctionLike||p);i.push({relativePath:o,line:u,sourceLine:d,ownerSymbol:f?.symbol??null,ownerShortName:f?T(f.symbol):p?.name??(m?T(m.symbol):null),ownerStartLine:b.startLine,ownerEndLine:b.endLine,matchKind:FB(d,n),seedPriority:S?0:y?1:2})}}return i}function MB(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 AC(e){return`${e.relativePath}\0${e.line}`}function tm(e,t,n){let i=On(K(e,t)?.callables??[],n)??jC(e,t,n);if(!i)return null;let o=ho(e,t,n,i.startLine,i.endLine);return{file:t,name:i.name,startLine:o.startLine,endLine:o.endLine}}function jC(e,t,n){let r=J(e,t)?.rootNode;if(!r||r.startPosition.row>n||r.endPosition.row<n)return null;let i=im(r,n);for(;i;){if(i.type==="variable_declarator"){let s=i.childForFieldName("name")??i.namedChild(0),a=i.childForFieldName("value")??i.namedChild(1);if(s?.type==="identifier"&&a&&nm(a,n))return{name:s.text,startLine:i.startPosition.row,endLine:i.endPosition.row}}if(i.type==="pair"){let s=i.childForFieldName("key")??i.namedChild(0),a=i.childForFieldName("value")??i.namedChild(1),c=s?.text.replace(/^(?:['"])(.*)(?:['"])$/u,"$1");if(c&&a&&/^[A-Za-z_$][\w$]*$/u.test(c)&&nm(a,n))return{name:c,startLine:i.startPosition.row,endLine:i.endPosition.row}}i=i.parent}let o=bi(e,t,n);return o?{name:`source@${n+1}`,startLine:o.startLine,endLine:o.endLine}:null}function nm(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&&nm(n,t))}function im(e,t){let n=e.namedChildren.filter(r=>r.startPosition.row<=t&&r.endPosition.row>=t).sort((r,i)=>r.endIndex-r.startIndex-(i.endIndex-i.startIndex)||r.startPosition.row-i.startPosition.row)[0];return n?im(n,t):e}function TB(e,t){let n=t.match(/^(.+):(\d+)(?:-(\d+))?$/u);if(!n)return null;let r=ri(e,n[1],{allowMultiple:!1})[0]?.relativePath;if(!r)return null;let i=Math.max(0,Number.parseInt(n[2],10)-1),o=n[3]?Math.max(i,Number.parseInt(n[3],10)-1):i,s=(K(e,r)?.callables??[]).filter(a=>a.startLine<=i&&a.endLine>=o).sort((a,c)=>a.endLine-a.startLine-(c.endLine-c.startLine)||a.startLine-c.startLine)[0];return s?{file:r,name:s.name,startLine:s.startLine,endLine:s.endLine}:null}function AB(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 FB(e,t){let n=/[\p{L}\p{N}_$]/u,r=e.indexOf(t);for(;r>=0;){let i=e[r-1]??"",o=e[r+t.length]??"";if((i==="'"||i==='"'||i==="`")&&o===i)return"exact-value";if(!n.test(i)&&!n.test(o))return"boundary";r=e.indexOf(t,r+Math.max(1,t.length))}return"embedded"}function rm(e){return q(e)==="test"?!1:!/(?:^|[/._-])(?:fixtures?|mocks?|previews?|demos?|examples?|stories)(?:[/._-]|$)/iu.test(e)}function kB(e,t){return e.matchKind!=="embedded"&&t(e.relativePath)&&(Al(e.relativePath)!=="production"||rm(e.relativePath))}function NB(e,t){let n=[...t].sort(_B),r=[],i=new Set;for(let o of n)if(!i.has(o.relativePath)&&(r.push(o),i.add(o.relativePath),r.length>=EC))break;for(let o of n){if(r.length>=EC)break;r.includes(o)||r.push(o)}return r.map(o=>({query:e,file:o.relativePath,line:o.line,ownerSymbol:o.ownerSymbol,ownerShortName:o.ownerShortName,ownerStartLine:o.ownerStartLine,ownerEndLine:o.ownerEndLine,sourceLine:o.sourceLine.trim(),matchKind:o.matchKind,traversalSeed:!1}))}function _B(e,t){let n={"exact-value":0,boundary:1,embedded:2};return n[e.matchKind]-n[t.matchKind]||+(t.ownerSymbol!==null)-+(e.ownerSymbol!==null)||+!rm(e.relativePath)-+!rm(t.relativePath)||e.relativePath.localeCompare(t.relativePath)||e.line-t.line}function OB(e,t){let n=new Map;for(let r of t){let i=BB(r.relativePath);n.set(i,(n.get(i)??0)+1)}return[...n].sort(([r,i],[o,s])=>s-i||r.localeCompare(o)).slice(0,jO).map(([r])=>`scip-query search ${ye(e)} --scope ${ye(r)}`)}function BB(e){let t=e.split("/").filter(Boolean);if(t.length<=1)return e;let n=t.slice(0,-1),r=n.lastIndexOf("src");return r>=0?n.slice(0,Math.min(n.length,r+3)).join("/"):n.slice(0,Math.min(n.length,3)).join("/")}function $B(e,t,n){let r=t.callerFileMap([n],{semantic:!1}).get(n.symbolId)??new Set,i=[];for(let o of[...r].sort()){let s=ae(e,o).filter(u=>u.importedName===n.leaf&&u.sourcePath!==null&&_e(u.sourcePath,n.relativePath)),a=new Set;if(s.length>0)for(let u of s)a.add(u.localName??u.importedName);else n.leaf&&a.add(n.leaf);let c=[...new Set([...a].flatMap(u=>hn(e,o,u)))].sort((u,d)=>u-d);if(c.length===0){i.push({file:o,line:null,enclosingSymbol:null});continue}let l=t.definitionsForFile(o);for(let u of c)i.push({file:o,line:u,enclosingSymbol:Oe(l,u)?.symbol??null})}return i}function jB(e,t){let n=e.all(`SELECT DISTINCT gs.symbol, def_d.relative_path AS from_file
78
- FROM mentions m
79
- JOIN chunks c ON m.chunk_id = c.id
80
- JOIN documents imp_d ON c.document_id = imp_d.id
81
- JOIN global_symbols gs ON m.symbol_id = gs.id
82
- LEFT JOIN (
83
- SELECT m2.symbol_id, c2.document_id
84
- FROM mentions m2
85
- JOIN chunks c2 ON m2.chunk_id = c2.id
86
- WHERE m2.role = 1
87
- GROUP BY m2.symbol_id
88
- ) sym_def ON sym_def.symbol_id = gs.id
89
- LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
90
- WHERE imp_d.relative_path = ? AND m.role = 2
91
- ORDER BY def_d.relative_path, gs.symbol`,t);return n.length>0?n.map(r=>({symbol:r.symbol,shortName:T(r.symbol),importedName:FC(T(r.symbol)),localName:FC(T(r.symbol)),fromFile:r.from_file,source:"compiler"})):ae(e,t).map(r=>{let i=HB(r.importedName,r.localName,r.kind),o=r.localName??r.importedName,s=r.importedName==="default"?o:r.importedName;return{symbol:i,shortName:i,importedName:s,localName:o,fromFile:r.sourcePath,source:"parsed-source"}})}function FC(e){return e.slice(e.lastIndexOf(":")+1).replace(/\(\)$/u,"")||e}function HB(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 lr(e,t,n){let r=Qe(e,n);if(!r.match)return{matches:[],total:0,omitted:0};let i=[r.match,...r.candidates.map(s=>Qe(e,s.symbol).match)].filter(s=>s!==null),o=new Map;for(let s of i){let a=t.definitionsForFile(s.relativePath).find(c=>c.symbol===s.symbol);a&&o.set(a.symbol,a)}return{matches:[...o.values()],total:r.total,omitted:Math.max(0,r.total-o.size)}}function UB(e){return{symbol:e.symbol,shortName:T(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine}}function St(e,t){let n=[t.kind,t.fromFile,t.fromSymbol??"",t.toFile,t.toSymbol??"",t.fromBoundaryParticipant?.observationId??"",t.toBoundaryParticipant?.observationId??"",t.fromSourceConstruct?on(t.fromSourceConstruct):"",t.toSourceConstruct?on(t.toSourceConstruct):"",t.runtimeBoundaryKey??"",t.line??""].join("\0");e.set(n,t)}function $i(e){return{observationId:e.id,action:e.action,protocol:e.protocol,role:e.role,address:HC(e),file:e.source.file,line:e.source.startLine,endLine:e.source.endLine,ownerName:e.owner.name,ownerSymbol:e.owner.symbol}}function Lc(e,t){let n=V(e,t.source.file);return ot(e,t.source.file,0,Math.max(0,n.length-1),[t.source.startLine])}function kC(e,t){let n=[...e.values()];for(let r of[t.owner,t.source]){let i=n.filter(o=>o.file===r.file&&o.startLine<=r.startLine&&o.endLine>=r.startLine).sort((o,s)=>o.endLine-o.startLine-(s.endLine-s.startLine)||o.startLine-s.startLine)[0];if(i)return i}return null}function NC(e,t,n,r,i){let o=[],s=n.get(e.id);s!==void 0&&s<=t&&o.push(s);for(let a of r.values()){if(a.depth>t)continue;let c=a.definition;_C(c,e)&&o.push(a.depth)}for(let a of i.values())a.depth>t||_C(a,e)&&o.push(a.depth);return o.length>0?Math.min(...o):null}function _C(e,t){let n=e.relativePath??e.file;return[t.owner,t.source].some(r=>n===r.file&&e.startLine<=r.startLine&&e.endLine>=r.startLine)}function om(e){return bt("runtime-boundary-participant",e)}function qB(e,t,n){let r=yt(e,n),i=yt(t,n);return r.relativeDir!==i.relativeDir?!0:/(?:^|\/)(?:contracts?|schemas?|db\/schema)(?:\/|$)/u.test(t)}function GB(e,t,n){return es(e,n).id===es(t,n).id}function zB(e,t,n,r){if(e.referenceScope==="all")return!0;let i=es(t,r).id;return[...n.values()].some(s=>s.promoteBoundaryImports&&es(s.file,r).id===i)?!0:e.referenceScope!=="cross-workspace-or-forward"?!1:yt(t,r).relativeDir!==yt(e.definition.relativePath,r).relativeDir}function KB(e,t){let n={none:0,"forward-regions":1,"cross-workspace-or-forward":2,all:3};return n[e]>=n[t]?e:t}function WB(e,t){let n=LC.get(e);if(n)return n;let r=t.fileDependencyGraph(),i={fileGraph:r,reverseFileGraph:VB(r),workspaces:YB(t.sourceFiles()),runtimeBoundaries:Ws(e)};return LC.set(e,i),i}function VB(e){let t=new Map;for(let[n,r]of e)for(let i of r){let o=t.get(i)??new Set;o.add(n),t.set(i,o)}return t}function yt(e,t){return t.find(n=>e===n.relativeDir||e.startsWith(`${n.relativeDir}/`))??{name:"root",relativeDir:""}}function YB(e){let t=new Set(["apps","packages","services","crates","libs","tools"]),n=new Map;for(let r of e){let i=r.split("/").filter(Boolean);if(i.length<3||!t.has(i[0]))continue;let o=`${i[0]}/${i[1]}`;n.set(o,{name:i[1],relativeDir:o})}return[...n.values()].sort((r,i)=>i.relativeDir.length-r.relativeDir.length)}function es(e,t){let n=yt(e,t),i=(n.relativeDir?e.slice(n.relativeDir.length+1):e).split("/").filter(Boolean);i[0]==="src"&&i.shift();let o=JB(i);return{id:`region:${n.relativeDir||"root"}:${o}`,label:`${n.name}:${o}`,workspace:n.name,structuralPath:o}}function JB(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 XB(e,t,n,r,i,o,s){let a=Be([...e.values()],p=>o.get(p.file).id),c=Be([...t.values()],p=>o.get(p.definition.relativePath).id),l=Be(n,p=>o.get(p.file).id),u=new Map;for(let p of r)for(let f of new Set([p.fromRegionId,p.toRegionId])){let g=u.get(f)??[];g.push(p),u.set(f,g)}let d=Be(i,p=>p.toRegionId),m=Be(i,p=>p.fromRegionId);return[...a.entries()].map(([p,f])=>{let g=o.get(f[0].file),h=c.get(p)??[],b=l.get(p)??[],S=u.get(p)??[],y=s.has(p),x=h.map(e$).sort(i$).slice(0,HO),v=f.filter(C=>q(C.file)==="test").length;return{id:p,label:g.label,workspace:g.workspace,structuralPath:g.structuralPath,minDepth:Math.min(...f.map(C=>C.depth)),fileCount:f.length,sourceFileCount:f.length-v,testFileCount:v,symbolCount:h.length,literalHitCount:b.length,anchorQueries:fe([...b.map(C=>C.query),...h.flatMap(C=>[...C.anchorQueries])]),relationKinds:fe(S.map(C=>C.kind)),incomingRegionIds:fe((d.get(p)??[]).map(C=>C.fromRegionId)),outgoingRegionIds:fe((m.get(p)??[]).map(C=>C.toRegionId)),memberCallCandidateRelationCount:S.filter(C=>C.evidence==="ast-member-import-candidate").length,notableSymbols:x,omittedNotableSymbols:Math.max(0,h.length-x.length),expanded:y,files:y?f.map(QB).sort(o$):[],symbols:y?h.map(ZB).sort(s$):[],literalHits:y?[...b].sort(qC):[],relations:y?[...S].sort(UC):[]}}).sort((p,f)=>p.minDepth-f.minDepth||p.label.localeCompare(f.label))}function QB(e){return{file:e.file,kind:q(e.file),depth:e.depth,origins:fe([...e.origins])}}function ZB(e){return{symbol:e.definition.symbol,shortName:T(e.definition.symbol),file:e.definition.relativePath,startLine:e.definition.startLine,endLine:e.definition.endLine,depth:e.depth,origins:fe([...e.origins]),anchorQueries:fe([...e.anchorQueries]),referenceExpansion:e.referenceScope!=="none",referenceScope:e.referenceScope}}function e$(e){return{shortName:T(e.definition.symbol),file:e.definition.relativePath,origins:fe([...e.origins])}}function t$(e){return[...Be(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:fe(n.map(r=>r.kind)),relationCount:n.length,fromFiles:fe(n.map(r=>r.fromFile)),toFiles:fe(n.map(r=>r.toFile)),fromSymbols:fe(n.flatMap(r=>r.fromSymbol?[T(r.fromSymbol)]:[])),toSymbols:fe(n.flatMap(r=>r.toSymbol?[T(r.toSymbol)]:[])),evidence:fe(n.map(r=>r.evidence)),strengths:fe(n.map(r=>r.strength??"unknown"))})).sort((n,r)=>n.fromRegionId.localeCompare(r.fromRegionId)||n.toRegionId.localeCompare(r.toRegionId))}function n$(e,t){return[...e.values()].map(n=>({kind:"external-import",name:n.name,fromRegionIds:fe([...n.fromFiles].flatMap(r=>{let i=t.get(r);return i?[i.id]:[]})),fromFiles:fe([...n.fromFiles])})).sort((n,r)=>n.name.localeCompare(r.name))}function r$(e,t,n,r){let i=e.kind==="literal"?t.filter(o=>o.query===e.query).map(o=>o.file):[...n.values()].filter(o=>o.anchorQueries.has(e.query)).map(o=>o.definition.relativePath);return fe(i.map(o=>r.get(o)?.id).filter(o=>!!o))}function HC(e){return e.keyParts.map(t=>`${t.name}=${t.value}`).join(" ")}function fe(e){return[...new Set(e)].sort()}function UC(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 i$(e,t){return Ni(e.origins)-Ni(t.origins)||e.shortName.localeCompare(t.shortName)}function o$(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)}function s$(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)||e.symbol.localeCompare(t.symbol)}function qC(e,t){return e.file.localeCompare(t.file)||e.line-t.line||e.query.localeCompare(t.query)}var c$=["causal","structure","complete"],l$={causal:["execution","runtime","dataflow","state","temporal"],structure:["contract","identity","ownership","dependencies"],complete:$t},u$=2,d$=48,GC=64,m$=5e4;function ts(e,t,n={}){let r=ke([...t.symbols??[],...t.locations??[]]),i=ke(t.searches??[]);if(r.length===0&&i.length===0)throw new Error("evidence requires at least one positional symbol, --symbol, --at, or --search selector.");let o=n.view??"causal",s=p$(n.families,o),a=n.direction??"both",c=ke(n.subtypes??[]),l=n.connecting??!1,u=n.inventoryOnly??!1,d=ke(n.foldIds??[]),m=n.maxDepth??u$,p=n.maxEdges??d$;if(!Number.isSafeInteger(m)||m<0)throw new RangeError(`Evidence depth must be a non-negative safe integer; received ${m}.`);if(!Number.isSafeInteger(p)||p<=0)throw new RangeError(`Evidence max edges must be a positive safe integer; received ${p}.`);if(!["incoming","outgoing","both"].includes(a))throw new Error(`Unsupported graph evidence direction: ${a}.`);if(u&&d.length>0)throw new Error("Evidence fold materialization cannot be combined with --inventory-only.");let f=OC(e,{symbols:r,searches:i,maxDepth:m,maxTopologyCharacters:m$,relations:f$(s)}),g=new Map(f.nodes.map(G=>[G.id,G])),h=f.edges.filter(G=>G.disposition==="emitted"||G.disposition==="folded").flatMap(G=>g$(G,g)),b=h.filter(G=>s.includes(G.family)).filter(G=>c.length===0||c.includes(G.subtype)),S=new Set(f.anchors.flatMap(G=>G.nodeIds));if(l&&S.size<2)throw new Error("Connecting evidence requires at least two resolved root nodes.");let y=new Set(b.map(G=>G.id)),x=sm(h,S,"incoming").filter(G=>y.has(G.id)),v=sm(h,S,"outgoing").filter(G=>y.has(G.id)),C=sm(h,S,"both").filter(G=>y.has(G.id)),R=v$(s,c,x,v,C),E=a==="incoming"?x:a==="outgoing"?v:C,I=l?L$(E,[...S],a):E,w=D$(I,S,a),A=[...I].sort((G,O)=>M$(G,O,w)),D=C$(A,p),k=R$(D,d),L=u?[]:d.length>0?A.filter(G=>k.has(G.id)):A,F=d.length>0?L:L.slice(0,p),P=d.length>0||u?[]:D,j=Math.max(0,L.length-F.length),B=f.frontiers.filter(G=>G.disposition==="unsupported").length,X=f.coverage.status==="incomplete"?"incomplete":j>0?"bounded":"accounted";return{kind:"graph",view:n.families&&n.families.length>0?"custom":o,families:s,selection:{direction:a,subtypes:c,connecting:l,inventoryOnly:u,foldIds:d},targets:f.anchors.map(G=>({kind:G.kind,query:G.query,status:G.status,nodeIds:[...G.nodeIds],omittedCandidates:G.omittedCandidates})),inventory:R,edges:F,folds:P,coverage:{status:X,topologyStatus:f.coverage.status,scope:f.coverage.scope,maxDepth:m,maxEdges:p,matchedEdges:A.length,eligibleEdges:L.length,returnedEdges:F.length,omittedEdges:j,frontierGroups:f.frontiers.length,unsupportedFrontiers:B,blindSpots:ke([...f.coverage.blindSpots,...Av(s)]),explanation:u?`${A.length} relationship(s) match the explicit projection; only exact inventory counts were requested.`:d.length>0?`Every relationship in ${d.length} explicitly selected recoverable fold(s) was emitted.`:X==="accounted"?"Every selected relationship in the bounded topology was emitted.":X==="bounded"?`${j} selected relationship(s) were withheld by the explicit edge budget.`:f.coverage.explanation}}}function p$(e,t){let n=e&&e.length>0?e:l$[t],r=n.filter(i=>!$t.includes(i));if(r.length>0)throw new Error(`Unsupported graph evidence family: ${r.join(", ")}.`);return ke(n)}function f$(e){return["call","contract-symbol","import","reference","runtime-boundary"]}function g$(e,t){let n=t.get(e.fromNodeId),r=t.get(e.toNodeId);return!n||!r?[]:(e.semantics??[]).flatMap((i,o)=>{let s=y$(i);if(!s)return[];let a=fc(s,i.subtype);if(!a)throw new Error(`No graph relation provider contract is registered for ${s}/${i.subtype}.`);let c=S$(e);return a.relation.evidenceStrengths.includes(c)?[{id:`${e.id}:${o}:${s}`,family:s,semanticFamily:i.family,subtype:i.subtype,from:zC(n),to:zC(r),sourceKind:e.kind,providerId:a.provider.id,supportCeiling:a.relation.supportCeiling,establishes:a.relation.establishes,nonClaims:[...a.relation.nonClaims],recoverWith:[...a.relation.recoverWith],evidenceStrength:c,evidenceMethods:ke(e.evidence.map(l=>l.method)),evidenceConstituents:h$(e.evidence),context:i.context?{...i.context}:null,attributes:i.attributes?{...i.attributes}:null}]:[]})}function h$(e){let t=new Map;for(let n of e)t.set(`${n.method}\0${n.strength}`,n);return[...t.values()].map(({method:n,strength:r})=>({method:n,strength:r}))}function y$(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 zC(e){let t=b$(e);return{id:e.id,kind:e.kind,label:t?T(t):e.label,symbol:t,location:e.location?{...e.location}:null}}function b$(e){return e.kind!=="symbol"||!e.id.startsWith("symbol:")?null:decodeURIComponent(e.id.slice(7))}function S$(e){let t=ke(e.evidence.map(n=>n.strength));return t.length===1?t[0]:t.includes("exact")&&t.every(n=>n==="exact"||n==="derived")?"mixed":t.includes("candidate")?"candidate":t.includes("unknown")||t.length===0?"unknown":"mixed"}function sm(e,t,n){let r=am(e,n),i=new Map,o=new Map,s=[...t].sort();for(let a of s)o.set(a,0);for(let a=0;a<s.length;a+=1){let c=s[a],l=o.get(c);for(let u of r.get(c)??[])i.set(u.edge.id,u.edge),!o.has(u.next)&&(o.set(u.next,l+1),s.push(u.next))}return[...i.values()]}function am(e,t){let n=new Map,r=(i,o,s)=>{let a=n.get(i)??[];a.push({edge:s,next:o}),n.set(i,a)};for(let i of e)t!=="incoming"&&r(i.from.id,i.to.id,i),t!=="outgoing"&&r(i.to.id,i.from.id,i);for(let i of n.values())i.sort((o,s)=>o.edge.id.localeCompare(s.edge.id)||o.next.localeCompare(s.next));return n}function v$(e,t,n,r,i){let o=new Set;for(let u of[...n,...r,...i])o.add(`${u.family}\0${u.subtype}`);if(t.length>0)for(let u of e)for(let d of t)o.add(`${u}\0${d}`);let s=u=>{let d=new Map;for(let m of u){let p=`${m.family}\0${m.subtype}`;d.set(p,(d.get(p)??0)+1)}return d},a=s(n),c=s(r),l=s(i);return[...o].map(u=>{let[d,m]=u.split("\0");return{family:d,subtype:m,incoming:a.get(u)??0,outgoing:c.get(u)??0,both:l.get(u)??0}}).sort((u,d)=>$t.indexOf(u.family)-$t.indexOf(d.family)||u.subtype.localeCompare(d.subtype))}function C$(e,t){let n=e.slice(t),r=new Map;for(let s of n){let a=x$(s),c=`${s.family}\0${a}`,l=r.get(c)??[];l.push(s),r.set(c,l)}let i=new Map(e.map((s,a)=>[s.id,a+1])),o=[];for(let[s,a]of[...r].sort(([c],[l])=>c.localeCompare(l))){let[c,l]=s.split("\0"),u=[...a].sort((d,m)=>d.id.localeCompare(m.id));for(let d=0;d<u.length;d+=GC){let m=u.slice(d,d+GC),p=m.map(b=>b.id),f=ke(m.map(b=>b.subtype)).sort(),g=f.length===1?f[0]:"mixed",h=[...new Set(m.flatMap(b=>[b.from.id,b.to.id]))].sort();o.push({id:w$(c,f.join("\0"),p),mode:E$(m),family:c,subtype:g,subtypes:f,region:l,edgeCount:p.length,edgeIds:p,nodeIds:h,minimumMaxEdges:Math.max(...p.map(b=>i.get(b)??e.length))})}}return o.sort((s,a)=>$t.indexOf(s.family)-$t.indexOf(a.family)||(s.region??"").localeCompare(a.region??"")||s.id.localeCompare(a.id))}function x$(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 R$(e,t){if(t.length===0)return new Set;let n=new Map(e.map(i=>[i.id,i])),r=t.filter(i=>!n.has(i));if(r.length>0){let i=e.map(o=>o.id).sort();throw new Error(`Unknown evidence fold ${r.join(", ")} for this projection. Available folds: ${i.join(", ")||"(none)"}.`)}return new Set(t.flatMap(i=>n.get(i).edgeIds))}function E$(e){let t=new Map,n=new Map,r=new Set;for(let o of e){r.add(o.from.id),r.add(o.to.id);let s=t.get(o.from.id)??new Set;s.add(o.to.id),t.set(o.from.id,s);let a=n.get(o.to.id)??new Set;a.add(o.from.id),n.set(o.to.id,a)}return I$(r,t)?"scc":[...r].every(o=>(n.get(o)?.size??0)<=1&&(t.get(o)?.size??0)<=1)?"linear":"topology"}function I$(e,t){let n=new Set,r=new Set,i=o=>{if(n.has(o))return!0;if(r.has(o))return!1;n.add(o);for(let s of t.get(o)??[])if(i(s))return!0;return n.delete(o),r.add(o),!1};return[...e].some(i)}function w$(e,t,n){return`fold:${a$("sha256").update([e,t,...n].join("\0")).digest("hex").slice(0,16)}`}function L$(e,t,n){let r=new Map,i=[...new Set(t)].sort();for(let o=0;o<i.length;o+=1)for(let s=o+1;s<i.length;s+=1)for(let a of P$(e,i[o],i[s],n))r.set(a.id,a);return[...r.values()]}function P$(e,t,n,r){let i=am(e,r),o=new Map([[t,0]]),s=new Map,a=[t];for(let l=0;l<a.length;l+=1){let u=a[l],d=o.get(u);if(u!==n)for(let m of i.get(u)??[])o.has(m.next)||(o.set(m.next,d+1),s.set(m.next,{node:u,edge:m.edge}),a.push(m.next))}if(!o.has(n))return[];let c=[];for(let l=n;l!==t;){let u=s.get(l);if(!u)return[];c.push(u.edge),l=u.node}return c.reverse()}function D$(e,t,n){let r=am(e,n),i=new Map,o=[...t];for(let s of t)i.set(s,0);for(let s=0;s<o.length;s+=1){let a=o[s],c=i.get(a);for(let{next:l}of r.get(a)??[])i.has(l)||(i.set(l,c+1),o.push(l))}return i}function M$(e,t,n){return KC(e,n)-KC(t,n)||WC(e)-WC(t)||VC(e.evidenceStrength)-VC(t.evidenceStrength)||$t.indexOf(e.family)-$t.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 KC(e,t){return Math.min(t.get(e.from.id)??Number.MAX_SAFE_INTEGER,t.get(e.to.id)??Number.MAX_SAFE_INTEGER)}function WC(e){let t=[e.from,e.to].filter(n=>n.kind==="structural-region").length;return t===2?2:t}function VC(e){switch(e){case"exact":return 0;case"mixed":return 1;case"derived":return 2;case"candidate":return 3;case"unknown":return 4}}function cm(e,t){let n=wr(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let r=n.map(()=>"?").join(", "),o=e.all(`SELECT relative_path FROM documents
92
- WHERE relative_path IN (${r})
93
- ORDER BY relative_path`,...n).map(l=>l.relative_path).filter(l=>!e.isIgnored(l)),s=qs(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:l,...u})=>u),a=Bn(e,"forward",n).filter(l=>!e.isIgnored(l)),c=Bn(e,"reverse",n).filter(l=>!e.isIgnored(l));return{files:o,symbols:s,dependsOn:a,dependedOnBy:c}}function lm(e,t){let n=wr(e,t);return n.length===0?[]:JC([...YC(e,n),...A$(e,n)]).filter(r=>!e.isIgnored(r.relative_path)).map(XC)}function T$(e,t){let n=wr(e,t);return n.length===0?[]:JC(YC(e,n)).filter(r=>!e.isIgnored(r.relative_path)).map(r=>({...XC(r),basis:"external-reference"}))}function YC(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
94
- FROM mentions m
95
- JOIN chunks c ON m.chunk_id = c.id
96
- JOIN documents d1 ON c.document_id = d1.id
97
- JOIN global_symbols gs ON m.symbol_id = gs.id
98
- WHERE d1.relative_path NOT IN (${n})
99
- AND (
100
- EXISTS (
101
- SELECT 1
102
- FROM defn_enclosing_ranges der
103
- JOIN documents d2 ON der.document_id = d2.id
104
- WHERE der.symbol_id = gs.id
105
- AND d2.relative_path IN (${n})
106
- )
107
- OR EXISTS (
108
- SELECT 1
109
- FROM mentions def_m
110
- JOIN chunks def_c ON def_m.chunk_id = def_c.id
111
- JOIN documents d2 ON def_c.document_id = d2.id
112
- WHERE def_m.symbol_id = gs.id
113
- AND def_m.role = 1
114
- AND d2.relative_path IN (${n})
115
- )
116
- )
117
- AND m.role != 1
118
- AND ${e.localSymbolPredicate}
119
- ${e.pathExclusionsFor("d1")}
120
- ORDER BY d1.relative_path`,...t,...t,...t)}function A$(e,t){let n=new H(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>Xe(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function JC(e){let t=new Set;return e.filter(n=>{let r=`${n.relative_path}|${n.symbol}`;return t.has(r)?!1:(t.add(r),!0)})}function XC(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:T(e.symbol)}}var ns=new WeakMap,QC=mt({kind:"definition-exclusions",invalidation:Te("definition-exclusions"),serialize:e=>JSON.stringify(e),deserialize:F$});function ex(e,t){let n=se(t);if(!(n==="rust"||n==="typescript"||n==="tsx"||n==="javascript"))return[];let i=W(e,t);if(!i)return[];let o=Et(e,t,i),s=QC.read(e,t,o);if(s)return s;let a=n==="rust"?H$(e,t):O$(e,t);return QC.write(e,t,o,a),a}function F$(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=t.map(k$);return n.some(r=>r===null)?null:n}catch{return null}}function k$(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?Z$(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 tx=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]),N$=/\b(?:describe|it|test|fdescribe|fit|xdescribe|xit|beforeEach|afterEach|beforeAll|afterAll|before|after|suite|bench|benchmark)\s*\(/,_$=/\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 O$(e,t){let n=W(e,t);if(!n||!B$(n))return[];let r=J(e,t);if(!r)return[];let i=ns.get(r);if(i)return i;let o=!1,s=r.rootNode;for(let c of s.namedChildren){if(c.type!=="expression_statement")continue;let l=c.namedChild(0);if(!l||l.type!=="call_expression")continue;let u=l.namedChild(0);if(!u)continue;let d=u.type==="member_expression"?u.namedChild(u.namedChildCount-1)?.text:u.text;if(d&&tx.has(d)){o=!0;break}}let a=[];o&&a.push({startLine:0,endLine:s.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)",disposition:"exclude"});for(let c of s.namedChildren){let l=null,u=null;if(c.type==="function_declaration")l=c.namedChild(0)?.text??null,u=c;else if(c.type==="export_statement"){let d=c.namedChild(0);d?.type==="function_declaration"&&(l=d.namedChild(0)?.text??null,u=d)}else if(c.type==="lexical_declaration"){let d=c.namedChild(0);if(d?.type==="variable_declarator"){let m=d.namedChild(0)?.text,p=d.namedChild(1);m&&(p?.type==="arrow_function"||p?.type==="function_expression")&&(l=m,u=d)}}l&&/^use[A-Z]/.test(l)&&u&&a.push({startLine:u.startPosition.row,endLine:u.endPosition.row,reason:"React custom hook (use*)",disposition:"exclude"})}return a.push(...nx(r,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),ns.set(r,a),a}function B$(e){if(e.includes("scip-query"))return!0;let t=!1;for(let n of tx)if(e.includes(n)){t=!0;break}return t&&N$.test(e)?!0:e.includes("use")&&_$.test(e)}var $$=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function j$(e){return $$.test(e)}function nx(e,t,n){let r=[],i=o=>{if(t.has(o.type)&&o.parent){let a=o.parent.children,c=-1;for(let l=0;l<a.length;l+=1)if(a[l].startIndex===o.startIndex&&a[l].type===o.type){c=l;break}if(c>0)for(let l=c-1;l>=0;l-=1){let u=a[l];if(n.has(u.type)){if(j$(u.text)){r.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"scip-query suppression comment",disposition:"exclude"});break}continue}if(!(u.type==="attribute_item"||u.type==="inner_attribute_item"))break}}for(let s of o.namedChildren)i(s)};return i(e.rootNode),r}function H$(e,t){let n=J(e,t);if(!n)return[];let r=ns.get(n);if(r)return r;let i=[],o=U$(n);return o?(ns.set(n,o),o):(rx(n.rootNode,i,!1,!1),i.push(...nx(n,new Set(["function_item","function_signature_item","struct_item","enum_item","union_item","impl_item","mod_item","static_item","const_item"]),new Set(["line_comment","block_comment"]))),i.push(...X$(n.rootNode)),ns.set(n,i),i)}function U$(e){return ej(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)",disposition:"exclude"}]:null}function rx(e,t,n,r){let i=n,o=r;e.type==="trait_item"&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait declaration body (dynamic dispatch)",disposition:"implicit-usage"}),e.type==="impl_item"&&e.childForFieldName("trait")&&(o=!0,t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl block (dynamic dispatch)",disposition:"implicit-usage"})),e.type==="function_item"||e.type==="function_signature_item"?q$(e,t,n,r):r&&J$(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"?G$(e,t,n):e.type==="mod_item"&&um(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(i=!0);for(let s of e.namedChildren)rx(s,t,i,o)}function q$(e,t,n,r){let i=um(e),o=null;r?o={reason:"trait impl method (dynamic dispatch)",disposition:"implicit-usage"}:n&&(o={reason:"inside #[cfg(test)] mod",disposition:"exclude"});for(let s of i){if(ix(s)){o={reason:"#[allow(dead_code)]",disposition:"exclude"};break}let a=V$(s);if(a){o=a;break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o.reason,disposition:o.disposition})}function G$(e,t,n){let r=um(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(Y$)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(...)] - generated impl may access fields",disposition:"implicit-usage",containerName:i}),r.some(ix)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",disposition:"exclude",containerName:i}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",disposition:"exclude",containerName:i})}function um(e){let t=e.parent;if(!t)return[];let n=t.children,r=-1;for(let o=0;o<n.length;o+=1)if(n[o].startIndex===e.startIndex&&n[o].type===e.type){r=o;break}if(r<=0)return[];let i=[];for(let o=r-1;o>=0;o-=1){let s=n[o];if(s.type==="attribute_item"||s.type==="inner_attribute_item")i.push(s.text);else{if(s.type==="line_comment"||s.type==="block_comment")continue;break}}return i}var z$=new Set(["test","bench","tokio::test","async_std::test"]),K$=new Set(["no_mangle","export_name","link_name","used","macro_export","proc_macro","proc_macro_derive","proc_macro_attribute"]),W$=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 V$(e){if(/#\[\s*cfg\s*\(\s*test\s*\)/.test(e))return{reason:"#[cfg(test)]",disposition:"exclude"};let t=Q$(e);return t?z$.has(t)?{reason:`#[${t}]`,disposition:"exclude"}:K$.has(t)?{reason:`Rust ABI/export attribute #[${t}]`,disposition:"implicit-usage"}:W$.has(t)?null:{reason:`Rust attribute macro #[${t}]`,disposition:"implicit-usage"}:null}function Y$(e){return/#\[\s*derive\s*\(/.test(e)}function ix(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function J$(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function X$(e){let t=tj(e);if(t.size===0)return[];let n=[];for(let r of e.descendantsOfType("mod_item")){let i=r.childForFieldName("name")?.text;i&&t.has(i)&&n.push({startLine:r.startPosition.row,endLine:r.endPosition.row,reason:'attribute `with = "..."` module - body may be invoked via reflection',disposition:"implicit-usage",containerName:i})}return n}function Q$(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 Z$(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 ej(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 ZC=/\bwith\s*=\s*"([^"]+)"/g;function tj(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){ZC.lastIndex=0;let r;for(;(r=ZC.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}function ox(e){let t=dm(e);return(n,r,i,o)=>t(n,r,i,o)?.disposition==="exclude"}function dm(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=ex(e,r),s=new Map;for(let a of o){if(!a.containerName)continue;let c=s.get(a.containerName)??[];c.push(a),s.set(a.containerName,c)}return i={ranges:o,containers:s},t.set(r,i),i};return(r,i,o,s)=>{let a=n(r),c=[];for(let u of a.ranges)i>=u.startLine&&i<=u.endLine&&c.push(u);let l=new Set;s&&l.add(s);for(let u of Gs(o))l.add(u);for(let u of l){let d=a.containers.get(u);d&&c.push(...d)}return nj(c)}}function nj(e){if(e.length===0)return null;let n=e.find(r=>r.disposition==="exclude")??e[0];return{disposition:n.disposition,reason:n.reason}}function mm(e,t={}){Qi(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function sx(e,t,n={}){Qi(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function ax(e,t){if(t.isIgnoredPath(e.relativePath))return rt("ignored-file");if(pe(e.symbol))return rt("module-like-symbol");if(!Tc(e.symbol))return rt("non-value-symbol");if(!e.isFunctionLike&&e.enclosingSymbol&&Tc(e.enclosingSymbol))return rt("nested-non-callable-value");if(!t.includeTests&&!rj(e.relativePath))return rt("test-file");if(!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName))return rt("excluded-file-region");let n=z(e.symbol);if(n==="<constructor>")return rt("implicit-constructor");if(e.symbol.startsWith("scip-python ")){if(n==="__all__")return rt("python-runtime-metadata");if(/^__[^_].*__$/.test(n))return rt("python-protocol-member")}return t.isDeclarationOnlyCallable()?rt("declaration-only-callable"):t.isFrameworkContractCallable()?rt("framework-contract-member"):He(e.symbol)?rt("rust-trait-impl-member"):ci(e.symbol)?rt("rust-test-module"):!t.includeMembers&&!ij(e)?rt("member"):e.endLine-e.startLine+1<t.minLoc?rt("below-min-loc"):{accepted:!0}}function rj(e){return q(e)!=="test"}function rt(e){return{accepted:!1,rejectionReason:e}}function Tc(e){return Se(e)||e.endsWith("().")||e.endsWith(".")}function ij(e){return Xe(e.symbol)||Gs(e.symbol).length===0}function cx(){return new Map}function lx(e,t,n){let r=new Map;for(let i of _f(e,n))e.isIgnored(i.relative_path)||t.has(i.relative_path)||Fc(r,i.symbol_id,i.relative_path,i.ref_count,"scip-mention");return r}function ux(e,t,n,r={}){let i=new Set;if(r.conservative||n.size===0){for(let o of Bf(e,t))i.add(o.symbol_id);return i}for(let o of Of(e,t))e.isIgnored(o.relative_path)||n.has(o.relative_path)||i.add(o.symbol_id);return i}function pm(e,t){let n=e.get(t);if(!n)return!1;for(let r of n.values())if(r.occurrences>0)return!0;return!1}function Ac(e,t,n){let r=e.get(t);if(!r)return!1;for(let[i,o]of r)if(i!==n&&o.occurrences>0)return!0;return!1}function dx(e){return e?.occurrences??0}function Fc(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=px(e,t,n);o.occurrences+=r,o.sources.add(i)}function mx(e,t,n,r,i){if(r<=0)return;let o=px(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function px(e,t,n){let r=e.get(t);r||(r=new Map,e.set(t,r));let i=r.get(n);return i||(i={occurrences:0,sources:new Set},r.set(n,i)),i}var oj=new Set(["componentDidCatch","componentDidMount","componentDidUpdate","componentWillUnmount","getDerivedStateFromError","getDerivedStateFromProps","getSnapshotBeforeUpdate","render","shouldComponentUpdate","UNSAFE_componentWillMount","UNSAFE_componentWillReceiveProps","UNSAFE_componentWillUpdate"]);function ji(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=J(e,t.relativePath);if(!n)return!1;let r=n.rootNode.descendantsOfType("method_definition").find(s=>s.startPosition.row<=t.startLine&&s.endPosition.row>=t.endLine);if(!r)return!1;if(/\boverride\b/.test(r.text.slice(0,Math.max(0,r.text.indexOf("{")))))return!0;let i=r.parent;for(;i&&i.type!=="class_declaration"&&i.type!=="class";)i=i.parent;if(!i)return!1;let o=i.text.slice(0,Math.max(0,i.text.indexOf("{")));return/\bimplements\b/.test(o)||/\bextends\b/.test(o)?!0:oj.has(t.leaf)&&/\bextends\s+(?:React\.)?(?:Component|PureComponent)\b/.test(o)}var sj=64,aj=300;function Vr(e,t={}){let{scope:n,minLoc:r=1,includeTests:i=!1,skipBarrels:o=!1,includeMembers:s=!1,deadCodeOnly:a=!1,scanLimit:c,semantic:l=!0}=t,u=0,d=N("dead.candidates",()=>{let v=he(cj(e,{scope:n,minLoc:r,includeTests:i,includeMembers:s}),c);return u=v.length,v},()=>({definitions:u})),m=0,p=o?N("dead.inactive-barrels",()=>{let v=new Set(Kb(e));return m=v.size,v},()=>({paths:m})):new Set,f=0,g=a?cx():N("dead.mention-reference-counts",()=>{let v=lx(e,p,d.map(C=>C.symbolId));return f=v.size,v},()=>({definitions:d.length,symbolsWithReferences:f})),h=0,b=a?N("dead.mentioned-symbol-ids",()=>{let v=ux(e,d.map(C=>C.symbolId),p,{conservative:p.size===0});return h=v.size,v},()=>({definitions:d.length,referencedSymbols:h})):new Set,S=a?d.filter(v=>!b.has(v.symbolId)):d.filter(v=>!Ac(g,v.symbolId,v.relativePath));a?N("dead.source-fallback.dead-code-only",()=>gj(e,S,g,{inactiveBarrelPaths:p}),()=>({definitions:S.length,testReferencesIncluded:!0})):N("dead.source-fallback.ast",()=>fj(e,S,g,{inactiveBarrelPaths:p}),()=>({definitions:S.length,testReferencesIncluded:!0}));let y=a?S.filter(v=>!pm(g,v.symbolId)):S.filter(v=>!Ac(g,v.symbolId,v.relativePath));N("dead.caller-map-supplement",()=>Sj(e,y,g,{inactiveBarrelPaths:p,includeSemantic:!a&&l}),()=>({definitions:y.length,semantic:!a&&l}));let x=a?S.filter(v=>!pm(g,v.symbolId)):d;return pj(e,dj(x,g))}function cj(e,t){let n=ox(e),r=[];for(let i of no(e,{scope:t.scope,symbolMatches:Tc,sqlPrefilter:"function-like"}))ax(i,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:s=>e.isIgnored(s),isExcludedRegion:n,isDeclarationOnlyCallable:()=>uj(e,i),isFrameworkContractCallable:()=>ji(e,i)}).accepted&&r.push(i);return r}var lj=["method_signature","abstract_method_signature","call_signature","construct_signature"];function uj(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=J(e,t.relativePath);if(n)return n.rootNode.descendantsOfType([...lj]).some(i=>i.startPosition.row<=t.startLine&&i.endPosition.row>=t.endLine);let r=V(e,t.relativePath).slice(t.startLine,t.endLine+1).join(`
121
- `).trim();return r.endsWith(";")&&!r.includes("=>")&&!r.includes("{")}function dj(e,t){return e.map(n=>mj(n,t)).filter(n=>n.cross_file_refs===0).sort((n,r)=>r.loc-n.loc||n.relative_path.localeCompare(r.relative_path)||n.start_line-r.start_line)}function mj(e,t){let n=t.get(e.symbolId)??new Map,r=dx(n.get(e.relativePath)),i=0;for(let[o,s]of n)o!==e.relativePath&&(i+=s.occurrences);return{relative_path:e.relativePath,start_line:e.startLine,end_line:e.endLine,loc:e.endLine-e.startLine+1,symbol:e.symbol,parent_type_name:e.parentTypeName,same_file_refs:r,cross_file_refs:i}}function pj(e,t){let n=dm(e),r=[],i=0,o=0,s=0,a=0,c=0,l=0;for(let u of t){if(e.isIgnored(u.relative_path))continue;if(Ue(e,u.relative_path)){a++;continue}if(Fe(e,u.symbol,u.relative_path)){c++;continue}let d=n(u.relative_path,u.start_line,u.symbol,u.parent_type_name),m=d?.disposition==="implicit-usage"?d.reason:void 0,p=m?"implicit-usage":u.same_file_refs===0?"dead-code":"file-internal";p==="dead-code"?i++:p==="file-internal"?o++:s++,l+=u.loc,r.push({relativePath:u.relative_path,startLine:u.start_line,endLine:u.end_line,loc:u.loc,symbol:u.symbol,shortName:T(u.symbol),sameFileRefs:u.same_file_refs,kind:p,...m?{implicitUsageReason:m}:{}})}return{symbols:r,counts:{total:r.length,deadCode:i,fileInternal:o,implicitUsage:s,loc:l},applicability:{entrySurfaceExcluded:a,externalRootExcluded:c,implicitUsageSignals:s},totalCount:r.length,deadCodeCount:i,fileInternalCount:o,implicitUsageCount:s,totalLoc:l}}function fj(e,t,n,r){if(t.length===0)return;let i=new H(e),o=new Set(t.map(c=>c.symbolId)),s=new Set(t.map(c=>c.leaf).filter(Boolean)),a=new Set(i.sourceFiles());for(let c of Q(e))a.add(c);i.scanSourceReferences({paths:a,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:s,skipPath:c=>r.inactiveBarrelPaths.has(c)},c=>{o.has(c.target.symbolId)&&(yj(e,c)||Fc(n,c.target.symbolId,c.sourceFile,bj(c),"source-fallback"))})}function gj(e,t,n,r){if(t.length===0)return;let i=new H(e),o=Tf(t),s=new Set(i.sourceFiles());for(let u of Q(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let d=c.get(u);return d||(d=Uf(e,u),c.set(u,d)),d};i.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:u=>r.inactiveBarrelPaths.has(u),resolveTargets:({sourceFile:u,name:d,kind:m})=>{let p=o.get(d);return p?hj(u,d,p,()=>l(u),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),sx(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&fx(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||Fc(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function hj(e,t,n,r,i){let o=n.filter(l=>l.relativePath===e);if(o.length>0)return o;if(!i.permissive&&n.length===1)return[...n];let s=r(),a=s.get(t);if(a)for(let l of a){let u=n.filter(d=>_e(l,d.relativePath));if(u.length>0)return u}let c=new Set;for(let l of s.values())for(let u of l)c.add(u);for(let l of c){let u=n.filter(d=>_e(l,d.relativePath));if(u.length>0&&u.length===n.length)return u}return i.permissive?[...n]:[]}function yj(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&fx(e,t)}function bj(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function fx(e,t){return t.occurrences>1?!1:ae(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function Sj(e,t,n,r){let i=r.includeSemantic!==!1,o=i&&t.length>=sj&&Q(e).length>=aj,s=(u,d)=>{d===u.relativePath||e.isIgnored(d)||r.inactiveBarrelPaths.has(d)||mx(n,u.symbolId,d,1,"caller-map")};if(o?N("dead.caller-map.per-symbol-non-semantic",()=>{let u=bn(e,t,{semantic:!1,semanticEvidence:re});for(let d of t){let m=u.get(d.symbolId)??[];for(let p of m)s(d,p.file)}},()=>({definitions:t.length,semantic:!1,batched:!0})):N("dead.caller-map.per-symbol",()=>{for(let u of t){let d=zn(e,u,{semantic:i,semanticEvidence:re});if(d.length!==0)for(let m of d)s(u,m.file)}},()=>({definitions:t.length,semantic:i})),!o)return;let a=0,c=N("dead.caller-map.semantic-candidates",()=>{let u=t.filter(d=>!Ac(n,d.symbolId,d.relativePath));return a=u.length,u},()=>({definitions:t.length,semanticCandidates:a}));if(c.length===0)return;let l=qy(e,c);for(let u of c){let d=l.get(u.symbolId);if(d)for(let m of d)s(u,m)}}function vj(e,t={}){let{limit:n=30,scope:r}=t,i=r?"AND def_d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[],a=e.all(`SELECT
122
- gs.symbol,
123
- COUNT(*) AS ref_count,
124
- COUNT(DISTINCT ref_d.id) AS file_count,
125
- def_d.relative_path AS defined_in
126
- FROM mentions m
127
- JOIN chunks c ON m.chunk_id = c.id
128
- JOIN documents ref_d ON c.document_id = ref_d.id
129
- JOIN global_symbols gs ON m.symbol_id = gs.id
130
- JOIN (
131
- SELECT m2.symbol_id, c2.document_id
132
- FROM mentions m2
133
- JOIN chunks c2 ON m2.chunk_id = c2.id
134
- WHERE m2.role = 1
135
- GROUP BY m2.symbol_id
136
- ) sym_def ON sym_def.symbol_id = gs.id
137
- JOIN documents def_d ON sym_def.document_id = def_d.id
138
- WHERE m.role != 1
139
- AND def_d.id != ref_d.id
140
- ${e.pathExclusionsFor("def_d")}
141
- ${e.symbolNoiseFor("gs")}
142
- ${i}
143
- GROUP BY gs.id
144
- ORDER BY ref_count DESC
145
- LIMIT ?`,...o,n).filter(c=>!e.isIgnored(c.defined_in)).map(c=>({symbol:c.symbol,shortName:T(c.symbol),refCount:c.ref_count,fileCount:c.file_count,definedIn:c.defined_in,basis:"scip-cross-file-mentions",countUnit:"reference-occurrences"}));return a.length>0?a:Cj(e,r,n)}function Cj(e,t,n){return ve(e,{scope:t}).filter(r=>!e.isIgnored(r.relativePath)).map(r=>xj(e,r)).filter(r=>r.refCount>0).sort((r,i)=>i.refCount-r.refCount||i.fileCount-r.fileCount).slice(0,n)}function xj(e,t){let r=zn(e,t,{limit:500,semanticEvidence:re}).filter(i=>i.file!==t.relativePath);return{symbol:t.symbol,shortName:T(t.symbol),refCount:r.length,fileCount:new Set(r.map(i=>i.file)).size,definedIn:t.relativePath,basis:"source-backed-incoming-evidence",countUnit:"distinct-incoming-evidence-rows"}}function Rj(e,t,n={}){return Fj(e,t,n)?.map(r=>({symbol:r.symbol,shortName:r.shortName,fromFile:r.fromFile}))??[]}function Ej(e,t){let n=ne(e,t),r=Lj(e,t);if(r.length>0&&!Dj(n))return r;let i=Pj(e,t,n);return fm(t)&&i.length>0?i:Mj([...r,...i])}function Ij(e,t,n={}){let r=pt(e,t);if(!r)return[];let i=hx(e,r),o=n.semantic===!1?null:gx(e,r);return(o?wj(o,i):i).filter(a=>!a.used).map(a=>({symbol:a.symbol,shortName:a.shortName,importedIn:a.importer}))}function wj(e,t){let n=new Map;for(let i of t){let o=n.get(i.shortName);o?o.push(i):n.set(i.shortName,[i])}let r=e.map(i=>{let o=n.get(i.shortName),s=o?.shift();return o?.length===0&&n.delete(i.shortName),s?{...i,used:i.used||s.used}:i});return r.push(...[...n.values()].flat()),r}function Lj(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
146
- FROM mentions m
147
- JOIN chunks c ON m.chunk_id = c.id
148
- JOIN documents d ON c.document_id = d.id
149
- JOIN global_symbols gs ON m.symbol_id = gs.id
150
- WHERE gs.symbol LIKE ?
151
- AND m.role = 2
152
- ORDER BY d.relative_path`,`%${t}%`).filter(r=>!e.isIgnored(r.importer)).map(r=>({symbol:r.symbol,shortName:T(r.symbol),fromFile:r.importer}))}function Pj(e,t,n=ne(e,t)){let r=n?.relativePath??null,i=n?z(n.symbol):t.replace(/\(\)$/,""),o=n?pe(n.symbol):!1,s=new Set;for(let c of Q(e,{includeIgnored:!1}))for(let l of ae(e,c))Tj(l,c,{targetFile:r,targetLeaf:i,targetIsModule:o,targetPattern:t})&&s.add(c);let a=fm(t)?t.trim():null;return[...s].sort().map(c=>({symbol:a??n?.symbol??i,shortName:a??(n?T(n.symbol):i),fromFile:c}))}function Dj(e){return!!(e&&(e.symbol.startsWith("scip-clojure ")||se(e.relativePath)==="clojure"))}function Mj(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.fromFile}`;t.has(i)||(t.add(i),n.push(r))}return n.sort((r,i)=>r.fromFile.localeCompare(i.fromFile)||r.shortName.localeCompare(i.shortName))}function Tj(e,t,n){return!e.sourcePath||n.targetFile&&it(e.sourcePath)!==it(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&Oj(t)||e.kind==="namespace"&&Aj(e,n.targetPattern)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function Aj(e,t){let n=t.trim().replace(/\(\)$/,"");return fm(n)?e.importedName===n||e.localName===n:!1}function fm(e){let t=e.trim().replace(/\(\)$/,"");return t.includes(".")&&!t.includes("/")&&!t.includes(":")}function Fj(e,t,n={}){let r=pt(e,t);return r?kj(e,r,n)??(n.semantic===!1?null:gx(e,r))??hx(e,r):null}function kj(e,t,n){let i=e.all(`SELECT DISTINCT
153
- gs.symbol,
154
- def_d.relative_path AS from_file,
155
- imp_d.relative_path AS importer,
156
- EXISTS (
157
- SELECT 1
158
- FROM mentions ref_m
159
- JOIN chunks ref_c ON ref_m.chunk_id = ref_c.id
160
- WHERE ref_m.symbol_id = gs.id
161
- AND ref_m.role != 1
162
- AND ref_c.document_id = imp_d.id
163
- ) AS used
164
- FROM mentions m
165
- JOIN chunks c ON m.chunk_id = c.id
166
- JOIN documents imp_d ON c.document_id = imp_d.id
167
- JOIN global_symbols gs ON m.symbol_id = gs.id
168
- LEFT JOIN (
169
- SELECT m2.symbol_id, c2.document_id
170
- FROM mentions m2
171
- JOIN chunks c2 ON m2.chunk_id = c2.id
172
- WHERE m2.role = 1
173
- GROUP BY m2.symbol_id
174
- ) sym_def ON sym_def.symbol_id = gs.id
175
- LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
176
- WHERE imp_d.relative_path = ?
177
- AND m.role = 2
178
- ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(i.length>0){let o=n.semantic===!1?[]:To(e,t);return i.map(s=>({symbol:s.symbol,shortName:T(s.symbol),fromFile:s.from_file??"(external)",importer:s.importer,used:s.used!==0||o.some(a=>a.isUsed&&a.sourcePath===s.from_file)}))}return null}function gx(e,t){let n=To(e,t);return n.length>0?n.map(r=>{let i=yx(r.importedName,r.localName,r.kind);return{symbol:i,shortName:i,fromFile:r.sourcePath??"(external)",importer:t,used:r.kind==="side-effect"?!0:r.isUsed}}):null}function hx(e,t){let n=Nj(t,W(e,t));return ae(e,t).map(r=>{let i=yx(r.importedName,r.localName,r.kind),o=r.kind==="side-effect"||_j(t,r)||n.has(r.localName??r.importedName)?!0:r.used;return{symbol:i,shortName:i,fromFile:r.sourcePath??"(external)",importer:t,used:o}})}function Nj(e,t){let n=new Set;if(se(e)!=="python")return n;let r=/(?:^|\n)\s*__all__\s*(?:\+?=)\s*[[(]([\s\S]*?)[\])]/g;for(let i of t.matchAll(r)){let o=i[1]??"";for(let s of o.matchAll(/(['"])([A-Za-z_]\w*)\1/g))n.add(s[2])}return n}function _j(e,t){if(se(e)!=="rust"||t.used||t.kind==="side-effect")return!1;let n=t.localName??t.importedName;return n==="_"||/^[A-Z]/.test(n)}function yx(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 Oj(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function Bj(e,t){let n=ne(e,t);if(!n)return[];let i=new H(e).definitionsForFile(n.relativePath).filter(o=>o.symbol!==n.symbol).filter(o=>Df(n.symbol,o.symbol)).sort((o,s)=>o.startLine-s.startLine||o.endLine-s.endLine).map(o=>({symbol:o.symbol,shortName:T(o.symbol),startLine:o.startLine,endLine:o.endLine,kind:Lt(o.symbol)??"unknown"}));return se(n.relativePath)!=="clojure"?i:jj(i,$j(e,n))}function $j(e,t){let n=z(t.symbol);if(!n)return[];let r=T(t.symbol);return(K(e,t.relativePath)?.clojureMembers??[]).filter(i=>i.ownerName===n).map(i=>({symbol:`${t.symbol}${i.memberName}().`,shortName:`${r}:${i.memberName}()`,startLine:i.startLine,endLine:i.endLine,kind:i.memberKind}))}function jj(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.shortName}:${r.startLine}:${r.endLine}`,r);return[...n.values()].sort((r,i)=>r.startLine-i.startLine||r.endLine-i.endLine)}function Hj(e,t){let n=ne(e,t);if(!n)return[];let r=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
179
- FROM mentions m
180
- JOIN chunks c ON m.chunk_id = c.id
181
- JOIN (
182
- SELECT m2.symbol_id, c2.document_id
183
- FROM mentions m2
184
- JOIN chunks c2 ON m2.chunk_id = c2.id
185
- WHERE m2.role = 1
186
- GROUP BY m2.symbol_id
187
- ) sym_def ON sym_def.symbol_id = m.symbol_id
188
- WHERE m.symbol_id = ?
189
- AND m.role != 1
190
- AND sym_def.document_id != c.document_id`,n.symbolId);return[{name:T(n.symbol),count:r?.file_count??0,symbol:n.symbol,definedIn:n.relativePath}]}function Uj(e,t){let n=pt(e,t);return n?e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
191
- FROM mentions m
192
- JOIN chunks c ON m.chunk_id = c.id
193
- JOIN documents d ON c.document_id = d.id
194
- JOIN global_symbols gs ON m.symbol_id = gs.id
195
- JOIN (
196
- SELECT m2.symbol_id, c2.document_id
197
- FROM mentions m2
198
- JOIN chunks c2 ON m2.chunk_id = c2.id
199
- WHERE m2.role = 1
200
- GROUP BY m2.symbol_id
201
- ) sym_def ON sym_def.symbol_id = gs.id
202
- JOIN documents def_d ON sym_def.document_id = def_d.id
203
- WHERE d.relative_path = ?
204
- AND m.role != 1
205
- AND def_d.id != d.id
206
- GROUP BY d.id
207
- ORDER BY symbol_count DESC`,n).filter(o=>!e.isIgnored(o.relative_path)).map(o=>({name:o.relative_path,count:o.symbol_count,file:o.relative_path,basis:"external-symbol-references"})):[]}function qj(e,t={}){return Gj(e,t).map(n=>({name:T(n.symbol),count:n.file_count,symbol:n.symbol,definedIn:n.defined_in}))}function Gj(e,t){let{limit:n=30,scope:r}=t,i=r?"AND def_d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[];return e.all(`SELECT gs.symbol,
208
- COUNT(DISTINCT c.document_id) AS file_count,
209
- def_d.relative_path AS defined_in
210
- FROM mentions m
211
- JOIN chunks c ON m.chunk_id = c.id
212
- JOIN global_symbols gs ON m.symbol_id = gs.id
213
- JOIN (
214
- SELECT m2.symbol_id, c2.document_id
215
- FROM mentions m2
216
- JOIN chunks c2 ON m2.chunk_id = c2.id
217
- WHERE m2.role = 1
218
- GROUP BY m2.symbol_id
219
- ) sym_def ON sym_def.symbol_id = gs.id
220
- JOIN documents def_d ON sym_def.document_id = def_d.id
221
- WHERE m.role != 1
222
- AND def_d.id != c.document_id
223
- ${e.pathExclusionsFor("def_d")}
224
- ${e.symbolNoiseFor("gs")}
225
- ${i}
226
- GROUP BY gs.id
227
- HAVING file_count > 1
228
- ORDER BY file_count DESC
229
- LIMIT ?`,...o,n)}function zj(e,t={}){let{limit:n=30,scope:r}=t,i=r?"AND d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[];return e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
230
- FROM mentions m
231
- JOIN chunks c ON m.chunk_id = c.id
232
- JOIN documents d ON c.document_id = d.id
233
- JOIN global_symbols gs ON m.symbol_id = gs.id
234
- JOIN (
235
- SELECT m2.symbol_id, c2.document_id
236
- FROM mentions m2
237
- JOIN chunks c2 ON m2.chunk_id = c2.id
238
- WHERE m2.role = 1
239
- GROUP BY m2.symbol_id
240
- ) sym_def ON sym_def.symbol_id = gs.id
241
- JOIN documents def_d ON sym_def.document_id = def_d.id
242
- WHERE m.role != 1
243
- AND def_d.id != d.id
244
- ${e.pathExclusionsFor("d")}
245
- ${e.symbolNoiseFor("gs")}
246
- ${i}
247
- GROUP BY d.id
248
- ORDER BY symbol_count DESC
249
- LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}))}var bx=`SELECT COUNT(*) AS shared
250
- FROM (
251
- SELECT definition_m.symbol_id
252
- FROM documents definition_d
253
- JOIN chunks definition_c ON definition_c.document_id = definition_d.id
254
- JOIN mentions definition_m ON definition_m.chunk_id = definition_c.id
255
- AND definition_m.role = 1
256
- JOIN mentions reference_m ON reference_m.symbol_id = definition_m.symbol_id
257
- AND reference_m.role != 1
258
- JOIN chunks reference_c ON reference_c.id = reference_m.chunk_id
259
- JOIN documents reference_d ON reference_d.id = reference_c.document_id
260
- WHERE definition_d.relative_path = ?
261
- AND reference_d.relative_path = ?
262
- UNION
263
- SELECT definition_m.symbol_id
264
- FROM documents definition_d
265
- JOIN chunks definition_c ON definition_c.document_id = definition_d.id
266
- JOIN mentions definition_m ON definition_m.chunk_id = definition_c.id
267
- AND definition_m.role = 1
268
- JOIN mentions reference_m ON reference_m.symbol_id = definition_m.symbol_id
269
- AND reference_m.role != 1
270
- JOIN chunks reference_c ON reference_c.id = reference_m.chunk_id
271
- JOIN documents reference_d ON reference_d.id = reference_c.document_id
272
- WHERE definition_d.relative_path = ?
273
- AND reference_d.relative_path = ?
274
- )`;function Kj(e,t,n){let r=pt(e,t)??t,i=pt(e,n)??n,o=e.get(bx,r,i,i,r);return{...Sx(r,i,o?.shared??0)}}function Wj(e,t={}){let{limit:n=20,scope:r}=t,i=r?"AND def_d.relative_path LIKE ? AND ref_d.relative_path LIKE ?":"",o=r?[`%${r}%`,`%${r}%`]:[];return e.all(`SELECT
275
- CASE WHEN def_d.relative_path < ref_d.relative_path THEN def_d.relative_path ELSE ref_d.relative_path END AS file1,
276
- CASE WHEN def_d.relative_path < ref_d.relative_path THEN ref_d.relative_path ELSE def_d.relative_path END AS file2,
277
- COUNT(DISTINCT gs.id) AS shared
278
- FROM mentions m
279
- JOIN chunks c ON m.chunk_id = c.id
280
- JOIN documents ref_d ON c.document_id = ref_d.id
281
- JOIN global_symbols gs ON m.symbol_id = gs.id
282
- JOIN (
283
- SELECT m2.symbol_id, c2.document_id
284
- FROM mentions m2
285
- JOIN chunks c2 ON m2.chunk_id = c2.id
286
- WHERE m2.role = 1
287
- GROUP BY m2.symbol_id
288
- ) sym_def ON sym_def.symbol_id = gs.id
289
- JOIN documents def_d ON sym_def.document_id = def_d.id
290
- WHERE m.role != 1
291
- AND def_d.id != ref_d.id
292
- ${e.pathExclusionsFor("def_d","ref_d")}
293
- ${i}
294
- GROUP BY file1, file2
295
- ORDER BY shared DESC, file1, file2
296
- LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.file1)&&!e.isIgnored(a.file2)).map(a=>Sx(a.file1,a.file2,a.shared))}function Sx(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 Yr(e){let t=new Map,n=[],r=new Map,i=new Map,o=new Set,s=[],a=0,c=l=>(e.get(l)??[]).values();for(let l of e.keys()){if(r.has(l))continue;let u=[];for(r.set(l,a),i.set(l,a),a+=1,s.push(l),o.add(l),u.push({node:l,iter:c(l),pendingChild:null});u.length>0;){let d=u[u.length-1];if(d.pendingChild!==null){let f=d.pendingChild;d.pendingChild=null,i.set(d.node,Math.min(i.get(d.node),i.get(f)))}let m=d.iter.next();if(m.done){if(i.get(d.node)===r.get(d.node)){let f=[];for(;;){let g=s.pop();if(o.delete(g),f.push(g),t.set(g,n.length),g===d.node)break}n.push(f)}u.pop();continue}let p=m.value;r.has(p)?o.has(p)&&i.set(d.node,Math.min(i.get(d.node),r.get(p))):(r.set(p,a),i.set(p,a),a+=1,s.push(p),o.add(p),d.pendingChild=p,u.push({node:p,iter:c(p),pendingChild:null}))}}return{components:n,componentOf:t}}function rs(e,t={}){return xx(e,t).cycles}function xx(e,t={}){return Rx(e,t)}function Rx(e,t={}){let{scope:n,maxDepth:r=10,edgeBasis:i="symbol-references"}=t,o=Ae(e,n,i==="imports"?{scipEdges:"imports-only",sourceEdges:"imports-only"}:void 0),{components:s}=Yr(o),a=s.filter(c=>Vj(o,c)).map(c=>{let l=[...c].sort(),u=Yj(o,l),d=Xj(u);return{path:u,component:l,edgeBasis:i,witness:!0,classification:d==="real"?"dependency-cycle":"module-structure-candidate",kind:d}});return a.sort((c,l)=>c.kind!==l.kind?c.kind==="real"?-1:1:c.path.length-l.path.length),{cycles:a,truncated:!1,edgeBasis:i,maxDepth:r}}function Vj(e,t){if(t.length>1)return!0;let n=t[0];return n!==void 0&&e.get(n)?.has(n)===!0}function Yj(e,t){let n=t[0];if(!n)return[];let r=new Set(t);for(let i of[...e.get(n)??[]].filter(o=>r.has(o)).sort()){if(i===n)return[n,n];let o=Jj(e,i,n,r);if(o)return[n,...o]}throw new Error(`Cyclic component did not contain a witness path from ${n}.`)}function Jj(e,t,n,r){let i=[t],o=new Map([[t,null]]);for(let s=0;s<i.length;s+=1){let a=i[s];if(a===n){let c=[];for(let l=a;l!==null;l=o.get(l)??null)c.push(l);return c.reverse()}for(let c of[...e.get(a)??[]].filter(l=>r.has(l)).sort())o.has(c)||(o.set(c,a),i.push(c))}return null}function Xj(e){for(let r of e){let i=q(r);if(i==="test"||i==="barrel"||i==="entry")return"module-hierarchy"}if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":Pi(t)||Pi(n)||vx(t,n)||vx(n,t)||Cx(t,n)||Cx(n,t)||q(t)==="entry"||q(n)==="entry"?"module-hierarchy":"real"}function vx(e,t){if(!e.endsWith(".rs")||!t.endsWith(".rs"))return!1;let n=t.replace(/\.rs$/,"/");return e.startsWith(n)?!e.slice(n.length).includes("/"):!1}function Cx(e,t){if(!e.endsWith(".rs")||!t.endsWith(".rs"))return!1;let n=e.replace(/\.rs$/,""),r=t.replace(/\.rs$/,"");if(n===r+"_tests"||n===r+"/tests")return!0;let i=e.split("/"),o=t.split("/");if(i.length===o.length&&i.includes("tests")&&o.includes("src")){let s=i[i.length-1],a=o[o.length-1];if(s&&s===a)return!0}return!1}function ur(e,t){let n=Ex(e),r=Ex(t);if(n.endsWith("/**")){let i=n.slice(0,-3);return r===i||r.startsWith(`${i}/`)}if(n.endsWith("/*")){let i=n.slice(0,-2);if(!r.startsWith(`${i}/`))return!1;let o=r.slice(i.length+1);return o.length>0&&!o.includes("/")}return n==="**"?!0:n==="*"?r.length>0&&!r.includes("/"):n===r}function Ex(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}import{readdirSync as Qj}from"fs";import{join as Ix}from"path";function Zj(e){return wx(e).replace(/\/\*\*?$/,"")}function kc(e,t){let n=wx(t),r=Zj(n),i=n.endsWith("/**"),o=[],s=(a,c)=>{let l;try{l=Qj(a,{withFileTypes:!0})}catch{return}for(let u of l){if(u.name.startsWith("."))continue;let d=c?`${c}/${u.name}`:u.name;ur(n,d)&&o.push(d),i&&u.isDirectory()&&s(Ix(a,u.name),d)}};return s(Ix(e,r),r),o.sort()}function wx(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}var e1=/\.(test|spec)\.(ts|tsx|js|jsx|mts|cts)$/,Lx=new Map;function Px(e,t,n,r){if(!t?.testPaths?.length)return[];let i=t1(t),o=[];for(let s of n1(e,t.testPaths)){let a=r1(e,s,r),c=a?n(a):null;if(c)for(let l of ae(e,s)){let u=l.sourcePath;if(!u)continue;let d=n(u);d&&d!==c&&(i.get(c)?.has(d)||o.push({testFile:s,ownerBoundary:c,importedFile:u,importedBoundary:d,reason:"outside-owner-policy"}))}}return i1(o)}function t1(e){let t=e.allowedDependencies??{},n=e.boundaries.map(s=>s.name),r=new Map,i=(s,a)=>{for(let c of t[s]??[])a.has(c)||(a.add(c),i(c,a))};for(let s of n){let a=new Set;i(s,a),r.set(s,a)}let o=new Map;for(let s of n){let a=new Set(r.get(s));for(let c of n)c!==s&&r.get(c)?.has(s)&&a.add(c);o.set(s,a)}return o}function n1(e,t){let n=`${e.config.projectRoot}\0${t.join("\0")}`,r=Lx.get(n);if(r)return r;let i=new Set;for(let s of t)for(let a of kc(e.config.projectRoot,s))e1.test(a)&&i.add(a);let o=[...i].sort();return Lx.set(n,o),o}function r1(e,t,n){let r=t.replace(/^tests\//,"src/").replace(/\.(test|spec)\.(\w+)$/,".$2");if(r!==t&&n(r))return r;let i=t.split("/").pop().replace(/\.(test|spec)\.(\w+)$/,".$2"),o=ae(e,t).map(s=>s.sourcePath).filter(s=>!!s&&n(s)&&s.split("/").pop()===i);return o.length===1?o[0]:null}function i1(e){let t=new Map;for(let n of e){let r=`${n.testFile}\0${n.importedBoundary}`;t.has(r)||t.set(r,n)}return[...t.values()].sort((n,r)=>n.testFile.localeCompare(r.testFile)||n.importedBoundary.localeCompare(r.importedBoundary))}function Dx(e,t){let n=(e?.boundaries??[]).filter(r=>r.paths.some(i=>ur(i,t)));return n.length===1?n[0].name:null}var Mn="architecture:";function Mx(e,t,n,r={}){let i=s1(e,t);if(!n||n.boundaries.length===0)return{configured:!1,boundaries:[],edges:[],forbiddenEdges:[],reciprocalPairs:[],cycles:[],coarseBoundaries:[],staleAllowances:[],boundaryLimits:[],fragileEdges:[],testBoundaryViolations:[],coverage:{totalFiles:i.length,mappedFiles:0,unmappedFiles:[],ambiguousFiles:[]},policyCoverage:{declaredRows:0,totalBoundaries:0,missingRows:[],requiresCompletePolicy:!1,requiresCompleteCoverage:!1,requiresMinimalPolicy:!1}};let o=new Map,s=new Map(n.boundaries.map(y=>[y.name,new Set])),a=[],c=[];for(let y of i){let x=n.boundaries.filter(v=>v.paths.some(C=>ur(C,y))).map(v=>v.name).sort();if(x.length===0)a.push(y);else if(x.length>1)c.push({file:y,boundaries:x});else{let v=x[0];o.set(y,v),s.get(v).add(y)}}let l=new Map;for(let[y,x]of e){let v=o.get(y);if(v)for(let C of x){let R=o.get(C);if(!R||v===R)continue;let E=Hi(v,R),I=l.get(E);I||(I={from:v,to:R,fileEdges:[],importers:new Set,importedFiles:new Set},l.set(E,I)),I.fileEdges.push({fromFile:y,toFile:C}),I.importers.add(y),I.importedFiles.add(C)}}let u=[...l.values()].map(y=>a1(y,n)).sort(g1),d=u,m=new Map(d.map(y=>[Hi(y.from,y.to),y])),p=new Map(n.boundaries.map(y=>[y.name,new Set]));for(let y of d)p.get(y.from).add(y.to);let f=[];for(let y of d){if(y.from>=y.to)continue;let x=m.get(Hi(y.to,y.from));x&&f.push({boundaries:[y.from,y.to],forward:y,reverse:x})}let{components:g}=Yr(p),h=g.filter(y=>y.length>1).map(y=>l1(y,d,n.requireAcyclic===!0)).sort((y,x)=>x.boundaries.length-y.boundaries.length||y.boundaries.join("/").localeCompare(x.boundaries.join("/"))),b=n.allowedDependencies??{},S=n.boundaries.map(y=>y.name).filter(y=>!Object.hasOwn(b,y)).sort();return{configured:!0,boundaries:n.boundaries.map(y=>({name:y.name,paths:[...y.paths],fileCount:s.get(y.name).size,dependencyPolicyDeclared:Object.hasOwn(b,y.name)})).sort((y,x)=>y.name.localeCompare(x.name)),edges:u,forbiddenEdges:d.filter(y=>y.policyStatus==="forbidden"),reciprocalPairs:f,cycles:h,staleAllowances:d1(n,d),boundaryLimits:m1(n,d,s),fragileEdges:d.filter(y=>y.fragile),testBoundaryViolations:r.testBoundaryViolations??[],coarseBoundaries:u1(e,s,r.isModuleHierarchyFile,n.requireResolvedBoundaries===!0,y=>n.boundaries.find(x=>x.name===y)?.subUnits??"directory"),coverage:{totalFiles:i.length,mappedFiles:o.size,unmappedFiles:a,ambiguousFiles:c},policyCoverage:{declaredRows:n.boundaries.length-S.length,totalBoundaries:n.boundaries.length,missingRows:S,requiresCompletePolicy:n.requireCompletePolicy===!0,requiresCompleteCoverage:n.requireCompleteCoverage===!0,requiresMinimalPolicy:n.requireMinimalPolicy===!0}}}function is(e,t={}){let n=Ae(e,t.scope,{scipEdges:"imports-only",sourceEdges:"imports-and-reexports"}),r=Q(e,{includeIgnored:!1}).filter(o=>!t.scope||o.includes(t.scope)),i=new Set(r);return Mx(n,r,e.config.architecture,{isModuleHierarchyFile:o=>o1(e,o),testBoundaryViolations:Px(e,e.config.architecture,o=>Dx(e.config.architecture,o),o=>i.has(o))})}function o1(e,t){let n=q(t);return n==="test"||n==="entry"?!0:n!=="barrel"?!1:U(e,t).length===0}function gm(e){let t=e.forbiddenEdges.map(r=>`${Mn}forbidden-edge:${encodeURIComponent(r.from)}:${encodeURIComponent(r.to)}`);if(e.policyCoverage.requiresCompletePolicy)for(let r of e.policyCoverage.missingRows)t.push(`${Mn}missing-policy-row:${encodeURIComponent(r)}`);if(e.policyCoverage.requiresCompleteCoverage){for(let r of e.coverage.unmappedFiles)t.push(`${Mn}unmapped-file:${encodeURIComponent(r)}`);for(let r of e.coverage.ambiguousFiles)t.push(`${Mn}ambiguous-file:${encodeURIComponent(r.file)}:${r.boundaries.map(i=>encodeURIComponent(i)).sort().join("|")}`)}if(e.policyCoverage.requiresMinimalPolicy)for(let r of e.staleAllowances)t.push(`${Mn}stale-allowance:${encodeURIComponent(r.from)}:${encodeURIComponent(r.to)}`);for(let r of e.testBoundaryViolations)t.push(`${Mn}test-boundary:${encodeURIComponent(r.testFile)}:${encodeURIComponent(r.importedBoundary)}`);for(let r of e.boundaryLimits)t.push(`${Mn}boundary-limit:${r.kind}:${encodeURIComponent(r.boundary)}`);let n=new Map;for(let r of e.coarseBoundaries)r.violatesPolicy&&n.set(r.boundary,(n.get(r.boundary)??0)+1);for(let[r,i]of n){let o=`${Mn}coarse-boundary:${encodeURIComponent(r)}`;t.push(o);for(let s=2;s<=i;s+=1)t.push(`${o}:component:${s}`)}for(let r of e.cycles)r.violatesPolicy&&t.push(`${Mn}cycle:${r.boundaries.map(i=>encodeURIComponent(i)).sort().join("|")}`);return[...new Set(t)].sort()}function s1(e,t){let n=new Set(t);for(let[r,i]of e){n.add(r);for(let o of i)n.add(o)}return[...n].sort()}function a1(e,t){let n=[...e.fileEdges].sort((r,i)=>r.fromFile.localeCompare(i.fromFile)||r.toFile.localeCompare(i.toFile));return{from:e.from,to:e.to,policyStatus:c1(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 c1(e,t,n){return!e.allowedDependencies||!Object.hasOwn(e.allowedDependencies,t)?"undeclared":e.allowedDependencies[t].includes(n)?"allowed":"forbidden"}function l1(e,t,n){let r=[...e].sort(),i=new Set(r),o=t.filter(a=>i.has(a.from)&&i.has(a.to)),s=Math.min(...o.map(a=>a.fileEdgeCount));return{boundaries:r,internalEdges:o,narrowestEdges:o.filter(a=>a.fileEdgeCount===s),violatesPolicy:n}}function u1(e,t,n=p1,r=!1,i=()=>"directory"){let o=[];for(let[s,a]of t){let c=i(s)==="file"?f=>f:f1,l=[...a].filter(f=>!n(f));if(l.length<2)continue;let u=new Set(l),d=new Map,m=new Map;for(let f of l)m.set(c(f),new Set);for(let f of l)for(let g of e.get(f)??[]){if(!u.has(g))continue;let h=c(f),b=c(g);if(h===b)continue;let S=Hi(h,b),y=d.get(S);y||(y={from:h,to:b,fileEdges:[]},d.set(S,y)),y.fileEdges.push({fromFile:f,toFile:g}),m.get(h).add(b)}let{components:p}=Yr(m);for(let f of p){if(f.length<2)continue;let g=new Set(f),h=[...d.values()].filter(S=>g.has(S.from)&&g.has(S.to)).map(S=>({from:S.from,to:S.to,fileEdgeCount:S.fileEdges.length,examples:S.fileEdges.slice(0,5)})).sort((S,y)=>S.from.localeCompare(y.from)||S.to.localeCompare(y.to)),b=Math.min(...h.map(S=>S.fileEdgeCount));o.push({boundary:s,violatesPolicy:r,subUnits:[...f].sort(),internalEdges:h,narrowestEdges:h.filter(S=>S.fileEdgeCount===b)})}}return o.sort((s,a)=>a.subUnits.length-s.subUnits.length||s.boundary.localeCompare(a.boundary))}function d1(e,t){let n=new Set(t.map(s=>Hi(s.from,s.to))),r=e.allowedDependencies??{},i=new Set(e.boundaries.map(s=>s.name)),o=[];for(let[s,a]of Object.entries(r))if(i.has(s))for(let c of a)!i.has(c)||n.has(Hi(s,c))||o.push({from:s,to:c});return o.sort((s,a)=>s.from.localeCompare(a.from)||s.to.localeCompare(a.to))}function m1(e,t,n){let r=[],i=new Map;for(let o of t)i.set(o.from,(i.get(o.from)??0)+1);for(let o of e.boundaries){if(e.maxBoundaryFanOut!==void 0){let a=i.get(o.name)??0;a>e.maxBoundaryFanOut&&r.push({boundary:o.name,kind:"fan-out",observed:a,limit:e.maxBoundaryFanOut})}let s=o.maxFiles??e.maxBoundaryFiles;if(s!==void 0){let a=n.get(o.name)?.size??0;a>s&&r.push({boundary:o.name,kind:"files",observed:a,limit:s})}}return r.sort((o,s)=>o.boundary.localeCompare(s.boundary)||o.kind.localeCompare(s.kind))}function p1(e){let t=q(e);return t==="test"||t==="entry"}function f1(e){let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)}function Hi(e,t){return`${e}\0${t}`}function g1(e,t){return e.from.localeCompare(t.from)||e.to.localeCompare(t.to)}function h1(e,t={}){let{limit:n=20,scope:r,minFanIn:i=2,minFanOut:o=2,scanLimit:s}=t,a=new H(e),c=he(a.productionCallableDefinitions({scope:r,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s),l=t.semantic!==!1,u=bn(e,c,{limit:500,semantic:l,semanticEvidence:re});return c.map(m=>y1(e,m,l,u.get(m.symbolId)??[])).filter(m=>m.fanIn>=i&&m.fanOut>=o).sort((m,p)=>p.score-m.score||p.fanIn-m.fanIn).slice(0,n)}function y1(e,t,n,r){let i=[...new Set(r.map(m=>m.file))].sort(),o=[...new Set(r.filter(m=>m.source!=="caller-map-inversion"||m.callEvidence==="scip-chunk").map(m=>m.file))].sort(),s=new Map;for(let m of Dt(e,t,{limit:500,semantic:n,semanticEvidence:re})){if(m.file===t.relativePath)continue;let p=`${m.symbol}|${m.file}`;s.has(p)||s.set(p,{symbol:m.symbol,shortName:T(m.symbol),file:m.file,evidenceStrength:m.source==="scip-chunk"?"candidate":"exact",evidenceSource:m.source})}let a=[...s.values()].sort((m,p)=>m.file.localeCompare(p.file)||m.symbol.localeCompare(p.symbol)),c=i.length,l=a.length,u=c*l,d=a.filter(m=>m.evidenceStrength==="candidate").map(m=>m.symbol);return{symbol:t.symbol,shortName:T(t.symbol),fanIn:c,fanOut:l,callerFiles:i,candidateCallerFiles:o,externalCallees:a.map(({symbol:m,shortName:p,file:f})=>({symbol:m,shortName:p,file:f})),externalCalleeEvidence:a,candidateExternalCallees:d,inputBasis:"mixed-static-call-or-reference-evidence",score:u,definedIn:t.relativePath,actionTier:"signal",riskKind:"coordination-hotspot",evidenceReasons:[`${c} incoming file(s) reference this symbol`,`${l} distinct cross-file callee symbol(s) are reached from it`,`centrality score is ${u} (fan-in * fan-out)`,`${o.length} incoming file(s) and ${d.length} outgoing target(s) rely on candidate rather than exact call evidence`],recommendation:"Review ownership, API stability, and caller groups before changing this central symbol; do not refactor solely from graph centrality."}}function os(e,t={}){let{scope:n,minLoc:r=3,scanLimit:i}=t,o=new H(e),s=t.semantic!==!1,a=0,c=N("isolated.candidates",()=>{let C=he(o.productionCallableDefinitions({scope:n,minLoc:r,excludeEntrySurfaces:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:typeof i=="number"&&i>0}),i).filter(R=>!ji(e,R));return a=C.length,C},()=>({definitions:a})),l=0,u=N("isolated.strict-callees",()=>{let v=o.symbolsWithNonSelfCallees(c,{additive:!1,semantic:!1});return l=v.size,v},()=>({definitions:c.length,symbols:l})),d=c.filter(v=>!u.has(v.symbolId)),m=0,p=N("isolated.scip-callers",()=>{let v=o.crossFileCallerMap(d,{semantic:!1});return m=v.size,v},()=>({definitions:d.length,symbols:m})),f=new Set(p.keys());for(let v of o.frameworkReferencedSymbolIds(d))f.add(v);let g=d.filter(v=>!f.has(v.symbolId));if(s&&g.length>0){for(let v of Xn(e,g).keys())f.add(v);for(let v of o.symbolsWithNonSelfCallees(g,{additive:!1,semantic:!0}))u.add(v);g=g.filter(v=>!f.has(v.symbolId)).filter(v=>!u.has(v.symbolId))}let h=0,b=N("isolated.source-fallback-callers",()=>{let v=o.sourceFallbackCallerFiles(g,{skipPath:C=>q(C)==="test"});return h=v.size,v},()=>({definitions:g.length,symbols:h}));for(let v of b.keys())f.add(v);let S=g.filter(v=>!f.has(v.symbolId)),y=0,x=N("isolated.additive-callees",()=>{let v=o.symbolsWithNonSelfCallees(S,{additive:!0,semantic:s});return y=v.size,v},()=>({definitions:S.length,symbols:y}));for(let v of x)u.add(v);return S.filter(v=>!u.has(v.symbolId)).sort((v,C)=>ee(C)-ee(v)||v.relativePath.localeCompare(C.relativePath)||v.startLine-C.startLine).map(v=>({symbol:v.symbol,shortName:T(v.symbol),relativePath:v.relativePath,startLine:v.startLine,endLine:v.endLine,loc:ee(v)}))}import{SymbolInformation_Kind as Ke}from"@c4312/scip";var Tx=500;function b1(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),r=Pg.get(n);if(r!==void 0)return r;for(let[i,o]of oa)if(o.toLowerCase().includes(n))return i;return null}function S1(e,t,n={}){let{scope:r,limit:i=100}=n,o=b1(t);return o===null?[]:C1(e,r).map(a=>({row:a,resolvedKind:Fx(a)})).filter(a=>a.resolvedKind===o).slice(0,i).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:T(a.symbol),kind:c,kindName:so(c),relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function v1(e,t={}){let n=x1(e,t.scope);for(let r of R1(e,t.scope)){let i=Fx(r);i===null||i===0||n.set(i,(n.get(i)??0)+1)}return[...n.entries()].sort((r,i)=>i[1]-r[1]||r[0]-i[0]).map(([r,i])=>({kind:r,kindName:so(r),count:i}))}function C1(e,t){return ve(e,{scope:t}).map(E1)}function x1(e,t){let n=new Map;for(let r of Ax(Q(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", "),o=e.all(`SELECT gs.kind AS kind, COUNT(*) AS count
297
- FROM defn_enclosing_ranges der
298
- JOIN global_symbols gs ON der.symbol_id = gs.id
299
- JOIN documents d ON der.document_id = d.id
300
- WHERE gs.kind IS NOT NULL
301
- AND gs.kind != 0
302
- AND gs.symbol NOT LIKE '%#'
303
- AND d.relative_path IN (${i})
304
- GROUP BY gs.kind`,...r);for(let s of o)n.set(s.kind,(n.get(s.kind)??0)+s.count)}return n}function R1(e,t){let n=[];for(let r of Ax(Q(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", ");n.push(...e.all(`SELECT gs.symbol,
305
- gs.kind,
306
- gs.documentation,
307
- gs.enclosing_symbol,
308
- d.relative_path,
309
- der.start_line,
310
- der.end_line
311
- FROM defn_enclosing_ranges der
312
- JOIN global_symbols gs ON der.symbol_id = gs.id
313
- JOIN documents d ON der.document_id = d.id
314
- WHERE (gs.kind IS NULL OR gs.kind = 0 OR gs.symbol LIKE '%#')
315
- ${e.symbolNoiseFor("gs")}
316
- AND d.relative_path IN (${i})
317
- ORDER BY d.relative_path, der.start_line, der.end_line, gs.symbol`,...r))}return n}function Ax(e){let t=[];for(let n=0;n<e.length;n+=Tx)t.push(e.slice(n,n+Tx));return t}function E1(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 Fx(e){return e.kind!==null&&e.kind!==0?I1(e.kind,e.symbol,e.documentation):w1(e.symbol,e.documentation,e.enclosing_symbol)}function I1(e,t,n){let r=(n??"").toLowerCase();if(Lt(t)==="type"){if(r.includes("type "))return Ke.TypeAlias;if(r.includes("interface "))return Ke.Interface;if(r.includes("struct "))return Ke.Struct;if(r.includes("trait "))return Ke.Trait;if(r.includes("class "))return Ke.Class}return e}function w1(e,t,n){let r=$n(e);if("kind"in r)return null;let i=r.descriptors,o=i[i.length-2]??null,s=Lt(e),a=(t??"").toLowerCase();return s==="type"?a.includes("type ")?Ke.TypeAlias:a.includes("interface ")?Ke.Interface:a.includes("struct ")?Ke.Struct:a.includes("trait ")?Ke.Trait:a.includes("class ")?Ke.Class:Ke.Class:s==="method"?o?.suffix==="type"?Ke.Method:Ke.Function:s==="namespace"?Ke.Module:s!=="term"?null:a.includes("async def ")||a.includes("def ")?Ke.Function:(n?Lt(n):o?.suffix??null)==="type"?Ke.Field:Ke.Variable}function L1(e,t={}){let{limit:n=10,scope:r,minDepth:i=3,edgeBasis:o="symbol-references"}=t,s=Ae(e,r,o==="imports"?{scipEdges:"imports-only",sourceEdges:"imports-only"}:void 0),{components:a,componentOf:c}=Yr(s),l=new Map;for(let h=0;h<a.length;h++)l.set(h,new Set);for(let[h,b]of s){let S=c.get(h);for(let y of b){let x=c.get(y);x!==S&&l.get(S).add(x)}}let u=new Array(a.length),d=new Array(a.length);for(let h=0;h<a.length;h++){let b=[],S=0;for(let y of[...l.get(h)].sort((x,v)=>x-v)){let x=d[y];(x>S||x===S&&P1(u[y],b,a)<0)&&(S=x,b=u[y])}u[h]=[h,...b],d[h]=1+S}function m(h){return u[h]}let p=a.map(h=>[...h].sort()),f=new Set,g=[];for(let h=0;h<a.length;h++){let S=m(h).map(v=>p[v]),y=S.map(v=>v[0]);if(S.length<i)continue;let x=y.join(" ");f.has(x)||(f.add(x),g.push(D1(y,S,o)))}return g.sort((h,b)=>b.depth-h.depth||h.chain.join("\0").localeCompare(b.chain.join("\0"))),M1(g).slice(0,n)}function P1(e,t,n){if(t.length===0)return-1;let r=e.map(o=>[...n[o]].sort()[0]??"").join("\0"),i=t.map(o=>[...n[o]].sort()[0]??"").join("\0");return r.localeCompare(i)}function D1(e,t,n){let r=t.reduce((o,s)=>o+s.length,0),i=t.filter(o=>o.length>1).length;return{chain:e,components:t,depth:t.length,fileCount:r,edgeBasis:n,actionTier:"signal",chainKind:"transitive-dependency-depth",evidenceReasons:[`${t.length} condensed dependency component(s) form the representative transitive path`,`${r} file(s) are represented; ${i} component(s) contain a dependency cycle`,`edge basis: ${n==="imports"?"resolved file imports":"cross-file symbol references plus resolved source imports"}`,"cycles count once toward depth and retain their full membership separately"],recommendation:"Review whether the chain crosses ownership or layer boundaries; shorten it only when the dependency direction is accidental."}}function M1(e){let t=[];for(let n of e)t.some(r=>T1(n.chain,r.chain))||t.push(n);return t}function T1(e,t){if(e.length>=t.length)return!1;let n=t.length-e.length;for(let r=0;r<e.length;r++)if(e[r]!==t[n+r])return!1;return!0}function A1(e,t){let n=ne(e,t);if(!n)return[];let r=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
318
- WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:T(r.symbol),depth:0}],o=r.enclosing_symbol,s=1,a=new Set([r.symbol]);for(;o&&!a.has(o)&&s<20;){a.add(o);let d=e.get("SELECT symbol, enclosing_symbol FROM global_symbols WHERE symbol = ?",o);if(!d)break;i.push({symbol:d.symbol,shortName:T(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(i.length>1)return i;let c=$n(r.symbol);if("kind"in c)return i;let l=c.descriptors;if(l.length<=1)return i;let u=[i[0]];for(let d=l.length-2,m=1;d>=0;d--,m++){let f=l.slice(0,d+1).map(g=>g.suffix==="method"?`${g.name}()`:g.name.replace(/\.(ts|tsx|js|jsx|mjs|cjs|py|pyi|rs|java|scala|kt|kts|rb|go|cs|vb|dart|php|c|cc|cpp|cxx|h|hpp)$/,"")).join(":");u.push({symbol:f,shortName:f,depth:m})}return u}function F1(e,t={}){let r=new H(e).productionCallableDefinitions({scope:t.scope,requireCallableSymbol:!0,includeSuppressed:!0}),i=Ox(e,r),o=t.search?.trim().toLocaleLowerCase();return r.map(s=>Bx(e,s,i.get(s.symbolId)??[])).filter(s=>s!==null).map(s=>s.result).filter(s=>!o||_1(s).includes(o)).sort(O1)}function k1(e,t,n={}){let r=Qe(e,t);if(!r.match)return{kind:"missing",query:t};if(r.total>1)return{kind:"ambiguous",query:t,total:r.total,candidates:[{symbol:r.match.symbol,shortName:T(r.match.symbol),relativePath:r.match.relativePath,startLine:r.match.startLine},...r.candidates]};let i=new H(e),o=i.definitionsForFile(r.match.relativePath).find(p=>p.symbol===r.match.symbol);if(!o?.isFunctionLike)return{kind:"not-entry",query:t,symbol:r.match.symbol,shortName:T(r.match.symbol),file:r.match.relativePath,reason:"The resolved symbol is not a callable definition."};let s=Ox(e,[o]),a=Bx(e,o,s.get(o.symbolId)??[]);if(!a)return{kind:"not-entry",query:t,symbol:o.symbol,shortName:T(o.symbol),file:o.relativePath,reason:"The callable is neither an external root nor an uncalled callable on a detected entry surface."};let c=B1(e,i,o),l=new Set(n.expand??[]),u=U1(c,l),d=new Set(u.regions.filter(p=>p.expanded).map(p=>p.id)),m=[...l].filter(p=>!d.has(p)).sort();return{kind:"matched",query:t,entry:a.result,regions:u.regions,regionEdges:u.regionEdges,unmatchedExpansions:m,coverage:{completeWithinIndexedStaticCallEdges:!0,completeWithinSelectedStaticEvidence:!0,candidateReachabilityIncluded:c.edges.some(p=>p.evidenceStrength==="candidate"),dynamicDispatchRepresented:!1,symbolCount:c.symbols.length,symbolEdgeCount:c.edges.length,exactSymbolEdgeCount:c.edges.filter(p=>p.evidenceStrength==="exact").length,candidateSymbolEdgeCount:c.edges.filter(p=>p.evidenceStrength==="candidate").length,regionCount:u.regions.length,regionEdgeCount:u.regionEdges.length,externalCallCount:c.externalCalls.length}}}function Ox(e,t){let n=t.filter(r=>$x(e,r.relativePath)||Di(e,r.symbol,r.relativePath).length>0);return bn(e,n,{semantic:!1,semanticEvidence:re})}function Bx(e,t,n){let r=N1(e,t),i=r.length>0,o=$x(e,t.relativePath)&&n.length===0;if(!i&&!o)return null;let s=[...r];return o&&s.push("entry-surface-without-indexed-caller"),{definition:t,result:{symbol:t.symbol,shortName:T(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,documentation:t.documentation,confidence:i?"root":"candidate",evidence:s,indexedCallerCount:n.length}}}function $x(e,t){return Ue(e,t)||/(?:^|\/)entry\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(t)}function N1(e,t){let n=Di(e,t.symbol,t.relativePath),r=[];return kx(n,["package-surface-file","transitive-package-surface"])&&ft(e,t)&&r.push("package-public-export"),n.includes("rust-public-library")&&r.push("rust-public-library"),n.includes("framework-entrypoint")&&r.push("framework-dispatched-export"),kx(n,["configured-file","configured-path-prefix","configured-qualified-var","configured-symbol-pattern"])&&r.push("configured-entry-root"),r}function kx(e,t){return t.some(n=>e.includes(n))}function _1(e){return[e.symbol,e.shortName,e.file,e.documentation??"",...e.evidence].join(`
319
- `).toLocaleLowerCase()}function O1(e,t){return Nx(e.confidence)-Nx(t.confidence)||e.file.localeCompare(t.file)||e.startLine-t.startLine||e.symbol.localeCompare(t.symbol)}function Nx(e){return e==="root"?0:1}function B1(e,t,n){let r=new Map([[n.symbol,0]]),i=new Map,o=new Map([[n.symbol,n]]),s=new Map,a=new Map,c=[n];for(;c.length>0;){let l=t.calleeMap(c,{additive:!1,semantic:!1}),u=[];for(let d of c){let m=r.get(d.symbol)??0;i.set(d.symbol,_x(d,m));for(let p of l.get(d.symbolId)??[]){let f=$1(t,p,o);if(!f){let S=H1(d,p);a.set(z1(S),S);continue}let g=m+1,h=r.get(f.symbol);(h===void 0||g<h)&&r.set(f.symbol,g),i.set(f.symbol,_x(f,Math.min(g,h??g)));let b=j1(d,f,p);s.set(G1(b),b),h===void 0&&u.push(f)}}c=u}return{symbols:[...i.values()].sort(K1),edges:[...s.values()].sort(W1),externalCalls:[...a.values()].sort(V1)}}function $1(e,t,n){let r=n.get(t.symbol);if(r)return r;let i=e.definitionsForFile(t.file).find(o=>o.symbol===t.symbol)??null;return i&&n.set(i.symbol,i),i}function _x(e,t){return{symbol:e.symbol,shortName:T(e.symbol),file:e.relativePath,depth:t}}function j1(e,t,n){return{fromSymbol:e.symbol,fromShortName:T(e.symbol),fromFile:e.relativePath,toSymbol:t.symbol,toShortName:T(t.symbol),toFile:t.relativePath,source:n.source,evidenceStrength:n.source==="scip-chunk"?"candidate":"exact"}}function H1(e,t){return{fromSymbol:e.symbol,fromShortName:T(e.symbol),fromFile:e.relativePath,toSymbol:t.symbol,toShortName:T(t.symbol),reportedFile:t.file,source:t.source,evidenceStrength:t.source==="scip-chunk"?"candidate":"exact"}}function U1(e,t){let n=Be(e.symbols,l=>l.file),r=Be(e.edges.filter(l=>l.fromFile===l.toFile),l=>l.fromFile),i=Be(e.externalCalls,l=>l.fromFile),o=q1(e.edges.filter(l=>l.fromFile!==l.toFile)),s=Be(o,l=>l.toRegionId),a=Be(o,l=>l.fromRegionId);return{regions:[...n.entries()].map(([l,u])=>{let d=hm(l),m=t.has(d),p=r.get(l)??[],f=i.get(l)??[];return{id:d,file:l,minDepth:Math.min(...u.map(g=>g.depth)),symbolCount:u.length,internalEdgeCount:p.length,externalCallCount:f.length,incomingRegionIds:ss((s.get(d)??[]).map(g=>g.fromRegionId)),outgoingRegionIds:ss((a.get(d)??[]).map(g=>g.toRegionId)),expanded:m,symbols:m?u:[],internalEdges:m?p:[],externalCalls:m?f:[]}}).sort((l,u)=>l.minDepth-u.minDepth||l.file.localeCompare(u.file)),regionEdges:o}}function q1(e){let t=new Map;for(let n of e){let r=`${n.fromFile}\0${n.toFile}`,i=t.get(r)??[];i.push(n),t.set(r,i)}return[...t.values()].map(n=>{let r=n[0];return{fromRegionId:hm(r.fromFile),fromFile:r.fromFile,toRegionId:hm(r.toFile),toFile:r.toFile,callCount:n.length,exactCallCount:n.filter(i=>i.evidenceStrength==="exact").length,candidateCallCount:n.filter(i=>i.evidenceStrength==="candidate").length,fromSymbols:ss(n.map(i=>i.fromShortName)),toSymbols:ss(n.map(i=>i.toShortName)),evidence:ss(n.map(i=>i.source))}}).sort((n,r)=>n.fromFile.localeCompare(r.fromFile)||n.toFile.localeCompare(r.toFile))}function hm(e){return`file:${e}`}function ss(e){return[...new Set(e)].sort()}function G1(e){return`${e.fromSymbol}\0${e.toSymbol}`}function z1(e){return`${e.fromSymbol}\0${e.toSymbol}`}function K1(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)||e.symbol.localeCompare(t.symbol)}function W1(e,t){return e.fromFile.localeCompare(t.fromFile)||e.fromSymbol.localeCompare(t.fromSymbol)||e.toSymbol.localeCompare(t.toSymbol)}function V1(e,t){return e.fromFile.localeCompare(t.fromFile)||e.fromSymbol.localeCompare(t.fromSymbol)||e.toSymbol.localeCompare(t.toSymbol)}function Ft(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function We(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function dr(e,t){if(e.size===0&&t.size===0)return 0;let n=0;for(let i of e)t.has(i)&&(n+=1);let r=e.size+t.size-n;return r===0?0:n/r}function jx(e,t){if(e.size===0)return 0;let n=0;for(let r of e)t.has(r)&&(n+=1);return n/e.size}function ym(e,t){if(t<=0)return new Map;let n=new Map;for(let[r,i]of e)i>0&&n.set(r,Math.log(t/i));return n}function Ui(e){let t=[...e.values()].sort((r,i)=>r-i);if(t.length===0)return 0;let n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function qi(e,t){let n=0;for(let r of e){let i=t.get(r)??0;n+=i*i}return Math.sqrt(n)}function Hx(e,t,n,r={}){let i=0,o=0,s=0,a=r.medianIdf??Ui(n),c=[],l=[];for(let m of e){let p=n.get(m)??0;o+=p*p,t.has(m)&&(i+=p*p,p>=a?c.push(m):l.push(m))}if(c.length===0&&l.length===0)return{similarity:0,significantShared:[],trivialShared:[]};for(let m of t){let p=n.get(m)??0;s+=p*p}let u=Math.sqrt(o)*Math.sqrt(s),d=u>0?i/u:0;return c.sort((m,p)=>(n.get(p)??0)-(n.get(m)??0)),{similarity:d,significantShared:c,trivialShared:l}}function Ux(e,t,n,r){let i=0,o=r.medianIdf??Ui(n),s=[],a=[];for(let u of e){if(!t.has(u))continue;let d=n.get(u)??0;i+=d*d,d>=o?s.push(u):a.push(u)}if(s.length===0&&a.length===0)return{similarity:0,significantShared:[],trivialShared:[]};let c=r.magnitudeA*r.magnitudeB,l=c>0?i/c:0;return s.sort((u,d)=>(n.get(d)??0)-(n.get(u)??0)),{similarity:l,significantShared:s,trivialShared:a}}function as(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=rH(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!Se(o.symbol))return[];if(o.callees.size===0)return qx(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"});let s=J1(e,o,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,i):qx(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"})}function Cm(e,t,n,r={}){let i=ne(e,t),o=ne(e,n);if(!i||!o)return null;let s=as(e,i.symbol,{minSimilarity:0,limit:Number.POSITIVE_INFINITY,semantic:r.semantic,scanLimit:r.scanLimit}).find(l=>l.symbolB===o.symbol||l.symbolA===o.symbol);if(!s)return null;let a=i.endLine-i.startLine+1,c=o.endLine-o.startLine+1;return{symbolA:{symbol:i.symbol,shortName:T(i.symbol),file:i.relativePath,loc:a},symbolB:{symbol:o.symbol,shortName:T(o.symbol),file:o.relativePath,loc:c},similarity:s.similarity,similarityBasis:s.similarityBasis??"callees",sharedEvidence:s.sharedCallees,uniqueToA:s.uniqueToA,uniqueToB:s.uniqueToB,evidenceClass:s.evidenceClass,actionTier:s.actionTier,recommendation:s.recommendation,consolidationStrategy:Y1(s)}}function Y1(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 J1(e,t,n,r){let i=Gi(e).calleeIndex({minCallees:3,scanLimit:r.scanLimit,semantic:r.semantic}),o=dH(t,i.corpus),s=cH(o,i),a=X1(o,i),c=Ui(a),l=qi(o.callees,a),u=[];for(let d of s){if(d.callees.size<3)continue;let m=qi(d.callees,a),p=Wx(o,d,a,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0,medianIdf:c,magnitudeA:l,magnitudeB:m});p&&u.push(p)}return u.sort((d,m)=>m.similarity-d.similarity),u}function X1(e,t){let n=new Map(t.docFreq);for(let r of e.callees)n.set(r,(n.get(r)??0)+1);return ym(n,t.corpus.length+1)}function Wx(e,t,n,r){let i=Z1(e,t,n,r);if(!eH(i,r))return null;let{similarity:o,significantShared:s,trivialShared:a}=i,c=s.length>0?s:a,l=Qx(c,"callees");return{symbolA:e.symbol,shortNameA:T(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:T(t.symbol),fileB:t.file,similarity:o,similarityBasis:"callees",sharedCallees:c.map(T),uniqueToA:[...We(e.callees,t.callees)].map(T),uniqueToB:[...We(t.callees,e.callees)].map(T),...l}}function Q1(e,t,n,r){let i=r.magnitudeA??qi(e.callees,n),o=r.magnitudeB??qi(t.callees,n),s=0,a=0,c=0,l=r.medianIdf??Ui(n);for(let m of e.callees){if(!t.callees.has(m))continue;let p=n.get(m)??0;s+=p*p,c+=1,p>=l&&(a+=1)}if(c===0)return!1;let u=i*o;return(u>0?s/u:0)<r.minSimilarity?!1:a>=r.requireSignificantShared||c>=r.requireSharedCount}function Z1(e,t,n,r){return r.magnitudeA===void 0||r.magnitudeB===void 0?Hx(e.callees,t.callees,n,{medianIdf:r.medianIdf}):Ux(e.callees,t.callees,n,{medianIdf:r.medianIdf,magnitudeA:r.magnitudeA,magnitudeB:r.magnitudeB})}function eH(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 cs(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=t.semantic!==!1,l=be(),u=0,d=0,m=0,p=0,f=0,g=0,h=0;return N("similar.all",()=>{let S=Gi(e).calleeIndex({minCallees:o,scope:i,scanLimit:a,semantic:c}),y=S.corpus;u=y.length;let x=t.focusFiles,v=[],C=0;return N("similar.all.pair-scan",()=>{for(let R=0;R<y.length;R+=1){let E=y[R],I=x?.has(E.file)??!1,w=S.weightedMagnitudes[R],A=new Set;for(let D of E.callees){let k=S.candidateIndexesByCallee.get(D);if(k)for(let L of k)L<=R||x&&!I&&!x.has(y[L].file)||A.add(L)}l&&(m+=A.size,A.size>0&&(d+=1));for(let D of A){let k=y[D];if(s&&E.file===k.file){l&&(f+=1);continue}if(Vx(E,k)){l&&(g+=1);continue}l&&(p+=1);let L=Wx(E,k,S.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:S.medianIdf,magnitudeA:w,magnitudeB:S.weightedMagnitudes[D]});L&&(tH(v,L,r,C),l&&(h+=1),C+=1)}}},()=>({corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:p,crossFileSkips:f,signatureSkips:g,insertedResults:h,topResults:v.length})),N("similar.all.sort-project",()=>(v.sort((R,E)=>E.result.similarity-R.result.similarity||R.order-E.order),v.map(R=>R.result)),()=>({topResults:v.length}))},()=>({minSimilarity:n,limit:r,scope:i,minCallees:o,crossFileOnly:s,scanLimit:a,semantic:c,corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:p,crossFileSkips:f,signatureSkips:g,insertedResults:h}))}function xm(e,t={}){let{minSimilarity:n=.5,scope:r,minCallees:i=4,crossFileOnly:o=!1,scanLimit:s}=t,a=t.semantic!==!1,c=be(),l=0,u=0,d=0,m=0,p=0,f=0,g=0;return N("similar.all-count",()=>{let b=Gi(e).calleeIndex({minCallees:i,scope:r,scanLimit:s,semantic:a}),S=b.corpus;l=S.length;let y=t.focusFiles;return N("similar.all-count.pair-scan",()=>{for(let x=0;x<S.length;x+=1){let v=S[x],C=y?.has(v.file)??!1,R=b.weightedMagnitudes[x],E=new Set;for(let I of v.callees){let w=b.candidateIndexesByCallee.get(I);if(w)for(let A of w)A<=x||y&&!C&&!y.has(S[A].file)||E.add(A)}c&&(d+=E.size,E.size>0&&(u+=1));for(let I of E){let w=S[I];if(o&&v.file===w.file){c&&(p+=1);continue}if(Vx(v,w)){c&&(f+=1);continue}c&&(m+=1),Q1(v,w,b.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:b.medianIdf,magnitudeA:R,magnitudeB:b.weightedMagnitudes[I]})&&(g+=1)}}},()=>({corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:p,signatureSkips:f,insertedResults:g})),g},()=>({minSimilarity:n,scope:r,minCallees:i,crossFileOnly:o,scanLimit:s,semantic:a,corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:p,signatureSkips:f,insertedResults:g}))}function Vx(e,t){if(e.paramCount<0||t.paramCount<0)return!1;let n=Math.abs(e.paramCount-t.paramCount),r=Math.max(2,Math.ceil(Math.max(e.paramCount,t.paramCount)*.5));return n>r}var Yx=mt({kind:"source-fingerprints",invalidation:Te("source-fingerprints"),serialize:TH,deserialize:MH});function tH(e,t,n,r){if(n<=0)return;if(e.length<n){e.push({result:t,order:r});return}let i=0;for(let s=1;s<e.length;s+=1){let a=e[s],c=e[i];(a.result.similarity<c.result.similarity||a.result.similarity===c.result.similarity&&a.order>c.order)&&(i=s)}let o=e[i];t.similarity<=o.result.similarity||(e[i]={result:t,order:r})}var nH=["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 rH(e,t,n){let r=ne(e,t);if(!r||!Se(r.symbol))return null;let i=new H(e),o=Dt(e,r,{semantic:n.semantic,semanticEvidence:re});return{symbol:r.symbol,file:r.relativePath,callees:Nc(o.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}var iH=me("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),oH=me("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function Jx(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:o}=t,s=t.semantic!==!1,a=iH.get(e,()=>new Map),c=`${n}|${r??""}|${o??""}|${s}`,l=!0,u=0,d=0;return N("similar.callee-fingerprints.resolve",()=>{let m=a.get(c);if(l=m!==void 0,m||(m=lH(e,{minCallees:n,scope:r,scanLimit:o,semantic:s}),a.set(c,m)),u=m.length,i===void 0)return m;let p=m.filter(f=>f.symbol!==i);return d=m.length-p.length,p},()=>({minCallees:n,scope:r,scanLimit:o,semantic:s,cacheHit:l,corpusSize:u,excludeSymbol:i!==void 0,excludedSymbols:d}))}function sH(e,t){let{minCallees:n,scope:r,scanLimit:i}=t,o=t.semantic!==!1,s=oH.get(e,()=>new Map),a=`${n}|${r??""}|${i??""}|${o}`,c=!0,l=0,u=0,d=0;return N("similar.callee-index.resolve",()=>{let m=s.get(a);return c=m!==void 0,m||(m=aH(Jx(e,{minCallees:n,scope:r,scanLimit:i,semantic:o})),s.set(a,m)),l=m.corpus.length,u=m.docFreq.size,d=m.candidateIndexesByCallee.size,m},()=>({minCallees:n,scope:r,scanLimit:i,semantic:o,cacheHit:c,corpusSize:l,indexedCallees:u,candidateBuckets:d}))}function Gi(e){return{calleeCorpus:t=>Jx(e,t),calleeIndex:t=>sH(e,t),sourceCorpus:(t={})=>rR(e,t),sourceIndex:(t={})=>Kx(e,t),sourceCandidates:(t,n)=>(n.candidateMode??"full")==="target-pruned"?xH(e,t,{minSimilarity:n.minSimilarity,scanLimit:n.scanLimit}):CH(t,Kx(e,{scanLimit:n.scanLimit}))}}function aH(e){let t=be(),n=0,r=N("similar.callee-index.doc-frequency",()=>{let m=new Map;for(let p of e)for(let f of p.callees)m.set(f,(m.get(f)??0)+1);return n=m.size,m},()=>({corpusSize:e.length,uniqueCallees:n})),i=Math.max(8,Math.ceil(Math.sqrt(e.length))),o=N("similar.callee-index.idf-weights",()=>ym(r,e.length),()=>({corpusSize:e.length,uniqueCallees:r.size})),s=N("similar.callee-index.weighted-magnitudes",()=>e.map(m=>qi(m.callees,o)),()=>({corpusSize:e.length})),a=0,c=0,l=0,u=N("similar.callee-index.candidate-buckets",()=>{let m=new Map;for(let p=0;p<e.length;p+=1){let f=e[p];for(let g of f.callees){if((r.get(g)??0)>i){t&&(c+=1);continue}let h=m.get(g);h||(h=[],m.set(g,h)),h.push(p),t&&(a+=1)}}return t&&(l=m.size),m},()=>({corpusSize:e.length,buckets:l,candidateRefs:a,ubiquitousSkips:c,ubiquityThreshold:i})),d=N("similar.callee-index.median-idf",()=>Ui(o),()=>({uniqueCallees:o.size}));return{corpus:e,candidateIndexesByCallee:u,docFreq:r,idfWeights:o,weightedMagnitudes:s,medianIdf:d,ubiquityThreshold:i}}function cH(e,t){let n=new Map;for(let r of e.callees)for(let i of t.candidateIndexesByCallee.get(r)??[]){let o=t.corpus[i];o.symbol!==e.symbol&&n.set(o.symbol,o)}return n.size>0?[...n.values()]:t.corpus.filter(r=>r.symbol!==e.symbol)}function lH(e,t){let{minCallees:n,scope:r,scanLimit:i,semantic:o}=t,s=be(),a=new H(e),c=0,l=N("similar.callee-fingerprints.candidates",()=>{let g=he(a.productionCallableDefinitions({scope:r,minLoc:5,sortByLocDesc:typeof i=="number"&&i>0}),i);return c=g.length,g},()=>({scope:r,scanLimit:i,candidateCount:c})),u=0,d=N("similar.callee-fingerprints.callee-map",()=>{let g=a.calleeMap(l,{semantic:o});if(s)for(let h of g.values())u+=h.length;return g},()=>({candidateCount:c,semantic:o,calleeEdges:u})),m=0,p=0,f=0;return N("similar.callee-fingerprints.shape",()=>{let g=l.map(S=>({symbol:S.symbol,file:S.relativePath,callees:Nc((d.get(S.symbolId)??[]).map(y=>y.symbol)),paramCount:a.callableSignature(S)?.paramCount??-1})),h=uH(g);s&&(f=h.filter((S,y)=>S.callees.size!==g[y].callees.size).length);let b=h.filter(S=>S.callees.size>=n);return m=b.length,s&&(p=b.reduce((S,y)=>S+y.callees.size,0)),b},()=>({candidateCount:c,fingerprintCount:m,retainedCalleeCount:p,minCallees:n,siblingSaturatedFingerprints:f}))}var Xx=5;function uH(e){let t=new Map;for(let n of e){let r=t.get(n.file);r||(r=new Map,t.set(n.file,r));for(let i of n.callees)r.set(i,(r.get(i)??0)+1)}return e.map(n=>{let r=t.get(n.file);if(!r)return n;let i=[...n.callees].filter(s=>(r.get(s)??0)>=Xx);if(i.length===0)return n;let o=new Set(n.callees);for(let s of i)o.delete(s);return{...n,callees:o}})}function dH(e,t){let n=new Map;for(let o of t)if(!(o.file!==e.file||o.symbol===e.symbol))for(let s of o.callees)n.set(s,(n.get(s)??0)+1);let r=[...e.callees].filter(o=>(n.get(o)??0)+1>=Xx);if(r.length===0)return e;let i=new Set(e.callees);for(let o of r)i.delete(o);return{...e,callees:i}}function Nc(e){return new Set([...e].filter(t=>!mH(t)))}function mH(e){return nH.some(t=>e.includes(t))}function qx(e,t,n){let r=hH(e,t);if(!r||r.tokens.size<3)return[];let i=n.minSimilarity>=.5?n.minSimilarity:.3,o=[],s=n.candidateMode??"full",a=0,c=0,l=0,u=0;return N("similar.source-shape",()=>{let m=Gi(e).sourceCandidates(r,{minSimilarity:i,scanLimit:n.scanLimit,candidateMode:s});a=m.length;for(let p of m){if(p.symbol===r.symbol||p.tokens.size<3)continue;c+=1;let f=Ft(r.tokens,p.tokens);if(f.size<2){l+=1;continue}let g=new Set([...r.tokens,...p.tokens]),h=g.size>0?f.size/g.size:0;if(h<i){u+=1;continue}o.push({symbolA:r.symbol,shortNameA:T(r.symbol),fileA:r.file,symbolB:p.symbol,shortNameB:T(p.symbol),fileB:p.file,similarity:h,similarityBasis:"source-tokens",sharedCallees:[...f].sort(),uniqueToA:[...We(r.tokens,p.tokens)].sort(),uniqueToB:[...We(p.tokens,r.tokens)].sort(),...Qx([...f],"source-tokens")})}return o.sort((p,f)=>f.similarity-p.similarity||p.shortNameB.localeCompare(f.shortNameB)),o.slice(0,n.limit)},()=>({symbol:r.symbol,file:r.file,targetTokens:r.tokens.size,candidateMode:s,candidates:a,comparedPairs:c,sharedSkips:l,similaritySkips:u,results:o.length}))}function Qx(e,t){let n=e.flatMap(Sm),r=e.flatMap(h=>Gx(h,t)),i=bm(n,Zx),o=bm(n,eR),s=bm(r,vm),a=[...new Set(r.filter(zx))],c=e.filter(h=>{let b=Gx(h,t);return b.some(S=>vm.has(S))&&b.some(zx)}).length,l=[];i.length>0&&l.push(`access/query scaffolding: ${i.slice(0,5).join(", ")}`),o.length>0&&l.push(`framework/generic scaffolding: ${o.slice(0,5).join(", ")}`),s.length>0&&l.push(`domain behavior verbs: ${s.slice(0,5).join(", ")}`),s.length>0&&a.length>0&&l.push(`domain-specific terms: ${a.slice(0,5).join(", ")}`);let u=t==="source-tokens"&&n.length>0&&n.every(h=>tR.has(h));u&&l.push("shared source tokens are generic scaffolding");let d=s.length>0&&a.length>0,m=i.length+o.length>0,p=t==="callees"&&d&&e.length>=4&&a.length>=4&&c>=2,f=p?"domain-behavior":d?m?"mixed":"domain-behavior":i.length>0?"access-query-scaffolding":o.length>0||u?"framework-scaffolding":"structural-overlap";f==="structural-overlap"&&e.length>0&&l.push(`shared ${t} overlap has no recognized domain or scaffolding category`);let g=f==="domain-behavior"&&(e.length>=3||p)?"direct":"signal";return{evidenceClass:f,actionTier:g,evidenceClassReasons:l,recommendation:pH(f,g)}}function pH(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 bm(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function Sm(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function Gx(e,t){if(t==="source-tokens")return Sm(e);let n=z(e);return Sm(n.length>0?n:fH(e))}function fH(e){return e.replace(/[()`]/g," ").replace(/\.[a-z][a-z0-9]+(?=\s|$)/gi," ").split(/[:/\\\s]+/).map(r=>r.trim()).filter(r=>/[A-Za-z]/.test(r)).at(-1)?.replace(/\.$/,"")??e}function zx(e){return e.length>3&&!vm.has(e)&&!Zx.has(e)&&!eR.has(e)&&!tR.has(e)&&!gH.has(e)}var vm=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),Zx=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),eR=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"]),tR=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),gH=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 hH(e,t){let n=ne(e,t);if(!n||!Se(n.symbol))return null;let r=yH(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function yH(e,t){let n=z(t.symbol),r=LH(e,t.relativePath,t.startLine,t.endLine,n),i=sR(r,n);return i.size>0?i:null}var bH=me("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),SH=me("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function nR(e){return`${e.scanLimit??""}`}function rR(e,t={}){let n=bH.get(e,()=>new Map),r=nR(t),i=n.get(r);return i||(i=wH(e,t),n.set(r,i)),i}function Kx(e,t={}){let n=SH.get(e,()=>new Map),r=nR(t),i=n.get(r);return i||(i=vH(rR(e,t)),n.set(r,i)),i}function vH(e){let t=new Map;for(let i of e)for(let o of i.tokens)t.set(o,(t.get(o)??0)+1);let n=Math.max(8,Math.ceil(Math.sqrt(e.length))),r=new Map;for(let i of e)for(let o of i.tokens){if((t.get(o)??0)>n)continue;let s=r.get(o);s||(s=[],r.set(o,s)),s.push(i)}return{corpus:e,candidateByToken:r,docFreq:t,ubiquityThreshold:n}}function CH(e,t){let n=new Map;for(let r of e.tokens)for(let i of t.candidateByToken.get(r)??[])i.symbol!==e.symbol&&n.set(i.symbol,i);return n.size>0?[...n.values()]:t.corpus.filter(r=>r.symbol!==e.symbol)}function xH(e,t,n){let r=be(),i=new H(e),o=RH(t.tokens.size,n.minSimilarity),s=0,a=0,c=0,l=N("similar.source-shape.target-files",()=>{let f=[...t.tokens],g=[];for(let h of Q(e,{includeIgnored:!1})){s+=1;let b=W(e,h);b&&(a+=1,EH(b,f,o)&&g.push(h))}return c=g.length,g},()=>({symbol:t.symbol,targetTokens:t.tokens.size,requiredSharedTokens:o,scannedFiles:s,readableFiles:a,candidateFiles:c})),u=0,d=N("similar.source-shape.target-definitions",()=>{let f=he(i.productionCallableDefinitions({files:l,sortByLocDesc:typeof n.scanLimit=="number"&&n.scanLimit>0}),n.scanLimit);return u=f.length,f},()=>({symbol:t.symbol,candidateFiles:c,scanLimit:n.scanLimit,definitionCount:u})),m=0;return N("similar.source-shape.target-fingerprints",()=>{let f=iR(e,d);return r&&(m=f.length),f},()=>({symbol:t.symbol,definitionCount:u,fingerprintCount:m})).filter(f=>f.symbol!==t.symbol)}function RH(e,t){return Math.max(2,Math.ceil(e*t))}function EH(e,t,n){if(t.length<n)return!1;let r=e.toLowerCase(),i=0;for(let o of t)if(IH(r,o)&&(i+=1,i>=n))return!0;return!1}function IH(e,t){return t==="num"?/\b\d+\b/.test(e):e.includes(t)}function wH(e,t={}){let n=new H(e),{scanLimit:r}=t,i=he(n.productionCallableDefinitions({sortByLocDesc:typeof r=="number"&&r>0}),r);return iR(e,i)}function iR(e,t){let n=new Map;for(let i of t){let o=n.get(i.relativePath)??[];o.push(i),n.set(i.relativePath,o)}let r=new Map;for(let[i,o]of n){let s=W(e,i);if(!s)continue;let a=Et(e,i,s),c=DH(e,i,a),l=!1,u=null;for(let d of o){let m=PH(d),p=c.get(m),f=p?new Set(p.tokens):null;f||(u??=V(e,i),f=sR(oR(u,d.startLine,d.endLine,d.leaf),d.leaf),c.set(m,{key:m,symbol:d.symbol,startLine:d.startLine,endLine:d.endLine,leaf:d.leaf,tokens:[...f].sort()}),l=!0),f.size>0&&r.set(d.symbol,{symbol:d.symbol,file:d.relativePath,tokens:f})}l&&AH(e,i,a,c)}return t.map(i=>r.get(i.symbol)).filter(i=>!!i)}function LH(e,t,n,r,i){let o=V(e,t);return o.length===0?"":oR(o,n,r,i)}function oR(e,t,n,r){if(n>=t&&n-t<=12)return e.slice(t,n+1).join(`
320
- `);let i=[new RegExp(`\\bdef\\s+${xe(r)}\\b`),new RegExp(`\\bfun\\s+${xe(r)}\\b`),new RegExp(`\\bfn\\s+${xe(r)}\\b`),new RegExp(`\\bfunction\\s+${xe(r)}\\b`),new RegExp(`\\b${xe(r)}\\s*\\(`)],o=e.findIndex(s=>i.some(a=>a.test(s)));if(o>=0){let s=o;for(let a=o+1;a<e.length&&a<=o+8;a++){let c=e[a]??"";if(a>o&&kH(c)||(s=a,c.trim()===""&&a>o+1))break}return e.slice(o,s+1).join(`
321
- `)}return e.slice(t,Math.min(e.length,t+8)).join(`
322
- `)}function PH(e){return`${e.symbol}\0${e.startLine}\0${e.endLine}\0${e.leaf}`}function DH(e,t,n){return Yx.read(e,t,n)??new Map}function MH(e){try{let t=JSON.parse(e);if(!Array.isArray(t.entries))return null;let n=new Map;for(let r of t.entries){if(!r||typeof r.key!="string"||typeof r.symbol!="string"||typeof r.startLine!="number"||typeof r.endLine!="number"||typeof r.leaf!="string"||!Array.isArray(r.tokens)||!r.tokens.every(i=>typeof i=="string"))return null;n.set(r.key,r)}return n}catch{return null}}function TH(e){let t={entries:[...e.values()].sort((n,r)=>n.key.localeCompare(r.key))};return JSON.stringify(t)}function AH(e,t,n,r){Yx.write(e,t,n,new Map(r))}function sR(e,t){if(!e)return new Set;let n=new Set(["public","private","protected","final","static","class","def","fun","fn","function","return","string","bool","boolean","void","unit","self","this","new","const","let","var","end","pub"]),r=FH(t),o=e.replace(/["'`]/g," ").replace(/\b\d+\b/g," NUM ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[^A-Za-z0-9_]+/g," ").replace(/_/g," ").toLowerCase().split(/\s+/).map(s=>s.trim()).filter(s=>s.length>1).filter(s=>!n.has(s)).filter(s=>!r.has(s));return new Set(o)}function FH(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 kH(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function sn(e,t){let n=new Map;return e.forEach((r,i)=>{let o=new Set;for(let s of t(r)){if(o.has(s))continue;o.add(s);let a=n.get(s);a?a.push(i):n.set(s,[i])}}),{candidatesFor:(r,i)=>{let o=new Set;for(let s of t(r)){let a=n.get(s);if(a)for(let c of a)c!==i&&o.add(c)}return[...o].sort((s,a)=>s-a)}}}function an(e){let t=aR(e.profile?.name),n=()=>{let r=[];t=aR(e.profile?.name,e);let i=(s,a)=>{let c=e.profiles[s],l=e.profiles[a];t.candidatePairs+=1,t.comparedPairs+=1;let u=e.compare(c,l);u&&r.push(u)};if(e.filePattern){let s=e.profiles.findIndex(a=>a.file.includes(e.filePattern));if(s>=0){let a=e.profiles[s];for(let c of NH(e,s)){let l=e.profiles[c];e.focusFiles&&!e.focusFiles.has(a.file)&&!e.focusFiles.has(l.file)||i(s,c)}}}else if(e.focusFiles?.size!==0){let s=typeof e.overrunFactor=="number"&&Number.isFinite(e.limit)?e.limit*e.overrunFactor:Number.POSITIVE_INFINITY;for(let a=0;a<e.profiles.length;a+=1){let c=e.profiles[a],l=e.focusFiles?.has(c.file)??!1;for(let u of _H(e,a))e.focusFiles&&!l&&!e.focusFiles.has(e.profiles[u].file)||i(a,u);if(r.length>s){t.overrunApplied=!0;break}}}r.sort(e.sort??((s,a)=>a.similarity-s.similarity)),t.matchedResults=r.length;let o=r.slice(0,e.limit);return t.emittedResults=o.length,e.onProfile?.({...t}),o};return e.profile?N(`pairwise-profile:${e.profile.name}`,n,()=>({...OH(e.profile?.metadata),...t})):n()}function NH(e,t){if(e.candidateIndex)return cR(e,t,-1);let n=[];for(let r=0;r<e.profiles.length;r+=1)r!==t&&n.push(r);return n}function _H(e,t){if(e.candidateIndex)return cR(e,t,t);let n=[];for(let r=t+1;r<e.profiles.length;r+=1)n.push(r);return n}function cR(e,t,n){let r=e.profiles[t],i=new Set;for(let o of e.candidateIndex?.candidatesFor(r,t,e.profiles)??[])o<=n||o!==t&&(o<0||o>=e.profiles.length||i.add(o));return[...i].sort((o,s)=>o-s)}function aR(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 OH(e){return typeof e=="function"?e():e??{}}function BH(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=$H(e,{scope:i,minDeps:s}),l=sn(a,u=>u.deps);return an({profiles:a,limit:r,filePattern:o,overrunFactor:5,candidateIndex:l,profile:{name:"similar-files"},compare:(u,d)=>HH(u,d,n,c)})}function $H(e,t){let{scope:n,minDeps:r}=t,i=Ae(e,n),{universalDeps:o,distinctiveDeps:s}=jH(i),a=[];for(let[c,l]of i)l.size>=r&&a.push({file:c,deps:new Set([...l].filter(u=>!o.has(u)))});return{profiles:a,distinctiveDeps:s}}function jH(e){let t=new Set,n=new Set,r=e.size;if(r===0)return{universalDeps:t,distinctiveDeps:n};let i=new Map;for(let s of e.values())for(let a of s)i.set(a,(i.get(a)??0)+1);let o=Math.max(3,Math.ceil(r*.03));for(let[s,a]of i)a>=5&&a/r>.3?t.add(s):a<=o&&n.add(s);return{universalDeps:t,distinctiveDeps:n}}function HH(e,t,n,r){let i=new Set;for(let l of e.deps)t.deps.has(l)&&i.add(l);if(i.size<3||e.deps.size<4||t.deps.size<4)return null;let o=0;for(let l of i)r.has(l)&&o++;if(o<2)return null;let s=dr(e.deps,t.deps);if(s<n)return null;let a=[];for(let l of e.deps)t.deps.has(l)||a.push(l);let c=[];for(let l of t.deps)e.deps.has(l)||c.push(l);return{fileA:e.file,fileB:t.file,similarity:s,sharedDeps:[...i],uniqueToA:a,uniqueToB:c}}function mr(e){let t=[],n=[],r=[];for(let l of e.primitiveGroups)l.values.length!==0&&lR(l.bucket,n,r).push(`${l.reasonPrefix}: ${l.values.join(", ")}`);for(let l of e.nameGroups)UH(l.names,l.label,e.genericWords,e.stripPrefixes??[],t,lR(l.fallbackBucket,n,r));let i=t.length>0,o=n.length>0,s=r.length>0,a=i?o||s?"mixed":"domain-behavior":s?"shared-abstraction":"generic-workflow-scaffolding";return{actionTier:a==="domain-behavior"||a==="mixed"?"signal":"support",evidenceClass:a,reasons:[...t,...r,...n].slice(0,6),recommendation:e.recommendation(a)}}function _c(e,t){if(e.size===0||t.size===0)return 0;let i=Ft(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(dr(e,t),i)}function pr(e,t){let n=Object.fromEntries(e.map(r=>[r.name,r.count]));for(let r of t)if(Object.entries(r.min).every(([o,s])=>(n[o]??0)>=s))return{pass:!0,reason:r.reason,counts:n};return{pass:!1,reason:"shared tokens did not meet calibrated overlap thresholds",counts:n}}function Oc(e,t,n){let r=t.map(c=>{let l=c.value(e),u=c.weightedValue?c.weightedValue(e,l):l;return{axis:c,value:l,weighted:u,qualifies:c.qualifies?c.qualifies(e,l):l>0}}),i=r.filter(c=>c.qualifies&&c.axis.reason).map(c=>c.axis.reason(e,c.value)),o=r.filter(c=>c.qualifies&&c.axis.dominantEligible!==!1).sort((c,l)=>l.weighted-c.weighted)[0],s=o&&o.weighted>0?o.axis.axis:n,a=[...new Set(r.filter(c=>c.qualifies).map(c=>c.axis.axis).concat(i.length>0?[]:[s]))];return{dominantPressure:s,pressureKinds:a,reasons:i}}function de(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function et(e){return[...e].sort()}function UH(e,t,n,r,i,o){let s=[],a=[];for(let c of e)qH(c,r).filter(u=>!n.has(u)).length>0?s.push(c):a.push(c);s.length&&i.push(`${t} has domain term(s): ${s.slice(0,6).join(", ")}`),a.length&&o.push(`${t} is generic workflow: ${a.slice(0,6).join(", ")}`)}function qH(e,t){let n=e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2");for(let r of t)n=n.replace(r,"");return n.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function lR(e,t,n){return e==="generic"?t:n}function ls(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=wt(e).reactProfiles({scope:o,minJsxTokens:r,scanLimit:s}).filter(d=>d.kind==="component").map(d=>({file:d.file,component:d.name,tokens:d.jsxTokens,profile:d})),u=sn(l,d=>d.tokens);return an({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-component-duplicates"},compare:(d,m)=>GH(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 GH(e,t,n){let r=Ft(e.tokens,t.tokens);if(r.size<6||!zH(r))return null;let i=dr(e.tokens,t.tokens);if(i<n)return null;let o=de(r,"component:"),s=de(r,"native:"),a=de(r,"prop:"),c=de(r,"event:"),l=de(r,"binding:"),u=KH({sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:c,sharedBindings:l});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:i,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:et(r),sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:c,sharedBindings:l,evidenceClass:u.evidenceClass,actionTier:u.actionTier,evidenceClassReasons:u.reasons,recommendation:u.recommendation,uniqueToA:et(We(e.tokens,t.tokens)).slice(0,25),uniqueToB:et(We(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function zH(e){let t=0,n=0;for(let r of e)r.startsWith("component:")&&(t+=1),(r.startsWith("prop:")||r.startsWith("event:")||r.startsWith("native:")||r.startsWith("jsx:"))&&(n+=1);return pr([{name:"component",count:t},{name:"shape",count:n}],[{min:{component:1},reason:"shared custom component"},{min:{shape:4},reason:"shared JSX structure"}]).pass}function KH(e){return mr({genericWords:VH,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:WH})}function WH(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 VH=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 us(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=wt(e).reactProfiles({scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(d=>({file:d.file,component:d.name,tokens:d.behaviorTokens,profile:d})),u=sn(l,d=>d.tokens);return an({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-hook-candidates"},compare:(d,m)=>YH(d,m,n,r),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.componentA.localeCompare(m.componentA)||d.fileB.localeCompare(m.fileB)||d.componentB.localeCompare(m.componentB)})}function YH(e,t,n,r){let i=Ft(e.tokens,t.tokens);if(i.size<r||!QH(i))return null;let o=_c(e.tokens,t.tokens);if(o<n)return null;let s=de(i,"hook:"),a=de(i,"react-hook:"),c=de(i,"effect:"),l=de(i,"state:"),u=de(i,"request:"),d=de(i,"handler:"),m=de(i,"handler-verb:"),p=JH({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:o,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:et(i),sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m,evidenceClass:p.evidenceClass,actionTier:p.actionTier,evidenceClassReasons:p.reasons,recommendation:p.recommendation,uniqueToA:et(We(e.tokens,t.tokens)).slice(0,25),uniqueToB:et(We(t.tokens,e.tokens)).slice(0,25),reason:ZH({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m}),locA:e.profile.loc,locB:t.profile.loc}}function JH(e){return mr({genericWords:eU,stripPrefixes:tU,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:XH})}function XH(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 QH(e){let t=0,n=0,r=0,i=0,o=0,s=0,a=0;for(let u of e)u.startsWith("hook:")?t+=1:u.startsWith("react-hook:")?n+=1:u.startsWith("effect:")?r+=1:u.startsWith("request:")?i+=1:u.startsWith("handler:")||u.startsWith("handler-verb:")?o+=1:u.startsWith("state:")?s+=1:u.startsWith("state-hook:")&&(a+=1);let c=s+a,l=t+n+r+i+o+c;return pr([{name:"requests",count:i},{name:"customHooks",count:t},{name:"namedStates",count:s},{name:"handlers",count:o},{name:"effects",count:r},{name:"reactHooks",count:n},{name:"namedBehavior",count:l}],[{min:{requests:1,namedBehavior:4},reason:"shared request workflow"},{min:{customHooks:1,requests:1,namedBehavior:5},reason:"shared custom hook and request workflow"},{min:{customHooks:1,namedStates:1,namedBehavior:5},reason:"shared custom hook and state"},{min:{customHooks:1,handlers:2,namedBehavior:5},reason:"shared custom hook and handlers"},{min:{namedStates:1,handlers:2,effects:1,namedBehavior:5},reason:"shared stateful effects"},{min:{namedStates:1,handlers:2,reactHooks:2,namedBehavior:5},reason:"shared stateful React primitives"}]).pass}function ZH(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 eU=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"]),tU=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function Rm(e,t={}){let{minComponentLines:n=300,minFileLines:r=800,minJsxTokens:i=80,minBehaviorTokens:o=40,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return wt(e).reactProfiles({scope:a,scanLimit:c}).filter(d=>d.kind==="component").filter(d=>!l||d.file.includes(l)||d.name.includes(l)).map(d=>nU(d,{minComponentLines:n,minFileLines:r,minJsxTokens:i,minBehaviorTokens:o})).filter(d=>d!==null).sort((d,m)=>m.componentLines-d.componentLines||m.fileLines-d.fileLines||d.file.localeCompare(m.file)).slice(0,s)}function nU(e,t){let n=Math.max(80,Math.floor(t.minComponentLines/2)),r=Oc(e,rU({minComponentLines:t.minComponentLines,minFileLines:t.minFileLines,minJsxTokens:t.minJsxTokens,minBehaviorTokens:t.minBehaviorTokens,substantialComponentLines:n}),"component"),{reasons:i}=r;if(i.length===0)return null;let o=r.dominantPressure,s=r.pressureKinds,a=iU(e),c=oU(o,s,a);return{file:e.file,component:e.name,componentLines:e.loc,fileLines:e.fileLines,jsxTokens:e.jsxTokens.size,behaviorTokens:e.behaviorTokens.size,dominantPressure:o,pressureKinds:s,contextKind:a,recommendationKind:c,recommendation:sU(c,a),reasons:i,loc:e.loc}}function rU(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 iU(e){let t=e.file.split(/[\\/]+/).filter(Boolean),n=t.slice(0,-1).map(m=>m.toLowerCase()),r=(t.at(-1)??e.name).replace(/\.[^.]+$/,""),o=n.findIndex(m=>cU.has(m))>=0,s=n.some(m=>aU.has(m));if(uR(r)||uR(e.name))return"component";let c=lU.has(r.toLowerCase()),l=/(?:Page|Route|Screen)$/.test(e.name),u=o&&/View$/.test(e.name),d=!s&&r.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()===e.name.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()&&/(?:Page|Route|Screen|View)$/.test(r);return c||l||u||d?"route-page":"component"}function uR(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&dR.has(t.at(-1))?!0:[...dR].some(n=>e.endsWith(uU(n)))}function oU(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 sU(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 aU=new Set(["component","components","panel","panels","partial","partials"]),dR=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"]),cU=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),lU=new Set(["page","route","screen"]);function uU(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ds(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=dU(e,{scope:o,minTokens:r,scanLimit:s}),u=sn(l,d=>d.tokens);return an({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-component-duplicates"},compare:(d,m)=>pU(d,m,n),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function dU(e,t){return wt(e).vueProfiles({scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:mU(n)}))}function mU(e){return e.totalLines}function pU(e,t,n){let r=Ft(e.tokens,t.tokens);if(r.size<6||!fU(r))return null;let i=dr(e.tokens,t.tokens);if(i<n)return null;let o=de(r,"component:"),s=de(r,"prop:"),a=de(r,"event:"),c=de(r,"directive:"),l=de(r,"slot:"),u=de(r,"id:"),d=gU({sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:c,sharedSlots:l,sharedIdentifiers:u});return{fileA:e.file,fileB:t.file,similarity:i,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:et(r),sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:c,sharedSlots:l,sharedIdentifiers:u,evidenceClass:d.evidenceClass,actionTier:d.actionTier,evidenceClassReasons:d.reasons,recommendation:d.recommendation,uniqueToA:et(We(e.tokens,t.tokens)).slice(0,25),uniqueToB:et(We(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function fU(e){let t=0,n=0;for(let r of e)r.startsWith("component:")&&(t+=1),(r.startsWith("prop:")||r.startsWith("event:")||r.startsWith("directive:")||r.startsWith("slot:"))&&(n+=1);return pr([{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 gU(e){return mr({genericWords:yU,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:hU})}function hU(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 yU=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 ms(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=wt(e).vueProfiles({scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(d=>({file:d.file,tokens:d.behaviorTokens,profile:d})),u=sn(l,d=>d.tokens);return an({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-composable-candidates"},compare:(d,m)=>bU(d,m,n,r),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function bU(e,t,n,r){let i=Ft(e.tokens,t.tokens);if(i.size<r||!CU(i))return null;let o=_c(e.tokens,t.tokens);if(o<n)return null;let s=de(i,"composable:"),a=de(i,"store:"),c=de(i,"reactivity:"),l=de(i,"lifecycle:"),u=de(i,"request:"),d=de(i,"function:"),m=de(i,"function-verb:"),p=de(i,"template-binding:"),f=de(i,"template-event:"),g=SU({sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p,sharedTemplateEvents:f});return{fileA:e.file,fileB:t.file,similarity:o,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:et(i),sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p,sharedTemplateEvents:f,evidenceClass:g.evidenceClass,actionTier:g.actionTier,evidenceClassReasons:g.reasons,recommendation:g.recommendation,uniqueToA:et(We(e.tokens,t.tokens)).slice(0,25),uniqueToB:et(We(t.tokens,e.tokens)).slice(0,25),reason:xU({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:l,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function SU(e){return mr({genericWords:RU,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:vU})}function vU(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 CU(e){let t=0,n=0,r=0,i=0,o=0,s=0,a=0;for(let u of e)u.startsWith("composable:")?t+=1:u.startsWith("store:")?n+=1:u.startsWith("request:")?r+=1:u.startsWith("lifecycle:")?i+=1:u.startsWith("function:")?o+=1:u.startsWith("reactivity:")?s+=1:(u.startsWith("function-verb:")||u.startsWith("template-binding:")||u.startsWith("template-event:"))&&(a+=1);let c=t+n,l=c+r+i+o+a;return pr([{name:"requests",count:r},{name:"lifecycle",count:i},{name:"functions",count:o},{name:"reusableHooks",count:c},{name:"reactivity",count:s},{name:"namedBehavior",count:l}],[{min:{requests:1,namedBehavior:4},reason:"shared request workflow"},{min:{lifecycle:1,functions:2,namedBehavior:4},reason:"shared lifecycle workflow"},{min:{reusableHooks:2,requests:1,namedBehavior:5},reason:"shared reusable Vue hooks and requests"},{min:{reusableHooks:2,functions:2,namedBehavior:5},reason:"shared reusable Vue hooks and functions"},{min:{functions:2,reactivity:1,namedBehavior:4},reason:"shared reactive functions"}]).pass}function xU(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 RU=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 Em(e,t={}){let{minTotalLines:n=800,minTemplateLines:r=300,minScriptLines:i=300,minStyleLines:o=500,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return wt(e).vueProfiles({scope:a,scanLimit:c}).filter(d=>!l||d.file.includes(l)).map(d=>EU(d,{minTotalLines:n,minTemplateLines:r,minScriptLines:i,minStyleLines:o})).filter(d=>d!==null).sort((d,m)=>m.totalLines-d.totalLines||d.file.localeCompare(m.file)).slice(0,s)}function EU(e,t){let n=Oc(e,IU(t),"total"),{reasons:r}=n;if(r.length===0)return null;let i=n.dominantPressure,o=n.pressureKinds.includes("total")?[...new Set([...n.pressureKinds,i])]:n.pressureKinds,s=wU(e.file),a=LU(i,s),c=e.totalLines+e.delegatedComposableLines;return{file:e.file,totalLines:c,sfcLines:e.sfcLines,templateLines:e.templateLines,scriptLines:e.scriptLines,styleLines:e.styleLines,externalScriptLines:e.externalScriptLines,externalScriptPaths:e.externalScriptPaths,customBlockLines:e.customBlockLines,delegatedComposableLines:e.delegatedComposableLines,delegatedComposablePaths:e.delegatedComposablePaths,dominantPressure:i,pressureKinds:o,contextKind:s,recommendationKind:a,recommendation:PU(a,s),reasons:r,loc:c}}function IU(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 wU(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(r=>DU.has(r))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function LU(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 PU(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 DU=new Set(["landing","page","pages","route","routes","view","views"]);function MU(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:o=3,maxChainLength:s=8}=t,a=Ae(e,i),c=BU(a,o,s);if(c.length===0)return[];let l=TU(c);return l.length<2?[]:OU(kU(l,n,r),r)}function TU(e){let t=AU(e),n=[];for(let r of e){let i=r.filter(o=>!t.has(o));i.length>=2&&n.push({original:r,filtered:i})}return n}function AU(e){let{nodeFreq:t,tailFreq:n}=FU(e),r=e.length*.9,i=e.length*.8,o=new Set;for(let[a,c]of t)c>r&&o.add(a);for(let[a,c]of n)c>i&&o.add(a);let s=["index.ts","index.js","cli.ts","main.ts","health.ts","health.js"];for(let a of t.keys()){let c=a.split("/").pop()??"";s.includes(c)&&o.add(a)}return o}function FU(e){let t=new Map,n=new Map;for(let r of e){let i=new Set;for(let o of r)i.has(o)||(t.set(o,(t.get(o)??0)+1),i.add(o));for(let o=Math.max(0,r.length-2);o<r.length;o++)n.set(r[o],(n.get(r[o])??0)+1)}return{nodeFreq:t,tailFreq:n}}function kU(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let o=i+1;o<e.length;o++){let s=NU(e[i],e[o],t);s&&r.push(s)}if(r.length>n*10)break}return r.sort((i,o)=>Math.abs(o.similarity-i.similarity)>.01?o.similarity-i.similarity:i.divergencePoints.length-o.divergencePoints.length),r}function NU(e,t,n){if(!_U(e.filtered,t.filtered))return null;let{distance:r,ops:i}=$U(e.filtered,t.filtered),o=Math.max(e.filtered.length,t.filtered.length);if(o===0)return null;let s=1-r/o;if(s<n||r===0)return null;let a=i.filter(l=>l.type==="substitute").map(l=>({index:l.indexA,nodeA:e.filtered[l.indexA],nodeB:t.filtered[l.indexB]}));return a.length===0||i.filter(l=>l.type==="match").length<2?null:{chainA:e.original,chainB:t.original,similarity:s,editDistance:r,divergencePoints:a,commonPrefix:jU(e.original,t.original),commonSuffix:HU(e.original,t.original)}}function _U(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function OU(e,t){let n=[];for(let r of e)if(n.some(o=>mR(r.chainA,o.chainA)&&mR(r.chainB,o.chainB))||n.push(r),n.length>=t)break;return n}function BU(e,t,n){let r=[];for(let o of e.keys()){if(r.length>=500)break;pR(e,o,[o],new Set([o]),t,n,r,500)}return r}function pR(e,t,n,r,i,o,s,a){if(s.length>=a)return;if(n.length>=o){n.length>=i&&s.push([...n]);return}let c=e.get(t);if(!c||c.size===0){n.length>=i&&s.push([...n]);return}let l=!1;for(let u of c)if(!r.has(u)&&(r.add(u),n.push(u),pR(e,u,n,r,i,o,s,a),n.pop(),r.delete(u),l=!0,s.length>=a))return;!l&&n.length>=i&&s.push([...n])}function $U(e,t){let n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let c=0;c<=n;c++)i[c][0]=c;for(let c=0;c<=r;c++)i[0][c]=c;for(let c=1;c<=n;c++)for(let l=1;l<=r;l++)e[c-1]===t[l-1]?i[c][l]=i[c-1][l-1]:i[c][l]=1+Math.min(i[c-1][l],i[c][l-1],i[c-1][l-1]);let o=[],s=n,a=r;for(;s>0||a>0;)s>0&&a>0&&e[s-1]===t[a-1]?(o.unshift({type:"match",indexA:s-1,indexB:a-1}),s--,a--):s>0&&a>0&&i[s][a]===i[s-1][a-1]+1?(o.unshift({type:"substitute",indexA:s-1,indexB:a-1}),s--,a--):a>0&&i[s][a]===i[s][a-1]+1?(o.unshift({type:"insert",indexA:s,indexB:a-1}),a--):(o.unshift({type:"delete",indexA:s-1,indexB:a}),s--);return{distance:i[n][r],ops:o}}function jU(e,t){let n=[];for(let r=0;r<Math.min(e.length,t.length)&&e[r]===t[r];r++)n.push(e[r]);return n}function HU(e,t){let n=[],r=e.length-1,i=t.length-1;for(;r>=0&&i>=0&&e[r]===t[i];)n.unshift(e[r]),r--,i--;return n}function mR(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),r=e.join("\u2192");return n.includes(r)}function kt(e){let t=UU(e.profile?.name),n=()=>{let r=e.candidates(),i=e.filterCandidate?r.filter(e.filterCandidate):r,o=e.orderCandidates?[...i].sort(e.orderCandidates):i,s=he(o,e.scanLimit);t={pipeline:e.profile?.name,loadedCandidates:r.length,filteredCandidates:i.length,scannedCandidates:s.length,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:s.length<i.length,resultLimitApplied:!1};let a=e.prepare?.(s)??void 0,c=[];for(let u of s){t.evaluatedCandidates+=1;let d=e.evaluate(u,a);d&&c.push(d)}t.matchedResults=c.length,e.orderResults&&c.sort(e.orderResults);let l=typeof e.limit=="number"?c.slice(0,e.limit):c;return t.emittedResults=l.length,t.resultLimitApplied=l.length<c.length,e.onProfile?.({...t}),l};return e.profile?N(`candidate-pipeline:${e.profile.name}`,n,()=>({...qU(e.profile?.metadata),...t})):n()}function UU(e){return{pipeline:e,loadedCandidates:0,filteredCandidates:0,scannedCandidates:0,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:!1,resultLimitApplied:!1}}function qU(e){return typeof e=="function"?e():e??{}}function ps(e,t={}){let{scope:n,minLoc:r=10,minCallees:i=6,limit:o=20,scanLimit:s}=t,a=new H(e);return kt({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:r,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:s,profile:{name:"extract-candidates"},prepare:c=>a.calleeMap(c,{semantic:t.semantic!==!1}),evaluate:(c,l)=>GU(c,l.get(c.symbolId)??[],i),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function GU(e,t,n){let r=new Set(t.map(l=>l.symbol));if(r.size<n)return null;let i=YU(r,t),o=JU(r,i);if(o.length<2)return null;let s=XU(o,i);if(s.length===0)return null;let a=T(e.symbol),c=zU(a,r.size,o.length,s);return{symbol:e.symbol,shortName:a,relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:ee(e),totalCallees:r.size,extractionKind:c.extractionKind,actionTier:"signal",evidenceReasons:c.evidenceReasons,recommendation:c.recommendation,clusters:s}}function zU(e,t,n,r){let i=Math.max(...r.map(c=>c.callees.length)),o=Math.max(...r.map(c=>c.isolation)),s=[`${t} distinct callees across ${n} co-occurrence cluster(s)`,`${r.length} extractable cluster(s) passed size and isolation thresholds`,`largest extractable cluster has ${i} callees at ${Math.round(o*100)}% isolation`],a=KU(e,t,n);return a!==null?{extractionKind:"workflow-orchestration",evidenceReasons:[...s,a],recommendation:"Review the isolated helper group as a possible private or feature-local helper, but keep the orchestration sequence together when it preserves the workflow."}:i>=6?{extractionKind:"broad-helper-cluster",evidenceReasons:[...s,"one isolated helper group is broad enough to deserve a named review"],recommendation:"Review whether the broad helper cluster has a stable concept name before extracting it; avoid creating a bag-of-helpers abstraction."}:{extractionKind:"cohesive-helper-cluster",evidenceReasons:s,recommendation:"Review the isolated callee group as a possible same-file or feature-local helper; extract only if the new name preserves the current behavior."}}function KU(e,t,n){if(t>=10)return`callee breadth suggests orchestration: ${t} callees`;if(n>=4)return`multiple disconnected callee groups suggest orchestration: ${n} groups`;let r=WU(e);return VU.has(r)?`caller verb suggests orchestration: ${r}`:null}function WU(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 VU=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function YU(e,t){let n=new Map;for(let i of e)n.set(i,new Set);let r=new Map;for(let i of t){let o=r.get(i.chunkId);o||(o=new Set,r.set(i.chunkId,o)),o.add(i.symbol)}for(let i of r.values()){let o=[...i];for(let s=0;s<o.length;s++)for(let a=s+1;a<o.length;a++)n.get(o[s]).add(o[a]),n.get(o[a]).add(o[s])}return n}function JU(e,t){let n=new Set,r=[];for(let i of e){if(n.has(i))continue;let o=new Set,s=[i];for(;s.length>0;){let a=s.pop();if(!n.has(a)){n.add(a),o.add(a);for(let c of t.get(a)??[])n.has(c)||s.push(c)}}r.push(o)}return r}function XU(e,t){return e.filter(n=>n.size>=3).map(n=>QU(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function QU(e,t,n){let r=new Set;for(let a of t)if(a!==e)for(let c of a)r.add(c);let i=0;for(let a of e)for(let c of n.get(a)??[])r.has(c)&&i++;let o=e.size*r.size,s=o>0?1-i/o:1;return{callees:[...e].map(T),isolation:s}}import{posix as zi}from"path";import{spawnSync as ZU}from"child_process";import{createHash as eq}from"crypto";import{existsSync as tq}from"fs";import{dirname as fR,join as nq}from"path";import{fileURLToPath as rq}from"url";var yR=Nn("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]}),gR=mt({kind:"consumer-file-usage",invalidation:Te("consumer-file-usage"),serialize:fq,deserialize:gq});function Tn(e,t){return{forDefinitions(n,r){return iq(e,t,n,r)}}}function An(e){let t=new Map;for(let[n,r]of e)t.set(n,new Set(r.files.map(i=>i.file)));return t}function $c(e,t,n){return SR(e,t,n).partition}function iq(e,t,n,r){let i=bR(n.length),o=be()?dt(e):null,s=o?oq(n,r,o):void 0,a=s?{workIdentity:s,workOutcome:"computed"}:{};return N("consumer-evidence.product",()=>{let c=N("consumer-evidence.provenance",()=>sq(e,t,n,r),()=>({...a,definitions:n.length,semantic:r.semantic,sourceFallback:r.sourceFallback!==!1})),l=new Map;i={...i,...c.counters};let u=aq(n,c.sources);return N("consumer-evidence.classify",()=>{let d=cq(e,n,c.sources,u);for(let m of n){let p=d.get(m.symbolId)??uq();i.realFiles+=p.partition.realConsumers.length,i.reexportOnlyFiles+=p.partition.barrelConsumers,i.importOnlyFiles+=p.partition.importOnlyConsumers,l.set(m.symbolId,{definition:m,files:p.files,...p.partition})}},()=>({...a,...u,realFiles:i.realFiles,reexportOnlyFiles:i.reexportOnlyFiles,importOnlyFiles:i.importOnlyFiles})),l},()=>({...a,...i}))}function oq(e,t,n){let r=eq("sha256").update("consumer-evidence-v1\0").update(n).update("\0").update(t.semantic?"semantic\0":"indexed\0").update(t.sourceFallback===!1?"no-source-fallback":"source-fallback");for(let i of e.map(o=>o.symbol).sort())r.update("\0").update(i);return r.digest("hex").slice(0,24)}function bR(e){return{definitions:e,indexedFiles:0,semanticFiles:0,fallbackFiles:0,totalFiles:0,realFiles:0,reexportOnlyFiles:0,importOnlyFiles:0}}function sq(e,t,n,r){let i=bR(n.length),o=new Map;return Im(o,i,"indexed",t.crossFileCallerMap(n,{semantic:!1})),r.semantic&&Im(o,i,"semantic",Xn(e,n)),r.sourceFallback!==!1&&Im(o,i,"source-fallback",t.sourceFallbackCallerFiles(n)),i.totalFiles=[...o.values()].reduce((s,a)=>s+a.size,0),{sources:o,counters:i}}function aq(e,t){return{definitions:e.length,consumerFiles:[...t.values()].reduce((n,r)=>n+r.size,0),nativeAttempted:!1,nativeUsed:!1,nativeReason:"not-attempted"}}function Im(e,t,n,r){let i=0;for(let[o,s]of r){let a=e.get(o);a||(a=new Map,e.set(o,a));for(let c of s){i++;let l=a.get(c)??new Set;l.add(n),a.set(c,l)}}n==="indexed"?t.indexedFiles+=i:n==="semantic"?t.semanticFiles+=i:t.fallbackFiles+=i}function cq(e,t,n,r){let i=xq(e,t,n,r);return i||lq(e,t,n)}function lq(e,t,n){let r=new Map;for(let i of t){let o=n.get(i.symbolId)??new Map;r.set(i.symbolId,SR(e,i,[...o.keys()],o))}return r}function SR(e,t,n,r=new Map){let i=[],o=0,s=0,a=z(t.symbol),c=[];for(let l of n){let u;hq(e,l,t.relativePath,a)?(o++,u="reexport-only"):wm(e,l,a)?(s++,u="import-only"):(i.push(l),u="real"),c.push({file:l,sources:[...r.get(l)??[]],classification:u})}return{partition:{realConsumers:i,barrelConsumers:o,importOnlyConsumers:s},files:c}}function uq(){return{partition:{realConsumers:[],barrelConsumers:0,importOnlyConsumers:0},files:[]}}function wm(e,t,n){if(!n)return!1;let r=se(t);if(!r)return!1;let i=yR.get(e,t,()=>vR(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function vR(e,t,n){let r=gn(e).forFile(t,{text:!0}).text;if(!r)return pq();let i=Et(e,t,r),o=gR.read(e,t,i);if(o)return o;let s=mq(gn(e).forFile(t,{ast:!0}).ast,n);return gR.write(e,t,i,s),s}var dq=new Set(["identifier","type_identifier","property_identifier","field_identifier"]);function mq(e,t){let n=new Set,r=new Set;if(!e)return{importedLeaves:n,usedLeaves:r};let i=t==="rust"?new Set(["use_declaration"]):t==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),o=e.walk(),s=0,a=!1;for(;!a;){let c=o.nodeType,l=i.has(c);if(l&&(s+=1),dq.has(c)&&(s>0?n:r).add(o.nodeText),!o.gotoFirstChild())for(l&&(s-=1);!o.gotoNextSibling();){if(!o.gotoParent()){a=!0;break}i.has(o.nodeType)&&(s-=1)}}return{importedLeaves:n,usedLeaves:r}}function pq(){return{importedLeaves:new Set,usedLeaves:new Set}}function fq(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function gq(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 hq(e,t,n,r){if(!r)return!1;let i=gn(e).forFile(t,{lines:!0,reexports:!0}),o=i.lines??[];if(o.length===0)return!1;let s=i.reexports??[];return CR(o,s,r)}function CR(e,t,n){if(e.length===0||t.length===0)return!1;let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\b${r}\\b`),o=0;for(let s=0;s<e.length;s++){if(!i.test(e[s]??""))continue;if(o++,!t.find(c=>c.startLine<=s&&s<=c.endLine))return!1}return o>0}var yq="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY",bq="SCIP_QUERY_NATIVE_KERNELS_BIN",Sq="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY_MIN_FILES",hR=1e3,vq=5e3,Cq=64*1024*1024,Bc;function xq(e,t,n,r){let i=process.env[yq]?.toLowerCase();if(i!=="1"&&i!=="true")return r.nativeReason=i==="0"||i==="false"?"disabled":"opt-in-required",null;if(r.consumerFiles<Dq())return r.nativeReason="below-threshold",null;let o=Mq();if(!o)return r.nativeReason="binary-missing",null;r.nativeAttempted=!0;let s=Rq(e,t,n),a=ZU(o,["consumer-classify"],{input:JSON.stringify(s),encoding:"utf8",timeout:vq,maxBuffer:Cq});if(a.status!==0||a.error)return r.nativeReason=a.error?`spawn-error:${a.error.message}`:`exit-${a.status??"null"}`,null;try{let c=JSON.parse(a.stdout),l=Iq(c,t);return l?(r.nativeUsed=!0,r.nativeReason="used",l):(r.nativeReason="invalid-response",null)}catch{return r.nativeReason="invalid-json",null}}function Rq(e,t,n){let r=new Map,i=[];for(let a of t){let c=z(a.symbol),u=[...(n.get(a.symbolId)??new Map).entries()].map(([d,m])=>{let p=r.get(d)??new Set;return c&&p.add(c),r.set(d,p),{file:d,sources:[...m]}});i.push({symbol_id:a.symbolId,leaf:c,consumer_files:u})}let o={},s={};for(let[a,c]of r){let l=se(a);if(l){let d=yR.get(e,a,()=>vR(e,a,l));o[a]={imported_leaves:[...d.importedLeaves],used_leaves:[...d.usedLeaves]}}let u=Eq(e,a,c);u.length>0&&(s[a]=u)}return{definitions:i,file_usages:o,reexport_only_leaves:s}}function Eq(e,t,n){if(n.size===0)return[];let r=gn(e).forFile(t,{lines:!0,reexports:!0}),i=r.lines??[],o=r.reexports??[];return i.length===0||o.length===0?[]:[...n].filter(s=>CR(i,o,s))}function Iq(e,t){if(!Array.isArray(e.entries)||e.entries.length!==t.length)return null;let n=new Set(t.map(i=>i.symbolId)),r=new Map;for(let i of e.entries){let o=wq(i);if(!o||!n.has(o.symbol_id))return null;r.set(o.symbol_id,{partition:{realConsumers:o.real_consumers,barrelConsumers:o.barrel_consumers,importOnlyConsumers:o.import_only_consumers},files:o.files})}for(let i of n)if(!r.has(i))return null;return r}function wq(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.symbol_id!="number"||!Array.isArray(t.real_consumers)||typeof t.barrel_consumers!="number"||typeof t.import_only_consumers!="number"||!Array.isArray(t.files)||!t.real_consumers.every(r=>typeof r=="string"))return null;let n=[];for(let r of t.files){if(!r||typeof r!="object")return null;let i=r;if(typeof i.file!="string"||!Array.isArray(i.sources)||!i.sources.every(Lq)||!Pq(i.classification))return null;n.push({file:i.file,sources:i.sources,classification:i.classification})}return{symbol_id:t.symbol_id,real_consumers:t.real_consumers,barrel_consumers:t.barrel_consumers,import_only_consumers:t.import_only_consumers,files:n}}function Lq(e){return e==="indexed"||e==="semantic"||e==="source-fallback"}function Pq(e){return e==="real"||e==="reexport-only"||e==="import-only"}function Dq(){let e=process.env[Sq];if(!e)return hR;let t=Number(e);return Number.isFinite(t)&&t>=0?t:hR}function Mq(){if(Bc!==void 0)return Bc;let e=process.env[bq],t=process.platform==="win32"?"scip-query-kernels.exe":"scip-query-kernels";return Bc=[...e?[e]:[],...Tq().map(r=>nq(r,"target","release",t))].find(r=>tq(r))??null,Bc}function Tq(){let e=new Set,t=fR(rq(import.meta.url));for(let n=0;n<5;n++)e.add(t),t=fR(t);return[...e]}var Aq=20,Fq=1,kq=new Map([["app","app"],["apps","app"],["component","component"],["components","component"],["composable","composable"],["composables","composable"],["contract","contract"],["contracts","contract"],["domain","domain"],["domains","domain"],["feature","feature"],["features","feature"],["hook","hook"],["hooks","hook"],["lib","library"],["module","module"],["modules","module"],["package","package"],["packages","package"],["page","page"],["pages","page"],["route","route"],["routes","route"],["screen","screen"],["screens","screen"],["service","service"],["services","service"],["shared","shared"],["src","source-root"],["store","state"],["stores","state"],["test","test"],["tests","test"],["util","utility"],["utils","utility"],["view","view"],["views","view"]]),Nq=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),_q=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 Oq(e,t={}){let n=Dm(t.limit,Aq),r=Dm(t.minConsumers,Fq),i=new H(e),o=i.fileDependencyGraph(t.scope),s=rG(Q(e,{includeIgnored:!1})),a=sG(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?Bq(e,i,t.target):$q(e,t.scope,t.scanLimit)).map(u=>jq(e,i,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=r||t.target).sort(nG).slice(0,n)}function Bq(e,t,n){let r=qq(e,n);if(r)return[wR(r)];let i=ne(e,n);if(!i)return[];let o=t.definitionsForFile(i.relativePath).find(s=>s.symbolId===i.symbolId);return o?[Gq(o)]:[{unit:{kind:"symbol",file:i.relativePath,shortName:T(i.symbol),symbol:i.symbol,startLine:i.startLine,endLine:i.endLine}}]}function $q(e,t,n){let r=Q(e,{scope:t,includeIgnored:!1}),i=Dm(n,r.length);return r.slice(0,i).map(o=>wR(o))}function jq(e,t,n,r,i,o,s){let a=r.definition?Hq(e,t,r.definition,i.semantic):Uq(n,r.unit.file),c=r.definition?a.length>0?"exact":"none":a.length>0?"file-level":"none",l=r.unit.file,u=jt(zi.dirname(l)),d=Kq(a),m=zq(u),p=Tm([...xR(u),...d?xR(d):[]]),f=Wq(r.unit,u,d,a),g=Vq(f,r.unit,u,d,a,o,s),h=Zq(r.unit,c,d,a,u,g.whyNoSuggestedHome),b=eG(r.unit,u,d,a,g.suggestedHome,g.whyNoSuggestedHome);return{actionTier:"signal",sourceUnit:r.unit,candidatePath:l,currentDirectory:u,directoryAncestry:m,consumerFiles:a,consumerCoverage:c,nearestCommonOwner:d,boundaryMarkers:p,recommendedTier:f,suggestedHome:g.suggestedHome,destinationConfidence:g.confidence,whyNoSuggestedHome:g.whyNoSuggestedHome,counterevidence:h,reasons:b,recommendation:tG(f,g.suggestedHome,c)}}function Hq(e,t,n,r){let i=An(Tn(e,t).forDefinitions([n],{semantic:r!==!1,sourceFallback:!0}));return TR(i.get(n.symbolId)??[])}function Uq(e,t){let n=[];for(let[r,i]of e.entries())r!==t&&i.has(t)&&n.push(r);return TR(n)}function qq(e,t){let n=Ms(t),r=Q(e,{includeIgnored:!1}),i=r.find(s=>s===n);if(i)return i;let o=r.find(s=>s.endsWith(`/${n}`));return o||(r.find(s=>s.includes(n))??null)}function Gq(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:T(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function wR(e){return{unit:{kind:"file",file:e,shortName:zi.basename(e)}}}function zq(e){if(e===".")return[{path:".",depth:0,markers:[]}];let t=[],n=e.split("/").filter(Boolean);for(let r=0;r<n.length;r+=1){let i=n.slice(0,r+1).join("/");t.push({path:i,depth:r,markers:Mm(i)})}return t}function xR(e){return e==="."?[]:LR(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function Mm(e){return Tm(LR(e).map(({marker:t})=>t))}function LR(e){let t=e.split("/").filter(Boolean),n=[];for(let r=0;r<t.length;r+=1){let i=kq.get(t[r]);i&&n.push({marker:i,prefix:t.slice(0,r+1).join("/")})}return n}function Kq(e){if(e.length===0)return null;let t=e.map(r=>jt(zi.dirname(r))),n=t[0].split("/").filter(Boolean);for(let r of t.slice(1)){let i=r.split("/").filter(Boolean),o=[],s=Math.min(n.length,i.length);for(let a=0;a<s&&n[a]===i[a];a+=1)o.push(n[a]);n=o}return n.length===0?".":n.join("/")}function Wq(e,t,n,r){return n?e.kind==="symbol"&&r.length===1?r[0]===e.file?"same-file":"sibling-folder":n==="."||n==="src"?"repository-level-review":ER(n,"package")?"package-level-shared":ER(n,"app")?"app-level-shared":IR(n,["feature","domain","module"])||IR(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function Vq(e,t,n,r,i,o,s){let a=Yq(e,r);if(a)return fr(a);let c=iG(t.file),l=Jq(e,n,c,i,s);if(l)return l;let u=r;if(jt(n)===jt(u))return fr(`${n} is already the nearest common owner for its consumers.`);let d=Xq(u,n,c,s);return d||Qq(u,n,c,o,s)}function Yq(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 Jq(e,t,n,r,i){if(e==="same-file"){let o=r[0]??null;return o?Lm(o):fr("No same-file consumer path was available.")}if(e==="sibling-folder"&&r.length===1){let o=jt(zi.dirname(r[0])),s=MR(t,n,o,i);return s?fr(s):Lm(o)}return null}function Xq(e,t,n,r){return cG(e)?PR(e,t,n,r,`Nearest shared owner ${e} is outside source root ${n}.`):null}function Qq(e,t,n,r,i){if(e===".")return fr("The nearest common owner is the repository root.");let o=`${e}/shared`,s=PR(o,t,n,i,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||r.has(o)?s:fr(`${o} does not exist in the indexed project.`)}function PR(e,t,n,r,i){if(!DR(e,n))return fr(i);let o=MR(t,n,e,r);return o?fr(o):Lm(e)}function Lm(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function fr(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function Zq(e,t,n,r,i,o){let s=["Report-only signal; review ownership before moving files."];return t==="none"&&s.push("No consumers were found in the current index."),t==="file-level"&&s.push("File-level import evidence can hide which exported unit is actually used."),(n==="."||n==="src")&&s.push("Nearest common owner is broad, so this is not enough evidence for automatic placement."),r.length===1&&s.push("Only one consumer was found; inlining or same-folder placement may be better than shared extraction."),e.kind==="file"&&s.push("File targets describe module locality, not symbol-level usage."),n&&i.startsWith(`${n}/`)&&s.push("Candidate already lives under the nearest common owner."),o&&s.push(`No exact suggested home: ${o}`),s}function eG(e,t,n,r,i,o){let s=[];return s.push(`${e.shortName} currently lives in ${t}.`),n?s.push(`${r.length} consumer file(s) share ${n} as their nearest common owner.`):s.push("No consumer owner could be inferred from the current index."),i?s.push(`Suggested home is ${i}.`):o&&s.push(`No exact suggested home: ${o}`),s}function tG(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 nG(e,t){return RR(t)-RR(e)||e.candidatePath.localeCompare(t.candidatePath)}function RR(e){let t=e.consumerFiles.length*10;return e.consumerCoverage==="exact"&&(t+=5),e.suggestedHome&&(t+=3),e.recommendedTier==="repository-level-review"&&(t*=.1),e.recommendedTier==="no-exact-consumers"&&(t*=.05),t}function rG(e){let t=new Set(["."]);for(let n of e){let r=jt(zi.dirname(n));for(;!t.has(r)&&(t.add(r),r!==".");)r=jt(zi.dirname(r))}return t}function iG(e){let t=Pm(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function DR(e,t){let n=jt(e),r=jt(t);return r==="."||n===r||n.startsWith(`${r}/`)}function oG(e,t,n){let r=Pm(e),i=Pm(t);return(DR(e,t)?r.slice(i.length):r).some(s=>n.has(s.toLowerCase()))}function MR(e,t,n,r){return jt(e)===jt(n)||!oG(e,t,r)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function sG(...e){let t=new Set(_q);for(let n of e)for(let r of n??[]){let i=aG(r);i&&t.add(i)}return t}function aG(e){let t=e.trim().toLowerCase();return t===""?null:t}function ER(e,t){return Mm(e).includes(t)}function IR(e,t){let n=Mm(e);return t.some(r=>n.includes(r))}function cG(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?Nq.has(n):!1}function jt(e){let t=Ms(e);return t===""?".":t}function Pm(e){let t=Ms(e);return t==="."?[]:t.split("/").filter(Boolean)}function Dm(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function TR(e){return Tm([...e]).sort((t,n)=>t.localeCompare(n))}function Tm(e){return[...new Set(e)]}function Am(e,t,n={}){return AR(e,t,n).rows}function lG(e,t,n={}){return AR(e,t,n)}function AR(e,t,n){let{maxDepth:r=5,scope:i}=n,o=r===Number.MAX_SAFE_INTEGER,s=o?null:500,a=ne(e,t);if(!a)return{rows:[],coverage:{status:"incomplete",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:r,reachedDepth:0,perSymbolEvidenceLimit:s,remainingFrontierSymbols:0,reasons:["The requested symbol could not be resolved."]}};let c=[],l=new Set([a.symbolId]),u=new Set,d=[a],m=0,p=!1;for(let h=1;h<=r&&d.length!==0;h++){m=h;let b=[],S=bn(e,d,{...o?{}:{limit:s+1},semanticEvidence:re});for(let y of d){let x=S.get(y.symbolId)??[];s!==null&&x.length>s&&(p=!0);let v=s===null?x:x.slice(0,s);for(let C of uG(e,y,i,v)){let R=`${C.file}|${C.shortName}`;if(C.symbolId!==null){if(l.has(C.symbolId))continue;l.add(C.symbolId)}else if(u.has(R))continue;u.add(R),c.push({symbol:C.symbol,shortName:C.shortName,file:C.file,depth:h}),C.symbolId!==null&&C.symbolMatch&&b.push(C.symbolMatch)}}d=b}c.sort((h,b)=>h.depth-b.depth||h.file.localeCompare(b.file));let f=d.length>0,g=[];return f&&g.push(`${d.length} symbol(s) remain eligible beyond depth ${r}.`),p&&g.push(`At least one symbol had more than ${s} incoming evidence row(s).`),g.length===0&&g.push("The discovered reverse evidence frontier was exhausted."),{rows:c,coverage:{status:f||p?"bounded":"accounted",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:r,reachedDepth:m,perSymbolEvidenceLimit:s,remainingFrontierSymbols:d.length,reasons:g}}}function uG(e,t,n,r){let i=r.filter(u=>!e.isIgnored(u.file)).filter(u=>!n||u.file.includes(n)),o=new Set(i.map(u=>u.file)),s=[];for(let u of dG(e,t,n)){if(o.has(u))continue;let d=U(e,u),m=d.length>0?Oe(d,d[0].startLine):null;s.push({symbol:m?.symbol??u,file:u})}let a=[...i,...s],c=[],l=new Set;for(let u of a){let d=xr(e,u.symbol);if(!d){let p=`${u.file}|${u.symbol}`;if(l.has(p))continue;l.add(p),c.push({symbolId:null,symbol:u.symbol,shortName:T(u.symbol),file:u.file,symbolMatch:null});continue}if(d.symbolId===t.symbolId||e.isIgnored(d.relativePath)||!mG(d))continue;let m=`${d.symbolId}|${d.relativePath}`;l.has(m)||(l.add(m),c.push({symbolId:d.symbolId,symbol:d.symbol,shortName:T(d.symbol),file:d.relativePath,symbolMatch:d}))}return c}function dG(e,t,n){let r=n?"AND consumer_d.relative_path LIKE ?":"",i=[t.symbolId,t.documentId];return n&&i.push(`%${n}%`),new Set(e.all(`SELECT DISTINCT consumer_d.relative_path
323
- FROM mentions m
324
- JOIN chunks c ON m.chunk_id = c.id
325
- JOIN documents consumer_d ON consumer_d.id = c.document_id
326
- WHERE m.symbol_id = ?
327
- AND m.role != 1
328
- AND c.document_id != ?
329
- ${e.pathExclusionsFor("consumer_d")}
330
- ${r}`,...i).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function mG(e){if(e.symbol.startsWith("scip-clojure ")||se(e.relativePath)==="clojure")return!0;let t=Lt(e.symbol);return t==="method"||t==="type"||e.symbol.endsWith("().")}function kR(e,t){let n=it(t),r=[],i="complete",o=q(n);o==="entry"&&Fn(r,"operational-root","structural entrypoint path"),o==="worker"&&Fn(r,"operational-root","worker launch convention"),pd(n)&&Fn(r,"operational-root","framework-discovered entrypoint"),pG(e,n)&&Fn(r,"operational-root","configured entry root");let s=!1;try{s=En(e,n),s&&Fn(r,"published-api","package manifest export");for(let a of Nb(e,n))Fn(r,"operational-root",a)}catch(a){i="partial",Fn(r,"metadata-unavailable",`package metadata unavailable: ${FR(a)}`)}try{let a=Ye(e.config.projectRoot,n,{maxBytes:8388608,inputKind:"change-surface source"});fG(a)&&Fn(r,"operational-root","module contains a direct-execution process guard")}catch(a){i="partial",Fn(r,"metadata-unavailable",Je(a)?"indexed source file is unavailable on disk":`source metadata unavailable: ${FR(a)}`)}return{operationalRoot:r.some(a=>a.kind==="operational-root"),publishedApi:s,coverage:i,reasons:r}}function pG(e,t){let n=e.config.entryRoots;return n?n.files?.some(r=>it(r)===t)?!0:n.pathPrefixes?.some(r=>t.startsWith(it(r)))??!1:!1}function fG(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 Fn(e,t,n){e.some(r=>r.kind===t&&r.detail===n)||e.push({kind:t,detail:n})}function FR(e){return e instanceof Error?e.message:String(e)}function Fm(e,t,n={}){let r=pt(e,t);if(!r)return null;let i=gG(e,r);if(!i||e.isIgnored(i.relative_path))return null;let o=[],s=0,a=hG(e,i.relative_path),c=kR(e,i.relative_path),l=n.semantic===!1?new Map:Xn(e,a);for(let u of a){let d=yG(e,i,u,l.get(u.symbolId)??new Set);s+=d;let m=bG(d),p=[...c.reasons,...d>0?[{kind:"external-consumers",detail:`${d} external consumer${d===1?"":"s"}`}]:[]];o.push({symbol:u.symbol,shortName:T(u.symbol),startLine:u.startLine,endLine:u.endLine,externalConsumers:d,externalConsumerRiskLevel:m,riskLevel:SG(m,c),riskReasons:p})}return{file:i.relative_path,symbols:o,totalExternalConsumers:s,fileRisk:c}}function gG(e,t){return e.get(`SELECT id, relative_path FROM documents
331
- WHERE relative_path = ?
332
- ${e.pathExclusionsFor("documents")}
333
- LIMIT 1`,t)??null}function hG(e,t){return new H(e).definitionsForFile(t).sort((n,r)=>n.startLine-r.startLine||n.endLine-r.endLine)}function yG(e,t,n,r){let i=e.all(`SELECT DISTINCT consumer_d.relative_path
334
- FROM mentions m
335
- JOIN chunks c ON m.chunk_id = c.id
336
- JOIN documents consumer_d ON consumer_d.id = c.document_id
337
- WHERE m.symbol_id = ?
338
- AND m.role != 1
339
- AND c.document_id != ?`,n.symbolId,t.id);return new Set([...i.map(o=>o.relative_path),...[...r].filter(o=>o!==t.relative_path)]).size}function bG(e){return e>10?"high":e>0?"medium":"low"}function SG(e,t){return e==="high"?"high":e==="medium"||t.operationalRoot||t.publishedApi||t.coverage==="partial"?"medium":"low"}function vG(e,t={}){let{scope:n,minLoc:r=1,maxDepth:i=5,scanLimit:o}=t,s=new H(e),a=CG(e,n,r,o),c=new km;for(let g of a)c.add(g);let l=[],u=[];a.length>0&&l.push(NR(e,0,a,c));let d=a.map(g=>g.definition).filter(g=>g!==null),m=new Set(a.map(g=>g.symbol));for(let g=1;g<=i&&d.length>0;g++){let h=s.calleeMap(d,{semantic:!1}),b=new Set;for(let y of d)for(let x of h.get(y.symbolId)??[])m.has(x.symbol)||b.add(x.symbol);let S=[];for(let y of b){m.add(y);let x=_R(e,y);if(!x||e.isIgnored(x.relativePath)||Ue(e,x.relativePath)||Fe(e,x.symbol,x.relativePath)||s.fileKind(x.relativePath)==="test"||s.hasSuppressionComment(x))continue;let v=RG(e,x,c);v.removable?S.push(xG(x,"cascade")):v.blockingFiles.length>0&&u.push({shortName:T(x.symbol),file:x.relativePath,blockingFiles:v.blockingFiles.slice(0,3)})}if(S.length===0)break;for(let y of S)c.add(y);l.push(NR(e,g,S,c)),d=S.map(y=>y.definition).filter(y=>y!==null)}let p=l.reduce((g,h)=>g+h.loc,0),f=l.reduce((g,h)=>g+h.entries.length,0);return{batches:l,totalSymbols:f,totalLoc:p,blocked:u}}function CG(e,t,n,r){let i=Vr(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:r,semantic:!1}),o=[];for(let s of i.symbols)s.kind==="dead-code"&&(Ue(e,s.relativePath)||Fe(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:_R(e,s.symbol)}));return o}function xG(e,t){return{symbol:e.symbol,shortName:T(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function _R(e,t){let n=e.get(`SELECT d.relative_path
340
- FROM global_symbols gs
341
- JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
342
- JOIN documents d ON d.id = der.document_id
343
- WHERE gs.symbol = ?
344
- LIMIT 1`,t);return n?U(e,n.relative_path).find(r=>r.symbol===t)??null:null}function RG(e,t,n){let r=ro(e,t);if(r.length===0)return{removable:!1,blockingFiles:[]};let i=new Set;for(let o of r)o.file===t.relativePath&&o.line>=t.startLine&&o.line<=t.endLine||n.contains(o.file,o.line)||i.add(o.file);return{removable:i.size===0,blockingFiles:[...i]}}function NR(e,t,n,r){let i=[...n].sort((a,c)=>a.file.localeCompare(c.file)||a.startLine-c.startLine),o=new Set(i.map(a=>a.file)),s=[];for(let a of o){let c=U(e,a);c.length>0&&c.every(l=>r.contains(a,l.startLine))&&s.push(a)}return{depth:t,entries:i.map(({definition:a,...c})=>c),loc:i.reduce((a,c)=>a+c.loc,0),filesEmptied:s.sort()}}var km=class{ranges=new Map;add(t){let n=this.ranges.get(t.file)??[];n.push({start:t.startLine,end:t.endLine}),this.ranges.set(t.file,n)}contains(t,n){let r=this.ranges.get(t);return r?r.some(i=>n>=i.start&&n<=i.end):!1}};import{execFileSync as Ki}from"child_process";import{existsSync as EG}from"fs";import{basename as OR}from"path";function jc(e){let t=new Map;for(let n of e){let r=t.get(n.file);r||(r=[],t.set(n.file,r)),r.push(n)}return t}var $m="Unable to compute git diff.",IG={semanticConsumers:Xn,sourceFallbackConsumers:No,semanticReadiness:jy},jm={resolveCommit:vl,readBatch({projectRoot:e,resolvedBase:t,relativePaths:n}){let r=n.map(i=>`${t}:./${i}
345
- `).join("");return Ki("git",["cat-file","--batch"],{cwd:e,input:r,maxBuffer:256*1024*1024,timeout:1e4,stdio:["pipe","pipe","ignore"]})}};function Hc(e,t={}){let n=t.plan??Wi(e,t);return n.note?wG(n.note,n.changedFileLines):n.changedFiles.length===0?LG(n.changedFileLines):Uc(n.changedFiles,[HR(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function Wi(e,t={}){let{base:n="HEAD"}=t;try{let r=vl(e.config.projectRoot,n),i=PG(e.config.projectRoot,r),o=i.changedFileLines,s=kG(e,o),a=NG(e,i.changedRanges);return{changedFileLines:o,changedFiles:s,changedRanges:a,renamedFiles:TG(e.config.projectRoot,r,s,i),note:o.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:$m}}}function HR(e,t,n,r=[],i={}){let o=i.evidenceRuntime??IG,s=new H(e),a=new Set(n),c=jc(r),l=[],u=new Map,d=t.flatMap(I=>s.definitionsForFile(I)).filter(XG),m=d.filter(I=>OG(I,c)),p=$G(e,d,m,c),f=UG([...m,...p.definitions]).sort((I,w)=>I.relativePath.localeCompare(w.relativePath)||I.startLine-w.startLine),g=f.map(I=>I.symbolId),h=VG(e,g),b=YG(e,g,n),S=f.filter(I=>(h.get(I.symbolId)??0)===0),y=S.length>0?o.semanticReadiness?.(e)??{ready:!0}:{ready:!0},x=y.ready?jR("semantic-consumers",S.length,()=>o.semanticConsumers(e,S)):{values:new Map,status:{tier:"semantic-consumers",state:"failed",attemptedSymbols:S.length,reason:y.reason}},v=x.values,C=S.filter(I=>(v.get(I.symbolId)?.size??0)===0),R=jR("source-fallback-consumers",C.length,()=>o.sourceFallbackConsumers(e,C)),E=R.values;for(let I of f)zG(e,I,a,l,u,v.get(I.symbolId)??new Set,E.get(I.symbolId)??new Set,h.get(I.symbolId)??0,b.get(I.symbolId)??new Set);return{changedSymbols:l,consumerEntries:[...u.entries()].map(([I,w])=>({file:I,symbols:[...w].sort()})),attributionNotes:p.notes,evidenceTiers:[x.status,R.status]}}function Uc(e,t){let n=new Map,r=t.flatMap(a=>a.changedSymbols),i=t.flatMap(a=>a.attributionNotes??[]),o=KG(t);for(let a of t)for(let c of a.consumerEntries){let l=n.get(c.file);l||(l=new Set,n.set(c.file,l));for(let u of c.symbols)l.add(u)}let s=JG(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:s,attributionNotes:i,evidenceTiers:o,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:s.length}}}function wG(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:VR(),summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function LG(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:VR(),summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function PG(e,t){let n=Ki("git",["diff","--name-status","--find-renames",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864}),r=Ki("git",["diff","--name-status","--find-renames","--cached",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),i=Ki("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),o=Ki("git",["diff","--unified=0",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),s=Ki("git",["diff","--unified=0","--cached",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),a=AG([n,r]);return{changedFileLines:[...new Set([...a.changedFiles,...GR(i)])],changedRanges:KR([...$R(o),...$R(s)]),renamedFiles:a.renamedFiles,deletedFiles:a.deletedFiles}}function DG(e,t,n){let r=typeof e=="string"?{projectRoot:e,base:t,relativePath:n}:e;if(typeof r.projectRoot!="string"||typeof r.base!="string"||typeof r.relativePath!="string")throw new TypeError("fileContentAtBase requires projectRoot, base, and relativePath.");let i={projectRoot:r.projectRoot,base:r.base,relativePath:r.relativePath},{relativePath:o}=i,s=Hm(i);if(s.state==="unavailable")throw new Error(`Base content unavailable for ${o}: ${s.reason}`);return s.state==="present"?s.content:null}function Hm(e,t=jm){return qR(e.relativePath),Um({projectRoot:e.projectRoot,base:e.base,relativePaths:[e.relativePath]},t).get(e.relativePath)??{state:"unavailable",reason:`Base-content lookup omitted ${e.relativePath}.`}}function Um(e,t=jm){for(let s of e.relativePaths)qR(s);let n=[...new Set(e.relativePaths)];if(n.length===0)return new Map;let r;try{r=t.resolveCommit(e.projectRoot,e.base)}catch(s){return Nm(n,_m(s))}let i;try{i=t.readBatch({projectRoot:e.projectRoot,resolvedBase:r,relativePaths:n})}catch(s){return Nm(n,_m(s))}let o;try{o=MG(i,n)}catch(s){return Nm(n,`Malformed git cat-file batch output: ${_m(s)}`)}return new Map(n.map(s=>{let a=o.get(s)??null;return[s,a===null?{state:"absent"}:{state:"present",content:a}]}))}function qm(e,t=jm){let n=Um({projectRoot:e.projectRoot,base:e.base,relativePaths:e.preloadPaths??[]},t);return r=>(n.has(r)||n.set(r,Hm({projectRoot:e.projectRoot,base:e.base,relativePath:r},t)),n.get(r)??{state:"unavailable",reason:`Base-content reader omitted ${r}.`})}function UR(e,t=e.changedFiles){let n=new Map(e.renamedFiles.map(r=>[r.to,r.from]));return[...new Set(t.map(r=>n.get(r)??r))]}function qR(e){mn(e)}function Nm(e,t){return new Map(e.map(n=>[n,{state:"unavailable",reason:t}]))}function _m(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 MG(e,t){let n=new Map,r=0;for(let i of t){let o=e.indexOf(10,r);if(o<0)throw new Error("git cat-file batch output ended before object header");let s=e.subarray(r,o).toString("utf-8");if(r=o+1,s.endsWith(" missing")){n.set(i,null);continue}let a=/^[0-9a-f]+ ([^ ]+) (\d+)$/.exec(s);if(!a)throw new Error(`unexpected git cat-file batch header: ${s}`);let[,c,l]=a,u=Number(l);if(!Number.isFinite(u)||u<0)throw new Error(`unexpected git cat-file batch size: ${s}`);if(r+u>e.length)throw new Error("git cat-file batch output ended before blob payload");let d=e.subarray(r,r+u);n.set(i,c==="blob"?d.toString("utf-8"):null),r+=u,e[r]===10&&(r+=1)}return n}function TG(e,t,n,r){if(n.length===0)return[];let i=new Map,o=new Set;for(let a of r.renamedFiles)n.includes(a.to)&&(i.set(a.to,a),o.add(a.from));let s=r.deletedFiles;if(s.length===0)return[...i.values()].sort((a,c)=>a.to.localeCompare(c.to));for(let a of n){if(i.has(a)||!EG(`${e}/${a}`))continue;let c=s.filter(d=>!o.has(d)).filter(d=>OR(d)===OR(a));if(c.length===0)continue;let l=Ye(e,a),u=c.map(d=>({from:d,to:a,similarity:FG(DG({projectRoot:e,base:t,relativePath:d})??"",l)})).sort((d,m)=>m.similarity-d.similarity)[0];u&&u.similarity>=.45&&(i.set(a,u),o.add(u.from))}return[...i.values()].sort((a,c)=>a.to.localeCompare(c.to))}function AG(e){let t=new Set,n=new Map,r=new Set;for(let i of e.flatMap(o=>GR(o))){let[o,s,a]=i.split(" ");if(!(!o||!s)){if(o.startsWith("R")&&a){t.add(a),n.set(a,{from:s,to:a,similarity:Number(o.slice(1))/100});continue}t.add(s),o.startsWith("D")&&r.add(s)}}return{changedFiles:[...t],renamedFiles:[...n.values()],deletedFiles:[...r]}}function FG(e,t){let n=new Set(BR(e)),r=new Set(BR(t));if(n.size===0&&r.size===0)return 1;if(n.size===0||r.size===0)return 0;let i=0;for(let o of n)r.has(o)&&(i+=1);return 2*i/(n.size+r.size)}function BR(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function GR(e){return e.split(`
346
- `).map(t=>t.trim()).filter(t=>t.length>0)}function kG(e,t){let n=zR(e),r=[];for(let i of t){let o=n(i);o&&!e.isIgnored(o)&&r.push(o)}return r}function NG(e,t){let n=zR(e),r=[];for(let i of t){let o=n(i.file);o&&!e.isIgnored(o)&&r.push({...i,file:o})}return KR(r)}function zR(e){let t=e.all(`SELECT relative_path FROM documents
347
- ORDER BY id`).map(r=>r.relative_path),n=new Map(t.map(r=>[r,r]));return r=>{let i=r.replace(/\\/g,"/"),o=n.get(i);return o||(t.find(s=>s.endsWith(i))??null)}}function $R(e){let t=[],n=null;for(let r of e.split(`
348
- `)){if(r.startsWith("+++ ")){n=_G(r.slice(4).trim());continue}if(!n||!r.startsWith("@@ "))continue;let i=/@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(r);if(!i)continue;let o=Math.max(0,Number(i[1])-1),s=i[2]===void 0?1:Number(i[2]);t.push({file:n,startLine:o,endLine:Math.max(o,o+Math.max(s,1)-1)})}return t}function _G(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function KR(e){let t=new Set,n=[];for(let r of e){let i=`${r.file}:${r.startLine}:${r.endLine}`;t.has(i)||(t.add(i),n.push(r))}return n}function OG(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(r=>Gm(e.startLine,e.endLine,r.startLine,r.endLine))}function BG(e,t,n){let r=new Map,i=[],o=WR(e),s=qG(n);for(let a of t){let c=o.get(a.file)??[];if(c.some(d=>Gm(d.startLine,d.endLine,a.startLine,a.endLine)))continue;let l=s.get(a.file)??[],u=GG(l,a);if(u){let d=c.find(m=>m.startLine>=u.startLine&&m.startLine<=u.endLine);if(d){r.set(d.symbolId,d),i.push(Om(a,"ast-widened"));continue}}if(l.length===0){let d=[...c].filter(m=>m.startLine<=a.startLine).sort((m,p)=>p.startLine-m.startLine||m.endLine-p.endLine)[0];if(d){r.set(d.symbolId,d),i.push(Om(a,"nearest-preceding"));continue}}i.push(Om(a,"unattributed"))}return{definitions:[...r.values()],notes:i}}function $G(e,t,n,r){let i=WR(n),o=[],s=[],a=[...new Set(t.map(c=>c.relativePath))];for(let c of a){let l=r.get(c)??[];if(l.length===0)continue;let u=i.get(c)??[];for(let d of l)u.some(m=>Gm(m.startLine,m.endLine,d.startLine,d.endLine))||o.push(d);o.some(d=>d.file===c)&&s.push(...jG(e,c))}return BG(t,o,s)}function jG(e,t){let n=J(e,t);return n?n.rootNode.namedChildren.filter(HG).map(r=>({file:t,startLine:r.startPosition.row,endLine:r.endPosition.row})).filter(r=>r.endLine>=r.startLine):[]}function HG(e){return e.endPosition.row<e.startPosition.row?!1:!new Set(["import_statement","comment"]).has(e.type)}function UG(e){let t=new Map;for(let n of e)t.set(n.symbolId,n);return[...t.values()]}function WR(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath)??[];r.push(n),t.set(n.relativePath,r)}return t}function qG(e){let t=new Map;for(let n of e){let r=t.get(n.file)??[];r.push(n),t.set(n.file,r)}return t}function GG(e,t){return e.filter(n=>n.startLine<=t.startLine&&n.endLine>=t.endLine).sort((n,r)=>n.endLine-n.startLine-(r.endLine-r.startLine))[0]}function Om(e,t){return{file:e.file,startLine:e.startLine,endLine:e.endLine,method:t}}function Gm(e,t,n,r){return e<=r&&n<=t}function zG(e,t,n,r,i,o,s,a,c){let l=Math.max(a,o.size,s.size);if(!QG(t,l))return;let u=T(t.symbol);r.push({symbol:t.symbol,shortName:u,file:t.relativePath,startLine:t.startLine,endLine:t.endLine,fanIn:l});for(let d of c)Bm(e,n,i,d,u);for(let d of o)Bm(e,n,i,d,u);for(let d of s)Bm(e,n,i,d,u)}function jR(e,t,n){try{return{values:n(),status:{tier:e,state:"complete",attemptedSymbols:t}}}catch(r){return{values:new Map,status:{tier:e,state:"failed",attemptedSymbols:t,reason:WG(r)}}}}function KG(e){return["semantic-consumers","source-fallback-consumers"].map(t=>{let n=e.map(o=>o.evidenceTiers?.find(s=>s.tier===t)??{tier:t,state:"failed",attemptedSymbols:0,reason:"isolated diff-impact batch omitted its evidence-tier status"}),r=n.reduce((o,s)=>o+s.attemptedSymbols,0),i=[...new Set(n.filter(o=>o.state==="failed").map(o=>o.reason))];return i.length===0?{tier:t,state:"complete",attemptedSymbols:r}:{tier:t,state:"failed",attemptedSymbols:r,reason:i.join("; ").slice(0,500)}})}function VR(){return[{tier:"semantic-consumers",state:"complete",attemptedSymbols:0},{tier:"source-fallback-consumers",state:"complete",attemptedSymbols:0}]}function WG(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 VG(e,t){if(t.length===0)return new Map;let n=e.all(`SELECT m.symbol_id, COUNT(DISTINCT c.document_id) AS fan_in
349
- FROM mentions m
350
- JOIN chunks c ON m.chunk_id = c.id
351
- WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
352
- AND m.role != 1
353
- GROUP BY m.symbol_id`,...t);return new Map(n.map(r=>[r.symbol_id,r.fan_in]))}function YG(e,t,n){if(t.length===0||n.length===0)return new Map;let r=e.all(`SELECT DISTINCT m.symbol_id, ref_d.relative_path
354
- FROM mentions m
355
- JOIN chunks c ON m.chunk_id = c.id
356
- JOIN documents ref_d ON c.document_id = ref_d.id
357
- WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
358
- AND m.role != 1
359
- AND ref_d.relative_path NOT IN (${n.map(()=>"?").join(",")})
360
- ${e.pathExclusionsFor("ref_d")}`,...t,...n),i=new Map;for(let o of r){let s=i.get(o.symbol_id);s||(s=new Set,i.set(o.symbol_id,s)),s.add(o.relative_path)}return i}function Bm(e,t,n,r,i){if(e.isIgnored(r)||t.has(r))return;let o=n.get(r);o||(o=new Set,n.set(r,o)),o.add(i)}function JG(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function XG(e){return!(pe(e.symbol)||e.parentTypeName!==null&&!Xe(e.symbol))}function QG(e,t){return Xe(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}var ZG=5;function ez(e,t={}){let{base:n="HEAD",minContainment:r=.7,minCallees:i=3,minSiteCoverage:o=.4,maxHelpers:s=Number.POSITIVE_INFINITY,limit:a=20,scanLimit:c}=t,l=t.semantic!==!1,u=t.diffPlan??Wi(e,{base:n}),d={available:u.note!==$m,base:n,changedFiles:u.changedFiles,helpersChecked:0,skipped:[],findings:[],...u.note?{note:u.note}:{}};if(!d.available||u.changedFiles.length===0)return d;let m=new H(e),p=new Set(u.changedFiles),f=new Map(u.renamedFiles.map(R=>[R.to,R.from]));if(t.baseContentAt&&t.baseContentResultAt)throw new Error("Specify only one of baseContentAt or baseContentResultAt.");let g=t.baseContentResultAt?t.baseContentResultAt:t.baseContentAt?az(t.baseContentAt):qm({projectRoot:e.config.projectRoot,base:n,preloadPaths:UR(u)}),h=sz(m,p,f,g);if(h.unavailable)return d.available=!1,d.note=`Base content unavailable: ${h.unavailable.reason}`,d;if(h.definitions.length===0)return d;let b=h.definitions.slice(0,s);h.definitions.length>s&&(d.note=`helper scoring capped at ${s} of ${h.definitions.length} new symbols`);let S=m.calleeMap(b,{semantic:l}),y=b.map(R=>({def:R,callees:Nc((S.get(R.symbolId)??[]).map(E=>E.symbol))})),x=Gi(e),v,C=()=>(v??=x.calleeIndex({minCallees:Math.min(3,i),scanLimit:c,semantic:l}),v);for(let{def:R,callees:E}of y){let I=T(R.symbol);if(E.size<i){d.skipped.push({helperShortName:I,helperFile:R.relativePath,reason:`fewer than ${i} meaningful callees \u2014 too small to score`});continue}let w=C(),A=oz(E,w);if(A===0){d.skipped.push({helperShortName:I,helperFile:R.relativePath,reason:"helper callee pattern is all project-wide infrastructure \u2014 too generic to score"});continue}let D=cz(e,R.symbolId);if(D.length===0){d.skipped.push({helperShortName:I,helperFile:R.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}d.helpersChecked+=1;let k=tz({candidateIndex:w,changed:p,helperCallees:E,helperFile:R.relativePath,helperSymbol:R.symbol,minContainment:r,minSiteCoverage:o,migratedFiles:D});k.length!==0&&(k.sort((L,F)=>YR(F.migrationScope)-YR(L.migrationScope)||F.containment-L.containment||F.siteCoverage-L.siteCoverage||L.file.localeCompare(F.file)),d.findings.push({helperSymbol:R.symbol,helperShortName:I,helperFile:R.relativePath,helperShape:"specific-callee-cluster",helperCalleeCount:E.size,specificHelperCalleeCount:A,migratedFiles:D.sort(),leftovers:k.slice(0,ZG)}))}return d.findings.sort((R,E)=>(E.leftovers[0]?.containment??0)-(R.leftovers[0]?.containment??0)||R.helperFile.localeCompare(E.helperFile)),d.findings=d.findings.slice(0,a),d}function tz(e){let t=[],n=nz(e.helperSymbol,e.helperFile,e.migratedFiles),r=new Set;for(let i of e.helperCallees)for(let o of e.candidateIndex.candidateIndexesByCallee.get(i)??[])r.add(o);for(let i of r){let o=e.candidateIndex.corpus[i];if(o.symbol===e.helperSymbol||e.changed.has(o.file)||o.callees.has(e.helperSymbol))continue;let s=jx(e.helperCallees,o.callees);if(s<e.minContainment)continue;let a=[...e.helperCallees].filter(u=>o.callees.has(u)),c=o.callees.size===0?0:a.length/o.callees.size;if(c<e.minSiteCoverage||!a.some(u=>(e.candidateIndex.docFreq.get(u)??0)<=e.candidateIndex.ubiquityThreshold))continue;let l=rz(n,o.symbol,o.file);t.push({symbol:o.symbol,shortName:T(o.symbol),file:o.file,...l,containment:s,siteCoverage:c,uniqueSiteCalleeCount:Math.max(0,o.callees.size-a.length),sharedCallees:a.map(T).sort()})}return t}function YR(e){return e==="same-scope"?2:e==="unknown"?1:0}function nz(e,t,n){let r=new Set([...zm(t),...Km(z(e))]);for(let i of n)for(let o of zm(i))r.add(o);return r}function rz(e,t,n){let r=new Set([...zm(n),...Km(z(t))]);if(e.size===0||r.size===0)return{migrationScope:"unknown",migrationScopeReasons:["insufficient path/name tokens to infer migration scope"]};let i=[...r].filter(o=>e.has(o)).sort();return i.length>0?{migrationScope:"same-scope",migrationScopeReasons:[`shares migration-scope token(s): ${i.slice(0,5).join(", ")}`]}:{migrationScope:"possible-subtype",migrationScopeReasons:["no path/name tokens shared with the helper or already migrated files"]}}var iz=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 zm(e){return Km(e.replace(/\.[^.]+$/,""))}function Km(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!iz.has(t))}function oz(e,t){let n=0;for(let r of e)(t.docFreq.get(r)??0)<=t.ubiquityThreshold&&(n+=1);return n}function sz(e,t,n,r){let i=[];for(let o of e.productionCallableDefinitions({files:[...t],requireFunctionLikeSymbol:!0})){if(!t.has(o.relativePath))continue;let s=n.get(o.relativePath)??o.relativePath,a=r(s);if(a.state==="unavailable")return{definitions:[],unavailable:a};(a.state==="absent"||!new RegExp(`\\b${xe(o.leaf)}\\b`).test(a.content))&&i.push(o)}return{definitions:i}}function az(e){return t=>{let n=e(t);return n===null?{state:"absent"}:{state:"present",content:n}}}function cz(e,t){return e.all(`SELECT DISTINCT ref_d.relative_path
361
- FROM mentions m
362
- JOIN chunks c ON m.chunk_id = c.id
363
- JOIN documents ref_d ON c.document_id = ref_d.id
364
- WHERE m.symbol_id = ?
365
- AND m.role != 1
366
- ${e.pathExclusionsFor("ref_d")}`,t).map(r=>r.relative_path)}import{execFileSync as lz}from"child_process";var eE=2e3,qc=50,uz=64,dz=8,mz=3,pz=2160*60*60,fz=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,gz=3,hz=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,yz=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function bz(e){let t=me(e,{clearGroups:["whole-project"]});return(n,r,i)=>{let o=i??Wm(n.config.projectRoot);if(!o)return null;let s=t.has(n)?t.get(n,()=>({head:"",value:null})):null;return s&&s.head===o?s.value:(t.invalidate(n),t.get(n,()=>({head:o,value:r(n.config.projectRoot,o)})).value)}}function Gc(e){let t=me(e,{clearGroups:["whole-project"]});return(n,r,i,o)=>{let s=o??Wm(n.config.projectRoot);if(!s)return null;let a=t.has(n)?t.get(n,()=>({head:"",values:new Map})):null;(!a||a.head!==s)&&t.invalidate(n);let c=t.get(n,()=>({head:s,values:new Map}));if(c.values.has(r))return c.values.get(r)??null;let l=i(n.config.projectRoot,s);return c.values.set(r,l),l}}var Sz=Gc("git-commit-history");function Ht(e,t={}){let n=t.historyMode??"bounded",r=t.head;return{capability:i=>vz(e,i,r),commitHistory:()=>fs(e,n,r),fileChurn:()=>Rz(e,n,r),changeAmplification:()=>Ez(e,n,r),trackedFiles:()=>wz(e,r),fileAddRecords:()=>Pz(e,n,r),coChangePairs:(i={})=>Nz(e,i,n,r),coChangePairsForFiles:(i,o={})=>rE(e,i,o,n,r),directionalCoChangePairsForFiles:(i,o={})=>_z(e,i,o,n,r)}}function fs(e,t="bounded",n){return Sz(e,Vi(t),(r,i)=>Cz(r,i,t),n)}function vz(e,t,n){let r=n??Wm(e.config.projectRoot);return r?{slot:t,available:!0,head:r}:{slot:t,available:!1,head:null,reason:"git history is unavailable for this project"}}function Wm(e){try{return cn(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function cn(e,t){return lz("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"})}function Cz(e,t,n){let r;try{r=cn(e,["log","--no-merges","--name-only",...zc(n),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}return{head:t,...Jm(r,qc)}}function xz(e){return fz.test(e.subject)}function Rz(e,t,n){let r=fs(e,t,n);if(!r)return null;let i=new Map;for(let o of r.commits){let s=xz(o);for(let a of o.files){let c=i.get(a)??{changes:0,fixChanges:0,lastChangedAt:0};c.changes+=1,s&&(c.fixChanges+=1),o.timestamp>c.lastChangedAt&&(c.lastChangedAt=o.timestamp),i.set(a,c)}}return i}function Ez(e,t,n){let r=fs(e,t,n);if(!r||r.commits.length===0)return null;let i=r.commits.map(o=>o.files.length).filter(o=>o>0).sort((o,s)=>o-s);return i.length===0?null:{medianFilesPerCommit:JR(i,.5),p90FilesPerCommit:JR(i,.9),commitsAnalyzed:i.length}}function JR(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var Iz=bz("git-tracked-files");function wz(e,t){return Iz(e,n=>{try{let r=cn(n,["ls-files"]);return new Set(r.split(`
367
- `).map(i=>i.trim()).filter(i=>i!==""))}catch{return null}},t)}var Lz=Gc("git-file-adds"),XR="__git__/file-adds",QR=mt({kind:"git-file-adds",invalidation:Te("git-file-adds"),serialize:Mz,deserialize:Tz});function tE(e){return Ht(e).fileAddRecords()}function Pz(e,t,n){let r=Vi(t);return Lz(e,r,(i,o)=>Dz(e,i,o,t),n)}function Dz(e,t,n,r){let i=QR.read(e,ZR(r),n);if(i)return i;let o=Az(t,r);return o&&QR.write(e,ZR(r),n,o),o}function Mz(e){return JSON.stringify([...e.entries()])}function Tz(e){if(!e)return null;try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=new Map;for(let r of t){if(!Array.isArray(r)||r.length!==2||typeof r[0]!="string")return null;let i=r[1];if(!i||typeof i.commitsAgo!="number"||!Number.isFinite(i.commitsAgo)||typeof i.addedAt!="number"||!Number.isFinite(i.addedAt))return null;n.set(r[0],{commitsAgo:i.commitsAgo,addedAt:i.addedAt})}return n}catch{return null}}function Az(e,t){let n;try{n=cn(e,["log","--no-merges","--find-renames","--name-status",...zc(t),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let r=new Map,i=new Map,o=-1;for(let s of n.split("")){if(s.trim()==="")continue;o+=1;let a=s.indexOf(`
368
- `),c=a>=0?s.slice(0,a):s,[,l]=c.split("\0"),u=Number(l)||0;if(!(a<0))for(let d of s.slice(a+1).split(`
369
- `)){let m=Fz(d);if(!m)continue;if(m.status==="R"&&m.from&&m.to){let f=i.get(m.to)??new Set([m.to]);i.set(m.from,f);continue}if(m.status!=="A"||!m.to)continue;let p={commitsAgo:o,addedAt:u};r.set(m.to,p);for(let f of i.get(m.to)??[])r.set(f,p)}}return r}function Fz(e){let t=e.trim().split(" "),n=t[0]??"";if(!n)return null;let r=n[0]??"";if(r==="R"){let o=t[1],s=t[2];return o&&s?{status:r,from:o,to:s}:null}let i=t[1];return i?{status:r,to:i}:null}var nE=Gc("git-co-change-pairs"),kz=Gc("git-directional-co-change-pairs");function Nz(e,t,n,r){let i=`all\0${Vi(n)}\0${Vm(t)}`,o=nE(e,i,()=>{let s=fs(e,n,r);return s?Ym(s,t):null},r);return o&&[...o]}function rE(e,t,n,r,i){if(t.size===0)return[];let o=`files\0${Vi(r)}\0${iE(t)}\0${Vm(n)}`,s=nE(e,o,()=>{let a=fs(e,r,i);return a?Ym(a,n,t):null},i);return s&&[...s]}function _z(e,t,n,r,i){if(t.size===0)return[];let o=n.maxFilesPerCommit??qc;if(t.size>uz)return rE(e,t,n,r,i);let s=`directional\0${Vi(r)}\0${iE(t)}\0${Vm({...n,maxFilesPerCommit:o})}`,a=kz(e,s,(c,l)=>{let u=Oz(c,l,t,o,r);return u?Ym(u,n,t):null},i);return a&&[...a]}function Vm(e){let t=e.minTogether??4,n=e.minConfidence??.6,r=e.maxFilesPerCommit??qc;return`${t}\0${n}\0${r}`}function iE(e){return[...e].sort().join("\0")}function Ym(e,t,n){let{minTogether:r=4,minConfidence:i=.6,maxFilesPerCommit:o=qc}=t,s=new Map,a=new Map,c=e.newestAnalyzedAt??0;for(let d of e.commits){let m=[...new Set(d.files)].sort();if(m.length>o)continue;e.newestAnalyzedAt===void 0&&d.timestamp>c&&(c=d.timestamp);let p=jz(m),f=n===void 0||m.some(g=>n.has(g));for(let g of m)s.set(g,(s.get(g)??0)+1);if(f)for(let g=0;g<m.length;g++)for(let h=g+1;h<m.length;h++){if(n&&!n.has(m[g])&&!n.has(m[h]))continue;let b=`${m[g]}\0${m[h]}`,S=a.get(b)??{together:0,focusedTogether:0,broadTogether:0,lastTogetherAt:0,timestamps:[],subjects:[]};S.together+=1,p?S.broadTogether+=1:S.focusedTogether+=1,d.timestamp>S.lastTogetherAt&&(S.lastTogetherAt=d.timestamp),S.timestamps.push(d.timestamp),S.subjects.push(d.subject),a.set(b,S)}}let l=[],u=c-pz;for(let[d,m]of a){let p=m.together;if(p<r)continue;let[f,g]=d.split("\0"),h=s.get(f)??p,b=s.get(g)??p,S=Math.max(p/h,p/b);if(S<i)continue;let y=m.broadTogether/p,x=m.timestamps.filter(v=>v>=u).length;l.push({fileA:f,fileB:g,together:p,confidence:S,changesA:h,changesB:b,focusedTogether:m.focusedTogether,broadTogether:m.broadTogether,broadCommitRatio:y,lastTogetherAt:m.lastTogetherAt,recentTogether:x,commitScope:Uz(m.broadTogether,p),recency:x>0?"recent":"stale",subjectContext:qz(m.subjects)})}return l.sort((d,m)=>m.together-d.together||m.confidence-d.confidence||d.fileA.localeCompare(m.fileA)),l}function Oz(e,t,n,r,i){let o;try{o=Bz(e,i)}catch{return null}if(o.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:0};let s;try{s=cn(e,["log","--no-merges","--format=%H",...zc(i),"--",...[...n].sort()])}catch{return null}let a=new Set(o.map(m=>m.hash)),c=s.split(`
370
- `).map(m=>m.trim()).filter(m=>m!==""&&a.has(m)),l=$z(e,o,r);if(c.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:l};let u;try{u=cn(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...c])}catch{return null}let d=Jm(u,r);return{head:t,...d,newestAnalyzedAt:l}}function Bz(e,t){return cn(e,["log","--no-merges","--format=%H%x00%ct",...zc(t)]).split(`
371
- `).map(r=>r.trim()).filter(r=>r!=="").map(r=>{let[i,o]=r.split("\0");return{hash:i??"",timestamp:Number(o)||0}}).filter(r=>r.hash!=="")}function zc(e){return e==="full"?[]:["-n",String(oE())]}function oE(){return Yn(process.env.SCIP_QUERY_GIT_HISTORY_MAX_COMMITS)??eE}function Vi(e){return e==="full"?"full":`bounded:${oE()}`}function ZR(e){let t=Vi(e);return t===`bounded:${eE}`?XR:`${XR}:${t}`}function $z(e,t,n){for(let i=0;i<t.length;i+=20){let o=t.slice(i,i+20),s;try{s=cn(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...o.map(c=>c.hash)])}catch{return t[0]?.timestamp??0}let a=Jm(s,n);if(a.commits.length>0)return a.commits[0].timestamp}return 0}function Jm(e,t){let n=[],r=0;for(let i of e.split("")){if(i.trim()==="")continue;let o=i.indexOf(`
372
- `),s=o>=0?i.slice(0,o):i,[a,c,l]=s.split("\0");if(!a||!c)continue;let u=o>=0?i.slice(o+1).split(`
373
- `).map(d=>d.trim()).filter(d=>d!==""):[];if(u.length>t){r+=1;continue}n.push({hash:a,timestamp:Number(c)||0,subject:l??"",files:u})}return{commits:n,skippedBulkCommits:r}}function jz(e){return e.length>=dz?!0:Hz(e).size>=mz}function Hz(e){let t=new Set;for(let n of e){let r=n.indexOf("/");t.add(r>=0?n.slice(0,r):".")}return t}function Uz(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function qz(e){let t=new Set,n=[],r=[];for(let i of e){!r.includes(i)&&r.length<gz&&r.push(i);for(let o of Gz(i))t.add(o);for(let o of i.match(hz)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:r,externalIssueLabelStatus:"unavailable"}}function Gz(e){let t=new Set,n=yz.exec(e)?.[1]?.toLowerCase();return n&&t.add(zz(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 zz(e){return e==="feat"?"feature":e}var sE=/(?:^|\/)(?: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 gs(e,t,n={}){let{minTogether:r=4,minConfidence:i=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=Ht(e,{historyMode:n.historyMode,...n.head?{head:n.head}:{}}),c=a.commitHistory(),l=t!==void 0,u=a.coChangePairs({minTogether:l?Math.min(r,2):r,minConfidence:l?0:i,maxFilesPerCommit:s});if(!c||!u)return{available:!1,commitsAnalyzed:0,findings:[]};let d=typeof n.scanLimit=="number"?u.slice(0,n.scanLimit):u,m=Ae(e),p=dE(e),f=Vz(e,m,p),g=n.includeLinked===!0||l,h=[];for(let b of d){if(sE.test(b.fileA)||sE.test(b.fileB)||!aE(e,b.fileA)||!aE(e,b.fileB)||l&&!b.fileA.includes(t)&&!b.fileB.includes(t)||!l&&(q(b.fileA)==="test"||q(b.fileB)==="test"||Qz(b.fileA,b.fileB)||Jz(b.fileA,b.fileB)))continue;let S=f(b.fileA,b.fileB);if(!g&&S)continue;let y=Kz(b.fileA,b.fileB),x=Wz(b,y,S);if(h.push({...b,structurallyLinked:S,partnerClass:y.partnerClass,partnerClassReasons:y.reasons,...x?{declaredCouplingSuggestion:x}:{}}),h.length>=o)break}return{available:!0,commitsAnalyzed:c.commits.length,findings:h}}function aE(e,t){return xt(e.config.projectRoot,t)}function Kz(e,t){let n=lE(e),r=lE(t),i=[],o=c=>{i.includes(c)||i.push(c)},s=(c,l)=>n.tags.has(c)&&r.tags.has(l)||n.tags.has(l)&&r.tags.has(c);if(s("doc","code"))return o("one side is documentation and the other is executable source"),{partnerClass:"doc-code",reasons:i};if(n.tags.has("test")||r.tags.has("test"))return o("one side is classified as a test file"),{partnerClass:"test-code",reasons:i};if(s("schema","script"))return o("schema or contract file changes with a script or generated-code path"),{partnerClass:"schema-script",reasons:i};if(s("model","view"))return o("model or state path changes with a view or component path"),{partnerClass:"model-view",reasons:i};if(s("config","code"))return o("configuration file changes with executable source"),{partnerClass:"config-code",reasons:i};let a=lK(n.tokens,r.tokens).filter(c=>!aK.has(c));return uE(e,t)||a.length>=2?(o(uE(e,t)?"both files live in the same directory":`files share feature tokens: ${a.slice(0,4).join(", ")}`),{partnerClass:"same-feature",reasons:i}):(o("no specific relationship pattern matched"),{partnerClass:"unknown",reasons:i})}function Wz(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!sK.has(t.partnerClass))return;let r=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${uK(r)}`,files:r,reason:`${t.partnerClass} pair changed together ${e.together}x with ${Math.round(e.confidence*100)}% confidence; declare it if future edits should require both sides.`}}function Vz(e,t=Ae(e),n=dE(e)){return(r,i)=>Zz(t,n,r,i)}var Yz=/(?:^|\/)(?:locales|i18n)\//i;function cE(e){return Yz.test(e)}function Jz(e,t){return cE(e)&&cE(t)?!0:Xz(e,t)}function Xz(e,t){if(!e.endsWith(".json")||!t.endsWith(".json"))return!1;let n=e.lastIndexOf("/"),r=t.lastIndexOf("/");if(n<0||r<0)return!1;let i=e.slice(0,n),o=t.slice(0,r);if(i===o)return!1;let s=e.slice(n+1),a=t.slice(r+1);if(s!==a)return!1;let c=i.lastIndexOf("/"),l=o.lastIndexOf("/"),u=c>=0?i.slice(0,c):"",d=l>=0?o.slice(0,l):"";return u===d}function Qz(e,t){let n=e.lastIndexOf("/"),r=t.lastIndexOf("/");if(e.slice(0,n)!==t.slice(0,r))return!1;let i=e.slice(n+1).split(".")[0],o=t.slice(r+1).split(".")[0];return i!==""&&i===o}function dE(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function Zz(e,t,n,r){return e.get(n)?.has(r)===!0||e.get(r)?.has(n)===!0?!0:t.some(i=>i.has(n)&&i.has(r))}var eK=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,tK=/(?:^|\/)(?:\.[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,nK=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,rK=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,iK=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,oK=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,sK=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),aK=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 lE(e){let t=e.replace(/\\/g,"/"),n=new Set;return eK.test(t)&&n.add("doc"),tK.test(t)&&n.add("config"),nK.test(t)&&n.add("schema"),rK.test(t)&&n.add("script"),iK.test(t)&&n.add("model"),oK.test(t)&&n.add("view"),q(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:cK(t)}}function uE(e,t){let n=e.lastIndexOf("/"),r=t.lastIndexOf("/"),i=n>=0?e.slice(0,n):"",o=r>=0?t.slice(0,r):"";return i!==""&&i===o}function cK(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 lK(e,t){let n=new Set(t);return[...new Set(e.filter(r=>n.has(r)))].sort()}function uK(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}function Vc(e,t){let n=dK(e,t)??mK(e,t)??pK(e,t)??fK(e,t);return gK(e,n,t)}function dK(e,t){let n=-1,r=null;for(let i=0;i<=t;i+=1){let o=Xm(e[i]??"");o&&(r===null?(r=o,n=i):o===r&&(r=null,n=-1))}if(r===null||n<0)return null;for(let i=t+1;i<e.length;i+=1)if(Xm(e[i]??"")===r)return{start:n,end:i+1};return{start:n,end:e.length}}function Xm(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function mK(e,t){if(!Kc(e[t]??""))return null;let n=t;for(;n>0&&Kc(e[n-1]??"");)n-=1;let r=t+1;for(;r<e.length&&Kc(e[r]??"");)r+=1;return{start:n,end:r}}function Kc(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function pK(e,t){let n=t;for(;n>=0;){let o=e[n]??"";if(Wc(o)!==null)break;if(Qm(o)!==null)return null;n-=1}if(n<0)return null;let r=Wc(e[n]??"");if(r===null)return null;let i=n+1;for(;i<e.length;){let o=e[i]??"",s=Wc(o);if(s!==null){if(s<=r)break;i+=1;continue}if(Qm(o)!==null)break;i+=1}return{start:n,end:i}}function Wc(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function fK(e,t){let n=e[t]??"";if(pE(n)||n.trim().length===0)return{start:t,end:t+1};let r=t;for(;r>0&&mE(e[r-1]??"");)r-=1;let i=t+1;for(;i<e.length&&mE(e[i]??"");)i+=1;return{start:r,end:i}}function mE(e){return Qm(e)===null}function Qm(e){return e.trim().length===0?"blank":pE(e)?"heading":Xm(e)?"fence":Kc(e)?"table":Wc(e)!==null?"list":null}function pE(e){return/^#{1,6}\s+/.test(e.trim())}function gK(e,t,n){let{start:r,end:i}=t;if(i-r>40){let s=Math.floor(20);r=Math.max(r,n-s),i=Math.min(i,r+40),r=Math.max(t.start,i-40)}let o=e.slice(r,i).join(`
374
- `).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}function Jr(e,t){return t.filter(n=>e.includes(n))}var hK=/<!--\s*scip-query:\s*snapshot\s*-->/i;function fE(e,t){if((e.config.docs?.snapshotPaths??[]).some(i=>ur(i,t)))return!0;let r=W(e,t);return r.length>0&&hK.test(r)}var gE={classifyCitation:bK,citationContexts:SK,citationKindLabel:CK,citationRemediation:xK,referenceTargets:RK,hasLineAnchoredCitation:yK};function yK(e){return e.some(t=>(t.lineReferences?.length??0)>0)}function bK(e){let t=e.join(`
375
- `).toLowerCase(),n=[],r=Jr(t,[".scipquery","declaredcouplings","suppression","suppressions","config","configuration","json"]);if(r.length>0)return n.push(`configuration/example terms near citation: ${r.join(", ")}`),{citationKind:"configuration-example",actionTier:"support",reasons:n};let i=Jr(t,["accepted","intentional","intentionally","retained","historical"]);if(i.length>0)return n.push(`intentional-record terms near citation: ${i.join(", ")}`),{citationKind:"intentional-record",actionTier:"support",reasons:n};let o=Jr(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 SK(e,t,n){let r=W(e,t);if(!r&&!xt(e.config.projectRoot,t))return[];let i=r.split(/\r?\n/),o=n.flatMap(vK),s=[];for(let a=0;a<i.length;a+=1){let c=i[a]??"";o.some(l=>c.includes(l))&&s.push(Vc(i,a))}return s}function vK(e){let t=e.split("/");return[e,`./${e}`,t.slice(-3).join("/"),t.slice(-2).join("/")].filter((n,r,i)=>n.length>0&&i.indexOf(n)===r)}function CK(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 xK(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 RK(e,t,n){let r=jc(n),i=new Set;for(let o of t)EK(e,o,r.get(o)??[])&&i.add(o);return i}function EK(e,t,n){if(!IK.test(t)||!xt(e.config.projectRoot,t))return!0;if(n.length===0)return!1;let r=Ye(e.config.projectRoot,t,{inputKind:"changed source file"}).split(/\r?\n/),i=wK(r);for(let o of n)for(let s=o.startLine;s<=o.endLine;s+=1)if((r[s]??"").trim()!==""&&!i.has(s))return!0;return!1}var IK=/\.(?:[cm]?[jt]sx?)$/i;function wK(e){let t=new Set,n=!1;for(let r=0;r<e.length;r+=1){let i=e[r].trim();!n&&LK(i)&&(n=!0),n&&(t.add(r),i.endsWith(";")&&(n=!1))}return t}function LK(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}var hE=mt({kind:"doc-path-evidence",invalidation:Te("doc-path-evidence"),serialize:HK,deserialize:UK}),hs=/\.(?:md|mdx|rst|txt)$/i;function PK(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var DK=3,MK=/([A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6})(?::([1-9][0-9]*))?\b/g;function TK(e,t={}){let{doc:n,limit:r=20,minCoupling:i=DK,includeSnapshotExcluded:o=!1}=t,s=NK(e,t.historyMode??"bounded");if(!s)return{available:!1,commitsAnalyzed:0,docsScanned:0,findings:[]};let a=[];for(let c of s.docFiles){if(n!==void 0&&!c.includes(n)||n===void 0&&!_K(e,c)||n!==void 0&&!xt(e.config.projectRoot,c))continue;let l=fE(e,c);if(l&&!o)continue;let{value:u,estimated:d}=AK(e,c,s.changeTimes.get(c)),m=FK(e,c),p=new Map,{resolved:f,broken:g,citations:h}=BK(e,c,s.tracked,s.trackedBySuffix,s.everSeenInHistory),b=new Map(h.map(y=>[y.file,y]));for(let y of f){if(y===c||hs.test(y))continue;let x=(s.changeTimes.get(y)??[]).filter(C=>C>u).length;if(x===0)continue;let v=b.get(y);p.set(y,{file:y,evidence:"reference",coChanges:0,changesSinceDocUpdate:x,...Zm("reference",m,v?.contexts),citationContexts:v?.contexts,citedLines:v?.lineReferences})}for(let[y,x]of s.coupling.get(c)??[]){if(x<i||!s.tracked.has(y))continue;let v=(s.changeTimes.get(y)??[]).filter(R=>R>u).length;if(v===0)continue;let C=p.get(y);C?(C.evidence="both",C.coChanges=x,Object.assign(C,Zm("both",m,C.citationContexts))):p.set(y,{file:y,evidence:"co-change",coChanges:x,changesSinceDocUpdate:v,...Zm("co-change",m)})}if(p.size===0&&g.length===0)continue;let S=[...p.values()].sort((y,x)=>x.changesSinceDocUpdate-y.changesSinceDocUpdate);a.push({doc:c,docLastChangedAt:u,staleness:S.reduce((y,x)=>y+x.changesSinceDocUpdate,0)+g.length*10,subjects:S.slice(0,8),brokenReferences:g,...l?{snapshotExcluded:!0}:{},...d?{docLastChangedAtEstimated:!0}:{}})}return a.sort((c,l)=>l.staleness-c.staleness),{available:!0,commitsAnalyzed:s.historyCommitCount,docsScanned:s.docFiles.length,findings:a.slice(0,r)}}function AK(e,t,n){if(n&&n.length>0)return{value:Math.max(...n),estimated:!1};try{return{value:Math.floor(As(e.config.projectRoot,t).mtimeMs/1e3),estimated:!0}}catch(r){if(xt(e.config.projectRoot,t))throw r;return{value:0,estimated:!1}}}function FK(e,t){let n=W(e,t).slice(0,6e3);if(!n)return{docIntent:"unknown",reasons:["doc text unavailable"]};let r=`${t}
376
- ${n}`.toLowerCase(),i=Jr(r,["historical note","historical record","history note","retrospective","postmortem","post-mortem","archived","archive","previously","legacy","recorded","record of","snapshot","as of","migration note","decision record"]);if(i.length>0)return{docIntent:"historical-note",reasons:[`historical-note terms: ${i.join(", ")}`]};let o=Jr(r,["current","standard","standards","must","should","policy","guide","guidance","workflow","contract","invariant","source of truth"]);return o.length>0?{docIntent:"current-guidance",reasons:[`current-guidance terms: ${o.join(", ")}`]}:{docIntent:"unknown",reasons:["no current-guidance or historical-note markers found"]}}function Zm(e,t,n=[]){let r=e==="co-change"||n.length===0?null:gE.classifyCitation(n);return{actionTier:kK(e,t.docIntent,r?.actionTier),docIntent:t.docIntent,docIntentReasons:t.reasons,...r?{citationKind:r.citationKind,citationKindReasons:r.reasons}:{}}}function kK(e,t,n){return t==="historical-note"?"support":n||(e==="co-change"?"signal":"direct")}function NK(e,t){let n=Ht(e,{historyMode:t}),r=n.commitHistory();if(!r)return null;let i=n.trackedFiles()??new Set,o=new Map,s=new Map,a=new Set;for(let c of r.commits){let l=[...new Set(c.files)],u=l.filter(m=>hs.test(m)),d=l.filter(m=>!hs.test(m));for(let m of l){a.add(m);let p=o.get(m)??[];p.push(c.timestamp),o.set(m,p)}for(let m of u){let p=s.get(m);p||(p=new Map,s.set(m,p));for(let f of d)p.set(f,(p.get(f)??0)+1)}}return{changeTimes:o,coupling:s,docFiles:[...i].filter(c=>hs.test(c)),everSeenInHistory:a,historyCommitCount:r.commits.length,tracked:i,trackedBySuffix:OK(i)}}function _K(e,t){return hs.test(t)&&!PK(t)&&xt(e.config.projectRoot,t)}function OK(e){let t=new Map;for(let n of e){let r=n.split("/");for(let i of[2,3]){if(r.length<i)continue;let o=r.slice(-i).join("/"),s=t.get(o)??[];s.push(n),t.set(o,s)}}return t}function BK(e,t,n,r,i){let o=new Set,s=new Set,a=$K(e,t);if(!a)return{resolved:o,broken:[],citations:[]};let c=a.candidates,l=a.contextsByCandidate,u=a.lineReferencesByCandidate,d=new Map,m=new Map,p=(f,g)=>{let h=l.get(g);if(h&&h.length>0){let S=d.get(f)??[];S.push(...h),d.set(f,yE(S).slice(0,3))}let b=u.get(g);b&&b.length>0&&m.set(f,ep([...m.get(f)??[],...b]))};for(let f of c){if(n.has(f)){o.add(f),p(f,f);continue}let g=r.get(f);if(g&&g.length===1){o.add(g[0]),p(g[0],f);continue}g&&g.length>1||i.has(f)&&s.add(f)}return{resolved:o,broken:[...s],citations:[...d].map(([f,g])=>({file:f,contexts:g,lineReferences:m.get(f)}))}}function $K(e,t,n){let r=n;if(r===void 0&&(r=W(e,t),!r&&!xt(e.config.projectRoot,t)))return null;let i=Et(e,t,r),o=hE.read(e,t,i);if(o)return o;let s=jK(r);return hE.write(e,t,i,s),s}function jK(e){let t=e.split(/\r?\n/),n=new Set,r=new Map,i=new Map;for(let o=0;o<t.length;o+=1){let s=t[o]??"";for(let a of s.matchAll(MK)){let c=(a[1]??"").replace(/^\.?\//,"");if(c.length===0)continue;n.add(c);let l=a[2]?Number(a[2]):null;l!==null&&Number.isSafeInteger(l)&&i.set(c,ep([...i.get(c)??[],l]));let u=Vc(t,o);if(u.length===0)continue;let d=r.get(c)??[];d.push(u),r.set(c,yE(d).slice(0,3))}}return{candidates:[...n],contextsByCandidate:r,lineReferencesByCandidate:i}}function HK(e){let t={candidates:e.candidates,contextsByCandidate:[...e.contextsByCandidate.entries()],lineReferencesByCandidate:[...e.lineReferencesByCandidate.entries()]};return JSON.stringify(t)}function UK(e){try{let t=JSON.parse(e);if(!bf(t))return null;let n=Zi(t.candidates),r=GK(t.contextsByCandidate),i=qK(t.lineReferencesByCandidate);return!n||!r?null:{candidates:n,contextsByCandidate:new Map(r),lineReferencesByCandidate:new Map(i??[])}}catch{return null}}function qK(e){if(e===void 0)return[];if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string"||!Array.isArray(n[1]))return null;let r=[];for(let i of n[1]){if(typeof i!="number"||!Number.isSafeInteger(i))return null;r.push(i)}t.push([n[0],ep(r)])}return t}function GK(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string")return null;let r=Zi(n[1]);if(!r)return null;t.push([n[0],r])}return t}function yE(e){let t=[];for(let n of new Set(e))t.some(r=>zK(r,n))||t.push(n);return t}function ep(e){return[...new Set(e)].sort((t,n)=>t-n)}function zK(e,t){if(e===t)return!0;let n=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),r=t.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),i=Math.min(n.length,r.length);if(i===0)return!1;if(i<3)return e.includes(t)||t.includes(e);let o=new Set(r),s=n.filter(a=>o.has(a)).length;return s>=3&&s/i>=.6}import{createHash as KK}from"crypto";var WK=3;function ys(e,t={}){let{scope:n,maxLoc:r=15,minLoc:i=WK,limit:o,scanLimit:s}=t,a=tE(e),c=VK(e,{scope:n,maxLoc:r,scanLimit:s}).map(u=>YK(e,u,a,i)).filter(u=>u!==null),l=vE(c);return o?l.slice(0,o):l}function SE(e){let t=ln(e);return fn(t).replace(/\s+/g,"")}function vE(e){let t=new Map;for(let r of e){if(r.normalizedBody.length<8)continue;let i=XK(r.normalizedBody),o=t.get(i)??[];o.push(r),t.set(i,o)}let n=[];for(let[r,i]of t){let o=new Set(i.map(a=>a.file));if(i.length<2||o.size<2)continue;let s=[...i].sort(QK).map(({normalizedBody:a,...c})=>c);n.push({hash:r,canonical:s[0],functions:s})}return n.sort((r,i)=>{let o=i.functions.length-r.functions.length;if(o!==0)return o;let s=bE(i)-bE(r);return s!==0?s:r.canonical.file.localeCompare(i.canonical.file)}),n}function VK(e,t){let n=ve(e,{scope:t.scope}).filter(r=>r.isFunctionLike&&!e.isIgnored(r.relativePath)).filter(r=>!Bs(e,r.relativePath,r.startLine,"similar")).filter(r=>ee(r)<=t.maxLoc);return n.sort((r,i)=>ee(i)-ee(r)||r.relativePath.localeCompare(i.relativePath)),he(n,t.scanLimit)}function YK(e,t,n,r){let i=Ut(e,t);if(!i||JK(i)<r)return null;let o=tp(e,t);return o?{symbol:t.symbol,shortName:T(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:ee(t),ageCommits:n?.get(t.relativePath)?.commitsAgo??null,normalizedBody:o}:null}function tp(e,t){let n=Ut(e,t);return n&&SE(n)||null}function Ut(e,t){let n=V(e,t.relativePath);return n.length===0?null:n.slice(t.startLine,t.endLine+1).join(`
377
- `)}function ln(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(t>=0&&n>t)return e.slice(t+1,n);let r=e.indexOf("=>");return r>=0?e.slice(r+2).replace(/;+\s*$/,""):e}function JK(e){return ln(e).split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0).length}function XK(e){return KK("sha256").update(e).digest("hex").slice(0,16)}function QK(e,t){let n=e.ageCommits??-1;return(t.ageCommits??-1)-n||e.file.localeCompare(t.file)||e.startLine-t.startLine}function bE(e){return e.functions.reduce((t,n)=>t+n.loc,0)}var ZK=new Set(Wt());function eW(e,t={}){let{includeHomonyms:n=!1,limit:r}=t,i=Yc(e,t).filter(o=>o.relationship==="divergent"||n&&o.relationship==="homonym");return r?i.slice(0,r):i}function Yc(e,t={}){let{scope:n,minSimilarity:r=.3,scanLimit:i}=t,o=rW(e,{scope:n,scanLimit:i});return RE(o,{minSimilarity:r,isDelegatePair:IW(e)}).filter(s=>!s.members.some(a=>Bs(e,a.file,a.startLine,"twin")))}function RE(e,t={}){let n=t.minSimilarity??.3,r=t.isDelegatePair,i=e.filter(l=>!ME(l.leaf)&&!fW(l.leaf)&&q(l.file)!=="test"&&!He(l.symbol)&&!IE(l.symbol)&&!wE(l.symbol,l.leaf)),{recordsByLeaf:o,recordOrder:s}=N("twin-drift.group-by-leaf",()=>tW(i),()=>({records:i.length})),a=N("twin-drift.cluster-leaf-names",()=>EE([...o.keys()]),()=>({leaves:o.size}));return N("twin-drift.compare-clusters",()=>{let l=[];for(let u of a){let d=nW(u,o,s);if(d.length<2||new Set(d.map(S=>S.file)).size<2)continue;let m=null,p=!1,f=!1,g=new Set;for(let S=0;S<d.length;S+=1)for(let y=S+1;y<d.length;y+=1){let x=d[S],v=d[y];if(x.file===v.file||!bW(x,v)||r?.(x,v,d)||r?.(v,x,d))continue;if(p=!0,g.add(x.symbol),g.add(v.symbol),x.normalizedBody===v.normalizedBody){f=!0;continue}let C=uW(x.tokens,v.tokens);(!m||C>m.similarity)&&(m={a:x,b:v,similarity:C})}if(!p)continue;let h=d.filter(S=>g.has(S.symbol)).sort((S,y)=>S.file.localeCompare(y.file)||S.startLine-y.startLine).map(lW);if(!m){l.push({leaf:xE(u),relationship:f?"identical":"homonym",maxDivergence:0,members:h});continue}let b=m.similarity>=n?"divergent":"homonym";l.push({leaf:xE(u),relationship:b,maxDivergence:Math.round((1-m.similarity)*1e3)/1e3,members:h,...b==="divergent"?{firstDivergentTokens:dW(m.a.tokens,m.b.tokens)}:{}})}return l},()=>({clusters:a.length,records:i.length})).sort((l,u)=>u.members.length-l.members.length||u.maxDivergence-l.maxDivergence||l.leaf.localeCompare(u.leaf))}function tW(e){let t=new Map,n=new Map;for(let[r,i]of e.entries()){let o=t.get(i.leaf)??[];o.push(i),t.set(i.leaf,o),n.set(i,r)}return{recordsByLeaf:t,recordOrder:n}}function nW(e,t,n){let r=[...e].flatMap(i=>t.get(i)??[]);return e.size>1&&r.sort((i,o)=>(n.get(i)??0)-(n.get(o)??0)),r}function rW(e,t){let n=N("twin-drift.load-definitions",()=>ve(e,{scope:t.scope}).filter(o=>iW(o)&&!e.isIgnored(o.relativePath)).filter(o=>!Pi(o.relativePath)));N("twin-drift.sort-definitions",()=>n.sort((o,s)=>o.relativePath.localeCompare(s.relativePath)||o.startLine-s.startLine),()=>({definitions:n.length}));let r=he(n,t.scanLimit),i=N("twin-drift.select-candidates",()=>oW(r),()=>({scanned:r.length}));return N("twin-drift.build-records",()=>{let o=[];for(let s of i){let a=sW(e,s);a&&o.push(a)}return o},()=>({candidates:i.length,scanned:r.length}))}function iW(e){return e.isFunctionLike?e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&ZK.has(e.kind):!0:!1}function oW(e){let t=e.filter(o=>o.leaf&&!ME(o.leaf)&&!He(o.symbol)&&!IE(o.symbol)&&!wE(o.symbol,o.leaf)),n=new Map;for(let o of t){let s=n.get(o.leaf)??[];s.push(o),n.set(o.leaf,s)}let r=EE([...n.keys()]),i=new Set;for(let o of r){let s=[...o].flatMap(a=>n.get(a)??[]);if(!(s.length<2)&&!(new Set(s.map(a=>a.relativePath)).size<2)&&!s.every(a=>q(a.relativePath)==="test"))for(let a of s)i.add(a)}return e.filter(o=>i.has(o))}function sW(e,t){if(!t.leaf)return null;let n=Ut(e,t);if(!n||!Xe(t.symbol)&&!aW(n,t.leaf))return null;let r=fn(ln(n)),i=r.replace(/\s+/g,"");if(!i||i.length<8)return null;let o=r.match(cW)??[];return o.length===0?null:{leaf:t.leaf,symbol:t.symbol,shortName:T(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:ee(t),normalizedBody:i,tokens:o,isThinForwarder:PE(r)}}function aW(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 cW=/[A-Za-z_$][A-Za-z0-9_$]*|\d+(?:\.\d+)?|[^\sA-Za-z0-9_$]/g;function lW(e){return{symbol:e.symbol,shortName:e.shortName,file:e.file,startLine:e.startLine,endLine:e.endLine,loc:e.loc}}function uW(e,t){let n=new Set(e),r=new Set(t);if(n.size===0&&r.size===0)return 1;if(n.size===0||r.size===0)return 0;let i=0;for(let s of n)r.has(s)&&(i+=1);let o=n.size+r.size-i;return o===0?0:i/o}function dW(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;let i=e.slice(r,r+6).join(" "),o=t.slice(r,r+6).join(" ");return!i&&!o?"(bodies differ only in trailing length)":`A: ${i||"(end)"} | B: ${o||"(end)"}`}function EE(e){let t=new Map;for(let s of e)t.set(s,s);let n=s=>{let a=s;for(;t.get(a)!==a;)a=t.get(a);let c=s;for(;t.get(c)!==a;){let l=t.get(c);t.set(c,a),c=l}return a},r=(s,a)=>{let c=n(s),l=n(a);c!==l&&t.set(c,l)},i=new Map;for(let s of e){let a=s.slice(0,2).toLowerCase(),c=i.get(a)??[];c.push(s),i.set(a,c)}for(let s of i.values())for(let a=0;a<s.length;a+=1)for(let c=a+1;c<s.length;c+=1)mW(s[a],s[c])&&r(s[a],s[c]);let o=new Map;for(let s of e){let a=n(s),c=o.get(a)??new Set;c.add(s),o.set(a,c)}return[...o.values()]}function mW(e,t){return e===t||e.toLowerCase()===t.toLowerCase()?!0:e.length<8||t.length<8||Math.abs(e.length-t.length)>2||pW(e.toLowerCase(),t.toLowerCase())/Math.max(e.length,t.length)<.8?!1:SW(e.toLowerCase(),t.toLowerCase(),2)}function pW(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;return r}function fW(e){return/^[A-Z][A-Z0-9_]*$/.test(e)||/^__[^_].*__$/.test(e)||gW.has(e.toLowerCase())}var gW=new Set(["main","row"]),hW=new Set(["app","component","components","feature","features","impl","index","lib","route","routes","shared","src","tsx","typescript","ui"]);function IE(e){return e.startsWith("rust-analyzer ")&&/\/(?:tests?|benches?)\//.test(e)}var yW=new Set(["default","new","reset"]);function wE(e,t){return e.startsWith("rust-analyzer ")&&yW.has(t.toLowerCase())}function bW(e,t){if(e.leaf.toLowerCase()!==t.leaf.toLowerCase()||e.leaf.length>4)return!0;let n=CE(e);return[...CE(t)].some(r=>n.has(r))}function CE(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&&!hW.has(n)))}function SW(e,t,n){if(Math.abs(e.length-t.length)>n)return!1;let r=Array.from({length:t.length+1},(i,o)=>o);for(let i=1;i<=e.length;i+=1){let o=[i],s=o[0];for(let a=1;a<=t.length;a+=1){let c=e[i-1]===t[a-1]?0:1,l=Math.min(r[a]+1,o[a-1]+1,r[a-1]+c);o.push(l),s=Math.min(s,l)}if(s>n)return!1;r=o}return r[t.length]<=n}function LE(e){return PE(fn(ln(e)))}function PE(e){let t=e.trim();if(!t||vW.test(t))return!1;let n=RW(t);return n.length===0||n.length>2?!1:xW(n[n.length-1])}var vW=/\b(?:if|else|for|while|switch|try|catch|do)\b/,CW=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^[\]]*\])*\((?:[^()]|\([^()]*\))*\)$/;function xW(e){let t=e.trim().replace(/^return\s+/,"").replace(/^await\s+/,"").replace(/;\s*$/,"").trim();return CW.test(t)}function RW(e){let t=[],n=0,r="";for(let i of e){if(i==="("||i==="["||i==="{"?n+=1:(i===")"||i==="]"||i==="}")&&(n=Math.max(0,n-1)),i===";"&&n===0){t.push(r),r="";continue}r+=i}return r.trim()&&t.push(r),t.map(i=>i.trim()).filter(i=>i.length>0)}var EW=3;function IW(e){let t=new Map;return(n,r,i)=>{if(!n.isThinForwarder)return!1;let o=`${n.symbol}\0${r.symbol}`,s=t.get(o);if(s!==void 0)return s;let a=DE(e,n,r,i,EW,new Set);return t.set(o,a),a}}function DE(e,t,n,r,i,o){if(i<=0||o.has(t.symbol)||(o.add(t.symbol),(zt(e,t.file)??[]).filter(c=>c.line>=t.startLine&&c.line<=t.endLine&&c.calleeLeaf===n.leaf).length===0))return!1;let a=new Set(ae(e,t.file).filter(c=>c.sourcePath&&(c.kind!=="namespace"||c.usedMembers.includes(n.leaf))).map(c=>c.sourcePath));if([...a].some(c=>_e(c,n.file)))return!0;for(let c of r)if(!(c.symbol===t.symbol||c.symbol===n.symbol||!c.isThinForwarder)&&[...a].some(l=>_e(l,c.file))&&DE(e,c,n,r,i-1,o))return!0;return!1}function ME(e){return e.startsWith("<")&&e.endsWith(">")}function xE(e){return[...e].sort()[0]}import{dirname as jW,isAbsolute as HW,relative as UW,resolve as qW}from"path";import{basename as TE,extname as AE}from"path";function Jc(e,t,n,r,i,o){let s=new Set;LW(e,t,n,r)&&s.add(i);for(let a of o)a.value&&wW(s,a.label,a.value);return[...s].slice(0,6)}function wW(e,t,n){let r=PW(n);t.endsWith("name")&&DW(r)&&e.add(`${t} has type-guard boundary shape`);for(let i of r){let o=MW.get(i);o&&e.add(`${t} has ${o} term: ${i}`)}}function LW(e,t,n,r){if(n<=0)return!1;let i=V(e,t);if(i.length===0)return!1;for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(i[o]??"").trim();if(s!==""){if(_s(s)===r)return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function PW(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 DW(e){return e.some(t=>TW.has(t))&&e.some(t=>AW.has(t))}var MW=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"]]),TW=new Set(["can","has","is","should"]),AW=new Set(["access","api","auth","collision","expired","input","keyboard","overlap","permission","permissions","policy","projectile","response","route","routes","scope"]);function bs(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new H(e);return kt({candidates:()=>$W(e,s,n,r),orderCandidates:Za,scanLimit:o,profile:{name:"passthrough-candidates"},prepare:a=>s.calleeMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,c)=>FW(e,a,c.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:i})}function FW(e,t,n){let r=BW(n);if(r.size!==1||!Ef(e,t.relativePath,t.startLine,t.endLine))return null;let[,i]=[...r.entries()][0],o=kW(e,t,i),s=_W(e,t),a=o.length>0||s.length>0?"signal":"direct";return{symbol:t.symbol,shortName:T(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:ee(t),forwardsTo:i.symbol,forwardsToShort:T(i.symbol),forwardsToFile:i.file,actionTier:a,boundaryEvidence:o,publicFacadeEvidence:s,recommendation:NW(a,o,s)}}function kW(e,t,n){return Jc(e,t.relativePath,t.startLine,"passthrough","explicit ignore-passthrough comment",[{label:"passthrough name",value:T(t.symbol)},{label:"callee name",value:T(n.symbol)},{label:"passthrough module",value:TE(t.relativePath,AE(t.relativePath))},{label:"callee module",value:TE(n.file,AE(n.file))}])}function NW(e,t,n){if(e==="signal"){if(n.length>0)return`Review the public API before inlining; public-facade evidence: ${n.slice(0,2).join("; ")}.`;let r=t.filter(OW);return r.length>0?`Review the public API before inlining; public-surface evidence: ${r.slice(0,2).join("; ")}.`:`Review the boundary before inlining; boundary evidence: ${t.slice(0,2).join("; ")}.`}return"Inline or remove this passthrough unless an external API or runtime registration depends on the forwarding name."}function _W(e,t){return ft(e,t)?En(e,t.relativePath)?["exported passthrough is declared on the package public surface"]:Fe(e,t.symbol,t.relativePath)?["exported passthrough matches configured or framework public entry surface"]:[]:[]}function OW(e){return e.includes("public surface")}function BW(e){let t=e.some(r=>Se(r.symbol))?e.filter(r=>Se(r.symbol)):e,n=new Map;for(let r of t)n.has(r.symbol)||n.set(r.symbol,r);return n}function $W(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:3,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0}).filter(i=>!js(e,i))}var GW=new Set(Wt());function zW(e,t){return`tests/generated/twin-ab/${FE(e)}-vs-${FE(t)}.test.ts`}function FE(e){return(e.split(/[/#]/).pop()||e).replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"symbol"}function KW(e,t,n,r){let{refA:i,refB:o,outFile:s}=typeof t=="string"?{refA:t,refB:n,outFile:r}:t;if(typeof i!="string"||typeof o!="string"||typeof s!="string")throw new TypeError("twinAb requires refA, refB, and outFile.");if(!HW(s))throw new TypeError("twinAb outFile must be an absolute path.");let a=kE(e,i);if(!a.ok)return a;let c=kE(e,o);if(!c.ok)return c;let l=a.symbol.paramCount===null||c.symbol.paramCount===null?null:a.symbol.paramCount===c.symbol.paramCount,u=VW(a.symbol,c.symbol,e.config.projectRoot,s,l);return{ok:!0,a:a.symbol,b:c.symbol,signatureCompatible:l,testSource:u}}function kE(e,t){let r=Qe(e,t).match;if(!r)return{ok:!1,reason:`${t} does not resolve to an indexed symbol.`};let o=e.get("SELECT kind FROM global_symbols WHERE id = ?",r.symbolId)?.kind??null;if(!(o!==null?GW.has(o):Se(r.symbol)))return{ok:!1,reason:`${t} resolves to ${T(r.symbol)}${o!==null?` with SCIP kind ${so(o)}`:""} \u2014 twin-ab compares call outputs, so both referents must be functions or methods.`};if(!ft(e,r))return{ok:!1,reason:`${t} (${T(r.symbol)} at ${r.relativePath}:${r.startLine+1}) is not exported \u2014 twin-ab needs an importable named binding for both twins.`};let a=e.get("SELECT documentation FROM global_symbols WHERE id = ?",r.symbolId),c=li(ui(a?.documentation??null));return{ok:!0,symbol:{ref:t,symbol:r.symbol,shortName:z(r.symbol)||T(r.symbol),file:r.relativePath,startLine:r.startLine,signature:c,paramCount:c?WW(c):null}}}function WW(e){let t=e.indexOf("(");if(t===-1)return null;let n=0,r=-1;for(let a=t;a<e.length;a+=1){let c=e[a];if(c==="(")n+=1;else if(c===")"&&(n-=1,n===0)){r=a;break}}if(r===-1)return null;let i=e.slice(t+1,r).trim();if(!i)return 0;let o=1,s=0;for(let a of i)a==="("||a==="["||a==="{"?s+=1:a===")"||a==="]"||a==="}"?s=Math.max(0,s-1):a===","&&s===0&&(o+=1);return o}function NE(e,t,n){let r=jW(t),i=qW(e,n),s=UW(r,i).replace(/\\/g,"/").replace(/\.tsx?$/,".js");return s.startsWith(".")?s:`./${s}`}function VW(e,t,n,r,i){let o=NE(n,r,e.file),s=NE(n,r,t.file),a=i===null?"Signature comparison: unknown (one or both signatures unavailable in the index) \u2014 check by hand.":i?"Signature comparison: param counts match.":"Signature comparison: param counts DIFFER \u2014 twins may not be directly comparable; check by hand.";return`/**
378
- * Generated by 'scip-query twin-ab'. Cleanup integrity scenario.
379
- * ("cross-examine same-concept twins"): where one concept is computed in
380
- * more than one place, feed both the same input and require the same
381
- * answer. Disagreement between twins means at least one is wrong \u2014
382
- * determine which before consolidating.
383
- *
384
- * Twin A: ${e.shortName} (${e.file}:${e.startLine+1})
385
- * ${e.signature??"(signature unavailable)"}
386
- * Twin B: ${t.shortName} (${t.file}:${t.startLine+1})
387
- * ${t.signature??"(signature unavailable)"}
388
- * ${a}
389
- *
390
- * Fill in the TODO input table below with inputs both twins should agree
391
- * on, then run this file with vitest.
392
- */
393
- import { describe, expect, it } from 'vitest';
394
- import { ${e.shortName} as twinA } from '${o}';
395
- import { ${t.shortName} as twinB } from '${s}';
396
-
397
- // TODO: fill in shared inputs both twins should agree on \u2014 one arg array per call.
398
- const inputs: any[][] = [
399
- // [/* arg1, arg2, ... */],
400
- ];
401
-
402
- // Cast to a variadic signature so the input table can hold any arg shape \u2014
403
- // the real twins have fixed, non-rest parameter lists, and TS rejects
404
- // spreading a generic args array into those (TS2556) even when the array
405
- // itself is 'any'; casting the callee's signature, not the args, satisfies
406
- // the checker without weakening the twins' real exported types elsewhere.
407
- const callA = twinA as (...callArgs: any[]) => any;
408
- const callB = twinB as (...callArgs: any[]) => any;
409
-
410
- describe.skipIf(inputs.length === 0)('twin-ab: ${e.shortName} vs ${t.shortName}', () => {
411
- it.each(inputs)('agrees on input %#', (...args) => {
412
- expect(callA(...args)).toEqual(callB(...args));
413
- });
414
- });
415
- `}var _E={caller:3,"entry-surface":2,rooted:1},YW=/not\s*yet\s*implement|not\s*implement|unimplement|\bnyi\b|\btodo\b|\bstub\b|not\s*supported|coming\s*soon/i,JW=/^throw\s+new\s+[\w.]*Error\s*\(([\s\S]*)\)\s*;?$/,XW=/^return(\s+(null|undefined|false|0|''|""|``|\[\]|\{\}))?\s*;?$/,QW=/\/\/\s*TODO\b|\/\*\s*TODO\b/i,ZW=/(?:=>|\))\s*(?::\s*[^{;=]+)?\s*\{\s*\}\s*;?\s*$/;function eV(e,t={}){let{scope:n,limit:r=30,scanLimit:i,semantic:o=!0}=t,s=new H(e),a=he(s.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),c=[];for(let p of a){let f=nV(e,p);f&&c.push(f)}if(c.length===0)return[];let l=sV(e,c,a),u=c.filter(p=>!l.has(p.def.symbol));if(u.length===0)return[];let d=Tn(e,s).forDefinitions(u.map(p=>p.def),{semantic:o}),m=[];for(let p of u){let g=d.get(p.def.symbolId)?.realConsumers.length??0,h=tV(e,p.def,g);h&&m.push({symbol:p.def.symbol,shortName:T(p.def.symbol),file:p.def.relativePath,startLine:p.def.startLine,endLine:p.def.endLine,loc:ee(p.def),stubKind:p.stubKind,reachability:h,callerFanIn:g,stubText:p.stubText})}return m.sort((p,f)=>_E[f.reachability]-_E[p.reachability]||f.callerFanIn-p.callerFanIn||p.file.localeCompare(f.file)||p.startLine-f.startLine),r?m.slice(0,r):m}function tV(e,t,n){return n>0?"caller":Fe(e,t.symbol,t.relativePath)?"rooted":Ue(e,t.relativePath)?"entry-surface":null}function nV(e,t){let n=Ut(e,t);if(!n)return null;let r=ln(n),i=r.trim();if(i==="")return!oV(n)||!ft(e,t)?null:{def:t,stubKind:"empty-body",stubText:"(empty body)"};let o=eo(r),s=fn(r),a=rV(o,s);if(a.length!==1)return null;let c=a[0];return iV(c)?{def:t,stubKind:"throw-stub",stubText:c.trim()}:QW.test(r)&&XW.test(c.trim())?{def:t,stubKind:"todo-return-default",stubText:i}:null}function rV(e,t){let n=[],r=0,i="";for(let o=0;o<t.length;o+=1){let s=t[o];if(s==="("||s==="["||s==="{"?r+=1:(s===")"||s==="]"||s==="}")&&(r=Math.max(0,r-1)),s===";"&&r===0){n.push(i),i="";continue}i+=e[o]??""}return i.trim()&&n.push(i),n.map(o=>o.trim()).filter(o=>o.length>0)}function iV(e){let t=JW.exec(e.trim());return t?YW.test(t[1]??""):!1}function oV(e){return ZW.test(e.trimEnd())}function sV(e,t,n){let r=new Set,i=new Set(t.map(a=>a.def.parentTypeName).filter(a=>a!==null));if(i.size===0)return r;let o=cV(e,i),s=new Map;for(let a of n){if(!a.parentTypeName)continue;let c=s.get(a.leaf)??new Set;c.add(a.parentTypeName),s.set(a.leaf,c)}for(let a of t){let c=a.def.parentTypeName;if(!c)continue;let l=o.get(c);if(!l||l.size===0)continue;let u=s.get(a.def.leaf)??new Set;[...l].every(m=>u.has(m))&&r.add(a.def.symbol)}return r}var aV=/\bclass\s+([A-Za-z_$][\w$]*)\s+extends\s+([A-Za-z_$][\w$]*)/g;function cV(e,t){let n=new Map;for(let r of Q(e,{includeIgnored:!1})){let i=W(e,r);if(i)for(let o of i.matchAll(aV)){let s=o[1],a=o[2];if(!s||!a||!t.has(a))continue;let c=n.get(a)??new Set;c.add(s),n.set(a,c)}}return n}var lV=/^(?:validate|verify|check|assert)(?:[A-Z].*)?$/,uV=/^(?:is|has)(?:[A-Z].*)?$/,dV=/[{,]\s*(?:ok|success|valid|isValid)\s*:\s*false\b/,np=/\breturn\b/g,mV=/\bfunction\b|=>|\)\s*(?::\s*[^{;=]+)?\s*\{/,pV=/\.(?:addIssue|push)\s*\(/;function fV(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new H(e),s=he(o.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),a=[];for(let c of s){let l=hV(e,c);l&&a.push({symbol:c.symbol,shortName:T(c.symbol),file:c.relativePath,startLine:c.startLine,endLine:c.endLine,loc:ee(c),...l})}return a.sort((c,l)=>c.file.localeCompare(l.file)||c.startLine-l.startLine||c.loc-l.loc),r?a.slice(0,r):a}function gV(e){return lV.test(e)?"imperative":uV.test(e)?"predicate":null}function hV(e,t){let n=gV(t.leaf);if(!n||ji(e,t))return null;let r=Ut(e,t);if(!r||!mV.test(r))return null;let i=K(e,t.relativePath)?.callables.find(s=>s.startLine===t.startLine&&s.endLine===t.endLine);if(n==="predicate"&&i?.paramCount===0)return null;if(LE(r)){let s=SV(e,t);return!s||$E(s.body,BE(s.snippet))||OE(s.body)?null:{nameKind:n,resolvedVia:"one-hop-delegate",delegateTarget:s.shortName}}let o=ln(r);return $E(o,BE(r))||OE(o)?null:{nameKind:n,resolvedVia:"direct"}}var yV=new Set(["if","for","while","switch","catch","function"]);function OE(e){let t=eo(e);for(let n of t.matchAll(/\b([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(/g))if(!yV.has(n[1]))return!0;return!1}function BE(e){let t=e.indexOf("=>");return t===-1?!1:!/^\s*\{/.test(e.slice(t+2))}function $E(e,t){let n=eo(e);if(/\bthrow\b/.test(n)||/\.reject\s*\(/.test(n)||dV.test(n)||pV.test(n))return!0;let r=bV(n);if(t&&r.length===0){let i=n.trim();return i!==""&&i!=="true"}for(let i of r)if(i!==""&&i!=="true")return!0;return!1}function bV(e){let t=[];np.lastIndex=0;let n;for(;n=np.exec(e);){let r=n.index+n[0].length,i=0,o=e.length;for(let s=r;s<e.length;s+=1){let a=e[s];if(a==="("||a==="["||a==="{")i+=1;else if(a===")"||a==="]"||a==="}"){if(i===0){o=s;break}i-=1}else if(a===";"&&i===0){o=s;break}}t.push(e.slice(r,o).trim()),np.lastIndex=o}return t}function SV(e,t){let n=Dt(e,t,{callableOnly:!0,limit:3,semanticEvidence:re}),r=[...new Set(n.map(c=>c.symbol))].filter(c=>c!==t.symbol);if(r.length!==1)return null;let o=Qe(e,r[0]).match;if(!o)return null;let s=U(e,o.relativePath).find(c=>c.symbolId===o.symbolId);if(!s)return null;let a=Ut(e,s);return a?{body:ln(a),snippet:a,shortName:T(s.symbol)}:null}var vV=60;function CV(e,t={}){let{scope:n,limit:r=30,scanLimit:i,rotDays:o=vV}=t,s=he(oi(e,{extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs"]}).filter(u=>q(u)==="test").filter(u=>!n||u.includes(n)).filter(u=>!e.isIgnored(u)).sort(),i),a=[],c=[],l=[];for(let u of s){let d=W(e,u);if(!d)continue;let m=vf(d),p=EV(d);for(let g of PV(m,p))p.add(g);let f=xV(m);for(let g of f){if(g.skip){c.push(NV(e,u,g,o));continue}if(g.kind==="describe")continue;let h=HE(d,g.argsStart),b=m.slice(g.argsStart,g.callEnd),S=d.slice(g.argsStart,g.callEnd);UE(b,p)||a.push({file:u,startLine:Ss(d,g.callStart),endLine:Ss(d,g.callEnd),title:h,severity:/\bawait\b/.test(b)?"low":"high"});let y=AV(b,S);y&&l.push({file:u,startLine:Ss(d,g.callStart),endLine:Ss(d,g.callEnd),title:h,echoedValue:y})}}return{assertionFree:r?a.slice(0,r):a,skipped:r?c.slice(0,r):c,mockEcho:r?l.slice(0,r):l}}var rp=/(?<!\.)\b(?:x(it|test|describe)|(it|test|describe)(?:\.\s*(skip|only|todo|each\s*\([^)]*\)))?)\s*\(/g;function xV(e){let t=[];rp.lastIndex=0;let n;for(;n=rp.exec(e);){let r=n[1],i=r??n[2];if(!i)continue;let o=n[3]?.split(/\s*\(/)[0],s=n.index,a=n.index+n[0].length-1,c=vs(e,a);rp.lastIndex=a+1,o!=="each"&&t.push({kind:i,skip:r!==void 0||o==="skip"||o==="todo",skipKind:o==="todo"?"todo":"skip",callStart:s,argsStart:a+1,callEnd:c+1})}return t}function vs(e,t){let n=0;for(let r=t;r<e.length;r+=1){let i=e[r];if(i==="(")n+=1;else if(i===")"&&(n-=1,n===0))return r}return e.length-1}function Ss(e,t){let n=0;for(let r=0;r<t&&r<e.length;r+=1)e[r]===`
416
- `&&(n+=1);return n}function HE(e,t){let n=e.slice(t,t+400),r=/^\s*(['"`])((?:\\.|(?!\1)[\s\S])*)\1/.exec(n);return r?r[2]:"(anonymous)"}var RV=new Set(["vitest","chai","jest","@jest/globals","assert","node:assert","node:assert/strict","assert/strict","uvu/assert","expect","chai-as-promised"]),jE=/import\s+(?:\*\s+as\s+(\w+)|\{([^}]*)\}|(\w+))\s+from\s+['"]([^'"]+)['"]/g;function EV(e){let t=new Set(["expect","assert"]);jE.lastIndex=0;let n;for(;n=jE.exec(e);){let[,r,i,o,s]=n;if(!(!s||!RV.has(s))&&(r&&t.add(r),o&&t.add(o),i))for(let a of i.split(",")){let c=a.trim().replace(/^type\s+/,"");if(!c)continue;let l=/^(\w+)\s+as\s+(\w+)$/.exec(c);t.add(l?l[2]:c)}}return t}function UE(e,t){if(/\.should\b/.test(e)||/\bawait\s+(?:[\w$.]+\.)?findBy[A-Z]\w*\s*\(/.test(e)||/\bawait\s+\w*waitFor(?:Text|Value|Condition|Result|Event)\s*\(/.test(e)||/\bthrow\b/.test(e))return!0;for(let n of t){let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`\\b${r}\\s*(?:<[^<>]*>)?\\s*[.(]`).test(e))return!0}return!1}var IV=/\bfunction\s+(\w+)\s*\(/g,wV=/\b(?:const|let)\s+(\w+)\s*=\s*(?:async\s*)?\(/g,LV=60;function PV(e,t){let n=new Set;for(let r of[IV,wV]){r.lastIndex=0;let i;for(;i=r.exec(e);){let o=i[1],s=i.index+i[0].length-1,a=vs(e,s),c=e.indexOf("{",a+1);if(c===-1||c-a>LV)continue;let l=DV(e,c),u=e.slice(c+1,l);UE(u,t)&&n.add(o)}}return n}function DV(e,t){let n=0;for(let r=t;r<e.length;r+=1){let i=e[r];if(i==="{")n+=1;else if(i==="}"&&(n-=1,n===0))return r}return e.length-1}var MV=/\bmock(?:ReturnValue|ResolvedValue)(?:Once)?\s*\(/g,ip=/\bexpect\s*\(/g,TV=/^\s*\.\s*(?:toBe|toEqual|toStrictEqual)\s*\(/,qE=/^(?:-?\d+(?:\.\d+)?|(['"`]).+\1)$/;function AV(e,t){let n=FV(e,t,MV);if(n.length===0)return null;let r=kV(e,t);for(let i of r)if(n.includes(i))return i;return null}function FV(e,t,n){let r=[];n.lastIndex=0;let i;for(;i=n.exec(e);){let o=i.index+i[0].length-1,s=vs(e,o),a=t.slice(o+1,s).trim();qE.test(a)&&r.push(a),n.lastIndex=s+1}return r}function kV(e,t){let n=[];ip.lastIndex=0;let r;for(;r=ip.exec(e);){let i=r.index+r[0].length-1,o=vs(e,i),s=e.slice(o+1),a=TV.exec(s);if(ip.lastIndex=o+1,!a)continue;let c=o+1+a[0].length-1,l=vs(e,c),u=t.slice(c+1,l).trim();qE.test(u)&&n.push(u)}return n}function NV(e,t,n,r){let i=W(e,t),o=HE(i,n.argsStart),s=Ss(i,n.callStart),a=_V(e.config.projectRoot,t,s),c=a===null?"unknown":a>=r?"rot":"workflow";return{file:t,startLine:s,title:o,skipKind:n.skipKind,blockKind:n.kind,ageDays:a,rot:c}}function _V(e,t,n){let r=n+1;try{let i=cn(e,["blame","-L",`${r},${r}`,"--porcelain","--",t]),o=/^author-time (\d+)$/m.exec(i);if(!o)return null;let s=Number(o[1]);return Number.isFinite(s)?Math.max(0,Math.round((Date.now()/1e3-s)/86400)):null}catch{return null}}var OV=.7,GE=.62,zE=.45;function BV(e,t={}){let{windowCommits:n=100,limit:r=30,scope:i,scanLimit:o}=t,s=Ht(e,{historyMode:t.historyMode}).fileAddRecords();if(!s)return{available:!1,windowCommits:n,findings:[]};if(r<=0)return{available:!0,windowCommits:n,findings:[]};let a=WV(s,n);if(a.size===0)return{available:!0,windowCommits:n,findings:[]};let l=$V(e,{limit:r,minSimilarity:t.minSimilarity,scanLimit:o,scope:i,semantic:t.semantic,focusFiles:Number.isFinite(r)?void 0:a}).map(d=>VV(d,s,n)).filter(d=>d!==null);l.sort((d,m)=>(d.kind===m.kind?0:d.kind==="echo"?-1:1)||m.similarity-d.similarity||d.echoFile.localeCompare(m.echoFile)||d.echoSymbol.localeCompare(m.echoSymbol)||d.domain.localeCompare(m.domain));let u=l.slice(0,r).map(YV);return{available:!0,windowCommits:n,findings:u,rootCauseGroups:JV(u)}}function $V(e,t){let n=QV(t.limit),r=[...jV(e,{scope:t.scope,minSimilarity:t.minSimilarity??OV,limit:n,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles})],i=Hs(e,{scope:t.scope});return i.react&&r.push(...HV(e,{scope:t.scope,minSimilarity:t.minSimilarity??GE,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...UV(e,{scope:t.scope,minSimilarity:t.minSimilarity??zE,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),i.vue&&r.push(...zV(e,{scope:t.scope,minSimilarity:t.minSimilarity??GE,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...KV(e,{scope:t.scope,minSimilarity:t.minSimilarity??zE,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),r}function jV(e,t){return cs(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles}).filter(n=>!He(n.symbolA)&&!He(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 HV(e,t){return Qc(e,t,{query:ls,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 Qc(e,t,n){return n.query(e,t).filter(r=>r.fileA!==r.fileB).filter(r=>n.acceptPair?.(r)??!0).map(r=>({domain:n.domain,basis:n.basis,symbolA:n.symbolA(r),fileA:r.fileA,symbolB:n.symbolB(r),fileB:r.fileB,similarity:r.similarity,sharedEvidence:ZV(...n.evidenceBuckets(r)),sharedCallees:[]}))}function UV(e,t){return Qc(e,t,{query:us,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,acceptPair:GV,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 qV=new Set(["useCallback","useEffect","useLayoutEffect","useMemo","useMutation","useQueries","useQuery","useQueryClient","useReducer","useRef","useState"]);function GV(e){return e.sharedHooks.some(t=>!qV.has(t))||e.sharedState.length>0||e.sharedHandlers.length>0||e.sharedHandlerVerbs.length>=2}function zV(e,t){return Qc(e,t,{query:ds,domain:"vue-component",basis:"vue-template",symbolA:n=>Xc(n.fileA),symbolB:n=>Xc(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function KV(e,t){return Qc(e,t,{query:ms,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>Xc(n.fileA),symbolB:n=>Xc(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 WV(e,t){let n=new Set;for(let[r,i]of e)i.commitsAgo<=t&&n.add(r);return n}function VV(e,t,n){let r=t.get(e.fileA)?.commitsAgo??null,i=t.get(e.fileB)?.commitsAgo??null,o=r!==null&&r<=n,s=i!==null&&i<=n;if(!o&&!s)return null;if(o&&s){let a=(r??0)<=(i??0);return{kind:"twin",domain:e.domain,basis:e.basis,echoSymbol:a?e.symbolA:e.symbolB,echoFile:a?e.fileA:e.fileB,echoAgeCommits:(a?r:i)??0,establishedSymbol:a?e.symbolB:e.symbolA,establishedFile:a?e.fileB:e.fileA,establishedAgeCommits:a?i:r,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}return{kind:"echo",domain:e.domain,basis:e.basis,echoSymbol:o?e.symbolA:e.symbolB,echoFile:o?e.fileA:e.fileB,echoAgeCommits:(o?r:i)??0,establishedSymbol:o?e.symbolB:e.symbolA,establishedFile:o?e.fileB:e.fileA,establishedAgeCommits:o?i:r,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}function YV(e){let t=KE(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function KE(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 JV(e){let t=new Map;for(let[n,r]of e.entries()){let i=r.rootCauseKey??KE(r),o=r.groupKey??`recent-duplicate:${i}`,s=t.get(o);s||(s={groupKey:o,rootCauseKey:i,kind:r.kind,domain:r.domain,basis:r.basis,count:0,maxSimilarity:r.similarity,findingIndexes:[],echoFiles:new Set,establishedFile:r.kind==="echo"?r.establishedFile:void 0,establishedSymbol:r.kind==="echo"?r.establishedSymbol:void 0,relatedFiles:new Set,sharedEvidence:new Set,recommendation:XV(r)},t.set(o,s)),s.count+=1,s.maxSimilarity=Math.max(s.maxSimilarity,r.similarity),s.findingIndexes.push(n),s.echoFiles.add(r.echoFile),s.relatedFiles.add(r.echoFile),s.relatedFiles.add(r.establishedFile);for(let a of r.sharedEvidence)s.sharedEvidence.add(a)}return[...t.values()].map(n=>({...n,echoFiles:[...n.echoFiles].sort(),relatedFiles:[...n.relatedFiles].sort(),sharedEvidence:[...n.sharedEvidence].sort().slice(0,16)})).sort((n,r)=>r.count-n.count||r.maxSimilarity-n.maxSimilarity||n.groupKey.localeCompare(r.groupKey))}function XV(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 QV(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function ZV(...e){let t=[],n=new Set;for(let[r,i]of e)for(let o of i){let s=`${r}:${o}`;n.has(s)||(n.add(s),t.push(s))}return t}function Xc(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var e2=me("suppression-inventory",{clearGroups:["whole-project"]});function Zc(e){return e2.get(e,()=>t2(e))}function t2(e){let t={dead:0,stale:0,wrapper:0,passthrough:0,drift:0,extract:0,similar:0,twin:0,uncategorized:0},n=new Map,r=0;for(let i of oi(e)){let o=W(e,i);if(!(!o||!o.includes("scip-query")))for(let s of o.split(/\r?\n/)){let a=_s(s);if(a===null)continue;r+=1,n.set(i,(n.get(i)??0)+1);let c=WE(a);t[c]+=1}}for(let i of e.config.suppressions??[])i.expiresAt&&Date.parse(i.expiresAt)<=Date.now()||(r+=1,i.file&&n.set(i.file,(n.get(i.file)??0)+1),t[WE(i.check)]+=1);return{total:r,byCategory:t,byFile:n}}function WE(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 op(e,t,n={}){let r=ne(e,t);if(!r)return null;let i=new H(e),o=n2(e,r),s=r.endLine-r.startLine+1,c=i.calleeMap([r],{additive:!0,semantic:n.semantic}).get(r.symbolId)??[],l=new Set(c.map(u=>u.symbol));return{symbol:r.symbol,shortName:T(r.symbol),relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,loc:s,branches:o.branches,estimateBasis:o.estimateBasis,cyclomaticEstimate:o.branches+1,calleeCount:l.size,fanIn:i2(e,r.symbolId),fanOut:o2(c,r.relativePath)}}function n2(e,t){let n=J(e,t.relativePath);if(n){let r=vr(n.rootNode,t.startLine,t.endLine);if(r)return{branches:s2(r),estimateBasis:"ast"}}return{branches:XE(JE(e,t.relativePath,t.startLine,t.endLine),YE(e,t.relativePath)),estimateBasis:"regex-fallback"}}function VE(e,t){let n=new Map,r=new Map;for(let i of t){let o=r.get(i.relativePath)??[];o.push(i),r.set(i.relativePath,o)}for(let[i,o]of r){let s=new Map;for(let d of K(e,i)?.callables??[])d.branches!==void 0&&s.set(`${d.startLine}:${d.endLine}`,d.branches);let a=[];for(let d of o){let m=s.get(`${d.startLine}:${d.endLine}`);m===void 0?a.push(d):n.set(d.symbolId,{branches:m,estimateBasis:"ast"})}if(a.length===0)continue;let c=J(e,i),l=c===null?[]:a.filter(d=>c.rootNode.startPosition.row<=d.startLine&&c.rootNode.endPosition.row>=d.endLine),u=new Set(l.map(d=>d.symbolId));if(c&&l.length>0){for(let d of l)n.set(d.symbolId,{branches:0,estimateBasis:"ast"});a2(c.rootNode,l,n)}for(let d of a)u.has(d.symbolId)||n.set(d.symbolId,r2(e,d))}return n}function r2(e,t){return{branches:XE(JE(e,t.relativePath,t.startLine,t.endLine),YE(e,t.relativePath)),estimateBasis:"regex-fallback"}}function YE(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function JE(e,t,n,r){try{return Ye(e.config.projectRoot,t,{inputKind:"indexed source file"}).split(`
417
- `).slice(n,r+1).join(`
418
- `)}catch(i){if(!Je(i))throw i;return""}}function i2(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
419
- FROM mentions m
420
- JOIN chunks c ON m.chunk_id = c.id
421
- JOIN (
422
- SELECT m2.symbol_id, c2.document_id
423
- FROM mentions m2
424
- JOIN chunks c2 ON m2.chunk_id = c2.id
425
- WHERE m2.role = 1
426
- GROUP BY m2.symbol_id
427
- ) sym_def ON sym_def.symbol_id = m.symbol_id
428
- WHERE m.symbol_id = ?
429
- AND m.role != 1
430
- AND sym_def.document_id != c.document_id`,t)?.c??0}function o2(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function s2(e){let t=0;return Dl(e,n=>{t+=Tl(n)}),t}function a2(e,t,n){let r=[...t].sort((i,o)=>i.startLine-o.startLine||o.endLine-i.endLine);Dl(e,i=>{let o=Tl(i);if(o===0)return;let s=i.startPosition.row,a=i.endPosition.row;for(let c of r){if(c.startLine>s)break;if(c.endLine<a)continue;let l=n.get(c.symbolId);l&&(l.branches+=o)}})}function XE(e,t){let n=fn(e),r=0,i=[/\bif\b/g,/\belse\s+if\b/g,/\belse\b/g,/\bfor\b/g,/\bwhile\b/g,/\bswitch\b/g,/\bcase\b/g,/\bcatch\b/g,/\?\s*[^?]/g,/&&/g,/\|\|/g];for(let o of i){let s=n.match(o);s&&(r+=s.length)}if(t==="python"){let o=[/\belif\b/g,/\bexcept\b/g,/\bfinally\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="rust"){let o=[/\bmatch\b/g,/=>/g,/\bloop\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="ruby"){let o=[/\belsif\b/g,/\bunless\b/g,/\brescue\b/g,/\bwhen\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="go"){let o=[/\bselect\b/g,/\bdefer\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}return r}function QE(e,t,n={}){let r=ne(e,t);if(!r)return null;let i=[{file:r.relativePath,line:r.startLine}],o=Un(e,r,{semantic:n.semantic,semanticEvidence:re}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?T(c.enclosingSymbol):"(top-level)"})),{outgoingCalls:s,incomingCalls:a}=c2(e,r,o,{semantic:n.semantic!==!1});return{symbol:r.symbol,shortName:T(r.symbol),relativePath:r.relativePath,definitionSites:i.filter(c=>!e.isIgnored(c.file)),referenceSites:o,outgoingCalls:s.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:T(c.symbol),file:c.file})),incomingCalls:a.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:c.symbol===c.file?"(top-level)":T(c.symbol),file:c.file}))}}function sp(e,t,n={}){let r=QE(e,t,n);return r?{symbol:r.symbol,shortName:r.shortName,relativePath:r.relativePath,definitionSites:r.definitionSites,usageSites:r.referenceSites,producers:r.outgoingCalls,consumers:r.incomingCalls}:null}function c2(e,t,n,r){let i=Mi(Dt(e,t,{limit:30,semantic:r.semantic,semanticEvidence:re}).map(a=>({symbol:a.symbol,file:a.file}))),o=Mi(zn(e,t,{limit:30,semantic:r.semantic,semanticEvidence:re})),s=o.length>0?o:Mi(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{outgoingCalls:i,incomingCalls:s}}function ZE(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,o=ne(e,t);return o?r==="backward"?l2(e,o,i,{semantic:n.semantic!==!1}):u2(e,o,{semantic:n.semantic!==!1}):null}function el(e,t,n={}){return ZE(e,t,n)}function l2(e,t,n,r){let i=[],o=new Set([t.symbol]),s=[t];for(let a=1;a<=n&&s.length!==0;a++){let c=[];for(let l of s){let u=Dt(e,l,{semantic:r.semantic,semanticEvidence:re});for(let d of u){if(o.has(d.symbol))continue;o.add(d.symbol),i.push({symbol:d.symbol,shortName:T(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let m=xr(e,d.symbol);m&&!e.isIgnored(m.relativePath)&&c.push(m)}}s=c}return{symbol:t.symbol,shortName:T(t.symbol),direction:"backward",connectedSymbols:i}}function u2(e,t,n){let r=new Set,i=[],o=new H(e);for(let s of Un(e,t,{semantic:n.semantic,semanticEvidence:re})){if(i.length>=30)break;let a=s.enclosingSymbol??Oe(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=xr(e,a);!c||e.isIgnored(c.relativePath)||r.has(c.symbol)||(r.add(c.symbol),i.push({symbol:c.symbol,shortName:T(c.symbol),file:c.relativePath,relationship:`references target at ${s.file}:${s.line+1}`}))}return i.sort((s,a)=>s.file.localeCompare(a.file)),{symbol:t.symbol,shortName:T(t.symbol),direction:"forward",connectedSymbols:i}}function eI(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 sI=6,nl=10,cp=3,lp=8,d2=.7,tI=24,ap=200,aI=12,nI=80,rI=600;function m2(e,t,n={}){let r=n.impactDepth??3,i=n.sliceDepth??3,o=n.semantic,s=R2(t)?g2(e,t):null,a=s?s.primary?.symbol??null:t,{traceResult:c,callGraphResult:l,complexityResult:u,dataflowResult:d,backwardSliceResult:m,forwardSliceResult:p,affectedResults:f,reuseCandidates:g,targetSymbol:h,affectedConsumerReuse:b}=p2(e,a,n,r,i),S=$e("change-surface",t,()=>Fm(e,t,{semantic:o}),D=>({symbols:D?.symbols.length??0,externalConsumers:D?.totalExternalConsumers??0})),y=$e("system",t,()=>cm(e,t),D=>({files:D.files.length,symbols:D.symbols.length})),x=y.files.length===1,v=$e("deps",t,()=>x?y.dependsOn.map(D=>({relativePath:D,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):Uo(e,t),D=>({files:D.length,reusedSystem:x})),C=$e("rdeps",t,()=>x?y.dependedOnBy.map(D=>({relativePath:D,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):qo(e,t),D=>({files:D.length,reusedSystem:x})),R=$e("surface",t,()=>lm(e,t),D=>({consumers:D.length})),E={symbol:c.definitions.length>0||c.referencedBy.length>0||l!==null||u!==null||d!==null||m!==null||p!==null||f.length>0,file:S!==null||v.length>0||C.length>0,module:y.files.length>0||y.symbols.length>0||R.length>0},I=[];s&&!s.primary&&s.callableCount>1&&I.push(`File target has ${s.callableCount} callable symbols; use one callable name for compiler-resolved flow.`);let w=[...new Set(c.referencedBy.map(D=>D.relativePath))];w.length>0&&w.every(D=>q(D)==="test")&&I.push("Only test references were found for this target. For replacement or retirement work, map the currently wired owner or one production entry point before planning; this target does not describe the live affected surface."),!E.symbol&&!E.file&&!E.module&&I.push("No symbol, file, or module matched target.");let A=S?.file??c.definitions[0]?.relativePath??null;return{target:t,...s?.primary?{primaryCallable:{symbol:s.primary.symbol,shortName:z(s.primary.symbol),file:s.primary.relativePath}}:{},matched:E,history:$e("history",A??t,()=>x2(e,A,n.gitHead)),trace:f2(c),callGraph:l,complexity:u,dataflow:d,backwardSlice:m,forwardSlice:p,affected:f,changeSurface:S,deps:v,rdeps:C,system:y,surface:R,reuseCandidates:g,affectedConsumerReuse:b,sourcePacket:h2(e,h,c,b,g),warnings:I}}function p2(e,t,n,r,i){let o=n.semantic,s=t?$e("trace",t,()=>Ad(e,t,{semantic:o,referenceContext:aI}),h=>({definitions:h.definitions.length,references:h.referencedBy.length})):{definitions:[],referencedBy:[],claimSupport:null},a=t?$e("call-graph",t,()=>Ho(e,t,{semantic:o}),h=>({callers:h?.callers.length??0,callees:h?.callees.length??0})):null,c=t?$e("complexity",t,()=>op(e,t,{semantic:o}),h=>({callees:h?.calleeCount??0})):null,l=t?$e("dataflow",t,()=>sp(e,t,{semantic:o}),h=>({references:h?.usageSites.length??0,producers:h?.producers.length??0,consumers:h?.consumers.length??0})):null,u=t?$e("backward-slice",t,()=>el(e,t,{direction:"backward",maxDepth:i,semantic:o}),h=>({maxDepth:i,connectedSymbols:h?.connectedSymbols.length??0})):null,d=t?$e("forward-slice",t,()=>el(e,t,{direction:"forward",maxDepth:i,semantic:o}),h=>({maxDepth:i,connectedSymbols:h?.connectedSymbols.length??0})):null,m=t?$e("affected",t,()=>Am(e,t,{maxDepth:r,scope:n.scope}),h=>({maxDepth:r,affectedSymbols:h.length})):[],p=t?$e("reuse-candidates",t,()=>as(e,t,{minSimilarity:.4,limit:5,semantic:o,sourceCandidateMode:"target-pruned"}),h=>({candidates:h.length,direct:h.filter(b=>b.actionTier==="direct").length})):[],f=t?ne(e,t)?.symbol??null:null,g=t?$e("affected-consumer-reuse",t,()=>y2(s,f,h=>as(e,h,{minSimilarity:.4,limit:nl,semantic:o,sourceCandidateMode:"target-pruned"}),{consumerLimit:sI,perConsumerSearchLimit:nl,perConsumerCandidateLimit:cp,candidateLimit:lp}),h=>({totalConsumers:h.coverage.totalConsumers,analyzedConsumers:h.coverage.analyzedConsumers,candidates:h.candidates.length})):C2();return{traceResult:s,callGraphResult:a,complexityResult:c,dataflowResult:l,backwardSliceResult:u,forwardSliceResult:d,affectedResults:m,reuseCandidates:p,targetSymbol:f,affectedConsumerReuse:g}}function f2(e){return{definitions:e.definitions,referencedBy:e.referencedBy.map(t=>({relativePath:t.relativePath,line:t.line,enclosingSymbol:t.enclosingSymbol,enclosingShort:t.enclosingShort}))}}function g2(e,t){let n=wr(e,t);if(n.length!==1)return{primary:null,callableCount:0};let r=U(e,n[0]).filter(s=>s.isFunctionLike),i=r.filter(s=>s.enclosingSymbol===null),o=i.length>0?i:r;return{primary:o.length===1?o[0]:null,callableCount:o.length}}function h2(e,t,n,r,i){let o=[...t?[{definition:iI(e,t),role:"target"}]:[],...[...r.candidates.map(d=>d.candidate),...i].map(d=>({definition:iI(e,d.symbolB),role:"reuse-candidate"}))],s=new Map;for(let d of eI(o)){if(s.has(d.definition.symbol))continue;let m=d.role==="target"?ap:nI,p=d.definition.endLine<=d.definition.startLine?Wn(e,d.definition.relativePath,d.definition.startLine,m):null,f=p?.unitType?p.source:Ut(e,d.definition);if(!f)continue;let g=f.split(`
431
- `),h=Math.min(g.length,m),b=p?.unitType?p.startLine:d.definition.startLine;s.set(d.definition.symbol,{role:d.role,symbol:d.definition.symbol,shortName:z(d.definition.symbol),file:d.definition.relativePath,startLine:b,endLine:b+h-1,source:g.slice(0,h).join(`
432
- `),omittedLines:(p?.unitType?p.omittedLines:0)+Math.max(0,g.length-h)})}let a=new Map;for(let d of n.referencedBy){if(d.source===void 0||d.source===null||d.sourceStartLine===void 0||d.sourceStartLine===null||d.sourceEndLine===void 0||d.sourceEndLine===null)continue;let m=`${d.relativePath}:${d.sourceStartLine}-${d.sourceEndLine}`,p=a.get(m);if(p){p.focusLines=[...new Set([...p.focusLines??[],d.line])].sort((f,g)=>f-g);continue}a.set(m,{role:"consumer",symbol:d.enclosingSymbol??`${d.relativePath}:${d.line}`,shortName:d.enclosingShort,file:d.relativePath,startLine:d.sourceStartLine,endLine:d.sourceEndLine,source:d.source,omittedLines:0,focusLines:[d.line]})}let c=[...[...s.values()].filter(d=>d.role==="target"),...a.values(),...[...s.values()].filter(d=>d.role==="reuse-candidate")],l=[],u=rI;for(let d of c){if(l.length>=tI||u<=0)break;let m=d.source.split(`
433
- `),p=Math.min(m.length,u);l.push({...d,endLine:d.startLine+p-1,source:m.slice(0,p).join(`
434
- `),omittedLines:d.omittedLines+Math.max(0,m.length-p),...d.focusLines?{focusLines:d.focusLines.filter(f=>f<=d.startLine+p-1)}:{}}),u-=p}return{slices:l,candidateSlices:c.length,omittedSlices:Math.max(0,c.length-l.length),maxSlices:tI,maxLinesPerSlice:ap,maxTotalLines:rI,targetLineLimit:ap,consumerContextLines:aI,reuseLineLimit:nI}}function iI(e,t){let n=xr(e,t);return n?U(e,n.relativePath).find(r=>r.symbol===t)??null:null}function y2(e,t,n,r={}){let i=tl(r.consumerLimit,sI),o=tl(r.perConsumerSearchLimit,nl),s=tl(r.perConsumerCandidateLimit,cp),a=tl(r.candidateLimit,lp),c=b2(e),l=c.slice(0,i),u=new Set(c.map(p=>p.symbol));t&&u.add(t);let d=new Map;for(let p of l){let f=n(p.symbol).slice(0,o),g=0;for(let h of f){let b=S2(h,p.symbol);if(!b||u.has(b.symbolB))continue;let S=d.get(b.symbolB);if(S?(S.consumers.some(y=>y.symbol===p.symbol)||S.consumers.push(p),b.similarity>S.candidate.similarity&&(S.candidate=b)):d.set(b.symbolB,{candidate:b,consumers:[p]}),g+=1,g>=s)break}}let m=[...d.values()].filter(p=>p.candidate.actionTier==="direct"||p.candidate.similarity>=d2||p.consumers.length>1).sort(v2).slice(0,a);return{candidates:m,coverage:{totalConsumers:c.length,analyzedConsumers:l.length,omittedConsumers:Math.max(0,c.length-l.length),perConsumerSearchLimit:o,perConsumerCandidateLimit:s,candidateLimit:a,returnedCandidates:m.length}}}function b2(e){let t=new Map;for(let n of e.referencedBy){if(!n.enclosingSymbol)continue;let r=t.get(n.enclosingSymbol);if(r){r.referenceCount+=1;continue}t.set(n.enclosingSymbol,{symbol:n.enclosingSymbol,shortName:z(n.enclosingSymbol)||n.enclosingShort,file:n.relativePath,referenceCount:1})}return[...t.values()].sort((n,r)=>r.referenceCount-n.referenceCount||n.symbol.localeCompare(r.symbol))}function S2(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 v2(e,t){let n=oI(t.candidate.actionTier)-oI(e.candidate.actionTier);if(n!==0)return n;let r=t.consumers.length-e.consumers.length;if(r!==0)return r;let i=t.candidate.similarity-e.candidate.similarity;return i!==0?i:e.candidate.symbolB.localeCompare(t.candidate.symbolB)}function oI(e){return e==="direct"?1:0}function tl(e,t){return typeof e=="number"&&Number.isFinite(e)?Math.max(1,Math.floor(e)):t}function C2(){return{candidates:[],coverage:{totalConsumers:0,analyzedConsumers:0,omittedConsumers:0,perConsumerSearchLimit:nl,perConsumerCandidateLimit:cp,candidateLimit:lp,returnedCandidates:0}}}function $e(e,t,n,r=()=>({})){let i;return N(`context.${e}`,()=>(i=n(),i),()=>({target:t,...r(i)}))}function x2(e,t,n){let r={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return r;let i=Ht(e,n?{head:n}:{}),o=$e("history.churn",t,()=>i.fileChurn(),c=>({files:c?.size??0}));if(!o)return r;let s=$e("history.co-change",t,()=>gs(e,t,{limit:5,...n?{head:n}:{}}),c=>({commits:c.commitsAnalyzed,partners:c.findings.length})),a=$e("history.suppressions",t,()=>Zc(e).byFile.get(t)??0,c=>({suppressions:c}));return{available:!0,file:t,churn:o.get(t)??{changes:0,fixChanges:0,lastChangedAt:0},coChangePartners:s.findings.map(c=>({file:c.fileA===t?c.fileB:c.fileA,together:c.together,confidence:c.confidence,subjectContext:c.subjectContext})),suppressionsInFile:a}}function R2(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}var Ie={dead:{minLoc:1,skipBarrels:!1,deadCodeOnly:!1},isolated:{minLoc:3},similar:{minSimilarity:.6,limit:50,minCallees:4},duplicateBodies:{maxLoc:15,limit:50},extract:{minLoc:15,minCallees:5,limit:50},wrappers:{maxLoc:15,limit:50},passthroughs:{maxLoc:15,limit:50},stale:{minLoc:3,limit:50},drift:{},twinDrift:{minSimilarity:.3}};import{existsSync as E2}from"fs";import{isAbsolute as I2,join as w2}from"path";var L2=".scipquery-baseline.json";function up(e){if(e.startsWith("similar:")){let t=e.slice(8).split("|");return t.length!==2?e:`similar:${t.map(T).sort().join("|")}`}if(e.startsWith("duplicate-bodies:")){let t=e.slice(17),n=t.indexOf(":");if(n<0)return e;let r=t.slice(0,n),i=t.slice(n+1).split("|");return i.length<2?e:`duplicate-bodies:${r}:${i.map(T).sort().join("|")}`}return e}function dp(e,t){return t&&I2(t)?t:w2(e.config.projectRoot,t??L2)}function cI(e,t,n={}){let r=dp(e,n.path);if(!E2(r))throw new Error(`No baseline found at ${r}. Create one with: scip-query health --write-baseline`);let o=(JSON.parse(Ve(r,"health baseline")).findings??[]).map(up),s=new Set(n.accept?o.filter(n.accept):o),a=new Set(t);return{baselinePath:r,baselineCount:s.size,current:[...t],newFindings:t.filter(c=>!s.has(c)),fixedFindings:[...s].filter(c=>!a.has(c))}}import Cs from"path";function Rs(e,t){let{scope:n,minDeviation:r=5,limit:i=50}=t??{},o=t?.semantic!==!1,s=t?.includePatternDeviations===!0,c=new H(e).fileDependencyGraph(n),l=is(e,{scope:n}),u=A2([...P2(e,c,{scope:n,semantic:o}),...M2(l.forbiddenEdges),...s?T2(c,r):[]]);return t?.includeArchitecture===!0&&(u.architecture=l),i<=0||u.results.length<=i?u:{...u,results:u.results.slice(0,i),totalResults:u.results.length}}function P2(e,t,n){let r=N2(e,n.scope),i=[],o=new Set;for(let[a,c]of t){if(xs(a))continue;let l=r.get(a)??new Set;for(let u of c)xs(u)||l.has(u)||D2(e,a,u,n)||(i.push({file:a,dep:u}),o.add(a))}o.size>0&&B2(e,r,{paths:[...o]});let s=[];for(let{file:a,dep:c}of i)(r.get(a)??new Set).has(c)||s.push({file:a,kind:"unused-import",description:`Depends on ${c} but references none of its symbols`,dep:c,actionTier:"direct",evidenceReasons:[`dependency edge exists from ${a} to ${c}`,"no semantic, source, type-only, side-effect, or Vue-template usage survived the conservative skip gates"],recommendation:"Remove the unused import or dependency edge after running the project checks."});return s}function D2(e,t,n,r){return H2(e,t,n)||U2(e,t,n)||$2(n)||G2(e,t,n)||q2(n)?!0:r.semantic&&j2(e,t,n)}function M2(e){return e.flatMap(t=>{let n=t.examples[0];return n?[{file:n.fromFile,kind:"architecture-violation",description:`${t.from} depends on forbidden boundary ${t.to} through ${t.fileEdgeCount} file edge(s)`,dep:n.toFile,detail:`${t.from} may not depend on ${t.to}`,actionTier:"direct",policyBasis:"explicit",architecture:{fromBoundary:t.from,toBoundary:t.to,fileEdgeCount:t.fileEdgeCount,importerCount:t.importerCount,importedFileCount:t.importedFileCount,examples:t.examples},evidenceReasons:[`configured dependency row for ${t.from} does not allow ${t.to}`,`${t.fileEdgeCount} file edge(s) connect ${t.importerCount} importer(s) to ${t.importedFileCount} imported file(s)`,...t.examples.map(r=>`${r.fromFile} imports ${r.toFile}`)],recommendation:"Move the dependency behind an allowed boundary, reverse the dependency through an owned interface, or deliberately update the project architecture rule."}]:[]})}function T2(e,t){let n=[];for(let[r,i]of F2(e)){let o=i.filter(a=>!xs(a));if(o.length<t)continue;let s=k2(e,o);for(let a of o)for(let c of e.get(a)??[])xs(c)||(s.get(c)??0)===1&&Cs.dirname(c)!==r&&Cs.dirname(c)!==Cs.dirname(r)&&n.push({file:a,kind:"pattern-deviation",description:`Only file in ${r}/ that depends on ${c}`,dep:c,actionTier:"signal",evidenceReasons:[`${o.length} sibling file(s) in ${r}/ were compared`,`${a} is the only non-skipped sibling depending on ${c}`],recommendation:"Review sibling ownership before changing this import; unique dependency shape can be intentional specialization."})}return n}function A2(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 F2(e){let t=new Map;for(let n of e.keys()){let r=Cs.dirname(n),i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function k2(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])xs(i)||n.set(i,(n.get(i)??0)+1);return n}function N2(e,t){let n=new Map;return _2(e,n,t),n}function _2(e,t,n){for(let r of O2(e,n))lI(e,t,r.from_file,r.to_file)}function O2(e,t){let n=t?"AND d1.relative_path LIKE ?":"",r=t?[`%${t}%`]:[];return e.all(`SELECT DISTINCT d1.relative_path AS from_file, d2.relative_path AS to_file
435
- FROM mentions m
436
- JOIN chunks c ON m.chunk_id = c.id
437
- JOIN documents d1 ON c.document_id = d1.id
438
- JOIN global_symbols gs ON m.symbol_id = gs.id
439
- JOIN (
440
- SELECT m2.symbol_id, c2.document_id
441
- FROM mentions m2
442
- JOIN chunks c2 ON m2.chunk_id = c2.id
443
- WHERE m2.role = 1
444
- GROUP BY m2.symbol_id
445
- ) sym_def ON sym_def.symbol_id = gs.id
446
- JOIN documents d2 ON sym_def.document_id = d2.id
447
- WHERE d1.id != d2.id
448
- AND m.role != 1
449
- ${e.pathExclusionsFor("d1","d2")}
450
- ${n}`,...r)}function B2(e,t,n={}){new H(e).scanSourceReferences({paths:n.paths??Q(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},i=>{i.target.relativePath!==i.sourceFile&&(e.isIgnored(i.target.relativePath)||lI(e,t,i.sourceFile,i.target.relativePath))})}function lI(e,t,n,r){if(e.isIgnored(n)||e.isIgnored(r))return;let i=t.get(n);i||(i=new Set,t.set(n,i)),i.add(r)}function $2(e){return e.includes("types")||e.endsWith(".d.ts")}function j2(e,t,n){return To(e,t).filter(i=>i.sourcePath===n).some(i=>i.isUsed)}function H2(e,t,n){return ae(e,t).filter(i=>i.sourcePath===n).some(i=>i.used)}function U2(e,t,n){let r=ae(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.every(i=>i.isTypeOnly===!0)}function q2(e){return e.endsWith(".vue")}function G2(e,t,n){let r=ae(e,t).filter(i=>i.sourcePath===n);return r.length===0?!1:r.every(i=>i.kind==="side-effect"||i.kind==="namespace"&&i.usedMembers.length===0&&!i.used)}function xs(e){let t=q(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||z2(Cs.basename(e)))}function z2(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 Es(e,t){let{scope:n,minLoc:r=3,maxLoc:i=80,limit:o=30,includeLowConfidence:s=!1,scanLimit:a}=t??{},c=t?.semantic!==!1,l=new H(e),u=l.scopedDefinitions(n),d=rY(l,n),m={high:0,medium:1,low:2};return kt({candidates:()=>K2(e,l,u,{minLoc:r,maxLoc:i}),orderCandidates:(p,f)=>ee(f)-ee(p)||p.relativePath.localeCompare(f.relativePath),scanLimit:a,profile:{name:"stale-abstractions"},prepare:p=>{let f=V2(p),g=W2(e,l,p,f,{semantic:c}),h=p.filter(b=>{if(l.hasSuppressionComment(b))return!1;let S=rl(e,b,g,f);return S.realConsumers.length<=1&&!S.transitivelyReachable&&uI(b,S.realConsumers.length,d)});return{consumerFileMap:g,singletonBackedClassIds:X2(e,l,u,h,{semantic:c}),candidateIndex:f}},evaluate:(p,f)=>{if(l.hasSuppressionComment(p)||f.singletonBackedClassIds.has(p.symbolId))return null;let g=rl(e,p,f.consumerFileMap,f.candidateIndex);if(g.transitivelyReachable||g.realConsumers.length>1||g.realConsumers.length===0&&g.barrelConsumers>0||!uI(g.definition,g.realConsumers.length,d))return null;let h=Y2(e,g);return!s&&h.confidence==="low"?null:h},orderResults:(p,f)=>m[p.confidence]-m[f.confidence]||f.loc-p.loc||p.file.localeCompare(f.file)||p.startLine-f.startLine,limit:o})}function K2(e,t,n,r){return n.filter(i=>i.isTypeLike&&ee(i)>=r.minLoc).filter(i=>ee(i)<=r.maxLoc).filter(i=>!e.isIgnored(i.relativePath)).filter(i=>!i.relativePath.endsWith(".d.ts")).filter(i=>q(i.relativePath)!=="test").filter(i=>!Fe(e,i.symbol,i.relativePath)).filter(i=>!iY(i.symbol))}function mp(e,t,n,r){return An(Tn(e,t).forDefinitions(n,{semantic:r.semantic,sourceFallback:r.sourceFallback}))}function W2(e,t,n,r,i){let o=mp(e,t,n,{semantic:!1,sourceFallback:!1}),s=n.filter(l=>{let u=rl(e,l,o,r);return u.realConsumers.length<=1&&!(u.realConsumers.length>0&&pp(l.relativePath))}),a=i.semantic&&s.length>0?en(o,mp(e,t,s,{semantic:!0,sourceFallback:!1})):o,c=s.filter(l=>rl(e,l,a,r).realConsumers.length<=1);return en(a,mp(e,t,c,{semantic:!1,sourceFallback:!0}))}function V2(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);r||(r=new Map,t.set(n.relativePath,r));let i=z(n.symbol);i&&r.set(i,n)}return t}function rl(e,t,n,r){let o=[...n.get(t.symbolId)??new Set].filter(u=>u!==t.relativePath&&!e.isIgnored(u)),{realConsumers:s,barrelConsumers:a,importOnlyConsumers:c}=$c(e,t,o),l=oY(e,t,n,r);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:l}}function Y2(e,t){let n=mI(e,t.definition.relativePath,t.definition.startLine),r=pp(t.definition.relativePath)?!0:sY(e,t.definition),{confidence:i,reason:o}=aY(t.realConsumers.length,n,r),s=J2(t.realConsumers.length,n,r);return{symbol:t.definition.symbol,shortName:T(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:ee(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:r,confidence:i,reason:o,actionTier:s.actionTier,stalenessKind:s.stalenessKind,recommendation:s.recommendation}}function J2(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 X2(e,t,n,r,i){let o=Z2(e,Q2(n),r),s=o.map(l=>l.singleton);if(o.length===0)return new Set;let a=An(Tn(e,t).forDefinitions(s,{semantic:i.semantic,sourceFallback:!0})),c=new Set;for(let{singleton:l,classId:u}of o)tY(e,l,a)&&c.add(u);return c}function Q2(e){let t=new Map;for(let n of e){let r=z(n.symbol);r&&t.set(dI(n.relativePath,r),n)}return t}function Z2(e,t,n){let r=[];for(let i of n){let o=eY(e,t,i);o&&r.push({singleton:o,classId:i.symbolId})}return r}function eY(e,t,n){if(mI(e,n.relativePath,n.startLine)!=="class")return null;let r=z(n.symbol);if(!r)return null;let i=nY(e,n.relativePath,r);return i?t.get(dI(n.relativePath,i))??null:null}function tY(e,t,n){let r=z(t.symbol),i=n.get(t.symbolId);return!r||!i?!1:[...i].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!wm(e,o,r))}function dI(e,t){return`${e}\0${t}`}function nY(e,t,n){let r=W(e,t);if(!r)return null;let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\bexport\\s+const\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*new\\s+${i}\\s*\\(`);return r.match(o)?.[1]??null}function rY(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function iY(e){let t=$n(e);if("kind"in t)return!1;let n=t.descriptors;if(n.length<2)return!1;let r=n[n.length-1],i=n[n.length-2];return r?.suffix==="type"&&i?.suffix==="type"}function pp(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 uI(e,t,n){return!(pp(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function oY(e,t,n,r){let i=If(e,t.relativePath),o=z(t.symbol);if(!o)return!1;let s=r.get(t.relativePath);if(!s)return!1;let a=[...i.get(o)??[]],c=new Set;for(;a.length>0;){let l=a.pop();if(c.has(l))continue;c.add(l);let u=s.get(l);if(!u)continue;let d=n.get(u.symbolId);if(d){for(let m of d)if(m!==t.relativePath&&!e.isIgnored(m))return!0}for(let m of i.get(l)??[])a.push(m)}return!1}function mI(e,t,n){let r=W(e,t);if(!r)return"other";let i=r.split(`
451
- `),o=Math.max(0,n-2),s=Math.min(i.length-1,n+2);for(let a=o;a<=s;a++){let l=(i[a]??"").replace(/^\s*\/\/.*$/g,"");if(/\b(?:export\s+)?(?:abstract\s+)?class\s+\w/.test(l))return"class";if(/\b(?:export\s+)?interface\s+\w/.test(l))return"interface";if(/\b(?:export\s+)?type\s+\w/.test(l))return"type";if(/\b(?:export\s+)?(?:const\s+)?enum\s+\w/.test(l))return"enum"}return"other"}function sY(e,t){let n=W(e,t.relativePath);if(!n)return!1;let r=z(t.symbol);if(!r)return!1;let i=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${i}\\b`),s=n.split(`
452
- `);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function aY(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 Yi,extname as il}from"path";function Is(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new H(e),a=pY(s.fileDependencyGraph(n));return kt({candidates:()=>uY(e,s,n,r),orderCandidates:Za,scanLimit:o,profile:{name:"wrapper-candidates"},prepare:c=>({callerFileMap:cY(e,s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>lY(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:i})}function cY(e,t,n,r){let i=Tn(e,t),o=An(i.forDefinitions(n,{semantic:!1,sourceFallback:!1})),s=[];r.semantic&&N("wrapper.semantic-candidates",()=>{s=n.filter(m=>fp(e,t,m,o).length<=1)},()=>({symbols:n.length,semanticCandidates:s.length}));let a=s.length===0?new Map:An(i.forDefinitions(s,{semantic:!0,sourceFallback:!1})),c=a.size===0?o:en(o,a),l=new Map(n.map(m=>[m.symbolId,m])),u=new Map;for(let m of n){let p=fp(e,t,m,c);if(p.length>1||(u.set(m.symbolId,m),p.length!==1))continue;let f=p[0],g=pI(e,m.symbolId,f);if(!g)continue;let h=fI(t,e,f,m.symbol,g);h?.isFunctionLike&&l.has(h.symbolId)&&u.set(h.symbolId,l.get(h.symbolId))}let d=[...u.values()];return d.length===0?c:en(c,An(i.forDefinitions(d,{semantic:!1,sourceFallback:!0})))}function lY(e,t,n,r){let i=fp(e,t,n,r.callerFileMap);if(i.length!==1)return null;let o=i[0],s=pI(e,n.symbolId,o);if(!s)return null;let a=fI(t,e,o,n.symbol,s);if(a&&ci(a.symbol))return null;let{fanIn:c,source:l}=dY(r.callerFileMap,r.reverseFanIn,o,a);if(l==="function"?c<=3:c<=5)return null;let u=gY(e,n,o,a);return{symbol:n.symbol,shortName:T(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:ee(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?T(a.symbol):Yi(o),callerFanIn:c,actionTier:u.length>0?"signal":"direct",boundaryEvidence:u}}function uY(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:2,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0}).filter(i=>!js(e,i))}function fp(e,t,n,r){let i=Yi(n.relativePath,il(n.relativePath)),o=[...r.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>Yi(s,il(s))!==i).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return $c(e,n,o).realConsumers}function pI(e,t,n){return e.get(`SELECT c.start_line, c.end_line
453
- FROM mentions m
454
- JOIN chunks c ON m.chunk_id = c.id
455
- JOIN documents d ON c.document_id = d.id
456
- WHERE m.symbol_id = ? AND m.role != 1 AND d.relative_path = ?
457
- LIMIT 1`,t,n)}function fI(e,t,n,r,i){let o=e.definitionsForFile(n),s=mY(t,n,r,i.start_line,i.end_line);return Oe(o,s)}function dY(e,t,n,r){if(r?.isFunctionLike){let i=[...e.get(r.symbolId)??[]].filter(o=>o!==r.relativePath);if(i.length>0)return{fanIn:i.length,source:"function"}}return{fanIn:fY(t,n),source:"file"}}function mY(e,t,n,r,i){let o=z(n);if(!o)return r;let s=di(e,t).get(o);if(!s||s.length===0)return r;for(let a of s)if(a>=r&&a<=i)return a;return r}function pY(e){let t=new Map;for(let[n,r]of e){t.has(n)||t.set(n,t.get(n)??0);for(let i of r)t.set(i,(t.get(i)??0)+1)}return t}function fY(e,t){let n=e.get(t)??0;if(n>0)return n;let r=Yi(t,il(t)),i=0;for(let[o,s]of e)o!==t&&Yi(o,il(o))===r&&s>i&&(i=s);return i}function gY(e,t,n,r){return Jc(e,t.relativePath,t.startLine,"wrapper","explicit ignore-wrapper comment",[{label:"wrapper name",value:T(t.symbol)},{label:"caller name",value:r?.symbol?T(r.symbol):Yi(n)},{label:"wrapper path",value:t.relativePath},{label:"caller path",value:n}])}var hY=25e3,yY=2500,bY=2500;function SY(e){let t=_r(e);return t.symbols>=hY||t.documents>=yY?bY:void 0}function gp(e,t={}){let{scope:n}=t,r=SY(e),i=[],o=Vr(e,{scope:n,...Ie.dead,scanLimit:r});for(let s of o.symbols)Ue(e,s.relativePath)||Fe(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&i.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of os(e,{scope:n,...Ie.isolated,scanLimit:r}))Ue(e,s.relativePath)||Fe(e,s.symbol,s.relativePath)||i.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of rs(e,{scope:n}))s.kind==="real"&&i.push(`cycle:${vY(s.path)}`);for(let s of cs(e,{scope:n,...Ie.similar,scanLimit:r}))i.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of ys(e,{scope:n,...Ie.duplicateBodies,scanLimit:r}))i.push(`duplicate-bodies:${s.hash}:${s.functions.map(a=>a.symbol).sort().join("|")}`);for(let s of ps(e,{scope:n,...Ie.extract,scanLimit:r}))i.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of Is(e,{scope:n,...Ie.wrappers,scanLimit:r}))i.push(`wrapper:${s.file}:${s.shortName}`);for(let s of bs(e,{scope:n,...Ie.passthroughs,scanLimit:r}))i.push(`passthrough:${s.file}:${s.shortName}`);for(let s of Es(e,{scope:n,...Ie.stale,scanLimit:r}))i.push(`stale:${s.file}:${s.shortName}`);for(let s of Rs(e,{scope:n,...Ie.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY}).results)s.kind!=="architecture-violation"&&i.push(`drift:${s.kind}:${s.file}:${s.dep}`);return i.push(...gm(is(e,{scope:n}))),[...new Set(i.map(up))].sort()}function vY(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 CY(e,t={}){let n=gp(e,{scope:t.scope}),r=dp(e,t.path);return Qf(r,{version:1,findings:n},{spacing:2,trailingNewline:!0}),{path:r,findingCount:n.length}}function xY(e,t={}){return cI(e,gp(e,{scope:t.scope}),{path:t.path})}function RY(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new H(e);return kt({candidates:()=>o.productionCallableDefinitions({scope:n,files:t.files,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}),filterCandidate:s=>EY(s.relativePath),scanLimit:i,profile:{name:"unused-params"},evaluate:s=>{let a=K(e,s.relativePath)?.callables.find(u=>u.startLine===s.startLine&&u.endLine===s.endLine);if(!a||a.params.length===0||a.params.some(u=>!u.simple)||a.paramsEndLine>=a.endLine)return null;let c=di(e,s.relativePath),l=[];for(let u=a.params.length-1;u>=0;u--){let d=a.params[u];if(d.name===""||d.name.startsWith("_")||IY(c.get(d.name),a.paramsEndLine,a.endLine))break;l.unshift(d.name)}return l.length===0?null:{symbol:s.symbol,shortName:T(s.symbol),file:s.relativePath,startLine:s.startLine,endLine:s.endLine,paramCount:a.paramCount,unusedTrailing:l}},orderResults:(s,a)=>a.unusedTrailing.length-s.unusedTrailing.length||s.file.localeCompare(a.file)||s.startLine-a.startLine,limit:r})}function EY(e){let t=se(e);return t==="typescript"||t==="tsx"||t==="javascript"}function IY(e,t,n){return e?e.some(r=>r>t&&r<=n):!1}var wY=new Set(Wt());function hp(e,t){let{scope:n,minLoc:r=10,limit:i=30,scanLimit:o}=t??{},s=new H(e);return kt({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:r,requireFunctionLikeSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,filterCandidate:LY,profile:{name:"complexity-hotspots"},prepare:a=>{let c=DY(e,a),l=t?.semantic!==!1,u=l?st(e):null;u?.materializeReferences(a,{prefetchCallees:!0});let d=s.crossFileCallerMap(a,{semantic:!1});return{callerMap:u?en(d,u.callerMap(a)):d,calleeMap:s.calleeMap(a,{semantic:l}),languageByFile:c,clojureCallableIds:MY(e,a,c),branchEstimates:VE(e,a)}},evaluate:(a,c)=>PY(a,c,r),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:i})}function LY(e){return e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&wY.has(e.kind):!0}function PY(e,t,n){if(t.languageByFile.get(e.relativePath)==="clojure"&&!t.clojureCallableIds.has(e.symbolId))return null;let r=e.endLine-e.startLine+1;if(r<n)return null;let i=t.callerMap.get(e.symbolId)?.size??0,o=t.calleeMap.get(e.symbolId)??[],s=new Set,a=new Set;for(let m of o){let p=`${m.symbol}|${m.file}`;s.add(p),m.file!==e.relativePath&&a.add(p)}let c=a.size,l=s.size,u=t.branchEstimates.get(e.symbolId)??{branches:0,estimateBasis:"regex-fallback"},d=u.branches+1;return{symbol:e.symbol,shortName:T(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:r,fanIn:i,fanOut:c,calleeCount:l,branches:u.branches,estimateBasis:u.estimateBasis,score:Math.round(r/50*(i/5)*Math.max(c/5,1)*Math.max(d/5,1)*100)/100}}function DY(e,t){let n=[...new Set(t.map(o=>o.relativePath))];if(n.length===0)return new Map;let r=n.map(()=>"?").join(", "),i=e.all(`SELECT relative_path, language
458
- FROM documents
459
- WHERE relative_path IN (${r})`,...n);return new Map(i.map(o=>[o.relative_path,o.language?.toLowerCase()??null]))}function MY(e,t,n){let r=new Set,i=new Map;for(let o of t){if(n.get(o.relativePath)!=="clojure")continue;let s=i.get(o.relativePath);s||(s=new Set((K(e,o.relativePath)?.callables??[]).map(a=>`${a.name}:${a.startLine}`)),i.set(o.relativePath,s)),s.has(`${o.leaf}:${o.startLine}`)&&r.add(o.symbolId)}return r}import{readdirSync as TY}from"fs";import{basename as AY,join as gI}from"path";function FY(e,t,n={}){let r=new Set(e),i=new Set(t),o=[...i].filter(a=>!r.has(a)).sort(),s=n.allowExtra?[]:[...r].filter(a=>!i.has(a)).sort();return{missing:o,extra:s}}function kY(e,t){let n=NY(e,t.file,t.keys);if(!n.ok)return{name:t.name,file:t.file,status:"unavailable",missing:[],extra:[],unavailableReason:n.reason};let r=HY(e.config.projectRoot,t.mustEqual),i=FY(n.keys,r,{allowExtra:t.allowExtra??!1}),o=i.missing.length>0||i.extra.length>0?"violated":"ok";return{name:t.name,file:t.file,status:o,missing:i.missing,extra:i.extra}}function yI(e,t){return t.map(n=>kY(e,n))}function NY(e,t,n){return n.type==="markdown-list"?jY(e,t,n.marker):_Y(e,t,n)}function _Y(e,t,n){if(!W(e,t))return{ok:!1,reason:`file not found: ${t}`};let i=se(t);if(!i)return{ok:!1,reason:`unsupported file type for ${n.type} extraction: ${t}`};let o=J(e,t);if(!o)return{ok:!1,reason:`tree-sitter parser unavailable for ${i} (${t}) \u2014 contract skipped, not silently passed`,disclosedUnavailable:{language:i,reason:"parser-unavailable"}};let s=n.type==="object-literal-keys"?OY(o,n.identifier):$Y(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 bI(e){let t=e.childForFieldName("value");return t?t.type==="as_expression"||t.type==="satisfies_expression"?t.namedChild(0):t:null}function OY(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=bI(n);if(i?.type==="object")return BY(i)}return null}function BY(e){let t=new Set;for(let n of e.namedChildren)if(n.type==="pair"){let r=n.childForFieldName("key");r&&t.add(SI(r.text))}else n.type==="shorthand_property_identifier"&&t.add(n.text);return[...t].sort()}function $Y(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=bI(n);if(i?.type!=="array")continue;let o=new Set;for(let s of i.namedChildren)s.type==="string"&&o.add(SI(s.text));return[...o].sort()}return null}function SI(e){return e.length>=2&&(e[0]==="'"&&e.endsWith("'")||e[0]==='"'&&e.endsWith('"'))?e.slice(1,-1):e}function jY(e,t,n){let r=W(e,t);if(!r)return{ok:!1,reason:`file not found: ${t}`};let i=vI(r,n);return i===null?{ok:!1,reason:`no <!-- BEGIN GENERATED ${n} --> ... <!-- END GENERATED ${n} --> block in ${t}`}:{ok:!0,keys:CI(i)}}function vI(e,t){let n=xe(t),i=new RegExp(`<!--\\s*BEGIN GENERATED ${n}\\s*-->([\\s\\S]*?)<!--\\s*END GENERATED ${n}\\s*-->`).exec(e);return i?i[1]:null}function CI(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 HY(e,t){switch(t.type){case"top-level-dirs":return hI(gI(e,t.path));case"file-glob":return[...new Set(kc(e,t.pattern).map(n=>AY(n)))].sort();case"registered-commands":return UY(e);case"builtin-skills":return hI(gI(e,"skills"))}}function hI(e){let t;try{t=TY(e,{withFileTypes:!0})}catch{return[]}return t.filter(n=>n.isDirectory()&&!n.name.startsWith(".")).map(n=>n.name).sort()}function UY(e){let t;try{t=Ye(e,"docs/COMMAND_REFERENCE.md",{maxBytes:8*1024*1024,inputKind:"generated command reference"})}catch(r){if(!Je(r))throw r;return[]}let n=vI(t,"COMMAND REFERENCE");return n?CI(n):[]}function kn(e){return e.scoreCount??e.count}function EI(e){let t=KY(e),{breakdown:n,pressure:r}=WY(e),i=RI(n,"risk"),o=RI(n,"hygiene");return{score:Math.min(i,o),riskScore:i,hygieneScore:o,scoreBreakdown:n,overview:{documents:e.statsResult.documents,symbols:e.statsResult.symbols,indexSizeBytes:e.statsResult.indexSizeBytes},findings:{deadSymbols:e.dead.count,deadLoc:e.dead.loc,isolatedSymbols:e.isolated.count,isolatedLoc:e.isolated.loc,cycles:e.realCycleCount,similarPairs:e.similarCount,duplicateBodyGroups:e.duplicateBodies.count,duplicateBodyLoc:e.duplicateBodies.loc,twinDriftGroups:e.twinDrift.count,twinDriftLoc:e.twinDrift.loc,reactComponentDuplicatePairs:e.reactComponentDuplicates.count,reactHookCandidatePairs:e.reactHookCandidates.count,reactHookCandidateScoreCount:kn(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:kn(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:kn(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:qY(e),validation:zY(e),suppressions:e.suppressions,actions:t,pressure:r,topComplexity:e.complexity.top,detectorEvidence:e.detectorEvidence,warnings:e.warnings.length>0?e.warnings:void 0}}function qY(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:GY(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 GY(e){let t=e.gitEvidence?.fileStats;return t?e.complexity.top.map(n=>{let r=n.file?t[n.file]?.changes??0:0;return{...n,changes:r,weighted:un(n.score*Math.log2(1+r))}}).sort((n,r)=>r.weighted-n.weighted):null}function zY(e){let t=e.gitEvidence?.fileStats;if(!t)return null;let n={dead:e.dead.files??[],isolated:e.isolated.files??[],twinDrift:e.twinDrift.files??[],wrappers:e.wrappers.files??[],passthroughs:e.passthroughs.files??[],stale:e.stale.files??[],reactComponents:e.reactComponentDuplicates.files??[],reactHooks:e.reactHookCandidates.files??[],reactLargeComponents:e.reactLargeComponentPressure.files??[],vueComponents:e.vueComponentDuplicates.files??[],vueComposables:e.vueComposableCandidates.files??[],vueLargeViews:e.vueLargeViewPressure.files??[]},r=new Set(Object.values(n).flat()),i=0,o=0,s=0;for(let[u,d]of Object.entries(t))r.has(u)?i+=d.fixChanges:(o+=d.fixChanges,s+=1);let a=r.size>0?un(i/r.size):0,c=s>0?un(o/s):0,l={};for(let[u,d]of Object.entries(n)){let m=new Set(d);if(m.size===0)continue;let p=0;for(let g of m)p+=t[g]?.fixChanges??0;let f=un(p/m.size);l[u]={flaggedFiles:m.size,fixDensity:f,lift:c>0?un(f/c):null}}return{flaggedFiles:r.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:r.size>0&&c>0?un(a/c):null,byCategory:l,validationBasis:{method:"subject-regex",commitsScanned:e.gitEvidence?.commitsScanned??0}}}function un(e){return Math.round(e*100)/100}function II(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function ol(e,t="existing shared infrastructure discount"){let n=kn(e);return Math.abs(n-e.count)<.01?"":` (${II(n)} score-weighted after ${t})`}function ws(e,t){let n=kn(e),r=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?r:`${r} (${II(n)} score-weighted)`}function KY(e){let t=[];if(e.dead.count>0&&t.push({category:"Dead code",evidence:"graph-fact",evidenceContractId:"dead-visible-references",description:`${e.dead.count} indexed symbols with no visible repository references \u2014 review runtime/framework roots and the capability disclosure, then verify any deletion with cleanup-plan --verify`,effort:"low",impact:"high",count:e.dead.count,locRecoverable:e.dead.loc}),e.isolated.count>0&&t.push({category:"Isolated symbols",evidence:"graph-fact",evidenceContractId:"isolated-visible-connectivity",description:`${e.isolated.count} symbols with no visible indexed or source-supported caller/callee after root exclusions \u2014 runtime reflection and generated dispatch remain disclosed blind spots`,effort:"low",impact:"medium",count:e.isolated.count,locRecoverable:e.isolated.loc}),e.realCycleCount>0&&t.push({category:"Circular dependencies",evidence:"graph-fact",description:`${e.realCycleCount} indexed dependency cycle(s) \u2014 inspect ownership and runtime order before choosing whether or how to break them`,effort:"medium",impact:"high",count:e.realCycleCount,locRecoverable:0}),e.similarCount>0&&t.push({category:"Similar functions",evidence:"heuristic",evidenceContractId:"duplicate-structural-candidate",description:`${e.similarCount} pairs share disclosed call or source-token evidence beyond imports \u2014 review domain identity before considering consolidation`,effort:"medium",impact:"medium",count:e.similarCount,locRecoverable:0}),e.duplicateBodies.count>0&&t.push({category:"Duplicate function bodies",evidence:"heuristic",evidenceContractId:"duplicate-structural-candidate",description:`${e.duplicateBodies.count} exact small-body group(s) across files \u2014 consolidate only when the domain concept matches`,effort:"low",impact:"medium",count:e.duplicateBodies.count,locRecoverable:e.duplicateBodies.loc}),e.twinDrift.count>0&&t.push({category:"Drifted twin implementations",evidence:"heuristic",description:`${e.twinDrift.count} same-name (or near-name) function group(s) across files with diverged or identical bodies \u2014 determine whether they represent the same concept before acting`,effort:"medium",impact:"medium",count:e.twinDrift.count,locRecoverable:0}),e.reactComponentDuplicates.count>0&&t.push({category:"Duplicated React components",evidence:"heuristic",description:`${e.reactComponentDuplicates.count} React component pair(s) share JSX structure \u2014 review whether local product intent justifies reuse`,effort:"medium",impact:"medium",count:e.reactComponentDuplicates.count,locRecoverable:e.reactComponentDuplicates.loc}),e.reactHookCandidates.count>0&&t.push({category:"Duplicated React hook behavior",evidence:"heuristic",description:`${e.reactHookCandidates.count} React component pair(s) share state/effect/request behavior${ol(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${ol(e.vueComposableCandidates)} \u2014 review whether a common composable would preserve ownership and lifecycle semantics`,effort:"medium",impact:"medium",count:e.vueComposableCandidates.count,locRecoverable:e.vueComposableCandidates.loc}),e.vueLargeViewPressure.count>0&&t.push({category:"Large Vue views",evidence:"heuristic",description:`${e.vueLargeViewPressure.count} Vue file(s) concentrate template/script/style pressure \u2014 split by reason to change`,effort:"medium",impact:"medium",count:e.vueLargeViewPressure.count,locRecoverable:0}),e.extractCount>0&&t.push({category:"Extraction candidates",evidence:"heuristic",description:`${e.extractCount} large functions with isolated callee clusters \u2014 review same-file or feature-local extraction seams`,effort:"medium",impact:"medium",count:e.extractCount,locRecoverable:0}),e.wrappers.count>0&&t.push({category:"Wrapper functions",evidence:"heuristic",evidenceContractId:"wrapper-indirection-candidate",description:`${e.wrappers.count} single-consumer symbols${ol(e.wrappers,"boundary-evidence discount")} \u2014 inspect whether each is indirection or an intentional API, framework, or ownership boundary`,effort:"low",impact:"low",count:e.wrappers.count,locRecoverable:e.wrappers.loc}),e.passthroughs.count>0&&t.push({category:"Passthrough functions",evidence:"heuristic",evidenceContractId:"passthrough-forwarding-candidate",description:`${e.passthroughs.count} functions that literally forward to one callee \u2014 inspect whether each is unnecessary indirection or an intentional boundary`,effort:"low",impact:"low",count:e.passthroughs.count,locRecoverable:e.passthroughs.loc}),e.stale.count>0){let i=[];e.stale.unused>0&&i.push(`${e.stale.unused} unused`),e.stale.singleUse>0&&i.push(`${e.stale.singleUse} single-consumer (not in types file)`),t.push({category:"Stale abstractions",evidence:"heuristic",evidenceContractId:"stale-abstraction-candidate",description:`${i.join(", ")} \u2014 review public, runtime-registration, and ownership evidence before removing, moving, or inlining`,effort:"low",impact:"medium",count:e.stale.count,locRecoverable:e.stale.loc})}if(e.drift.count>0){let i=[];e.drift.unusedImports>0&&i.push(`${e.drift.unusedImports} unused imports`),e.drift.architectureViolations>0&&i.push(`${e.drift.architectureViolations} declared architecture violations`),t.push({category:"Structural drift",evidence:"heuristic",description:`${i.join(", ")} \u2014 repair direct dependency-rule breaks; inspect boundary signals with \`drift --architecture\``,effort:e.drift.architectureViolations>0?"medium":"low",impact:e.drift.architectureViolations>0?"medium":"low",count:e.drift.count,locRecoverable:0})}if(e.coverageContracts.count>0&&t.push({category:"Coverage contract drift",evidence:"graph-fact",description:`${e.coverageContracts.count} configured coverage contract(s) drifted from their ground-truth source (enumeration rot) \u2014 run \`scip-query health --json\` for the missing/extra keys`,effort:"low",impact:"medium",count:e.coverageContracts.count,locRecoverable:0}),e.gitEvidence&&e.gitEvidence.hiddenCoupling.pairCount>0){let i=e.gitEvidence.hiddenCoupling.top[0];t.push({category:"Hidden coupling",evidence:"change-graph",description:`${e.gitEvidence.hiddenCoupling.pairCount} file pair(s) co-change without a structural link`+ol({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:e.gitEvidence.hiddenCoupling.scoreCount},"broad/stale-history discount")+(i?` (e.g. ${i.fileA} \u2194 ${i.fileB})`:"")+" \u2014 inspect whether a shared concept, generated artifact, or coordinated contract explains the history",effort:"medium",impact:"high",count:e.gitEvidence.hiddenCoupling.pairCount,locRecoverable:0})}let n={high:3,medium:2,low:1},r={low:3,medium:2,high:1};return t.sort((i,o)=>{let s=n[i.impact]*r[i.effort];return n[o.impact]*r[o.effort]-s}),t}var xI={"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 RI(e,t){let n=e.filter(r=>r.kind===t).reduce((r,i)=>r+i.points,0);return Math.max(0,Math.min(100,100-n))}function WY(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),r=[],i=[],o=(R,E,I)=>{E>0&&r.push({axis:R,points:E,detail:I,kind:xI[R]??"hygiene"})},s=(R,E,I,w,A,D,k)=>{let L=Math.max(w,1);if(I<=L)return;let F=I/L,P=Math.min(A,Math.ceil(Math.log2(F)*D));if(P<=0)return;let j=xI[R]??"hygiene";i.push({axis:R,category:E,kind:j,count:I,threshold:un(L),ratio:un(F),extraPenalty:P}),o(R,P,`${I} ${k} exceed pressure threshold ${un(L)} (${un(F)}x)`)},a=e.dead.count/n;o("dead-code",Math.min(20,Math.round(a*200)),`${e.dead.count} dead symbols (${e.dead.loc} LOC deletable)`);let c=e.isolated.count/n;o("isolated",Math.min(10,Math.round(c*200)),`${e.isolated.count} isolated symbols (${e.isolated.loc} LOC deletable)`),o("cycles",Math.min(15,e.realCycleCount*5),`${e.realCycleCount} real dependency cycle(s)`);let l=e.similarCount/n*1e3;o("similar",Math.min(10,Math.round(l)),`${e.similarCount} similar function pair(s)`);let u=e.duplicateBodies.count/n*1e3;o("duplicate-bodies",Math.min(10,Math.round(u*2)),`${e.duplicateBodies.count} exact duplicate small-body group(s) (${e.duplicateBodies.loc} duplicate LOC)`);let d=e.twinDrift.count/n*1e3;o("twin-drift",Math.min(10,Math.round(d*2)),`${e.twinDrift.count} drifted twin implementation group(s) (same or near-same name, diverged or identical bodies)`);let m=e.reactComponentDuplicates.count/t*1e3;o("react-component-duplicates",Math.min(10,Math.round(m)),`${e.reactComponentDuplicates.count} duplicated React component pair(s)`);let p=kn(e.reactHookCandidates),f=p/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(f)),ws(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=kn(e.vueComposableCandidates),S=b/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(S)),ws(e.vueComposableCandidates,"duplicated Vue behavior pair(s)"));let y=e.vueLargeViewPressure.count/t*1e3;o("vue-large-view-pressure",Math.min(5,Math.round(y/2)),`${e.vueLargeViewPressure.count} large Vue view pressure file(s)`);let x=kn(e.wrappers);o("wrappers",Math.min(3,x),ws(e.wrappers,"wrapper candidate(s)"));let v=kn(e.passthroughs);o("passthroughs",Math.min(3,v),ws(e.passthroughs,"passthrough candidate(s)")),o("stale-abstractions",Math.min(8,e.stale.unused),`${e.stale.unused} unused stale abstraction(s); ${e.stale.singleUse} single-consumer signal(s)`);let C=e.drift.direct/t;if(o("drift",Math.min(5,Math.round(C*50)),`${e.drift.direct} direct drift finding(s); ${e.drift.signal} signal drift finding(s)`),o("complexity",Math.min(5,e.complexity.extremeCount*2),`${e.complexity.extremeCount} extreme complexity hotspot(s)`),e.gitEvidence){let R=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(R/10)),ws({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:R},"co-changing pair(s) without a structural link"))}if(s("cycles-pressure","Circular dependencies",e.realCycleCount,3,10,3,"cycle(s)"),s("complexity-pressure","Extreme complexity",e.complexity.extremeCount,3,5,2,"extreme complexity hotspot(s)"),e.gitEvidence){let R=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",R,50,10,4,"score-weighted co-changing pair(s)")}return s("similar-pressure","Similar functions",e.similarCount,Math.max(50,n*.01),8,4,"similar function pair(s)"),s("duplicate-bodies-pressure","Duplicate function bodies",e.duplicateBodies.count,Math.max(20,n*.005),8,4,"exact duplicate small-body group(s)"),s("twin-drift-pressure","Drifted twin implementations",e.twinDrift.count,Math.max(20,n*.005),8,4,"drifted twin implementation group(s)"),s("react-component-duplicates-pressure","Duplicated React components",e.reactComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated React component pair(s)"),s("react-hook-candidates-pressure","Duplicated React hook behavior",p,Math.max(10,t*.01),8,4,"duplicated React behavior pair(s)"),s("react-large-component-pressure-pressure","Large React components",e.reactLargeComponentPressure.count,Math.max(10,t*.01),4,2,"large React component pressure file(s)"),s("vue-component-duplicates-pressure","Duplicated Vue components",e.vueComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated Vue component pair(s)"),s("vue-composable-candidates-pressure","Duplicated Vue behavior",b,Math.max(10,t*.01),8,4,"duplicated Vue behavior pair(s)"),s("vue-large-view-pressure-pressure","Large Vue views",e.vueLargeViewPressure.count,Math.max(10,t*.01),4,2,"large Vue view pressure file(s)"),s("extract-pressure","Extraction candidates",e.extractCount,Math.max(50,n*.01),4,2,"extraction candidate(s)"),s("wrappers-pressure","Wrapper functions",x,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",v,50,4,2,"passthrough candidate(s)"),s("stale-abstractions-pressure","Single-consumer stale abstraction signals",e.stale.singleUse,Math.max(50,n*.02),4,2,"single-consumer stale abstraction signal(s)"),s("drift-pressure","Structural drift signals",e.drift.signal,Math.max(10,t*.1),4,2,"signal drift finding(s)"),{breakdown:r,pressure:i}}import{getHeapStatistics as VY}from"v8";var YY=64*1024*1024;function yp(){let e=globalThis.gc;if(!e)return;let t=VY();t.heap_size_limit-t.used_heap_size<YY||e()}var JY=[{id:"dead-visible-references",detector:"dead",claim:"The symbol has no visible repository reference after entry, framework, and rooted-symbol exclusions.",relationRequirements:[{family:"identity",subtype:"references",minimumStrength:"exact"},{family:"execution",subtype:"call",minimumStrength:"exact"}],structuralEvidence:["entry-surface exclusions","framework/source fallback references","rooted-symbol exclusions"],calibration:"mixed",providerCoverage:"partial",nonClaims:["Absence of visible references does not prove absence of reflection, generated dispatch, or external use."],recoverWith:"scip-query evidence --symbol <symbol> --edge execution --edge runtime --edge identity --direction both --depth 2 --max-edges 100"},{id:"isolated-visible-connectivity",detector:"isolated",claim:"The callable has no visible non-self caller or callee after entry, framework, and rooted-symbol exclusions.",relationRequirements:[{family:"execution",subtype:"call",minimumStrength:"exact"},{family:"identity",subtype:"references",minimumStrength:"exact"}],structuralEvidence:["entry-surface exclusions","framework contract exclusions","source fallback callers"],calibration:"mixed",providerCoverage:"partial",nonClaims:["Visible graph isolation does not establish runtime unreachability through reflection or generated dispatch."],recoverWith:"scip-query evidence --symbol <symbol> --edge execution --edge runtime --edge identity --direction both --depth 2 --max-edges 100"},{id:"wrapper-indirection-candidate",detector:"wrapper-candidates",claim:"A small callable has one visible consumer and wrapper-shaped delegation, after boundary evidence is disclosed.",relationRequirements:[{family:"execution",subtype:"call",minimumStrength:"exact"},{family:"ownership",subtype:"contains",minimumStrength:"exact"}],structuralEvidence:["callable body shape","public and runtime-boundary signals","consumer fan-in"],calibration:"candidate",providerCoverage:"partial",nonClaims:["Wrapper shape does not prove that an API, ownership, observability, or compatibility boundary is unnecessary."],recoverWith:"scip-query inspect --symbol <symbol> --view behavior"},{id:"passthrough-forwarding-candidate",detector:"passthrough-candidates",claim:"A small callable visibly forwards to one callee, with public-facade and boundary signals disclosed.",relationRequirements:[{family:"execution",subtype:"call",minimumStrength:"exact"},{family:"contract",subtype:"uses-contract-symbol",minimumStrength:"exact"}],structuralEvidence:["statement-complete forwarding shape","public facade evidence","runtime-boundary signals"],calibration:"mixed",providerCoverage:"partial",nonClaims:["Literal forwarding does not prove the callable has no contract, naming, policy, or compatibility role."],recoverWith:"scip-query inspect --symbol <symbol> --view behavior"},{id:"stale-abstraction-candidate",detector:"stale-abstractions",claim:"A type-like abstraction has zero or one visible real consumer after re-export and ownership distinctions.",relationRequirements:[{family:"identity",subtype:"references",minimumStrength:"exact"},{family:"ownership",subtype:"contains",minimumStrength:"exact"}],structuralEvidence:["definition kind","barrel-only consumer distinction","defining-file usage"],calibration:"mixed",providerCoverage:"partial",nonClaims:["Low visible consumer count does not prove a public contract or runtime-registered type is obsolete."],recoverWith:"scip-query evidence --symbol <symbol> --edge identity --edge ownership --edge contract --direction both --depth 2 --max-edges 100"},{id:"complexity-control-pressure",detector:"complexity-hotspots",claim:"A callable concentrates local branch/control pressure and graph fan-in or fan-out.",relationRequirements:[{family:"execution",subtype:"predicate-consequence",minimumStrength:"exact"},{family:"execution",subtype:"call",minimumStrength:"exact"}],structuralEvidence:["AST branch count or disclosed regex fallback","call fan-in","callee count"],calibration:"mixed",providerCoverage:"partial",nonClaims:["Structural complexity does not establish runtime frequency, latency, defect density, or a required refactor."],recoverWith:"scip-query inspect --symbol <symbol> --view behavior"},{id:"decorative-checker-terminal-behavior",detector:"decorative-checkers",claim:"A checker-shaped callable lacks a visible failure terminal directly or through one resolved delegate.",relationRequirements:[{family:"execution",subtype:"returns",minimumStrength:"exact"},{family:"execution",subtype:"throws",minimumStrength:"exact"}],structuralEvidence:["checker naming shape","direct terminal behavior","one-hop delegate body"],calibration:"mixed",providerCoverage:"partial",nonClaims:["No visible terminal does not prove the checker cannot fail through an opaque call, exception, or process exit."],recoverWith:"scip-query inspect --symbol <symbol> --view behavior"},{id:"duplicate-structural-candidate",detector:"duplicate and similarity detectors",claim:"Two source units share the detector-specific structural or token pattern.",relationRequirements:[],structuralEvidence:["normalized source/token/JSX/template similarity"],calibration:"candidate",providerCoverage:"partial",nonClaims:["Structural similarity does not establish shared domain identity or justify consolidation."],recoverWith:"scip-query inspect --symbol <symbol-a> --symbol <symbol-b> --view behavior"}];function wI(e=new Set(["indexed-graph","source-facts"])){return JY.map(t=>{let n=t.relationRequirements.map(i=>{let o=fc(i.family,i.subtype);if(!o)throw new Error(`Detector ${t.id} names an unregistered relation ${i.family}/${i.subtype}`);if(!o.relation.evidenceStrengths.includes(i.minimumStrength))throw new Error(`Detector ${t.id} requires unsupported strength ${i.minimumStrength} for ${i.family}/${i.subtype}`);return o.provider}),r=[...new Set(n.flatMap(i=>i.requirements))].filter(i=>!e.has(i));return{...t,status:r.length>0?"unsupported":t.calibration,providerIds:[...new Set(n.map(i=>i.id))],unavailableRequirements:r}})}var XY=50,QY=25e3,ZY=2500,LI=2500,PI=50,eJ=10,sl=["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"],tJ={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:oJ(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:sJ(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:aJ(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:cJ(e,t,n)}),"duplicate-bodies":(e,t,n)=>({phase:"duplicate-bodies",duplicateBodies:uJ(e,t,n)}),"twin-drift":(e,t,n)=>({phase:"twin-drift",twinDrift:dJ(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:mJ(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:pJ(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:fJ(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:gJ(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:hJ(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:yJ(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:lJ(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:bJ(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:SJ(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:vJ(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:EJ(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:IJ(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:CJ(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:xJ(e,n)}),"coverage-contracts":(e,t,n)=>({phase:"coverage-contracts",coverageContracts:RJ(e,n)})};function bp(e,t,n={}){return nJ(e,[t],n)[0]}function nJ(e,t,n={}){return rJ(e,n.full!==!1,(r,i)=>{let o={...i,releaseCachesBetweenPhases:!1};return t.map(s=>tJ[s](e,n.scope,o,r))})}function rJ(e,t,n){let r=_r(e),i=wJ(r,t);try{return n(r,i)}finally{mm(e,{semanticProvider:!0}),yp()}}function Sp(e){return EI(iJ(e))}function iJ(e){let t=De(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,detectorEvidence:wI(),dead:De(e,"dead").dead,isolated:De(e,"isolated").isolated,realCycleCount:De(e,"cycles").realCycleCount,similarCount:De(e,"similar").similarCount,duplicateBodies:De(e,"duplicate-bodies").duplicateBodies,twinDrift:De(e,"twin-drift").twinDrift,reactComponentDuplicates:De(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:De(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:De(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:De(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:De(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:De(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:De(e,"extract-candidates").extractCount,wrappers:De(e,"wrapper-candidates").wrappers,passthroughs:De(e,"passthrough-candidates").passthroughs,stale:De(e,"stale-abstractions").stale,drift:De(e,"drift").drift,complexity:De(e,"complexity-hotspots").complexity,gitEvidence:DI(e,"git-evidence")?.gitEvidence??null,suppressions:DI(e,"suppressions")?.suppressions??null,coverageContracts:De(e,"coverage-contracts").coverageContracts}}function DI(e,t){return e.find(n=>n.phase===t)}function De(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function oJ(e,t,n){return we(e,n,"dead",()=>{let r=Vr(e,{scope:t,...Ie.dead,scanLimit:n.candidateScanLimit,semantic:n.semantic});return al(DJ(e,r.symbols))})}function sJ(e,t,n){return we(e,n,"isolated",()=>{let r=os(e,{scope:t,...Ie.isolated,scanLimit:n.candidateScanLimit,semantic:n.semantic});return al(MJ(e,r))})}function aJ(e,t,n){return we(e,n,"cycles",()=>rs(e,{scope:t}).filter(i=>i.kind==="real").length)}function cJ(e,t,n){let r=we(e,n,"similar",()=>xm(e,{scope:t,...Ie.similar,scanLimit:n.candidateScanLimit,semantic:n.semantic}));return Math.min(r,n.candidateResultLimit)}function lJ(e,t,n){return we(e,n,"extract-candidates",()=>ps(e,{scope:t,...Ie.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}).length)}function uJ(e,t,n){return we(e,n,"duplicate-bodies",()=>{let r=ys(e,{scope:t,...Ie.duplicateBodies,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),i=new Set,o=0;for(let s of r)for(let a of s.functions.slice(1))i.add(a.file),o+=a.loc;return{count:r.length,loc:o,files:[...i]}})}function dJ(e,t,n){return we(e,n,"twin-drift",()=>{let r=Yc(e,{scope:t,...Ie.twinDrift,scanLimit:n.candidateScanLimit}).filter(s=>s.relationship==="divergent"||s.relationship==="identical"),i=new Set,o=0;for(let s of r)for(let a of s.members)i.add(a.file),o+=a.loc;return{count:r.length,loc:o,files:[...i].sort()}})}function mJ(e,t,n){return we(e,n,"react-component-duplicates",()=>{let r=ls(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return vp(r)})}function pJ(e,t,n){return we(e,n,"react-hook-candidates",()=>{let r=us(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return AI(r,AJ)})}function fJ(e,t,n){return we(e,n,"react-large-component-pressure",()=>{let r=Rm(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return TJ(r)})}function gJ(e,t,n){return we(e,n,"vue-component-duplicates",()=>{let r=ds(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return vp(r)})}function hJ(e,t,n){return we(e,n,"vue-composable-candidates",()=>{let r=ms(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return AI(r,FJ)})}function yJ(e,t,n){return we(e,n,"vue-large-view-pressure",()=>{let r=Em(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return al(r)})}function bJ(e,t,n){return we(e,n,"wrapper-candidates",()=>{let r=Is(e,{scope:t,...Ie.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return TI(r,kJ)})}function SJ(e,t,n){return we(e,n,"passthrough-candidates",()=>{let r=bs(e,{scope:t,...Ie.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return TI(r,NJ)})}function vJ(e,t,n){return we(e,n,"stale-abstractions",()=>{let r=Es(e,{scope:t,...Ie.stale,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}),i=r.filter(o=>o.consumers===0).length;return{count:r.length,loc:r.reduce((o,s)=>o+s.loc,0),files:[...new Set(r.map(o=>o.file))],unused:i,singleUse:r.length-i}})}function CJ(e,t){return we(e,t,"git-evidence",()=>{let n=Ht(e,{historyMode:t.gitHistoryMode}),r=n.fileChurn();if(!r)return null;let i=n.commitHistory(),o=gs(e,void 0,{limit:t.candidateResultLimit,historyMode:t.gitHistoryMode}),s={};for(let[a,c]of r)s[a]={changes:c.changes,fixChanges:c.fixChanges};return{amplification:n.changeAmplification(),hiddenCoupling:{pairCount:o.findings.length,scoreCount:Cp(o.findings.reduce((a,c)=>a+MI(c),0)),top:o.findings.slice(0,5).map(a=>({fileA:a.fileA,fileB:a.fileB,together:a.together,confidence:a.confidence,focusedTogether:a.focusedTogether,broadTogether:a.broadTogether,broadCommitRatio:a.broadCommitRatio,lastTogetherAt:a.lastTogetherAt,recentTogether:a.recentTogether,commitScope:a.commitScope,recency:a.recency,scoreWeight:MI(a),subjectContext:a.subjectContext}))},fileStats:s,commitsScanned:i?.commits.length??0}})}function xJ(e,t){return we(e,t,"suppressions",()=>{let n=Zc(e);return{total:n.total,byCategory:{...n.byCategory}}})}function RJ(e,t){return we(e,t,"coverage-contracts",()=>{let n=e.config.coverageContracts??[],i=yI(e,n).filter(o=>o.status!=="ok");return{count:i.length,loc:0,files:[...new Set(i.map(o=>o.file))].sort()}})}function EJ(e,t,n){return we(e,n,"drift",()=>{let r=Rs(e,{scope:t,...Ie.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY,semantic:n.semantic}),i=r.results.filter(a=>a.kind!=="pattern-deviation"),o=i.filter(a=>a.actionTier==="direct").length,s=i.length-o;return{count:i.length,unusedImports:r.unusedImports,architectureViolations:r.architectureViolations,layerViolations:r.layerViolations,direct:o,signal:s}})}function IJ(e,t,n){return we(e,n,"complexity-hotspots",()=>{let r=hp(e,{scope:t,minLoc:10,limit:n.complexityResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return{top:r.slice(0,5).map(i=>({symbol:i.shortName,score:i.score,file:i.file})),extremeCount:r.filter(i=>i.score>XY).length}})}function wJ(e,t){let n=e.symbols>=QY||e.documents>=ZY,r=t?Number.POSITIVE_INFINITY:PI,i=t?Number.POSITIVE_INFINITY:eJ;return!n||t?{candidateScanLimit:void 0,candidateResultLimit:r,complexityResultLimit:i,semantic:!0,gitHistoryMode:t?"full":"bounded",releaseCachesBetweenPhases:!0,warnings:t&&n?["Large index detected; running health without candidate scan or result caps because full mode is enabled."]:[]}:{candidateScanLimit:LI,candidateResultLimit:r,complexityResultLimit:i,semantic:!1,gitHistoryMode:"bounded",releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${LI} symbols and reported their top ${PI} findings. Enable full mode for unbounded candidate counts.`]}}function LJ(e,t){t.releaseCachesBetweenPhases&&(mm(e),yp())}function we(e,t,n,r){PJ(n);try{return r()}finally{LJ(e,t)}}function PJ(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function DJ(e,t){return t.filter(n=>!Ue(e,n.relativePath)&&!Fe(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function MJ(e,t){return t.filter(n=>!Ue(e,n.relativePath)&&!Fe(e,n.symbol,n.relativePath))}function al(e){let t=new Set;for(let n of e){let r=n.relativePath??n.file;r&&t.add(r)}return{count:e.length,loc:e.reduce((n,r)=>n+r.loc,0),files:[...t]}}function TI(e,t){return{...al(e),scoreCount:Cp(e.reduce((r,i)=>r+t(i),0))}}function TJ(e){let t=new Map;for(let n of e)t.set(n.file,Math.max(t.get(n.file)??0,n.loc));return{count:t.size,loc:[...t.values()].reduce((n,r)=>n+r,0),files:[...t.keys()]}}function vp(e){let t=new Map;for(let n of e)t.set(n.fileA,Math.max(t.get(n.fileA)??0,n.locA)),t.set(n.fileB,Math.max(t.get(n.fileB)??0,n.locB));return{count:e.length,loc:[...t.values()].reduce((n,r)=>n+r,0),files:[...t.keys()]}}function AI(e,t){return{...vp(e),scoreCount:Cp(e.reduce((r,i)=>r+t(i),0))}}function AJ(e){let t=e.sharedHooks.length>0,n=FI({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:kI(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function FJ(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=FI({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:kI(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function FI(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!_I.has(NI(t))).length+Math.min(e.functions.length,3)}function kI(e,t,n){let r=[...e,...t,...n].map(NI);return r.length>0&&r.every(i=>_I.has(i))}function NI(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function kJ(e){return e.actionTier==="signal"?.25:1}function NJ(e){return e.actionTier==="signal"?.25:1}function MI(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 Cp(e){return Math.round(e*100)/100}var _I=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 _J(e,t,n,r={}){let i=Cm(e,t,n,r);return i?{symbolA:i.symbolA,symbolB:i.symbolB,similarity:i.similarity,sharedCallees:i.sharedEvidence,uniqueToA:i.uniqueToA,uniqueToB:i.uniqueToB,consolidationStrategy:i.consolidationStrategy}:null}function OJ(e,t,n={}){let r=ts(e,t,{families:["dataflow"],...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.maxEdges!==void 0?{maxEdges:n.maxEdges}:{}});return{kind:"value-flow",targets:r.targets,edges:r.edges,coverage:{status:r.coverage.status,basis:"proved-bounded-static-value-flow",analysisBasis:"partial-system-definition-use",providers:["bounded-static-value-flow","typescript-local-dependence"],supportedRelations:["compiler-identified local definitions reaching local reads through a TypeScript control-flow graph","right-hand-side local reads supplying assignments and declarations","candidate closure captures and bounded same-owner field flow with explicit evidence strength","direct argument-to-parameter forwarding at compiler-resolved calls","bounded mechanically derived static arguments","callee return value to a consumed compiler-resolved call result"],unsupportedRelations:["general heap alias and cross-instance field points-to flow","exceptional control and value flow","closure invocation order","downstream local definition-use after a call result","dynamic calls not resolved by the semantic provider"],graph:r.coverage}}}var BJ=/:\d+(?:-\d+)?$/u;function $J(e,t,n={}){let r=n.direction??"backward",i=n.maxDepth??3;if(!Number.isSafeInteger(i)||i<0)throw new RangeError(`Dependence-slice depth must be a non-negative safe integer; received ${i}.`);let o=BJ.test(t),s=ts(e,o?{locations:[t]}:{symbols:[t]},{families:["execution","runtime","dataflow","ownership"],maxDepth:i+1,maxEdges:n.maxEdges??200}),a=new Set(s.targets.flatMap(d=>d.nodeIds)),c=new Set(a),l=new Map;OI(s.edges,c,l,0);for(let d=1;d<=i;d+=1){let m=[];for(let p of s.edges)if(r==="backward"?c.has(p.to.id):c.has(p.from.id)){let f=r==="backward"?p.from.id:p.to.id;if(c.has(f))continue;m.push(f),l.set(p.id,d)}if(m.length===0)break;for(let p of m)c.add(p);OI(s.edges,c,l,d)}let u=s.edges.filter(d=>c.has(d.from.id)&&c.has(d.to.id)).filter(d=>l.has(d.id)||d.family==="ownership").map(d=>({...d,traversalDepth:l.get(d.id)??0,supporting:d.family!=="dataflow"&&!jJ(d)})).sort((d,m)=>d.traversalDepth-m.traversalDepth||d.family.localeCompare(m.family)||d.from.label.localeCompare(m.from.label)||d.to.label.localeCompare(m.to.label));return{kind:"dependence-slice",direction:r,criterion:t,targets:s.targets,nodeIds:[...c].sort(),edges:u,coverage:{status:s.coverage.status,criterionKind:o?"source-location-summary":"symbol-summary",basis:"partial-system-dependence-graph",analysisBasis:"typescript-cfg-reaching-definitions-plus-system-edges",providers:["typescript-local-dependence","bounded-static-value-flow"],graph:s.coverage,unsupportedRelations:["general heap alias and cross-instance field points-to flow","exceptional control and value flow","closure invocation order","downstream local definition-use after a call result","unresolved dynamic dispatch"]}}}function OI(e,t,n,r){let i=!0;for(;i;){i=!1;for(let o of e)o.family!=="ownership"||!t.has(o.from.id)||t.has(o.to.id)||(t.add(o.to.id),n.set(o.id,r),i=!0)}}function jJ(e){return e.semanticFamily==="control"&&e.sourceKind==="control-dependence"}function HJ(e,t={}){let{scope:n,limit:r}=t,i=new H(e),o=JJ([...UJ(e,n),...zJ(e,i,n)]);return XJ(o),r?o.slice(0,r):o}function UJ(e,t){let n=[];for(let r of qJ(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||md(e,r.barrel_path)||W(e,r.barrel_path)&&Us(e,r.barrel_path).length===0)continue;let i=GJ(e,r),o=i?.barrel_consumers??0,s=i?.direct_consumers??0;o!==0||s!==0||n.push({barrelFile:r.barrel_path,symbol:r.symbol,shortName:T(r.symbol),originalFile:r.original_path,barrelConsumers:o,directConsumers:s,...$I(e,r.barrel_path)})}return n}function qJ(e,t){let n=t?"AND barrel_d.relative_path LIKE ?":"",r=t?[`%${t}%`]:[];return e.all(`WITH barrel_refs AS MATERIALIZED (
460
- SELECT DISTINCT
461
- barrel_d.id AS barrel_doc_id,
462
- barrel_d.relative_path AS barrel_path,
463
- m.symbol_id
464
- FROM documents barrel_d
465
- JOIN chunks c ON c.document_id = barrel_d.id
466
- JOIN mentions m ON m.chunk_id = c.id
467
- WHERE m.role != 1
468
- AND (barrel_d.relative_path LIKE '%/index.ts'
469
- OR barrel_d.relative_path LIKE '%/index.js'
470
- OR barrel_d.relative_path = 'index.ts'
471
- OR barrel_d.relative_path = 'index.js')
472
- ${e.pathExclusionsFor("barrel_d")}
473
- ${n}
474
- ),
475
- sym_def AS MATERIALIZED (
476
- SELECT m2.symbol_id, c2.document_id
477
- FROM barrel_refs br
478
- -- Keep the bounded barrel-symbol set on the outer side. An ordinary
479
- -- JOIN lets SQLite scan every definition mention before applying the
480
- -- barrel-symbol bloom filter on large indexes.
481
- CROSS JOIN mentions m2 ON m2.symbol_id = br.symbol_id
482
- AND m2.role = 1
483
- JOIN chunks c2 ON m2.chunk_id = c2.id
484
- GROUP BY m2.symbol_id
485
- )
486
- SELECT DISTINCT
487
- br.barrel_doc_id,
488
- br.barrel_path,
489
- gs.id AS symbol_id,
490
- gs.symbol AS symbol,
491
- orig_d.id AS original_doc_id,
492
- orig_d.relative_path AS original_path
493
- FROM barrel_refs br
494
- JOIN global_symbols gs ON br.symbol_id = gs.id
495
- JOIN sym_def ON sym_def.symbol_id = gs.id
496
- JOIN documents orig_d ON sym_def.document_id = orig_d.id
497
- WHERE orig_d.id != br.barrel_doc_id
498
- ${e.pathExclusionsFor("orig_d")}
499
- ${e.symbolNoiseFor("gs")}
500
- -- Only function-level symbols (ending with ().), not module-level
501
- AND gs.symbol LIKE '%().'
502
- ORDER BY br.barrel_path, gs.symbol`,...r)}function GJ(e,t){return e.get(`SELECT
503
- SUM(CASE WHEN uses_barrel = 1 THEN 1 ELSE 0 END) AS barrel_consumers,
504
- SUM(CASE WHEN uses_barrel = 0 THEN 1 ELSE 0 END) AS direct_consumers
505
- FROM (
506
- SELECT
507
- consumer_d.id AS consumer_doc_id,
508
- MAX(CASE WHEN EXISTS (
509
- SELECT 1
510
- FROM mentions barrel_m
511
- JOIN chunks barrel_c ON barrel_m.chunk_id = barrel_c.id
512
- WHERE barrel_c.document_id = consumer_d.id
513
- AND barrel_m.role != 1
514
- AND barrel_m.symbol_id IN (
515
- SELECT m2.symbol_id
516
- FROM mentions m2
517
- JOIN chunks c2 ON m2.chunk_id = c2.id
518
- WHERE c2.document_id = ?
519
- AND m2.role != 1
520
- )
521
- ) THEN 1 ELSE 0 END) AS uses_barrel
522
- FROM mentions ref_m
523
- JOIN chunks ref_c ON ref_m.chunk_id = ref_c.id
524
- JOIN documents consumer_d ON ref_c.document_id = consumer_d.id
525
- WHERE ref_m.symbol_id = ?
526
- AND ref_m.role != 1
527
- AND consumer_d.id != ?
528
- AND consumer_d.id != ?
529
- ${e.pathExclusionsFor("consumer_d")}
530
- GROUP BY consumer_d.id
531
- )`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function zJ(e,t,n){let r=[],i=YJ(e);for(let o of KJ(e,n))jI(i,o,o)>0||r.push(...WJ(e,t,o,i));return r}function KJ(e,t){return Q(e,{scope:t,includeIgnored:!1}).filter(n=>Us(e,n).length>0||Cr(e,n).length>0)}function WJ(e,t,n,r){let i=Us(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>BI(e,t,n,s.sourcePath,r,[VJ(s.specifier)])),o=Cr(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>BI(e,t,n,s.sourcePath,r,s.kind==="named"&&s.names.length>0?s.names:[s.kind==="star"?`* from ${s.sourcePath}`:`* namespace from ${s.sourcePath}`]));return[...i,...o]}function BI(e,t,n,r,i,o){let s=t.definitionsForFile(r);return o.map(a=>{let c=s.find(l=>l.leaf===a);return{barrelFile:n,symbol:c?.symbol??`source-reexport:${n}:${a}`,shortName:c?T(c.symbol):a,originalFile:r,barrelConsumers:0,directConsumers:jI(i,r,n),...$I(e,n)}})}function VJ(e){return e.split("::").at(-1)?.split("/").at(-1)?.replace(/\.[^.]+$/,"")??e}function $I(e,t){return En(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 YJ(e){let t=new Map;for(let n of Q(e,{includeIgnored:!1}))for(let r of ae(e,n)){if(!r.sourcePath)continue;let i=t.get(r.sourcePath)??new Set;i.add(n),t.set(r.sourcePath,i)}return t}function jI(e,t,n){let r=e.get(t);return r?r.size-(r.has(n)?1:0):0}function JJ(e){let t=new Set,n=[];for(let r of e){let i=`${r.barrelFile}|${r.symbol}|${r.originalFile}`;t.has(i)||(t.add(i),n.push(r))}return n}function XJ(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function QJ(e,t={}){let{samples:n=50,scope:r,maxDisagreements:i=5}=t,o=new H(e),s=ZJ(o.productionCallableDefinitions({scope:r,minLoc:2,requireFunctionLikeSymbol:!0}),n),a=e5(e,s);if(s.length===0||!a)return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let c={references:HI(),callees:HI()},l=[],u=0,d=a==="semantic"?Aa(e,s):new Map,m=a==="source"?r5(e,o,s):null;for(let p of s){let f=cl(p,a==="semantic"?Ta(e,p).map(x=>x.file):[...m?.referencesBySymbolId.get(p.symbolId)??[]]),g=cl(p,a==="semantic"?(d.get(p.symbolId)??[]).map(x=>x.file):[...m?.calleesBySymbolId.get(p.symbolId)??[]]);u+=1;let h=cl(p,Un(e,p,{semanticEvidence:re}).map(x=>x.file)),b=cl(p,(o.calleeMap([p],{semantic:!1}).get(p.symbolId)??[]).map(x=>x.file)),S=xp(a,"references"),y=xp(a,"callees");UI(c.references,p,"references",h,f,S,l),UI(c.callees,p,"callees",b,g,y,l)}return l.sort((p,f)=>f.cheapOnly.length+f.oracleOnly.length-(p.cheapOnly.length+p.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?Ep(u/s.length):0,oracleKind:a,scores:["references","callees"].map(p=>n5(p,c[p],a)),topDisagreements:l.slice(0,i)}}function HI(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0,skippedOraclePartial:0}}function ZJ(e,t){let n=[...e].sort((o,s)=>o.symbolId-s.symbolId);if(n.length<=t)return n;let r=n.length/t,i=[];for(let o=0;o<t;o++)i.push(n[Math.floor(o*r)]);return i}function e5(e,t){let n=t[0];if(!n)return null;if(Rp(e,n))return"source";try{if(st(e).capability("semantic-references",n.relativePath).available)return"semantic"}catch{}return t.some(r=>Rp(e,r))?"source":null}function cl(e,t){let n=new Set;for(let r of t)r!==e.relativePath&&n.add(r);return n}function UI(e,t,n,r,i,o,s){if(!o&&i.size===0){e.skippedOraclePartial+=1;return}e.comparedSymbols+=1,e.cheapTotal+=r.size,e.oracleTotal+=i.size;let a=[],c=[];for(let l of r)i.has(l)?e.agreed+=1:a.push(l);for(let l of i)r.has(l)||c.push(l);(a.length>0||c.length>0)&&s.push({symbol:T(t.symbol),question:n,cheapOnly:a,oracleOnly:c})}var t5={references:!0,callees:!1};function n5(e,t,n){let r=t.oracleTotal>0?t.agreed/t.oracleTotal:1,i=t.cheapTotal-t.agreed,o=xp(n,e);return{question:e,comparedSymbols:t.comparedSymbols,precision:o&&t.cheapTotal>0?Ep(t.agreed/t.cheapTotal):null,recall:Ep(r),unverified:i,skippedOraclePartial:t.skippedOraclePartial}}function xp(e,t){return e==="semantic"?t5[t]:!1}function Rp(e,t){return se(t.relativePath)==="clojure"&&K(e,t.relativePath)!==null}function r5(e,t,n){let r=new Map,i=new Map,o=n.filter(c=>Rp(e,c)),s=new Map;for(let c of o){let l=s.get(c.leaf)??[];l.push(c),s.set(c.leaf,l)}for(let c of t.sourceFiles()){if(se(c)!=="clojure")continue;let l=K(e,c);if(l)for(let u of l.fileIdentifiers)for(let d of s.get(u)??[])qI(r,d.symbolId,c)}let a=new Map;for(let c of t.scopedDefinitions()){if(se(c.relativePath)!=="clojure")continue;let l=a.get(c.leaf)??[];l.push(c),a.set(c.leaf,l)}for(let c of o){let l=K(e,c.relativePath);if(l){for(let u of l.callSites)if(!(u.line<c.startLine||u.line>c.endLine))for(let d of a.get(u.calleeLeaf)??[])qI(i,c.symbolId,d.relativePath)}}return{referencesBySymbolId:r,calleesBySymbolId:i}}function qI(e,t,n){let r=e.get(t);if(r){r.add(n);return}e.set(t,new Set([n]))}function Ep(e){return Math.round(e*1e3)/1e3}var i5=new Set(Wt());function o5(e,t={}){let{scope:n,minLoc:r=1,limit:i,scanLimit:o,maxShapeFrequency:s=12}=t,a=t.semantic!==!1,c=c5(e,s5(e,{scope:n,minLoc:r,scanLimit:o}),{semantic:a,maxShapeFrequency:s}),l=u5(c);return i?l.slice(0,i):l}function s5(e,t){let n=ve(e,{scope:t.scope}).filter(r=>a5(r)&&!e.isIgnored(r.relativePath)).filter(r=>ee(r)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((r,i)=>ee(i)-ee(r)||r.relativePath.localeCompare(i.relativePath)),he(n,t.scanLimit)}function a5(e){return!e.isFunctionLike||He(e.symbol)?!1:e.kind===null||i5.has(e.kind)}function c5(e,t,n){let r=[];for(let s of t){let a=m5(e,s,n);a&&r.push({signature:a,definition:s,fn:l5(s)})}let i=new Map;for(let s of r)i.set(s.signature,(i.get(s.signature)??0)+1);let o=new Map;for(let s of r){let a=d5(s.fn.loc),c=(i.get(s.signature)??0)>n.maxShapeFrequency,l=c?tp(e,s.definition):null;if(c&&!l)continue;let u=c?`${s.signature}\0body\0${l}`:`${s.signature}\0band\0${a}`,d=o.get(u)??{signature:s.signature,locBand:a,exactBody:c,functions:[]};d.functions.push(s.fn),o.set(u,d)}return[...o.values()]}function l5(e){return{symbol:e.symbol,shortName:T(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:ee(e)}}function u5(e){let t=[];for(let n of e)n.functions.length>=2&&t.push(n);return t.sort((n,r)=>{let i=r.functions.length-n.functions.length;if(i!==0)return i;let o=n.functions.reduce((a,c)=>a+c.loc,0);return r.functions.reduce((a,c)=>a+c.loc,0)-o}),t}function d5(e){return e<=5?"<=5":e<=20?"6-20":">20"}function m5(e,t,n){if(n.semantic){let o=zy(e,t);if(o)return o}let r=p5(t.documentation),i=r?h5(r):null;return i||y5(f5(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function p5(e){return li(ui(e))}function f5(e,t,n,r,i){let o=W(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=S5(s,n,r,i);for(let c of a){let l=Math.min(s.length-1,Math.max(c,c+4)),u="";for(let d=c;d<=l;d+=1){let m=s[d]?.trim();if(m&&(u=u?`${u} ${m}`:m,g5(u)))return u}if(u&&u.includes("("))return u}return null}function g5(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||Cf(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function h5(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 y5(e,t){if(!e||!e.trim())return null;let n=e.replace(/\s+/g," ").trim(),r=n.indexOf("(");if(r===-1)return null;let i=n.slice(0,r),s=new RegExp(`\\b${xe(t)}\\b`,"i").exec(i);s&&typeof s.index=="number"&&(i=i.slice(0,s.index)),i=i.replace(/\b(public|private|protected|internal|final|static|abstract|sealed|virtual|override|async|suspend|inline|constexpr|consteval|constinit|const|pub|fn|function|def|sub|friend|shared|readonly|new|open|partial|export)\b/gi," ").replace(/\s+/g," ").trim();let a=b5(n.slice(r)).replace(/\)\s*=\s*[\s\S]*$/,")").replace(/\s+throws\s+[^={]+$/i,"").replace(/\s+where\s+.+$/i,"").replace(/\s+/g," ").trim();if(!a.startsWith("("))return null;let c=`${i?`${i} `:""}${a}`.replace(/\s+/g,"").toLowerCase();return c.length>=3?c:null}function b5(e){let t=0,n=0,r=0,i=0,o=null,s=!1;for(let a=0;a<e.length;a+=1){let c=e[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c===o&&(o=null);continue}if(c==='"'||c==="'"||c==="`"){o=c;continue}if(c==="(")t+=1;else if(c===")")t=Math.max(0,t-1);else if(c==="[")r+=1;else if(c==="]")r=Math.max(0,r-1);else if(c==="<")i+=1;else if(c===">")i=Math.max(0,i-1);else if(c==="{"){if(t===0&&r===0&&i===0)return e.slice(0,a);n+=1}else if(c==="}")n=Math.max(0,n-1);else if(c==="="&&e[a+1]===">"&&t===0&&n===0&&r===0&&i===0)return e.slice(0,a)}return e}function S5(e,t,n,r){let i=xe(r),o=new RegExp(`\\b${i}\\b\\s*\\(`,"i"),s=new RegExp(`\\bdef\\s+${i}\\b`,"i"),a=[],c=new Set,l=Math.max(0,Math.min(t,e.length-1)),u=Math.max(l,Math.min(e.length-1,Math.max(n,t+4)));for(let d=l;d<=u;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!c.has(d)&&(c.add(d),a.push(d))}for(let d=0;d<e.length;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!c.has(d)&&(c.add(d),a.push(d))}return a}async function GI(e,t,n={}){let r=Math.max(1,Math.floor(n.batchSize??64)),i=n.collectGarbage??to,o=[],s=0;for(let a=0;a<t.length;a+=r){for(let c of t.slice(a,a+r)){for(let l of U(e,c))e.isIgnored(l.relativePath)||o.push(l);Lf(e,c),Cr(e,c),Rf(e,c),s+=1}n.onBatch?.({files:s,total:t.length,definitions:o.length}),i(),await n.yieldToEventLoop?.()}return{files:s,definitions:o}}import{spawnSync as Fye}from"child_process";import{execFileSync as iye}from"child_process";import{createHash as sye}from"crypto";import{lstatSync as cye,readlinkSync as lye,readdirSync as uye,realpathSync as dye,statSync as mye}from"fs";import{dirname as fye,isAbsolute as gye,join as hye,posix as yye,relative as bye,resolve as Sye,sep as vye}from"path";var xye=512*1024*1024;function zI(e){return Rr({version:e.version,...e.base?{base:e.base}:{},files:[...e.files].sort((t,n)=>t.path.localeCompare(n.path))})}function Ip(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 C5="scip-query:collaboration-domain",x5="scip-query:workspace-instance",R5="scip-query:index-generation",E5="scip-query:repository-content",KI="scip-query:index-inputs",I5="scip-query:index-inputs";function Xr(e){let t=e.snapshot,n=e.observedSourceKinds?new Set(e.observedSourceKinds):void 0,r=e.gitContext??t?.gitContext??(n?.has("live-workspace")?Cl(e.projectRoot):void 0),i=e.collaborationDomainId??e.db?.config.collaborationDomainId,o=i?Fr(C5,1,i):void 0,s=r?Fr(x5,1,r.worktreeId):void 0,a=t?Fr(E5,1,zI(t.repositoryContent)):void 0,c=t?Fr(KI,t.indexInputs.version,Ip(t.indexInputs)):void 0,l=e.db&&t?L5(e.db.generation.metadataRaw):void 0,u=e.db?{generation:Fr(R5,1,e.db.generation.identity),...l?{inputs:l}:{},source:e.db.generation.source}:void 0,d=n??new Set([...u?["index-generation"]:[],...a?["repository-snapshot"]:s?["live-workspace"]:[]]),m=[...u&&d.has("index-generation")?[{kind:"index-generation",identity:u.generation}]:[],...a&&d.has("repository-snapshot")?[{kind:"repository-snapshot",identity:a}]:[],...s&&d.has("live-workspace")?[{kind:"live-workspace",identity:s}]:[],...d.has("process")?[{kind:"process"}]:[]],p=[...u&&d.has("index-generation")?[{source:"index-generation",kind:u.source==="immutable"?"immutable":"not-established"}]:[],...a&&d.has("repository-snapshot")?[{source:"repository-snapshot",kind:"fixed-snapshot"}]:[],...s&&d.has("live-workspace")?[{source:"live-workspace",kind:"not-established"}]:[],...d.has("process")?[{source:"process",kind:"not-established"}]:[]];return m.length===0&&(m.push({kind:"process"}),p.push({source:"process",kind:"not-established"})),{schemaVersion:tr,observedAt:(e.observedAt??(t?new Date(t.capturedAt):new Date)).toISOString(),facts:{...o?{collaborationDomain:o}:{},...s?{workspaceInstance:s}:{},...a?{wholeContent:a}:{},...c?{relevantInputs:[{subject:I5,identity:c}]}:{},...u?{index:u}:{}},observedSources:m,stabilityProofs:p,...r?{diagnostics:{clean:r.clean,...r.headCommit?{headCommit:r.headCommit}:{},...r.treeOid?{treeOid:r.treeOid}:{}}}:{}}}function w5(e){return Xr({projectRoot:e.projectRoot,db:e.db,...e.gitContext?{gitContext:e.gitContext}:{},...e.observedAt?{observedAt:e.observedAt}:{},observedSourceKinds:["index-generation"]})}function Mye(){let e=za();if(!e)return Xr({projectRoot:Ga(),observedSourceKinds:["process"]});let t=e.config.projectRoot,n=Cl(t);return w5({projectRoot:t,db:e,...n?{gitContext:n}:{}})}function L5(e){if(!e)return;let t=br(e);if(t.kind!=="legacy"&&t.kind!=="supported")return;let n=Xi(t.metadata.fingerprint);return n&&Number.isSafeInteger(n.version)&&n.version>0?Fr(KI,n.version,Ip(n)):void 0}var Lp="scip-query-isolated-analysis",Pp=1;function P5(e){let t=[...e??[]];return t.includes("--json")?t:["--json",...t]}var dn=class extends Error{constructor(n,r,i=!0){super(`${n} timed out after ${r}ms.`);this.label=n;this.timeoutMs=r;this.reaped=i;this.name="IsolatedProcessTimeoutError"}label;timeoutMs;reaped;timedOut=!0};function Hye(e,t){let n=za(),r={protocol:Lp,schemaVersion:Pp,producer:{name:"scip-query",version:yr},command:e,result:t,...n?{observationReceipt:Xr({projectRoot:n.config.projectRoot,db:n,observedSourceKinds:["index-generation"]})}:{}};sd(JSON.stringify(r))}function WI(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Ls(e){let t=e.timeoutMs??mg.analysis,n=e.maxBuffer??10*1024*1024;return fg({command:process.execPath,args:[...process.execArgv,e.cliPath,e.command,...P5(e.args)],cwd:process.cwd(),env:e.env??process.env,label:e.label,timeoutMs:t,maxStdoutBytes:n,maxStderrBytes:n}).catch(r=>{throw r instanceof pg&&r.kind==="timeout"?new dn(e.label,t,r.reaped):r}).then(r=>{let i=r.stderr.trim();if(r.status!==0)throw new Error(`${e.label} failed${i?`:
532
- ${i}`:""}`);return D5(r.stdout,e)})}function D5(e,t){let n;try{n=JSON.parse(e)}catch(i){throw new Error(`${t.label} returned invalid JSON: ${i instanceof Error?i.message:i}`,{cause:i})}if(!Z(n))throw new Error(`${t.label} returned a non-object isolated-analysis message.`);if(n.protocol!==Lp)throw new Error(`${t.label} returned protocol ${wp(n.protocol)}; expected ${Lp}.`);if(n.schemaVersion!==Pp)throw new Error(`${t.label} returned unsupported isolated-analysis schemaVersion ${wp(n.schemaVersion)}; expected ${Pp}.`);if(!M5(n.producer))throw new Error(`${t.label} did not identify a scip-query producer version.`);if(n.command!==t.command)throw new Error(`${t.label} returned result for command ${wp(n.command)}; expected ${t.command}.`);if(!Object.hasOwn(n,"result"))throw new Error(`${t.label} omitted the isolated-analysis result.`);let r=n.observationReceipt;if(r!==void 0&&(!ka(r)||r.schemaVersion!==2))throw new Error(`${t.label} returned an invalid observation receipt.`);return{result:n.result,...r?{observationReceipt:r}:{}}}function M5(e){return Z(e)&&e.name==="scip-query"&&typeof e.version=="string"&&e.version.length>0}function wp(e){return typeof e=="string"?JSON.stringify(e):String(e)}async function ll(e,t,n){let r=new Array(e.length),i=0;async function o(){for(;i<e.length;){let s=i++;r[s]=await n(e[s])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),r}function VI(e,t){let n=new Set,r=[];for(let i of e){if(n.has(i))continue;let o=t.find(a=>a.has(i));if(!o){n.add(i),r.push([i]);continue}let s=e.filter(a=>o.has(a));s.forEach(a=>n.add(a)),r.push(s)}return r}import{spawnSync as T5}from"child_process";import{existsSync as A5,mkdirSync as F5,renameSync as k5,writeFileSync as N5}from"fs";import{dirname as YI,join as _5}from"path";var ul=5,O5="health-report-cache.json";function Dp(e,t,n,r=H5()){let i=dt(e);return i?{version:ul,projectFingerprint:i,cliVersion:n,scope:t.scope??null,full:t.full===!0,phaseTimeoutMs:t.phaseTimeoutMs??null,gitHead:r.gitHead(e.config.projectRoot)}:null}function JI(e,t,n=ew()){let r=QI(e),i=ZI(t),o=!1;return N("health.report-cache.read",()=>{if(!n.existsSync(r))return null;try{let s=JSON.parse(n.readFile(r));return!B5(s)||s.keyHash!==i?null:(o=!0,s.report)}catch{return null}},()=>({available:!0,hit:o,keyHash:i}))}function XI(e,t,n,r=ew()){let i=QI(e),o={version:ul,keyHash:ZI(t),key:t,writtenAt:r.nowIso(),report:n};r.mkdirSync(YI(i),{recursive:!0});let s=`${i}.${process.pid}.${Date.now()}.tmp`;r.writeFileSync(s,JSON.stringify(o)),r.renameSync(s,i)}function QI(e){return _5(YI(e.config.dbPath),O5)}function ZI(e){return Gt(JSON.stringify(e))}function B5(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===ul&&typeof t.keyHash=="string"&&$5(t.key)&&typeof t.writtenAt=="string"&&j5(t.report)}function $5(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===ul&&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 j5(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.score=="number"&&typeof t.riskScore=="number"&&typeof t.hygieneScore=="number"&&typeof t.overview=="object"&&typeof t.findings=="object"&&Array.isArray(t.scoreBreakdown)&&Array.isArray(t.actions)&&Array.isArray(t.pressure)&&Array.isArray(t.topComplexity)&&Array.isArray(t.detectorEvidence)}function H5(){return{gitHead(e){let t=T5("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",timeout:3e4,killSignal:"SIGKILL"});return t.status===0?t.stdout.trim():null}}}function ew(){return{existsSync:A5,mkdirSync:F5,readFile:e=>Ve(e,"health report cache"),renameSync:k5,writeFileSync:N5,nowIso:()=>new Date().toISOString()}}var ow="__health-phase",q5="__health-semantic-prewarm",G5="__diff-impact-batch",z5=128,K5=1,W5=1,V5=6144,Y5=2048,J5=10*6e4,X5=25e3,Q5=2500,Mp=2500,Z5=4,e4=12,t4=1,n4=4,r4=7*1024*1024*1024,i4=6144,o4=10*6e4,s4=3e4,a4=16384,c4=2048,l4=10*6e4,sw=new Set(["react-component-duplicates","react-hook-candidates","react-large-component-pressure"]),aw=new Set(["vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure"]),u4=new Set([...aw,"suppressions"]),d4=new Set(["similar","extract-candidates"]),Ps=2,Ap=Sr({kind:"health-semantic-prewarm",invalidation:Te("health-semantic-prewarm"),serialize:e=>JSON.stringify(e),deserialize:m4});function m4(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return n.version!==Ps||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:Ps,definitions:n.definitions,referenceCacheWrites:n.referenceCacheWrites,referenceIncomplete:n.referenceIncomplete,calleeRows:n.calleeRows,warmedAt:n.warmedAt}}catch{return null}}function p4(e,t){return!t||t.count<=1?[...e]:e.filter((n,r)=>r%t.count===t.index)}function vbe(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
533
- `)}function f4(e){let t=_r(e);return t.symbols>=X5||t.documents>=Q5}function Cbe(e,t,n,r={}){if(!f4(e))return{semantic:!0};if(n)return t==="dead"?(r.quiet||console.error("Large index detected; dead is scanning all candidates with semantic enrichment disabled to keep memory bounded."),{semantic:!1}):(r.quiet||console.error(`Large index detected; ${t} is running the unbounded semantic pass because --full was supplied.`),{semantic:!0});if(!r.quiet){let i=t==="inspect"?"Use --full only when every omitted semantic candidate can change the decision; it does not override source or behavior materialization ceilings.":t==="dead"?'Run "scip-query dead --full" for an unbounded candidate scan; semantic enrichment remains disabled on large indexes to keep memory bounded.':`Run "scip-query ${t} --full" for the unbounded semantic pass.`;console.error(`Large index detected; ${t} is using its bounded default analysis with semantic enrichment disabled. Candidate scans, when this command uses one, are capped at ${Mp}. `+i)}return{scanLimit:Mp,semantic:!1,analysisBudget:{scanLimit:Mp,semanticEnrichment:!1,reason:t==="dead"?"large index default budget; pass --full for an unbounded memory-safe candidate scan":"large index default budget; pass --full for unbounded semantic analysis"}}}var g4={env:process.env,projectFingerprint:dt,semanticEngineFingerprint:lw,readMarker:(e,t,n)=>Ap.read(e,t,n),writeMarker:(e,t,n,r)=>Ap.write(e,t,n,r),projectFiles:(e,t)=>p4(Q(e,{scope:t.scope,includeIgnored:!1}),t.shard),candidateDefinitions:async(e,t,n)=>{let r=await GI(e,n,{collectGarbage:to,yieldToEventLoop:()=>new Promise(a=>setImmediate(a))}),i=new Set(n),o=new Set(r.definitions.map(a=>a.symbolId)),s=[];for(let a of[{},{requireCallableSymbol:!0},{requireFunctionLikeSymbol:!0}])for(let c of Ya(e,{...a,scope:t.scope}))!i.has(c.relativePath)||o.has(c.symbolId)||(o.add(c.symbolId),s.push(c));return[...r.definitions,...s].filter(a=>Pe(a.relativePath)!==null)},warmReferenceFragments:(e,t,n)=>rg(e,r=>vn(e,r),{onBatch:t,...n?{files:n}:{}}),materializeReferences:(e,t,n)=>st(e).materializeReferences(t,n),materializeCallees:Gu,releaseSemanticMemory:e=>Qi(e,{groups:["semantic-provider"]}),heapUsedFraction:()=>{let e=U5();return e.heap_size_limit>0?e.used_heap_size/e.heap_size_limit:0},collectGarbage:to,yieldToEventLoop:()=>new Promise(e=>setImmediate(e))},h4=256,y4=.75;function tw(e,t=h4){if(!Number.isSafeInteger(t)||t<1)throw new Error(`Prewarm batch size must be a positive safe integer; received ${t}.`);let n=new Map;for(let s of e){let a=n.get(s.relativePath);a?a.push(s):n.set(s.relativePath,[s])}let r=[],i=[],o=0;for(let s of n.values())o>=t&&(r.push(i),i=[],o=0),i.push(...s),o+=1;return i.length>0&&r.push(i),r}async function xbe(e,t,n=g4){if(t.full!==!0)return gr("default-mode");if((n.env??process.env).SCIP_QUERY_HEALTH_SEMANTIC_PREWARM==="0")return gr("disabled");let r=gr("error");return ii("health.semantic-prewarm",async()=>{try{r=await v4(e,t,n)}catch(i){r=gr("error",{error:i instanceof Error?i.message:String(i)})}return r},()=>C4(r))}function b4(e,t){let n=0,r=0,i=()=>(t.heapUsedFraction?.()??0)>=y4;return{relieve({release:o}){i()&&(t.collectGarbage?.()&&(n+=1,!i())||o&&(t.releaseSemanticMemory?.(e),r+=1))},get collections(){return n},get releases(){return r}}}function S4(e,t){e.definitions+=t.definitions,e.cacheHits+=t.cacheHits,e.cacheWrites+=t.cacheWrites,e.inMemoryHits+=t.inMemoryHits,e.misses+=t.misses,e.unkeyed+=t.unkeyed,e.incomplete+=t.incomplete}async function v4(e,t,n){let r=n.projectFingerprint(e);if(!r)return gr("missing-project-fingerprint");let i=cw(t,n.semanticEngineFingerprint(e)),o=n.readMarker(e,i,r);if(o&&o.referenceIncomplete===0)return gr("cache-hit");let s=n.projectFiles(e,t),a=[];if(a=await ii("health.semantic-prewarm.candidate-definitions",async()=>(a=await n.candidateDefinitions(e,t,s),a),()=>({definitions:a.length,files:s.length,shard:t.shard??null})),a.length===0)return gr("no-semantic-definitions");let c=b4(e,n),l=async()=>{await n.yieldToEventLoop?.()},u=a.filter(y=>Pe(y.relativePath)==="typescript"),d=null;if(u.length>0){let y=null;d=await ii("health.semantic-prewarm.reference-fragments",async()=>(y=await n.warmReferenceFragments(e,()=>c.relieve({release:!0}),s),y),()=>({definitions:u.length,rows:y?.computedFiles??0,files:y?.files??0,cacheHits:y?.cacheHits??0,available:y!==null}))}let m=d?a.filter(y=>Pe(y.relativePath)!=="typescript"):a,p={definitions:0,cacheHits:0,cacheWrites:0,inMemoryHits:0,misses:0,unkeyed:0,incomplete:0},f=0;await ii("health.semantic-prewarm.references",async()=>{for(let y of tw(m))S4(p,n.materializeReferences(e,y,{prefetchCallees:!1})),c.relieve({release:!0}),await l();f=p.cacheHits+p.cacheWrites+p.inMemoryHits},()=>({definitions:m.length,rows:f,releases:c.releases}));let g=d?u.length:0;if(f+g===0&&p.misses+p.unkeyed>0)return gr("provider-unavailable",{definitions:a.length,referenceMisses:p.misses});N("health.semantic-prewarm.release-reference-memory",()=>n.releaseSemanticMemory?.(e));let h=0,b=c.releases;await ii("health.semantic-prewarm.callees",async()=>{for(let y of tw(a))h+=n.materializeCallees(e,y).size,c.relieve({release:!0}),await l()},()=>({definitions:a.length,rows:h,releases:c.releases-b,collections:c.collections}));let S={warmedFiles:s.length,...d?{referenceFragmentFiles:d.files,referenceFragmentComputedFiles:d.computedFiles}:{}};return p.incomplete>0?{status:"partial",reason:"incomplete-references",definitions:a.length,referenceCacheHits:p.cacheHits,referenceCacheWrites:p.cacheWrites,referenceMisses:p.misses,referenceIncomplete:p.incomplete,...S,calleeRows:h}:(t.shard||N("health.semantic-prewarm.marker-write",()=>n.writeMarker(e,i,r,{version:Ps,definitions:a.length,referenceCacheWrites:p.cacheWrites,referenceIncomplete:p.incomplete,calleeRows:h,warmedAt:Date.now()})),{status:"warmed",reason:"cache-miss",definitions:a.length,referenceCacheHits:p.cacheHits,referenceCacheWrites:p.cacheWrites,referenceMisses:p.misses,referenceIncomplete:p.incomplete,...S,calleeRows:h})}function cw(e,t){return JSON.stringify({version:Ps,cliVersion:yr,semanticEngineFingerprint:t,scope:e.scope??null})}function lw(e){return Gt(JSON.stringify({kind:"health-semantic-prewarm-engine",rust:Dr(e.config.projectRoot)}))}function gr(e,t={}){return{status:"skipped",reason:e,definitions:0,referenceCacheHits:0,referenceCacheWrites:0,referenceMisses:0,referenceIncomplete:0,calleeRows:0,...t}}function C4(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 Fp(e){return Ka(t=>{let n=Xr({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 dl(e,t,n){let r=e[0];if(!r)throw new Error("An evidence-bound analysis requires at least one index observation anchor.");let i=r.generationDigest,o=e.every(a=>a.generationDigest===i),s=t.every(a=>a?.facts.index?.generation.digest===i);return Xr({projectRoot:r.database.config.projectRoot,...o&&s?{db:r.database}:{},observedSourceKinds:n})}async function Rbe(e){return(await x4(e)).result}async function x4(e){let t=j4(e),n={...e,phaseTimeoutMs:t??null},r=Fp(b=>{let S=Dp(b,n,yr);if(!S)return null;let y=JI(b,S);return y||null});if(r.value)return{result:r.value,observationReceipt:dl([r.anchor],[],["index-generation","live-workspace"])};let i=Fp(b=>({applicability:F4(b,e),overview:bp(b,"overview",e)})),{applicability:o,overview:s}=i.value,a=[r.anchor,i.anchor],c=new Map;c.set("overview",s);let l=sl.filter(b=>b==="overview"?!1:k4(b,o)?!0:(c.set(b,Qr(b)),!1)),u=O4(N4(l)),d=[],m=[];if(e.full)try{m=await L4(e)}catch(b){d.push(`Health semantic prewarm omitted: ${kp(b)}.`)}let p=e.full?U4(u.length):H4(u.length),f=await ll(u,p,b=>B4(b,e,t));if(f.flatMap(b=>b.result).forEach(b=>{b.healthPhaseMeta&&d.push(e.full?`Health phase "${b.phase}" omitted after a bounded worker failure: ${b.healthPhaseMeta.reason}.`:`Health phase "${b.phase}" deferred: ${b.healthPhaseMeta.reason}. Run health --full for exhaustive analysis.`),c.set(b.phase,b)}),d.length>0){let b=c.get("overview");c.set("overview",{...b,warnings:[...b.warnings,...d]})}let h=Sp(sl.map(b=>c.get(b)));return Ka(b=>{let S=Dp(b,n,yr);S&&XI(b,S,h)}),{result:h,observationReceipt:dl(a,[...m.map(b=>b.observationReceipt),...f.map(b=>b.observationReceipt)],["index-generation","live-workspace"])}}var nw=12288,R4=2048,E4=8192,I4=4;function w4(e=process.env,t=iw(),n=ml()){let r={shards:1,heapMb:D4(e,n)},i=Number.isFinite(n)&&n>0?n/(1024*1024):0,o=Math.floor(Math.max(0,i-E4)/(nw+R4)),s=Number.isFinite(t)?Math.max(1,t-1):1,a=Number.parseInt(e.SCIP_QUERY_HEALTH_PREWARM_SHARDS??"",10),c=Number.isSafeInteger(a)&&a>0?a:Number.POSITIVE_INFINITY,l=Math.min(I4,o,s,c);return!Number.isFinite(l)||l<2?r:{shards:l,heapMb:nw}}function rw(e,t){let n=process.argv[1]??pl(import.meta.url),r=["--full"];return e.scope&&r.push("--scope",e.scope),e.shard&&r.push("--shard-index",String(e.shard.index),"--shard-count",String(e.shard.count)),Ls({cliPath:n,command:q5,args:r,env:{...process.env,NODE_OPTIONS:na(process.env.NODE_OPTIONS,t)},label:e.shard?`Health semantic prewarm ${e.shard.index+1}/${e.shard.count}`:"Health semantic prewarm",timeoutMs:T4()})}async function L4(e,t=w4()){if(t.shards<2)return[await rw(e,t.heapMb)];let n=Array.from({length:t.shards},(o,s)=>({index:s,count:t.shards})),r=await ll(n,t.shards,o=>rw({...e,shard:o},t.heapMb)),i=P4(r.map(o=>o.result));return i.status==="warmed"&&Ka(o=>{let s=dt(o);s&&Ap.write(o,cw(e,lw(o)),s,{version:Ps,definitions:i.definitions,referenceCacheWrites:i.referenceCacheWrites,referenceIncomplete:i.referenceIncomplete,calleeRows:i.calleeRows,warmedAt:Date.now()})}),r}function P4(e){let t=i=>e.reduce((o,s)=>o+(i(s)??0),0),n={definitions:t(i=>i.definitions),referenceCacheHits:t(i=>i.referenceCacheHits),referenceCacheWrites:t(i=>i.referenceCacheWrites),referenceMisses:t(i=>i.referenceMisses),referenceIncomplete:t(i=>i.referenceIncomplete),calleeRows:t(i=>i.calleeRows),warmedFiles:t(i=>i.warmedFiles),referenceFragmentFiles:t(i=>i.referenceFragmentFiles),referenceFragmentComputedFiles:t(i=>i.referenceFragmentComputedFiles)},r=e.find(i=>i.status==="partial")??e.find(i=>i.status==="skipped"&&i.reason!=="cache-hit");return r?{...n,status:r.status,reason:r.reason,...r.error?{error:r.error}:{}}:e.length>0&&e.every(i=>i.status==="skipped")?{...n,status:"skipped",reason:"cache-hit"}:{...n,status:"warmed",reason:"cache-miss"}}function D4(e=process.env,t=ml()){let n=Number.parseInt(e.SCIP_QUERY_HEALTH_SEMANTIC_PREWARM_HEAP_MB??"",10);return Number.isSafeInteger(n)&&n>0?n:M4(t)}function M4(e){return uw(e,{min:c4,max:a4})}function uw(e,t){let n=Math.floor(e/2097152);return!Number.isFinite(n)||n<=0?t.max:Math.max(t.min,Math.min(t.max,n))}function T4(e=process.env){let t=Number.parseInt(e.SCIP_QUERY_HEALTH_SEMANTIC_PREWARM_TIMEOUT_MS??"",10);return Number.isSafeInteger(t)&&t>0?t:l4}function A4(e=process.env){let t=Number.parseInt(e.SCIP_QUERY_HEALTH_FULL_PHASE_HEAP_MB??"",10);return Number.isSafeInteger(t)&&t>0?t:i4}function F4(e,t){return Hs(e,{scope:t.scope})}function k4(e,t){return sw.has(e)?t.react:aw.has(e)?t.vue:!0}function N4(e){return VI(e,[sw,u4,d4])}var _4={"wrapper-candidates":49,"complexity-hotspots":35,"passthrough-candidates":31,"stale-abstractions":30,"extract-candidates":29,similar:29,dead:20,isolated:12,"react-component-duplicates":10,"react-hook-candidates":10,cycles:8};function O4(e){let t=n=>n.reduce((r,i)=>r+(_4[i]??1),0);return e.map((n,r)=>({task:n,index:r,weight:t(n)})).sort((n,r)=>r.weight-n.weight||n.index-r.index).map(n=>n.task)}function Qr(e){switch(e){case"react-component-duplicates":return{phase:e,reactComponentDuplicates:{count:0,loc:0,files:[]}};case"react-hook-candidates":return{phase:e,reactHookCandidates:{count:0,loc:0,files:[]}};case"react-large-component-pressure":return{phase:e,reactLargeComponentPressure:{count:0,loc:0,files:[]}};case"vue-component-duplicates":return{phase:e,vueComponentDuplicates:{count:0,loc:0,files:[]}};case"vue-composable-candidates":return{phase:e,vueComposableCandidates:{count:0,loc:0,files:[]}};case"vue-large-view-pressure":return{phase:e,vueLargeViewPressure:{count:0,loc:0,files:[]}};default:throw new Error(`Health phase "${e}" cannot be synthesized.`)}}function B4(e,t,n){if(e.length===1)return $4(e[0],t,n).then(s=>({result:[s.result],...s.observationReceipt?{observationReceipt:s.observationReceipt}:{}}));let r=e.join(","),i=process.argv[1]??pl(import.meta.url),o=[r];return t.scope&&o.push("--scope",t.scope),t.full&&o.push("--full"),Ls({cliPath:i,command:ow,args:o,...t.full?{env:dw()}:{},label:`Health phases "${r}"`,timeoutMs:n}).catch(s=>{if(!t.full&&!(s instanceof dn))throw s;let a=s instanceof dn?s.timeoutMs:n??0;return{result:e.map(c=>mw(c,a,s instanceof dn?`timed out after ${s.timeoutMs}ms`:kp(s)))}})}function $4(e,t,n){let r=process.argv[1]??pl(import.meta.url),i=[e];return t.scope&&i.push("--scope",t.scope),t.full&&i.push("--full"),Ls({cliPath:r,command:ow,args:i,...t.full?{env:dw()}:{},label:`Health phase "${e}"`,timeoutMs:n}).catch(o=>{if(!t.full&&!(o instanceof dn))throw o;let s=o instanceof dn?o.timeoutMs:n??0;return{result:mw(e,s,o instanceof dn?`timed out after ${o.timeoutMs}ms`:kp(o))}})}function kp(e){let t=e instanceof Error?e.message:String(e);if(/heap out of memory|reaching memory limit/i.test(t))return"exceeded its isolated memory limit";let n=t.split(/\r?\n/,1)[0]?.trim()||"isolated worker failed";return n.length<=240?n:`${n.slice(0,237)}...`}function dw(e=process.env){return{...e,NODE_OPTIONS:na(e.NODE_OPTIONS,A4(e))}}function j4(e,t=process.env){let n=e.full?o4:s4,r=t.SCIP_QUERY_HEALTH_PHASE_TIMEOUT_MS;if(!r)return n;let i=parseInt(r,10);return!Number.isFinite(i)||i<0?n:i===0?void 0:i}function mw(e,t,n){let r={healthPhaseMeta:{status:"deferred",reason:n,timeoutMs:t}};switch(e){case"overview":throw new Error("Overview health phase cannot be deferred.");case"dead":return{phase:e,dead:{count:0,loc:0,files:[]},...r};case"isolated":return{phase:e,isolated:{count:0,loc:0,files:[]},...r};case"cycles":return{phase:e,realCycleCount:0,...r};case"similar":return{phase:e,similarCount:0,...r};case"duplicate-bodies":return{phase:e,duplicateBodies:{count:0,loc:0,files:[]},...r};case"twin-drift":return{phase:e,twinDrift:{count:0,loc:0,files:[]},...r};case"react-component-duplicates":return{...Qr(e),...r};case"react-hook-candidates":return{...Qr(e),...r};case"react-large-component-pressure":return{...Qr(e),...r};case"vue-component-duplicates":return{...Qr(e),...r};case"vue-composable-candidates":return{...Qr(e),...r};case"vue-large-view-pressure":return{...Qr(e),...r};case"extract-candidates":return{phase:e,extractCount:0,...r};case"wrapper-candidates":return{phase:e,wrappers:{count:0,loc:0,files:[]},...r};case"passthrough-candidates":return{phase:e,passthroughs:{count:0,loc:0,files:[]},...r};case"stale-abstractions":return{phase:e,stale:{count:0,loc:0,files:[],unused:0,singleUse:0},...r};case"drift":return{phase:e,drift:{count:0,unusedImports:0,architectureViolations:0,layerViolations:0,direct:0,signal:0},...r};case"complexity-hotspots":return{phase:e,complexity:{top:[],extremeCount:0},...r};case"git-evidence":return{phase:e,gitEvidence:null,...r};case"suppressions":return{phase:e,suppressions:{total:0,byCategory:{}},...r};case"coverage-contracts":return{phase:e,coverageContracts:{count:0,loc:0,files:[]},...r}}}var H4=Np({envKey:"SCIP_QUERY_HEALTH_CONCURRENCY",defaultMinimum:Z5,defaultMaximum:e4}),U4=Np({envKey:"SCIP_QUERY_HEALTH_FULL_CONCURRENCY",defaultMinimum:t4,defaultMaximum:n4,memoryPerTaskBytes:r4});function Ebe(e){if(console.log(`
534
- Codebase Health Score: ${e.score}/100`),console.log(` Risk: ${e.riskScore}/100 (risk-oriented graph facts + change graph)`),console.log(` Hygiene: ${e.hygieneScore}/100 (tidiness candidates)
535
- `),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${id(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: ${Tp(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: ${Tp(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: ${Tp(t.wrappers,t.wrapperScoreCount)}`),t.passthroughs>0&&console.log(` Passthroughs: ${t.passthroughs}`),t.staleTypes>0&&console.log(` Stale abstractions: ${t.staleTypes}`),t.driftedFiles>0&&console.log(` Pattern drift: ${t.driftedFiles} files`),t.complexityHotspotCount>0&&console.log(` Complexity hotspots: ${t.complexityHotspotCount}`),e.actions.length>0){console.log(`
537
- Prioritized Actions (highest impact + lowest effort first):`);for(let n=0;n<e.actions.length;n++){let r=e.actions[n],i=r.locRecoverable>0?` (~${r.locRecoverable} LOC involved)`:"";console.log(` ${n+1}. [${r.effort} effort / ${r.impact} impact] ${r.description}${i}`)}}if(e.topComplexity.length>0){console.log(`
538
- Top Complexity Hotspots:`);for(let n of e.topComplexity)console.log(` ${n.score.toFixed(1).padStart(6)} ${n.symbol}`)}if(e.detectorEvidence.length>0){console.log(`
539
- Detector Evidence Calibration:`);for(let n of e.detectorEvidence){let r=n.unavailableRequirements.length>0?`; unavailable: ${n.unavailableRequirements.join(", ")}`:"";console.log(` ${n.detector}: ${n.status}/${n.providerCoverage}${r}`)}console.log(" Full claims, non-claims, providers, and recovery commands are available in health --json.")}if(z4(e),G4(e),e.scoreBreakdown.length>0){console.log(`
540
- Score Breakdown (100 minus the following):`);for(let n of e.scoreBreakdown)console.log(` -${String(n.points).padStart(2)} ${n.axis}: ${n.detail}`)}e.actions.length===0&&console.log(e.warnings&&e.warnings.length>0?`
541
- No findings from completed analyses. Review warnings before interpreting this result as clean.`:`
542
- No issues found. Codebase is clean.`)}function Tp(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${q4(t)} score-weighted)`}function q4(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function G4(e){if(e.pressure.length!==0){console.log(`
543
- Maintenance Pressure:`);for(let t of e.pressure)console.log(` ${t.category}: ${t.count} / ${t.threshold} threshold (${t.ratio}x, -${t.extraPenalty} ${t.kind})`)}}function z4(e){let t=e.axes;if(console.log(`
544
- Axes:`),console.log(` Zero-reference candidates: ${t.deletable.loc} LOC across ${t.deletable.symbols} symbols`),t.changeAmplification){let r=t.changeAmplification;console.log(` Change amplification: ${r.medianFilesPerCommit} files/commit median, ${r.p90FilesPerCommit} p90 (${r.commitsAnalyzed} commits)`)}if(t.hiddenCoupling&&t.hiddenCoupling.pairCount>0){console.log(` Hidden coupling: ${t.hiddenCoupling.pairCount} co-changing pair(s) without a dependency edge`);for(let r of t.hiddenCoupling.top.slice(0,3))console.log(` ${r.fileA} <-> ${r.fileB} (${r.together}x together, ${Math.round(r.confidence*100)}%)`)}if(t.churnWeightedComplexity&&t.churnWeightedComplexity.length>0){let r=t.churnWeightedComplexity[0];r.weighted>0&&console.log(` Churn x complexity: hottest is ${r.symbol} (${r.changes} changes, weighted ${r.weighted})`)}let n=t.evidenceQuality;if(console.log(` Evidence quality: ${n.graphFindings} graph-fact finding(s), ${n.heuristicFindings} heuristic finding(s), ${n.userSuppressed} user-suppressed`),e.validation&&e.validation.flaggedFiles>0){let r=e.validation,i=r.ratio===null?"n/a":`${r.ratio}x`;console.log(` Validation: flagged files fix-density ${r.flaggedFixDensity} vs baseline ${r.baselineFixDensity} (${i})`),console.log(` fix-commit signal: subject-keyword heuristic over ${r.validationBasis.commitsScanned} commits`)}}async function Ibe(e){let t=Fp(o=>{let s=Wi(o,{base:e.base});return s.note?{kind:"complete",result:Hc(o,{base:e.base})}:s.changedFiles.length===0?{kind:"complete",result:Hc(o,{base:e.base})}:{kind:"batched",plan:s}}),n=t.value;if(n.kind==="complete")return{result:n.result,observationReceipt:dl([t.anchor],[],["index-generation","live-workspace"])};let r=W4(n.plan.changedFiles),i=await ll(r,K4(r.length),o=>J4(o,e));return{result:Uc(n.plan.changedFiles,i.map(o=>o.result)),observationReceipt:dl([t.anchor],i.map(o=>o.observationReceipt),["index-generation","live-workspace"])}}var K4=Np({envKey:"SCIP_QUERY_DIFF_IMPACT_CONCURRENCY",defaultMinimum:K5,defaultMaximum:W5});function W4(e){return WI(e,z5)}function Np(e){return(t,n=process.env,r=iw,i=ml())=>V4(t,n,r,i,e)}function V4(e,t,n,r,i){let o=t[i.envKey],s=Y4(n,r,i),a=o?parseInt(o,10):s;return!Number.isFinite(a)||a<1?Math.min(s,e):Math.min(a,e)}function Y4(e,t,n){let r=e(),i=Number.isFinite(r)?Math.max(n.defaultMinimum,r-1):0,o=n.memoryPerTaskBytes!==void 0&&Number.isFinite(t)&&t>0?Math.floor(t/2/n.memoryPerTaskBytes):Number.POSITIVE_INFINITY;return Math.min(n.defaultMaximum,o,Math.max(n.defaultMinimum,i))}function J4(e,t){let n=process.argv[1]??pl(import.meta.url),r=[];return t.base&&r.push("--base",t.base),Ls({cliPath:n,command:G5,args:r,env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e),NODE_OPTIONS:na(process.env.NODE_OPTIONS,Q4())},label:"Diff-impact batch",timeoutMs:X4()})}function X4(e=process.env){let t=Number.parseInt(e.SCIP_QUERY_DIFF_IMPACT_BATCH_TIMEOUT_MS??"",10);return Number.isSafeInteger(t)&&t>0?t:J5}function Q4(e=process.env,t=ml()){let n=Number.parseInt(e.SCIP_QUERY_DIFF_IMPACT_BATCH_HEAP_MB??"",10);return Number.isSafeInteger(n)&&n>0?n:uw(t,{min:Y5,max:V5})}function wbe(e){console.log(`Changed files: ${e.summary.totalChangedFiles}`),console.log(`Changed symbols: ${e.summary.totalChangedSymbols}`),console.log(`Affected consumer files: ${e.summary.totalAffectedFiles}`),e.summary.note&&console.log(`Note: ${e.summary.note}`);for(let n of e.evidenceTiers.filter(r=>r.state==="failed"))console.log(`WARNING: ${n.tier} evidence failed for ${n.attemptedSymbols} candidate symbol(s): ${n.reason}`);let t=e.attributionNotes.filter(n=>n.method==="unattributed");if(t.length>0){let n=[...new Set(t.map(r=>r.file))];for(let r of n){let i=t.filter(o=>o.file===r).length;console.log(`note: ${i} changed line-range(s) in ${r} belong to no indexed symbol`)}}console.log(""),e.changedSymbols.length>0&&(console.log("Changed symbols:"),cd.list(e.changedSymbols,n=>` ${n.file} ${n.shortName} (fan-in: ${n.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
545
- Affected consumer files:`),cd.list(e.affectedConsumers,n=>` ${n.file} (${n.consumedSymbols} symbol(s))`))}import{AsyncLocalStorage as Z4}from"async_hooks";import{createHash as Op}from"crypto";import{existsSync as eX,mkdirSync as tX}from"fs";import{tmpdir as nX}from"os";import{isAbsolute as rX,join as gw,resolve as hw}from"path";var _p=2,iX="SCIP_QUERY_SESSION",pw="SCIP_QUERY_SESSION_DIR",oX=128,Ji=new Z4;function $be(e,t){let n=e.sessionEnabled===!1||e.json?void 0:SX(),r={enabled:n!==void 0,reemit:e.reemit===!0,command:e.command,projectRoot:hw(e.cwd),sessionIdentity:n,staged:[],stagedEvidence:[],finalized:!1};return Ji.run(r,t)}function jbe(e){let t=Ji.getStore();!t||t.finalized||(t.generationIdentity=e)}function Hbe(e){let t=Ji.getStore();if(!t||t.finalized)return;t.finalized=!0;let n=t.state;if(!n){t.staged.length=0,t.stagedEvidence.length=0;return}try{if(e&&(t.staged.length>0||t.stagedEvidence.length>0)){let r=n.ledger.nextOrdinal,i=fX(t.staged).map(s=>({...s,ordinal:r,command:t.command})),o=hX(t.stagedEvidence).map(s=>({...s,ordinal:r,command:t.command}));n.ledger.ranges.push(...i),n.ledger.evidence.push(...o),n.ledger.nextOrdinal+=1,n.ledger.updatedAt=new Date().toISOString(),Er(n.ledgerPath,n.ledger,{spacing:2,trailingNewline:!0})}}catch{}finally{n.lock.release(),t.state=null,t.staged.length=0,t.stagedEvidence.length=0}}function Ube(e){let t=e.source.split(`
546
- `);if(t.length===0)return"";let n=sX(e.relativePath,e.startLine,t,e.ownerSymbol,e.sessionPolicy??"exact-unit"),r=e.indent??" ",i=e.sourceIndent??" ",o=e.focusLines??new Set;return n.map(s=>{let a=ad(e.relativePath,s.startLine,s.endLine);if(s.kind==="covered"){let u=s.ordinal===null?"this command":`session #${s.ordinal} via ${s.command}`;return[`${r}${a} [source previously emitted: ${u}; not repeated]`,...e.afterHeader??[]].join(`
547
- `)}let c=e.headerSuffix??"",l=s.lines.map((u,d)=>{let m=s.startLine+d,p=e.showFocusMarker===!1?"":o.has(m)?">":" ",f=e.lineNumberWidth??5;return`${i}${p}${String(Wa(m)).padStart(f)} ${u}`});return[`${r}${a}${c}`,...e.blankAfterHeader?[""]:[],...e.afterHeader??[],...l].join(`
548
- `)}).join(`
549
- `)}function qbe(e){let t=Ji.getStore();if(!t||!t.enabled)return e.content;let n=Bp(t);if(!n)return e.content;let r=yw(e.content),i=fl(n.ledger.evidence,o=>o.kind===e.kind&&o.identity===e.identity&&o.contentHash===r);if(i&&!t.reemit){let o=e.label?`; ${fw(e.label)}`:"";return`${e.indent??""}[${e.kind} evidence previously emitted: receipt ${i.receiptId}; session #${i.ordinal} via ${i.command}${o}; not repeated]`}return t.stagedEvidence.push({kind:e.kind,identity:e.identity,contentHash:r,receiptId:vX(e.kind,e.identity,r),...e.label?{label:fw(e.label)}:{}}),e.content}function Gbe(e=!1){let t=Ji.getStore();if(!t?.enabled)return{enabled:!1,reason:"No explicit SCIP_QUERY_SESSION is active; source packets render independently.",uniqueLines:0,evidenceItems:0,emissions:0,rows:[]};let n=Bp(t);if(!n)return{enabled:!1,reason:"The exploration-session ledger was unavailable or contended; evidence output is fail-open for this command.",uniqueLines:0,evidenceItems:0,emissions:0,rows:[]};if(e){n.ledger.ranges=[],n.ledger.evidence=[],n.ledger.nextOrdinal=1,n.ledger.updatedAt=new Date().toISOString();try{Er(n.ledgerPath,n.ledger,{spacing:2,trailingNewline:!0})}catch{return{enabled:!1,reason:"The exploration-session ledger could not be reset; evidence output remains fail-open.",uniqueLines:0,evidenceItems:0,emissions:0,rows:[]}}}let r=new Map;for(let a of n.ledger.ranges){let c=r.get(a.ordinal)??[];c.push(a),r.set(a.ordinal,c)}let i=new Map;for(let a of n.ledger.evidence){let c=i.get(a.ordinal)??[];c.push(a),i.set(a.ordinal,c)}let s=[...new Set([...r.keys(),...i.keys()])].sort((a,c)=>a-c).map(a=>{let c=r.get(a)??[],l=i.get(a)??[],u=c[0]?.command??l[0]?.command??"unknown",d=c.length===0?null:(()=>{let f=c.slice(0,8).map(h=>ad(h.relativePath,h.startLine,h.endLine)).join(", "),g=c.length>8?`, ... ${c.length-8} more range(s)`:"";return` #${a} ${u}: ${f}${g}`})();if(l.length===0)return d;let m=l.slice(0,8).map(f=>`${f.receiptId} ${f.kind}${f.label?` ${f.label}`:""}`).join(", "),p=l.length>8?`, ... ${l.length-8} more item(s)`:"";return d?`${d}
550
- evidence: ${m}${p}`:` #${a} ${u}: ${m}${p}`});return{enabled:!0,uniqueLines:yX(n.ledger.ranges),evidenceItems:n.ledger.evidence.length,emissions:new Set([...r.keys(),...i.keys()]).size,rows:s}}function sX(e,t,n,r,i){let o=Ji.getStore(),s=t+n.length-1;if(!o)return[{kind:"source",startLine:t,endLine:s,lines:[...n]}];let c=(o.enabled?Bp(o):null)?.ledger.ranges??[],l=n.map(yw),u=i==="exact-unit"&&!o.reemit?fl(c,h=>h.policy==="exact-unit"&&h.relativePath===e&&h.startLine===t&&h.endLine===s&&h.ownerSymbol===r&&CX(h.lineHashes,l)):void 0;if(u)return[{kind:"covered",startLine:t,endLine:s,ordinal:u.ordinal,command:u.command}];let d=i==="exact-unit"&&!o.reemit?cX(c,e,t,s,l):void 0;if(d)return[{kind:"covered",startLine:t,endLine:s,ordinal:d.ordinal,command:d.command}];let m=n.map((h,b)=>aX(c,e,t+b,l[b]));if(!(i==="preview"&&!o.reemit&&m.every(h=>h!==void 0)))return o.staged.push({relativePath:e,startLine:t,endLine:s,ownerSymbol:r,policy:i,lineHashes:l}),[{kind:"source",startLine:t,endLine:s,lines:[...n]}];let f=[],g=0;for(;g<n.length;){let h=m[g],b=g;for(;b+1<n.length&&lX(h,m[b+1]);)b+=1;let S=t+g,y=t+b;f.push({kind:"covered",startLine:S,endLine:y,ordinal:h.ordinal,command:h.command}),g=b+1}return f}function aX(e,t,n,r){let i=fl(e,o=>o.relativePath===t&&o.startLine<=n&&n<=o.endLine&&o.lineHashes[n-o.startLine]===r);if(i)return{ordinal:i.ordinal,command:i.command}}function cX(e,t,n,r,i){let o=fl(e,s=>s.policy==="exact-unit"&&s.relativePath===t&&s.startLine<=n&&s.endLine>=r&&i.every((a,c)=>s.lineHashes[n-s.startLine+c]===a));return o?{ordinal:o.ordinal,command:o.command}:void 0}function lX(e,t){return!e||!t?e===t:e.ordinal===t.ordinal&&e.command===t.command}function Bp(e){if(e.state!==void 0)return e.state;if(!e.sessionIdentity||!e.generationIdentity)return e.state=null,null;try{let t=bX();tX(t,{recursive:!0,mode:448});let n=Op("sha256").update(e.projectRoot).update("\0").update(e.generationIdentity).update("\0").update(e.sessionIdentity).digest("hex"),r=gw(t,`${n}.json`),i=fi(`${r}.lock`,{kind:"source-emission-session",detail:{session:n.slice(0,12)}});if(i.kind!=="acquired")return e.state=null,null;let o;try{o=eX(r)?dX(JSON.parse(Ve(r,"source emission session ledger")),{projectRoot:e.projectRoot,generationIdentity:e.generationIdentity,sessionIdentity:e.sessionIdentity}):uX(e)}catch{return i.lock.release(),e.state=null,null}return e.state={ledgerPath:r,lock:i.lock,ledger:o},e.state}catch{return e.state=null,null}}function uX(e){return{version:_p,projectRoot:e.projectRoot,generationIdentity:e.generationIdentity,sessionIdentity:e.sessionIdentity,nextOrdinal:1,updatedAt:new Date().toISOString(),ranges:[],evidence:[]}}function dX(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid source emission ledger.");let n=e;if(e.version===1&&n.projectRoot===t.projectRoot&&n.generationIdentity===t.generationIdentity&&n.sessionIdentity===t.sessionIdentity&&Number.isSafeInteger(n.nextOrdinal)&&(n.nextOrdinal??0)>0)return{version:_p,projectRoot:t.projectRoot,generationIdentity:t.generationIdentity,sessionIdentity:t.sessionIdentity,nextOrdinal:n.nextOrdinal,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:new Date().toISOString(),ranges:[],evidence:[]};if(n.version!==_p||n.projectRoot!==t.projectRoot||n.generationIdentity!==t.generationIdentity||n.sessionIdentity!==t.sessionIdentity||!Number.isSafeInteger(n.nextOrdinal)||(n.nextOrdinal??0)<=0||!Array.isArray(n.ranges)||!n.ranges.every(mX)||!Array.isArray(n.evidence)||!n.evidence.every(pX))throw new Error("Invalid source emission ledger.");return n}function mX(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.relativePath=="string"&&t.relativePath!==""&&Number.isSafeInteger(t.startLine)&&(t.startLine??-1)>=0&&Number.isSafeInteger(t.endLine)&&(t.endLine??-1)>=(t.startLine??0)&&Number.isSafeInteger(t.ordinal)&&(t.ordinal??0)>0&&typeof t.command=="string"&&t.command!==""&&(t.policy==="exact-unit"||t.policy==="preview")&&Array.isArray(t.lineHashes)&&t.lineHashes.length===(t.endLine??0)-(t.startLine??0)+1&&t.lineHashes.every(ni)&&(t.ownerSymbol===void 0||typeof t.ownerSymbol=="string")}function pX(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return(t.kind==="unit"||t.kind==="edge")&&typeof t.identity=="string"&&t.identity!==""&&typeof t.contentHash=="string"&&ni(t.contentHash)&&typeof t.receiptId=="string"&&/^ev-[0-9a-f]{12}$/u.test(t.receiptId)&&Number.isSafeInteger(t.ordinal)&&(t.ordinal??0)>0&&typeof t.command=="string"&&t.command!==""&&(t.label===void 0||typeof t.label=="string")}function fX(e){let t=[...e].sort((r,i)=>r.relativePath.localeCompare(i.relativePath)||r.startLine-i.startLine||r.endLine-i.endLine),n=[];for(let r of t){let i=n[n.length-1];if(i&&i.relativePath===r.relativePath&&i.ownerSymbol===r.ownerSymbol&&i.policy===r.policy&&r.startLine<=i.endLine+1&&gX(i,r)){let o=r.startLine-i.startLine;for(let s=0;s<r.lineHashes.length;s+=1)i.lineHashes[o+s]??=r.lineHashes[s];i.endLine=Math.max(i.endLine,r.endLine)}else n.push({...r,lineHashes:[...r.lineHashes]})}return n}function gX(e,t){let n=Math.max(e.startLine,t.startLine),r=Math.min(e.endLine,t.endLine);for(let i=n;i<=r;i+=1)if(e.lineHashes[i-e.startLine]!==t.lineHashes[i-t.startLine])return!1;return!0}function hX(e){let t=new Set,n=[];for(let r of e){let i=`${r.kind}\0${r.identity}\0${r.contentHash}`;t.has(i)||(t.add(i),n.push(r))}return n}function yX(e){let t=new Map;for(let r of e){let i=t.get(r.relativePath)??[];i.push(r),t.set(r.relativePath,i)}let n=0;for(let r of t.values()){r.sort((s,a)=>s.startLine-a.startLine||s.endLine-a.endLine);let i=-1,o=-1;for(let s of r)i<0?(i=s.startLine,o=s.endLine):s.startLine<=o+1?o=Math.max(o,s.endLine):(n+=o-i+1,i=s.startLine,o=s.endLine);i>=0&&(n+=o-i+1)}return n}function bX(){let e=process.env[pw];if(!e)return gw(nX(),`scip-query-source-sessions-${process.getuid?.()??"user"}`);if(!rX(e))throw new Error(`${pw} must be an absolute path.`);return hw(e)}function SX(){let e=process.env[iX]?.trim();if(e&&!(e.length>oX||!/^[A-Za-z0-9._:-]+$/.test(e)))return`explicit:${e}`}function vX(e,t,n){return`ev-${Op("sha256").update(e).update("\0").update(t).update("\0").update(n).digest("hex").slice(0,12)}`}function fw(e){let t=e.replace(/[\r\n\t]+/gu," ").replace(/\s+/gu," ").trim();return t.length<=160?t:`${t.slice(0,157)}...`}function yw(e){return Op("sha256").update(e).digest("hex")}function CX(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function fl(e,t){for(let n=e.length-1;n>=0;n-=1){let r=e[n];if(t(r))return r}}import{createHash as xX}from"crypto";import{existsSync as jp,mkdirSync as RX,rmSync as EX}from"fs";import{tmpdir as IX}from"os";import{isAbsolute as wX,join as Sw,resolve as gl}from"path";var vw=1,LX="SCIP_QUERY_SESSION",bw="SCIP_QUERY_SESSION_DIR",PX=128,Cw=8,xw=32768,hl=new Map;function Zbe(e,t,n=!0){if(!n)return;let r=yl();if(!r)return;let i=qp(e),o=t.map(a=>a.trim()).filter(a=>a.startsWith("scip-query system-map ")&&a.length<=xw).slice(0,Cw),s=Rw(i,r);o.length===0?hl.delete(s):hl.set(s,o)}function eSe(e,t,n,r=!0,i){if(!r||e!=="anchors"&&e!=="system-map")return;let o=yl();if(!o)return;let s=qp(t),a=Up(s,o);if(e==="system-map"){n?EX(a,{force:!0}):jp(a)&&i&&$p(a,()=>{let c=Hp(a,s,o);c&&Er(a,{...c,pendingMapContinuation:i,mapExecution:void 0,updatedAt:new Date().toISOString()},{spacing:2,trailingNewline:!0})});return}$p(a,()=>{let c=DX(s,o),l={version:vw,projectRoot:s,sessionIdentity:o,mapRequired:!0,...c.length>0?{recommendedMapCommands:c}:{},updatedAt:new Date().toISOString()};Er(a,l,{spacing:2,trailingNewline:!0})})}function tSe(e,t=!0){if(!t)return;let n=yl();if(!n)return;let r=qp(e),i=Up(r,n);jp(i)&&$p(i,()=>{let o=Hp(i,r,n);if(o){if(o.pendingMapContinuation)throw new Error(["MAP TRANSPORT INCOMPLETE","The selected system map has already been computed. Restarting it would repeat the same repository work.",`Continue exactly: ${o.pendingMapContinuation}`].join(`
551
- `));if(o.mapExecution&&MX(o.mapExecution.processId))throw new Error(["NAVIGATION MAP ALREADY RUNNING","A selected system map is already computing in this SCIP_QUERY_SESSION.","Poll the existing terminal execution. Do not launch a duplicate map or inspect in parallel."].join(`
552
- `));Er(i,{...o,mapExecution:{processId:process.pid,startedAt:new Date().toISOString()},updatedAt:new Date().toISOString()},{spacing:2,trailingNewline:!0})}})}function nSe(e,t,n=!0){if(!n)return;let r=yl();if(!r)return;let i=Up(gl(e),r);if(!jp(i))return;let o=Hp(i,gl(e),r);if(!o?.mapRequired)return;let s=o.recommendedMapCommands?.length?["This refusal is a recoverable protocol step, not evidence that the requested code cannot be explored.","Run exactly one of the ranked map commands below, then finish every emitted continuation:",...o.recommendedMapCommands.map((a,c)=>` [${c+1}] ${a}`)]:[`Do not retry ${t}. Run one printed next-abstraction system-map command and finish every emitted continuation first.`];throw new Error(["NAVIGATION MAP REQUIRED","An anchors locator completed in this SCIP_QUERY_SESSION, but its selected system map has not reached transport completion.",`Do not retry ${t}.`,...s,"The map must complete before the agent can choose source detail; map and detail exploration cannot run concurrently."].join(`
553
- `))}function Hp(e,t,n){try{let r=JSON.parse(Ve(e,"navigation session state"));return r.version===vw&&r.projectRoot===t&&r.sessionIdentity===n&&r.mapRequired===!0&&(r.recommendedMapCommands===void 0||Array.isArray(r.recommendedMapCommands)&&r.recommendedMapCommands.length<=Cw&&r.recommendedMapCommands.every(i=>typeof i=="string"&&i.startsWith("scip-query system-map ")&&i.length<=xw))&&(r.pendingMapContinuation===void 0||typeof r.pendingMapContinuation=="string")&&(r.mapExecution===void 0||typeof r.mapExecution=="object"&&r.mapExecution!==null&&Number.isSafeInteger(r.mapExecution.processId)&&typeof r.mapExecution.startedAt=="string")?r:null}catch{return null}}function DX(e,t){let n=Rw(e,t),r=hl.get(n)??[];return hl.delete(n),r}function Rw(e,t){return`${e}\0${t}`}function MX(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function Up(e,t){let n=TX();RX(n,{recursive:!0,mode:448});let r=xX("sha256").update(e).update("\0").update(t).digest("hex");return Sw(n,`navigation-${r}.json`)}function TX(){let e=process.env[bw];if(!e)return Sw(IX(),`scip-query-source-sessions-${process.getuid?.()??"user"}`);if(!wX(e))throw new Error(`${bw} must be an absolute path.`);return gl(e)}function qp(e){let t=process.env.SCIP_QUERY_PROJECT_ROOT?.trim();return gl(t||e)}function yl(){let e=process.env[LX]?.trim();if(e&&!(e.length>PX||!/^[A-Za-z0-9._:-]+$/u.test(e)))return`explicit:${e}`}function $p(e,t){let n=fi(`${e}.lock`,{kind:"navigation-session",detail:{state:e.slice(-17,-5)}});if(n.kind!=="acquired")throw new Error("Navigation session state is busy. Retry the completed command.");try{t()}finally{n.lock.release()}}export{kr as a,_r as b,TF as c,HF as d,so as e,Wt as f,Dg as g,e3 as h,va as i,I6 as j,_D as k,Ii as l,Iy as m,KZ as n,n0 as o,Ho as p,Sg as q,K3 as r,Uo as s,qo as t,uc as u,sv as v,bN as w,HN as x,n9 as y,Sre as z,WN as A,ZN as B,$t as C,Be as D,Fv as E,KO as F,c$ as G,ts as H,cm as I,T$ as J,Vr as K,vj as L,Rj as M,Ej as N,Ij as O,Bj as P,Hj as Q,Uj as R,qj as S,zj as T,Kj as U,Wj as V,Rx as W,is as X,gm as Y,h1 as Z,os as _,S1 as $,v1 as aa,L1 as ba,A1 as ca,F1 as da,k1 as ea,as as fa,Cm as ga,cs as ha,BH as ia,ls as ja,us as ka,Rm as la,ds as ma,ms as na,Em as oa,MU as pa,ps as qa,Oq as ra,lG as sa,Fm as ta,vG as ua,Wi as va,HR as wa,ez as xa,gs as ya,TK as za,ys as Aa,eW as Ba,bs as Ca,zW as Da,KW as Ea,eV as Fa,fV as Ga,CV as Ha,BV as Ia,op as Ja,QE as Ka,sp as La,ZE as Ma,el as Na,m2 as Oa,Rs as Pa,Es as Qa,Is as Ra,CY as Sa,xY as Ta,RY as Ua,hp as Va,sl as Wa,bp as Xa,nJ as Ya,_J as Za,OJ as _a,$J as $a,HJ as ab,QJ as bb,o5 as cb,GM as db,c9 as eb,Na as fb,Fo as gb,hb,N9 as ib,_9 as jb,O9 as kb,B9 as lb,$9 as mb,j9 as nb,t7 as ob,Sb as pb,n7 as qb,vb as rb,Cb as sb,qa as tb,pA as ub,fA as vb,gA as wb,hA as xb,Rb as yb,Ga as zb,R7 as Ab,za as Bb,Eb as Cb,E7 as Db,I7 as Eb,w7 as Fb,L7 as Gb,CA as Hb,Ka as Ib,P7 as Jb,D7 as Kb,id as Lb,M7 as Mb,A7 as Nb,F7 as Ob,k7 as Pb,N7 as Qb,wb as Rb,Tt as Sb,sd as Tb,_7 as Ub,Xr as Vb,Mye as Wb,Hye as Xb,Wa as Yb,MA as Zb,ad as _b,$7 as $b,cd as ac,ow as bc,q5 as cc,G5 as dc,vbe as ec,Cbe as fc,xbe as gc,Rbe as hc,x4 as ic,Ebe as jc,Ibe as kc,wbe as lc,$be as mc,jbe as nc,Hbe as oc,Ube as pc,qbe as qc,Gbe as rc,Zbe as sc,eSe as tc,tSe as uc,nSe as vc};
554
- //# sourceMappingURL=chunk-NOYBFVJA.js.map