codebaseiq 0.1.0 → 0.2.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 (422) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/dist/augment-vue-worker.js +1 -1
  3. package/dist/{chunk-DQMDCD24.js → chunk-27PHVDKL.js} +2 -2
  4. package/dist/{chunk-ZMI2JSX2.js → chunk-2DMVFAY7.js} +2 -2
  5. package/dist/{chunk-5PUWMSDU.js → chunk-2E6BTWER.js} +2 -2
  6. package/dist/{chunk-YESXMKX3.js → chunk-2F5ERMNI.js} +2 -2
  7. package/dist/chunk-2VKB5CMA.js +60 -0
  8. package/dist/{chunk-NNJ2KZZG.js → chunk-327YK6TB.js} +4 -4
  9. package/dist/chunk-347TXATM.js +2 -0
  10. package/dist/{chunk-VEXUL62T.js → chunk-35YYZD3D.js} +2 -2
  11. package/dist/chunk-36WRYYTE.js +3 -0
  12. package/dist/chunk-37TKC6MB.js +2 -0
  13. package/dist/{chunk-FAJQ7LWY.js → chunk-3AC56WAR.js} +2 -2
  14. package/dist/{chunk-JE3WZ6II.js → chunk-3NUZVLR7.js} +2 -2
  15. package/dist/{chunk-UZGZB3VB.js → chunk-3XFJUWJE.js} +2 -2
  16. package/dist/{chunk-OVTS4DKB.js → chunk-4AOOSCZ7.js} +2 -2
  17. package/dist/{chunk-LU3BMVH2.js → chunk-4IFISPQW.js} +2 -2
  18. package/dist/chunk-4NHWNAWQ.js +11 -0
  19. package/dist/chunk-4O52YNKL.js +5 -0
  20. package/dist/{chunk-HPJRBHVT.js → chunk-54K6556S.js} +2 -2
  21. package/dist/{chunk-HRWGYWRJ.js → chunk-57GCCPLS.js} +2 -2
  22. package/dist/{chunk-J77SU6VA.js → chunk-57KEZDPT.js} +2 -2
  23. package/dist/{chunk-OFBE4NGP.js → chunk-57KFVPVZ.js} +2 -2
  24. package/dist/{chunk-WOQBZPIF.js → chunk-5BDK6QC3.js} +2 -2
  25. package/dist/{chunk-7MGU3HPH.js → chunk-5IO2APSS.js} +2 -2
  26. package/dist/chunk-5NJPH3QZ.js +61 -0
  27. package/dist/{chunk-GW6Z3WGY.js → chunk-5WXOEJ4G.js} +2 -2
  28. package/dist/chunk-5XEVXVTK.js +3 -0
  29. package/dist/{chunk-RR7SX44N.js → chunk-6OVNYYY4.js} +2 -2
  30. package/dist/{chunk-ZV3JV5G5.js → chunk-6SDEQTVY.js} +2 -2
  31. package/dist/{chunk-EF2R3WNQ.js → chunk-6URCE5QY.js} +2 -2
  32. package/dist/{chunk-UCD3H3UZ.js → chunk-6ZV5EDUT.js} +2 -2
  33. package/dist/{chunk-C6SBF2WH.js → chunk-77GHPR2R.js} +2 -2
  34. package/dist/{chunk-YVCIMIOC.js → chunk-7R64XY4Y.js} +2 -2
  35. package/dist/{chunk-VXYS3FZD.js → chunk-7Z7HCZ7J.js} +2 -2
  36. package/dist/{chunk-CO5R3UNA.js → chunk-A67HT5FR.js} +2 -2
  37. package/dist/{chunk-UDS562V4.js → chunk-A7XQT7MH.js} +2 -2
  38. package/dist/{chunk-RDBI2RXU.js → chunk-ACZDU5GK.js} +2 -2
  39. package/dist/{chunk-FETNQCFO.js → chunk-AM5SUGHF.js} +2 -2
  40. package/dist/{chunk-NNOKTMZT.js → chunk-B2E3HZ2A.js} +2 -2
  41. package/dist/{chunk-CVYSU6BX.js → chunk-BH5CE4LN.js} +2 -2
  42. package/dist/chunk-BLKYYQ7C.js +543 -0
  43. package/dist/{chunk-4WKDMDEW.js → chunk-BX2U3QQV.js} +2 -2
  44. package/dist/{chunk-ZKX2FRS6.js → chunk-CANBLFVQ.js} +2 -2
  45. package/dist/{chunk-SMRBZ6EC.js → chunk-CCRZLRWJ.js} +2 -2
  46. package/dist/chunk-CDWSLAPN.js +21 -0
  47. package/dist/chunk-CIVYHK7U.js +22 -0
  48. package/dist/{chunk-L57ZKWVG.js → chunk-CMXW7MFV.js} +2 -2
  49. package/dist/{chunk-T3DGWPXM.js → chunk-CSZOQ7YO.js} +2 -2
  50. package/dist/{chunk-ZZXSWSN6.js → chunk-CWMHWD56.js} +2 -2
  51. package/dist/{chunk-6NW7MU72.js → chunk-CZEIHYMP.js} +2 -2
  52. package/dist/{chunk-DO6WQD2T.js → chunk-D62CTZX6.js} +2 -2
  53. package/dist/{chunk-XWUOUWYI.js → chunk-DFPAZXLU.js} +2 -2
  54. package/dist/{chunk-MOVBWNIP.js → chunk-DKJXK3HA.js} +2 -2
  55. package/dist/{chunk-XMQ23E27.js → chunk-DLC6JDN7.js} +2 -2
  56. package/dist/chunk-DUKHVPU5.js +4 -0
  57. package/dist/{chunk-ID63777H.js → chunk-DVYG3JTA.js} +2 -2
  58. package/dist/{chunk-NE6IU5ZD.js → chunk-EFFMFK7C.js} +2 -2
  59. package/dist/{chunk-I2T2LLK2.js → chunk-EM5UHLAM.js} +2 -2
  60. package/dist/chunk-EN4AHLL3.js +3 -0
  61. package/dist/chunk-EXMVF3JR.js +3 -0
  62. package/dist/{chunk-SWHMHUKF.js → chunk-FEBLLMTL.js} +2 -2
  63. package/dist/chunk-FIXYHQ3W.js +3 -0
  64. package/dist/{chunk-RKEJ6VTF.js → chunk-FLLXYUOL.js} +2 -2
  65. package/dist/{chunk-KWVHSKHK.js → chunk-FPDL2TUB.js} +2 -2
  66. package/dist/chunk-FQA3KIFX.js +17 -0
  67. package/dist/chunk-FWY2PRIF.js +3 -0
  68. package/dist/chunk-FY5V4V4F.js +2 -0
  69. package/dist/chunk-G2XUZCF2.js +88 -0
  70. package/dist/{chunk-QHRNXP3C.js → chunk-GXVDTHFC.js} +2 -2
  71. package/dist/{chunk-6MUIJMVL.js → chunk-H3CKAL6P.js} +2 -2
  72. package/dist/chunk-H5QXP63L.js +2 -0
  73. package/dist/{chunk-VUIYB2V3.js → chunk-HBQGKMM3.js} +2 -2
  74. package/dist/{chunk-PYAB5SM6.js → chunk-HBXZAGY6.js} +2 -2
  75. package/dist/{chunk-NNO6A2PO.js → chunk-HCMQZPEO.js} +2 -2
  76. package/dist/{chunk-Q65CQ4XL.js → chunk-HHBBGWES.js} +2 -2
  77. package/dist/{chunk-GTXSJDCO.js → chunk-HIEXRDJF.js} +2 -2
  78. package/dist/{chunk-4FC325IF.js → chunk-HYKSLTAR.js} +2 -2
  79. package/dist/{chunk-XLQ3GLWZ.js → chunk-I2KP4AGR.js} +2 -2
  80. package/dist/chunk-I5FCDTK2.js +2 -0
  81. package/dist/{chunk-QKPLA6IC.js → chunk-I645ZF75.js} +2 -2
  82. package/dist/{chunk-FDGD5AB5.js → chunk-IBM3F2BJ.js} +2 -2
  83. package/dist/{chunk-Q72QSKXC.js → chunk-IEL6Q5W3.js} +38 -38
  84. package/dist/{chunk-NCZUNH3E.js → chunk-IGQQUENU.js} +12 -12
  85. package/dist/chunk-IGYAZPRX.js +4 -0
  86. package/dist/chunk-IOVPAZWP.js +3 -0
  87. package/dist/{chunk-OL6KJP3N.js → chunk-IVJJNVSX.js} +2 -2
  88. package/dist/{chunk-AKB7V7TV.js → chunk-IWAMYGPN.js} +2 -2
  89. package/dist/chunk-IYBIBMPF.js +90 -0
  90. package/dist/{chunk-IOP6FWIM.js → chunk-J24VICI5.js} +2 -2
  91. package/dist/{chunk-C7QOQX32.js → chunk-JN5LIBT3.js} +2 -2
  92. package/dist/{chunk-O6QTXQPJ.js → chunk-JOALNFY3.js} +2 -2
  93. package/dist/{chunk-GCHRX4YW.js → chunk-JUO3Z644.js} +2 -2
  94. package/dist/{chunk-BJ6SQAEN.js → chunk-JXHLB7TP.js} +2 -2
  95. package/dist/{chunk-IJ4HMYBE.js → chunk-JYX5UZSZ.js} +2 -2
  96. package/dist/chunk-K2O7SBAU.js +2 -0
  97. package/dist/{chunk-OLF4MA5W.js → chunk-K5G7SPAG.js} +2 -2
  98. package/dist/{chunk-YSNONTJ2.js → chunk-KDYQQJ6X.js} +2 -2
  99. package/dist/{chunk-7NVGT435.js → chunk-KM4QRWI5.js} +2 -2
  100. package/dist/{chunk-HKQUXIFO.js → chunk-KNV5VFDV.js} +2 -2
  101. package/dist/chunk-L3YSDLNB.js +2 -0
  102. package/dist/{chunk-EZNMUY67.js → chunk-LAGDJXFY.js} +2 -2
  103. package/dist/{chunk-ENCCHKM6.js → chunk-LY2NB5XR.js} +4 -4
  104. package/dist/chunk-M4EVGA5S.js +14 -0
  105. package/dist/chunk-M7LAIM77.js +127 -0
  106. package/dist/{chunk-BVAJLC5A.js → chunk-MRGTCMDK.js} +2 -2
  107. package/dist/{chunk-OZYRSMSH.js → chunk-MT5W4DUG.js} +2 -2
  108. package/dist/{chunk-VE5AVNMP.js → chunk-MTMF4N7F.js} +2 -2
  109. package/dist/chunk-N3Q3AWGW.js +545 -0
  110. package/dist/{chunk-TXXOEMZJ.js → chunk-NDGTJHQN.js} +2 -2
  111. package/dist/chunk-NIO346UL.js +2 -0
  112. package/dist/chunk-NJA4MMBD.js +2 -0
  113. package/dist/{chunk-7FND7D7N.js → chunk-NK76RSB6.js} +2 -2
  114. package/dist/{chunk-H3LGFZVK.js → chunk-NTRW52UR.js} +2 -2
  115. package/dist/{chunk-JOIRNPPY.js → chunk-OJFLPVBP.js} +2 -2
  116. package/dist/{chunk-KMITESMT.js → chunk-OMBRP7BB.js} +2 -2
  117. package/dist/{chunk-UP3BUZR5.js → chunk-OVKZM2XI.js} +2 -2
  118. package/dist/{chunk-MVB3DAEY.js → chunk-PARCKE3Q.js} +2 -2
  119. package/dist/{chunk-CAUCPUOF.js → chunk-PFPHS4NO.js} +2 -2
  120. package/dist/chunk-PHPQ24UG.js +22 -0
  121. package/dist/chunk-PLZXWZHY.js +77 -0
  122. package/dist/{chunk-34WBMAYK.js → chunk-PNVZIJ57.js} +2 -2
  123. package/dist/{chunk-SYDJMPES.js → chunk-QKVTWODE.js} +2 -2
  124. package/dist/{chunk-FW53T7EB.js → chunk-QLTFXVUI.js} +2 -2
  125. package/dist/{chunk-PBI2LFKH.js → chunk-QMGWSEPL.js} +2 -2
  126. package/dist/{chunk-CQP3THUZ.js → chunk-QVHZB75Z.js} +2 -2
  127. package/dist/{chunk-6BQ3DSPK.js → chunk-QVWDQTMG.js} +2 -2
  128. package/dist/{chunk-ST7V3SKN.js → chunk-RCPZOPV6.js} +2 -2
  129. package/dist/chunk-RJWAB4VR.js +345 -0
  130. package/dist/chunk-RRPK327J.js +20 -0
  131. package/dist/chunk-RVYLJDXC.js +21 -0
  132. package/dist/chunk-RWKEXCHU.js +3 -0
  133. package/dist/{chunk-L4NRUAGJ.js → chunk-S5SKXCND.js} +2 -2
  134. package/dist/{chunk-RBAS5ZHI.js → chunk-S64NCE2Z.js} +2 -2
  135. package/dist/{chunk-WMPRTGH2.js → chunk-SF34QLK2.js} +2 -2
  136. package/dist/{chunk-ANFVSJWQ.js → chunk-SJZQ2PTZ.js} +2 -2
  137. package/dist/{chunk-4XTAUQFD.js → chunk-SRY26ITJ.js} +2 -2
  138. package/dist/chunk-SV2LEFVM.js +2 -0
  139. package/dist/{chunk-7XAN6GKB.js → chunk-T3YFIJ5P.js} +2 -2
  140. package/dist/chunk-T55YPJGB.js +3 -0
  141. package/dist/chunk-TAJ6UGCO.js +21 -0
  142. package/dist/{chunk-PIOMTC27.js → chunk-TUTSO7UZ.js} +2 -2
  143. package/dist/{chunk-FQKZWM4L.js → chunk-U24M5RQM.js} +5 -5
  144. package/dist/{chunk-XME3HPXZ.js → chunk-U2XX3BT4.js} +2 -2
  145. package/dist/{chunk-SZD2KF7Q.js → chunk-UWB5WMC2.js} +2 -2
  146. package/dist/{chunk-6CS3UQTN.js → chunk-VCL7FK3E.js} +2 -2
  147. package/dist/{chunk-N3IQCBCF.js → chunk-VCWAJPXQ.js} +2 -2
  148. package/dist/{chunk-LZYFLFEH.js → chunk-VG55NFXF.js} +2 -2
  149. package/dist/{chunk-PTAWHLVJ.js → chunk-VLTUX4IF.js} +2 -2
  150. package/dist/{chunk-JEJLSICM.js → chunk-VVCBMH5O.js} +2 -2
  151. package/dist/{chunk-JSOYNVWH.js → chunk-VYZQZ4ZN.js} +2 -2
  152. package/dist/chunk-W3FK73MD.js +8 -0
  153. package/dist/{chunk-UNBY47BC.js → chunk-W6C6QTXJ.js} +2 -2
  154. package/dist/chunk-WH5SYOMD.js +2 -0
  155. package/dist/chunk-WJOQC4P7.js +7 -0
  156. package/dist/chunk-WO47BIPY.js +3 -0
  157. package/dist/chunk-WOOTEWQT.js +239 -0
  158. package/dist/{chunk-UBGWN7I4.js → chunk-X5I2BQGX.js} +2 -2
  159. package/dist/{chunk-PX4RYAAK.js → chunk-XNUWRTYM.js} +2 -2
  160. package/dist/{chunk-ICFDQHAM.js → chunk-XUJM6474.js} +2 -2
  161. package/dist/chunk-XYLV727H.js +21 -0
  162. package/dist/{chunk-TRRC4ZJ7.js → chunk-YFQPWKHR.js} +2 -2
  163. package/dist/{chunk-NEDP5RFQ.js → chunk-YIOQJ45A.js} +2 -2
  164. package/dist/{chunk-Y6KHROC3.js → chunk-YXJ4IAHH.js} +2 -2
  165. package/dist/chunk-YYFV32WR.js +3 -0
  166. package/dist/{chunk-BH5F2Q4O.js → chunk-ZB3V5QM7.js} +2 -2
  167. package/dist/chunk-ZJZQ7Q2Q.js +3 -0
  168. package/dist/{chunk-EMNIHCRB.js → chunk-ZNQCR656.js} +2 -2
  169. package/dist/{chunk-TIIC3ZE7.js → chunk-ZOEDRCR4.js} +2 -2
  170. package/dist/cli-context-TSADTXLB.js +2 -0
  171. package/dist/cli-context-XEPPF4RX.js +3 -0
  172. package/dist/cli-program-KJGQEM72.js +7 -0
  173. package/dist/cli.js +1 -1
  174. package/dist/{code-DlqpBDd0.d.ts → code-CDe-mIjx.d.ts} +1 -1
  175. package/dist/code-viewer-YGDON6SY.js +12 -0
  176. package/dist/code-viewer-ZCTHXQ5C.js +11 -0
  177. package/dist/command-descriptors-5VAB2MZX.js +335 -0
  178. package/dist/command-descriptors-EAHKIRAG.js +337 -0
  179. package/dist/{config-types-BNoC96J3.d.ts → config-types-D6X5S68_.d.ts} +50 -0
  180. package/dist/{db-D7sauVFH.d.ts → db-DmRNdCtm.d.ts} +1 -1
  181. package/dist/direct-navigation-B3SGOOBW.js +2 -0
  182. package/dist/direct-navigation-ZL362KXF.js +3 -0
  183. package/dist/{graph-evidence-BIFqyisO.d.ts → graph-evidence-Bs54NWws.d.ts} +1 -1
  184. package/dist/{health-DJaZXg8I.d.ts → health-BnzbSLCE.d.ts} +1 -1
  185. package/dist/index.d.ts +2 -2
  186. package/dist/index.js +1 -1
  187. package/dist/invocation-command-descriptors-CSUGUHTT.js +2 -0
  188. package/dist/invocation-command-descriptors-PPVZOIE5.js +3 -0
  189. package/dist/output-continuation-command-FTVVBVSN.js +2 -0
  190. package/dist/output-continuation-command-ITPRC3YV.js +3 -0
  191. package/dist/project-reindex-7HZSLLLY.js +3 -0
  192. package/dist/project-reindex-NGM3DYBN.js +2 -0
  193. package/dist/queries/affected.d.ts +2 -2
  194. package/dist/queries/affected.js +1 -1
  195. package/dist/queries/anchors.d.ts +2 -2
  196. package/dist/queries/anchors.js +1 -1
  197. package/dist/queries/architecture.d.ts +2 -2
  198. package/dist/queries/architecture.js +1 -1
  199. package/dist/queries/bottlenecks.d.ts +2 -2
  200. package/dist/queries/bottlenecks.js +1 -1
  201. package/dist/queries/by-kind.d.ts +2 -2
  202. package/dist/queries/by-kind.js +1 -1
  203. package/dist/queries/call-graph.d.ts +2 -2
  204. package/dist/queries/call-graph.js +1 -1
  205. package/dist/queries/change-surface.d.ts +2 -2
  206. package/dist/queries/change-surface.js +1 -1
  207. package/dist/queries/cleanup-plan.d.ts +2 -2
  208. package/dist/queries/cleanup-plan.js +1 -1
  209. package/dist/queries/co-change.d.ts +2 -2
  210. package/dist/queries/co-change.js +1 -1
  211. package/dist/queries/code.d.ts +3 -3
  212. package/dist/queries/code.js +1 -1
  213. package/dist/queries/complexity-hotspots.d.ts +2 -2
  214. package/dist/queries/complexity-hotspots.js +1 -1
  215. package/dist/queries/complexity.d.ts +2 -2
  216. package/dist/queries/complexity.js +1 -1
  217. package/dist/queries/context.d.ts +2 -2
  218. package/dist/queries/context.js +1 -1
  219. package/dist/queries/convergence.d.ts +2 -2
  220. package/dist/queries/convergence.js +1 -1
  221. package/dist/queries/coupling.d.ts +2 -2
  222. package/dist/queries/coupling.js +1 -1
  223. package/dist/queries/cycles.d.ts +2 -2
  224. package/dist/queries/cycles.js +1 -1
  225. package/dist/queries/dataflow.d.ts +2 -2
  226. package/dist/queries/dataflow.js +1 -1
  227. package/dist/queries/dead.d.ts +2 -2
  228. package/dist/queries/dead.js +1 -1
  229. package/dist/queries/decorative-checkers.d.ts +2 -2
  230. package/dist/queries/decorative-checkers.js +1 -1
  231. package/dist/queries/deep-chains.d.ts +2 -2
  232. package/dist/queries/deep-chains.js +1 -1
  233. package/dist/queries/dependence-slice.d.ts +3 -3
  234. package/dist/queries/dependence-slice.js +1 -1
  235. package/dist/queries/dependency-depth.d.ts +2 -2
  236. package/dist/queries/dependency-depth.js +1 -1
  237. package/dist/queries/deps.d.ts +2 -2
  238. package/dist/queries/deps.js +1 -1
  239. package/dist/queries/diff-impact.d.ts +2 -2
  240. package/dist/queries/diff-impact.js +1 -1
  241. package/dist/queries/doc-drift.d.ts +2 -2
  242. package/dist/queries/doc-drift.js +1 -1
  243. package/dist/queries/drift.d.ts +2 -2
  244. package/dist/queries/drift.js +1 -1
  245. package/dist/queries/duplicate-bodies.d.ts +2 -2
  246. package/dist/queries/duplicate-bodies.js +1 -1
  247. package/dist/queries/entry-map.d.ts +2 -2
  248. package/dist/queries/entry-map.js +1 -1
  249. package/dist/queries/evidence.d.ts +3 -3
  250. package/dist/queries/evidence.js +1 -1
  251. package/dist/queries/extract-candidates.d.ts +2 -2
  252. package/dist/queries/extract-candidates.js +1 -1
  253. package/dist/queries/fan.d.ts +2 -2
  254. package/dist/queries/fan.js +1 -1
  255. package/dist/queries/files.d.ts +2 -2
  256. package/dist/queries/files.js +1 -1
  257. package/dist/queries/health.d.ts +3 -3
  258. package/dist/queries/health.js +1 -1
  259. package/dist/queries/hierarchy.d.ts +2 -2
  260. package/dist/queries/hierarchy.js +1 -1
  261. package/dist/queries/hotspots.d.ts +2 -2
  262. package/dist/queries/hotspots.js +1 -1
  263. package/dist/queries/imports.d.ts +2 -2
  264. package/dist/queries/imports.js +1 -1
  265. package/dist/queries/incomplete-migration.d.ts +2 -2
  266. package/dist/queries/incomplete-migration.js +1 -1
  267. package/dist/queries/index.d.ts +5 -5
  268. package/dist/queries/index.js +1 -1
  269. package/dist/queries/isolated.d.ts +2 -2
  270. package/dist/queries/isolated.js +1 -1
  271. package/dist/queries/locality-candidates.d.ts +2 -2
  272. package/dist/queries/locality-candidates.js +1 -1
  273. package/dist/queries/members.d.ts +2 -2
  274. package/dist/queries/members.js +1 -1
  275. package/dist/queries/methods.d.ts +2 -2
  276. package/dist/queries/methods.js +1 -1
  277. package/dist/queries/not-implemented.d.ts +2 -2
  278. package/dist/queries/not-implemented.js +1 -1
  279. package/dist/queries/outline.d.ts +2 -2
  280. package/dist/queries/outline.js +1 -1
  281. package/dist/queries/passthrough-candidates.d.ts +2 -2
  282. package/dist/queries/passthrough-candidates.js +1 -1
  283. package/dist/queries/plan-context.d.ts +2 -2
  284. package/dist/queries/plan-context.js +1 -1
  285. package/dist/queries/react-component-duplicates.d.ts +2 -2
  286. package/dist/queries/react-component-duplicates.js +1 -1
  287. package/dist/queries/react-hook-candidates.d.ts +2 -2
  288. package/dist/queries/react-hook-candidates.js +1 -1
  289. package/dist/queries/react-large-component-pressure.d.ts +2 -2
  290. package/dist/queries/react-large-component-pressure.js +1 -1
  291. package/dist/queries/recent-duplicates.d.ts +2 -2
  292. package/dist/queries/recent-duplicates.js +1 -1
  293. package/dist/queries/redundant-reexports.d.ts +2 -2
  294. package/dist/queries/redundant-reexports.js +1 -1
  295. package/dist/queries/reference-neighborhood.d.ts +2 -2
  296. package/dist/queries/reference-neighborhood.js +1 -1
  297. package/dist/queries/reference-reachability.d.ts +2 -2
  298. package/dist/queries/reference-reachability.js +1 -1
  299. package/dist/queries/refs.d.ts +2 -2
  300. package/dist/queries/refs.js +1 -1
  301. package/dist/queries/self-audit.d.ts +2 -2
  302. package/dist/queries/self-audit.js +1 -1
  303. package/dist/queries/similar-chains.d.ts +2 -2
  304. package/dist/queries/similar-chains.js +1 -1
  305. package/dist/queries/similar-files.d.ts +2 -2
  306. package/dist/queries/similar-files.js +1 -1
  307. package/dist/queries/similar-signatures.d.ts +2 -2
  308. package/dist/queries/similar-signatures.js +1 -1
  309. package/dist/queries/similar.d.ts +2 -2
  310. package/dist/queries/similar.js +1 -1
  311. package/dist/queries/slice.d.ts +2 -2
  312. package/dist/queries/slice.js +1 -1
  313. package/dist/queries/source-inspection.d.ts +4 -4
  314. package/dist/queries/source-inspection.js +1 -1
  315. package/dist/queries/source-search.d.ts +2 -2
  316. package/dist/queries/source-search.js +1 -1
  317. package/dist/queries/stale-abstractions.d.ts +2 -2
  318. package/dist/queries/stale-abstractions.js +1 -1
  319. package/dist/queries/stats.d.ts +2 -2
  320. package/dist/queries/surface.d.ts +2 -2
  321. package/dist/queries/surface.js +1 -1
  322. package/dist/queries/symbols.d.ts +2 -2
  323. package/dist/queries/symbols.js +1 -1
  324. package/dist/queries/system-map.d.ts +2 -2
  325. package/dist/queries/system-map.js +1 -1
  326. package/dist/queries/system.d.ts +2 -2
  327. package/dist/queries/system.js +1 -1
  328. package/dist/queries/test-quality.d.ts +2 -2
  329. package/dist/queries/test-quality.js +1 -1
  330. package/dist/queries/trace.d.ts +2 -2
  331. package/dist/queries/trace.js +1 -1
  332. package/dist/queries/twin-ab.d.ts +2 -2
  333. package/dist/queries/twin-ab.js +1 -1
  334. package/dist/queries/twin-drift.d.ts +2 -2
  335. package/dist/queries/twin-drift.js +1 -1
  336. package/dist/queries/unused-imports.d.ts +2 -2
  337. package/dist/queries/unused-imports.js +1 -1
  338. package/dist/queries/unused-params.d.ts +2 -2
  339. package/dist/queries/unused-params.js +1 -1
  340. package/dist/queries/value-flow.d.ts +3 -3
  341. package/dist/queries/value-flow.js +1 -1
  342. package/dist/queries/vue-component-duplicates.d.ts +2 -2
  343. package/dist/queries/vue-component-duplicates.js +1 -1
  344. package/dist/queries/vue-composable-candidates.d.ts +2 -2
  345. package/dist/queries/vue-composable-candidates.js +1 -1
  346. package/dist/queries/vue-large-view-pressure.d.ts +2 -2
  347. package/dist/queries/vue-large-view-pressure.js +1 -1
  348. package/dist/queries/wrapper-candidates.d.ts +2 -2
  349. package/dist/queries/wrapper-candidates.js +1 -1
  350. package/dist/reindex-worker.js +1 -1
  351. package/dist/reindex.d.ts +3 -3
  352. package/dist/reindex.js +31 -31
  353. package/dist/runtime.d.ts +24 -4
  354. package/dist/runtime.js +3 -3
  355. package/dist/rust-semantic-session-server.js +1 -1
  356. package/dist/rust-semantic-session-worker.js +1 -1
  357. package/dist/rust-semantic-worker.js +1 -1
  358. package/dist/{scip-cli-B7N3haxa.d.ts → scip-cli-BRFKkHQn.d.ts} +1 -1
  359. package/dist/sentinel-ensure-command-KYYULCFU.js +2 -0
  360. package/dist/sentinel-ensure-command-RIZA3RY7.js +3 -0
  361. package/dist/sentinel-hook.js +39 -0
  362. package/dist/sentinel-worker.js +16 -0
  363. package/dist/typescript-mailbox-worker.js +1 -1
  364. package/dist/watch-server.js +6 -6
  365. package/docs/COMMAND_REFERENCE.md +5 -3
  366. package/docs/schemas/project-config.schema.json +159 -0
  367. package/package.json +9 -5
  368. package/skills/codebaseiq/SKILL.md +1 -1
  369. package/skills/concrete-plan/SKILL.md +1 -1
  370. package/ui/view/api.js +450 -0
  371. package/ui/view/app.js +394 -0
  372. package/ui/view/builder.js +323 -0
  373. package/ui/view/file-panel.js +170 -0
  374. package/ui/view/focus.js +379 -0
  375. package/ui/view/index.html +54 -0
  376. package/ui/view/map.js +424 -0
  377. package/ui/view/styles.css +1125 -0
  378. package/dist/chunk-2X7V4HS4.js +0 -88
  379. package/dist/chunk-3IER7Q6H.js +0 -12
  380. package/dist/chunk-3JSXXYTZ.js +0 -345
  381. package/dist/chunk-476NR5B7.js +0 -2
  382. package/dist/chunk-5VKBFZZU.js +0 -3
  383. package/dist/chunk-ADTBPVUZ.js +0 -21
  384. package/dist/chunk-BFFZDZQV.js +0 -2
  385. package/dist/chunk-BMYOV5GP.js +0 -77
  386. package/dist/chunk-C74PPYLA.js +0 -3
  387. package/dist/chunk-CWONGW6P.js +0 -3
  388. package/dist/chunk-DDZ7VHWV.js +0 -20
  389. package/dist/chunk-DR2LURYU.js +0 -3
  390. package/dist/chunk-ECQBG7PW.js +0 -564
  391. package/dist/chunk-FM5BPL4V.js +0 -60
  392. package/dist/chunk-G6XFR4ZL.js +0 -4
  393. package/dist/chunk-GTIYTDRE.js +0 -562
  394. package/dist/chunk-HOA5YGOH.js +0 -3
  395. package/dist/chunk-KUW32IRO.js +0 -2
  396. package/dist/chunk-LTA3BRZX.js +0 -2
  397. package/dist/chunk-NAUD7LCA.js +0 -2
  398. package/dist/chunk-OGTFJ3XD.js +0 -2
  399. package/dist/chunk-Q5ELPRKQ.js +0 -2
  400. package/dist/chunk-QCN62RTF.js +0 -3
  401. package/dist/chunk-QW7EP6WI.js +0 -21
  402. package/dist/chunk-RU65DDUP.js +0 -215
  403. package/dist/chunk-SELM5MER.js +0 -2
  404. package/dist/chunk-SNNWPCN7.js +0 -4
  405. package/dist/chunk-TFZB6XTM.js +0 -239
  406. package/dist/chunk-UXM43C7T.js +0 -3
  407. package/dist/chunk-VFY6Y2H6.js +0 -61
  408. package/dist/chunk-WE5RZHZ7.js +0 -5
  409. package/dist/chunk-Z54RD7VL.js +0 -3
  410. package/dist/cli-context-3SNLDYBM.js +0 -3
  411. package/dist/cli-context-T3B7W6GG.js +0 -2
  412. package/dist/cli-program-YNOXO72B.js +0 -7
  413. package/dist/command-descriptors-6AOUKWW7.js +0 -346
  414. package/dist/command-descriptors-ZFKJSRUP.js +0 -344
  415. package/dist/direct-navigation-DP4LVMRX.js +0 -3
  416. package/dist/direct-navigation-FLUS3BT6.js +0 -2
  417. package/dist/invocation-command-descriptors-QT2JMY5J.js +0 -3
  418. package/dist/invocation-command-descriptors-YN4QJEAX.js +0 -2
  419. package/dist/output-continuation-command-2V2SL4TD.js +0 -2
  420. package/dist/output-continuation-command-65J5IP3O.js +0 -3
  421. package/dist/project-reindex-5JOKXAXT.js +0 -2
  422. package/dist/project-reindex-UQBIKO4M.js +0 -3
@@ -1,562 +0,0 @@
1
- import{b as ft,c as jc}from"./chunk-ZZ3MWF33.js";import{A as Zt,B as up,C as dp,D as mp,E as Bc,F as pp,I as fp,J as Tr,K as gp,L as Hn,M as hp,N as yp,O as bp,S as Mr,T as fs,X as Ep,Y as $c,a as Dm,b as Tm,c as Mm,d as Oe,f as Pr,h as kc,i as _c,j as V,k as Oc,l as $n,m as op,n as Sn,o as Ki,p as sp,q as pe,r as rt,s as li,t as ms,u as ap,v as cp,w as lp,x as ps,y as Qt,z as jn}from"./chunk-NCZUNH3E.js";import{a as Ip,b as Lp,c as Pp,d as ui,i as hs,j as ys,k as Dp,l as bs,o as Tp}from"./chunk-NNO6A2PO.js";import{a as gs}from"./chunk-P5XHIJHI.js";import{h as wp}from"./chunk-5VKBFZZU.js";import{c as _p}from"./chunk-FAJQ7LWY.js";import{E as Np,G as Cs,P as Hc,R as kp,a as Mp,b as di,c as Ap,f as Ss,s as vs,t as Fp}from"./chunk-Z54RD7VL.js";import{$ as On,A as Wm,D as ae,F as ee,G as Vm,H as ss,I as Nt,J as Xt,K as Jm,L as kt,M as ji,N as Ym,P as Lr,Q as Ce,R as cs,T as ls,U as Xm,a as Ht,b as Ft,c as yn,ca as zi,da as Gi,e as Hm,f as Um,fa as tp,g as Fc,ga as J,h as zm,ha as ze,i as xt,ia as np,j as wr,ja as ip,k as Je,ka as Dr,la as us,ma as rp,na as Ge,p as se,pa as ds,q as ie,r as is,s as rs,t as os,u as He,v as bn,w as Ir,x as Km,y as qm,z as ye}from"./chunk-RU65DDUP.js";import{d as Qo,p as Gm,q as Nc}from"./chunk-QW7EP6WI.js";import{a as Bi,b as Me,e as he,f as ns,i as $i,j as as}from"./chunk-3IER7Q6H.js";import{a as $m,b as jm,d as Ac}from"./chunk-FM5BPL4V.js";import{a as Hi,b as Qm,c as k,d as re,e as Bn,f as it,g as ke,h as Le,i as at,j as Ui,k as Zm,l as ep}from"./chunk-DRENNWRG.js";import{a as Lc,j as ts,l as Oi,r as Yt,s as Bm,t as Sp,u as vp,x as Cp,y as xp,z as Rp}from"./chunk-RDBI2RXU.js";import{a as mt,g as Fm,i as $}from"./chunk-R2NOK63J.js";import{a as Pm,b as Xo,c as Er,d as Zo}from"./chunk-EF2R3WNQ.js";import{$ as _m,A as pt,B as Mt,F as hn,G as ci,R as Pc,S as Dc,X as km,Z as Tc,aa as Mc,ba as nt,c as Jo,ca as Ct,da as At,ea as Om,f as Yo,g as Lm,h as vt,o as Am,y as Nm,z as es}from"./chunk-WE5RZHZ7.js";import{existsSync as KR}from"fs";import{isAbsolute as qR,join as WR}from"path";function ct(e,t){let n=Bp(e,t,{allowMultiple:!1})[0]?.relativePath;return n||Op(e,t)}function vn(e,t){return Bp(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function Op(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),i=qR(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,r=WR(e.config.projectRoot,i);return KR(r)?i:null}function Bp(e,t,n){let i=ns(e,t,n);if(i.length===0){if(Op(e,t))return[];let r=pe(e,t);return!r||e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,score:700}]}return i}function $p(e,t){let n=vn(e,t),i=us(e,n,{sort:!0});if(i.length===0)return[];let r=i.map(a=>({symbol:a.symbol,shortName:a.shortName,startLine:a.startLine,endLine:a.endLine,signature:a.signature,children:[]})),o=new Map;for(let a of r)o.set(a.symbol,a);let s=[];for(let a=0;a<i.length;a++){let c=i[a],l=r[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 r)if(m!==l&&m.startLine<=l.startLine&&m.endLine>=l.endLine){if(m.startLine===l.startLine&&m.endLine===l.endLine&&!ep(m.symbol,l.symbol))continue;let f=m.endLine-m.startLine;f<d&&(d=f,u=m)}u?u.children.push(l):s.push(l)}return s}import{basename as tw,extname as yf}from"path";function Rt(e,t){let n=ie(e,t.relativePath);if(n.length===0)return!1;let i=re(t.symbol);if(!i)return!1;let r=n.slice(Math.max(0,t.startLine-2),t.startLine+1).join(`
2
- `),o=He(i);return new RegExp(`^\\s*export\\s+(?:default\\s+)?(?:(?:async\\s+)?function\\s+${o}\\b|(?:abstract\\s+)?class\\s+${o}\\b|(?:interface|type|enum|namespace|module)\\s+${o}\\b|(?:const|let|var)\\s+${o}\\b)`,"m").test(r)?!0:VR(n,i)}function VR(e,t){if(!t)return!1;let n=new RegExp(`^\\s*export\\s*\\{[^}\\n]*\\b${He(t)}\\b`);return e.some(i=>n.test(i))}import{createHash as JR}from"crypto";import{TextDecoder as YR}from"util";var XR=new YR("utf-8",{fatal:!0});function Uc(e){return Om(e.config.projectRoot)}function xs(e,t){let n=hn(t),i;try{i=Mc(e.config.projectRoot,n,{inputKind:"repository text file"})}catch(o){if(Ct(o)||o instanceof Tc)return null;throw o}let r=Gp(i);return r===null?null:Hp(n,i,r,zp(e),Up(e))}function Rs(e,t={}){let n=Uc(e).filter(u=>!t.scope||u.includes(t.scope)),i=zp(e),r=Up(e),o=[],s=[],a=[],c=[],l=0;for(let u of n){let d;try{d=Mc(e.config.projectRoot,u,{inputKind:"repository text file"})}catch(p){if(p instanceof Tc){c.push(u);continue}if(Ct(p))continue;a.push(u);continue}let m=Gp(d);if(m===null){s.push(u);continue}l+=d.byteLength,o.push(Hp(u,d,m,i,r))}return{files:o,candidateFiles:n.length,scannedBytes:l,skippedBinaryPaths:s,skippedUnreadablePaths:a,skippedOversizedPaths:c}}function Hp(e,t,n,i,r){let o=JR("sha256").update(t).digest("hex");return{relativePath:e,text:n,bytes:t.byteLength,freshness:{exactText:{state:"current",basis:"working-tree-read",sha256:o},semantic:QR(e,o,i,r)}}}function QR(e,t,n,i){if(!i.has(e))return{state:"unavailable",basis:"no-compiler-document"};let r=n.get(e);return r?{state:r===t?"aligned":"stale",basis:"indexed-input-fingerprint"}:{state:"unavailable",basis:"fingerprint-unavailable"}}function Up(e){return new Set(e.all(`SELECT documents.relative_path FROM documents WHERE 1 = 1 ${e.pathExclusionsFor("documents")}`).map(t=>t.relative_path))}function zp(e){let t=new Map;if(!e.generation.metadataRaw)return t;let n=Qo(e.generation.metadataRaw);if(n.kind!=="legacy"&&n.kind!=="supported")return t;let i=n.metadata.fingerprint;if(!jp(i)||!Array.isArray(i.files))return t;for(let r of i.files)!jp(r)||typeof r.path!="string"||typeof r.hash!="string"||t.set(r.path,r.hash);return t}function Gp(e){if(e.includes(0))return null;try{return XR.decode(e)}catch{return null}}function jp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{SymbolInformation_Kind as Re}from"@c4312/scip";var Es=new Map(Object.entries(Re).filter(([e,t])=>Number.isInteger(Number(e))&&typeof t=="string").map(([e,t])=>[Number(e),t])),Kp=new Map([...Es.entries()].map(([e,t])=>[t.toLowerCase(),e]));function Ar(e){return Es.get(e)??"Unknown"}function en(){return[Re.Function,Re.Method,Re.Macro,Re.Constructor,Re.Getter,Re.Setter,Re.StaticMethod,Re.SingletonMethod,Re.AbstractMethod,Re.ProtocolMethod,Re.TraitMethod]}function qp(){return[Re.Class,Re.Interface,Re.Struct,Re.Trait,Re.Type,Re.TypeAlias,Re.Enum,Re.Union,Re.Protocol]}function YW(){return[Re.Constant,Re.Variable,Re.Value,Re.Field,Re.Property,Re.StaticDataMember,Re.StaticField,Re.StaticProperty,Re.StaticVariable,Re.EnumMember]}function ws(e,t,n={}){return mi(e,t,n).rows}function mi(e,t,n={}){let i=Fr(e,[t],{additive:n.additive,semantic:n.semantic,semanticEvidence:n.semanticEvidence}),r=n.callableOnly?(i.rows.get(t.symbolId)??[]).filter(o=>it(o.symbol)||o.source==="ast-callsite"):i.rows.get(t.symbolId)??[];return{rows:typeof n.limit=="number"?r.slice(0,n.limit):r,semanticIncomplete:i.incompleteSymbolIds.has(t.symbolId),semanticUnavailable:i.unavailableSymbolIds.has(t.symbolId)}}function Is(e,t,n){return Gc(e,t,n).rows}function Gc(e,t,n){let i=tn(e,[t],n);return{rows:i.rows.get(t.symbolId)??[],semanticIncomplete:i.incompleteSymbolIds.has(t.symbolId),semanticUnavailable:i.unavailableSymbolIds.has(t.symbolId)}}function Vp(e,t,n){return tn(e,t,n).rows}function tn(e,t,n){let i=iE(e)?oE(e,t,{semantic:n.semantic!==!1,semanticEvidence:n.semanticEvidence}):rE(e,n.semanticEvidence,{semantic:n.semantic!==!1});return{rows:new Map(t.map(o=>[o.symbolId,typeof n.limit=="number"?(i.rows.get(o.symbolId)??[]).slice(0,n.limit):i.rows.get(o.symbolId)??[]])),incompleteSymbolIds:new Set(t.filter(o=>i.incompleteSymbolIds.has(o.symbolId)).map(o=>o.symbolId)),unavailableSymbolIds:new Set(t.filter(o=>i.unavailableSymbolIds.has(o.symbolId)).map(o=>o.symbolId))}}var ZR=Me("caller-rows",{clearGroups:["whole-project"]}),eE=Me("caller-rows-non-semantic",{clearGroups:["whole-project"]}),tE=Me("targeted-caller-strategy",{clearGroups:["whole-project"]}),nE=2e4;function iE(e){return tE.get(e,()=>(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>nE)}function rE(e,t,n={}){return(n.semantic===!1?eE:ZR).get(e,()=>{let r=ze(e),o=Fr(e,r,{semantic:n.semantic!==!1,semanticEvidence:t}),s=new Map;for(let l of r)s.set(l.symbol,l.symbolId);let a=new Map,c=new Map;for(let l of r){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 p=a.get(m);p||(p=[],a.set(m,p),c.set(m,new Set));let f=`${l.symbol}|${l.relativePath}`;c.get(m).has(f)||(c.get(m).add(f),p.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(r.map(l=>l.symbolId)),unavailableSymbolIds:o.unavailableSymbolIds.size===0?new Set:new Set(r.map(l=>l.symbolId))}})}function oE(e,t,n){let i=n.semantic&&n.semanticEvidence?t.flatMap(u=>{let d=sE(e,u);return d?[d]:[]}):[],r=new Map(i.map(u=>[u.symbolId,u])),o=n.semantic&&n.semanticEvidence?n.semanticEvidence.referenceEvidenceMap(e,i):{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set},s=gp(e,t),a=new Map;for(let u of t){let d=[],m=new Set,p=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&&p({symbol:g.enclosingSymbol??g.file,file:g.file,source:"resolved-reference"});let f=r.get(u.symbolId);if(f)for(let g of o.rows.get(f.symbolId)??[]){if(g.file===u.relativePath||e.isIgnored(g.file))continue;let h=Ge(J(e,g.file),g.line);p({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)r.has(u.symbolId)||c.add(u.symbolId);return{rows:a,incompleteSymbolIds:c,unavailableSymbolIds:l}}function sE(e,t){let n=en().join(", "),i=qp().join(", ");return e.get(`SELECT
3
- d.id AS documentId,
4
- gs.id AS symbolId,
5
- gs.symbol,
6
- d.relative_path AS relativePath,
7
- COALESCE(der.start_line, c.start_line) AS startLine,
8
- COALESCE(der.end_line, c.end_line) AS endLine,
9
- COALESCE(gs.display_name, '') AS leaf,
10
- NULL AS parentTypeName,
11
- CASE WHEN gs.kind IN (${n}) OR gs.symbol LIKE '%().' THEN 1 ELSE 0 END AS isFunctionLike,
12
- CASE WHEN gs.kind IN (${i}) THEN 1 ELSE 0 END AS isTypeLike,
13
- gs.kind AS kind,
14
- gs.documentation AS documentation,
15
- gs.enclosing_symbol AS enclosingSymbol
16
- FROM global_symbols gs
17
- LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
18
- LEFT JOIN chunks c ON c.document_id = der.document_id
19
- JOIN documents d ON d.id = COALESCE(der.document_id, c.document_id)
20
- WHERE gs.id = ?
21
- LIMIT 1`,t.symbolId)??null}function Kc(e,t,n={}){return Fr(e,t,n).rows}function Fr(e,t,n={}){if(t.length===0)return{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set};let i=n.additive??!1,r=[],o=[];for(let m of t)ye(m.relativePath)&&Xt(e,m.relativePath)!==null?r.push(m):o.push(m);let s=new Map,a=new Map,c=m=>{for(let[p,f]of m){let g=s.get(p);g||(g=[],s.set(p,g));let h=a.get(p);h||(h=new Set,a.set(p,h));for(let b of f){let v=`${b.symbol}|${b.chunkId}`;h.has(v)||(h.add(v),g.push(b))}}};r.length>0&&c(aE(e,r));let l=new Set,u=new Set;if(n.semantic!==!1&&n.semanticEvidence){let m=n.semanticEvidence.calleeEvidenceMap(e,t);c(pE(m.rows));for(let p of m.incompleteSymbolIds)l.add(p);for(let p of m.unavailableSymbolIds)u.add(p)}else if(n.semantic!==!1)for(let m of t)u.add(m.symbolId);let d=i?t:o;return d.length>0&&c(dE(e,d)),{rows:s,incompleteSymbolIds:l,unavailableSymbolIds:u}}function aE(e,t){let n=new Map,i=cE(t,n),r=Zt(e);for(let[o,s]of i){let a=Xt(e,o);if(!a)continue;let c=rp(s);for(let l of a){let u=c.get(l.line);if(!u)continue;let d=lE(e,o,r,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 cE(e,t){let n=new Map;for(let i of e){let r=n.get(i.relativePath);r?r.push(i):n.set(i.relativePath,[i]),t.set(i.symbolId,[])}for(let i of n.values())i.sort((r,o)=>r.endLine-r.startLine-(o.endLine-o.startLine));return n}function lE(e,t,n,i){let r=Qt(t,n.get(i.calleeLeaf)??[]);if(r.length===0)return null;let o=uE(e,t,r,i.calleeQualifier);return o||jn(e,t,r,i.memberAccess,i.calleeQualifier)}function uE(e,t,n,i){if(!i||ye(t)!=="clojure")return null;let o=Ce(e,t).filter(s=>s.kind==="namespace"&&s.localName===i&&s.sourcePath).map(s=>s.sourcePath);for(let s of o){let a=n.find(c=>Mt(s,c.file));if(a)return a}return n.find(s=>/`([^`]+)`\//.exec(s.symbol)?.[1]===i)??null}function dE(e,t){if(t.length===0)return new Map;let i=zc(t.map(p=>p.documentId)).flatMap(p=>e.all(`SELECT c.document_id, c.id AS chunk_id, c.start_line, c.end_line, m.symbol_id
22
- FROM mentions m
23
- JOIN chunks c ON m.chunk_id = c.id
24
- WHERE m.role != 1
25
- AND c.document_id IN (${p.map(()=>"?").join(",")})`,...p)),r=new Map;for(let p of i)r.has(p.document_id)||r.set(p.document_id,[]),r.get(p.document_id).push(p);let s=zc(i.map(p=>p.symbol_id)).flatMap(p=>e.all(`SELECT gs.id AS symbol_id, gs.symbol,
26
- COALESCE(der.document_id, def_chunk.document_id) AS document_id
27
- FROM global_symbols gs
28
- LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
29
- LEFT JOIN (
30
- SELECT m.symbol_id, MIN(c.document_id) AS document_id
31
- FROM mentions m
32
- JOIN chunks c ON m.chunk_id = c.id
33
- WHERE m.role = 1
34
- AND m.symbol_id IN (${p.map(()=>"?").join(",")})
35
- GROUP BY m.symbol_id
36
- ) def_chunk ON def_chunk.symbol_id = gs.id
37
- WHERE gs.id IN (${p.map(()=>"?").join(",")})`,...p,...p)),a=zc([...t.map(p=>p.documentId),...s.flatMap(p=>p.document_id===null?[]:[p.document_id])]),c=new Map(a.flatMap(p=>e.all(`SELECT id, relative_path FROM documents
38
- WHERE id IN (${p.map(()=>"?").join(",")})`,...p).map(f=>[f.id,f.relative_path]))),l=new Map;for(let p of s)l.has(p.symbol_id)||l.set(p.symbol_id,{symbol:p.symbol,file:p.document_id!==null?c.get(p.document_id)??"":""});let u=new Map,d=c,m=mE(t);for(let[p,f]of m){let h=[...r.get(p)??[]].sort((E,w)=>E.start_line-w.start_line||E.end_line-w.end_line),b=[...f].sort((E,w)=>E.startLine-w.startLine||E.endLine-w.endLine),v=new Set,y=0;for(let E of b){for(;y<h.length&&h[y].start_line<=E.endLine;)v.add(h[y]),y+=1;for(let L of v)L.end_line<E.startLine&&v.delete(L);let w=new Set,S=[],R=null,C=()=>{if(R)return R;let L=d.get(E.documentId)??"",I=new Set;if(L){let x=sp(e,L),D=Math.max(0,E.startLine),_=Math.min(x.length-1,E.endLine);for(let P=D;P<=_;P+=1)for(let T of x[P])I.add(T)}return R=I,I};for(let L of v){if(L.symbol_id===E.symbolId)continue;let I=l.get(L.symbol_id);if(!I)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 P=re(I.symbol);if(!P||!C().has(P))continue}let D=`${I.symbol}|${L.chunk_id}`;w.has(D)||(w.add(D),S.push({...I,chunkId:L.chunk_id,source:"scip-chunk"}))}u.set(E.symbolId,S)}}return u}var Wp=500;function zc(e){let t=[...new Set(e)],n=[];for(let i=0;i<t.length;i+=Wp)n.push(t.slice(i,i+Wp));return n}function mE(e){let t=new Map;for(let n of e){let i=t.get(n.documentId);i?i.push(n):t.set(n.documentId,[n])}return t}function pE(e){let t=new Map;for(let[n,i]of e){let r=[];for(let o of i)r.push({symbol:o.symbol,file:o.file,chunkId:-1,source:"semantic-callee",...o.callsiteLine===void 0?{}:{callsiteLine:o.callsiteLine}});t.set(n,r)}return t}var fE=12,gE=280;function qi(e,t,n,i){let r=hE(e,t,n,i);if(r.size===0)return vE();let o=[],s=new Set,a=(l,u,d,m)=>{if(u===t&&d<=i&&m>=n)return;let p=`${u}:${d}:${m}:${l}`;s.has(p)||(s.add(p),o.push({name:l,relativePath:u,startLine:d,endLine:m}))};for(let l of J(e,t))r.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||!r.has(u)||!l.sourcePath||l.kind==="namespace")continue;let d=l.importedName==="default"?u:l.importedName;for(let m of $n(e,l.sourcePath,d,{maxReexportDepth:3}))a(u,m.relativePath,m.startLine,m.endLine)}o.sort(Yp);let c=o.map(l=>{let u=yE(e,l);return u?{...l,source:u}:null}).filter(l=>l!==null).slice(0,fE);return qc(c)}function Ls(e,t=[]){return qc(bE(e.flatMap(n=>n?.inline??[]),t))}function Jp(e){return e?e.inline.reduce((t,n)=>t+n.name.length+n.source.length+32,0):0}function hE(e,t,n,i){let r=ee(e,t),o=new Set;if(!r)return o;for(let s=n;s<=i;s+=1)for(let a of r.identifiersByLine[s]??[])o.add(a);return o}function yE(e,t){if(t.startLine!==t.endLine)return null;let n=(ie(e,t.relativePath)[t.startLine]??"").trim();if(!n||n.length>gE)return null;let i=n.indexOf("=");if(i<0||n[i+1]===">")return null;let r=n.slice(i+1).replace(/(?:\/\/|#).*$/u,"").trim();if(!r||r.includes("${")||/\b(?:function|class|struct|interface|trait|enum|lambda)\b/u.test(r))return null;let s=r.replace(/(['"`])(?:\\.|(?!\1).)*\1/gu,"").replace(/\b(?:0[xX][\dA-Fa-f_]+|0[bB][01_]+|0[oO][0-7_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:[eE][+-]?\d+)?)n?\b/gu,""),a=new Set(["true","false","null","undefined","None","True","False"]);return(s.match(/[A-Za-z_][A-Za-z0-9_]*/gu)??[]).some(l=>!a.has(l))?null:n}function bE(e,t){let n=new Map;for(let i of e){if(SE(i,t))continue;let r=`${i.relativePath}:${i.startLine}:${i.endLine}:${i.name}`;n.has(r)||n.set(r,{...i})}return[...n.values()].sort(Yp)}function SE(e,t){return t.some(n=>n.relativePath===e.relativePath&&n.startLine<=e.startLine&&n.endLine>=e.endLine)}function Yp(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||e.name.localeCompare(t.name)}function qc(e){return{coverage:"indexed-project-literal-values",inline:e}}function vE(){return qc([])}var CE=12,xE=20,Vc=200,Jc=800,RE=.9,Qp={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"},Fs=["anchor","signature","binding","branch","loop","call","await","return","throw","mutation","shape","spread","catch","finally"],Zp=[...Fs,"lifecycle"],ef=["loop","await","throw","mutation","spread","catch","finally","lifecycle"],EE=new Set(["onBeforeMount","onBeforeUnmount","onMounted","onUnmounted","useEffect","useInsertionEffect","useLayoutEffect"]);var tf=new Set(["object","object_pattern","dictionary","field_declaration_list","struct_expression","struct_pattern"]);function Wi(e,t,n,i,r=[],o={}){let s=ae(e,t);if(!s)return null;let a=ie(e,t),c=gt(e,t,n,i,r),l=_s(e,t,c.startLine,c.endLine),u=l?.startLine??n,d=l?.endLine??i,m=(l?Vi(s.rootNode,c.startLine,c.endLine):null)??Hr(s.rootNode,u,d);if(!m)return null;let p=af(m,a,u,d,r);if(!p||p.lines.length===0||p.lines.some(b=>b.text.length>Jc))return null;let f=UE(a,u,d),g=zE(p);if((o.requireSavings??!0)&&g>=f*RE)return null;let h=Fs.filter(b=>p.lines.some(v=>v.signals.includes(b)));return{...l?{callable:{name:l.name,startLine:l.startLine,endLine:l.endLine}}:{},representation:"outline",constructKind:p.constructKind,signature:p.signature,lines:p.lines,signals:h,testCases:V(t)==="test"?VE(a,u,d):[],coverage:{sourceStatements:p.sourceStatements,representedStatements:p.sourceStatements,copiedStatements:p.copiedStatements,omittedStatements:0},rawCharacters:f,outlineCharacters:g,candidateLines:p.sourceStatements,omittedLines:0}}function Ns(e,t,n,i,r){if(r.length===0)return[];let o=ae(e,t);if(!o)return[];let s=ie(e,t),a=gt(e,t,n,i,r),c=_s(e,t,a.startLine,a.endLine),l=c?.startLine??n,u=c?.endLine??i,d=(c?Vi(o.rootNode,a.startLine,a.endLine):null)??Hr(o.rootNode,l,u);if(!d)return[];let m=af(d,s,l,u,r);return m?m.lines.filter(p=>p.text.length<=Jc&&p.signals.some(f=>["branch","loop","catch","finally"].includes(f))&&r.some(f=>f>=p.line&&f<=p.endLine)):[]}function nf(e,t,n,i){let r=ae(e,t);if(!r)return null;let o=Vi(r.rootNode,n,i)??Hr(r.rootNode,n,i);if(!o)return null;let s=[],a=Qc(o),c=[];return Zc(o,o,l=>{if(kr.has(l.type)||wE.has(l.type)){LE(s,c,l);return}if(ks.has(l.type)){PE(s,c,l);return}if($r.has(l.type)){DE(s,c,l);return}jr.has(l.type)&&TE(s,l)}),{facts:kE(s),terminals:sf(a),unsupported:c}}function gt(e,t,n,i,r=[]){let o=r.filter(d=>d>=n&&d<=i),s=ae(e,t);if(o.length>0&&s){let d=[];pi(s.rootNode,p=>{_E(p)&&p.startPosition.row>=n&&p.endPosition.row<=i&&o.every(f=>p.startPosition.row<=f&&p.endPosition.row>=f)&&d.push(p)});let m=d.sort((p,f)=>p.endPosition.row-p.startPosition.row-(f.endPosition.row-f.startPosition.row)||p.startPosition.row-f.startPosition.row)[0];if(m)return{startLine:m.startPosition.row,endLine:m.endPosition.row}}let a=_s(e,t,n,i);if(a)return{startLine:a.startLine,endLine:a.endLine};if(o.length===0)return{startLine:n,endLine:i};let c=(ee(e,t)?.callables??[]).filter(d=>d.startLine>=n&&d.endLine<=i&&o.every(m=>d.startLine<=m&&d.endLine>=m)).sort((d,m)=>d.endLine-d.startLine-(m.endLine-m.startLine)||d.startLine-m.startLine)[0];if(!s)return c?{startLine:c.startLine,endLine:c.endLine}:{startLine:n,endLine:i};let l=[];pi(s.rootNode,d=>{Un.has(d.type)&&d.startPosition.row>=n&&d.endPosition.row<=i&&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:i}}function Yc(e,t,n,i,r={}){if(i-n+1<(r.minimumBodyLines??xE))return null;let s=lf(e,t,n,i,[],!1);if(!s)return null;let a=s.candidates.map(b=>({...b,signals:b.signals.filter(v=>v!=="anchor"&&v!=="signature")})).filter(b=>b.signals.length>0);if(a.length===0)return null;let c=qE(a),l=a.filter(b=>b.text.length<=Vc);if(l.length===0)return null;let u=ef.filter(b=>(c[b]??0)>0),d=u.filter(b=>b!=="await"),m=s.shapes.reduce((b,v)=>b+v.fields.length,0);if(d.length===0&&!((c.await??0)>0&&m>0)&&m<3)return null;let p=WE(l,c),f=new Map;for(let b of u){let v=p.find(y=>y.signals.includes(b));v&&f.set(v.line,v)}if(f.size===0){let b=p.find(v=>v.signals.includes("branch"));b&&f.set(b.line,b)}let g=Math.min(10,Math.max(1,r.maxLines??f.size)),h=new Map;for(let b of f.values()){if(h.size>=g)break;h.set(b.line,b)}return h.size>=a.length&&s.shapes.length===0?null:{owner:s.callable?.name??null,startLine:n,endLine:i,lines:[...h.values()].sort((b,v)=>b.line-v.line),shapes:s.shapes,signalCounts:c,candidateLines:a.length,omittedLines:a.length-h.size}}function Cn(e,t,n,i){let r=lf(e,t,n,i,[],!1);return r?new Map(r.candidates.map(o=>[o.line,o.signals.filter(s=>s!=="lifecycle")])):new Map}var Un=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"]),kr=new Set(["if_expression","if_statement","unless","unless_statement"]),wE=new Set(["conditional_expression","ternary_expression"]),ks=new Set(["do_statement","enhanced_for_statement","for_expression","for_in_statement","for_of_statement","for_statement","loop_expression","while_statement"]),$r=new Set(["match_expression","match_statement","switch_expression","switch_statement"]),rf=new Set(["case_statement","match_arm","switch_case","switch_default"]),jr=new Set(["try_expression","try_statement"]),Ts=new Set(["catch_clause","except_clause","rescue"]),Or=new Set(["ensure","finally_clause"]),_r=new Set(["else","else_clause"]),of=new Set(["raise_statement","return_statement","throw_statement"]),IE=new Set(["block_comment","comment","line_comment"]);function LE(e,t,n){let i=n.childForFieldName("condition")??tl(n),r=n.childForFieldName("consequence")??n.childForFieldName("body")??n.namedChildren.find(c=>Et.has(c.type)),o=n.childForFieldName("alternative")??n.namedChildren.find(c=>_r.has(c.type));if(!i||!r){t.push(el(n,"conditional-fields-unresolved"));return}let s=rn(i,"predicate",i.text),a=rn(r,Xp(r),"consequence");if(nn(e,s,a,"predicate-consequence",{branchRole:"consequence"}),Ms(e,s,r,"consequence"),o){let c=rn(o,Xp(o),"alternative");nn(e,s,c,"predicate-alternative",{branchRole:"alternative"}),Ms(e,s,o,"alternative");return}nn(e,s,Xc(s,"otherwise continue"),"predicate-fallthrough",{branchRole:"fallthrough"})}function PE(e,t,n){let i=n.childForFieldName("body")??n.namedChildren.find(s=>Et.has(s.type));if(!i){t.push(el(n,"loop-body-unresolved"));return}let r=n.childForFieldName("condition"),o=rn(r??n,"predicate",r?.text??Ut(n,i));nn(e,o,rn(i,"outcome","iteration"),"loop-iteration",{branchRole:"iteration"}),Ms(e,o,i,"iteration"),nn(e,o,Xc(o,"loop exits"),"loop-exit",{branchRole:"exit"})}function DE(e,t,n){let i=n.childForFieldName("body")??n.namedChildren.find(c=>Et.has(c.type)),r=n.childForFieldName("value")??n.childForFieldName("condition")??n.childForFieldName("subject")??tl(n),o=AE(i??n);if(!r||o.length===0){t.push(el(n,"switch-cases-unresolved"));return}let s=rn(r,"predicate",r.text),a=!1;for(let c of o){let l=NE(c);a||=l;let u=Ut(c,c.namedChildren.find(d=>As(d)));nn(e,s,rn(c,"outcome",u||(l?"default":"case")),l?"predicate-default":"predicate-case",{branchRole:l?"default":"case"}),Ms(e,s,c,l?"default":"case")}a||nn(e,s,Xc(s,"no case matched"),"predicate-fallthrough",{branchRole:"fallthrough"})}function TE(e,t){let n=rn(t,"scope","try");for(let i of FE(t)){let r=Or.has(i.type),o=rn(i,"handler",r?"finally":Ut(i,Ps(i)));nn(e,n,o,r?"finally-cleanup":"exception-handler",{branchRole:r?"finally":"catch"}),ME(e,o,i,r?"finally":"catch")}}function ME(e,t,n,i){for(let r of Qc(n)){let o=r.label.startsWith("throw")||r.label.startsWith("raise")?"throw":"return";nn(e,t,r,o==="throw"?"handler-throw":"handler-return",{branchRole:i,terminalKind:o})}}function Ms(e,t,n,i){for(let r of Qc(n)){let o=r.label.startsWith("throw")||r.label.startsWith("raise")?"throw":"return";nn(e,t,r,o==="throw"?"predicate-throw":"predicate-return",{branchRole:i,terminalKind:o})}}function nn(e,t,n,i,r){e.push({controller:t,outcome:n,subtype:i,attributes:r})}function rn(e,t,n){return{kind:t,label:Br(n).slice(0,Jc),startLine:e.startPosition.row,endLine:e.endPosition.row,implicit:!1}}function Xc(e,t){return{...e,kind:"outcome",label:t,implicit:!0}}function Xp(e){return of.has(e.type)?"terminal":"outcome"}function Qc(e){let t=[];return Zc(e,e,n=>{of.has(n.type)&&t.push(rn(n,"terminal",n.text))}),sf(t)}function Zc(e,t,n){n(t);for(let i of t.namedChildren)i!==e&&Un.has(i.type)||Zc(e,i,n)}function AE(e){let t=[],n=i=>{for(let r of i.namedChildren)$r.has(r.type)||(rf.has(r.type)?t.push(r):n(r))};return n(e),t}function FE(e){let t=[],n=i=>{for(let r of i.namedChildren)jr.has(r.type)||(Ts.has(r.type)||Or.has(r.type)?t.push(r):Un.has(r.type)||n(r))};return n(e),t}function NE(e){let t=Ut(e,e.namedChildren.find(n=>As(n))).trim();return e.type==="switch_default"||/^(?:default\b|_\s*=>)/u.test(t)}function el(e,t){return{startLine:e.startPosition.row,endLine:e.endPosition.row,reason:t}}function kE(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 sf(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 _E(e){return Un.has(e.type)||ks.has(e.type)||$r.has(e.type)||jr.has(e.type)||Ts.has(e.type)||Or.has(e.type)}function af(e,t,n,i,r){let s=Vi(e,n,i)??e,a=Ps(s),c=[],l=0,u=0,d=(S,R,C,L,I=!1,x=!0)=>{let D=I?C.trim():Br(C);if(!D)return;let _=Math.max(n,S.startPosition.row),P=Math.min(i,S.endPosition.row);c.push({line:_,endLine:Math.max(_,P),depth:R,signals:Fs.filter(T=>L.includes(T)||T==="anchor"&&r.some(F=>F>=_&&F<=P)),text:D,copied:I}),x&&(l+=1,I&&(u+=1))},m=(S,R)=>{for(let C of S.namedChildren)w(C,R)},p=(S,R)=>{if(kr.has(S.type)){f(S,R,"else if");return}if(_r.has(S.type)){let C=S.namedChildren.find(I=>kr.has(I.type));if(C){f(C,R,"else if");return}d(S,R,"else",["branch"],!1,!1);let L=Ps(S)??S.namedChildren.find(I=>Et.has(I.type));if(L)w(L,R+1);else for(let I of S.namedChildren)w(I,R+1);return}d(S,R,"else",["branch"],!1,!1),w(S,R+1)},f=(S,R,C=S.type.startsWith("unless")?"unless":"if")=>{let L=S.childForFieldName("condition")??tl(S),I=S.childForFieldName("consequence")??S.childForFieldName("body")??S.namedChildren.find(_=>Et.has(_.type)),x=S.childForFieldName("alternative")??S.namedChildren.find(_=>_r.has(_.type)),D=L?L.text:Ut(S,I);d(S,R,`${C} ${jE(D)}`,Nr(L,["branch"])),I&&w(I,R+1),x&&p(x,R)},g=(S,R)=>{let C=S.childForFieldName("body")??S.namedChildren.find(L=>Et.has(L.type));d(S,R,Ut(S,C),Nr(S,["loop"])),C&&w(C,R+1)},h=(S,R)=>{let C=S.childForFieldName("body")??S.namedChildren.find(L=>Et.has(L.type));d(S,R,Ut(S,C),Nr(S,["branch"])),C&&w(C,R+1)},b=(S,R)=>{let C=S.namedChildren.find(L=>As(L));d(S,R,Ut(S,C),["branch"],!1,!1);for(let L of S.namedChildren)(L===C||As(L))&&w(L,R+1)},v=(S,R)=>{d(S,R,"try",[],!1);for(let C of S.namedChildren)Et.has(C.type)?w(C,R+1):(Ts.has(C.type)||Or.has(C.type))&&w(C,R)},y=(S,R,C)=>{let L=S.childForFieldName("body")??S.namedChildren.find(x=>Et.has(x.type)),I=C==="finally"?"finally":Ut(S,L);d(S,R,I,[C],!1,!1),L&&w(L,R+1)},E=(S,R)=>{let C=Ps(S);d(S,R,Ut(S,C),Nr(S,["binding"])),C&&w(C,R+1)},w=(S,R)=>{if(S.startPosition.row>i||S.endPosition.row<n||IE.has(S.type)||S.type==="empty_statement")return;if(Et.has(S.type)){m(S,R);return}if(kr.has(S.type)){f(S,R);return}if(ks.has(S.type)){g(S,R);return}if($r.has(S.type)){h(S,R);return}if(rf.has(S.type)){b(S,R);return}if(jr.has(S.type)){v(S,R);return}if(Ts.has(S.type)){y(S,R,"catch");return}if(Or.has(S.type)){y(S,R,"finally");return}if(_r.has(S.type)){p(S,R);return}if(Un.has(S.type)){E(S,R);return}let L=!cf(S)||HE(S);d(S,R,S.text,Nr(S),L)};return w(a&&a!==s?a:s,0),l===0?null:{constructKind:$E(s),signature:BE(s,a,t,n),lines:c,sourceStatements:l,copiedStatements:u}}function Vi(e,t,n){let i=e.namedChildren.filter(r=>r.startPosition.row<=t&&r.endPosition.row>=n);for(let r of i.sort(OE)){let o=Vi(r,t,n);if(o)return o}return Un.has(e.type)&&e.startPosition.row<=t&&e.endPosition.row>=n?e:null}function OE(e,t){return e.endPosition.row-e.startPosition.row-(t.endPosition.row-t.startPosition.row)||e.startPosition.row-t.startPosition.row}function Ps(e){return e.childForFieldName("body")??e.childForFieldName("consequence")??e.namedChildren.find(t=>Et.has(t.type))??null}function BE(e,t,n,i){let r=Ut(e,t);return r||(n[i]??e.text).trim()}function $E(e){return e.type.includes("constructor")?"constructor":e.type.includes("method")||e.type==="method"?Wc(e,new Set(["class_body","class_declaration","class_definition"]))?"class method":"object method":e.type==="arrow_function"||e.type==="function_expression"||e.type==="lambda"?Wc(e,new Set(["object","pair"]))?"object member":"function value":e.type.includes("function")?Wc(e,Un)?"nested function":"module function":"source construct"}function Wc(e,t){let n=e.parent;for(;n;){if(t.has(n.type))return!0;n=n.parent}return!1}function tl(e){return e.namedChildren.find(t=>!Et.has(t.type)&&!_r.has(t.type))??null}function Ut(e,t){if(!t)return Br(e.text);let n=Math.max(0,t.startIndex-e.startIndex);return Br(e.text.slice(0,n)).replace(/[:{]\s*$/u,"").trim()}function jE(e){let t=Br(e);return t.startsWith("(")&&t.endsWith(")")?t.slice(1,-1).trim():t}function Br(e){return e.trim().replace(/\r?\n[\t ]*/gu," ")}function Nr(e,t=[]){let n=new Set(t);return e&&pi(e,i=>{let r=Qp[i.type];r&&n.add(r),i.type==="call_expression"&&(n.add("call"),uf(i)&&n.add("shape")),nl.has(i.type)&&n.add("binding")}),Fs.filter(i=>n.has(i))}function HE(e){let t=!1;return pi(e,n=>{t||!n.text.includes(`
39
- `)||/(?:string|template|heredoc|raw_string)/u.test(n.type)&&(t=!0)}),t}function As(e){return Et.has(e.type)||kr.has(e.type)||ks.has(e.type)||$r.has(e.type)||jr.has(e.type)||Un.has(e.type)||cf(e)}function cf(e){return/(?:statement|declaration|expression|assignment|return|throw|raise|break|continue|yield|with_item)$/u.test(e.type)||nl.has(e.type)}function UE(e,t,n){let i=0;for(let r=t;r<=n;r+=1)i+=(e[r]?.length??0)+10;return i}function zE(e){return e.constructKind.length+e.signature.length+80+e.lines.reduce((t,n)=>t+n.text.length+n.depth*2+10,0)}function lf(e,t,n,i,r,o){let s=ae(e,t);if(!s)return null;let a=ie(e,t),c=_s(e,t,n,i),l=o?c?.startLine??n:n,u=o?c?.endLine??i:i,m=(c?.startLine===l&&c.endLine===u?Vi(s.rootNode,l,u):null)??Hr(s.rootNode,l,u);if(!m)return null;let p=new Map,f=new Map,g=new Map,h=(y,E)=>{if(y<l||y>u)return;let w=p.get(y)??new Set;w.add(E),p.set(y,w)};c&&h(c.startLine,"signature");for(let y of r)h(y,"anchor");pi(m,y=>{let E=Qp[y.type];if(E&&h(y.startPosition.row,E),E==="shape"&&GE(f,y,m,l,u),y.type==="call_expression"){let S=(y.childForFieldName("function")??y.namedChild(0))?.text.split(".").at(-1);if(uf(y)){h(y.startPosition.row,"shape");let R=Ds(y.text);R.length<=Vc&&g.set(y.startPosition.row,R)}if(S&&EE.has(S)){h(y.startPosition.row,"lifecycle");let R=Ds(y.text);R.length<=Vc&&g.set(y.startPosition.row,R)}}nl.has(y.type)&&h(y.startPosition.row,"binding")});let b=ee(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 v=[...p.entries()].sort(([y],[E])=>y-E).map(([y,E])=>({line:y,signals:Zp.filter(w=>E.has(w)),text:g.get(y)??Ds(a[y]??"")})).filter(y=>y.text.length>0||y.signals.includes("anchor"));return{...c?{callable:c}:{},rangeStart:l,rangeEnd:u,sourceLines:a,candidates:v,shapes:[...f.values()].sort((y,E)=>y.startLine-E.startLine)}}function GE(e,t,n,i,r){if(t.startPosition.row<i||t.endPosition.row>r)return;let o=t.childForFieldName("key")??t.childForFieldName("name")??t.namedChild(0),s=Ds(o?.text??"");if(!s||s.includes(`
40
- `)||s.length>60)return;let a=KE(t,n);if(a.startPosition.row<i||a.endPosition.row>r)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 KE(e,t){let n=e.parent;for(;n&&n!==t.parent;){if(tf.has(n.type))return n;if(n===t)break;n=n.parent}return e.parent??e}function _s(e,t,n,i){return ee(e,t)?.callables.filter(r=>r.startLine<=n&&r.endLine>=i).sort((r,o)=>r.endLine-r.startLine-(o.endLine-o.startLine)||r.startLine-o.startLine)[0]}function Hr(e,t,n){if(e.startPosition.row>t||e.endPosition.row<n)return null;for(let i of e.namedChildren){let r=Hr(i,t,n);if(r)return r}return e}function pi(e,t){t(e);for(let n of e.namedChildren)pi(n,t)}function Ds(e){return e.trim().replace(/\s+/gu," ")}function uf(e){if(e.type!=="call_expression")return!1;let t=e.childForFieldName("arguments")??e.namedChildren.find(i=>i.type==="arguments"||i.type==="argument_list");if(!t)return!1;let n=!1;return pi(t,i=>{tf.has(i.type)&&(n=!0)}),n}function qE(e){let t={};for(let n of Zp){let i=e.filter(r=>r.signals.includes(n)).length;i>0&&(t[n]=i)}return t}function WE(e,t){let n=new Map;for(let o of e){let s=o.signals.join(",");n.set(s,(n.get(s)??0)+1)}let i=new Set(ef),r=o=>{let s=n.get(o.signals.join(","))??1,a=Math.min(...o.signals.map(u=>t[u]??1)),c=o.signals.some(u=>i.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)=>r(s)-r(o)||s.line-o.line)}var nl=new Set(["lexical_declaration","variable_declarator","const_item","static_item","let_declaration","assignment"]);function VE(e,t,n){let i=[],r=/\b(?:describe|it|test)(?:\.(?:only|skip|todo))?\s*\(\s*(['"`])([^'"`]+)\1/u;for(let o=t;o<=n;o+=1){let s=r.exec(e[o]??"")?.[2];if(!(!s||i.includes(s))&&(i.push(s),i.length>=CE))break}return i}var JE=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 Ji(e,t,n){let i=ae(e,t)?.rootNode??null,r=YE(i,n);if(!r)return null;let o=ie(e,t);if(o.length===0)return null;let s=Math.max(0,r.startPosition.row),a=r.endPosition.column===0?r.endPosition.row-1:r.endPosition.row;return{type:r.type,startLine:s,endLine:Math.min(o.length-1,Math.max(s,a))}}function Ur(e,t,n,i,r){let o=gt(e,t,i,r,[n]),s=o.startLine===o.endLine&&/(?:=>|\(|\{|\[|,)\s*$/u.test(ie(e,t)[o.startLine]??"");if(!s&&(o.startLine>i||o.endLine<r))return o;let a=Ji(e,t,n);return s&&a?{startLine:a.startLine,endLine:a.endLine}:a&&a.startLine>=i&&a.endLine<=r?{startLine:a.startLine,endLine:a.endLine}:{startLine:i,endLine:r}}function YE(e,t){if(!e||!pf(e,t))return null;let n=mf(e,t);for(;n;){if(JE.has(n.type))return n;n=n.parent}return null}function mf(e,t){let n=e.namedChildren.filter(i=>pf(i,t)).sort((i,r)=>df(i)-df(r));return n.length>0?mf(n[0],t):e}function pf(e,t){return e.startPosition.row<=t&&e.endPosition.row>=t}function df(e){return e.endIndex-e.startIndex}var XE=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 Os(e,t,n,i){if(!Number.isSafeInteger(n)||n<0)return null;if(!Number.isSafeInteger(i)||i<0)throw new RangeError(`contextLines must be a non-negative safe integer; received ${i}`);let r=ie(e,t);if(r.length===0||n>=r.length)return null;let o=Math.max(0,n-i),s=Math.min(r.length-1,n+i);return{relativePath:t,startLine:o,endLine:s,focusLine:n,source:r.slice(o,s+1).join(`
41
- `)}}function ff(e,t,n,i,r){let o=Os(e,t,n,i);if(!o)return null;let s=ae(e,t)?.rootNode??null;if(!s)return{...o,kind:"bounded-context"};let a=QE(s,n,r);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(`
42
- `),kind:"complete-call-expression"}}function gf(e,t,n,i,r){if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`maxLines must be a positive safe integer; received ${r}`);let o=ie(e,t);if(o.length===0||n<0||n>=o.length)return null;let s=Math.min(o.length-1,i,n+r-1);return{relativePath:t,startLine:n,endLine:s,focusLine:n,source:o.slice(n,s+1).join(`
43
- `)}}function zn(e,t,n,i,r=6){if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`maxLines must be a positive safe integer; received ${i}`);let o=ie(e,t);if(o.length===0||n<0||n>=o.length)return null;let s=Ji(e,t,n);if(!s){let g=Os(e,t,n,r);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,i),d=n-a-Math.floor(u/2),m=Math.max(0,Math.min(l-u,d)),p=a+m,f=p+u-1;return{relativePath:t,startLine:p,endLine:f,focusLine:n,source:o.slice(p,f+1).join(`
44
- `),unitType:s.type,unitStartLine:a,unitEndLine:c,omittedLines:l-u}}function QE(e,t,n){let i=[];return hf(e,t,n,i),i.filter(r=>!i.some(o=>o!==r&&o.startIndex>=r.startIndex&&o.endIndex<=r.endIndex))}function hf(e,t,n,i){if(ew(e,t)){XE.has(e.type)&&ZE(e)===n&&i.push(e);for(let r of e.namedChildren)hf(r,t,n,i)}}function ZE(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 ew(e,t){return e.startPosition.row<=t&&e.endPosition.row>=t}function bf(e,t,n={}){let{context:i=0}=n,r=Pf(t);if(r)return Df(e,r.filePath,r.startLine,r.endLine,i);let o=If(e,t);if(o)return Rf(e,o);let s=pe(e,t);return s?zr(e,s,i):null}function $V(e,t,n={}){if(t.length===0)throw new RangeError("code requires at least one selector.");if(t.length>24)throw new RangeError(`code accepts at most ${24} selectors per complete packet; received ${t.length}.`);let i=n.context??0,r=n.members??"exported",o=t.map(c=>nw(e,c,i,r)),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:Ls(s.map(c=>c.bindingClosure),a)}}function nw(e,t,n,i){let r=Pf(t);if(r){let u=Df(e,r.filePath,r.startLine,r.endLine,n);return u?iw(e,t,u,n):il(e,t,"definition-source-unreadable")}let o=If(e,t);if(o)return ow(e,t,o,n,i);let s=rt(e,t);if(!s.match)return il(e,t,"definition-not-found");let a=fw(e,s),c=a.map(Lf);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=zr(e,d,n);return m?[m]:[]}):[],definitions:[],candidates:c,omittedCandidates:Math.max(0,s.total-c.length),suggestions:[]}}let l=zr(e,s.match,n);return l?pw(t,l):il(e,t,"definition-source-unreadable")}function iw(e,t,n,i){let r=J(e,n.relativePath).filter(l=>!Sf(l,n.relativePath)),o=rw(e,n,r),s=xf(o.map(l=>zr(e,l,i)).filter(l=>l!==null)).filter(l=>!wf(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(Lf);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 rw(e,t,n){if(!Gr(t.freshness))return[];if(n.length===0)return[];let i=Kc(e,n,{additive:!1,semantic:!1}),r=new Map;for(let s of n){let a=r.get(s.symbol)??[];a.push(s),r.set(s.symbol,a)}let o=new Map;for(let s of n)if(!(s.endLine<t.startLine||s.startLine>t.endLine)){for(let a of i.get(s.symbolId)??[])if(a.file===t.relativePath&&!(a.source==="ast-callsite"&&(a.chunkId<t.startLine||a.chunkId>t.endLine)))for(let c of r.get(a.symbol)??[])o.set(c.symbolId,c)}return Cf(e,[...o.values()],n)}function ow(e,t,n,i,r){let o=n.relativePath,s=aw(e,o),a=Gr(n.freshness)?J(e,o).filter(g=>!Sf(g,o)):[],c=a.filter(g=>Rt(e,g)),l=c.length>0?c:sw(s,a),u=r==="all"?[]:Cf(e,l,a),d=r==="all"||a.length===0?[Rf(e,n)]:xf(u.map(g=>zr(e,g,i)).filter(g=>g!==null)),m=lw(s,d),p=uw(o,s,d),f=dw(s);return{selector:t,status:"matched",kind:"file-source",totalCandidates:1,results:d,definitions:[],candidates:[],omittedCandidates:0,suggestions:[],fileCoverage:{members:r,basis:r==="all"||a.length===0?"complete-file-source":c.length>0?"explicit-exports-and-same-file-reference-closure":"top-level-and-same-file-reference-closure",totalDefinitions:f,returnedDefinitions:m,returnedBodies:d.length,omittedDefinitions:Math.max(0,f-m),omittedLedger:p}}}function sw(e,t){let n=new Set(e.map(i=>i.symbol));return t.filter(i=>n.has(i.symbol))}function aw(e,t){return $p(e,t).flatMap(n=>cw(n,t)?n.children:[n])}function Sf(e,t){return vf(t).has(e.leaf)}function cw(e,t){return vf(t).has(re(e.symbol))}function vf(e){let t=tw(e);return new Set([t,t.slice(0,Math.max(0,t.length-yf(t).length))])}function Cf(e,t,n){if(t.length===0)return[];let i=Kc(e,n,{additive:!0,semantic:!1}),r=new Map;for(let a of n){let c=r.get(a.symbol)??[];c.push(a),r.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 i.get(a.symbolId)??[])for(let l of r.get(c.symbol)??[])o.has(l.symbolId)||s.push(l)}}return[...o.values()].sort(mw)}function xf(e){let t=[...e].sort((i,r)=>i.relativePath.localeCompare(r.relativePath)||i.startLine-r.startLine||r.endLine-i.endLine),n=[];for(let i of t)n.some(r=>wf(r,i))||n.push(i);return n}function Rf(e,t){let n=t.text.split(`
45
- `);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??ol(t.relativePath),source:t.text,freshness:t.freshness,...Gr(t.freshness)?{bindingClosure:qi(e,t.relativePath,0,Math.max(0,n.length-1))}:{}}}function lw(e,t){return Bs(e).filter(n=>t.some(i=>rl(n,i))).length}function uw(e,t,n){let i=[];return Ef(i,e,t,n,0),i}function Ef(e,t,n,i,r){for(let o of n){if(i.some(a=>rl(o,a)))continue;let s=Bs(o.children).filter(a=>!i.some(c=>rl(a,c))).length;e.push({symbol:o.symbol,shortName:o.shortName,relativePath:t,startLine:o.startLine,endLine:o.endLine,signature:o.signature,depth:r,nestedDefinitions:s}),Ef(e,t,o.children,i,r+1)}}function Bs(e){return e.flatMap(t=>[t,...Bs(t.children)])}function dw(e){return Bs(e).length}function rl(e,t){return t.startLine<=e.startLine&&t.endLine>=e.endLine}function wf(e,t){return e.relativePath===t.relativePath&&e.startLine<=t.startLine&&e.endLine>=t.endLine}function mw(e,t){return e.startLine-t.startLine||t.endLine-e.endLine||e.symbol.localeCompare(t.symbol)}function pw(e,t){return{selector:e,status:"matched",kind:"source",totalCandidates:1,results:[t],definitions:[],candidates:[],omittedCandidates:0,suggestions:[]}}function il(e,t,n){return{selector:t,status:"missing",kind:"source",totalCandidates:0,results:[],definitions:[],candidates:[],omittedCandidates:0,suggestions:ms(e,t,5),reason:n}}function If(e,t){try{return xs(e,t)}catch(n){if(n instanceof Nm)return null;throw n}}function fw(e,t){if(!t.match)return[];let n=[t.match];for(let r of t.candidates){let o=J(e,r.relativePath).find(s=>s.symbol===r.symbol&&s.startLine===r.startLine);o&&n.push(o)}let i=new Set;return n.filter(r=>{let o=`${r.relativePath}:${r.startLine}:${r.endLine}:${r.symbol}`;return i.has(o)?!1:(i.add(o),!0)})}function Lf(e){return{symbol:e.symbol,shortName:k(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine}}function Pf(e){let t=e.match(/^(.+):(\d+)-(\d+)$/);if(!t)return null;let n=Number(t[2]),i=Number(t[3]);if(!Number.isSafeInteger(n)||n<1)throw new RangeError(`Source range start line must be a positive integer, got "${t[2]}".`);if(!Number.isSafeInteger(i)||i<n)throw new RangeError(`Source range end line must be an integer at or after ${n}, got "${t[3]}".`);return{filePath:t[1],startLine:n,endLine:i}}function zr(e,t,n){let i=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),r=xs(e,t.relativePath);if(!r)return null;let s=r.text.split(`
46
- `),a=t.endLine<=t.startLine?zn(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(`
47
- `);return{symbol:t.symbol,shortName:k(t.symbol),relativePath:t.relativePath,startLine:u,endLine:d,language:i?.language??ol(t.relativePath),source:m,freshness:r.freshness,...Gr(r.freshness)?{bindingClosure:qi(e,t.relativePath,u,d)}:{}}}function Df(e,t,n,i,r){let o=xs(e,t);if(!o)return null;let s=e.get("SELECT language FROM documents WHERE relative_path = ?",o.relativePath),c=o.text.split(`
48
- `);if(n>c.length)return null;let l=Math.max(0,n-1-r),u=Math.min(c.length-1,i-1+r),d=c.slice(l,u+1).join(`
49
- `);return{symbol:`${o.relativePath}:${n}-${i}`,shortName:`${o.relativePath}:${n}-${i}`,relativePath:o.relativePath,startLine:l,endLine:u,language:s?.language??ol(o.relativePath),source:d,freshness:o.freshness,...Gr(o.freshness)?{bindingClosure:qi(e,o.relativePath,l,u)}:{}}}function Gr(e){return!!(e&&e.semantic.state!=="stale"&&e.semantic.basis!=="no-compiler-document")}function ol(e){switch(yf(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 $s(e){let t=new Map;for(let n of e){let i=t.get(n.relativePath)??[];i.push(n),t.set(n.relativePath,i)}return t}function Tf(e){let t=new Map,n=hw(e),i=new Map;return r=>{let o=gw(r),s=i.get(o);if(s!==void 0)return s;if(!n.has(r.file))return i.set(o,r.symbol),r.symbol;let a=t.get(r.file);a||(a=yw(J(e,r.file)),t.set(r.file,a));let c=bw(a,r);return i.set(o,c),c}}function gw(e){return`${e.file}\0${e.symbol}\0${e.line}`}function hw(e){return new Set(e.all("SELECT relative_path FROM documents").map(t=>t.relative_path))}function yw(e){let t=new Map,n=new Map;for(let i of e){let r=t.get(i.leaf);r?r.push(i):t.set(i.leaf,[i]);let o=n.get(i.startLine);o?o.push(i):n.set(i.startLine,[i])}return{definitions:e,byLeaf:t,byStartLine:n}}function bw(e,t){if(e.definitions.length===0)return t.symbol;let n=Cw(t.symbol),i=Sw(e.byLeaf,n),r=vw(i,t.line);if(r)return r.symbol;let o=e.byStartLine.get(t.line)??[];return o.length===1?o[0].symbol:t.symbol}function Sw(e,t){let n=[],i=new Set;for(let r of t)for(let o of e.get(r)??[])i.has(o.symbolId)||(i.add(o.symbolId),n.push(o));return n}function vw(e,t){let n=null;for(let i of e)if(!(i.startLine>t||i.endLine<t)){if(i.startLine===t)return i;(!n||i.endLine-i.startLine<n.endLine-n.startLine)&&(n=i)}return n}function Cw(e){let t=new Set([e]),i=e.split(/::|\.|#/).filter(Boolean).at(-1);return i&&t.add(i),t}function Mf(e,t){let i=Ce(e,t).map(r=>Rw(t,r));return{usage:i,positions:Ew(e,t,i)}}function Af(e,t){return{importUsage(n){let i=e.importUsageFacts(n);if(!t||i.positions.length===0)return i.usage;let r=t.importDefinitionsForFile(n,i.positions);return r.available?xw(i.usage,r.sourcePaths):i.usage}}}function xw(e,t){return e.map((n,i)=>{let r=t.get(String(i));return r?{...n,sourcePath:r}:n})}function Rw(e,t){let n=t.isTypeOnly===!0,i=t.kind==="side-effect"||n||t.used;return{importer:e,sourcePath:t.sourcePath,importedName:t.importedName,localName:t.localName,kind:t.kind,isTypeOnly:n,isUsed:i,isTypeUsed:n,isValueUsed:t.kind==="side-effect"||!n&&t.used,references:[]}}function Ew(e,t,n){let i=ae(e,t);if(!i)return[];let r=ww(i.rootNode),o=new Map;for(let a of r){let c=o.get(al(a.importedName,a.localName));c?c.push(a.position):o.set(al(a.importedName,a.localName),[a.position])}let s=[];return n.forEach((a,c)=>{let l=o.get(al(a.importedName,a.localName??a.importedName))?.shift();l&&s.push({...l,id:String(c),file:t})}),s}function ww(e){let t=[];for(let n of e.descendantsOfType("use_declaration")){let i=n.namedChildren.find(r=>r.type!=="visibility_modifier");i&&t.push(...js(i,""))}return t.filter(n=>n.importedName!=="*")}function js(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":return[{importedName:e.text,localName:e.text,position:sl(e,e.text)}];case"scoped_identifier":{let n=e.text.split("::").pop()??e.text;return[{importedName:n,localName:n,position:sl(e,n)}]}case"scoped_use_list":{let n=e.namedChild(0),i=e.namedChild(1);if(!n||!i)return[];let r=Ym(t,n.text);return i.namedChildren.flatMap(o=>js(o,r))}case"use_list":return e.namedChildren.flatMap(n=>js(n,t));case"use_as_clause":{let n=e.namedChild(0),i=e.namedChild(1);return!n||!i?[]:js(n,t).map(r=>({...r,localName:i.text}))}case"use_wildcard":{let n=e.namedChild(0),i="*";return[{importedName:i,localName:i,position:sl(n??e,i)}]}default:return[]}}function sl(e,t){let n=Math.max(0,e.text.lastIndexOf(t));return{id:"",file:"",line:e.startPosition.row,column:e.startPosition.column+n+Iw(t)}}function Iw(e){return Math.max(0,Math.min(e.length-1,1))}function al(e,t){return`${e}\0${t}`}import{spawnSync as cl}from"child_process";import{existsSync as ll}from"fs";import{fileURLToPath as Lw}from"url";var ul=15e3,dl=8;function _f(e,t={}){let n=t.status??Pp,i=Tw(e,n),r=Mw(e,n),o=Aw(e,n),s=t.referenceResolver||t.calleeResolver||t.signatureResolver||!Pw(t)?null:Dp(e,n,{fallbackReferenceResolver:i,fallbackCalleeResolver:r,fallbackSignatureResolver:o}),a=t.referenceResolver??s??i,c=t.calleeResolver??s??r,l=t.signatureResolver??s??o,u=t.importUsageResolver??Af(t.sourceImportUsageResolver??Dw(),t.importDefinitionResolver??s),d=t.calleeSymbolResolver,m=t.sourceZeroCalleeOracle,p=t.scipOccurrenceCalleeOracle,f=new Map,g=new Map,h=null,b=null,v=()=>(h??=n(e),h),y=()=>{let C=v();return C.dependencyAvailable?b??C:C},E=C=>{if(C.length===0)return new Map;let L=qr(C);try{let I=a.referencesForDefinitions(L),x=v();return b=Hs(x,I),I.available?new Map(I.references):hs(L,I.references)}catch(I){let x=v();return b=Kr(x,I),fi(L)}},w=C=>{if(C.length===0)return new Map;let L=qr(C),I=L.filter(Ff);if(I.length===0)return gi(L);let x=new Map,D=kf(I,p),_=[];for(let P of I)g.has(P.symbolId)?x.set(P.symbolId,g.get(P.symbolId)??[]):D.has(P.symbolId)?x.set(P.symbolId,D.get(P.symbolId)??[]):Nf(P,m)?x.set(P.symbolId,[]):_.push(P);if(_.length===0)return Yi(L,x,void 0);try{let P=c.calleesForDefinitions(_),T=v();b=Hs(T,P);let F=Yi(_,P.callees,d);for(let[W,ce]of F)x.set(W,ce);return Yi(L,x,void 0)}catch(P){let T=v();return b=Kr(T,P),gi(L)}},S=(C,L)=>{let I=qr(C),x=qr(L),D=x.filter(Ff),_=new Map,P=kf(D,p),T=[];for(let F of D)P.has(F.symbolId)?_.set(F.symbolId,P.get(F.symbolId)??[]):Nf(F,m)?_.set(F.symbolId,[]):T.push(F);if(I.length===0&&T.length===0)return{references:fi(I),callees:Yi(x,_,void 0)};try{let F=s?s.referencesAndCalleesForDefinitions(I,T):_w(a,c,{referenceDefinitions:I,calleeDefinitions:T}),W=v();b=Hs(W,F);let ce=F.available?new Map(F.references):hs(I,F.references);for(let[Y,N]of F.callees)_.set(Y,N);let q=Yi(x,_,d);for(let[Y,N]of q)g.set(Y,N);return{references:ce,callees:q}}catch(F){let W=v();return b=Kr(W,F),{references:fi(I),callees:gi(x)}}},R=C=>{if(C.length===0)return new Map;let L=qr(C);try{let I=l.signaturesForDefinitions(L),x=v();return b=Hs(x,I),Of(L,I.signatures)}catch(I){let x=v();return b=Kr(x,I),Us(L)}};return{language:"rust",availability:y,dispose:()=>{s?.dispose()},importUsage:C=>{let L=f.get(C);if(L)return L;try{let I=u.importUsage(C);return f.set(C,I),I}catch(I){let x=v();return b=Kr(x,I),[]}},referencesFor:C=>E([C]).get(C.symbolId)??[],referencesForDefinitions:E,referencesAndCalleesForDefinitions:S,calleesFor:C=>w([C]).get(C.symbolId)??[],calleesForDefinitions:w,signatureFor:C=>R([C]).get(C.symbolId)??null}}function Hs(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 Kr(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 Pw(e){if(e.usePersistentSession!==void 0)return e.usePersistentSession;let t=process.env.SCIP_RUST_SEMANTIC_SESSION;return t!=="0"&&t!=="false"}function Dw(){return{importUsageFacts:()=>({usage:[],positions:[]})}}function qr(e){return e.map(t=>{let n=t;return{...t,leaf:typeof n.leaf=="string"?n.leaf:re(t.symbol),parentTypeName:n.parentTypeName??null,isFunctionLike:typeof n.isFunctionLike=="boolean"?n.isFunctionLike:ke(t.symbol),isTypeLike:n.isTypeLike??!1,kind:n.kind??null,documentation:n.documentation??null,enclosingSymbol:n.enclosingSymbol??null}})}function Ff(e){return e.isFunctionLike}function Nf(e,t){if(!t)return!1;try{return t(e)}catch{return!1}}function kf(e,t){if(!t||e.length===0)return new Map;try{return t(e)}catch{return new Map}}function Tw(e,t){return{referencesForDefinitions:n=>Fw(e,t,n)}}function Mw(e,t){return{calleesForDefinitions:n=>Nw(e,t,n)}}function Aw(e,t){return{signaturesForDefinitions:n=>kw(e,t,n)}}function Fw(e,t,n){let i=t(e);if(!i.available||!i.resolvedBinary)return{available:!1,resolvedBinary:i.resolvedBinary,reason:fl(i),references:fi(n)};let r=ml();if(!ll(r))return{available:!1,resolvedBinary:i.resolvedBinary,reason:`Rust semantic worker was not found at ${r}. Run npm run build before using built semantic Rust queries.`,references:fi(n)};let o=Xi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,ul),s=zs(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),a=Xi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,dl),c=zs(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),l=bs(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!0}),u={projectRoot:e,rustAnalyzerBinary:i.resolvedBinary,definitions:[...n],requestTimeoutMs:o,...s>0?{referenceRetryTimeoutMs:s}:{},diagnosticsTimeoutMs:c,settleDelayMs:l,concurrency:a},d=cl(process.execPath,[r],{cwd:e,input:JSON.stringify(u),encoding:"utf8",maxBuffer:50*1024*1024,windowsHide:!0,timeout:ys(n.length,Tp(o,u.referenceRetryTimeoutMs),a)}),m=gl(d.stdout);if(m)return{...pl(m),resolvedBinary:i.resolvedBinary,references:hs(n,new Map(m.references),new Set(m.incompleteReferenceSymbolIds??[]))};let p=d.error instanceof Error?d.error.message:d.stderr.trim()||`Rust semantic worker exited with status ${d.status??"unknown"}.`;return{available:!1,resolvedBinary:i.resolvedBinary,reason:p,references:fi(n)}}function Nw(e,t,n){let i=t(e);if(!i.available||!i.resolvedBinary)return{available:!1,resolvedBinary:i.resolvedBinary,reason:fl(i),callees:gi(n)};let r=ml();if(!ll(r))return{available:!1,resolvedBinary:i.resolvedBinary,reason:`Rust semantic worker was not found at ${r}. Run npm run build before using built semantic Rust queries.`,callees:gi(n)};let o=Xi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,ul),s=Xi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,dl),a=zs(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=bs(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!0}),l={projectRoot:e,rustAnalyzerBinary:i.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:c,concurrency:s,includeReferences:!1,includeCallees:!0},u=cl(process.execPath,[r],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,windowsHide:!0,timeout:ys(n.length,o,s)}),d=gl(u.stdout);if(d)return{...pl(d),resolvedBinary:i.resolvedBinary,callees:Yi(n,new Map(d.callees??[]),void 0)};let m=u.error instanceof Error?u.error.message:u.stderr.trim()||`Rust semantic worker exited with status ${u.status??"unknown"}.`;return{available:!1,resolvedBinary:i.resolvedBinary,reason:m,callees:gi(n)}}function kw(e,t,n){let i=t(e);if(!i.available||!i.resolvedBinary)return{available:!1,resolvedBinary:i.resolvedBinary,reason:fl(i),signatures:Us(n)};let r=ml();if(!ll(r))return{available:!1,resolvedBinary:i.resolvedBinary,reason:`Rust semantic worker was not found at ${r}. Run npm run build before using built semantic Rust queries.`,signatures:Us(n)};let o=Xi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,ul),s=Xi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,dl),a=zs(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=bs(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!1,includeSignatures:!0}),l={projectRoot:e,rustAnalyzerBinary:i.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:c,concurrency:s,includeReferences:!1,includeCallees:!1,includeSignatures:!0},u=cl(process.execPath,[r],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,windowsHide:!0,timeout:ys(n.length,o,s)}),d=gl(u.stdout);if(d)return{...pl(d),resolvedBinary:i.resolvedBinary,signatures:Of(n,new Map(d.signatures??[]))};let m=u.error instanceof Error?u.error.message:u.stderr.trim()||`Rust semantic worker exited with status ${u.status??"unknown"}.`;return{available:!1,resolvedBinary:i.resolvedBinary,reason:m,signatures:Us(n)}}function _w(e,t,n){let i=n.referenceDefinitions.length>0?e.referencesForDefinitions(n.referenceDefinitions):{available:!0,references:fi(n.referenceDefinitions)},r=n.calleeDefinitions.length>0?t.calleesForDefinitions(n.calleeDefinitions):{available:!0,callees:gi(n.calleeDefinitions)},o={resolvedBinary:i.resolvedBinary??r.resolvedBinary,references:i.references,callees:r.callees};return i.available&&r.available?{available:!0,...o}:{available:!1,reason:(i.available?void 0:i.reason)??(r.available?void 0:r.reason)??"Rust semantic resolution was unavailable.",...o}}function fi(e){return new Map(e.map(t=>[t.symbolId,[]]))}function gi(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Us(e){return new Map(e.map(t=>[t.symbolId,null]))}function Yi(e,t,n){let i=0,r=0;return $("rust.semantic.callees.complete-map",()=>{let o=new Map;for(let s of e){let a=t.get(s.symbolId)??[];a.length>0&&(i+=1),r+=a.length,o.set(s.symbolId,a.map(c=>({...c,symbol:n?n(c):c.symbol})))}return o},()=>({definitions:e.length,rows:i,callees:r,resolveSymbols:!!n}))}function Of(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function ml(){return Lw(new URL("./rust-semantic-worker.js",import.meta.url))}function pl(e){return e.available?{available:!0}:{available:!1,reason:e.reason}}function fl(e){return e.available?"rust-analyzer binary path is unavailable.":e.reason}function gl(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;if(typeof n.available!="boolean"||!Array.isArray(n.references)||n.available===!1&&typeof n.reason!="string"||n.available===!0&&n.reason!==void 0)return null;let i={references:n.references,incompleteReferenceSymbolIds:Array.isArray(n.incompleteReferenceSymbolIds)?n.incompleteReferenceSymbolIds.filter(r=>typeof r=="number"):void 0,callees:Array.isArray(n.callees)?n.callees:void 0,signatures:Array.isArray(n.signatures)?n.signatures:void 0};return n.available===!0?{available:!0,...i}:{available:!1,reason:String(n.reason),...i}}catch{return null}}function Xi(e,t){return gs(e)??t}function zs(e,t){if(!e)return t;let n=Number(e);return Number.isInteger(n)&&n>=0?n:t}import{existsSync as Ow}from"fs";import{deserializeSCIP as Bw,SymbolRole as $w}from"@c4312/scip";var hl=new WeakMap;function $f(e,t){let n=t.filter(jw);if(n.length===0)return new Map;let i=!1,r=0,o=0;return $("rust.scip-occurrence.callees",()=>{let s=zw(e);if(i=!!s,!s)return new Map;let a=new Map;for(let c of n){let l=Hw(e,s,c);l!==null&&(a.set(c.symbolId,l),r+=1,o+=l.length)}return a},()=>({definitions:t.length,candidates:n.length,indexAvailable:i,resolvedDefinitions:r,resolvedCallees:o}))}function jw(e){return!(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||!e.isFunctionLike||e.leaf==="main"||at(e.symbol))}function Hw(e,t,n){let i=ee(e,n.relativePath);if(!i||i.language!=="rust")return null;let r=i.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(!r)return null;let o=i.callSites.filter(l=>l.line>=r.startLine&&l.line<=r.endLine);if(o.length===0)return null;let s=(t.occurrencesByFile.get(n.relativePath)??[]).filter(l=>l.line>=r.startLine&&l.line<=r.endLine&&l.callee.symbol!==n.symbol);if(s.some(l=>l.traitImplMember)||!Uw(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 Uw(e,t){let n=Bf(e),i=Bf(t);if(n.size!==i.size)return!1;for(let[r,o]of n)if(i.get(r)!==o)return!1;return!0}function Bf(e){let t=new Map;for(let n of e){let i=n.calleeLeaf??n.leaf;if(!i)continue;let r=`${n.line}\0${i}`;t.set(r,(t.get(r)??0)+1)}return t}function zw(e){if(hl.has(e))return hl.get(e)??null;let t=Gw(e);return hl.set(e,t),t}function Gw(e){if(!e.generation.indexPath||!Ow(e.generation.indexPath))return null;try{let t=ze(e).filter(o=>o.symbol.startsWith("rust-analyzer ")&&o.relativePath.endsWith(".rs")&&o.isFunctionLike),n=new Map(t.map(o=>[o.symbol,o])),i=Bw(Yo(e.generation.indexPath,{inputKind:"SCIP occurrence-callee index",maxBytes:Jo})),r=new Map;for(let o of i.documents??[]){let s=o.relativePath;if(!s||!s.endsWith(".rs")||e.isIgnored(s))continue;let a=[];for(let c of o.occurrences??[]){if(!c.symbol||(c.symbolRoles&$w.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:at(l.symbol),callee:{symbol:l.symbol,file:l.relativePath,line:l.startLine,callsiteLine:u}})}r.set(s,a)}return{occurrencesByFile:r}}catch{return null}}var Gs=class{sessions=new WeakMap;getOrCreate(t,n,i){let r=Kw(t,n),o=this.sessions.get(t);o||(o=new Map,this.sessions.set(t,o));let s=o.get(r);if(s)return s.hits+=1,s.lastUsedAtMs=Date.now(),s.provider;let a=Date.now(),c=i();return o.set(r,{key:r,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 i of n.values())i.provider.dispose?.();this.sessions.delete(t)}};function Kw(e,t){return`${e.config.projectRoot}:${t}-workspace`}import{randomUUID as qw}from"crypto";import{existsSync as Ww}from"fs";import{dirname as Vw}from"path";function jf(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}var Jw=12e4,Yw=5;function Gf(e,t,n={}){let i=new yl(e,n),r=null,o=null,s=process.env.CODEBASEIQ_SKIP_WATCH_SERVICE==="1",a=()=>(r??=_p(e,t),r),c=(d,m,p)=>{if(s)return p();try{return m(i.request(d))}catch{return s=!0,p()}},l=(d,m)=>c({kind:"references",definitions:[...d],...m?.exact?{exact:!0}:{}},p=>zf(p),()=>a().referencesForDefinitions?.(d,m)??new Map(d.map(p=>[p.symbolId,a().referencesFor(p)]))),u=d=>c({kind:"callees",definitions:[...d]},m=>zf(m),()=>a().calleesForDefinitions?.(d)??new Map(d.map(m=>[m.symbolId,a().calleesFor(m)])));return{language:"typescript",availability:()=>(o??=c({kind:"availability"},Zw,()=>a().availability()),o),importUsage:d=>c({kind:"import-usage",file:d},m=>m,()=>a().importUsage(d)),referencesFor:d=>Hf(l([d]),d,"reference"),referencesForDefinitions:l,referenceFragmentsForFiles:d=>c({kind:"reference-fragments",files:[...d]},m=>Qw(m),()=>a().referenceFragmentsForFiles?.(d)??new Map),calleesFor:d=>Hf(u([d]),d,"callee"),calleesForDefinitions:u,signatureFor:d=>c({kind:"signature",definition:d},eI,()=>a().signatureFor(d)),dispose:()=>r?.dispose?.()}}function Hf(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 yl=class{constructor(t,n={}){this.db=t;this.runtime=n.runtime??nI,this.timeoutMs=n.timeoutMs??tI(),this.mailboxLimits=n.mailboxLimits??{},this.cacheDir=Vw(t.config.dbPath),this.projectRoot=km(t.config.projectRoot)}db;runtime;timeoutMs;cacheDir;projectRoot;mailboxLimits;request(t){let n=Ep(this.cacheDir),i=Fp(this.cacheDir),r=$c(n.statePath);if(!Uf(r,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript semantic service is not running.");let o=this.db.generation.identity;if(!o)throw new Error("Published TypeScript generation identity is unavailable.");let s=this.runtime.now(),a=s+this.timeoutMs,c=(this.runtime.monotonicNow??Zo)()+this.timeoutMs,l=Fm(),u=Cp("typescript-semantic-v4",{generation:o,profileEnvironment:l,request:t}),d=xp(u),m=Rp(i,{mailboxVersion:vp,operationKey:u,clientId:this.runtime.randomId(),enqueuedAtMs:s,deadlineAtMs:a,protocolVersion:vs,id:d,generation:o,profileEnvironment:l,request:t},{nowMs:s,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??Zo)()<=c;){if(Ww(m.responsePath))return Xw(Lm(m.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript semantic mailbox response"}),d,o,u);let p=$c(n.statePath);if(!Uf(p,this.projectRoot,this.runtime))throw new Error("TypeScript semantic service stopped while processing a request.");this.runtime.sleep(Yw)}throw new Error(`TypeScript semantic service timed out after ${this.timeoutMs}ms.`)}};function Uf(e,t,n){let i=e?.processIdentity?n.readProcessIdentity?.(e.pid):null;return e!==null&&e.projectRoot===t&&e.typescriptSemantic?.protocolVersion===vs&&n.isProcessAlive(e.pid)&&(!e.processIdentity||i!=null&&Xo(e.processIdentity,i))}function Xw(e,t,n,i){let r=JSON.parse(e);if(r.protocolVersion!==vs||r.id!==t||r.operationKey!==i||r.ok===!0&&r.generation!==n)throw new Error("TypeScript semantic service wrote an incompatible response.");if(r.ok===!0)return r.response;throw new Error(typeof r.error=="string"?r.error:"TypeScript semantic service request failed.")}function zf(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid numeric map.");return new Map(e)}function Qw(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid string map.");return new Map(e)}function Zw(e){let t=jf(e);if(!t)throw new Error("TypeScript semantic service wrote invalid availability.");return t}function eI(e){if(e!==null&&typeof e!="string")throw new Error("TypeScript semantic service wrote an invalid signature.");return e}function tI(){let e=Number(process.env.SCIP_TYPESCRIPT_SEMANTIC_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Jw}var nI={now:Date.now,monotonicNow:Zo,randomId:qw,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:ts,readProcessIdentity:Er};var bl=new Gs;$m({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>bl.clear(e)});jm({name:"semantic-provider",close:e=>bl.clear(e)});function hi(e,t){let n=Ke(t)??"typescript";return bl.getOrCreate(e,n,()=>n==="rust"?_f(e.config.projectRoot,{sourceImportUsageResolver:{importUsageFacts:i=>Mf(e,i)},calleeSymbolResolver:Tf(e),sourceZeroCalleeOracle:i=>iI(e,i),scipOccurrenceCalleeOracle:i=>$f(e,i)}):Gf(e,t))}function Ke(e){return e?ye(e)==="rust"?"rust":ls(e)?"typescript":null:"typescript"}function iI(e,t){let n=ee(e,t.relativePath);if(!n||n.language!=="rust")return!1;let i=n.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine&&r.name===t.leaf)??n.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine);return i?!n.callSites.some(r=>r.line>=i.startLine&&r.line<=i.endLine):!1}var rI=/^[A-Za-z_][A-Za-z0-9_]*$/,Kf=/\bDefault::default\b/g,oI=/^\.\.\s*Default::default\b/;function qf(e,t){let n=new Map,i=new Map;for(let r of t){let o=Sl(e,r,i);o!==null&&n.set(r.symbolId,o)}return n}function Sl(e,t,n=new Map){let i=aI(t.symbol);if(!i)return null;let r=ps(e,[t.symbolId]);if(r.length===0)return null;let o=new RegExp(`(^|[^A-Za-z0-9_])${He(i)}::default\\b`,"g"),s=new RegExp(`(^|[^A-Za-z0-9_])${He(i)}\\s*$`),a=sI(e,t.symbolId),c=[];for(let l of r){let u=cI(e,l.relative_path,n);if(u===null)return null;let d=u.split(/\r?\n/),m=0,p=[],f=0;for(let g=l.chunk_start;g<=l.chunk_end&&g<d.length;g+=1){let b=d[g]??"",v=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+i.length+2}),f+=1;for(let E=0;E<b.length;E+=1){let w=oI.exec(b.slice(E));if(w){if(a&&p.includes(m)){let R=E+w[0].lastIndexOf("default");c.push({file:l.relative_path,line:g,column:R}),v.add(R),f+=1}E+=w[0].length-1;continue}let S=b[E];if(S==="{"){let R=s.test(b.slice(0,E));m+=1,R&&p.push(m);continue}if(S==="}")for(m=Math.max(0,m-1);p.length>0&&p[p.length-1]>m;)p.pop()}for(Kf.lastIndex=0;y=Kf.exec(b);){let E=y.index+9;if(!v.has(E))return null}}if(f===0)return null}return wp(c)}function sI(e,t){return e.get("SELECT 1 AS present FROM mentions WHERE symbol_id = ? AND role = 1 LIMIT 1",t)?.present===1}function aI(e){let t=/impl#\[([^\]]+)\]\[Default\]default\(\)\./.exec(e)?.[1]??null;return!t||!rI.test(t)?null:t}function cI(e,t,n){if(n.has(t))return n.get(t)??null;let i=e.get("SELECT text FROM documents WHERE relative_path = ?",t),r=typeof i?.text=="string"?i.text:lI(e,t);return n.set(t,r),r}function lI(e,t){try{return nt(e.config.projectRoot,t,{inputKind:"indexed Rust source file"})}catch(n){if(!Ct(n))throw n;return null}}var Ks=new WeakMap;function Qf(e){Ks.delete(e)}function Zf(e){let t=Ks.get(e);return{incompleteSymbolIds:new Set(t?.incompleteSymbolIds),unavailableSymbolIds:new Set(t?.unavailableSymbolIds)}}function xl(e,t){if(t.incompleteSymbolIds.size===0&&t.unavailableSymbolIds.size===0)return;let n=Ks.get(e)??{incompleteSymbolIds:new Set,unavailableSymbolIds:new Set};for(let i of t.incompleteSymbolIds)n.incompleteSymbolIds.add(i);for(let i of t.unavailableSymbolIds)n.unavailableSymbolIds.add(i);Ks.set(e,n)}var uI="typescript-import-usage-v1",dI="typescript-signatures-v1",vl=Me("semantic-prefetched-callees",{clearGroups:["whole-project","source-file","semantic-provider"]}),Wf=wr({kind:"semantic-import-usage",invalidation:Je("semantic-import-usage"),serialize:e=>JSON.stringify(e),deserialize:lg}),Vf=wr({kind:"semantic-signatures",invalidation:Je("semantic-signatures"),serialize:e=>JSON.stringify(e),deserialize:SI}),Jf=xt({kind:"typescript-import-usage",invalidation:Je("typescript-import-usage"),serialize:e=>JSON.stringify(e),deserialize:lg}),Yf=xt({kind:"typescript-signatures",invalidation:Je("typescript-signatures"),serialize:e=>JSON.stringify(e),deserialize:vI});function _t(e){let t=new Map,n=new Set;return{capability:(i,r)=>ug(e,i,r),importUsage:i=>pI(e,i),references:i=>ng(e,i),materializeReferences:(i,r)=>rg(e,i,t,n,r),callerMap:i=>fI(e,i,t,n),calleeMap:i=>sg(e,i),signature:i=>yI(e,i)}}function mI(e,t){if(t.size===0)return;let n=vl.get(e,()=>new Map);for(let[i,r]of t)n.set(i,[...r])}function eg(e,t){if(!vl.has(e))return{hits:[],misses:[...t]};let n=vl.get(e,()=>new Map),i=[],r=[];for(let o of t)n.has(o.symbolId)?i.push({definition:o,callees:n.get(o.symbolId)??[]}):r.push(o);return{hits:i,misses:r}}function Vr(e,t){return _t(e).importUsage(t)}function pI(e,t){if(Ke(t)==="typescript"){let o="fallback",s=0,a=0,c=0,l=0;return $("typescript.import-usage.materialize",()=>{let u=Pr(e,t,uI);if(u?.key){s=1;let m=Jf.read(e,t,u.key);if(m)return o="hit",a=1,m;c=1;let p=xn(e,t);if(!p)return o="unavailable",[];let f=p.importUsage(t);return Jf.write(e,t,u.key,f),o="computed",f}l=1;let d=xn(e,t);return d?(o="direct-fallback",d.importUsage(t)):(o="unavailable",[])},()=>({state:o,eligible:s,cacheHits:a,cacheMisses:c,fallbacks:l}))}let n=cg(e,"semantic-import-usage",t);if(n){let o=Wf.read(e,t,n);if(o)return o}let i=xn(e,t);if(!i)return[];let r=i.importUsage(t);return n&&Wf.write(e,t,n,r),r}function tg(e,t){return _t(e).references(t)}function ng(e,t){let n=Sl(e,t);if(n)return n;let i=Lp(e,t);if(i)return i;let r=xn(e,t.relativePath);return r?r.referencesFor(t):[]}function ig(e,t){let n=Rn(e,t),i=n.incompleteSymbolIds.size+n.unavailableSymbolIds.size;if(i>0)throw new Error(`Exact semantic caller evidence is incomplete for ${i} definition(s).`);return n.callers}function Rn(e,t,n=i=>hi(e,i)){let i=new Map,r=new Set,o=new Set,s=new Map;for(let c of t){let l=Ke(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}Cl(e,i,c,ng(e,c))}for(let[c,l]of s){let u=_c(e,l,n),d=u?.references??(c.referencesForDefinitions?c.referencesForDefinitions(l,{exact:!0}):new Map(l.map(m=>[m.symbolId,c.referencesFor(m)])));!u&&mt()&&kc(e,l,d,n);for(let m of l){if(!d.has(m.symbolId)){r.add(m.symbolId);continue}Cl(e,i,m,d.get(m.symbolId)??[])}}let a={callers:i,incompleteSymbolIds:r,unavailableSymbolIds:o};return xl(e,a),a}function fI(e,t,n=new Map,i=new Set){let r=new Map,o=rg(e,t,n,i),s=0;return $("semantic.callers.from-references",()=>{for(let a of t)s+=Cl(e,r,a,n.get(a.symbolId)??[])},()=>({definitions:t.length,materialized:o.definitions,inMemoryHits:o.inMemoryHits,incompleteInMemoryHits:o.incompleteInMemoryHits,resultRows:r.size,callerFiles:s})),r}function rg(e,t,n,i,r={}){let o=yn(e),s=[],a=[],c=[],l=0,u=0,d=0,m=0,p=0,f=0,g=0,h=0,b=0,v=0,y=0,E=0,w=[],S=new Map,R=t.filter(L=>Ke(L.relativePath)==="typescript"&&!n.has(L.symbolId)&&!i.has(L.symbolId)),C=_c(e,R,L=>hi(e,L));if(C){b=R.length,v=C.cacheHits,y=C.cacheMisses,E=C.computedFiles;for(let L of R)n.set(L.symbolId,C.references.get(L.symbolId)??[])}if($("semantic.references.cache-scan",()=>{for(let[L,I]of $s(t)){let x=[];for(let P of I)n.has(P.symbolId)?u+=1:i.has(P.symbolId)?h+=1:x.push(P);if(x.length===0){g+=1;continue}let D=gI(e,o,L);if(!D){for(let P of x)Ke(P.relativePath)||(l+=1),c.push(P);continue}f+=1;let _=Um(e,L,D);for(let P of x){let T=_.get(P.symbol)??null;if(T!==null){let F=hI(T);if(F){d+=1,n.set(P.symbolId,F);continue}m+=1}a.push({definition:P,cacheFingerprint:D})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:l,cacheHits:d,parseFailures:m,misses:a.length,unkeyed:c.length,inMemoryHits:u,incompleteInMemoryHits:h,fullyInMemoryFiles:g,cacheReadFiles:f})),a.length>0||c.length>0){w=[...c,...a.map(L=>L.definition)],S=$("semantic.references.compute-misses",()=>{let L=qs(e,w,r);return p=L.size,L},()=>({definitions:w.length,misses:a.length,unkeyed:c.length,rows:p}));for(let L of w)S.has(L.symbolId)?(n.set(L.symbolId,S.get(L.symbolId)??[]),i.delete(L.symbolId)):i.add(L.symbolId);for(let{definition:L,cacheFingerprint:I}of a)S.has(L.symbolId)&&ug(e,"semantic-references",L.relativePath).available&&s.push({relativePath:L.relativePath,symbol:L.symbol,projectFingerprint:I,payload:JSON.stringify(S.get(L.symbolId)??[])})}return s.length>0&&$("semantic.references.cache-write",()=>zm(e,s),()=>({entries:s.length})),S.size>0&&kc(e,w,S,L=>hi(e,L)),{definitions:t.length,inMemoryHits:u,incompleteInMemoryHits:h,cacheHits:d,misses:a.length,unkeyed:c.length,skippedUnsupportedLanguage:l,parseFailures:m,computed:p,incomplete:i.size,cacheWrites:s.length,fragmentDefinitions:b,fragmentCacheHits:v,fragmentCacheMisses:y,fragmentComputedFiles:E}}function gI(e,t,n){if(!t)return null;let i=Ke(n);return i==="typescript"?Ht(JSON.stringify({kind:"semantic-references",language:i,schema:"typescript-references-v2-incomplete-scan",projectFingerprint:t})):i==="rust"?Ht(JSON.stringify({kind:"semantic-references",language:i,engine:ui(e.config.projectRoot),projectFingerprint:t})):null}function qs(e,t,n={}){let i=mt(),r=new Map,o=0,s=0,a=0,c=0,l=0,u=0,d=0,m=0,p=0;return $("semantic.references.provider-loop",()=>{let f=qf(e,t),g=Ip(e,t),h=new Map,b=n.prefetchCallees?new Map:null,v=[];for(let E of t){let w,S=()=>(w??=xn(e,E.relativePath),w);if(b){let I=S();if(I?.referencesAndCalleesForDefinitions){let x=b.get(I);x?x.push(E):b.set(I,[E]),p+=1}}let R=f.get(E.symbolId);if(R){a+=1,c+=R.length,Wr(r,E.symbolId,R,i,I=>{d+=1,m+=I});continue}let C=g.get(E.symbolId);if(C){l+=1,u+=C.length,Wr(r,E.symbolId,C,i,I=>{d+=1,m+=I});continue}let L=S();if(!L){i&&(s+=1);continue}if(i&&(o+=1),L.referencesForDefinitions){let I=h.get(L);I?I.push(E):h.set(L,[E])}else v.push({provider:L,definition:E})}let y=new Set;if(b)for(let[E,w]of b){if(!E.referencesAndCalleesForDefinitions)continue;let S=h.get(E)??[],R=E.referencesAndCalleesForDefinitions(S,w);y.add(E),mI(e,R.callees);for(let C of S){if(!R.references.has(C.symbolId))continue;let L=R.references.get(C.symbolId)??[];Wr(r,C.symbolId,L,i,I=>{d+=1,m+=I})}}for(let[E,w]of h){if(y.has(E))continue;let S=E.referencesForDefinitions(w);for(let R of w){if(!S.has(R.symbolId))continue;let C=S.get(R.symbolId)??[];Wr(r,R.symbolId,C,i,L=>{d+=1,m+=L})}}for(let{provider:E,definition:w}of v){let S=E.referencesFor(w);Wr(r,w.symbolId,S,i,R=>{d+=1,m+=R})}return r},()=>({definitions:t.length,providerHits:o,providerMisses:s,rustDefaultFastPathRows:a,rustDefaultFastPathReferences:c,rustScipOccurrenceFastPathRows:l,rustScipOccurrenceFastPathReferences:u,prefetchCalleeDefinitions:p,definitionsWithReferences:d,referenceCount:m,rows:r.size}))}function Ws(e,t,n={}){let i=qs(e,t,n),r=og(e,t,i);return xl(e,r),{rows:i,...r}}function Wr(e,t,n,i,r){e.set(t,n),i&&n.length>0&&r(n.length)}function Cl(e,t,n,i){let r=0;for(let o of i){if(o.file===n.relativePath||e.isIgnored(o.file))continue;let s=t.get(n.symbolId);s||(s=new Set,t.set(n.symbolId,s));let a=s.size;s.add(o.file),s.size!==a&&(r+=1)}return r}function hI(e){try{return JSON.parse(e)}catch{return null}}function Vs(e,t,n){let i=sg(e,t,n),r=og(e,t,i,n);return xl(e,r),{rows:i,...r}}function og(e,t,n,i){let r=new Set,o=new Set;for(let s of t)if(!(n.has(s.symbolId)||!Ke(s.relativePath)))try{(i?i(s.relativePath):hi(e,s.relativePath)).availability().available?r.add(s.symbolId):o.add(s.symbolId)}catch{o.add(s.symbolId)}return{incompleteSymbolIds:r,unavailableSymbolIds:o}}function sg(e,t,n){let i=mt(),r=new Map,o=0,s=0,a=0,c=0;return $("semantic.callees.provider-loop",()=>{let l=new Map,u=[];for(let d of t){let m=n?n(d.relativePath):xn(e,d.relativePath);if(m&&!m.availability().available){i&&(s+=1);continue}if(!m){i&&(s+=1);continue}i&&(o+=1);let p=d;if(m.calleesForDefinitions){let f=l.get(m);f?f.push(p):l.set(m,[p])}else u.push({provider:m,definition:p})}for(let[d,m]of l){let p=d.calleesForDefinitions(m);for(let f of m){if(!p.has(f.symbolId))continue;let g=p.get(f.symbolId)??[];Xf(r,f.symbolId,g,i,h=>{a+=1,c+=h})}}for(let{provider:d,definition:m}of u){let p=d.calleesFor(m);Xf(r,m.symbolId,p,i,f=>{a+=1,c+=f})}return r},()=>({definitions:t.length,providerHits:o,providerMisses:s,definitionsWithCallees:a,calleeCount:c,rows:r.size}))}function Xf(e,t,n,i,r){e.set(t,n),i&&n.length>0&&r(n.length)}function ag(e,t){return _t(e).signature(t)}function yI(e,t){if(Ke(t.relativePath)==="typescript"){let s="fallback",a=0,c=0,l=0,u=0;return $("typescript.signature.materialize",()=>{let d=Pr(e,t.relativePath,dI);if(d?.key){a=1;let p=Yf.read(e,t.relativePath,d.key)??{};if(Object.prototype.hasOwnProperty.call(p,t.symbol))return s="hit",c=1,p[t.symbol]??null;l=1;let f=xn(e,t.relativePath);if(!f)return s="unavailable",null;let g=f.signatureFor(t);return Yf.write(e,t.relativePath,d.key,{...p,[t.symbol]:g}),s="computed",g}u=1;let m=xn(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=cg(e,"semantic-signatures",t.relativePath),i=bI(t);if(n){let s=Vf.read(e,i,n);if(s)return s.signature}let r=xn(e,t.relativePath);if(!r)return null;let o=r.signatureFor(t);return n&&Vf.write(e,i,n,{signature:o}),o}function cg(e,t,n){let i=yn(e);if(!i)return null;let r=Ke(n);return r!=="rust"?null:Ht(JSON.stringify({kind:t,language:r,engine:ui(e.config.projectRoot),projectFingerprint:i}))}function bI(e){return`${e.relativePath}\0${e.symbol}`}function lg(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:null}catch{return null}}function SI(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 vI(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 ug(e,t,n){let i=Ke(n);if(!i)return{slot:t,language:"typescript",available:!1,reason:"semantic evidence is only available for TypeScript or Rust files"};try{return{slot:t,language:i,...hi(e,n).availability()}}catch(r){return{slot:t,language:i,available:!1,reason:r instanceof Error?r.message:String(r)}}}function xn(e,t){if(!Ke(t))return null;let n=hi(e,t);return n.availability().available?n:null}var fe={references:tg,referenceMap:qs,referenceEvidenceMap:Ws,callerMap:(e,t)=>_t(e).callerMap(t),calleeMap:Rl,calleeEvidenceMap:dg};function Rl(e,t,n={}){return dg(e,t,n).rows}function dg(e,t,n={}){let i=mt(),r=new Map,o=eg(e,t),s=[],a=[],c=0,l=0,u=0,d=0,m=0,p=0,f=0,g=new Set,h=new Set;for(let{definition:S,callees:R}of o.hits)m+=1,r.set(S.symbolId,R),R.length>0&&(p+=1,f+=R.length);let b=CI(e,o.hits);if(b.entries.length>0&&$("semantic.callees.prefetch-cache-write",()=>Fc(e,b.entries),()=>({entries:b.entries.length,sourceMissing:b.sourceMissing,skippedUnsupportedLanguage:b.skippedUnsupportedLanguage})),$("semantic.callees.cache-scan",()=>{for(let[S,R]of $s(o.misses)){if(!Ke(S)){i&&(c+=R.length);continue}let C=se(e,S);if(!C){i&&(l+=R.length),a.push(...R);continue}let L=Ft(e,S,C),I=mg(e,S);if(!I){a.push(...R);continue}let x=Hm(e,S,L,I);for(let D of R){let _=x.get(D.symbol)??null;if(_!==null){let P=RI(_);if(P){i&&(u+=1),r.set(D.symbolId,P);continue}i&&(d+=1)}s.push({def:D,contentHash:L,depsDigest:I})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:c,sourceMissing:l,cacheHits:u,parseFailures:d,misses:s.length,unkeyed:a.length,inMemoryHits:m,inMemoryRows:p,inMemoryCalleeCount:f,resultRows:r.size})),s.length===0&&a.length===0)return{rows:r,incompleteSymbolIds:g,unavailableSymbolIds:h};let v=[...a,...s.map(S=>S.def)],y=0,E=$("semantic.callees.compute-misses",()=>{let S=Vs(e,v,n.resolveProvider);for(let R of S.incompleteSymbolIds)g.add(R);for(let R of S.unavailableSymbolIds)h.add(R);return y=S.rows.size,S.rows},()=>({definitions:v.length,misses:s.length,unkeyed:a.length,rows:y}));for(let[S,R]of E)r.set(S,R);let w=s.filter(S=>E.has(S.def.symbolId)&&_t(e).capability("semantic-callees",S.def.relativePath).available).map(S=>({relativePath:S.def.relativePath,symbol:S.def.symbol,contentHash:S.contentHash,depsDigest:S.depsDigest,payload:JSON.stringify(E.get(S.def.symbolId)??[])}));return w.length>0?$("semantic.callees.cache-write",()=>Fc(e,w),()=>({entries:w.length})):$("semantic.callees.cache-write-skip",()=>{},()=>({reason:"provider-unavailable",misses:s.length})),{rows:r,incompleteSymbolIds:g,unavailableSymbolIds:h}}function CI(e,t){let n=[],i=new Map,r=0,o=0;for(let{definition:s,callees:a}of t){if(!Ke(s.relativePath)){o+=1;continue}if(!i.has(s.relativePath)){let l=se(e,s.relativePath),u=l?mg(e,s.relativePath):null;i.set(s.relativePath,l&&u?{contentHash:Ft(e,s.relativePath,l),depsDigest:u}:null)}let c=i.get(s.relativePath);if(!c){r+=1;continue}n.push({relativePath:s.relativePath,symbol:s.symbol,contentHash:c.contentHash,depsDigest:c.depsDigest,payload:JSON.stringify(a)})}return{entries:n,sourceMissing:r,skippedUnsupportedLanguage:o}}var xI="typescript-callees-v3-incomplete-scan";function mg(e,t){let n=Ke(t);if(n==="typescript")return Pr(e,t,xI)?.key??null;let i=wI(e,t);return n==="rust"?Ht(JSON.stringify({kind:"semantic-callees",language:n,engine:ui(e.config.projectRoot),positionMapping:"nearby-leaf-v2-callsite-line",depsDigest:i})):i}function RI(e){try{return JSON.parse(e)}catch{return null}}var EI=Bi("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function wI(e,t){return EI.get(e,t,()=>{let i=[...Oe(e).get(t)??[]].sort().map(r=>`${r}:${Ft(e,r,se(e,r))}`);return Ht(i.join("|"))})}function C5(e,t,n={}){let i=pe(e,t);if(!i)return[];let o=!ke(i.symbol)&&!e.isIgnored(i.relativePath)?[{relativePath:i.relativePath,line:i.startLine}]:[],s=Hn(e,i,{semantic:n.semantic,semanticEvidence:fe}).map(u=>({relativePath:u.file,line:u.line})),a=II(e,i),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 II(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=LI(t.symbol);if(n.length===0)return[];let i=[];for(let r of he(e,{extensions:[".rb"],includeIgnored:!1})){let o=se(e,r);if(!o)continue;let s=o.split(`
50
- `);for(let a=0;a<s.length;a++){let c=s[a]??"";n.some(l=>new RegExp(`@${l}\\b|\\b${l}:`).test(c))&&i.push({relativePath:r,line:a})}}return i}function LI(e){let n=(e.split(":").pop()??e).replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),i=n.split("_").filter(Boolean),r=new Set;return n&&r.add(n),i.length>=1&&r.add(i[i.length-1]),i.length>=2&&r.add(i.slice(-2).join("_")),[...r]}function Js(e){return e+1}function PI(e,t){return`${Js(e)}-${Js(t)}`}function El(e,t,n){return`${ft(e)}:${PI(t,n)}`}function E5(e,t=180){let n=ft(e).replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var wl={empty(e){console.log(ft(e))},list(e,t){for(let n of e)console.log(ft(t(n)))},groupedByFile(e,t,n=i=>i.relativePath){let i="";for(let r of e){let o=n(r);o!==i&&(i&&console.log(""),console.log(ft(o)),i=o),console.log(ft(t(r)))}},sectionedReport(e){let t=!0;for(let n of e)if(!(n.skipIfEmpty&&n.rows.length===0)){t||console.log(""),t=!1,n.title!==void 0&&console.log(`\u2550\u2550\u2550 ${ft(n.title)} \u2550\u2550\u2550`),n.explanation!==void 0&&console.log(ft(n.explanation));for(let i of n.rows)console.log(ft(i))}},table(e,t,n){console.log(` ${e.map(ft).join(" ")}`);let i=n??e.map(r=>r.length);console.log(` ${i.map(r=>"\u2500".repeat(r)).join(" ")}`);for(let r of t)console.log(ft(r))}};import{availableParallelism as vq}from"os";import{fileURLToPath as Xd}from"url";import{existsSync as Ys,readdirSync as gg}from"fs";import{join as Jr}from"path";var DI={files:new Set,pathPrefixes:[]},TI={reasonsByFile:new Map},Il=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,MI=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,hg=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],AI=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),FI=4,NI=Me("package-surface",{clearGroups:["whole-project"]}),kI=Me("package-operational-surface",{clearGroups:["whole-project"]});function yg(e){return NI.get(e,()=>OI(e.config.projectRoot))}function wn(e,t){let n=yg(e);return n.files.has(t)?!0:n.pathPrefixes.some(i=>t.startsWith(i))}function bg(e,t){return yg(e).files.has(t)}function _I(e){return kI.get(e,()=>BI(e.config.projectRoot))}function Sg(e,t){return _I(e).reasonsByFile.get(t)??[]}function OI(e){let t=new Set,n=[];for(let{manifest:i,packageRoot:r}of vg(e))for(let o of $I(i))Eg(e,r,o,t,n);return t.size===0&&n.length===0?DI:{files:t,pathPrefixes:n}}function BI(e){let t=new Map;for(let{manifest:n,packageRoot:i}of vg(e)){let r=jI(n);for(let s of r)pg(e,i,s,"package binary",t);let o=n.scripts;if(!(!o||typeof o!="object")){for(let[s,a]of Object.entries(o))if(typeof a=="string")for(let c of HI(a))pg(e,i,c,`package script "${s}"`,t)}}return t.size===0?TI:{reasonsByFile:t}}function vg(e){let t=[],n=xg(e,"");return n&&t.push({manifest:n,packageRoot:""}),Cg(e,"",t,0),t}function Cg(e,t,n,i){if(i>=FI)return;let r=Jr(e,t);if(Ys(r))for(let o of gg(r,{withFileTypes:!0})){if(!o.isDirectory()||AI.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=xg(e,s);a&&n.push({manifest:a,packageRoot:s}),Cg(e,s,n,i+1)}}function xg(e,t){let n;try{n=nt(e,Jr(t,"package.json"),{maxBytes:8*1024*1024,inputKind:"package manifest"})}catch(i){if(!Ct(i))throw i;return null}try{let i=JSON.parse(n);return i&&typeof i=="object"?i:null}catch{return null}}function $I(e){let t=[];for(let i of["main","module","types","browser"])typeof e[i]=="string"&&t.push(e[i]);let n=e.bin;if(typeof n=="string")t.push(n);else if(n&&typeof n=="object")for(let i of Object.values(n))typeof i=="string"&&t.push(i);return Rg(e.exports,t),t}function jI(e){let t=e.bin;return typeof t=="string"?[t]:!t||typeof t!="object"?[]:Object.values(t).filter(n=>typeof n=="string")}function HI(e){let t=[],n=/(?:^|&&|\|\||;)\s*(?:(?:cross-env|env)(?:\s+[A-Za-z_][A-Za-z0-9_]*=\S+)*\s+)?(?:node|bun|tsx|ts-node|vite-node|python3?|deno\s+run)\s+(?:(?:--?[A-Za-z0-9-]+(?:=\S+)?)\s+)*["']?([^"'`\s]+\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs|py))["']?/g;for(let i of e.matchAll(n)){let r=i[1];r&&!r.startsWith("node_modules/")&&!r.startsWith("./node_modules/")&&t.push(r)}return t}function pg(e,t,n,i,r){let o=new Set;Eg(e,t,n,o,[]);for(let s of o){let a=r.get(s)??[];a.includes(i)||a.push(i),r.set(s,a)}}function Rg(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))Rg(n,t)}function Eg(e,t,n,i,r){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 fg(c))l!==""&&r.push(En(t,l));return}let a=o.replace(MI,"");for(let c of fg(a)){c===a&&c===o&&i.add(En(t,o));for(let l of hg)UI(e,i,t,c+l)}i.add(En(t,o))}function fg(e){let t=[e];return Il.test(e)&&(t.push(e.replace(Il,"src/")),t.push(e.replace(Il,""))),t}function UI(e,t,n,i){let r=En(n,i);if(t.add(r),!i.startsWith("src/")||Ys(Jr(e,r)))return;let o=hg.find(u=>i.endsWith(u));if(!o)return;let s=i.slice(0,-o.length);zI(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 wg(e,n,c,`${l}${o}`))t.add(u)}function zI(e,t,n,i,r){let o=En(n,`${i}/index${r}`);Ys(Jr(e,o))&&t.add(o)}function wg(e,t,n,i){let r=Jr(e,t,n);if(!Ys(r))return[];let o=[];for(let s of gg(r,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...wg(e,t,a,i)):s.isFile()&&s.name===i&&o.push(En(t,a))}return o}function En(e,t){return e?`${e}/${t}`:t}import{existsSync as Ll,readdirSync as GI}from"fs";import{dirname as KI,join as Pl}from"path";var qI={rootFiles:new Set,sourcePrefixes:[]},WI=new Set([".git",".codebaseiq","node_modules","target"]),VI=6,JI=Me("rust-library-surface",{clearGroups:["whole-project"]});function Ig(e,t,n){if(!n.endsWith(".rs")||!QI(YI(e),n))return!1;let i=J(e,n).find(r=>r.symbol===t);return i?ZI(ie(e,n)[i.startLine]??""):!1}function YI(e){return JI.get(e,()=>XI(e.config.projectRoot))}function XI(e){let t=new Set,n=new Set;for(let i of eL(e)){let r=nt(e,Pl(i,"Cargo.toml"),{maxBytes:8388608,inputKind:"Cargo manifest"}),o=tL(r),s=En(i,"src/lib.rs"),a=o?En(i,o):!nL(r)&&At(e,s)?s:null;if(!a)continue;t.add(a);let c=KI(a).replaceAll("\\","/");n.add(c==="."?"":`${c}/`)}return t.size===0?qI:{rootFiles:t,sourcePrefixes:[...n].sort()}}function QI(e,t){return t.endsWith(".rs")?e.rootFiles.has(t)?!0:iL(t)?!1:e.sourcePrefixes.some(n=>t.startsWith(n)):!1}function ZI(e){return/^\s*pub\s+(?!\()/.test(e)}function eL(e){if(!Ll(e))return[];let t=[];return Lg(e,"",t,0),t}function Lg(e,t,n,i){let r=Pl(e,t);if(Ll(r)&&(Ll(Pl(r,"Cargo.toml"))&&n.push(t),!(i>=VI)))for(let o of GI(r,{withFileTypes:!0})){if(!o.isDirectory()||WI.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name;Lg(e,s,n,i+1)}}function tL(e){let t=!1;for(let n of e.split(`
51
- `)){let i=n.replace(/\s+#.*$/,"").trim(),r=/^\[([^\]]+)\]$/.exec(i);if(r){t=r[1]==="lib";continue}if(!t)continue;let o=/^path\s*=\s*["']([^"']+)["']/.exec(i)?.[1];if(o)return o.replaceAll("\\","/").replace(/^\.\//,"")}return null}function nL(e){let t=!1;for(let n of e.split(`
52
- `)){let i=n.replace(/\s+#.*$/,"").trim(),r=/^\[([^\]]+)\]$/.exec(i);if(r){t=r[1]==="package";continue}if(t&&/^autolib\s*=\s*false\b/.test(i))return!0}return!1}function iL(e){return/(?:^|\/)src\/main\.rs$/.test(e)||/(?:^|\/)src\/bin\//.test(e)||/(?:^|\/)(?:examples|tests|benches)\//.test(e)}function Qi(e){return V(e)==="barrel"}function Dg(e){return rL.get(e,()=>{let n=he(e,{includeIgnored:!1}).filter(s=>{let a=V(s);return a==="entry"||a==="worker"});if(n.length===0)return new Set;let i=Oe(e),r=new Set,o=new Set;for(;n.length>0;){let s=n.shift();if(!r.has(s)){r.add(s),V(s)==="barrel"&&o.add(s);for(let a of i.get(s)??[])r.has(a)||n.push(a)}}return o})}var rL=Me("live-barrels",{clearGroups:["whole-project"]});function Dl(e,t){return Dg(e).has(pt(t))}function Tg(e){let t=Dg(e);return he(e,{includeIgnored:!1}).filter(n=>Qi(n)&&!t.has(n)&&!oL(e,n))}function oL(e,t){let n=pt(t),i=On(e).forFile(n,{facts:!0}).facts?.callables;return i&&i.length>0?!0:(e.get(`SELECT COUNT(*) AS n
53
- FROM defn_enclosing_ranges der
54
- JOIN documents d ON d.id = der.document_id
55
- WHERE d.relative_path = ?
56
- AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function Ye(e,t){let n=pt(t),i=V(t);return i==="entry"||i==="worker"||Tl(n)||Dl(e,n)}function Zi(e,t,n){let i=pt(n),r=[];wn(e,i)&&r.push("package-surface-file"),cL(e,t,i)&&r.push("transitive-package-surface"),Ig(e,t,i)&&r.push("rust-public-library"),bL(t,i)&&r.push("framework-entrypoint");let o=e.config.entryRoots;return o&&(o.files?.some(s=>pt(s)===i)&&r.push("configured-file"),o.pathPrefixes?.some(s=>i.startsWith(pt(s)))&&r.push("configured-path-prefix"),o.qualifiedVars?.some(s=>CL(t,s))&&r.push("configured-qualified-var"),o.symbolPatterns?.some(s=>{try{return Ss(s,"entryRoots.symbolPatterns entry").test(t)}catch{return!1}})&&r.push("configured-symbol-pattern")),r}function Ue(e,t,n){return Zi(e,t,n).length>0}var sL=Me("package-surface-reachability",{clearGroups:["whole-project"]}),aL=Me("explicit-package-surface-reachability",{clearGroups:["whole-project"]});function cL(e,t,n){let i=lL(e).get(n);return i===void 0?!1:i===null||i.has(re(t))}function Mg(e,t,n){let i=uL(e).get(n);return i===void 0?!1:i===null||i.has(re(t))}function lL(e){return sL.get(e,()=>Ag(e,t=>wn(e,t)))}function uL(e){return aL.get(e,()=>Ag(e,t=>bg(e,t)))}function Ag(e,t){let n=new Map,i=[];for(let r of he(e,{includeIgnored:!1}))t(r)&&(n.set(r,null),i.push(r));for(;i.length>0;){let r=i.shift(),o=n.get(r);if(o!==void 0)for(let s of Lr(e,r)){if(!s.sourcePath||e.isIgnored(s.sourcePath))continue;let a=dL(o,s);a!==void 0&&mL(n,s.sourcePath,a)&&i.push(s.sourcePath)}}return n}function dL(e,t){if(e===null)return t.kind==="named"?new Set(t.names):null;if(t.kind==="star")return new Set(e);if(t.kind==="star-as")return t.names.some(i=>e.has(i))?null:void 0;let n=t.names.filter(i=>e.has(i));return n.length>0?new Set(n):void 0}function mL(e,t,n){if(!e.has(t))return e.set(t,n),!0;let i=e.get(t);if(i===void 0)return!1;if(i===null||n===null)return i===null?!1:(e.set(t,null),!0);let r=!1;for(let o of n)i.has(o)||(i.add(o),r=!0);return r}var Fg=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),pL=new Set(["default","generateMetadata","generateStaticParams"]),fL=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),gL=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),hL=new Set(["load","actions","entries",...Fg]),yL=new Set(["default"]);function bL(e,t){let n=re(e);return n===""?!1:Ng(t)?Fg.has(n):kg(t)?pL.has(n):_g(t)?fL.has(n):Og(t)?gL.has(n):Bg(t)?hL.has(n):vL(t)?yL.has(n):!1}function Tl(e){return Ng(e)||kg(e)||_g(e)||SL(e)||Og(e)||Bg(e)}function Ng(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function kg(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function _g(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function SL(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 Og(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Bg(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function vL(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function CL(e,t){let n=t.lastIndexOf("/");if(n<0)return!1;let i=t.slice(0,n),r=t.slice(n+1);return e.includes(Pg(i)+"/")&&e.includes(Pg(r)+".")}function Pg(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function $g(e,t,n={}){let i=new Map;if(t&&t.length===0)return i;let r=he(e,{includeIgnored:!1}),o=Zt(e),s=t??ze(e),a=new Set(s.map(l=>l.symbolId)),c=PL(s);return xL(e,i,r,o,a,c),RL(e,i,s,a),LL(e,i,r,o,a,c),n.semantic!==!1&&n.semanticEvidence&&TL(i,n.semanticEvidence.callerMap(e,DL(s))),i}function xL(e,t,n,i,r,o){for(let s of n){if(!ye(s))continue;let a=Xt(e,s);if(a)for(let c of a){if(o&&!o.has(c.calleeLeaf))continue;let l=Qt(s,i.get(c.calleeLeaf)??[]);if(!l||l.length===0)continue;let u=jn(e,s,l,c.memberAccess,c.calleeQualifier);u&&r.has(u.symbolId)&&u.file!==s&&Ml(t,u.symbolId,s)}}}function RL(e,t,n,i){let r=wL(n);for(let o of EL(e,i))e.isIgnored(o.relative_path)||IL(o,r.get(o.symbol_id))||Ml(t,o.symbol_id,o.relative_path)}function EL(e,t){return ps(e,t?[...t]:void 0)}function wL(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 IL(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function LL(e,t,n,i,r,o){for(let s of n){if(ye(s)!=="rust")continue;let a=ji(e,s,{includeRustAttributeNames:!0});if(a.length!==0)for(let{name:c}of a){if(o&&!o.has(c))continue;let l=i.get(c);if(l)for(let u of l)r.has(u.symbolId)&&u.file!==s&&Ml(t,u.symbolId,s)}}}function Ml(e,t,n){let i=e.get(t);i||(i=new Set,e.set(t,i)),i.add(n)}function PL(e){let t=new Set;for(let n of e){let i="leaf"in n&&typeof n.leaf=="string"?n.leaf:"symbol"in n&&typeof n.symbol=="string"?re(n.symbol):"";i&&t.add(i)}return t.size>0?t:null}function DL(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function TL(e,t){for(let[n,i]of t){let r=e.get(n);r||(r=new Set,e.set(n,r));for(let o of i)r.add(o)}}function Al(e,t,n={}){return $g(e,t,n)}function Yr(e,t,n={}){return fp(e,t,n)}function jg(e,t,n={}){let i=Al(e,t,{semantic:n.semantic,semanticEvidence:n.semanticEvidence});return n.sourceFallback===!1?i:yi(i,Yr(e,t))}function yi(e,t){let n=new Map;for(let[i,r]of e)n.set(i,new Set(r));for(let[i,r]of t){let o=n.get(i)??new Set;for(let s of r)o.add(s);n.set(i,o)}return n}function Hg(e,t,n){let i=t.identifierResolution==="strict"?Bc:pp,r=t.candidateNames?up(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&&Wm(u)))&&!e.isIgnored(u)&&!t.skipPath?.(u))try{if(r&&!dp(se(e,u),r))continue;s+=1;let m=(f,g,h,b)=>{if(t.candidateNames&&!t.candidateNames.has(f))return;a+=1;let v=t.resolveTargets?t.resolveTargets({sourceFile:u,name:f,kind:g,defaultTargets:b}):b();for(let y of v)c+=1,n({sourceFile:u,name:f,target:y,occurrences:h,kind:g})},p=Ki(e,u);for(let[f,g]of p)m(f,"identifier",g.length,()=>i(e,u,f));for(let f of ji(e,u,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let g=f.kind==="cross-language-dispatch"?()=>Bc(e,u,f.name):()=>i(e,u,f.name);m(f.name,f.kind,f.occurrences,g)}}finally{t.afterPath?.(u),o%10===0&&$("source-reference-scan.progress",()=>{},()=>({scannedPaths:o,currentPath:l,candidateMatchedPaths:s,visitedNames:a,visitedHits:c}))}}function de(e){return e.endLine-e.startLine+1}function Ug(e,t={}){let{scope:n,files:i,minLoc:r=1,maxLoc:o=Number.POSITIVE_INFINITY,excludeSymbol:s,excludeEntrySurfaces:a=!1,excludeTypesFiles:c=!1,excludeRootedSymbols:l=!1,requireFunctionLikeSymbol:u=!1,requireCallableSymbol:d=!1,excludeRustTraitImplMembers:m=!1,includeSuppressed:p=!1,sortByLocDesc:f=!1}=t,g=[],h=ML(e,{scope:n,files:i,requireFunctionLikeSymbol:u,requireCallableSymbol:d}),b=new Map,v=new Map,y=w=>{let S=b.get(w);if(S!==void 0)return S;let R=Ye(e,w);return b.set(w,R),R},E=w=>{let S=v.get(w);if(S!==void 0)return S;let R=V(w);return v.set(w,R),R};for(let w of h){let S=w.relativePath;if(e.isIgnored(S)||a&&y(S)||!AL(w,{requireFunctionLikeSymbol:u,requireCallableSymbol:d})||s!==void 0&&w.symbol===s)continue;let R=de(w);R<r||R>o||c&&FL(S)||l&&Ue(e,w.symbol,S)||m&&at(w.symbol)||E(S)!=="test"&&(Ui(w.symbol)||!p&&rs(e,S,w.startLine)||g.push(w))}return f?g.sort((w,S)=>de(S)-de(w)):g}function ML(e,t){return t.files!==void 0?[...new Set(t.files.map(i=>i.replace(/\\/g,"/")))].sort().filter(i=>!t.scope||i.includes(t.scope)).flatMap(i=>J(e,i)):t.requireCallableSymbol?Dr(e,{scope:t.scope,symbolMatches:it,sqlPrefilter:"callable"}):t.requireFunctionLikeSymbol?Dr(e,{scope:t.scope,symbolMatches:ke,sqlPrefilter:"function-like"}):ip(e,t.scope)}function AL(e,t){return t.requireCallableSymbol?it(e.symbol):t.requireFunctionLikeSymbol?ke(e.symbol):e.isFunctionLike}function FL(e){return(e.split("/").pop()??"").includes("types")}var U=class{constructor(t){this.db=t}db;scopedDefinitions(t){return np(this.db,t)}definitionsForFile(t){return J(this.db,t)}productionCallableDefinitions(t={}){return Ug(this.db,t)}calleeMap(t,n={}){return this.calleeEvidenceMap(t,n).rows}calleeEvidenceMap(t,n={}){return Fr(this.db,t,{...n,semanticEvidence:fe})}crossFileCallerMap(t,n={}){return Al(this.db,t,{...n,semanticEvidence:fe})}sourceFallbackCallerFiles(t,n={}){return Yr(this.db,t,n)}callerFileMap(t,n={}){return jg(this.db,t,{...n,semanticEvidence:fe})}frameworkReferencedSymbolIds(t){let n=new Map;for(let r of t){if(!r.leaf)continue;let o=n.get(r.leaf)??[];o.push(r.symbolId),n.set(r.leaf,o)}let i=new Set;for(let r of he(this.db,{includeIgnored:!1}))if(ye(r)==="rust")for(let{name:o}of ji(this.db,r,{includeRustAttributeNames:!0}))for(let s of n.get(o)??[])i.add(s);return i}symbolsWithNonSelfCallees(t,n={}){if(t.length===0)return new Set;let i=new Map(t.map(s=>[s.symbolId,s.symbol])),r=this.calleeEvidenceMap(t,n),o=new Set([...r.rows.entries()].filter(([s,a])=>{let c=i.get(s);return a.some(l=>l.symbol!==c)}).map(([s])=>s));for(let s of r.incompleteSymbolIds)o.add(s);for(let s of r.unavailableSymbolIds)o.add(s);return o}fileDependencyGraph(t){return Oe(this.db,t)}fileKind(t){return V(t)}hasSuppressionComment(t){return rs(this.db,t.relativePath,t.startLine)}sourceFiles(){return $i(this.db)}scanSourceReferences(t,n){Hg(this.db,t,n)}callableSignature(t){let n=On(this.db).forFile(t.relativePath,{facts:!0}).facts?.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};import{statSync as NL}from"fs";function bi(e){let t=e.get("SELECT COUNT(*) as c FROM documents").c,n=e.get("SELECT COUNT(*) as c FROM global_symbols").c,i=e.get("SELECT COUNT(*) as c FROM mentions WHERE role = 1").c,r=e.get("SELECT COUNT(*) as c FROM mentions WHERE role != 1").c;return{documents:t,symbols:n,definitions:i,references:r,...kL(e.generation.databasePath)}}function kL(e){try{let t=NL(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function _L(e,t){return Uc(e).filter(n=>OL({pattern:t,relativePath:n})).map(n=>({relativePath:n}))}function OL(e,t){let n=typeof e=="string"?{pattern:e,relativePath:t}:e;if(typeof n.pattern!="string"||typeof n.relativePath!="string")throw new TypeError("pathMatchesGlob requires pattern and relativePath.");let i=hn(n.pattern),r=hn(n.relativePath);if(!/[*?]/.test(i))return r.includes(i);let o=i.includes("/")?i:`**/${i}`;return Xs(o.split("/"),r.split("/"))}function Xs(e,t){if(e.length===0)return t.length===0;let[n,...i]=e;return n==="**"?Xs(i,t)||t.length>0&&Xs(e,t.slice(1)):t.length===0||!BL(n??"",t[0]??"")?!1:Xs(i,t.slice(1))}function BL(e,t){let n="^";for(let i of e)i==="*"?n+="[^/]*":i==="?"?n+="[^/]":n+=$L(i);return n+="$",new RegExp(n).test(t)}function $L(e){return/[\\^$.*+?()[\]{}|]/.test(e)?`\\${e}`:e}function Gg(e,t,n){let i=[],r=[],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){r.push(s);continue}i.push(s),o.set(a,l+1)}return{selected:i,omitted:r}}function Qs(e,t,n,i,r=!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||r&&s.length===0);if(l.length===0)break;let u=l.filter(m=>m.roles.includes("location")||m.roles.includes("definition")).sort(i);l.sort((m,p)=>zg(p,a)-zg(m,a)||i(m,p));let d=u[0]??l[0];s.push(d),c+=d.evidenceCharacters;for(let m of Kg(d))a.add(m.key);o.splice(o.indexOf(d),1)}return{selected:s,omitted:o.sort(i)}}function zg(e,t){let n=Kg(e).reduce((o,s)=>o+(t.has(s.key)?0:s.weight),0),i=Math.max(0,8-e.priority)*20,r=Math.min(500,Math.ceil(e.evidenceCharacters/160));return n+i-r}function Kg(e){return[...e.reasons.map(jL),...e.roles.map(t=>({key:`role:${t}`,weight:HL(t)})),{key:`file:${e.relativePath}`,weight:180},{key:`scope:${UL(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 jL(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 HL(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 UL(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}var qg=64,Wg=12;function Fl(e,t,n={}){if(t.length===0)throw new Error("The source search pattern must not be empty.");let i=n.context??6;if(!Number.isSafeInteger(i)||i<0)throw new RangeError(`context must be a non-negative safe integer; received ${i}`);let r=n.limit??12;if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`limit must be a positive safe integer; received ${r}`);let o=n.regexp?Ss(t,"source search pattern",n.ignoreCase?"iu":"u"):null,s=n.ignoreCase?t.toLocaleLowerCase():t,a=Rs(e,{scope:n.scope}),c=[],l=[];for(let h of a.files){let b=h.relativePath,v=KL(h.text);if(v.length===0)continue;let y=h.freshness.semantic.state!=="stale"&&h.freshness.semantic.basis!=="no-compiler-document"?J(e,b):[],E=ee(e,b)?.callables??[],w=0;for(let S=0;S<v.length;S+=1){let R=v[S]??"",C=R.endsWith("\r")?R.slice(0,-1):R;if(!(o?o.test(C):(n.ignoreCase?C.toLocaleLowerCase():C).includes(s)))continue;w+=1;let I=Ge(y,S),x=zL(E,S),D=I&&!Le(I.symbol)?I:null,_=D?.startLine??x?.startLine??I?.startLine??S,P=D?.endLine??x?.endLine??I?.endLine??S,T=Ur(e,b,S,_,P);c.push({relativePath:b,focusLine:S,ownerSymbol:D?.symbol??null,ownerShort:D?k(D.symbol):x?.name??(I?k(I.symbol):null),ownerStartLine:T.startLine,ownerEndLine:T.endLine,fileKind:V(b),freshness:h.freshness})}w>0&&l.push({relativePath:b,matchingLines:w,returnedMatches:0,freshness:h.freshness})}c.sort(Jg);let u=c.length>qg?Vg(c,qg):c,d=r===Number.MAX_SAFE_INTEGER?c:n.ranking?Vg(c,r):c.slice(0,r),m=new Map(a.files.map(h=>[h.relativePath,h.text])),p=d.flatMap(h=>{let b=m.get(h.relativePath),v=b===void 0?null:GL(h.relativePath,b,h.focusLine,i);return v?[{...v,...h}]:[]}),f=new Map;for(let h of p)f.set(h.relativePath,(f.get(h.relativePath)??0)+1);for(let h of l)h.returnedMatches=f.get(h.relativePath)??0;let g=qL(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:p,matchingLines:c.length,matchingFiles:l.length,omittedMatches:Math.max(0,c.length-p.length),fileCoverage:l,scopeHints:g.slice(0,Wg),omittedScopeHints:Math.max(0,g.length-Wg),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 zL(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,i)=>n.endLine-n.startLine-(i.endLine-i.startLine)||n.startLine-i.startLine)[0]??null}function GL(e,t,n,i){let r=t.split(`
57
- `),o=t.endsWith(`
58
- `)?r.length-1:r.length;if(n<0||n>=o)return null;let s=Math.max(0,n-i),a=Math.min(o-1,n+i);return{relativePath:e,startLine:s,endLine:a,focusLine:n,source:r.slice(s,a+1).join(`
59
- `)}}function KL(e){if(e.length===0)return[];let t=e.split(`
60
- `);return e.endsWith(`
61
- `)&&t.pop(),t}function qL(e){let t=new Map;for(let n of e){let i=WL(n.relativePath),r=t.get(i)??{matchingLines:0,matchingFiles:0};r.matchingLines+=n.matchingLines,r.matchingFiles+=1,t.set(i,r)}return[...t.entries()].map(([n,i])=>({scope:n,...i})).sort((n,i)=>i.matchingLines-n.matchingLines||i.matchingFiles-n.matchingFiles||n.scope.localeCompare(i.scope))}function WL(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}function Vg(e,t){let n=e.map((r,o)=>({...r,priority:Zs(r.fileKind),sequence:o,evidenceCharacters:1,roles:["search"],reasons:["search"],symbols:r.ownerSymbol?[r.ownerSymbol]:[],behaviorSignals:[]})),i=[];for(let r of[0,1,2]){let o=t-i.length;if(o===0)break;let s=n.filter(a=>Zs(a.fileKind)===r);i.push(...Qs(s,o,Number.MAX_SAFE_INTEGER,Jg).selected)}return i.map(({priority:r,sequence:o,evidenceCharacters:s,roles:a,reasons:c,symbols:l,behaviorSignals:u,...d})=>d)}function Jg(e,t){return Zs(e.fileKind)-Zs(t.fileKind)||+(t.ownerSymbol!==null)-+(e.ownerSymbol!==null)||e.relativePath.localeCompare(t.relativePath)||e.focusLine-t.focusLine}function Zs(e){switch(e){case"entry":case"source":case"worker":return 0;case"barrel":return 1;case"test":return 2}}var Yg=new WeakMap,Xg=new WeakMap,Qg=new WeakMap,Zg=new WeakMap,eh=new WeakMap;function th(e,t){let n=Xg.get(e);n||(n=new Map,Xg.set(e,n));let i=n.get(t);if(i)return i;let r=ae(e,t)?.rootNode;if(!r)return n.set(t,[]),[];let o=new Set;zt(r,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"){J(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=_l([...a]).sort();return n.set(t,c),c}function Kn(e,t,n={}){let r=Xt(e,t)?.filter(p=>!n.ranges||n.ranges.some(f=>p.line>=f.startLine&&p.line<=f.endLine));if(!r)return{targets:[],unresolvedCallsites:0};let o=Ce(e,t).filter(p=>!!p.sourcePath),s=uP(se(e,t)??""),a=ae(e,t)?.rootNode??null,c=a?JL(a):nh(),l=new Map,u=Zt(e),d=[],m=0;for(let p of r){if(!p.memberAccess)continue;let f=Qt(t,u.get(p.calleeLeaf)??[]);if(n.excludeIndexedTargets!==!1&&jn(e,t,f,!0,p.calleeQualifier))continue;let g=p.calleeQualifier,h=cP(e,t,p,o);if(h){d.push(h);continue}let b=VL(e,t,p,o,YL(c,p.calleeQualifier,p.line));if(b.length>0){d.push(...b);continue}let v=XL(e,t,p);if(v.length>0){d.push(...v);continue}let y=g?s.get(g)??g:null,w=(y?_l(o.filter(R=>(R.localName??R.importedName)===y).map(R=>R.sourcePath)):[]).flatMap(R=>{let C=l.get(R);return C||(C=Nt(e,R)??[],l.set(R,C)),C.filter(L=>L.name===p.calleeLeaf).map(L=>({file:R,callable:L}))});if(w.length!==1){m+=1;continue}let S=w[0];d.push({calleeLeaf:p.calleeLeaf,line:p.line,sourceFile:t,targetFile:S.file,targetStartLine:S.callable.startLine,targetEndLine:S.callable.endLine,resolution:"direct-import-receiver",strength:"candidate"})}return{targets:d,unresolvedCallsites:m}}function VL(e,t,n,i,r){let o=n.calleeQualifier;if(!o||!/^[A-Za-z_$][\w$]*$/u.test(o))return[];if(r.size!==1)return[];let s=[...r][0],a=_l(i.filter(u=>u.localName===s||u.importedName===s).map(u=>u.sourcePath));if(a.length!==1)return[];let c=a[0],l=tP(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 nh(){return{declarations:new Map,callbacks:[]}}function JL(e){let t=nh();return zt(e,n=>{if(n.type==="variable_declarator"){let c=n.childForFieldName("name")??n.namedChild(0),l=n.childForFieldName("value")??n.namedChild(1);if(c?.type!=="identifier"||!l)return;let u=new Set;if(zt(l,d=>{if(d.type!=="member_expression")return;let m=d.childForFieldName("object")??d.namedChild(0),p=d.childForFieldName("property")??d.namedChild(1);m?.type==="identifier"&&p?.text==="Service"&&u.add(m.text)}),u.size===1){let d=t.declarations.get(c.text)??[];d.push({line:n.startPosition.row,alias:[...u][0]}),t.declarations.set(c.text,d)}return}if(!["arrow_function","function_expression","generator_function"].includes(n.type))return;let i=n.childForFieldName("parameters")??n.childForFieldName("parameter");if(!i)return;let r=n.parent;for(;r&&r.type!=="call_expression";)r=r.parent;if(!r)return;let o=r.childForFieldName("function")??r.namedChild(0),s=/^([A-Za-z_$][\w$]*)\.Service\.use$/u.exec(o?.text??"");if(!s)return;let a=new Set;zt(i,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 YL(e,t,n){if(!t||!/^[A-Za-z_$][\w$]*$/u.test(t))return new Set;let i=new Set((e.declarations.get(t)??[]).filter(r=>r.line<=n).map(r=>r.alias));for(let r of e.callbacks)r.startLine<=n&&r.endLine>=n&&r.receivers.has(t)&&i.add(r.alias);return i}function XL(e,t,n){let i=n.calleeQualifier;if(!i||!/^[A-Za-z_$][\w$]*$/u.test(i))return[];let r=ae(e,t)?.rootNode;if(!r)return[];let o=QL(e,t,r,n.line,n.calleeLeaf,i),s=o?eP(o,i):null;if(!s)return[];if(!ZL(s))return[];let a=(Nt(e,t)??[]).filter(p=>p.startLine<=s.startPosition.row&&p.endLine>=s.endPosition.row).sort((p,f)=>p.endLine-p.startLine-(f.endLine-f.startLine))[0];if(!a)return[];let c=J(e,t).filter(p=>p.isFunctionLike&&p.leaf===a.name);if(c.length!==1)return[];let l=c[0],u=Zg.get(e);u||(u=new Map,Zg.set(e,u));let d=`${l.symbol}\0${n.calleeLeaf}`,m=u.get(d);if(!m){let p=[];for(let f of Tr(e,l)){let g=ae(e,f.file)?.rootNode;if(!g)continue;let h=g.descendantsOfType("call_expression").filter(y=>y.startPosition.row>f.line||y.endPosition.row<f.line?!1:(y.childForFieldName("function")??y.namedChild(0))?.text.replace(/\s+/gu,"").replace(/<[^<>]*>$/u,"").match(/[A-Za-z_$][\w$]*$/u)?.[0]===l.leaf);if(h.length!==1)continue;let v=h[0].childForFieldName("arguments")?.namedChildren.find(y=>Si(y).type==="object");if(v)for(let y of Si(v).namedChildren){if(y.type==="shorthand_property_identifier"&&y.text===n.calleeLeaf){p.push(...ea(e,f.file,n.calleeLeaf,y,y));continue}if(y.type!=="pair")continue;let E=y.childForFieldName("key")??y.namedChild(0),w=y.childForFieldName("value")??y.namedChild(1);ta(E?.text)!==n.calleeLeaf||!w||p.push(...ea(e,f.file,n.calleeLeaf,w,y))}}m=p.filter((f,g,h)=>h.findIndex(b=>b.file===f.file&&b.startLine===f.startLine&&b.endLine===f.endLine&&b.name===f.name)===g),u.set(d,m)}return m.map(p=>({calleeLeaf:p.name,line:n.line,sourceFile:t,targetFile:p.file,targetStartLine:p.startLine,targetEndLine:p.endLine,resolutionAlternativeCount:m.length,resolution:"factory-callback-member",strength:m.length===1?"exact":"candidate"}))}function QL(e,t,n,i,r,o){let s=Qg.get(e);s||(s=new Map,Qg.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]}`,p=a.get(m);(!p||c.endIndex-c.startIndex<p.endIndex-p.startIndex)&&a.set(m,c)}}s.set(t,a)}return a.get(`${i}\0${o}\0${r}`)??null}function ZL(e){return e.descendantsOfType("return_statement").some(t=>{let n=t.childForFieldName("argument")??t.namedChild(0);return!!(n&&Si(n).type==="object")})}function eP(e,t){let n=e.parent;for(;n;){if(/(?:function|method|lambda)/u.test(n.type)||n.type==="arrow_function"){let i=n.childForFieldName("parameters")??n.childForFieldName("parameter"),r=!1;if(i&&zt(i,o=>{o.type==="identifier"&&o.text===t&&(r=!0)}),r)return n}n=n.parent}return null}function ea(e,t,n,i,r){if(i.type==="identifier")return(Nt(e,t)??[]).filter(c=>c.name===i.text).map(c=>({...c,file:t}));let o=Nl(e,t,i.text);if(o.length>0)return o;if(!kl(i))return[];let a=(Nt(e,t)??[]).filter(c=>c.startLine>=r.startPosition.row&&c.endLine<=r.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:r.startPosition.row,endLine:r.endPosition.row}]}function tP(e,t,n){let i=eh.get(e);i||(i=new Map,eh.set(e,i));let r=`${t}\0${n}`,o=i.get(r);if(o)return o;let s=rP(e,t).flatMap(a=>nP(e,a,t,n));return i.set(r,s),s}function nP(e,t,n,i){let r=ae(e,t)?.rootNode,o=Nt(e,t)??[];if(!r)return[];let s=oP(e,t,n);if(s.size===0)return[];let a=new Set,c=[],l=[],u=[];return zt(r,m=>{if(iP(m,s)){if(m.type==="pair"){let p=m.childForFieldName("key")??m.namedChild(0),f=m.childForFieldName("value")??m.namedChild(1);if(ta(p?.text)!==i||!f)return;if(f.type==="identifier")a.add(f.text);else if(kl(f))c.push({name:i,startLine:m.startPosition.row,endLine:m.endPosition.row});else{let g=sP(e,t,f.text),h=Nl(e,t,f.text);if(g.length>0)u.push(...g);else if(h.length>0)u.push(...h);else{let b=aP(m);b&&l.push(b)}}return}m.type==="shorthand_property_identifier"&&m.text===i&&a.add(i)}}),[...o.filter(m=>a.has(m.name)).map(m=>({...m,file:t})),...c.map(m=>({...m,file:t})),...l.map(m=>({...m,file:t})),...u].filter((m,p,f)=>f.findIndex(g=>g.file===m.file&&g.name===m.name&&g.startLine===m.startLine&&g.endLine===m.endLine)===p)}function iP(e,t){let n=e,i=null;for(;n;){if(n.type==="object"&&(i=n),n.type==="call_expression"){if(!i)return!1;let r=n.childForFieldName("function")??n.namedChild(0);return r?t.has(r.text.replace(/\.of$/u,""))&&r.text.endsWith(".of"):!1}n=n.parent}return!1}function rP(e,t){let n=Yg.get(e);n||(n=new Map,Yg.set(e,n));let i=n.get(t);if(i)return i;let r=new Set([t]),o=J(e,t).filter(a=>a.leaf==="Service"&&a.isTypeLike);for(let a of o)for(let c of Tr(e,a))r.add(c.file);let s=[...r].sort();return n.set(t,s),s}function oP(e,t,n){let i=new Set;Mt(t,n)&&i.add("Service");for(let r of Ce(e,t)){if(!r.sourcePath||!Mt(r.sourcePath,n))continue;if(r.kind==="namespace"&&r.localName){i.add(`${r.localName}.Service`);continue}(r.importedName==="default"?r.localName:r.importedName)==="Service"?i.add(r.localName??r.importedName):r.localName&&r.importedName!=="default"&&i.add(`${r.localName}.Service`)}return i}function Nl(e,t,n){let i=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(n.replace(/\s+/gu,""));if(!i)return[];let r=ae(e,t)?.rootNode;if(!r)return[];let o=ih(r,i[1]),s=o?rh(o):null;if(!s)return[];let a=s.childForFieldName("function")??s.namedChild(0),c=a?oh(e,t,a.text):[];if(c.length!==1)return[];let l=c[0],u=ae(e,l.relativePath)?.rootNode;if(!u)return[];let d=sh(u,l.startLine,l.endLine);if(!d)return[];let m=[];for(let p of d.descendantsOfType("return_statement")){let f=p.childForFieldName("argument")??p.namedChild(0);if(!f)continue;let g=Si(f);if(g.type==="object")for(let h of g.namedChildren){if(h.type==="shorthand_property_identifier"&&h.text===i[2]){for(let y of Nt(e,l.relativePath)??[])y.name===i[2]&&m.push({...y,file:l.relativePath});continue}if(h.type!=="pair")continue;let b=h.childForFieldName("key")??h.namedChild(0),v=h.childForFieldName("value")??h.namedChild(1);if(!(ta(b?.text)!==i[2]||!v))if(v.type==="identifier")for(let y of Nt(e,l.relativePath)??[])y.name===v.text&&m.push({...y,file:l.relativePath});else kl(v)&&m.push({name:i[2],startLine:h.startPosition.row,endLine:h.endPosition.row,file:l.relativePath})}}return m.filter((p,f,g)=>g.findIndex(h=>h.file===p.file&&h.name===p.name&&h.startLine===p.startLine&&h.endLine===p.endLine)===f)}function sP(e,t,n){let i=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(n.replace(/\s+/gu,""));if(!i)return[];let r=ae(e,t)?.rootNode;if(!r)return[];let o=ih(r,i[1]),s=o?rh(o):null,a=s?.childForFieldName("function")??s?.namedChild(0),c=a?oh(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=sh(u,l.startLine,l.endLine);if(!d)return[];let m=new Set,p=d.childForFieldName("parameters")??d.childForFieldName("parameter");if(p&&zt(p,R=>{R.type==="identifier"&&m.add(R.text)}),m.size===0)return[];let f=Nl(e,t,n);if(f.length===0)return[];let g=(Nt(e,l.relativePath)??[]).filter(R=>R.startLine>=l.startLine&&R.endLine<=l.endLine),h=(Xt(e,l.relativePath)??[]).filter(R=>R.line>=l.startLine&&R.line<=l.endLine),b=new Set,v=f.map(R=>({name:R.name,startLine:R.startLine,endLine:R.endLine})),y=new Set;for(;v.length>0&&y.size<32;){let R=v.shift(),C=`${R.name}\0${R.startLine}\0${R.endLine}`;if(!y.has(C)){y.add(C);for(let L of h.filter(I=>I.line>=R.startLine&&I.line<=R.endLine)){if(L.memberAccess&&L.calleeQualifier&&m.has(L.calleeQualifier)){b.add(L.calleeLeaf);continue}if(L.memberAccess)continue;let I=g.filter(x=>x.name===L.calleeLeaf);I.length===1&&v.push(I[0])}}}if(b.size===0)return[];let w=s.childForFieldName("arguments")?.namedChildren.find(R=>Si(R).type==="object");if(!w)return[];let S=[];for(let R of Si(w).namedChildren){if(R.type==="shorthand_property_identifier"&&b.has(R.text)){S.push(...ea(e,t,R.text,R,R));continue}if(R.type!=="pair")continue;let C=R.childForFieldName("key")??R.namedChild(0),L=R.childForFieldName("value")??R.namedChild(1),I=ta(C?.text);!I||!b.has(I)||!L||S.push(...ea(e,t,I,L,R))}return S.filter((R,C,L)=>L.findIndex(I=>I.file===R.file&&I.name===R.name&&I.startLine===R.startLine&&I.endLine===R.endLine)===C)}function ih(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 rh(e){return e.type==="call_expression"?e:e.descendantsOfType("call_expression")[0]??null}function oh(e,t,n){let i=n.replace(/\s+/gu,"").replace(/<[^<>]*>$/u,""),r=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(i);if(r){let d=Ce(e,t).filter(f=>f.localName===r[1]&&f.sourcePath);if(d.length!==1||!d[0].sourcePath)return[];let m=d[0].sourcePath,p=$n(e,m,r[2]).filter(f=>f.isFunctionLike);return p.length>0?p:(Nt(e,m)??[]).filter(f=>f.name===r[2]).map(f=>({...f,relativePath:m}))}if(!/^[A-Za-z_$][\w$]*$/u.test(i))return[];let o=J(e,t).filter(d=>d.leaf===i&&d.isFunctionLike);if(o.length>0)return o;let s=(Nt(e,t)??[]).filter(d=>d.name===i).map(d=>({...d,relativePath:t}));if(s.length>0)return s;let a=Ce(e,t).filter(d=>d.localName===i&&d.sourcePath&&d.kind!=="namespace");if(a.length!==1||!a[0].sourcePath)return[];let c=a[0].sourcePath,l=a[0].importedName==="default"?i:a[0].importedName,u=$n(e,c,l).filter(d=>d.isFunctionLike);return u.length>0?u:(Nt(e,c)??[]).filter(d=>d.name===l).map(d=>({...d,relativePath:c}))}function sh(e,t,n){let i=null;return zt(e,r=>{!/(?:function|method|lambda)/u.test(r.type)&&r.type!=="arrow_function"||r.startPosition.row>t||r.endPosition.row<n||(!i||r.endIndex-r.startIndex<i.endIndex-i.startIndex)&&(i=r)}),i}function kl(e){return["arrow_function","function_expression","generator_function"].includes(e.type)||e.descendantsOfType(["arrow_function","function_expression","generator_function"]).length>0}function aP(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 ta(e){return e?e.replace(/^(?:['"])(.*)(?:['"])$/u,"$1"):null}function cP(e,t,n,i){let r=/^this\.([A-Za-z_$][\w$]*)$/u.exec(n.calleeQualifier??"");if(!r)return null;let o=ae(e,t)?.rootNode;if(!o)return null;let s=lP(o,n.line);if(!s)return null;let a=new Set;if(zt(s,g=>{if(g.type!=="assignment_expression")return;let h=g.childForFieldName("left")??g.namedChild(0),b=g.childForFieldName("right")??g.namedChild(g.namedChildCount-1);if(h?.text.replace(/\s+/gu,"")!==`this.${r[1]}`||!b)return;let v=Si(b);if(v.type!=="new_expression")return;let E=(v.childForFieldName("constructor")??v.namedChild(0))?.text.match(/[A-Za-z_$][\w$]*$/u)?.[0];E&&a.add(E)}),a.size!==1)return null;let c=[...a][0],l=i.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"?$n(e,l[0].sourcePath,c):[],m=d.length===1?d[0].leaf:u,p=J(e,l[0].sourcePath).filter(g=>g.isFunctionLike&&g.leaf===n.calleeLeaf&&Qm(g.symbol)===m);if(p.length!==1)return null;let f=p[0];return{calleeLeaf:n.calleeLeaf,line:n.line,sourceFile:t,targetFile:f.relativePath,targetStartLine:f.startLine,targetEndLine:f.endLine,targetSymbol:f.symbol,resolution:"constructed-member-receiver",strength:"exact"}}function lP(e,t){let n=[];return zt(e,i=>{["class","class_declaration","class_definition"].includes(i.type)&&i.startPosition.row<=t&&i.endPosition.row>=t&&n.push(i)}),n.sort((i,r)=>i.endPosition.row-i.startPosition.row-(r.endPosition.row-r.startPosition.row))[0]??null}function Si(e){let t=e;for(;["parenthesized_expression","as_expression","type_assertion","satisfies_expression"].includes(t.type)&&t.namedChildCount===1;)t=t.namedChild(0);return t}function zt(e,t){t(e);for(let n of e.namedChildren)zt(n,t)}function uP(e){let t=new Map,n=/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*([A-Za-z_$][\w$]*)\s*;/gu;for(let i of e.matchAll(n)){let r=i[1],o=i[2];r&&o&&t.set(r,o)}return t}function _l(e){let t=[];for(let n of e)t.some(i=>Mt(i,n))||t.push(n);return t}import{existsSync as mP}from"fs";import{SymbolRole as pP}from"@c4312/scip";import{deserializeSCIP as dP}from"@c4312/scip";function ah(e,t){return dP(Yo(e,{inputKind:t,maxBytes:Jo}))}var Ol=new WeakMap;function In(e,t,n,i){let r=ee(e,t),o=(r?.callSites??[]).filter(p=>p.line>=n&&p.line<=i);if(!r||o.length===0)return{available:!!r,targets:[],resolvedCallsites:0,unresolvedCallsites:0};let s=$l(e);if(!s)return{available:!1,targets:[],resolvedCallsites:0,unresolvedCallsites:o.length};let a=(s.byFile.get(t)??[]).filter(p=>p.sourceLine>=n&&p.sourceLine<=i).map(p=>({...p,calleeLeaf:p.definition.leaf})),c=ch(o.map(p=>({line:p.line,leaf:p.calleeLeaf}))),l=ch(a.map(p=>({line:p.sourceLine,leaf:p.calleeLeaf}))),u=new Set([...c].flatMap(([p,f])=>l.get(p)===f?[p]:[])),d=a.filter(p=>u.has(uh(p.sourceLine,p.calleeLeaf))),m=[...u].reduce((p,f)=>p+(c.get(f)??0),0);return{available:!0,targets:d,resolvedCallsites:m,unresolvedCallsites:Math.max(0,o.length-m)}}function Bl(e,t,n,i){let r=$l(e);return r?{available:!0,targets:(r.byFile.get(t)??[]).filter(o=>o.sourceLine>=n&&o.sourceLine<=i)}:{available:!1,targets:[]}}function lh(e,t,n,i){let r=$l(e);return r?{available:!0,targets:(r.byFile.get(t)??[]).filter(o=>o.sourceLine>=n&&o.sourceLine<=i&&na(e,o.definition)).map(o=>({...o,calleeLeaf:o.definition.leaf}))}:{available:!1,targets:[]}}function $l(e){if(Ol.has(e))return Ol.get(e)??null;let t=fP(e);return Ol.set(e,t),t}function fP(e){if(!e.generation.indexPath||!mP(e.generation.indexPath))return null;try{let t=ze(e),n=new Map(t.map(o=>[o.symbol,o])),i=ah(e.generation.indexPath,"SCIP source-range call-target index"),r=new Map;for(let o of i.documents??[]){let s=o.relativePath;if(!s||e.isIgnored(s))continue;let a=[];for(let c of o.occurrences??[]){if(!c.symbol||(c.symbolRoles&pP.Definition)!==0)continue;let l=n.get(c.symbol),u=c.range?.[0];!l||!Number.isInteger(u)||a.push({sourceLine:u,definition:l})}r.set(s,a)}return{byFile:r}}catch{return null}}function na(e,t){if(!t.isFunctionLike)return!1;let n=ee(e,t.relativePath);return!n||n.callables.some(i=>i.name===t.leaf&&i.startLine===t.startLine&&i.endLine===t.endLine)?!0:gP(t)}function gP(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 ch(e){let t=new Map;for(let n of e){let i=uh(n.line,n.leaf);t.set(i,(t.get(i)??0)+1)}return t}function uh(e,t){return`${e}\0${t}`}var hP=16,yP=4,jl=3e3,bP=800,SP=new Set(["assignment","const_declaration","const_item","field_declaration","lexical_declaration","local_declaration_statement","local_variable_declaration","static_item","variable_declaration"]);function hh(e,t,n={}){let i=n.maxSteps??hP;if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`maxSteps must be a positive safe integer; received ${i}`);let r=new Map(t.nodes.map(M=>[M.id,M])),o=IP(n.focusLocations??[]),s=new Set,a=new Map(t.edges.map(M=>[M.id,M])),c=Ln(t.paths.flatMap(M=>M.nodeIds)),l=Ln(t.anchors.filter(M=>M.status==="matched").flatMap(M=>M.nodeIds)),u=t.nodes.filter(M=>M.disposition==="emitted"&&M.attributes.upstreamCausalPath===!0).sort((M,Q)=>Number(Q.attributes.upstreamCausalDistance??0)-Number(M.attributes.upstreamCausalDistance??0)||M.id.localeCompare(Q.id)).map(M=>M.id),d=new Set(u),m=Math.max(0,i-l.length),f=vP(t,l,o,m).slice(0,m),g=new Set(f),h=new Set(f),b=new Set([...c,...u,...l]),v=t.edges.filter(M=>M.disposition==="emitted"&&M.kind!=="structural-membership"),y=t.edges.filter(M=>M.disposition!=="excluded"&&M.disposition!=="unsupported"&&M.kind!=="structural-membership"),E=new Set([...t.paths.flatMap(M=>M.edgeIds),...v.filter(M=>d.has(M.fromNodeId)&&d.has(M.toNodeId)).map(M=>M.id)]),w=t.paths.some(M=>M.edgeIds.length>0),S=new Set(l);for(let M of f)S.add(M);for(let M of t.paths){let Q=M.nodeIds[0],X=a.get(M.edgeIds[0]??""),Se=M.nodeIds[1];Q&&Se&&X?.fromNodeId===Q&&X.toNodeId===Se&&S.add(Q)}if(t.paths.every(M=>M.nodeIds.length===0))for(let M of t.anchors)for(let Q of M.nodeIds)S.add(Q);let R=MP(l,y,r,yP),C=Ln(v.filter(M=>M.kind==="call"&&l.includes(M.fromNodeId)).map(M=>M.toNodeId)),L=new Set(Ln([...R,...w?[]:C]));for(let M of L)S.add(M);let I=Ln(v.flatMap(M=>b.has(M.fromNodeId)||b.has(M.toNodeId)?[M.fromNodeId,M.toNodeId]:[])),x=t.nodes.filter(M=>M.disposition==="emitted"&&M.kind!=="structural-region"&&v.some(Q=>Q.fromNodeId===M.id||Q.toNodeId===M.id)).map(M=>M.id),D=Ln([...u,...c,...l,...f,...L,...I,...x]).filter(M=>r.has(M)),_=[];for(let M of D)w&&!b.has(M)&&!g.has(M)&&!L.has(M)||_.length>=i&&!b.has(M)||_.push(M);let P=new Set(_),T=new Map(_.map(M=>[M,FP(M)])),F=new Set([...c,...u]),W=new Set(t.anchors.flatMap(M=>M.nodeIds)),ce=_.map((M,Q)=>{let X=r.get(M),Se=wP(X,o);for(let tt of Se)s.add(er(X.location.file,tt));return{id:T.get(M),nodeId:M,order:Q,role:W.has(M)?"anchor":F.has(M)?"connector":"junction",kind:X.kind,label:X.label,location:X.location,behavior:CP(e,X,W.has(M),[...new Set([...Se,...EP(e,X,y,r,E,S)])],Se,S.has(X.id)&&(Se.length===0||W.has(X.id)),L.has(X.id),h.has(X.id)&&Se.length===0)}}),q=new Map;for(let M of t.paths)for(let Q=0;Q<M.edgeIds.length;Q+=1){let X=a.get(M.edgeIds[Q]),Se=M.nodeIds[Q],tt=M.nodeIds[Q+1];!X||!Se||!tt||q.set(X.id,X.fromNodeId===Se&&X.toNodeId===tt?"forward":"reverse")}let N=y.filter(M=>P.has(M.fromNodeId)&&P.has(M.toNodeId)).sort((M,Q)=>AP(M,Q,t)).map((M,Q)=>({id:NP(M.id),edgeId:M.id,order:Q,kind:M.kind,fromStepId:T.get(M.fromNodeId),toStepId:T.get(M.toNodeId),directed:!0,pathTraversal:q.get(M.id)??"adjacent",evidence:M.evidence})),K=new Map(N.map(M=>[M.edgeId,M.id])),te=t.paths.map(M=>({id:M.id,status:M.status,stepIds:M.nodeIds.flatMap(Q=>{let X=T.get(Q);return X?[X]:[]}),transitionIds:M.edgeIds.flatMap(Q=>{let X=K.get(Q);return X?[X]:[]})})),me=ce.flatMap(M=>M.location?[`${M.location.file}:${M.location.line+1}`]:[]),ge=t.anchors.some(M=>M.status==="ambiguous"),le=te.some(M=>M.status==="connected"||M.status==="candidate"),be=te.some(M=>M.status==="partial");return{status:ce.length===0?"unavailable":ge?"ambiguous":le&&!be?"connected":be?"partial":"connected",steps:ce,transitions:N,paths:te,coverage:{candidateNodes:D.length,returnedNodes:_.length,omittedNodeIds:D.filter(M=>!P.has(M)),returnedTransitions:N.length,withheldStatements:ce.reduce((M,Q)=>M+(Q.behavior?.coverage.omittedStatements??0),0),requestedFocusLocations:o,matchedFocusLocations:o.filter(M=>s.has(er(M.file,M.line))),unmatchedFocusLocations:o.filter(M=>!s.has(er(M.file,M.line)))},behaviorCommand:gh(me,"behavior"),exactSourceCommand:gh(me,"source")}}function vP(e,t,n,i){if(i<=0||n.length===0)return[];let r=new Set(t),o=new Set(n.map(s=>er(s.file,s.line)));return Ln(e.edges.filter(s=>s.disposition!=="excluded"&&s.disposition!=="unsupported"&&["call","runtime-boundary"].includes(s.kind)&&r.has(s.fromNodeId)&&s.evidence.some(a=>!["candidate","unknown"].includes(a.strength)&&a.location&&o.has(er(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,i)}function CP(e,t,n,i,r,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=i.length>0?i:[t.location.line],d=t.kind==="runtime-boundary-participant"?gt(e,t.location.file,0,Math.max(0,l.length-1),[t.location.line]):gt(e,t.location.file,t.location.line,c,u),m=i.filter(L=>L>=d.startLine&&L<=d.endLine),p=Wi(e,t.location.file,d.startLine,d.endLine,m),f=p??(m.length>0?Wi(e,t.location.file,d.startLine,d.endLine,m,{requireSavings:!1}):null),g=m.length>0?LP(e,t,d.startLine,d.endLine,m,f,o):null,h=l.slice(d.startLine,d.endLine+1).join(`
62
- `).length,b=Cn(e,t.location.file,d.startLine,d.endLine),v=l.slice(d.startLine,d.endLine+1).some((L,I)=>L.length>bP&&(b.get(d.startLine+I)??[]).some(x=>["binding","branch","loop","call","return","throw","mutation"].includes(x))),y=L=>xP(e,t,d.startLine,d.endLine,r.filter(I=>I>=d.startLine&&I<=d.endLine),L),E=(s||t.kind==="runtime-boundary-participant"||t.anchorIds.length>0)&&h<=jl,w=n&&(m.length===0||E);if(p&&(a||w))return y(dh(p));if(!a&&!w&&g&&!v&&!E&&g.renderedCharacters<(f?.outlineCharacters??h))return y(g);if(p)return y(dh(p));let S=l.slice(d.startLine,d.endLine+1),R=S.join(`
63
- `),C=Cn(e,t.location.file,d.startLine,d.endLine);return y({kind:"source",constructKind:"source construct",signature:S.find(L=>L.trim().length>0)?.trim()??t.label,lines:S.map((L,I)=>({line:d.startLine+I,endLine:d.startLine+I,depth:0,signals:C.get(d.startLine+I)??[],text:L,copied:!0})),coverage:{sourceStatements:S.length,representedStatements:S.length,copiedStatements:S.length,omittedStatements:0},rawCharacters:R.length,renderedCharacters:R.length})}function xP(e,t,n,i,r,o){if(!t.location)return o;let s=Bl(e,t.location.file,n,i);if(!s.available)return o;let a=Cn(e,t.location.file,n,i),c=ie(e,t.location.file),l=new Set(r);for(let v of r){let y=ia(c[v]??"");if(!y)continue;let E=Sn(e,t.location.file,y).find(w=>w>v&&w<=i);E!==void 0&&l.add(E)}let u=[...new Map(s.targets.flatMap(v=>{let y=v.definition,E=y.relativePath===t.location.file&&y.startLine<=i&&y.endLine>=n;if(y.isTypeLike||E)return[];let w=na(e,y),S=r.length>0&&w&&a.get(v.sourceLine)?.includes("return"),R=w&&l.has(v.sourceLine);return w&&!S&&!R?[]:[[y.symbol,{definition:y,kind:S?"return-value-transformer":R?"focused-causal-target":"compiler-referenced-declaration"}]]})).values()].sort((v,y)=>v.definition.relativePath.localeCompare(y.definition.relativePath)||v.definition.startLine-y.definition.startLine||v.definition.symbol.localeCompare(y.definition.symbol)),d=[],m=u.filter(({kind:v})=>v!=="compiler-referenced-declaration").map(({definition:v})=>({owner:v,depth:1})),p=new Set,f=new Set(u.map(({definition:v})=>v.symbol));for(;m.length>0;){let v=m.shift();if(!v||p.has(v.owner.symbol))continue;p.add(v.owner.symbol);let{owner:y,depth:E}=v,w=Bl(e,y.relativePath,y.startLine,y.endLine);if(!w.available)continue;let S=Cn(e,y.relativePath,y.startLine,y.endLine),R=ie(e,y.relativePath);for(let C of w.targets){let L=C.definition,I=L.relativePath===y.relativePath&&L.startLine<=y.endLine&&L.endLine>=y.startLine;if(L.isTypeLike||I)continue;let x=na(e,L),D=ia(R[C.sourceLine]??""),_=x&&D!==null&&Sn(e,y.relativePath,D).some(T=>T>C.sourceLine&&T<=y.endLine&&(S.get(T)??[]).some(F=>["branch","return","throw"].includes(F))),P=x&&((S.get(C.sourceLine)??[]).some(T=>["branch","return","throw"].includes(T))||_);x&&!P||(f.has(L.symbol)||(f.add(L.symbol),d.push({definition:L,kind:x?"focused-causal-target":"compiler-referenced-declaration"})),x&&E<2&&m.push({owner:L,depth:E+1}))}}let g=[...new Map([...u,...d].map(v=>[v.definition.symbol,v])).values()].sort((v,y)=>v.definition.relativePath.localeCompare(y.definition.relativePath)||v.definition.startLine-y.definition.startLine||v.definition.symbol.localeCompare(y.definition.symbol)),h=[],b=[];for(let{definition:v,kind:y}of g){let E=y==="compiler-referenced-declaration"?RP(e,v.relativePath,v.startLine,v.endLine):{startLine:v.startLine,endLine:v.endLine},w=ie(e,v.relativePath).slice(E.startLine,E.endLine+1).join(`
64
- `),S=y==="compiler-referenced-declaration"?null:Wi(e,v.relativePath,v.startLine,v.endLine,[]),R=S?[S.signature,...S.lines.map(D=>`${D.line+1}${D.signals.length>0?`[${D.signals.join(",")}]`:""} ${D.text}`)].join(" | "):null,C=R&&R.length<w.length?R:w,L={symbol:v.symbol,label:v.leaf,file:v.relativePath,line:E.startLine,endLine:E.endLine},I=y==="compiler-referenced-declaration"?1e3:8e3,x=y==="compiler-referenced-declaration"?12:120;if(C.length>I||E.endLine-E.startLine>x){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 RP(e,t,n,i){let r=ae(e,t);if(!r)return{startLine:n,endLine:i};let o=[];yh(r.rootNode,a=>{SP.has(a.type)&&a.startPosition.row<=n&&a.endPosition.row>=i&&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:i}}function yh(e,t){t(e);for(let n of e.namedChildren)yh(n,t)}function dh(e){return{kind:"outline",constructKind:e.constructKind,signature:e.signature,lines:e.lines,coverage:e.coverage,rawCharacters:e.rawCharacters,renderedCharacters:e.outlineCharacters}}function EP(e,t,n,i,r,o){if(!t.location||!["symbol","source-construct","runtime-boundary-participant"].includes(t.kind))return[];let s=new Set,a=new Set(ee(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 Mr(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=i.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(!r.has(c.id)&&!u&&!d)continue;let m=c.evidence.flatMap(b=>b.location?.file===t.location.file?[b.location.line]:[]),p=m.filter(b=>a.has(b));for(let b of p.length>0?p:m)s.add(b);let f=l?.attributes.leaf;if(typeof f!="string"||f.length===0)continue;let g=Sn(e,t.location.file,f).filter(b=>b>=t.location.line&&b<=(t.location.endLine??t.location.line)),h=g.find(b=>a.has(b))??g[0];h!==void 0&&s.add(h)}return[...s].sort((c,l)=>c-l)}function wP(e,t){if(!e.location)return[];let n=e.location.endLine??e.location.line;return t.filter(i=>i.file===e.location.file&&i.line>=e.location.line&&i.line<=n).map(i=>i.line)}function IP(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(er(n.file,n.line),{file:n.file,line:n.line})}return[...t.values()].sort((n,i)=>n.file.localeCompare(i.file)||n.line-i.line)}function er(e,t){return`${e}\0${t}`}function LP(e,t,n,i,r,o,s){if(!t.location)return null;let a=ie(e,t.location.file),c=Cn(e,t.location.file,n,i),l=[...c].filter(([,P])=>P.length>0).map(([P])=>P).sort((P,T)=>P-T),u=r.map(P=>(c.get(P)??[]).length>0?P:l.find(T=>T>P&&T-P<=8)??P),d=new Set([...r,...u]),m=s?Yc(e,t.location.file,n,i,{minimumBodyLines:0}):null,p=o?[...new Map(u.flatMap(P=>o.lines.filter(T=>T.text.length<=500&&T.signals.some(F=>["branch","loop","catch","finally"].includes(F))&&P>=T.line&&P<=T.endLine).sort((T,F)=>T.endLine-T.line-(F.endLine-F.line)||T.line-F.line).slice(0,2).map(T=>[`${T.line}\0${T.endLine}`,T]))).values()]:Ns(e,t.location.file,n,i,u);for(let P of m?.lines??[])d.add(P.line);for(let P of p)d.add(P.line);for(let[P,T]of c)T.includes("call")&&T.includes("shape")&&d.add(P);let f=[];for(let P of u){let T=ia(a[P]??"");if(!T)continue;let F=Sn(e,t.location.file,T).filter(N=>N>P&&N<=i),W=F[0];W!==void 0&&d.add(W);let ce=F.find(N=>(c.get(N)??[]).some(K=>K==="branch"||K==="loop"));if(ce===void 0)continue;d.add(ce);let q=(o?.lines??[]).find(N=>N.line===ce)??{line:ce,endLine:Math.min(i,ce+40),depth:0,signals:c.get(ce)??[],text:(a[ce]??"").trim(),copied:!0},Y=o?.lines??a.slice(q.line,q.endLine+1).map((N,K)=>{let te=q.line+K;return{line:te,endLine:te,depth:0,signals:c.get(te)??[],text:N.trim(),copied:!0}});f.push({focusLine:P,governingUse:ce,lines:Y.filter(N=>N.line>=q.line&&N.line<=q.endLine&&N.text.length<=500&&N.signals.some(K=>["binding","branch","call","mutation"].includes(K)))})}for(let P of f.sort((T,F)=>F.governingUse-F.focusLine-(T.governingUse-T.focusLine)||T.focusLine-F.focusLine).slice(0,2))for(let T of P.lines.slice(0,14))d.add(T.line);let g=new Set(["binding","branch","loop","call","return","throw","mutation"]);for(let P of p)for(let T of o?.lines??[])T.line<P.line||T.line>P.endLine||T.signals.some(F=>g.has(F))&&d.add(T.line);let h=a.slice(n,i+1).flatMap((P,T)=>{let F=ia(P);return F?[{name:F,line:n+T}]:[]}),b=!0;for(;b;){b=!1;for(let P of h)if([...d].some(F=>DP(a[F]??"",P.name))){d.has(P.line)||(d.add(P.line),b=!0);for(let F of Sn(e,t.location.file,P.name))F<n||F>i||d.has(F)||(c.get(F)??[]).some(W=>g.has(W))&&(d.add(F),b=!0)}}for(let P of o?.lines??[])if(P.signals.some(T=>["branch","loop","catch","finally"].includes(T))&&d.has(P.line))for(let T of o?.lines??[])T.line<P.line||T.line>P.endLine||T.signals.some(F=>g.has(F))&&d.add(T.line);let v=ee(e,t.location.file),y=new Set(v?.callSites.map(P=>P.line)??[]),E=c,w=new Map([...o?.lines??[],...p].filter(P=>P.signals.some(T=>["branch","loop","catch","finally"].includes(T))).map(P=>[P.line,P])),S=new Map((o?.lines??[]).filter(P=>P.text.length<=500&&P.signals.includes("shape")&&(P.signals.includes("call")||P.signals.includes("mutation")||P.signals.includes("return"))).sort((P,T)=>P.endLine-P.line-(T.endLine-T.line)||P.line-T.line).map(P=>[P.line,P])),R=new Map((m?.lines??[]).map(P=>[P.line,P.signals.filter(T=>T!=="lifecycle")])),C=[...d].filter(P=>P>=n&&P<=i).sort((P,T)=>P-T).map(P=>{let T=w.get(P)??S.get(P);return{line:P,endLine:T?.endLine??P,depth:T?.depth??0,signals:PP([...E.get(P)??[],...o?.lines.filter(F=>P>=F.line&&P<=F.endLine).flatMap(F=>F.signals)??[],...R.get(P)??[],...r.includes(P)?["anchor"]:[],...y.has(P)?["call"]:[]]),text:T?.text??(a[P]??"").trim(),copied:T?.copied??!0}}).filter(P=>P.text.length>0);if(C.length===0)return null;let L=m?.candidateLines??Yc(e,t.location.file,n,i,{minimumBodyLines:0})?.candidateLines??0,I=Math.max(o?.coverage.sourceStatements??0,L,C.length),x=o?.signature??(a[n]??t.label).trim(),D=x.length+C.reduce((P,T)=>P+T.text.length+T.signals.join(",").length+12,0),_=a.slice(n,i+1).join(`
65
- `).length;return{kind:"connector-slice",constructKind:o?.constructKind??"source construct",signature:x,lines:C,coverage:{sourceStatements:I,representedStatements:C.length,copiedStatements:C.length,omittedStatements:Math.max(0,I-C.length)},rawCharacters:_,renderedCharacters:D}}function PP(e){let t=["anchor","signature","binding","branch","loop","call","await","return","throw","mutation","shape","spread","catch","finally"],n=new Set(e);return t.filter(i=>n.has(i))}function ia(e){return/\b(?:const|let|var)\s+([\p{L}_$][\p{L}\p{N}_$]*)\s*(?:=|\bof\b|\bin\b)/u.exec(e)?.[1]??null}function DP(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`(?:^|[^\\p{L}\\p{N}_$])${n}(?:$|[^\\p{L}\\p{N}_$])`,"u").test(e)}function TP(e,t,n){return Ln(e.flatMap(i=>{let r=n.get(i),o=t.filter(s=>s.kind==="call"&&s.toNodeId===i).map(s=>({edge:s,node:n.get(s.fromNodeId)})).filter(s=>s.node!==void 0&&["symbol","source-construct","runtime-boundary-participant"].includes(s.node.kind)&&s.node.location!==null).sort((s,a)=>{let c=mh(a.edge)-mh(s.edge);if(c!==0)return c;let l=ph(s.node,r)?0:1,u=ph(a.node,r)?0:1,d=(s.node.location?.endLine??s.node.location?.line??0)-(s.node.location?.line??0),m=(a.node.location?.endLine??a.node.location?.line??0)-(a.node.location?.line??0);return l-u||d-m||s.node.label.localeCompare(a.node.label)});return o[0]?[o[0].node.id]:[]}))}function mh(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 ph(e,t){return!e.location||!t?.location?!1:fh(e.location.file)===fh(t.location.file)}function fh(e){return e.split("/").filter(Boolean).slice(0,2).join("/")}function MP(e,t,n,i){let r=new Set(e),o=new Set,s=[],a=Ln(e);for(let c=0;c<i&&a.length>0;c+=1){let l=a.filter(d=>!o.has(d));for(let d of l)o.add(d);let u=TP(l,t,n);a=[];for(let d of u)!r.has(d)&&!s.includes(d)&&s.push(d),o.has(d)||a.push(d)}return s}function AP(e,t,n){let i=new Map(n.paths.flatMap(r=>r.edgeIds).map((r,o)=>[r,o]));return(i.get(e.id)??Number.MAX_SAFE_INTEGER)-(i.get(t.id)??Number.MAX_SAFE_INTEGER)||e.id.localeCompare(t.id)}function FP(e){return`step:${e}`}function NP(e){return`transition:${e}`}function gh(e,t){return e.length===0?null:`codebaseiq inspect ${e.map(n=>`--at ${kP(n)}`).join(" ")} --view ${t}`}function kP(e){return`'${e.replace(/'/gu,`'"'"'`)}'`}function Ln(e){return[...new Set(e)]}var bh=4,_P=3,OP=12,BP=48,$P=64,xi=10,vi=6,jP=24,HP=320,Hl=6,UP=12,zP=1,GP=4,KP=7,qP=12,ql="source-construct:",WP=96,VP=32,Sh=4,JP=32,YP=8,vh=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 XP(e,t,n={}){let i=kh(t),r=OD(t);if(i.length===0)throw new Error("Anchor discovery requires at least one non-trivial repository term.");let o=n.limit??bh,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(N=>!Le(N.symbol)),l=[...c],u=new Map(l.map(N=>[N.symbol,N])),d=new Map;for(let N of c)Ch(d,N,i);let m=Rs(e,{scope:n.scope});for(let N of m.files){let te=J(e,N.relativePath).filter(ge=>!Le(ge.symbol));if(te.length===0)continue;let me=Nh(N.text);for(let ge=0;ge<me.length;ge+=1){let le=ht(me[ge]??""),be=i.filter(Q=>le.has(Q));if(be.length===0)continue;let M=Ge(te,ge);if(!(!M||Le(M.symbol)))for(let Q of be)Xr(d,M,Q,"source",N.relativePath,ge)}}let p=xh(d),f=[...d.values()].map(N=>ra(N,p,r)).sort(Xe),g=ZP(m.files,f,i),h=-1;for(let N of g){let K=J(e,N.relativePath),te=K.filter(M=>!Le(M.symbol)),me=ee(e,N.relativePath)?.callables??[],ge=new Map,le=M=>{let Q=`${M.startLine}\0${M.endLine}\0${M.name}`,X=ge.get(Q);if(X)return X;let Se=QP(N.relativePath,K,M,()=>h--);return Se?(ge.set(Q,Se),l.push(Se),u.set(Se.symbol,Se),Ch(d,Se,i),Se):null};for(let M of me){let Q=ht(M.name);i.some(X=>Q.has(X))&&le(M)}if(me.length===0)continue;let be=Nh(N.text);for(let M=0;M<be.length;M+=1){let Q=ht(be[M]??""),X=i.filter(_i=>Q.has(_i));if(X.length===0)continue;let Se=eD(me,M),tt=Se?le(Se):null;if(!tt)continue;let ai=Rh(te,M);if(Rh(ai?[ai,tt]:[tt],M)?.symbol===tt.symbol)for(let _i of X)Xr(d,tt,_i,"source",N.relativePath,M)}}let b=xh(d),v=new Map(m.files.map(N=>[N.relativePath,N.text.split(/\r?\n/u)]));for(let N of d.values()){let K=v.get(N.definition.relativePath);K&&(N.sourceCharacters=K.slice(N.definition.startLine,N.definition.endLine+1).join(`
66
- `).length)}let y=[...d.values()].map(N=>ra(N,b,r)).sort(Xe),E=Math.min(y.length,Math.max(OP,o*_P)),w=s?y:tr([...y.slice(0,E),...[...y].sort(zl).slice(0,Math.max(BP,E)),...TD(y,i),...MD(y,i,b)]),S=w.length,R=w.map(N=>u.get(N.symbol)).filter(N=>N?.isFunctionLike===!0),C=tD(l),L=nD(e,a,w,R,u,C,new Set(d.keys()),n.semantic!==!1),I=oD(L,w,d,b,u),x=sD(I,b,i),D=vD(e,a,L,d,b,l,u,n.semantic!==!1),P=[...cD(e,a,I,u,b,n.semantic!==!1),...x,...I,...D].map(N=>({...N,queryPathMatches:FD(N)})).sort((N,K)=>Ci(N,K,b)),T=s?P:ND(P,o,b),F=i.filter(N=>b.has(N)),W=i.filter(N=>!b.has(N)),ce=Math.max(0,y.length-S),q=Math.max(0,P.length-T.length)+ce,Y=s?y.length:Math.min(y.length,o+bh);return{query:t,queryPathFragments:r,normalizedTerms:i,matchedTerms:F,unmatchedTerms:W,groups:T,candidateRoots:y,candidateRootCount:y.length,analyzedRootCount:S,omittedRootCount:ce,omittedGroupCount:q,scannedFiles:m.files.length,scannedBytes:m.scannedBytes,recoveryCommand:q===0?null:`codebaseiq anchors ${ca(t)}${n.scope?` --scope ${ca(n.scope)}`:""} --limit ${Y}`}}function kh(e){let t=la(e).filter(n=>!vh.has(n.toLocaleLowerCase())).map(Wl).filter(n=>n.length>=3&&!vh.has(n));return[...new Set(t)]}function Ch(e,t,n){let i=ht(t.leaf),r=ht(t.relativePath),o=ht(t.documentation??"");for(let a of n)i.has(a)&&Xr(e,t,a,"symbol"),r.has(a)&&Xr(e,t,a,"path"),o.has(a)&&Xr(e,t,a,"documentation");let s=e.get(t.symbol);s&&(s.symbolPhraseLength=$D(t.leaf,n))}function Xr(e,t,n,i,r,o){let s=e.get(t.symbol)??{definition:t,matches:new Map,symbolPhraseLength:0},a=s.matches.get(n)??{sources:new Set,locations:new Map};a.sources.add(i),r!==void 0&&o!==void 0&&a.locations.set(`${r}\0${o}`,{file:r,line:o}),s.matches.set(n,a),e.set(t.symbol,s)}function xh(e){let t=new Map;for(let n of e.values())for(let i of n.matches.keys())t.set(i,(t.get(i)??0)+1);return t}function QP(e,t,n,i){let r=t[0]?.documentId;if(r===void 0||t.find(a=>a.isFunctionLike&&a.leaf===n.name&&a.startLine===n.startLine&&a.endLine===n.endLine))return null;let s=i();return{documentId:r,symbolId:s,symbol:`${ql}${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 ZP(e,t,n){let i=new Set(t.slice(0,WP).map(s=>s.file)),r=new Set(n),o=e.map(s=>{let a=ht(s.relativePath),c=s.relativePath.slice(s.relativePath.lastIndexOf("/")+1).replace(/\.[^.]+$/u,""),l=ht(c),u=[...a].filter(m=>r.has(m)).length,d=[...l].filter(m=>r.has(m)).length;return{file:s,score:d*4+u}}).filter(s=>s.score>0).sort((s,a)=>a.score-s.score||Gt(V(s.file.relativePath))-Gt(V(a.file.relativePath))||s.file.relativePath.localeCompare(a.file.relativePath)).slice(0,VP);for(let s of o)i.add(s.file.relativePath);return e.filter(s=>i.has(s.relativePath))}function eD(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,i)=>n.endLine-n.startLine-(i.endLine-i.startLine)||n.startLine-i.startLine)[0]}function tD(e){let t=new Map;for(let n of e){if(!on(n))continue;let i=`${n.relativePath}\0${sn(n.leaf)}`,r=t.get(i)??[];r.push(n),t.set(i,r)}return t}function Rh(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,i)=>n.endLine-n.startLine-(i.endLine-i.startLine)||Number(on(i))-Number(on(n))||n.startLine-i.startLine||n.symbol.localeCompare(i.symbol))[0]}function on(e){return e.symbol.startsWith(ql)}function qn(e){return on(e)?e.leaf:k(e.symbol)}function ra(e,t,n=[]){let i=e.definition,r=[...e.matches.entries()].map(([l,u])=>({term:l,sources:[...u.sources].sort(jD),locations:[...u.locations.values()].sort($h).slice(0,3)})).sort((l,u)=>l.term.localeCompare(u.term)),o=r.filter(l=>l.sources.some(u=>u!=="source")).map(l=>l.term),s=r.filter(l=>l.sources.includes("symbol")).map(l=>l.term),a=r.reduce((l,u)=>l+1/Math.max(1,t.get(u.term)??1),0),c=r.filter(l=>l.sources.includes("symbol")).reduce((l,u)=>l+1/Math.max(1,t.get(u.term)??1),0);return{symbol:i.symbol,label:qn(i),leaf:i.leaf,file:i.relativePath,line:i.startLine,endLine:i.endLine,kind:i.isFunctionLike?"callable":i.isTypeLike?"type":"symbol",fileKind:V(i.relativePath),matches:r,focusLocations:zD(e,t),matchedTerms:r.map(l=>l.term),symbolMatchedTerms:s,symbolPhraseLength:e.symbolPhraseLength,identityMatchedTerms:o,rarity:a,symbolRarity:c,queryPathMatches:BD(i.relativePath,n),...e.sourceCharacters===void 0?{}:{sourceCharacters:e.sourceCharacters}}}function nD(e,t,n,i,r,o,s,a){let c=i.filter(g=>!on(g)),l=t.calleeMap(c,{additive:!1,semantic:a}),u=new Map,d=new Map;for(let g of n){let h=r.get(g.symbol),b=h?on(h)?Eh(e,h,r,o,1):oa(e,h,l.get(h.symbolId)??[],r,1,s):[];u.set(g.symbol,b);for(let v of b){let y=r.get(v.toSymbol);y?.isFunctionLike&&(!h||!on(h)||on(y))&&d.set(y.symbol,y)}}let m=[...d.values()],p=t.calleeMap(m.filter(g=>!on(g)),{additive:!1,semantic:a}),f=new Map;for(let g of m)f.set(g.symbol,on(g)?Eh(e,g,r,o,2):oa(e,g,p.get(g.symbolId)??[],r,2,s));return n.map(g=>{let h=u.get(g.symbol)??[],b=h.flatMap(y=>f.get(y.toSymbol)??[]),v=Pn([...h,...b]);return{root:g,relations:v,nodeSymbols:new Set([g.symbol,...v.flatMap(y=>[y.fromSymbol,y.toSymbol])])}})}function oa(e,t,n,i,r,o=new Set){let s=new Map;for(let a of n){let c=i.get(a.symbol);if(!c?.isFunctionLike||c.symbol===t.symbol||a.source==="ast-callsite"&&!rD(e,t,c,a.callsiteLine))continue;let l=s.get(c.symbol);(!l||_D(a,l)<0)&&s.set(c.symbol,a)}return[...s.entries()].map(([a,c])=>{let l=i.get(a);return{kind:"call",fromSymbol:t.symbol,fromLabel:k(t.symbol),fromFile:t.relativePath,toSymbol:l.symbol,toLabel:k(l.symbol),toFile:l.relativePath,depth:r,strength:Kl(c.source),evidence:c.source,callsiteLine:c.callsiteLine??iD(e,t,l)}}).sort((a,c)=>Number(o.has(c.toSymbol))-Number(o.has(a.toSymbol))||an(a,c)).slice(0,$P)}function Eh(e,t,n,i,r){let o=In(e,t.relativePath,t.startLine,t.endLine).targets.flatMap(s=>{let a=n.get(s.definition.symbol)??s.definition;return!a.isFunctionLike||a.symbol===t.symbol?[]:[{kind:"call",fromSymbol:t.symbol,fromLabel:qn(t),fromFile:t.relativePath,toSymbol:a.symbol,toLabel:qn(a),toFile:a.relativePath,depth:r,strength:"exact",evidence:"scip-occurrence-callsite",callsiteLine:s.sourceLine}]});for(let s of Kn(e,t.relativePath,{ranges:[{startLine:t.startLine,endLine:t.endLine}],excludeIndexedTargets:!1}).targets){let a=[...i.get(`${s.targetFile}\0${sn(s.calleeLeaf)}`)??[],...J(e,s.targetFile).filter(c=>c.isFunctionLike&&sn(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:qn(t),fromFile:t.relativePath,toSymbol:a.symbol,toLabel:qn(a),toFile:a.relativePath,depth:r,strength:s.strength==="exact"?"exact":"derived",evidence:"ast-member-import-candidate",callsiteLine:s.line})}for(let s of ee(e,t.relativePath)?.callSites??[]){if(s.line<t.startLine||s.line>t.endLine||s.memberAccess)continue;let a=(i.get(`${t.relativePath}\0${sn(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:qn(t),fromFile:t.relativePath,toSymbol:c.symbol,toLabel:qn(c),toFile:c.relativePath,depth:r,strength:"derived",evidence:"ast-callsite",callsiteLine:s.line})}return Pn(o).sort(an)}function iD(e,t,n){let i=sn(n.leaf);return ee(e,t.relativePath)?.callSites.find(r=>r.line>=t.startLine&&r.line<=t.endLine&&sn(r.calleeLeaf)===i)?.line??null}function rD(e,t,n,i){if(i===void 0)return!1;let r=sn(n.leaf);return ee(e,t.relativePath)?.callSites.some(o=>o.line===i&&sn(o.calleeLeaf)===r)??!1}function sn(e){return e.replace(/^#/u,"").replace(/\(\)$/u,"")}function oD(e,t,n,i,r){let o=new Map(t.map((u,d)=>[u.symbol,d])),s=t.map((u,d)=>d),a=u=>{let d=u;for(;s[d]!==d;)d=s[d];for(;s[u]!==u;){let m=s[u];s[u]=d,u=m}return d},c=(u,d)=>{let m=a(u),p=a(d);m!==p&&(s[p]=m)};for(let u of e){let d=o.get(u.root.symbol);if(d!==void 0)for(let m of u.nodeSymbols){let p=o.get(m);p!==void 0&&c(d,p)}}let l=new Map;for(let u=0;u<t.length;u+=1){let d=a(u),m=l.get(d)??[];m.push(t[u]),l.set(d,m)}return[...l.values()].map((u,d)=>{let m=new Set(u.map(y=>y.symbol)),p=Pn(e.filter(y=>m.has(y.root.symbol)).flatMap(y=>y.relations)).sort(an),f=new Map(u.map(y=>[y.symbol,y]));for(let y of new Set(p.flatMap(E=>[E.fromSymbol,E.toSymbol]))){let E=n.get(y);if(E)f.has(y)||f.set(y,ra(E,i));else{let w=r.get(y);w&&f.set(y,Oh(w))}}let g=LD(u,p,f),h=u.filter(y=>p.some(E=>E.fromSymbol===y.symbol)).length,b=[...new Set(u.flatMap(y=>y.matchedTerms))].sort(),v=ID(p,g,m,f);return{id:`anchor-set:${d+1}:${Zr(u[0])}`,kind:"connected-flow",roots:[...u].sort(Xe),keyAnchors:g,candidateOwnerCount:g.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:[],matchedTerms:b,relations:v,relationCount:p.length,orchestrationRootCount:h,omittedRelations:Math.max(0,p.length-xi),systemMapCommand:to(g,p,b)}})}function sD(e,t,n){let i=new Map(n.map((o,s)=>[o,s])),r=[];for(let o=0;o<e.length;o+=1){let s=e[o],a=wh(s);if(a.size!==0)for(let c=o+1;c<e.length;c+=1){let l=e[c],u=wh(l),d=[...a].filter(w=>u.has(w));if(d.length===0||![...a].some(w=>!u.has(w))||![...u].some(w=>!a.has(w)))continue;let m=aD(s,l);if(m.length<2)continue;let p=Pn([...s.relations,...l.relations]).sort(an),f=p.slice(0,xi),g=tr([...s.roots,...l.roots]).sort(Xe),h=[...new Set([...s.matchedTerms,...l.matchedTerms])].sort(),b=d.sort((w,S)=>(i.get(w)??Number.MAX_SAFE_INTEGER)-(i.get(S)??Number.MAX_SAFE_INTEGER)||w.localeCompare(S)),v=+(s.relationCount>0)+ +(l.relationCount>0),y=+((s.orchestrationRootCount??0)>0)+ +((l.orchestrationRootCount??0)>0),E=Math.min(...b.map(w=>t.get(w)??Number.MAX_SAFE_INTEGER));r.push({sharedOrder:Math.min(...b.map(w=>i.get(w)??Number.MAX_SAFE_INTEGER)),sharedFrequency:E,connectedSides:v,orchestrationSides:y,group:{id:`parallel-paths:${Zr(s.roots[0])}:${Zr(l.roots[0])}`,kind:"parallel-paths",roots:g,keyAnchors:m,candidateOwnerCount:m.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:[...s.upstreamEntries,...l.upstreamEntries],matchedTerms:h,relations:f,relationCount:p.length,parallelConnectedSides:v,parallelOrchestrationSides:y,parallelSharedPathTerms:b,parallelSharedPathFrequency:E,orchestrationRootCount:(s.orchestrationRootCount??0)+(l.orchestrationRootCount??0),omittedRelations:Math.max(0,p.length-f.length),systemMapCommand:to(m,p,h)}})}}return r.sort((o,s)=>o.sharedFrequency-s.sharedFrequency||s.orchestrationSides-o.orchestrationSides||s.connectedSides-o.connectedSides||o.sharedOrder-s.sharedOrder||s.group.matchedTerms.length-o.group.matchedTerms.length||Ci(o.group,s.group,t)).slice(0,qP).map(o=>o.group)}function wh(e){return new Set(e.roots.flatMap(t=>t.matches.filter(n=>n.sources.includes("path")).map(n=>n.term)))}function aD(e,t){return tr([Ih(e),Ih(t)].filter(n=>n!==void 0))}function Ih(e){let t=new Set(e.keyAnchors.map(i=>i.symbol)),n=new Map;for(let i of e.relations)!t.has(i.fromSymbol)||!t.has(i.toSymbol)||n.set(i.fromSymbol,(n.get(i.fromSymbol)??0)+1);return[...e.keyAnchors].sort((i,r)=>+((n.get(r.symbol)??0)>0)-+((n.get(i.symbol)??0)>0)||Lh(r)-Lh(i)||r.identityMatchedTerms.length-i.identityMatchedTerms.length||r.symbolMatchedTerms.length-i.symbolMatchedTerms.length||(n.get(r.symbol)??0)-(n.get(i.symbol)??0)||Xe(i,r))[0]}function Lh(e){return e.matchedTerms.length+e.identityMatchedTerms.length*2+(e.queryPathMatches?.length??0)*4}function cD(e,t,n,i,r,o){let s=fs(e);if(!s||s.links.length===0||n.length<2)return[];let a=new Map(s.observations.map(p=>[p.id,p])),c=new Map,l=new Map,u=[...n].sort((p,f)=>Ci(p,f,r)).slice(0,UP),d=s.links.filter(p=>p.strength!=="candidate").sort((p,f)=>Wn(f.strength)-Wn(p.strength)||f.matchedKeyParts.length-p.matchedKeyParts.length||p.id.localeCompare(f.id));for(let p of u)for(let f of d){let g=a.get(f.from),h=a.get(f.to);if(!g||!h||!lD(p,g,i))continue;let b=uD(p,g,i);if(!b)continue;let v=c.get(h.id)??pD(e,t,h,i,o,GP);if(c.set(h.id,v),v.reachedSymbols.size===0)continue;let y=n.filter(P=>P.id!==p.id&&dD(P).some(T=>v.reachedSymbols.has(T))&&Ul(b,P)>=2).sort((P,T)=>Ul(b,T)-Ul(b,P)||Ci(P,T,r)).slice(0,zP);if(y.length===0)continue;let E=[p.id,g.id,...y.map(P=>P.id).sort()].join("\0");if(l.has(E))continue;let w=new Set(y.flatMap(eo)),S=bD(Qr(h),w,v.relations);if(S.length===0)continue;let R=yD(g,h,f.joinRule,f.matchedKeyParts,f.strength),C=Pn([R,...v.relations,...p.relations,...y.flatMap(P=>P.relations)]),L=SD([R,...S],C,p,y),I=tr([b,...y.flatMap(P=>P.roots)]).sort(Xe),x=tr([b,...y.flatMap(P=>P.keyAnchors)]).slice(0,KP),D=[...new Set([...b.matchedTerms,...y.flatMap(P=>P.matchedTerms)])].sort(),_=mD(e,t,b,i,o);I.length===0||x.length<2||l.set(E,{id:`cross-boundary-set:${Zr(b)}:${l.size+1}`,kind:"cross-boundary-flow",roots:I,keyAnchors:x,candidateOwnerCount:x.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:_,matchedTerms:D,relations:L,relationCount:C.length,omittedRelations:Math.max(0,C.length-L.length),systemMapCommand:to(x,C,D)})}let m=new Map;for(let[p,f]of l){let g=p.slice(0,p.indexOf("\0")),h=m.get(g);(!h||Ci(f,h,r)<0)&&m.set(g,f)}return[...m.values()]}function lD(e,t,n){let i=new Set(eo(e));return t.owner.symbol&&i.has(t.owner.symbol)?!0:[...i].map(r=>n.get(r)).some(r=>r?.relativePath===t.source.file&&r.startLine<=t.source.startLine&&r.endLine>=t.source.endLine)}function uD(e,t,n){let i=tr([...e.roots,...e.keyAnchors]);if(t.owner.symbol){let r=i.find(o=>o.symbol===t.owner.symbol);if(r)return r}return i.find(r=>{let o=n.get(r.symbol);return o?.relativePath===t.source.file&&o.startLine<=t.source.startLine&&o.endLine>=t.source.endLine})??null}function eo(e){return[...new Set([...e.roots.map(t=>t.symbol),...e.keyAnchors.map(t=>t.symbol),...e.relations.flatMap(t=>[t.fromSymbol,t.toSymbol])])]}function dD(e){return[...new Set([...e.roots,...e.keyAnchors].map(t=>t.symbol))]}function Ul(e,t){let n=ht(e.leaf),i=[...t.roots,...t.keyAnchors].map(o=>ht(o.leaf)),r=0;for(let o of i){let s=0;for(let a of n)o.has(a)&&(s+=1);r=Math.max(r,s)}return r}function mD(e,t,n,i,r){let o=i.get(n.symbol);if(!o?.isFunctionLike)return[];let s=t.callerFileMap([o],{semantic:r,sourceFallback:!0}).get(o.symbolId);if(!s)return[];let a=ht(n.leaf);return[...s].filter(c=>c!==n.file&&V(c)!=="test").flatMap(c=>{let l=ee(e,c);return(l?.callSites??[]).filter(u=>sn(u.calleeLeaf)===sn(n.leaf)).flatMap(u=>{let d=(l?.callables??[]).filter(p=>p.startLine<=u.line&&p.endLine>=u.line).sort((p,f)=>p.endLine-p.startLine-(f.endLine-f.startLine)||p.startLine-f.startLine)[0];if(!d)return[];let m=[...ht(d.name)].filter(p=>a.has(p)).length;return m>=2?[{name:d.name,file:c,line:d.startLine,endLine:d.endLine,callsiteLine:u.line,overlap:m}]:[]})}).sort((c,l)=>l.overlap-c.overlap||c.file.localeCompare(l.file)||c.line-l.line).slice(0,1).map(({name:c,file:l,line:u,endLine:d,callsiteLine:m})=>({name:c,file:l,line:u,endLine:d,callsiteLine:m}))}function pD(e,t,n,i,r,o){let s=fD(e,n,i),a=s.map(({definition:m,evidence:p,line:f})=>({kind:"call",fromSymbol:Qr(n),fromLabel:sa(n),fromFile:n.source.file,toSymbol:m.symbol,toLabel:k(m.symbol),toFile:m.relativePath,depth:1,strength:p==="scip-occurrence-callsite"?"exact":"derived",evidence:p,callsiteLine:f})),c=gD(e,n);a.push(...c.relations);let l=_h([...s.map(m=>m.definition),...c.definitions]),u=l,d=new Set(u.map(m=>m.symbol));for(let m=2;m<=o+1&&u.length>0;m+=1){let p=t.calleeMap(u,{additive:!1,semantic:r}),f=new Map;for(let g of u){let h=oa(e,g,p.get(g.symbolId)??[],i,m);a.push(...h);for(let b of h){let v=i.get(b.toSymbol);v?.isFunctionLike&&!d.has(v.symbol)&&f.set(v.symbol,v)}}u=[...f.values()];for(let g of u)d.add(g.symbol)}return{entryDefinitions:l,relations:Pn(a),reachedSymbols:new Set([...l.map(m=>m.symbol),...a.flatMap(m=>[m.fromSymbol,m.toSymbol])])}}function fD(e,t,n){let i=t.owner.symbol?n.get(t.owner.symbol):void 0;if(i?.isFunctionLike&&!Le(i.symbol))return[{definition:i,evidence:"scip-occurrence-callsite",line:t.source.startLine}];let r=ie(e,t.source.file),o=gt(e,t.source.file,0,Math.max(0,r.length-1),[t.source.startLine]),s=In(e,t.source.file,o.startLine,o.endLine).targets.map(u=>({definition:u.definition,evidence:"scip-occurrence-callsite",line:u.sourceLine})),a=ee(e,t.source.file),c=Zt(e),l=(a?.callSites??[]).flatMap(u=>{if(u.line<o.startLine||u.line>o.endLine)return[];let d=Qt(t.source.file,c.get(u.calleeLeaf)??[]),m=jn(e,t.source.file,d,u.memberAccess,u.calleeQualifier),p=m?n.get(m.symbol):void 0;return p?.isFunctionLike?[{definition:p,evidence:"ast-callsite",line:u.line}]:[]});return hD([...s,...l])}function gD(e,t){let n=ie(e,t.source.file),i=gt(e,t.source.file,0,Math.max(0,n.length-1),[t.source.startLine]),r=Kn(e,t.source.file,{ranges:[i],excludeIndexedTargets:!1}).targets,o=[],s=[];for(let a of r){let c=`source-construct:${a.targetFile}:${a.targetStartLine}:${a.targetEndLine}:${a.calleeLeaf}`;s.push({kind:"call",fromSymbol:Qr(t),fromLabel:sa(t),fromFile:t.source.file,toSymbol:c,toLabel:a.calleeLeaf,toFile:a.targetFile,depth:1,strength:"derived",evidence:"ast-member-import-candidate",callsiteLine:a.line});let l=In(e,a.targetFile,a.targetStartLine,a.targetEndLine).targets;for(let u of l)o.push(u.definition),s.push({kind:"call",fromSymbol:c,fromLabel:a.calleeLeaf,fromFile:a.targetFile,toSymbol:u.definition.symbol,toLabel:k(u.definition.symbol),toFile:u.definition.relativePath,depth:2,strength:"exact",evidence:"scip-occurrence-callsite",callsiteLine:u.sourceLine})}return{definitions:_h(o),relations:Pn(s)}}function hD(e){return[...new Map(e.map(t=>[t.definition.symbol,t])).values()]}function _h(e){return[...new Map(e.map(t=>[t.symbol,t])).values()]}function Qr(e){return e.owner.symbol??e.id}function sa(e){return e.owner.name??`${e.source.file}:${e.source.startLine+1}`}function yD(e,t,n,i,r){return{kind:"runtime-boundary",fromSymbol:Qr(e),fromLabel:sa(e),fromFile:e.source.file,toSymbol:Qr(t),toLabel:sa(t),toFile:t.source.file,depth:1,strength:r,evidence:`runtime-boundary:${n}`,callsiteLine:e.source.startLine,runtimeBoundaryKey:i.map(o=>`${o.name}=${o.value}`).join(" ")}}function bD(e,t,n){let i=new Map;for(let s of n){let a=i.get(s.fromSymbol)??[];a.push(s),i.set(s.fromSymbol,a)}let r=[{symbol:e,path:[]}],o=new Set([e]);for(;r.length>0;){let s=r.shift();if(s.path.length>0&&t.has(s.symbol))return s.path;for(let a of(i.get(s.symbol)??[]).sort(an))o.has(a.toSymbol)||(o.add(a.toSymbol),r.push({symbol:a.toSymbol,path:[...s.path,a]}))}return[]}function SD(e,t,n,i){let r=Pn(e),o=new Set([n,...i].flatMap(s=>[...eo(s),...s.keyAnchors.map(a=>a.symbol)]));for(let s of t){if(r.length>=xi)break;!o.has(s.fromSymbol)&&!o.has(s.toSymbol)||r.some(a=>a.fromSymbol===s.fromSymbol&&a.toSymbol===s.toSymbol)||r.push(s)}return r.slice(0,xi)}function vD(e,t,n,i,r,o,s,a){let c=n.filter(u=>!u.root.symbol.startsWith(ql)).map(u=>({root:u.root,relations:u.relations.filter(d=>d.depth===1&&d.fromSymbol===u.root.symbol)}));return CD(c).flatMap((u,d)=>{let m=new Set(u.map(F=>F.root.symbol)),p=new Map;for(let F of u)for(let W of new Set(F.relations.map(ce=>ce.toSymbol)))p.set(W,(p.get(W)??0)+1);let f=[...p].filter(([,F])=>F>=2).sort(([F,W],[ce,q])=>q-W||xD(F,ce,i,r,s)).map(([F])=>s.get(F)).filter(F=>F?.isFunctionLike===!0).slice(0,jP);if(f.length===0)return[];let g=t.callerFileMap(f,{semantic:a,sourceFallback:!0}),h=new Set;for(let F of f){h.add(F.relativePath);for(let W of g.get(F.symbolId)??[])h.add(W)}let b=o.filter(F=>F.isFunctionLike&&h.has(F.relativePath)).sort(RD).slice(0,HP),v=t.calleeMap(b,{additive:!1,semantic:a}),y=new Set(f.map(F=>F.symbol)),E=Pn(b.flatMap(F=>oa(e,F,v.get(F.symbolId)??[],s,1,y).filter(W=>y.has(W.toSymbol)))),w=new Map;for(let F of E){let W=w.get(F.fromSymbol)??new Set;W.add(F.toSymbol),w.set(F.fromSymbol,W)}let S=new Set([...w].filter(([F,W])=>W.size>=2||m.has(F)).map(([F])=>F)),R=E.filter(F=>S.has(F.fromSymbol));if(S.size<2||R.length===0)return[];let L=[...new Set(R.map(F=>F.toSymbol))].map(F=>aa(F,i,r,s)).filter(F=>F!==null).sort(Xe),I=[...S].map(F=>aa(F,i,r,s)).filter(F=>F!==null),x=ED(I,R),D=x.slice(0,Hl),_=x.slice(Hl);if(L.length===0||D.length===0)return[];let P=[...new Set([...L.flatMap(F=>F.matchedTerms),...u.flatMap(F=>F.root.matchedTerms)])].sort(),T=wD(R,D);return[{id:`effect-owner-set:${d+1}:${Zr(L[0])}`,kind:"shared-callee-owners",roots:L,keyAnchors:D,candidateOwnerCount:x.length,omittedCandidateOwners:_,ownerRecoveryCommands:GD(_,Hl),upstreamEntries:[],matchedTerms:P,relations:T,relationCount:R.length,omittedRelations:Math.max(0,R.length-T.length),systemMapCommand:to(D,R,P)}]})}function CD(e){let t=e.map((s,a)=>a),n=s=>{for(;t[s]!==s;)t[s]=t[t[s]],s=t[s];return s},i=(s,a)=>{let c=n(s),l=n(a);c!==l&&(t[l]=c)},r=e.map(s=>new Set(s.relations.map(a=>a.toSymbol)));for(let s=0;s<e.length;s+=1)for(let a=s+1;a<e.length;a+=1){let c=0;for(let l of r[s]??[])if((r[a]??new Set).has(l)&&(c+=1),c>=2)break;c>=2&&i(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 xD(e,t,n,i,r){let o=aa(e,n,i,r),s=aa(t,n,i,r);return o?s?Xe(o,s):-1:s?1:e.localeCompare(t)}function RD(e,t){return Gt(V(e.relativePath))-Gt(V(t.relativePath))||e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine}function aa(e,t,n,i){let r=t.get(e);if(r)return ra(r,n);let o=i.get(e);return o?Oh(o):null}function ED(e,t){let n=new Map;for(let r of t){let o=n.get(r.toSymbol)??new Set;o.add(r.fromSymbol),n.set(r.toSymbol,o)}let i=new Map;for(let r of t){let o=n.get(r.toSymbol)?.size??1;i.set(r.fromSymbol,(i.get(r.fromSymbol)??0)+o*o)}return[...e].sort((r,o)=>Number(r.leaf.startsWith("#"))-Number(o.leaf.startsWith("#"))||o.identityMatchedTerms.length-r.identityMatchedTerms.length||(i.get(o.symbol)??0)-(i.get(r.symbol)??0)||Xe(r,o))}function wD(e,t){let n=new Map(t.map((s,a)=>[s.symbol,a])),i=t.map(s=>e.filter(a=>a.fromSymbol===s.symbol).sort(an)),r=[],o=0;for(;r.length<xi&&i.some(s=>o<s.length);){for(let s of i){let a=s[o];if(a&&r.push(a),r.length>=xi)break}o+=1}return r.sort((s,a)=>n.get(s.fromSymbol)-n.get(a.fromSymbol)||an(s,a))}function ID(e,t,n,i){let r=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 r.has(u.fromSymbol)&&(d+=100),n.has(u.toSymbol)&&(d+=60),d+=Math.min(40,(o.get(u.toSymbol)??0)*8),(i.get(u.toSymbol)?.matchedTerms.length??0)>0&&(d+=25),u.fromFile!==u.toFile&&(d+=15),u.strength==="exact"&&(d+=5),d};return l(c)-l(a)||an(a,c)}).slice(0,xi).sort((a,c)=>(r.get(a.fromSymbol)??vi)-(r.get(c.fromSymbol)??vi)||a.depth-c.depth||(a.callsiteLine??Number.MAX_SAFE_INTEGER)-(c.callsiteLine??Number.MAX_SAFE_INTEGER)||an(a,c))}function Oh(e){return{symbol:e.symbol,label:qn(e),leaf:e.leaf,file:e.relativePath,line:e.startLine,endLine:e.endLine,kind:e.isFunctionLike?"callable":e.isTypeLike?"type":"symbol",fileKind:V(e.relativePath),matches:[],focusLocations:[],matchedTerms:[],symbolMatchedTerms:[],symbolPhraseLength:0,identityMatchedTerms:[],rarity:0,symbolRarity:0}}function LD(e,t,n){let i=[...e].sort(Xe),r=[],o=new Map;for(let u of t)o.set(u.fromSymbol,(o.get(u.fromSymbol)??0)+1);let s=new Set,a=new Set,c=u=>{if(!(!u||r.some(d=>d.symbol===u.symbol))){r.push(u);for(let d of u.matchedTerms)s.add(d);for(let d of u.symbolMatchedTerms)a.add(d)}},l=i.filter(u=>u.symbolPhraseLength>=2&&(o.get(u.symbol)??0)>=2);for(;r.length<Math.min(2,vi);){let u=l.filter(d=>!r.some(m=>m.symbol===d.symbol)).sort((d,m)=>m.symbolMatchedTerms.filter(p=>!a.has(p)).length-d.symbolMatchedTerms.filter(p=>!a.has(p)).length||m.symbolPhraseLength-d.symbolPhraseLength||(o.get(m.symbol)??0)-(o.get(d.symbol)??0)||zl(d,m))[0];if(!u||r.length>0&&u.symbolMatchedTerms.every(d=>a.has(d)))break;c(u)}if(c(i[0]),r.length>=2){let u=PD(r[0].symbol,r[1].symbol,t,n);for(let d of u?.slice(1,-1)??[]){if(r.length>=vi)break;c(n.get(d))}if(r.length<vi){let d=new Set(r.map(f=>f.symbol)),m=new Set(t.filter(f=>f.depth===1&&d.has(f.fromSymbol)&&d.has(f.toSymbol)).map(f=>f.fromSymbol)),p=t.filter(f=>f.depth===1&&m.has(f.fromSymbol)&&!d.has(f.toSymbol)).map(f=>({relation:f,candidate:n.get(f.toSymbol)})).filter(f=>f.candidate!==void 0&&f.candidate.symbolPhraseLength>=2&&f.candidate.symbolMatchedTerms.length>=2).sort((f,g)=>(o.get(f.relation.fromSymbol)??0)-(o.get(g.relation.fromSymbol)??0)||zl(f.candidate,g.candidate))[0]?.candidate;c(p)}}else for(;r.length<Math.min(3,vi);){let u=i.filter(d=>!r.some(m=>m.symbol===d.symbol)).sort((d,m)=>m.matchedTerms.filter(p=>!s.has(p)).length-d.matchedTerms.filter(p=>!s.has(p)).length||Xe(d,m))[0];if(!u||u.matchedTerms.every(d=>s.has(d)))break;c(u)}for(;r.length>=2&&r.length<vi;){let u=new Set(r.map(m=>m.symbol)),d=[...n.values()].filter(m=>!u.has(m.symbol)&&(o.get(m.symbol)??0)>0&&t.some(p=>u.has(p.fromSymbol)&&p.toSymbol===m.symbol)).sort((m,p)=>p.identityMatchedTerms.length-m.identityMatchedTerms.length||p.symbolMatchedTerms.length-m.symbolMatchedTerms.length||p.matchedTerms.length-m.matchedTerms.length||(o.get(p.symbol)??0)-(o.get(m.symbol)??0)||Xe(m,p))[0];if(!d)break;c(d)}if(r.length<2){let u=r[0],d=u?i.filter(m=>m.symbol!==u.symbol).map(m=>({root:m,path:DD(m.symbol,u.symbol,t)})).filter(m=>m.path!==null).sort((m,p)=>+(p.root.file!==u.file)-+(m.root.file!==u.file)||m.path.length-p.path.length||Xe(m.root,p.root))[0]?.root:void 0;c(d)}return r}function PD(e,t,n,i){let r=new Map;for(let a of n){let c=r.get(a.fromSymbol)??new Set;c.add(a.toSymbol),r.set(a.fromSymbol,c);let l=r.get(a.toSymbol)??new Set;l.add(a.fromSymbol),r.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 r.get(l)??[]){let d=i.get(u),m=u===t?1:!d||d.matchedTerms.length===0?9:d.symbolPhraseLength>=2?1:d.identityMatchedTerms.length>=2?2:4,p=c+m;p>=(s.get(u)??Number.POSITIVE_INFINITY)||(s.set(u,p),o.push({path:[...a,u],cost:p}))}}return null}function DD(e,t,n){let i=new Map;for(let s of n){let a=i.get(s.fromSymbol)??[];a.push(s.toSymbol),i.set(s.fromSymbol,a)}let r=[[e]],o=new Set([e]);for(;r.length>0;){let s=r.shift(),a=s.at(-1);if(a===t)return s;for(let c of i.get(a)??[])o.has(c)||(o.add(c),r.push([...s,c]))}return null}function Xe(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||nr(e.kind)-nr(t.kind)||Gt(e.fileKind)-Gt(t.fileKind)||e.file.localeCompare(t.file)||e.line-t.line}function zl(e,t){return t.symbolPhraseLength-e.symbolPhraseLength||t.symbolMatchedTerms.length-e.symbolMatchedTerms.length||nr(e.kind)-nr(t.kind)||t.symbolRarity-e.symbolRarity||Xe(e,t)}function TD(e,t){return t.flatMap(n=>{let i=e.filter(s=>s.matchedTerms.includes(n)).sort((s,a)=>AD(s,a,n)),r=[],o=new Set;for(let s of i)if(!o.has(s.file)&&(r.push(s),o.add(s.file),r.length>=Sh))return r;for(let s of i)if(!r.some(a=>a.symbol===s.symbol)&&(r.push(s),r.length>=Sh))break;return r})}function MD(e,t,n){let i=new Set(t),r=new Map;for(let o of e){if(o.kind!=="callable")continue;let s=o.file.slice(o.file.lastIndexOf("/")+1).replace(/\.[^.]+$/u,"");if(![...ht(s)].some(c=>i.has(c)))continue;let a=r.get(o.file)??[];a.push(o),r.set(o.file,a)}return[...r.entries()].map(([o,s])=>{let a=o.slice(o.lastIndexOf("/")+1).replace(/\.[^.]+$/u,""),c=[...ht(a)].filter(l=>i.has(l));return{file:o,fileCandidates:s,sharedFrequency:Math.min(...c.map(l=>n.get(l)??Number.MAX_SAFE_INTEGER))}}).sort((o,s)=>Gt(o.fileCandidates[0].fileKind)-Gt(s.fileCandidates[0].fileKind)||o.sharedFrequency-s.sharedFrequency||o.file.localeCompare(s.file)).flatMap(({fileCandidates:o})=>[...o].sort(Xe).slice(0,YP)).slice(0,JP)}function AD(e,t,n){return Ph(e,n)-Ph(t,n)||Gt(e.fileKind)-Gt(t.fileKind)||t.symbolPhraseLength-e.symbolPhraseLength||nr(e.kind)-nr(t.kind)||Xe(e,t)}function Ph(e,t){let n=e.matches.find(i=>i.term===t)?.sources??[];return Math.min(...n.map(Gl),Number.MAX_SAFE_INTEGER)}function tr(e){return[...new Map(e.map(t=>[t.symbol,t])).values()]}function Ci(e,t,n){let i=new Set(e.roots.flatMap(o=>o.symbolMatchedTerms)),r=new Set(t.roots.flatMap(o=>o.symbolMatchedTerms));return(t.queryPathMatches?.length??0)-(e.queryPathMatches?.length??0)||Ah(e.kind)-Ah(t.kind)||Th(e)-Th(t)||Mh(e)-Mh(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)||Dh(t,n)-Dh(e,n)||t.matchedTerms.length-e.matchedTerms.length||Math.max(...t.roots.map(o=>o.symbolPhraseLength))-Math.max(...e.roots.map(o=>o.symbolPhraseLength))||r.size-i.size||Xe(e.roots[0],t.roots[0])||t.roots.length-e.roots.length||e.relationCount-t.relationCount||e.id.localeCompare(t.id)}function Dh(e,t){return e.matchedTerms.reduce((n,i)=>n+1/Math.max(1,t.get(i)??1),0)}function FD(e){return[...new Set(e.roots.flatMap(t=>t.queryPathMatches??[]))].sort()}function Th(e){let t=e.keyAnchors.length>0?e.keyAnchors:e.roots;return Math.max(...t.map(n=>Gt(n.fileKind)))}function Mh(e){return e.kind==="parallel-paths"?2-(e.parallelConnectedSides??0):e.kind!=="connected-flow"||e.relationCount>0?0:1}function ND(e,t,n){let i=e.slice(0,t);if(t<2||i.some(o=>o.kind==="shared-callee-owners"))return i;let r=e.filter(o=>o.kind==="shared-callee-owners");for(let o of i){if(o.kind==="shared-callee-owners"||o.kind==="parallel-paths")continue;let s=new Set(eo(o)),a=r.map(l=>({group:l,overlap:kD(l,s)})).filter(({overlap:l})=>l>0).sort(({group:l,overlap:u},{group:d,overlap:m})=>m-u||Ci(l,d,n))[0]?.group;if(!a)continue;let c=i.length-1;for(;c>=0&&i[c]===o;)c-=1;return c<0?i:(i[c]=a,[...i].sort((l,u)=>Ci(l,u,n)))}return i}function kD(e,t){return eo(e).filter(n=>t.has(n)).length}function Ah(e){switch(e){case"cross-boundary-flow":return 0;case"parallel-paths":case"connected-flow":return 1;case"shared-callee-owners":return 2}}function an(e,t){return e.depth-t.depth||Wn(t.strength)-Wn(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 _D(e,t){return Wn(Kl(t.source))-Wn(Kl(e.source))||(e.callsiteLine??Number.MAX_SAFE_INTEGER)-(t.callsiteLine??Number.MAX_SAFE_INTEGER)||e.symbol.localeCompare(t.symbol)}function Pn(e){let t=new Map;for(let n of e){let i=`${n.fromSymbol}\0${n.toSymbol}`,r=t.get(i);(!r||an(n,r)<0)&&t.set(i,n)}return[...t.values()]}function la(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 OD(e){let t=e.match(/[\p{L}\d_.-]+(?:\/[\p{L}\d_.-]+)+/gu)??[];return[...new Set(t.map(n=>n.replace(/[.;:!?]+$/gu,"").toLocaleLowerCase()))]}function BD(e,t){let n=e.replace(/\\/gu,"/").toLocaleLowerCase();return t.filter(i=>{let r=n.indexOf(i);if(r<0)return!1;let o=r===0?"/":n[r-1],s=n[r+i.length];return o==="/"&&(s===void 0||s==="/")})}function $D(e,t){let n=la(e).map(Wl),i=0;for(let r=0;r<n.length;r+=1)for(let o=0;o<t.length;o+=1){let s=0;for(;r+s<n.length&&o+s<t.length&&n[r+s]===t[o+s];)s+=1;i=Math.max(i,s)}return i}function ht(e){return new Set(la(e).flatMap(Bh).filter(t=>t.length>=3))}function Bh(e){let t=Wl(e);return t.length>4&&t.endsWith("e")?[t,t.slice(0,-1)]:[t]}function Wl(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")?Fh(t.slice(0,-2)):t.length>5&&t.endsWith("ing")?Fh(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 Fh(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 Nh(e){if(e.length===0)return[];let t=e.split(`
67
- `);return e.endsWith(`
68
- `)&&t.pop(),t}function jD(e,t){return Gl(e)-Gl(t)}function Gl(e){switch(e){case"symbol":return 0;case"path":return 1;case"documentation":return 2;case"source":return 3}}function nr(e){return e==="callable"?0:e==="type"?1:2}function Gt(e){switch(e){case"entry":case"source":case"worker":return 0;case"barrel":return 1;case"test":return 2}}function Kl(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function Wn(e){return e==="exact"?2:1}function $h(e,t){return e.file.localeCompare(t.file)||e.line-t.line}function Zr(e){return`${e.file}:${e.line+1}`}function to(e,t=[],n=[]){let i=e.map(s=>`--symbol ${ca(`${s.file}:${s.line+1}-${s.endLine+1}`)}`),r=new Set(e.map(s=>s.symbol)),o=e.flatMap(s=>(s.sourceCharacters??0)>jl?HD(s,t,n,r).map(a=>`--focus-at ${ca(`${a.file}:${a.line+1}`)}`):[]);return`codebaseiq system-map ${[...i,...o,"--relation call","--relation runtime-boundary"].join(" ")}`}function HD(e,t,n,i){let r=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:i.has(l.toSymbol),overlap:new Set(la(UD(l.toLabel)).flatMap(Bh).filter(u=>r.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||Wn(u.strength)-Wn(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 UD(e){return e.slice(Math.max(e.lastIndexOf(":"),e.lastIndexOf("."))+1)}function zD(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 i=[...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)||$h(o,s)),r=[];for(let o of i)if(!r.some(s=>s.file===o.file&&Math.abs(s.line-o.line)<8)&&(r.push(o),r.length>=3))break;return r.map(o=>({file:o.file,line:o.line,matchedTerms:[...o.matchedTerms].sort()}))}function GD(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(to(e.slice(i,i+t)));return n}function ca(e){return`'${e.replaceAll("'",`'"'"'`)}'`}import{createHash as ly}from"crypto";function ua(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 ir(e){let t=new Set,n=[];for(let i of e){let r=`${i.symbol}|${i.file}`;t.has(r)||(t.add(r),n.push(i))}return n}function no(e,t,n={}){let i=pe(e,t);if(!i)return null;let r=n.semantic!==!1,o=Gc(e,i,{semantic:r,semanticEvidence:fe}),s=o.rows.filter(d=>ke(d.symbol)).slice(0,50),a=mi(e,i,{limit:50,additive:!0,callableOnly:!0,semantic:r,semanticEvidence:fe}),c=ir(a.rows),l=s.map(d=>({symbol:d.symbol,shortName:k(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:k(d.symbol),file:d.file,relationship:d.source==="scip-chunk"?"chunk-candidate":"resolved-call",evidenceStrength:d.source==="scip-chunk"?"candidate":"exact",evidenceSource:d.source}));return{symbol:i.symbol,shortName:k(i.symbol),callers:l.map(({symbol:d,shortName:m,file:p})=>({symbol:d,shortName:m,file:p})),callees:u.map(({symbol:d,shortName:m,file:p})=>({symbol:d,shortName:m,file:p})),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:r,incoming:jh(r,o),outgoing:jh(r,a)}}}}function jh(e,t){return e?t.semanticIncomplete&&t.semanticUnavailable?"incomplete-and-unavailable":t.semanticIncomplete?"incomplete":t.semanticUnavailable?"unavailable":"complete":"disabled"}function rr(e,t,n){if(n.length===0)return[];let i=new Set(n),r=Oe(e),o=new Set;if(t==="forward")for(let s of i)for(let a of r.get(s)??[])i.has(a)||o.add(a);else for(let[s,a]of r)if(!i.has(s))for(let c of i)a.has(c)&&o.add(s);return[...o].sort()}function io(e,t){let n=ct(e,t);return n?rr(e,"forward",[n]).filter(r=>!e.isIgnored(r)).map(r=>({relativePath:r,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):[]}function ro(e,t){let n=ct(e,t);return n?rr(e,"reverse",[n]).filter(r=>!e.isIgnored(r)).map(r=>({relativePath:r,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):[]}function Vl(e,t,n={}){let i=da(e,t,n);return{definitions:i.definitions,referencedBy:i.referencedBy}}function da(e,t,n={}){let i=pe(e,t);if(!i)return{definitions:[],referencedBy:[],referenceEvidence:[],claimSupport:null};let r=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",i.symbolId),o=Gi(r?.documentation??null),s=e.isIgnored(i.relativePath)?[]:[{relativePath:i.relativePath,startLine:i.startLine,endLine:i.endLine,signature:YD(o,r?.display_name??null,i.symbol),source:JD(e,i.relativePath,i.startLine,i.endLine)}],a=n.referenceContext??2,c=hp(e,i,{semantic:n.semantic,semanticEvidence:fe}).map(u=>{let d=ff(e,u.file,u.line,a,re(i.symbol));return{relativePath:u.file,line:u.line,enclosingSymbol:u.enclosingSymbol,enclosingShort:u.enclosingSymbol?k(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(KD);return{definitions:s,referencedBy:l,referenceEvidence:c.map(u=>({relativePath:u.relativePath,line:u.line,provenance:u.provenance,sourceKind:u.sourceKind})),claimSupport:qD(c)}}function KD(e){return{relativePath:e.relativePath,line:e.line,enclosingSymbol:e.enclosingSymbol,enclosingShort:e.enclosingShort,sourceStartLine:e.sourceStartLine,sourceEndLine:e.sourceEndLine,source:e.source}}function qD(e){let t="resolved source-attributed or SCIP-indexed references to this exact symbol",n=["Dynamic dispatch, reflection, generated calls, and unindexed source are outside this scope."],i=e.filter(o=>o.sourceKind!=="complete-call-expression"&&o.sourceKind!=="non-call-reference"),r="direct, statically visible call expressions among the resolved reference sites";return{referenceAbsence:{status:"eligible",scope:t,limitations:n},callsitePredicates:i.length===0?{status:"eligible",scope:r,limitations:n}:{status:"ineligible",scope:r,reason:`${i.length} reference site(s) lack one unambiguous complete call expression.`,followup:WD(i)}}}function WD(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 ${VD(n)}`).join(" ")} --view behavior`}function VD(e){return`'${e.replaceAll("'","'\\''")}'`}function JD(e,t,n,i){let r=se(e,t);if(!r)return null;let s=r.split(`
69
- `).slice(n,i+1).join(`
70
- `).trimEnd();return s.length>0?s:null}function YD(e,t,n){let i=zi(e);if(i&&!XD(i))return i;let r=(t??"").trim();return r?ke(n)&&!r.endsWith("()")?`${r}()`:r:k(n)}function XD(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function Jl(e,t,n={}){let i=zh(e,t,n);if(i.kind!=="matched")return i;let{referenceEvidence:r,claimSupport:o,...s}=i;return s}function zh(e,t,n={}){let i=rt(e,t);if(!i.match)return{kind:"missing",query:t};if(i.total>1)return{kind:"ambiguous",query:t,total:i.total,candidates:[{symbol:i.match.symbol,shortName:k(i.match.symbol),relativePath:i.match.relativePath,startLine:i.match.startLine},...i.candidates]};let r=i.match,o=ZD(n.parts),s=o.includes("definition")||o.includes("references")?da(e,r.symbol,{semantic:n.semantic,referenceContext:n.referenceContext}):{definitions:[],referencedBy:[],referenceEvidence:[],claimSupport:null},a=o.includes("callers")||o.includes("callees")?no(e,r.symbol,{semantic:n.semantic}):null,c=n.relatedSourceLines??80;return{kind:"matched",query:t,symbol:r.symbol,shortName:k(r.symbol),file:r.relativePath,parts:o,definition:o.includes("definition")?bf(e,r.symbol):null,referenceWindows:o.includes("references")?QD(e,s.referencedBy):[],callers:o.includes("callers")?Uh(e,a?.callers??[],c):[],callees:o.includes("callees")?Uh(e,a?.callees??[],c):[],dependencies:o.includes("dependencies")?io(e,r.relativePath):[],consumers:o.includes("consumers")?ro(e,r.relativePath):[],referenceEvidence:s.referenceEvidence,claimSupport:s.claimSupport}}function QD(e,t){let n=t.filter(r=>r.sourceStartLine!==null&&r.sourceEndLine!==null&&r.source!==null).sort((r,o)=>r.relativePath.localeCompare(o.relativePath)||r.sourceStartLine-o.sourceStartLine||r.line-o.line),i=[];for(let r of n){let o=i[i.length-1];if(o&&o.relativePath===r.relativePath&&r.sourceStartLine<=o.endLine+1){o.endLine=Math.max(o.endLine,r.sourceEndLine),o.references.push(Hh(r)),o.source=ie(e,o.relativePath).slice(o.startLine,o.endLine+1).join(`
71
- `);continue}i.push({relativePath:r.relativePath,startLine:r.sourceStartLine,endLine:r.sourceEndLine,source:r.source,references:[Hh(r)]})}return i}function Hh(e){return{line:e.line,enclosingSymbol:e.enclosingSymbol,enclosingShort:e.enclosingShort}}function ZD(e){let t=e&&e.length>0?e:["definition","references"];return[...new Set(t)]}function Uh(e,t,n){let i=[],r=new Set;for(let o of t){if(r.has(o.symbol))continue;r.add(o.symbol);let s=(o.file?J(e,o.file).find(c=>c.symbol===o.symbol):void 0)??rt(e,o.symbol).match;if(!s)continue;let a=gf(e,s.relativePath,s.startLine,s.endLine,n);a&&i.push({...a,symbol:o.symbol,shortName:o.shortName,omittedLines:Math.max(0,s.endLine-a.endLine)})}return i}var Vh=6;function Gh(e,t,n){return`${e}\0${t}\0${n??t}`}function Jh(e,t,n,i={}){let r=i.limit??Vh;if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`next-anchor limit must be a positive safe integer; received ${r}`);let o=i.sourceAllowed??(()=>!0),s=new Map(t.nodes.map(C=>[C.id,C])),a=new Set(n.steps.map(C=>C.nodeId)),c=new Set(n.steps.flatMap(C=>{let L=Ql(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(Gh(L.file,L.line,L.endLine));let u=C=>C.symbol!==null&&c.has(C.symbol)||l.has(Gh(C.file,C.line,C.endLine)),d=new Map(n.steps.flatMap(C=>{if(!C.location)return[];let L=Ql(s.get(C.nodeId));if(!L)return[];let I=J(e,C.location.file).find(x=>x.symbol===L);return I?[[C.id,I]]:[]})),m=new U(e).calleeMap([...d.values()],{additive:!1,semantic:!0}),p=[],f=new Set,g=new Set,h=0,b=0,v=0,y=0,E=0,w=0,S=0,R=0;for(let C of n.steps){if(!C.location||!C.behavior)continue;let L=t.edges.filter(N=>["call","runtime-boundary"].includes(N.kind)&&(N.fromNodeId===C.nodeId||N.toNodeId===C.nodeId)&&N.disposition!=="excluded"&&N.disposition!=="unsupported");for(let N of L){let K=N.toNodeId===C.nodeId,te=K?N.fromNodeId:N.toNodeId;if(a.has(te))continue;let me=s.get(te);if(!me?.location||!o(me.location.file))continue;let ge=N.kind==="call"?eu(e,me):Zl(me);if(!ge||u(ge))continue;let le=tu(N,me.location.file)??me.location,be=ie(e,le.file)[le.line]?.trim(),M=K?"upstream":"downstream",Q=N.kind==="runtime-boundary"?K?"runtime-producer":"runtime-consumer":K?"caller":"callee",X=["call"],Se=Yl(N.evidence),tt=oo(me);p.push({anchor:{id:Vn(C.id,le.line,me.id),status:Se,source:"graph-relation",direction:M,causalRole:Q,relationKind:N.kind,fromStepId:C.id,fromLabel:C.label,callsite:{file:le.file,line:le.line,endLine:le.endLine??le.line,text:be||`${me.label} \u2192 ${C.label}`,signals:X,calleeLeaf:tt},alternatives:[ge],alternativeCount:1,evidence:N.evidence}}),K&&(w+=1),N.kind==="runtime-boundary"&&(R+=1)}let I=t.edges.filter(N=>N.kind==="reference"&&N.fromNodeId===C.nodeId&&N.disposition!=="excluded"&&N.disposition!=="unsupported"&&!a.has(N.toNodeId));for(let N of I){let K=s.get(N.toNodeId);if(!K?.location||!o(K.location.file))continue;let te=eu(e,K);if(!te||u(te))continue;let me=oo(K),ge=tu(N,C.location.file)?.line,le=C.behavior.lines.find(X=>(ge===void 0||ge>=X.line&&ge<=X.endLine)&&X.text.includes(me));if(!le)continue;let be=Xh(le.signals),M=be==="result-callback",Q=Yl(N.evidence);p.push({anchor:{id:Vn(C.id,le.line,K.id),status:Q,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:me},alternatives:[te],alternativeCount:1,evidence:N.evidence}}),M&&(S+=1)}let x=In(e,C.location.file,C.location.line,C.location.endLine??C.location.line),D=ie(e,C.location.file),_=Cn(e,C.location.file,C.location.line,C.location.endLine??C.location.line);for(let N of x.targets){if(!o(N.definition.relativePath))continue;let K=Ri(C.location.file,N.sourceLine,N.calleeLeaf);if(f.has(K))continue;f.add(K);let te=Xl(_.get(N.sourceLine)),me={symbol:N.definition.symbol,label:N.definition.leaf,file:N.definition.relativePath,line:N.definition.startLine,endLine:N.definition.endLine};u(me)||p.push({anchor:{id:Vn(C.id,N.sourceLine,N.definition.symbol),status:"exact",source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:C.id,fromLabel:C.label,callsite:{file:C.location.file,line:N.sourceLine,endLine:N.sourceLine,text:D[N.sourceLine]?.trim()||`${N.calleeLeaf}()`,signals:te,calleeLeaf:N.calleeLeaf},alternatives:[me],alternativeCount:1,evidence:[{method:"scip-occurrence-callsite",strength:"exact",identity:N.definition.symbol,location:{file:C.location.file,line:N.sourceLine}}]}})}let P=C.behavior.lines.filter(N=>N.signals.includes("call"));if(P.length===0)continue;h+=1;let T=(ee(e,C.location.file)?.callSites??[]).filter(N=>P.some(K=>N.line>=K.line&&N.line<=K.endLine));b+=T.length;let F=t.edges.filter(N=>N.kind==="call"&&N.fromNodeId===C.nodeId&&N.disposition!=="excluded"&&N.disposition!=="unsupported"),W=new Map;for(let N of F){let K=s.get(N.toNodeId);if(!K)continue;let te=oo(K);W.set(te,(W.get(te)??0)+1)}let ce=d.get(C.id),q=tT(e,ce?m.get(ce.symbolId)??[]:[]),Y=nT(q);for(let N of q){if(!o(N.alternative.file)||u(N.alternative))continue;let K=ma(N.alternative.label),te=qh(T,P,K,N.row.callsiteLine,Y.get(K)===1);if(!te)continue;let me=so(P,te.line,K);if(!me)continue;let ge=Ri(C.location.file,te.line,K);if(f.has(ge))continue;f.add(ge);let le=ty(N.row.source);p.push({anchor:{id:Vn(C.id,te.line,N.alternative.symbol??N.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:me.line,endLine:me.endLine,text:me.text,signals:me.signals,calleeLeaf:K},alternatives:[N.alternative],alternativeCount:1,evidence:[{method:N.row.source,strength:le,identity:N.row.symbol,location:{file:C.location.file,line:te.line}}]}})}for(let N of F){if(a.has(N.toNodeId))continue;let K=s.get(N.toNodeId);if(!K?.location||!o(K.location.file))continue;let te=oo(K),me=N.evidence.find(X=>{let Se=X.location;return Se!==null&&Se.file===C.location?.file&&Se.line>=0})?.location?.line,ge=qh(T,P,te,me,W.get(te)===1);if(!ge)continue;let le=so(P,ge.line,te);if(!le)continue;let be=Ri(C.location.file,ge.line,te);if(f.has(be))continue;f.add(be);let M=Zl(K);if(!M||u(M))continue;let Q=Yl(N.evidence);p.push({anchor:{id:Vn(C.id,ge.line,K.id),status:Q,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:te},alternatives:[M],alternativeCount:1,evidence:N.evidence}})}for(let N of T){let K=Ri(C.location.file,N.line,N.calleeLeaf);if(f.has(K))continue;let te=so(P,N.line,N.calleeLeaf);if(!te)continue;let me=Qt(C.location.file,Zt(e).get(N.calleeLeaf)??[]).flatMap(M=>J(e,M.file).filter(Q=>Q.symbol===M.symbol&&Q.isFunctionLike)).filter(M=>o(M.relativePath)&&!u({symbol:M.symbol,label:M.leaf,file:M.relativePath,line:M.startLine,endLine:M.endLine})),ge=fa(me.map(M=>({symbol:M.symbol,label:M.leaf??N.calleeLeaf,file:M.relativePath,line:M.startLine,endLine:M.endLine})));if(ge.length===0){E+=1;continue}let le=`${C.id}\0${N.line}\0${N.calleeLeaf}`;if(g.has(le))continue;g.add(le);let be=ge.length>1;be?y+=1:v+=1,p.push({anchor:{id:Vn(C.id,N.line,N.calleeLeaf),status:be?"ambiguous":"candidate",source:"leaf-identity-candidate",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:C.id,fromLabel:C.label,callsite:{file:C.location.file,line:te.line,endLine:te.endLine,text:te.text,signals:te.signals,calleeLeaf:N.calleeLeaf},alternatives:ge.slice(0,3),alternativeCount:ge.length,evidence:[]}})}}return Zh(e,p,n.steps,r,{scannedBehaviorSteps:h,visibleCallsites:b,graphEvidencedCallsites:f.size,identityCandidateCallsites:v,ambiguousCallsites:y,unresolvedCallsites:E,upstreamCandidates:w,resultCandidates:S,runtimeCandidates:R},i.selectionTerms)}function Yh(e,t,n){let i=new Map(t.nodes.map(r=>[r.id,r]));for(let r of n.steps)if(!(!r.behavior||!r.location))for(let o of t.edges){if(o.kind!=="reference"||o.fromNodeId!==r.nodeId||o.disposition==="excluded"||o.disposition==="unsupported")continue;let s=i.get(o.toNodeId);if(!s?.location||!eu(e,s))continue;let a=oo(s),c=tu(o,r.location.file)?.line,l=r.behavior.lines.find(u=>(c===void 0||c>=u.line&&c<=u.endLine)&&u.text.includes(a));!l||Xh(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 Xh(e){return e.includes("call")&&e.some(t=>["return","mutation","shape","spread","binding"].includes(t))?"result-callback":"callable-reference"}function Qh(e,t,n={}){let i=n.limit??Vh;if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`next-anchor limit must be a positive safe integer; received ${i}`);let r=n.sourceAllowed??(()=>!0),o=[],s=t.map((p,f)=>({id:p.id,nodeId:p.id,order:f,role:"anchor",kind:"source-construct",label:p.label,location:{file:p.file,line:p.startLine,endLine:p.endLine},behavior:null})),a=t.map(p=>({file:p.file,startLine:p.startLine,endLine:p.endLine})),c=0,l=0,u=0,d=0,m=0;for(let p of t){let f=ie(e,p.file),h=(ee(e,p.file)?.callSites??[]).filter(S=>S.line>=p.startLine&&S.line<=p.endLine);c+=h.length;let b=Cn(e,p.file,p.startLine,p.endLine),v=In(e,p.file,p.startLine,p.endLine),y=new Set;for(let S of v.targets){if(!r(S.definition.relativePath)||a.some(I=>I.file===S.definition.relativePath&&I.startLine<=S.definition.startLine&&I.endLine>=S.definition.endLine))continue;let R=Ri(p.file,S.sourceLine,S.calleeLeaf);y.add(R);let C=Xl(b.get(S.sourceLine)),L={symbol:S.definition.symbol,label:S.definition.leaf,file:S.definition.relativePath,line:S.definition.startLine,endLine:S.definition.endLine};o.push({anchor:{id:Vn(p.id,S.sourceLine,S.definition.symbol),status:"exact",source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:p.id,fromLabel:p.label,callsite:{file:p.file,line:S.sourceLine,endLine:S.sourceLine,text:f[S.sourceLine]?.trim()||`${S.calleeLeaf}()`,signals:C,calleeLeaf:S.calleeLeaf},alternatives:[L],alternativeCount:1,evidence:[{method:"scip-occurrence-callsite",strength:"exact",identity:S.definition.symbol,location:{file:p.file,line:S.sourceLine}}]}})}l+=v.resolvedCallsites;let E=Kn(e,p.file,{ranges:[{startLine:p.startLine,endLine:p.endLine}]}),w=new Map;for(let S of E.targets){let R=h.find(I=>I.line===S.line)?.calleeLeaf??S.calleeLeaf,C=Ri(p.file,S.line,R),L=w.get(C)??[];L.push(S),w.set(C,L)}for(let[S,R]of w){if(y.has(S))continue;y.add(S);let C=R.filter(P=>r(P.targetFile)&&!a.some(T=>T.file===P.targetFile&&T.startLine<=P.targetStartLine&&T.endLine>=P.targetEndLine));if(C.length===0)continue;let L=C[0],I=h.find(P=>P.line===L.line)?.calleeLeaf??L.calleeLeaf,x=Xl(b.get(L.line)),D=fa(C.map(P=>({symbol:P.targetSymbol??null,label:P.calleeLeaf,file:P.targetFile,line:P.targetStartLine,endLine:P.targetEndLine}))),_=C.some(P=>(P.resolutionAlternativeCount??0)>1)?"candidate":C.every(P=>P.strength==="exact")?"exact":"derived";o.push({anchor:{id:Vn(p.id,L.line,D.map(P=>`${P.file}:${P.line}`).join("|")),status:D.length>1?"ambiguous":_,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:p.id,fromLabel:p.label,callsite:{file:p.file,line:L.line,endLine:L.line,text:f[L.line]?.trim()||`${L.calleeLeaf}()`,signals:x,calleeLeaf:I},alternatives:D.slice(0,3),alternativeCount:D.length,evidence:C.map(P=>({method:P.resolution==="constructed-member-receiver"?"ast-constructed-member-callsite":P.resolution==="factory-callback-member"?"ast-factory-callback-callsite":P.resolution==="imported-service-object-member"?"ast-service-member-callsite":"ast-import-member-callsite",strength:_,identity:P.targetSymbol??`${P.targetFile}:${P.targetStartLine}-${P.targetEndLine}`,location:{file:p.file,line:L.line}}))}})}l+=w.size;for(let S of h){let R=Ri(p.file,S.line,S.calleeLeaf);y.has(R)||(m+=1)}}return Zh(e,o,s,i,{scannedBehaviorSteps:t.length,visibleCallsites:c,graphEvidencedCallsites:l,identityCandidateCallsites:u,ambiguousCallsites:d,unresolvedCallsites:m,upstreamCandidates:0,resultCandidates:0,runtimeCandidates:0})}function Zh(e,t,n,i,r,o=[]){let s=iT(t).sort(ey),a=s.filter(f=>eT(e,f)).slice(0,i),c=new Set(a.map(f=>f.anchor.id)),l=s.filter(f=>!c.has(f.anchor.id)),u=a.map(f=>f.anchor),d=l.map(f=>f.anchor),m=fa(u.flatMap(f=>f.alternativeCount===1?f.alternatives:[])),p=fa(d.flatMap(f=>f.alternativeCount===1?f.alternatives:[]));return{anchors:u,withheldAnchors:d,candidateAnchors:s.length,omittedAnchors:Math.max(0,s.length-u.length),...r,inspectCommand:m.length===0?null:`codebaseiq inspect ${m.map(Wh).join(" ")} --view behavior`,remainingInspectCommands:oT(p,8).map(f=>`codebaseiq inspect ${f.map(Wh).join(" ")} --view behavior`)}}function ey(e,t){let n=e.anchor.alternatives[0],i=t.anchor.alternatives[0];return pa(e.anchor.status)-pa(t.anchor.status)||(e.anchor.direction??"").localeCompare(t.anchor.direction??"")||(e.anchor.relationKind??"").localeCompare(t.anchor.relationKind??"")||(e.anchor.causalRole??"").localeCompare(t.anchor.causalRole??"")||e.anchor.fromStepId.localeCompare(t.anchor.fromStepId)||e.anchor.callsite.file.localeCompare(t.anchor.callsite.file)||e.anchor.callsite.line-t.anchor.callsite.line||(n?.file??"").localeCompare(i?.file??"")||(n?.line??0)-(i?.line??0)||e.anchor.id.localeCompare(t.anchor.id)}function eT(e,t){if(t.anchor.alternativeCount!==1)return!0;let n=t.anchor.alternatives[0],i=n.endLine??n.line;return ie(e,n.file).slice(n.line,i+1).join(`
72
- `).length<=2e4}function Xl(e){return e?.includes("call")?[...e]:["call",...e??[]]}function tT(e,t){let n=new Map;for(let i of t){let r=J(e,i.file).find(a=>a.symbol===i.symbol&&a.isFunctionLike);if(!r)continue;let o={symbol:r.symbol,label:r.leaf,file:r.relativePath,line:r.startLine,endLine:r.endLine},s=n.get(r.symbol);!s||Kh(i.source)>Kh(s.row.source)?n.set(r.symbol,{row:{...i,...i.callsiteLine===void 0&&s?.row.callsiteLine!==void 0?{callsiteLine:s.row.callsiteLine}:{}},alternative:o}):s.row.callsiteLine===void 0&&i.callsiteLine!==void 0&&n.set(r.symbol,{...s,row:{...s.row,callsiteLine:i.callsiteLine}})}return[...n.values()]}function nT(e){let t=new Map;for(let n of e){let i=ma(n.alternative.label);t.set(i,(t.get(i)??0)+1)}return t}function ty(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function Kh(e){return ty(e)==="exact"?2:1}function so(e,t,n){return e.find(i=>t>=i.line&&t<=i.endLine&&i.text.includes(n))??e.find(i=>t>=i.line&&t<=i.endLine)??null}function qh(e,t,n,i,r){if(i!==void 0)return e.find(s=>s.line===i&&s.calleeLeaf===n&&so(t,s.line,n)!==null)??null;let o=e.filter(s=>s.calleeLeaf===n&&so(t,s.line,s.calleeLeaf)!==null);return r&&o.length===1?o[0]:null}function oo(e){let t=e.attributes.leaf;if(typeof t=="string"&&t.length>0)return ma(t);let n=e.label.slice(e.label.lastIndexOf(":")+1);return ma(n)}function ma(e){return e.replace(/\(\)$/u,"").replace(/^#/u,"")}function Ql(e){if(e?.kind!=="symbol"||!e.id.startsWith("symbol:"))return null;try{return decodeURIComponent(e.id.slice(7))}catch{return null}}function Zl(e){return e.location?{symbol:Ql(e),label:e.label,file:e.location.file,line:e.location.line,endLine:e.location.endLine??null}:null}function eu(e,t){let n=Zl(t);return n?.symbol&&J(e,n.file).some(r=>r.symbol===n.symbol&&r.isFunctionLike)?n:null}function tu(e,t){return e.evidence.find(n=>n.location?.file===t)?.location??e.evidence.find(n=>n.location!==null)?.location??null}function Yl(e){let t={exact:5,derived:4,mixed:3,candidate:2,unknown:1};return e.reduce((n,i)=>t[i.strength]>t[n]?i.strength:n,"unknown")}function iT(e){let t=new Map;for(let n of e){let r=n.anchor.alternatives[0]?.symbol??`${n.anchor.callsite.file}:${n.anchor.callsite.line}:${n.anchor.callsite.calleeLeaf}`,o=t.get(r);(!o||rT(n,o)<0)&&t.set(r,n)}return[...t.values()]}function rT(e,t){return pa(e.anchor.status)-pa(t.anchor.status)||e.anchor.alternativeCount-t.anchor.alternativeCount||ey(e,t)}function pa(e){return{exact:0,derived:1,mixed:2,candidate:3,unknown:4,ambiguous:5}[e]}function fa(e){let t=new Map;for(let n of e)t.set(n.symbol??`${n.file}:${n.line}`,n);return[...t.values()].sort((n,i)=>n.file.localeCompare(i.file)||n.line-i.line||n.label.localeCompare(i.label))}function Wh(e){return`--at ${sT(`${e.file}:${e.line+1}`)}`}function oT(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}function sT(e){return`'${e.replaceAll("'","'\\''")}'`}function Ri(e,t,n){return`${e}\0${t}\0${n}`}function Vn(e,t,n){return["next-anchor",e,String(t),n].map(encodeURIComponent).join(":")}var uy=6,aT=12,cT=48,lT=2e4,ny=12,Ei=Number.MAX_SAFE_INTEGER,uT=["definition","callers","callees"],su={search:12,"exact-source":24,definition:24,caller:8,callee:8,"production-reference":6,"test-reference":2,dependency:6,consumer:6};function dT(e,t){if(t.cursor)throw new Error("Inspect no longer accepts semantic packet cursors. Run the original inspect selectors again.");let n=pT(t),i=hT(e,n),r=i.candidates.sort((D,_)=>nu(D,_));n.view==="behavior"&&ST(e,r),vT(e,r),n.view==="behavior"&&yT(e,r);let o=Gg(r.map(D=>ru(D,n.view)),n.evidenceBudgets,(D,_)=>nu(D.candidate,_.candidate)),{selected:s,omitted:a}=Qs(o.selected,n.maxUnits,n.maxCharacters,(D,_)=>nu(D.candidate,_.candidate),n.view==="source"),c=s.map(D=>D.candidate),l=[...o.omitted,...a].map(D=>D.candidate),u=c.map(DT),d=Ls(c.map(D=>D.kind==="source"?D.bindingClosure:void 0),c.filter(D=>D.kind==="source").map(D=>({relativePath:D.relativePath,startLine:D.startLine,endLine:D.endLine}))),m=u.reduce((D,_)=>D+(_.kind==="source"?AT(_.source):0),0),p=u.reduce((D,_)=>D+(_.kind==="source"?_.source.length:0),0),f=u.reduce((D,_)=>D+py(_,n.view),0),g=u.filter(D=>D.kind==="source"&&(D.roles.includes("search")||D.roles.includes("location"))).map(TT),h=r.filter(D=>D.kind==="source"&&(D.roles.includes("search")||D.roles.includes("location"))).length,b=u.filter(D=>D.kind==="source"&&(D.roles.includes("search")||D.roles.includes("location"))).length,v=i.searches.map(D=>RT(D,r,c)),y=ET(l),E=i.locations.every(D=>D.matched)&&i.evidence.every(D=>D.kind==="matched")&&i.searches.every(D=>IT(D.textCoverage))&&l.every(D=>!D.roles.some(_=>_==="location"||_==="definition")),w=v.reduce((D,_)=>D+_.omittedMatches,0),S=l.length===0&&w===0,R=S?void 0:my(n,!0),C=CT(n,l),L=mT(S,E,l.length+w,C,v,R),I=r.filter(D=>n.view==="behavior"&&D.kind==="source"&&D.roles.some(_=>_==="location"||_==="definition"||_==="search")).map(D=>({id:`inspect:${D.relativePath}:${D.startLine}-${D.endLine}`,label:D.ownerShort??`${D.relativePath}:${D.startLine+1}`,file:D.relativePath,startLine:D.startLine,endLine:D.endLine})),x=I.length>0?Qh(e,I):void 0;return{searches:v,evidence:i.evidence,locations:i.locations,slices:g,candidateSlices:h,omittedSlices:h-b,maxSlices:h,maxTotalLines:m,units:u,candidateUnits:r.length,omittedUnits:l.length,maxUnits:n.maxUnits,maxCharacters:n.maxCharacters,returnedLines:m,returnedCharacters:p,returnedViewCharacters:f,view:n.view,omissionGroups:C,packetCoverage:{mode:S?"complete":"bounded",candidateUnits:r.length,returnedUnits:u.length,omittedUnits:l.length,omittedByRole:y,exactSelectorsComplete:E,maxUnits:n.maxUnits,maxCharacters:n.maxCharacters,channels:wT(r,c,n.evidenceBudgets,n.view),...R?{expansionCommand:R}:{}},stoppingSummary:L,...x&&x.candidateAnchors>0?{causalFrontier:x}:{},bindingClosure:d,continuation:null}}function mT(e,t,n,i,r,o){let s=lt([...i.map(a=>a.drillCommand),...r.flatMap(a=>a.exactFollowup?[a.exactFollowup]:[]),...o?[o]:[]]);return e&&t?{queryStatus:"selection-complete",status:"stop-ready",openEvidence:0,guidance:"All evidence requested by this inspect query was materialized.",drillCommands:[]}:t?{queryStatus:"frontier-accounted",status:"relevance-check-required",openEvidence:n,guidance:"Withheld evidence is accounted for by recoverable groups; drill the groups relevant to the current decision.",drillCommands:s}:{queryStatus:"coverage-incomplete",status:"exact-evidence-withheld",openEvidence:n,guidance:"A requested identity, exact source unit, or current-text coverage requirement is unresolved; drill before relying on it.",drillCommands:s}}function pT(e){let t=iu(e.searches),n=iu(e.symbols),i=iu(e.locations),r=t.length+n.length+i.length;if(r===0)throw new Error("inspect requires at least one --search, --symbol, or --at selector.");if(r>24)throw new RangeError(`inspect accepts at most ${24} selectors; received ${r}.`);let o=e.evidence??{};if(e.unitLines!==void 0&&Jn(e.unitLines,"unitLines"),e.totalLines!==void 0&&Jn(e.totalLines,"totalLines"),e.sliceLimit!==void 0&&Jn(e.sliceLimit,"sliceLimit"),e.maxCharacters!==void 0&&Jn(e.maxCharacters,"maxCharacters"),e.maxUnits!==void 0&&Jn(e.maxUnits,"maxUnits"),e.view!==void 0&&e.view!=="source"&&e.view!=="behavior")throw new Error(`Unknown inspect view: ${String(e.view)}. Use source or behavior.`);if(e.full&&(e.searchLimit!==void 0||e.maxUnits!==void 0||e.maxCharacters!==void 0||e.evidenceBudgets!==void 0))throw new Error("full inspect cannot be combined with searchLimit, maxUnits, maxCharacters, or evidenceBudgets.");let s=e.full??!1;return{searches:t,symbols:n,locations:i,...e.scope?.trim()?{scope:e.scope.trim()}:{},context:cy(e.context??uy,"context"),searchLimit:Jn(e.searchLimit??(s?Ei:aT),"searchLimit"),maxUnits:Jn(s?Ei:e.maxUnits??cT,"maxUnits"),maxCharacters:Jn(s?Ei:e.maxCharacters??lT,"maxCharacters"),evidenceBudgets:s?gT():fT(e.evidenceBudgets??su),view:e.view??"source",evidence:{...o.parts?{parts:[...o.parts]}:n.length>0?{parts:[...uT]}:{},...o.referenceContext!==void 0?{referenceContext:cy(o.referenceContext,"referenceContext")}:{},relatedSourceLines:o.relatedSourceLines??60,...o.semantic!==void 0?{semantic:o.semantic}:{}}}}function fT(e){let t={...su};for(let[n,i]of Object.entries(e)){if(!(n in t))throw new Error(`Unknown inspect evidence channel: ${n}.`);if(!Number.isSafeInteger(i)||(i??-1)<0)throw new RangeError(`Evidence budget ${n} must be a non-negative safe integer; received ${i}.`);t[n]=i}return t}function gT(){return Object.fromEntries(Object.keys(su).map(e=>[e,Ei]))}function hT(e,t){let n=[],i=0,r=t.searches.map(l=>{let u=Fl(e,l,{scope:t.scope,context:0,limit:t.searchLimit,ranking:"structural"});return{pattern:l,result:u,matches:u.matches}}),o=Math.max(0,...r.map(l=>l.matches.length));for(let l=0;l<o;l+=1)for(let u of r){let d=u.matches[l];if(!d)continue;let m=zn(e,d.relativePath,d.focusLine,Ei,t.context);m&&or(e,n,m,"search",`search:${u.pattern}`,d.ownerSymbol,d.ownerShort,1,i++)}let s=r.map(({pattern:l,result:u})=>{let d=u.omittedMatches>0?dy(l,t.scope):void 0,m=u.fileCoverage??[],p=LT(l,m,t.scope);return{pattern:l,matchingLines:u.matchingLines,returnedMatches:u.matches.length,omittedMatches:u.omittedMatches,matchingFiles:m.length,returnedFiles:m.filter(f=>f.returnedMatches>0).length,omittedFiles:m.filter(f=>f.returnedMatches===0).length,candidateUnits:0,selectedUnits:0,omittedUnits:0,scopeHints:p.slice(0,ny),omittedScopeHints:Math.max(0,p.length-ny),textCoverage:u.textCoverage,...d?{exactFollowup:d}:{}}}),a=t.locations.map(l=>{let u=MT(l),d=u?ct(e,u.path):null,m=d?zn(e,d,u.line-1,Ei,t.context):null;return m&&or(e,n,m,"location",`at:${l}`,null,null,0,i++),{target:l,matched:m!==null}}),c=t.symbols.map(l=>Jl(e,l,t.evidence));for(let l of c)if(l.kind==="matched"){if(l.definition){let u=zn(e,l.definition.relativePath,l.definition.startLine,Ei,t.context);u&&or(e,n,u,"definition",`definition:${l.shortName}`,l.symbol,l.shortName,0,i++)}for(let u of l.referenceWindows){let d=u.references[0];or(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,V(u.relativePath)==="test"?5:4,i++,u.references.map(m=>m.line),l.symbol)}for(let u of l.callers)ry(e,n,u,"caller",l,2,i++);for(let u of l.callees)ry(e,n,u,"callee",l,3,i++);for(let u of l.dependencies)oy(e,n,"dependency",l.file,u.relativePath,l.symbol,t.context,6,i++);for(let u of l.consumers)oy(e,n,"consumer",u.relativePath,l.file,l.symbol,t.context,7,i++)}return{searches:s,evidence:c,locations:a,candidates:n}}function nu(e,t){return e.priority-t.priority||t.roles.length-e.roles.length||t.reasons.length-e.reasons.length||iy(V(e.relativePath))-iy(V(t.relativePath))||e.sequence-t.sequence}function iy(e){switch(e){case"entry":case"source":case"worker":return 0;case"barrel":return 1;case"test":return 2}}function ru(e,t){return{candidate:e,priority:e.priority,sequence:e.sequence,relativePath:e.relativePath,fileKind:V(e.relativePath),evidenceCharacters:py(e,t),roles:e.roles,reasons:e.reasons,symbols:e.symbols,behaviorSignals:e.kind==="source"?e.behavior?.signals??[]:[],channel:ou(e)}}function ou(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")?V(e.relativePath)==="test"?"test-reference":"production-reference":t.includes("dependency")?"dependency":t.includes("consumer")?"consumer":"search"}function yT(e,t){let n=t.filter(r=>r.kind==="source"),i=Mr(e,{files:lt(n.map(r=>r.relativePath))});for(let r of n){r.behavior=Wi(e,r.relativePath,r.startLine,r.endLine,r.focusLines)??void 0;let o=i.filter(a=>a.source.file===r.relativePath&&a.source.startLine<=r.endLine&&a.source.endLine>=r.startLine),s=o.filter(a=>!bT(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}}));r.runtimeFacts=s.length>0?s:void 0}}function bT(e,t){if(e.strength!=="candidate"||e.protocol!=="http")return!1;let n=e.keyParts.find(r=>r.name==="path")?.value,i=e.keyParts.find(r=>r.name==="method")?.value;return n?t.some(r=>{if(r===e||r.action!==e.action||r.role!==e.role||r.source.startLine!==e.source.startLine||r.derivation.rule!=="http.mount-prefix")return!1;let o=r.keyParts.find(a=>a.name==="path")?.value,s=r.keyParts.find(a=>a.name==="method")?.value;return!!(o&&o!==n&&o.endsWith(n)&&(!i||i===s))}):!1}function ST(e,t){for(let n of t){if(n.kind!=="source")continue;let i=gt(e,n.relativePath,n.startLine,n.endLine,n.focusLines);i.startLine===n.startLine&&i.endLine===n.endLine||(n.startLine=i.startLine,n.endLine=i.endLine,n.source=ie(e,n.relativePath).slice(i.startLine,i.endLine+1).join(`
73
- `),n.unitStartLine=i.startLine,n.unitEndLine=i.endLine,n.omittedLines=0)}}function vT(e,t){for(let n of t)n.kind==="source"&&(n.bindingClosure=qi(e,n.relativePath,n.startLine,n.endLine))}function CT(e,t){let n=new Map;for(let i of t){let r=ga(i.relativePath),o=ou(i),s=[...i.roles].sort().join(","),a=i.kind==="path"?i.relationship:"",c=`${r}|${o}|${s}|${a}`,l=n.get(c)??[];l.push(i),n.set(c,l)}return[...n.entries()].map(([i,r])=>{let o=r[0],s=lt(r.flatMap(c=>[...c.roles])).sort(),a=lt(r.flatMap(c=>c.kind==="source"?c.behavior?.signals??[]:[])).sort();return{id:`g-${ly("sha256").update(i).digest("hex").slice(0,8)}`,scope:ga(o.relativePath),channel:ou(o),roles:s,behaviorSignals:a,candidateUnits:r.length,sourceCharacters:r.reduce((c,l)=>c+(l.kind==="source"?l.source.length:0),0),anchors:r.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:xT(e,r)}}).sort((i,r)=>r.candidateUnits-i.candidateUnits||r.sourceCharacters-i.sourceCharacters||i.scope.localeCompare(r.scope)||i.id.localeCompare(r.id))}function xT(e,t){let n=lt(t.flatMap(o=>o.reasons.filter(s=>s.startsWith("search:")).map(s=>s.slice(7)))),i=ga(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 ${Ot(s)}`);return o.push(`--scope ${Ot(i)}`,"--full"),e.view==="behavior"&&o.push("--view behavior"),o.join(" ")}let r=t.filter(o=>o.kind==="source");if(r.length>0&&r.length<=24){let o=["codebaseiq inspect"];for(let s of r)o.push(`--at ${Ot(`${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:my(e,!0)}function RT(e,t,n){let i=`search:${e.pattern}`,r=t.filter(a=>a.reasons.includes(i)).length,o=new Set(n),s=t.filter(a=>a.reasons.includes(i)&&o.has(a)).length;return{...e,candidateUnits:r,selectedUnits:s,omittedUnits:r-s}}function ET(e){let t={};for(let n of e)for(let i of n.roles)t[i]=(t[i]??0)+1;return t}function wT(e,t,n,i){let r=e.map(s=>ru(s,i).channel),o=t.map(s=>ru(s,i).channel);return Object.fromEntries(Object.keys(n).map(s=>{let a=r.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 IT(e){return!!(e&&e.skippedUnreadablePaths.length===0&&e.skippedOversizedPaths.length===0)}function LT(e,t,n){let i=new Map;for(let r of t){let o=ga(r.relativePath),s=i.get(o)??{matchingLines:0,returnedMatches:0};s.matchingLines+=r.matchingLines,s.returnedMatches+=r.returnedMatches,i.set(o,s)}return[...i.entries()].map(([r,o])=>({scope:r,...o,exactFollowup:dy(e,r||n)})).sort((r,o)=>o.matchingLines-r.matchingLines||o.returnedMatches-r.returnedMatches||r.scope.localeCompare(o.scope))}function ga(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}function dy(e,t){return`codebaseiq inspect --search ${Ot(e)}${t?` --scope ${Ot(t)}`:""} --full`}function my(e,t){let n=["codebaseiq inspect"];for(let i of e.searches)n.push(`--search ${Ot(i)}`);for(let i of e.symbols)n.push(`--symbol ${Ot(i)}`);for(let i of e.locations)n.push(`--at ${Ot(i)}`);return e.scope&&n.push(`--scope ${Ot(e.scope)}`),e.context!==uy&&n.push(`--context ${e.context}`),e.evidence.parts&&n.push(`--include ${Ot(e.evidence.parts.join(","))}`),t&&n.push("--full"),e.view==="behavior"&&n.push("--view behavior"),n.join(" ")}function ry(e,t,n,i,r,o,s){or(e,t,{...n,unitType:null,unitStartLine:n.startLine,unitEndLine:n.endLine+n.omittedLines},i,`${i}:${r.shortName}`,n.symbol,n.shortName,o,s,[n.focusLine],r.symbol)}function oy(e,t,n,i,r,o,s,a,c){let l=`${i} -> ${r}`,u=Ce(e,i).filter(h=>h.sourcePath===r),d=ie(e,i),m=PT(d,u,r),p=m===null?null:Os(e,i,m,Math.min(s,4));if(p){or(e,t,{...p,unitType:null,unitStartLine:p.startLine,unitEndLine:p.endLine,omittedLines:0},n,`${n}:${l}`,null,null,a,c,[p.focusLine],o);return}let f=`codebaseiq inspect --search ${Ot(fy(r))} --scope ${Ot(i)}`,g=t.find(h=>h.kind==="path"&&h.relativePath===i&&h.relationship===l);if(g){g.roles=lt([...g.roles,n]),g.reasons=lt([...g.reasons,`${n}:${l}`]),g.symbols=lt([...g.symbols,o]),g.priority=Math.min(g.priority,a);return}t.push({kind:"path",roles:[n],relativePath:i,relationship:l,reasons:[`${n}:${l}`],symbols:[o],exactFollowup:f,priority:a,sequence:c})}function PT(e,t,n){let i=lt(t.flatMap(c=>[c.importedName,c.localName??""]).filter(c=>c.length>1)),r=fy(n).replace(/\.[^.]+$/u,""),o=lt([...i,r]).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 or(e,t,n,i,r,o,s,a,c,l=[n.focusLine],u){let d=t.find(m=>m.kind==="source"&&m.relativePath===n.relativePath&&m.startLine<=n.endLine&&n.startLine<=m.endLine);if(d){let m=Math.min(d.startLine,n.startLine),p=Math.max(d.endLine,n.endLine);d.startLine=m,d.endLine=p,d.source=ie(e,n.relativePath).slice(m,p+1).join(`
74
- `),d.focusLine=Math.min(d.focusLine,n.focusLine),d.focusLines=ay([...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=lt([...d.reasons,r]),d.roles=lt([...d.roles,i]),d.symbols=lt([...d.symbols,...u?[u]:[]]),!d.ownerSymbol&&o&&(d.ownerSymbol=o),!d.ownerShort&&s&&(d.ownerShort=s),d.priority=Math.min(d.priority,a);return}t.push({kind:"source",...n,reasons:[r],focusLines:ay(l),ownerSymbol:o,ownerShort:s,roles:[i],symbols:u?[u]:[],priority:a,sequence:c})}function DT(e){if(e.kind==="path"){let{priority:o,sequence:s,...a}=e;return{...a,id:sy(a)}}let{priority:t,sequence:n,bindingClosure:i,...r}=e;return{...r,id:sy(r),omittedCharacters:0}}function TT(e){let{kind:t,id:n,roles:i,symbols:r,omittedCharacters:o,behavior:s,runtimeFacts:a,...c}=e;return c}function sy(e){return ly("sha256").update(JSON.stringify(e)).digest("hex").slice(0,16)}function MT(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 iu(e){return lt((e??[]).map(t=>t.trim()).filter(Boolean))}function lt(e){return[...new Set(e)]}function ay(e){return lt(e).sort((t,n)=>t-n)}function AT(e){return e.length===0?0:e.split(`
75
- `).length}function py(e,t){if(e.kind==="path")return e.relationship.length+e.exactFollowup.length;let n="bindingClosure"in e?Jp(e.bindingClosure):0,i=(e.runtimeFacts??[]).reduce((r,o)=>r+o.action.length+o.derivation.rule.length+o.keyParts.reduce((s,a)=>s+a.name.length+a.value.length+4,0)+24,0);return t!=="behavior"?e.source.length+n:e.behavior?e.behavior.lines.reduce((r,o)=>r+o.text.length+o.signals.join(",").length+12,0)+e.behavior.testCases.reduce((r,o)=>r+o.length+2,0)+i+n:e.source.length+n+i}function fy(e){return e.split("/").at(-1)??e}function Ot(e){return`'${e.replaceAll("'","'\\''")}'`}function Jn(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new RangeError(`${t} must be a positive safe integer; received ${e}`);return e}function cy(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 FT}from"path";function NT(e,t){let n=t.className,i=rt(e,n);return i.match?i.total>1?{kind:"ambiguous",query:n,total:i.total,candidates:[gy(i.match),...i.candidates]}:{kind:"matched",query:n,owner:_T(i.match),methods:kT(e,i.match)}:{kind:"missing",query:n,suggestions:ms(e,n,5)}}function kT(e,t){let n=re(t.symbol),r=new U(e).definitionsForFile(t.relativePath).filter(c=>it(c.symbol)),o=r.filter(c=>c.parentTypeName===n||c.symbol.includes(n)),a=(o.length>0?o:OT(FT(t.relativePath))===n?r.filter(c=>c.symbol.includes("<invalid-global-code>")):[]).map(c=>({startLine:c.startLine,endLine:c.endLine,name:re(c.symbol)}));return ye(t.relativePath)!=="clojure"?a:$T(a,BT(e,t))}function gy(e){return{symbol:e.symbol,shortName:k(e.symbol),relativePath:e.relativePath,startLine:e.startLine}}function _T(e){return{...gy(e),endLine:e.endLine}}function OT(e){return e.replace(/\.[^.]+$/,"")}function BT(e,t){let n=re(t.symbol);return n?(ee(e,t.relativePath)?.clojureMembers??[]).filter(i=>i.ownerName===n).map(i=>({startLine:i.startLine,endLine:i.endLine,name:i.memberName})):[]}function $T(e,t){let n=new Map;for(let i of[...e,...t])n.set(`${i.name}:${i.startLine}:${i.endLine}`,i);return[...n.values()].sort((i,r)=>i.startLine-r.startLine||i.endLine-r.endLine)}import{createHash as _A}from"crypto";var J4={exact:"Direct compiler or source evidence establishes this relationship within the provider's reported coverage.",derived:"A deterministic analysis computed this relationship from reported input facts; it was not directly observed.",candidate:"Ambiguous or heuristic evidence identifies a lead that requires exact graph or source confirmation.",mixed:"The relationship combines evidence of different strengths; its constituent methods and strengths remain disclosed.",unknown:"The relationship has no calibrated evidence strength and cannot support a stronger claim than its raw observation."},jT=[{id:"general-interprocedural-value-flow",families:["dataflow"],capability:"Whole-program definition-use flow through arbitrary calls and returns is unavailable.",consequence:"Missing dataflow edges cannot establish that a value never crosses an unmodeled call.",recoverWith:["value-flow","dependence-slice","inspect","code"]},{id:"heap-aliasing",families:["dataflow","state"],capability:"Heap points-to and cross-instance alias analysis are unavailable.",consequence:"Missing field or state edges cannot establish that two references never reach the same object.",recoverWith:["value-flow","dependence-slice","inspect","code"]},{id:"exceptional-flow",families:["execution","dataflow","temporal"],capability:"Interprocedural exception propagation and finally completion flow are unavailable.",consequence:"Normal-path reachability and ordering do not establish behavior after a throw or rejection.",recoverWith:["dependence-slice","inspect","code"]},{id:"reflection",families:["execution","runtime","identity","dependencies"],capability:"Reflective lookup, dynamic loading, and name-computed invocation are unavailable without exact evidence.",consequence:"Missing static edges cannot establish that a construct is unreachable through reflection.",recoverWith:["search","inspect","code"]},{id:"generated-dispatch",families:["execution","runtime","identity"],capability:"Dispatch tables or names created only by generated or unavailable source are unavailable.",consequence:"Missing dispatch edges cannot establish that no generated consumer exists.",recoverWith:["search","inspect","code"]},{id:"unsupported-framework-adapters",families:["runtime","dataflow","state","temporal"],capability:"Framework runtime crossings without a registered source adapter are unavailable.",consequence:"Missing boundary edges cannot establish that no producer, consumer, state effect, or ordering exists.",recoverWith:["search","inspect","code"]}];function HT(e){let t=new Set(e);return jT.filter(n=>n.families.some(i=>t.has(i)))}function hy(e){return HT(e).map(t=>`[${t.id}] ${t.capability} ${t.consequence} Recover selected paths with: ${t.recoverWith.map(n=>`codebaseiq ${n}`).join(", ")}.`)}var UT=["incoming","outgoing","both"];function Ae(e,t,n,i={}){return{family:e,subtype:t,...i.match?{match:i.match}:{},directions:UT,evidenceStrengths:i.strengths??["exact","derived","mixed"],supportCeiling:i.supportCeiling??"partial",establishes:n,nonClaims:i.nonClaims??[],recoverWith:i.recoverWith??["inspect","code"]}}var zT=["predicate-consequence","predicate-alternative","predicate-fallthrough","predicate-case","predicate-default","predicate-return","predicate-throw","loop-iteration","loop-exit","exception-handler","finally-cleanup","handler-return","handler-throw"],GT=["captured-value-to-state","constant-to-state","expression-to-state","property-to-state","return-to-state","value-to-state"],KT=["await-completion-before","awaits-completion","inside-lock-scope","lexical-successor"],qT=[{id:"indexed-program-identity",label:"SCIP/compiler identity and source ownership",requirements:["indexed-graph"],relations:[Ae("execution","call","The source construct may call the resolved target.",{nonClaims:["Static may-call reachability does not prove that an invocation occurred at runtime."],recoverWith:["call-graph","inspect","code"]}),Ae("execution","result-callback","The referenced callable can produce the result consumed by this path.",{nonClaims:["A callback relationship does not prove invocation order or runtime selection."],recoverWith:["call-graph","inspect","code"]}),Ae("contract","uses-contract-symbol","The source construct refers to the identified contract symbol.",{supportCeiling:"exact",nonClaims:["Contract identity does not prove runtime invocation or behavioral conformance."],recoverWith:["hierarchy","inspect","code"]}),Ae("identity","references","The occurrence resolves to the identified compiler-owned symbol.",{supportCeiling:"exact",nonClaims:["A reference does not establish execution or value transfer."],recoverWith:["refs","trace","inspect"]}),Ae("ownership","contains","The owner contains the identified program construct.",{supportCeiling:"exact",nonClaims:["Structural containment does not establish runtime lifetime or sharing scope."],recoverWith:["outline","inspect"]}),Ae("ownership","contains-","The owner contains the identified program construct.",{match:"prefix",supportCeiling:"exact",nonClaims:["Structural containment does not establish runtime lifetime or sharing scope."],recoverWith:["outline","inspect"]}),Ae("ownership","owns-","The owner owns the identified source or runtime observation.",{match:"prefix",supportCeiling:"exact",nonClaims:["Observation ownership does not establish singleton lifetime or exclusive ownership."],recoverWith:["inspect","code"]}),Ae("dependencies","imports","The source file or module statically imports the indexed target.",{nonClaims:["An import does not establish that imported code executes."],recoverWith:["imports","deps","code"]}),Ae("dependencies","imports-external","The source region statically imports an external package.",{nonClaims:["An external import does not establish which package behavior executes."],recoverWith:["imports","code"]})]},{id:"runtime-boundary-join",label:"source-grounded runtime-boundary joins",requirements:["indexed-graph","source-facts"],relations:[Ae("runtime","runtime-handoff","A producer and consumer share a source-grounded runtime rendezvous.",{strengths:["exact","derived","candidate","mixed"],nonClaims:["A candidate or unresolved join does not prove a runtime handoff."],recoverWith:["evidence","inspect","code"]}),Ae("runtime","discriminator-dispatch","A serialized discriminator selects the reported consumer.",{strengths:["exact","derived","mixed"],nonClaims:["The dispatch edge does not prove delivery, retry, or successful handling."],recoverWith:["evidence","inspect","code"]}),Ae("dataflow","serialized-discriminator-transfer","The producer serializes the discriminator consumed by dispatch.",{strengths:["exact","derived","mixed"],nonClaims:["This edge does not establish the flow of every payload field."],recoverWith:["value-flow","inspect","code"]}),Ae("temporal","enqueue-before-consume","The reported enqueue precedes a possible consume through the queue.",{strengths:["exact","derived","mixed"],nonClaims:["Queue order does not establish delivery time, uniqueness, retry count, or durability."],recoverWith:["evidence","inspect","code"]})]},{id:"parser-control-dependence",label:"parser-proved intraprocedural control dependence",requirements:["indexed-graph","source-facts"],relations:[...zT.map(e=>Ae("execution",e,"The outcome is control-dependent on the reported predicate or handler.",{strengths:["exact"],nonClaims:["Local control dependence does not establish that the containing function executes."],recoverWith:["dependence-slice","inspect","code"]})),Ae("execution","returns","The selected construct contains the reported return terminal.",{strengths:["exact"],nonClaims:["A local return terminal does not establish that the containing callable executes."],recoverWith:["inspect","code"]}),Ae("execution","throws","The selected construct contains the reported throw terminal.",{strengths:["exact"],nonClaims:["A local throw terminal does not establish propagation, handling, or callable execution."],recoverWith:["inspect","code"]})]},{id:"bounded-static-value-flow",label:"compiler callsites and bounded static value evaluation",requirements:["indexed-graph","source-facts"],relations:[...["argument-to-parameter","constant-to-parameter","property-to-parameter","return-to-parameter","return-to-call-result"].map(e=>Ae("dataflow",e,"The reported value may reach the target through the evidenced callsite transfer.",{strengths:["exact","derived","mixed"],nonClaims:["This provider does not establish general local definition-use, alias, field, or heap flow."],recoverWith:["value-flow","dependence-slice","inspect","code"]}))]},{id:"typescript-local-dependence",label:"TypeScript compiler identities, control-flow graph, and reaching definitions",requirements:["typescript-semantic"],relations:[Ae("dataflow","definition-to-use","The definition reaches the reported read on a feasible local control-flow path.",{strengths:["exact"],nonClaims:["Local reaching definitions do not establish heap aliasing, exceptional flow, or the runtime order of closure invocation."],recoverWith:["value-flow","dependence-slice","inspect","code"]}),Ae("dataflow","value-to-definition","The reported right-hand-side read supplies the assigned local definition.",{strengths:["exact"],nonClaims:["A local assignment edge does not establish field or heap points-to flow."],recoverWith:["value-flow","dependence-slice","inspect","code"]}),Ae("dataflow","closure-capture","The nested callable reads the reported binding from an enclosing callable.",{strengths:["candidate"],supportCeiling:"candidate",nonClaims:["Closure capture does not establish whether or when the nested callable executes."],recoverWith:["call-graph","inspect","code"]}),Ae("dataflow","field-definition-to-use","The reported same-owner field definition can reach the field read.",{strengths:["exact","candidate"],nonClaims:["Field-name identity does not establish whole-program heap aliasing or cross-instance flow."],recoverWith:["value-flow","dependence-slice","inspect","code"]}),Ae("execution","control-dependence","Execution of the reported statement depends on the outcome of the predicate.",{strengths:["exact"],nonClaims:["Intraprocedural control dependence does not establish that the containing callable executes."],recoverWith:["dependence-slice","inspect","code"]})]},{id:"parser-state-temporal",label:"parser-proved local state and temporal facts",requirements:["indexed-graph","source-facts"],relations:[...GT.map(e=>Ae("dataflow",e,"The reported source value is assigned into the identified state resource.",{strengths:["exact"],nonClaims:["The edge does not establish alias, heap, or later read flow."],recoverWith:["value-flow","inspect","code"]})),...["writes-resource","deletes-resource","reads-resource","enqueues-resource","consumes-resource"].map(e=>Ae("state",e,"The reported construct performs the named operation on the identified resource.",{strengths:["exact"],nonClaims:["A state operation does not establish transactionality, durability, or exclusive ownership."],recoverWith:["evidence","inspect","code"]})),...KT.map(e=>Ae("temporal",e,"The reported source constructs have the named local ordering relationship.",{strengths:["exact"],nonClaims:["Local source order does not establish cross-process happens-before or durable completion."],recoverWith:["evidence","inspect","code"]}))]}];function yy(e,t){let n=qT.flatMap(i=>i.relations.filter(r=>r.family===e&&(r.match==="prefix"?t.startsWith(r.subtype):t===r.subtype)).map(r=>({provider:i,relation:r})));if(n.length>1)throw new Error(`Ambiguous graph relation provider for ${e}/${t}: ${n.map(i=>i.provider.id).join(", ")}`);return n[0]??null}var Kt=["execution","runtime","dataflow","state","temporal","contract","identity","ownership","dependencies"];var by=["call","contract-symbol","import","reference","runtime-boundary"],WT={call:[{family:"control",subtype:"call"}],"contract-symbol":[{family:"contract",subtype:"uses-contract-symbol"}],import:[{family:"identity",subtype:"imports"}],reference:[{family:"identity",subtype:"references"}]},VT={"structural-membership":[{family:"identity",subtype:"contains"}],"boundary-observation":[{family:"identity",subtype:"owns-runtime-observation"}],"external-import":[{family:"identity",subtype:"imports-external"}]};function Sy(e){if(e.kind!=="runtime-boundary")return vy(WT[e.kind]);let t=e.fromBoundaryParticipant?.protocol??e.toBoundaryParticipant?.protocol,n={crossesRuntimeBoundary:!0,...t?{protocol:t}:{},...e.runtimeBoundaryKey?{runtimeKey:e.runtimeBoundaryKey}:{}},i=[{family:"control",subtype:"runtime-handoff",context:n}];return e.evidence==="runtime-boundary:carrier.discriminator"&&(i.push({family:"control",subtype:"discriminator-dispatch",context:{...n},attributes:{joinRule:"carrier.discriminator",...e.fromBoundaryParticipant?.action?{producerAction:e.fromBoundaryParticipant.action}:{},...e.toBoundaryParticipant?.action?{consumerAction:e.toBoundaryParticipant.action}:{}}}),i.push({family:"data",subtype:"serialized-discriminator-transfer",context:{...n},attributes:{joinRule:"carrier.discriminator"}})),e.evidence==="runtime-boundary:queue.address"&&e.fromBoundaryParticipant?.action==="queue.send"&&e.toBoundaryParticipant?.action==="queue.consume"&&i.push({family:"temporal",subtype:"enqueue-before-consume",context:{...n},attributes:{producerAction:e.fromBoundaryParticipant.action,consumerAction:e.toBoundaryParticipant.action,retryPolicy:"unknown"}}),i}function ha(e){return vy(VT[e])}function vy(e){return e.map(t=>({...t,...t.context?{context:{...t.context}}:{},...t.attributes?{attributes:{...t.attributes}}:{}}))}import{join as v0}from"path";import{createRequire as JT}from"module";import{resolve as co}from"path";var YT=JT(import.meta.url),ao;function xy(e,t,n){let i=XT();if(!i)return au("The TypeScript compiler runtime is unavailable.");let r=QT(i,e,t),o=r.getSourceFile(co(t))??r.getSourceFile(t);if(!o)return au(`The TypeScript compiler did not materialize ${t}.`);let s={ts:i,sourceFile:o,checker:r.getTypeChecker(),points:new Map,edges:new Map,unsupported:new Set,nextCfgId:0},a=e0(i,o,n);if(a.length===0)return au("No function-like construct intersects the selected source range.");let c=new Map(a.map(d=>[d,t0(o,d)])),l=a.map(d=>i0(s,d,n0(i,d,c),c.get(d)));for(let d of l)r0(s,d),c0(s,d),d0(s,d);p0(s,l);let u=[...s.unsupported].sort();return{points:[...s.points.values()].map(({node:d,...m})=>m).sort(S0),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 XT(){if(ao!==void 0)return ao;try{ao=YT("typescript")}catch{ao=Xm()?.ts??null}return ao}function QT(e,t,n){let i=co(n),r={target:e.ScriptTarget.ESNext,module:e.ModuleKind.NodeNext,moduleResolution:e.ModuleResolutionKind.NodeNext,skipLibCheck:!0,noResolve:!0},o=e.createSourceFile(i,t,r.target,!0,ZT(e,i)),s=e.createCompilerHost(r,!0),a=s.getSourceFile.bind(s),c=s.readFile.bind(s),l=s.fileExists.bind(s);return s.getSourceFile=(u,d,m,p)=>co(u)===i?o:a(u,d,m,p),s.readFile=u=>co(u)===i?t:c(u),s.fileExists=u=>co(u)===i||l(u),e.createProgram([i],r,s)}function ZT(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 e0(e,t,n){let i=[],r=o=>{if(Ry(e,o)){let s=t.getLineAndCharacterOfPosition(o.getStart(t)).line,a=t.getLineAndCharacterOfPosition(o.getEnd()).line;(!n||s<=n.endLine&&a>=n.startLine)&&i.push(o)}o.forEachChild(r)};return t.forEachChild(r),i.sort((o,s)=>o.getStart(t)-s.getStart(t))}function Ry(e,t){return e.isFunctionLike(t)&&"body"in t&&t.body!==void 0}function t0(e,t){return`callable:${encodeURIComponent(e.fileName)}:${t.getStart(e)}:${t.getEnd()}`}function n0(e,t,n){for(let i=t.parent;i;i=i.parent)if(Ry(e,i)&&n.has(i))return n.get(i);return null}function i0(e,t,n,i){let r=new Map,o=Qe(e,r,"exit",null),s=t.body,a=o.id;if(s&&e.ts.isBlock(s))a=cu(e,r,[...s.statements],o.id,{breakTarget:null,continueTarget:null});else if(s){let l=Qe(e,r,"statement",s);_e(r,l.id,o.id),a=l.id}let c=Qe(e,r,"entry",t);return _e(r,c.id,a),{id:i,node:t,parentId:n,cfg:r,entryId:c.id,exitId:o.id}}function cu(e,t,n,i,r){let o=i;for(let s=n.length-1;s>=0;s-=1)o=wi(e,t,n[s],o,r);return o}function wi(e,t,n,i,r){let o=e.ts;if(o.isBlock(n))return cu(e,t,[...n.statements],i,r);if(o.isIfStatement(n)){let a=Qe(e,t,"predicate",n.expression),c=wi(e,t,n.thenStatement,i,r),l=n.elseStatement?wi(e,t,n.elseStatement,i,r):i;return _e(t,a.id,c),_e(t,a.id,l),a.id}if(o.isWhileStatement(n)){let a=Qe(e,t,"predicate",n.expression),c=wi(e,t,n.statement,a.id,{breakTarget:i,continueTarget:a.id});return _e(t,a.id,c),_e(t,a.id,i),a.id}if(o.isDoStatement(n)){let a=Qe(e,t,"predicate",n.expression),c=wi(e,t,n.statement,a.id,{breakTarget:i,continueTarget:a.id});return _e(t,a.id,c),_e(t,a.id,i),c}if(o.isForStatement(n)){let a=Qe(e,t,"predicate",n.condition??n),c=n.incrementor?Qe(e,t,"statement",n.incrementor):null;c&&_e(t,c.id,a.id);let l=c?.id??a.id,u=wi(e,t,n.statement,l,{breakTarget:i,continueTarget:l});if(_e(t,a.id,u),n.condition&&_e(t,a.id,i),!n.initializer)return a.id;let d=Qe(e,t,"statement",n.initializer);return _e(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=Qe(e,t,"predicate",n.expression),c=Qe(e,t,"statement",n.initializer),l=wi(e,t,n.statement,a.id,{breakTarget:i,continueTarget:a.id});return _e(t,a.id,c.id),_e(t,a.id,i),_e(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=Qe(e,t,"predicate",n.expression),c=i,l=[];for(let u=n.caseBlock.clauses.length-1;u>=0;u-=1){let d=n.caseBlock.clauses[u];c=cu(e,t,[...d.statements],c,{...r,breakTarget:i}),l.push(c)}for(let u of l)_e(t,a.id,u);return _e(t,a.id,i),a.id}if(o.isReturnStatement(n)||o.isThrowStatement(n)){let a=Qe(e,t,"statement",n),c=[...t.values()].find(l=>l.kind==="exit");return _e(t,a.id,c.id),a.id}if(o.isBreakStatement(n)){let a=Qe(e,t,"statement",n);return r.breakTarget||e.unsupported.add("A break statement could not be attached to a structured target."),_e(t,a.id,r.breakTarget??i),a.id}if(o.isContinueStatement(n)){let a=Qe(e,t,"statement",n);return r.continueTarget||e.unsupported.add("A continue statement could not be attached to a structured target."),_e(t,a.id,r.continueTarget??i),a.id}if(o.isTryStatement(n)){e.unsupported.add("Exceptional control-flow and finally completion are not included in the local compiler CFG.");let a=Qe(e,t,"statement",n);return a.invalidatesAllDefinitions=!0,_e(t,a.id,i),a.id}let s=Qe(e,t,"statement",n);return _e(t,s.id,i),s.id}function Qe(e,t,n,i){let r={id:`cfg:${e.nextCfgId++}`,kind:n,ast:i,successors:new Set,predecessors:new Set,definitions:[],uses:[],displayPoint:null,invalidatesAllDefinitions:!1};return t.set(r.id,r),r}function _e(e,t,n){e.get(t).successors.add(n),e.get(n).predecessors.add(t)}function r0(e,t){let n=t.cfg.get(t.entryId);for(let i of t.node.parameters){let r=Ii(e,i.name);if(!r){e.unsupported.add("Destructured parameter definition-use is not implemented.");continue}n.definitions.push({point:Li(e,r.node,"parameter-definition",r.symbolKey,r.name,t.id),rhsUseIds:[]})}for(let i of t.cfg.values())!i.ast||i.kind==="entry"||i.kind==="exit"||(i.kind==="predicate"&&(i.displayPoint=Li(e,i.ast,"predicate",null,"predicate",t.id)),o0(e,t,i,i.ast),!i.displayPoint&&i.definitions.length===0&&i.uses.length===0&&(i.displayPoint=Li(e,i.ast,"statement",null,g0(e,i.ast),t.id)))}function o0(e,t,n,i){let r=e.ts;if(r.isTryStatement(i))return;let o=s=>{if(!(s!==i&&r.isFunctionLike(s))){if(r.isVariableDeclaration(s)){let a=s.initializer?ya(e,t.id,s.initializer,n):[];n.uses.push(...a);let c=Ii(e,s.name);c?n.definitions.push({point:Li(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(r.isBinaryExpression(s)&&Iy(r,s.operatorToken.kind)){let a=ya(e,t.id,s.right,n);s.operatorToken.kind!==r.SyntaxKind.EqualsToken&&a.push(...ya(e,t.id,s.left,n)),n.uses.push(...a);let c=Ii(e,s.left);c?n.definitions.push({point:Li(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((r.isPrefixUnaryExpression(s)||r.isPostfixUnaryExpression(s))&&(s.operator===r.SyntaxKind.PlusPlusToken||s.operator===r.SyntaxKind.MinusMinusToken)){let a=ya(e,t.id,s.operand,n);n.uses.push(...a);let c=Ii(e,s.operand);c&&n.definitions.push({point:Li(e,c.node,"definition",c.symbolKey,c.name,t.id),rhsUseIds:a.map(l=>l.point.id)});return}if(!(r.isFunctionDeclaration(s)||r.isClassDeclaration(s)||r.isInterfaceDeclaration(s))){if(Ey(e,s)){let a=wy(e,t.id,s);a&&n.uses.push(a),r.isPropertyAccessExpression(s)&&o(s.expression);return}s.forEachChild(o)}}};o(i),n.uses=Ly(n.uses)}function ya(e,t,n,i){let r=[],o=s=>{if(!e.ts.isFunctionLike(s)){if(e.ts.isBinaryExpression(s)&&Iy(e.ts,s.operatorToken.kind)){i.invalidatesAllDefinitions=!0,e.unsupported.add("Nested assignment expressions are not included in ordered local definition-use flow."),s.operatorToken.kind!==e.ts.SyntaxKind.EqualsToken&&o(s.left),o(s.right);return}if(Ey(e,s)){let a=wy(e,t,s);a&&r.push(a),e.ts.isPropertyAccessExpression(s)&&o(s.expression);return}s.forEachChild(o)}};return o(n),Ly(r)}function Ey(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&&s0(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)||a0(e.ts,t))}function s0(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 a0(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 wy(e,t,n){let i=Ii(e,n);return i?{point:Li(e,i.node,"use",i.symbolKey,i.name,t),property:e.ts.isPropertyAccessExpression(n)}:null}function Ii(e,t){let n=e.ts;if(n.isIdentifier(t)){let i=Cy(e,t);return i?{node:t,symbolKey:i,name:t.text}:null}if(n.isPropertyAccessExpression(t)){let i=Cy(e,t.name);return i?{node:t,symbolKey:i,name:t.getText(e.sourceFile)}:null}return n.isParenthesizedExpression(t)||n.isAsExpression(t)||n.isTypeAssertionExpression(t)||n.isNonNullExpression(t)?Ii(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 Cy(e,t){let n=e.checker.getSymbolAtLocation(t);if(!n)return null;if((n.flags&e.ts.SymbolFlags.Alias)!==0)try{n=e.checker.getAliasedSymbol(n)}catch{}let i=n.valueDeclaration??n.declarations?.[0];return i?`symbol:${encodeURIComponent(i.getSourceFile().fileName)}:${i.getStart()}:${n.getName()}`:`symbol:${n.getName()}`}function Li(e,t,n,i,r,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(i??r)}`,u=e.points.get(l);if(u)return u;let d={id:l,kind:n,name:r,symbolKey:i,callableId:o,start:s,end:a,line:c.line,column:c.character,node:t};return e.points.set(l,d),d}function c0(e,t){let n=[...t.cfg.values()].flatMap(c=>c.definitions),i=new Map(n.map(c=>[c.point.id,c])),r=l0(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=y0([...c.predecessors].map(m=>s.get(m))),u=new Set(l);c.invalidatesAllDefinitions&&u.clear();let d=u0(c.definitions);for(let m of d){for(let p of r.get(m.point.symbolKey)??[])u.delete(p.point.id);u.add(m.point.id)}lu(o.get(c.id),l)||(o.set(c.id,l),a=!0),lu(s.get(c.id),u)||(s.set(c.id,u),a=!0)}}for(let c of t.cfg.values()){let l=o.get(c.id);for(let u of c.uses){let d=c.definitions.filter(p=>p.point.symbolKey===u.point.symbolKey&&p.point.start<u.point.start&&!p.rhsUseIds.includes(u.point.id)).sort((p,f)=>f.point.start-p.point.start)[0],m=d?[d.point.id]:l;for(let p of m){let f=i.get(p);f.point.symbolKey===u.point.symbolKey&&lo(e,"reaching-definition",f.point.id,u.point.id,"exact","A CFG path reaches this use without an intervening definition.")}}for(let u of c.definitions)for(let d of u.rhsUseIds)lo(e,"value-source",d,u.point.id,"exact","This right-hand-side use supplies the new definition.")}}function l0(e){let t=new Map;for(let n of e){if(!n.point.symbolKey)continue;let i=t.get(n.point.symbolKey)??[];i.push(n),t.set(n.point.symbolKey,i)}return t}function u0(e){let t=new Map;for(let n of e)n.point.symbolKey&&t.set(n.point.symbolKey,n);return[...t.values()]}function d0(e,t){let n=m0(t);for(let i of t.cfg.values()){if(i.successors.size<2||!i.displayPoint)continue;let r=n.get(i.id);for(let o of i.successors)for(let s of n.get(o)??[]){if(r.has(s)||s===t.exitId)continue;let a=t.cfg.get(s),c=[...a.definitions.map(l=>l.point),...a.uses.map(l=>l.point),...a.displayPoint?[a.displayPoint]:[]];for(let l of h0(c))lo(e,"control-dependence",i.displayPoint.id,l.id,"exact","The target postdominates a branch successor but does not postdominate the predicate.")}}}function m0(e){let t=[...e.cfg.keys()],n=new Set(t),i=new Map;for(let o of t)i.set(o,o===e.exitId?new Set([o]):new Set(n));let r=!0;for(;r;){r=!1;for(let o of e.cfg.values()){if(o.id===e.exitId)continue;let s=[...o.successors].map(c=>i.get(c)),a=new Set([o.id,...b0(s)]);lu(i.get(o.id),a)||(i.set(o.id,a),r=!0)}}return i}function p0(e,t){let n=new Map(t.map(s=>[s.id,s.parentId])),i=t.flatMap(s=>[...s.cfg.values()].flatMap(a=>a.definitions.map(c=>c.point))),r=new Map;for(let s of i){if(!s.symbolKey)continue;let a=r.get(s.symbolKey)??[];a.push(s),r.set(s.symbolKey,a)}let o=new Set([...e.edges.values()].filter(s=>s.kind==="reaching-definition").map(s=>s.toPointId));for(let s of t)for(let a of[...s.cfg.values()].flatMap(c=>c.uses)){if(!a.point.symbolKey||o.has(a.point.id))continue;let c=r.get(a.point.symbolKey)??[];for(let l of c)f0(l.callableId,a.point.callableId,n)?lo(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&&lo(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 f0(e,t,n){for(let i=n.get(t)??null;i;i=n.get(i)??null)if(i===e)return!0;return!1}function lo(e,t,n,i,r,o){let s=`local-flow-edge:${t}:${encodeURIComponent(n)}:${encodeURIComponent(i)}`;e.edges.set(s,{id:s,kind:t,fromPointId:n,toPointId:i,strength:r,reason:o})}function Iy(e,t){return t>=e.SyntaxKind.FirstAssignment&&t<=e.SyntaxKind.LastAssignment}function g0(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 Ly(e){return[...new Map(e.map(t=>[t.point.id,t])).values()]}function h0(e){return[...new Map(e.map(t=>[t.id,t])).values()]}function y0(e){return new Set(e.flatMap(t=>[...t]))}function b0(e){return e.length===0?new Set:new Set([...e[0]].filter(t=>e.slice(1).every(n=>n.has(t))))}function lu(e,t){return e.size===t.size&&[...e].every(n=>t.has(n))}function S0(e,t){return e.start-t.start||e.kind.localeCompare(t.kind)||e.id.localeCompare(t.id)}function au(e){return{points:[],edges:[],coverage:{status:"unsupported",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:[e]}}}var C0=Bi("typescript-local-flow",{clearGroups:["whole-project","source-file","semantic-provider"]});function uu(e,t,n,i){if(!ls(t))return null;let r=`${t}\0${n}\0${i}`;return C0.get(e,r,()=>{let o=se(e,t);return o?xy(o,v0(e.config.projectRoot,t),{startLine:n,endLine:i}):{points:[],edges:[],coverage:{status:"unsupported",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:[`Current source is unavailable for ${t}.`]}}})}function x0(e,t=new Map){let n=new Map,i=new Map,r=[];for(let o of e.transfers){if(!e.caller)continue;let s=ba(e.caller,o.callerPosition),a=ba(e.callee,o.calleePosition);uo(n,s),uo(n,a),mu(i,e.caller,s),mu(i,e.callee,a);let c=ut("edge","data-transfer",o.proof.file,String(o.proof.startLine),String(o.callerPosition),String(o.calleePosition));i.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=ba(e.callee,o.calleePosition);uo(n,a),mu(i,e.callee,a);let c=t.get(o.calleePosition);if(c&&F0(c)){A0(i,n,e,o.calleePosition,o.argumentText,c);return}let l=T0(e,o.calleePosition,o.argumentText);uo(n,l);let u=ut("edge","data-transfer-unsupported",o.proof.file,String(o.proof.startLine),String(o.calleePosition),String(s));i.set(u,{id:u,kind:"data-transfer",fromNodeId: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}}]}),r.push({id:ut("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:[...i.values()],frontiers:r,blindSpots:[]}}function Dy(e,t,n=[]){let i=Ty(),r=new Map,o=new Set;for(let s of t){if(s.kind!=="call"||!s.fromSymbol||!s.toSymbol||s.line===null)continue;let a=D0(r,e,s.toFile,s.toSymbol);if(!a)continue;let c=yp(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&&i.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=bp(e,u),p=ae(e,u.file)?.rootNode,f=new Map;if(p)for(let g of m.unknown){let h=op({db:e,file:u.file,root:p},u.arguments[g.calleePosition]);h&&f.set(g.calleePosition,h)}Py(i,x0(m,f)),m.caller&&L0(u.callNode)&&P0(i,m,u.callNode)}for(let s of n){if(!s.location||!["source-construct","symbol"].includes(s.kind))continue;let a=s.location.endLine??s.location.line,c=uu(e,s.location.file,s.location.line,a);if(c){Py(i,R0(s,c.points,c.edges));for(let l of c.coverage.unsupported)i.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 i.blindSpots=[...new Set(i.blindSpots)].sort(),i}function R0(e,t,n){let i=Ty(),r=new Map,o=new Map,s=new Map,a=e.location.file;for(let c of t){let l=E0(e,a,c);s.set(c.id,l.id),r.set(l.id,l),w0(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=I0(c),m=ut("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:r.get(l)?.location??e.location}]})}return i.nodes=[...r.values()],i.edges=[...o.values()],i}function E0(e,t,n){return{id:ut("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 w0(e,t,n){let i=ut("edge","local-flow-owner",t.id,n.id);e.has(i)||e.set(i,{id:i,kind:"local-flow-owner",fromNodeId:t.id,toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:"contains"}],evidence:[{method:"typescript-compiler-local-flow-owner",strength:"exact",identity:t.id,location:n.location}]})}function I0(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 L0(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 P0(e,t,n){if(!t.caller)return;let i={id:ut("call-result",t.call.file,String(n.startIndex),String(n.endIndex),t.callee.symbol),kind:"call-result",label:`result of ${t.callee.leaf}`,disposition:"folded",location:{file:t.call.file,line:t.call.startLine,endLine:t.call.endLine},anchorIds:[],attributes:{calleeSymbol:t.callee.symbol,callerSymbol:t.caller.symbol}},r=ut("edge","return-to-call-result",t.callee.symbol,i.id),o=ut("edge","call-result-owner",t.caller.symbol,i.id);e.nodes.push(i),e.edges.push({id:r,kind:"data-transfer",fromNodeId:pu(t.callee.symbol),toNodeId:i.id,directed:!0,disposition:"folded",semantics:[{family:"data",subtype:"return-to-call-result"}],evidence:[{method:"compiler-callsite-used-result",strength:"exact",identity:`${t.callee.symbol} -> ${t.caller.symbol}`,location:i.location}]},{id:o,kind:"call-result-owner",fromNodeId:pu(t.caller.symbol),toNodeId:i.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:"contains-call-result"}],evidence:[{method:"compiler-call-result-owner",strength:"exact",identity:t.caller.symbol,location:i.location}]})}function Ty(){return{nodes:[],edges:[],frontiers:[],blindSpots:[]}}function Py(e,t){du(e.nodes,t.nodes),du(e.edges,t.edges),du(e.frontiers,t.frontiers),e.blindSpots.push(...t.blindSpots)}function du(e,t){let n=new Set(e.map(i=>i.id));for(let i of t)n.has(i.id)||(n.add(i.id),e.push(i))}function D0(e,t,n,i){let r=`${n}\0${i}`,o=e.get(r);if(o!==void 0)return o;let s=J(t,n).find(a=>a.symbol===i)??null;return e.set(r,s),s}function ba(e,t){return{id:_0(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 T0(e,t,n){return{id:ut("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 M0(e,t,n){return{id:ut("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 A0(e,t,n,i,r,o){let s=M0(n,i,o),a=ba(n.callee,i);uo(t,s);let c=ut("edge","static-value-transfer",n.call.file,String(n.call.startLine),String(i));e.set(c,{id:c,kind:"data-transfer",fromNodeId:s.id,toNodeId:a.id,directed:!0,disposition:"folded",semantics:[{family:"data",subtype:N0(o),attributes:{argumentText:r,calleePosition:i,value:o.value,precision:o.precision,derivationRule:o.derivation.rule}}],evidence:k0(o,n)})}function F0(e){return e.derivation.kind!=="heuristic"&&e.precision!=="symbolic"&&e.precision!=="unknown"}function N0(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 k0(e,t){return(e.derivation.sourceSpans.length>0?e.derivation.sourceSpans:[t.call]).map(i=>({method:`static-value:${e.derivation.rule}`,strength:e.derivation.kind==="direct"?"exact":"derived",identity:e.derivation.inputFactIds.join(",")||e.value,location:{file:i.file,line:i.startLine,endLine:i.endLine}}))}function uo(e,t){e.has(t.id)||e.set(t.id,t)}function mu(e,t,n){let i=ut("edge","parameter-owner",t.symbol,n.id);e.has(i)||e.set(i,{id:i,kind:"parameter-owner",fromNodeId:pu(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 _0(e,t){return ut("parameter",e,String(t))}function pu(e){return ut("symbol",e)}function ut(...e){return e.map(t=>encodeURIComponent(t)).join(":")}function My(e,t){let n=new Map,i=new Map,r=new Map,o=new Set;for(let s of t){if(!s.location||!["source-construct","symbol"].includes(s.kind))continue;let a=s.location.endLine??s.location.line,c=nf(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=fu(s,l.controller),d=fu(s,l.outcome);n.set(u.id,u),n.set(d.id,d),O0(i,s,u);let m=Pi("edge","control-dependence",u.id,d.id,l.subtype);i.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=fu(s,l);n.set(u.id,u);let d=l.label.startsWith("throw")||l.label.startsWith("raise")?"throw":"return",m=Pi("edge","control-terminal",s.id,u.id,d);i.set(m,{id:m,kind:"control-terminal",fromNodeId:s.id,toNodeId:u.id,directed:!0,disposition:"folded",semantics:[{family:"control",subtype:d==="throw"?"throws":"returns"}],evidence:[{method:"parser-terminal-statement",strength:"exact",identity:l.label,location:{file:s.location.file,line:l.startLine,endLine:l.endLine}}]})}for(let l of c.unsupported){let u=Pi("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=Pi("edge","control-unsupported",s.id,u);i.set(d,{id:d,kind:"control-dependence",fromNodeId:s.id,toNodeId:u,directed:!0,disposition:"unsupported",semantics:[{family:"control",subtype:"unresolved-control-construct"}],evidence:[{method:"parser-control-construct",strength:"exact",identity:l.reason,location:{file:s.location.file,line:l.startLine,endLine:l.endLine}}]});let m=Pi("frontier","control-dependence",u);r.set(m,{id:m,kind:"control-dependence",direction:"unresolved",fromNodeIds:[s.id],edgeIds:[d],memberNodeIds:[u],memberCount:1,disposition:"unsupported",reason:l.reason,expansion:null})}}return{nodes:[...n.values()],edges:[...i.values()],frontiers:[...r.values()],blindSpots:[...o].sort()}}function fu(e,t){let n=e.location.file;return{id:Pi(`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 O0(e,t,n){let i=Pi("edge","control-owner",t.id,n.id);e.has(i)||e.set(i,{id:i,kind:"control-owner",fromNodeId:t.id,toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:"contains-control"}],evidence:[{method:"parser-control-owner",strength:"exact",identity:t.id,location:t.location}]})}function Pi(...e){return e.map(t=>encodeURIComponent(t)).join(":")}var Sa=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"]),po=new Set(["block","body","compound_statement","declaration_list","statement_block"]),B0=new Set(["assignment","assignment_expression","augmented_assignment_expression"]),hu=new Set(["update_expression"]),ky=new Set(["array_access","element_access_expression","subscript_expression"]),_y=new Set(["attribute","field_access","field_expression","member_access_expression","member_expression","selector_expression"]),$0=new Set(["false","null","null_literal","number","number_literal","string","string_literal","template_string","true"]),j0=new Set(["call_expression","method_invocation","object_creation_expression"]),H0=new Set(["comment","else_clause","formal_parameters","parameters","type_parameters"]);function Oy(e,t,n,i){let r=ae(e,t);if(!r)return null;let o=J0(r.rootNode,n,i);if(!o)return null;let s=[],a=[],c=[];return Di(o,l=>{if(B0.has(l.type)||hu.has(l.type)||$y(l)){let u=U0(l);u?s.push(u):c.push({family:"state",startLine:l.startPosition.row,endLine:l.endPosition.row,reason:`Mutation target ${cn(l.text)} could not be resolved to an exact source resource.`})}}),Di(o,l=>{if(!po.has(l.type))return;let u=W0(l);for(let d=0;d<u.length-1;d+=1)a.push({from:mo(u[d]),to:mo(u[d+1]),subtype:"lexical-successor",synchronizationScope:null,attributes:{sameScope:!0,executionConditional:!0}});for(let d=0;d<u.length;d+=1){let m=u[d],p=X0(m).filter(f=>f.type==="await_expression");for(let f of p){let g=fo("event",`await ${cn(f.text.replace(/^await\s+/u,""))}`,f);a.push({from:mo(m),to:g,subtype:"awaits-completion",synchronizationScope:null,attributes:{completionRequired:!0}});let h=u[d+1];h&&a.push({from:g,to:mo(h),subtype:"await-completion-before",synchronizationScope:null,attributes:{continuationOnly:!0}})}}}),Di(o,l=>{if(l.type!=="synchronized_statement")return;let u=l.childForFieldName("object")??l.childForFieldName("condition")??l.namedChildren.find(g=>!po.has(g.type)),d=l.childForFieldName("body")??l.namedChildren.find(g=>po.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=cn(u.text).replace(/^\(|\)$/gu,""),p=fo("lock",m,u),f=Y0(d).filter(g=>g.parent!==null&&jy(g));for(let g of V0(f))a.push({from:p,to:mo(g),subtype:"inside-lock-scope",synchronizationScope:m,attributes:{syntaxNative:!0}})}),{mutations:s,temporal:a,unsupported:c}}function U0(e){let t=$y(e),n=e.childForFieldName("left")??e.childForFieldName("argument")??(t?e.namedChildren.at(-1)??null:e.namedChildren[0]??null);if(!n)return null;let i=z0(n);if(!i)return null;let r=t?"delete":hu.has(e.type)||!q0(e,n).startsWith("=")?"update":"assign",o=t||hu.has(e.type)?null:e.childForFieldName("right");return{event:fo("event",cn(e.text),e),resource:{kind:"resource",label:i.name,startLine:n.startPosition.row,endLine:n.endPosition.row},operation:r,durabilityClass:"in-memory",recordIdentity:i.recordIdentity,value:o?fo("value",cn(o.text),o):null,dataSubtype:o?G0(o,e):null}}function z0(e){if(ky.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:`${cn(t.text)}[]`,recordIdentity:cn(n.text)}}return _y.has(e.type)?{name:cn(e.text),recordIdentity:null}:/^(?:identifier|property_identifier|field_identifier)$/u.test(e.type)?{name:cn(e.text),recordIdentity:null}:null}function G0(e,t){return $0.has(e.type)||/(?:integer|float|decimal|boolean|character)_literal$/u.test(e.type)?"constant-to-state":j0.has(e.type)?"return-to-state":_y.has(e.type)||ky.has(e.type)?"property-to-state":/identifier$/u.test(e.type)?K0(e.text,t)?"captured-value-to-state":"value-to-state":"expression-to-state"}function K0(e,t){let n=gu(t.parent);if(!n||Ay(n,e))return!1;let i=gu(n.parent);for(;i;){if(Ay(i,e))return!0;i=gu(i.parent)}return!1}function gu(e){let t=e;for(;t;){if(Sa.has(t.type))return t;t=t.parent}return null}function Ay(e,t){let n=e.childForFieldName("parameters")??e.namedChildren.find(o=>["formal_parameters","parameters"].includes(o.type));if(n&&Fy(n,t))return!0;let i=e.childForFieldName("body")??e.namedChildren.find(o=>po.has(o.type));if(!i)return!1;let r=!1;return By(i,e,o=>{if(r||!/(?:declarator|declaration|parameter)$/u.test(o.type))return;let s=o.childForFieldName("name")??o.childForFieldName("pattern")??o.namedChildren[0];s&&Fy(s,t)&&(r=!0)}),r}function Fy(e,t){let n=!1;return Di(e,i=>{/identifier$/u.test(i.type)&&i.text===t&&(n=!0)}),n}function By(e,t,n){n(e);for(let i of e.namedChildren)i!==t&&Sa.has(i.type)||By(i,t,n)}function q0(e,t){let n=e.childForFieldName("right"),i=Math.max(0,t.endIndex-e.startIndex),r=n?Math.max(i,n.startIndex-e.startIndex):e.text.length;return e.text.slice(i,r).trim()}function $y(e){return(e.type==="delete_expression"||e.type==="unary_expression")&&/^delete\b/u.test(e.text.trim())}function W0(e){return e.namedChildren.filter(t=>jy(t))}function jy(e){return H0.has(e.type)||po.has(e.type)?!1:/(?:statement|declaration)$/u.test(e.type)||e.type==="expression_statement"||e.type==="local_variable_declaration"}function V0(e){let t=new Set(e);return e.filter(n=>{let i=n.parent;for(;i;){if(t.has(i))return!1;i=i.parent}return!0})}function mo(e){return fo("event",cn(e.text),e)}function fo(e,t,n){return{kind:e,label:t,startLine:n.startPosition.row,endLine:n.endPosition.row}}function J0(e,t,n){let i=[];return Di(e,o=>{o.startPosition.row<=t&&o.endPosition.row>=n&&i.push(o)}),i.filter(o=>Sa.has(o.type)).sort(Ny)[0]??i.sort(Ny)[0]??null}function Ny(e,t){return e.endIndex-e.startIndex-(t.endIndex-t.startIndex)||e.startIndex-t.startIndex}function Y0(e){let t=[];return Di(e,n=>t.push(n)),t}function X0(e){let t=[],n=i=>{t.push(i);for(let r of i.namedChildren)r!==e&&Sa.has(r.type)||n(r)};return n(e),t}function Di(e,t){t(e);for(let n of e.namedChildren)Di(n,t)}function cn(e){return e.trim().replace(/\s+/gu," ")}function zy(e,t,n=[]){let i=new Map,r=new Map,o=new Map,s=new Set;for(let a of t){if(!a.location||!["source-construct","symbol"].includes(a.kind))continue;let c=a.location.endLine??a.location.line,l=Oy(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=Ca(a,u.event),m=iM(a,u.resource,u.durabilityClass);if(i.set(d.id,d),i.set(m.id,m),xa(r,a,d,"contains-state-effect"),Ra(r,{kind:"state-resource",from:d,to:m,semantics:[{family:"state",subtype:u.operation==="delete"?"deletes-resource":"writes-resource",attributes:{operation:u.operation,durabilityClass:u.durabilityClass,resource:u.resource.label,recordIdentity:u.recordIdentity,transactionMembership:"unknown"}}],method:"parser-state-mutation",identity:u.event.label}),u.value&&u.dataSubtype){let p=Ca(a,u.value);i.set(p.id,p),Ra(r,{kind:"data-to-state",from:p,to:m,semantics:[{family:"data",subtype:u.dataSubtype,attributes:{operation:u.operation,resource:u.resource.label,recordIdentity:u.recordIdentity,value:u.value.label}}],method:"parser-assignment-value",identity:`${u.value.label} -> ${u.resource.label}`})}}for(let u of l.temporal){let d=Ca(a,u.from),m=Ca(a,u.to);i.set(d.id,d),i.set(m.id,m),xa(r,a,d,u.from.kind==="lock"?"contains-lock-scope":"contains-event"),xa(r,a,m,"contains-event"),Ra(r,{kind:"temporal-order",from:d,to:m,semantics:[{family:"temporal",subtype:u.subtype,context:u.synchronizationScope?{synchronizationScope:u.synchronizationScope}:void 0,attributes:{...u.attributes}}],method:u.subtype==="inside-lock-scope"?"parser-synchronized-scope":"parser-program-order",identity:`${u.from.label} -> ${u.to.label}`})}for(let u of l.unsupported){let d=Dn(`${u.family}-unsupported`,a.location.file,String(u.startLine),String(u.endLine),u.reason);i.set(d,{id:d,kind:`${u.family}-unsupported`,label:u.reason,disposition:"unsupported",location:{file:a.location.file,line:u.startLine,endLine:u.endLine},anchorIds:[],attributes:{ownerNodeId:a.id}});let m=Dn("edge",`${u.family}-unsupported`,a.id,d);r.set(m,{id:m,kind:`${u.family}-unsupported`,fromNodeId:a.id,toNodeId:d,directed:!0,disposition:"unsupported",semantics:[{family:u.family,subtype:`unresolved-${u.family}-construct`}],evidence:[{method:`parser-${u.family}-construct`,strength:"exact",identity:u.reason,location:{file:a.location.file,line:u.startLine,endLine:u.endLine}}]});let p=Dn("frontier",u.family,d);o.set(p,{id:p,kind:u.family,direction:"unresolved",fromNodeIds:[a.id],edgeIds:[m],memberNodeIds:[d],memberCount:1,disposition:"unsupported",reason:u.reason,expansion:null})}}for(let a of t.filter(c=>c.kind==="runtime-boundary-participant")){let c=va(a,"protocol"),l=va(a,"action"),u=va(a,"address")??a.label;!c||!l||!Uy(c,l)||Hy(i,r,a,{observationId:a.id,action:l,strength:"exact",file:a.location?.file??"",line:a.location?.line??0,address:u,protocol:c,role:va(a,"role")??void 0,resolution:"locally-linked"})}for(let a of n){if(!a.protocol||!Uy(a.protocol,a.action))continue;let c=tM(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}Hy(i,r,c,a)}return{nodes:[...i.values()],edges:[...r.values()],frontiers:[...o.values()],blindSpots:[...s].sort()}}function Hy(e,t,n,i){let r=Z0(i),s={id:Dn("runtime-state-event",i.observationId),kind:"runtime-state-event",label:`${i.action} ${r}`,disposition:"folded",location:{file:i.file,line:i.line},anchorIds:[],attributes:{action:i.action,protocol:i.protocol??null,modality:i.modality??null,resolution:i.resolution??null}},a=i.protocol==="database"?"external-durable-intent":"external",c={id:Dn("runtime-state-resource",i.protocol??"unknown",r),kind:"runtime-state-resource",label:r,disposition:"folded",location:{file:i.file,line:i.line},anchorIds:[],attributes:{protocol:i.protocol??null,durabilityClass:a}};e.set(s.id,s),e.set(c.id,c),xa(t,n,s,"contains-runtime-state-effect");let l=Q0(i.action);Ra(t,{kind:"runtime-state-resource",from:s,to:c,semantics:[{family:"state",subtype:l,context:{crossesRuntimeBoundary:!0,protocol:i.protocol},attributes:{operation:i.action,durabilityClass:a,resource:r,recordIdentity:eM(i),modality:i.modality??null,resolution:i.resolution??null,transactionMembership:"unknown",commitState:i.protocol==="database"?"unknown":null}}],method:`runtime-boundary-${i.strength}`,identity:i.observationId})}function Q0(e){return e==="database.read"?"reads-resource":e==="queue.send"?"enqueues-resource":e==="queue.consume"?"consumes-resource":"writes-resource"}function Z0(e){return(e.keyParts?.find(n=>["address","resource"].includes(n.name))?.value??e.address)||e.observationId}function eM(e){return e.keyParts?.find(n=>/^(?:id|key|record)$/u.test(n.name))?.value??null}function Uy(e,t){return e==="database"&&["database.read","database.write"].includes(t)||e==="queue"&&["queue.consume","queue.send"].includes(t)}function va(e,t){let n=e.attributes[t];return typeof n=="string"?n:null}function tM(e,t,n,i){let r=e.filter(s=>s.location?.file===t&&["source-construct","symbol"].includes(s.kind)),o=r.filter(s=>s.location.line<=n&&(s.location.endLine??s.location.line)>=n).sort(nM)[0];if(o)return o;if(i){let s=r.find(a=>a.label===i||a.label.endsWith(`.${i}`)||a.label.includes(i));if(s)return s}return r.length===1?r[0]:null}function nM(e,t){let n=(e.location?.endLine??e.location?.line??0)-(e.location?.line??0),i=(t.location?.endLine??t.location?.line??0)-(t.location?.line??0);return n-i}function Ca(e,t){let n=e.location.file;return{id:Dn(`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 iM(e,t,n){let i=e.location.file;return{id:Dn("program-resource",i,e.id,t.label,n),kind:"program-resource",label:t.label,disposition:"folded",location:{file:i,line:t.startLine,endLine:t.endLine},anchorIds:[],attributes:{ownerNodeId:e.id,durabilityClass:n}}}function xa(e,t,n,i){let r=Dn("edge","program-owner",t.id,n.id,i);e.has(r)||e.set(r,{id:r,kind:"program-owner",fromNodeId:t.id,toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:i}],evidence:[{method:"parser-program-owner",strength:"exact",identity:t.id,location:n.location}]})}function Ra(e,t){let n=Dn("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 Dn(...e){return e.map(t=>encodeURIComponent(t)).join(":")}var rM=new Set(["control","data","state","temporal"]),Ea=new Set(["contains-control","contains-event","contains-lock-scope","contains-state-effect","contains-runtime-state-effect","contains","owns-parameter","owns-runtime-observation"]),Wy=new Set(["discriminator-dispatch","result-callback","returns","runtime-handoff","throws"]);function Vy(e,t={}){let n=new Map(e.nodes.map(C=>[C.id,C])),i=dM(e.nodes,t.focusLocations),r=mM(e.edges,t.focusLocations),o=pM(e.edges,r),s=new Set(e.paths.flatMap(C=>C.edgeIds)),a=Tn(e.anchors.filter(C=>C.status==="matched").flatMap(C=>C.nodeIds)),l=e.edges.filter(qy).filter(C=>oM(C,i,r,s)),u=l.filter(C=>lM(C,i,r,o,n,s)),d=Gy(a,u,"forward"),m=cM(d,u),p=Gy(m,u,"backward"),f=new Set([...d].filter(C=>p.has(C)));for(let C of a)f.add(C);let g=new Set(u.filter(C=>f.has(C.fromNodeId)&&f.has(C.toNodeId)).map(C=>C.id)),h=new Set(f),b=new Set(g);sM(l,h,b,i,r);let v=e.frontiers.filter(C=>gM(C,h)),y=Tn(v.filter(C=>C.disposition==="unsupported").map(C=>C.id)),E=Tn(e.edges.filter(C=>!qy(C)&&Yy(C)&&fM(C,h)).map(C=>C.id)),w=Tn(v.map(C=>C.id)),S=[];a.length===0&&S.push("No matched anchor node starts the corridor."),m.length===0&&S.push("No proved mechanical outcome is reachable from a matched anchor."),y.length>0&&S.push(`${y.length} unsupported frontier(s) touch the protected corridor.`),E.length>0&&S.push(`${E.length} candidate or unknown edge(s) touch the protected corridor.`);let R=S.length===0?"complete":"incomplete";return{schemaVersion:1,status:R,startNodeIds:a,outcomeNodeIds:m,baseNodeIds:Tn([...f]),baseEdgeIds:Tn([...g]),nodeIds:Tn([...h]),edgeIds:Tn([...b]),accountedFrontierIds:w,unresolvedFrontierIds:y,unresolvedEdgeIds:E,coverage:{protectedNodes:h.size,protectedEdges:b.size,baseNodes:f.size,baseEdges:g.size,accountedFrontiers:w.length,unresolvedFrontiers:y.length,unresolvedEdges:E.length},explanation:R==="complete"?"Every proved anchor-to-outcome path is closed over its material causal facts within reported coverage.":S.join(" ")}}function oM(e,t,n,i){return t===null||e.disposition==="emitted"||i.has(e.id)||n?.has(e.id)===!0?!0:(e.semantics??[]).some(r=>{if(r.family==="identity"&&Ea.has(r.subtype))return t.has(e.toNodeId);if(r.family==="contract")return t.has(e.fromNodeId)&&t.has(e.toNodeId);if(r.family==="state")return t.has(e.fromNodeId);if(r.family==="data"||r.family==="temporal")return t.has(e.fromNodeId)||t.has(e.toNodeId);if(r.family==="control"){if(Xy(r))return t.has(e.fromNodeId);if(["returns","throws"].includes(r.subtype))return t.has(e.toNodeId);if(r.subtype==="completion-callback")return t.has(e.fromNodeId)||t.has(e.toNodeId)}return!1})}function sM(e,t,n,i,r){let o=!0;for(;o;){o=!1;for(let s of e)aM(s,t,i,r)&&(n.has(s.id)||(n.add(s.id),o=!0),t.has(s.fromNodeId)||(t.add(s.fromNodeId),o=!0),t.has(s.toNodeId)||(t.add(s.toNodeId),o=!0))}}function aM(e,t,n,i){let r=t.has(e.fromNodeId),o=t.has(e.toNodeId);return!r&&!o?!1:(e.semantics??[]).some(s=>s.family==="identity"?Ea.has(s.subtype)&&(o||n===null||n.has(e.toNodeId)):s.family==="contract"?!0:s.family==="state"?r&&(n===null||n.has(e.fromNodeId)):s.family==="temporal"?s.subtype==="lexical-successor"?r&&o:!0:s.family==="data"?o&&(r||n===null||n.has(e.fromNodeId)||i?.has(e.id)===!0):s.family==="control"?Jy(s)||["returns","throws"].includes(s.subtype)&&!o&&n!==null&&!n.has(e.toNodeId)?!1:Wy.has(s.subtype)||Xy(s)||s.subtype==="completion-callback":!1)}function cM(e,t){let n=new Set,i=new Map,r=new Map;for(let o of t)!e.has(o.fromNodeId)||!e.has(o.toNodeId)||(i.set(o.fromNodeId,(i.get(o.fromNodeId)??0)+1),r.set(o.toNodeId,(r.get(o.toNodeId)??0)+1),(o.semantics??[]).some(s=>s.family==="state"||s.family==="control"&&Wy.has(s.subtype))&&n.add(o.toNodeId));for(let o of e)(r.get(o)??0)>0&&(i.get(o)??0)===0&&n.add(o);return Tn([...n])}function Gy(e,t,n){let i=new Map;for(let s of t){let a=n==="forward"?s.fromNodeId:s.toNodeId,c=n==="forward"?s.toNodeId:s.fromNodeId,l=i.get(a)??[];l.push(c),i.set(a,l)}let r=new Set(e),o=[...e];for(;o.length>0;){let s=o.shift();for(let a of i.get(s)??[])r.has(a)||(r.add(a),o.push(a))}return r}function lM(e,t,n,i,r,o){return(e.semantics??[]).some(s=>e.disposition==="emitted"||o.has(e.id)?!0:s.family==="identity"&&Ea.has(s.subtype)?t===null||t.has(e.toNodeId)||i?.has(e.toNodeId)===!0:!rM.has(s.family)||Jy(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"?uM(e,r)&&(t.has(e.fromNodeId)||t.has(e.toNodeId)):!1)}function Jy(e){return e.family==="control"&&["call","discriminator-dispatch","result-callback","runtime-handoff"].includes(e.subtype)}function uM(e,t){let n=t.get(e.fromNodeId),i=t.get(e.toNodeId);if(!n||!i)return!1;let r=Ky(n,"ownerNodeId")??(n.kind==="symbol"?n.id:null),o=Ky(i,"ownerNodeId")??(i.kind==="symbol"?i.id:null);return r!==null&&r===o}function dM(e,t){if(!t)return null;let n=new Map;for(let i of t){let r=n.get(i.file)??[];r.push(i.line),n.set(i.file,r)}return new Set(e.filter(i=>{if(!i.location||i.kind==="parameter")return!1;let r=n.get(i.location.file)??[],o=i.location.endLine??i.location.line;return r.some(s=>s>=i.location.line&&s<=o)}).map(i=>i.id))}function mM(e,t){if(!t)return null;let n=new Map;for(let i of t){let r=n.get(i.file)??[];r.push(i.line),n.set(i.file,r)}return new Set(e.filter(i=>i.evidence.some(r=>{if(!r.location)return!1;let o=n.get(r.location.file)??[],s=r.location.endLine??r.location.line;return o.some(a=>a>=r.location.line&&a<=s)})).map(i=>i.id))}function pM(e,t){return t===null?null:new Set(e.filter(n=>t.has(n.id)).flatMap(n=>[n.fromNodeId,n.toNodeId]))}function Ky(e,t){let n=e.attributes[t];return typeof n=="string"?n:null}function qy(e){return e.disposition==="excluded"||e.disposition==="unsupported"||!Yy(e)?!1:e.evidence.some(t=>t.strength==="exact"||t.strength==="derived")}function Yy(e){return(e.semantics??[]).some(t=>t.family!=="identity"||Ea.has(t.subtype))}function Xy(e){return e.subtype.startsWith("predicate-")||e.subtype.startsWith("loop-")||e.subtype.startsWith("exception-")||e.subtype.startsWith("finally-")||e.subtype.startsWith("handler-")}function fM(e,t){return t.has(e.fromNodeId)||t.has(e.toNodeId)}function gM(e,t){return[...e.fromNodeIds,...e.memberNodeIds].some(n=>t.has(n))}function Tn(e){return[...new Set(e)].sort()}import{createHash as hM}from"crypto";var wa=["identity","contract","control","data","state","temporal"],yM=new Set(wa);function La(e){let t=ar(e.anchors,"anchor"),n=ar(e.nodes,"node"),i=ar(e.edges,"edge"),r=ar(e.paths??[],"path"),o=ar(e.frontiers??[],"frontier"),s=new Set(t.map(p=>p.id)),a=new Set(n.map(p=>p.id)),c=new Set(i.map(p=>p.id)),l=e.routeCatalog?{...e.routeCatalog,routes:ar(e.routeCatalog.routes,"route"),selectedRouteIds:yt(e.routeCatalog.selectedRouteIds)}:void 0;for(let p of t)wt(`anchor ${p.id}`,[...p.nodeIds,...p.candidateNodeIds],a,"node");for(let p of n)wt(`node ${p.id}`,p.anchorIds,s,"anchor");for(let p of i){if(wt(`edge ${p.id}`,[p.fromNodeId,p.toNodeId],a,"node"),p.evidence.length===0)throw new Error(`Exploration edge ${p.id} has no evidence source.`);vM(p)}for(let p of r)wt(`path ${p.id}`,[p.fromAnchorId,p.toAnchorId],s,"anchor"),wt(`path ${p.id}`,p.nodeIds,a,"node"),wt(`path ${p.id}`,p.edgeIds,c,"edge");for(let p of o)if(wt(`frontier ${p.id}`,p.fromNodeIds,a,"node"),wt(`frontier ${p.id}`,p.edgeIds,c,"edge"),wt(`frontier ${p.id}`,p.memberNodeIds,a,"node"),p.memberCount!==p.memberNodeIds.length)throw new Error(`Exploration frontier ${p.id} reports ${p.memberCount} member(s) but identifies ${p.memberNodeIds.length}.`);for(let p of l?.routes??[])wt(`route ${p.id}`,p.nodeIds,a,"node"),wt(`route ${p.id}`,p.edgeIds,c,"edge"),wt(`route ${p.id}`,[p.anchorNodeId,p.endpointNodeId],a,"node");l&&wt("route catalog selection",l.selectedRouteIds,new Set(l.routes.map(p=>p.id)),"route");let u=yt(e.incompleteReasons??[]),d=u.length===0?"accounted":"incomplete",m=t.reduce((p,f)=>p+f.omittedCandidates,0);return{schemaVersion:1,anchors:t,nodes:n,edges:i,paths:r,frontiers:o,coverage:{status:d,scope:e.scope,nodes:sb(n),edges:sb(i),matchedAnchors:t.filter(p=>p.status==="matched").length,ambiguousAnchors:t.filter(p=>p.status==="ambiguous").length,missingAnchors:t.filter(p=>p.status==="missing").length,omittedCandidates:m,frontierGroups:o.length,programEdges:SM(i),blindSpots:yt(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:RM(d,r,e.scope),...l?{routeCatalog:l}:{}}}function bM(e){return e.flatMap(t=>CM(t.semantics??[]).map(n=>({id:xM(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 SM(e){let t=bM(e),n=new Set(t.map(s=>s.sourceEdgeId)),i=new Map(wa.map(s=>[s,new Set])),r=new Map(wa.map(s=>[s,new Set])),o=new Map(wa.map(s=>[s,0]));for(let s of t)i.get(s.family).add(s.sourceEdgeId),r.get(s.family).add(s.subtype),o.set(s.family,o.get(s.family)+1);return{sourceEdges:e.length,mappedSourceEdges:n.size,projectedEdges:t.length,unmappedSourceEdges:e.length-n.size,unsupportedSourceEdges:e.filter(s=>s.disposition==="unsupported").length,unmappedKinds:yt(e.filter(s=>!n.has(s.id)).map(s=>s.kind)),families:{identity:sr("identity",i,o,r),contract:sr("contract",i,o,r),control:sr("control",i,o,r),data:sr("data",i,o,r),state:sr("state",i,o,r),temporal:sr("temporal",i,o,r)}}}function sr(e,t,n,i){return{sourceEdges:t.get(e)?.size??0,projectedEdges:n.get(e)??0,subtypes:[...i.get(e)??[]].sort()}}function vM(e){let t=new Set;for(let n of e.semantics??[]){if(!yM.has(n.family))throw new Error(`Exploration edge ${e.id} has unknown program edge family: ${n.family}.`);if(n.subtype.trim().length===0)throw new Error(`Exploration edge ${e.id} has an empty program edge subtype.`);let i=yu(n);if(t.has(i))throw new Error(`Exploration edge ${e.id} repeats program edge semantic ${i}.`);t.add(i)}}function CM(e){return[...e].sort((t,n)=>yu(t).localeCompare(yu(n)))}function yu(e){return`${e.family}:${e.subtype}`}function xM(e,t){return`program:${encodeURIComponent(e)}:${t.family}:${encodeURIComponent(t.subtype)}`}function RM(e,t,n){return e==="incomplete"||t.some(i=>i.status!=="connected")?{status:"coverage-incomplete",scope:n,explanation:"The declared graph query has an ambiguous, missing, candidate-only, or disconnected anchor relationship."}:t.length>0?{status:"connector-complete",scope:n,explanation:"Every requested anchor pair has a selected path supported by proved repository relationships."}:{status:"frontier-accounted",scope:n,explanation:"Every discovered direction in the declared graph query is emitted or represented by an exact frontier."}}function ab(e,t={}){let n=t.maxSelectedNodes??24;if(!Number.isSafeInteger(n)||n<=0)throw new RangeError(`maxSelectedNodes must be a positive safe integer; received ${n}`);let i=new Set(e.anchors.flatMap(I=>[...I.nodeIds,...I.candidateNodeIds])),r=[],o=e.anchors.filter(I=>I.status!=="missing"&&I.nodeIds.length+I.candidateNodeIds.length>0);for(let I=0;I<o.length;I+=1)for(let x=I+1;x<o.length;x+=1){let D=o[I],_=o[x],P=nb(e,D,_,!1),F=P??nb(e,D,_,!0);F?(F.nodeIds.forEach(W=>i.add(W)),r.push({id:Ia("path",D.id,_.id),fromAnchorId:D.id,toAnchorId:_.id,status:!P||D.status==="ambiguous"||_.status==="ambiguous"?"candidate":"connected",nodeIds:F.nodeIds,edgeIds:F.edgeIds})):r.push({id:Ia("path",D.id,_.id),fromAnchorId:D.id,toAnchorId:_.id,status:"partial",nodeIds:[],edgeIds:[]})}let s=yt(t.routeIds??[]),a=EM(e,s),c=new Set(a.routes.map(I=>I.id)),l=s.filter(I=>!c.has(I));if(l.length>0)throw new Error(`Unknown exploration route id(s): ${l.join(", ")}`);let d=a.routes.filter(I=>s.includes(I.id)).map(I=>({anchorNodeId:I.anchorNodeId,endpointNodeId:I.endpointNodeId,endpointKind:I.endpointKind,endpointPriority:2,nodeIds:[...I.nodeIds].reverse(),edgeIds:[...I.edgeIds].reverse()}));for(let I of d)I.nodeIds.forEach(x=>i.add(x));let m=r.length===0||r.some(I=>I.edgeIds.length>0);m&&rb(e,i,n);let p=ob(e,i),f=new Set(t.expandedFrontierIds??[]),g=new Set(p.map(I=>I.id)),h=[...f].filter(I=>!g.has(I)).sort();if(h.length>0)throw new Error(`Unknown exploration frontier id(s): ${h.join(", ")}`);for(let I of p)f.has(I.id)&&I.memberNodeIds.forEach(x=>i.add(x));m&&rb(e,i,n);let b=new Map(d.map(I=>[I.endpointNodeId,I.endpointKind])),v=new Set(d.flatMap(I=>I.nodeIds)),y=new Map;for(let I of d)for(let x=0;x<I.nodeIds.length;x+=1){let D=I.nodeIds[x],_=x;y.set(D,Math.max(y.get(D)??0,_))}let E=e.nodes.map(I=>{let x=b.get(I.id),D=v.has(I.id)?{upstreamCausalPath:!0,upstreamCausalDistance:y.get(I.id)??0,...x?{upstreamCausalEndpoint:x}:{}}:{};return{...I,attributes:{...I.attributes,...D},disposition:I.disposition==="excluded"||I.disposition==="unsupported"?I.disposition:i.has(I.id)?"emitted":"folded"}}),w=new Set([...r.flatMap(I=>I.edgeIds),...d.flatMap(I=>I.edgeIds)]),S=e.edges.map(I=>({...I,disposition:I.disposition==="excluded"||I.disposition==="unsupported"?I.disposition:w.has(I.id)||i.has(I.fromNodeId)&&i.has(I.toNodeId)?"emitted":"folded"})),R=La({anchors:e.anchors,nodes:E,edges:S,paths:r,frontiers:[...e.frontiers.filter(I=>I.disposition!=="folded"),...ob({...e,nodes:E,edges:S},i)],scope:e.coverage.scope,blindSpots:e.coverage.blindSpots,incompleteReasons:e.coverage.status==="incomplete"?[e.coverage.explanation]:[],routeCatalog:a}),C=new Set(R.frontiers.flatMap(I=>I.edgeIds)),L=R.edges.filter(I=>I.disposition==="folded"&&!C.has(I.id)).map(I=>I.id);if(L.length>0)throw new Error(`Folded exploration edge(s) are not frontier-accounted: ${L.sort().join(", ")}`);return R}var Qy=10;function EM(e,t=[]){let n=new Map(e.nodes.map(h=>[h.id,h])),i=new Map(e.edges.map(h=>[h.id,h])),r=new Map;for(let h of e.edges){if(!wM(h))continue;let b=r.get(h.toNodeId)??[];b.push(h),r.set(h.toNodeId,b)}for(let h of r.values())h.sort((b,v)=>Number(go(v))-Number(go(b))||tb(v)-tb(b)||b.fromNodeId.localeCompare(v.fromNodeId)||b.id.localeCompare(v.id));let o=yt(e.anchors.filter(h=>h.status==="matched").flatMap(h=>h.nodeIds)),s=new Map,a=new Set,c=(h,b,v)=>{let y=b.nodeIds[b.nodeIds.length-1],E=n.get(y),w=n.get(h);if(!E?.location||!w)return;let S=[...b.nodeIds].reverse(),R=[...b.edgeIds].reverse(),C=new Set(S),L=R.flatMap(P=>{let T=i.get(P);return T?[T]:[]}),I=e.edges.filter(P=>P.disposition!=="excluded"&&P.disposition!=="unsupported"&&(C.has(P.fromNodeId)||C.has(P.toNodeId))),x={id:Ia("route",h,y,v,...R),status:"proved",anchorNodeId:h,anchorLabel:w.label,endpointNodeId:y,endpointLabel:E.label,endpointLocation:{...E.location},endpointKind:v,nodeIds:S,edgeIds:R,evidenceStrengths:yt(L.flatMap(P=>P.evidence.map(T=>T.strength))),spineEdgeFamilies:Zy(L,!0),relatedEdgeFamilies:Zy(I,!1),crossesRuntimeBoundary:L.some(go)},D=`${h}\0${y}\0${v}`,_=s.get(D);(!_||eb(x,_)<0)&&s.set(D,x)};for(let h of o){n.get(h)?.attributes.publicEntry===!0&&c(h,{nodeIds:[h],edgeIds:[]},"public-entry");let b=[{nodeIds:[h],edgeIds:[]}],v=new Map([[h,0]]);for(let y=0;y<b.length;y+=1){let E=b[y],w=E.nodeIds[E.nodeIds.length-1];E.edgeIds.length>0&&n.get(w)?.location&&n.get(w)?.attributes.publicEntry===!0&&c(h,E,"public-entry");let S=r.get(w)??[];if(E.edgeIds.length>=Qy){S.some(R=>!E.nodeIds.includes(R.fromNodeId))&&a.add(h);continue}for(let R of S){if(E.nodeIds.includes(R.fromNodeId))continue;let C=E.edgeIds.length+1,L=v.get(R.fromNodeId);if(L!==void 0&&L<=C)continue;let I={nodeIds:[...E.nodeIds,R.fromNodeId],edgeIds:[...E.edgeIds,R.id]};if(v.set(R.fromNodeId,C),go(R)&&n.get(R.fromNodeId)?.location){c(h,I,"runtime-boundary");continue}b.push(I)}}}let l=[...s.values()].sort(eb),u=new Set(l.map(h=>h.id)),d=yt(t.filter(h=>u.has(h))),m=yt(l.map(h=>h.anchorNodeId)),p=o.filter(h=>!m.includes(h)),f=[...a].sort(),g=e.coverage.status==="accounted"&&f.length===0?"accounted":"incomplete";return{schemaVersion:1,routes:l,selectedRouteIds:d,coverage:{status:g,scope:"Distinct proved public-entry and runtime-boundary endpoints reachable upstream in the supplied topology.",enumeration:"one-shortest-proved-path-per-endpoint",maximumDepth:Qy,anchorNodeIds:o,anchorsWithRoutes:m,anchorsWithoutRoutes:p,depthLimitedAnchorNodeIds:f,routeCount:l.length,explanation:g==="accounted"?"Every distinct proved upstream public/runtime endpoint in the supplied topology has one stable shortest route.":"Route enumeration is incomplete because the supplied topology has incomplete coverage or a traversal reached the route-depth bound."}}}function Zy(e,t){let n=e.flatMap(i=>i.semantics?.map(r=>r.family)??[]);return t&&e.length>0&&n.length===0&&n.push("control"),yt(n)}function eb(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 wM(e){return e.disposition!=="excluded"&&e.disposition!=="unsupported"&&IM(e)&&e.evidence.some(t=>["exact","derived","mixed"].includes(t.strength))}function IM(e){return go(e)||e.kind==="boundary-observation"||e.kind==="call"||e.kind==="compiler:call"}function go(e){return e.kind==="runtime-boundary"||e.kind.startsWith("runtime:")}function tb(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 nb(e,t,n,i){return ib(e,t,n,i)??ib(e,n,t,i)}function ib(e,t,n,i){let r=[...t.nodeIds,...t.candidateNodeIds].sort(),o=new Set([...n.nodeIds,...n.candidateNodeIds]);if(r.some(u=>o.has(u)))return{nodeIds:[r.find(d=>o.has(d))],edgeIds:[]};let s=new Set(e.nodes.filter(u=>u.kind==="structural-region").map(u=>u.id)),a=new Map;for(let u of e.edges)u.disposition==="excluded"||u.disposition==="unsupported"||u.kind==="structural-membership"||s.has(u.fromNodeId)||s.has(u.toNodeId)||u.evidence.every(m=>["candidate","unknown"].includes(m.strength))&&!i||LM(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=r.map(u=>({nodeId:u,nodeIds:[u],edgeIds:[]})),l=new Set(r);for(let u=0;u<c.length;u+=1){let d=c[u];for(let m of a.get(d.nodeId)??[]){if(l.has(m.nodeId))continue;let p={nodeId:m.nodeId,nodeIds:[...d.nodeIds,m.nodeId],edgeIds:[...d.edgeIds,m.edgeId]};if(o.has(m.nodeId))return p;l.add(m.nodeId),c.push(p)}}return null}function LM(e,t,n,i){let r=e.get(t)??[];r.push({nodeId:n,edgeId:i}),e.set(t,r)}function PM(e,t,n){let i=new Map;for(let a of e.edges){let c=i.get(a.fromNodeId)??{incoming:0,outgoing:0},l=i.get(a.toNodeId)??{incoming:0,outgoing:0};c.outgoing+=1,l.incoming+=1,i.set(a.fromNodeId,c),i.set(a.toNodeId,l)}let r=new Set,o=new Map;for(let a of e.edges){let c=t.has(a.fromNodeId),l=t.has(a.toNodeId);if(c===l)continue;let u=c?a.toNodeId:a.fromNodeId,d=c?a.fromNodeId:a.toNodeId,m=e.nodes.find(g=>g.id===u);if(m?.kind==="structural-region")continue;let p=o.get(u)??new Set;p.add(d),o.set(u,p),(/(?:runtime-boundary|external)/u.test(a.kind)||m&&/(?:frontier|external)/u.test(m.kind))&&r.add(u)}let s=[...o].filter(([a,c])=>{if(r.has(a))return!0;let l=i.get(a)??{incoming:0,outgoing:0};return(l.incoming>1||l.outgoing>1)&&c.size>1}).sort(([a,c],[l,u])=>Number(r.has(l))-Number(r.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 rb(e,t,n){let i=-1;for(;t.size!==i&&t.size<n;)i=t.size,PM(e,t,n)}function ob(e,t){let n=new Set(e.nodes.filter(s=>!t.has(s.id)&&s.disposition!=="excluded"&&s.disposition!=="unsupported").map(s=>s.id)),i=new Map;for(let s of e.edges){if(!n.has(s.fromNodeId)||!n.has(s.toNodeId))continue;let a=i.get(s.fromNodeId)??new Set,c=i.get(s.toNodeId)??new Set;a.add(s.toNodeId),c.add(s.fromNodeId),i.set(s.fromNodeId,a),i.set(s.toNodeId,c)}let r=[],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[...i.get(u)??[]].sort())o.has(d)||(o.add(d),c.push(d))}r.push(a.sort())}return r.map(s=>{let a=new Set(s),c=e.edges.filter(f=>a.has(f.fromNodeId)||a.has(f.toNodeId)),l=c.filter(f=>a.has(f.fromNodeId)!==a.has(f.toNodeId)),u=yt(l.map(f=>a.has(f.fromNodeId)?f.toNodeId:f.fromNodeId)),d=new Set(l.map(f=>a.has(f.toNodeId)?"outgoing":"incoming")),m=yt(c.map(f=>f.id)),p=yt(l.map(f=>f.kind));return{id:Ia("frontier",...s,...m),kind:p.join("+")||"disconnected",direction:d.size===1?[...d][0]:"undirected",fromNodeIds:u,edgeIds:m,memberNodeIds:s,memberCount:s.length,disposition:"folded",reason:l.length>0?"Connected evidence is folded beyond the first edge leaving the selected connector graph.":"Discovered evidence is disconnected from every selected anchor connector under the declared relation scope.",expansion:null}})}function Ia(e,...t){let n=hM("sha256").update(t.join("\0")).digest("hex").slice(0,16);return`${e}:${n}`}function ar(e,t){let n=[...e].sort((i,r)=>i.id.localeCompare(r.id));for(let i=1;i<n.length;i+=1)if(n[i-1].id===n[i].id)throw new Error(`Duplicate exploration ${t} id: ${n[i].id}`);return n}function wt(e,t,n,i){let r=yt(t.filter(o=>!n.has(o)));if(r.length>0)throw new Error(`Exploration ${e} references missing ${i}(s): ${r.join(", ")}`)}function sb(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 yt(e){return[...new Set(e)].sort()}var DM=5,TM=12,MM=8,AM=3,cb=8,FM=6,NM=12,lb=12,kM=12,_M=2,OM=new Set(["branch","loop","call","await","return","throw","mutation","catch","finally"]),BM=9e3,ub=by;function $M(e,t){return vb(e,t,"full")}function Sb(e,t){return vb(e,t,"topology")}function vb(e,t,n){let i=Ta(t.searches??[]),r=Ta(t.symbols??[]),o=Ta(t.relations&&t.relations.length>0?t.relations:ub),s=o.filter(A=>!ub.includes(A));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=Ta(t.sourceScopes&&t.sourceScopes.length>0?t.sourceScopes:["production"]),u=["production","test","fixture","example","generated","script","unknown"],d=l.filter(A=>!u.includes(A));if(d.length>0)throw new Error(`Unsupported system-map source scope(s): ${d.join(", ")}`);let m=new Set(l),p=A=>m.has(Oc(A));if(i.length===0&&r.length===0)throw new Error("system-map requires at least one --search or --symbol anchor.");let f=t.maxDepth??DM;if(!Number.isSafeInteger(f)||f<0)throw new RangeError(`maxDepth must be a non-negative safe integer; received ${f}`);let g=t.maxTopologyCharacters??BM;if(!Number.isSafeInteger(g)||g<=0)throw new RangeError(`maxTopologyCharacters must be a positive safe integer; received ${g}`);let h=new U(e),b=h.fileDependencyGraph(),v=RA(b),y=EA(h.sourceFiles()),E=fs(e),w=new Map((E?.observations??[]).map(A=>[A.id,A])),S=new Set((E?.observations??[]).map(A=>`${A.source.file}\0${A.source.startLine}`)),R=new Set,C=new Map,L=new Map,I=new Map,x=new Map,D=[],_=new Map,P=new Map,T=[],F=0,W=0,ce=0,q=0,Y=0,N=0,K=new Set,te=new Map,me=new Map,ge=A=>{let H=me.get(A);if(H)return H;let Z=Kn(e,A,{excludeIndexedTargets:!1});return me.set(A,Z),Z},le=(A,H,Z,we,j=!1)=>{let O=L.get(A);if(O)return O.depth=Math.min(O.depth,H),O.primary||=we,O.promoteBoundaryImports||=j,O.origins.add(Z),O;let G={file:A,depth:H,primary:we,promoteBoundaryImports:j,origins:new Set([Z]),processed:!1};return L.set(A,G),G},be=(A,H,Z,we,j="none",O=!1)=>{let G=I.get(A.symbol);if(G)return G.depth=Math.min(G.depth,H),G.origins.add(Z),we&&G.anchorQueries.add(we),G.referenceScope=xA(G.referenceScope,j),le(A.relativePath,H,Z,!0,O),G;let oe={definition:A,depth:H,origins:new Set([Z]),anchorQueries:new Set(we?[we]:[]),referenceScope:j,processed:!1};return I.set(A.symbol,oe),le(A.relativePath,H,Z,!0,O),oe},M=(A,H,Z,we,j=!1,O=!0)=>{let G=ln(A),oe=x.get(G);if(oe)return oe.depth=Math.min(oe.depth,H),oe.origins.add(Z),we&&oe.anchorQueries.add(we),oe.reverseCallExpansion||=j,oe.traversalEligible||=O,le(A.file,H,Z,oe.traversalEligible,!0),oe;let z={...A,depth:H,origins:new Set([Z]),anchorQueries:new Set(we?[we]:[]),reverseCallExpansion:j,traversalEligible:O};return x.set(G,z),le(A.file,H,Z,O,!0),z},Q=(A,H,Z)=>{le(A.source.file,H,Z,!0,!0),A.owner.file!==A.source.file&&le(A.owner.file,H,`${Z}:owner`,!0,!0);let we=J(e,A.owner.file),j=A.owner.symbol?Yn(e,h,A.owner.symbol).matches.find(oe=>oe.relativePath===A.owner.file):null,O=(j&&!Le(j.symbol)?j:null)??Ge(we,A.source.startLine);if(O&&!Le(O.symbol))return be(O,H,Z,void 0,"none",!0),O.symbol;A.owner.name&&M({file:A.owner.file,name:A.owner.name,startLine:A.owner.startLine,endLine:A.owner.endLine},H,`${Z}:source-owner`,void 0,!0);let G=h.definitionsForFile(A.source.file).filter(oe=>!!oe.leaf&&Sn(e,A.source.file,oe.leaf).some(z=>z>=A.source.startLine&&z<=A.source.endLine));if(G.length===1){let oe=G[0];be(oe,H,`${Z}:handler-identifier`,void 0,"none",!0),It(_,{kind:"runtime-boundary",evidence:"runtime-boundary:handler-identifier",fromFile:A.source.file,fromSymbol:null,toFile:oe.relativePath,toSymbol:oe.symbol,fromBoundaryParticipant:lr(A),line:A.source.startLine,strength:"derived"})}return null};for(let A of i){let H=oA(e,h,A,S),Z=H.filter(G=>uA(G,p)),we=!t.fullLiteralTraversal&&(H.length>TM||Z.length>MM),j=we?[]:H,O=new Set((we?[]:t.fullLiteralTraversal?Z:[...Z].sort(sA).slice(0,AM)).map(fb));we&&(W+=1,ce+=H.length);for(let G of j){let oe=O.has(fb(G)),z=oe&&!G.ownerSymbol&&G.ownerStartLine!==null&&G.ownerEndLine!==null;if(le(G.relativePath,0,`${oe?"literal-anchor":"literal-match"}:${A}`,z,z),z&&M({file:G.relativePath,name:G.ownerShortName??`${G.relativePath}:${G.ownerStartLine+1}`,startLine:G.ownerStartLine,endLine:G.ownerEndLine},0,`literal-source-owner:${A}`,A,!0),oe&&G.ownerSymbol){let ue=Yn(e,h,G.ownerSymbol).matches[0];ue&&!Le(ue.symbol)&&be(ue,0,"literal-owner",A,"all",!0)}D.push({query:A,file:G.relativePath,line:G.line,ownerSymbol:G.ownerSymbol,ownerShortName:G.ownerShortName,ownerStartLine:G.ownerStartLine,ownerEndLine:G.ownerEndLine,sourceLine:G.sourceLine.trim(),matchKind:G.matchKind,traversalSeed:oe})}T.push({kind:"literal",query:A,status:H.length>0?"matched":"missing",matchedRegionIds:[],matchingLines:H.length,seedMatchingLines:we?0:O.size,matchOnlyLines:H.length-O.size,eligibleSeedMatchingLines:Z.length,materializedMatchingLines:j.length,withheldMatchingLines:we?H.length:0,literalTraversal:we?"withheld-broad":"materialized",representativeMatches:we?dA(A,H):void 0,narrowingCommands:we?pA(A,H):void 0,exhaustiveTraversalCommand:we||O.size<Z.length?`codebaseiq system-map --search ${Ne(A)} --full-literal-traversal`:void 0,seedRegionIds:[],matchOnlyRegionIds:[]})}for(let A of r){let H=Yn(e,h,A);F+=H.omitted;let Z=aA(e,A),we=H.matches.filter(z=>!Le(z.symbol)),j=Z!==null&&we.length===0;j&&M(Z,0,"source-construct-anchor",A,!0);let O=j?we:H.matches;for(let z of O)be(z,0,"symbol-anchor",A,"all",!0);let G=j?cA(Z):null,oe=j?1:H.total;T.push({kind:"symbol",query:A,status:oe===0?"missing":oe===1?"matched":"ambiguous",matchedRegionIds:[],symbolCandidates:[...G?[G]:[],...O.map(bA)],totalSymbolCandidates:oe,omittedSymbolCandidates:H.omitted})}for(let A=0;A<f;A+=1){if(a.has("call")){let j=[...x.values()].filter(O=>O.traversalEligible&&O.reverseCallExpansion&&O.depth<=A&&!K.has(ln(O)));for(let O of j){K.add(ln(O));let G=ee(e,O.file);if((G?.callables??[]).filter(ue=>ue.name===O.name&&ue.startLine<=O.endLine&&ue.endLine>=O.startLine).length===1){let ue=(G?.callSites??[]).filter(xe=>xe.calleeLeaf===O.name&&!xe.memberAccess);for(let xe of ue){let Te=A+1,ve=Ge(J(e,O.file),xe.line),De=null,We=null;if(ve&&!Le(ve.symbol)){if(ve.relativePath===O.file&&ve.startLine<=O.endLine&&ve.endLine>=O.startLine)continue;be(ve,Te,"reverse-local-call-owner",void 0,"forward-regions",!0),De=ve.symbol}else{let B=bu(e,O.file,xe.line);B&&ln(B)!==ln(O)&&(We=M(B,Te,"reverse-local-call-source-owner",void 0,!0))}!De&&!We||It(_,{kind:"call",evidence:"ast-callsite",fromFile:O.file,fromSymbol:De,toFile:O.file,toSymbol:null,fromSourceConstruct:We?bt(We):void 0,toSourceConstruct:bt(O),line:xe.line,strength:"derived"})}}let z=new Set([...v.get(O.file)??[],...te.get(ln(O))??[],...th(e,O.file).flatMap(ue=>[...v.get(ue)??[]])]);for(let ue of z){if(!p(ue))continue;let Te=ge(ue).targets.filter(ve=>ve.targetFile===O.file&&ve.targetStartLine<=O.endLine&&ve.targetEndLine>=O.startLine);for(let ve of Te){let De=A+1,We=Ge(J(e,ue),ve.line),B=null,Ie=null;if(We&&!Le(We.symbol))be(We,De,"reverse-member-call-owner",void 0,"cross-workspace-or-forward",!0),B=We.symbol;else{let ne=bu(e,ue,ve.line);ne&&(Ie=M(ne,De,"reverse-member-call-source-owner",void 0,!0))}!B&&!Ie||It(_,{kind:"call",evidence:"ast-service-member-callsite",fromFile:ue,fromSymbol:B,toFile:O.file,toSymbol:null,fromSourceConstruct:Ie?bt(Ie):void 0,toSourceConstruct:bt(O),line:ve.line,strength:ve.strength==="exact"?"exact":"derived"})}}}}let H=[...I.values()].filter(j=>!j.processed&&j.depth<=A),Z=a.has("call")?h.calleeMap(H.map(j=>j.definition),{additive:!1,semantic:!1}):new Map;for(let j of H){j.processed=!0;let O=j.definition;if(j.referenceScope!=="none"&&(a.has("call")||a.has("reference")||a.has("contract-symbol"))){let G=gA(e,h,O).filter(z=>p(z.file)&&CA(j,z.file,L,y)),oe=new Set(G.flatMap(z=>{if(!(a.has("call")&&ee(e,z.file)?.callSites.some(Te=>Te.line===z.line&&Te.calleeLeaf===O.leaf)===!0)||!z.enclosingSymbol)return[];let xe=Yn(e,h,z.enclosingSymbol).matches[0];return xe&&!Le(xe.symbol)?[{owner:xe,site:z}]:[]}).sort((z,ue)=>{let xe=Pt(O.relativePath,y).relativeDir,Te=Pt(z.owner.relativePath,y).relativeDir===xe,ve=Pt(ue.owner.relativePath,y).relativeDir===xe,De=db(e,z.owner),We=db(e,ue.owner),B=z.owner.endLine-z.owner.startLine,Ie=ue.owner.endLine-ue.owner.startLine;return Number(ve)-Number(Te)||We-De||B-Ie||z.owner.symbol.localeCompare(ue.owner.symbol)}).filter((z,ue,xe)=>xe.findIndex(Te=>Te.owner.symbol===z.owner.symbol)===ue).reduce((z,ue)=>{if(z.length>=_M)return z;let xe=Pt(ue.owner.relativePath,y).relativeDir;return z.some(Te=>Te.workspace===xe)||z.push({symbol:ue.owner.symbol,workspace:xe}),z},[]).map(z=>z.symbol));for(let z of G){let ue=A+1;le(z.file,ue,`reference:${k(O.symbol)}`,!0);let xe=a.has("call")&&ee(e,z.file)?.callSites.some(De=>De.line===z.line&&De.calleeLeaf===O.leaf)===!0,Te=null,ve=null;if(z.enclosingSymbol){let De=Yn(e,h,z.enclosingSymbol).matches[0];De&&!Le(De.symbol)&&(be(De,ue,"reference-owner",void 0,xe&&oe.has(De.symbol)?j.referenceScope:"none"),Te=De.symbol)}if(!Te&&z.line!==null){let De=bu(e,z.file,z.line);De&&(ve=M(De,ue,"reference-source-owner",void 0,xe))}a.has("reference")&&It(_,{kind:"reference",evidence:"indexed-or-source-reference",fromFile:z.file,fromSymbol:Te,toFile:O.relativePath,toSymbol:O.symbol,fromSourceConstruct:ve?bt(ve):void 0,line:z.line,strength:"mixed"}),xe&&It(_,{kind:"call",evidence:"ast-callsite",fromFile:z.file,fromSymbol:Te,toFile:O.relativePath,toSymbol:O.symbol,fromSourceConstruct:ve?bt(ve):void 0,line:z.line,strength:"derived"}),a.has("contract-symbol")&&Pt(z.file,y).relativeDir!==Pt(O.relativePath,y).relativeDir&&It(_,{kind:"contract-symbol",evidence:"compiler-cross-workspace-symbol",fromFile:z.file,fromSymbol:Te,toFile:O.relativePath,toSymbol:O.symbol,fromSourceConstruct:ve?bt(ve):void 0,line:z.line,strength:"exact"})}}for(let G of Z.get(O.symbolId)??[]){let oe=Yn(e,h,G.symbol).matches.find(ue=>ue.relativePath===G.file);if(!oe||!p(oe.relativePath))continue;if(!(oe.relativePath===O.relativePath||(b.get(O.relativePath)??new Set).has(oe.relativePath))){q+=1;continue}be(oe,A+1,`call:${k(O.symbol)}`,void 0,"none",!0),It(_,{kind:"call",evidence:G.source,fromFile:O.relativePath,fromSymbol:O.symbol,toFile:oe.relativePath,toSymbol:oe.symbol,line:null,strength:XM(G.source)})}}let we=[...L.values()].filter(j=>!j.processed&&j.primary&&j.depth<=A);for(let j of we){j.processed=!0;let O=[...x.values()].filter(B=>B.traversalEligible&&B.file===j.file&&B.depth<=A),G=[...I.values()].filter(B=>B.definition.relativePath===j.file&&B.depth<=A).map(B=>{let Ie=Ji(e,j.file,B.definition.startLine);return{startLine:Ie?.startLine??B.definition.startLine,endLine:Ie?.endLine??B.definition.endLine}}),oe=B=>[...I.values()].filter(Ie=>Ie.definition.relativePath===j.file&&Ie.definition.startLine<=B&&Ie.definition.endLine>=B).sort((Ie,ne)=>Ie.definition.endLine-Ie.definition.startLine-(ne.definition.endLine-ne.definition.startLine)||Ie.definition.startLine-ne.definition.startLine)[0],z=[...w.values()].filter(B=>B.source.file===j.file&&C.has(B.id)),ue=[...O.map(B=>({startLine:B.startLine,endLine:B.endLine})),...z.map(B=>({...Da(e,B)}))],xe=[...G,...ue],Te=(ee(e,j.file)?.callSites??[]).filter(B=>xe.some(Ie=>B.line>=Ie.startLine&&B.line<=Ie.endLine)),ve=new Set;if(a.has("call"))for(let B of xe){let Ie=In(e,j.file,B.startLine,B.endLine);for(let ne of Ie.targets){if(!p(ne.definition.relativePath))continue;let Ve=oe(ne.sourceLine),jt=O.find(Tt=>Tt.startLine<=ne.sourceLine&&Tt.endLine>=ne.sourceLine),St=z.find(Tt=>{let st=Da(e,Tt);return st.startLine<=ne.sourceLine&&st.endLine>=ne.sourceLine});be(ne.definition,A+1,`scip-occurrence-call:${j.file}:${ne.sourceLine+1}`,void 0,"none",!0),It(_,{kind:"call",evidence:"scip-occurrence-callsite",fromFile:j.file,fromSymbol:Ve?.definition.symbol??null,toFile:ne.definition.relativePath,toSymbol:ne.definition.symbol,fromBoundaryParticipant:St?lr(St):void 0,fromSourceConstruct:jt?bt(jt):void 0,line:ne.sourceLine,strength:"exact"}),ve.add(`${ne.sourceLine}\0${ne.calleeLeaf}`)}}if(a.has("reference"))for(let B of xe){let Ie=lh(e,j.file,B.startLine,B.endLine);for(let ne of Ie.targets){if(!p(ne.definition.relativePath)||ve.has(`${ne.sourceLine}\0${ne.calleeLeaf}`))continue;let Ve=oe(ne.sourceLine);if(Ve?.definition.symbol===ne.definition.symbol)continue;let jt=O.find(Tt=>Tt.startLine<=ne.sourceLine&&Tt.endLine>=ne.sourceLine),St=z.find(Tt=>{let st=Da(e,Tt);return st.startLine<=ne.sourceLine&&st.endLine>=ne.sourceLine});be(ne.definition,A+1,`scip-occurrence-reference:${j.file}:${ne.sourceLine+1}`,void 0,"none",!0),It(_,{kind:"reference",evidence:"scip-occurrence-reference",fromFile:j.file,fromSymbol:Ve?.definition.symbol??null,toFile:ne.definition.relativePath,toSymbol:ne.definition.symbol,fromBoundaryParticipant:St?lr(St):void 0,fromSourceConstruct:jt?bt(jt):void 0,line:ne.sourceLine,strength:"exact"})}}let De=a.has("call")?Kn(e,j.file,{ranges:xe,excludeIndexedTargets:!1}):{targets:[],unresolvedCallsites:0};N+=De.unresolvedCallsites;let We=De.targets.filter(B=>!ve.has(`${B.line}\0${B.calleeLeaf}`));Y+=We.filter(B=>B.strength!=="exact"&&(B.resolution!=="imported-service-object-member"||(B.resolutionAlternativeCount??0)>1)).length;for(let B of We){let Ie=(B.resolutionAlternativeCount??1)===1,ne=B.targetSymbol?J(e,B.targetFile).find(st=>st.symbol===B.targetSymbol):void 0,Ve=ne?null:M({file:B.targetFile,name:B.calleeLeaf,startLine:B.targetStartLine,endLine:B.targetEndLine},A+1,`member-call:${j.file}`,void 0,B.resolution==="imported-service-object-member"&&Ie,Ie);if(Ve&&B.serviceFile){let st=ln(Ve),Rr=te.get(st)??new Set;for(let GR of v.get(B.serviceFile)??[])Rr.add(GR);te.set(st,Rr)}ne&&be(ne,A+1,`member-call:${j.file}`,void 0,"none",!0);let jt=O.find(st=>st.startLine<=B.line&&st.endLine>=B.line),St=oe(B.line),Tt=z.find(st=>{let Rr=Da(e,st);return Rr.startLine<=B.line&&Rr.endLine>=B.line});It(_,{kind:"call",evidence:B.resolution==="constructed-member-receiver"?"ast-constructed-member-callsite":B.resolution==="factory-callback-member"?"ast-factory-callback-callsite":B.resolution==="imported-service-object-member"?"ast-service-member-callsite":"ast-member-import-candidate",fromFile:j.file,fromSymbol:St?.definition.symbol??null,toFile:B.targetFile,toSymbol:ne?.symbol??null,fromBoundaryParticipant:Tt?lr(Tt):void 0,fromSourceConstruct:jt?bt(jt):void 0,toSourceConstruct:Ve?bt(Ve):void 0,line:B.line,strength:B.resolution==="imported-service-object-member"?(B.resolutionAlternativeCount??0)===1?"derived":"candidate":B.strength??"candidate"})}for(let B of a.has("import")||a.has("call")?hA(e,j.file):[]){if(!B.fromFile){if(a.has("import")){let ne=P.get(B.shortName)??{name:B.shortName,fromFiles:new Set};ne.fromFiles.add(j.file),P.set(B.shortName,ne)}continue}if(!p(B.fromFile))continue;if(a.has("import")&&(le(B.fromFile,A+1,`import:${j.file}`,!1),It(_,{kind:"import",evidence:"indexed-or-source-import",fromFile:j.file,fromSymbol:null,toFile:B.fromFile,toSymbol:B.symbol,line:null,strength:"mixed"})),a.has("call")&&Te.length>0){let ne=(B.source==="compiler"?Yn(e,h,B.symbol).matches:$n(e,B.fromFile,B.importedName)).filter(Ve=>!Le(Ve.symbol));for(let Ve of ne){let jt=Te.filter(St=>St.calleeLeaf===B.localName).map(St=>St.line);if(jt.length!==0){be(Ve,A+1,`source-call:${j.file}`,void 0,"none",!0);for(let St of jt)It(_,{kind:"call",evidence:"ast-callsite",fromFile:j.file,fromSymbol:null,toFile:Ve.relativePath,toSymbol:Ve.symbol,line:St,strength:"derived"})}}}if(!j.promoteBoundaryImports||!SA(j.file,B.fromFile,y))continue;let Ie=Yn(e,h,B.symbol);for(let ne of Ie.matches)if(vA(ne.relativePath,B.fromFile,y)&&!Le(ne.symbol)){let Ve=Pt(j.file,y).relativeDir!==Pt(ne.relativePath,y).relativeDir;be(ne,A+1,`boundary-import:${j.file}`,void 0,Ve?"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"||R.has(j.id))continue;let O=w.get(j.from),G=w.get(j.to);if(!O||!G||!p(O.source.file)||!p(G.source.file))continue;let oe=yb(O,A,C,I,x),z=yb(G,A,C,I,x);if(oe===null&&z===null)continue;let ue=A+1,xe=Q(O,oe??ue,`runtime-boundary:${j.joinRule}`),Te=Q(G,z??ue,`runtime-boundary:${j.joinRule}`),ve=xe?null:hb(x,O),De=Te?null:hb(x,G);C.set(O.id,oe??ue),C.set(G.id,z??ue),It(_,{kind:"runtime-boundary",evidence:`runtime-boundary:${j.joinRule}`,fromFile:O.source.file,fromSymbol:xe,toFile:G.source.file,toSymbol:Te,fromBoundaryParticipant:lr(O),toBoundaryParticipant:lr(G),fromSourceConstruct:ve?bt(ve):void 0,toSourceConstruct:De?bt(De):void 0,runtimeBoundaryKey:j.matchedKeyParts.map(We=>`${We.name}=${We.value}`).join(" "),line:O.source.startLine,strength:j.strength}),R.add(j.id)}}let X=new Map;for(let A of L.keys())X.set(A,ho(A,y));let Se=[..._.values()].filter(A=>X.has(A.fromFile)&&X.has(A.toFile)).map(A=>({...A,fromRegionId:X.get(A.fromFile).id,toRegionId:X.get(A.toFile).id})).sort(Eb),tt=TA(Se),ai=new Set(t.expand??[]),_n=IA(L,I,D,Se,tt,X,ai),_i=new Set([...L.values()].filter(A=>[...A.origins].some(H=>H.startsWith("literal-anchor:")||H==="literal-owner"||H==="symbol-anchor")).map(A=>X.get(A.file).id)),bm=tA(_n),FR=new Set(_n.map(A=>A.id)),NR=[...ai].filter(A=>!FR.has(A)).sort();for(let A of T)if(A.matchedRegionIds=AA(A,D,I,X),A.kind==="literal"){let H=D.filter(Z=>Z.query===A.query);A.seedRegionIds=Pe(H.filter(Z=>Z.traversalSeed).map(Z=>X.get(Z.file).id)),A.matchOnlyRegionIds=Pe(H.filter(Z=>!Z.traversalSeed).map(Z=>X.get(Z.file).id))}let Sm=[...I.values()].filter(A=>!A.processed).length,vm=[...L.values()].filter(A=>A.primary&&!A.processed).length,Cm=[...L.values()].filter(A=>!A.primary&&!A.processed).length,xm=[...I.values()].filter(A=>A.processed),Wo=(E?.frontiers??[]).flatMap(A=>{let H=w.get(A.observationId);return!H&&A.source&&A.action&&A.strength?!a.has("runtime-boundary")||!p(A.source.file)||c==="exact"||!L.has(A.source.file)?[]:[{observationId:A.observationId,action:A.action,strength:A.strength,file:A.source.file,line:A.source.startLine,ownerShortName:A.ownerShortName??null,address:A.address??A.missingKeyParts.join(", "),reason:A.reason}]:!a.has("runtime-boundary")||!H||!p(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:Rb(H),reason:A.reason,protocol:H.protocol,role:H.role,modality:H.modality,resolution:H.resolution,sourceScope:H.sourceScope,keyParts:H.keyParts.map(Z=>({name:Z.name,value:Z.value,evidence:Z.evidence}))}]}).sort((A,H)=>A.file.localeCompare(H.file)||A.line-H.line),Ec=(E?.links??[]).filter(A=>{if(!a.has("runtime-boundary")||c==="exact"&&A.strength!=="exact")return!1;let H=w.get(A.from),Z=w.get(A.to);return!!(H&&Z&&p(H.source.file)&&p(Z.source.file)&&(L.has(H.source.file)||L.has(Z.source.file)))}),kR=Ec.filter(A=>A.strength==="exact").length,_R=Ec.filter(A=>A.strength==="derived").length,OR=Ec.filter(A=>A.strength==="candidate").length,BR=E?.links.filter(A=>A.strength==="exact").length??0,$R=E?.links.filter(A=>A.strength==="derived").length??0,jR=E?.links.filter(A=>A.strength==="candidate").length??0,wc=MA(P,X),Ic=F===0?"accounted":"incomplete",Rm=[...W>0?[`${W} 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 ${f}; nonzero frontier counts identify evidence that was discovered but not traversed.`,"Region labels are structural path groupings, not inferred runtime or architectural boundaries."],Dt=GM({db:e,anchors:T,regions:_n,symbolStates:I,sourceConstructStates:x,literalHits:D,relations:Se,externalBoundaries:wc,boundaryFrontiers:Wo,regionForFile:X,closureStatus:Ic,omittedSymbolCandidates:F,maxDepth:f,requestedRelationKinds:o,evidenceFloor:c,includedSourceScopes:l,blindSpots:Rm,topologyFrontiers:t.topologyFrontiers??[],routeIds:t.routeIds??[],expandedRegionIds:[...ai],maxTopologyCharacters:g,fullLiteralTraversal:t.fullLiteralTraversal??!1});if(n==="topology")return Dt;let Em=(t.behaviorFocusLocations?.length??0)>0?new Set([...Dt.anchors.flatMap(A=>A.nodeIds),...Dt.paths.flatMap(A=>A.nodeIds)]).size:void 0,Vo=hh(e,Dt,{focusLocations:t.behaviorFocusLocations,...Em?{maxSteps:Em}:{}});Yh(e,Dt,Vo);let HR=jM(e,Dt,Vo,t.behaviorFocusLocations??[]);Dt.corridor=Vy(Dt,{focusLocations:HR});let wm=Jh(e,Dt,Vo,{sourceAllowed:p,selectionTerms:t.selectionTerms}),Im=JM(Dt),UR=ZM(i,r,f,o,c,l,t.fullLiteralTraversal??!1,g,_n,tt,_i,ai,Im),zR=QM(i,r,f,_n.filter(A=>Im.has(A.id)),_i,o,c,l,t.fullLiteralTraversal??!1,g);return{anchors:T,regions:_n,regionRelations:tt,externalBoundaries:wc,boundaryFrontiers:Wo,unmatchedExpansions:NR,expansion:zR,drilldown:bm,presentation:UR,topology:Dt,behavior:Vo,nextAnchors:wm,closure:{status:Ic,emitted:{regions:_n.length,relations:Se.length,runtimeLinks:R.size},withheld:{symbols:Sm,files:vm+Cm,regions:Dt.nodes.filter(A=>A.kind==="structural-region"&&A.disposition==="folded").length,drillAnchors:(bm?.omittedAnchors??0)+wm.omittedAnchors,literalMatches:ce},ambiguous:{anchors:T.filter(A=>A.status==="ambiguous").length,omittedSymbolCandidates:F},external:wc.length,unresolved:Wo.length,explanation:Ic==="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:T.length,requestedRelationKinds:o,evidenceFloor:c,includedSourceScopes:l,matchedAnchorCount:T.filter(A=>A.status!=="missing").length,literalSearchesComplete:!0,broadLiteralAnchors:W,withheldLiteralMatches:ce,symbolCandidateSetsComplete:F===0,omittedSymbolCandidates:F,maxTraversalDepth:f,frontierSymbols:Sm,frontierFiles:vm,supportFilesNotTraversed:Cm,filteredUnverifiedCallEdges:q,memberCallCandidateEdges:Y,unresolvedMemberCallsites:N,runtimeBoundaryEvidenceAvailable:E!==null,runtimeBoundaryObservations:E?.observations.length??0,runtimeBoundaryExactLinks:kR,runtimeBoundaryDerivedLinks:_R,runtimeBoundaryCandidateLinks:OR,repositoryRuntimeBoundaryExactLinks:BR,repositoryRuntimeBoundaryDerivedLinks:$R,repositoryRuntimeBoundaryCandidateLinks:jR,runtimeBoundaryTraversedLinks:R.size,runtimeBoundaryFrontiers:Wo.length,referenceExpansionEligibleSymbols:xm.filter(A=>A.referenceScope!=="none").length,referenceExpansionSkippedSymbols:xm.filter(A=>A.referenceScope==="none").length,dynamicDispatchRepresented:E?.links.some(A=>A.joinRule==="carrier.discriminator"&&R.has(A.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:Rm}}}function jM(e,t,n,i){let r=new Map,o=c=>{r.set(`${c.file}\0${c.line}`,c)};for(let c of i)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=>OM.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=Ns(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[...r.values()].sort((c,l)=>c.file.localeCompare(l.file)||c.line-l.line)}function HM(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 ln(e){return`${e.file}\0${e.startLine}\0${e.endLine}\0${e.name}`}function bt(e){return{file:e.file,name:e.name,startLine:e.startLine,endLine:e.endLine}}function Pa(e,t){let n=xu(ee(e,t.file)?.callables??[],t.startLine);if(n&&n.endLine>=t.endLine)return{file:t.file,name:/^source@\d+$/u.test(n.name)&&!/^source@\d+$/u.test(t.name)?t.name:n.name,startLine:n.startLine,endLine:n.endLine};let i=xb(e,t.file,t.startLine);return i&&i.endLine>=t.endLine?{file:t.file,name:i.name,startLine:i.startLine,endLine:i.endLine}:bt(t)}function cr(e){return Lt("source-construct",e.file,String(e.startLine),String(e.endLine),e.name)}function Ma(e,t){let n=Zi(e,t.symbol,t.relativePath),i=new Set(["package-surface-file","transitive-package-surface"]),r=n.filter(s=>!i.has(s)||Rt(e,t)),o=r.some(s=>!i.has(s));return{evidence:r,priority:o||Mg(e,t.symbol,t.relativePath)?2:1}}function db(e,t){let n=Ma(e,t);return n.evidence.length>0?n.priority:0}function UM(e,t){let n=J(e,t.file),i=n.filter(r=>r.startLine<=t.startLine&&r.endLine>=t.startLine).sort((r,o)=>r.endLine-r.startLine-(o.endLine-o.startLine)||r.startLine-o.startLine);for(let r of i){let o=Ma(e,r);if(o.evidence.length>0)return o}for(let r of zM(e,t.file,t.startLine)){let o=n.filter(s=>s.leaf===r.name).sort((s,a)=>Math.abs(s.startLine-r.startLine)-Math.abs(a.startLine-r.startLine)||s.symbol.localeCompare(a.symbol));for(let s of o){let a=Ma(e,s);if(a.evidence.length>0)return a}return{evidence:[],priority:0}}return{evidence:[],priority:0}}function zM(e,t,n){let i=ae(e,t)?.rootNode;if(!i||i.startPosition.row>n||i.endPosition.row<n)return[];let r=[],o=Ru(i,n);for(;o;){if(o.type==="variable_declarator"||o.type==="function_declaration"||o.type==="generator_function_declaration"||o.type==="class_declaration"){let s=o.childForFieldName("name")??o.namedChild(0);(s?.type==="identifier"||s?.type==="type_identifier")&&r.push({name:s.text,startLine:o.startPosition.row})}o=o.parent}return r}function GM(e){let t=[...new Map([...e.sourceConstructStates.values()].map(x=>Pa(e.db,x)).map(x=>[ln(x),x])).values()].sort((x,D)=>x.file.localeCompare(D.file)||x.startLine-D.startLine||x.endLine-D.endLine),n=e.anchors.map((x,D)=>{let _=Lt("anchor",String(D),x.kind,x.query),P=[...e.symbolStates.values()].filter(q=>q.anchorQueries.has(x.query)).flatMap(q=>{if(!Le(q.definition.symbol))return[Xn(q.definition.symbol)];let Y=t.filter(N=>N.file===q.definition.relativePath).map(N=>cr(N));return Y.length>0?Y:[Xn(q.definition.symbol)]}),T=[...e.sourceConstructStates.values()].filter(q=>q.anchorQueries.has(x.query)).map(q=>cr(Pa(e.db,q))),F=e.literalHits.filter(q=>q.query===x.query&&q.traversalSeed===!0&&q.ownerSymbol&&e.symbolStates.has(q.ownerSymbol)).map(q=>Xn(q.ownerSymbol)),W=e.literalHits.filter(q=>q.query===x.query&&q.traversalSeed===!0&&!q.ownerSymbol&&q.ownerStartLine!==null&&q.ownerStartLine!==void 0&&q.ownerEndLine!==null&&q.ownerEndLine!==void 0).map(q=>cr(Pa(e.db,HM(q)))),ce=Pe(x.kind==="symbol"?[...P,...T]:F.length+W.length>0?[...F,...W]:x.seedRegionIds??[]);return{id:_,kind:x.kind,query:x.query,status:x.status,nodeIds:x.status==="ambiguous"?[]:ce,candidateNodeIds:x.status==="ambiguous"?ce:[],omittedCandidates:x.omittedSymbolCandidates??0}}),i=new Map;for(let x of n)for(let D of[...x.nodeIds,...x.candidateNodeIds]){let _=i.get(D)??[];_.push(x.id),i.set(D,_)}let r=e.relations.flatMap(x=>[x.fromBoundaryParticipant,x.toBoundaryParticipant].flatMap(D=>D?.ownerName?[D]:[])),o=e.regions.map(x=>({id:x.id,kind:"structural-region",label:x.label,disposition:"folded",location:null,anchorIds:Pe(i.get(x.id)??[]),attributes:{workspace:x.workspace,structuralPath:x.structuralPath,minimumDepth:x.minDepth,files:x.fileCount,symbols:x.symbolCount,expanded:x.expanded}}));for(let x of e.symbolStates.values()){let D=e.regionForFile.get(x.definition.relativePath)?.id;if(!D)throw new Error(`System-map symbol ${x.definition.symbol} has no structural region.`);let _=Xn(x.definition.symbol),P=Ma(e.db,x.definition);o.push({id:_,kind:"symbol",label:k(x.definition.symbol),disposition:(i.get(_)?.length??0)>0?"emitted":"folded",location:{file:x.definition.relativePath,line:x.definition.startLine,endLine:x.definition.endLine},anchorIds:Pe(i.get(_)??[]),attributes:{regionId:D,depth:x.depth,leaf:x.definition.leaf??k(x.definition.symbol),referenceScope:x.referenceScope,...P.evidence.length>0?{publicEntry:!0,publicEntryPriority:P.priority,publicEntryEvidence:P.evidence.join(",")}:{}}})}for(let x of t){let D=e.regionForFile.get(x.file)?.id;if(!D)throw new Error(`Source construct ${x.name} has no structural region.`);let _=cr(x),T=r.find(W=>W.file===x.file&&W.line>=x.startLine&&W.line<=x.endLine)?.ownerName??x.name,F=UM(e.db,x);o.push({id:_,kind:"source-construct",label:T,disposition:(i.get(_)?.length??0)>0?"emitted":"folded",location:{file:x.file,line:x.startLine,endLine:x.endLine},anchorIds:Pe(i.get(_)??[]),attributes:{regionId:D,leaf:T,sourceOwned:!0,...F.evidence.length>0?{publicEntry:!0,publicEntryPriority:F.priority,publicEntryEvidence:F.evidence.join(",")}:{}}})}let s=new Map;for(let x of e.relations)x.fromBoundaryParticipant&&s.set(x.fromBoundaryParticipant.observationId,x.fromBoundaryParticipant),x.toBoundaryParticipant&&s.set(x.toBoundaryParticipant.observationId,x.toBoundaryParticipant);for(let x of[...s.values()].sort((D,_)=>D.observationId.localeCompare(_.observationId))){let D=e.regionForFile.get(x.file)?.id;if(!D)throw new Error(`Runtime-boundary participant ${x.observationId} has no structural region.`);o.push({id:Su(x.observationId),kind:"runtime-boundary-participant",label:x.address||x.ownerName||`${x.role} ${x.action}`,disposition:"folded",location:{file:x.file,line:x.line,endLine:x.endLine},anchorIds:[],attributes:{regionId:D,action:x.action,protocol:x.protocol,role:x.role,...x.address?{address:x.address}:{},ownerSymbol:x.ownerSymbol}})}let a=new Set(o.map(x=>x.id)),c=qt(t,x=>x.file),l=(x,D,_,P,T,F,W=!1)=>{let ce=x?Xn(x):null;if(ce&&a.has(ce)&&!Le(x))return ce;let q=D?Su(D.observationId):null;if(W&&q&&a.has(q))return q;let Y=_?cr(Pa(e.db,_)):null;if(Y&&a.has(Y))return Y;if(q&&a.has(q))return q;let N=F===null?null:(c.get(T)??[]).filter(K=>K.startLine<=F&&K.endLine>=F).sort((K,te)=>K.endLine-K.startLine-(te.endLine-te.startLine)||K.startLine-te.startLine)[0]??null;return N?cr(N):ce&&a.has(ce)?ce:P},u=[];for(let x of e.symbolStates.values()){let D=e.regionForFile.get(x.definition.relativePath)?.id;if(!D)continue;let _=Xn(x.definition.symbol);u.push({id:Lt("edge","structural-membership",D,_),kind:"structural-membership",fromNodeId:D,toNodeId:_,directed:!0,disposition:"folded",semantics:ha("structural-membership"),evidence:[{method:"indexed-definition-file",strength:"exact",identity:x.definition.symbol,location:{file:x.definition.relativePath,line:x.definition.startLine,endLine:x.definition.endLine}}]})}let d=qt(e.relations,x=>`${l(x.fromSymbol,x.fromBoundaryParticipant,x.fromSourceConstruct,x.fromRegionId,x.fromFile,x.line,x.kind==="runtime-boundary")}\0${l(x.toSymbol,x.toBoundaryParticipant,x.toSourceConstruct,x.toRegionId,x.toFile,null)}\0${x.kind}`),m=new Set;for(let x of d.values()){let D=x[0],_=l(D.fromSymbol,D.fromBoundaryParticipant,D.fromSourceConstruct,D.fromRegionId,D.fromFile,D.line,D.kind==="runtime-boundary"),P=l(D.toSymbol,D.toBoundaryParticipant,D.toSourceConstruct,D.toRegionId,D.toFile,null);if(D.kind==="runtime-boundary"&&D.fromBoundaryParticipant){let F=Su(D.fromBoundaryParticipant.observationId),W=l(D.fromSymbol,void 0,D.fromSourceConstruct,D.fromRegionId,D.fromFile,D.line);W!==F&&!m.has(F)&&(m.add(F),u.push({id:Lt("edge","boundary-observation",W,F),kind:"boundary-observation",fromNodeId:W,toNodeId:F,directed:!0,disposition:"folded",semantics:ha("boundary-observation"),evidence:[{method:"runtime-boundary-observation-owner",strength:D.strength??"unknown",identity:D.fromBoundaryParticipant.observationId,location:{file:D.fromBoundaryParticipant.file,line:D.fromBoundaryParticipant.line,endLine:D.fromBoundaryParticipant.endLine}}]}))}(_===P?o.find(F=>F.id===_):null)?.kind!=="structural-region"&&u.push({id:Lt("edge",D.kind,_,P),kind:D.kind,fromNodeId:_,toNodeId:P,directed:!0,disposition:"folded",semantics:Sy(D),evidence:YM(x.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 x of e.externalBoundaries){let D=Lt("external",x.kind,x.name),_=Pe(x.fromRegionIds);o.push({id:D,kind:x.kind,label:x.name,disposition:"folded",location:null,anchorIds:[],attributes:{}});for(let P of _)u.push({id:Lt("edge",x.kind,P,D),kind:x.kind,fromNodeId:P,toNodeId:D,directed:!0,disposition:"folded",semantics:ha("external-import"),evidence:[{method:"indexed-or-source-import",strength:"mixed",identity:`${P} -> ${x.name}`,location:null}]})}let p=[];e.boundaryFrontiers.forEach((x,D)=>{let _=e.regionForFile.get(x.file)?.id;if(!_)throw new Error(`Runtime-boundary frontier ${x.observationId} has no system-map region.`);let P=Lt("unsupported","runtime-boundary",x.observationId,String(D)),T=Lt("edge","runtime-boundary-frontier",_,P);o.push({id:P,kind:"runtime-boundary-frontier",label:x.address,disposition:"unsupported",location:{file:x.file,line:x.line},anchorIds:[],attributes:{action:x.action,strength:x.strength,owner:x.ownerShortName}}),u.push({id:T,kind:"runtime-boundary-frontier",fromNodeId:_,toNodeId:P,directed:!0,disposition:"unsupported",evidence:[{method:"runtime-boundary-extractor",strength:x.strength,identity:x.observationId,location:{file:x.file,line:x.line}}]}),p.push({id:Lt("frontier","runtime-boundary",x.observationId,String(D)),kind:"runtime-boundary",direction:"unresolved",fromNodeIds:[_],edgeIds:[T],memberNodeIds:[P],memberCount:1,disposition:"unsupported",reason:x.reason,expansion:null})});let f=La({anchors:n,nodes:o,edges:u,paths:[],frontiers:p,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(x=>x==="frontier:program-facts"),h=ab(f,{expandedFrontierIds:e.topologyFrontiers.filter(x=>x!=="frontier:program-facts"),routeIds:e.routeIds}),b=h.nodes.filter(x=>x.disposition==="emitted"||h.anchors.some(D=>D.status==="matched"&&D.nodeIds.includes(x.id))),v=e.relations.filter(x=>b.some(D=>KM(x,D))),y=e.boundaryFrontiers.filter(x=>b.some(D=>qM(x,D))),E=Dy(e.db,v,b),w=My(e.db,b),S=zy(e.db,b,y),R=[...E.nodes,...w.nodes,...S.nodes].map(x=>g&&x.disposition==="folded"?{...x,disposition:"emitted"}:x),C=[...E.edges,...w.edges,...S.edges].map(x=>g&&x.disposition==="folded"?{...x,disposition:"emitted"}:x),L=g?null:WM(b,R,C),I=La({anchors:h.anchors,nodes:[...h.nodes,...R],edges:[...h.edges,...C],paths:h.paths,frontiers:[...h.frontiers,...E.frontiers,...w.frontiers,...S.frontiers,...L?[L]:[]],scope:h.coverage.scope,blindSpots:[...h.coverage.blindSpots,...E.blindSpots,...w.blindSpots,...S.blindSpots],incompleteReasons:h.coverage.status==="incomplete"?[h.coverage.explanation]:[],...h.routeCatalog?{routeCatalog:h.routeCatalog}:{}});I.completion=h.completion;for(let x of I.frontiers)x.disposition==="folded"&&(x.id.startsWith("frontier:program-facts:")||(x.expansion=VM(e,x.id)));return I}function KM(e,t){if(e.fromSymbol&&t.id===Xn(e.fromSymbol)||e.toSymbol&&t.id===Xn(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 qM(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 WM(e,t,n){let i=Pe(t.filter(o=>o.disposition==="folded").map(o=>o.id)),r=Pe(n.filter(o=>o.disposition==="folded").map(o=>o.id));return i.length===0&&r.length===0?null:{id:Lt("frontier","program-facts"),kind:"program-facts",direction:"outgoing",fromNodeIds:Pe(e.map(o=>o.id)),edgeIds:r,memberNodeIds:i,memberCount:i.length,disposition:"folded",reason:"Control, data, state, and temporal facts are folded beneath the selected high-level owners.",expansion:null}}function VM(e,t){return`codebaseiq system-map ${[...e.anchors.flatMap(i=>i.kind==="literal"?[`--search ${Ne(i.query)}`]:[`--symbol ${Ne(i.query)}`]),`--depth ${e.maxDepth}`,...e.requestedRelationKinds.map(i=>`--relation ${Ne(i)}`),`--evidence-floor ${Ne(e.evidenceFloor)}`,...e.includedSourceScopes.map(i=>`--source-scope ${Ne(i)}`),...e.fullLiteralTraversal?["--full-literal-traversal"]:[],`--topology-characters ${e.maxTopologyCharacters}`,...e.expandedRegionIds.map(i=>`--expand ${Ne(i)}`),...e.topologyFrontiers.map(i=>`--frontier ${Ne(i)}`),...e.routeIds.map(i=>`--route ${Ne(i)}`),`--frontier ${Ne(t)}`].join(" ")}`}function JM(e){let t=new Set;for(let n of e.nodes){if(n.disposition!=="emitted")continue;n.kind==="structural-region"&&t.add(n.id);let i=n.attributes.regionId;typeof i=="string"&&t.add(i)}return t}function YM(e){let t=new Map;for(let n of e){let i=n.location?`${n.location.file}:${n.location.line}`:"";t.set(`${n.method}\0${n.strength}\0${n.identity??""}\0${i}`,n)}return[...t.values()].sort((n,i)=>n.method.localeCompare(i.method)||(n.identity??"").localeCompare(i.identity??"")||(n.location?.file??"").localeCompare(i.location?.file??"")||(n.location?.line??0)-(i.location?.line??0))}function Lt(...e){return e.map(t=>encodeURIComponent(t)).join(":")}function Xn(e){return Lt("symbol",e)}function XM(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function QM(e,t,n,i,r,o,s,a,c,l){let u=[...i].sort((g,h)=>Cb(g,h,r)),m=u.slice(0,lb).map(g=>g.id),p=u.slice(lb).map(g=>g.id),f=[...e.map(g=>`--search ${Ne(g)}`),...t.map(g=>`--symbol ${Ne(g)}`),`--depth ${n}`,...o.map(g=>`--relation ${Ne(g)}`),`--evidence-floor ${Ne(s)}`,...a.map(g=>`--source-scope ${Ne(g)}`),...c?["--full-literal-traversal"]:[],`--topology-characters ${l}`,...m.map(g=>`--expand ${Ne(g)}`)];return{command:m.length===0?null:`codebaseiq system-map ${f.join(" ")}`,regionCount:m.length,regionIds:m,candidateRegionCount:i.length,omittedRegionIds:p}}function ZM(e,t,n,i,r,o,s,a,c,l,u,d,m){let p=[...c].sort((I,x)=>Cb(I,x,u)).filter(I=>!m||m.has(I.id)||d.has(I.id)),f=l.length>0?Math.floor(a*.4):0,g=a-f,h=new Set,b=0;for(let I of p){let x=mb(I);!d.has(I.id)&&h.size>0&&b+x>g||(h.add(I.id),b+=x)}let v=l.filter(I=>h.has(I.fromRegionId)&&h.has(I.toRegionId)).sort(eA),y=[];for(let I of v){let x=pb(I);y.length>0&&b+x>a||(y.push(Aa(I)),b+=x)}let E=c.filter(I=>!h.has(I.id)).map(I=>I.id).sort(),w=new Set(y),S=l.filter(I=>!w.has(Aa(I))).length,R=c.reduce((I,x)=>I+mb(x),0)+l.reduce((I,x)=>I+pb(x),0),C=p.every(I=>h.has(I.id))&&y.length===v.length,L=[...e.map(I=>`--search ${Ne(I)}`),...t.map(I=>`--symbol ${Ne(I)}`),`--depth ${n}`,...i.map(I=>`--relation ${Ne(I)}`),`--evidence-floor ${Ne(r)}`,...o.map(I=>`--source-scope ${Ne(I)}`),...s?["--full-literal-traversal"]:[],`--topology-characters ${Math.max(a,R)}`];return{maxCharacters:a,estimatedCharacters:b,totalEstimatedCharacters:R,regionIds:[...h],omittedRegionIds:E,relationKeys:y,omittedRelations:S,complete:C,expansionCommand:C?null:`codebaseiq system-map ${L.join(" ")}`}}function mb(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 pb(e){return 70+e.fromRegionId.length+e.toRegionId.length+e.kinds.join(",").length+e.evidence.join(",").length}function eA(e,t){let n=i=>i.kinds.includes("runtime-boundary")?0:i.kinds.includes("contract-symbol")?1:2;return n(e)-n(t)||t.relationCount-e.relationCount||Aa(e).localeCompare(Aa(t))}function Aa(e){return`${e.fromRegionId}\0${e.toRegionId}`}function Cb(e,t,n){let i=a=>n.has(a.id)?0:1,r=a=>a.sourceFileCount===0?1:0,o=a=>a.symbolCount+a.literalHitCount>0?0:1,s=a=>[...a.incomingRegionIds,...a.outgoingRegionIds].filter(c=>n.has(c)).length;return i(e)-i(t)||o(e)-o(t)||r(e)-r(t)||e.minDepth-t.minDepth||s(t)-s(e)||t.literalHitCount-e.literalHitCount||e.testFileCount-t.testFileCount||e.label.localeCompare(t.label)}function tA(e){let t=[],n=new Set;for(let r of e.filter(o=>o.expanded)){for(let c of r.symbols)c.origins.includes("symbol-anchor")&&n.add(c.file);let o=qt(r.symbols,c=>c.file),s=qt(r.literalHits,c=>c.file),a=[...r.files].sort((c,l)=>iA(c,l,o,s));for(let c of a){let l=(o.get(c.file)??[]).sort(rA)[0];if(l){t.push({kind:"symbol",regionId:r.id,file:l.file,line:l.startLine,endLine:l.endLine,label:l.shortName});continue}let u=(s.get(c.file)??[]).sort(wb)[0];u&&t.push({kind:"literal",regionId:r.id,file:u.file,line:u.line,endLine:null,label:u.ownerShortName??u.query})}}let i=nA(t,n);return{command:i.length===0?null:`codebaseiq inspect ${i.map(r=>`--at ${Ne(`${r.file}:${r.line+1}`)}`).join(" ")} --view behavior`,definitionCommand:null,candidateAnchors:t.length,selectedAnchors:i.length,omittedAnchors:t.length-i.length,anchors:i}}function nA(e,t){let n=[...qt(e,s=>s.regionId).values()],i=[],r=new Set,o=Math.min(kM,24);for(let s of e)if(!(!t.has(s.file)||r.has(s.file))&&(i.push(s),r.add(s.file),i.length===o))return i;for(let s=0;i.length<o;s+=1){let a=!1;for(let c of n){let l=c[s];if(l&&(a=!0,!r.has(l.file)&&(i.push(l),r.add(l.file),i.length===o)))break}if(!a)break}return i}function iA(e,t,n,i){let r=a=>a.kind==="test"?2:a.kind==="barrel"?1:0,o=a=>(i.get(a.file)??[]).some(c=>c.traversalSeed)?0:1,s=a=>{let c=n.get(a.file)??[];return Math.min(5,...c.map(l=>yo(l.origins)))};return r(e)-r(t)||o(e)-o(t)||s(e)-s(t)||e.depth-t.depth||e.file.localeCompare(t.file)}function rA(e,t){return yo(e.origins)-yo(t.origins)||e.depth-t.depth||e.startLine-t.startLine||e.shortName.localeCompare(t.shortName)}function Ne(e){return`'${e.replaceAll("'","'\\''")}'`}function oA(e,t,n,i){let r=[];for(let o of he(e,{includeIgnored:!1})){let s=ie(e,o);if(s.length===0)continue;let a=t.definitionsForFile(o),c=ee(e,o)?.callables??[];for(let l=0;l<s.length;l+=1){let u=s[l]??"";if(!u.includes(n))continue;let d=Ge(a,l),m=xu(c,l),p=d&&!Le(d.symbol)?d:null,f=p?.startLine??m?.startLine??d?.startLine??l,g=p?.endLine??m?.endLine??d?.endLine??l,h=Ur(e,o,l,f,g),b=i.has(`${o}\0${l}`),v=!!(p?.isFunctionLike||m);r.push({relativePath:o,line:l,sourceLine:u,ownerSymbol:p?.symbol??null,ownerShortName:p?k(p.symbol):m?.name??(d?k(d.symbol):null),ownerStartLine:h.startLine,ownerEndLine:h.endLine,matchKind:lA(u,n),seedPriority:b?0:v?1:2})}}return r}function sA(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 fb(e){return`${e.relativePath}\0${e.line}`}function xu(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,i)=>n.endLine-n.startLine-(i.endLine-i.startLine)||n.startLine-i.startLine)[0]??null}function bu(e,t,n){let r=xu(ee(e,t)?.callables??[],n)??xb(e,t,n);if(!r)return null;let o=Ur(e,t,n,r.startLine,r.endLine);return{file:t,name:r.name,startLine:o.startLine,endLine:o.endLine}}function xb(e,t,n){let i=ae(e,t)?.rootNode;if(!i||i.startPosition.row>n||i.endPosition.row<n)return null;let r=Ru(i,n);for(;r;){if(r.type==="variable_declarator"){let s=r.childForFieldName("name")??r.namedChild(0),a=r.childForFieldName("value")??r.namedChild(1);if(s?.type==="identifier"&&a&&vu(a,n))return{name:s.text,startLine:r.startPosition.row,endLine:r.endPosition.row}}if(r.type==="pair"){let s=r.childForFieldName("key")??r.namedChild(0),a=r.childForFieldName("value")??r.namedChild(1),c=s?.text.replace(/^(?:['"])(.*)(?:['"])$/u,"$1");if(c&&a&&/^[A-Za-z_$][\w$]*$/u.test(c)&&vu(a,n))return{name:c,startLine:r.startPosition.row,endLine:r.endPosition.row}}r=r.parent}let o=Ji(e,t,n);return o?{name:`source@${n+1}`,startLine:o.startLine,endLine:o.endLine}:null}function vu(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&&vu(n,t))}function Ru(e,t){let n=e.namedChildren.filter(i=>i.startPosition.row<=t&&i.endPosition.row>=t).sort((i,r)=>i.endIndex-i.startIndex-(r.endIndex-r.startIndex)||i.startPosition.row-r.startPosition.row)[0];return n?Ru(n,t):e}function aA(e,t){let n=t.match(/^(.+):(\d+)(?:-(\d+))?$/u);if(!n)return null;let i=ns(e,n[1],{allowMultiple:!1})[0]?.relativePath;if(!i)return null;let r=Math.max(0,Number.parseInt(n[2],10)-1),o=n[3]?Math.max(r,Number.parseInt(n[3],10)-1):r,s=(ee(e,i)?.callables??[]).filter(a=>a.startLine<=r&&a.endLine>=o).sort((a,c)=>a.endLine-a.startLine-(c.endLine-c.startLine)||a.startLine-c.startLine)[0];return s?{file:i,name:s.name,startLine:s.startLine,endLine:s.endLine}:null}function cA(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 lA(e,t){let n=/[\p{L}\p{N}_$]/u,i=e.indexOf(t);for(;i>=0;){let r=e[i-1]??"",o=e[i+t.length]??"";if((r==="'"||r==='"'||r==="`")&&o===r)return"exact-value";if(!n.test(r)&&!n.test(o))return"boundary";i=e.indexOf(t,i+Math.max(1,t.length))}return"embedded"}function Cu(e){return V(e)==="test"?!1:!/(?:^|[/._-])(?:fixtures?|mocks?|previews?|demos?|examples?|stories)(?:[/._-]|$)/iu.test(e)}function uA(e,t){return e.matchKind!=="embedded"&&t(e.relativePath)&&(Oc(e.relativePath)!=="production"||Cu(e.relativePath))}function dA(e,t){let n=[...t].sort(mA),i=[],r=new Set;for(let o of n)if(!r.has(o.relativePath)&&(i.push(o),r.add(o.relativePath),i.length>=cb))break;for(let o of n){if(i.length>=cb)break;i.includes(o)||i.push(o)}return i.map(o=>({query:e,file:o.relativePath,line:o.line,ownerSymbol:o.ownerSymbol,ownerShortName:o.ownerShortName,ownerStartLine:o.ownerStartLine,ownerEndLine:o.ownerEndLine,sourceLine:o.sourceLine.trim(),matchKind:o.matchKind,traversalSeed:!1}))}function mA(e,t){let n={"exact-value":0,boundary:1,embedded:2};return n[e.matchKind]-n[t.matchKind]||+(t.ownerSymbol!==null)-+(e.ownerSymbol!==null)||+!Cu(e.relativePath)-+!Cu(t.relativePath)||e.relativePath.localeCompare(t.relativePath)||e.line-t.line}function pA(e,t){let n=new Map;for(let i of t){let r=fA(i.relativePath);n.set(r,(n.get(r)??0)+1)}return[...n].sort(([i,r],[o,s])=>s-r||i.localeCompare(o)).slice(0,FM).map(([i])=>`codebaseiq search ${Ne(e)} --scope ${Ne(i)}`)}function fA(e){let t=e.split("/").filter(Boolean);if(t.length<=1)return e;let n=t.slice(0,-1),i=n.lastIndexOf("src");return i>=0?n.slice(0,Math.min(n.length,i+3)).join("/"):n.slice(0,Math.min(n.length,3)).join("/")}function gA(e,t,n){let i=t.callerFileMap([n],{semantic:!1}).get(n.symbolId)??new Set,r=[];for(let o of[...i].sort()){let s=n.leaf?Sn(e,o,n.leaf):[];if(s.length===0){r.push({file:o,line:null,enclosingSymbol:null});continue}let a=t.definitionsForFile(o);for(let c of s)r.push({file:o,line:c,enclosingSymbol:Ge(a,c)?.symbol??null})}return r}function hA(e,t){let n=e.all(`SELECT DISTINCT gs.symbol, def_d.relative_path AS from_file
76
- FROM mentions m
77
- JOIN chunks c ON m.chunk_id = c.id
78
- JOIN documents imp_d ON c.document_id = imp_d.id
79
- JOIN global_symbols gs ON m.symbol_id = gs.id
80
- LEFT JOIN (
81
- SELECT m2.symbol_id, c2.document_id
82
- FROM mentions m2
83
- JOIN chunks c2 ON m2.chunk_id = c2.id
84
- WHERE m2.role = 1
85
- GROUP BY m2.symbol_id
86
- ) sym_def ON sym_def.symbol_id = gs.id
87
- LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
88
- WHERE imp_d.relative_path = ? AND m.role = 2
89
- ORDER BY def_d.relative_path, gs.symbol`,t);return n.length>0?n.map(i=>({symbol:i.symbol,shortName:k(i.symbol),importedName:gb(k(i.symbol)),localName:gb(k(i.symbol)),fromFile:i.from_file,source:"compiler"})):Ce(e,t).map(i=>{let r=yA(i.importedName,i.localName,i.kind),o=i.localName??i.importedName,s=i.importedName==="default"?o:i.importedName;return{symbol:r,shortName:r,importedName:s,localName:o,fromFile:i.sourcePath,source:"parsed-source"}})}function gb(e){return e.slice(e.lastIndexOf(":")+1).replace(/\(\)$/u,"")||e}function yA(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 Yn(e,t,n){let i=rt(e,n);if(!i.match)return{matches:[],total:0,omitted:0};let r=[i.match,...i.candidates.map(s=>rt(e,s.symbol).match)].filter(s=>s!==null),o=new Map;for(let s of r){let a=t.definitionsForFile(s.relativePath).find(c=>c.symbol===s.symbol);a&&o.set(a.symbol,a)}return{matches:[...o.values()],total:i.total,omitted:Math.max(0,i.total-o.size)}}function bA(e){return{symbol:e.symbol,shortName:k(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine}}function It(e,t){let n=[t.kind,t.fromFile,t.fromSymbol??"",t.toFile,t.toSymbol??"",t.fromBoundaryParticipant?.observationId??"",t.toBoundaryParticipant?.observationId??"",t.fromSourceConstruct?ln(t.fromSourceConstruct):"",t.toSourceConstruct?ln(t.toSourceConstruct):"",t.runtimeBoundaryKey??"",t.line??""].join("\0");e.set(n,t)}function lr(e){return{observationId:e.id,action:e.action,protocol:e.protocol,role:e.role,address:Rb(e),file:e.source.file,line:e.source.startLine,endLine:e.source.endLine,ownerName:e.owner.name,ownerSymbol:e.owner.symbol}}function Da(e,t){let n=ie(e,t.source.file);return gt(e,t.source.file,0,Math.max(0,n.length-1),[t.source.startLine])}function hb(e,t){let n=[...e.values()];for(let i of[t.owner,t.source]){let r=n.filter(o=>o.file===i.file&&o.startLine<=i.startLine&&o.endLine>=i.startLine).sort((o,s)=>o.endLine-o.startLine-(s.endLine-s.startLine)||o.startLine-s.startLine)[0];if(r)return r}return null}function yb(e,t,n,i,r){let o=[],s=n.get(e.id);s!==void 0&&s<=t&&o.push(s);for(let a of i.values()){if(a.depth>t)continue;let c=a.definition;bb(c,e)&&o.push(a.depth)}for(let a of r.values())a.depth>t||bb(a,e)&&o.push(a.depth);return o.length>0?Math.min(...o):null}function bb(e,t){let n=e.relativePath??e.file;return[t.owner,t.source].some(i=>n===i.file&&e.startLine<=i.startLine&&e.endLine>=i.startLine)}function Su(e){return Lt("runtime-boundary-participant",e)}function SA(e,t,n){let i=Pt(e,n),r=Pt(t,n);return i.relativeDir!==r.relativeDir?!0:/(?:^|\/)(?:contracts?|schemas?|db\/schema)(?:\/|$)/u.test(t)}function vA(e,t,n){return ho(e,n).id===ho(t,n).id}function CA(e,t,n,i){if(e.referenceScope==="all")return!0;let r=ho(t,i).id;return[...n.values()].some(s=>s.promoteBoundaryImports&&ho(s.file,i).id===r)?!0:e.referenceScope!=="cross-workspace-or-forward"?!1:Pt(t,i).relativeDir!==Pt(e.definition.relativePath,i).relativeDir}function xA(e,t){let n={none:0,"forward-regions":1,"cross-workspace-or-forward":2,all:3};return n[e]>=n[t]?e:t}function RA(e){let t=new Map;for(let[n,i]of e)for(let r of i){let o=t.get(r)??new Set;o.add(n),t.set(r,o)}return t}function Pt(e,t){return t.find(n=>e===n.relativeDir||e.startsWith(`${n.relativeDir}/`))??{name:"root",relativeDir:""}}function EA(e){let t=new Set(["apps","packages","services","crates","libs","tools"]),n=new Map;for(let i of e){let r=i.split("/").filter(Boolean);if(r.length<3||!t.has(r[0]))continue;let o=`${r[0]}/${r[1]}`;n.set(o,{name:r[1],relativeDir:o})}return[...n.values()].sort((i,r)=>r.relativeDir.length-i.relativeDir.length)}function ho(e,t){let n=Pt(e,t),r=(n.relativeDir?e.slice(n.relativeDir.length+1):e).split("/").filter(Boolean);r[0]==="src"&&r.shift();let o=wA(r);return{id:`region:${n.relativeDir||"root"}:${o}`,label:`${n.name}:${o}`,workspace:n.name,structuralPath:o}}function wA(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 IA(e,t,n,i,r,o,s){let a=qt([...e.values()],p=>o.get(p.file).id),c=qt([...t.values()],p=>o.get(p.definition.relativePath).id),l=qt(n,p=>o.get(p.file).id),u=new Map;for(let p of i)for(let f of new Set([p.fromRegionId,p.toRegionId])){let g=u.get(f)??[];g.push(p),u.set(f,g)}let d=qt(r,p=>p.toRegionId),m=qt(r,p=>p.fromRegionId);return[...a.entries()].map(([p,f])=>{let g=o.get(f[0].file),h=c.get(p)??[],b=l.get(p)??[],v=u.get(p)??[],y=s.has(p),E=h.map(DA).sort(FA).slice(0,NM),w=f.filter(S=>V(S.file)==="test").length;return{id:p,label:g.label,workspace:g.workspace,structuralPath:g.structuralPath,minDepth:Math.min(...f.map(S=>S.depth)),fileCount:f.length,sourceFileCount:f.length-w,testFileCount:w,symbolCount:h.length,literalHitCount:b.length,anchorQueries:Pe([...b.map(S=>S.query),...h.flatMap(S=>[...S.anchorQueries])]),relationKinds:Pe(v.map(S=>S.kind)),incomingRegionIds:Pe((d.get(p)??[]).map(S=>S.fromRegionId)),outgoingRegionIds:Pe((m.get(p)??[]).map(S=>S.toRegionId)),memberCallCandidateRelationCount:v.filter(S=>S.evidence==="ast-member-import-candidate").length,notableSymbols:E,omittedNotableSymbols:Math.max(0,h.length-E.length),expanded:y,files:y?f.map(LA).sort(NA):[],symbols:y?h.map(PA).sort(kA):[],literalHits:y?[...b].sort(wb):[],relations:y?[...v].sort(Eb):[]}}).sort((p,f)=>p.minDepth-f.minDepth||p.label.localeCompare(f.label))}function LA(e){return{file:e.file,kind:V(e.file),depth:e.depth,origins:Pe([...e.origins])}}function PA(e){return{symbol:e.definition.symbol,shortName:k(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 DA(e){return{shortName:k(e.definition.symbol),file:e.definition.relativePath,origins:Pe([...e.origins])}}function TA(e){return[...qt(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(i=>i.kind)),relationCount:n.length,fromFiles:Pe(n.map(i=>i.fromFile)),toFiles:Pe(n.map(i=>i.toFile)),fromSymbols:Pe(n.flatMap(i=>i.fromSymbol?[k(i.fromSymbol)]:[])),toSymbols:Pe(n.flatMap(i=>i.toSymbol?[k(i.toSymbol)]:[])),evidence:Pe(n.map(i=>i.evidence)),strengths:Pe(n.map(i=>i.strength??"unknown"))})).sort((n,i)=>n.fromRegionId.localeCompare(i.fromRegionId)||n.toRegionId.localeCompare(i.toRegionId))}function MA(e,t){return[...e.values()].map(n=>({kind:"external-import",name:n.name,fromRegionIds:Pe([...n.fromFiles].flatMap(i=>{let r=t.get(i);return r?[r.id]:[]})),fromFiles:Pe([...n.fromFiles])})).sort((n,i)=>n.name.localeCompare(i.name))}function AA(e,t,n,i){let r=e.kind==="literal"?t.filter(o=>o.query===e.query).map(o=>o.file):[...n.values()].filter(o=>o.anchorQueries.has(e.query)).map(o=>o.definition.relativePath);return Pe(r.map(o=>i.get(o)?.id).filter(o=>!!o))}function Rb(e){return e.keyParts.map(t=>`${t.name}=${t.value}`).join(" ")}function Ta(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))]}function Pe(e){return[...new Set(e)].sort()}function qt(e,t){let n=new Map;for(let i of e){let r=t(i),o=n.get(r)??[];o.push(i),n.set(r,o)}return n}function Eb(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 FA(e,t){return yo(e.origins)-yo(t.origins)||e.shortName.localeCompare(t.shortName)}function yo(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 NA(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)}function kA(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)||e.symbol.localeCompare(t.symbol)}function wb(e,t){return e.file.localeCompare(t.file)||e.line-t.line||e.query.localeCompare(t.query)}var OA=["causal","structure","complete"],BA={causal:["execution","runtime","dataflow","state","temporal"],structure:["contract","identity","ownership","dependencies"],complete:Kt},$A=2,jA=48,Ib=64,HA=5e4;function bo(e,t,n={}){let i=Mn([...t.symbols??[],...t.locations??[]]),r=Mn(t.searches??[]);if(i.length===0&&r.length===0)throw new Error("evidence requires at least one positional symbol, --symbol, --at, or --search selector.");let o=n.view??"causal",s=UA(n.families,o),a=n.direction??"both",c=Mn(n.subtypes??[]),l=n.connecting??!1,u=n.inventoryOnly??!1,d=Mn(n.foldIds??[]),m=n.maxDepth??$A,p=n.maxEdges??jA;if(!Number.isSafeInteger(m)||m<0)throw new RangeError(`Evidence depth must be a non-negative safe integer; received ${m}.`);if(!Number.isSafeInteger(p)||p<=0)throw new RangeError(`Evidence max edges must be a positive safe integer; received ${p}.`);if(!["incoming","outgoing","both"].includes(a))throw new Error(`Unsupported graph evidence direction: ${a}.`);if(u&&d.length>0)throw new Error("Evidence fold materialization cannot be combined with --inventory-only.");let f=Sb(e,{symbols:i,searches:r,maxDepth:m,maxTopologyCharacters:HA,relations:zA(s)}),g=new Map(f.nodes.map(Y=>[Y.id,Y])),h=f.edges.filter(Y=>Y.disposition==="emitted"||Y.disposition==="folded").flatMap(Y=>GA(Y,g)),b=h.filter(Y=>s.includes(Y.family)).filter(Y=>c.length===0||c.includes(Y.subtype)),v=new Set(f.anchors.flatMap(Y=>Y.nodeIds));if(l&&v.size<2)throw new Error("Connecting evidence requires at least two resolved root nodes.");let y=new Set(b.map(Y=>Y.id)),E=Eu(h,v,"incoming").filter(Y=>y.has(Y.id)),w=Eu(h,v,"outgoing").filter(Y=>y.has(Y.id)),S=Eu(h,v,"both").filter(Y=>y.has(Y.id)),R=JA(s,c,E,w,S),C=a==="incoming"?E:a==="outgoing"?w:S,L=l?nF(C,[...v],a):C,I=rF(L,v,a),x=[...L].sort((Y,N)=>oF(Y,N,I)),D=YA(x,p),_=QA(D,d),P=u?[]:d.length>0?x.filter(Y=>_.has(Y.id)):x,T=d.length>0?P:P.slice(0,p),F=d.length>0||u?[]:D,W=Math.max(0,P.length-T.length),ce=f.frontiers.filter(Y=>Y.disposition==="unsupported").length,q=f.coverage.status==="incomplete"?"incomplete":W>0?"bounded":"accounted";return{kind:"graph",view:n.families&&n.families.length>0?"custom":o,families:s,selection:{direction:a,subtypes:c,connecting:l,inventoryOnly:u,foldIds:d},targets:f.anchors.map(Y=>({kind:Y.kind,query:Y.query,status:Y.status,nodeIds:[...Y.nodeIds],omittedCandidates:Y.omittedCandidates})),inventory:R,edges:T,folds:F,coverage:{status:q,topologyStatus:f.coverage.status,scope:f.coverage.scope,maxDepth:m,maxEdges:p,matchedEdges:x.length,eligibleEdges:P.length,returnedEdges:T.length,omittedEdges:W,frontierGroups:f.frontiers.length,unsupportedFrontiers:ce,blindSpots:Mn([...f.coverage.blindSpots,...hy(s)]),explanation:u?`${x.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.`:q==="accounted"?"Every selected relationship in the bounded topology was emitted.":q==="bounded"?`${W} selected relationship(s) were withheld by the explicit edge budget.`:f.coverage.explanation}}}function UA(e,t){let n=e&&e.length>0?e:BA[t],i=n.filter(r=>!Kt.includes(r));if(i.length>0)throw new Error(`Unsupported graph evidence family: ${i.join(", ")}.`);return Mn(n)}function zA(e){return["call","contract-symbol","import","reference","runtime-boundary"]}function GA(e,t){let n=t.get(e.fromNodeId),i=t.get(e.toNodeId);return!n||!i?[]:(e.semantics??[]).flatMap((r,o)=>{let s=qA(r);if(!s)return[];let a=yy(s,r.subtype);if(!a)throw new Error(`No graph relation provider contract is registered for ${s}/${r.subtype}.`);let c=VA(e);if(!a.relation.evidenceStrengths.includes(c))throw new Error(`Graph relation provider ${a.provider.id} does not admit ${c} evidence for ${s}/${r.subtype}.`);return[{id:`${e.id}:${o}:${s}`,family:s,semanticFamily:r.family,subtype:r.subtype,from:Lb(n),to:Lb(i),sourceKind:e.kind,providerId:a.provider.id,supportCeiling:a.relation.supportCeiling,establishes:a.relation.establishes,nonClaims:[...a.relation.nonClaims],recoverWith:[...a.relation.recoverWith],evidenceStrength:c,evidenceMethods:Mn(e.evidence.map(l=>l.method)),evidenceConstituents:KA(e.evidence),context:r.context?{...r.context}:null,attributes:r.attributes?{...r.attributes}:null}]})}function KA(e){let t=new Map;for(let n of e)t.set(`${n.method}\0${n.strength}`,n);return[...t.values()].map(({method:n,strength:i})=>({method:n,strength:i}))}function qA(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 Lb(e){let t=WA(e);return{id:e.id,kind:e.kind,label:t?k(t):e.label,symbol:t,location:e.location?{...e.location}:null}}function WA(e){return e.kind!=="symbol"||!e.id.startsWith("symbol:")?null:decodeURIComponent(e.id.slice(7))}function VA(e){let t=Mn(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 Eu(e,t,n){let i=wu(e,n),r=new Map,o=new Map,s=[...t].sort();for(let a of s)o.set(a,0);for(let a=0;a<s.length;a+=1){let c=s[a],l=o.get(c);for(let u of i.get(c)??[])r.set(u.edge.id,u.edge),!o.has(u.next)&&(o.set(u.next,l+1),s.push(u.next))}return[...r.values()]}function wu(e,t){let n=new Map,i=(r,o,s)=>{let a=n.get(r)??[];a.push({edge:s,next:o}),n.set(r,a)};for(let r of e)t!=="incoming"&&i(r.from.id,r.to.id,r),t!=="outgoing"&&i(r.to.id,r.from.id,r);for(let r of n.values())r.sort((o,s)=>o.edge.id.localeCompare(s.edge.id)||o.next.localeCompare(s.next));return n}function JA(e,t,n,i,r){let o=new Set;for(let u of[...n,...i,...r])o.add(`${u.family}\0${u.subtype}`);if(t.length>0)for(let u of e)for(let d of t)o.add(`${u}\0${d}`);let s=u=>{let d=new Map;for(let m of u){let p=`${m.family}\0${m.subtype}`;d.set(p,(d.get(p)??0)+1)}return d},a=s(n),c=s(i),l=s(r);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 YA(e,t){let n=e.slice(t),i=new Map;for(let s of n){let a=XA(s),c=`${s.family}\0${a}`,l=i.get(c)??[];l.push(s),i.set(c,l)}let r=new Map(e.map((s,a)=>[s.id,a+1])),o=[];for(let[s,a]of[...i].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+=Ib){let m=u.slice(d,d+Ib),p=m.map(b=>b.id),f=Mn(m.map(b=>b.subtype)).sort(),g=f.length===1?f[0]:"mixed",h=[...new Set(m.flatMap(b=>[b.from.id,b.to.id]))].sort();o.push({id:tF(c,f.join("\0"),p),mode:ZA(m),family:c,subtype:g,subtypes:f,region:l,edgeCount:p.length,edgeIds:p,nodeIds:h,minimumMaxEdges:Math.max(...p.map(b=>r.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 XA(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 QA(e,t){if(t.length===0)return new Set;let n=new Map(e.map(r=>[r.id,r])),i=t.filter(r=>!n.has(r));if(i.length>0){let r=e.map(o=>o.id).sort();throw new Error(`Unknown evidence fold ${i.join(", ")} for this projection. Available folds: ${r.join(", ")||"(none)"}.`)}return new Set(t.flatMap(r=>n.get(r).edgeIds))}function ZA(e){let t=new Map,n=new Map,i=new Set;for(let o of e){i.add(o.from.id),i.add(o.to.id);let s=t.get(o.from.id)??new Set;s.add(o.to.id),t.set(o.from.id,s);let a=n.get(o.to.id)??new Set;a.add(o.from.id),n.set(o.to.id,a)}return eF(i,t)?"scc":[...i].every(o=>(n.get(o)?.size??0)<=1&&(t.get(o)?.size??0)<=1)?"linear":"topology"}function eF(e,t){let n=new Set,i=new Set,r=o=>{if(n.has(o))return!0;if(i.has(o))return!1;n.add(o);for(let s of t.get(o)??[])if(r(s))return!0;return n.delete(o),i.add(o),!1};return[...e].some(r)}function tF(e,t,n){return`fold:${_A("sha256").update([e,t,...n].join("\0")).digest("hex").slice(0,16)}`}function nF(e,t,n){let i=new Map,r=[...new Set(t)].sort();for(let o=0;o<r.length;o+=1)for(let s=o+1;s<r.length;s+=1)for(let a of iF(e,r[o],r[s],n))i.set(a.id,a);return[...i.values()]}function iF(e,t,n,i){let r=wu(e,i),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 r.get(u)??[])o.has(m.next)||(o.set(m.next,d+1),s.set(m.next,{node:u,edge:m.edge}),a.push(m.next))}if(!o.has(n))return[];let 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 rF(e,t,n){let i=wu(e,n),r=new Map,o=[...t];for(let s of t)r.set(s,0);for(let s=0;s<o.length;s+=1){let a=o[s],c=r.get(a);for(let{next:l}of i.get(a)??[])r.has(l)||(r.set(l,c+1),o.push(l))}return r}function oF(e,t,n){return Pb(e,n)-Pb(t,n)||Db(e)-Db(t)||Tb(e.evidenceStrength)-Tb(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 Pb(e,t){return Math.min(t.get(e.from.id)??Number.MAX_SAFE_INTEGER,t.get(e.to.id)??Number.MAX_SAFE_INTEGER)}function Db(e){let t=[e.from,e.to].filter(n=>n.kind==="structural-region").length;return t===2?2:t}function Tb(e){switch(e){case"exact":return 0;case"mixed":return 1;case"derived":return 2;case"candidate":return 3;case"unknown":return 4}}function Mn(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))]}function Iu(e,t){let n=vn(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let i=n.map(()=>"?").join(", "),o=e.all(`SELECT relative_path FROM documents
90
- WHERE relative_path IN (${i})
91
- ORDER BY relative_path`,...n).map(l=>l.relative_path).filter(l=>!e.isIgnored(l)),s=us(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:l,...u})=>u),a=rr(e,"forward",n).filter(l=>!e.isIgnored(l)),c=rr(e,"reverse",n).filter(l=>!e.isIgnored(l));return{files:o,symbols:s,dependsOn:a,dependedOnBy:c}}function Lu(e,t){let n=vn(e,t);return n.length===0?[]:Ab([...Mb(e,n),...aF(e,n)]).filter(i=>!e.isIgnored(i.relative_path)).map(Fb)}function sF(e,t){let n=vn(e,t);return n.length===0?[]:Ab(Mb(e,n)).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({...Fb(i),basis:"external-reference"}))}function Mb(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
92
- FROM mentions m
93
- JOIN chunks c ON m.chunk_id = c.id
94
- JOIN documents d1 ON c.document_id = d1.id
95
- JOIN global_symbols gs ON m.symbol_id = gs.id
96
- WHERE d1.relative_path NOT IN (${n})
97
- AND (
98
- EXISTS (
99
- SELECT 1
100
- FROM defn_enclosing_ranges der
101
- JOIN documents d2 ON der.document_id = d2.id
102
- WHERE der.symbol_id = gs.id
103
- AND d2.relative_path IN (${n})
104
- )
105
- OR EXISTS (
106
- SELECT 1
107
- FROM mentions def_m
108
- JOIN chunks def_c ON def_m.chunk_id = def_c.id
109
- JOIN documents d2 ON def_c.document_id = d2.id
110
- WHERE def_m.symbol_id = gs.id
111
- AND def_m.role = 1
112
- AND d2.relative_path IN (${n})
113
- )
114
- )
115
- AND m.role != 1
116
- AND ${e.localSymbolPredicate}
117
- ${e.pathExclusionsFor("d1")}
118
- ORDER BY d1.relative_path`,...t,...t,...t)}function aF(e,t){let n=new U(e);return t.flatMap(i=>n.definitionsForFile(i).filter(r=>it(r.symbol)).map(r=>({relative_path:i,symbol:r.symbol})))}function Ab(e){let t=new Set;return e.filter(n=>{let i=`${n.relative_path}|${n.symbol}`;return t.has(i)?!1:(t.add(i),!0)})}function Fb(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:k(e.symbol)}}var So=new WeakMap,Nb=xt({kind:"definition-exclusions",invalidation:Je("definition-exclusions"),serialize:e=>JSON.stringify(e),deserialize:cF});function _b(e,t){let n=ye(t);if(!(n==="rust"||n==="typescript"||n==="tsx"||n==="javascript"))return[];let r=se(e,t);if(!r)return[];let o=Ft(e,t,r),s=Nb.read(e,t,o);if(s)return s;let a=n==="rust"?hF(e,t):mF(e,t);return Nb.write(e,t,o,a),a}function cF(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=t.map(lF);return n.some(i=>i===null)?null:n}catch{return null}}function lF(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?PF(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 Ob=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]),uF=/\b(?:describe|it|test|fdescribe|fit|xdescribe|xit|beforeEach|afterEach|beforeAll|afterAll|before|after|suite|bench|benchmark)\s*\(/,dF=/\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 mF(e,t){let n=se(e,t);if(!n||!pF(n))return[];let i=ae(e,t);if(!i)return[];let r=So.get(i);if(r)return r;let o=!1,s=i.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&&Ob.has(d)){o=!0;break}}let a=[];o&&a.push({startLine:0,endLine:s.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)",disposition:"exclude"});for(let c of s.namedChildren){let l=null,u=null;if(c.type==="function_declaration")l=c.namedChild(0)?.text??null,u=c;else if(c.type==="export_statement"){let d=c.namedChild(0);d?.type==="function_declaration"&&(l=d.namedChild(0)?.text??null,u=d)}else if(c.type==="lexical_declaration"){let d=c.namedChild(0);if(d?.type==="variable_declarator"){let m=d.namedChild(0)?.text,p=d.namedChild(1);m&&(p?.type==="arrow_function"||p?.type==="function_expression")&&(l=m,u=d)}}l&&/^use[A-Z]/.test(l)&&u&&a.push({startLine:u.startPosition.row,endLine:u.endPosition.row,reason:"React custom hook (use*)",disposition:"exclude"})}return a.push(...Bb(i,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),So.set(i,a),a}function pF(e){if(e.includes("codebaseiq"))return!0;let t=!1;for(let n of Ob)if(e.includes(n)){t=!0;break}return t&&uF.test(e)?!0:e.includes("use")&&dF.test(e)}var fF=/codebaseiq[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function gF(e){return fF.test(e)}function Bb(e,t,n){let i=[],r=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(gF(u.text)){i.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"codebaseiq suppression comment",disposition:"exclude"});break}continue}if(!(u.type==="attribute_item"||u.type==="inner_attribute_item"))break}}for(let s of o.namedChildren)r(s)};return r(e.rootNode),i}function hF(e,t){let n=ae(e,t);if(!n)return[];let i=So.get(n);if(i)return i;let r=[],o=yF(n);return o?(So.set(n,o),o):($b(n.rootNode,r,!1,!1),r.push(...Bb(n,new Set(["function_item","function_signature_item","struct_item","enum_item","union_item","impl_item","mod_item","static_item","const_item"]),new Set(["line_comment","block_comment"]))),r.push(...IF(n.rootNode)),So.set(n,r),r)}function yF(e){return DF(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)",disposition:"exclude"}]:null}function $b(e,t,n,i){let r=n,o=i;e.type==="trait_item"&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait declaration body (dynamic dispatch)",disposition:"implicit-usage"}),e.type==="impl_item"&&e.childForFieldName("trait")&&(o=!0,t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl block (dynamic dispatch)",disposition:"implicit-usage"})),e.type==="function_item"||e.type==="function_signature_item"?bF(e,t,n,i):i&&wF(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"?SF(e,t,n):e.type==="mod_item"&&Pu(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(r=!0);for(let s of e.namedChildren)$b(s,t,r,o)}function bF(e,t,n,i){let r=Pu(e),o=null;i?o={reason:"trait impl method (dynamic dispatch)",disposition:"implicit-usage"}:n&&(o={reason:"inside #[cfg(test)] mod",disposition:"exclude"});for(let s of r){if(jb(s)){o={reason:"#[allow(dead_code)]",disposition:"exclude"};break}let a=RF(s);if(a){o=a;break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o.reason,disposition:o.disposition})}function SF(e,t,n){let i=Pu(e),r=e.namedChildren.find(o=>o.type==="type_identifier")?.text;i.some(EF)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(...)] - generated impl may access fields",disposition:"implicit-usage",containerName:r}),i.some(jb)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",disposition:"exclude",containerName:r}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",disposition:"exclude",containerName:r})}function Pu(e){let t=e.parent;if(!t)return[];let n=t.children,i=-1;for(let o=0;o<n.length;o+=1)if(n[o].startIndex===e.startIndex&&n[o].type===e.type){i=o;break}if(i<=0)return[];let r=[];for(let o=i-1;o>=0;o-=1){let s=n[o];if(s.type==="attribute_item"||s.type==="inner_attribute_item")r.push(s.text);else{if(s.type==="line_comment"||s.type==="block_comment")continue;break}}return r}var vF=new Set(["test","bench","tokio::test","async_std::test"]),CF=new Set(["no_mangle","export_name","link_name","used","macro_export","proc_macro","proc_macro_derive","proc_macro_attribute"]),xF=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 RF(e){if(/#\[\s*cfg\s*\(\s*test\s*\)/.test(e))return{reason:"#[cfg(test)]",disposition:"exclude"};let t=LF(e);return t?vF.has(t)?{reason:`#[${t}]`,disposition:"exclude"}:CF.has(t)?{reason:`Rust ABI/export attribute #[${t}]`,disposition:"implicit-usage"}:xF.has(t)?null:{reason:`Rust attribute macro #[${t}]`,disposition:"implicit-usage"}:null}function EF(e){return/#\[\s*derive\s*\(/.test(e)}function jb(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function wF(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function IF(e){let t=TF(e);if(t.size===0)return[];let n=[];for(let i of e.descendantsOfType("mod_item")){let r=i.childForFieldName("name")?.text;r&&t.has(r)&&n.push({startLine:i.startPosition.row,endLine:i.endPosition.row,reason:'attribute `with = "..."` module - body may be invoked via reflection',disposition:"implicit-usage",containerName:r})}return n}function LF(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 PF(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 DF(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 kb=/\bwith\s*=\s*"([^"]+)"/g;function TF(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){kb.lastIndex=0;let i;for(;(i=kb.exec(n.text))!==null;){let r=i[1],o=r.split("::").pop()??r;o&&t.add(o)}}return t}function Hb(e){let t=Du(e);return(n,i,r,o)=>t(n,i,r,o)?.disposition==="exclude"}function Du(e){let t=new Map,n=i=>{let r=t.get(i);if(r)return r;let o=_b(e,i),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 r={ranges:o,containers:s},t.set(i,r),r};return(i,r,o,s)=>{let a=n(i),c=[];for(let u of a.ranges)r>=u.startLine&&r<=u.endLine&&c.push(u);let l=new Set;s&&l.add(s);for(let u of ds(o))l.add(u);for(let u of l){let d=a.containers.get(u);d&&c.push(...d)}return MF(c)}}function MF(e){if(e.length===0)return null;let n=e.find(i=>i.disposition==="exclude")??e[0];return{disposition:n.disposition,reason:n.reason}}function Tu(e,t={}){Ac(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function Ub(e,t,n={}){Ac(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function zb(e,t){if(t.isIgnoredPath(e.relativePath))return dt("ignored-file");if(Le(e.symbol))return dt("module-like-symbol");if(!Fa(e.symbol))return dt("non-value-symbol");if(!e.isFunctionLike&&e.enclosingSymbol&&Fa(e.enclosingSymbol))return dt("nested-non-callable-value");if(!t.includeTests&&!AF(e.relativePath))return dt("test-file");if(!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName))return dt("excluded-file-region");let n=re(e.symbol);if(n==="<constructor>")return dt("implicit-constructor");if(e.symbol.startsWith("scip-python ")){if(n==="__all__")return dt("python-runtime-metadata");if(/^__[^_].*__$/.test(n))return dt("python-protocol-member")}return t.isDeclarationOnlyCallable()?dt("declaration-only-callable"):t.isFrameworkContractCallable()?dt("framework-contract-member"):at(e.symbol)?dt("rust-trait-impl-member"):Ui(e.symbol)?dt("rust-test-module"):!t.includeMembers&&!FF(e)?dt("member"):e.endLine-e.startLine+1<t.minLoc?dt("below-min-loc"):{accepted:!0}}function AF(e){return V(e)!=="test"}function dt(e){return{accepted:!1,rejectionReason:e}}function Fa(e){return ke(e)||e.endsWith("().")||e.endsWith(".")}function FF(e){return it(e.symbol)||ds(e.symbol).length===0}function Gb(){return new Map}function Kb(e,t,n){let i=new Map;for(let r of ap(e,n))e.isIgnored(r.relative_path)||t.has(r.relative_path)||ka(i,r.symbol_id,r.relative_path,r.ref_count,"scip-mention");return i}function qb(e,t,n,i={}){let r=new Set;if(i.conservative||n.size===0){for(let o of lp(e,t))r.add(o.symbol_id);return r}for(let o of cp(e,t))e.isIgnored(o.relative_path)||n.has(o.relative_path)||r.add(o.symbol_id);return r}function Mu(e,t){let n=e.get(t);if(!n)return!1;for(let i of n.values())if(i.occurrences>0)return!0;return!1}function Na(e,t,n){let i=e.get(t);if(!i)return!1;for(let[r,o]of i)if(r!==n&&o.occurrences>0)return!0;return!1}function Wb(e){return e?.occurrences??0}function ka(e,t,n,i,r="source-fallback"){if(i<=0)return;let o=Jb(e,t,n);o.occurrences+=i,o.sources.add(r)}function Vb(e,t,n,i,r){if(i<=0)return;let o=Jb(e,t,n);o.occurrences=Math.max(i,o.occurrences),o.sources.add(r)}function Jb(e,t,n){let i=e.get(t);i||(i=new Map,e.set(t,i));let r=i.get(n);return r||(r={occurrences:0,sources:new Set},i.set(n,r)),r}var NF=new Set(["componentDidCatch","componentDidMount","componentDidUpdate","componentWillUnmount","getDerivedStateFromError","getDerivedStateFromProps","getSnapshotBeforeUpdate","render","shouldComponentUpdate","UNSAFE_componentWillMount","UNSAFE_componentWillReceiveProps","UNSAFE_componentWillUpdate"]);function ur(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=ae(e,t.relativePath);if(!n)return!1;let i=n.rootNode.descendantsOfType("method_definition").find(s=>s.startPosition.row<=t.startLine&&s.endPosition.row>=t.endLine);if(!i)return!1;if(/\boverride\b/.test(i.text.slice(0,Math.max(0,i.text.indexOf("{")))))return!0;let r=i.parent;for(;r&&r.type!=="class_declaration"&&r.type!=="class";)r=r.parent;if(!r)return!1;let o=r.text.slice(0,Math.max(0,r.text.indexOf("{")));return/\bimplements\b/.test(o)||/\bextends\b/.test(o)?!0:NF.has(t.leaf)&&/\bextends\s+(?:React\.)?(?:Component|PureComponent)\b/.test(o)}function Ti(e,t={}){let{scope:n,minLoc:i=1,includeTests:r=!1,skipBarrels:o=!1,includeMembers:s=!1,deadCodeOnly:a=!1,scanLimit:c,semantic:l=!0}=t,u=0,d=$("dead.candidates",()=>{let S=Fe(kF(e,{scope:n,minLoc:i,includeTests:r,includeMembers:s}),c);return u=S.length,S},()=>({definitions:u})),m=0,p=o?$("dead.inactive-barrels",()=>{let S=new Set(Tg(e));return m=S.size,S},()=>({paths:m})):new Set,f=0,g=a?Gb():$("dead.mention-reference-counts",()=>{let S=Kb(e,p,d.map(R=>R.symbolId));return f=S.size,S},()=>({definitions:d.length,symbolsWithReferences:f})),h=0,b=a?$("dead.mentioned-symbol-ids",()=>{let S=qb(e,d.map(R=>R.symbolId),p,{conservative:p.size===0});return h=S.size,S},()=>({definitions:d.length,referencedSymbols:h})):new Set,v=a?d.filter(S=>!b.has(S.symbolId)):d.filter(S=>!Na(g,S.symbolId,S.relativePath));a?$("dead.source-fallback.dead-code-only",()=>UF(e,v,g,{inactiveBarrelPaths:p}),()=>({definitions:v.length,testReferencesIncluded:!0})):$("dead.source-fallback.ast",()=>HF(e,v,g,{inactiveBarrelPaths:p}),()=>({definitions:v.length,testReferencesIncluded:!0}));let y=a?v.filter(S=>!Mu(g,S.symbolId)):v.filter(S=>!Na(g,S.symbolId,S.relativePath)),E=new Set;$("dead.caller-map-supplement",()=>{E=qF(e,y,g,{inactiveBarrelPaths:p,includeSemantic:!a&&l})},()=>({definitions:y.length,semantic:!a&&l}));let w=a?v.filter(S=>!Mu(g,S.symbolId)):d.filter(S=>!E.has(S.symbolId));return jF(e,BF(w,g))}function kF(e,t){let n=Hb(e),i=[];for(let r of Dr(e,{scope:t.scope,symbolMatches:Fa,sqlPrefilter:"function-like"}))zb(r,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:s=>e.isIgnored(s),isExcludedRegion:n,isDeclarationOnlyCallable:()=>OF(e,r),isFrameworkContractCallable:()=>ur(e,r)}).accepted&&i.push(r);return i}var _F=["method_signature","abstract_method_signature","call_signature","construct_signature"];function OF(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([..._F]).some(r=>r.startPosition.row<=t.startLine&&r.endPosition.row>=t.endLine);let i=ie(e,t.relativePath).slice(t.startLine,t.endLine+1).join(`
119
- `).trim();return i.endsWith(";")&&!i.includes("=>")&&!i.includes("{")}function BF(e,t){return e.map(n=>$F(n,t)).filter(n=>n.cross_file_refs===0).sort((n,i)=>i.loc-n.loc||n.relative_path.localeCompare(i.relative_path)||n.start_line-i.start_line)}function $F(e,t){let n=t.get(e.symbolId)??new Map,i=Wb(n.get(e.relativePath)),r=0;for(let[o,s]of n)o!==e.relativePath&&(r+=s.occurrences);return{relative_path:e.relativePath,start_line:e.startLine,end_line:e.endLine,loc:e.endLine-e.startLine+1,symbol:e.symbol,parent_type_name:e.parentTypeName,same_file_refs:i,cross_file_refs:r}}function jF(e,t){let n=Du(e),i=[],r=0,o=0,s=0,a=0,c=0,l=0;for(let u of t){if(e.isIgnored(u.relative_path))continue;if(Ye(e,u.relative_path)){a++;continue}if(Ue(e,u.symbol,u.relative_path)){c++;continue}let d=n(u.relative_path,u.start_line,u.symbol,u.parent_type_name),m=d?.disposition==="implicit-usage"?d.reason:void 0,p=m?"implicit-usage":u.same_file_refs===0?"dead-code":"file-internal";p==="dead-code"?r++:p==="file-internal"?o++:s++,l+=u.loc,i.push({relativePath:u.relative_path,startLine:u.start_line,endLine:u.end_line,loc:u.loc,symbol:u.symbol,shortName:k(u.symbol),sameFileRefs:u.same_file_refs,kind:p,...m?{implicitUsageReason:m}:{}})}return{symbols:i,counts:{total:i.length,deadCode:r,fileInternal:o,implicitUsage:s,loc:l},applicability:{entrySurfaceExcluded:a,externalRootExcluded:c,implicitUsageSignals:s},totalCount:i.length,deadCodeCount:r,fileInternalCount:o,implicitUsageCount:s,totalLoc:l}}function HF(e,t,n,i){if(t.length===0)return;let r=new U(e),o=new Set(t.map(c=>c.symbolId)),s=new Set(t.map(c=>c.leaf).filter(Boolean)),a=new Set(r.sourceFiles());for(let c of he(e))a.add(c);r.scanSourceReferences({paths:a,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:s,skipPath:c=>i.inactiveBarrelPaths.has(c)},c=>{o.has(c.target.symbolId)&&(GF(e,c)||ka(n,c.target.symbolId,c.sourceFile,KF(c),"source-fallback"))})}function UF(e,t,n,i){if(t.length===0)return;let r=new U(e),o=tp(t),s=new Set(r.sourceFiles());for(let u of he(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let d=c.get(u);return d||(d=mp(e,u),c.set(u,d)),d};r.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:u=>i.inactiveBarrelPaths.has(u),resolveTargets:({sourceFile:u,name:d,kind:m})=>{let p=o.get(d);return p?zF(u,d,p,()=>l(u),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),Ub(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&Yb(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||ka(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function zF(e,t,n,i,r){let o=n.filter(l=>l.relativePath===e);if(o.length>0)return o;if(!r.permissive&&n.length===1)return[...n];let s=i(),a=s.get(t);if(a)for(let l of a){let u=n.filter(d=>Mt(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=>Mt(l,d.relativePath));if(u.length>0&&u.length===n.length)return u}return r.permissive?[...n]:[]}function GF(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&Yb(e,t)}function KF(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function Yb(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 qF(e,t,n,i){let r=new Set,o=i.includeSemantic!==!1,s=(u,d)=>{d===u.relativePath||e.isIgnored(d)||i.inactiveBarrelPaths.has(d)||Vb(n,u.symbolId,d,1,"caller-map")};if($("dead.caller-map.per-symbol-non-semantic",()=>{for(let u of t){let d=Is(e,u,{semantic:!1,semanticEvidence:fe});for(let m of d)s(u,m.file)}},()=>({definitions:t.length,semantic:!1})),!o)return r;let a=0,c=$("dead.caller-map.semantic-candidates",()=>{let u=t.filter(d=>!Na(n,d.symbolId,d.relativePath));return a=u.length,u},()=>({definitions:t.length,semanticCandidates:a}));if(c.length===0)return r;let l=Rn(e,c);for(let u of l.incompleteSymbolIds)r.add(u);for(let u of l.unavailableSymbolIds)r.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 r}function WF(e,t={}){let{limit:n=30,scope:i}=t,r=i?"AND def_d.relative_path LIKE ?":"",o=i?[`%${i}%`]:[],a=e.all(`SELECT
120
- gs.symbol,
121
- COUNT(*) AS ref_count,
122
- COUNT(DISTINCT ref_d.id) AS file_count,
123
- def_d.relative_path AS defined_in
124
- FROM mentions m
125
- JOIN chunks c ON m.chunk_id = c.id
126
- JOIN documents ref_d ON c.document_id = ref_d.id
127
- JOIN global_symbols gs ON m.symbol_id = gs.id
128
- JOIN (
129
- SELECT m2.symbol_id, c2.document_id
130
- FROM mentions m2
131
- JOIN chunks c2 ON m2.chunk_id = c2.id
132
- WHERE m2.role = 1
133
- GROUP BY m2.symbol_id
134
- ) sym_def ON sym_def.symbol_id = gs.id
135
- JOIN documents def_d ON sym_def.document_id = def_d.id
136
- WHERE m.role != 1
137
- AND def_d.id != ref_d.id
138
- ${e.pathExclusionsFor("def_d")}
139
- ${e.symbolNoiseFor("gs")}
140
- ${r}
141
- GROUP BY gs.id
142
- ORDER BY ref_count DESC
143
- LIMIT ?`,...o,n).filter(c=>!e.isIgnored(c.defined_in)).map(c=>({symbol:c.symbol,shortName:k(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}}}:VF(e,i,n)}function VF(e,t,n){let i=ze(e,{scope:t}).filter(a=>!e.isIgnored(a.relativePath)),r=tn(e,i,{limit:500,semanticEvidence:fe}),o=i.filter(a=>!r.incompleteSymbolIds.has(a.symbolId)&&!r.unavailableSymbolIds.has(a.symbolId)).map(a=>JF(a,r.rows.get(a.symbolId)??[])).filter(a=>a.refCount>0).sort((a,c)=>c.refCount-a.refCount||c.fileCount-a.fileCount).slice(0,n),s=r.incompleteSymbolIds.size>0&&r.unavailableSymbolIds.size>0?"incomplete-and-unavailable":r.incompleteSymbolIds.size>0?"incomplete":r.unavailableSymbolIds.size>0?"unavailable":"complete";return{rows:o,coverage:{semanticEvidence:{enabled:!0,status:s,incompleteSymbolCount:r.incompleteSymbolIds.size,unavailableSymbolCount:r.unavailableSymbolIds.size}}}}function JF(e,t){let n=t.filter(i=>i.file!==e.relativePath);return{symbol:e.symbol,shortName:k(e.symbol),refCount:n.length,fileCount:new Set(n.map(i=>i.file)).size,definedIn:e.relativePath,basis:"source-backed-incoming-evidence",countUnit:"distinct-incoming-evidence-rows"}}function YF(e,t,n={}){return sN(e,t,n)?.map(i=>({symbol:i.symbol,shortName:i.shortName,fromFile:i.fromFile}))??[]}function XF(e,t){let n=pe(e,t),i=eN(e,t);if(i.length>0&&!nN(n))return i;let r=tN(e,t,n);return Au(t)&&r.length>0?r:iN([...i,...r])}function QF(e,t,n={}){let i=ct(e,t);if(!i)return[];let r=Qb(e,i),o=n.semantic===!1?null:Xb(e,i);return(o?ZF(o,r):r).filter(a=>!a.used).map(a=>({symbol:a.symbol,shortName:a.shortName,importedIn:a.importer}))}function ZF(e,t){let n=new Map;for(let r of t){let o=n.get(r.shortName);o?o.push(r):n.set(r.shortName,[r])}let i=e.map(r=>{let o=n.get(r.shortName),s=o?.shift();return o?.length===0&&n.delete(r.shortName),s?{...r,used:r.used||s.used}:r});return i.push(...[...n.values()].flat()),i}function eN(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
144
- FROM mentions m
145
- JOIN chunks c ON m.chunk_id = c.id
146
- JOIN documents d ON c.document_id = d.id
147
- JOIN global_symbols gs ON m.symbol_id = gs.id
148
- WHERE gs.symbol LIKE ?
149
- AND m.role = 2
150
- ORDER BY d.relative_path`,`%${t}%`).filter(i=>!e.isIgnored(i.importer)).map(i=>({symbol:i.symbol,shortName:k(i.symbol),fromFile:i.importer}))}function tN(e,t,n=pe(e,t)){let i=n?.relativePath??null,r=n?re(n.symbol):t.replace(/\(\)$/,""),o=n?Le(n.symbol):!1,s=new Set;for(let c of he(e,{includeIgnored:!1}))for(let l of Ce(e,c))rN(l,c,{targetFile:i,targetLeaf:r,targetIsModule:o,targetPattern:t})&&s.add(c);let a=Au(t)?t.trim():null;return[...s].sort().map(c=>({symbol:a??n?.symbol??r,shortName:a??(n?k(n.symbol):r),fromFile:c}))}function nN(e){return!!(e&&(e.symbol.startsWith("scip-clojure ")||ye(e.relativePath)==="clojure"))}function iN(e){let t=new Set,n=[];for(let i of e){let r=`${i.symbol}|${i.fromFile}`;t.has(r)||(t.add(r),n.push(i))}return n.sort((i,r)=>i.fromFile.localeCompare(r.fromFile)||i.shortName.localeCompare(r.shortName))}function rN(e,t,n){return!e.sourcePath||n.targetFile&&pt(e.sourcePath)!==pt(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&uN(t)||e.kind==="namespace"&&oN(e,n.targetPattern)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function oN(e,t){let n=t.trim().replace(/\(\)$/,"");return Au(n)?e.importedName===n||e.localName===n:!1}function Au(e){let t=e.trim().replace(/\(\)$/,"");return t.includes(".")&&!t.includes("/")&&!t.includes(":")}function sN(e,t,n={}){let i=ct(e,t);return i?aN(e,i,n)??(n.semantic===!1?null:Xb(e,i))??Qb(e,i):null}function aN(e,t,n){let r=e.all(`SELECT DISTINCT
151
- gs.symbol,
152
- def_d.relative_path AS from_file,
153
- imp_d.relative_path AS importer,
154
- EXISTS (
155
- SELECT 1
156
- FROM mentions ref_m
157
- JOIN chunks ref_c ON ref_m.chunk_id = ref_c.id
158
- WHERE ref_m.symbol_id = gs.id
159
- AND ref_m.role != 1
160
- AND ref_c.document_id = imp_d.id
161
- ) AS used
162
- FROM mentions m
163
- JOIN chunks c ON m.chunk_id = c.id
164
- JOIN documents imp_d ON c.document_id = imp_d.id
165
- JOIN global_symbols gs ON m.symbol_id = gs.id
166
- LEFT JOIN (
167
- SELECT m2.symbol_id, c2.document_id
168
- FROM mentions m2
169
- JOIN chunks c2 ON m2.chunk_id = c2.id
170
- WHERE m2.role = 1
171
- GROUP BY m2.symbol_id
172
- ) sym_def ON sym_def.symbol_id = gs.id
173
- LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
174
- WHERE imp_d.relative_path = ?
175
- AND m.role = 2
176
- ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(r.length>0){let o=n.semantic===!1?[]:Vr(e,t);return r.map(s=>({symbol:s.symbol,shortName:k(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 Xb(e,t){let n=Vr(e,t);return n.length>0?n.map(i=>{let r=Zb(i.importedName,i.localName,i.kind);return{symbol:r,shortName:r,fromFile:i.sourcePath??"(external)",importer:t,used:i.kind==="side-effect"?!0:i.isUsed}}):null}function Qb(e,t){let n=cN(t,se(e,t));return Ce(e,t).map(i=>{let r=Zb(i.importedName,i.localName,i.kind),o=i.kind==="side-effect"||lN(t,i)||n.has(i.localName??i.importedName)?!0:i.used;return{symbol:r,shortName:r,fromFile:i.sourcePath??"(external)",importer:t,used:o}})}function cN(e,t){let n=new Set;if(ye(e)!=="python")return n;let i=/(?:^|\n)\s*__all__\s*(?:\+?=)\s*[[(]([\s\S]*?)[\])]/g;for(let r of t.matchAll(i)){let o=r[1]??"";for(let s of o.matchAll(/(['"])([A-Za-z_]\w*)\1/g))n.add(s[2])}return n}function lN(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 Zb(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 uN(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function dN(e,t){let n=pe(e,t);if(!n)return[];let r=new U(e).definitionsForFile(n.relativePath).filter(o=>o.symbol!==n.symbol).filter(o=>Zm(n.symbol,o.symbol)).sort((o,s)=>o.startLine-s.startLine||o.endLine-s.endLine).map(o=>({symbol:o.symbol,shortName:k(o.symbol),startLine:o.startLine,endLine:o.endLine,kind:Bn(o.symbol)??"unknown"}));return ye(n.relativePath)!=="clojure"?r:pN(r,mN(e,n))}function mN(e,t){let n=re(t.symbol);if(!n)return[];let i=k(t.symbol);return(ee(e,t.relativePath)?.clojureMembers??[]).filter(r=>r.ownerName===n).map(r=>({symbol:`${t.symbol}${r.memberName}().`,shortName:`${i}:${r.memberName}()`,startLine:r.startLine,endLine:r.endLine,kind:r.memberKind}))}function pN(e,t){let n=new Map;for(let i of[...e,...t])n.set(`${i.shortName}:${i.startLine}:${i.endLine}`,i);return[...n.values()].sort((i,r)=>i.startLine-r.startLine||i.endLine-r.endLine)}function fN(e,t){let n=pe(e,t);if(!n)return[];let i=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
177
- FROM mentions m
178
- JOIN chunks c ON m.chunk_id = c.id
179
- JOIN (
180
- SELECT m2.symbol_id, c2.document_id
181
- FROM mentions m2
182
- JOIN chunks c2 ON m2.chunk_id = c2.id
183
- WHERE m2.role = 1
184
- GROUP BY m2.symbol_id
185
- ) sym_def ON sym_def.symbol_id = m.symbol_id
186
- WHERE m.symbol_id = ?
187
- AND m.role != 1
188
- AND sym_def.document_id != c.document_id`,n.symbolId);return[{name:k(n.symbol),count:i?.file_count??0,symbol:n.symbol,definedIn:n.relativePath}]}function gN(e,t){let n=ct(e,t);return n?e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
189
- FROM mentions m
190
- JOIN chunks c ON m.chunk_id = c.id
191
- JOIN documents d ON c.document_id = d.id
192
- JOIN global_symbols gs ON m.symbol_id = gs.id
193
- JOIN (
194
- SELECT m2.symbol_id, c2.document_id
195
- FROM mentions m2
196
- JOIN chunks c2 ON m2.chunk_id = c2.id
197
- WHERE m2.role = 1
198
- GROUP BY m2.symbol_id
199
- ) sym_def ON sym_def.symbol_id = gs.id
200
- JOIN documents def_d ON sym_def.document_id = def_d.id
201
- WHERE d.relative_path = ?
202
- AND m.role != 1
203
- AND def_d.id != d.id
204
- GROUP BY d.id
205
- 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 hN(e,t={}){return yN(e,t).map(n=>({name:k(n.symbol),count:n.file_count,symbol:n.symbol,definedIn:n.defined_in}))}function yN(e,t){let{limit:n=30,scope:i}=t,r=i?"AND def_d.relative_path LIKE ?":"",o=i?[`%${i}%`]:[];return e.all(`SELECT gs.symbol,
206
- COUNT(DISTINCT c.document_id) AS file_count,
207
- def_d.relative_path AS defined_in
208
- FROM mentions m
209
- JOIN chunks c ON m.chunk_id = c.id
210
- JOIN global_symbols gs ON m.symbol_id = gs.id
211
- JOIN (
212
- SELECT m2.symbol_id, c2.document_id
213
- FROM mentions m2
214
- JOIN chunks c2 ON m2.chunk_id = c2.id
215
- WHERE m2.role = 1
216
- GROUP BY m2.symbol_id
217
- ) sym_def ON sym_def.symbol_id = gs.id
218
- JOIN documents def_d ON sym_def.document_id = def_d.id
219
- WHERE m.role != 1
220
- AND def_d.id != c.document_id
221
- ${e.pathExclusionsFor("def_d")}
222
- ${e.symbolNoiseFor("gs")}
223
- ${r}
224
- GROUP BY gs.id
225
- HAVING file_count > 1
226
- ORDER BY file_count DESC
227
- LIMIT ?`,...o,n)}function bN(e,t={}){let{limit:n=30,scope:i}=t,r=i?"AND d.relative_path LIKE ?":"",o=i?[`%${i}%`]:[];return e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
228
- FROM mentions m
229
- JOIN chunks c ON m.chunk_id = c.id
230
- JOIN documents d ON c.document_id = d.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 != d.id
242
- ${e.pathExclusionsFor("d")}
243
- ${e.symbolNoiseFor("gs")}
244
- ${r}
245
- GROUP BY d.id
246
- ORDER BY symbol_count DESC
247
- LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}))}var eS=`SELECT COUNT(*) AS shared
248
- FROM (
249
- SELECT definition_m.symbol_id
250
- FROM documents definition_d
251
- JOIN chunks definition_c ON definition_c.document_id = definition_d.id
252
- JOIN mentions definition_m ON definition_m.chunk_id = definition_c.id
253
- AND definition_m.role = 1
254
- JOIN mentions reference_m ON reference_m.symbol_id = definition_m.symbol_id
255
- AND reference_m.role != 1
256
- JOIN chunks reference_c ON reference_c.id = reference_m.chunk_id
257
- JOIN documents reference_d ON reference_d.id = reference_c.document_id
258
- WHERE definition_d.relative_path = ?
259
- AND reference_d.relative_path = ?
260
- UNION
261
- SELECT definition_m.symbol_id
262
- FROM documents definition_d
263
- JOIN chunks definition_c ON definition_c.document_id = definition_d.id
264
- JOIN mentions definition_m ON definition_m.chunk_id = definition_c.id
265
- AND definition_m.role = 1
266
- JOIN mentions reference_m ON reference_m.symbol_id = definition_m.symbol_id
267
- AND reference_m.role != 1
268
- JOIN chunks reference_c ON reference_c.id = reference_m.chunk_id
269
- JOIN documents reference_d ON reference_d.id = reference_c.document_id
270
- WHERE definition_d.relative_path = ?
271
- AND reference_d.relative_path = ?
272
- )`;function SN(e,t,n){let i=ct(e,t)??t,r=ct(e,n)??n,o=e.get(eS,i,r,r,i);return{...tS(i,r,o?.shared??0)}}function vN(e,t={}){let{limit:n=20,scope:i}=t,r=i?"AND def_d.relative_path LIKE ? AND ref_d.relative_path LIKE ?":"",o=i?[`%${i}%`,`%${i}%`]:[];return e.all(`SELECT
273
- CASE WHEN def_d.relative_path < ref_d.relative_path THEN def_d.relative_path ELSE ref_d.relative_path END AS file1,
274
- CASE WHEN def_d.relative_path < ref_d.relative_path THEN ref_d.relative_path ELSE def_d.relative_path END AS file2,
275
- COUNT(DISTINCT gs.id) AS shared
276
- FROM mentions m
277
- JOIN chunks c ON m.chunk_id = c.id
278
- JOIN documents ref_d ON c.document_id = ref_d.id
279
- JOIN global_symbols gs ON m.symbol_id = gs.id
280
- JOIN (
281
- SELECT m2.symbol_id, c2.document_id
282
- FROM mentions m2
283
- JOIN chunks c2 ON m2.chunk_id = c2.id
284
- WHERE m2.role = 1
285
- GROUP BY m2.symbol_id
286
- ) sym_def ON sym_def.symbol_id = gs.id
287
- JOIN documents def_d ON sym_def.document_id = def_d.id
288
- WHERE m.role != 1
289
- AND def_d.id != ref_d.id
290
- ${e.pathExclusionsFor("def_d","ref_d")}
291
- ${r}
292
- GROUP BY file1, file2
293
- ORDER BY shared DESC, file1, file2
294
- LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.file1)&&!e.isIgnored(a.file2)).map(a=>tS(a.file1,a.file2,a.shared))}function tS(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 Mi(e){let t=new Map,n=[],i=new Map,r=new Map,o=new Set,s=[],a=0,c=l=>(e.get(l)??[]).values();for(let l of e.keys()){if(i.has(l))continue;let u=[];for(i.set(l,a),r.set(l,a),a+=1,s.push(l),o.add(l),u.push({node:l,iter:c(l),pendingChild:null});u.length>0;){let d=u[u.length-1];if(d.pendingChild!==null){let f=d.pendingChild;d.pendingChild=null,r.set(d.node,Math.min(r.get(d.node),r.get(f)))}let m=d.iter.next();if(m.done){if(r.get(d.node)===i.get(d.node)){let f=[];for(;;){let g=s.pop();if(o.delete(g),f.push(g),t.set(g,n.length),g===d.node)break}n.push(f)}u.pop();continue}let p=m.value;i.has(p)?o.has(p)&&r.set(d.node,Math.min(r.get(d.node),i.get(p))):(i.set(p,a),r.set(p,a),a+=1,s.push(p),o.add(p),d.pendingChild=p,u.push({node:p,iter:c(p),pendingChild:null}))}}return{components:n,componentOf:t}}function vo(e,t={}){return rS(e,t).cycles}function rS(e,t={}){return oS(e,t)}function oS(e,t={}){let{scope:n,maxDepth:i=10,edgeBasis:r="symbol-references"}=t,o=Oe(e,n,r==="imports"?{scipEdges:"imports-only",sourceEdges:"imports-only"}:void 0),{components:s}=Mi(o),a=s.filter(c=>CN(o,c)).map(c=>{let l=[...c].sort(),u=xN(o,l),d=EN(u);return{path:u,component:l,edgeBasis:r,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:r,maxDepth:i}}function CN(e,t){if(t.length>1)return!0;let n=t[0];return n!==void 0&&e.get(n)?.has(n)===!0}function xN(e,t){let n=t[0];if(!n)return[];let i=new Set(t);for(let r of[...e.get(n)??[]].filter(o=>i.has(o)).sort()){if(r===n)return[n,n];let o=RN(e,r,n,i);if(o)return[n,...o]}throw new Error(`Cyclic component did not contain a witness path from ${n}.`)}function RN(e,t,n,i){let r=[t],o=new Map([[t,null]]);for(let s=0;s<r.length;s+=1){let a=r[s];if(a===n){let 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=>i.has(l)).sort())o.has(c)||(o.set(c,a),r.push(c))}return null}function EN(e){for(let i of e){let r=V(i);if(r==="test"||r==="barrel"||r==="entry")return"module-hierarchy"}if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":Qi(t)||Qi(n)||nS(t,n)||nS(n,t)||iS(t,n)||iS(n,t)||V(t)==="entry"||V(n)==="entry"?"module-hierarchy":"real"}function nS(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 iS(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=e.replace(/\.rs$/,""),i=t.replace(/\.rs$/,"");if(n===i+"_tests"||n===i+"/tests")return!0;let r=e.split("/"),o=t.split("/");if(r.length===o.length&&r.includes("tests")&&o.includes("src")){let s=r[r.length-1],a=o[o.length-1];if(s&&s===a)return!0}return!1}import{readdirSync as wN}from"fs";import{join as cS}from"path";function aS(e,t){let n=sS(e),i=sS(t);if(n.endsWith("/**")){let r=n.slice(0,-3);return i===r||i.startsWith(`${r}/`)}if(n.endsWith("/*")){let r=n.slice(0,-2);if(!i.startsWith(`${r}/`))return!1;let o=i.slice(r.length+1);return o.length>0&&!o.includes("/")}return n==="**"?!0:n==="*"?i.length>0&&!i.includes("/"):n===i}function sS(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}function Qn(e,t){return aS(e,t)}function IN(e){return lS(e).replace(/\/\*\*?$/,"")}function _a(e,t){let n=lS(t),i=IN(n),r=n.endsWith("/**"),o=[],s=(a,c)=>{let l;try{l=wN(a,{withFileTypes:!0})}catch{return}for(let u of l){if(u.name.startsWith("."))continue;let d=c?`${c}/${u.name}`:u.name;Qn(n,d)&&o.push(d),r&&u.isDirectory()&&s(cS(a,u.name),d)}};return s(cS(e,i),i),o.sort()}function lS(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}var LN=/\.(test|spec)\.(ts|tsx|js|jsx|mts|cts)$/,uS=new Map;function dS(e,t,n,i){if(!t?.testPaths?.length)return[];let r=PN(t),o=[];for(let s of DN(e,t.testPaths)){let a=TN(e,s,i),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&&(r.get(c)?.has(d)||o.push({testFile:s,ownerBoundary:c,importedFile:u,importedBoundary:d,reason:"outside-owner-policy"}))}}return MN(o)}function PN(e){let t=e.allowedDependencies??{},n=e.boundaries.map(s=>s.name),i=new Map,r=(s,a)=>{for(let c of t[s]??[])a.has(c)||(a.add(c),r(c,a))};for(let s of n){let a=new Set;r(s,a),i.set(s,a)}let o=new Map;for(let s of n){let a=new Set(i.get(s));for(let c of n)c!==s&&i.get(c)?.has(s)&&a.add(c);o.set(s,a)}return o}function DN(e,t){let n=`${e.config.projectRoot}\0${t.join("\0")}`,i=uS.get(n);if(i)return i;let r=new Set;for(let s of t)for(let a of _a(e.config.projectRoot,s))LN.test(a)&&r.add(a);let o=[...r].sort();return uS.set(n,o),o}function TN(e,t,n){let i=t.replace(/^tests\//,"src/").replace(/\.(test|spec)\.(\w+)$/,".$2");if(i!==t&&n(i))return i;let r=t.split("/").pop().replace(/\.(test|spec)\.(\w+)$/,".$2"),o=Ce(e,t).map(s=>s.sourcePath).filter(s=>!!s&&n(s)&&s.split("/").pop()===r);return o.length===1?o[0]:null}function MN(e){let t=new Map;for(let n of e){let i=`${n.testFile}\0${n.importedBoundary}`;t.has(i)||t.set(i,n)}return[...t.values()].sort((n,i)=>n.testFile.localeCompare(i.testFile)||n.importedBoundary.localeCompare(i.importedBoundary))}function mS(e,t){let n=(e?.boundaries??[]).filter(i=>i.paths.some(r=>Qn(r,t)));return n.length===1?n[0].name:null}var An="architecture:";function pS(e,t,n,i={}){let r=FN(e,t);if(!n||n.boundaries.length===0)return{configured:!1,boundaries:[],edges:[],forbiddenEdges:[],reciprocalPairs:[],cycles:[],coarseBoundaries:[],staleAllowances:[],boundaryLimits:[],fragileEdges:[],testBoundaryViolations:[],coverage:{totalFiles:r.length,mappedFiles:0,unmappedFiles:[],ambiguousFiles:[]},policyCoverage:{declaredRows:0,totalBoundaries:0,missingRows:[],requiresCompletePolicy:!1,requiresCompleteCoverage:!1,requiresMinimalPolicy:!1}};let o=new Map,s=new Map(n.boundaries.map(y=>[y.name,new Set])),a=[],c=[];for(let y of r){let E=n.boundaries.filter(w=>w.paths.some(S=>Qn(S,y))).map(w=>w.name).sort();if(E.length===0)a.push(y);else if(E.length>1)c.push({file:y,boundaries:E});else{let w=E[0];o.set(y,w),s.get(w).add(y)}}let l=new Map;for(let[y,E]of e){let w=o.get(y);if(w)for(let S of E){let R=o.get(S);if(!R||w===R)continue;let C=dr(w,R),L=l.get(C);L||(L={from:w,to:R,fileEdges:[],importers:new Set,importedFiles:new Set},l.set(C,L)),L.fileEdges.push({fromFile:y,toFile:S}),L.importers.add(y),L.importedFiles.add(S)}}let u=[...l.values()].map(y=>NN(y,n)).sort(UN),d=u,m=new Map(d.map(y=>[dr(y.from,y.to),y])),p=new Map(n.boundaries.map(y=>[y.name,new Set]));for(let y of d)p.get(y.from).add(y.to);let f=[];for(let y of d){if(y.from>=y.to)continue;let E=m.get(dr(y.to,y.from));E&&f.push({boundaries:[y.from,y.to],forward:y,reverse:E})}let{components:g}=Mi(p),h=g.filter(y=>y.length>1).map(y=>_N(y,d,n.requireAcyclic===!0)).sort((y,E)=>E.boundaries.length-y.boundaries.length||y.boundaries.join("/").localeCompare(E.boundaries.join("/"))),b=n.allowedDependencies??{},v=n.boundaries.map(y=>y.name).filter(y=>!Object.hasOwn(b,y)).sort();return{configured:!0,boundaries:n.boundaries.map(y=>({name:y.name,paths:[...y.paths],fileCount:s.get(y.name).size,dependencyPolicyDeclared:Object.hasOwn(b,y.name)})).sort((y,E)=>y.name.localeCompare(E.name)),edges:u,forbiddenEdges:d.filter(y=>y.policyStatus==="forbidden"),reciprocalPairs:f,cycles:h,staleAllowances:BN(n,d),boundaryLimits:$N(n,d,s),fragileEdges:d.filter(y=>y.fragile),testBoundaryViolations:i.testBoundaryViolations??[],coarseBoundaries:ON(e,s,i.isModuleHierarchyFile,n.requireResolvedBoundaries===!0,y=>n.boundaries.find(E=>E.name===y)?.subUnits??"directory"),coverage:{totalFiles:r.length,mappedFiles:o.size,unmappedFiles:a,ambiguousFiles:c},policyCoverage:{declaredRows:n.boundaries.length-v.length,totalBoundaries:n.boundaries.length,missingRows:v,requiresCompletePolicy:n.requireCompletePolicy===!0,requiresCompleteCoverage:n.requireCompleteCoverage===!0,requiresMinimalPolicy:n.requireMinimalPolicy===!0}}}function Co(e,t={}){let n=Oe(e,t.scope,{scipEdges:"imports-only",sourceEdges:"imports-and-reexports"}),i=he(e,{includeIgnored:!1}).filter(o=>!t.scope||o.includes(t.scope)),r=new Set(i);return pS(n,i,e.config.architecture,{isModuleHierarchyFile:o=>AN(e,o),testBoundaryViolations:dS(e,e.config.architecture,o=>mS(e.config.architecture,o),o=>r.has(o))})}function AN(e,t){let n=V(t);return n==="test"||n==="entry"?!0:n!=="barrel"?!1:J(e,t).length===0}function Fu(e){let t=e.forbiddenEdges.map(i=>`${An}forbidden-edge:${encodeURIComponent(i.from)}:${encodeURIComponent(i.to)}`);if(e.policyCoverage.requiresCompletePolicy)for(let i of e.policyCoverage.missingRows)t.push(`${An}missing-policy-row:${encodeURIComponent(i)}`);if(e.policyCoverage.requiresCompleteCoverage){for(let i of e.coverage.unmappedFiles)t.push(`${An}unmapped-file:${encodeURIComponent(i)}`);for(let i of e.coverage.ambiguousFiles)t.push(`${An}ambiguous-file:${encodeURIComponent(i.file)}:${i.boundaries.map(r=>encodeURIComponent(r)).sort().join("|")}`)}if(e.policyCoverage.requiresMinimalPolicy)for(let i of e.staleAllowances)t.push(`${An}stale-allowance:${encodeURIComponent(i.from)}:${encodeURIComponent(i.to)}`);for(let i of e.testBoundaryViolations)t.push(`${An}test-boundary:${encodeURIComponent(i.testFile)}:${encodeURIComponent(i.importedBoundary)}`);for(let i of e.boundaryLimits)t.push(`${An}boundary-limit:${i.kind}:${encodeURIComponent(i.boundary)}`);let n=new Map;for(let i of e.coarseBoundaries)i.violatesPolicy&&n.set(i.boundary,(n.get(i.boundary)??0)+1);for(let[i,r]of n){let o=`${An}coarse-boundary:${encodeURIComponent(i)}`;t.push(o);for(let s=2;s<=r;s+=1)t.push(`${o}:component:${s}`)}for(let i of e.cycles)i.violatesPolicy&&t.push(`${An}cycle:${i.boundaries.map(r=>encodeURIComponent(r)).sort().join("|")}`);return[...new Set(t)].sort()}function FN(e,t){let n=new Set(t);for(let[i,r]of e){n.add(i);for(let o of r)n.add(o)}return[...n].sort()}function NN(e,t){let n=[...e.fileEdges].sort((i,r)=>i.fromFile.localeCompare(r.fromFile)||i.toFile.localeCompare(r.toFile));return{from:e.from,to:e.to,policyStatus:kN(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 kN(e,t,n){return!e.allowedDependencies||!Object.hasOwn(e.allowedDependencies,t)?"undeclared":e.allowedDependencies[t].includes(n)?"allowed":"forbidden"}function _N(e,t,n){let i=[...e].sort(),r=new Set(i),o=t.filter(a=>r.has(a.from)&&r.has(a.to)),s=Math.min(...o.map(a=>a.fileEdgeCount));return{boundaries:i,internalEdges:o,narrowestEdges:o.filter(a=>a.fileEdgeCount===s),violatesPolicy:n}}function ON(e,t,n=jN,i=!1,r=()=>"directory"){let o=[];for(let[s,a]of t){let c=r(s)==="file"?f=>f:HN,l=[...a].filter(f=>!n(f));if(l.length<2)continue;let u=new Set(l),d=new Map,m=new Map;for(let f of l)m.set(c(f),new Set);for(let f of l)for(let g of e.get(f)??[]){if(!u.has(g))continue;let h=c(f),b=c(g);if(h===b)continue;let v=dr(h,b),y=d.get(v);y||(y={from:h,to:b,fileEdges:[]},d.set(v,y)),y.fileEdges.push({fromFile:f,toFile:g}),m.get(h).add(b)}let{components:p}=Mi(m);for(let f of p){if(f.length<2)continue;let g=new Set(f),h=[...d.values()].filter(v=>g.has(v.from)&&g.has(v.to)).map(v=>({from:v.from,to:v.to,fileEdgeCount:v.fileEdges.length,examples:v.fileEdges.slice(0,5)})).sort((v,y)=>v.from.localeCompare(y.from)||v.to.localeCompare(y.to)),b=Math.min(...h.map(v=>v.fileEdgeCount));o.push({boundary:s,violatesPolicy:i,subUnits:[...f].sort(),internalEdges:h,narrowestEdges:h.filter(v=>v.fileEdgeCount===b)})}}return o.sort((s,a)=>a.subUnits.length-s.subUnits.length||s.boundary.localeCompare(a.boundary))}function BN(e,t){let n=new Set(t.map(s=>dr(s.from,s.to))),i=e.allowedDependencies??{},r=new Set(e.boundaries.map(s=>s.name)),o=[];for(let[s,a]of Object.entries(i))if(r.has(s))for(let c of a)!r.has(c)||n.has(dr(s,c))||o.push({from:s,to:c});return o.sort((s,a)=>s.from.localeCompare(a.from)||s.to.localeCompare(a.to))}function $N(e,t,n){let i=[],r=new Map;for(let o of t)r.set(o.from,(r.get(o.from)??0)+1);for(let o of e.boundaries){if(e.maxBoundaryFanOut!==void 0){let a=r.get(o.name)??0;a>e.maxBoundaryFanOut&&i.push({boundary:o.name,kind:"fan-out",observed:a,limit:e.maxBoundaryFanOut})}let s=o.maxFiles??e.maxBoundaryFiles;if(s!==void 0){let a=n.get(o.name)?.size??0;a>s&&i.push({boundary:o.name,kind:"files",observed:a,limit:s})}}return i.sort((o,s)=>o.boundary.localeCompare(s.boundary)||o.kind.localeCompare(s.kind))}function jN(e){let t=V(e);return t==="test"||t==="entry"}function HN(e){let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)}function dr(e,t){return`${e}\0${t}`}function UN(e,t){return e.from.localeCompare(t.from)||e.to.localeCompare(t.to)}function zN(e,t={}){let{limit:n=20,scope:i,minFanIn:r=2,minFanOut:o=2,scanLimit:s}=t,a=new U(e),c=Fe(a.productionCallableDefinitions({scope:i,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s),l=t.semantic!==!1,u=tn(e,c,{limit:500,semantic:l,semanticEvidence:fe}),d=a.calleeEvidenceMap(c,{semantic:l}),m=new Set([...u.incompleteSymbolIds,...d.incompleteSymbolIds]),p=new Set([...u.unavailableSymbolIds,...d.unavailableSymbolIds]);return{rows:c.filter(g=>!m.has(g.symbolId)&&!p.has(g.symbolId)).map(g=>KN(g,u.rows.get(g.symbolId)??[],d.rows.get(g.symbolId)??[])).filter(g=>g.fanIn>=r&&g.fanOut>=o).sort((g,h)=>h.score-g.score||h.fanIn-g.fanIn).slice(0,n),coverage:GN(l,m,p)}}function GN(e,t,n){let i=e?t.size>0&&n.size>0?"incomplete-and-unavailable":t.size>0?"incomplete":n.size>0?"unavailable":"complete":"disabled";return{semanticEvidence:{enabled:e,status:i,incompleteSymbolCount:t.size,unavailableSymbolCount:n.size,excludedSymbolCount:new Set([...t,...n]).size}}}function KN(e,t,n){let i=[...new Set(t.map(d=>d.file))].sort(),r=[...new Set(t.filter(d=>d.source!=="caller-map-inversion"||d.callEvidence==="scip-chunk").map(d=>d.file))].sort(),o=new Map;for(let d of n.slice(0,500)){if(d.file===e.relativePath)continue;let m=`${d.symbol}|${d.file}`;o.has(m)||o.set(m,{symbol:d.symbol,shortName:k(d.symbol),file:d.file,evidenceStrength:d.source==="scip-chunk"?"candidate":"exact",evidenceSource:d.source})}let s=[...o.values()].sort((d,m)=>d.file.localeCompare(m.file)||d.symbol.localeCompare(m.symbol)),a=i.length,c=s.length,l=a*c,u=s.filter(d=>d.evidenceStrength==="candidate").map(d=>d.symbol);return{symbol:e.symbol,shortName:k(e.symbol),fanIn:a,fanOut:c,callerFiles:i,candidateCallerFiles:r,externalCallees:s.map(({symbol:d,shortName:m,file:p})=>({symbol:d,shortName:m,file:p})),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)`,`${r.length} incoming file(s) and ${u.length} outgoing target(s) rely on candidate rather than exact call evidence`],recommendation:"Review ownership, API stability, and caller groups before changing this central symbol; do not refactor solely from graph centrality."}}function xo(e,t={}){let{scope:n,minLoc:i=3,scanLimit:r}=t,o=new U(e),s=t.semantic!==!1,a=0,c=$("isolated.candidates",()=>{let S=Fe(o.productionCallableDefinitions({scope:n,minLoc:i,excludeEntrySurfaces:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:typeof r=="number"&&r>0}),r).filter(R=>!ur(e,R));return a=S.length,S},()=>({definitions:a})),l=0,u=$("isolated.strict-callees",()=>{let w=o.symbolsWithNonSelfCallees(c,{additive:!1,semantic:!1});return l=w.size,w},()=>({definitions:c.length,symbols:l})),d=c.filter(w=>!u.has(w.symbolId)),m=0,p=$("isolated.scip-callers",()=>{let w=o.crossFileCallerMap(d,{semantic:!1});return m=w.size,w},()=>({definitions:d.length,symbols:m})),f=new Set(p.keys());for(let w of o.frameworkReferencedSymbolIds(d))f.add(w);let g=d.filter(w=>!f.has(w.symbolId));if(s&&g.length>0){let w=Rn(e,g);for(let S of w.callers.keys())f.add(S);for(let S of w.incompleteSymbolIds)f.add(S);for(let S of w.unavailableSymbolIds)f.add(S);for(let S of o.symbolsWithNonSelfCallees(g,{additive:!1,semantic:!0}))u.add(S);g=g.filter(S=>!f.has(S.symbolId)).filter(S=>!u.has(S.symbolId))}let h=0,b=$("isolated.source-fallback-callers",()=>{let w=o.sourceFallbackCallerFiles(g,{skipPath:S=>V(S)==="test"});return h=w.size,w},()=>({definitions:g.length,symbols:h}));for(let w of b.keys())f.add(w);let v=g.filter(w=>!f.has(w.symbolId)),y=0,E=$("isolated.additive-callees",()=>{let w=o.symbolsWithNonSelfCallees(v,{additive:!0,semantic:s});return y=w.size,w},()=>({definitions:v.length,symbols:y}));for(let w of E)u.add(w);return v.filter(w=>!u.has(w.symbolId)).sort((w,S)=>de(S)-de(w)||w.relativePath.localeCompare(S.relativePath)||w.startLine-S.startLine).map(w=>({symbol:w.symbol,shortName:k(w.symbol),relativePath:w.relativePath,startLine:w.startLine,endLine:w.endLine,loc:de(w)}))}import{SymbolInformation_Kind as Ze}from"@c4312/scip";var fS=500;function qN(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),i=Kp.get(n);if(i!==void 0)return i;for(let[r,o]of Es)if(o.toLowerCase().includes(n))return r;return null}function WN(e,t,n={}){let{scope:i,limit:r=100}=n,o=qN(t);return o===null?[]:JN(e,i).map(a=>({row:a,resolvedKind:hS(a)})).filter(a=>a.resolvedKind===o).slice(0,r).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:k(a.symbol),kind:c,kindName:Ar(c),relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function VN(e,t={}){let n=YN(e,t.scope);for(let i of XN(e,t.scope)){let r=hS(i);r===null||r===0||n.set(r,(n.get(r)??0)+1)}return[...n.entries()].sort((i,r)=>r[1]-i[1]||i[0]-r[0]).map(([i,r])=>({kind:i,kindName:Ar(i),count:r}))}function JN(e,t){return ze(e,{scope:t}).map(QN)}function YN(e,t){let n=new Map;for(let i of gS(he(e,{scope:t,includeIgnored:!1}))){let r=i.map(()=>"?").join(", "),o=e.all(`SELECT gs.kind AS kind, COUNT(*) AS count
295
- FROM defn_enclosing_ranges der
296
- JOIN global_symbols gs ON der.symbol_id = gs.id
297
- JOIN documents d ON der.document_id = d.id
298
- WHERE gs.kind IS NOT NULL
299
- AND gs.kind != 0
300
- AND gs.symbol NOT LIKE '%#'
301
- AND d.relative_path IN (${r})
302
- GROUP BY gs.kind`,...i);for(let s of o)n.set(s.kind,(n.get(s.kind)??0)+s.count)}return n}function XN(e,t){let n=[];for(let i of gS(he(e,{scope:t,includeIgnored:!1}))){let r=i.map(()=>"?").join(", ");n.push(...e.all(`SELECT gs.symbol,
303
- gs.kind,
304
- gs.documentation,
305
- gs.enclosing_symbol,
306
- d.relative_path,
307
- der.start_line,
308
- der.end_line
309
- FROM defn_enclosing_ranges der
310
- JOIN global_symbols gs ON der.symbol_id = gs.id
311
- JOIN documents d ON der.document_id = d.id
312
- WHERE (gs.kind IS NULL OR gs.kind = 0 OR gs.symbol LIKE '%#')
313
- ${e.symbolNoiseFor("gs")}
314
- AND d.relative_path IN (${r})
315
- ORDER BY d.relative_path, der.start_line, der.end_line, gs.symbol`,...i))}return n}function gS(e){let t=[];for(let n=0;n<e.length;n+=fS)t.push(e.slice(n,n+fS));return t}function QN(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 hS(e){return e.kind!==null&&e.kind!==0?ZN(e.kind,e.symbol,e.documentation):ek(e.symbol,e.documentation,e.enclosing_symbol)}function ZN(e,t,n){let i=(n??"").toLowerCase();if(Bn(t)==="type"){if(i.includes("type "))return Ze.TypeAlias;if(i.includes("interface "))return Ze.Interface;if(i.includes("struct "))return Ze.Struct;if(i.includes("trait "))return Ze.Trait;if(i.includes("class "))return Ze.Class}return e}function ek(e,t,n){let i=Hi(e);if("kind"in i)return null;let r=i.descriptors,o=r[r.length-2]??null,s=Bn(e),a=(t??"").toLowerCase();return s==="type"?a.includes("type ")?Ze.TypeAlias:a.includes("interface ")?Ze.Interface:a.includes("struct ")?Ze.Struct:a.includes("trait ")?Ze.Trait:a.includes("class ")?Ze.Class:Ze.Class:s==="method"?o?.suffix==="type"?Ze.Method:Ze.Function:s==="namespace"?Ze.Module:s!=="term"?null:a.includes("async def ")||a.includes("def ")?Ze.Function:(n?Bn(n):o?.suffix??null)==="type"?Ze.Field:Ze.Variable}function tk(e,t={}){let{limit:n=10,scope:i,minDepth:r=3,edgeBasis:o="symbol-references"}=t,s=Oe(e,i,o==="imports"?{scipEdges:"imports-only",sourceEdges:"imports-only"}:void 0),{components:a,componentOf:c}=Mi(s),l=new Map;for(let h=0;h<a.length;h++)l.set(h,new Set);for(let[h,b]of s){let v=c.get(h);for(let y of b){let E=c.get(y);E!==v&&l.get(v).add(E)}}let u=new Array(a.length),d=new Array(a.length);for(let h=0;h<a.length;h++){let b=[],v=0;for(let y of[...l.get(h)].sort((E,w)=>E-w)){let E=d[y];(E>v||E===v&&nk(u[y],b,a)<0)&&(v=E,b=u[y])}u[h]=[h,...b],d[h]=1+v}function m(h){return u[h]}let p=a.map(h=>[...h].sort()),f=new Set,g=[];for(let h=0;h<a.length;h++){let v=m(h).map(w=>p[w]),y=v.map(w=>w[0]);if(v.length<r)continue;let E=y.join(" ");f.has(E)||(f.add(E),g.push(ik(y,v,o)))}return g.sort((h,b)=>b.depth-h.depth||h.chain.join("\0").localeCompare(b.chain.join("\0"))),rk(g).slice(0,n)}function nk(e,t,n){if(t.length===0)return-1;let i=e.map(o=>[...n[o]].sort()[0]??"").join("\0"),r=t.map(o=>[...n[o]].sort()[0]??"").join("\0");return i.localeCompare(r)}function ik(e,t,n){let i=t.reduce((o,s)=>o+s.length,0),r=t.filter(o=>o.length>1).length;return{chain:e,components:t,depth:t.length,fileCount:i,edgeBasis:n,actionTier:"signal",chainKind:"transitive-dependency-depth",evidenceReasons:[`${t.length} condensed dependency component(s) form the representative transitive path`,`${i} file(s) are represented; ${r} component(s) contain a dependency cycle`,`edge basis: ${n==="imports"?"resolved file imports":"cross-file symbol references plus resolved source imports"}`,"cycles count once toward depth and retain their full membership separately"],recommendation:"Review whether the chain crosses ownership or layer boundaries; shorten it only when the dependency direction is accidental."}}function rk(e){let t=[];for(let n of e)t.some(i=>ok(n.chain,i.chain))||t.push(n);return t}function ok(e,t){if(e.length>=t.length)return!1;let n=t.length-e.length;for(let i=0;i<e.length;i++)if(e[i]!==t[n+i])return!1;return!0}function sk(e,t){let n=pe(e,t);if(!n)return[];let i=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
316
- WHERE id = ? LIMIT 1`,n.symbolId);if(!i)return[];let r=[{symbol:i.symbol,shortName:k(i.symbol),depth:0}],o=i.enclosing_symbol,s=1,a=new Set([i.symbol]);for(;o&&!a.has(o)&&s<20;){a.add(o);let d=e.get("SELECT symbol, enclosing_symbol FROM global_symbols WHERE symbol = ?",o);if(!d)break;r.push({symbol:d.symbol,shortName:k(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(r.length>1)return r;let c=Hi(i.symbol);if("kind"in c)return r;let l=c.descriptors;if(l.length<=1)return r;let u=[r[0]];for(let d=l.length-2,m=1;d>=0;d--,m++){let f=l.slice(0,d+1).map(g=>g.suffix==="method"?`${g.name}()`:g.name.replace(/\.(ts|tsx|js|jsx|mjs|cjs|py|pyi|rs|java|scala|kt|kts|rb|go|cs|vb|dart|php|c|cc|cpp|cxx|h|hpp)$/,"")).join(":");u.push({symbol:f,shortName:f,depth:m})}return u}function ak(e,t={}){let i=new U(e).productionCallableDefinitions({scope:t.scope,requireCallableSymbol:!0,includeSuppressed:!0}),r=vS(e,i),o=t.search?.trim().toLocaleLowerCase();return i.map(s=>CS(e,s,r.get(s.symbolId)??[])).filter(s=>s!==null).map(s=>s.result).filter(s=>!o||uk(s).includes(o)).sort(dk)}function ck(e,t,n={}){let i=rt(e,t);if(!i.match)return{kind:"missing",query:t};if(i.total>1)return{kind:"ambiguous",query:t,total:i.total,candidates:[{symbol:i.match.symbol,shortName:k(i.match.symbol),relativePath:i.match.relativePath,startLine:i.match.startLine},...i.candidates]};let r=new U(e),o=r.definitionsForFile(i.match.relativePath).find(p=>p.symbol===i.match.symbol);if(!o?.isFunctionLike)return{kind:"not-entry",query:t,symbol:i.match.symbol,shortName:k(i.match.symbol),file:i.match.relativePath,reason:"The resolved symbol is not a callable definition."};let s=vS(e,[o]),a=CS(e,o,s.get(o.symbolId)??[]);if(!a)return{kind:"not-entry",query:t,symbol:o.symbol,shortName:k(o.symbol),file:o.relativePath,reason:"The callable is neither an external root nor an uncalled callable on a detected entry surface."};let c=mk(e,r,o),l=new Set(n.expand??[]),u=hk(c,l),d=new Set(u.regions.filter(p=>p.expanded).map(p=>p.id)),m=[...l].filter(p=>!d.has(p)).sort();return{kind:"matched",query:t,entry:a.result,regions:u.regions,regionEdges:u.regionEdges,unmatchedExpansions:m,coverage:{completeWithinIndexedStaticCallEdges:!0,completeWithinSelectedStaticEvidence:!0,candidateReachabilityIncluded:c.edges.some(p=>p.evidenceStrength==="candidate"),dynamicDispatchRepresented:!1,symbolCount:c.symbols.length,symbolEdgeCount:c.edges.length,exactSymbolEdgeCount:c.edges.filter(p=>p.evidenceStrength==="exact").length,candidateSymbolEdgeCount:c.edges.filter(p=>p.evidenceStrength==="candidate").length,regionCount:u.regions.length,regionEdgeCount:u.regionEdges.length,externalCallCount:c.externalCalls.length}}}function vS(e,t){let n=t.filter(i=>xS(e,i.relativePath)||Zi(e,i.symbol,i.relativePath).length>0);return Vp(e,n,{semantic:!1,semanticEvidence:fe})}function CS(e,t,n){let i=lk(e,t),r=i.length>0,o=xS(e,t.relativePath)&&n.length===0;if(!r&&!o)return null;let s=[...i];return o&&s.push("entry-surface-without-indexed-caller"),{definition:t,result:{symbol:t.symbol,shortName:k(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,documentation:t.documentation,confidence:r?"root":"candidate",evidence:s,indexedCallerCount:n.length}}}function xS(e,t){return Ye(e,t)||/(?:^|\/)entry\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(t)}function lk(e,t){let n=Zi(e,t.symbol,t.relativePath),i=[];return yS(n,["package-surface-file","transitive-package-surface"])&&Rt(e,t)&&i.push("package-public-export"),n.includes("rust-public-library")&&i.push("rust-public-library"),n.includes("framework-entrypoint")&&i.push("framework-dispatched-export"),yS(n,["configured-file","configured-path-prefix","configured-qualified-var","configured-symbol-pattern"])&&i.push("configured-entry-root"),i}function yS(e,t){return t.some(n=>e.includes(n))}function uk(e){return[e.symbol,e.shortName,e.file,e.documentation??"",...e.evidence].join(`
317
- `).toLocaleLowerCase()}function dk(e,t){return bS(e.confidence)-bS(t.confidence)||e.file.localeCompare(t.file)||e.startLine-t.startLine||e.symbol.localeCompare(t.symbol)}function bS(e){return e==="root"?0:1}function mk(e,t,n){let i=new Map([[n.symbol,0]]),r=new Map,o=new Map([[n.symbol,n]]),s=new Map,a=new Map,c=[n];for(;c.length>0;){let l=t.calleeMap(c,{additive:!1,semantic:!1}),u=[];for(let d of c){let m=i.get(d.symbol)??0;r.set(d.symbol,SS(d,m));for(let p of l.get(d.symbolId)??[]){let f=pk(t,p,o);if(!f){let v=gk(d,p);a.set(Sk(v),v);continue}let g=m+1,h=i.get(f.symbol);(h===void 0||g<h)&&i.set(f.symbol,g),r.set(f.symbol,SS(f,Math.min(g,h??g)));let b=fk(d,f,p);s.set(bk(b),b),h===void 0&&u.push(f)}}c=u}return{symbols:[...r.values()].sort(vk),edges:[...s.values()].sort(Ck),externalCalls:[...a.values()].sort(xk)}}function pk(e,t,n){let i=n.get(t.symbol);if(i)return i;let r=e.definitionsForFile(t.file).find(o=>o.symbol===t.symbol)??null;return r&&n.set(r.symbol,r),r}function SS(e,t){return{symbol:e.symbol,shortName:k(e.symbol),file:e.relativePath,depth:t}}function fk(e,t,n){return{fromSymbol:e.symbol,fromShortName:k(e.symbol),fromFile:e.relativePath,toSymbol:t.symbol,toShortName:k(t.symbol),toFile:t.relativePath,source:n.source,evidenceStrength:n.source==="scip-chunk"?"candidate":"exact"}}function gk(e,t){return{fromSymbol:e.symbol,fromShortName:k(e.symbol),fromFile:e.relativePath,toSymbol:t.symbol,toShortName:k(t.symbol),reportedFile:t.file,source:t.source,evidenceStrength:t.source==="scip-chunk"?"candidate":"exact"}}function hk(e,t){let n=Ro(e.symbols,l=>l.file),i=Ro(e.edges.filter(l=>l.fromFile===l.toFile),l=>l.fromFile),r=Ro(e.externalCalls,l=>l.fromFile),o=yk(e.edges.filter(l=>l.fromFile!==l.toFile)),s=Ro(o,l=>l.toRegionId),a=Ro(o,l=>l.fromRegionId);return{regions:[...n.entries()].map(([l,u])=>{let d=Nu(l),m=t.has(d),p=i.get(l)??[],f=r.get(l)??[];return{id:d,file:l,minDepth:Math.min(...u.map(g=>g.depth)),symbolCount:u.length,internalEdgeCount:p.length,externalCallCount:f.length,incomingRegionIds:Eo((s.get(d)??[]).map(g=>g.fromRegionId)),outgoingRegionIds:Eo((a.get(d)??[]).map(g=>g.toRegionId)),expanded:m,symbols:m?u:[],internalEdges:m?p:[],externalCalls:m?f:[]}}).sort((l,u)=>l.minDepth-u.minDepth||l.file.localeCompare(u.file)),regionEdges:o}}function yk(e){let t=new Map;for(let n of e){let i=`${n.fromFile}\0${n.toFile}`,r=t.get(i)??[];r.push(n),t.set(i,r)}return[...t.values()].map(n=>{let i=n[0];return{fromRegionId:Nu(i.fromFile),fromFile:i.fromFile,toRegionId:Nu(i.toFile),toFile:i.toFile,callCount:n.length,exactCallCount:n.filter(r=>r.evidenceStrength==="exact").length,candidateCallCount:n.filter(r=>r.evidenceStrength==="candidate").length,fromSymbols:Eo(n.map(r=>r.fromShortName)),toSymbols:Eo(n.map(r=>r.toShortName)),evidence:Eo(n.map(r=>r.source))}}).sort((n,i)=>n.fromFile.localeCompare(i.fromFile)||n.toFile.localeCompare(i.toFile))}function Ro(e,t){let n=new Map;for(let i of e){let r=t(i),o=n.get(r)??[];o.push(i),n.set(r,o)}return n}function Nu(e){return`file:${e}`}function Eo(e){return[...new Set(e)].sort()}function bk(e){return`${e.fromSymbol}\0${e.toSymbol}`}function Sk(e){return`${e.fromSymbol}\0${e.toSymbol}`}function vk(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)||e.symbol.localeCompare(t.symbol)}function Ck(e,t){return e.fromFile.localeCompare(t.fromFile)||e.fromSymbol.localeCompare(t.fromSymbol)||e.toSymbol.localeCompare(t.toSymbol)}function xk(e,t){return e.fromFile.localeCompare(t.fromFile)||e.fromSymbol.localeCompare(t.fromSymbol)||e.toSymbol.localeCompare(t.toSymbol)}function Bt(e,t){let n=new Set;for(let i of e)t.has(i)&&n.add(i);return n}function et(e,t){let n=new Set;for(let i of e)t.has(i)||n.add(i);return n}function Zn(e,t){if(e.size===0&&t.size===0)return 0;let n=0;for(let r of e)t.has(r)&&(n+=1);let i=e.size+t.size-n;return i===0?0:n/i}function RS(e,t){if(e.size===0)return 0;let n=0;for(let i of e)t.has(i)&&(n+=1);return n/e.size}function ku(e,t){if(t<=0)return new Map;let n=new Map;for(let[i,r]of e)r>0&&n.set(i,Math.log(t/r));return n}function mr(e){let t=[...e.values()].sort((i,r)=>i-r);if(t.length===0)return 0;let n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function pr(e,t){let n=0;for(let i of e){let r=t.get(i)??0;n+=r*r}return Math.sqrt(n)}function ES(e,t,n,i={}){let r=0,o=0,s=0,a=i.medianIdf??mr(n),c=[],l=[];for(let m of e){let p=n.get(m)??0;o+=p*p,t.has(m)&&(r+=p*p,p>=a?c.push(m):l.push(m))}if(c.length===0&&l.length===0)return{similarity:0,significantShared:[],trivialShared:[]};for(let m of t){let p=n.get(m)??0;s+=p*p}let u=Math.sqrt(o)*Math.sqrt(s),d=u>0?r/u:0;return c.sort((m,p)=>(n.get(p)??0)-(n.get(m)??0)),{similarity:d,significantShared:c,trivialShared:l}}function wS(e,t,n,i){let r=0,o=i.medianIdf??mr(n),s=[],a=[];for(let u of e){if(!t.has(u))continue;let d=n.get(u)??0;r+=d*d,d>=o?s.push(u):a.push(u)}if(s.length===0&&a.length===0)return{similarity:0,significantShared:[],trivialShared:[]};let c=i.magnitudeA*i.magnitudeB,l=c>0?r/c:0;return s.sort((u,d)=>(n.get(d)??0)-(n.get(u)??0)),{similarity:l,significantShared:s,trivialShared:a}}function wo(e,t,n={}){let{minSimilarity:i=.4,limit:r=20}=n,o=()=>Hk(e,t,{minSimilarity:i,limit:r,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"}),s=Mk(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(!ke(a.symbol))return[];if(a.callees.size===0)return o();let c=Ek(e,a,i,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return c.length>0?c.slice(0,r):o()}function $u(e,t,n,i={}){let r=pe(e,t),o=pe(e,n);if(!r||!o)return null;let s=wo(e,r.symbol,{minSimilarity:0,limit:Number.POSITIVE_INFINITY,semantic:i.semantic,scanLimit:i.scanLimit}).find(l=>l.symbolB===o.symbol||l.symbolA===o.symbol);if(!s)return null;let a=r.endLine-r.startLine+1,c=o.endLine-o.startLine+1;return{symbolA:{symbol:r.symbol,shortName:k(r.symbol),file:r.relativePath,loc:a},symbolB:{symbol:o.symbol,shortName:k(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:Rk(s)}}function Rk(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 Ek(e,t,n,i){let r=fr(e).calleeIndex({minCallees:3,scanLimit:i.scanLimit,semantic:i.semantic}),o=$k(t,r.corpus),s=_k(o,r),a=wk(o,r),c=mr(a),l=pr(o.callees,a),u=[];for(let d of s){if(d.callees.size<3)continue;let m=pr(d.callees,a),p=DS(o,d,a,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0,medianIdf:c,magnitudeA:l,magnitudeB:m});p&&u.push(p)}return u.sort((d,m)=>m.similarity-d.similarity),u}function wk(e,t){let n=new Map(t.docFreq);for(let i of e.callees)n.set(i,(n.get(i)??0)+1);return ku(n,t.corpus.length+1)}function DS(e,t,n,i){let r=Lk(e,t,n,i);if(!Pk(r,i))return null;let{similarity:o,significantShared:s,trivialShared:a}=r,c=s.length>0?s:a,l=NS(c,"callees");return{symbolA:e.symbol,shortNameA:k(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:k(t.symbol),fileB:t.file,similarity:o,similarityBasis:"callees",sharedCallees:c.map(k),uniqueToA:[...et(e.callees,t.callees)].map(k),uniqueToB:[...et(t.callees,e.callees)].map(k),...l}}function Ik(e,t,n,i){let r=i.magnitudeA??pr(e.callees,n),o=i.magnitudeB??pr(t.callees,n),s=0,a=0,c=0,l=i.medianIdf??mr(n);for(let m of e.callees){if(!t.callees.has(m))continue;let p=n.get(m)??0;s+=p*p,c+=1,p>=l&&(a+=1)}if(c===0)return!1;let u=r*o;return(u>0?s/u:0)<i.minSimilarity?!1:a>=i.requireSignificantShared||c>=i.requireSharedCount}function Lk(e,t,n,i){return i.magnitudeA===void 0||i.magnitudeB===void 0?ES(e.callees,t.callees,n,{medianIdf:i.medianIdf}):wS(e.callees,t.callees,n,{medianIdf:i.medianIdf,magnitudeA:i.magnitudeA,magnitudeB:i.magnitudeB})}function Pk(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 Io(e,t={}){let{minSimilarity:n=.5,limit:i=20,scope:r,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=t.semantic!==!1,l=mt(),u=0,d=0,m=0,p=0,f=0,g=0,h=0;return $("similar.all",()=>{let v=fr(e).calleeIndex({minCallees:o,scope:r,scanLimit:a,semantic:c}),y=v.corpus;u=y.length;let E=t.focusFiles,w=[],S=0;return $("similar.all.pair-scan",()=>{for(let R=0;R<y.length;R+=1){let C=y[R],L=E?.has(C.file)??!1,I=v.weightedMagnitudes[R],x=new Set;for(let D of C.callees){let _=v.candidateIndexesByCallee.get(D);if(_)for(let P of _)P<=R||E&&!L&&!E.has(y[P].file)||x.add(P)}l&&(m+=x.size,x.size>0&&(d+=1));for(let D of x){let _=y[D];if(s&&C.file===_.file){l&&(f+=1);continue}if(TS(C,_)){l&&(g+=1);continue}l&&(p+=1);let P=DS(C,_,v.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:v.medianIdf,magnitudeA:I,magnitudeB:v.weightedMagnitudes[D]});P&&(Dk(w,P,i,S),l&&(h+=1),S+=1)}}},()=>({corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:p,crossFileSkips:f,signatureSkips:g,insertedResults:h,topResults:w.length})),$("similar.all.sort-project",()=>(w.sort((R,C)=>C.result.similarity-R.result.similarity||R.order-C.order),w.map(R=>R.result)),()=>({topResults:w.length}))},()=>({minSimilarity:n,limit:i,scope:r,minCallees:o,crossFileOnly:s,scanLimit:a,semantic:c,corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:p,crossFileSkips:f,signatureSkips:g,insertedResults:h}))}function ju(e,t={}){let{minSimilarity:n=.5,scope:i,minCallees:r=4,crossFileOnly:o=!1,scanLimit:s}=t,a=t.semantic!==!1,c=mt(),l=0,u=0,d=0,m=0,p=0,f=0,g=0;return $("similar.all-count",()=>{let b=fr(e).calleeIndex({minCallees:r,scope:i,scanLimit:s,semantic:a}),v=b.corpus;l=v.length;let y=t.focusFiles;return $("similar.all-count.pair-scan",()=>{for(let E=0;E<v.length;E+=1){let w=v[E],S=y?.has(w.file)??!1,R=b.weightedMagnitudes[E],C=new Set;for(let L of w.callees){let I=b.candidateIndexesByCallee.get(L);if(I)for(let x of I)x<=E||y&&!S&&!y.has(v[x].file)||C.add(x)}c&&(d+=C.size,C.size>0&&(u+=1));for(let L of C){let I=v[L];if(o&&w.file===I.file){c&&(p+=1);continue}if(TS(w,I)){c&&(f+=1);continue}c&&(m+=1),Ik(w,I,b.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:b.medianIdf,magnitudeA:R,magnitudeB:b.weightedMagnitudes[L]})&&(g+=1)}}},()=>({corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:p,signatureSkips:f,insertedResults:g})),g},()=>({minSimilarity:n,scope:i,minCallees:r,crossFileOnly:o,scanLimit:s,semantic:a,corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:p,signatureSkips:f,insertedResults:g}))}function TS(e,t){if(e.paramCount<0||t.paramCount<0)return!1;let n=Math.abs(e.paramCount-t.paramCount),i=Math.max(2,Math.ceil(Math.max(e.paramCount,t.paramCount)*.5));return n>i}var MS=xt({kind:"source-fingerprints",invalidation:Je("source-fingerprints"),serialize:s_,deserialize:o_});function Dk(e,t,n,i){if(n<=0)return;if(e.length<n){e.push({result:t,order:i});return}let r=0;for(let s=1;s<e.length;s+=1){let a=e[s],c=e[r];(a.result.similarity<c.result.similarity||a.result.similarity===c.result.similarity&&a.order>c.order)&&(r=s)}let o=e[r];t.similarity<=o.result.similarity||(e[r]={result:t,order:i})}var Tk=["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 Mk(e,t,n){let i=pe(e,t);if(!i)return{kind:"not-callable"};if(!ke(i.symbol))return{kind:"not-callable"};let r=new U(e),o=mi(e,i,{semantic:n.semantic,semanticEvidence:fe});return o.semanticIncomplete||o.semanticUnavailable?{kind:"callee-evidence-unusable"}:{kind:"resolved",target:{symbol:i.symbol,file:i.relativePath,callees:Oa(o.rows.map(s=>s.symbol)),paramCount:r.callableSignature(i)?.paramCount??-1}}}var Ak=Me("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),Fk=Me("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function AS(e,t){let{minCallees:n,scope:i,excludeSymbol:r,scanLimit:o}=t,s=t.semantic!==!1,a=Ak.get(e,()=>new Map),c=`${n}|${i??""}|${o??""}|${s}`,l=!0,u=0,d=0;return $("similar.callee-fingerprints.resolve",()=>{let m=a.get(c);if(l=m!==void 0,m||(m=Ok(e,{minCallees:n,scope:i,scanLimit:o,semantic:s}),a.set(c,m)),u=m.length,r===void 0)return m;let p=m.filter(f=>f.symbol!==r);return d=m.length-p.length,p},()=>({minCallees:n,scope:i,scanLimit:o,semantic:s,cacheHit:l,corpusSize:u,excludeSymbol:r!==void 0,excludedSymbols:d}))}function Nk(e,t){let{minCallees:n,scope:i,scanLimit:r}=t,o=t.semantic!==!1,s=Fk.get(e,()=>new Map),a=`${n}|${i??""}|${r??""}|${o}`,c=!0,l=0,u=0,d=0;return $("similar.callee-index.resolve",()=>{let m=s.get(a);return c=m!==void 0,m||(m=kk(AS(e,{minCallees:n,scope:i,scanLimit:r,semantic:o})),s.set(a,m)),l=m.corpus.length,u=m.docFreq.size,d=m.candidateIndexesByCallee.size,m},()=>({minCallees:n,scope:i,scanLimit:r,semantic:o,cacheHit:c,corpusSize:l,indexedCallees:u,candidateBuckets:d}))}function fr(e){return{calleeCorpus:t=>AS(e,t),calleeIndex:t=>Nk(e,t),sourceCorpus:(t={})=>$S(e,t),sourceIndex:(t={})=>PS(e,t),sourceCandidates:(t,n)=>(n.candidateMode??"full")==="target-pruned"?Xk(e,t,{minSimilarity:n.minSimilarity,scanLimit:n.scanLimit}):Yk(t,PS(e,{scanLimit:n.scanLimit}))}}function kk(e){let t=mt(),n=0,i=$("similar.callee-index.doc-frequency",()=>{let m=new Map;for(let p of e)for(let f of p.callees)m.set(f,(m.get(f)??0)+1);return n=m.size,m},()=>({corpusSize:e.length,uniqueCallees:n})),r=Math.max(8,Math.ceil(Math.sqrt(e.length))),o=$("similar.callee-index.idf-weights",()=>ku(i,e.length),()=>({corpusSize:e.length,uniqueCallees:i.size})),s=$("similar.callee-index.weighted-magnitudes",()=>e.map(m=>pr(m.callees,o)),()=>({corpusSize:e.length})),a=0,c=0,l=0,u=$("similar.callee-index.candidate-buckets",()=>{let m=new Map;for(let p=0;p<e.length;p+=1){let f=e[p];for(let g of f.callees){if((i.get(g)??0)>r){t&&(c+=1);continue}let h=m.get(g);h||(h=[],m.set(g,h)),h.push(p),t&&(a+=1)}}return t&&(l=m.size),m},()=>({corpusSize:e.length,buckets:l,candidateRefs:a,ubiquitousSkips:c,ubiquityThreshold:r})),d=$("similar.callee-index.median-idf",()=>mr(o),()=>({uniqueCallees:o.size}));return{corpus:e,candidateIndexesByCallee:u,docFreq:i,idfWeights:o,weightedMagnitudes:s,medianIdf:d,ubiquityThreshold:r}}function _k(e,t){let n=new Map;for(let i of e.callees)for(let r of t.candidateIndexesByCallee.get(i)??[]){let o=t.corpus[r];o.symbol!==e.symbol&&n.set(o.symbol,o)}return n.size>0?[...n.values()]:t.corpus.filter(i=>i.symbol!==e.symbol)}function Ok(e,t){let{minCallees:n,scope:i,scanLimit:r,semantic:o}=t,s=mt(),a=new U(e),c=0,l=$("similar.callee-fingerprints.candidates",()=>{let g=Fe(a.productionCallableDefinitions({scope:i,minLoc:5,sortByLocDesc:typeof r=="number"&&r>0}),r);return c=g.length,g},()=>({scope:i,scanLimit:r,candidateCount:c})),u=0,d=$("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,p=0,f=0;return $("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:Oa((d.rows.get(y.symbolId)??[]).map(E=>E.symbol)),paramCount:a.callableSignature(y)?.paramCount??-1})),b=Bk(h);s&&(f=b.filter((y,E)=>y.callees.size!==h[E].callees.size).length);let v=b.filter(y=>y.callees.size>=n);return m=v.length,s&&(p=v.reduce((y,E)=>y+E.callees.size,0)),v},()=>({candidateCount:c,fingerprintCount:m,retainedCalleeCount:p,minCallees:n,siblingSaturatedFingerprints:f}))}var FS=5;function Bk(e){let t=new Map;for(let n of e){let i=t.get(n.file);i||(i=new Map,t.set(n.file,i));for(let r of n.callees)i.set(r,(i.get(r)??0)+1)}return e.map(n=>{let i=t.get(n.file);if(!i)return n;let r=[...n.callees].filter(s=>(i.get(s)??0)>=FS);if(r.length===0)return n;let o=new Set(n.callees);for(let s of r)o.delete(s);return{...n,callees:o}})}function $k(e,t){let n=new Map;for(let o of t)if(!(o.file!==e.file||o.symbol===e.symbol))for(let s of o.callees)n.set(s,(n.get(s)??0)+1);let i=[...e.callees].filter(o=>(n.get(o)??0)+1>=FS);if(i.length===0)return e;let r=new Set(e.callees);for(let o of i)r.delete(o);return{...e,callees:r}}function Oa(e){return new Set([...e].filter(t=>!jk(t)))}function jk(e){return Tk.some(t=>e.includes(t))}function Hk(e,t,n){let i=Kk(e,t);if(!i||i.tokens.size<3)return[];let r=n.minSimilarity>=.5?n.minSimilarity:.3,o=[],s=n.candidateMode??"full",a=0,c=0,l=0,u=0;return $("similar.source-shape",()=>{let m=fr(e).sourceCandidates(i,{minSimilarity:r,scanLimit:n.scanLimit,candidateMode:s});a=m.length;for(let p of m){if(p.symbol===i.symbol||p.tokens.size<3)continue;c+=1;let f=Bt(i.tokens,p.tokens);if(f.size<2){l+=1;continue}let g=new Set([...i.tokens,...p.tokens]),h=g.size>0?f.size/g.size:0;if(h<r){u+=1;continue}o.push({symbolA:i.symbol,shortNameA:k(i.symbol),fileA:i.file,symbolB:p.symbol,shortNameB:k(p.symbol),fileB:p.file,similarity:h,similarityBasis:"source-tokens",sharedCallees:[...f].sort(),uniqueToA:[...et(i.tokens,p.tokens)].sort(),uniqueToB:[...et(p.tokens,i.tokens)].sort(),...NS([...f],"source-tokens")})}return o.sort((p,f)=>f.similarity-p.similarity||p.shortNameB.localeCompare(f.shortNameB)),o.slice(0,n.limit)},()=>({symbol:i.symbol,file:i.file,targetTokens:i.tokens.size,candidateMode:s,candidates:a,comparedPairs:c,sharedSkips:l,similaritySkips:u,results:o.length}))}function NS(e,t){let n=e.flatMap(Ou),i=e.flatMap(h=>IS(h,t)),r=_u(n,kS),o=_u(n,_S),s=_u(i,Bu),a=[...new Set(i.filter(LS))],c=e.filter(h=>{let b=IS(h,t);return b.some(v=>Bu.has(v))&&b.some(LS)}).length,l=[];r.length>0&&l.push(`access/query scaffolding: ${r.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=>OS.has(h));u&&l.push("shared source tokens are generic scaffolding");let d=s.length>0&&a.length>0,m=r.length+o.length>0,p=t==="callees"&&d&&e.length>=4&&a.length>=4&&c>=2,f=p?"domain-behavior":d?m?"mixed":"domain-behavior":r.length>0?"access-query-scaffolding":o.length>0||u?"framework-scaffolding":"structural-overlap";f==="structural-overlap"&&e.length>0&&l.push(`shared ${t} overlap has no recognized domain or scaffolding category`);let g=f==="domain-behavior"&&(e.length>=3||p)?"direct":"signal";return{evidenceClass:f,actionTier:g,evidenceClassReasons:l,recommendation:Uk(f,g)}}function Uk(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 _u(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function Ou(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function IS(e,t){if(t==="source-tokens")return Ou(e);let n=re(e);return Ou(n.length>0?n:zk(e))}function zk(e){return e.replace(/[()`]/g," ").replace(/\.[a-z][a-z0-9]+(?=\s|$)/gi," ").split(/[:/\\\s]+/).map(i=>i.trim()).filter(i=>/[A-Za-z]/.test(i)).at(-1)?.replace(/\.$/,"")??e}function LS(e){return e.length>3&&!Bu.has(e)&&!kS.has(e)&&!_S.has(e)&&!OS.has(e)&&!Gk.has(e)}var Bu=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),kS=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),_S=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"]),OS=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),Gk=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 Kk(e,t){let n=pe(e,t);if(!n||!ke(n.symbol))return null;let i=qk(e,n);return i?{symbol:n.symbol,file:n.relativePath,tokens:i}:null}function qk(e,t){let n=re(t.symbol),i=n_(e,t.relativePath,t.startLine,t.endLine,n),r=US(i,n);return r.size>0?r:null}var Wk=Me("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),Vk=Me("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function BS(e){return`${e.scanLimit??""}`}function $S(e,t={}){let n=Wk.get(e,()=>new Map),i=BS(t),r=n.get(i);return r||(r=t_(e,t),n.set(i,r)),r}function PS(e,t={}){let n=Vk.get(e,()=>new Map),i=BS(t),r=n.get(i);return r||(r=Jk($S(e,t)),n.set(i,r)),r}function Jk(e){let t=new Map;for(let r of e)for(let o of r.tokens)t.set(o,(t.get(o)??0)+1);let n=Math.max(8,Math.ceil(Math.sqrt(e.length))),i=new Map;for(let r of e)for(let o of r.tokens){if((t.get(o)??0)>n)continue;let s=i.get(o);s||(s=[],i.set(o,s)),s.push(r)}return{corpus:e,candidateByToken:i,docFreq:t,ubiquityThreshold:n}}function Yk(e,t){let n=new Map;for(let i of e.tokens)for(let r of t.candidateByToken.get(i)??[])r.symbol!==e.symbol&&n.set(r.symbol,r);return n.size>0?[...n.values()]:t.corpus.filter(i=>i.symbol!==e.symbol)}function Xk(e,t,n){let i=mt(),r=new U(e),o=Qk(t.tokens.size,n.minSimilarity),s=0,a=0,c=0,l=$("similar.source-shape.target-files",()=>{let f=[...t.tokens],g=[];for(let h of he(e,{includeIgnored:!1})){s+=1;let b=se(e,h);b&&(a+=1,Zk(b,f,o)&&g.push(h))}return c=g.length,g},()=>({symbol:t.symbol,targetTokens:t.tokens.size,requiredSharedTokens:o,scannedFiles:s,readableFiles:a,candidateFiles:c})),u=0,d=$("similar.source-shape.target-definitions",()=>{let f=Fe(r.productionCallableDefinitions({files:l,sortByLocDesc:typeof n.scanLimit=="number"&&n.scanLimit>0}),n.scanLimit);return u=f.length,f},()=>({symbol:t.symbol,candidateFiles:c,scanLimit:n.scanLimit,definitionCount:u})),m=0;return $("similar.source-shape.target-fingerprints",()=>{let f=jS(e,d);return i&&(m=f.length),f},()=>({symbol:t.symbol,definitionCount:u,fingerprintCount:m})).filter(f=>f.symbol!==t.symbol)}function Qk(e,t){return Math.max(2,Math.ceil(e*t))}function Zk(e,t,n){if(t.length<n)return!1;let i=e.toLowerCase(),r=0;for(let o of t)if(e_(i,o)&&(r+=1,r>=n))return!0;return!1}function e_(e,t){return t==="num"?/\b\d+\b/.test(e):e.includes(t)}function t_(e,t={}){let n=new U(e),{scanLimit:i}=t,r=Fe(n.productionCallableDefinitions({sortByLocDesc:typeof i=="number"&&i>0}),i);return jS(e,r)}function jS(e,t){let n=new Map;for(let r of t){let o=n.get(r.relativePath)??[];o.push(r),n.set(r.relativePath,o)}let i=new Map;for(let[r,o]of n){let s=se(e,r);if(!s)continue;let a=Ft(e,r,s),c=r_(e,r,a),l=!1,u=null;for(let d of o){let m=i_(d),p=c.get(m),f=p?new Set(p.tokens):null;f||(u??=ie(e,r),f=US(HS(u,d.startLine,d.endLine,d.leaf),d.leaf),c.set(m,{key:m,symbol:d.symbol,startLine:d.startLine,endLine:d.endLine,leaf:d.leaf,tokens:[...f].sort()}),l=!0),f.size>0&&i.set(d.symbol,{symbol:d.symbol,file:d.relativePath,tokens:f})}l&&a_(e,r,a,c)}return t.map(r=>i.get(r.symbol)).filter(r=>!!r)}function n_(e,t,n,i,r){let o=ie(e,t);return o.length===0?"":HS(o,n,i,r)}function HS(e,t,n,i){if(n>=t&&n-t<=12)return e.slice(t,n+1).join(`
318
- `);let r=[new RegExp(`\\bdef\\s+${He(i)}\\b`),new RegExp(`\\bfun\\s+${He(i)}\\b`),new RegExp(`\\bfn\\s+${He(i)}\\b`),new RegExp(`\\bfunction\\s+${He(i)}\\b`),new RegExp(`\\b${He(i)}\\s*\\(`)],o=e.findIndex(s=>r.some(a=>a.test(s)));if(o>=0){let s=o;for(let a=o+1;a<e.length&&a<=o+8;a++){let c=e[a]??"";if(a>o&&l_(c)||(s=a,c.trim()===""&&a>o+1))break}return e.slice(o,s+1).join(`
319
- `)}return e.slice(t,Math.min(e.length,t+8)).join(`
320
- `)}function i_(e){return`${e.symbol}\0${e.startLine}\0${e.endLine}\0${e.leaf}`}function r_(e,t,n){return MS.read(e,t,n)??new Map}function o_(e){try{let t=JSON.parse(e);if(!Array.isArray(t.entries))return null;let n=new Map;for(let i of t.entries){if(!i||typeof i.key!="string"||typeof i.symbol!="string"||typeof i.startLine!="number"||typeof i.endLine!="number"||typeof i.leaf!="string"||!Array.isArray(i.tokens)||!i.tokens.every(r=>typeof r=="string"))return null;n.set(i.key,i)}return n}catch{return null}}function s_(e){let t={entries:[...e.values()].sort((n,i)=>n.key.localeCompare(i.key))};return JSON.stringify(t)}function a_(e,t,n,i){MS.write(e,t,n,new Map(i))}function US(e,t){if(!e)return new Set;let n=new Set(["public","private","protected","final","static","class","def","fun","fn","function","return","string","bool","boolean","void","unit","self","this","new","const","let","var","end","pub"]),i=c_(t),o=e.replace(/["'`]/g," ").replace(/\b\d+\b/g," NUM ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[^A-Za-z0-9_]+/g," ").replace(/_/g," ").toLowerCase().split(/\s+/).map(s=>s.trim()).filter(s=>s.length>1).filter(s=>!n.has(s)).filter(s=>!i.has(s));return new Set(o)}function c_(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 l_(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function un(e,t){let n=new Map;return e.forEach((i,r)=>{let o=new Set;for(let s of t(i)){if(o.has(s))continue;o.add(s);let a=n.get(s);a?a.push(r):n.set(s,[r])}}),{candidatesFor:(i,r)=>{let o=new Set;for(let s of t(i)){let a=n.get(s);if(a)for(let c of a)c!==r&&o.add(c)}return[...o].sort((s,a)=>s-a)}}}function dn(e){let t=zS(e.profile?.name),n=()=>{let i=[];t=zS(e.profile?.name,e);let r=(s,a)=>{let c=e.profiles[s],l=e.profiles[a];t.candidatePairs+=1,t.comparedPairs+=1;let u=e.compare(c,l);u&&i.push(u)};if(e.filePattern){let s=e.profiles.findIndex(a=>a.file.includes(e.filePattern));if(s>=0){let a=e.profiles[s];for(let c of u_(e,s)){let l=e.profiles[c];e.focusFiles&&!e.focusFiles.has(a.file)&&!e.focusFiles.has(l.file)||r(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 d_(e,a))e.focusFiles&&!l&&!e.focusFiles.has(e.profiles[u].file)||r(a,u);if(i.length>s){t.overrunApplied=!0;break}}}i.sort(e.sort??((s,a)=>a.similarity-s.similarity)),t.matchedResults=i.length;let o=i.slice(0,e.limit);return t.emittedResults=o.length,e.onProfile?.({...t}),o};return e.profile?$(`pairwise-profile:${e.profile.name}`,n,()=>({...m_(e.profile?.metadata),...t})):n()}function u_(e,t){if(e.candidateIndex)return GS(e,t,-1);let n=[];for(let i=0;i<e.profiles.length;i+=1)i!==t&&n.push(i);return n}function d_(e,t){if(e.candidateIndex)return GS(e,t,t);let n=[];for(let i=t+1;i<e.profiles.length;i+=1)n.push(i);return n}function GS(e,t,n){let i=e.profiles[t],r=new Set;for(let o of e.candidateIndex?.candidatesFor(i,t,e.profiles)??[])o<=n||o!==t&&(o<0||o>=e.profiles.length||r.add(o));return[...r].sort((o,s)=>o-s)}function zS(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 m_(e){return typeof e=="function"?e():e??{}}function p_(e,t={}){let{minSimilarity:n=.5,limit:i=20,scope:r,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=f_(e,{scope:r,minDeps:s}),l=un(a,u=>u.deps);return dn({profiles:a,limit:i,filePattern:o,overrunFactor:5,candidateIndex:l,profile:{name:"similar-files"},compare:(u,d)=>h_(u,d,n,c)})}function f_(e,t){let{scope:n,minDeps:i}=t,r=Oe(e,n),{universalDeps:o,distinctiveDeps:s}=g_(r),a=[];for(let[c,l]of r)l.size>=i&&a.push({file:c,deps:new Set([...l].filter(u=>!o.has(u)))});return{profiles:a,distinctiveDeps:s}}function g_(e){let t=new Set,n=new Set,i=e.size;if(i===0)return{universalDeps:t,distinctiveDeps:n};let r=new Map;for(let s of e.values())for(let a of s)r.set(a,(r.get(a)??0)+1);let o=Math.max(3,Math.ceil(i*.03));for(let[s,a]of r)a>=5&&a/i>.3?t.add(s):a<=o&&n.add(s);return{universalDeps:t,distinctiveDeps:n}}function h_(e,t,n,i){let r=new Set;for(let l of e.deps)t.deps.has(l)&&r.add(l);if(r.size<3||e.deps.size<4||t.deps.size<4)return null;let o=0;for(let l of r)i.has(l)&&o++;if(o<2)return null;let s=Zn(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:[...r],uniqueToA:a,uniqueToB:c}}function ei(e){let t=[],n=[],i=[];for(let l of e.primitiveGroups)l.values.length!==0&&KS(l.bucket,n,i).push(`${l.reasonPrefix}: ${l.values.join(", ")}`);for(let l of e.nameGroups)y_(l.names,l.label,e.genericWords,e.stripPrefixes??[],t,KS(l.fallbackBucket,n,i));let r=t.length>0,o=n.length>0,s=i.length>0,a=r?o||s?"mixed":"domain-behavior":s?"shared-abstraction":"generic-workflow-scaffolding";return{actionTier:a==="domain-behavior"||a==="mixed"?"signal":"support",evidenceClass:a,reasons:[...t,...i,...n].slice(0,6),recommendation:e.recommendation(a)}}function Ba(e,t){if(e.size===0||t.size===0)return 0;let r=Bt(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(Zn(e,t),r)}function ti(e,t){let n=Object.fromEntries(e.map(i=>[i.name,i.count]));for(let i of t)if(Object.entries(i.min).every(([o,s])=>(n[o]??0)>=s))return{pass:!0,reason:i.reason,counts:n};return{pass:!1,reason:"shared tokens did not meet calibrated overlap thresholds",counts:n}}function $a(e,t,n){let i=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}}),r=i.filter(c=>c.qualifies&&c.axis.reason).map(c=>c.axis.reason(e,c.value)),o=i.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(i.filter(c=>c.qualifies).map(c=>c.axis.axis).concat(r.length>0?[]:[s]))];return{dominantPressure:s,pressureKinds:a,reasons:r}}function Ee(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function ot(e){return[...e].sort()}function y_(e,t,n,i,r,o){let s=[],a=[];for(let c of e)b_(c,i).filter(u=>!n.has(u)).length>0?s.push(c):a.push(c);s.length&&r.push(`${t} has domain term(s): ${s.slice(0,6).join(", ")}`),a.length&&o.push(`${t} is generic workflow: ${a.slice(0,6).join(", ")}`)}function b_(e,t){let n=e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2");for(let i of t)n=n.replace(i,"");return n.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function KS(e,t,n){return e==="generic"?t:n}function Lo(e,t={}){let{minSimilarity:n=.62,minTokens:i=8,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=kt(e).reactProfiles({scope:o,minJsxTokens:i,scanLimit:s}).filter(d=>d.kind==="component").map(d=>({file:d.file,component:d.name,tokens:d.jsxTokens,profile:d})),u=un(l,d=>d.tokens);return dn({profiles:l,limit:r,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-component-duplicates"},compare:(d,m)=>S_(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 S_(e,t,n){let i=Bt(e.tokens,t.tokens);if(i.size<6||!v_(i))return null;let r=Zn(e.tokens,t.tokens);if(r<n)return null;let o=Ee(i,"component:"),s=Ee(i,"native:"),a=Ee(i,"prop:"),c=Ee(i,"event:"),l=Ee(i,"binding:"),u=C_({sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:c,sharedBindings:l});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:r,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:ot(i),sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:c,sharedBindings:l,evidenceClass:u.evidenceClass,actionTier:u.actionTier,evidenceClassReasons:u.reasons,recommendation:u.recommendation,uniqueToA:ot(et(e.tokens,t.tokens)).slice(0,25),uniqueToB:ot(et(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function v_(e){let t=0,n=0;for(let i of e)i.startsWith("component:")&&(t+=1),(i.startsWith("prop:")||i.startsWith("event:")||i.startsWith("native:")||i.startsWith("jsx:"))&&(n+=1);return ti([{name:"component",count:t},{name:"shape",count:n}],[{min:{component:1},reason:"shared custom component"},{min:{shape:4},reason:"shared JSX structure"}]).pass}function C_(e){return ei({genericWords:R_,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:x_})}function x_(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 R_=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 Po(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:i=6,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=kt(e).reactProfiles({scope:o,minBehaviorTokens:Math.max(3,i),scanLimit:s}).map(d=>({file:d.file,component:d.name,tokens:d.behaviorTokens,profile:d})),u=un(l,d=>d.tokens);return dn({profiles:l,limit:r,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-hook-candidates"},compare:(d,m)=>E_(d,m,n,i),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.componentA.localeCompare(m.componentA)||d.fileB.localeCompare(m.fileB)||d.componentB.localeCompare(m.componentB)})}function E_(e,t,n,i){let r=Bt(e.tokens,t.tokens);if(r.size<i||!L_(r))return null;let o=Ba(e.tokens,t.tokens);if(o<n)return null;let s=Ee(r,"hook:"),a=Ee(r,"react-hook:"),c=Ee(r,"effect:"),l=Ee(r,"state:"),u=Ee(r,"request:"),d=Ee(r,"handler:"),m=Ee(r,"handler-verb:"),p=w_({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:ot(r),sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m,evidenceClass:p.evidenceClass,actionTier:p.actionTier,evidenceClassReasons:p.reasons,recommendation:p.recommendation,uniqueToA:ot(et(e.tokens,t.tokens)).slice(0,25),uniqueToB:ot(et(t.tokens,e.tokens)).slice(0,25),reason:P_({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m}),locA:e.profile.loc,locB:t.profile.loc}}function w_(e){return ei({genericWords:D_,stripPrefixes:T_,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:I_})}function I_(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 L_(e){let t=0,n=0,i=0,r=0,o=0,s=0,a=0;for(let u of e)u.startsWith("hook:")?t+=1:u.startsWith("react-hook:")?n+=1:u.startsWith("effect:")?i+=1:u.startsWith("request:")?r+=1:u.startsWith("handler:")||u.startsWith("handler-verb:")?o+=1:u.startsWith("state:")?s+=1:u.startsWith("state-hook:")&&(a+=1);let c=s+a,l=t+n+i+r+o+c;return ti([{name:"requests",count:r},{name:"customHooks",count:t},{name:"namedStates",count:s},{name:"handlers",count:o},{name:"effects",count:i},{name:"reactHooks",count:n},{name:"namedBehavior",count: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 P_(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 D_=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"]),T_=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function Hu(e,t={}){let{minComponentLines:n=300,minFileLines:i=800,minJsxTokens:r=80,minBehaviorTokens:o=40,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return kt(e).reactProfiles({scope:a,scanLimit:c}).filter(d=>d.kind==="component").filter(d=>!l||d.file.includes(l)||d.name.includes(l)).map(d=>M_(d,{minComponentLines:n,minFileLines:i,minJsxTokens:r,minBehaviorTokens:o})).filter(d=>d!==null).sort((d,m)=>m.componentLines-d.componentLines||m.fileLines-d.fileLines||d.file.localeCompare(m.file)).slice(0,s)}function M_(e,t){let n=Math.max(80,Math.floor(t.minComponentLines/2)),i=$a(e,A_({minComponentLines:t.minComponentLines,minFileLines:t.minFileLines,minJsxTokens:t.minJsxTokens,minBehaviorTokens:t.minBehaviorTokens,substantialComponentLines:n}),"component"),{reasons:r}=i;if(r.length===0)return null;let o=i.dominantPressure,s=i.pressureKinds,a=F_(e),c=N_(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:k_(c,a),reasons:r,loc:e.loc}}function A_(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 F_(e){let t=e.file.split(/[\\/]+/).filter(Boolean),n=t.slice(0,-1).map(m=>m.toLowerCase()),i=(t.at(-1)??e.name).replace(/\.[^.]+$/,""),o=n.findIndex(m=>O_.has(m))>=0,s=n.some(m=>__.has(m));if(qS(i)||qS(e.name))return"component";let c=B_.has(i.toLowerCase()),l=/(?:Page|Route|Screen)$/.test(e.name),u=o&&/View$/.test(e.name),d=!s&&i.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()===e.name.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()&&/(?:Page|Route|Screen|View)$/.test(i);return c||l||u||d?"route-page":"component"}function qS(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&WS.has(t.at(-1))?!0:[...WS].some(n=>e.endsWith($_(n)))}function N_(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 k_(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 __=new Set(["component","components","panel","panels","partial","partials"]),WS=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"]),O_=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),B_=new Set(["page","route","screen"]);function $_(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Do(e,t={}){let{minSimilarity:n=.62,minTokens:i=8,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=j_(e,{scope:o,minTokens:i,scanLimit:s}),u=un(l,d=>d.tokens);return dn({profiles:l,limit:r,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-component-duplicates"},compare:(d,m)=>U_(d,m,n),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function j_(e,t){return kt(e).vueProfiles({scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:H_(n)}))}function H_(e){return e.totalLines}function U_(e,t,n){let i=Bt(e.tokens,t.tokens);if(i.size<6||!z_(i))return null;let r=Zn(e.tokens,t.tokens);if(r<n)return null;let o=Ee(i,"component:"),s=Ee(i,"prop:"),a=Ee(i,"event:"),c=Ee(i,"directive:"),l=Ee(i,"slot:"),u=Ee(i,"id:"),d=G_({sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:c,sharedSlots:l,sharedIdentifiers:u});return{fileA:e.file,fileB:t.file,similarity:r,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:ot(i),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:ot(et(e.tokens,t.tokens)).slice(0,25),uniqueToB:ot(et(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function z_(e){let t=0,n=0;for(let i of e)i.startsWith("component:")&&(t+=1),(i.startsWith("prop:")||i.startsWith("event:")||i.startsWith("directive:")||i.startsWith("slot:"))&&(n+=1);return ti([{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 G_(e){return ei({genericWords:q_,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:K_})}function K_(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 q_=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 To(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:i=6,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=kt(e).vueProfiles({scope:o,minBehaviorTokens:Math.max(3,i),scanLimit:s}).map(d=>({file:d.file,tokens:d.behaviorTokens,profile:d})),u=un(l,d=>d.tokens);return dn({profiles:l,limit:r,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-composable-candidates"},compare:(d,m)=>W_(d,m,n,i),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function W_(e,t,n,i){let r=Bt(e.tokens,t.tokens);if(r.size<i||!Y_(r))return null;let o=Ba(e.tokens,t.tokens);if(o<n)return null;let s=Ee(r,"composable:"),a=Ee(r,"store:"),c=Ee(r,"reactivity:"),l=Ee(r,"lifecycle:"),u=Ee(r,"request:"),d=Ee(r,"function:"),m=Ee(r,"function-verb:"),p=Ee(r,"template-binding:"),f=Ee(r,"template-event:"),g=V_({sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p,sharedTemplateEvents:f});return{fileA:e.file,fileB:t.file,similarity:o,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:ot(r),sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p,sharedTemplateEvents:f,evidenceClass:g.evidenceClass,actionTier:g.actionTier,evidenceClassReasons:g.reasons,recommendation:g.recommendation,uniqueToA:ot(et(e.tokens,t.tokens)).slice(0,25),uniqueToB:ot(et(t.tokens,e.tokens)).slice(0,25),reason:X_({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:l,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function V_(e){return ei({genericWords:Q_,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:J_})}function J_(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 Y_(e){let t=0,n=0,i=0,r=0,o=0,s=0,a=0;for(let u of e)u.startsWith("composable:")?t+=1:u.startsWith("store:")?n+=1:u.startsWith("request:")?i+=1:u.startsWith("lifecycle:")?r+=1:u.startsWith("function:")?o+=1:u.startsWith("reactivity:")?s+=1:(u.startsWith("function-verb:")||u.startsWith("template-binding:")||u.startsWith("template-event:"))&&(a+=1);let c=t+n,l=c+i+r+o+a;return ti([{name:"requests",count:i},{name:"lifecycle",count:r},{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 X_(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 Q_=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 Uu(e,t={}){let{minTotalLines:n=800,minTemplateLines:i=300,minScriptLines:r=300,minStyleLines:o=500,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return kt(e).vueProfiles({scope:a,scanLimit:c}).filter(d=>!l||d.file.includes(l)).map(d=>Z_(d,{minTotalLines:n,minTemplateLines:i,minScriptLines:r,minStyleLines:o})).filter(d=>d!==null).sort((d,m)=>m.totalLines-d.totalLines||d.file.localeCompare(m.file)).slice(0,s)}function Z_(e,t){let n=$a(e,eO(t),"total"),{reasons:i}=n;if(i.length===0)return null;let r=n.dominantPressure,o=n.pressureKinds.includes("total")?[...new Set([...n.pressureKinds,r])]:n.pressureKinds,s=tO(e.file),a=nO(r,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:r,pressureKinds:o,contextKind:s,recommendationKind:a,recommendation:iO(a,s),reasons:i,loc:c}}function eO(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 tO(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(i=>rO.has(i))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function nO(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 iO(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 rO=new Set(["landing","page","pages","route","routes","view","views"]);function oO(e,t={}){let{minSimilarity:n=.5,limit:i=15,scope:r,minChainLength:o=3,maxChainLength:s=8}=t,a=Oe(e,r),c=pO(a,o,s);if(c.length===0)return[];let l=sO(c);return l.length<2?[]:mO(lO(l,n,i),i)}function sO(e){let t=aO(e),n=[];for(let i of e){let r=i.filter(o=>!t.has(o));r.length>=2&&n.push({original:i,filtered:r})}return n}function aO(e){let{nodeFreq:t,tailFreq:n}=cO(e),i=e.length*.9,r=e.length*.8,o=new Set;for(let[a,c]of t)c>i&&o.add(a);for(let[a,c]of n)c>r&&o.add(a);let s=["index.ts","index.js","cli.ts","main.ts","health.ts","health.js"];for(let a of t.keys()){let c=a.split("/").pop()??"";s.includes(c)&&o.add(a)}return o}function cO(e){let t=new Map,n=new Map;for(let i of e){let r=new Set;for(let o of i)r.has(o)||(t.set(o,(t.get(o)??0)+1),r.add(o));for(let o=Math.max(0,i.length-2);o<i.length;o++)n.set(i[o],(n.get(i[o])??0)+1)}return{nodeFreq:t,tailFreq:n}}function lO(e,t,n){let i=[];for(let r=0;r<e.length;r++){for(let o=r+1;o<e.length;o++){let s=uO(e[r],e[o],t);s&&i.push(s)}if(i.length>n*10)break}return i.sort((r,o)=>Math.abs(o.similarity-r.similarity)>.01?o.similarity-r.similarity:r.divergencePoints.length-o.divergencePoints.length),i}function uO(e,t,n){if(!dO(e.filtered,t.filtered))return null;let{distance:i,ops:r}=fO(e.filtered,t.filtered),o=Math.max(e.filtered.length,t.filtered.length);if(o===0)return null;let s=1-i/o;if(s<n||i===0)return null;let a=r.filter(l=>l.type==="substitute").map(l=>({index:l.indexA,nodeA:e.filtered[l.indexA],nodeB:t.filtered[l.indexB]}));return a.length===0||r.filter(l=>l.type==="match").length<2?null:{chainA:e.original,chainB:t.original,similarity:s,editDistance:i,divergencePoints:a,commonPrefix:gO(e.original,t.original),commonSuffix:hO(e.original,t.original)}}function dO(e,t){let n=new Set(e);return t.some(i=>n.has(i))}function mO(e,t){let n=[];for(let i of e)if(n.some(o=>VS(i.chainA,o.chainA)&&VS(i.chainB,o.chainB))||n.push(i),n.length>=t)break;return n}function pO(e,t,n){let i=[];for(let o of e.keys()){if(i.length>=500)break;JS(e,o,[o],new Set([o]),t,n,i,500)}return i}function JS(e,t,n,i,r,o,s,a){if(s.length>=a)return;if(n.length>=o){n.length>=r&&s.push([...n]);return}let c=e.get(t);if(!c||c.size===0){n.length>=r&&s.push([...n]);return}let l=!1;for(let u of c)if(!i.has(u)&&(i.add(u),n.push(u),JS(e,u,n,i,r,o,s,a),n.pop(),i.delete(u),l=!0,s.length>=a))return;!l&&n.length>=r&&s.push([...n])}function fO(e,t){let n=e.length,i=t.length,r=Array.from({length:n+1},()=>Array(i+1).fill(0));for(let c=0;c<=n;c++)r[c][0]=c;for(let c=0;c<=i;c++)r[0][c]=c;for(let c=1;c<=n;c++)for(let l=1;l<=i;l++)e[c-1]===t[l-1]?r[c][l]=r[c-1][l-1]:r[c][l]=1+Math.min(r[c-1][l],r[c][l-1],r[c-1][l-1]);let o=[],s=n,a=i;for(;s>0||a>0;)s>0&&a>0&&e[s-1]===t[a-1]?(o.unshift({type:"match",indexA:s-1,indexB:a-1}),s--,a--):s>0&&a>0&&r[s][a]===r[s-1][a-1]+1?(o.unshift({type:"substitute",indexA:s-1,indexB:a-1}),s--,a--):a>0&&r[s][a]===r[s][a-1]+1?(o.unshift({type:"insert",indexA:s,indexB:a-1}),a--):(o.unshift({type:"delete",indexA:s-1,indexB:a}),s--);return{distance:r[n][i],ops:o}}function gO(e,t){let n=[];for(let i=0;i<Math.min(e.length,t.length)&&e[i]===t[i];i++)n.push(e[i]);return n}function hO(e,t){let n=[],i=e.length-1,r=t.length-1;for(;i>=0&&r>=0&&e[i]===t[r];)n.unshift(e[i]),i--,r--;return n}function VS(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),i=e.join("\u2192");return n.includes(i)}function $t(e){let t=yO(e.profile?.name),n=()=>{let i=e.candidates(),r=e.filterCandidate?i.filter(e.filterCandidate):i,o=e.orderCandidates?[...r].sort(e.orderCandidates):r,s=Fe(o,e.scanLimit);t={pipeline:e.profile?.name,loadedCandidates:i.length,filteredCandidates:r.length,scannedCandidates:s.length,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:s.length<r.length,resultLimitApplied:!1};let a=e.prepare?.(s)??void 0,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?$(`candidate-pipeline:${e.profile.name}`,n,()=>({...bO(e.profile?.metadata),...t})):n()}function yO(e){return{pipeline:e,loadedCandidates:0,filteredCandidates:0,scannedCandidates:0,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:!1,resultLimitApplied:!1}}function bO(e){return typeof e=="function"?e():e??{}}function Mo(e,t={}){let{scope:n,minLoc:i=10,minCallees:r=6,limit:o=20,scanLimit:s}=t,a=new U(e);return $t({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:i,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:SO(c,l.rows.get(c.symbolId)??[],r),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function SO(e,t,n){let i=new Set(t.map(l=>l.symbol));if(i.size<n)return null;let r=EO(i,t),o=wO(i,r);if(o.length<2)return null;let s=IO(o,r);if(s.length===0)return null;let a=k(e.symbol),c=vO(a,i.size,o.length,s);return{symbol:e.symbol,shortName:a,relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:de(e),totalCallees:i.size,extractionKind:c.extractionKind,actionTier:"signal",evidenceReasons:c.evidenceReasons,recommendation:c.recommendation,clusters:s}}function vO(e,t,n,i){let r=Math.max(...i.map(c=>c.callees.length)),o=Math.max(...i.map(c=>c.isolation)),s=[`${t} distinct callees across ${n} co-occurrence cluster(s)`,`${i.length} extractable cluster(s) passed size and isolation thresholds`,`largest extractable cluster has ${r} callees at ${Math.round(o*100)}% isolation`],a=CO(e,t,n);return a!==null?{extractionKind:"workflow-orchestration",evidenceReasons:[...s,a],recommendation:"Review the isolated helper group as a possible private or feature-local helper, but keep the orchestration sequence together when it preserves the workflow."}:r>=6?{extractionKind:"broad-helper-cluster",evidenceReasons:[...s,"one isolated helper group is broad enough to deserve a named review"],recommendation:"Review whether the broad helper cluster has a stable concept name before extracting it; avoid creating a bag-of-helpers abstraction."}:{extractionKind:"cohesive-helper-cluster",evidenceReasons:s,recommendation:"Review the isolated callee group as a possible same-file or feature-local helper; extract only if the new name preserves the current behavior."}}function CO(e,t,n){if(t>=10)return`callee breadth suggests orchestration: ${t} callees`;if(n>=4)return`multiple disconnected callee groups suggest orchestration: ${n} groups`;let i=xO(e);return RO.has(i)?`caller verb suggests orchestration: ${i}`:null}function xO(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 RO=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function EO(e,t){let n=new Map;for(let r of e)n.set(r,new Set);let i=new Map;for(let r of t){let o=i.get(r.chunkId);o||(o=new Set,i.set(r.chunkId,o)),o.add(r.symbol)}for(let r of i.values()){let o=[...r];for(let s=0;s<o.length;s++)for(let a=s+1;a<o.length;a++)n.get(o[s]).add(o[a]),n.get(o[a]).add(o[s])}return n}function wO(e,t){let n=new Set,i=[];for(let r of e){if(n.has(r))continue;let o=new Set,s=[r];for(;s.length>0;){let a=s.pop();if(!n.has(a)){n.add(a),o.add(a);for(let c of t.get(a)??[])n.has(c)||s.push(c)}}i.push(o)}return i}function IO(e,t){return e.filter(n=>n.size>=3).map(n=>LO(n,e,t)).filter(n=>n.isolation>.5).sort((n,i)=>i.isolation-n.isolation)}function LO(e,t,n){let i=new Set;for(let a of t)if(a!==e)for(let c of a)i.add(c);let r=0;for(let a of e)for(let c of n.get(a)??[])i.has(c)&&r++;let o=e.size*i.size,s=o>0?1-r/o:1;return{callees:[...e].map(k),isolation:s}}import{posix as gr}from"path";import{spawnSync as PO}from"child_process";import{createHash as DO}from"crypto";import{existsSync as TO}from"fs";import{dirname as YS,join as MO}from"path";import{fileURLToPath as AO}from"url";var ZS=Bi("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]}),XS=xt({kind:"consumer-file-usage",invalidation:Je("consumer-file-usage"),serialize:UO,deserialize:zO});function mn(e,t){return{forDefinitions(n,i){return FO(e,t,n,i)}}}function ni(e){let t=new Map;for(let[n,i]of e)t.set(n,new Set(i.files.map(r=>r.file)));return t}function Ha(e,t,n){return tv(e,t,n).partition}function FO(e,t,n,i){let r=ev(n.length),o=mt()?yn(e):null,s=o?NO(n,i,o):void 0,a=s?{workIdentity:s,workOutcome:"computed"}:{};return $("consumer-evidence.product",()=>{let c=$("consumer-evidence.provenance",()=>kO(e,t,n,i),()=>({...a,definitions:n.length,semantic:i.semantic,sourceFallback:i.sourceFallback!==!1})),l=new Map;r={...r,...c.counters};let u=_O(n,c.sources);return $("consumer-evidence.classify",()=>{let d=OO(e,n,c.sources,u);for(let m of n){let p=d.get(m.symbolId)??$O();r.realFiles+=p.partition.realConsumers.length,r.reexportOnlyFiles+=p.partition.barrelConsumers,r.importOnlyFiles+=p.partition.importOnlyConsumers,l.set(m.symbolId,{definition:m,files:p.files,semanticIncomplete:c.incompleteSymbolIds.has(m.symbolId),semanticUnavailable:c.unavailableSymbolIds.has(m.symbolId),...p.partition})}},()=>({...a,...u,realFiles:r.realFiles,reexportOnlyFiles:r.reexportOnlyFiles,importOnlyFiles:r.importOnlyFiles})),l},()=>({...a,...r}))}function NO(e,t,n){let i=DO("sha256").update("consumer-evidence-v3-calibrated-semantic\0").update(n).update("\0").update(t.semantic?"semantic\0":"indexed\0").update(t.sourceFallback===!1?"no-source-fallback":"source-fallback");for(let r of e.map(o=>o.symbol).sort())i.update("\0").update(r);return i.digest("hex").slice(0,24)}function ev(e){return{definitions:e,indexedFiles:0,semanticFiles:0,fallbackFiles:0,totalFiles:0,realFiles:0,reexportOnlyFiles:0,importOnlyFiles:0}}function kO(e,t,n,i){let r=ev(n.length),o=new Map,s=new Set,a=new Set;if(zu(o,r,"indexed",t.crossFileCallerMap(n,{semantic:!1})),i.semantic){let c=Rn(e,n);zu(o,r,"semantic",c.callers);for(let l of c.incompleteSymbolIds)s.add(l);for(let l of c.unavailableSymbolIds)a.add(l)}return i.sourceFallback!==!1&&zu(o,r,"source-fallback",t.sourceFallbackCallerFiles(n)),r.totalFiles=[...o.values()].reduce((c,l)=>c+l.size,0),{sources:o,counters:r,incompleteSymbolIds:s,unavailableSymbolIds:a}}function _O(e,t){return{definitions:e.length,consumerFiles:[...t.values()].reduce((n,i)=>n+i.size,0),nativeAttempted:!1,nativeUsed:!1,nativeReason:"not-attempted"}}function zu(e,t,n,i){let r=0;for(let[o,s]of i){let a=e.get(o);a||(a=new Map,e.set(o,a));for(let c of s){r++;let l=a.get(c)??new Set;l.add(n),a.set(c,l)}}n==="indexed"?t.indexedFiles+=r:n==="semantic"?t.semanticFiles+=r:t.fallbackFiles+=r}function OO(e,t,n,i){let r=YO(e,t,n,i);return r||BO(e,t,n)}function BO(e,t,n){let i=new Map;for(let r of t){let o=n.get(r.symbolId)??new Map;i.set(r.symbolId,tv(e,r,[...o.keys()],o))}return i}function tv(e,t,n,i=new Map){let r=[],o=0,s=0,a=re(t.symbol),c=[];for(let l of n){let u;GO(e,l,t.relativePath,a)?(o++,u="reexport-only"):Gu(e,l,a)?(s++,u="import-only"):(r.push(l),u="real"),c.push({file:l,sources:[...i.get(l)??[]],classification:u})}return{partition:{realConsumers:r,barrelConsumers:o,importOnlyConsumers:s},files:c}}function $O(){return{partition:{realConsumers:[],barrelConsumers:0,importOnlyConsumers:0},files:[]}}function Gu(e,t,n){if(!n)return!1;let i=ye(t);if(!i)return!1;let r=ZS.get(e,t,()=>nv(e,t,i));return r.importedLeaves.has(n)&&!r.usedLeaves.has(n)}function nv(e,t,n){let i=On(e).forFile(t,{text:!0,ast:!0}),r=i.text;if(!r)return HO();let o=Ft(e,t,r),s=XS.read(e,t,o);if(s)return s;let a=jO(i.ast,n);return XS.write(e,t,o,a),a}function jO(e,t){let n=new Set,i=new Set;if(!e)return{importedLeaves:n,usedLeaves:i};let r=t==="rust"?new Set(["use_declaration"]):t==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),o=(s,a)=>{let c=a||r.has(s.type);(s.type==="identifier"||s.type==="type_identifier"||s.type==="property_identifier"||s.type==="field_identifier")&&(c?n.add(s.text):i.add(s.text));for(let l of s.children)o(l,c)};return o(e.rootNode,!1),{importedLeaves:n,usedLeaves:i}}function HO(){return{importedLeaves:new Set,usedLeaves:new Set}}function UO(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function zO(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 GO(e,t,n,i){if(!i)return!1;let r=On(e).forFile(t,{lines:!0,reexports:!0}),o=r.lines??[];if(o.length===0)return!1;let s=r.reexports??[];return iv(o,s,i)}function iv(e,t,n){if(e.length===0||t.length===0)return!1;let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`\\b${i}\\b`),o=0;for(let s=0;s<e.length;s++){if(!r.test(e[s]??""))continue;if(o++,!t.find(c=>c.startLine<=s&&s<=c.endLine))return!1}return o>0}var KO="CODEBASEIQ_NATIVE_CONSUMER_CLASSIFY",qO="CODEBASEIQ_NATIVE_KERNELS_BIN",WO="CODEBASEIQ_NATIVE_CONSUMER_CLASSIFY_MIN_FILES",QS=1e3,VO=5e3,JO=64*1024*1024,ja;function YO(e,t,n,i){let r=process.env[KO]?.toLowerCase();if(r!=="1"&&r!=="true")return i.nativeReason=r==="0"||r==="false"?"disabled":"opt-in-required",null;if(i.consumerFiles<iB())return i.nativeReason="below-threshold",null;let o=rB();if(!o)return i.nativeReason="binary-missing",null;i.nativeAttempted=!0;let s=XO(e,t,n),a=PO(o,["consumer-classify"],{input:JSON.stringify(s),encoding:"utf8",timeout:VO,maxBuffer:JO,windowsHide:!0});if(a.status!==0||a.error)return i.nativeReason=a.error?`spawn-error:${a.error.message}`:`exit-${a.status??"null"}`,null;try{let c=JSON.parse(a.stdout),l=ZO(c,t);return l?(i.nativeUsed=!0,i.nativeReason="used",l):(i.nativeReason="invalid-response",null)}catch{return i.nativeReason="invalid-json",null}}function XO(e,t,n){let i=new Map,r=[];for(let a of t){let c=re(a.symbol),u=[...(n.get(a.symbolId)??new Map).entries()].map(([d,m])=>{let p=i.get(d)??new Set;return c&&p.add(c),i.set(d,p),{file:d,sources:[...m]}});r.push({symbol_id:a.symbolId,leaf:c,consumer_files:u})}let o={},s={};for(let[a,c]of i){let l=ye(a);if(l){let d=ZS.get(e,a,()=>nv(e,a,l));o[a]={imported_leaves:[...d.importedLeaves],used_leaves:[...d.usedLeaves]}}let u=QO(e,a,c);u.length>0&&(s[a]=u)}return{definitions:r,file_usages:o,reexport_only_leaves:s}}function QO(e,t,n){if(n.size===0)return[];let i=On(e).forFile(t,{lines:!0,reexports:!0}),r=i.lines??[],o=i.reexports??[];return r.length===0||o.length===0?[]:[...n].filter(s=>iv(r,o,s))}function ZO(e,t){if(!Array.isArray(e.entries)||e.entries.length!==t.length)return null;let n=new Set(t.map(r=>r.symbolId)),i=new Map;for(let r of e.entries){let o=eB(r);if(!o||!n.has(o.symbol_id))return null;i.set(o.symbol_id,{partition:{realConsumers:o.real_consumers,barrelConsumers:o.barrel_consumers,importOnlyConsumers:o.import_only_consumers},files:o.files})}for(let r of n)if(!i.has(r))return null;return i}function eB(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.symbol_id!="number"||!Array.isArray(t.real_consumers)||typeof t.barrel_consumers!="number"||typeof t.import_only_consumers!="number"||!Array.isArray(t.files)||!t.real_consumers.every(i=>typeof i=="string"))return null;let n=[];for(let i of t.files){if(!i||typeof i!="object")return null;let r=i;if(typeof r.file!="string"||!Array.isArray(r.sources)||!r.sources.every(tB)||!nB(r.classification))return null;n.push({file:r.file,sources:r.sources,classification:r.classification})}return{symbol_id:t.symbol_id,real_consumers:t.real_consumers,barrel_consumers:t.barrel_consumers,import_only_consumers:t.import_only_consumers,files:n}}function tB(e){return e==="indexed"||e==="semantic"||e==="source-fallback"}function nB(e){return e==="real"||e==="reexport-only"||e==="import-only"}function iB(){let e=process.env[WO];if(!e)return QS;let t=Number(e);return Number.isFinite(t)&&t>=0?t:QS}function rB(){if(ja!==void 0)return ja;let e=process.env[qO],t=process.platform==="win32"?"codebaseiq-kernels.exe":"codebaseiq-kernels";return ja=[...e?[e]:[],...oB().map(i=>MO(i,"target","release",t))].find(i=>TO(i))??null,ja}function oB(){let e=new Set,t=YS(AO(import.meta.url));for(let n=0;n<5;n++)e.add(t),t=YS(t);return[...e]}var sB=20,aB=1,cB=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"]]),lB=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),uB=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 dB(e,t={}){let n=Wu(t.limit,sB),i=Wu(t.minConsumers,aB),r=new U(e),o=r.fileDependencyGraph(t.scope),s=MB(he(e,{includeIgnored:!1})),a=NB(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?mB(e,r,t.target):pB(e,t.scope,t.scanLimit)).map(u=>fB(e,r,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=i||t.target).sort(TB).slice(0,n)}function mB(e,t,n){let i=yB(e,n);if(i)return[cv(i)];let r=pe(e,n);if(!r)return[];let o=t.definitionsForFile(r.relativePath).find(s=>s.symbolId===r.symbolId);return o?[bB(o)]:[{unit:{kind:"symbol",file:r.relativePath,shortName:k(r.symbol),symbol:r.symbol,startLine:r.startLine,endLine:r.endLine}}]}function pB(e,t,n){let i=he(e,{scope:t,includeIgnored:!1}),r=Wu(n,i.length);return i.slice(0,r).map(o=>cv(o))}function fB(e,t,n,i,r,o,s){let a=i.definition?gB(e,t,i.definition,r.semantic):null,c=a?.files??hB(n,i.unit.file),l=i.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=i.unit.file,m=Wt(gr.dirname(d)),p=vB(c),f=SB(m),g=Ju([...rv(m),...p?rv(p):[]]),h=u?"repository-level-review":CB(i.unit,m,p,c),b=u?{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:`Compiler-resolved consumer evidence is ${l}; no relocation destination is safe to score.`}:xB(h,i.unit,m,p,c,o,s),v=LB(i.unit,l,p,c,m,b.whyNoSuggestedHome),y=PB(i.unit,m,p,c,b.suggestedHome,b.whyNoSuggestedHome);return{actionTier:"signal",sourceUnit:i.unit,candidatePath:d,currentDirectory:m,directoryAncestry:f,consumerFiles:c,consumerCoverage:l,nearestCommonOwner:p,boundaryMarkers:g,recommendedTier:h,suggestedHome:b.suggestedHome,destinationConfidence:b.confidence,whyNoSuggestedHome:b.whyNoSuggestedHome,counterevidence:u?[...v,"Known consumer files are retained, but missing compiler evidence can hide additional owners."]:v,reasons:y,recommendation:u?"Retain the current location until compiler-resolved consumer evidence is complete.":DB(h,b.suggestedHome,l)}}function gB(e,t,n,i){let r=mn(e,t).forDefinitions([n],{semantic:i!==!1,sourceFallback:!0}).get(n.symbolId),o=r?.semanticIncomplete?r.semanticUnavailable?"incomplete-and-unavailable":"incomplete":r?.semanticUnavailable?"unavailable":"complete";return{files:pv(r?.files.map(s=>s.file)??[]),coverage:o}}function hB(e,t){let n=[];for(let[i,r]of e.entries())i!==t&&r.has(t)&&n.push(i);return pv(n)}function yB(e,t){let n=es(t),i=he(e,{includeIgnored:!1}),r=i.find(s=>s===n);if(r)return r;let o=i.find(s=>s.endsWith(`/${n}`));return o||(i.find(s=>s.includes(n))??null)}function bB(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:k(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function cv(e){return{unit:{kind:"file",file:e,shortName:gr.basename(e)}}}function SB(e){if(e===".")return[{path:".",depth:0,markers:[]}];let t=[],n=e.split("/").filter(Boolean);for(let i=0;i<n.length;i+=1){let r=n.slice(0,i+1).join("/");t.push({path:r,depth:i,markers:Vu(r)})}return t}function rv(e){return e==="."?[]:lv(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function Vu(e){return Ju(lv(e).map(({marker:t})=>t))}function lv(e){let t=e.split("/").filter(Boolean),n=[];for(let i=0;i<t.length;i+=1){let r=cB.get(t[i]);r&&n.push({marker:r,prefix:t.slice(0,i+1).join("/")})}return n}function vB(e){if(e.length===0)return null;let t=e.map(i=>Wt(gr.dirname(i))),n=t[0].split("/").filter(Boolean);for(let i of t.slice(1)){let r=i.split("/").filter(Boolean),o=[],s=Math.min(n.length,r.length);for(let a=0;a<s&&n[a]===r[a];a+=1)o.push(n[a]);n=o}return n.length===0?".":n.join("/")}function CB(e,t,n,i){return n?e.kind==="symbol"&&i.length===1?i[0]===e.file?"same-file":"sibling-folder":n==="."||n==="src"?"repository-level-review":sv(n,"package")?"package-level-shared":sv(n,"app")?"app-level-shared":av(n,["feature","domain","module"])||av(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function xB(e,t,n,i,r,o,s){let a=RB(e,i);if(a)return ii(a);let c=AB(t.file),l=EB(e,n,c,r,s);if(l)return l;let u=i;if(Wt(n)===Wt(u))return ii(`${n} is already the nearest common owner for its consumers.`);let d=wB(u,n,c,s);return d||IB(u,n,c,o,s)}function RB(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 EB(e,t,n,i,r){if(e==="same-file"){let o=i[0]??null;return o?Ku(o):ii("No same-file consumer path was available.")}if(e==="sibling-folder"&&i.length===1){let o=Wt(gr.dirname(i[0])),s=mv(t,n,o,r);return s?ii(s):Ku(o)}return null}function wB(e,t,n,i){return _B(e)?uv(e,t,n,i,`Nearest shared owner ${e} is outside source root ${n}.`):null}function IB(e,t,n,i,r){if(e===".")return ii("The nearest common owner is the repository root.");let o=`${e}/shared`,s=uv(o,t,n,r,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||i.has(o)?s:ii(`${o} does not exist in the indexed project.`)}function uv(e,t,n,i,r){if(!dv(e,n))return ii(r);let o=mv(t,n,e,i);return o?ii(o):Ku(e)}function Ku(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function ii(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function LB(e,t,n,i,r,o){let s=["Report-only signal; review ownership before moving files."];return t==="none"&&s.push("No consumers were found in the current index."),t==="file-level"&&s.push("File-level import evidence can hide which exported unit is actually used."),(n==="."||n==="src")&&s.push("Nearest common owner is broad, so this is not enough evidence for automatic placement."),i.length===1&&s.push("Only one consumer was found; inlining or same-folder placement may be better than shared extraction."),e.kind==="file"&&s.push("File targets describe module locality, not symbol-level usage."),n&&r.startsWith(`${n}/`)&&s.push("Candidate already lives under the nearest common owner."),o&&s.push(`No exact suggested home: ${o}`),s}function PB(e,t,n,i,r,o){let s=[];return s.push(`${e.shortName} currently lives in ${t}.`),n?s.push(`${i.length} consumer file(s) share ${n} as their nearest common owner.`):s.push("No consumer owner could be inferred from the current index."),r?s.push(`Suggested home is ${r}.`):o&&s.push(`No exact suggested home: ${o}`),s}function DB(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 TB(e,t){return ov(t)-ov(e)||e.candidatePath.localeCompare(t.candidatePath)}function ov(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 MB(e){let t=new Set(["."]);for(let n of e){let i=Wt(gr.dirname(n));for(;!t.has(i)&&(t.add(i),i!==".");)i=Wt(gr.dirname(i))}return t}function AB(e){let t=qu(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function dv(e,t){let n=Wt(e),i=Wt(t);return i==="."||n===i||n.startsWith(`${i}/`)}function FB(e,t,n){let i=qu(e),r=qu(t);return(dv(e,t)?i.slice(r.length):i).some(s=>n.has(s.toLowerCase()))}function mv(e,t,n,i){return Wt(e)===Wt(n)||!FB(e,t,i)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function NB(...e){let t=new Set(uB);for(let n of e)for(let i of n??[]){let r=kB(i);r&&t.add(r)}return t}function kB(e){let t=e.trim().toLowerCase();return t===""?null:t}function sv(e,t){return Vu(e).includes(t)}function av(e,t){let n=Vu(e);return t.some(i=>n.includes(i))}function _B(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?lB.has(n):!1}function Wt(e){let t=es(e);return t===""?".":t}function qu(e){let t=es(e);return t==="."?[]:t.split("/").filter(Boolean)}function Wu(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function pv(e){return Ju([...e]).sort((t,n)=>t.localeCompare(n))}function Ju(e){return[...new Set(e)]}function Yu(e,t,n={}){return OB(e,t,n)}function OB(e,t,n){let{maxDepth:i=5,scope:r}=n,o=i===Number.MAX_SAFE_INTEGER,s=o?null:500,a=pe(e,t);if(!a)return{rows:[],coverage:{status:"incomplete",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:i,reachedDepth:0,perSymbolEvidenceLimit:s,remainingFrontierSymbols:0,reasons:["The requested symbol could not be resolved."],semanticEvidence:"incomplete"}};let c=[],l=new Set([a.symbolId]),u=new Set,d=[a],m=0,p=!1,f=!1,g=!1;for(let v=1;v<=i&&d.length!==0;v++){m=v;let y=[],E=tn(e,d,{...o?{}:{limit:s+1},semanticEvidence:fe});E.incompleteSymbolIds.size>0&&(f=!0),E.unavailableSymbolIds.size>0&&(g=!0);for(let w of d){let S=E.rows.get(w.symbolId)??[];s!==null&&S.length>s&&(p=!0);let R=s===null?S:S.slice(0,s);for(let C of BB(e,w,r,R)){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:v}),C.symbolId!==null&&C.symbolMatch&&y.push(C.symbolMatch)}}d=y}c.sort((v,y)=>v.depth-y.depth||v.file.localeCompare(y.file));let h=d.length>0,b=[];return h&&b.push(`${d.length} symbol(s) remain eligible beyond depth ${i}.`),p&&b.push(`At least one symbol had more than ${s} incoming evidence row(s).`),f&&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:f||g?"incomplete":h||p?"bounded":"accounted",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:i,reachedDepth:m,perSymbolEvidenceLimit:s,remainingFrontierSymbols:d.length,reasons:b,semanticEvidence:f&&g?"incomplete-and-unavailable":f?"incomplete":g?"unavailable":"complete"}}}function BB(e,t,n,i){let r=i.filter(u=>!e.isIgnored(u.file)).filter(u=>!n||u.file.includes(n)),o=new Set(r.map(u=>u.file)),s=[];for(let u of $B(e,t,n)){if(o.has(u))continue;let d=J(e,u),m=d.length>0?Ge(d,d[0].startLine):null;s.push({symbol:m?.symbol??u,file:u})}let a=[...r,...s],c=[],l=new Set;for(let u of a){let d=li(e,u.symbol);if(!d){let p=`${u.file}|${u.symbol}`;if(l.has(p))continue;l.add(p),c.push({symbolId:null,symbol:u.symbol,shortName:k(u.symbol),file:u.file,symbolMatch:null});continue}if(d.symbolId===t.symbolId||e.isIgnored(d.relativePath)||!jB(d))continue;let m=`${d.symbolId}|${d.relativePath}`;l.has(m)||(l.add(m),c.push({symbolId:d.symbolId,symbol:d.symbol,shortName:k(d.symbol),file:d.relativePath,symbolMatch:d}))}return c}function $B(e,t,n){let i=n?"AND consumer_d.relative_path LIKE ?":"",r=[t.symbolId,t.documentId];return n&&r.push(`%${n}%`),new Set(e.all(`SELECT DISTINCT consumer_d.relative_path
321
- FROM mentions m
322
- JOIN chunks c ON m.chunk_id = c.id
323
- JOIN documents consumer_d ON consumer_d.id = c.document_id
324
- WHERE m.symbol_id = ?
325
- AND m.role != 1
326
- AND c.document_id != ?
327
- ${e.pathExclusionsFor("consumer_d")}
328
- ${i}`,...r).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function jB(e){if(e.symbol.startsWith("scip-clojure ")||ye(e.relativePath)==="clojure")return!0;let t=Bn(e.symbol);return t==="method"||t==="type"||e.symbol.endsWith("().")}function gv(e,t){let n=pt(t),i=[],r="complete",o=V(n);o==="entry"&&Fn(i,"operational-root","structural entrypoint path"),o==="worker"&&Fn(i,"operational-root","worker launch convention"),Tl(n)&&Fn(i,"operational-root","framework-discovered entrypoint"),HB(e,n)&&Fn(i,"operational-root","configured entry root");let s=!1;try{s=wn(e,n),s&&Fn(i,"published-api","package manifest export");for(let a of Sg(e,n))Fn(i,"operational-root",a)}catch(a){r="partial",Fn(i,"metadata-unavailable",`package metadata unavailable: ${fv(a)}`)}try{let a=nt(e.config.projectRoot,n,{maxBytes:8388608,inputKind:"change-surface source"});UB(a)&&Fn(i,"operational-root","module contains a direct-execution process guard")}catch(a){r="partial",Fn(i,"metadata-unavailable",Ct(a)?"indexed source file is unavailable on disk":`source metadata unavailable: ${fv(a)}`)}return{operationalRoot:i.some(a=>a.kind==="operational-root"),publishedApi:s,coverage:r,reasons:i}}function HB(e,t){let n=e.config.entryRoots;return n?n.files?.some(i=>pt(i)===t)?!0:n.pathPrefixes?.some(i=>t.startsWith(pt(i)))??!1:!1}function UB(e){return e.includes("import.meta.url")&&/process\.argv\s*\[\s*1\s*\]/.test(e)||/require\.main\s*===\s*module/.test(e)||/__name__\s*==\s*['"]__main__['"]/.test(e)}function Fn(e,t,n){e.some(i=>i.kind===t&&i.detail===n)||e.push({kind:t,detail:n})}function fv(e){return e instanceof Error?e.message:String(e)}function Xu(e,t,n={}){let i=ct(e,t);if(!i)return null;let r=GB(e,i);if(!r||e.isIgnored(r.relative_path))return null;let o=[],s=0,a=!0,c=KB(e,r.relative_path),l=gv(e,r.relative_path),u=n.semantic===!1?{callers:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set}:Rn(e,c);for(let d of c){let m=qB(e,r,d,u.callers.get(d.symbolId)??new Set);s+=m;let p=zB(n.semantic!==!1,d.symbolId,u),f=p==="complete"||p==="disabled";f||(a=!1);let g=f?m:null,h=g===null?void 0:WB(g),b=[...l.reasons,...m>0?[{kind:"external-consumers",detail:`${m} known external consumer${m===1?"":"s"}`}]:[],...f?[]:[{kind:"semantic-consumer-coverage",detail:`compiler-resolved consumer evidence is ${p}`}]];o.push({symbol:d.symbol,shortName:k(d.symbol),startLine:d.startLine,endLine:d.endLine,externalConsumers:g,knownExternalConsumers:m,consumerCoverage:p,externalConsumerRiskLevel:h,riskLevel:VB(h,l,!f),riskReasons:b})}return{file:r.relative_path,symbols:o,totalExternalConsumers:a?s:null,knownTotalExternalConsumers:s,fileRisk:l}}function zB(e,t,n){if(!e)return"disabled";let i=n.incompleteSymbolIds.has(t),r=n.unavailableSymbolIds.has(t);return i&&r?"incomplete-and-unavailable":i?"incomplete":r?"unavailable":"complete"}function GB(e,t){return e.get(`SELECT id, relative_path FROM documents
329
- WHERE relative_path = ?
330
- ${e.pathExclusionsFor("documents")}
331
- LIMIT 1`,t)??null}function KB(e,t){return new U(e).definitionsForFile(t).sort((n,i)=>n.startLine-i.startLine||n.endLine-i.endLine)}function qB(e,t,n,i){let r=e.all(`SELECT DISTINCT consumer_d.relative_path
332
- FROM mentions m
333
- JOIN chunks c ON m.chunk_id = c.id
334
- JOIN documents consumer_d ON consumer_d.id = c.document_id
335
- WHERE m.symbol_id = ?
336
- AND m.role != 1
337
- AND c.document_id != ?`,n.symbolId,t.id);return new Set([...r.map(o=>o.relative_path),...[...i].filter(o=>o!==t.relative_path)]).size}function WB(e){return e>10?"high":e>0?"medium":"low"}function VB(e,t,n){return e==="high"?"high":n||e==="medium"||t.operationalRoot||t.publishedApi||t.coverage==="partial"?"medium":"low"}function JB(e,t={}){let{scope:n,minLoc:i=1,maxDepth:r=5,scanLimit:o}=t,s=new U(e),a=YB(e,n,i,o),c=new Qu;for(let g of a)c.add(g);let l=[],u=[];a.length>0&&l.push(hv(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<=r&&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 v=[];for(let y of b){m.add(y);let E=yv(e,y);if(!E||e.isIgnored(E.relativePath)||Ye(e,E.relativePath)||Ue(e,E.symbol,E.relativePath)||s.fileKind(E.relativePath)==="test"||s.hasSuppressionComment(E))continue;let w=QB(e,E,c);w.removable?v.push(XB(E,"cascade")):w.blockingFiles.length>0&&u.push({shortName:k(E.symbol),file:E.relativePath,blockingFiles:w.blockingFiles.slice(0,3)})}if(v.length===0)break;for(let y of v)c.add(y);l.push(hv(e,g,v,c)),d=v.map(y=>y.definition).filter(y=>y!==null)}let p=l.reduce((g,h)=>g+h.loc,0),f=l.reduce((g,h)=>g+h.entries.length,0);return{batches:l,totalSymbols:f,totalLoc:p,blocked:u}}function YB(e,t,n,i){let r=Ti(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:i,semantic:!1}),o=[];for(let s of r.symbols)s.kind==="dead-code"&&(Ye(e,s.relativePath)||Ue(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:yv(e,s.symbol)}));return o}function XB(e,t){return{symbol:e.symbol,shortName:k(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function yv(e,t){let n=e.get(`SELECT d.relative_path
338
- FROM global_symbols gs
339
- JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
340
- JOIN documents d ON d.id = der.document_id
341
- WHERE gs.symbol = ?
342
- LIMIT 1`,t);return n?J(e,n.relative_path).find(i=>i.symbol===t)??null:null}function QB(e,t,n){let i=Tr(e,t);if(i.length===0)return{removable:!1,blockingFiles:[]};let r=new Set;for(let o of i)o.file===t.relativePath&&o.line>=t.startLine&&o.line<=t.endLine||n.contains(o.file,o.line)||r.add(o.file);return{removable:r.size===0,blockingFiles:[...r]}}function hv(e,t,n,i){let r=[...n].sort((a,c)=>a.file.localeCompare(c.file)||a.startLine-c.startLine),o=new Set(r.map(a=>a.file)),s=[];for(let a of o){let c=J(e,a);c.length>0&&c.every(l=>i.contains(a,l.startLine))&&s.push(a)}return{depth:t,entries:r.map(({definition:a,...c})=>c),loc:r.reduce((a,c)=>a+c.loc,0),filesEmptied:s.sort()}}var Qu=class{ranges=new Map;add(t){let n=this.ranges.get(t.file)??[];n.push({start:t.startLine,end:t.endLine}),this.ranges.set(t.file,n)}contains(t,n){let i=this.ranges.get(t);return i?i.some(r=>n>=r.start&&n<=r.end):!1}};import{execFileSync as hr}from"child_process";import{existsSync as ZB}from"fs";import{basename as bv}from"path";function Ua(e){let t=new Map;for(let n of e){let i=t.get(n.file);i||(i=[],t.set(n.file,i)),i.push(n)}return t}var id="Unable to compute git diff.",e$={semanticConsumers:ig,sourceFallbackConsumers:Yr},rd={resolveCommit:Pc,readBatch({projectRoot:e,resolvedBase:t,relativePaths:n}){let i=n.map(r=>`${t}:./${r}
343
- `).join("");return hr("git",["cat-file","--batch"],{cwd:e,input:i,maxBuffer:256*1024*1024,timeout:1e4,stdio:["pipe","pipe","ignore"],windowsHide:!0})}};function za(e,t={}){let n=t.plan??yr(e,t);return n.note?t$(n.note,n.changedFileLines):n.changedFiles.length===0?n$(n.changedFileLines):Ga(n.changedFiles,[xv(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function yr(e,t={}){let{base:n="HEAD"}=t;try{let i=Pc(e.config.projectRoot,n),r=i$(e.config.projectRoot,i),o=r.changedFileLines,s=l$(e,o),a=u$(e,r.changedRanges);return{changedFileLines:o,changedFiles:s,changedRanges:a,renamedFiles:s$(e.config.projectRoot,i,s,r),note:o.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:id}}}function xv(e,t,n,i=[],r={}){let o=r.evidenceRuntime??e$,s=new U(e),a=new Set(n),c=Ua(i),l=[],u=new Map,d=t.flatMap(C=>s.definitionsForFile(C)).filter(I$),m=d.filter(C=>m$(C,c)),p=f$(e,d,m,c),f=y$([...m,...p.definitions]).sort((C,L)=>C.relativePath.localeCompare(L.relativePath)||C.startLine-L.startLine),g=f.map(C=>C.symbolId),h=R$(e,g),b=E$(e,g,n),v=f.filter(C=>(h.get(C.symbolId)??0)===0),y=Cv("semantic-consumers",v.length,()=>o.semanticConsumers(e,v)),E=y.values,w=v.filter(C=>(E.get(C.symbolId)?.size??0)===0),S=Cv("source-fallback-consumers",w.length,()=>o.sourceFallbackConsumers(e,w)),R=S.values;for(let C of f)v$(e,C,a,l,u,E.get(C.symbolId)??new Set,R.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:p.notes,evidenceTiers:[y.status,S.status]}}function Ga(e,t){let n=new Map,i=t.flatMap(a=>a.changedSymbols),r=t.flatMap(a=>a.attributionNotes??[]),o=C$(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=w$(n);return{changedFiles:[...e],changedSymbols:i,affectedConsumers:s,attributionNotes:r,evidenceTiers:o,summary:{totalChangedFiles:e.length,totalChangedSymbols:i.length,totalAffectedFiles:s.length}}}function t$(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:Dv(),summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function n$(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:Dv(),summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function i$(e,t){let n=hr("git",["diff","--name-status","--find-renames",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864,windowsHide:!0}),i=hr("git",["diff","--name-status","--find-renames","--cached",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024,windowsHide:!0}),r=hr("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024,windowsHide:!0}),o=hr("git",["diff","--unified=0",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024,windowsHide:!0}),s=hr("git",["diff","--unified=0","--cached",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024,windowsHide:!0}),a=a$([n,i]);return{changedFileLines:[...new Set([...a.changedFiles,...wv(r)])],changedRanges:Lv([...vv(o),...vv(s)]),renamedFiles:a.renamedFiles,deletedFiles:a.deletedFiles}}function r$(e,t,n){let i=typeof e=="string"?{projectRoot:e,base:t,relativePath:n}:e;if(typeof i.projectRoot!="string"||typeof i.base!="string"||typeof i.relativePath!="string")throw new TypeError("fileContentAtBase requires projectRoot, base, and relativePath.");let r={projectRoot:i.projectRoot,base:i.base,relativePath:i.relativePath},{relativePath:o}=r,s=od(r);if(s.state==="unavailable")throw new Error(`Base content unavailable for ${o}: ${s.reason}`);return s.state==="present"?s.content:null}function od(e,t=rd){return Ev(e.relativePath),sd({projectRoot:e.projectRoot,base:e.base,relativePaths:[e.relativePath]},t).get(e.relativePath)??{state:"unavailable",reason:`Base-content lookup omitted ${e.relativePath}.`}}function sd(e,t=rd){for(let s of e.relativePaths)Ev(s);let n=[...new Set(e.relativePaths)];if(n.length===0)return new Map;let i;try{i=t.resolveCommit(e.projectRoot,e.base)}catch(s){return Zu(n,ed(s))}let r;try{r=t.readBatch({projectRoot:e.projectRoot,resolvedBase:i,relativePaths:n})}catch(s){return Zu(n,ed(s))}let o;try{o=o$(r,n)}catch(s){return Zu(n,`Malformed git cat-file batch output: ${ed(s)}`)}return new Map(n.map(s=>{let a=o.get(s)??null;return[s,a===null?{state:"absent"}:{state:"present",content:a}]}))}function ad(e,t=rd){let n=sd({projectRoot:e.projectRoot,base:e.base,relativePaths:e.preloadPaths??[]},t);return i=>(n.has(i)||n.set(i,od({projectRoot:e.projectRoot,base:e.base,relativePath:i},t)),n.get(i)??{state:"unavailable",reason:`Base-content reader omitted ${i}.`})}function Rv(e,t=e.changedFiles){let n=new Map(e.renamedFiles.map(i=>[i.to,i.from]));return[...new Set(t.map(i=>n.get(i)??i))]}function Ev(e){hn(e)}function Zu(e,t){return new Map(e.map(n=>[n,{state:"unavailable",reason:t}]))}function ed(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 o$(e,t){let n=new Map,i=0;for(let r of t){let o=e.indexOf(10,i);if(o<0)throw new Error("git cat-file batch output ended before object header");let s=e.subarray(i,o).toString("utf-8");if(i=o+1,s.endsWith(" missing")){n.set(r,null);continue}let a=/^[0-9a-f]+ ([^ ]+) (\d+)$/.exec(s);if(!a)throw new Error(`unexpected git cat-file batch header: ${s}`);let[,c,l]=a,u=Number(l);if(!Number.isFinite(u)||u<0)throw new Error(`unexpected git cat-file batch size: ${s}`);if(i+u>e.length)throw new Error("git cat-file batch output ended before blob payload");let d=e.subarray(i,i+u);n.set(r,c==="blob"?d.toString("utf-8"):null),i+=u,e[i]===10&&(i+=1)}return n}function s$(e,t,n,i){if(n.length===0)return[];let r=new Map,o=new Set;for(let a of i.renamedFiles)n.includes(a.to)&&(r.set(a.to,a),o.add(a.from));let s=i.deletedFiles;if(s.length===0)return[...r.values()].sort((a,c)=>a.to.localeCompare(c.to));for(let a of n){if(r.has(a)||!ZB(`${e}/${a}`))continue;let c=s.filter(d=>!o.has(d)).filter(d=>bv(d)===bv(a));if(c.length===0)continue;let l=nt(e,a),u=c.map(d=>({from:d,to:a,similarity:c$(r$({projectRoot:e,base:t,relativePath:d})??"",l)})).sort((d,m)=>m.similarity-d.similarity)[0];u&&u.similarity>=.45&&(r.set(a,u),o.add(u.from))}return[...r.values()].sort((a,c)=>a.to.localeCompare(c.to))}function a$(e){let t=new Set,n=new Map,i=new Set;for(let r of e.flatMap(o=>wv(o))){let[o,s,a]=r.split(" ");if(!(!o||!s)){if(o.startsWith("R")&&a){t.add(a),n.set(a,{from:s,to:a,similarity:Number(o.slice(1))/100});continue}t.add(s),o.startsWith("D")&&i.add(s)}}return{changedFiles:[...t],renamedFiles:[...n.values()],deletedFiles:[...i]}}function c$(e,t){let n=new Set(Sv(e)),i=new Set(Sv(t));if(n.size===0&&i.size===0)return 1;if(n.size===0||i.size===0)return 0;let r=0;for(let o of n)i.has(o)&&(r+=1);return 2*r/(n.size+i.size)}function Sv(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function wv(e){return e.split(`
344
- `).map(t=>t.trim()).filter(t=>t.length>0)}function l$(e,t){let n=Iv(e),i=[];for(let r of t){let o=n(r);o&&!e.isIgnored(o)&&i.push(o)}return i}function u$(e,t){let n=Iv(e),i=[];for(let r of t){let o=n(r.file);o&&!e.isIgnored(o)&&i.push({...r,file:o})}return Lv(i)}function Iv(e){let n=e.all(`SELECT relative_path FROM documents
345
- ORDER BY id`).map(r=>r.relative_path).map(r=>({path:r,normalized:hn(r)})),i=new Map;for(let r of n){let o=i.get(r.normalized);i.set(r.normalized,o===void 0||o===r.path?r.path:null)}return r=>{let o=hn(r),s=i.get(o);if(s)return s;let a=n.filter(c=>c.normalized.endsWith(o));return a.length===1?a[0].path:null}}function vv(e){let t=[],n=null;for(let i of e.split(`
346
- `)){if(i.startsWith("+++ ")){n=d$(i.slice(4).trim());continue}if(!n||!i.startsWith("@@ "))continue;let r=/@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(i);if(!r)continue;let o=Math.max(0,Number(r[1])-1),s=r[2]===void 0?1:Number(r[2]);t.push({file:n,startLine:o,endLine:Math.max(o,o+Math.max(s,1)-1)})}return t}function d$(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function Lv(e){let t=new Set,n=[];for(let i of e){let r=`${i.file}:${i.startLine}:${i.endLine}`;t.has(r)||(t.add(r),n.push(i))}return n}function m$(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(i=>cd(e.startLine,e.endLine,i.startLine,i.endLine))}function p$(e,t,n){let i=new Map,r=[],o=Pv(e),s=b$(n);for(let a of t){let c=o.get(a.file)??[];if(c.some(d=>cd(d.startLine,d.endLine,a.startLine,a.endLine)))continue;let l=s.get(a.file)??[],u=S$(l,a);if(u){let d=c.find(m=>m.startLine>=u.startLine&&m.startLine<=u.endLine);if(d){i.set(d.symbolId,d),r.push(td(a,"ast-widened"));continue}}if(l.length===0){let d=[...c].filter(m=>m.startLine<=a.startLine).sort((m,p)=>p.startLine-m.startLine||m.endLine-p.endLine)[0];if(d){i.set(d.symbolId,d),r.push(td(a,"nearest-preceding"));continue}}r.push(td(a,"unattributed"))}return{definitions:[...i.values()],notes:r}}function f$(e,t,n,i){let r=Pv(n),o=[],s=[],a=[...new Set(t.map(c=>c.relativePath))];for(let c of a){let l=i.get(c)??[];if(l.length===0)continue;let u=r.get(c)??[];for(let d of l)u.some(m=>cd(m.startLine,m.endLine,d.startLine,d.endLine))||o.push(d);o.some(d=>d.file===c)&&s.push(...g$(e,c))}return p$(t,o,s)}function g$(e,t){let n=ae(e,t);return n?n.rootNode.namedChildren.filter(h$).map(i=>({file:t,startLine:i.startPosition.row,endLine:i.endPosition.row})).filter(i=>i.endLine>=i.startLine):[]}function h$(e){return e.endPosition.row<e.startPosition.row?!1:!new Set(["import_statement","comment"]).has(e.type)}function y$(e){let t=new Map;for(let n of e)t.set(n.symbolId,n);return[...t.values()]}function Pv(e){let t=new Map;for(let n of e){let i=t.get(n.relativePath)??[];i.push(n),t.set(n.relativePath,i)}return t}function b$(e){let t=new Map;for(let n of e){let i=t.get(n.file)??[];i.push(n),t.set(n.file,i)}return t}function S$(e,t){return e.filter(n=>n.startLine<=t.startLine&&n.endLine>=t.endLine).sort((n,i)=>n.endLine-n.startLine-(i.endLine-i.startLine))[0]}function td(e,t){return{file:e.file,startLine:e.startLine,endLine:e.endLine,method:t}}function cd(e,t,n,i){return e<=i&&n<=t}function v$(e,t,n,i,r,o,s,a,c){let l=Math.max(a,o.size,s.size);if(!L$(t,l))return;let u=k(t.symbol);i.push({symbol:t.symbol,shortName:u,file:t.relativePath,startLine:t.startLine,endLine:t.endLine,fanIn:l});for(let d of c)nd(e,n,r,d,u);for(let d of o)nd(e,n,r,d,u);for(let d of s)nd(e,n,r,d,u)}function Cv(e,t,n){try{return{values:n(),status:{tier:e,state:"complete",attemptedSymbols:t}}}catch(i){return{values:new Map,status:{tier:e,state:"failed",attemptedSymbols:t,reason:x$(i)}}}}function C$(e){return["semantic-consumers","source-fallback-consumers"].map(t=>{let n=e.map(o=>o.evidenceTiers?.find(s=>s.tier===t)??{tier:t,state:"failed",attemptedSymbols:0,reason:"isolated diff-impact batch omitted its evidence-tier status"}),i=n.reduce((o,s)=>o+s.attemptedSymbols,0),r=[...new Set(n.filter(o=>o.state==="failed").map(o=>o.reason))];return r.length===0?{tier:t,state:"complete",attemptedSymbols:i}:{tier:t,state:"failed",attemptedSymbols:i,reason:r.join("; ").slice(0,500)}})}function Dv(){return[{tier:"semantic-consumers",state:"complete",attemptedSymbols:0},{tier:"source-fallback-consumers",state:"complete",attemptedSymbols:0}]}function x$(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 R$(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
347
- FROM mentions m
348
- JOIN chunks c ON m.chunk_id = c.id
349
- WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
350
- AND m.role != 1
351
- GROUP BY m.symbol_id`,...t);return new Map(n.map(i=>[i.symbol_id,i.fan_in]))}function E$(e,t,n){if(t.length===0||n.length===0)return new Map;let i=e.all(`SELECT DISTINCT m.symbol_id, ref_d.relative_path
352
- FROM mentions m
353
- JOIN chunks c ON m.chunk_id = c.id
354
- JOIN documents ref_d ON c.document_id = ref_d.id
355
- WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
356
- AND m.role != 1
357
- AND ref_d.relative_path NOT IN (${n.map(()=>"?").join(",")})
358
- ${e.pathExclusionsFor("ref_d")}`,...t,...n),r=new Map;for(let o of i){let s=r.get(o.symbol_id);s||(s=new Set,r.set(o.symbol_id,s)),s.add(o.relative_path)}return r}function nd(e,t,n,i,r){if(e.isIgnored(i)||t.has(i))return;let o=n.get(i);o||(o=new Set,n.set(i,o)),o.add(r)}function w$(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function I$(e){return!(Le(e.symbol)||e.parentTypeName!==null&&!it(e.symbol))}function L$(e,t){return it(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}var P$=5;function D$(e,t={}){let{base:n="HEAD",minContainment:i=.7,minCallees:r=3,minSiteCoverage:o=.4,maxHelpers:s=Number.POSITIVE_INFINITY,limit:a=20,scanLimit:c}=t,l=t.semantic!==!1,u=t.diffPlan??yr(e,{base:n}),d={available:u.note!==id,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),p=new Set(u.changedFiles),f=new Map(u.renamedFiles.map(R=>[R.to,R.from]));if(t.baseContentAt&&t.baseContentResultAt)throw new Error("Specify only one of baseContentAt or baseContentResultAt.");let g=t.baseContentResultAt?t.baseContentResultAt:t.baseContentAt?_$(t.baseContentAt):ad({projectRoot:e.config.projectRoot,base:n,preloadPaths:Rv(u)}),h=k$(m,p,f,g);if(h.unavailable)return d.available=!1,d.note=`Base content unavailable: ${h.unavailable.reason}`,d;if(h.definitions.length===0)return d;let b=h.definitions.slice(0,s);h.definitions.length>s&&(d.note=`helper scoring capped at ${s} of ${h.definitions.length} new symbols`);let v=m.calleeEvidenceMap(b,{semantic:l}),y=b.filter(R=>!v.incompleteSymbolIds.has(R.symbolId)&&!v.unavailableSymbolIds.has(R.symbolId)).map(R=>({def:R,callees:Oa((v.rows.get(R.symbolId)??[]).map(C=>C.symbol))}));for(let R of b)!v.incompleteSymbolIds.has(R.symbolId)&&!v.unavailableSymbolIds.has(R.symbolId)||d.skipped.push({helperShortName:k(R.symbol),helperFile:R.relativePath,reason:"compiler-resolved callee evidence is incomplete or unavailable \u2014 unsafe to score"});let E=fr(e),w,S=()=>(w??=E.calleeIndex({minCallees:Math.min(3,r),scanLimit:c,semantic:l}),w);for(let{def:R,callees:C}of y){let L=k(R.symbol);if(C.size<r){d.skipped.push({helperShortName:L,helperFile:R.relativePath,reason:`fewer than ${r} meaningful callees \u2014 too small to score`});continue}let I=S(),x=N$(C,I);if(x===0){d.skipped.push({helperShortName:L,helperFile:R.relativePath,reason:"helper callee pattern is all project-wide infrastructure \u2014 too generic to score"});continue}let D=O$(e,R.symbolId);if(D.length===0){d.skipped.push({helperShortName:L,helperFile:R.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}d.helpersChecked+=1;let _=T$({candidateIndex:I,changed:p,helperCallees:C,helperFile:R.relativePath,helperSymbol:R.symbol,minContainment:i,minSiteCoverage:o,migratedFiles:D});_.length!==0&&(_.sort((P,T)=>Tv(T.migrationScope)-Tv(P.migrationScope)||T.containment-P.containment||T.siteCoverage-P.siteCoverage||P.file.localeCompare(T.file)),d.findings.push({helperSymbol:R.symbol,helperShortName:L,helperFile:R.relativePath,helperShape:"specific-callee-cluster",helperCalleeCount:C.size,specificHelperCalleeCount:x,migratedFiles:D.sort(),leftovers:_.slice(0,P$)}))}return d.findings.sort((R,C)=>(C.leftovers[0]?.containment??0)-(R.leftovers[0]?.containment??0)||R.helperFile.localeCompare(C.helperFile)),d.findings=d.findings.slice(0,a),d}function T$(e){let t=[],n=M$(e.helperSymbol,e.helperFile,e.migratedFiles),i=new Set;for(let r of e.helperCallees)for(let o of e.candidateIndex.candidateIndexesByCallee.get(r)??[])i.add(o);for(let r of i){let o=e.candidateIndex.corpus[r];if(o.symbol===e.helperSymbol||e.changed.has(o.file)||o.callees.has(e.helperSymbol))continue;let s=RS(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=A$(n,o.symbol,o.file);t.push({symbol:o.symbol,shortName:k(o.symbol),file:o.file,...l,containment:s,siteCoverage:c,uniqueSiteCalleeCount:Math.max(0,o.callees.size-a.length),sharedCallees:a.map(k).sort()})}return t}function Tv(e){return e==="same-scope"?2:e==="unknown"?1:0}function M$(e,t,n){let i=new Set([...ld(t),...ud(re(e))]);for(let r of n)for(let o of ld(r))i.add(o);return i}function A$(e,t,n){let i=new Set([...ld(n),...ud(re(t))]);if(e.size===0||i.size===0)return{migrationScope:"unknown",migrationScopeReasons:["insufficient path/name tokens to infer migration scope"]};let r=[...i].filter(o=>e.has(o)).sort();return r.length>0?{migrationScope:"same-scope",migrationScopeReasons:[`shares migration-scope token(s): ${r.slice(0,5).join(", ")}`]}:{migrationScope:"possible-subtype",migrationScopeReasons:["no path/name tokens shared with the helper or already migrated files"]}}var F$=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 ld(e){return ud(e.replace(/\.[^.]+$/,""))}function ud(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!F$.has(t))}function N$(e,t){let n=0;for(let i of e)(t.docFreq.get(i)??0)<=t.ubiquityThreshold&&(n+=1);return n}function k$(e,t,n,i){let r=[];for(let o of e.productionCallableDefinitions({files:[...t],requireFunctionLikeSymbol:!0})){if(!t.has(o.relativePath))continue;let s=n.get(o.relativePath)??o.relativePath,a=i(s);if(a.state==="unavailable")return{definitions:[],unavailable:a};(a.state==="absent"||!new RegExp(`\\b${He(o.leaf)}\\b`).test(a.content))&&r.push(o)}return{definitions:r}}function _$(e){return t=>{let n=e(t);return n===null?{state:"absent"}:{state:"present",content:n}}}function O$(e,t){return e.all(`SELECT DISTINCT ref_d.relative_path
359
- FROM mentions m
360
- JOIN chunks c ON m.chunk_id = c.id
361
- JOIN documents ref_d ON c.document_id = ref_d.id
362
- WHERE m.symbol_id = ?
363
- AND m.role != 1
364
- ${e.pathExclusionsFor("ref_d")}`,t).map(i=>i.relative_path)}import{execFileSync as B$}from"child_process";var kv=2e3,Ka=50,$$=64,j$=8,H$=3,U$=2160*60*60,z$=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,G$=3,K$=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,q$=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function W$(e){let t=Me(e,{clearGroups:["whole-project"]});return(n,i,r)=>{let o=r??dd(n.config.projectRoot);if(!o)return null;let s=t.has(n)?t.get(n,()=>({head:"",value:null})):null;return s&&s.head===o?s.value:(t.invalidate(n),t.get(n,()=>({head:o,value:i(n.config.projectRoot,o)})).value)}}function qa(e){let t=Me(e,{clearGroups:["whole-project"]});return(n,i,r,o)=>{let s=o??dd(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(i))return c.values.get(i)??null;let l=r(n.config.projectRoot,s);return c.values.set(i,l),l}}var V$=qa("git-commit-history");function Vt(e,t={}){let n=t.historyMode??"bounded",i=t.head;return{capability:r=>J$(e,r,i),commitHistory:()=>Ao(e,n,i),fileChurn:()=>Q$(e,n,i),changeAmplification:()=>Z$(e,n,i),trackedFiles:()=>t1(e,i),fileAddRecords:()=>i1(e,n,i),coChangePairs:(r={})=>u1(e,r,n,i),coChangePairsForFiles:(r,o={})=>Bv(e,r,o,n,i),directionalCoChangePairsForFiles:(r,o={})=>d1(e,r,o,n,i)}}function Ao(e,t="bounded",n){return V$(e,br(t),(i,r)=>Y$(i,r,t),n)}function J$(e,t,n){let i=n??dd(e.config.projectRoot);return i?{slot:t,available:!0,head:i}:{slot:t,available:!1,head:null,reason:"git history is unavailable for this project"}}function dd(e){try{return pn(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function pn(e,t){return B$("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:3e4,killSignal:"SIGKILL"})}function Y$(e,t,n){let i;try{i=pn(e,["log","--no-merges","--name-only",...Wa(n),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}return{head:t,...fd(i,Ka)}}function X$(e){return z$.test(e.subject)}function Q$(e,t,n){let i=Ao(e,t,n);if(!i)return null;let r=new Map;for(let o of i.commits){let s=X$(o);for(let a of o.files){let c=r.get(a)??{changes:0,fixChanges:0,lastChangedAt:0};c.changes+=1,s&&(c.fixChanges+=1),o.timestamp>c.lastChangedAt&&(c.lastChangedAt=o.timestamp),r.set(a,c)}}return r}function Z$(e,t,n){let i=Ao(e,t,n);if(!i||i.commits.length===0)return null;let r=i.commits.map(o=>o.files.length).filter(o=>o>0).sort((o,s)=>o-s);return r.length===0?null:{medianFilesPerCommit:Mv(r,.5),p90FilesPerCommit:Mv(r,.9),commitsAnalyzed:r.length}}function Mv(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var e1=W$("git-tracked-files");function t1(e,t){return e1(e,n=>{try{let i=pn(n,["ls-files"]);return new Set(i.split(`
365
- `).map(r=>r.trim()).filter(r=>r!==""))}catch{return null}},t)}var n1=qa("git-file-adds"),Av="__git__/file-adds",Fv=xt({kind:"git-file-adds",invalidation:Je("git-file-adds"),serialize:o1,deserialize:s1});function _v(e){return Vt(e).fileAddRecords()}function i1(e,t,n){let i=br(t);return n1(e,i,(r,o)=>r1(e,r,o,t),n)}function r1(e,t,n,i){let r=Fv.read(e,Nv(i),n);if(r)return r;let o=a1(t,i);return o&&Fv.write(e,Nv(i),n,o),o}function o1(e){return JSON.stringify([...e.entries()])}function s1(e){if(!e)return null;try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=new Map;for(let i of t){if(!Array.isArray(i)||i.length!==2||typeof i[0]!="string")return null;let r=i[1];if(!r||typeof r.commitsAgo!="number"||!Number.isFinite(r.commitsAgo)||typeof r.addedAt!="number"||!Number.isFinite(r.addedAt))return null;n.set(i[0],{commitsAgo:r.commitsAgo,addedAt:r.addedAt})}return n}catch{return null}}function a1(e,t){let n;try{n=pn(e,["log","--no-merges","--find-renames","--name-status",...Wa(t),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let i=new Map,r=new Map,o=-1;for(let s of n.split("")){if(s.trim()==="")continue;o+=1;let a=s.indexOf(`
366
- `),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(`
367
- `)){let m=c1(d);if(!m)continue;if(m.status==="R"&&m.from&&m.to){let f=r.get(m.to)??new Set([m.to]);r.set(m.from,f);continue}if(m.status!=="A"||!m.to)continue;let p={commitsAgo:o,addedAt:u};i.set(m.to,p);for(let f of r.get(m.to)??[])i.set(f,p)}}return i}function c1(e){let t=e.trim().split(" "),n=t[0]??"";if(!n)return null;let i=n[0]??"";if(i==="R"){let o=t[1],s=t[2];return o&&s?{status:i,from:o,to:s}:null}let r=t[1];return r?{status:i,to:r}:null}var Ov=qa("git-co-change-pairs"),l1=qa("git-directional-co-change-pairs");function u1(e,t,n,i){let r=`all\0${br(n)}\0${md(t)}`,o=Ov(e,r,()=>{let s=Ao(e,n,i);return s?pd(s,t):null},i);return o&&[...o]}function Bv(e,t,n,i,r){if(t.size===0)return[];let o=`files\0${br(i)}\0${$v(t)}\0${md(n)}`,s=Ov(e,o,()=>{let a=Ao(e,i,r);return a?pd(a,n,t):null},r);return s&&[...s]}function d1(e,t,n,i,r){if(t.size===0)return[];let o=n.maxFilesPerCommit??Ka;if(t.size>$$)return Bv(e,t,n,i,r);let s=`directional\0${br(i)}\0${$v(t)}\0${md({...n,maxFilesPerCommit:o})}`,a=l1(e,s,(c,l)=>{let u=m1(c,l,t,o,i);return u?pd(u,n,t):null},r);return a&&[...a]}function md(e){let t=e.minTogether??4,n=e.minConfidence??.6,i=e.maxFilesPerCommit??Ka;return`${t}\0${n}\0${i}`}function $v(e){return[...e].sort().join("\0")}function pd(e,t,n){let{minTogether:i=4,minConfidence:r=.6,maxFilesPerCommit:o=Ka}=t,s=new Map,a=new Map,c=e.newestAnalyzedAt??0;for(let d of e.commits){let m=[...new Set(d.files)].sort();if(m.length>o)continue;e.newestAnalyzedAt===void 0&&d.timestamp>c&&(c=d.timestamp);let p=g1(m),f=n===void 0||m.some(g=>n.has(g));for(let g of m)s.set(g,(s.get(g)??0)+1);if(f)for(let g=0;g<m.length;g++)for(let h=g+1;h<m.length;h++){if(n&&!n.has(m[g])&&!n.has(m[h]))continue;let b=`${m[g]}\0${m[h]}`,v=a.get(b)??{together:0,focusedTogether:0,broadTogether:0,lastTogetherAt:0,timestamps:[],subjects:[]};v.together+=1,p?v.broadTogether+=1:v.focusedTogether+=1,d.timestamp>v.lastTogetherAt&&(v.lastTogetherAt=d.timestamp),v.timestamps.push(d.timestamp),v.subjects.push(d.subject),a.set(b,v)}}let l=[],u=c-U$;for(let[d,m]of a){let p=m.together;if(p<i)continue;let[f,g]=d.split("\0"),h=s.get(f)??p,b=s.get(g)??p,v=Math.max(p/h,p/b);if(v<r)continue;let y=m.broadTogether/p,E=m.timestamps.filter(w=>w>=u).length;l.push({fileA:f,fileB:g,together:p,confidence:v,changesA:h,changesB:b,focusedTogether:m.focusedTogether,broadTogether:m.broadTogether,broadCommitRatio:y,lastTogetherAt:m.lastTogetherAt,recentTogether:E,commitScope:y1(m.broadTogether,p),recency:E>0?"recent":"stale",subjectContext:b1(m.subjects)})}return l.sort((d,m)=>m.together-d.together||m.confidence-d.confidence||d.fileA.localeCompare(m.fileA)),l}function m1(e,t,n,i,r){let o;try{o=p1(e,r)}catch{return null}if(o.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:0};let s;try{s=pn(e,["log","--no-merges","--format=%H",...Wa(r),"--",...[...n].sort()])}catch{return null}let a=new Set(o.map(m=>m.hash)),c=s.split(`
368
- `).map(m=>m.trim()).filter(m=>m!==""&&a.has(m)),l=f1(e,o,i);if(c.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:l};let u;try{u=pn(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...c])}catch{return null}let d=fd(u,i);return{head:t,...d,newestAnalyzedAt:l}}function p1(e,t){return pn(e,["log","--no-merges","--format=%H%x00%ct",...Wa(t)]).split(`
369
- `).map(i=>i.trim()).filter(i=>i!=="").map(i=>{let[r,o]=i.split("\0");return{hash:r??"",timestamp:Number(o)||0}}).filter(i=>i.hash!=="")}function Wa(e){return e==="full"?[]:["-n",String(jv())]}function jv(){return gs(process.env.CODEBASEIQ_GIT_HISTORY_MAX_COMMITS)??kv}function br(e){return e==="full"?"full":`bounded:${jv()}`}function Nv(e){let t=br(e);return t===`bounded:${kv}`?Av:`${Av}:${t}`}function f1(e,t,n){for(let r=0;r<t.length;r+=20){let o=t.slice(r,r+20),s;try{s=pn(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=fd(s,n);if(a.commits.length>0)return a.commits[0].timestamp}return 0}function fd(e,t){let n=[],i=0;for(let r of e.split("")){if(r.trim()==="")continue;let o=r.indexOf(`
370
- `),s=o>=0?r.slice(0,o):r,[a,c,l]=s.split("\0");if(!a||!c)continue;let u=o>=0?r.slice(o+1).split(`
371
- `).map(d=>d.trim()).filter(d=>d!==""):[];if(u.length>t){i+=1;continue}n.push({hash:a,timestamp:Number(c)||0,subject:l??"",files:u})}return{commits:n,skippedBulkCommits:i}}function g1(e){return e.length>=j$?!0:h1(e).size>=H$}function h1(e){let t=new Set;for(let n of e){let i=n.indexOf("/");t.add(i>=0?n.slice(0,i):".")}return t}function y1(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function b1(e){let t=new Set,n=[],i=[];for(let r of e){!i.includes(r)&&i.length<G$&&i.push(r);for(let o of S1(r))t.add(o);for(let o of r.match(K$)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:i,externalIssueLabelStatus:"unavailable"}}function S1(e){let t=new Set,n=q$.exec(e)?.[1]?.toLowerCase();return n&&t.add(v1(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 v1(e){return e==="feat"?"feature":e}var Hv=/(?:^|\/)(?: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 Fo(e,t,n={}){let{minTogether:i=4,minConfidence:r=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=Vt(e,{historyMode:n.historyMode,...n.head?{head:n.head}:{}}),c=a.commitHistory(),l=t!==void 0,u=a.coChangePairs({minTogether:l?Math.min(i,2):i,minConfidence:l?0:r,maxFilesPerCommit:s});if(!c||!u)return{available:!1,commitsAnalyzed:0,findings:[]};let d=typeof n.scanLimit=="number"?u.slice(0,n.scanLimit):u,m=Oe(e),p=qv(e),f=R1(e,m,p),g=n.includeLinked===!0||l,h=[];for(let b of d){if(Hv.test(b.fileA)||Hv.test(b.fileB)||!Uv(e,b.fileA)||!Uv(e,b.fileB)||l&&!b.fileA.includes(t)&&!b.fileB.includes(t)||!l&&(V(b.fileA)==="test"||V(b.fileB)==="test"||L1(b.fileA,b.fileB)||w1(b.fileA,b.fileB)))continue;let v=f(b.fileA,b.fileB);if(!g&&v)continue;let y=C1(b.fileA,b.fileB),E=x1(b,y,v);if(h.push({...b,structurallyLinked:v,partnerClass:y.partnerClass,partnerClassReasons:y.reasons,...E?{declaredCouplingSuggestion:E}:{}}),h.length>=o)break}return{available:!0,commitsAnalyzed:c.commits.length,findings:h}}function Uv(e,t){return At(e.config.projectRoot,t)}function C1(e,t){let n=Gv(e),i=Gv(t),r=[],o=c=>{r.includes(c)||r.push(c)},s=(c,l)=>n.tags.has(c)&&i.tags.has(l)||n.tags.has(l)&&i.tags.has(c);if(s("doc","code"))return o("one side is documentation and the other is executable source"),{partnerClass:"doc-code",reasons:r};if(n.tags.has("test")||i.tags.has("test"))return o("one side is classified as a test file"),{partnerClass:"test-code",reasons:r};if(s("schema","script"))return o("schema or contract file changes with a script or generated-code path"),{partnerClass:"schema-script",reasons:r};if(s("model","view"))return o("model or state path changes with a view or component path"),{partnerClass:"model-view",reasons:r};if(s("config","code"))return o("configuration file changes with executable source"),{partnerClass:"config-code",reasons:r};let a=B1(n.tokens,i.tokens).filter(c=>!_1.has(c));return Kv(e,t)||a.length>=2?(o(Kv(e,t)?"both files live in the same directory":`files share feature tokens: ${a.slice(0,4).join(", ")}`),{partnerClass:"same-feature",reasons:r}):(o("no specific relationship pattern matched"),{partnerClass:"unknown",reasons:r})}function x1(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!k1.has(t.partnerClass))return;let i=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${$1(i)}`,files:i,reason:`${t.partnerClass} pair changed together ${e.together}x with ${Math.round(e.confidence*100)}% confidence; declare it if future edits should require both sides.`}}function R1(e,t=Oe(e),n=qv(e)){return(i,r)=>P1(t,n,i,r)}var E1=/(?:^|\/)(?:locales|i18n)\//i;function zv(e){return E1.test(e)}function w1(e,t){return zv(e)&&zv(t)?!0:I1(e,t)}function I1(e,t){if(!e.endsWith(".json")||!t.endsWith(".json"))return!1;let n=e.lastIndexOf("/"),i=t.lastIndexOf("/");if(n<0||i<0)return!1;let r=e.slice(0,n),o=t.slice(0,i);if(r===o)return!1;let s=e.slice(n+1),a=t.slice(i+1);if(s!==a)return!1;let c=r.lastIndexOf("/"),l=o.lastIndexOf("/"),u=c>=0?r.slice(0,c):"",d=l>=0?o.slice(0,l):"";return u===d}function L1(e,t){let n=e.lastIndexOf("/"),i=t.lastIndexOf("/");if(e.slice(0,n)!==t.slice(0,i))return!1;let r=e.slice(n+1).split(".")[0],o=t.slice(i+1).split(".")[0];return r!==""&&r===o}function qv(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function P1(e,t,n,i){return e.get(n)?.has(i)===!0||e.get(i)?.has(n)===!0?!0:t.some(r=>r.has(n)&&r.has(i))}var D1=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,T1=/(?:^|\/)(?:\.[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,M1=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,A1=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,F1=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,N1=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,k1=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),_1=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 Gv(e){let t=e.replace(/\\/g,"/"),n=new Set;return D1.test(t)&&n.add("doc"),T1.test(t)&&n.add("config"),M1.test(t)&&n.add("schema"),A1.test(t)&&n.add("script"),F1.test(t)&&n.add("model"),N1.test(t)&&n.add("view"),V(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:O1(t)}}function Kv(e,t){let n=e.lastIndexOf("/"),i=t.lastIndexOf("/"),r=n>=0?e.slice(0,n):"",o=i>=0?t.slice(0,i):"";return r!==""&&r===o}function O1(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 B1(e,t){let n=new Set(t);return[...new Set(e.filter(i=>n.has(i)))].sort()}function $1(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}function Ya(e,t){let n=j1(e,t)??H1(e,t)??U1(e,t)??z1(e,t);return G1(e,n,t)}function j1(e,t){let n=-1,i=null;for(let r=0;r<=t;r+=1){let o=gd(e[r]??"");o&&(i===null?(i=o,n=r):o===i&&(i=null,n=-1))}if(i===null||n<0)return null;for(let r=t+1;r<e.length;r+=1)if(gd(e[r]??"")===i)return{start:n,end:r+1};return{start:n,end:e.length}}function gd(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function H1(e,t){if(!Va(e[t]??""))return null;let n=t;for(;n>0&&Va(e[n-1]??"");)n-=1;let i=t+1;for(;i<e.length&&Va(e[i]??"");)i+=1;return{start:n,end:i}}function Va(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function U1(e,t){let n=t;for(;n>=0;){let o=e[n]??"";if(Ja(o)!==null)break;if(hd(o)!==null)return null;n-=1}if(n<0)return null;let i=Ja(e[n]??"");if(i===null)return null;let r=n+1;for(;r<e.length;){let o=e[r]??"",s=Ja(o);if(s!==null){if(s<=i)break;r+=1;continue}if(hd(o)!==null)break;r+=1}return{start:n,end:r}}function Ja(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function z1(e,t){let n=e[t]??"";if(Vv(n)||n.trim().length===0)return{start:t,end:t+1};let i=t;for(;i>0&&Wv(e[i-1]??"");)i-=1;let r=t+1;for(;r<e.length&&Wv(e[r]??"");)r+=1;return{start:i,end:r}}function Wv(e){return hd(e)===null}function hd(e){return e.trim().length===0?"blank":Vv(e)?"heading":gd(e)?"fence":Va(e)?"table":Ja(e)!==null?"list":null}function Vv(e){return/^#{1,6}\s+/.test(e.trim())}function G1(e,t,n){let{start:i,end:r}=t;if(r-i>40){let s=Math.floor(20);i=Math.max(i,n-s),r=Math.min(r,i+40),i=Math.max(t.start,r-40)}let o=e.slice(i,r).join(`
372
- `).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}function Ai(e,t){return t.filter(n=>e.includes(n))}var K1=/<!--\s*codebaseiq:\s*snapshot\s*-->/i;function Jv(e,t){if((e.config.docs?.snapshotPaths??[]).some(r=>Qn(r,t)))return!0;let i=se(e,t);return i.length>0&&K1.test(i)}var Yv={classifyCitation:W1,citationContexts:V1,citationKindLabel:Y1,citationRemediation:X1,referenceTargets:Q1,hasLineAnchoredCitation:q1};function q1(e){return e.some(t=>(t.lineReferences?.length??0)>0)}function W1(e){let t=e.join(`
373
- `).toLowerCase(),n=[],i=Ai(t,[".codebaseiq","declaredcouplings","suppression","suppressions","config","configuration","json"]);if(i.length>0)return n.push(`configuration/example terms near citation: ${i.join(", ")}`),{citationKind:"configuration-example",actionTier:"support",reasons:n};let r=Ai(t,["accepted","intentional","intentionally","retained","historical"]);if(r.length>0)return n.push(`intentional-record terms near citation: ${r.join(", ")}`),{citationKind:"intentional-record",actionTier:"support",reasons:n};let o=Ai(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 V1(e,t,n){let i=se(e,t);if(!i&&!At(e.config.projectRoot,t))return[];let r=i.split(/\r?\n/),o=n.flatMap(J1),s=[];for(let a=0;a<r.length;a+=1){let c=r[a]??"";o.some(l=>c.includes(l))&&s.push(Ya(r,a))}return s}function J1(e){let t=e.split("/");return[e,`./${e}`,t.slice(-3).join("/"),t.slice(-2).join("/")].filter((n,i,r)=>n.length>0&&r.indexOf(n)===i)}function Y1(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 X1(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 Q1(e,t,n){let i=Ua(n),r=new Set;for(let o of t)Z1(e,o,i.get(o)??[])&&r.add(o);return r}function Z1(e,t,n){if(!ej.test(t)||!At(e.config.projectRoot,t))return!0;if(n.length===0)return!1;let i=nt(e.config.projectRoot,t,{inputKind:"changed source file"}).split(/\r?\n/),r=tj(i);for(let o of n)for(let s=o.startLine;s<=o.endLine;s+=1)if((i[s]??"").trim()!==""&&!r.has(s))return!0;return!1}var ej=/\.(?:[cm]?[jt]sx?)$/i;function tj(e){let t=new Set,n=!1;for(let i=0;i<e.length;i+=1){let r=e[i].trim();!n&&nj(r)&&(n=!0),n&&(t.add(i),r.endsWith(";")&&(n=!1))}return t}function nj(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}var Xv=xt({kind:"doc-path-evidence",invalidation:Je("doc-path-evidence"),serialize:hj,deserialize:yj}),No=/\.(?:md|mdx|rst|txt)$/i;function ij(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var rj=3,oj=/([A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6})(?::([1-9][0-9]*))?\b/g;function sj(e,t={}){let{doc:n,limit:i=20,minCoupling:r=rj,includeSnapshotExcluded:o=!1}=t,s=uj(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&&!dj(e,c)||n!==void 0&&!At(e.config.projectRoot,c))continue;let l=Jv(e,c);if(l&&!o)continue;let{value:u,estimated:d}=aj(e,c,s.changeTimes.get(c)),m=cj(e,c),p=new Map,{resolved:f,broken:g,citations:h}=pj(e,c,s.tracked,s.trackedBySuffix,s.everSeenInHistory),b=new Map(h.map(y=>[y.file,y]));for(let y of f){if(y===c||No.test(y))continue;let E=(s.changeTimes.get(y)??[]).filter(S=>S>u).length;if(E===0)continue;let w=b.get(y);p.set(y,{file:y,evidence:"reference",coChanges:0,changesSinceDocUpdate:E,...yd("reference",m,w?.contexts),citationContexts:w?.contexts,citedLines:w?.lineReferences})}for(let[y,E]of s.coupling.get(c)??[]){if(E<r||!s.tracked.has(y))continue;let w=(s.changeTimes.get(y)??[]).filter(R=>R>u).length;if(w===0)continue;let S=p.get(y);S?(S.evidence="both",S.coChanges=E,Object.assign(S,yd("both",m,S.citationContexts))):p.set(y,{file:y,evidence:"co-change",coChanges:E,changesSinceDocUpdate:w,...yd("co-change",m)})}if(p.size===0&&g.length===0)continue;let v=[...p.values()].sort((y,E)=>E.changesSinceDocUpdate-y.changesSinceDocUpdate);a.push({doc:c,docLastChangedAt:u,staleness:v.reduce((y,E)=>y+E.changesSinceDocUpdate,0)+g.length*10,subjects:v.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,i)}}function aj(e,t,n){if(n&&n.length>0)return{value:Math.max(...n),estimated:!1};try{return{value:Math.floor(_m(e.config.projectRoot,t).mtimeMs/1e3),estimated:!0}}catch(i){if(At(e.config.projectRoot,t))throw i;return{value:0,estimated:!1}}}function cj(e,t){let n=se(e,t).slice(0,6e3);if(!n)return{docIntent:"unknown",reasons:["doc text unavailable"]};let i=`${t}
374
- ${n}`.toLowerCase(),r=Ai(i,["historical note","historical record","history note","retrospective","postmortem","post-mortem","archived","archive","previously","legacy","recorded","record of","snapshot","as of","migration note","decision record"]);if(r.length>0)return{docIntent:"historical-note",reasons:[`historical-note terms: ${r.join(", ")}`]};let o=Ai(i,["current","standard","standards","must","should","policy","guide","guidance","workflow","contract","invariant","source of truth"]);return o.length>0?{docIntent:"current-guidance",reasons:[`current-guidance terms: ${o.join(", ")}`]}:{docIntent:"unknown",reasons:["no current-guidance or historical-note markers found"]}}function yd(e,t,n=[]){let i=e==="co-change"||n.length===0?null:Yv.classifyCitation(n);return{actionTier:lj(e,t.docIntent,i?.actionTier),docIntent:t.docIntent,docIntentReasons:t.reasons,...i?{citationKind:i.citationKind,citationKindReasons:i.reasons}:{}}}function lj(e,t,n){return t==="historical-note"?"support":n||(e==="co-change"?"signal":"direct")}function uj(e,t){let n=Vt(e,{historyMode:t}),i=n.commitHistory();if(!i)return null;let r=n.trackedFiles()??new Set,o=new Map,s=new Map,a=new Set;for(let c of i.commits){let l=[...new Set(c.files)],u=l.filter(m=>No.test(m)),d=l.filter(m=>!No.test(m));for(let m of l){a.add(m);let p=o.get(m)??[];p.push(c.timestamp),o.set(m,p)}for(let m of u){let p=s.get(m);p||(p=new Map,s.set(m,p));for(let f of d)p.set(f,(p.get(f)??0)+1)}}return{changeTimes:o,coupling:s,docFiles:[...r].filter(c=>No.test(c)),everSeenInHistory:a,historyCommitCount:i.commits.length,tracked:r,trackedBySuffix:mj(r)}}function dj(e,t){return No.test(t)&&!ij(t)&&At(e.config.projectRoot,t)}function mj(e){let t=new Map;for(let n of e){let i=n.split("/");for(let r of[2,3]){if(i.length<r)continue;let o=i.slice(-r).join("/"),s=t.get(o)??[];s.push(n),t.set(o,s)}}return t}function pj(e,t,n,i,r){let o=new Set,s=new Set,a=fj(e,t);if(!a)return{resolved:o,broken:[],citations:[]};let c=a.candidates,l=a.contextsByCandidate,u=a.lineReferencesByCandidate,d=new Map,m=new Map,p=(f,g)=>{let h=l.get(g);if(h&&h.length>0){let v=d.get(f)??[];v.push(...h),d.set(f,Qv(v).slice(0,3))}let b=u.get(g);b&&b.length>0&&m.set(f,bd([...m.get(f)??[],...b]))};for(let f of c){if(n.has(f)){o.add(f),p(f,f);continue}let g=i.get(f);if(g&&g.length===1){o.add(g[0]),p(g[0],f);continue}g&&g.length>1||r.has(f)&&s.add(f)}return{resolved:o,broken:[...s],citations:[...d].map(([f,g])=>({file:f,contexts:g,lineReferences:m.get(f)}))}}function fj(e,t,n){let i=n;if(i===void 0&&(i=se(e,t),!i&&!At(e.config.projectRoot,t)))return null;let r=Ft(e,t,i),o=Xv.read(e,t,r);if(o)return o;let s=gj(i);return Xv.write(e,t,r,s),s}function gj(e){let t=e.split(/\r?\n/),n=new Set,i=new Map,r=new Map;for(let o=0;o<t.length;o+=1){let s=t[o]??"";for(let a of s.matchAll(oj)){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)&&r.set(c,bd([...r.get(c)??[],l]));let u=Ya(t,o);if(u.length===0)continue;let d=i.get(c)??[];d.push(u),i.set(c,Qv(d).slice(0,3))}}return{candidates:[...n],contextsByCandidate:i,lineReferencesByCandidate:r}}function hj(e){let t={candidates:e.candidates,contextsByCandidate:[...e.contextsByCandidate.entries()],lineReferencesByCandidate:[...e.lineReferencesByCandidate.entries()]};return JSON.stringify(t)}function yj(e){try{let t=JSON.parse(e);if(!Gm(t))return null;let n=Nc(t.candidates),i=Sj(t.contextsByCandidate),r=bj(t.lineReferencesByCandidate);return!n||!i?null:{candidates:n,contextsByCandidate:new Map(i),lineReferencesByCandidate:new Map(r??[])}}catch{return null}}function bj(e){if(e===void 0)return[];if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string"||!Array.isArray(n[1]))return null;let i=[];for(let r of n[1]){if(typeof r!="number"||!Number.isSafeInteger(r))return null;i.push(r)}t.push([n[0],bd(i)])}return t}function Sj(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string")return null;let i=Nc(n[1]);if(!i)return null;t.push([n[0],i])}return t}function Qv(e){let t=[];for(let n of new Set(e))t.some(i=>vj(i,n))||t.push(n);return t}function bd(e){return[...new Set(e)].sort((t,n)=>t-n)}function vj(e,t){if(e===t)return!0;let n=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),i=t.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),r=Math.min(n.length,i.length);if(r===0)return!1;if(r<3)return e.includes(t)||t.includes(e);let o=new Set(i),s=n.filter(a=>o.has(a)).length;return s>=3&&s/r>=.6}import{createHash as Cj}from"crypto";var xj=3;function ko(e,t={}){let{scope:n,maxLoc:i=15,minLoc:r=xj,limit:o,scanLimit:s}=t,a=_v(e),c=Rj(e,{scope:n,maxLoc:i,scanLimit:s}).map(u=>Ej(e,u,a,r)).filter(u=>u!==null),l=tC(c);return o?l.slice(0,o):l}function eC(e){let t=fn(e);return bn(t).replace(/\s+/g,"")}function tC(e){let t=new Map;for(let i of e){if(i.normalizedBody.length<8)continue;let r=Ij(i.normalizedBody),o=t.get(r)??[];o.push(i),t.set(r,o)}let n=[];for(let[i,r]of t){let o=new Set(r.map(a=>a.file));if(r.length<2||o.size<2)continue;let s=[...r].sort(Lj).map(({normalizedBody:a,...c})=>c);n.push({hash:i,canonical:s[0],functions:s})}return n.sort((i,r)=>{let o=r.functions.length-i.functions.length;if(o!==0)return o;let s=Zv(r)-Zv(i);return s!==0?s:i.canonical.file.localeCompare(r.canonical.file)}),n}function Rj(e,t){let n=ze(e,{scope:t.scope}).filter(i=>i.isFunctionLike&&!e.isIgnored(i.relativePath)).filter(i=>!os(e,i.relativePath,i.startLine,"similar")).filter(i=>de(i)<=t.maxLoc);return n.sort((i,r)=>de(r)-de(i)||i.relativePath.localeCompare(r.relativePath)),Fe(n,t.scanLimit)}function Ej(e,t,n,i){let r=Jt(e,t);if(!r||wj(r)<i)return null;let o=Sd(e,t);return o?{symbol:t.symbol,shortName:k(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 Sd(e,t){let n=Jt(e,t);return n&&eC(n)||null}function Jt(e,t){let n=ie(e,t.relativePath);return n.length===0?null:n.slice(t.startLine,t.endLine+1).join(`
375
- `)}function fn(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(t>=0&&n>t)return e.slice(t+1,n);let i=e.indexOf("=>");return i>=0?e.slice(i+2).replace(/;+\s*$/,""):e}function wj(e){return fn(e).split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0).length}function Ij(e){return Cj("sha256").update(e).digest("hex").slice(0,16)}function Lj(e,t){let n=e.ageCommits??-1;return(t.ageCommits??-1)-n||e.file.localeCompare(t.file)||e.startLine-t.startLine}function Zv(e){return e.functions.reduce((t,n)=>t+n.loc,0)}var Pj=new Set(en());function Dj(e,t={}){let{includeHomonyms:n=!1,limit:i}=t,r=Xa(e,t).filter(o=>o.relationship==="divergent"||n&&o.relationship==="homonym");return i?r.slice(0,i):r}function Xa(e,t={}){let{scope:n,minSimilarity:i=.3,scanLimit:r}=t,o=Aj(e,{scope:n,scanLimit:r});return rC(o,{minSimilarity:i,isDelegatePair:eH(e)}).filter(s=>!s.members.some(a=>os(e,a.file,a.startLine,"twin")))}function rC(e,t={}){let n=t.minSimilarity??.3,i=t.isDelegatePair,r=e.filter(l=>!dC(l.leaf)&&!zj(l.leaf)&&V(l.file)!=="test"&&!at(l.symbol)&&!sC(l.symbol)&&!aC(l.symbol,l.leaf)),{recordsByLeaf:o,recordOrder:s}=$("twin-drift.group-by-leaf",()=>Tj(r),()=>({records:r.length})),a=$("twin-drift.cluster-leaf-names",()=>oC([...o.keys()]),()=>({leaves:o.size}));return $("twin-drift.compare-clusters",()=>{let l=[];for(let u of a){let d=Mj(u,o,s);if(d.length<2||new Set(d.map(v=>v.file)).size<2)continue;let m=null,p=!1,f=!1,g=new Set;for(let v=0;v<d.length;v+=1)for(let y=v+1;y<d.length;y+=1){let E=d[v],w=d[y];if(E.file===w.file||!Wj(E,w)||i?.(E,w,d)||i?.(w,E,d))continue;if(p=!0,g.add(E.symbol),g.add(w.symbol),E.normalizedBody===w.normalizedBody){f=!0;continue}let S=$j(E.tokens,w.tokens);(!m||S>m.similarity)&&(m={a:E,b:w,similarity:S})}if(!p)continue;let h=d.filter(v=>g.has(v.symbol)).sort((v,y)=>v.file.localeCompare(y.file)||v.startLine-y.startLine).map(Bj);if(!m){l.push({leaf:iC(u),relationship:f?"identical":"homonym",maxDivergence:0,members:h});continue}let b=m.similarity>=n?"divergent":"homonym";l.push({leaf:iC(u),relationship:b,maxDivergence:Math.round((1-m.similarity)*1e3)/1e3,members:h,...b==="divergent"?{firstDivergentTokens:jj(m.a.tokens,m.b.tokens)}:{}})}return l},()=>({clusters:a.length,records:r.length})).sort((l,u)=>u.members.length-l.members.length||u.maxDivergence-l.maxDivergence||l.leaf.localeCompare(u.leaf))}function Tj(e){let t=new Map,n=new Map;for(let[i,r]of e.entries()){let o=t.get(r.leaf)??[];o.push(r),t.set(r.leaf,o),n.set(r,i)}return{recordsByLeaf:t,recordOrder:n}}function Mj(e,t,n){let i=[...e].flatMap(r=>t.get(r)??[]);return e.size>1&&i.sort((r,o)=>(n.get(r)??0)-(n.get(o)??0)),i}function Aj(e,t){let n=$("twin-drift.load-definitions",()=>ze(e,{scope:t.scope}).filter(o=>Fj(o)&&!e.isIgnored(o.relativePath)).filter(o=>!Qi(o.relativePath)));$("twin-drift.sort-definitions",()=>n.sort((o,s)=>o.relativePath.localeCompare(s.relativePath)||o.startLine-s.startLine),()=>({definitions:n.length}));let i=Fe(n,t.scanLimit),r=$("twin-drift.select-candidates",()=>Nj(i),()=>({scanned:i.length}));return $("twin-drift.build-records",()=>{let o=[];for(let s of r){let a=kj(e,s);a&&o.push(a)}return o},()=>({candidates:r.length,scanned:i.length}))}function Fj(e){return e.isFunctionLike?e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&Pj.has(e.kind):!0:!1}function Nj(e){let t=e.filter(o=>o.leaf&&!dC(o.leaf)&&!at(o.symbol)&&!sC(o.symbol)&&!aC(o.symbol,o.leaf)),n=new Map;for(let o of t){let s=n.get(o.leaf)??[];s.push(o),n.set(o.leaf,s)}let i=oC([...n.keys()]),r=new Set;for(let o of i){let s=[...o].flatMap(a=>n.get(a)??[]);if(!(s.length<2)&&!(new Set(s.map(a=>a.relativePath)).size<2)&&!s.every(a=>V(a.relativePath)==="test"))for(let a of s)r.add(a)}return e.filter(o=>r.has(o))}function kj(e,t){if(!t.leaf)return null;let n=Jt(e,t);if(!n||!it(t.symbol)&&!_j(n,t.leaf))return null;let i=bn(fn(n)),r=i.replace(/\s+/g,"");if(!r||r.length<8)return null;let o=i.match(Oj)??[];return o.length===0?null:{leaf:t.leaf,symbol:t.symbol,shortName:k(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:de(t),normalizedBody:r,tokens:o,isThinForwarder:lC(i)}}function _j(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 Oj=/[A-Za-z_$][A-Za-z0-9_$]*|\d+(?:\.\d+)?|[^\sA-Za-z0-9_$]/g;function Bj(e){return{symbol:e.symbol,shortName:e.shortName,file:e.file,startLine:e.startLine,endLine:e.endLine,loc:e.loc}}function $j(e,t){let n=new Set(e),i=new Set(t);if(n.size===0&&i.size===0)return 1;if(n.size===0||i.size===0)return 0;let r=0;for(let s of n)i.has(s)&&(r+=1);let o=n.size+i.size-r;return o===0?0:r/o}function jj(e,t){let n=Math.min(e.length,t.length),i=0;for(;i<n&&e[i]===t[i];)i+=1;let r=e.slice(i,i+6).join(" "),o=t.slice(i,i+6).join(" ");return!r&&!o?"(bodies differ only in trailing length)":`A: ${r||"(end)"} | B: ${o||"(end)"}`}function oC(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},i=(s,a)=>{let c=n(s),l=n(a);c!==l&&t.set(c,l)},r=new Map;for(let s of e){let a=s.slice(0,2).toLowerCase(),c=r.get(a)??[];c.push(s),r.set(a,c)}for(let s of r.values())for(let a=0;a<s.length;a+=1)for(let c=a+1;c<s.length;c+=1)Hj(s[a],s[c])&&i(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 Hj(e,t){return e===t||e.toLowerCase()===t.toLowerCase()?!0:e.length<8||t.length<8||Math.abs(e.length-t.length)>2||Uj(e.toLowerCase(),t.toLowerCase())/Math.max(e.length,t.length)<.8?!1:Vj(e.toLowerCase(),t.toLowerCase(),2)}function Uj(e,t){let n=Math.min(e.length,t.length),i=0;for(;i<n&&e[i]===t[i];)i+=1;return i}function zj(e){return/^[A-Z][A-Z0-9_]*$/.test(e)||/^__[^_].*__$/.test(e)||Gj.has(e.toLowerCase())}var Gj=new Set(["main","row"]),Kj=new Set(["app","component","components","feature","features","impl","index","lib","route","routes","shared","src","tsx","typescript","ui"]);function sC(e){return e.startsWith("rust-analyzer ")&&/\/(?:tests?|benches?)\//.test(e)}var qj=new Set(["default","new","reset"]);function aC(e,t){return e.startsWith("rust-analyzer ")&&qj.has(t.toLowerCase())}function Wj(e,t){if(e.leaf.toLowerCase()!==t.leaf.toLowerCase()||e.leaf.length>4)return!0;let n=nC(e);return[...nC(t)].some(i=>n.has(i))}function nC(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&&!Kj.has(n)))}function Vj(e,t,n){if(Math.abs(e.length-t.length)>n)return!1;let i=Array.from({length:t.length+1},(r,o)=>o);for(let r=1;r<=e.length;r+=1){let o=[r],s=o[0];for(let a=1;a<=t.length;a+=1){let c=e[r-1]===t[a-1]?0:1,l=Math.min(i[a]+1,o[a-1]+1,i[a-1]+c);o.push(l),s=Math.min(s,l)}if(s>n)return!1;i=o}return i[t.length]<=n}function cC(e){return lC(bn(fn(e)))}function lC(e){let t=e.trim();if(!t||Jj.test(t))return!1;let n=Qj(t);return n.length===0||n.length>2?!1:Xj(n[n.length-1])}var Jj=/\b(?:if|else|for|while|switch|try|catch|do)\b/,Yj=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^[\]]*\])*\((?:[^()]|\([^()]*\))*\)$/;function Xj(e){let t=e.trim().replace(/^return\s+/,"").replace(/^await\s+/,"").replace(/;\s*$/,"").trim();return Yj.test(t)}function Qj(e){let t=[],n=0,i="";for(let r of e){if(r==="("||r==="["||r==="{"?n+=1:(r===")"||r==="]"||r==="}")&&(n=Math.max(0,n-1)),r===";"&&n===0){t.push(i),i="";continue}i+=r}return i.trim()&&t.push(i),t.map(r=>r.trim()).filter(r=>r.length>0)}var Zj=3;function eH(e){let t=new Map;return(n,i,r)=>{if(!n.isThinForwarder)return!1;let o=`${n.symbol}\0${i.symbol}`,s=t.get(o);if(s!==void 0)return s;let a=uC(e,n,i,r,Zj,new Set);return t.set(o,a),a}}function uC(e,t,n,i,r,o){if(r<=0||o.has(t.symbol)||(o.add(t.symbol),(Xt(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=>Mt(c,n.file)))return!0;for(let c of i)if(!(c.symbol===t.symbol||c.symbol===n.symbol||!c.isThinForwarder)&&[...a].some(l=>Mt(l,c.file))&&uC(e,c,n,i,r-1,o))return!0;return!1}function dC(e){return e.startsWith("<")&&e.endsWith(">")}function iC(e){return[...e].sort()[0]}import{dirname as gH,isAbsolute as hH,relative as yH,resolve as bH}from"path";import{basename as mC,extname as pC}from"path";function Qa(e,t,n,i,r,o){let s=new Set;nH(e,t,n,i)&&s.add(r);for(let a of o)a.value&&tH(s,a.label,a.value);return[...s].slice(0,6)}function tH(e,t,n){let i=iH(n);t.endsWith("name")&&rH(i)&&e.add(`${t} has type-guard boundary shape`);for(let r of i){let o=oH.get(r);o&&e.add(`${t} has ${o} term: ${r}`)}}function nH(e,t,n,i){if(n<=0)return!1;let r=ie(e,t);if(r.length===0)return!1;for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(r[o]??"").trim();if(s!==""){if(is(s)===i)return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function iH(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 rH(e){return e.some(t=>sH.has(t))&&e.some(t=>aH.has(t))}var oH=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"]]),sH=new Set(["can","has","is","should"]),aH=new Set(["access","api","auth","collision","expired","input","keyboard","overlap","permission","permissions","policy","projectile","response","route","routes","scope"]);function _o(e,t){let{scope:n,maxLoc:i=15,limit:r=30,scanLimit:o}=t??{},s=new U(e);return $t({candidates:()=>fH(e,s,n,i),orderCandidates:ua,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:cH(e,a,c.rows.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:r})}function cH(e,t,n){let i=pH(n);if(i.size!==1||!Vm(e,t.relativePath,t.startLine,t.endLine))return null;let[,r]=[...i.entries()][0],o=lH(e,t,r),s=dH(e,t),a=o.length>0||s.length>0?"signal":"direct";return{symbol:t.symbol,shortName:k(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:de(t),forwardsTo:r.symbol,forwardsToShort:k(r.symbol),forwardsToFile:r.file,actionTier:a,boundaryEvidence:o,publicFacadeEvidence:s,recommendation:uH(a,o,s)}}function lH(e,t,n){return Qa(e,t.relativePath,t.startLine,"passthrough","explicit ignore-passthrough comment",[{label:"passthrough name",value:k(t.symbol)},{label:"callee name",value:k(n.symbol)},{label:"passthrough module",value:mC(t.relativePath,pC(t.relativePath))},{label:"callee module",value:mC(n.file,pC(n.file))}])}function uH(e,t,n){if(e==="signal"){if(n.length>0)return`Review the public API before inlining; public-facade evidence: ${n.slice(0,2).join("; ")}.`;let i=t.filter(mH);return i.length>0?`Review the public API before inlining; public-surface evidence: ${i.slice(0,2).join("; ")}.`:`Review the boundary before inlining; boundary evidence: ${t.slice(0,2).join("; ")}.`}return"Inline or remove this passthrough unless an external API or runtime registration depends on the forwarding name."}function dH(e,t){return Rt(e,t)?wn(e,t.relativePath)?["exported passthrough is declared on the package public surface"]:Ue(e,t.symbol,t.relativePath)?["exported passthrough matches configured or framework public entry surface"]:[]:[]}function mH(e){return e.includes("public surface")}function pH(e){let t=e.some(i=>ke(i.symbol))?e.filter(i=>ke(i.symbol)):e,n=new Map;for(let i of t)n.has(i.symbol)||n.set(i.symbol,i);return n}function fH(e,t,n,i){return t.productionCallableDefinitions({scope:n,minLoc:3,maxLoc:i,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0}).filter(r=>!ss(e,r))}var SH=new Set(en());function vH(e,t){return`tests/generated/twin-ab/${fC(e)}-vs-${fC(t)}.test.ts`}function fC(e){return(e.split(/[/#]/).pop()||e).replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"symbol"}function CH(e,t,n,i){let{refA:r,refB:o,outFile:s}=typeof t=="string"?{refA:t,refB:n,outFile:i}:t;if(typeof r!="string"||typeof o!="string"||typeof s!="string")throw new TypeError("twinAb requires refA, refB, and outFile.");if(!hH(s))throw new TypeError("twinAb outFile must be an absolute path.");let a=gC(e,r);if(!a.ok)return a;let c=gC(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=RH(a.symbol,c.symbol,e.config.projectRoot,s,l);return{ok:!0,a:a.symbol,b:c.symbol,signatureCompatible:l,testSource:u}}function gC(e,t){let i=rt(e,t).match;if(!i)return{ok:!1,reason:`${t} does not resolve to an indexed symbol.`};let o=e.get("SELECT kind FROM global_symbols WHERE id = ?",i.symbolId)?.kind??null;if(!(o!==null?SH.has(o):ke(i.symbol)))return{ok:!1,reason:`${t} resolves to ${k(i.symbol)}${o!==null?` with SCIP kind ${Ar(o)}`:""} \u2014 twin-ab compares call outputs, so both referents must be functions or methods.`};if(!Rt(e,i))return{ok:!1,reason:`${t} (${k(i.symbol)} at ${i.relativePath}:${i.startLine+1}) is not exported \u2014 twin-ab needs an importable named binding for both twins.`};let a=e.get("SELECT documentation FROM global_symbols WHERE id = ?",i.symbolId),c=zi(Gi(a?.documentation??null));return{ok:!0,symbol:{ref:t,symbol:i.symbol,shortName:re(i.symbol)||k(i.symbol),file:i.relativePath,startLine:i.startLine,signature:c,paramCount:c?xH(c):null}}}function xH(e){let t=e.indexOf("(");if(t===-1)return null;let n=0,i=-1;for(let a=t;a<e.length;a+=1){let c=e[a];if(c==="(")n+=1;else if(c===")"&&(n-=1,n===0)){i=a;break}}if(i===-1)return null;let r=e.slice(t+1,i).trim();if(!r)return 0;let o=1,s=0;for(let a of r)a==="("||a==="["||a==="{"?s+=1:a===")"||a==="]"||a==="}"?s=Math.max(0,s-1):a===","&&s===0&&(o+=1);return o}function hC(e,t,n){let i=gH(t),r=bH(e,n),s=yH(i,r).replace(/\\/g,"/").replace(/\.tsx?$/,".js");return s.startsWith(".")?s:`./${s}`}function RH(e,t,n,i,r){let o=hC(n,i,e.file),s=hC(n,i,t.file),a=r===null?"Signature comparison: unknown (one or both signatures unavailable in the index) \u2014 check by hand.":r?"Signature comparison: param counts match.":"Signature comparison: param counts DIFFER \u2014 twins may not be directly comparable; check by hand.";return`/**
376
- * Generated by 'codebaseiq twin-ab'. Cleanup integrity scenario.
377
- * ("cross-examine same-concept twins"): where one concept is computed in
378
- * more than one place, feed both the same input and require the same
379
- * answer. Disagreement between twins means at least one is wrong \u2014
380
- * determine which before consolidating.
381
- *
382
- * Twin A: ${e.shortName} (${e.file}:${e.startLine+1})
383
- * ${e.signature??"(signature unavailable)"}
384
- * Twin B: ${t.shortName} (${t.file}:${t.startLine+1})
385
- * ${t.signature??"(signature unavailable)"}
386
- * ${a}
387
- *
388
- * Fill in the TODO input table below with inputs both twins should agree
389
- * on, then run this file with vitest.
390
- */
391
- import { describe, expect, it } from 'vitest';
392
- import { ${e.shortName} as twinA } from '${o}';
393
- import { ${t.shortName} as twinB } from '${s}';
394
-
395
- // TODO: fill in shared inputs both twins should agree on \u2014 one arg array per call.
396
- const inputs: any[][] = [
397
- // [/* arg1, arg2, ... */],
398
- ];
399
-
400
- // Cast to a variadic signature so the input table can hold any arg shape \u2014
401
- // the real twins have fixed, non-rest parameter lists, and TS rejects
402
- // spreading a generic args array into those (TS2556) even when the array
403
- // itself is 'any'; casting the callee's signature, not the args, satisfies
404
- // the checker without weakening the twins' real exported types elsewhere.
405
- const callA = twinA as (...callArgs: any[]) => any;
406
- const callB = twinB as (...callArgs: any[]) => any;
407
-
408
- describe.skipIf(inputs.length === 0)('twin-ab: ${e.shortName} vs ${t.shortName}', () => {
409
- it.each(inputs)('agrees on input %#', (...args) => {
410
- expect(callA(...args)).toEqual(callB(...args));
411
- });
412
- });
413
- `}var yC={caller:3,"entry-surface":2,rooted:1},EH=/not\s*yet\s*implement|not\s*implement|unimplement|\bnyi\b|\btodo\b|\bstub\b|not\s*supported|coming\s*soon/i,wH=/^throw\s+new\s+[\w.]*Error\s*\(([\s\S]*)\)\s*;?$/,IH=/^return(\s+(null|undefined|false|0|''|""|``|\[\]|\{\}))?\s*;?$/,LH=/\/\/\s*TODO\b|\/\*\s*TODO\b/i,PH=/(?:=>|\))\s*(?::\s*[^{;=]+)?\s*\{\s*\}\s*;?\s*$/;function DH(e,t={}){let{scope:n,limit:i=30,scanLimit:r,semantic:o=!0}=t,s=new U(e),a=Fe(s.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),r),c=[];for(let p of a){let f=MH(e,p);f&&c.push(f)}if(c.length===0)return[];let l=kH(e,c,a),u=c.filter(p=>!l.has(p.def.symbol));if(u.length===0)return[];let d=mn(e,s).forDefinitions(u.map(p=>p.def),{semantic:o}),m=[];for(let p of u){let f=d.get(p.def.symbolId);if(f?.semanticIncomplete||f?.semanticUnavailable)continue;let g=f?.realConsumers.length??0,h=TH(e,p.def,g);h&&m.push({symbol:p.def.symbol,shortName:k(p.def.symbol),file:p.def.relativePath,startLine:p.def.startLine,endLine:p.def.endLine,loc:de(p.def),stubKind:p.stubKind,reachability:h,callerFanIn:g,stubText:p.stubText})}return m.sort((p,f)=>yC[f.reachability]-yC[p.reachability]||f.callerFanIn-p.callerFanIn||p.file.localeCompare(f.file)||p.startLine-f.startLine),i?m.slice(0,i):m}function TH(e,t,n){return n>0?"caller":Ue(e,t.symbol,t.relativePath)?"rooted":Ye(e,t.relativePath)?"entry-surface":null}function MH(e,t){let n=Jt(e,t);if(!n)return null;let i=fn(n),r=i.trim();if(r==="")return!NH(n)||!Rt(e,t)?null:{def:t,stubKind:"empty-body",stubText:"(empty body)"};let o=Ir(i),s=bn(i),a=AH(o,s);if(a.length!==1)return null;let c=a[0];return FH(c)?{def:t,stubKind:"throw-stub",stubText:c.trim()}:LH.test(i)&&IH.test(c.trim())?{def:t,stubKind:"todo-return-default",stubText:r}:null}function AH(e,t){let n=[],i=0,r="";for(let o=0;o<t.length;o+=1){let s=t[o];if(s==="("||s==="["||s==="{"?i+=1:(s===")"||s==="]"||s==="}")&&(i=Math.max(0,i-1)),s===";"&&i===0){n.push(r),r="";continue}r+=e[o]??""}return r.trim()&&n.push(r),n.map(o=>o.trim()).filter(o=>o.length>0)}function FH(e){let t=wH.exec(e.trim());return t?EH.test(t[1]??""):!1}function NH(e){return PH.test(e.trimEnd())}function kH(e,t,n){let i=new Set,r=new Set(t.map(a=>a.def.parentTypeName).filter(a=>a!==null));if(r.size===0)return i;let o=OH(e,r),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))&&i.add(a.def.symbol)}return i}var _H=/\bclass\s+([A-Za-z_$][\w$]*)\s+extends\s+([A-Za-z_$][\w$]*)/g;function OH(e,t){let n=new Map;for(let i of he(e,{includeIgnored:!1})){let r=se(e,i);if(r)for(let o of r.matchAll(_H)){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 BH=/^(?:validate|verify|check|assert)(?:[A-Z].*)?$/,$H=/^(?:is|has)(?:[A-Z].*)?$/,jH=/[{,]\s*(?:ok|success|valid|isValid)\s*:\s*false\b/,vd=/\breturn\b/g,HH=/\bfunction\b|=>|\)\s*(?::\s*[^{;=]+)?\s*\{/,UH=/\.(?:addIssue|push)\s*\(/;function zH(e,t={}){let{scope:n,limit:i=30,scanLimit:r}=t,o=new U(e),s=Fe(o.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),r),a=[];for(let c of s){let l=KH(e,c);l&&a.push({symbol:c.symbol,shortName:k(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),i?a.slice(0,i):a}function GH(e){return BH.test(e)?"imperative":$H.test(e)?"predicate":null}function KH(e,t){let n=GH(t.leaf);if(!n||ur(e,t))return null;let i=Jt(e,t);if(!i||!HH.test(i))return null;let r=ee(e,t.relativePath)?.callables.find(s=>s.startLine===t.startLine&&s.endLine===t.endLine);if(n==="predicate"&&r?.paramCount===0)return null;if(cC(i)){let s=VH(e,t);return!s||vC(s.body,SC(s.snippet))||bC(s.body)?null:{nameKind:n,resolvedVia:"one-hop-delegate",delegateTarget:s.shortName}}let o=fn(i);return vC(o,SC(i))||bC(o)?null:{nameKind:n,resolvedVia:"direct"}}var qH=new Set(["if","for","while","switch","catch","function"]);function bC(e){let t=Ir(e);for(let n of t.matchAll(/\b([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(/g))if(!qH.has(n[1]))return!0;return!1}function SC(e){let t=e.indexOf("=>");return t===-1?!1:!/^\s*\{/.test(e.slice(t+2))}function vC(e,t){let n=Ir(e);if(/\bthrow\b/.test(n)||/\.reject\s*\(/.test(n)||jH.test(n)||UH.test(n))return!0;let i=WH(n);if(t&&i.length===0){let r=n.trim();return r!==""&&r!=="true"}for(let r of i)if(r!==""&&r!=="true")return!0;return!1}function WH(e){let t=[];vd.lastIndex=0;let n;for(;n=vd.exec(e);){let i=n.index+n[0].length,r=0,o=e.length;for(let s=i;s<e.length;s+=1){let a=e[s];if(a==="("||a==="["||a==="{")r+=1;else if(a===")"||a==="]"||a==="}"){if(r===0){o=s;break}r-=1}else if(a===";"&&r===0){o=s;break}}t.push(e.slice(i,o).trim()),vd.lastIndex=o}return t}function VH(e,t){let n=mi(e,t,{callableOnly:!0,limit:3,semanticEvidence:fe});if(n.semanticIncomplete||n.semanticUnavailable)return null;let i=n.rows,r=[...new Set(i.map(l=>l.symbol))].filter(l=>l!==t.symbol);if(r.length!==1)return null;let s=rt(e,r[0]).match;if(!s)return null;let a=J(e,s.relativePath).find(l=>l.symbolId===s.symbolId);if(!a)return null;let c=Jt(e,a);return c?{body:fn(c),snippet:c,shortName:k(a.symbol)}:null}var JH=60;function YH(e,t={}){let{scope:n,limit:i=30,scanLimit:r,rotDays:o=JH}=t,s=Fe($i(e,{extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs"]}).filter(u=>V(u)==="test").filter(u=>!n||u.includes(n)).filter(u=>!e.isIgnored(u)).sort(),r),a=[],c=[],l=[];for(let u of s){let d=se(e,u);if(!d)continue;let m=Km(d),p=ZH(d);for(let g of iU(m,p))p.add(g);let f=XH(m);for(let g of f){if(g.skip){c.push(uU(e,u,g,o));continue}if(g.kind==="describe")continue;let h=xC(d,g.argsStart),b=m.slice(g.argsStart,g.callEnd),v=d.slice(g.argsStart,g.callEnd);RC(b,p)||a.push({file:u,startLine:Oo(d,g.callStart),endLine:Oo(d,g.callEnd),title:h,severity:/\bawait\b/.test(b)?"low":"high"});let y=aU(b,v);y&&l.push({file:u,startLine:Oo(d,g.callStart),endLine:Oo(d,g.callEnd),title:h,echoedValue:y})}}return{assertionFree:i?a.slice(0,i):a,skipped:i?c.slice(0,i):c,mockEcho:i?l.slice(0,i):l}}var Cd=/(?<!\.)\b(?:x(it|test|describe)|(it|test|describe)(?:\.\s*(skip|only|todo|each\s*\([^)]*\)))?)\s*\(/g;function XH(e){let t=[];Cd.lastIndex=0;let n;for(;n=Cd.exec(e);){let i=n[1],r=i??n[2];if(!r)continue;let o=n[3]?.split(/\s*\(/)[0],s=n.index,a=n.index+n[0].length-1,c=Bo(e,a);Cd.lastIndex=a+1,o!=="each"&&t.push({kind:r,skip:i!==void 0||o==="skip"||o==="todo",skipKind:o==="todo"?"todo":"skip",callStart:s,argsStart:a+1,callEnd:c+1})}return t}function Bo(e,t){let n=0;for(let i=t;i<e.length;i+=1){let r=e[i];if(r==="(")n+=1;else if(r===")"&&(n-=1,n===0))return i}return e.length-1}function Oo(e,t){let n=0;for(let i=0;i<t&&i<e.length;i+=1)e[i]===`
414
- `&&(n+=1);return n}function xC(e,t){let n=e.slice(t,t+400),i=/^\s*(['"`])((?:\\.|(?!\1)[\s\S])*)\1/.exec(n);return i?i[2]:"(anonymous)"}var QH=new Set(["vitest","chai","jest","@jest/globals","assert","node:assert","node:assert/strict","assert/strict","uvu/assert","expect","chai-as-promised"]),CC=/import\s+(?:\*\s+as\s+(\w+)|\{([^}]*)\}|(\w+))\s+from\s+['"]([^'"]+)['"]/g;function ZH(e){let t=new Set(["expect","assert"]);CC.lastIndex=0;let n;for(;n=CC.exec(e);){let[,i,r,o,s]=n;if(!(!s||!QH.has(s))&&(i&&t.add(i),o&&t.add(o),r))for(let a of r.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 RC(e,t){if(/\.should\b/.test(e)||/\bawait\s+(?:[\w$.]+\.)?findBy[A-Z]\w*\s*\(/.test(e)||/\bawait\s+\w*waitFor(?:Text|Value|Condition|Result|Event)\s*\(/.test(e)||/\bthrow\b/.test(e))return!0;for(let n of t){let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`\\b${i}\\s*(?:<[^<>]*>)?\\s*[.(]`).test(e))return!0}return!1}var eU=/\bfunction\s+(\w+)\s*\(/g,tU=/\b(?:const|let)\s+(\w+)\s*=\s*(?:async\s*)?\(/g,nU=60;function iU(e,t){let n=new Set;for(let i of[eU,tU]){i.lastIndex=0;let r;for(;r=i.exec(e);){let o=r[1],s=r.index+r[0].length-1,a=Bo(e,s),c=e.indexOf("{",a+1);if(c===-1||c-a>nU)continue;let l=rU(e,c),u=e.slice(c+1,l);RC(u,t)&&n.add(o)}}return n}function rU(e,t){let n=0;for(let i=t;i<e.length;i+=1){let r=e[i];if(r==="{")n+=1;else if(r==="}"&&(n-=1,n===0))return i}return e.length-1}var oU=/\bmock(?:ReturnValue|ResolvedValue)(?:Once)?\s*\(/g,xd=/\bexpect\s*\(/g,sU=/^\s*\.\s*(?:toBe|toEqual|toStrictEqual)\s*\(/,EC=/^(?:-?\d+(?:\.\d+)?|(['"`]).+\1)$/;function aU(e,t){let n=cU(e,t,oU);if(n.length===0)return null;let i=lU(e,t);for(let r of i)if(n.includes(r))return r;return null}function cU(e,t,n){let i=[];n.lastIndex=0;let r;for(;r=n.exec(e);){let o=r.index+r[0].length-1,s=Bo(e,o),a=t.slice(o+1,s).trim();EC.test(a)&&i.push(a),n.lastIndex=s+1}return i}function lU(e,t){let n=[];xd.lastIndex=0;let i;for(;i=xd.exec(e);){let r=i.index+i[0].length-1,o=Bo(e,r),s=e.slice(o+1),a=sU.exec(s);if(xd.lastIndex=o+1,!a)continue;let c=o+1+a[0].length-1,l=Bo(e,c),u=t.slice(c+1,l).trim();EC.test(u)&&n.push(u)}return n}function uU(e,t,n,i){let r=se(e,t),o=xC(r,n.argsStart),s=Oo(r,n.callStart),a=dU(e.config.projectRoot,t,s),c=a===null?"unknown":a>=i?"rot":"workflow";return{file:t,startLine:s,title:o,skipKind:n.skipKind,blockKind:n.kind,ageDays:a,rot:c}}function dU(e,t,n){let i=n+1;try{let r=pn(e,["blame","-L",`${i},${i}`,"--porcelain","--",t]),o=/^author-time (\d+)$/m.exec(r);if(!o)return null;let s=Number(o[1]);return Number.isFinite(s)?Math.max(0,Math.round((Date.now()/1e3-s)/86400)):null}catch{return null}}var mU=.7,wC=.62,IC=.45;function pU(e,t={}){let{windowCommits:n=100,limit:i=30,scope:r,scanLimit:o}=t,s=Vt(e,{historyMode:t.historyMode}).fileAddRecords();if(!s)return{available:!1,windowCommits:n,findings:[]};if(i<=0)return{available:!0,windowCommits:n,findings:[]};let a=xU(s,n);if(a.size===0)return{available:!0,windowCommits:n,findings:[]};let l=fU(e,{limit:i,minSimilarity:t.minSimilarity,scanLimit:o,scope:r,semantic:t.semantic,focusFiles:Number.isFinite(i)?void 0:a}).map(d=>RU(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,i).map(EU);return{available:!0,windowCommits:n,findings:u,rootCauseGroups:wU(u)}}function fU(e,t){let n=LU(t.limit),i=[...gU(e,{scope:t.scope,minSimilarity:t.minSimilarity??mU,limit:n,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles})],r=as(e,{scope:t.scope});return r.react&&i.push(...hU(e,{scope:t.scope,minSimilarity:t.minSimilarity??wC,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...yU(e,{scope:t.scope,minSimilarity:t.minSimilarity??IC,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),r.vue&&i.push(...vU(e,{scope:t.scope,minSimilarity:t.minSimilarity??wC,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...CU(e,{scope:t.scope,minSimilarity:t.minSimilarity??IC,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),i}function gU(e,t){return Io(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles}).filter(n=>!at(n.symbolA)&&!at(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 hU(e,t){return ec(e,t,{query:Lo,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 ec(e,t,n){return n.query(e,t).filter(i=>i.fileA!==i.fileB).filter(i=>n.acceptPair?.(i)??!0).map(i=>({domain:n.domain,basis:n.basis,symbolA:n.symbolA(i),fileA:i.fileA,symbolB:n.symbolB(i),fileB:i.fileB,similarity:i.similarity,sharedEvidence:PU(...n.evidenceBuckets(i)),sharedCallees:[]}))}function yU(e,t){return ec(e,t,{query:Po,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,acceptPair:SU,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 bU=new Set(["useCallback","useEffect","useLayoutEffect","useMemo","useMutation","useQueries","useQuery","useQueryClient","useReducer","useRef","useState"]);function SU(e){return e.sharedHooks.some(t=>!bU.has(t))||e.sharedState.length>0||e.sharedHandlers.length>0||e.sharedHandlerVerbs.length>=2}function vU(e,t){return ec(e,t,{query:Do,domain:"vue-component",basis:"vue-template",symbolA:n=>Za(n.fileA),symbolB:n=>Za(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function CU(e,t){return ec(e,t,{query:To,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>Za(n.fileA),symbolB:n=>Za(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 xU(e,t){let n=new Set;for(let[i,r]of e)r.commitsAgo<=t&&n.add(i);return n}function RU(e,t,n){let i=t.get(e.fileA)?.commitsAgo??null,r=t.get(e.fileB)?.commitsAgo??null,o=i!==null&&i<=n,s=r!==null&&r<=n;if(!o&&!s)return null;if(o&&s){let a=(i??0)<=(r??0);return{kind:"twin",domain:e.domain,basis:e.basis,echoSymbol:a?e.symbolA:e.symbolB,echoFile:a?e.fileA:e.fileB,echoAgeCommits:(a?i:r)??0,establishedSymbol:a?e.symbolB:e.symbolA,establishedFile:a?e.fileB:e.fileA,establishedAgeCommits:a?r:i,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}return{kind:"echo",domain:e.domain,basis:e.basis,echoSymbol:o?e.symbolA:e.symbolB,echoFile:o?e.fileA:e.fileB,echoAgeCommits:(o?i:r)??0,establishedSymbol:o?e.symbolB:e.symbolA,establishedFile:o?e.fileB:e.fileA,establishedAgeCommits:o?r:i,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}function EU(e){let t=LC(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function LC(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 wU(e){let t=new Map;for(let[n,i]of e.entries()){let r=i.rootCauseKey??LC(i),o=i.groupKey??`recent-duplicate:${r}`,s=t.get(o);s||(s={groupKey:o,rootCauseKey:r,kind:i.kind,domain:i.domain,basis:i.basis,count:0,maxSimilarity:i.similarity,findingIndexes:[],echoFiles:new Set,establishedFile:i.kind==="echo"?i.establishedFile:void 0,establishedSymbol:i.kind==="echo"?i.establishedSymbol:void 0,relatedFiles:new Set,sharedEvidence:new Set,recommendation:IU(i)},t.set(o,s)),s.count+=1,s.maxSimilarity=Math.max(s.maxSimilarity,i.similarity),s.findingIndexes.push(n),s.echoFiles.add(i.echoFile),s.relatedFiles.add(i.echoFile),s.relatedFiles.add(i.establishedFile);for(let a of i.sharedEvidence)s.sharedEvidence.add(a)}return[...t.values()].map(n=>({...n,echoFiles:[...n.echoFiles].sort(),relatedFiles:[...n.relatedFiles].sort(),sharedEvidence:[...n.sharedEvidence].sort().slice(0,16)})).sort((n,i)=>i.count-n.count||i.maxSimilarity-n.maxSimilarity||n.groupKey.localeCompare(i.groupKey))}function IU(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 LU(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function PU(...e){let t=[],n=new Set;for(let[i,r]of e)for(let o of r){let s=`${i}:${o}`;n.has(s)||(n.add(s),t.push(s))}return t}function Za(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var DU=Me("suppression-inventory",{clearGroups:["whole-project"]});function tc(e){return DU.get(e,()=>TU(e))}function TU(e){let t={dead:0,stale:0,wrapper:0,passthrough:0,drift:0,extract:0,similar:0,twin:0,uncategorized:0},n=new Map,i=0;for(let r of $i(e)){let o=se(e,r);if(!(!o||!o.includes("codebaseiq")))for(let s of o.split(/\r?\n/)){let a=is(s);if(a===null)continue;i+=1,n.set(r,(n.get(r)??0)+1);let c=PC(a);t[c]+=1}}for(let r of e.config.suppressions??[])r.expiresAt&&Date.parse(r.expiresAt)<=Date.now()||(i+=1,r.file&&n.set(r.file,(n.get(r.file)??0)+1),t[PC(r.check)]+=1);return{total:i,byCategory:t,byFile:n}}function PC(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 Rd(e,t,n={}){let i=pe(e,t);if(!i)return null;let r=new U(e),o=MU(e,i),s=i.endLine-i.startLine+1,a=r.calleeEvidenceMap([i],{additive:!0,semantic:n.semantic}),c=a.rows.get(i.symbolId)??[],l=new Set(c.map(f=>f.symbol)),u=a.incompleteSymbolIds.has(i.symbolId),d=a.unavailableSymbolIds.has(i.symbolId),m=n.semantic===!1?"disabled":u&&d?"incomplete-and-unavailable":u?"incomplete":d?"unavailable":"complete",p=!u&&!d;return{symbol:i.symbol,shortName:k(i.symbol),relativePath:i.relativePath,startLine:i.startLine,endLine:i.endLine,loc:s,branches:o.branches,estimateBasis:o.estimateBasis,cyclomaticEstimate:o.branches+1,calleeCount:p?l.size:null,fanIn:FU(e,i.symbolId),fanOut:p?NU(c,i.relativePath):null,coverage:{semanticEvidence:m}}}function MU(e,t){let n=ae(e,t.relativePath);if(n){let i=AC(n.rootNode,t.startLine,t.endLine);if(i)return{branches:kU(i),estimateBasis:"ast"}}return{branches:NC(MC(e,t.relativePath,t.startLine,t.endLine),TC(e,t.relativePath)),estimateBasis:"regex-fallback"}}function DC(e,t){let n=new Map,i=new Map;for(let r of t){let o=i.get(r.relativePath)??[];o.push(r),i.set(r.relativePath,o)}for(let[r,o]of i){let s=ae(e,r),a=s===null?[]:o.filter(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"});_U(s.rootNode,a,n)}for(let l of o)c.has(l.symbolId)||n.set(l.symbolId,AU(e,l))}return n}function AU(e,t){return{branches:NC(MC(e,t.relativePath,t.startLine,t.endLine),TC(e,t.relativePath)),estimateBasis:"regex-fallback"}}function TC(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function MC(e,t,n,i){try{return nt(e.config.projectRoot,t,{inputKind:"indexed source file"}).split(`
415
- `).slice(n,i+1).join(`
416
- `)}catch(r){if(!Ct(r))throw r;return""}}function FU(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
417
- FROM mentions m
418
- JOIN chunks c ON m.chunk_id = c.id
419
- JOIN (
420
- SELECT m2.symbol_id, c2.document_id
421
- FROM mentions m2
422
- JOIN chunks c2 ON m2.chunk_id = c2.id
423
- WHERE m2.role = 1
424
- GROUP BY m2.symbol_id
425
- ) sym_def ON sym_def.symbol_id = m.symbol_id
426
- WHERE m.symbol_id = ?
427
- AND m.role != 1
428
- AND sym_def.document_id != c.document_id`,t)?.c??0}function NU(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function kU(e){let t=0;return Ed(e,n=>{t+=FC(n)}),t}function _U(e,t,n){let i=[...t].sort((r,o)=>r.startLine-o.startLine||o.endLine-r.endLine);Ed(e,r=>{let o=FC(r);if(o===0)return;let s=r.startPosition.row,a=r.endPosition.row;for(let c of i){if(c.startLine>s)break;if(c.endLine<a)continue;let l=n.get(c.symbolId);l&&(l.branches+=o)}})}function Ed(e,t){t(e);for(let n of e.namedChildren)Ed(n,t)}function AC(e,t,n){if(e.startPosition.row>t||e.endPosition.row<n)return null;for(let i of e.namedChildren){let r=AC(i,t,n);if(r)return r}return e}var OU=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 FC(e){return OU.has(e.type)?1:e.type==="binary_expression"&&e.parent?.type!=="binary_expression"&&(e.text.includes("&&")||e.text.includes("||"))?BU(e.text):0}function BU(e){return(e.match(/&&|\|\|/g)??[]).length}function NC(e,t){let n=bn(e),i=0,r=[/\bif\b/g,/\belse\s+if\b/g,/\belse\b/g,/\bfor\b/g,/\bwhile\b/g,/\bswitch\b/g,/\bcase\b/g,/\bcatch\b/g,/\?\s*[^?]/g,/&&/g,/\|\|/g];for(let o of r){let s=n.match(o);s&&(i+=s.length)}if(t==="python"){let o=[/\belif\b/g,/\bexcept\b/g,/\bfinally\b/g];for(let s of o){let a=n.match(s);a&&(i+=a.length)}}else if(t==="rust"){let o=[/\bmatch\b/g,/=>/g,/\bloop\b/g];for(let s of o){let a=n.match(s);a&&(i+=a.length)}}else if(t==="ruby"){let o=[/\belsif\b/g,/\bunless\b/g,/\brescue\b/g,/\bwhen\b/g];for(let s of o){let a=n.match(s);a&&(i+=a.length)}}else if(t==="go"){let o=[/\bselect\b/g,/\bdefer\b/g];for(let s of o){let a=n.match(s);a&&(i+=a.length)}}return i}function kC(e,t,n={}){let i=pe(e,t);if(!i)return null;let r=[{file:i.relativePath,line:i.startLine}],o=Hn(e,i,{semantic:n.semantic,semanticEvidence:fe}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?k(c.enclosingSymbol):"(top-level)"})),{outgoingCalls:s,incomingCalls:a}=$U(e,i,o,{semantic:n.semantic!==!1});return{symbol:i.symbol,shortName:k(i.symbol),relativePath:i.relativePath,definitionSites:r.filter(c=>!e.isIgnored(c.file)),referenceSites:o,outgoingCalls:s.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:k(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)":k(c.symbol),file:c.file}))}}function wd(e,t,n={}){let i=kC(e,t,n);return i?{symbol:i.symbol,shortName:i.shortName,relativePath:i.relativePath,definitionSites:i.definitionSites,usageSites:i.referenceSites,producers:i.outgoingCalls,consumers:i.incomingCalls}:null}function $U(e,t,n,i){let r=ir(ws(e,t,{limit:30,semantic:i.semantic,semanticEvidence:fe}).map(a=>({symbol:a.symbol,file:a.file}))),o=ir(Is(e,t,{limit:30,semantic:i.semantic,semanticEvidence:fe})),s=o.length>0?o:ir(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{outgoingCalls:r,incomingCalls:s}}function _C(e,t,n={}){let{direction:i="backward",maxDepth:r=3}=n,o=pe(e,t);return o?i==="backward"?jU(e,o,r,{semantic:n.semantic!==!1}):HU(e,o,{semantic:n.semantic!==!1}):null}function nc(e,t,n={}){return _C(e,t,n)}function jU(e,t,n,i){let r=[],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=ws(e,l,{semantic:i.semantic,semanticEvidence:fe});for(let d of u){if(o.has(d.symbol))continue;o.add(d.symbol),r.push({symbol:d.symbol,shortName:k(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let m=li(e,d.symbol);m&&!e.isIgnored(m.relativePath)&&c.push(m)}}s=c}return{symbol:t.symbol,shortName:k(t.symbol),direction:"backward",connectedSymbols:r}}function HU(e,t,n){let i=new Set,r=[],o=new U(e);for(let s of Hn(e,t,{semantic:n.semantic,semanticEvidence:fe})){if(r.length>=30)break;let a=s.enclosingSymbol??Ge(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=li(e,a);!c||e.isIgnored(c.relativePath)||i.has(c.symbol)||(i.add(c.symbol),r.push({symbol:c.symbol,shortName:k(c.symbol),file:c.relativePath,relationship:`references target at ${s.file}:${s.line+1}`}))}return r.sort((s,a)=>s.file.localeCompare(a.file)),{symbol:t.symbol,shortName:k(t.symbol),direction:"forward",connectedSymbols:r}}function OC(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 zC=6,rc=10,Ld=3,Pd=8,UU=.7,BC=24,Id=200,GC=12,$C=80,jC=600;function zU(e,t,n={}){let i=n.impactDepth??3,r=n.sliceDepth??3,o=n.semantic,s=ZU(t)?KU(e,t):null,a=s?s.primary?.symbol??null:t,c=a!==null,l=c?qe("trace",a,()=>Vl(e,a,{semantic:o,referenceContext:GC}),T=>({definitions:T.definitions.length,references:T.referencedBy.length})):{definitions:[],referencedBy:[],claimSupport:null},u=c?qe("call-graph",a,()=>no(e,a,{semantic:o}),T=>({callers:T?.callers.length??0,callees:T?.callees.length??0})):null,d=c?qe("complexity",a,()=>Rd(e,a,{semantic:o}),T=>({callees:T?.calleeCount??0})):null,m=c?qe("dataflow",a,()=>wd(e,a,{semantic:o}),T=>({references:T?.usageSites.length??0,producers:T?.producers.length??0,consumers:T?.consumers.length??0})):null,p=c?qe("backward-slice",a,()=>nc(e,a,{direction:"backward",maxDepth:r,semantic:o}),T=>({maxDepth:r,connectedSymbols:T?.connectedSymbols.length??0})):null,f=c?qe("forward-slice",a,()=>nc(e,a,{direction:"forward",maxDepth:r,semantic:o}),T=>({maxDepth:r,connectedSymbols:T?.connectedSymbols.length??0})):null,g=c?qe("affected",a,()=>Yu(e,a,{maxDepth:i,scope:n.scope}),T=>({maxDepth:i,affectedSymbols:T.rows.length,coverage:T.coverage.status})):null,h=g?.rows??[],b=g?.coverage??null,v=c?qe("reuse-candidates",a,()=>wo(e,a,{minSimilarity:.4,limit:5,semantic:o,sourceCandidateMode:"target-pruned"}),T=>({candidates:T.length,direct:T.filter(F=>F.actionTier==="direct").length})):[],y=c?pe(e,a)?.symbol??null:null,E=c?qe("affected-consumer-reuse",a,()=>WU(l,y,T=>wo(e,T,{minSimilarity:.4,limit:rc,semantic:o,sourceCandidateMode:"target-pruned"}),{consumerLimit:zC,perConsumerSearchLimit:rc,perConsumerCandidateLimit:Ld,candidateLimit:Pd}),T=>({totalConsumers:T.coverage.totalConsumers,analyzedConsumers:T.coverage.analyzedConsumers,candidates:T.candidates.length})):XU(),w=qe("change-surface",t,()=>Xu(e,t,{semantic:o}),T=>({symbols:T?.symbols.length??0,externalConsumers:T?.totalExternalConsumers??0})),S=qe("system",t,()=>Iu(e,t),T=>({files:T.files.length,symbols:T.symbols.length})),R=S.files.length===1,C=qe("deps",t,()=>R?S.dependsOn.map(T=>({relativePath:T,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):io(e,t),T=>({files:T.length,reusedSystem:R})),L=qe("rdeps",t,()=>R?S.dependedOnBy.map(T=>({relativePath:T,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):ro(e,t),T=>({files:T.length,reusedSystem:R})),I=qe("surface",t,()=>Lu(e,t),T=>({consumers:T.length})),x={symbol:l.definitions.length>0||l.referencedBy.length>0||u!==null||d!==null||m!==null||p!==null||f!==null||h.length>0,file:w!==null||C.length>0||L.length>0,module:S.files.length>0||S.symbols.length>0||I.length>0},D=[];s&&!s.primary&&s.callableCount>1&&D.push(`File target has ${s.callableCount} callable symbols; use one callable name for compiler-resolved flow.`);let _=[...new Set(l.referencedBy.map(T=>T.relativePath))];_.length>0&&_.every(T=>V(T)==="test")&&D.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."),!x.symbol&&!x.file&&!x.module&&D.push("No symbol, file, or module matched target."),b&&b.status!=="accounted"&&D.push(`Possible-impact coverage is ${b.status}: ${b.reasons.join(" ")}`);let P=w?.file??l.definitions[0]?.relativePath??null;return{target:t,...s?.primary?{primaryCallable:{symbol:s.primary.symbol,shortName:re(s.primary.symbol),file:s.primary.relativePath}}:{},matched:x,history:qe("history",P??t,()=>QU(e,P,n.gitHead)),trace:GU(l),callGraph:u,complexity:d,dataflow:m,backwardSlice:p,forwardSlice:f,affected:h,affectedCoverage:b,changeSurface:w,deps:C,rdeps:L,system:S,surface:I,reuseCandidates:v,affectedConsumerReuse:E,sourcePacket:qU(e,y,l,E,v),warnings:D}}function GU(e){return{definitions:e.definitions,referencedBy:e.referencedBy.map(t=>({relativePath:t.relativePath,line:t.line,enclosingSymbol:t.enclosingSymbol,enclosingShort:t.enclosingShort}))}}function KU(e,t){let n=vn(e,t);if(n.length!==1)return{primary:null,callableCount:0};let i=J(e,n[0]).filter(s=>s.isFunctionLike),r=i.filter(s=>s.enclosingSymbol===null),o=r.length>0?r:i;return{primary:o.length===1?o[0]:null,callableCount:o.length}}function qU(e,t,n,i,r){let o=[...t?[{definition:HC(e,t),role:"target"}]:[],...[...i.candidates.map(d=>d.candidate),...r].map(d=>({definition:HC(e,d.symbolB),role:"reuse-candidate"}))],s=new Map;for(let d of OC(o)){if(s.has(d.definition.symbol))continue;let m=d.role==="target"?Id:$C,p=d.definition.endLine<=d.definition.startLine?zn(e,d.definition.relativePath,d.definition.startLine,m):null,f=p?.unitType?p.source:Jt(e,d.definition);if(!f)continue;let g=f.split(`
429
- `),h=Math.min(g.length,m),b=p?.unitType?p.startLine:d.definition.startLine;s.set(d.definition.symbol,{role:d.role,symbol:d.definition.symbol,shortName:re(d.definition.symbol),file:d.definition.relativePath,startLine:b,endLine:b+h-1,source:g.slice(0,h).join(`
430
- `),omittedLines:(p?.unitType?p.omittedLines:0)+Math.max(0,g.length-h)})}let a=new Map;for(let d of n.referencedBy){if(d.source===void 0||d.source===null||d.sourceStartLine===void 0||d.sourceStartLine===null||d.sourceEndLine===void 0||d.sourceEndLine===null)continue;let m=`${d.relativePath}:${d.sourceStartLine}-${d.sourceEndLine}`,p=a.get(m);if(p){p.focusLines=[...new Set([...p.focusLines??[],d.line])].sort((f,g)=>f-g);continue}a.set(m,{role:"consumer",symbol:d.enclosingSymbol??`${d.relativePath}:${d.line}`,shortName:d.enclosingShort,file:d.relativePath,startLine:d.sourceStartLine,endLine:d.sourceEndLine,source:d.source,omittedLines:0,focusLines:[d.line]})}let c=[...[...s.values()].filter(d=>d.role==="target"),...a.values(),...[...s.values()].filter(d=>d.role==="reuse-candidate")],l=[],u=jC;for(let d of c){if(l.length>=BC||u<=0)break;let m=d.source.split(`
431
- `),p=Math.min(m.length,u);l.push({...d,endLine:d.startLine+p-1,source:m.slice(0,p).join(`
432
- `),omittedLines:d.omittedLines+Math.max(0,m.length-p),...d.focusLines?{focusLines:d.focusLines.filter(f=>f<=d.startLine+p-1)}:{}}),u-=p}return{slices:l,candidateSlices:c.length,omittedSlices:Math.max(0,c.length-l.length),maxSlices:BC,maxLinesPerSlice:Id,maxTotalLines:jC,targetLineLimit:Id,consumerContextLines:GC,reuseLineLimit:$C}}function HC(e,t){let n=li(e,t);return n?J(e,n.relativePath).find(i=>i.symbol===t)??null:null}function WU(e,t,n,i={}){let r=ic(i.consumerLimit,zC),o=ic(i.perConsumerSearchLimit,rc),s=ic(i.perConsumerCandidateLimit,Ld),a=ic(i.candidateLimit,Pd),c=VU(e),l=c.slice(0,r),u=new Set(c.map(p=>p.symbol));t&&u.add(t);let d=new Map;for(let p of l){let f=n(p.symbol).slice(0,o),g=0;for(let h of f){let b=JU(h,p.symbol);if(!b||u.has(b.symbolB))continue;let v=d.get(b.symbolB);if(v?(v.consumers.some(y=>y.symbol===p.symbol)||v.consumers.push(p),b.similarity>v.candidate.similarity&&(v.candidate=b)):d.set(b.symbolB,{candidate:b,consumers:[p]}),g+=1,g>=s)break}}let m=[...d.values()].filter(p=>p.candidate.actionTier==="direct"||p.candidate.similarity>=UU||p.consumers.length>1).sort(YU).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 VU(e){let t=new Map;for(let n of e.referencedBy){if(!n.enclosingSymbol)continue;let i=t.get(n.enclosingSymbol);if(i){i.referenceCount+=1;continue}t.set(n.enclosingSymbol,{symbol:n.enclosingSymbol,shortName:re(n.enclosingSymbol)||n.enclosingShort,file:n.relativePath,referenceCount:1})}return[...t.values()].sort((n,i)=>i.referenceCount-n.referenceCount||n.symbol.localeCompare(i.symbol))}function JU(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 YU(e,t){let n=UC(t.candidate.actionTier)-UC(e.candidate.actionTier);if(n!==0)return n;let i=t.consumers.length-e.consumers.length;if(i!==0)return i;let r=t.candidate.similarity-e.candidate.similarity;return r!==0?r:e.candidate.symbolB.localeCompare(t.candidate.symbolB)}function UC(e){return e==="direct"?1:0}function ic(e,t){return typeof e=="number"&&Number.isFinite(e)?Math.max(1,Math.floor(e)):t}function XU(){return{candidates:[],coverage:{totalConsumers:0,analyzedConsumers:0,omittedConsumers:0,perConsumerSearchLimit:rc,perConsumerCandidateLimit:Ld,candidateLimit:Pd,returnedCandidates:0}}}function qe(e,t,n,i=()=>({})){let r;return $(`context.${e}`,()=>(r=n(),r),()=>({target:t,...i(r)}))}function QU(e,t,n){let i={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return i;let r=Vt(e,n?{head:n}:{}),o=qe("history.churn",t,()=>r.fileChurn(),c=>({files:c?.size??0}));if(!o)return i;let s=qe("history.co-change",t,()=>Fo(e,t,{limit:5,...n?{head:n}:{}}),c=>({commits:c.commitsAnalyzed,partners:c.findings.length})),a=qe("history.suppressions",t,()=>tc(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 ZU(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}var Be={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 ez}from"fs";import{isAbsolute as tz,join as nz}from"path";var iz=".codebaseiq-baseline.json";function Dd(e){if(e.startsWith("similar:")){let t=e.slice(8).split("|");return t.length!==2?e:`similar:${t.map(k).sort().join("|")}`}if(e.startsWith("duplicate-bodies:")){let t=e.slice(17),n=t.indexOf(":");if(n<0)return e;let i=t.slice(0,n),r=t.slice(n+1).split("|");return r.length<2?e:`duplicate-bodies:${i}:${r.map(k).sort().join("|")}`}return e}function Td(e,t){return t&&tz(t)?t:nz(e.config.projectRoot,t??iz)}function KC(e,t,n={}){let i=Td(e,n.path);if(!ez(i))throw new Error(`No baseline found at ${i}. Create one with: codebaseiq health --write-baseline`);let o=(JSON.parse(vt(i,"health baseline")).findings??[]).map(Dd),s=new Set(n.accept?o.filter(n.accept):o),a=new Set(t);return{baselinePath:i,baselineCount:s.size,current:[...t],newFindings:t.filter(c=>!s.has(c)),fixedFindings:[...s].filter(c=>!a.has(c))}}import $o from"path";function Ho(e,t){let{scope:n,minDeviation:i=5,limit:r=50}=t??{},o=t?.semantic!==!1,s=t?.includePatternDeviations===!0,c=new U(e).fileDependencyGraph(n),l=Co(e,{scope:n}),u=cz([...rz(e,c,{scope:n,semantic:o}),...sz(l.forbiddenEdges),...s?az(c,i):[]]);return t?.includeArchitecture===!0&&(u.architecture=l),r<=0||u.results.length<=r?u:{...u,results:u.results.slice(0,r),totalResults:u.results.length}}function rz(e,t,n){let i=dz(e,n.scope),r=[],o=new Set;for(let[a,c]of t){if(jo(a))continue;let l=i.get(a)??new Set;for(let u of c)jo(u)||l.has(u)||oz(e,a,u,n)||(r.push({file:a,dep:u}),o.add(a))}o.size>0&&fz(e,i,{paths:[...o]});let s=[];for(let{file:a,dep:c}of r)(i.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 oz(e,t,n,i){return yz(e,t,n)||bz(e,t,n)||gz(n)||vz(e,t,n)||Sz(n)?!0:i.semantic&&hz(e,t,n)}function sz(e){return e.flatMap(t=>{let n=t.examples[0];return n?[{file:n.fromFile,kind:"architecture-violation",description:`${t.from} depends on forbidden boundary ${t.to} through ${t.fileEdgeCount} file edge(s)`,dep:n.toFile,detail:`${t.from} may not depend on ${t.to}`,actionTier:"direct",policyBasis:"explicit",architecture:{fromBoundary:t.from,toBoundary:t.to,fileEdgeCount:t.fileEdgeCount,importerCount:t.importerCount,importedFileCount:t.importedFileCount,examples:t.examples},evidenceReasons:[`configured dependency row for ${t.from} does not allow ${t.to}`,`${t.fileEdgeCount} file edge(s) connect ${t.importerCount} importer(s) to ${t.importedFileCount} imported file(s)`,...t.examples.map(i=>`${i.fromFile} imports ${i.toFile}`)],recommendation:"Move the dependency behind an allowed boundary, reverse the dependency through an owned interface, or deliberately update the project architecture rule."}]:[]})}function az(e,t){let n=[];for(let[i,r]of lz(e)){let o=r.filter(a=>!jo(a));if(o.length<t)continue;let s=uz(e,o);for(let a of o)for(let c of e.get(a)??[])jo(c)||(s.get(c)??0)===1&&$o.dirname(c)!==i&&$o.dirname(c)!==$o.dirname(i)&&n.push({file:a,kind:"pattern-deviation",description:`Only file in ${i}/ that depends on ${c}`,dep:c,actionTier:"signal",evidenceReasons:[`${o.length} sibling file(s) in ${i}/ 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 cz(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 lz(e){let t=new Map;for(let n of e.keys()){let i=$o.dirname(n),r=t.get(i);r||(r=[],t.set(i,r)),r.push(n)}return t}function uz(e,t){let n=new Map;for(let i of t)for(let r of e.get(i)??[])jo(r)||n.set(r,(n.get(r)??0)+1);return n}function dz(e,t){let n=new Map;return mz(e,n,t),n}function mz(e,t,n){for(let i of pz(e,n))qC(e,t,i.from_file,i.to_file)}function pz(e,t){let n=t?"AND d1.relative_path LIKE ?":"",i=t?[`%${t}%`]:[];return e.all(`SELECT DISTINCT d1.relative_path AS from_file, d2.relative_path AS to_file
433
- FROM mentions m
434
- JOIN chunks c ON m.chunk_id = c.id
435
- JOIN documents d1 ON c.document_id = d1.id
436
- JOIN global_symbols gs ON m.symbol_id = gs.id
437
- JOIN (
438
- SELECT m2.symbol_id, c2.document_id
439
- FROM mentions m2
440
- JOIN chunks c2 ON m2.chunk_id = c2.id
441
- WHERE m2.role = 1
442
- GROUP BY m2.symbol_id
443
- ) sym_def ON sym_def.symbol_id = gs.id
444
- JOIN documents d2 ON sym_def.document_id = d2.id
445
- WHERE d1.id != d2.id
446
- AND m.role != 1
447
- ${e.pathExclusionsFor("d1","d2")}
448
- ${n}`,...i)}function fz(e,t,n={}){new U(e).scanSourceReferences({paths:n.paths??he(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},r=>{r.target.relativePath!==r.sourceFile&&(e.isIgnored(r.target.relativePath)||qC(e,t,r.sourceFile,r.target.relativePath))})}function qC(e,t,n,i){if(e.isIgnored(n)||e.isIgnored(i))return;let r=t.get(n);r||(r=new Set,t.set(n,r)),r.add(i)}function gz(e){return e.includes("types")||e.endsWith(".d.ts")}function hz(e,t,n){let i=Vr(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.some(r=>r.isUsed)}function yz(e,t,n){let i=Ce(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.some(r=>r.used)}function bz(e,t,n){let i=Ce(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.every(r=>r.isTypeOnly===!0)}function Sz(e){return e.endsWith(".vue")}function vz(e,t,n){let i=Ce(e,t).filter(r=>r.sourcePath===n);return i.length===0?!1:i.every(r=>r.kind==="side-effect"||r.kind==="namespace"&&r.usedMembers.length===0&&!r.used)}function jo(e){let t=V(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||Cz($o.basename(e)))}function Cz(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 Uo(e,t){let{scope:n,minLoc:i=3,maxLoc:r=80,limit:o=30,includeLowConfidence:s=!1,scanLimit:a}=t??{},c=t?.semantic!==!1,l=new U(e),u=l.scopedDefinitions(n),d=Fz(l,n),m={high:0,medium:1,low:2};return $t({candidates:()=>xz(e,l,u,{minLoc:i,maxLoc:r}),orderCandidates:(p,f)=>de(f)-de(p)||p.relativePath.localeCompare(f.relativePath),scanLimit:a,profile:{name:"stale-abstractions"},prepare:p=>{let f=Ez(p),g=Rz(e,l,p,f,{semantic:c}),h=p.filter(b=>{if(g.incompleteSymbolIds.has(b.symbolId)||g.unavailableSymbolIds.has(b.symbolId)||l.hasSuppressionComment(b))return!1;let v=oc(e,b,g.consumerFileMap,f);return v.realConsumers.length<=1&&!v.transitivelyReachable&&VC(b,v.realConsumers.length,d)});return{...g,singletonBackedClassIds:Lz(e,l,u,h,{semantic:c}),candidateIndex:f}},evaluate:(p,f)=>{if(f.incompleteSymbolIds.has(p.symbolId)||f.unavailableSymbolIds.has(p.symbolId)||l.hasSuppressionComment(p)||f.singletonBackedClassIds.has(p.symbolId))return null;let g=oc(e,p,f.consumerFileMap,f.candidateIndex);if(g.transitivelyReachable||g.realConsumers.length>1||g.realConsumers.length===0&&g.barrelConsumers>0||!VC(g.definition,g.realConsumers.length,d))return null;let h=wz(e,g);return!s&&h.confidence==="low"?null:h},orderResults:(p,f)=>m[p.confidence]-m[f.confidence]||f.loc-p.loc||p.file.localeCompare(f.file)||p.startLine-f.startLine,limit:o})}function xz(e,t,n,i){return n.filter(r=>r.isTypeLike&&de(r)>=i.minLoc).filter(r=>de(r)<=i.maxLoc).filter(r=>!e.isIgnored(r.relativePath)).filter(r=>!r.relativePath.endsWith(".d.ts")).filter(r=>V(r.relativePath)!=="test").filter(r=>!Ue(e,r.symbol,r.relativePath)).filter(r=>!Nz(r.symbol))}function WC(e,t,n,i){return ni(mn(e,t).forDefinitions(n,{semantic:i.semantic,sourceFallback:i.sourceFallback}))}function Rz(e,t,n,i,r){let o=WC(e,t,n,{semantic:!1,sourceFallback:!1}),s=n.filter(m=>{let p=oc(e,m,o,i);return p.realConsumers.length<=1&&!(p.realConsumers.length>0&&Md(m.relativePath))}),a=mn(e,t).forDefinitions(s,{semantic:r.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=r.semantic&&s.length>0?yi(o,ni(a)):o,d=s.filter(m=>oc(e,m,u,i).realConsumers.length<=1);return{consumerFileMap:yi(u,WC(e,t,d,{semantic:!1,sourceFallback:!0})),incompleteSymbolIds:c,unavailableSymbolIds:l}}function Ez(e){let t=new Map;for(let n of e){let i=t.get(n.relativePath);i||(i=new Map,t.set(n.relativePath,i));let r=re(n.symbol);r&&i.set(r,n)}return t}function oc(e,t,n,i){let o=[...n.get(t.symbolId)??new Set].filter(u=>u!==t.relativePath&&!e.isIgnored(u)),{realConsumers:s,barrelConsumers:a,importOnlyConsumers:c}=Ha(e,t,o),l=kz(e,t,n,i);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:l}}function wz(e,t){let n=YC(e,t.definition.relativePath,t.definition.startLine),i=Md(t.definition.relativePath)?!0:_z(e,t.definition),{confidence:r,reason:o}=Oz(t.realConsumers.length,n,i),s=Iz(t.realConsumers.length,n,i);return{symbol:t.definition.symbol,shortName:k(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:de(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:i,confidence:r,reason:o,actionTier:s.actionTier,stalenessKind:s.stalenessKind,recommendation:s.recommendation}}function Iz(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 Lz(e,t,n,i,r){let o=Dz(e,Pz(n),i),s=o.map(u=>u.singleton);if(o.length===0)return new Set;let a=mn(e,t).forDefinitions(s,{semantic:r.semantic,sourceFallback:!0}),c=ni(a),l=new Set;for(let{singleton:u,classId:d}of o){let m=a.get(u.symbolId);(m?.semanticIncomplete||m?.semanticUnavailable||Mz(e,u,c))&&l.add(d)}return l}function Pz(e){let t=new Map;for(let n of e){let i=re(n.symbol);i&&t.set(JC(n.relativePath,i),n)}return t}function Dz(e,t,n){let i=[];for(let r of n){let o=Tz(e,t,r);o&&i.push({singleton:o,classId:r.symbolId})}return i}function Tz(e,t,n){if(YC(e,n.relativePath,n.startLine)!=="class")return null;let i=re(n.symbol);if(!i)return null;let r=Az(e,n.relativePath,i);return r?t.get(JC(n.relativePath,r))??null:null}function Mz(e,t,n){let i=re(t.symbol),r=n.get(t.symbolId);return!i||!r?!1:[...r].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!Gu(e,o,i))}function JC(e,t){return`${e}\0${t}`}function Az(e,t,n){let i=se(e,t);if(!i)return null;let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\bexport\\s+const\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*new\\s+${r}\\s*\\(`);return i.match(o)?.[1]??null}function Fz(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function Nz(e){let t=Hi(e);if("kind"in t)return!1;let n=t.descriptors;if(n.length<2)return!1;let i=n[n.length-1],r=n[n.length-2];return i?.suffix==="type"&&r?.suffix==="type"}function Md(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 VC(e,t,n){return!(Md(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function kz(e,t,n,i){let r=Jm(e,t.relativePath),o=re(t.symbol);if(!o)return!1;let s=i.get(t.relativePath);if(!s)return!1;let a=[...r.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 r.get(l)??[])a.push(m)}return!1}function YC(e,t,n){let i=se(e,t);if(!i)return"other";let r=i.split(`
449
- `),o=Math.max(0,n-2),s=Math.min(r.length-1,n+2);for(let a=o;a<=s;a++){let l=(r[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 _z(e,t){let n=se(e,t.relativePath);if(!n)return!1;let i=re(t.symbol);if(!i)return!1;let r=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${r}\\b`),s=n.split(`
450
- `);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function Oz(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 Sr,extname as sc}from"path";function zo(e,t){let{scope:n,maxLoc:i=15,limit:r=30,scanLimit:o}=t??{},s=new U(e),a=zz(s.fileDependencyGraph(n));return $t({candidates:()=>jz(e,s,n,i),orderCandidates:ua,scanLimit:o,profile:{name:"wrapper-candidates"},prepare:c=>({...Bz(e,s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>$z(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:r})}function Bz(e,t,n,i){let r=mn(e,t),o=ni(r.forDefinitions(n,{semantic:!1,sourceFallback:!1})),s=[];i.semantic&&$("wrapper.semantic-candidates",()=>{s=n.filter(h=>Ad(e,t,h,o).length<=1)},()=>({symbols:n.length,semanticCandidates:s.length}));let a=r.forDefinitions(s,{semantic:!0,sourceFallback:!1}),c=ni(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:yi(o,c),m=new Map(n.map(h=>[h.symbolId,h])),p=new Map;for(let h of n){let b=Ad(e,t,h,d);if(b.length>1||(p.set(h.symbolId,h),b.length!==1))continue;let v=b[0],y=XC(e,h.symbolId,v);if(!y)continue;let E=QC(t,e,v,h.symbol,y);E?.isFunctionLike&&m.has(E.symbolId)&&p.set(E.symbolId,m.get(E.symbolId))}let f=[...p.values()];return{callerFileMap:f.length===0?d:yi(d,ni(r.forDefinitions(f,{semantic:!1,sourceFallback:!0}))),incompleteSymbolIds:l,unavailableSymbolIds:u}}function $z(e,t,n,i){if(i.incompleteSymbolIds.has(n.symbolId)||i.unavailableSymbolIds.has(n.symbolId))return null;let r=Ad(e,t,n,i.callerFileMap);if(r.length!==1)return null;let o=r[0],s=XC(e,n.symbolId,o);if(!s)return null;let a=QC(t,e,o,n.symbol,s);if(a&&Ui(a.symbol))return null;let{fanIn:c,source:l}=Hz(i.callerFileMap,i.reverseFanIn,o,a);if(l==="function"?c<=3:c<=5)return null;let u=Kz(e,n,o,a);return{symbol:n.symbol,shortName:k(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:de(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?k(a.symbol):Sr(o),callerFanIn:c,actionTier:u.length>0?"signal":"direct",boundaryEvidence:u}}function jz(e,t,n,i){return t.productionCallableDefinitions({scope:n,minLoc:2,maxLoc:i,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0}).filter(r=>!ss(e,r))}function Ad(e,t,n,i){let r=Sr(n.relativePath,sc(n.relativePath)),o=[...i.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>Sr(s,sc(s))!==r).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return Ha(e,n,o).realConsumers}function XC(e,t,n){return e.get(`SELECT c.start_line, c.end_line
451
- FROM mentions m
452
- JOIN chunks c ON m.chunk_id = c.id
453
- JOIN documents d ON c.document_id = d.id
454
- WHERE m.symbol_id = ? AND m.role != 1 AND d.relative_path = ?
455
- LIMIT 1`,t,n)}function QC(e,t,n,i,r){let o=e.definitionsForFile(n),s=Uz(t,n,i,r.start_line,r.end_line);return Ge(o,s)}function Hz(e,t,n,i){if(i?.isFunctionLike){let r=[...e.get(i.symbolId)??[]].filter(o=>o!==i.relativePath);if(r.length>0)return{fanIn:r.length,source:"function"}}return{fanIn:Gz(t,n),source:"file"}}function Uz(e,t,n,i,r){let o=re(n);if(!o)return i;let s=Ki(e,t).get(o);if(!s||s.length===0)return i;for(let a of s)if(a>=i&&a<=r)return a;return i}function zz(e){let t=new Map;for(let[n,i]of e){t.has(n)||t.set(n,t.get(n)??0);for(let r of i)t.set(r,(t.get(r)??0)+1)}return t}function Gz(e,t){let n=e.get(t)??0;if(n>0)return n;let i=Sr(t,sc(t)),r=0;for(let[o,s]of e)o!==t&&Sr(o,sc(o))===i&&s>r&&(r=s);return r}function Kz(e,t,n,i){return Qa(e,t.relativePath,t.startLine,"wrapper","explicit ignore-wrapper comment",[{label:"wrapper name",value:k(t.symbol)},{label:"caller name",value:i?.symbol?k(i.symbol):Sr(n)},{label:"wrapper path",value:t.relativePath},{label:"caller path",value:n}])}var qz=25e3,Wz=2500,Vz=2500;function Jz(e){let t=bi(e);return t.symbols>=qz||t.documents>=Wz?Vz:void 0}function Fd(e,t={}){let{scope:n}=t,i=Jz(e),r=[],o=Ti(e,{scope:n,...Be.dead,scanLimit:i});for(let s of o.symbols)Ye(e,s.relativePath)||Ue(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&r.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of xo(e,{scope:n,...Be.isolated,scanLimit:i}))Ye(e,s.relativePath)||Ue(e,s.symbol,s.relativePath)||r.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of vo(e,{scope:n}))s.kind==="real"&&r.push(`cycle:${Yz(s.path)}`);for(let s of Io(e,{scope:n,...Be.similar,scanLimit:i}))r.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of ko(e,{scope:n,...Be.duplicateBodies,scanLimit:i}))r.push(`duplicate-bodies:${s.hash}:${s.functions.map(a=>a.symbol).sort().join("|")}`);for(let s of Mo(e,{scope:n,...Be.extract,scanLimit:i}))r.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of zo(e,{scope:n,...Be.wrappers,scanLimit:i}))r.push(`wrapper:${s.file}:${s.shortName}`);for(let s of _o(e,{scope:n,...Be.passthroughs,scanLimit:i}))r.push(`passthrough:${s.file}:${s.shortName}`);for(let s of Uo(e,{scope:n,...Be.stale,scanLimit:i}))r.push(`stale:${s.file}:${s.shortName}`);for(let s of Ho(e,{scope:n,...Be.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY}).results)s.kind!=="architecture-violation"&&r.push(`drift:${s.kind}:${s.file}:${s.dep}`);return r.push(...Fu(Co(e,{scope:n}))),[...new Set(r.map(Dd))].sort()}function Yz(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 Xz(e,t={}){let n=Fd(e,{scope:t.scope}),i=Td(e,t.path);return Bm(i,{version:1,findings:n},{spacing:2,trailingNewline:!0}),{path:i,findingCount:n.length}}function Qz(e,t={}){return KC(e,Fd(e,{scope:t.scope}),{path:t.path})}function Zz(e,t={}){let{scope:n,limit:i=30,scanLimit:r}=t,o=new U(e);return $t({candidates:()=>o.productionCallableDefinitions({scope:n,files:t.files,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}),filterCandidate:s=>eG(s.relativePath),scanLimit:r,profile:{name:"unused-params"},evaluate:s=>{let a=ee(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=Ki(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("_")||tG(c.get(d.name),a.paramsEndLine,a.endLine))break;l.unshift(d.name)}return l.length===0?null:{symbol:s.symbol,shortName:k(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:i})}function eG(e){let t=ye(e);return t==="typescript"||t==="tsx"||t==="javascript"}function tG(e,t,n){return e?e.some(i=>i>t&&i<=n):!1}var nG=new Set(en());function Nd(e,t){let{scope:n,minLoc:i=10,limit:r=30,scanLimit:o}=t??{},s=new U(e),a=t?.semantic!==!1,c=ZC(a,new Set,new Set);return{rows:$t({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:i,requireFunctionLikeSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,filterCandidate:iG,profile:{name:"complexity-hotspots"},prepare:u=>{let d=oG(e,u);(a?_t(e):null)?.materializeReferences(u,{prefetchCallees:!0});let p=tn(e,u,{semantic:a,semanticEvidence:fe}),f=s.calleeEvidenceMap(u,{semantic:a}),g=new Set([...p.incompleteSymbolIds,...f.incompleteSymbolIds]),h=new Set([...p.unavailableSymbolIds,...f.unavailableSymbolIds]);c=ZC(a,g,h);let b=new Map(u.map(v=>[v.symbolId,v]));return{callerMap:new Map([...p.rows].map(([v,y])=>[v,new Set(y.filter(E=>E.file!==b.get(v)?.relativePath).map(E=>E.file))])),calleeMap:f.rows,incompleteSymbolIds:g,unavailableSymbolIds:h,languageByFile:d,clojureCallableIds:sG(e,u,d),branchEstimates:DC(e,u)}},evaluate:(u,d)=>d.incompleteSymbolIds.has(u.symbolId)||d.unavailableSymbolIds.has(u.symbolId)?null:rG(u,d,i),orderResults:(u,d)=>d.score-u.score||d.loc-u.loc,limit:r}),coverage:c}}function ZC(e,t,n){let i=new Set([...t,...n]).size,r=e?t.size>0&&n.size>0?"incomplete-and-unavailable":t.size>0?"incomplete":n.size>0?"unavailable":"complete":"disabled";return{semanticEvidence:{enabled:e,status:r,incompleteSymbolCount:t.size,unavailableSymbolCount:n.size,excludedSymbolCount:i}}}function iG(e){return e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&nG.has(e.kind):!0}function rG(e,t,n){if(t.languageByFile.get(e.relativePath)==="clojure"&&!t.clojureCallableIds.has(e.symbolId))return null;let i=e.endLine-e.startLine+1;if(i<n)return null;let r=t.callerMap.get(e.symbolId)?.size??0,o=t.calleeMap.get(e.symbolId)??[],s=new Set,a=new Set;for(let m of o){let p=`${m.symbol}|${m.file}`;s.add(p),m.file!==e.relativePath&&a.add(p)}let c=a.size,l=s.size,u=t.branchEstimates.get(e.symbolId)??{branches:0,estimateBasis:"regex-fallback"},d=u.branches+1;return{symbol:e.symbol,shortName:k(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:i,fanIn:r,fanOut:c,calleeCount:l,branches:u.branches,estimateBasis:u.estimateBasis,score:Math.round(i/50*(r/5)*Math.max(c/5,1)*Math.max(d/5,1)*100)/100}}function oG(e,t){let n=[...new Set(t.map(o=>o.relativePath))];if(n.length===0)return new Map;let i=n.map(()=>"?").join(", "),r=e.all(`SELECT relative_path, language
456
- FROM documents
457
- WHERE relative_path IN (${i})`,...n);return new Map(r.map(o=>[o.relative_path,o.language?.toLowerCase()??null]))}function sG(e,t,n){let i=new Set,r=new Map;for(let o of t){if(n.get(o.relativePath)!=="clojure")continue;let s=r.get(o.relativePath);s||(s=new Set((ee(e,o.relativePath)?.callables??[]).map(a=>`${a.name}:${a.startLine}`)),r.set(o.relativePath,s)),s.has(`${o.leaf}:${o.startLine}`)&&i.add(o.symbolId)}return i}import{readdirSync as aG}from"fs";import{basename as cG,join as ex}from"path";function lG(e,t,n={}){let i=new Set(e),r=new Set(t),o=[...r].filter(a=>!i.has(a)).sort(),s=n.allowExtra?[]:[...i].filter(a=>!r.has(a)).sort();return{missing:o,extra:s}}function uG(e,t){let n=dG(e,t.file,t.keys);if(!n.ok)return{name:t.name,file:t.file,status:"unavailable",missing:[],extra:[],unavailableReason:n.reason};let i=yG(e.config.projectRoot,t.mustEqual),r=lG(n.keys,i,{allowExtra:t.allowExtra??!1}),o=r.missing.length>0||r.extra.length>0?"violated":"ok";return{name:t.name,file:t.file,status:o,missing:r.missing,extra:r.extra}}function nx(e,t){return t.map(n=>uG(e,n))}function dG(e,t,n){return n.type==="markdown-list"?hG(e,t,n.marker):mG(e,t,n)}function mG(e,t,n){if(!se(e,t))return{ok:!1,reason:`file not found: ${t}`};let r=ye(t);if(!r)return{ok:!1,reason:`unsupported file type for ${n.type} extraction: ${t}`};let o=ae(e,t);if(!o)return{ok:!1,reason:`tree-sitter parser unavailable for ${r} (${t}) \u2014 contract skipped, not silently passed`,disclosedUnavailable:{language:r,reason:"parser-unavailable"}};let s=n.type==="object-literal-keys"?pG(o,n.identifier):gG(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 ix(e){let t=e.childForFieldName("value");return t?t.type==="as_expression"||t.type==="satisfies_expression"?t.namedChild(0):t:null}function pG(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let r=ix(n);if(r?.type==="object")return fG(r)}return null}function fG(e){let t=new Set;for(let n of e.namedChildren)if(n.type==="pair"){let i=n.childForFieldName("key");i&&t.add(rx(i.text))}else n.type==="shorthand_property_identifier"&&t.add(n.text);return[...t].sort()}function gG(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let r=ix(n);if(r?.type!=="array")continue;let o=new Set;for(let s of r.namedChildren)s.type==="string"&&o.add(rx(s.text));return[...o].sort()}return null}function rx(e){return e.length>=2&&(e[0]==="'"&&e.endsWith("'")||e[0]==='"'&&e.endsWith('"'))?e.slice(1,-1):e}function hG(e,t,n){let i=se(e,t);if(!i)return{ok:!1,reason:`file not found: ${t}`};let r=ox(i,n);return r===null?{ok:!1,reason:`no <!-- BEGIN GENERATED ${n} --> ... <!-- END GENERATED ${n} --> block in ${t}`}:{ok:!0,keys:sx(r)}}function ox(e,t){let n=He(t),r=new RegExp(`<!--\\s*BEGIN GENERATED ${n}\\s*-->([\\s\\S]*?)<!--\\s*END GENERATED ${n}\\s*-->`).exec(e);return r?r[1]:null}function sx(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 yG(e,t){switch(t.type){case"top-level-dirs":return tx(ex(e,t.path));case"file-glob":return[...new Set(_a(e,t.pattern).map(n=>cG(n)))].sort();case"registered-commands":return bG(e);case"builtin-skills":return tx(ex(e,"skills"))}}function tx(e){let t;try{t=aG(e,{withFileTypes:!0})}catch{return[]}return t.filter(n=>n.isDirectory()&&!n.name.startsWith(".")).map(n=>n.name).sort()}function bG(e){let t;try{t=nt(e,"docs/COMMAND_REFERENCE.md",{maxBytes:8*1024*1024,inputKind:"generated command reference"})}catch(i){if(!Ct(i))throw i;return[]}let n=ox(t,"COMMAND REFERENCE");return n?sx(n):[]}function Nn(e){return e.scoreCount??e.count}function lx(e){let t=RG(e),{breakdown:n,pressure:i}=EG(e),r=cx(n,"risk"),o=cx(n,"hygiene"),s=SG(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(r,o),riskScore:r,hygieneScore:o,scoreBreakdown:n,overview:{documents:e.statsResult.documents,symbols:e.statsResult.symbols,indexSizeBytes:e.statsResult.indexSizeBytes},findings:{deadSymbols:e.dead.count,deadLoc:e.dead.loc,isolatedSymbols:e.isolated.count,isolatedLoc:e.isolated.loc,cycles:e.realCycleCount,similarPairs:e.similarCount,duplicateBodyGroups:e.duplicateBodies.count,duplicateBodyLoc:e.duplicateBodies.loc,twinDriftGroups:e.twinDrift.count,twinDriftLoc:e.twinDrift.loc,reactComponentDuplicatePairs:e.reactComponentDuplicates.count,reactHookCandidatePairs:e.reactHookCandidates.count,reactHookCandidateScoreCount:Nn(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:Nn(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:Nn(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:vG(e),validation:xG(e),suppressions:e.suppressions,actions:t,pressure:i,topComplexity:e.complexity.top,coverage:s,warnings:a.length>0?a:void 0}}function SG(e){let t=e.complexity.coverage.semanticEvidence.status;return{status:e.evidenceCoverage.some(i=>i.semanticEvidence.status!=="complete"&&i.semanticEvidence.status!=="disabled")?"incomplete":t==="disabled"?"semantic-disabled":t==="complete"?"complete":"incomplete",complexity:e.complexity.coverage,phases:e.evidenceCoverage}}function vG(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:CG(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 CG(e){let t=e.gitEvidence?.fileStats;return t?e.complexity.top.map(n=>{let i=n.file?t[n.file]?.changes??0:0;return{...n,changes:i,weighted:gn(n.score*Math.log2(1+i))}}).sort((n,i)=>i.weighted-n.weighted):null}function xG(e){let t=e.gitEvidence?.fileStats;if(!t)return null;let n={dead:e.dead.files??[],isolated:e.isolated.files??[],twinDrift:e.twinDrift.files??[],wrappers:e.wrappers.files??[],passthroughs:e.passthroughs.files??[],stale:e.stale.files??[],reactComponents:e.reactComponentDuplicates.files??[],reactHooks:e.reactHookCandidates.files??[],reactLargeComponents:e.reactLargeComponentPressure.files??[],vueComponents:e.vueComponentDuplicates.files??[],vueComposables:e.vueComposableCandidates.files??[],vueLargeViews:e.vueLargeViewPressure.files??[]},i=new Set(Object.values(n).flat()),r=0,o=0,s=0;for(let[u,d]of Object.entries(t))i.has(u)?r+=d.fixChanges:(o+=d.fixChanges,s+=1);let a=i.size>0?gn(r/i.size):0,c=s>0?gn(o/s):0,l={};for(let[u,d]of Object.entries(n)){let m=new Set(d);if(m.size===0)continue;let p=0;for(let g of m)p+=t[g]?.fixChanges??0;let f=gn(p/m.size);l[u]={flaggedFiles:m.size,fixDensity:f,lift:c>0?gn(f/c):null}}return{flaggedFiles:i.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:i.size>0&&c>0?gn(a/c):null,byCategory:l,validationBasis:{method:"subject-regex",commitsScanned:e.gitEvidence?.commitsScanned??0}}}function gn(e){return Math.round(e*100)/100}function ux(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function ac(e,t="existing shared infrastructure discount"){let n=Nn(e);return Math.abs(n-e.count)<.01?"":` (${ux(n)} score-weighted after ${t})`}function Go(e,t){let n=Nn(e),i=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?i:`${i} (${ux(n)} score-weighted)`}function RG(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${ac(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${ac(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${ac(e.wrappers,"boundary-evidence discount")} \u2014 inspect whether each is indirection or an intentional API, framework, or ownership boundary`,effort:"low",impact:"low",count:e.wrappers.count,locRecoverable:e.wrappers.loc}),e.passthroughs.count>0&&t.push({category:"Passthrough functions",evidence:"heuristic",description:`${e.passthroughs.count} functions that literally forward to one callee \u2014 inspect whether each is unnecessary indirection or an intentional boundary`,effort:"low",impact:"low",count:e.passthroughs.count,locRecoverable:e.passthroughs.loc}),e.stale.count>0){let r=[];e.stale.unused>0&&r.push(`${e.stale.unused} unused`),e.stale.singleUse>0&&r.push(`${e.stale.singleUse} single-consumer (not in types file)`),t.push({category:"Stale abstractions",evidence:"heuristic",description:`${r.join(", ")} \u2014 review public, runtime-registration, and ownership evidence before removing, moving, or inlining`,effort:"low",impact:"medium",count:e.stale.count,locRecoverable:e.stale.loc})}if(e.drift.count>0){let r=[];e.drift.unusedImports>0&&r.push(`${e.drift.unusedImports} unused imports`),e.drift.architectureViolations>0&&r.push(`${e.drift.architectureViolations} declared architecture violations`),t.push({category:"Structural drift",evidence:"heuristic",description:`${r.join(", ")} \u2014 repair direct dependency-rule breaks; inspect boundary signals with \`drift --architecture\``,effort:e.drift.architectureViolations>0?"medium":"low",impact:e.drift.architectureViolations>0?"medium":"low",count:e.drift.count,locRecoverable:0})}if(e.coverageContracts.count>0&&t.push({category:"Coverage contract drift",evidence:"graph-fact",description:`${e.coverageContracts.count} configured coverage contract(s) drifted from their ground-truth source (enumeration rot) \u2014 run \`codebaseiq health --json\` for the missing/extra keys`,effort:"low",impact:"medium",count:e.coverageContracts.count,locRecoverable:0}),e.gitEvidence&&e.gitEvidence.hiddenCoupling.pairCount>0){let r=e.gitEvidence.hiddenCoupling.top[0];t.push({category:"Hidden coupling",evidence:"change-graph",description:`${e.gitEvidence.hiddenCoupling.pairCount} file pair(s) co-change without a structural link`+ac({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:e.gitEvidence.hiddenCoupling.scoreCount},"broad/stale-history discount")+(r?` (e.g. ${r.fileA} \u2194 ${r.fileB})`:"")+" \u2014 inspect whether a shared concept, generated artifact, or coordinated contract explains the history",effort:"medium",impact:"high",count:e.gitEvidence.hiddenCoupling.pairCount,locRecoverable:0})}let n={high:3,medium:2,low:1},i={low:3,medium:2,high:1};return t.sort((r,o)=>{let s=n[r.impact]*i[r.effort];return n[o.impact]*i[o.effort]-s}),t}var ax={"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 cx(e,t){let n=e.filter(i=>i.kind===t).reduce((i,r)=>i+r.points,0);return Math.max(0,Math.min(100,100-n))}function EG(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),i=[],r=[],o=(R,C,L)=>{C>0&&i.push({axis:R,points:C,detail:L,kind:ax[R]??"hygiene"})},s=(R,C,L,I,x,D,_)=>{let P=Math.max(I,1);if(L<=P)return;let T=L/P,F=Math.min(x,Math.ceil(Math.log2(T)*D));if(F<=0)return;let W=ax[R]??"hygiene";r.push({axis:R,category:C,kind:W,count:L,threshold:gn(P),ratio:gn(T),extraPenalty:F}),o(R,F,`${L} ${_} exceed pressure threshold ${gn(P)} (${gn(T)}x)`)},a=e.dead.count/n;o("dead-code",Math.min(20,Math.round(a*200)),`${e.dead.count} dead symbols (${e.dead.loc} LOC deletable)`);let c=e.isolated.count/n;o("isolated",Math.min(10,Math.round(c*200)),`${e.isolated.count} isolated symbols (${e.isolated.loc} LOC deletable)`),o("cycles",Math.min(15,e.realCycleCount*5),`${e.realCycleCount} real dependency cycle(s)`);let l=e.similarCount/n*1e3;o("similar",Math.min(10,Math.round(l)),`${e.similarCount} similar function pair(s)`);let u=e.duplicateBodies.count/n*1e3;o("duplicate-bodies",Math.min(10,Math.round(u*2)),`${e.duplicateBodies.count} exact duplicate small-body group(s) (${e.duplicateBodies.loc} duplicate LOC)`);let d=e.twinDrift.count/n*1e3;o("twin-drift",Math.min(10,Math.round(d*2)),`${e.twinDrift.count} drifted twin implementation group(s) (same or near-same name, diverged or identical bodies)`);let m=e.reactComponentDuplicates.count/t*1e3;o("react-component-duplicates",Math.min(10,Math.round(m)),`${e.reactComponentDuplicates.count} duplicated React component pair(s)`);let p=Nn(e.reactHookCandidates),f=p/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(f)),Go(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=Nn(e.vueComposableCandidates),v=b/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(v)),Go(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=Nn(e.wrappers);o("wrappers",Math.min(3,E),Go(e.wrappers,"wrapper candidate(s)"));let w=Nn(e.passthroughs);o("passthroughs",Math.min(3,w),Go(e.passthroughs,"passthrough candidate(s)")),o("stale-abstractions",Math.min(8,e.stale.unused),`${e.stale.unused} unused stale abstraction(s); ${e.stale.singleUse} single-consumer signal(s)`);let S=e.drift.direct/t;if(o("drift",Math.min(5,Math.round(S*50)),`${e.drift.direct} direct drift finding(s); ${e.drift.signal} signal drift finding(s)`),o("complexity",Math.min(5,e.complexity.extremeCount*2),`${e.complexity.extremeCount} extreme complexity hotspot(s)`),e.gitEvidence){let R=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(R/10)),Go({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:R},"co-changing pair(s) without a structural link"))}if(s("cycles-pressure","Circular dependencies",e.realCycleCount,3,10,3,"cycle(s)"),s("complexity-pressure","Extreme complexity",e.complexity.extremeCount,3,5,2,"extreme complexity hotspot(s)"),e.gitEvidence){let R=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",R,50,10,4,"score-weighted co-changing pair(s)")}return s("similar-pressure","Similar functions",e.similarCount,Math.max(50,n*.01),8,4,"similar function pair(s)"),s("duplicate-bodies-pressure","Duplicate function bodies",e.duplicateBodies.count,Math.max(20,n*.005),8,4,"exact duplicate small-body group(s)"),s("twin-drift-pressure","Drifted twin implementations",e.twinDrift.count,Math.max(20,n*.005),8,4,"drifted twin implementation group(s)"),s("react-component-duplicates-pressure","Duplicated React components",e.reactComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated React component pair(s)"),s("react-hook-candidates-pressure","Duplicated React hook behavior",p,Math.max(10,t*.01),8,4,"duplicated React behavior pair(s)"),s("react-large-component-pressure-pressure","Large React components",e.reactLargeComponentPressure.count,Math.max(10,t*.01),4,2,"large React component pressure file(s)"),s("vue-component-duplicates-pressure","Duplicated Vue components",e.vueComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated Vue component pair(s)"),s("vue-composable-candidates-pressure","Duplicated Vue behavior",b,Math.max(10,t*.01),8,4,"duplicated Vue behavior pair(s)"),s("vue-large-view-pressure-pressure","Large Vue views",e.vueLargeViewPressure.count,Math.max(10,t*.01),4,2,"large Vue view pressure file(s)"),s("extract-pressure","Extraction candidates",e.extractCount,Math.max(50,n*.01),4,2,"extraction candidate(s)"),s("wrappers-pressure","Wrapper functions",E,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",w,50,4,2,"passthrough candidate(s)"),s("stale-abstractions-pressure","Single-consumer stale abstraction signals",e.stale.singleUse,Math.max(50,n*.02),4,2,"single-consumer stale abstraction signal(s)"),s("drift-pressure","Structural drift signals",e.drift.signal,Math.max(10,t*.1),4,2,"signal drift finding(s)"),{breakdown:i,pressure:r}}import{getHeapStatistics as wG}from"v8";var IG=64*1024*1024;function kd(){let e=globalThis.gc;if(!e)return;let t=wG();t.heap_size_limit-t.used_heap_size<IG||e()}var LG=50,PG=25e3,DG=2500,dx=2500,mx=50,TG=10,cc=["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"],MG={overview:(e,t,n,i)=>({phase:"overview",statsResult:i,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:_G(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:OG(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:BG(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:$G(e,t,n)}),"duplicate-bodies":(e,t,n)=>({phase:"duplicate-bodies",duplicateBodies:HG(e,t,n)}),"twin-drift":(e,t,n)=>({phase:"twin-drift",twinDrift:UG(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:zG(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:GG(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:KG(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:qG(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:WG(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:VG(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:jG(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:JG(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:YG(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:XG(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:tK(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:nK(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:QG(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:ZG(e,n)}),"coverage-contracts":(e,t,n)=>({phase:"coverage-contracts",coverageContracts:eK(e,n)})};function _d(e,t,n={}){return AG(e,[t],n)[0]}function AG(e,t,n={}){return FG(e,n.full!==!1,(i,r)=>{let o={...r,releaseCachesBetweenPhases:!1};return t.map(s=>kG(e,s,n.scope,o,i))})}function FG(e,t,n){let i=bi(e),r=iK(i,t);try{return n(i,r)}finally{Tu(e,{semanticProvider:!0}),kd()}}function Od(e){return lx(NG(e))}function NG(e){let t=je(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,evidenceCoverage:e.map(i=>({phase:i.phase,semanticEvidence:i.evidenceCoverage})),dead:je(e,"dead").dead,isolated:je(e,"isolated").isolated,realCycleCount:je(e,"cycles").realCycleCount,similarCount:je(e,"similar").similarCount,duplicateBodies:je(e,"duplicate-bodies").duplicateBodies,twinDrift:je(e,"twin-drift").twinDrift,reactComponentDuplicates:je(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:je(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:je(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:je(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:je(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:je(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:je(e,"extract-candidates").extractCount,wrappers:je(e,"wrapper-candidates").wrappers,passthroughs:je(e,"passthrough-candidates").passthroughs,stale:je(e,"stale-abstractions").stale,drift:je(e,"drift").drift,complexity:je(e,"complexity-hotspots").complexity,gitEvidence:px(e,"git-evidence")?.gitEvidence??null,suppressions:px(e,"suppressions")?.suppressions??null,coverageContracts:je(e,"coverage-contracts").coverageContracts}}function px(e,t){return e.find(n=>n.phase===t)}function je(e,t){let n=e.find(i=>i.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function kG(e,t,n,i,r){Qf(e);let o=MG[t](e,n,i,r),s=Zf(e),a=s.incompleteSymbolIds.size,c=s.unavailableSymbolIds.size,l=i.semantic?a>0&&c>0?"incomplete-and-unavailable":a>0?"incomplete":c>0?"unavailable":"complete":"disabled";return{...o,evidenceCoverage:{enabled:i.semantic,status:l,incompleteSymbolCount:a,unavailableSymbolCount:c}}}function _G(e,t,n){return $e(e,n,"dead",()=>{let i=Ti(e,{scope:t,...Be.dead,scanLimit:n.candidateScanLimit,semantic:n.semantic});return lc(sK(e,i.symbols))})}function OG(e,t,n){return $e(e,n,"isolated",()=>{let i=xo(e,{scope:t,...Be.isolated,scanLimit:n.candidateScanLimit,semantic:n.semantic});return lc(aK(e,i))})}function BG(e,t,n){return $e(e,n,"cycles",()=>vo(e,{scope:t}).filter(r=>r.kind==="real").length)}function $G(e,t,n){let i=$e(e,n,"similar",()=>ju(e,{scope:t,...Be.similar,scanLimit:n.candidateScanLimit,semantic:n.semantic}));return Math.min(i,n.candidateResultLimit)}function jG(e,t,n){return $e(e,n,"extract-candidates",()=>Mo(e,{scope:t,...Be.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}).length)}function HG(e,t,n){return $e(e,n,"duplicate-bodies",()=>{let i=ko(e,{scope:t,...Be.duplicateBodies,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),r=new Set,o=0;for(let s of i)for(let a of s.functions.slice(1))r.add(a.file),o+=a.loc;return{count:i.length,loc:o,files:[...r]}})}function UG(e,t,n){return $e(e,n,"twin-drift",()=>{let i=Xa(e,{scope:t,...Be.twinDrift,scanLimit:n.candidateScanLimit}).filter(s=>s.relationship==="divergent"||s.relationship==="identical"),r=new Set,o=0;for(let s of i)for(let a of s.members)r.add(a.file),o+=a.loc;return{count:i.length,loc:o,files:[...r].sort()}})}function zG(e,t,n){return $e(e,n,"react-component-duplicates",()=>{let i=Lo(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Bd(i)})}function GG(e,t,n){return $e(e,n,"react-hook-candidates",()=>{let i=Po(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return hx(i,lK)})}function KG(e,t,n){return $e(e,n,"react-large-component-pressure",()=>{let i=Hu(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return cK(i)})}function qG(e,t,n){return $e(e,n,"vue-component-duplicates",()=>{let i=Do(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Bd(i)})}function WG(e,t,n){return $e(e,n,"vue-composable-candidates",()=>{let i=To(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return hx(i,uK)})}function VG(e,t,n){return $e(e,n,"vue-large-view-pressure",()=>{let i=Uu(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return lc(i)})}function JG(e,t,n){return $e(e,n,"wrapper-candidates",()=>{let i=zo(e,{scope:t,...Be.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return gx(i,dK)})}function YG(e,t,n){return $e(e,n,"passthrough-candidates",()=>{let i=_o(e,{scope:t,...Be.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return gx(i,mK)})}function XG(e,t,n){return $e(e,n,"stale-abstractions",()=>{let i=Uo(e,{scope:t,...Be.stale,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}),r=i.filter(o=>o.consumers===0).length;return{count:i.length,loc:i.reduce((o,s)=>o+s.loc,0),files:[...new Set(i.map(o=>o.file))],unused:r,singleUse:i.length-r}})}function QG(e,t){return $e(e,t,"git-evidence",()=>{let n=Vt(e,{historyMode:t.gitHistoryMode}),i=n.fileChurn();if(!i)return null;let r=n.commitHistory(),o=Fo(e,void 0,{limit:t.candidateResultLimit,historyMode:t.gitHistoryMode}),s={};for(let[a,c]of i)s[a]={changes:c.changes,fixChanges:c.fixChanges};return{amplification:n.changeAmplification(),hiddenCoupling:{pairCount:o.findings.length,scoreCount:$d(o.findings.reduce((a,c)=>a+fx(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:fx(a),subjectContext:a.subjectContext}))},fileStats:s,commitsScanned:r?.commits.length??0}})}function ZG(e,t){return $e(e,t,"suppressions",()=>{let n=tc(e);return{total:n.total,byCategory:{...n.byCategory}}})}function eK(e,t){return $e(e,t,"coverage-contracts",()=>{let n=e.config.coverageContracts??[],r=nx(e,n).filter(o=>o.status!=="ok");return{count:r.length,loc:0,files:[...new Set(r.map(o=>o.file))].sort()}})}function tK(e,t,n){return $e(e,n,"drift",()=>{let i=Ho(e,{scope:t,...Be.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY,semantic:n.semantic}),r=i.results.filter(a=>a.kind!=="pattern-deviation"),o=r.filter(a=>a.actionTier==="direct").length,s=r.length-o;return{count:r.length,unusedImports:i.unusedImports,architectureViolations:i.architectureViolations,layerViolations:i.layerViolations,direct:o,signal:s}})}function nK(e,t,n){return $e(e,n,"complexity-hotspots",()=>{let i=Nd(e,{scope:t,minLoc:10,limit:n.complexityResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return{top:i.rows.slice(0,5).map(r=>({symbol:r.shortName,score:r.score,file:r.file})),extremeCount:i.rows.filter(r=>r.score>LG).length,coverage:i.coverage}})}function iK(e,t){let n=e.symbols>=PG||e.documents>=DG,i=t?Number.POSITIVE_INFINITY:mx,r=t?Number.POSITIVE_INFINITY:TG;return!n||t?{candidateScanLimit:void 0,candidateResultLimit:i,complexityResultLimit:r,semantic:!0,gitHistoryMode:t?"full":"bounded",releaseCachesBetweenPhases:!0,warnings:t&&n?["Large index detected; running health without candidate scan or result caps because full mode is enabled."]:[]}:{candidateScanLimit:dx,candidateResultLimit:i,complexityResultLimit:r,semantic:!1,gitHistoryMode:"bounded",releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${dx} symbols and reported their top ${mx} findings. Enable full mode for unbounded candidate counts.`]}}function rK(e,t){t.releaseCachesBetweenPhases&&(Tu(e),kd())}function $e(e,t,n,i){oK(n);try{return i()}finally{rK(e,t)}}function oK(e){process.env.CODEBASEIQ_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function sK(e,t){return t.filter(n=>!Ye(e,n.relativePath)&&!Ue(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function aK(e,t){return t.filter(n=>!Ye(e,n.relativePath)&&!Ue(e,n.symbol,n.relativePath))}function lc(e){let t=new Set;for(let n of e){let i=n.relativePath??n.file;i&&t.add(i)}return{count:e.length,loc:e.reduce((n,i)=>n+i.loc,0),files:[...t]}}function gx(e,t){return{...lc(e),scoreCount:$d(e.reduce((i,r)=>i+t(r),0))}}function cK(e){let t=new Map;for(let n of e)t.set(n.file,Math.max(t.get(n.file)??0,n.loc));return{count:t.size,loc:[...t.values()].reduce((n,i)=>n+i,0),files:[...t.keys()]}}function Bd(e){let t=new Map;for(let n of e)t.set(n.fileA,Math.max(t.get(n.fileA)??0,n.locA)),t.set(n.fileB,Math.max(t.get(n.fileB)??0,n.locB));return{count:e.length,loc:[...t.values()].reduce((n,i)=>n+i,0),files:[...t.keys()]}}function hx(e,t){return{...Bd(e),scoreCount:$d(e.reduce((i,r)=>i+t(r),0))}}function lK(e){let t=e.sharedHooks.length>0,n=yx({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:bx(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function uK(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=yx({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:bx(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function yx(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!vx.has(Sx(t))).length+Math.min(e.functions.length,3)}function bx(e,t,n){let i=[...e,...t,...n].map(Sx);return i.length>0&&i.every(r=>vx.has(r))}function Sx(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function dK(e){return e.actionTier==="signal"?.25:1}function mK(e){return e.actionTier==="signal"?.25:1}function fx(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 $d(e){return Math.round(e*100)/100}var vx=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 pK(e,t,n,i={}){let r=$u(e,t,n,i);return r?{symbolA:r.symbolA,symbolB:r.symbolB,similarity:r.similarity,sharedCallees:r.sharedEvidence,uniqueToA:r.uniqueToA,uniqueToB:r.uniqueToB,consolidationStrategy:r.consolidationStrategy}:null}function fK(e,t,n={}){let i=bo(e,t,{families:["dataflow"],...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.maxEdges!==void 0?{maxEdges:n.maxEdges}:{}});return{kind:"value-flow",targets:i.targets,edges:i.edges,coverage:{status:i.coverage.status,basis:"proved-bounded-static-value-flow",analysisBasis:"partial-system-definition-use",providers:["bounded-static-value-flow","typescript-local-dependence"],supportedRelations:["compiler-identified local definitions reaching local reads through a TypeScript control-flow graph","right-hand-side local reads supplying assignments and declarations","candidate closure captures and bounded same-owner field flow with explicit evidence strength","direct argument-to-parameter forwarding at compiler-resolved calls","bounded mechanically derived static arguments","callee return value to a consumed compiler-resolved call result"],unsupportedRelations:["general heap alias and cross-instance field points-to flow","exceptional control and value flow","closure invocation order","downstream local definition-use after a call result","dynamic calls not resolved by the semantic provider"],graph:i.coverage}}}var gK=/:\d+(?:-\d+)?$/u;function hK(e,t,n={}){let i=n.direction??"backward",r=n.maxDepth??3;if(!Number.isSafeInteger(r)||r<0)throw new RangeError(`Dependence-slice depth must be a non-negative safe integer; received ${r}.`);let o=gK.test(t),s=bo(e,o?{locations:[t]}:{symbols:[t]},{families:["execution","runtime","dataflow","ownership"],maxDepth:r+1,maxEdges:n.maxEdges??200}),a=new Set(s.targets.flatMap(d=>d.nodeIds)),c=new Set(a),l=new Map;Cx(s.edges,c,l,0);for(let d=1;d<=r;d+=1){let m=[];for(let p of s.edges)if(i==="backward"?c.has(p.to.id):c.has(p.from.id)){let f=i==="backward"?p.from.id:p.to.id;if(c.has(f))continue;m.push(f),l.set(p.id,d)}if(m.length===0)break;for(let p of m)c.add(p);Cx(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"&&!yK(d)})).sort((d,m)=>d.traversalDepth-m.traversalDepth||d.family.localeCompare(m.family)||d.from.label.localeCompare(m.from.label)||d.to.label.localeCompare(m.to.label));return{kind:"dependence-slice",direction:i,criterion:t,targets:s.targets,nodeIds:[...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 Cx(e,t,n,i){let r=!0;for(;r;){r=!1;for(let o of e)o.family!=="ownership"||!t.has(o.from.id)||t.has(o.to.id)||(t.add(o.to.id),n.set(o.id,i),r=!0)}}function yK(e){return e.semanticFamily==="control"&&e.sourceKind==="control-dependence"}function bK(e,t={}){let{scope:n,limit:i}=t,r=new U(e),o=LK([...SK(e,n),...xK(e,r,n)]);return PK(o),i?o.slice(0,i):o}function SK(e,t){let n=[];for(let i of vK(e,t)){if(e.isIgnored(i.barrel_path)||e.isIgnored(i.original_path)||Dl(e,i.barrel_path)||se(e,i.barrel_path)&&cs(e,i.barrel_path).length===0)continue;let r=CK(e,i),o=r?.barrel_consumers??0,s=r?.direct_consumers??0;o!==0||s!==0||n.push({barrelFile:i.barrel_path,symbol:i.symbol,shortName:k(i.symbol),originalFile:i.original_path,barrelConsumers:o,directConsumers:s,...Rx(e,i.barrel_path)})}return n}function vK(e,t){let n=t?"AND barrel_d.relative_path LIKE ?":"",i=t?[`%${t}%`]:[];return e.all(`WITH barrel_refs AS MATERIALIZED (
458
- SELECT DISTINCT
459
- barrel_d.id AS barrel_doc_id,
460
- barrel_d.relative_path AS barrel_path,
461
- m.symbol_id
462
- FROM documents barrel_d
463
- JOIN chunks c ON c.document_id = barrel_d.id
464
- JOIN mentions m ON m.chunk_id = c.id
465
- WHERE m.role != 1
466
- AND (barrel_d.relative_path LIKE '%/index.ts'
467
- OR barrel_d.relative_path LIKE '%/index.js'
468
- OR barrel_d.relative_path = 'index.ts'
469
- OR barrel_d.relative_path = 'index.js')
470
- ${e.pathExclusionsFor("barrel_d")}
471
- ${n}
472
- ),
473
- sym_def AS MATERIALIZED (
474
- SELECT m2.symbol_id, c2.document_id
475
- FROM barrel_refs br
476
- -- Keep the bounded barrel-symbol set on the outer side. An ordinary
477
- -- JOIN lets SQLite scan every definition mention before applying the
478
- -- barrel-symbol bloom filter on large indexes.
479
- CROSS JOIN mentions m2 ON m2.symbol_id = br.symbol_id
480
- AND m2.role = 1
481
- JOIN chunks c2 ON m2.chunk_id = c2.id
482
- GROUP BY m2.symbol_id
483
- )
484
- SELECT DISTINCT
485
- br.barrel_doc_id,
486
- br.barrel_path,
487
- gs.id AS symbol_id,
488
- gs.symbol AS symbol,
489
- orig_d.id AS original_doc_id,
490
- orig_d.relative_path AS original_path
491
- FROM barrel_refs br
492
- JOIN global_symbols gs ON br.symbol_id = gs.id
493
- JOIN sym_def ON sym_def.symbol_id = gs.id
494
- JOIN documents orig_d ON sym_def.document_id = orig_d.id
495
- WHERE orig_d.id != br.barrel_doc_id
496
- ${e.pathExclusionsFor("orig_d")}
497
- ${e.symbolNoiseFor("gs")}
498
- -- Only function-level symbols (ending with ().), not module-level
499
- AND gs.symbol LIKE '%().'
500
- ORDER BY br.barrel_path, gs.symbol`,...i)}function CK(e,t){return e.get(`SELECT
501
- SUM(CASE WHEN uses_barrel = 1 THEN 1 ELSE 0 END) AS barrel_consumers,
502
- SUM(CASE WHEN uses_barrel = 0 THEN 1 ELSE 0 END) AS direct_consumers
503
- FROM (
504
- SELECT
505
- consumer_d.id AS consumer_doc_id,
506
- MAX(CASE WHEN EXISTS (
507
- SELECT 1
508
- FROM mentions barrel_m
509
- JOIN chunks barrel_c ON barrel_m.chunk_id = barrel_c.id
510
- WHERE barrel_c.document_id = consumer_d.id
511
- AND barrel_m.role != 1
512
- AND barrel_m.symbol_id IN (
513
- SELECT m2.symbol_id
514
- FROM mentions m2
515
- JOIN chunks c2 ON m2.chunk_id = c2.id
516
- WHERE c2.document_id = ?
517
- AND m2.role != 1
518
- )
519
- ) THEN 1 ELSE 0 END) AS uses_barrel
520
- FROM mentions ref_m
521
- JOIN chunks ref_c ON ref_m.chunk_id = ref_c.id
522
- JOIN documents consumer_d ON ref_c.document_id = consumer_d.id
523
- WHERE ref_m.symbol_id = ?
524
- AND ref_m.role != 1
525
- AND consumer_d.id != ?
526
- AND consumer_d.id != ?
527
- ${e.pathExclusionsFor("consumer_d")}
528
- GROUP BY consumer_d.id
529
- )`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function xK(e,t,n){let i=[],r=IK(e);for(let o of RK(e,n))Ex(r,o,o)>0||i.push(...EK(e,t,o,r));return i}function RK(e,t){return he(e,{scope:t,includeIgnored:!1}).filter(n=>cs(e,n).length>0||Lr(e,n).length>0)}function EK(e,t,n,i){let r=cs(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>xx(e,t,n,s.sourcePath,i,[wK(s.specifier)])),o=Lr(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>xx(e,t,n,s.sourcePath,i,s.kind==="named"&&s.names.length>0?s.names:[s.kind==="star"?`* from ${s.sourcePath}`:`* namespace from ${s.sourcePath}`]));return[...r,...o]}function xx(e,t,n,i,r,o){let s=t.definitionsForFile(i);return o.map(a=>{let c=s.find(l=>l.leaf===a);return{barrelFile:n,symbol:c?.symbol??`source-reexport:${n}:${a}`,shortName:c?k(c.symbol):a,originalFile:i,barrelConsumers:0,directConsumers:Ex(r,i,n),...Rx(e,n)}})}function wK(e){return e.split("::").at(-1)?.split("/").at(-1)?.replace(/\.[^.]+$/,"")??e}function Rx(e,t){return wn(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 IK(e){let t=new Map;for(let n of he(e,{includeIgnored:!1}))for(let i of Ce(e,n)){if(!i.sourcePath)continue;let r=t.get(i.sourcePath)??new Set;r.add(n),t.set(i.sourcePath,r)}return t}function Ex(e,t,n){let i=e.get(t);return i?i.size-(i.has(n)?1:0):0}function LK(e){let t=new Set,n=[];for(let i of e){let r=`${i.barrelFile}|${i.symbol}|${i.originalFile}`;t.has(r)||(t.add(r),n.push(i))}return n}function PK(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function DK(e,t={}){let{samples:n=50,scope:i,maxDisagreements:r=5}=t,o=new U(e),s=TK(o.productionCallableDefinitions({scope:i,minLoc:2,requireFunctionLikeSymbol:!0}),n),a=MK(e,s);if(s.length===0||!a)return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let c={references:wx(),callees:wx()},l=[],u=0,d=a==="semantic"?Ws(e,s):{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set},m=a==="semantic"?Vs(e,s):{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set},p=a==="source"?NK(e,o,s):null;for(let f of s){let g=uc(f,a==="semantic"?(d.rows.get(f.symbolId)??[]).map(R=>R.file):[...p?.referencesBySymbolId.get(f.symbolId)??[]]),h=uc(f,a==="semantic"?(m.rows.get(f.symbolId)??[]).map(R=>R.file):[...p?.calleesBySymbolId.get(f.symbolId)??[]]),b=a!=="semantic"||!d.incompleteSymbolIds.has(f.symbolId)&&!d.unavailableSymbolIds.has(f.symbolId),v=a!=="semantic"||!m.incompleteSymbolIds.has(f.symbolId)&&!m.unavailableSymbolIds.has(f.symbolId);b&&v&&(u+=1);let y=uc(f,Hn(e,f,{semanticEvidence:fe}).map(R=>R.file)),E=uc(f,(o.calleeMap([f],{semantic:!1}).get(f.symbolId)??[]).map(R=>R.file)),w=jd(a,"references"),S=jd(a,"callees");b?Ix(c.references,f,"references",y,g,w,l):c.references.skippedOracleUnavailable+=1,v?Ix(c.callees,f,"callees",E,h,S,l):c.callees.skippedOracleUnavailable+=1}return l.sort((f,g)=>g.cheapOnly.length+g.oracleOnly.length-(f.cheapOnly.length+f.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?Ud(u/s.length):0,oracleKind:a,scores:["references","callees"].map(f=>FK(f,c[f],a)),topDisagreements:l.slice(0,r)}}function wx(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0,skippedOraclePartial:0,skippedOracleUnavailable:0}}function TK(e,t){let n=[...e].sort((o,s)=>o.symbolId-s.symbolId);if(n.length<=t)return n;let i=n.length/t,r=[];for(let o=0;o<t;o++)r.push(n[Math.floor(o*i)]);return r}function MK(e,t){let n=t[0];if(!n)return null;if(Hd(e,n))return"source";try{if(_t(e).capability("semantic-references",n.relativePath).available)return"semantic"}catch{}return t.some(i=>Hd(e,i))?"source":null}function uc(e,t){let n=new Set;for(let i of t)i!==e.relativePath&&n.add(i);return n}function Ix(e,t,n,i,r,o,s){if(!o&&r.size===0){e.skippedOraclePartial+=1;return}e.comparedSymbols+=1,e.cheapTotal+=i.size,e.oracleTotal+=r.size;let a=[],c=[];for(let l of i)r.has(l)?e.agreed+=1:a.push(l);for(let l of r)i.has(l)||c.push(l);(a.length>0||c.length>0)&&s.push({symbol:k(t.symbol),question:n,cheapOnly:a,oracleOnly:c})}var AK={references:!0,callees:!1};function FK(e,t,n){let i=t.oracleTotal>0?t.agreed/t.oracleTotal:1,r=t.cheapTotal-t.agreed,o=jd(n,e);return{question:e,comparedSymbols:t.comparedSymbols,precision:o&&t.cheapTotal>0?Ud(t.agreed/t.cheapTotal):null,recall:Ud(i),unverified:r,skippedOraclePartial:t.skippedOraclePartial,skippedOracleUnavailable:t.skippedOracleUnavailable}}function jd(e,t){return e==="semantic"?AK[t]:!1}function Hd(e,t){return ye(t.relativePath)==="clojure"&&ee(e,t.relativePath)!==null}function NK(e,t,n){let i=new Map,r=new Map,o=n.filter(c=>Hd(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=ee(e,c);if(l)for(let u of l.fileIdentifiers)for(let d of s.get(u)??[])Lx(i,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=ee(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)??[])Lx(r,c.symbolId,d.relativePath)}}return{referencesBySymbolId:i,calleesBySymbolId:r}}function Lx(e,t,n){let i=e.get(t);if(i){i.add(n);return}e.set(t,new Set([n]))}function Ud(e){return Math.round(e*1e3)/1e3}var kK=new Set(en());function _K(e,t={}){let{scope:n,minLoc:i=1,limit:r,scanLimit:o,maxShapeFrequency:s=12}=t,a=t.semantic!==!1,c=$K(e,OK(e,{scope:n,minLoc:i,scanLimit:o}),{semantic:a,maxShapeFrequency:s}),l=HK(c);return r?l.slice(0,r):l}function OK(e,t){let n=ze(e,{scope:t.scope}).filter(i=>BK(i)&&!e.isIgnored(i.relativePath)).filter(i=>de(i)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((i,r)=>de(r)-de(i)||i.relativePath.localeCompare(r.relativePath)),Fe(n,t.scanLimit)}function BK(e){return!e.isFunctionLike||at(e.symbol)?!1:e.kind===null||kK.has(e.kind)}function $K(e,t,n){let i=[];for(let s of t){let a=zK(e,s,n);a&&i.push({signature:a,definition:s,fn:jK(s)})}let r=new Map;for(let s of i)r.set(s.signature,(r.get(s.signature)??0)+1);let o=new Map;for(let s of i){let a=UK(s.fn.loc),c=(r.get(s.signature)??0)>n.maxShapeFrequency,l=c?Sd(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 jK(e){return{symbol:e.symbol,shortName:k(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:de(e)}}function HK(e){let t=[];for(let n of e)n.functions.length>=2&&t.push(n);return t.sort((n,i)=>{let r=i.functions.length-n.functions.length;if(r!==0)return r;let o=n.functions.reduce((a,c)=>a+c.loc,0);return i.functions.reduce((a,c)=>a+c.loc,0)-o}),t}function UK(e){return e<=5?"<=5":e<=20?"6-20":">20"}function zK(e,t,n){if(n.semantic){let o=ag(e,t);if(o)return o}let i=GK(t.documentation),r=i?WK(i):null;return r||VK(KK(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function GK(e){return zi(Gi(e))}function KK(e,t,n,i,r){let o=se(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=YK(s,n,i,r);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,qK(u)))return u}if(u&&u.includes("("))return u}return null}function qK(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||qm(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function WK(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 VK(e,t){if(!e||!e.trim())return null;let n=e.replace(/\s+/g," ").trim(),i=n.indexOf("(");if(i===-1)return null;let r=n.slice(0,i),s=new RegExp(`\\b${He(t)}\\b`,"i").exec(r);s&&typeof s.index=="number"&&(r=r.slice(0,s.index)),r=r.replace(/\b(public|private|protected|internal|final|static|abstract|sealed|virtual|override|async|suspend|inline|constexpr|consteval|constinit|const|pub|fn|function|def|sub|friend|shared|readonly|new|open|partial|export)\b/gi," ").replace(/\s+/g," ").trim();let a=JK(n.slice(i)).replace(/\)\s*=\s*[\s\S]*$/,")").replace(/\s+throws\s+[^={]+$/i,"").replace(/\s+where\s+.+$/i,"").replace(/\s+/g," ").trim();if(!a.startsWith("("))return null;let c=`${r?`${r} `:""}${a}`.replace(/\s+/g,"").toLowerCase();return c.length>=3?c:null}function JK(e){let t=0,n=0,i=0,r=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==="[")i+=1;else if(c==="]")i=Math.max(0,i-1);else if(c==="<")r+=1;else if(c===">")r=Math.max(0,r-1);else if(c==="{"){if(t===0&&i===0&&r===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&&i===0&&r===0)return e.slice(0,a)}return e}function YK(e,t,n,i){let r=He(i),o=new RegExp(`\\b${r}\\b\\s*\\(`,"i"),s=new RegExp(`\\bdef\\s+${r}\\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 Xse}from"child_process";import{execFileSync as Cse}from"child_process";import{createHash as Rse}from"crypto";import{lstatSync as wse,readlinkSync as Ise,readdirSync as Lse,realpathSync as Pse,statSync as Dse}from"fs";import{dirname as Mse,isAbsolute as Ase,join as Fse,posix as Nse,relative as kse,resolve as _se,sep as Ose}from"path";var $se=512*1024*1024;function Px(e){return Sp({version:e.version,...e.base?{base:e.base}:{},files:[...e.files].sort((t,n)=>t.path.localeCompare(n.path))})}function zd(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 QK="codebaseiq:collaboration-domain",ZK="codebaseiq:workspace-instance",eq="codebaseiq:index-generation",tq="codebaseiq:repository-content",Dx="codebaseiq:index-inputs",nq="codebaseiq:index-inputs";function Fi(e){let t=e.snapshot,n=e.observedSourceKinds?new Set(e.observedSourceKinds):void 0,i=e.gitContext??t?.gitContext??(n?.has("live-workspace")?Dc(e.projectRoot):void 0),r=e.collaborationDomainId??e.db?.config.collaborationDomainId,o=r?di(QK,1,r):void 0,s=i?di(ZK,1,i.worktreeId):void 0,a=t?di(tq,1,Px(t.repositoryContent)):void 0,c=t?di(Dx,t.indexInputs.version,zd(t.indexInputs)):void 0,l=e.db&&t?rq(e.db.generation.metadataRaw):void 0,u=e.db?{generation:di(eq,1,e.db.generation.identity),...l?{inputs:l}:{},source:e.db.generation.source}:void 0,d=n??new Set([...u?["index-generation"]:[],...a?["repository-snapshot"]:s?["live-workspace"]:[]]),m=[...u&&d.has("index-generation")?[{kind:"index-generation",identity:u.generation}]:[],...a&&d.has("repository-snapshot")?[{kind:"repository-snapshot",identity:a}]:[],...s&&d.has("live-workspace")?[{kind:"live-workspace",identity:s}]:[],...d.has("process")?[{kind:"process"}]:[]],p=[...u&&d.has("index-generation")?[{source:"index-generation",kind:u.source==="immutable"?"immutable":"not-established"}]:[],...a&&d.has("repository-snapshot")?[{source:"repository-snapshot",kind:"fixed-snapshot"}]:[],...s&&d.has("live-workspace")?[{source:"live-workspace",kind:"not-established"}]:[],...d.has("process")?[{source:"process",kind:"not-established"}]:[]];return m.length===0&&(m.push({kind:"process"}),p.push({source:"process",kind:"not-established"})),{schemaVersion:Mp,observedAt:(e.observedAt??(t?new Date(t.capturedAt):new Date)).toISOString(),facts:{...o?{collaborationDomain:o}:{},...s?{workspaceInstance:s}:{},...a?{wholeContent:a}:{},...c?{relevantInputs:[{subject:nq,identity:c}]}:{},...u?{index:u}:{}},observedSources:m,stabilityProofs:p,...i?{diagnostics:{clean:i.clean,...i.headCommit?{headCommit:i.headCommit}:{},...i.treeOid?{treeOid:i.treeOid}:{}}}:{}}}function iq(e){return Fi({projectRoot:e.projectRoot,db:e.db,...e.gitContext?{gitContext:e.gitContext}:{},...e.observedAt?{observedAt:e.observedAt}:{},observedSourceKinds:["index-generation"]})}function Vse(){let e=Cs();if(!e)return Fi({projectRoot:Np(),observedSourceKinds:["process"]});let t=e.config.projectRoot,n=Dc(t);return iq({projectRoot:t,db:e,...n?{gitContext:n}:{}})}function rq(e){if(!e)return;let t=Qo(e);if(t.kind!=="legacy"&&t.kind!=="supported")return;let n=Am(t.metadata.fingerprint);return n&&Number.isSafeInteger(n.version)&&n.version>0?di(Dx,n.version,zd(n)):void 0}var Kd="codebaseiq-isolated-analysis",qd=1;function oq(e){let t=[...e??[]];return t.includes("--json")?t:["--json",...t]}var vr=class extends Error{constructor(n,i,r=!0){super(`${n} timed out after ${i}ms.`);this.label=n;this.timeoutMs=i;this.reaped=r;this.name="IsolatedProcessTimeoutError"}label;timeoutMs;reaped;timedOut=!0};function oae(e,t){let n=Cs(),i={protocol:Kd,schemaVersion:qd,producer:{name:"codebaseiq",version:ci},command:e,result:t,...n?{observationReceipt:Fi({projectRoot:n.config.projectRoot,db:n,observedSourceKinds:["index-generation"]})}:{}};jc(JSON.stringify(i))}function Tx(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}function dc(e){let t=e.timeoutMs??Dm.analysis,n=e.maxBuffer??10*1024*1024;return Mm({command:process.execPath,args:[...process.execArgv,e.cliPath,e.command,...oq(e.args)],cwd:process.cwd(),env:e.env??process.env,label:e.label,timeoutMs:t,maxStdoutBytes:n,maxStderrBytes:n,signal:e.signal}).catch(i=>{throw i instanceof Tm&&i.kind==="timeout"?new vr(e.label,t,i.reaped):i}).then(i=>{let r=i.stderr.trim();if(i.status!==0)throw new Error(`${e.label} failed${r?`:
530
- ${r}`:""}`);return sq(i.stdout,e)})}function sq(e,t){let n;try{n=JSON.parse(e)}catch(r){throw new Error(`${t.label} returned invalid JSON: ${r instanceof Error?r.message:r}`,{cause:r})}if(!Lc(n))throw new Error(`${t.label} returned a non-object isolated-analysis message.`);if(n.protocol!==Kd)throw new Error(`${t.label} returned protocol ${Gd(n.protocol)}; expected ${Kd}.`);if(n.schemaVersion!==qd)throw new Error(`${t.label} returned unsupported isolated-analysis schemaVersion ${Gd(n.schemaVersion)}; expected ${qd}.`);if(!aq(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 ${Gd(n.command)}; expected ${t.command}.`);if(!Object.hasOwn(n,"result"))throw new Error(`${t.label} omitted the isolated-analysis result.`);let i=n.observationReceipt;if(i!==void 0&&(!Ap(i)||i.schemaVersion!==2))throw new Error(`${t.label} returned an invalid observation receipt.`);return{result:n.result,...i?{observationReceipt:i}:{}}}function aq(e){return Lc(e)&&e.name==="codebaseiq"&&typeof e.version=="string"&&e.version.length>0}function Gd(e){return typeof e=="string"?JSON.stringify(e):String(e)}async function Wd(e,t,n){let i=new Array(e.length),r=new AbortController,o=0,s,a=!1;async function c(){for(;!r.signal.aborted&&o<e.length;){let l=o++;try{i[l]=await n(e[l],r.signal)}catch(u){throw a||(a=!0,s=u,r.abort(u)),u}}}if(await Promise.allSettled(Array.from({length:Math.min(t,e.length)},()=>c())),a)throw s;return i}function Mx(e,t){let n=new Set,i=[];for(let r of e){if(n.has(r))continue;let o=t.find(a=>a.has(r));if(!o){n.add(r),i.push([r]);continue}let s=e.filter(a=>o.has(a));s.forEach(a=>n.add(a)),i.push(s)}return i}import{spawnSync as cq}from"child_process";import{existsSync as lq,mkdirSync as uq,renameSync as dq,writeFileSync as mq}from"fs";import{dirname as Fx,join as pq}from"path";var mc=6,fq="health-report-cache.json";function Vd(e,t,n,i=Sq()){let r=yn(e);return r?{version:mc,projectFingerprint:r,cliVersion:n,scope:t.scope??null,full:t.full===!0,phaseTimeoutMs:t.phaseTimeoutMs??null,gitHead:i.gitHead(e.config.projectRoot)}:null}function Nx(e,t,n=Bx()){let i=_x(e),r=Ox(t),o=!1;return $("health.report-cache.read",()=>{if(!n.existsSync(i))return null;try{let s=JSON.parse(n.readFile(i));return!gq(s)||s.keyHash!==r?null:(o=!0,s.report)}catch{return null}},()=>({available:!0,hit:o,keyHash:r}))}function kx(e,t,n,i=Bx()){let r=_x(e),o={version:mc,keyHash:Ox(t),key:t,writtenAt:i.nowIso(),report:n};i.mkdirSync(Fx(r),{recursive:!0});let s=`${r}.${process.pid}.${Date.now()}.tmp`;i.writeFileSync(s,JSON.stringify(o)),i.renameSync(s,r)}function _x(e){return pq(Fx(e.config.dbPath),fq)}function Ox(e){return Ht(JSON.stringify(e))}function gq(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===mc&&typeof t.keyHash=="string"&&hq(t.key)&&typeof t.writtenAt=="string"&&yq(t.report)}function hq(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===mc&&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 yq(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)&&bq(t.coverage)}function bq(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 Ax(n)&&typeof n.excludedSymbolCount=="number"&&Array.isArray(t.phases)&&t.phases.every(i=>!!i&&typeof i=="object"&&typeof i.phase=="string"&&Ax(i.semanticEvidence))}function Ax(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 Sq(){return{gitHead(e){let t=cq("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",timeout:3e4,killSignal:"SIGKILL",windowsHide:!0});return t.status===0?t.stdout.trim():null}}}function Bx(){return{existsSync:lq,mkdirSync:uq,readFile:e=>vt(e,"health report cache"),renameSync:dq,writeFileSync:mq,nowIso:()=>new Date().toISOString()}}var Hx="__health-phase",Cq="__diff-impact-batch",xq=10,Rq=4,Eq=8,wq=25e3,Iq=2500,Jd=2500,Lq=4,Pq=12,$x=3e4,Ux=new Set(["react-component-duplicates","react-hook-candidates","react-large-component-pressure"]),zx=new Set(["vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure"]),Dq=new Set([...zx,"suppressions"]),Tq=new Set(["similar","extract-candidates"]),fc=3,jx=wr({kind:"health-semantic-prewarm",invalidation:Je("health-semantic-prewarm"),serialize:e=>JSON.stringify(e),deserialize:Mq});function Mq(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return n.version!==fc||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:fc,definitions:n.definitions,referenceCacheWrites:n.referenceCacheWrites,referenceIncomplete:n.referenceIncomplete,calleeRows:n.calleeRows,warmedAt:n.warmedAt}}catch{return null}}function Mae(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
531
- `)}function Aq(e){let t=bi(e);return t.symbols>=wq||t.documents>=Iq}function Aae(e,t,n,i={}){if(!Aq(e))return{semantic:!0};if(n)return i.quiet||console.error(`Large index detected; ${t} is running the unbounded semantic pass because --full was supplied.`),{semantic:!0};if(!i.quiet){let r=t==="inspect"?"Use --full only when every omitted semantic candidate can change the decision; it does not override source or behavior materialization ceilings.":`Run "codebaseiq ${t} --full" for the unbounded semantic pass.`;console.error(`Large index detected; ${t} is using its bounded default analysis with semantic enrichment disabled. Candidate scans, when this command uses one, are capped at ${Jd}. `+r)}return{scanLimit:Jd,semantic:!1,analysisBudget:{scanLimit:Jd,semanticEnrichment:!1,reason:"large index default budget; pass --full for unbounded semantic analysis"}}}var Fq={env:process.env,projectFingerprint:yn,semanticEngineFingerprint:Oq,readMarker:(e,t,n)=>jx.read(e,t,n),writeMarker:(e,t,n,i)=>jx.write(e,t,n,i),candidateDefinitions:(e,t)=>new U(e).scopedDefinitions(t.scope).filter(n=>Ke(n.relativePath)!==null),materializeReferences:(e,t,n)=>_t(e).materializeReferences(t,n),materializeCallees:Rl};function Nq(e,t,n=Fq){if(t.full!==!0)return ri("default-mode");if((n.env??process.env).CODEBASEIQ_HEALTH_SEMANTIC_PREWARM==="0")return ri("disabled");let i=ri("error");return $("health.semantic-prewarm",()=>{try{i=kq(e,t,n)}catch(r){i=ri("error",{error:r instanceof Error?r.message:String(r)})}return i},()=>Bq(i))}function kq(e,t,n){let i=n.projectFingerprint(e);if(!i)return ri("missing-project-fingerprint");let r=_q(t,n.semanticEngineFingerprint(e)),o=n.readMarker(e,r,i);if(o&&o.referenceIncomplete===0)return ri("cache-hit");let s=[];if(s=$("health.semantic-prewarm.candidate-definitions",()=>(s=n.candidateDefinitions(e,t),s),()=>({definitions:s.length})),s.length===0)return ri("no-semantic-definitions");let a=0,c=$("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 ri("provider-unavailable",{definitions:s.length,referenceMisses:c.misses});let u=0,d=$("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}:($("health.semantic-prewarm.marker-write",()=>n.writeMarker(e,r,i,{version:fc,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 _q(e,t){return JSON.stringify({version:fc,cliVersion:ci,semanticEngineFingerprint:t,scope:e.scope??null})}function Oq(e){return Ht(JSON.stringify({kind:"health-semantic-prewarm-engine",rust:ui(e.config.projectRoot)}))}function ri(e,t={}){return{status:"skipped",reason:e,definitions:0,referenceCacheHits:0,referenceCacheWrites:0,referenceMisses:0,referenceIncomplete:0,calleeRows:0,...t}}function Bq(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 pc(e){return Hc(t=>{let n=Fi({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 gc(e,t,n){let i=e[0];if(!i)throw new Error("An evidence-bound analysis requires at least one index observation anchor.");let r=i.generationDigest,o=e.every(a=>a.generationDigest===r),s=t.every(a=>a?.facts.index?.generation.digest===r);return Fi({projectRoot:i.database.config.projectRoot,...o&&s?{db:i.database}:{},observedSourceKinds:n})}async function Fae(e){return(await $q(e)).result}async function $q(e){let t=Kq(e),n={...e,phaseTimeoutMs:t??null},i=pc(g=>{let h=Vd(g,n,ci);if(!h)return null;let b=Nx(g,h);return b||null});if(i.value)return{result:i.value,observationReceipt:gc([i.anchor],[],["index-generation","live-workspace"])};let r=pc(g=>({applicability:jq(g,e),overview:_d(g,"overview",e)})),{applicability:o,overview:s}=r.value,a=[i.anchor,r.anchor],c=new Map;c.set("overview",s);let l=cc.filter(g=>g==="overview"?!1:Hq(g,o)?!0:(c.set(g,Ni(g)),!1)),u=Uq(l);if(e.full){let g=pc(h=>Nq(h,e));a.push(g.anchor)}let d=await Wd(u,qq(u.length),(g,h)=>zq(g,e,t,h)),m=d.flatMap(g=>g.result),p=[];if(m.forEach(g=>{g.healthPhaseMeta&&p.push(`Health phase "${g.phase}" deferred: ${g.healthPhaseMeta.reason}. Run health --full for exhaustive analysis.`),c.set(g.phase,g)}),p.length>0){let g=c.get("overview");c.set("overview",{...g,warnings:[...g.warnings,...p]})}let f=Od(cc.map(g=>c.get(g)));return Hc(g=>{let h=Vd(g,n,ci);h&&kx(g,h,f)}),{result:f,observationReceipt:gc(a,d.map(g=>g.observationReceipt),["index-generation","live-workspace"])}}function jq(e,t){return as(e,{scope:t.scope})}function Hq(e,t){return Ux.has(e)?t.react:zx.has(e)?t.vue:!0}function Uq(e){return Mx(e,[Ux,Dq,Tq])}function Ni(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 zq(e,t,n,i){if(e.length===1)return Gq(e[0],t,n,i).then(a=>({result:[a.result],...a.observationReceipt?{observationReceipt:a.observationReceipt}:{}}));let r=e.join(","),o=process.argv[1]??Xd(import.meta.url),s=[r];return t.scope&&s.push("--scope",t.scope),t.full&&s.push("--full"),dc({cliPath:o,command:Hx,args:s,label:`Health phases "${r}"`,timeoutMs:n,signal:i}).catch(a=>{if(t.full||!(a instanceof vr))throw a;return{result:e.map(c=>Gx(c,a.timeoutMs,`timed out after ${a.timeoutMs}ms`))}})}function Gq(e,t,n,i){let r=process.argv[1]??Xd(import.meta.url),o=[e];return t.scope&&o.push("--scope",t.scope),t.full&&o.push("--full"),dc({cliPath:r,command:Hx,args:o,label:`Health phase "${e}"`,timeoutMs:n,signal:i}).catch(s=>{if(t.full||!(s instanceof vr))throw s;return{result:Gx(e,s.timeoutMs,`timed out after ${s.timeoutMs}ms`)}})}function Kq(e,t=process.env){if(e.full)return;let n=t.CODEBASEIQ_HEALTH_PHASE_TIMEOUT_MS;if(!n)return $x;let i=parseInt(n,10);return!Number.isFinite(i)||i<0?$x:i===0?void 0:i}function Gx(e,t,n){let i={evidenceCoverage:{enabled:!0,status:"unavailable",incompleteSymbolCount:0,unavailableSymbolCount:0},healthPhaseMeta:{status:"deferred",reason:n,timeoutMs:t}};switch(e){case"overview":throw new Error("Overview health phase cannot be deferred.");case"dead":return{phase:e,dead:{count:0,loc:0,files:[]},...i};case"isolated":return{phase:e,isolated:{count:0,loc:0,files:[]},...i};case"cycles":return{phase:e,realCycleCount:0,...i};case"similar":return{phase:e,similarCount:0,...i};case"duplicate-bodies":return{phase:e,duplicateBodies:{count:0,loc:0,files:[]},...i};case"twin-drift":return{phase:e,twinDrift:{count:0,loc:0,files:[]},...i};case"react-component-duplicates":return{...Ni(e),...i};case"react-hook-candidates":return{...Ni(e),...i};case"react-large-component-pressure":return{...Ni(e),...i};case"vue-component-duplicates":return{...Ni(e),...i};case"vue-composable-candidates":return{...Ni(e),...i};case"vue-large-view-pressure":return{...Ni(e),...i};case"extract-candidates":return{phase:e,extractCount:0,...i};case"wrapper-candidates":return{phase:e,wrappers:{count:0,loc:0,files:[]},...i};case"passthrough-candidates":return{phase:e,passthroughs:{count:0,loc:0,files:[]},...i};case"stale-abstractions":return{phase:e,stale:{count:0,loc:0,files:[],unused:0,singleUse:0},...i};case"drift":return{phase:e,drift:{count:0,unusedImports:0,architectureViolations:0,layerViolations:0,direct:0,signal:0},...i};case"complexity-hotspots":return{phase:e,complexity:{top:[],extremeCount:0,coverage:{semanticEvidence:{enabled:!0,status:"unavailable",incompleteSymbolCount:0,unavailableSymbolCount:0,excludedSymbolCount:0}}},...i};case"git-evidence":return{phase:e,gitEvidence:null,...i};case"suppressions":return{phase:e,suppressions:{total:0,byCategory:{}},...i};case"coverage-contracts":return{phase:e,coverageContracts:{count:0,loc:0,files:[]},...i}}}var qq=Kx({envKey:"CODEBASEIQ_HEALTH_CONCURRENCY",defaultMinimum:Lq,defaultMaximum:Pq});function Nae(e){if(console.log(`
532
- 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)
533
- `),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${kp(e.overview.indexSizeBytes)}
534
- `),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: ${Yd(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: ${Yd(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: ${Yd(t.wrappers,t.wrapperScoreCount)}`),t.passthroughs>0&&console.log(` Passthroughs: ${t.passthroughs}`),t.staleTypes>0&&console.log(` Stale abstractions: ${t.staleTypes}`),t.driftedFiles>0&&console.log(` Pattern drift: ${t.driftedFiles} files`),t.complexityHotspotCount>0&&console.log(` Complexity hotspots: ${t.complexityHotspotCount}`),e.actions.length>0){console.log(`
535
- Prioritized Actions (highest impact + lowest effort first):`);for(let n=0;n<e.actions.length;n++){let i=e.actions[n],r=i.locRecoverable>0?` (~${i.locRecoverable} LOC involved)`:"";console.log(` ${n+1}. [${i.effort} effort / ${i.impact} impact] ${i.description}${r}`)}}if(e.topComplexity.length>0){console.log(`
536
- Top Complexity Hotspots:`);for(let n of e.topComplexity)console.log(` ${n.score.toFixed(1).padStart(6)} ${n.symbol}`)}if(Jq(e),Vq(e),e.scoreBreakdown.length>0){console.log(`
537
- 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?`
538
- No findings from completed analyses. Review warnings before interpreting this result as clean.`:`
539
- No issues found. Codebase is clean.`)}function Yd(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${Wq(t)} score-weighted)`}function Wq(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function Vq(e){if(e.pressure.length!==0){console.log(`
540
- 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 Jq(e){let t=e.axes;if(console.log(`
541
- Axes:`),console.log(` Zero-reference candidates: ${t.deletable.loc} LOC across ${t.deletable.symbols} symbols`),t.changeAmplification){let i=t.changeAmplification;console.log(` Change amplification: ${i.medianFilesPerCommit} files/commit median, ${i.p90FilesPerCommit} p90 (${i.commitsAnalyzed} commits)`)}if(t.hiddenCoupling&&t.hiddenCoupling.pairCount>0){console.log(` Hidden coupling: ${t.hiddenCoupling.pairCount} co-changing pair(s) without a dependency edge`);for(let i of t.hiddenCoupling.top.slice(0,3))console.log(` ${i.fileA} <-> ${i.fileB} (${i.together}x together, ${Math.round(i.confidence*100)}%)`)}if(t.churnWeightedComplexity&&t.churnWeightedComplexity.length>0){let i=t.churnWeightedComplexity[0];i.weighted>0&&console.log(` Churn x complexity: hottest is ${i.symbol} (${i.changes} changes, weighted ${i.weighted})`)}let n=t.evidenceQuality;if(console.log(` Evidence quality: ${n.graphFindings} graph-fact finding(s), ${n.heuristicFindings} heuristic finding(s), ${n.userSuppressed} user-suppressed`),e.validation&&e.validation.flaggedFiles>0){let i=e.validation,r=i.ratio===null?"n/a":`${i.ratio}x`;console.log(` Validation: flagged files fix-density ${i.flaggedFixDensity} vs baseline ${i.baselineFixDensity} (${r})`),console.log(` fix-commit signal: subject-keyword heuristic over ${i.validationBasis.commitsScanned} commits`)}}async function kae(e){let t=pc(o=>{let s=yr(o,{base:e.base});return s.note?{kind:"complete",result:za(o,{base:e.base})}:s.changedFiles.length===0?{kind:"complete",result:za(o,{base:e.base})}:{kind:"batched",plan:s}}),n=t.value;if(n.kind==="complete")return{result:n.result,observationReceipt:gc([t.anchor],[],["index-generation","live-workspace"])};let i=Tx(n.plan.changedFiles,xq),r=await Wd(i,Yq(i.length),(o,s)=>e2(o,e,s));return{result:Ga(n.plan.changedFiles,r.map(o=>o.result)),observationReceipt:gc([t.anchor],r.map(o=>o.observationReceipt),["index-generation","live-workspace"])}}var Yq=Kx({envKey:"CODEBASEIQ_DIFF_IMPACT_CONCURRENCY",defaultMinimum:Rq,defaultMaximum:Eq});function Kx(e){return(t,n=process.env,i=vq)=>Xq(t,n,i,e)}function Xq(e,t,n,i){let r=t[i.envKey],o=Zq(n,i),s=r?parseInt(r,10):o,a=!Number.isFinite(s)||s<1?Math.min(o,e):Math.min(s,e),c=Qq(t);return c===null?a:Math.min(c,a)}function Qq(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 Zq(e,t){let n=e(),i=Number.isFinite(n)?Math.max(t.defaultMinimum,n-1):0;return Math.min(t.defaultMaximum,Math.max(t.defaultMinimum,i))}function e2(e,t,n){let i=process.argv[1]??Xd(import.meta.url),r=[];return t.base&&r.push("--base",t.base),dc({cliPath:i,command:Cq,args:r,env:{...process.env,CODEBASEIQ_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch",signal:n})}function _ae(e){console.log(`Changed files: ${e.summary.totalChangedFiles}`),console.log(`Changed symbols: ${e.summary.totalChangedSymbols}`),console.log(`Affected consumer files: ${e.summary.totalAffectedFiles}`),e.summary.note&&console.log(`Note: ${e.summary.note}`);for(let n of e.evidenceTiers.filter(i=>i.state==="failed"))console.log(`WARNING: ${n.tier} evidence failed for ${n.attemptedSymbols} candidate symbol(s): ${n.reason}`);let t=e.attributionNotes.filter(n=>n.method==="unattributed");if(t.length>0){let n=[...new Set(t.map(i=>i.file))];for(let i of n){let r=t.filter(o=>o.file===i).length;console.log(`note: ${r} changed line-range(s) in ${i} belong to no indexed symbol`)}}console.log(""),e.changedSymbols.length>0&&(console.log("Changed symbols:"),wl.list(e.changedSymbols,n=>` ${n.file} ${n.shortName} (fan-in: ${n.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
542
- Affected consumer files:`),wl.list(e.affectedConsumers,n=>` ${n.file} (${n.consumedSymbols} symbol(s))`))}import{AsyncLocalStorage as t2}from"async_hooks";import{createHash as Zd}from"crypto";import{existsSync as n2,mkdirSync as i2}from"fs";import{tmpdir as r2}from"os";import{isAbsolute as o2,join as Vx,resolve as Jx}from"path";var Qd=2,s2="CODEBASEIQ_SESSION",qx="CODEBASEIQ_SESSION_DIR",a2=128,oi=new t2;function Yx(e,t){let n=e.sessionEnabled===!1||e.json?void 0:C2(),i={enabled:n!==void 0,reemit:e.reemit===!0,command:e.command,projectRoot:Jx(e.cwd),sessionIdentity:n,staged:[],stagedEvidence:[],finalized:!1};return oi.run(i,t)}function Vae(e){let t=oi.getStore();!t||t.finalized||(t.generationIdentity=e)}function Jae(){return oi.getStore()?.staged.length??0}function Yae(e){let t=oi.getStore();!t||e<0||e>t.staged.length||(t.staged.length=e)}function em(e){let t=oi.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 i=n.ledger.nextOrdinal,r=h2(t.staged).map(s=>({...s,ordinal:i,command:t.command})),o=b2(t.stagedEvidence).map(s=>({...s,ordinal:i,command:t.command}));n.ledger.ranges.push(...r),n.ledger.evidence.push(...o),n.ledger.nextOrdinal+=1,n.ledger.updatedAt=new Date().toISOString(),Yt(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 Xae(e){let t=e.source.split(`
543
- `);if(t.length===0)return"";let n=c2(e.relativePath,e.startLine,t,e.ownerSymbol,e.sessionPolicy??"exact-unit"),i=e.indent??" ",r=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[`${i}${a} [source previously emitted: ${u}; not repeated]`,...e.afterHeader??[]].join(`
544
- `)}let c=e.headerSuffix??"",l=s.lines.map((u,d)=>{let m=s.startLine+d,p=e.showFocusMarker===!1?"":o.has(m)?">":" ",f=e.lineNumberWidth??5;return`${r}${p}${String(Js(m)).padStart(f)} ${u}`});return[`${i}${a}${c}`,...e.blankAfterHeader?[""]:[],...e.afterHeader??[],...l].join(`
545
- `)}).join(`
546
- `)}function Qae(e){let t=oi.getStore();if(!t||!t.enabled)return e.content;let n=tm(t);if(!n)return e.content;let i=Xx(e.content),r=hc(n.ledger.evidence,o=>o.kind===e.kind&&o.identity===e.identity&&o.contentHash===i);if(r&&!t.reemit){let o=e.label?`; ${Wx(e.label)}`:"";return`${e.indent??""}[${e.kind} evidence previously emitted: receipt ${r.receiptId}; session #${r.ordinal} via ${r.command}${o}; not repeated]`}return t.stagedEvidence.push({kind:e.kind,identity:e.identity,contentHash:i,receiptId:x2(e.kind,e.identity,i),...e.label?{label:Wx(e.label)}:{}}),e.content}function Zae(e=!1){let t=oi.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=tm(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{Yt(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 i=new Map;for(let a of n.ledger.ranges){let c=i.get(a.ordinal)??[];c.push(a),i.set(a.ordinal,c)}let r=new Map;for(let a of n.ledger.evidence){let c=r.get(a.ordinal)??[];c.push(a),r.set(a.ordinal,c)}let s=[...new Set([...i.keys(),...r.keys()])].sort((a,c)=>a-c).map(a=>{let c=i.get(a)??[],l=r.get(a)??[],u=c[0]?.command??l[0]?.command??"unknown",d=c.length===0?null:(()=>{let f=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}: ${f}${g}`})();if(l.length===0)return d;let m=l.slice(0,8).map(f=>`${f.receiptId} ${f.kind}${f.label?` ${f.label}`:""}`).join(", "),p=l.length>8?`, ... ${l.length-8} more item(s)`:"";return d?`${d}
547
- evidence: ${m}${p}`:` #${a} ${u}: ${m}${p}`});return{enabled:!0,uniqueLines:S2(n.ledger.ranges),evidenceItems:n.ledger.evidence.length,emissions:new Set([...i.keys(),...r.keys()]).size,rows:s}}function c2(e,t,n,i,r){let o=oi.getStore(),s=t+n.length-1;if(!o)return[{kind:"source",startLine:t,endLine:s,lines:[...n]}];let c=(o.enabled?tm(o):null)?.ledger.ranges??[],l=n.map(Xx),u=r==="exact-unit"&&!o.reemit?hc(c,h=>h.policy==="exact-unit"&&h.relativePath===e&&h.startLine===t&&h.endLine===s&&h.ownerSymbol===i&&R2(h.lineHashes,l)):void 0;if(u)return[{kind:"covered",startLine:t,endLine:s,ordinal:u.ordinal,command:u.command}];let d=r==="exact-unit"&&!o.reemit?u2(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)=>l2(c,e,t+b,l[b]));if(!(r==="preview"&&!o.reemit&&m.every(h=>h!==void 0)))return o.staged.push({relativePath:e,startLine:t,endLine:s,ownerSymbol:i,policy:r,lineHashes:l}),[{kind:"source",startLine:t,endLine:s,lines:[...n]}];let f=[],g=0;for(;g<n.length;){let h=m[g],b=g;for(;b+1<n.length&&d2(h,m[b+1]);)b+=1;let v=t+g,y=t+b;f.push({kind:"covered",startLine:v,endLine:y,ordinal:h.ordinal,command:h.command}),g=b+1}return f}function l2(e,t,n,i){let r=hc(e,o=>o.relativePath===t&&o.startLine<=n&&n<=o.endLine&&o.lineHashes[n-o.startLine]===i);if(r)return{ordinal:r.ordinal,command:r.command}}function u2(e,t,n,i,r){let o=hc(e,s=>s.policy==="exact-unit"&&s.relativePath===t&&s.startLine<=n&&s.endLine>=i&&r.every((a,c)=>s.lineHashes[n-s.startLine+c]===a));return o?{ordinal:o.ordinal,command:o.command}:void 0}function d2(e,t){return!e||!t?e===t:e.ordinal===t.ordinal&&e.command===t.command}function tm(e){if(e.state!==void 0)return e.state;if(!e.sessionIdentity||!e.generationIdentity)return e.state=null,null;try{let t=v2();i2(t,{recursive:!0,mode:448});let n=Zd("sha256").update(e.projectRoot).update("\0").update(e.generationIdentity).update("\0").update(e.sessionIdentity).digest("hex"),i=Vx(t,`${n}.json`),r=Oi(`${i}.lock`,{kind:"source-emission-session",detail:{session:n.slice(0,12)}});if(r.kind!=="acquired")return e.state=null,null;let o;try{o=n2(i)?p2(JSON.parse(vt(i,"source emission session ledger")),{projectRoot:e.projectRoot,generationIdentity:e.generationIdentity,sessionIdentity:e.sessionIdentity}):m2(e)}catch{return r.lock.release(),e.state=null,null}return e.state={ledgerPath:i,lock:r.lock,ledger:o},e.state}catch{return e.state=null,null}}function m2(e){return{version:Qd,projectRoot:e.projectRoot,generationIdentity:e.generationIdentity,sessionIdentity:e.sessionIdentity,nextOrdinal:1,updatedAt:new Date().toISOString(),ranges:[],evidence:[]}}function p2(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:Qd,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!==Qd||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(f2)||!Array.isArray(n.evidence)||!n.evidence.every(g2))throw new Error("Invalid source emission ledger.");return n}function f2(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(Qx)&&(t.ownerSymbol===void 0||typeof t.ownerSymbol=="string")}function g2(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"&&Qx(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 h2(e){let t=[...e].sort((i,r)=>i.relativePath.localeCompare(r.relativePath)||i.startLine-r.startLine||i.endLine-r.endLine),n=[];for(let i of t){let r=n[n.length-1];if(r&&r.relativePath===i.relativePath&&r.ownerSymbol===i.ownerSymbol&&r.policy===i.policy&&i.startLine<=r.endLine+1&&y2(r,i)){let o=i.startLine-r.startLine;for(let s=0;s<i.lineHashes.length;s+=1)r.lineHashes[o+s]??=i.lineHashes[s];r.endLine=Math.max(r.endLine,i.endLine)}else n.push({...i,lineHashes:[...i.lineHashes]})}return n}function y2(e,t){let n=Math.max(e.startLine,t.startLine),i=Math.min(e.endLine,t.endLine);for(let r=n;r<=i;r+=1)if(e.lineHashes[r-e.startLine]!==t.lineHashes[r-t.startLine])return!1;return!0}function b2(e){let t=new Set,n=[];for(let i of e){let r=`${i.kind}\0${i.identity}\0${i.contentHash}`;t.has(r)||(t.add(r),n.push(i))}return n}function S2(e){let t=new Map;for(let i of e){let r=t.get(i.relativePath)??[];r.push(i),t.set(i.relativePath,r)}let n=0;for(let i of t.values()){i.sort((s,a)=>s.startLine-a.startLine||s.endLine-a.endLine);let r=-1,o=-1;for(let s of i)r<0?(r=s.startLine,o=s.endLine):s.startLine<=o+1?o=Math.max(o,s.endLine):(n+=o-r+1,r=s.startLine,o=s.endLine);r>=0&&(n+=o-r+1)}return n}function v2(){let e=process.env[qx];if(!e)return Vx(r2(),`codebaseiq-source-sessions-${process.getuid?.()??"user"}`);if(!o2(e))throw new Error(`${qx} must be an absolute path.`);return Jx(e)}function C2(){let e=process.env[s2]?.trim();if(e&&!(e.length>a2||!/^[A-Za-z0-9._:-]+$/.test(e)))return`explicit:${e}`}function x2(e,t,n){return`ev-${Zd("sha256").update(e).update("\0").update(t).update("\0").update(n).digest("hex").slice(0,12)}`}function Wx(e){let t=e.replace(/[\r\n\t]+/gu," ").replace(/\s+/gu," ").trim();return t.length<=160?t:`${t.slice(0,157)}...`}function Xx(e){return Zd("sha256").update(e).digest("hex")}function R2(e,t){return e.length===t.length&&e.every((n,i)=>n===t[i])}function hc(e,t){for(let n=e.length-1;n>=0;n-=1){let i=e[n];if(t(i))return i}}function Qx(e){return typeof e=="string"&&/^[0-9a-f]{64}$/u.test(e)}import{createHash as E2}from"crypto";import{existsSync as im,mkdirSync as w2,rmSync as I2}from"fs";import{tmpdir as L2}from"os";import{isAbsolute as P2,join as eR,resolve as yc}from"path";var tR=1,D2="CODEBASEIQ_SESSION",Zx="CODEBASEIQ_SESSION_DIR",T2=128,nR=8,iR=32768,bc=new Map;function cce(e,t,n=!0){if(!n)return;let i=Sc();if(!i)return;let r=cm(e),o=t.map(a=>a.trim()).filter(a=>a.startsWith("codebaseiq system-map ")&&a.length<=iR).slice(0,nR),s=rR(r,i);o.length===0?bc.delete(s):bc.set(s,o)}function rm(e,t,n,i=!0,r){if(!i||e!=="anchors"&&e!=="system-map")return;let o=Sc();if(!o)return;let s=cm(t),a=am(s,o);if(e==="system-map"){n?I2(a,{force:!0}):im(a)&&r&&nm(a,()=>{let c=sm(a,s,o);c&&Yt(a,{...c,pendingMapContinuation:r,mapExecution:void 0,updatedAt:new Date().toISOString()},{spacing:2,trailingNewline:!0})});return}nm(a,()=>{let c=M2(s,o),l={version:tR,projectRoot:s,sessionIdentity:o,mapRequired:!0,...c.length>0?{recommendedMapCommands:c}:{},updatedAt:new Date().toISOString()};Yt(a,l,{spacing:2,trailingNewline:!0})})}function om(e,t=!0){if(!t)return;let n=Sc();if(!n)return;let i=cm(e),r=am(i,n);im(r)&&nm(r,()=>{let o=sm(r,i,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(`
548
- `));if(o.mapExecution&&A2(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(`
549
- `));Yt(r,{...o,mapExecution:{processId:process.pid,startedAt:new Date().toISOString()},updatedAt:new Date().toISOString()},{spacing:2,trailingNewline:!0})}})}function lce(e,t,n=!0){if(!n)return;let i=Sc();if(!i)return;let r=am(yc(e),i);if(!im(r))return;let o=sm(r,yc(e),i);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(`
550
- `))}function sm(e,t,n){try{let i=JSON.parse(vt(e,"navigation session state"));return i.version===tR&&i.projectRoot===t&&i.sessionIdentity===n&&i.mapRequired===!0&&(i.recommendedMapCommands===void 0||Array.isArray(i.recommendedMapCommands)&&i.recommendedMapCommands.length<=nR&&i.recommendedMapCommands.every(r=>typeof r=="string"&&r.startsWith("codebaseiq system-map ")&&r.length<=iR))&&(i.pendingMapContinuation===void 0||typeof i.pendingMapContinuation=="string")&&(i.mapExecution===void 0||typeof i.mapExecution=="object"&&i.mapExecution!==null&&Number.isSafeInteger(i.mapExecution.processId)&&typeof i.mapExecution.startedAt=="string")?i:null}catch{return null}}function M2(e,t){let n=rR(e,t),i=bc.get(n)??[];return bc.delete(n),i}function rR(e,t){return`${e}\0${t}`}function A2(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function am(e,t){let n=F2();w2(n,{recursive:!0,mode:448});let i=E2("sha256").update(e).update("\0").update(t).digest("hex");return eR(n,`navigation-${i}.json`)}function F2(){let e=process.env[Zx];if(!e)return eR(L2(),`codebaseiq-source-sessions-${process.getuid?.()??"user"}`);if(!P2(e))throw new Error(`${Zx} must be an absolute path.`);return yc(e)}function cm(e){let t=process.env.CODEBASEIQ_PROJECT_ROOT?.trim();return yc(t||e)}function Sc(){let e=process.env[D2]?.trim();if(e&&!(e.length>T2||!/^[A-Za-z0-9._:-]+$/u.test(e)))return`explicit:${e}`}function nm(e,t){let n=Oi(`${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 Cc,randomBytes as k2}from"crypto";import{chmodSync as _2,closeSync as um,fstatSync as sR,lstatSync as O2,mkdirSync as B2,openSync as uR,readSync as $2,readdirSync as dR,renameSync as j2,rmSync as mR,statSync as H2,writeSync as U2}from"fs";import{tmpdir as z2}from"os";import{join as qo}from"path";import{StringDecoder as pR}from"string_decoder";import{InvalidArgumentError as aR}from"commander";var N2=/^[A-Za-z0-9_@%+=:,./-]+$/u;function oR(e,t={}){return t.omitSafeQuotes&&N2.test(e)?e:(t.platform??process.platform)==="win32"?`"${e.replaceAll("%","%%").replaceAll('"','\\"')}"`:`'${e.replaceAll("'",`'"'"'`)}'`}var G2="codebaseiq-output-page",K2=1,q2="continue",vc=32e3,Cr=256,xr=1e5,xc=4096,dm=32e6,W2=64*1024*1024,V2=256*1024*1024,J2=32,mm=32768,fR=3600*1e3,gR=3;function hR(){return qo(z2(),`codebaseiq-output-pages-${typeof process.getuid=="function"?process.getuid():"user"}`)}var hm=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u,yR=/^[A-Za-z0-9_][A-Za-z0-9_-]{11}$/u,Y2=/^4\.([A-Za-z0-9_-]{22})\.([0-9a-z]{1,10})$/u,X2=/^([A-Za-z0-9_][A-Za-z0-9_-]{11})(?:\.([0-9a-z]{1,10}))?$/u,bR=1,Q2="quota.lock",Z2=2e3,eW=5,cR=1024*1024,tW=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)),lm,nW=Object.freeze({maxSnapshotBytes:W2,maxAggregateBytes:V2,maxSnapshotCount:J2});var SR={writeStdout:e=>{process.stdout.write(e)},writeStderr:e=>{process.stderr.write(e)}};async function iW(e,t,n=SR){return Yx({command:e.command,cwd:e.cwd,argv:e.argv,json:e.json,sessionEnabled:e.sourceSession,reemit:e.reemitSource},async()=>{try{await rW(e,t,n)}finally{em(!1)}})}async function rW(e,t,n){let i=e.pageSize??vc,r=e.snapshotRoot??hR(),o=mW(e.snapshotLimits),s=e.maxOutputCharacters??dm;if(!Number.isSafeInteger(s)||s<=0)throw new Error("Output character safety limit must be a positive integer.");let a=Math.min(s,dm);if(vR(i),e.cursor!==void 0&&e.cursor.length>xc)throw new Error(`Output cursor exceeds the ${xc}-character limit. Run the command again without --output-cursor.`);if(e.json&&e.pageSize===void 0&&e.cursor===void 0){e.command==="system-map"&&om(e.cwd,e.sourceSession!==!1),await oW(e,t,n);return}let c=PR(e.argv),l=TR(e.invocationPrefix),u=LR(e.command,e.cwd,l,c),d=e.cursor===void 0?void 0:RW(e.cursor,u);e.command==="system-map"&&!d&&om(e.cwd,e.sourceSession!==!1);let m=d?.snapshotId,p;if(d)try{p=cW(d,u,i,a,r,e.onSnapshotRead)}catch(v){let y=v instanceof Error?v.message:String(v);throw new Error(`${y} Restart with: ${DR(l,c,i)}`,{cause:v})}else{let v=new fm(u,l,e.command,e.cwd,c,i,a,r,o,!e.json),y=sW(S=>v.write(S)),E=!1;try{await t(),E=!0}finally{y(),E||v.abort()}let w;try{w=v.complete()}catch(S){throw v.abort(),S}m=w.snapshotId,p={content:w.content,offset:0,pageIndex:0,pageCount:w.pageCount,totalCharacters:w.totalCharacters,outputHash:w.outputHash}}let f=p.offset+p.content.length,g=p.pageIndex+1>=p.pageCount,h=g?void 0:CW({invocationPrefix:l,nextPageIndex:p.pageIndex+1,snapshotId:bW(m)});if(rm(e.command,e.cwd,g,e.sourceSession!==!1,h?.command),p.offset===0&&g&&e.cursor===void 0){n.writeStdout(p.content),em(!0),m&&ki(m,r);return}let b={kind:G2,schemaVersion:K2,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:p.offset,returnedCharacters:p.content.length,totalCharacters:p.totalCharacters,omittedCharacters:p.totalCharacters-p.content.length,remainingCharacters:p.totalCharacters-f,complete:!1,outputHash:p.outputHash,continuation:h}:{offset:p.offset,returnedCharacters:p.content.length,totalCharacters:p.totalCharacters,omittedCharacters:p.totalCharacters-p.content.length,remainingCharacters:p.totalCharacters-f,complete:!0,outputHash:p.outputHash},content:p.content};if(e.json){n.writeStdout(`${JSON.stringify(b)}
551
- `),g&&m&&ki(m,r);return}n.writeStdout(DW(b)),g&&m&&ki(m,r)}async function Lce(e,t,n=hR(),i=SR){if(e.length>xc)throw new Error(`Output cursor exceeds the ${xc}-character limit.`);let r=IR(e);if(!r)throw new Error("Invalid output cursor. Run the original command again.");let o=xR(r.snapshotId,n);await iW({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.")},i)}function Pce(e){if(!/^\d+$/u.test(e))throw new aR(`Output page size must be an integer from ${Cr} through ${xr}.`);let t=Number(e);try{vR(t)}catch{throw new aR(`Output page size must be an integer from ${Cr} through ${xr}.`)}return t}function vR(e){if(!Number.isSafeInteger(e)||e<Cr||e>xr)throw new Error(`Output page size must be an integer from ${Cr} through ${xr}.`)}async function oW(e,t,n){let i=new pm(vc,e.maxOutputCharacters??dm),r=process.stdout.write,o=!1,s=`${ft(`codebaseiq: JSON output exceeds ${vc} characters and may be truncated by the client. Do not use possibly partial client output as evidence. Read every page with: ${DR(TR(e.invocationPrefix),PR(e.argv),vc)}`)}
552
- `;process.stdout.write=((a,c,l)=>{let u=i.push(a,c);return u!==void 0&&(o||(o=!0,n.writeStderr(s)),r.call(process.stdout,u)),CR(c,l),!0});try{await t();let a=i.finish();a.crossedPageBoundary&&!o&&(o=!0,n.writeStderr(s)),a.bytes.length>0&&r.call(process.stdout,a.bytes),o&&n.writeStderr(s),rm(e.command,e.cwd,!0,e.sourceSession!==!1)}finally{process.stdout.write=r}}function sW(e){let t=process.stdout.write;return process.stdout.write=((n,i,r)=>{let o=aW(n,i);return e(o),CR(i,r),!0}),()=>{process.stdout.write=t}}function aW(e,t){return typeof e=="string"?Buffer.from(e,typeof t=="string"?t:"utf8"):Buffer.from(e)}function CR(e,t){let n=typeof e=="function"?e:t;typeof n=="function"&&n()}var pm=class{constructor(t,n){this.limit=t;this.maxOutputCharacters=n}limit;maxOutputCharacters;decoder=new pR("utf8");chunks=[];overflowed=!1;totalCharacters=0;push(t,n){let i=typeof t=="string"?Buffer.from(t,typeof n=="string"?n:"utf8"):Buffer.from(t);if(this.addCharacters(this.decoder.write(i)),this.overflowed)return i;if(this.chunks.push(i),this.totalCharacters<=this.limit)return;this.overflowed=!0;let r=Buffer.concat(this.chunks);return this.chunks.length=0,r}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.`)}},fm=class{constructor(t,n,i,r,o,s,a,c,l,u){this.invocationHash=t;this.invocationPrefix=n;this.command=i;this.cwd=r;this.argv=o;this.pageSize=s;this.maxOutputCharacters=a;this.snapshotRoot=c;this.limits=l;this.preferLineBoundaries=u;ym(c);do this.snapshotId=k2(9).toString("base64url");while(this.snapshotId.startsWith("-"));this.temporaryPath=kn(c,this.snapshotId,"tmp")}invocationHash;invocationPrefix;command;cwd;argv;pageSize;maxOutputCharacters;snapshotRoot;limits;preferLineBoundaries;snapshotId;temporaryPath;decoder=new pR("utf8");hash=Cc("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 r=this.pending,o=Buffer.from(r);return this.assertWithinByteLimit(o.length),this.hash.update(o),this.pending="",{content:r,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.");um(this.descriptor),this.descriptor=null;let t=this.hash.digest("hex"),n=kn(this.snapshotRoot,this.snapshotId,"output"),i=kn(this.snapshotRoot,this.snapshotId,"json");try{j2(this.temporaryPath,n);let r={version:gR,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 Yt(i,r),lR(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(r){throw ki(this.snapshotId,this.snapshotRoot),r}}abort(){this.descriptor!==null&&(um(this.descriptor),this.descriptor=null),this.finished=!0,ki(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 i=vW(this.pending,this.pageSize,this.preferLineBoundaries),r=this.pending.slice(0,i);this.pending=this.pending.slice(i),this.flushPage(r)}}open(){if(!this.opened){pW(this.snapshotRoot,this.snapshotId,0,this.limits);try{this.descriptor=uR(this.temporaryPath,"wx",384),this.opened=!0}catch(t){throw fW(this.snapshotRoot,this.snapshotId),t}}}flushPage(t){if(this.descriptor===null)throw new Error("Output snapshot writer is not open.");if(this.pages.length>=mm)throw new Error(`Command output requires more than ${mm} snapshot pages. Retry with a larger --output-page-size or narrow the query.`);let n=Buffer.from(t),i=this.byteLength+n.length;if(this.assertWithinByteLimit(i),i>this.reservedBytes){let s=Math.min(this.limits.maxSnapshotBytes,Math.ceil(i/cR)*cR);lR(this.snapshotRoot,this.snapshotId,s,"active",this.limits),this.reservedBytes=s}let r=0;for(;r<n.length;){let s=U2(this.descriptor,n,r,n.length-r);if(s<=0)throw new Error("Output snapshot write made no progress.");r+=s}let o={characterOffset:this.pageCharacterOffset,characterLength:t.length,byteOffset:this.byteLength,byteLength:n.length,hash:Cc("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=i}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 cW(e,t,n,i,r,o){ym(r);let s=xR(e.snapshotId,r);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>i)throw new Error(`Output snapshot exceeds the ${i}-character safety limit.`);if(Date.now()-s.createdAtMs>fR)throw ki(e.snapshotId,r),new Error("Output snapshot expired before all pages were read.");let c=kn(r,e.snapshotId,"output"),l=uR(c,"r");try{let u=sR(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=$2(l,d,m,d.length-m,a.byteOffset+m);if(g===0)break;m+=g,o?.(g)}let p=sR(l);if(p.dev!==u.dev||p.ino!==u.ino||p.size!==u.size||m!==a.byteLength)throw new Error("Output snapshot changed while it was being read.");if(Cc("sha256").update(d).digest("hex")!==a.hash)throw new Error("Output snapshot page no longer matches its metadata.");let f=d.toString("utf8");if(f.length!==a.characterLength)throw new Error("Output snapshot page character count changed.");return{content:f,offset:a.characterOffset,pageIndex:e.pageIndex,pageCount:s.pages.length,totalCharacters:s.totalCharacters,outputHash:s.outputHash}}catch(u){throw ki(e.snapshotId,r),u}finally{um(l)}}function xR(e,t){if(!si(e))throw new Error("Output snapshot identifier is invalid.");let n;try{n=JSON.parse(vt(kn(t,e,"json"),"output snapshot metadata"))}catch(i){throw new Error("Output snapshot is unavailable.",{cause:i})}if(!lW(n))throw new Error("Output snapshot metadata is invalid.");return n}function lW(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===gR&&typeof t.snapshotId=="string"&&si(t.snapshotId)&&Ko(t.invocationHash)&&MR(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&&PW(t.argv)&&LR(t.command,t.cwd,t.invocationPrefix,t.argv)===t.invocationHash&&Ko(t.outputHash)&&Number.isSafeInteger(t.pageSize)&&(t.pageSize??0)>=Cr&&(t.pageSize??0)<=xr&&Array.isArray(t.pages)&&t.pages.length>1&&t.pages.length<=mm&&t.pages.every(uW)&&dW(t.pages)&&Number.isSafeInteger(t.totalCharacters)&&(t.totalCharacters??-1)>=0&&t.pages.reduce((n,i)=>n+i.characterLength,0)===t.totalCharacters&&Number.isSafeInteger(t.byteLength)&&(t.byteLength??-1)>=0&&t.pages.reduce((n,i)=>n+i.byteLength,0)===t.byteLength&&Number.isSafeInteger(t.createdAtMs)&&(t.createdAtMs??-1)>=0}function uW(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&&Ko(t.hash)}function dW(e){let t=0,n=0;for(let i of e){if(i.characterOffset!==t||i.byteOffset!==n)return!1;t+=i.characterLength,n+=i.byteLength}return!0}function ym(e){B2(e,{recursive:!0,mode:448});let t=O2(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"&&_2(e,448)}function mW(e){let t={...nW,...e};for(let[n,i]of Object.entries(t))if(!Number.isSafeInteger(i)||i<=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 pW(e,t,n,i){Rc(e,()=>{hW(e),RR(e,t,n,"active",i)})}function lR(e,t,n,i,r){if(!Number.isSafeInteger(n)||n<0||n>r.maxSnapshotBytes)throw new Error(`Command output exceeds the ${r.maxSnapshotBytes}-byte snapshot limit.`);Rc(e,()=>{RR(e,t,n,i,r)})}function RR(e,t,n,i,r){if(!Number.isSafeInteger(n)||n<0||n>r.maxSnapshotBytes)throw new Error(`Command output exceeds the ${r.maxSnapshotBytes}-byte snapshot limit.`);let o=gW(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>r.maxSnapshotCount||a>r.maxAggregateBytes)throw new Error(`Output snapshot capacity is full (${c}/${r.maxSnapshotCount} snapshots, ${a}/${r.maxAggregateBytes} bytes). Narrow the query or finish an existing pagination sequence before retrying.`);let l=Date.now(),u={version:bR,snapshotId:t,pid:process.pid,...gm()?{processIdentity:gm()}:{},reservedBytes:n,state:i,createdAtMs:s?.createdAtMs??l,updatedAtMs:l};Yt(kn(e,t,"reserve"),u)}function fW(e,t){Rc(e,()=>{mR(kn(e,t,"reserve"),{force:!0})})}function gW(e){let t=[];for(let n of dR(e,{withFileTypes:!0})){if(!n.isFile()||!n.name.endsWith(".reserve"))continue;let i=n.name.slice(0,-8);if(si(i))try{let r=JSON.parse(vt(qo(e,n.name),"output snapshot reservation"));if(!ER(r)||r.snapshotId!==i)throw new Error("reservation identity is invalid");t.push(r)}catch(r){throw new Error(`Output snapshot reservation ${n.name} is invalid; retry after its owning process or snapshot expires.`,{cause:r})}}return t}function ER(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===bR&&typeof t.snapshotId=="string"&&si(t.snapshotId)&&Number.isSafeInteger(t.pid)&&(t.pid??0)>0&&(t.processIdentity===void 0||Pm(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 hW(e){let t=Date.now();for(let n of dR(e,{withFileTypes:!0})){if(!n.isFile()||!n.name.endsWith(".reserve"))continue;let i=n.name.slice(0,-8);if(!si(i))continue;let r=null;try{let c=JSON.parse(vt(qo(e,n.name),"output snapshot reservation"));r=ER(c)?c:null}catch{r=null}let o=yW(kn(e,i,"json")),s=r?.state==="active"&&ts(r.pid)&&(r.processIdentity===void 0||(()=>{let c=Er(r.pid);return c!==null&&Xo(r.processIdentity,c)})()),a=r?t-r.updatedAtMs>fR:!1;s||o&&!a||!o&&r&&!a&&r.state==="complete"||wR(i,e)}}function yW(e){try{return H2(e),!0}catch{return!1}}function Rc(e,t){ym(e);let n=qo(e,Q2),i=Date.now()+Z2;for(;;){let r=Oi(n,{kind:"output-snapshot-quota",processIdentity:gm()});if(r.kind==="acquired")try{return t()}finally{r.lock.release()}if(Date.now()>=i)throw new Error("Output snapshot quota is busy. Retry the command.");Atomics.wait(tW,0,0,eW)}}function gm(){return lm===void 0&&(lm=Er(process.pid)),lm}function ki(e,t){si(e)&&Rc(t,()=>wR(e,t))}function wR(e,t){for(let n of["json","output","tmp","reserve"])mR(kn(t,e,n),{force:!0})}function kn(e,t,n){if(!si(t))throw new Error("Output snapshot identifier is invalid.");return qo(e,`${t}.${n}`)}function bW(e){if(!e)throw new Error("Incomplete output did not create a resumable snapshot.");return e}function SW(e){return e>=55296&&e<=56319}function vW(e,t,n){if(n){let i=e.lastIndexOf(`
553
- `,t-1);if(i>=0)return i+1}return SW(e.charCodeAt(t-1))?t-1:t}function CW(e){let t=xW({pageIndex:e.nextPageIndex,snapshotId:e.snapshotId});return{cursor:t,command:LW(e.invocationPrefix,t)}}function xW(e){return yR.test(e.snapshotId)?e.pageIndex===1?e.snapshotId:`${e.snapshotId}.${e.pageIndex.toString(36)}`:`4.${wW(e.snapshotId)}.${e.pageIndex.toString(36)}`}function RW(e,t){let n=IR(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 IR(e){let t=X2.exec(e);if(t){let i=t[2]??"1",r=Number.parseInt(i,36);return Number.isSafeInteger(r)&&r>=1&&r.toString(36)===i?{version:4,pageIndex:r,snapshotId:t[1]}:null}let n=Y2.exec(e);if(n){let i=IW(n[1]),r=Number.parseInt(n[2],36);return i&&Number.isSafeInteger(r)&&r>=1&&r.toString(36)===n[2]?{version:4,pageIndex:r,snapshotId:i}:null}try{let i=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return EW(i)?i:null}catch{return null}}function EW(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===3&&Ko(t.invocationHash)&&Number.isSafeInteger(t.pageIndex)&&(t.pageIndex??-1)>=1&&Number.isSafeInteger(t.pageSize)&&(t.pageSize??0)>=Cr&&(t.pageSize??0)<=xr&&Ko(t.outputHash)&&typeof t.snapshotId=="string"&&si(t.snapshotId)}function wW(e){if(!hm.test(e))throw new Error("Output snapshot identifier is invalid.");return Buffer.from(e.replaceAll("-",""),"hex").toString("base64url")}function IW(e){let t=Buffer.from(e,"base64url");if(t.length!==16)return null;let n=t.toString("hex"),i=`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`;return hm.test(i)?i:null}function si(e){return typeof e=="string"&&(yR.test(e)||hm.test(e))}function Ko(e){return typeof e=="string"&&/^[a-f0-9]{64}$/u.test(e)}function LR(e,t,n,i){return Cc("sha256").update(JSON.stringify({command:e,cwd:t,invocationPrefix:n,argv:i})).digest("hex")}function PR(e){let t=[];for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="--output-page-size"||i==="--output-cursor"){n+=1;continue}i.startsWith("--output-page-size=")||i.startsWith("--output-cursor=")||t.push(i)}return t}function DR(e,t,n){return AR([...e,...t,"--output-page-size",String(n)])}function LW(e,t){return AR([...e,q2,t])}function TR(e){let t=e===void 0?["codebaseiq"]:[...e];if(!MR(t))throw new Error("Output pagination invocation prefix must contain one to sixteen non-empty shell arguments.");return t}function MR(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(`
554
- `))}function PW(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(`
555
- `))}function AR(e){return e.map(t=>oR(t,{omitSafeQuotes:!0})).join(" ")}function DW(e){let t=e.page.continuation,n=Math.max(e.page.offset,e.page.offset+e.page.returnedCharacters-1),i=`[codebaseiq output page: characters ${e.page.offset}-${n} of ${e.page.totalCharacters}]
556
- `,r=t?`
557
- [Incomplete: ${e.page.remainingCharacters} characters remain. Continue exactly:
558
- ${t.command}]
559
- `:`
560
- [codebaseiq transport complete; evaluate command coverage separately]
561
- `;return`${i}${e.content}${r}`}export{Ar as a,en as b,qp as c,YW as d,bi as e,_L as f,Fl as g,XP as h,no as i,$p as j,$V as k,io as l,ro as m,da as n,zh as o,dT as p,NT as q,C5 as r,J4 as s,jT as t,qT as u,Kt as v,$M as w,OA as x,bo as y,Iu as z,sF as A,Ti as B,WF as C,YF as D,XF as E,QF as F,dN as G,fN as H,gN as I,hN as J,bN as K,SN as L,vN as M,oS as N,Co as O,Fu as P,zN as Q,xo as R,WN as S,VN as T,tk as U,sk as V,ak as W,ck as X,wo as Y,$u as Z,Io as _,p_ as $,Lo as aa,Po as ba,Hu as ca,Do as da,To as ea,Uu as fa,oO as ga,Mo as ha,dB as ia,Yu as ja,Xu as ka,JB as la,yr as ma,xv as na,D$ as oa,Fo as pa,sj as qa,ko as ra,Dj as sa,_o as ta,vH as ua,CH as va,DH as wa,zH as xa,YH as ya,pU as za,Rd as Aa,kC as Ba,wd as Ca,_C as Da,nc as Ea,zU as Fa,Ho as Ga,Uo as Ha,zo as Ia,Xz as Ja,Qz as Ka,Zz as La,Nd as Ma,cc as Na,_d as Oa,AG as Pa,pK as Qa,fK as Ra,hK as Sa,bK as Ta,DK as Ua,_K as Va,Fi as Wa,Vse as Xa,oae as Ya,Js as Za,PI as _a,El as $a,E5 as ab,wl as bb,Hx as cb,Cq as db,Mae as eb,Aae as fb,Fae as gb,$q as hb,Nae as ib,kae as jb,_ae as kb,Vae as lb,Jae as mb,Yae as nb,Xae as ob,Qae as pb,Zae as qb,cce as rb,lce as sb,q2 as tb,vc as ub,iW as vb,Lce as wb,Pce as xb};
562
- //# sourceMappingURL=chunk-GTIYTDRE.js.map