codebaseiq 0.1.0 → 0.3.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 (447) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/README.md +1 -1
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/{chunk-ZMI2JSX2.js → chunk-23C5AD3B.js} +2 -2
  5. package/dist/chunk-2E6OUPCF.js +2 -0
  6. package/dist/chunk-2EDX3JT5.js +3 -0
  7. package/dist/chunk-2I2UHZET.js +2 -0
  8. package/dist/{chunk-T3DGWPXM.js → chunk-2OMXFE64.js} +2 -2
  9. package/dist/chunk-2PRONPAS.js +3 -0
  10. package/dist/{chunk-GW6Z3WGY.js → chunk-356EZBIP.js} +2 -2
  11. package/dist/{chunk-UDS562V4.js → chunk-36JC5BG2.js} +2 -2
  12. package/dist/chunk-3RR2K7EZ.js +20 -0
  13. package/dist/{chunk-JE3WZ6II.js → chunk-3RSBGWGL.js} +2 -2
  14. package/dist/{chunk-VE5AVNMP.js → chunk-3VJ3OCRE.js} +2 -2
  15. package/dist/{chunk-FDGD5AB5.js → chunk-4LK5OIPW.js} +2 -2
  16. package/dist/chunk-5DSL3NT2.js +17 -0
  17. package/dist/chunk-5FWR5HLG.js +90 -0
  18. package/dist/chunk-5IC2WZAL.js +22 -0
  19. package/dist/{chunk-MVB3DAEY.js → chunk-5IZRKWTZ.js} +2 -2
  20. package/dist/{chunk-Q65CQ4XL.js → chunk-5LL4KEHO.js} +2 -2
  21. package/dist/chunk-5T44HG5Y.js +88 -0
  22. package/dist/{chunk-TRRC4ZJ7.js → chunk-5ZI2PPI7.js} +2 -2
  23. package/dist/{chunk-7XAN6GKB.js → chunk-67VJAYVR.js} +2 -2
  24. package/dist/{chunk-MOVBWNIP.js → chunk-6BF3VYEF.js} +2 -2
  25. package/dist/chunk-6JMAVFL4.js +3 -0
  26. package/dist/chunk-6O3KXIDL.js +2 -0
  27. package/dist/{chunk-JOIRNPPY.js → chunk-6VREELBC.js} +2 -2
  28. package/dist/chunk-6WAPPQ5F.js +82 -0
  29. package/dist/{chunk-FW53T7EB.js → chunk-75KJGYX7.js} +2 -2
  30. package/dist/chunk-7GAK2F3H.js +77 -0
  31. package/dist/{chunk-UBGWN7I4.js → chunk-7JELP5YE.js} +2 -2
  32. package/dist/chunk-7UCDGXRW.js +8 -0
  33. package/dist/{chunk-L57ZKWVG.js → chunk-AEXQYQD7.js} +2 -2
  34. package/dist/chunk-AQI4N64O.js +22 -0
  35. package/dist/{chunk-ICFDQHAM.js → chunk-AURCQHSG.js} +2 -2
  36. package/dist/{chunk-I2T2LLK2.js → chunk-BBP7HVBJ.js} +2 -2
  37. package/dist/{chunk-OFBE4NGP.js → chunk-BFBIMTCJ.js} +2 -2
  38. package/dist/{chunk-JEJLSICM.js → chunk-BGGB5N53.js} +2 -2
  39. package/dist/{chunk-TIIC3ZE7.js → chunk-BRQL7AFJ.js} +2 -2
  40. package/dist/{chunk-YSNONTJ2.js → chunk-BWL3PMPT.js} +2 -2
  41. package/dist/chunk-C6WKPKCF.js +127 -0
  42. package/dist/{chunk-YESXMKX3.js → chunk-C7OUW52M.js} +2 -2
  43. package/dist/chunk-C7QWUBR2.js +545 -0
  44. package/dist/{chunk-4WKDMDEW.js → chunk-CCIYWXX6.js} +2 -2
  45. package/dist/{chunk-FAJQ7LWY.js → chunk-CIYA2KZN.js} +2 -2
  46. package/dist/{chunk-VEXUL62T.js → chunk-CR3OG6SQ.js} +2 -2
  47. package/dist/{chunk-JSOYNVWH.js → chunk-CVHOQONG.js} +2 -2
  48. package/dist/{chunk-LU3BMVH2.js → chunk-CW6AXOLR.js} +2 -2
  49. package/dist/{chunk-TXXOEMZJ.js → chunk-D53LWANR.js} +2 -2
  50. package/dist/{chunk-DO6WQD2T.js → chunk-D62CTZX6.js} +2 -2
  51. package/dist/{chunk-N3IQCBCF.js → chunk-D7AZAOZX.js} +2 -2
  52. package/dist/{chunk-RDBI2RXU.js → chunk-D7DOB27N.js} +7 -7
  53. package/dist/chunk-DAKIGMIK.js +21 -0
  54. package/dist/chunk-DDN2F6GB.js +2 -0
  55. package/dist/chunk-DUKHVPU5.js +4 -0
  56. package/dist/chunk-DVWO7RBC.js +2 -0
  57. package/dist/{chunk-HKQUXIFO.js → chunk-E52K4L2W.js} +2 -2
  58. package/dist/chunk-EIBGSU2R.js +2 -0
  59. package/dist/chunk-EN4AHLL3.js +3 -0
  60. package/dist/chunk-EQNMD62X.js +51 -0
  61. package/dist/{chunk-ENCCHKM6.js → chunk-EXZ7VLRY.js} +4 -4
  62. package/dist/{chunk-NEDP5RFQ.js → chunk-F3QSL4W2.js} +2 -2
  63. package/dist/{chunk-O6QTXQPJ.js → chunk-F74LZWCE.js} +2 -2
  64. package/dist/{chunk-BH5F2Q4O.js → chunk-FEIZXBLH.js} +2 -2
  65. package/dist/chunk-FH5WG4LE.js +2 -0
  66. package/dist/{chunk-BVAJLC5A.js → chunk-FOZ74V56.js} +2 -2
  67. package/dist/{chunk-L4NRUAGJ.js → chunk-FQTIFWLR.js} +2 -2
  68. package/dist/chunk-FTTV7IRX.js +355 -0
  69. package/dist/chunk-FWQGH2N2.js +2 -0
  70. package/dist/{chunk-CAUCPUOF.js → chunk-GDHWOA57.js} +2 -2
  71. package/dist/{chunk-6MUIJMVL.js → chunk-GIDCP7KV.js} +2 -2
  72. package/dist/{chunk-ZV3JV5G5.js → chunk-GL6UTNUB.js} +2 -2
  73. package/dist/chunk-GP7C5VAE.js +2 -0
  74. package/dist/{chunk-FQKZWM4L.js → chunk-GQLDYCWS.js} +5 -5
  75. package/dist/chunk-GQXXOS55.js +2 -0
  76. package/dist/{chunk-H3LGFZVK.js → chunk-GUFPEFBG.js} +2 -2
  77. package/dist/{chunk-NNOKTMZT.js → chunk-GV2CEZCW.js} +2 -2
  78. package/dist/{chunk-FETNQCFO.js → chunk-GVAF222T.js} +2 -2
  79. package/dist/chunk-GWYZVVKY.js +21 -0
  80. package/dist/{chunk-7FND7D7N.js → chunk-HENP2O4A.js} +2 -2
  81. package/dist/{chunk-LZYFLFEH.js → chunk-HINZQKSY.js} +2 -2
  82. package/dist/{chunk-RR7SX44N.js → chunk-HQA7EBSK.js} +2 -2
  83. package/dist/{chunk-XMQ23E27.js → chunk-HVFB3PME.js} +2 -2
  84. package/dist/chunk-I22IZYDI.js +2 -0
  85. package/dist/chunk-ICUL7XRT.js +21 -0
  86. package/dist/{chunk-CQP3THUZ.js → chunk-IHSLIIL3.js} +2 -2
  87. package/dist/{chunk-34WBMAYK.js → chunk-ITSJMNUD.js} +2 -2
  88. package/dist/{chunk-PX4RYAAK.js → chunk-IZDPGOZR.js} +2 -2
  89. package/dist/chunk-J3GLP7Q5.js +3 -0
  90. package/dist/{chunk-CVYSU6BX.js → chunk-J7AMBVWF.js} +2 -2
  91. package/dist/{chunk-Y6KHROC3.js → chunk-JCMFBF4Z.js} +2 -2
  92. package/dist/chunk-JFIA2JI3.js +3 -0
  93. package/dist/chunk-JLZLLLW5.js +3 -0
  94. package/dist/{chunk-5PUWMSDU.js → chunk-JSNTHRLQ.js} +2 -2
  95. package/dist/{chunk-C6SBF2WH.js → chunk-JX6ZWDOS.js} +2 -2
  96. package/dist/{chunk-4XTAUQFD.js → chunk-JYI7CV25.js} +2 -2
  97. package/dist/chunk-K7JLSGCJ.js +8 -0
  98. package/dist/{chunk-XWUOUWYI.js → chunk-KPZGTB2O.js} +2 -2
  99. package/dist/{chunk-VXYS3FZD.js → chunk-LKUTSP4G.js} +2 -2
  100. package/dist/{chunk-GTXSJDCO.js → chunk-LMTSB3TB.js} +2 -2
  101. package/dist/chunk-LONKINMJ.js +543 -0
  102. package/dist/{chunk-WMPRTGH2.js → chunk-LQHYYIOB.js} +2 -2
  103. package/dist/{chunk-VUIYB2V3.js → chunk-LZSQ6X7E.js} +2 -2
  104. package/dist/{chunk-ST7V3SKN.js → chunk-M2Y6PCFE.js} +2 -2
  105. package/dist/chunk-MEUHIDI3.js +7 -0
  106. package/dist/{chunk-OZYRSMSH.js → chunk-MHWMEZDA.js} +2 -2
  107. package/dist/{chunk-RKEJ6VTF.js → chunk-MQW6SJ4P.js} +2 -2
  108. package/dist/{chunk-J77SU6VA.js → chunk-MSI3K7PJ.js} +2 -2
  109. package/dist/chunk-MVRGB4KJ.js +278 -0
  110. package/dist/{chunk-DQMDCD24.js → chunk-MZNMASFM.js} +2 -2
  111. package/dist/{chunk-ID63777H.js → chunk-NBCQZSGR.js} +2 -2
  112. package/dist/chunk-NBZKSTXP.js +2 -0
  113. package/dist/{chunk-SZD2KF7Q.js → chunk-NCJILOAK.js} +2 -2
  114. package/dist/{chunk-C7QOQX32.js → chunk-NDKOVQFG.js} +2 -2
  115. package/dist/{chunk-UNBY47BC.js → chunk-NEWHKGVD.js} +2 -2
  116. package/dist/{chunk-PYAB5SM6.js → chunk-O2M3VNDY.js} +2 -2
  117. package/dist/chunk-OFGOOL6U.js +3 -0
  118. package/dist/{chunk-SWHMHUKF.js → chunk-OQUCBKOI.js} +2 -2
  119. package/dist/{chunk-7MGU3HPH.js → chunk-P4NVCOM7.js} +2 -2
  120. package/dist/{chunk-ANFVSJWQ.js → chunk-PFC44E6D.js} +2 -2
  121. package/dist/{chunk-EZNMUY67.js → chunk-PHNCEUXX.js} +2 -2
  122. package/dist/{chunk-4FC325IF.js → chunk-PTQPPPG2.js} +2 -2
  123. package/dist/chunk-PUVNH4PO.js +3 -0
  124. package/dist/chunk-Q23IMHXS.js +343 -0
  125. package/dist/chunk-Q3ZCQY2Y.js +3 -0
  126. package/dist/{chunk-KMITESMT.js → chunk-Q4XEU3UH.js} +2 -2
  127. package/dist/{chunk-QKPLA6IC.js → chunk-QEOWONKY.js} +2 -2
  128. package/dist/{chunk-BJ6SQAEN.js → chunk-QMOZZ2VX.js} +2 -2
  129. package/dist/chunk-RCIGX23V.js +60 -0
  130. package/dist/{chunk-IOP6FWIM.js → chunk-RIYJ4L33.js} +2 -2
  131. package/dist/chunk-RJVAPMHF.js +14 -0
  132. package/dist/chunk-SB7NASHU.js +2 -0
  133. package/dist/{chunk-UZGZB3VB.js → chunk-SGMNWYTH.js} +2 -2
  134. package/dist/chunk-SMDIEDM4.js +27 -0
  135. package/dist/chunk-SV2LEFVM.js +2 -0
  136. package/dist/chunk-SX72EVMY.js +3 -0
  137. package/dist/chunk-T5X7DK6C.js +3 -0
  138. package/dist/{chunk-6NW7MU72.js → chunk-T6MQNNAC.js} +2 -2
  139. package/dist/chunk-T75DS2E6.js +21 -0
  140. package/dist/{chunk-HRWGYWRJ.js → chunk-TEANKHUU.js} +2 -2
  141. package/dist/chunk-TJBOJUVN.js +3 -0
  142. package/dist/{chunk-XLQ3GLWZ.js → chunk-TJWVT4DO.js} +2 -2
  143. package/dist/{chunk-7NVGT435.js → chunk-TNJGTQWO.js} +2 -2
  144. package/dist/{chunk-NE6IU5ZD.js → chunk-TOTWJZIX.js} +2 -2
  145. package/dist/{chunk-PBI2LFKH.js → chunk-TPO7XC5Z.js} +2 -2
  146. package/dist/{chunk-HPJRBHVT.js → chunk-U33PMPNW.js} +2 -2
  147. package/dist/{chunk-QHRNXP3C.js → chunk-U7NUXDQO.js} +2 -2
  148. package/dist/chunk-UC2FD2PS.js +4 -0
  149. package/dist/{chunk-PIOMTC27.js → chunk-UQE4XFSA.js} +2 -2
  150. package/dist/chunk-UQYQBLJX.js +5 -0
  151. package/dist/{chunk-KWVHSKHK.js → chunk-USOAJHY7.js} +2 -2
  152. package/dist/{chunk-GCHRX4YW.js → chunk-UW6KD57C.js} +2 -2
  153. package/dist/{chunk-PTAWHLVJ.js → chunk-VGWZ4MOY.js} +2 -2
  154. package/dist/{chunk-XME3HPXZ.js → chunk-VWYGCMV5.js} +2 -2
  155. package/dist/{chunk-AKB7V7TV.js → chunk-W7YLRXZE.js} +2 -2
  156. package/dist/{chunk-SYDJMPES.js → chunk-WK2IQJPK.js} +2 -2
  157. package/dist/{chunk-RBAS5ZHI.js → chunk-WWCV4E6J.js} +2 -2
  158. package/dist/{chunk-OL6KJP3N.js → chunk-XMJ53WG4.js} +2 -2
  159. package/dist/chunk-XN3EKMLI.js +4 -0
  160. package/dist/chunk-XQAVQVIL.js +3 -0
  161. package/dist/{chunk-IJ4HMYBE.js → chunk-XQPPURLQ.js} +2 -2
  162. package/dist/{chunk-OVTS4DKB.js → chunk-YHPG3S2U.js} +2 -2
  163. package/dist/{chunk-WOQBZPIF.js → chunk-YRKP7PM7.js} +2 -2
  164. package/dist/chunk-YT4DVWUV.js +11 -0
  165. package/dist/chunk-YTJHCGYB.js +61 -0
  166. package/dist/chunk-Z35GOVEH.js +2 -0
  167. package/dist/{chunk-OLF4MA5W.js → chunk-Z6RL7XOE.js} +4 -4
  168. package/dist/{chunk-UP3BUZR5.js → chunk-ZAFGY22Q.js} +2 -2
  169. package/dist/{chunk-CO5R3UNA.js → chunk-ZB4C5TTR.js} +2 -2
  170. package/dist/{chunk-ZZXSWSN6.js → chunk-ZNH33XIB.js} +2 -2
  171. package/dist/{chunk-EMNIHCRB.js → chunk-ZQ62NNKN.js} +2 -2
  172. package/dist/cli-context-FJL2JHOE.js +3 -0
  173. package/dist/cli-context-PQNWHMCQ.js +2 -0
  174. package/dist/cli-program-UO7PZD6V.js +7 -0
  175. package/dist/cli.js +1 -1
  176. package/dist/{code-DlqpBDd0.d.ts → code-DfX3xeWy.d.ts} +1 -1
  177. package/dist/code-viewer-KIXEYQNJ.js +12 -0
  178. package/dist/code-viewer-VHLBLIUM.js +11 -0
  179. package/dist/command-descriptors-F5P2V3NW.js +335 -0
  180. package/dist/command-descriptors-YCLATF5I.js +337 -0
  181. package/dist/{config-types-BNoC96J3.d.ts → config-types-D6X5S68_.d.ts} +50 -0
  182. package/dist/{db-D7sauVFH.d.ts → db-BoG_PWYH.d.ts} +2 -2
  183. package/dist/direct-navigation-4XJTXIDT.js +2 -0
  184. package/dist/direct-navigation-J5MVYYAD.js +3 -0
  185. package/dist/{graph-evidence-BIFqyisO.d.ts → graph-evidence-D1jx1Cql.d.ts} +1 -1
  186. package/dist/{health-DJaZXg8I.d.ts → health-DkYBS5BI.d.ts} +1 -1
  187. package/dist/index.d.ts +2 -2
  188. package/dist/index.js +1 -1
  189. package/dist/invocation-command-descriptors-RWV4VAI4.js +2 -0
  190. package/dist/invocation-command-descriptors-U76PN7IY.js +3 -0
  191. package/dist/{scip-cli-B7N3haxa.d.ts → maintenance-types-CdL5eQii.d.ts} +2 -21
  192. package/dist/output-continuation-command-BL25S26S.js +3 -0
  193. package/dist/output-continuation-command-BTETTXEC.js +2 -0
  194. package/dist/postinstall.js +1 -1
  195. package/dist/project-reindex-CRJU3IFG.js +2 -0
  196. package/dist/project-reindex-TQFCOA2O.js +3 -0
  197. package/dist/queries/affected.d.ts +2 -2
  198. package/dist/queries/affected.js +1 -1
  199. package/dist/queries/anchors.d.ts +2 -2
  200. package/dist/queries/anchors.js +1 -1
  201. package/dist/queries/architecture.d.ts +2 -2
  202. package/dist/queries/architecture.js +1 -1
  203. package/dist/queries/bottlenecks.d.ts +2 -2
  204. package/dist/queries/bottlenecks.js +1 -1
  205. package/dist/queries/by-kind.d.ts +2 -2
  206. package/dist/queries/by-kind.js +1 -1
  207. package/dist/queries/call-graph.d.ts +2 -2
  208. package/dist/queries/call-graph.js +1 -1
  209. package/dist/queries/change-surface.d.ts +2 -2
  210. package/dist/queries/change-surface.js +1 -1
  211. package/dist/queries/cleanup-plan.d.ts +2 -2
  212. package/dist/queries/cleanup-plan.js +1 -1
  213. package/dist/queries/co-change.d.ts +2 -2
  214. package/dist/queries/co-change.js +1 -1
  215. package/dist/queries/code.d.ts +3 -3
  216. package/dist/queries/code.js +1 -1
  217. package/dist/queries/complexity-hotspots.d.ts +2 -2
  218. package/dist/queries/complexity-hotspots.js +1 -1
  219. package/dist/queries/complexity.d.ts +2 -2
  220. package/dist/queries/complexity.js +1 -1
  221. package/dist/queries/context.d.ts +2 -2
  222. package/dist/queries/context.js +1 -1
  223. package/dist/queries/convergence.d.ts +2 -2
  224. package/dist/queries/convergence.js +1 -1
  225. package/dist/queries/coupling.d.ts +2 -2
  226. package/dist/queries/coupling.js +1 -1
  227. package/dist/queries/cycles.d.ts +2 -2
  228. package/dist/queries/cycles.js +1 -1
  229. package/dist/queries/dataflow.d.ts +2 -2
  230. package/dist/queries/dataflow.js +1 -1
  231. package/dist/queries/dead.d.ts +2 -2
  232. package/dist/queries/dead.js +1 -1
  233. package/dist/queries/decorative-checkers.d.ts +2 -2
  234. package/dist/queries/decorative-checkers.js +1 -1
  235. package/dist/queries/deep-chains.d.ts +2 -2
  236. package/dist/queries/deep-chains.js +1 -1
  237. package/dist/queries/dependence-slice.d.ts +3 -3
  238. package/dist/queries/dependence-slice.js +1 -1
  239. package/dist/queries/dependency-depth.d.ts +2 -2
  240. package/dist/queries/dependency-depth.js +1 -1
  241. package/dist/queries/deps.d.ts +2 -2
  242. package/dist/queries/deps.js +1 -1
  243. package/dist/queries/diff-impact.d.ts +2 -2
  244. package/dist/queries/diff-impact.js +1 -1
  245. package/dist/queries/doc-drift.d.ts +2 -2
  246. package/dist/queries/doc-drift.js +1 -1
  247. package/dist/queries/drift.d.ts +2 -2
  248. package/dist/queries/drift.js +1 -1
  249. package/dist/queries/duplicate-bodies.d.ts +2 -2
  250. package/dist/queries/duplicate-bodies.js +1 -1
  251. package/dist/queries/entry-map.d.ts +2 -2
  252. package/dist/queries/entry-map.js +1 -1
  253. package/dist/queries/evidence.d.ts +3 -3
  254. package/dist/queries/evidence.js +1 -1
  255. package/dist/queries/extract-candidates.d.ts +2 -2
  256. package/dist/queries/extract-candidates.js +1 -1
  257. package/dist/queries/fan.d.ts +2 -2
  258. package/dist/queries/fan.js +1 -1
  259. package/dist/queries/files.d.ts +2 -2
  260. package/dist/queries/files.js +1 -1
  261. package/dist/queries/health.d.ts +3 -3
  262. package/dist/queries/health.js +1 -1
  263. package/dist/queries/hierarchy.d.ts +2 -2
  264. package/dist/queries/hierarchy.js +1 -1
  265. package/dist/queries/hotspots.d.ts +2 -2
  266. package/dist/queries/hotspots.js +1 -1
  267. package/dist/queries/imports.d.ts +2 -2
  268. package/dist/queries/imports.js +1 -1
  269. package/dist/queries/incomplete-migration.d.ts +2 -2
  270. package/dist/queries/incomplete-migration.js +1 -1
  271. package/dist/queries/index.d.ts +5 -5
  272. package/dist/queries/index.js +1 -1
  273. package/dist/queries/isolated.d.ts +2 -2
  274. package/dist/queries/isolated.js +1 -1
  275. package/dist/queries/locality-candidates.d.ts +2 -2
  276. package/dist/queries/locality-candidates.js +1 -1
  277. package/dist/queries/members.d.ts +2 -2
  278. package/dist/queries/members.js +1 -1
  279. package/dist/queries/methods.d.ts +2 -2
  280. package/dist/queries/methods.js +1 -1
  281. package/dist/queries/not-implemented.d.ts +2 -2
  282. package/dist/queries/not-implemented.js +1 -1
  283. package/dist/queries/outline.d.ts +2 -2
  284. package/dist/queries/outline.js +1 -1
  285. package/dist/queries/passthrough-candidates.d.ts +2 -2
  286. package/dist/queries/passthrough-candidates.js +1 -1
  287. package/dist/queries/plan-context.d.ts +2 -2
  288. package/dist/queries/plan-context.js +1 -1
  289. package/dist/queries/react-component-duplicates.d.ts +2 -2
  290. package/dist/queries/react-component-duplicates.js +1 -1
  291. package/dist/queries/react-hook-candidates.d.ts +2 -2
  292. package/dist/queries/react-hook-candidates.js +1 -1
  293. package/dist/queries/react-large-component-pressure.d.ts +2 -2
  294. package/dist/queries/react-large-component-pressure.js +1 -1
  295. package/dist/queries/recent-duplicates.d.ts +2 -2
  296. package/dist/queries/recent-duplicates.js +1 -1
  297. package/dist/queries/redundant-reexports.d.ts +2 -2
  298. package/dist/queries/redundant-reexports.js +1 -1
  299. package/dist/queries/reference-neighborhood.d.ts +2 -2
  300. package/dist/queries/reference-neighborhood.js +1 -1
  301. package/dist/queries/reference-reachability.d.ts +2 -2
  302. package/dist/queries/reference-reachability.js +1 -1
  303. package/dist/queries/refs.d.ts +2 -2
  304. package/dist/queries/refs.js +1 -1
  305. package/dist/queries/self-audit.d.ts +2 -2
  306. package/dist/queries/self-audit.js +1 -1
  307. package/dist/queries/similar-chains.d.ts +2 -2
  308. package/dist/queries/similar-chains.js +1 -1
  309. package/dist/queries/similar-files.d.ts +2 -2
  310. package/dist/queries/similar-files.js +1 -1
  311. package/dist/queries/similar-signatures.d.ts +2 -2
  312. package/dist/queries/similar-signatures.js +1 -1
  313. package/dist/queries/similar.d.ts +2 -2
  314. package/dist/queries/similar.js +1 -1
  315. package/dist/queries/slice.d.ts +2 -2
  316. package/dist/queries/slice.js +1 -1
  317. package/dist/queries/source-inspection.d.ts +4 -4
  318. package/dist/queries/source-inspection.js +1 -1
  319. package/dist/queries/source-search.d.ts +2 -2
  320. package/dist/queries/source-search.js +1 -1
  321. package/dist/queries/stale-abstractions.d.ts +2 -2
  322. package/dist/queries/stale-abstractions.js +1 -1
  323. package/dist/queries/stats.d.ts +2 -2
  324. package/dist/queries/surface.d.ts +2 -2
  325. package/dist/queries/surface.js +1 -1
  326. package/dist/queries/symbols.d.ts +2 -2
  327. package/dist/queries/symbols.js +1 -1
  328. package/dist/queries/system-map.d.ts +2 -2
  329. package/dist/queries/system-map.js +1 -1
  330. package/dist/queries/system.d.ts +2 -2
  331. package/dist/queries/system.js +1 -1
  332. package/dist/queries/test-quality.d.ts +2 -2
  333. package/dist/queries/test-quality.js +1 -1
  334. package/dist/queries/trace.d.ts +2 -2
  335. package/dist/queries/trace.js +1 -1
  336. package/dist/queries/twin-ab.d.ts +2 -2
  337. package/dist/queries/twin-ab.js +1 -1
  338. package/dist/queries/twin-drift.d.ts +2 -2
  339. package/dist/queries/twin-drift.js +1 -1
  340. package/dist/queries/unused-imports.d.ts +2 -2
  341. package/dist/queries/unused-imports.js +1 -1
  342. package/dist/queries/unused-params.d.ts +2 -2
  343. package/dist/queries/unused-params.js +1 -1
  344. package/dist/queries/value-flow.d.ts +3 -3
  345. package/dist/queries/value-flow.js +1 -1
  346. package/dist/queries/vue-component-duplicates.d.ts +2 -2
  347. package/dist/queries/vue-component-duplicates.js +1 -1
  348. package/dist/queries/vue-composable-candidates.d.ts +2 -2
  349. package/dist/queries/vue-composable-candidates.js +1 -1
  350. package/dist/queries/vue-large-view-pressure.d.ts +2 -2
  351. package/dist/queries/vue-large-view-pressure.js +1 -1
  352. package/dist/queries/wrapper-candidates.d.ts +2 -2
  353. package/dist/queries/wrapper-candidates.js +1 -1
  354. package/dist/reindex-worker.js +2 -2
  355. package/dist/reindex.d.ts +3 -5
  356. package/dist/reindex.js +72 -33
  357. package/dist/runtime.d.ts +23 -4
  358. package/dist/runtime.js +3 -3
  359. package/dist/rust-semantic-session-server.js +1 -1
  360. package/dist/rust-semantic-session-worker.js +1 -1
  361. package/dist/rust-semantic-worker.js +1 -1
  362. package/dist/sentinel-ensure-command-OSWGCFFL.js +3 -0
  363. package/dist/sentinel-ensure-command-SPW7XQLB.js +2 -0
  364. package/dist/sentinel-hook.js +39 -0
  365. package/dist/sentinel-worker.js +16 -0
  366. package/dist/typescript-mailbox-worker.js +1 -1
  367. package/dist/watch-server.js +6 -6
  368. package/docs/COMMAND_REFERENCE.md +5 -3
  369. package/docs/INDEX_GENERATIONS.md +2 -2
  370. package/docs/NPM_RELEASE.md +323 -0
  371. package/docs/schemas/npm-release-state.schema.json +4 -13
  372. package/docs/schemas/project-config.schema.json +159 -0
  373. package/package.json +10 -14
  374. package/skills/codebaseiq/SKILL.md +1 -1
  375. package/skills/concrete-plan/SKILL.md +1 -1
  376. package/ui/view/api.js +450 -0
  377. package/ui/view/app.js +394 -0
  378. package/ui/view/builder.js +323 -0
  379. package/ui/view/file-panel.js +170 -0
  380. package/ui/view/focus.js +379 -0
  381. package/ui/view/index.html +54 -0
  382. package/ui/view/map.js +424 -0
  383. package/ui/view/styles.css +1125 -0
  384. package/dist/chunk-2Q2LW5JW.js +0 -14
  385. package/dist/chunk-2X7V4HS4.js +0 -88
  386. package/dist/chunk-3IER7Q6H.js +0 -12
  387. package/dist/chunk-3JSXXYTZ.js +0 -345
  388. package/dist/chunk-476NR5B7.js +0 -2
  389. package/dist/chunk-5VKBFZZU.js +0 -3
  390. package/dist/chunk-6BQ3DSPK.js +0 -2
  391. package/dist/chunk-6CS3UQTN.js +0 -3
  392. package/dist/chunk-6OAHRI2D.js +0 -6
  393. package/dist/chunk-ADTBPVUZ.js +0 -21
  394. package/dist/chunk-BFFZDZQV.js +0 -2
  395. package/dist/chunk-BMYOV5GP.js +0 -77
  396. package/dist/chunk-C74PPYLA.js +0 -3
  397. package/dist/chunk-CWONGW6P.js +0 -3
  398. package/dist/chunk-DDZ7VHWV.js +0 -20
  399. package/dist/chunk-DR2LURYU.js +0 -3
  400. package/dist/chunk-ECQBG7PW.js +0 -564
  401. package/dist/chunk-EF2R3WNQ.js +0 -2
  402. package/dist/chunk-FM5BPL4V.js +0 -60
  403. package/dist/chunk-G6XFR4ZL.js +0 -4
  404. package/dist/chunk-GTIYTDRE.js +0 -562
  405. package/dist/chunk-HOA5YGOH.js +0 -3
  406. package/dist/chunk-KUW32IRO.js +0 -2
  407. package/dist/chunk-LTA3BRZX.js +0 -2
  408. package/dist/chunk-NAUD7LCA.js +0 -2
  409. package/dist/chunk-NCZUNH3E.js +0 -109
  410. package/dist/chunk-NNJ2KZZG.js +0 -4
  411. package/dist/chunk-NNO6A2PO.js +0 -2
  412. package/dist/chunk-OGTFJ3XD.js +0 -2
  413. package/dist/chunk-Q5ELPRKQ.js +0 -2
  414. package/dist/chunk-Q72QSKXC.js +0 -308
  415. package/dist/chunk-QCN62RTF.js +0 -3
  416. package/dist/chunk-QW7EP6WI.js +0 -21
  417. package/dist/chunk-RU65DDUP.js +0 -215
  418. package/dist/chunk-SELM5MER.js +0 -2
  419. package/dist/chunk-SMRBZ6EC.js +0 -2
  420. package/dist/chunk-SNNWPCN7.js +0 -4
  421. package/dist/chunk-TFZB6XTM.js +0 -239
  422. package/dist/chunk-UCD3H3UZ.js +0 -5
  423. package/dist/chunk-UXM43C7T.js +0 -3
  424. package/dist/chunk-VFY6Y2H6.js +0 -61
  425. package/dist/chunk-WE5RZHZ7.js +0 -5
  426. package/dist/chunk-YMGZZEW4.js +0 -2
  427. package/dist/chunk-YVCIMIOC.js +0 -12
  428. package/dist/chunk-Z54RD7VL.js +0 -3
  429. package/dist/chunk-ZKX2FRS6.js +0 -15
  430. package/dist/cli-context-3SNLDYBM.js +0 -3
  431. package/dist/cli-context-T3B7W6GG.js +0 -2
  432. package/dist/cli-program-YNOXO72B.js +0 -7
  433. package/dist/command-descriptors-6AOUKWW7.js +0 -346
  434. package/dist/command-descriptors-ZFKJSRUP.js +0 -344
  435. package/dist/direct-navigation-DP4LVMRX.js +0 -3
  436. package/dist/direct-navigation-FLUS3BT6.js +0 -2
  437. package/dist/invocation-command-descriptors-QT2JMY5J.js +0 -3
  438. package/dist/invocation-command-descriptors-YN4QJEAX.js +0 -2
  439. package/dist/output-continuation-command-2V2SL4TD.js +0 -2
  440. package/dist/output-continuation-command-65J5IP3O.js +0 -3
  441. package/dist/project-reindex-5JOKXAXT.js +0 -2
  442. package/dist/project-reindex-UQBIKO4M.js +0 -3
  443. package/docs/WINDOWS_SIDECAR_RELEASE.md +0 -424
  444. package/docs/schemas/windows-sidecar-provenance.schema.json +0 -137
  445. package/scripts/build-codebaseiq-windows.mjs +0 -197
  446. package/scripts/codebaseiq-windows-provenance.mjs +0 -364
  447. package/scripts/verify-codebaseiq-windows.mjs +0 -29
@@ -1,564 +0,0 @@
1
- #!/usr/bin/env node
2
- import{b as yt,c as bl}from"./chunk-XZEE23VG.js";import{C as Qf,E as Ns,N as yl,P as Zf,a as qf,b as Rr,c as Kf,f as Ms,s as As,t as Xf}from"./chunk-G6XFR4ZL.js";import{$ as Vn,A as Yi,Aa as bp,B as op,Ba as pe,C as sp,Ca as at,D as ye,Da as Er,Db as to,E as ap,Ea as Ks,Eb as Ys,Fa as Sp,Fb as $p,Ga as vp,Gb as jp,H as ae,Ha as Cp,Hb as Hp,I as te,Ia as Gs,J as cp,Ja as on,K as js,Ka as Jn,L as _t,La as sn,M as rn,Ma as xp,N as lp,Na as Rp,Oa as Ip,Pa as Cl,Q as oi,Qa as Ep,R as Hs,S as Ot,T as si,Ta as wp,U as up,Ua as Zi,Va as Lp,W as Xi,Wa as Yn,X as Ce,Xa as Dp,Y as Us,Z as $e,_ as Wn,a as Gn,aa as dp,ab as Pp,b as ke,ba as N,c as qt,ca as Y,d as Nt,da as Bt,e as In,ea as st,fa as _e,g as ep,ga as De,h as tp,ha as Xe,i as Sl,ia as ai,ib as Mp,j as np,ja as mp,jb as Tp,k as me,ka as fp,kb as Ws,l as _s,la as ci,lb as Xn,m as rp,ma as li,mb as Vs,n as ip,na as pp,nb as kp,oa as W,ob as Js,p as vl,pa as Ue,pb as Fp,q as Rt,qa as gp,r as Ji,ra as hp,rb as eo,s as Ye,sa as Qi,t as se,ta as zs,tb as xl,u as ie,ua as yp,ub as Rl,v as Os,va as Ke,vb as Il,w as Bs,wa as qs,wb as Qn,x as $s,xa as J,xb as Ap,y as Be,ya as wn,yb as Np,z as En,za as ui,zb as _p}from"./chunk-3JSXXYTZ.js";import{d as Bf,e as ml}from"./chunk-DO6WQD2T.js";import{Aa as Ir,Ba as ii,C as Ps,Ca as Yf,Da as Wi,Ea as Vi,Fa as Fs,H as tn,L as ri,U as nn,V as zf,Z as Ne,da as Gf,ea as O,f as $f,g as Ds,ga as Ts,h as ht,i as Ft,ia as pl,k as Rn,ka as ks,l as xr,la as gl,ma as it,na as ot,oa as At,pa as Wf,qa as Vf,u as jf,v as Hf,w as fl,y as Uf,ya as Jf,za as hl}from"./chunk-2X7V4HS4.js";import{A as Kn,C as kt,b as ll,c as ul,h as _f,i as qn,j as Of,k as Cr,l as Zr,o as ei,p as en,q as dt,u as dl,v as ti,w as ni,x as xn}from"./chunk-SNNWPCN7.js";import{c as Op,e as Bp,f as Kt}from"./chunk-B2OB55RR.js";function Xs(e){return e+1}function qE(e,t){return`${Xs(e)}-${Xs(t)}`}function El(e,t,n){return`${yt(e)}:${qE(t,n)}`}function K5(e,t=180){let n=yt(e).replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var wl={empty(e){console.log(yt(e))},list(e,t){for(let n of e)console.log(yt(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(yt(o)),r=o),console.log(yt(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 ${yt(n.title)} \u2550\u2550\u2550`),n.explanation!==void 0&&console.log(yt(n.explanation));for(let r of n.rows)console.log(yt(r))}},table(e,t,n){console.log(` ${e.map(yt).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(yt(i))}};import{AsyncLocalStorage as KE}from"async_hooks";import{createHash as Dl}from"crypto";import{existsSync as GE,mkdirSync as WE}from"fs";import{tmpdir as VE}from"os";import{isAbsolute as JE,join as qp,resolve as Kp}from"path";var Ll=2,YE="CODEBASEIQ_SESSION",Up="CODEBASEIQ_SESSION_DIR",XE=128,Zn=new KE;function Gp(e,t){let n=e.sessionEnabled===!1||e.json?void 0:dw(),r={enabled:n!==void 0,reemit:e.reemit===!0,command:e.command,projectRoot:Kp(e.cwd),sessionIdentity:n,staged:[],stagedEvidence:[],finalized:!1};return Zn.run(r,t)}function nY(e){let t=Zn.getStore();!t||t.finalized||(t.generationIdentity=e)}function rY(){return Zn.getStore()?.staged.length??0}function iY(e){let t=Zn.getStore();!t||e<0||e>t.staged.length||(t.staged.length=e)}function Pl(e){let t=Zn.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=sw(t.staged).map(s=>({...s,ordinal:r,command:t.command})),o=cw(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(),nn(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 oY(e){let t=e.source.split(`
3
- `);if(t.length===0)return"";let n=QE(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=El(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(`
4
- `)}let c=e.headerSuffix??"",l=s.lines.map((u,d)=>{let m=s.startLine+d,f=e.showFocusMarker===!1?"":o.has(m)?">":" ",p=e.lineNumberWidth??5;return`${i}${f}${String(Xs(m)).padStart(p)} ${u}`});return[`${r}${a}${c}`,...e.blankAfterHeader?[""]:[],...e.afterHeader??[],...l].join(`
5
- `)}).join(`
6
- `)}function sY(e){let t=Zn.getStore();if(!t||!t.enabled)return e.content;let n=Ml(t);if(!n)return e.content;let r=Wp(e.content),i=Qs(n.ledger.evidence,o=>o.kind===e.kind&&o.identity===e.identity&&o.contentHash===r);if(i&&!t.reemit){let o=e.label?`; ${zp(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:mw(e.kind,e.identity,r),...e.label?{label:zp(e.label)}:{}}),e.content}function aY(e=!1){let t=Zn.getStore();if(!t?.enabled)return{enabled:!1,reason:"No explicit CODEBASEIQ_SESSION is active; source packets render independently.",uniqueLines:0,evidenceItems:0,emissions:0,rows:[]};let n=Ml(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{nn(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 p=c.slice(0,8).map(h=>El(h.relativePath,h.startLine,h.endLine)).join(", "),g=c.length>8?`, ... ${c.length-8} more range(s)`:"";return` #${a} ${u}: ${p}${g}`})();if(l.length===0)return d;let m=l.slice(0,8).map(p=>`${p.receiptId} ${p.kind}${p.label?` ${p.label}`:""}`).join(", "),f=l.length>8?`, ... ${l.length-8} more item(s)`:"";return d?`${d}
7
- evidence: ${m}${f}`:` #${a} ${u}: ${m}${f}`});return{enabled:!0,uniqueLines:lw(n.ledger.ranges),evidenceItems:n.ledger.evidence.length,emissions:new Set([...r.keys(),...i.keys()]).size,rows:s}}function QE(e,t,n,r,i){let o=Zn.getStore(),s=t+n.length-1;if(!o)return[{kind:"source",startLine:t,endLine:s,lines:[...n]}];let c=(o.enabled?Ml(o):null)?.ledger.ranges??[],l=n.map(Wp),u=i==="exact-unit"&&!o.reemit?Qs(c,h=>h.policy==="exact-unit"&&h.relativePath===e&&h.startLine===t&&h.endLine===s&&h.ownerSymbol===r&&fw(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?ew(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)=>ZE(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 p=[],g=0;for(;g<n.length;){let h=m[g],b=g;for(;b+1<n.length&&tw(h,m[b+1]);)b+=1;let S=t+g,y=t+b;p.push({kind:"covered",startLine:S,endLine:y,ordinal:h.ordinal,command:h.command}),g=b+1}return p}function ZE(e,t,n,r){let i=Qs(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 ew(e,t,n,r,i){let o=Qs(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 tw(e,t){return!e||!t?e===t:e.ordinal===t.ordinal&&e.command===t.command}function Ml(e){if(e.state!==void 0)return e.state;if(!e.sessionIdentity||!e.generationIdentity)return e.state=null,null;try{let t=uw();WE(t,{recursive:!0,mode:448});let n=Dl("sha256").update(e.projectRoot).update("\0").update(e.generationIdentity).update("\0").update(e.sessionIdentity).digest("hex"),r=qp(t,`${n}.json`),i=ri(`${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=GE(r)?rw(JSON.parse(dt(r,"source emission session ledger")),{projectRoot:e.projectRoot,generationIdentity:e.generationIdentity,sessionIdentity:e.sessionIdentity}):nw(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 nw(e){return{version:Ll,projectRoot:e.projectRoot,generationIdentity:e.generationIdentity,sessionIdentity:e.sessionIdentity,nextOrdinal:1,updatedAt:new Date().toISOString(),ranges:[],evidence:[]}}function rw(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:Ll,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!==Ll||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(iw)||!Array.isArray(n.evidence)||!n.evidence.every(ow))throw new Error("Invalid source emission ledger.");return n}function iw(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(Vp)&&(t.ownerSymbol===void 0||typeof t.ownerSymbol=="string")}function ow(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"&&Vp(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 sw(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&&aw(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 aw(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 cw(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 lw(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 uw(){let e=process.env[Up];if(!e)return qp(VE(),`codebaseiq-source-sessions-${process.getuid?.()??"user"}`);if(!JE(e))throw new Error(`${Up} must be an absolute path.`);return Kp(e)}function dw(){let e=process.env[YE]?.trim();if(e&&!(e.length>XE||!/^[A-Za-z0-9._:-]+$/.test(e)))return`explicit:${e}`}function mw(e,t,n){return`ev-${Dl("sha256").update(e).update("\0").update(t).update("\0").update(n).digest("hex").slice(0,12)}`}function zp(e){let t=e.replace(/[\r\n\t]+/gu," ").replace(/\s+/gu," ").trim();return t.length<=160?t:`${t.slice(0,157)}...`}function Wp(e){return Dl("sha256").update(e).digest("hex")}function fw(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function Qs(e,t){for(let n=e.length-1;n>=0;n-=1){let r=e[n];if(t(r))return r}}function Vp(e){return typeof e=="string"&&/^[0-9a-f]{64}$/u.test(e)}import{createHash as pw}from"crypto";import{existsSync as kl,mkdirSync as gw,rmSync as hw}from"fs";import{tmpdir as yw}from"os";import{isAbsolute as bw,join as Yp,resolve as Zs}from"path";var Xp=1,Sw="CODEBASEIQ_SESSION",Jp="CODEBASEIQ_SESSION_DIR",vw=128,Qp=8,Zp=32768,ea=new Map;function hY(e,t,n=!0){if(!n)return;let r=ta();if(!r)return;let i=Ol(e),o=t.map(a=>a.trim()).filter(a=>a.startsWith("codebaseiq system-map ")&&a.length<=Zp).slice(0,Qp),s=eg(i,r);o.length===0?ea.delete(s):ea.set(s,o)}function Fl(e,t,n,r=!0,i){if(!r||e!=="anchors"&&e!=="system-map")return;let o=ta();if(!o)return;let s=Ol(t),a=_l(s,o);if(e==="system-map"){n?hw(a,{force:!0}):kl(a)&&i&&Tl(a,()=>{let c=Nl(a,s,o);c&&nn(a,{...c,pendingMapContinuation:i,mapExecution:void 0,updatedAt:new Date().toISOString()},{spacing:2,trailingNewline:!0})});return}Tl(a,()=>{let c=Cw(s,o),l={version:Xp,projectRoot:s,sessionIdentity:o,mapRequired:!0,...c.length>0?{recommendedMapCommands:c}:{},updatedAt:new Date().toISOString()};nn(a,l,{spacing:2,trailingNewline:!0})})}function Al(e,t=!0){if(!t)return;let n=ta();if(!n)return;let r=Ol(e),i=_l(r,n);kl(i)&&Tl(i,()=>{let o=Nl(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(`
8
- `));if(o.mapExecution&&xw(o.mapExecution.processId))throw new Error(["NAVIGATION MAP ALREADY RUNNING","A selected system map is already computing in this CODEBASEIQ_SESSION.","Poll the existing terminal execution. Do not launch a duplicate map or inspect in parallel."].join(`
9
- `));nn(i,{...o,mapExecution:{processId:process.pid,startedAt:new Date().toISOString()},updatedAt:new Date().toISOString()},{spacing:2,trailingNewline:!0})}})}function yY(e,t,n=!0){if(!n)return;let r=ta();if(!r)return;let i=_l(Zs(e),r);if(!kl(i))return;let o=Nl(i,Zs(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 CODEBASEIQ_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(`
10
- `))}function Nl(e,t,n){try{let r=JSON.parse(dt(e,"navigation session state"));return r.version===Xp&&r.projectRoot===t&&r.sessionIdentity===n&&r.mapRequired===!0&&(r.recommendedMapCommands===void 0||Array.isArray(r.recommendedMapCommands)&&r.recommendedMapCommands.length<=Qp&&r.recommendedMapCommands.every(i=>typeof i=="string"&&i.startsWith("codebaseiq system-map ")&&i.length<=Zp))&&(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 Cw(e,t){let n=eg(e,t),r=ea.get(n)??[];return ea.delete(n),r}function eg(e,t){return`${e}\0${t}`}function xw(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function _l(e,t){let n=Rw();gw(n,{recursive:!0,mode:448});let r=pw("sha256").update(e).update("\0").update(t).digest("hex");return Yp(n,`navigation-${r}.json`)}function Rw(){let e=process.env[Jp];if(!e)return Yp(yw(),`codebaseiq-source-sessions-${process.getuid?.()??"user"}`);if(!bw(e))throw new Error(`${Jp} must be an absolute path.`);return Zs(e)}function Ol(e){let t=process.env.CODEBASEIQ_PROJECT_ROOT?.trim();return Zs(t||e)}function ta(){let e=process.env[Sw]?.trim();if(e&&!(e.length>vw||!/^[A-Za-z0-9._:-]+$/u.test(e)))return`explicit:${e}`}function Tl(e,t){let n=ri(`${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()}}import{createHash as ra,randomBytes as Ew}from"crypto";import{chmodSync as ww,closeSync as $l,fstatSync as ng,lstatSync as Lw,mkdirSync as Dw,openSync as sg,readSync as Pw,readdirSync as ag,renameSync as Mw,rmSync as cg,statSync as Tw,writeSync as kw}from"fs";import{tmpdir as Fw}from"os";import{join as ro}from"path";import{StringDecoder as lg}from"string_decoder";import{InvalidArgumentError as rg}from"commander";var Iw=/^[A-Za-z0-9_@%+=:,./-]+$/u;function tg(e,t={}){return t.omitSafeQuotes&&Iw.test(e)?e:(t.platform??process.platform)==="win32"?`"${e.replaceAll("%","%%").replaceAll('"','\\"')}"`:`'${e.replaceAll("'",`'"'"'`)}'`}var Aw="codebaseiq-output-page",Nw=1,_w="continue",na=32e3,di=256,mi=1e5,ia=4096,jl=32e6,Ow=64*1024*1024,Bw=256*1024*1024,$w=32,Hl=32768,ug=3600*1e3,dg=3;function mg(){return ro(Fw(),`codebaseiq-output-pages-${typeof process.getuid=="function"?process.getuid():"user"}`)}var Kl=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u,fg=/^[A-Za-z0-9_][A-Za-z0-9_-]{11}$/u,jw=/^4\.([A-Za-z0-9_-]{22})\.([0-9a-z]{1,10})$/u,Hw=/^([A-Za-z0-9_][A-Za-z0-9_-]{11})(?:\.([0-9a-z]{1,10}))?$/u,pg=1,Uw="quota.lock",zw=2e3,qw=5,ig=1024*1024,Kw=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)),Bl,Gw=Object.freeze({maxSnapshotBytes:Ow,maxAggregateBytes:Bw,maxSnapshotCount:$w});var gg={writeStdout:e=>{process.stdout.write(e)},writeStderr:e=>{process.stderr.write(e)}};async function Ww(e,t,n=gg){return Gp({command:e.command,cwd:e.cwd,argv:e.argv,json:e.json,sessionEnabled:e.sourceSession,reemit:e.reemitSource},async()=>{try{await Vw(e,t,n)}finally{Pl(!1)}})}async function Vw(e,t,n){let r=e.pageSize??na,i=e.snapshotRoot??mg(),o=nL(e.snapshotLimits),s=e.maxOutputCharacters??jl;if(!Number.isSafeInteger(s)||s<=0)throw new Error("Output character safety limit must be a positive integer.");let a=Math.min(s,jl);if(hg(r),e.cursor!==void 0&&e.cursor.length>ia)throw new Error(`Output cursor exceeds the ${ia}-character limit. Run the command again without --output-cursor.`);if(e.json&&e.pageSize===void 0&&e.cursor===void 0){e.command==="system-map"&&Al(e.cwd,e.sourceSession!==!1),await Jw(e,t,n);return}let c=Ig(e.argv),l=wg(e.invocationPrefix),u=Rg(e.command,e.cwd,l,c),d=e.cursor===void 0?void 0:fL(e.cursor,u);e.command==="system-map"&&!d&&Al(e.cwd,e.sourceSession!==!1);let m=d?.snapshotId,f;if(d)try{f=Qw(d,u,r,a,i,e.onSnapshotRead)}catch(S){let y=S instanceof Error?S.message:String(S);throw new Error(`${y} Restart with: ${Eg(l,c,r)}`,{cause:S})}else{let S=new zl(u,l,e.command,e.cwd,c,r,a,i,o,!e.json),y=Yw(v=>S.write(v)),E=!1;try{await t(),E=!0}finally{y(),E||S.abort()}let I;try{I=S.complete()}catch(v){throw S.abort(),v}m=I.snapshotId,f={content:I.content,offset:0,pageIndex:0,pageCount:I.pageCount,totalCharacters:I.totalCharacters,outputHash:I.outputHash}}let p=f.offset+f.content.length,g=f.pageIndex+1>=f.pageCount,h=g?void 0:dL({invocationPrefix:l,nextPageIndex:f.pageIndex+1,snapshotId:cL(m)});if(Fl(e.command,e.cwd,g,e.sourceSession!==!1,h?.command),f.offset===0&&g&&e.cursor===void 0){n.writeStdout(f.content),Pl(!0),m&&wr(m,i);return}let b={kind:Aw,schemaVersion:Nw,producer:{name:"codebaseiq",version:e.producerVersion},command:e.command,contentType:e.json?"application/json":"text/plain",agentInstruction:h?"INCOMPLETE EVIDENCE: do not draw conclusions or report completion from this partial page. Run page.continuation.command exactly, then repeat until page.complete is true.":"OUTPUT COMPLETE: all rendered characters have been retrieved. Evaluate the command result's own coverage separately.",page:h?{offset:f.offset,returnedCharacters:f.content.length,totalCharacters:f.totalCharacters,omittedCharacters:f.totalCharacters-f.content.length,remainingCharacters:f.totalCharacters-p,complete:!1,outputHash:f.outputHash,continuation:h}:{offset:f.offset,returnedCharacters:f.content.length,totalCharacters:f.totalCharacters,omittedCharacters:f.totalCharacters-f.content.length,remainingCharacters:f.totalCharacters-p,complete:!0,outputHash:f.outputHash},content:f.content};if(e.json){n.writeStdout(`${JSON.stringify(b)}
11
- `),g&&m&&wr(m,i);return}n.writeStdout(SL(b)),g&&m&&wr(m,i)}async function NY(e,t,n=mg(),r=gg){if(e.length>ia)throw new Error(`Output cursor exceeds the ${ia}-character limit.`);let i=xg(e);if(!i)throw new Error("Invalid output cursor. Run the original command again.");let o=bg(i.snapshotId,n);await Ww({command:o.command,producerVersion:t,invocationPrefix:o.invocationPrefix,argv:[...o.argv,"--output-page-size",String(o.pageSize),"--output-cursor",e],cwd:o.cwd,json:o.argv.some(s=>s==="--json"||s.startsWith("--json=")),sourceSession:!o.argv.some(s=>s==="--no-session"),pageSize:o.pageSize,cursor:e,snapshotRoot:n},()=>{throw new Error("Output continuation attempted to rerun the original command.")},r)}function _Y(e){if(!/^\d+$/u.test(e))throw new rg(`Output page size must be an integer from ${di} through ${mi}.`);let t=Number(e);try{hg(t)}catch{throw new rg(`Output page size must be an integer from ${di} through ${mi}.`)}return t}function hg(e){if(!Number.isSafeInteger(e)||e<di||e>mi)throw new Error(`Output page size must be an integer from ${di} through ${mi}.`)}async function Jw(e,t,n){let r=new Ul(na,e.maxOutputCharacters??jl),i=process.stdout.write,o=!1,s=`${yt(`codebaseiq: JSON output exceeds ${na} characters and may be truncated by the client. Do not use possibly partial client output as evidence. Read every page with: ${Eg(wg(e.invocationPrefix),Ig(e.argv),na)}`)}
12
- `;process.stdout.write=((a,c,l)=>{let u=r.push(a,c);return u!==void 0&&(o||(o=!0,n.writeStderr(s)),i.call(process.stdout,u)),yg(c,l),!0});try{await t();let a=r.finish();a.crossedPageBoundary&&!o&&(o=!0,n.writeStderr(s)),a.bytes.length>0&&i.call(process.stdout,a.bytes),o&&n.writeStderr(s),Fl(e.command,e.cwd,!0,e.sourceSession!==!1)}finally{process.stdout.write=i}}function Yw(e){let t=process.stdout.write;return process.stdout.write=((n,r,i)=>{let o=Xw(n,r);return e(o),yg(r,i),!0}),()=>{process.stdout.write=t}}function Xw(e,t){return typeof e=="string"?Buffer.from(e,typeof t=="string"?t:"utf8"):Buffer.from(e)}function yg(e,t){let n=typeof e=="function"?e:t;typeof n=="function"&&n()}var Ul=class{constructor(t,n){this.limit=t;this.maxOutputCharacters=n}limit;maxOutputCharacters;decoder=new lg("utf8");chunks=[];overflowed=!1;totalCharacters=0;push(t,n){let r=typeof t=="string"?Buffer.from(t,typeof n=="string"?n:"utf8"):Buffer.from(t);if(this.addCharacters(this.decoder.write(r)),this.overflowed)return r;if(this.chunks.push(r),this.totalCharacters<=this.limit)return;this.overflowed=!0;let i=Buffer.concat(this.chunks);return this.chunks.length=0,i}finish(){this.addCharacters(this.decoder.end());let t=this.totalCharacters>this.limit,n=Buffer.concat(this.chunks);return this.chunks.length=0,{bytes:n,crossedPageBoundary:t}}addCharacters(t){if(this.totalCharacters+=t.length,!Number.isSafeInteger(this.totalCharacters)||this.totalCharacters>this.maxOutputCharacters)throw new Error(`Command output exceeds the ${this.maxOutputCharacters}-character safety limit. Narrow the query before retrying.`)}},zl=class{constructor(t,n,r,i,o,s,a,c,l,u){this.invocationHash=t;this.invocationPrefix=n;this.command=r;this.cwd=i;this.argv=o;this.pageSize=s;this.maxOutputCharacters=a;this.snapshotRoot=c;this.limits=l;this.preferLineBoundaries=u;Gl(c);do this.snapshotId=Ew(9).toString("base64url");while(this.snapshotId.startsWith("-"));this.temporaryPath=Ln(c,this.snapshotId,"tmp")}invocationHash;invocationPrefix;command;cwd;argv;pageSize;maxOutputCharacters;snapshotRoot;limits;preferLineBoundaries;snapshotId;temporaryPath;decoder=new lg("utf8");hash=ra("sha256");pages=[];descriptor=null;pending="";firstPageContent="";totalCharacters=0;pageCharacterOffset=0;byteLength=0;reservedBytes=0;opened=!1;finished=!1;write(t){if(this.finished)throw new Error("Output snapshot writer is closed.");this.appendDecoded(this.decoder.write(t))}complete(){if(this.finished)throw new Error("Output snapshot writer is closed.");if(this.appendDecoded(this.decoder.end()),this.finished=!0,!this.opened){let i=this.pending,o=Buffer.from(i);return this.assertWithinByteLimit(o.length),this.hash.update(o),this.pending="",{content:i,totalCharacters:this.totalCharacters,outputHash:this.hash.digest("hex"),pageCount:1}}if((this.pending.length>0||this.pages.length===0)&&(this.flushPage(this.pending),this.pending=""),this.descriptor===null)throw new Error("Output snapshot writer is not open.");$l(this.descriptor),this.descriptor=null;let t=this.hash.digest("hex"),n=Ln(this.snapshotRoot,this.snapshotId,"output"),r=Ln(this.snapshotRoot,this.snapshotId,"json");try{Mw(this.temporaryPath,n);let i={version:dg,snapshotId:this.snapshotId,invocationHash:this.invocationHash,invocationPrefix:[...this.invocationPrefix],command:this.command,cwd:this.cwd,argv:[...this.argv],outputHash:t,pageSize:this.pageSize,pages:this.pages,totalCharacters:this.totalCharacters,byteLength:this.byteLength,createdAtMs:Date.now()};return nn(r,i),og(this.snapshotRoot,this.snapshotId,this.byteLength,"complete",this.limits),this.reservedBytes=this.byteLength,{content:this.firstPageContent,totalCharacters:this.totalCharacters,outputHash:t,pageCount:this.pages.length,snapshotId:this.snapshotId}}catch(i){throw wr(this.snapshotId,this.snapshotRoot),i}}abort(){this.descriptor!==null&&($l(this.descriptor),this.descriptor=null),this.finished=!0,wr(this.snapshotId,this.snapshotRoot)}appendDecoded(t){if(t.length===0)return;let n=this.totalCharacters+t.length;if(!Number.isSafeInteger(n)||n>this.maxOutputCharacters)throw new Error(`Command output exceeds the ${this.maxOutputCharacters}-character safety limit. Narrow the query before retrying.`);for(this.totalCharacters=n,this.pending+=t,this.assertWithinByteLimit(this.byteLength+Buffer.byteLength(this.pending));this.pending.length>this.pageSize;){this.open();let r=uL(this.pending,this.pageSize,this.preferLineBoundaries),i=this.pending.slice(0,r);this.pending=this.pending.slice(r),this.flushPage(i)}}open(){if(!this.opened){rL(this.snapshotRoot,this.snapshotId,0,this.limits);try{this.descriptor=sg(this.temporaryPath,"wx",384),this.opened=!0}catch(t){throw iL(this.snapshotRoot,this.snapshotId),t}}}flushPage(t){if(this.descriptor===null)throw new Error("Output snapshot writer is not open.");if(this.pages.length>=Hl)throw new Error(`Command output requires more than ${Hl} snapshot pages. Retry with a larger --output-page-size or narrow the query.`);let n=Buffer.from(t),r=this.byteLength+n.length;if(this.assertWithinByteLimit(r),r>this.reservedBytes){let s=Math.min(this.limits.maxSnapshotBytes,Math.ceil(r/ig)*ig);og(this.snapshotRoot,this.snapshotId,s,"active",this.limits),this.reservedBytes=s}let i=0;for(;i<n.length;){let s=kw(this.descriptor,n,i,n.length-i);if(s<=0)throw new Error("Output snapshot write made no progress.");i+=s}let o={characterOffset:this.pageCharacterOffset,characterLength:t.length,byteOffset:this.byteLength,byteLength:n.length,hash:ra("sha256").update(n).digest("hex")};this.pages.length===0&&(this.firstPageContent=t),this.pages.push(o),this.hash.update(n),this.pageCharacterOffset+=t.length,this.byteLength=r}assertWithinByteLimit(t){if(!Number.isSafeInteger(t)||t>this.limits.maxSnapshotBytes)throw new Error(`Command output exceeds the ${this.limits.maxSnapshotBytes}-byte snapshot limit. Narrow the query before retrying.`)}};function Qw(e,t,n,r,i,o){Gl(i);let s=bg(e.snapshotId,i);if(s.invocationHash!==t)throw new Error("This output cursor belongs to a different command, working directory, or argument set. Run again without --output-cursor.");if(s.snapshotId!==e.snapshotId||e.version===3&&(s.invocationHash!==e.invocationHash||s.outputHash!==e.outputHash))throw new Error("Output snapshot identity does not match this cursor.");if(s.pageSize!==n||e.version===3&&e.pageSize!==n)throw new Error(`Output page size changed after this cursor was issued; use ${s.pageSize}.`);let a=s.pages[e.pageIndex];if(!a)throw new Error("Output cursor points past the current result.");if(s.totalCharacters>r)throw new Error(`Output snapshot exceeds the ${r}-character safety limit.`);if(Date.now()-s.createdAtMs>ug)throw wr(e.snapshotId,i),new Error("Output snapshot expired before all pages were read.");let c=Ln(i,e.snapshotId,"output"),l=sg(c,"r");try{let u=ng(l);if(!u.isFile()||u.size!==s.byteLength)throw new Error("Output snapshot size or type changed.");let d=Buffer.allocUnsafe(a.byteLength),m=0;for(;m<d.length;){let g=Pw(l,d,m,d.length-m,a.byteOffset+m);if(g===0)break;m+=g,o?.(g)}let f=ng(l);if(f.dev!==u.dev||f.ino!==u.ino||f.size!==u.size||m!==a.byteLength)throw new Error("Output snapshot changed while it was being read.");if(ra("sha256").update(d).digest("hex")!==a.hash)throw new Error("Output snapshot page no longer matches its metadata.");let p=d.toString("utf8");if(p.length!==a.characterLength)throw new Error("Output snapshot page character count changed.");return{content:p,offset:a.characterOffset,pageIndex:e.pageIndex,pageCount:s.pages.length,totalCharacters:s.totalCharacters,outputHash:s.outputHash}}catch(u){throw wr(e.snapshotId,i),u}finally{$l(l)}}function bg(e,t){if(!er(e))throw new Error("Output snapshot identifier is invalid.");let n;try{n=JSON.parse(dt(Ln(t,e,"json"),"output snapshot metadata"))}catch(r){throw new Error("Output snapshot is unavailable.",{cause:r})}if(!Zw(n))throw new Error("Output snapshot metadata is invalid.");return n}function Zw(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===dg&&typeof t.snapshotId=="string"&&er(t.snapshotId)&&no(t.invocationHash)&&Lg(t.invocationPrefix)&&typeof t.command=="string"&&t.command.length>0&&t.command.length<=256&&typeof t.cwd=="string"&&t.cwd.length>0&&t.cwd.length<=8192&&bL(t.argv)&&Rg(t.command,t.cwd,t.invocationPrefix,t.argv)===t.invocationHash&&no(t.outputHash)&&Number.isSafeInteger(t.pageSize)&&(t.pageSize??0)>=di&&(t.pageSize??0)<=mi&&Array.isArray(t.pages)&&t.pages.length>1&&t.pages.length<=Hl&&t.pages.every(eL)&&tL(t.pages)&&Number.isSafeInteger(t.totalCharacters)&&(t.totalCharacters??-1)>=0&&t.pages.reduce((n,r)=>n+r.characterLength,0)===t.totalCharacters&&Number.isSafeInteger(t.byteLength)&&(t.byteLength??-1)>=0&&t.pages.reduce((n,r)=>n+r.byteLength,0)===t.byteLength&&Number.isSafeInteger(t.createdAtMs)&&(t.createdAtMs??-1)>=0}function eL(e){if(!e||typeof e!="object")return!1;let t=e;return Number.isSafeInteger(t.characterOffset)&&(t.characterOffset??-1)>=0&&Number.isSafeInteger(t.characterLength)&&(t.characterLength??0)>0&&Number.isSafeInteger(t.byteOffset)&&(t.byteOffset??-1)>=0&&Number.isSafeInteger(t.byteLength)&&(t.byteLength??0)>0&&no(t.hash)}function tL(e){let t=0,n=0;for(let r of e){if(r.characterOffset!==t||r.byteOffset!==n)return!1;t+=r.characterLength,n+=r.byteLength}return!0}function Gl(e){Dw(e,{recursive:!0,mode:448});let t=Lw(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Output snapshot root is not a private directory: ${e}`);if(typeof process.getuid=="function"&&t.uid!==process.getuid())throw new Error(`Output snapshot root is not owned by the current user: ${e}`);process.platform!=="win32"&&ww(e,448)}function nL(e){let t={...Gw,...e};for(let[n,r]of Object.entries(t))if(!Number.isSafeInteger(r)||r<=0)throw new Error(`Output snapshot ${n} must be a positive integer.`);if(t.maxSnapshotBytes>t.maxAggregateBytes)throw new Error("Output snapshot maxSnapshotBytes cannot exceed maxAggregateBytes.");return t}function rL(e,t,n,r){oa(e,()=>{sL(e),Sg(e,t,n,"active",r)})}function og(e,t,n,r,i){if(!Number.isSafeInteger(n)||n<0||n>i.maxSnapshotBytes)throw new Error(`Command output exceeds the ${i.maxSnapshotBytes}-byte snapshot limit.`);oa(e,()=>{Sg(e,t,n,r,i)})}function Sg(e,t,n,r,i){if(!Number.isSafeInteger(n)||n<0||n>i.maxSnapshotBytes)throw new Error(`Command output exceeds the ${i.maxSnapshotBytes}-byte snapshot limit.`);let o=oL(e),s=o.find(d=>d.snapshotId===t),a=o.reduce((d,m)=>d+m.reservedBytes,0)-(s?.reservedBytes??0)+n,c=o.length+(s?0:1);if(c>i.maxSnapshotCount||a>i.maxAggregateBytes)throw new Error(`Output snapshot capacity is full (${c}/${i.maxSnapshotCount} snapshots, ${a}/${i.maxAggregateBytes} bytes). Narrow the query or finish an existing pagination sequence before retrying.`);let l=Date.now(),u={version:pg,snapshotId:t,pid:process.pid,...ql()?{processIdentity:ql()}:{},reservedBytes:n,state:r,createdAtMs:s?.createdAtMs??l,updatedAtMs:l};nn(Ln(e,t,"reserve"),u)}function iL(e,t){oa(e,()=>{cg(Ln(e,t,"reserve"),{force:!0})})}function oL(e){let t=[];for(let n of ag(e,{withFileTypes:!0})){if(!n.isFile()||!n.name.endsWith(".reserve"))continue;let r=n.name.slice(0,-8);if(er(r))try{let i=JSON.parse(dt(ro(e,n.name),"output snapshot reservation"));if(!vg(i)||i.snapshotId!==r)throw new Error("reservation identity is invalid");t.push(i)}catch(i){throw new Error(`Output snapshot reservation ${n.name} is invalid; retry after its owning process or snapshot expires.`,{cause:i})}}return t}function vg(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===pg&&typeof t.snapshotId=="string"&&er(t.snapshotId)&&Number.isSafeInteger(t.pid)&&(t.pid??0)>0&&(t.processIdentity===void 0||ti(t.processIdentity)!==null&&t.processIdentity.pid===t.pid)&&Number.isSafeInteger(t.reservedBytes)&&(t.reservedBytes??-1)>=0&&(t.state==="active"||t.state==="complete")&&Number.isSafeInteger(t.createdAtMs)&&Number.isSafeInteger(t.updatedAtMs)}function sL(e){let t=Date.now();for(let n of ag(e,{withFileTypes:!0})){if(!n.isFile()||!n.name.endsWith(".reserve"))continue;let r=n.name.slice(0,-8);if(!er(r))continue;let i=null;try{let c=JSON.parse(dt(ro(e,n.name),"output snapshot reservation"));i=vg(c)?c:null}catch{i=null}let o=aL(Ln(e,r,"json")),s=i?.state==="active"&&qn(i.pid)&&(i.processIdentity===void 0||(()=>{let c=xn(i.pid);return c!==null&&ni(i.processIdentity,c)})()),a=i?t-i.updatedAtMs>ug:!1;s||o&&!a||!o&&i&&!a&&i.state==="complete"||Cg(r,e)}}function aL(e){try{return Tw(e),!0}catch{return!1}}function oa(e,t){Gl(e);let n=ro(e,Uw),r=Date.now()+zw;for(;;){let i=ri(n,{kind:"output-snapshot-quota",processIdentity:ql()});if(i.kind==="acquired")try{return t()}finally{i.lock.release()}if(Date.now()>=r)throw new Error("Output snapshot quota is busy. Retry the command.");Atomics.wait(Kw,0,0,qw)}}function ql(){return Bl===void 0&&(Bl=xn(process.pid)),Bl}function wr(e,t){er(e)&&oa(t,()=>Cg(e,t))}function Cg(e,t){for(let n of["json","output","tmp","reserve"])cg(Ln(t,e,n),{force:!0})}function Ln(e,t,n){if(!er(t))throw new Error("Output snapshot identifier is invalid.");return ro(e,`${t}.${n}`)}function cL(e){if(!e)throw new Error("Incomplete output did not create a resumable snapshot.");return e}function lL(e){return e>=55296&&e<=56319}function uL(e,t,n){if(n){let r=e.lastIndexOf(`
13
- `,t-1);if(r>=0)return r+1}return lL(e.charCodeAt(t-1))?t-1:t}function dL(e){let t=mL({pageIndex:e.nextPageIndex,snapshotId:e.snapshotId});return{cursor:t,command:yL(e.invocationPrefix,t)}}function mL(e){return fg.test(e.snapshotId)?e.pageIndex===1?e.snapshotId:`${e.snapshotId}.${e.pageIndex.toString(36)}`:`4.${gL(e.snapshotId)}.${e.pageIndex.toString(36)}`}function fL(e,t){let n=xg(e);if(!n)throw new Error("Invalid output cursor. Run the command again without --output-cursor.");if(n.version===3&&n.invocationHash!==t)throw new Error("This output cursor belongs to a different command, working directory, or argument set. Run again without --output-cursor.");return n}function xg(e){let t=Hw.exec(e);if(t){let r=t[2]??"1",i=Number.parseInt(r,36);return Number.isSafeInteger(i)&&i>=1&&i.toString(36)===r?{version:4,pageIndex:i,snapshotId:t[1]}:null}let n=jw.exec(e);if(n){let r=hL(n[1]),i=Number.parseInt(n[2],36);return r&&Number.isSafeInteger(i)&&i>=1&&i.toString(36)===n[2]?{version:4,pageIndex:i,snapshotId:r}:null}try{let r=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return pL(r)?r:null}catch{return null}}function pL(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===3&&no(t.invocationHash)&&Number.isSafeInteger(t.pageIndex)&&(t.pageIndex??-1)>=1&&Number.isSafeInteger(t.pageSize)&&(t.pageSize??0)>=di&&(t.pageSize??0)<=mi&&no(t.outputHash)&&typeof t.snapshotId=="string"&&er(t.snapshotId)}function gL(e){if(!Kl.test(e))throw new Error("Output snapshot identifier is invalid.");return Buffer.from(e.replaceAll("-",""),"hex").toString("base64url")}function hL(e){let t=Buffer.from(e,"base64url");if(t.length!==16)return null;let n=t.toString("hex"),r=`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`;return Kl.test(r)?r:null}function er(e){return typeof e=="string"&&(fg.test(e)||Kl.test(e))}function no(e){return typeof e=="string"&&/^[a-f0-9]{64}$/u.test(e)}function Rg(e,t,n,r){return ra("sha256").update(JSON.stringify({command:e,cwd:t,invocationPrefix:n,argv:r})).digest("hex")}function Ig(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="--output-page-size"||r==="--output-cursor"){n+=1;continue}r.startsWith("--output-page-size=")||r.startsWith("--output-cursor=")||t.push(r)}return t}function Eg(e,t,n){return Dg([...e,...t,"--output-page-size",String(n)])}function yL(e,t){return Dg([...e,_w,t])}function wg(e){let t=e===void 0?["codebaseiq"]:[...e];if(!Lg(t))throw new Error("Output pagination invocation prefix must contain one to sixteen non-empty shell arguments.");return t}function Lg(e){return Array.isArray(e)&&e.length>0&&e.length<=16&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=2048&&!t.includes("\0")&&!t.includes("\r")&&!t.includes(`
14
- `))}function bL(e){return Array.isArray(e)&&e.length>0&&e.length<=256&&e.every(t=>typeof t=="string"&&t.length<=8192&&!t.includes("\0")&&!t.includes("\r")&&!t.includes(`
15
- `))}function Dg(e){return e.map(t=>tg(t,{omitSafeQuotes:!0})).join(" ")}function SL(e){let t=e.page.continuation,n=Math.max(e.page.offset,e.page.offset+e.page.returnedCharacters-1),r=`[codebaseiq output page: characters ${e.page.offset}-${n} of ${e.page.totalCharacters}]
16
- `,i=t?`
17
- [Incomplete: ${e.page.remainingCharacters} characters remain. Continue exactly:
18
- ${t.command}]
19
- `:`
20
- [codebaseiq transport complete; evaluate command coverage separately]
21
- `;return`${r}${e.content}${i}`}import{existsSync as vL}from"fs";import{isAbsolute as CL,join as xL}from"path";function mt(e,t){let n=Mg(e,t,{allowMultiple:!1})[0]?.relativePath;return n||Pg(e,t)}function Dn(e,t){return Mg(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function Pg(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=CL(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,i=xL(e.config.projectRoot,r);return vL(i)?r:null}function Mg(e,t,n){let r=_s(e,t,n);if(r.length===0){if(Pg(e,t))return[];let i=pe(e,t);return!i||e.isIgnored(i.relativePath)?[]:[{relativePath:i.relativePath,score:700}]}return r}function Tg(e,t){let n=Dn(e,t),r=zs(e,n,{sort:!0});if(r.length===0)return[];let i=r.map(a=>({symbol:a.symbol,shortName:a.shortName,startLine:a.startLine,endLine:a.endLine,signature:a.signature,children:[]})),o=new Map;for(let a of i)o.set(a.symbol,a);let s=[];for(let a=0;a<r.length;a++){let c=r[a],l=i[a];if(c.enclosingSymbol&&o.has(c.enclosingSymbol)){o.get(c.enclosingSymbol).children.push(l);continue}let u=null,d=1/0;for(let m of i)if(m!==l&&m.startLine<=l.startLine&&m.endLine>=l.endLine){if(m.startLine===l.startLine&&m.endLine===l.endLine&&!fp(m.symbol,l.symbol))continue;let p=m.endLine-m.startLine;p<d&&(d=p,u=m)}u?u.children.push(l):s.push(l)}return s}import{basename as MD,extname as ch}from"path";function It(e,t){let n=ie(e,t.relativePath);if(n.length===0)return!1;let r=Y(t.symbol);if(!r)return!1;let i=n.slice(Math.max(0,t.startLine-2),t.startLine+1).join(`
22
- `),o=Be(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:RL(n,r)}function RL(e,t){if(!t)return!1;let n=new RegExp(`^\\s*export\\s*\\{[^}\\n]*\\b${Be(t)}\\b`);return e.some(r=>n.test(r))}import{createHash as IL}from"crypto";import{TextDecoder as EL}from"util";var wL=new EL("utf-8",{fatal:!0});function Wl(e){return Wf(e.config.projectRoot)}function sa(e,t){let n=Rn(t),r;try{r=gl(e.config.projectRoot,n,{inputKind:"repository text file"})}catch(o){if(ot(o)||o instanceof pl)return null;throw o}let i=_g(r);return i===null?null:Fg(n,r,i,Ng(e),Ag(e))}function aa(e,t={}){let n=Wl(e).filter(u=>!t.scope||u.includes(t.scope)),r=Ng(e),i=Ag(e),o=[],s=[],a=[],c=[],l=0;for(let u of n){let d;try{d=gl(e.config.projectRoot,u,{inputKind:"repository text file"})}catch(f){if(f instanceof pl){c.push(u);continue}if(ot(f))continue;a.push(u);continue}let m=_g(d);if(m===null){s.push(u);continue}l+=d.byteLength,o.push(Fg(u,d,m,r,i))}return{files:o,candidateFiles:n.length,scannedBytes:l,skippedBinaryPaths:s,skippedUnreadablePaths:a,skippedOversizedPaths:c}}function Fg(e,t,n,r,i){let o=IL("sha256").update(t).digest("hex");return{relativePath:e,text:n,bytes:t.byteLength,freshness:{exactText:{state:"current",basis:"working-tree-read",sha256:o},semantic:LL(e,o,r,i)}}}function LL(e,t,n,r){if(!r.has(e))return{state:"unavailable",basis:"no-compiler-document"};let i=n.get(e);return i?{state:i===t?"aligned":"stale",basis:"indexed-input-fingerprint"}:{state:"unavailable",basis:"fingerprint-unavailable"}}function Ag(e){return new Set(e.all(`SELECT documents.relative_path FROM documents WHERE 1 = 1 ${e.pathExclusionsFor("documents")}`).map(t=>t.relative_path))}function Ng(e){let t=new Map;if(!e.generation.metadataRaw)return t;let n=Ps(e.generation.metadataRaw);if(n.kind!=="legacy"&&n.kind!=="supported")return t;let r=n.metadata.fingerprint;if(!kg(r)||!Array.isArray(r.files))return t;for(let i of r.files)!kg(i)||typeof i.path!="string"||typeof i.hash!="string"||t.set(i.path,i.hash);return t}function _g(e){if(e.includes(0))return null;try{return wL.decode(e)}catch{return null}}function kg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{SymbolInformation_Kind as Ie}from"@c4312/scip";var ca=new Map(Object.entries(Ie).filter(([e,t])=>Number.isInteger(Number(e))&&typeof t=="string").map(([e,t])=>[Number(e),t])),Og=new Map([...ca.entries()].map(([e,t])=>[t.toLowerCase(),e]));function io(e){return ca.get(e)??"Unknown"}function an(){return[Ie.Function,Ie.Method,Ie.Macro,Ie.Constructor,Ie.Getter,Ie.Setter,Ie.StaticMethod,Ie.SingletonMethod,Ie.AbstractMethod,Ie.ProtocolMethod,Ie.TraitMethod]}function Bg(){return[Ie.Class,Ie.Interface,Ie.Struct,Ie.Trait,Ie.Type,Ie.TypeAlias,Ie.Enum,Ie.Union,Ie.Protocol]}function i3(){return[Ie.Constant,Ie.Variable,Ie.Value,Ie.Field,Ie.Property,Ie.StaticDataMember,Ie.StaticField,Ie.StaticProperty,Ie.StaticVariable,Ie.EnumMember]}function la(e,t,n={}){return Lr(e,t,n).rows}function Lr(e,t,n={}){let r=oo(e,[t],{additive:n.additive,semantic:n.semantic,semanticEvidence:n.semanticEvidence}),i=n.callableOnly?(r.rows.get(t.symbolId)??[]).filter(o=>st(o.symbol)||o.source==="ast-callsite"):r.rows.get(t.symbolId)??[];return{rows:typeof n.limit=="number"?i.slice(0,n.limit):i,semanticIncomplete:r.incompleteSymbolIds.has(t.symbolId),semanticUnavailable:r.unavailableSymbolIds.has(t.symbolId)}}function ua(e,t,n){return Jl(e,t,n).rows}function Jl(e,t,n){let r=cn(e,[t],n);return{rows:r.rows.get(t.symbolId)??[],semanticIncomplete:r.incompleteSymbolIds.has(t.symbolId),semanticUnavailable:r.unavailableSymbolIds.has(t.symbolId)}}function jg(e,t,n){return cn(e,t,n).rows}function cn(e,t,n){let r=kL(e)?AL(e,t,{semantic:n.semantic!==!1,semanticEvidence:n.semanticEvidence}):FL(e,n.semanticEvidence,{semantic:n.semantic!==!1});return{rows:new Map(t.map(o=>[o.symbolId,typeof n.limit=="number"?(r.rows.get(o.symbolId)??[]).slice(0,n.limit):r.rows.get(o.symbolId)??[]])),incompleteSymbolIds:new Set(t.filter(o=>r.incompleteSymbolIds.has(o.symbolId)).map(o=>o.symbolId)),unavailableSymbolIds:new Set(t.filter(o=>r.unavailableSymbolIds.has(o.symbolId)).map(o=>o.symbolId))}}var DL=ke("caller-rows",{clearGroups:["whole-project"]}),PL=ke("caller-rows-non-semantic",{clearGroups:["whole-project"]}),ML=ke("targeted-caller-strategy",{clearGroups:["whole-project"]}),TL=2e4;function kL(e){return ML.get(e,()=>(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>TL)}function FL(e,t,n={}){return(n.semantic===!1?PL:DL).get(e,()=>{let i=Ue(e),o=oo(e,i,{semantic:n.semantic!==!1,semanticEvidence:t}),s=new Map;for(let l of i)s.set(l.symbol,l.symbolId);let a=new Map,c=new Map;for(let l of i){let u=o.rows.get(l.symbolId);if(!(!u||u.length===0))for(let d of u){let m=s.get(d.symbol);if(m===void 0||m===l.symbolId)continue;let f=a.get(m);f||(f=[],a.set(m,f),c.set(m,new Set));let p=`${l.symbol}|${l.relativePath}`;c.get(m).has(p)||(c.get(m).add(p),f.push({symbol:l.symbol,file:l.relativePath,source:"caller-map-inversion",callEvidence:d.source}))}}return{rows:a,incompleteSymbolIds:o.incompleteSymbolIds.size===0?new Set:new Set(i.map(l=>l.symbolId)),unavailableSymbolIds:o.unavailableSymbolIds.size===0?new Set:new Set(i.map(l=>l.symbolId))}})}function AL(e,t,n){let r=n.semantic&&n.semanticEvidence?t.flatMap(u=>{let d=NL(e,u);return d?[d]:[]}):[],i=new Map(r.map(u=>[u.symbolId,u])),o=n.semantic&&n.semanticEvidence?n.semanticEvidence.referenceEvidenceMap(e,r):{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set},s=Lp(e,t),a=new Map;for(let u of t){let d=[],m=new Set,f=g=>{if(g.symbol===u.symbol)return;let h=`${g.symbol}|${g.file}`;m.has(h)||(m.add(h),d.push(g))};for(let g of s.get(u.symbolId)??[])g.file!==u.relativePath&&f({symbol:g.enclosingSymbol??g.file,file:g.file,source:"resolved-reference"});let p=i.get(u.symbolId);if(p)for(let g of o.rows.get(p.symbolId)??[]){if(g.file===u.relativePath||e.isIgnored(g.file))continue;let h=Ke(W(e,g.file),g.line);f({symbol:h?.symbol??g.file,file:g.file,source:"semantic-reference"})}a.set(u.symbolId,d)}let c=new Set(o.incompleteSymbolIds),l=new Set(o.unavailableSymbolIds);if(n.semantic)for(let u of t)i.has(u.symbolId)||c.add(u.symbolId);return{rows:a,incompleteSymbolIds:c,unavailableSymbolIds:l}}function NL(e,t){let n=an().join(", "),r=Bg().join(", ");return e.get(`SELECT
23
- d.id AS documentId,
24
- gs.id AS symbolId,
25
- gs.symbol,
26
- d.relative_path AS relativePath,
27
- COALESCE(der.start_line, c.start_line) AS startLine,
28
- COALESCE(der.end_line, c.end_line) AS endLine,
29
- COALESCE(gs.display_name, '') AS leaf,
30
- NULL AS parentTypeName,
31
- CASE WHEN gs.kind IN (${n}) OR gs.symbol LIKE '%().' THEN 1 ELSE 0 END AS isFunctionLike,
32
- CASE WHEN gs.kind IN (${r}) THEN 1 ELSE 0 END AS isTypeLike,
33
- gs.kind AS kind,
34
- gs.documentation AS documentation,
35
- gs.enclosing_symbol AS enclosingSymbol
36
- FROM global_symbols gs
37
- LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
38
- LEFT JOIN chunks c ON c.document_id = der.document_id
39
- JOIN documents d ON d.id = COALESCE(der.document_id, c.document_id)
40
- WHERE gs.id = ?
41
- LIMIT 1`,t.symbolId)??null}function Yl(e,t,n={}){return oo(e,t,n).rows}function oo(e,t,n={}){if(t.length===0)return{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set};let r=n.additive??!1,i=[],o=[];for(let m of t)ye(m.relativePath)&&rn(e,m.relativePath)!==null?i.push(m):o.push(m);let s=new Map,a=new Map,c=m=>{for(let[f,p]of m){let g=s.get(f);g||(g=[],s.set(f,g));let h=a.get(f);h||(h=new Set,a.set(f,h));for(let b of p){let S=`${b.symbol}|${b.chunkId}`;h.has(S)||(h.add(S),g.push(b))}}};i.length>0&&c(_L(e,i));let l=new Set,u=new Set;if(n.semantic!==!1&&n.semanticEvidence){let m=n.semanticEvidence.calleeEvidenceMap(e,t);c(UL(m.rows));for(let f of m.incompleteSymbolIds)l.add(f);for(let f of m.unavailableSymbolIds)u.add(f)}else if(n.semantic!==!1)for(let m of t)u.add(m.symbolId);let d=r?t:o;return d.length>0&&c(jL(e,d)),{rows:s,incompleteSymbolIds:l,unavailableSymbolIds:u}}function _L(e,t){let n=new Map,r=OL(t,n),i=sn(e);for(let[o,s]of r){let a=rn(e,o);if(!a)continue;let c=yp(s);for(let l of a){let u=c.get(l.line);if(!u)continue;let d=BL(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 OL(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 BL(e,t,n,r){let i=on(t,n.get(r.calleeLeaf)??[]);if(i.length===0)return null;let o=$L(e,t,i,r.calleeQualifier);return o||Jn(e,t,i,r.memberAccess,r.calleeQualifier)}function $L(e,t,n,r){if(!r||ye(t)!=="clojure")return null;let o=Ce(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=>Ft(s,c.file));if(a)return a}return n.find(s=>/`([^`]+)`\//.exec(s.symbol)?.[1]===r)??null}function jL(e,t){if(t.length===0)return new Map;let r=Vl(t.map(f=>f.documentId)).flatMap(f=>e.all(`SELECT c.document_id, c.id AS chunk_id, c.start_line, c.end_line, m.symbol_id
42
- FROM mentions m
43
- JOIN chunks c ON m.chunk_id = c.id
44
- WHERE m.role != 1
45
- AND c.document_id IN (${f.map(()=>"?").join(",")})`,...f)),i=new Map;for(let f of r)i.has(f.document_id)||i.set(f.document_id,[]),i.get(f.document_id).push(f);let s=Vl(r.map(f=>f.symbol_id)).flatMap(f=>e.all(`SELECT gs.id AS symbol_id, gs.symbol,
46
- COALESCE(der.document_id, def_chunk.document_id) AS document_id
47
- FROM global_symbols gs
48
- LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
49
- LEFT JOIN (
50
- SELECT m.symbol_id, MIN(c.document_id) AS document_id
51
- FROM mentions m
52
- JOIN chunks c ON m.chunk_id = c.id
53
- WHERE m.role = 1
54
- AND m.symbol_id IN (${f.map(()=>"?").join(",")})
55
- GROUP BY m.symbol_id
56
- ) def_chunk ON def_chunk.symbol_id = gs.id
57
- WHERE gs.id IN (${f.map(()=>"?").join(",")})`,...f,...f)),a=Vl([...t.map(f=>f.documentId),...s.flatMap(f=>f.document_id===null?[]:[f.document_id])]),c=new Map(a.flatMap(f=>e.all(`SELECT id, relative_path FROM documents
58
- WHERE id IN (${f.map(()=>"?").join(",")})`,...f).map(p=>[p.id,p.relative_path]))),l=new Map;for(let f of s)l.has(f.symbol_id)||l.set(f.symbol_id,{symbol:f.symbol,file:f.document_id!==null?c.get(f.document_id)??"":""});let u=new Map,d=c,m=HL(t);for(let[f,p]of m){let h=[...i.get(f)??[]].sort((E,I)=>E.start_line-I.start_line||E.end_line-I.end_line),b=[...p].sort((E,I)=>E.startLine-I.startLine||E.endLine-I.endLine),S=new Set,y=0;for(let E of b){for(;y<h.length&&h[y].start_line<=E.endLine;)S.add(h[y]),y+=1;for(let L of S)L.end_line<E.startLine&&S.delete(L);let I=new Set,v=[],x=null,C=()=>{if(x)return x;let L=d.get(E.documentId)??"",w=new Set;if(L){let R=bp(e,L),P=Math.max(0,E.startLine),_=Math.min(R.length-1,E.endLine);for(let D=P;D<=_;D+=1)for(let M of R[D])w.add(M)}return x=w,w};for(let L of S){if(L.symbol_id===E.symbolId)continue;let w=l.get(L.symbol_id);if(!w)continue;if(!(L.start_line>=E.startLine&&L.end_line<=E.endLine)){if(!(L.start_line<=E.endLine&&L.end_line>=E.startLine))continue;let D=Y(w.symbol);if(!D||!C().has(D))continue}let P=`${w.symbol}|${L.chunk_id}`;I.has(P)||(I.add(P),v.push({...w,chunkId:L.chunk_id,source:"scip-chunk"}))}u.set(E.symbolId,v)}}return u}var $g=500;function Vl(e){let t=[...new Set(e)],n=[];for(let r=0;r<t.length;r+=$g)n.push(t.slice(r,r+$g));return n}function HL(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 UL(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 zL=12,qL=280;function fi(e,t,n,r){let i=KL(e,t,n,r);if(i.size===0)return JL();let o=[],s=new Set,a=(l,u,d,m)=>{if(u===t&&d<=r&&m>=n)return;let f=`${u}:${d}:${m}:${l}`;s.has(f)||(s.add(f),o.push({name:l,relativePath:u,startLine:d,endLine:m}))};for(let l of W(e,t))i.has(l.leaf)&&a(l.leaf,l.relativePath,l.startLine,l.endLine);for(let l of Ce(e,t)){let u=l.localName;if(!u||!i.has(u)||!l.sourcePath||l.kind==="namespace")continue;let d=l.importedName==="default"?u:l.importedName;for(let m of Qn(e,l.sourcePath,d,{maxReexportDepth:3}))a(u,m.relativePath,m.startLine,m.endLine)}o.sort(Ug);let c=o.map(l=>{let u=GL(e,l);return u?{...l,source:u}:null}).filter(l=>l!==null).slice(0,zL);return Xl(c)}function da(e,t=[]){return Xl(WL(e.flatMap(n=>n?.inline??[]),t))}function Hg(e){return e?e.inline.reduce((t,n)=>t+n.name.length+n.source.length+32,0):0}function KL(e,t,n,r){let i=te(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 GL(e,t){if(t.startLine!==t.endLine)return null;let n=(ie(e,t.relativePath)[t.startLine]??"").trim();if(!n||n.length>qL)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 WL(e,t){let n=new Map;for(let r of e){if(VL(r,t))continue;let i=`${r.relativePath}:${r.startLine}:${r.endLine}:${r.name}`;n.has(i)||n.set(i,{...r})}return[...n.values()].sort(Ug)}function VL(e,t){return t.some(n=>n.relativePath===e.relativePath&&n.startLine<=e.startLine&&n.endLine>=e.endLine)}function Ug(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||e.name.localeCompare(t.name)}function Xl(e){return{coverage:"indexed-project-literal-values",inline:e}}function JL(){return Xl([])}var YL=12,XL=20,Zl=200,eu=800,QL=.9,qg={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"},ya=["anchor","signature","binding","branch","loop","call","await","return","throw","mutation","shape","spread","catch","finally"],Kg=[...ya,"lifecycle"],Gg=["loop","await","throw","mutation","spread","catch","finally","lifecycle"],ZL=new Set(["onBeforeMount","onBeforeUnmount","onMounted","onUnmounted","useEffect","useInsertionEffect","useLayoutEffect"]);var Wg=new Set(["object","object_pattern","dictionary","field_declaration_list","struct_expression","struct_pattern"]);function pi(e,t,n,r,i=[],o={}){let s=ae(e,t);if(!s)return null;let a=ie(e,t),c=bt(e,t,n,r,i),l=va(e,t,c.startLine,c.endLine),u=l?.startLine??n,d=l?.endLine??r,m=(l?gi(s.rootNode,c.startLine,c.endLine):null)??po(s.rootNode,u,d);if(!m)return null;let f=Qg(m,a,u,d,i);if(!f||f.lines.length===0||f.lines.some(b=>b.text.length>eu))return null;let p=yD(a,u,d),g=bD(f);if((o.requireSavings??!0)&&g>=p*QL)return null;let h=ya.filter(b=>f.lines.some(S=>S.signals.includes(b)));return{...l?{callable:{name:l.name,startLine:l.startLine,endLine:l.endLine}}:{},representation:"outline",constructKind:f.constructKind,signature:f.signature,lines:f.lines,signals:h,testCases:J(t)==="test"?RD(a,u,d):[],coverage:{sourceStatements:f.sourceStatements,representedStatements:f.sourceStatements,copiedStatements:f.copiedStatements,omittedStatements:0},rawCharacters:p,outlineCharacters:g,candidateLines:f.sourceStatements,omittedLines:0}}function ba(e,t,n,r,i){if(i.length===0)return[];let o=ae(e,t);if(!o)return[];let s=ie(e,t),a=bt(e,t,n,r,i),c=va(e,t,a.startLine,a.endLine),l=c?.startLine??n,u=c?.endLine??r,d=(c?gi(o.rootNode,a.startLine,a.endLine):null)??po(o.rootNode,l,u);if(!d)return[];let m=Qg(d,s,l,u,i);return m?m.lines.filter(f=>f.text.length<=eu&&f.signals.some(p=>["branch","loop","catch","finally"].includes(p))&&i.some(p=>p>=f.line&&p<=f.endLine)):[]}function Vg(e,t,n,r){let i=ae(e,t);if(!i)return null;let o=gi(i.rootNode,n,r)??po(i.rootNode,n,r);if(!o)return null;let s=[],a=ru(o),c=[];return iu(o,o,l=>{if(ao.has(l.type)||eD.has(l.type)){nD(s,c,l);return}if(Sa.has(l.type)){rD(s,c,l);return}if(mo.has(l.type)){iD(s,c,l);return}fo.has(l.type)&&oD(s,l)}),{facts:uD(s),terminals:Xg(a),unsupported:c}}function bt(e,t,n,r,i=[]){let o=i.filter(d=>d>=n&&d<=r),s=ae(e,t);if(o.length>0&&s){let d=[];Dr(s.rootNode,f=>{dD(f)&&f.startPosition.row>=n&&f.endPosition.row<=r&&o.every(p=>f.startPosition.row<=p&&f.endPosition.row>=p)&&d.push(f)});let m=d.sort((f,p)=>f.endPosition.row-f.startPosition.row-(p.endPosition.row-p.startPosition.row)||f.startPosition.row-p.startPosition.row)[0];if(m)return{startLine:m.startPosition.row,endLine:m.endPosition.row}}let a=va(e,t,n,r);if(a)return{startLine:a.startLine,endLine:a.endLine};if(o.length===0)return{startLine:n,endLine:r};let c=(te(e,t)?.callables??[]).filter(d=>d.startLine>=n&&d.endLine<=r&&o.every(m=>d.startLine<=m&&d.endLine>=m)).sort((d,m)=>d.endLine-d.startLine-(m.endLine-m.startLine)||d.startLine-m.startLine)[0];if(!s)return c?{startLine:c.startLine,endLine:c.endLine}:{startLine:n,endLine:r};let l=[];Dr(s.rootNode,d=>{tr.has(d.type)&&d.startPosition.row>=n&&d.endPosition.row<=r&&o.every(m=>d.startPosition.row<=m&&d.endPosition.row>=m)&&l.push(d)});let u=l.sort((d,m)=>d.endPosition.row-d.startPosition.row-(m.endPosition.row-m.startPosition.row)||d.startPosition.row-m.startPosition.row)[0];return u?{startLine:u.startPosition.row,endLine:u.endPosition.row}:c?{startLine:c.startLine,endLine:c.endLine}:{startLine:n,endLine:r}}function tu(e,t,n,r,i={}){if(r-n+1<(i.minimumBodyLines??XL))return null;let s=eh(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=CD(a),l=a.filter(b=>b.text.length<=Zl);if(l.length===0)return null;let u=Gg.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 f=xD(l,c),p=new Map;for(let b of u){let S=f.find(y=>y.signals.includes(b));S&&p.set(S.line,S)}if(p.size===0){let b=f.find(S=>S.signals.includes("branch"));b&&p.set(b.line,b)}let g=Math.min(10,Math.max(1,i.maxLines??p.size)),h=new Map;for(let b of p.values()){if(h.size>=g)break;h.set(b.line,b)}return h.size>=a.length&&s.shapes.length===0?null:{owner:s.callable?.name??null,startLine:n,endLine: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 Pn(e,t,n,r){let i=eh(e,t,n,r,[],!1);return i?new Map(i.candidates.map(o=>[o.line,o.signals.filter(s=>s!=="lifecycle")])):new Map}var tr=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"]),Et=new Set(["block","body","compound_statement","declaration_list","statement_block"]),ao=new Set(["if_expression","if_statement","unless","unless_statement"]),eD=new Set(["conditional_expression","ternary_expression"]),Sa=new Set(["do_statement","enhanced_for_statement","for_expression","for_in_statement","for_of_statement","for_statement","loop_expression","while_statement"]),mo=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"]),pa=new Set(["catch_clause","except_clause","rescue"]),lo=new Set(["ensure","finally_clause"]),co=new Set(["else","else_clause"]),Yg=new Set(["raise_statement","return_statement","throw_statement"]),tD=new Set(["block_comment","comment","line_comment"]);function nD(e,t,n){let r=n.childForFieldName("condition")??su(n),i=n.childForFieldName("consequence")??n.childForFieldName("body")??n.namedChildren.find(c=>Et.has(c.type)),o=n.childForFieldName("alternative")??n.namedChildren.find(c=>co.has(c.type));if(!r||!i){t.push(ou(n,"conditional-fields-unresolved"));return}let s=un(r,"predicate",r.text),a=un(i,zg(i),"consequence");if(ln(e,s,a,"predicate-consequence",{branchRole:"consequence"}),ga(e,s,i,"consequence"),o){let c=un(o,zg(o),"alternative");ln(e,s,c,"predicate-alternative",{branchRole:"alternative"}),ga(e,s,o,"alternative");return}ln(e,s,nu(s,"otherwise continue"),"predicate-fallthrough",{branchRole:"fallthrough"})}function rD(e,t,n){let r=n.childForFieldName("body")??n.namedChildren.find(s=>Et.has(s.type));if(!r){t.push(ou(n,"loop-body-unresolved"));return}let i=n.childForFieldName("condition"),o=un(i??n,"predicate",i?.text??Gt(n,r));ln(e,o,un(r,"outcome","iteration"),"loop-iteration",{branchRole:"iteration"}),ga(e,o,r,"iteration"),ln(e,o,nu(o,"loop exits"),"loop-exit",{branchRole:"exit"})}function iD(e,t,n){let r=n.childForFieldName("body")??n.namedChildren.find(c=>Et.has(c.type)),i=n.childForFieldName("value")??n.childForFieldName("condition")??n.childForFieldName("subject")??su(n),o=aD(r??n);if(!i||o.length===0){t.push(ou(n,"switch-cases-unresolved"));return}let s=un(i,"predicate",i.text),a=!1;for(let c of o){let l=lD(c);a||=l;let u=Gt(c,c.namedChildren.find(d=>ha(d)));ln(e,s,un(c,"outcome",u||(l?"default":"case")),l?"predicate-default":"predicate-case",{branchRole:l?"default":"case"}),ga(e,s,c,l?"default":"case")}a||ln(e,s,nu(s,"no case matched"),"predicate-fallthrough",{branchRole:"fallthrough"})}function oD(e,t){let n=un(t,"scope","try");for(let r of cD(t)){let i=lo.has(r.type),o=un(r,"handler",i?"finally":Gt(r,ma(r)));ln(e,n,o,i?"finally-cleanup":"exception-handler",{branchRole:i?"finally":"catch"}),sD(e,o,r,i?"finally":"catch")}}function sD(e,t,n,r){for(let i of ru(n)){let o=i.label.startsWith("throw")||i.label.startsWith("raise")?"throw":"return";ln(e,t,i,o==="throw"?"handler-throw":"handler-return",{branchRole:r,terminalKind:o})}}function ga(e,t,n,r){for(let i of ru(n)){let o=i.label.startsWith("throw")||i.label.startsWith("raise")?"throw":"return";ln(e,t,i,o==="throw"?"predicate-throw":"predicate-return",{branchRole:r,terminalKind:o})}}function ln(e,t,n,r,i){e.push({controller:t,outcome:n,subtype:r,attributes:i})}function un(e,t,n){return{kind:t,label:uo(n).slice(0,eu),startLine:e.startPosition.row,endLine:e.endPosition.row,implicit:!1}}function nu(e,t){return{...e,kind:"outcome",label:t,implicit:!0}}function zg(e){return Yg.has(e.type)?"terminal":"outcome"}function ru(e){let t=[];return iu(e,e,n=>{Yg.has(n.type)&&t.push(un(n,"terminal",n.text))}),Xg(t)}function iu(e,t,n){n(t);for(let r of t.namedChildren)r!==e&&tr.has(r.type)||iu(e,r,n)}function aD(e){let t=[],n=r=>{for(let i of r.namedChildren)mo.has(i.type)||(Jg.has(i.type)?t.push(i):n(i))};return n(e),t}function cD(e){let t=[],n=r=>{for(let i of r.namedChildren)fo.has(i.type)||(pa.has(i.type)||lo.has(i.type)?t.push(i):tr.has(i.type)||n(i))};return n(e),t}function lD(e){let t=Gt(e,e.namedChildren.find(n=>ha(n))).trim();return e.type==="switch_default"||/^(?:default\b|_\s*=>)/u.test(t)}function ou(e,t){return{startLine:e.startPosition.row,endLine:e.endPosition.row,reason:t}}function uD(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 Xg(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 dD(e){return tr.has(e.type)||Sa.has(e.type)||mo.has(e.type)||fo.has(e.type)||pa.has(e.type)||lo.has(e.type)}function Qg(e,t,n,r,i){let s=gi(e,n,r)??e,a=ma(s),c=[],l=0,u=0,d=(v,x,C,L,w=!1,R=!0)=>{let P=w?C.trim():uo(C);if(!P)return;let _=Math.max(n,v.startPosition.row),D=Math.min(r,v.endPosition.row);c.push({line:_,endLine:Math.max(_,D),depth:x,signals:ya.filter(M=>L.includes(M)||M==="anchor"&&i.some(F=>F>=_&&F<=D)),text:P,copied:w}),R&&(l+=1,w&&(u+=1))},m=(v,x)=>{for(let C of v.namedChildren)I(C,x)},f=(v,x)=>{if(ao.has(v.type)){p(v,x,"else if");return}if(co.has(v.type)){let C=v.namedChildren.find(w=>ao.has(w.type));if(C){p(C,x,"else if");return}d(v,x,"else",["branch"],!1,!1);let L=ma(v)??v.namedChildren.find(w=>Et.has(w.type));if(L)I(L,x+1);else for(let w of v.namedChildren)I(w,x+1);return}d(v,x,"else",["branch"],!1,!1),I(v,x+1)},p=(v,x,C=v.type.startsWith("unless")?"unless":"if")=>{let L=v.childForFieldName("condition")??su(v),w=v.childForFieldName("consequence")??v.childForFieldName("body")??v.namedChildren.find(_=>Et.has(_.type)),R=v.childForFieldName("alternative")??v.namedChildren.find(_=>co.has(_.type)),P=L?L.text:Gt(v,w);d(v,x,`${C} ${gD(P)}`,so(L,["branch"])),w&&I(w,x+1),R&&f(R,x)},g=(v,x)=>{let C=v.childForFieldName("body")??v.namedChildren.find(L=>Et.has(L.type));d(v,x,Gt(v,C),so(v,["loop"])),C&&I(C,x+1)},h=(v,x)=>{let C=v.childForFieldName("body")??v.namedChildren.find(L=>Et.has(L.type));d(v,x,Gt(v,C),so(v,["branch"])),C&&I(C,x+1)},b=(v,x)=>{let C=v.namedChildren.find(L=>ha(L));d(v,x,Gt(v,C),["branch"],!1,!1);for(let L of v.namedChildren)(L===C||ha(L))&&I(L,x+1)},S=(v,x)=>{d(v,x,"try",[],!1);for(let C of v.namedChildren)Et.has(C.type)?I(C,x+1):(pa.has(C.type)||lo.has(C.type))&&I(C,x)},y=(v,x,C)=>{let L=v.childForFieldName("body")??v.namedChildren.find(R=>Et.has(R.type)),w=C==="finally"?"finally":Gt(v,L);d(v,x,w,[C],!1,!1),L&&I(L,x+1)},E=(v,x)=>{let C=ma(v);d(v,x,Gt(v,C),so(v,["binding"])),C&&I(C,x+1)},I=(v,x)=>{if(v.startPosition.row>r||v.endPosition.row<n||tD.has(v.type)||v.type==="empty_statement")return;if(Et.has(v.type)){m(v,x);return}if(ao.has(v.type)){p(v,x);return}if(Sa.has(v.type)){g(v,x);return}if(mo.has(v.type)){h(v,x);return}if(Jg.has(v.type)){b(v,x);return}if(fo.has(v.type)){S(v,x);return}if(pa.has(v.type)){y(v,x,"catch");return}if(lo.has(v.type)){y(v,x,"finally");return}if(co.has(v.type)){f(v,x);return}if(tr.has(v.type)){E(v,x);return}let L=!Zg(v)||hD(v);d(v,x,v.text,so(v),L)};return I(a&&a!==s?a:s,0),l===0?null:{constructKind:pD(s),signature:fD(s,a,t,n),lines:c,sourceStatements:l,copiedStatements:u}}function gi(e,t,n){let r=e.namedChildren.filter(i=>i.startPosition.row<=t&&i.endPosition.row>=n);for(let i of r.sort(mD)){let o=gi(i,t,n);if(o)return o}return tr.has(e.type)&&e.startPosition.row<=t&&e.endPosition.row>=n?e:null}function mD(e,t){return e.endPosition.row-e.startPosition.row-(t.endPosition.row-t.startPosition.row)||e.startPosition.row-t.startPosition.row}function ma(e){return e.childForFieldName("body")??e.childForFieldName("consequence")??e.namedChildren.find(t=>Et.has(t.type))??null}function fD(e,t,n,r){let i=Gt(e,t);return i||(n[r]??e.text).trim()}function pD(e){return e.type.includes("constructor")?"constructor":e.type.includes("method")||e.type==="method"?Ql(e,new Set(["class_body","class_declaration","class_definition"]))?"class method":"object method":e.type==="arrow_function"||e.type==="function_expression"||e.type==="lambda"?Ql(e,new Set(["object","pair"]))?"object member":"function value":e.type.includes("function")?Ql(e,tr)?"nested function":"module function":"source construct"}function Ql(e,t){let n=e.parent;for(;n;){if(t.has(n.type))return!0;n=n.parent}return!1}function su(e){return e.namedChildren.find(t=>!Et.has(t.type)&&!co.has(t.type))??null}function Gt(e,t){if(!t)return uo(e.text);let n=Math.max(0,t.startIndex-e.startIndex);return uo(e.text.slice(0,n)).replace(/[:{]\s*$/u,"").trim()}function gD(e){let t=uo(e);return t.startsWith("(")&&t.endsWith(")")?t.slice(1,-1).trim():t}function uo(e){return e.trim().replace(/\r?\n[\t ]*/gu," ")}function so(e,t=[]){let n=new Set(t);return e&&Dr(e,r=>{let i=qg[r.type];i&&n.add(i),r.type==="call_expression"&&(n.add("call"),th(r)&&n.add("shape")),au.has(r.type)&&n.add("binding")}),ya.filter(r=>n.has(r))}function hD(e){let t=!1;return Dr(e,n=>{t||!n.text.includes(`
59
- `)||/(?:string|template|heredoc|raw_string)/u.test(n.type)&&(t=!0)}),t}function ha(e){return Et.has(e.type)||ao.has(e.type)||Sa.has(e.type)||mo.has(e.type)||fo.has(e.type)||tr.has(e.type)||Zg(e)}function Zg(e){return/(?:statement|declaration|expression|assignment|return|throw|raise|break|continue|yield|with_item)$/u.test(e.type)||au.has(e.type)}function yD(e,t,n){let r=0;for(let i=t;i<=n;i+=1)r+=(e[i]?.length??0)+10;return r}function bD(e){return e.constructKind.length+e.signature.length+80+e.lines.reduce((t,n)=>t+n.text.length+n.depth*2+10,0)}function eh(e,t,n,r,i,o){let s=ae(e,t);if(!s)return null;let a=ie(e,t),c=va(e,t,n,r),l=o?c?.startLine??n:n,u=o?c?.endLine??r:r,m=(c?.startLine===l&&c.endLine===u?gi(s.rootNode,l,u):null)??po(s.rootNode,l,u);if(!m)return null;let f=new Map,p=new Map,g=new Map,h=(y,E)=>{if(y<l||y>u)return;let I=f.get(y)??new Set;I.add(E),f.set(y,I)};c&&h(c.startLine,"signature");for(let y of i)h(y,"anchor");Dr(m,y=>{let E=qg[y.type];if(E&&h(y.startPosition.row,E),E==="shape"&&SD(p,y,m,l,u),y.type==="call_expression"){let v=(y.childForFieldName("function")??y.namedChild(0))?.text.split(".").at(-1);if(th(y)){h(y.startPosition.row,"shape");let x=fa(y.text);x.length<=Zl&&g.set(y.startPosition.row,x)}if(v&&ZL.has(v)){h(y.startPosition.row,"lifecycle");let x=fa(y.text);x.length<=Zl&&g.set(y.startPosition.row,x)}}au.has(y.type)&&h(y.startPosition.row,"binding")});let b=te(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=[...f.entries()].sort(([y],[E])=>y-E).map(([y,E])=>({line:y,signals:Kg.filter(I=>E.has(I)),text:g.get(y)??fa(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:[...p.values()].sort((y,E)=>y.startLine-E.startLine)}}function SD(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=fa(o?.text??"");if(!s||s.includes(`
60
- `)||s.length>60)return;let a=vD(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 vD(e,t){let n=e.parent;for(;n&&n!==t.parent;){if(Wg.has(n.type))return n;if(n===t)break;n=n.parent}return e.parent??e}function va(e,t,n,r){return te(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 po(e,t,n){if(e.startPosition.row>t||e.endPosition.row<n)return null;for(let r of e.namedChildren){let i=po(r,t,n);if(i)return i}return e}function Dr(e,t){t(e);for(let n of e.namedChildren)Dr(n,t)}function fa(e){return e.trim().replace(/\s+/gu," ")}function th(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 Dr(t,r=>{Wg.has(r.type)&&(n=!0)}),n}function CD(e){let t={};for(let n of Kg){let r=e.filter(i=>i.signals.includes(n)).length;r>0&&(t[n]=r)}return t}function xD(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(Gg),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 au=new Set(["lexical_declaration","variable_declarator","const_item","static_item","let_declaration","assignment"]);function RD(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>=YL))break}return r}var ID=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 hi(e,t,n){let r=ae(e,t)?.rootNode??null,i=ED(r,n);if(!i)return null;let o=ie(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 go(e,t,n,r,i){let o=bt(e,t,r,i,[n]),s=o.startLine===o.endLine&&/(?:=>|\(|\{|\[|,)\s*$/u.test(ie(e,t)[o.startLine]??"");if(!s&&(o.startLine>r||o.endLine<i))return o;let a=hi(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 ED(e,t){if(!e||!ih(e,t))return null;let n=rh(e,t);for(;n;){if(ID.has(n.type))return n;n=n.parent}return null}function rh(e,t){let n=e.namedChildren.filter(r=>ih(r,t)).sort((r,i)=>nh(r)-nh(i));return n.length>0?rh(n[0],t):e}function ih(e,t){return e.startPosition.row<=t&&e.endPosition.row>=t}function nh(e){return e.endIndex-e.startIndex}var wD=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 Ca(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=ie(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(`
61
- `)}}function oh(e,t,n,r,i){let o=Ca(e,t,n,r);if(!o)return null;let s=ae(e,t)?.rootNode??null;if(!s)return{...o,kind:"bounded-context"};let a=LD(s,n,i);if(a.length!==1)return{...o,kind:a.length===0?"non-call-reference":"bounded-context"};let c=a[0],l=ie(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(`
62
- `),kind:"complete-call-expression"}}function sh(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=ie(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(`
63
- `)}}function nr(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=ie(e,t);if(o.length===0||n<0||n>=o.length)return null;let s=hi(e,t,n);if(!s){let g=Ca(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)),f=a+m,p=f+u-1;return{relativePath:t,startLine:f,endLine:p,focusLine:n,source:o.slice(f,p+1).join(`
64
- `),unitType:s.type,unitStartLine:a,unitEndLine:c,omittedLines:l-u}}function LD(e,t,n){let r=[];return ah(e,t,n,r),r.filter(i=>!r.some(o=>o!==i&&o.startIndex>=i.startIndex&&o.endIndex<=i.endIndex))}function ah(e,t,n,r){if(PD(e,t)){wD.has(e.type)&&DD(e)===n&&r.push(e);for(let i of e.namedChildren)ah(i,t,n,r)}}function DD(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 PD(e,t){return e.startPosition.row<=t&&e.endPosition.row>=t}function lh(e,t,n={}){let{context:r=0}=n,i=Sh(t);if(i)return vh(e,i.filePath,i.startLine,i.endLine,r);let o=yh(e,t);if(o)return ph(e,o);let s=pe(e,t);return s?ho(e,s,r):null}function W3(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=>TD(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:da(s.map(c=>c.bindingClosure),a)}}function TD(e,t,n,r){let i=Sh(t);if(i){let u=vh(e,i.filePath,i.startLine,i.endLine,n);return u?kD(e,t,u,n):cu(e,t,"definition-source-unreadable")}let o=yh(e,t);if(o)return AD(e,t,o,n,r);let s=at(e,t);if(!s.match)return cu(e,t,"definition-not-found");let a=zD(e,s),c=a.map(bh);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=ho(e,d,n);return m?[m]:[]}):[],definitions:[],candidates:c,omittedCandidates:Math.max(0,s.total-c.length),suggestions:[]}}let l=ho(e,s.match,n);return l?UD(t,l):cu(e,t,"definition-source-unreadable")}function kD(e,t,n,r){let i=W(e,n.relativePath).filter(l=>!uh(l,n.relativePath)),o=FD(e,n,i),s=fh(o.map(l=>ho(e,l,r)).filter(l=>l!==null)).filter(l=>!hh(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(bh);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 FD(e,t,n){if(!yo(t.freshness))return[];if(n.length===0)return[];let r=Yl(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 mh(e,[...o.values()],n)}function AD(e,t,n,r,i){let o=n.relativePath,s=_D(e,o),a=yo(n.freshness)?W(e,o).filter(g=>!uh(g,o)):[],c=a.filter(g=>It(e,g)),l=c.length>0?c:ND(s,a),u=i==="all"?[]:mh(e,l,a),d=i==="all"||a.length===0?[ph(e,n)]:fh(u.map(g=>ho(e,g,r)).filter(g=>g!==null)),m=BD(s,d),f=$D(o,s,d),p=jD(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:p,returnedDefinitions:m,returnedBodies:d.length,omittedDefinitions:Math.max(0,p-m),omittedLedger:f}}}function ND(e,t){let n=new Set(e.map(r=>r.symbol));return t.filter(r=>n.has(r.symbol))}function _D(e,t){return Tg(e,t).flatMap(n=>OD(n,t)?n.children:[n])}function uh(e,t){return dh(t).has(e.leaf)}function OD(e,t){return dh(t).has(Y(e.symbol))}function dh(e){let t=MD(e);return new Set([t,t.slice(0,Math.max(0,t.length-ch(t).length))])}function mh(e,t,n){if(t.length===0)return[];let r=Yl(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(HD)}function fh(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=>hh(i,r))||n.push(r);return n}function ph(e,t){let n=t.text.split(`
65
- `);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??uu(t.relativePath),source:t.text,freshness:t.freshness,...yo(t.freshness)?{bindingClosure:fi(e,t.relativePath,0,Math.max(0,n.length-1))}:{}}}function BD(e,t){return xa(e).filter(n=>t.some(r=>lu(n,r))).length}function $D(e,t,n){let r=[];return gh(r,e,t,n,0),r}function gh(e,t,n,r,i){for(let o of n){if(r.some(a=>lu(o,a)))continue;let s=xa(o.children).filter(a=>!r.some(c=>lu(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}),gh(e,t,o.children,r,i+1)}}function xa(e){return e.flatMap(t=>[t,...xa(t.children)])}function jD(e){return xa(e).length}function lu(e,t){return t.startLine<=e.startLine&&t.endLine>=e.endLine}function hh(e,t){return e.relativePath===t.relativePath&&e.startLine<=t.startLine&&e.endLine>=t.endLine}function HD(e,t){return e.startLine-t.startLine||t.endLine-e.endLine||e.symbol.localeCompare(t.symbol)}function UD(e,t){return{selector:e,status:"matched",kind:"source",totalCandidates:1,results:[t],definitions:[],candidates:[],omittedCandidates:0,suggestions:[]}}function cu(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 yh(e,t){try{return sa(e,t)}catch(n){if(n instanceof $f)return null;throw n}}function zD(e,t){if(!t.match)return[];let n=[t.match];for(let i of t.candidates){let o=W(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 bh(e){return{symbol:e.symbol,shortName:N(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine}}function Sh(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 ho(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=sa(e,t.relativePath);if(!i)return null;let s=i.text.split(`
66
- `),a=t.endLine<=t.startLine?nr(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(`
67
- `);return{symbol:t.symbol,shortName:N(t.symbol),relativePath:t.relativePath,startLine:u,endLine:d,language:r?.language??uu(t.relativePath),source:m,freshness:i.freshness,...yo(i.freshness)?{bindingClosure:fi(e,t.relativePath,u,d)}:{}}}function vh(e,t,n,r,i){let o=sa(e,t);if(!o)return null;let s=e.get("SELECT language FROM documents WHERE relative_path = ?",o.relativePath),c=o.text.split(`
68
- `);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(`
69
- `);return{symbol:`${o.relativePath}:${n}-${r}`,shortName:`${o.relativePath}:${n}-${r}`,relativePath:o.relativePath,startLine:l,endLine:u,language:s?.language??uu(o.relativePath),source:d,freshness:o.freshness,...yo(o.freshness)?{bindingClosure:fi(e,o.relativePath,l,u)}:{}}}function yo(e){return!!(e&&e.semantic.state!=="stale"&&e.semantic.basis!=="no-compiler-document")}function uu(e){switch(ch(e).toLowerCase()){case".ts":case".tsx":case".mts":case".cts":return"typescript";case".js":case".jsx":case".mjs":case".cjs":return"javascript";case".py":case".pyi":return"python";case".rs":return"rust";case".go":return"go";case".java":return"java";case".kt":case".kts":return"kotlin";case".scala":return"scala";case".rb":return"ruby";case".php":return"php";case".cs":return"csharp";case".vb":return"vb";case".dart":return"dart";case".c":case".h":return"c";case".cc":case".cpp":case".cxx":case".hpp":case".hh":case".hxx":return"cpp";case".vue":return"vue";default:return null}}function Ra(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath)??[];r.push(n),t.set(n.relativePath,r)}return t}function Ch(e){let t=new Map,n=KD(e),r=new Map;return i=>{let o=qD(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=GD(W(e,i.file)),t.set(i.file,a));let c=WD(a,i);return r.set(o,c),c}}function qD(e){return`${e.file}\0${e.symbol}\0${e.line}`}function KD(e){return new Set(e.all("SELECT relative_path FROM documents").map(t=>t.relative_path))}function GD(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 WD(e,t){if(e.definitions.length===0)return t.symbol;let n=YD(t.symbol),r=VD(e.byLeaf,n),i=JD(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 VD(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 JD(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 YD(e){let t=new Set([e]),r=e.split(/::|\.|#/).filter(Boolean).at(-1);return r&&t.add(r),t}function xh(e,t){let r=Ce(e,t).map(i=>QD(t,i));return{usage:r,positions:ZD(e,t,r)}}function Rh(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?XD(r.usage,i.sourcePaths):r.usage}}}function XD(e,t){return e.map((n,r)=>{let i=t.get(String(r));return i?{...n,sourcePath:i}:n})}function QD(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 ZD(e,t,n){let r=ae(e,t);if(!r)return[];let i=eP(r.rootNode),o=new Map;for(let a of i){let c=o.get(mu(a.importedName,a.localName));c?c.push(a.position):o.set(mu(a.importedName,a.localName),[a.position])}let s=[];return n.forEach((a,c)=>{let l=o.get(mu(a.importedName,a.localName??a.importedName))?.shift();l&&s.push({...l,id:String(c),file:t})}),s}function eP(e){let t=[];for(let n of e.descendantsOfType("use_declaration")){let r=n.namedChildren.find(i=>i.type!=="visibility_modifier");r&&t.push(...Ia(r,""))}return t.filter(n=>n.importedName!=="*")}function Ia(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":return[{importedName:e.text,localName:e.text,position:du(e,e.text)}];case"scoped_identifier":{let n=e.text.split("::").pop()??e.text;return[{importedName:n,localName:n,position:du(e,n)}]}case"scoped_use_list":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=up(t,n.text);return r.namedChildren.flatMap(o=>Ia(o,i))}case"use_list":return e.namedChildren.flatMap(n=>Ia(n,t));case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);return!n||!r?[]:Ia(n,t).map(i=>({...i,localName:r.text}))}case"use_wildcard":{let n=e.namedChild(0),r="*";return[{importedName:r,localName:r,position:du(n??e,r)}]}default:return[]}}function du(e,t){let n=Math.max(0,e.text.lastIndexOf(t));return{id:"",file:"",line:e.startPosition.row,column:e.startPosition.column+n+tP(t)}}function tP(e){return Math.max(0,Math.min(e.length-1,1))}function mu(e,t){return`${e}\0${t}`}import{spawnSync as Iu}from"child_process";import{existsSync as Eu}from"fs";import{fileURLToPath as tM}from"url";function ir(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function Ea(e){let t=Mp(Pp,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 jP,mkdtempSync as Gh,rmSync as bu}from"fs";import{tmpdir as Cu}from"os";import{join as Su}from"path";import{fileURLToPath as Io,pathToFileURL as HP}from"url";import{SHARE_ENV as UP,Worker as zP}from"worker_threads";function or(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=ir(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 vP}from"child_process";import{createHash as CP,randomUUID as xP}from"crypto";import{existsSync as Bh,realpathSync as RP,rmSync as IP}from"fs";import{tmpdir as EP}from"os";import{resolve as bi}from"path";import{execFileSync as lP}from"child_process";import{existsSync as nP}from"fs";import{deserializeSCIP as rP,SymbolRole as iP}from"@c4312/scip";import{realpathSync as cX}from"fs";import{basename as uX,dirname as dX,join as mX,relative as fX,sep as pX}from"path";import{fileURLToPath as hX,pathToFileURL as yX}from"url";function wa(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 fu=new WeakMap,oP="SCIP_RUST_SCIP_OCCURRENCE_REFERENCE_MODE";function Ih(e,t){let n=new Map,r=La(),i=t.filter(s=>Lh(s,r));if(i.length===0)return n;let o=Dh(e);if(!o)return n;for(let s of i){let a=wh(o,s);a!==null&&n.set(s.symbolId,a)}return n}function Eh(e,t){if(!Lh(t,La()))return null;let n=Dh(e);return n?wh(n,t):null}function wh(e,t){return e.referencesBySymbol.get(t.symbol)??[]}function Lh(e,t="safe"){if(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||Xe(e.symbol)||/impl#\[[^\]]+\]\[Default\]default\(\)\.$/.test(e.symbol))return!1;if(t==="all")return!0;let n=Bt(e.symbol);if(n==="method")return!0;if(n!=="term")return!1;let r=Vn(e.symbol);return"kind"in r?!1:!sP(r)}function sP(e){for(let t=0;t<e.descriptors.length-1;t+=1)if(e.descriptors[t]?.suffix==="type")return!0;return!1}function Dh(e){if(fu.has(e))return fu.get(e)??null;let t=aP(e);return fu.set(e,t),t}function aP(e){if(!e.generation.indexPath||!nP(e.generation.indexPath))return null;try{let t=rP(ei(e.generation.indexPath,{inputKind:"SCIP occurrence-reference index",maxBytes:Zr})),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&iP.Definition)!==0)continue;let s=cP(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,wa(i));return{referencesBySymbol:n}}catch{return null}}function cP(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 La(){return process.env[oP]==="all"?"all":"safe"}var Ph=new Map;function pu(e){let n=Ea(e).resolvedBinary??null;return{engine:"rust-analyzer",resolvedBinary:n,version:n?uP(e,n):"unavailable"}}function Mr(e){return{...pu(e),scipOccurrenceReferenceMode:La()}}function uP(e,t){let n=`${e}\0${t}`,r=Ph.get(n);if(r)return r;let i;try{i=lP(t,["--version"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:2e3}).trim()}catch{i="unknown"}return Ph.set(n,i),i}import{createHash as dP}from"crypto";var mP=new Set(["Cargo.lock","Cargo.toml","rust-project.json","rust-toolchain","rust-toolchain.toml"]);function Mh(e){let t=Vf(e,{includePath:fP});return dP("sha256").update(JSON.stringify(t)).digest("hex")}function fP(e){let t=e.replaceAll("\\","/"),n=t.split("/").at(-1)??t;return t.endsWith(".rs")||mP.has(n)?!0:t===".cargo/config"||t===".cargo/config.toml"||t.endsWith("/.cargo/config")||t.endsWith("/.cargo/config.toml")}import{createHash as pP}from"crypto";import{resolve as gP}from"path";var yi=3;function hu(e){return pP("sha256").update(Ir({kind:"codebaseiq-durable-rust-mailbox",protocolVersion:yi,sessionDir:gP(e)})).digest("hex")}function Fh(e,t){return Kn(e)?e.protocolVersion!==yi?kh(e.protocolVersion===void 0?"helper wrote a prior uncorrelated response protocol":`helper wrote unsupported response protocol ${String(e.protocolVersion)}`):e.mailboxVersion!==ii||e.id!==t.requestId||e.operationKey!==t.operationKey||e.sessionIdentity!==t.sessionIdentity||e.deadlineAtMs!==t.deadlineAtMs?kh("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"||!SP(e.errorCode)?gu("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"||!hP(e.response,t.requestKind)?gu("helper wrote an invalid success response"):{ok:!0,session:e.session,response:e.response}:gu("helper wrote an invalid response object")}function hP(e,t){return!Kn(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")):Th(e.references,yP)&&(e.incompleteReferenceSymbolIds===void 0||Array.isArray(e.incompleteReferenceSymbolIds)&&e.incompleteReferenceSymbolIds.every(n=>Number.isSafeInteger(n)))&&(e.callees===void 0||Th(e.callees,bP))&&(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 Th(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 yP(e){return Kn(e)&&typeof e.file=="string"&&kt(e.line)&&kt(e.column)}function bP(e){return Kn(e)&&typeof e.symbol=="string"&&typeof e.file=="string"&&kt(e.line)&&(e.callsiteLine===void 0||kt(e.callsiteLine))}function SP(e){return e==="unsupported-protocol"||e==="malformed-request"||e==="expired-request"||e==="handler-error"}function gu(e){return{ok:!1,code:"malformed-response",error:e}}function kh(e){return{ok:!1,code:"incompatible-response",error:e}}var wP=5e3,$h=10,LP=3e4;function Ah(e,t,n,r=zh){let i=r.engineIdentity(e),o={protocolVersion:yi,projectRoot:r.canonicalProjectRoot(e),projectFingerprint:r.projectFingerprint(e),engine:{engine:i.engine,resolvedBinary:i.resolvedBinary,version:i.version},workerFingerprint:r.fileFingerprint(t),environment:jh(r.environment())};return{key:qh(Ir(o)),...o}}function bo(e,t,n,r){if(e.protocolVersion!==yi||!n(e.pid))return!1;if(!e.processIdentity)return!0;let i=r?.(e.pid);return i!=null&&ni(e.processIdentity,i)}function yu(e,t,n){let r;try{r=dl(t,{maxBytes:Cr,inputKind:"Rust semantic engine artifact"})}catch{r="missing"}let i=qh(Ir({projectRoot:bi(e),serverPath:bi(t),serverFingerprint:r})).slice(0,20);return bi(n,`codebaseiq-rust-session-${i}`)}function Nh(e){let t=e===void 0?Number.NaN:Number(e);return Number.isInteger(t)&&t>=0?t:0}function jh(e){return Object.fromEntries(Object.entries(e).filter(([t])=>Uh(t)).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,n??null]))}function Hh(e,t){let n=t.runtime??FP,r=t.identityRuntime??zh,i=yu(e,t.serverPath,t.tempRoot??EP()),o=!1,s=(a,c)=>{if(o)throw new Error("Durable Rust semantic session was already disposed.");return PP(i,t.serverPath,t.semanticWorkerPath,a,c,n,t.mailboxLimits)};return{requestSemantic(a,c){let l=Ah(e,t.semanticWorkerPath,a,r),{readinessDeadlineMs:u,...d}=a;return s({kind:"semantic",identityKey:l.key,workerEnvironment:Oh(),request:{...d,referenceRetryTimeoutMs:DP(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,a.referenceRetryTimeoutMs),settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:Nh(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},requestImportDefinitions(a,c){let l=Ah(e,t.semanticWorkerPath,a,r),{readinessDeadlineMs:u,...d}=a;return s({kind:"import-definitions",identityKey:l.key,workerEnvironment:Oh(),request:{...d,settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:Nh(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},shutdown(){o=!0}}}function DP(e,t){return t!==void 0?t:e===void 0?LP:void 0}function PP(e,t,n,r,i,o,s={}){let a=o.now(),c=a+i,l=(o.monotonicNow??tn)(),u=l+i,d=Wi("rust-semantic-v3",r),m=Vi(d),f=Yf(e),p=hu(e),g=Fs(f,{mailboxVersion:ii,protocolVersion:yi,id:m,operationKey:d,clientId:o.randomId(),enqueuedAtMs:a,deadlineAtMs:c,sessionIdentity:p,request:r},{nowMs:a,limits:s});for(_h(e,t,n,u,o);(o.monotonicNow??tn)()<=u;){if(Bh(g.responsePath)){let b=MP(en(g.responsePath,{maxBytes:s.maxItemBytes??Cr,inputKind:"durable Rust semantic mailbox response"}),{requestId:m,operationKey:d,sessionIdentity:p,deadlineAtMs:g.authoritativeDeadlineAtMs,requestKind:r.kind,nowMs:o.now()});if(!b.ok)throw new Error(b.error);return Ne()&&Ts({type:"span",name:"rust.semantic.durable-session.request",durationMs:(o.monotonicNow??tn)()-l,ok:!0,session:b.session,kind:r.kind}),b.response}let h=So(e);(!h||!bo(h,o.now(),o.isProcessAlive,o.readProcessIdentity))&&_h(e,t,n,u,o),o.sleep($h)}throw new Error(`Durable Rust semantic session timed out after ${(i/1e3).toFixed(0)}s.`)}function _h(e,t,n,r,i){let o=So(e);if(o&&bo(o,i.now(),i.isProcessAlive,i.readProcessIdentity))return;IP(bi(e,"server.json"),{force:!0}),i.spawnServer(t,e,n);let s=i.monotonicNow??tn,a=Math.min(r,s()+wP);for(;s()<=a;){let c=So(e);if(c&&bo(c,i.now(),i.isProcessAlive,i.readProcessIdentity))return;i.sleep($h)}throw new Error("Durable Rust semantic session helper did not become ready within 5s.")}function So(e){try{let t=JSON.parse(en(bi(e,"server.json"),{maxBytes:Of,inputKind:"durable Rust session state"}));if(typeof t.protocolVersion!="number"||t.sessionIdentity!==void 0&&(typeof t.sessionIdentity!="string"||t.sessionIdentity!==hu(e))||typeof t.pid!="number"||typeof t.heartbeatAtMs!="number"||t.busyUntilMs!==void 0&&typeof t.busyUntilMs!="number"||t.mailbox!==void 0&&!TP(t.mailbox))return null;let n=t.processIdentity===void 0?null:ti(t.processIdentity);return t.processIdentity!==void 0&&(!n||n.pid!==t.pid)?null:{protocolVersion:t.protocolVersion,...t.sessionIdentity===void 0?{}:{sessionIdentity:t.sessionIdentity},pid:t.pid,...n?{processIdentity:n}:{},heartbeatAtMs:t.heartbeatAtMs,...t.busyUntilMs===void 0?{}:{busyUntilMs:t.busyUntilMs},...t.mailbox===void 0?{}:{mailbox:t.mailbox}}}catch{return null}}function MP(e,t){try{return Fh(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 TP(e){if(!e||typeof e!="object")return!1;let t=e;return kt(t.pending)&&kt(t.inflight)&&kt(t.responses)&&kt(t.deadLetters)&&kt(t.invalid)&&kt(t.totalItems)&&typeof t.totalBytes=="number"&&Number.isFinite(t.totalBytes)&&t.totalBytes>=0&&(t.oldestPendingAt===void 0||Number.isFinite(Date.parse(t.oldestPendingAt)))}function Oh(){return Object.fromEntries(Object.entries(process.env).filter(([e])=>kP(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t??null]))}function Uh(e){return e==="HOME"||e==="PATH"||e.startsWith("CARGO_")||e.startsWith("RA_")||e.startsWith("RUST")}function kP(e){return Uh(e)||e.startsWith("SCIP_RUST_")||e==="CODEBASEIQ_PROFILE"||e==="CODEBASEIQ_PROFILE_CACHE_STATE"||e==="CODEBASEIQ_PROFILE_COMMAND"||e==="CODEBASEIQ_PROFILE_OUT"||e==="CODEBASEIQ_PROFILE_RUN_ID"||e==="CODEBASEIQ_PROFILE_WORKLOAD_IDENTITY"||e==="CODEBASEIQ_PROFILE_WORKLOAD_IDENTITY_KIND"||e==="CODEBASEIQ_PROFILE_MIN_MS"}var zh={canonicalProjectRoot(e){try{return RP(e)}catch{return bi(e)}},projectFingerprint(e){return Mh(e)},engineIdentity:pu,fileFingerprint(e){return dl(e,{maxBytes:Cr,inputKind:"Rust semantic engine artifact"})},environment(){return jh(process.env)}},FP={now:Date.now,monotonicNow:tn,randomId:xP,isProcessAlive:qn,readProcessIdentity:xn,spawnServer(e,t,n){if(!Bh(e))throw new Error(`Durable Rust semantic session helper was not found at ${e}. Run npm run build first.`);vP(process.execPath,[e,t,n],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)}};function qh(e){return CP("sha256").update(e).digest("hex")}import{randomUUID as s4}from"crypto";import{readdirSync as AP,rmSync as c4,writeFileSync as l4}from"fs";import{join as NP}from"path";var _P="rust-analyzer-owner-",OP=".json",BP=16*1024;async function Kh(e,t){if(!e)return[];let n;try{n=AP(e)}catch{return[]}let r=n.filter(s=>s.startsWith(_P)&&s.endsWith(OP)).map(s=>NP(e,s)),i=[],o=[];for(let s of r){let a=$P(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=>Tp(s,t)))),i}function $P(e){try{let t=en(e,{maxBytes:BP,inputKind:"rust-analyzer process ownership record"}),n=JSON.parse(t),r=ti(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 Wh=15e3,Vh=8,Yh=5e3,qP=64,KP=96,xu=class{constructor(t,n,r={}){this.projectRoot=t;this.status=n;this.opts=r;this.requester=r.requester??VP(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:Co(n),references:xo(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!0});return{...vo(r),resolvedBinary:n.resolvedBinary,references:or(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:xo(t)}}}calleesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:Co(n),callees:Ro(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!0});return{...vo(r),resolvedBinary:n.resolvedBinary,callees:vu(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:Ro(t)}}}referencesAndCalleesForDefinitions(t,n){let r=this.status(this.projectRoot);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:Co(r),references:xo(t),callees:Ro(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{...vo(o),resolvedBinary:r.resolvedBinary,references:or(t,new Map(o.references),new Set(o.incompleteReferenceSymbolIds??[])),callees:vu(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:Co(n),signatures:Jh(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!1,includeSignatures:!0});return{...vo(r),resolvedBinary:n.resolvedBinary,signatures:ZP(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:Jh(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:Co(r),sourcePaths:new Map(n.map(i=>[i.id,null]))};try{let i=this.requestImportDefinitions(r.resolvedBinary,t,n);return{...vo(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=Da(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Wh),o=Pa(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),s=Da(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Vh),a=Pa(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=Eo(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},f=eM(m);return O("rust.semantic.session.request",()=>this.requester.requestSemantic(m,Pr(f,Ru(i,m.referenceRetryTimeoutMs),s)),()=>({definitions:n.length,operationDefinitions:f,referenceDefinitions:m.referenceDefinitions?.length,calleeDefinitions:m.calleeDefinitions?.length,signatureDefinitions:m.signatureDefinitions?.length,references:m.includeReferences!==!1,callees:m.includeCallees===!0,signatures:m.includeSignatures===!0,referenceRetryTimeoutMs:m.referenceRetryTimeoutMs}))}fallbackReferencesAndCallees(t,n,r,i){let o=n.length===0?{available:!0,resolvedBinary:t.resolvedBinary,references:xo(n)}:this.opts.fallbackReferenceResolver?.referencesForDefinitions(n),s=r.length===0?{available:!0,resolvedBinary:t.resolvedBinary,callees:Ro(r)}:this.opts.fallbackCalleeResolver?.calleesForDefinitions(r);if(o&&s){let a={resolvedBinary:o.resolvedBinary??s.resolvedBinary??t.resolvedBinary,references:or(n,o.references),callees:vu(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:xo(n),callees:Ro(r)}}requestImportDefinitions(t,n,r){let i=Da(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Wh),o=Da(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Vh),s=Pa(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),a=Pa(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,Yh),c={projectRoot:this.projectRoot,rustAnalyzerBinary:t,file:n,positions:[...r],requestTimeoutMs:i,diagnosticsTimeoutMs:s,settleDelayMs:a,concurrency:o};return O("rust.semantic.import-definitions.session.request",()=>this.requester.requestImportDefinitions(c,Pr(r.length,i,o)),()=>({file:n,positions:r.length}))}};function vo(e){return e.available?{available:!0}:{available:!1,reason:e.reason}}function Co(e){return e.available?"rust-analyzer binary path is unavailable.":e.reason}function Xh(e,t,n={}){return new xu(e,t,n)}function Eo(e,t){let n=ty(e);if(n!==null)return n;let r=t.includeReferences!==!1;return r&&t.includeCallees!==!0&&t.includeSignatures!==!0&&t.definitionCount<=qP||r&&t.includeCallees===!0&&t.includeSignatures!==!0&&t.definitionCount<=KP?0:Yh}function Qh(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 GP(e){return Qh(e).transport}function D4(e,t){let n=Qh(t);if(n.transport==="worker")return{...n,state:"per-command"};let r=Io(ey()),i=yu(e,r,Cu()),o=So(i);return o?{...n,state:bo(o,Date.now(),qn,xn)?"live":"stale",pid:o.pid,heartbeatAtMs:o.heartbeatAtMs,...o.busyUntilMs===void 0?{}:{busyUntilMs:o.busyUntilMs}}:{...n,state:"stopped"}}function WP(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 f=QP(u);r=!0;try{a()}catch{}Ne()&&Ts({type:"span",name:"rust.semantic.durable-session.request",durationMs:m,ok:!1,kind:d,session:"worker-fallback",reason:f})},l=(u,d,m)=>{if(o)throw new Error("Rust semantic failover session was already disposed.");if(r)return m(s());let f=performance.now();try{return d(e)}catch(p){c(p,u,performance.now()-f)}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 VP(e,t,n={worker:()=>JP(),durable:()=>Hh(e,{serverPath:Io(ey()),semanticWorkerPath:Io(Zh())})}){return GP(t)==="durable"?WP(n.durable(),n.worker):n.worker()}function JP(e={}){let t=null,n=null,r=1,i=!1,o=null,s=null,a=d=>{d&&bu(d,{recursive:!0,force:!0})},c=()=>{if(o)return;let d=t,m=n;t=null,n=null;let f=d?d.terminate():Promise.resolve(0);o=Promise.allSettled([f,Kh(m,{gracefulMs:1e3,forceMs:1e3})]).then(([p,g])=>{let b=(g.status==="fulfilled"?g.value:[{reaped:!1,detail:String(g.reason)}]).filter(S=>!S.reaped);if(p.status==="rejected"||b.length>0){s=new Error(`Rust semantic worker cleanup did not complete; ownership evidence remains at ${m??"unknown"}.`);return}a(m)}).finally(()=>{o=null})},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?HP(e.semanticWorkerPath):Zh();if(!jP(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=Gh(Su(Cu(),"codebaseiq-rust-session-")),t=new zP(d,e.shareEnvironment?{env:UP}:void 0),t.unref(),t},u=()=>{let d=n??Gh(Su(Cu(),"codebaseiq-rust-session-"));return n=d,Su(d,`${r++}.json`)};return{requestSemantic(d,m){if(i)throw new Error("Rust semantic session was already disposed.");let f=l(),p=u(),g=new SharedArrayBuffer(4),h=new Int32Array(g);if(f.postMessage({kind:"semantic",request:d,responsePath:p,sharedBuffer:g}),Atomics.wait(h,0,0,m)==="timed-out")throw c(),new Error(`Rust semantic session worker timed out after ${(m/1e3).toFixed(0)}s`);try{let S=YP(en(p,{maxBytes:Cr,inputKind:"Rust semantic worker response"}));if(!S.ok)throw new Error(S.error);return S.response}finally{bu(p,{force:!0})}},requestImportDefinitions(d,m){if(i)throw new Error("Rust semantic session was already disposed.");let f=l(),p=u(),g=new SharedArrayBuffer(4),h=new Int32Array(g);if(f.postMessage({kind:"import-definitions",request:d,responsePath:p,sharedBuffer:g}),Atomics.wait(h,0,0,m)==="timed-out")throw c(),new Error(`Rust semantic import-definition session worker timed out after ${(m/1e3).toFixed(0)}s`);try{let S=XP(en(p,{maxBytes:Cr,inputKind:"Rust import-definition worker response"}));if(!S.ok)throw new Error(S.error);return S.response}finally{bu(p,{force:!0})}},shutdown(){if(i)return;if(i=!0,!t){a(n),n=null;return}let d=u(),m=new SharedArrayBuffer(4),f=new Int32Array(m);t.postMessage({kind:"shutdown",responsePath:d,sharedBuffer:m}),Atomics.wait(f,0,0,5e3),c()}}}function YP(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 XP(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 QP(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 xo(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Ro(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Jh(e){return new Map(e.map(t=>[t.symbolId,null]))}function vu(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??[]]))}function ZP(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function eM(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 Ru(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 ey(){return new URL("./rust-semantic-session-server.js",import.meta.url)}function Da(e,t){return ir(e)??t}function Pa(e,t){return ty(e)??t}function ty(e){if(!e)return null;let t=Number(e);return Number.isInteger(t)&&t>=0?t:null}var wu=15e3,Lu=8;function oy(e,t={}){let n=t.status??Ea,r=iM(e,n),i=oM(e,n),o=sM(e,n),s=t.referenceResolver||t.calleeResolver||t.signatureResolver||!nM(t)?null:Xh(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??Rh(t.sourceImportUsageResolver??rM(),t.importDefinitionResolver??s),d=t.calleeSymbolResolver,m=t.sourceZeroCalleeOracle,f=t.scipOccurrenceCalleeOracle,p=new Map,g=new Map,h=null,b=null,S=()=>(h??=n(e),h),y=()=>{let C=S();return C.dependencyAvailable?b??C:C},E=C=>{if(C.length===0)return new Map;let L=Lo(C);try{let w=a.referencesForDefinitions(L),R=S();return b=Ma(R,w),w.available?new Map(w.references):or(L,w.references)}catch(w){let R=S();return b=wo(R,w),Tr(L)}},I=C=>{if(C.length===0)return new Map;let L=Lo(C),w=L.filter(ny);if(w.length===0)return kr(L);let R=new Map,P=iy(w,f),_=[];for(let D of w)g.has(D.symbolId)?R.set(D.symbolId,g.get(D.symbolId)??[]):P.has(D.symbolId)?R.set(D.symbolId,P.get(D.symbolId)??[]):ry(D,m)?R.set(D.symbolId,[]):_.push(D);if(_.length===0)return Si(L,R,void 0);try{let D=c.calleesForDefinitions(_),M=S();b=Ma(M,D);let F=Si(_,D.callees,d);for(let[V,ce]of F)R.set(V,ce);return Si(L,R,void 0)}catch(D){let M=S();return b=wo(M,D),kr(L)}},v=(C,L)=>{let w=Lo(C),R=Lo(L),P=R.filter(ny),_=new Map,D=iy(P,f),M=[];for(let F of P)D.has(F.symbolId)?_.set(F.symbolId,D.get(F.symbolId)??[]):ry(F,m)?_.set(F.symbolId,[]):M.push(F);if(w.length===0&&M.length===0)return{references:Tr(w),callees:Si(R,_,void 0)};try{let F=s?s.referencesAndCalleesForDefinitions(w,M):uM(a,c,{referenceDefinitions:w,calleeDefinitions:M}),V=S();b=Ma(V,F);let ce=F.available?new Map(F.references):or(w,F.references);for(let[X,A]of F.callees)_.set(X,A);let G=Si(R,_,d);for(let[X,A]of G)g.set(X,A);return{references:ce,callees:G}}catch(F){let V=S();return b=wo(V,F),{references:Tr(w),callees:kr(R)}}},x=C=>{if(C.length===0)return new Map;let L=Lo(C);try{let w=l.signaturesForDefinitions(L),R=S();return b=Ma(R,w),sy(L,w.signatures)}catch(w){let R=S();return b=wo(R,w),Ta(L)}};return{language:"rust",availability:y,dispose:()=>{s?.dispose()},importUsage:C=>{let L=p.get(C);if(L)return L;try{let w=u.importUsage(C);return p.set(C,w),w}catch(w){let R=S();return b=wo(R,w),[]}},referencesFor:C=>E([C]).get(C.symbolId)??[],referencesForDefinitions:E,referencesAndCalleesForDefinitions:v,calleesFor:C=>I([C]).get(C.symbolId)??[],calleesForDefinitions:I,signatureFor:C=>x([C]).get(C.symbolId)??null}}function Ma(e,t){let n={dependencyAvailable:e.dependencyAvailable,resolvedBinary:t.resolvedBinary??e.resolvedBinary,...e.note?{note:e.note}:{}};return t.available?{available:!0,...n}:{available:!1,reason:t.reason,...n}}function wo(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 nM(e){if(e.usePersistentSession!==void 0)return e.usePersistentSession;let t=process.env.SCIP_RUST_SEMANTIC_SESSION;return t!=="0"&&t!=="false"}function rM(){return{importUsageFacts:()=>({usage:[],positions:[]})}}function Lo(e){return e.map(t=>{let n=t;return{...t,leaf:typeof n.leaf=="string"?n.leaf:Y(t.symbol),parentTypeName:n.parentTypeName??null,isFunctionLike:typeof n.isFunctionLike=="boolean"?n.isFunctionLike:_e(t.symbol),isTypeLike:n.isTypeLike??!1,kind:n.kind??null,documentation:n.documentation??null,enclosingSymbol:n.enclosingSymbol??null}})}function ny(e){return e.isFunctionLike}function ry(e,t){if(!t)return!1;try{return t(e)}catch{return!1}}function iy(e,t){if(!t||e.length===0)return new Map;try{return t(e)}catch{return new Map}}function iM(e,t){return{referencesForDefinitions:n=>aM(e,t,n)}}function oM(e,t){return{calleesForDefinitions:n=>cM(e,t,n)}}function sM(e,t){return{signaturesForDefinitions:n=>lM(e,t,n)}}function aM(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:Mu(r),references:Tr(n)};let i=Du();if(!Eu(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:Tr(n)};let o=vi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,wu),s=ka(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),a=vi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Lu),c=ka(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),l=Eo(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=Iu(process.execPath,[i],{cwd:e,input:JSON.stringify(u),encoding:"utf8",maxBuffer:50*1024*1024,windowsHide:!0,timeout:Pr(n.length,Ru(o,u.referenceRetryTimeoutMs),a)}),m=Tu(d.stdout);if(m)return{...Pu(m),resolvedBinary:r.resolvedBinary,references:or(n,new Map(m.references),new Set(m.incompleteReferenceSymbolIds??[]))};let f=d.error instanceof Error?d.error.message:d.stderr.trim()||`Rust semantic worker exited with status ${d.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:f,references:Tr(n)}}function cM(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:Mu(r),callees:kr(n)};let i=Du();if(!Eu(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:kr(n)};let o=vi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,wu),s=vi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Lu),a=ka(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=Eo(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=Iu(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,windowsHide:!0,timeout:Pr(n.length,o,s)}),d=Tu(u.stdout);if(d)return{...Pu(d),resolvedBinary:r.resolvedBinary,callees:Si(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:kr(n)}}function lM(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:Mu(r),signatures:Ta(n)};let i=Du();if(!Eu(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:Ta(n)};let o=vi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,wu),s=vi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Lu),a=ka(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=Eo(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=Iu(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,windowsHide:!0,timeout:Pr(n.length,o,s)}),d=Tu(u.stdout);if(d)return{...Pu(d),resolvedBinary:r.resolvedBinary,signatures:sy(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:Ta(n)}}function uM(e,t,n){let r=n.referenceDefinitions.length>0?e.referencesForDefinitions(n.referenceDefinitions):{available:!0,references:Tr(n.referenceDefinitions)},i=n.calleeDefinitions.length>0?t.calleesForDefinitions(n.calleeDefinitions):{available:!0,callees:kr(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 Tr(e){return new Map(e.map(t=>[t.symbolId,[]]))}function kr(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Ta(e){return new Map(e.map(t=>[t.symbolId,null]))}function Si(e,t,n){let r=0,i=0;return O("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 sy(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function Du(){return tM(new URL("./rust-semantic-worker.js",import.meta.url))}function Pu(e){return e.available?{available:!0}:{available:!1,reason:e.reason}}function Mu(e){return e.available?"rust-analyzer binary path is unavailable.":e.reason}function Tu(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 vi(e,t){return ir(e)??t}function ka(e,t){if(!e)return t;let n=Number(e);return Number.isInteger(n)&&n>=0?n:t}import{existsSync as dM}from"fs";import{deserializeSCIP as mM,SymbolRole as fM}from"@c4312/scip";var ku=new WeakMap;function cy(e,t){let n=t.filter(pM);if(n.length===0)return new Map;let r=!1,i=0,o=0;return O("rust.scip-occurrence.callees",()=>{let s=yM(e);if(r=!!s,!s)return new Map;let a=new Map;for(let c of n){let l=gM(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 pM(e){return!(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||!e.isFunctionLike||e.leaf==="main"||Xe(e.symbol))}function gM(e,t,n){let r=te(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)||!hM(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 hM(e,t){let n=ay(e),r=ay(t);if(n.size!==r.size)return!1;for(let[i,o]of n)if(r.get(i)!==o)return!1;return!0}function ay(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 yM(e){if(ku.has(e))return ku.get(e)??null;let t=bM(e);return ku.set(e,t),t}function bM(e){if(!e.generation.indexPath||!dM(e.generation.indexPath))return null;try{let t=Ue(e).filter(o=>o.symbol.startsWith("rust-analyzer ")&&o.relativePath.endsWith(".rs")&&o.isFunctionLike),n=new Map(t.map(o=>[o.symbol,o])),r=mM(ei(e.generation.indexPath,{inputKind:"SCIP occurrence-callee index",maxBytes:Zr})),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&fM.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:Xe(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 Fa=class{sessions=new WeakMap;getOrCreate(t,n,r){let i=SM(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 SM(e,t){return`${e.config.projectRoot}:${t}-workspace`}import{randomUUID as zM}from"crypto";import{existsSync as qM}from"fs";import{dirname as KM}from"path";function ly(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(typeof t.available!="boolean"||t.dependencyAvailable!==void 0&&typeof t.dependencyAvailable!="boolean"||t.tsconfigPath!==void 0&&typeof t.tsconfigPath!="string"||t.tsconfigPaths!==void 0&&(!Array.isArray(t.tsconfigPaths)||!t.tsconfigPaths.every(n=>typeof n=="string"))||t.resolvedBinary!==void 0&&typeof t.resolvedBinary!="string"||t.note!==void 0&&typeof t.note!="string")return null;if(t.available===!0){if(t.reason!==void 0)return null}else if(typeof t.reason!="string"||t.reason.length===0)return null;return t}import{performance as xe}from"perf_hooks";function Wt(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}import my from"path";import{realpathSync as uy}from"fs";function vM(e,t){return e.getReferences().map(n=>{let r=n.getNode();return Aa(r,t)})}function CM(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function fy(e,t,n,r){let i=[];for(let o of CM(e))for(let s of vM(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 Ci(i)}function py(e,t,n,r){let i=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();xi(r,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||i.push({location:Aa(a,r),node:a}))}return i}function Aa(e,t){let n=e.getSourceFile(),r=n.getLineAndColumnAtPos(e.getStart());return{file:xi(t,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function Fu(e,t,n){let r=e.getSourceFile(),i=Nu(r,e),o=e.getText(),s=new RegExp(`\\b${Be(o)}\\b`,"g"),a=r.getFullText().split(`
70
- `),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 Ci(c.filter(l=>xi(n,my.join(n,l.file))===t))}function Au(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 Nu(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function Ci(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 xi(e,t){let n=e||process.cwd(),r=dy(n,t);if(r)return r;try{return dy(uy(n),uy(t))}catch{return null}}function dy(e,t){let n=my.relative(e,t).replace(/\\/g,"/");return!n||n===".."||n.startsWith("../")?null:n}function gy(e,t,n,r){let i=xM(t,r);return i.size===0?new Map:RM(e,n,i)}function xM(e,t){let n=new Map;for(let r of W(e,t)){let i=Y(r.symbol)??r.leaf;if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push(r)}return n}function RM(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of IM(e,o)){let a=n.get(s);if(!a)continue;let c=Nu(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 IM(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 EM=Gn("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function hy(e,t,n,r){let i=Bu(e,t),o=_u(i.get(r)??[],n);if(o)return o;let s=[];for(let a of i.values())for(let c of a)((c.leaf||Y(c.symbol)||"").includes(r)||c.symbol.includes(r))&&s.push(c);return _u(s,n)}function Ou(e,t,n,r){return _u(Bu(e,t).get(r)??[],n)}function yy(e,t){let n=new Map;for(let[r,i]of Bu(e,t)){let o=i[0];o&&n.set(r,o)}return n}function Bu(e,t){return EM.get(e,t,()=>{let n=new Map;for(let r of W(e,t)){let i=r.leaf||Y(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 _u(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 wM from"path";import{realpathSync as LM}from"fs";function by(e,t){let n=new Map,r=null,i=null,o=()=>(i??=me(e,{extensions:Ws}),i),s=()=>(r??=O("typescript.source-file-index",()=>DM(e.config.projectRoot,t,o()),()=>({projects:t.length,indexedDocuments:o().length})),r),a=c=>Xn(c)?Wt(n,c,()=>{let l=Sy(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&&$u(d,m)),m)return{project:u,sourceFile:m}}return null}):null;return{sourceFile:c=>a(c)?.sourceFile??null,sourceFileMatch:a,indexedTypeScriptLikeDocuments:o}}function DM(e,t,n){let r=t.map(({project:i})=>{let o=new Map;for(let s of i.getSourceFiles())$u(o,s);return{project:i,sourceFiles:o}});for(let i of n){let o=Sy(e,i);if(o)for(let s of r){if(s.sourceFiles.has(o))break;let a=s.project.addSourceFileAtPathIfExists(o)??null;if(a){$u(s.sourceFiles,a);break}}}return r}function $u(e,t){let n=ju(t.getFilePath());e.set(n,t);try{e.set(ju(LM(n)),t)}catch(r){if(!ot(r))throw r}}function Sy(e,t){try{return ju(ks(e,t,{inputKind:"indexed TypeScript source file"}).absolutePath)}catch(n){if(!ot(n))throw n;return null}}function ju(e){return wM.resolve(e)}function Hu(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function vy(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 ct from"path";var Uu=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function zu(e,t){let r=t?ct.dirname(ct.join(e,t)):e,i=ct.resolve(e);for(;r.startsWith(i);){for(let s of Uu){let a=ct.join(r,s);if(Do(a))return a}let o=ct.dirname(r);if(o===r)break;r=o}for(let o of Uu){let s=ct.join(e,o);if(Do(s))return s}return null}function Cy(e){let t=e.config.projectRoot,n=new Set(PM(t,e.config.semantic?.typescript?.tsconfigs)),r=me(e,{includeIgnored:!1,extensions:Ws});for(let i of r){let o=zu(t,i);o&&n.add(ct.resolve(o))}if(n.size===0){let i=zu(t);i&&n.add(ct.resolve(i))}return[...n].filter(i=>!xy(t,i)).sort((i,o)=>i.localeCompare(o))}function PM(e,t=[]){let n=new Set;for(let r of t){let i=ct.isAbsolute(r)?r:ct.join(e,r);Do(i)&&n.add(ct.resolve(i))}for(let r of MM(e))for(let i of Uu){let o=ct.join(r,i);Do(o)&&n.add(ct.resolve(o))}if(n.size===0){let r=zu(e);r&&n.add(ct.resolve(r))}return[...n].filter(r=>!xy(e,r)).sort((r,i)=>r.localeCompare(i))}function MM(e){let t=ct.join(e,"package.json");if(!Do(t))return[];let n;try{n=JSON.parse(dt(t,"project package manifest"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>ip(e,i))}function xy(e,t){let n=ct.relative(e,t).replace(/\\/g,"/");return n.startsWith("..")||n.includes("/node_modules/")||n.startsWith("node_modules/")||n.includes("/dist/")||n.startsWith("dist/")}function qu(e,t){try{return e()}catch{t?.();return}}var TM=32;function Dy(e,t){let n=O("typescript.provider.load",()=>Vs());if(!n)return Js("ts-morph is not installed");let r=O("typescript.provider.tsconfig-discovery",()=>Cy(e));if(r.length===0)return Js("no tsconfig found");try{let i=O("typescript.provider.project-bundles",()=>kp(n,r),()=>({tsconfigs:r.length}));return kM(e,n,i)}catch(i){return Js(i instanceof Error?i.message:String(i),r[0],r)}}function kM(e,t,n,r={}){return O("typescript.provider.construct",()=>new Ku(e,t,n),()=>({tsconfigs:n.length,reusedProjects:r.reusedProjects===!0}))}var Ku=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=rp(t.config.projectRoot),this.sourceFiles=by(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 Wt(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let r=AM();return O("typescript.import-usage.file",()=>this.importUsageForSourceFile(t,n,r),()=>({file:t,...r}))})}referencesFor(t){return Wt(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);return this.referencesForDefinitionNode(t,n)})}referencesForDefinitions(t,n={}){let r=new Map,i=Ne(),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=>!Iy(u));if(a.length>=TM){let u=this.referencesForDefinitionsBySymbolScan(a);if(u.incompleteFiles.size===0)for(let d of a){let m=u.references.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,m),r.set(d.symbolId,m)}if(s=o.filter(d=>Iy(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=Ey();O("typescript.references-map.file",()=>{let f=this.definitionNodesForFile(u);for(let p of d){i&&(m.cacheMisses+=1);let g=f.get(p.symbolId)??null;i&&(g?m.nodeHits+=1:m.nodeMisses+=1);try{let h=this.referencesForDefinitionNode(p,g,i?m:void 0);this.referencesCache.set(p.symbolId,h),r.set(p.symbolId,h)}catch{m.preciseSearchFailures+=1,l.push(p)}}},()=>({relativePath:u,definitions:d.length,...wy(m)}))}if(l.length>0){let u=this.referencesForDefinitionsBySymbolScan(l);if(u.incompleteFiles.size===0)for(let d of l){let m=u.references.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,m),r.set(d.symbolId,m)}}return r}referenceFragmentsForFiles(t){let n=Ue(this.db).filter(s=>Xn(s.relativePath)),r=t.filter(s=>this.sourceFiles.sourceFile(s)!==null),i=this.referencesForDefinitionsBySymbolScan(n,r),o=r.filter(s=>!i.incompleteFiles.has(s));return Fp(n,i.references,o)}referencesForDefinitionsBySymbolScan(t,n){let r=Ne(),i=Ey(),o=new Map,s=new Set,a=new Set(t.map(l=>l.symbolId)),c=new Map(t.map(l=>[l.symbolId,l]));for(let l of t)o.set(l.symbolId,[]);return O("typescript.references-map.inverted-scan",()=>{let l=r?xe.now():0,u=n?this.packageImportReferencesForFiles(n):this.packageImportReferences();for(let b of t){let S=u.get(b.symbolId)??[];if(S.length>0){let y=o.get(b.symbolId)??[];y.push(...S),o.set(b.symbolId,y)}r&&(i.packageReferenceCount+=S.length)}r&&(i.packageRefsMs+=xe.now()-l);let d=new Map,m=new Map,f=this.hierarchyTargetsForDefinitions(t),p=new Set(t.map(b=>b.leaf).filter(Boolean)),g=r?xe.now():0;for(let b of n??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(b))continue;let S=this.sourceFiles.sourceFile(b);if(!S)continue;r&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(S,b,a,c,f,p,d,m,o,r?i:void 0)||s.add(b)}r&&(i.scanMs+=xe.now()-g);let h=r?xe.now():0;this.addHierarchyMemberReferences(t,o,r?i:void 0),r&&(i.hierarchyMs+=xe.now()-h);for(let[b,S]of o){let y=Ci(S);o.set(b,y),r&&(i.referenceCount+=y.length)}},()=>({definitions:t.length,...wy(i)})),{references:o,incompleteFiles:s}}addReferencesFromSourceFileScan(t,n,r,i,o,s,a,c,l,u){let d=this.compilerCheckerForSourceFile(t),m=t.compilerNode,f=OM(t),p=!0,g=h=>{if(this.tsMorph.ts.isIdentifier(h)){if(u&&(u.identifiers+=1),!s.has(h.text)&&!f.has(h.text)){this.tsMorph.ts.forEachChild(h,g);return}let b=this.compilerReferenceSymbol(d,h,u,()=>{p=!1});if(b){let S;a.has(b)?S=a.get(b)??null:(S=this.referenceDefinitionFromCompilerSymbol(b),a.set(b,S)),u&&(S?u.targetHits+=1:u.targetMisses+=1);let y=Wt(c,b,()=>this.compilerSymbolKeys(b)),E=null,I=null,v=S&&r.has(S.symbolId)?i.get(S.symbolId):void 0;if(v&&(E=Na(m,h),!Ry(v,n,E))){let x=m.getLineAndCharacterOfPosition(h.getStart(m));I={file:n,line:x.line,column:x.character};let C=l.get(v.symbolId)??[];C.push(I),l.set(v.symbolId,C),u&&(u.requestedHits+=1)}for(let x of y)for(let C of o.get(x)?.values()??[]){if(E??=Na(m,h),Ry(C,n,E))continue;if(!I){let w=m.getLineAndCharacterOfPosition(h.getStart(m));I={file:n,line:w.line,column:w.character}}let L=l.get(C.symbolId)??[];L.push(I),l.set(C.symbolId,L),u&&(u.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(h,g)};return g(m),p}hierarchyTargetsForDefinitions(t){let n=new Map;for(let 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)),f={definition:o,location:{file:o.relativePath,line:m.line,column:m.character}},p=n.get(o.symbolId)??[];for(let h of this.hierarchyMemberSymbols(l,c,u))if(h!==u)for(let b of this.compilerSymbolLocations(h))p.push(b),r&&(r.hierarchyReferences+=1);n.set(o.symbolId,p);let g=this.hierarchyRootMemberSymbols(l,c,u);for(let h of g){let b=i.get(h)??new Map;b.set(o.symbolId,f),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=xi(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,i){r&&(r.symbolLookups+=1);let o=qu(()=>t.getSymbolAtLocation(n),i);if(o){if((o.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return o;try{return r&&(r.aliasResolutions+=1),t.getAliasedSymbol(o)}catch{return i?.(),o}}}calleesFor(t){if(this.calleesCache.has(t.symbolId))return this.calleesCache.get(t.symbolId)??[];let n=Wt(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath));if(n.incompleteSymbolIds.has(t.symbolId))throw new Error(`TypeScript callee evidence is incomplete for ${t.symbol}.`);let r=n.callees.get(t.symbolId)??[];return this.calleesCache.set(t.symbolId,r),r}calleesForDefinitions(t){let n=new Map,r=new Map;for(let i of t){if(this.calleesCache.has(i.symbolId)){n.set(i.symbolId,this.calleesCache.get(i.symbolId)??[]);continue}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){if(c.incompleteSymbolIds.has(l.symbolId))continue;let u=c.callees.get(l.symbolId)??[];this.calleesCache.set(l.symbolId,u),n.set(l.symbolId,u)}}return n}referencesForDefinitionNode(t,n,r){let i=r?xe.now():0,o=this.packageImportReferencesForDefinition(t);if(r&&(r.packageRefsMs+=xe.now()-i,r.packageReferenceCount+=o.length),!n)return o;let s=r?xe.now():0,a=fy(n,t,o,this.db.config.projectRoot);return r&&(r.semanticRefsMs+=xe.now()-s,r.referenceCount+=a.length),a}signatureFor(t){return Wt(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 Ly(c)}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${Ly(o)}`})}importUsageForSourceFile(t,n,r){let i=[],o=new Map;for(let s of n.getImportDeclarations()){r.declarations+=1;let a=vl(this.db,t,s.getModuleSpecifierValue()),c=s.getImportClause()?.isTypeOnly()??!1;for(let l of Gu(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||NM(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:Aa(s,this.db.config.projectRoot),node:s}),r.matchedReferences+=1;break}}}),i.map(s=>s.typeOnlyDeclaration?FM(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;try{i=r.identifier?r.identifier.findReferences():[]}catch{let s=r.identifier?Fu(r.identifier,t,this.db.config.projectRoot):[];return{importer:t,sourcePath:n,importedName:r.importedName,localName:r.localName,kind:r.kind,isTypeOnly:r.isTypeOnly,isUsed:r.isTypeOnly||s.length>0,isTypeUsed:r.isTypeOnly,isValueUsed:!r.isTypeOnly&&s.length>0,references:s}}let o=[];for(let s of i)for(let a of py(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=>!Au(c.node)),s=i.some(c=>Au(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=Hu(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,Ci(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,Ci(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=Hu(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of Gu(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=Fu(a.identifier,r,this.db.config.projectRoot);l.length>0&&HM(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 vy(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?vl(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,f=this.indexedDefinitionByLeaf(c,d);if(!f)continue;let p=r.get(m);p||(p=new Set,r.set(m,p)),p.add(f.symbolId)}}}indexedDefinitionByLeaf(t,n){return Wt(this.indexedDefinitionLeafCache,t,()=>yy(this.db,t)).get(n)??null}nodeForDefinition(t){return Wt(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return Wt(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?gy(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?xe.now():0,s=t.declarations??[];n&&(n.declarationsMs+=xe.now()-o,n.declarationChecks+=s.length);for(let a of s){let c=n?xe.now():0,l=a.getSourceFile(),u=xi(this.db.config.projectRoot,l.fileName),d=l.getLineAndCharacterOfPosition(a.getStart(l)).line;if(n&&(n.declarationLocationMs+=xe.now()-c),!u||this.db.isIgnored(u))continue;let m=n?xe.now():0,f=this.compilerDeclarationName(a),p=r?Ou(this.db,u,d,i)??(f&&f!==i?Ou(this.db,u,d,f):null):hy(this.db,u,d,i);if(n&&(n.indexedLookupMs+=xe.now()-m),p)return{symbolId:p.symbolId,symbol:p.symbol,file:p.relativePath,line:p.startLine}}return null}compilerDeclarationName(t){let n=t.name;return n&&this.tsMorph.ts.isIdentifier(n)?n.text:null}calleeMapForFile(t,n){let r=Ne(),i=0,o=0,s=0,a=0,c=0,l=0,u=0,d=0,m=r?$M():void 0;return O("typescript.callee-map.file",()=>{let f=r?xe.now():0,p=this.sourceFiles.sourceFile(t);if(r&&(c=Math.round(xe.now()-f)),!p)return{callees:new Map,incompleteSymbolIds:new Set};let g=r?xe.now():0,h=W(this.db,t).sort((L,w)=>L.startLine-w.startLine||w.endLine-L.endLine);if(r&&(l=Math.round(xe.now()-g)),i=h.length,h.length===0)return{callees:new Map,incompleteSymbolIds:new Set};let b=new Map,S=new Set,y=r?xe.now():0,E=this.compilerCheckerForSourceFile(p),I=p.compilerNode;r&&(u=Math.round(xe.now()-y));let v=new Map,x=L=>{if(this.tsMorph.ts.isCallExpression(L)||this.tsMorph.ts.isNewExpression(L)){r&&(o+=1);let w=this.semanticCalleeForCallNode(E,I,h,L,v,n,S,m);w&&(r&&(s+=1),_M(b,w.callerId,w.target))}this.tsMorph.ts.forEachChild(L,x)},C=r?xe.now():0;x(I),r&&(d=Math.round(xe.now()-C));for(let[L,w]of b)b.set(L,UM(w));return a=b.size,{callees:b,incompleteSymbolIds:S}},()=>({relativePath:t,definitions:i,callNodes:o,resolvedCallees:s,outputRows:a,requestedDefinitions:n?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:u,traversalMs:d,...m?jM(m):{}}))}semanticCalleeForCallNode(t,n,r,i,o,s,a,c){let l=c?xe.now():0,u=BM(r,Na(n,i));if(c&&(c.callerLookupMs+=xe.now()-l),!u)return null;if(s&&!s.has(u.symbolId))return c&&(c.skippedUnrequestedCallers+=1),null;let d=i.expression,m=this.compilerSymbolForExpression(t,d,c);m.incomplete&&a?.add(u.symbolId);let f=m.symbol,p=null;if(f)if(c&&(c.targetSymbolHits+=1),o.has(f))c&&(c.compilerSymbolCacheHits+=1),p=o.get(f)??null;else{c&&(c.compilerSymbolCacheMisses+=1);let g=c?xe.now():0;p=this.definitionFromCompilerSymbol(f,c),c&&(c.targetLookupMs+=xe.now()-g),o.set(f,p)}else c&&(c.targetMisses+=1);return p?{callerId:u.symbolId,target:{symbol:p.symbol,file:p.file,line:p.line,callsiteLine:Na(n,i)}}:null}compilerSymbolForExpression(t,n,r){let i=!1,o=r?xe.now():0,s=qu(()=>t.getSymbolAtLocation(n),()=>{i=!0});if(r&&(r.expressionSymbolMs+=xe.now()-o),s)return{symbol:s,incomplete:!1};r&&(r.typeFallbacks+=1);let a=!1,c=r?xe.now():0,l=qu(()=>t.getTypeAtLocation(n).getSymbol(),()=>{a=!0});return r&&(r.typeSymbolMs+=xe.now()-c),{symbol:l,incomplete:!l&&(i||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 Gu(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 FM(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 AM(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function NM(e){for(let t=e;t;t=t.getParent())if(t.getKindName()==="ImportDeclaration")return!0;return!1}function _M(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function OM(e){let t=new Set;for(let n of e.getImportDeclarations())for(let r of Gu(n))r.localName&&t.add(r.localName);return t}function BM(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 Na(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line}function Ry(e,t,n){return t===e.relativePath&&n>=e.startLine&&n<=e.endLine}function Iy(e){return e.symbol.includes("#")?Bt(e.symbol)==="type"&&e.relativePath.endsWith(".d.ts"):!1}function $M(){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 jM(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 Ey(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0,preciseSearchFailures:0,hierarchyDefinitions:0,hierarchyFamilies:0,hierarchyReferences:0,hierarchyMs:0}}function wy(e){return{...e,scanMs:Math.round(e.scanMs),packageRefsMs:Math.round(e.packageRefsMs),semanticRefsMs:Math.round(e.semanticRefsMs),hierarchyMs:Math.round(e.hierarchyMs)}}function HM(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function UM(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 Ly(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var GM=12e4,WM=5;function ky(e,t,n={}){let r=new Wu(e,n),i=null,o=null,s=process.env.CODEBASEIQ_SKIP_WATCH_SERVICE==="1",a=()=>(i??=Dy(e,t),i),c=(d,m,f)=>{if(s)return f();try{return m(r.request(d))}catch{return s=!0,f()}},l=(d,m)=>c({kind:"references",definitions:[...d],...m?.exact?{exact:!0}:{}},f=>Ty(f),()=>a().referencesForDefinitions?.(d,m)??new Map(d.map(f=>[f.symbolId,a().referencesFor(f)]))),u=d=>c({kind:"callees",definitions:[...d]},m=>Ty(m),()=>a().calleesForDefinitions?.(d)??new Map(d.map(m=>[m.symbolId,a().calleesFor(m)])));return{language:"typescript",availability:()=>(o??=c({kind:"availability"},YM,()=>a().availability()),o),importUsage:d=>c({kind:"import-usage",file:d},m=>m,()=>a().importUsage(d)),referencesFor:d=>Py(l([d]),d,"reference"),referencesForDefinitions:l,referenceFragmentsForFiles:d=>c({kind:"reference-fragments",files:[...d]},m=>JM(m),()=>a().referenceFragmentsForFiles?.(d)??new Map),calleesFor:d=>Py(u([d]),d,"callee"),calleesForDefinitions:u,signatureFor:d=>c({kind:"signature",definition:d},XM,()=>a().signatureFor(d)),dispose:()=>i?.dispose?.()}}function Py(e,t,n){if(!e.has(t.symbolId))throw new Error(`TypeScript ${n} evidence is incomplete for ${t.symbol}.`);return e.get(t.symbolId)}var Wu=class{constructor(t,n={}){this.db=t;this.runtime=n.runtime??ZM,this.timeoutMs=n.timeoutMs??QM(),this.mailboxLimits=n.mailboxLimits??{},this.cacheDir=KM(t.config.dbPath),this.projectRoot=_f(t.config.projectRoot)}db;runtime;timeoutMs;cacheDir;projectRoot;mailboxLimits;request(t){let n=Bf(this.cacheDir),r=Xf(this.cacheDir),i=ml(n.statePath);if(!My(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??tn)()+this.timeoutMs,l=Gf(),u=Wi("typescript-semantic-v4",{generation:o,profileEnvironment:l,request:t}),d=Vi(u),m=Fs(r,{mailboxVersion:ii,operationKey:u,clientId:this.runtime.randomId(),enqueuedAtMs:s,deadlineAtMs:a,protocolVersion:As,id:d,generation:o,profileEnvironment:l,request:t},{nowMs:s,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??tn)()<=c;){if(qM(m.responsePath))return VM(en(m.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript semantic mailbox response"}),d,o,u);let f=ml(n.statePath);if(!My(f,this.projectRoot,this.runtime))throw new Error("TypeScript semantic service stopped while processing a request.");this.runtime.sleep(WM)}throw new Error(`TypeScript semantic service timed out after ${this.timeoutMs}ms.`)}};function My(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null;return e!==null&&e.projectRoot===t&&e.typescriptSemantic?.protocolVersion===As&&n.isProcessAlive(e.pid)&&(!e.processIdentity||r!=null&&ni(e.processIdentity,r))}function VM(e,t,n,r){let i=JSON.parse(e);if(i.protocolVersion!==As||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 Ty(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid numeric map.");return new Map(e)}function JM(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid string map.");return new Map(e)}function YM(e){let t=ly(e);if(!t)throw new Error("TypeScript semantic service wrote invalid availability.");return t}function XM(e){if(e!==null&&typeof e!="string")throw new Error("TypeScript semantic service wrote an invalid signature.");return e}function QM(){let e=Number(process.env.SCIP_TYPESCRIPT_SEMANTIC_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:GM}var ZM={now:Date.now,monotonicNow:tn,randomId:zM,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:qn,readProcessIdentity:xn};var Vu=new Fa;jf({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>Vu.clear(e)});Hf({name:"semantic-provider",close:e=>Vu.clear(e)});function Fr(e,t){let n=Ge(t)??"typescript";return Vu.getOrCreate(e,n,()=>n==="rust"?oy(e.config.projectRoot,{sourceImportUsageResolver:{importUsageFacts:r=>xh(e,r)},calleeSymbolResolver:Ch(e),sourceZeroCalleeOracle:r=>eT(e,r),scipOccurrenceCalleeOracle:r=>cy(e,r)}):ky(e,t))}function Ge(e){return e?ye(e)==="rust"?"rust":Xn(e)?"typescript":null:"typescript"}function eT(e,t){let n=te(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 tT=/^[A-Za-z_][A-Za-z0-9_]*$/,Fy=/\bDefault::default\b/g,nT=/^\.\.\s*Default::default\b/;function Ay(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=iT(t.symbol);if(!r)return null;let i=Gs(e,[t.symbolId]);if(i.length===0)return null;let o=new RegExp(`(^|[^A-Za-z0-9_])${Be(r)}::default\\b`,"g"),s=new RegExp(`(^|[^A-Za-z0-9_])${Be(r)}\\s*$`),a=rT(e,t.symbolId),c=[];for(let l of i){let u=oT(e,l.relative_path,n);if(u===null)return null;let d=u.split(/\r?\n/),m=0,f=[],p=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}),p+=1;for(let E=0;E<b.length;E+=1){let I=nT.exec(b.slice(E));if(I){if(a&&f.includes(m)){let x=E+I[0].lastIndexOf("default");c.push({file:l.relative_path,line:g,column:x}),S.add(x),p+=1}E+=I[0].length-1;continue}let v=b[E];if(v==="{"){let x=s.test(b.slice(0,E));m+=1,x&&f.push(m);continue}if(v==="}")for(m=Math.max(0,m-1);f.length>0&&f[f.length-1]>m;)f.pop()}for(Fy.lastIndex=0;y=Fy.exec(b);){let E=y.index+9;if(!S.has(E))return null}}if(p===0)return null}return wa(c)}function rT(e,t){return e.get("SELECT 1 AS present FROM mentions WHERE symbol_id = ? AND role = 1 LIMIT 1",t)?.present===1}function iT(e){let t=/impl#\[([^\]]+)\]\[Default\]default\(\)\./.exec(e)?.[1]??null;return!t||!tT.test(t)?null:t}function oT(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:sT(e,t);return n.set(t,i),i}function sT(e,t){try{return it(e.config.projectRoot,t,{inputKind:"indexed Rust source file"})}catch(n){if(!ot(n))throw n;return null}}var _a=new WeakMap;function jy(e){_a.delete(e)}function Hy(e){let t=_a.get(e);return{incompleteSymbolIds:new Set(t?.incompleteSymbolIds),unavailableSymbolIds:new Set(t?.unavailableSymbolIds)}}function Qu(e,t){if(t.incompleteSymbolIds.size===0&&t.unavailableSymbolIds.size===0)return;let n=_a.get(e)??{incompleteSymbolIds:new Set,unavailableSymbolIds:new Set};for(let r of t.incompleteSymbolIds)n.incompleteSymbolIds.add(r);for(let r of t.unavailableSymbolIds)n.unavailableSymbolIds.add(r);_a.set(e,n)}var aT="typescript-import-usage-v1",cT="typescript-signatures-v1",Yu=ke("semantic-prefetched-callees",{clearGroups:["whole-project","source-file","semantic-provider"]}),Ny=Ji({kind:"semantic-import-usage",invalidation:Ye("semantic-import-usage"),serialize:e=>JSON.stringify(e),deserialize:Xy}),_y=Ji({kind:"semantic-signatures",invalidation:Ye("semantic-signatures"),serialize:e=>JSON.stringify(e),deserialize:hT}),Oy=Rt({kind:"typescript-import-usage",invalidation:Ye("typescript-import-usage"),serialize:e=>JSON.stringify(e),deserialize:Xy}),By=Rt({kind:"typescript-signatures",invalidation:Ye("typescript-signatures"),serialize:e=>JSON.stringify(e),deserialize:yT});function $t(e){let t=new Map,n=new Set;return{capability:(r,i)=>Qy(e,r,i),importUsage:r=>uT(e,r),references:r=>qy(e,r),materializeReferences:(r,i)=>Gy(e,r,t,n,i),callerMap:r=>dT(e,r,t,n),calleeMap:r=>Vy(e,r),signature:r=>pT(e,r)}}function lT(e,t){if(t.size===0)return;let n=Yu.get(e,()=>new Map);for(let[r,i]of t)n.set(r,[...i])}function Uy(e,t){if(!Yu.has(e))return{hits:[],misses:[...t]};let n=Yu.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 Mo(e,t){return $t(e).importUsage(t)}function uT(e,t){if(Ge(t)==="typescript"){let o="fallback",s=0,a=0,c=0,l=0;return O("typescript.import-usage.materialize",()=>{let u=eo(e,t,aT);if(u?.key){s=1;let m=Oy.read(e,t,u.key);if(m)return o="hit",a=1,m;c=1;let f=Mn(e,t);if(!f)return o="unavailable",[];let p=f.importUsage(t);return Oy.write(e,t,u.key,p),o="computed",p}l=1;let d=Mn(e,t);return d?(o="direct-fallback",d.importUsage(t)):(o="unavailable",[])},()=>({state:o,eligible:s,cacheHits:a,cacheMisses:c,fallbacks:l}))}let n=Yy(e,"semantic-import-usage",t);if(n){let o=Ny.read(e,t,n);if(o)return o}let r=Mn(e,t);if(!r)return[];let i=r.importUsage(t);return n&&Ny.write(e,t,n,i),i}function zy(e,t){return $t(e).references(t)}function qy(e,t){let n=Ju(e,t);if(n)return n;let r=Eh(e,t);if(r)return r;let i=Mn(e,t.relativePath);return i?i.referencesFor(t):[]}function Ky(e,t){let n=Tn(e,t),r=n.incompleteSymbolIds.size+n.unavailableSymbolIds.size;if(r>0)throw new Error(`Exact semantic caller evidence is incomplete for ${r} definition(s).`);return n.callers}function Tn(e,t,n=r=>Fr(e,r)){let r=new Map,i=new Set,o=new Set,s=new Map;for(let c of t){let l=Ge(c.relativePath);if(!l)continue;let u;try{u=n(c.relativePath)}catch{o.add(c.symbolId);continue}if(!u.availability().available){o.add(c.symbolId);continue}if(l==="typescript"){let d=s.get(u)??[];d.push(c),s.set(u,d);continue}Xu(e,r,c,qy(e,c))}for(let[c,l]of s){let u=Rl(e,l,n),d=u?.references??(c.referencesForDefinitions?c.referencesForDefinitions(l,{exact:!0}):new Map(l.map(m=>[m.symbolId,c.referencesFor(m)])));!u&&Ne()&&xl(e,l,d,n);for(let m of l){if(!d.has(m.symbolId)){i.add(m.symbolId);continue}Xu(e,r,m,d.get(m.symbolId)??[])}}let a={callers:r,incompleteSymbolIds:i,unavailableSymbolIds:o};return Qu(e,a),a}function dT(e,t,n=new Map,r=new Set){let i=new Map,o=Gy(e,t,n,r),s=0;return O("semantic.callers.from-references",()=>{for(let a of t)s+=Xu(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=In(e),s=[],a=[],c=[],l=0,u=0,d=0,m=0,f=0,p=0,g=0,h=0,b=0,S=0,y=0,E=0,I=[],v=new Map,x=t.filter(L=>Ge(L.relativePath)==="typescript"&&!n.has(L.symbolId)&&!r.has(L.symbolId)),C=Rl(e,x,L=>Fr(e,L));if(C){b=x.length,S=C.cacheHits,y=C.cacheMisses,E=C.computedFiles;for(let L of x)n.set(L.symbolId,C.references.get(L.symbolId)??[])}if(O("semantic.references.cache-scan",()=>{for(let[L,w]of Ra(t)){let R=[];for(let D of w)n.has(D.symbolId)?u+=1:r.has(D.symbolId)?h+=1:R.push(D);if(R.length===0){g+=1;continue}let P=mT(e,o,L);if(!P){for(let D of R)Ge(D.relativePath)||(l+=1),c.push(D);continue}p+=1;let _=tp(e,L,P);for(let D of R){let M=_.get(D.symbol)??null;if(M!==null){let F=fT(M);if(F){d+=1,n.set(D.symbolId,F);continue}m+=1}a.push({definition:D,cacheFingerprint:P})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:l,cacheHits:d,parseFailures:m,misses:a.length,unkeyed:c.length,inMemoryHits:u,incompleteInMemoryHits:h,fullyInMemoryFiles:g,cacheReadFiles:p})),a.length>0||c.length>0){I=[...c,...a.map(L=>L.definition)],v=O("semantic.references.compute-misses",()=>{let L=Oa(e,I,i);return f=L.size,L},()=>({definitions:I.length,misses:a.length,unkeyed:c.length,rows:f}));for(let L of I)v.has(L.symbolId)?(n.set(L.symbolId,v.get(L.symbolId)??[]),r.delete(L.symbolId)):r.add(L.symbolId);for(let{definition:L,cacheFingerprint:w}of a)v.has(L.symbolId)&&Qy(e,"semantic-references",L.relativePath).available&&s.push({relativePath:L.relativePath,symbol:L.symbol,projectFingerprint:w,payload:JSON.stringify(v.get(L.symbolId)??[])})}return s.length>0&&O("semantic.references.cache-write",()=>np(e,s),()=>({entries:s.length})),v.size>0&&xl(e,I,v,L=>Fr(e,L)),{definitions:t.length,inMemoryHits:u,incompleteInMemoryHits:h,cacheHits:d,misses:a.length,unkeyed:c.length,skippedUnsupportedLanguage:l,parseFailures:m,computed:f,incomplete:r.size,cacheWrites:s.length,fragmentDefinitions:b,fragmentCacheHits:S,fragmentCacheMisses:y,fragmentComputedFiles:E}}function mT(e,t,n){if(!t)return null;let r=Ge(n);return r==="typescript"?qt(JSON.stringify({kind:"semantic-references",language:r,schema:"typescript-references-v2-incomplete-scan",projectFingerprint:t})):r==="rust"?qt(JSON.stringify({kind:"semantic-references",language:r,engine:Mr(e.config.projectRoot),projectFingerprint:t})):null}function Oa(e,t,n={}){let r=Ne(),i=new Map,o=0,s=0,a=0,c=0,l=0,u=0,d=0,m=0,f=0;return O("semantic.references.provider-loop",()=>{let p=Ay(e,t),g=Ih(e,t),h=new Map,b=n.prefetchCallees?new Map:null,S=[];for(let E of t){let I,v=()=>(I??=Mn(e,E.relativePath),I);if(b){let w=v();if(w?.referencesAndCalleesForDefinitions){let R=b.get(w);R?R.push(E):b.set(w,[E]),f+=1}}let x=p.get(E.symbolId);if(x){a+=1,c+=x.length,Po(i,E.symbolId,x,r,w=>{d+=1,m+=w});continue}let C=g.get(E.symbolId);if(C){l+=1,u+=C.length,Po(i,E.symbolId,C,r,w=>{d+=1,m+=w});continue}let L=v();if(!L){r&&(s+=1);continue}if(r&&(o+=1),L.referencesForDefinitions){let w=h.get(L);w?w.push(E):h.set(L,[E])}else S.push({provider:L,definition:E})}let y=new Set;if(b)for(let[E,I]of b){if(!E.referencesAndCalleesForDefinitions)continue;let v=h.get(E)??[],x=E.referencesAndCalleesForDefinitions(v,I);y.add(E),lT(e,x.callees);for(let C of v){if(!x.references.has(C.symbolId))continue;let L=x.references.get(C.symbolId)??[];Po(i,C.symbolId,L,r,w=>{d+=1,m+=w})}}for(let[E,I]of h){if(y.has(E))continue;let v=E.referencesForDefinitions(I);for(let x of I){if(!v.has(x.symbolId))continue;let C=v.get(x.symbolId)??[];Po(i,x.symbolId,C,r,L=>{d+=1,m+=L})}}for(let{provider:E,definition:I}of S){let v=E.referencesFor(I);Po(i,I.symbolId,v,r,x=>{d+=1,m+=x})}return i},()=>({definitions:t.length,providerHits:o,providerMisses:s,rustDefaultFastPathRows:a,rustDefaultFastPathReferences:c,rustScipOccurrenceFastPathRows:l,rustScipOccurrenceFastPathReferences:u,prefetchCalleeDefinitions:f,definitionsWithReferences:d,referenceCount:m,rows:i.size}))}function Ba(e,t,n={}){let r=Oa(e,t,n),i=Wy(e,t,r);return Qu(e,i),{rows:r,...i}}function Po(e,t,n,r,i){e.set(t,n),r&&n.length>0&&i(n.length)}function Xu(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 fT(e){try{return JSON.parse(e)}catch{return null}}function $a(e,t,n){let r=Vy(e,t,n),i=Wy(e,t,r,n);return Qu(e,i),{rows:r,...i}}function Wy(e,t,n,r){let i=new Set,o=new Set;for(let s of t)if(!(n.has(s.symbolId)||!Ge(s.relativePath)))try{(r?r(s.relativePath):Fr(e,s.relativePath)).availability().available?i.add(s.symbolId):o.add(s.symbolId)}catch{o.add(s.symbolId)}return{incompleteSymbolIds:i,unavailableSymbolIds:o}}function Vy(e,t,n){let r=Ne(),i=new Map,o=0,s=0,a=0,c=0;return O("semantic.callees.provider-loop",()=>{let l=new Map,u=[];for(let d of t){let m=n?n(d.relativePath):Mn(e,d.relativePath);if(m&&!m.availability().available){r&&(s+=1);continue}if(!m){r&&(s+=1);continue}r&&(o+=1);let f=d;if(m.calleesForDefinitions){let p=l.get(m);p?p.push(f):l.set(m,[f])}else u.push({provider:m,definition:f})}for(let[d,m]of l){let f=d.calleesForDefinitions(m);for(let p of m){if(!f.has(p.symbolId))continue;let g=f.get(p.symbolId)??[];$y(i,p.symbolId,g,r,h=>{a+=1,c+=h})}}for(let{provider:d,definition:m}of u){let f=d.calleesFor(m);$y(i,m.symbolId,f,r,p=>{a+=1,c+=p})}return i},()=>({definitions:t.length,providerHits:o,providerMisses:s,definitionsWithCallees:a,calleeCount:c,rows:i.size}))}function $y(e,t,n,r,i){e.set(t,n),r&&n.length>0&&i(n.length)}function Jy(e,t){return $t(e).signature(t)}function pT(e,t){if(Ge(t.relativePath)==="typescript"){let s="fallback",a=0,c=0,l=0,u=0;return O("typescript.signature.materialize",()=>{let d=eo(e,t.relativePath,cT);if(d?.key){a=1;let f=By.read(e,t.relativePath,d.key)??{};if(Object.prototype.hasOwnProperty.call(f,t.symbol))return s="hit",c=1,f[t.symbol]??null;l=1;let p=Mn(e,t.relativePath);if(!p)return s="unavailable",null;let g=p.signatureFor(t);return By.write(e,t.relativePath,d.key,{...f,[t.symbol]:g}),s="computed",g}u=1;let m=Mn(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=Yy(e,"semantic-signatures",t.relativePath),r=gT(t);if(n){let s=_y.read(e,r,n);if(s)return s.signature}let i=Mn(e,t.relativePath);if(!i)return null;let o=i.signatureFor(t);return n&&_y.write(e,r,n,{signature:o}),o}function Yy(e,t,n){let r=In(e);if(!r)return null;let i=Ge(n);return i!=="rust"?null:qt(JSON.stringify({kind:t,language:i,engine:Mr(e.config.projectRoot),projectFingerprint:r}))}function gT(e){return`${e.relativePath}\0${e.symbol}`}function Xy(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:null}catch{return null}}function hT(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 yT(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 Qy(e,t,n){let r=Ge(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,...Fr(e,n).availability()}}catch(i){return{slot:t,language:r,available:!1,reason:i instanceof Error?i.message:String(i)}}}function Mn(e,t){if(!Ge(t))return null;let n=Fr(e,t);return n.availability().available?n:null}var ge={references:zy,referenceMap:Oa,referenceEvidenceMap:Ba,callerMap:(e,t)=>$t(e).callerMap(t),calleeMap:Zu,calleeEvidenceMap:Zy};function Zu(e,t,n={}){return Zy(e,t,n).rows}function Zy(e,t,n={}){let r=Ne(),i=new Map,o=Uy(e,t),s=[],a=[],c=0,l=0,u=0,d=0,m=0,f=0,p=0,g=new Set,h=new Set;for(let{definition:v,callees:x}of o.hits)m+=1,i.set(v.symbolId,x),x.length>0&&(f+=1,p+=x.length);let b=bT(e,o.hits);if(b.entries.length>0&&O("semantic.callees.prefetch-cache-write",()=>Sl(e,b.entries),()=>({entries:b.entries.length,sourceMissing:b.sourceMissing,skippedUnsupportedLanguage:b.skippedUnsupportedLanguage})),O("semantic.callees.cache-scan",()=>{for(let[v,x]of Ra(o.misses)){if(!Ge(v)){r&&(c+=x.length);continue}let C=se(e,v);if(!C){r&&(l+=x.length),a.push(...x);continue}let L=Nt(e,v,C),w=eb(e,v);if(!w){a.push(...x);continue}let R=ep(e,v,L,w);for(let P of x){let _=R.get(P.symbol)??null;if(_!==null){let D=vT(_);if(D){r&&(u+=1),i.set(P.symbolId,D);continue}r&&(d+=1)}s.push({def:P,contentHash:L,depsDigest:w})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:c,sourceMissing:l,cacheHits:u,parseFailures:d,misses:s.length,unkeyed:a.length,inMemoryHits:m,inMemoryRows:f,inMemoryCalleeCount:p,resultRows:i.size})),s.length===0&&a.length===0)return{rows:i,incompleteSymbolIds:g,unavailableSymbolIds:h};let S=[...a,...s.map(v=>v.def)],y=0,E=O("semantic.callees.compute-misses",()=>{let v=$a(e,S,n.resolveProvider);for(let x of v.incompleteSymbolIds)g.add(x);for(let x of v.unavailableSymbolIds)h.add(x);return y=v.rows.size,v.rows},()=>({definitions:S.length,misses:s.length,unkeyed:a.length,rows:y}));for(let[v,x]of E)i.set(v,x);let I=s.filter(v=>E.has(v.def.symbolId)&&$t(e).capability("semantic-callees",v.def.relativePath).available).map(v=>({relativePath:v.def.relativePath,symbol:v.def.symbol,contentHash:v.contentHash,depsDigest:v.depsDigest,payload:JSON.stringify(E.get(v.def.symbolId)??[])}));return I.length>0?O("semantic.callees.cache-write",()=>Sl(e,I),()=>({entries:I.length})):O("semantic.callees.cache-write-skip",()=>{},()=>({reason:"provider-unavailable",misses:s.length})),{rows:i,incompleteSymbolIds:g,unavailableSymbolIds:h}}function bT(e,t){let n=[],r=new Map,i=0,o=0;for(let{definition:s,callees:a}of t){if(!Ge(s.relativePath)){o+=1;continue}if(!r.has(s.relativePath)){let l=se(e,s.relativePath),u=l?eb(e,s.relativePath):null;r.set(s.relativePath,l&&u?{contentHash:Nt(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 ST="typescript-callees-v3-incomplete-scan";function eb(e,t){let n=Ge(t);if(n==="typescript")return eo(e,t,ST)?.key??null;let r=xT(e,t);return n==="rust"?qt(JSON.stringify({kind:"semantic-callees",language:n,engine:Mr(e.config.projectRoot),positionMapping:"nearby-leaf-v2-callsite-line",depsDigest:r})):r}function vT(e){try{return JSON.parse(e)}catch{return null}}var CT=Gn("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function xT(e,t){return CT.get(e,t,()=>{let r=[...$e(e).get(t)??[]].sort().map(i=>`${i}:${Nt(e,i,se(e,i))}`);return qt(r.join("|"))})}function JQ(e,t,n={}){let r=pe(e,t);if(!r)return[];let o=!_e(r.symbol)&&!e.isIgnored(r.relativePath)?[{relativePath:r.relativePath,line:r.startLine}]:[],s=Yn(e,r,{semantic:n.semantic,semanticEvidence:ge}).map(u=>({relativePath:u.file,line:u.line})),a=RT(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 RT(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=IT(t.symbol);if(n.length===0)return[];let r=[];for(let i of me(e,{extensions:[".rb"],includeIgnored:!1})){let o=se(e,i);if(!o)continue;let s=o.split(`
71
- `);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 IT(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{availableParallelism as l5}from"os";import{fileURLToPath as wf}from"url";import{existsSync as ja,readdirSync as rb}from"fs";import{join as To}from"path";var ET={files:new Set,pathPrefixes:[]},wT={reasonsByFile:new Map},ed=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,LT=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,ib=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],DT=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),PT=4,MT=ke("package-surface",{clearGroups:["whole-project"]}),TT=ke("package-operational-surface",{clearGroups:["whole-project"]});function ob(e){return MT.get(e,()=>FT(e.config.projectRoot))}function Fn(e,t){let n=ob(e);return n.files.has(t)?!0:n.pathPrefixes.some(r=>t.startsWith(r))}function sb(e,t){return ob(e).files.has(t)}function kT(e){return TT.get(e,()=>AT(e.config.projectRoot))}function ab(e,t){return kT(e).reasonsByFile.get(t)??[]}function FT(e){let t=new Set,n=[];for(let{manifest:r,packageRoot:i}of cb(e))for(let o of NT(r))mb(e,i,o,t,n);return t.size===0&&n.length===0?ET:{files:t,pathPrefixes:n}}function AT(e){let t=new Map;for(let{manifest:n,packageRoot:r}of cb(e)){let i=_T(n);for(let s of i)tb(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 OT(a))tb(e,r,c,`package script "${s}"`,t)}}return t.size===0?wT:{reasonsByFile:t}}function cb(e){let t=[],n=ub(e,"");return n&&t.push({manifest:n,packageRoot:""}),lb(e,"",t,0),t}function lb(e,t,n,r){if(r>=PT)return;let i=To(e,t);if(ja(i))for(let o of rb(i,{withFileTypes:!0})){if(!o.isDirectory()||DT.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=ub(e,s);a&&n.push({manifest:a,packageRoot:s}),lb(e,s,n,r+1)}}function ub(e,t){let n;try{n=it(e,To(t,"package.json"),{maxBytes:8*1024*1024,inputKind:"package manifest"})}catch(r){if(!ot(r))throw r;return null}try{let r=JSON.parse(n);return r&&typeof r=="object"?r:null}catch{return null}}function NT(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 db(e.exports,t),t}function _T(e){let t=e.bin;return typeof t=="string"?[t]:!t||typeof t!="object"?[]:Object.values(t).filter(n=>typeof n=="string")}function OT(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 tb(e,t,n,r,i){let o=new Set;mb(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 db(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))db(n,t)}function mb(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 nb(c))l!==""&&i.push(kn(t,l));return}let a=o.replace(LT,"");for(let c of nb(a)){c===a&&c===o&&r.add(kn(t,o));for(let l of ib)BT(e,r,t,c+l)}r.add(kn(t,o))}function nb(e){let t=[e];return ed.test(e)&&(t.push(e.replace(ed,"src/")),t.push(e.replace(ed,""))),t}function BT(e,t,n,r){let i=kn(n,r);if(t.add(i),!r.startsWith("src/")||ja(To(e,i)))return;let o=ib.find(u=>r.endsWith(u));if(!o)return;let s=r.slice(0,-o.length);$T(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 fb(e,n,c,`${l}${o}`))t.add(u)}function $T(e,t,n,r,i){let o=kn(n,`${r}/index${i}`);ja(To(e,o))&&t.add(o)}function fb(e,t,n,r){let i=To(e,t,n);if(!ja(i))return[];let o=[];for(let s of rb(i,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...fb(e,t,a,r)):s.isFile()&&s.name===r&&o.push(kn(t,a))}return o}function kn(e,t){return e?`${e}/${t}`:t}import{existsSync as td,readdirSync as jT}from"fs";import{dirname as HT,join as nd}from"path";var UT={rootFiles:new Set,sourcePrefixes:[]},zT=new Set([".git",".codebaseiq","node_modules","target"]),qT=6,KT=ke("rust-library-surface",{clearGroups:["whole-project"]});function pb(e,t,n){if(!n.endsWith(".rs")||!VT(GT(e),n))return!1;let r=W(e,n).find(i=>i.symbol===t);return r?JT(ie(e,n)[r.startLine]??""):!1}function GT(e){return KT.get(e,()=>WT(e.config.projectRoot))}function WT(e){let t=new Set,n=new Set;for(let r of YT(e)){let i=it(e,nd(r,"Cargo.toml"),{maxBytes:8388608,inputKind:"Cargo manifest"}),o=XT(i),s=kn(r,"src/lib.rs"),a=o?kn(r,o):!QT(i)&&At(e,s)?s:null;if(!a)continue;t.add(a);let c=HT(a).replaceAll("\\","/");n.add(c==="."?"":`${c}/`)}return t.size===0?UT:{rootFiles:t,sourcePrefixes:[...n].sort()}}function VT(e,t){return t.endsWith(".rs")?e.rootFiles.has(t)?!0:ZT(t)?!1:e.sourcePrefixes.some(n=>t.startsWith(n)):!1}function JT(e){return/^\s*pub\s+(?!\()/.test(e)}function YT(e){if(!td(e))return[];let t=[];return gb(e,"",t,0),t}function gb(e,t,n,r){let i=nd(e,t);if(td(i)&&(td(nd(i,"Cargo.toml"))&&n.push(t),!(r>=qT)))for(let o of jT(i,{withFileTypes:!0})){if(!o.isDirectory()||zT.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name;gb(e,s,n,r+1)}}function XT(e){let t=!1;for(let n of e.split(`
72
- `)){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 QT(e){let t=!1;for(let n of e.split(`
73
- `)){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 ZT(e){return/(?:^|\/)src\/main\.rs$/.test(e)||/(?:^|\/)src\/bin\//.test(e)||/(?:^|\/)(?:examples|tests|benches)\//.test(e)}function Ri(e){return J(e)==="barrel"}function yb(e){return e0.get(e,()=>{let n=me(e,{includeIgnored:!1}).filter(s=>{let a=J(s);return a==="entry"||a==="worker"});if(n.length===0)return new Set;let r=$e(e),i=new Set,o=new Set;for(;n.length>0;){let s=n.shift();if(!i.has(s)){i.add(s),J(s)==="barrel"&&o.add(s);for(let a of r.get(s)??[])i.has(a)||n.push(a)}}return o})}var e0=ke("live-barrels",{clearGroups:["whole-project"]});function rd(e,t){return yb(e).has(ht(t))}function bb(e){let t=yb(e);return me(e,{includeIgnored:!1}).filter(n=>Ri(n)&&!t.has(n)&&!t0(e,n))}function t0(e,t){let n=ht(t),r=Wn(e).forFile(n,{facts:!0}).facts?.callables;return r&&r.length>0?!0:(e.get(`SELECT COUNT(*) AS n
74
- FROM defn_enclosing_ranges der
75
- JOIN documents d ON d.id = der.document_id
76
- WHERE d.relative_path = ?
77
- AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function Qe(e,t){let n=ht(t),r=J(t);return r==="entry"||r==="worker"||id(n)||rd(e,n)}function Ii(e,t,n){let r=ht(n),i=[];Fn(e,r)&&i.push("package-surface-file"),i0(e,t,r)&&i.push("transitive-package-surface"),pb(e,t,r)&&i.push("rust-public-library"),p0(t,r)&&i.push("framework-entrypoint");let o=e.config.entryRoots;return o&&(o.files?.some(s=>ht(s)===r)&&i.push("configured-file"),o.pathPrefixes?.some(s=>r.startsWith(ht(s)))&&i.push("configured-path-prefix"),o.qualifiedVars?.some(s=>y0(t,s))&&i.push("configured-qualified-var"),o.symbolPatterns?.some(s=>{try{return Ms(s,"entryRoots.symbolPatterns entry").test(t)}catch{return!1}})&&i.push("configured-symbol-pattern")),i}function qe(e,t,n){return Ii(e,t,n).length>0}var n0=ke("package-surface-reachability",{clearGroups:["whole-project"]}),r0=ke("explicit-package-surface-reachability",{clearGroups:["whole-project"]});function i0(e,t,n){let r=o0(e).get(n);return r===void 0?!1:r===null||r.has(Y(t))}function Sb(e,t,n){let r=s0(e).get(n);return r===void 0?!1:r===null||r.has(Y(t))}function o0(e){return n0.get(e,()=>vb(e,t=>Fn(e,t)))}function s0(e){return r0.get(e,()=>vb(e,t=>sb(e,t)))}function vb(e,t){let n=new Map,r=[];for(let i of me(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 Xi(e,i)){if(!s.sourcePath||e.isIgnored(s.sourcePath))continue;let a=a0(o,s);a!==void 0&&c0(n,s.sourcePath,a)&&r.push(s.sourcePath)}}return n}function a0(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 c0(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 Cb=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),l0=new Set(["default","generateMetadata","generateStaticParams"]),u0=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),d0=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),m0=new Set(["load","actions","entries",...Cb]),f0=new Set(["default"]);function p0(e,t){let n=Y(e);return n===""?!1:xb(t)?Cb.has(n):Rb(t)?l0.has(n):Ib(t)?u0.has(n):Eb(t)?d0.has(n):wb(t)?m0.has(n):h0(t)?f0.has(n):!1}function id(e){return xb(e)||Rb(e)||Ib(e)||g0(e)||Eb(e)||wb(e)}function xb(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Rb(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Ib(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function g0(e){let t="(?:middleware|proxy|instrumentation)\\.(?:ts|js|mts|mjs)";return new RegExp(`^(?:src/)?${t}$`).test(e)||new RegExp(`(?:^|/)src/${t}$`).test(e)||new RegExp(`(?:^|/)(?:apps|services|packages)/[^/]+/(?:src/)?${t}$`).test(e)}function Eb(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function wb(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function h0(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function y0(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(hb(r)+"/")&&e.includes(hb(i)+".")}function hb(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function Lb(e,t,n={}){let r=new Map;if(t&&t.length===0)return r;let i=me(e,{includeIgnored:!1}),o=sn(e),s=t??Ue(e),a=new Set(s.map(l=>l.symbolId)),c=I0(s);return b0(e,r,i,o,a,c),S0(e,r,s,a),R0(e,r,i,o,a,c),n.semantic!==!1&&n.semanticEvidence&&w0(r,n.semanticEvidence.callerMap(e,E0(s))),r}function b0(e,t,n,r,i,o){for(let s of n){if(!ye(s))continue;let a=rn(e,s);if(a)for(let c of a){if(o&&!o.has(c.calleeLeaf))continue;let l=on(s,r.get(c.calleeLeaf)??[]);if(!l||l.length===0)continue;let u=Jn(e,s,l,c.memberAccess,c.calleeQualifier);u&&i.has(u.symbolId)&&u.file!==s&&od(t,u.symbolId,s)}}}function S0(e,t,n,r){let i=C0(n);for(let o of v0(e,r))e.isIgnored(o.relative_path)||x0(o,i.get(o.symbol_id))||od(t,o.symbol_id,o.relative_path)}function v0(e,t){return Gs(e,t?[...t]:void 0)}function C0(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 x0(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function R0(e,t,n,r,i,o){for(let s of n){if(ye(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&&od(t,u.symbolId,s)}}}function od(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function I0(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"?Y(n.symbol):"";r&&t.add(r)}return t.size>0?t:null}function E0(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function w0(e,t){for(let[n,r]of t){let i=e.get(n);i||(i=new Set,e.set(n,i));for(let o of r)i.add(o)}}function sd(e,t,n={}){return Lb(e,t,n)}function ko(e,t,n={}){return wp(e,t,n)}function Db(e,t,n={}){let r=sd(e,t,{semantic:n.semantic,semanticEvidence:n.semanticEvidence});return n.sourceFallback===!1?r:Ar(r,ko(e,t))}function Ar(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 Pb(e,t,n){let r=t.identifierResolution==="strict"?Cl:Ep,i=t.candidateNames?xp(t.candidateNames):null,o=0,s=0,a=0,c=0,l="";for(let u of t.paths)if(o+=1,l=u,!(!ye(u)&&!(t.includeVueSfc&&ap(u)))&&!e.isIgnored(u)&&!t.skipPath?.(u))try{if(i&&!Rp(se(e,u),i))continue;s+=1;let m=(p,g,h,b)=>{if(t.candidateNames&&!t.candidateNames.has(p))return;a+=1;let S=t.resolveTargets?t.resolveTargets({sourceFile:u,name:p,kind:g,defaultTargets:b}):b();for(let y of S)c+=1,n({sourceFile:u,name:p,target:y,occurrences:h,kind:g})},f=ui(e,u);for(let[p,g]of f)m(p,"identifier",g.length,()=>r(e,u,p));for(let p of si(e,u,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let g=p.kind==="cross-language-dispatch"?()=>Cl(e,u,p.name):()=>r(e,u,p.name);m(p.name,p.kind,p.occurrences,g)}}finally{t.afterPath?.(u),o%10===0&&O("source-reference-scan.progress",()=>{},()=>({scannedPaths:o,currentPath:l,candidateMatchedPaths:s,visitedNames:a,visitedHits:c}))}}function de(e){return e.endLine-e.startLine+1}function Mb(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:f=!1,sortByLocDesc:p=!1}=t,g=[],h=L0(e,{scope:n,files:r,requireFunctionLikeSymbol:u,requireCallableSymbol:d}),b=new Map,S=new Map,y=I=>{let v=b.get(I);if(v!==void 0)return v;let x=Qe(e,I);return b.set(I,x),x},E=I=>{let v=S.get(I);if(v!==void 0)return v;let x=J(I);return S.set(I,x),x};for(let I of h){let v=I.relativePath;if(e.isIgnored(v)||a&&y(v)||!D0(I,{requireFunctionLikeSymbol:u,requireCallableSymbol:d})||s!==void 0&&I.symbol===s)continue;let x=de(I);x<i||x>o||c&&P0(v)||l&&qe(e,I.symbol,v)||m&&Xe(I.symbol)||E(v)!=="test"&&(ai(I.symbol)||!f&&Bs(e,v,I.startLine)||g.push(I))}return p?g.sort((I,v)=>de(v)-de(I)):g}function L0(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=>W(e,r)):t.requireCallableSymbol?Qi(e,{scope:t.scope,symbolMatches:st,sqlPrefilter:"callable"}):t.requireFunctionLikeSymbol?Qi(e,{scope:t.scope,symbolMatches:_e,sqlPrefilter:"function-like"}):hp(e,t.scope)}function D0(e,t){return t.requireCallableSymbol?st(e.symbol):t.requireFunctionLikeSymbol?_e(e.symbol):e.isFunctionLike}function P0(e){return(e.split("/").pop()??"").includes("types")}var U=class{constructor(t){this.db=t}db;scopedDefinitions(t){return gp(this.db,t)}definitionsForFile(t){return W(this.db,t)}productionCallableDefinitions(t={}){return Mb(this.db,t)}calleeMap(t,n={}){return this.calleeEvidenceMap(t,n).rows}calleeEvidenceMap(t,n={}){return oo(this.db,t,{...n,semanticEvidence:ge})}crossFileCallerMap(t,n={}){return sd(this.db,t,{...n,semanticEvidence:ge})}sourceFallbackCallerFiles(t,n={}){return ko(this.db,t,n)}callerFileMap(t,n={}){return Db(this.db,t,{...n,semanticEvidence:ge})}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 me(this.db,{includeIgnored:!1}))if(ye(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(s=>[s.symbolId,s.symbol])),i=this.calleeEvidenceMap(t,n),o=new Set([...i.rows.entries()].filter(([s,a])=>{let c=r.get(s);return a.some(l=>l.symbol!==c)}).map(([s])=>s));for(let s of i.incompleteSymbolIds)o.add(s);for(let s of i.unavailableSymbolIds)o.add(s);return o}fileDependencyGraph(t){return $e(this.db,t)}fileKind(t){return J(t)}hasSuppressionComment(t){return Bs(this.db,t.relativePath,t.startLine)}sourceFiles(){return oi(this.db)}scanSourceReferences(t,n){Pb(this.db,t,n)}callableSignature(t){let n=Wn(this.db).forFile(t.relativePath,{facts:!0}).facts?.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};import{statSync as M0}from"fs";function Nr(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,...T0(e.generation.databasePath)}}function T0(e){try{let t=M0(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function k0(e,t){return Wl(e).filter(n=>F0({pattern:t,relativePath:n})).map(n=>({relativePath:n}))}function F0(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=Rn(n.pattern),i=Rn(n.relativePath);if(!/[*?]/.test(r))return i.includes(r);let o=r.includes("/")?r:`**/${r}`;return Ha(o.split("/"),i.split("/"))}function Ha(e,t){if(e.length===0)return t.length===0;let[n,...r]=e;return n==="**"?Ha(r,t)||t.length>0&&Ha(e,t.slice(1)):t.length===0||!A0(n??"",t[0]??"")?!1:Ha(r,t.slice(1))}function A0(e,t){let n="^";for(let r of e)r==="*"?n+="[^/]*":r==="?"?n+="[^/]":n+=N0(r);return n+="$",new RegExp(n).test(t)}function N0(e){return/[\\^$.*+?()[\]{}|]/.test(e)?`\\${e}`:e}function kb(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 Ua(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,f)=>Tb(f,a)-Tb(m,a)||r(m,f));let d=u[0]??l[0];s.push(d),c+=d.evidenceCharacters;for(let m of Fb(d))a.add(m.key);o.splice(o.indexOf(d),1)}return{selected:s,omitted:o.sort(r)}}function Tb(e,t){let n=Fb(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 Fb(e){return[...e.reasons.map(_0),...e.roles.map(t=>({key:`role:${t}`,weight:O0(t)})),{key:`file:${e.relativePath}`,weight:180},{key:`scope:${B0(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 _0(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 O0(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 B0(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}var Ab=64,Nb=12;function ad(e,t,n={}){if(t.length===0)throw new Error("The source search pattern must not be empty.");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=n.regexp?Ms(t,"source search pattern",n.ignoreCase?"iu":"u"):null,s=n.ignoreCase?t.toLocaleLowerCase():t,a=aa(e,{scope:n.scope}),c=[],l=[];for(let h of a.files){let b=h.relativePath,S=H0(h.text);if(S.length===0)continue;let y=h.freshness.semantic.state!=="stale"&&h.freshness.semantic.basis!=="no-compiler-document"?W(e,b):[],E=te(e,b)?.callables??[],I=0;for(let v=0;v<S.length;v+=1){let x=S[v]??"",C=x.endsWith("\r")?x.slice(0,-1):x;if(!(o?o.test(C):(n.ignoreCase?C.toLocaleLowerCase():C).includes(s)))continue;I+=1;let w=Ke(y,v),R=$0(E,v),P=w&&!De(w.symbol)?w:null,_=P?.startLine??R?.startLine??w?.startLine??v,D=P?.endLine??R?.endLine??w?.endLine??v,M=go(e,b,v,_,D);c.push({relativePath:b,focusLine:v,ownerSymbol:P?.symbol??null,ownerShort:P?N(P.symbol):R?.name??(w?N(w.symbol):null),ownerStartLine:M.startLine,ownerEndLine:M.endLine,fileKind:J(b),freshness:h.freshness})}I>0&&l.push({relativePath:b,matchingLines:I,returnedMatches:0,freshness:h.freshness})}c.sort(Ob);let u=c.length>Ab?_b(c,Ab):c,d=i===Number.MAX_SAFE_INTEGER?c:n.ranking?_b(c,i):c.slice(0,i),m=new Map(a.files.map(h=>[h.relativePath,h.text])),f=d.flatMap(h=>{let b=m.get(h.relativePath),S=b===void 0?null:j0(h.relativePath,b,h.focusLine,r);return S?[{...S,...h}]:[]}),p=new Map;for(let h of f)p.set(h.relativePath,(p.get(h.relativePath)??0)+1);for(let h of l)h.returnedMatches=p.get(h.relativePath)??0;let g=U0(l);return{pattern:t,mode:n.regexp?"regexp":"literal",identities:c,...u.length<c.length?{identityManifest:u}:{},identityCoverage:{mode:u.length===c.length?"complete":"bounded",returned:u.length,total:c.length,omitted:c.length-u.length},matches:f,matchingLines:c.length,matchingFiles:l.length,omittedMatches:Math.max(0,c.length-f.length),fileCoverage:l,scopeHints:g.slice(0,Nb),omittedScopeHints:Math.max(0,g.length-Nb),scannedFiles:a.files.length,textCoverage:{basis:"current-project-text-files",candidateFiles:a.candidateFiles,scannedTextFiles:a.files.length,scannedBytes:a.scannedBytes,skippedBinaryPaths:a.skippedBinaryPaths,skippedUnreadablePaths:a.skippedUnreadablePaths,skippedOversizedPaths:a.skippedOversizedPaths,semanticFiles:{aligned:a.files.filter(h=>h.freshness.semantic.state==="aligned").length,stale:a.files.filter(h=>h.freshness.semantic.state==="stale").length,unavailable:a.files.filter(h=>h.freshness.semantic.state==="unavailable").length}}}}function $0(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,r)=>n.endLine-n.startLine-(r.endLine-r.startLine)||n.startLine-r.startLine)[0]??null}function j0(e,t,n,r){let i=t.split(`
78
- `),o=t.endsWith(`
79
- `)?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(`
80
- `)}}function H0(e){if(e.length===0)return[];let t=e.split(`
81
- `);return e.endsWith(`
82
- `)&&t.pop(),t}function U0(e){let t=new Map;for(let n of e){let r=z0(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 z0(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}function _b(e,t){let n=e.map((i,o)=>({...i,priority:za(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=>za(a.fileKind)===i);r.push(...Ua(s,o,Number.MAX_SAFE_INTEGER,Ob).selected)}return r.map(({priority:i,sequence:o,evidenceCharacters:s,roles:a,reasons:c,symbols:l,behaviorSignals:u,...d})=>d)}function Ob(e,t){return za(e.fileKind)-za(t.fileKind)||+(t.ownerSymbol!==null)-+(e.ownerSymbol!==null)||e.relativePath.localeCompare(t.relativePath)||e.focusLine-t.focusLine}function za(e){switch(e){case"entry":case"source":case"worker":return 0;case"barrel":return 1;case"test":return 2}}var Bb=new WeakMap,$b=new WeakMap,jb=new WeakMap,Hb=new WeakMap,Ub=new WeakMap;function zb(e,t){let n=$b.get(e);n||(n=new Map,$b.set(e,n));let r=n.get(t);if(r)return r;let i=ae(e,t)?.rootNode;if(!i)return n.set(t,[]),[];let o=new Set;Vt(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=Ce(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"){W(e,t).some(d=>d.leaf==="Service")&&a.add(t);for(let d of s)(d.localName??d.importedName)==="Service"&&a.add(d.sourcePath)}}let c=ud([...a]).sort();return n.set(t,c),c}function sr(e,t,n={}){let i=rn(e,t)?.filter(f=>!n.ranges||n.ranges.some(p=>f.line>=p.startLine&&f.line<=p.endLine));if(!i)return{targets:[],unresolvedCallsites:0};let o=Ce(e,t).filter(f=>!!f.sourcePath),s=sk(se(e,t)??""),a=ae(e,t)?.rootNode??null,c=a?K0(a):qb(),l=new Map,u=sn(e),d=[],m=0;for(let f of i){if(!f.memberAccess)continue;let p=on(t,u.get(f.calleeLeaf)??[]);if(n.excludeIndexedTargets!==!1&&Jn(e,t,p,!0,f.calleeQualifier))continue;let g=f.calleeQualifier,h=ik(e,t,f,o);if(h){d.push(h);continue}let b=q0(e,t,f,o,G0(c,f.calleeQualifier,f.line));if(b.length>0){d.push(...b);continue}let S=W0(e,t,f);if(S.length>0){d.push(...S);continue}let y=g?s.get(g)??g:null,I=(y?ud(o.filter(x=>(x.localName??x.importedName)===y).map(x=>x.sourcePath)):[]).flatMap(x=>{let C=l.get(x);return C||(C=_t(e,x)??[],l.set(x,C)),C.filter(L=>L.name===f.calleeLeaf).map(L=>({file:x,callable:L}))});if(I.length!==1){m+=1;continue}let v=I[0];d.push({calleeLeaf:f.calleeLeaf,line:f.line,sourceFile:t,targetFile:v.file,targetStartLine:v.callable.startLine,targetEndLine:v.callable.endLine,resolution:"direct-import-receiver",strength:"candidate"})}return{targets:d,unresolvedCallsites:m}}function q0(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=ud(r.filter(u=>u.localName===s||u.importedName===s).map(u=>u.sourcePath));if(a.length!==1)return[];let c=a[0],l=X0(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 qb(){return{declarations:new Map,callbacks:[]}}function K0(e){let t=qb();return Vt(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(Vt(l,d=>{if(d.type!=="member_expression")return;let m=d.childForFieldName("object")??d.namedChild(0),f=d.childForFieldName("property")??d.namedChild(1);m?.type==="identifier"&&f?.text==="Service"&&u.add(m.text)}),u.size===1){let d=t.declarations.get(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;Vt(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 G0(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 W0(e,t,n){let r=n.calleeQualifier;if(!r||!/^[A-Za-z_$][\w$]*$/u.test(r))return[];let i=ae(e,t)?.rootNode;if(!i)return[];let o=V0(e,t,i,n.line,n.calleeLeaf,r),s=o?Y0(o,r):null;if(!s)return[];if(!J0(s))return[];let a=(_t(e,t)??[]).filter(f=>f.startLine<=s.startPosition.row&&f.endLine>=s.endPosition.row).sort((f,p)=>f.endLine-f.startLine-(p.endLine-p.startLine))[0];if(!a)return[];let c=W(e,t).filter(f=>f.isFunctionLike&&f.leaf===a.name);if(c.length!==1)return[];let l=c[0],u=Hb.get(e);u||(u=new Map,Hb.set(e,u));let d=`${l.symbol}\0${n.calleeLeaf}`,m=u.get(d);if(!m){let f=[];for(let p of Zi(e,l)){let g=ae(e,p.file)?.rootNode;if(!g)continue;let h=g.descendantsOfType("call_expression").filter(y=>y.startPosition.row>p.line||y.endPosition.row<p.line?!1:(y.childForFieldName("function")??y.namedChild(0))?.text.replace(/\s+/gu,"").replace(/<[^<>]*>$/u,"").match(/[A-Za-z_$][\w$]*$/u)?.[0]===l.leaf);if(h.length!==1)continue;let S=h[0].childForFieldName("arguments")?.namedChildren.find(y=>_r(y).type==="object");if(S)for(let y of _r(S).namedChildren){if(y.type==="shorthand_property_identifier"&&y.text===n.calleeLeaf){f.push(...qa(e,p.file,n.calleeLeaf,y,y));continue}if(y.type!=="pair")continue;let E=y.childForFieldName("key")??y.namedChild(0),I=y.childForFieldName("value")??y.namedChild(1);Ka(E?.text)!==n.calleeLeaf||!I||f.push(...qa(e,p.file,n.calleeLeaf,I,y))}}m=f.filter((p,g,h)=>h.findIndex(b=>b.file===p.file&&b.startLine===p.startLine&&b.endLine===p.endLine&&b.name===p.name)===g),u.set(d,m)}return m.map(f=>({calleeLeaf:f.name,line:n.line,sourceFile:t,targetFile:f.file,targetStartLine:f.startLine,targetEndLine:f.endLine,resolutionAlternativeCount:m.length,resolution:"factory-callback-member",strength:m.length===1?"exact":"candidate"}))}function V0(e,t,n,r,i,o){let s=jb.get(e);s||(s=new Map,jb.set(e,s));let a=s.get(t);if(!a){a=new Map;for(let c of n.descendantsOfType("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]}`,f=a.get(m);(!f||c.endIndex-c.startIndex<f.endIndex-f.startIndex)&&a.set(m,c)}}s.set(t,a)}return a.get(`${r}\0${o}\0${i}`)??null}function J0(e){return e.descendantsOfType("return_statement").some(t=>{let n=t.childForFieldName("argument")??t.namedChild(0);return!!(n&&_r(n).type==="object")})}function Y0(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&&Vt(r,o=>{o.type==="identifier"&&o.text===t&&(i=!0)}),i)return n}n=n.parent}return null}function qa(e,t,n,r,i){if(r.type==="identifier")return(_t(e,t)??[]).filter(c=>c.name===r.text).map(c=>({...c,file:t}));let o=cd(e,t,r.text);if(o.length>0)return o;if(!ld(r))return[];let a=(_t(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 X0(e,t,n){let r=Ub.get(e);r||(r=new Map,Ub.set(e,r));let i=`${t}\0${n}`,o=r.get(i);if(o)return o;let s=ek(e,t).flatMap(a=>Q0(e,a,t,n));return r.set(i,s),s}function Q0(e,t,n,r){let i=ae(e,t)?.rootNode,o=_t(e,t)??[];if(!i)return[];let s=tk(e,t,n);if(s.size===0)return[];let a=new Set,c=[],l=[],u=[];return Vt(i,m=>{if(Z0(m,s)){if(m.type==="pair"){let f=m.childForFieldName("key")??m.namedChild(0),p=m.childForFieldName("value")??m.namedChild(1);if(Ka(f?.text)!==r||!p)return;if(p.type==="identifier")a.add(p.text);else if(ld(p))c.push({name:r,startLine:m.startPosition.row,endLine:m.endPosition.row});else{let g=nk(e,t,p.text),h=cd(e,t,p.text);if(g.length>0)u.push(...g);else if(h.length>0)u.push(...h);else{let b=rk(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,f,p)=>p.findIndex(g=>g.file===m.file&&g.name===m.name&&g.startLine===m.startLine&&g.endLine===m.endLine)===f)}function Z0(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 ek(e,t){let n=Bb.get(e);n||(n=new Map,Bb.set(e,n));let r=n.get(t);if(r)return r;let i=new Set([t]),o=W(e,t).filter(a=>a.leaf==="Service"&&a.isTypeLike);for(let a of o)for(let c of Zi(e,a))i.add(c.file);let s=[...i].sort();return n.set(t,s),s}function tk(e,t,n){let r=new Set;Ft(t,n)&&r.add("Service");for(let i of Ce(e,t)){if(!i.sourcePath||!Ft(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 cd(e,t,n){let r=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(n.replace(/\s+/gu,""));if(!r)return[];let i=ae(e,t)?.rootNode;if(!i)return[];let o=Kb(i,r[1]),s=o?Gb(o):null;if(!s)return[];let a=s.childForFieldName("function")??s.namedChild(0),c=a?Wb(e,t,a.text):[];if(c.length!==1)return[];let l=c[0],u=ae(e,l.relativePath)?.rootNode;if(!u)return[];let d=Vb(u,l.startLine,l.endLine);if(!d)return[];let m=[];for(let f of d.descendantsOfType("return_statement")){let p=f.childForFieldName("argument")??f.namedChild(0);if(!p)continue;let g=_r(p);if(g.type==="object")for(let h of g.namedChildren){if(h.type==="shorthand_property_identifier"&&h.text===r[2]){for(let y of _t(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(!(Ka(b?.text)!==r[2]||!S))if(S.type==="identifier")for(let y of _t(e,l.relativePath)??[])y.name===S.text&&m.push({...y,file:l.relativePath});else ld(S)&&m.push({name:r[2],startLine:h.startPosition.row,endLine:h.endPosition.row,file:l.relativePath})}}return m.filter((f,p,g)=>g.findIndex(h=>h.file===f.file&&h.name===f.name&&h.startLine===f.startLine&&h.endLine===f.endLine)===p)}function nk(e,t,n){let r=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(n.replace(/\s+/gu,""));if(!r)return[];let i=ae(e,t)?.rootNode;if(!i)return[];let o=Kb(i,r[1]),s=o?Gb(o):null,a=s?.childForFieldName("function")??s?.namedChild(0),c=a?Wb(e,t,a.text):[];if(c.length!==1||!s)return[];let l=c[0],u=ae(e,l.relativePath)?.rootNode;if(!u)return[];let d=Vb(u,l.startLine,l.endLine);if(!d)return[];let m=new Set,f=d.childForFieldName("parameters")??d.childForFieldName("parameter");if(f&&Vt(f,x=>{x.type==="identifier"&&m.add(x.text)}),m.size===0)return[];let p=cd(e,t,n);if(p.length===0)return[];let g=(_t(e,l.relativePath)??[]).filter(x=>x.startLine>=l.startLine&&x.endLine<=l.endLine),h=(rn(e,l.relativePath)??[]).filter(x=>x.line>=l.startLine&&x.line<=l.endLine),b=new Set,S=p.map(x=>({name:x.name,startLine:x.startLine,endLine:x.endLine})),y=new Set;for(;S.length>0&&y.size<32;){let x=S.shift(),C=`${x.name}\0${x.startLine}\0${x.endLine}`;if(!y.has(C)){y.add(C);for(let L of h.filter(w=>w.line>=x.startLine&&w.line<=x.endLine)){if(L.memberAccess&&L.calleeQualifier&&m.has(L.calleeQualifier)){b.add(L.calleeLeaf);continue}if(L.memberAccess)continue;let w=g.filter(R=>R.name===L.calleeLeaf);w.length===1&&S.push(w[0])}}}if(b.size===0)return[];let I=s.childForFieldName("arguments")?.namedChildren.find(x=>_r(x).type==="object");if(!I)return[];let v=[];for(let x of _r(I).namedChildren){if(x.type==="shorthand_property_identifier"&&b.has(x.text)){v.push(...qa(e,t,x.text,x,x));continue}if(x.type!=="pair")continue;let C=x.childForFieldName("key")??x.namedChild(0),L=x.childForFieldName("value")??x.namedChild(1),w=Ka(C?.text);!w||!b.has(w)||!L||v.push(...qa(e,t,w,L,x))}return v.filter((x,C,L)=>L.findIndex(w=>w.file===x.file&&w.name===x.name&&w.startLine===x.startLine&&w.endLine===x.endLine)===C)}function Kb(e,t){for(let n of e.descendantsOfType("variable_declarator"))if((n.childForFieldName("name")??n.namedChild(0))?.text===t)return n.childForFieldName("value")??n.namedChild(1);return null}function Gb(e){return e.type==="call_expression"?e:e.descendantsOfType("call_expression")[0]??null}function Wb(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=Ce(e,t).filter(p=>p.localName===i[1]&&p.sourcePath);if(d.length!==1||!d[0].sourcePath)return[];let m=d[0].sourcePath,f=Qn(e,m,i[2]).filter(p=>p.isFunctionLike);return f.length>0?f:(_t(e,m)??[]).filter(p=>p.name===i[2]).map(p=>({...p,relativePath:m}))}if(!/^[A-Za-z_$][\w$]*$/u.test(r))return[];let o=W(e,t).filter(d=>d.leaf===r&&d.isFunctionLike);if(o.length>0)return o;let s=(_t(e,t)??[]).filter(d=>d.name===r).map(d=>({...d,relativePath:t}));if(s.length>0)return s;let a=Ce(e,t).filter(d=>d.localName===r&&d.sourcePath&&d.kind!=="namespace");if(a.length!==1||!a[0].sourcePath)return[];let c=a[0].sourcePath,l=a[0].importedName==="default"?r:a[0].importedName,u=Qn(e,c,l).filter(d=>d.isFunctionLike);return u.length>0?u:(_t(e,c)??[]).filter(d=>d.name===l).map(d=>({...d,relativePath:c}))}function Vb(e,t,n){let r=null;return Vt(e,i=>{!/(?:function|method|lambda)/u.test(i.type)&&i.type!=="arrow_function"||i.startPosition.row>t||i.endPosition.row<n||(!r||i.endIndex-i.startIndex<r.endIndex-r.startIndex)&&(r=i)}),r}function ld(e){return["arrow_function","function_expression","generator_function"].includes(e.type)||e.descendantsOfType(["arrow_function","function_expression","generator_function"]).length>0}function rk(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 Ka(e){return e?e.replace(/^(?:['"])(.*)(?:['"])$/u,"$1"):null}function ik(e,t,n,r){let i=/^this\.([A-Za-z_$][\w$]*)$/u.exec(n.calleeQualifier??"");if(!i)return null;let o=ae(e,t)?.rootNode;if(!o)return null;let s=ok(o,n.line);if(!s)return null;let a=new Set;if(Vt(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=_r(b);if(S.type!=="new_expression")return;let E=(S.childForFieldName("constructor")??S.namedChild(0))?.text.match(/[A-Za-z_$][\w$]*$/u)?.[0];E&&a.add(E)}),a.size!==1)return null;let c=[...a][0],l=r.filter(g=>g.localName===c);if(l.length!==1)return null;let u=l[0].importedName==="default"?c:l[0].importedName,d=l[0].importedName==="default"?Qn(e,l[0].sourcePath,c):[],m=d.length===1?d[0].leaf:u,f=W(e,l[0].sourcePath).filter(g=>g.isFunctionLike&&g.leaf===n.calleeLeaf&&dp(g.symbol)===m);if(f.length!==1)return null;let p=f[0];return{calleeLeaf:n.calleeLeaf,line:n.line,sourceFile:t,targetFile:p.relativePath,targetStartLine:p.startLine,targetEndLine:p.endLine,targetSymbol:p.symbol,resolution:"constructed-member-receiver",strength:"exact"}}function ok(e,t){let n=[];return Vt(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 _r(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 Vt(e,t){t(e);for(let n of e.namedChildren)Vt(n,t)}function sk(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 ud(e){let t=[];for(let n of e)t.some(r=>Ft(r,n))||t.push(n);return t}import{existsSync as ck}from"fs";import{SymbolRole as lk}from"@c4312/scip";import{deserializeSCIP as ak}from"@c4312/scip";function Jb(e,t){return ak(ei(e,{inputKind:t,maxBytes:Zr}))}var dd=new WeakMap;function An(e,t,n,r){let i=te(e,t),o=(i?.callSites??[]).filter(f=>f.line>=n&&f.line<=r);if(!i||o.length===0)return{available:!!i,targets:[],resolvedCallsites:0,unresolvedCallsites:0};let s=fd(e);if(!s)return{available:!1,targets:[],resolvedCallsites:0,unresolvedCallsites:o.length};let a=(s.byFile.get(t)??[]).filter(f=>f.sourceLine>=n&&f.sourceLine<=r).map(f=>({...f,calleeLeaf:f.definition.leaf})),c=Yb(o.map(f=>({line:f.line,leaf:f.calleeLeaf}))),l=Yb(a.map(f=>({line:f.sourceLine,leaf:f.calleeLeaf}))),u=new Set([...c].flatMap(([f,p])=>l.get(f)===p?[f]:[])),d=a.filter(f=>u.has(Qb(f.sourceLine,f.calleeLeaf))),m=[...u].reduce((f,p)=>f+(c.get(p)??0),0);return{available:!0,targets:d,resolvedCallsites:m,unresolvedCallsites:Math.max(0,o.length-m)}}function md(e,t,n,r){let i=fd(e);return i?{available:!0,targets:(i.byFile.get(t)??[]).filter(o=>o.sourceLine>=n&&o.sourceLine<=r)}:{available:!1,targets:[]}}function Xb(e,t,n,r){let i=fd(e);return i?{available:!0,targets:(i.byFile.get(t)??[]).filter(o=>o.sourceLine>=n&&o.sourceLine<=r&&Ga(e,o.definition)).map(o=>({...o,calleeLeaf:o.definition.leaf}))}:{available:!1,targets:[]}}function fd(e){if(dd.has(e))return dd.get(e)??null;let t=uk(e);return dd.set(e,t),t}function uk(e){if(!e.generation.indexPath||!ck(e.generation.indexPath))return null;try{let t=Ue(e),n=new Map(t.map(o=>[o.symbol,o])),r=Jb(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&lk.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 Ga(e,t){if(!t.isFunctionLike)return!1;let n=te(e,t.relativePath);return!n||n.callables.some(r=>r.name===t.leaf&&r.startLine===t.startLine&&r.endLine===t.endLine)?!0:dk(t)}function dk(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 Yb(e){let t=new Map;for(let n of e){let r=Qb(n.line,n.leaf);t.set(r,(t.get(r)??0)+1)}return t}function Qb(e,t){return`${e}\0${t}`}var mk=16,fk=4,pd=3e3,pk=800,gk=new Set(["assignment","const_declaration","const_item","field_declaration","lexical_declaration","local_declaration_statement","local_variable_declaration","static_item","variable_declaration"]);function iS(e,t,n={}){let r=n.maxSteps??mk;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(T=>[T.id,T])),o=xk(n.focusLocations??[]),s=new Set,a=new Map(t.edges.map(T=>[T.id,T])),c=Nn(t.paths.flatMap(T=>T.nodeIds)),l=Nn(t.anchors.filter(T=>T.status==="matched").flatMap(T=>T.nodeIds)),u=t.nodes.filter(T=>T.disposition==="emitted"&&T.attributes.upstreamCausalPath===!0).sort((T,Z)=>Number(Z.attributes.upstreamCausalDistance??0)-Number(T.attributes.upstreamCausalDistance??0)||T.id.localeCompare(Z.id)).map(T=>T.id),d=new Set(u),m=Math.max(0,r-l.length),p=hk(t,l,o,m).slice(0,m),g=new Set(p),h=new Set(p),b=new Set([...c,...u,...l]),S=t.edges.filter(T=>T.disposition==="emitted"&&T.kind!=="structural-membership"),y=t.edges.filter(T=>T.disposition!=="excluded"&&T.disposition!=="unsupported"&&T.kind!=="structural-membership"),E=new Set([...t.paths.flatMap(T=>T.edgeIds),...S.filter(T=>d.has(T.fromNodeId)&&d.has(T.toNodeId)).map(T=>T.id)]),I=t.paths.some(T=>T.edgeIds.length>0),v=new Set(l);for(let T of p)v.add(T);for(let T of t.paths){let Z=T.nodeIds[0],Q=a.get(T.edgeIds[0]??""),Se=T.nodeIds[1];Z&&Se&&Q?.fromNodeId===Z&&Q.toNodeId===Se&&v.add(Z)}if(t.paths.every(T=>T.nodeIds.length===0))for(let T of t.anchors)for(let Z of T.nodeIds)v.add(Z);let x=Lk(l,y,i,fk),C=Nn(S.filter(T=>T.kind==="call"&&l.includes(T.fromNodeId)).map(T=>T.toNodeId)),L=new Set(Nn([...x,...I?[]:C]));for(let T of L)v.add(T);let w=Nn(S.flatMap(T=>b.has(T.fromNodeId)||b.has(T.toNodeId)?[T.fromNodeId,T.toNodeId]:[])),R=t.nodes.filter(T=>T.disposition==="emitted"&&T.kind!=="structural-region"&&S.some(Z=>Z.fromNodeId===T.id||Z.toNodeId===T.id)).map(T=>T.id),P=Nn([...u,...c,...l,...p,...L,...w,...R]).filter(T=>i.has(T)),_=[];for(let T of P)I&&!b.has(T)&&!g.has(T)&&!L.has(T)||_.length>=r&&!b.has(T)||_.push(T);let D=new Set(_),M=new Map(_.map(T=>[T,Pk(T)])),F=new Set([...c,...u]),V=new Set(t.anchors.flatMap(T=>T.nodeIds)),ce=_.map((T,Z)=>{let Q=i.get(T),Se=Ck(Q,o);for(let rt of Se)s.add(Ei(Q.location.file,rt));return{id:M.get(T),nodeId:T,order:Z,role:V.has(T)?"anchor":F.has(T)?"connector":"junction",kind:Q.kind,label:Q.label,location:Q.location,behavior:yk(e,Q,V.has(T),[...new Set([...Se,...vk(e,Q,y,i,E,v)])],Se,v.has(Q.id)&&(Se.length===0||V.has(Q.id)),L.has(Q.id),h.has(Q.id)&&Se.length===0)}}),G=new Map;for(let T of t.paths)for(let Z=0;Z<T.edgeIds.length;Z+=1){let Q=a.get(T.edgeIds[Z]),Se=T.nodeIds[Z],rt=T.nodeIds[Z+1];!Q||!Se||!rt||G.set(Q.id,Q.fromNodeId===Se&&Q.toNodeId===rt?"forward":"reverse")}let A=y.filter(T=>D.has(T.fromNodeId)&&D.has(T.toNodeId)).sort((T,Z)=>Dk(T,Z,t)).map((T,Z)=>({id:Mk(T.id),edgeId:T.id,order:Z,kind:T.kind,fromStepId:M.get(T.fromNodeId),toStepId:M.get(T.toNodeId),directed:!0,pathTraversal:G.get(T.id)??"adjacent",evidence:T.evidence})),K=new Map(A.map(T=>[T.edgeId,T.id])),ne=t.paths.map(T=>({id:T.id,status:T.status,stepIds:T.nodeIds.flatMap(Z=>{let Q=M.get(Z);return Q?[Q]:[]}),transitionIds:T.edgeIds.flatMap(Z=>{let Q=K.get(Z);return Q?[Q]:[]})})),fe=ce.flatMap(T=>T.location?[`${T.location.file}:${T.location.line+1}`]:[]),he=t.anchors.some(T=>T.status==="ambiguous"),le=ne.some(T=>T.status==="connected"||T.status==="candidate"),be=ne.some(T=>T.status==="partial");return{status:ce.length===0?"unavailable":he?"ambiguous":le&&!be?"connected":be?"partial":"connected",steps:ce,transitions:A,paths:ne,coverage:{candidateNodes:P.length,returnedNodes:_.length,omittedNodeIds:P.filter(T=>!D.has(T)),returnedTransitions:A.length,withheldStatements:ce.reduce((T,Z)=>T+(Z.behavior?.coverage.omittedStatements??0),0),requestedFocusLocations:o,matchedFocusLocations:o.filter(T=>s.has(Ei(T.file,T.line))),unmatchedFocusLocations:o.filter(T=>!s.has(Ei(T.file,T.line)))},behaviorCommand:rS(fe,"behavior"),exactSourceCommand:rS(fe,"source")}}function hk(e,t,n,r){if(r<=0||n.length===0)return[];let i=new Set(t),o=new Set(n.map(s=>Ei(s.file,s.line)));return Nn(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(Ei(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 yk(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=ie(e,t.location.file),u=r.length>0?r:[t.location.line],d=t.kind==="runtime-boundary-participant"?bt(e,t.location.file,0,Math.max(0,l.length-1),[t.location.line]):bt(e,t.location.file,t.location.line,c,u),m=r.filter(L=>L>=d.startLine&&L<=d.endLine),f=pi(e,t.location.file,d.startLine,d.endLine,m),p=f??(m.length>0?pi(e,t.location.file,d.startLine,d.endLine,m,{requireSavings:!1}):null),g=m.length>0?Rk(e,t,d.startLine,d.endLine,m,p,o):null,h=l.slice(d.startLine,d.endLine+1).join(`
83
- `).length,b=Pn(e,t.location.file,d.startLine,d.endLine),S=l.slice(d.startLine,d.endLine+1).some((L,w)=>L.length>pk&&(b.get(d.startLine+w)??[]).some(R=>["binding","branch","loop","call","return","throw","mutation"].includes(R))),y=L=>bk(e,t,d.startLine,d.endLine,i.filter(w=>w>=d.startLine&&w<=d.endLine),L),E=(s||t.kind==="runtime-boundary-participant"||t.anchorIds.length>0)&&h<=pd,I=n&&(m.length===0||E);if(f&&(a||I))return y(Zb(f));if(!a&&!I&&g&&!S&&!E&&g.renderedCharacters<(p?.outlineCharacters??h))return y(g);if(f)return y(Zb(f));let v=l.slice(d.startLine,d.endLine+1),x=v.join(`
84
- `),C=Pn(e,t.location.file,d.startLine,d.endLine);return y({kind:"source",constructKind:"source construct",signature:v.find(L=>L.trim().length>0)?.trim()??t.label,lines:v.map((L,w)=>({line:d.startLine+w,endLine:d.startLine+w,depth:0,signals:C.get(d.startLine+w)??[],text:L,copied:!0})),coverage:{sourceStatements:v.length,representedStatements:v.length,copiedStatements:v.length,omittedStatements:0},rawCharacters:x.length,renderedCharacters:x.length})}function bk(e,t,n,r,i,o){if(!t.location)return o;let s=md(e,t.location.file,n,r);if(!s.available)return o;let a=Pn(e,t.location.file,n,r),c=ie(e,t.location.file),l=new Set(i);for(let S of i){let y=Wa(c[S]??"");if(!y)continue;let E=wn(e,t.location.file,y).find(I=>I>S&&I<=r);E!==void 0&&l.add(E)}let u=[...new Map(s.targets.flatMap(S=>{let y=S.definition,E=y.relativePath===t.location.file&&y.startLine<=r&&y.endLine>=n;if(y.isTypeLike||E)return[];let I=Ga(e,y),v=i.length>0&&I&&a.get(S.sourceLine)?.includes("return"),x=I&&l.has(S.sourceLine);return I&&!v&&!x?[]:[[y.symbol,{definition:y,kind:v?"return-value-transformer":x?"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})),f=new Set,p=new Set(u.map(({definition:S})=>S.symbol));for(;m.length>0;){let S=m.shift();if(!S||f.has(S.owner.symbol))continue;f.add(S.owner.symbol);let{owner:y,depth:E}=S,I=md(e,y.relativePath,y.startLine,y.endLine);if(!I.available)continue;let v=Pn(e,y.relativePath,y.startLine,y.endLine),x=ie(e,y.relativePath);for(let C of I.targets){let L=C.definition,w=L.relativePath===y.relativePath&&L.startLine<=y.endLine&&L.endLine>=y.startLine;if(L.isTypeLike||w)continue;let R=Ga(e,L),P=Wa(x[C.sourceLine]??""),_=R&&P!==null&&wn(e,y.relativePath,P).some(M=>M>C.sourceLine&&M<=y.endLine&&(v.get(M)??[]).some(F=>["branch","return","throw"].includes(F))),D=R&&((v.get(C.sourceLine)??[]).some(M=>["branch","return","throw"].includes(M))||_);R&&!D||(p.has(L.symbol)||(p.add(L.symbol),d.push({definition:L,kind:R?"focused-causal-target":"compiler-referenced-declaration"})),R&&E<2&&m.push({owner:L,depth:E+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 E=y==="compiler-referenced-declaration"?Sk(e,S.relativePath,S.startLine,S.endLine):{startLine:S.startLine,endLine:S.endLine},I=ie(e,S.relativePath).slice(E.startLine,E.endLine+1).join(`
85
- `),v=y==="compiler-referenced-declaration"?null:pi(e,S.relativePath,S.startLine,S.endLine,[]),x=v?[v.signature,...v.lines.map(P=>`${P.line+1}${P.signals.length>0?`[${P.signals.join(",")}]`:""} ${P.text}`)].join(" | "):null,C=x&&x.length<I.length?x:I,L={symbol:S.symbol,label:S.leaf,file:S.relativePath,line:E.startLine,endLine:E.endLine},w=y==="compiler-referenced-declaration"?1e3:8e3,R=y==="compiler-referenced-declaration"?12:120;if(C.length>w||E.endLine-E.startLine>R){b.push({...L,reason:"source-too-large"});continue}h.push({kind:y,...L,text:C})}return{...o,...h.length===0?{}:{supportingDeclarations:h},...b.length===0?{}:{omittedSupportingDeclarations:b}}}function Sk(e,t,n,r){let i=ae(e,t);if(!i)return{startLine:n,endLine:r};let o=[];oS(i.rootNode,a=>{gk.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 oS(e,t){t(e);for(let n of e.namedChildren)oS(n,t)}function Zb(e){return{kind:"outline",constructKind:e.constructKind,signature:e.signature,lines:e.lines,coverage:e.coverage,rawCharacters:e.rawCharacters,renderedCharacters:e.outlineCharacters}}function vk(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(te(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 to(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]:[]),f=m.filter(b=>a.has(b));for(let b of f.length>0?f:m)s.add(b);let p=l?.attributes.leaf;if(typeof p!="string"||p.length===0)continue;let g=wn(e,t.location.file,p).filter(b=>b>=t.location.line&&b<=(t.location.endLine??t.location.line)),h=g.find(b=>a.has(b))??g[0];h!==void 0&&s.add(h)}return[...s].sort((c,l)=>c-l)}function Ck(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 xk(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(Ei(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 Ei(e,t){return`${e}\0${t}`}function Rk(e,t,n,r,i,o,s){if(!t.location)return null;let a=ie(e,t.location.file),c=Pn(e,t.location.file,n,r),l=[...c].filter(([,D])=>D.length>0).map(([D])=>D).sort((D,M)=>D-M),u=i.map(D=>(c.get(D)??[]).length>0?D:l.find(M=>M>D&&M-D<=8)??D),d=new Set([...i,...u]),m=s?tu(e,t.location.file,n,r,{minimumBodyLines:0}):null,f=o?[...new Map(u.flatMap(D=>o.lines.filter(M=>M.text.length<=500&&M.signals.some(F=>["branch","loop","catch","finally"].includes(F))&&D>=M.line&&D<=M.endLine).sort((M,F)=>M.endLine-M.line-(F.endLine-F.line)||M.line-F.line).slice(0,2).map(M=>[`${M.line}\0${M.endLine}`,M]))).values()]:ba(e,t.location.file,n,r,u);for(let D of m?.lines??[])d.add(D.line);for(let D of f)d.add(D.line);for(let[D,M]of c)M.includes("call")&&M.includes("shape")&&d.add(D);let p=[];for(let D of u){let M=Wa(a[D]??"");if(!M)continue;let F=wn(e,t.location.file,M).filter(A=>A>D&&A<=r),V=F[0];V!==void 0&&d.add(V);let ce=F.find(A=>(c.get(A)??[]).some(K=>K==="branch"||K==="loop"));if(ce===void 0)continue;d.add(ce);let G=(o?.lines??[]).find(A=>A.line===ce)??{line:ce,endLine:Math.min(r,ce+40),depth:0,signals:c.get(ce)??[],text:(a[ce]??"").trim(),copied:!0},X=o?.lines??a.slice(G.line,G.endLine+1).map((A,K)=>{let ne=G.line+K;return{line:ne,endLine:ne,depth:0,signals:c.get(ne)??[],text:A.trim(),copied:!0}});p.push({focusLine:D,governingUse:ce,lines:X.filter(A=>A.line>=G.line&&A.line<=G.endLine&&A.text.length<=500&&A.signals.some(K=>["binding","branch","call","mutation"].includes(K)))})}for(let D of p.sort((M,F)=>F.governingUse-F.focusLine-(M.governingUse-M.focusLine)||M.focusLine-F.focusLine).slice(0,2))for(let M of D.lines.slice(0,14))d.add(M.line);let g=new Set(["binding","branch","loop","call","return","throw","mutation"]);for(let D of f)for(let M of o?.lines??[])M.line<D.line||M.line>D.endLine||M.signals.some(F=>g.has(F))&&d.add(M.line);let h=a.slice(n,r+1).flatMap((D,M)=>{let F=Wa(D);return F?[{name:F,line:n+M}]:[]}),b=!0;for(;b;){b=!1;for(let D of h)if([...d].some(F=>Ek(a[F]??"",D.name))){d.has(D.line)||(d.add(D.line),b=!0);for(let F of wn(e,t.location.file,D.name))F<n||F>r||d.has(F)||(c.get(F)??[]).some(V=>g.has(V))&&(d.add(F),b=!0)}}for(let D of o?.lines??[])if(D.signals.some(M=>["branch","loop","catch","finally"].includes(M))&&d.has(D.line))for(let M of o?.lines??[])M.line<D.line||M.line>D.endLine||M.signals.some(F=>g.has(F))&&d.add(M.line);let S=te(e,t.location.file),y=new Set(S?.callSites.map(D=>D.line)??[]),E=c,I=new Map([...o?.lines??[],...f].filter(D=>D.signals.some(M=>["branch","loop","catch","finally"].includes(M))).map(D=>[D.line,D])),v=new Map((o?.lines??[]).filter(D=>D.text.length<=500&&D.signals.includes("shape")&&(D.signals.includes("call")||D.signals.includes("mutation")||D.signals.includes("return"))).sort((D,M)=>D.endLine-D.line-(M.endLine-M.line)||D.line-M.line).map(D=>[D.line,D])),x=new Map((m?.lines??[]).map(D=>[D.line,D.signals.filter(M=>M!=="lifecycle")])),C=[...d].filter(D=>D>=n&&D<=r).sort((D,M)=>D-M).map(D=>{let M=I.get(D)??v.get(D);return{line:D,endLine:M?.endLine??D,depth:M?.depth??0,signals:Ik([...E.get(D)??[],...o?.lines.filter(F=>D>=F.line&&D<=F.endLine).flatMap(F=>F.signals)??[],...x.get(D)??[],...i.includes(D)?["anchor"]:[],...y.has(D)?["call"]:[]]),text:M?.text??(a[D]??"").trim(),copied:M?.copied??!0}}).filter(D=>D.text.length>0);if(C.length===0)return null;let L=m?.candidateLines??tu(e,t.location.file,n,r,{minimumBodyLines:0})?.candidateLines??0,w=Math.max(o?.coverage.sourceStatements??0,L,C.length),R=o?.signature??(a[n]??t.label).trim(),P=R.length+C.reduce((D,M)=>D+M.text.length+M.signals.join(",").length+12,0),_=a.slice(n,r+1).join(`
86
- `).length;return{kind:"connector-slice",constructKind:o?.constructKind??"source construct",signature:R,lines:C,coverage:{sourceStatements:w,representedStatements:C.length,copiedStatements:C.length,omittedStatements:Math.max(0,w-C.length)},rawCharacters:_,renderedCharacters:P}}function Ik(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 Wa(e){return/\b(?:const|let|var)\s+([\p{L}_$][\p{L}\p{N}_$]*)\s*(?:=|\bof\b|\bin\b)/u.exec(e)?.[1]??null}function Ek(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`(?:^|[^\\p{L}\\p{N}_$])${n}(?:$|[^\\p{L}\\p{N}_$])`,"u").test(e)}function wk(e,t,n){return Nn(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=eS(a.edge)-eS(s.edge);if(c!==0)return c;let l=tS(s.node,i)?0:1,u=tS(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 eS(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 tS(e,t){return!e.location||!t?.location?!1:nS(e.location.file)===nS(t.location.file)}function nS(e){return e.split("/").filter(Boolean).slice(0,2).join("/")}function Lk(e,t,n,r){let i=new Set(e),o=new Set,s=[],a=Nn(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=wk(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 Dk(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 Pk(e){return`step:${e}`}function Mk(e){return`transition:${e}`}function rS(e,t){return e.length===0?null:`codebaseiq inspect ${e.map(n=>`--at ${Tk(n)}`).join(" ")} --view ${t}`}function Tk(e){return`'${e.replace(/'/gu,`'"'"'`)}'`}function Nn(e){return[...new Set(e)]}var sS=4,kk=3,Fk=12,Ak=48,Nk=64,$r=10,Or=6,_k=24,Ok=320,gd=6,Bk=12,$k=1,jk=4,Hk=7,Uk=12,vd="source-construct:",zk=96,qk=32,aS=4,Kk=32,Gk=8,cS=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 Wk(e,t,n={}){let r=RS(t),i=FF(t);if(r.length===0)throw new Error("Anchor discovery requires at least one non-trivial repository term.");let o=n.limit??sS,s=n.full===!0;if(!Number.isSafeInteger(o)||o<=0)throw new RangeError(`anchor group limit must be a positive safe integer; received ${o}`);let a=new U(e),c=a.scopedDefinitions(n.scope).filter(A=>!De(A.symbol)),l=[...c],u=new Map(l.map(A=>[A.symbol,A])),d=new Map;for(let A of c)lS(d,A,r);let m=aa(e,{scope:n.scope});for(let A of m.files){let ne=W(e,A.relativePath).filter(he=>!De(he.symbol));if(ne.length===0)continue;let fe=xS(A.text);for(let he=0;he<fe.length;he+=1){let le=St(fe[he]??""),be=r.filter(Z=>le.has(Z));if(be.length===0)continue;let T=Ke(ne,he);if(!(!T||De(T.symbol)))for(let Z of be)Fo(d,T,Z,"source",A.relativePath,he)}}let f=uS(d),p=[...d.values()].map(A=>Va(A,f,i)).sort(Ze),g=Jk(m.files,p,r),h=-1;for(let A of g){let K=W(e,A.relativePath),ne=K.filter(T=>!De(T.symbol)),fe=te(e,A.relativePath)?.callables??[],he=new Map,le=T=>{let Z=`${T.startLine}\0${T.endLine}\0${T.name}`,Q=he.get(Z);if(Q)return Q;let Se=Vk(A.relativePath,K,T,()=>h--);return Se?(he.set(Z,Se),l.push(Se),u.set(Se.symbol,Se),lS(d,Se,r),Se):null};for(let T of fe){let Z=St(T.name);r.some(Q=>Z.has(Q))&&le(T)}if(fe.length===0)continue;let be=xS(A.text);for(let T=0;T<be.length;T+=1){let Z=St(be[T]??""),Q=r.filter(Qr=>Z.has(Qr));if(Q.length===0)continue;let Se=Yk(fe,T),rt=Se?le(Se):null;if(!rt)continue;let vr=dS(ne,T);if(dS(vr?[vr,rt]:[rt],T)?.symbol===rt.symbol)for(let Qr of Q)Fo(d,rt,Qr,"source",A.relativePath,T)}}let b=uS(d),S=new Map(m.files.map(A=>[A.relativePath,A.text.split(/\r?\n/u)]));for(let A of d.values()){let K=S.get(A.definition.relativePath);K&&(A.sourceCharacters=K.slice(A.definition.startLine,A.definition.endLine+1).join(`
87
- `).length)}let y=[...d.values()].map(A=>Va(A,b,i)).sort(Ze),E=Math.min(y.length,Math.max(Fk,o*kk)),I=s?y:wi([...y.slice(0,E),...[...y].sort(yd).slice(0,Math.max(Ak,E)),...wF(y,r),...LF(y,r,b)]),v=I.length,x=I.map(A=>u.get(A.symbol)).filter(A=>A?.isFunctionLike===!0),C=Xk(l),L=Qk(e,a,I,x,u,C,new Set(d.keys()),n.semantic!==!1),w=tF(L,I,d,b,u),R=nF(w,b,r),P=hF(e,a,L,d,b,l,u,n.semantic!==!1),D=[...iF(e,a,w,u,b,n.semantic!==!1),...R,...w,...P].map(A=>({...A,queryPathMatches:PF(A)})).sort((A,K)=>Br(A,K,b)),M=s?D:MF(D,o,b),F=r.filter(A=>b.has(A)),V=r.filter(A=>!b.has(A)),ce=Math.max(0,y.length-v),G=Math.max(0,D.length-M.length)+ce,X=s?y.length:Math.min(y.length,o+sS);return{query:t,queryPathFragments:i,normalizedTerms:r,matchedTerms:F,unmatchedTerms:V,groups:M,candidateRoots:y,candidateRootCount:y.length,analyzedRootCount:v,omittedRootCount:ce,omittedGroupCount:G,scannedFiles:m.files.length,scannedBytes:m.scannedBytes,recoveryCommand:G===0?null:`codebaseiq anchors ${Qa(t)}${n.scope?` --scope ${Qa(n.scope)}`:""} --limit ${X}`}}function RS(e){let t=Za(e).filter(n=>!cS.has(n.toLocaleLowerCase())).map(Cd).filter(n=>n.length>=3&&!cS.has(n));return[...new Set(t)]}function lS(e,t,n){let r=St(t.leaf),i=St(t.relativePath),o=St(t.documentation??"");for(let a of n)r.has(a)&&Fo(e,t,a,"symbol"),i.has(a)&&Fo(e,t,a,"path"),o.has(a)&&Fo(e,t,a,"documentation");let s=e.get(t.symbol);s&&(s.symbolPhraseLength=NF(t.leaf,n))}function Fo(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 uS(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 Vk(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:`${vd}${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 Jk(e,t,n){let r=new Set(t.slice(0,zk).map(s=>s.file)),i=new Set(n),o=e.map(s=>{let a=St(s.relativePath),c=s.relativePath.slice(s.relativePath.lastIndexOf("/")+1).replace(/\.[^.]+$/u,""),l=St(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||Jt(J(s.file.relativePath))-Jt(J(a.file.relativePath))||s.file.relativePath.localeCompare(a.file.relativePath)).slice(0,qk);for(let s of o)r.add(s.file.relativePath);return e.filter(s=>r.has(s.relativePath))}function Yk(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,r)=>n.endLine-n.startLine-(r.endLine-r.startLine)||n.startLine-r.startLine)[0]}function Xk(e){let t=new Map;for(let n of e){if(!dn(n))continue;let r=`${n.relativePath}\0${mn(n.leaf)}`,i=t.get(r)??[];i.push(n),t.set(r,i)}return t}function dS(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,r)=>n.endLine-n.startLine-(r.endLine-r.startLine)||Number(dn(r))-Number(dn(n))||n.startLine-r.startLine||n.symbol.localeCompare(r.symbol))[0]}function dn(e){return e.symbol.startsWith(vd)}function ar(e){return dn(e)?e.leaf:N(e.symbol)}function Va(e,t,n=[]){let r=e.definition,i=[...e.matches.entries()].map(([l,u])=>({term:l,sources:[...u.sources].sort(_F),locations:[...u.locations.values()].sort(LS).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:ar(r),leaf:r.leaf,file:r.relativePath,line:r.startLine,endLine:r.endLine,kind:r.isFunctionLike?"callable":r.isTypeLike?"type":"symbol",fileKind:J(r.relativePath),matches:i,focusLocations:$F(e,t),matchedTerms:i.map(l=>l.term),symbolMatchedTerms:s,symbolPhraseLength:e.symbolPhraseLength,identityMatchedTerms:o,rarity:a,symbolRarity:c,queryPathMatches:AF(r.relativePath,n),...e.sourceCharacters===void 0?{}:{sourceCharacters:e.sourceCharacters}}}function Qk(e,t,n,r,i,o,s,a){let c=r.filter(g=>!dn(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?dn(h)?mS(e,h,i,o,1):Ja(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||!dn(h)||dn(y))&&d.set(y.symbol,y)}}let m=[...d.values()],f=t.calleeMap(m.filter(g=>!dn(g)),{additive:!1,semantic:a}),p=new Map;for(let g of m)p.set(g.symbol,dn(g)?mS(e,g,i,o,2):Ja(e,g,f.get(g.symbolId)??[],i,2,s));return n.map(g=>{let h=u.get(g.symbol)??[],b=h.flatMap(y=>p.get(y.toSymbol)??[]),S=_n([...h,...b]);return{root:g,relations:S,nodeSymbols:new Set([g.symbol,...S.flatMap(y=>[y.fromSymbol,y.toSymbol])])}})}function Ja(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"&&!eF(e,t,c,a.callsiteLine))continue;let l=s.get(c.symbol);(!l||kF(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:N(t.symbol),fromFile:t.relativePath,toSymbol:l.symbol,toLabel:N(l.symbol),toFile:l.relativePath,depth:i,strength:Sd(c.source),evidence:c.source,callsiteLine:c.callsiteLine??Zk(e,t,l)}}).sort((a,c)=>Number(o.has(c.toSymbol))-Number(o.has(a.toSymbol))||fn(a,c)).slice(0,Nk)}function mS(e,t,n,r,i){let o=An(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:ar(t),fromFile:t.relativePath,toSymbol:a.symbol,toLabel:ar(a),toFile:a.relativePath,depth:i,strength:"exact",evidence:"scip-occurrence-callsite",callsiteLine:s.sourceLine}]});for(let s of sr(e,t.relativePath,{ranges:[{startLine:t.startLine,endLine:t.endLine}],excludeIndexedTargets:!1}).targets){let a=[...r.get(`${s.targetFile}\0${mn(s.calleeLeaf)}`)??[],...W(e,s.targetFile).filter(c=>c.isFunctionLike&&mn(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:ar(t),fromFile:t.relativePath,toSymbol:a.symbol,toLabel:ar(a),toFile:a.relativePath,depth:i,strength:s.strength==="exact"?"exact":"derived",evidence:"ast-member-import-candidate",callsiteLine:s.line})}for(let s of te(e,t.relativePath)?.callSites??[]){if(s.line<t.startLine||s.line>t.endLine||s.memberAccess)continue;let a=(r.get(`${t.relativePath}\0${mn(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:ar(t),fromFile:t.relativePath,toSymbol:c.symbol,toLabel:ar(c),toFile:c.relativePath,depth:i,strength:"derived",evidence:"ast-callsite",callsiteLine:s.line})}return _n(o).sort(fn)}function Zk(e,t,n){let r=mn(n.leaf);return te(e,t.relativePath)?.callSites.find(i=>i.line>=t.startLine&&i.line<=t.endLine&&mn(i.calleeLeaf)===r)?.line??null}function eF(e,t,n,r){if(r===void 0)return!1;let i=mn(n.leaf);return te(e,t.relativePath)?.callSites.some(o=>o.line===r&&mn(o.calleeLeaf)===i)??!1}function mn(e){return e.replace(/^#/u,"").replace(/\(\)$/u,"")}function tF(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),f=a(d);m!==f&&(s[f]=m)};for(let u of e){let d=o.get(u.root.symbol);if(d!==void 0)for(let m of u.nodeSymbols){let f=o.get(m);f!==void 0&&c(d,f)}}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)),f=_n(e.filter(y=>m.has(y.root.symbol)).flatMap(y=>y.relations)).sort(fn),p=new Map(u.map(y=>[y.symbol,y]));for(let y of new Set(f.flatMap(E=>[E.fromSymbol,E.toSymbol]))){let E=n.get(y);if(E)p.has(y)||p.set(y,Va(E,r));else{let I=i.get(y);I&&p.set(y,ES(I))}}let g=RF(u,f,p),h=u.filter(y=>f.some(E=>E.fromSymbol===y.symbol)).length,b=[...new Set(u.flatMap(y=>y.matchedTerms))].sort(),S=xF(f,g,m,p);return{id:`anchor-set:${d+1}:${No(u[0])}`,kind:"connected-flow",roots:[...u].sort(Ze),keyAnchors:g,candidateOwnerCount:g.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:[],matchedTerms:b,relations:S,relationCount:f.length,orchestrationRootCount:h,omittedRelations:Math.max(0,f.length-$r),systemMapCommand:Oo(g,f,b)}})}function nF(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=fS(s);if(a.size!==0)for(let c=o+1;c<e.length;c+=1){let l=e[c],u=fS(l),d=[...a].filter(I=>u.has(I));if(d.length===0||![...a].some(I=>!u.has(I))||![...u].some(I=>!a.has(I)))continue;let m=rF(s,l);if(m.length<2)continue;let f=_n([...s.relations,...l.relations]).sort(fn),p=f.slice(0,$r),g=wi([...s.roots,...l.roots]).sort(Ze),h=[...new Set([...s.matchedTerms,...l.matchedTerms])].sort(),b=d.sort((I,v)=>(r.get(I)??Number.MAX_SAFE_INTEGER)-(r.get(v)??Number.MAX_SAFE_INTEGER)||I.localeCompare(v)),S=+(s.relationCount>0)+ +(l.relationCount>0),y=+((s.orchestrationRootCount??0)>0)+ +((l.orchestrationRootCount??0)>0),E=Math.min(...b.map(I=>t.get(I)??Number.MAX_SAFE_INTEGER));i.push({sharedOrder:Math.min(...b.map(I=>r.get(I)??Number.MAX_SAFE_INTEGER)),sharedFrequency:E,connectedSides:S,orchestrationSides:y,group:{id:`parallel-paths:${No(s.roots[0])}:${No(l.roots[0])}`,kind:"parallel-paths",roots:g,keyAnchors:m,candidateOwnerCount:m.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:[...s.upstreamEntries,...l.upstreamEntries],matchedTerms:h,relations:p,relationCount:f.length,parallelConnectedSides:S,parallelOrchestrationSides:y,parallelSharedPathTerms:b,parallelSharedPathFrequency:E,orchestrationRootCount:(s.orchestrationRootCount??0)+(l.orchestrationRootCount??0),omittedRelations:Math.max(0,f.length-p.length),systemMapCommand:Oo(m,f,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||Br(o.group,s.group,t)).slice(0,Uk).map(o=>o.group)}function fS(e){return new Set(e.roots.flatMap(t=>t.matches.filter(n=>n.sources.includes("path")).map(n=>n.term)))}function rF(e,t){return wi([pS(e),pS(t)].filter(n=>n!==void 0))}function pS(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)||gS(i)-gS(r)||i.identityMatchedTerms.length-r.identityMatchedTerms.length||i.symbolMatchedTerms.length-r.symbolMatchedTerms.length||(n.get(i.symbol)??0)-(n.get(r.symbol)??0)||Ze(r,i))[0]}function gS(e){return e.matchedTerms.length+e.identityMatchedTerms.length*2+(e.queryPathMatches?.length??0)*4}function iF(e,t,n,r,i,o){let s=Ys(e);if(!s||s.links.length===0||n.length<2)return[];let a=new Map(s.observations.map(f=>[f.id,f])),c=new Map,l=new Map,u=[...n].sort((f,p)=>Br(f,p,i)).slice(0,Bk),d=s.links.filter(f=>f.strength!=="candidate").sort((f,p)=>cr(p.strength)-cr(f.strength)||p.matchedKeyParts.length-f.matchedKeyParts.length||f.id.localeCompare(p.id));for(let f of u)for(let p of d){let g=a.get(p.from),h=a.get(p.to);if(!g||!h||!oF(f,g,r))continue;let b=sF(f,g,r);if(!b)continue;let S=c.get(h.id)??lF(e,t,h,r,o,jk);if(c.set(h.id,S),S.reachedSymbols.size===0)continue;let y=n.filter(D=>D.id!==f.id&&aF(D).some(M=>S.reachedSymbols.has(M))&&hd(b,D)>=2).sort((D,M)=>hd(b,M)-hd(b,D)||Br(D,M,i)).slice(0,$k);if(y.length===0)continue;let E=[f.id,g.id,...y.map(D=>D.id).sort()].join("\0");if(l.has(E))continue;let I=new Set(y.flatMap(_o)),v=pF(Ao(h),I,S.relations);if(v.length===0)continue;let x=fF(g,h,p.joinRule,p.matchedKeyParts,p.strength),C=_n([x,...S.relations,...f.relations,...y.flatMap(D=>D.relations)]),L=gF([x,...v],C,f,y),w=wi([b,...y.flatMap(D=>D.roots)]).sort(Ze),R=wi([b,...y.flatMap(D=>D.keyAnchors)]).slice(0,Hk),P=[...new Set([...b.matchedTerms,...y.flatMap(D=>D.matchedTerms)])].sort(),_=cF(e,t,b,r,o);w.length===0||R.length<2||l.set(E,{id:`cross-boundary-set:${No(b)}:${l.size+1}`,kind:"cross-boundary-flow",roots:w,keyAnchors:R,candidateOwnerCount:R.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:_,matchedTerms:P,relations:L,relationCount:C.length,omittedRelations:Math.max(0,C.length-L.length),systemMapCommand:Oo(R,C,P)})}let m=new Map;for(let[f,p]of l){let g=f.slice(0,f.indexOf("\0")),h=m.get(g);(!h||Br(p,h,i)<0)&&m.set(g,p)}return[...m.values()]}function oF(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 sF(e,t,n){let r=wi([...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 aF(e){return[...new Set([...e.roots,...e.keyAnchors].map(t=>t.symbol))]}function hd(e,t){let n=St(e.leaf),r=[...t.roots,...t.keyAnchors].map(o=>St(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 cF(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=St(n.leaf);return[...s].filter(c=>c!==n.file&&J(c)!=="test").flatMap(c=>{let l=te(e,c);return(l?.callSites??[]).filter(u=>mn(u.calleeLeaf)===mn(n.leaf)).flatMap(u=>{let d=(l?.callables??[]).filter(f=>f.startLine<=u.line&&f.endLine>=u.line).sort((f,p)=>f.endLine-f.startLine-(p.endLine-p.startLine)||f.startLine-p.startLine)[0];if(!d)return[];let m=[...St(d.name)].filter(f=>a.has(f)).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 lF(e,t,n,r,i,o){let s=uF(e,n,r),a=s.map(({definition:m,evidence:f,line:p})=>({kind:"call",fromSymbol:Ao(n),fromLabel:Ya(n),fromFile:n.source.file,toSymbol:m.symbol,toLabel:N(m.symbol),toFile:m.relativePath,depth:1,strength:f==="scip-occurrence-callsite"?"exact":"derived",evidence:f,callsiteLine:p})),c=dF(e,n);a.push(...c.relations);let l=IS([...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 f=t.calleeMap(u,{additive:!1,semantic:i}),p=new Map;for(let g of u){let h=Ja(e,g,f.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)&&p.set(S.symbol,S)}}u=[...p.values()];for(let g of u)d.add(g.symbol)}return{entryDefinitions:l,relations:_n(a),reachedSymbols:new Set([...l.map(m=>m.symbol),...a.flatMap(m=>[m.fromSymbol,m.toSymbol])])}}function uF(e,t,n){let r=t.owner.symbol?n.get(t.owner.symbol):void 0;if(r?.isFunctionLike&&!De(r.symbol))return[{definition:r,evidence:"scip-occurrence-callsite",line:t.source.startLine}];let i=ie(e,t.source.file),o=bt(e,t.source.file,0,Math.max(0,i.length-1),[t.source.startLine]),s=An(e,t.source.file,o.startLine,o.endLine).targets.map(u=>({definition:u.definition,evidence:"scip-occurrence-callsite",line:u.sourceLine})),a=te(e,t.source.file),c=sn(e),l=(a?.callSites??[]).flatMap(u=>{if(u.line<o.startLine||u.line>o.endLine)return[];let d=on(t.source.file,c.get(u.calleeLeaf)??[]),m=Jn(e,t.source.file,d,u.memberAccess,u.calleeQualifier),f=m?n.get(m.symbol):void 0;return f?.isFunctionLike?[{definition:f,evidence:"ast-callsite",line:u.line}]:[]});return mF([...s,...l])}function dF(e,t){let n=ie(e,t.source.file),r=bt(e,t.source.file,0,Math.max(0,n.length-1),[t.source.startLine]),i=sr(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:Ao(t),fromLabel:Ya(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=An(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:N(u.definition.symbol),toFile:u.definition.relativePath,depth:2,strength:"exact",evidence:"scip-occurrence-callsite",callsiteLine:u.sourceLine})}return{definitions:IS(o),relations:_n(s)}}function mF(e){return[...new Map(e.map(t=>[t.definition.symbol,t])).values()]}function IS(e){return[...new Map(e.map(t=>[t.symbol,t])).values()]}function Ao(e){return e.owner.symbol??e.id}function Ya(e){return e.owner.name??`${e.source.file}:${e.source.startLine+1}`}function fF(e,t,n,r,i){return{kind:"runtime-boundary",fromSymbol:Ao(e),fromLabel:Ya(e),fromFile:e.source.file,toSymbol:Ao(t),toLabel:Ya(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 pF(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(fn))o.has(a.toSymbol)||(o.add(a.toSymbol),i.push({symbol:a.toSymbol,path:[...s.path,a]}))}return[]}function gF(e,t,n,r){let i=_n(e),o=new Set([n,...r].flatMap(s=>[..._o(s),...s.keyAnchors.map(a=>a.symbol)]));for(let s of t){if(i.length>=$r)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,$r)}function hF(e,t,n,r,i,o,s,a){let c=n.filter(u=>!u.root.symbol.startsWith(vd)).map(u=>({root:u.root,relations:u.relations.filter(d=>d.depth===1&&d.fromSymbol===u.root.symbol)}));return yF(c).flatMap((u,d)=>{let m=new Set(u.map(F=>F.root.symbol)),f=new Map;for(let F of u)for(let V of new Set(F.relations.map(ce=>ce.toSymbol)))f.set(V,(f.get(V)??0)+1);let p=[...f].filter(([,F])=>F>=2).sort(([F,V],[ce,G])=>G-V||bF(F,ce,r,i,s)).map(([F])=>s.get(F)).filter(F=>F?.isFunctionLike===!0).slice(0,_k);if(p.length===0)return[];let g=t.callerFileMap(p,{semantic:a,sourceFallback:!0}),h=new Set;for(let F of p){h.add(F.relativePath);for(let V of g.get(F.symbolId)??[])h.add(V)}let b=o.filter(F=>F.isFunctionLike&&h.has(F.relativePath)).sort(SF).slice(0,Ok),S=t.calleeMap(b,{additive:!1,semantic:a}),y=new Set(p.map(F=>F.symbol)),E=_n(b.flatMap(F=>Ja(e,F,S.get(F.symbolId)??[],s,1,y).filter(V=>y.has(V.toSymbol)))),I=new Map;for(let F of E){let V=I.get(F.fromSymbol)??new Set;V.add(F.toSymbol),I.set(F.fromSymbol,V)}let v=new Set([...I].filter(([F,V])=>V.size>=2||m.has(F)).map(([F])=>F)),x=E.filter(F=>v.has(F.fromSymbol));if(v.size<2||x.length===0)return[];let L=[...new Set(x.map(F=>F.toSymbol))].map(F=>Xa(F,r,i,s)).filter(F=>F!==null).sort(Ze),w=[...v].map(F=>Xa(F,r,i,s)).filter(F=>F!==null),R=vF(w,x),P=R.slice(0,gd),_=R.slice(gd);if(L.length===0||P.length===0)return[];let D=[...new Set([...L.flatMap(F=>F.matchedTerms),...u.flatMap(F=>F.root.matchedTerms)])].sort(),M=CF(x,P);return[{id:`effect-owner-set:${d+1}:${No(L[0])}`,kind:"shared-callee-owners",roots:L,keyAnchors:P,candidateOwnerCount:R.length,omittedCandidateOwners:_,ownerRecoveryCommands:jF(_,gd),upstreamEntries:[],matchedTerms:D,relations:M,relationCount:x.length,omittedRelations:Math.max(0,x.length-M.length),systemMapCommand:Oo(P,x,D)}]})}function yF(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 bF(e,t,n,r,i){let o=Xa(e,n,r,i),s=Xa(t,n,r,i);return o?s?Ze(o,s):-1:s?1:e.localeCompare(t)}function SF(e,t){return Jt(J(e.relativePath))-Jt(J(t.relativePath))||e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine}function Xa(e,t,n,r){let i=t.get(e);if(i)return Va(i,n);let o=r.get(e);return o?ES(o):null}function vF(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)||Ze(i,o))}function CF(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(fn)),i=[],o=0;for(;i.length<$r&&r.some(s=>o<s.length);){for(let s of r){let a=s[o];if(a&&i.push(a),i.length>=$r)break}o+=1}return i.sort((s,a)=>n.get(s.fromSymbol)-n.get(a.fromSymbol)||fn(s,a))}function xF(e,t,n,r){let i=new Map(t.map((a,c)=>[a.symbol,c])),o=new Map;for(let a of e)o.set(a.fromSymbol,(o.get(a.fromSymbol)??0)+1);return[...e].sort((a,c)=>{let l=u=>{let d=0;return i.has(u.fromSymbol)&&(d+=100),n.has(u.toSymbol)&&(d+=60),d+=Math.min(40,(o.get(u.toSymbol)??0)*8),(r.get(u.toSymbol)?.matchedTerms.length??0)>0&&(d+=25),u.fromFile!==u.toFile&&(d+=15),u.strength==="exact"&&(d+=5),d};return l(c)-l(a)||fn(a,c)}).slice(0,$r).sort((a,c)=>(i.get(a.fromSymbol)??Or)-(i.get(c.fromSymbol)??Or)||a.depth-c.depth||(a.callsiteLine??Number.MAX_SAFE_INTEGER)-(c.callsiteLine??Number.MAX_SAFE_INTEGER)||fn(a,c))}function ES(e){return{symbol:e.symbol,label:ar(e),leaf:e.leaf,file:e.relativePath,line:e.startLine,endLine:e.endLine,kind:e.isFunctionLike?"callable":e.isTypeLike?"type":"symbol",fileKind:J(e.relativePath),matches:[],focusLocations:[],matchedTerms:[],symbolMatchedTerms:[],symbolPhraseLength:0,identityMatchedTerms:[],rarity:0,symbolRarity:0}}function RF(e,t,n){let r=[...e].sort(Ze),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,Or);){let u=l.filter(d=>!i.some(m=>m.symbol===d.symbol)).sort((d,m)=>m.symbolMatchedTerms.filter(f=>!a.has(f)).length-d.symbolMatchedTerms.filter(f=>!a.has(f)).length||m.symbolPhraseLength-d.symbolPhraseLength||(o.get(m.symbol)??0)-(o.get(d.symbol)??0)||yd(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=IF(i[0].symbol,i[1].symbol,t,n);for(let d of u?.slice(1,-1)??[]){if(i.length>=Or)break;c(n.get(d))}if(i.length<Or){let d=new Set(i.map(p=>p.symbol)),m=new Set(t.filter(p=>p.depth===1&&d.has(p.fromSymbol)&&d.has(p.toSymbol)).map(p=>p.fromSymbol)),f=t.filter(p=>p.depth===1&&m.has(p.fromSymbol)&&!d.has(p.toSymbol)).map(p=>({relation:p,candidate:n.get(p.toSymbol)})).filter(p=>p.candidate!==void 0&&p.candidate.symbolPhraseLength>=2&&p.candidate.symbolMatchedTerms.length>=2).sort((p,g)=>(o.get(p.relation.fromSymbol)??0)-(o.get(g.relation.fromSymbol)??0)||yd(p.candidate,g.candidate))[0]?.candidate;c(f)}}else for(;i.length<Math.min(3,Or);){let u=r.filter(d=>!i.some(m=>m.symbol===d.symbol)).sort((d,m)=>m.matchedTerms.filter(f=>!s.has(f)).length-d.matchedTerms.filter(f=>!s.has(f)).length||Ze(d,m))[0];if(!u||u.matchedTerms.every(d=>s.has(d)))break;c(u)}for(;i.length>=2&&i.length<Or;){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(f=>u.has(f.fromSymbol)&&f.toSymbol===m.symbol)).sort((m,f)=>f.identityMatchedTerms.length-m.identityMatchedTerms.length||f.symbolMatchedTerms.length-m.symbolMatchedTerms.length||f.matchedTerms.length-m.matchedTerms.length||(o.get(f.symbol)??0)-(o.get(m.symbol)??0)||Ze(m,f))[0];if(!d)break;c(d)}if(i.length<2){let u=i[0],d=u?r.filter(m=>m.symbol!==u.symbol).map(m=>({root:m,path:EF(m.symbol,u.symbol,t)})).filter(m=>m.path!==null).sort((m,f)=>+(f.root.file!==u.file)-+(m.root.file!==u.file)||m.path.length-f.path.length||Ze(m.root,f.root))[0]?.root:void 0;c(d)}return i}function IF(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,f=c+m;f>=(s.get(u)??Number.POSITIVE_INFINITY)||(s.set(u,f),o.push({path:[...a,u],cost:f}))}}return null}function EF(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 Ze(e,t){return(t.queryPathMatches?.length??0)-(e.queryPathMatches?.length??0)||t.identityMatchedTerms.length-e.identityMatchedTerms.length||t.matchedTerms.length-e.matchedTerms.length||t.rarity-e.rarity||Li(e.kind)-Li(t.kind)||Jt(e.fileKind)-Jt(t.fileKind)||e.file.localeCompare(t.file)||e.line-t.line}function yd(e,t){return t.symbolPhraseLength-e.symbolPhraseLength||t.symbolMatchedTerms.length-e.symbolMatchedTerms.length||Li(e.kind)-Li(t.kind)||t.symbolRarity-e.symbolRarity||Ze(e,t)}function wF(e,t){return t.flatMap(n=>{let r=e.filter(s=>s.matchedTerms.includes(n)).sort((s,a)=>DF(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>=aS))return i;for(let s of r)if(!i.some(a=>a.symbol===s.symbol)&&(i.push(s),i.length>=aS))break;return i})}function LF(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(![...St(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=[...St(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)=>Jt(o.fileCandidates[0].fileKind)-Jt(s.fileCandidates[0].fileKind)||o.sharedFrequency-s.sharedFrequency||o.file.localeCompare(s.file)).flatMap(({fileCandidates:o})=>[...o].sort(Ze).slice(0,Gk)).slice(0,Kk)}function DF(e,t,n){return hS(e,n)-hS(t,n)||Jt(e.fileKind)-Jt(t.fileKind)||t.symbolPhraseLength-e.symbolPhraseLength||Li(e.kind)-Li(t.kind)||Ze(e,t)}function hS(e,t){let n=e.matches.find(r=>r.term===t)?.sources??[];return Math.min(...n.map(bd),Number.MAX_SAFE_INTEGER)}function wi(e){return[...new Map(e.map(t=>[t.symbol,t])).values()]}function Br(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)||vS(e.kind)-vS(t.kind)||bS(e)-bS(t)||SS(e)-SS(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)||yS(t,n)-yS(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||Ze(e.roots[0],t.roots[0])||t.roots.length-e.roots.length||e.relationCount-t.relationCount||e.id.localeCompare(t.id)}function yS(e,t){return e.matchedTerms.reduce((n,r)=>n+1/Math.max(1,t.get(r)??1),0)}function PF(e){return[...new Set(e.roots.flatMap(t=>t.queryPathMatches??[]))].sort()}function bS(e){let t=e.keyAnchors.length>0?e.keyAnchors:e.roots;return Math.max(...t.map(n=>Jt(n.fileKind)))}function SS(e){return e.kind==="parallel-paths"?2-(e.parallelConnectedSides??0):e.kind!=="connected-flow"||e.relationCount>0?0:1}function MF(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:TF(l,s)})).filter(({overlap:l})=>l>0).sort(({group:l,overlap:u},{group:d,overlap:m})=>m-u||Br(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)=>Br(l,u,n)))}return r}function TF(e,t){return _o(e).filter(n=>t.has(n)).length}function vS(e){switch(e){case"cross-boundary-flow":return 0;case"parallel-paths":case"connected-flow":return 1;case"shared-callee-owners":return 2}}function fn(e,t){return e.depth-t.depth||cr(t.strength)-cr(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 kF(e,t){return cr(Sd(t.source))-cr(Sd(e.source))||(e.callsiteLine??Number.MAX_SAFE_INTEGER)-(t.callsiteLine??Number.MAX_SAFE_INTEGER)||e.symbol.localeCompare(t.symbol)}function _n(e){let t=new Map;for(let n of e){let r=`${n.fromSymbol}\0${n.toSymbol}`,i=t.get(r);(!i||fn(n,i)<0)&&t.set(r,n)}return[...t.values()]}function Za(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 FF(e){let t=e.match(/[\p{L}\d_.-]+(?:\/[\p{L}\d_.-]+)+/gu)??[];return[...new Set(t.map(n=>n.replace(/[.;:!?]+$/gu,"").toLocaleLowerCase()))]}function AF(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 NF(e,t){let n=Za(e).map(Cd),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 St(e){return new Set(Za(e).flatMap(wS).filter(t=>t.length>=3))}function wS(e){let t=Cd(e);return t.length>4&&t.endsWith("e")?[t,t.slice(0,-1)]:[t]}function Cd(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")?CS(t.slice(0,-2)):t.length>5&&t.endsWith("ing")?CS(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 CS(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 xS(e){if(e.length===0)return[];let t=e.split(`
88
- `);return e.endsWith(`
89
- `)&&t.pop(),t}function _F(e,t){return bd(e)-bd(t)}function bd(e){switch(e){case"symbol":return 0;case"path":return 1;case"documentation":return 2;case"source":return 3}}function Li(e){return e==="callable"?0:e==="type"?1:2}function Jt(e){switch(e){case"entry":case"source":case"worker":return 0;case"barrel":return 1;case"test":return 2}}function Sd(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function cr(e){return e==="exact"?2:1}function LS(e,t){return e.file.localeCompare(t.file)||e.line-t.line}function No(e){return`${e.file}:${e.line+1}`}function Oo(e,t=[],n=[]){let r=e.map(s=>`--symbol ${Qa(`${s.file}:${s.line+1}-${s.endLine+1}`)}`),i=new Set(e.map(s=>s.symbol)),o=e.flatMap(s=>(s.sourceCharacters??0)>pd?OF(s,t,n,i).map(a=>`--focus-at ${Qa(`${a.file}:${a.line+1}`)}`):[]);return`codebaseiq system-map ${[...r,...o,"--relation call","--relation runtime-boundary"].join(" ")}`}function OF(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(Za(BF(l.toLabel)).flatMap(wS).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||cr(u.strength)-cr(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 BF(e){return e.slice(Math.max(e.lastIndexOf(":"),e.lastIndexOf("."))+1)}function $F(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)||LS(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 jF(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(Oo(e.slice(r,r+t)));return n}function Qa(e){return`'${e.replaceAll("'",`'"'"'`)}'`}import{createHash as XS}from"crypto";function ec(e,t){return de(e)-de(t)||e.relativePath.localeCompare(t.relativePath)}function Fe(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function Di(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 Bo(e,t,n={}){let r=pe(e,t);if(!r)return null;let i=n.semantic!==!1,o=Jl(e,r,{semantic:i,semanticEvidence:ge}),s=o.rows.filter(d=>_e(d.symbol)).slice(0,50),a=Lr(e,r,{limit:50,additive:!0,callableOnly:!0,semantic:i,semanticEvidence:ge}),c=Di(a.rows),l=s.map(d=>({symbol:d.symbol,shortName:N(d.symbol),file:d.file,relationship:d.source!=="caller-map-inversion"?"reference-candidate":d.callEvidence==="scip-chunk"?"chunk-candidate":"resolved-call",evidenceStrength:d.source==="caller-map-inversion"&&d.callEvidence!=="scip-chunk"?"exact":"candidate",evidenceSource:d.callEvidence??d.source})),u=c.map(d=>({symbol:d.symbol,shortName:N(d.symbol),file:d.file,relationship:d.source==="scip-chunk"?"chunk-candidate":"resolved-call",evidenceStrength:d.source==="scip-chunk"?"candidate":"exact",evidenceSource:d.source}));return{symbol:r.symbol,shortName:N(r.symbol),callers:l.map(({symbol:d,shortName:m,file:f})=>({symbol:d,shortName:m,file:f})),callees:u.map(({symbol:d,shortName:m,file:f})=>({symbol:d,shortName:m,file:f})),callerEvidence:l,calleeEvidence:u,coverage:{scope:"indexed-static-call-graph",blindSpots:["unresolved dynamic dispatch and reflection","external or unindexed callees without a resolved symbol identity","SCIP chunk co-occurrence is retained only as candidate call evidence",...o.semanticIncomplete?["compiler-resolved incoming evidence was incomplete; known callers are retained"]:[],...o.semanticUnavailable?["compiler-resolved incoming evidence was unavailable; known callers are retained"]:[],...a.semanticIncomplete?["compiler-resolved outgoing evidence was incomplete; known callees are retained"]:[],...a.semanticUnavailable?["compiler-resolved outgoing evidence was unavailable; known callees are retained"]:[]],semanticEvidence:{enabled:i,incoming:DS(i,o),outgoing:DS(i,a)}}}}function DS(e,t){return e?t.semanticIncomplete&&t.semanticUnavailable?"incomplete-and-unavailable":t.semanticIncomplete?"incomplete":t.semanticUnavailable?"unavailable":"complete":"disabled"}function Pi(e,t,n){if(n.length===0)return[];let r=new Set(n),i=$e(e),o=new Set;if(t==="forward")for(let s of r)for(let a of i.get(s)??[])r.has(a)||o.add(a);else for(let[s,a]of i)if(!r.has(s))for(let c of r)a.has(c)&&o.add(s);return[...o].sort()}function $o(e,t){let n=mt(e,t);return n?Pi(e,"forward",[n]).filter(i=>!e.isIgnored(i)).map(i=>({relativePath:i,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):[]}function jo(e,t){let n=mt(e,t);return n?Pi(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 xd(e,t,n={}){let r=tc(e,t,n);return{definitions:r.definitions,referencedBy:r.referencedBy}}function tc(e,t,n={}){let r=pe(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=li(i?.documentation??null),s=e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,signature:GF(o,i?.display_name??null,r.symbol),source:KF(e,r.relativePath,r.startLine,r.endLine)}],a=n.referenceContext??2,c=Dp(e,r,{semantic:n.semantic,semanticEvidence:ge}).map(u=>{let d=oh(e,u.file,u.line,a,Y(r.symbol));return{relativePath:u.file,line:u.line,enclosingSymbol:u.enclosingSymbol,enclosingShort:u.enclosingSymbol?N(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(HF);return{definitions:s,referencedBy:l,referenceEvidence:c.map(u=>({relativePath:u.relativePath,line:u.line,provenance:u.provenance,sourceKind:u.sourceKind})),claimSupport:UF(c)}}function HF(e){return{relativePath:e.relativePath,line:e.line,enclosingSymbol:e.enclosingSymbol,enclosingShort:e.enclosingShort,sourceStartLine:e.sourceStartLine,sourceEndLine:e.sourceEndLine,source:e.source}}function UF(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:zF(r)}}}function zF(e){let t=[...new Set(e.map(n=>`${n.relativePath}:${n.line+1}`))];return t.length===0||t.length>24?null:`codebaseiq inspect ${t.map(n=>`--at ${qF(n)}`).join(" ")} --view behavior`}function qF(e){return`'${e.replaceAll("'","'\\''")}'`}function KF(e,t,n,r){let i=se(e,t);if(!i)return null;let s=i.split(`
90
- `).slice(n,r+1).join(`
91
- `).trimEnd();return s.length>0?s:null}function GF(e,t,n){let r=ci(e);if(r&&!WF(r))return r;let i=(t??"").trim();return i?_e(n)&&!i.endsWith("()")?`${i}()`:i:N(n)}function WF(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function Rd(e,t,n={}){let r=TS(e,t,n);if(r.kind!=="matched")return r;let{referenceEvidence:i,claimSupport:o,...s}=r;return s}function TS(e,t,n={}){let r=at(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:N(r.match.symbol),relativePath:r.match.relativePath,startLine:r.match.startLine},...r.candidates]};let i=r.match,o=JF(n.parts),s=o.includes("definition")||o.includes("references")?tc(e,i.symbol,{semantic:n.semantic,referenceContext:n.referenceContext}):{definitions:[],referencedBy:[],referenceEvidence:[],claimSupport:null},a=o.includes("callers")||o.includes("callees")?Bo(e,i.symbol,{semantic:n.semantic}):null,c=n.relatedSourceLines??80;return{kind:"matched",query:t,symbol:i.symbol,shortName:N(i.symbol),file:i.relativePath,parts:o,definition:o.includes("definition")?lh(e,i.symbol):null,referenceWindows:o.includes("references")?VF(e,s.referencedBy):[],callers:o.includes("callers")?MS(e,a?.callers??[],c):[],callees:o.includes("callees")?MS(e,a?.callees??[],c):[],dependencies:o.includes("dependencies")?$o(e,i.relativePath):[],consumers:o.includes("consumers")?jo(e,i.relativePath):[],referenceEvidence:s.referenceEvidence,claimSupport:s.claimSupport}}function VF(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(PS(i)),o.source=ie(e,o.relativePath).slice(o.startLine,o.endLine+1).join(`
92
- `);continue}r.push({relativePath:i.relativePath,startLine:i.sourceStartLine,endLine:i.sourceEndLine,source:i.source,references:[PS(i)]})}return r}function PS(e){return{line:e.line,enclosingSymbol:e.enclosingSymbol,enclosingShort:e.enclosingShort}}function JF(e){let t=e&&e.length>0?e:["definition","references"];return[...new Set(t)]}function MS(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?W(e,o.file).find(c=>c.symbol===o.symbol):void 0)??at(e,o.symbol).match;if(!s)continue;let a=sh(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 _S=6;function kS(e,t,n){return`${e}\0${t}\0${n??t}`}function OS(e,t,n,r={}){let i=r.limit??_S;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(C=>[C.id,C])),a=new Set(n.steps.map(C=>C.nodeId)),c=new Set(n.steps.flatMap(C=>{let L=wd(s.get(C.nodeId));return L?[L]:[]})),l=new Set;for(let C of n.steps)for(let L of C.behavior?.supportingDeclarations??[])c.add(L.symbol),l.add(kS(L.file,L.line,L.endLine));let u=C=>C.symbol!==null&&c.has(C.symbol)||l.has(kS(C.file,C.line,C.endLine)),d=new Map(n.steps.flatMap(C=>{if(!C.location)return[];let L=wd(s.get(C.nodeId));if(!L)return[];let w=W(e,C.location.file).find(R=>R.symbol===L);return w?[[C.id,w]]:[]})),m=new U(e).calleeMap([...d.values()],{additive:!1,semantic:!0}),f=[],p=new Set,g=new Set,h=0,b=0,S=0,y=0,E=0,I=0,v=0,x=0;for(let C of n.steps){if(!C.location||!C.behavior)continue;let L=t.edges.filter(A=>["call","runtime-boundary"].includes(A.kind)&&(A.fromNodeId===C.nodeId||A.toNodeId===C.nodeId)&&A.disposition!=="excluded"&&A.disposition!=="unsupported");for(let A of L){let K=A.toNodeId===C.nodeId,ne=K?A.fromNodeId:A.toNodeId;if(a.has(ne))continue;let fe=s.get(ne);if(!fe?.location||!o(fe.location.file))continue;let he=A.kind==="call"?Dd(e,fe):Ld(fe);if(!he||u(he))continue;let le=Pd(A,fe.location.file)??fe.location,be=ie(e,le.file)[le.line]?.trim(),T=K?"upstream":"downstream",Z=A.kind==="runtime-boundary"?K?"runtime-producer":"runtime-consumer":K?"caller":"callee",Q=["call"],Se=Id(A.evidence),rt=Ho(fe);f.push({anchor:{id:lr(C.id,le.line,fe.id),status:Se,source:"graph-relation",direction:T,causalRole:Z,relationKind:A.kind,fromStepId:C.id,fromLabel:C.label,callsite:{file:le.file,line:le.line,endLine:le.endLine??le.line,text:be||`${fe.label} \u2192 ${C.label}`,signals:Q,calleeLeaf:rt},alternatives:[he],alternativeCount:1,evidence:A.evidence}}),K&&(I+=1),A.kind==="runtime-boundary"&&(x+=1)}let w=t.edges.filter(A=>A.kind==="reference"&&A.fromNodeId===C.nodeId&&A.disposition!=="excluded"&&A.disposition!=="unsupported"&&!a.has(A.toNodeId));for(let A of w){let K=s.get(A.toNodeId);if(!K?.location||!o(K.location.file))continue;let ne=Dd(e,K);if(!ne||u(ne))continue;let fe=Ho(K),he=Pd(A,C.location.file)?.line,le=C.behavior.lines.find(Q=>(he===void 0||he>=Q.line&&he<=Q.endLine)&&Q.text.includes(fe));if(!le)continue;let be=$S(le.signals),T=be==="result-callback",Z=Id(A.evidence);f.push({anchor:{id:lr(C.id,le.line,K.id),status:Z,source:"graph-relation",direction:"downstream",causalRole:be,relationKind:"reference",fromStepId:C.id,fromLabel:C.label,callsite:{file:C.location.file,line:le.line,endLine:le.endLine,text:le.text,signals:le.signals,calleeLeaf:fe},alternatives:[ne],alternativeCount:1,evidence:A.evidence}}),T&&(v+=1)}let R=An(e,C.location.file,C.location.line,C.location.endLine??C.location.line),P=ie(e,C.location.file),_=Pn(e,C.location.file,C.location.line,C.location.endLine??C.location.line);for(let A of R.targets){if(!o(A.definition.relativePath))continue;let K=jr(C.location.file,A.sourceLine,A.calleeLeaf);if(p.has(K))continue;p.add(K);let ne=Ed(_.get(A.sourceLine)),fe={symbol:A.definition.symbol,label:A.definition.leaf,file:A.definition.relativePath,line:A.definition.startLine,endLine:A.definition.endLine};u(fe)||f.push({anchor:{id:lr(C.id,A.sourceLine,A.definition.symbol),status:"exact",source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:C.id,fromLabel:C.label,callsite:{file:C.location.file,line:A.sourceLine,endLine:A.sourceLine,text:P[A.sourceLine]?.trim()||`${A.calleeLeaf}()`,signals:ne,calleeLeaf:A.calleeLeaf},alternatives:[fe],alternativeCount:1,evidence:[{method:"scip-occurrence-callsite",strength:"exact",identity:A.definition.symbol,location:{file:C.location.file,line:A.sourceLine}}]}})}let D=C.behavior.lines.filter(A=>A.signals.includes("call"));if(D.length===0)continue;h+=1;let M=(te(e,C.location.file)?.callSites??[]).filter(A=>D.some(K=>A.line>=K.line&&A.line<=K.endLine));b+=M.length;let F=t.edges.filter(A=>A.kind==="call"&&A.fromNodeId===C.nodeId&&A.disposition!=="excluded"&&A.disposition!=="unsupported"),V=new Map;for(let A of F){let K=s.get(A.toNodeId);if(!K)continue;let ne=Ho(K);V.set(ne,(V.get(ne)??0)+1)}let ce=d.get(C.id),G=XF(e,ce?m.get(ce.symbolId)??[]:[]),X=QF(G);for(let A of G){if(!o(A.alternative.file)||u(A.alternative))continue;let K=nc(A.alternative.label),ne=AS(M,D,K,A.row.callsiteLine,X.get(K)===1);if(!ne)continue;let fe=Uo(D,ne.line,K);if(!fe)continue;let he=jr(C.location.file,ne.line,K);if(p.has(he))continue;p.add(he);let le=zS(A.row.source);f.push({anchor:{id:lr(C.id,ne.line,A.alternative.symbol??A.alternative.file),status:le,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:C.id,fromLabel:C.label,callsite:{file:C.location.file,line:fe.line,endLine:fe.endLine,text:fe.text,signals:fe.signals,calleeLeaf:K},alternatives:[A.alternative],alternativeCount:1,evidence:[{method:A.row.source,strength:le,identity:A.row.symbol,location:{file:C.location.file,line:ne.line}}]}})}for(let A of F){if(a.has(A.toNodeId))continue;let K=s.get(A.toNodeId);if(!K?.location||!o(K.location.file))continue;let ne=Ho(K),fe=A.evidence.find(Q=>{let Se=Q.location;return Se!==null&&Se.file===C.location?.file&&Se.line>=0})?.location?.line,he=AS(M,D,ne,fe,V.get(ne)===1);if(!he)continue;let le=Uo(D,he.line,ne);if(!le)continue;let be=jr(C.location.file,he.line,ne);if(p.has(be))continue;p.add(be);let T=Ld(K);if(!T||u(T))continue;let Z=Id(A.evidence);f.push({anchor:{id:lr(C.id,he.line,K.id),status:Z,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:C.id,fromLabel:C.label,callsite:{file:C.location.file,line:le.line,endLine:le.endLine,text:le.text,signals:le.signals,calleeLeaf:ne},alternatives:[T],alternativeCount:1,evidence:A.evidence}})}for(let A of M){let K=jr(C.location.file,A.line,A.calleeLeaf);if(p.has(K))continue;let ne=Uo(D,A.line,A.calleeLeaf);if(!ne)continue;let fe=on(C.location.file,sn(e).get(A.calleeLeaf)??[]).flatMap(T=>W(e,T.file).filter(Z=>Z.symbol===T.symbol&&Z.isFunctionLike)).filter(T=>o(T.relativePath)&&!u({symbol:T.symbol,label:T.leaf,file:T.relativePath,line:T.startLine,endLine:T.endLine})),he=ic(fe.map(T=>({symbol:T.symbol,label:T.leaf??A.calleeLeaf,file:T.relativePath,line:T.startLine,endLine:T.endLine})));if(he.length===0){E+=1;continue}let le=`${C.id}\0${A.line}\0${A.calleeLeaf}`;if(g.has(le))continue;g.add(le);let be=he.length>1;be?y+=1:S+=1,f.push({anchor:{id:lr(C.id,A.line,A.calleeLeaf),status:be?"ambiguous":"candidate",source:"leaf-identity-candidate",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:C.id,fromLabel:C.label,callsite:{file:C.location.file,line:ne.line,endLine:ne.endLine,text:ne.text,signals:ne.signals,calleeLeaf:A.calleeLeaf},alternatives:he.slice(0,3),alternativeCount:he.length,evidence:[]}})}}return HS(e,f,n.steps,i,{scannedBehaviorSteps:h,visibleCallsites:b,graphEvidencedCallsites:p.size,identityCandidateCallsites:S,ambiguousCallsites:y,unresolvedCallsites:E,upstreamCandidates:I,resultCandidates:v,runtimeCandidates:x},r.selectionTerms)}function BS(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||!Dd(e,s))continue;let a=Ho(s),c=Pd(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||$S(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 $S(e){return e.includes("call")&&e.some(t=>["return","mutation","shape","spread","binding"].includes(t))?"result-callback":"callable-reference"}function jS(e,t,n={}){let r=n.limit??_S;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((f,p)=>({id:f.id,nodeId:f.id,order:p,role:"anchor",kind:"source-construct",label:f.label,location:{file:f.file,line:f.startLine,endLine:f.endLine},behavior:null})),a=t.map(f=>({file:f.file,startLine:f.startLine,endLine:f.endLine})),c=0,l=0,u=0,d=0,m=0;for(let f of t){let p=ie(e,f.file),h=(te(e,f.file)?.callSites??[]).filter(v=>v.line>=f.startLine&&v.line<=f.endLine);c+=h.length;let b=Pn(e,f.file,f.startLine,f.endLine),S=An(e,f.file,f.startLine,f.endLine),y=new Set;for(let v of S.targets){if(!i(v.definition.relativePath)||a.some(w=>w.file===v.definition.relativePath&&w.startLine<=v.definition.startLine&&w.endLine>=v.definition.endLine))continue;let x=jr(f.file,v.sourceLine,v.calleeLeaf);y.add(x);let C=Ed(b.get(v.sourceLine)),L={symbol:v.definition.symbol,label:v.definition.leaf,file:v.definition.relativePath,line:v.definition.startLine,endLine:v.definition.endLine};o.push({anchor:{id:lr(f.id,v.sourceLine,v.definition.symbol),status:"exact",source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:f.id,fromLabel:f.label,callsite:{file:f.file,line:v.sourceLine,endLine:v.sourceLine,text:p[v.sourceLine]?.trim()||`${v.calleeLeaf}()`,signals:C,calleeLeaf:v.calleeLeaf},alternatives:[L],alternativeCount:1,evidence:[{method:"scip-occurrence-callsite",strength:"exact",identity:v.definition.symbol,location:{file:f.file,line:v.sourceLine}}]}})}l+=S.resolvedCallsites;let E=sr(e,f.file,{ranges:[{startLine:f.startLine,endLine:f.endLine}]}),I=new Map;for(let v of E.targets){let x=h.find(w=>w.line===v.line)?.calleeLeaf??v.calleeLeaf,C=jr(f.file,v.line,x),L=I.get(C)??[];L.push(v),I.set(C,L)}for(let[v,x]of I){if(y.has(v))continue;y.add(v);let C=x.filter(D=>i(D.targetFile)&&!a.some(M=>M.file===D.targetFile&&M.startLine<=D.targetStartLine&&M.endLine>=D.targetEndLine));if(C.length===0)continue;let L=C[0],w=h.find(D=>D.line===L.line)?.calleeLeaf??L.calleeLeaf,R=Ed(b.get(L.line)),P=ic(C.map(D=>({symbol:D.targetSymbol??null,label:D.calleeLeaf,file:D.targetFile,line:D.targetStartLine,endLine:D.targetEndLine}))),_=C.some(D=>(D.resolutionAlternativeCount??0)>1)?"candidate":C.every(D=>D.strength==="exact")?"exact":"derived";o.push({anchor:{id:lr(f.id,L.line,P.map(D=>`${D.file}:${D.line}`).join("|")),status:P.length>1?"ambiguous":_,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:f.id,fromLabel:f.label,callsite:{file:f.file,line:L.line,endLine:L.line,text:p[L.line]?.trim()||`${L.calleeLeaf}()`,signals:R,calleeLeaf:w},alternatives:P.slice(0,3),alternativeCount:P.length,evidence:C.map(D=>({method:D.resolution==="constructed-member-receiver"?"ast-constructed-member-callsite":D.resolution==="factory-callback-member"?"ast-factory-callback-callsite":D.resolution==="imported-service-object-member"?"ast-service-member-callsite":"ast-import-member-callsite",strength:_,identity:D.targetSymbol??`${D.targetFile}:${D.targetStartLine}-${D.targetEndLine}`,location:{file:f.file,line:L.line}}))}})}l+=I.size;for(let v of h){let x=jr(f.file,v.line,v.calleeLeaf);y.has(x)||(m+=1)}}return HS(e,o,s,r,{scannedBehaviorSteps:t.length,visibleCallsites:c,graphEvidencedCallsites:l,identityCandidateCallsites:u,ambiguousCallsites:d,unresolvedCallsites:m,upstreamCandidates:0,resultCandidates:0,runtimeCandidates:0})}function HS(e,t,n,r,i,o=[]){let s=ZF(t).sort(US),a=s.filter(p=>YF(e,p)).slice(0,r),c=new Set(a.map(p=>p.anchor.id)),l=s.filter(p=>!c.has(p.anchor.id)),u=a.map(p=>p.anchor),d=l.map(p=>p.anchor),m=ic(u.flatMap(p=>p.alternativeCount===1?p.alternatives:[])),f=ic(d.flatMap(p=>p.alternativeCount===1?p.alternatives:[]));return{anchors:u,withheldAnchors:d,candidateAnchors:s.length,omittedAnchors:Math.max(0,s.length-u.length),...i,inspectCommand:m.length===0?null:`codebaseiq inspect ${m.map(NS).join(" ")} --view behavior`,remainingInspectCommands:tA(f,8).map(p=>`codebaseiq inspect ${p.map(NS).join(" ")} --view behavior`)}}function US(e,t){let n=e.anchor.alternatives[0],r=t.anchor.alternatives[0];return rc(e.anchor.status)-rc(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 YF(e,t){if(t.anchor.alternativeCount!==1)return!0;let n=t.anchor.alternatives[0],r=n.endLine??n.line;return ie(e,n.file).slice(n.line,r+1).join(`
93
- `).length<=2e4}function Ed(e){return e?.includes("call")?[...e]:["call",...e??[]]}function XF(e,t){let n=new Map;for(let r of t){let i=W(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||FS(r.source)>FS(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 QF(e){let t=new Map;for(let n of e){let r=nc(n.alternative.label);t.set(r,(t.get(r)??0)+1)}return t}function zS(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function FS(e){return zS(e)==="exact"?2:1}function Uo(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 AS(e,t,n,r,i){if(r!==void 0)return e.find(s=>s.line===r&&s.calleeLeaf===n&&Uo(t,s.line,n)!==null)??null;let o=e.filter(s=>s.calleeLeaf===n&&Uo(t,s.line,s.calleeLeaf)!==null);return i&&o.length===1?o[0]:null}function Ho(e){let t=e.attributes.leaf;if(typeof t=="string"&&t.length>0)return nc(t);let n=e.label.slice(e.label.lastIndexOf(":")+1);return nc(n)}function nc(e){return e.replace(/\(\)$/u,"").replace(/^#/u,"")}function wd(e){if(e?.kind!=="symbol"||!e.id.startsWith("symbol:"))return null;try{return decodeURIComponent(e.id.slice(7))}catch{return null}}function Ld(e){return e.location?{symbol:wd(e),label:e.label,file:e.location.file,line:e.location.line,endLine:e.location.endLine??null}:null}function Dd(e,t){let n=Ld(t);return n?.symbol&&W(e,n.file).some(i=>i.symbol===n.symbol&&i.isFunctionLike)?n:null}function Pd(e,t){return e.evidence.find(n=>n.location?.file===t)?.location??e.evidence.find(n=>n.location!==null)?.location??null}function Id(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 ZF(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||eA(n,o)<0)&&t.set(i,n)}return[...t.values()]}function eA(e,t){return rc(e.anchor.status)-rc(t.anchor.status)||e.anchor.alternativeCount-t.anchor.alternativeCount||US(e,t)}function rc(e){return{exact:0,derived:1,mixed:2,candidate:3,unknown:4,ambiguous:5}[e]}function ic(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 NS(e){return`--at ${nA(`${e.file}:${e.line+1}`)}`}function tA(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function nA(e){return`'${e.replaceAll("'","'\\''")}'`}function jr(e,t,n){return`${e}\0${t}\0${n}`}function lr(e,t,n){return["next-anchor",e,String(t),n].map(encodeURIComponent).join(":")}var QS=6,rA=12,iA=48,oA=2e4,qS=12,Hr=Number.MAX_SAFE_INTEGER,sA=["definition","callers","callees"],Ad={search:12,"exact-source":24,definition:24,caller:8,callee:8,"production-reference":6,"test-reference":2,dependency:6,consumer:6};function aA(e,t){if(t.cursor)throw new Error("Inspect no longer accepts semantic packet cursors. Run the original inspect selectors again.");let n=lA(t),r=mA(e,n),i=r.candidates.sort((P,_)=>Md(P,_));n.view==="behavior"&&gA(e,i),hA(e,i),n.view==="behavior"&&fA(e,i);let o=kb(i.map(P=>kd(P,n.view)),n.evidenceBudgets,(P,_)=>Md(P.candidate,_.candidate)),{selected:s,omitted:a}=Ua(o.selected,n.maxUnits,n.maxCharacters,(P,_)=>Md(P.candidate,_.candidate),n.view==="source"),c=s.map(P=>P.candidate),l=[...o.omitted,...a].map(P=>P.candidate),u=c.map(EA),d=da(c.map(P=>P.kind==="source"?P.bindingClosure:void 0),c.filter(P=>P.kind==="source").map(P=>({relativePath:P.relativePath,startLine:P.startLine,endLine:P.endLine}))),m=u.reduce((P,_)=>P+(_.kind==="source"?DA(_.source):0),0),f=u.reduce((P,_)=>P+(_.kind==="source"?_.source.length:0),0),p=u.reduce((P,_)=>P+tv(_,n.view),0),g=u.filter(P=>P.kind==="source"&&(P.roles.includes("search")||P.roles.includes("location"))).map(wA),h=i.filter(P=>P.kind==="source"&&(P.roles.includes("search")||P.roles.includes("location"))).length,b=u.filter(P=>P.kind==="source"&&(P.roles.includes("search")||P.roles.includes("location"))).length,S=r.searches.map(P=>SA(P,i,c)),y=vA(l),E=r.locations.every(P=>P.matched)&&r.evidence.every(P=>P.kind==="matched")&&r.searches.every(P=>xA(P.textCoverage))&&l.every(P=>!P.roles.some(_=>_==="location"||_==="definition")),I=S.reduce((P,_)=>P+_.omittedMatches,0),v=l.length===0&&I===0,x=v?void 0:ev(n,!0),C=yA(n,l),L=cA(v,E,l.length+I,C,S,x),w=i.filter(P=>n.view==="behavior"&&P.kind==="source"&&P.roles.some(_=>_==="location"||_==="definition"||_==="search")).map(P=>({id:`inspect:${P.relativePath}:${P.startLine}-${P.endLine}`,label:P.ownerShort??`${P.relativePath}:${P.startLine+1}`,file:P.relativePath,startLine:P.startLine,endLine:P.endLine})),R=w.length>0?jS(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:f,returnedViewCharacters:p,view:n.view,omissionGroups:C,packetCoverage:{mode:v?"complete":"bounded",candidateUnits:i.length,returnedUnits:u.length,omittedUnits:l.length,omittedByRole:y,exactSelectorsComplete:E,maxUnits:n.maxUnits,maxCharacters:n.maxCharacters,channels:CA(i,c,n.evidenceBudgets,n.view),...x?{expansionCommand:x}:{}},stoppingSummary:L,...R&&R.candidateAnchors>0?{causalFrontier:R}:{},bindingClosure:d,continuation:null}}function cA(e,t,n,r,i,o){let s=ft([...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 lA(e){let t=Td(e.searches),n=Td(e.symbols),r=Td(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&&ur(e.unitLines,"unitLines"),e.totalLines!==void 0&&ur(e.totalLines,"totalLines"),e.sliceLimit!==void 0&&ur(e.sliceLimit,"sliceLimit"),e.maxCharacters!==void 0&&ur(e.maxCharacters,"maxCharacters"),e.maxUnits!==void 0&&ur(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:YS(e.context??QS,"context"),searchLimit:ur(e.searchLimit??(s?Hr:rA),"searchLimit"),maxUnits:ur(s?Hr:e.maxUnits??iA,"maxUnits"),maxCharacters:ur(s?Hr:e.maxCharacters??oA,"maxCharacters"),evidenceBudgets:s?dA():uA(e.evidenceBudgets??Ad),view:e.view??"source",evidence:{...o.parts?{parts:[...o.parts]}:n.length>0?{parts:[...sA]}:{},...o.referenceContext!==void 0?{referenceContext:YS(o.referenceContext,"referenceContext")}:{},relatedSourceLines:o.relatedSourceLines??60,...o.semantic!==void 0?{semantic:o.semantic}:{}}}}function uA(e){let t={...Ad};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 dA(){return Object.fromEntries(Object.keys(Ad).map(e=>[e,Hr]))}function mA(e,t){let n=[],r=0,i=t.searches.map(l=>{let u=ad(e,l,{scope:t.scope,context:0,limit:t.searchLimit,ranking:"structural"});return{pattern:l,result:u,matches:u.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=nr(e,d.relativePath,d.focusLine,Hr,t.context);m&&Mi(e,n,m,"search",`search:${u.pattern}`,d.ownerSymbol,d.ownerShort,1,r++)}let s=i.map(({pattern:l,result:u})=>{let d=u.omittedMatches>0?ZS(l,t.scope):void 0,m=u.fileCoverage??[],f=RA(l,m,t.scope);return{pattern:l,matchingLines:u.matchingLines,returnedMatches:u.matches.length,omittedMatches:u.omittedMatches,matchingFiles:m.length,returnedFiles:m.filter(p=>p.returnedMatches>0).length,omittedFiles:m.filter(p=>p.returnedMatches===0).length,candidateUnits:0,selectedUnits:0,omittedUnits:0,scopeHints:f.slice(0,qS),omittedScopeHints:Math.max(0,f.length-qS),textCoverage:u.textCoverage,...d?{exactFollowup:d}:{}}}),a=t.locations.map(l=>{let u=LA(l),d=u?mt(e,u.path):null,m=d?nr(e,d,u.line-1,Hr,t.context):null;return m&&Mi(e,n,m,"location",`at:${l}`,null,null,0,r++),{target:l,matched:m!==null}}),c=t.symbols.map(l=>Rd(e,l,t.evidence));for(let l of c)if(l.kind==="matched"){if(l.definition){let u=nr(e,l.definition.relativePath,l.definition.startLine,Hr,t.context);u&&Mi(e,n,u,"definition",`definition:${l.shortName}`,l.symbol,l.shortName,0,r++)}for(let u of l.referenceWindows){let d=u.references[0];Mi(e,n,{...u,focusLine:d?.line??u.startLine,unitType:null,unitStartLine:u.startLine,unitEndLine:u.endLine,omittedLines:0},"reference",`reference:${l.shortName}`,d?.enclosingSymbol??null,d?.enclosingShort??null,J(u.relativePath)==="test"?5:4,r++,u.references.map(m=>m.line),l.symbol)}for(let u of l.callers)GS(e,n,u,"caller",l,2,r++);for(let u of l.callees)GS(e,n,u,"callee",l,3,r++);for(let u of l.dependencies)WS(e,n,"dependency",l.file,u.relativePath,l.symbol,t.context,6,r++);for(let u of l.consumers)WS(e,n,"consumer",u.relativePath,l.file,l.symbol,t.context,7,r++)}return{searches:s,evidence:c,locations:a,candidates:n}}function Md(e,t){return e.priority-t.priority||t.roles.length-e.roles.length||t.reasons.length-e.reasons.length||KS(J(e.relativePath))-KS(J(t.relativePath))||e.sequence-t.sequence}function KS(e){switch(e){case"entry":case"source":case"worker":return 0;case"barrel":return 1;case"test":return 2}}function kd(e,t){return{candidate:e,priority:e.priority,sequence:e.sequence,relativePath:e.relativePath,fileKind:J(e.relativePath),evidenceCharacters:tv(e,t),roles:e.roles,reasons:e.reasons,symbols:e.symbols,behaviorSignals:e.kind==="source"?e.behavior?.signals??[]:[],channel:Fd(e)}}function Fd(e){let t=e.roles;return t.includes("location")?"exact-source":t.includes("definition")?"definition":t.includes("caller")?"caller":t.includes("callee")?"callee":t.includes("reference")?J(e.relativePath)==="test"?"test-reference":"production-reference":t.includes("dependency")?"dependency":t.includes("consumer")?"consumer":"search"}function fA(e,t){let n=t.filter(i=>i.kind==="source"),r=to(e,{files:ft(n.map(i=>i.relativePath))});for(let i of n){i.behavior=pi(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=>!pA(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 pA(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 gA(e,t){for(let n of t){if(n.kind!=="source")continue;let r=bt(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=ie(e,n.relativePath).slice(r.startLine,r.endLine+1).join(`
94
- `),n.unitStartLine=r.startLine,n.unitEndLine=r.endLine,n.omittedLines=0)}}function hA(e,t){for(let n of t)n.kind==="source"&&(n.bindingClosure=fi(e,n.relativePath,n.startLine,n.endLine))}function yA(e,t){let n=new Map;for(let r of t){let i=oc(r.relativePath),o=Fd(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=ft(i.flatMap(c=>[...c.roles])).sort(),a=ft(i.flatMap(c=>c.kind==="source"?c.behavior?.signals??[]:[])).sort();return{id:`g-${XS("sha256").update(r).digest("hex").slice(0,8)}`,scope:oc(o.relativePath),channel:Fd(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:bA(e,i)}}).sort((r,i)=>i.candidateUnits-r.candidateUnits||i.sourceCharacters-r.sourceCharacters||r.scope.localeCompare(i.scope)||r.id.localeCompare(i.id))}function bA(e,t){let n=ft(t.flatMap(o=>o.reasons.filter(s=>s.startsWith("search:")).map(s=>s.slice(7)))),r=oc(t[0].relativePath);if(n.length>0&&t.every(o=>o.kind==="source"&&o.roles.includes("search"))){let o=["codebaseiq inspect"];for(let s of n)o.push(`--search ${jt(s)}`);return o.push(`--scope ${jt(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=["codebaseiq inspect"];for(let s of i)o.push(`--at ${jt(`${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:ev(e,!0)}function SA(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 vA(e){let t={};for(let n of e)for(let r of n.roles)t[r]=(t[r]??0)+1;return t}function CA(e,t,n,r){let i=e.map(s=>kd(s,r).channel),o=t.map(s=>kd(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 xA(e){return!!(e&&e.skippedUnreadablePaths.length===0&&e.skippedOversizedPaths.length===0)}function RA(e,t,n){let r=new Map;for(let i of t){let o=oc(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:ZS(e,i||n)})).sort((i,o)=>o.matchingLines-i.matchingLines||o.returnedMatches-i.returnedMatches||i.scope.localeCompare(o.scope))}function oc(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}function ZS(e,t){return`codebaseiq inspect --search ${jt(e)}${t?` --scope ${jt(t)}`:""} --full`}function ev(e,t){let n=["codebaseiq inspect"];for(let r of e.searches)n.push(`--search ${jt(r)}`);for(let r of e.symbols)n.push(`--symbol ${jt(r)}`);for(let r of e.locations)n.push(`--at ${jt(r)}`);return e.scope&&n.push(`--scope ${jt(e.scope)}`),e.context!==QS&&n.push(`--context ${e.context}`),e.evidence.parts&&n.push(`--include ${jt(e.evidence.parts.join(","))}`),t&&n.push("--full"),e.view==="behavior"&&n.push("--view behavior"),n.join(" ")}function GS(e,t,n,r,i,o,s){Mi(e,t,{...n,unitType:null,unitStartLine:n.startLine,unitEndLine:n.endLine+n.omittedLines},r,`${r}:${i.shortName}`,n.symbol,n.shortName,o,s,[n.focusLine],i.symbol)}function WS(e,t,n,r,i,o,s,a,c){let l=`${r} -> ${i}`,u=Ce(e,r).filter(h=>h.sourcePath===i),d=ie(e,r),m=IA(d,u,i),f=m===null?null:Ca(e,r,m,Math.min(s,4));if(f){Mi(e,t,{...f,unitType:null,unitStartLine:f.startLine,unitEndLine:f.endLine,omittedLines:0},n,`${n}:${l}`,null,null,a,c,[f.focusLine],o);return}let p=`codebaseiq inspect --search ${jt(nv(i))} --scope ${jt(r)}`,g=t.find(h=>h.kind==="path"&&h.relativePath===r&&h.relationship===l);if(g){g.roles=ft([...g.roles,n]),g.reasons=ft([...g.reasons,`${n}:${l}`]),g.symbols=ft([...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:p,priority:a,sequence:c})}function IA(e,t,n){let r=ft(t.flatMap(c=>[c.importedName,c.localName??""]).filter(c=>c.length>1)),i=nv(n).replace(/\.[^.]+$/u,""),o=ft([...r,i]).filter(Boolean),s=/\b(?:from|import|include|require|use)\b/u,a=e.findIndex(c=>s.test(c)&&o.some(l=>c.includes(l)));return a>=0?a:null}function Mi(e,t,n,r,i,o,s,a,c,l=[n.focusLine],u){let d=t.find(m=>m.kind==="source"&&m.relativePath===n.relativePath&&m.startLine<=n.endLine&&n.startLine<=m.endLine);if(d){let m=Math.min(d.startLine,n.startLine),f=Math.max(d.endLine,n.endLine);d.startLine=m,d.endLine=f,d.source=ie(e,n.relativePath).slice(m,f+1).join(`
95
- `),d.focusLine=Math.min(d.focusLine,n.focusLine),d.focusLines=JS([...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=ft([...d.reasons,i]),d.roles=ft([...d.roles,r]),d.symbols=ft([...d.symbols,...u?[u]:[]]),!d.ownerSymbol&&o&&(d.ownerSymbol=o),!d.ownerShort&&s&&(d.ownerShort=s),d.priority=Math.min(d.priority,a);return}t.push({kind:"source",...n,reasons:[i],focusLines:JS(l),ownerSymbol:o,ownerShort:s,roles:[r],symbols:u?[u]:[],priority:a,sequence:c})}function EA(e){if(e.kind==="path"){let{priority:o,sequence:s,...a}=e;return{...a,id:VS(a)}}let{priority:t,sequence:n,bindingClosure:r,...i}=e;return{...i,id:VS(i),omittedCharacters:0}}function wA(e){let{kind:t,id:n,roles:r,symbols:i,omittedCharacters:o,behavior:s,runtimeFacts:a,...c}=e;return c}function VS(e){return XS("sha256").update(JSON.stringify(e)).digest("hex").slice(0,16)}function LA(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 Td(e){return ft((e??[]).map(t=>t.trim()).filter(Boolean))}function ft(e){return[...new Set(e)]}function JS(e){return ft(e).sort((t,n)=>t-n)}function DA(e){return e.length===0?0:e.split(`
96
- `).length}function tv(e,t){if(e.kind==="path")return e.relationship.length+e.exactFollowup.length;let n="bindingClosure"in e?Hg(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 nv(e){return e.split("/").at(-1)??e}function jt(e){return`'${e.replaceAll("'","'\\''")}'`}function ur(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new RangeError(`${t} must be a positive safe integer; received ${e}`);return e}function YS(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 PA}from"path";function MA(e,t){let n=t.className,r=at(e,n);return r.match?r.total>1?{kind:"ambiguous",query:n,total:r.total,candidates:[rv(r.match),...r.candidates]}:{kind:"matched",query:n,owner:kA(r.match),methods:TA(e,r.match)}:{kind:"missing",query:n,suggestions:Ks(e,n,5)}}function TA(e,t){let n=Y(t.symbol),i=new U(e).definitionsForFile(t.relativePath).filter(c=>st(c.symbol)),o=i.filter(c=>c.parentTypeName===n||c.symbol.includes(n)),a=(o.length>0?o:FA(PA(t.relativePath))===n?i.filter(c=>c.symbol.includes("<invalid-global-code>")):[]).map(c=>({startLine:c.startLine,endLine:c.endLine,name:Y(c.symbol)}));return ye(t.relativePath)!=="clojure"?a:NA(a,AA(e,t))}function rv(e){return{symbol:e.symbol,shortName:N(e.symbol),relativePath:e.relativePath,startLine:e.startLine}}function kA(e){return{...rv(e),endLine:e.endLine}}function FA(e){return e.replace(/\.[^.]+$/,"")}function AA(e,t){let n=Y(t.symbol);return n?(te(e,t.relativePath)?.clojureMembers??[]).filter(r=>r.ownerName===n).map(r=>({startLine:r.startLine,endLine:r.endLine,name:r.memberName})):[]}function NA(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 EO}from"crypto";var iv=["call","contract-symbol","import","reference","runtime-boundary"],_A={call:[{family:"control",subtype:"call"}],"contract-symbol":[{family:"contract",subtype:"uses-contract-symbol"}],import:[{family:"identity",subtype:"imports"}],reference:[{family:"identity",subtype:"references"}]},OA={"structural-membership":[{family:"identity",subtype:"contains"}],"boundary-observation":[{family:"identity",subtype:"owns-runtime-observation"}],"external-import":[{family:"identity",subtype:"imports-external"}]};function ov(e){if(e.kind!=="runtime-boundary")return sv(_A[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 sc(e){return sv(OA[e])}function sv(e){return e.map(t=>({...t,...t.context?{context:{...t.context}}:{},...t.attributes?{attributes:{...t.attributes}}:{}}))}import{join as lN}from"path";import{createRequire as BA}from"module";import{resolve as qo}from"path";var $A=BA(import.meta.url),zo;function cv(e,t,n){let r=jA();if(!r)return Nd("The TypeScript compiler runtime is unavailable.");let i=HA(r,e,t),o=i.getSourceFile(qo(t))??i.getSourceFile(t);if(!o)return Nd(`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=zA(r,o,n);if(a.length===0)return Nd("No function-like construct intersects the selected source range.");let c=new Map(a.map(d=>[d,qA(o,d)])),l=a.map(d=>GA(s,d,KA(r,d,c),c.get(d)));for(let d of l)WA(s,d),XA(s,d),eN(s,d);nN(s,l);let u=[...s.unsupported].sort();return{points:[...s.points.values()].map(({node:d,...m})=>m).sort(cN),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 jA(){if(zo!==void 0)return zo;try{zo=$A("typescript")}catch{zo=Vs()?.ts??null}return zo}function HA(e,t,n){let r=qo(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,UA(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,f)=>qo(u)===r?o:a(u,d,m,f),s.readFile=u=>qo(u)===r?t:c(u),s.fileExists=u=>qo(u)===r||l(u),e.createProgram([r],i,s)}function UA(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 zA(e,t,n){let r=[],i=o=>{if(lv(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 lv(e,t){return e.isFunctionLike(t)&&"body"in t&&t.body!==void 0}function qA(e,t){return`callable:${encodeURIComponent(e.fileName)}:${t.getStart(e)}:${t.getEnd()}`}function KA(e,t,n){for(let r=t.parent;r;r=r.parent)if(lv(e,r)&&n.has(r))return n.get(r);return null}function GA(e,t,n,r){let i=new Map,o=et(e,i,"exit",null),s=t.body,a=o.id;if(s&&e.ts.isBlock(s))a=_d(e,i,[...s.statements],o.id,{breakTarget:null,continueTarget:null});else if(s){let l=et(e,i,"statement",s);Oe(i,l.id,o.id),a=l.id}let c=et(e,i,"entry",t);return Oe(i,c.id,a),{id:r,node:t,parentId:n,cfg:i,entryId:c.id,exitId:o.id}}function _d(e,t,n,r,i){let o=r;for(let s=n.length-1;s>=0;s-=1)o=Ur(e,t,n[s],o,i);return o}function Ur(e,t,n,r,i){let o=e.ts;if(o.isBlock(n))return _d(e,t,[...n.statements],r,i);if(o.isIfStatement(n)){let a=et(e,t,"predicate",n.expression),c=Ur(e,t,n.thenStatement,r,i),l=n.elseStatement?Ur(e,t,n.elseStatement,r,i):r;return Oe(t,a.id,c),Oe(t,a.id,l),a.id}if(o.isWhileStatement(n)){let a=et(e,t,"predicate",n.expression),c=Ur(e,t,n.statement,a.id,{breakTarget:r,continueTarget:a.id});return Oe(t,a.id,c),Oe(t,a.id,r),a.id}if(o.isDoStatement(n)){let a=et(e,t,"predicate",n.expression),c=Ur(e,t,n.statement,a.id,{breakTarget:r,continueTarget:a.id});return Oe(t,a.id,c),Oe(t,a.id,r),c}if(o.isForStatement(n)){let a=et(e,t,"predicate",n.condition??n),c=n.incrementor?et(e,t,"statement",n.incrementor):null;c&&Oe(t,c.id,a.id);let l=c?.id??a.id,u=Ur(e,t,n.statement,l,{breakTarget:r,continueTarget:l});if(Oe(t,a.id,u),n.condition&&Oe(t,a.id,r),!n.initializer)return a.id;let d=et(e,t,"statement",n.initializer);return Oe(t,d.id,a.id),d.id}if(o.isForInStatement(n)||o.isForOfStatement(n)){e.unsupported.add("for-in/for-of iterator assignment is conservatively represented without iterable element flow.");let a=et(e,t,"predicate",n.expression),c=et(e,t,"statement",n.initializer),l=Ur(e,t,n.statement,a.id,{breakTarget:r,continueTarget:a.id});return Oe(t,a.id,c.id),Oe(t,a.id,r),Oe(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=et(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=_d(e,t,[...d.statements],c,{...i,breakTarget:r}),l.push(c)}for(let u of l)Oe(t,a.id,u);return Oe(t,a.id,r),a.id}if(o.isReturnStatement(n)||o.isThrowStatement(n)){let a=et(e,t,"statement",n),c=[...t.values()].find(l=>l.kind==="exit");return Oe(t,a.id,c.id),a.id}if(o.isBreakStatement(n)){let a=et(e,t,"statement",n);return i.breakTarget||e.unsupported.add("A break statement could not be attached to a structured target."),Oe(t,a.id,i.breakTarget??r),a.id}if(o.isContinueStatement(n)){let a=et(e,t,"statement",n);return i.continueTarget||e.unsupported.add("A continue statement could not be attached to a structured target."),Oe(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=et(e,t,"statement",n);return a.invalidatesAllDefinitions=!0,Oe(t,a.id,r),a.id}let s=et(e,t,"statement",n);return Oe(t,s.id,r),s.id}function et(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 Oe(e,t,n){e.get(t).successors.add(n),e.get(n).predecessors.add(t)}function WA(e,t){let n=t.cfg.get(t.entryId);for(let r of t.node.parameters){let i=zr(e,r.name);if(!i){e.unsupported.add("Destructured parameter definition-use is not implemented.");continue}n.definitions.push({point:qr(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=qr(e,r.ast,"predicate",null,"predicate",t.id)),VA(e,t,r,r.ast),!r.displayPoint&&r.definitions.length===0&&r.uses.length===0&&(r.displayPoint=qr(e,r.ast,"statement",null,iN(e,r.ast),t.id)))}function VA(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?ac(e,t.id,s.initializer,n):[];n.uses.push(...a);let c=zr(e,s.name);c?n.definitions.push({point:qr(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)&&mv(i,s.operatorToken.kind)){let a=ac(e,t.id,s.right,n);s.operatorToken.kind!==i.SyntaxKind.EqualsToken&&a.push(...ac(e,t.id,s.left,n)),n.uses.push(...a);let c=zr(e,s.left);c?n.definitions.push({point:qr(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=ac(e,t.id,s.operand,n);n.uses.push(...a);let c=zr(e,s.operand);c&&n.definitions.push({point:qr(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(uv(e,s)){let a=dv(e,t.id,s);a&&n.uses.push(a),i.isPropertyAccessExpression(s)&&o(s.expression);return}s.forEachChild(o)}}};o(r),n.uses=fv(n.uses)}function ac(e,t,n,r){let i=[],o=s=>{if(!e.ts.isFunctionLike(s)){if(e.ts.isBinaryExpression(s)&&mv(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(uv(e,s)){let a=dv(e,t,s);a&&i.push(a),e.ts.isPropertyAccessExpression(s)&&o(s.expression);return}s.forEachChild(o)}};return o(n),fv(i)}function uv(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&&JA(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)||YA(e.ts,t))}function JA(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 YA(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 dv(e,t,n){let r=zr(e,n);return r?{point:qr(e,r.node,"use",r.symbolKey,r.name,t),property:e.ts.isPropertyAccessExpression(n)}:null}function zr(e,t){let n=e.ts;if(n.isIdentifier(t)){let r=av(e,t);return r?{node:t,symbolKey:r,name:t.text}:null}if(n.isPropertyAccessExpression(t)){let r=av(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)?zr(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 av(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 qr(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 XA(e,t){let n=[...t.cfg.values()].flatMap(c=>c.definitions),r=new Map(n.map(c=>[c.point.id,c])),i=QA(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=sN([...c.predecessors].map(m=>s.get(m))),u=new Set(l);c.invalidatesAllDefinitions&&u.clear();let d=ZA(c.definitions);for(let m of d){for(let f of i.get(m.point.symbolKey)??[])u.delete(f.point.id);u.add(m.point.id)}Od(o.get(c.id),l)||(o.set(c.id,l),a=!0),Od(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(f=>f.point.symbolKey===u.point.symbolKey&&f.point.start<u.point.start&&!f.rhsUseIds.includes(u.point.id)).sort((f,p)=>p.point.start-f.point.start)[0],m=d?[d.point.id]:l;for(let f of m){let p=r.get(f);p.point.symbolKey===u.point.symbolKey&&Ko(e,"reaching-definition",p.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)Ko(e,"value-source",d,u.point.id,"exact","This right-hand-side use supplies the new definition.")}}function QA(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 ZA(e){let t=new Map;for(let n of e)n.point.symbolKey&&t.set(n.point.symbolKey,n);return[...t.values()]}function eN(e,t){let n=tN(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 oN(c))Ko(e,"control-dependence",r.displayPoint.id,l.id,"exact","The target postdominates a branch successor but does not postdominate the predicate.")}}}function tN(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,...aN(s)]);Od(r.get(o.id),a)||(r.set(o.id,a),i=!0)}}return r}function nN(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)rN(l.callableId,a.point.callableId,n)?Ko(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&&Ko(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 rN(e,t,n){for(let r=n.get(t)??null;r;r=n.get(r)??null)if(r===e)return!0;return!1}function Ko(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 mv(e,t){return t>=e.SyntaxKind.FirstAssignment&&t<=e.SyntaxKind.LastAssignment}function iN(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 fv(e){return[...new Map(e.map(t=>[t.point.id,t])).values()]}function oN(e){return[...new Map(e.map(t=>[t.id,t])).values()]}function sN(e){return new Set(e.flatMap(t=>[...t]))}function aN(e){return e.length===0?new Set:new Set([...e[0]].filter(t=>e.slice(1).every(n=>n.has(t))))}function Od(e,t){return e.size===t.size&&[...e].every(n=>t.has(n))}function cN(e,t){return e.start-t.start||e.kind.localeCompare(t.kind)||e.id.localeCompare(t.id)}function Nd(e){return{points:[],edges:[],coverage:{status:"unsupported",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:[e]}}}var uN=Gn("typescript-local-flow",{clearGroups:["whole-project","source-file","semantic-provider"]});function Bd(e,t,n,r){if(!Xn(t))return null;let i=`${t}\0${n}\0${r}`;return uN.get(e,i,()=>{let o=se(e,t);return o?cv(o,lN(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 dN(e,t=new Map){let n=new Map,r=new Map,i=[];for(let o of e.transfers){if(!e.caller)continue;let s=cc(e.caller,o.callerPosition),a=cc(e.callee,o.calleePosition);Go(n,s),Go(n,a),jd(r,e.caller,s),jd(r,e.callee,a);let c=pt("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=cc(e.callee,o.calleePosition);Go(n,a),jd(r,e.callee,a);let c=t.get(o.calleePosition);if(c&&xN(c)){CN(r,n,e,o.calleePosition,o.argumentText,c);return}let l=SN(e,o.calleePosition,o.argumentText);Go(n,l);let u=pt("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:pt("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 gv(e,t,n=[]){let r=hv(),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=bN(i,e,s.toFile,s.toSymbol);if(!a)continue;let c=Np(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=_p(e,u),f=ae(e,u.file)?.rootNode,p=new Map;if(f)for(let g of m.unknown){let h=Ap({db:e,file:u.file,root:f},u.arguments[g.calleePosition]);h&&p.set(g.calleePosition,h)}pv(r,dN(m,p)),m.caller&&hN(u.callNode)&&yN(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=Bd(e,s.location.file,s.location.line,a);if(c){pv(r,mN(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: codebaseiq inspect --at '${s.location.file}:${s.location.line+1}-${a+1}' --view behavior.`)}}return r.blindSpots=[...new Set(r.blindSpots)].sort(),r}function mN(e,t,n){let r=hv(),i=new Map,o=new Map,s=new Map,a=e.location.file;for(let c of t){let l=fN(e,a,c);s.set(c.id,l.id),i.set(l.id,l),pN(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=gN(c),m=pt("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 fN(e,t,n){return{id:pt("local-flow-point",t,String(n.start),String(n.end),n.kind,n.symbolKey??n.name),kind:n.kind==="parameter-definition"||n.kind==="definition"?"local-definition":n.kind==="use"?"local-use":n.kind==="predicate"?"control-predicate":"local-statement",label:n.name,disposition:"folded",location:{file:t,line:n.line,endLine:n.line},anchorIds:[],attributes:{ownerNodeId:e.id,pointKind:n.kind,callableId:n.callableId,symbolKey:n.symbolKey,column:n.column}}}function pN(e,t,n){let r=pt("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 gN(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 hN(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 yN(e,t,n){if(!t.caller)return;let r={id:pt("call-result",t.call.file,String(n.startIndex),String(n.endIndex),t.callee.symbol),kind:"call-result",label:`result of ${t.callee.leaf}`,disposition:"folded",location:{file:t.call.file,line:t.call.startLine,endLine:t.call.endLine},anchorIds:[],attributes:{calleeSymbol:t.callee.symbol,callerSymbol:t.caller.symbol}},i=pt("edge","return-to-call-result",t.callee.symbol,r.id),o=pt("edge","call-result-owner",t.caller.symbol,r.id);e.nodes.push(r),e.edges.push({id:i,kind:"data-transfer",fromNodeId:Hd(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:Hd(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 hv(){return{nodes:[],edges:[],frontiers:[],blindSpots:[]}}function pv(e,t){$d(e.nodes,t.nodes),$d(e.edges,t.edges),$d(e.frontiers,t.frontiers),e.blindSpots.push(...t.blindSpots)}function $d(e,t){let n=new Set(e.map(r=>r.id));for(let r of t)n.has(r.id)||(n.add(r.id),e.push(r))}function bN(e,t,n,r){let i=`${n}\0${r}`,o=e.get(i);if(o!==void 0)return o;let s=W(t,n).find(a=>a.symbol===r)??null;return e.set(i,s),s}function cc(e,t){return{id:EN(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 SN(e,t,n){return{id:pt("argument-expression",e.call.file,String(e.call.startLine),String(e.call.endLine),String(t)),kind:"argument-expression",label:n,disposition:"unsupported",location:{file:e.call.file,line:e.call.startLine,endLine:e.call.endLine},anchorIds:[],attributes:{calleeSymbol:e.callee.symbol,position:t}}}function vN(e,t,n){return{id:pt("static-value",e.call.file,String(e.call.startLine),String(e.call.endLine),String(t)),kind:"static-value",label:n.value,disposition:"folded",location:{file:e.call.file,line:e.call.startLine,endLine:e.call.endLine},anchorIds:[],attributes:{value:n.value,precision:n.precision,evidence:n.evidence,termKind:n.term.kind,derivationRule:n.derivation.rule}}}function CN(e,t,n,r,i,o){let s=vN(n,r,o),a=cc(n.callee,r);Go(t,s);let c=pt("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:RN(o),attributes:{argumentText:i,calleePosition:r,value:o.value,precision:o.precision,derivationRule:o.derivation.rule}}],evidence:IN(o,n)})}function xN(e){return e.derivation.kind!=="heuristic"&&e.precision!=="symbolic"&&e.precision!=="unknown"}function RN(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 IN(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 Go(e,t){e.has(t.id)||e.set(t.id,t)}function jd(e,t,n){let r=pt("edge","parameter-owner",t.symbol,n.id);e.has(r)||e.set(r,{id:r,kind:"parameter-owner",fromNodeId:Hd(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 EN(e,t){return pt("parameter",e,String(t))}function Hd(e){return pt("symbol",e)}function pt(...e){return e.map(t=>encodeURIComponent(t)).join(":")}function yv(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=Vg(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=Ud(s,l.controller),d=Ud(s,l.outcome);n.set(u.id,u),n.set(d.id,d),wN(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=Ud(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 Ud(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 wN(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 lc=new Set(["arrow_function","constructor_declaration","function_declaration","function_definition","function_expression","generator_function","generator_function_declaration","function_item","lambda","lambda_expression","method","method_declaration","method_definition"]),Vo=new Set(["block","body","compound_statement","declaration_list","statement_block"]),LN=new Set(["assignment","assignment_expression","augmented_assignment_expression"]),qd=new Set(["update_expression"]),Cv=new Set(["array_access","element_access_expression","subscript_expression"]),xv=new Set(["attribute","field_access","field_expression","member_access_expression","member_expression","selector_expression"]),DN=new Set(["false","null","null_literal","number","number_literal","string","string_literal","template_string","true"]),PN=new Set(["call_expression","method_invocation","object_creation_expression"]),MN=new Set(["comment","else_clause","formal_parameters","parameters","type_parameters"]);function Rv(e,t,n,r){let i=ae(e,t);if(!i)return null;let o=BN(i.rootNode,n,r);if(!o)return null;let s=[],a=[],c=[];return Gr(o,l=>{if(LN.has(l.type)||qd.has(l.type)||Ev(l)){let u=TN(l);u?s.push(u):c.push({family:"state",startLine:l.startPosition.row,endLine:l.endPosition.row,reason:`Mutation target ${pn(l.text)} could not be resolved to an exact source resource.`})}}),Gr(o,l=>{if(!Vo.has(l.type))return;let u=_N(l);for(let d=0;d<u.length-1;d+=1)a.push({from:Wo(u[d]),to:Wo(u[d+1]),subtype:"lexical-successor",synchronizationScope:null,attributes:{sameScope:!0,executionConditional:!0}});for(let d=0;d<u.length;d+=1){let m=u[d],f=jN(m).filter(p=>p.type==="await_expression");for(let p of f){let g=Jo("event",`await ${pn(p.text.replace(/^await\s+/u,""))}`,p);a.push({from:Wo(m),to:g,subtype:"awaits-completion",synchronizationScope:null,attributes:{completionRequired:!0}});let h=u[d+1];h&&a.push({from:g,to:Wo(h),subtype:"await-completion-before",synchronizationScope:null,attributes:{continuationOnly:!0}})}}}),Gr(o,l=>{if(l.type!=="synchronized_statement")return;let u=l.childForFieldName("object")??l.childForFieldName("condition")??l.namedChildren.find(g=>!Vo.has(g.type)),d=l.childForFieldName("body")??l.namedChildren.find(g=>Vo.has(g.type));if(!u||!d){c.push({family:"temporal",startLine:l.startPosition.row,endLine:l.endPosition.row,reason:"Synchronized scope has no structurally resolved monitor or body."});return}let m=pn(u.text).replace(/^\(|\)$/gu,""),f=Jo("lock",m,u),p=$N(d).filter(g=>g.parent!==null&&wv(g));for(let g of ON(p))a.push({from:f,to:Wo(g),subtype:"inside-lock-scope",synchronizationScope:m,attributes:{syntaxNative:!0}})}),{mutations:s,temporal:a,unsupported:c}}function TN(e){let t=Ev(e),n=e.childForFieldName("left")??e.childForFieldName("argument")??(t?e.namedChildren.at(-1)??null:e.namedChildren[0]??null);if(!n)return null;let r=kN(n);if(!r)return null;let i=t?"delete":qd.has(e.type)||!NN(e,n).startsWith("=")?"update":"assign",o=t||qd.has(e.type)?null:e.childForFieldName("right");return{event:Jo("event",pn(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?Jo("value",pn(o.text),o):null,dataSubtype:o?FN(o,e):null}}function kN(e){if(Cv.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:`${pn(t.text)}[]`,recordIdentity:pn(n.text)}}return xv.has(e.type)?{name:pn(e.text),recordIdentity:null}:/^(?:identifier|property_identifier|field_identifier)$/u.test(e.type)?{name:pn(e.text),recordIdentity:null}:null}function FN(e,t){return DN.has(e.type)||/(?:integer|float|decimal|boolean|character)_literal$/u.test(e.type)?"constant-to-state":PN.has(e.type)?"return-to-state":xv.has(e.type)||Cv.has(e.type)?"property-to-state":/identifier$/u.test(e.type)?AN(e.text,t)?"captured-value-to-state":"value-to-state":"expression-to-state"}function AN(e,t){let n=zd(t.parent);if(!n||bv(n,e))return!1;let r=zd(n.parent);for(;r;){if(bv(r,e))return!0;r=zd(r.parent)}return!1}function zd(e){let t=e;for(;t;){if(lc.has(t.type))return t;t=t.parent}return null}function bv(e,t){let n=e.childForFieldName("parameters")??e.namedChildren.find(o=>["formal_parameters","parameters"].includes(o.type));if(n&&Sv(n,t))return!0;let r=e.childForFieldName("body")??e.namedChildren.find(o=>Vo.has(o.type));if(!r)return!1;let i=!1;return Iv(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&&Sv(s,t)&&(i=!0)}),i}function Sv(e,t){let n=!1;return Gr(e,r=>{/identifier$/u.test(r.type)&&r.text===t&&(n=!0)}),n}function Iv(e,t,n){n(e);for(let r of e.namedChildren)r!==t&&lc.has(r.type)||Iv(r,t,n)}function NN(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 Ev(e){return(e.type==="delete_expression"||e.type==="unary_expression")&&/^delete\b/u.test(e.text.trim())}function _N(e){return e.namedChildren.filter(t=>wv(t))}function wv(e){return MN.has(e.type)||Vo.has(e.type)?!1:/(?:statement|declaration)$/u.test(e.type)||e.type==="expression_statement"||e.type==="local_variable_declaration"}function ON(e){let t=new Set(e);return e.filter(n=>{let r=n.parent;for(;r;){if(t.has(r))return!1;r=r.parent}return!0})}function Wo(e){return Jo("event",pn(e.text),e)}function Jo(e,t,n){return{kind:e,label:t,startLine:n.startPosition.row,endLine:n.endPosition.row}}function BN(e,t,n){let r=[];return Gr(e,o=>{o.startPosition.row<=t&&o.endPosition.row>=n&&r.push(o)}),r.filter(o=>lc.has(o.type)).sort(vv)[0]??r.sort(vv)[0]??null}function vv(e,t){return e.endIndex-e.startIndex-(t.endIndex-t.startIndex)||e.startIndex-t.startIndex}function $N(e){let t=[];return Gr(e,n=>t.push(n)),t}function jN(e){let t=[],n=r=>{t.push(r);for(let i of r.namedChildren)i!==e&&lc.has(i.type)||n(i)};return n(e),t}function Gr(e,t){t(e);for(let n of e.namedChildren)Gr(n,t)}function pn(e){return e.trim().replace(/\s+/gu," ")}function Pv(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=Rv(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=dc(a,u.event),m=GN(a,u.resource,u.durabilityClass);if(r.set(d.id,d),r.set(m.id,m),mc(i,a,d,"contains-state-effect"),fc(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 f=dc(a,u.value);r.set(f.id,f),fc(i,{kind:"data-to-state",from:f,to:m,semantics:[{family:"data",subtype:u.dataSubtype,attributes:{operation:u.operation,resource:u.resource.label,recordIdentity:u.recordIdentity,value:u.value.label}}],method:"parser-assignment-value",identity:`${u.value.label} -> ${u.resource.label}`})}}for(let u of l.temporal){let d=dc(a,u.from),m=dc(a,u.to);r.set(d.id,d),r.set(m.id,m),mc(i,a,d,u.from.kind==="lock"?"contains-lock-scope":"contains-event"),mc(i,a,m,"contains-event"),fc(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=On(`${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=On("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 f=On("frontier",u.family,d);o.set(f,{id:f,kind:u.family,direction:"unresolved",fromNodeIds:[a.id],edgeIds:[m],memberNodeIds:[d],memberCount:1,disposition:"unsupported",reason:u.reason,expansion:null})}}for(let a of t.filter(c=>c.kind==="runtime-boundary-participant")){let c=uc(a,"protocol"),l=uc(a,"action"),u=uc(a,"address")??a.label;!c||!l||!Dv(c,l)||Lv(r,i,a,{observationId:a.id,action:l,strength:"exact",file:a.location?.file??"",line:a.location?.line??0,address:u,protocol:c,role:uc(a,"role")??void 0,resolution:"locally-linked"})}for(let a of n){if(!a.protocol||!Dv(a.protocol,a.action))continue;let c=qN(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}Lv(r,i,c,a)}return{nodes:[...r.values()],edges:[...i.values()],frontiers:[...o.values()],blindSpots:[...s].sort()}}function Lv(e,t,n,r){let i=UN(r),s={id:On("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:On("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),mc(t,n,s,"contains-runtime-state-effect");let l=HN(r.action);fc(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:zN(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 HN(e){return e==="database.read"?"reads-resource":e==="queue.send"?"enqueues-resource":e==="queue.consume"?"consumes-resource":"writes-resource"}function UN(e){return(e.keyParts?.find(n=>["address","resource"].includes(n.name))?.value??e.address)||e.observationId}function zN(e){return e.keyParts?.find(n=>/^(?:id|key|record)$/u.test(n.name))?.value??null}function Dv(e,t){return e==="database"&&["database.read","database.write"].includes(t)||e==="queue"&&["queue.consume","queue.send"].includes(t)}function uc(e,t){let n=e.attributes[t];return typeof n=="string"?n:null}function qN(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(KN)[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 KN(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 dc(e,t){let n=e.location.file;return{id:On(`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 GN(e,t,n){let r=e.location.file;return{id:On("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 mc(e,t,n,r){let i=On("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 fc(e,t){let n=On("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 On(...e){return e.map(t=>encodeURIComponent(t)).join(":")}var WN=new Set(["control","data","state","temporal"]),pc=new Set(["contains-control","contains-event","contains-lock-scope","contains-state-effect","contains-runtime-state-effect","contains","owns-parameter","owns-runtime-observation"]),Fv=new Set(["discriminator-dispatch","result-callback","returns","runtime-handoff","throws"]);function Av(e,t={}){let n=new Map(e.nodes.map(C=>[C.id,C])),r=e_(e.nodes,t.focusLocations),i=t_(e.edges,t.focusLocations),o=n_(e.edges,i),s=new Set(e.paths.flatMap(C=>C.edgeIds)),a=Bn(e.anchors.filter(C=>C.status==="matched").flatMap(C=>C.nodeIds)),l=e.edges.filter(kv).filter(C=>VN(C,r,i,s)),u=l.filter(C=>QN(C,r,i,o,n,s)),d=Mv(a,u,"forward"),m=XN(d,u),f=Mv(m,u,"backward"),p=new Set([...d].filter(C=>f.has(C)));for(let C of a)p.add(C);let g=new Set(u.filter(C=>p.has(C.fromNodeId)&&p.has(C.toNodeId)).map(C=>C.id)),h=new Set(p),b=new Set(g);JN(l,h,b,r,i);let S=e.frontiers.filter(C=>i_(C,h)),y=Bn(S.filter(C=>C.disposition==="unsupported").map(C=>C.id)),E=Bn(e.edges.filter(C=>!kv(C)&&_v(C)&&r_(C,h)).map(C=>C.id)),I=Bn(S.map(C=>C.id)),v=[];a.length===0&&v.push("No matched anchor node starts the corridor."),m.length===0&&v.push("No proved mechanical outcome is reachable from a matched anchor."),y.length>0&&v.push(`${y.length} unsupported frontier(s) touch the protected corridor.`),E.length>0&&v.push(`${E.length} candidate or unknown edge(s) touch the protected corridor.`);let x=v.length===0?"complete":"incomplete";return{schemaVersion:1,status:x,startNodeIds:a,outcomeNodeIds:m,baseNodeIds:Bn([...p]),baseEdgeIds:Bn([...g]),nodeIds:Bn([...h]),edgeIds:Bn([...b]),accountedFrontierIds:I,unresolvedFrontierIds:y,unresolvedEdgeIds:E,coverage:{protectedNodes:h.size,protectedEdges:b.size,baseNodes:p.size,baseEdges:g.size,accountedFrontiers:I.length,unresolvedFrontiers:y.length,unresolvedEdges:E.length},explanation:x==="complete"?"Every proved anchor-to-outcome path is closed over its material causal facts within reported coverage.":v.join(" ")}}function VN(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"&&pc.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(Ov(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 JN(e,t,n,r,i){let o=!0;for(;o;){o=!1;for(let s of e)YN(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 YN(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"?pc.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"?Nv(s)||["returns","throws"].includes(s.subtype)&&!o&&n!==null&&!n.has(e.toNodeId)?!1:Fv.has(s.subtype)||Ov(s)||s.subtype==="completion-callback":!1)}function XN(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"&&Fv.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 Bn([...n])}function Mv(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 QN(e,t,n,r,i,o){return(e.semantics??[]).some(s=>e.disposition==="emitted"||o.has(e.id)?!0:s.family==="identity"&&pc.has(s.subtype)?t===null||t.has(e.toNodeId)||r?.has(e.toNodeId)===!0:!WN.has(s.family)||Nv(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"?ZN(e,i)&&(t.has(e.fromNodeId)||t.has(e.toNodeId)):!1)}function Nv(e){return e.family==="control"&&["call","discriminator-dispatch","result-callback","runtime-handoff"].includes(e.subtype)}function ZN(e,t){let n=t.get(e.fromNodeId),r=t.get(e.toNodeId);if(!n||!r)return!1;let i=Tv(n,"ownerNodeId")??(n.kind==="symbol"?n.id:null),o=Tv(r,"ownerNodeId")??(r.kind==="symbol"?r.id:null);return i!==null&&i===o}function e_(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 t_(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 n_(e,t){return t===null?null:new Set(e.filter(n=>t.has(n.id)).flatMap(n=>[n.fromNodeId,n.toNodeId]))}function Tv(e,t){let n=e.attributes[t];return typeof n=="string"?n:null}function kv(e){return e.disposition==="excluded"||e.disposition==="unsupported"||!_v(e)?!1:e.evidence.some(t=>t.strength==="exact"||t.strength==="derived")}function _v(e){return(e.semantics??[]).some(t=>t.family!=="identity"||pc.has(t.subtype))}function Ov(e){return e.subtype.startsWith("predicate-")||e.subtype.startsWith("loop-")||e.subtype.startsWith("exception-")||e.subtype.startsWith("finally-")||e.subtype.startsWith("handler-")}function r_(e,t){return t.has(e.fromNodeId)||t.has(e.toNodeId)}function i_(e,t){return[...e.fromNodeIds,...e.memberNodeIds].some(n=>t.has(n))}function Bn(e){return[...new Set(e)].sort()}import{createHash as o_}from"crypto";var gc=["identity","contract","control","data","state","temporal"],s_=new Set(gc);function yc(e){let t=ki(e.anchors,"anchor"),n=ki(e.nodes,"node"),r=ki(e.edges,"edge"),i=ki(e.paths??[],"path"),o=ki(e.frontiers??[],"frontier"),s=new Set(t.map(f=>f.id)),a=new Set(n.map(f=>f.id)),c=new Set(r.map(f=>f.id)),l=e.routeCatalog?{...e.routeCatalog,routes:ki(e.routeCatalog.routes,"route"),selectedRouteIds:vt(e.routeCatalog.selectedRouteIds)}:void 0;for(let f of t)wt(`anchor ${f.id}`,[...f.nodeIds,...f.candidateNodeIds],a,"node");for(let f of n)wt(`node ${f.id}`,f.anchorIds,s,"anchor");for(let f of r){if(wt(`edge ${f.id}`,[f.fromNodeId,f.toNodeId],a,"node"),f.evidence.length===0)throw new Error(`Exploration edge ${f.id} has no evidence source.`);l_(f)}for(let f of i)wt(`path ${f.id}`,[f.fromAnchorId,f.toAnchorId],s,"anchor"),wt(`path ${f.id}`,f.nodeIds,a,"node"),wt(`path ${f.id}`,f.edgeIds,c,"edge");for(let f of o)if(wt(`frontier ${f.id}`,f.fromNodeIds,a,"node"),wt(`frontier ${f.id}`,f.edgeIds,c,"edge"),wt(`frontier ${f.id}`,f.memberNodeIds,a,"node"),f.memberCount!==f.memberNodeIds.length)throw new Error(`Exploration frontier ${f.id} reports ${f.memberCount} member(s) but identifies ${f.memberNodeIds.length}.`);for(let f of l?.routes??[])wt(`route ${f.id}`,f.nodeIds,a,"node"),wt(`route ${f.id}`,f.edgeIds,c,"edge"),wt(`route ${f.id}`,[f.anchorNodeId,f.endpointNodeId],a,"node");l&&wt("route catalog selection",l.selectedRouteIds,new Set(l.routes.map(f=>f.id)),"route");let u=vt(e.incompleteReasons??[]),d=u.length===0?"accounted":"incomplete",m=t.reduce((f,p)=>f+p.omittedCandidates,0);return{schemaVersion:1,anchors:t,nodes:n,edges:r,paths:i,frontiers:o,coverage:{status:d,scope:e.scope,nodes:Gv(n),edges:Gv(r),matchedAnchors:t.filter(f=>f.status==="matched").length,ambiguousAnchors:t.filter(f=>f.status==="ambiguous").length,missingAnchors:t.filter(f=>f.status==="missing").length,omittedCandidates:m,frontierGroups:o.length,programEdges:c_(r),blindSpots:vt(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:m_(d,i,e.scope),...l?{routeCatalog:l}:{}}}function a_(e){return e.flatMap(t=>u_(t.semantics??[]).map(n=>({id:d_(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 c_(e){let t=a_(e),n=new Set(t.map(s=>s.sourceEdgeId)),r=new Map(gc.map(s=>[s,new Set])),i=new Map(gc.map(s=>[s,new Set])),o=new Map(gc.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:vt(e.filter(s=>!n.has(s.id)).map(s=>s.kind)),families:{identity:Ti("identity",r,o,i),contract:Ti("contract",r,o,i),control:Ti("control",r,o,i),data:Ti("data",r,o,i),state:Ti("state",r,o,i),temporal:Ti("temporal",r,o,i)}}}function Ti(e,t,n,r){return{sourceEdges:t.get(e)?.size??0,projectedEdges:n.get(e)??0,subtypes:[...r.get(e)??[]].sort()}}function l_(e){let t=new Set;for(let n of e.semantics??[]){if(!s_.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=Kd(n);if(t.has(r))throw new Error(`Exploration edge ${e.id} repeats program edge semantic ${r}.`);t.add(r)}}function u_(e){return[...e].sort((t,n)=>Kd(t).localeCompare(Kd(n)))}function Kd(e){return`${e.family}:${e.subtype}`}function d_(e,t){return`program:${encodeURIComponent(e)}:${t.family}:${encodeURIComponent(t.subtype)}`}function m_(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 Wv(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 R=w+1;R<o.length;R+=1){let P=o[w],_=o[R],D=Uv(e,P,_,!1),F=D??Uv(e,P,_,!0);F?(F.nodeIds.forEach(V=>r.add(V)),i.push({id:hc("path",P.id,_.id),fromAnchorId:P.id,toAnchorId:_.id,status:!D||P.status==="ambiguous"||_.status==="ambiguous"?"candidate":"connected",nodeIds:F.nodeIds,edgeIds:F.edgeIds})):i.push({id:hc("path",P.id,_.id),fromAnchorId:P.id,toAnchorId:_.id,status:"partial",nodeIds:[],edgeIds:[]})}let s=vt(t.routeIds??[]),a=f_(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(R=>r.add(R));let m=i.length===0||i.some(w=>w.edgeIds.length>0);m&&qv(e,r,n);let f=Kv(e,r),p=new Set(t.expandedFrontierIds??[]),g=new Set(f.map(w=>w.id)),h=[...p].filter(w=>!g.has(w)).sort();if(h.length>0)throw new Error(`Unknown exploration frontier id(s): ${h.join(", ")}`);for(let w of f)p.has(w.id)&&w.memberNodeIds.forEach(R=>r.add(R));m&&qv(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 R=0;R<w.nodeIds.length;R+=1){let P=w.nodeIds[R],_=R;y.set(P,Math.max(y.get(P)??0,_))}let E=e.nodes.map(w=>{let R=b.get(w.id),P=S.has(w.id)?{upstreamCausalPath:!0,upstreamCausalDistance:y.get(w.id)??0,...R?{upstreamCausalEndpoint:R}:{}}:{};return{...w,attributes:{...w.attributes,...P},disposition:w.disposition==="excluded"||w.disposition==="unsupported"?w.disposition:r.has(w.id)?"emitted":"folded"}}),I=new Set([...i.flatMap(w=>w.edgeIds),...d.flatMap(w=>w.edgeIds)]),v=e.edges.map(w=>({...w,disposition:w.disposition==="excluded"||w.disposition==="unsupported"?w.disposition:I.has(w.id)||r.has(w.fromNodeId)&&r.has(w.toNodeId)?"emitted":"folded"})),x=yc({anchors:e.anchors,nodes:E,edges:v,paths:i,frontiers:[...e.frontiers.filter(w=>w.disposition!=="folded"),...Kv({...e,nodes:E,edges:v},r)],scope:e.coverage.scope,blindSpots:e.coverage.blindSpots,incompleteReasons:e.coverage.status==="incomplete"?[e.coverage.explanation]:[],routeCatalog:a}),C=new Set(x.frontiers.flatMap(w=>w.edgeIds)),L=x.edges.filter(w=>w.disposition==="folded"&&!C.has(w.id)).map(w=>w.id);if(L.length>0)throw new Error(`Folded exploration edge(s) are not frontier-accounted: ${L.sort().join(", ")}`);return x}var Bv=10;function f_(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(!p_(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(Yo(S))-Number(Yo(b))||Hv(S)-Hv(b)||b.fromNodeId.localeCompare(S.fromNodeId)||b.id.localeCompare(S.id));let o=vt(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],E=n.get(y),I=n.get(h);if(!E?.location||!I)return;let v=[...b.nodeIds].reverse(),x=[...b.edgeIds].reverse(),C=new Set(v),L=x.flatMap(D=>{let M=r.get(D);return M?[M]:[]}),w=e.edges.filter(D=>D.disposition!=="excluded"&&D.disposition!=="unsupported"&&(C.has(D.fromNodeId)||C.has(D.toNodeId))),R={id:hc("route",h,y,S,...x),status:"proved",anchorNodeId:h,anchorLabel:I.label,endpointNodeId:y,endpointLabel:E.label,endpointLocation:{...E.location},endpointKind:S,nodeIds:v,edgeIds:x,evidenceStrengths:vt(L.flatMap(D=>D.evidence.map(M=>M.strength))),spineEdgeFamilies:$v(L,!0),relatedEdgeFamilies:$v(w,!1),crossesRuntimeBoundary:L.some(Yo)},P=`${h}\0${y}\0${S}`,_=s.get(P);(!_||jv(R,_)<0)&&s.set(P,R)};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 E=b[y],I=E.nodeIds[E.nodeIds.length-1];E.edgeIds.length>0&&n.get(I)?.location&&n.get(I)?.attributes.publicEntry===!0&&c(h,E,"public-entry");let v=i.get(I)??[];if(E.edgeIds.length>=Bv){v.some(x=>!E.nodeIds.includes(x.fromNodeId))&&a.add(h);continue}for(let x of v){if(E.nodeIds.includes(x.fromNodeId))continue;let C=E.edgeIds.length+1,L=S.get(x.fromNodeId);if(L!==void 0&&L<=C)continue;let w={nodeIds:[...E.nodeIds,x.fromNodeId],edgeIds:[...E.edgeIds,x.id]};if(S.set(x.fromNodeId,C),Yo(x)&&n.get(x.fromNodeId)?.location){c(h,w,"runtime-boundary");continue}b.push(w)}}}let l=[...s.values()].sort(jv),u=new Set(l.map(h=>h.id)),d=vt(t.filter(h=>u.has(h))),m=vt(l.map(h=>h.anchorNodeId)),f=o.filter(h=>!m.includes(h)),p=[...a].sort(),g=e.coverage.status==="accounted"&&p.length===0?"accounted":"incomplete";return{schemaVersion:1,routes: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:Bv,anchorNodeIds:o,anchorsWithRoutes:m,anchorsWithoutRoutes:f,depthLimitedAnchorNodeIds:p,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 $v(e,t){let n=e.flatMap(r=>r.semantics?.map(i=>i.family)??[]);return t&&e.length>0&&n.length===0&&n.push("control"),vt(n)}function jv(e,t){return e.anchorNodeId.localeCompare(t.anchorNodeId)||e.edgeIds.length-t.edgeIds.length||e.endpointKind.localeCompare(t.endpointKind)||e.endpointNodeId.localeCompare(t.endpointNodeId)||e.id.localeCompare(t.id)}function p_(e){return e.disposition!=="excluded"&&e.disposition!=="unsupported"&&g_(e)&&e.evidence.some(t=>["exact","derived","mixed"].includes(t.strength))}function g_(e){return Yo(e)||e.kind==="boundary-observation"||e.kind==="call"||e.kind==="compiler:call"}function Yo(e){return e.kind==="runtime-boundary"||e.kind.startsWith("runtime:")}function Hv(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 Uv(e,t,n,r){return zv(e,t,n,r)??zv(e,n,t,r)}function zv(e,t,n,r){let i=[...t.nodeIds,...t.candidateNodeIds].sort(),o=new Set([...n.nodeIds,...n.candidateNodeIds]);if(i.some(u=>o.has(u)))return{nodeIds:[i.find(d=>o.has(d))],edgeIds:[]};let s=new Set(e.nodes.filter(u=>u.kind==="structural-region").map(u=>u.id)),a=new Map;for(let u of e.edges)u.disposition==="excluded"||u.disposition==="unsupported"||u.kind==="structural-membership"||s.has(u.fromNodeId)||s.has(u.toNodeId)||u.evidence.every(m=>["candidate","unknown"].includes(m.strength))&&!r||h_(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 f={nodeId:m.nodeId,nodeIds:[...d.nodeIds,m.nodeId],edgeIds:[...d.edgeIds,m.edgeId]};if(o.has(m.nodeId))return f;l.add(m.nodeId),c.push(f)}}return null}function h_(e,t,n,r){let i=e.get(t)??[];i.push({nodeId:n,edgeId:r}),e.set(t,i)}function y_(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 f=o.get(u)??new Set;f.add(d),o.set(u,f),(/(?:runtime-boundary|external)/u.test(a.kind)||m&&/(?:frontier|external)/u.test(m.kind))&&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 qv(e,t,n){let r=-1;for(;t.size!==r&&t.size<n;)r=t.size,y_(e,t,n)}function Kv(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(p=>a.has(p.fromNodeId)||a.has(p.toNodeId)),l=c.filter(p=>a.has(p.fromNodeId)!==a.has(p.toNodeId)),u=vt(l.map(p=>a.has(p.fromNodeId)?p.toNodeId:p.fromNodeId)),d=new Set(l.map(p=>a.has(p.toNodeId)?"outgoing":"incoming")),m=vt(c.map(p=>p.id)),f=vt(l.map(p=>p.kind));return{id:hc("frontier",...s,...m),kind:f.join("+")||"disconnected",direction:d.size===1?[...d][0]:"undirected",fromNodeIds:u,edgeIds:m,memberNodeIds:s,memberCount:s.length,disposition:"folded",reason: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 hc(e,...t){let n=o_("sha256").update(t.join("\0")).digest("hex").slice(0,16);return`${e}:${n}`}function ki(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 wt(e,t,n,r){let i=vt(t.filter(o=>!n.has(o)));if(i.length>0)throw new Error(`Exploration ${e} references missing ${r}(s): ${i.join(", ")}`)}function Gv(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 vt(e){return[...new Set(e)].sort()}var b_=5,S_=12,v_=8,C_=3,Vv=8,x_=6,R_=12,Jv=12,I_=12,E_=2,w_=new Set(["branch","loop","call","await","return","throw","mutation","catch","finally"]),L_=9e3,Yv=iv;function D_(e,t){return sC(e,t,"full")}function oC(e,t){return sC(e,t,"topology")}function sC(e,t,n){let r=vc(t.searches??[]),i=vc(t.symbols??[]),o=vc(t.relations&&t.relations.length>0?t.relations:Yv),s=o.filter(k=>!Yv.includes(k));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=vc(t.sourceScopes&&t.sourceScopes.length>0?t.sourceScopes:["production"]),u=["production","test","fixture","example","generated","script","unknown"],d=l.filter(k=>!u.includes(k));if(d.length>0)throw new Error(`Unsupported system-map source scope(s): ${d.join(", ")}`);let m=new Set(l),f=k=>m.has(Il(k));if(r.length===0&&i.length===0)throw new Error("system-map requires at least one --search or --symbol anchor.");let p=t.maxDepth??b_;if(!Number.isSafeInteger(p)||p<0)throw new RangeError(`maxDepth must be a non-negative safe integer; received ${p}`);let g=t.maxTopologyCharacters??L_;if(!Number.isSafeInteger(g)||g<=0)throw new RangeError(`maxTopologyCharacters must be a positive safe integer; received ${g}`);let h=new U(e),b=h.fileDependencyGraph(),S=mO(b),y=fO(h.sourceFiles()),E=Ys(e),I=new Map((E?.observations??[]).map(k=>[k.id,k])),v=new Set((E?.observations??[]).map(k=>`${k.source.file}\0${k.source.startLine}`)),x=new Set,C=new Map,L=new Map,w=new Map,R=new Map,P=[],_=new Map,D=new Map,M=[],F=0,V=0,ce=0,G=0,X=0,A=0,K=new Set,ne=new Map,fe=new Map,he=k=>{let H=fe.get(k);if(H)return H;let ee=sr(e,k,{excludeIndexedTargets:!1});return fe.set(k,ee),ee},le=(k,H,ee,we,j=!1)=>{let B=L.get(k);if(B)return B.depth=Math.min(B.depth,H),B.primary||=we,B.promoteBoundaryImports||=j,B.origins.add(ee),B;let q={file:k,depth:H,primary:we,promoteBoundaryImports:j,origins:new Set([ee]),processed:!1};return L.set(k,q),q},be=(k,H,ee,we,j="none",B=!1)=>{let q=w.get(k.symbol);if(q)return q.depth=Math.min(q.depth,H),q.origins.add(ee),we&&q.anchorQueries.add(we),q.referenceScope=dO(q.referenceScope,j),le(k.relativePath,H,ee,!0,B),q;let oe={definition:k,depth:H,origins:new Set([ee]),anchorQueries:new Set(we?[we]:[]),referenceScope:j,processed:!1};return w.set(k.symbol,oe),le(k.relativePath,H,ee,!0,B),oe},T=(k,H,ee,we,j=!1,B=!0)=>{let q=gn(k),oe=R.get(q);if(oe)return oe.depth=Math.min(oe.depth,H),oe.origins.add(ee),we&&oe.anchorQueries.add(we),oe.reverseCallExpansion||=j,oe.traversalEligible||=B,le(k.file,H,ee,oe.traversalEligible,!0),oe;let z={...k,depth:H,origins:new Set([ee]),anchorQueries:new Set(we?[we]:[]),reverseCallExpansion:j,traversalEligible:B};return R.set(q,z),le(k.file,H,ee,B,!0),z},Z=(k,H,ee)=>{le(k.source.file,H,ee,!0,!0),k.owner.file!==k.source.file&&le(k.owner.file,H,`${ee}:owner`,!0,!0);let we=W(e,k.owner.file),j=k.owner.symbol?dr(e,h,k.owner.symbol).matches.find(oe=>oe.relativePath===k.owner.file):null,B=(j&&!De(j.symbol)?j:null)??Ke(we,k.source.startLine);if(B&&!De(B.symbol))return be(B,H,ee,void 0,"none",!0),B.symbol;k.owner.name&&T({file:k.owner.file,name:k.owner.name,startLine:k.owner.startLine,endLine:k.owner.endLine},H,`${ee}:source-owner`,void 0,!0);let q=h.definitionsForFile(k.source.file).filter(oe=>!!oe.leaf&&wn(e,k.source.file,oe.leaf).some(z=>z>=k.source.startLine&&z<=k.source.endLine));if(q.length===1){let oe=q[0];be(oe,H,`${ee}:handler-identifier`,void 0,"none",!0),Lt(_,{kind:"runtime-boundary",evidence:"runtime-boundary:handler-identifier",fromFile:k.source.file,fromSymbol:null,toFile:oe.relativePath,toSymbol:oe.symbol,fromBoundaryParticipant:Ai(k),line:k.source.startLine,strength:"derived"})}return null};for(let k of r){let H=V_(e,h,k,v),ee=H.filter(q=>Z_(q,f)),we=!t.fullLiteralTraversal&&(H.length>S_||ee.length>v_),j=we?[]:H,B=new Set((we?[]:t.fullLiteralTraversal?ee:[...ee].sort(J_).slice(0,C_)).map(eC));we&&(V+=1,ce+=H.length);for(let q of j){let oe=B.has(eC(q)),z=oe&&!q.ownerSymbol&&q.ownerStartLine!==null&&q.ownerEndLine!==null;if(le(q.relativePath,0,`${oe?"literal-anchor":"literal-match"}:${k}`,z,z),z&&T({file:q.relativePath,name:q.ownerShortName??`${q.relativePath}:${q.ownerStartLine+1}`,startLine:q.ownerStartLine,endLine:q.ownerEndLine},0,`literal-source-owner:${k}`,k,!0),oe&&q.ownerSymbol){let ue=dr(e,h,q.ownerSymbol).matches[0];ue&&!De(ue.symbol)&&be(ue,0,"literal-owner",k,"all",!0)}P.push({query:k,file:q.relativePath,line:q.line,ownerSymbol:q.ownerSymbol,ownerShortName:q.ownerShortName,ownerStartLine:q.ownerStartLine,ownerEndLine:q.ownerEndLine,sourceLine:q.sourceLine.trim(),matchKind:q.matchKind,traversalSeed:oe})}M.push({kind:"literal",query:k,status:H.length>0?"matched":"missing",matchedRegionIds:[],matchingLines:H.length,seedMatchingLines:we?0:B.size,matchOnlyLines:H.length-B.size,eligibleSeedMatchingLines:ee.length,materializedMatchingLines:j.length,withheldMatchingLines:we?H.length:0,literalTraversal:we?"withheld-broad":"materialized",representativeMatches:we?eO(k,H):void 0,narrowingCommands:we?nO(k,H):void 0,exhaustiveTraversalCommand:we||B.size<ee.length?`codebaseiq system-map --search ${Ae(k)} --full-literal-traversal`:void 0,seedRegionIds:[],matchOnlyRegionIds:[]})}for(let k of i){let H=dr(e,h,k);F+=H.omitted;let ee=Y_(e,k),we=H.matches.filter(z=>!De(z.symbol)),j=ee!==null&&we.length===0;j&&T(ee,0,"source-construct-anchor",k,!0);let B=j?we:H.matches;for(let z of B)be(z,0,"symbol-anchor",k,"all",!0);let q=j?X_(ee):null,oe=j?1:H.total;M.push({kind:"symbol",query:k,status:oe===0?"missing":oe===1?"matched":"ambiguous",matchedRegionIds:[],symbolCandidates:[...q?[q]:[],...B.map(aO)],totalSymbolCandidates:oe,omittedSymbolCandidates:H.omitted})}for(let k=0;k<p;k+=1){if(a.has("call")){let j=[...R.values()].filter(B=>B.traversalEligible&&B.reverseCallExpansion&&B.depth<=k&&!K.has(gn(B)));for(let B of j){K.add(gn(B));let q=te(e,B.file);if((q?.callables??[]).filter(ue=>ue.name===B.name&&ue.startLine<=B.endLine&&ue.endLine>=B.startLine).length===1){let ue=(q?.callSites??[]).filter(Re=>Re.calleeLeaf===B.name&&!Re.memberAccess);for(let Re of ue){let Te=k+1,ve=Ke(W(e,B.file),Re.line),Me=null,Ve=null;if(ve&&!De(ve.symbol)){if(ve.relativePath===B.file&&ve.startLine<=B.endLine&&ve.endLine>=B.startLine)continue;be(ve,Te,"reverse-local-call-owner",void 0,"forward-regions",!0),Me=ve.symbol}else{let $=Gd(e,B.file,Re.line);$&&gn($)!==gn(B)&&(Ve=T($,Te,"reverse-local-call-source-owner",void 0,!0))}!Me&&!Ve||Lt(_,{kind:"call",evidence:"ast-callsite",fromFile:B.file,fromSymbol:Me,toFile:B.file,toSymbol:null,fromSourceConstruct:Ve?Ct(Ve):void 0,toSourceConstruct:Ct(B),line:Re.line,strength:"derived"})}}let z=new Set([...S.get(B.file)??[],...ne.get(gn(B))??[],...zb(e,B.file).flatMap(ue=>[...S.get(ue)??[]])]);for(let ue of z){if(!f(ue))continue;let Te=he(ue).targets.filter(ve=>ve.targetFile===B.file&&ve.targetStartLine<=B.endLine&&ve.targetEndLine>=B.startLine);for(let ve of Te){let Me=k+1,Ve=Ke(W(e,ue),ve.line),$=null,Le=null;if(Ve&&!De(Ve.symbol))be(Ve,Me,"reverse-member-call-owner",void 0,"cross-workspace-or-forward",!0),$=Ve.symbol;else{let re=Gd(e,ue,ve.line);re&&(Le=T(re,Me,"reverse-member-call-source-owner",void 0,!0))}!$&&!Le||Lt(_,{kind:"call",evidence:"ast-service-member-callsite",fromFile:ue,fromSymbol:$,toFile:B.file,toSymbol:null,fromSourceConstruct:Le?Ct(Le):void 0,toSourceConstruct:Ct(B),line:ve.line,strength:ve.strength==="exact"?"exact":"derived"})}}}}let H=[...w.values()].filter(j=>!j.processed&&j.depth<=k),ee=a.has("call")?h.calleeMap(H.map(j=>j.definition),{additive:!1,semantic:!1}):new Map;for(let j of H){j.processed=!0;let B=j.definition;if(j.referenceScope!=="none"&&(a.has("call")||a.has("reference")||a.has("contract-symbol"))){let q=iO(e,h,B).filter(z=>f(z.file)&&uO(j,z.file,L,y)),oe=new Set(q.flatMap(z=>{if(!(a.has("call")&&te(e,z.file)?.callSites.some(Te=>Te.line===z.line&&Te.calleeLeaf===B.leaf)===!0)||!z.enclosingSymbol)return[];let Re=dr(e,h,z.enclosingSymbol).matches[0];return Re&&!De(Re.symbol)?[{owner:Re,site:z}]:[]}).sort((z,ue)=>{let Re=Pt(B.relativePath,y).relativeDir,Te=Pt(z.owner.relativePath,y).relativeDir===Re,ve=Pt(ue.owner.relativePath,y).relativeDir===Re,Me=Xv(e,z.owner),Ve=Xv(e,ue.owner),$=z.owner.endLine-z.owner.startLine,Le=ue.owner.endLine-ue.owner.startLine;return Number(ve)-Number(Te)||Ve-Me||$-Le||z.owner.symbol.localeCompare(ue.owner.symbol)}).filter((z,ue,Re)=>Re.findIndex(Te=>Te.owner.symbol===z.owner.symbol)===ue).reduce((z,ue)=>{if(z.length>=E_)return z;let Re=Pt(ue.owner.relativePath,y).relativeDir;return z.some(Te=>Te.workspace===Re)||z.push({symbol:ue.owner.symbol,workspace:Re}),z},[]).map(z=>z.symbol));for(let z of q){let ue=k+1;le(z.file,ue,`reference:${N(B.symbol)}`,!0);let Re=a.has("call")&&te(e,z.file)?.callSites.some(Me=>Me.line===z.line&&Me.calleeLeaf===B.leaf)===!0,Te=null,ve=null;if(z.enclosingSymbol){let Me=dr(e,h,z.enclosingSymbol).matches[0];Me&&!De(Me.symbol)&&(be(Me,ue,"reference-owner",void 0,Re&&oe.has(Me.symbol)?j.referenceScope:"none"),Te=Me.symbol)}if(!Te&&z.line!==null){let Me=Gd(e,z.file,z.line);Me&&(ve=T(Me,ue,"reference-source-owner",void 0,Re))}a.has("reference")&&Lt(_,{kind:"reference",evidence:"indexed-or-source-reference",fromFile:z.file,fromSymbol:Te,toFile:B.relativePath,toSymbol:B.symbol,fromSourceConstruct:ve?Ct(ve):void 0,line:z.line,strength:"mixed"}),Re&&Lt(_,{kind:"call",evidence:"ast-callsite",fromFile:z.file,fromSymbol:Te,toFile:B.relativePath,toSymbol:B.symbol,fromSourceConstruct:ve?Ct(ve):void 0,line:z.line,strength:"derived"}),a.has("contract-symbol")&&Pt(z.file,y).relativeDir!==Pt(B.relativePath,y).relativeDir&&Lt(_,{kind:"contract-symbol",evidence:"compiler-cross-workspace-symbol",fromFile:z.file,fromSymbol:Te,toFile:B.relativePath,toSymbol:B.symbol,fromSourceConstruct:ve?Ct(ve):void 0,line:z.line,strength:"exact"})}}for(let q of ee.get(B.symbolId)??[]){let oe=dr(e,h,q.symbol).matches.find(ue=>ue.relativePath===q.file);if(!oe||!f(oe.relativePath))continue;if(!(oe.relativePath===B.relativePath||(b.get(B.relativePath)??new Set).has(oe.relativePath))){G+=1;continue}be(oe,k+1,`call:${N(B.symbol)}`,void 0,"none",!0),Lt(_,{kind:"call",evidence:q.source,fromFile:B.relativePath,fromSymbol:B.symbol,toFile:oe.relativePath,toSymbol:oe.symbol,line:null,strength:j_(q.source)})}}let we=[...L.values()].filter(j=>!j.processed&&j.primary&&j.depth<=k);for(let j of we){j.processed=!0;let B=[...R.values()].filter($=>$.traversalEligible&&$.file===j.file&&$.depth<=k),q=[...w.values()].filter($=>$.definition.relativePath===j.file&&$.depth<=k).map($=>{let Le=hi(e,j.file,$.definition.startLine);return{startLine:Le?.startLine??$.definition.startLine,endLine:Le?.endLine??$.definition.endLine}}),oe=$=>[...w.values()].filter(Le=>Le.definition.relativePath===j.file&&Le.definition.startLine<=$&&Le.definition.endLine>=$).sort((Le,re)=>Le.definition.endLine-Le.definition.startLine-(re.definition.endLine-re.definition.startLine)||Le.definition.startLine-re.definition.startLine)[0],z=[...I.values()].filter($=>$.source.file===j.file&&C.has($.id)),ue=[...B.map($=>({startLine:$.startLine,endLine:$.endLine})),...z.map($=>({...Sc(e,$)}))],Re=[...q,...ue],Te=(te(e,j.file)?.callSites??[]).filter($=>Re.some(Le=>$.line>=Le.startLine&&$.line<=Le.endLine)),ve=new Set;if(a.has("call"))for(let $ of Re){let Le=An(e,j.file,$.startLine,$.endLine);for(let re of Le.targets){if(!f(re.definition.relativePath))continue;let Je=oe(re.sourceLine),zt=B.find(Tt=>Tt.startLine<=re.sourceLine&&Tt.endLine>=re.sourceLine),xt=z.find(Tt=>{let ut=Sc(e,Tt);return ut.startLine<=re.sourceLine&&ut.endLine>=re.sourceLine});be(re.definition,k+1,`scip-occurrence-call:${j.file}:${re.sourceLine+1}`,void 0,"none",!0),Lt(_,{kind:"call",evidence:"scip-occurrence-callsite",fromFile:j.file,fromSymbol:Je?.definition.symbol??null,toFile:re.definition.relativePath,toSymbol:re.definition.symbol,fromBoundaryParticipant:xt?Ai(xt):void 0,fromSourceConstruct:zt?Ct(zt):void 0,line:re.sourceLine,strength:"exact"}),ve.add(`${re.sourceLine}\0${re.calleeLeaf}`)}}if(a.has("reference"))for(let $ of Re){let Le=Xb(e,j.file,$.startLine,$.endLine);for(let re of Le.targets){if(!f(re.definition.relativePath)||ve.has(`${re.sourceLine}\0${re.calleeLeaf}`))continue;let Je=oe(re.sourceLine);if(Je?.definition.symbol===re.definition.symbol)continue;let zt=B.find(Tt=>Tt.startLine<=re.sourceLine&&Tt.endLine>=re.sourceLine),xt=z.find(Tt=>{let ut=Sc(e,Tt);return ut.startLine<=re.sourceLine&&ut.endLine>=re.sourceLine});be(re.definition,k+1,`scip-occurrence-reference:${j.file}:${re.sourceLine+1}`,void 0,"none",!0),Lt(_,{kind:"reference",evidence:"scip-occurrence-reference",fromFile:j.file,fromSymbol:Je?.definition.symbol??null,toFile:re.definition.relativePath,toSymbol:re.definition.symbol,fromBoundaryParticipant:xt?Ai(xt):void 0,fromSourceConstruct:zt?Ct(zt):void 0,line:re.sourceLine,strength:"exact"})}}let Me=a.has("call")?sr(e,j.file,{ranges:Re,excludeIndexedTargets:!1}):{targets:[],unresolvedCallsites:0};A+=Me.unresolvedCallsites;let Ve=Me.targets.filter($=>!ve.has(`${$.line}\0${$.calleeLeaf}`));X+=Ve.filter($=>$.strength!=="exact"&&($.resolution!=="imported-service-object-member"||($.resolutionAlternativeCount??0)>1)).length;for(let $ of Ve){let Le=($.resolutionAlternativeCount??1)===1,re=$.targetSymbol?W(e,$.targetFile).find(ut=>ut.symbol===$.targetSymbol):void 0,Je=re?null:T({file:$.targetFile,name:$.calleeLeaf,startLine:$.targetStartLine,endLine:$.targetEndLine},k+1,`member-call:${j.file}`,void 0,$.resolution==="imported-service-object-member"&&Le,Le);if(Je&&$.serviceFile){let ut=gn(Je),Gi=ne.get(ut)??new Set;for(let zE of S.get($.serviceFile)??[])Gi.add(zE);ne.set(ut,Gi)}re&&be(re,k+1,`member-call:${j.file}`,void 0,"none",!0);let zt=B.find(ut=>ut.startLine<=$.line&&ut.endLine>=$.line),xt=oe($.line),Tt=z.find(ut=>{let Gi=Sc(e,ut);return Gi.startLine<=$.line&&Gi.endLine>=$.line});Lt(_,{kind:"call",evidence:$.resolution==="constructed-member-receiver"?"ast-constructed-member-callsite":$.resolution==="factory-callback-member"?"ast-factory-callback-callsite":$.resolution==="imported-service-object-member"?"ast-service-member-callsite":"ast-member-import-candidate",fromFile:j.file,fromSymbol:xt?.definition.symbol??null,toFile:$.targetFile,toSymbol:re?.symbol??null,fromBoundaryParticipant:Tt?Ai(Tt):void 0,fromSourceConstruct:zt?Ct(zt):void 0,toSourceConstruct:Je?Ct(Je):void 0,line:$.line,strength:$.resolution==="imported-service-object-member"?($.resolutionAlternativeCount??0)===1?"derived":"candidate":$.strength??"candidate"})}for(let $ of a.has("import")||a.has("call")?oO(e,j.file):[]){if(!$.fromFile){if(a.has("import")){let re=D.get($.shortName)??{name:$.shortName,fromFiles:new Set};re.fromFiles.add(j.file),D.set($.shortName,re)}continue}if(!f($.fromFile))continue;if(a.has("import")&&(le($.fromFile,k+1,`import:${j.file}`,!1),Lt(_,{kind:"import",evidence:"indexed-or-source-import",fromFile:j.file,fromSymbol:null,toFile:$.fromFile,toSymbol:$.symbol,line:null,strength:"mixed"})),a.has("call")&&Te.length>0){let re=($.source==="compiler"?dr(e,h,$.symbol).matches:Qn(e,$.fromFile,$.importedName)).filter(Je=>!De(Je.symbol));for(let Je of re){let zt=Te.filter(xt=>xt.calleeLeaf===$.localName).map(xt=>xt.line);if(zt.length!==0){be(Je,k+1,`source-call:${j.file}`,void 0,"none",!0);for(let xt of zt)Lt(_,{kind:"call",evidence:"ast-callsite",fromFile:j.file,fromSymbol:null,toFile:Je.relativePath,toSymbol:Je.symbol,line:xt,strength:"derived"})}}}if(!j.promoteBoundaryImports||!cO(j.file,$.fromFile,y))continue;let Le=dr(e,h,$.symbol);for(let re of Le.matches)if(lO(re.relativePath,$.fromFile,y)&&!De(re.symbol)){let Je=Pt(j.file,y).relativeDir!==Pt(re.relativePath,y).relativeDir;be(re,k+1,`boundary-import:${j.file}`,void 0,Je?"cross-workspace-or-forward":"forward-regions")}}}for(let j of a.has("runtime-boundary")?E?.links??[]:[]){if(j.strength==="candidate"||c==="exact"&&j.strength!=="exact"||x.has(j.id))continue;let B=I.get(j.from),q=I.get(j.to);if(!B||!q||!f(B.source.file)||!f(q.source.file))continue;let oe=rC(B,k,C,w,R),z=rC(q,k,C,w,R);if(oe===null&&z===null)continue;let ue=k+1,Re=Z(B,oe??ue,`runtime-boundary:${j.joinRule}`),Te=Z(q,z??ue,`runtime-boundary:${j.joinRule}`),ve=Re?null:nC(R,B),Me=Te?null:nC(R,q);C.set(B.id,oe??ue),C.set(q.id,z??ue),Lt(_,{kind:"runtime-boundary",evidence:`runtime-boundary:${j.joinRule}`,fromFile:B.source.file,fromSymbol:Re,toFile:q.source.file,toSymbol:Te,fromBoundaryParticipant:Ai(B),toBoundaryParticipant:Ai(q),fromSourceConstruct:ve?Ct(ve):void 0,toSourceConstruct:Me?Ct(Me):void 0,runtimeBoundaryKey:j.matchedKeyParts.map(Ve=>`${Ve.name}=${Ve.value}`).join(" "),line:B.source.startLine,strength:j.strength}),x.add(j.id)}}let Q=new Map;for(let k of L.keys())Q.set(k,Xo(k,y));let Se=[..._.values()].filter(k=>Q.has(k.fromFile)&&Q.has(k.toFile)).map(k=>({...k,fromRegionId:Q.get(k.fromFile).id,toRegionId:Q.get(k.toFile).id})).sort(uC),rt=SO(Se),vr=new Set(t.expand??[]),zn=gO(L,w,P,Se,rt,Q,vr),Qr=new Set([...L.values()].filter(k=>[...k.origins].some(H=>H.startsWith("literal-anchor:")||H==="literal-owner"||H==="symbol-anchor")).map(k=>Q.get(k.file).id)),Lf=q_(zn),kE=new Set(zn.map(k=>k.id)),FE=[...vr].filter(k=>!kE.has(k)).sort();for(let k of M)if(k.matchedRegionIds=CO(k,P,w,Q),k.kind==="literal"){let H=P.filter(ee=>ee.query===k.query);k.seedRegionIds=Pe(H.filter(ee=>ee.traversalSeed).map(ee=>Q.get(ee.file).id)),k.matchOnlyRegionIds=Pe(H.filter(ee=>!ee.traversalSeed).map(ee=>Q.get(ee.file).id))}let Df=[...w.values()].filter(k=>!k.processed).length,Pf=[...L.values()].filter(k=>k.primary&&!k.processed).length,Mf=[...L.values()].filter(k=>!k.primary&&!k.processed).length,Tf=[...w.values()].filter(k=>k.processed),ws=(E?.frontiers??[]).flatMap(k=>{let H=I.get(k.observationId);return!H&&k.source&&k.action&&k.strength?!a.has("runtime-boundary")||!f(k.source.file)||c==="exact"||!L.has(k.source.file)?[]:[{observationId:k.observationId,action:k.action,strength:k.strength,file:k.source.file,line:k.source.startLine,ownerShortName:k.ownerShortName??null,address:k.address??k.missingKeyParts.join(", "),reason:k.reason}]:!a.has("runtime-boundary")||!H||!f(H.source.file)||c==="exact"&&H.strength!=="exact"||!L.has(H.source.file)?[]:[{observationId:H.id,action:H.action,strength:H.strength,file:H.source.file,line:H.source.startLine,ownerShortName:H.owner.name,address:lC(H),reason:k.reason,protocol:H.protocol,role:H.role,modality:H.modality,resolution:H.resolution,sourceScope:H.sourceScope,keyParts:H.keyParts.map(ee=>({name:ee.name,value:ee.value,evidence:ee.evidence}))}]}).sort((k,H)=>k.file.localeCompare(H.file)||k.line-H.line),sl=(E?.links??[]).filter(k=>{if(!a.has("runtime-boundary")||c==="exact"&&k.strength!=="exact")return!1;let H=I.get(k.from),ee=I.get(k.to);return!!(H&&ee&&f(H.source.file)&&f(ee.source.file)&&(L.has(H.source.file)||L.has(ee.source.file)))}),AE=sl.filter(k=>k.strength==="exact").length,NE=sl.filter(k=>k.strength==="derived").length,_E=sl.filter(k=>k.strength==="candidate").length,OE=E?.links.filter(k=>k.strength==="exact").length??0,BE=E?.links.filter(k=>k.strength==="derived").length??0,$E=E?.links.filter(k=>k.strength==="candidate").length??0,al=vO(D,Q),cl=F===0?"accounted":"incomplete",kf=[...V>0?[`${V} broad literal anchor(s) withheld ${ce} 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 (${l.join(", ")}) remain visible as match-only evidence and do not seed traversal.`,E?"Built-in runtime-boundary extractors traverse direct and replayably derived links; heuristic candidates, unsupported frameworks, reflection, generated names, and dependency wiring not recoverable from compiler occurrences or constructor assignments remain disclosed frontiers.":"Runtime-boundary evidence is unavailable for this index; run codebaseiq reindex with this build to extract supported HTTP, event, registry, and persistence observations.","Reverse references do not recursively expand from discovered callers or callees.","Member calls use compiler occurrences, exact constructor-assigned fields, bounded unique service providers, direct factory-return members, and compiler-resolved object-literal callbacks when available. Ambiguous providers remain candidate frontiers; callback values routed through mutation, reflection, or unsupported dependency containers remain unrepresented.","Literal traversal is bounded to the smallest parser-delimited source construct; parser gaps may reduce an owner to one source line and leave its continuation untraversed.","Schema consumers stay within forward-flow regions; cross-workspace contracts may discover consumers in other workspaces. Add an explicit symbol anchor to widen either scope.",`Traversal stops after depth ${p}; nonzero frontier counts identify evidence that was discovered but not traversed.`,"Region labels are structural path groupings, not inferred runtime or architectural boundaries."],Mt=F_({db:e,anchors:M,regions:zn,symbolStates:w,sourceConstructStates:R,literalHits:P,relations:Se,externalBoundaries:al,boundaryFrontiers:ws,regionForFile:Q,closureStatus:cl,omittedSymbolCandidates:F,maxDepth:p,requestedRelationKinds:o,evidenceFloor:c,includedSourceScopes:l,blindSpots:kf,topologyFrontiers:t.topologyFrontiers??[],routeIds:t.routeIds??[],expandedRegionIds:[...vr],maxTopologyCharacters:g,fullLiteralTraversal:t.fullLiteralTraversal??!1});if(n==="topology")return Mt;let Ff=(t.behaviorFocusLocations?.length??0)>0?new Set([...Mt.anchors.flatMap(k=>k.nodeIds),...Mt.paths.flatMap(k=>k.nodeIds)]).size:void 0,Ls=iS(e,Mt,{focusLocations:t.behaviorFocusLocations,...Ff?{maxSteps:Ff}:{}});BS(e,Mt,Ls);let jE=P_(e,Mt,Ls,t.behaviorFocusLocations??[]);Mt.corridor=Av(Mt,{focusLocations:jE});let Af=OS(e,Mt,Ls,{sourceAllowed:f,selectionTerms:t.selectionTerms}),Nf=B_(Mt),HE=U_(r,i,p,o,c,l,t.fullLiteralTraversal??!1,g,zn,rt,Qr,vr,Nf),UE=H_(r,i,p,zn.filter(k=>Nf.has(k.id)),Qr,o,c,l,t.fullLiteralTraversal??!1,g);return{anchors:M,regions:zn,regionRelations:rt,externalBoundaries:al,boundaryFrontiers:ws,unmatchedExpansions:FE,expansion:UE,drilldown:Lf,presentation:HE,topology:Mt,behavior:Ls,nextAnchors:Af,closure:{status:cl,emitted:{regions:zn.length,relations:Se.length,runtimeLinks:x.size},withheld:{symbols:Df,files:Pf+Mf,regions:Mt.nodes.filter(k=>k.kind==="structural-region"&&k.disposition==="folded").length,drillAnchors:(Lf?.omittedAnchors??0)+Af.omittedAnchors,literalMatches:ce},ambiguous:{anchors:M.filter(k=>k.status==="ambiguous").length,omittedSymbolCandidates:F},external:al.length,unresolved:ws.length,explanation:cl==="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:M.length,requestedRelationKinds:o,evidenceFloor:c,includedSourceScopes:l,matchedAnchorCount:M.filter(k=>k.status!=="missing").length,literalSearchesComplete:!0,broadLiteralAnchors:V,withheldLiteralMatches:ce,symbolCandidateSetsComplete:F===0,omittedSymbolCandidates:F,maxTraversalDepth:p,frontierSymbols:Df,frontierFiles:Pf,supportFilesNotTraversed:Mf,filteredUnverifiedCallEdges:G,memberCallCandidateEdges:X,unresolvedMemberCallsites:A,runtimeBoundaryEvidenceAvailable:E!==null,runtimeBoundaryObservations:E?.observations.length??0,runtimeBoundaryExactLinks:AE,runtimeBoundaryDerivedLinks:NE,runtimeBoundaryCandidateLinks:_E,repositoryRuntimeBoundaryExactLinks:OE,repositoryRuntimeBoundaryDerivedLinks:BE,repositoryRuntimeBoundaryCandidateLinks:$E,runtimeBoundaryTraversedLinks:x.size,runtimeBoundaryFrontiers:ws.length,referenceExpansionEligibleSymbols:Tf.filter(k=>k.referenceScope!=="none").length,referenceExpansionSkippedSymbols:Tf.filter(k=>k.referenceScope==="none").length,dynamicDispatchRepresented:E?.links.some(k=>k.joinRule==="carrier.discriminator"&&x.has(k.id))??!1,runtimeGeneratedLinksRepresented:E!==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:kf}}}function P_(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=>w_.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=ba(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 M_(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 gn(e){return`${e.file}\0${e.startLine}\0${e.endLine}\0${e.name}`}function Ct(e){return{file:e.file,name:e.name,startLine:e.startLine,endLine:e.endLine}}function bc(e,t){let n=Yd(te(e,t.file)?.callables??[],t.startLine);if(n&&n.endLine>=t.endLine)return{file:t.file,name:/^source@\d+$/u.test(n.name)&&!/^source@\d+$/u.test(t.name)?t.name:n.name,startLine:n.startLine,endLine:n.endLine};let r=cC(e,t.file,t.startLine);return r&&r.endLine>=t.endLine?{file:t.file,name:r.name,startLine:r.startLine,endLine:r.endLine}:Ct(t)}function Fi(e){return Dt("source-construct",e.file,String(e.startLine),String(e.endLine),e.name)}function Cc(e,t){let n=Ii(e,t.symbol,t.relativePath),r=new Set(["package-surface-file","transitive-package-surface"]),i=n.filter(s=>!r.has(s)||It(e,t)),o=i.some(s=>!r.has(s));return{evidence:i,priority:o||Sb(e,t.symbol,t.relativePath)?2:1}}function Xv(e,t){let n=Cc(e,t);return n.evidence.length>0?n.priority:0}function T_(e,t){let n=W(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=Cc(e,i);if(o.evidence.length>0)return o}for(let i of k_(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=Cc(e,s);if(a.evidence.length>0)return a}return{evidence:[],priority:0}}return{evidence:[],priority:0}}function k_(e,t,n){let r=ae(e,t)?.rootNode;if(!r||r.startPosition.row>n||r.endPosition.row<n)return[];let i=[],o=Xd(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 F_(e){let t=[...new Map([...e.sourceConstructStates.values()].map(R=>bc(e.db,R)).map(R=>[gn(R),R])).values()].sort((R,P)=>R.file.localeCompare(P.file)||R.startLine-P.startLine||R.endLine-P.endLine),n=e.anchors.map((R,P)=>{let _=Dt("anchor",String(P),R.kind,R.query),D=[...e.symbolStates.values()].filter(G=>G.anchorQueries.has(R.query)).flatMap(G=>{if(!De(G.definition.symbol))return[mr(G.definition.symbol)];let X=t.filter(A=>A.file===G.definition.relativePath).map(A=>Fi(A));return X.length>0?X:[mr(G.definition.symbol)]}),M=[...e.sourceConstructStates.values()].filter(G=>G.anchorQueries.has(R.query)).map(G=>Fi(bc(e.db,G))),F=e.literalHits.filter(G=>G.query===R.query&&G.traversalSeed===!0&&G.ownerSymbol&&e.symbolStates.has(G.ownerSymbol)).map(G=>mr(G.ownerSymbol)),V=e.literalHits.filter(G=>G.query===R.query&&G.traversalSeed===!0&&!G.ownerSymbol&&G.ownerStartLine!==null&&G.ownerStartLine!==void 0&&G.ownerEndLine!==null&&G.ownerEndLine!==void 0).map(G=>Fi(bc(e.db,M_(G)))),ce=Pe(R.kind==="symbol"?[...D,...M]:F.length+V.length>0?[...F,...V]:R.seedRegionIds??[]);return{id:_,kind:R.kind,query:R.query,status:R.status,nodeIds:R.status==="ambiguous"?[]:ce,candidateNodeIds:R.status==="ambiguous"?ce:[],omittedCandidates:R.omittedSymbolCandidates??0}}),r=new Map;for(let R of n)for(let P of[...R.nodeIds,...R.candidateNodeIds]){let _=r.get(P)??[];_.push(R.id),r.set(P,_)}let i=e.relations.flatMap(R=>[R.fromBoundaryParticipant,R.toBoundaryParticipant].flatMap(P=>P?.ownerName?[P]:[])),o=e.regions.map(R=>({id:R.id,kind:"structural-region",label:R.label,disposition:"folded",location:null,anchorIds:Pe(r.get(R.id)??[]),attributes:{workspace:R.workspace,structuralPath:R.structuralPath,minimumDepth:R.minDepth,files:R.fileCount,symbols:R.symbolCount,expanded:R.expanded}}));for(let R of e.symbolStates.values()){let P=e.regionForFile.get(R.definition.relativePath)?.id;if(!P)throw new Error(`System-map symbol ${R.definition.symbol} has no structural region.`);let _=mr(R.definition.symbol),D=Cc(e.db,R.definition);o.push({id:_,kind:"symbol",label:N(R.definition.symbol),disposition:(r.get(_)?.length??0)>0?"emitted":"folded",location:{file:R.definition.relativePath,line:R.definition.startLine,endLine:R.definition.endLine},anchorIds:Pe(r.get(_)??[]),attributes:{regionId:P,depth:R.depth,leaf:R.definition.leaf??N(R.definition.symbol),referenceScope:R.referenceScope,...D.evidence.length>0?{publicEntry:!0,publicEntryPriority:D.priority,publicEntryEvidence:D.evidence.join(",")}:{}}})}for(let R of t){let P=e.regionForFile.get(R.file)?.id;if(!P)throw new Error(`Source construct ${R.name} has no structural region.`);let _=Fi(R),M=i.find(V=>V.file===R.file&&V.line>=R.startLine&&V.line<=R.endLine)?.ownerName??R.name,F=T_(e.db,R);o.push({id:_,kind:"source-construct",label:M,disposition:(r.get(_)?.length??0)>0?"emitted":"folded",location:{file:R.file,line:R.startLine,endLine:R.endLine},anchorIds:Pe(r.get(_)??[]),attributes:{regionId:P,leaf:M,sourceOwned:!0,...F.evidence.length>0?{publicEntry:!0,publicEntryPriority:F.priority,publicEntryEvidence:F.evidence.join(",")}:{}}})}let s=new Map;for(let R of e.relations)R.fromBoundaryParticipant&&s.set(R.fromBoundaryParticipant.observationId,R.fromBoundaryParticipant),R.toBoundaryParticipant&&s.set(R.toBoundaryParticipant.observationId,R.toBoundaryParticipant);for(let R of[...s.values()].sort((P,_)=>P.observationId.localeCompare(_.observationId))){let P=e.regionForFile.get(R.file)?.id;if(!P)throw new Error(`Runtime-boundary participant ${R.observationId} has no structural region.`);o.push({id:Wd(R.observationId),kind:"runtime-boundary-participant",label:R.address||R.ownerName||`${R.role} ${R.action}`,disposition:"folded",location:{file:R.file,line:R.line,endLine:R.endLine},anchorIds:[],attributes:{regionId:P,action:R.action,protocol:R.protocol,role:R.role,...R.address?{address:R.address}:{},ownerSymbol:R.ownerSymbol}})}let a=new Set(o.map(R=>R.id)),c=Yt(t,R=>R.file),l=(R,P,_,D,M,F,V=!1)=>{let ce=R?mr(R):null;if(ce&&a.has(ce)&&!De(R))return ce;let G=P?Wd(P.observationId):null;if(V&&G&&a.has(G))return G;let X=_?Fi(bc(e.db,_)):null;if(X&&a.has(X))return X;if(G&&a.has(G))return G;let A=F===null?null:(c.get(M)??[]).filter(K=>K.startLine<=F&&K.endLine>=F).sort((K,ne)=>K.endLine-K.startLine-(ne.endLine-ne.startLine)||K.startLine-ne.startLine)[0]??null;return A?Fi(A):ce&&a.has(ce)?ce:D},u=[];for(let R of e.symbolStates.values()){let P=e.regionForFile.get(R.definition.relativePath)?.id;if(!P)continue;let _=mr(R.definition.symbol);u.push({id:Dt("edge","structural-membership",P,_),kind:"structural-membership",fromNodeId:P,toNodeId:_,directed:!0,disposition:"folded",semantics:sc("structural-membership"),evidence:[{method:"indexed-definition-file",strength:"exact",identity:R.definition.symbol,location:{file:R.definition.relativePath,line:R.definition.startLine,endLine:R.definition.endLine}}]})}let d=Yt(e.relations,R=>`${l(R.fromSymbol,R.fromBoundaryParticipant,R.fromSourceConstruct,R.fromRegionId,R.fromFile,R.line,R.kind==="runtime-boundary")}\0${l(R.toSymbol,R.toBoundaryParticipant,R.toSourceConstruct,R.toRegionId,R.toFile,null)}\0${R.kind}`),m=new Set;for(let R of d.values()){let P=R[0],_=l(P.fromSymbol,P.fromBoundaryParticipant,P.fromSourceConstruct,P.fromRegionId,P.fromFile,P.line,P.kind==="runtime-boundary"),D=l(P.toSymbol,P.toBoundaryParticipant,P.toSourceConstruct,P.toRegionId,P.toFile,null);if(P.kind==="runtime-boundary"&&P.fromBoundaryParticipant){let F=Wd(P.fromBoundaryParticipant.observationId),V=l(P.fromSymbol,void 0,P.fromSourceConstruct,P.fromRegionId,P.fromFile,P.line);V!==F&&!m.has(F)&&(m.add(F),u.push({id:Dt("edge","boundary-observation",V,F),kind:"boundary-observation",fromNodeId:V,toNodeId:F,directed:!0,disposition:"folded",semantics:sc("boundary-observation"),evidence:[{method:"runtime-boundary-observation-owner",strength:P.strength??"unknown",identity:P.fromBoundaryParticipant.observationId,location:{file:P.fromBoundaryParticipant.file,line:P.fromBoundaryParticipant.line,endLine:P.fromBoundaryParticipant.endLine}}]}))}(_===D?o.find(F=>F.id===_):null)?.kind!=="structural-region"&&u.push({id:Dt("edge",P.kind,_,D),kind:P.kind,fromNodeId:_,toNodeId:D,directed:!0,disposition:"folded",semantics:ov(P),evidence:$_(R.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}})))})}for(let R of e.externalBoundaries){let P=Dt("external",R.kind,R.name),_=Pe(R.fromRegionIds);o.push({id:P,kind:R.kind,label:R.name,disposition:"folded",location:null,anchorIds:[],attributes:{}});for(let D of _)u.push({id:Dt("edge",R.kind,D,P),kind:R.kind,fromNodeId:D,toNodeId:P,directed:!0,disposition:"folded",semantics:sc("external-import"),evidence:[{method:"indexed-or-source-import",strength:"mixed",identity:`${D} -> ${R.name}`,location:null}]})}let f=[];e.boundaryFrontiers.forEach((R,P)=>{let _=e.regionForFile.get(R.file)?.id;if(!_)throw new Error(`Runtime-boundary frontier ${R.observationId} has no system-map region.`);let D=Dt("unsupported","runtime-boundary",R.observationId,String(P)),M=Dt("edge","runtime-boundary-frontier",_,D);o.push({id:D,kind:"runtime-boundary-frontier",label:R.address,disposition:"unsupported",location:{file:R.file,line:R.line},anchorIds:[],attributes:{action:R.action,strength:R.strength,owner:R.ownerShortName}}),u.push({id:M,kind:"runtime-boundary-frontier",fromNodeId:_,toNodeId:D,directed:!0,disposition:"unsupported",evidence:[{method:"runtime-boundary-extractor",strength:R.strength,identity:R.observationId,location:{file:R.file,line:R.line}}]}),f.push({id:Dt("frontier","runtime-boundary",R.observationId,String(P)),kind:"runtime-boundary",direction:"unresolved",fromNodeIds:[_],edgeIds:[M],memberNodeIds:[D],memberCount:1,disposition:"unsupported",reason:R.reason,expansion:null})});let p=yc({anchors:n,nodes:o,edges:u,paths:[],frontiers:f,scope:`explicit anchors; relations ${e.requestedRelationKinds.join(", ")}; depth ${e.maxDepth}; evidence floor ${e.evidenceFloor}; source scopes ${e.includedSourceScopes.join(", ")}`,blindSpots:[...e.blindSpots],incompleteReasons:e.closureStatus==="incomplete"?[`${e.omittedSymbolCandidates} ambiguous symbol candidate(s) were omitted`]:[]}),g=e.topologyFrontiers.some(R=>R==="frontier:program-facts"),h=Wv(p,{expandedFrontierIds:e.topologyFrontiers.filter(R=>R!=="frontier:program-facts"),routeIds:e.routeIds}),b=h.nodes.filter(R=>R.disposition==="emitted"||h.anchors.some(P=>P.status==="matched"&&P.nodeIds.includes(R.id))),S=e.relations.filter(R=>b.some(P=>A_(R,P))),y=e.boundaryFrontiers.filter(R=>b.some(P=>N_(R,P))),E=gv(e.db,S,b),I=yv(e.db,b),v=Pv(e.db,b,y),x=[...E.nodes,...I.nodes,...v.nodes].map(R=>g&&R.disposition==="folded"?{...R,disposition:"emitted"}:R),C=[...E.edges,...I.edges,...v.edges].map(R=>g&&R.disposition==="folded"?{...R,disposition:"emitted"}:R),L=g?null:__(b,x,C),w=yc({anchors:h.anchors,nodes:[...h.nodes,...x],edges:[...h.edges,...C],paths:h.paths,frontiers:[...h.frontiers,...E.frontiers,...I.frontiers,...v.frontiers,...L?[L]:[]],scope:h.coverage.scope,blindSpots:[...h.coverage.blindSpots,...E.blindSpots,...I.blindSpots,...v.blindSpots],incompleteReasons:h.coverage.status==="incomplete"?[h.coverage.explanation]:[],...h.routeCatalog?{routeCatalog:h.routeCatalog}:{}});w.completion=h.completion;for(let R of w.frontiers)R.disposition==="folded"&&(R.id.startsWith("frontier:program-facts:")||(R.expansion=O_(e,R.id)));return w}function A_(e,t){if(e.fromSymbol&&t.id===mr(e.fromSymbol)||e.toSymbol&&t.id===mr(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 N_(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 __(e,t,n){let r=Pe(t.filter(o=>o.disposition==="folded").map(o=>o.id)),i=Pe(n.filter(o=>o.disposition==="folded").map(o=>o.id));return r.length===0&&i.length===0?null:{id:Dt("frontier","program-facts"),kind:"program-facts",direction:"outgoing",fromNodeIds:Pe(e.map(o=>o.id)),edgeIds:i,memberNodeIds:r,memberCount:r.length,disposition:"folded",reason:"Control, data, state, and temporal facts are folded beneath the selected high-level owners.",expansion:null}}function O_(e,t){return`codebaseiq system-map ${[...e.anchors.flatMap(r=>r.kind==="literal"?[`--search ${Ae(r.query)}`]:[`--symbol ${Ae(r.query)}`]),`--depth ${e.maxDepth}`,...e.requestedRelationKinds.map(r=>`--relation ${Ae(r)}`),`--evidence-floor ${Ae(e.evidenceFloor)}`,...e.includedSourceScopes.map(r=>`--source-scope ${Ae(r)}`),...e.fullLiteralTraversal?["--full-literal-traversal"]:[],`--topology-characters ${e.maxTopologyCharacters}`,...e.expandedRegionIds.map(r=>`--expand ${Ae(r)}`),...e.topologyFrontiers.map(r=>`--frontier ${Ae(r)}`),...e.routeIds.map(r=>`--route ${Ae(r)}`),`--frontier ${Ae(t)}`].join(" ")}`}function B_(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 $_(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 Dt(...e){return e.map(t=>encodeURIComponent(t)).join(":")}function mr(e){return Dt("symbol",e)}function j_(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function H_(e,t,n,r,i,o,s,a,c,l){let u=[...r].sort((g,h)=>aC(g,h,i)),m=u.slice(0,Jv).map(g=>g.id),f=u.slice(Jv).map(g=>g.id),p=[...e.map(g=>`--search ${Ae(g)}`),...t.map(g=>`--symbol ${Ae(g)}`),`--depth ${n}`,...o.map(g=>`--relation ${Ae(g)}`),`--evidence-floor ${Ae(s)}`,...a.map(g=>`--source-scope ${Ae(g)}`),...c?["--full-literal-traversal"]:[],`--topology-characters ${l}`,...m.map(g=>`--expand ${Ae(g)}`)];return{command:m.length===0?null:`codebaseiq system-map ${p.join(" ")}`,regionCount:m.length,regionIds:m,candidateRegionCount:r.length,omittedRegionIds:f}}function U_(e,t,n,r,i,o,s,a,c,l,u,d,m){let f=[...c].sort((w,R)=>aC(w,R,u)).filter(w=>!m||m.has(w.id)||d.has(w.id)),p=l.length>0?Math.floor(a*.4):0,g=a-p,h=new Set,b=0;for(let w of f){let R=Qv(w);!d.has(w.id)&&h.size>0&&b+R>g||(h.add(w.id),b+=R)}let S=l.filter(w=>h.has(w.fromRegionId)&&h.has(w.toRegionId)).sort(z_),y=[];for(let w of S){let R=Zv(w);y.length>0&&b+R>a||(y.push(xc(w)),b+=R)}let E=c.filter(w=>!h.has(w.id)).map(w=>w.id).sort(),I=new Set(y),v=l.filter(w=>!I.has(xc(w))).length,x=c.reduce((w,R)=>w+Qv(R),0)+l.reduce((w,R)=>w+Zv(R),0),C=f.every(w=>h.has(w.id))&&y.length===S.length,L=[...e.map(w=>`--search ${Ae(w)}`),...t.map(w=>`--symbol ${Ae(w)}`),`--depth ${n}`,...r.map(w=>`--relation ${Ae(w)}`),`--evidence-floor ${Ae(i)}`,...o.map(w=>`--source-scope ${Ae(w)}`),...s?["--full-literal-traversal"]:[],`--topology-characters ${Math.max(a,x)}`];return{maxCharacters:a,estimatedCharacters:b,totalEstimatedCharacters:x,regionIds:[...h],omittedRegionIds:E,relationKeys:y,omittedRelations:v,complete:C,expansionCommand:C?null:`codebaseiq system-map ${L.join(" ")}`}}function Qv(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 Zv(e){return 70+e.fromRegionId.length+e.toRegionId.length+e.kinds.join(",").length+e.evidence.join(",").length}function z_(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||xc(e).localeCompare(xc(t))}function xc(e){return`${e.fromRegionId}\0${e.toRegionId}`}function aC(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 q_(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=Yt(i.symbols,c=>c.file),s=Yt(i.literalHits,c=>c.file),a=[...i.files].sort((c,l)=>G_(c,l,o,s));for(let c of a){let l=(o.get(c.file)??[]).sort(W_)[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(dC)[0];u&&t.push({kind:"literal",regionId:i.id,file:u.file,line:u.line,endLine:null,label:u.ownerShortName??u.query})}}let r=K_(t,n);return{command:r.length===0?null:`codebaseiq inspect ${r.map(i=>`--at ${Ae(`${i.file}:${i.line+1}`)}`).join(" ")} --view behavior`,definitionCommand:null,candidateAnchors:t.length,selectedAnchors:r.length,omittedAnchors:t.length-r.length,anchors:r}}function K_(e,t){let n=[...Yt(e,s=>s.regionId).values()],r=[],i=new Set,o=Math.min(I_,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 G_(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=>Qo(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 W_(e,t){return Qo(e.origins)-Qo(t.origins)||e.depth-t.depth||e.startLine-t.startLine||e.shortName.localeCompare(t.shortName)}function Ae(e){return`'${e.replaceAll("'","'\\''")}'`}function V_(e,t,n,r){let i=[];for(let o of me(e,{includeIgnored:!1})){let s=ie(e,o);if(s.length===0)continue;let a=t.definitionsForFile(o),c=te(e,o)?.callables??[];for(let l=0;l<s.length;l+=1){let u=s[l]??"";if(!u.includes(n))continue;let d=Ke(a,l),m=Yd(c,l),f=d&&!De(d.symbol)?d:null,p=f?.startLine??m?.startLine??d?.startLine??l,g=f?.endLine??m?.endLine??d?.endLine??l,h=go(e,o,l,p,g),b=r.has(`${o}\0${l}`),S=!!(f?.isFunctionLike||m);i.push({relativePath:o,line:l,sourceLine:u,ownerSymbol:f?.symbol??null,ownerShortName:f?N(f.symbol):m?.name??(d?N(d.symbol):null),ownerStartLine:h.startLine,ownerEndLine:h.endLine,matchKind:Q_(u,n),seedPriority:b?0:S?1:2})}}return i}function J_(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 eC(e){return`${e.relativePath}\0${e.line}`}function Yd(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,r)=>n.endLine-n.startLine-(r.endLine-r.startLine)||n.startLine-r.startLine)[0]??null}function Gd(e,t,n){let i=Yd(te(e,t)?.callables??[],n)??cC(e,t,n);if(!i)return null;let o=go(e,t,n,i.startLine,i.endLine);return{file:t,name:i.name,startLine:o.startLine,endLine:o.endLine}}function cC(e,t,n){let r=ae(e,t)?.rootNode;if(!r||r.startPosition.row>n||r.endPosition.row<n)return null;let i=Xd(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&&Vd(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)&&Vd(a,n))return{name:c,startLine:i.startPosition.row,endLine:i.endPosition.row}}i=i.parent}let o=hi(e,t,n);return o?{name:`source@${n+1}`,startLine:o.startLine,endLine:o.endLine}:null}function Vd(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&&Vd(n,t))}function Xd(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?Xd(n,t):e}function Y_(e,t){let n=t.match(/^(.+):(\d+)(?:-(\d+))?$/u);if(!n)return null;let r=_s(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=(te(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 X_(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 Q_(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 Jd(e){return J(e)==="test"?!1:!/(?:^|[/._-])(?:fixtures?|mocks?|previews?|demos?|examples?|stories)(?:[/._-]|$)/iu.test(e)}function Z_(e,t){return e.matchKind!=="embedded"&&t(e.relativePath)&&(Il(e.relativePath)!=="production"||Jd(e.relativePath))}function eO(e,t){let n=[...t].sort(tO),r=[],i=new Set;for(let o of n)if(!i.has(o.relativePath)&&(r.push(o),i.add(o.relativePath),r.length>=Vv))break;for(let o of n){if(r.length>=Vv)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 tO(e,t){let n={"exact-value":0,boundary:1,embedded:2};return n[e.matchKind]-n[t.matchKind]||+(t.ownerSymbol!==null)-+(e.ownerSymbol!==null)||+!Jd(e.relativePath)-+!Jd(t.relativePath)||e.relativePath.localeCompare(t.relativePath)||e.line-t.line}function nO(e,t){let n=new Map;for(let r of t){let i=rO(r.relativePath);n.set(i,(n.get(i)??0)+1)}return[...n].sort(([r,i],[o,s])=>s-i||r.localeCompare(o)).slice(0,x_).map(([r])=>`codebaseiq search ${Ae(e)} --scope ${Ae(r)}`)}function rO(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 iO(e,t,n){let r=t.callerFileMap([n],{semantic:!1}).get(n.symbolId)??new Set,i=[];for(let o of[...r].sort()){let s=n.leaf?wn(e,o,n.leaf):[];if(s.length===0){i.push({file:o,line:null,enclosingSymbol:null});continue}let a=t.definitionsForFile(o);for(let c of s)i.push({file:o,line:c,enclosingSymbol:Ke(a,c)?.symbol??null})}return i}function oO(e,t){let n=e.all(`SELECT DISTINCT gs.symbol, def_d.relative_path AS from_file
97
- FROM mentions m
98
- JOIN chunks c ON m.chunk_id = c.id
99
- JOIN documents imp_d ON c.document_id = imp_d.id
100
- JOIN global_symbols gs ON m.symbol_id = gs.id
101
- LEFT JOIN (
102
- SELECT m2.symbol_id, c2.document_id
103
- FROM mentions m2
104
- JOIN chunks c2 ON m2.chunk_id = c2.id
105
- WHERE m2.role = 1
106
- GROUP BY m2.symbol_id
107
- ) sym_def ON sym_def.symbol_id = gs.id
108
- LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
109
- WHERE imp_d.relative_path = ? AND m.role = 2
110
- ORDER BY def_d.relative_path, gs.symbol`,t);return n.length>0?n.map(r=>({symbol:r.symbol,shortName:N(r.symbol),importedName:tC(N(r.symbol)),localName:tC(N(r.symbol)),fromFile:r.from_file,source:"compiler"})):Ce(e,t).map(r=>{let i=sO(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 tC(e){return e.slice(e.lastIndexOf(":")+1).replace(/\(\)$/u,"")||e}function sO(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 dr(e,t,n){let r=at(e,n);if(!r.match)return{matches:[],total:0,omitted:0};let i=[r.match,...r.candidates.map(s=>at(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 aO(e){return{symbol:e.symbol,shortName:N(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine}}function Lt(e,t){let n=[t.kind,t.fromFile,t.fromSymbol??"",t.toFile,t.toSymbol??"",t.fromBoundaryParticipant?.observationId??"",t.toBoundaryParticipant?.observationId??"",t.fromSourceConstruct?gn(t.fromSourceConstruct):"",t.toSourceConstruct?gn(t.toSourceConstruct):"",t.runtimeBoundaryKey??"",t.line??""].join("\0");e.set(n,t)}function Ai(e){return{observationId:e.id,action:e.action,protocol:e.protocol,role:e.role,address:lC(e),file:e.source.file,line:e.source.startLine,endLine:e.source.endLine,ownerName:e.owner.name,ownerSymbol:e.owner.symbol}}function Sc(e,t){let n=ie(e,t.source.file);return bt(e,t.source.file,0,Math.max(0,n.length-1),[t.source.startLine])}function nC(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 rC(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;iC(c,e)&&o.push(a.depth)}for(let a of i.values())a.depth>t||iC(a,e)&&o.push(a.depth);return o.length>0?Math.min(...o):null}function iC(e,t){let n=e.relativePath??e.file;return[t.owner,t.source].some(r=>n===r.file&&e.startLine<=r.startLine&&e.endLine>=r.startLine)}function Wd(e){return Dt("runtime-boundary-participant",e)}function cO(e,t,n){let r=Pt(e,n),i=Pt(t,n);return r.relativeDir!==i.relativeDir?!0:/(?:^|\/)(?:contracts?|schemas?|db\/schema)(?:\/|$)/u.test(t)}function lO(e,t,n){return Xo(e,n).id===Xo(t,n).id}function uO(e,t,n,r){if(e.referenceScope==="all")return!0;let i=Xo(t,r).id;return[...n.values()].some(s=>s.promoteBoundaryImports&&Xo(s.file,r).id===i)?!0:e.referenceScope!=="cross-workspace-or-forward"?!1:Pt(t,r).relativeDir!==Pt(e.definition.relativePath,r).relativeDir}function dO(e,t){let n={none:0,"forward-regions":1,"cross-workspace-or-forward":2,all:3};return n[e]>=n[t]?e:t}function mO(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 Pt(e,t){return t.find(n=>e===n.relativeDir||e.startsWith(`${n.relativeDir}/`))??{name:"root",relativeDir:""}}function fO(e){let t=new Set(["apps","packages","services","crates","libs","tools"]),n=new Map;for(let r of e){let i=r.split("/").filter(Boolean);if(i.length<3||!t.has(i[0]))continue;let o=`${i[0]}/${i[1]}`;n.set(o,{name:i[1],relativeDir:o})}return[...n.values()].sort((r,i)=>i.relativeDir.length-r.relativeDir.length)}function Xo(e,t){let n=Pt(e,t),i=(n.relativeDir?e.slice(n.relativeDir.length+1):e).split("/").filter(Boolean);i[0]==="src"&&i.shift();let o=pO(i);return{id:`region:${n.relativeDir||"root"}:${o}`,label:`${n.name}:${o}`,workspace:n.name,structuralPath:o}}function pO(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 gO(e,t,n,r,i,o,s){let a=Yt([...e.values()],f=>o.get(f.file).id),c=Yt([...t.values()],f=>o.get(f.definition.relativePath).id),l=Yt(n,f=>o.get(f.file).id),u=new Map;for(let f of r)for(let p of new Set([f.fromRegionId,f.toRegionId])){let g=u.get(p)??[];g.push(f),u.set(p,g)}let d=Yt(i,f=>f.toRegionId),m=Yt(i,f=>f.fromRegionId);return[...a.entries()].map(([f,p])=>{let g=o.get(p[0].file),h=c.get(f)??[],b=l.get(f)??[],S=u.get(f)??[],y=s.has(f),E=h.map(bO).sort(xO).slice(0,R_),I=p.filter(v=>J(v.file)==="test").length;return{id:f,label:g.label,workspace:g.workspace,structuralPath:g.structuralPath,minDepth:Math.min(...p.map(v=>v.depth)),fileCount:p.length,sourceFileCount:p.length-I,testFileCount:I,symbolCount:h.length,literalHitCount:b.length,anchorQueries:Pe([...b.map(v=>v.query),...h.flatMap(v=>[...v.anchorQueries])]),relationKinds:Pe(S.map(v=>v.kind)),incomingRegionIds:Pe((d.get(f)??[]).map(v=>v.fromRegionId)),outgoingRegionIds:Pe((m.get(f)??[]).map(v=>v.toRegionId)),memberCallCandidateRelationCount:S.filter(v=>v.evidence==="ast-member-import-candidate").length,notableSymbols:E,omittedNotableSymbols:Math.max(0,h.length-E.length),expanded:y,files:y?p.map(hO).sort(RO):[],symbols:y?h.map(yO).sort(IO):[],literalHits:y?[...b].sort(dC):[],relations:y?[...S].sort(uC):[]}}).sort((f,p)=>f.minDepth-p.minDepth||f.label.localeCompare(p.label))}function hO(e){return{file:e.file,kind:J(e.file),depth:e.depth,origins:Pe([...e.origins])}}function yO(e){return{symbol:e.definition.symbol,shortName:N(e.definition.symbol),file:e.definition.relativePath,startLine:e.definition.startLine,endLine:e.definition.endLine,depth:e.depth,origins:Pe([...e.origins]),anchorQueries:Pe([...e.anchorQueries]),referenceExpansion:e.referenceScope!=="none",referenceScope:e.referenceScope}}function bO(e){return{shortName:N(e.definition.symbol),file:e.definition.relativePath,origins:Pe([...e.origins])}}function SO(e){return[...Yt(e.filter(n=>n.fromRegionId!==n.toRegionId),n=>`${n.fromRegionId}\0${n.toRegionId}`).values()].map(n=>({fromRegionId:n[0].fromRegionId,toRegionId:n[0].toRegionId,kinds:Pe(n.map(r=>r.kind)),relationCount:n.length,fromFiles:Pe(n.map(r=>r.fromFile)),toFiles:Pe(n.map(r=>r.toFile)),fromSymbols:Pe(n.flatMap(r=>r.fromSymbol?[N(r.fromSymbol)]:[])),toSymbols:Pe(n.flatMap(r=>r.toSymbol?[N(r.toSymbol)]:[])),evidence:Pe(n.map(r=>r.evidence)),strengths:Pe(n.map(r=>r.strength??"unknown"))})).sort((n,r)=>n.fromRegionId.localeCompare(r.fromRegionId)||n.toRegionId.localeCompare(r.toRegionId))}function vO(e,t){return[...e.values()].map(n=>({kind:"external-import",name:n.name,fromRegionIds:Pe([...n.fromFiles].flatMap(r=>{let i=t.get(r);return i?[i.id]:[]})),fromFiles:Pe([...n.fromFiles])})).sort((n,r)=>n.name.localeCompare(r.name))}function CO(e,t,n,r){let i=e.kind==="literal"?t.filter(o=>o.query===e.query).map(o=>o.file):[...n.values()].filter(o=>o.anchorQueries.has(e.query)).map(o=>o.definition.relativePath);return Pe(i.map(o=>r.get(o)?.id).filter(o=>!!o))}function lC(e){return e.keyParts.map(t=>`${t.name}=${t.value}`).join(" ")}function vc(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))]}function Pe(e){return[...new Set(e)].sort()}function Yt(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 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 xO(e,t){return Qo(e.origins)-Qo(t.origins)||e.shortName.localeCompare(t.shortName)}function Qo(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 RO(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)}function IO(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)||e.symbol.localeCompare(t.symbol)}function dC(e,t){return e.file.localeCompare(t.file)||e.line-t.line||e.query.localeCompare(t.query)}var wO=["causal","structure","complete"],LO={causal:["execution","runtime","dataflow","state","temporal"],structure:["contract","identity","ownership","dependencies"],complete:Kt},DO=2,PO=48,mC=64,MO=5e4;function Zo(e,t,n={}){let r=$n([...t.symbols??[],...t.locations??[]]),i=$n(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=TO(n.families,o),a=n.direction??"both",c=$n(n.subtypes??[]),l=n.connecting??!1,u=n.inventoryOnly??!1,d=$n(n.foldIds??[]),m=n.maxDepth??DO,f=n.maxEdges??PO;if(!Number.isSafeInteger(m)||m<0)throw new RangeError(`Evidence depth must be a non-negative safe integer; received ${m}.`);if(!Number.isSafeInteger(f)||f<=0)throw new RangeError(`Evidence max edges must be a positive safe integer; received ${f}.`);if(!["incoming","outgoing","both"].includes(a))throw new Error(`Unsupported graph evidence direction: ${a}.`);if(u&&d.length>0)throw new Error("Evidence fold materialization cannot be combined with --inventory-only.");let p=oC(e,{symbols:r,searches:i,maxDepth:m,maxTopologyCharacters:MO,relations:kO(s)}),g=new Map(p.nodes.map(X=>[X.id,X])),h=p.edges.filter(X=>X.disposition==="emitted"||X.disposition==="folded").flatMap(X=>FO(X,g)),b=h.filter(X=>s.includes(X.family)).filter(X=>c.length===0||c.includes(X.subtype)),S=new Set(p.anchors.flatMap(X=>X.nodeIds));if(l&&S.size<2)throw new Error("Connecting evidence requires at least two resolved root nodes.");let y=new Set(b.map(X=>X.id)),E=Qd(h,S,"incoming").filter(X=>y.has(X.id)),I=Qd(h,S,"outgoing").filter(X=>y.has(X.id)),v=Qd(h,S,"both").filter(X=>y.has(X.id)),x=BO(s,c,E,I,v),C=a==="incoming"?E:a==="outgoing"?I:v,L=l?KO(C,[...S],a):C,w=WO(L,S,a),R=[...L].sort((X,A)=>VO(X,A,w)),P=$O(R,f),_=HO(P,d),D=u?[]:d.length>0?R.filter(X=>_.has(X.id)):R,M=d.length>0?D:D.slice(0,f),F=d.length>0||u?[]:P,V=Math.max(0,D.length-M.length),ce=p.frontiers.filter(X=>X.disposition==="unsupported").length,G=p.coverage.status==="incomplete"?"incomplete":V>0?"bounded":"accounted";return{kind:"graph",view:n.families&&n.families.length>0?"custom":o,families:s,selection:{direction:a,subtypes:c,connecting:l,inventoryOnly:u,foldIds:d},targets:p.anchors.map(X=>({kind:X.kind,query:X.query,status:X.status,nodeIds:[...X.nodeIds],omittedCandidates:X.omittedCandidates})),inventory:x,edges:M,folds:F,coverage:{status:G,topologyStatus:p.coverage.status,scope:p.coverage.scope,maxDepth:m,maxEdges:f,matchedEdges:R.length,eligibleEdges:D.length,returnedEdges:M.length,omittedEdges:V,frontierGroups:p.frontiers.length,unsupportedFrontiers:ce,blindSpots:$n([...p.coverage.blindSpots,...Op(s)]),explanation:u?`${R.length} relationship(s) match the explicit projection; only exact inventory counts were requested.`:d.length>0?`Every relationship in ${d.length} explicitly selected recoverable fold(s) was emitted.`:G==="accounted"?"Every selected relationship in the bounded topology was emitted.":G==="bounded"?`${V} selected relationship(s) were withheld by the explicit edge budget.`:p.coverage.explanation}}}function TO(e,t){let n=e&&e.length>0?e:LO[t],r=n.filter(i=>!Kt.includes(i));if(r.length>0)throw new Error(`Unsupported graph evidence family: ${r.join(", ")}.`);return $n(n)}function kO(e){return["call","contract-symbol","import","reference","runtime-boundary"]}function FO(e,t){let n=t.get(e.fromNodeId),r=t.get(e.toNodeId);return!n||!r?[]:(e.semantics??[]).flatMap((i,o)=>{let s=NO(i);if(!s)return[];let a=Bp(s,i.subtype);if(!a)throw new Error(`No graph relation provider contract is registered for ${s}/${i.subtype}.`);let c=OO(e);if(!a.relation.evidenceStrengths.includes(c))throw new Error(`Graph relation provider ${a.provider.id} does not admit ${c} evidence for ${s}/${i.subtype}.`);return[{id:`${e.id}:${o}:${s}`,family:s,semanticFamily:i.family,subtype:i.subtype,from:fC(n),to:fC(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:$n(e.evidence.map(l=>l.method)),evidenceConstituents:AO(e.evidence),context:i.context?{...i.context}:null,attributes:i.attributes?{...i.attributes}:null}]})}function AO(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 NO(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 fC(e){let t=_O(e);return{id:e.id,kind:e.kind,label:t?N(t):e.label,symbol:t,location:e.location?{...e.location}:null}}function _O(e){return e.kind!=="symbol"||!e.id.startsWith("symbol:")?null:decodeURIComponent(e.id.slice(7))}function OO(e){let t=$n(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 Qd(e,t,n){let r=Zd(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 Zd(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 BO(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 f=`${m.family}\0${m.subtype}`;d.set(f,(d.get(f)??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)=>Kt.indexOf(u.family)-Kt.indexOf(d.family)||u.subtype.localeCompare(d.subtype))}function $O(e,t){let n=e.slice(t),r=new Map;for(let s of n){let a=jO(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+=mC){let m=u.slice(d,d+mC),f=m.map(b=>b.id),p=$n(m.map(b=>b.subtype)).sort(),g=p.length===1?p[0]:"mixed",h=[...new Set(m.flatMap(b=>[b.from.id,b.to.id]))].sort();o.push({id:qO(c,p.join("\0"),f),mode:UO(m),family:c,subtype:g,subtypes:p,region:l,edgeCount:f.length,edgeIds:f,nodeIds:h,minimumMaxEdges:Math.max(...f.map(b=>i.get(b)??e.length))})}}return o.sort((s,a)=>Kt.indexOf(s.family)-Kt.indexOf(a.family)||(s.region??"").localeCompare(a.region??"")||s.id.localeCompare(a.id))}function jO(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 HO(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 UO(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 zO(r,t)?"scc":[...r].every(o=>(n.get(o)?.size??0)<=1&&(t.get(o)?.size??0)<=1)?"linear":"topology"}function zO(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 qO(e,t,n){return`fold:${EO("sha256").update([e,t,...n].join("\0")).digest("hex").slice(0,16)}`}function KO(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 GO(e,i[o],i[s],n))r.set(a.id,a);return[...r.values()]}function GO(e,t,n,r){let i=Zd(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 WO(e,t,n){let r=Zd(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 VO(e,t,n){return pC(e,n)-pC(t,n)||gC(e)-gC(t)||hC(e.evidenceStrength)-hC(t.evidenceStrength)||Kt.indexOf(e.family)-Kt.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 pC(e,t){return Math.min(t.get(e.from.id)??Number.MAX_SAFE_INTEGER,t.get(e.to.id)??Number.MAX_SAFE_INTEGER)}function gC(e){let t=[e.from,e.to].filter(n=>n.kind==="structural-region").length;return t===2?2:t}function hC(e){switch(e){case"exact":return 0;case"mixed":return 1;case"derived":return 2;case"candidate":return 3;case"unknown":return 4}}function $n(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))]}function em(e,t){let n=Dn(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let r=n.map(()=>"?").join(", "),o=e.all(`SELECT relative_path FROM documents
111
- WHERE relative_path IN (${r})
112
- ORDER BY relative_path`,...n).map(l=>l.relative_path).filter(l=>!e.isIgnored(l)),s=zs(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:l,...u})=>u),a=Pi(e,"forward",n).filter(l=>!e.isIgnored(l)),c=Pi(e,"reverse",n).filter(l=>!e.isIgnored(l));return{files:o,symbols:s,dependsOn:a,dependedOnBy:c}}function tm(e,t){let n=Dn(e,t);return n.length===0?[]:bC([...yC(e,n),...YO(e,n)]).filter(r=>!e.isIgnored(r.relative_path)).map(SC)}function JO(e,t){let n=Dn(e,t);return n.length===0?[]:bC(yC(e,n)).filter(r=>!e.isIgnored(r.relative_path)).map(r=>({...SC(r),basis:"external-reference"}))}function yC(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
113
- FROM mentions m
114
- JOIN chunks c ON m.chunk_id = c.id
115
- JOIN documents d1 ON c.document_id = d1.id
116
- JOIN global_symbols gs ON m.symbol_id = gs.id
117
- WHERE d1.relative_path NOT IN (${n})
118
- AND (
119
- EXISTS (
120
- SELECT 1
121
- FROM defn_enclosing_ranges der
122
- JOIN documents d2 ON der.document_id = d2.id
123
- WHERE der.symbol_id = gs.id
124
- AND d2.relative_path IN (${n})
125
- )
126
- OR EXISTS (
127
- SELECT 1
128
- FROM mentions def_m
129
- JOIN chunks def_c ON def_m.chunk_id = def_c.id
130
- JOIN documents d2 ON def_c.document_id = d2.id
131
- WHERE def_m.symbol_id = gs.id
132
- AND def_m.role = 1
133
- AND d2.relative_path IN (${n})
134
- )
135
- )
136
- AND m.role != 1
137
- AND ${e.localSymbolPredicate}
138
- ${e.pathExclusionsFor("d1")}
139
- ORDER BY d1.relative_path`,...t,...t,...t)}function YO(e,t){let n=new U(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>st(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function bC(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 SC(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:N(e.symbol)}}var es=new WeakMap,vC=Rt({kind:"definition-exclusions",invalidation:Ye("definition-exclusions"),serialize:e=>JSON.stringify(e),deserialize:XO});function xC(e,t){let n=ye(t);if(!(n==="rust"||n==="typescript"||n==="tsx"||n==="javascript"))return[];let i=se(e,t);if(!i)return[];let o=Nt(e,t,i),s=vC.read(e,t,o);if(s)return s;let a=n==="rust"?oB(e,t):tB(e,t);return vC.write(e,t,o,a),a}function XO(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=t.map(QO);return n.some(r=>r===null)?null:n}catch{return null}}function QO(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?yB(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 RC=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]),ZO=/\b(?:describe|it|test|fdescribe|fit|xdescribe|xit|beforeEach|afterEach|beforeAll|afterAll|before|after|suite|bench|benchmark)\s*\(/,eB=/\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 tB(e,t){let n=se(e,t);if(!n||!nB(n))return[];let r=ae(e,t);if(!r)return[];let i=es.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&&RC.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,f=d.namedChild(1);m&&(f?.type==="arrow_function"||f?.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(...IC(r,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),es.set(r,a),a}function nB(e){if(e.includes("codebaseiq"))return!0;let t=!1;for(let n of RC)if(e.includes(n)){t=!0;break}return t&&ZO.test(e)?!0:e.includes("use")&&eB.test(e)}var rB=/codebaseiq[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function iB(e){return rB.test(e)}function IC(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(iB(u.text)){r.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"codebaseiq suppression comment",disposition:"exclude"});break}continue}if(!(u.type==="attribute_item"||u.type==="inner_attribute_item"))break}}for(let s of o.namedChildren)i(s)};return i(e.rootNode),r}function oB(e,t){let n=ae(e,t);if(!n)return[];let r=es.get(n);if(r)return r;let i=[],o=sB(n);return o?(es.set(n,o),o):(EC(n.rootNode,i,!1,!1),i.push(...IC(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(...gB(n.rootNode)),es.set(n,i),i)}function sB(e){return bB(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)",disposition:"exclude"}]:null}function EC(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"?aB(e,t,n,r):r&&pB(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"?cB(e,t,n):e.type==="mod_item"&&nm(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(i=!0);for(let s of e.namedChildren)EC(s,t,i,o)}function aB(e,t,n,r){let i=nm(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(wC(s)){o={reason:"#[allow(dead_code)]",disposition:"exclude"};break}let a=mB(s);if(a){o=a;break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o.reason,disposition:o.disposition})}function cB(e,t,n){let r=nm(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(fB)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(...)] - generated impl may access fields",disposition:"implicit-usage",containerName:i}),r.some(wC)&&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 nm(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 lB=new Set(["test","bench","tokio::test","async_std::test"]),uB=new Set(["no_mangle","export_name","link_name","used","macro_export","proc_macro","proc_macro_derive","proc_macro_attribute"]),dB=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 mB(e){if(/#\[\s*cfg\s*\(\s*test\s*\)/.test(e))return{reason:"#[cfg(test)]",disposition:"exclude"};let t=hB(e);return t?lB.has(t)?{reason:`#[${t}]`,disposition:"exclude"}:uB.has(t)?{reason:`Rust ABI/export attribute #[${t}]`,disposition:"implicit-usage"}:dB.has(t)?null:{reason:`Rust attribute macro #[${t}]`,disposition:"implicit-usage"}:null}function fB(e){return/#\[\s*derive\s*\(/.test(e)}function wC(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function pB(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function gB(e){let t=SB(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 hB(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 yB(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 bB(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 CC=/\bwith\s*=\s*"([^"]+)"/g;function SB(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){CC.lastIndex=0;let r;for(;(r=CC.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}function LC(e){let t=rm(e);return(n,r,i,o)=>t(n,r,i,o)?.disposition==="exclude"}function rm(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=xC(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 qs(o))l.add(u);for(let u of l){let d=a.containers.get(u);d&&c.push(...d)}return vB(c)}}function vB(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 im(e,t={}){fl(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function DC(e,t,n={}){fl(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function PC(e,t){if(t.isIgnoredPath(e.relativePath))return gt("ignored-file");if(De(e.symbol))return gt("module-like-symbol");if(!Rc(e.symbol))return gt("non-value-symbol");if(!e.isFunctionLike&&e.enclosingSymbol&&Rc(e.enclosingSymbol))return gt("nested-non-callable-value");if(!t.includeTests&&!CB(e.relativePath))return gt("test-file");if(!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName))return gt("excluded-file-region");let n=Y(e.symbol);if(n==="<constructor>")return gt("implicit-constructor");if(e.symbol.startsWith("scip-python ")){if(n==="__all__")return gt("python-runtime-metadata");if(/^__[^_].*__$/.test(n))return gt("python-protocol-member")}return t.isDeclarationOnlyCallable()?gt("declaration-only-callable"):t.isFrameworkContractCallable()?gt("framework-contract-member"):Xe(e.symbol)?gt("rust-trait-impl-member"):ai(e.symbol)?gt("rust-test-module"):!t.includeMembers&&!xB(e)?gt("member"):e.endLine-e.startLine+1<t.minLoc?gt("below-min-loc"):{accepted:!0}}function CB(e){return J(e)!=="test"}function gt(e){return{accepted:!1,rejectionReason:e}}function Rc(e){return _e(e)||e.endsWith("().")||e.endsWith(".")}function xB(e){return st(e.symbol)||qs(e.symbol).length===0}function MC(){return new Map}function TC(e,t,n){let r=new Map;for(let i of Sp(e,n))e.isIgnored(i.relative_path)||t.has(i.relative_path)||Ec(r,i.symbol_id,i.relative_path,i.ref_count,"scip-mention");return r}function kC(e,t,n,r={}){let i=new Set;if(r.conservative||n.size===0){for(let o of Cp(e,t))i.add(o.symbol_id);return i}for(let o of vp(e,t))e.isIgnored(o.relative_path)||n.has(o.relative_path)||i.add(o.symbol_id);return i}function om(e,t){let n=e.get(t);if(!n)return!1;for(let r of n.values())if(r.occurrences>0)return!0;return!1}function Ic(e,t,n){let r=e.get(t);if(!r)return!1;for(let[i,o]of r)if(i!==n&&o.occurrences>0)return!0;return!1}function FC(e){return e?.occurrences??0}function Ec(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=NC(e,t,n);o.occurrences+=r,o.sources.add(i)}function AC(e,t,n,r,i){if(r<=0)return;let o=NC(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function NC(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 RB=new Set(["componentDidCatch","componentDidMount","componentDidUpdate","componentWillUnmount","getDerivedStateFromError","getDerivedStateFromProps","getSnapshotBeforeUpdate","render","shouldComponentUpdate","UNSAFE_componentWillMount","UNSAFE_componentWillReceiveProps","UNSAFE_componentWillUpdate"]);function Ni(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=ae(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:RB.has(t.leaf)&&/\bextends\s+(?:React\.)?(?:Component|PureComponent)\b/.test(o)}function Wr(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=O("dead.candidates",()=>{let v=Fe(IB(e,{scope:n,minLoc:r,includeTests:i,includeMembers:s}),c);return u=v.length,v},()=>({definitions:u})),m=0,f=o?O("dead.inactive-barrels",()=>{let v=new Set(bb(e));return m=v.size,v},()=>({paths:m})):new Set,p=0,g=a?MC():O("dead.mention-reference-counts",()=>{let v=TC(e,f,d.map(x=>x.symbolId));return p=v.size,v},()=>({definitions:d.length,symbolsWithReferences:p})),h=0,b=a?O("dead.mentioned-symbol-ids",()=>{let v=kC(e,d.map(x=>x.symbolId),f,{conservative:f.size===0});return h=v.size,v},()=>({definitions:d.length,referencedSymbols:h})):new Set,S=a?d.filter(v=>!b.has(v.symbolId)):d.filter(v=>!Ic(g,v.symbolId,v.relativePath));a?O("dead.source-fallback.dead-code-only",()=>TB(e,S,g,{inactiveBarrelPaths:f}),()=>({definitions:S.length,testReferencesIncluded:!0})):O("dead.source-fallback.ast",()=>MB(e,S,g,{inactiveBarrelPaths:f}),()=>({definitions:S.length,testReferencesIncluded:!0}));let y=a?S.filter(v=>!om(g,v.symbolId)):S.filter(v=>!Ic(g,v.symbolId,v.relativePath)),E=new Set;O("dead.caller-map-supplement",()=>{E=NB(e,y,g,{inactiveBarrelPaths:f,includeSemantic:!a&&l})},()=>({definitions:y.length,semantic:!a&&l}));let I=a?S.filter(v=>!om(g,v.symbolId)):d.filter(v=>!E.has(v.symbolId));return PB(e,LB(I,g))}function IB(e,t){let n=LC(e),r=[];for(let i of Qi(e,{scope:t.scope,symbolMatches:Rc,sqlPrefilter:"function-like"}))PC(i,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:s=>e.isIgnored(s),isExcludedRegion:n,isDeclarationOnlyCallable:()=>wB(e,i),isFrameworkContractCallable:()=>Ni(e,i)}).accepted&&r.push(i);return r}var EB=["method_signature","abstract_method_signature","call_signature","construct_signature"];function wB(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=ae(e,t.relativePath);if(n)return n.rootNode.descendantsOfType([...EB]).some(i=>i.startPosition.row<=t.startLine&&i.endPosition.row>=t.endLine);let r=ie(e,t.relativePath).slice(t.startLine,t.endLine+1).join(`
140
- `).trim();return r.endsWith(";")&&!r.includes("=>")&&!r.includes("{")}function LB(e,t){return e.map(n=>DB(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 DB(e,t){let n=t.get(e.symbolId)??new Map,r=FC(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 PB(e,t){let n=rm(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(Qe(e,u.relative_path)){a++;continue}if(qe(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,f=m?"implicit-usage":u.same_file_refs===0?"dead-code":"file-internal";f==="dead-code"?i++:f==="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:N(u.symbol),sameFileRefs:u.same_file_refs,kind:f,...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 MB(e,t,n,r){if(t.length===0)return;let i=new U(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 me(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)&&(FB(e,c)||Ec(n,c.target.symbolId,c.sourceFile,AB(c),"source-fallback"))})}function TB(e,t,n,r){if(t.length===0)return;let i=new U(e),o=pp(t),s=new Set(i.sourceFiles());for(let u of me(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let d=c.get(u);return d||(d=Ip(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 f=o.get(d);return f?kB(u,d,f,()=>l(u),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),DC(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&_C(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||Ec(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function kB(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=>Ft(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=>Ft(l,d.relativePath));if(u.length>0&&u.length===n.length)return u}return i.permissive?[...n]:[]}function FB(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&_C(e,t)}function AB(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function _C(e,t){return t.occurrences>1?!1:Ce(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function NB(e,t,n,r){let i=new Set,o=r.includeSemantic!==!1,s=(u,d)=>{d===u.relativePath||e.isIgnored(d)||r.inactiveBarrelPaths.has(d)||AC(n,u.symbolId,d,1,"caller-map")};if(O("dead.caller-map.per-symbol-non-semantic",()=>{for(let u of t){let d=ua(e,u,{semantic:!1,semanticEvidence:ge});for(let m of d)s(u,m.file)}},()=>({definitions:t.length,semantic:!1})),!o)return i;let a=0,c=O("dead.caller-map.semantic-candidates",()=>{let u=t.filter(d=>!Ic(n,d.symbolId,d.relativePath));return a=u.length,u},()=>({definitions:t.length,semanticCandidates:a}));if(c.length===0)return i;let l=Tn(e,c);for(let u of l.incompleteSymbolIds)i.add(u);for(let u of l.unavailableSymbolIds)i.add(u);for(let u of c){let d=l.callers.get(u.symbolId);if(d)for(let m of d)s(u,m)}return i}function _B(e,t={}){let{limit:n=30,scope:r}=t,i=r?"AND def_d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[],a=e.all(`SELECT
141
- gs.symbol,
142
- COUNT(*) AS ref_count,
143
- COUNT(DISTINCT ref_d.id) AS file_count,
144
- def_d.relative_path AS defined_in
145
- FROM mentions m
146
- JOIN chunks c ON m.chunk_id = c.id
147
- JOIN documents ref_d ON c.document_id = ref_d.id
148
- JOIN global_symbols gs ON m.symbol_id = gs.id
149
- JOIN (
150
- SELECT m2.symbol_id, c2.document_id
151
- FROM mentions m2
152
- JOIN chunks c2 ON m2.chunk_id = c2.id
153
- WHERE m2.role = 1
154
- GROUP BY m2.symbol_id
155
- ) sym_def ON sym_def.symbol_id = gs.id
156
- JOIN documents def_d ON sym_def.document_id = def_d.id
157
- WHERE m.role != 1
158
- AND def_d.id != ref_d.id
159
- ${e.pathExclusionsFor("def_d")}
160
- ${e.symbolNoiseFor("gs")}
161
- ${i}
162
- GROUP BY gs.id
163
- ORDER BY ref_count DESC
164
- LIMIT ?`,...o,n).filter(c=>!e.isIgnored(c.defined_in)).map(c=>({symbol:c.symbol,shortName:N(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?{rows:a,coverage:{semanticEvidence:{enabled:!1,status:"disabled",incompleteSymbolCount:0,unavailableSymbolCount:0}}}:OB(e,r,n)}function OB(e,t,n){let r=Ue(e,{scope:t}).filter(a=>!e.isIgnored(a.relativePath)),i=cn(e,r,{limit:500,semanticEvidence:ge}),o=r.filter(a=>!i.incompleteSymbolIds.has(a.symbolId)&&!i.unavailableSymbolIds.has(a.symbolId)).map(a=>BB(a,i.rows.get(a.symbolId)??[])).filter(a=>a.refCount>0).sort((a,c)=>c.refCount-a.refCount||c.fileCount-a.fileCount).slice(0,n),s=i.incompleteSymbolIds.size>0&&i.unavailableSymbolIds.size>0?"incomplete-and-unavailable":i.incompleteSymbolIds.size>0?"incomplete":i.unavailableSymbolIds.size>0?"unavailable":"complete";return{rows:o,coverage:{semanticEvidence:{enabled:!0,status:s,incompleteSymbolCount:i.incompleteSymbolIds.size,unavailableSymbolCount:i.unavailableSymbolIds.size}}}}function BB(e,t){let n=t.filter(r=>r.file!==e.relativePath);return{symbol:e.symbol,shortName:N(e.symbol),refCount:n.length,fileCount:new Set(n.map(r=>r.file)).size,definedIn:e.relativePath,basis:"source-backed-incoming-evidence",countUnit:"distinct-incoming-evidence-rows"}}function $B(e,t,n={}){return JB(e,t,n)?.map(r=>({symbol:r.symbol,shortName:r.shortName,fromFile:r.fromFile}))??[]}function jB(e,t){let n=pe(e,t),r=zB(e,t);if(r.length>0&&!KB(n))return r;let i=qB(e,t,n);return sm(t)&&i.length>0?i:GB([...r,...i])}function HB(e,t,n={}){let r=mt(e,t);if(!r)return[];let i=BC(e,r),o=n.semantic===!1?null:OC(e,r);return(o?UB(o,i):i).filter(a=>!a.used).map(a=>({symbol:a.symbol,shortName:a.shortName,importedIn:a.importer}))}function UB(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 zB(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
165
- FROM mentions m
166
- JOIN chunks c ON m.chunk_id = c.id
167
- JOIN documents d ON c.document_id = d.id
168
- JOIN global_symbols gs ON m.symbol_id = gs.id
169
- WHERE gs.symbol LIKE ?
170
- AND m.role = 2
171
- ORDER BY d.relative_path`,`%${t}%`).filter(r=>!e.isIgnored(r.importer)).map(r=>({symbol:r.symbol,shortName:N(r.symbol),fromFile:r.importer}))}function qB(e,t,n=pe(e,t)){let r=n?.relativePath??null,i=n?Y(n.symbol):t.replace(/\(\)$/,""),o=n?De(n.symbol):!1,s=new Set;for(let c of me(e,{includeIgnored:!1}))for(let l of Ce(e,c))WB(l,c,{targetFile:r,targetLeaf:i,targetIsModule:o,targetPattern:t})&&s.add(c);let a=sm(t)?t.trim():null;return[...s].sort().map(c=>({symbol:a??n?.symbol??i,shortName:a??(n?N(n.symbol):i),fromFile:c}))}function KB(e){return!!(e&&(e.symbol.startsWith("scip-clojure ")||ye(e.relativePath)==="clojure"))}function GB(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 WB(e,t,n){return!e.sourcePath||n.targetFile&&ht(e.sourcePath)!==ht(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&ZB(t)||e.kind==="namespace"&&VB(e,n.targetPattern)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function VB(e,t){let n=t.trim().replace(/\(\)$/,"");return sm(n)?e.importedName===n||e.localName===n:!1}function sm(e){let t=e.trim().replace(/\(\)$/,"");return t.includes(".")&&!t.includes("/")&&!t.includes(":")}function JB(e,t,n={}){let r=mt(e,t);return r?YB(e,r,n)??(n.semantic===!1?null:OC(e,r))??BC(e,r):null}function YB(e,t,n){let i=e.all(`SELECT DISTINCT
172
- gs.symbol,
173
- def_d.relative_path AS from_file,
174
- imp_d.relative_path AS importer,
175
- EXISTS (
176
- SELECT 1
177
- FROM mentions ref_m
178
- JOIN chunks ref_c ON ref_m.chunk_id = ref_c.id
179
- WHERE ref_m.symbol_id = gs.id
180
- AND ref_m.role != 1
181
- AND ref_c.document_id = imp_d.id
182
- ) AS used
183
- FROM mentions m
184
- JOIN chunks c ON m.chunk_id = c.id
185
- JOIN documents imp_d ON c.document_id = imp_d.id
186
- JOIN global_symbols gs ON m.symbol_id = gs.id
187
- LEFT JOIN (
188
- SELECT m2.symbol_id, c2.document_id
189
- FROM mentions m2
190
- JOIN chunks c2 ON m2.chunk_id = c2.id
191
- WHERE m2.role = 1
192
- GROUP BY m2.symbol_id
193
- ) sym_def ON sym_def.symbol_id = gs.id
194
- LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
195
- WHERE imp_d.relative_path = ?
196
- AND m.role = 2
197
- ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(i.length>0){let o=n.semantic===!1?[]:Mo(e,t);return i.map(s=>({symbol:s.symbol,shortName:N(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 OC(e,t){let n=Mo(e,t);return n.length>0?n.map(r=>{let i=$C(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 BC(e,t){let n=XB(t,se(e,t));return Ce(e,t).map(r=>{let i=$C(r.importedName,r.localName,r.kind),o=r.kind==="side-effect"||QB(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 XB(e,t){let n=new Set;if(ye(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 QB(e,t){if(ye(e)!=="rust"||t.used||t.kind==="side-effect")return!1;let n=t.localName??t.importedName;return n==="_"||/^[A-Z]/.test(n)}function $C(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 ZB(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function e$(e,t){let n=pe(e,t);if(!n)return[];let i=new U(e).definitionsForFile(n.relativePath).filter(o=>o.symbol!==n.symbol).filter(o=>mp(n.symbol,o.symbol)).sort((o,s)=>o.startLine-s.startLine||o.endLine-s.endLine).map(o=>({symbol:o.symbol,shortName:N(o.symbol),startLine:o.startLine,endLine:o.endLine,kind:Bt(o.symbol)??"unknown"}));return ye(n.relativePath)!=="clojure"?i:n$(i,t$(e,n))}function t$(e,t){let n=Y(t.symbol);if(!n)return[];let r=N(t.symbol);return(te(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 n$(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 r$(e,t){let n=pe(e,t);if(!n)return[];let r=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
198
- FROM mentions m
199
- JOIN chunks c ON m.chunk_id = c.id
200
- JOIN (
201
- SELECT m2.symbol_id, c2.document_id
202
- FROM mentions m2
203
- JOIN chunks c2 ON m2.chunk_id = c2.id
204
- WHERE m2.role = 1
205
- GROUP BY m2.symbol_id
206
- ) sym_def ON sym_def.symbol_id = m.symbol_id
207
- WHERE m.symbol_id = ?
208
- AND m.role != 1
209
- AND sym_def.document_id != c.document_id`,n.symbolId);return[{name:N(n.symbol),count:r?.file_count??0,symbol:n.symbol,definedIn:n.relativePath}]}function i$(e,t){let n=mt(e,t);return n?e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
210
- FROM mentions m
211
- JOIN chunks c ON m.chunk_id = c.id
212
- JOIN documents d ON c.document_id = d.id
213
- JOIN global_symbols gs ON m.symbol_id = gs.id
214
- JOIN (
215
- SELECT m2.symbol_id, c2.document_id
216
- FROM mentions m2
217
- JOIN chunks c2 ON m2.chunk_id = c2.id
218
- WHERE m2.role = 1
219
- GROUP BY m2.symbol_id
220
- ) sym_def ON sym_def.symbol_id = gs.id
221
- JOIN documents def_d ON sym_def.document_id = def_d.id
222
- WHERE d.relative_path = ?
223
- AND m.role != 1
224
- AND def_d.id != d.id
225
- GROUP BY d.id
226
- ORDER BY symbol_count DESC`,n).filter(o=>!e.isIgnored(o.relative_path)).map(o=>({name:o.relative_path,count:o.symbol_count,file:o.relative_path,basis:"external-symbol-references"})):[]}function o$(e,t={}){return s$(e,t).map(n=>({name:N(n.symbol),count:n.file_count,symbol:n.symbol,definedIn:n.defined_in}))}function s$(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,
227
- COUNT(DISTINCT c.document_id) AS file_count,
228
- def_d.relative_path AS defined_in
229
- FROM mentions m
230
- JOIN chunks c ON m.chunk_id = c.id
231
- JOIN global_symbols gs ON m.symbol_id = gs.id
232
- JOIN (
233
- SELECT m2.symbol_id, c2.document_id
234
- FROM mentions m2
235
- JOIN chunks c2 ON m2.chunk_id = c2.id
236
- WHERE m2.role = 1
237
- GROUP BY m2.symbol_id
238
- ) sym_def ON sym_def.symbol_id = gs.id
239
- JOIN documents def_d ON sym_def.document_id = def_d.id
240
- WHERE m.role != 1
241
- AND def_d.id != c.document_id
242
- ${e.pathExclusionsFor("def_d")}
243
- ${e.symbolNoiseFor("gs")}
244
- ${i}
245
- GROUP BY gs.id
246
- HAVING file_count > 1
247
- ORDER BY file_count DESC
248
- LIMIT ?`,...o,n)}function a$(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
249
- FROM mentions m
250
- JOIN chunks c ON m.chunk_id = c.id
251
- JOIN documents d ON c.document_id = d.id
252
- JOIN global_symbols gs ON m.symbol_id = gs.id
253
- JOIN (
254
- SELECT m2.symbol_id, c2.document_id
255
- FROM mentions m2
256
- JOIN chunks c2 ON m2.chunk_id = c2.id
257
- WHERE m2.role = 1
258
- GROUP BY m2.symbol_id
259
- ) sym_def ON sym_def.symbol_id = gs.id
260
- JOIN documents def_d ON sym_def.document_id = def_d.id
261
- WHERE m.role != 1
262
- AND def_d.id != d.id
263
- ${e.pathExclusionsFor("d")}
264
- ${e.symbolNoiseFor("gs")}
265
- ${i}
266
- GROUP BY d.id
267
- ORDER BY symbol_count DESC
268
- LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}))}var jC=`SELECT COUNT(*) AS shared
269
- FROM (
270
- SELECT definition_m.symbol_id
271
- FROM documents definition_d
272
- JOIN chunks definition_c ON definition_c.document_id = definition_d.id
273
- JOIN mentions definition_m ON definition_m.chunk_id = definition_c.id
274
- AND definition_m.role = 1
275
- JOIN mentions reference_m ON reference_m.symbol_id = definition_m.symbol_id
276
- AND reference_m.role != 1
277
- JOIN chunks reference_c ON reference_c.id = reference_m.chunk_id
278
- JOIN documents reference_d ON reference_d.id = reference_c.document_id
279
- WHERE definition_d.relative_path = ?
280
- AND reference_d.relative_path = ?
281
- UNION
282
- SELECT definition_m.symbol_id
283
- FROM documents definition_d
284
- JOIN chunks definition_c ON definition_c.document_id = definition_d.id
285
- JOIN mentions definition_m ON definition_m.chunk_id = definition_c.id
286
- AND definition_m.role = 1
287
- JOIN mentions reference_m ON reference_m.symbol_id = definition_m.symbol_id
288
- AND reference_m.role != 1
289
- JOIN chunks reference_c ON reference_c.id = reference_m.chunk_id
290
- JOIN documents reference_d ON reference_d.id = reference_c.document_id
291
- WHERE definition_d.relative_path = ?
292
- AND reference_d.relative_path = ?
293
- )`;function c$(e,t,n){let r=mt(e,t)??t,i=mt(e,n)??n,o=e.get(jC,r,i,i,r);return{...HC(r,i,o?.shared??0)}}function l$(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
294
- CASE WHEN def_d.relative_path < ref_d.relative_path THEN def_d.relative_path ELSE ref_d.relative_path END AS file1,
295
- CASE WHEN def_d.relative_path < ref_d.relative_path THEN ref_d.relative_path ELSE def_d.relative_path END AS file2,
296
- COUNT(DISTINCT gs.id) AS shared
297
- FROM mentions m
298
- JOIN chunks c ON m.chunk_id = c.id
299
- JOIN documents ref_d ON c.document_id = ref_d.id
300
- JOIN global_symbols gs ON m.symbol_id = gs.id
301
- JOIN (
302
- SELECT m2.symbol_id, c2.document_id
303
- FROM mentions m2
304
- JOIN chunks c2 ON m2.chunk_id = c2.id
305
- WHERE m2.role = 1
306
- GROUP BY m2.symbol_id
307
- ) sym_def ON sym_def.symbol_id = gs.id
308
- JOIN documents def_d ON sym_def.document_id = def_d.id
309
- WHERE m.role != 1
310
- AND def_d.id != ref_d.id
311
- ${e.pathExclusionsFor("def_d","ref_d")}
312
- ${i}
313
- GROUP BY file1, file2
314
- ORDER BY shared DESC, file1, file2
315
- LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.file1)&&!e.isIgnored(a.file2)).map(a=>HC(a.file1,a.file2,a.shared))}function HC(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 Vr(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 p=d.pendingChild;d.pendingChild=null,i.set(d.node,Math.min(i.get(d.node),i.get(p)))}let m=d.iter.next();if(m.done){if(i.get(d.node)===r.get(d.node)){let p=[];for(;;){let g=s.pop();if(o.delete(g),p.push(g),t.set(g,n.length),g===d.node)break}n.push(p)}u.pop();continue}let f=m.value;r.has(f)?o.has(f)&&i.set(d.node,Math.min(i.get(d.node),r.get(f))):(r.set(f,a),i.set(f,a),a+=1,s.push(f),o.add(f),d.pendingChild=f,u.push({node:f,iter:c(f),pendingChild:null}))}}return{components:n,componentOf:t}}function ts(e,t={}){return qC(e,t).cycles}function qC(e,t={}){return KC(e,t)}function KC(e,t={}){let{scope:n,maxDepth:r=10,edgeBasis:i="symbol-references"}=t,o=$e(e,n,i==="imports"?{scipEdges:"imports-only",sourceEdges:"imports-only"}:void 0),{components:s}=Vr(o),a=s.filter(c=>u$(o,c)).map(c=>{let l=[...c].sort(),u=d$(o,l),d=f$(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 u$(e,t){if(t.length>1)return!0;let n=t[0];return n!==void 0&&e.get(n)?.has(n)===!0}function d$(e,t){let n=t[0];if(!n)return[];let 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=m$(e,i,n,r);if(o)return[n,...o]}throw new Error(`Cyclic component did not contain a witness path from ${n}.`)}function m$(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 f$(e){for(let r of e){let i=J(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":Ri(t)||Ri(n)||UC(t,n)||UC(n,t)||zC(t,n)||zC(n,t)||J(t)==="entry"||J(n)==="entry"?"module-hierarchy":"real"}function UC(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=t.replace(/\.rs$/,"/");return e.startsWith(n)?!e.slice(n.length).includes("/"):!1}function zC(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))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}import{readdirSync as p$}from"fs";import{join as VC}from"path";function WC(e,t){let n=GC(e),r=GC(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 GC(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}function fr(e,t){return WC(e,t)}function g$(e){return JC(e).replace(/\/\*\*?$/,"")}function wc(e,t){let n=JC(t),r=g$(n),i=n.endsWith("/**"),o=[],s=(a,c)=>{let l;try{l=p$(a,{withFileTypes:!0})}catch{return}for(let u of l){if(u.name.startsWith("."))continue;let d=c?`${c}/${u.name}`:u.name;fr(n,d)&&o.push(d),i&&u.isDirectory()&&s(VC(a,u.name),d)}};return s(VC(e,r),r),o.sort()}function JC(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}var h$=/\.(test|spec)\.(ts|tsx|js|jsx|mts|cts)$/,YC=new Map;function XC(e,t,n,r){if(!t?.testPaths?.length)return[];let i=y$(t),o=[];for(let s of b$(e,t.testPaths)){let a=S$(e,s,r),c=a?n(a):null;if(c)for(let l of Ce(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 v$(o)}function y$(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 b$(e,t){let n=`${e.config.projectRoot}\0${t.join("\0")}`,r=YC.get(n);if(r)return r;let i=new Set;for(let s of t)for(let a of wc(e.config.projectRoot,s))h$.test(a)&&i.add(a);let o=[...i].sort();return YC.set(n,o),o}function S$(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=Ce(e,t).map(s=>s.sourcePath).filter(s=>!!s&&n(s)&&s.split("/").pop()===i);return o.length===1?o[0]:null}function v$(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 QC(e,t){let n=(e?.boundaries??[]).filter(r=>r.paths.some(i=>fr(i,t)));return n.length===1?n[0].name:null}var jn="architecture:";function ZC(e,t,n,r={}){let i=x$(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 E=n.boundaries.filter(I=>I.paths.some(v=>fr(v,y))).map(I=>I.name).sort();if(E.length===0)a.push(y);else if(E.length>1)c.push({file:y,boundaries:E});else{let I=E[0];o.set(y,I),s.get(I).add(y)}}let l=new Map;for(let[y,E]of e){let I=o.get(y);if(I)for(let v of E){let x=o.get(v);if(!x||I===x)continue;let C=_i(I,x),L=l.get(C);L||(L={from:I,to:x,fileEdges:[],importers:new Set,importedFiles:new Set},l.set(C,L)),L.fileEdges.push({fromFile:y,toFile:v}),L.importers.add(y),L.importedFiles.add(v)}}let u=[...l.values()].map(y=>R$(y,n)).sort(T$),d=u,m=new Map(d.map(y=>[_i(y.from,y.to),y])),f=new Map(n.boundaries.map(y=>[y.name,new Set]));for(let y of d)f.get(y.from).add(y.to);let p=[];for(let y of d){if(y.from>=y.to)continue;let E=m.get(_i(y.to,y.from));E&&p.push({boundaries:[y.from,y.to],forward:y,reverse:E})}let{components:g}=Vr(f),h=g.filter(y=>y.length>1).map(y=>E$(y,d,n.requireAcyclic===!0)).sort((y,E)=>E.boundaries.length-y.boundaries.length||y.boundaries.join("/").localeCompare(E.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,E)=>y.name.localeCompare(E.name)),edges:u,forbiddenEdges:d.filter(y=>y.policyStatus==="forbidden"),reciprocalPairs:p,cycles:h,staleAllowances:L$(n,d),boundaryLimits:D$(n,d,s),fragileEdges:d.filter(y=>y.fragile),testBoundaryViolations:r.testBoundaryViolations??[],coarseBoundaries:w$(e,s,r.isModuleHierarchyFile,n.requireResolvedBoundaries===!0,y=>n.boundaries.find(E=>E.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 ns(e,t={}){let n=$e(e,t.scope,{scipEdges:"imports-only",sourceEdges:"imports-and-reexports"}),r=me(e,{includeIgnored:!1}).filter(o=>!t.scope||o.includes(t.scope)),i=new Set(r);return ZC(n,r,e.config.architecture,{isModuleHierarchyFile:o=>C$(e,o),testBoundaryViolations:XC(e,e.config.architecture,o=>QC(e.config.architecture,o),o=>i.has(o))})}function C$(e,t){let n=J(t);return n==="test"||n==="entry"?!0:n!=="barrel"?!1:W(e,t).length===0}function am(e){let t=e.forbiddenEdges.map(r=>`${jn}forbidden-edge:${encodeURIComponent(r.from)}:${encodeURIComponent(r.to)}`);if(e.policyCoverage.requiresCompletePolicy)for(let r of e.policyCoverage.missingRows)t.push(`${jn}missing-policy-row:${encodeURIComponent(r)}`);if(e.policyCoverage.requiresCompleteCoverage){for(let r of e.coverage.unmappedFiles)t.push(`${jn}unmapped-file:${encodeURIComponent(r)}`);for(let r of e.coverage.ambiguousFiles)t.push(`${jn}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(`${jn}stale-allowance:${encodeURIComponent(r.from)}:${encodeURIComponent(r.to)}`);for(let r of e.testBoundaryViolations)t.push(`${jn}test-boundary:${encodeURIComponent(r.testFile)}:${encodeURIComponent(r.importedBoundary)}`);for(let r of e.boundaryLimits)t.push(`${jn}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=`${jn}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(`${jn}cycle:${r.boundaries.map(i=>encodeURIComponent(i)).sort().join("|")}`);return[...new Set(t)].sort()}function x$(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 R$(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:I$(t,e.from,e.to),fileEdgeCount:n.length,importerCount:e.importers.size,importedFileCount:e.importedFiles.size,examples:n.slice(0,5),fragile:n.length===1}}function I$(e,t,n){return!e.allowedDependencies||!Object.hasOwn(e.allowedDependencies,t)?"undeclared":e.allowedDependencies[t].includes(n)?"allowed":"forbidden"}function E$(e,t,n){let 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 w$(e,t,n=P$,r=!1,i=()=>"directory"){let o=[];for(let[s,a]of t){let c=i(s)==="file"?p=>p:M$,l=[...a].filter(p=>!n(p));if(l.length<2)continue;let u=new Set(l),d=new Map,m=new Map;for(let p of l)m.set(c(p),new Set);for(let p of l)for(let g of e.get(p)??[]){if(!u.has(g))continue;let h=c(p),b=c(g);if(h===b)continue;let S=_i(h,b),y=d.get(S);y||(y={from:h,to:b,fileEdges:[]},d.set(S,y)),y.fileEdges.push({fromFile:p,toFile:g}),m.get(h).add(b)}let{components:f}=Vr(m);for(let p of f){if(p.length<2)continue;let g=new Set(p),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:[...p].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 L$(e,t){let n=new Set(t.map(s=>_i(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(_i(s,c))||o.push({from:s,to:c});return o.sort((s,a)=>s.from.localeCompare(a.from)||s.to.localeCompare(a.to))}function D$(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 P$(e){let t=J(e);return t==="test"||t==="entry"}function M$(e){let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)}function _i(e,t){return`${e}\0${t}`}function T$(e,t){return e.from.localeCompare(t.from)||e.to.localeCompare(t.to)}function k$(e,t={}){let{limit:n=20,scope:r,minFanIn:i=2,minFanOut:o=2,scanLimit:s}=t,a=new U(e),c=Fe(a.productionCallableDefinitions({scope:r,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s),l=t.semantic!==!1,u=cn(e,c,{limit:500,semantic:l,semanticEvidence:ge}),d=a.calleeEvidenceMap(c,{semantic:l}),m=new Set([...u.incompleteSymbolIds,...d.incompleteSymbolIds]),f=new Set([...u.unavailableSymbolIds,...d.unavailableSymbolIds]);return{rows:c.filter(g=>!m.has(g.symbolId)&&!f.has(g.symbolId)).map(g=>A$(g,u.rows.get(g.symbolId)??[],d.rows.get(g.symbolId)??[])).filter(g=>g.fanIn>=i&&g.fanOut>=o).sort((g,h)=>h.score-g.score||h.fanIn-g.fanIn).slice(0,n),coverage:F$(l,m,f)}}function F$(e,t,n){let r=e?t.size>0&&n.size>0?"incomplete-and-unavailable":t.size>0?"incomplete":n.size>0?"unavailable":"complete":"disabled";return{semanticEvidence:{enabled:e,status:r,incompleteSymbolCount:t.size,unavailableSymbolCount:n.size,excludedSymbolCount:new Set([...t,...n]).size}}}function A$(e,t,n){let r=[...new Set(t.map(d=>d.file))].sort(),i=[...new Set(t.filter(d=>d.source!=="caller-map-inversion"||d.callEvidence==="scip-chunk").map(d=>d.file))].sort(),o=new Map;for(let d of n.slice(0,500)){if(d.file===e.relativePath)continue;let m=`${d.symbol}|${d.file}`;o.has(m)||o.set(m,{symbol:d.symbol,shortName:N(d.symbol),file:d.file,evidenceStrength:d.source==="scip-chunk"?"candidate":"exact",evidenceSource:d.source})}let s=[...o.values()].sort((d,m)=>d.file.localeCompare(m.file)||d.symbol.localeCompare(m.symbol)),a=r.length,c=s.length,l=a*c,u=s.filter(d=>d.evidenceStrength==="candidate").map(d=>d.symbol);return{symbol:e.symbol,shortName:N(e.symbol),fanIn:a,fanOut:c,callerFiles:r,candidateCallerFiles:i,externalCallees:s.map(({symbol:d,shortName:m,file:f})=>({symbol:d,shortName:m,file:f})),externalCalleeEvidence:s,candidateExternalCallees:u,inputBasis:"mixed-static-call-or-reference-evidence",score:l,definedIn:e.relativePath,actionTier:"signal",riskKind:"coordination-hotspot",evidenceReasons:[`${a} incoming file(s) reference this symbol`,`${c} distinct cross-file callee symbol(s) are reached from it`,`centrality score is ${l} (fan-in * fan-out)`,`${i.length} incoming file(s) and ${u.length} outgoing target(s) rely on candidate rather than exact call evidence`],recommendation:"Review ownership, API stability, and caller groups before changing this central symbol; do not refactor solely from graph centrality."}}function rs(e,t={}){let{scope:n,minLoc:r=3,scanLimit:i}=t,o=new U(e),s=t.semantic!==!1,a=0,c=O("isolated.candidates",()=>{let v=Fe(o.productionCallableDefinitions({scope:n,minLoc:r,excludeEntrySurfaces:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:typeof i=="number"&&i>0}),i).filter(x=>!Ni(e,x));return a=v.length,v},()=>({definitions:a})),l=0,u=O("isolated.strict-callees",()=>{let I=o.symbolsWithNonSelfCallees(c,{additive:!1,semantic:!1});return l=I.size,I},()=>({definitions:c.length,symbols:l})),d=c.filter(I=>!u.has(I.symbolId)),m=0,f=O("isolated.scip-callers",()=>{let I=o.crossFileCallerMap(d,{semantic:!1});return m=I.size,I},()=>({definitions:d.length,symbols:m})),p=new Set(f.keys());for(let I of o.frameworkReferencedSymbolIds(d))p.add(I);let g=d.filter(I=>!p.has(I.symbolId));if(s&&g.length>0){let I=Tn(e,g);for(let v of I.callers.keys())p.add(v);for(let v of I.incompleteSymbolIds)p.add(v);for(let v of I.unavailableSymbolIds)p.add(v);for(let v of o.symbolsWithNonSelfCallees(g,{additive:!1,semantic:!0}))u.add(v);g=g.filter(v=>!p.has(v.symbolId)).filter(v=>!u.has(v.symbolId))}let h=0,b=O("isolated.source-fallback-callers",()=>{let I=o.sourceFallbackCallerFiles(g,{skipPath:v=>J(v)==="test"});return h=I.size,I},()=>({definitions:g.length,symbols:h}));for(let I of b.keys())p.add(I);let S=g.filter(I=>!p.has(I.symbolId)),y=0,E=O("isolated.additive-callees",()=>{let I=o.symbolsWithNonSelfCallees(S,{additive:!0,semantic:s});return y=I.size,I},()=>({definitions:S.length,symbols:y}));for(let I of E)u.add(I);return S.filter(I=>!u.has(I.symbolId)).sort((I,v)=>de(v)-de(I)||I.relativePath.localeCompare(v.relativePath)||I.startLine-v.startLine).map(I=>({symbol:I.symbol,shortName:N(I.symbol),relativePath:I.relativePath,startLine:I.startLine,endLine:I.endLine,loc:de(I)}))}import{SymbolInformation_Kind as tt}from"@c4312/scip";var ex=500;function N$(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),r=Og.get(n);if(r!==void 0)return r;for(let[i,o]of ca)if(o.toLowerCase().includes(n))return i;return null}function _$(e,t,n={}){let{scope:r,limit:i=100}=n,o=N$(t);return o===null?[]:B$(e,r).map(a=>({row:a,resolvedKind:nx(a)})).filter(a=>a.resolvedKind===o).slice(0,i).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:N(a.symbol),kind:c,kindName:io(c),relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function O$(e,t={}){let n=$$(e,t.scope);for(let r of j$(e,t.scope)){let i=nx(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:io(r),count:i}))}function B$(e,t){return Ue(e,{scope:t}).map(H$)}function $$(e,t){let n=new Map;for(let r of tx(me(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", "),o=e.all(`SELECT gs.kind AS kind, COUNT(*) AS count
316
- FROM defn_enclosing_ranges der
317
- JOIN global_symbols gs ON der.symbol_id = gs.id
318
- JOIN documents d ON der.document_id = d.id
319
- WHERE gs.kind IS NOT NULL
320
- AND gs.kind != 0
321
- AND gs.symbol NOT LIKE '%#'
322
- AND d.relative_path IN (${i})
323
- GROUP BY gs.kind`,...r);for(let s of o)n.set(s.kind,(n.get(s.kind)??0)+s.count)}return n}function j$(e,t){let n=[];for(let r of tx(me(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", ");n.push(...e.all(`SELECT gs.symbol,
324
- gs.kind,
325
- gs.documentation,
326
- gs.enclosing_symbol,
327
- d.relative_path,
328
- der.start_line,
329
- der.end_line
330
- FROM defn_enclosing_ranges der
331
- JOIN global_symbols gs ON der.symbol_id = gs.id
332
- JOIN documents d ON der.document_id = d.id
333
- WHERE (gs.kind IS NULL OR gs.kind = 0 OR gs.symbol LIKE '%#')
334
- ${e.symbolNoiseFor("gs")}
335
- AND d.relative_path IN (${i})
336
- ORDER BY d.relative_path, der.start_line, der.end_line, gs.symbol`,...r))}return n}function tx(e){let t=[];for(let n=0;n<e.length;n+=ex)t.push(e.slice(n,n+ex));return t}function H$(e){return{symbol:e.symbol,kind:e.kind,documentation:e.documentation,enclosing_symbol:e.enclosingSymbol,relative_path:e.relativePath,start_line:e.startLine,end_line:e.endLine}}function nx(e){return e.kind!==null&&e.kind!==0?U$(e.kind,e.symbol,e.documentation):z$(e.symbol,e.documentation,e.enclosing_symbol)}function U$(e,t,n){let r=(n??"").toLowerCase();if(Bt(t)==="type"){if(r.includes("type "))return tt.TypeAlias;if(r.includes("interface "))return tt.Interface;if(r.includes("struct "))return tt.Struct;if(r.includes("trait "))return tt.Trait;if(r.includes("class "))return tt.Class}return e}function z$(e,t,n){let r=Vn(e);if("kind"in r)return null;let i=r.descriptors,o=i[i.length-2]??null,s=Bt(e),a=(t??"").toLowerCase();return s==="type"?a.includes("type ")?tt.TypeAlias:a.includes("interface ")?tt.Interface:a.includes("struct ")?tt.Struct:a.includes("trait ")?tt.Trait:a.includes("class ")?tt.Class:tt.Class:s==="method"?o?.suffix==="type"?tt.Method:tt.Function:s==="namespace"?tt.Module:s!=="term"?null:a.includes("async def ")||a.includes("def ")?tt.Function:(n?Bt(n):o?.suffix??null)==="type"?tt.Field:tt.Variable}function q$(e,t={}){let{limit:n=10,scope:r,minDepth:i=3,edgeBasis:o="symbol-references"}=t,s=$e(e,r,o==="imports"?{scipEdges:"imports-only",sourceEdges:"imports-only"}:void 0),{components:a,componentOf:c}=Vr(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 E=c.get(y);E!==S&&l.get(S).add(E)}}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((E,I)=>E-I)){let E=d[y];(E>S||E===S&&K$(u[y],b,a)<0)&&(S=E,b=u[y])}u[h]=[h,...b],d[h]=1+S}function m(h){return u[h]}let f=a.map(h=>[...h].sort()),p=new Set,g=[];for(let h=0;h<a.length;h++){let S=m(h).map(I=>f[I]),y=S.map(I=>I[0]);if(S.length<i)continue;let E=y.join(" ");p.has(E)||(p.add(E),g.push(G$(y,S,o)))}return g.sort((h,b)=>b.depth-h.depth||h.chain.join("\0").localeCompare(b.chain.join("\0"))),W$(g).slice(0,n)}function K$(e,t,n){if(t.length===0)return-1;let 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 G$(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 W$(e){let t=[];for(let n of e)t.some(r=>V$(n.chain,r.chain))||t.push(n);return t}function V$(e,t){if(e.length>=t.length)return!1;let n=t.length-e.length;for(let r=0;r<e.length;r++)if(e[r]!==t[n+r])return!1;return!0}function J$(e,t){let n=pe(e,t);if(!n)return[];let r=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
337
- WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:N(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:N(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(i.length>1)return i;let c=Vn(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 p=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:p,shortName:p,depth:m})}return u}function Y$(e,t={}){let r=new U(e).productionCallableDefinitions({scope:t.scope,requireCallableSymbol:!0,includeSuppressed:!0}),i=sx(e,r),o=t.search?.trim().toLocaleLowerCase();return r.map(s=>ax(e,s,i.get(s.symbolId)??[])).filter(s=>s!==null).map(s=>s.result).filter(s=>!o||Z$(s).includes(o)).sort(e1)}function X$(e,t,n={}){let r=at(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:N(r.match.symbol),relativePath:r.match.relativePath,startLine:r.match.startLine},...r.candidates]};let i=new U(e),o=i.definitionsForFile(r.match.relativePath).find(f=>f.symbol===r.match.symbol);if(!o?.isFunctionLike)return{kind:"not-entry",query:t,symbol:r.match.symbol,shortName:N(r.match.symbol),file:r.match.relativePath,reason:"The resolved symbol is not a callable definition."};let s=sx(e,[o]),a=ax(e,o,s.get(o.symbolId)??[]);if(!a)return{kind:"not-entry",query:t,symbol:o.symbol,shortName:N(o.symbol),file:o.relativePath,reason:"The callable is neither an external root nor an uncalled callable on a detected entry surface."};let c=t1(e,i,o),l=new Set(n.expand??[]),u=o1(c,l),d=new Set(u.regions.filter(f=>f.expanded).map(f=>f.id)),m=[...l].filter(f=>!d.has(f)).sort();return{kind:"matched",query:t,entry:a.result,regions:u.regions,regionEdges:u.regionEdges,unmatchedExpansions:m,coverage:{completeWithinIndexedStaticCallEdges:!0,completeWithinSelectedStaticEvidence:!0,candidateReachabilityIncluded:c.edges.some(f=>f.evidenceStrength==="candidate"),dynamicDispatchRepresented:!1,symbolCount:c.symbols.length,symbolEdgeCount:c.edges.length,exactSymbolEdgeCount:c.edges.filter(f=>f.evidenceStrength==="exact").length,candidateSymbolEdgeCount:c.edges.filter(f=>f.evidenceStrength==="candidate").length,regionCount:u.regions.length,regionEdgeCount:u.regionEdges.length,externalCallCount:c.externalCalls.length}}}function sx(e,t){let n=t.filter(r=>cx(e,r.relativePath)||Ii(e,r.symbol,r.relativePath).length>0);return jg(e,n,{semantic:!1,semanticEvidence:ge})}function ax(e,t,n){let r=Q$(e,t),i=r.length>0,o=cx(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:N(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,documentation:t.documentation,confidence:i?"root":"candidate",evidence:s,indexedCallerCount:n.length}}}function cx(e,t){return Qe(e,t)||/(?:^|\/)entry\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(t)}function Q$(e,t){let n=Ii(e,t.symbol,t.relativePath),r=[];return rx(n,["package-surface-file","transitive-package-surface"])&&It(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"),rx(n,["configured-file","configured-path-prefix","configured-qualified-var","configured-symbol-pattern"])&&r.push("configured-entry-root"),r}function rx(e,t){return t.some(n=>e.includes(n))}function Z$(e){return[e.symbol,e.shortName,e.file,e.documentation??"",...e.evidence].join(`
338
- `).toLocaleLowerCase()}function e1(e,t){return ix(e.confidence)-ix(t.confidence)||e.file.localeCompare(t.file)||e.startLine-t.startLine||e.symbol.localeCompare(t.symbol)}function ix(e){return e==="root"?0:1}function t1(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,ox(d,m));for(let f of l.get(d.symbolId)??[]){let p=n1(t,f,o);if(!p){let S=i1(d,f);a.set(c1(S),S);continue}let g=m+1,h=r.get(p.symbol);(h===void 0||g<h)&&r.set(p.symbol,g),i.set(p.symbol,ox(p,Math.min(g,h??g)));let b=r1(d,p,f);s.set(a1(b),b),h===void 0&&u.push(p)}}c=u}return{symbols:[...i.values()].sort(l1),edges:[...s.values()].sort(u1),externalCalls:[...a.values()].sort(d1)}}function n1(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 ox(e,t){return{symbol:e.symbol,shortName:N(e.symbol),file:e.relativePath,depth:t}}function r1(e,t,n){return{fromSymbol:e.symbol,fromShortName:N(e.symbol),fromFile:e.relativePath,toSymbol:t.symbol,toShortName:N(t.symbol),toFile:t.relativePath,source:n.source,evidenceStrength:n.source==="scip-chunk"?"candidate":"exact"}}function i1(e,t){return{fromSymbol:e.symbol,fromShortName:N(e.symbol),fromFile:e.relativePath,toSymbol:t.symbol,toShortName:N(t.symbol),reportedFile:t.file,source:t.source,evidenceStrength:t.source==="scip-chunk"?"candidate":"exact"}}function o1(e,t){let n=is(e.symbols,l=>l.file),r=is(e.edges.filter(l=>l.fromFile===l.toFile),l=>l.fromFile),i=is(e.externalCalls,l=>l.fromFile),o=s1(e.edges.filter(l=>l.fromFile!==l.toFile)),s=is(o,l=>l.toRegionId),a=is(o,l=>l.fromRegionId);return{regions:[...n.entries()].map(([l,u])=>{let d=cm(l),m=t.has(d),f=r.get(l)??[],p=i.get(l)??[];return{id:d,file:l,minDepth:Math.min(...u.map(g=>g.depth)),symbolCount:u.length,internalEdgeCount:f.length,externalCallCount:p.length,incomingRegionIds:os((s.get(d)??[]).map(g=>g.fromRegionId)),outgoingRegionIds:os((a.get(d)??[]).map(g=>g.toRegionId)),expanded:m,symbols:m?u:[],internalEdges:m?f:[],externalCalls:m?p:[]}}).sort((l,u)=>l.minDepth-u.minDepth||l.file.localeCompare(u.file)),regionEdges:o}}function s1(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:cm(r.fromFile),fromFile:r.fromFile,toRegionId:cm(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:os(n.map(i=>i.fromShortName)),toSymbols:os(n.map(i=>i.toShortName)),evidence:os(n.map(i=>i.source))}}).sort((n,r)=>n.fromFile.localeCompare(r.fromFile)||n.toFile.localeCompare(r.toFile))}function is(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 cm(e){return`file:${e}`}function os(e){return[...new Set(e)].sort()}function a1(e){return`${e.fromSymbol}\0${e.toSymbol}`}function c1(e){return`${e.fromSymbol}\0${e.toSymbol}`}function l1(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)||e.symbol.localeCompare(t.symbol)}function u1(e,t){return e.fromFile.localeCompare(t.fromFile)||e.fromSymbol.localeCompare(t.fromSymbol)||e.toSymbol.localeCompare(t.toSymbol)}function d1(e,t){return e.fromFile.localeCompare(t.fromFile)||e.fromSymbol.localeCompare(t.fromSymbol)||e.toSymbol.localeCompare(t.toSymbol)}function Ht(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function nt(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function pr(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 lx(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 lm(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 Oi(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 Bi(e,t){let n=0;for(let r of e){let i=t.get(r)??0;n+=i*i}return Math.sqrt(n)}function ux(e,t,n,r={}){let i=0,o=0,s=0,a=r.medianIdf??Oi(n),c=[],l=[];for(let m of e){let f=n.get(m)??0;o+=f*f,t.has(m)&&(i+=f*f,f>=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 f=n.get(m)??0;s+=f*f}let u=Math.sqrt(o)*Math.sqrt(s),d=u>0?i/u:0;return c.sort((m,f)=>(n.get(f)??0)-(n.get(m)??0)),{similarity:d,significantShared:c,trivialShared:l}}function dx(e,t,n,r){let i=0,o=r.medianIdf??Oi(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 ss(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=()=>M1(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"}),s=v1(e,t,{semantic:n.semantic!==!1});if(s.kind==="not-callable")return[];if(s.kind==="callee-evidence-unusable")return o();let a=s.target;if(!_e(a.symbol))return[];if(a.callees.size===0)return o();let c=f1(e,a,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return c.length>0?c.slice(0,i):o()}function fm(e,t,n,r={}){let i=pe(e,t),o=pe(e,n);if(!i||!o)return null;let s=ss(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:N(i.symbol),file:i.relativePath,loc:a},symbolB:{symbol:o.symbol,shortName:N(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:m1(s)}}function m1(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 f1(e,t,n,r){let i=$i(e).calleeIndex({minCallees:3,scanLimit:r.scanLimit,semantic:r.semantic}),o=D1(t,i.corpus),s=E1(o,i),a=p1(o,i),c=Oi(a),l=Bi(o.callees,a),u=[];for(let d of s){if(d.callees.size<3)continue;let m=Bi(d.callees,a),f=gx(o,d,a,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0,medianIdf:c,magnitudeA:l,magnitudeB:m});f&&u.push(f)}return u.sort((d,m)=>m.similarity-d.similarity),u}function p1(e,t){let n=new Map(t.docFreq);for(let r of e.callees)n.set(r,(n.get(r)??0)+1);return lm(n,t.corpus.length+1)}function gx(e,t,n,r){let i=h1(e,t,n,r);if(!y1(i,r))return null;let{similarity:o,significantShared:s,trivialShared:a}=i,c=s.length>0?s:a,l=vx(c,"callees");return{symbolA:e.symbol,shortNameA:N(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:N(t.symbol),fileB:t.file,similarity:o,similarityBasis:"callees",sharedCallees:c.map(N),uniqueToA:[...nt(e.callees,t.callees)].map(N),uniqueToB:[...nt(t.callees,e.callees)].map(N),...l}}function g1(e,t,n,r){let i=r.magnitudeA??Bi(e.callees,n),o=r.magnitudeB??Bi(t.callees,n),s=0,a=0,c=0,l=r.medianIdf??Oi(n);for(let m of e.callees){if(!t.callees.has(m))continue;let f=n.get(m)??0;s+=f*f,c+=1,f>=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 h1(e,t,n,r){return r.magnitudeA===void 0||r.magnitudeB===void 0?ux(e.callees,t.callees,n,{medianIdf:r.medianIdf}):dx(e.callees,t.callees,n,{medianIdf:r.medianIdf,magnitudeA:r.magnitudeA,magnitudeB:r.magnitudeB})}function y1(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 as(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=Ne(),u=0,d=0,m=0,f=0,p=0,g=0,h=0;return O("similar.all",()=>{let S=$i(e).calleeIndex({minCallees:o,scope:i,scanLimit:a,semantic:c}),y=S.corpus;u=y.length;let E=t.focusFiles,I=[],v=0;return O("similar.all.pair-scan",()=>{for(let x=0;x<y.length;x+=1){let C=y[x],L=E?.has(C.file)??!1,w=S.weightedMagnitudes[x],R=new Set;for(let P of C.callees){let _=S.candidateIndexesByCallee.get(P);if(_)for(let D of _)D<=x||E&&!L&&!E.has(y[D].file)||R.add(D)}l&&(m+=R.size,R.size>0&&(d+=1));for(let P of R){let _=y[P];if(s&&C.file===_.file){l&&(p+=1);continue}if(hx(C,_)){l&&(g+=1);continue}l&&(f+=1);let D=gx(C,_,S.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:S.medianIdf,magnitudeA:w,magnitudeB:S.weightedMagnitudes[P]});D&&(b1(I,D,r,v),l&&(h+=1),v+=1)}}},()=>({corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:f,crossFileSkips:p,signatureSkips:g,insertedResults:h,topResults:I.length})),O("similar.all.sort-project",()=>(I.sort((x,C)=>C.result.similarity-x.result.similarity||x.order-C.order),I.map(x=>x.result)),()=>({topResults:I.length}))},()=>({minSimilarity:n,limit:r,scope:i,minCallees:o,crossFileOnly:s,scanLimit:a,semantic:c,corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:f,crossFileSkips:p,signatureSkips:g,insertedResults:h}))}function pm(e,t={}){let{minSimilarity:n=.5,scope:r,minCallees:i=4,crossFileOnly:o=!1,scanLimit:s}=t,a=t.semantic!==!1,c=Ne(),l=0,u=0,d=0,m=0,f=0,p=0,g=0;return O("similar.all-count",()=>{let b=$i(e).calleeIndex({minCallees:i,scope:r,scanLimit:s,semantic:a}),S=b.corpus;l=S.length;let y=t.focusFiles;return O("similar.all-count.pair-scan",()=>{for(let E=0;E<S.length;E+=1){let I=S[E],v=y?.has(I.file)??!1,x=b.weightedMagnitudes[E],C=new Set;for(let L of I.callees){let w=b.candidateIndexesByCallee.get(L);if(w)for(let R of w)R<=E||y&&!v&&!y.has(S[R].file)||C.add(R)}c&&(d+=C.size,C.size>0&&(u+=1));for(let L of C){let w=S[L];if(o&&I.file===w.file){c&&(f+=1);continue}if(hx(I,w)){c&&(p+=1);continue}c&&(m+=1),g1(I,w,b.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:b.medianIdf,magnitudeA:x,magnitudeB:b.weightedMagnitudes[L]})&&(g+=1)}}},()=>({corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:f,signatureSkips:p,insertedResults:g})),g},()=>({minSimilarity:n,scope:r,minCallees:i,crossFileOnly:o,scanLimit:s,semantic:a,corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:f,signatureSkips:p,insertedResults:g}))}function hx(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=Rt({kind:"source-fingerprints",invalidation:Ye("source-fingerprints"),serialize:J1,deserialize:V1});function b1(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 S1=["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 v1(e,t,n){let r=pe(e,t);if(!r)return{kind:"not-callable"};if(!_e(r.symbol))return{kind:"not-callable"};let i=new U(e),o=Lr(e,r,{semantic:n.semantic,semanticEvidence:ge});return o.semanticIncomplete||o.semanticUnavailable?{kind:"callee-evidence-unusable"}:{kind:"resolved",target:{symbol:r.symbol,file:r.relativePath,callees:Lc(o.rows.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}}var C1=ke("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),x1=ke("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function bx(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:o}=t,s=t.semantic!==!1,a=C1.get(e,()=>new Map),c=`${n}|${r??""}|${o??""}|${s}`,l=!0,u=0,d=0;return O("similar.callee-fingerprints.resolve",()=>{let m=a.get(c);if(l=m!==void 0,m||(m=w1(e,{minCallees:n,scope:r,scanLimit:o,semantic:s}),a.set(c,m)),u=m.length,i===void 0)return m;let f=m.filter(p=>p.symbol!==i);return d=m.length-f.length,f},()=>({minCallees:n,scope:r,scanLimit:o,semantic:s,cacheHit:l,corpusSize:u,excludeSymbol:i!==void 0,excludedSymbols:d}))}function R1(e,t){let{minCallees:n,scope:r,scanLimit:i}=t,o=t.semantic!==!1,s=x1.get(e,()=>new Map),a=`${n}|${r??""}|${i??""}|${o}`,c=!0,l=0,u=0,d=0;return O("similar.callee-index.resolve",()=>{let m=s.get(a);return c=m!==void 0,m||(m=I1(bx(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 $i(e){return{calleeCorpus:t=>bx(e,t),calleeIndex:t=>R1(e,t),sourceCorpus:(t={})=>Ex(e,t),sourceIndex:(t={})=>px(e,t),sourceCandidates:(t,n)=>(n.candidateMode??"full")==="target-pruned"?j1(e,t,{minSimilarity:n.minSimilarity,scanLimit:n.scanLimit}):$1(t,px(e,{scanLimit:n.scanLimit}))}}function I1(e){let t=Ne(),n=0,r=O("similar.callee-index.doc-frequency",()=>{let m=new Map;for(let f of e)for(let p of f.callees)m.set(p,(m.get(p)??0)+1);return n=m.size,m},()=>({corpusSize:e.length,uniqueCallees:n})),i=Math.max(8,Math.ceil(Math.sqrt(e.length))),o=O("similar.callee-index.idf-weights",()=>lm(r,e.length),()=>({corpusSize:e.length,uniqueCallees:r.size})),s=O("similar.callee-index.weighted-magnitudes",()=>e.map(m=>Bi(m.callees,o)),()=>({corpusSize:e.length})),a=0,c=0,l=0,u=O("similar.callee-index.candidate-buckets",()=>{let m=new Map;for(let f=0;f<e.length;f+=1){let p=e[f];for(let g of p.callees){if((r.get(g)??0)>i){t&&(c+=1);continue}let h=m.get(g);h||(h=[],m.set(g,h)),h.push(f),t&&(a+=1)}}return t&&(l=m.size),m},()=>({corpusSize:e.length,buckets:l,candidateRefs:a,ubiquitousSkips:c,ubiquityThreshold:i})),d=O("similar.callee-index.median-idf",()=>Oi(o),()=>({uniqueCallees:o.size}));return{corpus:e,candidateIndexesByCallee:u,docFreq:r,idfWeights:o,weightedMagnitudes:s,medianIdf:d,ubiquityThreshold:i}}function E1(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 w1(e,t){let{minCallees:n,scope:r,scanLimit:i,semantic:o}=t,s=Ne(),a=new U(e),c=0,l=O("similar.callee-fingerprints.candidates",()=>{let g=Fe(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=O("similar.callee-fingerprints.callee-map",()=>{let g=a.calleeEvidenceMap(l,{semantic:o});if(s)for(let h of g.rows.values())u+=h.length;return g},()=>({candidateCount:c,semantic:o,calleeEdges:u})),m=0,f=0,p=0;return O("similar.callee-fingerprints.shape",()=>{let h=l.filter(y=>!d.incompleteSymbolIds.has(y.symbolId)&&!d.unavailableSymbolIds.has(y.symbolId)).map(y=>({symbol:y.symbol,file:y.relativePath,callees:Lc((d.rows.get(y.symbolId)??[]).map(E=>E.symbol)),paramCount:a.callableSignature(y)?.paramCount??-1})),b=L1(h);s&&(p=b.filter((y,E)=>y.callees.size!==h[E].callees.size).length);let S=b.filter(y=>y.callees.size>=n);return m=S.length,s&&(f=S.reduce((y,E)=>y+E.callees.size,0)),S},()=>({candidateCount:c,fingerprintCount:m,retainedCalleeCount:f,minCallees:n,siblingSaturatedFingerprints:p}))}var Sx=5;function L1(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)>=Sx);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 D1(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>=Sx);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 Lc(e){return new Set([...e].filter(t=>!P1(t)))}function P1(e){return S1.some(t=>e.includes(t))}function M1(e,t,n){let r=A1(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 O("similar.source-shape",()=>{let m=$i(e).sourceCandidates(r,{minSimilarity:i,scanLimit:n.scanLimit,candidateMode:s});a=m.length;for(let f of m){if(f.symbol===r.symbol||f.tokens.size<3)continue;c+=1;let p=Ht(r.tokens,f.tokens);if(p.size<2){l+=1;continue}let g=new Set([...r.tokens,...f.tokens]),h=g.size>0?p.size/g.size:0;if(h<i){u+=1;continue}o.push({symbolA:r.symbol,shortNameA:N(r.symbol),fileA:r.file,symbolB:f.symbol,shortNameB:N(f.symbol),fileB:f.file,similarity:h,similarityBasis:"source-tokens",sharedCallees:[...p].sort(),uniqueToA:[...nt(r.tokens,f.tokens)].sort(),uniqueToB:[...nt(f.tokens,r.tokens)].sort(),...vx([...p],"source-tokens")})}return o.sort((f,p)=>p.similarity-f.similarity||f.shortNameB.localeCompare(p.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 vx(e,t){let n=e.flatMap(dm),r=e.flatMap(h=>mx(h,t)),i=um(n,Cx),o=um(n,xx),s=um(r,mm),a=[...new Set(r.filter(fx))],c=e.filter(h=>{let b=mx(h,t);return b.some(S=>mm.has(S))&&b.some(fx)}).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=>Rx.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,f=t==="callees"&&d&&e.length>=4&&a.length>=4&&c>=2,p=f?"domain-behavior":d?m?"mixed":"domain-behavior":i.length>0?"access-query-scaffolding":o.length>0||u?"framework-scaffolding":"structural-overlap";p==="structural-overlap"&&e.length>0&&l.push(`shared ${t} overlap has no recognized domain or scaffolding category`);let g=p==="domain-behavior"&&(e.length>=3||f)?"direct":"signal";return{evidenceClass:p,actionTier:g,evidenceClassReasons:l,recommendation:T1(p,g)}}function T1(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 um(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function dm(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function mx(e,t){if(t==="source-tokens")return dm(e);let n=Y(e);return dm(n.length>0?n:k1(e))}function k1(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 fx(e){return e.length>3&&!mm.has(e)&&!Cx.has(e)&&!xx.has(e)&&!Rx.has(e)&&!F1.has(e)}var mm=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),Cx=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),xx=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"]),Rx=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),F1=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 A1(e,t){let n=pe(e,t);if(!n||!_e(n.symbol))return null;let r=N1(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function N1(e,t){let n=Y(t.symbol),r=K1(e,t.relativePath,t.startLine,t.endLine,n),i=Dx(r,n);return i.size>0?i:null}var _1=ke("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),O1=ke("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function Ix(e){return`${e.scanLimit??""}`}function Ex(e,t={}){let n=_1.get(e,()=>new Map),r=Ix(t),i=n.get(r);return i||(i=q1(e,t),n.set(r,i)),i}function px(e,t={}){let n=O1.get(e,()=>new Map),r=Ix(t),i=n.get(r);return i||(i=B1(Ex(e,t)),n.set(r,i)),i}function B1(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 $1(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 j1(e,t,n){let r=Ne(),i=new U(e),o=H1(t.tokens.size,n.minSimilarity),s=0,a=0,c=0,l=O("similar.source-shape.target-files",()=>{let p=[...t.tokens],g=[];for(let h of me(e,{includeIgnored:!1})){s+=1;let b=se(e,h);b&&(a+=1,U1(b,p,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=O("similar.source-shape.target-definitions",()=>{let p=Fe(i.productionCallableDefinitions({files:l,sortByLocDesc:typeof n.scanLimit=="number"&&n.scanLimit>0}),n.scanLimit);return u=p.length,p},()=>({symbol:t.symbol,candidateFiles:c,scanLimit:n.scanLimit,definitionCount:u})),m=0;return O("similar.source-shape.target-fingerprints",()=>{let p=wx(e,d);return r&&(m=p.length),p},()=>({symbol:t.symbol,definitionCount:u,fingerprintCount:m})).filter(p=>p.symbol!==t.symbol)}function H1(e,t){return Math.max(2,Math.ceil(e*t))}function U1(e,t,n){if(t.length<n)return!1;let r=e.toLowerCase(),i=0;for(let o of t)if(z1(r,o)&&(i+=1,i>=n))return!0;return!1}function z1(e,t){return t==="num"?/\b\d+\b/.test(e):e.includes(t)}function q1(e,t={}){let n=new U(e),{scanLimit:r}=t,i=Fe(n.productionCallableDefinitions({sortByLocDesc:typeof r=="number"&&r>0}),r);return wx(e,i)}function wx(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=se(e,i);if(!s)continue;let a=Nt(e,i,s),c=W1(e,i,a),l=!1,u=null;for(let d of o){let m=G1(d),f=c.get(m),p=f?new Set(f.tokens):null;p||(u??=ie(e,i),p=Dx(Lx(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:[...p].sort()}),l=!0),p.size>0&&r.set(d.symbol,{symbol:d.symbol,file:d.relativePath,tokens:p})}l&&Y1(e,i,a,c)}return t.map(i=>r.get(i.symbol)).filter(i=>!!i)}function K1(e,t,n,r,i){let o=ie(e,t);return o.length===0?"":Lx(o,n,r,i)}function Lx(e,t,n,r){if(n>=t&&n-t<=12)return e.slice(t,n+1).join(`
339
- `);let i=[new RegExp(`\\bdef\\s+${Be(r)}\\b`),new RegExp(`\\bfun\\s+${Be(r)}\\b`),new RegExp(`\\bfn\\s+${Be(r)}\\b`),new RegExp(`\\bfunction\\s+${Be(r)}\\b`),new RegExp(`\\b${Be(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&&Q1(c)||(s=a,c.trim()===""&&a>o+1))break}return e.slice(o,s+1).join(`
340
- `)}return e.slice(t,Math.min(e.length,t+8)).join(`
341
- `)}function G1(e){return`${e.symbol}\0${e.startLine}\0${e.endLine}\0${e.leaf}`}function W1(e,t,n){return yx.read(e,t,n)??new Map}function V1(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 J1(e){let t={entries:[...e.values()].sort((n,r)=>n.key.localeCompare(r.key))};return JSON.stringify(t)}function Y1(e,t,n,r){yx.write(e,t,n,new Map(r))}function Dx(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=X1(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 X1(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 Q1(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function hn(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 yn(e){let t=Px(e.profile?.name),n=()=>{let r=[];t=Px(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 Z1(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 ej(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?O(`pairwise-profile:${e.profile.name}`,n,()=>({...tj(e.profile?.metadata),...t})):n()}function Z1(e,t){if(e.candidateIndex)return Mx(e,t,-1);let n=[];for(let r=0;r<e.profiles.length;r+=1)r!==t&&n.push(r);return n}function ej(e,t){if(e.candidateIndex)return Mx(e,t,t);let n=[];for(let r=t+1;r<e.profiles.length;r+=1)n.push(r);return n}function Mx(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 Px(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 tj(e){return typeof e=="function"?e():e??{}}function nj(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=rj(e,{scope:i,minDeps:s}),l=hn(a,u=>u.deps);return yn({profiles:a,limit:r,filePattern:o,overrunFactor:5,candidateIndex:l,profile:{name:"similar-files"},compare:(u,d)=>oj(u,d,n,c)})}function rj(e,t){let{scope:n,minDeps:r}=t,i=$e(e,n),{universalDeps:o,distinctiveDeps:s}=ij(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 ij(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 oj(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=pr(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 gr(e){let t=[],n=[],r=[];for(let l of e.primitiveGroups)l.values.length!==0&&Tx(l.bucket,n,r).push(`${l.reasonPrefix}: ${l.values.join(", ")}`);for(let l of e.nameGroups)sj(l.names,l.label,e.genericWords,e.stripPrefixes??[],t,Tx(l.fallbackBucket,n,r));let i=t.length>0,o=n.length>0,s=r.length>0,a=i?o||s?"mixed":"domain-behavior":s?"shared-abstraction":"generic-workflow-scaffolding";return{actionTier:a==="domain-behavior"||a==="mixed"?"signal":"support",evidenceClass:a,reasons:[...t,...r,...n].slice(0,6),recommendation:e.recommendation(a)}}function Dc(e,t){if(e.size===0||t.size===0)return 0;let i=Ht(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(pr(e,t),i)}function hr(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 Pc(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 Ee(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function lt(e){return[...e].sort()}function sj(e,t,n,r,i,o){let s=[],a=[];for(let c of e)aj(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 aj(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 Tx(e,t,n){return e==="generic"?t:n}function cs(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=Ot(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=hn(l,d=>d.tokens);return yn({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-component-duplicates"},compare:(d,m)=>cj(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 cj(e,t,n){let r=Ht(e.tokens,t.tokens);if(r.size<6||!lj(r))return null;let i=pr(e.tokens,t.tokens);if(i<n)return null;let o=Ee(r,"component:"),s=Ee(r,"native:"),a=Ee(r,"prop:"),c=Ee(r,"event:"),l=Ee(r,"binding:"),u=uj({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:lt(r),sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:c,sharedBindings:l,evidenceClass:u.evidenceClass,actionTier:u.actionTier,evidenceClassReasons:u.reasons,recommendation:u.recommendation,uniqueToA:lt(nt(e.tokens,t.tokens)).slice(0,25),uniqueToB:lt(nt(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function lj(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 hr([{name:"component",count:t},{name:"shape",count:n}],[{min:{component:1},reason:"shared custom component"},{min:{shape:4},reason:"shared JSX structure"}]).pass}function uj(e){return gr({genericWords:mj,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:dj})}function dj(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 mj=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 ls(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=Ot(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=hn(l,d=>d.tokens);return yn({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-hook-candidates"},compare:(d,m)=>fj(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 fj(e,t,n,r){let i=Ht(e.tokens,t.tokens);if(i.size<r||!hj(i))return null;let o=Dc(e.tokens,t.tokens);if(o<n)return null;let s=Ee(i,"hook:"),a=Ee(i,"react-hook:"),c=Ee(i,"effect:"),l=Ee(i,"state:"),u=Ee(i,"request:"),d=Ee(i,"handler:"),m=Ee(i,"handler-verb:"),f=pj({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:lt(i),sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m,evidenceClass:f.evidenceClass,actionTier:f.actionTier,evidenceClassReasons:f.reasons,recommendation:f.recommendation,uniqueToA:lt(nt(e.tokens,t.tokens)).slice(0,25),uniqueToB:lt(nt(t.tokens,e.tokens)).slice(0,25),reason:yj({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m}),locA:e.profile.loc,locB:t.profile.loc}}function pj(e){return gr({genericWords:bj,stripPrefixes:Sj,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:gj})}function gj(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 hj(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 hr([{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 yj(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 bj=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"]),Sj=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function gm(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 Ot(e).reactProfiles({scope:a,scanLimit:c}).filter(d=>d.kind==="component").filter(d=>!l||d.file.includes(l)||d.name.includes(l)).map(d=>vj(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 vj(e,t){let n=Math.max(80,Math.floor(t.minComponentLines/2)),r=Pc(e,Cj({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=xj(e),c=Rj(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:Ij(c,a),reasons:i,loc:e.loc}}function Cj(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 xj(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=>wj.has(m))>=0,s=n.some(m=>Ej.has(m));if(kx(r)||kx(e.name))return"component";let c=Lj.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 kx(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&Fx.has(t.at(-1))?!0:[...Fx].some(n=>e.endsWith(Dj(n)))}function Rj(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 Ij(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 Ej=new Set(["component","components","panel","panels","partial","partials"]),Fx=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"]),wj=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),Lj=new Set(["page","route","screen"]);function Dj(e){return e.charAt(0).toUpperCase()+e.slice(1)}function us(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=Pj(e,{scope:o,minTokens:r,scanLimit:s}),u=hn(l,d=>d.tokens);return yn({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-component-duplicates"},compare:(d,m)=>Tj(d,m,n),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function Pj(e,t){return Ot(e).vueProfiles({scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:Mj(n)}))}function Mj(e){return e.totalLines}function Tj(e,t,n){let r=Ht(e.tokens,t.tokens);if(r.size<6||!kj(r))return null;let i=pr(e.tokens,t.tokens);if(i<n)return null;let o=Ee(r,"component:"),s=Ee(r,"prop:"),a=Ee(r,"event:"),c=Ee(r,"directive:"),l=Ee(r,"slot:"),u=Ee(r,"id:"),d=Fj({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:lt(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:lt(nt(e.tokens,t.tokens)).slice(0,25),uniqueToB:lt(nt(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function kj(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 hr([{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 Fj(e){return gr({genericWords:Nj,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:Aj})}function Aj(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 Nj=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 ds(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=Ot(e).vueProfiles({scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(d=>({file:d.file,tokens:d.behaviorTokens,profile:d})),u=hn(l,d=>d.tokens);return yn({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-composable-candidates"},compare:(d,m)=>_j(d,m,n,r),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function _j(e,t,n,r){let i=Ht(e.tokens,t.tokens);if(i.size<r||!$j(i))return null;let o=Dc(e.tokens,t.tokens);if(o<n)return null;let s=Ee(i,"composable:"),a=Ee(i,"store:"),c=Ee(i,"reactivity:"),l=Ee(i,"lifecycle:"),u=Ee(i,"request:"),d=Ee(i,"function:"),m=Ee(i,"function-verb:"),f=Ee(i,"template-binding:"),p=Ee(i,"template-event:"),g=Oj({sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f,sharedTemplateEvents:p});return{fileA:e.file,fileB:t.file,similarity:o,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:lt(i),sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f,sharedTemplateEvents:p,evidenceClass:g.evidenceClass,actionTier:g.actionTier,evidenceClassReasons:g.reasons,recommendation:g.recommendation,uniqueToA:lt(nt(e.tokens,t.tokens)).slice(0,25),uniqueToB:lt(nt(t.tokens,e.tokens)).slice(0,25),reason:jj({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:l,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function Oj(e){return gr({genericWords:Hj,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:Bj})}function Bj(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 $j(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 hr([{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 jj(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 Hj=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 hm(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 Ot(e).vueProfiles({scope:a,scanLimit:c}).filter(d=>!l||d.file.includes(l)).map(d=>Uj(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 Uj(e,t){let n=Pc(e,zj(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=qj(e.file),a=Kj(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:Gj(a,s),reasons:r,loc:c}}function zj(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 qj(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(r=>Wj.has(r))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function Kj(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 Gj(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 Wj=new Set(["landing","page","pages","route","routes","view","views"]);function Vj(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:o=3,maxChainLength:s=8}=t,a=$e(e,i),c=nH(a,o,s);if(c.length===0)return[];let l=Jj(c);return l.length<2?[]:tH(Qj(l,n,r),r)}function Jj(e){let t=Yj(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 Yj(e){let{nodeFreq:t,tailFreq:n}=Xj(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 Xj(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 Qj(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let o=i+1;o<e.length;o++){let s=Zj(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 Zj(e,t,n){if(!eH(e.filtered,t.filtered))return null;let{distance:r,ops:i}=rH(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:iH(e.original,t.original),commonSuffix:oH(e.original,t.original)}}function eH(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function tH(e,t){let n=[];for(let r of e)if(n.some(o=>Ax(r.chainA,o.chainA)&&Ax(r.chainB,o.chainB))||n.push(r),n.length>=t)break;return n}function nH(e,t,n){let r=[];for(let o of e.keys()){if(r.length>=500)break;Nx(e,o,[o],new Set([o]),t,n,r,500)}return r}function Nx(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),Nx(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 rH(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 iH(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 oH(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 Ax(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),r=e.join("\u2192");return n.includes(r)}function Ut(e){let t=sH(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=Fe(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?O(`candidate-pipeline:${e.profile.name}`,n,()=>({...aH(e.profile?.metadata),...t})):n()}function sH(e){return{pipeline:e,loadedCandidates:0,filteredCandidates:0,scannedCandidates:0,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:!1,resultLimitApplied:!1}}function aH(e){return typeof e=="function"?e():e??{}}function ms(e,t={}){let{scope:n,minLoc:r=10,minCallees:i=6,limit:o=20,scanLimit:s}=t,a=new U(e);return Ut({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:r,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:s,profile:{name:"extract-candidates"},prepare:c=>a.calleeEvidenceMap(c,{semantic:t.semantic!==!1}),evaluate:(c,l)=>l.incompleteSymbolIds.has(c.symbolId)||l.unavailableSymbolIds.has(c.symbolId)?null:cH(c,l.rows.get(c.symbolId)??[],i),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function cH(e,t,n){let r=new Set(t.map(l=>l.symbol));if(r.size<n)return null;let i=fH(r,t),o=pH(r,i);if(o.length<2)return null;let s=gH(o,i);if(s.length===0)return null;let a=N(e.symbol),c=lH(a,r.size,o.length,s);return{symbol:e.symbol,shortName:a,relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:de(e),totalCallees:r.size,extractionKind:c.extractionKind,actionTier:"signal",evidenceReasons:c.evidenceReasons,recommendation:c.recommendation,clusters:s}}function lH(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=uH(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 uH(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=dH(e);return mH.has(r)?`caller verb suggests orchestration: ${r}`:null}function dH(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 mH=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function fH(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 pH(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 gH(e,t){return e.filter(n=>n.size>=3).map(n=>hH(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function hH(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(N),isolation:s}}import{posix as ji}from"path";import{spawnSync as yH}from"child_process";import{createHash as bH}from"crypto";import{existsSync as SH}from"fs";import{dirname as _x,join as vH}from"path";import{fileURLToPath as CH}from"url";var $x=Gn("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]}),Ox=Rt({kind:"consumer-file-usage",invalidation:Ye("consumer-file-usage"),serialize:TH,deserialize:kH});function bn(e,t){return{forDefinitions(n,r){return xH(e,t,n,r)}}}function yr(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 Tc(e,t,n){return Hx(e,t,n).partition}function xH(e,t,n,r){let i=jx(n.length),o=Ne()?In(e):null,s=o?RH(n,r,o):void 0,a=s?{workIdentity:s,workOutcome:"computed"}:{};return O("consumer-evidence.product",()=>{let c=O("consumer-evidence.provenance",()=>IH(e,t,n,r),()=>({...a,definitions:n.length,semantic:r.semantic,sourceFallback:r.sourceFallback!==!1})),l=new Map;i={...i,...c.counters};let u=EH(n,c.sources);return O("consumer-evidence.classify",()=>{let d=wH(e,n,c.sources,u);for(let m of n){let f=d.get(m.symbolId)??DH();i.realFiles+=f.partition.realConsumers.length,i.reexportOnlyFiles+=f.partition.barrelConsumers,i.importOnlyFiles+=f.partition.importOnlyConsumers,l.set(m.symbolId,{definition:m,files:f.files,semanticIncomplete:c.incompleteSymbolIds.has(m.symbolId),semanticUnavailable:c.unavailableSymbolIds.has(m.symbolId),...f.partition})}},()=>({...a,...u,realFiles:i.realFiles,reexportOnlyFiles:i.reexportOnlyFiles,importOnlyFiles:i.importOnlyFiles})),l},()=>({...a,...i}))}function RH(e,t,n){let r=bH("sha256").update("consumer-evidence-v3-calibrated-semantic\0").update(n).update("\0").update(t.semantic?"semantic\0":"indexed\0").update(t.sourceFallback===!1?"no-source-fallback":"source-fallback");for(let i of e.map(o=>o.symbol).sort())r.update("\0").update(i);return r.digest("hex").slice(0,24)}function jx(e){return{definitions:e,indexedFiles:0,semanticFiles:0,fallbackFiles:0,totalFiles:0,realFiles:0,reexportOnlyFiles:0,importOnlyFiles:0}}function IH(e,t,n,r){let i=jx(n.length),o=new Map,s=new Set,a=new Set;if(ym(o,i,"indexed",t.crossFileCallerMap(n,{semantic:!1})),r.semantic){let c=Tn(e,n);ym(o,i,"semantic",c.callers);for(let l of c.incompleteSymbolIds)s.add(l);for(let l of c.unavailableSymbolIds)a.add(l)}return r.sourceFallback!==!1&&ym(o,i,"source-fallback",t.sourceFallbackCallerFiles(n)),i.totalFiles=[...o.values()].reduce((c,l)=>c+l.size,0),{sources:o,counters:i,incompleteSymbolIds:s,unavailableSymbolIds:a}}function EH(e,t){return{definitions:e.length,consumerFiles:[...t.values()].reduce((n,r)=>n+r.size,0),nativeAttempted:!1,nativeUsed:!1,nativeReason:"not-attempted"}}function ym(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 wH(e,t,n,r){let i=$H(e,t,n,r);return i||LH(e,t,n)}function LH(e,t,n){let r=new Map;for(let i of t){let o=n.get(i.symbolId)??new Map;r.set(i.symbolId,Hx(e,i,[...o.keys()],o))}return r}function Hx(e,t,n,r=new Map){let i=[],o=0,s=0,a=Y(t.symbol),c=[];for(let l of n){let u;FH(e,l,t.relativePath,a)?(o++,u="reexport-only"):bm(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 DH(){return{partition:{realConsumers:[],barrelConsumers:0,importOnlyConsumers:0},files:[]}}function bm(e,t,n){if(!n)return!1;let r=ye(t);if(!r)return!1;let i=$x.get(e,t,()=>Ux(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function Ux(e,t,n){let r=Wn(e).forFile(t,{text:!0,ast:!0}),i=r.text;if(!i)return MH();let o=Nt(e,t,i),s=Ox.read(e,t,o);if(s)return s;let a=PH(r.ast,n);return Ox.write(e,t,o,a),a}function PH(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=(s,a)=>{let c=a||i.has(s.type);(s.type==="identifier"||s.type==="type_identifier"||s.type==="property_identifier"||s.type==="field_identifier")&&(c?n.add(s.text):r.add(s.text));for(let l of s.children)o(l,c)};return o(e.rootNode,!1),{importedLeaves:n,usedLeaves:r}}function MH(){return{importedLeaves:new Set,usedLeaves:new Set}}function TH(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function kH(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 FH(e,t,n,r){if(!r)return!1;let i=Wn(e).forFile(t,{lines:!0,reexports:!0}),o=i.lines??[];if(o.length===0)return!1;let s=i.reexports??[];return zx(o,s,r)}function zx(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 AH="CODEBASEIQ_NATIVE_CONSUMER_CLASSIFY",NH="CODEBASEIQ_NATIVE_KERNELS_BIN",_H="CODEBASEIQ_NATIVE_CONSUMER_CLASSIFY_MIN_FILES",Bx=1e3,OH=5e3,BH=64*1024*1024,Mc;function $H(e,t,n,r){let i=process.env[AH]?.toLowerCase();if(i!=="1"&&i!=="true")return r.nativeReason=i==="0"||i==="false"?"disabled":"opt-in-required",null;if(r.consumerFiles<GH())return r.nativeReason="below-threshold",null;let o=WH();if(!o)return r.nativeReason="binary-missing",null;r.nativeAttempted=!0;let s=jH(e,t,n),a=yH(o,["consumer-classify"],{input:JSON.stringify(s),encoding:"utf8",timeout:OH,maxBuffer:BH,windowsHide:!0});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=UH(c,t);return l?(r.nativeUsed=!0,r.nativeReason="used",l):(r.nativeReason="invalid-response",null)}catch{return r.nativeReason="invalid-json",null}}function jH(e,t,n){let r=new Map,i=[];for(let a of t){let c=Y(a.symbol),u=[...(n.get(a.symbolId)??new Map).entries()].map(([d,m])=>{let f=r.get(d)??new Set;return c&&f.add(c),r.set(d,f),{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=ye(a);if(l){let d=$x.get(e,a,()=>Ux(e,a,l));o[a]={imported_leaves:[...d.importedLeaves],used_leaves:[...d.usedLeaves]}}let u=HH(e,a,c);u.length>0&&(s[a]=u)}return{definitions:i,file_usages:o,reexport_only_leaves:s}}function HH(e,t,n){if(n.size===0)return[];let r=Wn(e).forFile(t,{lines:!0,reexports:!0}),i=r.lines??[],o=r.reexports??[];return i.length===0||o.length===0?[]:[...n].filter(s=>zx(i,o,s))}function UH(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=zH(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 zH(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(qH)||!KH(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 qH(e){return e==="indexed"||e==="semantic"||e==="source-fallback"}function KH(e){return e==="real"||e==="reexport-only"||e==="import-only"}function GH(){let e=process.env[_H];if(!e)return Bx;let t=Number(e);return Number.isFinite(t)&&t>=0?t:Bx}function WH(){if(Mc!==void 0)return Mc;let e=process.env[NH],t=process.platform==="win32"?"codebaseiq-kernels.exe":"codebaseiq-kernels";return Mc=[...e?[e]:[],...VH().map(r=>vH(r,"target","release",t))].find(r=>SH(r))??null,Mc}function VH(){let e=new Set,t=_x(CH(import.meta.url));for(let n=0;n<5;n++)e.add(t),t=_x(t);return[...e]}var JH=20,YH=1,XH=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"]]),QH=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),ZH=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 eU(e,t={}){let n=Cm(t.limit,JH),r=Cm(t.minConsumers,YH),i=new U(e),o=i.fileDependencyGraph(t.scope),s=vU(me(e,{includeIgnored:!1})),a=RU(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?tU(e,i,t.target):nU(e,t.scope,t.scanLimit)).map(u=>rU(e,i,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=r||t.target).sort(SU).slice(0,n)}function tU(e,t,n){let r=sU(e,n);if(r)return[Vx(r)];let i=pe(e,n);if(!i)return[];let o=t.definitionsForFile(i.relativePath).find(s=>s.symbolId===i.symbolId);return o?[aU(o)]:[{unit:{kind:"symbol",file:i.relativePath,shortName:N(i.symbol),symbol:i.symbol,startLine:i.startLine,endLine:i.endLine}}]}function nU(e,t,n){let r=me(e,{scope:t,includeIgnored:!1}),i=Cm(n,r.length);return r.slice(0,i).map(o=>Vx(o))}function rU(e,t,n,r,i,o,s){let a=r.definition?iU(e,t,r.definition,i.semantic):null,c=a?.files??oU(n,r.unit.file),l=r.definition?a.coverage==="complete"?c.length>0?"exact":"none":a.coverage:c.length>0?"file-level":"none",u=l==="incomplete"||l==="unavailable"||l==="incomplete-and-unavailable",d=r.unit.file,m=Xt(ji.dirname(d)),f=lU(c),p=cU(m),g=Rm([...qx(m),...f?qx(f):[]]),h=u?"repository-level-review":uU(r.unit,m,f,c),b=u?{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:`Compiler-resolved consumer evidence is ${l}; no relocation destination is safe to score.`}:dU(h,r.unit,m,f,c,o,s),S=hU(r.unit,l,f,c,m,b.whyNoSuggestedHome),y=yU(r.unit,m,f,c,b.suggestedHome,b.whyNoSuggestedHome);return{actionTier:"signal",sourceUnit:r.unit,candidatePath:d,currentDirectory:m,directoryAncestry:p,consumerFiles:c,consumerCoverage:l,nearestCommonOwner:f,boundaryMarkers:g,recommendedTier:h,suggestedHome:b.suggestedHome,destinationConfidence:b.confidence,whyNoSuggestedHome:b.whyNoSuggestedHome,counterevidence:u?[...S,"Known consumer files are retained, but missing compiler evidence can hide additional owners."]:S,reasons:y,recommendation:u?"Retain the current location until compiler-resolved consumer evidence is complete.":bU(h,b.suggestedHome,l)}}function iU(e,t,n,r){let i=bn(e,t).forDefinitions([n],{semantic:r!==!1,sourceFallback:!0}).get(n.symbolId),o=i?.semanticIncomplete?i.semanticUnavailable?"incomplete-and-unavailable":"incomplete":i?.semanticUnavailable?"unavailable":"complete";return{files:Zx(i?.files.map(s=>s.file)??[]),coverage:o}}function oU(e,t){let n=[];for(let[r,i]of e.entries())r!==t&&i.has(t)&&n.push(r);return Zx(n)}function sU(e,t){let n=Ds(t),r=me(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 aU(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:N(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function Vx(e){return{unit:{kind:"file",file:e,shortName:ji.basename(e)}}}function cU(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:xm(i)})}return t}function qx(e){return e==="."?[]:Jx(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function xm(e){return Rm(Jx(e).map(({marker:t})=>t))}function Jx(e){let t=e.split("/").filter(Boolean),n=[];for(let r=0;r<t.length;r+=1){let i=XH.get(t[r]);i&&n.push({marker:i,prefix:t.slice(0,r+1).join("/")})}return n}function lU(e){if(e.length===0)return null;let t=e.map(r=>Xt(ji.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 uU(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":Gx(n,"package")?"package-level-shared":Gx(n,"app")?"app-level-shared":Wx(n,["feature","domain","module"])||Wx(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function dU(e,t,n,r,i,o,s){let a=mU(e,r);if(a)return br(a);let c=CU(t.file),l=fU(e,n,c,i,s);if(l)return l;let u=r;if(Xt(n)===Xt(u))return br(`${n} is already the nearest common owner for its consumers.`);let d=pU(u,n,c,s);return d||gU(u,n,c,o,s)}function mU(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 fU(e,t,n,r,i){if(e==="same-file"){let o=r[0]??null;return o?Sm(o):br("No same-file consumer path was available.")}if(e==="sibling-folder"&&r.length===1){let o=Xt(ji.dirname(r[0])),s=Qx(t,n,o,i);return s?br(s):Sm(o)}return null}function pU(e,t,n,r){return EU(e)?Yx(e,t,n,r,`Nearest shared owner ${e} is outside source root ${n}.`):null}function gU(e,t,n,r,i){if(e===".")return br("The nearest common owner is the repository root.");let o=`${e}/shared`,s=Yx(o,t,n,i,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||r.has(o)?s:br(`${o} does not exist in the indexed project.`)}function Yx(e,t,n,r,i){if(!Xx(e,n))return br(i);let o=Qx(t,n,e,r);return o?br(o):Sm(e)}function Sm(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function br(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function hU(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 yU(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 bU(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 SU(e,t){return Kx(t)-Kx(e)||e.candidatePath.localeCompare(t.candidatePath)}function Kx(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 vU(e){let t=new Set(["."]);for(let n of e){let r=Xt(ji.dirname(n));for(;!t.has(r)&&(t.add(r),r!==".");)r=Xt(ji.dirname(r))}return t}function CU(e){let t=vm(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function Xx(e,t){let n=Xt(e),r=Xt(t);return r==="."||n===r||n.startsWith(`${r}/`)}function xU(e,t,n){let r=vm(e),i=vm(t);return(Xx(e,t)?r.slice(i.length):r).some(s=>n.has(s.toLowerCase()))}function Qx(e,t,n,r){return Xt(e)===Xt(n)||!xU(e,t,r)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function RU(...e){let t=new Set(ZH);for(let n of e)for(let r of n??[]){let i=IU(r);i&&t.add(i)}return t}function IU(e){let t=e.trim().toLowerCase();return t===""?null:t}function Gx(e,t){return xm(e).includes(t)}function Wx(e,t){let n=xm(e);return t.some(r=>n.includes(r))}function EU(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?QH.has(n):!1}function Xt(e){let t=Ds(e);return t===""?".":t}function vm(e){let t=Ds(e);return t==="."?[]:t.split("/").filter(Boolean)}function Cm(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function Zx(e){return Rm([...e]).sort((t,n)=>t.localeCompare(n))}function Rm(e){return[...new Set(e)]}function Im(e,t,n={}){return wU(e,t,n)}function wU(e,t,n){let{maxDepth:r=5,scope:i}=n,o=r===Number.MAX_SAFE_INTEGER,s=o?null:500,a=pe(e,t);if(!a)return{rows:[],coverage:{status:"incomplete",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:r,reachedDepth:0,perSymbolEvidenceLimit:s,remainingFrontierSymbols:0,reasons:["The requested symbol could not be resolved."],semanticEvidence:"incomplete"}};let c=[],l=new Set([a.symbolId]),u=new Set,d=[a],m=0,f=!1,p=!1,g=!1;for(let S=1;S<=r&&d.length!==0;S++){m=S;let y=[],E=cn(e,d,{...o?{}:{limit:s+1},semanticEvidence:ge});E.incompleteSymbolIds.size>0&&(p=!0),E.unavailableSymbolIds.size>0&&(g=!0);for(let I of d){let v=E.rows.get(I.symbolId)??[];s!==null&&v.length>s&&(f=!0);let x=s===null?v:v.slice(0,s);for(let C of LU(e,I,i,x)){let L=`${C.file}|${C.shortName}`;if(C.symbolId!==null){if(l.has(C.symbolId))continue;l.add(C.symbolId)}else if(u.has(L))continue;u.add(L),c.push({symbol:C.symbol,shortName:C.shortName,file:C.file,depth:S}),C.symbolId!==null&&C.symbolMatch&&y.push(C.symbolMatch)}}d=y}c.sort((S,y)=>S.depth-y.depth||S.file.localeCompare(y.file));let h=d.length>0,b=[];return h&&b.push(`${d.length} symbol(s) remain eligible beyond depth ${r}.`),f&&b.push(`At least one symbol had more than ${s} incoming evidence row(s).`),p&&b.push("Compiler-resolved incoming evidence was incomplete for at least one traversed symbol."),g&&b.push("Compiler-resolved incoming evidence was unavailable for at least one traversed symbol."),b.length===0&&b.push("The discovered reverse evidence frontier was exhausted."),{rows:c,coverage:{status:p||g?"incomplete":h||f?"bounded":"accounted",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:r,reachedDepth:m,perSymbolEvidenceLimit:s,remainingFrontierSymbols:d.length,reasons:b,semanticEvidence:p&&g?"incomplete-and-unavailable":p?"incomplete":g?"unavailable":"complete"}}}function LU(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 DU(e,t,n)){if(o.has(u))continue;let d=W(e,u),m=d.length>0?Ke(d,d[0].startLine):null;s.push({symbol:m?.symbol??u,file:u})}let a=[...i,...s],c=[],l=new Set;for(let u of a){let d=Er(e,u.symbol);if(!d){let f=`${u.file}|${u.symbol}`;if(l.has(f))continue;l.add(f),c.push({symbolId:null,symbol:u.symbol,shortName:N(u.symbol),file:u.file,symbolMatch:null});continue}if(d.symbolId===t.symbolId||e.isIgnored(d.relativePath)||!PU(d))continue;let m=`${d.symbolId}|${d.relativePath}`;l.has(m)||(l.add(m),c.push({symbolId:d.symbolId,symbol:d.symbol,shortName:N(d.symbol),file:d.relativePath,symbolMatch:d}))}return c}function DU(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
342
- FROM mentions m
343
- JOIN chunks c ON m.chunk_id = c.id
344
- JOIN documents consumer_d ON consumer_d.id = c.document_id
345
- WHERE m.symbol_id = ?
346
- AND m.role != 1
347
- AND c.document_id != ?
348
- ${e.pathExclusionsFor("consumer_d")}
349
- ${r}`,...i).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function PU(e){if(e.symbol.startsWith("scip-clojure ")||ye(e.relativePath)==="clojure")return!0;let t=Bt(e.symbol);return t==="method"||t==="type"||e.symbol.endsWith("().")}function tR(e,t){let n=ht(t),r=[],i="complete",o=J(n);o==="entry"&&Hn(r,"operational-root","structural entrypoint path"),o==="worker"&&Hn(r,"operational-root","worker launch convention"),id(n)&&Hn(r,"operational-root","framework-discovered entrypoint"),MU(e,n)&&Hn(r,"operational-root","configured entry root");let s=!1;try{s=Fn(e,n),s&&Hn(r,"published-api","package manifest export");for(let a of ab(e,n))Hn(r,"operational-root",a)}catch(a){i="partial",Hn(r,"metadata-unavailable",`package metadata unavailable: ${eR(a)}`)}try{let a=it(e.config.projectRoot,n,{maxBytes:8388608,inputKind:"change-surface source"});TU(a)&&Hn(r,"operational-root","module contains a direct-execution process guard")}catch(a){i="partial",Hn(r,"metadata-unavailable",ot(a)?"indexed source file is unavailable on disk":`source metadata unavailable: ${eR(a)}`)}return{operationalRoot:r.some(a=>a.kind==="operational-root"),publishedApi:s,coverage:i,reasons:r}}function MU(e,t){let n=e.config.entryRoots;return n?n.files?.some(r=>ht(r)===t)?!0:n.pathPrefixes?.some(r=>t.startsWith(ht(r)))??!1:!1}function TU(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 Hn(e,t,n){e.some(r=>r.kind===t&&r.detail===n)||e.push({kind:t,detail:n})}function eR(e){return e instanceof Error?e.message:String(e)}function Em(e,t,n={}){let r=mt(e,t);if(!r)return null;let i=FU(e,r);if(!i||e.isIgnored(i.relative_path))return null;let o=[],s=0,a=!0,c=AU(e,i.relative_path),l=tR(e,i.relative_path),u=n.semantic===!1?{callers:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set}:Tn(e,c);for(let d of c){let m=NU(e,i,d,u.callers.get(d.symbolId)??new Set);s+=m;let f=kU(n.semantic!==!1,d.symbolId,u),p=f==="complete"||f==="disabled";p||(a=!1);let g=p?m:null,h=g===null?void 0:_U(g),b=[...l.reasons,...m>0?[{kind:"external-consumers",detail:`${m} known external consumer${m===1?"":"s"}`}]:[],...p?[]:[{kind:"semantic-consumer-coverage",detail:`compiler-resolved consumer evidence is ${f}`}]];o.push({symbol:d.symbol,shortName:N(d.symbol),startLine:d.startLine,endLine:d.endLine,externalConsumers:g,knownExternalConsumers:m,consumerCoverage:f,externalConsumerRiskLevel:h,riskLevel:OU(h,l,!p),riskReasons:b})}return{file:i.relative_path,symbols:o,totalExternalConsumers:a?s:null,knownTotalExternalConsumers:s,fileRisk:l}}function kU(e,t,n){if(!e)return"disabled";let r=n.incompleteSymbolIds.has(t),i=n.unavailableSymbolIds.has(t);return r&&i?"incomplete-and-unavailable":r?"incomplete":i?"unavailable":"complete"}function FU(e,t){return e.get(`SELECT id, relative_path FROM documents
350
- WHERE relative_path = ?
351
- ${e.pathExclusionsFor("documents")}
352
- LIMIT 1`,t)??null}function AU(e,t){return new U(e).definitionsForFile(t).sort((n,r)=>n.startLine-r.startLine||n.endLine-r.endLine)}function NU(e,t,n,r){let i=e.all(`SELECT DISTINCT consumer_d.relative_path
353
- FROM mentions m
354
- JOIN chunks c ON m.chunk_id = c.id
355
- JOIN documents consumer_d ON consumer_d.id = c.document_id
356
- WHERE m.symbol_id = ?
357
- AND m.role != 1
358
- 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 _U(e){return e>10?"high":e>0?"medium":"low"}function OU(e,t,n){return e==="high"?"high":n||e==="medium"||t.operationalRoot||t.publishedApi||t.coverage==="partial"?"medium":"low"}function BU(e,t={}){let{scope:n,minLoc:r=1,maxDepth:i=5,scanLimit:o}=t,s=new U(e),a=$U(e,n,r,o),c=new wm;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 E of h.get(y.symbolId)??[])m.has(E.symbol)||b.add(E.symbol);let S=[];for(let y of b){m.add(y);let E=rR(e,y);if(!E||e.isIgnored(E.relativePath)||Qe(e,E.relativePath)||qe(e,E.symbol,E.relativePath)||s.fileKind(E.relativePath)==="test"||s.hasSuppressionComment(E))continue;let I=HU(e,E,c);I.removable?S.push(jU(E,"cascade")):I.blockingFiles.length>0&&u.push({shortName:N(E.symbol),file:E.relativePath,blockingFiles:I.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 f=l.reduce((g,h)=>g+h.loc,0),p=l.reduce((g,h)=>g+h.entries.length,0);return{batches:l,totalSymbols:p,totalLoc:f,blocked:u}}function $U(e,t,n,r){let i=Wr(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:r,semantic:!1}),o=[];for(let s of i.symbols)s.kind==="dead-code"&&(Qe(e,s.relativePath)||qe(e,s.symbol,s.relativePath)||o.push({symbol:s.symbol,shortName:s.shortName,file:s.relativePath,startLine:s.startLine,endLine:s.endLine,loc:s.loc,evidence:"graph-fact",definition:rR(e,s.symbol)}));return o}function jU(e,t){return{symbol:e.symbol,shortName:N(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function rR(e,t){let n=e.get(`SELECT d.relative_path
359
- FROM global_symbols gs
360
- JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
361
- JOIN documents d ON d.id = der.document_id
362
- WHERE gs.symbol = ?
363
- LIMIT 1`,t);return n?W(e,n.relative_path).find(r=>r.symbol===t)??null:null}function HU(e,t,n){let r=Zi(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=W(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 wm=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 Hi}from"child_process";import{existsSync as UU}from"fs";import{basename as iR}from"path";function kc(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 Tm="Unable to compute git diff.",zU={semanticConsumers:Ky,sourceFallbackConsumers:ko},km={resolveCommit:ll,readBatch({projectRoot:e,resolvedBase:t,relativePaths:n}){let r=n.map(i=>`${t}:./${i}
364
- `).join("");return Hi("git",["cat-file","--batch"],{cwd:e,input:r,maxBuffer:256*1024*1024,timeout:1e4,stdio:["pipe","pipe","ignore"],windowsHide:!0})}};function Fc(e,t={}){let n=t.plan??Ui(e,t);return n.note?qU(n.note,n.changedFileLines):n.changedFiles.length===0?KU(n.changedFileLines):Ac(n.changedFiles,[cR(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function Ui(e,t={}){let{base:n="HEAD"}=t;try{let r=ll(e.config.projectRoot,n),i=GU(e.config.projectRoot,r),o=i.changedFileLines,s=QU(e,o),a=ZU(e,i.changedRanges);return{changedFileLines:o,changedFiles:s,changedRanges:a,renamedFiles:JU(e.config.projectRoot,r,s,i),note:o.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:Tm}}}function cR(e,t,n,r=[],i={}){let o=i.evidenceRuntime??zU,s=new U(e),a=new Set(n),c=kc(r),l=[],u=new Map,d=t.flatMap(C=>s.definitionsForFile(C)).filter(gz),m=d.filter(C=>tz(C,c)),f=rz(e,d,m,c),p=sz([...m,...f.definitions]).sort((C,L)=>C.relativePath.localeCompare(L.relativePath)||C.startLine-L.startLine),g=p.map(C=>C.symbolId),h=mz(e,g),b=fz(e,g,n),S=p.filter(C=>(h.get(C.symbolId)??0)===0),y=aR("semantic-consumers",S.length,()=>o.semanticConsumers(e,S)),E=y.values,I=S.filter(C=>(E.get(C.symbolId)?.size??0)===0),v=aR("source-fallback-consumers",I.length,()=>o.sourceFallbackConsumers(e,I)),x=v.values;for(let C of p)lz(e,C,a,l,u,E.get(C.symbolId)??new Set,x.get(C.symbolId)??new Set,h.get(C.symbolId)??0,b.get(C.symbolId)??new Set);return{changedSymbols:l,consumerEntries:[...u.entries()].map(([C,L])=>({file:C,symbols:[...L].sort()})),attributionNotes:f.notes,evidenceTiers:[y.status,v.status]}}function Ac(e,t){let n=new Map,r=t.flatMap(a=>a.changedSymbols),i=t.flatMap(a=>a.attributionNotes??[]),o=uz(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=pz(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:s,attributionNotes:i,evidenceTiers:o,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:s.length}}}function qU(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:gR(),summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function KU(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:gR(),summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function GU(e,t){let n=Hi("git",["diff","--name-status","--find-renames",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864,windowsHide:!0}),r=Hi("git",["diff","--name-status","--find-renames","--cached",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024,windowsHide:!0}),i=Hi("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024,windowsHide:!0}),o=Hi("git",["diff","--unified=0",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024,windowsHide:!0}),s=Hi("git",["diff","--unified=0","--cached",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024,windowsHide:!0}),a=YU([n,r]);return{changedFileLines:[...new Set([...a.changedFiles,...dR(i)])],changedRanges:fR([...sR(o),...sR(s)]),renamedFiles:a.renamedFiles,deletedFiles:a.deletedFiles}}function WU(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=Fm(i);if(s.state==="unavailable")throw new Error(`Base content unavailable for ${o}: ${s.reason}`);return s.state==="present"?s.content:null}function Fm(e,t=km){return uR(e.relativePath),Am({projectRoot:e.projectRoot,base:e.base,relativePaths:[e.relativePath]},t).get(e.relativePath)??{state:"unavailable",reason:`Base-content lookup omitted ${e.relativePath}.`}}function Am(e,t=km){for(let s of e.relativePaths)uR(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 Lm(n,Dm(s))}let i;try{i=t.readBatch({projectRoot:e.projectRoot,resolvedBase:r,relativePaths:n})}catch(s){return Lm(n,Dm(s))}let o;try{o=VU(i,n)}catch(s){return Lm(n,`Malformed git cat-file batch output: ${Dm(s)}`)}return new Map(n.map(s=>{let a=o.get(s)??null;return[s,a===null?{state:"absent"}:{state:"present",content:a}]}))}function Nm(e,t=km){let n=Am({projectRoot:e.projectRoot,base:e.base,relativePaths:e.preloadPaths??[]},t);return r=>(n.has(r)||n.set(r,Fm({projectRoot:e.projectRoot,base:e.base,relativePath:r},t)),n.get(r)??{state:"unavailable",reason:`Base-content reader omitted ${r}.`})}function lR(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 uR(e){Rn(e)}function Lm(e,t){return new Map(e.map(n=>[n,{state:"unavailable",reason:t}]))}function Dm(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 VU(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 JU(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)||!UU(`${e}/${a}`))continue;let c=s.filter(d=>!o.has(d)).filter(d=>iR(d)===iR(a));if(c.length===0)continue;let l=it(e,a),u=c.map(d=>({from:d,to:a,similarity:XU(WU({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 YU(e){let t=new Set,n=new Map,r=new Set;for(let i of e.flatMap(o=>dR(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 XU(e,t){let n=new Set(oR(e)),r=new Set(oR(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 oR(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function dR(e){return e.split(`
365
- `).map(t=>t.trim()).filter(t=>t.length>0)}function QU(e,t){let n=mR(e),r=[];for(let i of t){let o=n(i);o&&!e.isIgnored(o)&&r.push(o)}return r}function ZU(e,t){let n=mR(e),r=[];for(let i of t){let o=n(i.file);o&&!e.isIgnored(o)&&r.push({...i,file:o})}return fR(r)}function mR(e){let n=e.all(`SELECT relative_path FROM documents
366
- ORDER BY id`).map(i=>i.relative_path).map(i=>({path:i,normalized:Rn(i)})),r=new Map;for(let i of n){let o=r.get(i.normalized);r.set(i.normalized,o===void 0||o===i.path?i.path:null)}return i=>{let o=Rn(i),s=r.get(o);if(s)return s;let a=n.filter(c=>c.normalized.endsWith(o));return a.length===1?a[0].path:null}}function sR(e){let t=[],n=null;for(let r of e.split(`
367
- `)){if(r.startsWith("+++ ")){n=ez(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 ez(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function fR(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 tz(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(r=>_m(e.startLine,e.endLine,r.startLine,r.endLine))}function nz(e,t,n){let r=new Map,i=[],o=pR(e),s=az(n);for(let a of t){let c=o.get(a.file)??[];if(c.some(d=>_m(d.startLine,d.endLine,a.startLine,a.endLine)))continue;let l=s.get(a.file)??[],u=cz(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(Pm(a,"ast-widened"));continue}}if(l.length===0){let d=[...c].filter(m=>m.startLine<=a.startLine).sort((m,f)=>f.startLine-m.startLine||m.endLine-f.endLine)[0];if(d){r.set(d.symbolId,d),i.push(Pm(a,"nearest-preceding"));continue}}i.push(Pm(a,"unattributed"))}return{definitions:[...r.values()],notes:i}}function rz(e,t,n,r){let i=pR(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=>_m(m.startLine,m.endLine,d.startLine,d.endLine))||o.push(d);o.some(d=>d.file===c)&&s.push(...iz(e,c))}return nz(t,o,s)}function iz(e,t){let n=ae(e,t);return n?n.rootNode.namedChildren.filter(oz).map(r=>({file:t,startLine:r.startPosition.row,endLine:r.endPosition.row})).filter(r=>r.endLine>=r.startLine):[]}function oz(e){return e.endPosition.row<e.startPosition.row?!1:!new Set(["import_statement","comment"]).has(e.type)}function sz(e){let t=new Map;for(let n of e)t.set(n.symbolId,n);return[...t.values()]}function pR(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 az(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 cz(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 Pm(e,t){return{file:e.file,startLine:e.startLine,endLine:e.endLine,method:t}}function _m(e,t,n,r){return e<=r&&n<=t}function lz(e,t,n,r,i,o,s,a,c){let l=Math.max(a,o.size,s.size);if(!hz(t,l))return;let u=N(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)Mm(e,n,i,d,u);for(let d of o)Mm(e,n,i,d,u);for(let d of s)Mm(e,n,i,d,u)}function aR(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:dz(r)}}}}function uz(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 gR(){return[{tier:"semantic-consumers",state:"complete",attemptedSymbols:0},{tier:"source-fallback-consumers",state:"complete",attemptedSymbols:0}]}function dz(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 mz(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
368
- FROM mentions m
369
- JOIN chunks c ON m.chunk_id = c.id
370
- WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
371
- AND m.role != 1
372
- GROUP BY m.symbol_id`,...t);return new Map(n.map(r=>[r.symbol_id,r.fan_in]))}function fz(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
373
- FROM mentions m
374
- JOIN chunks c ON m.chunk_id = c.id
375
- JOIN documents ref_d ON c.document_id = ref_d.id
376
- WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
377
- AND m.role != 1
378
- AND ref_d.relative_path NOT IN (${n.map(()=>"?").join(",")})
379
- ${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 Mm(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 pz(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function gz(e){return!(De(e.symbol)||e.parentTypeName!==null&&!st(e.symbol))}function hz(e,t){return st(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}var yz=5;function bz(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??Ui(e,{base:n}),d={available:u.note!==Tm,base:n,changedFiles:u.changedFiles,helpersChecked:0,skipped:[],findings:[],...u.note?{note:u.note}:{}};if(!d.available||u.changedFiles.length===0)return d;let m=new U(e),f=new Set(u.changedFiles),p=new Map(u.renamedFiles.map(x=>[x.to,x.from]));if(t.baseContentAt&&t.baseContentResultAt)throw new Error("Specify only one of baseContentAt or baseContentResultAt.");let g=t.baseContentResultAt?t.baseContentResultAt:t.baseContentAt?Ez(t.baseContentAt):Nm({projectRoot:e.config.projectRoot,base:n,preloadPaths:lR(u)}),h=Iz(m,f,p,g);if(h.unavailable)return d.available=!1,d.note=`Base content unavailable: ${h.unavailable.reason}`,d;if(h.definitions.length===0)return d;let b=h.definitions.slice(0,s);h.definitions.length>s&&(d.note=`helper scoring capped at ${s} of ${h.definitions.length} new symbols`);let S=m.calleeEvidenceMap(b,{semantic:l}),y=b.filter(x=>!S.incompleteSymbolIds.has(x.symbolId)&&!S.unavailableSymbolIds.has(x.symbolId)).map(x=>({def:x,callees:Lc((S.rows.get(x.symbolId)??[]).map(C=>C.symbol))}));for(let x of b)!S.incompleteSymbolIds.has(x.symbolId)&&!S.unavailableSymbolIds.has(x.symbolId)||d.skipped.push({helperShortName:N(x.symbol),helperFile:x.relativePath,reason:"compiler-resolved callee evidence is incomplete or unavailable \u2014 unsafe to score"});let E=$i(e),I,v=()=>(I??=E.calleeIndex({minCallees:Math.min(3,i),scanLimit:c,semantic:l}),I);for(let{def:x,callees:C}of y){let L=N(x.symbol);if(C.size<i){d.skipped.push({helperShortName:L,helperFile:x.relativePath,reason:`fewer than ${i} meaningful callees \u2014 too small to score`});continue}let w=v(),R=Rz(C,w);if(R===0){d.skipped.push({helperShortName:L,helperFile:x.relativePath,reason:"helper callee pattern is all project-wide infrastructure \u2014 too generic to score"});continue}let P=wz(e,x.symbolId);if(P.length===0){d.skipped.push({helperShortName:L,helperFile:x.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}d.helpersChecked+=1;let _=Sz({candidateIndex:w,changed:f,helperCallees:C,helperFile:x.relativePath,helperSymbol:x.symbol,minContainment:r,minSiteCoverage:o,migratedFiles:P});_.length!==0&&(_.sort((D,M)=>hR(M.migrationScope)-hR(D.migrationScope)||M.containment-D.containment||M.siteCoverage-D.siteCoverage||D.file.localeCompare(M.file)),d.findings.push({helperSymbol:x.symbol,helperShortName:L,helperFile:x.relativePath,helperShape:"specific-callee-cluster",helperCalleeCount:C.size,specificHelperCalleeCount:R,migratedFiles:P.sort(),leftovers:_.slice(0,yz)}))}return d.findings.sort((x,C)=>(C.leftovers[0]?.containment??0)-(x.leftovers[0]?.containment??0)||x.helperFile.localeCompare(C.helperFile)),d.findings=d.findings.slice(0,a),d}function Sz(e){let t=[],n=vz(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=lx(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=Cz(n,o.symbol,o.file);t.push({symbol:o.symbol,shortName:N(o.symbol),file:o.file,...l,containment:s,siteCoverage:c,uniqueSiteCalleeCount:Math.max(0,o.callees.size-a.length),sharedCallees:a.map(N).sort()})}return t}function hR(e){return e==="same-scope"?2:e==="unknown"?1:0}function vz(e,t,n){let r=new Set([...Om(t),...Bm(Y(e))]);for(let i of n)for(let o of Om(i))r.add(o);return r}function Cz(e,t,n){let r=new Set([...Om(n),...Bm(Y(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 xz=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 Om(e){return Bm(e.replace(/\.[^.]+$/,""))}function Bm(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!xz.has(t))}function Rz(e,t){let n=0;for(let r of e)(t.docFreq.get(r)??0)<=t.ubiquityThreshold&&(n+=1);return n}function Iz(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${Be(o.leaf)}\\b`).test(a.content))&&i.push(o)}return{definitions:i}}function Ez(e){return t=>{let n=e(t);return n===null?{state:"absent"}:{state:"present",content:n}}}function wz(e,t){return e.all(`SELECT DISTINCT ref_d.relative_path
380
- FROM mentions m
381
- JOIN chunks c ON m.chunk_id = c.id
382
- JOIN documents ref_d ON c.document_id = ref_d.id
383
- WHERE m.symbol_id = ?
384
- AND m.role != 1
385
- ${e.pathExclusionsFor("ref_d")}`,t).map(r=>r.relative_path)}import{execFileSync as Lz}from"child_process";var CR=2e3,Nc=50,Dz=64,Pz=8,Mz=3,Tz=2160*60*60,kz=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,Fz=3,Az=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,Nz=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function _z(e){let t=ke(e,{clearGroups:["whole-project"]});return(n,r,i)=>{let o=i??$m(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 _c(e){let t=ke(e,{clearGroups:["whole-project"]});return(n,r,i,o)=>{let s=o??$m(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 Oz=_c("git-commit-history");function Qt(e,t={}){let n=t.historyMode??"bounded",r=t.head;return{capability:i=>Bz(e,i,r),commitHistory:()=>fs(e,n,r),fileChurn:()=>Hz(e,n,r),changeAmplification:()=>Uz(e,n,r),trackedFiles:()=>qz(e,r),fileAddRecords:()=>Gz(e,n,r),coChangePairs:(i={})=>Zz(e,i,n,r),coChangePairsForFiles:(i,o={})=>IR(e,i,o,n,r),directionalCoChangePairsForFiles:(i,o={})=>eq(e,i,o,n,r)}}function fs(e,t="bounded",n){return Oz(e,zi(t),(r,i)=>$z(r,i,t),n)}function Bz(e,t,n){let r=n??$m(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 $m(e){try{return Sn(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function Sn(e,t){return Lz("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:3e4,killSignal:"SIGKILL"})}function $z(e,t,n){let r;try{r=Sn(e,["log","--no-merges","--name-only",...Oc(n),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}return{head:t,...Um(r,Nc)}}function jz(e){return kz.test(e.subject)}function Hz(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=jz(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 Uz(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:yR(i,.5),p90FilesPerCommit:yR(i,.9),commitsAnalyzed:i.length}}function yR(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var zz=_z("git-tracked-files");function qz(e,t){return zz(e,n=>{try{let r=Sn(n,["ls-files"]);return new Set(r.split(`
386
- `).map(i=>i.trim()).filter(i=>i!==""))}catch{return null}},t)}var Kz=_c("git-file-adds"),bR="__git__/file-adds",SR=Rt({kind:"git-file-adds",invalidation:Ye("git-file-adds"),serialize:Vz,deserialize:Jz});function xR(e){return Qt(e).fileAddRecords()}function Gz(e,t,n){let r=zi(t);return Kz(e,r,(i,o)=>Wz(e,i,o,t),n)}function Wz(e,t,n,r){let i=SR.read(e,vR(r),n);if(i)return i;let o=Yz(t,r);return o&&SR.write(e,vR(r),n,o),o}function Vz(e){return JSON.stringify([...e.entries()])}function Jz(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 Yz(e,t){let n;try{n=Sn(e,["log","--no-merges","--find-renames","--name-status",...Oc(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(`
387
- `),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(`
388
- `)){let m=Xz(d);if(!m)continue;if(m.status==="R"&&m.from&&m.to){let p=i.get(m.to)??new Set([m.to]);i.set(m.from,p);continue}if(m.status!=="A"||!m.to)continue;let f={commitsAgo:o,addedAt:u};r.set(m.to,f);for(let p of i.get(m.to)??[])r.set(p,f)}}return r}function Xz(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 RR=_c("git-co-change-pairs"),Qz=_c("git-directional-co-change-pairs");function Zz(e,t,n,r){let i=`all\0${zi(n)}\0${jm(t)}`,o=RR(e,i,()=>{let s=fs(e,n,r);return s?Hm(s,t):null},r);return o&&[...o]}function IR(e,t,n,r,i){if(t.size===0)return[];let o=`files\0${zi(r)}\0${ER(t)}\0${jm(n)}`,s=RR(e,o,()=>{let a=fs(e,r,i);return a?Hm(a,n,t):null},i);return s&&[...s]}function eq(e,t,n,r,i){if(t.size===0)return[];let o=n.maxFilesPerCommit??Nc;if(t.size>Dz)return IR(e,t,n,r,i);let s=`directional\0${zi(r)}\0${ER(t)}\0${jm({...n,maxFilesPerCommit:o})}`,a=Qz(e,s,(c,l)=>{let u=tq(c,l,t,o,r);return u?Hm(u,n,t):null},i);return a&&[...a]}function jm(e){let t=e.minTogether??4,n=e.minConfidence??.6,r=e.maxFilesPerCommit??Nc;return`${t}\0${n}\0${r}`}function ER(e){return[...e].sort().join("\0")}function Hm(e,t,n){let{minTogether:r=4,minConfidence:i=.6,maxFilesPerCommit:o=Nc}=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 f=iq(m),p=n===void 0||m.some(g=>n.has(g));for(let g of m)s.set(g,(s.get(g)??0)+1);if(p)for(let g=0;g<m.length;g++)for(let h=g+1;h<m.length;h++){if(n&&!n.has(m[g])&&!n.has(m[h]))continue;let b=`${m[g]}\0${m[h]}`,S=a.get(b)??{together:0,focusedTogether:0,broadTogether:0,lastTogetherAt:0,timestamps:[],subjects:[]};S.together+=1,f?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-Tz;for(let[d,m]of a){let f=m.together;if(f<r)continue;let[p,g]=d.split("\0"),h=s.get(p)??f,b=s.get(g)??f,S=Math.max(f/h,f/b);if(S<i)continue;let y=m.broadTogether/f,E=m.timestamps.filter(I=>I>=u).length;l.push({fileA:p,fileB:g,together:f,confidence:S,changesA:h,changesB:b,focusedTogether:m.focusedTogether,broadTogether:m.broadTogether,broadCommitRatio:y,lastTogetherAt:m.lastTogetherAt,recentTogether:E,commitScope:sq(m.broadTogether,f),recency:E>0?"recent":"stale",subjectContext:aq(m.subjects)})}return l.sort((d,m)=>m.together-d.together||m.confidence-d.confidence||d.fileA.localeCompare(m.fileA)),l}function tq(e,t,n,r,i){let o;try{o=nq(e,i)}catch{return null}if(o.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:0};let s;try{s=Sn(e,["log","--no-merges","--format=%H",...Oc(i),"--",...[...n].sort()])}catch{return null}let a=new Set(o.map(m=>m.hash)),c=s.split(`
389
- `).map(m=>m.trim()).filter(m=>m!==""&&a.has(m)),l=rq(e,o,r);if(c.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:l};let u;try{u=Sn(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...c])}catch{return null}let d=Um(u,r);return{head:t,...d,newestAnalyzedAt:l}}function nq(e,t){return Sn(e,["log","--no-merges","--format=%H%x00%ct",...Oc(t)]).split(`
390
- `).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 Oc(e){return e==="full"?[]:["-n",String(wR())]}function wR(){return ir(process.env.CODEBASEIQ_GIT_HISTORY_MAX_COMMITS)??CR}function zi(e){return e==="full"?"full":`bounded:${wR()}`}function vR(e){let t=zi(e);return t===`bounded:${CR}`?bR:`${bR}:${t}`}function rq(e,t,n){for(let i=0;i<t.length;i+=20){let o=t.slice(i,i+20),s;try{s=Sn(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...o.map(c=>c.hash)])}catch{return t[0]?.timestamp??0}let a=Um(s,n);if(a.commits.length>0)return a.commits[0].timestamp}return 0}function Um(e,t){let n=[],r=0;for(let i of e.split("")){if(i.trim()==="")continue;let o=i.indexOf(`
391
- `),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(`
392
- `).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 iq(e){return e.length>=Pz?!0:oq(e).size>=Mz}function oq(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 sq(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function aq(e){let t=new Set,n=[],r=[];for(let i of e){!r.includes(i)&&r.length<Fz&&r.push(i);for(let o of cq(i))t.add(o);for(let o of i.match(Az)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:r,externalIssueLabelStatus:"unavailable"}}function cq(e){let t=new Set,n=Nz.exec(e)?.[1]?.toLowerCase();return n&&t.add(lq(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 lq(e){return e==="feat"?"feature":e}var LR=/(?:^|\/)(?: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 ps(e,t,n={}){let{minTogether:r=4,minConfidence:i=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=Qt(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=$e(e),f=kR(e),p=mq(e,m,f),g=n.includeLinked===!0||l,h=[];for(let b of d){if(LR.test(b.fileA)||LR.test(b.fileB)||!DR(e,b.fileA)||!DR(e,b.fileB)||l&&!b.fileA.includes(t)&&!b.fileB.includes(t)||!l&&(J(b.fileA)==="test"||J(b.fileB)==="test"||hq(b.fileA,b.fileB)||pq(b.fileA,b.fileB)))continue;let S=p(b.fileA,b.fileB);if(!g&&S)continue;let y=uq(b.fileA,b.fileB),E=dq(b,y,S);if(h.push({...b,structurallyLinked:S,partnerClass:y.partnerClass,partnerClassReasons:y.reasons,...E?{declaredCouplingSuggestion:E}:{}}),h.length>=o)break}return{available:!0,commitsAnalyzed:c.commits.length,findings:h}}function DR(e,t){return At(e.config.projectRoot,t)}function uq(e,t){let n=MR(e),r=MR(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=Lq(n.tokens,r.tokens).filter(c=>!Eq.has(c));return TR(e,t)||a.length>=2?(o(TR(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 dq(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!Iq.has(t.partnerClass))return;let r=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${Dq(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 mq(e,t=$e(e),n=kR(e)){return(r,i)=>yq(t,n,r,i)}var fq=/(?:^|\/)(?:locales|i18n)\//i;function PR(e){return fq.test(e)}function pq(e,t){return PR(e)&&PR(t)?!0:gq(e,t)}function gq(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 hq(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 kR(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function yq(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 bq=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,Sq=/(?:^|\/)(?:\.[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,vq=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,Cq=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,xq=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,Rq=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,Iq=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),Eq=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 MR(e){let t=e.replace(/\\/g,"/"),n=new Set;return bq.test(t)&&n.add("doc"),Sq.test(t)&&n.add("config"),vq.test(t)&&n.add("schema"),Cq.test(t)&&n.add("script"),xq.test(t)&&n.add("model"),Rq.test(t)&&n.add("view"),J(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:wq(t)}}function TR(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 wq(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 Lq(e,t){let n=new Set(t);return[...new Set(e.filter(r=>n.has(r)))].sort()}function Dq(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}function jc(e,t){let n=Pq(e,t)??Mq(e,t)??Tq(e,t)??kq(e,t);return Fq(e,n,t)}function Pq(e,t){let n=-1,r=null;for(let i=0;i<=t;i+=1){let o=zm(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(zm(e[i]??"")===r)return{start:n,end:i+1};return{start:n,end:e.length}}function zm(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function Mq(e,t){if(!Bc(e[t]??""))return null;let n=t;for(;n>0&&Bc(e[n-1]??"");)n-=1;let r=t+1;for(;r<e.length&&Bc(e[r]??"");)r+=1;return{start:n,end:r}}function Bc(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function Tq(e,t){let n=t;for(;n>=0;){let o=e[n]??"";if($c(o)!==null)break;if(qm(o)!==null)return null;n-=1}if(n<0)return null;let r=$c(e[n]??"");if(r===null)return null;let i=n+1;for(;i<e.length;){let o=e[i]??"",s=$c(o);if(s!==null){if(s<=r)break;i+=1;continue}if(qm(o)!==null)break;i+=1}return{start:n,end:i}}function $c(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function kq(e,t){let n=e[t]??"";if(AR(n)||n.trim().length===0)return{start:t,end:t+1};let r=t;for(;r>0&&FR(e[r-1]??"");)r-=1;let i=t+1;for(;i<e.length&&FR(e[i]??"");)i+=1;return{start:r,end:i}}function FR(e){return qm(e)===null}function qm(e){return e.trim().length===0?"blank":AR(e)?"heading":zm(e)?"fence":Bc(e)?"table":$c(e)!==null?"list":null}function AR(e){return/^#{1,6}\s+/.test(e.trim())}function Fq(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(`
393
- `).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}function Jr(e,t){return t.filter(n=>e.includes(n))}var Aq=/<!--\s*codebaseiq:\s*snapshot\s*-->/i;function NR(e,t){if((e.config.docs?.snapshotPaths??[]).some(i=>fr(i,t)))return!0;let r=se(e,t);return r.length>0&&Aq.test(r)}var _R={classifyCitation:_q,citationContexts:Oq,citationKindLabel:$q,citationRemediation:jq,referenceTargets:Hq,hasLineAnchoredCitation:Nq};function Nq(e){return e.some(t=>(t.lineReferences?.length??0)>0)}function _q(e){let t=e.join(`
394
- `).toLowerCase(),n=[],r=Jr(t,[".codebaseiq","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 Oq(e,t,n){let r=se(e,t);if(!r&&!At(e.config.projectRoot,t))return[];let i=r.split(/\r?\n/),o=n.flatMap(Bq),s=[];for(let a=0;a<i.length;a+=1){let c=i[a]??"";o.some(l=>c.includes(l))&&s.push(jc(i,a))}return s}function Bq(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 $q(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 jq(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 Hq(e,t,n){let r=kc(n),i=new Set;for(let o of t)Uq(e,o,r.get(o)??[])&&i.add(o);return i}function Uq(e,t,n){if(!zq.test(t)||!At(e.config.projectRoot,t))return!0;if(n.length===0)return!1;let r=it(e.config.projectRoot,t,{inputKind:"changed source file"}).split(/\r?\n/),i=qq(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 zq=/\.(?:[cm]?[jt]sx?)$/i;function qq(e){let t=new Set,n=!1;for(let r=0;r<e.length;r+=1){let i=e[r].trim();!n&&Kq(i)&&(n=!0),n&&(t.add(r),i.endsWith(";")&&(n=!1))}return t}function Kq(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}var OR=Rt({kind:"doc-path-evidence",invalidation:Ye("doc-path-evidence"),serialize:oK,deserialize:sK}),gs=/\.(?:md|mdx|rst|txt)$/i;function Gq(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var Wq=3,Vq=/([A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6})(?::([1-9][0-9]*))?\b/g;function Jq(e,t={}){let{doc:n,limit:r=20,minCoupling:i=Wq,includeSnapshotExcluded:o=!1}=t,s=Zq(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&&!eK(e,c)||n!==void 0&&!At(e.config.projectRoot,c))continue;let l=NR(e,c);if(l&&!o)continue;let{value:u,estimated:d}=Yq(e,c,s.changeTimes.get(c)),m=Xq(e,c),f=new Map,{resolved:p,broken:g,citations:h}=nK(e,c,s.tracked,s.trackedBySuffix,s.everSeenInHistory),b=new Map(h.map(y=>[y.file,y]));for(let y of p){if(y===c||gs.test(y))continue;let E=(s.changeTimes.get(y)??[]).filter(v=>v>u).length;if(E===0)continue;let I=b.get(y);f.set(y,{file:y,evidence:"reference",coChanges:0,changesSinceDocUpdate:E,...Km("reference",m,I?.contexts),citationContexts:I?.contexts,citedLines:I?.lineReferences})}for(let[y,E]of s.coupling.get(c)??[]){if(E<i||!s.tracked.has(y))continue;let I=(s.changeTimes.get(y)??[]).filter(x=>x>u).length;if(I===0)continue;let v=f.get(y);v?(v.evidence="both",v.coChanges=E,Object.assign(v,Km("both",m,v.citationContexts))):f.set(y,{file:y,evidence:"co-change",coChanges:E,changesSinceDocUpdate:I,...Km("co-change",m)})}if(f.size===0&&g.length===0)continue;let S=[...f.values()].sort((y,E)=>E.changesSinceDocUpdate-y.changesSinceDocUpdate);a.push({doc:c,docLastChangedAt:u,staleness:S.reduce((y,E)=>y+E.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 Yq(e,t,n){if(n&&n.length>0)return{value:Math.max(...n),estimated:!1};try{return{value:Math.floor(ks(e.config.projectRoot,t).mtimeMs/1e3),estimated:!0}}catch(r){if(At(e.config.projectRoot,t))throw r;return{value:0,estimated:!1}}}function Xq(e,t){let n=se(e,t).slice(0,6e3);if(!n)return{docIntent:"unknown",reasons:["doc text unavailable"]};let r=`${t}
395
- ${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 Km(e,t,n=[]){let r=e==="co-change"||n.length===0?null:_R.classifyCitation(n);return{actionTier:Qq(e,t.docIntent,r?.actionTier),docIntent:t.docIntent,docIntentReasons:t.reasons,...r?{citationKind:r.citationKind,citationKindReasons:r.reasons}:{}}}function Qq(e,t,n){return t==="historical-note"?"support":n||(e==="co-change"?"signal":"direct")}function Zq(e,t){let n=Qt(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=>gs.test(m)),d=l.filter(m=>!gs.test(m));for(let m of l){a.add(m);let f=o.get(m)??[];f.push(c.timestamp),o.set(m,f)}for(let m of u){let f=s.get(m);f||(f=new Map,s.set(m,f));for(let p of d)f.set(p,(f.get(p)??0)+1)}}return{changeTimes:o,coupling:s,docFiles:[...i].filter(c=>gs.test(c)),everSeenInHistory:a,historyCommitCount:r.commits.length,tracked:i,trackedBySuffix:tK(i)}}function eK(e,t){return gs.test(t)&&!Gq(t)&&At(e.config.projectRoot,t)}function tK(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 nK(e,t,n,r,i){let o=new Set,s=new Set,a=rK(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,f=(p,g)=>{let h=l.get(g);if(h&&h.length>0){let S=d.get(p)??[];S.push(...h),d.set(p,BR(S).slice(0,3))}let b=u.get(g);b&&b.length>0&&m.set(p,Gm([...m.get(p)??[],...b]))};for(let p of c){if(n.has(p)){o.add(p),f(p,p);continue}let g=r.get(p);if(g&&g.length===1){o.add(g[0]),f(g[0],p);continue}g&&g.length>1||i.has(p)&&s.add(p)}return{resolved:o,broken:[...s],citations:[...d].map(([p,g])=>({file:p,contexts:g,lineReferences:m.get(p)}))}}function rK(e,t,n){let r=n;if(r===void 0&&(r=se(e,t),!r&&!At(e.config.projectRoot,t)))return null;let i=Nt(e,t,r),o=OR.read(e,t,i);if(o)return o;let s=iK(r);return OR.write(e,t,i,s),s}function iK(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(Vq)){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,Gm([...i.get(c)??[],l]));let u=jc(t,o);if(u.length===0)continue;let d=r.get(c)??[];d.push(u),r.set(c,BR(d).slice(0,3))}}return{candidates:[...n],contextsByCandidate:r,lineReferencesByCandidate:i}}function oK(e){let t={candidates:e.candidates,contextsByCandidate:[...e.contextsByCandidate.entries()],lineReferencesByCandidate:[...e.lineReferencesByCandidate.entries()]};return JSON.stringify(t)}function sK(e){try{let t=JSON.parse(e);if(!Jf(t))return null;let n=hl(t.candidates),r=cK(t.contextsByCandidate),i=aK(t.lineReferencesByCandidate);return!n||!r?null:{candidates:n,contextsByCandidate:new Map(r),lineReferencesByCandidate:new Map(i??[])}}catch{return null}}function aK(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],Gm(r)])}return t}function cK(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=hl(n[1]);if(!r)return null;t.push([n[0],r])}return t}function BR(e){let t=[];for(let n of new Set(e))t.some(r=>lK(r,n))||t.push(n);return t}function Gm(e){return[...new Set(e)].sort((t,n)=>t-n)}function lK(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 uK}from"crypto";var dK=3;function hs(e,t={}){let{scope:n,maxLoc:r=15,minLoc:i=dK,limit:o,scanLimit:s}=t,a=xR(e),c=mK(e,{scope:n,maxLoc:r,scanLimit:s}).map(u=>fK(e,u,a,i)).filter(u=>u!==null),l=HR(c);return o?l.slice(0,o):l}function jR(e){let t=vn(e);return En(t).replace(/\s+/g,"")}function HR(e){let t=new Map;for(let r of e){if(r.normalizedBody.length<8)continue;let i=gK(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(hK).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=$R(i)-$R(r);return s!==0?s:r.canonical.file.localeCompare(i.canonical.file)}),n}function mK(e,t){let n=Ue(e,{scope:t.scope}).filter(r=>r.isFunctionLike&&!e.isIgnored(r.relativePath)).filter(r=>!$s(e,r.relativePath,r.startLine,"similar")).filter(r=>de(r)<=t.maxLoc);return n.sort((r,i)=>de(i)-de(r)||r.relativePath.localeCompare(i.relativePath)),Fe(n,t.scanLimit)}function fK(e,t,n,r){let i=Zt(e,t);if(!i||pK(i)<r)return null;let o=Wm(e,t);return o?{symbol:t.symbol,shortName:N(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:de(t),ageCommits:n?.get(t.relativePath)?.commitsAgo??null,normalizedBody:o}:null}function Wm(e,t){let n=Zt(e,t);return n&&jR(n)||null}function Zt(e,t){let n=ie(e,t.relativePath);return n.length===0?null:n.slice(t.startLine,t.endLine+1).join(`
396
- `)}function vn(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 pK(e){return vn(e).split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0).length}function gK(e){return uK("sha256").update(e).digest("hex").slice(0,16)}function hK(e,t){let n=e.ageCommits??-1;return(t.ageCommits??-1)-n||e.file.localeCompare(t.file)||e.startLine-t.startLine}function $R(e){return e.functions.reduce((t,n)=>t+n.loc,0)}var yK=new Set(an());function bK(e,t={}){let{includeHomonyms:n=!1,limit:r}=t,i=Hc(e,t).filter(o=>o.relationship==="divergent"||n&&o.relationship==="homonym");return r?i.slice(0,r):i}function Hc(e,t={}){let{scope:n,minSimilarity:r=.3,scanLimit:i}=t,o=CK(e,{scope:n,scanLimit:i});return qR(o,{minSimilarity:r,isDelegatePair:zK(e)}).filter(s=>!s.members.some(a=>$s(e,a.file,a.startLine,"twin")))}function qR(e,t={}){let n=t.minSimilarity??.3,r=t.isDelegatePair,i=e.filter(l=>!XR(l.leaf)&&!kK(l.leaf)&&J(l.file)!=="test"&&!Xe(l.symbol)&&!GR(l.symbol)&&!WR(l.symbol,l.leaf)),{recordsByLeaf:o,recordOrder:s}=O("twin-drift.group-by-leaf",()=>SK(i),()=>({records:i.length})),a=O("twin-drift.cluster-leaf-names",()=>KR([...o.keys()]),()=>({leaves:o.size}));return O("twin-drift.compare-clusters",()=>{let l=[];for(let u of a){let d=vK(u,o,s);if(d.length<2||new Set(d.map(S=>S.file)).size<2)continue;let m=null,f=!1,p=!1,g=new Set;for(let S=0;S<d.length;S+=1)for(let y=S+1;y<d.length;y+=1){let E=d[S],I=d[y];if(E.file===I.file||!_K(E,I)||r?.(E,I,d)||r?.(I,E,d))continue;if(f=!0,g.add(E.symbol),g.add(I.symbol),E.normalizedBody===I.normalizedBody){p=!0;continue}let v=DK(E.tokens,I.tokens);(!m||v>m.similarity)&&(m={a:E,b:I,similarity:v})}if(!f)continue;let h=d.filter(S=>g.has(S.symbol)).sort((S,y)=>S.file.localeCompare(y.file)||S.startLine-y.startLine).map(LK);if(!m){l.push({leaf:zR(u),relationship:p?"identical":"homonym",maxDivergence:0,members:h});continue}let b=m.similarity>=n?"divergent":"homonym";l.push({leaf:zR(u),relationship:b,maxDivergence:Math.round((1-m.similarity)*1e3)/1e3,members:h,...b==="divergent"?{firstDivergentTokens:PK(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 SK(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 vK(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 CK(e,t){let n=O("twin-drift.load-definitions",()=>Ue(e,{scope:t.scope}).filter(o=>xK(o)&&!e.isIgnored(o.relativePath)).filter(o=>!Ri(o.relativePath)));O("twin-drift.sort-definitions",()=>n.sort((o,s)=>o.relativePath.localeCompare(s.relativePath)||o.startLine-s.startLine),()=>({definitions:n.length}));let r=Fe(n,t.scanLimit),i=O("twin-drift.select-candidates",()=>RK(r),()=>({scanned:r.length}));return O("twin-drift.build-records",()=>{let o=[];for(let s of i){let a=IK(e,s);a&&o.push(a)}return o},()=>({candidates:i.length,scanned:r.length}))}function xK(e){return e.isFunctionLike?e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&yK.has(e.kind):!0:!1}function RK(e){let t=e.filter(o=>o.leaf&&!XR(o.leaf)&&!Xe(o.symbol)&&!GR(o.symbol)&&!WR(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=KR([...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=>J(a.relativePath)==="test"))for(let a of s)i.add(a)}return e.filter(o=>i.has(o))}function IK(e,t){if(!t.leaf)return null;let n=Zt(e,t);if(!n||!st(t.symbol)&&!EK(n,t.leaf))return null;let r=En(vn(n)),i=r.replace(/\s+/g,"");if(!i||i.length<8)return null;let o=r.match(wK)??[];return o.length===0?null:{leaf:t.leaf,symbol:t.symbol,shortName:N(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:de(t),normalizedBody:i,tokens:o,isThinForwarder:JR(r)}}function EK(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 wK=/[A-Za-z_$][A-Za-z0-9_$]*|\d+(?:\.\d+)?|[^\sA-Za-z0-9_$]/g;function LK(e){return{symbol:e.symbol,shortName:e.shortName,file:e.file,startLine:e.startLine,endLine:e.endLine,loc:e.loc}}function DK(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 PK(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 KR(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)MK(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 MK(e,t){return e===t||e.toLowerCase()===t.toLowerCase()?!0:e.length<8||t.length<8||Math.abs(e.length-t.length)>2||TK(e.toLowerCase(),t.toLowerCase())/Math.max(e.length,t.length)<.8?!1:OK(e.toLowerCase(),t.toLowerCase(),2)}function TK(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;return r}function kK(e){return/^[A-Z][A-Z0-9_]*$/.test(e)||/^__[^_].*__$/.test(e)||FK.has(e.toLowerCase())}var FK=new Set(["main","row"]),AK=new Set(["app","component","components","feature","features","impl","index","lib","route","routes","shared","src","tsx","typescript","ui"]);function GR(e){return e.startsWith("rust-analyzer ")&&/\/(?:tests?|benches?)\//.test(e)}var NK=new Set(["default","new","reset"]);function WR(e,t){return e.startsWith("rust-analyzer ")&&NK.has(t.toLowerCase())}function _K(e,t){if(e.leaf.toLowerCase()!==t.leaf.toLowerCase()||e.leaf.length>4)return!0;let n=UR(e);return[...UR(t)].some(r=>n.has(r))}function UR(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&&!AK.has(n)))}function OK(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 VR(e){return JR(En(vn(e)))}function JR(e){let t=e.trim();if(!t||BK.test(t))return!1;let n=HK(t);return n.length===0||n.length>2?!1:jK(n[n.length-1])}var BK=/\b(?:if|else|for|while|switch|try|catch|do)\b/,$K=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^[\]]*\])*\((?:[^()]|\([^()]*\))*\)$/;function jK(e){let t=e.trim().replace(/^return\s+/,"").replace(/^await\s+/,"").replace(/;\s*$/,"").trim();return $K.test(t)}function HK(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 UK=3;function zK(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=YR(e,n,r,i,UK,new Set);return t.set(o,a),a}}function YR(e,t,n,r,i,o){if(i<=0||o.has(t.symbol)||(o.add(t.symbol),(rn(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(Ce(e,t.file).filter(c=>c.sourcePath&&(c.kind!=="namespace"||c.usedMembers.includes(n.leaf))).map(c=>c.sourcePath));if([...a].some(c=>Ft(c,n.file)))return!0;for(let c of r)if(!(c.symbol===t.symbol||c.symbol===n.symbol||!c.isThinForwarder)&&[...a].some(l=>Ft(l,c.file))&&YR(e,c,n,r,i-1,o))return!0;return!1}function XR(e){return e.startsWith("<")&&e.endsWith(">")}function zR(e){return[...e].sort()[0]}import{dirname as iG,isAbsolute as oG,relative as sG,resolve as aG}from"path";import{basename as QR,extname as ZR}from"path";function Uc(e,t,n,r,i,o){let s=new Set;KK(e,t,n,r)&&s.add(i);for(let a of o)a.value&&qK(s,a.label,a.value);return[...s].slice(0,6)}function qK(e,t,n){let r=GK(n);t.endsWith("name")&&WK(r)&&e.add(`${t} has type-guard boundary shape`);for(let i of r){let o=VK.get(i);o&&e.add(`${t} has ${o} term: ${i}`)}}function KK(e,t,n,r){if(n<=0)return!1;let i=ie(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(Os(s)===r)return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function GK(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 WK(e){return e.some(t=>JK.has(t))&&e.some(t=>YK.has(t))}var VK=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"]]),JK=new Set(["can","has","is","should"]),YK=new Set(["access","api","auth","collision","expired","input","keyboard","overlap","permission","permissions","policy","projectile","response","route","routes","scope"]);function ys(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new U(e);return Ut({candidates:()=>rG(e,s,n,r),orderCandidates:ec,scanLimit:o,profile:{name:"passthrough-candidates"},prepare:a=>s.calleeEvidenceMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,c)=>c.incompleteSymbolIds.has(a.symbolId)||c.unavailableSymbolIds.has(a.symbolId)?null:XK(e,a,c.rows.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:i})}function XK(e,t,n){let r=nG(n);if(r.size!==1||!cp(e,t.relativePath,t.startLine,t.endLine))return null;let[,i]=[...r.entries()][0],o=QK(e,t,i),s=eG(e,t),a=o.length>0||s.length>0?"signal":"direct";return{symbol:t.symbol,shortName:N(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:de(t),forwardsTo:i.symbol,forwardsToShort:N(i.symbol),forwardsToFile:i.file,actionTier:a,boundaryEvidence:o,publicFacadeEvidence:s,recommendation:ZK(a,o,s)}}function QK(e,t,n){return Uc(e,t.relativePath,t.startLine,"passthrough","explicit ignore-passthrough comment",[{label:"passthrough name",value:N(t.symbol)},{label:"callee name",value:N(n.symbol)},{label:"passthrough module",value:QR(t.relativePath,ZR(t.relativePath))},{label:"callee module",value:QR(n.file,ZR(n.file))}])}function ZK(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(tG);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 eG(e,t){return It(e,t)?Fn(e,t.relativePath)?["exported passthrough is declared on the package public surface"]:qe(e,t.symbol,t.relativePath)?["exported passthrough matches configured or framework public entry surface"]:[]:[]}function tG(e){return e.includes("public surface")}function nG(e){let t=e.some(r=>_e(r.symbol))?e.filter(r=>_e(r.symbol)):e,n=new Map;for(let r of t)n.has(r.symbol)||n.set(r.symbol,r);return n}function rG(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:3,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0}).filter(i=>!js(e,i))}var cG=new Set(an());function lG(e,t){return`tests/generated/twin-ab/${eI(e)}-vs-${eI(t)}.test.ts`}function eI(e){return(e.split(/[/#]/).pop()||e).replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"symbol"}function uG(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(!oG(s))throw new TypeError("twinAb outFile must be an absolute path.");let a=tI(e,i);if(!a.ok)return a;let c=tI(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=mG(a.symbol,c.symbol,e.config.projectRoot,s,l);return{ok:!0,a:a.symbol,b:c.symbol,signatureCompatible:l,testSource:u}}function tI(e,t){let r=at(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?cG.has(o):_e(r.symbol)))return{ok:!1,reason:`${t} resolves to ${N(r.symbol)}${o!==null?` with SCIP kind ${io(o)}`:""} \u2014 twin-ab compares call outputs, so both referents must be functions or methods.`};if(!It(e,r))return{ok:!1,reason:`${t} (${N(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=ci(li(a?.documentation??null));return{ok:!0,symbol:{ref:t,symbol:r.symbol,shortName:Y(r.symbol)||N(r.symbol),file:r.relativePath,startLine:r.startLine,signature:c,paramCount:c?dG(c):null}}}function dG(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 nI(e,t,n){let r=iG(t),i=aG(e,n),s=sG(r,i).replace(/\\/g,"/").replace(/\.tsx?$/,".js");return s.startsWith(".")?s:`./${s}`}function mG(e,t,n,r,i){let o=nI(n,r,e.file),s=nI(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`/**
397
- * Generated by 'codebaseiq twin-ab'. Cleanup integrity scenario.
398
- * ("cross-examine same-concept twins"): where one concept is computed in
399
- * more than one place, feed both the same input and require the same
400
- * answer. Disagreement between twins means at least one is wrong \u2014
401
- * determine which before consolidating.
402
- *
403
- * Twin A: ${e.shortName} (${e.file}:${e.startLine+1})
404
- * ${e.signature??"(signature unavailable)"}
405
- * Twin B: ${t.shortName} (${t.file}:${t.startLine+1})
406
- * ${t.signature??"(signature unavailable)"}
407
- * ${a}
408
- *
409
- * Fill in the TODO input table below with inputs both twins should agree
410
- * on, then run this file with vitest.
411
- */
412
- import { describe, expect, it } from 'vitest';
413
- import { ${e.shortName} as twinA } from '${o}';
414
- import { ${t.shortName} as twinB } from '${s}';
415
-
416
- // TODO: fill in shared inputs both twins should agree on \u2014 one arg array per call.
417
- const inputs: any[][] = [
418
- // [/* arg1, arg2, ... */],
419
- ];
420
-
421
- // Cast to a variadic signature so the input table can hold any arg shape \u2014
422
- // the real twins have fixed, non-rest parameter lists, and TS rejects
423
- // spreading a generic args array into those (TS2556) even when the array
424
- // itself is 'any'; casting the callee's signature, not the args, satisfies
425
- // the checker without weakening the twins' real exported types elsewhere.
426
- const callA = twinA as (...callArgs: any[]) => any;
427
- const callB = twinB as (...callArgs: any[]) => any;
428
-
429
- describe.skipIf(inputs.length === 0)('twin-ab: ${e.shortName} vs ${t.shortName}', () => {
430
- it.each(inputs)('agrees on input %#', (...args) => {
431
- expect(callA(...args)).toEqual(callB(...args));
432
- });
433
- });
434
- `}var rI={caller:3,"entry-surface":2,rooted:1},fG=/not\s*yet\s*implement|not\s*implement|unimplement|\bnyi\b|\btodo\b|\bstub\b|not\s*supported|coming\s*soon/i,pG=/^throw\s+new\s+[\w.]*Error\s*\(([\s\S]*)\)\s*;?$/,gG=/^return(\s+(null|undefined|false|0|''|""|``|\[\]|\{\}))?\s*;?$/,hG=/\/\/\s*TODO\b|\/\*\s*TODO\b/i,yG=/(?:=>|\))\s*(?::\s*[^{;=]+)?\s*\{\s*\}\s*;?\s*$/;function bG(e,t={}){let{scope:n,limit:r=30,scanLimit:i,semantic:o=!0}=t,s=new U(e),a=Fe(s.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),c=[];for(let f of a){let p=vG(e,f);p&&c.push(p)}if(c.length===0)return[];let l=IG(e,c,a),u=c.filter(f=>!l.has(f.def.symbol));if(u.length===0)return[];let d=bn(e,s).forDefinitions(u.map(f=>f.def),{semantic:o}),m=[];for(let f of u){let p=d.get(f.def.symbolId);if(p?.semanticIncomplete||p?.semanticUnavailable)continue;let g=p?.realConsumers.length??0,h=SG(e,f.def,g);h&&m.push({symbol:f.def.symbol,shortName:N(f.def.symbol),file:f.def.relativePath,startLine:f.def.startLine,endLine:f.def.endLine,loc:de(f.def),stubKind:f.stubKind,reachability:h,callerFanIn:g,stubText:f.stubText})}return m.sort((f,p)=>rI[p.reachability]-rI[f.reachability]||p.callerFanIn-f.callerFanIn||f.file.localeCompare(p.file)||f.startLine-p.startLine),r?m.slice(0,r):m}function SG(e,t,n){return n>0?"caller":qe(e,t.symbol,t.relativePath)?"rooted":Qe(e,t.relativePath)?"entry-surface":null}function vG(e,t){let n=Zt(e,t);if(!n)return null;let r=vn(n),i=r.trim();if(i==="")return!RG(n)||!It(e,t)?null:{def:t,stubKind:"empty-body",stubText:"(empty body)"};let o=Yi(r),s=En(r),a=CG(o,s);if(a.length!==1)return null;let c=a[0];return xG(c)?{def:t,stubKind:"throw-stub",stubText:c.trim()}:hG.test(r)&&gG.test(c.trim())?{def:t,stubKind:"todo-return-default",stubText:i}:null}function CG(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 xG(e){let t=pG.exec(e.trim());return t?fG.test(t[1]??""):!1}function RG(e){return yG.test(e.trimEnd())}function IG(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=wG(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 EG=/\bclass\s+([A-Za-z_$][\w$]*)\s+extends\s+([A-Za-z_$][\w$]*)/g;function wG(e,t){let n=new Map;for(let r of me(e,{includeIgnored:!1})){let i=se(e,r);if(i)for(let o of i.matchAll(EG)){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 LG=/^(?:validate|verify|check|assert)(?:[A-Z].*)?$/,DG=/^(?:is|has)(?:[A-Z].*)?$/,PG=/[{,]\s*(?:ok|success|valid|isValid)\s*:\s*false\b/,Vm=/\breturn\b/g,MG=/\bfunction\b|=>|\)\s*(?::\s*[^{;=]+)?\s*\{/,TG=/\.(?:addIssue|push)\s*\(/;function kG(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new U(e),s=Fe(o.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),a=[];for(let c of s){let l=AG(e,c);l&&a.push({symbol:c.symbol,shortName:N(c.symbol),file:c.relativePath,startLine:c.startLine,endLine:c.endLine,loc:de(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 FG(e){return LG.test(e)?"imperative":DG.test(e)?"predicate":null}function AG(e,t){let n=FG(t.leaf);if(!n||Ni(e,t))return null;let r=Zt(e,t);if(!r||!MG.test(r))return null;let i=te(e,t.relativePath)?.callables.find(s=>s.startLine===t.startLine&&s.endLine===t.endLine);if(n==="predicate"&&i?.paramCount===0)return null;if(VR(r)){let s=OG(e,t);return!s||sI(s.body,oI(s.snippet))||iI(s.body)?null:{nameKind:n,resolvedVia:"one-hop-delegate",delegateTarget:s.shortName}}let o=vn(r);return sI(o,oI(r))||iI(o)?null:{nameKind:n,resolvedVia:"direct"}}var NG=new Set(["if","for","while","switch","catch","function"]);function iI(e){let t=Yi(e);for(let n of t.matchAll(/\b([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(/g))if(!NG.has(n[1]))return!0;return!1}function oI(e){let t=e.indexOf("=>");return t===-1?!1:!/^\s*\{/.test(e.slice(t+2))}function sI(e,t){let n=Yi(e);if(/\bthrow\b/.test(n)||/\.reject\s*\(/.test(n)||PG.test(n)||TG.test(n))return!0;let r=_G(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 _G(e){let t=[];Vm.lastIndex=0;let n;for(;n=Vm.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()),Vm.lastIndex=o}return t}function OG(e,t){let n=Lr(e,t,{callableOnly:!0,limit:3,semanticEvidence:ge});if(n.semanticIncomplete||n.semanticUnavailable)return null;let r=n.rows,i=[...new Set(r.map(l=>l.symbol))].filter(l=>l!==t.symbol);if(i.length!==1)return null;let s=at(e,i[0]).match;if(!s)return null;let a=W(e,s.relativePath).find(l=>l.symbolId===s.symbolId);if(!a)return null;let c=Zt(e,a);return c?{body:vn(c),snippet:c,shortName:N(a.symbol)}:null}var BG=60;function $G(e,t={}){let{scope:n,limit:r=30,scanLimit:i,rotDays:o=BG}=t,s=Fe(oi(e,{extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs"]}).filter(u=>J(u)==="test").filter(u=>!n||u.includes(n)).filter(u=>!e.isIgnored(u)).sort(),i),a=[],c=[],l=[];for(let u of s){let d=se(e,u);if(!d)continue;let m=op(d),f=UG(d);for(let g of GG(m,f))f.add(g);let p=jG(m);for(let g of p){if(g.skip){c.push(ZG(e,u,g,o));continue}if(g.kind==="describe")continue;let h=cI(d,g.argsStart),b=m.slice(g.argsStart,g.callEnd),S=d.slice(g.argsStart,g.callEnd);lI(b,f)||a.push({file:u,startLine:bs(d,g.callStart),endLine:bs(d,g.callEnd),title:h,severity:/\bawait\b/.test(b)?"low":"high"});let y=YG(b,S);y&&l.push({file:u,startLine:bs(d,g.callStart),endLine:bs(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 Jm=/(?<!\.)\b(?:x(it|test|describe)|(it|test|describe)(?:\.\s*(skip|only|todo|each\s*\([^)]*\)))?)\s*\(/g;function jG(e){let t=[];Jm.lastIndex=0;let n;for(;n=Jm.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=Ss(e,a);Jm.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 Ss(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 bs(e,t){let n=0;for(let r=0;r<t&&r<e.length;r+=1)e[r]===`
435
- `&&(n+=1);return n}function cI(e,t){let n=e.slice(t,t+400),r=/^\s*(['"`])((?:\\.|(?!\1)[\s\S])*)\1/.exec(n);return r?r[2]:"(anonymous)"}var HG=new Set(["vitest","chai","jest","@jest/globals","assert","node:assert","node:assert/strict","assert/strict","uvu/assert","expect","chai-as-promised"]),aI=/import\s+(?:\*\s+as\s+(\w+)|\{([^}]*)\}|(\w+))\s+from\s+['"]([^'"]+)['"]/g;function UG(e){let t=new Set(["expect","assert"]);aI.lastIndex=0;let n;for(;n=aI.exec(e);){let[,r,i,o,s]=n;if(!(!s||!HG.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 lI(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 zG=/\bfunction\s+(\w+)\s*\(/g,qG=/\b(?:const|let)\s+(\w+)\s*=\s*(?:async\s*)?\(/g,KG=60;function GG(e,t){let n=new Set;for(let r of[zG,qG]){r.lastIndex=0;let i;for(;i=r.exec(e);){let o=i[1],s=i.index+i[0].length-1,a=Ss(e,s),c=e.indexOf("{",a+1);if(c===-1||c-a>KG)continue;let l=WG(e,c),u=e.slice(c+1,l);lI(u,t)&&n.add(o)}}return n}function WG(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 VG=/\bmock(?:ReturnValue|ResolvedValue)(?:Once)?\s*\(/g,Ym=/\bexpect\s*\(/g,JG=/^\s*\.\s*(?:toBe|toEqual|toStrictEqual)\s*\(/,uI=/^(?:-?\d+(?:\.\d+)?|(['"`]).+\1)$/;function YG(e,t){let n=XG(e,t,VG);if(n.length===0)return null;let r=QG(e,t);for(let i of r)if(n.includes(i))return i;return null}function XG(e,t,n){let r=[];n.lastIndex=0;let i;for(;i=n.exec(e);){let o=i.index+i[0].length-1,s=Ss(e,o),a=t.slice(o+1,s).trim();uI.test(a)&&r.push(a),n.lastIndex=s+1}return r}function QG(e,t){let n=[];Ym.lastIndex=0;let r;for(;r=Ym.exec(e);){let i=r.index+r[0].length-1,o=Ss(e,i),s=e.slice(o+1),a=JG.exec(s);if(Ym.lastIndex=o+1,!a)continue;let c=o+1+a[0].length-1,l=Ss(e,c),u=t.slice(c+1,l).trim();uI.test(u)&&n.push(u)}return n}function ZG(e,t,n,r){let i=se(e,t),o=cI(i,n.argsStart),s=bs(i,n.callStart),a=eW(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 eW(e,t,n){let r=n+1;try{let i=Sn(e,["blame","-L",`${r},${r}`,"--porcelain","--",t]),o=/^author-time (\d+)$/m.exec(i);if(!o)return null;let s=Number(o[1]);return Number.isFinite(s)?Math.max(0,Math.round((Date.now()/1e3-s)/86400)):null}catch{return null}}var tW=.7,dI=.62,mI=.45;function nW(e,t={}){let{windowCommits:n=100,limit:r=30,scope:i,scanLimit:o}=t,s=Qt(e,{historyMode:t.historyMode}).fileAddRecords();if(!s)return{available:!1,windowCommits:n,findings:[]};if(r<=0)return{available:!0,windowCommits:n,findings:[]};let a=dW(s,n);if(a.size===0)return{available:!0,windowCommits:n,findings:[]};let l=rW(e,{limit:r,minSimilarity:t.minSimilarity,scanLimit:o,scope:i,semantic:t.semantic,focusFiles:Number.isFinite(r)?void 0:a}).map(d=>mW(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(fW);return{available:!0,windowCommits:n,findings:u,rootCauseGroups:pW(u)}}function rW(e,t){let n=hW(t.limit),r=[...iW(e,{scope:t.scope,minSimilarity:t.minSimilarity??tW,limit:n,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles})],i=Hs(e,{scope:t.scope});return i.react&&r.push(...oW(e,{scope:t.scope,minSimilarity:t.minSimilarity??dI,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...sW(e,{scope:t.scope,minSimilarity:t.minSimilarity??mI,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),i.vue&&r.push(...lW(e,{scope:t.scope,minSimilarity:t.minSimilarity??dI,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...uW(e,{scope:t.scope,minSimilarity:t.minSimilarity??mI,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),r}function iW(e,t){return as(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles}).filter(n=>!Xe(n.symbolA)&&!Xe(n.symbolB)).map(n=>({domain:"callable",basis:n.similarityBasis??"callees",symbolA:n.shortNameA,fileA:n.fileA,symbolB:n.shortNameB,fileB:n.fileB,similarity:n.similarity,sharedEvidence:n.sharedCallees,sharedCallees:n.sharedCallees}))}function oW(e,t){return qc(e,t,{query:cs,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:yW(...n.evidenceBuckets(r)),sharedCallees:[]}))}function sW(e,t){return qc(e,t,{query:ls,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,acceptPair:cW,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 aW=new Set(["useCallback","useEffect","useLayoutEffect","useMemo","useMutation","useQueries","useQuery","useQueryClient","useReducer","useRef","useState"]);function cW(e){return e.sharedHooks.some(t=>!aW.has(t))||e.sharedState.length>0||e.sharedHandlers.length>0||e.sharedHandlerVerbs.length>=2}function lW(e,t){return qc(e,t,{query:us,domain:"vue-component",basis:"vue-template",symbolA:n=>zc(n.fileA),symbolB:n=>zc(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function uW(e,t){return qc(e,t,{query:ds,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>zc(n.fileA),symbolB:n=>zc(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 dW(e,t){let n=new Set;for(let[r,i]of e)i.commitsAgo<=t&&n.add(r);return n}function mW(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 fW(e){let t=fI(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function fI(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 pW(e){let t=new Map;for(let[n,r]of e.entries()){let i=r.rootCauseKey??fI(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:gW(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 gW(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 hW(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function yW(...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 zc(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var bW=ke("suppression-inventory",{clearGroups:["whole-project"]});function Kc(e){return bW.get(e,()=>SW(e))}function SW(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=se(e,i);if(!(!o||!o.includes("codebaseiq")))for(let s of o.split(/\r?\n/)){let a=Os(s);if(a===null)continue;r+=1,n.set(i,(n.get(i)??0)+1);let c=pI(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[pI(i.check)]+=1);return{total:r,byCategory:t,byFile:n}}function pI(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 Xm(e,t,n={}){let r=pe(e,t);if(!r)return null;let i=new U(e),o=vW(e,r),s=r.endLine-r.startLine+1,a=i.calleeEvidenceMap([r],{additive:!0,semantic:n.semantic}),c=a.rows.get(r.symbolId)??[],l=new Set(c.map(p=>p.symbol)),u=a.incompleteSymbolIds.has(r.symbolId),d=a.unavailableSymbolIds.has(r.symbolId),m=n.semantic===!1?"disabled":u&&d?"incomplete-and-unavailable":u?"incomplete":d?"unavailable":"complete",f=!u&&!d;return{symbol:r.symbol,shortName:N(r.symbol),relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,loc:s,branches:o.branches,estimateBasis:o.estimateBasis,cyclomaticEstimate:o.branches+1,calleeCount:f?l.size:null,fanIn:xW(e,r.symbolId),fanOut:f?RW(c,r.relativePath):null,coverage:{semanticEvidence:m}}}function vW(e,t){let n=ae(e,t.relativePath);if(n){let r=bI(n.rootNode,t.startLine,t.endLine);if(r)return{branches:IW(r),estimateBasis:"ast"}}return{branches:vI(yI(e,t.relativePath,t.startLine,t.endLine),hI(e,t.relativePath)),estimateBasis:"regex-fallback"}}function gI(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=ae(e,i),a=s===null?[]:o.filter(l=>s.rootNode.startPosition.row<=l.startLine&&s.rootNode.endPosition.row>=l.endLine),c=new Set(a.map(l=>l.symbolId));if(s&&a.length>0){for(let l of a)n.set(l.symbolId,{branches:0,estimateBasis:"ast"});EW(s.rootNode,a,n)}for(let l of o)c.has(l.symbolId)||n.set(l.symbolId,CW(e,l))}return n}function CW(e,t){return{branches:vI(yI(e,t.relativePath,t.startLine,t.endLine),hI(e,t.relativePath)),estimateBasis:"regex-fallback"}}function hI(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function yI(e,t,n,r){try{return it(e.config.projectRoot,t,{inputKind:"indexed source file"}).split(`
436
- `).slice(n,r+1).join(`
437
- `)}catch(i){if(!ot(i))throw i;return""}}function xW(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
438
- FROM mentions m
439
- JOIN chunks c ON m.chunk_id = c.id
440
- JOIN (
441
- SELECT m2.symbol_id, c2.document_id
442
- FROM mentions m2
443
- JOIN chunks c2 ON m2.chunk_id = c2.id
444
- WHERE m2.role = 1
445
- GROUP BY m2.symbol_id
446
- ) sym_def ON sym_def.symbol_id = m.symbol_id
447
- WHERE m.symbol_id = ?
448
- AND m.role != 1
449
- AND sym_def.document_id != c.document_id`,t)?.c??0}function RW(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function IW(e){let t=0;return Qm(e,n=>{t+=SI(n)}),t}function EW(e,t,n){let r=[...t].sort((i,o)=>i.startLine-o.startLine||o.endLine-i.endLine);Qm(e,i=>{let o=SI(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 Qm(e,t){t(e);for(let n of e.namedChildren)Qm(n,t)}function bI(e,t,n){if(e.startPosition.row>t||e.endPosition.row<n)return null;for(let r of e.namedChildren){let i=bI(r,t,n);if(i)return i}return e}var wW=new Set(["if_statement","conditional_expression","ternary_expression","for_statement","for_in_statement","for_of_statement","while_statement","do_statement","switch_case","case_statement","catch_clause","except_clause","elif_clause","match_arm"]);function SI(e){return wW.has(e.type)?1:e.type==="binary_expression"&&e.parent?.type!=="binary_expression"&&(e.text.includes("&&")||e.text.includes("||"))?LW(e.text):0}function LW(e){return(e.match(/&&|\|\|/g)??[]).length}function vI(e,t){let n=En(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 CI(e,t,n={}){let r=pe(e,t);if(!r)return null;let i=[{file:r.relativePath,line:r.startLine}],o=Yn(e,r,{semantic:n.semantic,semanticEvidence:ge}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?N(c.enclosingSymbol):"(top-level)"})),{outgoingCalls:s,incomingCalls:a}=DW(e,r,o,{semantic:n.semantic!==!1});return{symbol:r.symbol,shortName:N(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:N(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)":N(c.symbol),file:c.file}))}}function Zm(e,t,n={}){let r=CI(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 DW(e,t,n,r){let i=Di(la(e,t,{limit:30,semantic:r.semantic,semanticEvidence:ge}).map(a=>({symbol:a.symbol,file:a.file}))),o=Di(ua(e,t,{limit:30,semantic:r.semantic,semanticEvidence:ge})),s=o.length>0?o:Di(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{outgoingCalls:i,incomingCalls:s}}function xI(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,o=pe(e,t);return o?r==="backward"?PW(e,o,i,{semantic:n.semantic!==!1}):MW(e,o,{semantic:n.semantic!==!1}):null}function Gc(e,t,n={}){return xI(e,t,n)}function PW(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=la(e,l,{semantic:r.semantic,semanticEvidence:ge});for(let d of u){if(o.has(d.symbol))continue;o.add(d.symbol),i.push({symbol:d.symbol,shortName:N(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let m=Er(e,d.symbol);m&&!e.isIgnored(m.relativePath)&&c.push(m)}}s=c}return{symbol:t.symbol,shortName:N(t.symbol),direction:"backward",connectedSymbols:i}}function MW(e,t,n){let r=new Set,i=[],o=new U(e);for(let s of Yn(e,t,{semantic:n.semantic,semanticEvidence:ge})){if(i.length>=30)break;let a=s.enclosingSymbol??Ke(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=Er(e,a);!c||e.isIgnored(c.relativePath)||r.has(c.symbol)||(r.add(c.symbol),i.push({symbol:c.symbol,shortName:N(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:N(t.symbol),direction:"forward",connectedSymbols:i}}function RI(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 PI=6,Vc=10,tf=3,nf=8,TW=.7,II=24,ef=200,MI=12,EI=80,wI=600;function kW(e,t,n={}){let r=n.impactDepth??3,i=n.sliceDepth??3,o=n.semantic,s=UW(t)?AW(e,t):null,a=s?s.primary?.symbol??null:t,c=a!==null,l=c?We("trace",a,()=>xd(e,a,{semantic:o,referenceContext:MI}),M=>({definitions:M.definitions.length,references:M.referencedBy.length})):{definitions:[],referencedBy:[],claimSupport:null},u=c?We("call-graph",a,()=>Bo(e,a,{semantic:o}),M=>({callers:M?.callers.length??0,callees:M?.callees.length??0})):null,d=c?We("complexity",a,()=>Xm(e,a,{semantic:o}),M=>({callees:M?.calleeCount??0})):null,m=c?We("dataflow",a,()=>Zm(e,a,{semantic:o}),M=>({references:M?.usageSites.length??0,producers:M?.producers.length??0,consumers:M?.consumers.length??0})):null,f=c?We("backward-slice",a,()=>Gc(e,a,{direction:"backward",maxDepth:i,semantic:o}),M=>({maxDepth:i,connectedSymbols:M?.connectedSymbols.length??0})):null,p=c?We("forward-slice",a,()=>Gc(e,a,{direction:"forward",maxDepth:i,semantic:o}),M=>({maxDepth:i,connectedSymbols:M?.connectedSymbols.length??0})):null,g=c?We("affected",a,()=>Im(e,a,{maxDepth:r,scope:n.scope}),M=>({maxDepth:r,affectedSymbols:M.rows.length,coverage:M.coverage.status})):null,h=g?.rows??[],b=g?.coverage??null,S=c?We("reuse-candidates",a,()=>ss(e,a,{minSimilarity:.4,limit:5,semantic:o,sourceCandidateMode:"target-pruned"}),M=>({candidates:M.length,direct:M.filter(F=>F.actionTier==="direct").length})):[],y=c?pe(e,a)?.symbol??null:null,E=c?We("affected-consumer-reuse",a,()=>_W(l,y,M=>ss(e,M,{minSimilarity:.4,limit:Vc,semantic:o,sourceCandidateMode:"target-pruned"}),{consumerLimit:PI,perConsumerSearchLimit:Vc,perConsumerCandidateLimit:tf,candidateLimit:nf}),M=>({totalConsumers:M.coverage.totalConsumers,analyzedConsumers:M.coverage.analyzedConsumers,candidates:M.candidates.length})):jW(),I=We("change-surface",t,()=>Em(e,t,{semantic:o}),M=>({symbols:M?.symbols.length??0,externalConsumers:M?.totalExternalConsumers??0})),v=We("system",t,()=>em(e,t),M=>({files:M.files.length,symbols:M.symbols.length})),x=v.files.length===1,C=We("deps",t,()=>x?v.dependsOn.map(M=>({relativePath:M,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):$o(e,t),M=>({files:M.length,reusedSystem:x})),L=We("rdeps",t,()=>x?v.dependedOnBy.map(M=>({relativePath:M,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):jo(e,t),M=>({files:M.length,reusedSystem:x})),w=We("surface",t,()=>tm(e,t),M=>({consumers:M.length})),R={symbol:l.definitions.length>0||l.referencedBy.length>0||u!==null||d!==null||m!==null||f!==null||p!==null||h.length>0,file:I!==null||C.length>0||L.length>0,module:v.files.length>0||v.symbols.length>0||w.length>0},P=[];s&&!s.primary&&s.callableCount>1&&P.push(`File target has ${s.callableCount} callable symbols; use one callable name for compiler-resolved flow.`);let _=[...new Set(l.referencedBy.map(M=>M.relativePath))];_.length>0&&_.every(M=>J(M)==="test")&&P.push("Only test references were found for this target. For replacement or retirement work, map the currently wired owner or one production entry point before planning; this target does not describe the live affected surface."),!R.symbol&&!R.file&&!R.module&&P.push("No symbol, file, or module matched target."),b&&b.status!=="accounted"&&P.push(`Possible-impact coverage is ${b.status}: ${b.reasons.join(" ")}`);let D=I?.file??l.definitions[0]?.relativePath??null;return{target:t,...s?.primary?{primaryCallable:{symbol:s.primary.symbol,shortName:Y(s.primary.symbol),file:s.primary.relativePath}}:{},matched:R,history:We("history",D??t,()=>HW(e,D,n.gitHead)),trace:FW(l),callGraph:u,complexity:d,dataflow:m,backwardSlice:f,forwardSlice:p,affected:h,affectedCoverage:b,changeSurface:I,deps:C,rdeps:L,system:v,surface:w,reuseCandidates:S,affectedConsumerReuse:E,sourcePacket:NW(e,y,l,E,S),warnings:P}}function FW(e){return{definitions:e.definitions,referencedBy:e.referencedBy.map(t=>({relativePath:t.relativePath,line:t.line,enclosingSymbol:t.enclosingSymbol,enclosingShort:t.enclosingShort}))}}function AW(e,t){let n=Dn(e,t);if(n.length!==1)return{primary:null,callableCount:0};let r=W(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 NW(e,t,n,r,i){let o=[...t?[{definition:LI(e,t),role:"target"}]:[],...[...r.candidates.map(d=>d.candidate),...i].map(d=>({definition:LI(e,d.symbolB),role:"reuse-candidate"}))],s=new Map;for(let d of RI(o)){if(s.has(d.definition.symbol))continue;let m=d.role==="target"?ef:EI,f=d.definition.endLine<=d.definition.startLine?nr(e,d.definition.relativePath,d.definition.startLine,m):null,p=f?.unitType?f.source:Zt(e,d.definition);if(!p)continue;let g=p.split(`
450
- `),h=Math.min(g.length,m),b=f?.unitType?f.startLine:d.definition.startLine;s.set(d.definition.symbol,{role:d.role,symbol:d.definition.symbol,shortName:Y(d.definition.symbol),file:d.definition.relativePath,startLine:b,endLine:b+h-1,source:g.slice(0,h).join(`
451
- `),omittedLines:(f?.unitType?f.omittedLines:0)+Math.max(0,g.length-h)})}let a=new Map;for(let d of n.referencedBy){if(d.source===void 0||d.source===null||d.sourceStartLine===void 0||d.sourceStartLine===null||d.sourceEndLine===void 0||d.sourceEndLine===null)continue;let m=`${d.relativePath}:${d.sourceStartLine}-${d.sourceEndLine}`,f=a.get(m);if(f){f.focusLines=[...new Set([...f.focusLines??[],d.line])].sort((p,g)=>p-g);continue}a.set(m,{role:"consumer",symbol:d.enclosingSymbol??`${d.relativePath}:${d.line}`,shortName:d.enclosingShort,file:d.relativePath,startLine:d.sourceStartLine,endLine:d.sourceEndLine,source:d.source,omittedLines:0,focusLines:[d.line]})}let c=[...[...s.values()].filter(d=>d.role==="target"),...a.values(),...[...s.values()].filter(d=>d.role==="reuse-candidate")],l=[],u=wI;for(let d of c){if(l.length>=II||u<=0)break;let m=d.source.split(`
452
- `),f=Math.min(m.length,u);l.push({...d,endLine:d.startLine+f-1,source:m.slice(0,f).join(`
453
- `),omittedLines:d.omittedLines+Math.max(0,m.length-f),...d.focusLines?{focusLines:d.focusLines.filter(p=>p<=d.startLine+f-1)}:{}}),u-=f}return{slices:l,candidateSlices:c.length,omittedSlices:Math.max(0,c.length-l.length),maxSlices:II,maxLinesPerSlice:ef,maxTotalLines:wI,targetLineLimit:ef,consumerContextLines:MI,reuseLineLimit:EI}}function LI(e,t){let n=Er(e,t);return n?W(e,n.relativePath).find(r=>r.symbol===t)??null:null}function _W(e,t,n,r={}){let i=Wc(r.consumerLimit,PI),o=Wc(r.perConsumerSearchLimit,Vc),s=Wc(r.perConsumerCandidateLimit,tf),a=Wc(r.candidateLimit,nf),c=OW(e),l=c.slice(0,i),u=new Set(c.map(f=>f.symbol));t&&u.add(t);let d=new Map;for(let f of l){let p=n(f.symbol).slice(0,o),g=0;for(let h of p){let b=BW(h,f.symbol);if(!b||u.has(b.symbolB))continue;let S=d.get(b.symbolB);if(S?(S.consumers.some(y=>y.symbol===f.symbol)||S.consumers.push(f),b.similarity>S.candidate.similarity&&(S.candidate=b)):d.set(b.symbolB,{candidate:b,consumers:[f]}),g+=1,g>=s)break}}let m=[...d.values()].filter(f=>f.candidate.actionTier==="direct"||f.candidate.similarity>=TW||f.consumers.length>1).sort($W).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 OW(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:Y(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 BW(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 $W(e,t){let n=DI(t.candidate.actionTier)-DI(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 DI(e){return e==="direct"?1:0}function Wc(e,t){return typeof e=="number"&&Number.isFinite(e)?Math.max(1,Math.floor(e)):t}function jW(){return{candidates:[],coverage:{totalConsumers:0,analyzedConsumers:0,omittedConsumers:0,perConsumerSearchLimit:Vc,perConsumerCandidateLimit:tf,candidateLimit:nf,returnedCandidates:0}}}function We(e,t,n,r=()=>({})){let i;return O(`context.${e}`,()=>(i=n(),i),()=>({target:t,...r(i)}))}function HW(e,t,n){let r={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return r;let i=Qt(e,n?{head:n}:{}),o=We("history.churn",t,()=>i.fileChurn(),c=>({files:c?.size??0}));if(!o)return r;let s=We("history.co-change",t,()=>ps(e,t,{limit:5,...n?{head:n}:{}}),c=>({commits:c.commitsAnalyzed,partners:c.findings.length})),a=We("history.suppressions",t,()=>Kc(e).byFile.get(t)??0,c=>({suppressions:c}));return{available:!0,file:t,churn:o.get(t)??{changes:0,fixChanges:0,lastChangedAt:0},coChangePartners:s.findings.map(c=>({file:c.fileA===t?c.fileB:c.fileA,together:c.together,confidence:c.confidence,subjectContext:c.subjectContext})),suppressionsInFile:a}}function UW(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}var je={dead:{minLoc:3,skipBarrels:!0,deadCodeOnly:!0},isolated:{minLoc:3},similar:{minSimilarity:.6,limit:50,minCallees:4},duplicateBodies:{maxLoc:15,limit:50},extract:{minLoc:15,minCallees:5,limit:50},wrappers:{maxLoc:15,limit:50},passthroughs:{maxLoc:15,limit:50},stale:{minLoc:3,limit:50},drift:{},twinDrift:{minSimilarity:.3}};import{existsSync as zW}from"fs";import{isAbsolute as qW,join as KW}from"path";var GW=".codebaseiq-baseline.json";function rf(e){if(e.startsWith("similar:")){let t=e.slice(8).split("|");return t.length!==2?e:`similar:${t.map(N).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(N).sort().join("|")}`}return e}function of(e,t){return t&&qW(t)?t:KW(e.config.projectRoot,t??GW)}function TI(e,t,n={}){let r=of(e,n.path);if(!zW(r))throw new Error(`No baseline found at ${r}. Create one with: codebaseiq health --write-baseline`);let o=(JSON.parse(dt(r,"health baseline")).findings??[]).map(rf),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 vs from"path";function xs(e,t){let{scope:n,minDeviation:r=5,limit:i=50}=t??{},o=t?.semantic!==!1,s=t?.includePatternDeviations===!0,c=new U(e).fileDependencyGraph(n),l=ns(e,{scope:n}),u=XW([...WW(e,c,{scope:n,semantic:o}),...JW(l.forbiddenEdges),...s?YW(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 WW(e,t,n){let r=e2(e,n.scope),i=[],o=new Set;for(let[a,c]of t){if(Cs(a))continue;let l=r.get(a)??new Set;for(let u of c)Cs(u)||l.has(u)||VW(e,a,u,n)||(i.push({file:a,dep:u}),o.add(a))}o.size>0&&r2(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 VW(e,t,n,r){return s2(e,t,n)||a2(e,t,n)||i2(n)||l2(e,t,n)||c2(n)?!0:r.semantic&&o2(e,t,n)}function JW(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 YW(e,t){let n=[];for(let[r,i]of QW(e)){let o=i.filter(a=>!Cs(a));if(o.length<t)continue;let s=ZW(e,o);for(let a of o)for(let c of e.get(a)??[])Cs(c)||(s.get(c)??0)===1&&vs.dirname(c)!==r&&vs.dirname(c)!==vs.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 XW(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 QW(e){let t=new Map;for(let n of e.keys()){let r=vs.dirname(n),i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function ZW(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])Cs(i)||n.set(i,(n.get(i)??0)+1);return n}function e2(e,t){let n=new Map;return t2(e,n,t),n}function t2(e,t,n){for(let r of n2(e,n))kI(e,t,r.from_file,r.to_file)}function n2(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
454
- FROM mentions m
455
- JOIN chunks c ON m.chunk_id = c.id
456
- JOIN documents d1 ON c.document_id = d1.id
457
- JOIN global_symbols gs ON m.symbol_id = gs.id
458
- JOIN (
459
- SELECT m2.symbol_id, c2.document_id
460
- FROM mentions m2
461
- JOIN chunks c2 ON m2.chunk_id = c2.id
462
- WHERE m2.role = 1
463
- GROUP BY m2.symbol_id
464
- ) sym_def ON sym_def.symbol_id = gs.id
465
- JOIN documents d2 ON sym_def.document_id = d2.id
466
- WHERE d1.id != d2.id
467
- AND m.role != 1
468
- ${e.pathExclusionsFor("d1","d2")}
469
- ${n}`,...r)}function r2(e,t,n={}){new U(e).scanSourceReferences({paths:n.paths??me(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},i=>{i.target.relativePath!==i.sourceFile&&(e.isIgnored(i.target.relativePath)||kI(e,t,i.sourceFile,i.target.relativePath))})}function kI(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 i2(e){return e.includes("types")||e.endsWith(".d.ts")}function o2(e,t,n){let r=Mo(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.isUsed)}function s2(e,t,n){let r=Ce(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.used)}function a2(e,t,n){let r=Ce(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.every(i=>i.isTypeOnly===!0)}function c2(e){return e.endsWith(".vue")}function l2(e,t,n){let r=Ce(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 Cs(e){let t=J(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||u2(vs.basename(e)))}function u2(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 Rs(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 U(e),u=l.scopedDefinitions(n),d=x2(l,n),m={high:0,medium:1,low:2};return Ut({candidates:()=>d2(e,l,u,{minLoc:r,maxLoc:i}),orderCandidates:(f,p)=>de(p)-de(f)||f.relativePath.localeCompare(p.relativePath),scanLimit:a,profile:{name:"stale-abstractions"},prepare:f=>{let p=f2(f),g=m2(e,l,f,p,{semantic:c}),h=f.filter(b=>{if(g.incompleteSymbolIds.has(b.symbolId)||g.unavailableSymbolIds.has(b.symbolId)||l.hasSuppressionComment(b))return!1;let S=Jc(e,b,g.consumerFileMap,p);return S.realConsumers.length<=1&&!S.transitivelyReachable&&AI(b,S.realConsumers.length,d)});return{...g,singletonBackedClassIds:h2(e,l,u,h,{semantic:c}),candidateIndex:p}},evaluate:(f,p)=>{if(p.incompleteSymbolIds.has(f.symbolId)||p.unavailableSymbolIds.has(f.symbolId)||l.hasSuppressionComment(f)||p.singletonBackedClassIds.has(f.symbolId))return null;let g=Jc(e,f,p.consumerFileMap,p.candidateIndex);if(g.transitivelyReachable||g.realConsumers.length>1||g.realConsumers.length===0&&g.barrelConsumers>0||!AI(g.definition,g.realConsumers.length,d))return null;let h=p2(e,g);return!s&&h.confidence==="low"?null:h},orderResults:(f,p)=>m[f.confidence]-m[p.confidence]||p.loc-f.loc||f.file.localeCompare(p.file)||f.startLine-p.startLine,limit:o})}function d2(e,t,n,r){return n.filter(i=>i.isTypeLike&&de(i)>=r.minLoc).filter(i=>de(i)<=r.maxLoc).filter(i=>!e.isIgnored(i.relativePath)).filter(i=>!i.relativePath.endsWith(".d.ts")).filter(i=>J(i.relativePath)!=="test").filter(i=>!qe(e,i.symbol,i.relativePath)).filter(i=>!R2(i.symbol))}function FI(e,t,n,r){return yr(bn(e,t).forDefinitions(n,{semantic:r.semantic,sourceFallback:r.sourceFallback}))}function m2(e,t,n,r,i){let o=FI(e,t,n,{semantic:!1,sourceFallback:!1}),s=n.filter(m=>{let f=Jc(e,m,o,r);return f.realConsumers.length<=1&&!(f.realConsumers.length>0&&sf(m.relativePath))}),a=bn(e,t).forDefinitions(s,{semantic:i.semantic,sourceFallback:!1}),c=new Set([...a.values()].filter(m=>m.semanticIncomplete).map(m=>m.definition.symbolId)),l=new Set([...a.values()].filter(m=>m.semanticUnavailable).map(m=>m.definition.symbolId)),u=i.semantic&&s.length>0?Ar(o,yr(a)):o,d=s.filter(m=>Jc(e,m,u,r).realConsumers.length<=1);return{consumerFileMap:Ar(u,FI(e,t,d,{semantic:!1,sourceFallback:!0})),incompleteSymbolIds:c,unavailableSymbolIds:l}}function f2(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=Y(n.symbol);i&&r.set(i,n)}return t}function Jc(e,t,n,r){let o=[...n.get(t.symbolId)??new Set].filter(u=>u!==t.relativePath&&!e.isIgnored(u)),{realConsumers:s,barrelConsumers:a,importOnlyConsumers:c}=Tc(e,t,o),l=I2(e,t,n,r);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:l}}function p2(e,t){let n=_I(e,t.definition.relativePath,t.definition.startLine),r=sf(t.definition.relativePath)?!0:E2(e,t.definition),{confidence:i,reason:o}=w2(t.realConsumers.length,n,r),s=g2(t.realConsumers.length,n,r);return{symbol:t.definition.symbol,shortName:N(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:de(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:r,confidence:i,reason:o,actionTier:s.actionTier,stalenessKind:s.stalenessKind,recommendation:s.recommendation}}function g2(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 h2(e,t,n,r,i){let o=b2(e,y2(n),r),s=o.map(u=>u.singleton);if(o.length===0)return new Set;let a=bn(e,t).forDefinitions(s,{semantic:i.semantic,sourceFallback:!0}),c=yr(a),l=new Set;for(let{singleton:u,classId:d}of o){let m=a.get(u.symbolId);(m?.semanticIncomplete||m?.semanticUnavailable||v2(e,u,c))&&l.add(d)}return l}function y2(e){let t=new Map;for(let n of e){let r=Y(n.symbol);r&&t.set(NI(n.relativePath,r),n)}return t}function b2(e,t,n){let r=[];for(let i of n){let o=S2(e,t,i);o&&r.push({singleton:o,classId:i.symbolId})}return r}function S2(e,t,n){if(_I(e,n.relativePath,n.startLine)!=="class")return null;let r=Y(n.symbol);if(!r)return null;let i=C2(e,n.relativePath,r);return i?t.get(NI(n.relativePath,i))??null:null}function v2(e,t,n){let r=Y(t.symbol),i=n.get(t.symbolId);return!r||!i?!1:[...i].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!bm(e,o,r))}function NI(e,t){return`${e}\0${t}`}function C2(e,t,n){let r=se(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 x2(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function R2(e){let t=Vn(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 sf(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 AI(e,t,n){return!(sf(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function I2(e,t,n,r){let i=lp(e,t.relativePath),o=Y(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 _I(e,t,n){let r=se(e,t);if(!r)return"other";let i=r.split(`
470
- `),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 E2(e,t){let n=se(e,t.relativePath);if(!n)return!1;let r=Y(t.symbol);if(!r)return!1;let i=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${i}\\b`),s=n.split(`
471
- `);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function w2(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 qi,extname as Yc}from"path";function Is(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new U(e),a=k2(s.fileDependencyGraph(n));return Ut({candidates:()=>P2(e,s,n,r),orderCandidates:ec,scanLimit:o,profile:{name:"wrapper-candidates"},prepare:c=>({...L2(e,s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>D2(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:i})}function L2(e,t,n,r){let i=bn(e,t),o=yr(i.forDefinitions(n,{semantic:!1,sourceFallback:!1})),s=[];r.semantic&&O("wrapper.semantic-candidates",()=>{s=n.filter(h=>af(e,t,h,o).length<=1)},()=>({symbols:n.length,semanticCandidates:s.length}));let a=i.forDefinitions(s,{semantic:!0,sourceFallback:!1}),c=yr(a),l=new Set([...a.values()].filter(h=>h.semanticIncomplete).map(h=>h.definition.symbolId)),u=new Set([...a.values()].filter(h=>h.semanticUnavailable).map(h=>h.definition.symbolId)),d=c.size===0?o:Ar(o,c),m=new Map(n.map(h=>[h.symbolId,h])),f=new Map;for(let h of n){let b=af(e,t,h,d);if(b.length>1||(f.set(h.symbolId,h),b.length!==1))continue;let S=b[0],y=OI(e,h.symbolId,S);if(!y)continue;let E=BI(t,e,S,h.symbol,y);E?.isFunctionLike&&m.has(E.symbolId)&&f.set(E.symbolId,m.get(E.symbolId))}let p=[...f.values()];return{callerFileMap:p.length===0?d:Ar(d,yr(i.forDefinitions(p,{semantic:!1,sourceFallback:!0}))),incompleteSymbolIds:l,unavailableSymbolIds:u}}function D2(e,t,n,r){if(r.incompleteSymbolIds.has(n.symbolId)||r.unavailableSymbolIds.has(n.symbolId))return null;let i=af(e,t,n,r.callerFileMap);if(i.length!==1)return null;let o=i[0],s=OI(e,n.symbolId,o);if(!s)return null;let a=BI(t,e,o,n.symbol,s);if(a&&ai(a.symbol))return null;let{fanIn:c,source:l}=M2(r.callerFileMap,r.reverseFanIn,o,a);if(l==="function"?c<=3:c<=5)return null;let u=A2(e,n,o,a);return{symbol:n.symbol,shortName:N(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:de(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?N(a.symbol):qi(o),callerFanIn:c,actionTier:u.length>0?"signal":"direct",boundaryEvidence:u}}function P2(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 af(e,t,n,r){let i=qi(n.relativePath,Yc(n.relativePath)),o=[...r.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>qi(s,Yc(s))!==i).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return Tc(e,n,o).realConsumers}function OI(e,t,n){return e.get(`SELECT c.start_line, c.end_line
472
- FROM mentions m
473
- JOIN chunks c ON m.chunk_id = c.id
474
- JOIN documents d ON c.document_id = d.id
475
- WHERE m.symbol_id = ? AND m.role != 1 AND d.relative_path = ?
476
- LIMIT 1`,t,n)}function BI(e,t,n,r,i){let o=e.definitionsForFile(n),s=T2(t,n,r,i.start_line,i.end_line);return Ke(o,s)}function M2(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:F2(t,n),source:"file"}}function T2(e,t,n,r,i){let o=Y(n);if(!o)return r;let s=ui(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 k2(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 F2(e,t){let n=e.get(t)??0;if(n>0)return n;let r=qi(t,Yc(t)),i=0;for(let[o,s]of e)o!==t&&qi(o,Yc(o))===r&&s>i&&(i=s);return i}function A2(e,t,n,r){return Uc(e,t.relativePath,t.startLine,"wrapper","explicit ignore-wrapper comment",[{label:"wrapper name",value:N(t.symbol)},{label:"caller name",value:r?.symbol?N(r.symbol):qi(n)},{label:"wrapper path",value:t.relativePath},{label:"caller path",value:n}])}var N2=25e3,_2=2500,O2=2500;function B2(e){let t=Nr(e);return t.symbols>=N2||t.documents>=_2?O2:void 0}function cf(e,t={}){let{scope:n}=t,r=B2(e),i=[],o=Wr(e,{scope:n,...je.dead,scanLimit:r});for(let s of o.symbols)Qe(e,s.relativePath)||qe(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&i.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of rs(e,{scope:n,...je.isolated,scanLimit:r}))Qe(e,s.relativePath)||qe(e,s.symbol,s.relativePath)||i.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of ts(e,{scope:n}))s.kind==="real"&&i.push(`cycle:${$2(s.path)}`);for(let s of as(e,{scope:n,...je.similar,scanLimit:r}))i.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of hs(e,{scope:n,...je.duplicateBodies,scanLimit:r}))i.push(`duplicate-bodies:${s.hash}:${s.functions.map(a=>a.symbol).sort().join("|")}`);for(let s of ms(e,{scope:n,...je.extract,scanLimit:r}))i.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of Is(e,{scope:n,...je.wrappers,scanLimit:r}))i.push(`wrapper:${s.file}:${s.shortName}`);for(let s of ys(e,{scope:n,...je.passthroughs,scanLimit:r}))i.push(`passthrough:${s.file}:${s.shortName}`);for(let s of Rs(e,{scope:n,...je.stale,scanLimit:r}))i.push(`stale:${s.file}:${s.shortName}`);for(let s of xs(e,{scope:n,...je.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY}).results)s.kind!=="architecture-violation"&&i.push(`drift:${s.kind}:${s.file}:${s.dep}`);return i.push(...am(ns(e,{scope:n}))),[...new Set(i.map(rf))].sort()}function $2(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 j2(e,t={}){let n=cf(e,{scope:t.scope}),r=of(e,t.path);return zf(r,{version:1,findings:n},{spacing:2,trailingNewline:!0}),{path:r,findingCount:n.length}}function H2(e,t={}){return TI(e,cf(e,{scope:t.scope}),{path:t.path})}function U2(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new U(e);return Ut({candidates:()=>o.productionCallableDefinitions({scope:n,files:t.files,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}),filterCandidate:s=>z2(s.relativePath),scanLimit:i,profile:{name:"unused-params"},evaluate:s=>{let a=te(e,s.relativePath)?.callables.find(u=>u.startLine===s.startLine&&u.endLine===s.endLine);if(!a||a.params.length===0||a.params.some(u=>!u.simple)||a.paramsEndLine>=a.endLine)return null;let c=ui(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("_")||q2(c.get(d.name),a.paramsEndLine,a.endLine))break;l.unshift(d.name)}return l.length===0?null:{symbol:s.symbol,shortName:N(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 z2(e){let t=ye(e);return t==="typescript"||t==="tsx"||t==="javascript"}function q2(e,t,n){return e?e.some(r=>r>t&&r<=n):!1}var K2=new Set(an());function lf(e,t){let{scope:n,minLoc:r=10,limit:i=30,scanLimit:o}=t??{},s=new U(e),a=t?.semantic!==!1,c=$I(a,new Set,new Set);return{rows:Ut({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:r,requireFunctionLikeSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,filterCandidate:G2,profile:{name:"complexity-hotspots"},prepare:u=>{let d=V2(e,u);(a?$t(e):null)?.materializeReferences(u,{prefetchCallees:!0});let f=cn(e,u,{semantic:a,semanticEvidence:ge}),p=s.calleeEvidenceMap(u,{semantic:a}),g=new Set([...f.incompleteSymbolIds,...p.incompleteSymbolIds]),h=new Set([...f.unavailableSymbolIds,...p.unavailableSymbolIds]);c=$I(a,g,h);let b=new Map(u.map(S=>[S.symbolId,S]));return{callerMap:new Map([...f.rows].map(([S,y])=>[S,new Set(y.filter(E=>E.file!==b.get(S)?.relativePath).map(E=>E.file))])),calleeMap:p.rows,incompleteSymbolIds:g,unavailableSymbolIds:h,languageByFile:d,clojureCallableIds:J2(e,u,d),branchEstimates:gI(e,u)}},evaluate:(u,d)=>d.incompleteSymbolIds.has(u.symbolId)||d.unavailableSymbolIds.has(u.symbolId)?null:W2(u,d,r),orderResults:(u,d)=>d.score-u.score||d.loc-u.loc,limit:i}),coverage:c}}function $I(e,t,n){let r=new Set([...t,...n]).size,i=e?t.size>0&&n.size>0?"incomplete-and-unavailable":t.size>0?"incomplete":n.size>0?"unavailable":"complete":"disabled";return{semanticEvidence:{enabled:e,status:i,incompleteSymbolCount:t.size,unavailableSymbolCount:n.size,excludedSymbolCount:r}}}function G2(e){return e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&K2.has(e.kind):!0}function W2(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 f=`${m.symbol}|${m.file}`;s.add(f),m.file!==e.relativePath&&a.add(f)}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:N(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 V2(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
477
- FROM documents
478
- WHERE relative_path IN (${r})`,...n);return new Map(i.map(o=>[o.relative_path,o.language?.toLowerCase()??null]))}function J2(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((te(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 Y2}from"fs";import{basename as X2,join as jI}from"path";function Q2(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 Z2(e,t){let n=eV(e,t.file,t.keys);if(!n.ok)return{name:t.name,file:t.file,status:"unavailable",missing:[],extra:[],unavailableReason:n.reason};let r=sV(e.config.projectRoot,t.mustEqual),i=Q2(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 UI(e,t){return t.map(n=>Z2(e,n))}function eV(e,t,n){return n.type==="markdown-list"?oV(e,t,n.marker):tV(e,t,n)}function tV(e,t,n){if(!se(e,t))return{ok:!1,reason:`file not found: ${t}`};let i=ye(t);if(!i)return{ok:!1,reason:`unsupported file type for ${n.type} extraction: ${t}`};let o=ae(e,t);if(!o)return{ok:!1,reason:`tree-sitter parser unavailable for ${i} (${t}) \u2014 contract skipped, not silently passed`,disclosedUnavailable:{language:i,reason:"parser-unavailable"}};let s=n.type==="object-literal-keys"?nV(o,n.identifier):iV(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 zI(e){let t=e.childForFieldName("value");return t?t.type==="as_expression"||t.type==="satisfies_expression"?t.namedChild(0):t:null}function nV(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=zI(n);if(i?.type==="object")return rV(i)}return null}function rV(e){let t=new Set;for(let n of e.namedChildren)if(n.type==="pair"){let r=n.childForFieldName("key");r&&t.add(qI(r.text))}else n.type==="shorthand_property_identifier"&&t.add(n.text);return[...t].sort()}function iV(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=zI(n);if(i?.type!=="array")continue;let o=new Set;for(let s of i.namedChildren)s.type==="string"&&o.add(qI(s.text));return[...o].sort()}return null}function qI(e){return e.length>=2&&(e[0]==="'"&&e.endsWith("'")||e[0]==='"'&&e.endsWith('"'))?e.slice(1,-1):e}function oV(e,t,n){let r=se(e,t);if(!r)return{ok:!1,reason:`file not found: ${t}`};let i=KI(r,n);return i===null?{ok:!1,reason:`no <!-- BEGIN GENERATED ${n} --> ... <!-- END GENERATED ${n} --> block in ${t}`}:{ok:!0,keys:GI(i)}}function KI(e,t){let n=Be(t),i=new RegExp(`<!--\\s*BEGIN GENERATED ${n}\\s*-->([\\s\\S]*?)<!--\\s*END GENERATED ${n}\\s*-->`).exec(e);return i?i[1]:null}function GI(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 sV(e,t){switch(t.type){case"top-level-dirs":return HI(jI(e,t.path));case"file-glob":return[...new Set(wc(e,t.pattern).map(n=>X2(n)))].sort();case"registered-commands":return aV(e);case"builtin-skills":return HI(jI(e,"skills"))}}function HI(e){let t;try{t=Y2(e,{withFileTypes:!0})}catch{return[]}return t.filter(n=>n.isDirectory()&&!n.name.startsWith(".")).map(n=>n.name).sort()}function aV(e){let t;try{t=it(e,"docs/COMMAND_REFERENCE.md",{maxBytes:8*1024*1024,inputKind:"generated command reference"})}catch(r){if(!ot(r))throw r;return[]}let n=KI(t,"COMMAND REFERENCE");return n?GI(n):[]}function Un(e){return e.scoreCount??e.count}function JI(e){let t=mV(e),{breakdown:n,pressure:r}=fV(e),i=VI(n,"risk"),o=VI(n,"hygiene"),s=cV(e),a=[...e.warnings];e.complexity.coverage.semanticEvidence.excludedSymbolCount>0&&a.push(`Complexity scoring excluded ${e.complexity.coverage.semanticEvidence.excludedSymbolCount} symbol(s) with incomplete or unavailable compiler evidence.`);let c=e.evidenceCoverage.filter(l=>l.semanticEvidence.status!=="complete"&&l.semanticEvidence.status!=="disabled");return c.length>0&&a.push(`Compiler-resolved evidence was incomplete or unavailable in health phase(s): ${c.map(l=>l.phase).join(", ")}.`),{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:Un(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:Un(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:Un(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:lV(e),validation:dV(e),suppressions:e.suppressions,actions:t,pressure:r,topComplexity:e.complexity.top,coverage:s,warnings:a.length>0?a:void 0}}function cV(e){let t=e.complexity.coverage.semanticEvidence.status;return{status:e.evidenceCoverage.some(r=>r.semanticEvidence.status!=="complete"&&r.semanticEvidence.status!=="disabled")?"incomplete":t==="disabled"?"semantic-disabled":t==="complete"?"complete":"incomplete",complexity:e.complexity.coverage,phases:e.evidenceCoverage}}function lV(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:uV(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 uV(e){let t=e.gitEvidence?.fileStats;return t?e.complexity.top.map(n=>{let r=n.file?t[n.file]?.changes??0:0;return{...n,changes:r,weighted:Cn(n.score*Math.log2(1+r))}}).sort((n,r)=>r.weighted-n.weighted):null}function dV(e){let t=e.gitEvidence?.fileStats;if(!t)return null;let n={dead:e.dead.files??[],isolated:e.isolated.files??[],twinDrift:e.twinDrift.files??[],wrappers:e.wrappers.files??[],passthroughs:e.passthroughs.files??[],stale:e.stale.files??[],reactComponents:e.reactComponentDuplicates.files??[],reactHooks:e.reactHookCandidates.files??[],reactLargeComponents:e.reactLargeComponentPressure.files??[],vueComponents:e.vueComponentDuplicates.files??[],vueComposables:e.vueComposableCandidates.files??[],vueLargeViews:e.vueLargeViewPressure.files??[]},r=new Set(Object.values(n).flat()),i=0,o=0,s=0;for(let[u,d]of Object.entries(t))r.has(u)?i+=d.fixChanges:(o+=d.fixChanges,s+=1);let a=r.size>0?Cn(i/r.size):0,c=s>0?Cn(o/s):0,l={};for(let[u,d]of Object.entries(n)){let m=new Set(d);if(m.size===0)continue;let f=0;for(let g of m)f+=t[g]?.fixChanges??0;let p=Cn(f/m.size);l[u]={flaggedFiles:m.size,fixDensity:p,lift:c>0?Cn(p/c):null}}return{flaggedFiles:r.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:r.size>0&&c>0?Cn(a/c):null,byCategory:l,validationBasis:{method:"subject-regex",commitsScanned:e.gitEvidence?.commitsScanned??0}}}function Cn(e){return Math.round(e*100)/100}function YI(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function Xc(e,t="existing shared infrastructure discount"){let n=Un(e);return Math.abs(n-e.count)<.01?"":` (${YI(n)} score-weighted after ${t})`}function Es(e,t){let n=Un(e),r=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?r:`${r} (${YI(n)} score-weighted)`}function mV(e){let t=[];if(e.dead.count>0&&t.push({category:"Dead code",evidence:"graph-fact",description:`${e.dead.count} indexed symbols with no visible repository references \u2014 review runtime/framework roots and the capability disclosure, then verify any deletion with cleanup-plan --verify`,effort:"low",impact:"high",count:e.dead.count,locRecoverable:e.dead.loc}),e.isolated.count>0&&t.push({category:"Isolated symbols",evidence:"graph-fact",description:`${e.isolated.count} symbols completely disconnected from the codebase graph`,effort:"low",impact:"medium",count:e.isolated.count,locRecoverable:e.isolated.loc}),e.realCycleCount>0&&t.push({category:"Circular dependencies",evidence:"graph-fact",description:`${e.realCycleCount} indexed dependency cycle(s) \u2014 inspect ownership and runtime order before choosing whether or how to break them`,effort:"medium",impact:"high",count:e.realCycleCount,locRecoverable:0}),e.similarCount>0&&t.push({category:"Similar functions",evidence:"heuristic",description:`${e.similarCount} pairs share disclosed call or source-token evidence beyond imports \u2014 review domain identity before considering consolidation`,effort:"medium",impact:"medium",count:e.similarCount,locRecoverable:0}),e.duplicateBodies.count>0&&t.push({category:"Duplicate function bodies",evidence:"heuristic",description:`${e.duplicateBodies.count} exact small-body group(s) across files \u2014 consolidate only when the domain concept matches`,effort:"low",impact:"medium",count:e.duplicateBodies.count,locRecoverable:e.duplicateBodies.loc}),e.twinDrift.count>0&&t.push({category:"Drifted twin implementations",evidence:"heuristic",description:`${e.twinDrift.count} same-name (or near-name) function group(s) across files with diverged or identical bodies \u2014 determine whether they represent the same concept before acting`,effort:"medium",impact:"medium",count:e.twinDrift.count,locRecoverable:0}),e.reactComponentDuplicates.count>0&&t.push({category:"Duplicated React components",evidence:"heuristic",description:`${e.reactComponentDuplicates.count} React component pair(s) share JSX structure \u2014 review whether local product intent justifies reuse`,effort:"medium",impact:"medium",count:e.reactComponentDuplicates.count,locRecoverable:e.reactComponentDuplicates.loc}),e.reactHookCandidates.count>0&&t.push({category:"Duplicated React hook behavior",evidence:"heuristic",description:`${e.reactHookCandidates.count} React component pair(s) share state/effect/request behavior${Xc(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${Xc(e.vueComposableCandidates)} \u2014 review whether a common composable would preserve ownership and lifecycle semantics`,effort:"medium",impact:"medium",count:e.vueComposableCandidates.count,locRecoverable:e.vueComposableCandidates.loc}),e.vueLargeViewPressure.count>0&&t.push({category:"Large Vue views",evidence:"heuristic",description:`${e.vueLargeViewPressure.count} Vue file(s) concentrate template/script/style pressure \u2014 split by reason to change`,effort:"medium",impact:"medium",count:e.vueLargeViewPressure.count,locRecoverable:0}),e.extractCount>0&&t.push({category:"Extraction candidates",evidence:"heuristic",description:`${e.extractCount} large functions with isolated callee clusters \u2014 review same-file or feature-local extraction seams`,effort:"medium",impact:"medium",count:e.extractCount,locRecoverable:0}),e.wrappers.count>0&&t.push({category:"Wrapper functions",evidence:"heuristic",description:`${e.wrappers.count} single-consumer symbols${Xc(e.wrappers,"boundary-evidence discount")} \u2014 inspect whether each is indirection or an intentional API, framework, or ownership boundary`,effort:"low",impact:"low",count:e.wrappers.count,locRecoverable:e.wrappers.loc}),e.passthroughs.count>0&&t.push({category:"Passthrough functions",evidence:"heuristic",description:`${e.passthroughs.count} functions that literally forward to one callee \u2014 inspect whether each is unnecessary indirection or an intentional boundary`,effort:"low",impact:"low",count:e.passthroughs.count,locRecoverable:e.passthroughs.loc}),e.stale.count>0){let 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",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 \`codebaseiq health --json\` for the missing/extra keys`,effort:"low",impact:"medium",count:e.coverageContracts.count,locRecoverable:0}),e.gitEvidence&&e.gitEvidence.hiddenCoupling.pairCount>0){let 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`+Xc({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 WI={"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 VI(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 fV(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),r=[],i=[],o=(x,C,L)=>{C>0&&r.push({axis:x,points:C,detail:L,kind:WI[x]??"hygiene"})},s=(x,C,L,w,R,P,_)=>{let D=Math.max(w,1);if(L<=D)return;let M=L/D,F=Math.min(R,Math.ceil(Math.log2(M)*P));if(F<=0)return;let V=WI[x]??"hygiene";i.push({axis:x,category:C,kind:V,count:L,threshold:Cn(D),ratio:Cn(M),extraPenalty:F}),o(x,F,`${L} ${_} exceed pressure threshold ${Cn(D)} (${Cn(M)}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 f=Un(e.reactHookCandidates),p=f/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(p)),Es(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=Un(e.vueComposableCandidates),S=b/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(S)),Es(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 E=Un(e.wrappers);o("wrappers",Math.min(3,E),Es(e.wrappers,"wrapper candidate(s)"));let I=Un(e.passthroughs);o("passthroughs",Math.min(3,I),Es(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 v=e.drift.direct/t;if(o("drift",Math.min(5,Math.round(v*50)),`${e.drift.direct} direct drift finding(s); ${e.drift.signal} signal drift finding(s)`),o("complexity",Math.min(5,e.complexity.extremeCount*2),`${e.complexity.extremeCount} extreme complexity hotspot(s)`),e.gitEvidence){let x=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(x/10)),Es({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:x},"co-changing pair(s) without a structural link"))}if(s("cycles-pressure","Circular dependencies",e.realCycleCount,3,10,3,"cycle(s)"),s("complexity-pressure","Extreme complexity",e.complexity.extremeCount,3,5,2,"extreme complexity hotspot(s)"),e.gitEvidence){let x=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",x,50,10,4,"score-weighted co-changing pair(s)")}return s("similar-pressure","Similar functions",e.similarCount,Math.max(50,n*.01),8,4,"similar function pair(s)"),s("duplicate-bodies-pressure","Duplicate function bodies",e.duplicateBodies.count,Math.max(20,n*.005),8,4,"exact duplicate small-body group(s)"),s("twin-drift-pressure","Drifted twin implementations",e.twinDrift.count,Math.max(20,n*.005),8,4,"drifted twin implementation group(s)"),s("react-component-duplicates-pressure","Duplicated React components",e.reactComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated React component pair(s)"),s("react-hook-candidates-pressure","Duplicated React hook behavior",f,Math.max(10,t*.01),8,4,"duplicated React behavior pair(s)"),s("react-large-component-pressure-pressure","Large React components",e.reactLargeComponentPressure.count,Math.max(10,t*.01),4,2,"large React component pressure file(s)"),s("vue-component-duplicates-pressure","Duplicated Vue components",e.vueComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated Vue component pair(s)"),s("vue-composable-candidates-pressure","Duplicated Vue behavior",b,Math.max(10,t*.01),8,4,"duplicated Vue behavior pair(s)"),s("vue-large-view-pressure-pressure","Large Vue views",e.vueLargeViewPressure.count,Math.max(10,t*.01),4,2,"large Vue view pressure file(s)"),s("extract-pressure","Extraction candidates",e.extractCount,Math.max(50,n*.01),4,2,"extraction candidate(s)"),s("wrappers-pressure","Wrapper functions",E,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",I,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 pV}from"v8";var gV=64*1024*1024;function uf(){let e=globalThis.gc;if(!e)return;let t=pV();t.heap_size_limit-t.used_heap_size<gV||e()}var hV=50,yV=25e3,bV=2500,XI=2500,QI=50,SV=10,Qc=["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"],vV={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:EV(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:wV(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:LV(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:DV(e,t,n)}),"duplicate-bodies":(e,t,n)=>({phase:"duplicate-bodies",duplicateBodies:MV(e,t,n)}),"twin-drift":(e,t,n)=>({phase:"twin-drift",twinDrift:TV(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:kV(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:FV(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:AV(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:NV(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:_V(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:OV(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:PV(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:BV(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:$V(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:jV(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:qV(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:KV(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:HV(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:UV(e,n)}),"coverage-contracts":(e,t,n)=>({phase:"coverage-contracts",coverageContracts:zV(e,n)})};function df(e,t,n={}){return CV(e,[t],n)[0]}function CV(e,t,n={}){return xV(e,n.full!==!1,(r,i)=>{let o={...i,releaseCachesBetweenPhases:!1};return t.map(s=>IV(e,s,n.scope,o,r))})}function xV(e,t,n){let r=Nr(e),i=GV(r,t);try{return n(r,i)}finally{im(e,{semanticProvider:!0}),uf()}}function mf(e){return JI(RV(e))}function RV(e){let t=ze(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,evidenceCoverage:e.map(r=>({phase:r.phase,semanticEvidence:r.evidenceCoverage})),dead:ze(e,"dead").dead,isolated:ze(e,"isolated").isolated,realCycleCount:ze(e,"cycles").realCycleCount,similarCount:ze(e,"similar").similarCount,duplicateBodies:ze(e,"duplicate-bodies").duplicateBodies,twinDrift:ze(e,"twin-drift").twinDrift,reactComponentDuplicates:ze(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:ze(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:ze(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:ze(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:ze(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:ze(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:ze(e,"extract-candidates").extractCount,wrappers:ze(e,"wrapper-candidates").wrappers,passthroughs:ze(e,"passthrough-candidates").passthroughs,stale:ze(e,"stale-abstractions").stale,drift:ze(e,"drift").drift,complexity:ze(e,"complexity-hotspots").complexity,gitEvidence:ZI(e,"git-evidence")?.gitEvidence??null,suppressions:ZI(e,"suppressions")?.suppressions??null,coverageContracts:ze(e,"coverage-contracts").coverageContracts}}function ZI(e,t){return e.find(n=>n.phase===t)}function ze(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function IV(e,t,n,r,i){jy(e);let o=vV[t](e,n,r,i),s=Hy(e),a=s.incompleteSymbolIds.size,c=s.unavailableSymbolIds.size,l=r.semantic?a>0&&c>0?"incomplete-and-unavailable":a>0?"incomplete":c>0?"unavailable":"complete":"disabled";return{...o,evidenceCoverage:{enabled:r.semantic,status:l,incompleteSymbolCount:a,unavailableSymbolCount:c}}}function EV(e,t,n){return He(e,n,"dead",()=>{let r=Wr(e,{scope:t,...je.dead,scanLimit:n.candidateScanLimit,semantic:n.semantic});return Zc(JV(e,r.symbols))})}function wV(e,t,n){return He(e,n,"isolated",()=>{let r=rs(e,{scope:t,...je.isolated,scanLimit:n.candidateScanLimit,semantic:n.semantic});return Zc(YV(e,r))})}function LV(e,t,n){return He(e,n,"cycles",()=>ts(e,{scope:t}).filter(i=>i.kind==="real").length)}function DV(e,t,n){let r=He(e,n,"similar",()=>pm(e,{scope:t,...je.similar,scanLimit:n.candidateScanLimit,semantic:n.semantic}));return Math.min(r,n.candidateResultLimit)}function PV(e,t,n){return He(e,n,"extract-candidates",()=>ms(e,{scope:t,...je.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}).length)}function MV(e,t,n){return He(e,n,"duplicate-bodies",()=>{let r=hs(e,{scope:t,...je.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 TV(e,t,n){return He(e,n,"twin-drift",()=>{let r=Hc(e,{scope:t,...je.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 kV(e,t,n){return He(e,n,"react-component-duplicates",()=>{let r=cs(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return ff(r)})}function FV(e,t,n){return He(e,n,"react-hook-candidates",()=>{let r=ls(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return nE(r,QV)})}function AV(e,t,n){return He(e,n,"react-large-component-pressure",()=>{let r=gm(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return XV(r)})}function NV(e,t,n){return He(e,n,"vue-component-duplicates",()=>{let r=us(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return ff(r)})}function _V(e,t,n){return He(e,n,"vue-composable-candidates",()=>{let r=ds(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return nE(r,ZV)})}function OV(e,t,n){return He(e,n,"vue-large-view-pressure",()=>{let r=hm(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Zc(r)})}function BV(e,t,n){return He(e,n,"wrapper-candidates",()=>{let r=Is(e,{scope:t,...je.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return tE(r,eJ)})}function $V(e,t,n){return He(e,n,"passthrough-candidates",()=>{let r=ys(e,{scope:t,...je.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return tE(r,tJ)})}function jV(e,t,n){return He(e,n,"stale-abstractions",()=>{let r=Rs(e,{scope:t,...je.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 HV(e,t){return He(e,t,"git-evidence",()=>{let n=Qt(e,{historyMode:t.gitHistoryMode}),r=n.fileChurn();if(!r)return null;let i=n.commitHistory(),o=ps(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:pf(o.findings.reduce((a,c)=>a+eE(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:eE(a),subjectContext:a.subjectContext}))},fileStats:s,commitsScanned:i?.commits.length??0}})}function UV(e,t){return He(e,t,"suppressions",()=>{let n=Kc(e);return{total:n.total,byCategory:{...n.byCategory}}})}function zV(e,t){return He(e,t,"coverage-contracts",()=>{let n=e.config.coverageContracts??[],i=UI(e,n).filter(o=>o.status!=="ok");return{count:i.length,loc:0,files:[...new Set(i.map(o=>o.file))].sort()}})}function qV(e,t,n){return He(e,n,"drift",()=>{let r=xs(e,{scope:t,...je.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 KV(e,t,n){return He(e,n,"complexity-hotspots",()=>{let r=lf(e,{scope:t,minLoc:10,limit:n.complexityResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return{top:r.rows.slice(0,5).map(i=>({symbol:i.shortName,score:i.score,file:i.file})),extremeCount:r.rows.filter(i=>i.score>hV).length,coverage:r.coverage}})}function GV(e,t){let n=e.symbols>=yV||e.documents>=bV,r=t?Number.POSITIVE_INFINITY:QI,i=t?Number.POSITIVE_INFINITY:SV;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:XI,candidateResultLimit:r,complexityResultLimit:i,semantic:!1,gitHistoryMode:"bounded",releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${XI} symbols and reported their top ${QI} findings. Enable full mode for unbounded candidate counts.`]}}function WV(e,t){t.releaseCachesBetweenPhases&&(im(e),uf())}function He(e,t,n,r){VV(n);try{return r()}finally{WV(e,t)}}function VV(e){process.env.CODEBASEIQ_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function JV(e,t){return t.filter(n=>!Qe(e,n.relativePath)&&!qe(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function YV(e,t){return t.filter(n=>!Qe(e,n.relativePath)&&!qe(e,n.symbol,n.relativePath))}function Zc(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 tE(e,t){return{...Zc(e),scoreCount:pf(e.reduce((r,i)=>r+t(i),0))}}function XV(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 ff(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 nE(e,t){return{...ff(e),scoreCount:pf(e.reduce((r,i)=>r+t(i),0))}}function QV(e){let t=e.sharedHooks.length>0,n=rE({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:iE(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function ZV(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=rE({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:iE(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function rE(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!sE.has(oE(t))).length+Math.min(e.functions.length,3)}function iE(e,t,n){let r=[...e,...t,...n].map(oE);return r.length>0&&r.every(i=>sE.has(i))}function oE(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function eJ(e){return e.actionTier==="signal"?.25:1}function tJ(e){return e.actionTier==="signal"?.25:1}function eE(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 pf(e){return Math.round(e*100)/100}var sE=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 nJ(e,t,n,r={}){let i=fm(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 rJ(e,t,n={}){let r=Zo(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 iJ=/:\d+(?:-\d+)?$/u;function oJ(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=iJ.test(t),s=Zo(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;aE(s.edges,c,l,0);for(let d=1;d<=i;d+=1){let m=[];for(let f of s.edges)if(r==="backward"?c.has(f.to.id):c.has(f.from.id)){let p=r==="backward"?f.from.id:f.to.id;if(c.has(p))continue;m.push(p),l.set(f.id,d)}if(m.length===0)break;for(let f of m)c.add(f);aE(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"&&!sJ(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 aE(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 sJ(e){return e.semanticFamily==="control"&&e.sourceKind==="control-dependence"}function aJ(e,t={}){let{scope:n,limit:r}=t,i=new U(e),o=hJ([...cJ(e,n),...dJ(e,i,n)]);return yJ(o),r?o.slice(0,r):o}function cJ(e,t){let n=[];for(let r of lJ(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||rd(e,r.barrel_path)||se(e,r.barrel_path)&&Us(e,r.barrel_path).length===0)continue;let i=uJ(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:N(r.symbol),originalFile:r.original_path,barrelConsumers:o,directConsumers:s,...lE(e,r.barrel_path)})}return n}function lJ(e,t){let n=t?"AND barrel_d.relative_path LIKE ?":"",r=t?[`%${t}%`]:[];return e.all(`WITH barrel_refs AS MATERIALIZED (
479
- SELECT DISTINCT
480
- barrel_d.id AS barrel_doc_id,
481
- barrel_d.relative_path AS barrel_path,
482
- m.symbol_id
483
- FROM documents barrel_d
484
- JOIN chunks c ON c.document_id = barrel_d.id
485
- JOIN mentions m ON m.chunk_id = c.id
486
- WHERE m.role != 1
487
- AND (barrel_d.relative_path LIKE '%/index.ts'
488
- OR barrel_d.relative_path LIKE '%/index.js'
489
- OR barrel_d.relative_path = 'index.ts'
490
- OR barrel_d.relative_path = 'index.js')
491
- ${e.pathExclusionsFor("barrel_d")}
492
- ${n}
493
- ),
494
- sym_def AS MATERIALIZED (
495
- SELECT m2.symbol_id, c2.document_id
496
- FROM barrel_refs br
497
- -- Keep the bounded barrel-symbol set on the outer side. An ordinary
498
- -- JOIN lets SQLite scan every definition mention before applying the
499
- -- barrel-symbol bloom filter on large indexes.
500
- CROSS JOIN mentions m2 ON m2.symbol_id = br.symbol_id
501
- AND m2.role = 1
502
- JOIN chunks c2 ON m2.chunk_id = c2.id
503
- GROUP BY m2.symbol_id
504
- )
505
- SELECT DISTINCT
506
- br.barrel_doc_id,
507
- br.barrel_path,
508
- gs.id AS symbol_id,
509
- gs.symbol AS symbol,
510
- orig_d.id AS original_doc_id,
511
- orig_d.relative_path AS original_path
512
- FROM barrel_refs br
513
- JOIN global_symbols gs ON br.symbol_id = gs.id
514
- JOIN sym_def ON sym_def.symbol_id = gs.id
515
- JOIN documents orig_d ON sym_def.document_id = orig_d.id
516
- WHERE orig_d.id != br.barrel_doc_id
517
- ${e.pathExclusionsFor("orig_d")}
518
- ${e.symbolNoiseFor("gs")}
519
- -- Only function-level symbols (ending with ().), not module-level
520
- AND gs.symbol LIKE '%().'
521
- ORDER BY br.barrel_path, gs.symbol`,...r)}function uJ(e,t){return e.get(`SELECT
522
- SUM(CASE WHEN uses_barrel = 1 THEN 1 ELSE 0 END) AS barrel_consumers,
523
- SUM(CASE WHEN uses_barrel = 0 THEN 1 ELSE 0 END) AS direct_consumers
524
- FROM (
525
- SELECT
526
- consumer_d.id AS consumer_doc_id,
527
- MAX(CASE WHEN EXISTS (
528
- SELECT 1
529
- FROM mentions barrel_m
530
- JOIN chunks barrel_c ON barrel_m.chunk_id = barrel_c.id
531
- WHERE barrel_c.document_id = consumer_d.id
532
- AND barrel_m.role != 1
533
- AND barrel_m.symbol_id IN (
534
- SELECT m2.symbol_id
535
- FROM mentions m2
536
- JOIN chunks c2 ON m2.chunk_id = c2.id
537
- WHERE c2.document_id = ?
538
- AND m2.role != 1
539
- )
540
- ) THEN 1 ELSE 0 END) AS uses_barrel
541
- FROM mentions ref_m
542
- JOIN chunks ref_c ON ref_m.chunk_id = ref_c.id
543
- JOIN documents consumer_d ON ref_c.document_id = consumer_d.id
544
- WHERE ref_m.symbol_id = ?
545
- AND ref_m.role != 1
546
- AND consumer_d.id != ?
547
- AND consumer_d.id != ?
548
- ${e.pathExclusionsFor("consumer_d")}
549
- GROUP BY consumer_d.id
550
- )`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function dJ(e,t,n){let r=[],i=gJ(e);for(let o of mJ(e,n))uE(i,o,o)>0||r.push(...fJ(e,t,o,i));return r}function mJ(e,t){return me(e,{scope:t,includeIgnored:!1}).filter(n=>Us(e,n).length>0||Xi(e,n).length>0)}function fJ(e,t,n,r){let i=Us(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>cE(e,t,n,s.sourcePath,r,[pJ(s.specifier)])),o=Xi(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>cE(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 cE(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?N(c.symbol):a,originalFile:r,barrelConsumers:0,directConsumers:uE(i,r,n),...lE(e,n)}})}function pJ(e){return e.split("::").at(-1)?.split("/").at(-1)?.replace(/\.[^.]+$/,"")??e}function lE(e,t){return Fn(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 gJ(e){let t=new Map;for(let n of me(e,{includeIgnored:!1}))for(let r of Ce(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 uE(e,t,n){let r=e.get(t);return r?r.size-(r.has(n)?1:0):0}function hJ(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 yJ(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function bJ(e,t={}){let{samples:n=50,scope:r,maxDisagreements:i=5}=t,o=new U(e),s=SJ(o.productionCallableDefinitions({scope:r,minLoc:2,requireFunctionLikeSymbol:!0}),n),a=vJ(e,s);if(s.length===0||!a)return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let c={references:dE(),callees:dE()},l=[],u=0,d=a==="semantic"?Ba(e,s):{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set},m=a==="semantic"?$a(e,s):{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set},f=a==="source"?RJ(e,o,s):null;for(let p of s){let g=el(p,a==="semantic"?(d.rows.get(p.symbolId)??[]).map(x=>x.file):[...f?.referencesBySymbolId.get(p.symbolId)??[]]),h=el(p,a==="semantic"?(m.rows.get(p.symbolId)??[]).map(x=>x.file):[...f?.calleesBySymbolId.get(p.symbolId)??[]]),b=a!=="semantic"||!d.incompleteSymbolIds.has(p.symbolId)&&!d.unavailableSymbolIds.has(p.symbolId),S=a!=="semantic"||!m.incompleteSymbolIds.has(p.symbolId)&&!m.unavailableSymbolIds.has(p.symbolId);b&&S&&(u+=1);let y=el(p,Yn(e,p,{semanticEvidence:ge}).map(x=>x.file)),E=el(p,(o.calleeMap([p],{semantic:!1}).get(p.symbolId)??[]).map(x=>x.file)),I=gf(a,"references"),v=gf(a,"callees");b?mE(c.references,p,"references",y,g,I,l):c.references.skippedOracleUnavailable+=1,S?mE(c.callees,p,"callees",E,h,v,l):c.callees.skippedOracleUnavailable+=1}return l.sort((p,g)=>g.cheapOnly.length+g.oracleOnly.length-(p.cheapOnly.length+p.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?yf(u/s.length):0,oracleKind:a,scores:["references","callees"].map(p=>xJ(p,c[p],a)),topDisagreements:l.slice(0,i)}}function dE(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0,skippedOraclePartial:0,skippedOracleUnavailable:0}}function SJ(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 vJ(e,t){let n=t[0];if(!n)return null;if(hf(e,n))return"source";try{if($t(e).capability("semantic-references",n.relativePath).available)return"semantic"}catch{}return t.some(r=>hf(e,r))?"source":null}function el(e,t){let n=new Set;for(let r of t)r!==e.relativePath&&n.add(r);return n}function mE(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:N(t.symbol),question:n,cheapOnly:a,oracleOnly:c})}var CJ={references:!0,callees:!1};function xJ(e,t,n){let r=t.oracleTotal>0?t.agreed/t.oracleTotal:1,i=t.cheapTotal-t.agreed,o=gf(n,e);return{question:e,comparedSymbols:t.comparedSymbols,precision:o&&t.cheapTotal>0?yf(t.agreed/t.cheapTotal):null,recall:yf(r),unverified:i,skippedOraclePartial:t.skippedOraclePartial,skippedOracleUnavailable:t.skippedOracleUnavailable}}function gf(e,t){return e==="semantic"?CJ[t]:!1}function hf(e,t){return ye(t.relativePath)==="clojure"&&te(e,t.relativePath)!==null}function RJ(e,t,n){let r=new Map,i=new Map,o=n.filter(c=>hf(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(ye(c)!=="clojure")continue;let l=te(e,c);if(l)for(let u of l.fileIdentifiers)for(let d of s.get(u)??[])fE(r,d.symbolId,c)}let a=new Map;for(let c of t.scopedDefinitions()){if(ye(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=te(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)??[])fE(i,c.symbolId,d.relativePath)}}return{referencesBySymbolId:r,calleesBySymbolId:i}}function fE(e,t,n){let r=e.get(t);if(r){r.add(n);return}e.set(t,new Set([n]))}function yf(e){return Math.round(e*1e3)/1e3}var IJ=new Set(an());function EJ(e,t={}){let{scope:n,minLoc:r=1,limit:i,scanLimit:o,maxShapeFrequency:s=12}=t,a=t.semantic!==!1,c=DJ(e,wJ(e,{scope:n,minLoc:r,scanLimit:o}),{semantic:a,maxShapeFrequency:s}),l=MJ(c);return i?l.slice(0,i):l}function wJ(e,t){let n=Ue(e,{scope:t.scope}).filter(r=>LJ(r)&&!e.isIgnored(r.relativePath)).filter(r=>de(r)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((r,i)=>de(i)-de(r)||r.relativePath.localeCompare(i.relativePath)),Fe(n,t.scanLimit)}function LJ(e){return!e.isFunctionLike||Xe(e.symbol)?!1:e.kind===null||IJ.has(e.kind)}function DJ(e,t,n){let r=[];for(let s of t){let a=kJ(e,s,n);a&&r.push({signature:a,definition:s,fn:PJ(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=TJ(s.fn.loc),c=(i.get(s.signature)??0)>n.maxShapeFrequency,l=c?Wm(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 PJ(e){return{symbol:e.symbol,shortName:N(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:de(e)}}function MJ(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 TJ(e){return e<=5?"<=5":e<=20?"6-20":">20"}function kJ(e,t,n){if(n.semantic){let o=Jy(e,t);if(o)return o}let r=FJ(t.documentation),i=r?_J(r):null;return i||OJ(AJ(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function FJ(e){return ci(li(e))}function AJ(e,t,n,r,i){let o=se(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=$J(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,NJ(u)))return u}if(u&&u.includes("("))return u}return null}function NJ(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||sp(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function _J(e){if(!e||!e.trim())return null;let t=e.replace(/^```\w*\s*/,"").replace(/\s*```$/,"").replace(/^\(method\)\s*/,"").replace(/^\(property\)\s*/,"").replace(/^\(function\)\s*/,"").replace(/^\(class\)\s*/,"").replace(/^\(interface\)\s*/,"").replace(/^\(enum\)\s*/,"").replace(/^\(type alias\)\s*/,"").replace(/^\(const\)\s*/,"").replace(/^\(var\)\s*/,"").trim(),n=t.indexOf("(");return n===-1||(t=t.slice(n),t=t.replace(/\s+/g,"").toLowerCase(),t.length<3)?null:t}function OJ(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${Be(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=BJ(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 BJ(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 $J(e,t,n,r){let i=Be(r),o=new RegExp(`\\b${i}\\b\\s*\\(`,"i"),s=new RegExp(`\\bdef\\s+${i}\\b`,"i"),a=[],c=new Set,l=Math.max(0,Math.min(t,e.length-1)),u=Math.max(l,Math.min(e.length-1,Math.max(n,t+4)));for(let d=l;d<=u;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!c.has(d)&&(c.add(d),a.push(d))}for(let d=0;d<e.length;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!c.has(d)&&(c.add(d),a.push(d))}return a}import{spawnSync as Sfe}from"child_process";import{execFileSync as zme}from"child_process";import{createHash as Kme}from"crypto";import{lstatSync as Wme,readlinkSync as Vme,readdirSync as Jme,realpathSync as Yme,statSync as Xme}from"fs";import{dirname as Zme,isAbsolute as efe,join as tfe,posix as nfe,relative as rfe,resolve as ife,sep as ofe}from"path";var afe=512*1024*1024;function pE(e){return Ir({version:e.version,...e.base?{base:e.base}:{},files:[...e.files].sort((t,n)=>t.path.localeCompare(n.path))})}function bf(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 HJ="codebaseiq:collaboration-domain",UJ="codebaseiq:workspace-instance",zJ="codebaseiq:index-generation",qJ="codebaseiq:repository-content",gE="codebaseiq:index-inputs",KJ="codebaseiq:index-inputs";function Yr(e){let t=e.snapshot,n=e.observedSourceKinds?new Set(e.observedSourceKinds):void 0,r=e.gitContext??t?.gitContext??(n?.has("live-workspace")?ul(e.projectRoot):void 0),i=e.collaborationDomainId??e.db?.config.collaborationDomainId,o=i?Rr(HJ,1,i):void 0,s=r?Rr(UJ,1,r.worktreeId):void 0,a=t?Rr(qJ,1,pE(t.repositoryContent)):void 0,c=t?Rr(gE,t.indexInputs.version,bf(t.indexInputs)):void 0,l=e.db&&t?WJ(e.db.generation.metadataRaw):void 0,u=e.db?{generation:Rr(zJ,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"}]:[]],f=[...u&&d.has("index-generation")?[{source:"index-generation",kind:u.source==="immutable"?"immutable":"not-established"}]:[],...a&&d.has("repository-snapshot")?[{source:"repository-snapshot",kind:"fixed-snapshot"}]:[],...s&&d.has("live-workspace")?[{source:"live-workspace",kind:"not-established"}]:[],...d.has("process")?[{source:"process",kind:"not-established"}]:[]];return m.length===0&&(m.push({kind:"process"}),f.push({source:"process",kind:"not-established"})),{schemaVersion:qf,observedAt:(e.observedAt??(t?new Date(t.capturedAt):new Date)).toISOString(),facts:{...o?{collaborationDomain:o}:{},...s?{workspaceInstance:s}:{},...a?{wholeContent:a}:{},...c?{relevantInputs:[{subject:KJ,identity:c}]}:{},...u?{index:u}:{}},observedSources:m,stabilityProofs:f,...r?{diagnostics:{clean:r.clean,...r.headCommit?{headCommit:r.headCommit}:{},...r.treeOid?{treeOid:r.treeOid}:{}}}:{}}}function GJ(e){return Yr({projectRoot:e.projectRoot,db:e.db,...e.gitContext?{gitContext:e.gitContext}:{},...e.observedAt?{observedAt:e.observedAt}:{},observedSourceKinds:["index-generation"]})}function hfe(){let e=Ns();if(!e)return Yr({projectRoot:Qf(),observedSourceKinds:["process"]});let t=e.config.projectRoot,n=ul(t);return GJ({projectRoot:t,db:e,...n?{gitContext:n}:{}})}function WJ(e){if(!e)return;let t=Ps(e);if(t.kind!=="legacy"&&t.kind!=="supported")return;let n=Uf(t.metadata.fingerprint);return n&&Number.isSafeInteger(n.version)&&n.version>0?Rr(gE,n.version,bf(n)):void 0}var vf="codebaseiq-isolated-analysis",Cf=1;function VJ(e){let t=[...e??[]];return t.includes("--json")?t:["--json",...t]}var Ki=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 Lfe(e,t){let n=Ns(),r={protocol:vf,schemaVersion:Cf,producer:{name:"codebaseiq",version:xr},command:e,result:t,...n?{observationReceipt:Yr({projectRoot:n.config.projectRoot,db:n,observedSourceKinds:["index-generation"]})}:{}};bl(JSON.stringify(r))}function hE(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function tl(e){let t=e.timeoutMs??$p.analysis,n=e.maxBuffer??10*1024*1024;return Hp({command:process.execPath,args:[...process.execArgv,e.cliPath,e.command,...VJ(e.args)],cwd:process.cwd(),env:e.env??process.env,label:e.label,timeoutMs:t,maxStdoutBytes:n,maxStderrBytes:n,signal:e.signal}).catch(r=>{throw r instanceof jp&&r.kind==="timeout"?new Ki(e.label,t,r.reaped):r}).then(r=>{let i=r.stderr.trim();if(r.status!==0)throw new Error(`${e.label} failed${i?`:
551
- ${i}`:""}`);return JJ(r.stdout,e)})}function JJ(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(!Kn(n))throw new Error(`${t.label} returned a non-object isolated-analysis message.`);if(n.protocol!==vf)throw new Error(`${t.label} returned protocol ${Sf(n.protocol)}; expected ${vf}.`);if(n.schemaVersion!==Cf)throw new Error(`${t.label} returned unsupported isolated-analysis schemaVersion ${Sf(n.schemaVersion)}; expected ${Cf}.`);if(!YJ(n.producer))throw new Error(`${t.label} did not identify a codebaseiq producer version.`);if(n.command!==t.command)throw new Error(`${t.label} returned result for command ${Sf(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&&(!Kf(r)||r.schemaVersion!==2))throw new Error(`${t.label} returned an invalid observation receipt.`);return{result:n.result,...r?{observationReceipt:r}:{}}}function YJ(e){return Kn(e)&&e.name==="codebaseiq"&&typeof e.version=="string"&&e.version.length>0}function Sf(e){return typeof e=="string"?JSON.stringify(e):String(e)}async function xf(e,t,n){let r=new Array(e.length),i=new AbortController,o=0,s,a=!1;async function c(){for(;!i.signal.aborted&&o<e.length;){let l=o++;try{r[l]=await n(e[l],i.signal)}catch(u){throw a||(a=!0,s=u,i.abort(u)),u}}}if(await Promise.allSettled(Array.from({length:Math.min(t,e.length)},()=>c())),a)throw s;return r}function yE(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 XJ}from"child_process";import{existsSync as QJ,mkdirSync as ZJ,renameSync as e5,writeFileSync as t5}from"fs";import{dirname as SE,join as n5}from"path";var nl=6,r5="health-report-cache.json";function Rf(e,t,n,r=c5()){let i=In(e);return i?{version:nl,projectFingerprint:i,cliVersion:n,scope:t.scope??null,full:t.full===!0,phaseTimeoutMs:t.phaseTimeoutMs??null,gitHead:r.gitHead(e.config.projectRoot)}:null}function vE(e,t,n=IE()){let r=xE(e),i=RE(t),o=!1;return O("health.report-cache.read",()=>{if(!n.existsSync(r))return null;try{let s=JSON.parse(n.readFile(r));return!i5(s)||s.keyHash!==i?null:(o=!0,s.report)}catch{return null}},()=>({available:!0,hit:o,keyHash:i}))}function CE(e,t,n,r=IE()){let i=xE(e),o={version:nl,keyHash:RE(t),key:t,writtenAt:r.nowIso(),report:n};r.mkdirSync(SE(i),{recursive:!0});let s=`${i}.${process.pid}.${Date.now()}.tmp`;r.writeFileSync(s,JSON.stringify(o)),r.renameSync(s,i)}function xE(e){return n5(SE(e.config.dbPath),r5)}function RE(e){return qt(JSON.stringify(e))}function i5(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===nl&&typeof t.keyHash=="string"&&o5(t.key)&&typeof t.writtenAt=="string"&&s5(t.report)}function o5(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===nl&&typeof t.projectFingerprint=="string"&&typeof t.cliVersion=="string"&&(t.scope===null||typeof t.scope=="string")&&typeof t.full=="boolean"&&(t.phaseTimeoutMs===null||typeof t.phaseTimeoutMs=="number")&&(t.gitHead===null||typeof t.gitHead=="string")}function s5(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)&&a5(t.coverage)}function a5(e){if(!e||typeof e!="object")return!1;let t=e;if(t.status!=="complete"&&t.status!=="incomplete"&&t.status!=="semantic-disabled")return!1;let n=t.complexity?.semanticEvidence;return bE(n)&&typeof n.excludedSymbolCount=="number"&&Array.isArray(t.phases)&&t.phases.every(r=>!!r&&typeof r=="object"&&typeof r.phase=="string"&&bE(r.semanticEvidence))}function bE(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.enabled=="boolean"&&(t.status==="complete"||t.status==="incomplete"||t.status==="unavailable"||t.status==="incomplete-and-unavailable"||t.status==="disabled")&&typeof t.incompleteSymbolCount=="number"&&typeof t.unavailableSymbolCount=="number"}function c5(){return{gitHead(e){let t=XJ("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",timeout:3e4,killSignal:"SIGKILL",windowsHide:!0});return t.status===0?t.stdout.trim():null}}}function IE(){return{existsSync:QJ,mkdirSync:ZJ,readFile:e=>dt(e,"health report cache"),renameSync:e5,writeFileSync:t5,nowIso:()=>new Date().toISOString()}}var LE="__health-phase",u5="__diff-impact-batch",d5=10,m5=4,f5=8,p5=25e3,g5=2500,If=2500,h5=4,y5=12,EE=3e4,DE=new Set(["react-component-duplicates","react-hook-candidates","react-large-component-pressure"]),PE=new Set(["vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure"]),b5=new Set([...PE,"suppressions"]),S5=new Set(["similar","extract-candidates"]),il=3,wE=Ji({kind:"health-semantic-prewarm",invalidation:Ye("health-semantic-prewarm"),serialize:e=>JSON.stringify(e),deserialize:v5});function v5(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return n.version!==il||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:il,definitions:n.definitions,referenceCacheWrites:n.referenceCacheWrites,referenceIncomplete:n.referenceIncomplete,calleeRows:n.calleeRows,warmedAt:n.warmedAt}}catch{return null}}function Zfe(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
552
- `)}function C5(e){let t=Nr(e);return t.symbols>=p5||t.documents>=g5}function epe(e,t,n,r={}){if(!C5(e))return{semantic:!0};if(n)return 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.":`Run "codebaseiq ${t} --full" for the unbounded semantic pass.`;console.error(`Large index detected; ${t} is using its bounded default analysis with semantic enrichment disabled. Candidate scans, when this command uses one, are capped at ${If}. `+i)}return{scanLimit:If,semantic:!1,analysisBudget:{scanLimit:If,semanticEnrichment:!1,reason:"large index default budget; pass --full for unbounded semantic analysis"}}}var x5={env:process.env,projectFingerprint:In,semanticEngineFingerprint:w5,readMarker:(e,t,n)=>wE.read(e,t,n),writeMarker:(e,t,n,r)=>wE.write(e,t,n,r),candidateDefinitions:(e,t)=>new U(e).scopedDefinitions(t.scope).filter(n=>Ge(n.relativePath)!==null),materializeReferences:(e,t,n)=>$t(e).materializeReferences(t,n),materializeCallees:Zu};function R5(e,t,n=x5){if(t.full!==!0)return Sr("default-mode");if((n.env??process.env).CODEBASEIQ_HEALTH_SEMANTIC_PREWARM==="0")return Sr("disabled");let r=Sr("error");return O("health.semantic-prewarm",()=>{try{r=I5(e,t,n)}catch(i){r=Sr("error",{error:i instanceof Error?i.message:String(i)})}return r},()=>L5(r))}function I5(e,t,n){let r=n.projectFingerprint(e);if(!r)return Sr("missing-project-fingerprint");let i=E5(t,n.semanticEngineFingerprint(e)),o=n.readMarker(e,i,r);if(o&&o.referenceIncomplete===0)return Sr("cache-hit");let s=[];if(s=O("health.semantic-prewarm.candidate-definitions",()=>(s=n.candidateDefinitions(e,t),s),()=>({definitions:s.length})),s.length===0)return Sr("no-semantic-definitions");let a=0,c=O("health.semantic-prewarm.references",()=>{let m=n.materializeReferences(e,s,{prefetchCallees:!0});return a=m.cacheHits+m.cacheWrites+m.inMemoryHits,m},()=>({definitions:s.length,rows:a}));if(c.cacheHits+c.cacheWrites+c.inMemoryHits===0&&c.misses+c.unkeyed>0)return Sr("provider-unavailable",{definitions:s.length,referenceMisses:c.misses});let u=0,d=O("health.semantic-prewarm.callees",()=>{let m=n.materializeCallees(e,s);return u=m.size,m},()=>({definitions:s.length,rows:u}));return c.incomplete>0?{status:"partial",reason:"incomplete-references",definitions:s.length,referenceCacheHits:c.cacheHits,referenceCacheWrites:c.cacheWrites,referenceMisses:c.misses,referenceIncomplete:c.incomplete,calleeRows:d.size}:(O("health.semantic-prewarm.marker-write",()=>n.writeMarker(e,i,r,{version:il,definitions:s.length,referenceCacheWrites:c.cacheWrites,referenceIncomplete:c.incomplete,calleeRows:d.size,warmedAt:Date.now()})),{status:"warmed",reason:"cache-miss",definitions:s.length,referenceCacheHits:c.cacheHits,referenceCacheWrites:c.cacheWrites,referenceMisses:c.misses,referenceIncomplete:c.incomplete,calleeRows:d.size})}function E5(e,t){return JSON.stringify({version:il,cliVersion:xr,semanticEngineFingerprint:t,scope:e.scope??null})}function w5(e){return qt(JSON.stringify({kind:"health-semantic-prewarm-engine",rust:Mr(e.config.projectRoot)}))}function Sr(e,t={}){return{status:"skipped",reason:e,definitions:0,referenceCacheHits:0,referenceCacheWrites:0,referenceMisses:0,referenceIncomplete:0,calleeRows:0,...t}}function L5(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 rl(e){return yl(t=>{let n=Yr({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 ol(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 Yr({projectRoot:r.database.config.projectRoot,...o&&s?{db:r.database}:{},observedSourceKinds:n})}async function tpe(e){return(await D5(e)).result}async function D5(e){let t=A5(e),n={...e,phaseTimeoutMs:t??null},r=rl(g=>{let h=Rf(g,n,xr);if(!h)return null;let b=vE(g,h);return b||null});if(r.value)return{result:r.value,observationReceipt:ol([r.anchor],[],["index-generation","live-workspace"])};let i=rl(g=>({applicability:P5(g,e),overview:df(g,"overview",e)})),{applicability:o,overview:s}=i.value,a=[r.anchor,i.anchor],c=new Map;c.set("overview",s);let l=Qc.filter(g=>g==="overview"?!1:M5(g,o)?!0:(c.set(g,Xr(g)),!1)),u=T5(l);if(e.full){let g=rl(h=>R5(h,e));a.push(g.anchor)}let d=await xf(u,N5(u.length),(g,h)=>k5(g,e,t,h)),m=d.flatMap(g=>g.result),f=[];if(m.forEach(g=>{g.healthPhaseMeta&&f.push(`Health phase "${g.phase}" deferred: ${g.healthPhaseMeta.reason}. Run health --full for exhaustive analysis.`),c.set(g.phase,g)}),f.length>0){let g=c.get("overview");c.set("overview",{...g,warnings:[...g.warnings,...f]})}let p=mf(Qc.map(g=>c.get(g)));return yl(g=>{let h=Rf(g,n,xr);h&&CE(g,h,p)}),{result:p,observationReceipt:ol(a,d.map(g=>g.observationReceipt),["index-generation","live-workspace"])}}function P5(e,t){return Hs(e,{scope:t.scope})}function M5(e,t){return DE.has(e)?t.react:PE.has(e)?t.vue:!0}function T5(e){return yE(e,[DE,b5,S5])}function Xr(e){let t={enabled:!0,status:"complete",incompleteSymbolCount:0,unavailableSymbolCount:0};switch(e){case"react-component-duplicates":return{phase:e,reactComponentDuplicates:{count:0,loc:0,files:[]},evidenceCoverage:t};case"react-hook-candidates":return{phase:e,reactHookCandidates:{count:0,loc:0,files:[]},evidenceCoverage:t};case"react-large-component-pressure":return{phase:e,reactLargeComponentPressure:{count:0,loc:0,files:[]},evidenceCoverage:t};case"vue-component-duplicates":return{phase:e,vueComponentDuplicates:{count:0,loc:0,files:[]},evidenceCoverage:t};case"vue-composable-candidates":return{phase:e,vueComposableCandidates:{count:0,loc:0,files:[]},evidenceCoverage:t};case"vue-large-view-pressure":return{phase:e,vueLargeViewPressure:{count:0,loc:0,files:[]},evidenceCoverage:t};default:throw new Error(`Health phase "${e}" cannot be synthesized.`)}}function k5(e,t,n,r){if(e.length===1)return F5(e[0],t,n,r).then(a=>({result:[a.result],...a.observationReceipt?{observationReceipt:a.observationReceipt}:{}}));let i=e.join(","),o=process.argv[1]??wf(import.meta.url),s=[i];return t.scope&&s.push("--scope",t.scope),t.full&&s.push("--full"),tl({cliPath:o,command:LE,args:s,label:`Health phases "${i}"`,timeoutMs:n,signal:r}).catch(a=>{if(t.full||!(a instanceof Ki))throw a;return{result:e.map(c=>ME(c,a.timeoutMs,`timed out after ${a.timeoutMs}ms`))}})}function F5(e,t,n,r){let i=process.argv[1]??wf(import.meta.url),o=[e];return t.scope&&o.push("--scope",t.scope),t.full&&o.push("--full"),tl({cliPath:i,command:LE,args:o,label:`Health phase "${e}"`,timeoutMs:n,signal:r}).catch(s=>{if(t.full||!(s instanceof Ki))throw s;return{result:ME(e,s.timeoutMs,`timed out after ${s.timeoutMs}ms`)}})}function A5(e,t=process.env){if(e.full)return;let n=t.CODEBASEIQ_HEALTH_PHASE_TIMEOUT_MS;if(!n)return EE;let r=parseInt(n,10);return!Number.isFinite(r)||r<0?EE:r===0?void 0:r}function ME(e,t,n){let r={evidenceCoverage:{enabled:!0,status:"unavailable",incompleteSymbolCount:0,unavailableSymbolCount:0},healthPhaseMeta:{status:"deferred",reason:n,timeoutMs:t}};switch(e){case"overview":throw new Error("Overview health phase cannot be deferred.");case"dead":return{phase:e,dead:{count:0,loc:0,files:[]},...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{...Xr(e),...r};case"react-hook-candidates":return{...Xr(e),...r};case"react-large-component-pressure":return{...Xr(e),...r};case"vue-component-duplicates":return{...Xr(e),...r};case"vue-composable-candidates":return{...Xr(e),...r};case"vue-large-view-pressure":return{...Xr(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,coverage:{semanticEvidence:{enabled:!0,status:"unavailable",incompleteSymbolCount:0,unavailableSymbolCount:0,excludedSymbolCount: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 N5=TE({envKey:"CODEBASEIQ_HEALTH_CONCURRENCY",defaultMinimum:h5,defaultMaximum:y5});function npe(e){if(console.log(`
553
- 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)
554
- `),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${Zf(e.overview.indexSizeBytes)}
555
- `),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: ${Ef(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: ${Ef(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: ${Ef(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(`
556
- 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(`
557
- Top Complexity Hotspots:`);for(let n of e.topComplexity)console.log(` ${n.score.toFixed(1).padStart(6)} ${n.symbol}`)}if(B5(e),O5(e),e.scoreBreakdown.length>0){console.log(`
558
- 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?`
559
- No findings from completed analyses. Review warnings before interpreting this result as clean.`:`
560
- No issues found. Codebase is clean.`)}function Ef(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${_5(t)} score-weighted)`}function _5(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function O5(e){if(e.pressure.length!==0){console.log(`
561
- 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 B5(e){let t=e.axes;if(console.log(`
562
- 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 rpe(e){let t=rl(o=>{let s=Ui(o,{base:e.base});return s.note?{kind:"complete",result:Fc(o,{base:e.base})}:s.changedFiles.length===0?{kind:"complete",result:Fc(o,{base:e.base})}:{kind:"batched",plan:s}}),n=t.value;if(n.kind==="complete")return{result:n.result,observationReceipt:ol([t.anchor],[],["index-generation","live-workspace"])};let r=hE(n.plan.changedFiles,d5),i=await xf(r,$5(r.length),(o,s)=>z5(o,e,s));return{result:Ac(n.plan.changedFiles,i.map(o=>o.result)),observationReceipt:ol([t.anchor],i.map(o=>o.observationReceipt),["index-generation","live-workspace"])}}var $5=TE({envKey:"CODEBASEIQ_DIFF_IMPACT_CONCURRENCY",defaultMinimum:m5,defaultMaximum:f5});function TE(e){return(t,n=process.env,r=l5)=>j5(t,n,r,e)}function j5(e,t,n,r){let i=t[r.envKey],o=U5(n,r),s=i?parseInt(i,10):o,a=!Number.isFinite(s)||s<1?Math.min(o,e):Math.min(s,e),c=H5(t);return c===null?a:Math.min(c,a)}function H5(e){let t=e.CODEBASEIQ_MAX_CONCURRENCY;if(!t)return null;let n=parseInt(t,10);return Number.isFinite(n)&&n>=1?n:null}function U5(e,t){let n=e(),r=Number.isFinite(n)?Math.max(t.defaultMinimum,n-1):0;return Math.min(t.defaultMaximum,Math.max(t.defaultMinimum,r))}function z5(e,t,n){let r=process.argv[1]??wf(import.meta.url),i=[];return t.base&&i.push("--base",t.base),tl({cliPath:r,command:u5,args:i,env:{...process.env,CODEBASEIQ_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch",signal:n})}function ipe(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:"),wl.list(e.changedSymbols,n=>` ${n.file} ${n.shortName} (fan-in: ${n.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
563
- Affected consumer files:`),wl.list(e.affectedConsumers,n=>` ${n.file} (${n.consumedSymbols} symbol(s))`))}export{Xs as a,qE as b,El as c,K5 as d,wl as e,nY as f,rY as g,iY as h,oY as i,sY as j,aY as k,hY as l,yY as m,_w as n,na as o,Ww as p,NY as q,_Y as r,io as s,an as t,Bg as u,i3 as v,Ea as w,D4 as x,PM as y,Nr as z,k0 as A,ad as B,Wk as C,Bo as D,Tg as E,W3 as F,$o as G,jo as H,tc as I,TS as J,aA as K,MA as L,JQ as M,D_ as N,wO as O,Zo as P,em as Q,JO as R,Wr as S,_B as T,$B as U,jB as V,HB as W,e$ as X,r$ as Y,i$ as Z,o$ as _,a$ as $,c$ as aa,l$ as ba,KC as ca,ns as da,am as ea,k$ as fa,rs as ga,_$ as ha,O$ as ia,q$ as ja,J$ as ka,Y$ as la,X$ as ma,ss as na,fm as oa,as as pa,nj as qa,cs as ra,ls as sa,gm as ta,us as ua,ds as va,hm as wa,Vj as xa,ms as ya,eU as za,Im as Aa,Em as Ba,BU as Ca,Ui as Da,cR as Ea,bz as Fa,ps as Ga,Jq as Ha,hs as Ia,bK as Ja,ys as Ka,lG as La,uG as Ma,bG as Na,kG as Oa,$G as Pa,nW as Qa,Xm as Ra,CI as Sa,Zm as Ta,xI as Ua,Gc as Va,kW as Wa,xs as Xa,Rs as Ya,Is as Za,j2 as _a,H2 as $a,U2 as ab,lf as bb,Qc as cb,df as db,CV as eb,nJ as fb,rJ as gb,oJ as hb,aJ as ib,bJ as jb,EJ as kb,Yr as lb,hfe as mb,Lfe as nb,LE as ob,u5 as pb,Zfe as qb,epe as rb,tpe as sb,D5 as tb,npe as ub,rpe as vb,ipe as wb};
564
- //# sourceMappingURL=chunk-ECQBG7PW.js.map