scip-query 0.24.0 → 0.26.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 (661) hide show
  1. package/CHANGELOG.md +247 -1
  2. package/README.md +111 -124
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/by-kind-PRVFAGTQ.js +2 -0
  5. package/dist/call-graph-DVPAQV2F.js +2 -0
  6. package/dist/{call-graph-evidence-BociKRpF.d.ts → call-graph-evidence-CUtj8V2I.d.ts} +1 -1
  7. package/dist/chunk-2FSBGL5P.js +2 -0
  8. package/dist/chunk-2HLAFUCY.js +2 -0
  9. package/dist/chunk-2IWUT6CJ.js +3 -0
  10. package/dist/chunk-2KNN7GTQ.js +2 -0
  11. package/dist/chunk-2LHXRE2B.js +8 -0
  12. package/dist/{chunk-E65ELFKU.js → chunk-2YXE77TJ.js} +2 -2
  13. package/dist/chunk-36SGVCGX.js +2 -0
  14. package/dist/chunk-3ABBFPTP.js +2 -0
  15. package/dist/chunk-3IVFU4FD.js +3 -0
  16. package/dist/chunk-3JIQS44J.js +7 -0
  17. package/dist/chunk-3ZRB6DNK.js +7 -0
  18. package/dist/{chunk-6YTSKJJ3.js → chunk-42EOW5VI.js} +1 -1
  19. package/dist/{chunk-BHKK5RJY.js → chunk-4BHGBMNO.js} +2 -2
  20. package/dist/chunk-4BP3UBDG.js +2 -0
  21. package/dist/chunk-4D6RO7G4.js +2 -0
  22. package/dist/chunk-4FEWQ6RH.js +2 -0
  23. package/dist/chunk-4IGEOBG7.js +2 -0
  24. package/dist/chunk-4QZXBUKC.js +2 -0
  25. package/dist/chunk-4WBDEVX2.js +4 -0
  26. package/dist/chunk-4WCUBZU3.js +8 -0
  27. package/dist/chunk-4WTUBQ36.js +40 -0
  28. package/dist/chunk-4XQ4O6IM.js +3 -0
  29. package/dist/chunk-55UQAMZO.js +4 -0
  30. package/dist/chunk-5D2LVK7O.js +125 -0
  31. package/dist/chunk-5IYJ56TT.js +2 -0
  32. package/dist/chunk-5PLMJC7Q.js +2 -0
  33. package/dist/chunk-5TNQJUR2.js +5 -0
  34. package/dist/chunk-62BDNPMI.js +2 -0
  35. package/dist/chunk-64DZ5TXR.js +7 -0
  36. package/dist/chunk-65245JCM.js +2 -0
  37. package/dist/chunk-6FFVZZL4.js +2 -0
  38. package/dist/chunk-6KO5JHAR.js +2 -0
  39. package/dist/chunk-6LRXOOSX.js +2 -0
  40. package/dist/chunk-6LSEIIF7.js +2 -0
  41. package/dist/chunk-6YMNWD3H.js +6 -0
  42. package/dist/chunk-72AD6ZRR.js +5 -0
  43. package/dist/chunk-73AAKPUC.js +4 -0
  44. package/dist/chunk-76CZ77DF.js +2 -0
  45. package/dist/chunk-7VPEEAAG.js +2 -0
  46. package/dist/chunk-7WTPQ4NX.js +14 -0
  47. package/dist/chunk-7Y5T6XDP.js +2 -0
  48. package/dist/chunk-A2IIGFMJ.js +5 -0
  49. package/dist/chunk-AB5KCTEV.js +2 -0
  50. package/dist/chunk-AC566WBP.js +6 -0
  51. package/dist/chunk-AGWFSTXC.js +3 -0
  52. package/dist/chunk-AOSIYPTA.js +2 -0
  53. package/dist/chunk-AUVEWPIF.js +2 -0
  54. package/dist/chunk-B56T42J3.js +25 -0
  55. package/dist/chunk-BIQEF5NE.js +2 -0
  56. package/dist/chunk-BL6XJKTA.js +3 -0
  57. package/dist/chunk-BMKOQJRI.js +2 -0
  58. package/dist/chunk-BOZ4EXBB.js +3 -0
  59. package/dist/chunk-BUTWYEPH.js +2 -0
  60. package/dist/chunk-BZB4QPIP.js +2 -0
  61. package/dist/{chunk-6ILKOOGH.js → chunk-CE357GEE.js} +4 -4
  62. package/dist/chunk-CFN45HFP.js +2 -0
  63. package/dist/chunk-CFYMZFXT.js +368 -0
  64. package/dist/chunk-CN5EH7O3.js +2 -0
  65. package/dist/chunk-D254DNNQ.js +4 -0
  66. package/dist/chunk-D3FDISIC.js +2 -0
  67. package/dist/chunk-D3NX5XIE.js +3 -0
  68. package/dist/chunk-DA7RPPDF.js +3 -0
  69. package/dist/chunk-DDMC3FON.js +3 -0
  70. package/dist/chunk-DIO3FUSG.js +2 -0
  71. package/dist/chunk-DJ2NNSUK.js +3 -0
  72. package/dist/chunk-DKYQIM3C.js +18 -0
  73. package/dist/{chunk-OHIV323X.js → chunk-DOOEL2IV.js} +2 -2
  74. package/dist/chunk-DVFP6PZI.js +2 -0
  75. package/dist/chunk-E3FDPXZK.js +2 -0
  76. package/dist/chunk-E7YNJLCB.js +2 -0
  77. package/dist/chunk-EFGW5JPH.js +2 -0
  78. package/dist/chunk-EJVTR244.js +13 -0
  79. package/dist/chunk-EOV7RTRZ.js +2 -0
  80. package/dist/chunk-ETOIKRHO.js +2 -0
  81. package/dist/chunk-EYK3ZAO2.js +3 -0
  82. package/dist/chunk-F2V2LPET.js +52 -0
  83. package/dist/chunk-F4LUHJTF.js +2 -0
  84. package/dist/chunk-F4PUT6IT.js +2 -0
  85. package/dist/chunk-F56GCXXS.js +5 -0
  86. package/dist/chunk-FC2EVQRM.js +2 -0
  87. package/dist/chunk-FL7NBMHP.js +3 -0
  88. package/dist/chunk-FMRN2TRL.js +3 -0
  89. package/dist/chunk-FVULPZDF.js +20 -0
  90. package/dist/chunk-GCKCF5FL.js +43 -0
  91. package/dist/chunk-GH2PYF46.js +2 -0
  92. package/dist/chunk-GHJAGXIP.js +2 -0
  93. package/dist/{chunk-2GJSD5GY.js → chunk-GMVSHUKZ.js} +2 -2
  94. package/dist/chunk-GS6KDO4R.js +2 -0
  95. package/dist/chunk-GUUBXNN7.js +2 -0
  96. package/dist/chunk-GVWX5T43.js +80 -0
  97. package/dist/chunk-GZKFETP5.js +2 -0
  98. package/dist/chunk-H4EQHO6J.js +9 -0
  99. package/dist/chunk-H73WY2RM.js +2 -0
  100. package/dist/chunk-H75GSPRV.js +60 -0
  101. package/dist/chunk-HDR3AHSV.js +61 -0
  102. package/dist/chunk-HQBSL74Y.js +2 -0
  103. package/dist/chunk-HRRFKWPZ.js +2 -0
  104. package/dist/chunk-HXENDJC6.js +2 -0
  105. package/dist/chunk-IIBAZNSW.js +21 -0
  106. package/dist/chunk-INLMWEUU.js +12 -0
  107. package/dist/chunk-IWQPAF4F.js +2 -0
  108. package/dist/chunk-IZJ6YUKP.js +35 -0
  109. package/dist/chunk-J2TMAIN5.js +60 -0
  110. package/dist/chunk-J5FJMODQ.js +142 -0
  111. package/dist/chunk-J7HZPIO3.js +2 -0
  112. package/dist/chunk-JEVRKFRL.js +2 -0
  113. package/dist/chunk-JFXSGAEB.js +30 -0
  114. package/dist/chunk-JVRTHGFS.js +3 -0
  115. package/dist/chunk-JYWEX7RR.js +360 -0
  116. package/dist/chunk-K3YL22N6.js +2 -0
  117. package/dist/chunk-K4CN7GXK.js +12 -0
  118. package/dist/chunk-K5TBVXU4.js +30 -0
  119. package/dist/chunk-KDDIE2DP.js +9 -0
  120. package/dist/chunk-KHWRRPV4.js +2 -0
  121. package/dist/chunk-KI6NBKDY.js +14 -0
  122. package/dist/chunk-KU3QRSTH.js +2 -0
  123. package/dist/chunk-KZBJWZJB.js +2 -0
  124. package/dist/chunk-L7GFM3NP.js +3 -0
  125. package/dist/chunk-LMO6PK3V.js +35 -0
  126. package/dist/chunk-LN4YXJJU.js +2 -0
  127. package/dist/chunk-LOVIZBJ4.js +43 -0
  128. package/dist/chunk-LPCRK4A2.js +11 -0
  129. package/dist/chunk-MMHZKBFA.js +2 -0
  130. package/dist/{chunk-A4WEAK35.js → chunk-MOQQBQRD.js} +2 -2
  131. package/dist/chunk-N2WN6I3L.js +2 -0
  132. package/dist/chunk-N3ORQT7L.js +2 -0
  133. package/dist/chunk-NAZ3RAIW.js +2 -0
  134. package/dist/chunk-NDUNO5JQ.js +2 -0
  135. package/dist/chunk-NEIWRNAZ.js +4 -0
  136. package/dist/chunk-NJJMVD65.js +2 -0
  137. package/dist/chunk-NLOQOBXI.js +20 -0
  138. package/dist/chunk-NOLZOVCU.js +2 -0
  139. package/dist/chunk-NOWINRRN.js +2 -0
  140. package/dist/chunk-NZAXKGRL.js +16 -0
  141. package/dist/chunk-O2C4UILI.js +2 -0
  142. package/dist/chunk-O3RHA6ZT.js +3 -0
  143. package/dist/chunk-O4UZSPPI.js +3 -0
  144. package/dist/chunk-OGFV2BUX.js +2 -0
  145. package/dist/chunk-OZCJXZK6.js +499 -0
  146. package/dist/chunk-P6ODM7BY.js +2 -0
  147. package/dist/{chunk-GHNPACNP.js → chunk-PAVGPRHJ.js} +2 -2
  148. package/dist/chunk-PH52RA7D.js +2 -0
  149. package/dist/chunk-PKN354TH.js +3 -0
  150. package/dist/chunk-PWOASWEG.js +11 -0
  151. package/dist/chunk-QIWXRW72.js +2 -0
  152. package/dist/chunk-QJRMOK5N.js +2 -0
  153. package/dist/{chunk-YXPUP5G2.js → chunk-QOIXNWQR.js} +2 -2
  154. package/dist/chunk-QXEUDXBT.js +3 -0
  155. package/dist/chunk-QYUVVBMR.js +6 -0
  156. package/dist/chunk-QZ7KQZRN.js +2 -0
  157. package/dist/chunk-R6LQBUDH.js +2 -0
  158. package/dist/chunk-RBS42E55.js +20 -0
  159. package/dist/chunk-RSJKPCFX.js +26 -0
  160. package/dist/chunk-S6CZA3MV.js +2 -0
  161. package/dist/chunk-STMVAHJP.js +2 -0
  162. package/dist/chunk-SYVPTTVW.js +2 -0
  163. package/dist/chunk-T6DK3ZP7.js +2 -0
  164. package/dist/chunk-TKD34PHN.js +4 -0
  165. package/dist/chunk-TNNQFH7W.js +2 -0
  166. package/dist/chunk-TNV7SSUF.js +2 -0
  167. package/dist/chunk-TO7ZR3EH.js +8 -0
  168. package/dist/chunk-TOU3CHK4.js +2 -0
  169. package/dist/chunk-TRBI4UKT.js +2 -0
  170. package/dist/chunk-TZCVNCAN.js +4 -0
  171. package/dist/chunk-U4LZA5LL.js +3 -0
  172. package/dist/chunk-U5RIG3JP.js +3 -0
  173. package/dist/chunk-UP5KXN2I.js +2 -0
  174. package/dist/chunk-UQFR3NDH.js +5 -0
  175. package/dist/chunk-UXYXF7GV.js +2 -0
  176. package/dist/chunk-VB3GOKOS.js +2 -0
  177. package/dist/{chunk-4FR6GQIT.js → chunk-VF5JZICY.js} +2 -2
  178. package/dist/chunk-VTY3VK6E.js +2 -0
  179. package/dist/chunk-VX2O4RIS.js +2 -0
  180. package/dist/chunk-WKPV2TDZ.js +2 -0
  181. package/dist/chunk-WOFQ5DTB.js +2 -0
  182. package/dist/chunk-WS4C6TCK.js +2 -0
  183. package/dist/chunk-WXU3DGPU.js +2 -0
  184. package/dist/{chunk-ATXPTSEI.js → chunk-X6RMKHJQ.js} +7 -7
  185. package/dist/{chunk-44IETFOU.js → chunk-XHMN6ZX7.js} +2 -2
  186. package/dist/chunk-XHTVFLWW.js +2 -0
  187. package/dist/chunk-XKIDJCIK.js +2 -0
  188. package/dist/chunk-XTYTYZPT.js +2 -0
  189. package/dist/chunk-Y2JHHTTA.js +2 -0
  190. package/dist/chunk-YGVRMGYN.js +4 -0
  191. package/dist/chunk-YNQCGEQE.js +2 -0
  192. package/dist/chunk-YOQVEXVE.js +14 -0
  193. package/dist/chunk-YRT2WLYY.js +2 -0
  194. package/dist/chunk-YTAP5Y2G.js +2 -0
  195. package/dist/chunk-YTYWI7VB.js +2 -0
  196. package/dist/chunk-YULZRALL.js +2 -0
  197. package/dist/chunk-Z33WQG4Q.js +2 -0
  198. package/dist/chunk-ZGTYGDMF.js +16 -0
  199. package/dist/chunk-ZHMRSZFD.js +43 -0
  200. package/dist/chunk-ZHSP366W.js +10 -0
  201. package/dist/chunk-ZIBYCYKK.js +7 -0
  202. package/dist/chunk-ZLADLUE6.js +3 -0
  203. package/dist/chunk-ZO4YXUT6.js +4 -0
  204. package/dist/{chunk-MZPXPSUJ.js → chunk-ZR4HBC2H.js} +2 -2
  205. package/dist/cli-main.js +6 -6
  206. package/dist/cli.js +1 -1
  207. package/dist/{code-B17qEMbt.d.ts → code-BNyrCF3_.d.ts} +3 -2
  208. package/dist/code-IL5WH3NZ.js +2 -0
  209. package/dist/code-result-json-ANTBEDFP.js +4 -0
  210. package/dist/command-descriptors-HEEMDHTU.js +222 -0
  211. package/dist/deps-EOWFC6FD.js +2 -0
  212. package/dist/direct-navigation-Y5B6OSIQ.js +3 -0
  213. package/dist/{exploration-topology-BG4v30HZ.d.ts → exploration-topology-CSgEyAz-.d.ts} +3 -1
  214. package/dist/files-K4AI3JUM.js +2 -0
  215. package/dist/{health-BI2a9WPy.d.ts → health-BtfmNrfa.d.ts} +5 -79
  216. package/dist/hierarchy-6W5NDIFI.js +2 -0
  217. package/dist/imports-WH365QY4.js +2 -0
  218. package/dist/index.d.ts +13 -1
  219. package/dist/index.js +1 -1
  220. package/dist/members-K3PHMF5S.js +2 -0
  221. package/dist/methods-E7KVMBX4.js +2 -0
  222. package/dist/output-continuation-command-BJSY67SN.js +3 -0
  223. package/dist/output-pagination-UZJ5ACIX.js +24 -0
  224. package/dist/postinstall.js +1 -1
  225. package/dist/project-reindex-EP24WT4X.js +3 -0
  226. package/dist/queries/affected.js +1 -1
  227. package/dist/queries/architecture.d.ts +15 -4
  228. package/dist/queries/architecture.js +1 -1
  229. package/dist/queries/bottlenecks.js +1 -1
  230. package/dist/queries/by-kind.js +1 -1
  231. package/dist/queries/call-graph.d.ts +1 -1
  232. package/dist/queries/call-graph.js +1 -1
  233. package/dist/queries/change-surface.d.ts +1 -0
  234. package/dist/queries/change-surface.js +1 -1
  235. package/dist/queries/cleanup-plan.d.ts +3 -3
  236. package/dist/queries/cleanup-plan.js +1 -1
  237. package/dist/queries/co-change.js +1 -1
  238. package/dist/queries/code.d.ts +1 -1
  239. package/dist/queries/code.js +1 -1
  240. package/dist/queries/complexity.d.ts +6 -3
  241. package/dist/queries/complexity.js +1 -1
  242. package/dist/queries/context.d.ts +1 -7
  243. package/dist/queries/context.js +1 -1
  244. package/dist/queries/coupling.js +1 -1
  245. package/dist/queries/cycles.js +1 -1
  246. package/dist/queries/dead.js +1 -1
  247. package/dist/queries/decorative-checkers.js +1 -1
  248. package/dist/queries/dependence-slice.d.ts +46 -22
  249. package/dist/queries/dependence-slice.js +1 -1
  250. package/dist/queries/dependency-depth.d.ts +1 -7
  251. package/dist/queries/dependency-depth.js +1 -1
  252. package/dist/queries/deps.js +1 -1
  253. package/dist/queries/diff-impact.d.ts +3 -1
  254. package/dist/queries/diff-impact.js +1 -1
  255. package/dist/queries/doc-drift.js +1 -1
  256. package/dist/queries/drift.d.ts +1 -1
  257. package/dist/queries/drift.js +1 -1
  258. package/dist/queries/duplicate-bodies.d.ts +1 -1
  259. package/dist/queries/duplicate-bodies.js +1 -1
  260. package/dist/queries/entry-map.d.ts +2 -4
  261. package/dist/queries/entry-map.js +1 -1
  262. package/dist/queries/evidence.d.ts +121 -61
  263. package/dist/queries/evidence.js +1 -1
  264. package/dist/queries/fan.js +1 -1
  265. package/dist/queries/files.js +1 -1
  266. package/dist/queries/health.d.ts +1 -1
  267. package/dist/queries/health.js +1 -1
  268. package/dist/queries/hierarchy.d.ts +2 -2
  269. package/dist/queries/hierarchy.js +1 -1
  270. package/dist/queries/hotspots.d.ts +1 -1
  271. package/dist/queries/hotspots.js +1 -1
  272. package/dist/queries/imports.d.ts +1 -0
  273. package/dist/queries/imports.js +1 -1
  274. package/dist/queries/incomplete-migration.d.ts +3 -3
  275. package/dist/queries/incomplete-migration.js +1 -1
  276. package/dist/queries/index.d.ts +15 -64
  277. package/dist/queries/index.js +1 -1
  278. package/dist/queries/locality-candidates.d.ts +4 -4
  279. package/dist/queries/locality-candidates.js +1 -1
  280. package/dist/queries/members.d.ts +2 -2
  281. package/dist/queries/members.js +1 -1
  282. package/dist/queries/methods.js +1 -1
  283. package/dist/queries/not-implemented.d.ts +2 -6
  284. package/dist/queries/not-implemented.js +1 -1
  285. package/dist/queries/outline.js +1 -1
  286. package/dist/queries/passthrough-candidates.js +1 -1
  287. package/dist/queries/react-component-duplicates.js +1 -1
  288. package/dist/queries/react-hook-candidates.js +1 -1
  289. package/dist/queries/react-large-component-pressure.js +1 -1
  290. package/dist/queries/recent-duplicates.js +1 -1
  291. package/dist/queries/redundant-reexports.d.ts +4 -14
  292. package/dist/queries/redundant-reexports.js +1 -1
  293. package/dist/queries/refs.d.ts +4 -1
  294. package/dist/queries/refs.js +1 -1
  295. package/dist/queries/review.d.ts +188 -0
  296. package/dist/queries/review.js +2 -0
  297. package/dist/queries/similar-files.d.ts +7 -10
  298. package/dist/queries/similar-files.js +1 -1
  299. package/dist/queries/similar-signatures.js +1 -1
  300. package/dist/queries/similar.d.ts +19 -1
  301. package/dist/queries/similar.js +1 -1
  302. package/dist/queries/slice-cohesion.d.ts +205 -0
  303. package/dist/queries/slice-cohesion.js +2 -0
  304. package/dist/queries/source-inspection.d.ts +6 -202
  305. package/dist/queries/source-inspection.js +1 -1
  306. package/dist/queries/source-search.d.ts +2 -3
  307. package/dist/queries/source-search.js +1 -1
  308. package/dist/queries/stats.d.ts +1 -0
  309. package/dist/queries/stats.js +1 -1
  310. package/dist/queries/surface.js +1 -1
  311. package/dist/queries/symbols.js +1 -1
  312. package/dist/queries/system.d.ts +4 -2
  313. package/dist/queries/system.js +1 -1
  314. package/dist/queries/test-quality.d.ts +1 -1
  315. package/dist/queries/test-quality.js +1 -1
  316. package/dist/queries/twin-drift.d.ts +1 -1
  317. package/dist/queries/twin-drift.js +1 -1
  318. package/dist/queries/unused-imports.js +1 -1
  319. package/dist/queries/unused-params.d.ts +3 -15
  320. package/dist/queries/unused-params.js +1 -1
  321. package/dist/queries/vue-component-duplicates.js +1 -1
  322. package/dist/queries/vue-composable-candidates.js +1 -1
  323. package/dist/queries/vue-large-view-pressure.js +1 -1
  324. package/dist/query-service-fastpath.js +5 -5
  325. package/dist/query-service-server.js +4 -4
  326. package/dist/refs-CCBJG7WK.js +2 -0
  327. package/dist/refs-pagination-DRNLVU4S.js +2 -0
  328. package/dist/reindex-worker.js +79 -29
  329. package/dist/reindex.js +45 -45
  330. package/dist/repository-cache-worker.js +2 -0
  331. package/dist/runtime.d.ts +8 -8
  332. package/dist/runtime.js +3 -4
  333. package/dist/rust-semantic-session-server.js +1 -1
  334. package/dist/rust-semantic-session-worker.js +1 -1
  335. package/dist/rust-semantic-worker.js +1 -1
  336. package/dist/service-queries-2WAJI7R6.js +6 -0
  337. package/dist/source-inspection-91U9zdO3.d.ts +341 -0
  338. package/dist/{source-search-types-Dwz8KeuW.d.ts → source-search-types-DWGYNg8M.d.ts} +15 -2
  339. package/dist/stats-G7DIV6VU.js +2 -0
  340. package/dist/surface-IO55UALI.js +2 -0
  341. package/dist/system-ZBMSHJXU.js +2 -0
  342. package/dist/{queries/trace.d.ts → trace-BMjw3prn.d.ts} +1 -18
  343. package/dist/typescript-indexer.js +2 -0
  344. package/dist/typescript-mailbox-worker.js +1 -1
  345. package/dist/watch-server.js +3 -3
  346. package/docs/AGENT_GUIDE.md +19 -128
  347. package/docs/CLI_JSON_OUTPUT.md +21 -17
  348. package/docs/COMMAND_REFERENCE.md +34 -49
  349. package/docs/CURRENT_COMMANDS.md +123 -0
  350. package/docs/DETECTOR_EVIDENCE_CONTRACTS.md +0 -40
  351. package/docs/DETECTOR_GUIDE.md +27 -23
  352. package/docs/PRODUCT_VISION.md +135 -0
  353. package/docs/PROPERTY_TESTING.md +73 -0
  354. package/docs/REVIEW.md +76 -0
  355. package/docs/SKILLS.md +51 -0
  356. package/docs/WINDOWS_SIDECAR_RELEASE.md +12 -3
  357. package/docs/accuracy-audit-checklist.md +34 -0
  358. package/docs/analyzer-inventory.md +2 -2
  359. package/package.json +18 -80
  360. package/scripts/evidence-product-contract.mjs +7 -3
  361. package/scripts/record-review-coverage.mjs +118 -0
  362. package/scripts/scip-windows-provenance.mjs +29 -19
  363. package/skills/scip-architecture-review/SKILL.md +57 -0
  364. package/skills/scip-architecture-review/agents/openai.yaml +4 -0
  365. package/skills/scip-architecture-review/references/design-checks.md +17 -0
  366. package/skills/scip-explore/SKILL.md +15 -59
  367. package/skills/scip-explore/agents/openai.yaml +3 -3
  368. package/skills/scip-explore/references/external-evidence.md +2 -2
  369. package/skills/scip-explore/references/information-model.md +26 -29
  370. package/skills/scip-explore/scripts/capture-evidence.mjs +68 -34
  371. package/skills/scip-integrity-audit/SKILL.md +53 -181
  372. package/skills/scip-integrity-audit/agents/openai.yaml +3 -3
  373. package/skills/scip-integrity-audit/references/integrity-probes.md +27 -0
  374. package/skills/scip-plan/SKILL.md +39 -65
  375. package/skills/scip-plan/agents/openai.yaml +2 -2
  376. package/skills/scip-query/SKILL.md +28 -81
  377. package/skills/scip-query/agents/openai.yaml +2 -2
  378. package/skills/scip-query/references/command-guide.md +169 -0
  379. package/skills/scip-setup/SKILL.md +4 -2
  380. package/skills/scip-setup/agents/openai.yaml +3 -3
  381. package/dist/by-kind-H3P6BR5G.js +0 -2
  382. package/dist/call-graph-VTG2CUOQ.js +0 -2
  383. package/dist/chunk-26CT72HM.js +0 -2
  384. package/dist/chunk-2BMSSRBH.js +0 -2
  385. package/dist/chunk-2M2LSIMY.js +0 -7
  386. package/dist/chunk-2N6WBNDC.js +0 -29
  387. package/dist/chunk-2OOY75BW.js +0 -2
  388. package/dist/chunk-2USA3S3P.js +0 -3
  389. package/dist/chunk-2VAHDDLM.js +0 -133
  390. package/dist/chunk-2XWIUW5Z.js +0 -455
  391. package/dist/chunk-35NLDRZC.js +0 -2
  392. package/dist/chunk-3AF4TUFK.js +0 -3
  393. package/dist/chunk-3D4BOXW6.js +0 -20
  394. package/dist/chunk-3LO4FST5.js +0 -16
  395. package/dist/chunk-3WTY4LP2.js +0 -3
  396. package/dist/chunk-3Z5AMSK6.js +0 -29
  397. package/dist/chunk-4KBTHJLP.js +0 -2
  398. package/dist/chunk-5BIKR67W.js +0 -2
  399. package/dist/chunk-5PROPLHI.js +0 -2
  400. package/dist/chunk-5V7EPTII.js +0 -2
  401. package/dist/chunk-62LPZCBQ.js +0 -3
  402. package/dist/chunk-64O2JHQA.js +0 -2
  403. package/dist/chunk-6D4F5VWG.js +0 -10
  404. package/dist/chunk-6ERFBC3X.js +0 -3
  405. package/dist/chunk-6MFXCMZC.js +0 -2
  406. package/dist/chunk-6O7FACKB.js +0 -2
  407. package/dist/chunk-6TS3KOXR.js +0 -2
  408. package/dist/chunk-76QOU4PK.js +0 -3
  409. package/dist/chunk-7DUI77BN.js +0 -2
  410. package/dist/chunk-7F45LJKI.js +0 -2
  411. package/dist/chunk-7F7T6DCR.js +0 -2
  412. package/dist/chunk-7H6VHWWJ.js +0 -2
  413. package/dist/chunk-7HXT6YLU.js +0 -5
  414. package/dist/chunk-7KCZELVM.js +0 -2
  415. package/dist/chunk-7R4V5ES6.js +0 -6
  416. package/dist/chunk-7RIRIADH.js +0 -7
  417. package/dist/chunk-7ZLWLOGT.js +0 -2
  418. package/dist/chunk-AADQLOQ4.js +0 -38
  419. package/dist/chunk-AN76MGUE.js +0 -2
  420. package/dist/chunk-ANLNLY66.js +0 -2
  421. package/dist/chunk-AX7IDVFT.js +0 -2
  422. package/dist/chunk-B3X6KU75.js +0 -2
  423. package/dist/chunk-B7MPDEAK.js +0 -3
  424. package/dist/chunk-BBB5FBX4.js +0 -2
  425. package/dist/chunk-BJT7LSPK.js +0 -3
  426. package/dist/chunk-BJWFVAA5.js +0 -2
  427. package/dist/chunk-BKVWUP7Y.js +0 -2
  428. package/dist/chunk-BKZYTLGE.js +0 -35
  429. package/dist/chunk-BL6DCHQP.js +0 -2
  430. package/dist/chunk-BOW7SSQH.js +0 -43
  431. package/dist/chunk-C4RHHCKL.js +0 -7
  432. package/dist/chunk-C7C6AKAT.js +0 -117
  433. package/dist/chunk-CD6M6LS2.js +0 -16
  434. package/dist/chunk-CFE6PSG6.js +0 -2
  435. package/dist/chunk-CFNIGQMT.js +0 -2
  436. package/dist/chunk-CKBUBRYD.js +0 -2
  437. package/dist/chunk-CZW5MZ5B.js +0 -2
  438. package/dist/chunk-DBBZ63ZX.js +0 -2
  439. package/dist/chunk-DBN7DMJB.js +0 -18
  440. package/dist/chunk-DUULLZHZ.js +0 -3
  441. package/dist/chunk-DV5Y5NOS.js +0 -2
  442. package/dist/chunk-DZOIKCTM.js +0 -3
  443. package/dist/chunk-E4PKTOL3.js +0 -2
  444. package/dist/chunk-E7QR35ST.js +0 -2
  445. package/dist/chunk-EFSXAINW.js +0 -2
  446. package/dist/chunk-EHVEIEQN.js +0 -18
  447. package/dist/chunk-EHYDXE3Z.js +0 -2
  448. package/dist/chunk-EP63Y6LD.js +0 -2
  449. package/dist/chunk-EPX6NQN6.js +0 -4
  450. package/dist/chunk-ETC674NS.js +0 -5
  451. package/dist/chunk-F5GSBHC6.js +0 -3
  452. package/dist/chunk-FH3DGXC6.js +0 -2
  453. package/dist/chunk-FI7VGOR4.js +0 -16
  454. package/dist/chunk-FJF6VO2P.js +0 -2
  455. package/dist/chunk-FLMTCX5R.js +0 -2
  456. package/dist/chunk-FVFDOIM3.js +0 -2
  457. package/dist/chunk-G2HU5WRN.js +0 -2
  458. package/dist/chunk-G4ALYS4J.js +0 -2
  459. package/dist/chunk-G56I7K4W.js +0 -26
  460. package/dist/chunk-GC4DG2V5.js +0 -2
  461. package/dist/chunk-GG45PK4S.js +0 -4
  462. package/dist/chunk-GINH3YQU.js +0 -20
  463. package/dist/chunk-GTZZVLKJ.js +0 -2
  464. package/dist/chunk-GXXW5ZHH.js +0 -2
  465. package/dist/chunk-H5EXS3HM.js +0 -2
  466. package/dist/chunk-HAXXKRTD.js +0 -4
  467. package/dist/chunk-HEZWBAZY.js +0 -2
  468. package/dist/chunk-HMEWLMML.js +0 -2
  469. package/dist/chunk-HOBOVYPO.js +0 -11
  470. package/dist/chunk-HRFQ6GW5.js +0 -8
  471. package/dist/chunk-HX4X7KG3.js +0 -2
  472. package/dist/chunk-HYT2R7LX.js +0 -4
  473. package/dist/chunk-IKQVBVQL.js +0 -40
  474. package/dist/chunk-IW5XQG5G.js +0 -2
  475. package/dist/chunk-J6GLBBRK.js +0 -4
  476. package/dist/chunk-J7A4PWFX.js +0 -3
  477. package/dist/chunk-JCSAZ35V.js +0 -2
  478. package/dist/chunk-JDU2IV3A.js +0 -2
  479. package/dist/chunk-JFMEXGFE.js +0 -2
  480. package/dist/chunk-JFMI5SGB.js +0 -4
  481. package/dist/chunk-JJP37RGX.js +0 -57
  482. package/dist/chunk-JZ2A7LDM.js +0 -5
  483. package/dist/chunk-KMVGRIO2.js +0 -2
  484. package/dist/chunk-KNLQGXVH.js +0 -80
  485. package/dist/chunk-KVQCECPR.js +0 -2
  486. package/dist/chunk-KXXORBZ2.js +0 -4
  487. package/dist/chunk-L5KYH6U3.js +0 -35
  488. package/dist/chunk-L6XHYJPZ.js +0 -21
  489. package/dist/chunk-L7KTFEAV.js +0 -43
  490. package/dist/chunk-LDXHR5EL.js +0 -23
  491. package/dist/chunk-LEECKFCJ.js +0 -2
  492. package/dist/chunk-MHGDSBFX.js +0 -2
  493. package/dist/chunk-MLQVVDG3.js +0 -74
  494. package/dist/chunk-MOKUWRHO.js +0 -3
  495. package/dist/chunk-MPYAPMNE.js +0 -2
  496. package/dist/chunk-MTDBHTSF.js +0 -2
  497. package/dist/chunk-MV6SPXCR.js +0 -7
  498. package/dist/chunk-MWN53KRN.js +0 -60
  499. package/dist/chunk-MXNGIEPU.js +0 -3
  500. package/dist/chunk-N55KIE46.js +0 -2
  501. package/dist/chunk-NB4D3BNM.js +0 -2
  502. package/dist/chunk-NGKBOT6G.js +0 -23
  503. package/dist/chunk-NJGKXKQF.js +0 -2
  504. package/dist/chunk-NJQISBL4.js +0 -8
  505. package/dist/chunk-NJT3ZEKY.js +0 -16
  506. package/dist/chunk-NKMKZP6A.js +0 -2
  507. package/dist/chunk-NODFZ6ED.js +0 -2
  508. package/dist/chunk-NSM5IEVW.js +0 -2
  509. package/dist/chunk-NTGUVNR2.js +0 -3
  510. package/dist/chunk-NU3KFF2O.js +0 -57
  511. package/dist/chunk-NWLVNU66.js +0 -557
  512. package/dist/chunk-NYKZMCRC.js +0 -4
  513. package/dist/chunk-O6BUXZEH.js +0 -6
  514. package/dist/chunk-ODPDP7A4.js +0 -3
  515. package/dist/chunk-OIAPEKMT.js +0 -3
  516. package/dist/chunk-OIOC5EHF.js +0 -3
  517. package/dist/chunk-ONPPQM4G.js +0 -2
  518. package/dist/chunk-OUHEZBYI.js +0 -2
  519. package/dist/chunk-OVGYW7UD.js +0 -29
  520. package/dist/chunk-OYKU4B3Y.js +0 -2
  521. package/dist/chunk-POBJ6FR2.js +0 -5
  522. package/dist/chunk-PSZPMMWN.js +0 -2
  523. package/dist/chunk-PXTRBKRK.js +0 -3
  524. package/dist/chunk-Q5JRIHT3.js +0 -4
  525. package/dist/chunk-Q7ATHARX.js +0 -2
  526. package/dist/chunk-Q7CSKIDM.js +0 -5
  527. package/dist/chunk-QBQE7ZJ5.js +0 -3
  528. package/dist/chunk-QH22UIXP.js +0 -5
  529. package/dist/chunk-QXCKQTKR.js +0 -60
  530. package/dist/chunk-RBAD4GJ2.js +0 -13
  531. package/dist/chunk-RMDPFPNW.js +0 -2
  532. package/dist/chunk-ROPJDEJZ.js +0 -4
  533. package/dist/chunk-RVZC6TJE.js +0 -2
  534. package/dist/chunk-S4QZBKSR.js +0 -3
  535. package/dist/chunk-SCPMZ73U.js +0 -2
  536. package/dist/chunk-SIAP5RGI.js +0 -73
  537. package/dist/chunk-SIX4RFR3.js +0 -3
  538. package/dist/chunk-SKKXTABJ.js +0 -16
  539. package/dist/chunk-SSRFUQBD.js +0 -2
  540. package/dist/chunk-SYVJEEUJ.js +0 -3
  541. package/dist/chunk-T3CZAZSI.js +0 -8
  542. package/dist/chunk-T6DWDI5E.js +0 -3
  543. package/dist/chunk-T6HRIROJ.js +0 -7
  544. package/dist/chunk-TAA7HXHE.js +0 -2
  545. package/dist/chunk-TJ2JQYT3.js +0 -2
  546. package/dist/chunk-TULNMD5T.js +0 -368
  547. package/dist/chunk-U2FPY5XA.js +0 -3
  548. package/dist/chunk-U3SXIMII.js +0 -38
  549. package/dist/chunk-U6KCHXJ4.js +0 -2
  550. package/dist/chunk-UH3XSKS5.js +0 -9
  551. package/dist/chunk-UIFUZVCC.js +0 -2
  552. package/dist/chunk-UXKURIVI.js +0 -2
  553. package/dist/chunk-V2RBODHL.js +0 -2
  554. package/dist/chunk-VBKUWB6N.js +0 -2
  555. package/dist/chunk-VBV6ALJE.js +0 -2
  556. package/dist/chunk-VDGFWCQV.js +0 -2
  557. package/dist/chunk-VDSDOEWF.js +0 -2
  558. package/dist/chunk-VZPWVCLN.js +0 -20
  559. package/dist/chunk-WDSFQDPN.js +0 -2
  560. package/dist/chunk-WFA35BGR.js +0 -7
  561. package/dist/chunk-WLMP3OCW.js +0 -2
  562. package/dist/chunk-WSA52GOR.js +0 -2
  563. package/dist/chunk-WYPL7GF7.js +0 -2
  564. package/dist/chunk-X3YVZAKZ.js +0 -5
  565. package/dist/chunk-X6OGVFIT.js +0 -2
  566. package/dist/chunk-XDAUYDFT.js +0 -2
  567. package/dist/chunk-XKXTR6ZI.js +0 -9
  568. package/dist/chunk-Y5DFAW5W.js +0 -4
  569. package/dist/chunk-YSYPDRD5.js +0 -3
  570. package/dist/chunk-ZFVPWH62.js +0 -5
  571. package/dist/chunk-ZGIHTH27.js +0 -2
  572. package/dist/chunk-ZGIQN2SX.js +0 -2
  573. package/dist/chunk-ZHG4WAHR.js +0 -12
  574. package/dist/chunk-ZKB2XUEN.js +0 -4
  575. package/dist/chunk-ZLMXIQLC.js +0 -21
  576. package/dist/chunk-ZMCQIHI4.js +0 -2
  577. package/dist/code-TAVIKWJI.js +0 -2
  578. package/dist/code-result-json-5FEFQCAQ.js +0 -2
  579. package/dist/command-descriptors-7BKH53Y3.js +0 -343
  580. package/dist/dataflow-GFBTVDH3.js +0 -2
  581. package/dist/dependence-slice-GWGQCODG.js +0 -2
  582. package/dist/deps-4QHVDPYA.js +0 -2
  583. package/dist/direct-navigation-4UBC6HNW.js +0 -3
  584. package/dist/entry-map-QCTF4RVY.js +0 -2
  585. package/dist/files-M2UBF5HJ.js +0 -2
  586. package/dist/graph-evidence-Bjyky2V4.d.ts +0 -126
  587. package/dist/hierarchy-2UIHRLW4.js +0 -2
  588. package/dist/imports-WIE3YZOB.js +0 -2
  589. package/dist/members-YKD636DA.js +0 -2
  590. package/dist/methods-VDF4IMYG.js +0 -2
  591. package/dist/next-anchor-candidates-BwMczMvX.d.ts +0 -90
  592. package/dist/output-continuation-command-4UMDOOLO.js +0 -3
  593. package/dist/output-pagination-2GME6OPY.js +0 -19
  594. package/dist/project-reindex-XEQTRCV5.js +0 -3
  595. package/dist/queries/anchors.d.ts +0 -123
  596. package/dist/queries/anchors.js +0 -2
  597. package/dist/queries/complexity-hotspots.d.ts +0 -40
  598. package/dist/queries/complexity-hotspots.js +0 -2
  599. package/dist/queries/convergence.d.ts +0 -33
  600. package/dist/queries/convergence.js +0 -2
  601. package/dist/queries/dataflow.d.ts +0 -77
  602. package/dist/queries/dataflow.js +0 -2
  603. package/dist/queries/deep-chains.d.ts +0 -5
  604. package/dist/queries/deep-chains.js +0 -2
  605. package/dist/queries/extract-candidates.d.ts +0 -79
  606. package/dist/queries/extract-candidates.js +0 -2
  607. package/dist/queries/isolated.d.ts +0 -24
  608. package/dist/queries/isolated.js +0 -2
  609. package/dist/queries/plan-context.d.ts +0 -33
  610. package/dist/queries/plan-context.js +0 -2
  611. package/dist/queries/reference-neighborhood.d.ts +0 -4
  612. package/dist/queries/reference-neighborhood.js +0 -2
  613. package/dist/queries/reference-reachability.d.ts +0 -48
  614. package/dist/queries/reference-reachability.js +0 -2
  615. package/dist/queries/self-audit.d.ts +0 -69
  616. package/dist/queries/self-audit.js +0 -2
  617. package/dist/queries/similar-chains.d.ts +0 -48
  618. package/dist/queries/similar-chains.js +0 -2
  619. package/dist/queries/slice.d.ts +0 -4
  620. package/dist/queries/slice.js +0 -2
  621. package/dist/queries/stale-abstractions.d.ts +0 -72
  622. package/dist/queries/stale-abstractions.js +0 -2
  623. package/dist/queries/system-map.d.ts +0 -449
  624. package/dist/queries/system-map.js +0 -2
  625. package/dist/queries/trace.js +0 -2
  626. package/dist/queries/twin-ab.d.ts +0 -66
  627. package/dist/queries/twin-ab.js +0 -2
  628. package/dist/queries/value-flow.d.ts +0 -43
  629. package/dist/queries/value-flow.js +0 -2
  630. package/dist/queries/wrapper-candidates.d.ts +0 -49
  631. package/dist/queries/wrapper-candidates.js +0 -2
  632. package/dist/refs-JNK5CLM7.js +0 -2
  633. package/dist/refs-pagination-6BLRYGMV.js +0 -2
  634. package/dist/slice-PHPVNCWX.js +0 -2
  635. package/dist/source-snippet-_wrcgmZc.d.ts +0 -15
  636. package/dist/stats-OOJ74B32.js +0 -2
  637. package/dist/surface-MQX5MPIV.js +0 -2
  638. package/dist/symbol-resolution-DBLVXLBC.js +0 -2
  639. package/dist/system-JOPKV4OG.js +0 -2
  640. package/dist/trace-I2P2YFH4.js +0 -2
  641. package/dist/value-flow-JJVMF7NP.js +0 -2
  642. package/skills/concrete-plan/SKILL.md +0 -8
  643. package/skills/concrete-plan/agents/openai.yaml +0 -4
  644. package/skills/conductor/SKILL.md +0 -110
  645. package/skills/conductor/agents/openai.yaml +0 -4
  646. package/skills/principal-maintainability-review/SKILL.md +0 -273
  647. package/skills/principal-maintainability-review/agents/openai.yaml +0 -4
  648. package/skills/scip-calibrate/SKILL.md +0 -102
  649. package/skills/scip-calibrate/agents/openai.yaml +0 -4
  650. package/skills/scip-claim-audit/SKILL.md +0 -113
  651. package/skills/scip-claim-audit/agents/openai.yaml +0 -4
  652. package/skills/scip-probe-reachability/SKILL.md +0 -93
  653. package/skills/scip-probe-reachability/agents/openai.yaml +0 -4
  654. package/skills/scip-root-cause/SKILL.md +0 -160
  655. package/skills/scip-root-cause/agents/openai.yaml +0 -4
  656. package/skills/scip-system-compression/SKILL.md +0 -252
  657. package/skills/scip-system-compression/agents/openai.yaml +0 -4
  658. package/skills/scip-system-compression/references/compression-atlas.md +0 -116
  659. package/skills/scip-system-compression/references/compression-patterns.md +0 -87
  660. package/skills/scip-twin-drift/SKILL.md +0 -109
  661. package/skills/scip-twin-drift/agents/openai.yaml +0 -4
@@ -1,557 +0,0 @@
1
- #!/usr/bin/env node
2
- import{$ as jf,$a as Ul,$c as ea,$d as _g,Aa as jl,Ab as zs,Ac as Qe,Ae as la,B as Nl,Ba as Lt,Bb as Ks,Bc as Re,Bd as go,Be as jg,C as _l,Ca as Us,Cb as Ie,Cc as fe,Cd as na,Ce as ua,Da as ci,Db as Dt,Dc as Ge,De as Hg,E as _f,Ea as jt,Eb as uo,Ec as gi,Ee as ho,Ef as Zg,Fb as ig,Fc as pg,Ff as eh,G as Of,Ga as Hl,Gb as og,Gc as fg,Ge as Xl,Gf as th,Ha as Wf,Hb as ae,Hc as hi,Hd as kg,He as Ql,Ib as sg,Ic as yi,Ie as Ug,Ja as Rr,Jb as Ws,Jc as gg,Je as qg,Kb as Gl,Kc as q,Lb as zl,Lc as ye,M as Ol,Mb as Ir,Mc as hg,Nb as mo,Nc as yg,Ne as Ci,Oa as Vf,Oc as po,Pa as co,Pc as Qs,Pd as Ag,Qa as Vt,Qb as J,Qc as bg,Qd as bi,Ra as te,Rb as jn,Rc as Oe,Rd as ra,Sa as Yf,Sb as Kl,Sc as Zs,Sd as ia,T as Bf,Tb as W,Tc as we,Td as Si,Te as Gg,Ua as Yt,Ub as ag,Uc as U,Ud as At,Ue as zg,Va as Pt,Vb as cg,Vc as Wl,Wa as pt,Wb as Vs,Wc as qn,Wd as Pr,We as da,Xb as Mt,Xc as Sg,Xe as Kg,Y as $f,Yb as Jt,Yc as vg,Yd as Fg,Ye as Wg,Za as Jf,Zb as lg,Zc as Cg,Zd as Ng,Ze as Vg,_ as xr,_a as Xf,_c as xg,_d as Dr,_e as Yg,ab as Qf,ac as di,ad as vn,ae as Cn,bb as Q,bc as Ys,bd as wr,c as ao,cb as li,cc as Tt,cd as Rg,ce as oa,db as Zf,dc as mi,dd as re,e as Tf,ea as Hf,eb as eg,ec as ug,ed as Ze,ee as Kn,fd as Lr,fe as Mr,gb as ql,gc as bn,gd as ta,ge as sa,h as kf,hb as tg,hc as ce,hd as Ht,i as Bs,ib as ng,ic as dg,id as Gn,j as pe,ja as Bl,jb as lo,jc as pi,jd as Xt,k as ke,kb as xe,kc as Js,kd as Eg,la as js,lc as Hn,ld as Ig,m as hn,ma as $l,mc as _e,md as wg,n as $s,na as Uf,nd as Vl,ne as Og,o as yn,oa as qf,od as Lg,p as si,pa as ve,pb as rg,pf as Zl,qa as Ce,qb as N,qe as Jl,ra as wt,rb as ui,rd as Yl,re as aa,rf as eu,s as ai,sa as Hs,sb as qs,sc as Sn,sd as fo,t as It,ta as Gf,tb as ft,tc as Un,td as Pg,te as ca,tf as Jg,u as Xe,ua as zf,ub as Er,uc as mg,ud as zn,ue as Wn,vb as Ne,vc as T,vd as Dg,w as Af,wb as V,wc as G,wd as Mg,x as Fl,xa as Kf,xb as $n,xc as fi,xd as Tg,xe as vi,y as Ff,ya as Z,yb as K,yc as Xs,ye as Bg,yf as Xg,z as Nf,zb as Gs,zc as kt,ze as $g,zf as Qg}from"./chunk-2XWIUW5Z.js";import{existsSync as YL}from"fs";import{isAbsolute as nh,join as JL}from"path";function gt(e,t){let n=tu(e,t,{allowMultiple:!1})[0]?.relativePath;return n||oh(e,t)}function Tr(e,t){return tu(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function rh(e,t){let n=tu(e,t,{allowMultiple:!0});return n.length===1?n[0].relativePath:null}function ih(e,t){let n=li(e,t,{allowMultiple:!0,requirePathMatch:!0});return n.length===1?n[0].relativePath:null}function oh(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=nh(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,i=JL(e.config.projectRoot,r);return YL(i)?r:null}function tu(e,t,n){let r=oh(e,t);if(r)return li(e,r,n).filter(a=>a.relativePath===r);let i=t.replace(/\\/g,"/").replace(/^\.\//,""),o=nh(i)||i.includes("/"),s=li(e,t,{...n,requirePathMatch:o});if(s.length===0){if(o)return[];let a=re(e,t);return!a||e.isIgnored(a.relativePath)?[]:[{relativePath:a.relativePath,score:700}]}return s}function sh(e,t){let n=rh(e,t);if(!n)return[];let r=Qs(e,[n],{sort:!0});if(r.length===0)return[];let i=Math.max(0,$n(V(e,n)).length-1),o=r.map(c=>({symbol:c.symbol,shortName:c.shortName,startLine:c.startLine,endLine:Math.min(c.endLine,i),signature:c.signature,children:[]})),s=new Map;for(let c of o)s.set(c.symbol,c);let a=[];for(let c=0;c<r.length;c++){let u=r[c],l=o[c];if(u.enclosingSymbol&&s.has(u.enclosingSymbol)){s.get(u.enclosingSymbol).children.push(l);continue}let d=null,m=1/0;for(let p of o)if(p!==l&&p.startLine<=l.startLine&&p.endLine>=l.endLine){if(p.startLine===l.startLine&&p.endLine===l.endLine&&!fg(p.symbol,l.symbol))continue;let g=p.endLine-p.startLine;g<m&&(m=g,d=p)}d?d.children.push(l):a.push(l)}return a}import{basename as xD,extname as Wh}from"path";function ht(e,t){let n=K(e,t.relativePath);if(n.length===0)return!1;let r=G(t.symbol);if(!r)return!1;let i=n.slice(Math.max(0,t.startLine-2),t.startLine+1).join(`
3
- `),o=Ie(r);return new RegExp(`^\\s*export\\s+(?:default\\s+)?(?:(?:async\\s+)?function\\s+${o}\\b|(?:abstract\\s+)?class\\s+${o}\\b|(?:interface|type|enum|namespace|module)\\s+${o}\\b|(?:const|let|var)\\s+${o}\\b)`,"m").test(i)?!0:XL(n,r)}function XL(e,t){if(!t)return!1;let n=new RegExp(`^\\s*export\\s*\\{[^}\\n]*\\b${Ie(t)}\\b`);return e.some(r=>n.test(r))}import{createHash as QL}from"crypto";import{isUtf8 as ZL}from"buffer";import{TextDecoder as eP}from"util";var ch=new eP("utf-8",{fatal:!0});function ru(e){return Hs(e.config.projectRoot)}function ma(e,t){let n=hn(t),r;try{r=$l(e.config.projectRoot,n,{inputKind:"repository text file"})}catch(o){if(Ce(o)||o instanceof Bl)return null;throw o}let i=tP(r);return i===null?null:uh(n,r,i,mh(e),dh(e))}function lh(e,t={}){let n=[],r=pa(e,t,i=>n.push(i));return{files:n,candidateFiles:r.candidateFiles,scannedBytes:r.scannedBytes,skippedBinaryPaths:r.skippedBinaryPaths,skippedUnreadablePaths:r.skippedUnreadablePaths,skippedOversizedPaths:r.skippedOversizedPaths}}function pa(e,t,n){let r=ru(e).filter(f=>!t.scope||f.includes(t.scope)),i=mh(e),o=dh(e),s=[],a=[],c=[],u=0,l=0,d={aligned:0,stale:0,unavailable:0},m=t.literalBytes?Buffer.isBuffer(t.literalBytes)?[t.literalBytes]:[...t.literalBytes]:[],p=m.length>0?Buffer.allocUnsafe(1024*1024):void 0;for(let f of r){let g,h,y=[],S=o.has(f);try{if(m.length>0){let x=m.length===1?Uf(e.config.projectRoot,f,m[0],{inputKind:"repository text file",computeSha256:S,scratchBuffer:p}):qf(e.config.projectRoot,f,m,{inputKind:"repository text file",computeSha256:S,scratchBuffer:p});if(!x.isUtf8Text){s.push(f);continue}u+=x.byteLength,l+=1,h=x.sha256;let v=nu(f,h,i,o);if(d[v.state]+=1,y="matchedLiteralIndexes"in x?x.matchedLiteralIndexes:x.includesLiteral?[0]:[],y.length===0||!x.bytes)continue;g=x.bytes}else g=$l(e.config.projectRoot,f,{inputKind:"repository text file"})}catch(x){if(x instanceof Bl){c.push(f);continue}if(Ce(x))continue;a.push(f);continue}if(m.length===0&&!ph(g)){s.push(f);continue}if(m.length===0){u+=g.byteLength,l+=1,h=S?fh(g):void 0;let x=nu(f,h,i,o);d[x.state]+=1}if(t.includeBytes&&!t.includeBytes(f,g))continue;let b=ch.decode(g);n(uh(f,g,b,i,o,h),y)}return{candidateFiles:r.length,scannedTextFiles:l,semanticFiles:d,scannedBytes:u,skippedBinaryPaths:s,skippedUnreadablePaths:a,skippedOversizedPaths:c}}function uh(e,t,n,r,i,o){let s=o??fh(t);return{relativePath:e,text:n,bytes:t.byteLength,freshness:{exactText:{state:"current",basis:"working-tree-read",sha256:s},semantic:nu(e,s,r,i)}}}function nu(e,t,n,r){if(!r.has(e))return{state:"unavailable",basis:"no-compiler-document"};let i=n.get(e);return!i||!t?{state:"unavailable",basis:"fingerprint-unavailable"}:{state:i===t?"aligned":"stale",basis:"indexed-input-fingerprint"}}function dh(e){return new Set(e.all(`SELECT documents.relative_path FROM documents WHERE 1 = 1 ${e.pathExclusionsFor("documents")}`).map(t=>t.relative_path))}function mh(e){let t=new Map;if(!e.generation.metadataRaw)return t;let n=Rr(e.generation.metadataRaw);if(n.kind!=="legacy"&&n.kind!=="supported")return t;let r=n.metadata.fingerprint;if(!ah(r)||!Array.isArray(r.files))return t;for(let i of r.files)!ah(i)||typeof i.path!="string"||typeof i.hash!="string"||t.set(i.path,i.hash);return t}function tP(e){return ph(e)?ch.decode(e):null}function ph(e){return!e.includes(0)&&ZL(e)}function fh(e){return QL("sha256").update(e).digest("hex")}function ah(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{SymbolInformation_Kind as de}from"@c4312/scip";var fa=new Map(Object.entries(de).filter(([e,t])=>Number.isInteger(Number(e))&&typeof t=="string").map(([e,t])=>[Number(e),t])),gh=new Map([...fa.entries()].map(([e,t])=>[t.toLowerCase(),e]));function yo(e){return fa.get(e)??"Unknown"}function Qt(){return[de.Function,de.Method,de.Macro,de.Constructor,de.Getter,de.Setter,de.StaticMethod,de.SingletonMethod,de.AbstractMethod,de.ProtocolMethod,de.TraitMethod]}function hh(){return[de.Class,de.Interface,de.Struct,de.Trait,de.Type,de.TypeAlias,de.Enum,de.Union,de.Protocol]}function fZ(){return[de.Constant,de.Variable,de.Value,de.Field,de.Property,de.StaticDataMember,de.StaticField,de.StaticProperty,de.StaticVariable,de.EnumMember]}import{existsSync as mP}from"fs";import{SymbolRole as pP}from"@c4312/scip";import{deserializeSCIP as nP}from"@c4312/scip";function yh(e,t){return nP(ai(e,{inputKind:t,maxBytes:si}))}import{fromBinary as rP}from"@bufbuild/protobuf";import{DocumentSchema as iP,SymbolRole as iu}from"@c4312/scip";import{zstdDecompressSync as oP}from"zlib";var sP=Vt("scip-chunk-occurrence-targets",{clearGroups:["whole-project","definition-catalog","source-file"],maxEntries:256}),aP=te("scip-chunk-occurrence-definitions",{clearGroups:["whole-project","definition-catalog"]}),bh=1,cP=te("scip-chunk-occurrence-data-present",{clearGroups:["whole-project"]});function ou(e){return cP.get(e,()=>{let t=e.get("SELECT length(occurrences) AS size FROM chunks LIMIT 1");return t!==void 0&&(t.size??0)>bh})}function Sh(e,t){return sP.get(e,t,()=>lP(e,t))}function su(e,t){return`${e}\0${t}`}function lP(e,t){let n=e.get("SELECT id FROM documents WHERE relative_path = ?",t);if(!n)return{available:!1,reason:"no-document"};let r=e.all("SELECT occurrences FROM chunks WHERE document_id = ? ORDER BY chunk_index",n.id);if(r.length===0)return ou(e)?{available:!0,targets:[],externalLeafKeys:new Set,locals:[]}:{available:!1,reason:"no-occurrence-data"};let i=aP.get(e,()=>new Map(ye(e).map(c=>[c.symbol,c]))),o=[],s=new Set,a=[];try{for(let c of r){let u=c.occurrences;if(!u||u.length<=bh)return{available:!1,reason:"no-occurrence-data"};let l=rP(iP,new Uint8Array(oP(u)));for(let d of l.occurrences){if(!d.symbol)continue;let m=d.range[0];if(!Number.isInteger(m))continue;if(d.symbol.startsWith("local ")){a.push(uP(d.symbol,d.range,d.symbolRoles));continue}if((d.symbolRoles&iu.Definition)!==0)continue;let p=i.get(d.symbol);if(p){o.push({sourceLine:m,definition:p});continue}let f=dP(d.symbol);f&&s.add(su(m,f))}}}catch{return{available:!1,reason:"no-occurrence-data"}}return{available:!0,targets:o,externalLeafKeys:s,locals:a}}function uP(e,t,n){let r=t.length===4;return{symbol:e,line:t[0],startChar:t[1]??0,endLine:r?t[2]:t[0],endChar:r?t[3]??0:t[2]??0,definition:(n&iu.Definition)!==0,write:(n&iu.WriteAccess)!==0}}function dP(e){if(e.startsWith("local "))return null;try{let t=G(e);return t.length>0?t:null}catch{return null}}var au=new WeakMap;function kr(e,t){let n=Sh(e,t);if(n.available)return{targets:n.targets,externalLeafKeys:n.externalLeafKeys,locals:n.locals};if(n.reason==="no-document")return null;if(ou(e))return{targets:[],externalLeafKeys:new Set,locals:[]};let r=fP(e);return r?{targets:r.byFile.get(t)??[],externalLeafKeys:new Set,locals:[]}:null}function xn(e,t,n,r){let i=W(e,t),o=(i?.callSites??[]).filter(p=>p.line>=n&&p.line<=r);if(!i||o.length===0)return{available:!!i,targets:[],resolvedCallsites:0,unresolvedCallsites:0};let s=kr(e,t);if(!s)return{available:!1,targets:[],resolvedCallsites:0,unresolvedCallsites:o.length};let a=s.targets.filter(p=>p.sourceLine>=n&&p.sourceLine<=r).map(p=>({...p,calleeLeaf:p.definition.leaf})),c=vh(o.map(p=>({line:p.line,leaf:p.calleeLeaf}))),u=vh(a.map(p=>({line:p.sourceLine,leaf:p.calleeLeaf}))),l=new Set([...c].flatMap(([p,f])=>u.get(p)===f?[p]:[])),d=a.filter(p=>l.has(xh(p.sourceLine,p.calleeLeaf))),m=[...l].reduce((p,f)=>p+(c.get(f)??0),0);return{available:!0,targets:d,resolvedCallsites:m,unresolvedCallsites:Math.max(0,o.length-m)}}function cu(e,t,n,r){let i=kr(e,t);return i?{available:!0,targets:i.targets.filter(o=>o.sourceLine>=n&&o.sourceLine<=r)}:{available:!1,targets:[]}}function Ch(e,t,n,r){let i=kr(e,t);return i?{available:!0,targets:i.targets.filter(o=>o.sourceLine>=n&&o.sourceLine<=r&&ga(e,o.definition)).map(o=>({...o,calleeLeaf:o.definition.leaf}))}:{available:!1,targets:[]}}function fP(e){if(au.has(e))return au.get(e)??null;let t=gP(e);return au.set(e,t),t}function gP(e){if(!e.generation.indexPath||!mP(e.generation.indexPath))return null;try{let t=ye(e),n=new Map(t.map(o=>[o.symbol,o])),r=yh(e.generation.indexPath,"SCIP source-range call-target index"),i=new Map;for(let o of r.documents??[]){let s=o.relativePath;if(!s||e.isIgnored(s))continue;let a=[];for(let c of o.occurrences??[]){if(!c.symbol||(c.symbolRoles&pP.Definition)!==0)continue;let u=n.get(c.symbol),l=c.range?.[0];!u||!Number.isInteger(l)||a.push({sourceLine:l,definition:u})}i.set(s,a)}return{byFile:i}}catch{return null}}function ga(e,t){if(!t.isFunctionLike)return!1;let n=W(e,t.relativePath);return!n||n.callables.some(r=>r.name===t.leaf&&r.startLine===t.startLine&&r.endLine===t.endLine)?!0:hP(t)}function hP(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 vh(e){let t=new Map;for(let n of e){let r=xh(n.line,n.leaf);t.set(r,(t.get(r)??0)+1)}return t}function xh(e,t){return`${e}\0${t}`}function Ft(e,t,n={}){let r=Ar(e,[t],{additive:n.additive,semantic:n.semantic,semanticEvidence:n.semanticEvidence}),i=n.callableOnly?(r.get(t.symbolId)??[]).filter(o=>Qe(o.symbol)||o.source==="ast-callsite"||o.source==="scip-occurrence"):r.get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}function Vn(e,t,n){return Rn(e,[t],n).get(t.symbolId)??[]}function Rn(e,t,n){let r=vP(e)?xP(e,t,{semantic:n.semantic!==!1,semanticEvidence:n.semanticEvidence}):CP(e,n.semanticEvidence);return typeof n.limit!="number"?new Map(t.map(i=>[i.symbolId,r.get(i.symbolId)??[]])):new Map(t.map(i=>[i.symbolId,(r.get(i.symbolId)??[]).slice(0,n.limit)]))}var yP=te("caller-rows",{clearGroups:["whole-project"]}),bP=te("targeted-caller-strategy",{clearGroups:["whole-project"]}),SP=2e4;function vP(e){return bP.get(e,()=>(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>SP)}function CP(e,t){return yP.get(e,()=>{let n=ye(e),r=Ar(e,n,{semanticEvidence:t}),i=new Map;for(let a of n)i.set(a.symbol,a.symbolId);let o=new Map,s=new Map;for(let a of n){let c=r.get(a.symbolId);if(!(!c||c.length===0))for(let u of c){let l=i.get(u.symbol);if(l===void 0||l===a.symbolId)continue;let d=o.get(l);d||(d=[],o.set(l,d),s.set(l,new Set));let m=`${a.symbol}|${a.relativePath}`;s.get(l).has(m)||(s.get(l).add(m),d.push({symbol:a.symbol,file:a.relativePath,source:"caller-map-inversion",callEvidence:u.source}))}}return o})}function xP(e,t,n){let r=n.semantic&&n.semanticEvidence?t.flatMap(p=>{let f=RP(e,p);return f?[f]:[]}):[],i=new Map(r.map(p=>[p.symbolId,p])),o=n.semanticEvidence?.referenceMap(e,r)??new Map,s=Pg(e,t),a=new Set(t.map(p=>p.symbol)),u=[...new Set(t.flatMap(p=>Hn(e,"reverse",[p.relativePath])))].flatMap(p=>q(e,p)),l=new Map,d=Eh(e,u);for(let p of u)for(let f of d.get(p.symbolId)??[]){if(!a.has(f.symbol))continue;let g=l.get(f.symbol)??[];g.push({symbol:p.symbol,file:p.relativePath,source:"caller-map-inversion",callEvidence:f.source}),l.set(f.symbol,g)}let m=new Map;for(let p of t){let f=[],g=new Set,h=S=>{if(S.symbol===p.symbol)return;let b=`${S.symbol}|${S.file}`;g.has(b)||(g.add(b),f.push(S))};for(let S of l.get(p.symbol)??[])h(S);for(let S of s.get(p.symbolId)??[])S.file!==p.relativePath&&h({symbol:S.enclosingSymbol??S.file,file:S.file,source:"resolved-reference"});let y=i.get(p.symbolId);if(y)for(let S of o.get(y.symbolId)??[]){if(S.file===p.relativePath||e.isIgnored(S.file))continue;let b=Oe(q(e,S.file),S.line);h({symbol:b?.symbol??S.file,file:S.file,source:"semantic-reference"})}m.set(p.symbolId,f)}return m}function RP(e,t){let n=Qt().join(", "),r=hh().join(", ");return e.get(`SELECT
4
- d.id AS documentId,
5
- gs.id AS symbolId,
6
- gs.symbol,
7
- d.relative_path AS relativePath,
8
- COALESCE(der.start_line, c.start_line) AS startLine,
9
- COALESCE(der.end_line, c.end_line) AS endLine,
10
- COALESCE(gs.display_name, '') AS leaf,
11
- NULL AS parentTypeName,
12
- CASE WHEN gs.kind IN (${n}) OR gs.symbol LIKE '%().' THEN 1 ELSE 0 END AS isFunctionLike,
13
- CASE WHEN gs.kind IN (${r}) THEN 1 ELSE 0 END AS isTypeLike,
14
- gs.kind AS kind,
15
- gs.documentation AS documentation,
16
- gs.enclosing_symbol AS enclosingSymbol
17
- FROM global_symbols gs
18
- LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
19
- LEFT JOIN chunks c ON c.document_id = der.document_id
20
- JOIN documents d ON d.id = COALESCE(der.document_id, c.document_id)
21
- WHERE gs.id = ?
22
- LIMIT 1`,t.symbolId)??null}function Ar(e,t,n={}){if(t.length===0)return new Map;let r=n.additive??!1,i=[],o=[];for(let l of t)ae(l.relativePath)&&Jt(e,l.relativePath)!==null?i.push(l):o.push(l);let s=new Map,a=new Map,c=l=>{for(let[d,m]of l){let p=s.get(d);p||(p=[],s.set(d,p));let f=a.get(d);f||(f=new Set,a.set(d,f));for(let g of m){let h=`${g.symbol}|${g.chunkId}`;f.has(h)||(f.add(h),p.push(g))}}};i.length>0&&c(Eh(e,i)),n.semantic!==!1&&n.semanticEvidence&&c(TP(n.semanticEvidence.calleeMap(e,t)));let u=r?t:o;return u.length>0&&c(DP(e,u)),s}function Eh(e,t){let n=new Map,r=wP(t,n),i=Xt(e);for(let[o,s]of r){let a=Jt(e,o);if(!a)continue;let c=bg(s),u=EP(kr(e,o));for(let l of a){let d=c.get(l.line);if(!d)continue;let m=u?IP(u,l):null,p=m??(u?.externalLeafKeys.has(su(l.line,l.calleeLeaf))?null:LP(e,o,i,l));p&&p.symbol!==d.symbol&&n.get(d.symbolId).push({symbol:p.symbol,file:p.file,chunkId:l.line,source:m?"scip-occurrence":"ast-callsite",callsiteLine:l.line,...l.kind==="jsx-render"?{kind:"jsx-render"}:{}})}}return n}function EP(e){if(!e)return null;let t=new Map;for(let n of e.targets){let r=t.get(n.sourceLine);r?r.push(n.definition):t.set(n.sourceLine,[n.definition])}return{targetsByLine:t,externalLeafKeys:e.externalLeafKeys}}function IP(e,t){let n=e.targetsByLine.get(t.line);if(!n)return null;let r=null;for(let i of n)if(i.leaf===t.calleeLeaf){if(r&&r.symbol!==i.symbol)return null;r=i}return r?{symbol:r.symbol,file:r.relativePath}:null}function wP(e,t){let n=new Map;for(let r of e){let i=n.get(r.relativePath);i?i.push(r):n.set(r.relativePath,[r]),t.set(r.symbolId,[])}for(let r of n.values())r.sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine));return n}function LP(e,t,n,r){let i=pi(e,t,r.calleeLeaf);if(i){let a=Ht(t,n.get(i.importedName)??[]).filter(c=>ke(i.sourcePath,c.file));return a.length===1?a[0]:null}let o=Ht(t,n.get(r.calleeLeaf)??[]);if(o.length===0)return null;let s=PP(e,t,o,r.calleeQualifier);return s||Gn(e,t,o,r.memberAccess,r.calleeQualifier)}function PP(e,t,n,r){if(!r||ae(t)!=="clojure")return null;let o=ce(e,t).filter(s=>s.kind==="namespace"&&s.localName===r&&s.sourcePath).map(s=>s.sourcePath);for(let s of o){let a=n.find(c=>ke(s,c.file));if(a)return a}return n.find(s=>/`([^`]+)`\//.exec(s.symbol)?.[1]===r)??null}function DP(e,t){if(t.length===0)return new Map;let r=lu(t.map(p=>p.documentId)).flatMap(p=>e.all(`SELECT c.document_id, c.id AS chunk_id, c.start_line, c.end_line, m.symbol_id
23
- FROM mentions m
24
- JOIN chunks c ON m.chunk_id = c.id
25
- WHERE m.role != 1
26
- AND c.document_id IN (${p.map(()=>"?").join(",")})`,...p)),i=new Map;for(let p of r)i.has(p.document_id)||i.set(p.document_id,[]),i.get(p.document_id).push(p);let s=lu(r.map(p=>p.symbol_id)).flatMap(p=>e.all(`SELECT gs.id AS symbol_id, gs.symbol,
27
- COALESCE(der.document_id, def_chunk.document_id) AS document_id
28
- FROM global_symbols gs
29
- LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
30
- LEFT JOIN (
31
- SELECT m.symbol_id, MIN(c.document_id) AS document_id
32
- FROM mentions m
33
- JOIN chunks c ON m.chunk_id = c.id
34
- WHERE m.role = 1
35
- AND m.symbol_id IN (${p.map(()=>"?").join(",")})
36
- GROUP BY m.symbol_id
37
- ) def_chunk ON def_chunk.symbol_id = gs.id
38
- WHERE gs.id IN (${p.map(()=>"?").join(",")})`,...p,...p)),a=lu([...t.map(p=>p.documentId),...s.flatMap(p=>p.document_id===null?[]:[p.document_id])]),c=new Map(a.flatMap(p=>e.all(`SELECT id, relative_path FROM documents
39
- WHERE id IN (${p.map(()=>"?").join(",")})`,...p).map(f=>[f.id,f.relative_path]))),u=new Map;for(let p of s)u.has(p.symbol_id)||u.set(p.symbol_id,{symbol:p.symbol,file:p.document_id!==null?c.get(p.document_id)??"":""});let l=new Map,d=c,m=MP(t);for(let[p,f]of m){let h=[...i.get(p)??[]].sort((x,v)=>x.start_line-v.start_line||x.end_line-v.end_line),y=[...f].sort((x,v)=>x.startLine-v.startLine||x.endLine-v.endLine),S=new Set,b=0;for(let x of y){for(;b<h.length&&h[b].start_line<=x.endLine;)S.add(h[b]),b+=1;for(let w of S)w.end_line<x.startLine&&S.delete(w);let v=new Set,C=[],R=null,E=()=>{if(R)return R;let w=d.get(x.documentId)??"",I=new Set;if(w){let k=Rg(e,w),D=Math.max(0,x.startLine),F=Math.min(k.length-1,x.endLine);for(let P=D;P<=F;P+=1)for(let A of k[P])I.add(A)}return R=I,I};for(let w of S){if(w.symbol_id===x.symbolId)continue;let I=u.get(w.symbol_id);if(!I)continue;if(!(w.start_line>=x.startLine&&w.end_line<=x.endLine)){if(!(w.start_line<=x.endLine&&w.end_line>=x.startLine))continue;let P=G(I.symbol);if(!P||!E().has(P))continue}let D=`${I.symbol}|${w.chunk_id}`;v.has(D)||(v.add(D),C.push({...I,chunkId:w.chunk_id,source:"scip-chunk"}))}l.set(x.symbolId,C)}}return l}var Rh=500;function lu(e){let t=[...new Set(e)],n=[];for(let r=0;r<t.length;r+=Rh)n.push(t.slice(r,r+Rh));return n}function MP(e){let t=new Map;for(let n of e){let r=t.get(n.documentId);r?r.push(n):t.set(n.documentId,[n])}return t}function TP(e){let t=new Map;for(let[n,r]of e){let i=[];for(let o of r)i.push({symbol:o.symbol,file:o.file,chunkId:-1,source:"semantic-callee",...o.callsiteLine===void 0?{}:{callsiteLine:o.callsiteLine},...o.kind==="jsx-render"?{kind:"jsx-render"}:{}});t.set(n,i)}return t}var kP=12,AP=280;function xi(e,t,n,r){let i=FP(e,t,n,r);if(i.size===0)return BP();let o=[],s=new Set,a=(u,l,d,m)=>{if(l===t&&d<=r&&m>=n)return;let p=`${l}:${d}:${m}:${u}`;s.has(p)||(s.add(p),o.push({name:u,relativePath:l,startLine:d,endLine:m}))};for(let u of q(e,t))i.has(u.leaf)&&a(u.leaf,u.relativePath,u.startLine,u.endLine);for(let u of ce(e,t)){let l=u.localName;if(!l||!i.has(l)||!u.sourcePath||u.kind==="namespace")continue;let d=u.importedName==="default"?l:u.importedName;for(let m of qn(e,u.sourcePath,d,{maxReexportDepth:3}))a(l,m.relativePath,m.startLine,m.endLine)}o.sort(wh);let c=o.map(u=>{let l=NP(e,u);return l?{...u,source:l}:null}).filter(u=>u!==null).slice(0,kP);return uu(c)}function ha(e,t=[]){return uu(_P(e.flatMap(n=>n?.inline??[]),t))}function Ih(e){return e?e.inline.reduce((t,n)=>t+n.name.length+n.source.length+32,0):0}function FP(e,t,n,r){let i=W(e,t),o=new Set;if(!i)return o;for(let s=n;s<=r;s+=1)for(let a of i.identifiersByLine[s]??[])o.add(a);return o}function NP(e,t){if(t.startLine!==t.endLine)return null;let n=(K(e,t.relativePath)[t.startLine]??"").trim();if(!n||n.length>AP)return null;let r=n.indexOf("=");if(r<0||n[r+1]===">")return null;let i=n.slice(r+1).replace(/(?:\/\/|#).*$/u,"").trim();if(!i||i.includes("${")||/\b(?:function|class|struct|interface|trait|enum|lambda)\b/u.test(i))return null;let s=i.replace(/(['"`])(?:\\.|(?!\1).)*\1/gu,"").replace(/\b(?:0[xX][\dA-Fa-f_]+|0[bB][01_]+|0[oO][0-7_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:[eE][+-]?\d+)?)n?\b/gu,""),a=new Set(["true","false","null","undefined","None","True","False"]);return(s.match(/[A-Za-z_][A-Za-z0-9_]*/gu)??[]).some(u=>!a.has(u))?null:n}function _P(e,t){let n=new Map;for(let r of e){if(OP(r,t))continue;let i=`${r.relativePath}:${r.startLine}:${r.endLine}:${r.name}`;n.has(i)||n.set(i,{...r})}return[...n.values()].sort(wh)}function OP(e,t){return t.some(n=>n.relativePath===e.relativePath&&n.startLine<=e.startLine&&n.endLine>=e.endLine)}function wh(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||e.name.localeCompare(t.name)}function uu(e){return{coverage:"indexed-project-literal-values",inline:e}}function BP(){return uu([])}var $P=12,jP=20,mu=200,pu=800,HP=.9,UP=64,qP=Yf("behavior-construct-ranges"),Ph={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"},xa=["anchor","signature","binding","branch","loop","call","await","return","throw","mutation","shape","spread","catch","finally"],Dh=[...xa,"lifecycle"],Mh=["loop","await","throw","mutation","spread","catch","finally","lifecycle"],GP=new Set(["onBeforeMount","onBeforeUnmount","onMounted","onUnmounted","useEffect","useInsertionEffect","useLayoutEffect"]);var Th=new Set(["object","object_pattern","dictionary","field_declaration_list","struct_expression","struct_pattern"]);function Ri(e,t,n,r,i=[],o={}){let s=J(e,t);if(!s)return null;let a=K(e,t),c=ot(e,t,n,r,i),u=Ia(e,t,c.startLine,c.endLine),l=u?.startLine??n,d=u?.endLine??r,m=(u?Ei(s.rootNode,c.startLine,c.endLine):null)??Ir(s.rootNode,l,d);if(!m)return null;let p=_h(m,a,l,d,i);if(!p||p.lines.length===0||p.lines.some(y=>y.text.length>pu))return null;let f=lD(a,l,d),g=uD(p);if((o.requireSavings??!0)&&g>=f*HP)return null;let h=xa.filter(y=>p.lines.some(S=>S.signals.includes(y)));return{...u?{callable:{name:u.name,startLine:u.startLine,endLine:u.endLine}}:{},representation:"outline",constructKind:p.constructKind,signature:p.signature,lines:p.lines,signals:h,testCases:U(t)==="test"?gD(a,l,d):[],coverage:{sourceStatements:p.sourceStatements,representedStatements:p.sourceStatements,copiedStatements:p.copiedStatements,omittedStatements:0},rawCharacters:f,outlineCharacters:g,candidateLines:p.sourceStatements,omittedLines:0}}function Ra(e,t,n,r,i){if(i.length===0)return[];let o=J(e,t);if(!o)return[];let s=K(e,t),a=ot(e,t,n,r,i),c=Ia(e,t,a.startLine,a.endLine),u=c?.startLine??n,l=c?.endLine??r,d=(c?Ei(o.rootNode,a.startLine,a.endLine):null)??Ir(o.rootNode,u,l);if(!d)return[];let m=_h(d,s,u,l,i);return m?m.lines.filter(p=>p.text.length<=pu&&p.signals.some(f=>["branch","loop","catch","finally"].includes(f))&&i.some(f=>f>=p.line&&f<=p.endLine)):[]}function kh(e,t,n,r){let i=J(e,t);if(!i)return null;let o=Ei(i.rootNode,n,r)??Ir(i.rootNode,n,r);if(!o)return null;let s=[],a=hu(o),c=[];return yu(o,o,u=>{if(So.has(u.type)||KP.has(u.type)){VP(s,c,u);return}if(Ea.has(u.type)){YP(s,c,u);return}if(Ro.has(u.type)){JP(s,c,u);return}Eo.has(u.type)&&XP(s,u)}),{facts:nD(s),terminals:Nh(a),unsupported:c}}function ot(e,t,n,r,i=[]){let o=i.filter(l=>l>=n&&l<=r),s=qP.get(e,t,V(e,t)??"",()=>new Map),a=`${n}:${r}:${o.join(",")}`,c=s.get(a);if(c)return s.delete(a),s.set(a,c),{startLine:c[0],endLine:c[1]};let u=zP(e,t,n,r,o);if(s.set(a,[u.startLine,u.endLine]),s.size>UP){let l=s.keys().next().value;l!==void 0&&s.delete(l)}return u}function zP(e,t,n,r,i){let o=J(e,t),s=[];if(i.length>0&&o){let l=[],d=i[0],m=d;for(let f of i)d=Math.min(d,f),m=Math.max(m,f);$h(o.rootNode,d,m,f=>{rD(f)&&f.startPosition.row>=n&&f.endPosition.row<=r&&i.every(g=>f.startPosition.row<=g&&f.endPosition.row>=g)&&l.push(f),Yn.has(f.type)&&f.startPosition.row>=n&&f.endPosition.row<=r&&i.every(g=>f.startPosition.row<=g&&f.endPosition.row>=g)&&s.push(f)});let p=l.sort((f,g)=>f.endPosition.row-f.startPosition.row-(g.endPosition.row-g.startPosition.row)||f.startPosition.row-g.startPosition.row)[0];if(p)return{startLine:p.startPosition.row,endLine:p.endPosition.row}}let a=Ia(e,t,n,r);if(a)return{startLine:a.startLine,endLine:a.endLine};if(i.length===0)return{startLine:n,endLine:r};let c=(W(e,t)?.callables??[]).filter(l=>l.startLine>=n&&l.endLine<=r&&i.every(d=>l.startLine<=d&&l.endLine>=d)).sort((l,d)=>l.endLine-l.startLine-(d.endLine-d.startLine)||l.startLine-d.startLine)[0];if(!o)return c?{startLine:c.startLine,endLine:c.endLine}:{startLine:n,endLine:r};let u=s.sort((l,d)=>l.endPosition.row-l.startPosition.row-(d.endPosition.row-d.startPosition.row)||l.startPosition.row-d.startPosition.row)[0];return u?{startLine:u.startPosition.row,endLine:u.endPosition.row}:c?{startLine:c.startLine,endLine:c.endLine}:{startLine:n,endLine:r}}function fu(e,t,n,r,i={}){if(r-n+1<(i.minimumBodyLines??jP))return null;let s=Bh(e,t,n,r,[],!1);if(!s)return null;let a=s.candidates.map(y=>({...y,signals:y.signals.filter(S=>S!=="anchor"&&S!=="signature")})).filter(y=>y.signals.length>0);if(a.length===0)return null;let c=pD(a),u=a.filter(y=>y.text.length<=mu);if(u.length===0)return null;let l=Mh.filter(y=>(c[y]??0)>0),d=l.filter(y=>y!=="await"),m=s.shapes.reduce((y,S)=>y+S.fields.length,0);if(d.length===0&&!((c.await??0)>0&&m>0)&&m<3)return null;let p=fD(u,c),f=new Map;for(let y of l){let S=p.find(b=>b.signals.includes(y));S&&f.set(S.line,S)}if(f.size===0){let y=p.find(S=>S.signals.includes("branch"));y&&f.set(y.line,y)}let g=Math.min(10,Math.max(1,i.maxLines??f.size)),h=new Map;for(let y of f.values()){if(h.size>=g)break;h.set(y.line,y)}return h.size>=a.length&&s.shapes.length===0?null:{owner:s.callable?.name??null,startLine:n,endLine:r,lines:[...h.values()].sort((y,S)=>y.line-S.line),shapes:s.shapes,signalCounts:c,candidateLines:a.length,omittedLines:a.length-h.size}}function En(e,t,n,r){let i=Bh(e,t,n,r,[],!1);return i?new Map(i.candidates.map(o=>[o.line,o.signals.filter(s=>s!=="lifecycle")])):new Map}var Yn=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"]),yt=new Set(["block","body","compound_statement","declaration_list","statement_block"]),So=new Set(["if_expression","if_statement","unless","unless_statement"]),KP=new Set(["conditional_expression","ternary_expression"]),Ea=new Set(["do_statement","enhanced_for_statement","for_expression","for_in_statement","for_of_statement","for_statement","loop_expression","while_statement"]),Ro=new Set(["match_expression","match_statement","switch_expression","switch_statement"]),Ah=new Set(["case_statement","match_arm","switch_case","switch_default"]),Eo=new Set(["try_expression","try_statement"]),Sa=new Set(["catch_clause","except_clause","rescue"]),Co=new Set(["ensure","finally_clause"]),vo=new Set(["else","else_clause"]),Fh=new Set(["raise_statement","return_statement","throw_statement"]),WP=new Set(["block_comment","comment","line_comment"]);function VP(e,t,n){let r=n.childForFieldName("condition")??Su(n),i=n.childForFieldName("consequence")??n.childForFieldName("body")??n.namedChildren.find(c=>yt.has(c.type)),o=n.childForFieldName("alternative")??n.namedChildren.find(c=>vo.has(c.type));if(!r||!i){t.push(bu(n,"conditional-fields-unresolved"));return}let s=en(r,"predicate",r.text),a=en(i,Lh(i),"consequence");if(Zt(e,s,a,"predicate-consequence",{branchRole:"consequence"}),va(e,s,i,"consequence"),o){let c=en(o,Lh(o),"alternative");Zt(e,s,c,"predicate-alternative",{branchRole:"alternative"}),va(e,s,o,"alternative");return}Zt(e,s,gu(s,"otherwise continue"),"predicate-fallthrough",{branchRole:"fallthrough"})}function YP(e,t,n){let r=n.childForFieldName("body")??n.namedChildren.find(s=>yt.has(s.type));if(!r){t.push(bu(n,"loop-body-unresolved"));return}let i=n.childForFieldName("condition"),o=en(i??n,"predicate",i?.text??Ut(n,r));Zt(e,o,en(r,"outcome","iteration"),"loop-iteration",{branchRole:"iteration"}),va(e,o,r,"iteration"),Zt(e,o,gu(o,"loop exits"),"loop-exit",{branchRole:"exit"})}function JP(e,t,n){let r=n.childForFieldName("body")??n.namedChildren.find(c=>yt.has(c.type)),i=n.childForFieldName("value")??n.childForFieldName("condition")??n.childForFieldName("subject")??Su(n),o=ZP(r??n);if(!i||o.length===0){t.push(bu(n,"switch-cases-unresolved"));return}let s=en(i,"predicate",i.text),a=!1;for(let c of o){let u=tD(c);a||=u;let l=Ut(c,c.namedChildren.find(d=>Ca(d)));Zt(e,s,en(c,"outcome",l||(u?"default":"case")),u?"predicate-default":"predicate-case",{branchRole:u?"default":"case"}),va(e,s,c,u?"default":"case")}a||Zt(e,s,gu(s,"no case matched"),"predicate-fallthrough",{branchRole:"fallthrough"})}function XP(e,t){let n=en(t,"scope","try");for(let r of eD(t)){let i=Co.has(r.type),o=en(r,"handler",i?"finally":Ut(r,ya(r)));Zt(e,n,o,i?"finally-cleanup":"exception-handler",{branchRole:i?"finally":"catch"}),QP(e,o,r,i?"finally":"catch")}}function QP(e,t,n,r){for(let i of hu(n)){let o=i.label.startsWith("throw")||i.label.startsWith("raise")?"throw":"return";Zt(e,t,i,o==="throw"?"handler-throw":"handler-return",{branchRole:r,terminalKind:o})}}function va(e,t,n,r){for(let i of hu(n)){let o=i.label.startsWith("throw")||i.label.startsWith("raise")?"throw":"return";Zt(e,t,i,o==="throw"?"predicate-throw":"predicate-return",{branchRole:r,terminalKind:o})}}function Zt(e,t,n,r,i){e.push({controller:t,outcome:n,subtype:r,attributes:i})}function en(e,t,n){return{kind:t,label:xo(n).slice(0,pu),startLine:e.startPosition.row,endLine:e.endPosition.row,implicit:!1}}function gu(e,t){return{...e,kind:"outcome",label:t,implicit:!0}}function Lh(e){return Fh.has(e.type)?"terminal":"outcome"}function hu(e){let t=[];return yu(e,e,n=>{Fh.has(n.type)&&t.push(en(n,"terminal",n.text))}),Nh(t)}function yu(e,t,n){n(t);for(let r of t.namedChildren)r!==e&&Yn.has(r.type)||yu(e,r,n)}function ZP(e){let t=[],n=r=>{for(let i of r.namedChildren)Ro.has(i.type)||(Ah.has(i.type)?t.push(i):n(i))};return n(e),t}function eD(e){let t=[],n=r=>{for(let i of r.namedChildren)Eo.has(i.type)||(Sa.has(i.type)||Co.has(i.type)?t.push(i):Yn.has(i.type)||n(i))};return n(e),t}function tD(e){let t=Ut(e,e.namedChildren.find(n=>Ca(n))).trim();return e.type==="switch_default"||/^(?:default\b|_\s*=>)/u.test(t)}function bu(e,t){return{startLine:e.startPosition.row,endLine:e.endPosition.row,reason:t}}function nD(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 Nh(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 rD(e){return Yn.has(e.type)||Ea.has(e.type)||Ro.has(e.type)||Eo.has(e.type)||Sa.has(e.type)||Co.has(e.type)}function _h(e,t,n,r,i){let s=Ei(e,n,r)??e,a=ya(s),c=[],u=0,l=0,d=(C,R,E,w,I=!1,k=!0)=>{let D=I?E.trim():xo(E);if(!D)return;let F=Math.max(n,C.startPosition.row),P=Math.min(r,C.endPosition.row);c.push({line:F,endLine:Math.max(F,P),depth:R,signals:xa.filter(A=>w.includes(A)||A==="anchor"&&i.some(L=>L>=F&&L<=P)),text:D,copied:I}),k&&(u+=1,I&&(l+=1))},m=(C,R)=>{for(let E of C.namedChildren)v(E,R)},p=(C,R)=>{if(So.has(C.type)){f(C,R,"else if");return}if(vo.has(C.type)){let E=C.namedChildren.find(I=>So.has(I.type));if(E){f(E,R,"else if");return}d(C,R,"else",["branch"],!1,!1);let w=ya(C)??C.namedChildren.find(I=>yt.has(I.type));if(w)v(w,R+1);else for(let I of C.namedChildren)v(I,R+1);return}d(C,R,"else",["branch"],!1,!1),v(C,R+1)},f=(C,R,E=C.type.startsWith("unless")?"unless":"if")=>{let w=C.childForFieldName("condition")??Su(C),I=C.childForFieldName("consequence")??C.childForFieldName("body")??C.namedChildren.find(F=>yt.has(F.type)),k=C.childForFieldName("alternative")??C.namedChildren.find(F=>vo.has(F.type)),D=w?w.text:Ut(C,I);d(C,R,`${E} ${aD(D)}`,bo(w,["branch"])),I&&v(I,R+1),k&&p(k,R)},g=(C,R)=>{let E=C.childForFieldName("body")??C.namedChildren.find(w=>yt.has(w.type));d(C,R,Ut(C,E),bo(C,["loop"])),E&&v(E,R+1)},h=(C,R)=>{let E=C.childForFieldName("body")??C.namedChildren.find(w=>yt.has(w.type));d(C,R,Ut(C,E),bo(C,["branch"])),E&&v(E,R+1)},y=(C,R)=>{let E=C.namedChildren.find(w=>Ca(w));d(C,R,Ut(C,E),["branch"],!1,!1);for(let w of C.namedChildren)(w===E||Ca(w))&&v(w,R+1)},S=(C,R)=>{d(C,R,"try",[],!1);for(let E of C.namedChildren)yt.has(E.type)?v(E,R+1):(Sa.has(E.type)||Co.has(E.type))&&v(E,R)},b=(C,R,E)=>{let w=C.childForFieldName("body")??C.namedChildren.find(k=>yt.has(k.type)),I=E==="finally"?"finally":Ut(C,w);d(C,R,I,[E],!1,!1),w&&v(w,R+1)},x=(C,R)=>{let E=ya(C);d(C,R,Ut(C,E),bo(C,["binding"])),E&&v(E,R+1)},v=(C,R)=>{if(C.startPosition.row>r||C.endPosition.row<n||WP.has(C.type)||C.type==="empty_statement")return;if(yt.has(C.type)){m(C,R);return}if(So.has(C.type)){f(C,R);return}if(Ea.has(C.type)){g(C,R);return}if(Ro.has(C.type)){h(C,R);return}if(Ah.has(C.type)){y(C,R);return}if(Eo.has(C.type)){S(C,R);return}if(Sa.has(C.type)){b(C,R,"catch");return}if(Co.has(C.type)){b(C,R,"finally");return}if(vo.has(C.type)){p(C,R);return}if(Yn.has(C.type)){x(C,R);return}let w=!Oh(C)||cD(C);d(C,R,C.text,bo(C),w)};return v(a&&a!==s?a:s,0),u===0?null:{constructKind:sD(s),signature:oD(s,a,t,n),lines:c,sourceStatements:u,copiedStatements:l}}function Ei(e,t,n){let r=e.namedChildren.filter(i=>i.startPosition.row<=t&&i.endPosition.row>=n);for(let i of r.sort(iD)){let o=Ei(i,t,n);if(o)return o}return Yn.has(e.type)&&e.startPosition.row<=t&&e.endPosition.row>=n?e:null}function iD(e,t){return e.endPosition.row-e.startPosition.row-(t.endPosition.row-t.startPosition.row)||e.startPosition.row-t.startPosition.row}function ya(e){return e.childForFieldName("body")??e.childForFieldName("consequence")??e.namedChildren.find(t=>yt.has(t.type))??null}function oD(e,t,n,r){let i=Ut(e,t);return i||(n[r]??e.text).trim()}function sD(e){return e.type.includes("constructor")?"constructor":e.type.includes("method")||e.type==="method"?du(e,new Set(["class_body","class_declaration","class_definition"]))?"class method":"object method":e.type==="arrow_function"||e.type==="function_expression"||e.type==="lambda"?du(e,new Set(["object","pair"]))?"object member":"function value":e.type.includes("function")?du(e,Yn)?"nested function":"module function":"source construct"}function du(e,t){let n=e.parent;for(;n;){if(t.has(n.type))return!0;n=n.parent}return!1}function Su(e){return e.namedChildren.find(t=>!yt.has(t.type)&&!vo.has(t.type))??null}function Ut(e,t){if(!t)return xo(e.text);let n=Math.max(0,t.startIndex-e.startIndex);return xo(e.text.slice(0,n)).replace(/[:{]\s*$/u,"").trim()}function aD(e){let t=xo(e);return t.startsWith("(")&&t.endsWith(")")?t.slice(1,-1).trim():t}function xo(e){return e.trim().replace(/\r?\n[\t ]*/gu," ")}function bo(e,t=[]){let n=new Set(t);return e&&Io(e,r=>{let i=Ph[r.type];i&&n.add(i),r.type==="call_expression"&&(n.add("call"),jh(r)&&n.add("shape")),vu.has(r.type)&&n.add("binding")}),xa.filter(r=>n.has(r))}function cD(e){let t=!1;return Io(e,n=>{t||!n.text.includes(`
40
- `)||/(?:string|template|heredoc|raw_string)/u.test(n.type)&&(t=!0)}),t}function Ca(e){return yt.has(e.type)||So.has(e.type)||Ea.has(e.type)||Ro.has(e.type)||Eo.has(e.type)||Yn.has(e.type)||Oh(e)}function Oh(e){return/(?:statement|declaration|expression|assignment|return|throw|raise|break|continue|yield|with_item)$/u.test(e.type)||vu.has(e.type)}function lD(e,t,n){let r=0;for(let i=t;i<=n;i+=1)r+=(e[i]?.length??0)+10;return r}function uD(e){return e.constructKind.length+e.signature.length+80+e.lines.reduce((t,n)=>t+n.text.length+n.depth*2+10,0)}function Bh(e,t,n,r,i,o){let s=J(e,t);if(!s)return null;let a=K(e,t),c=Ia(e,t,n,r),u=o?c?.startLine??n:n,l=o?c?.endLine??r:r,m=(c?.startLine===u&&c.endLine===l?Ei(s.rootNode,u,l):null)??Ir(s.rootNode,u,l);if(!m)return null;let p=new Map,f=new Map,g=new Map,h=(b,x)=>{if(b<u||b>l)return;let v=p.get(b)??new Set;v.add(x),p.set(b,v)};c&&h(c.startLine,"signature");for(let b of i)h(b,"anchor");Io(m,b=>{let x=Ph[b.type];if(x&&h(b.startPosition.row,x),x==="shape"&&dD(f,b,m,u,l),b.type==="call_expression"){let C=(b.childForFieldName("function")??b.namedChild(0))?.text.split(".").at(-1);if(jh(b)){h(b.startPosition.row,"shape");let R=ba(b.text);R.length<=mu&&g.set(b.startPosition.row,R)}if(C&&GP.has(C)){h(b.startPosition.row,"lifecycle");let R=ba(b.text);R.length<=mu&&g.set(b.startPosition.row,R)}}vu.has(b.type)&&h(b.startPosition.row,"binding")});let y=W(e,t);for(let b of y?.callSites??[])b.line<u||b.line>l||(h(b.line,"call"),b.calleeLeaf==="catch"&&h(b.line,"catch"));let S=[...p.entries()].sort(([b],[x])=>b-x).map(([b,x])=>({line:b,signals:Dh.filter(v=>x.has(v)),text:g.get(b)??ba(a[b]??"")})).filter(b=>b.text.length>0||b.signals.includes("anchor"));return{...c?{callable:c}:{},rangeStart:u,rangeEnd:l,sourceLines:a,candidates:S,shapes:[...f.values()].sort((b,x)=>b.startLine-x.startLine)}}function dD(e,t,n,r,i){if(t.startPosition.row<r||t.endPosition.row>i)return;let o=t.childForFieldName("key")??t.childForFieldName("name")??t.namedChild(0),s=ba(o?.text??"");if(!s||s.includes(`
41
- `)||s.length>60)return;let a=mD(t,n);if(a.startPosition.row<r||a.endPosition.row>i)return;let c=`${a.startPosition.row}:${a.endPosition.row}`,u=e.get(c)??{startLine:a.startPosition.row,endLine:a.endPosition.row,fields:[]};u.fields.some(l=>l.name===s&&l.line===t.startPosition.row)||u.fields.push({name:s,line:t.startPosition.row}),e.set(c,u)}function mD(e,t){let n=e.parent;for(;n&&n!==t.parent;){if(Th.has(n.type))return n;if(n===t)break;n=n.parent}return e.parent??e}function Ia(e,t,n,r){return W(e,t)?.callables.filter(i=>i.startLine<=n&&i.endLine>=r).sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine)||i.startLine-o.startLine)[0]}function Io(e,t){t(e);for(let n of e.namedChildren)Io(n,t)}function $h(e,t,n,r){r(e);for(let i of e.namedChildren)i.startPosition.row>t||i.endPosition.row<n||$h(i,t,n,r)}function ba(e){return e.trim().replace(/\s+/gu," ")}function jh(e){if(e.type!=="call_expression")return!1;let t=e.childForFieldName("arguments")??e.namedChildren.find(r=>r.type==="arguments"||r.type==="argument_list");if(!t)return!1;let n=!1;return Io(t,r=>{Th.has(r.type)&&(n=!0)}),n}function pD(e){let t={};for(let n of Dh){let r=e.filter(i=>i.signals.includes(n)).length;r>0&&(t[n]=r)}return t}function fD(e,t){let n=new Map;for(let o of e){let s=o.signals.join(",");n.set(s,(n.get(s)??0)+1)}let r=new Set(Mh),i=o=>{let s=n.get(o.signals.join(","))??1,a=Math.min(...o.signals.map(l=>t[l]??1)),c=o.signals.some(l=>r.has(l))?3:1,u=Math.max(0,o.signals.length-1)*1e3;return c*(1e3/s+1e3/a)+u};return[...e].sort((o,s)=>i(s)-i(o)||s.line-o.line)}var vu=new Set(["lexical_declaration","variable_declarator","const_item","static_item","let_declaration","assignment"]);function gD(e,t,n){let r=[],i=/\b(?:describe|it|test)(?:\.(?:only|skip|todo))?\s*\(\s*(['"`])([^'"`]+)\1/u;for(let o=t;o<=n;o+=1){let s=i.exec(e[o]??"")?.[2];if(!(!s||r.includes(s))&&(r.push(s),r.length>=$P))break}return r}var hD=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 Ii(e,t,n){let r=J(e,t)?.rootNode??null,i=yD(r,n);if(!i)return null;let o=K(e,t);if(o.length===0)return null;let s=Math.max(0,i.startPosition.row),a=i.endPosition.column===0?i.endPosition.row-1:i.endPosition.row;return{type:i.type,startLine:s,endLine:Math.min(o.length-1,Math.max(s,a))}}function wo(e,t,n,r,i){let o=ot(e,t,r,i,[n]),s=o.startLine===o.endLine&&/(?:=>|\(|\{|\[|,)\s*$/u.test(K(e,t)[o.startLine]??"");if(!s&&(o.startLine>r||o.endLine<i))return o;let a=Ii(e,t,n);return s&&a?{startLine:a.startLine,endLine:a.endLine}:a&&a.startLine>=r&&a.endLine<=i?{startLine:a.startLine,endLine:a.endLine}:{startLine:r,endLine:i}}function yD(e,t){if(!e||!qh(e,t))return null;let n=Uh(e,t);for(;n;){if(hD.has(n.type))return n;n=n.parent}return null}function Uh(e,t){let n=e.namedChildren.filter(r=>qh(r,t)).sort((r,i)=>Hh(r)-Hh(i));return n.length>0?Uh(n[0],t):e}function qh(e,t){return e.startPosition.row<=t&&e.endPosition.row>=t}function Hh(e){return e.endIndex-e.startIndex}var bD=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 wa(e,t,n,r){if(!Number.isSafeInteger(n)||n<0)return null;if(!Number.isSafeInteger(r)||r<0)throw new RangeError(`contextLines must be a non-negative safe integer; received ${r}`);let i=K(e,t);if(i.length===0||n>=i.length)return null;let o=Math.max(0,n-r),s=Math.min(i.length-1,n+r);return{relativePath:t,startLine:o,endLine:s,focusLine:n,source:i.slice(o,s+1).join(`
42
- `)}}function Gh(e,t,n,r,i){let o=wa(e,t,n,r);if(!o)return null;let s=J(e,t)?.rootNode??null;if(!s)return{...o,kind:"bounded-context"};let a=SD(s,n,i);if(a.length!==1)return{...o,kind:a.length===0?"non-call-reference":"bounded-context"};let c=a[0],u=K(e,t),l=Math.max(0,c.startPosition.row),d=c.endPosition.column===0?c.endPosition.row-1:c.endPosition.row,m=Math.min(u.length-1,Math.max(l,d));return{relativePath:t,startLine:l,endLine:m,focusLine:n,source:u.slice(l,m+1).join(`
43
- `),kind:"complete-call-expression"}}function zh(e,t,n,r,i){if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`maxLines must be a positive safe integer; received ${i}`);let o=K(e,t);if(o.length===0||n<0||n>=o.length)return null;let s=Math.min(o.length-1,r,n+i-1);return{relativePath:t,startLine:n,endLine:s,focusLine:n,source:o.slice(n,s+1).join(`
44
- `)}}function Jn(e,t,n,r,i=6){if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`maxLines must be a positive safe integer; received ${r}`);let o=K(e,t);if(o.length===0||n<0||n>=o.length)return null;let s=Ii(e,t,n);if(!s){let g=wa(e,t,n,i);return g?{...g,unitType:null,unitStartLine:g.startLine,unitEndLine:g.endLine,omittedLines:0}:null}let a=s.startLine,c=s.endLine,u=c-a+1,l=Math.min(u,r),d=n-a-Math.floor(l/2),m=Math.max(0,Math.min(u-l,d)),p=a+m,f=p+l-1;return{relativePath:t,startLine:p,endLine:f,focusLine:n,source:o.slice(p,f+1).join(`
45
- `),unitType:s.type,unitStartLine:a,unitEndLine:c,omittedLines:u-l}}function SD(e,t,n){let r=[];return Kh(e,t,n,r),r.filter(i=>!r.some(o=>o!==i&&o.startIndex>=i.startIndex&&o.endIndex<=i.endIndex))}function Kh(e,t,n,r){if(CD(e,t)){bD.has(e.type)&&vD(e)===n&&r.push(e);for(let i of e.namedChildren)Kh(i,t,n,r)}}function vD(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 CD(e,t){return e.startPosition.row<=t&&e.endPosition.row>=t}function Vh(e,t,n={}){let{context:r=0}=n,i=iy(t);if(i)return oy(e,i.filePath,i.startLine,i.endLine,r);let o=ny(e,t);if(o)return Zh(e,o);let s=re(e,t);return s?Lo(e,s,r):null}function I8(e,t,n={}){if(t.length===0)throw new RangeError("code requires at least one selector.");if(t.length>24)throw new RangeError(`code accepts at most ${24} selectors per complete packet; received ${t.length}.`);let r=n.context??0,i=n.members??"exported",o=t.map(c=>RD(e,c,r,i)),s=o.flatMap(c=>c.results),a=s.map(c=>({relativePath:c.relativePath,startLine:c.startLine,endLine:c.endLine}));return{requested:t.length,matched:o.filter(c=>c.status==="matched").length,ambiguous:o.filter(c=>c.status==="ambiguous").length,missing:o.filter(c=>c.status==="missing").length,entries:o,bindingClosure:ha(s.map(c=>c.bindingClosure),a)}}function RD(e,t,n,r){let i=iy(t);if(i){let l=oy(e,i.filePath,i.startLine,i.endLine,n);return l?ED(e,t,l,n):Cu(e,t,"definition-source-unreadable")}let o=ny(e,t);if(o)return wD(e,t,o,n,r);let s=Ze(e,t);if(!s.match)return Cu(e,t,"definition-not-found");let a=ND(e,s),c=a.map(ry);if(s.total>1){let l=s.total<=4&&a.length===s.total;return{selector:t,status:"ambiguous",kind:"source",totalCandidates:s.total,results:l?a.flatMap(d=>{let m=Lo(e,d,n);return m?[m]:[]}):[],definitions:[],candidates:c,omittedCandidates:Math.max(0,s.total-c.length),suggestions:[]}}let u=Lo(e,s.match,n);return u?FD(t,u):Cu(e,t,"definition-source-unreadable")}function ED(e,t,n,r){let i=q(e,n.relativePath).filter(u=>!Yh(u,n.relativePath)),o=ID(e,n,i),s=Qh(o.map(u=>Lo(e,u,r)).filter(u=>u!==null)).filter(u=>!ty(n,u)),a=new Set(s.map(u=>u.symbol)),c=o.filter(u=>!a.has(u.symbol)&&!(n.startLine<=u.startLine&&n.endLine>=u.endLine)).map(ry);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 ID(e,t,n){if(!Po(t.freshness))return[];if(n.length===0)return[];let r=Ar(e,n,{additive:!1,semantic:!1}),i=new Map;for(let s of n){let a=i.get(s.symbol)??[];a.push(s),i.set(s.symbol,a)}let o=new Map;for(let s of n)if(!(s.endLine<t.startLine||s.startLine>t.endLine)){for(let a of r.get(s.symbolId)??[])if(a.file===t.relativePath&&!((a.source==="ast-callsite"||a.source==="scip-occurrence")&&(a.chunkId<t.startLine||a.chunkId>t.endLine)))for(let c of i.get(a.symbol)??[])o.set(c.symbolId,c)}return Xh(e,[...o.values()],n)}function wD(e,t,n,r,i){let o=n.relativePath,s=PD(e,o),a=Po(n.freshness)?q(e,o).filter(g=>!Yh(g,o)):[],c=a.filter(g=>ht(e,g)),u=c.length>0?c:LD(s,a),l=i==="all"?[]:Xh(e,u,a),d=i==="all"||a.length===0?[Zh(e,n)]:Qh(l.map(g=>Lo(e,g,r)).filter(g=>g!==null)),m=MD(s,d),p=TD(o,s,d),f=kD(s);return{selector:t,status:"matched",kind:"file-source",totalCandidates:1,results:d,definitions:[],candidates:[],omittedCandidates:0,suggestions:[],fileCoverage:{members:i,basis:i==="all"||a.length===0?"complete-file-source":c.length>0?"explicit-exports-and-same-file-reference-closure":"top-level-and-same-file-reference-closure",totalDefinitions:f,returnedDefinitions:m,returnedBodies:d.length,omittedDefinitions:Math.max(0,f-m),omittedLedger:p}}}function LD(e,t){let n=new Set(e.map(r=>r.symbol));return t.filter(r=>n.has(r.symbol))}function PD(e,t){return sh(e,t).flatMap(n=>DD(n,t)?n.children:[n])}function Yh(e,t){return Jh(t).has(e.leaf)}function DD(e,t){return Jh(t).has(G(e.symbol))}function Jh(e){let t=xD(e);return new Set([t,t.slice(0,Math.max(0,t.length-Wh(t).length))])}function Xh(e,t,n){if(t.length===0)return[];let r=Ar(e,n,{additive:!0,semantic:!1}),i=new Map;for(let a of n){let c=i.get(a.symbol)??[];c.push(a),i.set(a.symbol,c)}let o=new Map,s=[...t];for(;s.length>0;){let a=s.shift();if(!o.has(a.symbolId)){o.set(a.symbolId,a);for(let c of r.get(a.symbolId)??[])for(let u of i.get(c.symbol)??[])o.has(u.symbolId)||s.push(u)}}return[...o.values()].sort(AD)}function Qh(e){let t=[...e].sort((r,i)=>r.relativePath.localeCompare(i.relativePath)||r.startLine-i.startLine||i.endLine-r.endLine),n=[];for(let r of t)n.some(i=>ty(i,r))||n.push(r);return n}function Zh(e,t){let n=t.text.split(`
46
- `);return{symbol:t.relativePath,shortName:t.relativePath,relativePath:t.relativePath,startLine:0,endLine:Math.max(0,n.length-1),language:e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath)?.language??Ru(t.relativePath),source:t.text,freshness:t.freshness,...Po(t.freshness)?{bindingClosure:xi(e,t.relativePath,0,Math.max(0,n.length-1))}:{}}}function MD(e,t){return La(e).filter(n=>t.some(r=>xu(n,r))).length}function TD(e,t,n){let r=[];return ey(r,e,t,n,0),r}function ey(e,t,n,r,i){for(let o of n){if(r.some(a=>xu(o,a)))continue;let s=La(o.children).filter(a=>!r.some(c=>xu(a,c))).length;e.push({symbol:o.symbol,shortName:o.shortName,relativePath:t,startLine:o.startLine,endLine:o.endLine,signature:o.signature,depth:i,nestedDefinitions:s}),ey(e,t,o.children,r,i+1)}}function La(e){return e.flatMap(t=>[t,...La(t.children)])}function kD(e){return La(e).length}function xu(e,t){return t.startLine<=e.startLine&&t.endLine>=e.endLine}function ty(e,t){return e.relativePath===t.relativePath&&e.startLine<=t.startLine&&e.endLine>=t.endLine}function AD(e,t){return e.startLine-t.startLine||t.endLine-e.endLine||e.symbol.localeCompare(t.symbol)}function FD(e,t){return{selector:e,status:"matched",kind:"source",totalCandidates:1,results:[t],definitions:[],candidates:[],omittedCandidates:0,suggestions:[]}}function Cu(e,t,n){return{selector:t,status:"missing",kind:"source",totalCandidates:0,results:[],definitions:[],candidates:[],omittedCandidates:0,suggestions:ta(e,t,5),reason:n}}function ny(e,t){try{return ma(e,t)}catch(n){if(n instanceof kf)return null;throw n}}function ND(e,t){if(!t.match)return[];let n=[t.match];for(let i of t.candidates){let o=q(e,i.relativePath).find(s=>s.symbol===i.symbol&&s.startLine===i.startLine);o&&n.push(o)}let r=new Set;return n.filter(i=>{let o=`${i.relativePath}:${i.startLine}:${i.endLine}:${i.symbol}`;return r.has(o)?!1:(r.add(o),!0)})}function ry(e){return{symbol:e.symbol,shortName:T(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine}}function iy(e){let t=e.match(/^(.+):(\d+)-(\d+)$/);if(!t)return null;let n=Number(t[2]),r=Number(t[3]);if(!Number.isSafeInteger(n)||n<1)throw new RangeError(`Source range start line must be a positive integer, got "${t[2]}".`);if(!Number.isSafeInteger(r)||r<n)throw new RangeError(`Source range end line must be an integer at or after ${n}, got "${t[3]}".`);return{filePath:t[1],startLine:n,endLine:r}}function Lo(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=ma(e,t.relativePath);if(!i)return null;let s=i.text.split(`
47
- `),a=t.endLine<=t.startLine?Jn(e,t.relativePath,t.startLine,Number.MAX_SAFE_INTEGER):null,c=a?.unitType?a.unitStartLine:t.startLine,u=a?.unitType?a.unitEndLine:t.endLine,l=Math.max(0,c-n),d=Math.min(s.length-1,u+n),m=s.slice(l,d+1).join(`
48
- `);return{symbol:t.symbol,shortName:T(t.symbol),relativePath:t.relativePath,startLine:l,endLine:d,language:r?.language??Ru(t.relativePath),source:m,freshness:i.freshness,...Po(i.freshness)?{bindingClosure:xi(e,t.relativePath,l,d)}:{}}}function oy(e,t,n,r,i){let o=ma(e,t);if(!o)return null;let s=e.get("SELECT language FROM documents WHERE relative_path = ?",o.relativePath),c=o.text.split(`
49
- `);if(n>c.length)return null;let u=Math.max(0,n-1-i),l=Math.min(c.length-1,r-1+i),d=c.slice(u,l+1).join(`
50
- `);return{symbol:`${o.relativePath}:${n}-${r}`,shortName:`${o.relativePath}:${n}-${r}`,relativePath:o.relativePath,startLine:u,endLine:l,language:s?.language??Ru(o.relativePath),source:d,freshness:o.freshness,...Po(o.freshness)?{bindingClosure:xi(e,o.relativePath,u,l)}:{}}}function Po(e){return!!(e&&e.semantic.state!=="stale"&&e.semantic.basis!=="no-compiler-document")}function Ru(e){switch(Wh(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 Pa(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath)??[];r.push(n),t.set(n.relativePath,r)}return t}function sy(e){let t=new Map,n=OD(e),r=new Map;return i=>{let o=_D(i),s=r.get(o);if(s!==void 0)return s;if(!n.has(i.file))return r.set(o,i.symbol),i.symbol;let a=t.get(i.file);a||(a=BD(q(e,i.file)),t.set(i.file,a));let c=$D(a,i);return r.set(o,c),c}}function _D(e){return`${e.file}\0${e.symbol}\0${e.line}`}function OD(e){return new Set(e.all("SELECT relative_path FROM documents").map(t=>t.relative_path))}function BD(e){let t=new Map,n=new Map;for(let r of e){let i=t.get(r.leaf);i?i.push(r):t.set(r.leaf,[r]);let o=n.get(r.startLine);o?o.push(r):n.set(r.startLine,[r])}return{definitions:e,byLeaf:t,byStartLine:n}}function $D(e,t){if(e.definitions.length===0)return t.symbol;let n=UD(t.symbol),r=jD(e.byLeaf,n),i=HD(r,t.line);if(i)return i.symbol;let o=e.byStartLine.get(t.line)??[];return o.length===1?o[0].symbol:t.symbol}function jD(e,t){let n=[],r=new Set;for(let i of t)for(let o of e.get(i)??[])r.has(o.symbolId)||(r.add(o.symbolId),n.push(o));return n}function HD(e,t){let n=null;for(let r of e)if(!(r.startLine>t||r.endLine<t)){if(r.startLine===t)return r;(!n||r.endLine-r.startLine<n.endLine-n.startLine)&&(n=r)}return n}function UD(e){let t=new Set([e]),r=e.split(/::|\.|#/).filter(Boolean).at(-1);return r&&t.add(r),t}function ay(e,t){let r=ce(e,t).map(i=>GD(t,i));return{usage:r,positions:zD(e,t,r)}}function cy(e,t){return{importUsage(n){let r=e.importUsageFacts(n);if(!t||r.positions.length===0)return r.usage;let i=t.importDefinitionsForFile(n,r.positions);return i.available?qD(r.usage,i.sourcePaths):r.usage}}}function qD(e,t){return e.map((n,r)=>{let i=t.get(String(r));return i?{...n,sourcePath:i}:n})}function GD(e,t){let n=t.isTypeOnly===!0,r=t.kind==="side-effect"||n||t.used;return{importer:e,sourcePath:t.sourcePath,importedName:t.importedName,localName:t.localName,kind:t.kind,isTypeOnly:n,isUsed:r,isTypeUsed:n,isValueUsed:t.kind==="side-effect"||!n&&t.used,references:[]}}function zD(e,t,n){let r=J(e,t);if(!r)return[];let i=KD(r.rootNode),o=new Map;for(let a of i){let c=o.get(Iu(a.importedName,a.localName));c?c.push(a.position):o.set(Iu(a.importedName,a.localName),[a.position])}let s=[];return n.forEach((a,c)=>{let u=o.get(Iu(a.importedName,a.localName??a.importedName))?.shift();u&&s.push({...u,id:String(c),file:t})}),s}function KD(e){let t=[];for(let n of e.descendantsOfType("use_declaration")){let r=n.namedChildren.find(i=>i.type!=="visibility_modifier");r&&t.push(...Da(r,""))}return t.filter(n=>n.importedName!=="*")}function Da(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":return[{importedName:e.text,localName:e.text,position:Eu(e,e.text)}];case"scoped_identifier":{let n=e.text.split("::").pop()??e.text;return[{importedName:n,localName:n,position:Eu(e,n)}]}case"scoped_use_list":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=ug(t,n.text);return r.namedChildren.flatMap(o=>Da(o,i))}case"use_list":return e.namedChildren.flatMap(n=>Da(n,t));case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);return!n||!r?[]:Da(n,t).map(i=>({...i,localName:r.text}))}case"use_wildcard":{let n=e.namedChild(0),r="*";return[{importedName:r,localName:r,position:Eu(n??e,r)}]}default:return[]}}function Eu(e,t){let n=Math.max(0,e.text.lastIndexOf(t));return{id:"",file:"",line:e.startPosition.row,column:e.startPosition.column+n+WD(t)}}function WD(e){return Math.max(0,Math.min(e.length-1,1))}function Iu(e,t){return`${e}\0${t}`}import{spawnSync as Ou}from"child_process";import{existsSync as Bu}from"fs";import{fileURLToPath as WM}from"url";function Qn(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function Ma(e){let t=Ag(kg,e),n=t.runnable;return n?{available:!0,dependencyAvailable:n,resolvedBinary:t.resolvedBinary??void 0,note:"rust-analyzer semantic reference queries are enabled."}:{available:!1,dependencyAvailable:n,resolvedBinary:t.resolvedBinary??void 0,reason:"rust-analyzer is not runnable; Rust semantic checks will use SCIP/source evidence only."}}import{existsSync as kM,mkdtempSync as Ty,rmSync as Tu}from"fs";import{tmpdir as Fu}from"os";import{join as ku}from"path";import{fileURLToPath as No,pathToFileURL as AM}from"url";import{SHARE_ENV as FM,Worker as NM}from"worker_threads";function Zn(e,t,n=new Set){let r=new Map;for(let i of e)n.has(i.symbolId)||r.set(i.symbolId,t.get(i.symbolId)??[]);return r}function Fr(e,t,n){let r=Qn(process.env.SCIP_RUST_SEMANTIC_BATCH_TIMEOUT_MS)??0;if(r>0)return r;let i=Math.max(1,Math.ceil(e/Math.max(1,n)));return Math.max(12e4,3e4+i*t)}import{spawn as mM}from"child_process";import{createHash as pM,randomUUID as fM}from"crypto";import{existsSync as Ry,realpathSync as gM,rmSync as hM}from"fs";import{tmpdir as yM}from"os";import{resolve as Li}from"path";import{execFileSync as tM}from"child_process";import{existsSync as VD}from"fs";import{deserializeSCIP as YD,SymbolRole as JD}from"@c4312/scip";import{realpathSync as j8}from"fs";import{basename as U8,dirname as q8,join as G8,relative as z8,sep as K8}from"path";import{fileURLToPath as V8,pathToFileURL as Y8}from"url";function Ta(e){let t=new Map;for(let n of e)t.set(`${n.file}\0${n.line}\0${n.column}`,n);return[...t.values()].sort((n,r)=>{let i=n.file.localeCompare(r.file);return i!==0?i:n.line!==r.line?n.line-r.line:n.column-r.column})}var wu=new WeakMap,XD="SCIP_RUST_SCIP_OCCURRENCE_REFERENCE_MODE";function ly(e,t){let n=new Map,r=ka(),i=t.filter(s=>my(s,r));if(i.length===0)return n;let o=py(e);if(!o)return n;for(let s of i){let a=dy(o,s);a!==null&&n.set(s.symbolId,a)}return n}function uy(e,t){if(!my(t,ka()))return null;let n=py(e);return n?dy(n,t):null}function dy(e,t){return e.referencesBySymbol.get(t.symbol)??[]}function my(e,t="safe"){if(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||Ge(e.symbol)||/impl#\[[^\]]+\]\[Default\]default\(\)\.$/.test(e.symbol))return!1;if(t==="all")return!0;let n=kt(e.symbol);if(n==="method")return!0;if(n!=="term")return!1;let r=Un(e.symbol);return"kind"in r?!1:!QD(r)}function QD(e){for(let t=0;t<e.descriptors.length-1;t+=1)if(e.descriptors[t]?.suffix==="type")return!0;return!1}function py(e){if(wu.has(e))return wu.get(e)??null;let t=ZD(e);return wu.set(e,t),t}function ZD(e){if(!e.generation.indexPath||!VD(e.generation.indexPath))return null;try{let t=YD(ai(e.generation.indexPath,{inputKind:"SCIP occurrence-reference index",maxBytes:si})),n=new Map;for(let r of t.documents??[]){let i=r.relativePath;if(!(!i||e.isIgnored(i)))for(let o of r.occurrences??[]){if(!o.symbol||(o.symbolRoles&JD.Definition)!==0)continue;let s=eM(i,o.range);if(!s)continue;let a=n.get(o.symbol)??[];a.push(s),n.set(o.symbol,a)}}for(let[r,i]of n)n.set(r,Ta(i));return{referencesBySymbol:n}}catch{return null}}function eM(e,t){if(t.length<3)return null;let n=t[0],r=t[1];return!Number.isInteger(n)||!Number.isInteger(r)?null:{file:e,line:n,column:r}}function ka(){return process.env[XD]==="all"?"all":"safe"}var fy=new Map;function Lu(e){let n=Ma(e).resolvedBinary??null;return{engine:"rust-analyzer",resolvedBinary:n,version:n?nM(e,n):"unavailable"}}function Nr(e){return{...Lu(e),scipOccurrenceReferenceMode:ka()}}function nM(e,t){let n=`${e}\0${t}`,r=fy.get(n);if(r)return r;let i;try{i=tM(t,["--version"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim()}catch{i="unknown"}return fy.set(n,i),i}import{createHash as rM}from"crypto";var iM=new Set(["Cargo.lock","Cargo.toml","rust-project.json","rust-toolchain","rust-toolchain.toml"]);function gy(e){let t=Gf(e,{includePath:oM});return rM("sha256").update(JSON.stringify(t)).digest("hex")}function oM(e){let t=e.replaceAll("\\","/"),n=t.split("/").at(-1)??t;return t.endsWith(".rs")||iM.has(n)?!0:t===".cargo/config"||t===".cargo/config.toml"||t.endsWith("/.cargo/config")||t.endsWith("/.cargo/config.toml")}import{createHash as sM}from"crypto";import{resolve as aM}from"path";var wi=3;function Du(e){return sM("sha256").update(Pr({kind:"scip-query-durable-rust-mailbox",protocolVersion:wi,sessionDir:aM(e)})).digest("hex")}function by(e,t){return Z(e)?e.protocolVersion!==wi?yy(e.protocolVersion===void 0?"helper wrote a prior uncorrelated response protocol":`helper wrote unsupported response protocol ${String(e.protocolVersion)}`):e.mailboxVersion!==Cn||e.id!==t.requestId||e.operationKey!==t.operationKey||e.sessionIdentity!==t.sessionIdentity||e.deadlineAtMs!==t.deadlineAtMs?yy("helper wrote an incompatible response identity"):typeof e.completedAtMs!="number"||!Number.isFinite(e.completedAtMs)||e.completedAtMs>t.deadlineAtMs||t.nowMs>t.deadlineAtMs?{ok:!1,code:"expired-request",error:"helper response arrived after the durable request deadline"}:e.ok===!1?typeof e.error!="string"||!dM(e.errorCode)?Pu("helper wrote an invalid rejection response"):{ok:!1,code:e.errorCode,error:e.error}:e.ok!==!0||e.session!=="created"&&e.session!=="reused"&&e.session!=="invalidated"||!cM(e.response,t.requestKind)?Pu("helper wrote an invalid success response"):{ok:!0,session:e.session,response:e.response}:Pu("helper wrote an invalid response object")}function cM(e,t){return!Z(e)||typeof e.available!="boolean"||e.available===!1&&(typeof e.reason!="string"||e.reason.length===0)||e.available===!0&&e.reason!==void 0?!1:t==="import-definitions"?Array.isArray(e.sourcePaths)&&e.sourcePaths.every(n=>Array.isArray(n)&&n.length===2&&typeof n[0]=="string"&&(n[1]===null||typeof n[1]=="string")):hy(e.references,lM)&&(e.incompleteReferenceSymbolIds===void 0||Array.isArray(e.incompleteReferenceSymbolIds)&&e.incompleteReferenceSymbolIds.every(n=>Number.isSafeInteger(n)))&&(e.callees===void 0||hy(e.callees,uM))&&(e.signatures===void 0||Array.isArray(e.signatures)&&e.signatures.every(n=>Array.isArray(n)&&n.length===2&&Number.isSafeInteger(n[0])&&(n[1]===null||typeof n[1]=="string")))}function hy(e,t){return Array.isArray(e)&&e.every(n=>Array.isArray(n)&&n.length===2&&Number.isSafeInteger(n[0])&&Array.isArray(n[1])&&n[1].every(t))}function lM(e){return Z(e)&&typeof e.file=="string"&&Lt(e.line)&&Lt(e.column)}function uM(e){return Z(e)&&typeof e.symbol=="string"&&typeof e.file=="string"&&Lt(e.line)&&(e.callsiteLine===void 0||Lt(e.callsiteLine))}function dM(e){return e==="unsupported-protocol"||e==="malformed-request"||e==="expired-request"||e==="handler-error"}function Pu(e){return{ok:!1,code:"malformed-response",error:e}}function yy(e){return{ok:!1,code:"incompatible-response",error:e}}var bM=5e3,Ey=10,SM=3e4;function Sy(e,t,n,r=Py){let i=r.engineIdentity(e),o={protocolVersion:wi,projectRoot:r.canonicalProjectRoot(e),projectFingerprint:r.projectFingerprint(e),engine:{engine:i.engine,resolvedBinary:i.resolvedBinary,version:i.version},workerFingerprint:r.fileFingerprint(t),environment:Iy(r.environment())};return{key:Dy(Pr(o)),...o}}function Do(e,t,n,r){if(e.protocolVersion!==wi||!n(e.pid))return!1;if(!e.processIdentity)return!0;let i=r?.(e.pid);return i!=null&&ia(e.processIdentity,i)}function Mu(e,t,n){let r;try{r=Fl(t,{maxBytes:yn,inputKind:"Rust semantic engine artifact"})}catch{r="missing"}let i=Dy(Pr({projectRoot:Li(e),serverPath:Li(t),serverFingerprint:r})).slice(0,20);return Li(n,`scip-query-rust-session-${i}`)}function vy(e){let t=e===void 0?Number.NaN:Number(e);return Number.isInteger(t)&&t>=0?t:0}function Iy(e){return Object.fromEntries(Object.entries(e).filter(([t])=>Ly(t)).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,n??null]))}function wy(e,t){let n=t.runtime??IM,r=t.identityRuntime??Py,i=Mu(e,t.serverPath,t.tempRoot??yM()),o=!1,s=(a,c)=>{if(o)throw new Error("Durable Rust semantic session was already disposed.");return CM(i,t.serverPath,t.semanticWorkerPath,a,c,n,t.mailboxLimits)};return{requestSemantic(a,c){let u=Sy(e,t.semanticWorkerPath,a,r),{readinessDeadlineMs:l,...d}=a;return s({kind:"semantic",identityKey:u.key,workerEnvironment:xy(),request:{...d,referenceRetryTimeoutMs:vM(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,a.referenceRetryTimeoutMs),settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:vy(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},requestImportDefinitions(a,c){let u=Sy(e,t.semanticWorkerPath,a,r),{readinessDeadlineMs:l,...d}=a;return s({kind:"import-definitions",identityKey:u.key,workerEnvironment:xy(),request:{...d,settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:vy(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},shutdown(){o=!0}}}function vM(e,t){return t!==void 0?t:e===void 0?SM:void 0}function CM(e,t,n,r,i,o,s={}){let a=o.now(),c=a+i,u=(o.monotonicNow??At)(),l=u+i,d=Kn("rust-semantic-v3",r),m=Mr(d),p=oa(e),f=Du(e),g=sa(p,{mailboxVersion:Cn,protocolVersion:wi,id:m,operationKey:d,clientId:o.randomId(),enqueuedAtMs:a,deadlineAtMs:c,sessionIdentity:f,request:r},{nowMs:a,limits:s});for(Cy(e,t,n,l,o);(o.monotonicNow??At)()<=l;){if(Ry(g.responsePath)){let y=xM(It(g.responsePath,{maxBytes:s.maxItemBytes??yn,inputKind:"durable Rust semantic mailbox response"}),{requestId:m,operationKey:d,sessionIdentity:f,deadlineAtMs:g.authoritativeDeadlineAtMs,requestKind:r.kind,nowMs:o.now()});if(!y.ok)throw new Error(y.error);return xe()&&qs({type:"span",name:"rust.semantic.durable-session.request",durationMs:(o.monotonicNow??At)()-u,ok:!0,session:y.session,kind:r.kind}),y.response}let h=Mo(e);(!h||!Do(h,o.now(),o.isProcessAlive,o.readProcessIdentity))&&Cy(e,t,n,l,o),o.sleep(Ey)}throw new Error(`Durable Rust semantic session timed out after ${(i/1e3).toFixed(0)}s.`)}function Cy(e,t,n,r,i){let o=Mo(e);if(o&&Do(o,i.now(),i.isProcessAlive,i.readProcessIdentity))return;hM(Li(e,"server.json"),{force:!0}),i.spawnServer(t,e,n);let s=i.monotonicNow??At,a=Math.min(r,s()+bM);for(;s()<=a;){let c=Mo(e);if(c&&Do(c,i.now(),i.isProcessAlive,i.readProcessIdentity))return;i.sleep(Ey)}throw new Error("Durable Rust semantic session helper did not become ready within 5s.")}function Mo(e){try{let t=JSON.parse(It(Li(e,"server.json"),{maxBytes:$s,inputKind:"durable Rust session state"}));if(typeof t.protocolVersion!="number"||t.sessionIdentity!==void 0&&(typeof t.sessionIdentity!="string"||t.sessionIdentity!==Du(e))||typeof t.pid!="number"||typeof t.heartbeatAtMs!="number"||t.busyUntilMs!==void 0&&typeof t.busyUntilMs!="number"||t.mailbox!==void 0&&!RM(t.mailbox))return null;let n=t.processIdentity===void 0?null:ra(t.processIdentity);return t.processIdentity!==void 0&&(!n||n.pid!==t.pid)?null:{protocolVersion:t.protocolVersion,...t.sessionIdentity===void 0?{}:{sessionIdentity:t.sessionIdentity},pid:t.pid,...n?{processIdentity:n}:{},heartbeatAtMs:t.heartbeatAtMs,...t.busyUntilMs===void 0?{}:{busyUntilMs:t.busyUntilMs},...t.mailbox===void 0?{}:{mailbox:t.mailbox}}}catch{return null}}function xM(e,t){try{return by(JSON.parse(e),t)}catch(n){return{ok:!1,code:"malformed-response",error:`helper wrote malformed JSON: ${n instanceof Error?n.message:String(n)}`}}}function RM(e){if(!e||typeof e!="object")return!1;let t=e;return Lt(t.pending)&&Lt(t.inflight)&&Lt(t.responses)&&Lt(t.deadLetters)&&Lt(t.invalid)&&Lt(t.totalItems)&&typeof t.totalBytes=="number"&&Number.isFinite(t.totalBytes)&&t.totalBytes>=0&&(t.oldestPendingAt===void 0||Number.isFinite(Date.parse(t.oldestPendingAt)))}function xy(){return Object.fromEntries(Object.entries(process.env).filter(([e])=>EM(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t??null]))}function Ly(e){return e==="HOME"||e==="PATH"||e.startsWith("CARGO_")||e.startsWith("RA_")||e.startsWith("RUST")}function EM(e){return Ly(e)||e.startsWith("SCIP_RUST_")||e==="SCIP_QUERY_PROFILE"||e==="SCIP_QUERY_PROFILE_CACHE_STATE"||e==="SCIP_QUERY_PROFILE_COMMAND"||e==="SCIP_QUERY_PROFILE_OUT"||e==="SCIP_QUERY_PROFILE_RUN_ID"||e==="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY"||e==="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY_KIND"||e==="SCIP_QUERY_PROFILE_MIN_MS"}var Py={canonicalProjectRoot(e){try{return gM(e)}catch{return Li(e)}},projectFingerprint(e){return gy(e)},engineIdentity:Lu,fileFingerprint(e){return Fl(e,{maxBytes:yn,inputKind:"Rust semantic engine artifact"})},environment(){return Iy(process.env)}},IM={now:Date.now,monotonicNow:At,randomId:fM,isProcessAlive:bi,readProcessIdentity:Si,spawnServer(e,t,n){if(!Ry(e))throw new Error(`Durable Rust semantic session helper was not found at ${e}. Run npm run build first.`);mM(process.execPath,[e,t,n],{detached:!0,stdio:"ignore"}).unref()},sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)}};function Dy(e){return pM("sha256").update(e).digest("hex")}import{randomUUID as _9}from"crypto";import{readdirSync as wM,rmSync as B9,writeFileSync as $9}from"fs";import{join as LM}from"path";var PM="rust-analyzer-owner-",DM=".json",MM=16*1024;async function My(e,t){if(!e)return[];let n;try{n=wM(e)}catch{return[]}let r=n.filter(s=>s.startsWith(PM)&&s.endsWith(DM)).map(s=>LM(e,s)),i=[],o=[];for(let s of r){let a=TM(s);a?o.push(a):i.push({reaped:!1,reason:"identity-unavailable",detail:`Rust analyzer ownership record ${s} could not be validated.`})}return i.push(...await Promise.all(o.map(s=>Og(s,t)))),i}function TM(e){try{let t=It(e,{maxBytes:MM,inputKind:"rust-analyzer process ownership record"}),n=JSON.parse(t),r=ra(n.rootIdentity);return n.version!==1||!r||typeof n.ownsProcessGroup!="boolean"?null:{rootPid:r.pid,rootIdentity:r,ownsProcessGroup:n.ownsProcessGroup,knownMembers:new Map([[r.pid,r]])}}catch{return null}}var ky=15e3,Ay=8,Ny=5e3,_M=64,OM=96,Nu=class{constructor(t,n,r={}){this.projectRoot=t;this.status=n;this.opts=r;this.requester=r.requester??jM(t,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION)}projectRoot;status;opts;requester;referencesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:ko(n),references:Ao(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!0});return{...To(r),resolvedBinary:n.resolvedBinary,references:Zn(t,new Map(r.references),new Set(r.incompleteReferenceSymbolIds??[]))}}catch(r){return this.opts.fallbackReferenceResolver?.referencesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),references:Ao(t)}}}calleesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:ko(n),callees:Fo(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!0});return{...To(r),resolvedBinary:n.resolvedBinary,callees:Au(t,new Map(r.callees??[]))}}catch(r){return this.opts.fallbackCalleeResolver?.calleesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),callees:Fo(t)}}}referencesAndCalleesForDefinitions(t,n){let r=this.status(this.projectRoot);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:ko(r),references:Ao(t),callees:Fo(n)};let i=[...t,...n];try{let o=this.requestSession(r.resolvedBinary,i,{includeReferences:t.length>0,includeCallees:n.length>0,referenceDefinitions:t,calleeDefinitions:n});return{...To(o),resolvedBinary:r.resolvedBinary,references:Zn(t,new Map(o.references),new Set(o.incompleteReferenceSymbolIds??[])),callees:Au(n,new Map(o.callees??[]))}}catch(o){return this.fallbackReferencesAndCallees(r,t,n,o)}}signaturesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:ko(n),signatures:Fy(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!1,includeSignatures:!0});return{...To(r),resolvedBinary:n.resolvedBinary,signatures:zM(t,new Map(r.signatures??[]))}}catch(r){return this.opts.fallbackSignatureResolver?.signaturesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),signatures:Fy(t)}}}importDefinitionsForFile(t,n){let r=this.status(this.projectRoot);if(n.length===0)return r.available?{available:!0,resolvedBinary:r.resolvedBinary,sourcePaths:new Map}:{available:!1,reason:r.reason,resolvedBinary:r.resolvedBinary,sourcePaths:new Map};if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:ko(r),sourcePaths:new Map(n.map(i=>[i.id,null]))};try{let i=this.requestImportDefinitions(r.resolvedBinary,t,n);return{...To(i),resolvedBinary:r.resolvedBinary,sourcePaths:new Map(i.sourcePaths)}}catch(i){return{available:!1,resolvedBinary:r.resolvedBinary,reason:i instanceof Error?i.message:String(i),sourcePaths:new Map(n.map(o=>[o.id,null]))}}}dispose(){this.requester.shutdown()}requestSession(t,n,r){let i=Aa(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,ky),o=Fa(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),s=Aa(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Ay),a=Fa(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),c=r.referenceDefinitions?[...r.referenceDefinitions]:void 0,u=r.calleeDefinitions?[...r.calleeDefinitions]:void 0,l=r.signatureDefinitions?[...r.signatureDefinitions]:void 0,d=_o(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,...r}),m={projectRoot:this.projectRoot,rustAnalyzerBinary:t,definitions:[...n],...c?{referenceDefinitions:c}:{},...u?{calleeDefinitions:u}:{},...l?{signatureDefinitions:l}:{},requestTimeoutMs:i,...r.includeReferences!==!1&&o>0?{referenceRetryTimeoutMs:o}:{},diagnosticsTimeoutMs:a,settleDelayMs:d,concurrency:s,includeReferences:r.includeReferences,includeCallees:r.includeCallees,includeSignatures:r.includeSignatures},p=KM(m);return N("rust.semantic.session.request",()=>this.requester.requestSemantic(m,Fr(p,_u(i,m.referenceRetryTimeoutMs),s)),()=>({definitions:n.length,operationDefinitions:p,referenceDefinitions:m.referenceDefinitions?.length,calleeDefinitions:m.calleeDefinitions?.length,signatureDefinitions:m.signatureDefinitions?.length,references:m.includeReferences!==!1,callees:m.includeCallees===!0,signatures:m.includeSignatures===!0,referenceRetryTimeoutMs:m.referenceRetryTimeoutMs}))}fallbackReferencesAndCallees(t,n,r,i){let o=n.length===0?{available:!0,resolvedBinary:t.resolvedBinary,references:Ao(n)}:this.opts.fallbackReferenceResolver?.referencesForDefinitions(n),s=r.length===0?{available:!0,resolvedBinary:t.resolvedBinary,callees:Fo(r)}:this.opts.fallbackCalleeResolver?.calleesForDefinitions(r);if(o&&s){let a={resolvedBinary:o.resolvedBinary??s.resolvedBinary??t.resolvedBinary,references:Zn(n,o.references),callees:Au(r,s.callees)};return o.available&&s.available?{available:!0,...a}:{available:!1,reason:(o.available?void 0:o.reason)??(s.available?void 0:s.reason)??"Rust semantic fallback was unavailable.",...a}}return{available:!1,resolvedBinary:t.resolvedBinary,reason:i instanceof Error?i.message:String(i),references:Ao(n),callees:Fo(r)}}requestImportDefinitions(t,n,r){let i=Aa(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,ky),o=Aa(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Ay),s=Fa(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),a=Fa(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,Ny),c={projectRoot:this.projectRoot,rustAnalyzerBinary:t,file:n,positions:[...r],requestTimeoutMs:i,diagnosticsTimeoutMs:s,settleDelayMs:a,concurrency:o};return N("rust.semantic.import-definitions.session.request",()=>this.requester.requestImportDefinitions(c,Fr(r.length,i,o)),()=>({file:n,positions:r.length}))}};function To(e){return e.available?{available:!0}:{available:!1,reason:e.reason}}function ko(e){return e.available?"rust-analyzer binary path is unavailable.":e.reason}function _y(e,t,n={}){return new Nu(e,t,n)}function _o(e,t){let n=jy(e);if(n!==null)return n;let r=t.includeReferences!==!1;return r&&t.includeCallees!==!0&&t.includeSignatures!==!0&&t.definitionCount<=_M||r&&t.includeCallees===!0&&t.includeSignatures!==!0&&t.definitionCount<=OM?0:Ny}function Oy(e){let t=e?.trim().toLowerCase(),n=t==="0"||t==="false"||t==="off"||t==="worker",r=t==="1"||t==="true"||t==="on"||t==="durable",i=t===void 0||t==="";return{transport:n||!i&&!r?"worker":"durable",source:i?"default":"environment",fallback:"worker",valid:i||n||r,optOut:"SCIP_RUST_SEMANTIC_DURABLE_SESSION=0"}}function BM(e){return Oy(e).transport}function i7(e,t){let n=Oy(t);if(n.transport==="worker")return{...n,state:"per-command"};let r=No($y()),i=Mu(e,r,Fu()),o=Mo(i);return o?{...n,state:Do(o,Date.now(),bi,Si)?"live":"stale",pid:o.pid,heartbeatAtMs:o.heartbeatAtMs,...o.busyUntilMs===void 0?{}:{busyUntilMs:o.busyUntilMs}}:{...n,state:"stopped"}}function $M(e,t){let n=null,r=!1,i=!1,o=!1,s=()=>n??=t(),a=()=>{i||(e.shutdown(),i=!0)},c=(l,d,m)=>{let p=GM(l);r=!0;try{a()}catch{}xe()&&qs({type:"span",name:"rust.semantic.durable-session.request",durationMs:m,ok:!1,kind:d,session:"worker-fallback",reason:p})},u=(l,d,m)=>{if(o)throw new Error("Rust semantic failover session was already disposed.");if(r)return m(s());let p=performance.now();try{return d(e)}catch(f){c(f,l,performance.now()-p)}return m(s())};return{requestSemantic(l,d){return u("semantic",m=>m.requestSemantic(l,d),m=>m.requestSemantic(l,d))},requestImportDefinitions(l,d){return u("import-definitions",m=>m.requestImportDefinitions(l,d),m=>m.requestImportDefinitions(l,d))},shutdown(){if(o)return;o=!0;let l=[];try{a()}catch(d){l.push(d)}try{n?.shutdown()}catch(d){l.push(d)}if(l.length>0)throw l[0]}}}function jM(e,t,n={worker:()=>HM(),durable:()=>wy(e,{serverPath:No($y()),semanticWorkerPath:No(By())})}){return BM(t)==="durable"?$M(n.durable(),n.worker):n.worker()}function HM(e={}){let t=null,n=null,r=1,i=!1,o=null,s=null,a=d=>{d&&Tu(d,{recursive:!0,force:!0})},c=()=>{if(o)return;let d=t,m=n;t=null,n=null;let p=d?d.terminate():Promise.resolve(0);o=Promise.allSettled([p,My(m,{gracefulMs:1e3,forceMs:1e3})]).then(([f,g])=>{let y=(g.status==="fulfilled"?g.value:[{reaped:!1,detail:String(g.reason)}]).filter(S=>!S.reaped);if(f.status==="rejected"||y.length>0){s=new Error(`Rust semantic worker cleanup did not complete; ownership evidence remains at ${m??"unknown"}.`);return}a(m)}).finally(()=>{o=null})},u=()=>{if(t)return t;if(o)throw new Error("The previous Rust semantic session worker is still terminating; retry the request.");if(s)throw s;let d=e.semanticWorkerPath?AM(e.semanticWorkerPath):By();if(!kM(No(d)))throw new Error(`Rust semantic session worker was not found at ${No(d)}. Run npm run build before using built semantic Rust queries.`);return n=Ty(ku(Fu(),"scip-query-rust-session-")),t=new NM(d,e.shareEnvironment?{env:FM}:void 0),t.unref(),t},l=()=>{let d=n??Ty(ku(Fu(),"scip-query-rust-session-"));return n=d,ku(d,`${r++}.json`)};return{requestSemantic(d,m){if(i)throw new Error("Rust semantic session was already disposed.");let p=u(),f=l(),g=new SharedArrayBuffer(4),h=new Int32Array(g);if(p.postMessage({kind:"semantic",request:d,responsePath:f,sharedBuffer:g}),Atomics.wait(h,0,0,m)==="timed-out")throw c(),new Error(`Rust semantic session worker timed out after ${(m/1e3).toFixed(0)}s`);try{let S=UM(It(f,{maxBytes:yn,inputKind:"Rust semantic worker response"}));if(!S.ok)throw new Error(S.error);return S.response}finally{Tu(f,{force:!0})}},requestImportDefinitions(d,m){if(i)throw new Error("Rust semantic session was already disposed.");let p=u(),f=l(),g=new SharedArrayBuffer(4),h=new Int32Array(g);if(p.postMessage({kind:"import-definitions",request:d,responsePath:f,sharedBuffer:g}),Atomics.wait(h,0,0,m)==="timed-out")throw c(),new Error(`Rust semantic import-definition session worker timed out after ${(m/1e3).toFixed(0)}s`);try{let S=qM(It(f,{maxBytes:yn,inputKind:"Rust import-definition worker response"}));if(!S.ok)throw new Error(S.error);return S.response}finally{Tu(f,{force:!0})}},shutdown(){if(i)return;if(i=!0,!t){a(n),n=null;return}let d=l(),m=new SharedArrayBuffer(4),p=new Int32Array(m);t.postMessage({kind:"shutdown",responsePath:d,sharedBuffer:m}),Atomics.wait(p,0,0,5e3),c()}}}function UM(e){let t=JSON.parse(e);if(!t||typeof t!="object")return{ok:!1,error:"Rust semantic session worker wrote a non-object response."};let n=t;return n.ok===!0&&"response"in n?{ok:!0,response:n.response}:{ok:!1,error:typeof t.error=="string"?t.error:"Rust semantic session worker failed."}}function qM(e){let t=JSON.parse(e);if(!t||typeof t!="object")return{ok:!1,error:"Rust semantic session worker wrote a non-object response."};let n=t;return n.ok===!0&&"response"in n?{ok:!0,response:n.response}:{ok:!1,error:typeof t.error=="string"?t.error:"Rust semantic session worker failed."}}function GM(e){let t=e instanceof Error?`${e.name} ${e.message}`.toLowerCase():String(e).toLowerCase();return t.includes("readiness")?"readiness":t.includes("timeout")||t.includes("timed out")?"timeout":t.includes("helper")?"helper":"request"}function Ao(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Fo(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Fy(e){return new Map(e.map(t=>[t.symbolId,null]))}function Au(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??[]]))}function zM(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function KM(e){let t=0;return e.includeReferences!==!1&&(t+=(e.referenceDefinitions??e.definitions).length),e.includeCallees===!0&&(t+=(e.calleeDefinitions??e.definitions).length),e.includeSignatures===!0&&(t+=(e.signatureDefinitions??e.definitions).length),Math.max(1,t)}function _u(e,t){return t&&t>0?Math.max(e,t):e}function By(){return new URL("./rust-semantic-session-worker.js",import.meta.url)}function $y(){return new URL("./rust-semantic-session-server.js",import.meta.url)}function Aa(e,t){return Qn(e)??t}function Fa(e,t){return jy(e)??t}function jy(e){if(!e)return null;let t=Number(e);return Number.isInteger(t)&&t>=0?t:null}var $u=15e3,ju=8;function Gy(e,t={}){let n=t.status??Ma,r=JM(e,n),i=XM(e,n),o=QM(e,n),s=t.referenceResolver||t.calleeResolver||t.signatureResolver||!VM(t)?null:_y(e,n,{fallbackReferenceResolver:r,fallbackCalleeResolver:i,fallbackSignatureResolver:o}),a=t.referenceResolver??s??r,c=t.calleeResolver??s??i,u=t.signatureResolver??s??o,l=t.importUsageResolver??cy(t.sourceImportUsageResolver??YM(),t.importDefinitionResolver??s),d=t.calleeSymbolResolver,m=t.sourceZeroCalleeOracle,p=t.scipOccurrenceCalleeOracle,f=new Map,g=new Map,h=null,y=null,S=()=>(h??=n(e),h),b=()=>{let E=S();return E.dependencyAvailable?y??E:E},x=E=>{if(E.length===0)return new Map;let w=Bo(E);try{let I=a.referencesForDefinitions(w),k=S();return y=Na(k,I),I.available?new Map(I.references):Zn(w,I.references)}catch(I){let k=S();return y=Oo(k,I),_r(w)}},v=E=>{if(E.length===0)return new Map;let w=Bo(E),I=w.filter(Hy);if(I.length===0)return Or(w);let k=new Map,D=qy(I,p),F=[];for(let P of I)g.has(P.symbolId)?k.set(P.symbolId,g.get(P.symbolId)??[]):D.has(P.symbolId)?k.set(P.symbolId,D.get(P.symbolId)??[]):Uy(P,m)?k.set(P.symbolId,[]):F.push(P);if(F.length===0)return Pi(w,k,void 0);try{let P=c.calleesForDefinitions(F),A=S();y=Na(A,P);let L=Pi(F,P.callees,d);for(let[$,B]of L)k.set($,B);return Pi(w,k,void 0)}catch(P){let A=S();return y=Oo(A,P),Or(w)}},C=(E,w)=>{let I=Bo(E),k=Bo(w),D=k.filter(Hy),F=new Map,P=qy(D,p),A=[];for(let L of D)P.has(L.symbolId)?F.set(L.symbolId,P.get(L.symbolId)??[]):Uy(L,m)?F.set(L.symbolId,[]):A.push(L);if(I.length===0&&A.length===0)return{references:_r(I),callees:Pi(k,F,void 0)};try{let L=s?s.referencesAndCalleesForDefinitions(I,A):nT(a,c,{referenceDefinitions:I,calleeDefinitions:A}),$=S();y=Na($,L);let B=L.available?new Map(L.references):Zn(I,L.references);for(let[z,O]of L.callees)F.set(z,O);let X=Pi(k,F,d);for(let[z,O]of X)g.set(z,O);return{references:B,callees:X}}catch(L){let $=S();return y=Oo($,L),{references:_r(I),callees:Or(k)}}},R=E=>{if(E.length===0)return new Map;let w=Bo(E);try{let I=u.signaturesForDefinitions(w),k=S();return y=Na(k,I),zy(w,I.signatures)}catch(I){let k=S();return y=Oo(k,I),_a(w)}};return{language:"rust",availability:b,dispose:()=>{s?.dispose()},importUsage:E=>{let w=f.get(E);if(w)return w;try{let I=l.importUsage(E);return f.set(E,I),I}catch(I){let k=S();return y=Oo(k,I),[]}},referencesFor:E=>x([E]).get(E.symbolId)??[],referencesForDefinitions:x,referencesAndCalleesForDefinitions:C,calleesFor:E=>v([E]).get(E.symbolId)??[],calleesForDefinitions:v,signatureFor:E=>R([E]).get(E.symbolId)??null}}function Na(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 Oo(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 VM(e){if(e.usePersistentSession!==void 0)return e.usePersistentSession;let t=process.env.SCIP_RUST_SEMANTIC_SESSION;return t!=="0"&&t!=="false"}function YM(){return{importUsageFacts:()=>({usage:[],positions:[]})}}function Bo(e){return e.map(t=>{let n=t;return{...t,leaf:typeof n.leaf=="string"?n.leaf:G(t.symbol),parentTypeName:n.parentTypeName??null,isFunctionLike:typeof n.isFunctionLike=="boolean"?n.isFunctionLike:Re(t.symbol),isTypeLike:n.isTypeLike??!1,kind:n.kind??null,documentation:n.documentation??null,enclosingSymbol:n.enclosingSymbol??null}})}function Hy(e){return e.isFunctionLike}function Uy(e,t){if(!t)return!1;try{return t(e)}catch{return!1}}function qy(e,t){if(!t||e.length===0)return new Map;try{return t(e)}catch{return new Map}}function JM(e,t){return{referencesForDefinitions:n=>ZM(e,t,n)}}function XM(e,t){return{calleesForDefinitions:n=>eT(e,t,n)}}function QM(e,t){return{signaturesForDefinitions:n=>tT(e,t,n)}}function ZM(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:qu(r),references:_r(n)};let i=Hu();if(!Bu(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,references:_r(n)};let o=Di(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,$u),s=Oa(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),a=Di(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,ju),c=Oa(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),u=_o(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!0}),l={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,...s>0?{referenceRetryTimeoutMs:s}:{},diagnosticsTimeoutMs:c,settleDelayMs:u,concurrency:a},d=Ou(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Fr(n.length,_u(o,l.referenceRetryTimeoutMs),a)}),m=Gu(d.stdout);if(m)return{...Uu(m),resolvedBinary:r.resolvedBinary,references:Zn(n,new Map(m.references),new Set(m.incompleteReferenceSymbolIds??[]))};let p=d.error instanceof Error?d.error.message:d.stderr.trim()||`Rust semantic worker exited with status ${d.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:p,references:_r(n)}}function eT(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:qu(r),callees:Or(n)};let i=Hu();if(!Bu(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,callees:Or(n)};let o=Di(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,$u),s=Di(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,ju),a=Oa(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=_o(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!0}),u={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:c,concurrency:s,includeReferences:!1,includeCallees:!0},l=Ou(process.execPath,[i],{cwd:e,input:JSON.stringify(u),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Fr(n.length,o,s)}),d=Gu(l.stdout);if(d)return{...Uu(d),resolvedBinary:r.resolvedBinary,callees:Pi(n,new Map(d.callees??[]),void 0)};let m=l.error instanceof Error?l.error.message:l.stderr.trim()||`Rust semantic worker exited with status ${l.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:m,callees:Or(n)}}function tT(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:qu(r),signatures:_a(n)};let i=Hu();if(!Bu(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,signatures:_a(n)};let o=Di(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,$u),s=Di(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,ju),a=Oa(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=_o(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!1,includeSignatures:!0}),u={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:c,concurrency:s,includeReferences:!1,includeCallees:!1,includeSignatures:!0},l=Ou(process.execPath,[i],{cwd:e,input:JSON.stringify(u),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Fr(n.length,o,s)}),d=Gu(l.stdout);if(d)return{...Uu(d),resolvedBinary:r.resolvedBinary,signatures:zy(n,new Map(d.signatures??[]))};let m=l.error instanceof Error?l.error.message:l.stderr.trim()||`Rust semantic worker exited with status ${l.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:m,signatures:_a(n)}}function nT(e,t,n){let r=n.referenceDefinitions.length>0?e.referencesForDefinitions(n.referenceDefinitions):{available:!0,references:_r(n.referenceDefinitions)},i=n.calleeDefinitions.length>0?t.calleesForDefinitions(n.calleeDefinitions):{available:!0,callees:Or(n.calleeDefinitions)},o={resolvedBinary:r.resolvedBinary??i.resolvedBinary,references:r.references,callees:i.callees};return r.available&&i.available?{available:!0,...o}:{available:!1,reason:(r.available?void 0:r.reason)??(i.available?void 0:i.reason)??"Rust semantic resolution was unavailable.",...o}}function _r(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Or(e){return new Map(e.map(t=>[t.symbolId,[]]))}function _a(e){return new Map(e.map(t=>[t.symbolId,null]))}function Pi(e,t,n){let r=0,i=0;return N("rust.semantic.callees.complete-map",()=>{let o=new Map;for(let s of e){let a=t.get(s.symbolId)??[];a.length>0&&(r+=1),i+=a.length,o.set(s.symbolId,a.map(c=>({...c,symbol:n?n(c):c.symbol})))}return o},()=>({definitions:e.length,rows:r,callees:i,resolveSymbols:!!n}))}function zy(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function Hu(){return WM(new URL("./rust-semantic-worker.js",import.meta.url))}function Uu(e){return e.available?{available:!0}:{available:!1,reason:e.reason}}function qu(e){return e.available?"rust-analyzer binary path is unavailable.":e.reason}function Gu(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;if(typeof n.available!="boolean"||!Array.isArray(n.references)||n.available===!1&&typeof n.reason!="string"||n.available===!0&&n.reason!==void 0)return null;let r={references:n.references,incompleteReferenceSymbolIds:Array.isArray(n.incompleteReferenceSymbolIds)?n.incompleteReferenceSymbolIds.filter(i=>typeof i=="number"):void 0,callees:Array.isArray(n.callees)?n.callees:void 0,signatures:Array.isArray(n.signatures)?n.signatures:void 0};return n.available===!0?{available:!0,...r}:{available:!1,reason:String(n.reason),...r}}catch{return null}}function Di(e,t){return Qn(e)??t}function Oa(e,t){if(!e)return t;let n=Number(e);return Number.isInteger(n)&&n>=0?n:t}import{existsSync as rT}from"fs";import{deserializeSCIP as iT,SymbolRole as oT}from"@c4312/scip";var zu=new WeakMap;function Wy(e,t){let n=t.filter(sT);if(n.length===0)return new Map;let r=!1,i=0,o=0;return N("rust.scip-occurrence.callees",()=>{let s=lT(e);if(r=!!s,!s)return new Map;let a=new Map;for(let c of n){let u=aT(e,s,c);u!==null&&(a.set(c.symbolId,u),i+=1,o+=u.length)}return a},()=>({definitions:t.length,candidates:n.length,indexAvailable:r,resolvedDefinitions:i,resolvedCallees:o}))}function sT(e){return!(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||!e.isFunctionLike||e.leaf==="main"||Ge(e.symbol))}function aT(e,t,n){let r=W(e,n.relativePath);if(!r||r.language!=="rust")return null;let i=r.callables.find(u=>u.startLine!==n.startLine||u.endLine!==n.endLine?!1:u.name===n.leaf||n.leaf.endsWith(u.name)||u.name.endsWith(n.leaf));if(!i)return null;let o=r.callSites.filter(u=>u.line>=i.startLine&&u.line<=i.endLine);if(o.length===0)return null;let s=(t.occurrencesByFile.get(n.relativePath)??[]).filter(u=>u.line>=i.startLine&&u.line<=i.endLine&&u.callee.symbol!==n.symbol);if(s.some(u=>u.traitImplMember)||!cT(o,s))return null;let a=[],c=new Set;for(let u of s){let l=`${u.callee.symbol}\0${u.callee.file}\0${u.callee.line}`;c.has(l)||(c.add(l),a.push(u.callee))}return a}function cT(e,t){let n=Ky(e),r=Ky(t);if(n.size!==r.size)return!1;for(let[i,o]of n)if(r.get(i)!==o)return!1;return!0}function Ky(e){let t=new Map;for(let n of e){let r=n.calleeLeaf??n.leaf;if(!r)continue;let i=`${n.line}\0${r}`;t.set(i,(t.get(i)??0)+1)}return t}function lT(e){if(zu.has(e))return zu.get(e)??null;let t=uT(e);return zu.set(e,t),t}function uT(e){if(!e.generation.indexPath||!rT(e.generation.indexPath))return null;try{let t=ye(e).filter(o=>o.symbol.startsWith("rust-analyzer ")&&o.relativePath.endsWith(".rs")&&o.isFunctionLike),n=new Map(t.map(o=>[o.symbol,o])),r=iT(ai(e.generation.indexPath,{inputKind:"SCIP occurrence-callee index",maxBytes:si})),i=new Map;for(let o of r.documents??[]){let s=o.relativePath;if(!s||!s.endsWith(".rs")||e.isIgnored(s))continue;let a=[];for(let c of o.occurrences??[]){if(!c.symbol||(c.symbolRoles&oT.Definition)!==0)continue;let u=n.get(c.symbol);if(!u)continue;let l=c.range?.[0];Number.isInteger(l)&&a.push({line:l,leaf:u.leaf,traitImplMember:Ge(u.symbol),callee:{symbol:u.symbol,file:u.relativePath,line:u.startLine,callsiteLine:l}})}i.set(s,a)}return{occurrencesByFile:i}}catch{return null}}var Ba=class{sessions=new WeakMap;getOrCreate(t,n,r){let i=dT(t,n),o=this.sessions.get(t);o||(o=new Map,this.sessions.set(t,o));let s=o.get(i);if(s)return s.hits+=1,s.lastUsedAtMs=Date.now(),s.provider;let a=Date.now(),c=r();return o.set(i,{key:i,language:n,projectRoot:t.config.projectRoot,provider:c,createdAtMs:a,lastUsedAtMs:a,hits:1}),c}sessionsFor(t){return[...this.sessions.get(t)?.values()??[]]}clear(t){let n=this.sessions.get(t);if(n)for(let r of n.values())r.provider.dispose?.();this.sessions.delete(t)}};function dT(e,t){return`${e.config.projectRoot}:${t}-workspace`}import{randomUUID as jT}from"crypto";import{existsSync as HT}from"fs";import{dirname as Rb}from"path";function Vy(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(typeof t.available!="boolean"||t.dependencyAvailable!==void 0&&typeof t.dependencyAvailable!="boolean"||t.tsconfigPath!==void 0&&typeof t.tsconfigPath!="string"||t.tsconfigPaths!==void 0&&(!Array.isArray(t.tsconfigPaths)||!t.tsconfigPaths.every(n=>typeof n=="string"))||t.resolvedBinary!==void 0&&typeof t.resolvedBinary!="string"||t.note!==void 0&&typeof t.note!="string")return null;if(t.available===!0){if(t.reason!==void 0)return null}else if(typeof t.reason!="string"||t.reason.length===0)return null;return t}import{performance as ue}from"perf_hooks";function bt(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}import Xy from"path";import{realpathSync as Yy}from"fs";function mT(e,t){return e.getReferences().map(n=>{let r=n.getNode();return $a(r,t)})}function pT(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function Qy(e,t,n,r){let i=[];for(let o of pT(e))for(let s of mT(o,r))s.file===t.relativePath&&s.line>=t.startLine&&s.line<=t.endLine||i.push(s);for(let o of n)i.push(o);return Mi(i)}function Zy(e,t,n,r){let i=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();Ti(r,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||i.push({location:$a(a,r),node:a}))}return i}function $a(e,t){let n=e.getSourceFile(),r=n.getLineAndColumnAtPos(e.getStart());return{file:Ti(t,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function eb(e,t,n){let r=e.getSourceFile(),i=Wu(r,e),o=e.getText(),s=new RegExp(`\\b${Ie(o)}\\b`,"g"),a=r.getFullText().split(`
51
- `),c=[];for(let u=0;u<a.length;u++){if(u===i)continue;let l=a[u]??"";s.lastIndex=0;let d;for(;(d=s.exec(l))!==null;)c.push({file:t,line:u,column:d.index})}return Mi(c.filter(u=>Ti(n,Xy.join(n,u.file))===t))}function Ku(e){for(let t=e;t;t=t.getParent()){let n=t.getKindName();if(n.includes("Type")||n==="InterfaceDeclaration"||n==="TypeAliasDeclaration")return!0;if(n==="CallExpression"||n==="NewExpression"||n==="ExpressionStatement")return!1}return!1}function Wu(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function Mi(e){let t=new Set,n=[];for(let r of e){let i=`${r.file}:${r.line}:${r.column}`;t.has(i)||(t.add(i),n.push(r))}return n}function Ti(e,t){let n=e||process.cwd(),r=Jy(n,t);if(r)return r;try{return Jy(Yy(n),Yy(t))}catch{return null}}function Jy(e,t){let n=Xy.relative(e,t).replace(/\\/g,"/");return!n||n===".."||n.startsWith("../")?null:n}function tb(e,t,n,r){let i=fT(t,r);return i.size===0?new Map:gT(e,n,i)}function fT(e,t){let n=new Map;for(let r of q(e,t)){let i=G(r.symbol)??r.leaf;if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push(r)}return n}function gT(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of hT(e,o)){let a=n.get(s);if(!a)continue;let c=Wu(t,o);for(let u of a){if(c<u.startLine-1||c>u.endLine+1)continue;let l=Math.abs(c-u.startLine),d=i.get(u.symbolId);d!==void 0&&d<=l||(i.set(u.symbolId,l),r.set(u.symbolId,o))}}}),r}function hT(e,t){let n=[],r=i=>{i&&!n.includes(i)&&n.push(i)};if("getNameNode"in t&&typeof t.getNameNode=="function"){let i=t.getNameNode();r(i?.getText())}if("getName"in t&&typeof t.getName=="function"){let i=t.getName();r(i)}return e.Node.isIdentifier(t)&&r(t.getText()),n}var yT=Vt("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function nb(e,t,n,r){let i=Ju(e,t),o=Vu(i.get(r)??[],n);if(o)return o;let s=[];for(let a of i.values())for(let c of a)((c.leaf||G(c.symbol)||"").includes(r)||c.symbol.includes(r))&&s.push(c);return Vu(s,n)}function Yu(e,t,n,r){return Vu(Ju(e,t).get(r)??[],n)}function rb(e,t){let n=new Map;for(let[r,i]of Ju(e,t)){let o=i[0];o&&n.set(r,o)}return n}function Ju(e,t){return yT.get(e,t,()=>{let n=new Map;for(let r of q(e,t)){let i=r.leaf||G(r.symbol);if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push({...r,leaf:i})}for(let r of n.values())r.sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine||i.symbolId-o.symbolId);return n})}function Vu(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let i of e){let o=Math.abs(i.startLine-t);(o<r||o===r&&n&&i.startLine<n.startLine)&&(n=i,r=o)}return n}import bT from"path";import{realpathSync as ST}from"fs";function ob(e,t){let n=new Map,r=new Map,i=null,o=()=>(i??=Q(e,{extensions:ca}),i),s=u=>bt(r,u,()=>N("typescript.source-file-index",()=>{let l=new Map;for(let d of u.project.getSourceFiles())ib(l,d);return{project:u.project,sourceFiles:l}},()=>({tsconfigPath:u.tsconfigPath,indexedDocuments:o().length}))),a=(u,l)=>{let d=s(u),m=d.sourceFiles.get(l)??null;return m||(m=u.project.addSourceFileAtPathIfExists(l)??null,m&&ib(d.sourceFiles,m)),m?{project:d.project,sourceFile:m}:null},c=u=>Wn(u)?bt(n,u,()=>{let l=vT(e.config.projectRoot,u);if(!l)return null;for(let p of t){if(!p.loaded)continue;let f=s(p).sourceFiles.get(l);if(f)return{project:p.project,sourceFile:f}}let d=t.find(p=>p.fileNames?.has(l));if(d)return a(d,l);for(let p of t){if(!p.loaded)continue;let f=a(p,l);if(f)return f}let m=t[0];return m?a(m,l):null}):null;return{sourceFile:u=>c(u)?.sourceFile??null,sourceFileMatch:c,indexedTypeScriptLikeDocuments:o}}function ib(e,t){let n=Xu(t.getFilePath());e.set(n,t);try{e.set(Xu(ST(n)),t)}catch(r){if(!Ce(r))throw r}}function vT(e,t){try{return Xu(js(e,t,{inputKind:"indexed TypeScript source file"}).absolutePath)}catch(n){if(!Ce(n))throw n;return null}}function Xu(e){return bT.resolve(e)}function Qu(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function sb(e){let t=`${e.relativeDir}/src`;return[`${t}/index.ts`,`${t}/index.tsx`,`${t}/index.mts`,`${t}/index.cts`]}import{existsSync as $o}from"fs";import et from"path";var Zu=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function ed(e,t){let r=t?et.dirname(et.join(e,t)):e,i=et.resolve(e);for(;r.startsWith(i);){for(let s of Zu){let a=et.join(r,s);if($o(a))return a}let o=et.dirname(r);if(o===r)break;r=o}for(let o of Zu){let s=et.join(e,o);if($o(s))return s}return null}function ja(e){let t=e.config.projectRoot,n=new Set(CT(t,e.config.semantic?.typescript?.tsconfigs)),r=Q(e,{includeIgnored:!1,extensions:ca});for(let i of r){let o=ed(t,i);o&&n.add(et.resolve(o))}if(n.size===0){let i=ed(t);i&&n.add(et.resolve(i))}return[...n].filter(i=>!ab(t,i)).sort((i,o)=>i.localeCompare(o))}function CT(e,t=[]){let n=new Set;for(let r of t){let i=et.isAbsolute(r)?r:et.join(e,r);$o(i)&&n.add(et.resolve(i))}for(let r of xT(e))for(let i of Zu){let o=et.join(r,i);$o(o)&&n.add(et.resolve(o))}if(n.size===0){let r=ed(e);r&&n.add(et.resolve(r))}return[...n].filter(r=>!ab(e,r)).sort((r,i)=>r.localeCompare(i))}function xT(e){let t=et.join(e,"package.json");if(!$o(t))return[];let n;try{n=JSON.parse(Xe(t,"project package manifest"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>eg(e,i))}function ab(e,t){let n=et.relative(e,t).replace(/\\/g,"/");return n.startsWith("..")||n.includes("/node_modules/")||n.startsWith("node_modules/")||n.includes("/dist/")||n.startsWith("dist/")}var RT=32;function hb(e,t){let n=N("typescript.provider.load",()=>vi());if(!n)return ua("ts-morph is not installed");let r=N("typescript.provider.tsconfig-discovery",()=>ja(e));if(r.length===0)return ua("no tsconfig found");try{let i=N("typescript.provider.project-bundles",()=>Bg(n,r),()=>({tsconfigs:r.length}));return ET(e,n,i)}catch(i){return ua(i instanceof Error?i.message:String(i),r[0],r)}}function ET(e,t,n,r={}){return N("typescript.provider.construct",()=>new td(e,t,n),()=>({tsconfigs:n.length,reusedProjects:r.reusedProjects===!0}))}var td=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=Zf(t.config.projectRoot),this.sourceFiles=ob(t,r)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;compilerCheckerCache=new WeakMap;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){let t=la(this.projects);return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(n=>n.tsconfigPath),projectScope:t?"file-closure":"project",...t?{note:"compiler projects are file-scoped: callees, signatures, and import usage are served per file; references and hierarchies are unavailable"}:{}}}attachBatchFiles(t){if(la(this.projects))for(let n of new Set(t.map(r=>r.relativePath)))this.sourceFiles.sourceFile(n)}assertProjectWide(){if(la(this.projects))throw new Error($g)}importUsage(t){return bt(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let r=wT();return N("typescript.import-usage.file",()=>this.importUsageForSourceFile(t,n,r),()=>({file:t,...r}))})}referencesFor(t){return bt(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);return this.referencesForDefinitionNode(t,n)})}referencesForDefinitions(t,n={}){this.assertProjectWide();let r=new Map,i=xe(),o=[];for(let l of t){let d=this.referencesCache.get(l.symbolId);d?r.set(l.symbolId,d):o.push(l)}if(o.length===0)return r;let s=o,a=n.exact?[]:o.filter(l=>!ub(l));if(a.length>=RT){let l=this.referencesForDefinitionsBySymbolScan(a);for(let d of a){let m=l.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,m),r.set(d.symbolId,m)}if(s=o.filter(d=>ub(d)),s.length===0)return r}let c=new Map;for(let l of s){let d=c.get(l.relativePath);d?d.push(l):c.set(l.relativePath,[l])}let u=[];for(let[l,d]of c){let m=db();N("typescript.references-map.file",()=>{let p=this.definitionNodesForFile(l);for(let f of d){i&&(m.cacheMisses+=1);let g=p.get(f.symbolId)??null;i&&(g?m.nodeHits+=1:m.nodeMisses+=1);try{let h=this.referencesForDefinitionNode(f,g,i?m:void 0);this.referencesCache.set(f.symbolId,h),r.set(f.symbolId,h)}catch{m.preciseSearchFailures+=1,u.push(f)}}},()=>({relativePath:l,definitions:d.length,...pb(m)}))}if(u.length>0){let l=this.referencesForDefinitionsBySymbolScan(u);for(let d of u){let m=l.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,m),r.set(d.symbolId,m)}}return r}referenceFragmentsForFiles(t){this.assertProjectWide();let n=ye(this.db).filter(o=>Wn(o.relativePath)),r=t.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(n,r);return Hg(n,i,r)}referencesForDefinitionsBySymbolScan(t,n){let r=xe(),i=db(),o=new Map,s=new Set(t.map(c=>c.symbolId)),a=new Map(t.map(c=>[c.symbolId,c]));for(let c of t)o.set(c.symbolId,[]);return N("typescript.references-map.inverted-scan",()=>{let c=r?ue.now():0,u=n?this.packageImportReferencesForFiles(n):this.packageImportReferences();for(let h of t){let y=u.get(h.symbolId)??[];if(y.length>0){let S=o.get(h.symbolId)??[];S.push(...y),o.set(h.symbolId,S)}r&&(i.packageReferenceCount+=y.length)}r&&(i.packageRefsMs+=ue.now()-c);let l=new Map,d=new Map,m=this.hierarchyTargetsForDefinitions(t),p=new Set(t.map(h=>h.leaf).filter(Boolean)),f=r?ue.now():0;for(let h of n??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(h))continue;let y=this.sourceFiles.sourceFile(h);y&&(r&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(y,h,s,a,m,p,l,d,o,r?i:void 0))}r&&(i.scanMs+=ue.now()-f);let g=r?ue.now():0;this.addHierarchyMemberReferences(t,o,r?i:void 0),r&&(i.hierarchyMs+=ue.now()-g);for(let[h,y]of o){let S=Mi(y);o.set(h,S),r&&(i.referenceCount+=S.length)}},()=>({definitions:t.length,...pb(i)})),o}addReferencesFromSourceFileScan(t,n,r,i,o,s,a,c,u,l){let d=this.compilerCheckerForSourceFile(t),m=t.compilerNode,p=DT(t),f=g=>{if(this.tsMorph.ts.isIdentifier(g)){if(l&&(l.identifiers+=1),!s.has(g.text)&&!p.has(g.text)){this.tsMorph.ts.forEachChild(g,f);return}let h=this.compilerReferenceSymbol(d,g,l);if(h){let y;a.has(h)?y=a.get(h)??null:(y=this.referenceDefinitionFromCompilerSymbol(h),a.set(h,y)),l&&(y?l.targetHits+=1:l.targetMisses+=1);let S=bt(c,h,()=>this.compilerSymbolKeys(h)),b=null,x=null,v=y&&r.has(y.symbolId)?i.get(y.symbolId):void 0;if(v&&(b=jo(m,g),!lb(v,n,b))){let C=m.getLineAndCharacterOfPosition(g.getStart(m));x={file:n,line:C.line,column:C.character};let R=u.get(v.symbolId)??[];R.push(x),u.set(v.symbolId,R),l&&(l.requestedHits+=1)}for(let C of S)for(let R of o.get(C)?.values()??[]){if(b??=jo(m,g),lb(R,n,b))continue;if(!x){let w=m.getLineAndCharacterOfPosition(g.getStart(m));x={file:n,line:w.line,column:w.character}}let E=u.get(R.symbolId)??[];E.push(x),u.set(R.symbolId,E),l&&(l.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(g,f)};f(m)}hierarchyTargetsMemo=null;hierarchyTargetsForDefinitions(t){let n=AT(t);if(this.hierarchyTargetsMemo?.key===n)return this.hierarchyTargetsMemo.targets;let r=pt(this.db),i=`definitions:${n}`,o=!1,s=N("typescript.references-map.hierarchy-targets",()=>{if(r){let c=mb.read(this.db,i,r);if(c&&c.projectRoot===this.db.config.projectRoot)return o=!0,kT(c,t)}let a=this.computeHierarchyTargets(t);return r&&mb.write(this.db,i,r,{version:yb,projectRoot:this.db.config.projectRoot,entries:[...a].map(([c,u])=>[c,[...u.values()].map(l=>l.symbol)])}),a},()=>({definitions:t.length,hit:o}));return this.hierarchyTargetsMemo={key:n,targets:s},s}computeHierarchyTargets(t){let n=new Map;for(let r of t){let i=this.nodeForDefinition(r),o=i?.compilerNode;if(!o||!this.isHierarchyMethod(o))continue;let s=o.parent;if(!this.isHierarchyContainer(s))continue;let a=this.compilerCheckerForSourceFile(i.getSourceFile()),c=a.getSymbolAtLocation(o.name);if(c)for(let u of this.hierarchyMemberSymbols(a,s,c))for(let l of this.compilerSymbolKeys(u)){let d=n.get(l)??new Map;d.set(r.symbolId,r),n.set(l,d)}}return n}hierarchyMemberSymbols(t,n,r){let i=new Set,o=new Set,s=(a,c,u)=>{if(!o.has(a)){o.add(a),i.add(c);for(let l of u){let d=l.getProperty(r.name);d&&s(l,d,this.hierarchyAncestorTypesForType(t,l))}}};return s(t.getTypeAtLocation(n),r,this.hierarchyAncestorTypes(t,n)),i}addHierarchyMemberReferences(t,n,r){let i=new Map;for(let o of t){let s=this.nodeForDefinition(o),a=s?.compilerNode;if(!a||!this.isHierarchyMethod(a))continue;let c=a.parent;if(!this.isHierarchyContainer(c))continue;let u=this.compilerCheckerForSourceFile(s.getSourceFile()),l=u.getSymbolAtLocation(a.name);if(!l)continue;let d=a.getSourceFile(),m=d.getLineAndCharacterOfPosition(a.name.getStart(d)),p={definition:o,location:{file:o.relativePath,line:m.line,column:m.character}},f=n.get(o.symbolId)??[];for(let h of this.hierarchyMemberSymbols(u,c,l))if(h!==l)for(let y of this.compilerSymbolLocations(h))f.push(y),r&&(r.hierarchyReferences+=1);n.set(o.symbolId,f);let g=this.hierarchyRootMemberSymbols(u,c,l);for(let h of g){let y=i.get(h)??new Map;y.set(o.symbolId,p),i.set(h,y)}r&&(r.hierarchyDefinitions+=1)}for(let o of i.values())if(!(o.size<2)){r&&(r.hierarchyFamilies+=1);for(let{definition:s}of o.values()){let a=n.get(s.symbolId)??[];for(let c of o.values())c.definition.symbolId!==s.symbolId&&(a.push(c.location),r&&(r.hierarchyReferences+=1));n.set(s.symbolId,a)}}}hierarchyRootMemberSymbols(t,n,r){let i=new Set,o=new Set,s=(a,c,u)=>{if(o.has(a))return;o.add(a);let l=!1;for(let d of u){let m=d.getProperty(r.name);m&&(l=!0,s(d,m,this.hierarchyAncestorTypesForType(t,d)))}if(!l)for(let d of this.compilerSymbolKeys(c))i.add(d)};return s(t.getTypeAtLocation(n),r,this.hierarchyAncestorTypes(t,n)),i}compilerSymbolKeys(t){return(t.declarations??[]).map(n=>{let r=n.getSourceFile();return`${r.fileName}\0${n.getStart(r)}\0${t.name}`})}compilerSymbolLocations(t){let n=[];for(let r of t.declarations??[]){let i=r.getSourceFile(),o=Ti(this.db.config.projectRoot,i.fileName);if(!o)continue;let s=r.name,a=i.getLineAndCharacterOfPosition((s??r).getStart(i));n.push({file:o,line:a.line,column:a.character})}return n}baseTypes(t,n){try{return t.getBaseTypes(n)??[]}catch{return[]}}hierarchyAncestorTypes(t,n){let r=new Set(this.hierarchyAncestorTypesForType(t,t.getTypeAtLocation(n)));for(let i of n.heritageClauses??[])for(let o of i.types)r.add(t.getTypeAtLocation(o));return[...r]}hierarchyAncestorTypesForType(t,n){let r=new Set(this.baseTypes(t,n));for(let i of n.getSymbol()?.declarations??[])if(this.isHierarchyContainer(i))for(let o of i.heritageClauses??[])for(let s of o.types)r.add(t.getTypeAtLocation(s));return[...r]}isHierarchyMethod(t){return this.tsMorph.ts.isMethodDeclaration(t)||this.tsMorph.ts.isMethodSignature(t)}isHierarchyContainer(t){return this.tsMorph.ts.isClassDeclaration(t)||this.tsMorph.ts.isClassExpression(t)||this.tsMorph.ts.isInterfaceDeclaration(t)}compilerReferenceSymbol(t,n,r){r&&(r.symbolLookups+=1);let i=t.getSymbolAtLocation(n);if(i){if((i.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return i;try{return r&&(r.aliasResolutions+=1),t.getAliasedSymbol(i)}catch{return i}}}calleesFor(t){return bt(this.calleesCache,t.symbolId,()=>bt(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}calleesForDefinitions(t){let n=new Map;this.attachBatchFiles(t);let r=new Map;for(let i of t){let o=r.get(i.relativePath);o?o.push(i):r.set(i.relativePath,[i])}for(let[i,o]of r){let s=this.fileCalleesCache.get(i),a=new Set(o.map(u=>u.symbolId)),c=s??this.calleeMapForFile(i,a);for(let u of o){let l=c.get(u.symbolId)??[];this.calleesCache.set(u.symbolId,l),n.set(u.symbolId,l)}}return n}calleeCoverageForDefinitions(t){this.attachBatchFiles(t);let n=new Map,r=new Map;for(let i of t){let o=r.get(i.relativePath);o?o.push(i):r.set(i.relativePath,[i]),n.set(i.symbolId,{callSites:0,resolvedInRepository:0,resolvedExternal:0,unresolved:0})}for(let[i,o]of r){let s=this.sourceFiles.sourceFile(i);if(!s)continue;let a=this.compilerCheckerForSourceFile(s),c=s.compilerNode,u=new Map,l=d=>{if(this.tsMorph.ts.isCallExpression(d)||this.tsMorph.ts.isNewExpression(d)||fb(this.tsMorph.ts,d)){let m=cb(o,jo(c,d)),p=m?n.get(m.symbolId):void 0;if(p){p.callSites+=1;let f=this.tsMorph.ts.isJsxOpeningElement(d)||this.tsMorph.ts.isJsxSelfClosingElement(d),g=f&&!this.tsMorph.ts.isJsxNamespacedName(d.tagName)?d.tagName:f?null:d.expression,h=g?this.compilerSymbolForExpression(a,g):void 0;if(!h)p.unresolved+=1;else{let y=u.get(h);y===void 0&&(y=this.definitionFromCompilerSymbol(h),u.set(h,y)),y?p.resolvedInRepository+=1:p.resolvedExternal+=1}}}this.tsMorph.ts.forEachChild(d,l)};l(c)}return n}referencesForDefinitionNode(t,n,r){let i=r?ue.now():0,o=this.packageImportReferencesForDefinition(t);if(r&&(r.packageRefsMs+=ue.now()-i,r.packageReferenceCount+=o.length),!n)return o;let s=r?ue.now():0,a=Qy(n,t,o,this.db.config.projectRoot);return r&&(r.semanticRefsMs+=ue.now()-s,r.referenceCount+=a.length),a}signatureFor(t){return bt(this.signatureCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);if(!n||!this.tsMorph.Node.isFunctionDeclaration(n)&&!this.tsMorph.Node.isMethodDeclaration(n)&&!this.tsMorph.Node.isArrowFunction(n)&&!this.tsMorph.Node.isFunctionExpression(n)&&!this.tsMorph.Node.isConstructorDeclaration(n))return null;let r=n.getType().getCallSignatures()[0];if(!r)return null;let i=r.getParameters().map(s=>{let a=s.getDeclarations()[0],c=a?s.getTypeAtLocation(a).getText(a):s.getValueDeclaration()?.getType().getText()??"unknown";return gb(c)}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${gb(o)}`})}importUsageForSourceFile(t,n,r){let i=[],o=new Map;for(let s of n.getImportDeclarations()){r.declarations+=1;let a=ql(this.db,t,s.getModuleSpecifierValue()),c=s.getImportClause()?.isTypeOnly()??!1;for(let u of nd(s)){r.entries+=1;let l=c?null:u.identifier?.getSymbol()?.compilerSymbol??null;!c&&u.identifier&&(l?r.bindingSymbols+=1:r.missingBindingSymbols+=1);let d={sourcePath:a,entry:u,typeOnlyDeclaration:c,bindingSymbol:l,references:[]};if(i.push(d),c||!u.localName||!l)continue;let m=o.get(u.localName);m?m.push(d):o.set(u.localName,[d])}}return o.size>0&&n.forEachDescendant(s=>{if(s.getKindName()!=="Identifier")return;let a=o.get(s.getText());if(!a||LT(s))return;r.scannedIdentifiers+=1;let c=s.getSymbol()?.compilerSymbol;if(r.symbolLookups+=1,!!c){for(let u of a)if(u.bindingSymbol===c){u.references.push({location:$a(s,this.db.config.projectRoot),node:s}),r.matchedReferences+=1;break}}}),i.map(s=>s.typeOnlyDeclaration?IT(t,s.sourcePath,s.entry):s.entry.identifier&&!s.bindingSymbol?(r.fallbackEntries+=1,this.valueImportUsageForEntry(t,s.sourcePath,s.entry)):this.valueImportUsageFromLocations(t,s.sourcePath,s.entry,s.references))}valueImportUsageForEntry(t,n,r){let i=r.identifier?r.identifier.findReferences():[],o=[];for(let s of i)for(let a of Zy(s,t,r.identifier,this.db.config.projectRoot))o.push(a);return this.valueImportUsageFromLocations(t,n,r,o)}valueImportUsageFromLocations(t,n,r,i){let o=i.some(c=>!Ku(c.node)),s=i.some(c=>Ku(c.node)),a=r.isTypeOnly;return{importer:t,sourcePath:n,importedName:r.importedName,localName:r.localName,kind:r.kind,isTypeOnly:a,isUsed:a||i.length>0,isTypeUsed:a||s,isValueUsed:o,references:i.map(c=>c.location)}}packageImportReferencesForDefinition(t){return this.packageImportReferences().get(t.symbolId)??[]}packageImportReferencesForFiles(t){let n=new Map,r=new Set;for(let o of t){let s=this.sourceFiles.sourceFile(o);if(s)for(let a of s.getImportDeclarations()){let c=Qu(this.workspacePackages,a.getModuleSpecifierValue());c&&r.add(c)}}if(r.size===0)return n;let i=this.packageExportsForNames(r);for(let o of t)this.addPackageImportReferencesForDocument(n,i,o);for(let[o,s]of n)n.set(o,Mi(s));return n}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let t=new Map,n=this.packageExports();for(let r of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(t,n,r);for(let[r,i]of t)t.set(r,Mi(i));return this.packageImportReferenceIndex=t,t}addPackageImportReferencesForDocument(t,n,r){if(this.db.isIgnored(r))return;let i=this.sourceFiles.sourceFileMatch(r);if(i)for(let o of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(t,n,r,o)}addPackageImportReferencesForDeclaration(t,n,r,i){let o=Qu(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of nd(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let u=eb(a.identifier,r,this.db.config.projectRoot);u.length>0&&FT(t,c,u)}}packageExports(){return this.packageExportIndex?this.packageExportIndex:(this.packageExportIndex=this.packageExportsForNames(new Set(this.workspacePackages.map(t=>t.name))),this.packageExportIndex)}packageExportsForNames(t){let n=new Map;for(let r of this.workspacePackages){if(!t.has(r.name))continue;let i=new Map;for(let o of sb(r))this.collectPackageExports(r,o,i,new Set);i.size>0&&n.set(r.name,i)}return n}collectPackageExports(t,n,r,i){if(i.has(n))return;i.add(n);let o=this.sourceFiles.sourceFile(n);if(o)for(let s of o.getExportDeclarations()){let a=s.getModuleSpecifierValue(),c=a?ql(this.db,n,a):n;if(!c||!c.startsWith(`${t.relativeDir}/src/`))continue;let u=s.getNamedExports();if(u.length===0){if(s.isNamespaceExport())continue;this.collectPackageExports(t,c,r,i);continue}for(let l of u){let d=l.getNameNode().getText(),m=l.getAliasNode()?.getText()??d,p=this.indexedDefinitionByLeaf(c,d);if(!p)continue;let f=r.get(m);f||(f=new Set,r.set(m,f)),f.add(p.symbolId)}}}indexedDefinitionByLeaf(t,n){return bt(this.indexedDefinitionLeafCache,t,()=>rb(this.db,t)).get(n)??null}nodeForDefinition(t){return bt(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return bt(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?tb(this.tsMorph,this.db,n,t):new Map})}referenceDefinitionFromCompilerSymbol(t){return this.definitionFromCompilerSymbol(t,void 0,!0)}definitionFromCompilerSymbol(t,n,r=!1){let i=t.name,o=n?ue.now():0,s=t.declarations??[];n&&(n.declarationsMs+=ue.now()-o,n.declarationChecks+=s.length);for(let a of s){let c=n?ue.now():0,u=a.getSourceFile(),l=Ti(this.db.config.projectRoot,u.fileName),d=u.getLineAndCharacterOfPosition(a.getStart(u)).line;if(n&&(n.declarationLocationMs+=ue.now()-c),!l||this.db.isIgnored(l))continue;let m=n?ue.now():0,p=this.compilerDeclarationName(a),f=r?Yu(this.db,l,d,i)??(p&&p!==i?Yu(this.db,l,d,p):null):nb(this.db,l,d,i);if(n&&(n.indexedLookupMs+=ue.now()-m),f)return{symbolId:f.symbolId,symbol:f.symbol,file:f.relativePath,line:f.startLine}}return null}compilerDeclarationName(t){let n=t.name;return n&&this.tsMorph.ts.isIdentifier(n)?n.text:null}calleeMapForFile(t,n){let r=xe(),i=0,o=0,s=0,a=0,c=0,u=0,l=0,d=0,m=r?MT():void 0;return N("typescript.callee-map.file",()=>{let p=r?ue.now():0,f=this.sourceFiles.sourceFile(t);if(r&&(c=Math.round(ue.now()-p)),!f)return new Map;let g=r?ue.now():0,h=q(this.db,t).sort((E,w)=>E.startLine-w.startLine||w.endLine-E.endLine);if(r&&(u=Math.round(ue.now()-g)),i=h.length,h.length===0)return new Map;let y=new Map,S=r?ue.now():0,b=this.compilerCheckerForSourceFile(f),x=f.compilerNode;r&&(l=Math.round(ue.now()-S));let v=new Map,C=E=>{if(this.tsMorph.ts.isCallExpression(E)||this.tsMorph.ts.isNewExpression(E)||fb(this.tsMorph.ts,E)){r&&(o+=1);let w=this.semanticCalleeForCallNode(b,x,h,E,v,n,m);w&&(r&&(s+=1),PT(y,w.callerId,w.target))}this.tsMorph.ts.forEachChild(E,C)},R=r?ue.now():0;C(x),r&&(d=Math.round(ue.now()-R));for(let[E,w]of y)y.set(E,NT(w));return a=y.size,y},()=>({relativePath:t,definitions:i,callNodes:o,resolvedCallees:s,outputRows:a,requestedDefinitions:n?.size??i,sourceFileLookupMs:c,definitionsLoadMs:u,checkerLookupMs:l,traversalMs:d,...m?TT(m):{}}))}semanticCalleeForCallNode(t,n,r,i,o,s,a){let c=a?ue.now():0,u=cb(r,jo(n,i));if(a&&(a.callerLookupMs+=ue.now()-c),!u)return null;if(s&&!s.has(u.symbolId))return a&&(a.skippedUnrequestedCallers+=1),null;let l=this.tsMorph.ts.isJsxOpeningElement(i)||this.tsMorph.ts.isJsxSelfClosingElement(i);if(l&&this.tsMorph.ts.isJsxNamespacedName(i.tagName))return null;let d=l?i.tagName:i.expression,m=this.compilerSymbolForExpression(t,d,a),p=null;if(m)if(a&&(a.targetSymbolHits+=1),o.has(m))a&&(a.compilerSymbolCacheHits+=1),p=o.get(m)??null;else{a&&(a.compilerSymbolCacheMisses+=1);let f=a?ue.now():0;p=this.definitionFromCompilerSymbol(m,a),a&&(a.targetLookupMs+=ue.now()-f),o.set(m,p)}else a&&(a.targetMisses+=1);return p?{callerId:u.symbolId,target:{symbol:p.symbol,file:p.file,line:p.line,callsiteLine:jo(n,i),...l?{kind:"jsx-render"}:{}}}:null}compilerSymbolForExpression(t,n,r){let i=r?ue.now():0,o=t.getSymbolAtLocation(n);if(r&&(r.expressionSymbolMs+=ue.now()-i),o){if((o.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return o;try{return t.getAliasedSymbol(o)}catch{return o}}r&&(r.typeFallbacks+=1);let s=r?ue.now():0,a=t.getTypeAtLocation(n).getSymbol();return r&&(r.typeSymbolMs+=ue.now()-s),a}compilerCheckerForSourceFile(t){let n=t.getProject(),r=this.compilerCheckerCache.get(n);return r||(r=n.getTypeChecker().compilerObject,this.compilerCheckerCache.set(n,r)),r}};function nd(e){let t=[],n=e.getDefaultImport();n&&t.push({identifier:n,importedName:"default",localName:n.getText(),kind:"default",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});let r=e.getNamespaceImport();r&&t.push({identifier:r,importedName:"*",localName:r.getText(),kind:"namespace",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});for(let i of e.getNamedImports()){let o=i.getNameNode(),a=i.getAliasNode()??(o.getKindName()==="Identifier"?o:null);t.push({identifier:a,importedName:o.getText(),localName:a?.getText()??o.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(e.getImportClause()?.isTypeOnly()??!1)})}return t.length===0&&t.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),t}function IT(e,t,n){return{importer:e,sourcePath:t,importedName:n.importedName,localName:n.localName,kind:n.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function wT(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function LT(e){for(let t=e;t;t=t.getParent())if(t.getKindName()==="ImportDeclaration")return!0;return!1}function PT(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function DT(e){let t=new Set;for(let n of e.getImportDeclarations())for(let r of nd(n))r.localName&&t.add(r.localName);return t}function cb(e,t){let n=null;for(let r of e)t<r.startLine||t>r.endLine||(!n||r.startLine>=n.startLine)&&(n=r);return n}function jo(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line}function lb(e,t,n){return t===e.relativePath&&n>=e.startLine&&n<=e.endLine}function ub(e){return e.symbol.includes("#")?kt(e.symbol)==="type"&&e.relativePath.endsWith(".d.ts"):!1}function MT(){return{callerLookupMs:0,expressionSymbolMs:0,typeSymbolMs:0,targetLookupMs:0,declarationsMs:0,declarationLocationMs:0,indexedLookupMs:0,compilerSymbolCacheHits:0,compilerSymbolCacheMisses:0,targetSymbolHits:0,targetMisses:0,typeFallbacks:0,declarationChecks:0,skippedUnrequestedCallers:0}}function TT(e){return{...e,callerLookupMs:Math.round(e.callerLookupMs),expressionSymbolMs:Math.round(e.expressionSymbolMs),typeSymbolMs:Math.round(e.typeSymbolMs),targetLookupMs:Math.round(e.targetLookupMs),declarationsMs:Math.round(e.declarationsMs),declarationLocationMs:Math.round(e.declarationLocationMs),indexedLookupMs:Math.round(e.indexedLookupMs)}}function db(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0,preciseSearchFailures:0,hierarchyDefinitions:0,hierarchyFamilies:0,hierarchyReferences:0,hierarchyMs:0}}var yb=1,mb=Er({kind:"typescript-hierarchy-targets",invalidation:Ne("typescript-hierarchy-targets"),serialize:e=>JSON.stringify(e),deserialize:e=>{try{let t=JSON.parse(e);return t.version!==yb||typeof t.projectRoot!="string"||!Array.isArray(t.entries)?null:t}catch{return null}}});function kT(e,t){let n=new Map(t.map(i=>[i.symbol,i])),r=new Map;for(let[i,o]of e.entries){let s=new Map;for(let a of o){let c=n.get(a);c&&s.set(c.symbolId,c)}s.size>0&&r.set(i,s)}return r}function AT(e){let t=2166136261;for(let n of e)t^=n.symbolId,t=Math.imul(t,16777619)>>>0;return`${e.length}:${t.toString(16)}`}function pb(e){return{...e,scanMs:Math.round(e.scanMs),packageRefsMs:Math.round(e.packageRefsMs),semanticRefsMs:Math.round(e.semanticRefsMs),hierarchyMs:Math.round(e.hierarchyMs)}}function FT(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function fb(e,t){if(!e.isJsxOpeningElement(t)&&!e.isJsxSelfClosingElement(t))return!1;let n=t.tagName;return e.isPropertyAccessExpression(n)?!0:e.isIdentifier(n)?/^[A-Z]/.test(n.text):!1}function NT(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}|${r.line}|${r.callsiteLine??""}`;t.has(i)||(t.add(i),n.push(r))}return n}function gb(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}import{join as _T}from"path";var ki=3,OT=2,BT="typescript-semantic";function Sb(e){let t=_T(e,BT),n=oa(t);return{...n,requestDir:n.legacyRequestDir}}function Iee(e){let t=JSON.parse(e),n=t.protocolVersion,r=n===OT;if(!r&&n!==ki||typeof t.id!="string"||typeof t.generation!="string"||typeof t.deadlineAtMs!="number"||!Number.isFinite(t.deadlineAtMs)||t.profileEnvironment!==void 0&&!jl(t.profileEnvironment)||!t.request||!$T(t.request)||!r&&(t.mailboxVersion!==Cn||typeof t.operationKey!="string"||!/^[a-f0-9]{64}$/.test(t.operationKey)||t.id!==Mr(t.operationKey)||typeof t.clientId!="string"||!t.clientId||typeof t.enqueuedAtMs!="number"||!Number.isFinite(t.enqueuedAtMs)||t.deadlineAtMs<t.enqueuedAtMs))throw new Error("TypeScript semantic service received an invalid mailbox request.");if(!r){let o=t,s=Kn("typescript-semantic-v3",{generation:o.generation,profileEnvironment:o.profileEnvironment,request:o.request});if(o.operationKey!==s)throw new Error("TypeScript semantic service received a mismatched mailbox operation identity.");return o}let i=Kn("typescript-semantic-v2",{id:t.id,generation:t.generation,request:t.request});return{protocolVersion:ki,mailboxVersion:Cn,id:t.id,operationKey:i,clientId:"legacy-v2",enqueuedAtMs:t.deadlineAtMs,deadlineAtMs:t.deadlineAtMs,generation:t.generation,...t.profileEnvironment?{profileEnvironment:t.profileEnvironment}:{},request:t.request}}function $T(e){if(!e||typeof e!="object"||!("kind"in e))return!1;let t=e;switch(t.kind){case"availability":return!0;case"import-usage":return typeof t.file=="string";case"reference-fragments":return lo(t.files)!==null;case"references":return bb(t.definitions)&&(t.exact===void 0||typeof t.exact=="boolean");case"callees":case"callee-coverage":return bb(t.definitions);case"signature":return vb(t.definition);default:return!1}}function bb(e){return Array.isArray(e)&&e.every(vb)}function vb(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.symbolId=="number"&&typeof t.documentId=="number"&&typeof t.symbol=="string"&&typeof t.relativePath=="string"&&typeof t.leaf=="string"&&typeof t.startLine=="number"&&typeof t.endLine=="number"}var UT=12e4,qT=5;function Eb(e,t,n={}){let r=n.requester??new id(e,n),i=null,o=null,s=process.env.SCIP_QUERY_SKIP_WATCH_SERVICE==="1",a=null,c=()=>(i??=hb(e,t),i),u=(f,g,h)=>(s=!0,VT(e)?g():(a=f instanceof Error?f.message:String(f),console.error(`TypeScript semantic service request failed (${a}); semantic enrichment is disabled for the rest of this run because the index is too large for an in-process compiler.`),h())),l=(f,g,h,y=h)=>{if(a!==null)return y();if(s)return h();try{return g(r.request(f))}catch(S){return Cb(S)?y():u(S,h,y)}},d=(f,g,h,y)=>{if(a!==null)return new Map;if(s)return y();let S=b=>{try{return h(r.request(g(b)))}catch(x){if(!GT(x))throw x;let v=zT(b);if(!v)throw x;return new Map([...S(v[0]),...S(v[1])])}};try{return S(f)}catch(b){return Cb(b)?new Map:u(b,y,()=>new Map)}},m=(f,g)=>d(f,h=>({kind:"references",definitions:[...h],...g?.exact?{exact:!0}:{}}),h=>rd(h),()=>c().referencesForDefinitions?.(f,g)??new Map(f.map(h=>[h.symbolId,c().referencesFor(h)]))),p=f=>d(f,g=>({kind:"callees",definitions:[...g]}),g=>rd(g),()=>c().calleesForDefinitions?.(f)??new Map(f.map(g=>[g.symbolId,c().calleesFor(g)])));return{language:"typescript",availability:()=>(o??=l({kind:"availability"},QT,()=>c().availability(),()=>({available:!1,reason:`TypeScript semantic service declined: ${a??"unknown"}`})),o),importUsage:f=>l({kind:"import-usage",file:f},g=>g,()=>c().importUsage(f),()=>[]),referencesFor:f=>m([f]).get(f.symbolId)??[],referencesForDefinitions:m,referenceFragmentsForFiles:f=>l({kind:"reference-fragments",files:[...f]},g=>XT(g),()=>c().referenceFragmentsForFiles?.(f)??new Map,()=>new Map),calleesFor:f=>p([f]).get(f.symbolId)??[],calleesForDefinitions:p,calleeCoverageForDefinitions:f=>d(f,g=>({kind:"callee-coverage",definitions:[...g]}),g=>rd(g),()=>c().calleeCoverageForDefinitions?.(f)??new Map),signatureFor:f=>l({kind:"signature",definition:f},ZT,()=>c().signatureFor(f),()=>null),dispose:()=>i?.dispose?.()}}function GT(e){let t=e instanceof Error?e.message:String(e);return/memory limit|heap out of memory|worker terminated|worker failed/iu.test(t)}function zT(e){let t=[...new Set(e.map(r=>r.relativePath))].sort();if(t.length<2)return null;let n=new Set(t.slice(0,Math.ceil(t.length/2)));return[e.filter(r=>n.has(r.relativePath)),e.filter(r=>!n.has(r.relativePath))]}function Cb(e){let t=e instanceof Error?e.message:String(e);return t.includes("invalid mailbox request")||t.includes("Unhandled TypeScript semantic request")||t.includes("compiler project is file-scoped")}var KT=2500,WT=25e3,xb=new WeakMap;function VT(e){let t=xb.get(e);if(t!==void 0)return t;let n=YT(e);return xb.set(e,n),n}function YT(e){try{let t=e.get("SELECT (SELECT count(*) FROM documents) AS documents, (SELECT count(*) FROM global_symbols) AS symbols");return!t||t.documents<KT&&t.symbols<WT}catch{return!0}}var id=class{constructor(t,n={}){this.db=t;this.runtime=n.runtime??wb,this.timeoutMs=n.timeoutMs??ek(),this.mailboxLimits=n.mailboxLimits??{},this.cacheDir=Rb(t.config.dbPath),this.projectRoot=Ol(t.config.projectRoot)}db;runtime;timeoutMs;cacheDir;projectRoot;mailboxLimits;request(t){let n=Jl(this.cacheDir),r=Sb(this.cacheDir),i=aa(n.statePath);if(!od(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript semantic service is not running.");let o=this.db.generation.identity;if(!o)throw new Error("Published TypeScript generation identity is unavailable.");let s=this.runtime.now(),a=s+this.timeoutMs,c=(this.runtime.monotonicNow??At)()+this.timeoutMs,u=rg(),l=Kn("typescript-semantic-v3",{generation:o,profileEnvironment:u,request:t}),d=Mr(l),m=sa(r,{mailboxVersion:Cn,operationKey:l,clientId:this.runtime.randomId(),enqueuedAtMs:s,deadlineAtMs:a,protocolVersion:ki,id:d,generation:o,profileEnvironment:u,request:t},{nowMs:s,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??At)()<=c;){if(HT(m.responsePath))return JT(It(m.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript semantic mailbox response"}),d,o,l);let p=aa(n.statePath);if(!od(p,this.projectRoot,this.runtime))throw new Error("TypeScript semantic service stopped while processing a request.");this.runtime.sleep(qT)}throw new Error(`TypeScript semantic service timed out after ${this.timeoutMs}ms.`)}};function Ib(e){if(process.env.SCIP_QUERY_SKIP_WATCH_SERVICE==="1")return!1;try{let t=aa(Jl(Rb(e.config.dbPath)).statePath);return od(t,Ol(e.config.projectRoot),wb)}catch{return!1}}function od(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null;return e!==null&&e.projectRoot===t&&e.typescriptSemantic?.protocolVersion===ki&&n.isProcessAlive(e.pid)&&(!e.processIdentity||r!=null&&ia(e.processIdentity,r))}function JT(e,t,n,r){let i=JSON.parse(e);if(i.protocolVersion!==ki||i.id!==t||i.operationKey!==r||i.ok===!0&&i.generation!==n)throw new Error("TypeScript semantic service wrote an incompatible response.");if(i.ok===!0)return i.response;throw new Error(typeof i.error=="string"?i.error:"TypeScript semantic service request failed.")}function rd(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid numeric map.");return new Map(e)}function XT(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid string map.");return new Map(e)}function QT(e){let t=Vy(e);if(!t)throw new Error("TypeScript semantic service wrote invalid availability.");return t}function ZT(e){if(e!==null&&typeof e!="string")throw new Error("TypeScript semantic service wrote an invalid signature.");return e}function ek(){let e=Number(process.env.SCIP_TYPESCRIPT_SEMANTIC_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:UT}var wb={now:Date.now,monotonicNow:At,randomId:jT,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:bi,readProcessIdentity:Si};var Lb=new Ba;Vf({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>Lb.clear(e)});function In(e,t){let n=Ae(t)??"typescript";return Lb.getOrCreate(e,n,()=>n==="rust"?Gy(e.config.projectRoot,{sourceImportUsageResolver:{importUsageFacts:r=>ay(e,r)},calleeSymbolResolver:sy(e),sourceZeroCalleeOracle:r=>tk(e,r),scipOccurrenceCalleeOracle:r=>Wy(e,r)}):Eb(e,t))}function Ae(e){return e?ae(e)==="rust"?"rust":Wn(e)?"typescript":null:"typescript"}function tk(e,t){let n=W(e,t.relativePath);if(!n||n.language!=="rust")return!1;let r=n.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine&&i.name===t.leaf)??n.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine);return r?!n.callSites.some(i=>i.line>=r.startLine&&i.line<=r.endLine):!1}import{resolve as ck}from"path";var nk=/^[A-Za-z_][A-Za-z0-9_]*$/,Pb=/\bDefault::default\b/g,rk=/^\.\.\s*Default::default\b/;function Db(e,t){let n=new Map,r=new Map;for(let i of t){let o=sd(e,i,r);o!==null&&n.set(i.symbolId,o)}return n}function sd(e,t,n=new Map){let r=ok(t.symbol);if(!r)return null;let i=ea(e,[t.symbolId]);if(i.length===0)return null;let o=new RegExp(`(^|[^A-Za-z0-9_])${Ie(r)}::default\\b`,"g"),s=new RegExp(`(^|[^A-Za-z0-9_])${Ie(r)}\\s*$`),a=ik(e,t.symbolId),c=[];for(let u of i){let l=sk(e,u.relative_path,n);if(l===null)return null;let d=l.split(/\r?\n/),m=0,p=[],f=0;for(let g=u.chunk_start;g<=u.chunk_end&&g<d.length;g+=1){let y=d[g]??"",S=new Set;o.lastIndex=0;let b;for(;b=o.exec(y);)c.push({file:u.relative_path,line:g,column:b.index+b[1].length+r.length+2}),f+=1;for(let x=0;x<y.length;x+=1){let v=rk.exec(y.slice(x));if(v){if(a&&p.includes(m)){let R=x+v[0].lastIndexOf("default");c.push({file:u.relative_path,line:g,column:R}),S.add(R),f+=1}x+=v[0].length-1;continue}let C=y[x];if(C==="{"){let R=s.test(y.slice(0,x));m+=1,R&&p.push(m);continue}if(C==="}")for(m=Math.max(0,m-1);p.length>0&&p[p.length-1]>m;)p.pop()}for(Pb.lastIndex=0;b=Pb.exec(y);){let x=b.index+9;if(!S.has(x))return null}}if(f===0)return null}return Ta(c)}function ik(e,t){return e.get("SELECT 1 AS present FROM mentions WHERE symbol_id = ? AND role = 1 LIMIT 1",t)?.present===1}function ok(e){let t=/impl#\[([^\]]+)\]\[Default\]default\(\)\./.exec(e)?.[1]??null;return!t||!nk.test(t)?null:t}function sk(e,t,n){if(n.has(t))return n.get(t)??null;let r=e.get("SELECT text FROM documents WHERE relative_path = ?",t),i=typeof r?.text=="string"?r.text:ak(e,t);return n.set(t,i),i}function ak(e,t){try{return ve(e.config.projectRoot,t,{inputKind:"indexed Rust source file"})}catch(n){if(!Ce(n))throw n;return null}}var lk="typescript-import-usage-v1",uk="typescript-signatures-v1",ad=te("semantic-prefetched-callees",{clearGroups:["whole-project","source-file","semantic-provider"]}),Mb=Er({kind:"semantic-import-usage",invalidation:Ne("semantic-import-usage"),serialize:e=>JSON.stringify(e),deserialize:zb}),Tb=Er({kind:"semantic-signatures",invalidation:Ne("semantic-signatures"),serialize:e=>JSON.stringify(e),deserialize:Rk}),kb=ft({kind:"typescript-import-usage",invalidation:Ne("typescript-import-usage"),serialize:e=>JSON.stringify(e),deserialize:zb}),Ab=ft({kind:"typescript-signatures",invalidation:Ne("typescript-signatures"),serialize:e=>JSON.stringify(e),deserialize:Ek}),dk=256;function Nb(e,t={}){let n=t.coldFragmentLimit??dk,r=Ug(e);return r===null||r.missing<=n?{ready:!0}:(t.serviceAvailable??Ib)(e)?{ready:!0}:{ready:!1,reason:`TypeScript reference fragments are cold for ${r.missing} of ${r.files} files and no watch service is running; run \`scip-query health --full\` once or start the service with \`scip-query watch --daemon\`, then re-run this command.`}}var mk=te("typescript-reference-map",{clearGroups:["whole-project"]});function pk(e){return mk.get(e,()=>{let t=pt(e);if(!t)return null;let n=ye(e).filter(i=>Ae(i.relativePath)==="typescript"),r=Ql(e,n,i=>In(e,i));return r?{projectFingerprint:t,references:r.references,files:r.files,cacheHits:r.cacheHits,cacheMisses:r.cacheMisses,computedFiles:r.computedFiles}:null})}function st(e){let t=new Map,n=new Set;return{capability:(r,i)=>Kb(e,r,i),importUsage:r=>gk(e,r),references:r=>Ob(e,r),materializeReferences:(r,i)=>$b(e,r,t,n,i),callerMap:r=>hk(e,r,t,n),calleeMap:r=>Sk(e,r),signature:r=>Ck(e,r)}}function fk(e,t){if(t.size===0)return;let n=ad.get(e,()=>new Map);for(let[r,i]of t)n.set(r,[...i])}function _b(e,t){if(!ad.has(e))return{hits:[],misses:[...t]};let n=ad.get(e,()=>new Map),r=[],i=[];for(let o of t)n.has(o.symbolId)?r.push({definition:o,callees:n.get(o.symbolId)??[]}):i.push(o);return{hits:r,misses:i}}function Uo(e,t){return st(e).importUsage(t)}function gk(e,t){if(Ae(t)==="typescript"){let o="fallback",s=0,a=0,c=0,u=0;return N("typescript.import-usage.materialize",()=>{let l=ho(e,t,lk);if(l?.key){s=1;let m=kb.read(e,t,l.key);if(m)return o="hit",a=1,m;c=1;let p=qt(e,t);if(!p)return o="unavailable",[];let f=p.importUsage(t);return kb.write(e,t,l.key,f),o="computed",f}u=1;let d=qt(e,t);return d?(o="direct-fallback",d.importUsage(t)):(o="unavailable",[])},()=>({state:o,eligible:s,cacheHits:a,cacheMisses:c,fallbacks:u}))}let n=Gb(e,"semantic-import-usage",t);if(n){let o=Mb.read(e,t,n);if(o)return o}let r=qt(e,t);if(!r)return[];let i=r.importUsage(t);return n&&Mb.write(e,t,n,i),i}function Ha(e,t){return st(e).references(t)}function Ob(e,t){let n=sd(e,t);if(n)return n;let r=uy(e,t);if(r)return r;let i=qt(e,t.relativePath);return i?i.referencesFor(t):[]}function er(e,t){return st(e).callerMap(t)}function Bb(e,t){let n=new Map,r=[];for(let i of t){if(Ae(i.relativePath)==="typescript"){r.push(i);continue}cd(e,n,i,Ob(e,i))}if(r.length>0){let o=Ql(e,r,s=>In(e,s))?.references;if(!o){let s=qt(e,r[0].relativePath);o=s?s.referencesForDefinitions?s.referencesForDefinitions(r,{exact:!0}):new Map(r.map(a=>[a.symbolId,s.referencesFor(a)])):new Map,s&&xe()&&Xl(e,r,o,a=>In(e,a))}for(let s of r)cd(e,n,s,o.get(s.symbolId)??[])}return n}function hk(e,t,n=new Map,r=new Set){let i=new Map,o=$b(e,t,n,r),s=0;return N("semantic.callers.from-references",()=>{for(let a of t)s+=cd(e,i,a,n.get(a.symbolId)??[])},()=>({definitions:t.length,materialized:o.definitions,inMemoryHits:o.inMemoryHits,incompleteInMemoryHits:o.incompleteInMemoryHits,resultRows:i.size,callerFiles:s})),i}function $b(e,t,n,r,i={}){let o=pt(e),s=[],a=[],c=[],u=0,l=0,d=0,m=0,p=0,f=0,g=0,h=0,y=0,S=0,b=0,x=0,v=[],C=new Map,R=t.filter(w=>Ae(w.relativePath)==="typescript"&&!n.has(w.symbolId)&&!r.has(w.symbolId)),E=R.length>0?pk(e):null;if(E){y=R.length,S=E.cacheHits,b=E.cacheMisses,x=E.computedFiles;for(let w of R)n.set(w.symbolId,E.references.get(w.symbolId)??[])}if(N("semantic.references.cache-scan",()=>{for(let[w,I]of Pa(t)){let k=[];for(let P of I)n.has(P.symbolId)?l+=1:r.has(P.symbolId)?h+=1:k.push(P);if(k.length===0){g+=1;continue}let D=yk(e,o,w);if(!D){for(let P of k)Ae(P.relativePath)||(u+=1),c.push(P);continue}f+=1;let F=Xf(e,w,D);for(let P of k){let A=F.get(P.symbol)??null;if(A!==null){let L=bk(A);if(L){d+=1,n.set(P.symbolId,L);continue}m+=1}a.push({definition:P,cacheFingerprint:D})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:u,cacheHits:d,parseFailures:m,misses:a.length,unkeyed:c.length,inMemoryHits:l,incompleteInMemoryHits:h,fullyInMemoryFiles:g,cacheReadFiles:f})),a.length>0||c.length>0){v=[...c,...a.map(w=>w.definition)],C=N("semantic.references.compute-misses",()=>{let w=ld(e,v,i);return p=w.size,w},()=>({definitions:v.length,misses:a.length,unkeyed:c.length,rows:p}));for(let w of v)C.has(w.symbolId)?(n.set(w.symbolId,C.get(w.symbolId)??[]),r.delete(w.symbolId)):r.add(w.symbolId);for(let{definition:w,cacheFingerprint:I}of a)C.has(w.symbolId)&&Kb(e,"semantic-references",w.relativePath).available&&s.push({relativePath:w.relativePath,symbol:w.symbol,projectFingerprint:I,payload:JSON.stringify(C.get(w.symbolId)??[])})}return s.length>0&&N("semantic.references.cache-write",()=>Qf(e,s),()=>({entries:s.length})),C.size>0&&Xl(e,v,C,w=>In(e,w)),{definitions:t.length,inMemoryHits:l,incompleteInMemoryHits:h,cacheHits:d,misses:a.length,unkeyed:c.length,skippedUnsupportedLanguage:u,parseFailures:m,computed:p,incomplete:r.size,cacheWrites:s.length,fragmentDefinitions:y,fragmentCacheHits:S,fragmentCacheMisses:b,fragmentComputedFiles:x}}function yk(e,t,n){if(!t)return null;let r=Ae(n);return r==="typescript"?t:r==="rust"?Yt(JSON.stringify({kind:"semantic-references",language:r,engine:Nr(e.config.projectRoot),projectFingerprint:t})):null}function ld(e,t,n={}){let r=xe(),i=new Map,o=0,s=0,a=0,c=0,u=0,l=0,d=0,m=0,p=0;return N("semantic.references.provider-loop",()=>{let f=Db(e,t),g=ly(e,t),h=new Map,y=n.prefetchCallees?new Map:null,S=[];for(let x of t){let v,C=()=>(v??=qt(e,x.relativePath),v);if(y){let I=C();if(I?.referencesAndCalleesForDefinitions){let k=y.get(I);k?k.push(x):y.set(I,[x]),p+=1}}let R=f.get(x.symbolId);if(R){a+=1,c+=R.length,Ho(i,x.symbolId,R,r,I=>{d+=1,m+=I});continue}let E=g.get(x.symbolId);if(E){u+=1,l+=E.length,Ho(i,x.symbolId,E,r,I=>{d+=1,m+=I});continue}let w=C();if(!w){r&&(s+=1);continue}if(r&&(o+=1),w.referencesForDefinitions){let I=h.get(w);I?I.push(x):h.set(w,[x])}else S.push({provider:w,definition:x})}let b=new Set;if(y)for(let[x,v]of y){if(!x.referencesAndCalleesForDefinitions)continue;let C=h.get(x)??[],R=x.referencesAndCalleesForDefinitions(C,v);b.add(x),fk(e,R.callees);for(let E of C){if(!R.references.has(E.symbolId))continue;let w=R.references.get(E.symbolId)??[];Ho(i,E.symbolId,w,r,I=>{d+=1,m+=I})}}for(let[x,v]of h){if(b.has(x))continue;let C=x.referencesForDefinitions(v);for(let R of v){if(!C.has(R.symbolId))continue;let E=C.get(R.symbolId)??[];Ho(i,R.symbolId,E,r,w=>{d+=1,m+=w})}}for(let{provider:x,definition:v}of S){let C=x.referencesFor(v);Ho(i,v.symbolId,C,r,R=>{d+=1,m+=R})}return i},()=>({definitions:t.length,providerHits:o,providerMisses:s,rustDefaultFastPathRows:a,rustDefaultFastPathReferences:c,rustScipOccurrenceFastPathRows:u,rustScipOccurrenceFastPathReferences:l,prefetchCalleeDefinitions:p,definitionsWithReferences:d,referenceCount:m,rows:i.size}))}function Ho(e,t,n,r,i){e.set(t,n),r&&n.length>0&&i(n.length)}function cd(e,t,n,r){let i=0;for(let o of r){if(o.file===n.relativePath||e.isIgnored(o.file))continue;let s=t.get(n.symbolId);s||(s=new Set,t.set(n.symbolId,s));let a=s.size;s.add(o.file),s.size!==a&&(i+=1)}return i}function bk(e){try{return JSON.parse(e)}catch{return null}}function Ua(e,t){return st(e).calleeMap(t)}function jb(e){let t=vi();if(!t)return null;let n=ja(e);if(n.length===0)return null;let r=new Map;return n.forEach((i,o)=>{for(let s of jg(t,[i]))r.has(s)||r.set(s,o)}),i=>r.get(ck(e.config.projectRoot,i))??null}function Hb(e,t){let n=new Map,r=new Map;for(let i of t){let o=qt(e,i.relativePath);if(!o?.calleeCoverageForDefinitions)continue;let s=r.get(o);s?s.push(i):r.set(o,[i])}for(let[i,o]of r)for(let s of Ub(o))for(let[a,c]of i.calleeCoverageForDefinitions(s))n.set(a,c);return n}function Sk(e,t){let n=xe(),r=new Map,i=0,o=0,s=0,a=0;return N("semantic.callees.provider-loop",()=>{let c=new Map,u=[];for(let l of t){let d=qt(e,l.relativePath);if(!d){n&&(o+=1);continue}n&&(i+=1);let m=l;if(d.calleesForDefinitions){let p=c.get(d);p?p.push(m):c.set(d,[m])}else u.push({provider:d,definition:m})}for(let[l,d]of c)for(let m of Ub(d)){let p=l.calleesForDefinitions(m);for(let f of m){let g=p.get(f.symbolId)??[];Fb(r,f.symbolId,g,n,h=>{s+=1,a+=h})}}for(let{provider:l,definition:d}of u){let m=l.calleesFor(d);Fb(r,d.symbolId,m,n,p=>{s+=1,a+=p})}return r},()=>({definitions:t.length,providerHits:i,providerMisses:o,definitionsWithCallees:s,calleeCount:a,rows:r.size}))}var vk=256;function Ub(e){let t=new Map;for(let i of e){let o=t.get(i.relativePath);o?o.push(i):t.set(i.relativePath,[i])}let n=[],r=[];for(let i of t.values())r.length>0&&r.length+i.length>vk&&(n.push(r),r=[]),r.push(...i);return r.length>0&&n.push(r),n}function Fb(e,t,n,r,i){n.length>0&&(e.set(t,n),r&&i(n.length))}function qb(e,t){return st(e).signature(t)}function Ck(e,t){if(Ae(t.relativePath)==="typescript"){let s="fallback",a=0,c=0,u=0,l=0;return N("typescript.signature.materialize",()=>{let d=ho(e,t.relativePath,uk);if(d?.key){a=1;let p=Ab.read(e,t.relativePath,d.key)??{};if(Object.prototype.hasOwnProperty.call(p,t.symbol))return s="hit",c=1,p[t.symbol]??null;u=1;let f=qt(e,t.relativePath);if(!f)return s="unavailable",null;let g=f.signatureFor(t);return Ab.write(e,t.relativePath,d.key,{...p,[t.symbol]:g}),s="computed",g}l=1;let m=qt(e,t.relativePath);return m?(s="direct-fallback",m.signatureFor(t)):(s="unavailable",null)},()=>({state:s,eligible:a,cacheHits:c,cacheMisses:u,fallbacks:l}))}let n=Gb(e,"semantic-signatures",t.relativePath),r=xk(t);if(n){let s=Tb.read(e,r,n);if(s)return s.signature}let i=qt(e,t.relativePath);if(!i)return null;let o=i.signatureFor(t);return n&&Tb.write(e,r,n,{signature:o}),o}function Gb(e,t,n){let r=pt(e);if(!r)return null;let i=Ae(n);return i!=="rust"?null:Yt(JSON.stringify({kind:t,language:i,engine:Nr(e.config.projectRoot),projectFingerprint:r}))}function xk(e){return`${e.relativePath}\0${e.symbol}`}function zb(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:null}catch{return null}}function Rk(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 Ek(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 Kb(e,t,n){let r=Ae(n);if(!r)return{slot:t,language:"typescript",available:!1,reason:"semantic evidence is only available for TypeScript or Rust files"};try{return{slot:t,language:r,...In(e,n).availability()}}catch(i){return{slot:t,language:r,available:!1,reason:i instanceof Error?i.message:String(i)}}}function qt(e,t){if(!Ae(t))return null;let n=In(e,t);return n.availability().available?n:null}var ie={references:Ha,referenceMap:ld,callerMap:(e,t)=>st(e).callerMap(t),calleeMap:ud};function ud(e,t){let n=xe(),r=new Map,i=_b(e,t),o=[],s=[],a=0,c=0,u=0,l=0,d=0,m=0,p=0;for(let{definition:b,callees:x}of i.hits)d+=1,x.length>0&&(m+=1,p+=x.length,r.set(b.symbolId,x));let f=Ik(e,i.hits);if(f.entries.length>0&&N("semantic.callees.prefetch-cache-write",()=>Ul(e,f.entries),()=>({entries:f.entries.length,sourceMissing:f.sourceMissing,skippedUnsupportedLanguage:f.skippedUnsupportedLanguage})),N("semantic.callees.cache-scan",()=>{for(let[b,x]of Pa(i.misses)){if(!Ae(b)){n&&(a+=x.length);continue}let v=V(e,b);if(!v){n&&(c+=x.length),s.push(...x);continue}let C=Pt(e,b,v),R=Wb(e,b);if(!R){s.push(...x);continue}let E=Jf(e,b,C,R);for(let w of x){let I=E.get(w.symbol)??null;if(I!==null){let k=Lk(I);if(k){n&&(u+=1),k.length>0&&r.set(w.symbolId,k);continue}n&&(l+=1)}o.push({def:w,contentHash:C,depsDigest:R})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:a,sourceMissing:c,cacheHits:u,parseFailures:l,misses:o.length,unkeyed:s.length,inMemoryHits:d,inMemoryRows:m,inMemoryCalleeCount:p,resultRows:r.size,missSample:o.slice(0,8).map(b=>`${b.def.relativePath}#${b.def.symbol}`),unkeyedSample:s.slice(0,4).map(b=>`${b.relativePath}#${b.symbol}`)})),o.length===0&&s.length===0)return r;let g=[...s,...o.map(b=>b.def)],h=0,y=N("semantic.callees.compute-misses",()=>{let b=Ua(e,g);return h=b.size,b},()=>({definitions:g.length,misses:o.length,unkeyed:s.length,rows:h}));for(let[b,x]of y)r.set(b,x);let S=o.filter(b=>st(e).capability("semantic-callees",b.def.relativePath).available).map(b=>({relativePath:b.def.relativePath,symbol:b.def.symbol,contentHash:b.contentHash,depsDigest:b.depsDigest,payload:JSON.stringify(y.get(b.def.symbolId)??[])}));return S.length>0?N("semantic.callees.cache-write",()=>Ul(e,S),()=>({entries:S.length})):N("semantic.callees.cache-write-skip",()=>{},()=>({reason:"provider-unavailable",misses:o.length})),r}function Ik(e,t){let n=[],r=new Map,i=0,o=0;for(let{definition:s,callees:a}of t){if(!Ae(s.relativePath)){o+=1;continue}if(!r.has(s.relativePath)){let u=V(e,s.relativePath),l=u?Wb(e,s.relativePath):null;r.set(s.relativePath,u&&l?{contentHash:Pt(e,s.relativePath,u),depsDigest:l}:null)}let c=r.get(s.relativePath);if(!c){i+=1;continue}n.push({relativePath:s.relativePath,symbol:s.symbol,contentHash:c.contentHash,depsDigest:c.depsDigest,payload:JSON.stringify(a)})}return{entries:n,sourceMissing:i,skippedUnsupportedLanguage:o}}var wk="typescript-callees-v3-alias-resolved";function Wb(e,t){let n=Ae(t);if(n==="typescript")return ho(e,t,wk)?.key??null;let r=Dk(e,t);return n==="rust"?Yt(JSON.stringify({kind:"semantic-callees",language:n,engine:Nr(e.config.projectRoot),positionMapping:"nearby-leaf-v2-callsite-line",depsDigest:r})):r}function Lk(e){try{return JSON.parse(e)}catch{return null}}var Pk=Vt("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function Dk(e,t){return Pk.get(e,t,()=>{let r=[..._e(e).get(t)??[]].sort().map(i=>`${i}:${Pt(e,i,V(e,i))}`);return Yt(r.join("|"))})}function Bte(e,t,n={}){let r=re(e,t);if(!r)return[];let o=!Re(r.symbol)&&!e.isIgnored(r.relativePath)?[{relativePath:r.relativePath,line:r.startLine}]:[],s=zn(e,r,{semantic:n.semantic,semanticEvidence:ie}).map(l=>({relativePath:l.file,line:l.line})),a=Mk(e,r),c=new Set,u=[];for(let l of[...o,...s,...a]){let d=`${l.relativePath}:${l.line}`;c.has(d)||(c.add(d),u.push(l))}return u}function Mk(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=Tk(t.symbol);if(n.length===0)return[];let r=[];for(let i of Q(e,{extensions:[".rb"],includeIgnored:!1})){let o=V(e,i);if(!o)continue;let s=o.split(`
52
- `);for(let a=0;a<s.length;a++){let c=s[a]??"";n.some(u=>new RegExp(`@${u}\\b|\\b${u}:`).test(c))&&r.push({relativePath:i,line:a})}}return r}function Tk(e){let n=(e.split(":").pop()??e).replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),r=n.split("_").filter(Boolean),i=new Set;return n&&i.add(n),r.length>=1&&i.add(r[r.length-1]),r.length>=2&&i.add(r.slice(-2).join("_")),[...i]}import{existsSync as Rd,statSync as uF}from"fs";import{join as dF}from"path";import{existsSync as Fi}from"fs";import{randomUUID as dS}from"crypto";import{isAbsolute as pA,join as Ln,relative as fA,resolve as gA}from"path";var tr=1,nr=2,kk="./node_modules/scip-query/docs/schemas/project-config.schema.json";function dd(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(a){return{kind:"malformed",reason:`invalid JSON: ${a instanceof Error?a.message:String(a)}`}}if(!Z(t))return{kind:"malformed",reason:"project config must be a JSON object"};let n=t.schemaVersion;if(n!==void 0&&!Number.isInteger(n))return{kind:"malformed",reason:"schemaVersion must be an integer"};let r=n===void 0?tr:n;if(r!==tr&&r!==nr)return{kind:"unsupported",schemaVersion:r,direction:r<tr?"older":"future"};let i=t.$schema;if(i!==void 0&&(typeof i!="string"||i.trim()===""))return{kind:"malformed",reason:"$schema must be a non-empty string when present"};let o=qa(t),s=r!==nr||typeof t.$schema!="string";return r===tr?{kind:"legacy",sourceVersion:tr,config:o,needsMigration:s}:{kind:"supported",sourceVersion:nr,config:o,needsMigration:s}}function qa(e){let t=e,{$schema:n,schemaVersion:r,...i}=t;return{$schema:typeof n=="string"&&n.trim()!==""?n:kk,schemaVersion:nr,...i}}function Ai(e){return`${JSON.stringify(qa(e),null,2)}
53
- `}import{createHash as Ak}from"crypto";var nn=1,ir=2,Qb=1,gd=1,fd="sha256",Fk=1;function $r(e,t,n){if(!jt(e)||!Us(t))throw new Error("Observation identity requires a bounded projection name and positive projection version.");return{schemaVersion:Qb,canonicalizationVersion:gd,hashAlgorithm:fd,projection:{name:e,version:t},digest:Ak(fd).update(Nk(e,t,n)).digest("hex")}}function Nk(e,t,n){return`{"canonicalizationVersion":${gd},"projection":${JSON.stringify(e)},"projectionVersion":${t},"value":${JSON.stringify(n)}}`}function _k(e){if(!Z(e))return{kind:"malformed",reason:"observation receipt must be an object"};let t=e.schemaVersion;if(!Number.isInteger(t))return{kind:"malformed",reason:"observation receipt schemaVersion must be an integer"};if(t===nn)return qk(e)?{kind:"legacy",schemaVersion:nn,receipt:e}:{kind:"malformed",reason:"observation receipt v1 fields are malformed or contradictory"};if(t===ir)return Gk(e)?{kind:"supported",schemaVersion:ir,receipt:e}:{kind:"malformed",reason:"observation receipt v2 facts are malformed or contradictory"};let n=t;return{kind:"unsupported",schemaVersion:n,direction:n<nn?"older":"future"}}function Ga(e){let t=_k(e);return t.kind==="legacy"||t.kind==="supported"}function Ok(e,t){return{collaborationDomain:Br(tn(e,n=>n.facts.collaborationDomain),tn(t,n=>n.facts.collaborationDomain)),repositoryLineage:Br(tn(e,n=>n.facts.repositoryLineage),tn(t,n=>n.facts.repositoryLineage)),workspaceInstance:Br(tn(e,n=>n.facts.workspaceInstance),tn(t,n=>n.facts.workspaceInstance)),wholeContent:Br(tn(e,n=>n.facts.wholeContent),tn(t,n=>n.facts.wholeContent)),relevantInputs:Bk(e,t),indexInput:Br(tn(e,n=>n.facts.index?.inputs),tn(t,n=>n.facts.index?.inputs)),indexGeneration:$k(e,t),observationStability:Hk(e,t)}}function Gte(e,t,n=Ok(e,t)){let r=[["collaborationDomain",n.collaborationDomain],["wholeContent",n.wholeContent],["observationStability",n.observationStability]],i=[];for(let[s,a]of r)a.state!=="established"&&i.push(`${s}:${a.state}`);for(let[s,a]of[["left",e],["right",t]]){let c=Uk(a);c!=="not-applicable"&&c!=="established"&&i.push(`${s}IndexAlignment:${c}`)}let o=r.some(([,s])=>s.state==="disproven")||i.some(s=>s.endsWith(":disproven"));return{policyVersion:Fk,authority:i.length===0?"completion":o?"none":"advisory",requiredRelationships:["collaborationDomain","wholeContent","observationStability"],reasons:i}}function Bk(e,t){let n=Vb(e),r=Vb(t);return[...new Set([...n.keys(),...r.keys()])].sort().map(o=>{let s=n.get(o),a=r.get(o),c=s?.subject??a?.subject??o,u=s?.identity.projection.name??a?.identity.projection.name??o;return{subject:c,projection:u,judgment:Br(s?.identity,a?.identity)}})}function Vb(e){return e.schemaVersion!==ir?new Map:new Map((e.facts.relevantInputs??[]).map(t=>[`${t.subject}\0${t.identity.projection.name}`,t]))}function $k(e,t){return e.schemaVersion===nn&&t.schemaVersion===nn?jk(e.index?.generationIdentity,t.index?.generationIdentity):e.schemaVersion===nn||t.schemaVersion===nn?wn("unknown",["legacy-fact-not-comparable"],Jb(e),Jb(t)):Br(e.facts.index?.generation,t.facts.index?.generation)}function jk(e,t){let n=e?[{kind:"legacy-index-generation",value:e}]:[],r=t?[{kind:"legacy-index-generation",value:t}]:[];return e===void 0||t===void 0?Zb(n,r):wn(e===t?"established":"disproven",[e===t?"identities-equal":"identities-different"],n,r)}function Br(e,t){let n=e?[{kind:"identity",identity:e}]:[],r=t?[{kind:"identity",identity:t}]:[];return!e||!t?Zb(n,r):hd(e,t)?wn(e.digest===t.digest?"established":"disproven",[e.digest===t.digest?"identities-equal":"identities-different"],n,r):wn("unknown",["identity-projections-not-comparable"],n,r)}function Hk(e,t){if(e.schemaVersion===nn||t.schemaVersion===nn)return wn("unknown",["legacy-fact-not-comparable"],[],[]);let n=Xb(e),r=Xb(t),i=Yb(e),o=Yb(t);return i==="invalidated"||o==="invalidated"?wn("disproven",[...i==="invalidated"?["left-observation-invalidated"]:[],...o==="invalidated"?["right-observation-invalidated"]:[]],n,r):i!=="fixed"||o!=="fixed"?wn("unknown",[...i==="no-repository-source"?["left-observation-has-no-repository-source"]:i!=="fixed"?["left-observation-not-fixed"]:[],...o==="no-repository-source"?["right-observation-has-no-repository-source"]:o!=="fixed"?["right-observation-not-fixed"]:[]],n,r):wn("established",["all-observed-sources-fixed"],n,r)}function Yb(e){let t=e.observedSources.filter(r=>r.kind!=="process");if(t.length===0)return"no-repository-source";let n=new Map(e.stabilityProofs.map(r=>[r.source,r.kind]));return t.some(r=>n.get(r.kind)==="invalidated")?"invalidated":t.every(r=>{let i=n.get(r.kind);return i==="immutable"||i==="fixed-snapshot"})?"fixed":"unknown"}function Uk(e){if(e.schemaVersion!==ir)return e.index?"unknown":"not-applicable";if(!e.observedSources.some(r=>r.kind==="index-generation"))return"not-applicable";let t=e.facts.index?.inputs;if(!t)return"unknown";let n=(e.facts.relevantInputs??[]).find(r=>hd(r.identity,t))?.identity;return n?n.digest===t.digest?"established":"disproven":"unknown"}function tn(e,t){return e.schemaVersion===ir?t(e):void 0}function Jb(e){return e.schemaVersion===nn&&e.index?[{kind:"legacy-index-generation",value:e.index.generationIdentity}]:e.schemaVersion===ir&&e.facts.index?[{kind:"identity",identity:e.facts.index.generation}]:[]}function Xb(e){return e.stabilityProofs.map(t=>({kind:"stability",proof:t}))}function Zb(e,t){let n=e.length===0&&t.length===0?"both-facts-missing":e.length===0?"left-fact-missing":"right-fact-missing";return wn("unknown",[n],e,t)}function wn(e,t,n,r){return{state:e,reasons:t,facts:{left:n,right:r}}}function hd(e,t){return e.schemaVersion===t.schemaVersion&&e.canonicalizationVersion===t.canonicalizationVersion&&e.hashAlgorithm===t.hashAlgorithm&&e.projection.name===t.projection.name&&e.projection.version===t.projection.version}function qk(e){if(!Z(e))return!1;let t=e.index,n=e.worktree;return tS(e.observedAt)&&jt(e.projectIdentity)&&Xk(e.authorityKind)&&(t===void 0||Z(t)&&jt(t.generationIdentity)&&(t.source==="immutable"||t.source==="legacy")&&(t.alignment==="not-certified"||t.alignment==="leased"))&&(n===void 0||Z(n)&&jt(n.identity)&&typeof n.clean=="boolean"&&(n.headCommit===void 0||jt(n.headCommit))&&(n.treeOid===void 0||jt(n.treeOid)))&&Jk(e.authorityKind,t,n)}function Gk(e){if(!Z(e))return!1;let t=e.facts,n=e.observedSources,r=e.stabilityProofs;if(!tS(e.observedAt)||!Z(t)||!Array.isArray(n)||n.length===0||!n.every(Kk)||!pd(n,c=>c.kind)||!Array.isArray(r)||!r.every(Wk)||!pd(r,c=>c.source)||r.some(c=>!n.some(u=>u.kind===c.source))||!r.every(c=>Yk(c,t))||["collaborationDomain","repositoryLineage","workspaceInstance","wholeContent"].some(c=>t[c]!==void 0&&!rr(t[c])))return!1;let o=t.relevantInputs;if(o!==void 0&&(!Array.isArray(o)||!o.every(zk)||!pd(o,c=>`${c.subject}\0${c.identity.projection.name}`)))return!1;let s=t.index;if(s!==void 0&&(!Z(s)||!rr(s.generation)||s.inputs!==void 0&&!rr(s.inputs)||s.source!=="immutable"&&s.source!=="legacy"))return!1;let a=e.diagnostics;return(a===void 0||Z(a)&&(a.clean===void 0||typeof a.clean=="boolean")&&(a.headCommit===void 0||jt(a.headCommit))&&(a.treeOid===void 0||jt(a.treeOid)))&&Vk(t,n)}function rr(e){return!Z(e)||!Z(e.projection)?!1:e.schemaVersion===Qb&&e.canonicalizationVersion===gd&&e.hashAlgorithm===fd&&jt(e.projection.name)&&Us(e.projection.version)&&ci(e.digest)}function zk(e){return Z(e)&&jt(e.subject)&&rr(e.identity)}function Kk(e){return Z(e)&&eS(e.kind)&&(e.identity===void 0||rr(e.identity))}function Wk(e){return Z(e)&&eS(e.source)&&(e.kind==="immutable"||e.kind==="fixed-snapshot"||e.kind==="bracketed"||e.kind==="not-established"||e.kind==="invalidated")}function Vk(e,t){let n=e.index,r=t.find(c=>c.kind==="index-generation");if(r){if(!Z(n)||!rr(n.generation)||r.identity&&!md(r.identity,n.generation))return!1}else if(n!==void 0)return!1;let i=e.workspaceInstance,o=t.find(c=>c.kind==="live-workspace");if(o?.identity&&(!rr(i)||!md(o.identity,i)))return!1;let s=e.wholeContent,a=t.find(c=>c.kind==="repository-snapshot");return!(a?.identity&&(!rr(s)||!md(a.identity,s)))}function Yk(e,t){return e.kind==="not-established"||e.kind==="invalidated"?!0:e.source==="index-generation"?e.kind==="immutable"&&Z(t.index)&&t.index.source==="immutable":e.source==="repository-snapshot"?e.kind==="fixed-snapshot":e.source==="live-workspace"?e.kind==="bracketed":!1}function md(e,t){return hd(e,t)&&e.digest===t.digest}function Jk(e,t,n){return e==="index-worktree"?t!==void 0&&n!==void 0:e==="index-only"?t!==void 0&&n===void 0:e==="worktree-only"?t===void 0&&n!==void 0:e==="process-local"&&t===void 0&&n===void 0}function Xk(e){return e==="index-worktree"||e==="index-only"||e==="worktree-only"||e==="process-local"}function eS(e){return e==="index-generation"||e==="repository-snapshot"||e==="live-workspace"||e==="process"}function tS(e){return typeof e=="string"&&!Number.isNaN(Date.parse(e))}function pd(e,t){return new Set(e.map(t)).size===e.length}function za(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.kind==="automated-adjudication"&&t.policyVersion===1&&(t.decidedBy==="agent"||t.decidedBy==="human")&&Wf.includes(t.reasonCode)&&Array.isArray(t.evidence)&&t.evidence.length>0&&t.evidence.every(Qk)&&(t.observation===void 0||Ga(t.observation))&&!!t.invalidateOn&&typeof t.invalidateOn=="object"&&typeof t.invalidateOn.targetContentChange=="boolean"&&typeof t.invalidateOn.detectorMajorChange=="boolean"}function Qk(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return(t.kind==="source"||t.kind==="config"||t.kind==="test"||t.kind==="graph")&&typeof t.referent=="string"&&t.referent.trim()!==""&&typeof t.claim=="string"&&t.claim.trim()!==""&&(t.contentHash===void 0||/^[a-f0-9]{64}$/u.test(t.contentHash))&&(t.generation===void 0||typeof t.generation=="string"&&t.generation.length>0)}var Ka=class extends Error{constructor(n,r,i){super(`${n} is ${r} characters; the safety limit is ${i} characters`);this.inputKind=n;this.observedCharacters=r;this.limitCharacters=i;this.name="RegExpPatternBudgetError"}inputKind;observedCharacters;limitCharacters;code="SCIP_QUERY_REGEXP_PATTERN_BUDGET"};function jr(e,t,n,r=4096){if(!Number.isSafeInteger(r)||r<0)throw new RangeError(`maxCharacters must be a non-negative safe integer; received ${r}`);if(e.length>r)throw new Ka(t,e.length,r);return new RegExp(e,n)}import{createHash as nS}from"crypto";import{closeSync as Zk,fstatSync as rS,lstatSync as eA,openSync as tA,readlinkSync as nA,realpathSync as rA,rmSync as iA}from"fs";import{dirname as sS,resolve as oA}from"path";var sA=2e3,aA=10,cA=3,Va=class extends Error{constructor(n,r,i){super(`Concurrent edit detected for ${n}; expected revision ${oS(r)}, but found ${oS(i)}. The latest file was left untouched.`);this.path=n;this.original=r;this.latest=i;this.name="FileRevisionConflictError"}path;original;latest},qo=class extends Error{constructor(n,r){super(`Concurrent edit detected for ${n}: ${r} changed since it was read. The latest file was left untouched; reload it and retry.`);this.path=n;this.field=r;this.name="FileContentConflictError"}path;field};function Go(e,t,n={}){let r=lA(e),i=uA(r,n.lockTimeoutMs??sA,n.monotonicNow??At);try{let o=Math.max(0,Math.floor(n.maxRetries??cA));for(let s=0;;s+=1){let a=Wa(r),c=t(a,s);if(c.kind==="unchanged")return{changed:!1,attempts:s+1,previous:a,current:a};n.onBeforeCommit?.({attempt:s,snapshot:a,mutation:c});let u=Wa(r);if(!mA(a.revision,u.revision)){if(s<o)continue;throw new Va(r,a.revision,u.revision)}try{dA(r,c,a.revision)}catch(l){if(l.code==="EEXIST"){let d=Wa(r);if(s<o)continue;throw new Va(r,a.revision,d.revision)}throw l}return{changed:!0,attempts:s+1,previous:a,current:Wa(r)}}}finally{i.release()}}function lA(e){let t;try{if(!eA(e).isSymbolicLink())return e;t=nA(e)}catch{return e}try{return rA(e)}catch{return oA(sS(e),t)}}function Wa(e){for(let t=0;t<4;t+=1){let n;try{n=tA(e,"r");let r=iS(rS(n)),i=Af(n,{maxBytes:yn,inputKind:"revisioned text file"}),o=iS(rS(n));if(!aS(r,o))continue;return{path:e,text:i,revision:{exists:!0,hash:nS("sha256").update(i).digest("hex"),identity:o}}}catch(r){if(r.code==="ENOENT")return{path:e,text:"",revision:{exists:!1,hash:nS("sha256").update("").digest("hex")}};throw r}finally{n!==void 0&&Zk(n)}}throw new Error(`Could not read a stable revision of ${e}; the file is changing continuously.`)}function uA(e,t,n){let r=`${e}.scip-query-write.lock`,i=n()+Math.max(0,t);for(;;){let o=Ci(r,{kind:"revisioned-file-mutation",detail:{target:e}});if(o.kind==="acquired")return o.lock;if(n()>=i)throw new Error(`Timed out after ${t}ms waiting to update ${e}; the file was left untouched.`);Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,aA)}}function dA(e,t,n){if(t.kind==="delete"){if(!n.exists)return;iA(e),$f(sS(e));return}let r=t.mode??n.identity?.mode;n.exists?Fg(e,t.text,{durability:"durable",mode:r}):Ng(e,t.text,{durability:"durable",mode:r})}function mA(e,t){return e.exists===t.exists&&e.hash===t.hash&&(e.identity===void 0?t.identity===void 0:t.identity!==void 0&&aS(e.identity,t.identity))}function iS(e){return{dev:e.dev,ino:e.ino,size:e.size,mtimeMs:e.mtimeMs,mode:e.mode&511}}function aS(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.size===t.size&&e.mtimeMs===t.mtimeMs&&e.mode===t.mode}function oS(e){return e.exists?e.hash.slice(0,12):"<absent>"}var or=".scipquery.json",mS=2e3,Ya=5e3,yd=Ya,pS=15*6e4,bd={enabled:!0,windowMs:15*6e4,maxRebuilds:2,maxEstimatedWriteBytes:1024*1024*1024},hA={enabled:!1,autoStart:!1,allowExpensiveRebuild:!1,debounceMs:mS,cooldownMs:yd,gitPollMs:2e3,idleTimeoutMs:pS,autoRefresh:!0,ignore:[],resourceBudget:bd};var yA=new Set(["$schema","schemaVersion","collaborationDomainId","languages","indexerConcurrency","watch","indexer","dbPath","entryRoots","semantic","suppressions","declaredCouplings","locality","architecture","coverageContracts","docs"]),bA=new Set(["enabled","autoStart","allowExpensiveRebuild","debounceMs","cooldownMs","gitPollMs","idleTimeoutMs","autoRefresh","ignore","resourceBudget"]),SA=new Set(["enabled","windowMs","maxRebuilds","maxEstimatedWriteBytes"]),vA=new Set(["pathPrefixes","files","symbolPatterns","qualifiedVars"]),CA=new Set(["typescript","rust"]),xA=new Set(["tsconfigs"]),RA=new Set(["rustAnalyzerPath"]),cS=new Set(Hl),EA=new Set(["pnpmWorkspaces","projectMode","projects","configPath","maxWarmSessions","workerIdleMs","workerSoftMemoryMb","workerHeapMb","maxHeapMb"]),IA=new Set(["architecturalBoundarySegments"]),wA=new Set(["boundaries","allowedDependencies","requireCompletePolicy","requireCompleteCoverage","requireAcyclic","requireResolvedBoundaries","requireMinimalPolicy","maxBoundaryFanOut","maxBoundaryFiles","testPaths"]),LA=new Set(["name","paths","subUnits","maxFiles"]),PA=new Set(["snapshotPaths"]),DA=new Set(["name","files","reason"]),MA=new Set(["id","check","file","reason","expiresAt","createdAt","decision"]),TA=new Set(["kind","reasonCode","decidedBy","policyVersion","observation","evidence","invalidateOn"]),kA=new Set(["kind","referent","claim","contentHash","generation"]),AA=new Set(["targetContentChange","detectorMajorChange"]),FA=new Set(["name","file","keys","mustEqual","allowExtra"]),NA=new Set(["type","identifier","marker"]),_A=new Set(["type","path","pattern"]),OA=new Set(["object-literal-keys","string-array","markdown-list"]),BA=new Set(["top-level-dirs","file-glob","registered-commands","builtin-skills"]);function fS(e){let t=Ln(e,or);if(!Fi(t))return{};let n;try{n=It(t,{maxBytes:$s,inputKind:"scip-query project config"})}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`unable to read ${or} at ${t}: ${i}`,{cause:r})}return hS(dd(n),t,"read").config}function yne(e,t={}){let n=[];return YA(e,n),$A(e,n),jA(e,n),HA(e,n,t),UA(e,n),zA(e,n),qA(e,n,t),GA(e,n,t),VA(e,n,t),WA(e,n),n}function lS(e,t,n,r,i){if(!r)return;let o=gA(r,n),s=fA(r,o);if(s.startsWith("..")||pA(s)){e.push({level:"error",path:t,message:i.outside});return}Fi(o)||e.push({level:"warning",path:t,message:i.missing})}function $A(e,t){let n=e;n.schemaVersion!==void 0&&n.schemaVersion!==nr&&t.push({level:"error",path:"schemaVersion",message:`Must be ${nr}; unversioned and v${tr} files are migrated while loading.`}),n.$schema!==void 0&&(typeof n.$schema!="string"||n.$schema.trim()==="")&&t.push({level:"error",path:"$schema",message:"Must be a non-empty string."}),e.collaborationDomainId!==void 0&&!/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(e.collaborationDomainId)&&t.push({level:"error",path:"collaborationDomainId",message:"Must be a lowercase or uppercase UUID v4 generated for this collaboration domain."});let r=new Set(Hl);for(let[i,o]of(e.languages??[]).entries())r.has(o)||t.push({level:"error",path:`languages[${i}]`,message:`Unsupported language: ${o}`});for(let[i,o]of(e.entryRoots?.symbolPatterns??[]).entries())try{jr(o,`entryRoots.symbolPatterns[${i}]`)}catch(s){t.push({level:"error",path:`entryRoots.symbolPatterns[${i}]`,message:s instanceof Error?s.message:String(s)})}e.indexerConcurrency!==void 0&&(!Number.isInteger(e.indexerConcurrency)||e.indexerConcurrency<=0)&&t.push({level:"error",path:"indexerConcurrency",message:"Must be a positive integer."})}function jA(e,t){e.watch?.debounceMs!==void 0&&e.watch.debounceMs<=0&&t.push({level:"error",path:"watch.debounceMs",message:"Must be greater than 0."}),e.watch?.cooldownMs!==void 0&&(!Number.isInteger(e.watch.cooldownMs)||e.watch.cooldownMs<0)?t.push({level:"error",path:"watch.cooldownMs",message:"Must be a non-negative integer."}):e.watch?.cooldownMs!==void 0&&e.watch.cooldownMs<Ya&&t.push({level:"warning",path:"watch.cooldownMs",message:`Values below ${Ya}ms are raised to the safety floor at runtime.`}),e.watch?.gitPollMs!==void 0&&e.watch.gitPollMs<=0&&t.push({level:"error",path:"watch.gitPollMs",message:"Must be greater than 0."}),e.watch?.idleTimeoutMs!==void 0&&(!Number.isInteger(e.watch.idleTimeoutMs)||e.watch.idleTimeoutMs<0)&&t.push({level:"error",path:"watch.idleTimeoutMs",message:"Must be a non-negative integer; 0 disables idle shutdown."}),e.watch?.autoStart!==void 0&&typeof e.watch.autoStart!="boolean"&&t.push({level:"error",path:"watch.autoStart",message:"Must be a boolean."}),e.watch?.allowExpensiveRebuild!==void 0&&typeof e.watch.allowExpensiveRebuild!="boolean"&&t.push({level:"error",path:"watch.allowExpensiveRebuild",message:"Must be a boolean."}),e.watch?.autoRefresh!==void 0&&typeof e.watch.autoRefresh!="boolean"&&t.push({level:"error",path:"watch.autoRefresh",message:"Must be a boolean."});let n=e.watch?.resourceBudget;n?.enabled!==void 0&&typeof n.enabled!="boolean"&&t.push({level:"error",path:"watch.resourceBudget.enabled",message:"Must be a boolean."});for(let[r,i]of[["windowMs",n?.windowMs],["maxRebuilds",n?.maxRebuilds],["maxEstimatedWriteBytes",n?.maxEstimatedWriteBytes]])i!==void 0&&(!Number.isSafeInteger(i)||i<=0)&&t.push({level:"error",path:`watch.resourceBudget.${r}`,message:"Must be a positive safe integer."})}function HA(e,t,n){let r=e.indexer?.typescript;if(r?.projectMode!==void 0&&r.projectMode!=="single"&&r.projectMode!=="workspace"&&t.push({level:"error",path:"indexer.typescript.projectMode",message:'Must be "single" or "workspace".'}),r?.projects!==void 0)if(!Array.isArray(r.projects))t.push({level:"error",path:"indexer.typescript.projects",message:"Must be an array."});else for(let[s,a]of r.projects.entries()){let c=`indexer.typescript.projects[${s}]`;typeof a!="string"||a.trim()===""?t.push({level:"error",path:c,message:"Project path must be a non-empty string."}):lS(t,c,a,n.projectRoot,{outside:"Project path must stay inside the project root.",missing:`TypeScript project path does not exist: ${a}`})}r?.projectMode==="workspace"&&r.pnpmWorkspaces===!0&&t.push({level:"warning",path:"indexer.typescript.pnpmWorkspaces",message:'Ignored when projectMode is "workspace"; explicit TypeScript projects are indexed directly.'});for(let[s,a]of[["maxWarmSessions",r?.maxWarmSessions],["workerSoftMemoryMb",r?.workerSoftMemoryMb],["workerHeapMb",r?.workerHeapMb],["maxHeapMb",r?.maxHeapMb]])a!==void 0&&(!Number.isInteger(a)||a<=0)&&t.push({level:"error",path:`indexer.typescript.${s}`,message:"Must be a positive integer."});r?.workerIdleMs!==void 0&&(!Number.isInteger(r.workerIdleMs)||r.workerIdleMs<0)&&t.push({level:"error",path:"indexer.typescript.workerIdleMs",message:"Must be a non-negative integer."});let i=e.semantic?.rust;i?.rustAnalyzerPath!==void 0&&(typeof i.rustAnalyzerPath!="string"||i.rustAnalyzerPath.trim()==="")&&t.push({level:"error",path:"semantic.rust.rustAnalyzerPath",message:"Rust analyzer path must be a non-empty string."});let o=e.indexer?.clojure;if(o?.configPath!==void 0){let s="indexer.clojure.configPath";typeof o.configPath!="string"||o.configPath.trim()===""?t.push({level:"error",path:s,message:"Config path must be a non-empty string."}):lS(t,s,o.configPath,n.projectRoot,{outside:"Config path must stay inside the project root.",missing:`Clojure indexer config path does not exist: ${o.configPath}`})}}function UA(e,t){if(e.locality===void 0)return;if(!Z(e.locality)){t.push({level:"error",path:"locality",message:"Must be an object."});return}let n=e.locality.architecturalBoundarySegments;if(n!==void 0){if(!Array.isArray(n)){t.push({level:"error",path:"locality.architecturalBoundarySegments",message:"Must be an array."});return}for(let[r,i]of n.entries()){let o=`locality.architecturalBoundarySegments[${r}]`;typeof i!="string"||i.trim()===""?t.push({level:"error",path:o,message:"Boundary segment must be a non-empty string."}):(i.includes("/")||i.includes("\\"))&&t.push({level:"error",path:o,message:"Boundary segment must be a single folder name, not a path."})}}}function qA(e,t,n){if(e.declaredCouplings!==void 0&&!Array.isArray(e.declaredCouplings)){t.push({level:"error",path:"declaredCouplings",message:"Must be an array."});return}for(let[r,i]of(e.declaredCouplings??[]).entries()){let o=`declaredCouplings[${r}]`;if((!i.name||i.name.trim()==="")&&t.push({level:"error",path:`${o}.name`,message:"Declared coupling name is required."}),!Array.isArray(i.files)||i.files.length<2)t.push({level:"error",path:`${o}.files`,message:"Declared coupling needs at least two files."});else for(let[s,a]of i.files.entries())!a||a.trim()===""?t.push({level:"error",path:`${o}.files[${s}]`,message:"Declared coupling file path is required."}):n.projectRoot&&!Fi(Ln(n.projectRoot,a))&&t.push({level:"warning",path:`${o}.files[${s}]`,message:`Declared coupling file does not exist: ${a}`});i.reason!==void 0&&i.reason.trim()===""&&t.push({level:"error",path:`${o}.reason`,message:"Declared coupling reason cannot be blank."})}}function GA(e,t,n){let r=n.now??new Date;e.suppressions!==void 0&&!Array.isArray(e.suppressions)&&t.push({level:"error",path:"suppressions",message:"Must be an array."});for(let[i,o]of(Array.isArray(e.suppressions)?e.suppressions:[]).entries()){let s=`suppressions[${i}]`;if(!Z(o)){t.push({level:"error",path:s,message:"Suppression must be an object."});continue}if((!o.reason||o.reason.trim()==="")&&t.push({level:"error",path:`${s}.reason`,message:"Suppression reason is required."}),o.id!==void 0&&o.id.trim()===""&&t.push({level:"error",path:`${s}.id`,message:"Suppression id cannot be blank."}),o.check!==void 0&&o.check.trim()===""&&t.push({level:"error",path:`${s}.check`,message:"Suppression check cannot be blank."}),!o.id&&(!o.check||!o.file)?t.push({level:"error",path:s,message:"Suppression must include id or both check and file."}):!o.id&&o.check&&o.file&&t.push({level:"warning",path:s,message:"Check+file suppressions waive every matching finding in that file; prefer a stable id when available."}),o.file!==void 0&&(o.file.trim()===""?t.push({level:"error",path:`${s}.file`,message:"Suppression file path cannot be blank."}):n.projectRoot&&!Fi(Ln(n.projectRoot,o.file))&&t.push({level:"warning",path:`${s}.file`,message:`Suppression file does not exist: ${o.file}`})),o.expiresAt){let a=Date.parse(o.expiresAt);Number.isNaN(a)?t.push({level:"error",path:`${s}.expiresAt`,message:"Must be an ISO date string."}):a<=r.getTime()&&t.push({level:"warning",path:`${s}.expiresAt`,message:"Suppression has expired."})}if(o.decision!==void 0&&!za(o.decision))t.push({level:"error",path:`${s}.decision`,message:"Must be a valid automated-adjudication decision with reason code, evidence, and invalidation rules."});else if(o.decision&&n.projectRoot)for(let[a,c]of o.decision.evidence.entries())c.kind!=="graph"&&!Fi(Ln(n.projectRoot,c.referent))&&t.push({level:"error",path:`${s}.decision.evidence[${a}].referent`,message:`Suppression counterevidence does not exist: ${c.referent}`})}}function zA(e,t){if(e.architecture===void 0)return;if(!Z(e.architecture)){t.push({level:"error",path:"architecture",message:"Must be an object."});return}let n=e.architecture.boundaries;if(!Array.isArray(n)||n.length===0){t.push({level:"error",path:"architecture.boundaries",message:"Must be a non-empty array."});return}let r=new Set,i=new Set;for(let[a,c]of n.entries()){let u=`architecture.boundaries[${a}]`;if(!Z(c)){t.push({level:"error",path:u,message:"Architecture boundary must be an object."});continue}let l=c.name;typeof l!="string"||l.trim()===""?t.push({level:"error",path:`${u}.name`,message:"Boundary name is required."}):r.has(l)?t.push({level:"error",path:`${u}.name`,message:`Duplicate boundary name: ${l}`}):r.add(l);let d=c.subUnits;d!==void 0&&d!=="directory"&&d!=="file"&&t.push({level:"error",path:`${u}.subUnits`,message:"Must be 'directory' or 'file'."});let m=c.maxFiles;m!==void 0&&(typeof m!="number"||!Number.isInteger(m)||m<0)&&t.push({level:"error",path:`${u}.maxFiles`,message:"Must be a non-negative integer."});let p=c.paths;if(!Array.isArray(p)||p.length===0){t.push({level:"error",path:`${u}.paths`,message:"Boundary paths must be a non-empty array."});continue}for(let[f,g]of p.entries()){let h=`${u}.paths[${f}]`;if(typeof g!="string"||g.trim()===""){t.push({level:"error",path:h,message:"Boundary path must be a non-empty string."});continue}KA(g)||t.push({level:"error",path:h,message:"Boundary path must be project-relative and may use only one trailing /* or /** glob."}),i.has(g)?t.push({level:"error",path:h,message:`Duplicate boundary path: ${g}`}):i.add(g)}}let o=e.architecture.allowedDependencies;if(o!==void 0&&!Z(o))t.push({level:"error",path:"architecture.allowedDependencies",message:"Must be an object keyed by boundary name."});else if(Z(o))for(let[a,c]of Object.entries(o)){let u=`architecture.allowedDependencies.${a}`;if(r.has(a)||t.push({level:"error",path:u,message:`Unknown source boundary: ${a}`}),!Array.isArray(c)){t.push({level:"error",path:u,message:"Dependency row must be an array."});continue}let l=new Set;for(let[d,m]of c.entries()){let p=`${u}[${d}]`;typeof m!="string"||m.trim()===""?t.push({level:"error",path:p,message:"Target boundary name is required."}):r.has(m)?l.has(m)?t.push({level:"error",path:p,message:`Duplicate target boundary: ${m}`}):l.add(m):t.push({level:"error",path:p,message:`Unknown target boundary: ${m}`})}}e.architecture.requireAcyclic!==void 0&&typeof e.architecture.requireAcyclic!="boolean"&&t.push({level:"error",path:"architecture.requireAcyclic",message:"Must be a boolean."});for(let a of["requireCompleteCoverage","requireResolvedBoundaries","requireMinimalPolicy"])e.architecture[a]!==void 0&&typeof e.architecture[a]!="boolean"&&t.push({level:"error",path:`architecture.${a}`,message:"Must be a boolean."});for(let a of["maxBoundaryFanOut","maxBoundaryFiles"]){let c=e.architecture[a];c!==void 0&&(typeof c!="number"||!Number.isInteger(c)||c<0)&&t.push({level:"error",path:`architecture.${a}`,message:"Must be a non-negative integer."})}let s=e.architecture.testPaths;if(s!==void 0&&(!Array.isArray(s)||s.some(a=>typeof a!="string"))&&t.push({level:"error",path:"architecture.testPaths",message:"Must be an array of strings."}),e.architecture.requireCompletePolicy!==void 0&&typeof e.architecture.requireCompletePolicy!="boolean")t.push({level:"error",path:"architecture.requireCompletePolicy",message:"Must be a boolean."});else if(e.architecture.requireCompletePolicy===!0){let a=Z(o)?o:{};for(let c of[...r].sort())Object.hasOwn(a,c)||t.push({level:"error",path:`architecture.allowedDependencies.${c}`,message:"A dependency row is required by architecture.requireCompletePolicy."})}}function KA(e){let t=e.replace(/\\/g,"/");if(t.startsWith("/")||t==="."||t===".."||t.split("/").includes(".."))return!1;let n=t.replace(/\/\*\*?$/,"");return n.length>0&&!/[*?[\]]/.test(n)}function WA(e,t){let n=e.docs?.snapshotPaths;if(n!==void 0){if(!Array.isArray(n)){t.push({level:"error",path:"docs.snapshotPaths",message:"Must be an array."});return}for(let[r,i]of n.entries())(typeof i!="string"||i.trim()==="")&&t.push({level:"error",path:`docs.snapshotPaths[${r}]`,message:"Snapshot path glob must be a non-empty string."})}}function VA(e,t,n){if(e.coverageContracts!==void 0){if(!Array.isArray(e.coverageContracts)){t.push({level:"error",path:"coverageContracts",message:"Must be an array."});return}for(let[r,i]of e.coverageContracts.entries()){let o=`coverageContracts[${r}]`;if(!Z(i)){t.push({level:"error",path:o,message:"Coverage contract must be an object."});continue}(typeof i.name!="string"||i.name.trim()==="")&&t.push({level:"error",path:`${o}.name`,message:"Coverage contract name is required."}),typeof i.file!="string"||i.file.trim()===""?t.push({level:"error",path:`${o}.file`,message:"Coverage contract file is required."}):n.projectRoot&&!Fi(Ln(n.projectRoot,i.file))&&t.push({level:"warning",path:`${o}.file`,message:`Coverage contract file does not exist: ${i.file}`}),uS(t,i.keys,`${o}.keys`,OA,"Unknown coverage-contract key extractor type."),uS(t,i.mustEqual,`${o}.mustEqual`,BA,"Unknown coverage-contract ground-truth source type."),i.allowExtra!==void 0&&typeof i.allowExtra!="boolean"&&t.push({level:"error",path:`${o}.allowExtra`,message:"Must be a boolean."})}}}function uS(e,t,n,r,i){if(!Z(t)){e.push({level:"error",path:n,message:'Must be an object with a "type" field.'});return}if(typeof t.type!="string"||!r.has(t.type)){e.push({level:"error",path:`${n}.type`,message:`${i} Got: ${String(t.type)}`});return}let o={"object-literal-keys":["identifier"],"string-array":["identifier"],"markdown-list":["marker"],"top-level-dirs":["path"],"file-glob":["pattern"],"registered-commands":[],"builtin-skills":[]};for(let s of o[t.type]??[])(typeof t[s]!="string"||t[s].length===0)&&e.push({level:"error",path:`${n}.${s}`,message:`"${t.type}" requires a non-empty string "${s}".`})}function bne(e){return{...hA,...e.watch,cooldownMs:Math.max(Ya,e.watch?.cooldownMs??yd),resourceBudget:{...bd,...e.watch?.resourceBudget}}}function Sne(e,t){let n=Ln(e,or),r=dS(),i={collaborationDomainId:r,languages:t,watch:{enabled:!0,debounceMs:mS,cooldownMs:yd,gitPollMs:2e3,idleTimeoutMs:pS,autoRefresh:!0,resourceBudget:{...bd}}},o=Go(n,s=>{if(!s.revision.exists)return{kind:"write",text:Ai(i)};let a=Xa(s,i);return a.config.collaborationDomainId?{kind:"unchanged"}:{kind:"write",text:Ai({...a.config,collaborationDomainId:r})}});return{configPath:n,changed:o.changed}}function vne(e,t,n=dS()){let r=Ln(e,or),i=t,o=Go(r,s=>{let a=Xa(s,t);if(a.config.collaborationDomainId)return i=a.config,{kind:"unchanged"};let c={...a.config,collaborationDomainId:n};return i=c,{kind:"write",text:Ai(c)}});return{configPath:r,config:i,changed:o.changed}}function Cne(e,t,n){let r=Ln(e,or),i=[...n],o=t,s=Go(r,a=>{let c=Xa(a,t);if(gS(t.languages,c.config.languages,i))throw new qo(r,"languages");let u={...c.config,languages:i};return o=u,a.revision.exists&&!c.needsMigration&&Ja(u,c.config)?{kind:"unchanged"}:{kind:"write",text:Ai(u)}});return{configPath:r,config:o,changed:s.changed}}function xne(e,t,n){let r=Ln(e,or),i=t,o=Go(r,s=>{let a=Xa(s,t);if(gS(t.watch?.enabled,a.config.watch?.enabled,n))throw new qo(r,"watch.enabled");let c={...a.config,watch:{...a.config.watch,enabled:n,...n&&a.config.watch?.autoRefresh===void 0?{autoRefresh:!0}:{}}};return i=c,s.revision.exists&&!a.needsMigration&&Ja(c,a.config)?{kind:"unchanged"}:{kind:"write",text:Ai(c)}});return{configPath:r,config:i,changed:o.changed}}function Xa(e,t){if(!e.revision.exists)return{config:qa(t),needsMigration:!0};let n=hS(dd(e.text),e.path,"update");return{config:n.config,needsMigration:n.needsMigration}}function Ja(e,t){return JSON.stringify(e)===JSON.stringify(t)}function gS(e,t,n){return!Ja(e,t)&&!Ja(t,n)}function hS(e,t,n){if(e.kind==="legacy"||e.kind==="supported")return e;if(e.kind==="malformed"){let i=n==="read"?`invalid ${or} at ${t}: ${e.reason}`:`Cannot update ${t}: the latest project config is ${e.reason}.`;throw new Error(`${i} The file was left untouched.`)}let r=n==="read"?`invalid ${or} at ${t}`:`Cannot update ${t}: the latest project config is invalid`;throw new Error(`${r} (unsupported ${e.direction} schemaVersion ${e.schemaVersion}; this scip-query reads legacy v${tr} and current v${nr}). Upgrade scip-query before retrying; the file was left untouched.`)}function YA(e,t){if(!Z(e))return;let n=e;if(Le(t,n,"",yA),Le(t,n.watch,"watch",bA),Le(t,n.watch?.resourceBudget,"watch.resourceBudget",SA),Le(t,n.entryRoots,"entryRoots",vA),Le(t,n.semantic,"semantic",CA),Le(t,n.semantic?.typescript,"semantic.typescript",xA),Le(t,n.semantic?.rust,"semantic.rust",RA),Le(t,n.locality,"locality",IA),Le(t,n.architecture,"architecture",wA),Le(t,n.docs,"docs",PA),Array.isArray(n.architecture?.boundaries))for(let[r,i]of n.architecture.boundaries.entries())Le(t,i,`architecture.boundaries[${r}]`,LA);if(Z(n.indexer)){Le(t,n.indexer,"indexer",cS);for(let[r,i]of Object.entries(n.indexer))cS.has(r)&&Le(t,i,`indexer.${r}`,EA)}if(Array.isArray(n.declaredCouplings))for(let[r,i]of n.declaredCouplings.entries())Le(t,i,`declaredCouplings[${r}]`,DA);if(Array.isArray(n.suppressions)){for(let[r,i]of n.suppressions.entries())if(Le(t,i,`suppressions[${r}]`,MA),Z(i.decision)){if(Le(t,i.decision,`suppressions[${r}].decision`,TA),Array.isArray(i.decision.evidence))for(let[o,s]of i.decision.evidence.entries())Le(t,s,`suppressions[${r}].decision.evidence[${o}]`,kA);Le(t,i.decision.invalidateOn,`suppressions[${r}].decision.invalidateOn`,AA)}}if(Array.isArray(n.coverageContracts))for(let[r,i]of n.coverageContracts.entries()){let o=`coverageContracts[${r}]`;Le(t,i,o,FA),Z(i)&&(Le(t,i.keys,`${o}.keys`,NA),Le(t,i.mustEqual,`${o}.mustEqual`,_A))}}function Le(e,t,n,r){if(Z(t))for(let i of Object.keys(t))r.has(i)||e.push({level:"warning",path:n?`${n}.${i}`:i,message:"Unknown config key."})}import{existsSync as Qa,lstatSync as JA}from"fs";import{resolve as XA}from"path";function One(e){return e.state==="fresh"?!0:e.state!=="stale"?!1:!e.reason.startsWith("SQLite generation requires repair")}function yS(e,t,n,r={}){let i=new Date().toISOString();if(!Qa(n.dbPath))return{state:"missing",checkedAt:i,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!Qa(n.metaPath))return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let o=Rr(Xe(n.metaPath,"reindex metadata"));if(o.kind==="unsupported")return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Reindex metadata version ${o.version} is unsupported by this scip-query build.`,remedy:"Upgrade scip-query or run: scip-query reindex"};if(o.kind==="malformed")return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Could not decode reindex metadata: ${o.reason}`,remedy:"Run: scip-query reindex"};let s=o.metadata,a=t.languages??Vg(e),c=s.fingerprint,u=n.cacheDir&&r.gitContext&&eu(r.gitContext,n.cacheDir,c)?c:void 0,l=n.cacheDir&&r.gitContext&&u&&ZA(u,a,t)&&eF(e,u,t)?r.gitObservation?.context===r.gitContext?r.gitContext:_f(r.gitContext):void 0,d=r.gitObservation&&r.gitObservation.context===r.gitContext?r.gitObservation.projectFileInventorySequence:void 0,m=l?.clean&&Of(e,void 0,{cachedInventoryAfterSequence:d})?l:void 0,p=n.cacheDir&&m&&u&&eu(m,n.cacheDir,u)?u:QA(e,a,t),f=[...s.indexedLanguages??[]].sort(),g=o.capabilities.publishableGeneration&&Tf(ao(s.fingerprint),p)&&JSON.stringify(f)===JSON.stringify(p.languages),h=Zl(n.dbPath,n.metaPath),y=h.state==="invalid"||h.state==="drifted",S=g?Yg(n.dbPath,p,f):void 0,b=S?.state==="incomplete",x=g&&!y&&!b;return{state:x?"fresh":"stale",checkedAt:i,metaPath:n.metaPath,updatedAt:s.updatedAt,lastRefresh:s.lastRefresh,reason:y?`SQLite generation requires repair: ${h.reason}`:b?`SQLite generation is missing ${S.missingDocumentCount} indexed source document(s): ${S.missingPaths.join(", ")}`:g?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:x?void 0:"Run: scip-query reindex"}}catch(o){return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Could not read reindex metadata: ${o instanceof Error?o.message:String(o)}`,remedy:"Run: scip-query reindex"}}}function Bne(e){let t=new Date().toISOString();if(!Qa(e.dbPath))return{state:"missing",checkedAt:t,metaPath:e.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!Qa(e.metaPath))return{state:"unknown",checkedAt:t,metaPath:e.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let n=Rr(Xe(e.metaPath,"reindex metadata"));if(n.kind==="unsupported")return{state:"unknown",checkedAt:t,metaPath:e.metaPath,reason:`Reindex metadata version ${n.version} is unsupported by this scip-query build.`,remedy:"Upgrade scip-query or run: scip-query reindex"};if(n.kind==="malformed")return{state:"unknown",checkedAt:t,metaPath:e.metaPath,reason:`Could not decode reindex metadata: ${n.reason}`,remedy:"Run: scip-query reindex"};let r=n.metadata,i=[...r.indexedLanguages??[]].sort(),o=ao(r.fingerprint),s=[...o?.languages??[]].sort(),a=n.capabilities.publishableGeneration&&o!==null&&JSON.stringify(i)===JSON.stringify(s),c=Zl(e.dbPath,e.metaPath),u=c.state==="invalid"||c.state==="drifted",l=a&&!u;return{state:l?"fresh":"stale",checkedAt:t,metaPath:e.metaPath,updatedAt:r.updatedAt,lastRefresh:r.lastRefresh,reason:u?`SQLite generation requires repair: ${c.reason}`:a?"Watcher accepted the newly published index generation with no later changes pending.":"Published index metadata is not a complete queryable generation.",remedy:l?void 0:"Run: scip-query reindex"}}catch(n){return{state:"unknown",checkedAt:t,metaPath:e.metaPath,reason:`Could not read reindex metadata: ${n instanceof Error?n.message:String(n)}`,remedy:"Run: scip-query reindex"}}}function QA(e,t,n){return zf(e,t,{pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:n.indexer?.typescript?.projectMode,typescriptProjects:n.indexer?.typescript?.projects,clojureConfigPath:n.indexer?.clojure?.configPath})}function ZA(e,t,n){let r=tF(t,n);return e.version===r.version&&JSON.stringify([...e.languages].sort())===JSON.stringify(r.languages)&&e.pnpmWorkspaces===r.pnpmWorkspaces&&e.typescriptProjectMode===r.typescriptProjectMode&&JSON.stringify([...e.typescriptProjects].sort())===JSON.stringify(r.typescriptProjects)&&e.clojureConfigPath===r.clojureConfigPath}function eF(e,t,n){if(!(t.languages.includes("typescript")||!!t.clojureConfigPath))return!0;let i=Hs(e);if(t.clojureConfigPath){let o=hn(t.clojureConfigPath);if(!i.includes(o))return!1;try{if(!JA(XA(e,o)).isFile())return!1}catch{return!1}}return!t.languages.includes("typescript")||Bf(e,n.indexer?.typescript?.projectMode,n.indexer?.typescript?.projects??[],i)}function tF(e,t){return Kf(e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}import{existsSync as nF,readdirSync as rF}from"fs";import{createHash as iF}from"crypto";import{join as Cd}from"path";function vd(e){let t=0,n=0,r=0,i=0,o=0,s=[];for(let u of e)switch(u.state){case"legacy":t+=1;break;case"current":n+=1;break;case"unsupported-older":r+=1,s.push(Sd(u));break;case"unsupported-future":i+=1,s.push(Sd(u));break;case"malformed":o+=1,s.push(Sd(u));break}let a=t+n,c=r+i+o;return{complete:c===0,total:e.length,accepted:a,legacy:t,current:n,unsupportedOlder:r,unsupportedFuture:i,malformed:o,omitted:c,issues:s}}function Sd(e){if(e.state==="legacy"||e.state==="current")throw new Error(`accepted record ${e.path} cannot become a compatibility issue`);return{path:e.path,state:e.state,reason:e.reason??e.state}}var vS=Cd(".scipquery","suppressions"),bS="scip-query-suppression",SS=1,Za=2;function oF(e){return Cd(e,vS)}function sF(e){if(e.id&&e.id.trim()!=="")return`${e.id.trim()}.json`;let t=`${e.check??""}\0${e.file??""}`;return`CHECK-${iF("sha256").update(t).digest("hex").slice(0,12).toUpperCase()}.json`}function aF(e){return sF(e).slice(0,-5)}function cF(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return{state:"malformed",error:"not a suppression object"};let n=e;if(n.schemaVersion===void 0&&(n.kind!==void 0||n.suppressionIdentity!==void 0||n.writer!==void 0))return{state:"malformed",error:"suppression envelope metadata requires schemaVersion"};if(n.schemaVersion!==void 0){if(!Number.isSafeInteger(n.schemaVersion))return{state:"malformed",error:"schemaVersion must be a positive safe integer"};if(n.schemaVersion!==SS&&n.schemaVersion!==Za)return{state:n.schemaVersion>Za?"unsupported-future":"unsupported-older",error:`unsupported schemaVersion ${String(n.schemaVersion)}`};if(n.kind!==void 0&&n.kind!==bS)return{state:"malformed",error:`kind must be ${bS}`}}if(n.schemaVersion===SS&&n.decision!==void 0)return{state:"malformed",error:"schemaVersion 1 cannot carry automated adjudication metadata"};if(n.schemaVersion===Za&&!za(n.decision))return{state:"malformed",error:"schemaVersion 2 requires a valid automated adjudication decision"};if(typeof n.reason!="string"||n.reason.trim()==="")return{state:"malformed",error:"missing reason"};if(!n.id&&!n.check)return{state:"malformed",error:"needs an id or a check"};let r=lF(n);if(n.schemaVersion===void 0)return{state:"legacy",suppression:r,record:n,schemaVersion:0};let i=aF(r);return n.suppressionIdentity!==i||t!==void 0&&n.suppressionIdentity!==t?{state:"malformed",error:"suppressionIdentity does not match the suppression target or filename"}:!n.writer||n.writer.tool!=="scip-query"||typeof n.writer.version!="string"||n.writer.version.trim()===""?{state:"malformed",error:"missing valid writer metadata"}:typeof n.createdAt!="string"||!Number.isFinite(Date.parse(n.createdAt))?{state:"malformed",error:"missing valid createdAt timestamp"}:n.updatedAt!==void 0&&(typeof n.updatedAt!="string"||!Number.isFinite(Date.parse(n.updatedAt)))?{state:"malformed",error:"invalid updatedAt timestamp"}:{state:n.schemaVersion===Za?"current":"legacy",suppression:r,record:n,schemaVersion:n.schemaVersion}}function CS(e){let t=oF(e);if(!nF(t))return{suppressions:[],compatibility:vd([]),warnings:[]};let n=[],r=[];for(let o of rF(t).sort()){if(!o.endsWith(".json"))continue;let s=Cd(t,o),a=`${vS}/${o}`,c;try{c=JSON.parse(Xe(s,"suppression record"))}catch{r.push({path:a,state:"malformed",reason:"malformed JSON"});continue}let u=cF(c,o.slice(0,-5));if("error"in u){r.push({path:a,state:u.state,reason:u.error});continue}r.push({path:a,state:u.state}),n.push(u.suppression)}let i=vd(r);return{suppressions:n,compatibility:i,warnings:i.issues.map(o=>`${o.path}: ${o.reason} \u2014 ignored`)}}function lF(e){return{...typeof e.id=="string"?{id:e.id}:{},...typeof e.check=="string"?{check:e.check}:{},...typeof e.file=="string"?{file:e.file}:{},reason:e.reason,...typeof e.expiresAt=="string"?{expiresAt:e.expiresAt}:{},...typeof e.createdAt=="string"?{createdAt:e.createdAt}:{},...e.decision?{decision:e.decision}:{}}}function ec(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var xd,Hr;function ore(e){xd=e}function tc(){return Hr}function xS(e=ec(),t=void 0){if(t===void 0&&xd?.projectRoot===e)return xd;let n=fS(e),r=Hf(e,n),i=process.env.SCIP_QUERY_INDEX_DB;if(i)return{projectRoot:e,config:n,paths:r,dbPath:i,dbPathSource:"env",gitContext:t};if(Rd(r.dbPath))return{projectRoot:e,config:n,paths:r,dbPath:r.dbPath,dbPathSource:"configured",gitContext:t};let o=dF(e,"index.db");return{projectRoot:e,config:n,paths:r,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:fF(o,r.dbPath),gitContext:t}}function sre(e){return xS(e).dbPath}function are(e,t,n,r={}){if(Rd(n.dbPath)&&r.gitContext?.clean===!1&&r.watcherGeneration!==void 0&&zg(n.dbPath)===r.watcherGeneration)return Qg(e,t,n,r.gitContext);let i=yS(e,t,n,{gitContext:r.gitContext,gitObservation:r.gitObservation});return i.state==="fresh"?{kind:"local-fresh",freshness:i}:Xg(e,t,n,r.gitContext)}function cre(e){return!e.startsWith("__")&&!mF.has(e)}function lre(e){return e==="search"||e==="code"}var mF=new Set(["capabilities","check-deps","config-validate","continue","doctor","init","install-skills","reindex","setup","setup-agent","status","suppress","uninstall","watch"]);function RS(){try{return pF(ec(),{warnOnRootFallback:!0})}catch(e){console.error(`error: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}function pF(e,t={}){let{config:n,paths:r,dbPath:i,dbPathSource:o,rootFallbackWarning:s,gitContext:a}=xS(e);if(!Rd(i))throw new Error("No index.db found. Run: scip-query reindex");t.warnOnRootFallback&&o==="root-fallback"&&s&&console.error(s);let c=CS(e).suppressions,u={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??r.indexPath,projectRoot:e,collaborationDomainId:n.collaborationDomainId,sharedEvidenceDbPath:Jg(e,n,a),entryRoots:n.entryRoots,semantic:n.semantic,suppressions:[...n.suppressions??[],...c],declaredCouplings:n.declaredCouplings,locality:n.locality,architecture:n.architecture,coverageContracts:n.coverageContracts,docs:n.docs},l=Wg(e);return new Kg(u,l)}function fF(e,t){let n="unknown time";try{n=uF(e).mtime.toISOString()}catch{}return`warning: using legacy project-root index.db (${e}, modified ${n}) because the configured index was not found at ${t}. This fallback may be stale; run 'scip-query reindex' to refresh the configured index.`}function nc(e){return Ff(()=>{let t=RS(),n=Hr;Hr=t;try{return e(t)}finally{Hr=n,t.close()}})}async function ure(e){let t=Nf(),n=RS(),r=Hr;Hr=n;try{return await e(n)}finally{Hr=r,n.close(),t()}}function dre(e,t){return t.concat([e])}function Ed(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(0)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function mre(e){switch(e.state){case"idle":return"Watching (idle)";case"waiting":{let t=Math.round((e.reindexAt-Date.now())/1e3);return`${e.changedFiles} file(s) changed, reindexing in ${t}s...`}case"indexing":return`Reindexing... (${Math.round((Date.now()-e.startedAt)/1e3)}s)`;case"cooldown":return`Cooldown (${Math.round((e.until-Date.now())/1e3)}s)${e.dirty?" \u2014 changes pending":""}`;case"budget-paused":return`Automatic reindex paused by resource budget (${Math.max(0,Math.round((e.until-Date.now())/1e3))}s; ${e.reason}; ${e.rebuilt} rebuilds, ${Ed(e.estimatedWriteBytes)} estimated writes)${e.dirty?" \u2014 changes pending":""}`;case"draining":return`Stopping safely \u2014 ${e.reason}`;default:return gF(e)}}function gF(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}var hF=new Map([[8,"\u2408"],[9,"\u2409"],[10,"\u2424"],[13,"\u240D"]]),fre=6500,gre=8e3,hre=6500,yre=3500;function ES(e,t={}){let n=t.allowNewlines??!0,r=t.allowTabs??!0,i="";for(let o=0;o<e.length;){let s=e.charCodeAt(o);if(s===27){o=yF(e,o);continue}if(s===155){o=IS(e,o+1);continue}if(s===144||s===152||s===157||s===158||s===159){o=wS(e,o+1);continue}if(vF(s)){s===10&&n?i+=`
54
- `:s===9&&r?i+=" ":i+=hF.get(s)??"\uFFFD",o+=1;continue}if(CF(s)){i+="\uFFFD",o+=1;continue}i+=e[o],o+=1}return i}function Nt(e){return ES(e,{allowNewlines:!1,allowTabs:!1})}function wd(e,t=n=>process.stdout.write(n)){t(`${e}
55
- `)}function bre(e=console){let t={log:e.log.bind(e),error:e.error.bind(e),warn:e.warn.bind(e)};return e.log=(...n)=>t.log(...n.map(Id)),e.error=(...n)=>t.error(...n.map(Id)),e.warn=(...n)=>t.warn(...n.map(Id)),()=>{e.log=t.log,e.error=t.error,e.warn=t.warn}}function Id(e){return typeof e=="string"?ES(e):e}function yF(e,t){let n=e.charCodeAt(t+1);if(Number.isNaN(n))return e.length;if(n===91)return IS(e,t+2);if(n===80||n===88||n===93||n===94||n===95)return wS(e,t+2);let r=t+1;for(;r<e.length&&bF(e.charCodeAt(r));)r+=1;return r<e.length&&SF(e.charCodeAt(r))?r+1:t+1}function IS(e,t){let n=t;for(;n<e.length;){let r=e.charCodeAt(n);if(n+=1,r>=64&&r<=126)return n}return e.length}function wS(e,t){let n=t;for(;n<e.length;){let r=e.charCodeAt(n);if(r===7||r===156)return n+1;if(r===27&&e.charCodeAt(n+1)===92)return n+2;n+=1}return e.length}function bF(e){return e>=32&&e<=47}function SF(e){return e>=48&&e<=126}function vF(e){return e<=31||e>=127&&e<=159}function CF(e){return e===1564||e===8206||e===8207||e>=8234&&e<=8238||e>=8294&&e<=8297}function rc(e){return e+1}function xF(e,t){return`${rc(e)}-${rc(t)}`}function Ld(e,t,n){return`${Nt(e)}:${xF(t,n)}`}function Cre(e,t=180){let n=Nt(e).replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var Pd={empty(e){console.log(Nt(e))},list(e,t){for(let n of e)console.log(Nt(t(n)))},groupedByFile(e,t,n=r=>r.relativePath){let r="";for(let i of e){let o=n(i);o!==r&&(r&&console.log(""),console.log(Nt(o)),r=o),console.log(Nt(t(i)))}},sectionedReport(e){let t=!0;for(let n of e)if(!(n.skipIfEmpty&&n.rows.length===0)){t||console.log(""),t=!1,n.title!==void 0&&console.log(`\u2550\u2550\u2550 ${Nt(n.title)} \u2550\u2550\u2550`),n.explanation!==void 0&&console.log(Nt(n.explanation));for(let r of n.rows){let i=n.preserveRowNewlines?r.split(`
56
- `):[r];for(let o of i)console.log(Nt(o))}}},table(e,t,n){console.log(` ${e.map(Nt).join(" ")}`);let r=n??e.map(i=>i.length);console.log(` ${r.map(i=>"\u2500".repeat(i)).join(" ")}`);for(let i of t)console.log(Nt(i))}};import{availableParallelism as wL,totalmem as Ll}from"os";import{fileURLToPath as Pl}from"url";import{getHeapStatistics as tQ}from"v8";import{existsSync as ic,readdirSync as DS}from"fs";import{join as zo}from"path";var RF={files:new Set,pathPrefixes:[]},EF={reasonsByFile:new Map},Dd=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,IF=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,MS=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],wF=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),LF=4,PF=te("package-surface",{clearGroups:["whole-project"]}),DF=te("package-operational-surface",{clearGroups:["whole-project"]});function TS(e){return PF.get(e,()=>TF(e.config.projectRoot))}function Dn(e,t){let n=TS(e);return n.files.has(t)?!0:n.pathPrefixes.some(r=>t.startsWith(r))}function kS(e,t){return TS(e).files.has(t)}function MF(e){return DF.get(e,()=>kF(e.config.projectRoot))}function AS(e,t){return MF(e).reasonsByFile.get(t)??[]}function TF(e){let t=new Set,n=[];for(let{manifest:r,packageRoot:i}of FS(e))for(let o of AF(r))BS(e,i,o,t,n);return t.size===0&&n.length===0?RF:{files:t,pathPrefixes:n}}function kF(e){let t=new Map;for(let{manifest:n,packageRoot:r}of FS(e)){let i=FF(n);for(let s of i)LS(e,r,s,"package binary",t);let o=n.scripts;if(!(!o||typeof o!="object")){for(let[s,a]of Object.entries(o))if(typeof a=="string")for(let c of NF(a))LS(e,r,c,`package script "${s}"`,t)}}return t.size===0?EF:{reasonsByFile:t}}function FS(e){let t=[],n=_S(e,"");return n&&t.push({manifest:n,packageRoot:""}),NS(e,"",t,0),t}function NS(e,t,n,r){if(r>=LF)return;let i=zo(e,t);if(ic(i))for(let o of DS(i,{withFileTypes:!0})){if(!o.isDirectory()||wF.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=_S(e,s);a&&n.push({manifest:a,packageRoot:s}),NS(e,s,n,r+1)}}function _S(e,t){let n;try{n=ve(e,zo(t,"package.json"),{maxBytes:8*1024*1024,inputKind:"package manifest"})}catch(r){if(!Ce(r))throw r;return null}try{let r=JSON.parse(n);return r&&typeof r=="object"?r:null}catch{return null}}function AF(e){let t=[];for(let r of["main","module","types","browser"])typeof e[r]=="string"&&t.push(e[r]);let n=e.bin;if(typeof n=="string")t.push(n);else if(n&&typeof n=="object")for(let r of Object.values(n))typeof r=="string"&&t.push(r);return OS(e.exports,t),t}function FF(e){let t=e.bin;return typeof t=="string"?[t]:!t||typeof t!="object"?[]:Object.values(t).filter(n=>typeof n=="string")}function NF(e){let t=[],n=/(?:^|&&|\|\||;)\s*(?:(?:cross-env|env)(?:\s+[A-Za-z_][A-Za-z0-9_]*=\S+)*\s+)?(?:node|bun|tsx|ts-node|vite-node|python3?|deno\s+run)\s+(?:(?:--?[A-Za-z0-9-]+(?:=\S+)?)\s+)*["']?([^"'`\s]+\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs|py))["']?/g;for(let r of e.matchAll(n)){let i=r[1];i&&!i.startsWith("node_modules/")&&!i.startsWith("./node_modules/")&&t.push(i)}return t}function LS(e,t,n,r,i){let o=new Set;BS(e,t,n,o,[]);for(let s of o){let a=i.get(s)??[];a.includes(r)||a.push(r),i.set(s,a)}}function OS(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))OS(n,t)}function BS(e,t,n,r,i){let o=n.replace(/\\/g,"/").replace(/^\.\//,"");if(o===""||o.startsWith(".."))return;let s=o.indexOf("*");if(s>=0){let c=o.slice(0,s);for(let u of PS(c))u!==""&&i.push(Pn(t,u));return}let a=o.replace(IF,"");for(let c of PS(a)){c===a&&c===o&&r.add(Pn(t,o));for(let u of MS)_F(e,r,t,c+u)}r.add(Pn(t,o))}function PS(e){let t=[e];return Dd.test(e)&&(t.push(e.replace(Dd,"src/")),t.push(e.replace(Dd,""))),t}function _F(e,t,n,r){let i=Pn(n,r);if(t.add(i),!r.startsWith("src/")||ic(zo(e,i)))return;let o=MS.find(l=>r.endsWith(l));if(!o)return;let s=r.slice(0,-o.length);OF(e,t,n,s,o);let a=s.lastIndexOf("/");if(a<=4)return;let c=s.slice(0,a),u=s.slice(a+1);for(let l of $S(e,n,c,`${u}${o}`))t.add(l)}function OF(e,t,n,r,i){let o=Pn(n,`${r}/index${i}`);ic(zo(e,o))&&t.add(o)}function $S(e,t,n,r){let i=zo(e,t,n);if(!ic(i))return[];let o=[];for(let s of DS(i,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...$S(e,t,a,r)):s.isFile()&&s.name===r&&o.push(Pn(t,a))}return o}function Pn(e,t){return e?`${e}/${t}`:t}import{existsSync as Md,readdirSync as BF}from"fs";import{dirname as $F,join as Td}from"path";var jF={rootFiles:new Set,sourcePrefixes:[]},HF=new Set([".git",".scipquery","node_modules","target"]),UF=6,qF=te("rust-library-surface",{clearGroups:["whole-project"]});function jS(e,t,n){if(!n.endsWith(".rs")||!KF(GF(e),n))return!1;let r=q(e,n).find(i=>i.symbol===t);return r?WF(K(e,n)[r.startLine]??""):!1}function GF(e){return qF.get(e,()=>zF(e.config.projectRoot))}function zF(e){let t=new Set,n=new Set;for(let r of VF(e)){let i=ve(e,Td(r,"Cargo.toml"),{maxBytes:8388608,inputKind:"Cargo manifest"}),o=YF(i),s=Pn(r,"src/lib.rs"),a=o?Pn(r,o):!JF(i)&&wt(e,s)?s:null;if(!a)continue;t.add(a);let c=$F(a).replaceAll("\\","/");n.add(c==="."?"":`${c}/`)}return t.size===0?jF:{rootFiles:t,sourcePrefixes:[...n].sort()}}function KF(e,t){return t.endsWith(".rs")?e.rootFiles.has(t)?!0:XF(t)?!1:e.sourcePrefixes.some(n=>t.startsWith(n)):!1}function WF(e){return/^\s*pub\s+(?!\()/.test(e)}function VF(e){if(!Md(e))return[];let t=[];return HS(e,"",t,0),t}function HS(e,t,n,r){let i=Td(e,t);if(Md(i)&&(Md(Td(i,"Cargo.toml"))&&n.push(t),!(r>=UF)))for(let o of BF(i,{withFileTypes:!0})){if(!o.isDirectory()||HF.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name;HS(e,s,n,r+1)}}function YF(e){let t=!1;for(let n of e.split(`
57
- `)){let r=n.replace(/\s+#.*$/,"").trim(),i=/^\[([^\]]+)\]$/.exec(r);if(i){t=i[1]==="lib";continue}if(!t)continue;let o=/^path\s*=\s*["']([^"']+)["']/.exec(r)?.[1];if(o)return o.replaceAll("\\","/").replace(/^\.\//,"")}return null}function JF(e){let t=!1;for(let n of e.split(`
58
- `)){let r=n.replace(/\s+#.*$/,"").trim(),i=/^\[([^\]]+)\]$/.exec(r);if(i){t=i[1]==="package";continue}if(t&&/^autolib\s*=\s*false\b/.test(r))return!0}return!1}function XF(e){return/(?:^|\/)src\/main\.rs$/.test(e)||/(?:^|\/)src\/bin\//.test(e)||/(?:^|\/)(?:examples|tests|benches)\//.test(e)}import{existsSync as QF,readdirSync as ZF}from"fs";import{join as e0}from"path";var t0=/^(?:[\w.-]+\.config\.[cm]?[jt]s|package\.json)$/,n0=/(?:\.{1,2}\/)?[\w@./-]+\.(?:[cm]?[jt]sx?)\b/g,r0=te("config-referenced-files",{clearGroups:["whole-project"]});function i0(e){return r0.get(e,()=>o0(e))}function US(e,t){return i0(e).has(pe(t))}function o0(e){let t=new Set,n=e.config.projectRoot,r;try{r=ZF(n)}catch{return t}let i=r.filter(s=>t0.test(s)&&QF(e0(n,s)));if(i.length===0)return t;let o=new Set(Q(e,{includeIgnored:!1}).map(s=>pe(s)));for(let s of i){let a;try{a=ve(n,s,{inputKind:"root configuration file"})}catch(c){if(Ce(c))continue;continue}for(let c of a.matchAll(n0)){let u=pe(c[0]).replace(/^\.\//,"");u.startsWith("..")||u.startsWith("/")||o.has(u)&&t.add(u)}}return t}import{existsSync as kd,readdirSync as s0}from"fs";import{join as oc}from"path";var a0=["trigger.config.ts","trigger.config.mts","trigger.config.js","trigger.config.mjs"],c0=["./src/trigger","./trigger"],l0=/\bdirs\s*:\s*\[([^\]]*)\]/,u0=/["'`]([^"'`]+)["'`]/g,d0=["","apps","packages","services"],m0=te("framework-task-surface",{clearGroups:["whole-project"]});function p0(e){return m0.get(e,()=>f0(e))}function qS(e,t){let n=pe(t);return p0(e).directories.some(r=>n===r.directory||n.startsWith(`${r.directory}/`))}function f0(e){let t=new Map;for(let n of g0(e.config.projectRoot))for(let r of h0(e,n))t.has(r)||t.set(r,{directory:r,framework:"trigger.dev",config:n});return{directories:[...t.values()].sort((n,r)=>n.directory.localeCompare(r.directory))}}function g0(e){let t=[],n=r=>{for(let i of a0){let o=r?`${r}/${i}`:i;kd(oc(e,o))&&t.push(o)}};n("");for(let r of d0.slice(1)){let i=oc(e,r);if(!kd(i))continue;let o;try{o=s0(i)}catch{continue}for(let s of o)n(`${r}/${s}`)}return t}function h0(e,t){let n;try{n=ve(e.config.projectRoot,t,{inputKind:"framework task config"})}catch(a){return Ce(a)?[]:[]}let r=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",i=l0.exec(n)?.[1],o=i?[...i.matchAll(u0)].map(a=>a[1]):c0,s=[];for(let a of o){let c=pe(oc(r,a)).replace(/\/+$/,"");c===""||c.startsWith("..")||kd(oc(e.config.projectRoot,c))&&s.push(c)}return s}function Ur(e){return U(e)==="barrel"}function zS(e){return y0.get(e,()=>{let n=Q(e,{includeIgnored:!1}).filter(s=>{let a=U(s);return a==="entry"||a==="worker"});if(n.length===0)return new Set;let r=_e(e),i=new Set,o=new Set;for(;n.length>0;){let s=n.shift();if(!i.has(s)){i.add(s),U(s)==="barrel"&&o.add(s);for(let a of r.get(s)??[])i.has(a)||n.push(a)}}return o})}var y0=te("live-barrels",{clearGroups:["whole-project"]});function Ad(e,t){return zS(e).has(pe(t))}function KS(e){let t=zS(e);return Q(e,{includeIgnored:!1}).filter(n=>Ur(n)&&!t.has(n)&&!b0(e,n))}function b0(e,t){let n=pe(t),r=Sn(e).forFile(n,{facts:!0}).facts?.callables;return r&&r.length>0?!0:(e.get(`SELECT COUNT(*) AS n
59
- FROM defn_enclosing_ranges der
60
- JOIN documents d ON d.id = der.document_id
61
- WHERE d.relative_path = ?
62
- AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function ze(e,t){let n=pe(t),r=U(t);return r==="entry"||r==="worker"||Mn(n)||qS(e,n)||US(e,n)||Ad(e,n)}function Ni(e,t,n){let r=pe(n),i=[];Dn(e,r)&&i.push("package-surface-file"),C0(e,t,r)&&i.push("transitive-package-surface"),jS(e,t,r)&&i.push("rust-public-library"),F0(t,r)&&i.push("framework-entrypoint");let o=e.config.entryRoots;return o&&(o.files?.some(s=>pe(s)===r)&&i.push("configured-file"),o.pathPrefixes?.some(s=>r.startsWith(pe(s)))&&i.push("configured-path-prefix"),o.qualifiedVars?.some(s=>_0(t,s))&&i.push("configured-qualified-var"),o.symbolPatterns?.some(s=>{try{return jr(s,"entryRoots.symbolPatterns entry").test(t)}catch{return!1}})&&i.push("configured-symbol-pattern")),i}function Be(e,t,n){return Ni(e,t,n).length>0}var S0=te("package-surface-reachability",{clearGroups:["whole-project"]}),v0=te("explicit-package-surface-reachability",{clearGroups:["whole-project"]});function C0(e,t,n){let r=x0(e).get(n);return r===void 0?!1:r===null||r.has(G(t))}function WS(e,t,n){let r=R0(e).get(n);return r===void 0?!1:r===null||r.has(G(t))}function x0(e){return S0.get(e,()=>VS(e,t=>Dn(e,t)))}function R0(e){return v0.get(e,()=>VS(e,t=>kS(e,t)))}function VS(e,t){let n=new Map,r=[];for(let i of Q(e,{includeIgnored:!1}))t(i)&&(n.set(i,null),r.push(i));for(;r.length>0;){let i=r.shift(),o=n.get(i);if(o!==void 0)for(let s of bn(e,i)){if(!s.sourcePath||e.isIgnored(s.sourcePath))continue;let a=E0(o,s);a!==void 0&&I0(n,s.sourcePath,a)&&r.push(s.sourcePath)}}return n}function E0(e,t){if(e===null)return t.kind==="named"?new Set(t.names):null;if(t.kind==="star")return new Set(e);if(t.kind==="star-as")return t.names.some(r=>e.has(r))?null:void 0;let n=t.names.filter(r=>e.has(r));return n.length>0?new Set(n):void 0}function I0(e,t,n){if(!e.has(t))return e.set(t,n),!0;let r=e.get(t);if(r===void 0)return!1;if(r===null||n===null)return r===null?!1:(e.set(t,null),!0);let i=!1;for(let o of n)r.has(o)||(r.add(o),i=!0);return i}var YS=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),w0=new Set(["default","generateMetadata","generateStaticParams"]),L0=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),P0=new Set(["default","middleware","config"]),D0=new Set(["register","onRequestError"]),M0=new Set(["onRouterTransitionStart"]),T0=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),k0=new Set(["load","actions","entries",...YS]),A0=new Set(["default"]);function F0(e,t){let n=G(e);return n===""?!1:JS(t)?YS.has(n):XS(t)?w0.has(n):QS(t)?L0.has(n):ZS(t)?P0.has(n):ev(t)?D0.has(n):tv(t)?M0.has(n):nv(t)?T0.has(n):rv(t)?k0.has(n):N0(t)?A0.has(n):!1}function Mn(e){return JS(e)||XS(e)||QS(e)||ZS(e)||ev(e)||tv(e)||nv(e)||rv(e)}function JS(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function XS(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function QS(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function ZS(e){return Fd(e,"(?:middleware|proxy)\\.(?:ts|js|mts|mjs)")}function ev(e){return Fd(e,"instrumentation\\.(?:ts|js|mts|mjs)")}function tv(e){return Fd(e,"instrumentation-client\\.(?:ts|js|mts|mjs)")}function Fd(e,t){return new RegExp(`^(?:src/)?${t}$`).test(e)||new RegExp(`(?:^|/)src/${t}$`).test(e)||new RegExp(`(?:^|/)(?:apps|services|packages)/[^/]+/(?:src/)?${t}$`).test(e)}function nv(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function rv(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function N0(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function _0(e,t){let n=t.lastIndexOf("/");if(n<0)return!1;let r=t.slice(0,n),i=t.slice(n+1);return e.includes(GS(r)+"/")&&e.includes(GS(i)+".")}function GS(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function ee(e){return e.endLine-e.startLine+1}function sc(e,t={}){let{scope:n,files:r,minLoc:i=1,maxLoc:o=Number.POSITIVE_INFINITY,excludeSymbol:s,excludeEntrySurfaces:a=!1,excludeTypesFiles:c=!1,excludeRootedSymbols:u=!1,requireFunctionLikeSymbol:l=!1,requireCallableSymbol:d=!1,excludeRustTraitImplMembers:m=!1,includeSuppressed:p=!1,sortByLocDesc:f=!1}=t,g=[],h=O0(e,{scope:n,files:r,requireFunctionLikeSymbol:l,requireCallableSymbol:d}),y=new Map,S=new Map,b=v=>{let C=y.get(v);if(C!==void 0)return C;let R=ze(e,v);return y.set(v,R),R},x=v=>{let C=S.get(v);if(C!==void 0)return C;let R=U(v);return S.set(v,R),R};for(let v of h){let C=v.relativePath;if(e.isIgnored(C)||a&&b(C)||!B0(v,{requireFunctionLikeSymbol:l,requireCallableSymbol:d})||s!==void 0&&v.symbol===s)continue;let R=ee(v);R<i||R>o||c&&$0(C)||u&&Be(e,v.symbol,C)||m&&Ge(v.symbol)||x(C)!=="test"&&(gi(v.symbol)||!p&&zs(e,C,v.startLine)||g.push(v))}return f?g.sort((v,C)=>ee(C)-ee(v)):g}function O0(e,t){return t.files!==void 0?[...new Set(t.files.map(r=>r.replace(/\\/g,"/")))].sort().filter(r=>!t.scope||r.includes(t.scope)).flatMap(r=>q(e,r)):t.requireCallableSymbol?po(e,{scope:t.scope,symbolMatches:Qe,sqlPrefilter:"callable"}):t.requireFunctionLikeSymbol?po(e,{scope:t.scope,symbolMatches:Re,sqlPrefilter:"function-like"}):yg(e,t.scope)}function B0(e,t){return t.requireCallableSymbol?Qe(e.symbol):t.requireFunctionLikeSymbol?Re(e.symbol):e.isFunctionLike}function $0(e){return(e.split("/").pop()??"").includes("types")}import{statSync as j0}from"fs";function qr(e){let t=e.get("SELECT COUNT(*) as c FROM documents").c,n=e.get("SELECT COUNT(*) as c FROM global_symbols").c,r=e.get("SELECT COUNT(*) as c FROM mentions WHERE role = 1").c,i=e.get("SELECT COUNT(*) as c FROM mentions WHERE role != 1").c;return{documents:t,symbols:n,definitions:r,references:i,...H0(e.generation.databasePath)}}function H0(e){try{let t=j0(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function U0(e,t){return ru(e).filter(n=>q0({pattern:t,relativePath:n})).map(n=>({relativePath:n}))}function q0(e,t){let n=typeof e=="string"?{pattern:e,relativePath:t}:e;if(typeof n.pattern!="string"||typeof n.relativePath!="string")throw new TypeError("pathMatchesGlob requires pattern and relativePath.");let r=hn(n.pattern),i=hn(n.relativePath);if(!/[*?]/.test(r))return i.includes(r);let o=r.includes("/")?r:`**/${r}`;return ac(o.split("/"),i.split("/"))}function ac(e,t){if(e.length===0)return t.length===0;let[n,...r]=e;return n==="**"?ac(r,t)||t.length>0&&ac(e,t.slice(1)):t.length===0||!G0(n??"",t[0]??"")?!1:ac(r,t.slice(1))}function G0(e,t){let n="^";for(let r of e)r==="*"?n+="[^/]*":r==="?"?n+="[^/]":n+=z0(r);return n+="$",new RegExp(n).test(t)}function z0(e){return/[\\^$.*+?()[\]{}|]/.test(e)?`\\${e}`:e}function ov(e,t,n){let r=[],i=[],o=new Map;for(let s of[...e].sort(n)){let a=s.channel??"default",c=t[a]??Number.MAX_SAFE_INTEGER,u=o.get(a)??0;if(u>=c){i.push(s);continue}r.push(s),o.set(a,u+1)}return{selected:r,omitted:i}}function cc(e,t,n,r,i=!1){let o=[...e],s=[],a=new Set,c=0;for(;o.length>0&&s.length<t;){let u=o.filter(m=>c+m.evidenceCharacters<=n||i&&s.length===0);if(u.length===0)break;let l=u.filter(m=>m.roles.includes("location")||m.roles.includes("definition")).sort(r);u.sort((m,p)=>iv(p,a)-iv(m,a)||r(m,p));let d=l[0]??u[0];s.push(d),c+=d.evidenceCharacters;for(let m of sv(d))a.add(m.key);o.splice(o.indexOf(d),1)}return{selected:s,omitted:o.sort(r)}}function iv(e,t){let n=sv(e).reduce((o,s)=>o+(t.has(s.key)?0:s.weight),0),r=Math.max(0,8-e.priority)*20,i=Math.min(500,Math.ceil(e.evidenceCharacters/160));return n+r-i}function sv(e){return[...e.reasons.map(K0),...e.roles.map(t=>({key:`role:${t}`,weight:W0(t)})),{key:`file:${e.relativePath}`,weight:180},{key:`scope:${V0(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 K0(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 W0(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 V0(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}var av=64,cv=12;function lc(e,t,n={}){if(t.length===0)return[];let r=n.context??6;if(!Number.isSafeInteger(r)||r<0)throw new RangeError(`context must be a non-negative safe integer; received ${r}`);let i=n.limit??12;if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`limit must be a positive safe integer; received ${i}`);let o=t.map(s=>{if(s.length===0)throw new Error("The source search pattern must not be empty.");return{pattern:s,regexp:n.regexp?jr(s,"source search pattern",n.ignoreCase?"iu":"u"):null,literal:n.ignoreCase?s.toLocaleLowerCase():s,identities:[],fileCoverage:[],textByPath:new Map}});if(!n.regexp&&!n.ignoreCase){let s=o.map(c=>Buffer.from(c.pattern,"utf8")),a=pa(e,{scope:n.scope,literalBytes:s.length===1?s[0]:s},(c,u)=>{let l=$n(c.text);if(l.length!==0)for(let d of u){let m=o[d];m&&lv(e,m,c,l,n)}});return o.map(c=>uv(c,a,r,i,n))}return o.map(s=>{let a=pa(e,{scope:n.scope},c=>{let u=$n(c.text);u.length>0&&lv(e,s,c,u,n)});return uv(s,a,r,i,n)})}function lv(e,t,n,r,i){let o=[];for(let u=0;u<r.length;u+=1){let l=r[u]??"",d=l.endsWith("\r")?l.slice(0,-1):l;(t.regexp?t.regexp.test(d):(i.ignoreCase?d.toLocaleLowerCase():d).includes(t.literal))&&o.push(u)}if(o.length===0)return;let s=n.relativePath;t.textByPath.set(s,n.text);let a=n.freshness.semantic.state!=="stale"&&n.freshness.semantic.basis!=="no-compiler-document"?q(e,s):[],c=W(e,s)?.callables??[];for(let u of o){let l=Oe(a,u),d=jn(c,u),m=l&&!fe(l.symbol)?l:null,p=m?.startLine??d?.startLine??l?.startLine??u,f=m?.endLine??d?.endLine??l?.endLine??u,g=wo(e,s,u,p,f);t.identities.push({relativePath:s,focusLine:u,ownerSymbol:m?.symbol??null,ownerShort:m?T(m.symbol):d?.name??(l?T(l.symbol):null),ownerStartLine:g.startLine,ownerEndLine:g.endLine,fileKind:U(s),freshness:n.freshness})}t.fileCoverage.push({relativePath:s,matchingLines:o.length,returnedMatches:0,freshness:n.freshness})}function uv(e,t,n,r,i){e.identities.sort(mv);let o=e.identities.length>av?dv(e.identities,av):e.identities,a=(r===Number.MAX_SAFE_INTEGER?e.identities:i.ranking?dv(e.identities,r):e.identities.slice(0,r)).flatMap(l=>{let d=e.textByPath.get(l.relativePath),m=d===void 0?null:Y0(l.relativePath,d,l.focusLine,n);return m?[{...m,...l}]:[]}),c=new Map;for(let l of a)c.set(l.relativePath,(c.get(l.relativePath)??0)+1);for(let l of e.fileCoverage)l.returnedMatches=c.get(l.relativePath)??0;let u=J0(e.fileCoverage);return{pattern:e.pattern,mode:i.regexp?"regexp":"literal",identities:e.identities,...o.length<e.identities.length?{identityManifest:o}:{},identityCoverage:{mode:o.length===e.identities.length?"complete":"bounded",returned:o.length,total:e.identities.length,omitted:e.identities.length-o.length},matches:a,matchingLines:e.identities.length,matchingFiles:e.fileCoverage.length,omittedMatches:Math.max(0,e.identities.length-a.length),fileCoverage:e.fileCoverage,scopeHints:u.slice(0,cv),omittedScopeHints:Math.max(0,u.length-cv),scannedFiles:t.scannedTextFiles,textCoverage:{basis:"current-project-text-files",candidateFiles:t.candidateFiles,scannedTextFiles:t.scannedTextFiles,scannedBytes:t.scannedBytes,skippedBinaryPaths:t.skippedBinaryPaths,skippedUnreadablePaths:t.skippedUnreadablePaths,skippedOversizedPaths:t.skippedOversizedPaths,semanticFiles:t.semanticFiles}}}function Y0(e,t,n,r){let i=t.split(`
63
- `),o=t.endsWith(`
64
- `)?i.length-1:i.length;if(n<0||n>=o)return null;let s=Math.max(0,n-r),a=Math.min(o-1,n+r);return{relativePath:e,startLine:s,endLine:a,focusLine:n,source:i.slice(s,a+1).join(`
65
- `)}}function J0(e){let t=new Map;for(let n of e){let r=X0(n.relativePath),i=t.get(r)??{matchingLines:0,matchingFiles:0};i.matchingLines+=n.matchingLines,i.matchingFiles+=1,t.set(r,i)}return[...t.entries()].map(([n,r])=>({scope:n,...r})).sort((n,r)=>r.matchingLines-n.matchingLines||r.matchingFiles-n.matchingFiles||n.scope.localeCompare(r.scope))}function X0(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}function dv(e,t){let n=e.map((i,o)=>({...i,priority:we(i.fileKind),sequence:o,evidenceCharacters:1,roles:["search"],reasons:["search"],symbols:i.ownerSymbol?[i.ownerSymbol]:[],behaviorSignals:[]})),r=[];for(let i of[0,1,2]){let o=t-r.length;if(o===0)break;let s=n.filter(a=>we(a.fileKind)===i);r.push(...cc(s,o,Number.MAX_SAFE_INTEGER,mv).selected)}return r.map(({priority:i,sequence:o,evidenceCharacters:s,roles:a,reasons:c,symbols:u,behaviorSignals:l,...d})=>d)}function mv(e,t){return we(e.fileKind)-we(t.fileKind)||+(t.ownerSymbol!==null)-+(e.ownerSymbol!==null)||e.relativePath.localeCompare(t.relativePath)||e.focusLine-t.focusLine}function Q0(e,t,n={}){if(t.length===0)throw new Error("The source search pattern must not be empty.");return lc(e,[t],n)[0]}function uc(e,t){return ee(e)-ee(t)||e.relativePath.localeCompare(t.relativePath)}function be(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function _i(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}`;t.has(i)||(t.add(i),n.push(r))}return n}function $e(e){return[...new Set((e??[]).map(t=>t.trim()).filter(Boolean))]}function Ke(e){return e.replace(/^#/u,"").replace(/\(\)$/u,"")}var pv=new WeakMap,fv=new WeakMap,gv=new WeakMap,hv=new WeakMap,yv=new WeakMap;function bv(e,t){let n=fv.get(e);n||(n=new Map,fv.set(e,n));let r=n.get(t);if(r)return r;let i=J(e,t)?.rootNode;if(!i)return n.set(t,[]),[];let o=new Set;rn(i,u=>{if(u.type!=="call_expression")return;let l=u.childForFieldName("function")??u.namedChild(0),d=/^([A-Za-z_$][\w$]*(?:\.Service)?)\.of$/u.exec(l?.text.replace(/\s+/gu,"")??"");d&&o.add(d[1])});let s=ce(e,t).filter(u=>!!u.sourcePath),a=new Set;for(let u of o){let l=/^([A-Za-z_$][\w$]*)\.Service$/u.exec(u);if(l){for(let d of s)d.localName===l[1]&&a.add(d.sourcePath);continue}if(u==="Service"){q(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=Od([...a]).sort();return n.set(t,c),c}function sr(e,t,n={}){let i=Jt(e,t)?.filter(p=>!n.ranges||n.ranges.some(f=>p.line>=f.startLine&&p.line<=f.endLine));if(!i)return{targets:[],unresolvedCallsites:0};let o=ce(e,t).filter(p=>!!p.sourcePath),s=gN(V(e,t)??""),a=J(e,t)?.rootNode??null,c=a?eN(a):Sv(),u=new Map,l=Xt(e),d=[],m=0;for(let p of i){if(!p.memberAccess)continue;let f=Ht(t,l.get(p.calleeLeaf)??[]);if(n.excludeIndexedTargets!==!1&&Gn(e,t,f,!0,p.calleeQualifier))continue;let g=p.calleeQualifier,h=pN(e,t,p,o);if(h){d.push(h);continue}let y=Z0(e,t,p,o,tN(c,p.calleeQualifier,p.line));if(y.length>0){d.push(...y);continue}let S=nN(e,t,p);if(S.length>0){d.push(...S);continue}let b=g?s.get(g)??g:null,v=(b?Od(o.filter(R=>(R.localName??R.importedName)===b).map(R=>R.sourcePath)):[]).flatMap(R=>{let E=u.get(R);return E||(E=Mt(e,R)??[],u.set(R,E)),E.filter(w=>w.name===p.calleeLeaf).map(w=>({file:R,callable:w}))});if(v.length!==1){m+=1;continue}let C=v[0];d.push({calleeLeaf:p.calleeLeaf,line:p.line,sourceFile:t,targetFile:C.file,targetStartLine:C.callable.startLine,targetEndLine:C.callable.endLine,resolution:"direct-import-receiver",strength:"candidate"})}return{targets:d,unresolvedCallsites:m}}function Z0(e,t,n,r,i){let o=n.calleeQualifier;if(!o||!/^[A-Za-z_$][\w$]*$/u.test(o))return[];if(i.size!==1)return[];let s=[...i][0],a=Od(r.filter(l=>l.localName===s||l.importedName===s).map(l=>l.sourcePath));if(a.length!==1)return[];let c=a[0],u=sN(e,c,n.calleeLeaf);return u.map(l=>({calleeLeaf:l.name,line:n.line,sourceFile:t,targetFile:l.file,targetStartLine:l.startLine,targetEndLine:l.endLine,serviceFile:c,resolutionAlternativeCount:u.length,resolution:"imported-service-object-member",strength:"candidate"}))}function Sv(){return{declarations:new Map,callbacks:[]}}function eN(e){let t=Sv();return rn(e,n=>{if(n.type==="variable_declarator"){let c=n.childForFieldName("name")??n.namedChild(0),u=n.childForFieldName("value")??n.namedChild(1);if(c?.type!=="identifier"||!u)return;let l=new Set;if(rn(u,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"&&l.add(m.text)}),l.size===1){let d=t.declarations.get(c.text)??[];d.push({line:n.startPosition.row,alias:[...l][0]}),t.declarations.set(c.text,d)}return}if(!["arrow_function","function_expression","generator_function"].includes(n.type))return;let r=n.childForFieldName("parameters")??n.childForFieldName("parameter");if(!r)return;let i=n.parent;for(;i&&i.type!=="call_expression";)i=i.parent;if(!i)return;let o=i.childForFieldName("function")??i.namedChild(0),s=/^([A-Za-z_$][\w$]*)\.Service\.use$/u.exec(o?.text??"");if(!s)return;let a=new Set;rn(r,c=>{c.type==="identifier"&&a.add(c.text)}),a.size!==0&&t.callbacks.push({startLine:n.startPosition.row,endLine:n.endPosition.row,receivers:a,alias:s[1]})}),t}function tN(e,t,n){if(!t||!/^[A-Za-z_$][\w$]*$/u.test(t))return new Set;let r=new Set((e.declarations.get(t)??[]).filter(i=>i.line<=n).map(i=>i.alias));for(let i of e.callbacks)i.startLine<=n&&i.endLine>=n&&i.receivers.has(t)&&r.add(i.alias);return r}function nN(e,t,n){let r=n.calleeQualifier;if(!r||!/^[A-Za-z_$][\w$]*$/u.test(r))return[];let i=J(e,t)?.rootNode;if(!i)return[];let o=rN(e,t,i,n.line,n.calleeLeaf,r),s=o?oN(o,r):null;if(!s)return[];if(!iN(s))return[];let a=(Mt(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=q(e,t).filter(p=>p.isFunctionLike&&p.leaf===a.name);if(c.length!==1)return[];let u=c[0],l=hv.get(e);l||(l=new Map,hv.set(e,l));let d=`${u.symbol}\0${n.calleeLeaf}`,m=l.get(d);if(!m){let p=[];for(let f of fo(e,u)){let g=J(e,f.file)?.rootNode;if(!g)continue;let h=Ws(g,"call_expression").filter(b=>b.startPosition.row>f.line||b.endPosition.row<f.line?!1:(b.childForFieldName("function")??b.namedChild(0))?.text.replace(/\s+/gu,"").replace(/<[^<>]*>$/u,"").match(/[A-Za-z_$][\w$]*$/u)?.[0]===u.leaf);if(h.length!==1)continue;let S=h[0].childForFieldName("arguments")?.namedChildren.find(b=>Gr(b).type==="object");if(S)for(let b of Gr(S).namedChildren){if(b.type==="shorthand_property_identifier"&&b.text===n.calleeLeaf){p.push(...dc(e,f.file,n.calleeLeaf,b,b));continue}if(b.type!=="pair")continue;let x=b.childForFieldName("key")??b.namedChild(0),v=b.childForFieldName("value")??b.namedChild(1);mc(x?.text)!==n.calleeLeaf||!v||p.push(...dc(e,f.file,n.calleeLeaf,v,b))}}m=p.filter((f,g,h)=>h.findIndex(y=>y.file===f.file&&y.startLine===f.startLine&&y.endLine===f.endLine&&y.name===f.name)===g),l.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 rN(e,t,n,r,i,o){let s=gv.get(e);s||(s=new Map,gv.set(e,s));let a=s.get(t);if(!a){a=new Map;for(let c of Ws(n,"call_expression")){let u=c.childForFieldName("function")??c.namedChild(0),l=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(u?.text.replace(/\s+/gu,"")??"");if(l)for(let d=c.startPosition.row;d<=c.endPosition.row;d+=1){let m=`${d}\0${l[1]}\0${l[2]}`,p=a.get(m);(!p||c.endIndex-c.startIndex<p.endIndex-p.startIndex)&&a.set(m,c)}}s.set(t,a)}return a.get(`${r}\0${o}\0${i}`)??null}function iN(e){return e.descendantsOfType("return_statement").some(t=>{let n=t.childForFieldName("argument")??t.namedChild(0);return!!(n&&Gr(n).type==="object")})}function oN(e,t){let n=e.parent;for(;n;){if(/(?:function|method|lambda)/u.test(n.type)||n.type==="arrow_function"){let r=n.childForFieldName("parameters")??n.childForFieldName("parameter"),i=!1;if(r&&rn(r,o=>{o.type==="identifier"&&o.text===t&&(i=!0)}),i)return n}n=n.parent}return null}function dc(e,t,n,r,i){if(r.type==="identifier")return(Mt(e,t)??[]).filter(c=>c.name===r.text).map(c=>({...c,file:t}));let o=Nd(e,t,r.text);if(o.length>0)return o;if(!_d(r))return[];let a=(Mt(e,t)??[]).filter(c=>c.startLine>=i.startPosition.row&&c.endLine<=i.endPosition.row&&(c.name===n||c.name.startsWith("source@"))).sort((c,u)=>c.endLine-c.startLine-(u.endLine-u.startLine))[0];return[a?{...a,file:t}:{name:n,file:t,startLine:i.startPosition.row,endLine:i.endPosition.row}]}function sN(e,t,n){let r=yv.get(e);r||(r=new Map,yv.set(e,r));let i=`${t}\0${n}`,o=r.get(i);if(o)return o;let s=lN(e,t).flatMap(a=>aN(e,a,t,n));return r.set(i,s),s}function aN(e,t,n,r){let i=J(e,t)?.rootNode,o=Mt(e,t)??[];if(!i)return[];let s=uN(e,t,n);if(s.size===0)return[];let a=new Set,c=[],u=[],l=[];return rn(i,m=>{if(cN(m,s)){if(m.type==="pair"){let p=m.childForFieldName("key")??m.namedChild(0),f=m.childForFieldName("value")??m.namedChild(1);if(mc(p?.text)!==r||!f)return;if(f.type==="identifier")a.add(f.text);else if(_d(f))c.push({name:r,startLine:m.startPosition.row,endLine:m.endPosition.row});else{let g=dN(e,t,f.text),h=Nd(e,t,f.text);if(g.length>0)l.push(...g);else if(h.length>0)l.push(...h);else{let y=mN(m);y&&u.push(y)}}return}m.type==="shorthand_property_identifier"&&m.text===r&&a.add(r)}}),[...o.filter(m=>a.has(m.name)).map(m=>({...m,file:t})),...c.map(m=>({...m,file:t})),...u.map(m=>({...m,file:t})),...l].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 cN(e,t){let n=e,r=null;for(;n;){if(n.type==="object"&&(r=n),n.type==="call_expression"){if(!r)return!1;let i=n.childForFieldName("function")??n.namedChild(0);return i?t.has(i.text.replace(/\.of$/u,""))&&i.text.endsWith(".of"):!1}n=n.parent}return!1}function lN(e,t){let n=pv.get(e);n||(n=new Map,pv.set(e,n));let r=n.get(t);if(r)return r;let i=new Set([t]),o=q(e,t).filter(a=>a.leaf==="Service"&&a.isTypeLike);for(let a of o)for(let c of fo(e,a))i.add(c.file);let s=[...i].sort();return n.set(t,s),s}function uN(e,t,n){let r=new Set;ke(t,n)&&r.add("Service");for(let i of ce(e,t)){if(!i.sourcePath||!ke(i.sourcePath,n))continue;if(i.kind==="namespace"&&i.localName){r.add(`${i.localName}.Service`);continue}(i.importedName==="default"?i.localName:i.importedName)==="Service"?r.add(i.localName??i.importedName):i.localName&&i.importedName!=="default"&&r.add(`${i.localName}.Service`)}return r}function Nd(e,t,n){let r=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(n.replace(/\s+/gu,""));if(!r)return[];let i=J(e,t)?.rootNode;if(!i)return[];let o=vv(i,r[1]),s=o?Cv(o):null;if(!s)return[];let a=s.childForFieldName("function")??s.namedChild(0),c=a?xv(e,t,a.text):[];if(c.length!==1)return[];let u=c[0],l=J(e,u.relativePath)?.rootNode;if(!l)return[];let d=zl(l,u.startLine,u.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=Gr(f);if(g.type==="object")for(let h of g.namedChildren){if(h.type==="shorthand_property_identifier"&&h.text===r[2]){for(let b of Mt(e,u.relativePath)??[])b.name===r[2]&&m.push({...b,file:u.relativePath});continue}if(h.type!=="pair")continue;let y=h.childForFieldName("key")??h.namedChild(0),S=h.childForFieldName("value")??h.namedChild(1);if(!(mc(y?.text)!==r[2]||!S))if(S.type==="identifier")for(let b of Mt(e,u.relativePath)??[])b.name===S.text&&m.push({...b,file:u.relativePath});else _d(S)&&m.push({name:r[2],startLine:h.startPosition.row,endLine:h.endPosition.row,file:u.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 dN(e,t,n){let r=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(n.replace(/\s+/gu,""));if(!r)return[];let i=J(e,t)?.rootNode;if(!i)return[];let o=vv(i,r[1]),s=o?Cv(o):null,a=s?.childForFieldName("function")??s?.namedChild(0),c=a?xv(e,t,a.text):[];if(c.length!==1||!s)return[];let u=c[0],l=J(e,u.relativePath)?.rootNode;if(!l)return[];let d=zl(l,u.startLine,u.endLine);if(!d)return[];let m=new Set,p=d.childForFieldName("parameters")??d.childForFieldName("parameter");if(p&&rn(p,R=>{R.type==="identifier"&&m.add(R.text)}),m.size===0)return[];let f=Nd(e,t,n);if(f.length===0)return[];let g=(Mt(e,u.relativePath)??[]).filter(R=>R.startLine>=u.startLine&&R.endLine<=u.endLine),h=(Jt(e,u.relativePath)??[]).filter(R=>R.line>=u.startLine&&R.line<=u.endLine),y=new Set,S=f.map(R=>({name:R.name,startLine:R.startLine,endLine:R.endLine})),b=new Set;for(;S.length>0&&b.size<32;){let R=S.shift(),E=`${R.name}\0${R.startLine}\0${R.endLine}`;if(!b.has(E)){b.add(E);for(let w of h.filter(I=>I.line>=R.startLine&&I.line<=R.endLine)){if(w.memberAccess&&w.calleeQualifier&&m.has(w.calleeQualifier)){y.add(w.calleeLeaf);continue}if(w.memberAccess)continue;let I=g.filter(k=>k.name===w.calleeLeaf);I.length===1&&S.push(I[0])}}}if(y.size===0)return[];let v=s.childForFieldName("arguments")?.namedChildren.find(R=>Gr(R).type==="object");if(!v)return[];let C=[];for(let R of Gr(v).namedChildren){if(R.type==="shorthand_property_identifier"&&y.has(R.text)){C.push(...dc(e,t,R.text,R,R));continue}if(R.type!=="pair")continue;let E=R.childForFieldName("key")??R.namedChild(0),w=R.childForFieldName("value")??R.namedChild(1),I=mc(E?.text);!I||!y.has(I)||!w||C.push(...dc(e,t,I,w,R))}return C.filter((R,E,w)=>w.findIndex(I=>I.file===R.file&&I.name===R.name&&I.startLine===R.startLine&&I.endLine===R.endLine)===E)}function vv(e,t){for(let n of Ws(e,"variable_declarator"))if((n.childForFieldName("name")??n.namedChild(0))?.text===t)return n.childForFieldName("value")??n.namedChild(1);return null}function Cv(e){return e.type==="call_expression"?e:e.descendantsOfType("call_expression")[0]??null}function xv(e,t,n){let r=n.replace(/\s+/gu,"").replace(/<[^<>]*>$/u,""),i=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(r);if(i){let d=ce(e,t).filter(f=>f.localName===i[1]&&f.sourcePath);if(d.length!==1||!d[0].sourcePath)return[];let m=d[0].sourcePath,p=qn(e,m,i[2]).filter(f=>f.isFunctionLike);return p.length>0?p:(Mt(e,m)??[]).filter(f=>f.name===i[2]).map(f=>({...f,relativePath:m}))}if(!/^[A-Za-z_$][\w$]*$/u.test(r))return[];let o=q(e,t).filter(d=>d.leaf===r&&d.isFunctionLike);if(o.length>0)return o;let s=(Mt(e,t)??[]).filter(d=>d.name===r).map(d=>({...d,relativePath:t}));if(s.length>0)return s;let a=ce(e,t).filter(d=>d.localName===r&&d.sourcePath&&d.kind!=="namespace");if(a.length!==1||!a[0].sourcePath)return[];let c=a[0].sourcePath,u=a[0].importedName==="default"?r:a[0].importedName,l=qn(e,c,u).filter(d=>d.isFunctionLike);return l.length>0?l:(Mt(e,c)??[]).filter(d=>d.name===u).map(d=>({...d,relativePath:c}))}function _d(e){return["arrow_function","function_expression","generator_function"].includes(e.type)||e.descendantsOfType(["arrow_function","function_expression","generator_function"]).length>0}function mN(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 mc(e){return e?e.replace(/^(?:['"])(.*)(?:['"])$/u,"$1"):null}function pN(e,t,n,r){let i=/^this\.([A-Za-z_$][\w$]*)$/u.exec(n.calleeQualifier??"");if(!i)return null;let o=J(e,t)?.rootNode;if(!o)return null;let s=fN(o,n.line);if(!s)return null;let a=new Set;if(rn(s,g=>{if(g.type!=="assignment_expression")return;let h=g.childForFieldName("left")??g.namedChild(0),y=g.childForFieldName("right")??g.namedChild(g.namedChildCount-1);if(h?.text.replace(/\s+/gu,"")!==`this.${i[1]}`||!y)return;let S=Gr(y);if(S.type!=="new_expression")return;let x=(S.childForFieldName("constructor")??S.namedChild(0))?.text.match(/[A-Za-z_$][\w$]*$/u)?.[0];x&&a.add(x)}),a.size!==1)return null;let c=[...a][0],u=r.filter(g=>g.localName===c);if(u.length!==1)return null;let l=u[0].importedName==="default"?c:u[0].importedName,d=u[0].importedName==="default"?qn(e,u[0].sourcePath,c):[],m=d.length===1?d[0].leaf:l,p=q(e,u[0].sourcePath).filter(g=>g.isFunctionLike&&g.leaf===n.calleeLeaf&&mg(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 fN(e,t){let n=[];return rn(e,r=>{["class","class_declaration","class_definition"].includes(r.type)&&r.startPosition.row<=t&&r.endPosition.row>=t&&n.push(r)}),n.sort((r,i)=>r.endPosition.row-r.startPosition.row-(i.endPosition.row-i.startPosition.row))[0]??null}function Gr(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 rn(e,t){t(e);for(let n of e.namedChildren)rn(n,t)}function gN(e){let t=new Map,n=/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*([A-Za-z_$][\w$]*)\s*;/gu;for(let r of e.matchAll(n)){let i=r[1],o=r[2];i&&o&&t.set(i,o)}return t}function Od(e){let t=[];for(let n of e)t.some(r=>ke(r,n))||t.push(n);return t}function Bd(e,t,n={}){let r=new Map;if(t&&t.length===0)return r;let i=Q(e,{includeIgnored:!1}),o=Xt(e),s=t??ye(e),a=new Set(s.map(u=>u.symbolId)),c=xN(s);return hN(e,r,i,o,a,c),yN(e,r,s,a),CN(e,r,i,o,a,c),n.semantic!==!1&&n.semanticEvidence&&EN(r,n.semanticEvidence.callerMap(e,RN(s))),r}function hN(e,t,n,r,i,o){for(let s of n){if(!ae(s))continue;let a=Jt(e,s);if(a)for(let c of a){if(o&&!o.has(c.calleeLeaf))continue;let u=Ht(s,r.get(c.calleeLeaf)??[]);if(!u||u.length===0)continue;let l=Gn(e,s,u,c.memberAccess,c.calleeQualifier);l&&i.has(l.symbolId)&&l.file!==s&&$d(t,l.symbolId,s)}}}function yN(e,t,n,r){let i=SN(n);for(let o of bN(e,r))e.isIgnored(o.relative_path)||vN(o,i.get(o.symbol_id))||$d(t,o.symbol_id,o.relative_path)}function bN(e,t){return ea(e,t?[...t]:void 0)}function SN(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 vN(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function CN(e,t,n,r,i,o){for(let s of n){if(ae(s)!=="rust")continue;let a=mi(e,s,{includeRustAttributeNames:!0});if(a.length!==0)for(let{name:c}of a){if(o&&!o.has(c))continue;let u=r.get(c);if(u)for(let l of u)i.has(l.symbolId)&&l.file!==s&&$d(t,l.symbolId,s)}}}function $d(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function xN(e){let t=new Set;for(let n of e){let r="leaf"in n&&typeof n.leaf=="string"?n.leaf:"symbol"in n&&typeof n.symbol=="string"?G(n.symbol):"";r&&t.add(r)}return t.size>0?t:null}function RN(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function EN(e,t){for(let[n,r]of t){let i=e.get(n);i||(i=new Set,e.set(n,i));for(let o of r)i.add(o)}}var IN=te("cross-file-caller-files",{clearGroups:["whole-project","source-file"]}),wN=te("source-fallback-caller-files",{clearGroups:["whole-project","source-file"]});function Rv(e,t,n){let r=t.filter(o=>!e.has(o.symbolId));if(r.length>0){let o=n(r);for(let s of r)e.set(s.symbolId,o.get(s.symbolId)??new Set)}let i=new Map;for(let o of t){let s=e.get(o.symbolId);s&&s.size>0&&i.set(o.symbolId,new Set(s))}return i}function jd(e,t,n={}){if(t===void 0)return Bd(e,t,n);let r=Rv(IN.get(e,()=>new Map),t,i=>Bd(e,i,{semantic:!1}));return n.semantic===!1||!n.semanticEvidence?r:on(r,n.semanticEvidence.callerMap(e,t.filter(i=>"relativePath"in i&&"symbol"in i&&"leaf"in i)))}function Ko(e,t,n={}){return n.skipPath?Yl(e,t,n):Rv(wN.get(e,()=>new Map),t,r=>Yl(e,r))}function Ev(e,t,n={}){let r=jd(e,t,{semantic:n.semantic,semanticEvidence:n.semanticEvidence});return n.sourceFallback===!1?r:on(r,Ko(e,t))}function on(e,t){let n=new Map;for(let[r,i]of e)n.set(r,new Set(i));for(let[r,i]of t){let o=n.get(r)??new Set;for(let s of i)o.add(s);n.set(r,o)}return n}function Iv(e,t,n){let r=t.identifierResolution==="strict"?Vl:Lg,i=t.candidateNames?Eg(t.candidateNames):null,o=0,s=0,a=0,c=0,u="";for(let l of t.paths)if(o+=1,u=l,!(!ae(l)&&!(t.includeVueSfc&&sg(l)))&&!e.isIgnored(l)&&!t.skipPath?.(l))try{if(i&&!Ig(V(e,l),i))continue;s+=1;let m=(f,g,h,y)=>{if(t.candidateNames&&!t.candidateNames.has(f))return;a+=1;let S=t.resolveTargets?t.resolveTargets({sourceFile:l,name:f,kind:g,defaultTargets:y}):y();for(let b of S)c+=1,n({sourceFile:l,name:f,target:b,occurrences:h,kind:g})},p=wr(e,l);for(let[f,g]of p)m(f,"identifier",g.length,()=>r(e,l,f));for(let f of mi(e,l,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let g=f.kind==="cross-language-dispatch"?()=>Vl(e,l,f.name):()=>r(e,l,f.name);m(f.name,f.kind,f.occurrences,g)}}finally{t.afterPath?.(l),o%10===0&&N("source-reference-scan.progress",()=>{},()=>({scannedPaths:o,currentPath:u,candidateMatchedPaths:s,visitedNames:a,visitedHits:c}))}}var H=class{constructor(t){this.db=t}db;scopedDefinitions(t){return hg(this.db,t)}definitionsForFile(t){return q(this.db,t)}productionCallableDefinitions(t={}){return sc(this.db,t)}calleeMap(t,n={}){return Ar(this.db,t,{...n,semanticEvidence:ie})}crossFileCallerMap(t,n={}){return jd(this.db,t,{...n,semanticEvidence:ie})}sourceFallbackCallerFiles(t,n={}){return Ko(this.db,t,n)}callerFileMap(t,n={}){return Ev(this.db,t,{...n,semanticEvidence:ie})}frameworkReferencedSymbolIds(t){let n=new Map;for(let i of t){if(!i.leaf)continue;let o=n.get(i.leaf)??[];o.push(i.symbolId),n.set(i.leaf,o)}let r=new Set;for(let i of Q(this.db,{includeIgnored:!1}))if(ae(i)==="rust")for(let{name:o}of mi(this.db,i,{includeRustAttributeNames:!0}))for(let s of n.get(o)??[])r.add(s);return r}symbolsWithNonSelfCallees(t,n={}){if(t.length===0)return new Set;let r=new Map(t.map(o=>[o.symbolId,o.symbol])),i=this.calleeMap(t,n);return new Set([...i.entries()].filter(([o,s])=>{let a=r.get(o);return s.some(c=>c.symbol!==a)}).map(([o])=>o))}fileDependencyGraph(t){return _e(this.db,t)}fileKind(t){return U(t)}hasSuppressionComment(t){return zs(this.db,t.relativePath,t.startLine)}sourceFiles(){return di(this.db)}scanSourceReferences(t,n){Iv(this.db,t,n)}callableSignature(t){let n=Sn(this.db).forFile(t.relativePath,{facts:!0}).facts?.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};var LN=16,PN=4,Hd=3e3,DN=800,MN=new Set(["assignment","const_declaration","const_item","field_declaration","lexical_declaration","local_declaration_statement","local_variable_declaration","static_item","variable_declaration"]);function Tv(e,t,n={}){let r=n.maxSteps??LN;if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`maxSteps must be a positive safe integer; received ${r}`);let i=new Map(t.nodes.map(M=>[M.id,M])),o=ON(n.focusLocations??[]),s=new Set,a=new Map(t.edges.map(M=>[M.id,M])),c=Tn(t.paths.flatMap(M=>M.nodeIds)),u=Tn(t.anchors.filter(M=>M.status==="matched").flatMap(M=>M.nodeIds)),l=t.nodes.filter(M=>M.disposition==="emitted"&&M.attributes.upstreamCausalPath===!0).sort((M,j)=>Number(j.attributes.upstreamCausalDistance??0)-Number(M.attributes.upstreamCausalDistance??0)||M.id.localeCompare(j.id)).map(M=>M.id),d=new Set(l),m=Math.max(0,r-u.length),f=TN(t,u,o,m).slice(0,m),g=new Set(f),h=new Set(f),y=new Set([...c,...l,...u]),S=t.edges.filter(M=>M.disposition==="emitted"&&M.kind!=="structural-membership"),b=t.edges.filter(M=>M.disposition!=="excluded"&&M.disposition!=="unsupported"&&M.kind!=="structural-membership"),x=new Set([...t.paths.flatMap(M=>M.edgeIds),...S.filter(M=>d.has(M.fromNodeId)&&d.has(M.toNodeId)).map(M=>M.id)]),v=t.paths.some(M=>M.edgeIds.length>0),C=new Set(u);for(let M of f)C.add(M);for(let M of t.paths){let j=M.nodeIds[0],Y=a.get(M.edgeIds[0]??""),se=M.nodeIds[1];j&&se&&Y?.fromNodeId===j&&Y.toNodeId===se&&C.add(j)}if(t.paths.every(M=>M.nodeIds.length===0))for(let M of t.anchors)for(let j of M.nodeIds)C.add(j);let R=UN(u,b,i,PN),E=Tn(S.filter(M=>M.kind==="call"&&u.includes(M.fromNodeId)).map(M=>M.toNodeId)),w=new Set(Tn([...R,...v?[]:E]));for(let M of w)C.add(M);let I=Tn(S.flatMap(M=>y.has(M.fromNodeId)||y.has(M.toNodeId)?[M.fromNodeId,M.toNodeId]:[])),k=t.nodes.filter(M=>M.disposition==="emitted"&&M.kind!=="structural-region"&&S.some(j=>j.fromNodeId===M.id||j.toNodeId===M.id)).map(M=>M.id),D=Tn([...l,...c,...u,...f,...w,...I,...k]).filter(M=>i.has(M)),F=[];for(let M of D)v&&!y.has(M)&&!g.has(M)&&!w.has(M)||F.length>=r&&!y.has(M)||F.push(M);let P=new Set(F),A=new Map(F.map(M=>[M,GN(M)])),L=new Set([...c,...l]),$=new Set(t.anchors.flatMap(M=>M.nodeIds)),B=F.map((M,j)=>{let Y=i.get(M),se=_N(Y,o);for(let je of se)s.add(Oi(Y.location.file,je));return{id:A.get(M),nodeId:M,order:j,role:$.has(M)?"anchor":L.has(M)?"connector":"junction",kind:Y.kind,label:Y.label,location:Y.location,behavior:kN(e,Y,$.has(M),[...new Set([...se,...NN(e,Y,b,i,x,C)])],se,C.has(Y.id)&&(se.length===0||$.has(Y.id)),w.has(Y.id),h.has(Y.id)&&se.length===0)}}),X=new Map;for(let M of t.paths)for(let j=0;j<M.edgeIds.length;j+=1){let Y=a.get(M.edgeIds[j]),se=M.nodeIds[j],je=M.nodeIds[j+1];!Y||!se||!je||X.set(Y.id,Y.fromNodeId===se&&Y.toNodeId===je?"forward":"reverse")}let O=b.filter(M=>P.has(M.fromNodeId)&&P.has(M.toNodeId)).sort((M,j)=>qN(M,j,t)).map((M,j)=>({id:zN(M.id),edgeId:M.id,order:j,kind:M.kind,fromStepId:A.get(M.fromNodeId),toStepId:A.get(M.toNodeId),directed:!0,pathTraversal:X.get(M.id)??"adjacent",evidence:M.evidence})),ne=new Map(O.map(M=>[M.edgeId,M.id])),oe=t.paths.map(M=>({id:M.id,status:M.status,stepIds:M.nodeIds.flatMap(j=>{let Y=A.get(j);return Y?[Y]:[]}),transitionIds:M.edgeIds.flatMap(j=>{let Y=ne.get(j);return Y?[Y]:[]})})),Te=B.flatMap(M=>M.location?[`${M.location.file}:${M.location.line+1}`]:[]),Fe=t.anchors.some(M=>M.status==="ambiguous"),$t=oe.some(M=>M.status==="connected"||M.status==="candidate"),nt=oe.some(M=>M.status==="partial");return{status:B.length===0?"unavailable":Fe?"ambiguous":$t&&!nt?"connected":nt?"partial":"connected",steps:B,transitions:O,paths:oe,coverage:{candidateNodes:D.length,returnedNodes:F.length,omittedNodeIds:D.filter(M=>!P.has(M)),returnedTransitions:O.length,withheldStatements:B.reduce((M,j)=>M+(j.behavior?.coverage.omittedStatements??0),0),requestedFocusLocations:o,matchedFocusLocations:o.filter(M=>s.has(Oi(M.file,M.line))),unmatchedFocusLocations:o.filter(M=>!s.has(Oi(M.file,M.line)))},behaviorCommand:Mv(Te,"behavior"),exactSourceCommand:Mv(Te,"source")}}function TN(e,t,n,r){if(r<=0||n.length===0)return[];let i=new Set(t),o=new Set(n.map(s=>Oi(s.file,s.line)));return Tn(e.edges.filter(s=>s.disposition!=="excluded"&&s.disposition!=="unsupported"&&["call","runtime-boundary"].includes(s.kind)&&i.has(s.fromNodeId)&&s.evidence.some(a=>!["candidate","unknown"].includes(a.strength)&&a.location&&o.has(Oi(a.location.file,a.location.line)))).sort((s,a)=>{let c=s.evidence.find(l=>l.location)?.location,u=a.evidence.find(l=>l.location)?.location;return(c?.file??"").localeCompare(u?.file??"")||(c?.line??Number.MAX_SAFE_INTEGER)-(u?.line??Number.MAX_SAFE_INTEGER)||s.id.localeCompare(a.id)}).map(s=>s.toNodeId)).slice(0,r)}function kN(e,t,n,r,i,o,s,a){if(!t.location||!["symbol","source-construct","runtime-boundary-participant"].includes(t.kind))return null;let c=t.location.endLine??t.location.line,u=K(e,t.location.file),l=r.length>0?r:[t.location.line],d=t.kind==="runtime-boundary-participant"?ot(e,t.location.file,0,Math.max(0,u.length-1),[t.location.line]):ot(e,t.location.file,t.location.line,c,l),m=r.filter(w=>w>=d.startLine&&w<=d.endLine),p=Ri(e,t.location.file,d.startLine,d.endLine,m),f=p??(m.length>0?Ri(e,t.location.file,d.startLine,d.endLine,m,{requireSavings:!1}):null),g=m.length>0?BN(e,t,d.startLine,d.endLine,m,f,o):null,h=u.slice(d.startLine,d.endLine+1).join(`
66
- `).length,y=En(e,t.location.file,d.startLine,d.endLine),S=u.slice(d.startLine,d.endLine+1).some((w,I)=>w.length>DN&&(y.get(d.startLine+I)??[]).some(k=>["binding","branch","loop","call","return","throw","mutation"].includes(k))),b=w=>AN(e,t,d.startLine,d.endLine,i.filter(I=>I>=d.startLine&&I<=d.endLine),w),x=(s||t.kind==="runtime-boundary-participant"||t.anchorIds.length>0)&&h<=Hd,v=n&&(m.length===0||x);if(p&&(a||v))return b(wv(p));if(!a&&!v&&g&&!S&&!x&&g.renderedCharacters<(f?.outlineCharacters??h))return b(g);if(p)return b(wv(p));let C=u.slice(d.startLine,d.endLine+1),R=C.join(`
67
- `),E=En(e,t.location.file,d.startLine,d.endLine);return b({kind:"source",constructKind:"source construct",signature:C.find(w=>w.trim().length>0)?.trim()??t.label,lines:C.map((w,I)=>({line:d.startLine+I,endLine:d.startLine+I,depth:0,signals:E.get(d.startLine+I)??[],text:w,copied:!0})),coverage:{sourceStatements:C.length,representedStatements:C.length,copiedStatements:C.length,omittedStatements:0},rawCharacters:R.length,renderedCharacters:R.length})}function AN(e,t,n,r,i,o){if(!t.location)return o;let s=cu(e,t.location.file,n,r);if(!s.available)return o;let a=En(e,t.location.file,n,r),c=K(e,t.location.file),u=new Set(i);for(let S of i){let b=pc(c[S]??"");if(!b)continue;let x=vn(e,t.location.file,b).find(v=>v>S&&v<=r);x!==void 0&&u.add(x)}let l=[...new Map(s.targets.flatMap(S=>{let b=S.definition,x=b.relativePath===t.location.file&&b.startLine<=r&&b.endLine>=n;if(b.isTypeLike||x)return[];let v=ga(e,b),C=i.length>0&&v&&a.get(S.sourceLine)?.includes("return"),R=v&&u.has(S.sourceLine);return v&&!C&&!R?[]:[[b.symbol,{definition:b,kind:C?"return-value-transformer":R?"focused-causal-target":"compiler-referenced-declaration"}]]})).values()].sort((S,b)=>S.definition.relativePath.localeCompare(b.definition.relativePath)||S.definition.startLine-b.definition.startLine||S.definition.symbol.localeCompare(b.definition.symbol)),d=[],m=l.filter(({kind:S})=>S!=="compiler-referenced-declaration").map(({definition:S})=>({owner:S,depth:1})),p=new Set,f=new Set(l.map(({definition:S})=>S.symbol));for(;m.length>0;){let S=m.shift();if(!S||p.has(S.owner.symbol))continue;p.add(S.owner.symbol);let{owner:b,depth:x}=S,v=cu(e,b.relativePath,b.startLine,b.endLine);if(!v.available)continue;let C=En(e,b.relativePath,b.startLine,b.endLine),R=K(e,b.relativePath);for(let E of v.targets){let w=E.definition,I=w.relativePath===b.relativePath&&w.startLine<=b.endLine&&w.endLine>=b.startLine;if(w.isTypeLike||I)continue;let k=ga(e,w),D=pc(R[E.sourceLine]??""),F=k&&D!==null&&vn(e,b.relativePath,D).some(A=>A>E.sourceLine&&A<=b.endLine&&(C.get(A)??[]).some(L=>["branch","return","throw"].includes(L))),P=k&&((C.get(E.sourceLine)??[]).some(A=>["branch","return","throw"].includes(A))||F);k&&!P||(f.has(w.symbol)||(f.add(w.symbol),d.push({definition:w,kind:k?"focused-causal-target":"compiler-referenced-declaration"})),k&&x<2&&m.push({owner:w,depth:x+1}))}}let g=[...new Map([...l,...d].map(S=>[S.definition.symbol,S])).values()].sort((S,b)=>S.definition.relativePath.localeCompare(b.definition.relativePath)||S.definition.startLine-b.definition.startLine||S.definition.symbol.localeCompare(b.definition.symbol)),h=[],y=[];for(let{definition:S,kind:b}of g){let x=b==="compiler-referenced-declaration"?FN(e,S.relativePath,S.startLine,S.endLine):{startLine:S.startLine,endLine:S.endLine},v=K(e,S.relativePath).slice(x.startLine,x.endLine+1).join(`
68
- `),C=b==="compiler-referenced-declaration"?null:Ri(e,S.relativePath,S.startLine,S.endLine,[]),R=C?[C.signature,...C.lines.map(D=>`${D.line+1}${D.signals.length>0?`[${D.signals.join(",")}]`:""} ${D.text}`)].join(" | "):null,E=R&&R.length<v.length?R:v,w={symbol:S.symbol,label:S.leaf,file:S.relativePath,line:x.startLine,endLine:x.endLine},I=b==="compiler-referenced-declaration"?1e3:8e3,k=b==="compiler-referenced-declaration"?12:120;if(E.length>I||x.endLine-x.startLine>k){y.push({...w,reason:"source-too-large"});continue}h.push({kind:b,...w,text:E})}return{...o,...h.length===0?{}:{supportingDeclarations:h},...y.length===0?{}:{omittedSupportingDeclarations:y}}}function FN(e,t,n,r){let i=J(e,t);if(!i)return{startLine:n,endLine:r};let o=[];kv(i.rootNode,a=>{MN.has(a.type)&&a.startPosition.row<=n&&a.endPosition.row>=r&&o.push(a)});let s=o.sort((a,c)=>a.endPosition.row-a.startPosition.row-(c.endPosition.row-c.startPosition.row)||a.endIndex-a.startIndex-(c.endIndex-c.startIndex))[0];return s?{startLine:s.startPosition.row,endLine:s.endPosition.row}:{startLine:n,endLine:r}}function kv(e,t){t(e);for(let n of e.namedChildren)kv(n,t)}function wv(e){return{kind:"outline",constructKind:e.constructKind,signature:e.signature,lines:e.lines,coverage:e.coverage,rawCharacters:e.rawCharacters,renderedCharacters:e.outlineCharacters}}function NN(e,t,n,r,i,o){if(!t.location||!["symbol","source-construct","runtime-boundary-participant"].includes(t.kind))return[];let s=new Set,a=new Set(W(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 go(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 u=r.get(c.fromNodeId===t.id?c.toNodeId:c.fromNodeId),l=o.has(t.id)&&["call","reference","runtime-boundary"].includes(c.kind)&&c.fromNodeId===t.id,d=(u?.anchorIds.length??0)>0;if(!i.has(c.id)&&!l&&!d)continue;let m=c.evidence.flatMap(y=>y.location?.file===t.location.file?[y.location.line]:[]),p=m.filter(y=>a.has(y));for(let y of p.length>0?p:m)s.add(y);let f=u?.attributes.leaf;if(typeof f!="string"||f.length===0)continue;let g=vn(e,t.location.file,f).filter(y=>y>=t.location.line&&y<=(t.location.endLine??t.location.line)),h=g.find(y=>a.has(y))??g[0];h!==void 0&&s.add(h)}return[...s].sort((c,u)=>c-u)}function _N(e,t){if(!e.location)return[];let n=e.location.endLine??e.location.line;return t.filter(r=>r.file===e.location.file&&r.line>=e.location.line&&r.line<=n).map(r=>r.line)}function ON(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(Oi(n.file,n.line),{file:n.file,line:n.line})}return[...t.values()].sort((n,r)=>n.file.localeCompare(r.file)||n.line-r.line)}function Oi(e,t){return`${e}\0${t}`}function BN(e,t,n,r,i,o,s){if(!t.location)return null;let a=K(e,t.location.file),c=En(e,t.location.file,n,r),u=[...c].filter(([,P])=>P.length>0).map(([P])=>P).sort((P,A)=>P-A),l=i.map(P=>(c.get(P)??[]).length>0?P:u.find(A=>A>P&&A-P<=8)??P),d=new Set([...i,...l]),m=s?fu(e,t.location.file,n,r,{minimumBodyLines:0}):null,p=o?[...new Map(l.flatMap(P=>o.lines.filter(A=>A.text.length<=500&&A.signals.some(L=>["branch","loop","catch","finally"].includes(L))&&P>=A.line&&P<=A.endLine).sort((A,L)=>A.endLine-A.line-(L.endLine-L.line)||A.line-L.line).slice(0,2).map(A=>[`${A.line}\0${A.endLine}`,A]))).values()]:Ra(e,t.location.file,n,r,l);for(let P of m?.lines??[])d.add(P.line);for(let P of p)d.add(P.line);for(let[P,A]of c)A.includes("call")&&A.includes("shape")&&d.add(P);let f=[];for(let P of l){let A=pc(a[P]??"");if(!A)continue;let L=vn(e,t.location.file,A).filter(O=>O>P&&O<=r),$=L[0];$!==void 0&&d.add($);let B=L.find(O=>(c.get(O)??[]).some(ne=>ne==="branch"||ne==="loop"));if(B===void 0)continue;d.add(B);let X=(o?.lines??[]).find(O=>O.line===B)??{line:B,endLine:Math.min(r,B+40),depth:0,signals:c.get(B)??[],text:(a[B]??"").trim(),copied:!0},z=o?.lines??a.slice(X.line,X.endLine+1).map((O,ne)=>{let oe=X.line+ne;return{line:oe,endLine:oe,depth:0,signals:c.get(oe)??[],text:O.trim(),copied:!0}});f.push({focusLine:P,governingUse:B,lines:z.filter(O=>O.line>=X.line&&O.line<=X.endLine&&O.text.length<=500&&O.signals.some(ne=>["binding","branch","call","mutation"].includes(ne)))})}for(let P of f.sort((A,L)=>L.governingUse-L.focusLine-(A.governingUse-A.focusLine)||A.focusLine-L.focusLine).slice(0,2))for(let A of P.lines.slice(0,14))d.add(A.line);let g=new Set(["binding","branch","loop","call","return","throw","mutation"]);for(let P of p)for(let A of o?.lines??[])A.line<P.line||A.line>P.endLine||A.signals.some(L=>g.has(L))&&d.add(A.line);let h=a.slice(n,r+1).flatMap((P,A)=>{let L=pc(P);return L?[{name:L,line:n+A}]:[]}),y=!0;for(;y;){y=!1;for(let P of h)if([...d].some(L=>jN(a[L]??"",P.name))){d.has(P.line)||(d.add(P.line),y=!0);for(let L of vn(e,t.location.file,P.name))L<n||L>r||d.has(L)||(c.get(L)??[]).some($=>g.has($))&&(d.add(L),y=!0)}}for(let P of o?.lines??[])if(P.signals.some(A=>["branch","loop","catch","finally"].includes(A))&&d.has(P.line))for(let A of o?.lines??[])A.line<P.line||A.line>P.endLine||A.signals.some(L=>g.has(L))&&d.add(A.line);let S=W(e,t.location.file),b=new Set(S?.callSites.map(P=>P.line)??[]),x=c,v=new Map([...o?.lines??[],...p].filter(P=>P.signals.some(A=>["branch","loop","catch","finally"].includes(A))).map(P=>[P.line,P])),C=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,A)=>P.endLine-P.line-(A.endLine-A.line)||P.line-A.line).map(P=>[P.line,P])),R=new Map((m?.lines??[]).map(P=>[P.line,P.signals.filter(A=>A!=="lifecycle")])),E=[...d].filter(P=>P>=n&&P<=r).sort((P,A)=>P-A).map(P=>{let A=v.get(P)??C.get(P);return{line:P,endLine:A?.endLine??P,depth:A?.depth??0,signals:$N([...x.get(P)??[],...o?.lines.filter(L=>P>=L.line&&P<=L.endLine).flatMap(L=>L.signals)??[],...R.get(P)??[],...i.includes(P)?["anchor"]:[],...b.has(P)?["call"]:[]]),text:A?.text??(a[P]??"").trim(),copied:A?.copied??!0}}).filter(P=>P.text.length>0);if(E.length===0)return null;let w=m?.candidateLines??fu(e,t.location.file,n,r,{minimumBodyLines:0})?.candidateLines??0,I=Math.max(o?.coverage.sourceStatements??0,w,E.length),k=o?.signature??(a[n]??t.label).trim(),D=k.length+E.reduce((P,A)=>P+A.text.length+A.signals.join(",").length+12,0),F=a.slice(n,r+1).join(`
69
- `).length;return{kind:"connector-slice",constructKind:o?.constructKind??"source construct",signature:k,lines:E,coverage:{sourceStatements:I,representedStatements:E.length,copiedStatements:E.length,omittedStatements:Math.max(0,I-E.length)},rawCharacters:F,renderedCharacters:D}}function $N(e){let t=["anchor","signature","binding","branch","loop","call","await","return","throw","mutation","shape","spread","catch","finally"],n=new Set(e);return t.filter(r=>n.has(r))}function pc(e){return/\b(?:const|let|var)\s+([\p{L}_$][\p{L}\p{N}_$]*)\s*(?:=|\bof\b|\bin\b)/u.exec(e)?.[1]??null}function jN(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`(?:^|[^\\p{L}\\p{N}_$])${n}(?:$|[^\\p{L}\\p{N}_$])`,"u").test(e)}function HN(e,t,n){return Tn(e.flatMap(r=>{let i=n.get(r),o=t.filter(s=>s.kind==="call"&&s.toNodeId===r).map(s=>({edge:s,node:n.get(s.fromNodeId)})).filter(s=>s.node!==void 0&&["symbol","source-construct","runtime-boundary-participant"].includes(s.node.kind)&&s.node.location!==null).sort((s,a)=>{let c=Lv(a.edge)-Lv(s.edge);if(c!==0)return c;let u=Pv(s.node,i)?0:1,l=Pv(a.node,i)?0:1,d=(s.node.location?.endLine??s.node.location?.line??0)-(s.node.location?.line??0),m=(a.node.location?.endLine??a.node.location?.line??0)-(a.node.location?.line??0);return u-l||d-m||s.node.label.localeCompare(a.node.label)});return o[0]?[o[0].node.id]:[]}))}function Lv(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 Pv(e,t){return!e.location||!t?.location?!1:Dv(e.location.file)===Dv(t.location.file)}function Dv(e){return e.split("/").filter(Boolean).slice(0,2).join("/")}function UN(e,t,n,r){let i=new Set(e),o=new Set,s=[],a=Tn(e);for(let c=0;c<r&&a.length>0;c+=1){let u=a.filter(d=>!o.has(d));for(let d of u)o.add(d);let l=HN(u,t,n);a=[];for(let d of l)!i.has(d)&&!s.includes(d)&&s.push(d),o.has(d)||a.push(d)}return s}function qN(e,t,n){let r=new Map(n.paths.flatMap(i=>i.edgeIds).map((i,o)=>[i,o]));return(r.get(e.id)??Number.MAX_SAFE_INTEGER)-(r.get(t.id)??Number.MAX_SAFE_INTEGER)||e.id.localeCompare(t.id)}function GN(e){return`step:${e}`}function zN(e){return`transition:${e}`}function Mv(e,t){return e.length===0?null:`scip-query inspect ${e.map(n=>`--at ${KN(n)}`).join(" ")} --view ${t}`}function KN(e){return`'${e.replace(/'/gu,`'"'"'`)}'`}function Tn(e){return[...new Set(e)]}var Av=4,WN=3,VN=12,YN=48,JN=64,Wr=10,zr=6,XN=24,QN=320,Ud=6,ZN=12,e_=1,t_=4,n_=7,r_=12,Wd="source-construct:",i_=96,o_=32,Fv=4,s_=32,a_=8,Nv=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 c_(e,t,n={}){let r=Yv(t),i=W_(t);if(r.length===0)throw new Error("Anchor discovery requires at least one non-trivial repository term.");let o=n.limit??Av,s=n.full===!0;if(!Number.isSafeInteger(o)||o<=0)throw new RangeError(`anchor group limit must be a positive safe integer; received ${o}`);let a=new H(e),c=a.scopedDefinitions(n.scope).filter(O=>!fe(O.symbol)),u=[...c],l=new Map(u.map(O=>[O.symbol,O])),d=new Map;for(let O of c)_v(d,O,r);let m=lh(e,{scope:n.scope});for(let O of m.files){let oe=q(e,O.relativePath).filter(Fe=>!fe(Fe.symbol));if(oe.length===0)continue;let Te=$n(O.text);for(let Fe=0;Fe<Te.length;Fe+=1){let $t=at(Te[Fe]??""),nt=r.filter(j=>$t.has(j));if(nt.length===0)continue;let M=Oe(oe,Fe);if(!(!M||fe(M.symbol)))for(let j of nt)Wo(d,M,j,"source",O.relativePath,Fe)}}let p=Ov(d),f=[...d.values()].map(O=>fc(O,p,i)).sort(We),g=u_(m.files,f,r),h=-1;for(let O of g){let ne=q(e,O.relativePath),oe=ne.filter(M=>!fe(M.symbol)),Te=W(e,O.relativePath)?.callables??[],Fe=new Map,$t=M=>{let j=`${M.startLine}\0${M.endLine}\0${M.name}`,Y=Fe.get(j);if(Y)return Y;let se=l_(O.relativePath,ne,M,()=>h--);return se?(Fe.set(j,se),u.push(se),l.set(se.symbol,se),_v(d,se,r),se):null};for(let M of Te){let j=at(M.name);r.some(Y=>j.has(Y))&&$t(M)}if(Te.length===0)continue;let nt=$n(O.text);for(let M=0;M<nt.length;M+=1){let j=at(nt[M]??""),Y=r.filter(Cr=>j.has(Cr));if(Y.length===0)continue;let se=jn(Te,M),je=se?$t(se):null;if(!je)continue;let Wt=Bv(oe,M);if(Bv(Wt?[Wt,je]:[je],M)?.symbol===je.symbol)for(let Cr of Y)Wo(d,je,Cr,"source",O.relativePath,M)}}let y=Ov(d),S=new Map(m.files.map(O=>[O.relativePath,O.text.split(/\r?\n/u)]));for(let O of d.values()){let ne=S.get(O.definition.relativePath);ne&&(O.sourceCharacters=ne.slice(O.definition.startLine,O.definition.endLine+1).join(`
70
- `).length)}let b=[...d.values()].map(O=>fc(O,y,i)).sort(We),x=Math.min(b.length,Math.max(VN,o*WN)),v=s?b:Bi([...b.slice(0,x),...[...b].sort(Gd).slice(0,Math.max(YN,x)),...j_(b,r),...H_(b,r,y)]),C=v.length,R=v.map(O=>l.get(O.symbol)).filter(O=>O?.isFunctionLike===!0),E=d_(u),w=m_(e,a,v,R,l,E,new Set(d.keys()),n.semantic!==!1),I=g_(w,v,d,y,l),k=h_(I,y,r),D=M_(e,a,w,d,y,u,l,n.semantic!==!1),P=[...b_(e,a,I,l,y,n.semantic!==!1),...k,...I,...D].map(O=>({...O,queryPathMatches:q_(O)})).sort((O,ne)=>Kr(O,ne,y)),A=s?P:G_(P,o,y),L=r.filter(O=>y.has(O)),$=r.filter(O=>!y.has(O)),B=Math.max(0,b.length-C),X=Math.max(0,P.length-A.length)+B,z=s?b.length:Math.min(b.length,o+Av);return{query:t,queryPathFragments:i,normalizedTerms:r,matchedTerms:L,unmatchedTerms:$,groups:A,candidateRoots:b,candidateRootCount:b.length,analyzedRootCount:C,omittedRootCount:B,omittedGroupCount:X,scannedFiles:m.files.length,scannedBytes:m.scannedBytes,recoveryCommand:X===0?null:`scip-query anchors ${bc(t)}${n.scope?` --scope ${bc(n.scope)}`:""} --limit ${z}`}}function Yv(e){let t=Sc(e).filter(n=>!Nv.has(n.toLocaleLowerCase())).map(Vd).filter(n=>n.length>=3&&!Nv.has(n));return[...new Set(t)]}function _v(e,t,n){let r=at(t.leaf),i=at(t.relativePath),o=at(t.documentation??"");for(let a of n)r.has(a)&&Wo(e,t,a,"symbol"),i.has(a)&&Wo(e,t,a,"path"),o.has(a)&&Wo(e,t,a,"documentation");let s=e.get(t.symbol);s&&(s.symbolPhraseLength=Y_(t.leaf,n))}function Wo(e,t,n,r,i,o){let s=e.get(t.symbol)??{definition:t,matches:new Map,symbolPhraseLength:0},a=s.matches.get(n)??{sources:new Set,locations:new Map};a.sources.add(r),i!==void 0&&o!==void 0&&a.locations.set(`${i}\0${o}`,{file:i,line:o}),s.matches.set(n,a),e.set(t.symbol,s)}function Ov(e){let t=new Map;for(let n of e.values())for(let r of n.matches.keys())t.set(r,(t.get(r)??0)+1);return t}function l_(e,t,n,r){let i=t[0]?.documentId;if(i===void 0||t.find(a=>a.isFunctionLike&&a.leaf===n.name&&a.startLine===n.startLine&&a.endLine===n.endLine))return null;let s=r();return{documentId:i,symbolId:s,symbol:`${Wd}${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 u_(e,t,n){let r=new Set(t.slice(0,i_).map(s=>s.file)),i=new Set(n),o=e.map(s=>{let a=at(s.relativePath),c=s.relativePath.slice(s.relativePath.lastIndexOf("/")+1).replace(/\.[^.]+$/u,""),u=at(c),l=[...a].filter(m=>i.has(m)).length,d=[...u].filter(m=>i.has(m)).length;return{file:s,score:d*4+l}}).filter(s=>s.score>0).sort((s,a)=>a.score-s.score||we(U(s.file.relativePath))-we(U(a.file.relativePath))||s.file.relativePath.localeCompare(a.file.relativePath)).slice(0,o_);for(let s of o)r.add(s.file.relativePath);return e.filter(s=>r.has(s.relativePath))}function d_(e){let t=new Map;for(let n of e){if(!sn(n))continue;let r=`${n.relativePath}\0${Ke(n.leaf)}`,i=t.get(r)??[];i.push(n),t.set(r,i)}return t}function Bv(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,r)=>n.endLine-n.startLine-(r.endLine-r.startLine)||Number(sn(r))-Number(sn(n))||n.startLine-r.startLine||n.symbol.localeCompare(r.symbol))[0]}function sn(e){return e.symbol.startsWith(Wd)}function ar(e){return sn(e)?e.leaf:T(e.symbol)}function fc(e,t,n=[]){let r=e.definition,i=[...e.matches.entries()].map(([u,l])=>({term:u,sources:[...l.sources].sort(J_),locations:[...l.locations.values()].sort(Zv).slice(0,3)})).sort((u,l)=>u.term.localeCompare(l.term)),o=i.filter(u=>u.sources.some(l=>l!=="source")).map(u=>u.term),s=i.filter(u=>u.sources.includes("symbol")).map(u=>u.term),a=i.reduce((u,l)=>u+1/Math.max(1,t.get(l.term)??1),0),c=i.filter(u=>u.sources.includes("symbol")).reduce((u,l)=>u+1/Math.max(1,t.get(l.term)??1),0);return{symbol:r.symbol,label:ar(r),leaf:r.leaf,file:r.relativePath,line:r.startLine,endLine:r.endLine,kind:r.isFunctionLike?"callable":r.isTypeLike?"type":"symbol",fileKind:U(r.relativePath),matches:i,focusLocations:Z_(e,t),matchedTerms:i.map(u=>u.term),symbolMatchedTerms:s,symbolPhraseLength:e.symbolPhraseLength,identityMatchedTerms:o,rarity:a,symbolRarity:c,queryPathMatches:V_(r.relativePath,n),...e.sourceCharacters===void 0?{}:{sourceCharacters:e.sourceCharacters}}}function m_(e,t,n,r,i,o,s,a){let c=r.filter(g=>!sn(g)),u=t.calleeMap(c,{additive:!1,semantic:a}),l=new Map,d=new Map;for(let g of n){let h=i.get(g.symbol),y=h?sn(h)?$v(e,h,i,o,1):gc(e,h,u.get(h.symbolId)??[],i,1,s):[];l.set(g.symbol,y);for(let S of y){let b=i.get(S.toSymbol);b?.isFunctionLike&&(!h||!sn(h)||sn(b))&&d.set(b.symbol,b)}}let m=[...d.values()],p=t.calleeMap(m.filter(g=>!sn(g)),{additive:!1,semantic:a}),f=new Map;for(let g of m)f.set(g.symbol,sn(g)?$v(e,g,i,o,2):gc(e,g,p.get(g.symbolId)??[],i,2,s));return n.map(g=>{let h=l.get(g.symbol)??[],y=h.flatMap(b=>f.get(b.toSymbol)??[]),S=kn([...h,...y]);return{root:g,relations:S,nodeSymbols:new Set([g.symbol,...S.flatMap(b=>[b.fromSymbol,b.toSymbol])])}})}function gc(e,t,n,r,i,o=new Set){let s=new Map;for(let a of n){let c=r.get(a.symbol);if(!c?.isFunctionLike||c.symbol===t.symbol||a.source==="ast-callsite"&&!f_(e,t,c,a.callsiteLine))continue;let u=s.get(c.symbol);(!u||K_(a,u)<0)&&s.set(c.symbol,a)}return[...s.entries()].map(([a,c])=>{let u=r.get(a);return{kind:"call",fromSymbol:t.symbol,fromLabel:T(t.symbol),fromFile:t.relativePath,toSymbol:u.symbol,toLabel:T(u.symbol),toFile:u.relativePath,depth:i,strength:Kd(c.source),evidence:c.source,callsiteLine:c.callsiteLine??p_(e,t,u)}}).sort((a,c)=>Number(o.has(c.toSymbol))-Number(o.has(a.toSymbol))||an(a,c)).slice(0,JN)}function $v(e,t,n,r,i){let o=xn(e,t.relativePath,t.startLine,t.endLine).targets.flatMap(s=>{let a=n.get(s.definition.symbol)??s.definition;return!a.isFunctionLike||a.symbol===t.symbol?[]:[{kind:"call",fromSymbol:t.symbol,fromLabel:ar(t),fromFile:t.relativePath,toSymbol:a.symbol,toLabel:ar(a),toFile:a.relativePath,depth:i,strength:"exact",evidence:"scip-occurrence-callsite",callsiteLine:s.sourceLine}]});for(let s of sr(e,t.relativePath,{ranges:[{startLine:t.startLine,endLine:t.endLine}],excludeIndexedTargets:!1}).targets){let a=[...r.get(`${s.targetFile}\0${Ke(s.calleeLeaf)}`)??[],...q(e,s.targetFile).filter(c=>c.isFunctionLike&&Ke(c.leaf)===s.calleeLeaf)].find(c=>c.startLine===s.targetStartLine&&c.endLine===s.targetEndLine);!a||a.symbol===t.symbol||o.push({kind:"call",fromSymbol:t.symbol,fromLabel:ar(t),fromFile:t.relativePath,toSymbol:a.symbol,toLabel:ar(a),toFile:a.relativePath,depth:i,strength:s.strength==="exact"?"exact":"derived",evidence:"ast-member-import-candidate",callsiteLine:s.line})}for(let s of W(e,t.relativePath)?.callSites??[]){if(s.line<t.startLine||s.line>t.endLine||s.memberAccess)continue;let a=(r.get(`${t.relativePath}\0${Ke(s.calleeLeaf)}`)??[]).filter(u=>u.symbol!==t.symbol);if(a.length!==1)continue;let c=a[0];o.push({kind:"call",fromSymbol:t.symbol,fromLabel:ar(t),fromFile:t.relativePath,toSymbol:c.symbol,toLabel:ar(c),toFile:c.relativePath,depth:i,strength:"derived",evidence:"ast-callsite",callsiteLine:s.line})}return kn(o).sort(an)}function p_(e,t,n){let r=Ke(n.leaf);return W(e,t.relativePath)?.callSites.find(i=>i.line>=t.startLine&&i.line<=t.endLine&&Ke(i.calleeLeaf)===r)?.line??null}function f_(e,t,n,r){if(r===void 0)return!1;let i=Ke(n.leaf);return W(e,t.relativePath)?.callSites.some(o=>{if(o.line!==r)return!1;if(Ke(o.calleeLeaf)===i)return!0;let s=pi(e,t.relativePath,o.calleeLeaf);return s!==null&&Ke(s.importedName)===i&&ke(s.sourcePath,n.relativePath)})??!1}function g_(e,t,n,r,i){let o=new Map(t.map((l,d)=>[l.symbol,d])),s=t.map((l,d)=>d),a=l=>{let d=l;for(;s[d]!==d;)d=s[d];for(;s[l]!==l;){let m=s[l];s[l]=d,l=m}return d},c=(l,d)=>{let m=a(l),p=a(d);m!==p&&(s[p]=m)};for(let l of e){let d=o.get(l.root.symbol);if(d!==void 0)for(let m of l.nodeSymbols){let p=o.get(m);p!==void 0&&c(d,p)}}let u=new Map;for(let l=0;l<t.length;l+=1){let d=a(l),m=u.get(d)??[];m.push(t[l]),u.set(d,m)}return[...u.values()].map((l,d)=>{let m=new Set(l.map(b=>b.symbol)),p=kn(e.filter(b=>m.has(b.root.symbol)).flatMap(b=>b.relations)).sort(an),f=new Map(l.map(b=>[b.symbol,b]));for(let b of new Set(p.flatMap(x=>[x.fromSymbol,x.toSymbol]))){let x=n.get(b);if(x)f.has(b)||f.set(b,fc(x,r));else{let v=i.get(b);v&&f.set(b,Xv(v))}}let g=O_(l,p,f),h=l.filter(b=>p.some(x=>x.fromSymbol===b.symbol)).length,y=[...new Set(l.flatMap(b=>b.matchedTerms))].sort(),S=__(p,g,m,f);return{id:`anchor-set:${d+1}:${Yo(l[0])}`,kind:"connected-flow",roots:[...l].sort(We),keyAnchors:g,candidateOwnerCount:g.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:[],matchedTerms:y,relations:S,relationCount:p.length,orchestrationRootCount:h,omittedRelations:Math.max(0,p.length-Wr),systemMapCommand:Xo(g,p,y)}})}function h_(e,t,n){let r=new Map(n.map((o,s)=>[o,s])),i=[];for(let o=0;o<e.length;o+=1){let s=e[o],a=jv(s);if(a.size!==0)for(let c=o+1;c<e.length;c+=1){let u=e[c],l=jv(u),d=[...a].filter(v=>l.has(v));if(d.length===0||![...a].some(v=>!l.has(v))||![...l].some(v=>!a.has(v)))continue;let m=y_(s,u);if(m.length<2)continue;let p=kn([...s.relations,...u.relations]).sort(an),f=p.slice(0,Wr),g=Bi([...s.roots,...u.roots]).sort(We),h=[...new Set([...s.matchedTerms,...u.matchedTerms])].sort(),y=d.sort((v,C)=>(r.get(v)??Number.MAX_SAFE_INTEGER)-(r.get(C)??Number.MAX_SAFE_INTEGER)||v.localeCompare(C)),S=+(s.relationCount>0)+ +(u.relationCount>0),b=+((s.orchestrationRootCount??0)>0)+ +((u.orchestrationRootCount??0)>0),x=Math.min(...y.map(v=>t.get(v)??Number.MAX_SAFE_INTEGER));i.push({sharedOrder:Math.min(...y.map(v=>r.get(v)??Number.MAX_SAFE_INTEGER)),sharedFrequency:x,connectedSides:S,orchestrationSides:b,group:{id:`parallel-paths:${Yo(s.roots[0])}:${Yo(u.roots[0])}`,kind:"parallel-paths",roots:g,keyAnchors:m,candidateOwnerCount:m.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:[...s.upstreamEntries,...u.upstreamEntries],matchedTerms:h,relations:f,relationCount:p.length,parallelConnectedSides:S,parallelOrchestrationSides:b,parallelSharedPathTerms:y,parallelSharedPathFrequency:x,orchestrationRootCount:(s.orchestrationRootCount??0)+(u.orchestrationRootCount??0),omittedRelations:Math.max(0,p.length-f.length),systemMapCommand:Xo(m,p,h)}})}}return i.sort((o,s)=>o.sharedFrequency-s.sharedFrequency||s.orchestrationSides-o.orchestrationSides||s.connectedSides-o.connectedSides||o.sharedOrder-s.sharedOrder||s.group.matchedTerms.length-o.group.matchedTerms.length||Kr(o.group,s.group,t)).slice(0,r_).map(o=>o.group)}function jv(e){return new Set(e.roots.flatMap(t=>t.matches.filter(n=>n.sources.includes("path")).map(n=>n.term)))}function y_(e,t){return Bi([Hv(e),Hv(t)].filter(n=>n!==void 0))}function Hv(e){let t=new Set(e.keyAnchors.map(r=>r.symbol)),n=new Map;for(let r of e.relations)!t.has(r.fromSymbol)||!t.has(r.toSymbol)||n.set(r.fromSymbol,(n.get(r.fromSymbol)??0)+1);return[...e.keyAnchors].sort((r,i)=>+((n.get(i.symbol)??0)>0)-+((n.get(r.symbol)??0)>0)||Uv(i)-Uv(r)||i.identityMatchedTerms.length-r.identityMatchedTerms.length||i.symbolMatchedTerms.length-r.symbolMatchedTerms.length||(n.get(i.symbol)??0)-(n.get(r.symbol)??0)||We(r,i))[0]}function Uv(e){return e.matchedTerms.length+e.identityMatchedTerms.length*2+(e.queryPathMatches?.length??0)*4}function b_(e,t,n,r,i,o){let s=na(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,u=new Map,l=[...n].sort((p,f)=>Kr(p,f,i)).slice(0,ZN),d=s.links.filter(p=>p.strength!=="candidate").sort((p,f)=>cr(f.strength)-cr(p.strength)||f.matchedKeyParts.length-p.matchedKeyParts.length||p.id.localeCompare(f.id));for(let p of l)for(let f of d){let g=a.get(f.from),h=a.get(f.to);if(!g||!h||!S_(p,g,r))continue;let y=v_(p,g,r);if(!y)continue;let S=c.get(h.id)??R_(e,t,h,r,o,t_);if(c.set(h.id,S),S.reachedSymbols.size===0)continue;let b=n.filter(P=>P.id!==p.id&&C_(P).some(A=>S.reachedSymbols.has(A))&&qd(y,P)>=2).sort((P,A)=>qd(y,A)-qd(y,P)||Kr(P,A,i)).slice(0,e_);if(b.length===0)continue;let x=[p.id,g.id,...b.map(P=>P.id).sort()].join("\0");if(u.has(x))continue;let v=new Set(b.flatMap(Jo)),C=P_(Vo(h),v,S.relations);if(C.length===0)continue;let R=L_(g,h,f.joinRule,f.matchedKeyParts,f.strength),E=kn([R,...S.relations,...p.relations,...b.flatMap(P=>P.relations)]),w=D_([R,...C],E,p,b),I=Bi([y,...b.flatMap(P=>P.roots)]).sort(We),k=Bi([y,...b.flatMap(P=>P.keyAnchors)]).slice(0,n_),D=[...new Set([...y.matchedTerms,...b.flatMap(P=>P.matchedTerms)])].sort(),F=x_(e,t,y,r,o);I.length===0||k.length<2||u.set(x,{id:`cross-boundary-set:${Yo(y)}:${u.size+1}`,kind:"cross-boundary-flow",roots:I,keyAnchors:k,candidateOwnerCount:k.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:F,matchedTerms:D,relations:w,relationCount:E.length,omittedRelations:Math.max(0,E.length-w.length),systemMapCommand:Xo(k,E,D)})}let m=new Map;for(let[p,f]of u){let g=p.slice(0,p.indexOf("\0")),h=m.get(g);(!h||Kr(f,h,i)<0)&&m.set(g,f)}return[...m.values()]}function S_(e,t,n){let r=new Set(Jo(e));return t.owner.symbol&&r.has(t.owner.symbol)?!0:[...r].map(i=>n.get(i)).some(i=>i?.relativePath===t.source.file&&i.startLine<=t.source.startLine&&i.endLine>=t.source.endLine)}function v_(e,t,n){let r=Bi([...e.roots,...e.keyAnchors]);if(t.owner.symbol){let i=r.find(o=>o.symbol===t.owner.symbol);if(i)return i}return r.find(i=>{let o=n.get(i.symbol);return o?.relativePath===t.source.file&&o.startLine<=t.source.startLine&&o.endLine>=t.source.endLine})??null}function Jo(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 C_(e){return[...new Set([...e.roots,...e.keyAnchors].map(t=>t.symbol))]}function qd(e,t){let n=at(e.leaf),r=[...t.roots,...t.keyAnchors].map(o=>at(o.leaf)),i=0;for(let o of r){let s=0;for(let a of n)o.has(a)&&(s+=1);i=Math.max(i,s)}return i}function x_(e,t,n,r,i){let o=r.get(n.symbol);if(!o?.isFunctionLike)return[];let s=t.callerFileMap([o],{semantic:i,sourceFallback:!0}).get(o.symbolId);if(!s)return[];let a=at(n.leaf);return[...s].filter(c=>c!==n.file&&U(c)!=="test").flatMap(c=>{let u=W(e,c);return(u?.callSites??[]).filter(l=>Ke(l.calleeLeaf)===Ke(n.leaf)).flatMap(l=>{let d=(u?.callables??[]).filter(p=>p.startLine<=l.line&&p.endLine>=l.line).sort((p,f)=>p.endLine-p.startLine-(f.endLine-f.startLine)||p.startLine-f.startLine)[0];if(!d)return[];let m=[...at(d.name)].filter(p=>a.has(p)).length;return m>=2?[{name:d.name,file:c,line:d.startLine,endLine:d.endLine,callsiteLine:l.line,overlap:m}]:[]})}).sort((c,u)=>u.overlap-c.overlap||c.file.localeCompare(u.file)||c.line-u.line).slice(0,1).map(({name:c,file:u,line:l,endLine:d,callsiteLine:m})=>({name:c,file:u,line:l,endLine:d,callsiteLine:m}))}function R_(e,t,n,r,i,o){let s=E_(e,n,r),a=s.map(({definition:m,evidence:p,line:f})=>({kind:"call",fromSymbol:Vo(n),fromLabel:hc(n),fromFile:n.source.file,toSymbol:m.symbol,toLabel:T(m.symbol),toFile:m.relativePath,depth:1,strength:p==="scip-occurrence-callsite"?"exact":"derived",evidence:p,callsiteLine:f})),c=I_(e,n);a.push(...c.relations);let u=Jv([...s.map(m=>m.definition),...c.definitions]),l=u,d=new Set(l.map(m=>m.symbol));for(let m=2;m<=o+1&&l.length>0;m+=1){let p=t.calleeMap(l,{additive:!1,semantic:i}),f=new Map;for(let g of l){let h=gc(e,g,p.get(g.symbolId)??[],r,m);a.push(...h);for(let y of h){let S=r.get(y.toSymbol);S?.isFunctionLike&&!d.has(S.symbol)&&f.set(S.symbol,S)}}l=[...f.values()];for(let g of l)d.add(g.symbol)}return{entryDefinitions:u,relations:kn(a),reachedSymbols:new Set([...u.map(m=>m.symbol),...a.flatMap(m=>[m.fromSymbol,m.toSymbol])])}}function E_(e,t,n){let r=t.owner.symbol?n.get(t.owner.symbol):void 0;if(r?.isFunctionLike&&!fe(r.symbol))return[{definition:r,evidence:"scip-occurrence-callsite",line:t.source.startLine}];let i=K(e,t.source.file),o=ot(e,t.source.file,0,Math.max(0,i.length-1),[t.source.startLine]),s=xn(e,t.source.file,o.startLine,o.endLine).targets.map(l=>({definition:l.definition,evidence:"scip-occurrence-callsite",line:l.sourceLine})),a=W(e,t.source.file),c=Xt(e),u=(a?.callSites??[]).flatMap(l=>{if(l.line<o.startLine||l.line>o.endLine)return[];let d=Ht(t.source.file,c.get(l.calleeLeaf)??[]),m=Gn(e,t.source.file,d,l.memberAccess,l.calleeQualifier),p=m?n.get(m.symbol):void 0;return p?.isFunctionLike?[{definition:p,evidence:"ast-callsite",line:l.line}]:[]});return w_([...s,...u])}function I_(e,t){let n=K(e,t.source.file),r=ot(e,t.source.file,0,Math.max(0,n.length-1),[t.source.startLine]),i=sr(e,t.source.file,{ranges:[r],excludeIndexedTargets:!1}).targets,o=[],s=[];for(let a of i){let c=`source-construct:${a.targetFile}:${a.targetStartLine}:${a.targetEndLine}:${a.calleeLeaf}`;s.push({kind:"call",fromSymbol:Vo(t),fromLabel:hc(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 u=xn(e,a.targetFile,a.targetStartLine,a.targetEndLine).targets;for(let l of u)o.push(l.definition),s.push({kind:"call",fromSymbol:c,fromLabel:a.calleeLeaf,fromFile:a.targetFile,toSymbol:l.definition.symbol,toLabel:T(l.definition.symbol),toFile:l.definition.relativePath,depth:2,strength:"exact",evidence:"scip-occurrence-callsite",callsiteLine:l.sourceLine})}return{definitions:Jv(o),relations:kn(s)}}function w_(e){return[...new Map(e.map(t=>[t.definition.symbol,t])).values()]}function Jv(e){return[...new Map(e.map(t=>[t.symbol,t])).values()]}function Vo(e){return e.owner.symbol??e.id}function hc(e){return e.owner.name??`${e.source.file}:${e.source.startLine+1}`}function L_(e,t,n,r,i){return{kind:"runtime-boundary",fromSymbol:Vo(e),fromLabel:hc(e),fromFile:e.source.file,toSymbol:Vo(t),toLabel:hc(t),toFile:t.source.file,depth:1,strength:i,evidence:`runtime-boundary:${n}`,callsiteLine:e.source.startLine,runtimeBoundaryKey:r.map(o=>`${o.name}=${o.value}`).join(" ")}}function P_(e,t,n){let r=new Map;for(let s of n){let a=r.get(s.fromSymbol)??[];a.push(s),r.set(s.fromSymbol,a)}let i=[{symbol:e,path:[]}],o=new Set([e]);for(;i.length>0;){let s=i.shift();if(s.path.length>0&&t.has(s.symbol))return s.path;for(let a of(r.get(s.symbol)??[]).sort(an))o.has(a.toSymbol)||(o.add(a.toSymbol),i.push({symbol:a.toSymbol,path:[...s.path,a]}))}return[]}function D_(e,t,n,r){let i=kn(e),o=new Set([n,...r].flatMap(s=>[...Jo(s),...s.keyAnchors.map(a=>a.symbol)]));for(let s of t){if(i.length>=Wr)break;!o.has(s.fromSymbol)&&!o.has(s.toSymbol)||i.some(a=>a.fromSymbol===s.fromSymbol&&a.toSymbol===s.toSymbol)||i.push(s)}return i.slice(0,Wr)}function M_(e,t,n,r,i,o,s,a){let c=n.filter(l=>!l.root.symbol.startsWith(Wd)).map(l=>({root:l.root,relations:l.relations.filter(d=>d.depth===1&&d.fromSymbol===l.root.symbol)}));return T_(c).flatMap((l,d)=>{let m=new Set(l.map(L=>L.root.symbol)),p=new Map;for(let L of l)for(let $ of new Set(L.relations.map(B=>B.toSymbol)))p.set($,(p.get($)??0)+1);let f=[...p].filter(([,L])=>L>=2).sort(([L,$],[B,X])=>X-$||k_(L,B,r,i,s)).map(([L])=>s.get(L)).filter(L=>L?.isFunctionLike===!0).slice(0,XN);if(f.length===0)return[];let g=t.callerFileMap(f,{semantic:a,sourceFallback:!0}),h=new Set;for(let L of f){h.add(L.relativePath);for(let $ of g.get(L.symbolId)??[])h.add($)}let y=o.filter(L=>L.isFunctionLike&&h.has(L.relativePath)).sort(A_).slice(0,QN),S=t.calleeMap(y,{additive:!1,semantic:a}),b=new Set(f.map(L=>L.symbol)),x=kn(y.flatMap(L=>gc(e,L,S.get(L.symbolId)??[],s,1,b).filter($=>b.has($.toSymbol)))),v=new Map;for(let L of x){let $=v.get(L.fromSymbol)??new Set;$.add(L.toSymbol),v.set(L.fromSymbol,$)}let C=new Set([...v].filter(([L,$])=>$.size>=2||m.has(L)).map(([L])=>L)),R=x.filter(L=>C.has(L.fromSymbol));if(C.size<2||R.length===0)return[];let w=[...new Set(R.map(L=>L.toSymbol))].map(L=>yc(L,r,i,s)).filter(L=>L!==null).sort(We),I=[...C].map(L=>yc(L,r,i,s)).filter(L=>L!==null),k=F_(I,R),D=k.slice(0,Ud),F=k.slice(Ud);if(w.length===0||D.length===0)return[];let P=[...new Set([...w.flatMap(L=>L.matchedTerms),...l.flatMap(L=>L.root.matchedTerms)])].sort(),A=N_(R,D);return[{id:`effect-owner-set:${d+1}:${Yo(w[0])}`,kind:"shared-callee-owners",roots:w,keyAnchors:D,candidateOwnerCount:k.length,omittedCandidateOwners:F,ownerRecoveryCommands:eO(F,Ud),upstreamEntries:[],matchedTerms:P,relations:A,relationCount:R.length,omittedRelations:Math.max(0,R.length-A.length),systemMapCommand:Xo(D,R,P)}]})}function T_(e){let t=e.map((s,a)=>a),n=s=>{for(;t[s]!==s;)t[s]=t[t[s]],s=t[s];return s},r=(s,a)=>{let c=n(s),u=n(a);c!==u&&(t[u]=c)},i=e.map(s=>new Set(s.relations.map(a=>a.toSymbol)));for(let s=0;s<e.length;s+=1)for(let a=s+1;a<e.length;a+=1){let c=0;for(let u of i[s]??[])if((i[a]??new Set).has(u)&&(c+=1),c>=2)break;c>=2&&r(s,a)}let o=new Map;for(let s=0;s<e.length;s+=1){let a=n(s),c=o.get(a)??[];c.push(e[s]),o.set(a,c)}return[...o.values()].filter(s=>s.length>=2)}function k_(e,t,n,r,i){let o=yc(e,n,r,i),s=yc(t,n,r,i);return o?s?We(o,s):-1:s?1:e.localeCompare(t)}function A_(e,t){return we(U(e.relativePath))-we(U(t.relativePath))||e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine}function yc(e,t,n,r){let i=t.get(e);if(i)return fc(i,n);let o=r.get(e);return o?Xv(o):null}function F_(e,t){let n=new Map;for(let i of t){let o=n.get(i.toSymbol)??new Set;o.add(i.fromSymbol),n.set(i.toSymbol,o)}let r=new Map;for(let i of t){let o=n.get(i.toSymbol)?.size??1;r.set(i.fromSymbol,(r.get(i.fromSymbol)??0)+o*o)}return[...e].sort((i,o)=>Number(i.leaf.startsWith("#"))-Number(o.leaf.startsWith("#"))||o.identityMatchedTerms.length-i.identityMatchedTerms.length||(r.get(o.symbol)??0)-(r.get(i.symbol)??0)||We(i,o))}function N_(e,t){let n=new Map(t.map((s,a)=>[s.symbol,a])),r=t.map(s=>e.filter(a=>a.fromSymbol===s.symbol).sort(an)),i=[],o=0;for(;i.length<Wr&&r.some(s=>o<s.length);){for(let s of r){let a=s[o];if(a&&i.push(a),i.length>=Wr)break}o+=1}return i.sort((s,a)=>n.get(s.fromSymbol)-n.get(a.fromSymbol)||an(s,a))}function __(e,t,n,r){let i=new Map(t.map((a,c)=>[a.symbol,c])),o=new Map;for(let a of e)o.set(a.fromSymbol,(o.get(a.fromSymbol)??0)+1);return[...e].sort((a,c)=>{let u=l=>{let d=0;return i.has(l.fromSymbol)&&(d+=100),n.has(l.toSymbol)&&(d+=60),d+=Math.min(40,(o.get(l.toSymbol)??0)*8),(r.get(l.toSymbol)?.matchedTerms.length??0)>0&&(d+=25),l.fromFile!==l.toFile&&(d+=15),l.strength==="exact"&&(d+=5),d};return u(c)-u(a)||an(a,c)}).slice(0,Wr).sort((a,c)=>(i.get(a.fromSymbol)??zr)-(i.get(c.fromSymbol)??zr)||a.depth-c.depth||(a.callsiteLine??Number.MAX_SAFE_INTEGER)-(c.callsiteLine??Number.MAX_SAFE_INTEGER)||an(a,c))}function Xv(e){return{symbol:e.symbol,label:ar(e),leaf:e.leaf,file:e.relativePath,line:e.startLine,endLine:e.endLine,kind:e.isFunctionLike?"callable":e.isTypeLike?"type":"symbol",fileKind:U(e.relativePath),matches:[],focusLocations:[],matchedTerms:[],symbolMatchedTerms:[],symbolPhraseLength:0,identityMatchedTerms:[],rarity:0,symbolRarity:0}}function O_(e,t,n){let r=[...e].sort(We),i=[],o=new Map;for(let l of t)o.set(l.fromSymbol,(o.get(l.fromSymbol)??0)+1);let s=new Set,a=new Set,c=l=>{if(!(!l||i.some(d=>d.symbol===l.symbol))){i.push(l);for(let d of l.matchedTerms)s.add(d);for(let d of l.symbolMatchedTerms)a.add(d)}},u=r.filter(l=>l.symbolPhraseLength>=2&&(o.get(l.symbol)??0)>=2);for(;i.length<Math.min(2,zr);){let l=u.filter(d=>!i.some(m=>m.symbol===d.symbol)).sort((d,m)=>m.symbolMatchedTerms.filter(p=>!a.has(p)).length-d.symbolMatchedTerms.filter(p=>!a.has(p)).length||m.symbolPhraseLength-d.symbolPhraseLength||(o.get(m.symbol)??0)-(o.get(d.symbol)??0)||Gd(d,m))[0];if(!l||i.length>0&&l.symbolMatchedTerms.every(d=>a.has(d)))break;c(l)}if(c(r[0]),i.length>=2){let l=B_(i[0].symbol,i[1].symbol,t,n);for(let d of l?.slice(1,-1)??[]){if(i.length>=zr)break;c(n.get(d))}if(i.length<zr){let d=new Set(i.map(f=>f.symbol)),m=new Set(t.filter(f=>f.depth===1&&d.has(f.fromSymbol)&&d.has(f.toSymbol)).map(f=>f.fromSymbol)),p=t.filter(f=>f.depth===1&&m.has(f.fromSymbol)&&!d.has(f.toSymbol)).map(f=>({relation:f,candidate:n.get(f.toSymbol)})).filter(f=>f.candidate!==void 0&&f.candidate.symbolPhraseLength>=2&&f.candidate.symbolMatchedTerms.length>=2).sort((f,g)=>(o.get(f.relation.fromSymbol)??0)-(o.get(g.relation.fromSymbol)??0)||Gd(f.candidate,g.candidate))[0]?.candidate;c(p)}}else for(;i.length<Math.min(3,zr);){let l=r.filter(d=>!i.some(m=>m.symbol===d.symbol)).sort((d,m)=>m.matchedTerms.filter(p=>!s.has(p)).length-d.matchedTerms.filter(p=>!s.has(p)).length||We(d,m))[0];if(!l||l.matchedTerms.every(d=>s.has(d)))break;c(l)}for(;i.length>=2&&i.length<zr;){let l=new Set(i.map(m=>m.symbol)),d=[...n.values()].filter(m=>!l.has(m.symbol)&&(o.get(m.symbol)??0)>0&&t.some(p=>l.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)||We(m,p))[0];if(!d)break;c(d)}if(i.length<2){let l=i[0],d=l?r.filter(m=>m.symbol!==l.symbol).map(m=>({root:m,path:$_(m.symbol,l.symbol,t)})).filter(m=>m.path!==null).sort((m,p)=>+(p.root.file!==l.file)-+(m.root.file!==l.file)||m.path.length-p.path.length||We(m.root,p.root))[0]?.root:void 0;c(d)}return i}function B_(e,t,n,r){let i=new Map;for(let a of n){let c=i.get(a.fromSymbol)??new Set;c.add(a.toSymbol),i.set(a.fromSymbol,c);let u=i.get(a.toSymbol)??new Set;u.add(a.fromSymbol),i.set(a.toSymbol,u)}let o=[{path:[e],cost:0}],s=new Map([[e,0]]);for(;o.length>0;){o.sort((l,d)=>l.cost-d.cost||l.path.length-d.path.length);let{path:a,cost:c}=o.shift(),u=a.at(-1);if(u===t)return a;for(let l of i.get(u)??[]){let d=r.get(l),m=l===t?1:!d||d.matchedTerms.length===0?9:d.symbolPhraseLength>=2?1:d.identityMatchedTerms.length>=2?2:4,p=c+m;p>=(s.get(l)??Number.POSITIVE_INFINITY)||(s.set(l,p),o.push({path:[...a,l],cost:p}))}}return null}function $_(e,t,n){let r=new Map;for(let s of n){let a=r.get(s.fromSymbol)??[];a.push(s.toSymbol),r.set(s.fromSymbol,a)}let i=[[e]],o=new Set([e]);for(;i.length>0;){let s=i.shift(),a=s.at(-1);if(a===t)return s;for(let c of r.get(a)??[])o.has(c)||(o.add(c),i.push([...s,c]))}return null}function We(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||$i(e.kind)-$i(t.kind)||we(e.fileKind)-we(t.fileKind)||e.file.localeCompare(t.file)||e.line-t.line}function Gd(e,t){return t.symbolPhraseLength-e.symbolPhraseLength||t.symbolMatchedTerms.length-e.symbolMatchedTerms.length||$i(e.kind)-$i(t.kind)||t.symbolRarity-e.symbolRarity||We(e,t)}function j_(e,t){return t.flatMap(n=>{let r=e.filter(s=>s.matchedTerms.includes(n)).sort((s,a)=>U_(s,a,n)),i=[],o=new Set;for(let s of r)if(!o.has(s.file)&&(i.push(s),o.add(s.file),i.length>=Fv))return i;for(let s of r)if(!i.some(a=>a.symbol===s.symbol)&&(i.push(s),i.length>=Fv))break;return i})}function H_(e,t,n){let r=new Set(t),i=new Map;for(let o of e){if(o.kind!=="callable")continue;let s=o.file.slice(o.file.lastIndexOf("/")+1).replace(/\.[^.]+$/u,"");if(![...at(s)].some(c=>r.has(c)))continue;let a=i.get(o.file)??[];a.push(o),i.set(o.file,a)}return[...i.entries()].map(([o,s])=>{let a=o.slice(o.lastIndexOf("/")+1).replace(/\.[^.]+$/u,""),c=[...at(a)].filter(u=>r.has(u));return{file:o,fileCandidates:s,sharedFrequency:Math.min(...c.map(u=>n.get(u)??Number.MAX_SAFE_INTEGER))}}).sort((o,s)=>we(o.fileCandidates[0].fileKind)-we(s.fileCandidates[0].fileKind)||o.sharedFrequency-s.sharedFrequency||o.file.localeCompare(s.file)).flatMap(({fileCandidates:o})=>[...o].sort(We).slice(0,a_)).slice(0,s_)}function U_(e,t,n){return qv(e,n)-qv(t,n)||we(e.fileKind)-we(t.fileKind)||t.symbolPhraseLength-e.symbolPhraseLength||$i(e.kind)-$i(t.kind)||We(e,t)}function qv(e,t){let n=e.matches.find(r=>r.term===t)?.sources??[];return Math.min(...n.map(zd),Number.MAX_SAFE_INTEGER)}function Bi(e){return[...new Map(e.map(t=>[t.symbol,t])).values()]}function Kr(e,t,n){let r=new Set(e.roots.flatMap(o=>o.symbolMatchedTerms)),i=new Set(t.roots.flatMap(o=>o.symbolMatchedTerms));return(t.queryPathMatches?.length??0)-(e.queryPathMatches?.length??0)||Wv(e.kind)-Wv(t.kind)||zv(e)-zv(t)||Kv(e)-Kv(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)||Gv(t,n)-Gv(e,n)||t.matchedTerms.length-e.matchedTerms.length||Math.max(...t.roots.map(o=>o.symbolPhraseLength))-Math.max(...e.roots.map(o=>o.symbolPhraseLength))||i.size-r.size||We(e.roots[0],t.roots[0])||t.roots.length-e.roots.length||e.relationCount-t.relationCount||e.id.localeCompare(t.id)}function Gv(e,t){return e.matchedTerms.reduce((n,r)=>n+1/Math.max(1,t.get(r)??1),0)}function q_(e){return[...new Set(e.roots.flatMap(t=>t.queryPathMatches??[]))].sort()}function zv(e){let t=e.keyAnchors.length>0?e.keyAnchors:e.roots;return Math.max(...t.map(n=>we(n.fileKind)))}function Kv(e){return e.kind==="parallel-paths"?2-(e.parallelConnectedSides??0):e.kind!=="connected-flow"||e.relationCount>0?0:1}function G_(e,t,n){let r=e.slice(0,t);if(t<2||r.some(o=>o.kind==="shared-callee-owners"))return r;let i=e.filter(o=>o.kind==="shared-callee-owners");for(let o of r){if(o.kind==="shared-callee-owners"||o.kind==="parallel-paths")continue;let s=new Set(Jo(o)),a=i.map(u=>({group:u,overlap:z_(u,s)})).filter(({overlap:u})=>u>0).sort(({group:u,overlap:l},{group:d,overlap:m})=>m-l||Kr(u,d,n))[0]?.group;if(!a)continue;let c=r.length-1;for(;c>=0&&r[c]===o;)c-=1;return c<0?r:(r[c]=a,[...r].sort((u,l)=>Kr(u,l,n)))}return r}function z_(e,t){return Jo(e).filter(n=>t.has(n)).length}function Wv(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||cr(t.strength)-cr(e.strength)||e.fromLabel.localeCompare(t.fromLabel)||e.toLabel.localeCompare(t.toLabel)||(e.callsiteLine??Number.MAX_SAFE_INTEGER)-(t.callsiteLine??Number.MAX_SAFE_INTEGER)}function K_(e,t){return cr(Kd(t.source))-cr(Kd(e.source))||(e.callsiteLine??Number.MAX_SAFE_INTEGER)-(t.callsiteLine??Number.MAX_SAFE_INTEGER)||e.symbol.localeCompare(t.symbol)}function kn(e){let t=new Map;for(let n of e){let r=`${n.fromSymbol}\0${n.toSymbol}`,i=t.get(r);(!i||an(n,i)<0)&&t.set(r,n)}return[...t.values()]}function Sc(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 W_(e){let t=e.match(/[\p{L}\d_.-]+(?:\/[\p{L}\d_.-]+)+/gu)??[];return[...new Set(t.map(n=>n.replace(/[.;:!?]+$/gu,"").toLocaleLowerCase()))]}function V_(e,t){let n=e.replace(/\\/gu,"/").toLocaleLowerCase();return t.filter(r=>{let i=n.indexOf(r);if(i<0)return!1;let o=i===0?"/":n[i-1],s=n[i+r.length];return o==="/"&&(s===void 0||s==="/")})}function Y_(e,t){let n=Sc(e).map(Vd),r=0;for(let i=0;i<n.length;i+=1)for(let o=0;o<t.length;o+=1){let s=0;for(;i+s<n.length&&o+s<t.length&&n[i+s]===t[o+s];)s+=1;r=Math.max(r,s)}return r}function at(e){return new Set(Sc(e).flatMap(Qv).filter(t=>t.length>=3))}function Qv(e){let t=Vd(e);return t.length>4&&t.endsWith("e")?[t,t.slice(0,-1)]:[t]}function Vd(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")?Vv(t.slice(0,-2)):t.length>5&&t.endsWith("ing")?Vv(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 Vv(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 J_(e,t){return zd(e)-zd(t)}function zd(e){switch(e){case"symbol":return 0;case"path":return 1;case"documentation":return 2;case"source":return 3}}function $i(e){return e==="callable"?0:e==="type"?1:2}function Kd(e){return e==="semantic-callee"||e==="scip-chunk"||e==="scip-occurrence"?"exact":"derived"}function cr(e){return e==="exact"?2:1}function Zv(e,t){return e.file.localeCompare(t.file)||e.line-t.line}function Yo(e){return`${e.file}:${e.line+1}`}function Xo(e,t=[],n=[]){let r=e.map(s=>`--symbol ${bc(`${s.file}:${s.line+1}-${s.endLine+1}`)}`),i=new Set(e.map(s=>s.symbol)),o=e.flatMap(s=>(s.sourceCharacters??0)>Hd?X_(s,t,n,i).map(a=>`--focus-at ${bc(`${a.file}:${a.line+1}`)}`):[]);return`scip-query system-map ${[...r,...o,"--relation call","--relation runtime-boundary"].join(" ")}`}function X_(e,t,n,r){let i=new Set(n),o=t.filter(u=>u.fromSymbol===e.symbol&&u.callsiteLine!==null&&u.callsiteLine>=e.line&&u.callsiteLine<=e.endLine).map(u=>({file:e.file,line:u.callsiteLine,connectsAnchor:r.has(u.toSymbol),overlap:new Set(Sc(Q_(u.toLabel)).flatMap(Qv).filter(l=>i.has(l))).size,strength:u.strength})).filter(u=>u.overlap>0).sort((u,l)=>Number(l.connectsAnchor)-Number(u.connectsAnchor)||l.overlap-u.overlap||u.line-l.line||cr(l.strength)-cr(u.strength)),s=o.filter(u=>u.connectsAnchor),a=[...s.length>0?s:o,...s.length>0?[]:e.focusLocations.map(u=>({...u,connectsAnchor:!1,overlap:0,strength:"derived"}))],c=[];for(let u of a)if(!c.some(l=>l.file===u.file&&l.line===u.line)&&(c.push({file:u.file,line:u.line}),c.length>=3))break;return c}function Q_(e){return e.slice(Math.max(e.lastIndexOf(":"),e.lastIndexOf("."))+1)}function Z_(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}`,u=n.get(c)??{...a,matchedTerms:new Set};u.matchedTerms.add(o),n.set(c,u)}let r=[...n.values()].sort((o,s)=>s.matchedTerms.size-o.matchedTerms.size||[...s.matchedTerms].reduce((a,c)=>a+1/Math.max(1,t.get(c)??1),0)-[...o.matchedTerms].reduce((a,c)=>a+1/Math.max(1,t.get(c)??1),0)||Zv(o,s)),i=[];for(let o of r)if(!i.some(s=>s.file===o.file&&Math.abs(s.line-o.line)<8)&&(i.push(o),i.length>=3))break;return i.map(o=>({file:o.file,line:o.line,matchedTerms:[...o.matchedTerms].sort()}))}function eO(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(Xo(e.slice(r,r+t)));return n}function bc(e){return`'${e.replaceAll("'",`'"'"'`)}'`}import{createHash as CC}from"crypto";function Qo(e,t,n={}){let r=re(e,t);if(!r)return null;let i=n.semantic!==!1,o=Vn(e,r,{semantic:i,semanticEvidence:ie}).filter(u=>Re(u.symbol)).slice(0,50),s=_i(Ft(e,r,{limit:50,additive:!0,callableOnly:!0,semantic:i,semanticEvidence:ie})),a=o.map(u=>({symbol:u.symbol,shortName:T(u.symbol),file:u.file,relationship:u.source!=="caller-map-inversion"?"reference-candidate":u.callEvidence==="scip-chunk"?"chunk-candidate":"resolved-call",evidenceStrength:u.source==="caller-map-inversion"&&u.callEvidence!=="scip-chunk"?"exact":"candidate",evidenceSource:u.callEvidence??u.source})),c=s.map(u=>({symbol:u.symbol,shortName:T(u.symbol),file:u.file,relationship:u.source==="scip-chunk"?"chunk-candidate":"resolved-call",evidenceStrength:u.source==="scip-chunk"?"candidate":"exact",evidenceSource:u.source,...u.kind==="jsx-render"?{interaction:"render"}:{}}));return{symbol:r.symbol,shortName:T(r.symbol),callers:a.map(({symbol:u,shortName:l,file:d})=>({symbol:u,shortName:l,file:d})),callees:c.map(({symbol:u,shortName:l,file:d})=>({symbol:u,shortName:l,file:d})),callerEvidence:a,calleeEvidence:c,coverage:{scope:"indexed-static-call-graph",blindSpots:["unresolved dynamic dispatch and reflection","external or unindexed callees without a resolved symbol identity","SCIP chunk co-occurrence is retained only as candidate call evidence"]}}}function Zo(e,t){let n=gt(e,t);return n?Hn(e,"forward",[n]).filter(i=>!e.isIgnored(i)).map(i=>({relativePath:i,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):[]}function es(e,t){let n=gt(e,t);return n?Hn(e,"reverse",[n]).filter(i=>!e.isIgnored(i)).map(i=>({relativePath:i,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):[]}function Yd(e,t,n={}){let r=vc(e,t,n);return{definitions:r.definitions,referencedBy:r.referencedBy}}function vc(e,t,n={}){let r=re(e,t);if(!r)return{definitions:[],referencedBy:[],referenceEvidence:[],claimSupport:null};let i=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",r.symbolId),o=yi(i?.documentation??null),s=e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,signature:sO(o,i?.display_name??null,r.symbol),source:oO(e,r.relativePath,r.startLine,r.endLine)}],a=n.referenceContext??2,c=Dg(e,r,{semantic:n.semantic,semanticEvidence:ie}).map(l=>{let d=Gh(e,l.file,l.line,a,G(r.symbol));return{relativePath:l.file,line:l.line,enclosingSymbol:l.enclosingSymbol,enclosingShort:l.enclosingSymbol?T(l.enclosingSymbol):"(top-level)",provenance:l.provenance,sourceStartLine:d?.startLine??null,sourceEndLine:d?.endLine??null,source:d?.source??null,sourceKind:d?.kind??"unavailable"}}),u=c.map(tO);return{definitions:s,referencedBy:u,referenceEvidence:c.map(l=>({relativePath:l.relativePath,line:l.line,provenance:l.provenance,sourceKind:l.sourceKind})),claimSupport:nO(c)}}function tO(e){return{relativePath:e.relativePath,line:e.line,enclosingSymbol:e.enclosingSymbol,enclosingShort:e.enclosingShort,sourceStartLine:e.sourceStartLine,sourceEndLine:e.sourceEndLine,source:e.source}}function nO(e){let t="resolved source-attributed or SCIP-indexed references to this exact symbol",n=["Dynamic dispatch, reflection, generated calls, and unindexed source are outside this scope."],r=e.filter(o=>o.sourceKind!=="complete-call-expression"&&o.sourceKind!=="non-call-reference"),i="direct, statically visible call expressions among the resolved reference sites";return{referenceAbsence:{status:"eligible",scope:t,limitations:n},callsitePredicates:r.length===0?{status:"eligible",scope:i,limitations:n}:{status:"ineligible",scope:i,reason:`${r.length} reference site(s) lack one unambiguous complete call expression.`,followup:rO(r)}}}function rO(e){let t=[...new Set(e.map(n=>`${n.relativePath}:${n.line+1}`))];return t.length===0||t.length>24?null:`scip-query inspect ${t.map(n=>`--at ${iO(n)}`).join(" ")} --view behavior`}function iO(e){return`'${e.replaceAll("'","'\\''")}'`}function oO(e,t,n,r){let i=V(e,t);if(!i)return null;let s=i.split(`
71
- `).slice(n,r+1).join(`
72
- `).trimEnd();return s.length>0?s:null}function sO(e,t,n){let r=hi(e);if(r&&!aO(r))return r;let i=(t??"").trim();return i?Re(n)&&!i.endsWith("()")?`${i}()`:i:T(n)}function aO(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function Jd(e,t,n={}){let r=nC(e,t,n);if(r.kind!=="matched")return r;let{referenceEvidence:i,claimSupport:o,...s}=r;return s}function nC(e,t,n={}){let r=Ze(e,t);if(!r.match)return{kind:"missing",query:t};if(r.total>1)return{kind:"ambiguous",query:t,total:r.total,candidates:[{symbol:r.match.symbol,shortName:T(r.match.symbol),relativePath:r.match.relativePath,startLine:r.match.startLine},...r.candidates]};let i=r.match,o=lO(n.parts),s=o.includes("definition")||o.includes("references")?vc(e,i.symbol,{semantic:n.semantic,referenceContext:n.referenceContext}):{definitions:[],referencedBy:[],referenceEvidence:[],claimSupport:null},a=o.includes("callers")||o.includes("callees")?Qo(e,i.symbol,{semantic:n.semantic}):null,c=n.relatedSourceLines??80;return{kind:"matched",query:t,symbol:i.symbol,shortName:T(i.symbol),file:i.relativePath,parts:o,definition:o.includes("definition")?Vh(e,i.symbol):null,referenceWindows:o.includes("references")?cO(e,s.referencedBy):[],callers:o.includes("callers")?tC(e,a?.callers??[],c):[],callees:o.includes("callees")?tC(e,a?.callees??[],c):[],dependencies:o.includes("dependencies")?Zo(e,i.relativePath):[],consumers:o.includes("consumers")?es(e,i.relativePath):[],referenceEvidence:s.referenceEvidence,claimSupport:s.claimSupport}}function cO(e,t){let n=t.filter(i=>i.sourceStartLine!==null&&i.sourceEndLine!==null&&i.source!==null).sort((i,o)=>i.relativePath.localeCompare(o.relativePath)||i.sourceStartLine-o.sourceStartLine||i.line-o.line),r=[];for(let i of n){let o=r[r.length-1];if(o&&o.relativePath===i.relativePath&&i.sourceStartLine<=o.endLine+1){o.endLine=Math.max(o.endLine,i.sourceEndLine),o.references.push(eC(i)),o.source=K(e,o.relativePath).slice(o.startLine,o.endLine+1).join(`
73
- `);continue}r.push({relativePath:i.relativePath,startLine:i.sourceStartLine,endLine:i.sourceEndLine,source:i.source,references:[eC(i)]})}return r}function eC(e){return{line:e.line,enclosingSymbol:e.enclosingSymbol,enclosingShort:e.enclosingShort}}function lO(e){let t=e&&e.length>0?e:["definition","references"];return[...new Set(t)]}function tC(e,t,n){let r=[],i=new Set;for(let o of t){if(i.has(o.symbol))continue;i.add(o.symbol);let s=(o.file?q(e,o.file).find(c=>c.symbol===o.symbol):void 0)??Ze(e,o.symbol).match;if(!s)continue;let a=zh(e,s.relativePath,s.startLine,s.endLine,n);a&&r.push({...a,symbol:o.symbol,shortName:o.shortName,omittedLines:Math.max(0,s.endLine-a.endLine)})}return r}var aC=6;function rC(e,t,n){return`${e}\0${t}\0${n??t}`}function cC(e,t,n,r={}){let i=r.limit??aC;if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`next-anchor limit must be a positive safe integer; received ${i}`);let o=r.sourceAllowed??(()=>!0),s=new Map(t.nodes.map(E=>[E.id,E])),a=new Set(n.steps.map(E=>E.nodeId)),c=new Set(n.steps.flatMap(E=>{let w=Qd(s.get(E.nodeId));return w?[w]:[]})),u=new Set;for(let E of n.steps)for(let w of E.behavior?.supportingDeclarations??[])c.add(w.symbol),u.add(rC(w.file,w.line,w.endLine));let l=E=>E.symbol!==null&&c.has(E.symbol)||u.has(rC(E.file,E.line,E.endLine)),d=new Map(n.steps.flatMap(E=>{if(!E.location)return[];let w=Qd(s.get(E.nodeId));if(!w)return[];let I=q(e,E.location.file).find(k=>k.symbol===w);return I?[[E.id,I]]:[]})),m=new H(e).calleeMap([...d.values()],{additive:!1,semantic:!0}),p=[],f=new Set,g=new Set,h=0,y=0,S=0,b=0,x=0,v=0,C=0,R=0;for(let E of n.steps){if(!E.location||!E.behavior)continue;let w=uO(E,{db:e,topology:t,nodeById:s,returnedNodeIds:a,sourceAllowed:o,alternativeAlreadyReturned:l});p.push(...w.candidates),v+=w.upstreamCandidates,R+=w.runtimeCandidates,C+=w.resultCandidates;let I=dO(E,{db:e,topology:t,nodeById:s,returnedNodeIds:a,sourceAllowed:o,alternativeAlreadyReturned:l},f);p.push(...I);let k=mO(E,{db:e,topology:t,nodeById:s,returnedNodeIds:a,sourceAllowed:o,alternativeAlreadyReturned:l},{evidencedCallsiteKeys:f,consideredCandidateKeys:g,calleeMap:m,stepDefinition:d.get(E.id)});p.push(...k.candidates),h+=k.scannedBehaviorSteps,y+=k.visibleCallsites,S+=k.identityCandidateCallsites,b+=k.ambiguousCallsites,x+=k.unresolvedCallsites}return mC(e,p,n.steps,i,{scannedBehaviorSteps:h,visibleCallsites:y,graphEvidencedCallsites:f.size,identityCandidateCallsites:S,ambiguousCallsites:b,unresolvedCallsites:x,upstreamCandidates:v,resultCandidates:C,runtimeCandidates:R},r.selectionTerms)}function uO(e,t){let n=[],r=0,i=0,o=0;if(!e.location||!e.behavior)return{candidates:n,upstreamCandidates:r,resultCandidates:i,runtimeCandidates:o};let s=t.topology.edges.filter(c=>["call","runtime-boundary"].includes(c.kind)&&(c.fromNodeId===e.nodeId||c.toNodeId===e.nodeId)&&c.disposition!=="excluded"&&c.disposition!=="unsupported");for(let c of s){let u=c.toNodeId===e.nodeId,l=u?c.fromNodeId:c.toNodeId;if(t.returnedNodeIds.has(l))continue;let d=t.nodeById.get(l);if(!d?.location||!t.sourceAllowed(d.location.file))continue;let m=c.kind==="call"?Zd(t.db,d):nm(d);if(!m||t.alternativeAlreadyReturned(m))continue;let p=em(c,d.location.file)??d.location,f=K(t.db,p.file)[p.line]?.trim(),g=u?"upstream":"downstream",h=c.kind==="runtime-boundary"?u?"runtime-producer":"runtime-consumer":u?"caller":"callee",y=tm(c.evidence),S=ns(d);n.push({anchor:{id:lr(e.id,p.line,d.id),status:y,source:"graph-relation",direction:g,causalRole:h,relationKind:c.kind,fromStepId:e.id,fromLabel:e.label,callsite:{file:p.file,line:p.line,endLine:p.endLine??p.line,text:f||`${d.label} \u2192 ${e.label}`,signals:["call"],calleeLeaf:S},alternatives:[m],alternativeCount:1,evidence:c.evidence}}),u&&(r+=1),c.kind==="runtime-boundary"&&(o+=1)}let a=t.topology.edges.filter(c=>c.kind==="reference"&&c.fromNodeId===e.nodeId&&c.disposition!=="excluded"&&c.disposition!=="unsupported"&&!t.returnedNodeIds.has(c.toNodeId));for(let c of a){let u=t.nodeById.get(c.toNodeId);if(!u?.location||!t.sourceAllowed(u.location.file))continue;let l=Zd(t.db,u);if(!l||t.alternativeAlreadyReturned(l))continue;let d=ns(u),m=em(c,e.location.file)?.line,p=e.behavior.lines.find(h=>(m===void 0||m>=h.line&&m<=h.endLine)&&h.text.includes(d));if(!p)continue;let f=uC(p.signals),g=tm(c.evidence);n.push({anchor:{id:lr(e.id,p.line,u.id),status:g,source:"graph-relation",direction:"downstream",causalRole:f,relationKind:"reference",fromStepId:e.id,fromLabel:e.label,callsite:{file:e.location.file,line:p.line,endLine:p.endLine,text:p.text,signals:p.signals,calleeLeaf:d},alternatives:[l],alternativeCount:1,evidence:c.evidence}}),f==="result-callback"&&(i+=1)}return{candidates:n,upstreamCandidates:r,resultCandidates:i,runtimeCandidates:o}}function dO(e,t,n){let r=[];if(!e.location)return r;let i=xn(t.db,e.location.file,e.location.line,e.location.endLine??e.location.line),o=K(t.db,e.location.file),s=En(t.db,e.location.file,e.location.line,e.location.endLine??e.location.line);for(let a of i.targets){if(!t.sourceAllowed(a.definition.relativePath))continue;let c=Vr(e.location.file,a.sourceLine,a.calleeLeaf);if(n.has(c))continue;n.add(c);let u=Xd(s.get(a.sourceLine)),l={symbol:a.definition.symbol,label:a.definition.leaf,file:a.definition.relativePath,line:a.definition.startLine,endLine:a.definition.endLine};t.alternativeAlreadyReturned(l)||r.push({anchor:{id:lr(e.id,a.sourceLine,a.definition.symbol),status:"exact",source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:e.id,fromLabel:e.label,callsite:{file:e.location.file,line:a.sourceLine,endLine:a.sourceLine,text:o[a.sourceLine]?.trim()||`${a.calleeLeaf}()`,signals:u,calleeLeaf:a.calleeLeaf},alternatives:[l],alternativeCount:1,evidence:[{method:"scip-occurrence-callsite",strength:"exact",identity:a.definition.symbol,location:{file:e.location.file,line:a.sourceLine}}]}})}return r}function mO(e,t,n){let r={candidates:[],scannedBehaviorSteps:0,visibleCallsites:0,identityCandidateCallsites:0,ambiguousCallsites:0,unresolvedCallsites:0};if(!e.location||!e.behavior)return r;let i=e.behavior.lines.filter(f=>f.signals.includes("call"));if(i.length===0)return r;let o=[],s=0,a=0,c=0,u=(W(t.db,e.location.file)?.callSites??[]).filter(f=>i.some(g=>f.line>=g.line&&f.line<=g.endLine)),l=t.topology.edges.filter(f=>f.kind==="call"&&f.fromNodeId===e.nodeId&&f.disposition!=="excluded"&&f.disposition!=="unsupported"),d=new Map;for(let f of l){let g=t.nodeById.get(f.toNodeId);if(!g)continue;let h=ns(g);d.set(h,(d.get(h)??0)+1)}let m=fO(t.db,n.stepDefinition?n.calleeMap.get(n.stepDefinition.symbolId)??[]:[]),p=gO(m);for(let f of m){if(!t.sourceAllowed(f.alternative.file)||t.alternativeAlreadyReturned(f.alternative))continue;let g=Ke(f.alternative.label),h=oC(u,i,g,f.row.callsiteLine,p.get(g)===1);if(!h)continue;let y=ts(i,h.line,g);if(!y)continue;let S=Vr(e.location.file,h.line,g);if(n.evidencedCallsiteKeys.has(S))continue;n.evidencedCallsiteKeys.add(S);let b=fC(f.row.source);o.push({anchor:{id:lr(e.id,h.line,f.alternative.symbol??f.alternative.file),status:b,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:e.id,fromLabel:e.label,callsite:{file:e.location.file,line:y.line,endLine:y.endLine,text:y.text,signals:y.signals,calleeLeaf:g},alternatives:[f.alternative],alternativeCount:1,evidence:[{method:f.row.source,strength:b,identity:f.row.symbol,location:{file:e.location.file,line:h.line}}]}})}for(let f of l){if(t.returnedNodeIds.has(f.toNodeId))continue;let g=t.nodeById.get(f.toNodeId);if(!g?.location||!t.sourceAllowed(g.location.file))continue;let h=ns(g),y=f.evidence.find(R=>{let E=R.location;return E!==null&&E.file===e.location?.file&&E.line>=0})?.location?.line,S=oC(u,i,h,y,d.get(h)===1);if(!S)continue;let b=ts(i,S.line,h);if(!b)continue;let x=Vr(e.location.file,S.line,h);if(n.evidencedCallsiteKeys.has(x))continue;n.evidencedCallsiteKeys.add(x);let v=nm(g);if(!v||t.alternativeAlreadyReturned(v))continue;let C=tm(f.evidence);o.push({anchor:{id:lr(e.id,S.line,g.id),status:C,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:e.id,fromLabel:e.label,callsite:{file:e.location.file,line:b.line,endLine:b.endLine,text:b.text,signals:b.signals,calleeLeaf:h},alternatives:[v],alternativeCount:1,evidence:f.evidence}})}for(let f of u){let g=Vr(e.location.file,f.line,f.calleeLeaf);if(n.evidencedCallsiteKeys.has(g))continue;let h=ts(i,f.line,f.calleeLeaf);if(!h)continue;let y=Ht(e.location.file,Xt(t.db).get(f.calleeLeaf)??[]).flatMap(v=>q(t.db,v.file).filter(C=>C.symbol===v.symbol&&C.isFunctionLike)).filter(v=>t.sourceAllowed(v.relativePath)&&!t.alternativeAlreadyReturned({symbol:v.symbol,label:v.leaf,file:v.relativePath,line:v.startLine,endLine:v.endLine})),S=xc(y.map(v=>({symbol:v.symbol,label:v.leaf??f.calleeLeaf,file:v.relativePath,line:v.startLine,endLine:v.endLine})));if(S.length===0){c+=1;continue}let b=`${e.id}\0${f.line}\0${f.calleeLeaf}`;if(n.consideredCandidateKeys.has(b))continue;n.consideredCandidateKeys.add(b);let x=S.length>1;x?a+=1:s+=1,o.push({anchor:{id:lr(e.id,f.line,f.calleeLeaf),status:x?"ambiguous":"candidate",source:"leaf-identity-candidate",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:e.id,fromLabel:e.label,callsite:{file:e.location.file,line:h.line,endLine:h.endLine,text:h.text,signals:h.signals,calleeLeaf:f.calleeLeaf},alternatives:S.slice(0,3),alternativeCount:S.length,evidence:[]}})}return{candidates:o,scannedBehaviorSteps:1,visibleCallsites:u.length,identityCandidateCallsites:s,ambiguousCallsites:a,unresolvedCallsites:c}}function lC(e,t,n){let r=new Map(t.nodes.map(i=>[i.id,i]));for(let i of n.steps)if(!(!i.behavior||!i.location))for(let o of t.edges){if(o.kind!=="reference"||o.fromNodeId!==i.nodeId||o.disposition==="excluded"||o.disposition==="unsupported")continue;let s=r.get(o.toNodeId);if(!s?.location||!Zd(e,s))continue;let a=ns(s),c=em(o,i.location.file)?.line,u=i.behavior.lines.find(l=>(c===void 0||c>=l.line&&c<=l.endLine)&&l.text.includes(a));!u||uC(u.signals)!=="result-callback"||o.semantics?.some(({family:l,subtype:d})=>l==="control"&&d==="result-callback")||(o.semantics=[...o.semantics??[],{family:"control",subtype:"result-callback",attributes:{evidenceRole:"result-producing-callable-reference"}}])}}function uC(e){return e.includes("call")&&e.some(t=>["return","mutation","shape","spread","binding"].includes(t))?"result-callback":"callable-reference"}function dC(e,t,n={}){let r=n.limit??aC;if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`next-anchor limit must be a positive safe integer; received ${r}`);let i=n.sourceAllowed??(()=>!0),o=[],s=t.map((p,f)=>({id:p.id,nodeId:p.id,order:f,role:"anchor",kind:"source-construct",label:p.label,location:{file:p.file,line:p.startLine,endLine:p.endLine},behavior:null})),a=t.map(p=>({file:p.file,startLine:p.startLine,endLine:p.endLine})),c=0,u=0,l=0,d=0,m=0;for(let p of t){let f=K(e,p.file),h=(W(e,p.file)?.callSites??[]).filter(C=>C.line>=p.startLine&&C.line<=p.endLine);c+=h.length;let y=En(e,p.file,p.startLine,p.endLine),S=xn(e,p.file,p.startLine,p.endLine),b=new Set;for(let C of S.targets){if(!i(C.definition.relativePath)||a.some(I=>I.file===C.definition.relativePath&&I.startLine<=C.definition.startLine&&I.endLine>=C.definition.endLine))continue;let R=Vr(p.file,C.sourceLine,C.calleeLeaf);b.add(R);let E=Xd(y.get(C.sourceLine)),w={symbol:C.definition.symbol,label:C.definition.leaf,file:C.definition.relativePath,line:C.definition.startLine,endLine:C.definition.endLine};o.push({anchor:{id:lr(p.id,C.sourceLine,C.definition.symbol),status:"exact",source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:p.id,fromLabel:p.label,callsite:{file:p.file,line:C.sourceLine,endLine:C.sourceLine,text:f[C.sourceLine]?.trim()||`${C.calleeLeaf}()`,signals:E,calleeLeaf:C.calleeLeaf},alternatives:[w],alternativeCount:1,evidence:[{method:"scip-occurrence-callsite",strength:"exact",identity:C.definition.symbol,location:{file:p.file,line:C.sourceLine}}]}})}u+=S.resolvedCallsites;let x=sr(e,p.file,{ranges:[{startLine:p.startLine,endLine:p.endLine}]}),v=new Map;for(let C of x.targets){let R=h.find(I=>I.line===C.line)?.calleeLeaf??C.calleeLeaf,E=Vr(p.file,C.line,R),w=v.get(E)??[];w.push(C),v.set(E,w)}for(let[C,R]of v){if(b.has(C))continue;b.add(C);let E=R.filter(P=>i(P.targetFile)&&!a.some(A=>A.file===P.targetFile&&A.startLine<=P.targetStartLine&&A.endLine>=P.targetEndLine));if(E.length===0)continue;let w=E[0],I=h.find(P=>P.line===w.line)?.calleeLeaf??w.calleeLeaf,k=Xd(y.get(w.line)),D=xc(E.map(P=>({symbol:P.targetSymbol??null,label:P.calleeLeaf,file:P.targetFile,line:P.targetStartLine,endLine:P.targetEndLine}))),F=E.some(P=>(P.resolutionAlternativeCount??0)>1)?"candidate":E.every(P=>P.strength==="exact")?"exact":"derived";o.push({anchor:{id:lr(p.id,w.line,D.map(P=>`${P.file}:${P.line}`).join("|")),status:D.length>1?"ambiguous":F,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:p.id,fromLabel:p.label,callsite:{file:p.file,line:w.line,endLine:w.line,text:f[w.line]?.trim()||`${w.calleeLeaf}()`,signals:k,calleeLeaf:I},alternatives:D.slice(0,3),alternativeCount:D.length,evidence:E.map(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:F,identity:P.targetSymbol??`${P.targetFile}:${P.targetStartLine}-${P.targetEndLine}`,location:{file:p.file,line:w.line}}))}})}u+=v.size;for(let C of h){let R=Vr(p.file,C.line,C.calleeLeaf);b.has(R)||(m+=1)}}return mC(e,o,s,r,{scannedBehaviorSteps:t.length,visibleCallsites:c,graphEvidencedCallsites:u,identityCandidateCallsites:l,ambiguousCallsites:d,unresolvedCallsites:m,upstreamCandidates:0,resultCandidates:0,runtimeCandidates:0})}function mC(e,t,n,r,i,o=[]){let s=hO(t).sort(pC),a=s.filter(f=>pO(e,f)).slice(0,r),c=new Set(a.map(f=>f.anchor.id)),u=s.filter(f=>!c.has(f.anchor.id)),l=a.map(f=>f.anchor),d=u.map(f=>f.anchor),m=xc(l.flatMap(f=>f.alternativeCount===1?f.alternatives:[])),p=xc(d.flatMap(f=>f.alternativeCount===1?f.alternatives:[]));return{anchors:l,withheldAnchors:d,candidateAnchors:s.length,omittedAnchors:Math.max(0,s.length-l.length),...i,inspectCommand:m.length===0?null:`scip-query inspect ${m.map(sC).join(" ")} --view behavior`,remainingInspectCommands:bO(p,8).map(f=>`scip-query inspect ${f.map(sC).join(" ")} --view behavior`)}}function pC(e,t){let n=e.anchor.alternatives[0],r=t.anchor.alternatives[0];return Cc(e.anchor.status)-Cc(t.anchor.status)||(e.anchor.direction??"").localeCompare(t.anchor.direction??"")||(e.anchor.relationKind??"").localeCompare(t.anchor.relationKind??"")||(e.anchor.causalRole??"").localeCompare(t.anchor.causalRole??"")||e.anchor.fromStepId.localeCompare(t.anchor.fromStepId)||e.anchor.callsite.file.localeCompare(t.anchor.callsite.file)||e.anchor.callsite.line-t.anchor.callsite.line||(n?.file??"").localeCompare(r?.file??"")||(n?.line??0)-(r?.line??0)||e.anchor.id.localeCompare(t.anchor.id)}function pO(e,t){if(t.anchor.alternativeCount!==1)return!0;let n=t.anchor.alternatives[0],r=n.endLine??n.line;return K(e,n.file).slice(n.line,r+1).join(`
74
- `).length<=2e4}function Xd(e){return e?.includes("call")?[...e]:["call",...e??[]]}function fO(e,t){let n=new Map;for(let r of t){let i=q(e,r.file).find(a=>a.symbol===r.symbol&&a.isFunctionLike);if(!i)continue;let o={symbol:i.symbol,label:i.leaf,file:i.relativePath,line:i.startLine,endLine:i.endLine},s=n.get(i.symbol);!s||iC(r.source)>iC(s.row.source)?n.set(i.symbol,{row:{...r,...r.callsiteLine===void 0&&s?.row.callsiteLine!==void 0?{callsiteLine:s.row.callsiteLine}:{}},alternative:o}):s.row.callsiteLine===void 0&&r.callsiteLine!==void 0&&n.set(i.symbol,{...s,row:{...s.row,callsiteLine:r.callsiteLine}})}return[...n.values()]}function gO(e){let t=new Map;for(let n of e){let r=Ke(n.alternative.label);t.set(r,(t.get(r)??0)+1)}return t}function fC(e){return e==="semantic-callee"||e==="scip-chunk"||e==="scip-occurrence"?"exact":"derived"}function iC(e){return fC(e)==="exact"?2:1}function ts(e,t,n){return e.find(r=>t>=r.line&&t<=r.endLine&&r.text.includes(n))??e.find(r=>t>=r.line&&t<=r.endLine)??null}function oC(e,t,n,r,i){if(r!==void 0)return e.find(s=>s.line===r&&s.calleeLeaf===n&&ts(t,s.line,n)!==null)??null;let o=e.filter(s=>s.calleeLeaf===n&&ts(t,s.line,s.calleeLeaf)!==null);return i&&o.length===1?o[0]:null}function ns(e){let t=e.attributes.leaf;if(typeof t=="string"&&t.length>0)return Ke(t);let n=e.label.slice(e.label.lastIndexOf(":")+1);return Ke(n)}function Qd(e){if(e?.kind!=="symbol"||!e.id.startsWith("symbol:"))return null;try{return decodeURIComponent(e.id.slice(7))}catch{return null}}function nm(e){return e.location?{symbol:Qd(e),label:e.label,file:e.location.file,line:e.location.line,endLine:e.location.endLine??null}:null}function Zd(e,t){let n=nm(t);return n?.symbol&&q(e,n.file).some(i=>i.symbol===n.symbol&&i.isFunctionLike)?n:null}function em(e,t){return e.evidence.find(n=>n.location?.file===t)?.location??e.evidence.find(n=>n.location!==null)?.location??null}function tm(e){let t={exact:5,derived:4,mixed:3,candidate:2,unknown:1};return e.reduce((n,r)=>t[r.strength]>t[n]?r.strength:n,"unknown")}function hO(e){let t=new Map;for(let n of e){let i=n.anchor.alternatives[0]?.symbol??`${n.anchor.callsite.file}:${n.anchor.callsite.line}:${n.anchor.callsite.calleeLeaf}`,o=t.get(i);(!o||yO(n,o)<0)&&t.set(i,n)}return[...t.values()]}function yO(e,t){return Cc(e.anchor.status)-Cc(t.anchor.status)||e.anchor.alternativeCount-t.anchor.alternativeCount||pC(e,t)}function Cc(e){return{exact:0,derived:1,mixed:2,candidate:3,unknown:4,ambiguous:5}[e]}function xc(e){let t=new Map;for(let n of e)t.set(n.symbol??`${n.file}:${n.line}`,n);return[...t.values()].sort((n,r)=>n.file.localeCompare(r.file)||n.line-r.line||n.label.localeCompare(r.label))}function sC(e){return`--at ${SO(`${e.file}:${e.line+1}`)}`}function bO(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function SO(e){return`'${e.replaceAll("'","'\\''")}'`}function Vr(e,t,n){return`${e}\0${t}\0${n}`}function lr(e,t,n){return["next-anchor",e,String(t),n].map(encodeURIComponent).join(":")}var xC=6,vO=12,CO=48,xO=2e4,gC=12,Yr=Number.MAX_SAFE_INTEGER,RO=["definition","callers","callees"],sm={search:12,"exact-source":24,definition:24,caller:8,callee:8,"production-reference":6,"test-reference":2,dependency:6,consumer:6};function EO(e,t){if(t.cursor)throw new Error("Inspect no longer accepts semantic packet cursors. Run the original inspect selectors again.");let n=wO(t),r=DO(e,n),i=r.candidates.sort((D,F)=>rm(D,F));n.view==="behavior"&&kO(e,i),AO(e,i),n.view==="behavior"&&MO(e,i);let o=ov(i.map(D=>im(D,n.view)),n.evidenceBudgets,(D,F)=>rm(D.candidate,F.candidate)),{selected:s,omitted:a}=cc(o.selected,n.maxUnits,n.maxCharacters,(D,F)=>rm(D.candidate,F.candidate),n.view==="source"),c=s.map(D=>D.candidate),u=[...o.omitted,...a].map(D=>D.candidate),l=c.map(UO),d=ha(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=l.reduce((D,F)=>D+(F.kind==="source"?zO(F.source):0),0),p=l.reduce((D,F)=>D+(F.kind==="source"?F.source.length:0),0),f=l.reduce((D,F)=>D+IC(F,n.view),0),g=l.filter(D=>D.kind==="source"&&(D.roles.includes("search")||D.roles.includes("location"))).map(qO),h=i.filter(D=>D.kind==="source"&&(D.roles.includes("search")||D.roles.includes("location"))).length,y=l.filter(D=>D.kind==="source"&&(D.roles.includes("search")||D.roles.includes("location"))).length,S=r.searches.map(D=>_O(D,i,c)),b=OO(u),x=r.locations.every(D=>D.matched)&&r.evidence.every(D=>D.kind==="matched")&&r.searches.every(D=>$O(D.textCoverage))&&u.every(D=>!D.roles.some(F=>F==="location"||F==="definition")),v=S.reduce((D,F)=>D+F.omittedMatches,0),C=u.length===0&&v===0,R=C?void 0:EC(n,!0),E=FO(n,u),w=IO(C,x,u.length+v,E,S,R),I=i.filter(D=>n.view==="behavior"&&D.kind==="source"&&D.roles.some(F=>F==="location"||F==="definition"||F==="search")).map(D=>({id:`inspect:${D.relativePath}:${D.startLine}-${D.endLine}`,label:D.ownerShort??`${D.relativePath}:${D.startLine+1}`,file:D.relativePath,startLine:D.startLine,endLine:D.endLine})),k=I.length>0?dC(e,I):void 0;return{searches:S,evidence:r.evidence,locations:r.locations,slices:g,candidateSlices:h,omittedSlices:h-y,maxSlices:h,maxTotalLines:m,units:l,candidateUnits:i.length,omittedUnits:u.length,maxUnits:n.maxUnits,maxCharacters:n.maxCharacters,returnedLines:m,returnedCharacters:p,returnedViewCharacters:f,view:n.view,omissionGroups:E,packetCoverage:{mode:C?"complete":"bounded",candidateUnits:i.length,returnedUnits:l.length,omittedUnits:u.length,omittedByRole:b,exactSelectorsComplete:x,maxUnits:n.maxUnits,maxCharacters:n.maxCharacters,channels:BO(i,c,n.evidenceBudgets,n.view),...R?{expansionCommand:R}:{}},stoppingSummary:w,...k&&k.candidateAnchors>0?{causalFrontier:k}:{},bindingClosure:d,continuation:null}}function IO(e,t,n,r,i,o){let s=ct([...r.map(a=>a.drillCommand),...i.flatMap(a=>a.exactFollowup?[a.exactFollowup]:[]),...o?[o]:[]]);return e&&t?{queryStatus:"selection-complete",status:"stop-ready",openEvidence:0,guidance:"All evidence requested by this inspect query was materialized.",drillCommands:[]}:t?{queryStatus:"frontier-accounted",status:"relevance-check-required",openEvidence:n,guidance:"Withheld evidence is accounted for by recoverable groups; drill the groups relevant to the current decision.",drillCommands:s}:{queryStatus:"coverage-incomplete",status:"exact-evidence-withheld",openEvidence:n,guidance:"A requested identity, exact source unit, or current-text coverage requirement is unresolved; drill before relying on it.",drillCommands:s}}function wO(e){let t=$e(e.searches),n=$e(e.symbols),r=$e(e.locations),i=t.length+n.length+r.length;if(i===0)throw new Error("inspect requires at least one --search, --symbol, or --at selector.");if(i>24)throw new RangeError(`inspect accepts at most ${24} selectors; received ${i}.`);let o=e.evidence??{};if(e.unitLines!==void 0&&ur(e.unitLines,"unitLines"),e.totalLines!==void 0&&ur(e.totalLines,"totalLines"),e.sliceLimit!==void 0&&ur(e.sliceLimit,"sliceLimit"),e.maxCharacters!==void 0&&ur(e.maxCharacters,"maxCharacters"),e.maxUnits!==void 0&&ur(e.maxUnits,"maxUnits"),e.view!==void 0&&e.view!=="source"&&e.view!=="behavior")throw new Error(`Unknown inspect view: ${String(e.view)}. Use source or behavior.`);if(e.full&&(e.searchLimit!==void 0||e.maxUnits!==void 0||e.maxCharacters!==void 0||e.evidenceBudgets!==void 0))throw new Error("full inspect cannot be combined with searchLimit, maxUnits, maxCharacters, or evidenceBudgets.");let s=e.full??!1;return{searches:t,symbols:n,locations:r,...e.scope?.trim()?{scope:e.scope.trim()}:{},context:vC(e.context??xC,"context"),searchLimit:ur(e.searchLimit??(s?Yr:vO),"searchLimit"),maxUnits:ur(s?Yr:e.maxUnits??CO,"maxUnits"),maxCharacters:ur(s?Yr:e.maxCharacters??xO,"maxCharacters"),evidenceBudgets:s?PO():LO(e.evidenceBudgets??sm),view:e.view??"source",evidence:{...o.parts?{parts:[...o.parts]}:n.length>0?{parts:[...RO]}:{},...o.referenceContext!==void 0?{referenceContext:vC(o.referenceContext,"referenceContext")}:{},relatedSourceLines:o.relatedSourceLines??60,...o.semantic!==void 0?{semantic:o.semantic}:{}}}}function LO(e){let t={...sm};for(let[n,r]of Object.entries(e)){if(!(n in t))throw new Error(`Unknown inspect evidence channel: ${n}.`);if(!Number.isSafeInteger(r)||(r??-1)<0)throw new RangeError(`Evidence budget ${n} must be a non-negative safe integer; received ${r}.`);t[n]=r}return t}function PO(){return Object.fromEntries(Object.keys(sm).map(e=>[e,Yr]))}function DO(e,t){let n=[],r=0,i=lc(e,t.searches,{scope:t.scope,context:0,limit:t.searchLimit,ranking:"structural"}).map((u,l)=>({pattern:t.searches[l],result:u,matches:u.matches})),o=Math.max(0,...i.map(u=>u.matches.length));for(let u=0;u<o;u+=1)for(let l of i){let d=l.matches[u];if(!d)continue;let m=Jn(e,d.relativePath,d.focusLine,Yr,t.context);m&&ji(e,n,m,"search",`search:${l.pattern}`,d.ownerSymbol,d.ownerShort,1,r++)}let s=i.map(({pattern:u,result:l})=>{let d=l.omittedMatches>0?RC(u,t.scope):void 0,m=l.fileCoverage??[],p=jO(u,m,t.scope);return{pattern:u,matchingLines:l.matchingLines,returnedMatches:l.matches.length,omittedMatches:l.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,gC),omittedScopeHints:Math.max(0,p.length-gC),textCoverage:l.textCoverage,...d?{exactFollowup:d}:{}}}),a=t.locations.map(u=>{let l=GO(u),d=l?ih(e,l.path):null,m=d?Jn(e,d,l.line-1,Yr,t.context):null;return m&&ji(e,n,m,"location",`at:${u}`,null,null,0,r++),{target:u,matched:m!==null}}),c=t.symbols.map(u=>Jd(e,u,t.evidence));for(let u of c)if(u.kind==="matched"){if(u.definition){let l=Jn(e,u.definition.relativePath,u.definition.startLine,Yr,t.context);l&&ji(e,n,l,"definition",`definition:${u.shortName}`,u.symbol,u.shortName,0,r++)}for(let l of u.referenceWindows){let d=l.references[0];ji(e,n,{...l,focusLine:d?.line??l.startLine,unitType:null,unitStartLine:l.startLine,unitEndLine:l.endLine,omittedLines:0},"reference",`reference:${u.shortName}`,d?.enclosingSymbol??null,d?.enclosingShort??null,U(l.relativePath)==="test"?5:4,r++,l.references.map(m=>m.line),u.symbol)}for(let l of u.callers)hC(e,n,l,"caller",u,2,r++);for(let l of u.callees)hC(e,n,l,"callee",u,3,r++);for(let l of u.dependencies)yC(e,n,"dependency",u.file,l.relativePath,u.symbol,t.context,6,r++);for(let l of u.consumers)yC(e,n,"consumer",l.relativePath,u.file,u.symbol,t.context,7,r++)}return{searches:s,evidence:c,locations:a,candidates:n}}function rm(e,t){return e.priority-t.priority||t.roles.length-e.roles.length||t.reasons.length-e.reasons.length||we(U(e.relativePath))-we(U(t.relativePath))||e.sequence-t.sequence}function im(e,t){return{candidate:e,priority:e.priority,sequence:e.sequence,relativePath:e.relativePath,fileKind:U(e.relativePath),evidenceCharacters:IC(e,t),roles:e.roles,reasons:e.reasons,symbols:e.symbols,behaviorSignals:e.kind==="source"?e.behavior?.signals??[]:[],channel:om(e)}}function om(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")?U(e.relativePath)==="test"?"test-reference":"production-reference":t.includes("dependency")?"dependency":t.includes("consumer")?"consumer":"search"}function MO(e,t){let n=t.filter(i=>i.kind==="source"),r=go(e,{files:ct(n.map(i=>i.relativePath))});for(let i of n){i.behavior=Ri(e,i.relativePath,i.startLine,i.endLine,i.focusLines)??void 0;let o=r.filter(a=>a.source.file===i.relativePath&&a.source.startLine<=i.endLine&&a.source.endLine>=i.startLine),s=o.filter(a=>!TO(a,o)).map(a=>({observationId:a.id,protocol:a.protocol,action:a.action,role:a.role,strength:a.strength,resolution:a.resolution,line:a.source.startLine,endLine:a.source.endLine,keyParts:a.keyParts.map(c=>({name:c.name,value:c.value,evidence:c.evidence})),derivation:{kind:a.derivation.kind,rule:a.derivation.rule,sourceSpans:a.derivation.sourceSpans.length}}));i.runtimeFacts=s.length>0?s:void 0}}function TO(e,t){if(e.strength!=="candidate"||e.protocol!=="http")return!1;let n=e.keyParts.find(i=>i.name==="path")?.value,r=e.keyParts.find(i=>i.name==="method")?.value;return n?t.some(i=>{if(i===e||i.action!==e.action||i.role!==e.role||i.source.startLine!==e.source.startLine||i.derivation.rule!=="http.mount-prefix")return!1;let o=i.keyParts.find(a=>a.name==="path")?.value,s=i.keyParts.find(a=>a.name==="method")?.value;return!!(o&&o!==n&&o.endsWith(n)&&(!r||r===s))}):!1}function kO(e,t){for(let n of t){if(n.kind!=="source")continue;let r=ot(e,n.relativePath,n.startLine,n.endLine,n.focusLines);r.startLine===n.startLine&&r.endLine===n.endLine||(n.startLine=r.startLine,n.endLine=r.endLine,n.source=K(e,n.relativePath).slice(r.startLine,r.endLine+1).join(`
75
- `),n.unitStartLine=r.startLine,n.unitEndLine=r.endLine,n.omittedLines=0)}}function AO(e,t){for(let n of t)n.kind==="source"&&(n.bindingClosure=xi(e,n.relativePath,n.startLine,n.endLine))}function FO(e,t){let n=new Map;for(let r of t){let i=Rc(r.relativePath),o=om(r),s=[...r.roles].sort().join(","),a=r.kind==="path"?r.relationship:"",c=`${i}|${o}|${s}|${a}`,u=n.get(c)??[];u.push(r),n.set(c,u)}return[...n.entries()].map(([r,i])=>{let o=i[0],s=ct(i.flatMap(c=>[...c.roles])).sort(),a=ct(i.flatMap(c=>c.kind==="source"?c.behavior?.signals??[]:[])).sort();return{id:`g-${CC("sha256").update(r).digest("hex").slice(0,8)}`,scope:Rc(o.relativePath),channel:om(o),roles:s,behaviorSignals:a,candidateUnits:i.length,sourceCharacters:i.reduce((c,u)=>c+(u.kind==="source"?u.source.length:0),0),anchors:i.map(c=>({relativePath:c.relativePath,line:c.kind==="source"?c.focusLine:0,ownerShort:c.kind==="source"?c.ownerShort:null,roles:[...c.roles],behaviorSignals:c.kind==="source"?[...c.behavior?.signals??[]]:[]})),drillCommand:NO(e,i)}}).sort((r,i)=>i.candidateUnits-r.candidateUnits||i.sourceCharacters-r.sourceCharacters||r.scope.localeCompare(i.scope)||r.id.localeCompare(i.id))}function NO(e,t){let n=ct(t.flatMap(o=>o.reasons.filter(s=>s.startsWith("search:")).map(s=>s.slice(7)))),r=Rc(t[0].relativePath);if(n.length>0&&t.every(o=>o.kind==="source"&&o.roles.includes("search"))){let o=["scip-query inspect"];for(let s of n)o.push(`--search ${_t(s)}`);return o.push(`--scope ${_t(r)}`,"--full"),e.view==="behavior"&&o.push("--view behavior"),o.join(" ")}let i=t.filter(o=>o.kind==="source");if(i.length>0&&i.length<=24){let o=["scip-query inspect"];for(let s of i)o.push(`--at ${_t(`${s.relativePath}:${s.focusLine+1}`)}`);return e.view==="behavior"&&o.push("--view behavior"),o.join(" ")}return t.length===1&&t[0].kind==="path"?t[0].exactFollowup:EC(e,!0)}function _O(e,t,n){let r=`search:${e.pattern}`,i=t.filter(a=>a.reasons.includes(r)).length,o=new Set(n),s=t.filter(a=>a.reasons.includes(r)&&o.has(a)).length;return{...e,candidateUnits:i,selectedUnits:s,omittedUnits:i-s}}function OO(e){let t={};for(let n of e)for(let r of n.roles)t[r]=(t[r]??0)+1;return t}function BO(e,t,n,r){let i=e.map(s=>im(s,r).channel),o=t.map(s=>im(s,r).channel);return Object.fromEntries(Object.keys(n).map(s=>{let a=i.filter(u=>u===s).length,c=o.filter(u=>u===s).length;return[s,{candidateUnits:a,returnedUnits:c,omittedUnits:a-c,maxUnits:n[s]}]}))}function $O(e){return!!(e&&e.skippedUnreadablePaths.length===0&&e.skippedOversizedPaths.length===0)}function jO(e,t,n){let r=new Map;for(let i of t){let o=Rc(i.relativePath),s=r.get(o)??{matchingLines:0,returnedMatches:0};s.matchingLines+=i.matchingLines,s.returnedMatches+=i.returnedMatches,r.set(o,s)}return[...r.entries()].map(([i,o])=>({scope:i,...o,exactFollowup:RC(e,i||n)})).sort((i,o)=>o.matchingLines-i.matchingLines||o.returnedMatches-i.returnedMatches||i.scope.localeCompare(o.scope))}function Rc(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}function RC(e,t){return`scip-query inspect --search ${_t(e)}${t?` --scope ${_t(t)}`:""} --full`}function EC(e,t){let n=["scip-query inspect"];for(let r of e.searches)n.push(`--search ${_t(r)}`);for(let r of e.symbols)n.push(`--symbol ${_t(r)}`);for(let r of e.locations)n.push(`--at ${_t(r)}`);return e.scope&&n.push(`--scope ${_t(e.scope)}`),e.context!==xC&&n.push(`--context ${e.context}`),e.evidence.parts&&n.push(`--include ${_t(e.evidence.parts.join(","))}`),t&&n.push("--full"),e.view==="behavior"&&n.push("--view behavior"),n.join(" ")}function hC(e,t,n,r,i,o,s){ji(e,t,{...n,unitType:null,unitStartLine:n.startLine,unitEndLine:n.endLine+n.omittedLines},r,`${r}:${i.shortName}`,n.symbol,n.shortName,o,s,[n.focusLine],i.symbol)}function yC(e,t,n,r,i,o,s,a,c){let u=`${r} -> ${i}`,l=ce(e,r).filter(h=>h.sourcePath===i),d=K(e,r),m=HO(d,l,i),p=m===null?null:wa(e,r,m,Math.min(s,4));if(p){ji(e,t,{...p,unitType:null,unitStartLine:p.startLine,unitEndLine:p.endLine,omittedLines:0},n,`${n}:${u}`,null,null,a,c,[p.focusLine],o);return}let f=`scip-query inspect --search ${_t(wC(i))} --scope ${_t(r)}`,g=t.find(h=>h.kind==="path"&&h.relativePath===r&&h.relationship===u);if(g){g.roles=ct([...g.roles,n]),g.reasons=ct([...g.reasons,`${n}:${u}`]),g.symbols=ct([...g.symbols,o]),g.priority=Math.min(g.priority,a);return}t.push({kind:"path",roles:[n],relativePath:r,relationship:u,reasons:[`${n}:${u}`],symbols:[o],exactFollowup:f,priority:a,sequence:c})}function HO(e,t,n){let r=ct(t.flatMap(c=>[c.importedName,c.localName??""]).filter(c=>c.length>1)),i=wC(n).replace(/\.[^.]+$/u,""),o=ct([...r,i]).filter(Boolean),s=/\b(?:from|import|include|require|use)\b/u,a=e.findIndex(c=>s.test(c)&&o.some(u=>c.includes(u)));return a>=0?a:null}function ji(e,t,n,r,i,o,s,a,c,u=[n.focusLine],l){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=K(e,n.relativePath).slice(m,p+1).join(`
76
- `),d.focusLine=Math.min(d.focusLine,n.focusLine),d.focusLines=SC([...d.focusLines,...u]),d.unitStartLine=Math.min(d.unitStartLine,n.unitStartLine),d.unitEndLine=Math.max(d.unitEndLine,n.unitEndLine),d.omittedLines=Math.max(d.omittedLines,n.omittedLines),d.reasons=ct([...d.reasons,i]),d.roles=ct([...d.roles,r]),d.symbols=ct([...d.symbols,...l?[l]:[]]),!d.ownerSymbol&&o&&(d.ownerSymbol=o),!d.ownerShort&&s&&(d.ownerShort=s),d.priority=Math.min(d.priority,a);return}t.push({kind:"source",...n,reasons:[i],focusLines:SC(u),ownerSymbol:o,ownerShort:s,roles:[r],symbols:l?[l]:[],priority:a,sequence:c})}function UO(e){if(e.kind==="path"){let{priority:o,sequence:s,...a}=e;return{...a,id:bC(a)}}let{priority:t,sequence:n,bindingClosure:r,...i}=e;return{...i,id:bC(i),omittedCharacters:0}}function qO(e){let{kind:t,id:n,roles:r,symbols:i,omittedCharacters:o,behavior:s,runtimeFacts:a,...c}=e;return c}function bC(e){return CC("sha256").update(JSON.stringify(e)).digest("hex").slice(0,16)}function GO(e){let t=e.match(/^(.+\.\w+):(\d+)$/u);if(!t)return null;let n=Number(t[2]);return Number.isSafeInteger(n)&&n>0?{path:t[1],line:n}:null}function ct(e){return[...new Set(e)]}function SC(e){return ct(e).sort((t,n)=>t-n)}function zO(e){return e.length===0?0:e.split(`
77
- `).length}function IC(e,t){if(e.kind==="path")return e.relationship.length+e.exactFollowup.length;let n="bindingClosure"in e?Ih(e.bindingClosure):0,r=(e.runtimeFacts??[]).reduce((i,o)=>i+o.action.length+o.derivation.rule.length+o.keyParts.reduce((s,a)=>s+a.name.length+a.value.length+4,0)+24,0);return t!=="behavior"?e.source.length+n:e.behavior?e.behavior.lines.reduce((i,o)=>i+o.text.length+o.signals.join(",").length+12,0)+e.behavior.testCases.reduce((i,o)=>i+o.length+2,0)+r+n:e.source.length+n+r}function wC(e){return e.split("/").at(-1)??e}function _t(e){return`'${e.replaceAll("'","'\\''")}'`}function ur(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new RangeError(`${t} must be a positive safe integer; received ${e}`);return e}function vC(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 KO}from"path";function WO(e,t){let n=t.className,r=Ze(e,n);return r.match?r.total>1?{kind:"ambiguous",query:n,total:r.total,candidates:[LC(r.match),...r.candidates]}:{kind:"matched",query:n,owner:YO(r.match),methods:VO(e,r.match)}:{kind:"missing",query:n,suggestions:ta(e,n,5)}}function VO(e,t){let n=G(t.symbol),i=new H(e).definitionsForFile(t.relativePath).filter(c=>Qe(c.symbol)),o=i.filter(c=>c.parentTypeName===n||c.symbol.includes(n)),a=(o.length>0?o:JO(KO(t.relativePath))===n?i.filter(c=>c.symbol.includes("<invalid-global-code>")):[]).map(c=>({startLine:c.startLine,endLine:c.endLine,name:G(c.symbol)}));return ae(t.relativePath)!=="clojure"?a:QO(a,XO(e,t))}function LC(e){return{symbol:e.symbol,shortName:T(e.symbol),relativePath:e.relativePath,startLine:e.startLine}}function YO(e){return{...LC(e),endLine:e.endLine}}function JO(e){return e.replace(/\.[^.]+$/,"")}function XO(e,t){let n=G(t.symbol);return n?(W(e,t.relativePath)?.clojureMembers??[]).filter(r=>r.ownerName===n).map(r=>({startLine:r.startLine,endLine:r.endLine,name:r.memberName})):[]}function QO(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.name}:${r.startLine}:${r.endLine}`,r);return[...n.values()].sort((r,i)=>r.startLine-i.startLine||r.endLine-i.endLine)}import{createHash as p1}from"crypto";var aae={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."},ZO=[{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 eB(e){let t=new Set(e);return ZO.filter(n=>n.families.some(r=>t.has(r)))}function PC(e){return eB(e).map(t=>`[${t.id}] ${t.capability} ${t.consequence} Recover selected paths with: ${t.recoverWith.map(n=>`scip-query ${n}`).join(", ")}.`)}var tB=["incoming","outgoing","both"];function he(e,t,n,r={}){return{family:e,subtype:t,...r.match?{match:r.match}:{},directions:tB,evidenceStrengths:r.strengths??["exact","derived","mixed"],supportCeiling:r.supportCeiling??"partial",establishes:n,nonClaims:r.nonClaims??[],recoverWith:r.recoverWith??["inspect","code"]}}var nB=["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"],rB=["captured-value-to-state","constant-to-state","expression-to-state","property-to-state","return-to-state","value-to-state"],iB=["await-completion-before","awaits-completion","inside-lock-scope","lexical-successor"],oB=[{id:"indexed-program-identity",label:"SCIP/compiler identity and source ownership",requirements:["indexed-graph"],relations:[he("execution","call","The source construct may call the resolved target.",{strengths:["exact","derived","candidate","mixed"],nonClaims:["Static may-call reachability does not prove that an invocation occurred at runtime."],recoverWith:["call-graph","inspect","code"]}),he("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"]}),he("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"]}),he("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"]}),he("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"]}),he("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"]}),he("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"]}),he("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"]}),he("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:[he("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"]}),he("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"]}),he("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"]}),he("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:[...nB.map(e=>he("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"]})),he("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"]}),he("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=>he("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:[he("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"]}),he("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"]}),he("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"]}),he("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"]}),he("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:[...rB.map(e=>he("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=>he("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"]})),...iB.map(e=>he("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 Ec(e,t){let n=oB.flatMap(r=>r.relations.filter(i=>i.family===e&&(i.match==="prefix"?t.startsWith(i.subtype):t===i.subtype)).map(i=>({provider:r,relation:i})));if(n.length>1)throw new Error(`Ambiguous graph relation provider for ${e}/${t}: ${n.map(r=>r.provider.id).join(", ")}`);return n[0]??null}var Gt=["execution","runtime","dataflow","state","temporal","contract","identity","ownership","dependencies"];function He(e,t){let n=new Map;for(let r of e){let i=t(r),o=n.get(i)??[];o.push(r),n.set(i,o)}return n}function Hi(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 DC(e,t){return Hi(e.origins)-Hi(t.origins)||e.depth-t.depth||e.startLine-t.startLine||e.shortName.localeCompare(t.shortName)}var MC=["call","contract-symbol","import","reference","runtime-boundary"],sB={call:[{family:"control",subtype:"call"}],"contract-symbol":[{family:"contract",subtype:"uses-contract-symbol"}],import:[{family:"identity",subtype:"imports"}],reference:[{family:"identity",subtype:"references"}]},aB={"structural-membership":[{family:"identity",subtype:"contains"}],"boundary-observation":[{family:"identity",subtype:"owns-runtime-observation"}],"external-import":[{family:"identity",subtype:"imports-external"}]};function TC(e){if(e.kind!=="runtime-boundary")return kC(sB[e.kind]);let t=e.fromBoundaryParticipant?.protocol??e.toBoundaryParticipant?.protocol,n={crossesRuntimeBoundary:!0,...t?{protocol:t}:{},...e.runtimeBoundaryKey?{runtimeKey:e.runtimeBoundaryKey}:{}},r=[{family:"control",subtype:"runtime-handoff",context:n}];return e.evidence==="runtime-boundary:carrier.discriminator"&&(r.push({family:"control",subtype:"discriminator-dispatch",context:{...n},attributes:{joinRule:"carrier.discriminator",...e.fromBoundaryParticipant?.action?{producerAction:e.fromBoundaryParticipant.action}:{},...e.toBoundaryParticipant?.action?{consumerAction:e.toBoundaryParticipant.action}:{}}}),r.push({family:"data",subtype:"serialized-discriminator-transfer",context:{...n},attributes:{joinRule:"carrier.discriminator"}})),e.evidence==="runtime-boundary:queue.address"&&e.fromBoundaryParticipant?.action==="queue.send"&&e.toBoundaryParticipant?.action==="queue.consume"&&r.push({family:"temporal",subtype:"enqueue-before-consume",context:{...n},attributes:{producerAction:e.fromBoundaryParticipant.action,consumerAction:e.toBoundaryParticipant.action,retryPolicy:"unknown"}}),r}function Ic(e){return kC(aB[e])}function kC(e){return e.map(t=>({...t,...t.context?{context:{...t.context}}:{},...t.attributes?{attributes:{...t.attributes}}:{}}))}import{join as AB}from"path";import{createRequire as cB}from"module";import{resolve as is}from"path";var lB=cB(import.meta.url),rs;function FC(e,t,n){let r=uB();if(!r)return am("The TypeScript compiler runtime is unavailable.");let i=dB(r,e,t),o=i.getSourceFile(is(t))??i.getSourceFile(t);if(!o)return am(`The TypeScript compiler did not materialize ${t}.`);let s={ts:r,sourceFile:o,checker:i.getTypeChecker(),points:new Map,edges:new Map,unsupported:new Set,nextCfgId:0},a=pB(r,o,n);if(a.length===0)return am("No function-like construct intersects the selected source range.");let c=new Map(a.map(d=>[d,fB(o,d)])),u=a.map(d=>hB(s,d,gB(r,d,c),c.get(d)));for(let d of u)yB(s,d),CB(s,d),EB(s,d);wB(s,u);let l=[...s.unsupported].sort();return{points:[...s.points.values()].map(({node:d,...m})=>m).sort(kB),edges:[...s.edges.values()].sort((d,m)=>d.id.localeCompare(m.id)),coverage:{status:l.length===0?"complete":"partial",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:l}}}function uB(){if(rs!==void 0)return rs;try{rs=lB("typescript")}catch{rs=vi()?.ts??null}return rs}function dB(e,t,n){let r=is(n),i={target:e.ScriptTarget.ESNext,module:e.ModuleKind.NodeNext,moduleResolution:e.ModuleResolutionKind.NodeNext,skipLibCheck:!0,noResolve:!0},o=e.createSourceFile(r,t,i.target,!0,mB(e,r)),s=e.createCompilerHost(i,!0),a=s.getSourceFile.bind(s),c=s.readFile.bind(s),u=s.fileExists.bind(s);return s.getSourceFile=(l,d,m,p)=>is(l)===r?o:a(l,d,m,p),s.readFile=l=>is(l)===r?t:c(l),s.fileExists=l=>is(l)===r||u(l),e.createProgram([r],i,s)}function mB(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 pB(e,t,n){let r=[],i=o=>{if(NC(e,o)){let s=t.getLineAndCharacterOfPosition(o.getStart(t)).line,a=t.getLineAndCharacterOfPosition(o.getEnd()).line;(!n||s<=n.endLine&&a>=n.startLine)&&r.push(o)}o.forEachChild(i)};return t.forEachChild(i),r.sort((o,s)=>o.getStart(t)-s.getStart(t))}function NC(e,t){return e.isFunctionLike(t)&&"body"in t&&t.body!==void 0}function fB(e,t){return`callable:${encodeURIComponent(e.fileName)}:${t.getStart(e)}:${t.getEnd()}`}function gB(e,t,n){for(let r=t.parent;r;r=r.parent)if(NC(e,r)&&n.has(r))return n.get(r);return null}function hB(e,t,n,r){let i=new Map,o=Ve(e,i,"exit",null),s=t.body,a=o.id;if(s&&e.ts.isBlock(s))a=cm(e,i,[...s.statements],o.id,{breakTarget:null,continueTarget:null});else if(s){let u=Ve(e,i,"statement",s);Ee(i,u.id,o.id),a=u.id}let c=Ve(e,i,"entry",t);return Ee(i,c.id,a),{id:r,node:t,parentId:n,cfg:i,entryId:c.id,exitId:o.id}}function cm(e,t,n,r,i){let o=r;for(let s=n.length-1;s>=0;s-=1)o=Jr(e,t,n[s],o,i);return o}function Jr(e,t,n,r,i){let o=e.ts;if(o.isBlock(n))return cm(e,t,[...n.statements],r,i);if(o.isIfStatement(n)){let a=Ve(e,t,"predicate",n.expression),c=Jr(e,t,n.thenStatement,r,i),u=n.elseStatement?Jr(e,t,n.elseStatement,r,i):r;return Ee(t,a.id,c),Ee(t,a.id,u),a.id}if(o.isWhileStatement(n)){let a=Ve(e,t,"predicate",n.expression),c=Jr(e,t,n.statement,a.id,{breakTarget:r,continueTarget:a.id});return Ee(t,a.id,c),Ee(t,a.id,r),a.id}if(o.isDoStatement(n)){let a=Ve(e,t,"predicate",n.expression),c=Jr(e,t,n.statement,a.id,{breakTarget:r,continueTarget:a.id});return Ee(t,a.id,c),Ee(t,a.id,r),c}if(o.isForStatement(n)){let a=Ve(e,t,"predicate",n.condition??n),c=n.incrementor?Ve(e,t,"statement",n.incrementor):null;c&&Ee(t,c.id,a.id);let u=c?.id??a.id,l=Jr(e,t,n.statement,u,{breakTarget:r,continueTarget:u});if(Ee(t,a.id,l),n.condition&&Ee(t,a.id,r),!n.initializer)return a.id;let d=Ve(e,t,"statement",n.initializer);return Ee(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=Ve(e,t,"predicate",n.expression),c=Ve(e,t,"statement",n.initializer),u=Jr(e,t,n.statement,a.id,{breakTarget:r,continueTarget:a.id});return Ee(t,a.id,c.id),Ee(t,a.id,r),Ee(t,c.id,u),a.id}if(o.isSwitchStatement(n)){e.unsupported.add("switch fallthrough is represented conservatively; discriminant-to-case value refinement is unsupported.");let a=Ve(e,t,"predicate",n.expression),c=r,u=[];for(let l=n.caseBlock.clauses.length-1;l>=0;l-=1){let d=n.caseBlock.clauses[l];c=cm(e,t,[...d.statements],c,{...i,breakTarget:r}),u.push(c)}for(let l of u)Ee(t,a.id,l);return Ee(t,a.id,r),a.id}if(o.isReturnStatement(n)||o.isThrowStatement(n)){let a=Ve(e,t,"statement",n),c=[...t.values()].find(u=>u.kind==="exit");return Ee(t,a.id,c.id),a.id}if(o.isBreakStatement(n)){let a=Ve(e,t,"statement",n);return i.breakTarget||e.unsupported.add("A break statement could not be attached to a structured target."),Ee(t,a.id,i.breakTarget??r),a.id}if(o.isContinueStatement(n)){let a=Ve(e,t,"statement",n);return i.continueTarget||e.unsupported.add("A continue statement could not be attached to a structured target."),Ee(t,a.id,i.continueTarget??r),a.id}if(o.isTryStatement(n)){e.unsupported.add("Exceptional control-flow and finally completion are not included in the local compiler CFG.");let a=Ve(e,t,"statement",n);return a.invalidatesAllDefinitions=!0,Ee(t,a.id,r),a.id}let s=Ve(e,t,"statement",n);return Ee(t,s.id,r),s.id}function Ve(e,t,n,r){let i={id:`cfg:${e.nextCfgId++}`,kind:n,ast:r,successors:new Set,predecessors:new Set,definitions:[],uses:[],displayPoint:null,invalidatesAllDefinitions:!1};return t.set(i.id,i),i}function Ee(e,t,n){e.get(t).successors.add(n),e.get(n).predecessors.add(t)}function yB(e,t){let n=t.cfg.get(t.entryId);for(let r of t.node.parameters){let i=Xr(e,r.name);if(!i){e.unsupported.add("Destructured parameter definition-use is not implemented.");continue}n.definitions.push({point:Qr(e,i.node,"parameter-definition",i.symbolKey,i.name,t.id),rhsUseIds:[]})}for(let r of t.cfg.values())!r.ast||r.kind==="entry"||r.kind==="exit"||(r.kind==="predicate"&&(r.displayPoint=Qr(e,r.ast,"predicate",null,"predicate",t.id)),bB(e,t,r,r.ast),!r.displayPoint&&r.definitions.length===0&&r.uses.length===0&&(r.displayPoint=Qr(e,r.ast,"statement",null,PB(e,r.ast),t.id)))}function bB(e,t,n,r){let i=e.ts;if(i.isTryStatement(r))return;let o=s=>{if(!(s!==r&&i.isFunctionLike(s))){if(i.isVariableDeclaration(s)){let a=s.initializer?wc(e,t.id,s.initializer,n):[];n.uses.push(...a);let c=Xr(e,s.name);c?n.definitions.push({point:Qr(e,c.node,"definition",c.symbolKey,c.name,t.id),rhsUseIds:a.map(u=>u.point.id)}):(n.invalidatesAllDefinitions=!0,e.unsupported.add("Destructured variable reaching definitions are not implemented."));return}if(i.isBinaryExpression(s)&&BC(i,s.operatorToken.kind)){let a=wc(e,t.id,s.right,n);s.operatorToken.kind!==i.SyntaxKind.EqualsToken&&a.push(...wc(e,t.id,s.left,n)),n.uses.push(...a);let c=Xr(e,s.left);c?n.definitions.push({point:Qr(e,c.node,"definition",c.symbolKey,c.name,t.id),rhsUseIds:a.map(u=>u.point.id)}):(n.invalidatesAllDefinitions=!0,e.unsupported.add("Dynamic or destructured assignment targets are not included in reaching definitions."));return}if((i.isPrefixUnaryExpression(s)||i.isPostfixUnaryExpression(s))&&(s.operator===i.SyntaxKind.PlusPlusToken||s.operator===i.SyntaxKind.MinusMinusToken)){let a=wc(e,t.id,s.operand,n);n.uses.push(...a);let c=Xr(e,s.operand);c&&n.definitions.push({point:Qr(e,c.node,"definition",c.symbolKey,c.name,t.id),rhsUseIds:a.map(u=>u.point.id)});return}if(!(i.isFunctionDeclaration(s)||i.isClassDeclaration(s)||i.isInterfaceDeclaration(s))){if(_C(e,s)){let a=OC(e,t.id,s);a&&n.uses.push(a),i.isPropertyAccessExpression(s)&&o(s.expression);return}s.forEachChild(o)}}};o(r),n.uses=$C(n.uses)}function wc(e,t,n,r){let i=[],o=s=>{if(!e.ts.isFunctionLike(s)){if(e.ts.isBinaryExpression(s)&&BC(e.ts,s.operatorToken.kind)){r.invalidatesAllDefinitions=!0,e.unsupported.add("Nested assignment expressions are not included in ordered local definition-use flow."),s.operatorToken.kind!==e.ts.SyntaxKind.EqualsToken&&o(s.left),o(s.right);return}if(_C(e,s)){let a=OC(e,t,s);a&&i.push(a),e.ts.isPropertyAccessExpression(s)&&o(s.expression);return}s.forEachChild(o)}};return o(n),$C(i)}function _C(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&&SB(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)||vB(e.ts,t))}function SB(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 vB(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 OC(e,t,n){let r=Xr(e,n);return r?{point:Qr(e,r.node,"use",r.symbolKey,r.name,t),property:e.ts.isPropertyAccessExpression(n)}:null}function Xr(e,t){let n=e.ts;if(n.isIdentifier(t)){let r=AC(e,t);return r?{node:t,symbolKey:r,name:t.text}:null}if(n.isPropertyAccessExpression(t)){let r=AC(e,t.name);return r?{node:t,symbolKey:r,name:t.getText(e.sourceFile)}:null}return n.isParenthesizedExpression(t)||n.isAsExpression(t)||n.isTypeAssertionExpression(t)||n.isNonNullExpression(t)?Xr(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 AC(e,t){let n=e.checker.getSymbolAtLocation(t);if(!n)return null;if((n.flags&e.ts.SymbolFlags.Alias)!==0)try{n=e.checker.getAliasedSymbol(n)}catch{}let r=n.valueDeclaration??n.declarations?.[0];return r?`symbol:${encodeURIComponent(r.getSourceFile().fileName)}:${r.getStart()}:${n.getName()}`:`symbol:${n.getName()}`}function Qr(e,t,n,r,i,o){let s=t.getStart(e.sourceFile),a=t.getEnd(),c=e.sourceFile.getLineAndCharacterOfPosition(s),u=`flow-point:${encodeURIComponent(e.sourceFile.fileName)}:${s}:${a}:${n}:${encodeURIComponent(r??i)}`,l=e.points.get(u);if(l)return l;let d={id:u,kind:n,name:i,symbolKey:r,callableId:o,start:s,end:a,line:c.line,column:c.character,node:t};return e.points.set(u,d),d}function CB(e,t){let n=[...t.cfg.values()].flatMap(c=>c.definitions),r=new Map(n.map(c=>[c.point.id,c])),i=xB(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 u=MB([...c.predecessors].map(m=>s.get(m))),l=new Set(u);c.invalidatesAllDefinitions&&l.clear();let d=RB(c.definitions);for(let m of d){for(let p of i.get(m.point.symbolKey)??[])l.delete(p.point.id);l.add(m.point.id)}lm(o.get(c.id),u)||(o.set(c.id,u),a=!0),lm(s.get(c.id),l)||(s.set(c.id,l),a=!0)}}for(let c of t.cfg.values()){let u=o.get(c.id);for(let l of c.uses){let d=c.definitions.filter(p=>p.point.symbolKey===l.point.symbolKey&&p.point.start<l.point.start&&!p.rhsUseIds.includes(l.point.id)).sort((p,f)=>f.point.start-p.point.start)[0],m=d?[d.point.id]:u;for(let p of m){let f=r.get(p);f.point.symbolKey===l.point.symbolKey&&os(e,"reaching-definition",f.point.id,l.point.id,"exact","A CFG path reaches this use without an intervening definition.")}}for(let l of c.definitions)for(let d of l.rhsUseIds)os(e,"value-source",d,l.point.id,"exact","This right-hand-side use supplies the new definition.")}}function xB(e){let t=new Map;for(let n of e){if(!n.point.symbolKey)continue;let r=t.get(n.point.symbolKey)??[];r.push(n),t.set(n.point.symbolKey,r)}return t}function RB(e){let t=new Map;for(let n of e)n.point.symbolKey&&t.set(n.point.symbolKey,n);return[...t.values()]}function EB(e,t){let n=IB(t);for(let r of t.cfg.values()){if(r.successors.size<2||!r.displayPoint)continue;let i=n.get(r.id);for(let o of r.successors)for(let s of n.get(o)??[]){if(i.has(s)||s===t.exitId)continue;let a=t.cfg.get(s),c=[...a.definitions.map(u=>u.point),...a.uses.map(u=>u.point),...a.displayPoint?[a.displayPoint]:[]];for(let u of DB(c))os(e,"control-dependence",r.displayPoint.id,u.id,"exact","The target postdominates a branch successor but does not postdominate the predicate.")}}}function IB(e){let t=[...e.cfg.keys()],n=new Set(t),r=new Map;for(let o of t)r.set(o,o===e.exitId?new Set([o]):new Set(n));let i=!0;for(;i;){i=!1;for(let o of e.cfg.values()){if(o.id===e.exitId)continue;let s=[...o.successors].map(c=>r.get(c)),a=new Set([o.id,...TB(s)]);lm(r.get(o.id),a)||(r.set(o.id,a),i=!0)}}return r}function wB(e,t){let n=new Map(t.map(s=>[s.id,s.parentId])),r=t.flatMap(s=>[...s.cfg.values()].flatMap(a=>a.definitions.map(c=>c.point))),i=new Map;for(let s of r){if(!s.symbolKey)continue;let a=i.get(s.symbolKey)??[];a.push(s),i.set(s.symbolKey,a)}let o=new Set([...e.edges.values()].filter(s=>s.kind==="reaching-definition").map(s=>s.toPointId));for(let s of t)for(let a of[...s.cfg.values()].flatMap(c=>c.uses)){if(!a.point.symbolKey||o.has(a.point.id))continue;let c=i.get(a.point.symbolKey)??[];for(let u of c)LB(u.callableId,a.point.callableId,n)?os(e,"closure-capture",u.id,a.point.id,"candidate","Compiler identity proves the captured binding, but invocation order can select among outer definitions."):a.property&&os(e,"field-definition-to-use",u.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 LB(e,t,n){for(let r=n.get(t)??null;r;r=n.get(r)??null)if(r===e)return!0;return!1}function os(e,t,n,r,i,o){let s=`local-flow-edge:${t}:${encodeURIComponent(n)}:${encodeURIComponent(r)}`;e.edges.set(s,{id:s,kind:t,fromPointId:n,toPointId:r,strength:i,reason:o})}function BC(e,t){return t>=e.SyntaxKind.FirstAssignment&&t<=e.SyntaxKind.LastAssignment}function PB(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 $C(e){return[...new Map(e.map(t=>[t.point.id,t])).values()]}function DB(e){return[...new Map(e.map(t=>[t.id,t])).values()]}function MB(e){return new Set(e.flatMap(t=>[...t]))}function TB(e){return e.length===0?new Set:new Set([...e[0]].filter(t=>e.slice(1).every(n=>n.has(t))))}function lm(e,t){return e.size===t.size&&[...e].every(n=>t.has(n))}function kB(e,t){return e.start-t.start||e.kind.localeCompare(t.kind)||e.id.localeCompare(t.id)}function am(e){return{points:[],edges:[],coverage:{status:"unsupported",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:[e]}}}var FB=Vt("typescript-local-flow",{clearGroups:["whole-project","source-file","semantic-provider"]});function um(e,t,n,r){if(!Wn(t))return null;let i=`${t}\0${n}\0${r}`;return FB.get(e,i,()=>{let o=V(e,t);return o?FC(o,AB(e.config.projectRoot,t),{startLine:n,endLine:r}):{points:[],edges:[],coverage:{status:"unsupported",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:[`Current source is unavailable for ${t}.`]}}})}function NB(e,t=new Map){let n=new Map,r=new Map,i=[];for(let o of e.transfers){if(!e.caller)continue;let s=Lc(e.caller,o.callerPosition),a=Lc(e.callee,o.calleePosition);ss(n,s),ss(n,a),mm(r,e.caller,s),mm(r,e.callee,a);let c=rt("edge","data-transfer",o.proof.file,String(o.proof.startLine),String(o.callerPosition),String(o.calleePosition));r.set(c,{id:c,kind:"data-transfer",fromNodeId:s.id,toNodeId:a.id,directed:!0,disposition:"folded",semantics:[{family:"data",subtype:"argument-to-parameter",attributes:{argumentText:o.argumentText,callerPosition:o.callerPosition,calleePosition:o.calleePosition}}],evidence:[{method:"compiler-callsite-direct-parameter-transfer",strength:"exact",identity:`${e.caller.symbol}:${o.callerPosition} -> ${e.callee.symbol}:${o.calleePosition}`,location:{file:o.proof.file,line:o.proof.startLine,endLine:o.proof.endLine}}]})}return e.unknown.forEach((o,s)=>{let a=Lc(e.callee,o.calleePosition);ss(n,a),mm(r,e.callee,a);let c=t.get(o.calleePosition);if(c&&KB(c)){zB(r,n,e,o.calleePosition,o.argumentText,c);return}let u=qB(e,o.calleePosition,o.argumentText);ss(n,u);let l=rt("edge","data-transfer-unsupported",o.proof.file,String(o.proof.startLine),String(o.calleePosition),String(s));r.set(l,{id:l,kind:"data-transfer",fromNodeId:u.id,toNodeId:a.id,directed:!0,disposition:"unsupported",semantics:[{family:"data",subtype:"argument-to-parameter",attributes:{argumentText:o.argumentText,calleePosition:o.calleePosition}}],evidence:[{method:"compiler-callsite-argument-expression",strength:"exact",identity:o.argumentText,location:{file:o.proof.file,line:o.proof.startLine,endLine:o.proof.endLine}}]}),i.push({id:rt("frontier","data-transfer",l),kind:"data-transfer",direction:"unresolved",fromNodeIds:[u.id],edgeIds:[l],memberNodeIds:[a.id],memberCount:1,disposition:"unsupported",reason:c?.derivation.rule??o.reason,expansion:null})}),{nodes:[...n.values()],edges:[...r.values()],frontiers:i,blindSpots:[]}}function HC(e,t,n=[]){let r=UC(),i=new Map,o=new Set;for(let s of t){if(s.kind!=="call"||!s.fromSymbol||!s.toSymbol||s.line===null)continue;let a=UB(i,e,s.toFile,s.toSymbol);if(!a)continue;let c=Mg(e,a),u=c.sites.filter(g=>g.file===s.fromFile&&g.startLine<=s.line&&g.endLine>=s.line&&g.caller?.symbol===s.fromSymbol);if(u.length!==1){let g=c.unresolved.find(h=>h.file===s.fromFile&&h.line===s.line);g&&r.blindSpots.push(`Parameter flow unresolved at ${s.fromFile}:${s.line+1}: ${g.reason}.`);continue}let l=u[0],d=`${l.file}\0${l.callNode.startIndex}\0${l.callNode.endIndex}\0${a.symbol}`;if(o.has(d))continue;o.add(d);let m=Tg(e,l),p=J(e,l.file)?.rootNode,f=new Map;if(p)for(let g of m.unknown){let h=Sg({db:e,file:l.file,root:p},l.arguments[g.calleePosition]);h&&f.set(g.calleePosition,h)}jC(r,NB(m,f)),m.caller&&jB(l.callNode)&&HB(r,m,l.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=um(e,s.location.file,s.location.line,a);if(c){jC(r,_B(s,c.points,c.edges));for(let u of c.coverage.unsupported)r.blindSpots.push(`TypeScript local flow is partial for ${s.location.file}:${s.location.line+1}-${a+1}: ${u} Recover with: scip-query inspect --at '${s.location.file}:${s.location.line+1}-${a+1}' --view behavior.`)}}return r.blindSpots=[...new Set(r.blindSpots)].sort(),r}function _B(e,t,n){let r=UC(),i=new Map,o=new Map,s=new Map,a=e.location.file;for(let c of t){let u=OB(e,a,c);s.set(c.id,u.id),i.set(u.id,u),BB(o,e,u)}for(let c of n){let u=s.get(c.fromPointId),l=s.get(c.toPointId);if(!u||!l)continue;let d=$B(c),m=rt("edge","typescript-local-flow",a,c.id);o.set(m,{id:m,kind:c.kind==="control-dependence"?"control-dependence":"data-transfer",fromNodeId:u,toNodeId:l,directed:!0,disposition:"folded",semantics:[d],evidence:[{method:"typescript-compiler-cfg-reaching-definitions",strength:c.strength,identity:c.reason,location:i.get(u)?.location??e.location}]})}return r.nodes=[...i.values()],r.edges=[...o.values()],r}function OB(e,t,n){return{id:rt("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 BB(e,t,n){let r=rt("edge","local-flow-owner",t.id,n.id);e.has(r)||e.set(r,{id:r,kind:"local-flow-owner",fromNodeId:t.id,toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:"contains"}],evidence:[{method:"typescript-compiler-local-flow-owner",strength:"exact",identity:t.id,location:n.location}]})}function $B(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 jB(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 HB(e,t,n){if(!t.caller)return;let r={id:rt("call-result",t.call.file,String(n.startIndex),String(n.endIndex),t.callee.symbol),kind:"call-result",label:`result of ${t.callee.leaf}`,disposition:"folded",location:{file:t.call.file,line:t.call.startLine,endLine:t.call.endLine},anchorIds:[],attributes:{calleeSymbol:t.callee.symbol,callerSymbol:t.caller.symbol}},i=rt("edge","return-to-call-result",t.callee.symbol,r.id),o=rt("edge","call-result-owner",t.caller.symbol,r.id);e.nodes.push(r),e.edges.push({id:i,kind:"data-transfer",fromNodeId:pm(t.callee.symbol),toNodeId:r.id,directed:!0,disposition:"folded",semantics:[{family:"data",subtype:"return-to-call-result"}],evidence:[{method:"compiler-callsite-used-result",strength:"exact",identity:`${t.callee.symbol} -> ${t.caller.symbol}`,location:r.location}]},{id:o,kind:"call-result-owner",fromNodeId:pm(t.caller.symbol),toNodeId:r.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:"contains-call-result"}],evidence:[{method:"compiler-call-result-owner",strength:"exact",identity:t.caller.symbol,location:r.location}]})}function UC(){return{nodes:[],edges:[],frontiers:[],blindSpots:[]}}function jC(e,t){dm(e.nodes,t.nodes),dm(e.edges,t.edges),dm(e.frontiers,t.frontiers),e.blindSpots.push(...t.blindSpots)}function dm(e,t){let n=new Set(e.map(r=>r.id));for(let r of t)n.has(r.id)||(n.add(r.id),e.push(r))}function UB(e,t,n,r){let i=`${n}\0${r}`,o=e.get(i);if(o!==void 0)return o;let s=q(t,n).find(a=>a.symbol===r)??null;return e.set(i,s),s}function Lc(e,t){return{id:YB(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 qB(e,t,n){return{id:rt("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 GB(e,t,n){return{id:rt("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 zB(e,t,n,r,i,o){let s=GB(n,r,o),a=Lc(n.callee,r);ss(t,s);let c=rt("edge","static-value-transfer",n.call.file,String(n.call.startLine),String(r));e.set(c,{id:c,kind:"data-transfer",fromNodeId:s.id,toNodeId:a.id,directed:!0,disposition:"folded",semantics:[{family:"data",subtype:WB(o),attributes:{argumentText:i,calleePosition:r,value:o.value,precision:o.precision,derivationRule:o.derivation.rule}}],evidence:VB(o,n)})}function KB(e){return e.derivation.kind!=="heuristic"&&e.precision!=="symbolic"&&e.precision!=="unknown"}function WB(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 VB(e,t){return(e.derivation.sourceSpans.length>0?e.derivation.sourceSpans:[t.call]).map(r=>({method:`static-value:${e.derivation.rule}`,strength:e.derivation.kind==="direct"?"exact":"derived",identity:e.derivation.inputFactIds.join(",")||e.value,location:{file:r.file,line:r.startLine,endLine:r.endLine}}))}function ss(e,t){e.has(t.id)||e.set(t.id,t)}function mm(e,t,n){let r=rt("edge","parameter-owner",t.symbol,n.id);e.has(r)||e.set(r,{id:r,kind:"parameter-owner",fromNodeId:pm(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 YB(e,t){return rt("parameter",e,String(t))}function pm(e){return rt("symbol",e)}function rt(...e){return e.map(t=>encodeURIComponent(t)).join(":")}function qC(e,t){let n=new Map,r=new Map,i=new Map,o=new Set;for(let s of t){if(!s.location||!["source-construct","symbol"].includes(s.kind))continue;let a=s.location.endLine??s.location.line,c=kh(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 u of c.facts){let l=fm(s,u.controller),d=fm(s,u.outcome);n.set(l.id,l),n.set(d.id,d),JB(r,s,l);let m=Zr("edge","control-dependence",l.id,d.id,u.subtype);r.set(m,{id:m,kind:"control-dependence",fromNodeId:l.id,toNodeId:d.id,directed:!0,disposition:"folded",semantics:[{family:"control",subtype:u.subtype,attributes:{...u.attributes}}],evidence:[{method:"parser-control-dependence",strength:"exact",identity:`${s.location.file}:${u.controller.startLine+1}-${u.outcome.startLine+1}`,location:{file:s.location.file,line:u.controller.startLine,endLine:u.controller.endLine}}]})}for(let u of c.terminals){let l=fm(s,u);n.set(l.id,l);let d=u.label.startsWith("throw")||u.label.startsWith("raise")?"throw":"return",m=Zr("edge","control-terminal",s.id,l.id,d);r.set(m,{id:m,kind:"control-terminal",fromNodeId:s.id,toNodeId:l.id,directed:!0,disposition:"folded",semantics:[{family:"control",subtype:d==="throw"?"throws":"returns"}],evidence:[{method:"parser-terminal-statement",strength:"exact",identity:u.label,location:{file:s.location.file,line:u.startLine,endLine:u.endLine}}]})}for(let u of c.unsupported){let l=Zr("control-unsupported",s.location.file,String(u.startLine),String(u.endLine),u.reason);n.set(l,{id:l,kind:"control-unsupported",label:u.reason,disposition:"unsupported",location:{file:s.location.file,line:u.startLine,endLine:u.endLine},anchorIds:[],attributes:{ownerNodeId:s.id}});let d=Zr("edge","control-unsupported",s.id,l);r.set(d,{id:d,kind:"control-dependence",fromNodeId:s.id,toNodeId:l,directed:!0,disposition:"unsupported",semantics:[{family:"control",subtype:"unresolved-control-construct"}],evidence:[{method:"parser-control-construct",strength:"exact",identity:u.reason,location:{file:s.location.file,line:u.startLine,endLine:u.endLine}}]});let m=Zr("frontier","control-dependence",l);i.set(m,{id:m,kind:"control-dependence",direction:"unresolved",fromNodeIds:[s.id],edgeIds:[d],memberNodeIds:[l],memberCount:1,disposition:"unsupported",reason:u.reason,expansion:null})}}return{nodes:[...n.values()],edges:[...r.values()],frontiers:[...i.values()],blindSpots:[...o].sort()}}function fm(e,t){let n=e.location.file;return{id:Zr(`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 JB(e,t,n){let r=Zr("edge","control-owner",t.id,n.id);e.has(r)||e.set(r,{id:r,kind:"control-owner",fromNodeId:t.id,toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:"contains-control"}],evidence:[{method:"parser-control-owner",strength:"exact",identity:t.id,location:t.location}]})}function Zr(...e){return e.map(t=>encodeURIComponent(t)).join(":")}var Pc=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"]),cs=new Set(["block","body","compound_statement","declaration_list","statement_block"]),XB=new Set(["assignment","assignment_expression","augmented_assignment_expression"]),hm=new Set(["update_expression"]),WC=new Set(["array_access","element_access_expression","subscript_expression"]),VC=new Set(["attribute","field_access","field_expression","member_access_expression","member_expression","selector_expression"]),QB=new Set(["false","null","null_literal","number","number_literal","string","string_literal","template_string","true"]),ZB=new Set(["call_expression","method_invocation","object_creation_expression"]),e$=new Set(["comment","else_clause","formal_parameters","parameters","type_parameters"]);function YC(e,t,n,r){let i=J(e,t);if(!i)return null;let o=c$(i.rootNode,n,r);if(!o)return null;let s=[],a=[],c=[];return ei(o,u=>{if(XB.has(u.type)||hm.has(u.type)||XC(u)){let l=t$(u);l?s.push(l):c.push({family:"state",startLine:u.startPosition.row,endLine:u.endPosition.row,reason:`Mutation target ${cn(u.text)} could not be resolved to an exact source resource.`})}}),ei(o,u=>{if(!cs.has(u.type))return;let l=s$(u);for(let d=0;d<l.length-1;d+=1)a.push({from:as(l[d]),to:as(l[d+1]),subtype:"lexical-successor",synchronizationScope:null,attributes:{sameScope:!0,executionConditional:!0}});for(let d=0;d<l.length;d+=1){let m=l[d],p=u$(m).filter(f=>f.type==="await_expression");for(let f of p){let g=ls("event",`await ${cn(f.text.replace(/^await\s+/u,""))}`,f);a.push({from:as(m),to:g,subtype:"awaits-completion",synchronizationScope:null,attributes:{completionRequired:!0}});let h=l[d+1];h&&a.push({from:g,to:as(h),subtype:"await-completion-before",synchronizationScope:null,attributes:{continuationOnly:!0}})}}}),ei(o,u=>{if(u.type!=="synchronized_statement")return;let l=u.childForFieldName("object")??u.childForFieldName("condition")??u.namedChildren.find(g=>!cs.has(g.type)),d=u.childForFieldName("body")??u.namedChildren.find(g=>cs.has(g.type));if(!l||!d){c.push({family:"temporal",startLine:u.startPosition.row,endLine:u.endPosition.row,reason:"Synchronized scope has no structurally resolved monitor or body."});return}let m=cn(l.text).replace(/^\(|\)$/gu,""),p=ls("lock",m,l),f=l$(d).filter(g=>g.parent!==null&&QC(g));for(let g of a$(f))a.push({from:p,to:as(g),subtype:"inside-lock-scope",synchronizationScope:m,attributes:{syntaxNative:!0}})}),{mutations:s,temporal:a,unsupported:c}}function t$(e){let t=XC(e),n=e.childForFieldName("left")??e.childForFieldName("argument")??(t?e.namedChildren.at(-1)??null:e.namedChildren[0]??null);if(!n)return null;let r=n$(n);if(!r)return null;let i=t?"delete":hm.has(e.type)||!o$(e,n).startsWith("=")?"update":"assign",o=t||hm.has(e.type)?null:e.childForFieldName("right");return{event:ls("event",cn(e.text),e),resource:{kind:"resource",label:r.name,startLine:n.startPosition.row,endLine:n.endPosition.row},operation:i,durabilityClass:"in-memory",recordIdentity:r.recordIdentity,value:o?ls("value",cn(o.text),o):null,dataSubtype:o?r$(o,e):null}}function n$(e){if(WC.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 VC.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 r$(e,t){return QB.has(e.type)||/(?:integer|float|decimal|boolean|character)_literal$/u.test(e.type)?"constant-to-state":ZB.has(e.type)?"return-to-state":VC.has(e.type)||WC.has(e.type)?"property-to-state":/identifier$/u.test(e.type)?i$(e.text,t)?"captured-value-to-state":"value-to-state":"expression-to-state"}function i$(e,t){let n=gm(t.parent);if(!n||GC(n,e))return!1;let r=gm(n.parent);for(;r;){if(GC(r,e))return!0;r=gm(r.parent)}return!1}function gm(e){let t=e;for(;t;){if(Pc.has(t.type))return t;t=t.parent}return null}function GC(e,t){let n=e.childForFieldName("parameters")??e.namedChildren.find(o=>["formal_parameters","parameters"].includes(o.type));if(n&&zC(n,t))return!0;let r=e.childForFieldName("body")??e.namedChildren.find(o=>cs.has(o.type));if(!r)return!1;let i=!1;return JC(r,e,o=>{if(i||!/(?:declarator|declaration|parameter)$/u.test(o.type))return;let s=o.childForFieldName("name")??o.childForFieldName("pattern")??o.namedChildren[0];s&&zC(s,t)&&(i=!0)}),i}function zC(e,t){let n=!1;return ei(e,r=>{/identifier$/u.test(r.type)&&r.text===t&&(n=!0)}),n}function JC(e,t,n){n(e);for(let r of e.namedChildren)r!==t&&Pc.has(r.type)||JC(r,t,n)}function o$(e,t){let n=e.childForFieldName("right"),r=Math.max(0,t.endIndex-e.startIndex),i=n?Math.max(r,n.startIndex-e.startIndex):e.text.length;return e.text.slice(r,i).trim()}function XC(e){return(e.type==="delete_expression"||e.type==="unary_expression")&&/^delete\b/u.test(e.text.trim())}function s$(e){return e.namedChildren.filter(t=>QC(t))}function QC(e){return e$.has(e.type)||cs.has(e.type)?!1:/(?:statement|declaration)$/u.test(e.type)||e.type==="expression_statement"||e.type==="local_variable_declaration"}function a$(e){let t=new Set(e);return e.filter(n=>{let r=n.parent;for(;r;){if(t.has(r))return!1;r=r.parent}return!0})}function as(e){return ls("event",cn(e.text),e)}function ls(e,t,n){return{kind:e,label:t,startLine:n.startPosition.row,endLine:n.endPosition.row}}function c$(e,t,n){let r=[];return ei(e,o=>{o.startPosition.row<=t&&o.endPosition.row>=n&&r.push(o)}),r.filter(o=>Pc.has(o.type)).sort(KC)[0]??r.sort(KC)[0]??null}function KC(e,t){return e.endIndex-e.startIndex-(t.endIndex-t.startIndex)||e.startIndex-t.startIndex}function l$(e){let t=[];return ei(e,n=>t.push(n)),t}function u$(e){let t=[],n=r=>{t.push(r);for(let i of r.namedChildren)i!==e&&Pc.has(i.type)||n(i)};return n(e),t}function ei(e,t){t(e);for(let n of e.namedChildren)ei(n,t)}function cn(e){return e.trim().replace(/\s+/gu," ")}function tx(e,t,n=[]){let r=new Map,i=new Map,o=new Map,s=new Set;for(let a of t){if(!a.location||!["source-construct","symbol"].includes(a.kind))continue;let c=a.location.endLine??a.location.line,u=YC(e,a.location.file,a.location.line,c);if(!u){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 l of u.mutations){let d=Mc(a,l.event),m=h$(a,l.resource,l.durabilityClass);if(r.set(d.id,d),r.set(m.id,m),Tc(i,a,d,"contains-state-effect"),kc(i,{kind:"state-resource",from:d,to:m,semantics:[{family:"state",subtype:l.operation==="delete"?"deletes-resource":"writes-resource",attributes:{operation:l.operation,durabilityClass:l.durabilityClass,resource:l.resource.label,recordIdentity:l.recordIdentity,transactionMembership:"unknown"}}],method:"parser-state-mutation",identity:l.event.label}),l.value&&l.dataSubtype){let p=Mc(a,l.value);r.set(p.id,p),kc(i,{kind:"data-to-state",from:p,to:m,semantics:[{family:"data",subtype:l.dataSubtype,attributes:{operation:l.operation,resource:l.resource.label,recordIdentity:l.recordIdentity,value:l.value.label}}],method:"parser-assignment-value",identity:`${l.value.label} -> ${l.resource.label}`})}}for(let l of u.temporal){let d=Mc(a,l.from),m=Mc(a,l.to);r.set(d.id,d),r.set(m.id,m),Tc(i,a,d,l.from.kind==="lock"?"contains-lock-scope":"contains-event"),Tc(i,a,m,"contains-event"),kc(i,{kind:"temporal-order",from:d,to:m,semantics:[{family:"temporal",subtype:l.subtype,context:l.synchronizationScope?{synchronizationScope:l.synchronizationScope}:void 0,attributes:{...l.attributes}}],method:l.subtype==="inside-lock-scope"?"parser-synchronized-scope":"parser-program-order",identity:`${l.from.label} -> ${l.to.label}`})}for(let l of u.unsupported){let d=An(`${l.family}-unsupported`,a.location.file,String(l.startLine),String(l.endLine),l.reason);r.set(d,{id:d,kind:`${l.family}-unsupported`,label:l.reason,disposition:"unsupported",location:{file:a.location.file,line:l.startLine,endLine:l.endLine},anchorIds:[],attributes:{ownerNodeId:a.id}});let m=An("edge",`${l.family}-unsupported`,a.id,d);i.set(m,{id:m,kind:`${l.family}-unsupported`,fromNodeId:a.id,toNodeId:d,directed:!0,disposition:"unsupported",semantics:[{family:l.family,subtype:`unresolved-${l.family}-construct`}],evidence:[{method:`parser-${l.family}-construct`,strength:"exact",identity:l.reason,location:{file:a.location.file,line:l.startLine,endLine:l.endLine}}]});let p=An("frontier",l.family,d);o.set(p,{id:p,kind:l.family,direction:"unresolved",fromNodeIds:[a.id],edgeIds:[m],memberNodeIds:[d],memberCount:1,disposition:"unsupported",reason:l.reason,expansion:null})}}for(let a of t.filter(c=>c.kind==="runtime-boundary-participant")){let c=Dc(a,"protocol"),u=Dc(a,"action"),l=Dc(a,"address")??a.label;!c||!u||!ex(c,u)||ZC(r,i,a,{observationId:a.id,action:u,strength:"exact",file:a.location?.file??"",line:a.location?.line??0,address:l,protocol:c,role:Dc(a,"role")??void 0,resolution:"locally-linked"})}for(let a of n){if(!a.protocol||!ex(a.protocol,a.action))continue;let c=f$(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}ZC(r,i,c,a)}return{nodes:[...r.values()],edges:[...i.values()],frontiers:[...o.values()],blindSpots:[...s].sort()}}function ZC(e,t,n,r){let i=m$(r),s={id:An("runtime-state-event",r.observationId),kind:"runtime-state-event",label:`${r.action} ${i}`,disposition:"folded",location:{file:r.file,line:r.line},anchorIds:[],attributes:{action:r.action,protocol:r.protocol??null,modality:r.modality??null,resolution:r.resolution??null}},a=r.protocol==="database"?"external-durable-intent":"external",c={id:An("runtime-state-resource",r.protocol??"unknown",i),kind:"runtime-state-resource",label:i,disposition:"folded",location:{file:r.file,line:r.line},anchorIds:[],attributes:{protocol:r.protocol??null,durabilityClass:a}};e.set(s.id,s),e.set(c.id,c),Tc(t,n,s,"contains-runtime-state-effect");let u=d$(r.action);kc(t,{kind:"runtime-state-resource",from:s,to:c,semantics:[{family:"state",subtype:u,context:{crossesRuntimeBoundary:!0,protocol:r.protocol},attributes:{operation:r.action,durabilityClass:a,resource:i,recordIdentity:p$(r),modality:r.modality??null,resolution:r.resolution??null,transactionMembership:"unknown",commitState:r.protocol==="database"?"unknown":null}}],method:`runtime-boundary-${r.strength}`,identity:r.observationId})}function d$(e){return e==="database.read"?"reads-resource":e==="queue.send"?"enqueues-resource":e==="queue.consume"?"consumes-resource":"writes-resource"}function m$(e){return(e.keyParts?.find(n=>["address","resource"].includes(n.name))?.value??e.address)||e.observationId}function p$(e){return e.keyParts?.find(n=>/^(?:id|key|record)$/u.test(n.name))?.value??null}function ex(e,t){return e==="database"&&["database.read","database.write"].includes(t)||e==="queue"&&["queue.consume","queue.send"].includes(t)}function Dc(e,t){let n=e.attributes[t];return typeof n=="string"?n:null}function f$(e,t,n,r){let i=e.filter(s=>s.location?.file===t&&["source-construct","symbol"].includes(s.kind)),o=i.filter(s=>s.location.line<=n&&(s.location.endLine??s.location.line)>=n).sort(g$)[0];if(o)return o;if(r){let s=i.find(a=>a.label===r||a.label.endsWith(`.${r}`)||a.label.includes(r));if(s)return s}return i.length===1?i[0]:null}function g$(e,t){let n=(e.location?.endLine??e.location?.line??0)-(e.location?.line??0),r=(t.location?.endLine??t.location?.line??0)-(t.location?.line??0);return n-r}function Mc(e,t){let n=e.location.file;return{id:An(`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 h$(e,t,n){let r=e.location.file;return{id:An("program-resource",r,e.id,t.label,n),kind:"program-resource",label:t.label,disposition:"folded",location:{file:r,line:t.startLine,endLine:t.endLine},anchorIds:[],attributes:{ownerNodeId:e.id,durabilityClass:n}}}function Tc(e,t,n,r){let i=An("edge","program-owner",t.id,n.id,r);e.has(i)||e.set(i,{id:i,kind:"program-owner",fromNodeId:t.id,toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:r}],evidence:[{method:"parser-program-owner",strength:"exact",identity:t.id,location:n.location}]})}function kc(e,t){let n=An("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 An(...e){return e.map(t=>encodeURIComponent(t)).join(":")}var y$=new Set(["control","data","state","temporal"]),Ac=new Set(["contains-control","contains-event","contains-lock-scope","contains-state-effect","contains-runtime-state-effect","contains","owns-parameter","owns-runtime-observation"]),ox=new Set(["discriminator-dispatch","result-callback","returns","runtime-handoff","throws"]);function sx(e,t={}){let n=new Map(e.nodes.map(E=>[E.id,E])),r=E$(e.nodes,t.focusLocations),i=I$(e.edges,t.focusLocations),o=w$(e.edges,i),s=new Set(e.paths.flatMap(E=>E.edgeIds)),a=Fn(e.anchors.filter(E=>E.status==="matched").flatMap(E=>E.nodeIds)),u=e.edges.filter(ix).filter(E=>b$(E,r,i,s)),l=u.filter(E=>x$(E,r,i,o,n,s)),d=nx(a,l,"forward"),m=C$(d,l),p=nx(m,l,"backward"),f=new Set([...d].filter(E=>p.has(E)));for(let E of a)f.add(E);let g=new Set(l.filter(E=>f.has(E.fromNodeId)&&f.has(E.toNodeId)).map(E=>E.id)),h=new Set(f),y=new Set(g);S$(u,h,y,r,i);let S=e.frontiers.filter(E=>P$(E,h)),b=Fn(S.filter(E=>E.disposition==="unsupported").map(E=>E.id)),x=Fn(e.edges.filter(E=>!ix(E)&&cx(E)&&L$(E,h)).map(E=>E.id)),v=Fn(S.map(E=>E.id)),C=[];a.length===0&&C.push("No matched anchor node starts the corridor."),m.length===0&&C.push("No proved mechanical outcome is reachable from a matched anchor."),b.length>0&&C.push(`${b.length} unsupported frontier(s) touch the protected corridor.`),x.length>0&&C.push(`${x.length} candidate or unknown edge(s) touch the protected corridor.`);let R=C.length===0?"complete":"incomplete";return{schemaVersion:1,status:R,startNodeIds:a,outcomeNodeIds:m,baseNodeIds:Fn([...f]),baseEdgeIds:Fn([...g]),nodeIds:Fn([...h]),edgeIds:Fn([...y]),accountedFrontierIds:v,unresolvedFrontierIds:b,unresolvedEdgeIds:x,coverage:{protectedNodes:h.size,protectedEdges:y.size,baseNodes:f.size,baseEdges:g.size,accountedFrontiers:v.length,unresolvedFrontiers:b.length,unresolvedEdges:x.length},explanation:R==="complete"?"Every proved anchor-to-outcome path is closed over its material causal facts within reported coverage.":C.join(" ")}}function b$(e,t,n,r){return t===null||e.disposition==="emitted"||r.has(e.id)||n?.has(e.id)===!0?!0:(e.semantics??[]).some(i=>{if(i.family==="identity"&&Ac.has(i.subtype))return t.has(e.toNodeId);if(i.family==="contract")return t.has(e.fromNodeId)&&t.has(e.toNodeId);if(i.family==="state")return t.has(e.fromNodeId);if(i.family==="data"||i.family==="temporal")return t.has(e.fromNodeId)||t.has(e.toNodeId);if(i.family==="control"){if(lx(i))return t.has(e.fromNodeId);if(["returns","throws"].includes(i.subtype))return t.has(e.toNodeId);if(i.subtype==="completion-callback")return t.has(e.fromNodeId)||t.has(e.toNodeId)}return!1})}function S$(e,t,n,r,i){let o=!0;for(;o;){o=!1;for(let s of e)v$(s,t,r,i)&&(n.has(s.id)||(n.add(s.id),o=!0),t.has(s.fromNodeId)||(t.add(s.fromNodeId),o=!0),t.has(s.toNodeId)||(t.add(s.toNodeId),o=!0))}}function v$(e,t,n,r){let i=t.has(e.fromNodeId),o=t.has(e.toNodeId);return!i&&!o?!1:(e.semantics??[]).some(s=>s.family==="identity"?Ac.has(s.subtype)&&(o||n===null||n.has(e.toNodeId)):s.family==="contract"?!0:s.family==="state"?i&&(n===null||n.has(e.fromNodeId)):s.family==="temporal"?s.subtype==="lexical-successor"?i&&o:!0:s.family==="data"?o&&(i||n===null||n.has(e.fromNodeId)||r?.has(e.id)===!0):s.family==="control"?ax(s)||["returns","throws"].includes(s.subtype)&&!o&&n!==null&&!n.has(e.toNodeId)?!1:ox.has(s.subtype)||lx(s)||s.subtype==="completion-callback":!1)}function C$(e,t){let n=new Set,r=new Map,i=new Map;for(let o of t)!e.has(o.fromNodeId)||!e.has(o.toNodeId)||(r.set(o.fromNodeId,(r.get(o.fromNodeId)??0)+1),i.set(o.toNodeId,(i.get(o.toNodeId)??0)+1),(o.semantics??[]).some(s=>s.family==="state"||s.family==="control"&&ox.has(s.subtype))&&n.add(o.toNodeId));for(let o of e)(i.get(o)??0)>0&&(r.get(o)??0)===0&&n.add(o);return Fn([...n])}function nx(e,t,n){let r=new Map;for(let s of t){let a=n==="forward"?s.fromNodeId:s.toNodeId,c=n==="forward"?s.toNodeId:s.fromNodeId,u=r.get(a)??[];u.push(c),r.set(a,u)}let i=new Set(e),o=[...e];for(;o.length>0;){let s=o.shift();for(let a of r.get(s)??[])i.has(a)||(i.add(a),o.push(a))}return i}function x$(e,t,n,r,i,o){return(e.semantics??[]).some(s=>e.disposition==="emitted"||o.has(e.id)?!0:s.family==="identity"&&Ac.has(s.subtype)?t===null||t.has(e.toNodeId)||r?.has(e.toNodeId)===!0:!y$.has(s.family)||ax(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"?R$(e,i)&&(t.has(e.fromNodeId)||t.has(e.toNodeId)):!1)}function ax(e){return e.family==="control"&&["call","discriminator-dispatch","result-callback","runtime-handoff"].includes(e.subtype)}function R$(e,t){let n=t.get(e.fromNodeId),r=t.get(e.toNodeId);if(!n||!r)return!1;let i=rx(n,"ownerNodeId")??(n.kind==="symbol"?n.id:null),o=rx(r,"ownerNodeId")??(r.kind==="symbol"?r.id:null);return i!==null&&i===o}function E$(e,t){if(!t)return null;let n=new Map;for(let r of t){let i=n.get(r.file)??[];i.push(r.line),n.set(r.file,i)}return new Set(e.filter(r=>{if(!r.location||r.kind==="parameter")return!1;let i=n.get(r.location.file)??[],o=r.location.endLine??r.location.line;return i.some(s=>s>=r.location.line&&s<=o)}).map(r=>r.id))}function I$(e,t){if(!t)return null;let n=new Map;for(let r of t){let i=n.get(r.file)??[];i.push(r.line),n.set(r.file,i)}return new Set(e.filter(r=>r.evidence.some(i=>{if(!i.location)return!1;let o=n.get(i.location.file)??[],s=i.location.endLine??i.location.line;return o.some(a=>a>=i.location.line&&a<=s)})).map(r=>r.id))}function w$(e,t){return t===null?null:new Set(e.filter(n=>t.has(n.id)).flatMap(n=>[n.fromNodeId,n.toNodeId]))}function rx(e,t){let n=e.attributes[t];return typeof n=="string"?n:null}function ix(e){return e.disposition==="excluded"||e.disposition==="unsupported"||!cx(e)?!1:e.evidence.some(t=>t.strength==="exact"||t.strength==="derived")}function cx(e){return(e.semantics??[]).some(t=>t.family!=="identity"||Ac.has(t.subtype))}function lx(e){return e.subtype.startsWith("predicate-")||e.subtype.startsWith("loop-")||e.subtype.startsWith("exception-")||e.subtype.startsWith("finally-")||e.subtype.startsWith("handler-")}function L$(e,t){return t.has(e.fromNodeId)||t.has(e.toNodeId)}function P$(e,t){return[...e.fromNodeIds,...e.memberNodeIds].some(n=>t.has(n))}function Fn(e){return[...new Set(e)].sort()}import{createHash as D$}from"crypto";var Fc=["identity","contract","control","data","state","temporal"],M$=new Set(Fc);function _c(e){let t=qi(e.anchors,"anchor"),n=qi(e.nodes,"node"),r=qi(e.edges,"edge"),i=qi(e.paths??[],"path"),o=qi(e.frontiers??[],"frontier"),s=new Set(t.map(p=>p.id)),a=new Set(n.map(p=>p.id)),c=new Set(r.map(p=>p.id)),u=e.routeCatalog?{...e.routeCatalog,routes:qi(e.routeCatalog.routes,"route"),selectedRouteIds:lt(e.routeCatalog.selectedRouteIds)}:void 0;for(let p of t)St(`anchor ${p.id}`,[...p.nodeIds,...p.candidateNodeIds],a,"node");for(let p of n)St(`node ${p.id}`,p.anchorIds,s,"anchor");for(let p of r){if(St(`edge ${p.id}`,[p.fromNodeId,p.toNodeId],a,"node"),p.evidence.length===0)throw new Error(`Exploration edge ${p.id} has no evidence source.`);A$(p)}for(let p of i)St(`path ${p.id}`,[p.fromAnchorId,p.toAnchorId],s,"anchor"),St(`path ${p.id}`,p.nodeIds,a,"node"),St(`path ${p.id}`,p.edgeIds,c,"edge");for(let p of o)if(St(`frontier ${p.id}`,p.fromNodeIds,a,"node"),St(`frontier ${p.id}`,p.edgeIds,c,"edge"),St(`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 u?.routes??[])St(`route ${p.id}`,p.nodeIds,a,"node"),St(`route ${p.id}`,p.edgeIds,c,"edge"),St(`route ${p.id}`,[p.anchorNodeId,p.endpointNodeId],a,"node");u&&St("route catalog selection",u.selectedRouteIds,new Set(u.routes.map(p=>p.id)),"route");let l=lt(e.incompleteReasons??[]),d=l.length===0?"accounted":"incomplete",m=t.reduce((p,f)=>p+f.omittedCandidates,0);return{schemaVersion:1,anchors:t,nodes:n,edges:r,paths:i,frontiers:o,coverage:{status:d,scope:e.scope,nodes:bx(n),edges:bx(r),matchedAnchors:t.filter(p=>p.status==="matched").length,ambiguousAnchors:t.filter(p=>p.status==="ambiguous").length,missingAnchors:t.filter(p=>p.status==="missing").length,omittedCandidates:m,frontierGroups:o.length,programEdges:k$(r),blindSpots:lt(e.blindSpots??[]),explanation:d==="accounted"?"Every node and edge discovered within the declared query scope is emitted, folded with recoverable identity, explicitly excluded, or reported unsupported.":`The declared query scope is not fully accounted for: ${l.join("; ")}`},completion:_$(d,i,e.scope),...u?{routeCatalog:u}:{}}}function T$(e){return e.flatMap(t=>F$(t.semantics??[]).map(n=>({id:N$(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 k$(e){let t=T$(e),n=new Set(t.map(s=>s.sourceEdgeId)),r=new Map(Fc.map(s=>[s,new Set])),i=new Map(Fc.map(s=>[s,new Set])),o=new Map(Fc.map(s=>[s,0]));for(let s of t)r.get(s.family).add(s.sourceEdgeId),i.get(s.family).add(s.subtype),o.set(s.family,o.get(s.family)+1);return{sourceEdges:e.length,mappedSourceEdges:n.size,projectedEdges:t.length,unmappedSourceEdges:e.length-n.size,unsupportedSourceEdges:e.filter(s=>s.disposition==="unsupported").length,unmappedKinds:lt(e.filter(s=>!n.has(s.id)).map(s=>s.kind)),families:{identity:Ui("identity",r,o,i),contract:Ui("contract",r,o,i),control:Ui("control",r,o,i),data:Ui("data",r,o,i),state:Ui("state",r,o,i),temporal:Ui("temporal",r,o,i)}}}function Ui(e,t,n,r){return{sourceEdges:t.get(e)?.size??0,projectedEdges:n.get(e)??0,subtypes:[...r.get(e)??[]].sort()}}function A$(e){let t=new Set;for(let n of e.semantics??[]){if(!M$.has(n.family))throw new Error(`Exploration edge ${e.id} has unknown program edge family: ${n.family}.`);if(n.subtype.trim().length===0)throw new Error(`Exploration edge ${e.id} has an empty program edge subtype.`);let r=ym(n);if(t.has(r))throw new Error(`Exploration edge ${e.id} repeats program edge semantic ${r}.`);t.add(r)}}function F$(e){return[...e].sort((t,n)=>ym(t).localeCompare(ym(n)))}function ym(e){return`${e.family}:${e.subtype}`}function N$(e,t){return`program:${encodeURIComponent(e)}:${t.family}:${encodeURIComponent(t.subtype)}`}function _$(e,t,n){return e==="incomplete"||t.some(r=>r.status!=="connected")?{status:"coverage-incomplete",scope:n,explanation:"The declared graph query has an ambiguous, missing, candidate-only, or disconnected anchor relationship."}:t.length>0?{status:"connector-complete",scope:n,explanation:"Every requested anchor pair has a selected path supported by proved repository relationships."}:{status:"frontier-accounted",scope:n,explanation:"Every discovered direction in the declared graph query is emitted or represented by an exact frontier."}}function Sx(e,t={}){let n=t.maxSelectedNodes??24;if(!Number.isSafeInteger(n)||n<=0)throw new RangeError(`maxSelectedNodes must be a positive safe integer; received ${n}`);let r=new Set(e.anchors.flatMap(I=>[...I.nodeIds,...I.candidateNodeIds])),i=[],o=e.anchors.filter(I=>I.status!=="missing"&&I.nodeIds.length+I.candidateNodeIds.length>0);for(let I=0;I<o.length;I+=1)for(let k=I+1;k<o.length;k+=1){let D=o[I],F=o[k],P=fx(e,D,F,!1),L=P??fx(e,D,F,!0);L?(L.nodeIds.forEach($=>r.add($)),i.push({id:Nc("path",D.id,F.id),fromAnchorId:D.id,toAnchorId:F.id,status:!P||D.status==="ambiguous"||F.status==="ambiguous"?"candidate":"connected",nodeIds:L.nodeIds,edgeIds:L.edgeIds})):i.push({id:Nc("path",D.id,F.id),fromAnchorId:D.id,toAnchorId:F.id,status:"partial",nodeIds:[],edgeIds:[]})}let s=lt(t.routeIds??[]),a=O$(e,s),c=new Set(a.routes.map(I=>I.id)),u=s.filter(I=>!c.has(I));if(u.length>0)throw new Error(`Unknown exploration route id(s): ${u.join(", ")}`);let d=a.routes.filter(I=>s.includes(I.id)).map(I=>({anchorNodeId:I.anchorNodeId,endpointNodeId:I.endpointNodeId,endpointKind:I.endpointKind,endpointPriority:2,nodeIds:[...I.nodeIds].reverse(),edgeIds:[...I.edgeIds].reverse()}));for(let I of d)I.nodeIds.forEach(k=>r.add(k));let m=i.length===0||i.some(I=>I.edgeIds.length>0);m&&hx(e,r,n);let p=yx(e,r),f=new Set(t.expandedFrontierIds??[]),g=new Set(p.map(I=>I.id)),h=[...f].filter(I=>!g.has(I)).sort();if(h.length>0)throw new Error(`Unknown exploration frontier id(s): ${h.join(", ")}`);for(let I of p)f.has(I.id)&&I.memberNodeIds.forEach(k=>r.add(k));m&&hx(e,r,n);let y=new Map(d.map(I=>[I.endpointNodeId,I.endpointKind])),S=new Set(d.flatMap(I=>I.nodeIds)),b=new Map;for(let I of d)for(let k=0;k<I.nodeIds.length;k+=1){let D=I.nodeIds[k],F=k;b.set(D,Math.max(b.get(D)??0,F))}let x=e.nodes.map(I=>{let k=y.get(I.id),D=S.has(I.id)?{upstreamCausalPath:!0,upstreamCausalDistance:b.get(I.id)??0,...k?{upstreamCausalEndpoint:k}:{}}:{};return{...I,attributes:{...I.attributes,...D},disposition:I.disposition==="excluded"||I.disposition==="unsupported"?I.disposition:r.has(I.id)?"emitted":"folded"}}),v=new Set([...i.flatMap(I=>I.edgeIds),...d.flatMap(I=>I.edgeIds)]),C=e.edges.map(I=>({...I,disposition:I.disposition==="excluded"||I.disposition==="unsupported"?I.disposition:v.has(I.id)||r.has(I.fromNodeId)&&r.has(I.toNodeId)?"emitted":"folded"})),R=_c({anchors:e.anchors,nodes:x,edges:C,paths:i,frontiers:[...e.frontiers.filter(I=>I.disposition!=="folded"),...yx({...e,nodes:x,edges:C},r)],scope:e.coverage.scope,blindSpots:e.coverage.blindSpots,incompleteReasons:e.coverage.status==="incomplete"?[e.coverage.explanation]:[],routeCatalog:a}),E=new Set(R.frontiers.flatMap(I=>I.edgeIds)),w=R.edges.filter(I=>I.disposition==="folded"&&!E.has(I.id)).map(I=>I.id);if(w.length>0)throw new Error(`Folded exploration edge(s) are not frontier-accounted: ${w.sort().join(", ")}`);return R}var ux=10;function O$(e,t=[]){let n=new Map(e.nodes.map(h=>[h.id,h])),r=new Map(e.edges.map(h=>[h.id,h])),i=new Map;for(let h of e.edges){if(!B$(h))continue;let y=i.get(h.toNodeId)??[];y.push(h),i.set(h.toNodeId,y)}for(let h of i.values())h.sort((y,S)=>Number(us(S))-Number(us(y))||px(S)-px(y)||y.fromNodeId.localeCompare(S.fromNodeId)||y.id.localeCompare(S.id));let o=lt(e.anchors.filter(h=>h.status==="matched").flatMap(h=>h.nodeIds)),s=new Map,a=new Set,c=(h,y,S)=>{let b=y.nodeIds[y.nodeIds.length-1],x=n.get(b),v=n.get(h);if(!x?.location||!v)return;let C=[...y.nodeIds].reverse(),R=[...y.edgeIds].reverse(),E=new Set(C),w=R.flatMap(P=>{let A=r.get(P);return A?[A]:[]}),I=e.edges.filter(P=>P.disposition!=="excluded"&&P.disposition!=="unsupported"&&(E.has(P.fromNodeId)||E.has(P.toNodeId))),k={id:Nc("route",h,b,S,...R),status:"proved",anchorNodeId:h,anchorLabel:v.label,endpointNodeId:b,endpointLabel:x.label,endpointLocation:{...x.location},endpointKind:S,nodeIds:C,edgeIds:R,evidenceStrengths:lt(w.flatMap(P=>P.evidence.map(A=>A.strength))),spineEdgeFamilies:dx(w,!0),relatedEdgeFamilies:dx(I,!1),crossesRuntimeBoundary:w.some(us)},D=`${h}\0${b}\0${S}`,F=s.get(D);(!F||mx(k,F)<0)&&s.set(D,k)};for(let h of o){n.get(h)?.attributes.publicEntry===!0&&c(h,{nodeIds:[h],edgeIds:[]},"public-entry");let y=[{nodeIds:[h],edgeIds:[]}],S=new Map([[h,0]]);for(let b=0;b<y.length;b+=1){let x=y[b],v=x.nodeIds[x.nodeIds.length-1];x.edgeIds.length>0&&n.get(v)?.location&&n.get(v)?.attributes.publicEntry===!0&&c(h,x,"public-entry");let C=i.get(v)??[];if(x.edgeIds.length>=ux){C.some(R=>!x.nodeIds.includes(R.fromNodeId))&&a.add(h);continue}for(let R of C){if(x.nodeIds.includes(R.fromNodeId))continue;let E=x.edgeIds.length+1,w=S.get(R.fromNodeId);if(w!==void 0&&w<=E)continue;let I={nodeIds:[...x.nodeIds,R.fromNodeId],edgeIds:[...x.edgeIds,R.id]};if(S.set(R.fromNodeId,E),us(R)&&n.get(R.fromNodeId)?.location){c(h,I,"runtime-boundary");continue}y.push(I)}}}let u=[...s.values()].sort(mx),l=new Set(u.map(h=>h.id)),d=lt(t.filter(h=>l.has(h))),m=lt(u.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:u,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:ux,anchorNodeIds:o,anchorsWithRoutes:m,anchorsWithoutRoutes:p,depthLimitedAnchorNodeIds:f,routeCount:u.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 dx(e,t){let n=e.flatMap(r=>r.semantics?.map(i=>i.family)??[]);return t&&e.length>0&&n.length===0&&n.push("control"),lt(n)}function mx(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 B$(e){return e.disposition!=="excluded"&&e.disposition!=="unsupported"&&$$(e)&&e.evidence.some(t=>["exact","derived","mixed"].includes(t.strength))}function $$(e){return us(e)||e.kind==="boundary-observation"||e.kind==="call"||e.kind==="compiler:call"}function us(e){return e.kind==="runtime-boundary"||e.kind.startsWith("runtime:")}function px(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 fx(e,t,n,r){return gx(e,t,n,r)??gx(e,n,t,r)}function gx(e,t,n,r){let i=[...t.nodeIds,...t.candidateNodeIds].sort(),o=new Set([...n.nodeIds,...n.candidateNodeIds]);if(i.some(l=>o.has(l)))return{nodeIds:[i.find(d=>o.has(d))],edgeIds:[]};let s=new Set(e.nodes.filter(l=>l.kind==="structural-region").map(l=>l.id)),a=new Map;for(let l of e.edges)l.disposition==="excluded"||l.disposition==="unsupported"||l.kind==="structural-membership"||s.has(l.fromNodeId)||s.has(l.toNodeId)||l.evidence.every(m=>["candidate","unknown"].includes(m.strength))&&!r||j$(a,l.fromNodeId,l.toNodeId,l.id);for(let l of a.values())l.sort((d,m)=>d.nodeId.localeCompare(m.nodeId)||d.edgeId.localeCompare(m.edgeId));let c=i.map(l=>({nodeId:l,nodeIds:[l],edgeIds:[]})),u=new Set(i);for(let l=0;l<c.length;l+=1){let d=c[l];for(let m of a.get(d.nodeId)??[]){if(u.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;u.add(m.nodeId),c.push(p)}}return null}function j$(e,t,n,r){let i=e.get(t)??[];i.push({nodeId:n,edgeId:r}),e.set(t,i)}function H$(e,t,n){let r=new Map;for(let a of e.edges){let c=r.get(a.fromNodeId)??{incoming:0,outgoing:0},u=r.get(a.toNodeId)??{incoming:0,outgoing:0};c.outgoing+=1,u.incoming+=1,r.set(a.fromNodeId,c),r.set(a.toNodeId,u)}let i=new Set,o=new Map;for(let a of e.edges){let c=t.has(a.fromNodeId),u=t.has(a.toNodeId);if(c===u)continue;let l=c?a.toNodeId:a.fromNodeId,d=c?a.fromNodeId:a.toNodeId,m=e.nodes.find(g=>g.id===l);if(m?.kind==="structural-region")continue;let p=o.get(l)??new Set;p.add(d),o.set(l,p),(/(?:runtime-boundary|external)/u.test(a.kind)||m&&/(?:frontier|external)/u.test(m.kind))&&i.add(l)}let s=[...o].filter(([a,c])=>{if(i.has(a))return!0;let u=r.get(a)??{incoming:0,outgoing:0};return(u.incoming>1||u.outgoing>1)&&c.size>1}).sort(([a,c],[u,l])=>Number(i.has(u))-Number(i.has(a))||l.size-c.size||a.localeCompare(u)).map(([a])=>a);for(let a of s){if(t.size>=n)break;t.add(a)}}function hx(e,t,n){let r=-1;for(;t.size!==r&&t.size<n;)r=t.size,H$(e,t,n)}function yx(e,t){let n=new Set(e.nodes.filter(s=>!t.has(s.id)&&s.disposition!=="excluded"&&s.disposition!=="unsupported").map(s=>s.id)),r=new Map;for(let s of e.edges){if(!n.has(s.fromNodeId)||!n.has(s.toNodeId))continue;let a=r.get(s.fromNodeId)??new Set,c=r.get(s.toNodeId)??new Set;a.add(s.toNodeId),c.add(s.fromNodeId),r.set(s.fromNodeId,a),r.set(s.toNodeId,c)}let i=[],o=new Set;for(let s of[...n].sort()){if(o.has(s))continue;let a=[],c=[s];o.add(s);for(let u=0;u<c.length;u+=1){let l=c[u];a.push(l);for(let d of[...r.get(l)??[]].sort())o.has(d)||(o.add(d),c.push(d))}i.push(a.sort())}return i.map(s=>{let a=new Set(s),c=e.edges.filter(f=>a.has(f.fromNodeId)||a.has(f.toNodeId)),u=c.filter(f=>a.has(f.fromNodeId)!==a.has(f.toNodeId)),l=lt(u.map(f=>a.has(f.fromNodeId)?f.toNodeId:f.fromNodeId)),d=new Set(u.map(f=>a.has(f.toNodeId)?"outgoing":"incoming")),m=lt(c.map(f=>f.id)),p=lt(u.map(f=>f.kind));return{id:Nc("frontier",...s,...m),kind:p.join("+")||"disconnected",direction:d.size===1?[...d][0]:"undirected",fromNodeIds:l,edgeIds:m,memberNodeIds:s,memberCount:s.length,disposition:"folded",reason:u.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 Nc(e,...t){let n=D$("sha256").update(t.join("\0")).digest("hex").slice(0,16);return`${e}:${n}`}function qi(e,t){let n=[...e].sort((r,i)=>r.id.localeCompare(i.id));for(let r=1;r<n.length;r+=1)if(n[r-1].id===n[r].id)throw new Error(`Duplicate exploration ${t} id: ${n[r].id}`);return n}function St(e,t,n,r){let i=lt(t.filter(o=>!n.has(o)));if(i.length>0)throw new Error(`Exploration ${e} references missing ${r}(s): ${i.join(", ")}`)}function bx(e){return{total:e.length,emitted:e.filter(t=>t.disposition==="emitted").length,folded:e.filter(t=>t.disposition==="folded").length,excluded:e.filter(t=>t.disposition==="excluded").length,unsupported:e.filter(t=>t.disposition==="unsupported").length}}function lt(e){return[...new Set(e)].sort()}var U$=5,q$=12,G$=8,z$=3,vx=8,K$=6,W$=12,Cx=12,V$=12,Y$=2,J$=new Set(["branch","loop","call","await","return","throw","mutation","catch","finally"]),X$=9e3,xx=MC,Rx=new WeakMap;function Q$(e,t){return Fx(e,t,"full")}function Ax(e,t){return Fx(e,t,"topology")}function Z$(e,t,n,r,i,o=!1){let s=e.get(t);if(s)return s.depth=Math.min(s.depth,n),s.primary||=i,s.promoteBoundaryImports||=o,s.origins.add(r),s;let a={file:t,depth:n,primary:i,promoteBoundaryImports:o,origins:new Set([r]),processed:!1};return e.set(t,a),a}function ej(e,t,n,r,i,o,s="none",a=!1){let c=e.get(n.symbol);if(c)return c.depth=Math.min(c.depth,r),c.origins.add(i),o&&c.anchorQueries.add(o),c.referenceScope=Qj(c.referenceScope,s),t(n.relativePath,r,i,!0,a),c;let u={definition:n,depth:r,origins:new Set([i]),anchorQueries:new Set(o?[o]:[]),referenceScope:s,processed:!1};return e.set(n.symbol,u),t(n.relativePath,r,i,!0,a),u}function tj(e,t,n,r,i,o,s=!1,a=!0){let c=ln(n),u=e.get(c);if(u)return u.depth=Math.min(u.depth,r),u.origins.add(i),o&&u.anchorQueries.add(o),u.reverseCallExpansion||=s,u.traversalEligible||=a,t(n.file,r,i,u.traversalEligible,!0),u;let l={...n,depth:r,origins:new Set([i]),anchorQueries:new Set(o?[o]:[]),reverseCallExpansion:s,traversalEligible:a};return e.set(c,l),t(n.file,r,i,a,!0),l}function nj(e){let{db:t,index:n,pendingRelations:r,addFile:i,addSymbol:o,addSourceConstruct:s,observation:a,depth:c,origin:u}=e;i(a.source.file,c,u,!0,!0),a.owner.file!==a.source.file&&i(a.owner.file,c,`${u}:owner`,!0,!0);let l=q(t,a.owner.file),d=a.owner.symbol?mr(t,n,a.owner.symbol).matches.find(f=>f.relativePath===a.owner.file):null,m=(d&&!fe(d.symbol)?d:null)??Oe(l,a.source.startLine);if(m&&!fe(m.symbol))return o(m,c,u,void 0,"none",!0),m.symbol;a.owner.name&&s({file:a.owner.file,name:a.owner.name,startLine:a.owner.startLine,endLine:a.owner.endLine},c,`${u}:source-owner`,void 0,!0);let p=e.index.definitionsForFile(a.source.file).filter(f=>!!f.leaf&&vn(t,a.source.file,f.leaf).some(g=>g>=a.source.startLine&&g<=a.source.endLine));if(p.length===1){let f=p[0];o(f,c,`${u}:handler-identifier`,void 0,"none",!0),xt(r,{kind:"runtime-boundary",evidence:"runtime-boundary:handler-identifier",fromFile:a.source.file,fromSymbol:null,toFile:f.relativePath,toSymbol:f.symbol,fromBoundaryParticipant:zi(a),line:a.source.startLine,strength:"derived"})}return null}function rj(e){let t=0,n=0,r=0;for(let i of e.searches){let o=Nj(e.db,e.index,i,e.boundaryObservationLocations),s=o.filter(l=>jj(l,e.sourceAllowed)),a=!e.opts.fullLiteralTraversal&&(o.length>q$||s.length>G$),c=a?[]:o,u=new Set((a?[]:e.opts.fullLiteralTraversal?s:[...s].sort(_j).slice(0,z$)).map(Px));a&&(n+=1,r+=o.length);for(let l of c){let d=u.has(Px(l)),m=d&&!l.ownerSymbol&&l.ownerStartLine!==null&&l.ownerEndLine!==null;if(e.addFile(l.relativePath,0,`${d?"literal-anchor":"literal-match"}:${i}`,m,m),m&&e.addSourceConstruct({file:l.relativePath,name:l.ownerShortName??`${l.relativePath}:${l.ownerStartLine+1}`,startLine:l.ownerStartLine,endLine:l.ownerEndLine},0,`literal-source-owner:${i}`,i,!0),d&&l.ownerSymbol){let p=mr(e.db,e.index,l.ownerSymbol).matches[0];p&&!fe(p.symbol)&&e.addSymbol(p,0,"literal-owner",i,"all",!0)}e.literalHits.push({query:i,file:l.relativePath,line:l.line,ownerSymbol:l.ownerSymbol,ownerShortName:l.ownerShortName,ownerStartLine:l.ownerStartLine,ownerEndLine:l.ownerEndLine,sourceLine:l.sourceLine.trim(),matchKind:l.matchKind,traversalSeed:d})}e.anchors.push({kind:"literal",query:i,status:o.length>0?"matched":"missing",matchedRegionIds:[],matchingLines:o.length,seedMatchingLines:a?0:u.size,matchOnlyLines:o.length-u.size,eligibleSeedMatchingLines:s.length,materializedMatchingLines:c.length,withheldMatchingLines:a?o.length:0,literalTraversal:a?"withheld-broad":"materialized",representativeMatches:a?Hj(i,o):void 0,narrowingCommands:a?qj(i,o):void 0,exhaustiveTraversalCommand:a||u.size<s.length?`scip-query system-map --search ${Se(i)} --full-literal-traversal`:void 0,seedRegionIds:[],matchOnlyRegionIds:[]})}for(let i of e.symbolQueries){let o=mr(e.db,e.index,i);t+=o.omitted;let s=Oj(e.db,i),a=o.matches.filter(m=>!fe(m.symbol)),c=s!==null&&a.length===0;c&&e.addSourceConstruct(s,0,"source-construct-anchor",i,!0);let u=c?a:o.matches;for(let m of u)e.addSymbol(m,0,"symbol-anchor",i,"all",!0);let l=c?Bj(s):null,d=c?1:o.total;e.anchors.push({kind:"symbol",query:i,status:d===0?"missing":d===1?"matched":"ambiguous",matchedRegionIds:[],symbolCandidates:[...l?[l]:[],...u.map(Vj)],totalSymbolCandidates:d,omittedSymbolCandidates:o.omitted})}return{omittedSymbolCandidates:t,broadLiteralAnchors:n,withheldLiteralMatches:r}}function ij(e){let{db:t,opts:n,mode:r,searches:i,symbolQueries:o,maxDepth:s,maxTopologyCharacters:a,requestedRelationKinds:c,evidenceFloor:u,includedSourceScopes:l,workspaces:d,runtimeBoundaries:m,boundaryObservations:p,representedBoundaryLinkIds:f,files:g,symbols:h,sourceConstructs:y,literalHits:S,pendingRelations:b,externalImports:x,anchors:v,omittedSymbolCandidates:C,broadLiteralAnchors:R,withheldLiteralMatches:E,filteredUnverifiedCallEdges:w,memberCallCandidateEdges:I,unresolvedMemberCallsites:k,sourceAllowed:D}=e,F=new Set(c),P=new Map;for(let _ of g.keys())P.set(_,ds(_,d));let A=[...b.values()].filter(_=>P.has(_.fromFile)&&P.has(_.toFile)).map(_=>({..._,fromRegionId:P.get(_.fromFile).id,toRegionId:P.get(_.toFile).id})).sort(Bx),L=a1(A),$=new Set(n.expand??[]),B=r1(g,h,S,A,L,P,$),X=new Set([...g.values()].filter(_=>[..._.origins].some(le=>le.startsWith("literal-anchor:")||le==="literal-owner"||le==="symbol-anchor")).map(_=>P.get(_.file).id)),z=kj(B),O=new Set(B.map(_=>_.id)),ne=[...$].filter(_=>!O.has(_)).sort();for(let _ of v)if(_.matchedRegionIds=l1(_,S,h,P),_.kind==="literal"){let le=S.filter(qe=>qe.query===_.query);_.seedRegionIds=ge(le.filter(qe=>qe.traversalSeed).map(qe=>P.get(qe.file).id)),_.matchOnlyRegionIds=ge(le.filter(qe=>!qe.traversalSeed).map(qe=>P.get(qe.file).id))}let oe=[...h.values()].filter(_=>!_.processed).length,Te=[...g.values()].filter(_=>_.primary&&!_.processed).length,Fe=[...g.values()].filter(_=>!_.primary&&!_.processed).length,$t=[...h.values()].filter(_=>_.processed),nt=(m?.frontiers??[]).flatMap(_=>{let le=p.get(_.observationId);return!le&&_.source&&_.action&&_.strength?!F.has("runtime-boundary")||!D(_.source.file)||u==="exact"||!g.has(_.source.file)?[]:[{observationId:_.observationId,action:_.action,strength:_.strength,file:_.source.file,line:_.source.startLine,ownerShortName:_.ownerShortName??null,address:_.address??_.missingKeyParts.join(", "),reason:_.reason}]:!F.has("runtime-boundary")||!le||!D(le.source.file)||u==="exact"&&le.strength!=="exact"||!g.has(le.source.file)?[]:[{observationId:le.id,action:le.action,strength:le.strength,file:le.source.file,line:le.source.startLine,ownerShortName:le.owner.name,address:Ox(le),reason:_.reason,protocol:le.protocol,role:le.role,modality:le.modality,resolution:le.resolution,sourceScope:le.sourceScope,keyParts:le.keyParts.map(qe=>({name:qe.name,value:qe.value,evidence:qe.evidence}))}]}).sort((_,le)=>_.file.localeCompare(le.file)||_.line-le.line),M=(m?.links??[]).filter(_=>{if(!F.has("runtime-boundary")||u==="exact"&&_.strength!=="exact")return!1;let le=p.get(_.from),qe=p.get(_.to);return!!(le&&qe&&D(le.source.file)&&D(qe.source.file)&&(g.has(le.source.file)||g.has(qe.source.file)))}),j=M.filter(_=>_.strength==="exact").length,Y=M.filter(_=>_.strength==="derived").length,se=M.filter(_=>_.strength==="candidate").length,je=m?.links.filter(_=>_.strength==="exact").length??0,Wt=m?.links.filter(_=>_.strength==="derived").length??0,oi=m?.links.filter(_=>_.strength==="candidate").length??0,Cr=c1(x,P),Al=C===0?"accounted":"incomplete",Lf=[...R>0?[`${R} broad literal anchor(s) withheld ${E} exact match(es) before graph traversal; representative identities and scoped search commands preserve recovery without treating every textual occurrence as relevant.`]:[],`Literal matches outside the included source scopes (${l.join(", ")}) remain visible as match-only evidence and do not seed traversal.`,m?"Built-in runtime-boundary extractors traverse direct and replayably derived links; heuristic candidates, unsupported frameworks, reflection, generated names, and dependency wiring not recoverable from compiler occurrences or constructor assignments remain disclosed frontiers.":"Runtime-boundary evidence is unavailable for this index; run scip-query reindex with this build to extract supported HTTP, event, registry, and persistence observations.","Reverse references do not recursively expand from discovered callers or callees.","Member calls use compiler occurrences, exact constructor-assigned fields, bounded unique service providers, direct factory-return members, and compiler-resolved object-literal callbacks when available. Ambiguous providers remain candidate frontiers; callback values routed through mutation, reflection, or unsupported dependency containers remain unrepresented.","Literal traversal is bounded to the smallest parser-delimited source construct; parser gaps may reduce an owner to one source line and leave its continuation untraversed.","Schema consumers stay within forward-flow regions; cross-workspace contracts may discover consumers in other workspaces. Add an explicit symbol anchor to widen either scope.",`Traversal stops after depth ${s}; nonzero frontier counts identify evidence that was discovered but not traversed.`,"Region labels are structural path groupings, not inferred runtime or architectural boundaries."],Et=Cj({db:t,anchors:v,regions:B,symbolStates:h,sourceConstructStates:y,literalHits:S,relations:A,externalBoundaries:Cr,boundaryFrontiers:nt,regionForFile:P,closureStatus:Al,omittedSymbolCandidates:C,maxDepth:s,requestedRelationKinds:c,evidenceFloor:u,includedSourceScopes:l,blindSpots:Lf,topologyFrontiers:n.topologyFrontiers??[],routeIds:n.routeIds??[],expandedRegionIds:[...$],maxTopologyCharacters:a,fullLiteralTraversal:n.fullLiteralTraversal??!1});if(r==="topology")return Et;let Pf=(n.behaviorFocusLocations?.length??0)>0?new Set([...Et.anchors.flatMap(_=>_.nodeIds),...Et.paths.flatMap(_=>_.nodeIds)]).size:void 0,Os=Tv(t,Et,{focusLocations:n.behaviorFocusLocations,...Pf?{maxSteps:Pf}:{}});lC(t,Et,Os);let KL=lj(t,Et,Os,n.behaviorFocusLocations??[]);Et.corridor=sx(Et,{focusLocations:KL});let Df=cC(t,Et,Os,{sourceAllowed:D,selectionTerms:n.selectionTerms}),Mf=wj(Et),WL=Mj(i,o,s,c,u,l,n.fullLiteralTraversal??!1,a,B,L,X,$,Mf),VL=Dj(i,o,s,B.filter(_=>Mf.has(_.id)),X,c,u,l,n.fullLiteralTraversal??!1,a);return{anchors:v,regions:B,regionRelations:L,externalBoundaries:Cr,boundaryFrontiers:nt,unmatchedExpansions:ne,expansion:VL,drilldown:z,presentation:WL,topology:Et,behavior:Os,nextAnchors:Df,closure:{status:Al,emitted:{regions:B.length,relations:A.length,runtimeLinks:f.size},withheld:{symbols:oe,files:Te+Fe,regions:Et.nodes.filter(_=>_.kind==="structural-region"&&_.disposition==="folded").length,drillAnchors:(z?.omittedAnchors??0)+Df.omittedAnchors,literalMatches:E},ambiguous:{anchors:v.filter(_=>_.status==="ambiguous").length,omittedSymbolCandidates:C},external:Cr.length,unresolved:nt.length,explanation:Al==="accounted"?"Every fact reached under the declared anchors, relations, depth, evidence floor, source scopes, and installed analyzers is accounted for as emitted, withheld, ambiguous, external, or unresolved.":"Some ambiguous symbol candidates were not identified, so the declared query is not fully accounted for."},coverage:{explicitAnchorCount:v.length,requestedRelationKinds:c,evidenceFloor:u,includedSourceScopes:l,matchedAnchorCount:v.filter(_=>_.status!=="missing").length,literalSearchesComplete:!0,broadLiteralAnchors:R,withheldLiteralMatches:E,symbolCandidateSetsComplete:C===0,omittedSymbolCandidates:C,maxTraversalDepth:s,frontierSymbols:oe,frontierFiles:Te,supportFilesNotTraversed:Fe,filteredUnverifiedCallEdges:w,memberCallCandidateEdges:I,unresolvedMemberCallsites:k,runtimeBoundaryEvidenceAvailable:m!==null,runtimeBoundaryObservations:m?.observations.length??0,runtimeBoundaryExactLinks:j,runtimeBoundaryDerivedLinks:Y,runtimeBoundaryCandidateLinks:se,repositoryRuntimeBoundaryExactLinks:je,repositoryRuntimeBoundaryDerivedLinks:Wt,repositoryRuntimeBoundaryCandidateLinks:oi,runtimeBoundaryTraversedLinks:f.size,runtimeBoundaryFrontiers:nt.length,referenceExpansionEligibleSymbols:$t.filter(_=>_.referenceScope!=="none").length,referenceExpansionSkippedSymbols:$t.filter(_=>_.referenceScope==="none").length,dynamicDispatchRepresented:m?.links.some(_=>_.joinRule==="carrier.discriminator"&&f.has(_.id))??!1,runtimeGeneratedLinksRepresented:m!==null,regionBoundariesAreStructural:!0,relationFamilies:{"literal-anchor":{evidence:"exact-source",scope:"all indexed documents for each explicit literal",completeWithinScope:!0},reference:{evidence:"compiler-graph",scope:"all cross-file indexed/source-attributed sites for explicit anchors and promoted non-module boundary symbols",completeWithinScope:!0},call:{evidence:"mixed",scope:"static callees plus exact SCIP call occurrences in traversed source ranges, exact constructor-assigned member receivers, and uniquely attributed direct-import member candidates",completeWithinScope:!0},"contract-symbol":{evidence:"compiler-graph",scope:"compiler-resolved symbol identities referenced across inferred workspace boundaries",completeWithinScope:!0},import:{evidence:"compiler-graph",scope:"all indexed or source-resolved imports of traversed primary files",completeWithinScope:!0},"runtime-boundary":{evidence:"exact-source",scope:"direct and mechanically derived links produced by grounded runtime adapters and factorized relation groups",completeWithinScope:!0}},blindSpots:Lf}}}function oj(e,t){let{db:n,relationPolicy:r,sourceConstructs:i,reverseExpandedSourceConstructs:o,pendingRelations:s,reverseFileGraph:a,serviceCallerFilesBySourceConstruct:c,sourceAllowed:u,memberCallTargetsForWholeFile:l,addSymbol:d,addSourceConstruct:m}=e;if(r.has("call")){let p=[...i.values()].filter(f=>f.traversalEligible&&f.reverseCallExpansion&&f.depth<=t&&!o.has(ln(f)));for(let f of p){o.add(ln(f));let g=W(n,f.file);if((g?.callables??[]).filter(S=>S.name===f.name&&S.startLine<=f.endLine&&S.endLine>=f.startLine).length===1){let S=(g?.callSites??[]).filter(b=>b.calleeLeaf===f.name&&!b.memberAccess);for(let b of S){let x=t+1,v=Oe(q(n,f.file),b.line),C=null,R=null;if(v&&!fe(v.symbol)){if(v.relativePath===f.file&&v.startLine<=f.endLine&&v.endLine>=f.startLine)continue;d(v,x,"reverse-local-call-owner",void 0,"forward-regions",!0),C=v.symbol}else{let E=bm(n,f.file,b.line);E&&ln(E)!==ln(f)&&(R=m(E,x,"reverse-local-call-source-owner",void 0,!0))}!C&&!R||xt(s,{kind:"call",evidence:"ast-callsite",fromFile:f.file,fromSymbol:C,toFile:f.file,toSymbol:null,fromSourceConstruct:R?ut(R):void 0,toSourceConstruct:ut(f),line:b.line,strength:"derived"})}}let y=new Set([...a.get(f.file)??[],...c.get(ln(f))??[],...bv(n,f.file).flatMap(S=>[...a.get(S)??[]])]);for(let S of y){if(!u(S))continue;let x=l(S).targets.filter(v=>v.targetFile===f.file&&v.targetStartLine<=f.endLine&&v.targetEndLine>=f.startLine);for(let v of x){let C=t+1,R=Oe(q(n,S),v.line),E=null,w=null;if(R&&!fe(R.symbol))d(R,C,"reverse-member-call-owner",void 0,"cross-workspace-or-forward",!0),E=R.symbol;else{let I=bm(n,S,v.line);I&&(w=m(I,C,"reverse-member-call-source-owner",void 0,!0))}!E&&!w||xt(s,{kind:"call",evidence:"ast-service-member-callsite",fromFile:S,fromSymbol:E,toFile:f.file,toSymbol:null,fromSourceConstruct:w?ut(w):void 0,toSourceConstruct:ut(f),line:v.line,strength:v.strength==="exact"?"exact":"derived"})}}}}}function sj(e,t){let{db:n,index:r,relationPolicy:i,symbols:o,sourceAllowed:s,files:a,workspaces:c,addFile:u,addSymbol:l,addSourceConstruct:d,pendingRelations:m,fileGraph:p,traversalMetrics:f}=e,g=[...o.values()].filter(y=>!y.processed&&y.depth<=t),h=i.has("call")?r.calleeMap(g.map(y=>y.definition),{additive:!1,semantic:!1}):new Map;for(let y of g){y.processed=!0;let S=y.definition;if(y.referenceScope!=="none"&&(i.has("call")||i.has("reference")||i.has("contract-symbol"))){let b=zj(n,r,S).filter(v=>s(v.file)&&Xj(y,v.file,a,c)),x=new Set(b.flatMap(v=>{if(!(i.has("call")&&W(n,v.file)?.callSites.some(E=>E.line===v.line&&Ex(n,v.file,E,S))===!0)||!v.enclosingSymbol)return[];let R=mr(n,r,v.enclosingSymbol).matches[0];return R&&!fe(R.symbol)?[{owner:R,site:v}]:[]}).sort((v,C)=>{let R=vt(S.relativePath,c).relativeDir,E=vt(v.owner.relativePath,c).relativeDir===R,w=vt(C.owner.relativePath,c).relativeDir===R,I=Ix(n,v.owner),k=Ix(n,C.owner),D=v.owner.endLine-v.owner.startLine,F=C.owner.endLine-C.owner.startLine;return Number(w)-Number(E)||k-I||D-F||v.owner.symbol.localeCompare(C.owner.symbol)}).filter((v,C,R)=>R.findIndex(E=>E.owner.symbol===v.owner.symbol)===C).reduce((v,C)=>{if(v.length>=Y$)return v;let R=vt(C.owner.relativePath,c).relativeDir;return v.some(E=>E.workspace===R)||v.push({symbol:C.owner.symbol,workspace:R}),v},[]).map(v=>v.symbol));for(let v of b){let C=t+1;u(v.file,C,`reference:${T(S.symbol)}`,!0);let R=i.has("call")&&W(n,v.file)?.callSites.some(I=>I.line===v.line&&Ex(n,v.file,I,S))===!0,E=null,w=null;if(v.enclosingSymbol){let I=mr(n,r,v.enclosingSymbol).matches[0];I&&!fe(I.symbol)&&(l(I,C,"reference-owner",void 0,R&&x.has(I.symbol)?y.referenceScope:"none"),E=I.symbol)}if(!E&&v.line!==null){let I=bm(n,v.file,v.line);I&&(w=d(I,C,"reference-source-owner",void 0,R))}i.has("reference")&&xt(m,{kind:"reference",evidence:"indexed-or-source-reference",fromFile:v.file,fromSymbol:E,toFile:S.relativePath,toSymbol:S.symbol,fromSourceConstruct:w?ut(w):void 0,line:v.line,strength:"mixed"}),R&&xt(m,{kind:"call",evidence:"ast-callsite",fromFile:v.file,fromSymbol:E,toFile:S.relativePath,toSymbol:S.symbol,fromSourceConstruct:w?ut(w):void 0,line:v.line,strength:"derived"}),i.has("contract-symbol")&&vt(v.file,c).relativeDir!==vt(S.relativePath,c).relativeDir&&xt(m,{kind:"contract-symbol",evidence:"compiler-cross-workspace-symbol",fromFile:v.file,fromSymbol:E,toFile:S.relativePath,toSymbol:S.symbol,fromSourceConstruct:w?ut(w):void 0,line:v.line,strength:"exact"})}}for(let b of h.get(S.symbolId)??[]){let x=mr(n,r,b.symbol).matches.find(C=>C.relativePath===b.file);if(!x||!s(x.relativePath))continue;if(!(x.relativePath===S.relativePath||(p.get(S.relativePath)??new Set).has(x.relativePath))){f.filteredUnverifiedCallEdges+=1;continue}l(x,t+1,`call:${T(S.symbol)}`,void 0,"none",!0),xt(m,{kind:"call",evidence:b.source,fromFile:S.relativePath,fromSymbol:S.symbol,toFile:x.relativePath,toSymbol:x.symbol,line:null,strength:Pj(b.source)})}}}function aj(e,t){let{db:n,index:r,relationPolicy:i,files:o,sourceConstructs:s,symbols:a,boundaryObservations:c,boundaryObservationDepths:u,sourceAllowed:l,addSymbol:d,pendingRelations:m,traversalMetrics:p,addSourceConstruct:f,serviceCallerFilesBySourceConstruct:g,reverseFileGraph:h,externalImports:y,addFile:S,workspaces:b}=e,x=[...o.values()].filter(v=>!v.processed&&v.primary&&v.depth<=t);for(let v of x){v.processed=!0;let C=[...s.values()].filter(L=>L.traversalEligible&&L.file===v.file&&L.depth<=t),R=[...a.values()].filter(L=>L.definition.relativePath===v.file&&L.depth<=t).map(L=>{let $=Ii(n,v.file,L.definition.startLine);return{startLine:$?.startLine??L.definition.startLine,endLine:$?.endLine??L.definition.endLine}}),E=L=>[...a.values()].filter($=>$.definition.relativePath===v.file&&$.definition.startLine<=L&&$.definition.endLine>=L).sort(($,B)=>$.definition.endLine-$.definition.startLine-(B.definition.endLine-B.definition.startLine)||$.definition.startLine-B.definition.startLine)[0],w=[...c.values()].filter(L=>L.source.file===v.file&&u.has(L.id)),I=[...C.map(L=>({startLine:L.startLine,endLine:L.endLine})),...w.map(L=>({...Oc(n,L)}))],k=[...R,...I],D=(W(n,v.file)?.callSites??[]).filter(L=>k.some($=>L.line>=$.startLine&&L.line<=$.endLine)),F=new Set;if(i.has("call"))for(let L of k){let $=xn(n,v.file,L.startLine,L.endLine);for(let B of $.targets){if(!l(B.definition.relativePath))continue;let X=E(B.sourceLine),z=C.find(ne=>ne.startLine<=B.sourceLine&&ne.endLine>=B.sourceLine),O=w.find(ne=>{let oe=Oc(n,ne);return oe.startLine<=B.sourceLine&&oe.endLine>=B.sourceLine});d(B.definition,t+1,`scip-occurrence-call:${v.file}:${B.sourceLine+1}`,void 0,"none",!0),xt(m,{kind:"call",evidence:"scip-occurrence-callsite",fromFile:v.file,fromSymbol:X?.definition.symbol??null,toFile:B.definition.relativePath,toSymbol:B.definition.symbol,fromBoundaryParticipant:O?zi(O):void 0,fromSourceConstruct:z?ut(z):void 0,line:B.sourceLine,strength:"exact"}),F.add(`${B.sourceLine}\0${B.calleeLeaf}`)}}if(i.has("reference"))for(let L of k){let $=Ch(n,v.file,L.startLine,L.endLine);for(let B of $.targets){if(!l(B.definition.relativePath)||F.has(`${B.sourceLine}\0${B.calleeLeaf}`))continue;let X=E(B.sourceLine);if(X?.definition.symbol===B.definition.symbol)continue;let z=C.find(ne=>ne.startLine<=B.sourceLine&&ne.endLine>=B.sourceLine),O=w.find(ne=>{let oe=Oc(n,ne);return oe.startLine<=B.sourceLine&&oe.endLine>=B.sourceLine});d(B.definition,t+1,`scip-occurrence-reference:${v.file}:${B.sourceLine+1}`,void 0,"none",!0),xt(m,{kind:"reference",evidence:"scip-occurrence-reference",fromFile:v.file,fromSymbol:X?.definition.symbol??null,toFile:B.definition.relativePath,toSymbol:B.definition.symbol,fromBoundaryParticipant:O?zi(O):void 0,fromSourceConstruct:z?ut(z):void 0,line:B.sourceLine,strength:"exact"})}}let P=i.has("call")?sr(n,v.file,{ranges:k,excludeIndexedTargets:!1}):{targets:[],unresolvedCallsites:0};p.unresolvedMemberCallsites+=P.unresolvedCallsites;let A=P.targets.filter(L=>!F.has(`${L.line}\0${L.calleeLeaf}`));p.memberCallCandidateEdges+=A.filter(L=>L.strength!=="exact"&&(L.resolution!=="imported-service-object-member"||(L.resolutionAlternativeCount??0)>1)).length;for(let L of A){let $=(L.resolutionAlternativeCount??1)===1,B=L.targetSymbol?q(n,L.targetFile).find(oe=>oe.symbol===L.targetSymbol):void 0,X=B?null:f({file:L.targetFile,name:L.calleeLeaf,startLine:L.targetStartLine,endLine:L.targetEndLine},t+1,`member-call:${v.file}`,void 0,L.resolution==="imported-service-object-member"&&$,$);if(X&&L.serviceFile){let oe=ln(X),Te=g.get(oe)??new Set;for(let Fe of h.get(L.serviceFile)??[])Te.add(Fe);g.set(oe,Te)}B&&d(B,t+1,`member-call:${v.file}`,void 0,"none",!0);let z=C.find(oe=>oe.startLine<=L.line&&oe.endLine>=L.line),O=E(L.line),ne=w.find(oe=>{let Te=Oc(n,oe);return Te.startLine<=L.line&&Te.endLine>=L.line});xt(m,{kind:"call",evidence:L.resolution==="constructed-member-receiver"?"ast-constructed-member-callsite":L.resolution==="factory-callback-member"?"ast-factory-callback-callsite":L.resolution==="imported-service-object-member"?"ast-service-member-callsite":"ast-member-import-candidate",fromFile:v.file,fromSymbol:O?.definition.symbol??null,toFile:L.targetFile,toSymbol:B?.symbol??null,fromBoundaryParticipant:ne?zi(ne):void 0,fromSourceConstruct:z?ut(z):void 0,toSourceConstruct:X?ut(X):void 0,line:L.line,strength:L.resolution==="imported-service-object-member"?(L.resolutionAlternativeCount??0)===1?"derived":"candidate":L.strength??"candidate"})}for(let L of i.has("import")||i.has("call")?Kj(n,v.file):[]){if(!L.fromFile){if(i.has("import")){let B=y.get(L.shortName)??{name:L.shortName,fromFiles:new Set};B.fromFiles.add(v.file),y.set(L.shortName,B)}continue}if(!l(L.fromFile))continue;if(i.has("import")&&(S(L.fromFile,t+1,`import:${v.file}`,!1),xt(m,{kind:"import",evidence:"indexed-or-source-import",fromFile:v.file,fromSymbol:null,toFile:L.fromFile,toSymbol:L.symbol,line:null,strength:"mixed"})),i.has("call")&&D.length>0){let B=(L.source==="compiler"?mr(n,r,L.symbol).matches:qn(n,L.fromFile,L.importedName)).filter(X=>!fe(X.symbol));for(let X of B){let z=D.filter(O=>O.calleeLeaf===L.localName).map(O=>O.line);if(z.length!==0){d(X,t+1,`source-call:${v.file}`,void 0,"none",!0);for(let O of z)xt(m,{kind:"call",evidence:"ast-callsite",fromFile:v.file,fromSymbol:null,toFile:X.relativePath,toSymbol:X.symbol,line:O,strength:"derived"})}}}if(!v.promoteBoundaryImports||!Yj(v.file,L.fromFile,b))continue;let $=mr(n,r,L.symbol);for(let B of $.matches)if(Jj(B.relativePath,L.fromFile,b)&&!fe(B.symbol)){let X=vt(v.file,b).relativeDir!==vt(B.relativePath,b).relativeDir;d(B,t+1,`boundary-import:${v.file}`,void 0,X?"cross-workspace-or-forward":"forward-regions")}}}}function cj(e,t){let{relationPolicy:n,runtimeBoundaries:r,evidenceFloor:i,representedBoundaryLinkIds:o,boundaryObservations:s,sourceAllowed:a,boundaryObservationDepths:c,symbols:u,sourceConstructs:l,addBoundaryObservation:d,pendingRelations:m}=e;for(let p of n.has("runtime-boundary")?r?.links??[]:[]){if(p.strength==="candidate"||i==="exact"&&p.strength!=="exact"||o.has(p.id))continue;let f=s.get(p.from),g=s.get(p.to);if(!f||!g||!a(f.source.file)||!a(g.source.file))continue;let h=Tx(f,t,c,u,l),y=Tx(g,t,c,u,l);if(h===null&&y===null)continue;let S=t+1,b=d(f,h??S,`runtime-boundary:${p.joinRule}`),x=d(g,y??S,`runtime-boundary:${p.joinRule}`),v=b?null:Mx(l,f),C=x?null:Mx(l,g);c.set(f.id,h??S),c.set(g.id,y??S),xt(m,{kind:"runtime-boundary",evidence:`runtime-boundary:${p.joinRule}`,fromFile:f.source.file,fromSymbol:b,toFile:g.source.file,toSymbol:x,fromBoundaryParticipant:zi(f),toBoundaryParticipant:zi(g),fromSourceConstruct:v?ut(v):void 0,toSourceConstruct:C?ut(C):void 0,runtimeBoundaryKey:p.matchedKeyParts.map(R=>`${R.name}=${R.value}`).join(" "),line:f.source.startLine,strength:p.strength}),o.add(p.id)}}function Fx(e,t,n){let r=$e(t.searches??[]),i=$e(t.symbols??[]),o=$e(t.relations&&t.relations.length>0?t.relations:xx),s=o.filter(j=>!xx.includes(j));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 u=$e(t.sourceScopes&&t.sourceScopes.length>0?t.sourceScopes:["production"]),l=["production","test","fixture","example","generated","script","unknown"],d=u.filter(j=>!l.includes(j));if(d.length>0)throw new Error(`Unsupported system-map source scope(s): ${d.join(", ")}`);let m=new Set(u),p=j=>m.has(Wl(j));if(r.length===0&&i.length===0)throw new Error("system-map requires at least one --search or --symbol anchor.");let f=t.maxDepth??U$;if(!Number.isSafeInteger(f)||f<0)throw new RangeError(`maxDepth must be a non-negative safe integer; received ${f}`);let g=t.maxTopologyCharacters??X$;if(!Number.isSafeInteger(g)||g<=0)throw new RangeError(`maxTopologyCharacters must be a positive safe integer; received ${g}`);let h=new H(e),{fileGraph:y,reverseFileGraph:S,workspaces:b,runtimeBoundaries:x}=Zj(e,h),v=new Map((x?.observations??[]).map(j=>[j.id,j])),C=new Set((x?.observations??[]).map(j=>`${j.source.file}\0${j.source.startLine}`)),R=new Set,E=new Map,w=new Map,I=new Map,k=new Map,D=[],F=new Map,P=new Map,A=[],L={filteredUnverifiedCallEdges:0,memberCallCandidateEdges:0,unresolvedMemberCallsites:0},$=new Set,B=new Map,X=new Map,z=j=>{let Y=X.get(j);if(Y)return Y;let se=sr(e,j,{excludeIndexedTargets:!1});return X.set(j,se),se},O=(j,Y,se,je,Wt=!1)=>Z$(w,j,Y,se,je,Wt),ne=(j,Y,se,je,Wt="none",oi=!1)=>ej(I,O,j,Y,se,je,Wt,oi),oe=(j,Y,se,je,Wt=!1,oi=!0)=>tj(k,O,j,Y,se,je,Wt,oi),Te=(j,Y,se)=>nj({db:e,index:h,pendingRelations:F,addFile:O,addSymbol:ne,addSourceConstruct:oe,observation:j,depth:Y,origin:se}),{omittedSymbolCandidates:Fe,broadLiteralAnchors:$t,withheldLiteralMatches:nt}=rj({db:e,index:h,searches:r,symbolQueries:i,opts:t,boundaryObservationLocations:C,sourceAllowed:p,addFile:O,addSymbol:ne,addSourceConstruct:oe,literalHits:D,anchors:A}),M={db:e,index:h,relationPolicy:a,evidenceFloor:c,sourceAllowed:p,fileGraph:y,reverseFileGraph:S,workspaces:b,runtimeBoundaries:x,boundaryObservations:v,boundaryObservationDepths:E,representedBoundaryLinkIds:R,files:w,symbols:I,sourceConstructs:k,pendingRelations:F,externalImports:P,reverseExpandedSourceConstructs:$,serviceCallerFilesBySourceConstruct:B,traversalMetrics:L,memberCallTargetsForWholeFile:z,addFile:O,addSymbol:ne,addSourceConstruct:oe,addBoundaryObservation:Te};for(let j=0;j<f;j+=1)oj(M,j),sj(M,j),aj(M,j),cj(M,j);return ij({db:e,opts:t,mode:n,searches:r,symbolQueries:i,maxDepth:f,maxTopologyCharacters:g,requestedRelationKinds:o,evidenceFloor:c,includedSourceScopes:u,workspaces:b,runtimeBoundaries:x,boundaryObservations:v,representedBoundaryLinkIds:R,files:w,symbols:I,sourceConstructs:k,literalHits:D,pendingRelations:F,externalImports:P,anchors:A,omittedSymbolCandidates:Fe,broadLiteralAnchors:$t,withheldLiteralMatches:nt,filteredUnverifiedCallEdges:L.filteredUnverifiedCallEdges,memberCallCandidateEdges:L.memberCallCandidateEdges,unresolvedMemberCallsites:L.unresolvedMemberCallsites,sourceAllowed:p})}function lj(e,t,n,r){let i=new Map,o=c=>{i.set(`${c.file}\0${c.line}`,c)};for(let c of r)o(c);let s=new Set(t.anchors.filter(c=>c.status==="matched").flatMap(c=>c.nodeIds));for(let c of n.steps)if(!(!c.location||!s.has(c.nodeId)||(c.behavior?.rawCharacters??1/0)>3e3))for(let u of c.behavior?.lines??[])u.signals.some(l=>J$.has(l))&&o({file:c.location.file,line:u.line,endLine:u.endLine});let a=t.edges.filter(c=>c.disposition==="emitted").flatMap(c=>c.evidence.flatMap(u=>u.location?[u.location]:[]));for(let c of a){o(c);let u=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(!u?.location)continue;let l=Ra(e,c.file,u.location.line,u.location.endLine??u.location.line,[c.line]);for(let d of l)o({file:c.file,line:d.line,endLine:d.endLine})}return[...i.values()].sort((c,u)=>c.file.localeCompare(u.file)||c.line-u.line)}function uj(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 ut(e){return{file:e.file,name:e.name,startLine:e.startLine,endLine:e.endLine}}function Ex(e,t,n,r){if(n.calleeLeaf===r.leaf)return!0;let i=pi(e,t,n.calleeLeaf);return i!==null&&i.importedName===r.leaf&&i.sourcePath!==null&&ke(i.sourcePath,r.relativePath)}function Bc(e,t){let n=jn(W(e,t.file)?.callables??[],t.startLine);if(n&&n.endLine>=t.endLine)return{file:t.file,name:/^source@\d+$/u.test(n.name)&&!/^source@\d+$/u.test(t.name)?t.name:n.name,startLine:n.startLine,endLine:n.endLine};let r=_x(e,t.file,t.startLine);return r&&r.endLine>=t.endLine?{file:t.file,name:r.name,startLine:r.startLine,endLine:r.endLine}:ut(t)}function Gi(e){return Ct("source-construct",e.file,String(e.startLine),String(e.endLine),e.name)}function $c(e,t){let n=Ni(e,t.symbol,t.relativePath),r=new Set(["package-surface-file","transitive-package-surface"]),i=n.filter(s=>!r.has(s)||ht(e,t)),o=i.some(s=>!r.has(s));return{evidence:i,priority:o||WS(e,t.symbol,t.relativePath)?2:1}}function Ix(e,t){let n=$c(e,t);return n.evidence.length>0?n.priority:0}function dj(e,t){let n=q(e,t.file),r=n.filter(i=>i.startLine<=t.startLine&&i.endLine>=t.startLine).sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine)||i.startLine-o.startLine);for(let i of r){let o=$c(e,i);if(o.evidence.length>0)return o}for(let i of mj(e,t.file,t.startLine)){let o=n.filter(s=>s.leaf===i.name).sort((s,a)=>Math.abs(s.startLine-i.startLine)-Math.abs(a.startLine-i.startLine)||s.symbol.localeCompare(a.symbol));for(let s of o){let a=$c(e,s);if(a.evidence.length>0)return a}return{evidence:[],priority:0}}return{evidence:[],priority:0}}function mj(e,t,n){let r=J(e,t)?.rootNode;if(!r||r.startPosition.row>n||r.endPosition.row<n)return[];let i=[],o=Cm(r,n);for(;o;){if(o.type==="variable_declarator"||o.type==="function_declaration"||o.type==="generator_function_declaration"||o.type==="class_declaration"){let s=o.childForFieldName("name")??o.namedChild(0);(s?.type==="identifier"||s?.type==="type_identifier")&&i.push({name:s.text,startLine:o.startPosition.row})}o=o.parent}return i}function pj(e){return[...new Map([...e.sourceConstructStates.values()].map(t=>Bc(e.db,t)).map(t=>[ln(t),t])).values()].sort((t,n)=>t.file.localeCompare(n.file)||t.startLine-n.startLine||t.endLine-n.endLine)}function fj(e,t){return e.anchors.map((n,r)=>{let i=Ct("anchor",String(r),n.kind,n.query),o=[...e.symbolStates.values()].filter(l=>l.anchorQueries.has(n.query)).flatMap(l=>{if(!fe(l.definition.symbol))return[dr(l.definition.symbol)];let d=t.filter(m=>m.file===l.definition.relativePath).map(m=>Gi(m));return d.length>0?d:[dr(l.definition.symbol)]}),s=[...e.sourceConstructStates.values()].filter(l=>l.anchorQueries.has(n.query)).map(l=>Gi(Bc(e.db,l))),a=e.literalHits.filter(l=>l.query===n.query&&l.traversalSeed===!0&&l.ownerSymbol&&e.symbolStates.has(l.ownerSymbol)).map(l=>dr(l.ownerSymbol)),c=e.literalHits.filter(l=>l.query===n.query&&l.traversalSeed===!0&&!l.ownerSymbol&&l.ownerStartLine!==null&&l.ownerStartLine!==void 0&&l.ownerEndLine!==null&&l.ownerEndLine!==void 0).map(l=>Gi(Bc(e.db,uj(l)))),u=ge(n.kind==="symbol"?[...o,...s]:a.length+c.length>0?[...a,...c]:n.seedRegionIds??[]);return{id:i,kind:n.kind,query:n.query,status:n.status,nodeIds:n.status==="ambiguous"?[]:u,candidateNodeIds:n.status==="ambiguous"?u:[],omittedCandidates:n.omittedSymbolCandidates??0}})}function gj(e){let t=new Map;for(let n of e)for(let r of[...n.nodeIds,...n.candidateNodeIds]){let i=t.get(r)??[];i.push(n.id),t.set(r,i)}return t}function hj(e,t,n){let r=e.relations.flatMap(s=>[s.fromBoundaryParticipant,s.toBoundaryParticipant].flatMap(a=>a?.ownerName?[a]:[])),i=e.regions.map(s=>({id:s.id,kind:"structural-region",label:s.label,disposition:"folded",location:null,anchorIds:ge(n.get(s.id)??[]),attributes:{workspace:s.workspace,structuralPath:s.structuralPath,minimumDepth:s.minDepth,files:s.fileCount,symbols:s.symbolCount,expanded:s.expanded}}));for(let s of e.symbolStates.values()){let a=e.regionForFile.get(s.definition.relativePath)?.id;if(!a)throw new Error(`System-map symbol ${s.definition.symbol} has no structural region.`);let c=dr(s.definition.symbol),u=$c(e.db,s.definition);i.push({id:c,kind:"symbol",label:T(s.definition.symbol),disposition:(n.get(c)?.length??0)>0?"emitted":"folded",location:{file:s.definition.relativePath,line:s.definition.startLine,endLine:s.definition.endLine},anchorIds:ge(n.get(c)??[]),attributes:{regionId:a,depth:s.depth,leaf:s.definition.leaf??T(s.definition.symbol),referenceScope:s.referenceScope,...u.evidence.length>0?{publicEntry:!0,publicEntryPriority:u.priority,publicEntryEvidence:u.evidence.join(",")}:{}}})}for(let s of t){let a=e.regionForFile.get(s.file)?.id;if(!a)throw new Error(`Source construct ${s.name} has no structural region.`);let c=Gi(s),l=r.find(m=>m.file===s.file&&m.line>=s.startLine&&m.line<=s.endLine)?.ownerName??s.name,d=dj(e.db,s);i.push({id:c,kind:"source-construct",label:l,disposition:(n.get(c)?.length??0)>0?"emitted":"folded",location:{file:s.file,line:s.startLine,endLine:s.endLine},anchorIds:ge(n.get(c)??[]),attributes:{regionId:a,leaf:l,sourceOwned:!0,...d.evidence.length>0?{publicEntry:!0,publicEntryPriority:d.priority,publicEntryEvidence:d.evidence.join(",")}:{}}})}let o=new Map;for(let s of e.relations)s.fromBoundaryParticipant&&o.set(s.fromBoundaryParticipant.observationId,s.fromBoundaryParticipant),s.toBoundaryParticipant&&o.set(s.toBoundaryParticipant.observationId,s.toBoundaryParticipant);for(let s of[...o.values()].sort((a,c)=>a.observationId.localeCompare(c.observationId))){let a=e.regionForFile.get(s.file)?.id;if(!a)throw new Error(`Runtime-boundary participant ${s.observationId} has no structural region.`);i.push({id:xm(s.observationId),kind:"runtime-boundary-participant",label:s.address||s.ownerName||`${s.role} ${s.action}`,disposition:"folded",location:{file:s.file,line:s.line,endLine:s.endLine},anchorIds:[],attributes:{regionId:a,action:s.action,protocol:s.protocol,role:s.role,...s.address?{address:s.address}:{},ownerSymbol:s.ownerSymbol}})}return i}function yj(e,t,n,r,i,o,s,a,c,u=!1){let l=r?dr(r):null;if(l&&t.has(l)&&!fe(r))return l;let d=i?xm(i.observationId):null;if(u&&d&&t.has(d))return d;let m=o?Gi(Bc(e,o)):null;if(m&&t.has(m))return m;if(d&&t.has(d))return d;let p=c===null?null:(n.get(a)??[]).filter(f=>f.startLine<=c&&f.endLine>=c).sort((f,g)=>f.endLine-f.startLine-(g.endLine-g.startLine)||f.startLine-g.startLine)[0]??null;return p?Gi(p):l&&t.has(l)?l:s}function bj(e,t,n){let r=new Set(t.map(u=>u.id)),i=He(n,u=>u.file),o=(u,l,d,m,p,f,g=!1)=>yj(e.db,r,i,u,l,d,m,p,f,g),s=[];for(let u of e.symbolStates.values()){let l=e.regionForFile.get(u.definition.relativePath)?.id;if(!l)continue;let d=dr(u.definition.symbol);s.push({id:Ct("edge","structural-membership",l,d),kind:"structural-membership",fromNodeId:l,toNodeId:d,directed:!0,disposition:"folded",semantics:Ic("structural-membership"),evidence:[{method:"indexed-definition-file",strength:"exact",identity:u.definition.symbol,location:{file:u.definition.relativePath,line:u.definition.startLine,endLine:u.definition.endLine}}]})}let a=He(e.relations,u=>`${o(u.fromSymbol,u.fromBoundaryParticipant,u.fromSourceConstruct,u.fromRegionId,u.fromFile,u.line,u.kind==="runtime-boundary")}\0${o(u.toSymbol,u.toBoundaryParticipant,u.toSourceConstruct,u.toRegionId,u.toFile,null)}\0${u.kind}`),c=new Set;for(let u of a.values()){let l=u[0],d=o(l.fromSymbol,l.fromBoundaryParticipant,l.fromSourceConstruct,l.fromRegionId,l.fromFile,l.line,l.kind==="runtime-boundary"),m=o(l.toSymbol,l.toBoundaryParticipant,l.toSourceConstruct,l.toRegionId,l.toFile,null);if(l.kind==="runtime-boundary"&&l.fromBoundaryParticipant){let f=xm(l.fromBoundaryParticipant.observationId),g=o(l.fromSymbol,void 0,l.fromSourceConstruct,l.fromRegionId,l.fromFile,l.line);g!==f&&!c.has(f)&&(c.add(f),s.push({id:Ct("edge","boundary-observation",g,f),kind:"boundary-observation",fromNodeId:g,toNodeId:f,directed:!0,disposition:"folded",semantics:Ic("boundary-observation"),evidence:[{method:"runtime-boundary-observation-owner",strength:l.strength??"unknown",identity:l.fromBoundaryParticipant.observationId,location:{file:l.fromBoundaryParticipant.file,line:l.fromBoundaryParticipant.line,endLine:l.fromBoundaryParticipant.endLine}}]}))}(d===m?t.find(f=>f.id===d):null)?.kind!=="structural-region"&&s.push({id:Ct("edge",l.kind,d,m),kind:l.kind,fromNodeId:d,toNodeId:m,directed:!0,disposition:"folded",semantics:TC(l),evidence:Lj(u.map(f=>({method:f.evidence,strength:f.strength??"unknown",identity:f.kind==="runtime-boundary"&&f.runtimeBoundaryKey?f.runtimeBoundaryKey:`${f.fromSymbol??f.fromFile} -> ${f.toSymbol??f.toFile}`,location:f.line===null?null:{file:f.fromFile,line:f.line}})))})}return s}function Sj(e,t,n){for(let i of e.externalBoundaries){let o=Ct("external",i.kind,i.name),s=ge(i.fromRegionIds);t.push({id:o,kind:i.kind,label:i.name,disposition:"folded",location:null,anchorIds:[],attributes:{}});for(let a of s)n.push({id:Ct("edge",i.kind,a,o),kind:i.kind,fromNodeId:a,toNodeId:o,directed:!0,disposition:"folded",semantics:Ic("external-import"),evidence:[{method:"indexed-or-source-import",strength:"mixed",identity:`${a} -> ${i.name}`,location:null}]})}let r=[];return e.boundaryFrontiers.forEach((i,o)=>{let s=e.regionForFile.get(i.file)?.id;if(!s)throw new Error(`Runtime-boundary frontier ${i.observationId} has no system-map region.`);let a=Ct("unsupported","runtime-boundary",i.observationId,String(o)),c=Ct("edge","runtime-boundary-frontier",s,a);t.push({id:a,kind:"runtime-boundary-frontier",label:i.address,disposition:"unsupported",location:{file:i.file,line:i.line},anchorIds:[],attributes:{action:i.action,strength:i.strength,owner:i.ownerShortName}}),n.push({id:c,kind:"runtime-boundary-frontier",fromNodeId:s,toNodeId:a,directed:!0,disposition:"unsupported",evidence:[{method:"runtime-boundary-extractor",strength:i.strength,identity:i.observationId,location:{file:i.file,line:i.line}}]}),r.push({id:Ct("frontier","runtime-boundary",i.observationId,String(o)),kind:"runtime-boundary",direction:"unresolved",fromNodeIds:[s],edgeIds:[c],memberNodeIds:[a],memberCount:1,disposition:"unsupported",reason:i.reason,expansion:null})}),r}function vj(e,t){let n=t.topologyFrontiers.some(f=>f==="frontier:program-facts"),r=Sx(e,{expandedFrontierIds:t.topologyFrontiers.filter(f=>f!=="frontier:program-facts"),routeIds:t.routeIds}),i=r.nodes.filter(f=>f.disposition==="emitted"||r.anchors.some(g=>g.status==="matched"&&g.nodeIds.includes(f.id))),o=t.relations.filter(f=>i.some(g=>xj(f,g))),s=t.boundaryFrontiers.filter(f=>i.some(g=>Rj(f,g))),a=HC(t.db,o,i),c=qC(t.db,i),u=tx(t.db,i,s),l=[...a.nodes,...c.nodes,...u.nodes].map(f=>n&&f.disposition==="folded"?{...f,disposition:"emitted"}:f),d=[...a.edges,...c.edges,...u.edges].map(f=>n&&f.disposition==="folded"?{...f,disposition:"emitted"}:f),m=n?null:Ej(i,l,d),p=_c({anchors:r.anchors,nodes:[...r.nodes,...l],edges:[...r.edges,...d],paths:r.paths,frontiers:[...r.frontiers,...a.frontiers,...c.frontiers,...u.frontiers,...m?[m]:[]],scope:r.coverage.scope,blindSpots:[...r.coverage.blindSpots,...a.blindSpots,...c.blindSpots,...u.blindSpots],incompleteReasons:r.coverage.status==="incomplete"?[r.coverage.explanation]:[],...r.routeCatalog?{routeCatalog:r.routeCatalog}:{}});p.completion=r.completion;for(let f of p.frontiers)f.disposition==="folded"&&(f.id.startsWith("frontier:program-facts:")||(f.expansion=Ij(t,f.id)));return p}function Cj(e){let t=pj(e),n=fj(e,t),r=hj(e,t,gj(n)),i=bj(e,r,t),o=Sj(e,r,i);return vj(_c({anchors:n,nodes:r,edges:i,paths:[],frontiers:o,scope:`explicit anchors; relations ${e.requestedRelationKinds.join(", ")}; depth ${e.maxDepth}; evidence floor ${e.evidenceFloor}; source scopes ${e.includedSourceScopes.join(", ")}`,blindSpots:[...e.blindSpots],incompleteReasons:e.closureStatus==="incomplete"?[`${e.omittedSymbolCandidates} ambiguous symbol candidate(s) were omitted`]:[]}),e)}function xj(e,t){if(e.fromSymbol&&t.id===dr(e.fromSymbol)||e.toSymbol&&t.id===dr(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 Rj(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 Ej(e,t,n){let r=ge(t.filter(o=>o.disposition==="folded").map(o=>o.id)),i=ge(n.filter(o=>o.disposition==="folded").map(o=>o.id));return r.length===0&&i.length===0?null:{id:Ct("frontier","program-facts"),kind:"program-facts",direction:"outgoing",fromNodeIds:ge(e.map(o=>o.id)),edgeIds:i,memberNodeIds:r,memberCount:r.length,disposition:"folded",reason:"Control, data, state, and temporal facts are folded beneath the selected high-level owners.",expansion:null}}function Ij(e,t){return`scip-query system-map ${[...e.anchors.flatMap(r=>r.kind==="literal"?[`--search ${Se(r.query)}`]:[`--symbol ${Se(r.query)}`]),`--depth ${e.maxDepth}`,...e.requestedRelationKinds.map(r=>`--relation ${Se(r)}`),`--evidence-floor ${Se(e.evidenceFloor)}`,...e.includedSourceScopes.map(r=>`--source-scope ${Se(r)}`),...e.fullLiteralTraversal?["--full-literal-traversal"]:[],`--topology-characters ${e.maxTopologyCharacters}`,...e.expandedRegionIds.map(r=>`--expand ${Se(r)}`),...e.topologyFrontiers.map(r=>`--frontier ${Se(r)}`),...e.routeIds.map(r=>`--route ${Se(r)}`),`--frontier ${Se(t)}`].join(" ")}`}function wj(e){let t=new Set;for(let n of e.nodes){if(n.disposition!=="emitted")continue;n.kind==="structural-region"&&t.add(n.id);let r=n.attributes.regionId;typeof r=="string"&&t.add(r)}return t}function Lj(e){let t=new Map;for(let n of e){let r=n.location?`${n.location.file}:${n.location.line}`:"";t.set(`${n.method}\0${n.strength}\0${n.identity??""}\0${r}`,n)}return[...t.values()].sort((n,r)=>n.method.localeCompare(r.method)||(n.identity??"").localeCompare(r.identity??"")||(n.location?.file??"").localeCompare(r.location?.file??"")||(n.location?.line??0)-(r.location?.line??0))}function Ct(...e){return e.map(t=>encodeURIComponent(t)).join(":")}function dr(e){return Ct("symbol",e)}function Pj(e){return e==="semantic-callee"||e==="scip-chunk"||e==="scip-occurrence"?"exact":"derived"}function Dj(e,t,n,r,i,o,s,a,c,u){let l=[...r].sort((g,h)=>Nx(g,h,i)),m=l.slice(0,Cx).map(g=>g.id),p=l.slice(Cx).map(g=>g.id),f=[...e.map(g=>`--search ${Se(g)}`),...t.map(g=>`--symbol ${Se(g)}`),`--depth ${n}`,...o.map(g=>`--relation ${Se(g)}`),`--evidence-floor ${Se(s)}`,...a.map(g=>`--source-scope ${Se(g)}`),...c?["--full-literal-traversal"]:[],`--topology-characters ${u}`,...m.map(g=>`--expand ${Se(g)}`)];return{command:m.length===0?null:`scip-query system-map ${f.join(" ")}`,regionCount:m.length,regionIds:m,candidateRegionCount:r.length,omittedRegionIds:p}}function Mj(e,t,n,r,i,o,s,a,c,u,l,d,m){let p=[...c].sort((I,k)=>Nx(I,k,l)).filter(I=>!m||m.has(I.id)||d.has(I.id)),f=u.length>0?Math.floor(a*.4):0,g=a-f,h=new Set,y=0;for(let I of p){let k=wx(I);!d.has(I.id)&&h.size>0&&y+k>g||(h.add(I.id),y+=k)}let S=u.filter(I=>h.has(I.fromRegionId)&&h.has(I.toRegionId)).sort(Tj),b=[];for(let I of S){let k=Lx(I);b.length>0&&y+k>a||(b.push(jc(I)),y+=k)}let x=c.filter(I=>!h.has(I.id)).map(I=>I.id).sort(),v=new Set(b),C=u.filter(I=>!v.has(jc(I))).length,R=c.reduce((I,k)=>I+wx(k),0)+u.reduce((I,k)=>I+Lx(k),0),E=p.every(I=>h.has(I.id))&&b.length===S.length,w=[...e.map(I=>`--search ${Se(I)}`),...t.map(I=>`--symbol ${Se(I)}`),`--depth ${n}`,...r.map(I=>`--relation ${Se(I)}`),`--evidence-floor ${Se(i)}`,...o.map(I=>`--source-scope ${Se(I)}`),...s?["--full-literal-traversal"]:[],`--topology-characters ${Math.max(a,R)}`];return{maxCharacters:a,estimatedCharacters:y,totalEstimatedCharacters:R,regionIds:[...h],omittedRegionIds:x,relationKeys:b,omittedRelations:C,complete:E,expansionCommand:E?null:`scip-query system-map ${w.join(" ")}`}}function wx(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 Lx(e){return 70+e.fromRegionId.length+e.toRegionId.length+e.kinds.join(",").length+e.evidence.join(",").length}function Tj(e,t){let n=r=>r.kinds.includes("runtime-boundary")?0:r.kinds.includes("contract-symbol")?1:2;return n(e)-n(t)||t.relationCount-e.relationCount||jc(e).localeCompare(jc(t))}function jc(e){return`${e.fromRegionId}\0${e.toRegionId}`}function Nx(e,t,n){let r=a=>n.has(a.id)?0:1,i=a=>a.sourceFileCount===0?1:0,o=a=>a.symbolCount+a.literalHitCount>0?0:1,s=a=>[...a.incomingRegionIds,...a.outgoingRegionIds].filter(c=>n.has(c)).length;return r(e)-r(t)||o(e)-o(t)||i(e)-i(t)||e.minDepth-t.minDepth||s(t)-s(e)||t.literalHitCount-e.literalHitCount||e.testFileCount-t.testFileCount||e.label.localeCompare(t.label)}function kj(e){let t=[],n=new Set;for(let i of e.filter(o=>o.expanded)){for(let c of i.symbols)c.origins.includes("symbol-anchor")&&n.add(c.file);let o=He(i.symbols,c=>c.file),s=He(i.literalHits,c=>c.file),a=[...i.files].sort((c,u)=>Fj(c,u,o,s));for(let c of a){let u=(o.get(c.file)??[]).sort(DC)[0];if(u){t.push({kind:"symbol",regionId:i.id,file:u.file,line:u.startLine,endLine:u.endLine,label:u.shortName});continue}let l=(s.get(c.file)??[]).sort($x)[0];l&&t.push({kind:"literal",regionId:i.id,file:l.file,line:l.line,endLine:null,label:l.ownerShortName??l.query})}}let r=Aj(t,n);return{command:r.length===0?null:`scip-query inspect ${r.map(i=>`--at ${Se(`${i.file}:${i.line+1}`)}`).join(" ")} --view behavior`,definitionCommand:null,candidateAnchors:t.length,selectedAnchors:r.length,omittedAnchors:t.length-r.length,anchors:r}}function Aj(e,t){let n=[...He(e,s=>s.regionId).values()],r=[],i=new Set,o=Math.min(V$,24);for(let s of e)if(!(!t.has(s.file)||i.has(s.file))&&(r.push(s),i.add(s.file),r.length===o))return r;for(let s=0;r.length<o;s+=1){let a=!1;for(let c of n){let u=c[s];if(u&&(a=!0,!i.has(u.file)&&(r.push(u),i.add(u.file),r.length===o)))break}if(!a)break}return r}function Fj(e,t,n,r){let i=a=>a.kind==="test"?2:a.kind==="barrel"?1:0,o=a=>(r.get(a.file)??[]).some(c=>c.traversalSeed)?0:1,s=a=>{let c=n.get(a.file)??[];return Math.min(5,...c.map(u=>Hi(u.origins)))};return i(e)-i(t)||o(e)-o(t)||s(e)-s(t)||e.depth-t.depth||e.file.localeCompare(t.file)}function Se(e){return`'${e.replaceAll("'","'\\''")}'`}function Nj(e,t,n,r){let i=[];for(let o of Q(e,{includeIgnored:!1})){let s=K(e,o);if(s.length===0)continue;let a=[];for(let l=0;l<s.length;l+=1){let d=s[l]??"";d.includes(n)&&a.push({line:l,sourceLine:d})}if(a.length===0)continue;let c=t.definitionsForFile(o),u=W(e,o)?.callables??[];for(let{line:l,sourceLine:d}of a){let m=Oe(c,l),p=jn(u,l),f=m&&!fe(m.symbol)?m:null,g=f?.startLine??p?.startLine??m?.startLine??l,h=f?.endLine??p?.endLine??m?.endLine??l,y=wo(e,o,l,g,h),S=r.has(`${o}\0${l}`),b=!!(f?.isFunctionLike||p);i.push({relativePath:o,line:l,sourceLine:d,ownerSymbol:f?.symbol??null,ownerShortName:f?T(f.symbol):p?.name??(m?T(m.symbol):null),ownerStartLine:y.startLine,ownerEndLine:y.endLine,matchKind:$j(d,n),seedPriority:S?0:b?1:2})}}return i}function _j(e,t){let n={"exact-value":0,boundary:1,embedded:2};return e.seedPriority-t.seedPriority||n[e.matchKind]-n[t.matchKind]||e.relativePath.localeCompare(t.relativePath)||e.line-t.line}function Px(e){return`${e.relativePath}\0${e.line}`}function bm(e,t,n){let i=jn(W(e,t)?.callables??[],n)??_x(e,t,n);if(!i)return null;let o=wo(e,t,n,i.startLine,i.endLine);return{file:t,name:i.name,startLine:o.startLine,endLine:o.endLine}}function _x(e,t,n){let r=J(e,t)?.rootNode;if(!r||r.startPosition.row>n||r.endPosition.row<n)return null;let i=Cm(r,n);for(;i;){if(i.type==="variable_declarator"){let s=i.childForFieldName("name")??i.namedChild(0),a=i.childForFieldName("value")??i.namedChild(1);if(s?.type==="identifier"&&a&&Sm(a,n))return{name:s.text,startLine:i.startPosition.row,endLine:i.endPosition.row}}if(i.type==="pair"){let s=i.childForFieldName("key")??i.namedChild(0),a=i.childForFieldName("value")??i.namedChild(1),c=s?.text.replace(/^(?:['"])(.*)(?:['"])$/u,"$1");if(c&&a&&/^[A-Za-z_$][\w$]*$/u.test(c)&&Sm(a,n))return{name:c,startLine:i.startPosition.row,endLine:i.endPosition.row}}i=i.parent}let o=Ii(e,t,n);return o?{name:`source@${n+1}`,startLine:o.startLine,endLine:o.endLine}:null}function Sm(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&&Sm(n,t))}function Cm(e,t){let n=e.namedChildren.filter(r=>r.startPosition.row<=t&&r.endPosition.row>=t).sort((r,i)=>r.endIndex-r.startIndex-(i.endIndex-i.startIndex)||r.startPosition.row-i.startPosition.row)[0];return n?Cm(n,t):e}function Oj(e,t){let n=t.match(/^(.+):(\d+)(?:-(\d+))?$/u);if(!n)return null;let r=li(e,n[1],{allowMultiple:!1})[0]?.relativePath;if(!r)return null;let i=Math.max(0,Number.parseInt(n[2],10)-1),o=n[3]?Math.max(i,Number.parseInt(n[3],10)-1):i,s=(W(e,r)?.callables??[]).filter(a=>a.startLine<=i&&a.endLine>=o).sort((a,c)=>a.endLine-a.startLine-(c.endLine-c.startLine)||a.startLine-c.startLine)[0];return s?{file:r,name:s.name,startLine:s.startLine,endLine:s.endLine}:null}function Bj(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 $j(e,t){let n=/[\p{L}\p{N}_$]/u,r=e.indexOf(t);for(;r>=0;){let i=e[r-1]??"",o=e[r+t.length]??"";if((i==="'"||i==='"'||i==="`")&&o===i)return"exact-value";if(!n.test(i)&&!n.test(o))return"boundary";r=e.indexOf(t,r+Math.max(1,t.length))}return"embedded"}function vm(e){return U(e)==="test"?!1:!/(?:^|[/._-])(?:fixtures?|mocks?|previews?|demos?|examples?|stories)(?:[/._-]|$)/iu.test(e)}function jj(e,t){return e.matchKind!=="embedded"&&t(e.relativePath)&&(Wl(e.relativePath)!=="production"||vm(e.relativePath))}function Hj(e,t){let n=[...t].sort(Uj),r=[],i=new Set;for(let o of n)if(!i.has(o.relativePath)&&(r.push(o),i.add(o.relativePath),r.length>=vx))break;for(let o of n){if(r.length>=vx)break;r.includes(o)||r.push(o)}return r.map(o=>({query:e,file:o.relativePath,line:o.line,ownerSymbol:o.ownerSymbol,ownerShortName:o.ownerShortName,ownerStartLine:o.ownerStartLine,ownerEndLine:o.ownerEndLine,sourceLine:o.sourceLine.trim(),matchKind:o.matchKind,traversalSeed:!1}))}function Uj(e,t){let n={"exact-value":0,boundary:1,embedded:2};return n[e.matchKind]-n[t.matchKind]||+(t.ownerSymbol!==null)-+(e.ownerSymbol!==null)||+!vm(e.relativePath)-+!vm(t.relativePath)||e.relativePath.localeCompare(t.relativePath)||e.line-t.line}function qj(e,t){let n=new Map;for(let r of t){let i=Gj(r.relativePath);n.set(i,(n.get(i)??0)+1)}return[...n].sort(([r,i],[o,s])=>s-i||r.localeCompare(o)).slice(0,K$).map(([r])=>`scip-query search ${Se(e)} --scope ${Se(r)}`)}function Gj(e){let t=e.split("/").filter(Boolean);if(t.length<=1)return e;let n=t.slice(0,-1),r=n.lastIndexOf("src");return r>=0?n.slice(0,Math.min(n.length,r+3)).join("/"):n.slice(0,Math.min(n.length,3)).join("/")}function zj(e,t,n){let r=t.callerFileMap([n],{semantic:!1}).get(n.symbolId)??new Set,i=[];for(let o of[...r].sort()){let s=ce(e,o).filter(l=>l.importedName===n.leaf&&l.sourcePath!==null&&ke(l.sourcePath,n.relativePath)),a=new Set;if(s.length>0)for(let l of s)a.add(l.localName??l.importedName);else n.leaf&&a.add(n.leaf);let c=[...new Set([...a].flatMap(l=>vn(e,o,l)))].sort((l,d)=>l-d);if(c.length===0){i.push({file:o,line:null,enclosingSymbol:null});continue}let u=t.definitionsForFile(o);for(let l of c)i.push({file:o,line:l,enclosingSymbol:Oe(u,l)?.symbol??null})}return i}function Kj(e,t){let n=e.all(`SELECT DISTINCT gs.symbol, def_d.relative_path AS from_file
78
- FROM mentions m
79
- JOIN chunks c ON m.chunk_id = c.id
80
- JOIN documents imp_d ON c.document_id = imp_d.id
81
- JOIN global_symbols gs ON m.symbol_id = gs.id
82
- LEFT JOIN (
83
- SELECT m2.symbol_id, c2.document_id
84
- FROM mentions m2
85
- JOIN chunks c2 ON m2.chunk_id = c2.id
86
- WHERE m2.role = 1
87
- GROUP BY m2.symbol_id
88
- ) sym_def ON sym_def.symbol_id = gs.id
89
- LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
90
- WHERE imp_d.relative_path = ? AND m.role = 2
91
- ORDER BY def_d.relative_path, gs.symbol`,t);return n.length>0?n.map(r=>({symbol:r.symbol,shortName:T(r.symbol),importedName:Dx(T(r.symbol)),localName:Dx(T(r.symbol)),fromFile:r.from_file,source:"compiler"})):ce(e,t).map(r=>{let i=Wj(r.importedName,r.localName,r.kind),o=r.localName??r.importedName,s=r.importedName==="default"?o:r.importedName;return{symbol:i,shortName:i,importedName:s,localName:o,fromFile:r.sourcePath,source:"parsed-source"}})}function Dx(e){return e.slice(e.lastIndexOf(":")+1).replace(/\(\)$/u,"")||e}function Wj(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 mr(e,t,n){let r=Ze(e,n);if(!r.match)return{matches:[],total:0,omitted:0};let i=[r.match,...r.candidates.map(s=>Ze(e,s.symbol).match)].filter(s=>s!==null),o=new Map;for(let s of i){let a=t.definitionsForFile(s.relativePath).find(c=>c.symbol===s.symbol);a&&o.set(a.symbol,a)}return{matches:[...o.values()],total:r.total,omitted:Math.max(0,r.total-o.size)}}function Vj(e){return{symbol:e.symbol,shortName:T(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine}}function xt(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 zi(e){return{observationId:e.id,action:e.action,protocol:e.protocol,role:e.role,address:Ox(e),file:e.source.file,line:e.source.startLine,endLine:e.source.endLine,ownerName:e.owner.name,ownerSymbol:e.owner.symbol}}function Oc(e,t){let n=K(e,t.source.file);return ot(e,t.source.file,0,Math.max(0,n.length-1),[t.source.startLine])}function Mx(e,t){let n=[...e.values()];for(let r of[t.owner,t.source]){let i=n.filter(o=>o.file===r.file&&o.startLine<=r.startLine&&o.endLine>=r.startLine).sort((o,s)=>o.endLine-o.startLine-(s.endLine-s.startLine)||o.startLine-s.startLine)[0];if(i)return i}return null}function Tx(e,t,n,r,i){let o=[],s=n.get(e.id);s!==void 0&&s<=t&&o.push(s);for(let a of r.values()){if(a.depth>t)continue;let c=a.definition;kx(c,e)&&o.push(a.depth)}for(let a of i.values())a.depth>t||kx(a,e)&&o.push(a.depth);return o.length>0?Math.min(...o):null}function kx(e,t){let n=e.relativePath??e.file;return[t.owner,t.source].some(r=>n===r.file&&e.startLine<=r.startLine&&e.endLine>=r.startLine)}function xm(e){return Ct("runtime-boundary-participant",e)}function Yj(e,t,n){let r=vt(e,n),i=vt(t,n);return r.relativeDir!==i.relativeDir?!0:/(?:^|\/)(?:contracts?|schemas?|db\/schema)(?:\/|$)/u.test(t)}function Jj(e,t,n){return ds(e,n).id===ds(t,n).id}function Xj(e,t,n,r){if(e.referenceScope==="all")return!0;let i=ds(t,r).id;return[...n.values()].some(s=>s.promoteBoundaryImports&&ds(s.file,r).id===i)?!0:e.referenceScope!=="cross-workspace-or-forward"?!1:vt(t,r).relativeDir!==vt(e.definition.relativePath,r).relativeDir}function Qj(e,t){let n={none:0,"forward-regions":1,"cross-workspace-or-forward":2,all:3};return n[e]>=n[t]?e:t}function Zj(e,t){let n=Rx.get(e);if(n)return n;let r=t.fileDependencyGraph(),i={fileGraph:r,reverseFileGraph:e1(r),workspaces:t1(t.sourceFiles()),runtimeBoundaries:na(e)};return Rx.set(e,i),i}function e1(e){let t=new Map;for(let[n,r]of e)for(let i of r){let o=t.get(i)??new Set;o.add(n),t.set(i,o)}return t}function vt(e,t){return t.find(n=>e===n.relativeDir||e.startsWith(`${n.relativeDir}/`))??{name:"root",relativeDir:""}}function t1(e){let t=new Set(["apps","packages","services","crates","libs","tools"]),n=new Map;for(let r of e){let i=r.split("/").filter(Boolean);if(i.length<3||!t.has(i[0]))continue;let o=`${i[0]}/${i[1]}`;n.set(o,{name:i[1],relativeDir:o})}return[...n.values()].sort((r,i)=>i.relativeDir.length-r.relativeDir.length)}function ds(e,t){let n=vt(e,t),i=(n.relativeDir?e.slice(n.relativeDir.length+1):e).split("/").filter(Boolean);i[0]==="src"&&i.shift();let o=n1(i);return{id:`region:${n.relativeDir||"root"}:${o}`,label:`${n.name}:${o}`,workspace:n.name,structuralPath:o}}function n1(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 r1(e,t,n,r,i,o,s){let a=He([...e.values()],p=>o.get(p.file).id),c=He([...t.values()],p=>o.get(p.definition.relativePath).id),u=He(n,p=>o.get(p.file).id),l=new Map;for(let p of r)for(let f of new Set([p.fromRegionId,p.toRegionId])){let g=l.get(f)??[];g.push(p),l.set(f,g)}let d=He(i,p=>p.toRegionId),m=He(i,p=>p.fromRegionId);return[...a.entries()].map(([p,f])=>{let g=o.get(f[0].file),h=c.get(p)??[],y=u.get(p)??[],S=l.get(p)??[],b=s.has(p),x=h.map(s1).sort(u1).slice(0,W$),v=f.filter(C=>U(C.file)==="test").length;return{id:p,label:g.label,workspace:g.workspace,structuralPath:g.structuralPath,minDepth:Math.min(...f.map(C=>C.depth)),fileCount:f.length,sourceFileCount:f.length-v,testFileCount:v,symbolCount:h.length,literalHitCount:y.length,anchorQueries:ge([...y.map(C=>C.query),...h.flatMap(C=>[...C.anchorQueries])]),relationKinds:ge(S.map(C=>C.kind)),incomingRegionIds:ge((d.get(p)??[]).map(C=>C.fromRegionId)),outgoingRegionIds:ge((m.get(p)??[]).map(C=>C.toRegionId)),memberCallCandidateRelationCount:S.filter(C=>C.evidence==="ast-member-import-candidate").length,notableSymbols:x,omittedNotableSymbols:Math.max(0,h.length-x.length),expanded:b,files:b?f.map(i1).sort(d1):[],symbols:b?h.map(o1).sort(m1):[],literalHits:b?[...y].sort($x):[],relations:b?[...S].sort(Bx):[]}}).sort((p,f)=>p.minDepth-f.minDepth||p.label.localeCompare(f.label))}function i1(e){return{file:e.file,kind:U(e.file),depth:e.depth,origins:ge([...e.origins])}}function o1(e){return{symbol:e.definition.symbol,shortName:T(e.definition.symbol),file:e.definition.relativePath,startLine:e.definition.startLine,endLine:e.definition.endLine,depth:e.depth,origins:ge([...e.origins]),anchorQueries:ge([...e.anchorQueries]),referenceExpansion:e.referenceScope!=="none",referenceScope:e.referenceScope}}function s1(e){return{shortName:T(e.definition.symbol),file:e.definition.relativePath,origins:ge([...e.origins])}}function a1(e){return[...He(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:ge(n.map(r=>r.kind)),relationCount:n.length,fromFiles:ge(n.map(r=>r.fromFile)),toFiles:ge(n.map(r=>r.toFile)),fromSymbols:ge(n.flatMap(r=>r.fromSymbol?[T(r.fromSymbol)]:[])),toSymbols:ge(n.flatMap(r=>r.toSymbol?[T(r.toSymbol)]:[])),evidence:ge(n.map(r=>r.evidence)),strengths:ge(n.map(r=>r.strength??"unknown"))})).sort((n,r)=>n.fromRegionId.localeCompare(r.fromRegionId)||n.toRegionId.localeCompare(r.toRegionId))}function c1(e,t){return[...e.values()].map(n=>({kind:"external-import",name:n.name,fromRegionIds:ge([...n.fromFiles].flatMap(r=>{let i=t.get(r);return i?[i.id]:[]})),fromFiles:ge([...n.fromFiles])})).sort((n,r)=>n.name.localeCompare(r.name))}function l1(e,t,n,r){let i=e.kind==="literal"?t.filter(o=>o.query===e.query).map(o=>o.file):[...n.values()].filter(o=>o.anchorQueries.has(e.query)).map(o=>o.definition.relativePath);return ge(i.map(o=>r.get(o)?.id).filter(o=>!!o))}function Ox(e){return e.keyParts.map(t=>`${t.name}=${t.value}`).join(" ")}function ge(e){return[...new Set(e)].sort()}function Bx(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 u1(e,t){return Hi(e.origins)-Hi(t.origins)||e.shortName.localeCompare(t.shortName)}function d1(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)}function m1(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)||e.symbol.localeCompare(t.symbol)}function $x(e,t){return e.file.localeCompare(t.file)||e.line-t.line||e.query.localeCompare(t.query)}var f1=["causal","structure","complete"],g1={causal:["execution","runtime","dataflow","state","temporal"],structure:["contract","identity","ownership","dependencies"],complete:Gt},h1=2,y1=48,jx=64,b1=5e4;function ms(e,t,n={}){let r=$e([...t.symbols??[],...t.locations??[]]),i=$e(t.searches??[]);if(r.length===0&&i.length===0)throw new Error("evidence requires at least one positional symbol, --symbol, --at, or --search selector.");let o=n.view??"causal",s=S1(n.families,o),a=n.direction??"both",c=$e(n.subtypes??[]),u=n.connecting??!1,l=n.inventoryOnly??!1,d=$e(n.foldIds??[]),m=n.maxDepth??h1,p=n.maxEdges??y1;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(l&&d.length>0)throw new Error("Evidence fold materialization cannot be combined with --inventory-only.");let f=Ax(e,{symbols:r,searches:i,maxDepth:m,maxTopologyCharacters:b1,relations:v1(s)}),g=new Map(f.nodes.map(z=>[z.id,z])),h=f.edges.filter(z=>z.disposition==="emitted"||z.disposition==="folded").flatMap(z=>C1(z,g)),y=h.filter(z=>s.includes(z.family)).filter(z=>c.length===0||c.includes(z.subtype)),S=new Set(f.anchors.flatMap(z=>z.nodeIds));if(u&&S.size<2)throw new Error("Connecting evidence requires at least two resolved root nodes.");let b=new Set(y.map(z=>z.id)),x=Rm(h,S,"incoming").filter(z=>b.has(z.id)),v=Rm(h,S,"outgoing").filter(z=>b.has(z.id)),C=Rm(h,S,"both").filter(z=>b.has(z.id)),R=w1(s,c,x,v,C),E=a==="incoming"?x:a==="outgoing"?v:C,w=u?A1(E,[...S],a):E,I=N1(w,S,a),k=[...w].sort((z,O)=>_1(z,O,I)),D=L1(k,p),F=D1(D,d),P=l?[]:d.length>0?k.filter(z=>F.has(z.id)):k,A=d.length>0?P:P.slice(0,p),L=d.length>0||l?[]:D,$=Math.max(0,P.length-A.length),B=f.frontiers.filter(z=>z.disposition==="unsupported").length,X=f.coverage.status==="incomplete"?"incomplete":$>0?"bounded":"accounted";return{kind:"graph",view:n.families&&n.families.length>0?"custom":o,families:s,selection:{direction:a,subtypes:c,connecting:u,inventoryOnly:l,foldIds:d},targets:f.anchors.map(z=>({kind:z.kind,query:z.query,status:z.status,nodeIds:[...z.nodeIds],omittedCandidates:z.omittedCandidates})),inventory:R,edges:A,folds:L,coverage:{status:X,topologyStatus:f.coverage.status,scope:f.coverage.scope,maxDepth:m,maxEdges:p,matchedEdges:k.length,eligibleEdges:P.length,returnedEdges:A.length,omittedEdges:$,frontierGroups:f.frontiers.length,unsupportedFrontiers:B,blindSpots:$e([...f.coverage.blindSpots,...PC(s)]),explanation:l?`${k.length} relationship(s) match the explicit projection; only exact inventory counts were requested.`:d.length>0?`Every relationship in ${d.length} explicitly selected recoverable fold(s) was emitted.`:X==="accounted"?"Every selected relationship in the bounded topology was emitted.":X==="bounded"?`${$} selected relationship(s) were withheld by the explicit edge budget.`:f.coverage.explanation}}}function S1(e,t){let n=e&&e.length>0?e:g1[t],r=n.filter(i=>!Gt.includes(i));if(r.length>0)throw new Error(`Unsupported graph evidence family: ${r.join(", ")}.`);return $e(n)}function v1(e){return["call","contract-symbol","import","reference","runtime-boundary"]}function C1(e,t){let n=t.get(e.fromNodeId),r=t.get(e.toNodeId);return!n||!r?[]:(e.semantics??[]).flatMap((i,o)=>{let s=R1(i);if(!s)return[];let a=Ec(s,i.subtype);if(!a)throw new Error(`No graph relation provider contract is registered for ${s}/${i.subtype}.`);let c=I1(e);return a.relation.evidenceStrengths.includes(c)?[{id:`${e.id}:${o}:${s}`,family:s,semanticFamily:i.family,subtype:i.subtype,from:Hx(n),to:Hx(r),sourceKind:e.kind,providerId:a.provider.id,supportCeiling:a.relation.supportCeiling,establishes:a.relation.establishes,nonClaims:[...a.relation.nonClaims],recoverWith:[...a.relation.recoverWith],evidenceStrength:c,evidenceMethods:$e(e.evidence.map(u=>u.method)),evidenceConstituents:x1(e.evidence),context:i.context?{...i.context}:null,attributes:i.attributes?{...i.attributes}:null}]:[]})}function x1(e){let t=new Map;for(let n of e)t.set(`${n.method}\0${n.strength}`,n);return[...t.values()].map(({method:n,strength:r})=>({method:n,strength:r}))}function R1(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 Hx(e){let t=E1(e);return{id:e.id,kind:e.kind,label:t?T(t):e.label,symbol:t,location:e.location?{...e.location}:null}}function E1(e){return e.kind!=="symbol"||!e.id.startsWith("symbol:")?null:decodeURIComponent(e.id.slice(7))}function I1(e){let t=$e(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 Rm(e,t,n){let r=Em(e,n),i=new Map,o=new Map,s=[...t].sort();for(let a of s)o.set(a,0);for(let a=0;a<s.length;a+=1){let c=s[a],u=o.get(c);for(let l of r.get(c)??[])i.set(l.edge.id,l.edge),!o.has(l.next)&&(o.set(l.next,u+1),s.push(l.next))}return[...i.values()]}function Em(e,t){let n=new Map,r=(i,o,s)=>{let a=n.get(i)??[];a.push({edge:s,next:o}),n.set(i,a)};for(let i of e)t!=="incoming"&&r(i.from.id,i.to.id,i),t!=="outgoing"&&r(i.to.id,i.from.id,i);for(let i of n.values())i.sort((o,s)=>o.edge.id.localeCompare(s.edge.id)||o.next.localeCompare(s.next));return n}function w1(e,t,n,r,i){let o=new Set;for(let l of[...n,...r,...i])o.add(`${l.family}\0${l.subtype}`);if(t.length>0)for(let l of e)for(let d of t)o.add(`${l}\0${d}`);let s=l=>{let d=new Map;for(let m of l){let p=`${m.family}\0${m.subtype}`;d.set(p,(d.get(p)??0)+1)}return d},a=s(n),c=s(r),u=s(i);return[...o].map(l=>{let[d,m]=l.split("\0");return{family:d,subtype:m,incoming:a.get(l)??0,outgoing:c.get(l)??0,both:u.get(l)??0}}).sort((l,d)=>Gt.indexOf(l.family)-Gt.indexOf(d.family)||l.subtype.localeCompare(d.subtype))}function L1(e,t){let n=e.slice(t),r=new Map;for(let s of n){let a=P1(s),c=`${s.family}\0${a}`,u=r.get(c)??[];u.push(s),r.set(c,u)}let i=new Map(e.map((s,a)=>[s.id,a+1])),o=[];for(let[s,a]of[...r].sort(([c],[u])=>c.localeCompare(u))){let[c,u]=s.split("\0"),l=[...a].sort((d,m)=>d.id.localeCompare(m.id));for(let d=0;d<l.length;d+=jx){let m=l.slice(d,d+jx),p=m.map(y=>y.id),f=$e(m.map(y=>y.subtype)).sort(),g=f.length===1?f[0]:"mixed",h=[...new Set(m.flatMap(y=>[y.from.id,y.to.id]))].sort();o.push({id:k1(c,f.join("\0"),p),mode:M1(m),family:c,subtype:g,subtypes:f,region:u,edgeCount:p.length,edgeIds:p,nodeIds:h,minimumMaxEdges:Math.max(...p.map(y=>i.get(y)??e.length))})}}return o.sort((s,a)=>Gt.indexOf(s.family)-Gt.indexOf(a.family)||(s.region??"").localeCompare(a.region??"")||s.id.localeCompare(a.id))}function P1(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 D1(e,t){if(t.length===0)return new Set;let n=new Map(e.map(i=>[i.id,i])),r=t.filter(i=>!n.has(i));if(r.length>0){let i=e.map(o=>o.id).sort();throw new Error(`Unknown evidence fold ${r.join(", ")} for this projection. Available folds: ${i.join(", ")||"(none)"}.`)}return new Set(t.flatMap(i=>n.get(i).edgeIds))}function M1(e){let t=new Map,n=new Map,r=new Set;for(let o of e){r.add(o.from.id),r.add(o.to.id);let s=t.get(o.from.id)??new Set;s.add(o.to.id),t.set(o.from.id,s);let a=n.get(o.to.id)??new Set;a.add(o.from.id),n.set(o.to.id,a)}return T1(r,t)?"scc":[...r].every(o=>(n.get(o)?.size??0)<=1&&(t.get(o)?.size??0)<=1)?"linear":"topology"}function T1(e,t){let n=new Set,r=new Set,i=o=>{if(n.has(o))return!0;if(r.has(o))return!1;n.add(o);for(let s of t.get(o)??[])if(i(s))return!0;return n.delete(o),r.add(o),!1};return[...e].some(i)}function k1(e,t,n){return`fold:${p1("sha256").update([e,t,...n].join("\0")).digest("hex").slice(0,16)}`}function A1(e,t,n){let r=new Map,i=[...new Set(t)].sort();for(let o=0;o<i.length;o+=1)for(let s=o+1;s<i.length;s+=1)for(let a of F1(e,i[o],i[s],n))r.set(a.id,a);return[...r.values()]}function F1(e,t,n,r){let i=Em(e,r),o=new Map([[t,0]]),s=new Map,a=[t];for(let u=0;u<a.length;u+=1){let l=a[u],d=o.get(l);if(l!==n)for(let m of i.get(l)??[])o.has(m.next)||(o.set(m.next,d+1),s.set(m.next,{node:l,edge:m.edge}),a.push(m.next))}if(!o.has(n))return[];let c=[];for(let u=n;u!==t;){let l=s.get(u);if(!l)return[];c.push(l.edge),u=l.node}return c.reverse()}function N1(e,t,n){let r=Em(e,n),i=new Map,o=[...t];for(let s of t)i.set(s,0);for(let s=0;s<o.length;s+=1){let a=o[s],c=i.get(a);for(let{next:u}of r.get(a)??[])i.has(u)||(i.set(u,c+1),o.push(u))}return i}function _1(e,t,n){return Ux(e,n)-Ux(t,n)||qx(e)-qx(t)||Gx(e.evidenceStrength)-Gx(t.evidenceStrength)||Gt.indexOf(e.family)-Gt.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 Ux(e,t){return Math.min(t.get(e.from.id)??Number.MAX_SAFE_INTEGER,t.get(e.to.id)??Number.MAX_SAFE_INTEGER)}function qx(e){let t=[e.from,e.to].filter(n=>n.kind==="structural-region").length;return t===2?2:t}function Gx(e){switch(e){case"exact":return 0;case"mixed":return 1;case"derived":return 2;case"candidate":return 3;case"unknown":return 4}}function Im(e,t){let n=Tr(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let r=n.map(()=>"?").join(", "),o=e.all(`SELECT relative_path FROM documents
92
- WHERE relative_path IN (${r})
93
- ORDER BY relative_path`,...n).map(u=>u.relative_path).filter(u=>!e.isIgnored(u)),s=Qs(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:u,...l})=>l),a=Hn(e,"forward",n).filter(u=>!e.isIgnored(u)),c=Hn(e,"reverse",n).filter(u=>!e.isIgnored(u));return{files:o,symbols:s,dependsOn:a,dependedOnBy:c}}function wm(e,t){let n=Tr(e,t);return n.length===0?[]:Kx([...zx(e,n),...B1(e,n)]).filter(r=>!e.isIgnored(r.relative_path)).map(Wx)}function O1(e,t){let n=Tr(e,t);return n.length===0?[]:Kx(zx(e,n)).filter(r=>!e.isIgnored(r.relative_path)).map(r=>({...Wx(r),basis:"external-reference"}))}function zx(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
94
- FROM mentions m
95
- JOIN chunks c ON m.chunk_id = c.id
96
- JOIN documents d1 ON c.document_id = d1.id
97
- JOIN global_symbols gs ON m.symbol_id = gs.id
98
- WHERE d1.relative_path NOT IN (${n})
99
- AND (
100
- EXISTS (
101
- SELECT 1
102
- FROM defn_enclosing_ranges der
103
- JOIN documents d2 ON der.document_id = d2.id
104
- WHERE der.symbol_id = gs.id
105
- AND d2.relative_path IN (${n})
106
- )
107
- OR EXISTS (
108
- SELECT 1
109
- FROM mentions def_m
110
- JOIN chunks def_c ON def_m.chunk_id = def_c.id
111
- JOIN documents d2 ON def_c.document_id = d2.id
112
- WHERE def_m.symbol_id = gs.id
113
- AND def_m.role = 1
114
- AND d2.relative_path IN (${n})
115
- )
116
- )
117
- AND m.role != 1
118
- AND ${e.localSymbolPredicate}
119
- ${e.pathExclusionsFor("d1")}
120
- ORDER BY d1.relative_path`,...t,...t,...t)}function B1(e,t){let n=new H(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>Qe(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function Kx(e){let t=new Set;return e.filter(n=>{let r=`${n.relative_path}|${n.symbol}`;return t.has(r)?!1:(t.add(r),!0)})}function Wx(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:T(e.symbol)}}var ps=new WeakMap,Vx=ft({kind:"definition-exclusions",invalidation:Ne("definition-exclusions"),serialize:e=>JSON.stringify(e),deserialize:$1});function Jx(e,t){let n=ae(t);if(!(n==="rust"||n==="typescript"||n==="tsx"||n==="javascript"))return[];let i=V(e,t);if(!i)return[];let o=Pt(e,t,i),s=Vx.read(e,t,o);if(s)return s;let a=n==="rust"?W1(e,t):q1(e,t);return Vx.write(e,t,o,a),a}function $1(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=t.map(j1);return n.some(r=>r===null)?null:n}catch{return null}}function j1(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?oH(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 Xx=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]),H1=/\b(?:describe|it|test|fdescribe|fit|xdescribe|xit|beforeEach|afterEach|beforeAll|afterAll|before|after|suite|bench|benchmark)\s*\(/,U1=/\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 q1(e,t){let n=V(e,t);if(!n||!G1(n))return[];let r=J(e,t);if(!r)return[];let i=ps.get(r);if(i)return i;let o=!1,s=r.rootNode;for(let c of s.namedChildren){if(c.type!=="expression_statement")continue;let u=c.namedChild(0);if(!u||u.type!=="call_expression")continue;let l=u.namedChild(0);if(!l)continue;let d=l.type==="member_expression"?l.namedChild(l.namedChildCount-1)?.text:l.text;if(d&&Xx.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 u=null,l=null;if(c.type==="function_declaration")u=c.namedChild(0)?.text??null,l=c;else if(c.type==="export_statement"){let d=c.namedChild(0);d?.type==="function_declaration"&&(u=d.namedChild(0)?.text??null,l=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")&&(u=m,l=d)}}u&&/^use[A-Z]/.test(u)&&l&&a.push({startLine:l.startPosition.row,endLine:l.endPosition.row,reason:"React custom hook (use*)",disposition:"exclude"})}return a.push(...Qx(r,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),ps.set(r,a),a}function G1(e){if(e.includes("scip-query"))return!0;let t=!1;for(let n of Xx)if(e.includes(n)){t=!0;break}return t&&H1.test(e)?!0:e.includes("use")&&U1.test(e)}var z1=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function K1(e){return z1.test(e)}function Qx(e,t,n){let r=[],i=o=>{if(t.has(o.type)&&o.parent){let a=o.parent.children,c=-1;for(let u=0;u<a.length;u+=1)if(a[u].startIndex===o.startIndex&&a[u].type===o.type){c=u;break}if(c>0)for(let u=c-1;u>=0;u-=1){let l=a[u];if(n.has(l.type)){if(K1(l.text)){r.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"scip-query suppression comment",disposition:"exclude"});break}continue}if(!(l.type==="attribute_item"||l.type==="inner_attribute_item"))break}}for(let s of o.namedChildren)i(s)};return i(e.rootNode),r}function W1(e,t){let n=J(e,t);if(!n)return[];let r=ps.get(n);if(r)return r;let i=[],o=V1(n);return o?(ps.set(n,o),o):(Zx(n.rootNode,i,!1,!1),i.push(...Qx(n,new Set(["function_item","function_signature_item","struct_item","enum_item","union_item","impl_item","mod_item","static_item","const_item"]),new Set(["line_comment","block_comment"]))),i.push(...rH(n.rootNode)),ps.set(n,i),i)}function V1(e){return sH(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)",disposition:"exclude"}]:null}function Zx(e,t,n,r){let i=n,o=r;e.type==="trait_item"&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait declaration body (dynamic dispatch)",disposition:"implicit-usage"}),e.type==="impl_item"&&e.childForFieldName("trait")&&(o=!0,t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl block (dynamic dispatch)",disposition:"implicit-usage"})),e.type==="function_item"||e.type==="function_signature_item"?Y1(e,t,n,r):r&&nH(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"?J1(e,t,n):e.type==="mod_item"&&Lm(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(i=!0);for(let s of e.namedChildren)Zx(s,t,i,o)}function Y1(e,t,n,r){let i=Lm(e),o=null;r?o={reason:"trait impl method (dynamic dispatch)",disposition:"implicit-usage"}:n&&(o={reason:"inside #[cfg(test)] mod",disposition:"exclude"});for(let s of i){if(eR(s)){o={reason:"#[allow(dead_code)]",disposition:"exclude"};break}let a=eH(s);if(a){o=a;break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o.reason,disposition:o.disposition})}function J1(e,t,n){let r=Lm(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(tH)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(...)] - generated impl may access fields",disposition:"implicit-usage",containerName:i}),r.some(eR)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",disposition:"exclude",containerName:i}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",disposition:"exclude",containerName:i})}function Lm(e){let t=e.parent;if(!t)return[];let n=t.children,r=-1;for(let o=0;o<n.length;o+=1)if(n[o].startIndex===e.startIndex&&n[o].type===e.type){r=o;break}if(r<=0)return[];let i=[];for(let o=r-1;o>=0;o-=1){let s=n[o];if(s.type==="attribute_item"||s.type==="inner_attribute_item")i.push(s.text);else{if(s.type==="line_comment"||s.type==="block_comment")continue;break}}return i}var X1=new Set(["test","bench","tokio::test","async_std::test"]),Q1=new Set(["no_mangle","export_name","link_name","used","macro_export","proc_macro","proc_macro_derive","proc_macro_attribute"]),Z1=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 eH(e){if(/#\[\s*cfg\s*\(\s*test\s*\)/.test(e))return{reason:"#[cfg(test)]",disposition:"exclude"};let t=iH(e);return t?X1.has(t)?{reason:`#[${t}]`,disposition:"exclude"}:Q1.has(t)?{reason:`Rust ABI/export attribute #[${t}]`,disposition:"implicit-usage"}:Z1.has(t)?null:{reason:`Rust attribute macro #[${t}]`,disposition:"implicit-usage"}:null}function tH(e){return/#\[\s*derive\s*\(/.test(e)}function eR(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function nH(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function rH(e){let t=aH(e);if(t.size===0)return[];let n=[];for(let r of e.descendantsOfType("mod_item")){let i=r.childForFieldName("name")?.text;i&&t.has(i)&&n.push({startLine:r.startPosition.row,endLine:r.endPosition.row,reason:'attribute `with = "..."` module - body may be invoked via reflection',disposition:"implicit-usage",containerName:i})}return n}function iH(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 oH(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 sH(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 Yx=/\bwith\s*=\s*"([^"]+)"/g;function aH(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){Yx.lastIndex=0;let r;for(;(r=Yx.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}function tR(e){let t=Pm(e);return(n,r,i,o)=>t(n,r,i,o)?.disposition==="exclude"}function Pm(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=Jx(e,r),s=new Map;for(let a of o){if(!a.containerName)continue;let c=s.get(a.containerName)??[];c.push(a),s.set(a.containerName,c)}return i={ranges:o,containers:s},t.set(r,i),i};return(r,i,o,s)=>{let a=n(r),c=[];for(let l of a.ranges)i>=l.startLine&&i<=l.endLine&&c.push(l);let u=new Set;s&&u.add(s);for(let l of Zs(o))u.add(l);for(let l of u){let d=a.containers.get(l);d&&c.push(...d)}return cH(c)}}function cH(e){if(e.length===0)return null;let n=e.find(r=>r.disposition==="exclude")??e[0];return{disposition:n.disposition,reason:n.reason}}var lH=/(?:^|\/)(?:migrations?\/meta\/|drizzle\/meta\/|prisma\/migrations\/|__generated__\/|generated\/)|(?:^|\/)(?:_journal\.json|migration_lock\.toml)$|(?:^|\/)[^/]*(?:snapshot|\.generated|\.gen)\.[a-z0-9]+$|(?:^|\/)(?:migrations?|drizzle)\/[^/]+\.sql$|(?:^|\/)(?:migrations?|drizzle)\/(?:schema|relations)\.[cm]?[jt]s$/i;function Hc(e){return lH.test(pe(e))}function Dm(e,t={}){co(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function nR(e,t,n={}){co(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function rR(e,t){if(t.isIgnoredPath(e.relativePath))return it("ignored-file");if(fe(e.symbol))return it("module-like-symbol");if(!Uc(e.symbol))return it("non-value-symbol");if(!e.isFunctionLike&&e.enclosingSymbol&&Uc(e.enclosingSymbol))return it("nested-non-callable-value");if(!t.includeTests&&!uH(e.relativePath))return it("test-file");if(!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName))return it("excluded-file-region");let n=G(e.symbol);if(n==="<constructor>")return it("implicit-constructor");if(e.symbol.startsWith("scip-python ")){if(n==="__all__")return it("python-runtime-metadata");if(/^__[^_].*__$/.test(n))return it("python-protocol-member")}return t.isDeclarationOnlyCallable()?it("declaration-only-callable"):t.isFrameworkContractCallable()?it("framework-contract-member"):Ge(e.symbol)?it("rust-trait-impl-member"):gi(e.symbol)?it("rust-test-module"):!t.includeMembers&&!dH(e)?it("member"):e.endLine-e.startLine+1<t.minLoc?it("below-min-loc"):{accepted:!0}}function uH(e){return U(e)!=="test"}function it(e){return{accepted:!1,rejectionReason:e}}function Uc(e){return Re(e)||e.endsWith("().")||e.endsWith(".")}function dH(e){return Qe(e.symbol)||Zs(e.symbol).length===0}function iR(){return new Map}function oR(e,t,n){let r=new Map;for(let i of vg(e,n))e.isIgnored(i.relative_path)||t.has(i.relative_path)||Gc(r,i.symbol_id,i.relative_path,i.ref_count,"scip-mention");return r}function sR(e,t,n,r={}){let i=new Set;if(r.conservative||n.size===0){for(let o of xg(e,t))i.add(o.symbol_id);return i}for(let o of Cg(e,t))e.isIgnored(o.relative_path)||n.has(o.relative_path)||i.add(o.symbol_id);return i}function Mm(e,t){let n=e.get(t);if(!n)return!1;for(let r of n.values())if(r.occurrences>0)return!0;return!1}function qc(e,t,n){let r=e.get(t);if(!r)return!1;for(let[i,o]of r)if(i!==n&&o.occurrences>0)return!0;return!1}function aR(e){return e?.occurrences??0}function Gc(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=lR(e,t,n);o.occurrences+=r,o.sources.add(i)}function cR(e,t,n,r,i){if(r<=0)return;let o=lR(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function lR(e,t,n){let r=e.get(t);r||(r=new Map,e.set(t,r));let i=r.get(n);return i||(i={occurrences:0,sources:new Set},r.set(n,i)),i}var mH=new Set(["componentDidCatch","componentDidMount","componentDidUpdate","componentWillUnmount","getDerivedStateFromError","getDerivedStateFromProps","getSnapshotBeforeUpdate","render","shouldComponentUpdate","UNSAFE_componentWillMount","UNSAFE_componentWillReceiveProps","UNSAFE_componentWillUpdate"]);function Ki(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=J(e,t.relativePath);if(!n)return!1;let r=n.rootNode.descendantsOfType("method_definition").find(s=>s.startPosition.row<=t.startLine&&s.endPosition.row>=t.endLine);if(!r)return!1;if(/\boverride\b/.test(r.text.slice(0,Math.max(0,r.text.indexOf("{")))))return!0;let i=r.parent;for(;i&&i.type!=="class_declaration"&&i.type!=="class";)i=i.parent;if(!i)return!1;let o=i.text.slice(0,Math.max(0,i.text.indexOf("{")));return/\bimplements\b/.test(o)||/\bextends\b/.test(o)?!0:mH.has(t.leaf)&&/\bextends\s+(?:React\.)?(?:Component|PureComponent)\b/.test(o)}var pH=64,fH=300;function ti(e,t={}){let{scope:n,minLoc:r=1,includeTests:i=!1,skipBarrels:o=!1,includeMembers:s=!1,deadCodeOnly:a=!1,scanLimit:c,semantic:u=!0}=t,l=0,d=N("dead.candidates",()=>{let v=be(gH(e,{scope:n,minLoc:r,includeTests:i,includeMembers:s}),c);return l=v.length,v},()=>({definitions:l})),m=0,p=o?N("dead.inactive-barrels",()=>{let v=new Set(KS(e));return m=v.size,v},()=>({paths:m})):new Set,f=0,g=a?iR():N("dead.mention-reference-counts",()=>{let v=oR(e,p,d.map(C=>C.symbolId));return f=v.size,v},()=>({definitions:d.length,symbolsWithReferences:f})),h=0,y=a?N("dead.mentioned-symbol-ids",()=>{let v=sR(e,d.map(C=>C.symbolId),p,{conservative:p.size===0});return h=v.size,v},()=>({definitions:d.length,referencedSymbols:h})):new Set,S=a?d.filter(v=>!y.has(v.symbolId)):d.filter(v=>!qc(g,v.symbolId,v.relativePath));a?N("dead.source-fallback.dead-code-only",()=>xH(e,S,g,{inactiveBarrelPaths:p}),()=>({definitions:S.length,testReferencesIncluded:!0})):N("dead.source-fallback.ast",()=>CH(e,S,g,{inactiveBarrelPaths:p}),()=>({definitions:S.length,testReferencesIncluded:!0}));let b=a?S.filter(v=>!Mm(g,v.symbolId)):S.filter(v=>!qc(g,v.symbolId,v.relativePath));N("dead.caller-map-supplement",()=>wH(e,b,g,{inactiveBarrelPaths:p,includeSemantic:!a&&u}),()=>({definitions:b.length,semantic:!a&&u}));let x=a?S.filter(v=>!Mm(g,v.symbolId)):d;return vH(e,bH(x,g))}function gH(e,t){let n=tR(e),r=[];for(let i of po(e,{scope:t.scope,symbolMatches:Uc,sqlPrefilter:"function-like"}))rR(i,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:s=>e.isIgnored(s),isExcludedRegion:n,isDeclarationOnlyCallable:()=>yH(e,i),isFrameworkContractCallable:()=>Ki(e,i)}).accepted&&r.push(i);return r}var hH=["method_signature","abstract_method_signature","call_signature","construct_signature"];function yH(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=J(e,t.relativePath);if(n)return n.rootNode.descendantsOfType([...hH]).some(i=>i.startPosition.row<=t.startLine&&i.endPosition.row>=t.endLine);let r=K(e,t.relativePath).slice(t.startLine,t.endLine+1).join(`
121
- `).trim();return r.endsWith(";")&&!r.includes("=>")&&!r.includes("{")}function bH(e,t){return e.map(n=>SH(n,t)).filter(n=>n.cross_file_refs===0).sort((n,r)=>r.loc-n.loc||n.relative_path.localeCompare(r.relative_path)||n.start_line-r.start_line)}function SH(e,t){let n=t.get(e.symbolId)??new Map,r=aR(n.get(e.relativePath)),i=0;for(let[o,s]of n)o!==e.relativePath&&(i+=s.occurrences);return{relative_path:e.relativePath,start_line:e.startLine,end_line:e.endLine,loc:e.endLine-e.startLine+1,symbol:e.symbol,parent_type_name:e.parentTypeName,same_file_refs:r,cross_file_refs:i}}function vH(e,t){let n=Pm(e),r=[],i=0,o=0,s=0,a=0,c=0,u=0,l=0;for(let d of t){if(e.isIgnored(d.relative_path))continue;if(ze(e,d.relative_path)){a++;continue}if(Hc(d.relative_path)){u++;continue}if(Be(e,d.symbol,d.relative_path)){c++;continue}let m=n(d.relative_path,d.start_line,d.symbol,d.parent_type_name),p=m?.disposition==="implicit-usage"?m.reason:void 0,f=p?"implicit-usage":d.same_file_refs===0?"dead-code":"file-internal";f==="dead-code"?i++:f==="file-internal"?o++:s++,l+=d.loc,r.push({relativePath:d.relative_path,startLine:d.start_line,endLine:d.end_line,loc:d.loc,symbol:d.symbol,shortName:T(d.symbol),sameFileRefs:d.same_file_refs,kind:f,...p?{implicitUsageReason:p}:{}})}return{symbols:r,counts:{total:r.length,deadCode:i,fileInternal:o,implicitUsage:s,loc:l},applicability:{entrySurfaceExcluded:a,externalRootExcluded:c,generatedArtifactExcluded:u,implicitUsageSignals:s},totalCount:r.length,deadCodeCount:i,fileInternalCount:o,implicitUsageCount:s,totalLoc:l}}function CH(e,t,n,r){if(t.length===0)return;let i=new H(e),o=new Set(t.map(c=>c.symbolId)),s=new Set(t.map(c=>c.leaf).filter(Boolean)),a=new Set(i.sourceFiles());for(let c of Q(e))a.add(c);i.scanSourceReferences({paths:a,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:s,skipPath:c=>r.inactiveBarrelPaths.has(c)},c=>{o.has(c.target.symbolId)&&(EH(e,c)||Gc(n,c.target.symbolId,c.sourceFile,IH(c),"source-fallback"))})}function xH(e,t,n,r){if(t.length===0)return;let i=new H(e),o=gg(t),s=new Set(i.sourceFiles());for(let l of Q(e))s.add(l);let a=new Set(o.keys()),c=new Map,u=l=>{let d=c.get(l);return d||(d=wg(e,l),c.set(l,d)),d};i.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:l=>r.inactiveBarrelPaths.has(l),resolveTargets:({sourceFile:l,name:d,kind:m})=>{let p=o.get(d);return p?RH(l,d,p,()=>u(l),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:l=>{c.delete(l),nR(e,l)}},l=>{let d=l.kind==="identifier"&&l.sourceFile===l.target.relativePath?Math.max(0,l.occurrences-1):l.occurrences;l.kind==="identifier"&&uR(e,{sourceFile:l.sourceFile,name:l.name,target:l.target,occurrences:d})||Gc(n,l.target.symbolId,l.sourceFile,d,"source-fallback")})}function RH(e,t,n,r,i){let o=n.filter(u=>u.relativePath===e);if(o.length>0)return o;if(!i.permissive&&n.length===1)return[...n];let s=r(),a=s.get(t);if(a)for(let u of a){let l=n.filter(d=>ke(u,d.relativePath));if(l.length>0)return l}let c=new Set;for(let u of s.values())for(let l of u)c.add(l);for(let u of c){let l=n.filter(d=>ke(u,d.relativePath));if(l.length>0&&l.length===n.length)return l}return i.permissive?[...n]:[]}function EH(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&uR(e,t)}function IH(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function uR(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 wH(e,t,n,r){let i=r.includeSemantic!==!1,o=i&&t.length>=pH&&Q(e).length>=fH,s=(l,d)=>{d===l.relativePath||e.isIgnored(d)||r.inactiveBarrelPaths.has(d)||cR(n,l.symbolId,d,1,"caller-map")};if(o?N("dead.caller-map.per-symbol-non-semantic",()=>{let l=Rn(e,t,{semantic:!1,semanticEvidence:ie});for(let d of t){let m=l.get(d.symbolId)??[];for(let p of m)s(d,p.file)}},()=>({definitions:t.length,semantic:!1,batched:!0})):N("dead.caller-map.per-symbol",()=>{for(let l of t){let d=Vn(e,l,{semantic:i,semanticEvidence:ie});if(d.length!==0)for(let m of d)s(l,m.file)}},()=>({definitions:t.length,semantic:i})),!o)return;let a=0,c=N("dead.caller-map.semantic-candidates",()=>{let l=t.filter(d=>!qc(n,d.symbolId,d.relativePath));return a=l.length,l},()=>({definitions:t.length,semanticCandidates:a}));if(c.length===0)return;let u=Bb(e,c);for(let l of c){let d=u.get(l.symbolId);if(d)for(let m of d)s(l,m)}}function LH(e,t={}){let{limit:n=30,scope:r}=t,i=r?"AND def_d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[],a=e.all(`SELECT
122
- gs.symbol,
123
- COUNT(*) AS ref_count,
124
- COUNT(DISTINCT ref_d.id) AS file_count,
125
- def_d.relative_path AS defined_in
126
- FROM mentions m
127
- JOIN chunks c ON m.chunk_id = c.id
128
- JOIN documents ref_d ON c.document_id = ref_d.id
129
- JOIN global_symbols gs ON m.symbol_id = gs.id
130
- JOIN (
131
- SELECT m2.symbol_id, c2.document_id
132
- FROM mentions m2
133
- JOIN chunks c2 ON m2.chunk_id = c2.id
134
- WHERE m2.role = 1
135
- GROUP BY m2.symbol_id
136
- ) sym_def ON sym_def.symbol_id = gs.id
137
- JOIN documents def_d ON sym_def.document_id = def_d.id
138
- WHERE m.role != 1
139
- AND def_d.id != ref_d.id
140
- ${e.pathExclusionsFor("def_d")}
141
- ${e.symbolNoiseFor("gs")}
142
- ${i}
143
- GROUP BY gs.id
144
- ORDER BY ref_count DESC
145
- LIMIT ?`,...o,n).filter(c=>!e.isIgnored(c.defined_in)).map(c=>({symbol:c.symbol,shortName:T(c.symbol),refCount:c.ref_count,fileCount:c.file_count,definedIn:c.defined_in,basis:"scip-cross-file-mentions",countUnit:"reference-occurrences"}));return a.length>0?a:PH(e,r,n)}function PH(e,t,n){return ye(e,{scope:t}).filter(r=>!e.isIgnored(r.relativePath)).map(r=>DH(e,r)).filter(r=>r.refCount>0).sort((r,i)=>i.refCount-r.refCount||i.fileCount-r.fileCount).slice(0,n)}function DH(e,t){let r=Vn(e,t,{limit:500,semanticEvidence:ie}).filter(i=>i.file!==t.relativePath);return{symbol:t.symbol,shortName:T(t.symbol),refCount:r.length,fileCount:new Set(r.map(i=>i.file)).size,definedIn:t.relativePath,basis:"source-backed-incoming-evidence",countUnit:"distinct-incoming-evidence-rows"}}function MH(e,t,n={}){return jH(e,t,n)?.map(r=>({symbol:r.symbol,shortName:r.shortName,fromFile:r.fromFile}))??[]}function TH(e,t){let n=re(e,t),r=FH(e,t);if(r.length>0&&!_H(n))return r;let i=NH(e,t,n);return Tm(t)&&i.length>0?i:OH([...r,...i])}function kH(e,t,n={}){let r=gt(e,t);if(!r)return[];let i=mR(e,r),o=n.semantic===!1?null:dR(e,r);return(o?AH(o,i):i).filter(a=>!a.used).map(a=>({symbol:a.symbol,shortName:a.shortName,importedIn:a.importer}))}function AH(e,t){let n=new Map;for(let i of t){let o=n.get(i.shortName);o?o.push(i):n.set(i.shortName,[i])}let r=e.map(i=>{let o=n.get(i.shortName),s=o?.shift();return o?.length===0&&n.delete(i.shortName),s?{...i,used:i.used||s.used}:i});return r.push(...[...n.values()].flat()),r}function FH(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
146
- FROM mentions m
147
- JOIN chunks c ON m.chunk_id = c.id
148
- JOIN documents d ON c.document_id = d.id
149
- JOIN global_symbols gs ON m.symbol_id = gs.id
150
- WHERE gs.symbol LIKE ?
151
- AND m.role = 2
152
- ORDER BY d.relative_path`,`%${t}%`).filter(r=>!e.isIgnored(r.importer)).map(r=>({symbol:r.symbol,shortName:T(r.symbol),fromFile:r.importer}))}function NH(e,t,n=re(e,t)){let r=n?.relativePath??null,i=n?G(n.symbol):t.replace(/\(\)$/,""),o=n?fe(n.symbol):!1,s=new Set;for(let c of Q(e,{includeIgnored:!1}))for(let u of ce(e,c))BH(u,c,{targetFile:r,targetLeaf:i,targetIsModule:o,targetPattern:t})&&s.add(c);let a=Tm(t)?t.trim():null;return[...s].sort().map(c=>({symbol:a??n?.symbol??i,shortName:a??(n?T(n.symbol):i),fromFile:c}))}function _H(e){return!!(e&&(e.symbol.startsWith("scip-clojure ")||ae(e.relativePath)==="clojure"))}function OH(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.fromFile}`;t.has(i)||(t.add(i),n.push(r))}return n.sort((r,i)=>r.fromFile.localeCompare(i.fromFile)||r.shortName.localeCompare(i.shortName))}function BH(e,t,n){return!e.sourcePath||n.targetFile&&pe(e.sourcePath)!==pe(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&GH(t)||e.kind==="namespace"&&$H(e,n.targetPattern)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function $H(e,t){let n=t.trim().replace(/\(\)$/,"");return Tm(n)?e.importedName===n||e.localName===n:!1}function Tm(e){let t=e.trim().replace(/\(\)$/,"");return t.includes(".")&&!t.includes("/")&&!t.includes(":")}function jH(e,t,n={}){let r=gt(e,t);return r?HH(e,r,n)??(n.semantic===!1?null:dR(e,r))??mR(e,r):null}function HH(e,t,n){let i=e.all(`SELECT DISTINCT
153
- gs.symbol,
154
- def_d.relative_path AS from_file,
155
- imp_d.relative_path AS importer,
156
- EXISTS (
157
- SELECT 1
158
- FROM mentions ref_m
159
- JOIN chunks ref_c ON ref_m.chunk_id = ref_c.id
160
- WHERE ref_m.symbol_id = gs.id
161
- AND ref_m.role != 1
162
- AND ref_c.document_id = imp_d.id
163
- ) AS used
164
- FROM mentions m
165
- JOIN chunks c ON m.chunk_id = c.id
166
- JOIN documents imp_d ON c.document_id = imp_d.id
167
- JOIN global_symbols gs ON m.symbol_id = gs.id
168
- LEFT JOIN (
169
- SELECT m2.symbol_id, c2.document_id
170
- FROM mentions m2
171
- JOIN chunks c2 ON m2.chunk_id = c2.id
172
- WHERE m2.role = 1
173
- GROUP BY m2.symbol_id
174
- ) sym_def ON sym_def.symbol_id = gs.id
175
- LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
176
- WHERE imp_d.relative_path = ?
177
- AND m.role = 2
178
- ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(i.length>0){let o=n.semantic===!1?[]:Uo(e,t);return i.map(s=>({symbol:s.symbol,shortName:T(s.symbol),fromFile:s.from_file??"(external)",importer:s.importer,used:s.used!==0||o.some(a=>a.isUsed&&a.sourcePath===s.from_file)}))}return null}function dR(e,t){let n=Uo(e,t);return n.length>0?n.map(r=>{let i=pR(r.importedName,r.localName,r.kind);return{symbol:i,shortName:i,fromFile:r.sourcePath??"(external)",importer:t,used:r.kind==="side-effect"?!0:r.isUsed}}):null}function mR(e,t){let n=UH(t,V(e,t));return ce(e,t).map(r=>{let i=pR(r.importedName,r.localName,r.kind),o=r.kind==="side-effect"||qH(t,r)||n.has(r.localName??r.importedName)?!0:r.used;return{symbol:i,shortName:i,fromFile:r.sourcePath??"(external)",importer:t,used:o}})}function UH(e,t){let n=new Set;if(ae(e)!=="python")return n;let r=/(?:^|\n)\s*__all__\s*(?:\+?=)\s*[[(]([\s\S]*?)[\])]/g;for(let i of t.matchAll(r)){let o=i[1]??"";for(let s of o.matchAll(/(['"])([A-Za-z_]\w*)\1/g))n.add(s[2])}return n}function qH(e,t){if(ae(e)!=="rust"||t.used||t.kind==="side-effect")return!1;let n=t.localName??t.importedName;return n==="_"||/^[A-Z]/.test(n)}function pR(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 GH(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function zH(e,t){let n=re(e,t);if(!n)return[];let i=new H(e).definitionsForFile(n.relativePath).filter(o=>o.symbol!==n.symbol).filter(o=>pg(n.symbol,o.symbol)).sort((o,s)=>o.startLine-s.startLine||o.endLine-s.endLine).map(o=>({symbol:o.symbol,shortName:T(o.symbol),startLine:o.startLine,endLine:o.endLine,kind:kt(o.symbol)??"unknown"}));return ae(n.relativePath)!=="clojure"?i:WH(i,KH(e,n))}function KH(e,t){let n=G(t.symbol);if(!n)return[];let r=T(t.symbol);return(W(e,t.relativePath)?.clojureMembers??[]).filter(i=>i.ownerName===n).map(i=>({symbol:`${t.symbol}${i.memberName}().`,shortName:`${r}:${i.memberName}()`,startLine:i.startLine,endLine:i.endLine,kind:i.memberKind}))}function WH(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.shortName}:${r.startLine}:${r.endLine}`,r);return[...n.values()].sort((r,i)=>r.startLine-i.startLine||r.endLine-i.endLine)}function VH(e,t){let n=re(e,t);if(!n)return[];let r=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
179
- FROM mentions m
180
- JOIN chunks c ON m.chunk_id = c.id
181
- JOIN (
182
- SELECT m2.symbol_id, c2.document_id
183
- FROM mentions m2
184
- JOIN chunks c2 ON m2.chunk_id = c2.id
185
- WHERE m2.role = 1
186
- GROUP BY m2.symbol_id
187
- ) sym_def ON sym_def.symbol_id = m.symbol_id
188
- WHERE m.symbol_id = ?
189
- AND m.role != 1
190
- AND sym_def.document_id != c.document_id`,n.symbolId);return[{name:T(n.symbol),count:r?.file_count??0,symbol:n.symbol,definedIn:n.relativePath}]}function YH(e,t){let n=gt(e,t);return n?e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
191
- FROM mentions m
192
- JOIN chunks c ON m.chunk_id = c.id
193
- JOIN documents d ON c.document_id = d.id
194
- JOIN global_symbols gs ON m.symbol_id = gs.id
195
- JOIN (
196
- SELECT m2.symbol_id, c2.document_id
197
- FROM mentions m2
198
- JOIN chunks c2 ON m2.chunk_id = c2.id
199
- WHERE m2.role = 1
200
- GROUP BY m2.symbol_id
201
- ) sym_def ON sym_def.symbol_id = gs.id
202
- JOIN documents def_d ON sym_def.document_id = def_d.id
203
- WHERE d.relative_path = ?
204
- AND m.role != 1
205
- AND def_d.id != d.id
206
- GROUP BY d.id
207
- ORDER BY symbol_count DESC`,n).filter(o=>!e.isIgnored(o.relative_path)).map(o=>({name:o.relative_path,count:o.symbol_count,file:o.relative_path,basis:"external-symbol-references"})):[]}function JH(e,t={}){return XH(e,t).map(n=>({name:T(n.symbol),count:n.file_count,symbol:n.symbol,definedIn:n.defined_in}))}function XH(e,t){let{limit:n=30,scope:r}=t,i=r?"AND def_d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[];return e.all(`SELECT gs.symbol,
208
- COUNT(DISTINCT c.document_id) AS file_count,
209
- def_d.relative_path AS defined_in
210
- FROM mentions m
211
- JOIN chunks c ON m.chunk_id = c.id
212
- JOIN global_symbols gs ON m.symbol_id = gs.id
213
- JOIN (
214
- SELECT m2.symbol_id, c2.document_id
215
- FROM mentions m2
216
- JOIN chunks c2 ON m2.chunk_id = c2.id
217
- WHERE m2.role = 1
218
- GROUP BY m2.symbol_id
219
- ) sym_def ON sym_def.symbol_id = gs.id
220
- JOIN documents def_d ON sym_def.document_id = def_d.id
221
- WHERE m.role != 1
222
- AND def_d.id != c.document_id
223
- ${e.pathExclusionsFor("def_d")}
224
- ${e.symbolNoiseFor("gs")}
225
- ${i}
226
- GROUP BY gs.id
227
- HAVING file_count > 1
228
- ORDER BY file_count DESC
229
- LIMIT ?`,...o,n)}function QH(e,t={}){let{limit:n=30,scope:r}=t,i=r?"AND d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[];return e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
230
- FROM mentions m
231
- JOIN chunks c ON m.chunk_id = c.id
232
- JOIN documents d ON c.document_id = d.id
233
- JOIN global_symbols gs ON m.symbol_id = gs.id
234
- JOIN (
235
- SELECT m2.symbol_id, c2.document_id
236
- FROM mentions m2
237
- JOIN chunks c2 ON m2.chunk_id = c2.id
238
- WHERE m2.role = 1
239
- GROUP BY m2.symbol_id
240
- ) sym_def ON sym_def.symbol_id = gs.id
241
- JOIN documents def_d ON sym_def.document_id = def_d.id
242
- WHERE m.role != 1
243
- AND def_d.id != d.id
244
- ${e.pathExclusionsFor("d")}
245
- ${e.symbolNoiseFor("gs")}
246
- ${i}
247
- GROUP BY d.id
248
- ORDER BY symbol_count DESC
249
- LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}))}var fR=`SELECT COUNT(*) AS shared
250
- FROM (
251
- SELECT definition_m.symbol_id
252
- FROM documents definition_d
253
- JOIN chunks definition_c ON definition_c.document_id = definition_d.id
254
- JOIN mentions definition_m ON definition_m.chunk_id = definition_c.id
255
- AND definition_m.role = 1
256
- JOIN mentions reference_m ON reference_m.symbol_id = definition_m.symbol_id
257
- AND reference_m.role != 1
258
- JOIN chunks reference_c ON reference_c.id = reference_m.chunk_id
259
- JOIN documents reference_d ON reference_d.id = reference_c.document_id
260
- WHERE definition_d.relative_path = ?
261
- AND reference_d.relative_path = ?
262
- UNION
263
- SELECT definition_m.symbol_id
264
- FROM documents definition_d
265
- JOIN chunks definition_c ON definition_c.document_id = definition_d.id
266
- JOIN mentions definition_m ON definition_m.chunk_id = definition_c.id
267
- AND definition_m.role = 1
268
- JOIN mentions reference_m ON reference_m.symbol_id = definition_m.symbol_id
269
- AND reference_m.role != 1
270
- JOIN chunks reference_c ON reference_c.id = reference_m.chunk_id
271
- JOIN documents reference_d ON reference_d.id = reference_c.document_id
272
- WHERE definition_d.relative_path = ?
273
- AND reference_d.relative_path = ?
274
- )`;function ZH(e,t,n){let r=gt(e,t)??t,i=gt(e,n)??n,o=e.get(fR,r,i,i,r);return{...gR(r,i,o?.shared??0)}}function eU(e,t={}){let{limit:n=20,scope:r}=t,i=r?"AND def_d.relative_path LIKE ? AND ref_d.relative_path LIKE ?":"",o=r?[`%${r}%`,`%${r}%`]:[];return e.all(`SELECT
275
- CASE WHEN def_d.relative_path < ref_d.relative_path THEN def_d.relative_path ELSE ref_d.relative_path END AS file1,
276
- CASE WHEN def_d.relative_path < ref_d.relative_path THEN ref_d.relative_path ELSE def_d.relative_path END AS file2,
277
- COUNT(DISTINCT gs.id) AS shared
278
- FROM mentions m
279
- JOIN chunks c ON m.chunk_id = c.id
280
- JOIN documents ref_d ON c.document_id = ref_d.id
281
- JOIN global_symbols gs ON m.symbol_id = gs.id
282
- JOIN (
283
- SELECT m2.symbol_id, c2.document_id
284
- FROM mentions m2
285
- JOIN chunks c2 ON m2.chunk_id = c2.id
286
- WHERE m2.role = 1
287
- GROUP BY m2.symbol_id
288
- ) sym_def ON sym_def.symbol_id = gs.id
289
- JOIN documents def_d ON sym_def.document_id = def_d.id
290
- WHERE m.role != 1
291
- AND def_d.id != ref_d.id
292
- ${e.pathExclusionsFor("def_d","ref_d")}
293
- ${i}
294
- GROUP BY file1, file2
295
- ORDER BY shared DESC, file1, file2
296
- LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.file1)&&!e.isIgnored(a.file2)).map(a=>gR(a.file1,a.file2,a.shared))}function gR(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 pr(e){let t=new Map,n=[],r=new Map,i=new Map,o=new Set,s=[],a=0,c=u=>(e.get(u)??[]).values();for(let u of e.keys()){if(r.has(u))continue;let l=[];for(r.set(u,a),i.set(u,a),a+=1,s.push(u),o.add(u),l.push({node:u,iter:c(u),pendingChild:null});l.length>0;){let d=l[l.length-1];if(d.pendingChild!==null){let f=d.pendingChild;d.pendingChild=null,i.set(d.node,Math.min(i.get(d.node),i.get(f)))}let m=d.iter.next();if(m.done){if(i.get(d.node)===r.get(d.node)){let f=[];for(;;){let g=s.pop();if(o.delete(g),f.push(g),t.set(g,n.length),g===d.node)break}n.push(f)}l.pop();continue}let p=m.value;r.has(p)?o.has(p)&&i.set(d.node,Math.min(i.get(d.node),r.get(p))):(r.set(p,a),i.set(p,a),a+=1,s.push(p),o.add(p),d.pendingChild=p,l.push({node:p,iter:c(p),pendingChild:null}))}}return{components:n,componentOf:t}}function fs(e,t={}){return vR(e,t).cycles}function vR(e,t={}){return CR(e,t)}function CR(e,t={}){let{scope:n,maxDepth:r=10,edgeBasis:i="symbol-references"}=t,o=_e(e,n,i==="imports"?{scipEdges:"imports-only",sourceEdges:"imports-only"}:void 0),{components:s}=pr(o),a=s.filter(c=>xR(o,c)).map(c=>{let u=[...c].sort(),{path:l,kind:d}=tU(o,u);return{path:l,component:u,edgeBasis:i,witness:!0,classification:d==="real"?"dependency-cycle":"module-structure-candidate",kind:d}});return a.sort((c,u)=>c.kind!==u.kind?c.kind==="real"?-1:1:c.path.length-u.path.length),{cycles:a,truncated:!1,edgeBasis:i,maxDepth:r}}function tU(e,t){let n=hR(e,t),r=new Set(t.filter(c=>nU(c)));if(r.size===0)return{path:n,kind:yR(n)};let i=new Set(t),o=new Map;for(let c of t)r.has(c)||o.set(c,new Set([...e.get(c)??[]].filter(u=>i.has(u)&&!r.has(u))));let s=pr(o).components.filter(c=>xR(o,c)).map(c=>[...c].sort()).sort((c,u)=>c[0].localeCompare(u[0]))[0];if(!s)return{path:n,kind:"module-hierarchy"};let a=hR(o,s);return{path:a,kind:yR(a)}}function nU(e){let t=U(e);return t==="test"||t==="barrel"||t==="entry"||Ur(e)}function xR(e,t){if(t.length>1)return!0;let n=t[0];return n!==void 0&&e.get(n)?.has(n)===!0}function hR(e,t){let n=t[0];if(!n)return[];let r=new Set(t);for(let i of[...e.get(n)??[]].filter(o=>r.has(o)).sort()){if(i===n)return[n,n];let o=rU(e,i,n,r);if(o)return[n,...o]}throw new Error(`Cyclic component did not contain a witness path from ${n}.`)}function rU(e,t,n,r){let i=[t],o=new Map([[t,null]]);for(let s=0;s<i.length;s+=1){let a=i[s];if(a===n){let c=[];for(let u=a;u!==null;u=o.get(u)??null)c.push(u);return c.reverse()}for(let c of[...e.get(a)??[]].filter(u=>r.has(u)).sort())o.has(c)||(o.set(c,a),i.push(c))}return null}function yR(e){for(let r of e){let i=U(r);if(i==="test"||i==="barrel"||i==="entry")return"module-hierarchy"}if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":Ur(t)||Ur(n)||bR(t,n)||bR(n,t)||SR(t,n)||SR(n,t)||U(t)==="entry"||U(n)==="entry"?"module-hierarchy":"real"}function bR(e,t){if(!e.endsWith(".rs")||!t.endsWith(".rs"))return!1;let n=t.replace(/\.rs$/,"/");return e.startsWith(n)?!e.slice(n.length).includes("/"):!1}function SR(e,t){if(!e.endsWith(".rs")||!t.endsWith(".rs"))return!1;let n=e.replace(/\.rs$/,""),r=t.replace(/\.rs$/,"");if(n===r+"_tests"||n===r+"/tests")return!0;let i=e.split("/"),o=t.split("/");if(i.length===o.length&&i.includes("tests")&&o.includes("src")){let s=i[i.length-1],a=o[o.length-1];if(s&&s===a)return!0}return!1}function fr(e,t){let n=RR(e),r=RR(t);if(n.endsWith("/**")){let i=n.slice(0,-3);return r===i||r.startsWith(`${i}/`)}if(n.endsWith("/*")){let i=n.slice(0,-2);if(!r.startsWith(`${i}/`))return!1;let o=r.slice(i.length+1);return o.length>0&&!o.includes("/")}return n==="**"?!0:n==="*"?r.length>0&&!r.includes("/"):n===r}function RR(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}import{readdirSync as iU}from"fs";import{join as ER}from"path";function oU(e){return IR(e).replace(/\/\*\*?$/,"")}function zc(e,t){let n=IR(t),r=oU(n),i=n.endsWith("/**"),o=[],s=(a,c)=>{let u;try{u=iU(a,{withFileTypes:!0})}catch{return}for(let l of u){if(l.name.startsWith("."))continue;let d=c?`${c}/${l.name}`:l.name;fr(n,d)&&o.push(d),i&&l.isDirectory()&&s(ER(a,l.name),d)}};return s(ER(e,r),r),o.sort()}function IR(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}var sU=/\.(test|spec)\.(ts|tsx|js|jsx|mts|cts)$/,wR=new Map;function LR(e,t,n,r){if(!t?.testPaths?.length)return[];let i=aU(t),o=[];for(let s of cU(e,t.testPaths)){let a=lU(e,s,r),c=a?n(a):null;if(c)for(let u of ce(e,s)){let l=u.sourcePath;if(!l)continue;let d=n(l);d&&d!==c&&(i.get(c)?.has(d)||o.push({testFile:s,ownerBoundary:c,importedFile:l,importedBoundary:d,reason:"outside-owner-policy"}))}}return uU(o)}function aU(e){let t=e.allowedDependencies??{},n=e.boundaries.map(s=>s.name),r=new Map,i=(s,a)=>{for(let c of t[s]??[])a.has(c)||(a.add(c),i(c,a))};for(let s of n){let a=new Set;i(s,a),r.set(s,a)}let o=new Map;for(let s of n){let a=new Set(r.get(s));for(let c of n)c!==s&&r.get(c)?.has(s)&&a.add(c);o.set(s,a)}return o}function cU(e,t){let n=`${e.config.projectRoot}\0${t.join("\0")}`,r=wR.get(n);if(r)return r;let i=new Set;for(let s of t)for(let a of zc(e.config.projectRoot,s))sU.test(a)&&i.add(a);let o=[...i].sort();return wR.set(n,o),o}function lU(e,t,n){let r=t.replace(/^tests\//,"src/").replace(/\.(test|spec)\.(\w+)$/,".$2");if(r!==t&&n(r))return r;let i=t.split("/").pop().replace(/\.(test|spec)\.(\w+)$/,".$2"),o=ce(e,t).map(s=>s.sourcePath).filter(s=>!!s&&n(s)&&s.split("/").pop()===i);return o.length===1?o[0]:null}function uU(e){let t=new Map;for(let n of e){let r=`${n.testFile}\0${n.importedBoundary}`;t.has(r)||t.set(r,n)}return[...t.values()].sort((n,r)=>n.testFile.localeCompare(r.testFile)||n.importedBoundary.localeCompare(r.importedBoundary))}function PR(e,t){let n=(e?.boundaries??[]).filter(r=>r.paths.some(i=>fr(i,t)));return n.length===1?n[0].name:null}var Nn="architecture:";function DR(e,t,n,r={}){let i=mU(e,t);if(!n||n.boundaries.length===0)return{configured:!1,boundaries:[],edges:[],forbiddenEdges:[],reciprocalPairs:[],cycles:[],coarseBoundaries:[],staleAllowances:[],boundaryLimits:[],fragileEdges:[],testBoundaryViolations:[],coverage:{totalFiles:i.length,mappedFiles:0,unmappedFiles:[],ambiguousFiles:[]},policyCoverage:{declaredRows:0,totalBoundaries:0,missingRows:[],requiresCompletePolicy:!1,requiresCompleteCoverage:!1,requiresMinimalPolicy:!1}};let o=new Map,s=new Map(n.boundaries.map(b=>[b.name,new Set])),a=[],c=[];for(let b of i){let x=n.boundaries.filter(v=>v.paths.some(C=>fr(C,b))).map(v=>v.name).sort();if(x.length===0)a.push(b);else if(x.length>1)c.push({file:b,boundaries:x});else{let v=x[0];o.set(b,v),s.get(v).add(b)}}let u=new Map;for(let[b,x]of e){let v=o.get(b);if(v)for(let C of x){let R=o.get(C);if(!R||v===R)continue;let E=Wi(v,R),w=u.get(E);w||(w={from:v,to:R,fileEdges:[],importers:new Set,importedFiles:new Set},u.set(E,w)),w.fileEdges.push({fromFile:b,toFile:C}),w.importers.add(b),w.importedFiles.add(C)}}let l=[...u.values()].map(b=>pU(b,n)).sort(CU),d=l,m=new Map(d.map(b=>[Wi(b.from,b.to),b])),p=new Map(n.boundaries.map(b=>[b.name,new Set]));for(let b of d)p.get(b.from).add(b.to);let f=[];for(let b of d){if(b.from>=b.to)continue;let x=m.get(Wi(b.to,b.from));x&&f.push({boundaries:[b.from,b.to],forward:b,reverse:x})}let{components:g}=pr(p),h=g.filter(b=>b.length>1).map(b=>gU(b,d,n.requireAcyclic===!0)).sort((b,x)=>x.boundaries.length-b.boundaries.length||b.boundaries.join("/").localeCompare(x.boundaries.join("/"))),y=n.allowedDependencies??{},S=n.boundaries.map(b=>b.name).filter(b=>!Object.hasOwn(y,b)).sort();return{configured:!0,boundaries:n.boundaries.map(b=>({name:b.name,paths:[...b.paths],fileCount:s.get(b.name).size,dependencyPolicyDeclared:Object.hasOwn(y,b.name)})).sort((b,x)=>b.name.localeCompare(x.name)),edges:l,forbiddenEdges:d.filter(b=>b.policyStatus==="forbidden"),reciprocalPairs:f,cycles:h,staleAllowances:yU(n,d),boundaryLimits:bU(n,d,s),fragileEdges:d.filter(b=>b.fragile),testBoundaryViolations:r.testBoundaryViolations??[],coarseBoundaries:hU(e,s,r.isModuleHierarchyFile,n.requireResolvedBoundaries===!0,b=>n.boundaries.find(x=>x.name===b)?.subUnits??"directory"),coverage:{totalFiles:i.length,mappedFiles:o.size,unmappedFiles:a,ambiguousFiles:c},policyCoverage:{declaredRows:n.boundaries.length-S.length,totalBoundaries:n.boundaries.length,missingRows:S,requiresCompletePolicy:n.requireCompletePolicy===!0,requiresCompleteCoverage:n.requireCompleteCoverage===!0,requiresMinimalPolicy:n.requireMinimalPolicy===!0}}}function gs(e,t={}){let n=_e(e,t.scope,{scipEdges:"imports-only",sourceEdges:"imports-and-reexports"}),r=Q(e,{includeIgnored:!1}).filter(o=>!t.scope||o.includes(t.scope)),i=new Set(r);return DR(n,r,e.config.architecture,{isModuleHierarchyFile:o=>dU(e,o),testBoundaryViolations:LR(e,e.config.architecture,o=>PR(e.config.architecture,o),o=>i.has(o))})}function dU(e,t){let n=U(t);return n==="test"||n==="entry"?!0:n!=="barrel"?!1:q(e,t).length===0}function km(e){let t=e.forbiddenEdges.map(r=>`${Nn}forbidden-edge:${encodeURIComponent(r.from)}:${encodeURIComponent(r.to)}`);if(e.policyCoverage.requiresCompletePolicy)for(let r of e.policyCoverage.missingRows)t.push(`${Nn}missing-policy-row:${encodeURIComponent(r)}`);if(e.policyCoverage.requiresCompleteCoverage){for(let r of e.coverage.unmappedFiles)t.push(`${Nn}unmapped-file:${encodeURIComponent(r)}`);for(let r of e.coverage.ambiguousFiles)t.push(`${Nn}ambiguous-file:${encodeURIComponent(r.file)}:${r.boundaries.map(i=>encodeURIComponent(i)).sort().join("|")}`)}if(e.policyCoverage.requiresMinimalPolicy)for(let r of e.staleAllowances)t.push(`${Nn}stale-allowance:${encodeURIComponent(r.from)}:${encodeURIComponent(r.to)}`);for(let r of e.testBoundaryViolations)t.push(`${Nn}test-boundary:${encodeURIComponent(r.testFile)}:${encodeURIComponent(r.importedBoundary)}`);for(let r of e.boundaryLimits)t.push(`${Nn}boundary-limit:${r.kind}:${encodeURIComponent(r.boundary)}`);let n=new Map;for(let r of e.coarseBoundaries)r.violatesPolicy&&n.set(r.boundary,(n.get(r.boundary)??0)+1);for(let[r,i]of n){let o=`${Nn}coarse-boundary:${encodeURIComponent(r)}`;t.push(o);for(let s=2;s<=i;s+=1)t.push(`${o}:component:${s}`)}for(let r of e.cycles)r.violatesPolicy&&t.push(`${Nn}cycle:${r.boundaries.map(i=>encodeURIComponent(i)).sort().join("|")}`);return[...new Set(t)].sort()}function mU(e,t){let n=new Set(t);for(let[r,i]of e){n.add(r);for(let o of i)n.add(o)}return[...n].sort()}function pU(e,t){let n=[...e.fileEdges].sort((r,i)=>r.fromFile.localeCompare(i.fromFile)||r.toFile.localeCompare(i.toFile));return{from:e.from,to:e.to,policyStatus:fU(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 fU(e,t,n){return!e.allowedDependencies||!Object.hasOwn(e.allowedDependencies,t)?"undeclared":e.allowedDependencies[t].includes(n)?"allowed":"forbidden"}function gU(e,t,n){let r=[...e].sort(),i=new Set(r),o=t.filter(a=>i.has(a.from)&&i.has(a.to)),s=Math.min(...o.map(a=>a.fileEdgeCount));return{boundaries:r,internalEdges:o,narrowestEdges:o.filter(a=>a.fileEdgeCount===s),violatesPolicy:n}}function hU(e,t,n=SU,r=!1,i=()=>"directory"){let o=[];for(let[s,a]of t){let c=i(s)==="file"?f=>f:vU,u=[...a].filter(f=>!n(f));if(u.length<2)continue;let l=new Set(u),d=new Map,m=new Map;for(let f of u)m.set(c(f),new Set);for(let f of u)for(let g of e.get(f)??[]){if(!l.has(g))continue;let h=c(f),y=c(g);if(h===y)continue;let S=Wi(h,y),b=d.get(S);b||(b={from:h,to:y,fileEdges:[]},d.set(S,b)),b.fileEdges.push({fromFile:f,toFile:g}),m.get(h).add(y)}let{components:p}=pr(m);for(let f of p){if(f.length<2)continue;let g=new Set(f),h=[...d.values()].filter(S=>g.has(S.from)&&g.has(S.to)).map(S=>({from:S.from,to:S.to,fileEdgeCount:S.fileEdges.length,examples:S.fileEdges.slice(0,5)})).sort((S,b)=>S.from.localeCompare(b.from)||S.to.localeCompare(b.to)),y=Math.min(...h.map(S=>S.fileEdgeCount));o.push({boundary:s,violatesPolicy:r,subUnits:[...f].sort(),internalEdges:h,narrowestEdges:h.filter(S=>S.fileEdgeCount===y)})}}return o.sort((s,a)=>a.subUnits.length-s.subUnits.length||s.boundary.localeCompare(a.boundary))}function yU(e,t){let n=new Set(t.map(s=>Wi(s.from,s.to))),r=e.allowedDependencies??{},i=new Set(e.boundaries.map(s=>s.name)),o=[];for(let[s,a]of Object.entries(r))if(i.has(s))for(let c of a)!i.has(c)||n.has(Wi(s,c))||o.push({from:s,to:c});return o.sort((s,a)=>s.from.localeCompare(a.from)||s.to.localeCompare(a.to))}function bU(e,t,n){let r=[],i=new Map;for(let o of t)i.set(o.from,(i.get(o.from)??0)+1);for(let o of e.boundaries){if(e.maxBoundaryFanOut!==void 0){let a=i.get(o.name)??0;a>e.maxBoundaryFanOut&&r.push({boundary:o.name,kind:"fan-out",observed:a,limit:e.maxBoundaryFanOut})}let s=o.maxFiles??e.maxBoundaryFiles;if(s!==void 0){let a=n.get(o.name)?.size??0;a>s&&r.push({boundary:o.name,kind:"files",observed:a,limit:s})}}return r.sort((o,s)=>o.boundary.localeCompare(s.boundary)||o.kind.localeCompare(s.kind))}function SU(e){let t=U(e);return t==="test"||t==="entry"}function vU(e){let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)}function Wi(e,t){return`${e}\0${t}`}function CU(e,t){return e.from.localeCompare(t.from)||e.to.localeCompare(t.to)}function xU(e,t={}){let{limit:n=20,scope:r,minFanIn:i=2,minFanOut:o=2,scanLimit:s}=t,a=new H(e),c=be(a.productionCallableDefinitions({scope:r,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s),u=t.semantic!==!1,l=Rn(e,c,{limit:500,semantic:u,semanticEvidence:ie});return c.map(m=>RU(e,m,u,l.get(m.symbolId)??[])).filter(m=>m.fanIn>=i&&m.fanOut>=o).sort((m,p)=>p.score-m.score||p.fanIn-m.fanIn).slice(0,n)}function RU(e,t,n,r){let i=[...new Set(r.map(m=>m.file))].sort(),o=[...new Set(r.filter(m=>m.source!=="caller-map-inversion"||m.callEvidence==="scip-chunk").map(m=>m.file))].sort(),s=new Map;for(let m of Ft(e,t,{limit:500,semantic:n,semanticEvidence:ie})){if(m.file===t.relativePath)continue;let p=`${m.symbol}|${m.file}`;s.has(p)||s.set(p,{symbol:m.symbol,shortName:T(m.symbol),file:m.file,evidenceStrength:m.source==="scip-chunk"?"candidate":"exact",evidenceSource:m.source})}let a=[...s.values()].sort((m,p)=>m.file.localeCompare(p.file)||m.symbol.localeCompare(p.symbol)),c=i.length,u=a.length,l=c*u,d=a.filter(m=>m.evidenceStrength==="candidate").map(m=>m.symbol);return{symbol:t.symbol,shortName:T(t.symbol),fanIn:c,fanOut:u,callerFiles:i,candidateCallerFiles:o,externalCallees:a.map(({symbol:m,shortName:p,file:f})=>({symbol:m,shortName:p,file:f})),externalCalleeEvidence:a,candidateExternalCallees:d,inputBasis:"mixed-static-call-or-reference-evidence",score:l,definedIn:t.relativePath,actionTier:"signal",riskKind:"coordination-hotspot",evidenceReasons:[`${c} incoming file(s) reference this symbol`,`${u} distinct cross-file callee symbol(s) are reached from it`,`centrality score is ${l} (fan-in * fan-out)`,`${o.length} incoming file(s) and ${d.length} outgoing target(s) rely on candidate rather than exact call evidence`],recommendation:"Review ownership, API stability, and caller groups before changing this central symbol; do not refactor solely from graph centrality."}}function hs(e,t={}){let{scope:n,minLoc:r=3,scanLimit:i}=t,o=new H(e),s=t.semantic!==!1,a=0,c=N("isolated.candidates",()=>{let C=be(o.productionCallableDefinitions({scope:n,minLoc:r,excludeEntrySurfaces:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:typeof i=="number"&&i>0}),i).filter(R=>!Ki(e,R));return a=C.length,C},()=>({definitions:a})),u=0,l=N("isolated.strict-callees",()=>{let v=o.symbolsWithNonSelfCallees(c,{additive:!1,semantic:!1});return u=v.size,v},()=>({definitions:c.length,symbols:u})),d=c.filter(v=>!l.has(v.symbolId)),m=0,p=N("isolated.scip-callers",()=>{let v=o.crossFileCallerMap(d,{semantic:!1});return m=v.size,v},()=>({definitions:d.length,symbols:m})),f=new Set(p.keys());for(let v of o.frameworkReferencedSymbolIds(d))f.add(v);let g=d.filter(v=>!f.has(v.symbolId));if(s&&g.length>0){for(let v of er(e,g).keys())f.add(v);for(let v of o.symbolsWithNonSelfCallees(g,{additive:!1,semantic:!0}))l.add(v);g=g.filter(v=>!f.has(v.symbolId)).filter(v=>!l.has(v.symbolId))}let h=0,y=N("isolated.source-fallback-callers",()=>{let v=o.sourceFallbackCallerFiles(g,{skipPath:C=>U(C)==="test"});return h=v.size,v},()=>({definitions:g.length,symbols:h}));for(let v of y.keys())f.add(v);let S=g.filter(v=>!f.has(v.symbolId)),b=0,x=N("isolated.additive-callees",()=>{let v=o.symbolsWithNonSelfCallees(S,{additive:!0,semantic:s});return b=v.size,v},()=>({definitions:S.length,symbols:b}));for(let v of x)l.add(v);return S.filter(v=>!l.has(v.symbolId)).sort((v,C)=>ee(C)-ee(v)||v.relativePath.localeCompare(C.relativePath)||v.startLine-C.startLine).map(v=>({symbol:v.symbol,shortName:T(v.symbol),relativePath:v.relativePath,startLine:v.startLine,endLine:v.endLine,loc:ee(v)}))}import{SymbolInformation_Kind as Ye}from"@c4312/scip";var MR=500;function EU(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),r=gh.get(n);if(r!==void 0)return r;for(let[i,o]of fa)if(o.toLowerCase().includes(n))return i;return null}function IU(e,t,n={}){let{scope:r,limit:i=100}=n,o=EU(t);return o===null?[]:LU(e,r).map(a=>({row:a,resolvedKind:kR(a)})).filter(a=>a.resolvedKind===o).slice(0,i).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:T(a.symbol),kind:c,kindName:yo(c),relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function wU(e,t={}){let n=PU(e,t.scope);for(let r of DU(e,t.scope)){let i=kR(r);i===null||i===0||n.set(i,(n.get(i)??0)+1)}return[...n.entries()].sort((r,i)=>i[1]-r[1]||r[0]-i[0]).map(([r,i])=>({kind:r,kindName:yo(r),count:i}))}function LU(e,t){return ye(e,{scope:t}).map(MU)}function PU(e,t){let n=new Map;for(let r of TR(Q(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", "),o=e.all(`SELECT gs.kind AS kind, COUNT(*) AS count
297
- FROM defn_enclosing_ranges der
298
- JOIN global_symbols gs ON der.symbol_id = gs.id
299
- JOIN documents d ON der.document_id = d.id
300
- WHERE gs.kind IS NOT NULL
301
- AND gs.kind != 0
302
- AND gs.symbol NOT LIKE '%#'
303
- AND d.relative_path IN (${i})
304
- GROUP BY gs.kind`,...r);for(let s of o)n.set(s.kind,(n.get(s.kind)??0)+s.count)}return n}function DU(e,t){let n=[];for(let r of TR(Q(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", ");n.push(...e.all(`SELECT gs.symbol,
305
- gs.kind,
306
- gs.documentation,
307
- gs.enclosing_symbol,
308
- d.relative_path,
309
- der.start_line,
310
- der.end_line
311
- FROM defn_enclosing_ranges der
312
- JOIN global_symbols gs ON der.symbol_id = gs.id
313
- JOIN documents d ON der.document_id = d.id
314
- WHERE (gs.kind IS NULL OR gs.kind = 0 OR gs.symbol LIKE '%#')
315
- ${e.symbolNoiseFor("gs")}
316
- AND d.relative_path IN (${i})
317
- ORDER BY d.relative_path, der.start_line, der.end_line, gs.symbol`,...r))}return n}function TR(e){let t=[];for(let n=0;n<e.length;n+=MR)t.push(e.slice(n,n+MR));return t}function MU(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 kR(e){return e.kind!==null&&e.kind!==0?TU(e.kind,e.symbol,e.documentation):kU(e.symbol,e.documentation,e.enclosing_symbol)}function TU(e,t,n){let r=(n??"").toLowerCase();if(kt(t)==="type"){if(r.includes("type "))return Ye.TypeAlias;if(r.includes("interface "))return Ye.Interface;if(r.includes("struct "))return Ye.Struct;if(r.includes("trait "))return Ye.Trait;if(r.includes("class "))return Ye.Class}return e}function kU(e,t,n){let r=Un(e);if("kind"in r)return null;let i=r.descriptors,o=i[i.length-2]??null,s=kt(e),a=(t??"").toLowerCase();return s==="type"?a.includes("type ")?Ye.TypeAlias:a.includes("interface ")?Ye.Interface:a.includes("struct ")?Ye.Struct:a.includes("trait ")?Ye.Trait:a.includes("class ")?Ye.Class:Ye.Class:s==="method"?o?.suffix==="type"?Ye.Method:Ye.Function:s==="namespace"?Ye.Module:s!=="term"?null:a.includes("async def ")||a.includes("def ")?Ye.Function:(n?kt(n):o?.suffix??null)==="type"?Ye.Field:Ye.Variable}function AU(e,t={}){let{limit:n=10,scope:r,minDepth:i=3,edgeBasis:o="symbol-references"}=t,s=_e(e,r,o==="imports"?{scipEdges:"imports-only",sourceEdges:"imports-only"}:void 0),{components:a,componentOf:c}=pr(s),u=new Map;for(let h=0;h<a.length;h++)u.set(h,new Set);for(let[h,y]of s){let S=c.get(h);for(let b of y){let x=c.get(b);x!==S&&u.get(S).add(x)}}let l=new Array(a.length),d=new Array(a.length);for(let h=0;h<a.length;h++){let y=[],S=0;for(let b of[...u.get(h)].sort((x,v)=>x-v)){let x=d[b];(x>S||x===S&&FU(l[b],y,a)<0)&&(S=x,y=l[b])}l[h]=[h,...y],d[h]=1+S}function m(h){return l[h]}let p=a.map(h=>[...h].sort()),f=new Set,g=[];for(let h=0;h<a.length;h++){let S=m(h).map(v=>p[v]),b=S.map(v=>v[0]);if(S.length<i)continue;let x=b.join(" ");f.has(x)||(f.add(x),g.push(NU(b,S,o)))}return g.sort((h,y)=>y.depth-h.depth||h.chain.join("\0").localeCompare(y.chain.join("\0"))),_U(g).slice(0,n)}function FU(e,t,n){if(t.length===0)return-1;let r=e.map(o=>[...n[o]].sort()[0]??"").join("\0"),i=t.map(o=>[...n[o]].sort()[0]??"").join("\0");return r.localeCompare(i)}function NU(e,t,n){let r=t.reduce((o,s)=>o+s.length,0),i=t.filter(o=>o.length>1).length;return{chain:e,components:t,depth:t.length,fileCount:r,edgeBasis:n,actionTier:"signal",chainKind:"transitive-dependency-depth",evidenceReasons:[`${t.length} condensed dependency component(s) form the representative transitive path`,`${r} file(s) are represented; ${i} component(s) contain a dependency cycle`,`edge basis: ${n==="imports"?"resolved file imports":"cross-file symbol references plus resolved source imports"}`,"cycles count once toward depth and retain their full membership separately"],recommendation:"Review whether the chain crosses ownership or layer boundaries; shorten it only when the dependency direction is accidental."}}function _U(e){let t=[];for(let n of e)t.some(r=>OU(n.chain,r.chain))||t.push(n);return t}function OU(e,t){if(e.length>=t.length)return!1;let n=t.length-e.length;for(let r=0;r<e.length;r++)if(e[r]!==t[n+r])return!1;return!0}function BU(e,t){let n=re(e,t);if(!n)return[];let r=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
318
- WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:T(r.symbol),depth:0}],o=r.enclosing_symbol,s=1,a=new Set([r.symbol]);for(;o&&!a.has(o)&&s<20;){a.add(o);let d=e.get("SELECT symbol, enclosing_symbol FROM global_symbols WHERE symbol = ?",o);if(!d)break;i.push({symbol:d.symbol,shortName:T(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(i.length>1)return i;let c=Un(r.symbol);if("kind"in c)return i;let u=c.descriptors;if(u.length<=1)return i;let l=[i[0]];for(let d=u.length-2,m=1;d>=0;d--,m++){let f=u.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(":");l.push({symbol:f,shortName:f,depth:m})}return l}function $U(e,t={}){let r=new H(e).productionCallableDefinitions({scope:t.scope,requireCallableSymbol:!0,includeSuppressed:!0}),i=_R(e,r),o=t.search?.trim().toLocaleLowerCase();return r.map(s=>OR(e,s,i.get(s.symbolId)??[])).filter(s=>s!==null).map(s=>s.result).filter(s=>!o||UU(s).includes(o)).sort(qU)}function jU(e,t,n={}){let r=Ze(e,t);if(!r.match)return{kind:"missing",query:t};if(r.total>1)return{kind:"ambiguous",query:t,total:r.total,candidates:[{symbol:r.match.symbol,shortName:T(r.match.symbol),relativePath:r.match.relativePath,startLine:r.match.startLine},...r.candidates]};let i=new H(e),o=i.definitionsForFile(r.match.relativePath).find(p=>p.symbol===r.match.symbol);if(!o?.isFunctionLike)return{kind:"not-entry",query:t,symbol:r.match.symbol,shortName:T(r.match.symbol),file:r.match.relativePath,reason:"The resolved symbol is not a callable definition."};let s=_R(e,[o]),a=OR(e,o,s.get(o.symbolId)??[]);if(!a)return{kind:"not-entry",query:t,symbol:o.symbol,shortName:T(o.symbol),file:o.relativePath,reason:"The callable is neither an external root nor an uncalled callable on a detected entry surface."};let c=GU(e,i,o),u=new Set(n.expand??[]),l=VU(c,u),d=new Set(l.regions.filter(p=>p.expanded).map(p=>p.id)),m=[...u].filter(p=>!d.has(p)).sort();return{kind:"matched",query:t,entry:a.result,regions:l.regions,regionEdges:l.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:l.regions.length,regionEdgeCount:l.regionEdges.length,externalCallCount:c.externalCalls.length}}}function _R(e,t){let n=t.filter(r=>BR(e,r.relativePath)||Ni(e,r.symbol,r.relativePath).length>0);return Rn(e,n,{semantic:!1,semanticEvidence:ie})}function OR(e,t,n){let r=HU(e,t),i=r.length>0,o=BR(e,t.relativePath)&&n.length===0;if(!i&&!o)return null;let s=[...r];return o&&s.push("entry-surface-without-indexed-caller"),{definition:t,result:{symbol:t.symbol,shortName:T(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,documentation:t.documentation,confidence:i?"root":"candidate",evidence:s,indexedCallerCount:n.length}}}function BR(e,t){return ze(e,t)||/(?:^|\/)entry\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(t)}function HU(e,t){let n=Ni(e,t.symbol,t.relativePath),r=[];return AR(n,["package-surface-file","transitive-package-surface"])&&ht(e,t)&&r.push("package-public-export"),n.includes("rust-public-library")&&r.push("rust-public-library"),n.includes("framework-entrypoint")&&r.push("framework-dispatched-export"),AR(n,["configured-file","configured-path-prefix","configured-qualified-var","configured-symbol-pattern"])&&r.push("configured-entry-root"),r}function AR(e,t){return t.some(n=>e.includes(n))}function UU(e){return[e.symbol,e.shortName,e.file,e.documentation??"",...e.evidence].join(`
319
- `).toLocaleLowerCase()}function qU(e,t){return FR(e.confidence)-FR(t.confidence)||e.file.localeCompare(t.file)||e.startLine-t.startLine||e.symbol.localeCompare(t.symbol)}function FR(e){return e==="root"?0:1}function GU(e,t,n){let r=new Map([[n.symbol,0]]),i=new Map,o=new Map([[n.symbol,n]]),s=new Map,a=new Map,c=[n];for(;c.length>0;){let u=t.calleeMap(c,{additive:!1,semantic:!1}),l=[];for(let d of c){let m=r.get(d.symbol)??0;i.set(d.symbol,NR(d,m));for(let p of u.get(d.symbolId)??[]){let f=zU(t,p,o);if(!f){let S=WU(d,p);a.set(XU(S),S);continue}let g=m+1,h=r.get(f.symbol);(h===void 0||g<h)&&r.set(f.symbol,g),i.set(f.symbol,NR(f,Math.min(g,h??g)));let y=KU(d,f,p);s.set(JU(y),y),h===void 0&&l.push(f)}}c=l}return{symbols:[...i.values()].sort(QU),edges:[...s.values()].sort(ZU),externalCalls:[...a.values()].sort(eq)}}function zU(e,t,n){let r=n.get(t.symbol);if(r)return r;let i=e.definitionsForFile(t.file).find(o=>o.symbol===t.symbol)??null;return i&&n.set(i.symbol,i),i}function NR(e,t){return{symbol:e.symbol,shortName:T(e.symbol),file:e.relativePath,depth:t}}function KU(e,t,n){return{fromSymbol:e.symbol,fromShortName:T(e.symbol),fromFile:e.relativePath,toSymbol:t.symbol,toShortName:T(t.symbol),toFile:t.relativePath,source:n.source,evidenceStrength:n.source==="scip-chunk"?"candidate":"exact"}}function WU(e,t){return{fromSymbol:e.symbol,fromShortName:T(e.symbol),fromFile:e.relativePath,toSymbol:t.symbol,toShortName:T(t.symbol),reportedFile:t.file,source:t.source,evidenceStrength:t.source==="scip-chunk"?"candidate":"exact"}}function VU(e,t){let n=He(e.symbols,u=>u.file),r=He(e.edges.filter(u=>u.fromFile===u.toFile),u=>u.fromFile),i=He(e.externalCalls,u=>u.fromFile),o=YU(e.edges.filter(u=>u.fromFile!==u.toFile)),s=He(o,u=>u.toRegionId),a=He(o,u=>u.fromRegionId);return{regions:[...n.entries()].map(([u,l])=>{let d=Am(u),m=t.has(d),p=r.get(u)??[],f=i.get(u)??[];return{id:d,file:u,minDepth:Math.min(...l.map(g=>g.depth)),symbolCount:l.length,internalEdgeCount:p.length,externalCallCount:f.length,incomingRegionIds:ys((s.get(d)??[]).map(g=>g.fromRegionId)),outgoingRegionIds:ys((a.get(d)??[]).map(g=>g.toRegionId)),expanded:m,symbols:m?l:[],internalEdges:m?p:[],externalCalls:m?f:[]}}).sort((u,l)=>u.minDepth-l.minDepth||u.file.localeCompare(l.file)),regionEdges:o}}function YU(e){let t=new Map;for(let n of e){let r=`${n.fromFile}\0${n.toFile}`,i=t.get(r)??[];i.push(n),t.set(r,i)}return[...t.values()].map(n=>{let r=n[0];return{fromRegionId:Am(r.fromFile),fromFile:r.fromFile,toRegionId:Am(r.toFile),toFile:r.toFile,callCount:n.length,exactCallCount:n.filter(i=>i.evidenceStrength==="exact").length,candidateCallCount:n.filter(i=>i.evidenceStrength==="candidate").length,fromSymbols:ys(n.map(i=>i.fromShortName)),toSymbols:ys(n.map(i=>i.toShortName)),evidence:ys(n.map(i=>i.source))}}).sort((n,r)=>n.fromFile.localeCompare(r.fromFile)||n.toFile.localeCompare(r.toFile))}function Am(e){return`file:${e}`}function ys(e){return[...new Set(e)].sort()}function JU(e){return`${e.fromSymbol}\0${e.toSymbol}`}function XU(e){return`${e.fromSymbol}\0${e.toSymbol}`}function QU(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)||e.symbol.localeCompare(t.symbol)}function ZU(e,t){return e.fromFile.localeCompare(t.fromFile)||e.fromSymbol.localeCompare(t.fromSymbol)||e.toSymbol.localeCompare(t.toSymbol)}function eq(e,t){return e.fromFile.localeCompare(t.fromFile)||e.fromSymbol.localeCompare(t.fromSymbol)||e.toSymbol.localeCompare(t.toSymbol)}function Ot(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function Je(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function gr(e,t){if(e.size===0&&t.size===0)return 0;let n=0;for(let i of e)t.has(i)&&(n+=1);let r=e.size+t.size-n;return r===0?0:n/r}function $R(e,t){if(e.size===0)return 0;let n=0;for(let r of e)t.has(r)&&(n+=1);return n/e.size}function Fm(e,t){if(t<=0)return new Map;let n=new Map;for(let[r,i]of e)i>0&&n.set(r,Math.log(t/i));return n}function Vi(e){let t=[...e.values()].sort((r,i)=>r-i);if(t.length===0)return 0;let n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function Yi(e,t){let n=0;for(let r of e){let i=t.get(r)??0;n+=i*i}return Math.sqrt(n)}function jR(e,t,n,r={}){let i=0,o=0,s=0,a=r.medianIdf??Vi(n),c=[],u=[];for(let m of e){let p=n.get(m)??0;o+=p*p,t.has(m)&&(i+=p*p,p>=a?c.push(m):u.push(m))}if(c.length===0&&u.length===0)return{similarity:0,significantShared:[],trivialShared:[]};for(let m of t){let p=n.get(m)??0;s+=p*p}let l=Math.sqrt(o)*Math.sqrt(s),d=l>0?i/l:0;return c.sort((m,p)=>(n.get(p)??0)-(n.get(m)??0)),{similarity:d,significantShared:c,trivialShared:u}}function HR(e,t,n,r){let i=0,o=r.medianIdf??Vi(n),s=[],a=[];for(let l of e){if(!t.has(l))continue;let d=n.get(l)??0;i+=d*d,d>=o?s.push(l):a.push(l)}if(s.length===0&&a.length===0)return{similarity:0,significantShared:[],trivialShared:[]};let c=r.magnitudeA*r.magnitudeB,u=c>0?i/c:0;return s.sort((l,d)=>(n.get(d)??0)-(n.get(l)??0)),{similarity:u,significantShared:s,trivialShared:a}}function bs(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=lq(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!Re(o.symbol))return[];if(o.callees.size===0)return UR(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"});let s=nq(e,o,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,i):UR(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"})}function Bm(e,t,n,r={}){let i=re(e,t),o=re(e,n);if(!i||!o)return null;let s=bs(e,i.symbol,{minSimilarity:0,limit:Number.POSITIVE_INFINITY,semantic:r.semantic,scanLimit:r.scanLimit}).find(u=>u.symbolB===o.symbol||u.symbolA===o.symbol);if(!s)return null;let a=i.endLine-i.startLine+1,c=o.endLine-o.startLine+1;return{symbolA:{symbol:i.symbol,shortName:T(i.symbol),file:i.relativePath,loc:a},symbolB:{symbol:o.symbol,shortName:T(o.symbol),file:o.relativePath,loc:c},similarity:s.similarity,similarityBasis:s.similarityBasis??"callees",sharedEvidence:s.sharedCallees,uniqueToA:s.uniqueToA,uniqueToB:s.uniqueToB,evidenceClass:s.evidenceClass,actionTier:s.actionTier,recommendation:s.recommendation,consolidationStrategy:tq(s)}}function tq(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 nq(e,t,n,r){let i=Ji(e).calleeIndex({minCallees:3,scanLimit:r.scanLimit,semantic:r.semantic}),o=yq(t,i.corpus),s=fq(o,i),a=rq(o,i),c=Vi(a),u=Yi(o.callees,a),l=[];for(let d of s){if(d.callees.size<3)continue;let m=Yi(d.callees,a),p=KR(o,d,a,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0,medianIdf:c,magnitudeA:u,magnitudeB:m});p&&l.push(p)}return l.sort((d,m)=>m.similarity-d.similarity),l}function rq(e,t){let n=new Map(t.docFreq);for(let r of e.callees)n.set(r,(n.get(r)??0)+1);return Fm(n,t.corpus.length+1)}function KR(e,t,n,r){let i=oq(e,t,n,r);if(!sq(i,r))return null;let{similarity:o,significantShared:s,trivialShared:a}=i,c=s.length>0?s:a,u=XR(c,"callees");return{symbolA:e.symbol,shortNameA:T(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:T(t.symbol),fileB:t.file,similarity:o,similarityBasis:"callees",sharedCallees:c.map(T),uniqueToA:[...Je(e.callees,t.callees)].map(T),uniqueToB:[...Je(t.callees,e.callees)].map(T),...u}}function iq(e,t,n,r){let i=r.magnitudeA??Yi(e.callees,n),o=r.magnitudeB??Yi(t.callees,n),s=0,a=0,c=0,u=r.medianIdf??Vi(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>=u&&(a+=1)}if(c===0)return!1;let l=i*o;return(l>0?s/l:0)<r.minSimilarity?!1:a>=r.requireSignificantShared||c>=r.requireSharedCount}function oq(e,t,n,r){return r.magnitudeA===void 0||r.magnitudeB===void 0?jR(e.callees,t.callees,n,{medianIdf:r.medianIdf}):HR(e.callees,t.callees,n,{medianIdf:r.medianIdf,magnitudeA:r.magnitudeA,magnitudeB:r.magnitudeB})}function sq(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 Ss(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=t.semantic!==!1,u=xe(),l=0,d=0,m=0,p=0,f=0,g=0,h=0;return N("similar.all",()=>{let S=Ji(e).calleeIndex({minCallees:o,scope:i,scanLimit:a,semantic:c}),b=S.corpus;l=b.length;let x=t.focusFiles,v=[],C=0;return N("similar.all.pair-scan",()=>{for(let R=0;R<b.length;R+=1){let E=b[R],w=x?.has(E.file)??!1,I=S.weightedMagnitudes[R],k=new Set;for(let D of E.callees){let F=S.candidateIndexesByCallee.get(D);if(F)for(let P of F)P<=R||x&&!w&&!x.has(b[P].file)||k.add(P)}u&&(m+=k.size,k.size>0&&(d+=1));for(let D of k){let F=b[D];if(s&&E.file===F.file){u&&(f+=1);continue}if(WR(E,F)){u&&(g+=1);continue}u&&(p+=1);let P=KR(E,F,S.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:S.medianIdf,magnitudeA:I,magnitudeB:S.weightedMagnitudes[D]});P&&(aq(v,P,r,C),u&&(h+=1),C+=1)}}},()=>({corpusSize:l,candidateSets:d,candidatePairs:m,comparedPairs:p,crossFileSkips:f,signatureSkips:g,insertedResults:h,topResults:v.length})),N("similar.all.sort-project",()=>(v.sort((R,E)=>E.result.similarity-R.result.similarity||R.order-E.order),v.map(R=>R.result)),()=>({topResults:v.length}))},()=>({minSimilarity:n,limit:r,scope:i,minCallees:o,crossFileOnly:s,scanLimit:a,semantic:c,corpusSize:l,candidateSets:d,candidatePairs:m,comparedPairs:p,crossFileSkips:f,signatureSkips:g,insertedResults:h}))}function $m(e,t={}){let{minSimilarity:n=.5,scope:r,minCallees:i=4,crossFileOnly:o=!1,scanLimit:s}=t,a=t.semantic!==!1,c=xe(),u=0,l=0,d=0,m=0,p=0,f=0,g=0;return N("similar.all-count",()=>{let y=Ji(e).calleeIndex({minCallees:i,scope:r,scanLimit:s,semantic:a}),S=y.corpus;u=S.length;let b=t.focusFiles;return N("similar.all-count.pair-scan",()=>{for(let x=0;x<S.length;x+=1){let v=S[x],C=b?.has(v.file)??!1,R=y.weightedMagnitudes[x],E=new Set;for(let w of v.callees){let I=y.candidateIndexesByCallee.get(w);if(I)for(let k of I)k<=x||b&&!C&&!b.has(S[k].file)||E.add(k)}c&&(d+=E.size,E.size>0&&(l+=1));for(let w of E){let I=S[w];if(o&&v.file===I.file){c&&(p+=1);continue}if(WR(v,I)){c&&(f+=1);continue}c&&(m+=1),iq(v,I,y.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:y.medianIdf,magnitudeA:R,magnitudeB:y.weightedMagnitudes[w]})&&(g+=1)}}},()=>({corpusSize:u,candidateSets:l,candidatePairs:d,comparedPairs:m,crossFileSkips:p,signatureSkips:f,insertedResults:g})),g},()=>({minSimilarity:n,scope:r,minCallees:i,crossFileOnly:o,scanLimit:s,semantic:a,corpusSize:u,candidateSets:l,candidatePairs:d,comparedPairs:m,crossFileSkips:p,signatureSkips:f,insertedResults:g}))}function WR(e,t){if(e.paramCount<0||t.paramCount<0)return!1;let n=Math.abs(e.paramCount-t.paramCount),r=Math.max(2,Math.ceil(Math.max(e.paramCount,t.paramCount)*.5));return n>r}var VR=ft({kind:"source-fingerprints",invalidation:Ne("source-fingerprints"),serialize:Oq,deserialize:_q});function aq(e,t,n,r){if(n<=0)return;if(e.length<n){e.push({result:t,order:r});return}let i=0;for(let s=1;s<e.length;s+=1){let a=e[s],c=e[i];(a.result.similarity<c.result.similarity||a.result.similarity===c.result.similarity&&a.order>c.order)&&(i=s)}let o=e[i];t.similarity<=o.result.similarity||(e[i]={result:t,order:r})}var cq=["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 lq(e,t,n){let r=re(e,t);if(!r||!Re(r.symbol))return null;let i=new H(e),o=Ft(e,r,{semantic:n.semantic,semanticEvidence:ie});return{symbol:r.symbol,file:r.relativePath,callees:Kc(o.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}var uq=te("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),dq=te("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function YR(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:o}=t,s=t.semantic!==!1,a=uq.get(e,()=>new Map),c=`${n}|${r??""}|${o??""}|${s}`,u=!0,l=0,d=0;return N("similar.callee-fingerprints.resolve",()=>{let m=a.get(c);if(u=m!==void 0,m||(m=gq(e,{minCallees:n,scope:r,scanLimit:o,semantic:s}),a.set(c,m)),l=m.length,i===void 0)return m;let p=m.filter(f=>f.symbol!==i);return d=m.length-p.length,p},()=>({minCallees:n,scope:r,scanLimit:o,semantic:s,cacheHit:u,corpusSize:l,excludeSymbol:i!==void 0,excludedSymbols:d}))}function mq(e,t){let{minCallees:n,scope:r,scanLimit:i}=t,o=t.semantic!==!1,s=dq.get(e,()=>new Map),a=`${n}|${r??""}|${i??""}|${o}`,c=!0,u=0,l=0,d=0;return N("similar.callee-index.resolve",()=>{let m=s.get(a);return c=m!==void 0,m||(m=pq(YR(e,{minCallees:n,scope:r,scanLimit:i,semantic:o})),s.set(a,m)),u=m.corpus.length,l=m.docFreq.size,d=m.candidateIndexesByCallee.size,m},()=>({minCallees:n,scope:r,scanLimit:i,semantic:o,cacheHit:c,corpusSize:u,indexedCallees:l,candidateBuckets:d}))}function Ji(e){return{calleeCorpus:t=>YR(e,t),calleeIndex:t=>mq(e,t),sourceCorpus:(t={})=>nE(e,t),sourceIndex:(t={})=>zR(e,t),sourceCandidates:(t,n)=>(n.candidateMode??"full")==="target-pruned"?Pq(e,t,{minSimilarity:n.minSimilarity,scanLimit:n.scanLimit}):Lq(t,zR(e,{scanLimit:n.scanLimit}))}}function pq(e){let t=xe(),n=0,r=N("similar.callee-index.doc-frequency",()=>{let m=new Map;for(let p of e)for(let f of p.callees)m.set(f,(m.get(f)??0)+1);return n=m.size,m},()=>({corpusSize:e.length,uniqueCallees:n})),i=Math.max(8,Math.ceil(Math.sqrt(e.length))),o=N("similar.callee-index.idf-weights",()=>Fm(r,e.length),()=>({corpusSize:e.length,uniqueCallees:r.size})),s=N("similar.callee-index.weighted-magnitudes",()=>e.map(m=>Yi(m.callees,o)),()=>({corpusSize:e.length})),a=0,c=0,u=0,l=N("similar.callee-index.candidate-buckets",()=>{let m=new Map;for(let p=0;p<e.length;p+=1){let f=e[p];for(let g of f.callees){if((r.get(g)??0)>i){t&&(c+=1);continue}let h=m.get(g);h||(h=[],m.set(g,h)),h.push(p),t&&(a+=1)}}return t&&(u=m.size),m},()=>({corpusSize:e.length,buckets:u,candidateRefs:a,ubiquitousSkips:c,ubiquityThreshold:i})),d=N("similar.callee-index.median-idf",()=>Vi(o),()=>({uniqueCallees:o.size}));return{corpus:e,candidateIndexesByCallee:l,docFreq:r,idfWeights:o,weightedMagnitudes:s,medianIdf:d,ubiquityThreshold:i}}function fq(e,t){let n=new Map;for(let r of e.callees)for(let i of t.candidateIndexesByCallee.get(r)??[]){let o=t.corpus[i];o.symbol!==e.symbol&&n.set(o.symbol,o)}return n.size>0?[...n.values()]:t.corpus.filter(r=>r.symbol!==e.symbol)}function gq(e,t){let{minCallees:n,scope:r,scanLimit:i,semantic:o}=t,s=xe(),a=new H(e),c=0,u=N("similar.callee-fingerprints.candidates",()=>{let g=be(a.productionCallableDefinitions({scope:r,minLoc:5,sortByLocDesc:typeof i=="number"&&i>0}),i);return c=g.length,g},()=>({scope:r,scanLimit:i,candidateCount:c})),l=0,d=N("similar.callee-fingerprints.callee-map",()=>{let g=a.calleeMap(u,{semantic:o});if(s)for(let h of g.values())l+=h.length;return g},()=>({candidateCount:c,semantic:o,calleeEdges:l})),m=0,p=0,f=0;return N("similar.callee-fingerprints.shape",()=>{let g=u.map(S=>({symbol:S.symbol,file:S.relativePath,callees:Kc((d.get(S.symbolId)??[]).filter(b=>b.kind!=="jsx-render").map(b=>b.symbol)),paramCount:a.callableSignature(S)?.paramCount??-1})),h=hq(g);s&&(f=h.filter((S,b)=>S.callees.size!==g[b].callees.size).length);let y=h.filter(S=>S.callees.size>=n);return m=y.length,s&&(p=y.reduce((S,b)=>S+b.callees.size,0)),y},()=>({candidateCount:c,fingerprintCount:m,retainedCalleeCount:p,minCallees:n,siblingSaturatedFingerprints:f}))}var JR=5;function hq(e){let t=new Map;for(let n of e){let r=t.get(n.file);r||(r=new Map,t.set(n.file,r));for(let i of n.callees)r.set(i,(r.get(i)??0)+1)}return e.map(n=>{let r=t.get(n.file);if(!r)return n;let i=[...n.callees].filter(s=>(r.get(s)??0)>=JR);if(i.length===0)return n;let o=new Set(n.callees);for(let s of i)o.delete(s);return{...n,callees:o}})}function yq(e,t){let n=new Map;for(let o of t)if(!(o.file!==e.file||o.symbol===e.symbol))for(let s of o.callees)n.set(s,(n.get(s)??0)+1);let r=[...e.callees].filter(o=>(n.get(o)??0)+1>=JR);if(r.length===0)return e;let i=new Set(e.callees);for(let o of r)i.delete(o);return{...e,callees:i}}function Kc(e){return new Set([...e].filter(t=>!bq(t)))}function bq(e){return cq.some(t=>e.includes(t))}function UR(e,t,n){let r=xq(e,t);if(!r||r.tokens.size<3)return[];let i=n.minSimilarity>=.5?n.minSimilarity:.3,o=[],s=n.candidateMode??"full",a=0,c=0,u=0,l=0;return N("similar.source-shape",()=>{let m=Ji(e).sourceCandidates(r,{minSimilarity:i,scanLimit:n.scanLimit,candidateMode:s});a=m.length;for(let p of m){if(p.symbol===r.symbol||p.tokens.size<3)continue;c+=1;let f=Ot(r.tokens,p.tokens);if(f.size<2){u+=1;continue}let g=new Set([...r.tokens,...p.tokens]),h=g.size>0?f.size/g.size:0;if(h<i){l+=1;continue}o.push({symbolA:r.symbol,shortNameA:T(r.symbol),fileA:r.file,symbolB:p.symbol,shortNameB:T(p.symbol),fileB:p.file,similarity:h,similarityBasis:"source-tokens",sharedCallees:[...f].sort(),uniqueToA:[...Je(r.tokens,p.tokens)].sort(),uniqueToB:[...Je(p.tokens,r.tokens)].sort(),...XR([...f],"source-tokens")})}return o.sort((p,f)=>f.similarity-p.similarity||p.shortNameB.localeCompare(f.shortNameB)),o.slice(0,n.limit)},()=>({symbol:r.symbol,file:r.file,targetTokens:r.tokens.size,candidateMode:s,candidates:a,comparedPairs:c,sharedSkips:u,similaritySkips:l,results:o.length}))}function XR(e,t){let n=e.flatMap(_m),r=e.flatMap(h=>qR(h,t)),i=Nm(n,QR),o=Nm(n,ZR),s=Nm(r,Om),a=[...new Set(r.filter(GR))],c=e.filter(h=>{let y=qR(h,t);return y.some(S=>Om.has(S))&&y.some(GR)}).length,u=[];i.length>0&&u.push(`access/query scaffolding: ${i.slice(0,5).join(", ")}`),o.length>0&&u.push(`framework/generic scaffolding: ${o.slice(0,5).join(", ")}`),s.length>0&&u.push(`domain behavior verbs: ${s.slice(0,5).join(", ")}`),s.length>0&&a.length>0&&u.push(`domain-specific terms: ${a.slice(0,5).join(", ")}`);let l=t==="source-tokens"&&n.length>0&&n.every(h=>eE.has(h));l&&u.push("shared source tokens are generic scaffolding");let d=s.length>0&&a.length>0,m=i.length+o.length>0,p=t==="callees"&&d&&e.length>=4&&a.length>=4&&c>=2,f=p?"domain-behavior":d?m?"mixed":"domain-behavior":i.length>0?"access-query-scaffolding":o.length>0||l?"framework-scaffolding":"structural-overlap";f==="structural-overlap"&&e.length>0&&u.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:u,recommendation:Sq(f,g)}}function Sq(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 Nm(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function _m(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function qR(e,t){if(t==="source-tokens")return _m(e);let n=G(e);return _m(n.length>0?n:vq(e))}function vq(e){return e.replace(/[()`]/g," ").replace(/\.[a-z][a-z0-9]+(?=\s|$)/gi," ").split(/[:/\\\s]+/).map(r=>r.trim()).filter(r=>/[A-Za-z]/.test(r)).at(-1)?.replace(/\.$/,"")??e}function GR(e){return e.length>3&&!Om.has(e)&&!QR.has(e)&&!ZR.has(e)&&!eE.has(e)&&!Cq.has(e)}var Om=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),QR=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),ZR=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"]),eE=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),Cq=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 xq(e,t){let n=re(e,t);if(!n||!Re(n.symbol))return null;let r=Rq(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function Rq(e,t){let n=G(t.symbol),r=Aq(e,t.relativePath,t.startLine,t.endLine,n),i=oE(r,n);return i.size>0?i:null}var Eq=te("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),Iq=te("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function tE(e){return`${e.scanLimit??""}`}function nE(e,t={}){let n=Eq.get(e,()=>new Map),r=tE(t),i=n.get(r);return i||(i=kq(e,t),n.set(r,i)),i}function zR(e,t={}){let n=Iq.get(e,()=>new Map),r=tE(t),i=n.get(r);return i||(i=wq(nE(e,t)),n.set(r,i)),i}function wq(e){let t=new Map;for(let i of e)for(let o of i.tokens)t.set(o,(t.get(o)??0)+1);let n=Math.max(8,Math.ceil(Math.sqrt(e.length))),r=new Map;for(let i of e)for(let o of i.tokens){if((t.get(o)??0)>n)continue;let s=r.get(o);s||(s=[],r.set(o,s)),s.push(i)}return{corpus:e,candidateByToken:r,docFreq:t,ubiquityThreshold:n}}function Lq(e,t){let n=new Map;for(let r of e.tokens)for(let i of t.candidateByToken.get(r)??[])i.symbol!==e.symbol&&n.set(i.symbol,i);return n.size>0?[...n.values()]:t.corpus.filter(r=>r.symbol!==e.symbol)}function Pq(e,t,n){let r=xe(),i=new H(e),o=Dq(t.tokens.size,n.minSimilarity),s=0,a=0,c=0,u=N("similar.source-shape.target-files",()=>{let f=[...t.tokens],g=[];for(let h of Q(e,{includeIgnored:!1})){s+=1;let y=V(e,h);y&&(a+=1,Mq(y,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})),l=0,d=N("similar.source-shape.target-definitions",()=>{let f=be(i.productionCallableDefinitions({files:u,sortByLocDesc:typeof n.scanLimit=="number"&&n.scanLimit>0}),n.scanLimit);return l=f.length,f},()=>({symbol:t.symbol,candidateFiles:c,scanLimit:n.scanLimit,definitionCount:l})),m=0;return N("similar.source-shape.target-fingerprints",()=>{let f=rE(e,d);return r&&(m=f.length),f},()=>({symbol:t.symbol,definitionCount:l,fingerprintCount:m})).filter(f=>f.symbol!==t.symbol)}function Dq(e,t){return Math.max(2,Math.ceil(e*t))}function Mq(e,t,n){if(t.length<n)return!1;let r=e.toLowerCase(),i=0;for(let o of t)if(Tq(r,o)&&(i+=1,i>=n))return!0;return!1}function Tq(e,t){return t==="num"?/\b\d+\b/.test(e):e.includes(t)}function kq(e,t={}){let n=new H(e),{scanLimit:r}=t,i=be(n.productionCallableDefinitions({sortByLocDesc:typeof r=="number"&&r>0}),r);return rE(e,i)}function rE(e,t){let n=new Map;for(let i of t){let o=n.get(i.relativePath)??[];o.push(i),n.set(i.relativePath,o)}let r=new Map;for(let[i,o]of n){let s=V(e,i);if(!s)continue;let a=Pt(e,i,s),c=Nq(e,i,a),u=!1,l=null;for(let d of o){let m=Fq(d),p=c.get(m),f=p?new Set(p.tokens):null;f||(l??=K(e,i),f=oE(iE(l,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()}),u=!0),f.size>0&&r.set(d.symbol,{symbol:d.symbol,file:d.relativePath,tokens:f})}u&&Bq(e,i,a,c)}return t.map(i=>r.get(i.symbol)).filter(i=>!!i)}function Aq(e,t,n,r,i){let o=K(e,t);return o.length===0?"":iE(o,n,r,i)}function iE(e,t,n,r){if(n>=t&&n-t<=12)return e.slice(t,n+1).join(`
320
- `);let i=[new RegExp(`\\bdef\\s+${Ie(r)}\\b`),new RegExp(`\\bfun\\s+${Ie(r)}\\b`),new RegExp(`\\bfn\\s+${Ie(r)}\\b`),new RegExp(`\\bfunction\\s+${Ie(r)}\\b`),new RegExp(`\\b${Ie(r)}\\s*\\(`)],o=e.findIndex(s=>i.some(a=>a.test(s)));if(o>=0){let s=o;for(let a=o+1;a<e.length&&a<=o+8;a++){let c=e[a]??"";if(a>o&&jq(c)||(s=a,c.trim()===""&&a>o+1))break}return e.slice(o,s+1).join(`
321
- `)}return e.slice(t,Math.min(e.length,t+8)).join(`
322
- `)}function Fq(e){return`${e.symbol}\0${e.startLine}\0${e.endLine}\0${e.leaf}`}function Nq(e,t,n){return VR.read(e,t,n)??new Map}function _q(e){try{let t=JSON.parse(e);if(!Array.isArray(t.entries))return null;let n=new Map;for(let r of t.entries){if(!r||typeof r.key!="string"||typeof r.symbol!="string"||typeof r.startLine!="number"||typeof r.endLine!="number"||typeof r.leaf!="string"||!Array.isArray(r.tokens)||!r.tokens.every(i=>typeof i=="string"))return null;n.set(r.key,r)}return n}catch{return null}}function Oq(e){let t={entries:[...e.values()].sort((n,r)=>n.key.localeCompare(r.key))};return JSON.stringify(t)}function Bq(e,t,n,r){VR.write(e,t,n,new Map(r))}function oE(e,t){if(!e)return new Set;let n=new Set(["public","private","protected","final","static","class","def","fun","fn","function","return","string","bool","boolean","void","unit","self","this","new","const","let","var","end","pub"]),r=$q(t),o=e.replace(/["'`]/g," ").replace(/\b\d+\b/g," NUM ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[^A-Za-z0-9_]+/g," ").replace(/_/g," ").toLowerCase().split(/\s+/).map(s=>s.trim()).filter(s=>s.length>1).filter(s=>!n.has(s)).filter(s=>!r.has(s));return new Set(o)}function $q(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 jq(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((r,i)=>{let o=new Set;for(let s of t(r)){if(o.has(s))continue;o.add(s);let a=n.get(s);a?a.push(i):n.set(s,[i])}}),{candidatesFor:(r,i)=>{let o=new Set;for(let s of t(r)){let a=n.get(s);if(a)for(let c of a)c!==i&&o.add(c)}return[...o].sort((s,a)=>s-a)}}}function dn(e){let t=sE(e.profile?.name),n=()=>{let r=[];t=sE(e.profile?.name,e);let i=(s,a)=>{let c=e.profiles[s],u=e.profiles[a];t.candidatePairs+=1,t.comparedPairs+=1;let l=e.compare(c,u);l&&r.push(l)};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 Hq(e,s)){let u=e.profiles[c];e.focusFiles&&!e.focusFiles.has(a.file)&&!e.focusFiles.has(u.file)||i(s,c)}}}else if(e.focusFiles?.size!==0){let s=typeof e.overrunFactor=="number"&&Number.isFinite(e.limit)?e.limit*e.overrunFactor:Number.POSITIVE_INFINITY;for(let a=0;a<e.profiles.length;a+=1){let c=e.profiles[a],u=e.focusFiles?.has(c.file)??!1;for(let l of Uq(e,a))e.focusFiles&&!u&&!e.focusFiles.has(e.profiles[l].file)||i(a,l);if(r.length>s){t.overrunApplied=!0;break}}}r.sort(e.sort??((s,a)=>a.similarity-s.similarity)),t.matchedResults=r.length;let o=r.slice(0,e.limit);return t.emittedResults=o.length,e.onProfile?.({...t}),o};return e.profile?N(`pairwise-profile:${e.profile.name}`,n,()=>({...qq(e.profile?.metadata),...t})):n()}function Hq(e,t){if(e.candidateIndex)return aE(e,t,-1);let n=[];for(let r=0;r<e.profiles.length;r+=1)r!==t&&n.push(r);return n}function Uq(e,t){if(e.candidateIndex)return aE(e,t,t);let n=[];for(let r=t+1;r<e.profiles.length;r+=1)n.push(r);return n}function aE(e,t,n){let r=e.profiles[t],i=new Set;for(let o of e.candidateIndex?.candidatesFor(r,t,e.profiles)??[])o<=n||o!==t&&(o<0||o>=e.profiles.length||i.add(o));return[...i].sort((o,s)=>o-s)}function sE(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 qq(e){return typeof e=="function"?e():e??{}}function Gq(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=zq(e,{scope:i,minDeps:s}),u=un(a,l=>l.deps);return dn({profiles:a,limit:r,filePattern:o,overrunFactor:5,candidateIndex:u,profile:{name:"similar-files"},compare:(l,d)=>Wq(l,d,n,c)})}function zq(e,t){let{scope:n,minDeps:r}=t,i=_e(e,n),{universalDeps:o,distinctiveDeps:s}=Kq(i),a=[];for(let[c,u]of i)u.size>=r&&a.push({file:c,deps:new Set([...u].filter(l=>!o.has(l)))});return{profiles:a,distinctiveDeps:s}}function Kq(e){let t=new Set,n=new Set,r=e.size;if(r===0)return{universalDeps:t,distinctiveDeps:n};let i=new Map;for(let s of e.values())for(let a of s)i.set(a,(i.get(a)??0)+1);let o=Math.max(3,Math.ceil(r*.03));for(let[s,a]of i)a>=5&&a/r>.3?t.add(s):a<=o&&n.add(s);return{universalDeps:t,distinctiveDeps:n}}function Wq(e,t,n,r){let i=new Set;for(let u of e.deps)t.deps.has(u)&&i.add(u);if(i.size<3||e.deps.size<4||t.deps.size<4)return null;let o=0;for(let u of i)r.has(u)&&o++;if(o<2)return null;let s=gr(e.deps,t.deps);if(s<n)return null;let a=[];for(let u of e.deps)t.deps.has(u)||a.push(u);let c=[];for(let u of t.deps)e.deps.has(u)||c.push(u);return{fileA:e.file,fileB:t.file,similarity:s,sharedDeps:[...i],uniqueToA:a,uniqueToB:c}}function hr(e){let t=[],n=[],r=[];for(let u of e.primitiveGroups)u.values.length!==0&&cE(u.bucket,n,r).push(`${u.reasonPrefix}: ${u.values.join(", ")}`);for(let u of e.nameGroups)Vq(u.names,u.label,e.genericWords,e.stripPrefixes??[],t,cE(u.fallbackBucket,n,r));let i=t.length>0,o=n.length>0,s=r.length>0,a=i?o||s?"mixed":"domain-behavior":s?"shared-abstraction":"generic-workflow-scaffolding";return{actionTier:a==="domain-behavior"||a==="mixed"?"signal":"support",evidenceClass:a,reasons:[...t,...r,...n].slice(0,6),recommendation:e.recommendation(a)}}function Wc(e,t){if(e.size===0||t.size===0)return 0;let i=Ot(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(gr(e,t),i)}function yr(e,t){let n=Object.fromEntries(e.map(r=>[r.name,r.count]));for(let r of t)if(Object.entries(r.min).every(([o,s])=>(n[o]??0)>=s))return{pass:!0,reason:r.reason,counts:n};return{pass:!1,reason:"shared tokens did not meet calibrated overlap thresholds",counts:n}}function Vc(e,t,n){let r=t.map(c=>{let u=c.value(e),l=c.weightedValue?c.weightedValue(e,u):u;return{axis:c,value:u,weighted:l,qualifies:c.qualifies?c.qualifies(e,u):u>0}}),i=r.filter(c=>c.qualifies&&c.axis.reason).map(c=>c.axis.reason(e,c.value)),o=r.filter(c=>c.qualifies&&c.axis.dominantEligible!==!1).sort((c,u)=>u.weighted-c.weighted)[0],s=o&&o.weighted>0?o.axis.axis:n,a=[...new Set(r.filter(c=>c.qualifies).map(c=>c.axis.axis).concat(i.length>0?[]:[s]))];return{dominantPressure:s,pressureKinds:a,reasons:i}}function me(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function tt(e){return[...e].sort()}function Vq(e,t,n,r,i,o){let s=[],a=[];for(let c of e)Yq(c,r).filter(l=>!n.has(l)).length>0?s.push(c):a.push(c);s.length&&i.push(`${t} has domain term(s): ${s.slice(0,6).join(", ")}`),a.length&&o.push(`${t} is generic workflow: ${a.slice(0,6).join(", ")}`)}function Yq(e,t){let n=e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2");for(let r of t)n=n.replace(r,"");return n.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function cE(e,t,n){return e==="generic"?t:n}var Jq=new Set(["page","layout","template","loading","error","not-found","global-error","default","route"]),lE=/\.(?:ts|tsx|js|jsx|mjs|cjs)$/,Xq=/^\((\.{1,3})\)(.*)$/,Qq=/^\(\.\.\)\(\.\.\)(.*)$/;function uE(e){return jm(e)!==null}function jm(e){let t=pe(e);if(!lE.test(t))return null;let n=t.split("/"),r=n[n.length-1].replace(lE,"");if(!Jq.has(r))return null;let i=n.findIndex((a,c)=>a==="app"&&c<n.length-1);if(i<0)return null;let o=[],s=!1;for(let a of n.slice(i+1,-1)){if(a.startsWith("@"))continue;let c=Qq.exec(a);if(c){s=!0,o.splice(Math.max(0,o.length-2)),o.push(c[1]);continue}let u=Xq.exec(a);if(u){s=!0;let l=u[1];l===".."?o.splice(Math.max(0,o.length-1)):l==="..."&&o.splice(0),o.push(u[2]);continue}a.startsWith("(")&&a.endsWith(")")||o.push(a)}return{route:o,entry:r,intercepting:s}}function dE(e,t){let n=jm(e),r=jm(t);return!n||!r||!n.intercepting&&!r.intercepting||n.entry!==r.entry?!1:n.route.join("/")===r.route.join("/")}import{existsSync as fE,readdirSync as Zq,statSync as eG}from"fs";import{join as Xi}from"path";var mE="components.json",tG=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),nG=3,rG=/(?:^|\/)components\/ui$/i,iG=te("ui-kit-surface",{clearGroups:["whole-project"]});function oG(e){return iG.get(e,()=>sG(e))}function Hm(e,t){let n=pe(t),r=n.lastIndexOf("/");if(r<0)return null;let i=n.slice(0,r);for(let o of oG(e).directories)if(i===o.directory)return o;return rG.test(i)?{directory:i,source:"ui-directory-convention"}:null}function gE(e,t){return Hm(e,t)!==null}function sG(e){let t=new Map;for(let n of aG(e.config.projectRoot)){let r=cG(e,n);r&&!t.has(r)&&t.set(r,{directory:r,source:"shadcn-components-manifest",manifest:n})}return{directories:[...t.values()].sort((n,r)=>n.directory.localeCompare(r.directory))}}function aG(e){let t=[],n=(r,i)=>{let o=r?Xi(e,r):e,s=r?`${r}/${mE}`:mE;if(fE(Xi(e,s))&&t.push(s),i>=nG)return;let a;try{a=Zq(o,{withFileTypes:!0})}catch{return}for(let c of a)!c.isDirectory()||tG.has(c.name)||c.name.startsWith(".")||n(r?`${r}/${c.name}`:c.name,i+1)};return n("",0),t}function cG(e,t){let n;try{n=JSON.parse(ve(e.config.projectRoot,t,{inputKind:"components manifest"}))}catch(a){return a instanceof Error&&Ce(a),null}if(!pE(n))return null;let r=n.aliases;if(!pE(r))return null;let i=typeof r.ui=="string"?r.ui:null,o=typeof r.components=="string"?r.components:null,s=i??(o?`${o}/ui`:null);return s?lG(e,t,s):null}function lG(e,t,n){let r=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",i=[];if(n.startsWith("./")||n.startsWith("../")||n.startsWith("/"))i.push(pe(Xi(r,n)));else{let o=tg(e,t,n);o&&i.push(o);let s=n.replace(/^[@~]\//,"");i.push(pe(Xi(r,"src",s)),pe(Xi(r,s)))}for(let o of i){let s=Xi(e.config.projectRoot,o);if(fE(s)&&eG(s).isDirectory())return o.replace(/\/+$/,"")}return null}function pE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qi(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=uG(e,r);return t.set(r,o),o};return{roleOf:n,pairContext:(r,i)=>{let o=n(r),s=n(i);return o==="ui-kit"&&s==="ui-kit"?"ui-kit-pair":r!==i&&dE(r,i)?"intercepting-route-pair":o==="framework-route"&&s==="framework-route"&&r!==i?"framework-route-pair":"product"}}}function uG(e,t){return U(t)==="test"?"test":Hm(e,t)?"ui-kit":uE(t)||Mn(t)?"framework-route":"product"}var br=class{counts=new Map;record(t,n,r=1){if(r<=0)return;let i=this.counts.get(t);if(i){i.count+=r;return}this.counts.set(t,{reason:t,detail:n,count:r})}list(){return[...this.counts.values()].sort((t,n)=>t.reason.localeCompare(n.reason))}},mn={testFiles:"components defined in test files (fixture scaffolding, not product code)",uiKitPairs:"pairs where both components are vendored UI-kit primitives (similar by construction)",uiKitFiles:"components defined in vendored UI-kit directories",hookComponentPairs:"pairs that mix a hook with a component (a hook is already the extraction target)"};function Yc(e){switch(e){case"framework-route-pair":return"both files are framework route entries; route files share framework scaffolding by design";case"intercepting-route-pair":return"intercepting route and its target route are meant to render the same view";case"ui-kit-pair":return"both files are vendored UI-kit primitives";case"product":return null}}function Um(e,t={}){return qm(e,t).results}function qm(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,u=Qi(e),l=new br,d=Tt(e).reactProfiles({scope:o,minJsxTokens:r,scanLimit:s}).filter(f=>f.kind==="component").filter(f=>u.roleOf(f.file)!=="test"?!0:(l.record("test-files",mn.testFiles),!1)).map(f=>({file:f.file,component:f.name,tokens:f.jsxTokens,profile:f})),m=un(d,f=>f.tokens);return{results:dn({profiles:d,limit:i,filePattern:a,focusFiles:c,candidateIndex:m,profile:{name:"react-component-duplicates"},compare:(f,g)=>{let h=u.pairContext(f.file,g.file),y=dG(f,g,n,h);return y?h==="ui-kit-pair"?(l.record("ui-kit-pairs",mn.uiKitPairs),null):y:null},sort:(f,g)=>hE(f.actionTier)-hE(g.actionTier)||g.similarity-f.similarity||f.fileA.localeCompare(g.fileA)||f.componentA.localeCompare(g.componentA)||f.fileB.localeCompare(g.fileB)||f.componentB.localeCompare(g.componentB)}),exclusions:l.list()}}function hE(e){return e==="signal"?0:1}function dG(e,t,n,r){let i=Ot(e.tokens,t.tokens);if(i.size<6||!hG(i))return null;let o=gr(e.tokens,t.tokens);if(o<n)return null;let s=me(i,"component:"),a=me(i,"native:"),c=me(i,"prop:"),u=me(i,"event:"),l=me(i,"binding:"),d=yG({sharedComponents:s,sharedNativeTags:a,sharedProps:c,sharedEvents:u,sharedBindings:l}),m=Yc(r),p=pG(e.component,t.component,s),f=p?{actionTier:"support",recommendation:gG}:mG(r,d.actionTier,d.recommendation),g=[m,p].filter(h=>h!==null);return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:o,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:tt(i),sharedComponents:s,sharedNativeTags:a,sharedProps:c,sharedEvents:u,sharedBindings:l,evidenceClass:d.evidenceClass,actionTier:f.actionTier,evidenceClassReasons:[...g,...d.reasons],recommendation:f.recommendation,pairContext:r,uniqueToA:tt(Je(e.tokens,t.tokens)).slice(0,25),uniqueToB:tt(Je(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function mG(e,t,n){switch(e){case"framework-route-pair":return{actionTier:"support",recommendation:"Framework route entries share routing scaffolding by design; consolidate only a repeated non-routing body, and keep each route file as the framework entry."};case"intercepting-route-pair":return{actionTier:t,recommendation:"Render one shared view component from both the intercepting route and its target route; the routes are meant to show the same content, not to duplicate its body."};case"ui-kit-pair":case"product":return{actionTier:t,recommendation:n}}}function pG(e,t,n){return!yE.test(e)||!yE.test(t)||!n.every(r=>fG.has(r))?null:"both components are loading placeholders sharing only skeleton primitives"}var yE=/(?:Skeleton|Loading|Placeholder|Fallback)(?:[A-Z][A-Za-z0-9]*)?$|^Loading[A-Z]/,fG=new Set(["Skeleton","Spinner","Loader","Loader2","Placeholder"]),gG="Loading placeholders mirror the surface they stand in for; share a skeleton primitive only if the covered layouts are themselves shared.";function hG(e){let t=0,n=0;for(let r of e)r.startsWith("component:")&&(t+=1),(r.startsWith("prop:")||r.startsWith("event:")||r.startsWith("native:")||r.startsWith("jsx:"))&&(n+=1);return yr([{name:"component",count:t},{name:"shape",count:n}],[{min:{component:1},reason:"shared custom component"},{min:{shape:4},reason:"shared JSX structure"}]).pass}function yG(e){return hr({genericWords:SG,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:bG})}function bG(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 SG=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 Gm(e,t={}){return zm(e,t).results}function zm(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,u=Qi(e),l=new br,d=Tt(e).reactProfiles({scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).filter(f=>u.roleOf(f.file)!=="test"?!0:(l.record("test-files",mn.testFiles),!1)).map(f=>({file:f.file,component:f.name,tokens:f.behaviorTokens,profile:f})),m=un(d,f=>f.tokens);return{results:dn({profiles:d,limit:i,filePattern:a,focusFiles:c,candidateIndex:m,profile:{name:"react-hook-candidates"},compare:(f,g)=>{let h=u.pairContext(f.file,g.file),y=vG(f,g,n,r,h);return y?f.profile.kind!==g.profile.kind?(l.record("hook-component-pairs",mn.hookComponentPairs),null):h==="ui-kit-pair"?(l.record("ui-kit-pairs",mn.uiKitPairs),null):y:null},sort:(f,g)=>bE(f.actionTier)-bE(g.actionTier)||g.similarity-f.similarity||f.fileA.localeCompare(g.fileA)||f.componentA.localeCompare(g.componentA)||f.fileB.localeCompare(g.fileB)||f.componentB.localeCompare(g.componentB)}),exclusions:l.list()}}function bE(e){return e==="signal"?0:1}function vG(e,t,n,r,i){let o=Ot(e.tokens,t.tokens);if(o.size<r||!EG(o))return null;let s=Wc(e.tokens,t.tokens);if(s<n)return null;let a=me(o,"hook:"),c=me(o,"react-hook:"),u=me(o,"effect:"),l=me(o,"state:"),d=me(o,"request:"),m=me(o,"handler:"),p=me(o,"handler-verb:"),f=xG({sharedHooks:a,sharedReactHooks:c,sharedEffects:u,sharedState:l,sharedRequests:d,sharedHandlers:m,sharedHandlerVerbs:p}),g=Yc(i),h=CG(i,f.actionTier,f.recommendation);return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:s,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:tt(o),sharedHooks:a,sharedReactHooks:c,sharedEffects:u,sharedState:l,sharedRequests:d,sharedHandlers:m,sharedHandlerVerbs:p,evidenceClass:f.evidenceClass,actionTier:h.actionTier,evidenceClassReasons:g?[g,...f.reasons]:f.reasons,recommendation:h.recommendation,unitKind:e.profile.kind==="hook"&&t.profile.kind==="hook"?"hook":"component",pairContext:i,uniqueToA:tt(Je(e.tokens,t.tokens)).slice(0,25),uniqueToB:tt(Je(t.tokens,e.tokens)).slice(0,25),reason:IG({sharedHooks:a,sharedReactHooks:c,sharedEffects:u,sharedState:l,sharedRequests:d,sharedHandlers:m,sharedHandlerVerbs:p}),locA:e.profile.loc,locB:t.profile.loc}}function CG(e,t,n){switch(e){case"framework-route-pair":return{actionTier:t,recommendation:n};case"intercepting-route-pair":return{actionTier:t,recommendation:"Render one shared view component from both the intercepting route and its target route instead of repeating the behavior in each body."};case"ui-kit-pair":case"product":return{actionTier:t,recommendation:n}}}function xG(e){return hr({genericWords:wG,stripPrefixes:LG,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:RG})}function RG(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 EG(e){let t=0,n=0,r=0,i=0,o=0,s=0,a=0;for(let l of e)l.startsWith("hook:")?t+=1:l.startsWith("react-hook:")?n+=1:l.startsWith("effect:")?r+=1:l.startsWith("request:")?i+=1:l.startsWith("handler:")||l.startsWith("handler-verb:")?o+=1:l.startsWith("state:")?s+=1:l.startsWith("state-hook:")&&(a+=1);let c=s+a,u=t+n+r+i+o+c;return yr([{name:"requests",count:i},{name:"customHooks",count:t},{name:"namedStates",count:s},{name:"handlers",count:o},{name:"effects",count:r},{name:"reactHooks",count:n},{name:"namedBehavior",count:u}],[{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 IG(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 wG=new Set(["add","apply","async","callback","cancel","change","clear","client","close","context","create","data","deferred","delete","dispatch","draft","edit","effect","error","fetch","field","filter","form","handle","has","id","infinite","is","item","items","load","loader","loading","memo","mutate","mutation","name","navigate","navigation","open","params","pathname","query","reducer","refresh","ref","remove","request","reset","resource","router","row","rows","save","saving","search","select","selected","selector","state","store","submit","suspense","toggle","transition","update","use","value"]),LG=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function PG(e,t={}){return Km(e,t).results}function Km(e,t={}){let{minComponentLines:n=300,minFileLines:r=800,minJsxTokens:i=80,minBehaviorTokens:o=40,limit:s=20,scope:a,scanLimit:c,filePattern:u}=t,l=Qi(e),d=new br;return{results:Tt(e).reactProfiles({scope:a,scanLimit:c}).filter(f=>f.kind==="component").filter(f=>!u||f.file.includes(u)||f.name.includes(u)).map(f=>DG(f,{minComponentLines:n,minFileLines:r,minJsxTokens:i,minBehaviorTokens:o})).filter(f=>f!==null).filter(f=>{let g=l.roleOf(f.file);return g==="test"?(d.record("test-files",mn.testFiles),!1):g==="ui-kit"?(d.record("ui-kit-files",mn.uiKitFiles),!1):!0}).sort((f,g)=>g.componentLines-f.componentLines||g.fileLines-f.fileLines||f.file.localeCompare(g.file)).slice(0,s),exclusions:d.list()}}function DG(e,t){let n=Math.max(1,Math.floor(t.minComponentLines/2)),r=Vc(e,MG({minComponentLines:t.minComponentLines,minFileLines:t.minFileLines,minJsxTokens:t.minJsxTokens,minBehaviorTokens:t.minBehaviorTokens,substantialComponentLines:n}),"component"),{reasons:i}=r;if(i.length===0)return null;let o=r.dominantPressure,s=r.pressureKinds,a=TG(e),c=kG(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:AG(c,a),reasons:i,loc:e.loc}}function MG(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&&t.loc>=e.substantialComponentLines,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&&t.loc>=e.substantialComponentLines,reason:(t,n)=>`${n} behavior token(s)`}]}function TG(e){let t=e.file.split(/[\\/]+/).filter(Boolean),n=t.slice(0,-1).map(m=>m.toLowerCase()),r=(t.at(-1)??e.name).replace(/\.[^.]+$/,""),o=n.findIndex(m=>NG.has(m))>=0,s=n.some(m=>FG.has(m));if(SE(r)||SE(e.name))return"component";let c=_G.has(r.toLowerCase()),u=/(?:Page|Route|Screen)$/.test(e.name),l=o&&/View$/.test(e.name),d=!s&&r.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()===e.name.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()&&/(?:Page|Route|Screen|View)$/.test(r);return c||u||l||d?"route-page":"component"}function SE(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&vE.has(t.at(-1))?!0:[...vE].some(n=>e.endsWith(OG(n)))}function kG(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 AG(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 FG=new Set(["component","components","panel","panels","partial","partials"]),vE=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"]),NG=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),_G=new Set(["page","route","screen"]);function OG(e){return e.charAt(0).toUpperCase()+e.slice(1)}function vs(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,u=BG(e,{scope:o,minTokens:r,scanLimit:s}),l=un(u,d=>d.tokens);return dn({profiles:u,limit:i,filePattern:a,focusFiles:c,candidateIndex:l,profile:{name:"vue-component-duplicates"},compare:(d,m)=>jG(d,m,n),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function BG(e,t){return Tt(e).vueProfiles({scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:$G(n)}))}function $G(e){return e.totalLines}function jG(e,t,n){let r=Ot(e.tokens,t.tokens);if(r.size<6||!HG(r))return null;let i=gr(e.tokens,t.tokens);if(i<n)return null;let o=me(r,"component:"),s=me(r,"prop:"),a=me(r,"event:"),c=me(r,"directive:"),u=me(r,"slot:"),l=me(r,"id:"),d=UG({sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:c,sharedSlots:u,sharedIdentifiers:l});return{fileA:e.file,fileB:t.file,similarity:i,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:tt(r),sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:c,sharedSlots:u,sharedIdentifiers:l,evidenceClass:d.evidenceClass,actionTier:d.actionTier,evidenceClassReasons:d.reasons,recommendation:d.recommendation,uniqueToA:tt(Je(e.tokens,t.tokens)).slice(0,25),uniqueToB:tt(Je(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function HG(e){let t=0,n=0;for(let r of e)r.startsWith("component:")&&(t+=1),(r.startsWith("prop:")||r.startsWith("event:")||r.startsWith("directive:")||r.startsWith("slot:"))&&(n+=1);return yr([{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 UG(e){return hr({genericWords:GG,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:qG})}function qG(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 GG=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 Cs(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,u=Tt(e).vueProfiles({scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(d=>({file:d.file,tokens:d.behaviorTokens,profile:d})),l=un(u,d=>d.tokens);return dn({profiles:u,limit:i,filePattern:a,focusFiles:c,candidateIndex:l,profile:{name:"vue-composable-candidates"},compare:(d,m)=>zG(d,m,n,r),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function zG(e,t,n,r){let i=Ot(e.tokens,t.tokens);if(i.size<r||!VG(i))return null;let o=Wc(e.tokens,t.tokens);if(o<n)return null;let s=me(i,"composable:"),a=me(i,"store:"),c=me(i,"reactivity:"),u=me(i,"lifecycle:"),l=me(i,"request:"),d=me(i,"function:"),m=me(i,"function-verb:"),p=me(i,"template-binding:"),f=me(i,"template-event:"),g=KG({sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:u,sharedRequests:l,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:tt(i),sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:u,sharedRequests:l,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p,sharedTemplateEvents:f,evidenceClass:g.evidenceClass,actionTier:g.actionTier,evidenceClassReasons:g.reasons,recommendation:g.recommendation,uniqueToA:tt(Je(e.tokens,t.tokens)).slice(0,25),uniqueToB:tt(Je(t.tokens,e.tokens)).slice(0,25),reason:YG({sharedComposables:s,sharedStores:a,sharedRequests:l,sharedLifecycle:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function KG(e){return hr({genericWords:JG,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:WG})}function WG(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 VG(e){let t=0,n=0,r=0,i=0,o=0,s=0,a=0;for(let l of e)l.startsWith("composable:")?t+=1:l.startsWith("store:")?n+=1:l.startsWith("request:")?r+=1:l.startsWith("lifecycle:")?i+=1:l.startsWith("function:")?o+=1:l.startsWith("reactivity:")?s+=1:(l.startsWith("function-verb:")||l.startsWith("template-binding:")||l.startsWith("template-event:"))&&(a+=1);let c=t+n,u=c+r+i+o+a;return yr([{name:"requests",count:r},{name:"lifecycle",count:i},{name:"functions",count:o},{name:"reusableHooks",count:c},{name:"reactivity",count:s},{name:"namedBehavior",count:u}],[{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 YG(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 JG=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 Wm(e,t={}){let{minTotalLines:n=800,minTemplateLines:r=300,minScriptLines:i=300,minStyleLines:o=500,limit:s=20,scope:a,scanLimit:c,filePattern:u}=t;return Tt(e).vueProfiles({scope:a,scanLimit:c}).filter(d=>!u||d.file.includes(u)).map(d=>XG(d,{minTotalLines:n,minTemplateLines:r,minScriptLines:i,minStyleLines:o})).filter(d=>d!==null).sort((d,m)=>m.totalLines-d.totalLines||d.file.localeCompare(m.file)).slice(0,s)}function XG(e,t){let n=Vc(e,QG(t),"total"),{reasons:r}=n;if(r.length===0)return null;let i=n.dominantPressure,o=n.pressureKinds.includes("total")?[...new Set([...n.pressureKinds,i])]:n.pressureKinds,s=ZG(e.file),a=ez(i,s),c=e.totalLines+e.delegatedComposableLines;return{file:e.file,totalLines:c,sfcLines:e.sfcLines,templateLines:e.templateLines,scriptLines:e.scriptLines,styleLines:e.styleLines,externalScriptLines:e.externalScriptLines,externalScriptPaths:e.externalScriptPaths,customBlockLines:e.customBlockLines,delegatedComposableLines:e.delegatedComposableLines,delegatedComposablePaths:e.delegatedComposablePaths,dominantPressure:i,pressureKinds:o,contextKind:s,recommendationKind:a,recommendation:tz(a,s),reasons:r,loc:c}}function QG(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 ZG(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(r=>nz.has(r))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function ez(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 tz(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 nz=new Set(["landing","page","pages","route","routes","view","views"]);function rz(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:o=3,maxChainLength:s=8}=t,a=_e(e,i),c=dz(a,o,s);if(c.length===0)return[];let u=iz(c);return u.length<2?[]:uz(az(u,n,r),r)}function iz(e){let t=oz(e),n=[];for(let r of e){let i=r.filter(o=>!t.has(o));i.length>=2&&n.push({original:r,filtered:i})}return n}function oz(e){let{nodeFreq:t,tailFreq:n}=sz(e),r=e.length*.9,i=e.length*.8,o=new Set;for(let[a,c]of t)c>r&&o.add(a);for(let[a,c]of n)c>i&&o.add(a);let s=["index.ts","index.js","cli.ts","main.ts","health.ts","health.js"];for(let a of t.keys()){let c=a.split("/").pop()??"";s.includes(c)&&o.add(a)}return o}function sz(e){let t=new Map,n=new Map;for(let r of e){let i=new Set;for(let o of r)i.has(o)||(t.set(o,(t.get(o)??0)+1),i.add(o));for(let o=Math.max(0,r.length-2);o<r.length;o++)n.set(r[o],(n.get(r[o])??0)+1)}return{nodeFreq:t,tailFreq:n}}function az(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let o=i+1;o<e.length;o++){let s=cz(e[i],e[o],t);s&&r.push(s)}if(r.length>n*10)break}return r.sort((i,o)=>Math.abs(o.similarity-i.similarity)>.01?o.similarity-i.similarity:i.divergencePoints.length-o.divergencePoints.length),r}function cz(e,t,n){if(!lz(e.filtered,t.filtered))return null;let{distance:r,ops:i}=mz(e.filtered,t.filtered),o=Math.max(e.filtered.length,t.filtered.length);if(o===0)return null;let s=1-r/o;if(s<n||r===0)return null;let a=i.filter(u=>u.type==="substitute").map(u=>({index:u.indexA,nodeA:e.filtered[u.indexA],nodeB:t.filtered[u.indexB]}));return a.length===0||i.filter(u=>u.type==="match").length<2?null:{chainA:e.original,chainB:t.original,similarity:s,editDistance:r,divergencePoints:a,commonPrefix:pz(e.original,t.original),commonSuffix:fz(e.original,t.original)}}function lz(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function uz(e,t){let n=[];for(let r of e)if(n.some(o=>CE(r.chainA,o.chainA)&&CE(r.chainB,o.chainB))||n.push(r),n.length>=t)break;return n}function dz(e,t,n){let r=[];for(let o of e.keys()){if(r.length>=500)break;xE(e,o,[o],new Set([o]),t,n,r,500)}return r}function xE(e,t,n,r,i,o,s,a){if(s.length>=a)return;if(n.length>=o){n.length>=i&&s.push([...n]);return}let c=e.get(t);if(!c||c.size===0){n.length>=i&&s.push([...n]);return}let u=!1;for(let l of c)if(!r.has(l)&&(r.add(l),n.push(l),xE(e,l,n,r,i,o,s,a),n.pop(),r.delete(l),u=!0,s.length>=a))return;!u&&n.length>=i&&s.push([...n])}function mz(e,t){let n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let c=0;c<=n;c++)i[c][0]=c;for(let c=0;c<=r;c++)i[0][c]=c;for(let c=1;c<=n;c++)for(let u=1;u<=r;u++)e[c-1]===t[u-1]?i[c][u]=i[c-1][u-1]:i[c][u]=1+Math.min(i[c-1][u],i[c][u-1],i[c-1][u-1]);let o=[],s=n,a=r;for(;s>0||a>0;)s>0&&a>0&&e[s-1]===t[a-1]?(o.unshift({type:"match",indexA:s-1,indexB:a-1}),s--,a--):s>0&&a>0&&i[s][a]===i[s-1][a-1]+1?(o.unshift({type:"substitute",indexA:s-1,indexB:a-1}),s--,a--):a>0&&i[s][a]===i[s][a-1]+1?(o.unshift({type:"insert",indexA:s,indexB:a-1}),a--):(o.unshift({type:"delete",indexA:s-1,indexB:a}),s--);return{distance:i[n][r],ops:o}}function pz(e,t){let n=[];for(let r=0;r<Math.min(e.length,t.length)&&e[r]===t[r];r++)n.push(e[r]);return n}function fz(e,t){let n=[],r=e.length-1,i=t.length-1;for(;r>=0&&i>=0&&e[r]===t[i];)n.unshift(e[r]),r--,i--;return n}function CE(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),r=e.join("\u2192");return n.includes(r)}function Bt(e){let t=gz(e.profile?.name),n=()=>{let r=e.candidates(),i=e.filterCandidate?r.filter(e.filterCandidate):r,o=e.orderCandidates?[...i].sort(e.orderCandidates):i,s=be(o,e.scanLimit);t={pipeline:e.profile?.name,loadedCandidates:r.length,filteredCandidates:i.length,scannedCandidates:s.length,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:s.length<i.length,resultLimitApplied:!1};let a=e.prepare?.(s)??void 0,c=[];for(let l of s){t.evaluatedCandidates+=1;let d=e.evaluate(l,a);d&&c.push(d)}t.matchedResults=c.length,e.orderResults&&c.sort(e.orderResults);let u=typeof e.limit=="number"?c.slice(0,e.limit):c;return t.emittedResults=u.length,t.resultLimitApplied=u.length<c.length,e.onProfile?.({...t}),u};return e.profile?N(`candidate-pipeline:${e.profile.name}`,n,()=>({...hz(e.profile?.metadata),...t})):n()}function gz(e){return{pipeline:e,loadedCandidates:0,filteredCandidates:0,scannedCandidates:0,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:!1,resultLimitApplied:!1}}function hz(e){return typeof e=="function"?e():e??{}}var yz=3,bz=8,Sz=.75,vz=2,Cz=.5,xz=2,RE=5,EE=2,IE=2;function xs(e,t={}){let{scope:n,minLoc:r=10,minCallees:i=6,limit:o=20,scanLimit:s}=t,a=new H(e);return Bt({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:r,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:s,profile:{name:"extract-candidates"},prepare:c=>({callees:a.calleeMap(c,{semantic:t.semantic!==!1})}),evaluate:(c,u)=>Ez(c,u.callees.get(c.symbolId)??[],i,Rz(e,c.relativePath)),orderResults:(c,u)=>Jc(c.actionTier)-Jc(u.actionTier)||u.regions[0].lines-c.regions[0].lines||u.loc-c.loc,limit:o})}function Jc(e){return e==="signal"?0:1}function Rz(e,t){let n=kr(e,t)?.locals??[];return{available:n.length>0,occurrences:n,lines:K(e,t)}}function Ez(e,t,n,r){let{uses:i,unpositioned:o}=Iz(e,t);if(i.length<n)return null;let s=ee(e),a=[],c=[];for(let y of i){let S=Math.min(...y.lines),b=Math.max(...y.lines);y.lines.length>=2&&b-S+1>=Cz*s?a.push(y):c.push({symbol:y.symbol,min:S,max:b,render:y.render})}let u=new Set(i.flatMap(y=>y.lines)),l=Lz(wz(c),r.lines,Pz(e,r.lines)).map(y=>Mz(y,e,r.lines,u)),d=l.filter(y=>_z(y,c.length,s)).map(y=>Bz(e,y,a,r)).sort((y,S)=>S.lines-y.lines||y.startLine-S.startLine);if(d.length===0)return null;let m=new Set(i.flatMap(y=>y.lines)),p=[...d].sort((y,S)=>{let b=Jc(Ym(y,r.available,Jm(r.lines,y,m)).tier),x=Jc(Ym(S,r.available,Jm(r.lines,S,m)).tier);return b-x||S.lines-y.lines||y.startLine-S.startLine})[0],f=[`${i.length} callees placed on call lines across ${s} lines`+(o>0?`; ${o} callee row(s) without a call line ignored`:"")];a.length>0&&f.push(`${a.length} ambient callee(s) used across the body: ${a.map(y=>T(y.symbol)).join(", ")}`);for(let y of d)f.push(`lines ${y.startLine+1}-${y.endLine+1} (${y.lines} lines) use ${y.callees.length} callees exclusively`+(r.available?`; ${y.inboundLocals.length} local(s) in, ${y.outboundLocals.length} out`:"; local data flow unknown"));f.push(`${c.length-Oz(l,p)} callee(s) stay outside the largest region`);let g=Jm(r.lines,p,m),h=Ym(p,r.available,g);return f.push(h.reason),{symbol:e.symbol,shortName:T(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:s,totalCallees:i.length,unpositionedCallees:o,ambientCallees:a.map(y=>T(y.symbol)),localsAvailable:r.available,extractionKind:p.kind,actionTier:h.tier,tierReason:h.reason,ownReturnsInRegion:g,evidenceReasons:f,recommendation:Hz(p,r.available),regions:d}}function Iz(e,t){let n=new Map,r=new Set;for(let o of t){if(o.symbol===e.symbol)continue;let s=o.callsiteLine;if(s===void 0||s<e.startLine||s>e.endLine){r.add(o.symbol);continue}let a=n.get(o.symbol);a?(a.lines.includes(s)||a.lines.push(s),a.render||=o.kind==="jsx-render"):n.set(o.symbol,{symbol:o.symbol,lines:[s],render:o.kind==="jsx-render"})}let i=0;for(let o of r)n.has(o)||(i+=1);return{uses:[...n.values()],unpositioned:i}}function wz(e){let t=[...e].sort((r,i)=>r.min-i.min||r.max-i.max),n=[];for(let r of t){let i=n[n.length-1];i&&r.min<=i.end?(i.end=Math.max(i.end,r.max),i.members.push(r)):n.push({start:r.min,end:r.max,members:[r]})}return n}function Lz(e,t,n){let r=[];for(let i of e){let o=r[r.length-1],s=o!==void 0&&!Xm(o)&&!Xm(i)&&!Dz(t,o.end,i.start,n);o&&(i.start-o.end<=xz||s)?(o.end=i.end,o.members.push(...i.members)):r.push({start:i.start,end:i.end,members:[...i.members]})}return r}function Xm(e){return e.members.some(t=>t.render)}function Pz(e,t){for(let n=e.startLine+1;n<e.endLine;n+=1){let r=t[n]??"";if(r.trim().length>0)return Xc(r)}return 0}function Dz(e,t,n,r){for(let i=t+1;i<n;i+=1){let o=e[i]??"";if(o.trim().length!==0&&Xc(o)===r)return!0}return!1}function Mz(e,t,n,r){let i=e.start,o=e.end;for(let s=0;s<IE;s+=1){let a=i-1;if(a<=t.startLine||r.has(a)||!Fz(n[a]??""))break;i=a}for(let s=0;s<IE;s+=1){let a=o+1;if(a>=t.endLine||r.has(a)||!Nz(n[a]??""))break;o=a}if(Xm(e)){let s=Vm(n,i,o);for(let a=0;s>0&&a<wE&&o+1<t.endLine;a+=1)o+=1,s=Vm(n,i,o);for(let a=0;s<0&&a<wE&&i-1>t.startLine&&!/^\s*return\b/.test(n[i-1]??"");a+=1)i-=1,s=Vm(n,i,o)}return{start:i,end:o,members:e.members}}var wE=40,Tz=/<([A-Za-z][\w.:-]*)(?=[\s/>])/g,kz=/<\/[A-Za-z][\w.:-]*\s*>/g,Az=/\/>/g;function Vm(e,t,n){let r=0;for(let i=t;i<=n;i+=1){let o=e[i]??"";r+=(o.match(Tz)??[]).length,r-=(o.match(kz)??[]).length,r-=(o.match(Az)??[]).length}return r}function Fz(e){let t=e.trim();return t.length>0&&/(?:\{|\(|\[|=>|:)$/u.test(t)&&!/^(?:\/\/|\*|\/\*)/u.test(t)}function Nz(e){return/^[\s)\]}>;,]+$/u.test(e)&&e.trim().length>0}function _z(e,t,n){let r=e.end-e.start+1;return e.members.length>=yz&&r>=bz&&r<=Sz*n&&t-e.members.length>=vz}function Oz(e,t){return e.find(n=>n.start===t.startLine&&n.end===t.endLine)?.members.length??0}function Bz(e,t,n,r){let i=[...t.members].sort((a,c)=>a.min-c.min),o=i.filter(a=>a.render).length,s=$z(e,t,r);return{startLine:t.start,endLine:t.end,lines:t.end-t.start+1,kind:o*2>i.length?"render-region":"call-region",callees:i.map(a=>T(a.symbol)),renderCallees:o,inboundLocals:s.inbound,outboundLocals:s.outbound,ambientCallees:n.filter(a=>a.lines.some(c=>c>=t.start&&c<=t.end)).map(a=>T(a.symbol))}}function $z(e,t,n){if(!n.available)return{inbound:[],outbound:[]};let r=new Map;for(let a of n.occurrences){if(a.line<e.startLine||a.line>e.endLine)continue;let c=r.get(a.symbol);c||(c={declaredAt:null,name:"",uses:[],writes:[]},r.set(a.symbol,c)),a.definition?(c.declaredAt=a.line,c.name=jz(n.lines,a)):(c.uses.push(a.line),a.write&&c.writes.push(a.line))}let i=a=>a>=t.start&&a<=t.end,o=new Set,s=new Set;for(let a of r.values()){if(a.declaredAt===null||a.name==="")continue;let c=i(a.declaredAt),u=a.uses.some(l=>l>t.end);!c&&a.declaredAt<t.start&&a.uses.some(i)&&o.add(a.name),c&&u&&s.add(a.name),!c&&a.writes.some(i)&&u&&s.add(a.name)}return{inbound:[...o].sort(),outbound:[...s].sort()}}function jz(e,t){return t.endLine!==t.line?"":e[t.line]?.slice(t.startChar,t.endChar).trim()??""}function Ym(e,t,n){if(n>0)return{tier:"support",reason:`support tier: the largest region holds ${n} return statement(s) of the function itself, so it is the function's control flow rather than a helper`};if(!t)return{tier:"signal",reason:"signal tier: local data flow unknown, interface cost not assessed"};let r=e.inboundLocals.length,i=e.outboundLocals.length;return r<=RE&&i<=EE?{tier:"signal",reason:`signal tier: the largest region takes ${r} local(s) in and hands ${i} back`}:{tier:"support",reason:`support tier: the largest region would take ${r} local(s) in and hand ${i} back, more than ${RE} in or ${EE} out`}}function Jm(e,t,n){let r=Number.POSITIVE_INFINITY;for(let o=t.startLine;o<=t.endLine;o+=1)n.has(o)&&(r=Math.min(r,Xc(e[o]??"")));if(!Number.isFinite(r))return 0;let i=0;for(let o=t.startLine;o<=t.endLine;o+=1){let s=e[o]??"";/^\s*return\b/u.test(s)&&Xc(s)<=r&&(i+=1)}return i}function Xc(e){return e.length-e.trimStart().length}function Hz(e,t){let n=`${e.startLine+1}-${e.endLine+1}`,r=t?`; an extraction would take ${e.inboundLocals.length} local(s) in`+(e.inboundLocals.length>0?` (${e.inboundLocals.join(", ")})`:"")+` and hand ${e.outboundLocals.length} back`+(e.outboundLocals.length>0?` (${e.outboundLocals.join(", ")})`:""):"; local data flow is unknown because the indexer emitted no local symbols for this file";return e.kind==="render-region"?`Review lines ${n} as a child component: its ${e.callees.length} rendered or called names appear nowhere else in this component${r}. Extract only if the new name states what the subtree shows.`:`Review lines ${n} as a helper: its ${e.callees.length} callees are used nowhere else in this function${r}. Extract only if the new name states what the region does.`}import{posix as Zi}from"path";import{spawnSync as Uz}from"child_process";import{createHash as qz}from"crypto";import{existsSync as Gz}from"fs";import{dirname as LE,join as zz}from"path";import{fileURLToPath as Kz}from"url";var ME=Vt("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]}),PE=ft({kind:"consumer-file-usage",invalidation:Ne("consumer-file-usage"),serialize:rK,deserialize:iK});function _n(e,t){return{forDefinitions(n,r){return Wz(e,t,n,r)}}}function On(e){let t=new Map;for(let[n,r]of e)t.set(n,new Set(r.files.map(i=>i.file)));return t}function Zc(e,t,n){return kE(e,t,n).partition}function Wz(e,t,n,r){let i=TE(n.length),o=xe()?pt(e):null,s=o?Vz(n,r,o):void 0,a=s?{workIdentity:s,workOutcome:"computed"}:{};return N("consumer-evidence.product",()=>{let c=N("consumer-evidence.provenance",()=>Yz(e,t,n,r),()=>({...a,definitions:n.length,semantic:r.semantic,sourceFallback:r.sourceFallback!==!1})),u=new Map;i={...i,...c.counters};let l=Jz(n,c.sources);return N("consumer-evidence.classify",()=>{let d=Xz(e,n,c.sources,l);for(let m of n){let p=d.get(m.symbolId)??Zz();i.realFiles+=p.partition.realConsumers.length,i.reexportOnlyFiles+=p.partition.barrelConsumers,i.importOnlyFiles+=p.partition.importOnlyConsumers,u.set(m.symbolId,{definition:m,files:p.files,...p.partition})}},()=>({...a,...l,realFiles:i.realFiles,reexportOnlyFiles:i.reexportOnlyFiles,importOnlyFiles:i.importOnlyFiles})),u},()=>({...a,...i}))}function Vz(e,t,n){let r=qz("sha256").update("consumer-evidence-v1\0").update(n).update("\0").update(t.semantic?"semantic\0":"indexed\0").update(t.sourceFallback===!1?"no-source-fallback":"source-fallback");for(let i of e.map(o=>o.symbol).sort())r.update("\0").update(i);return r.digest("hex").slice(0,24)}function TE(e){return{definitions:e,indexedFiles:0,semanticFiles:0,fallbackFiles:0,totalFiles:0,realFiles:0,reexportOnlyFiles:0,importOnlyFiles:0}}function Yz(e,t,n,r){let i=TE(n.length),o=new Map;return Qm(o,i,"indexed",t.crossFileCallerMap(n,{semantic:!1})),r.semantic&&Qm(o,i,"semantic",er(e,n)),r.sourceFallback!==!1&&Qm(o,i,"source-fallback",t.sourceFallbackCallerFiles(n)),i.totalFiles=[...o.values()].reduce((s,a)=>s+a.size,0),{sources:o,counters:i}}function Jz(e,t){return{definitions:e.length,consumerFiles:[...t.values()].reduce((n,r)=>n+r.size,0),nativeAttempted:!1,nativeUsed:!1,nativeReason:"not-attempted"}}function Qm(e,t,n,r){let i=0;for(let[o,s]of r){let a=e.get(o);a||(a=new Map,e.set(o,a));for(let c of s){i++;let u=a.get(c)??new Set;u.add(n),a.set(c,u)}}n==="indexed"?t.indexedFiles+=i:n==="semantic"?t.semanticFiles+=i:t.fallbackFiles+=i}function Xz(e,t,n,r){let i=dK(e,t,n,r);return i||Qz(e,t,n)}function Qz(e,t,n){let r=new Map;for(let i of t){let o=n.get(i.symbolId)??new Map;r.set(i.symbolId,kE(e,i,[...o.keys()],o))}return r}function kE(e,t,n,r=new Map){let i=[],o=0,s=0,a=G(t.symbol),c=[];for(let u of n){let l;oK(e,u,t.relativePath,a)?(o++,l="reexport-only"):Zm(e,u,a)?(s++,l="import-only"):(i.push(u),l="real"),c.push({file:u,sources:[...r.get(u)??[]],classification:l})}return{partition:{realConsumers:i,barrelConsumers:o,importOnlyConsumers:s},files:c}}function Zz(){return{partition:{realConsumers:[],barrelConsumers:0,importOnlyConsumers:0},files:[]}}function Zm(e,t,n){if(!n)return!1;let r=ae(t);if(!r)return!1;let i=ME.get(e,t,()=>AE(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function AE(e,t,n){let r=Sn(e).forFile(t,{text:!0}).text;if(!r)return nK();let i=Pt(e,t,r),o=PE.read(e,t,i);if(o)return o;let s=tK(Sn(e).forFile(t,{ast:!0}).ast,n);return PE.write(e,t,i,s),s}var eK=new Set(["identifier","type_identifier","property_identifier","field_identifier"]);function tK(e,t){let n=new Set,r=new Set;if(!e)return{importedLeaves:n,usedLeaves:r};let i=t==="rust"?new Set(["use_declaration"]):t==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),o=e.walk(),s=0,a=!1;for(;!a;){let c=o.nodeType,u=i.has(c);if(u&&(s+=1),eK.has(c)&&(s>0?n:r).add(o.nodeText),!o.gotoFirstChild())for(u&&(s-=1);!o.gotoNextSibling();){if(!o.gotoParent()){a=!0;break}i.has(o.nodeType)&&(s-=1)}}return{importedLeaves:n,usedLeaves:r}}function nK(){return{importedLeaves:new Set,usedLeaves:new Set}}function rK(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function iK(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 oK(e,t,n,r){if(!r)return!1;let i=Sn(e).forFile(t,{lines:!0,reexports:!0}),o=i.lines??[];if(o.length===0)return!1;let s=i.reexports??[];return FE(o,s,r)}function FE(e,t,n){if(e.length===0||t.length===0)return!1;let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\b${r}\\b`),o=0;for(let s=0;s<e.length;s++){if(!i.test(e[s]??""))continue;if(o++,!t.find(c=>c.startLine<=s&&s<=c.endLine))return!1}return o>0}var sK="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY",aK="SCIP_QUERY_NATIVE_KERNELS_BIN",cK="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY_MIN_FILES",DE=1e3,lK=5e3,uK=64*1024*1024,Qc;function dK(e,t,n,r){let i=process.env[sK]?.toLowerCase();if(i!=="1"&&i!=="true")return r.nativeReason=i==="0"||i==="false"?"disabled":"opt-in-required",null;if(r.consumerFiles<bK())return r.nativeReason="below-threshold",null;let o=SK();if(!o)return r.nativeReason="binary-missing",null;r.nativeAttempted=!0;let s=mK(e,t,n),a=Uz(o,["consumer-classify"],{input:JSON.stringify(s),encoding:"utf8",timeout:lK,maxBuffer:uK});if(a.status!==0||a.error)return r.nativeReason=a.error?`spawn-error:${a.error.message}`:`exit-${a.status??"null"}`,null;try{let c=JSON.parse(a.stdout),u=fK(c,t);return u?(r.nativeUsed=!0,r.nativeReason="used",u):(r.nativeReason="invalid-response",null)}catch{return r.nativeReason="invalid-json",null}}function mK(e,t,n){let r=new Map,i=[];for(let a of t){let c=G(a.symbol),l=[...(n.get(a.symbolId)??new Map).entries()].map(([d,m])=>{let p=r.get(d)??new Set;return c&&p.add(c),r.set(d,p),{file:d,sources:[...m]}});i.push({symbol_id:a.symbolId,leaf:c,consumer_files:l})}let o={},s={};for(let[a,c]of r){let u=ae(a);if(u){let d=ME.get(e,a,()=>AE(e,a,u));o[a]={imported_leaves:[...d.importedLeaves],used_leaves:[...d.usedLeaves]}}let l=pK(e,a,c);l.length>0&&(s[a]=l)}return{definitions:i,file_usages:o,reexport_only_leaves:s}}function pK(e,t,n){if(n.size===0)return[];let r=Sn(e).forFile(t,{lines:!0,reexports:!0}),i=r.lines??[],o=r.reexports??[];return i.length===0||o.length===0?[]:[...n].filter(s=>FE(i,o,s))}function fK(e,t){if(!Array.isArray(e.entries)||e.entries.length!==t.length)return null;let n=new Set(t.map(i=>i.symbolId)),r=new Map;for(let i of e.entries){let o=gK(i);if(!o||!n.has(o.symbol_id))return null;r.set(o.symbol_id,{partition:{realConsumers:o.real_consumers,barrelConsumers:o.barrel_consumers,importOnlyConsumers:o.import_only_consumers},files:o.files})}for(let i of n)if(!r.has(i))return null;return r}function gK(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.symbol_id!="number"||!Array.isArray(t.real_consumers)||typeof t.barrel_consumers!="number"||typeof t.import_only_consumers!="number"||!Array.isArray(t.files)||!t.real_consumers.every(r=>typeof r=="string"))return null;let n=[];for(let r of t.files){if(!r||typeof r!="object")return null;let i=r;if(typeof i.file!="string"||!Array.isArray(i.sources)||!i.sources.every(hK)||!yK(i.classification))return null;n.push({file:i.file,sources:i.sources,classification:i.classification})}return{symbol_id:t.symbol_id,real_consumers:t.real_consumers,barrel_consumers:t.barrel_consumers,import_only_consumers:t.import_only_consumers,files:n}}function hK(e){return e==="indexed"||e==="semantic"||e==="source-fallback"}function yK(e){return e==="real"||e==="reexport-only"||e==="import-only"}function bK(){let e=process.env[cK];if(!e)return DE;let t=Number(e);return Number.isFinite(t)&&t>=0?t:DE}function SK(){if(Qc!==void 0)return Qc;let e=process.env[aK],t=process.platform==="win32"?"scip-query-kernels.exe":"scip-query-kernels";return Qc=[...e?[e]:[],...vK().map(r=>zz(r,"target","release",t))].find(r=>Gz(r))??null,Qc}function vK(){let e=new Set,t=LE(Kz(import.meta.url));for(let n=0;n<5;n++)e.add(t),t=LE(t);return[...e]}var CK=20,xK=1,RK=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"]]),EK=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),IK=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 wK(e,t={}){let n=np(t.limit,CK),r=np(t.minConsumers,xK),i=new H(e),o=i.fileDependencyGraph(t.scope),s=KK(Q(e,{includeIgnored:!1})),a=YK(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?LK(e,i,t.target):PK(e,t.scope,t.scanLimit)).map(l=>DK(e,i,o,l,t,s,a)).filter(l=>l.consumerFiles.length>=r||t.target).sort(zK).slice(0,n)}function LK(e,t,n){let r=kK(e,n);if(r)return[$E(r)];let i=re(e,n);if(!i)return[];let o=t.definitionsForFile(i.relativePath).find(s=>s.symbolId===i.symbolId);return o?[AK(o)]:[{unit:{kind:"symbol",file:i.relativePath,shortName:T(i.symbol),symbol:i.symbol,startLine:i.startLine,endLine:i.endLine}}]}function PK(e,t,n){let r=Q(e,{scope:t,includeIgnored:!1}),i=np(n,r.length);return r.slice(0,i).map(o=>$E(o))}function DK(e,t,n,r,i,o,s){let a=r.definition?MK(e,t,r.definition,i.semantic):TK(n,r.unit.file),c=r.definition?a.length>0?"exact":"none":a.length>0?"file-level":"none",u=r.unit.file,l=zt(Zi.dirname(u)),d=NK(a),m=FK(l),p=ip([...NE(l),...d?NE(d):[]]),f=_K(r.unit,l,d,a),g=OK(f,r.unit,l,d,a,o,s),h=UK(r.unit,c,d,a,l,g.whyNoSuggestedHome),y=qK(r.unit,l,d,a,g.suggestedHome,g.whyNoSuggestedHome);return{actionTier:"signal",sourceUnit:r.unit,candidatePath:u,currentDirectory:l,directoryAncestry:m,consumerFiles:a,consumerCoverage:c,nearestCommonOwner:d,boundaryMarkers:p,recommendedTier:f,suggestedHome:g.suggestedHome,destinationConfidence:g.confidence,whyNoSuggestedHome:g.whyNoSuggestedHome,counterevidence:h,reasons:y,recommendation:GK(f,g.suggestedHome,c)}}function MK(e,t,n,r){let i=On(_n(e,t).forDefinitions([n],{semantic:r!==!1,sourceFallback:!0}));return GE(i.get(n.symbolId)??[])}function TK(e,t){let n=[];for(let[r,i]of e.entries())r!==t&&i.has(t)&&n.push(r);return GE(n)}function kK(e,t){let n=Bs(t),r=Q(e,{includeIgnored:!1}),i=r.find(s=>s===n);if(i)return i;let o=r.find(s=>s.endsWith(`/${n}`));return o||(r.find(s=>s.includes(n))??null)}function AK(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:T(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function $E(e){return{unit:{kind:"file",file:e,shortName:Zi.basename(e)}}}function FK(e){if(e===".")return[{path:".",depth:0,markers:[]}];let t=[],n=e.split("/").filter(Boolean);for(let r=0;r<n.length;r+=1){let i=n.slice(0,r+1).join("/");t.push({path:i,depth:r,markers:rp(i)})}return t}function NE(e){return e==="."?[]:jE(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function rp(e){return ip(jE(e).map(({marker:t})=>t))}function jE(e){let t=e.split("/").filter(Boolean),n=[];for(let r=0;r<t.length;r+=1){let i=RK.get(t[r]);i&&n.push({marker:i,prefix:t.slice(0,r+1).join("/")})}return n}function NK(e){if(e.length===0)return null;let t=e.map(r=>zt(Zi.dirname(r))),n=t[0].split("/").filter(Boolean);for(let r of t.slice(1)){let i=r.split("/").filter(Boolean),o=[],s=Math.min(n.length,i.length);for(let a=0;a<s&&n[a]===i[a];a+=1)o.push(n[a]);n=o}return n.length===0?".":n.join("/")}function _K(e,t,n,r){return n?e.kind==="symbol"&&r.length===1?r[0]===e.file?"same-file":"sibling-folder":n==="."||n==="src"?"repository-level-review":OE(n,"package")?"package-level-shared":OE(n,"app")?"app-level-shared":BE(n,["feature","domain","module"])||BE(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function OK(e,t,n,r,i,o,s){let a=BK(e,r);if(a)return Sr(a);let c=WK(t.file),u=$K(e,n,c,i,s);if(u)return u;let l=r;if(zt(n)===zt(l))return Sr(`${n} is already the nearest common owner for its consumers.`);let d=jK(l,n,c,s);return d||HK(l,n,c,o,s)}function BK(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 $K(e,t,n,r,i){if(e==="same-file"){let o=r[0]??null;return o?ep(o):Sr("No same-file consumer path was available.")}if(e==="sibling-folder"&&r.length===1){let o=zt(Zi.dirname(r[0])),s=qE(t,n,o,i);return s?Sr(s):ep(o)}return null}function jK(e,t,n,r){return XK(e)?HE(e,t,n,r,`Nearest shared owner ${e} is outside source root ${n}.`):null}function HK(e,t,n,r,i){if(e===".")return Sr("The nearest common owner is the repository root.");let o=`${e}/shared`,s=HE(o,t,n,i,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||r.has(o)?s:Sr(`${o} does not exist in the indexed project.`)}function HE(e,t,n,r,i){if(!UE(e,n))return Sr(i);let o=qE(t,n,e,r);return o?Sr(o):ep(e)}function ep(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function Sr(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function UK(e,t,n,r,i,o){let s=["Report-only signal; review ownership before moving files."];return t==="none"&&s.push("No consumers were found in the current index."),t==="file-level"&&s.push("File-level import evidence can hide which exported unit is actually used."),(n==="."||n==="src")&&s.push("Nearest common owner is broad, so this is not enough evidence for automatic placement."),r.length===1&&s.push("Only one consumer was found; inlining or same-folder placement may be better than shared extraction."),e.kind==="file"&&s.push("File targets describe module locality, not symbol-level usage."),n&&i.startsWith(`${n}/`)&&s.push("Candidate already lives under the nearest common owner."),o&&s.push(`No exact suggested home: ${o}`),s}function qK(e,t,n,r,i,o){let s=[];return s.push(`${e.shortName} currently lives in ${t}.`),n?s.push(`${r.length} consumer file(s) share ${n} as their nearest common owner.`):s.push("No consumer owner could be inferred from the current index."),i?s.push(`Suggested home is ${i}.`):o&&s.push(`No exact suggested home: ${o}`),s}function GK(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 zK(e,t){return _E(t)-_E(e)||e.candidatePath.localeCompare(t.candidatePath)}function _E(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 KK(e){let t=new Set(["."]);for(let n of e){let r=zt(Zi.dirname(n));for(;!t.has(r)&&(t.add(r),r!==".");)r=zt(Zi.dirname(r))}return t}function WK(e){let t=tp(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function UE(e,t){let n=zt(e),r=zt(t);return r==="."||n===r||n.startsWith(`${r}/`)}function VK(e,t,n){let r=tp(e),i=tp(t);return(UE(e,t)?r.slice(i.length):r).some(s=>n.has(s.toLowerCase()))}function qE(e,t,n,r){return zt(e)===zt(n)||!VK(e,t,r)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function YK(...e){let t=new Set(IK);for(let n of e)for(let r of n??[]){let i=JK(r);i&&t.add(i)}return t}function JK(e){let t=e.trim().toLowerCase();return t===""?null:t}function OE(e,t){return rp(e).includes(t)}function BE(e,t){let n=rp(e);return t.some(r=>n.includes(r))}function XK(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?EK.has(n):!1}function zt(e){let t=Bs(e);return t===""?".":t}function tp(e){let t=Bs(e);return t==="."?[]:t.split("/").filter(Boolean)}function np(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function GE(e){return ip([...e]).sort((t,n)=>t.localeCompare(n))}function ip(e){return[...new Set(e)]}function op(e,t,n={}){return zE(e,t,n).rows}function QK(e,t,n={}){return zE(e,t,n)}function zE(e,t,n){let{maxDepth:r=5,scope:i}=n,o=r===Number.MAX_SAFE_INTEGER,s=o?null:500,a=re(e,t);if(!a)return{rows:[],coverage:{status:"incomplete",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:r,reachedDepth:0,perSymbolEvidenceLimit:s,remainingFrontierSymbols:0,reasons:["The requested symbol could not be resolved."]}};let c=[],u=new Set([a.symbolId]),l=new Set,d=[a],m=0,p=!1;for(let h=1;h<=r&&d.length!==0;h++){m=h;let y=[],S=Rn(e,d,{...o?{}:{limit:s+1},semanticEvidence:ie});for(let b of d){let x=S.get(b.symbolId)??[];s!==null&&x.length>s&&(p=!0);let v=s===null?x:x.slice(0,s);for(let C of ZK(e,b,i,v)){let R=`${C.file}|${C.shortName}`;if(C.symbolId!==null){if(u.has(C.symbolId))continue;u.add(C.symbolId)}else if(l.has(R))continue;l.add(R),c.push({symbol:C.symbol,shortName:C.shortName,file:C.file,depth:h}),C.symbolId!==null&&C.symbolMatch&&y.push(C.symbolMatch)}}d=y}c.sort((h,y)=>h.depth-y.depth||h.file.localeCompare(y.file));let f=d.length>0,g=[];return f&&g.push(`${d.length} symbol(s) remain eligible beyond depth ${r}.`),p&&g.push(`At least one symbol had more than ${s} incoming evidence row(s).`),g.length===0&&g.push("The discovered reverse evidence frontier was exhausted."),{rows:c,coverage:{status:f||p?"bounded":"accounted",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:r,reachedDepth:m,perSymbolEvidenceLimit:s,remainingFrontierSymbols:d.length,reasons:g}}}function ZK(e,t,n,r){let i=r.filter(l=>!e.isIgnored(l.file)).filter(l=>!n||l.file.includes(n)),o=new Set(i.map(l=>l.file)),s=[];for(let l of eW(e,t,n)){if(o.has(l))continue;let d=q(e,l),m=d.length>0?Oe(d,d[0].startLine):null;s.push({symbol:m?.symbol??l,file:l})}let a=[...i,...s],c=[],u=new Set;for(let l of a){let d=Lr(e,l.symbol);if(!d){let p=`${l.file}|${l.symbol}`;if(u.has(p))continue;u.add(p),c.push({symbolId:null,symbol:l.symbol,shortName:T(l.symbol),file:l.file,symbolMatch:null});continue}if(d.symbolId===t.symbolId||e.isIgnored(d.relativePath)||!tW(d))continue;let m=`${d.symbolId}|${d.relativePath}`;u.has(m)||(u.add(m),c.push({symbolId:d.symbolId,symbol:d.symbol,shortName:T(d.symbol),file:d.relativePath,symbolMatch:d}))}return c}function eW(e,t,n){let r=n?"AND consumer_d.relative_path LIKE ?":"",i=[t.symbolId,t.documentId];return n&&i.push(`%${n}%`),new Set(e.all(`SELECT DISTINCT consumer_d.relative_path
323
- FROM mentions m
324
- JOIN chunks c ON m.chunk_id = c.id
325
- JOIN documents consumer_d ON consumer_d.id = c.document_id
326
- WHERE m.symbol_id = ?
327
- AND m.role != 1
328
- AND c.document_id != ?
329
- ${e.pathExclusionsFor("consumer_d")}
330
- ${r}`,...i).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function tW(e){if(e.symbol.startsWith("scip-clojure ")||ae(e.relativePath)==="clojure")return!0;let t=kt(e.symbol);return t==="method"||t==="type"||e.symbol.endsWith("().")}function WE(e,t){let n=pe(t),r=[],i="complete",o=U(n);o==="entry"&&Bn(r,"operational-root","structural entrypoint path"),o==="worker"&&Bn(r,"operational-root","worker launch convention"),Mn(n)&&Bn(r,"operational-root","framework-discovered entrypoint"),nW(e,n)&&Bn(r,"operational-root","configured entry root");let s=!1;try{s=Dn(e,n),s&&Bn(r,"published-api","package manifest export");for(let a of AS(e,n))Bn(r,"operational-root",a)}catch(a){i="partial",Bn(r,"metadata-unavailable",`package metadata unavailable: ${KE(a)}`)}try{let a=ve(e.config.projectRoot,n,{maxBytes:8388608,inputKind:"change-surface source"});rW(a)&&Bn(r,"operational-root","module contains a direct-execution process guard")}catch(a){i="partial",Bn(r,"metadata-unavailable",Ce(a)?"indexed source file is unavailable on disk":`source metadata unavailable: ${KE(a)}`)}return{operationalRoot:r.some(a=>a.kind==="operational-root"),publishedApi:s,coverage:i,reasons:r}}function nW(e,t){let n=e.config.entryRoots;return n?n.files?.some(r=>pe(r)===t)?!0:n.pathPrefixes?.some(r=>t.startsWith(pe(r)))??!1:!1}function rW(e){return e.includes("import.meta.url")&&/process\.argv\s*\[\s*1\s*\]/.test(e)||/require\.main\s*===\s*module/.test(e)||/__name__\s*==\s*['"]__main__['"]/.test(e)}function Bn(e,t,n){e.some(r=>r.kind===t&&r.detail===n)||e.push({kind:t,detail:n})}function KE(e){return e instanceof Error?e.message:String(e)}function sp(e,t,n={}){let r=gt(e,t);if(!r)return null;let i=iW(e,r);if(!i||e.isIgnored(i.relative_path))return null;let o=[],s=0,a=oW(e,i.relative_path),c=WE(e,i.relative_path),u=n.semantic===!1?new Map:er(e,a);for(let l of a){let d=sW(e,i,l,u.get(l.symbolId)??new Set);s+=d;let m=aW(d),p=[...c.reasons,...d>0?[{kind:"external-consumers",detail:`${d} external consumer${d===1?"":"s"}`}]:[]];o.push({symbol:l.symbol,shortName:T(l.symbol),startLine:l.startLine,endLine:l.endLine,externalConsumers:d,externalConsumerRiskLevel:m,riskLevel:cW(m,c),riskReasons:p})}return{file:i.relative_path,symbols:o,totalExternalConsumers:s,fileRisk:c}}function iW(e,t){return e.get(`SELECT id, relative_path FROM documents
331
- WHERE relative_path = ?
332
- ${e.pathExclusionsFor("documents")}
333
- LIMIT 1`,t)??null}function oW(e,t){return new H(e).definitionsForFile(t).sort((n,r)=>n.startLine-r.startLine||n.endLine-r.endLine)}function sW(e,t,n,r){let i=e.all(`SELECT DISTINCT consumer_d.relative_path
334
- FROM mentions m
335
- JOIN chunks c ON m.chunk_id = c.id
336
- JOIN documents consumer_d ON consumer_d.id = c.document_id
337
- WHERE m.symbol_id = ?
338
- AND m.role != 1
339
- AND c.document_id != ?`,n.symbolId,t.id);return new Set([...i.map(o=>o.relative_path),...[...r].filter(o=>o!==t.relative_path)]).size}function aW(e){return e>10?"high":e>0?"medium":"low"}function cW(e,t){return e==="high"?"high":e==="medium"||t.operationalRoot||t.publishedApi||t.coverage==="partial"?"medium":"low"}function lW(e,t={}){let{scope:n,minLoc:r=1,maxDepth:i=5,scanLimit:o}=t,s=new H(e),a=uW(e,n,r,o),c=new ap;for(let g of a)c.add(g);let u=[],l=[];a.length>0&&u.push(VE(e,0,a,c));let d=a.map(g=>g.definition).filter(g=>g!==null),m=new Set(a.map(g=>g.symbol));for(let g=1;g<=i&&d.length>0;g++){let h=s.calleeMap(d,{semantic:!1}),y=new Set;for(let b of d)for(let x of h.get(b.symbolId)??[])m.has(x.symbol)||y.add(x.symbol);let S=[];for(let b of y){m.add(b);let x=YE(e,b);if(!x||e.isIgnored(x.relativePath)||ze(e,x.relativePath)||Be(e,x.symbol,x.relativePath)||s.fileKind(x.relativePath)==="test"||s.hasSuppressionComment(x))continue;let v=mW(e,x,c);v.removable?S.push(dW(x,"cascade")):v.blockingFiles.length>0&&l.push({shortName:T(x.symbol),file:x.relativePath,blockingFiles:v.blockingFiles.slice(0,3)})}if(S.length===0)break;for(let b of S)c.add(b);u.push(VE(e,g,S,c)),d=S.map(b=>b.definition).filter(b=>b!==null)}let p=u.reduce((g,h)=>g+h.loc,0),f=u.reduce((g,h)=>g+h.entries.length,0);return{batches:u,totalSymbols:f,totalLoc:p,blocked:l}}function uW(e,t,n,r){let i=ti(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:r,semantic:!1}),o=[];for(let s of i.symbols)s.kind==="dead-code"&&(ze(e,s.relativePath)||Be(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:YE(e,s.symbol)}));return o}function dW(e,t){return{symbol:e.symbol,shortName:T(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function YE(e,t){let n=e.get(`SELECT d.relative_path
340
- FROM global_symbols gs
341
- JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
342
- JOIN documents d ON d.id = der.document_id
343
- WHERE gs.symbol = ?
344
- LIMIT 1`,t);return n?q(e,n.relative_path).find(r=>r.symbol===t)??null:null}function mW(e,t,n){let r=fo(e,t);if(r.length===0)return{removable:!1,blockingFiles:[]};let i=new Set;for(let o of r)o.file===t.relativePath&&o.line>=t.startLine&&o.line<=t.endLine||n.contains(o.file,o.line)||i.add(o.file);return{removable:i.size===0,blockingFiles:[...i]}}function VE(e,t,n,r){let i=[...n].sort((a,c)=>a.file.localeCompare(c.file)||a.startLine-c.startLine),o=new Set(i.map(a=>a.file)),s=[];for(let a of o){let c=q(e,a);c.length>0&&c.every(u=>r.contains(a,u.startLine))&&s.push(a)}return{depth:t,entries:i.map(({definition:a,...c})=>c),loc:i.reduce((a,c)=>a+c.loc,0),filesEmptied:s.sort()}}var ap=class{ranges=new Map;add(t){let n=this.ranges.get(t.file)??[];n.push({start:t.startLine,end:t.endLine}),this.ranges.set(t.file,n)}contains(t,n){let r=this.ranges.get(t);return r?r.some(i=>n>=i.start&&n<=i.end):!1}};import{execFileSync as eo}from"child_process";import{existsSync as pW}from"fs";import{basename as JE}from"path";function el(e){let t=new Map;for(let n of e){let r=t.get(n.file);r||(r=[],t.set(n.file,r)),r.push(n)}return t}var mp="Unable to compute git diff.",fW={semanticConsumers:er,sourceFallbackConsumers:Ko,semanticReadiness:Nb},pp={resolveCommit:Nl,readBatch({projectRoot:e,resolvedBase:t,relativePaths:n}){let r=n.map(i=>`${t}:./${i}
345
- `).join("");return eo("git",["cat-file","--batch"],{cwd:e,input:r,maxBuffer:256*1024*1024,timeout:1e4,stdio:["pipe","pipe","ignore"]})}};function tl(e,t={}){let n=t.plan??to(e,t);return n.note?gW(n.note,n.changedFileLines):n.changedFiles.length===0?hW(n.changedFileLines):nl(n.changedFiles,[eI(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function to(e,t={}){let{base:n="HEAD"}=t;try{let r=Nl(e.config.projectRoot,n),i=yW(e.config.projectRoot,r),o=i.changedFileLines,s=RW(e,o),a=EW(e,i.changedRanges);return{changedFileLines:o,changedFiles:s,changedRanges:a,renamedFiles:vW(e.config.projectRoot,r,s,i),note:o.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:mp}}}function eI(e,t,n,r=[],i={}){let o=i.evidenceRuntime??fW,s=new H(e),a=new Set(n),c=el(r),u=[],l=new Map,d=t.flatMap(w=>s.definitionsForFile(w)).filter(jW),m=d.filter(w=>wW(w,c)),p=PW(e,d,m,c),f=TW([...m,...p.definitions]).sort((w,I)=>w.relativePath.localeCompare(I.relativePath)||w.startLine-I.startLine),g=f.map(w=>w.symbolId),h=OW(e,g),y=BW(e,g,n),S=f.filter(w=>(h.get(w.symbolId)??0)===0),b=S.length>0?o.semanticReadiness?.(e)??{ready:!0}:{ready:!0},x=b.ready?ZE("semantic-consumers",S.length,()=>o.semanticConsumers(e,S)):{values:new Map,status:{tier:"semantic-consumers",state:"failed",attemptedSymbols:S.length,reason:b.reason}},v=x.values,C=S.filter(w=>(v.get(w.symbolId)?.size??0)===0),R=ZE("source-fallback-consumers",C.length,()=>o.sourceFallbackConsumers(e,C)),E=R.values;for(let w of f)FW(e,w,a,u,l,v.get(w.symbolId)??new Set,E.get(w.symbolId)??new Set,h.get(w.symbolId)??0,y.get(w.symbolId)??new Set);return{changedSymbols:u,consumerEntries:[...l.entries()].map(([w,I])=>({file:w,symbols:[...I].sort()})),attributionNotes:p.notes,evidenceTiers:[x.status,R.status]}}function nl(e,t){let n=new Map,r=t.flatMap(a=>a.changedSymbols),i=t.flatMap(a=>a.attributionNotes??[]),o=NW(t);for(let a of t)for(let c of a.consumerEntries){let u=n.get(c.file);u||(u=new Set,n.set(c.file,u));for(let l of c.symbols)u.add(l)}let s=$W(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:s,attributionNotes:i,evidenceTiers:o,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:s.length}}}function gW(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:aI(),summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function hW(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:aI(),summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function yW(e,t){let n=eo("git",["diff","--name-status","--find-renames",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864}),r=eo("git",["diff","--name-status","--find-renames","--cached",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),i=eo("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),o=eo("git",["diff","--unified=0",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),s=eo("git",["diff","--unified=0","--cached",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),a=CW([n,r]);return{changedFileLines:[...new Set([...a.changedFiles,...rI(i)])],changedRanges:oI([...QE(o),...QE(s)]),renamedFiles:a.renamedFiles,deletedFiles:a.deletedFiles}}function bW(e,t,n){let r=typeof e=="string"?{projectRoot:e,base:t,relativePath:n}:e;if(typeof r.projectRoot!="string"||typeof r.base!="string"||typeof r.relativePath!="string")throw new TypeError("fileContentAtBase requires projectRoot, base, and relativePath.");let i={projectRoot:r.projectRoot,base:r.base,relativePath:r.relativePath},{relativePath:o}=i,s=fp(i);if(s.state==="unavailable")throw new Error(`Base content unavailable for ${o}: ${s.reason}`);return s.state==="present"?s.content:null}function fp(e,t=pp){return nI(e.relativePath),gp({projectRoot:e.projectRoot,base:e.base,relativePaths:[e.relativePath]},t).get(e.relativePath)??{state:"unavailable",reason:`Base-content lookup omitted ${e.relativePath}.`}}function gp(e,t=pp){for(let s of e.relativePaths)nI(s);let n=[...new Set(e.relativePaths)];if(n.length===0)return new Map;let r;try{r=t.resolveCommit(e.projectRoot,e.base)}catch(s){return cp(n,lp(s))}let i;try{i=t.readBatch({projectRoot:e.projectRoot,resolvedBase:r,relativePaths:n})}catch(s){return cp(n,lp(s))}let o;try{o=SW(i,n)}catch(s){return cp(n,`Malformed git cat-file batch output: ${lp(s)}`)}return new Map(n.map(s=>{let a=o.get(s)??null;return[s,a===null?{state:"absent"}:{state:"present",content:a}]}))}function hp(e,t=pp){let n=gp({projectRoot:e.projectRoot,base:e.base,relativePaths:e.preloadPaths??[]},t);return r=>(n.has(r)||n.set(r,fp({projectRoot:e.projectRoot,base:e.base,relativePath:r},t)),n.get(r)??{state:"unavailable",reason:`Base-content reader omitted ${r}.`})}function tI(e,t=e.changedFiles){let n=new Map(e.renamedFiles.map(r=>[r.to,r.from]));return[...new Set(t.map(r=>n.get(r)??r))]}function nI(e){hn(e)}function cp(e,t){return new Map(e.map(n=>[n,{state:"unavailable",reason:t}]))}function lp(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 SW(e,t){let n=new Map,r=0;for(let i of t){let o=e.indexOf(10,r);if(o<0)throw new Error("git cat-file batch output ended before object header");let s=e.subarray(r,o).toString("utf-8");if(r=o+1,s.endsWith(" missing")){n.set(i,null);continue}let a=/^[0-9a-f]+ ([^ ]+) (\d+)$/.exec(s);if(!a)throw new Error(`unexpected git cat-file batch header: ${s}`);let[,c,u]=a,l=Number(u);if(!Number.isFinite(l)||l<0)throw new Error(`unexpected git cat-file batch size: ${s}`);if(r+l>e.length)throw new Error("git cat-file batch output ended before blob payload");let d=e.subarray(r,r+l);n.set(i,c==="blob"?d.toString("utf-8"):null),r+=l,e[r]===10&&(r+=1)}return n}function vW(e,t,n,r){if(n.length===0)return[];let i=new Map,o=new Set;for(let a of r.renamedFiles)n.includes(a.to)&&(i.set(a.to,a),o.add(a.from));let s=r.deletedFiles;if(s.length===0)return[...i.values()].sort((a,c)=>a.to.localeCompare(c.to));for(let a of n){if(i.has(a)||!pW(`${e}/${a}`))continue;let c=s.filter(d=>!o.has(d)).filter(d=>JE(d)===JE(a));if(c.length===0)continue;let u=ve(e,a),l=c.map(d=>({from:d,to:a,similarity:xW(bW({projectRoot:e,base:t,relativePath:d})??"",u)})).sort((d,m)=>m.similarity-d.similarity)[0];l&&l.similarity>=.45&&(i.set(a,l),o.add(l.from))}return[...i.values()].sort((a,c)=>a.to.localeCompare(c.to))}function CW(e){let t=new Set,n=new Map,r=new Set;for(let i of e.flatMap(o=>rI(o))){let[o,s,a]=i.split(" ");if(!(!o||!s)){if(o.startsWith("R")&&a){t.add(a),n.set(a,{from:s,to:a,similarity:Number(o.slice(1))/100});continue}t.add(s),o.startsWith("D")&&r.add(s)}}return{changedFiles:[...t],renamedFiles:[...n.values()],deletedFiles:[...r]}}function xW(e,t){let n=new Set(XE(e)),r=new Set(XE(t));if(n.size===0&&r.size===0)return 1;if(n.size===0||r.size===0)return 0;let i=0;for(let o of n)r.has(o)&&(i+=1);return 2*i/(n.size+r.size)}function XE(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function rI(e){return e.split(`
346
- `).map(t=>t.trim()).filter(t=>t.length>0)}function RW(e,t){let n=iI(e),r=[];for(let i of t){let o=n(i);o&&!e.isIgnored(o)&&r.push(o)}return r}function EW(e,t){let n=iI(e),r=[];for(let i of t){let o=n(i.file);o&&!e.isIgnored(o)&&r.push({...i,file:o})}return oI(r)}function iI(e){let t=e.all(`SELECT relative_path FROM documents
347
- ORDER BY id`).map(r=>r.relative_path),n=new Map(t.map(r=>[r,r]));return r=>{let i=r.replace(/\\/g,"/"),o=n.get(i);return o||(t.find(s=>s.endsWith(i))??null)}}function QE(e){let t=[],n=null;for(let r of e.split(`
348
- `)){if(r.startsWith("+++ ")){n=IW(r.slice(4).trim());continue}if(!n||!r.startsWith("@@ "))continue;let i=/@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(r);if(!i)continue;let o=Math.max(0,Number(i[1])-1),s=i[2]===void 0?1:Number(i[2]);t.push({file:n,startLine:o,endLine:Math.max(o,o+Math.max(s,1)-1)})}return t}function IW(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function oI(e){let t=new Set,n=[];for(let r of e){let i=`${r.file}:${r.startLine}:${r.endLine}`;t.has(i)||(t.add(i),n.push(r))}return n}function wW(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(r=>yp(e.startLine,e.endLine,r.startLine,r.endLine))}function LW(e,t,n){let r=new Map,i=[],o=sI(e),s=kW(n);for(let a of t){let c=o.get(a.file)??[];if(c.some(d=>yp(d.startLine,d.endLine,a.startLine,a.endLine)))continue;let u=s.get(a.file)??[],l=AW(u,a);if(l){let d=c.find(m=>m.startLine>=l.startLine&&m.startLine<=l.endLine);if(d){r.set(d.symbolId,d),i.push(up(a,"ast-widened"));continue}}if(u.length===0){let d=[...c].filter(m=>m.startLine<=a.startLine).sort((m,p)=>p.startLine-m.startLine||m.endLine-p.endLine)[0];if(d){r.set(d.symbolId,d),i.push(up(a,"nearest-preceding"));continue}}i.push(up(a,"unattributed"))}return{definitions:[...r.values()],notes:i}}function PW(e,t,n,r){let i=sI(n),o=[],s=[],a=[...new Set(t.map(c=>c.relativePath))];for(let c of a){let u=r.get(c)??[];if(u.length===0)continue;let l=i.get(c)??[];for(let d of u)l.some(m=>yp(m.startLine,m.endLine,d.startLine,d.endLine))||o.push(d);o.some(d=>d.file===c)&&s.push(...DW(e,c))}return LW(t,o,s)}function DW(e,t){let n=J(e,t);return n?n.rootNode.namedChildren.filter(MW).map(r=>({file:t,startLine:r.startPosition.row,endLine:r.endPosition.row})).filter(r=>r.endLine>=r.startLine):[]}function MW(e){return e.endPosition.row<e.startPosition.row?!1:!new Set(["import_statement","comment"]).has(e.type)}function TW(e){let t=new Map;for(let n of e)t.set(n.symbolId,n);return[...t.values()]}function sI(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath)??[];r.push(n),t.set(n.relativePath,r)}return t}function kW(e){let t=new Map;for(let n of e){let r=t.get(n.file)??[];r.push(n),t.set(n.file,r)}return t}function AW(e,t){return e.filter(n=>n.startLine<=t.startLine&&n.endLine>=t.endLine).sort((n,r)=>n.endLine-n.startLine-(r.endLine-r.startLine))[0]}function up(e,t){return{file:e.file,startLine:e.startLine,endLine:e.endLine,method:t}}function yp(e,t,n,r){return e<=r&&n<=t}function FW(e,t,n,r,i,o,s,a,c){let u=Math.max(a,o.size,s.size);if(!HW(t,u))return;let l=T(t.symbol);r.push({symbol:t.symbol,shortName:l,file:t.relativePath,startLine:t.startLine,endLine:t.endLine,fanIn:u});for(let d of c)dp(e,n,i,d,l);for(let d of o)dp(e,n,i,d,l);for(let d of s)dp(e,n,i,d,l)}function ZE(e,t,n){try{return{values:n(),status:{tier:e,state:"complete",attemptedSymbols:t}}}catch(r){return{values:new Map,status:{tier:e,state:"failed",attemptedSymbols:t,reason:_W(r)}}}}function NW(e){return["semantic-consumers","source-fallback-consumers"].map(t=>{let n=e.map(o=>o.evidenceTiers?.find(s=>s.tier===t)??{tier:t,state:"failed",attemptedSymbols:0,reason:"isolated diff-impact batch omitted its evidence-tier status"}),r=n.reduce((o,s)=>o+s.attemptedSymbols,0),i=[...new Set(n.filter(o=>o.state==="failed").map(o=>o.reason))];return i.length===0?{tier:t,state:"complete",attemptedSymbols:r}:{tier:t,state:"failed",attemptedSymbols:r,reason:i.join("; ").slice(0,500)}})}function aI(){return[{tier:"semantic-consumers",state:"complete",attemptedSymbols:0},{tier:"source-fallback-consumers",state:"complete",attemptedSymbols:0}]}function _W(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 OW(e,t){if(t.length===0)return new Map;let n=e.all(`SELECT m.symbol_id, COUNT(DISTINCT c.document_id) AS fan_in
349
- FROM mentions m
350
- JOIN chunks c ON m.chunk_id = c.id
351
- WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
352
- AND m.role != 1
353
- GROUP BY m.symbol_id`,...t);return new Map(n.map(r=>[r.symbol_id,r.fan_in]))}function BW(e,t,n){if(t.length===0||n.length===0)return new Map;let r=e.all(`SELECT DISTINCT m.symbol_id, ref_d.relative_path
354
- FROM mentions m
355
- JOIN chunks c ON m.chunk_id = c.id
356
- JOIN documents ref_d ON c.document_id = ref_d.id
357
- WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
358
- AND m.role != 1
359
- AND ref_d.relative_path NOT IN (${n.map(()=>"?").join(",")})
360
- ${e.pathExclusionsFor("ref_d")}`,...t,...n),i=new Map;for(let o of r){let s=i.get(o.symbol_id);s||(s=new Set,i.set(o.symbol_id,s)),s.add(o.relative_path)}return i}function dp(e,t,n,r,i){if(e.isIgnored(r)||t.has(r))return;let o=n.get(r);o||(o=new Set,n.set(r,o)),o.add(i)}function $W(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function jW(e){return!(fe(e.symbol)||e.parentTypeName!==null&&!Qe(e.symbol))}function HW(e,t){return Qe(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}var UW=5;function qW(e,t={}){let{base:n="HEAD",minContainment:r=.7,minCallees:i=3,minSiteCoverage:o=.4,maxHelpers:s=Number.POSITIVE_INFINITY,limit:a=20,scanLimit:c}=t,u=t.semantic!==!1,l=t.diffPlan??to(e,{base:n}),d={available:l.note!==mp,base:n,changedFiles:l.changedFiles,helpersChecked:0,skipped:[],findings:[],...l.note?{note:l.note}:{}};if(!d.available||l.changedFiles.length===0)return d;let m=new H(e),p=new Set(l.changedFiles),f=new Map(l.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?JW(t.baseContentAt):hp({projectRoot:e.config.projectRoot,base:n,preloadPaths:tI(l)}),h=YW(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 y=h.definitions.slice(0,s);h.definitions.length>s&&(d.note=`helper scoring capped at ${s} of ${h.definitions.length} new symbols`);let S=m.calleeMap(y,{semantic:u}),b=y.map(R=>({def:R,callees:Kc((S.get(R.symbolId)??[]).map(E=>E.symbol))})),x=Ji(e),v,C=()=>(v??=x.calleeIndex({minCallees:Math.min(3,i),scanLimit:c,semantic:u}),v);for(let{def:R,callees:E}of b){let w=T(R.symbol);if(E.size<i){d.skipped.push({helperShortName:w,helperFile:R.relativePath,reason:`fewer than ${i} meaningful callees \u2014 too small to score`});continue}let I=C(),k=VW(E,I);if(k===0){d.skipped.push({helperShortName:w,helperFile:R.relativePath,reason:"helper callee pattern is all project-wide infrastructure \u2014 too generic to score"});continue}let D=XW(e,R.symbolId);if(D.length===0){d.skipped.push({helperShortName:w,helperFile:R.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}d.helpersChecked+=1;let F=GW({candidateIndex:I,changed:p,helperCallees:E,helperFile:R.relativePath,helperSymbol:R.symbol,minContainment:r,minSiteCoverage:o,migratedFiles:D});F.length!==0&&(F.sort((P,A)=>cI(A.migrationScope)-cI(P.migrationScope)||A.containment-P.containment||A.siteCoverage-P.siteCoverage||P.file.localeCompare(A.file)),d.findings.push({helperSymbol:R.symbol,helperShortName:w,helperFile:R.relativePath,helperShape:"specific-callee-cluster",helperCalleeCount:E.size,specificHelperCalleeCount:k,migratedFiles:D.sort(),leftovers:F.slice(0,UW)}))}return d.findings.sort((R,E)=>(E.leftovers[0]?.containment??0)-(R.leftovers[0]?.containment??0)||R.helperFile.localeCompare(E.helperFile)),d.findings=d.findings.slice(0,a),d}function GW(e){let t=[],n=zW(e.helperSymbol,e.helperFile,e.migratedFiles),r=new Set;for(let i of e.helperCallees)for(let o of e.candidateIndex.candidateIndexesByCallee.get(i)??[])r.add(o);for(let i of r){let o=e.candidateIndex.corpus[i];if(o.symbol===e.helperSymbol||e.changed.has(o.file)||o.callees.has(e.helperSymbol))continue;let s=$R(e.helperCallees,o.callees);if(s<e.minContainment)continue;let a=[...e.helperCallees].filter(l=>o.callees.has(l)),c=o.callees.size===0?0:a.length/o.callees.size;if(c<e.minSiteCoverage||!a.some(l=>(e.candidateIndex.docFreq.get(l)??0)<=e.candidateIndex.ubiquityThreshold))continue;let u=KW(n,o.symbol,o.file);t.push({symbol:o.symbol,shortName:T(o.symbol),file:o.file,...u,containment:s,siteCoverage:c,uniqueSiteCalleeCount:Math.max(0,o.callees.size-a.length),sharedCallees:a.map(T).sort()})}return t}function cI(e){return e==="same-scope"?2:e==="unknown"?1:0}function zW(e,t,n){let r=new Set([...bp(t),...Sp(G(e))]);for(let i of n)for(let o of bp(i))r.add(o);return r}function KW(e,t,n){let r=new Set([...bp(n),...Sp(G(t))]);if(e.size===0||r.size===0)return{migrationScope:"unknown",migrationScopeReasons:["insufficient path/name tokens to infer migration scope"]};let i=[...r].filter(o=>e.has(o)).sort();return i.length>0?{migrationScope:"same-scope",migrationScopeReasons:[`shares migration-scope token(s): ${i.slice(0,5).join(", ")}`]}:{migrationScope:"possible-subtype",migrationScopeReasons:["no path/name tokens shared with the helper or already migrated files"]}}var WW=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 bp(e){return Sp(e.replace(/\.[^.]+$/,""))}function Sp(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!WW.has(t))}function VW(e,t){let n=0;for(let r of e)(t.docFreq.get(r)??0)<=t.ubiquityThreshold&&(n+=1);return n}function YW(e,t,n,r){let i=[];for(let o of e.productionCallableDefinitions({files:[...t],requireFunctionLikeSymbol:!0})){if(!t.has(o.relativePath))continue;let s=n.get(o.relativePath)??o.relativePath,a=r(s);if(a.state==="unavailable")return{definitions:[],unavailable:a};(a.state==="absent"||!new RegExp(`\\b${Ie(o.leaf)}\\b`).test(a.content))&&i.push(o)}return{definitions:i}}function JW(e){return t=>{let n=e(t);return n===null?{state:"absent"}:{state:"present",content:n}}}function XW(e,t){return e.all(`SELECT DISTINCT ref_d.relative_path
361
- FROM mentions m
362
- JOIN chunks c ON m.chunk_id = c.id
363
- JOIN documents ref_d ON c.document_id = ref_d.id
364
- WHERE m.symbol_id = ?
365
- AND m.role != 1
366
- ${e.pathExclusionsFor("ref_d")}`,t).map(r=>r.relative_path)}import{execFileSync as QW}from"child_process";var pI=2e3,rl=50,ZW=64,eV=8,tV=3,nV=2160*60*60,rV=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,iV=3,oV=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,sV=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function aV(e){let t=te(e,{clearGroups:["whole-project"]});return(n,r,i)=>{let o=i??vp(n.config.projectRoot);if(!o)return null;let s=t.has(n)?t.get(n,()=>({head:"",value:null})):null;return s&&s.head===o?s.value:(t.invalidate(n),t.get(n,()=>({head:o,value:r(n.config.projectRoot,o)})).value)}}function il(e){let t=te(e,{clearGroups:["whole-project"]});return(n,r,i,o)=>{let s=o??vp(n.config.projectRoot);if(!s)return null;let a=t.has(n)?t.get(n,()=>({head:"",values:new Map})):null;(!a||a.head!==s)&&t.invalidate(n);let c=t.get(n,()=>({head:s,values:new Map}));if(c.values.has(r))return c.values.get(r)??null;let u=i(n.config.projectRoot,s);return c.values.set(r,u),u}}var cV=il("git-commit-history");function Kt(e,t={}){let n=t.historyMode??"bounded",r=t.head;return{capability:i=>lV(e,i,r),commitHistory:()=>Rs(e,n,r),fileChurn:()=>mV(e,n,r),changeAmplification:()=>pV(e,n,r),trackedFiles:()=>gV(e,r),fileAddRecords:()=>yV(e,n,r),coChangePairs:(i={})=>EV(e,i,n,r),coChangePairsForFiles:(i,o={})=>hI(e,i,o,n,r),directionalCoChangePairsForFiles:(i,o={})=>IV(e,i,o,n,r)}}function Rs(e,t="bounded",n){return cV(e,no(t),(r,i)=>uV(r,i,t),n)}function lV(e,t,n){let r=n??vp(e.config.projectRoot);return r?{slot:t,available:!0,head:r}:{slot:t,available:!1,head:null,reason:"git history is unavailable for this project"}}function vp(e){try{return dt(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function dt(e,t){return QW("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"})}function uV(e,t,n){let r;try{r=dt(e,["log","--no-merges","--name-only",...ol(n),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}return{head:t,...Rp(r,rl)}}function dV(e){return rV.test(e.subject)}function mV(e,t,n){let r=Rs(e,t,n);if(!r)return null;let i=new Map;for(let o of r.commits){let s=dV(o);for(let a of o.files){let c=i.get(a)??{changes:0,fixChanges:0,lastChangedAt:0};c.changes+=1,s&&(c.fixChanges+=1),o.timestamp>c.lastChangedAt&&(c.lastChangedAt=o.timestamp),i.set(a,c)}}return i}function pV(e,t,n){let r=Rs(e,t,n);if(!r||r.commits.length===0)return null;let i=r.commits.map(o=>o.files.length).filter(o=>o>0).sort((o,s)=>o-s);return i.length===0?null:{medianFilesPerCommit:lI(i,.5),p90FilesPerCommit:lI(i,.9),commitsAnalyzed:i.length}}function lI(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var fV=aV("git-tracked-files");function gV(e,t){return fV(e,n=>{try{let r=dt(n,["ls-files"]);return new Set(r.split(`
367
- `).map(i=>i.trim()).filter(i=>i!==""))}catch{return null}},t)}var hV=il("git-file-adds"),uI="__git__/file-adds",dI=ft({kind:"git-file-adds",invalidation:Ne("git-file-adds"),serialize:SV,deserialize:vV});function fI(e){return Kt(e).fileAddRecords()}function yV(e,t,n){let r=no(t);return hV(e,r,(i,o)=>bV(e,i,o,t),n)}function bV(e,t,n,r){let i=dI.read(e,mI(r),n);if(i)return i;let o=CV(t,r);return o&&dI.write(e,mI(r),n,o),o}function SV(e){return JSON.stringify([...e.entries()])}function vV(e){if(!e)return null;try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=new Map;for(let r of t){if(!Array.isArray(r)||r.length!==2||typeof r[0]!="string")return null;let i=r[1];if(!i||typeof i.commitsAgo!="number"||!Number.isFinite(i.commitsAgo)||typeof i.addedAt!="number"||!Number.isFinite(i.addedAt))return null;n.set(r[0],{commitsAgo:i.commitsAgo,addedAt:i.addedAt})}return n}catch{return null}}function CV(e,t){let n;try{n=dt(e,["log","--no-merges","--find-renames","--name-status",...ol(t),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let r=new Map,i=new Map,o=-1;for(let s of n.split("")){if(s.trim()==="")continue;o+=1;let a=s.indexOf(`
368
- `),c=a>=0?s.slice(0,a):s,[,u]=c.split("\0"),l=Number(u)||0;if(!(a<0))for(let d of s.slice(a+1).split(`
369
- `)){let m=xV(d);if(!m)continue;if(m.status==="R"&&m.from&&m.to){let f=i.get(m.to)??new Set([m.to]);i.set(m.from,f);continue}if(m.status!=="A"||!m.to)continue;let p={commitsAgo:o,addedAt:l};r.set(m.to,p);for(let f of i.get(m.to)??[])r.set(f,p)}}return r}function xV(e){let t=e.trim().split(" "),n=t[0]??"";if(!n)return null;let r=n[0]??"";if(r==="R"){let o=t[1],s=t[2];return o&&s?{status:r,from:o,to:s}:null}let i=t[1];return i?{status:r,to:i}:null}var gI=il("git-co-change-pairs"),RV=il("git-directional-co-change-pairs");function EV(e,t,n,r){let i=`all\0${no(n)}\0${Cp(t)}`,o=gI(e,i,()=>{let s=Rs(e,n,r);return s?xp(s,t):null},r);return o&&[...o]}function hI(e,t,n,r,i){if(t.size===0)return[];let o=`files\0${no(r)}\0${yI(t)}\0${Cp(n)}`,s=gI(e,o,()=>{let a=Rs(e,r,i);return a?xp(a,n,t):null},i);return s&&[...s]}function IV(e,t,n,r,i){if(t.size===0)return[];let o=n.maxFilesPerCommit??rl;if(t.size>ZW)return hI(e,t,n,r,i);let s=`directional\0${no(r)}\0${yI(t)}\0${Cp({...n,maxFilesPerCommit:o})}`,a=RV(e,s,(c,u)=>{let l=wV(c,u,t,o,r);return l?xp(l,n,t):null},i);return a&&[...a]}function Cp(e){let t=e.minTogether??4,n=e.minConfidence??.6,r=e.maxFilesPerCommit??rl;return`${t}\0${n}\0${r}`}function yI(e){return[...e].sort().join("\0")}function xp(e,t,n){let{minTogether:r=4,minConfidence:i=.6,maxFilesPerCommit:o=rl}=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=DV(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 y=`${m[g]}\0${m[h]}`,S=a.get(y)??{together:0,focusedTogether:0,broadTogether:0,lastTogetherAt:0,timestamps:[],subjects:[]};S.together+=1,p?S.broadTogether+=1:S.focusedTogether+=1,d.timestamp>S.lastTogetherAt&&(S.lastTogetherAt=d.timestamp),S.timestamps.push(d.timestamp),S.subjects.push(d.subject),a.set(y,S)}}let u=[],l=c-nV;for(let[d,m]of a){let p=m.together;if(p<r)continue;let[f,g]=d.split("\0"),h=s.get(f)??p,y=s.get(g)??p,S=Math.max(p/h,p/y);if(S<i)continue;let b=m.broadTogether/p,x=m.timestamps.filter(v=>v>=l).length;u.push({fileA:f,fileB:g,together:p,confidence:S,changesA:h,changesB:y,focusedTogether:m.focusedTogether,broadTogether:m.broadTogether,broadCommitRatio:b,lastTogetherAt:m.lastTogetherAt,recentTogether:x,commitScope:TV(m.broadTogether,p),recency:x>0?"recent":"stale",subjectContext:kV(m.subjects)})}return u.sort((d,m)=>m.together-d.together||m.confidence-d.confidence||d.fileA.localeCompare(m.fileA)),u}function wV(e,t,n,r,i){let o;try{o=LV(e,i)}catch{return null}if(o.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:0};let s;try{s=dt(e,["log","--no-merges","--format=%H",...ol(i),"--",...[...n].sort()])}catch{return null}let a=new Set(o.map(m=>m.hash)),c=s.split(`
370
- `).map(m=>m.trim()).filter(m=>m!==""&&a.has(m)),u=PV(e,o,r);if(c.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:u};let l;try{l=dt(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...c])}catch{return null}let d=Rp(l,r);return{head:t,...d,newestAnalyzedAt:u}}function LV(e,t){return dt(e,["log","--no-merges","--format=%H%x00%ct",...ol(t)]).split(`
371
- `).map(r=>r.trim()).filter(r=>r!=="").map(r=>{let[i,o]=r.split("\0");return{hash:i??"",timestamp:Number(o)||0}}).filter(r=>r.hash!=="")}function ol(e){return e==="full"?[]:["-n",String(bI())]}function bI(){return Qn(process.env.SCIP_QUERY_GIT_HISTORY_MAX_COMMITS)??pI}function no(e){return e==="full"?"full":`bounded:${bI()}`}function mI(e){let t=no(e);return t===`bounded:${pI}`?uI:`${uI}:${t}`}function PV(e,t,n){for(let i=0;i<t.length;i+=20){let o=t.slice(i,i+20),s;try{s=dt(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=Rp(s,n);if(a.commits.length>0)return a.commits[0].timestamp}return 0}function Rp(e,t){let n=[],r=0;for(let i of e.split("")){if(i.trim()==="")continue;let o=i.indexOf(`
372
- `),s=o>=0?i.slice(0,o):i,[a,c,u]=s.split("\0");if(!a||!c)continue;let l=o>=0?i.slice(o+1).split(`
373
- `).map(d=>d.trim()).filter(d=>d!==""):[];if(l.length>t){r+=1;continue}n.push({hash:a,timestamp:Number(c)||0,subject:u??"",files:l})}return{commits:n,skippedBulkCommits:r}}function DV(e){return e.length>=eV?!0:MV(e).size>=tV}function MV(e){let t=new Set;for(let n of e){let r=n.indexOf("/");t.add(r>=0?n.slice(0,r):".")}return t}function TV(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function kV(e){let t=new Set,n=[],r=[];for(let i of e){!r.includes(i)&&r.length<iV&&r.push(i);for(let o of AV(i))t.add(o);for(let o of i.match(oV)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:r,externalIssueLabelStatus:"unavailable"}}function AV(e){let t=new Set,n=sV.exec(e)?.[1]?.toLowerCase();return n&&t.add(FV(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 FV(e){return e==="feat"?"feature":e}function NV(e,t){return t==="config-code"||t==="doc-code"||t==="generated-artifact"||t==="schema-script"?{actionTier:"signal",tierReason:`${t} partner: configuration, documentation, schema, and generated files change alongside many sources`}:e.focusedTogether===0?{actionTier:"signal",tierReason:"every shared commit was a broad sweep; no focused change touched both files"}:e.recency==="stale"&&e.focusedTogether<=2?{actionTier:"signal",tierReason:"at most two focused co-changes, none of them recent"}:{actionTier:"direct",tierReason:`${e.focusedTogether} focused co-change(s)`}}var SI=/(?:^|\/)(?: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 Es(e,t,n={}){let{minTogether:r=4,minConfidence:i=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=Kt(e,{historyMode:n.historyMode,...n.head?{head:n.head}:{}}),c=a.commitHistory(),u=t!==void 0,l=a.coChangePairs({minTogether:u?Math.min(r,2):r,minConfidence:u?0:i,maxFilesPerCommit:s});if(!c||!l)return{available:!1,commitsAnalyzed:0,findings:[]};let d=typeof n.scanLimit=="number"?l.slice(0,n.scanLimit):l,m=_e(e),p=EI(e),f=BV(e,m,p),g=n.includeLinked===!0||u,h=[];for(let y of d){if(SI.test(y.fileA)||SI.test(y.fileB)||!vI(e,y.fileA)||!vI(e,y.fileB)||u&&!y.fileA.includes(t)&&!y.fileB.includes(t)||!u&&(U(y.fileA)==="test"||U(y.fileB)==="test"||UV(y.fileA,y.fileB)||jV(y.fileA,y.fileB)))continue;let S=f(y.fileA,y.fileB);if(!g&&S)continue;let b=_V(y.fileA,y.fileB),x=OV(y,b,S);if(h.push({...y,structurallyLinked:S,partnerClass:b.partnerClass,partnerClassReasons:b.reasons,...NV(y,b.partnerClass),...x?{declaredCouplingSuggestion:x}:{}}),h.length>=o)break}return{available:!0,commitsAnalyzed:c.commits.length,findings:h}}function vI(e,t){return wt(e.config.projectRoot,t)}function _V(e,t){let n=xI(e),r=xI(t),i=[],o=c=>{i.includes(c)||i.push(c)},s=(c,u)=>n.tags.has(c)&&r.tags.has(u)||n.tags.has(u)&&r.tags.has(c);if(n.tags.has("generated")||r.tags.has("generated"))return o("one side is a generated artifact (migration journal, snapshot, or codegen output) that a tool rewrites whenever its source changes"),{partnerClass:"generated-artifact",reasons:i};if(s("doc","code"))return o("one side is documentation and the other is executable source"),{partnerClass:"doc-code",reasons:i};if(n.tags.has("test")||r.tags.has("test"))return o("one side is classified as a test file"),{partnerClass:"test-code",reasons:i};if(s("schema","script"))return o("schema or contract file changes with a script or generated-code path"),{partnerClass:"schema-script",reasons:i};if(s("model","view"))return o("model or state path changes with a view or component path"),{partnerClass:"model-view",reasons:i};if(s("config","code"))return o("configuration file changes with executable source"),{partnerClass:"config-code",reasons:i};let a=ZV(n.tokens,r.tokens).filter(c=>!XV.has(c));return RI(e,t)||a.length>=2?(o(RI(e,t)?"both files live in the same directory":`files share feature tokens: ${a.slice(0,4).join(", ")}`),{partnerClass:"same-feature",reasons:i}):(o("no specific relationship pattern matched"),{partnerClass:"unknown",reasons:i})}function OV(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!JV.has(t.partnerClass))return;let r=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${e2(r)}`,files:r,reason:`${t.partnerClass} pair changed together ${e.together}x with ${Math.round(e.confidence*100)}% confidence; declare it if future edits should require both sides.`}}function BV(e,t=_e(e),n=EI(e)){return(r,i)=>qV(t,n,r,i)}var $V=/(?:^|\/)(?:locales|i18n)\//i;function CI(e){return $V.test(e)}function jV(e,t){return CI(e)&&CI(t)?!0:HV(e,t)}function HV(e,t){if(!e.endsWith(".json")||!t.endsWith(".json"))return!1;let n=e.lastIndexOf("/"),r=t.lastIndexOf("/");if(n<0||r<0)return!1;let i=e.slice(0,n),o=t.slice(0,r);if(i===o)return!1;let s=e.slice(n+1),a=t.slice(r+1);if(s!==a)return!1;let c=i.lastIndexOf("/"),u=o.lastIndexOf("/"),l=c>=0?i.slice(0,c):"",d=u>=0?o.slice(0,u):"";return l===d}function UV(e,t){let n=e.lastIndexOf("/"),r=t.lastIndexOf("/");if(e.slice(0,n)!==t.slice(0,r))return!1;let i=e.slice(n+1).split(".")[0],o=t.slice(r+1).split(".")[0];return i!==""&&i===o}function EI(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function qV(e,t,n,r){return e.get(n)?.has(r)===!0||e.get(r)?.has(n)===!0?!0:t.some(i=>i.has(n)&&i.has(r))}var GV=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,zV=/(?:^|\/)(?:\.[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,KV=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,WV=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,VV=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,YV=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,JV=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),XV=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 xI(e){let t=e.replace(/\\/g,"/"),n=new Set;return Hc(t)&&n.add("generated"),GV.test(t)&&n.add("doc"),zV.test(t)&&n.add("config"),KV.test(t)&&n.add("schema"),WV.test(t)&&n.add("script"),VV.test(t)&&n.add("model"),YV.test(t)&&n.add("view"),U(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:QV(t)}}function RI(e,t){let n=e.lastIndexOf("/"),r=t.lastIndexOf("/"),i=n>=0?e.slice(0,n):"",o=r>=0?t.slice(0,r):"";return i!==""&&i===o}function QV(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 ZV(e,t){let n=new Set(t);return[...new Set(e.filter(r=>n.has(r)))].sort()}function e2(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}function cl(e,t){let n=t2(e,t)??n2(e,t)??r2(e,t)??i2(e,t);return o2(e,n,t)}function t2(e,t){let n=-1,r=null;for(let i=0;i<=t;i+=1){let o=Ep(e[i]??"");o&&(r===null?(r=o,n=i):o===r&&(r=null,n=-1))}if(r===null||n<0)return null;for(let i=t+1;i<e.length;i+=1)if(Ep(e[i]??"")===r)return{start:n,end:i+1};return{start:n,end:e.length}}function Ep(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function n2(e,t){if(!sl(e[t]??""))return null;let n=t;for(;n>0&&sl(e[n-1]??"");)n-=1;let r=t+1;for(;r<e.length&&sl(e[r]??"");)r+=1;return{start:n,end:r}}function sl(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function r2(e,t){let n=t;for(;n>=0;){let o=e[n]??"";if(al(o)!==null)break;if(Ip(o)!==null)return null;n-=1}if(n<0)return null;let r=al(e[n]??"");if(r===null)return null;let i=n+1;for(;i<e.length;){let o=e[i]??"",s=al(o);if(s!==null){if(s<=r)break;i+=1;continue}if(Ip(o)!==null)break;i+=1}return{start:n,end:i}}function al(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function i2(e,t){let n=e[t]??"";if(wI(n)||n.trim().length===0)return{start:t,end:t+1};let r=t;for(;r>0&&II(e[r-1]??"");)r-=1;let i=t+1;for(;i<e.length&&II(e[i]??"");)i+=1;return{start:r,end:i}}function II(e){return Ip(e)===null}function Ip(e){return e.trim().length===0?"blank":wI(e)?"heading":Ep(e)?"fence":sl(e)?"table":al(e)!==null?"list":null}function wI(e){return/^#{1,6}\s+/.test(e.trim())}function o2(e,t,n){let{start:r,end:i}=t;if(i-r>40){let s=Math.floor(20);r=Math.max(r,n-s),i=Math.min(i,r+40),r=Math.max(t.start,i-40)}let o=e.slice(r,i).join(`
374
- `).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}function ni(e,t){return t.filter(n=>e.includes(n))}var s2=/<!--\s*scip-query:\s*snapshot\s*-->/i;function LI(e,t){if((e.config.docs?.snapshotPaths??[]).some(i=>fr(i,t)))return!0;let r=V(e,t);return r.length>0&&s2.test(r)}var PI={classifyCitation:c2,citationContexts:l2,citationKindLabel:d2,citationRemediation:m2,referenceTargets:p2,hasLineAnchoredCitation:a2};function a2(e){return e.some(t=>(t.lineReferences?.length??0)>0)}function c2(e){let t=e.join(`
375
- `).toLowerCase(),n=[],r=ni(t,[".scipquery","declaredcouplings","suppression","suppressions","config","configuration","json"]);if(r.length>0)return n.push(`configuration/example terms near citation: ${r.join(", ")}`),{citationKind:"configuration-example",actionTier:"support",reasons:n};let i=ni(t,["accepted","intentional","intentionally","retained","historical"]);if(i.length>0)return n.push(`intentional-record terms near citation: ${i.join(", ")}`),{citationKind:"intentional-record",actionTier:"support",reasons:n};let o=ni(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 l2(e,t,n){let r=V(e,t);if(!r&&!wt(e.config.projectRoot,t))return[];let i=r.split(/\r?\n/),o=n.flatMap(u2),s=[];for(let a=0;a<i.length;a+=1){let c=i[a]??"";o.some(u=>c.includes(u))&&s.push(cl(i,a))}return s}function u2(e){let t=e.split("/");return[e,`./${e}`,t.slice(-3).join("/"),t.slice(-2).join("/")].filter((n,r,i)=>n.length>0&&i.indexOf(n)===r)}function d2(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 m2(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 p2(e,t,n){let r=el(n),i=new Set;for(let o of t)f2(e,o,r.get(o)??[])&&i.add(o);return i}function f2(e,t,n){if(!g2.test(t)||!wt(e.config.projectRoot,t))return!0;if(n.length===0)return!1;let r=ve(e.config.projectRoot,t,{inputKind:"changed source file"}).split(/\r?\n/),i=h2(r);for(let o of n)for(let s=o.startLine;s<=o.endLine;s+=1)if((r[s]??"").trim()!==""&&!i.has(s))return!0;return!1}var g2=/\.(?:[cm]?[jt]sx?)$/i;function h2(e){let t=new Set,n=!1;for(let r=0;r<e.length;r+=1){let i=e[r].trim();!n&&y2(i)&&(n=!0),n&&(t.add(r),i.endsWith(";")&&(n=!1))}return t}function y2(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}var DI=ft({kind:"doc-path-evidence",invalidation:Ne("doc-path-evidence"),serialize:T2,deserialize:k2}),Is=/\.(?:md|mdx|rst|txt)$/i;function b2(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var S2=3,v2=/([A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6})(?::([1-9][0-9]*))?\b/g;function C2(e,t={}){let{doc:n,limit:r=20,minCoupling:i=S2,includeSnapshotExcluded:o=!1}=t,s=I2(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&&!w2(e,c)||n!==void 0&&!wt(e.config.projectRoot,c))continue;let u=LI(e,c);if(u&&!o)continue;let{value:l,estimated:d}=x2(e,c,s.changeTimes.get(c)),m=R2(e,c),p=new Map,{resolved:f,broken:g,citations:h}=P2(e,c,s.tracked,s.trackedBySuffix,s.everSeenInHistory),y=new Map(h.map(b=>[b.file,b]));for(let b of f){if(b===c||Is.test(b))continue;let x=(s.changeTimes.get(b)??[]).filter(C=>C>l).length;if(x===0)continue;let v=y.get(b);p.set(b,{file:b,evidence:"reference",coChanges:0,changesSinceDocUpdate:x,...wp("reference",m,v?.contexts),citationContexts:v?.contexts,citedLines:v?.lineReferences})}for(let[b,x]of s.coupling.get(c)??[]){if(x<i||!s.tracked.has(b))continue;let v=(s.changeTimes.get(b)??[]).filter(R=>R>l).length;if(v===0)continue;let C=p.get(b);C?(C.evidence="both",C.coChanges=x,Object.assign(C,wp("both",m,C.citationContexts))):p.set(b,{file:b,evidence:"co-change",coChanges:x,changesSinceDocUpdate:v,...wp("co-change",m)})}if(p.size===0&&g.length===0)continue;let S=[...p.values()].sort((b,x)=>x.changesSinceDocUpdate-b.changesSinceDocUpdate);a.push({doc:c,docLastChangedAt:l,staleness:S.reduce((b,x)=>b+x.changesSinceDocUpdate,0)+g.length*10,subjects:S.slice(0,8),brokenReferences:g,...u?{snapshotExcluded:!0}:{},...d?{docLastChangedAtEstimated:!0}:{}})}return a.sort((c,u)=>u.staleness-c.staleness),{available:!0,commitsAnalyzed:s.historyCommitCount,docsScanned:s.docFiles.length,findings:a.slice(0,r)}}function x2(e,t,n){if(n&&n.length>0)return{value:Math.max(...n),estimated:!1};try{return{value:Math.floor(js(e.config.projectRoot,t).mtimeMs/1e3),estimated:!0}}catch(r){if(wt(e.config.projectRoot,t))throw r;return{value:0,estimated:!1}}}function R2(e,t){let n=V(e,t).slice(0,6e3);if(!n)return{docIntent:"unknown",reasons:["doc text unavailable"]};let r=`${t}
376
- ${n}`.toLowerCase(),i=ni(r,["historical note","historical record","history note","retrospective","postmortem","post-mortem","archived","archive","previously","legacy","recorded","record of","snapshot","as of","migration note","decision record"]);if(i.length>0)return{docIntent:"historical-note",reasons:[`historical-note terms: ${i.join(", ")}`]};let o=ni(r,["current","standard","standards","must","should","policy","guide","guidance","workflow","contract","invariant","source of truth"]);return o.length>0?{docIntent:"current-guidance",reasons:[`current-guidance terms: ${o.join(", ")}`]}:{docIntent:"unknown",reasons:["no current-guidance or historical-note markers found"]}}function wp(e,t,n=[]){let r=e==="co-change"||n.length===0?null:PI.classifyCitation(n);return{actionTier:E2(e,t.docIntent,r?.actionTier),docIntent:t.docIntent,docIntentReasons:t.reasons,...r?{citationKind:r.citationKind,citationKindReasons:r.reasons}:{}}}function E2(e,t,n){return t==="historical-note"?"support":n||(e==="co-change"?"signal":"direct")}function I2(e,t){let n=Kt(e,{historyMode:t}),r=n.commitHistory();if(!r)return null;let i=n.trackedFiles()??new Set,o=new Map,s=new Map,a=new Set;for(let c of r.commits){let u=[...new Set(c.files)],l=u.filter(m=>Is.test(m)),d=u.filter(m=>!Is.test(m));for(let m of u){a.add(m);let p=o.get(m)??[];p.push(c.timestamp),o.set(m,p)}for(let m of l){let p=s.get(m);p||(p=new Map,s.set(m,p));for(let f of d)p.set(f,(p.get(f)??0)+1)}}return{changeTimes:o,coupling:s,docFiles:[...i].filter(c=>Is.test(c)),everSeenInHistory:a,historyCommitCount:r.commits.length,tracked:i,trackedBySuffix:L2(i)}}function w2(e,t){return Is.test(t)&&!b2(t)&&wt(e.config.projectRoot,t)}function L2(e){let t=new Map;for(let n of e){let r=n.split("/");for(let i of[2,3]){if(r.length<i)continue;let o=r.slice(-i).join("/"),s=t.get(o)??[];s.push(n),t.set(o,s)}}return t}function P2(e,t,n,r,i){let o=new Set,s=new Set,a=D2(e,t);if(!a)return{resolved:o,broken:[],citations:[]};let c=a.candidates,u=a.contextsByCandidate,l=a.lineReferencesByCandidate,d=new Map,m=new Map,p=(f,g)=>{let h=u.get(g);if(h&&h.length>0){let S=d.get(f)??[];S.push(...h),d.set(f,MI(S).slice(0,3))}let y=l.get(g);y&&y.length>0&&m.set(f,Lp([...m.get(f)??[],...y]))};for(let f of c){if(n.has(f)){o.add(f),p(f,f);continue}let g=r.get(f);if(g&&g.length===1){o.add(g[0]),p(g[0],f);continue}g&&g.length>1||i.has(f)&&s.add(f)}return{resolved:o,broken:[...s],citations:[...d].map(([f,g])=>({file:f,contexts:g,lineReferences:m.get(f)}))}}function D2(e,t,n){let r=n;if(r===void 0&&(r=V(e,t),!r&&!wt(e.config.projectRoot,t)))return null;let i=Pt(e,t,r),o=DI.read(e,t,i);if(o)return o;let s=M2(r);return DI.write(e,t,i,s),s}function M2(e){let t=e.split(/\r?\n/),n=new Set,r=new Map,i=new Map;for(let o=0;o<t.length;o+=1){let s=t[o]??"";for(let a of s.matchAll(v2)){let c=(a[1]??"").replace(/^\.?\//,"");if(c.length===0)continue;n.add(c);let u=a[2]?Number(a[2]):null;u!==null&&Number.isSafeInteger(u)&&i.set(c,Lp([...i.get(c)??[],u]));let l=cl(t,o);if(l.length===0)continue;let d=r.get(c)??[];d.push(l),r.set(c,MI(d).slice(0,3))}}return{candidates:[...n],contextsByCandidate:r,lineReferencesByCandidate:i}}function T2(e){let t={candidates:e.candidates,contextsByCandidate:[...e.contextsByCandidate.entries()],lineReferencesByCandidate:[...e.lineReferencesByCandidate.entries()]};return JSON.stringify(t)}function k2(e){try{let t=JSON.parse(e);if(!ng(t))return null;let n=lo(t.candidates),r=F2(t.contextsByCandidate),i=A2(t.lineReferencesByCandidate);return!n||!r?null:{candidates:n,contextsByCandidate:new Map(r),lineReferencesByCandidate:new Map(i??[])}}catch{return null}}function A2(e){if(e===void 0)return[];if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string"||!Array.isArray(n[1]))return null;let r=[];for(let i of n[1]){if(typeof i!="number"||!Number.isSafeInteger(i))return null;r.push(i)}t.push([n[0],Lp(r)])}return t}function F2(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string")return null;let r=lo(n[1]);if(!r)return null;t.push([n[0],r])}return t}function MI(e){let t=[];for(let n of new Set(e))t.some(r=>N2(r,n))||t.push(n);return t}function Lp(e){return[...new Set(e)].sort((t,n)=>t-n)}function N2(e,t){if(e===t)return!0;let n=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),r=t.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),i=Math.min(n.length,r.length);if(i===0)return!1;if(i<3)return e.includes(t)||t.includes(e);let o=new Set(r),s=n.filter(a=>o.has(a)).length;return s>=3&&s/i>=.6}import{createHash as _2}from"crypto";var O2=3;function Pp(e,t={}){return ll(e,t).groups}function ll(e,t={}){let{scope:n,maxLoc:r=15,minLoc:i=O2,limit:o,scanLimit:s}=t,a=fI(e),c=H2(e,{scope:n,maxLoc:r,scanLimit:s}).map(d=>U2(e,d,a,i)).filter(d=>d!==null),{groups:u,exclusions:l}=$2(e,FI(c));return{groups:o?u.slice(0,o):u,exclusions:l}}var B2=/^(?:GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD|default|loader|action|load|actions)$/;function $2(e,t){let n=new Map,r=(o,s)=>{let a=n.get(o);a?a.count+=1:n.set(o,{reason:o,detail:s,count:1})},i=[];for(let o of t){let s=[];for(let a of o.functions){let c=j2(e,a);if(c){r(c.reason,c.detail);continue}s.push(a)}s.length<2||new Set(s.map(a=>a.file)).size<2||i.push({hash:o.hash,canonical:s[0],functions:s})}return{groups:i,exclusions:[...n.values()].sort((o,s)=>o.reason.localeCompare(s.reason))}}function j2(e,t){let n=G(t.symbol);return n.startsWith("<")&&n.endsWith(">")?{reason:"synthetic-members",detail:"duplicate constructors and other compiler-named members every class carries"}:U(t.file)==="test"?{reason:"test-file-members",detail:"duplicate bodies in test files (fixture reuse, not product duplication)"}:B2.test(n)&&Mn(t.file)?{reason:"framework-route-exports",detail:"duplicate route-file verb exports whose identical glue the framework convention dictates"}:gE(e,t.file)?{reason:"ui-kit-members",detail:"duplicate bodies in vendored UI-kit directories generated from one template"}:null}function AI(e){let t=Rt(e);return Dt(t).replace(/\s+/g,"")}function FI(e){let t=new Map;for(let r of e){if(r.normalizedBody.length<8)continue;let i=G2(r.normalizedBody),o=t.get(i)??[];o.push(r),t.set(i,o)}let n=[];for(let[r,i]of t){let o=new Set(i.map(a=>a.file));if(i.length<2||o.size<2)continue;let s=[...i].sort(z2).map(({normalizedBody:a,...c})=>c);n.push({hash:r,canonical:s[0],functions:s})}return n.sort((r,i)=>{let o=i.functions.length-r.functions.length;if(o!==0)return o;let s=kI(i)-kI(r);return s!==0?s:r.canonical.file.localeCompare(i.canonical.file)}),n}function H2(e,t){let n=ye(e,{scope:t.scope}).filter(r=>r.isFunctionLike&&!e.isIgnored(r.relativePath)).filter(r=>!Ks(e,r.relativePath,r.startLine,"similar")).filter(r=>ee(r)<=t.maxLoc);return n.sort((r,i)=>ee(i)-ee(r)||r.relativePath.localeCompare(i.relativePath)),be(n,t.scanLimit)}function U2(e,t,n,r){let i=mt(e,t);if(!i||q2(i)<r)return null;let o=Dp(e,t);return o?{symbol:t.symbol,shortName:T(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:ee(t),ageCommits:n?.get(t.relativePath)?.commitsAgo??null,normalizedBody:o}:null}function Dp(e,t){let n=mt(e,t);return n&&AI(n)||null}function mt(e,t){let n=K(e,t.relativePath);return n.length===0?null:n.slice(t.startLine,t.endLine+1).join(`
377
- `)}function Rt(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="("||r==="[")t+=1;else if(r===")"||r==="]")t=Math.max(0,t-1);else if(r==="{"){if(t===0)return TI(e,n);t+=1}else if(r==="}")t=Math.max(0,t-1);else if(t===0&&r==="="&&e[n+1]===">"){let i=e.slice(n+2).trimStart();return i.startsWith("{")?TI(i,0):i.replace(/;+\s*$/,"")}}return e}function TI(e,t){let n=e.lastIndexOf("}");return n>t?e.slice(t+1,n):e}function q2(e){return Rt(e).split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0).length}function G2(e){return _2("sha256").update(e).digest("hex").slice(0,16)}function z2(e,t){let n=e.ageCommits??-1;return(t.ageCommits??-1)-n||e.file.localeCompare(t.file)||e.startLine-t.startLine}function kI(e){return e.functions.reduce((t,n)=>t+n.loc,0)}var K2=new Set(Qt());function W2(e,t={}){let{includeHomonyms:n=!1,limit:r}=t,i=ul(e,t).filter(o=>o.relationship==="divergent"||n&&o.relationship==="homonym");return r?i.slice(0,r):i}function ul(e,t={}){let{scope:n,minSimilarity:r=.3,scanLimit:i}=t,o=J2(e,{scope:n,scanLimit:i});return BI(o,{minSimilarity:r,isDelegatePair:IY(e)}).filter(s=>!s.members.some(a=>Ks(e,a.file,a.startLine,"twin")))}function BI(e,t={}){let n=t.minSimilarity??.3,r=t.isDelegatePair,i=e.filter(u=>!VI(u.leaf)&&!lY(u.leaf)&&!jI(u.symbol,u.leaf)&&!HI(u.file,u.leaf)&&U(u.file)!=="test"&&!Ge(u.symbol)&&!UI(u.symbol)&&!qI(u.symbol,u.leaf)),{recordsByLeaf:o,recordOrder:s}=N("twin-drift.group-by-leaf",()=>V2(i),()=>({records:i.length})),a=N("twin-drift.cluster-leaf-names",()=>$I([...o.keys()]),()=>({leaves:o.size}));return N("twin-drift.compare-clusters",()=>{let u=[];for(let l of a){let d=Y2(l,o,s),m=new Set(d.filter(x=>d.some(v=>v!==x&&v.file!==x.file&&r?.(x,v,d))).map(x=>x.symbol)),p=d.filter(x=>!m.has(x.symbol));if(p.length<2||new Set(p.map(x=>x.file)).size<2)continue;let f=null,g=!1,h=!1,y=new Set;for(let x=0;x<p.length;x+=1)for(let v=x+1;v<p.length;v+=1){let C=p[x],R=p[v];if(C.file===R.file||!yY(C,R)||r?.(C,R,p)||r?.(R,C,p)||NI(C,R)||NI(R,C))continue;if(g=!0,y.add(C.symbol),y.add(R.symbol),C.normalizedBody===R.normalizedBody){h=!0;continue}let E=oY(C.tokens,R.tokens);(!f||E>f.similarity)&&(f={a:C,b:R,similarity:E})}if(!g)continue;let S=p.filter(x=>y.has(x.symbol)).sort((x,v)=>x.file.localeCompare(v.file)||x.startLine-v.startLine).map(iY);if(!f){u.push({leaf:OI(l),relationship:h?"identical":"homonym",maxDivergence:0,members:S});continue}let b=f.similarity>=n?"divergent":"homonym";u.push({leaf:OI(l),relationship:b,maxDivergence:Math.round((1-f.similarity)*1e3)/1e3,members:S,...b==="divergent"?{firstDivergentTokens:sY(f.a.tokens,f.b.tokens)}:{}})}return u},()=>({clusters:a.length,records:i.length})).sort((u,l)=>l.members.length-u.members.length||l.maxDivergence-u.maxDivergence||u.leaf.localeCompare(l.leaf))}function V2(e){let t=new Map,n=new Map;for(let[r,i]of e.entries()){let o=t.get(i.leaf)??[];o.push(i),t.set(i.leaf,o),n.set(i,r)}return{recordsByLeaf:t,recordOrder:n}}function Y2(e,t,n){let r=[...e].flatMap(i=>t.get(i)??[]);return e.size>1&&r.sort((i,o)=>(n.get(i)??0)-(n.get(o)??0)),r}function J2(e,t){let n=N("twin-drift.load-definitions",()=>ye(e,{scope:t.scope}).filter(o=>X2(o)&&!e.isIgnored(o.relativePath)).filter(o=>!Ur(o.relativePath)));N("twin-drift.sort-definitions",()=>n.sort((o,s)=>o.relativePath.localeCompare(s.relativePath)||o.startLine-s.startLine),()=>({definitions:n.length}));let r=be(n,t.scanLimit),i=N("twin-drift.select-candidates",()=>Q2(r),()=>({scanned:r.length}));return N("twin-drift.build-records",()=>{let o=[];for(let s of i){let a=Z2(e,s);a&&o.push(a)}return o},()=>({candidates:i.length,scanned:r.length}))}function X2(e){return e.isFunctionLike?e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&K2.has(e.kind):!0:!1}function Q2(e){let t=e.filter(o=>o.leaf&&!VI(o.leaf)&&!jI(o.symbol,o.leaf)&&!HI(o.relativePath,o.leaf)&&!Ge(o.symbol)&&!UI(o.symbol)&&!qI(o.symbol,o.leaf)),n=new Map;for(let o of t){let s=n.get(o.leaf)??[];s.push(o),n.set(o.leaf,s)}let r=$I([...n.keys()]),i=new Set;for(let o of r){let s=[...o].flatMap(a=>n.get(a)??[]);if(!(s.length<2)&&!(new Set(s.map(a=>a.relativePath)).size<2)&&!s.every(a=>U(a.relativePath)==="test"))for(let a of s)i.add(a)}return e.filter(o=>i.has(o))}function Z2(e,t){if(!t.leaf)return null;let n=mt(e,t);if(!n||!Qe(t.symbol)&&!nY(n,t.leaf)||eY(n,t.leaf))return null;let r=Dt(Rt(n)),i=r.replace(/\s+/g,"");if(!i||i.length<8)return null;let o=r.match(rY)??[];return o.length===0?null:{leaf:t.leaf,symbol:t.symbol,shortName:T(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:ee(t),normalizedBody:i,tokens:o,isThinForwarder:Mp(r),forwardTargetLeaf:tY(r)}}function eY(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=e.split(`
378
- `).slice(0,2).join(`
379
- `);return new RegExp(`\\b(?:abstract|override)\\b[^\\n]*\\b${n}\\s*[(<]`).test(r)}function tY(e){if(!Mp(e))return null;let t=kp(e.trim()),n=Tp(t[t.length-1]),r=/^([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(/.exec(n)?.[1];return r?r.split(".").pop()??null:null}function NI(e,t){let n=e.forwardTargetLeaf;return typeof n=="string"&&n!==e.leaf&&n!==t.leaf&&!t.isThinForwarder}function nY(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 rY=/[A-Za-z_$][A-Za-z0-9_$]*|\d+(?:\.\d+)?|[^\sA-Za-z0-9_$]/g;function iY(e){return{symbol:e.symbol,shortName:e.shortName,file:e.file,startLine:e.startLine,endLine:e.endLine,loc:e.loc}}function oY(e,t){let n=new Set(e),r=new Set(t);if(n.size===0&&r.size===0)return 1;if(n.size===0||r.size===0)return 0;let i=0;for(let s of n)r.has(s)&&(i+=1);let o=n.size+r.size-i;return o===0?0:i/o}function sY(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;let i=e.slice(r,r+6).join(" "),o=t.slice(r,r+6).join(" ");return!i&&!o?"(bodies differ only in trailing length)":`A: ${i||"(end)"} | B: ${o||"(end)"}`}function $I(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 u=t.get(c);t.set(c,a),c=u}return a},r=(s,a)=>{let c=n(s),u=n(a);c!==u&&t.set(c,u)},i=new Map;for(let s of e){let a=s.slice(0,2).toLowerCase(),c=i.get(a)??[];c.push(s),i.set(a,c)}for(let s of i.values())for(let a=0;a<s.length;a+=1)for(let c=a+1;c<s.length;c+=1)aY(s[a],s[c])&&r(s[a],s[c]);let o=new Map;for(let s of e){let a=n(s),c=o.get(a)??new Set;c.add(s),o.set(a,c)}return[...o.values()]}function aY(e,t){if(e===t||e.toLowerCase()===t.toLowerCase())return!0;if(e.length<8||t.length<8||Math.abs(e.length-t.length)>2)return!1;let[n,r]=e.length<=t.length?[e,t]:[t,e];return r.length>n.length&&r.startsWith(n)&&/^[A-Z]/.test(r.slice(n.length))||cY(e.toLowerCase(),t.toLowerCase())/Math.max(e.length,t.length)<.8?!1:bY(e.toLowerCase(),t.toLowerCase(),2)}function cY(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;return r}function lY(e){return/^[A-Z][A-Z0-9_]*$/.test(e)||/^__[^_].*__$/.test(e)||uY.has(e.toLowerCase())}var uY=new Set(["main","row"]),dY=new Set(["close","connect","count","create","delete","destroy","disconnect","dispose","execute","exists","find","findAll","findById","findOne","get","getAll","getById","handle","init","initialize","list","load","open","patch","process","read","remove","reset","run","save","shutdown","start","stop","toJSON","toString","update","upsert"]),mY=/#(?:`[^`]+`|[^#/`]+)\(\)\.$/,pY=/^(?:get|find|list|load|fetch|count|delete|remove|update|upsert)(?:By|For)[A-Z]\w*$/;function jI(e,t){return(dY.has(t)||pY.test(t))&&mY.test(e)}var fY=/^(?:handler|handle(?:Get|Post|Put|Patch|Delete|Options|Head|Request)|(?:get|post|put|patch|delete|options|head|route|request)Handler|generateMetadata|generateStaticParams|generateViewport|generateSitemaps|loader|action|clientLoader|clientAction|middleware|config|default|load|actions|[A-Z][A-Za-z0-9]*(?:Page|Layout|Loading|Template|Route|Screen))$/;function HI(e,t){return fY.test(t)&&Mn(e.replace(/\\/g,"/"))}var gY=new Set(["app","component","components","feature","features","impl","index","lib","route","routes","shared","src","tsx","typescript","ui"]);function UI(e){return e.startsWith("rust-analyzer ")&&/\/(?:tests?|benches?)\//.test(e)}var hY=new Set(["default","new","reset"]);function qI(e,t){return e.startsWith("rust-analyzer ")&&hY.has(t.toLowerCase())}function yY(e,t){if(e.leaf.toLowerCase()!==t.leaf.toLowerCase()||e.leaf.length>4)return!0;let n=_I(e);return[..._I(t)].some(r=>n.has(r))}function _I(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&&!gY.has(n)))}function bY(e,t,n){if(Math.abs(e.length-t.length)>n)return!1;let r=Array.from({length:t.length+1},(i,o)=>o);for(let i=1;i<=e.length;i+=1){let o=[i],s=o[0];for(let a=1;a<=t.length;a+=1){let c=e[i-1]===t[a-1]?0:1,u=Math.min(r[a]+1,o[a-1]+1,r[a-1]+c);o.push(u),s=Math.min(s,u)}if(s>n)return!1;r=o}return r[t.length]<=n}function GI(e){return Mp(Dt(Rt(e)))}function zI(e){let t=Dt(Rt(e)).trim();if(!t||KI.test(t))return!1;let n=kp(t);if(n.length!==1)return!1;let r=Tp(n[0]),i=SY.exec(r);if(!i)return!1;let o=i[1].replace(/\[\s*\]|\{\s*\}/g,"");return!vY.test(o)}var SY=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^[\]]*\])*\(([\s\S]*)\)$/,vY=/[()[\]{}]|=>|\b(?:await|new|function)\b/;function Mp(e){let t=e.trim();if(!t||KI.test(t))return!1;let n=kp(t);return n.length===0||n.length>2?!1:xY(n[n.length-1])}var KI=/\b(?:if|else|for|while|switch|try|catch|do)\b/,CY=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^[\]]*\])*\((?:[^()]|\([^()]*\))*\)$/;function xY(e){return CY.test(Tp(e))}function Tp(e){return RY(e.trim().replace(/^return\s+/,"").replace(/^await\s+/,"").replace(/;\s*$/,"").trim())}function RY(e){let t=e.indexOf("<");if(t<0||!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(e.slice(0,t)))return e;let n=0;for(let r=t;r<e.length;r+=1){let i=e[r];if(i==="<")n+=1;else if(i===">"&&(n-=1,n===0))return e[r+1]==="("?e.slice(0,t)+e.slice(r+1):e}return e}function kp(e){let t=[],n=0,r="";for(let i of e){if(i==="("||i==="["||i==="{"?n+=1:(i===")"||i==="]"||i==="}")&&(n=Math.max(0,n-1)),i===";"&&n===0){t.push(r),r="";continue}r+=i}return r.trim()&&t.push(r),t.map(i=>i.trim()).filter(i=>i.length>0)}var EY=3;function IY(e){let t=new Map;return(n,r,i)=>{let o=`${n.symbol}\0${r.symbol}`,s=t.get(o);if(s!==void 0)return s;let a=WI(e,n,r,i,EY,new Set);return t.set(o,a),a}}function WI(e,t,n,r,i,o){if(i<=0||o.has(t.symbol))return!1;o.add(t.symbol);let s=ce(e,t.file),a=new Set;for(let l of s)l.importedName===n.leaf&&l.localName&&l.localName!==n.leaf&&a.add(l.localName);a.size===0&&a.add(n.leaf);let c=(Jt(e,t.file)??[]).filter(l=>l.line>=t.startLine&&l.line<=t.endLine&&a.has(l.calleeLeaf));if(c.length===0)return!1;for(let l of c){if(!l.calleeQualifier)continue;let d=s.find(m=>m.localName===l.calleeQualifier&&m.sourcePath);if(d?.sourcePath){if(ke(d.sourcePath,n.file))return!0;for(let m of ce(e,d.sourcePath))if(m.sourcePath&&ke(m.sourcePath,n.file))return!0}}let u=new Set(s.filter(l=>l.sourcePath&&(l.kind!=="namespace"||l.usedMembers.includes(n.leaf))).map(l=>l.sourcePath));for(let l of[...u])for(let d of bn(e,l))d.sourcePath&&u.add(d.sourcePath);if([...u].some(l=>ke(l,n.file)))return!0;for(let l of r)if(!(l.symbol===t.symbol||l.symbol===n.symbol||!l.isThinForwarder)&&[...u].some(d=>ke(d,l.file))&&WI(e,l,n,r,i-1,o))return!0;return!1}function VI(e){return e.startsWith("<")&&e.endsWith(">")}function OI(e){return[...e].sort()[0]}import{dirname as jY,isAbsolute as HY,relative as UY,resolve as qY}from"path";import{basename as JI,extname as XI}from"path";function dl(e,t,n,r,i,o){let s=new Set;PY(e,t,n,r)&&s.add(i);let a=wY(o);for(let c of o)c.value&&LY(s,c.label,c.value,a);return[...s].slice(0,6)}function wY(e){let t={self:new Set,other:new Set},n=0;for(let r of e)if(!(!r.side||!r.value)){n+=1;for(let i of YI(r.value))t[r.side].add(i)}return n===0||t.self.size===0||t.other.size===0?new Set:new Set([...t.self].filter(r=>t.other.has(r)))}function LY(e,t,n,r){let i=YI(n);t.endsWith("name")&&DY(i)&&e.add(`${t} has type-guard boundary shape`);for(let o of i){if(r.has(o))continue;let s=MY.get(o);s&&e.add(`${t} has ${s} term: ${o}`)}}function PY(e,t,n,r){if(n<=0)return!1;let i=K(e,t);if(i.length===0)return!1;for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(i[o]??"").trim();if(s!==""){if(Gs(s)===r)return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function YI(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 DY(e){return e.some(t=>TY.has(t))&&e.some(t=>kY.has(t))}var MY=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"]]),TY=new Set(["can","has","is","should"]),kY=new Set(["access","api","auth","collision","expired","input","keyboard","overlap","permission","permissions","policy","projectile","response","route","routes","scope"]);function ws(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new H(e),a=Bt({candidates:()=>$Y(e,s,n,r),orderCandidates:uc,scanLimit:o,profile:{name:"passthrough-candidates"},prepare:c=>s.calleeMap(c,{semantic:t?.semantic!==!1}),evaluate:(c,u)=>FY(e,c,u.get(c.symbolId)??[]),orderResults:(c,u)=>c.loc-u.loc||c.file.localeCompare(u.file)});return AY(a).slice(0,i===void 0?a.length:i)}var Ap=3;function AY(e){let t=new Map,n=new Map;for(let r of e){if(r.file===r.forwardsToFile)continue;let i=`${r.file}\0${r.forwardsToFile}`;t.set(i,(t.get(i)??0)+1);let o=Xs(r.symbol),s=Xs(r.forwardsTo);if(!o||!s||o===s)continue;let a=`${r.file}\0${o}`;n.set(a,(n.get(a)??0)+1)}return e.map(r=>{let i=t.get(`${r.file}\0${r.forwardsToFile}`)??0,o=Xs(r.symbol),s=o?n.get(`${r.file}\0${o}`)??0:0;if(i<Ap&&s<Ap)return r;let a=i>=Ap?`facade: ${i} sibling forwards from this file to ${r.forwardsToFile}`:`facade: ${s} methods of ${o} forward to members of its collaborators`,c=[...r.boundaryEvidence,a];return{...r,boundaryEvidence:c,actionTier:"signal",recommendation:QI("signal",c,r.publicFacadeEvidence)}})}function FY(e,t,n){let r=BY(n);if(r.size!==1||!cg(e,t.relativePath,t.startLine,t.endLine))return null;let[,i]=[...r.entries()][0],o=NY(e,t,i),s=_Y(e,t),a=o.length>0||s.length>0?"signal":"direct";return{symbol:t.symbol,shortName:T(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:ee(t),forwardsTo:i.symbol,forwardsToShort:T(i.symbol),forwardsToFile:i.file,actionTier:a,boundaryEvidence:o,publicFacadeEvidence:s,recommendation:QI(a,o,s)}}function NY(e,t,n){return dl(e,t.relativePath,t.startLine,"passthrough","explicit ignore-passthrough comment",[{label:"passthrough name",value:fi(t.symbol),side:"self"},{label:"callee name",value:fi(n.symbol),side:"other"},{label:"passthrough module",value:JI(t.relativePath,XI(t.relativePath)),side:"self"},{label:"callee module",value:JI(n.file,XI(n.file)),side:"other"}])}function QI(e,t,n){if(e==="signal"){if(n.length>0)return`Review the public API before inlining; public-facade evidence: ${n.slice(0,2).join("; ")}.`;let r=t.filter(OY);return r.length>0?`Review the public API before inlining; public-surface evidence: ${r.slice(0,2).join("; ")}.`:`Review the boundary before inlining; boundary evidence: ${t.slice(0,2).join("; ")}.`}return"Inline or remove this passthrough unless an external API or runtime registration depends on the forwarding name."}function _Y(e,t){return ht(e,t)?Dn(e,t.relativePath)?["exported passthrough is declared on the package public surface"]:Be(e,t.symbol,t.relativePath)?["exported passthrough matches configured or framework public entry surface"]:[]:[]}function OY(e){return e.includes("public surface")}function BY(e){let t=e.some(r=>Re(r.symbol))?e.filter(r=>Re(r.symbol)):e,n=new Map;for(let r of t)n.has(r.symbol)||n.set(r.symbol,r);return n}function $Y(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:3,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0}).filter(i=>!Vs(e,i))}var GY=new Set(Qt());function zY(e,t){return`tests/generated/twin-ab/${ZI(e)}-vs-${ZI(t)}.test.ts`}function ZI(e){return(e.split(/[/#]/).pop()||e).replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"symbol"}function KY(e,t,n,r){let{refA:i,refB:o,outFile:s}=typeof t=="string"?{refA:t,refB:n,outFile:r}:t;if(typeof i!="string"||typeof o!="string"||typeof s!="string")throw new TypeError("twinAb requires refA, refB, and outFile.");if(!HY(s))throw new TypeError("twinAb outFile must be an absolute path.");let a=ew(e,i);if(!a.ok)return a;let c=ew(e,o);if(!c.ok)return c;let u=a.symbol.paramCount===null||c.symbol.paramCount===null?null:a.symbol.paramCount===c.symbol.paramCount,l=VY(a.symbol,c.symbol,e.config.projectRoot,s,u);return{ok:!0,a:a.symbol,b:c.symbol,signatureCompatible:u,testSource:l}}function ew(e,t){let r=Ze(e,t).match;if(!r)return{ok:!1,reason:`${t} does not resolve to an indexed symbol.`};let o=e.get("SELECT kind FROM global_symbols WHERE id = ?",r.symbolId)?.kind??null;if(!(o!==null?GY.has(o):Re(r.symbol)))return{ok:!1,reason:`${t} resolves to ${T(r.symbol)}${o!==null?` with SCIP kind ${yo(o)}`:""} \u2014 twin-ab compares call outputs, so both referents must be functions or methods.`};if(!ht(e,r))return{ok:!1,reason:`${t} (${T(r.symbol)} at ${r.relativePath}:${r.startLine+1}) is not exported \u2014 twin-ab needs an importable named binding for both twins.`};let a=e.get("SELECT documentation FROM global_symbols WHERE id = ?",r.symbolId),c=hi(yi(a?.documentation??null));return{ok:!0,symbol:{ref:t,symbol:r.symbol,shortName:G(r.symbol)||T(r.symbol),file:r.relativePath,startLine:r.startLine,signature:c,paramCount:c?WY(c):null}}}function WY(e){let t=e.indexOf("(");if(t===-1)return null;let n=0,r=-1;for(let a=t;a<e.length;a+=1){let c=e[a];if(c==="(")n+=1;else if(c===")"&&(n-=1,n===0)){r=a;break}}if(r===-1)return null;let i=e.slice(t+1,r).trim();if(!i)return 0;let o=1,s=0;for(let a of i)a==="("||a==="["||a==="{"?s+=1:a===")"||a==="]"||a==="}"?s=Math.max(0,s-1):a===","&&s===0&&(o+=1);return o}function tw(e,t,n){let r=jY(t),i=qY(e,n),s=UY(r,i).replace(/\\/g,"/").replace(/\.tsx?$/,".js");return s.startsWith(".")?s:`./${s}`}function VY(e,t,n,r,i){let o=tw(n,r,e.file),s=tw(n,r,t.file),a=i===null?"Signature comparison: unknown (one or both signatures unavailable in the index) \u2014 check by hand.":i?"Signature comparison: param counts match.":"Signature comparison: param counts DIFFER \u2014 twins may not be directly comparable; check by hand.";return`/**
380
- * Generated by 'scip-query twin-ab'. Cleanup integrity scenario.
381
- * ("cross-examine same-concept twins"): where one concept is computed in
382
- * more than one place, feed both the same input and require the same
383
- * answer. Disagreement between twins means at least one is wrong \u2014
384
- * determine which before consolidating.
385
- *
386
- * Twin A: ${e.shortName} (${e.file}:${e.startLine+1})
387
- * ${e.signature??"(signature unavailable)"}
388
- * Twin B: ${t.shortName} (${t.file}:${t.startLine+1})
389
- * ${t.signature??"(signature unavailable)"}
390
- * ${a}
391
- *
392
- * Fill in the TODO input table below with inputs both twins should agree
393
- * on, then run this file with vitest.
394
- */
395
- import { describe, expect, it } from 'vitest';
396
- import { ${e.shortName} as twinA } from '${o}';
397
- import { ${t.shortName} as twinB } from '${s}';
398
-
399
- // TODO: fill in shared inputs both twins should agree on \u2014 one arg array per call.
400
- const inputs: any[][] = [
401
- // [/* arg1, arg2, ... */],
402
- ];
403
-
404
- // Cast to a variadic signature so the input table can hold any arg shape \u2014
405
- // the real twins have fixed, non-rest parameter lists, and TS rejects
406
- // spreading a generic args array into those (TS2556) even when the array
407
- // itself is 'any'; casting the callee's signature, not the args, satisfies
408
- // the checker without weakening the twins' real exported types elsewhere.
409
- const callA = twinA as (...callArgs: any[]) => any;
410
- const callB = twinB as (...callArgs: any[]) => any;
411
-
412
- describe.skipIf(inputs.length === 0)('twin-ab: ${e.shortName} vs ${t.shortName}', () => {
413
- it.each(inputs)('agrees on input %#', (...args) => {
414
- expect(callA(...args)).toEqual(callB(...args));
415
- });
416
- });
417
- `}var nw={caller:3,"entry-surface":2,rooted:1},YY=/not\s*yet\s*implement|not\s*implement|unimplement|\bnyi\b|\btodo\b|\bstub\b|not\s*supported|coming\s*soon/i,JY=/^throw\s+new\s+[\w.]*Error\s*\(([\s\S]*)\)\s*;?$/,XY=/^return(\s+(null|undefined|false|0|''|""|``|\[\]|\{\}))?\s*;?$/,QY=/\/\/\s*TODO\b|\/\*\s*TODO\b/i,ZY=/(?:=>|\))\s*(?::\s*[^{;=]+)?\s*\{\s*\}\s*;?\s*$/;function eJ(e,t={}){let{scope:n,limit:r=30,scanLimit:i,semantic:o=!0}=t,s=new H(e),a=be(s.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),c=[];for(let p of a){let f=nJ(e,p);f&&c.push(f)}if(c.length===0)return[];let u=sJ(e,c,a),l=c.filter(p=>!u.has(p.def.symbol));if(l.length===0)return[];let d=_n(e,s).forDefinitions(l.map(p=>p.def),{semantic:o}),m=[];for(let p of l){let g=d.get(p.def.symbolId)?.realConsumers.length??0,h=tJ(e,p.def,g);h&&m.push({symbol:p.def.symbol,shortName:T(p.def.symbol),file:p.def.relativePath,startLine:p.def.startLine,endLine:p.def.endLine,loc:ee(p.def),stubKind:p.stubKind,reachability:h,callerFanIn:g,stubText:p.stubText})}return m.sort((p,f)=>nw[f.reachability]-nw[p.reachability]||f.callerFanIn-p.callerFanIn||p.file.localeCompare(f.file)||p.startLine-f.startLine),r?m.slice(0,r):m}function tJ(e,t,n){return n>0?"caller":Be(e,t.symbol,t.relativePath)?"rooted":ze(e,t.relativePath)?"entry-surface":null}function nJ(e,t){let n=mt(e,t);if(!n)return null;let r=Rt(n),i=r.trim();if(i==="")return!oJ(n)||!ht(e,t)?null:{def:t,stubKind:"empty-body",stubText:"(empty body)"};let o=uo(r),s=Dt(r),a=rJ(o,s);if(a.length!==1)return null;let c=a[0];return iJ(c)?{def:t,stubKind:"throw-stub",stubText:c.trim()}:QY.test(r)&&XY.test(c.trim())?{def:t,stubKind:"todo-return-default",stubText:i}:null}function rJ(e,t){let n=[],r=0,i="";for(let o=0;o<t.length;o+=1){let s=t[o];if(s==="("||s==="["||s==="{"?r+=1:(s===")"||s==="]"||s==="}")&&(r=Math.max(0,r-1)),s===";"&&r===0){n.push(i),i="";continue}i+=e[o]??""}return i.trim()&&n.push(i),n.map(o=>o.trim()).filter(o=>o.length>0)}function iJ(e){let t=JY.exec(e.trim());return t?YY.test(t[1]??""):!1}function oJ(e){return ZY.test(e.trimEnd())}function sJ(e,t,n){let r=new Set,i=new Set(t.map(a=>a.def.parentTypeName).filter(a=>a!==null));if(i.size===0)return r;let o=cJ(e,i),s=new Map;for(let a of n){if(!a.parentTypeName)continue;let c=s.get(a.leaf)??new Set;c.add(a.parentTypeName),s.set(a.leaf,c)}for(let a of t){let c=a.def.parentTypeName;if(!c)continue;let u=o.get(c);if(!u||u.size===0)continue;let l=s.get(a.def.leaf)??new Set;[...u].every(m=>l.has(m))&&r.add(a.def.symbol)}return r}var aJ=/\bclass\s+([A-Za-z_$][\w$]*)\s+extends\s+([A-Za-z_$][\w$]*)/g;function cJ(e,t){let n=new Map;for(let r of Q(e,{includeIgnored:!1})){let i=V(e,r);if(i)for(let o of i.matchAll(aJ)){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 lJ=/^(?:validate|verify|check|assert)(?:[A-Z].*)?$/,uJ=/^(?:is|has)(?:[A-Z].*)?$/,dJ=/[{,]\s*(?:ok|success|valid|isValid)\s*:\s*false\b/,Fp=/\breturn\b/g,mJ=/\bfunction\b|=>|\)\s*(?::\s*[^{;=]+)?\s*\{/,pJ=/\.(?:addIssue|push)\s*\(/;function fJ(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new H(e),s=be(o.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),a=[];for(let c of s){let u=hJ(e,c);u&&a.push({symbol:c.symbol,shortName:T(c.symbol),file:c.relativePath,startLine:c.startLine,endLine:c.endLine,loc:ee(c),...u})}return a.sort((c,u)=>c.file.localeCompare(u.file)||c.startLine-u.startLine||c.loc-u.loc),r?a.slice(0,r):a}function gJ(e){return lJ.test(e)?"imperative":uJ.test(e)?"predicate":null}function hJ(e,t){let n=gJ(t.leaf);if(!n||Ki(e,t))return null;let r=mt(e,t);if(!r||!mJ.test(r))return null;let i=W(e,t.relativePath)?.callables.find(s=>s.startLine===t.startLine&&s.endLine===t.endLine);if(n==="predicate"&&i?.paramCount===0)return null;if(GI(r)){let s=SJ(e,t);return!s||ow(s.body,iw(s.snippet))||rw(s.body)?null:{nameKind:n,resolvedVia:"one-hop-delegate",delegateTarget:s.shortName}}let o=Rt(r);return ow(o,iw(r))||rw(o)?null:{nameKind:n,resolvedVia:"direct"}}var yJ=new Set(["if","for","while","switch","catch","function"]);function rw(e){let t=uo(e);for(let n of t.matchAll(/\b([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(/g))if(!yJ.has(n[1]))return!0;return!1}function iw(e){let t=e.indexOf("=>");return t===-1?!1:!/^\s*\{/.test(e.slice(t+2))}function ow(e,t){let n=uo(e);if(/\bthrow\b/.test(n)||/\.reject\s*\(/.test(n)||dJ.test(n)||pJ.test(n))return!0;let r=bJ(n);if(t&&r.length===0){let i=n.trim();return i!==""&&i!=="true"}for(let i of r)if(i!==""&&i!=="true")return!0;return!1}function bJ(e){let t=[];Fp.lastIndex=0;let n;for(;n=Fp.exec(e);){let r=n.index+n[0].length,i=0,o=e.length;for(let s=r;s<e.length;s+=1){let a=e[s];if(a==="("||a==="["||a==="{")i+=1;else if(a===")"||a==="]"||a==="}"){if(i===0){o=s;break}i-=1}else if(a===";"&&i===0){o=s;break}}t.push(e.slice(r,o).trim()),Fp.lastIndex=o}return t}function SJ(e,t){let n=Ft(e,t,{callableOnly:!0,limit:3,semanticEvidence:ie}),r=[...new Set(n.map(c=>c.symbol))].filter(c=>c!==t.symbol);if(r.length!==1)return null;let o=Ze(e,r[0]).match;if(!o)return null;let s=q(e,o.relativePath).find(c=>c.symbolId===o.symbolId);if(!s)return null;let a=mt(e,s);return a?{body:Rt(a),snippet:a,shortName:T(s.symbol)}:null}var vJ=60;function CJ(e,t={}){let{scope:n,limit:r=30,scanLimit:i,rotDays:o=vJ}=t,s=be(di(e,{extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs"]}).filter(l=>U(l)==="test").filter(l=>!n||l.includes(n)).filter(l=>!e.isIgnored(l)).sort(),i),a=[],c=[],u=[];for(let l of s){let d=V(e,l);if(!d)continue;let m=ig(d),p=EJ(d);for(let g of PJ(m,p))p.add(g);let f=xJ(m);for(let g of f){if(g.skip){c.push(NJ(e,l,g,o));continue}if(g.kind==="describe")continue;let h=aw(d,g.argsStart),y=m.slice(g.argsStart,g.callEnd),S=d.slice(g.argsStart,g.callEnd);cw(y,p)||a.push({file:l,startLine:Ls(d,g.callStart),endLine:Ls(d,g.callEnd),title:h,severity:/\bawait\b/.test(y)?"low":"high"});let b=kJ(y,S);b&&u.push({file:l,startLine:Ls(d,g.callStart),endLine:Ls(d,g.callEnd),title:h,echoedValue:b})}}return{assertionFree:r?a.slice(0,r):a,skipped:r?c.slice(0,r):c,mockEcho:r?u.slice(0,r):u}}var Np=/(?<!\.)\b(?:x(it|test|describe)|(it|test|describe)(?:\.\s*(skip|only|todo|each\s*\([^)]*\)))?)\s*\(/g;function xJ(e){let t=[];Np.lastIndex=0;let n;for(;n=Np.exec(e);){let r=n[1],i=r??n[2];if(!i)continue;let o=n[3]?.split(/\s*\(/)[0],s=n.index,a=n.index+n[0].length-1,c=Ps(e,a);Np.lastIndex=a+1,o!=="each"&&t.push({kind:i,skip:r!==void 0||o==="skip"||o==="todo",skipKind:o==="todo"?"todo":"skip",callStart:s,argsStart:a+1,callEnd:c+1})}return t}function Ps(e,t){let n=0;for(let r=t;r<e.length;r+=1){let i=e[r];if(i==="(")n+=1;else if(i===")"&&(n-=1,n===0))return r}return e.length-1}function Ls(e,t){let n=0;for(let r=0;r<t&&r<e.length;r+=1)e[r]===`
418
- `&&(n+=1);return n}function aw(e,t){let n=e.slice(t,t+400),r=/^\s*(['"`])((?:\\.|(?!\1)[\s\S])*)\1/.exec(n);return r?r[2]:"(anonymous)"}var RJ=new Set(["vitest","chai","jest","@jest/globals","assert","node:assert","node:assert/strict","assert/strict","uvu/assert","expect","chai-as-promised"]),sw=/import\s+(?:\*\s+as\s+(\w+)|\{([^}]*)\}|(\w+))\s+from\s+['"]([^'"]+)['"]/g;function EJ(e){let t=new Set(["expect","assert"]);sw.lastIndex=0;let n;for(;n=sw.exec(e);){let[,r,i,o,s]=n;if(!(!s||!RJ.has(s))&&(r&&t.add(r),o&&t.add(o),i))for(let a of i.split(",")){let c=a.trim().replace(/^type\s+/,"");if(!c)continue;let u=/^(\w+)\s+as\s+(\w+)$/.exec(c);t.add(u?u[2]:c)}}return t}function cw(e,t){if(/\.should\b/.test(e)||/\bawait\s+(?:[\w$.]+\.)?findBy[A-Z]\w*\s*\(/.test(e)||/\bawait\s+\w*waitFor(?:Text|Value|Condition|Result|Event)\s*\(/.test(e)||/\bthrow\b/.test(e))return!0;for(let n of t){let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`\\b${r}\\s*(?:<[^<>]*>)?\\s*[.(]`).test(e))return!0}return!1}var IJ=/\bfunction\s+(\w+)\s*\(/g,wJ=/\b(?:const|let)\s+(\w+)\s*=\s*(?:async\s*)?\(/g,LJ=60;function PJ(e,t){let n=new Set;for(let r of[IJ,wJ]){r.lastIndex=0;let i;for(;i=r.exec(e);){let o=i[1],s=i.index+i[0].length-1,a=Ps(e,s),c=e.indexOf("{",a+1);if(c===-1||c-a>LJ)continue;let u=DJ(e,c),l=e.slice(c+1,u);cw(l,t)&&n.add(o)}}return n}function DJ(e,t){let n=0;for(let r=t;r<e.length;r+=1){let i=e[r];if(i==="{")n+=1;else if(i==="}"&&(n-=1,n===0))return r}return e.length-1}var MJ=/\bmock(?:ReturnValue|ResolvedValue)(?:Once)?\s*\(/g,_p=/\bexpect\s*\(/g,TJ=/^\s*\.\s*(?:toBe|toEqual|toStrictEqual)\s*\(/,lw=/^(?:-?\d+(?:\.\d+)?|(['"`]).+\1)$/;function kJ(e,t){let n=AJ(e,t,MJ);if(n.length===0)return null;let r=FJ(e,t);for(let i of r)if(n.includes(i))return i;return null}function AJ(e,t,n){let r=[];n.lastIndex=0;let i;for(;i=n.exec(e);){let o=i.index+i[0].length-1,s=Ps(e,o),a=t.slice(o+1,s).trim();lw.test(a)&&r.push(a),n.lastIndex=s+1}return r}function FJ(e,t){let n=[];_p.lastIndex=0;let r;for(;r=_p.exec(e);){let i=r.index+r[0].length-1,o=Ps(e,i),s=e.slice(o+1),a=TJ.exec(s);if(_p.lastIndex=o+1,!a)continue;let c=o+1+a[0].length-1,u=Ps(e,c),l=t.slice(c+1,u).trim();lw.test(l)&&n.push(l)}return n}function NJ(e,t,n,r){let i=V(e,t),o=aw(i,n.argsStart),s=Ls(i,n.callStart),a=_J(e.config.projectRoot,t,s),c=a===null?"unknown":a>=r?"rot":"workflow";return{file:t,startLine:s,title:o,skipKind:n.skipKind,blockKind:n.kind,ageDays:a,rot:c}}function _J(e,t,n){let r=n+1;try{let i=dt(e,["blame","-L",`${r},${r}`,"--porcelain","--",t]),o=/^author-time (\d+)$/m.exec(i);if(!o)return null;let s=Number(o[1]);return Number.isFinite(s)?Math.max(0,Math.round((Date.now()/1e3-s)/86400)):null}catch{return null}}var OJ=.7,uw=.62,dw=.45;function BJ(e,t={}){let{windowCommits:n=100,limit:r=30,scope:i,scanLimit:o}=t,s=Kt(e,{historyMode:t.historyMode}).fileAddRecords();if(!s)return{available:!1,windowCommits:n,findings:[]};if(r<=0)return{available:!0,windowCommits:n,findings:[]};let a=WJ(s,n);if(a.size===0)return{available:!0,windowCommits:n,findings:[]};let u=$J(e,{limit:r,minSimilarity:t.minSimilarity,scanLimit:o,scope:i,semantic:t.semantic,focusFiles:Number.isFinite(r)?void 0:a}).map(d=>VJ(d,s,n)).filter(d=>d!==null);u.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 l=u.slice(0,r).map(YJ);return{available:!0,windowCommits:n,findings:l,rootCauseGroups:JJ(l)}}function $J(e,t){let n=QJ(t.limit),r=[...jJ(e,{scope:t.scope,minSimilarity:t.minSimilarity??OJ,limit:n,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles})],i=Ys(e,{scope:t.scope});return i.react&&r.push(...HJ(e,{scope:t.scope,minSimilarity:t.minSimilarity??uw,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...UJ(e,{scope:t.scope,minSimilarity:t.minSimilarity??dw,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),i.vue&&r.push(...zJ(e,{scope:t.scope,minSimilarity:t.minSimilarity??uw,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...KJ(e,{scope:t.scope,minSimilarity:t.minSimilarity??dw,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),r}function jJ(e,t){return Ss(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles}).filter(n=>!Ge(n.symbolA)&&!Ge(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 HJ(e,t){return pl(e,t,{query:Um,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 pl(e,t,n){return n.query(e,t).filter(r=>r.fileA!==r.fileB).filter(r=>n.acceptPair?.(r)??!0).map(r=>({domain:n.domain,basis:n.basis,symbolA:n.symbolA(r),fileA:r.fileA,symbolB:n.symbolB(r),fileB:r.fileB,similarity:r.similarity,sharedEvidence:ZJ(...n.evidenceBuckets(r)),sharedCallees:[]}))}function UJ(e,t){return pl(e,t,{query:Gm,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,acceptPair:GJ,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 qJ=new Set(["useCallback","useEffect","useLayoutEffect","useMemo","useMutation","useQueries","useQuery","useQueryClient","useReducer","useRef","useState"]);function GJ(e){return e.sharedHooks.some(t=>!qJ.has(t))||e.sharedState.length>0||e.sharedHandlers.length>0||e.sharedHandlerVerbs.length>=2}function zJ(e,t){return pl(e,t,{query:vs,domain:"vue-component",basis:"vue-template",symbolA:n=>ml(n.fileA),symbolB:n=>ml(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function KJ(e,t){return pl(e,t,{query:Cs,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>ml(n.fileA),symbolB:n=>ml(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 WJ(e,t){let n=new Set;for(let[r,i]of e)i.commitsAgo<=t&&n.add(r);return n}function VJ(e,t,n){let r=t.get(e.fileA)?.commitsAgo??null,i=t.get(e.fileB)?.commitsAgo??null,o=r!==null&&r<=n,s=i!==null&&i<=n;if(!o&&!s)return null;if(o&&s){let a=(r??0)<=(i??0);return{kind:"twin",domain:e.domain,basis:e.basis,echoSymbol:a?e.symbolA:e.symbolB,echoFile:a?e.fileA:e.fileB,echoAgeCommits:(a?r:i)??0,establishedSymbol:a?e.symbolB:e.symbolA,establishedFile:a?e.fileB:e.fileA,establishedAgeCommits:a?i:r,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}return{kind:"echo",domain:e.domain,basis:e.basis,echoSymbol:o?e.symbolA:e.symbolB,echoFile:o?e.fileA:e.fileB,echoAgeCommits:(o?r:i)??0,establishedSymbol:o?e.symbolB:e.symbolA,establishedFile:o?e.fileB:e.fileA,establishedAgeCommits:o?i:r,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}function YJ(e){let t=mw(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function mw(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 JJ(e){let t=new Map;for(let[n,r]of e.entries()){let i=r.rootCauseKey??mw(r),o=r.groupKey??`recent-duplicate:${i}`,s=t.get(o);s||(s={groupKey:o,rootCauseKey:i,kind:r.kind,domain:r.domain,basis:r.basis,count:0,maxSimilarity:r.similarity,findingIndexes:[],echoFiles:new Set,establishedFile:r.kind==="echo"?r.establishedFile:void 0,establishedSymbol:r.kind==="echo"?r.establishedSymbol:void 0,relatedFiles:new Set,sharedEvidence:new Set,recommendation:XJ(r)},t.set(o,s)),s.count+=1,s.maxSimilarity=Math.max(s.maxSimilarity,r.similarity),s.findingIndexes.push(n),s.echoFiles.add(r.echoFile),s.relatedFiles.add(r.echoFile),s.relatedFiles.add(r.establishedFile);for(let a of r.sharedEvidence)s.sharedEvidence.add(a)}return[...t.values()].map(n=>({...n,echoFiles:[...n.echoFiles].sort(),relatedFiles:[...n.relatedFiles].sort(),sharedEvidence:[...n.sharedEvidence].sort().slice(0,16)})).sort((n,r)=>r.count-n.count||r.maxSimilarity-n.maxSimilarity||n.groupKey.localeCompare(r.groupKey))}function XJ(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 QJ(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function ZJ(...e){let t=[],n=new Set;for(let[r,i]of e)for(let o of i){let s=`${r}:${o}`;n.has(s)||(n.add(s),t.push(s))}return t}function ml(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var e5=te("suppression-inventory",{clearGroups:["whole-project"]});function fl(e){return e5.get(e,()=>t5(e))}function t5(e){let t={dead:0,stale:0,wrapper:0,passthrough:0,drift:0,extract:0,similar:0,twin:0,uncategorized:0},n=new Map,r=0;for(let i of di(e)){let o=V(e,i);if(!(!o||!o.includes("scip-query")))for(let s of o.split(/\r?\n/)){let a=Gs(s);if(a===null)continue;r+=1,n.set(i,(n.get(i)??0)+1);let c=pw(a);t[c]+=1}}for(let i of e.config.suppressions??[])i.expiresAt&&Date.parse(i.expiresAt)<=Date.now()||(r+=1,i.file&&n.set(i.file,(n.get(i.file)??0)+1),t[pw(i.check)]+=1);return{total:r,byCategory:t,byFile:n}}function pw(e){if(!e)return"uncategorized";let t=e.toLowerCase();return t==="dead-code"||t==="new-dead"?"dead":t.includes("twin")?"twin":t.includes("similar")||t.includes("duplicate")?"similar":t.includes("wrapper")?"wrapper":t.includes("passthrough")?"passthrough":t.includes("drift")?"drift":t.includes("extract")?"extract":t.includes("stale")?"stale":"uncategorized"}function Op(e,t,n={}){let r=re(e,t);if(!r)return null;let i=new H(e),o=n5(e,r),s=r.endLine-r.startLine+1,c=i.calleeMap([r],{additive:!0,semantic:n.semantic}).get(r.symbolId)??[],u=new Set(c.map(l=>l.symbol));return{symbol:r.symbol,shortName:T(r.symbol),relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,loc:s,branches:o.branches,estimateBasis:o.estimateBasis,cyclomaticEstimate:o.branches+1,calleeCount:u.size,fanIn:i5(e,r.symbolId),fanOut:o5(c,r.relativePath)}}function n5(e,t){let n=J(e,t.relativePath);if(n){let r=Ir(n.rootNode,t.startLine,t.endLine);if(r)return{branches:s5(r),estimateBasis:"ast"}}return{branches:yw(hw(e,t.relativePath,t.startLine,t.endLine),gw(e,t.relativePath)),estimateBasis:"regex-fallback"}}function fw(e,t){let n=new Map,r=new Map;for(let i of t){let o=r.get(i.relativePath)??[];o.push(i),r.set(i.relativePath,o)}for(let[i,o]of r){let s=new Map;for(let d of W(e,i)?.callables??[])d.branches!==void 0&&s.set(`${d.startLine}:${d.endLine}`,d.branches);let a=[];for(let d of o){let m=s.get(`${d.startLine}:${d.endLine}`);m===void 0?a.push(d):n.set(d.symbolId,{branches:m,estimateBasis:"ast"})}if(a.length===0)continue;let c=J(e,i),u=c===null?[]:a.filter(d=>c.rootNode.startPosition.row<=d.startLine&&c.rootNode.endPosition.row>=d.endLine),l=new Set(u.map(d=>d.symbolId));if(c&&u.length>0){for(let d of u)n.set(d.symbolId,{branches:0,estimateBasis:"ast"});a5(c.rootNode,u,n)}for(let d of a)l.has(d.symbolId)||n.set(d.symbolId,r5(e,d))}return n}function r5(e,t){return{branches:yw(hw(e,t.relativePath,t.startLine,t.endLine),gw(e,t.relativePath)),estimateBasis:"regex-fallback"}}function gw(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function hw(e,t,n,r){try{return ve(e.config.projectRoot,t,{inputKind:"indexed source file"}).split(`
419
- `).slice(n,r+1).join(`
420
- `)}catch(i){if(!Ce(i))throw i;return""}}function i5(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
421
- FROM mentions m
422
- JOIN chunks c ON m.chunk_id = c.id
423
- JOIN (
424
- SELECT m2.symbol_id, c2.document_id
425
- FROM mentions m2
426
- JOIN chunks c2 ON m2.chunk_id = c2.id
427
- WHERE m2.role = 1
428
- GROUP BY m2.symbol_id
429
- ) sym_def ON sym_def.symbol_id = m.symbol_id
430
- WHERE m.symbol_id = ?
431
- AND m.role != 1
432
- AND sym_def.document_id != c.document_id`,t)?.c??0}function o5(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function s5(e){let t=0;return Gl(e,n=>{t+=Kl(n)}),t}function a5(e,t,n){let r=[...t].sort((i,o)=>i.startLine-o.startLine||o.endLine-i.endLine);Gl(e,i=>{let o=Kl(i);if(o===0)return;let s=i.startPosition.row,a=i.endPosition.row;for(let c of r){if(c.startLine>s)break;if(c.endLine<a)continue;let u=n.get(c.symbolId);u&&(u.branches+=o)}})}function yw(e,t){let n=Dt(e),r=0,i=[/\bif\b/g,/\belse\s+if\b/g,/\belse\b/g,/\bfor\b/g,/\bwhile\b/g,/\bswitch\b/g,/\bcase\b/g,/\bcatch\b/g,/\?\s*[^?]/g,/&&/g,/\|\|/g];for(let o of i){let s=n.match(o);s&&(r+=s.length)}if(t==="python"){let o=[/\belif\b/g,/\bexcept\b/g,/\bfinally\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="rust"){let o=[/\bmatch\b/g,/=>/g,/\bloop\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="ruby"){let o=[/\belsif\b/g,/\bunless\b/g,/\brescue\b/g,/\bwhen\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="go"){let o=[/\bselect\b/g,/\bdefer\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}return r}function bw(e,t,n={}){let r=re(e,t);if(!r)return null;let i=[{file:r.relativePath,line:r.startLine}],o=zn(e,r,{semantic:n.semantic,semanticEvidence:ie}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?T(c.enclosingSymbol):"(top-level)"})),{outgoingCalls:s,incomingCalls:a}=c5(e,r,o,{semantic:n.semantic!==!1});return{symbol:r.symbol,shortName:T(r.symbol),relativePath:r.relativePath,definitionSites:i.filter(c=>!e.isIgnored(c.file)),referenceSites:o,outgoingCalls:s.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:T(c.symbol),file:c.file})),incomingCalls:a.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:c.symbol===c.file?"(top-level)":T(c.symbol),file:c.file}))}}function Bp(e,t,n={}){let r=bw(e,t,n);return r?{symbol:r.symbol,shortName:r.shortName,relativePath:r.relativePath,definitionSites:r.definitionSites,usageSites:r.referenceSites,producers:r.outgoingCalls,consumers:r.incomingCalls}:null}function c5(e,t,n,r){let i=_i(Ft(e,t,{limit:30,semantic:r.semantic,semanticEvidence:ie}).map(a=>({symbol:a.symbol,file:a.file}))),o=_i(Vn(e,t,{limit:30,semantic:r.semantic,semanticEvidence:ie})),s=o.length>0?o:_i(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{outgoingCalls:i,incomingCalls:s}}function Sw(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,o=re(e,t);return o?r==="backward"?l5(e,o,i,{semantic:n.semantic!==!1}):u5(e,o,{semantic:n.semantic!==!1}):null}function gl(e,t,n={}){return Sw(e,t,n)}function l5(e,t,n,r){let i=[],o=new Set([t.symbol]),s=[t];for(let a=1;a<=n&&s.length!==0;a++){let c=[];for(let u of s){let l=Ft(e,u,{semantic:r.semantic,semanticEvidence:ie});for(let d of l){if(o.has(d.symbol))continue;o.add(d.symbol),i.push({symbol:d.symbol,shortName:T(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let m=Lr(e,d.symbol);m&&!e.isIgnored(m.relativePath)&&c.push(m)}}s=c}return{symbol:t.symbol,shortName:T(t.symbol),direction:"backward",connectedSymbols:i}}function u5(e,t,n){let r=new Set,i=[],o=new H(e);for(let s of zn(e,t,{semantic:n.semantic,semanticEvidence:ie})){if(i.length>=30)break;let a=s.enclosingSymbol??Oe(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=Lr(e,a);!c||e.isIgnored(c.relativePath)||r.has(c.symbol)||(r.add(c.symbol),i.push({symbol:c.symbol,shortName:T(c.symbol),file:c.relativePath,relationship:`references target at ${s.file}:${s.line+1}`}))}return i.sort((s,a)=>s.file.localeCompare(a.file)),{symbol:t.symbol,shortName:T(t.symbol),direction:"forward",connectedSymbols:i}}function vw(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 ww=6,yl=10,jp=3,Hp=8,d5=.7,Cw=24,$p=200,Lw=12,xw=80,Rw=600;function m5(e,t,n={}){let r=n.impactDepth??3,i=n.sliceDepth??3,o=n.semantic,s=R5(t)?g5(e,t):null,a=s?s.primary?.symbol??null:t,{traceResult:c,callGraphResult:u,complexityResult:l,dataflowResult:d,backwardSliceResult:m,forwardSliceResult:p,affectedResults:f,reuseCandidates:g,targetSymbol:h,affectedConsumerReuse:y}=p5(e,a,n,r,i),S=Ue("change-surface",t,()=>sp(e,t,{semantic:o}),D=>({symbols:D?.symbols.length??0,externalConsumers:D?.totalExternalConsumers??0})),b=Ue("system",t,()=>Im(e,t),D=>({files:D.files.length,symbols:D.symbols.length})),x=b.files.length===1,v=Ue("deps",t,()=>x?b.dependsOn.map(D=>({relativePath:D,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):Zo(e,t),D=>({files:D.length,reusedSystem:x})),C=Ue("rdeps",t,()=>x?b.dependedOnBy.map(D=>({relativePath:D,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):es(e,t),D=>({files:D.length,reusedSystem:x})),R=Ue("surface",t,()=>wm(e,t),D=>({consumers:D.length})),E={symbol:c.definitions.length>0||c.referencedBy.length>0||u!==null||l!==null||d!==null||m!==null||p!==null||f.length>0,file:S!==null||v.length>0||C.length>0,module:b.files.length>0||b.symbols.length>0||R.length>0},w=[];s&&!s.primary&&s.callableCount>1&&w.push(`File target has ${s.callableCount} callable symbols; use one callable name for compiler-resolved flow.`);let I=[...new Set(c.referencedBy.map(D=>D.relativePath))];I.length>0&&I.every(D=>U(D)==="test")&&w.push("Only test references were found for this target. For replacement or retirement work, map the currently wired owner or one production entry point before planning; this target does not describe the live affected surface."),!E.symbol&&!E.file&&!E.module&&w.push("No symbol, file, or module matched target.");let k=S?.file??c.definitions[0]?.relativePath??null;return{target:t,...s?.primary?{primaryCallable:{symbol:s.primary.symbol,shortName:G(s.primary.symbol),file:s.primary.relativePath}}:{},matched:E,history:Ue("history",k??t,()=>x5(e,k,n.gitHead)),trace:f5(c),callGraph:u,complexity:l,dataflow:d,backwardSlice:m,forwardSlice:p,affected:f,changeSurface:S,deps:v,rdeps:C,system:b,surface:R,reuseCandidates:g,affectedConsumerReuse:y,sourcePacket:h5(e,h,c,y,g),warnings:w}}function p5(e,t,n,r,i){let o=n.semantic,s=t?Ue("trace",t,()=>Yd(e,t,{semantic:o,referenceContext:Lw}),h=>({definitions:h.definitions.length,references:h.referencedBy.length})):{definitions:[],referencedBy:[],claimSupport:null},a=t?Ue("call-graph",t,()=>Qo(e,t,{semantic:o}),h=>({callers:h?.callers.length??0,callees:h?.callees.length??0})):null,c=t?Ue("complexity",t,()=>Op(e,t,{semantic:o}),h=>({callees:h?.calleeCount??0})):null,u=t?Ue("dataflow",t,()=>Bp(e,t,{semantic:o}),h=>({references:h?.usageSites.length??0,producers:h?.producers.length??0,consumers:h?.consumers.length??0})):null,l=t?Ue("backward-slice",t,()=>gl(e,t,{direction:"backward",maxDepth:i,semantic:o}),h=>({maxDepth:i,connectedSymbols:h?.connectedSymbols.length??0})):null,d=t?Ue("forward-slice",t,()=>gl(e,t,{direction:"forward",maxDepth:i,semantic:o}),h=>({maxDepth:i,connectedSymbols:h?.connectedSymbols.length??0})):null,m=t?Ue("affected",t,()=>op(e,t,{maxDepth:r,scope:n.scope}),h=>({maxDepth:r,affectedSymbols:h.length})):[],p=t?Ue("reuse-candidates",t,()=>bs(e,t,{minSimilarity:.4,limit:5,semantic:o,sourceCandidateMode:"target-pruned"}),h=>({candidates:h.length,direct:h.filter(y=>y.actionTier==="direct").length})):[],f=t?re(e,t)?.symbol??null:null,g=t?Ue("affected-consumer-reuse",t,()=>y5(s,f,h=>bs(e,h,{minSimilarity:.4,limit:yl,semantic:o,sourceCandidateMode:"target-pruned"}),{consumerLimit:ww,perConsumerSearchLimit:yl,perConsumerCandidateLimit:jp,candidateLimit:Hp}),h=>({totalConsumers:h.coverage.totalConsumers,analyzedConsumers:h.coverage.analyzedConsumers,candidates:h.candidates.length})):C5();return{traceResult:s,callGraphResult:a,complexityResult:c,dataflowResult:u,backwardSliceResult:l,forwardSliceResult:d,affectedResults:m,reuseCandidates:p,targetSymbol:f,affectedConsumerReuse:g}}function f5(e){return{definitions:e.definitions,referencedBy:e.referencedBy.map(t=>({relativePath:t.relativePath,line:t.line,enclosingSymbol:t.enclosingSymbol,enclosingShort:t.enclosingShort}))}}function g5(e,t){let n=Tr(e,t);if(n.length!==1)return{primary:null,callableCount:0};let r=q(e,n[0]).filter(s=>s.isFunctionLike),i=r.filter(s=>s.enclosingSymbol===null),o=i.length>0?i:r;return{primary:o.length===1?o[0]:null,callableCount:o.length}}function h5(e,t,n,r,i){let o=[...t?[{definition:Ew(e,t),role:"target"}]:[],...[...r.candidates.map(d=>d.candidate),...i].map(d=>({definition:Ew(e,d.symbolB),role:"reuse-candidate"}))],s=new Map;for(let d of vw(o)){if(s.has(d.definition.symbol))continue;let m=d.role==="target"?$p:xw,p=d.definition.endLine<=d.definition.startLine?Jn(e,d.definition.relativePath,d.definition.startLine,m):null,f=p?.unitType?p.source:mt(e,d.definition);if(!f)continue;let g=f.split(`
433
- `),h=Math.min(g.length,m),y=p?.unitType?p.startLine:d.definition.startLine;s.set(d.definition.symbol,{role:d.role,symbol:d.definition.symbol,shortName:G(d.definition.symbol),file:d.definition.relativePath,startLine:y,endLine:y+h-1,source:g.slice(0,h).join(`
434
- `),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")],u=[],l=Rw;for(let d of c){if(u.length>=Cw||l<=0)break;let m=d.source.split(`
435
- `),p=Math.min(m.length,l);u.push({...d,endLine:d.startLine+p-1,source:m.slice(0,p).join(`
436
- `),omittedLines:d.omittedLines+Math.max(0,m.length-p),...d.focusLines?{focusLines:d.focusLines.filter(f=>f<=d.startLine+p-1)}:{}}),l-=p}return{slices:u,candidateSlices:c.length,omittedSlices:Math.max(0,c.length-u.length),maxSlices:Cw,maxLinesPerSlice:$p,maxTotalLines:Rw,targetLineLimit:$p,consumerContextLines:Lw,reuseLineLimit:xw}}function Ew(e,t){let n=Lr(e,t);return n?q(e,n.relativePath).find(r=>r.symbol===t)??null:null}function y5(e,t,n,r={}){let i=hl(r.consumerLimit,ww),o=hl(r.perConsumerSearchLimit,yl),s=hl(r.perConsumerCandidateLimit,jp),a=hl(r.candidateLimit,Hp),c=b5(e),u=c.slice(0,i),l=new Set(c.map(p=>p.symbol));t&&l.add(t);let d=new Map;for(let p of u){let f=n(p.symbol).slice(0,o),g=0;for(let h of f){let y=S5(h,p.symbol);if(!y||l.has(y.symbolB))continue;let S=d.get(y.symbolB);if(S?(S.consumers.some(b=>b.symbol===p.symbol)||S.consumers.push(p),y.similarity>S.candidate.similarity&&(S.candidate=y)):d.set(y.symbolB,{candidate:y,consumers:[p]}),g+=1,g>=s)break}}let m=[...d.values()].filter(p=>p.candidate.actionTier==="direct"||p.candidate.similarity>=d5||p.consumers.length>1).sort(v5).slice(0,a);return{candidates:m,coverage:{totalConsumers:c.length,analyzedConsumers:u.length,omittedConsumers:Math.max(0,c.length-u.length),perConsumerSearchLimit:o,perConsumerCandidateLimit:s,candidateLimit:a,returnedCandidates:m.length}}}function b5(e){let t=new Map;for(let n of e.referencedBy){if(!n.enclosingSymbol)continue;let r=t.get(n.enclosingSymbol);if(r){r.referenceCount+=1;continue}t.set(n.enclosingSymbol,{symbol:n.enclosingSymbol,shortName:G(n.enclosingSymbol)||n.enclosingShort,file:n.relativePath,referenceCount:1})}return[...t.values()].sort((n,r)=>r.referenceCount-n.referenceCount||n.symbol.localeCompare(r.symbol))}function S5(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 v5(e,t){let n=Iw(t.candidate.actionTier)-Iw(e.candidate.actionTier);if(n!==0)return n;let r=t.consumers.length-e.consumers.length;if(r!==0)return r;let i=t.candidate.similarity-e.candidate.similarity;return i!==0?i:e.candidate.symbolB.localeCompare(t.candidate.symbolB)}function Iw(e){return e==="direct"?1:0}function hl(e,t){return typeof e=="number"&&Number.isFinite(e)?Math.max(1,Math.floor(e)):t}function C5(){return{candidates:[],coverage:{totalConsumers:0,analyzedConsumers:0,omittedConsumers:0,perConsumerSearchLimit:yl,perConsumerCandidateLimit:jp,candidateLimit:Hp,returnedCandidates:0}}}function Ue(e,t,n,r=()=>({})){let i;return N(`context.${e}`,()=>(i=n(),i),()=>({target:t,...r(i)}))}function x5(e,t,n){let r={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return r;let i=Kt(e,n?{head:n}:{}),o=Ue("history.churn",t,()=>i.fileChurn(),c=>({files:c?.size??0}));if(!o)return r;let s=Ue("history.co-change",t,()=>Es(e,t,{limit:5,...n?{head:n}:{}}),c=>({commits:c.commitsAnalyzed,partners:c.findings.length})),a=Ue("history.suppressions",t,()=>fl(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 R5(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}var Pe={dead:{minLoc:1,skipBarrels:!1,deadCodeOnly:!1},isolated:{minLoc:3},similar:{minSimilarity:.6,limit:50,minCallees:4},duplicateBodies:{maxLoc:15,limit:50},extract:{minLoc:15,minCallees:5,limit:50},wrappers:{maxLoc:15,limit:50},passthroughs:{maxLoc:15,limit:50},stale:{minLoc:3,limit:50},drift:{},twinDrift:{minSimilarity:.3}};import{existsSync as E5}from"fs";import{isAbsolute as I5,join as w5}from"path";var L5=".scipquery-baseline.json";function Up(e){if(e.startsWith("similar:")){let t=e.slice(8).split("|");return t.length!==2?e:`similar:${t.map(T).sort().join("|")}`}if(e.startsWith("duplicate-bodies:")){let t=e.slice(17),n=t.indexOf(":");if(n<0)return e;let r=t.slice(0,n),i=t.slice(n+1).split("|");return i.length<2?e:`duplicate-bodies:${r}:${i.map(T).sort().join("|")}`}return e}function qp(e,t){return t&&I5(t)?t:w5(e.config.projectRoot,t??L5)}function Pw(e,t,n={}){let r=qp(e,n.path);if(!E5(r))throw new Error(`No baseline found at ${r}. Create one with: scip-query health --write-baseline`);let o=(JSON.parse(Xe(r,"health baseline")).findings??[]).map(Up),s=new Set(n.accept?o.filter(n.accept):o),a=new Set(t);return{baselinePath:r,baselineCount:s.size,current:[...t],newFindings:t.filter(c=>!s.has(c)),fixedFindings:[...s].filter(c=>!a.has(c))}}import Ds from"path";function Ts(e,t){let{scope:n,minDeviation:r=5,limit:i=50}=t??{},o=t?.semantic!==!1,s=t?.includePatternDeviations===!0,c=new H(e).fileDependencyGraph(n),u=gs(e,{scope:n}),l=k5([...P5(e,c,{scope:n,semantic:o}),...M5(u.forbiddenEdges),...s?T5(c,r):[]]);return t?.includeArchitecture===!0&&(l.architecture=u),i<=0||l.results.length<=i?l:{...l,results:l.results.slice(0,i),totalResults:l.results.length}}function P5(e,t,n){let r=N5(e,n.scope),i=[],o=new Set;for(let[a,c]of t){if(Ms(a))continue;let u=r.get(a)??new Set;for(let l of c)Ms(l)||u.has(l)||D5(e,a,l,n)||(i.push({file:a,dep:l}),o.add(a))}o.size>0&&B5(e,r,{paths:[...o]});let s=[];for(let{file:a,dep:c}of i)(r.get(a)??new Set).has(c)||s.push({file:a,kind:"unused-import",description:`Depends on ${c} but references none of its symbols`,dep:c,actionTier:"direct",evidenceReasons:[`dependency edge exists from ${a} to ${c}`,"no semantic, source, type-only, side-effect, or Vue-template usage survived the conservative skip gates"],recommendation:"Remove the unused import or dependency edge after running the project checks."});return s}function D5(e,t,n,r){return H5(e,t,n)||U5(e,t,n)||$5(n)||G5(e,t,n)||q5(n)?!0:r.semantic&&j5(e,t,n)}function M5(e){return e.flatMap(t=>{let n=t.examples[0];return n?[{file:n.fromFile,kind:"architecture-violation",description:`${t.from} depends on forbidden boundary ${t.to} through ${t.fileEdgeCount} file edge(s)`,dep:n.toFile,detail:`${t.from} may not depend on ${t.to}`,actionTier:"direct",policyBasis:"explicit",architecture:{fromBoundary:t.from,toBoundary:t.to,fileEdgeCount:t.fileEdgeCount,importerCount:t.importerCount,importedFileCount:t.importedFileCount,examples:t.examples},evidenceReasons:[`configured dependency row for ${t.from} does not allow ${t.to}`,`${t.fileEdgeCount} file edge(s) connect ${t.importerCount} importer(s) to ${t.importedFileCount} imported file(s)`,...t.examples.map(r=>`${r.fromFile} imports ${r.toFile}`)],recommendation:"Move the dependency behind an allowed boundary, reverse the dependency through an owned interface, or deliberately update the project architecture rule."}]:[]})}function T5(e,t){let n=[];for(let[r,i]of A5(e)){let o=i.filter(a=>!Ms(a));if(o.length<t)continue;let s=F5(e,o);for(let a of o)for(let c of e.get(a)??[])Ms(c)||(s.get(c)??0)===1&&Ds.dirname(c)!==r&&Ds.dirname(c)!==Ds.dirname(r)&&n.push({file:a,kind:"pattern-deviation",description:`Only file in ${r}/ that depends on ${c}`,dep:c,actionTier:"signal",evidenceReasons:[`${o.length} sibling file(s) in ${r}/ were compared`,`${a} is the only non-skipped sibling depending on ${c}`],recommendation:"Review sibling ownership before changing this import; unique dependency shape can be intentional specialization."})}return n}function k5(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 A5(e){let t=new Map;for(let n of e.keys()){let r=Ds.dirname(n),i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function F5(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])Ms(i)||n.set(i,(n.get(i)??0)+1);return n}function N5(e,t){let n=new Map;return _5(e,n,t),n}function _5(e,t,n){for(let r of O5(e,n))Dw(e,t,r.from_file,r.to_file)}function O5(e,t){let n=t?"AND d1.relative_path LIKE ?":"",r=t?[`%${t}%`]:[];return e.all(`SELECT DISTINCT d1.relative_path AS from_file, d2.relative_path AS to_file
437
- FROM mentions m
438
- JOIN chunks c ON m.chunk_id = c.id
439
- JOIN documents d1 ON c.document_id = d1.id
440
- JOIN global_symbols gs ON m.symbol_id = gs.id
441
- JOIN (
442
- SELECT m2.symbol_id, c2.document_id
443
- FROM mentions m2
444
- JOIN chunks c2 ON m2.chunk_id = c2.id
445
- WHERE m2.role = 1
446
- GROUP BY m2.symbol_id
447
- ) sym_def ON sym_def.symbol_id = gs.id
448
- JOIN documents d2 ON sym_def.document_id = d2.id
449
- WHERE d1.id != d2.id
450
- AND m.role != 1
451
- ${e.pathExclusionsFor("d1","d2")}
452
- ${n}`,...r)}function B5(e,t,n={}){new H(e).scanSourceReferences({paths:n.paths??Q(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},i=>{i.target.relativePath!==i.sourceFile&&(e.isIgnored(i.target.relativePath)||Dw(e,t,i.sourceFile,i.target.relativePath))})}function Dw(e,t,n,r){if(e.isIgnored(n)||e.isIgnored(r))return;let i=t.get(n);i||(i=new Set,t.set(n,i)),i.add(r)}function $5(e){return e.includes("types")||e.endsWith(".d.ts")}function j5(e,t,n){return Uo(e,t).filter(i=>i.sourcePath===n).some(i=>i.isUsed)}function H5(e,t,n){return ce(e,t).filter(i=>i.sourcePath===n).some(i=>i.used)}function U5(e,t,n){let r=ce(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.every(i=>i.isTypeOnly===!0)}function q5(e){return e.endsWith(".vue")}function G5(e,t,n){let r=ce(e,t).filter(i=>i.sourcePath===n);return r.length===0?!1:r.every(i=>i.kind==="side-effect"||i.kind==="namespace"&&i.usedMembers.length===0&&!i.used)}function Ms(e){let t=U(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||z5(Ds.basename(e)))}function z5(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 ks(e,t){let{scope:n,minLoc:r=3,maxLoc:i=80,limit:o=30,includeLowConfidence:s=!1,scanLimit:a}=t??{},c=t?.semantic!==!1,u=new H(e),l=u.scopedDefinitions(n),d=rX(u,n),m={high:0,medium:1,low:2};return Bt({candidates:()=>K5(e,u,l,{minLoc:r,maxLoc:i}),orderCandidates:(p,f)=>ee(f)-ee(p)||p.relativePath.localeCompare(f.relativePath),scanLimit:a,profile:{name:"stale-abstractions"},prepare:p=>{let f=V5(p),g=W5(e,u,p,f,{semantic:c}),h=p.filter(y=>{if(u.hasSuppressionComment(y))return!1;let S=bl(e,y,g,f);return S.realConsumers.length<=1&&!S.transitivelyReachable&&Mw(y,S.realConsumers.length,d)});return{consumerFileMap:g,singletonBackedClassIds:X5(e,u,l,h,{semantic:c}),candidateIndex:f}},evaluate:(p,f)=>{if(u.hasSuppressionComment(p)||f.singletonBackedClassIds.has(p.symbolId))return null;let g=bl(e,p,f.consumerFileMap,f.candidateIndex);if(g.transitivelyReachable||g.realConsumers.length>1||g.realConsumers.length===0&&g.barrelConsumers>0||!Mw(g.definition,g.realConsumers.length,d))return null;let h=Y5(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 K5(e,t,n,r){return n.filter(i=>i.isTypeLike&&ee(i)>=r.minLoc).filter(i=>ee(i)<=r.maxLoc).filter(i=>!e.isIgnored(i.relativePath)).filter(i=>!i.relativePath.endsWith(".d.ts")).filter(i=>U(i.relativePath)!=="test").filter(i=>!Be(e,i.symbol,i.relativePath)).filter(i=>!iX(i.symbol))}function Gp(e,t,n,r){return On(_n(e,t).forDefinitions(n,{semantic:r.semantic,sourceFallback:r.sourceFallback}))}function W5(e,t,n,r,i){let o=Gp(e,t,n,{semantic:!1,sourceFallback:!1}),s=n.filter(u=>{let l=bl(e,u,o,r);return l.realConsumers.length<=1&&!(l.realConsumers.length>0&&zp(u.relativePath))}),a=i.semantic&&s.length>0?on(o,Gp(e,t,s,{semantic:!0,sourceFallback:!1})):o,c=s.filter(u=>bl(e,u,a,r).realConsumers.length<=1);return on(a,Gp(e,t,c,{semantic:!1,sourceFallback:!0}))}function V5(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);r||(r=new Map,t.set(n.relativePath,r));let i=G(n.symbol);i&&r.set(i,n)}return t}function bl(e,t,n,r){let o=[...n.get(t.symbolId)??new Set].filter(l=>l!==t.relativePath&&!e.isIgnored(l)),{realConsumers:s,barrelConsumers:a,importOnlyConsumers:c}=Zc(e,t,o),u=oX(e,t,n,r);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:u}}function Y5(e,t){let n=kw(e,t.definition.relativePath,t.definition.startLine),r=zp(t.definition.relativePath)?!0:sX(e,t.definition),{confidence:i,reason:o}=aX(t.realConsumers.length,n,r),s=J5(t.realConsumers.length,n,r);return{symbol:t.definition.symbol,shortName:T(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:ee(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:r,confidence:i,reason:o,actionTier:s.actionTier,stalenessKind:s.stalenessKind,recommendation:s.recommendation}}function J5(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 X5(e,t,n,r,i){let o=Z5(e,Q5(n),r),s=o.map(u=>u.singleton);if(o.length===0)return new Set;let a=On(_n(e,t).forDefinitions(s,{semantic:i.semantic,sourceFallback:!0})),c=new Set;for(let{singleton:u,classId:l}of o)tX(e,u,a)&&c.add(l);return c}function Q5(e){let t=new Map;for(let n of e){let r=G(n.symbol);r&&t.set(Tw(n.relativePath,r),n)}return t}function Z5(e,t,n){let r=[];for(let i of n){let o=eX(e,t,i);o&&r.push({singleton:o,classId:i.symbolId})}return r}function eX(e,t,n){if(kw(e,n.relativePath,n.startLine)!=="class")return null;let r=G(n.symbol);if(!r)return null;let i=nX(e,n.relativePath,r);return i?t.get(Tw(n.relativePath,i))??null:null}function tX(e,t,n){let r=G(t.symbol),i=n.get(t.symbolId);return!r||!i?!1:[...i].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!Zm(e,o,r))}function Tw(e,t){return`${e}\0${t}`}function nX(e,t,n){let r=V(e,t);if(!r)return null;let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\bexport\\s+const\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*new\\s+${i}\\s*\\(`);return r.match(o)?.[1]??null}function rX(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function iX(e){let t=Un(e);if("kind"in t)return!1;let n=t.descriptors;if(n.length<2)return!1;let r=n[n.length-1],i=n[n.length-2];return r?.suffix==="type"&&i?.suffix==="type"}function zp(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 Mw(e,t,n){return!(zp(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function oX(e,t,n,r){let i=lg(e,t.relativePath),o=G(t.symbol);if(!o)return!1;let s=r.get(t.relativePath);if(!s)return!1;let a=[...i.get(o)??[]],c=new Set;for(;a.length>0;){let u=a.pop();if(c.has(u))continue;c.add(u);let l=s.get(u);if(!l)continue;let d=n.get(l.symbolId);if(d){for(let m of d)if(m!==t.relativePath&&!e.isIgnored(m))return!0}for(let m of i.get(u)??[])a.push(m)}return!1}function kw(e,t,n){let r=V(e,t);if(!r)return"other";let i=r.split(`
453
- `),o=Math.max(0,n-2),s=Math.min(i.length-1,n+2);for(let a=o;a<=s;a++){let u=(i[a]??"").replace(/^\s*\/\/.*$/g,"");if(/\b(?:export\s+)?(?:abstract\s+)?class\s+\w/.test(u))return"class";if(/\b(?:export\s+)?interface\s+\w/.test(u))return"interface";if(/\b(?:export\s+)?type\s+\w/.test(u))return"type";if(/\b(?:export\s+)?(?:const\s+)?enum\s+\w/.test(u))return"enum"}return"other"}function sX(e,t){let n=V(e,t.relativePath);if(!n)return!1;let r=G(t.symbol);if(!r)return!1;let i=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${i}\\b`),s=n.split(`
454
- `);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function aX(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 ro,extname as Sl}from"path";function As(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new H(e),a=vX(s.fileDependencyGraph(n)),c=new Map,u=Bt({candidates:()=>gX(e,s,n,r),orderCandidates:uc,scanLimit:o,profile:{name:"wrapper-candidates"},prepare:l=>({callerFileMap:cX(e,s,l,{semantic:t?.semantic!==!1}),reverseFanIn:a,receivers:c}),evaluate:(l,d)=>lX(e,s,l,d),orderResults:(l,d)=>d.callerFanIn-l.callerFanIn||d.loc-l.loc,limit:i});return pX(u,c)}function cX(e,t,n,r){let i=_n(e,t),o=On(i.forDefinitions(n,{semantic:!1,sourceFallback:!1})),s=[];r.semantic&&N("wrapper.semantic-candidates",()=>{s=n.filter(m=>Kp(e,t,m,o).length<=1)},()=>({symbols:n.length,semanticCandidates:s.length}));let a=s.length===0?new Map:On(i.forDefinitions(s,{semantic:!0,sourceFallback:!1})),c=a.size===0?o:on(o,a),u=new Map(n.map(m=>[m.symbolId,m])),l=new Map;for(let m of n){let p=Kp(e,t,m,c);if(p.length>1||(l.set(m.symbolId,m),p.length!==1))continue;let f=p[0],g=Aw(e,m.symbolId,f);if(!g)continue;let h=Fw(t,e,f,m.symbol,g);h?.isFunctionLike&&u.has(h.symbolId)&&l.set(h.symbolId,u.get(h.symbolId))}let d=[...l.values()];return d.length===0?c:on(c,On(i.forDefinitions(d,{semantic:!1,sourceFallback:!0})))}function lX(e,t,n,r){let i=Kp(e,t,n,r.callerFileMap);if(i.length!==1)return null;let o=i[0],s=Aw(e,n.symbolId,o);if(!s)return null;let a=Fw(t,e,o,n.symbol,s);if(a&&gi(a.symbol))return null;let{fanIn:c,source:u}=bX(r.callerFileMap,r.reverseFanIn,o,a);if(u==="function"?c<=3:c<=5)return null;let l=xX(e,n,o,a),d=fX(e,n);d==="helper"&&l.push("body computes or branches rather than forwarding one call");let m=d==="forwarding"?uX(e,n):null;m&&r.receivers.set(n.symbol,m);let p=m&&dX(e,n.relativePath,m)?m:null;return p&&l.push(`forwards through module-private state: ${p}`),{symbol:n.symbol,shortName:T(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:ee(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?T(a.symbol):ro(o),callerFanIn:c,actionTier:l.length>0?"signal":"direct",bodyShape:d,boundaryEvidence:l}}function uX(e,t){let n=mt(e,t);if(!n)return null;let r=Dt(Rt(n)).trim(),i=/^(?:return\s+)?(?:await\s+)?([A-Za-z_$][\w$]*)\s*[.(]/.exec(r)?.[1];return!i||i==="this"||i==="super"?null:i}function dX(e,t,n){let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`^(?:const|let|var)\\s+${r}\\b`);return K(e,t).some(o=>i.test(o))}var mX=3;function pX(e,t){let n=new Map,r=i=>{let o=t.get(i.symbol);return o&&i.bodyShape==="forwarding"?`${i.file}\0${o}`:null};for(let i of e){let o=r(i);o&&n.set(o,(n.get(o)??0)+1)}return e.map(i=>{let o=r(i),s=o?n.get(o)??0:0;if(s<mX)return i;let a=t.get(i.symbol);return{...i,actionTier:"signal",boundaryEvidence:[...i.boundaryEvidence,`facade: ${s} sibling forwards from this file through ${a}`]}})}function fX(e,t){let n=mt(e,t);return n&&zI(n)?"forwarding":"helper"}function gX(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:2,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0}).filter(i=>!Vs(e,i)).filter(i=>!hX(i.leaf))}function hX(e){return typeof e=="string"&&e.startsWith("<")&&e.endsWith(">")}function Kp(e,t,n,r){let i=ro(n.relativePath,Sl(n.relativePath)),o=[...r.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>ro(s,Sl(s))!==i).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return Zc(e,n,o).realConsumers}function Aw(e,t,n){return e.get(`SELECT c.start_line, c.end_line
455
- FROM mentions m
456
- JOIN chunks c ON m.chunk_id = c.id
457
- JOIN documents d ON c.document_id = d.id
458
- WHERE m.symbol_id = ? AND m.role != 1 AND d.relative_path = ?
459
- LIMIT 1`,t,n)}function Fw(e,t,n,r,i){let o=e.definitionsForFile(n);for(let s of yX(t,n,r,i.start_line,i.end_line)){let a=Oe(o,s);if(a?.isFunctionLike)return a}return Oe(o,SX(t,n,r,i.start_line,i.end_line))}function yX(e,t,n,r,i){let o=G(n);return o?(wr(e,t).get(o)??[]).filter(s=>s>=r&&s<=i):[]}function bX(e,t,n,r){if(r?.isFunctionLike){let i=[...e.get(r.symbolId)??[]].filter(o=>o!==r.relativePath);if(i.length>0)return{fanIn:i.length,source:"function"}}return{fanIn:CX(t,n),source:"file"}}function SX(e,t,n,r,i){let o=G(n);if(!o)return r;let s=wr(e,t).get(o);if(!s||s.length===0)return r;for(let a of s)if(a>=r&&a<=i)return a;return r}function vX(e){let t=new Map;for(let[n,r]of e){t.has(n)||t.set(n,t.get(n)??0);for(let i of r)t.set(i,(t.get(i)??0)+1)}return t}function CX(e,t){let n=e.get(t)??0;if(n>0)return n;let r=ro(t,Sl(t)),i=0;for(let[o,s]of e)o!==t&&ro(o,Sl(o))===r&&s>i&&(i=s);return i}function xX(e,t,n,r){return dl(e,t.relativePath,t.startLine,"wrapper","explicit ignore-wrapper comment",[{label:"wrapper name",value:fi(t.symbol),side:"self"},{label:"caller name",value:r?.symbol?fi(r.symbol):ro(n),side:"other"},{label:"wrapper path",value:t.relativePath,side:"self"},{label:"caller path",value:n,side:"other"}])}var RX=25e3,EX=2500,IX=2500;function wX(e){let t=qr(e);return t.symbols>=RX||t.documents>=EX?IX:void 0}function Wp(e,t={}){let{scope:n}=t,r=wX(e),i=[],o=ti(e,{scope:n,...Pe.dead,scanLimit:r});for(let s of o.symbols)ze(e,s.relativePath)||Be(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&i.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of hs(e,{scope:n,...Pe.isolated,scanLimit:r}))ze(e,s.relativePath)||Be(e,s.symbol,s.relativePath)||i.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of fs(e,{scope:n}))s.kind==="real"&&i.push(`cycle:${LX(s.path)}`);for(let s of Ss(e,{scope:n,...Pe.similar,scanLimit:r}))i.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of Pp(e,{scope:n,...Pe.duplicateBodies,scanLimit:r}))i.push(`duplicate-bodies:${s.hash}:${s.functions.map(a=>a.symbol).sort().join("|")}`);for(let s of xs(e,{scope:n,...Pe.extract,scanLimit:r}))i.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of As(e,{scope:n,...Pe.wrappers,scanLimit:r}))i.push(`wrapper:${s.file}:${s.shortName}`);for(let s of ws(e,{scope:n,...Pe.passthroughs,scanLimit:r}))i.push(`passthrough:${s.file}:${s.shortName}`);for(let s of ks(e,{scope:n,...Pe.stale,scanLimit:r}))i.push(`stale:${s.file}:${s.shortName}`);for(let s of Ts(e,{scope:n,...Pe.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY}).results)s.kind!=="architecture-violation"&&i.push(`drift:${s.kind}:${s.file}:${s.dep}`);return i.push(...km(gs(e,{scope:n}))),[...new Set(i.map(Up))].sort()}function LX(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 PX(e,t={}){let n=Wp(e,{scope:t.scope}),r=qp(e,t.path);return _g(r,{version:1,findings:n},{spacing:2,trailingNewline:!0}),{path:r,findingCount:n.length}}function DX(e,t={}){return Pw(e,Wp(e,{scope:t.scope}),{path:t.path})}function MX(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new H(e);return Bt({candidates:()=>o.productionCallableDefinitions({scope:n,files:t.files,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}),filterCandidate:s=>TX(s.relativePath),scanLimit:i,profile:{name:"unused-params"},evaluate:s=>{let a=W(e,s.relativePath)?.callables.find(l=>l.startLine===s.startLine&&l.endLine===s.endLine);if(!a||a.params.length===0||a.params.some(l=>!l.simple)||a.paramsEndLine>=a.endLine)return null;let c=wr(e,s.relativePath),u=[];for(let l=a.params.length-1;l>=0;l--){let d=a.params[l];if(d.name===""||d.name.startsWith("_")||kX(c.get(d.name),a.paramsEndLine,a.endLine))break;u.unshift(d.name)}return u.length===0?null:{symbol:s.symbol,shortName:T(s.symbol),file:s.relativePath,startLine:s.startLine,endLine:s.endLine,paramCount:a.paramCount,unusedTrailing:u}},orderResults:(s,a)=>a.unusedTrailing.length-s.unusedTrailing.length||s.file.localeCompare(a.file)||s.startLine-a.startLine,limit:r})}function TX(e){let t=ae(e);return t==="typescript"||t==="tsx"||t==="javascript"}function kX(e,t,n){return e?e.some(r=>r>t&&r<=n):!1}var AX=new Set(Qt());function Vp(e,t){let{scope:n,minLoc:r=10,limit:i=30,scanLimit:o}=t??{},s=new H(e);return Bt({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:r,requireFunctionLikeSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,filterCandidate:FX,profile:{name:"complexity-hotspots"},prepare:a=>{let c=_X(e,a),u=t?.semantic!==!1,l=u?st(e):null;l?.materializeReferences(a,{prefetchCallees:!0});let d=s.crossFileCallerMap(a,{semantic:!1});return{callerMap:l?on(d,l.callerMap(a)):d,calleeMap:s.calleeMap(a,{semantic:u}),languageByFile:c,clojureCallableIds:OX(e,a,c),branchEstimates:fw(e,a)}},evaluate:(a,c)=>NX(a,c,r),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:i})}function FX(e){return e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&AX.has(e.kind):!0}function NX(e,t,n){if(t.languageByFile.get(e.relativePath)==="clojure"&&!t.clojureCallableIds.has(e.symbolId))return null;let r=e.endLine-e.startLine+1;if(r<n)return null;let i=t.callerMap.get(e.symbolId)?.size??0,o=t.calleeMap.get(e.symbolId)??[],s=new Set,a=new Set;for(let m of o){let p=`${m.symbol}|${m.file}`;s.add(p),m.file!==e.relativePath&&a.add(p)}let c=a.size,u=s.size,l=t.branchEstimates.get(e.symbolId)??{branches:0,estimateBasis:"regex-fallback"},d=l.branches+1;return{symbol:e.symbol,shortName:T(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:r,fanIn:i,fanOut:c,calleeCount:u,branches:l.branches,estimateBasis:l.estimateBasis,score:Math.round(r/50*(i/5)*Math.max(c/5,1)*Math.max(d/5,1)*100)/100}}function _X(e,t){let n=[...new Set(t.map(o=>o.relativePath))];if(n.length===0)return new Map;let r=n.map(()=>"?").join(", "),i=e.all(`SELECT relative_path, language
460
- FROM documents
461
- WHERE relative_path IN (${r})`,...n);return new Map(i.map(o=>[o.relative_path,o.language?.toLowerCase()??null]))}function OX(e,t,n){let r=new Set,i=new Map;for(let o of t){if(n.get(o.relativePath)!=="clojure")continue;let s=i.get(o.relativePath);s||(s=new Set((W(e,o.relativePath)?.callables??[]).map(a=>`${a.name}:${a.startLine}`)),i.set(o.relativePath,s)),s.has(`${o.leaf}:${o.startLine}`)&&r.add(o.symbolId)}return r}function Nw(e){let t;try{t=dt(e,["rev-parse","HEAD"]).trim()}catch{return null}return/^[0-9a-f]{40,64}$/u.test(t)?{head:t,branch:BX(e),dirtyPaths:$X(e)}:null}function BX(e){try{let t=dt(e,["rev-parse","--abbrev-ref","HEAD"]).trim();return t&&t!=="HEAD"?t:null}catch{return null}}function $X(e){try{return dt(e,["status","--porcelain"]).split(`
462
- `).filter(t=>t.length>0).length}catch{return 0}}import{readdirSync as jX}from"fs";import{basename as HX,join as _w}from"path";function UX(e,t,n={}){let r=new Set(e),i=new Set(t),o=[...i].filter(a=>!r.has(a)).sort(),s=n.allowExtra?[]:[...r].filter(a=>!i.has(a)).sort();return{missing:o,extra:s}}function qX(e,t){let n=GX(e,t.file,t.keys);if(!n.ok)return{name:t.name,file:t.file,status:"unavailable",missing:[],extra:[],unavailableReason:n.reason};let r=JX(e.config.projectRoot,t.mustEqual),i=UX(n.keys,r,{allowExtra:t.allowExtra??!1}),o=i.missing.length>0||i.extra.length>0?"violated":"ok";return{name:t.name,file:t.file,status:o,missing:i.missing,extra:i.extra}}function Bw(e,t){return t.map(n=>qX(e,n))}function GX(e,t,n){return n.type==="markdown-list"?YX(e,t,n.marker):zX(e,t,n)}function zX(e,t,n){if(!V(e,t))return{ok:!1,reason:`file not found: ${t}`};let i=ae(t);if(!i)return{ok:!1,reason:`unsupported file type for ${n.type} extraction: ${t}`};let o=J(e,t);if(!o)return{ok:!1,reason:`tree-sitter parser unavailable for ${i} (${t}) \u2014 contract skipped, not silently passed`,disclosedUnavailable:{language:i,reason:"parser-unavailable"}};let s=n.type==="object-literal-keys"?KX(o,n.identifier):VX(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 $w(e){let t=e.childForFieldName("value");return t?t.type==="as_expression"||t.type==="satisfies_expression"?t.namedChild(0):t:null}function KX(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=$w(n);if(i?.type==="object")return WX(i)}return null}function WX(e){let t=new Set;for(let n of e.namedChildren)if(n.type==="pair"){let r=n.childForFieldName("key");r&&t.add(jw(r.text))}else n.type==="shorthand_property_identifier"&&t.add(n.text);return[...t].sort()}function VX(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=$w(n);if(i?.type!=="array")continue;let o=new Set;for(let s of i.namedChildren)s.type==="string"&&o.add(jw(s.text));return[...o].sort()}return null}function jw(e){return e.length>=2&&(e[0]==="'"&&e.endsWith("'")||e[0]==='"'&&e.endsWith('"'))?e.slice(1,-1):e}function YX(e,t,n){let r=V(e,t);if(!r)return{ok:!1,reason:`file not found: ${t}`};let i=Hw(r,n);return i===null?{ok:!1,reason:`no <!-- BEGIN GENERATED ${n} --> ... <!-- END GENERATED ${n} --> block in ${t}`}:{ok:!0,keys:Uw(i)}}function Hw(e,t){let n=Ie(t),i=new RegExp(`<!--\\s*BEGIN GENERATED ${n}\\s*-->([\\s\\S]*?)<!--\\s*END GENERATED ${n}\\s*-->`).exec(e);return i?i[1]:null}function Uw(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 JX(e,t){switch(t.type){case"top-level-dirs":return Ow(_w(e,t.path));case"file-glob":return[...new Set(zc(e,t.pattern).map(n=>HX(n)))].sort();case"registered-commands":return XX(e);case"builtin-skills":return Ow(_w(e,"skills"))}}function Ow(e){let t;try{t=jX(e,{withFileTypes:!0})}catch{return[]}return t.filter(n=>n.isDirectory()&&!n.name.startsWith(".")).map(n=>n.name).sort()}function XX(e){let t;try{t=ve(e,"docs/COMMAND_REFERENCE.md",{maxBytes:8*1024*1024,inputKind:"generated command reference"})}catch(r){if(!Ce(r))throw r;return[]}let n=Hw(t,"COMMAND REFERENCE");return n?Uw(n):[]}function pn(e){return e.scoreCount??e.count}function zw(e,t){let n=r4(e),{breakdown:r,pressure:i}=i4(e),o=Gw(r,"risk"),s=Gw(r,"hygiene");return{score:Math.min(o,s),riskScore:o,hygieneScore:s,scoreBreakdown:r,overview:{documents:e.statsResult.documents,symbols:e.statsResult.symbols,indexSizeBytes:e.statsResult.indexSizeBytes},...t?{provenance:t}:{},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:pn(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:pn(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:pn(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:e4(e),validation:n4(e),suppressions:e.suppressions,actions:n,pressure:i,policyExclusions:ZX(e),topComplexity:e.complexity.top,detectorEvidence:e.detectorEvidence,warnings:e.warnings.length>0?e.warnings:void 0}}var QX=[["react-component-duplicates",e=>e.reactComponentDuplicates],["react-hook-candidates",e=>e.reactHookCandidates],["react-large-component-pressure",e=>e.reactLargeComponentPressure],["wrapper-candidates",e=>e.wrappers],["duplicate-bodies",e=>e.duplicateBodies],["dead",e=>e.dead]];function ZX(e){let t=[],n=(r,i)=>{for(let o of i??[])o.count<=0||t.push({detector:r,reason:o.reason,detail:o.detail,count:o.count})};for(let[r,i]of QX)n(r,i(e).exclusions);return n("extract-candidates",e.extractExclusions),n("complexity-hotspots",e.complexity.exclusions),n("co-change",e.gitEvidence?.hiddenCoupling.exclusions),t}function e4(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:t4(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 t4(e){let t=e.gitEvidence?.fileStats;return t?e.complexity.top.map(n=>{let r=n.file?t[n.file]?.changes??0:0;return{...n,changes:r,weighted:fn(n.score*Math.log2(1+r))}}).sort((n,r)=>r.weighted-n.weighted):null}function n4(e){let t=e.gitEvidence?.fileStats;if(!t)return null;let n={dead:e.dead.files??[],isolated:e.isolated.files??[],twinDrift:e.twinDrift.files??[],wrappers:e.wrappers.files??[],passthroughs:e.passthroughs.files??[],stale:e.stale.files??[],reactComponents:e.reactComponentDuplicates.files??[],reactHooks:e.reactHookCandidates.files??[],reactLargeComponents:e.reactLargeComponentPressure.files??[],vueComponents:e.vueComponentDuplicates.files??[],vueComposables:e.vueComposableCandidates.files??[],vueLargeViews:e.vueLargeViewPressure.files??[]},r=new Set(Object.values(n).flat()),i=0,o=0,s=0;for(let[l,d]of Object.entries(t))r.has(l)?i+=d.fixChanges:(o+=d.fixChanges,s+=1);let a=r.size>0?fn(i/r.size):0,c=s>0?fn(o/s):0,u={};for(let[l,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=fn(p/m.size);u[l]={flaggedFiles:m.size,fixDensity:f,lift:c>0?fn(f/c):null}}return{flaggedFiles:r.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:r.size>0&&c>0?fn(a/c):null,byCategory:u,validationBasis:{method:"subject-regex",commitsScanned:e.gitEvidence?.commitsScanned??0}}}function fn(e){return Math.round(e*100)/100}function Kw(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function Fs(e,t="existing shared infrastructure discount"){let n=pn(e);return Math.abs(n-e.count)<.01?"":` (${Kw(n)} score-weighted after ${t})`}function io(e,t){let n=pn(e),r=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?r:`${r} (${Kw(n)} score-weighted)`}function r4(e){let t=[];if(e.dead.count>0&&t.push({category:"Dead code",evidence:"graph-fact",evidenceContractId:"dead-visible-references",description:`${e.dead.count} indexed symbols with no visible repository references \u2014 review runtime/framework roots and the capability disclosure, then verify any deletion with cleanup-plan --verify`,effort:"low",impact:"high",count:e.dead.count,locRecoverable:e.dead.loc}),e.isolated.count>0&&t.push({category:"Isolated symbols",evidence:"graph-fact",evidenceContractId:"isolated-visible-connectivity",description:`${e.isolated.count} symbols with no visible indexed or source-supported caller/callee after root exclusions \u2014 runtime reflection and generated dispatch remain disclosed blind spots`,effort:"low",impact:"medium",count:e.isolated.count,locRecoverable:e.isolated.loc}),e.realCycleCount>0&&t.push({category:"Circular dependencies",evidence:"graph-fact",description:`${e.realCycleCount} indexed dependency cycle(s) \u2014 inspect ownership and runtime order before choosing whether or how to break them`,effort:"medium",impact:"high",count:e.realCycleCount,locRecoverable:0}),e.similarCount>0&&t.push({category:"Similar functions",evidence:"heuristic",evidenceContractId:"duplicate-structural-candidate",description:`${e.similarCount} pairs share disclosed call or source-token evidence beyond imports \u2014 review domain identity before considering consolidation`,effort:"medium",impact:"medium",count:e.similarCount,locRecoverable:0}),e.duplicateBodies.count>0&&t.push({category:"Duplicate function bodies",evidence:"heuristic",evidenceContractId:"duplicate-structural-candidate",description:`${e.duplicateBodies.count} exact small-body group(s) across files \u2014 consolidate only when the domain concept matches`,effort:"low",impact:"medium",count:e.duplicateBodies.count,locRecoverable:e.duplicateBodies.loc}),e.twinDrift.count>0&&t.push({category:"Drifted twin implementations",evidence:"heuristic",description:`${e.twinDrift.count} same-name (or near-name) function group(s) across files with diverged or identical bodies \u2014 determine whether they represent the same concept before acting`,effort:"medium",impact:"medium",count:e.twinDrift.count,locRecoverable:0}),e.reactComponentDuplicates.count>0&&t.push({category:"Duplicated React components",evidence:"heuristic",description:`${e.reactComponentDuplicates.count} React component pair(s) share JSX structure${Fs(e.reactComponentDuplicates,"support-tier discount")} \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${Fs(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${Fs(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 a contiguous region whose callees appear nowhere else in the body \u2014 review same-file or feature-local extraction seams`,effort:"medium",impact:"medium",count:e.extractCount,locRecoverable:0}),e.wrappers.count>0&&t.push({category:"Wrapper functions",evidence:"heuristic",evidenceContractId:"wrapper-indirection-candidate",description:`${e.wrappers.count} wrapper-shaped single-consumer callables${Fs(e.wrappers,"boundary-evidence discount")} \u2014 inspect whether each is indirection or an intentional API, framework, or ownership boundary`,effort:"low",impact:"low",count:e.wrappers.count,locRecoverable:e.wrappers.loc}),e.passthroughs.count>0&&t.push({category:"Passthrough functions",evidence:"heuristic",evidenceContractId:"passthrough-forwarding-candidate",description:`${e.passthroughs.count} functions that literally forward to one callee \u2014 inspect whether each is unnecessary indirection or an intentional boundary`,effort:"low",impact:"low",count:e.passthroughs.count,locRecoverable:e.passthroughs.loc}),e.stale.count>0){let i=[];e.stale.unused>0&&i.push(`${e.stale.unused} unused`),e.stale.singleUse>0&&i.push(`${e.stale.singleUse} single-consumer (not in types file)`),t.push({category:"Stale abstractions",evidence:"heuristic",evidenceContractId:"stale-abstraction-candidate",description:`${i.join(", ")} \u2014 review public, runtime-registration, and ownership evidence before removing, moving, or inlining`,effort:"low",impact:"medium",count:e.stale.count,locRecoverable:e.stale.loc})}if(e.drift.count>0){let i=[];e.drift.unusedImports>0&&i.push(`${e.drift.unusedImports} unused imports`),e.drift.architectureViolations>0&&i.push(`${e.drift.architectureViolations} declared architecture violations`),t.push({category:"Structural drift",evidence:"heuristic",description:`${i.join(", ")} \u2014 repair direct dependency-rule breaks; inspect boundary signals with \`drift --architecture\``,effort:e.drift.architectureViolations>0?"medium":"low",impact:e.drift.architectureViolations>0?"medium":"low",count:e.drift.count,locRecoverable:0})}if(e.coverageContracts.count>0&&t.push({category:"Coverage contract drift",evidence:"graph-fact",description:`${e.coverageContracts.count} configured coverage contract(s) drifted from their ground-truth source (enumeration rot) \u2014 run \`scip-query health --json\` for the missing/extra keys`,effort:"low",impact:"medium",count:e.coverageContracts.count,locRecoverable:0}),e.gitEvidence&&e.gitEvidence.hiddenCoupling.pairCount>0){let i=e.gitEvidence.hiddenCoupling.top[0];t.push({category:"Hidden coupling",evidence:"change-graph",description:`${e.gitEvidence.hiddenCoupling.pairCount} file pair(s) co-change without a structural link`+Fs({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:e.gitEvidence.hiddenCoupling.scoreCount},"broad/stale-history discount")+(i?` (e.g. ${i.fileA} \u2194 ${i.fileB})`:"")+" \u2014 inspect whether a shared concept, generated artifact, or coordinated contract explains the history",effort:"medium",impact:"high",count:e.gitEvidence.hiddenCoupling.pairCount,locRecoverable:0})}let n={high:3,medium:2,low:1},r={low:3,medium:2,high:1};return t.sort((i,o)=>{let s=n[i.impact]*r[i.effort];return n[o.impact]*r[o.effort]-s}),t}var qw={"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 Gw(e,t){let n=e.filter(r=>r.kind===t).reduce((r,i)=>r+i.points,0);return Math.max(0,Math.min(100,100-n))}function i4(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),r=[],i=[],o=(E,w,I)=>{w>0&&r.push({axis:E,points:w,detail:I,kind:qw[E]??"hygiene"})},s=(E,w,I,k,D,F,P)=>{let A=Math.max(k,1);if(I<=A)return;let L=I/A,$=Math.min(D,Math.ceil(Math.log2(L)*F));if($<=0)return;let B=qw[E]??"hygiene";i.push({axis:E,category:w,kind:B,count:I,threshold:fn(A),ratio:fn(L),extraPenalty:$}),o(E,$,`${I} ${P} exceed pressure threshold ${fn(A)} (${fn(L)}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 u=e.similarCount/n*1e3;o("similar",Math.min(10,Math.round(u)),`${e.similarCount} similar function pair(s)`);let l=e.duplicateBodies.count/n*1e3;o("duplicate-bodies",Math.min(10,Math.round(l*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=pn(e.reactComponentDuplicates),p=m/t*1e3;o("react-component-duplicates",Math.min(10,Math.round(p)),io(e.reactComponentDuplicates,"duplicated React component pair(s)"));let f=pn(e.reactHookCandidates),g=f/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(g)),io(e.reactHookCandidates,"duplicated React behavior pair(s)"));let h=e.reactLargeComponentPressure.count/t*1e3;o("react-large-component-pressure",Math.min(5,Math.round(h/2)),`${e.reactLargeComponentPressure.count} large React component pressure file(s)`);let y=e.vueComponentDuplicates.count/t*1e3;o("vue-component-duplicates",Math.min(10,Math.round(y)),`${e.vueComponentDuplicates.count} duplicated Vue component pair(s)`);let S=pn(e.vueComposableCandidates),b=S/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(b)),io(e.vueComposableCandidates,"duplicated Vue behavior pair(s)"));let x=e.vueLargeViewPressure.count/t*1e3;o("vue-large-view-pressure",Math.min(5,Math.round(x/2)),`${e.vueLargeViewPressure.count} large Vue view pressure file(s)`);let v=pn(e.wrappers);o("wrappers",Math.min(3,v),io(e.wrappers,"wrapper candidate(s)"));let C=pn(e.passthroughs);o("passthroughs",Math.min(3,C),io(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 R=e.drift.direct/t;if(o("drift",Math.min(5,Math.round(R*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 E=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(E/10)),io({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:E},"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,Math.max(3,Math.round(t*.005)),5,2,"extreme complexity hotspot(s)"),e.gitEvidence){let E=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",E,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",m,Math.max(10,t*.01),8,4,"duplicated React component pair(s)"),s("react-hook-candidates-pressure","Duplicated React hook behavior",f,Math.max(10,t*.01),8,4,"duplicated React behavior pair(s)"),s("react-large-component-pressure-pressure","Large React components",e.reactLargeComponentPressure.count,Math.max(10,t*.01),4,2,"large React component pressure file(s)"),s("vue-component-duplicates-pressure","Duplicated Vue components",e.vueComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated Vue component pair(s)"),s("vue-composable-candidates-pressure","Duplicated Vue behavior",S,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",v,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",C,50,4,2,"passthrough candidate(s)"),s("stale-abstractions-pressure","Single-consumer stale abstraction signals",e.stale.singleUse,Math.max(50,n*.02),4,2,"single-consumer stale abstraction signal(s)"),s("drift-pressure","Structural drift signals",e.drift.signal,Math.max(10,t*.1),4,2,"signal drift finding(s)"),{breakdown:r,pressure:i}}import{getHeapStatistics as o4}from"v8";var s4=64*1024*1024;function Yp(){let e=globalThis.gc;if(!e)return;let t=o4();t.heap_size_limit-t.used_heap_size<s4||e()}var a4=[{id:"dead-visible-references",detector:"dead",claim:"The symbol has no visible repository reference after entry, framework, and rooted-symbol exclusions.",relationRequirements:[{family:"identity",subtype:"references",minimumStrength:"exact"},{family:"execution",subtype:"call",minimumStrength:"exact"}],structuralEvidence:["entry-surface exclusions","framework/source fallback references","rooted-symbol exclusions"],calibration:"mixed",providerCoverage:"partial",nonClaims:["Absence of visible references does not prove absence of reflection, generated dispatch, or external use."],recoverWith:"scip-query evidence --symbol <symbol> --edge execution --edge runtime --edge identity --direction both --depth 2 --max-edges 100"},{id:"isolated-visible-connectivity",detector:"isolated",claim:"The callable has no visible non-self caller or callee after entry, framework, and rooted-symbol exclusions.",relationRequirements:[{family:"execution",subtype:"call",minimumStrength:"exact"},{family:"identity",subtype:"references",minimumStrength:"exact"}],structuralEvidence:["entry-surface exclusions","framework contract exclusions","source fallback callers"],calibration:"mixed",providerCoverage:"partial",nonClaims:["Visible graph isolation does not establish runtime unreachability through reflection or generated dispatch."],recoverWith:"scip-query evidence --symbol <symbol> --edge execution --edge runtime --edge identity --direction both --depth 2 --max-edges 100"},{id:"wrapper-indirection-candidate",detector:"wrapper-candidates",claim:"A small callable has one visible consumer and wrapper-shaped delegation, after boundary evidence is disclosed.",relationRequirements:[{family:"execution",subtype:"call",minimumStrength:"exact"},{family:"ownership",subtype:"contains",minimumStrength:"exact"}],structuralEvidence:["callable body shape","public and runtime-boundary signals","consumer fan-in"],calibration:"candidate",providerCoverage:"partial",nonClaims:["Wrapper shape does not prove that an API, ownership, observability, or compatibility boundary is unnecessary."],recoverWith:"scip-query inspect --symbol <symbol> --view behavior"},{id:"passthrough-forwarding-candidate",detector:"passthrough-candidates",claim:"A small callable visibly forwards to one callee, with public-facade and boundary signals disclosed.",relationRequirements:[{family:"execution",subtype:"call",minimumStrength:"exact"},{family:"contract",subtype:"uses-contract-symbol",minimumStrength:"exact"}],structuralEvidence:["statement-complete forwarding shape","public facade evidence","runtime-boundary signals"],calibration:"mixed",providerCoverage:"partial",nonClaims:["Literal forwarding does not prove the callable has no contract, naming, policy, or compatibility role."],recoverWith:"scip-query inspect --symbol <symbol> --view behavior"},{id:"stale-abstraction-candidate",detector:"stale-abstractions",claim:"A type-like abstraction has zero or one visible real consumer after re-export and ownership distinctions.",relationRequirements:[{family:"identity",subtype:"references",minimumStrength:"exact"},{family:"ownership",subtype:"contains",minimumStrength:"exact"}],structuralEvidence:["definition kind","barrel-only consumer distinction","defining-file usage"],calibration:"mixed",providerCoverage:"partial",nonClaims:["Low visible consumer count does not prove a public contract or runtime-registered type is obsolete."],recoverWith:"scip-query evidence --symbol <symbol> --edge identity --edge ownership --edge contract --direction both --depth 2 --max-edges 100"},{id:"complexity-control-pressure",detector:"complexity-hotspots",claim:"A callable concentrates local branch/control pressure and graph fan-in or fan-out.",relationRequirements:[{family:"execution",subtype:"predicate-consequence",minimumStrength:"exact"},{family:"execution",subtype:"call",minimumStrength:"exact"}],structuralEvidence:["AST branch count or disclosed regex fallback","call fan-in","callee count"],calibration:"mixed",providerCoverage:"partial",nonClaims:["Structural complexity does not establish runtime frequency, latency, defect density, or a required refactor."],recoverWith:"scip-query inspect --symbol <symbol> --view behavior"},{id:"decorative-checker-terminal-behavior",detector:"decorative-checkers",claim:"A checker-shaped callable lacks a visible failure terminal directly or through one resolved delegate.",relationRequirements:[{family:"execution",subtype:"returns",minimumStrength:"exact"},{family:"execution",subtype:"throws",minimumStrength:"exact"}],structuralEvidence:["checker naming shape","direct terminal behavior","one-hop delegate body"],calibration:"mixed",providerCoverage:"partial",nonClaims:["No visible terminal does not prove the checker cannot fail through an opaque call, exception, or process exit."],recoverWith:"scip-query inspect --symbol <symbol> --view behavior"},{id:"duplicate-structural-candidate",detector:"duplicate and similarity detectors",claim:"Two source units share the detector-specific structural or token pattern.",relationRequirements:[],structuralEvidence:["normalized source/token/JSX/template similarity"],calibration:"candidate",providerCoverage:"partial",nonClaims:["Structural similarity does not establish shared domain identity or justify consolidation."],recoverWith:"scip-query inspect --symbol <symbol-a> --symbol <symbol-b> --view behavior"}];function Ww(e=new Set(["indexed-graph","source-facts"])){return a4.map(t=>{let n=t.relationRequirements.map(i=>{let o=Ec(i.family,i.subtype);if(!o)throw new Error(`Detector ${t.id} names an unregistered relation ${i.family}/${i.subtype}`);if(!o.relation.evidenceStrengths.includes(i.minimumStrength))throw new Error(`Detector ${t.id} requires unsupported strength ${i.minimumStrength} for ${i.family}/${i.subtype}`);return o.provider}),r=[...new Set(n.flatMap(i=>i.requirements))].filter(i=>!e.has(i));return{...t,status:r.length>0?"unsupported":t.calibration,providerIds:[...new Set(n.map(i=>i.id))],unavailableRequirements:r}})}var Vw=50,Jp=10,c4=25e3,l4=2500,Yw=2500,Jw=50,u4=10,Cl=["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"],d4={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:g4(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:h4(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:y4(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:b4(e,t,n)}),"duplicate-bodies":(e,t,n)=>({phase:"duplicate-bodies",duplicateBodies:v4(e,t,n)}),"twin-drift":(e,t,n)=>({phase:"twin-drift",twinDrift:C4(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:x4(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:R4(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:E4(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:I4(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:w4(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:L4(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",...S4(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:P4(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:D4(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:M4(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:F4(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:N4(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:T4(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:k4(e,n)}),"coverage-contracts":(e,t,n)=>({phase:"coverage-contracts",coverageContracts:A4(e,n)})};function Zw(e){let t=e.generation.identity,n=Gg(e.config.dbPath),r=n?.currentGeneration===t?n:null;return{computedAt:new Date().toISOString(),generation:{identity:t,publishedAt:r?.publishedAt??null,mode:r?.publication?.mode??null},git:Nw(e.config.projectRoot)}}function Qp(e,t,n={}){return m4(e,[t],n)[0]}function m4(e,t,n={}){return p4(e,n.full!==!1,(r,i)=>{let o={...i,releaseCachesBetweenPhases:!1};return t.map(s=>d4[s](e,n.scope,o,r))})}function p4(e,t,n){let r=qr(e),i=_4(r,t);try{return n(r,i)}finally{Dm(e,{semanticProvider:!0}),Yp()}}function Zp(e,t){return zw(f4(e),t?Zw(t):void 0)}function f4(e){let t=De(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,detectorEvidence:Ww(),dead:De(e,"dead").dead,isolated:De(e,"isolated").isolated,realCycleCount:De(e,"cycles").realCycleCount,similarCount:De(e,"similar").similarCount,duplicateBodies:De(e,"duplicate-bodies").duplicateBodies,twinDrift:De(e,"twin-drift").twinDrift,reactComponentDuplicates:De(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:De(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:De(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:De(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:De(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:De(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:De(e,"extract-candidates").extractCount,extractExclusions:De(e,"extract-candidates").extractExclusions,wrappers:De(e,"wrapper-candidates").wrappers,passthroughs:De(e,"passthrough-candidates").passthroughs,stale:De(e,"stale-abstractions").stale,drift:De(e,"drift").drift,complexity:De(e,"complexity-hotspots").complexity,gitEvidence:Xw(e,"git-evidence")?.gitEvidence??null,suppressions:Xw(e,"suppressions")?.suppressions??null,coverageContracts:De(e,"coverage-contracts").coverageContracts}}function Xw(e,t){return e.find(n=>n.phase===t)}function De(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function g4(e,t,n){return Me(e,n,"dead",()=>{let r=ti(e,{scope:t,...Pe.dead,scanLimit:n.candidateScanLimit,semantic:n.semantic}),i=r.applicability;return{...xl($4(e,r.symbols)),exclusions:Rl([{reason:"entry-surface-symbols",detail:"zero-reference symbols in framework entry surfaces (route handlers, pages, scheduled tasks, live barrels) that the framework invokes",count:i.entrySurfaceExcluded},{reason:"generated-artifact-symbols",detail:"zero-reference symbols in generated artifacts (migration dumps, codegen output) owned by their generator",count:i.generatedArtifactExcluded??0}])}})}function h4(e,t,n){return Me(e,n,"isolated",()=>{let r=hs(e,{scope:t,...Pe.isolated,scanLimit:n.candidateScanLimit,semantic:n.semantic});return xl(j4(e,r))})}function y4(e,t,n){return Me(e,n,"cycles",()=>fs(e,{scope:t}).filter(i=>i.kind==="real").length)}function b4(e,t,n){let r=Me(e,n,"similar",()=>$m(e,{scope:t,...Pe.similar,scanLimit:n.candidateScanLimit,semantic:n.semantic}));return Math.min(r,n.candidateResultLimit)}function S4(e,t,n){return Me(e,n,"extract-candidates",()=>{let r=xs(e,{scope:t,...Pe.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}),i=r.filter(o=>o.actionTier==="support").length;return{extractCount:r.length-i,extractExclusions:i>0?[{reason:"wide-interface-regions",detail:"largest region would take more than five locals in or hand more than two back; listed by extract-candidates at support tier",count:i}]:[]}})}function v4(e,t,n){return Me(e,n,"duplicate-bodies",()=>{let r=ll(e,{scope:t,...Pe.duplicateBodies,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),i=new Set,o=0;for(let s of r.groups)for(let a of s.functions.slice(1))i.add(a.file),o+=a.loc;return{count:r.groups.length,loc:o,files:[...i],exclusions:r.exclusions.map(s=>({reason:s.reason,detail:`${s.detail}; group members removed before counting`,count:s.count}))}})}function C4(e,t,n){return Me(e,n,"twin-drift",()=>{let r=ul(e,{scope:t,...Pe.twinDrift,scanLimit:n.candidateScanLimit}).filter(s=>s.relationship==="divergent"||s.relationship==="identical"),i=new Set,o=0;for(let s of r)for(let a of s.members)i.add(a.file),o+=a.loc;return{count:r.length,loc:o,files:[...i].sort()}})}function x4(e,t,n){return Me(e,n,"react-component-duplicates",()=>{let r=qm(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),i=r.results.filter(o=>Qw(o)>0);return{...ef(i,Qw),exclusions:Rl(r.exclusions,[{reason:"support-tier-pairs",detail:"support-tier pairs (generic structure only, or framework route scaffolding); listed by react-component-duplicates but not counted",count:r.results.length-i.length}])}})}function R4(e,t,n){return Me(e,n,"react-hook-candidates",()=>{let r=zm(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),i=[],o=new Map;for(let s of r.results){let a=nL(s);if(a.weight>0){i.push(s);continue}let c=o.get(a.reason)??{reason:a.reason,detail:a.detail,count:0};c.count+=1,o.set(a.reason,c)}return{...ef(i,U4),exclusions:Rl(r.exclusions,[...o.values()])}})}function E4(e,t,n){return Me(e,n,"react-large-component-pressure",()=>{let r=Km(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return{...H4(r.results),exclusions:Rl(r.exclusions,[])}})}function I4(e,t,n){return Me(e,n,"vue-component-duplicates",()=>{let r=vs(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return tL(r)})}function w4(e,t,n){return Me(e,n,"vue-composable-candidates",()=>{let r=Cs(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return ef(r,q4)})}function L4(e,t,n){return Me(e,n,"vue-large-view-pressure",()=>{let r=Wm(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return xl(r)})}function P4(e,t,n){return Me(e,n,"wrapper-candidates",()=>{let r=As(e,{scope:t,...Pe.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}),i=r.filter(s=>s.bodyShape==="forwarding"),o=r.length-i.length;return{...eL(i,K4),exclusions:o>0?[{reason:"single-consumer-helpers",detail:"single-consumer callables whose body computes or branches instead of forwarding one call; listed by wrapper-candidates as signal tier",count:o}]:[]}})}function D4(e,t,n){return Me(e,n,"passthrough-candidates",()=>{let r=ws(e,{scope:t,...Pe.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return eL(r,W4)})}function M4(e,t,n){return Me(e,n,"stale-abstractions",()=>{let r=ks(e,{scope:t,...Pe.stale,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}),i=r.filter(o=>o.consumers===0).length;return{count:r.length,loc:r.reduce((o,s)=>o+s.loc,0),files:[...new Set(r.map(o=>o.file))],unused:i,singleUse:r.length-i}})}function T4(e,t){return Me(e,t,"git-evidence",()=>{let n=Kt(e,{historyMode:t.gitHistoryMode}),r=n.fileChurn();if(!r)return null;let i=n.commitHistory(),o=Es(e,void 0,{limit:t.candidateResultLimit,historyMode:t.gitHistoryMode}),s={};for(let[l,d]of r)s[l]={changes:d.changes,fixChanges:d.fixChanges};let a=o.findings.filter(l=>Xp(l).counted),c=new Map;for(let l of o.findings){let d=Xp(l);if(d.counted)continue;let m=c.get(d.reason)??{reason:d.reason,detail:d.detail,count:0};m.count+=1,c.set(d.reason,m)}let u=[...a].sort((l,d)=>vl(d)-vl(l)||d.together-l.together);return{amplification:n.changeAmplification(),hiddenCoupling:{pairCount:a.length,scoreCount:tf(a.reduce((l,d)=>l+vl(d),0)),exclusions:[...c.values()].sort((l,d)=>l.reason.localeCompare(d.reason)),top:u.slice(0,5).map(l=>({fileA:l.fileA,fileB:l.fileB,together:l.together,confidence:l.confidence,focusedTogether:l.focusedTogether,broadTogether:l.broadTogether,broadCommitRatio:l.broadCommitRatio,lastTogetherAt:l.lastTogetherAt,recentTogether:l.recentTogether,commitScope:l.commitScope,recency:l.recency,scoreWeight:vl(l),subjectContext:l.subjectContext}))},fileStats:s,commitsScanned:i?.commits.length??0}})}function k4(e,t){return Me(e,t,"suppressions",()=>{let n=fl(e);return{total:n.total,byCategory:{...n.byCategory}}})}function A4(e,t){return Me(e,t,"coverage-contracts",()=>{let n=e.config.coverageContracts??[],i=Bw(e,n).filter(o=>o.status!=="ok");return{count:i.length,loc:0,files:[...new Set(i.map(o=>o.file))].sort()}})}function F4(e,t,n){return Me(e,n,"drift",()=>{let r=Ts(e,{scope:t,...Pe.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY,semantic:n.semantic}),i=r.results.filter(a=>a.kind!=="pattern-deviation"),o=i.filter(a=>a.actionTier==="direct").length,s=i.length-o;return{count:i.length,unusedImports:r.unusedImports,architectureViolations:r.architectureViolations,layerViolations:r.layerViolations,direct:o,signal:s}})}function N4(e,t,n){return Me(e,n,"complexity-hotspots",()=>{let r=Vp(e,{scope:t,minLoc:10,limit:n.complexityResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}),i=r.filter(s=>s.score>Vw&&s.branches>=Jp),o=r.filter(s=>s.score>Vw&&s.branches<Jp).length;return{top:r.slice(0,5).map(s=>({symbol:s.shortName,score:s.score,file:s.file})),extremeCount:i.length,exclusions:o>0?[{reason:"popular-low-branch-callables",detail:`callables above the extreme score only through fan-in, with fewer than ${Jp} branches`,count:o}]:[]}})}function _4(e,t){let n=e.symbols>=c4||e.documents>=l4,r=t?Number.POSITIVE_INFINITY:Jw,i=t?Number.POSITIVE_INFINITY:u4;return!n||t?{candidateScanLimit:void 0,candidateResultLimit:r,complexityResultLimit:i,semantic:!0,gitHistoryMode:t?"full":"bounded",releaseCachesBetweenPhases:!0,warnings:t&&n?["Large index detected; running health without candidate scan or result caps because full mode is enabled."]:[]}:{candidateScanLimit:Yw,candidateResultLimit:r,complexityResultLimit:i,semantic:!1,gitHistoryMode:"bounded",releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${Yw} symbols and reported their top ${Jw} findings. Enable full mode for unbounded candidate counts.`]}}function O4(e,t){t.releaseCachesBetweenPhases&&(Dm(e),Yp())}function Me(e,t,n,r){B4(n);try{return r()}finally{O4(e,t)}}function B4(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function $4(e,t){return t.filter(n=>!ze(e,n.relativePath)&&!Be(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function j4(e,t){return t.filter(n=>!ze(e,n.relativePath)&&!Be(e,n.symbol,n.relativePath))}function xl(e){let t=new Set;for(let n of e){let r=n.relativePath??n.file;r&&t.add(r)}return{count:e.length,loc:e.reduce((n,r)=>n+r.loc,0),files:[...t]}}function eL(e,t){return{...xl(e),scoreCount:tf(e.reduce((r,i)=>r+t(i),0))}}function H4(e){let t=new Map;for(let n of e)t.set(n.file,Math.max(t.get(n.file)??0,n.loc));return{count:t.size,loc:[...t.values()].reduce((n,r)=>n+r,0),files:[...t.keys()]}}function tL(e){let t=new Map;for(let n of e)t.set(n.fileA,Math.max(t.get(n.fileA)??0,n.locA)),t.set(n.fileB,Math.max(t.get(n.fileB)??0,n.locB));return{count:e.length,loc:[...t.values()].reduce((n,r)=>n+r,0),files:[...t.keys()]}}function ef(e,t){return{...tL(e),scoreCount:tf(e.reduce((r,i)=>r+t(i),0))}}function Qw(e){return e.actionTier==="signal"?1:0}function U4(e){return nL(e).weight}function nL(e){if(e.evidenceClass==="generic-workflow-scaffolding")return{weight:0,reason:"generic-workflow-pairs",detail:"pairs whose shared behavior is only generic React mechanics (open/close/submit state and handlers)"};let t=e.sharedHooks.some(i=>!G4.has(i)),n=rL({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});if(t&&n<=2)return{weight:0,reason:"shared-hook-covered-pairs",detail:"pairs whose concrete shared behavior is already carried by a project hook both sides call"};if(!t&&n===0)return{weight:0,reason:"generic-workflow-pairs",detail:"pairs whose shared behavior is only generic React mechanics (open/close/submit state and handlers)"};let r={reason:"counted",detail:"counted"};return t?{weight:.5,...r}:iL(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?{weight:.25,...r}:{weight:n>=2?1:.5,...r}}function Rl(...e){let t=new Map;for(let n of e)for(let r of n){if(r.count<=0)continue;let i=t.get(r.reason);i?i.count+=r.count:t.set(r.reason,{...r})}return[...t.values()].sort((n,r)=>n.reason.localeCompare(r.reason))}function q4(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=rL({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:iL(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function rL(e){return e.requests.filter(n=>!z4.has(n)).length*2+e.lifecycle.length+e.namedState.filter(n=>!sL.has(oL(n))).length+Math.min(e.functions.length,3)}var G4=new Set(["useForm","useFormContext","useInfiniteQuery","useMutation","useParams","usePathname","useQuery","useQueryClient","useRouter","useSearchParams","useSelector","useDispatch","useSuspenseQuery","useTheme","useTranslation"]),z4=new Set(["axios","fetch","gql","graphql","mutate","query","request","useInfiniteQuery","useMutation","useQuery","useSuspenseQuery"]);function iL(e,t,n){let r=[...e,...t,...n].map(oL);return r.length>0&&r.every(i=>sL.has(i))}function oL(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function K4(e){return e.actionTier==="signal"?.25:1}function W4(e){return e.actionTier==="signal"?.25:1}function vl(e){return Xp(e).counted?e.commitScope==="broad-sweep"?e.recency==="recent"?.25:0:e.commitScope==="mixed"?e.recency==="recent"?.5:.25:e.recency==="recent"?1:.5:0}function Xp(e){if(e.actionTier==="signal"&&e.partnerClass!=="doc-code"&&e.partnerClass!=="generated-artifact")return{counted:!1,reason:"sweep-only-pairs",detail:"pairs whose shared commits were only broad sweeps, stale pairs with at most two focused co-changes, and configuration or schema partners; listed by co-change at signal tier"};switch(e.partnerClass){case"doc-code":return{counted:!1,reason:"doc-sync-pairs",detail:"documentation that changes alongside the code it describes (doc-drift owns stale docs)"};case"generated-artifact":return{counted:!1,reason:"generated-artifact-pairs",detail:"generated artifacts (migration journals, snapshots, codegen output) rewritten from their source"};default:return{counted:!0,reason:"counted",detail:"counted"}}}function tf(e){return Math.round(e*100)/100}var sL=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 V4(e,t,n,r={}){let i=Bm(e,t,n,r);return i?{symbolA:i.symbolA,symbolB:i.symbolB,similarity:i.similarity,sharedCallees:i.sharedEvidence,uniqueToA:i.uniqueToA,uniqueToB:i.uniqueToB,consolidationStrategy:i.consolidationStrategy}:null}function Y4(e,t,n={}){let r=ms(e,t,{families:["dataflow"],...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.maxEdges!==void 0?{maxEdges:n.maxEdges}:{}});return{kind:"value-flow",targets:r.targets,edges:r.edges,coverage:{status:r.coverage.status,basis:"proved-bounded-static-value-flow",analysisBasis:"partial-system-definition-use",providers:["bounded-static-value-flow","typescript-local-dependence"],supportedRelations:["compiler-identified local definitions reaching local reads through a TypeScript control-flow graph","right-hand-side local reads supplying assignments and declarations","candidate closure captures and bounded same-owner field flow with explicit evidence strength","direct argument-to-parameter forwarding at compiler-resolved calls","bounded mechanically derived static arguments","callee return value to a consumed compiler-resolved call result"],unsupportedRelations:["general heap alias and cross-instance field points-to flow","exceptional control and value flow","closure invocation order","downstream local definition-use after a call result","dynamic calls not resolved by the semantic provider"],graph:r.coverage}}}var J4=/:\d+(?:-\d+)?$/u;function X4(e,t,n={}){let r=n.direction??"backward",i=n.maxDepth??3;if(!Number.isSafeInteger(i)||i<0)throw new RangeError(`Dependence-slice depth must be a non-negative safe integer; received ${i}.`);let o=J4.test(t),s=ms(e,o?{locations:[t]}:{symbols:[t]},{families:["execution","runtime","dataflow","ownership"],maxDepth:i+1,maxEdges:n.maxEdges??200}),a=new Set(s.targets.flatMap(d=>d.nodeIds)),c=new Set(a),u=new Map;aL(s.edges,c,u,0);for(let d=1;d<=i;d+=1){let m=[];for(let p of s.edges)if(r==="backward"?c.has(p.to.id):c.has(p.from.id)){let f=r==="backward"?p.from.id:p.to.id;if(c.has(f))continue;m.push(f),u.set(p.id,d)}if(m.length===0)break;for(let p of m)c.add(p);aL(s.edges,c,u,d)}let l=s.edges.filter(d=>c.has(d.from.id)&&c.has(d.to.id)).filter(d=>u.has(d.id)||d.family==="ownership").map(d=>({...d,traversalDepth:u.get(d.id)??0,supporting:d.family!=="dataflow"&&!Q4(d)})).sort((d,m)=>d.traversalDepth-m.traversalDepth||d.family.localeCompare(m.family)||d.from.label.localeCompare(m.from.label)||d.to.label.localeCompare(m.to.label));return{kind:"dependence-slice",direction:r,criterion:t,targets:s.targets,nodeIds:[...c].sort(),edges:l,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 aL(e,t,n,r){let i=!0;for(;i;){i=!1;for(let o of e)o.family!=="ownership"||!t.has(o.from.id)||t.has(o.to.id)||(t.add(o.to.id),n.set(o.id,r),i=!0)}}function Q4(e){return e.semanticFamily==="control"&&e.sourceKind==="control-dependence"}function Z4(e,t={}){let{scope:n,limit:r}=t,i=new H(e),o=c3([...e3(e,n),...r3(e,i,n)]);return l3(o),r?o.slice(0,r):o}function e3(e,t){let n=[];for(let r of t3(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||Ad(e,r.barrel_path)||V(e,r.barrel_path)&&Js(e,r.barrel_path).length===0)continue;let i=n3(e,r),o=i?.barrel_consumers??0,s=i?.direct_consumers??0;o!==0||s!==0||n.push({barrelFile:r.barrel_path,symbol:r.symbol,shortName:T(r.symbol),originalFile:r.original_path,barrelConsumers:o,directConsumers:s,...lL(e,r.barrel_path)})}return n}function t3(e,t){let n=t?"AND barrel_d.relative_path LIKE ?":"",r=t?[`%${t}%`]:[];return e.all(`WITH barrel_refs AS MATERIALIZED (
463
- SELECT DISTINCT
464
- barrel_d.id AS barrel_doc_id,
465
- barrel_d.relative_path AS barrel_path,
466
- m.symbol_id
467
- FROM documents barrel_d
468
- JOIN chunks c ON c.document_id = barrel_d.id
469
- JOIN mentions m ON m.chunk_id = c.id
470
- WHERE m.role != 1
471
- AND (barrel_d.relative_path LIKE '%/index.ts'
472
- OR barrel_d.relative_path LIKE '%/index.js'
473
- OR barrel_d.relative_path = 'index.ts'
474
- OR barrel_d.relative_path = 'index.js')
475
- ${e.pathExclusionsFor("barrel_d")}
476
- ${n}
477
- ),
478
- sym_def AS MATERIALIZED (
479
- SELECT m2.symbol_id, c2.document_id
480
- FROM barrel_refs br
481
- -- Keep the bounded barrel-symbol set on the outer side. An ordinary
482
- -- JOIN lets SQLite scan every definition mention before applying the
483
- -- barrel-symbol bloom filter on large indexes.
484
- CROSS JOIN mentions m2 ON m2.symbol_id = br.symbol_id
485
- AND m2.role = 1
486
- JOIN chunks c2 ON m2.chunk_id = c2.id
487
- GROUP BY m2.symbol_id
488
- )
489
- SELECT DISTINCT
490
- br.barrel_doc_id,
491
- br.barrel_path,
492
- gs.id AS symbol_id,
493
- gs.symbol AS symbol,
494
- orig_d.id AS original_doc_id,
495
- orig_d.relative_path AS original_path
496
- FROM barrel_refs br
497
- JOIN global_symbols gs ON br.symbol_id = gs.id
498
- JOIN sym_def ON sym_def.symbol_id = gs.id
499
- JOIN documents orig_d ON sym_def.document_id = orig_d.id
500
- WHERE orig_d.id != br.barrel_doc_id
501
- ${e.pathExclusionsFor("orig_d")}
502
- ${e.symbolNoiseFor("gs")}
503
- -- Only function-level symbols (ending with ().), not module-level
504
- AND gs.symbol LIKE '%().'
505
- ORDER BY br.barrel_path, gs.symbol`,...r)}function n3(e,t){return e.get(`SELECT
506
- SUM(CASE WHEN uses_barrel = 1 THEN 1 ELSE 0 END) AS barrel_consumers,
507
- SUM(CASE WHEN uses_barrel = 0 THEN 1 ELSE 0 END) AS direct_consumers
508
- FROM (
509
- SELECT
510
- consumer_d.id AS consumer_doc_id,
511
- MAX(CASE WHEN EXISTS (
512
- SELECT 1
513
- FROM mentions barrel_m
514
- JOIN chunks barrel_c ON barrel_m.chunk_id = barrel_c.id
515
- WHERE barrel_c.document_id = consumer_d.id
516
- AND barrel_m.role != 1
517
- AND barrel_m.symbol_id IN (
518
- SELECT m2.symbol_id
519
- FROM mentions m2
520
- JOIN chunks c2 ON m2.chunk_id = c2.id
521
- WHERE c2.document_id = ?
522
- AND m2.role != 1
523
- )
524
- ) THEN 1 ELSE 0 END) AS uses_barrel
525
- FROM mentions ref_m
526
- JOIN chunks ref_c ON ref_m.chunk_id = ref_c.id
527
- JOIN documents consumer_d ON ref_c.document_id = consumer_d.id
528
- WHERE ref_m.symbol_id = ?
529
- AND ref_m.role != 1
530
- AND consumer_d.id != ?
531
- AND consumer_d.id != ?
532
- ${e.pathExclusionsFor("consumer_d")}
533
- GROUP BY consumer_d.id
534
- )`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function r3(e,t,n){let r=[],i=a3(e);for(let o of i3(e,n))uL(i,o,o)>0||r.push(...o3(e,t,o,i));return r}function i3(e,t){return Q(e,{scope:t,includeIgnored:!1}).filter(n=>Js(e,n).length>0||bn(e,n).length>0)}function o3(e,t,n,r){let i=Js(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>cL(e,t,n,s.sourcePath,r,[s3(s.specifier)])),o=bn(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>cL(e,t,n,s.sourcePath,r,s.kind==="named"&&s.names.length>0?s.names:[s.kind==="star"?`* from ${s.sourcePath}`:`* namespace from ${s.sourcePath}`]));return[...i,...o]}function cL(e,t,n,r,i,o){let s=t.definitionsForFile(r);return o.map(a=>{let c=s.find(u=>u.leaf===a);return{barrelFile:n,symbol:c?.symbol??`source-reexport:${n}:${a}`,shortName:c?T(c.symbol):a,originalFile:r,barrelConsumers:0,directConsumers:uL(i,r,n),...lL(e,n)}})}function s3(e){return e.split("::").at(-1)?.split("/").at(-1)?.replace(/\.[^.]+$/,"")??e}function lL(e,t){return Dn(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 a3(e){let t=new Map;for(let n of Q(e,{includeIgnored:!1}))for(let r of ce(e,n)){if(!r.sourcePath)continue;let i=t.get(r.sourcePath)??new Set;i.add(n),t.set(r.sourcePath,i)}return t}function uL(e,t,n){let r=e.get(t);return r?r.size-(r.has(n)?1:0):0}function c3(e){let t=new Set,n=[];for(let r of e){let i=`${r.barrelFile}|${r.symbol}|${r.originalFile}`;t.has(i)||(t.add(i),n.push(r))}return n}function l3(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function u3(e,t={}){let{samples:n=50,scope:r,maxDisagreements:i=5}=t,o=new H(e),s=d3(o.productionCallableDefinitions({scope:r,minLoc:2,requireFunctionLikeSymbol:!0}),n),a=m3(e,s);if(s.length===0||!a)return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let c={references:nf(),callees:nf(),renders:nf()},u=[],l=0,d=a==="semantic"?Ua(e,s):new Map,m=a==="semantic"?Hb(e,s):new Map,p=a==="semantic"?jb(e):null,f=y=>p===null||p(y)!==null,g=(y,S)=>p===null||p(S)===p(y.relativePath),h=a==="source"?h3(e,o,s):null;for(let y of s){let S=oo(y,a==="semantic"?Ha(e,y).map(L=>L.file):[...h?.referencesBySymbolId.get(y.symbolId)??[]]),b=a==="semantic"?d.get(y.symbolId)??[]:[...h?.calleesBySymbolId.get(y.symbolId)??[]].map(L=>({file:L})),x=oo(y,b.filter(L=>L.kind!=="jsx-render").map(L=>L.file)),v=oo(y,b.filter(L=>L.kind==="jsx-render").map(L=>L.file));l+=1;let C=oo(y,zn(e,y,{semanticEvidence:ie}).map(L=>L.file)),R=o.calleeMap([y],{semantic:!1}).get(y.symbolId)??[];for(let L of R){let $=(L.kind==="jsx-render"?c.renders:c.callees).sources;$[L.source]=($[L.source]??0)+1}let E=oo(y,R.filter(L=>L.kind!=="jsx-render").map(L=>L.file)),w=oo(y,R.filter(L=>L.kind==="jsx-render").map(L=>L.file)),I=f3(e,y),k=m.get(y.symbolId),D=k!==void 0&&k.unresolved===0,F=of(a,"references"),P=of(a,"callees")||D||I.calls===0,A=of(a,"renders")||D||I.renders===0;rf(c.references,y,"references",C,S,F,u,L=>g(y,L)),rf(c.callees,y,"callees",E,x,P,u,f),rf(c.renders,y,"renders",w,v,A,u,f)}return u.sort((y,S)=>S.cheapOnly.length+S.oracleOnly.length-(y.cheapOnly.length+y.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?af(l/s.length):0,oracleKind:a,scores:["references","callees","renders"].map(y=>g3(y,c[y],a)),topDisagreements:u.slice(0,i)}}function nf(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0,skippedOraclePartial:0,completeSymbols:0,completeCheapTotal:0,completeAgreed:0,outsideCoverage:0,sources:{}}}function d3(e,t){let n=[...e].sort((o,s)=>o.symbolId-s.symbolId);if(n.length<=t)return n;let r=n.length/t,i=[];for(let o=0;o<t;o++)i.push(n[Math.floor(o*r)]);return i}function m3(e,t){let n=t[0];if(!n)return null;if(sf(e,n))return"source";try{if(st(e).capability("semantic-references",n.relativePath).available)return"semantic"}catch{}return t.some(r=>sf(e,r))?"source":null}function oo(e,t){let n=new Set;for(let r of t)r!==e.relativePath&&n.add(r);return n}function rf(e,t,n,r,i,o,s,a=()=>!0){if(!o&&i.size===0){e.skippedOraclePartial+=1;return}let c=[...r].filter(m=>!i.has(m)&&!a(m));e.outsideCoverage+=c.length;let u=r.size-c.length;e.comparedSymbols+=1,e.cheapTotal+=u,e.oracleTotal+=i.size,o&&(e.completeSymbols+=1,e.completeCheapTotal+=u);let l=[],d=[];for(let m of r)i.has(m)?(e.agreed+=1,o&&(e.completeAgreed+=1)):a(m)&&l.push(m);for(let m of i)r.has(m)||d.push(m);(l.length>0||d.length>0)&&s.push({symbol:T(t.symbol),question:n,cheapOnly:l,oracleOnly:d})}var p3={references:!0,callees:!1,renders:!1};function f3(e,t){let n=W(e,t.relativePath),r=0,i=0;for(let o of n?.callSites??[])o.line<t.startLine||o.line>t.endLine||(o.kind==="jsx-render"?i+=1:r+=1);return{calls:r,renders:i}}function g3(e,t,n){let r=t.oracleTotal>0?t.agreed/t.oracleTotal:1,i=t.completeCheapTotal>0?af(t.completeAgreed/t.completeCheapTotal):null,o=t.cheapTotal-t.agreed-(t.completeCheapTotal-t.completeAgreed);return{question:e,comparedSymbols:t.comparedSymbols,precision:i,recall:af(r),unverified:o,skippedOraclePartial:t.skippedOraclePartial,completeOracleSymbols:t.completeSymbols,outsideOracleCoverage:t.outsideCoverage,cheapSources:t.sources}}function of(e,t){return e==="semantic"?p3[t]:!1}function sf(e,t){return ae(t.relativePath)==="clojure"&&W(e,t.relativePath)!==null}function h3(e,t,n){let r=new Map,i=new Map,o=n.filter(c=>sf(e,c)),s=new Map;for(let c of o){let u=s.get(c.leaf)??[];u.push(c),s.set(c.leaf,u)}for(let c of t.sourceFiles()){if(ae(c)!=="clojure")continue;let u=W(e,c);if(u)for(let l of u.fileIdentifiers)for(let d of s.get(l)??[])dL(r,d.symbolId,c)}let a=new Map;for(let c of t.scopedDefinitions()){if(ae(c.relativePath)!=="clojure")continue;let u=a.get(c.leaf)??[];u.push(c),a.set(c.leaf,u)}for(let c of o){let u=W(e,c.relativePath);if(u){for(let l of u.callSites)if(!(l.line<c.startLine||l.line>c.endLine))for(let d of a.get(l.calleeLeaf)??[])dL(i,c.symbolId,d.relativePath)}}return{referencesBySymbolId:r,calleesBySymbolId:i}}function dL(e,t,n){let r=e.get(t);if(r){r.add(n);return}e.set(t,new Set([n]))}function af(e){return Math.round(e*1e3)/1e3}var y3=new Set(Qt());function b3(e,t={}){let{scope:n,minLoc:r=1,limit:i,scanLimit:o,maxShapeFrequency:s=12}=t,a=t.semantic!==!1,c=C3(e,S3(e,{scope:n,minLoc:r,scanLimit:o}),{semantic:a,maxShapeFrequency:s}),u=R3(c);return i?u.slice(0,i):u}function S3(e,t){let n=ye(e,{scope:t.scope}).filter(r=>v3(r)&&!e.isIgnored(r.relativePath)).filter(r=>ee(r)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((r,i)=>ee(i)-ee(r)||r.relativePath.localeCompare(i.relativePath)),be(n,t.scanLimit)}function v3(e){return!e.isFunctionLike||Ge(e.symbol)?!1:e.kind===null||y3.has(e.kind)}function C3(e,t,n){let r=[];for(let s of t){let a=I3(e,s,n);a&&r.push({signature:a,definition:s,fn:x3(s)})}let i=new Map;for(let s of r)i.set(s.signature,(i.get(s.signature)??0)+1);let o=new Map;for(let s of r){let a=E3(s.fn.loc),c=(i.get(s.signature)??0)>n.maxShapeFrequency,u=c?Dp(e,s.definition):null;if(c&&!u)continue;let l=c?`${s.signature}\0body\0${u}`:`${s.signature}\0band\0${a}`,d=o.get(l)??{signature:s.signature,locBand:a,exactBody:c,functions:[]};d.functions.push(s.fn),o.set(l,d)}return[...o.values()]}function x3(e){return{symbol:e.symbol,shortName:T(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:ee(e)}}function R3(e){let t=[];for(let n of e)n.functions.length>=2&&t.push(n);return t.sort((n,r)=>{let i=r.functions.length-n.functions.length;if(i!==0)return i;let o=n.functions.reduce((a,c)=>a+c.loc,0);return r.functions.reduce((a,c)=>a+c.loc,0)-o}),t}function E3(e){return e<=5?"<=5":e<=20?"6-20":">20"}function I3(e,t,n){if(n.semantic){let o=qb(e,t);if(o)return o}let r=w3(t.documentation),i=r?D3(r):null;return i||M3(L3(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function w3(e){return hi(yi(e))}function L3(e,t,n,r,i){let o=V(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=k3(s,n,r,i);for(let c of a){let u=Math.min(s.length-1,Math.max(c,c+4)),l="";for(let d=c;d<=u;d+=1){let m=s[d]?.trim();if(m&&(l=l?`${l} ${m}`:m,P3(l)))return l}if(l&&l.includes("("))return l}return null}function P3(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||og(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function D3(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 M3(e,t){if(!e||!e.trim())return null;let n=e.replace(/\s+/g," ").trim(),r=n.indexOf("(");if(r===-1)return null;let i=n.slice(0,r),s=new RegExp(`\\b${Ie(t)}\\b`,"i").exec(i);s&&typeof s.index=="number"&&(i=i.slice(0,s.index)),i=i.replace(/\b(public|private|protected|internal|final|static|abstract|sealed|virtual|override|async|suspend|inline|constexpr|consteval|constinit|const|pub|fn|function|def|sub|friend|shared|readonly|new|open|partial|export)\b/gi," ").replace(/\s+/g," ").trim();let a=T3(n.slice(r)).replace(/\)\s*=\s*[\s\S]*$/,")").replace(/\s+throws\s+[^={]+$/i,"").replace(/\s+where\s+.+$/i,"").replace(/\s+/g," ").trim();if(!a.startsWith("("))return null;let c=`${i?`${i} `:""}${a}`.replace(/\s+/g,"").toLowerCase();return c.length>=3?c:null}function T3(e){let t=0,n=0,r=0,i=0,o=null,s=!1;for(let a=0;a<e.length;a+=1){let c=e[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c===o&&(o=null);continue}if(c==='"'||c==="'"||c==="`"){o=c;continue}if(c==="(")t+=1;else if(c===")")t=Math.max(0,t-1);else if(c==="[")r+=1;else if(c==="]")r=Math.max(0,r-1);else if(c==="<")i+=1;else if(c===">")i=Math.max(0,i-1);else if(c==="{"){if(t===0&&r===0&&i===0)return e.slice(0,a);n+=1}else if(c==="}")n=Math.max(0,n-1);else if(c==="="&&e[a+1]===">"&&t===0&&n===0&&r===0&&i===0)return e.slice(0,a)}return e}function k3(e,t,n,r){let i=Ie(r),o=new RegExp(`\\b${i}\\b\\s*\\(`,"i"),s=new RegExp(`\\bdef\\s+${i}\\b`,"i"),a=[],c=new Set,u=Math.max(0,Math.min(t,e.length-1)),l=Math.max(u,Math.min(e.length-1,Math.max(n,t+4)));for(let d=u;d<=l;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!c.has(d)&&(c.add(d),a.push(d))}for(let d=0;d<e.length;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!c.has(d)&&(c.add(d),a.push(d))}return a}async function mL(e,t,n={}){let r=Math.max(1,Math.floor(n.batchSize??64)),i=n.collectGarbage??mo,o=[],s=0;for(let a=0;a<t.length;a+=r){for(let c of t.slice(a,a+r)){for(let u of q(e,c))e.isIgnored(u.relativePath)||o.push(u);dg(e,c),bn(e,c),ag(e,c),s+=1}n.onBatch?.({files:s,total:t.length,definitions:o.length}),i(),await n.yieldToEventLoop?.()}return{files:s,definitions:o}}import{spawnSync as exe}from"child_process";import{execFileSync as ICe}from"child_process";import{createHash as LCe}from"crypto";import{lstatSync as DCe,readlinkSync as MCe,readdirSync as TCe,realpathSync as kCe,statSync as ACe}from"fs";import{dirname as NCe,isAbsolute as _Ce,join as OCe,posix as BCe,relative as $Ce,resolve as jCe,sep as HCe}from"path";var qCe=512*1024*1024;function pL(e){return Pr({version:e.version,...e.base?{base:e.base}:{},files:[...e.files].sort((t,n)=>t.path.localeCompare(n.path))})}function cf(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 F3="scip-query:collaboration-domain",N3="scip-query:workspace-instance",_3="scip-query:index-generation",O3="scip-query:repository-content",fL="scip-query:index-inputs",B3="scip-query:index-inputs";function ri(e){let t=e.snapshot,n=e.observedSourceKinds?new Set(e.observedSourceKinds):void 0,r=e.gitContext??t?.gitContext??(n?.has("live-workspace")?_l(e.projectRoot):void 0),i=e.collaborationDomainId??e.db?.config.collaborationDomainId,o=i?$r(F3,1,i):void 0,s=r?$r(N3,1,r.worktreeId):void 0,a=t?$r(O3,1,pL(t.repositoryContent)):void 0,c=t?$r(fL,t.indexInputs.version,cf(t.indexInputs)):void 0,u=e.db&&t?j3(e.db.generation.metadataRaw):void 0,l=e.db?{generation:$r(_3,1,e.db.generation.identity),...u?{inputs:u}:{},source:e.db.generation.source}:void 0,d=n??new Set([...l?["index-generation"]:[],...a?["repository-snapshot"]:s?["live-workspace"]:[]]),m=[...l&&d.has("index-generation")?[{kind:"index-generation",identity:l.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=[...l&&d.has("index-generation")?[{source:"index-generation",kind:l.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:ir,observedAt:(e.observedAt??(t?new Date(t.capturedAt):new Date)).toISOString(),facts:{...o?{collaborationDomain:o}:{},...s?{workspaceInstance:s}:{},...a?{wholeContent:a}:{},...c?{relevantInputs:[{subject:B3,identity:c}]}:{},...l?{index:l}:{}},observedSources:m,stabilityProofs:p,...r?{diagnostics:{clean:r.clean,...r.headCommit?{headCommit:r.headCommit}:{},...r.treeOid?{treeOid:r.treeOid}:{}}}:{}}}function $3(e){return ri({projectRoot:e.projectRoot,db:e.db,...e.gitContext?{gitContext:e.gitContext}:{},...e.observedAt?{observedAt:e.observedAt}:{},observedSourceKinds:["index-generation"]})}function XCe(){let e=tc();if(!e)return ri({projectRoot:ec(),observedSourceKinds:["process"]});let t=e.config.projectRoot,n=_l(t);return $3({projectRoot:t,db:e,...n?{gitContext:n}:{}})}function j3(e){if(!e)return;let t=Rr(e);if(t.kind!=="legacy"&&t.kind!=="supported")return;let n=ao(t.metadata.fingerprint);return n&&Number.isSafeInteger(n.version)&&n.version>0?$r(fL,n.version,cf(n)):void 0}var uf="scip-query-isolated-analysis",df=1;function H3(e){let t=[...e??[]];return t.includes("--json")?t:["--json",...t]}var gn=class extends Error{constructor(n,r,i=!0){super(`${n} timed out after ${r}ms.`);this.label=n;this.timeoutMs=r;this.reaped=i;this.name="IsolatedProcessTimeoutError"}label;timeoutMs;reaped;timedOut=!0};function cxe(e,t){let n=tc(),r={protocol:uf,schemaVersion:df,producer:{name:"scip-query",version:xr},command:e,result:t,...n?{observationReceipt:ri({projectRoot:n.config.projectRoot,db:n,observedSourceKinds:["index-generation"]})}:{}};wd(JSON.stringify(r))}function gL(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Ns(e){let t=e.timeoutMs??Zg.analysis,n=e.maxBuffer??10*1024*1024;return th({command:process.execPath,args:[...process.execArgv,e.cliPath,e.command,...H3(e.args)],cwd:process.cwd(),env:e.env??process.env,label:e.label,timeoutMs:t,maxStdoutBytes:n,maxStderrBytes:n}).catch(r=>{throw r instanceof eh&&r.kind==="timeout"?new gn(e.label,t,r.reaped):r}).then(r=>{let i=r.stderr.trim();if(r.status!==0)throw new Error(`${e.label} failed${i?`:
535
- ${i}`:""}`);return U3(r.stdout,e)})}function U3(e,t){let n;try{n=JSON.parse(e)}catch(i){throw new Error(`${t.label} returned invalid JSON: ${i instanceof Error?i.message:i}`,{cause:i})}if(!Z(n))throw new Error(`${t.label} returned a non-object isolated-analysis message.`);if(n.protocol!==uf)throw new Error(`${t.label} returned protocol ${lf(n.protocol)}; expected ${uf}.`);if(n.schemaVersion!==df)throw new Error(`${t.label} returned unsupported isolated-analysis schemaVersion ${lf(n.schemaVersion)}; expected ${df}.`);if(!q3(n.producer))throw new Error(`${t.label} did not identify a scip-query producer version.`);if(n.command!==t.command)throw new Error(`${t.label} returned result for command ${lf(n.command)}; expected ${t.command}.`);if(!Object.hasOwn(n,"result"))throw new Error(`${t.label} omitted the isolated-analysis result.`);let r=n.observationReceipt;if(r!==void 0&&(!Ga(r)||r.schemaVersion!==2))throw new Error(`${t.label} returned an invalid observation receipt.`);return{result:n.result,...r?{observationReceipt:r}:{}}}function q3(e){return Z(e)&&e.name==="scip-query"&&typeof e.version=="string"&&e.version.length>0}function lf(e){return typeof e=="string"?JSON.stringify(e):String(e)}async function El(e,t,n){let r=new Array(e.length),i=0;async function o(){for(;i<e.length;){let s=i++;r[s]=await n(e[s])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),r}function hL(e,t){let n=new Set,r=[];for(let i of e){if(n.has(i))continue;let o=t.find(a=>a.has(i));if(!o){n.add(i),r.push([i]);continue}let s=e.filter(a=>o.has(a));s.forEach(a=>n.add(a)),r.push(s)}return r}import{spawnSync as G3}from"child_process";import{existsSync as z3,mkdirSync as K3,renameSync as W3,writeFileSync as V3}from"fs";import{dirname as yL,join as Y3}from"path";var Il=5,J3="health-report-cache.json";function mf(e,t,n,r=eQ()){let i=pt(e);return i?{version:Il,projectFingerprint:i,cliVersion:n,scope:t.scope??null,full:t.full===!0,phaseTimeoutMs:t.phaseTimeoutMs??null,gitHead:r.gitHead(e.config.projectRoot),buildIdentity:(r.buildIdentity??jf)()}:null}function bL(e,t,n=xL()){let r=vL(e),i=CL(t),o=!1;return N("health.report-cache.read",()=>{if(!n.existsSync(r))return null;try{let s=JSON.parse(n.readFile(r));return!X3(s)||s.keyHash!==i?null:(o=!0,s.report)}catch{return null}},()=>({available:!0,hit:o,keyHash:i}))}function SL(e,t,n,r=xL()){let i=vL(e),o={version:Il,keyHash:CL(t),key:t,writtenAt:r.nowIso(),report:n};r.mkdirSync(yL(i),{recursive:!0});let s=`${i}.${process.pid}.${Date.now()}.tmp`;r.writeFileSync(s,JSON.stringify(o)),r.renameSync(s,i)}function vL(e){return Y3(yL(e.config.dbPath),J3)}function CL(e){return Yt(JSON.stringify(e))}function X3(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===Il&&typeof t.keyHash=="string"&&Q3(t.key)&&typeof t.writtenAt=="string"&&Z3(t.report)}function Q3(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===Il&&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")&&typeof t.buildIdentity=="string"}function Z3(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.score=="number"&&typeof t.riskScore=="number"&&typeof t.hygieneScore=="number"&&typeof t.overview=="object"&&typeof t.findings=="object"&&Array.isArray(t.scoreBreakdown)&&Array.isArray(t.actions)&&Array.isArray(t.pressure)&&Array.isArray(t.topComplexity)&&Array.isArray(t.detectorEvidence)}function eQ(){return{gitHead(e){let t=G3("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",timeout:3e4,killSignal:"SIGKILL"});return t.status===0?t.stdout.trim():null}}}function xL(){return{existsSync:z3,mkdirSync:K3,readFile:e=>Xe(e,"health report cache"),renameSync:W3,writeFileSync:V3,nowIso:()=>new Date().toISOString()}}var LL="__health-phase",nQ="__health-semantic-prewarm",rQ="__diff-impact-batch",iQ=128,oQ=1,sQ=1,aQ=6144,cQ=2048,lQ=10*6e4,uQ=25e3,dQ=2500,pf=2500,mQ=4,pQ=12,fQ=1,gQ=4,hQ=7*1024*1024*1024,yQ=6144,bQ=10*6e4,SQ=3e4,vQ=16384,CQ=2048,xQ=10*6e4,PL=new Set(["react-component-duplicates","react-hook-candidates","react-large-component-pressure"]),DL=new Set(["vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure"]),RQ=new Set([...DL,"suppressions"]),EQ=new Set(["similar","extract-candidates"]),_s=2,gf=Er({kind:"health-semantic-prewarm",invalidation:Ne("health-semantic-prewarm"),serialize:e=>JSON.stringify(e),deserialize:IQ});function IQ(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return n.version!==_s||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:_s,definitions:n.definitions,referenceCacheWrites:n.referenceCacheWrites,referenceIncomplete:n.referenceIncomplete,calleeRows:n.calleeRows,warmedAt:n.warmedAt}}catch{return null}}function wQ(e,t){return!t||t.count<=1?[...e]:e.filter((n,r)=>r%t.count===t.index)}function Uxe(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
536
- `)}function LQ(e){let t=qr(e);return t.symbols>=uQ||t.documents>=dQ}function qxe(e,t,n,r={}){if(!LQ(e))return{semantic:!0};if(n)return t==="dead"?(r.quiet||console.error("Large index detected; dead is scanning all candidates with semantic enrichment disabled to keep memory bounded."),{semantic:!1}):(r.quiet||console.error(`Large index detected; ${t} is running the unbounded semantic pass because --full was supplied.`),{semantic:!0});if(!r.quiet){let i=t==="inspect"?"Use --full only when every omitted semantic candidate can change the decision; it does not override source or behavior materialization ceilings.":t==="dead"?'Run "scip-query dead --full" for an unbounded candidate scan; semantic enrichment remains disabled on large indexes to keep memory bounded.':`Run "scip-query ${t} --full" for the unbounded semantic pass.`;console.error(`Large index detected; ${t} is using its bounded default analysis with semantic enrichment disabled. Candidate scans, when this command uses one, are capped at ${pf}. `+i)}return{scanLimit:pf,semantic:!1,analysisBudget:{scanLimit:pf,semanticEnrichment:!1,reason:t==="dead"?"large index default budget; pass --full for an unbounded memory-safe candidate scan":"large index default budget; pass --full for unbounded semantic analysis"}}}var PQ={env:process.env,projectFingerprint:pt,semanticEngineFingerprint:TL,readMarker:(e,t,n)=>gf.read(e,t,n),writeMarker:(e,t,n,r)=>gf.write(e,t,n,r),projectFiles:(e,t)=>wQ(Q(e,{scope:t.scope,includeIgnored:!1}),t.shard),candidateDefinitions:async(e,t,n)=>{let r=await mL(e,n,{collectGarbage:mo,yieldToEventLoop:()=>new Promise(a=>setImmediate(a))}),i=new Set(n),o=new Set(r.definitions.map(a=>a.symbolId)),s=[];for(let a of[{},{requireCallableSymbol:!0},{requireFunctionLikeSymbol:!0}])for(let c of sc(e,{...a,scope:t.scope}))!i.has(c.relativePath)||o.has(c.symbolId)||(o.add(c.symbolId),s.push(c));return[...r.definitions,...s].filter(a=>Ae(a.relativePath)!==null)},warmReferenceFragments:(e,t,n)=>qg(e,r=>In(e,r),{onBatch:t,...n?{files:n}:{}}),materializeReferences:(e,t,n)=>st(e).materializeReferences(t,n),materializeCallees:ud,releaseSemanticMemory:e=>co(e,{groups:["semantic-provider"]}),heapUsedFraction:()=>{let e=tQ();return e.heap_size_limit>0?e.used_heap_size/e.heap_size_limit:0},collectGarbage:mo,yieldToEventLoop:()=>new Promise(e=>setImmediate(e))},DQ=256,MQ=.75;function RL(e,t=DQ){if(!Number.isSafeInteger(t)||t<1)throw new Error(`Prewarm batch size must be a positive safe integer; received ${t}.`);let n=new Map;for(let s of e){let a=n.get(s.relativePath);a?a.push(s):n.set(s.relativePath,[s])}let r=[],i=[],o=0;for(let s of n.values())o>=t&&(r.push(i),i=[],o=0),i.push(...s),o+=1;return i.length>0&&r.push(i),r}async function Gxe(e,t,n=PQ){if(t.full!==!0)return vr("default-mode");if((n.env??process.env).SCIP_QUERY_HEALTH_SEMANTIC_PREWARM==="0")return vr("disabled");let r=vr("error");return ui("health.semantic-prewarm",async()=>{try{r=await AQ(e,t,n)}catch(i){r=vr("error",{error:i instanceof Error?i.message:String(i)})}return r},()=>FQ(r))}function TQ(e,t){let n=0,r=0,i=()=>(t.heapUsedFraction?.()??0)>=MQ;return{relieve({release:o}){i()&&(t.collectGarbage?.()&&(n+=1,!i())||o&&(t.releaseSemanticMemory?.(e),r+=1))},get collections(){return n},get releases(){return r}}}function kQ(e,t){e.definitions+=t.definitions,e.cacheHits+=t.cacheHits,e.cacheWrites+=t.cacheWrites,e.inMemoryHits+=t.inMemoryHits,e.misses+=t.misses,e.unkeyed+=t.unkeyed,e.incomplete+=t.incomplete}async function AQ(e,t,n){let r=n.projectFingerprint(e);if(!r)return vr("missing-project-fingerprint");let i=ML(t,n.semanticEngineFingerprint(e)),o=n.readMarker(e,i,r);if(o&&o.referenceIncomplete===0)return vr("cache-hit");let s=n.projectFiles(e,t),a=[];if(a=await ui("health.semantic-prewarm.candidate-definitions",async()=>(a=await n.candidateDefinitions(e,t,s),a),()=>({definitions:a.length,files:s.length,shard:t.shard??null})),a.length===0)return vr("no-semantic-definitions");let c=TQ(e,n),u=async()=>{await n.yieldToEventLoop?.()},l=a.filter(b=>Ae(b.relativePath)==="typescript"),d=null;if(l.length>0){let b=null;d=await ui("health.semantic-prewarm.reference-fragments",async()=>(b=await n.warmReferenceFragments(e,()=>c.relieve({release:!0}),s),b),()=>({definitions:l.length,rows:b?.computedFiles??0,files:b?.files??0,cacheHits:b?.cacheHits??0,available:b!==null}))}let m=d?a.filter(b=>Ae(b.relativePath)!=="typescript"):a,p={definitions:0,cacheHits:0,cacheWrites:0,inMemoryHits:0,misses:0,unkeyed:0,incomplete:0},f=0;await ui("health.semantic-prewarm.references",async()=>{for(let b of RL(m))kQ(p,n.materializeReferences(e,b,{prefetchCallees:!1})),c.relieve({release:!0}),await u();f=p.cacheHits+p.cacheWrites+p.inMemoryHits},()=>({definitions:m.length,rows:f,releases:c.releases}));let g=d?l.length:0;if(f+g===0&&p.misses+p.unkeyed>0)return vr("provider-unavailable",{definitions:a.length,referenceMisses:p.misses});N("health.semantic-prewarm.release-reference-memory",()=>n.releaseSemanticMemory?.(e));let h=0,y=c.releases;await ui("health.semantic-prewarm.callees",async()=>{for(let b of RL(a))h+=n.materializeCallees(e,b).size,c.relieve({release:!0}),await u()},()=>({definitions:a.length,rows:h,releases:c.releases-y,collections:c.collections}));let S={warmedFiles:s.length,...d?{referenceFragmentFiles:d.files,referenceFragmentComputedFiles:d.computedFiles}:{}};return p.incomplete>0?{status:"partial",reason:"incomplete-references",definitions:a.length,referenceCacheHits:p.cacheHits,referenceCacheWrites:p.cacheWrites,referenceMisses:p.misses,referenceIncomplete:p.incomplete,...S,calleeRows:h}:(t.shard||N("health.semantic-prewarm.marker-write",()=>n.writeMarker(e,i,r,{version:_s,definitions:a.length,referenceCacheWrites:p.cacheWrites,referenceIncomplete:p.incomplete,calleeRows:h,warmedAt:Date.now()})),{status:"warmed",reason:"cache-miss",definitions:a.length,referenceCacheHits:p.cacheHits,referenceCacheWrites:p.cacheWrites,referenceMisses:p.misses,referenceIncomplete:p.incomplete,...S,calleeRows:h})}function ML(e,t){return JSON.stringify({version:_s,cliVersion:xr,semanticEngineFingerprint:t,scope:e.scope??null})}function TL(e){return Yt(JSON.stringify({kind:"health-semantic-prewarm-engine",rust:Nr(e.config.projectRoot)}))}function vr(e,t={}){return{status:"skipped",reason:e,definitions:0,referenceCacheHits:0,referenceCacheWrites:0,referenceMisses:0,referenceIncomplete:0,calleeRows:0,...t}}function FQ(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 hf(e){return nc(t=>{let n=ri({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 wl(e,t,n){let r=e[0];if(!r)throw new Error("An evidence-bound analysis requires at least one index observation anchor.");let i=r.generationDigest,o=e.every(a=>a.generationDigest===i),s=t.every(a=>a?.facts.index?.generation.digest===i);return ri({projectRoot:r.database.config.projectRoot,...o&&s?{db:r.database}:{},observedSourceKinds:n})}async function zxe(e){return(await NQ(e)).result}async function NQ(e){let t=ZQ(e),n={...e,phaseTimeoutMs:t??null},r=hf(y=>{let S=mf(y,n,xr);if(!S)return null;let b=bL(y,S);return b||null});if(r.value)return{result:r.value,observationReceipt:wl([r.anchor],[],["index-generation","live-workspace"])};let i=hf(y=>({applicability:KQ(y,e),overview:Qp(y,"overview",e)})),{applicability:o,overview:s}=i.value,a=[r.anchor,i.anchor],c=new Map;c.set("overview",s);let u=Cl.filter(y=>y==="overview"?!1:WQ(y,o)?!0:(c.set(y,ii(y)),!1)),l=JQ(VQ(u)),d=[],m=[];if(e.full)try{m=await jQ(e)}catch(y){d.push(`Health semantic prewarm omitted: ${yf(y)}.`)}let p=e.full?t6(l.length):e6(l.length),f=await El(l,p,y=>XQ(y,e,t));if(f.flatMap(y=>y.result).forEach(y=>{y.healthPhaseMeta&&d.push(e.full?`Health phase "${y.phase}" omitted after a bounded worker failure: ${y.healthPhaseMeta.reason}.`:`Health phase "${y.phase}" deferred: ${y.healthPhaseMeta.reason}. Run health --full for exhaustive analysis.`),c.set(y.phase,y)}),d.length>0){let y=c.get("overview");c.set("overview",{...y,warnings:[...y.warnings,...d]})}return{result:nc(y=>{let S=Zp(Cl.map(x=>c.get(x)),y),b=mf(y,n,xr);return b&&SL(y,b,S),S}),observationReceipt:wl(a,[...m.map(y=>y.observationReceipt),...f.map(y=>y.observationReceipt)],["index-generation","live-workspace"])}}var EL=12288,_Q=2048,OQ=8192,BQ=4;function $Q(e=process.env,t=wL(),n=Ll()){let r={shards:1,heapMb:UQ(e,n)},i=Number.isFinite(n)&&n>0?n/(1024*1024):0,o=Math.floor(Math.max(0,i-OQ)/(EL+_Q)),s=Number.isFinite(t)?Math.max(1,t-1):1,a=Number.parseInt(e.SCIP_QUERY_HEALTH_PREWARM_SHARDS??"",10),c=Number.isSafeInteger(a)&&a>0?a:Number.POSITIVE_INFINITY,u=Math.min(BQ,o,s,c);return!Number.isFinite(u)||u<2?r:{shards:u,heapMb:EL}}function IL(e,t){let n=process.argv[1]??Pl(import.meta.url),r=["--full"];return e.scope&&r.push("--scope",e.scope),e.shard&&r.push("--shard-index",String(e.shard.index),"--shard-count",String(e.shard.count)),Ns({cliPath:n,command:nQ,args:r,env:{...process.env,NODE_OPTIONS:da(process.env.NODE_OPTIONS,t)},label:e.shard?`Health semantic prewarm ${e.shard.index+1}/${e.shard.count}`:"Health semantic prewarm",timeoutMs:GQ()})}async function jQ(e,t=$Q()){if(t.shards<2)return[await IL(e,t.heapMb)];let n=Array.from({length:t.shards},(o,s)=>({index:s,count:t.shards})),r=await El(n,t.shards,o=>IL({...e,shard:o},t.heapMb)),i=HQ(r.map(o=>o.result));return i.status==="warmed"&&nc(o=>{let s=pt(o);s&&gf.write(o,ML(e,TL(o)),s,{version:_s,definitions:i.definitions,referenceCacheWrites:i.referenceCacheWrites,referenceIncomplete:i.referenceIncomplete,calleeRows:i.calleeRows,warmedAt:Date.now()})}),r}function HQ(e){let t=i=>e.reduce((o,s)=>o+(i(s)??0),0),n={definitions:t(i=>i.definitions),referenceCacheHits:t(i=>i.referenceCacheHits),referenceCacheWrites:t(i=>i.referenceCacheWrites),referenceMisses:t(i=>i.referenceMisses),referenceIncomplete:t(i=>i.referenceIncomplete),calleeRows:t(i=>i.calleeRows),warmedFiles:t(i=>i.warmedFiles),referenceFragmentFiles:t(i=>i.referenceFragmentFiles),referenceFragmentComputedFiles:t(i=>i.referenceFragmentComputedFiles)},r=e.find(i=>i.status==="partial")??e.find(i=>i.status==="skipped"&&i.reason!=="cache-hit");return r?{...n,status:r.status,reason:r.reason,...r.error?{error:r.error}:{}}:e.length>0&&e.every(i=>i.status==="skipped")?{...n,status:"skipped",reason:"cache-hit"}:{...n,status:"warmed",reason:"cache-miss"}}function UQ(e=process.env,t=Ll()){let n=Number.parseInt(e.SCIP_QUERY_HEALTH_SEMANTIC_PREWARM_HEAP_MB??"",10);return Number.isSafeInteger(n)&&n>0?n:qQ(t)}function qQ(e){return kL(e,{min:CQ,max:vQ})}function kL(e,t){let n=Math.floor(e/2097152);return!Number.isFinite(n)||n<=0?t.max:Math.max(t.min,Math.min(t.max,n))}function GQ(e=process.env){let t=Number.parseInt(e.SCIP_QUERY_HEALTH_SEMANTIC_PREWARM_TIMEOUT_MS??"",10);return Number.isSafeInteger(t)&&t>0?t:xQ}function zQ(e=process.env){let t=Number.parseInt(e.SCIP_QUERY_HEALTH_FULL_PHASE_HEAP_MB??"",10);return Number.isSafeInteger(t)&&t>0?t:yQ}function KQ(e,t){return Ys(e,{scope:t.scope})}function WQ(e,t){return PL.has(e)?t.react:DL.has(e)?t.vue:!0}function VQ(e){return hL(e,[PL,RQ,EQ])}var YQ={"wrapper-candidates":49,"complexity-hotspots":35,"passthrough-candidates":31,"stale-abstractions":30,"extract-candidates":29,similar:29,dead:20,isolated:12,"react-component-duplicates":10,"react-hook-candidates":10,cycles:8};function JQ(e){let t=n=>n.reduce((r,i)=>r+(YQ[i]??1),0);return e.map((n,r)=>({task:n,index:r,weight:t(n)})).sort((n,r)=>r.weight-n.weight||n.index-r.index).map(n=>n.task)}function ii(e){switch(e){case"react-component-duplicates":return{phase:e,reactComponentDuplicates:{count:0,loc:0,files:[]}};case"react-hook-candidates":return{phase:e,reactHookCandidates:{count:0,loc:0,files:[]}};case"react-large-component-pressure":return{phase:e,reactLargeComponentPressure:{count:0,loc:0,files:[]}};case"vue-component-duplicates":return{phase:e,vueComponentDuplicates:{count:0,loc:0,files:[]}};case"vue-composable-candidates":return{phase:e,vueComposableCandidates:{count:0,loc:0,files:[]}};case"vue-large-view-pressure":return{phase:e,vueLargeViewPressure:{count:0,loc:0,files:[]}};default:throw new Error(`Health phase "${e}" cannot be synthesized.`)}}function XQ(e,t,n){if(e.length===1)return QQ(e[0],t,n).then(s=>({result:[s.result],...s.observationReceipt?{observationReceipt:s.observationReceipt}:{}}));let r=e.join(","),i=process.argv[1]??Pl(import.meta.url),o=[r];return t.scope&&o.push("--scope",t.scope),t.full&&o.push("--full"),Ns({cliPath:i,command:LL,args:o,...t.full?{env:AL()}:{},label:`Health phases "${r}"`,timeoutMs:n}).catch(s=>{if(!t.full&&!(s instanceof gn))throw s;let a=s instanceof gn?s.timeoutMs:n??0;return{result:e.map(c=>FL(c,a,s instanceof gn?`timed out after ${s.timeoutMs}ms`:yf(s)))}})}function QQ(e,t,n){let r=process.argv[1]??Pl(import.meta.url),i=[e];return t.scope&&i.push("--scope",t.scope),t.full&&i.push("--full"),Ns({cliPath:r,command:LL,args:i,...t.full?{env:AL()}:{},label:`Health phase "${e}"`,timeoutMs:n}).catch(o=>{if(!t.full&&!(o instanceof gn))throw o;let s=o instanceof gn?o.timeoutMs:n??0;return{result:FL(e,s,o instanceof gn?`timed out after ${o.timeoutMs}ms`:yf(o))}})}function yf(e){let t=e instanceof Error?e.message:String(e);if(/heap out of memory|reaching memory limit/i.test(t))return"exceeded its isolated memory limit";let n=t.split(/\r?\n/,1)[0]?.trim()||"isolated worker failed";return n.length<=240?n:`${n.slice(0,237)}...`}function AL(e=process.env){return{...e,NODE_OPTIONS:da(e.NODE_OPTIONS,zQ(e))}}function ZQ(e,t=process.env){let n=e.full?bQ:SQ,r=t.SCIP_QUERY_HEALTH_PHASE_TIMEOUT_MS;if(!r)return n;let i=parseInt(r,10);return!Number.isFinite(i)||i<0?n:i===0?void 0:i}function FL(e,t,n){let r={healthPhaseMeta:{status:"deferred",reason:n,timeoutMs:t}};switch(e){case"overview":throw new Error("Overview health phase cannot be deferred.");case"dead":return{phase:e,dead:{count:0,loc:0,files:[]},...r};case"isolated":return{phase:e,isolated:{count:0,loc:0,files:[]},...r};case"cycles":return{phase:e,realCycleCount:0,...r};case"similar":return{phase:e,similarCount:0,...r};case"duplicate-bodies":return{phase:e,duplicateBodies:{count:0,loc:0,files:[]},...r};case"twin-drift":return{phase:e,twinDrift:{count:0,loc:0,files:[]},...r};case"react-component-duplicates":return{...ii(e),...r};case"react-hook-candidates":return{...ii(e),...r};case"react-large-component-pressure":return{...ii(e),...r};case"vue-component-duplicates":return{...ii(e),...r};case"vue-composable-candidates":return{...ii(e),...r};case"vue-large-view-pressure":return{...ii(e),...r};case"extract-candidates":return{phase:e,extractCount:0,extractExclusions:[],...r};case"wrapper-candidates":return{phase:e,wrappers:{count:0,loc:0,files:[]},...r};case"passthrough-candidates":return{phase:e,passthroughs:{count:0,loc:0,files:[]},...r};case"stale-abstractions":return{phase:e,stale:{count:0,loc:0,files:[],unused:0,singleUse:0},...r};case"drift":return{phase:e,drift:{count:0,unusedImports:0,architectureViolations:0,layerViolations:0,direct:0,signal:0},...r};case"complexity-hotspots":return{phase:e,complexity:{top:[],extremeCount:0},...r};case"git-evidence":return{phase:e,gitEvidence:null,...r};case"suppressions":return{phase:e,suppressions:{total:0,byCategory:{}},...r};case"coverage-contracts":return{phase:e,coverageContracts:{count:0,loc:0,files:[]},...r}}}var e6=bf({envKey:"SCIP_QUERY_HEALTH_CONCURRENCY",defaultMinimum:mQ,defaultMaximum:pQ}),t6=bf({envKey:"SCIP_QUERY_HEALTH_FULL_CONCURRENCY",defaultMinimum:fQ,defaultMaximum:gQ,memoryPerTaskBytes:hQ});function n6(e){let t=e.generation,n=[t.mode,t.publishedAt?`published ${t.publishedAt}`:null].filter(i=>i!==null).join(", "),r=e.git?`git ${e.git.head.slice(0,12)}${e.git.branch?` on ${e.git.branch}`:" (detached)"}, ${e.git.dirtyPaths} uncommitted path(s)`:"git: not a repository";return`Input: generation ${t.identity.slice(0,12)}${n?` (${n})`:""}; ${r}`}function Kxe(e){if(console.log(`
537
- 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)
538
- `),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${Ed(e.overview.indexSizeBytes)}`),e.provenance&&console.log(` ${n6(e.provenance)}`),console.log(""),e.warnings&&e.warnings.length>0){console.log(" Warnings:");for(let r of e.warnings)console.log(` ${r}`);console.log("")}console.log(" Findings:");let t=e.findings;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: ${ff(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: ${ff(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: ${ff(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}`);let n=e.policyExclusions??[];if(n.length>0){console.log(`
539
- Policy exclusions (listed by the detector command, not counted above):`);for(let r of n)console.log(` ${r.detector}: ${r.count} ${r.detail}`)}if(e.actions.length>0){console.log(`
540
- Prioritized Actions (highest impact + lowest effort first):`);for(let r=0;r<e.actions.length;r++){let i=e.actions[r],o=i.locRecoverable>0?` (~${i.locRecoverable} LOC involved)`:"";console.log(` ${r+1}. [${i.effort} effort / ${i.impact} impact] ${i.description}${o}`)}}if(e.topComplexity.length>0){console.log(`
541
- Top Complexity Hotspots:`);for(let r of e.topComplexity)console.log(` ${r.score.toFixed(1).padStart(6)} ${r.symbol}`)}if(e.detectorEvidence.length>0){console.log(`
542
- Detector Evidence Calibration:`);for(let r of e.detectorEvidence){let i=r.unavailableRequirements.length>0?`; unavailable: ${r.unavailableRequirements.join(", ")}`:"";console.log(` ${r.detector}: ${r.status}/${r.providerCoverage}${i}`)}console.log(" Full claims, non-claims, providers, and recovery commands are available in health --json.")}if(o6(e),i6(e),e.scoreBreakdown.length>0){console.log(`
543
- Score Breakdown (100 minus the following):`);for(let r of e.scoreBreakdown)console.log(` -${String(r.points).padStart(2)} ${r.axis}: ${r.detail}`)}e.actions.length===0&&console.log(e.warnings&&e.warnings.length>0?`
544
- No findings from completed analyses. Review warnings before interpreting this result as clean.`:`
545
- No issues found. Codebase is clean.`)}function ff(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${r6(t)} score-weighted)`}function r6(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function i6(e){if(e.pressure.length!==0){console.log(`
546
- 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 o6(e){let t=e.axes;if(console.log(`
547
- Axes:`),console.log(` Zero-reference candidates: ${t.deletable.loc} LOC across ${t.deletable.symbols} symbols`),t.changeAmplification){let r=t.changeAmplification;console.log(` Change amplification: ${r.medianFilesPerCommit} files/commit median, ${r.p90FilesPerCommit} p90 (${r.commitsAnalyzed} commits)`)}if(t.hiddenCoupling&&t.hiddenCoupling.pairCount>0){console.log(` Hidden coupling: ${t.hiddenCoupling.pairCount} co-changing pair(s) without a dependency edge`);for(let r of t.hiddenCoupling.top.slice(0,3))console.log(` ${r.fileA} <-> ${r.fileB} (${r.together}x together, ${Math.round(r.confidence*100)}%)`)}if(t.churnWeightedComplexity&&t.churnWeightedComplexity.length>0){let r=t.churnWeightedComplexity[0];r.weighted>0&&console.log(` Churn x complexity: hottest is ${r.symbol} (${r.changes} changes, weighted ${r.weighted})`)}let n=t.evidenceQuality;if(console.log(` Evidence quality: ${n.graphFindings} graph-fact finding(s), ${n.heuristicFindings} heuristic finding(s), ${n.userSuppressed} user-suppressed`),e.validation&&e.validation.flaggedFiles>0){let r=e.validation,i=r.ratio===null?"n/a":`${r.ratio}x`;console.log(` Validation: flagged files fix-density ${r.flaggedFixDensity} vs baseline ${r.baselineFixDensity} (${i})`),console.log(` fix-commit signal: subject-keyword heuristic over ${r.validationBasis.commitsScanned} commits`)}}async function Wxe(e){let t=hf(o=>{let s=to(o,{base:e.base});return s.note?{kind:"complete",result:tl(o,{base:e.base})}:s.changedFiles.length===0?{kind:"complete",result:tl(o,{base:e.base})}:{kind:"batched",plan:s}}),n=t.value;if(n.kind==="complete")return{result:n.result,observationReceipt:wl([t.anchor],[],["index-generation","live-workspace"])};let r=a6(n.plan.changedFiles),i=await El(r,s6(r.length),o=>u6(o,e));return{result:nl(n.plan.changedFiles,i.map(o=>o.result)),observationReceipt:wl([t.anchor],i.map(o=>o.observationReceipt),["index-generation","live-workspace"])}}var s6=bf({envKey:"SCIP_QUERY_DIFF_IMPACT_CONCURRENCY",defaultMinimum:oQ,defaultMaximum:sQ});function a6(e){return gL(e,iQ)}function bf(e){return(t,n=process.env,r=wL,i=Ll())=>c6(t,n,r,i,e)}function c6(e,t,n,r,i){let o=t[i.envKey],s=l6(n,r,i),a=o?parseInt(o,10):s;return!Number.isFinite(a)||a<1?Math.min(s,e):Math.min(a,e)}function l6(e,t,n){let r=e(),i=Number.isFinite(r)?Math.max(n.defaultMinimum,r-1):0,o=n.memoryPerTaskBytes!==void 0&&Number.isFinite(t)&&t>0?Math.floor(t/2/n.memoryPerTaskBytes):Number.POSITIVE_INFINITY;return Math.min(n.defaultMaximum,o,Math.max(n.defaultMinimum,i))}function u6(e,t){let n=process.argv[1]??Pl(import.meta.url),r=[];return t.base&&r.push("--base",t.base),Ns({cliPath:n,command:rQ,args:r,env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e),NODE_OPTIONS:da(process.env.NODE_OPTIONS,m6())},label:"Diff-impact batch",timeoutMs:d6()})}function d6(e=process.env){let t=Number.parseInt(e.SCIP_QUERY_DIFF_IMPACT_BATCH_TIMEOUT_MS??"",10);return Number.isSafeInteger(t)&&t>0?t:lQ}function m6(e=process.env,t=Ll()){let n=Number.parseInt(e.SCIP_QUERY_DIFF_IMPACT_BATCH_HEAP_MB??"",10);return Number.isSafeInteger(n)&&n>0?n:kL(t,{min:cQ,max:aQ})}function Vxe(e){console.log(`Changed files: ${e.summary.totalChangedFiles}`),console.log(`Changed symbols: ${e.summary.totalChangedSymbols}`),console.log(`Affected consumer files: ${e.summary.totalAffectedFiles}`),e.summary.note&&console.log(`Note: ${e.summary.note}`);for(let n of e.evidenceTiers.filter(r=>r.state==="failed"))console.log(`WARNING: ${n.tier} evidence failed for ${n.attemptedSymbols} candidate symbol(s): ${n.reason}`);let t=e.attributionNotes.filter(n=>n.method==="unattributed");if(t.length>0){let n=[...new Set(t.map(r=>r.file))];for(let r of n){let i=t.filter(o=>o.file===r).length;console.log(`note: ${i} changed line-range(s) in ${r} belong to no indexed symbol`)}}console.log(""),e.changedSymbols.length>0&&(console.log("Changed symbols:"),Pd.list(e.changedSymbols,n=>` ${n.file} ${n.shortName} (fan-in: ${n.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
548
- Affected consumer files:`),Pd.list(e.affectedConsumers,n=>` ${n.file} (${n.consumedSymbols} symbol(s))`))}import{AsyncLocalStorage as p6}from"async_hooks";import{createHash as vf}from"crypto";import{existsSync as f6,mkdirSync as g6}from"fs";import{tmpdir as h6}from"os";import{isAbsolute as y6,join as OL,resolve as BL}from"path";var Sf=2,b6="SCIP_QUERY_SESSION",NL="SCIP_QUERY_SESSION_DIR",S6=128,so=new p6;function aRe(e,t){let n=e.sessionEnabled===!1||e.json?void 0:A6(),r={enabled:n!==void 0,reemit:e.reemit===!0,command:e.command,projectRoot:BL(e.cwd),sessionIdentity:n,staged:[],stagedEvidence:[],finalized:!1};return so.run(r,t)}function cRe(e){let t=so.getStore();!t||t.finalized||(t.generationIdentity=e)}function lRe(e){let t=so.getStore();if(!t||t.finalized)return;t.finalized=!0;let n=t.state;if(!n){t.staged.length=0,t.stagedEvidence.length=0;return}try{if(e&&(t.staged.length>0||t.stagedEvidence.length>0)){let r=n.ledger.nextOrdinal,i=P6(t.staged).map(s=>({...s,ordinal:r,command:t.command})),o=M6(t.stagedEvidence).map(s=>({...s,ordinal:r,command:t.command}));n.ledger.ranges.push(...i),n.ledger.evidence.push(...o),n.ledger.nextOrdinal+=1,n.ledger.updatedAt=new Date().toISOString(),Dr(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 uRe(e){let t=e.source.split(`
549
- `);if(t.length===0)return"";let n=v6(e.relativePath,e.startLine,t,e.ownerSymbol,e.sessionPolicy??"exact-unit"),r=e.indent??" ",i=e.sourceIndent??" ",o=e.focusLines??new Set;return n.map(s=>{let a=Ld(e.relativePath,s.startLine,s.endLine);if(s.kind==="covered"){let l=s.ordinal===null?"this command":`session #${s.ordinal} via ${s.command}`;return[`${r}${a} [source previously emitted: ${l}; not repeated]`,...e.afterHeader??[]].join(`
550
- `)}let c=e.headerSuffix??"",u=s.lines.map((l,d)=>{let m=s.startLine+d,p=e.showFocusMarker===!1?"":o.has(m)?">":" ",f=e.lineNumberWidth??5;return`${i}${p}${String(rc(m)).padStart(f)} ${l}`});return[`${r}${a}${c}`,...e.blankAfterHeader?[""]:[],...e.afterHeader??[],...u].join(`
551
- `)}).join(`
552
- `)}function dRe(e){let t=so.getStore();if(!t||!t.enabled)return e.content;let n=Cf(t);if(!n)return e.content;let r=$L(e.content),i=Dl(n.ledger.evidence,o=>o.kind===e.kind&&o.identity===e.identity&&o.contentHash===r);if(i&&!t.reemit){let o=e.label?`; ${_L(e.label)}`:"";return`${e.indent??""}[${e.kind} evidence previously emitted: receipt ${i.receiptId}; session #${i.ordinal} via ${i.command}${o}; not repeated]`}return t.stagedEvidence.push({kind:e.kind,identity:e.identity,contentHash:r,receiptId:F6(e.kind,e.identity,r),...e.label?{label:_L(e.label)}:{}}),e.content}function mRe(e=!1){let t=so.getStore();if(!t?.enabled)return{enabled:!1,reason:"No explicit SCIP_QUERY_SESSION is active; source packets render independently.",uniqueLines:0,evidenceItems:0,emissions:0,rows:[]};let n=Cf(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{Dr(n.ledgerPath,n.ledger,{spacing:2,trailingNewline:!0})}catch{return{enabled:!1,reason:"The exploration-session ledger could not be reset; evidence output remains fail-open.",uniqueLines:0,evidenceItems:0,emissions:0,rows:[]}}}let r=new Map;for(let a of n.ledger.ranges){let c=r.get(a.ordinal)??[];c.push(a),r.set(a.ordinal,c)}let i=new Map;for(let a of n.ledger.evidence){let c=i.get(a.ordinal)??[];c.push(a),i.set(a.ordinal,c)}let s=[...new Set([...r.keys(),...i.keys()])].sort((a,c)=>a-c).map(a=>{let c=r.get(a)??[],u=i.get(a)??[],l=c[0]?.command??u[0]?.command??"unknown",d=c.length===0?null:(()=>{let f=c.slice(0,8).map(h=>Ld(h.relativePath,h.startLine,h.endLine)).join(", "),g=c.length>8?`, ... ${c.length-8} more range(s)`:"";return` #${a} ${l}: ${f}${g}`})();if(u.length===0)return d;let m=u.slice(0,8).map(f=>`${f.receiptId} ${f.kind}${f.label?` ${f.label}`:""}`).join(", "),p=u.length>8?`, ... ${u.length-8} more item(s)`:"";return d?`${d}
553
- evidence: ${m}${p}`:` #${a} ${l}: ${m}${p}`});return{enabled:!0,uniqueLines:T6(n.ledger.ranges),evidenceItems:n.ledger.evidence.length,emissions:new Set([...r.keys(),...i.keys()]).size,rows:s}}function v6(e,t,n,r,i){let o=so.getStore(),s=t+n.length-1;if(!o)return[{kind:"source",startLine:t,endLine:s,lines:[...n]}];let c=(o.enabled?Cf(o):null)?.ledger.ranges??[],u=n.map($L),l=i==="exact-unit"&&!o.reemit?Dl(c,h=>h.policy==="exact-unit"&&h.relativePath===e&&h.startLine===t&&h.endLine===s&&h.ownerSymbol===r&&N6(h.lineHashes,u)):void 0;if(l)return[{kind:"covered",startLine:t,endLine:s,ordinal:l.ordinal,command:l.command}];let d=i==="exact-unit"&&!o.reemit?x6(c,e,t,s,u):void 0;if(d)return[{kind:"covered",startLine:t,endLine:s,ordinal:d.ordinal,command:d.command}];let m=n.map((h,y)=>C6(c,e,t+y,u[y]));if(!(i==="preview"&&!o.reemit&&m.every(h=>h!==void 0)))return o.staged.push({relativePath:e,startLine:t,endLine:s,ownerSymbol:r,policy:i,lineHashes:u}),[{kind:"source",startLine:t,endLine:s,lines:[...n]}];let f=[],g=0;for(;g<n.length;){let h=m[g],y=g;for(;y+1<n.length&&R6(h,m[y+1]);)y+=1;let S=t+g,b=t+y;f.push({kind:"covered",startLine:S,endLine:b,ordinal:h.ordinal,command:h.command}),g=y+1}return f}function C6(e,t,n,r){let i=Dl(e,o=>o.relativePath===t&&o.startLine<=n&&n<=o.endLine&&o.lineHashes[n-o.startLine]===r);if(i)return{ordinal:i.ordinal,command:i.command}}function x6(e,t,n,r,i){let o=Dl(e,s=>s.policy==="exact-unit"&&s.relativePath===t&&s.startLine<=n&&s.endLine>=r&&i.every((a,c)=>s.lineHashes[n-s.startLine+c]===a));return o?{ordinal:o.ordinal,command:o.command}:void 0}function R6(e,t){return!e||!t?e===t:e.ordinal===t.ordinal&&e.command===t.command}function Cf(e){if(e.state!==void 0)return e.state;if(!e.sessionIdentity||!e.generationIdentity)return e.state=null,null;try{let t=k6();g6(t,{recursive:!0,mode:448});let n=vf("sha256").update(e.projectRoot).update("\0").update(e.generationIdentity).update("\0").update(e.sessionIdentity).digest("hex"),r=OL(t,`${n}.json`),i=Ci(`${r}.lock`,{kind:"source-emission-session",detail:{session:n.slice(0,12)}});if(i.kind!=="acquired")return e.state=null,null;let o;try{o=f6(r)?I6(JSON.parse(Xe(r,"source emission session ledger")),{projectRoot:e.projectRoot,generationIdentity:e.generationIdentity,sessionIdentity:e.sessionIdentity}):E6(e)}catch{return i.lock.release(),e.state=null,null}return e.state={ledgerPath:r,lock:i.lock,ledger:o},e.state}catch{return e.state=null,null}}function E6(e){return{version:Sf,projectRoot:e.projectRoot,generationIdentity:e.generationIdentity,sessionIdentity:e.sessionIdentity,nextOrdinal:1,updatedAt:new Date().toISOString(),ranges:[],evidence:[]}}function I6(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:Sf,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!==Sf||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(w6)||!Array.isArray(n.evidence)||!n.evidence.every(L6))throw new Error("Invalid source emission ledger.");return n}function w6(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(ci)&&(t.ownerSymbol===void 0||typeof t.ownerSymbol=="string")}function L6(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"&&ci(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 P6(e){let t=[...e].sort((r,i)=>r.relativePath.localeCompare(i.relativePath)||r.startLine-i.startLine||r.endLine-i.endLine),n=[];for(let r of t){let i=n[n.length-1];if(i&&i.relativePath===r.relativePath&&i.ownerSymbol===r.ownerSymbol&&i.policy===r.policy&&r.startLine<=i.endLine+1&&D6(i,r)){let o=r.startLine-i.startLine;for(let s=0;s<r.lineHashes.length;s+=1)i.lineHashes[o+s]??=r.lineHashes[s];i.endLine=Math.max(i.endLine,r.endLine)}else n.push({...r,lineHashes:[...r.lineHashes]})}return n}function D6(e,t){let n=Math.max(e.startLine,t.startLine),r=Math.min(e.endLine,t.endLine);for(let i=n;i<=r;i+=1)if(e.lineHashes[i-e.startLine]!==t.lineHashes[i-t.startLine])return!1;return!0}function M6(e){let t=new Set,n=[];for(let r of e){let i=`${r.kind}\0${r.identity}\0${r.contentHash}`;t.has(i)||(t.add(i),n.push(r))}return n}function T6(e){let t=new Map;for(let r of e){let i=t.get(r.relativePath)??[];i.push(r),t.set(r.relativePath,i)}let n=0;for(let r of t.values()){r.sort((s,a)=>s.startLine-a.startLine||s.endLine-a.endLine);let i=-1,o=-1;for(let s of r)i<0?(i=s.startLine,o=s.endLine):s.startLine<=o+1?o=Math.max(o,s.endLine):(n+=o-i+1,i=s.startLine,o=s.endLine);i>=0&&(n+=o-i+1)}return n}function k6(){let e=process.env[NL];if(!e)return OL(h6(),`scip-query-source-sessions-${process.getuid?.()??"user"}`);if(!y6(e))throw new Error(`${NL} must be an absolute path.`);return BL(e)}function A6(){let e=process.env[b6]?.trim();if(e&&!(e.length>S6||!/^[A-Za-z0-9._:-]+$/.test(e)))return`explicit:${e}`}function F6(e,t,n){return`ev-${vf("sha256").update(e).update("\0").update(t).update("\0").update(n).digest("hex").slice(0,12)}`}function _L(e){let t=e.replace(/[\r\n\t]+/gu," ").replace(/\s+/gu," ").trim();return t.length<=160?t:`${t.slice(0,157)}...`}function $L(e){return vf("sha256").update(e).digest("hex")}function N6(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function Dl(e,t){for(let n=e.length-1;n>=0;n-=1){let r=e[n];if(t(r))return r}}import{createHash as _6}from"crypto";import{existsSync as Rf,mkdirSync as O6,rmSync as B6}from"fs";import{tmpdir as $6}from"os";import{isAbsolute as j6,join as HL,resolve as Ml}from"path";var UL=1,H6="SCIP_QUERY_SESSION",jL="SCIP_QUERY_SESSION_DIR",U6=128,qL=8,GL=32768,Tl=new Map;function CRe(e,t,n=!0){if(!n)return;let r=kl();if(!r)return;let i=wf(e),o=t.map(a=>a.trim()).filter(a=>a.startsWith("scip-query system-map ")&&a.length<=GL).slice(0,qL),s=zL(i,r);o.length===0?Tl.delete(s):Tl.set(s,o)}function xRe(e,t,n,r=!0,i){if(!r||e!=="anchors"&&e!=="system-map")return;let o=kl();if(!o)return;let s=wf(t),a=If(s,o);if(e==="system-map"){n?B6(a,{force:!0}):Rf(a)&&i&&xf(a,()=>{let c=Ef(a,s,o);c&&Dr(a,{...c,pendingMapContinuation:i,mapExecution:void 0,updatedAt:new Date().toISOString()},{spacing:2,trailingNewline:!0})});return}xf(a,()=>{let c=q6(s,o),u={version:UL,projectRoot:s,sessionIdentity:o,mapRequired:!0,...c.length>0?{recommendedMapCommands:c}:{},updatedAt:new Date().toISOString()};Dr(a,u,{spacing:2,trailingNewline:!0})})}function RRe(e,t=!0){if(!t)return;let n=kl();if(!n)return;let r=wf(e),i=If(r,n);Rf(i)&&xf(i,()=>{let o=Ef(i,r,n);if(o){if(o.pendingMapContinuation)throw new Error(["MAP TRANSPORT INCOMPLETE","The selected system map has already been computed. Restarting it would repeat the same repository work.",`Continue exactly: ${o.pendingMapContinuation}`].join(`
554
- `));if(o.mapExecution&&G6(o.mapExecution.processId))throw new Error(["NAVIGATION MAP ALREADY RUNNING","A selected system map is already computing in this SCIP_QUERY_SESSION.","Poll the existing terminal execution. Do not launch a duplicate map or inspect in parallel."].join(`
555
- `));Dr(i,{...o,mapExecution:{processId:process.pid,startedAt:new Date().toISOString()},updatedAt:new Date().toISOString()},{spacing:2,trailingNewline:!0})}})}function ERe(e,t,n=!0){if(!n)return;let r=kl();if(!r)return;let i=If(Ml(e),r);if(!Rf(i))return;let o=Ef(i,Ml(e),r);if(!o?.mapRequired)return;let s=o.recommendedMapCommands?.length?["This refusal is a recoverable protocol step, not evidence that the requested code cannot be explored.","Run exactly one of the ranked map commands below, then finish every emitted continuation:",...o.recommendedMapCommands.map((a,c)=>` [${c+1}] ${a}`)]:[`Do not retry ${t}. Run one printed next-abstraction system-map command and finish every emitted continuation first.`];throw new Error(["NAVIGATION MAP REQUIRED","An anchors locator completed in this SCIP_QUERY_SESSION, but its selected system map has not reached transport completion.",`Do not retry ${t}.`,...s,"The map must complete before the agent can choose source detail; map and detail exploration cannot run concurrently."].join(`
556
- `))}function Ef(e,t,n){try{let r=JSON.parse(Xe(e,"navigation session state"));return r.version===UL&&r.projectRoot===t&&r.sessionIdentity===n&&r.mapRequired===!0&&(r.recommendedMapCommands===void 0||Array.isArray(r.recommendedMapCommands)&&r.recommendedMapCommands.length<=qL&&r.recommendedMapCommands.every(i=>typeof i=="string"&&i.startsWith("scip-query system-map ")&&i.length<=GL))&&(r.pendingMapContinuation===void 0||typeof r.pendingMapContinuation=="string")&&(r.mapExecution===void 0||typeof r.mapExecution=="object"&&r.mapExecution!==null&&Number.isSafeInteger(r.mapExecution.processId)&&typeof r.mapExecution.startedAt=="string")?r:null}catch{return null}}function q6(e,t){let n=zL(e,t),r=Tl.get(n)??[];return Tl.delete(n),r}function zL(e,t){return`${e}\0${t}`}function G6(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function If(e,t){let n=z6();O6(n,{recursive:!0,mode:448});let r=_6("sha256").update(e).update("\0").update(t).digest("hex");return HL(n,`navigation-${r}.json`)}function z6(){let e=process.env[jL];if(!e)return HL($6(),`scip-query-source-sessions-${process.getuid?.()??"user"}`);if(!j6(e))throw new Error(`${jL} must be an absolute path.`);return Ml(e)}function wf(e){let t=process.env.SCIP_QUERY_PROJECT_ROOT?.trim();return Ml(t||e)}function kl(){let e=process.env[H6]?.trim();if(e&&!(e.length>U6||!/^[A-Za-z0-9._:-]+$/u.test(e)))return`explicit:${e}`}function xf(e,t){let n=Ci(`${e}.lock`,{kind:"navigation-session",detail:{state:e.slice(-17,-5)}});if(n.kind!=="acquired")throw new Error("Navigation session state is busy. Retry the completed command.");try{t()}finally{n.lock.release()}}export{jr as a,qr as b,U0 as c,Q0 as d,yo as e,Qt as f,hh as g,fZ as h,Ma as i,i7 as j,CT as k,ki as l,Sb as m,Iee as n,c_ as o,Qo as p,sh as q,I8 as r,Zo as s,es as t,vc as u,nC as v,EO as w,WO as x,Bte as y,aae as z,ZO as A,oB as B,Gt as C,He as D,DC as E,Q$ as F,f1 as G,ms as H,Im as I,O1 as J,ti as K,LH as L,MH as M,TH as N,kH as O,zH as P,VH as Q,YH as R,JH as S,QH as T,ZH as U,eU as V,CR as W,gs as X,km as Y,xU as Z,hs as _,IU as $,wU as aa,AU as ba,BU as ca,$U as da,jU as ea,bs as fa,Bm as ga,Ss as ha,Gq as ia,Um as ja,Gm as ka,PG as la,vs as ma,Cs as na,Wm as oa,rz as pa,xs as qa,wK as ra,QK as sa,sp as ta,lW as ua,to as va,eI as wa,qW as xa,Es as ya,C2 as za,ll as Aa,W2 as Ba,ws as Ca,zY as Da,KY as Ea,eJ as Fa,fJ as Ga,CJ as Ha,BJ as Ia,Op as Ja,bw as Ka,Bp as La,Sw as Ma,gl as Na,m5 as Oa,Ts as Pa,ks as Qa,As as Ra,PX as Sa,DX as Ta,MX as Ua,Vp as Va,Cl as Wa,Qp as Xa,m4 as Ya,V4 as Za,Y4 as _a,X4 as $a,Z4 as ab,u3 as bb,b3 as cb,_k as db,Gte as eb,za as fb,Go as gb,fS as hb,yne as ib,bne as jb,Sne as kb,vne as lb,Cne as mb,xne as nb,One as ob,yS as pb,Bne as qb,bS as rb,SS as sb,Za as tb,oF as ub,sF as vb,aF as wb,cF as xb,CS as yb,ec as zb,ore as Ab,tc as Bb,xS as Cb,sre as Db,are as Eb,cre as Fb,lre as Gb,pF as Hb,nc as Ib,ure as Jb,dre as Kb,Ed as Lb,mre as Mb,fre as Nb,gre as Ob,hre as Pb,yre as Qb,ES as Rb,Nt as Sb,wd as Tb,bre as Ub,ri as Vb,XCe as Wb,cxe as Xb,rc as Yb,xF as Zb,Ld as _b,Cre as $b,Pd as ac,LL as bc,nQ as cc,rQ as dc,Uxe as ec,qxe as fc,Gxe as gc,zxe as hc,NQ as ic,Kxe as jc,Wxe as kc,Vxe as lc,aRe as mc,cRe as nc,lRe as oc,uRe as pc,dRe as qc,mRe as rc,CRe as sc,xRe as tc,RRe as uc,ERe as vc};
557
- //# sourceMappingURL=chunk-NWLVNU66.js.map