scip-query 0.17.2 → 0.19.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 (300) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +3 -1
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/{chunk-ATC4MEVA.js → chunk-2FAJTZSX.js} +2 -2
  5. package/dist/{chunk-W7FNZKX5.js → chunk-2ZNZSNVW.js} +2 -2
  6. package/dist/chunk-35NLDRZC.js +2 -0
  7. package/dist/{chunk-PQD7P6WB.js → chunk-3KQOIXLO.js} +2 -2
  8. package/dist/{chunk-VCRMI56V.js → chunk-3OSRXJKK.js} +2 -2
  9. package/dist/chunk-42QYU6FD.js +3 -0
  10. package/dist/{chunk-BEGHYHOQ.js → chunk-4ZCNFENR.js} +2 -2
  11. package/dist/{chunk-O7NA5FCA.js → chunk-4ZHJAHLE.js} +2 -2
  12. package/dist/chunk-547VY366.js +18 -0
  13. package/dist/{chunk-NX2YAXVQ.js → chunk-54UYBTZW.js} +2 -2
  14. package/dist/{chunk-7ROLM67J.js → chunk-6DHPQS72.js} +2 -2
  15. package/dist/chunk-6SHX42QQ.js +6 -0
  16. package/dist/{chunk-FVLZB54V.js → chunk-7EI4MU5A.js} +2 -2
  17. package/dist/{chunk-J7IMQRCU.js → chunk-7FG5M53V.js} +2 -2
  18. package/dist/chunk-A45K6VUK.js +2 -0
  19. package/dist/{chunk-SXDXR5FH.js → chunk-AEDB4WXE.js} +2 -2
  20. package/dist/{chunk-O5A7BTMA.js → chunk-AERYQJ52.js} +2 -2
  21. package/dist/chunk-AM2LGOEX.js +3 -0
  22. package/dist/{chunk-P6FOIU7O.js → chunk-AWSRND4W.js} +2 -2
  23. package/dist/{chunk-5GAUXLOE.js → chunk-BOXAKNN6.js} +2 -2
  24. package/dist/{chunk-IKMOYFUM.js → chunk-BYPVNKJT.js} +2 -2
  25. package/dist/chunk-DQIJMKNE.js +3 -0
  26. package/dist/{chunk-K65T4TJS.js → chunk-DV6B262O.js} +2 -2
  27. package/dist/chunk-DWN7QDTV.js +26 -0
  28. package/dist/{chunk-G6DDSHMD.js → chunk-EZGT3NJX.js} +2 -2
  29. package/dist/{chunk-MFIA6EIT.js → chunk-EZHARAL4.js} +2 -2
  30. package/dist/chunk-F334Z5UA.js +38 -0
  31. package/dist/{chunk-2A7LUMZP.js → chunk-F5L7WEZF.js} +2 -2
  32. package/dist/{chunk-5CJ6AQN7.js → chunk-FLIF3JWA.js} +2 -2
  33. package/dist/chunk-FMC3BI4I.js +2 -0
  34. package/dist/{chunk-YMFHC5J2.js → chunk-G6QQCX45.js} +2 -2
  35. package/dist/{chunk-Q4GKL4CC.js → chunk-G6RQVDTI.js} +2 -2
  36. package/dist/chunk-GBB2RUDN.js +927 -0
  37. package/dist/{chunk-LL5NQB5V.js → chunk-GJ3FR5WG.js} +2 -2
  38. package/dist/chunk-GMZYT44R.js +5 -0
  39. package/dist/{chunk-OQFPCIXO.js → chunk-GNJHHPZE.js} +2 -2
  40. package/dist/chunk-HOXI4F5I.js +4 -0
  41. package/dist/{chunk-4QBRVI7D.js → chunk-IWK562KR.js} +2 -2
  42. package/dist/chunk-IXORBCMR.js +120 -0
  43. package/dist/chunk-J3U47L4Q.js +2 -0
  44. package/dist/{chunk-K4XL4HOK.js → chunk-J65FQLDL.js} +2 -2
  45. package/dist/{chunk-45QWQSWS.js → chunk-J6BR4MD6.js} +2 -2
  46. package/dist/{chunk-J7WYG63U.js → chunk-JFGUBZWE.js} +2 -2
  47. package/dist/{chunk-BPMBOZAN.js → chunk-KD6TPIXM.js} +2 -2
  48. package/dist/{chunk-3M2UCPFS.js → chunk-KHE7J5ZN.js} +1 -1
  49. package/dist/{chunk-IG6X65MG.js → chunk-KWBA6FDD.js} +2 -2
  50. package/dist/{chunk-KA7RMBVU.js → chunk-LJD7V7UO.js} +2 -2
  51. package/dist/{chunk-ROMKXEUM.js → chunk-MDDF67O2.js} +2 -2
  52. package/dist/{chunk-S22ICAWV.js → chunk-MFBXBLHA.js} +2 -2
  53. package/dist/{chunk-A2GX3PYV.js → chunk-MTFHE7ZO.js} +2 -2
  54. package/dist/chunk-NEG77KKH.js +4 -0
  55. package/dist/{chunk-WA64GKWB.js → chunk-NH7WNNQC.js} +3 -3
  56. package/dist/{chunk-K3UVTL3J.js → chunk-OGHGTD6Z.js} +2 -2
  57. package/dist/chunk-OYYZLJVT.js +2 -0
  58. package/dist/{chunk-DJI446FQ.js → chunk-PAZFJMXB.js} +2 -2
  59. package/dist/{chunk-U244OVE6.js → chunk-PBADFBRR.js} +2 -2
  60. package/dist/{chunk-UWR52GNZ.js → chunk-PKAPOFF5.js} +2 -2
  61. package/dist/{chunk-APCXCRED.js → chunk-PXJIEMND.js} +2 -2
  62. package/dist/{chunk-NJD4C5G5.js → chunk-QB5WSOTY.js} +2 -2
  63. package/dist/{chunk-AY44MGWS.js → chunk-QHOUNTDZ.js} +2 -2
  64. package/dist/chunk-QN67MWDU.js +2 -0
  65. package/dist/{chunk-JLZUM476.js → chunk-QNMOZ3CJ.js} +2 -2
  66. package/dist/{chunk-AWYKDRYV.js → chunk-RIGY5DDE.js} +2 -2
  67. package/dist/chunk-RJLU7IMR.js +10 -0
  68. package/dist/{chunk-N3JH45WR.js → chunk-S65OEY2G.js} +2 -2
  69. package/dist/chunk-SATRCB5O.js +20 -0
  70. package/dist/chunk-T5CSWYAZ.js +2 -0
  71. package/dist/{chunk-H4T2AST4.js → chunk-TC3X33N6.js} +2 -2
  72. package/dist/{chunk-3CJXFMR5.js → chunk-TCVRJ56J.js} +2 -2
  73. package/dist/{chunk-7XP7ZRSI.js → chunk-TDGCALH6.js} +2 -2
  74. package/dist/chunk-TDZXQAH7.js +2 -0
  75. package/dist/{chunk-SUYCF4SX.js → chunk-TOYQTO44.js} +2 -2
  76. package/dist/chunk-UJL3N6TC.js +5 -0
  77. package/dist/chunk-UVMME4FI.js +16 -0
  78. package/dist/{chunk-6JSTKSZH.js → chunk-UXOVHGT6.js} +2 -2
  79. package/dist/chunk-VV5WJLRO.js +67 -0
  80. package/dist/{chunk-4H7T7FIM.js → chunk-WT7TOU2C.js} +2 -2
  81. package/dist/{chunk-4FLF7BHJ.js → chunk-X36LKKVG.js} +2 -2
  82. package/dist/{chunk-C7MBQSIC.js → chunk-X3OOU7CF.js} +2 -2
  83. package/dist/chunk-X65VYV2S.js +2 -0
  84. package/dist/chunk-XBN5VO53.js +2 -0
  85. package/dist/{chunk-TLTLJ4SW.js → chunk-XDSB47KO.js} +2 -2
  86. package/dist/{chunk-4L4X66GE.js → chunk-XDVT7QPG.js} +2 -2
  87. package/dist/chunk-XESK6725.js +2 -0
  88. package/dist/{chunk-OQFA2SUQ.js → chunk-XPYXEEDO.js} +2 -2
  89. package/dist/{chunk-T4P27T6S.js → chunk-XTSVYYAL.js} +2 -2
  90. package/dist/{chunk-27YDE22N.js → chunk-YBAC3RON.js} +2 -2
  91. package/dist/{chunk-2DBY4MO7.js → chunk-YHYTDWFT.js} +2 -2
  92. package/dist/chunk-YYR7ADNB.js +2 -0
  93. package/dist/chunk-ZL5Y23AJ.js +3 -0
  94. package/dist/{chunk-CMLHZWRS.js → chunk-ZNSLF5AC.js} +2 -2
  95. package/dist/chunk-ZXWFN7CK.js +2 -0
  96. package/dist/cli.js +2 -2
  97. package/dist/{command-descriptors-7UUURHWT.js → command-descriptors-SWFWGIFK.js} +173 -167
  98. package/dist/{config-types-70s7NxKB.d.ts → config-types-BA3xLCfG.d.ts} +28 -1
  99. package/dist/{db-BBmJ0v3b.d.ts → db-CzA-9_rL.d.ts} +6 -18
  100. package/dist/direct-navigation-RKMPBXMI.js +3 -0
  101. package/dist/{health-CWpFL_6z.d.ts → health-DYy13GAe.d.ts} +3 -1
  102. package/dist/index.d.ts +23 -41
  103. package/dist/index.js +1 -1
  104. package/dist/postinstall.js +1 -1
  105. package/dist/queries/affected.d.ts +2 -2
  106. package/dist/queries/affected.js +1 -1
  107. package/dist/queries/architecture.d.ts +83 -0
  108. package/dist/queries/architecture.js +2 -0
  109. package/dist/queries/bottlenecks.d.ts +2 -2
  110. package/dist/queries/bottlenecks.js +1 -1
  111. package/dist/queries/by-kind.d.ts +2 -2
  112. package/dist/queries/by-kind.js +1 -1
  113. package/dist/queries/call-graph.d.ts +2 -2
  114. package/dist/queries/call-graph.js +1 -1
  115. package/dist/queries/change-surface.d.ts +2 -2
  116. package/dist/queries/change-surface.js +1 -1
  117. package/dist/queries/cleanup-plan.d.ts +2 -2
  118. package/dist/queries/cleanup-plan.js +1 -1
  119. package/dist/queries/co-change.d.ts +2 -2
  120. package/dist/queries/co-change.js +1 -1
  121. package/dist/queries/code.d.ts +2 -2
  122. package/dist/queries/code.js +1 -1
  123. package/dist/queries/complexity-hotspots.d.ts +2 -2
  124. package/dist/queries/complexity-hotspots.js +1 -1
  125. package/dist/queries/complexity.d.ts +2 -2
  126. package/dist/queries/complexity.js +1 -1
  127. package/dist/queries/convergence.d.ts +2 -2
  128. package/dist/queries/convergence.js +1 -1
  129. package/dist/queries/coupling.d.ts +2 -2
  130. package/dist/queries/coupling.js +1 -1
  131. package/dist/queries/cycles.d.ts +2 -2
  132. package/dist/queries/cycles.js +1 -1
  133. package/dist/queries/dataflow.d.ts +2 -2
  134. package/dist/queries/dataflow.js +1 -1
  135. package/dist/queries/dead.d.ts +2 -2
  136. package/dist/queries/dead.js +1 -1
  137. package/dist/queries/decorative-checkers.d.ts +2 -2
  138. package/dist/queries/decorative-checkers.js +1 -1
  139. package/dist/queries/deep-chains.d.ts +2 -2
  140. package/dist/queries/deep-chains.js +1 -1
  141. package/dist/queries/deps.d.ts +2 -2
  142. package/dist/queries/deps.js +1 -1
  143. package/dist/queries/diff-gate.d.ts +5 -3
  144. package/dist/queries/diff-gate.js +1 -1
  145. package/dist/queries/diff-impact.d.ts +2 -2
  146. package/dist/queries/diff-impact.js +1 -1
  147. package/dist/queries/doc-drift.d.ts +2 -2
  148. package/dist/queries/doc-drift.js +1 -1
  149. package/dist/queries/drift.d.ts +27 -10
  150. package/dist/queries/drift.js +1 -1
  151. package/dist/queries/duplicate-bodies.d.ts +2 -2
  152. package/dist/queries/duplicate-bodies.js +1 -1
  153. package/dist/queries/extract-candidates.d.ts +2 -2
  154. package/dist/queries/extract-candidates.js +1 -1
  155. package/dist/queries/fan.d.ts +2 -2
  156. package/dist/queries/fan.js +1 -1
  157. package/dist/queries/files.d.ts +2 -2
  158. package/dist/queries/health.d.ts +3 -3
  159. package/dist/queries/health.js +1 -1
  160. package/dist/queries/hierarchy.d.ts +2 -2
  161. package/dist/queries/hierarchy.js +1 -1
  162. package/dist/queries/hotspots.d.ts +2 -2
  163. package/dist/queries/hotspots.js +1 -1
  164. package/dist/queries/imports.d.ts +2 -2
  165. package/dist/queries/imports.js +1 -1
  166. package/dist/queries/incomplete-migration.d.ts +2 -2
  167. package/dist/queries/incomplete-migration.js +1 -1
  168. package/dist/queries/index.d.ts +5 -4
  169. package/dist/queries/index.js +1 -1
  170. package/dist/queries/isolated.d.ts +2 -2
  171. package/dist/queries/isolated.js +1 -1
  172. package/dist/queries/locality-candidates.d.ts +2 -2
  173. package/dist/queries/locality-candidates.js +1 -1
  174. package/dist/queries/members.d.ts +2 -2
  175. package/dist/queries/members.js +1 -1
  176. package/dist/queries/methods.d.ts +2 -2
  177. package/dist/queries/methods.js +1 -1
  178. package/dist/queries/not-implemented.d.ts +2 -2
  179. package/dist/queries/not-implemented.js +1 -1
  180. package/dist/queries/outline.d.ts +2 -2
  181. package/dist/queries/outline.js +1 -1
  182. package/dist/queries/passthrough-candidates.d.ts +2 -2
  183. package/dist/queries/passthrough-candidates.js +1 -1
  184. package/dist/queries/plan-context.d.ts +2 -2
  185. package/dist/queries/plan-context.js +1 -1
  186. package/dist/queries/react-component-duplicates.d.ts +2 -2
  187. package/dist/queries/react-component-duplicates.js +1 -1
  188. package/dist/queries/react-hook-candidates.d.ts +2 -2
  189. package/dist/queries/react-hook-candidates.js +1 -1
  190. package/dist/queries/react-large-component-pressure.d.ts +2 -2
  191. package/dist/queries/react-large-component-pressure.js +1 -1
  192. package/dist/queries/recent-duplicates.d.ts +2 -2
  193. package/dist/queries/recent-duplicates.js +1 -1
  194. package/dist/queries/redundant-reexports.d.ts +2 -2
  195. package/dist/queries/redundant-reexports.js +1 -1
  196. package/dist/queries/refs.d.ts +2 -2
  197. package/dist/queries/refs.js +1 -1
  198. package/dist/queries/self-audit.d.ts +2 -2
  199. package/dist/queries/self-audit.js +1 -1
  200. package/dist/queries/similar-chains.d.ts +2 -2
  201. package/dist/queries/similar-chains.js +1 -1
  202. package/dist/queries/similar-files.d.ts +2 -2
  203. package/dist/queries/similar-files.js +1 -1
  204. package/dist/queries/similar-signatures.d.ts +2 -2
  205. package/dist/queries/similar-signatures.js +1 -1
  206. package/dist/queries/similar.d.ts +2 -2
  207. package/dist/queries/similar.js +1 -1
  208. package/dist/queries/slice.d.ts +2 -2
  209. package/dist/queries/slice.js +1 -1
  210. package/dist/queries/stale-abstractions.d.ts +2 -2
  211. package/dist/queries/stale-abstractions.js +1 -1
  212. package/dist/queries/stats.d.ts +2 -2
  213. package/dist/queries/surface.d.ts +2 -2
  214. package/dist/queries/surface.js +1 -1
  215. package/dist/queries/symbols.d.ts +2 -2
  216. package/dist/queries/symbols.js +1 -1
  217. package/dist/queries/system.d.ts +2 -2
  218. package/dist/queries/system.js +1 -1
  219. package/dist/queries/test-quality.d.ts +2 -2
  220. package/dist/queries/test-quality.js +1 -1
  221. package/dist/queries/trace.d.ts +2 -2
  222. package/dist/queries/trace.js +1 -1
  223. package/dist/queries/twin-ab.d.ts +2 -2
  224. package/dist/queries/twin-ab.js +1 -1
  225. package/dist/queries/twin-drift.d.ts +2 -2
  226. package/dist/queries/twin-drift.js +1 -1
  227. package/dist/queries/unused-imports.d.ts +2 -2
  228. package/dist/queries/unused-imports.js +1 -1
  229. package/dist/queries/unused-params.d.ts +2 -2
  230. package/dist/queries/unused-params.js +1 -1
  231. package/dist/queries/vue-component-duplicates.d.ts +2 -2
  232. package/dist/queries/vue-component-duplicates.js +1 -1
  233. package/dist/queries/vue-composable-candidates.d.ts +2 -2
  234. package/dist/queries/vue-composable-candidates.js +1 -1
  235. package/dist/queries/vue-large-view-pressure.d.ts +2 -2
  236. package/dist/queries/vue-large-view-pressure.js +1 -1
  237. package/dist/queries/wrapper-candidates.d.ts +2 -2
  238. package/dist/queries/wrapper-candidates.js +1 -1
  239. package/dist/reindex-worker.js +24 -24
  240. package/dist/reindex.d.ts +12 -10
  241. package/dist/reindex.js +38 -38
  242. package/dist/runtime.d.ts +10 -9
  243. package/dist/runtime.js +2 -1
  244. package/dist/rust-semantic-session-server.js +1 -1
  245. package/dist/{scip-cli-CoMzb7Zu.d.ts → scip-cli-1bVKJgXi.d.ts} +1 -1
  246. package/dist/watch-server.js +7 -6
  247. package/docs/AI_FAILURE_MODES.md +1 -0
  248. package/docs/COMMAND_REFERENCE.md +4 -3
  249. package/docs/DETECTOR_GUIDE.md +5 -3
  250. package/docs/analyzer-inventory.md +16 -6
  251. package/docs/analyzer-validation-ledger.md +12 -1
  252. package/docs/architecture-coherence-vision.md +219 -0
  253. package/package.json +5 -1
  254. package/skills/_shared/SKILL.md +5 -4
  255. package/skills/scip-api-impact/SKILL.md +5 -1
  256. package/skills/scip-claim-audit/SKILL.md +1 -0
  257. package/skills/scip-cleanup-audit/SKILL.md +4 -0
  258. package/skills/scip-concrete-plan/SKILL.md +129 -48
  259. package/skills/scip-conductor/SKILL.md +1 -1
  260. package/skills/scip-debug/SKILL.md +6 -1
  261. package/skills/scip-directory-architecture/SKILL.md +116 -2
  262. package/skills/scip-explore/SKILL.md +2 -1
  263. package/skills/scip-integrity-audit/SKILL.md +17 -0
  264. package/skills/scip-maintainability/SKILL.md +9 -4
  265. package/skills/scip-query/SKILL.md +4 -1
  266. package/skills/scip-root-cause/SKILL.md +150 -0
  267. package/skills/scip-root-cause/agents/openai.yaml +4 -0
  268. package/skills/scip-tla-model-system/SKILL.md +7 -9
  269. package/skills/scip-twin-drift/SKILL.md +1 -1
  270. package/skills/scip-verify/SKILL.md +20 -3
  271. package/dist/chunk-6AITNECC.js +0 -928
  272. package/dist/chunk-7LERNHDG.js +0 -5
  273. package/dist/chunk-7VR5TNOI.js +0 -2
  274. package/dist/chunk-CHJ3QROR.js +0 -2
  275. package/dist/chunk-CVWX24IY.js +0 -2
  276. package/dist/chunk-ELLPMCWA.js +0 -3
  277. package/dist/chunk-IS7DZ7TB.js +0 -2
  278. package/dist/chunk-K53GNKY3.js +0 -2
  279. package/dist/chunk-KJOKTZUE.js +0 -2
  280. package/dist/chunk-KSD6IWF4.js +0 -38
  281. package/dist/chunk-LEKXKHIQ.js +0 -5
  282. package/dist/chunk-LFPQFRCX.js +0 -26
  283. package/dist/chunk-MBVHEPHQ.js +0 -16
  284. package/dist/chunk-NJTIAQY7.js +0 -3
  285. package/dist/chunk-OINSINYW.js +0 -2
  286. package/dist/chunk-QEIGJJBC.js +0 -20
  287. package/dist/chunk-RUQE7DZT.js +0 -2
  288. package/dist/chunk-RUV4KHWA.js +0 -2
  289. package/dist/chunk-SALRDXWM.js +0 -121
  290. package/dist/chunk-SMBIGBGN.js +0 -67
  291. package/dist/chunk-SON6DQNK.js +0 -7
  292. package/dist/chunk-SSGACGAD.js +0 -3
  293. package/dist/chunk-TFWDJDGO.js +0 -2
  294. package/dist/chunk-U4G4UYLB.js +0 -2
  295. package/dist/chunk-WD3PAQJT.js +0 -10
  296. package/dist/chunk-XLJORP6N.js +0 -4
  297. package/dist/chunk-XTF6ELXT.js +0 -3
  298. package/dist/chunk-YYYERNQL.js +0 -18
  299. package/dist/chunk-Z4MCFCGX.js +0 -3
  300. package/dist/direct-navigation-CVCFER5G.js +0 -3
@@ -1,928 +0,0 @@
1
- #!/usr/bin/env node
2
- import{createHash as QR}from"crypto";import{existsSync as ZR,mkdirSync as eI,readFileSync as tI}from"fs";import{dirname as Pc,join as nm}from"path";import Tc from"better-sqlite3";var em=[];function cn(e){e.groups.length>0&&em.push(e)}function kc(e,t){let n=new Set(t.groups);for(let r of em)r.groups.some(i=>n.has(i))&&(t.file!==void 0&&r.clearFile?r.clearFile(e,t.file):r.clearAll(e))}function tm(){let e=new WeakMap;return{cache:e,ensure(t){let n=e.get(t);return n||(n=new Map,e.set(t,n)),n}}}function j(e,t){let{cache:n,ensure:r}=tm(),i={get(o,s,a){let c=r(o);if(c.has(s))return c.get(s);let l=a();return c.set(s,l),l},invalidate(o,s){n.get(o)?.delete(s)},invalidateAll(o){n.delete(o)},size(o){return n.get(o)?.size??0}};return cn({name:e,groups:t.clearGroups,clearAll:o=>i.invalidateAll(o),clearFile:(o,s)=>i.invalidate(o,s)}),i}function K(e,t){let n=new WeakMap,r={get(i,o){let s=n.get(i);if(s)return s.value;let a=o();return n.set(i,{value:a}),a},invalidate(i){n.delete(i)},has(i){return n.has(i)}};return cn({name:e,groups:t.clearGroups,clearAll:i=>r.invalidate(i)}),r}var XR={clearGroups:["whole-project","source-file"]};function ln(e){return Ln(e,XR)}function Ln(e,t){let{cache:n,ensure:r}=tm(),i={get(o,s,a,c){let l=r(o),u=l.get(s);if(u&&u.source===a)return u.value;let d=c();return l.set(s,{source:a,value:d}),d},invalidate(o,s){n.get(o)?.delete(s)},invalidateAll(o){n.delete(o)}};return cn({name:e,groups:t.clearGroups,clearAll:o=>i.invalidateAll(o),clearFile:(o,s)=>i.invalidate(o,s)}),i}var nI="evidence.db";var rI=["source-facts","definition-exclusions","doc-path-tokens","react-component-behavior-profiles"],_c=new Set(rI),iI=25e4,oI=512*1024*1024,sI=5e3,jo=new WeakMap,aI=j("evidence-content-hash",{clearGroups:["whole-project","source-file"]}),cI=j("evidence-project-fingerprint",{clearGroups:["whole-project"]}),nt="evidence-v1",lr="version NOT LIKE 'evidence-%'";function ge(e){return QR("sha256").update(e).digest("hex")}function ae(e,t,n){return aI.get(e,t,()=>ge(n))}function Te(e){return cI.get(e,"current",()=>{try{let t=JSON.parse(tI(nm(Pc(e.config.dbPath),"meta.json"),"utf-8"));if(t.version!==2&&t.version!==3||t.status!=="complete"&&t.status!=="partial"||t.fingerprint===void 0)return null;let n=Array.isArray(t.indexedLanguages)?[...t.indexedLanguages].sort():[];return ge(JSON.stringify({fingerprint:t.fingerprint,indexedLanguages:n,status:t.status}))}catch(t){return ur("project fingerprint unavailable",t),null}})}function ur(e,t){process.env.SCIP_QUERY_DEBUG&&console.error(`evidence-cache: ${e}: ${t instanceof Error?t.message:String(t)}`)}function ht(e){if(jo.has(e))return jo.get(e)??null;let t=null;try{let n=new Tc(nm(Pc(e.config.dbPath),nI));n.pragma("journal_mode = WAL"),n.pragma("busy_timeout = 5000"),n.pragma("synchronous = NORMAL"),n.exec(`
3
- CREATE TABLE IF NOT EXISTS file_evidence (
4
- kind TEXT NOT NULL,
5
- relative_path TEXT NOT NULL,
6
- content_hash TEXT NOT NULL,
7
- version TEXT NOT NULL,
8
- payload TEXT NOT NULL,
9
- PRIMARY KEY (kind, relative_path)
10
- );
11
- CREATE TABLE IF NOT EXISTS project_evidence (
12
- kind TEXT NOT NULL,
13
- cache_key TEXT NOT NULL,
14
- project_fingerprint TEXT NOT NULL,
15
- version TEXT NOT NULL,
16
- payload TEXT NOT NULL,
17
- PRIMARY KEY (kind, cache_key)
18
- );
19
- CREATE TABLE IF NOT EXISTS semantic_callees (
20
- relative_path TEXT NOT NULL,
21
- symbol TEXT NOT NULL,
22
- content_hash TEXT NOT NULL,
23
- deps_digest TEXT NOT NULL,
24
- version TEXT NOT NULL,
25
- payload TEXT NOT NULL,
26
- PRIMARY KEY (relative_path, symbol)
27
- );
28
- CREATE TABLE IF NOT EXISTS semantic_references (
29
- relative_path TEXT NOT NULL,
30
- symbol TEXT NOT NULL,
31
- project_fingerprint TEXT NOT NULL,
32
- version TEXT NOT NULL,
33
- payload TEXT NOT NULL,
34
- PRIMARY KEY (relative_path, symbol)
35
- );
36
- CREATE TABLE IF NOT EXISTS finding_outcome_ledger (
37
- check_name TEXT NOT NULL,
38
- finding_id TEXT NOT NULL,
39
- first_seen INTEGER NOT NULL,
40
- last_seen INTEGER NOT NULL,
41
- times_shown INTEGER NOT NULL,
42
- outcome TEXT NOT NULL,
43
- PRIMARY KEY (check_name, finding_id)
44
- );
45
- `),t={evidence:n,shared:lI(e.config.sharedEvidenceDbPath),readFileEvidence:n.prepare("SELECT payload FROM file_evidence WHERE kind = ? AND relative_path = ? AND content_hash = ? AND version = ?"),readLegacyFileEvidence:n.prepare(`SELECT payload FROM file_evidence
46
- WHERE kind = ? AND relative_path = ? AND content_hash = ? AND ${lr}
47
- ORDER BY version DESC
48
- LIMIT 1`),writeFileEvidence:n.prepare("INSERT OR REPLACE INTO file_evidence (kind, relative_path, content_hash, version, payload) VALUES (?, ?, ?, ?, ?)"),readProjectEvidence:n.prepare("SELECT payload FROM project_evidence WHERE kind = ? AND cache_key = ? AND project_fingerprint = ? AND version = ?"),readLegacyProjectEvidence:n.prepare(`SELECT payload FROM project_evidence
49
- WHERE kind = ? AND cache_key = ? AND project_fingerprint = ? AND ${lr}
50
- ORDER BY version DESC
51
- LIMIT 1`),writeProjectEvidence:n.prepare("INSERT OR REPLACE INTO project_evidence (kind, cache_key, project_fingerprint, version, payload) VALUES (?, ?, ?, ?, ?)"),readCallees:n.prepare(`SELECT payload FROM semantic_callees
52
- WHERE relative_path = ? AND symbol = ? AND content_hash = ? AND deps_digest = ? AND version = ?`),readLegacyCallees:n.prepare(`SELECT payload FROM semantic_callees
53
- WHERE relative_path = ? AND symbol = ? AND content_hash = ? AND deps_digest = ? AND ${lr}
54
- ORDER BY version DESC
55
- LIMIT 1`),readCalleesForFile:n.prepare(`SELECT symbol, payload FROM semantic_callees
56
- WHERE relative_path = ? AND content_hash = ? AND deps_digest = ? AND version = ?`),readLegacyCalleesForFile:n.prepare(`SELECT symbol, payload FROM semantic_callees
57
- WHERE relative_path = ? AND content_hash = ? AND deps_digest = ? AND ${lr}
58
- ORDER BY symbol, version DESC`),writeCallees:n.prepare(`INSERT OR REPLACE INTO semantic_callees
59
- (relative_path, symbol, content_hash, deps_digest, version, payload) VALUES (?, ?, ?, ?, ?, ?)`),dropStaleCallees:n.prepare("DELETE FROM semantic_callees WHERE relative_path = ? AND content_hash != ?"),readReferences:n.prepare(`SELECT payload FROM semantic_references
60
- WHERE relative_path = ? AND symbol = ? AND project_fingerprint = ? AND version = ?`),readLegacyReferences:n.prepare(`SELECT payload FROM semantic_references
61
- WHERE relative_path = ? AND symbol = ? AND project_fingerprint = ? AND ${lr}
62
- ORDER BY version DESC
63
- LIMIT 1`),readReferencesForFile:n.prepare(`SELECT symbol, payload FROM semantic_references
64
- WHERE relative_path = ? AND project_fingerprint = ? AND version = ?`),readLegacyReferencesForFile:n.prepare(`SELECT symbol, payload FROM semantic_references
65
- WHERE relative_path = ? AND project_fingerprint = ? AND ${lr}
66
- ORDER BY symbol, version DESC`),writeReferences:n.prepare(`INSERT OR REPLACE INTO semantic_references
67
- (relative_path, symbol, project_fingerprint, version, payload) VALUES (?, ?, ?, ?, ?)`),dropStaleReferences:n.prepare("DELETE FROM semantic_references WHERE relative_path = ? AND project_fingerprint != ?"),readFindingOutcomeLedger:n.prepare("SELECT check_name, finding_id, first_seen, last_seen, times_shown, outcome FROM finding_outcome_ledger"),deleteFindingOutcomeLedgerForCheck:n.prepare("DELETE FROM finding_outcome_ledger WHERE check_name = ?"),writeFindingOutcomeLedgerRow:n.prepare(`INSERT INTO finding_outcome_ledger
68
- (check_name, finding_id, first_seen, last_seen, times_shown, outcome) VALUES (?, ?, ?, ?, ?, ?)`)}}catch(n){ur("disabled (open failed)",n)}return jo.set(e,t),t}function yt(e,t,n){ur(`disabled (${t})`,n),jo.set(e,null)}function lI(e){if(!e)return null;try{eI(Pc(e),{recursive:!0});let t=new Tc(e);return t.pragma("journal_mode = WAL"),t.pragma("busy_timeout = 250"),t.pragma("synchronous = NORMAL"),t.exec(`
69
- CREATE TABLE IF NOT EXISTS file_evidence (
70
- kind TEXT NOT NULL,
71
- relative_path TEXT NOT NULL,
72
- content_hash TEXT NOT NULL,
73
- version TEXT NOT NULL,
74
- payload TEXT NOT NULL,
75
- last_accessed_at INTEGER NOT NULL,
76
- PRIMARY KEY (kind, relative_path, content_hash, version)
77
- );
78
- `),{evidence:t,readFileEvidence:t.prepare("SELECT payload FROM file_evidence WHERE kind = ? AND relative_path = ? AND content_hash = ? AND version = ?"),writeFileEvidence:t.prepare(`INSERT INTO file_evidence (kind, relative_path, content_hash, version, payload, last_accessed_at)
79
- VALUES (?, ?, ?, ?, ?, ?)
80
- ON CONFLICT(kind, relative_path, content_hash, version)
81
- DO UPDATE SET payload = excluded.payload, last_accessed_at = excluded.last_accessed_at`)}}catch(t){return ur("shared cache disabled (open failed)",t),null}}function Fc(e,t,n){ur(`shared cache disabled (${t})`,n);try{e.shared?.evidence.close()}catch{}e.shared=null}function c5(e,t={}){if(!ZR(e))return null;let n;try{n=new Tc(e),n.pragma("busy_timeout = 50"),n.pragma("wal_checkpoint(TRUNCATE)");let r=n.prepare("SELECT COUNT(*) AS count FROM file_evidence").get().count,i=t.maxRows??iI,o=t.budgetBytes??oI,s=Number(n.pragma("page_size",{simple:!0})),a=Number(n.pragma("page_count",{simple:!0})),c=Number(n.pragma("freelist_count",{simple:!0})),l=Math.max(0,a-c)*s,u=r>0&&l>o?Math.min(r,Math.ceil((l-o)/Math.max(1,l/r))):0,d=Math.max(r-i,u);return d>0&&(n.prepare(`DELETE FROM file_evidence WHERE rowid IN (
82
- SELECT rowid FROM file_evidence ORDER BY last_accessed_at ASC, rowid ASC LIMIT ?
83
- )`).run(d),n.pragma("wal_checkpoint(TRUNCATE)")),{deletedRows:d,remainingRows:r-d}}catch(r){return ur("shared cache maintenance skipped",r),null}finally{try{n?.close()}catch{}}}function rm(e,t,n,r){let i=ht(e);if(!i)return null;try{let o=i.readFileEvidence.get(t,n,r,nt)??i.readLegacyFileEvidence.get(t,n,r);if(o?.payload!==void 0)return o.payload;if(!_c.has(t)||!i.shared)return null;try{return i.shared.readFileEvidence.get(t,n,r,nt)?.payload??null}catch(s){return Fc(i,"file_evidence read",s),null}}catch(o){return yt(e,"file_evidence read",o),null}}function im(e,t,n,r,i){let o=ht(e);if(o)try{if(o.writeFileEvidence.run(t,n,r,nt,i),_c.has(t)&&o.shared)try{o.shared.writeFileEvidence.run(t,n,r,nt,i,Date.now())}catch(s){Fc(o,"file_evidence write",s)}}catch(s){yt(e,"file_evidence write",s)}}function om(e,t){if(t.length===0)return;let n=ht(e);if(n)try{n.evidence.transaction(()=>{for(let i of t)n.writeFileEvidence.run(i.kind,i.relativePath,i.contentHash,nt,i.payload)})();let r=t.filter(i=>_c.has(i.kind));if(r.length>0&&n.shared)try{n.shared.evidence.transaction(()=>{for(let i of r)n.shared.writeFileEvidence.run(i.kind,i.relativePath,i.contentHash,nt,i.payload,Date.now())})()}catch(i){Fc(n,"file_evidence batch write",i)}}catch(r){yt(e,"file_evidence batch write",r)}}function sm(e,t,n,r){let i=ht(e);if(!i)return null;try{return(i.readProjectEvidence.get(t,n,r,nt)??i.readLegacyProjectEvidence.get(t,n,r))?.payload??null}catch(o){return yt(e,"project_evidence read",o),null}}function am(e,t,n,r,i){let o=ht(e);if(o)try{o.writeProjectEvidence.run(t,n,r,nt,i)}catch(s){yt(e,"project_evidence write",s)}}function cm(e,t,n,r){let i=ht(e);if(!i)return new Map;try{let o=i.readCalleesForFile.all(t,n,r,nt),s=i.readLegacyCalleesForFile.all(t,n,r);return um([...s,...o])}catch(o){return yt(e,"semantic_callees bulk read",o),new Map}}function lm(e,t,n){let r=ht(e);if(!r)return new Map;try{let i=r.readReferencesForFile.all(t,n,nt),o=r.readLegacyReferencesForFile.all(t,n);return um([...o,...i])}catch(i){return yt(e,"semantic_references bulk read",i),new Map}}function um(e){let t=new Map;for(let n of e)t.set(n.symbol,n.payload);return t}function Lc(e,t){if(t.length===0)return;let n=ht(e);if(n)try{n.evidence.transaction(()=>{let r=new Set;for(let i of t){let o=`${i.relativePath}\0${i.contentHash}`;r.has(o)||(r.add(o),n.dropStaleCallees.run(i.relativePath,i.contentHash)),n.writeCallees.run(i.relativePath,i.symbol,i.contentHash,i.depsDigest,nt,i.payload)}})()}catch(r){yt(e,"semantic_callees write",r)}}function dm(e,t){if(t.length===0)return;let n=ht(e);if(n)try{n.evidence.transaction(()=>{let r=new Set;for(let i of t){let o=`${i.relativePath}\0${i.projectFingerprint}`;r.has(o)||(r.add(o),n.dropStaleReferences.run(i.relativePath,i.projectFingerprint)),n.writeReferences.run(i.relativePath,i.symbol,i.projectFingerprint,nt,i.payload)}})()}catch(r){yt(e,"semantic_references write",r)}}function fm(e){let t=ht(e);if(!t)return[];try{return t.readFindingOutcomeLedger.all().map(r=>({check:r.check_name,findingId:r.finding_id,firstSeen:r.first_seen,lastSeen:r.last_seen,timesShown:r.times_shown,outcome:r.outcome}))}catch(n){return yt(e,"finding_outcome_ledger read",n),[]}}function mm(e,t){let n=ht(e);if(n)try{let r=new Map;for(let i of t){let o=r.get(i.check)??[];o.push(i),r.set(i.check,o)}n.evidence.transaction(()=>{for(let[i,o]of r){n.deleteFindingOutcomeLedgerForCheck.run(i);let s=[...o].sort((a,c)=>c.lastSeen-a.lastSeen).slice(0,sI);for(let a of s)n.writeFindingOutcomeLedgerRow.run(a.check,a.findingId,a.firstSeen,a.lastSeen,a.timesShown,a.outcome)}})()}catch(r){yt(e,"finding_outcome_ledger write",r)}}import{appendFileSync as uI,mkdirSync as dI}from"fs";import{createHash as fI,randomUUID as mI}from"crypto";import{dirname as pI}from"path";import{performance as dr}from"perf_hooks";var ym="SCIP_QUERY_PROFILE",bm="SCIP_QUERY_PROFILE_OUT",Sm="SCIP_QUERY_PROFILE_COMMAND",Cm="SCIP_QUERY_PROFILE_CACHE_STATE",Nc="SCIP_QUERY_PROFILE_RUN_ID",Ac="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY",Mc="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY_KIND",xm=[ym,bm,Sm,Cm,Nc,Ac,Mc],p5=new Set(xm),pm=new Set,gm=new Map,hm=!1;function H(){let e=process.env[ym];return e==="1"||e==="true"}function gI(){return process.env[bm]}function vm(){return process.env[Sm]}function hI(){return process.env[Cm]}function Rm(){let e=process.env[Nc];if(e)return e;if(!H())return;let t=mI();return process.env[Nc]=t,t}function Im(){return process.env[Ac]}function yI(e){let t=Im();if(t)return t;if(!H())return;let n=Rm();if(!n)return;let r=e.projectFingerprint?"published-project":"run-only",i=oi(["profile-workload-v1",e.toolVersion,e.command,e.projectFingerprint??n]);return process.env[Ac]=i,process.env[Mc]=r,i}function oi(e){return fI("sha256").update(JSON.stringify(e)).digest("hex").slice(0,24)}function wm(){return Object.fromEntries(xm.flatMap(e=>{let t=process.env[e];return t===void 0?[]:[[e,t]]}))}function D(e,t,n){if(!H())return t();let r=dr.now();try{let i=t();return un({type:"span",name:e,durationMs:Math.round(dr.now()-r),ok:!0,...$o(n)??{}}),i}catch(i){throw un({type:"span",name:e,durationMs:Math.round(dr.now()-r),ok:!1,error:i instanceof Error?i.message:String(i),...$o(n)??{}}),i}}async function g5(e,t,n){if(!H())return t();let r=dr.now();try{let i=await t();return un({type:"span",name:e,durationMs:Math.round(dr.now()-r),ok:!0,...$o(n)??{}}),i}catch(i){throw un({type:"span",name:e,durationMs:Math.round(dr.now()-r),ok:!1,error:i instanceof Error?i.message:String(i),...$o(n)??{}}),i}}function un(e,t=gI()){let n=bI(e),r={timestamp:new Date().toISOString(),pid:process.pid,runId:Rm(),command:vm(),cacheState:hI(),...n,...e},i=`${JSON.stringify(r)}
84
- `;if(t)try{let o=pI(t);pm.has(o)||(dI(o,{recursive:!0}),pm.add(o)),uI(t,i);return}catch(o){hm||(hm=!0,process.stderr.write(`[profile] failed to write ${t}: ${o instanceof Error?o.message:String(o)}
85
- `));return}H()&&process.stderr.write(i)}function bI(e){let t=Im()??yI({command:vm()??"unknown",toolVersion:"unknown",projectFingerprint:null});if(!t)return{};let n=process.env[Mc],r=typeof e.name=="string"?e.name:void 0;if(!r)return{workloadIdentity:t,workloadIdentityKind:n};let i=r.split(/[.:]/,1)[0]??r,o=`${t}\0${r}`,s=gm.get(o);return s||(s=oi(["profile-subsystem-v1",t,r]),gm.set(o,s)),{workloadIdentity:t,workloadIdentityKind:n,subsystem:i,subsystemWorkIdentity:s}}function $o(e){return typeof e=="function"?e():e}import{spawnSync as SI}from"child_process";import{createHash as CI}from"crypto";import{existsSync as xI,lstatSync as vI,realpathSync as RI}from"fs";import{dirname as II,isAbsolute as wI,join as DI,resolve as Ho}from"path";var si={run(e,t){let n=Em(e,t);return n.kind==="success"?n.output:void 0},runResult:Em},EI=["rev-parse","--show-toplevel","--absolute-git-dir","--git-common-dir","HEAD","HEAD^{tree}"],Dm=/^[0-9a-f]{40,64}$/;function x5(e,t=si){let n=t.run(e,["rev-parse","--show-toplevel"])?.trim();return n?Ke(n):void 0}function fr(e,t=si){let n=t.runResult(e,EI);if(n.kind==="success"){let r=kI(n.output);if(r)return PI(r,t)}return TI(e,t)}function kI(e){let t=e.split(`
86
- `).map(c=>c.trim());if(t.length!==5)return;let[n,r,i,o,s]=t;if(!n||!r||!i||!o||!s||!Dm.test(o)||!Dm.test(s))return;let a=Ke(n);return{root:a,gitDir:Ke(Bo(a,r)),commonDir:Ke(Bo(a,i)),headCommit:o,treeOid:s}}function PI(e,t){let n=t.run(e.root,["status","--porcelain=v1","-z","--untracked-files=all"]);return n===void 0?void 0:{...km(e.root,e.gitDir),commonDir:e.commonDir,repositoryId:$c("repository",e.commonDir),headCommit:e.headCommit,treeOid:e.treeOid,clean:n.length===0}}function TI(e,t){let n=jc(e,t);if(n.kind!=="worktree")return;let r=n.identity,i=r.projectRoot,o=t.run(i,["rev-parse","--git-common-dir"])?.trim();if(!o)return;let s=Ke(Bo(i,o)),a=Oc(t.run(i,["rev-parse","--verify","HEAD"])),c=Oc(t.run(i,["rev-parse","--verify","HEAD^{tree}"])),l=t.run(i,["status","--porcelain=v1","-z","--untracked-files=all"]);if(l!==void 0)return{...r,commonDir:s,repositoryId:$c("repository",s),headCommit:a,treeOid:c,clean:l.length===0}}function jc(e,t=si){let n=t.runResult(e,["rev-parse","--show-toplevel"]);if(n.kind==="not-repository")return{kind:"non-git"};if(n.kind==="error")return n;let r=n.output.trim();if(!r)return{kind:"error",message:"Git returned an empty worktree root."};let i=Ke(r),o=t.run(i,["rev-parse","--absolute-git-dir"])?.trim();if(!o)return{kind:"error",message:"Git did not return an absolute worktree directory."};let s=Ke(Bo(i,o));return{kind:"worktree",identity:km(i,s)}}function km(e,t){return{projectRoot:e,gitDir:t,worktreeId:$c("worktree",`${e}\0${t}`)}}function Pm(e,t=si){let n=t.run(e,["worktree","list","--porcelain","-z"]);return n===void 0?[]:_I(n)}function _I(e){let t=[],n;for(let r of e.split("\0")){if(r===""){n&&t.push(n),n=void 0;continue}let i=r.indexOf(" "),o=i<0?r:r.slice(0,i),s=i<0?"":r.slice(i+1);if(o==="worktree"){n&&t.push(n),n={path:Ke(s),detached:!1,bare:!1,prunable:!1,locked:!1};continue}n&&(o==="HEAD"?n.head=s:o==="branch"?n.branch=s:o==="detached"?n.detached=!0:o==="bare"?n.bare=!0:o==="prunable"?n.prunable=!0:o==="locked"&&(n.locked=!0))}return n&&t.push(n),t}function v5(e,t,n=si){return Oc(n.run(e,t))}function Bo(e,t){return wI(t)?t:Ho(e,t)}function Ke(e){try{return RI(e)}catch{return Ho(e)}}function $c(e,t){return CI("sha256").update(`${e}\0${t}`).digest("hex").slice(0,24)}function Oc(e){return e?.trim()||void 0}function Em(e,t){let n=SI("git",["-C",e,...t],{encoding:"utf-8",env:{...process.env,LC_ALL:"C"},maxBuffer:52428800,stdio:["ignore","pipe","pipe"]});if(n.status===0)return{kind:"success",output:n.stdout.trimEnd()};let i=(typeof n.stderr=="string"?n.stderr.trim():"")||n.error?.message||`git exited with status ${n.status??"unknown"}`,o=n.error?.code;return(/not a git repository/i.test(i)||o==="ENOENT"&&xI(Ho(e)))&&!FI(e)?{kind:"not-repository"}:{kind:"error",message:i}}function FI(e){if(process.env.GIT_DIR||process.env.GIT_COMMON_DIR)return!0;let t=Ho(e);for(;;){try{return vI(DI(t,".git")),!0}catch(r){let i=r.code;if(i!=="ENOENT"&&i!=="ENOTDIR")return!0}let n=II(t);if(n===t)return!1;t=n}}import{spawn as OI}from"child_process";import{closeSync as jI,existsSync as $I,mkdirSync as BI,openSync as HI,readFileSync as Gc,rmSync as ai,writeFileSync as UI}from"fs";import{dirname as WI,join as Bc,resolve as Go}from"path";import{fileURLToPath as GI}from"url";import{mkdirSync as LI,renameSync as NI,writeFileSync as AI}from"fs";import{dirname as MI}from"path";function he(e,t,n={}){LI(MI(e),{recursive:!0});let r=`${e}.${process.pid}.${Date.now()}.tmp`,i=JSON.stringify(t,null,n.spacing);AI(r,n.trailingNewline?`${i}
87
- `:i),NI(r,e)}function Ae(e){try{return process.kill(e,0),!0}catch(t){return typeof t=="object"&&t!==null&&"code"in t&&t.code==="EPERM"}}var zI=4,zc=5e3,VI="watch.lock",qI="watch-state.json",KI="watch-activity.json",Tm=5e3,JI=2e3,Lm=10,YI=new Set(["bench","config-validate","hook-context","hook-stop","init","reindex","setup","setup-agent","setup-ci","setup-hooks","uninstall","watch","work-audit"]);function A5(e){let t=e.classification;if(t.kind!=="live")return;let{state:n}=t;return n.watcher.state==="idle"&&n.lastError===void 0?n.indexGeneration:void 0}function XI(e,t=process.env){return t.SCIP_QUERY_SKIP_WATCH_SERVICE!=="1"&&!e.startsWith("__")&&!YI.has(e)}function M5(e){let t=e.env??process.env;if(t.SCIP_QUERY_SKIP_WATCH_SERVICE==="1")return{kind:"skipped",reason:"environment"};if(!XI(e.commandName,t))return{kind:"skipped",reason:"excluded-command"};if(e.config.watch?.enabled!==!0)return{kind:"skipped",reason:"disabled"};try{let n=QI({projectRoot:e.projectRoot,cacheDir:e.cacheDir,cliVersion:e.cliVersion,gitContext:e.gitContext,runtime:e.runtime});return{kind:n.disposition,state:n.state}}catch(n){return{kind:"failed",message:n instanceof Error?n.message:String(n)}}}function zo(e){return{lockPath:Bc(e,VI),statePath:Bc(e,qI),activityPath:Bc(e,KI)}}function Nm(e,t,n){let r=Ke(Go(e));if(n&&Ke(n.projectRoot)===r)return{projectRoot:r,worktreeKind:"git",worktreeId:n.worktreeId,cliVersion:t};let i=jc(r);if(i.kind==="error")throw new Error(`Could not establish Git worktree identity for ${r}: ${i.message}`);return i.kind==="non-git"?{projectRoot:r,worktreeKind:"non-git",cliVersion:t}:{projectRoot:r,worktreeKind:"git",worktreeId:i.identity.worktreeId,cliVersion:t}}function O5(e){return Wo(e,Nm(e.projectRoot,e.cliVersion,e.gitContext))}function Wo(e,t){let n=e.runtime??Vc,r=zo(e.cacheDir),i=li(r.statePath),o=mr(r.lockPath);return{identity:t,classification:tw(i,t,n.now(),n.isProcessAlive),lock:o,lockIsLive:o!==null&&n.isProcessAlive(o.pid),paths:r}}function QI(e){let t=e.runtime??Vc,n=Nm(e.projectRoot,e.cliVersion,e.gitContext),r=Wo(e,n),i=Uc("ensure",r.classification);if(i.kind==="reuse")return Uo(r.paths.activityPath,t.now()),{disposition:"reused",state:i.state};if(i.kind==="replace")Wc(i.state.pid,e,t),ci(r.paths,i.state.pid,t);else if(i.kind==="start"){if(r.lockIsLive){let a=_m(e,n,t,Math.min(e.startupTimeoutMs??1e3,1e3));if(a)return Uo(r.paths.activityPath,t.now()),{disposition:"reused",state:a};throw new Error(`scip-query watch is already running for ${Go(e.projectRoot)} (pid ${r.lock?.pid}; lock: ${r.paths.lockPath}) without compatible daemon state. Stop the foreground watcher before starting the service.`)}r.classification.kind==="stale"&&ci(r.paths,r.classification.state.pid,t)}else throw new Error(`Unexpected ensure action: ${i.kind}`);if(r=Wo(e,n),i=Uc("ensure",r.classification),i.kind==="reuse")return Uo(r.paths.activityPath,t.now()),{disposition:"reused",state:i.state};let o=e.serverPath??GI(new URL("./watch-server.js",import.meta.url));t.spawnServer(o,n.projectRoot,e.cliVersion,e.watchOverrides??{});let s=_m(e,n,t,e.startupTimeoutMs??Tm);if(!s)throw new Error(`scip-query watch service did not become ready within ${e.startupTimeoutMs??Tm}ms.`);return Uo(r.paths.activityPath,t.now()),{disposition:"started",state:s}}function j5(e){let t=e.runtime??Vc,n=zo(e.cacheDir),r=li(n.statePath),i=r?t.isProcessAlive(r.pid)?{kind:"live",state:r}:{kind:"stale",state:r,reason:"dead-process"}:{kind:"stopped"},o=Uc("stop",i);if(o.kind==="signal-stop")return Wc(o.state.pid,e,t),ci(n,o.state.pid,t),{disposition:"stopped",pid:o.state.pid};if(o.kind==="clean-stale")return ci(n,o.state.pid,t),{disposition:"stopped",pid:o.state.pid};let s=mr(n.lockPath);return o.kind==="already-stopped"&&s&&t.isProcessAlive(s.pid)?(Wc(s.pid,e,t),ci(n,s.pid,t),{disposition:"stopped",pid:s.pid}):{disposition:"already-stopped"}}function li(e){try{return ew(JSON.parse(Gc(e,"utf8")))}catch{return null}}function Uo(e,t=Date.now()){let n=ZI(e);he(e,{version:1,at:new Date(t).toISOString(),...n?.refreshRequestedAtMs===void 0?{}:{refreshRequestedAt:new Date(n.refreshRequestedAtMs).toISOString(),...n.refreshDetail?{refreshDetail:n.refreshDetail}:{}}})}function $5(e,t,n=Date.now()){he(e,{version:1,at:new Date(n).toISOString(),refreshRequestedAt:new Date(n).toISOString(),refreshDetail:t})}function ZI(e){try{let t=JSON.parse(Gc(e,"utf8"));return t.version!==1||!Be(t.at)||t.refreshRequestedAt!==void 0&&!Be(t.refreshRequestedAt)||t.refreshDetail!==void 0&&typeof t.refreshDetail!="string"?null:{atMs:Date.parse(t.at),...t.refreshRequestedAt===void 0?{}:{refreshRequestedAtMs:Date.parse(t.refreshRequestedAt)},...t.refreshDetail===void 0?{}:{refreshDetail:t.refreshDetail}}}catch{return null}}function B5(e,t,n={}){let r=n.pid??process.pid,i=n.isProcessAlive??Ae,o=()=>{},s=mr(e);if(s&&i(s.pid))return{acquired:!1,lockPath:e,message:Fm(e,t,s),release:o};s&&ai(e,{force:!0}),BI(WI(e),{recursive:!0});let a;try{a=HI(e,"wx")}catch(u){if(nw(u)==="EEXIST")return{acquired:!1,lockPath:e,message:Fm(e,t,mr(e)),release:o};throw u}let c={version:1,pid:r,projectRoot:Go(t),startedAt:(n.now??(()=>new Date))().toISOString()};UI(a,`${JSON.stringify(c)}
88
- `);let l=!1;return{acquired:!0,lockPath:e,message:"",release:()=>{if(l)return;l=!0,jI(a);let u=mr(e);u?.pid===c.pid&&u.startedAt===c.startedAt&&ai(e,{force:!0})}}}function mr(e){try{let t=JSON.parse(Gc(e,"utf-8"));return t.version!==1||typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0||typeof t.projectRoot!="string"||!Be(t.startedAt)?null:t}catch{return null}}function ew(e){if(!e||typeof e!="object")return null;let t=e;return t.version!==1||typeof t.protocolVersion!="number"||typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0||typeof t.projectRoot!="string"||t.worktreeId!==void 0&&(typeof t.worktreeId!="string"||t.worktreeId.length===0)||typeof t.cliVersion!="string"||!Be(t.startedAt)||!Be(t.heartbeatAt)||!Be(t.lastActivityAt)||!rw(t.watcher)||t.idleDeadlineAt!==void 0&&!Be(t.idleDeadlineAt)||t.indexGeneration!==void 0&&!/^[a-f0-9]{64}$/.test(t.indexGeneration)||t.lastError!==void 0&&!iw(t.lastError)||t.lastRefresh!==void 0&&!ow(t.lastRefresh)||t.typescriptSemantic!==void 0&&!sw(t.typescriptSemantic)||t.typescriptIndex!==void 0&&!aw(t.typescriptIndex)?null:t}function tw(e,t,n,r){if(!e)return{kind:"stopped"};if(e.protocolVersion!==zI)return{kind:"incompatible",state:e,reason:"protocol"};if(e.projectRoot!==t.projectRoot)return{kind:"incompatible",state:e,reason:"project"};let i=t.worktreeKind==="git"?t.worktreeId:void 0;if(e.worktreeId!==i)return{kind:"incompatible",state:e,reason:"worktree"};if(e.cliVersion!==t.cliVersion)return{kind:"incompatible",state:e,reason:"cli-version"};if(!r(e.pid))return{kind:"stale",state:e,reason:"dead-process"};let o=Date.parse(e.heartbeatAt);return n-o>zc?{kind:"stale",state:e,reason:"old-heartbeat"}:{kind:"live",state:e}}function Uc(e,t){switch(e){case"status":return{kind:"report",classification:t};case"ensure":switch(t.kind){case"stopped":return{kind:"start"};case"stale":return t.reason==="old-heartbeat"?{kind:"replace",state:t.state}:{kind:"start"};case"live":return{kind:"reuse",state:t.state};case"incompatible":return{kind:"replace",state:t.state};default:return Hc(t)}case"stop":switch(t.kind){case"stopped":return{kind:"already-stopped"};case"stale":return t.reason==="old-heartbeat"?{kind:"signal-stop",state:t.state}:{kind:"clean-stale",state:t.state};case"live":case"incompatible":return{kind:"signal-stop",state:t.state};default:return Hc(t)}default:return Hc(e)}}function _m(e,t,n,r){let i=n.now()+r;for(;n.now()<=i;){let o=Wo(e,t).classification;if(o.kind==="live")return o.state;n.sleep(Lm)}return null}function Wc(e,t,n){if(!n.isProcessAlive(e))return;n.signalProcess(e);let r=t.stopTimeoutMs??JI,i=n.now()+r;for(;n.now()<=i;){if(!n.isProcessAlive(e))return;n.sleep(Lm)}throw new Error(`scip-query watch service pid ${e} did not stop within ${r}ms.`)}function ci(e,t,n){ai(e.statePath,{force:!0}),ai(e.activityPath,{force:!0}),mr(e.lockPath)?.pid===t&&!n.isProcessAlive(t)&&ai(e.lockPath,{force:!0})}function Fm(e,t,n){return`error: scip-query watch is already running for ${Go(t)}${n?` (pid ${n.pid}, started ${n.startedAt}; lock: ${e})`:` (lock: ${e})`}. Stop that watcher before starting another.`}function nw(e){return typeof e=="object"&&e&&"code"in e?e.code:void 0}var Vc={now:Date.now,isProcessAlive:Ae,spawnServer(e,t,n,r){if(!$I(e))throw new Error(`Watch service helper was not found at ${e}. Run npm run build first.`);OI(process.execPath,[e,t,n,JSON.stringify(r)],{detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"}}).unref()},signalProcess(e){process.kill(e,"SIGTERM")},sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)}};function Be(e){return typeof e=="string"&&Number.isFinite(Date.parse(e))}function rw(e){if(!e||typeof e!="object"||!("state"in e))return!1;let t=e;switch(t.state){case"idle":return!0;case"waiting":return rt(t.changedFiles)&&rt(t.reindexAt);case"indexing":return rt(t.startedAt);case"cooldown":return rt(t.until)&&typeof t.dirty=="boolean";default:return!1}}function iw(e){if(!e||typeof e!="object")return!1;let t=e;return Be(t.at)&&typeof t.message=="string"}function ow(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.trigger?.kind=="string"&&typeof t.result=="string"&&Be(t.startedAt)&&Be(t.completedAt)&&rt(t.durationMs)}function sw(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.protocolVersion=="number"&&(t.state==="idle"||t.state==="ready"||t.state==="unavailable"||t.state==="error")&&rt(t.requests)&&rt(t.sessionsCreated)&&rt(t.sessionsReused)&&rt(t.sessionsRefreshed)&&rt(t.sessionsReplaced)&&rt(t.projectsCreated)&&(t.lastRequestAt===void 0||Be(t.lastRequestAt))&&(t.lastError===void 0||typeof t.lastError=="string")&&(t.busyUntil===void 0||Be(t.busyUntil))}function aw(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.protocolVersion=="number"&&(t.state==="idle"||t.state==="ready"||t.state==="unavailable"||t.state==="error")&&Nn(t.requests)&&Nn(t.sessionsCreated)&&Nn(t.sessionsReplaced)&&Nn(t.initializations)&&Nn(t.programUpdates)&&Nn(t.documentsEmitted)&&Nn(t.documentsRemoved)&&(t.lastRequestAt===void 0||Be(t.lastRequestAt))&&(t.lastDurationMs===void 0||rt(t.lastDurationMs)&&t.lastDurationMs>=0)&&(t.lastError===void 0||typeof t.lastError=="string")&&(t.busyUntil===void 0||Be(t.busyUntil))}function rt(e){return typeof e=="number"&&Number.isFinite(e)}function Nn(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Hc(e){throw new Error(`Unhandled watch service value: ${JSON.stringify(e)}`)}var cw={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function ye(e){if(e.startsWith("local "))return{kind:"local",id:e.slice(6),raw:e};let t=e.split(" ");if(t.length<4)return{scheme:t[0]??"",manager:t[1]??"",packageName:t[2]??"",version:"",descriptors:[],raw:e};let n=t[0],r=t[1],i=e.slice(n.length+1+r.length+1),o;if(i.startsWith("`")){let l=i.indexOf("`",1);l===-1?(o=i.slice(1),i=""):(o=i.slice(1,l),i=i.slice(l+2))}else{let l=i.indexOf(" ");l===-1?(o=i,i=""):(o=i.slice(0,l),i=i.slice(l+1))}let s,a=i.indexOf(" ");a===-1?(s=i,i=""):(s=i.slice(0,a),i=i.slice(a+1));let c=lw(i);return{scheme:n,manager:r,packageName:o,version:s,descriptors:c,raw:e}}function Rt(e){let t=ye(e);if("kind"in t)return null;for(let n=t.descriptors.length-2;n>=0;n--){let r=t.descriptors[n];if(r?.suffix==="type")return r.name}return null}function lw(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="["){let o=e.indexOf("]",n+1);if(o===-1){t.push({name:e.slice(n+1),suffix:"type-param"});break}t.push({name:e.slice(n+1,o),suffix:"type-param"}),n=o+1;continue}if(e[n]==="("&&(t.length===0||n===0||Am(e[n-1]))){let o=e.indexOf(")",n+1);if(o!==-1&&e[o+1]!=="."){t.push({name:e.slice(n+1,o),suffix:"parameter"}),n=o+1;continue}}let r;if(e[n]==="`"){let o=e.indexOf("`",n+1);if(o===-1){r=e.slice(n+1),t.push({name:r,suffix:"term"});break}r=e.slice(n+1,o),n=o+1}else{let o=n;for(;n<e.length&&!Am(e[n]);)n++;r=e.slice(o,n)}if(n>=e.length){r&&t.push({name:r,suffix:"term"});break}let i=e[n];if(i==="("){let o=e.indexOf(")",n+1);o!==-1&&e[o+1]==="."?(t.push({name:r,suffix:"method"}),n=o+2):o!==-1?(t.push({name:r,suffix:"method"}),n=o+1):(t.push({name:r,suffix:"term"}),n++)}else{let o=cw[i];o&&t.push({name:r,suffix:o}),n+=1}}return t}function Am(e){return e==="/"||e==="#"||e==="."||e==="("||e==="["||e===":"||e==="!"}function w(e){let t=ye(e);if("kind"in t&&t.kind==="local")return`local:${t.id}`;let n=t;if(n.descriptors.length===0)return n.raw;let r=[];for(let i of n.descriptors){let o=uw(i);o&&r.push(o)}return r.join(":")}function uw(e){let t=e.suffix==="namespace"?dw(e.name):e.name;return t?e.suffix==="method"?`${t}()`:t:""}function dw(e){return e.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/,"").replace(/\.(py|pyi)$/,"").replace(/\.(rs)$/,"").replace(/\.(java|scala|kt|kts)$/,"").replace(/\.(rb)$/,"").replace(/\.(go)$/,"").replace(/\.(cs|vb)$/,"").replace(/\.(dart)$/,"").replace(/\.(php)$/,"").replace(/\.(c|cc|cpp|cxx|h|hpp)$/,"")}function T(e){let t=ye(e);if("kind"in t&&t.kind==="local")return t.id;let n=t;return n.descriptors.length===0?"":n.descriptors[n.descriptors.length-1].name}function le(e){let t=ye(e);if("kind"in t&&t.kind==="local")return null;let n=t;return n.descriptors[n.descriptors.length-1]?.suffix??null}function ce(e){return e.endsWith("().")||le(e)==="method"}function Z(e){let t=le(e);return t==="method"?!0:t!=="term"?!1:e.endsWith("().")?!0:e.startsWith("rust-analyzer ")&&e.includes("#")?!1:e.startsWith("scip-typescript ")?!/#[A-Za-z0-9_$]+\.$/.test(e):!0}function dn(e){return le(e)==="namespace"}var fw=/^rust-analyzer\b.*[\s/]impl#\[[^\]]+\]\[[^\]]+\]/;function Re(e){return fw.test(e)}var mw=new Set(["test","tests","_tests"]);function pr(e){let t=ye(e);if("kind"in t)return!1;for(let n=0;n<t.descriptors.length-1;n+=1){let r=t.descriptors[n];if(r?.suffix==="namespace"&&r.name&&mw.has(r.name))return!0}return!1}function Mm(e,t){let n=ye(e),r=ye(t);if("kind"in n||"kind"in r)return!1;let i=n.descriptors,o=r.descriptors;if(o.length!==i.length+1)return!1;for(let s=0;s<i.length;s++){let a=i[s],c=o[s];if(a.name!==c.name||a.suffix!==c.suffix)return!1}return!0}function Om(e,t){let n=ye(e),r=ye(t);if("kind"in n||"kind"in r)return!1;let i=n.descriptors,o=r.descriptors;if(o.length<=i.length)return!1;for(let s=0;s<i.length;s++){let a=i[s],c=o[s];if(a.name!==c.name||a.suffix!==c.suffix)return!1}return!0}import{extname as jm}from"path";var pw={".rs":"rust",".ts":"typescript",".mts":"typescript",".cts":"typescript",".tsx":"tsx",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".pyi":"python",".java":"java",".kt":"kotlin",".kts":"kotlin",".scala":"scala",".sc":"scala",".rb":"ruby",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".hxx":"cpp",".cs":"csharp",".php":"php",".vb":"vb",".clj":"clojure",".cljs":"clojure",".cljc":"clojure"};function M(e){return pw[jm(e).toLowerCase()]??null}function Ot(e){return jm(e).toLowerCase()===".vue"}import{createRequire as gw}from"module";var Me=gw(import.meta.url),ui=null,qc=!1;function $m(){if(qc)return null;if(ui)return ui;try{return ui=Me("tree-sitter"),ui}catch{return qc=!0,null}}function V5(e){if(e==="clojure")return"reader";let t=$m();if(!t)return"unavailable";let n=Bm(e);if(!n)return"unavailable";try{return new t().setLanguage(n),"ast"}catch{return gr.add(e),"unavailable"}}var Kc=new Map,gr=new Set;function Bm(e){if(gr.has(e))return null;let t=Kc.get(e);if(t)return t;let n;try{switch(e){case"rust":n=Me("tree-sitter-rust");break;case"typescript":n=Me("tree-sitter-typescript").typescript;break;case"tsx":n=Me("tree-sitter-typescript").tsx;break;case"javascript":n=Me("tree-sitter-javascript");break;case"python":n=Me("tree-sitter-python");break;case"java":n=Me("tree-sitter-java");break;case"kotlin":n=Me("tree-sitter-kotlin");break;case"scala":n=Me("tree-sitter-scala");break;case"ruby":n=Me("tree-sitter-ruby");break;case"c":n=Me("tree-sitter-c");break;case"cpp":n=Me("tree-sitter-cpp");break;case"csharp":n=Me("tree-sitter-c-sharp");break;case"php":n=Me("tree-sitter-php").php;break;case"vb":{let r=Me("tree-sitter-vb-dotnet");n=r.language??r;break}case"clojure":return gr.add(e),null}}catch{return gr.add(e),null}return Kc.set(e,n),n}var Jc=new Map;function q5(){ui=null,qc=!1,Kc.clear(),gr.clear(),Jc.clear(),bw.clear()}function hw(e){let t=Jc.get(e);if(t)return t;let n=Bm(e);if(!n)return null;let r=$m();if(!r)return null;let i=new r;try{i.setLanguage(n)}catch{return gr.add(e),null}return Jc.set(e,i),i}function yw(e,t){return e.parse(r=>r>=t.length?null:t.slice(r,Math.min(t.length,r+16384)))}function di(e,t){let n=hw(e);if(!n)return null;try{return yw(n,t)}catch{return null}}var bw=new Map;import{readFileSync as Sw}from"fs";import{join as Cw}from"path";var xw=j("source-text",{clearGroups:["whole-project","source-file"]}),vw=j("source-lines",{clearGroups:["whole-project","source-file"]});function P(e,t){let n=t.replace(/\\/g,"/");return xw.get(e,n,()=>{let r=Cw(e.config.projectRoot,n);try{return Sw(r,"utf-8")}catch(i){if(Rw(i))return"";throw i}})}function Rw(e){return typeof e=="object"&&e!==null&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function Ce(e,t){let n=t.replace(/\\/g,"/");return vw.get(e,n,()=>{let r=P(e,n);return r?r.split(`
89
- `):[]})}var Iw=/^\s*(?:\/\/|#|\/\*+|\*)\s*scip-query[\s:-]*ignore(?:[\s:-]+(dead(?:-code)?|stale|wrapper|passthrough|drift|extract|similar|twin))?\b/i;function fi(e){let t=Iw.exec(e);return t?t[1]??"":null}function Vo(e,t,n){return Um(e,t,n).length>0}function Hm(e,t,n,r){let i=r.toLowerCase();return Um(e,t,n).some(o=>o.toLowerCase()===i)}function Um(e,t,n){if(n<=0)return[];let r=Ce(e,t);if(r.length===0)return[];let i=[];for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(r[o]??"").trim();if(s==="")continue;let a=fi(s);if(a!==null){i.push(a);continue}if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return i}return i}import{posix as Yc}from"path";import{parse as ww}from"@vue/compiler-sfc";var Dw=ln("vue-sfc-units");function hr(e,t){let n=zm(t),r=P(e,n);return Dw.get(e,n,r,()=>Xc(e,n,r))}function zm(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Ew(e){let t=e?.toLowerCase();return!t||t==="js"||t==="javascript"||t==="jsx"?"javascript":t==="ts"||t==="typescript"?"typescript":t==="tsx"?"tsx":null}function An(e){return!e||e.body.length===0?0:e.body.split(`
90
- `).length}function Xc(e,t,n){let r={relativePath:t,template:null,scripts:[],styles:[],customBlocks:[],errors:[]};if(!n)return r;let i;try{i=ww(n,{filename:t})}catch(s){return r.errors.push(Gm(s)),r}r.errors.push(...i.errors.map(Gm));let{descriptor:o}=i;return o.template&&(r.template=qo(e,t,"template",o.template)),o.script&&r.scripts.push(Wm(e,t,o.script,!1)),o.scriptSetup&&r.scripts.push(Wm(e,t,o.scriptSetup,!0)),r.styles=o.styles.map(s=>qo(e,t,"style",s)),r.customBlocks=o.customBlocks.map(s=>qo(e,t,"custom",s)),r.errors.push(...[r.template,...r.scripts,...r.styles,...r.customBlocks].flatMap(s=>s?.errors??[])),r}function Wm(e,t,n,r){let i=qo(e,t,"script",n);return{...i,kind:"script",setup:r,astLanguage:Ew(i.lang)}}function qo(e,t,n,r){let i=Pw(r.attrs),o=typeof i.lang=="string"?i.lang:null,s=typeof i.src=="string"?i.src:typeof r.src=="string"?r.src:void 0;if(s){let c=kw(t,s);if(!c)return{kind:n,ownerPath:t,sourcePath:t,external:!0,src:s,attrs:i,lang:o,body:"",startLine:0,endLine:0,errors:[`Could not resolve Vue ${n} block source: ${s}`]};let l=P(e,c),u=l?Math.max(0,l.split(`
91
- `).length-1):0;return{kind:n,ownerPath:t,sourcePath:c,external:!0,src:s,attrs:i,lang:o,body:l,startLine:0,endLine:u,errors:l?[]:[`Vue ${n} block source not found: ${c}`]}}let a=Math.max(0,r.loc.start.line-1);return{kind:n,ownerPath:t,sourcePath:t,external:!1,attrs:i,lang:o,body:r.content,startLine:a,endLine:Math.max(a,r.loc.end.line-1),errors:[]}}function kw(e,t){let n=t.split(/[?#]/,1)[0];if(!n||n.startsWith("/")||n.includes("://"))return null;let r=zm(Yc.normalize(Yc.join(Yc.dirname(e),n)));return r===".."||r.startsWith("../")?null:r}function Pw(e){return{...e}}function Gm(e){return e instanceof Error?e.message:String(e)}function Ko(e,t,n){let i=Xc(e,t,n).scripts.filter(s=>s.astLanguage&&s.body.length>0),o=i[0]?.astLanguage;return o?{body:i.map(s=>`${`
92
- `.repeat(s.startLine)}${s.body}`).join(`
93
- `),startLine:0,language:o}:null}var Vm=Ln("ast-trees",{clearGroups:["whole-project","source-file"]});function V(e,t){if(Ot(t))return Tw(e,t);let n=M(t);if(!n)return null;let r=P(e,t);return r?Vm.get(e,t,r,()=>di(n,r)):null}function Tw(e,t){let n=P(e,t);return n?Vm.get(e,t,n,()=>{let r=Ko(e,t,n);if(!r)return null;let i=`
94
- `.repeat(r.startLine)+r.body;return di(r.language,i)}):null}function yr(e,t){let n=_w(e,t);if(!n)return null;let r=Mn(n);return r?{calleeLeaf:r,memberAccess:Fw(n),line:e.startPosition.row}:null}function _w(e,t){if(t==="rust")return e.type==="call_expression"?e.childForFieldName("function")??e.namedChild(0):e.type==="macro_invocation"?e.childForFieldName("macro")??e.namedChild(0):null;if(t==="python")return e.type!=="call"?null:e.childForFieldName("function")??e.namedChild(0);if(t==="typescript"||t==="tsx"||t==="javascript"){if(e.type==="call_expression")return e.childForFieldName("function")??e.namedChild(0);if(e.type==="new_expression")return e.childForFieldName("constructor")??e.namedChild(0)}return null}function Fw(e){switch(e.type){case"field_expression":case"member_expression":case"attribute":return!0;default:return!1}}function Mn(e){switch(e.type){case"identifier":case"type_identifier":case"field_identifier":case"property_identifier":case"shorthand_property_identifier":return e.text;case"field_expression":case"member_expression":case"attribute":{let t=e.namedChild(e.namedChildCount-1);return t?Mn(t):null}case"generic_function":{let t=e.childForFieldName("function")??e.namedChild(0);return t?Mn(t):null}case"scoped_identifier":{let t=e.childForFieldName("name")??e.namedChild(e.namedChildCount-1);return t?Mn(t):null}case"super":case"self":case"this":return null;default:return null}}var Lw=[He("source-facts",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/source/source-facts.ts"}),He("file-definitions",{dependsOn:["content-hash","project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","contentHash","projectFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/symbols/definition-catalog.ts"}),He("definition-exclusions",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/analysis/framework-patterns.ts"}),He("doc-path-tokens",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-products.test.ts",owner:"tests/storage/evidence-cache.test.ts"}),He("doc-path-evidence",{dependsOn:["content-hash","git-history","git-head","tool-version"],keyParts:["kind","relativePath","contentHash","trackedFiles","historyWindow","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/queries/cleanup/doc-drift.ts"}),He("source-imports",{dependsOn:["content-hash","import-resolution-fingerprint","config","tool-version"],keyParts:["kind","relativePath","contentHash","importResolutionFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/language-parsers/index.ts"}),He("source-reexports",{dependsOn:["content-hash","import-resolution-fingerprint","config","tool-version"],keyParts:["kind","relativePath","contentHash","importResolutionFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/language-parsers/index.ts"}),He("source-fingerprints",{dependsOn:["content-hash","project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","contentHash","projectFingerprint","payloadVersion"],stalenessTest:"tests/symbols/definition-catalog.test.ts",owner:"src/queries/cleanup/similar.ts"}),He("consumer-file-usage",{dependsOn:["content-hash","project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","contentHash","projectFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/queries/internal/consumer-evidence.ts"}),He("react-component-behavior-profiles",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/source/react-profile.ts"}),He("git-file-adds",{dependsOn:["git-head","git-history","tool-version"],keyParts:["kind","cacheKey","head","historyWindow","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/analysis/git-history.ts"}),He("typescript-reference-fragments",{dependsOn:["content-hash","transitive-deps-digest","config","tool-version"],keyParts:["kind","relativePath","semanticIdentity","payloadVersion"],stalenessTest:"tests/semantic/typescript/typescript-reference-fragments.test.ts",owner:"src/semantic/typescript/reference-fragment-shadow.ts"}),He("typescript-import-usage",{dependsOn:["content-hash","transitive-deps-digest","config","tool-version"],keyParts:["kind","relativePath","semanticIdentity","payloadVersion"],stalenessTest:"tests/semantic/typescript/typescript-semantic-provider.test.ts",owner:"src/semantic/shared-primitives.ts"}),He("typescript-signatures",{dependsOn:["content-hash","transitive-deps-digest","config","tool-version"],keyParts:["kind","relativePath","semanticIdentity","payloadVersion"],stalenessTest:"tests/semantic/typescript/typescript-semantic-provider.test.ts",owner:"src/semantic/shared-primitives.ts"}),Jo("file-dependency-graph",{dependsOn:["project-fingerprint","indexed-language-set","import-resolution-fingerprint","tool-version"],keyParts:["kind","scope","projectFingerprint","payloadVersion"],stalenessTest:"tests/symbols/file-dep-graph.test.ts",owner:"src/symbols/graph/file-dep-graph.ts"}),Jo("semantic-import-usage",{dependsOn:["project-fingerprint","indexed-language-set","import-resolution-fingerprint","tool-version"],keyParts:["kind","relativePath","projectFingerprint","language","semanticEngine","payloadVersion"],stalenessTest:"tests/semantic/rust/rust-semantic-cache-gate.test.ts",owner:"src/semantic/shared-primitives.ts"}),Jo("semantic-signatures",{dependsOn:["project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","symbol","projectFingerprint","language","semanticEngine","payloadVersion"],stalenessTest:"tests/semantic/rust/rust-semantic-cache-gate.test.ts",owner:"src/semantic/shared-primitives.ts"}),Jo("health-semantic-prewarm",{dependsOn:["project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","scope","cliVersion","projectFingerprint","payloadVersion"],stalenessTest:"tests/runtime/cli-support.test.ts",owner:"src/runtime/cli-support.ts"})];function re(e){let t=new Map;return{kind:e.kind,read(n,r,i){let o=!1,s=0,a;if(H()){let c=Te(n);if(c){let l=`${c}\0${r}\0${i}`;a=t.get(l),a||(a=oi(["evidence-product-file-read-v1",e.kind,c,r,i]),t.set(l,a))}}return D("evidence-product.file.read",()=>{let c=rm(n,e.kind,r,i);if(c===null)return null;s=c.length;try{let l=e.deserialize(c);return o=l!==null,l}catch{return null}},()=>({...a?{workIdentity:a,workOutcome:"computed"}:{},scope:"file",kind:e.kind,available:!0,hit:o,payloadBytes:s}))},write(n,r,i,o){im(n,e.kind,r,i,e.serialize(o))},writeBatch(n,r){om(n,r.map(i=>({kind:e.kind,relativePath:i.relativePath,contentHash:i.contentHash,payload:e.serialize(i.value)})))}}}function On(e){let t=new Map;return{kind:e.kind,read(n,r,i){let o=!1,s=0,a;if(H()){let c=`${i}\0${r}`;a=t.get(c),a||(a=oi(["evidence-product-project-read-v1",e.kind,i,r]),t.set(c,a))}return D("evidence-product.project.read",()=>{let c=sm(n,e.kind,r,i);if(c===null)return null;s=c.length;try{let l=e.deserialize(c);return o=l!==null,l}catch{return null}},()=>({...a?{workIdentity:a,workOutcome:"computed"}:{},scope:"project",kind:e.kind,available:!0,hit:o,payloadBytes:s}))},write(n,r,i,o){am(n,e.kind,r,i,e.serialize(o))}}}function q(e){let t=Lw.find(n=>n.kind===e);if(!t)throw new Error(`missing evidence product manifest entry for ${e}`);return t.invalidation}function He(e,t){return{scope:"file",kind:e,invalidation:{scope:"file",...t}}}function Jo(e,t){return{scope:"project",kind:e,invalidation:{scope:"project",...t}}}function mi(e){return e.type==="comment"||e.type==="line_comment"||e.type==="block_comment"}var Nw=new Set(["function_declaration","method_definition","method_signature","function_signature"]);function Yo(e,t){let n=Mw(e,t);if(n)return{name:n.name,startLine:n.definitionNode.startPosition.row,endLine:n.definitionNode.endPosition.row,paramCount:Jm(n.functionNode),params:qm(n.functionNode),paramsEndLine:Km(n.functionNode),isLiteralPassthrough:Ym(n.functionNode,t)};if(!Aw(e.type,t))return null;let r=e.childForFieldName("name")??e.namedChildren.find(i=>i.type==="identifier"||i.type==="property_identifier");return r?{name:r.text,startLine:e.startPosition.row,endLine:e.endPosition.row,paramCount:Jm(e),params:qm(e),paramsEndLine:Km(e),isLiteralPassthrough:Ym(e,t)}:null}function Xm(e){return e.namedChildren.find(t=>t.type==="parameters"||t.type==="formal_parameters")}function qm(e){let t=Xm(e);if(!t)return[];let n=[];for(let r of t.namedChildren){if(mi(r))continue;if(r.type==="identifier"){n.push({name:r.text,simple:!0});continue}let i=r.namedChildren.some(a=>a.type.endsWith("_modifier"))||/^\s*(?:public|private|protected|readonly|override)\b/.test(r.text),o=r.childForFieldName("pattern");if(!i&&o&&o.type==="identifier"){n.push({name:o.text,simple:!0});continue}let s=r.namedChildren.find(a=>a.type==="identifier");n.push({name:o?.type==="identifier"?o.text:s?.text??"",simple:!1})}return n}function Km(e){let t=Xm(e);return t?t.endPosition.row:e.startPosition.row}function Aw(e,t){return t==="rust"?e==="function_item"||e==="function_signature_item":t==="python"?e==="function_definition":t==="typescript"||t==="tsx"||t==="javascript"?Nw.has(e):!1}function Mw(e,t){if(t!=="typescript"&&t!=="tsx"&&t!=="javascript")return null;if(e.type==="variable_declarator"){let n=e.childForFieldName("name")??e.namedChild(0),r=e.childForFieldName("value")??e.namedChild(1);return!n||!r||r.type!=="arrow_function"&&r.type!=="function_expression"?null:{name:n.text,definitionNode:e,functionNode:r}}if(e.type==="public_field_definition"){let n=e.childForFieldName("name")??e.namedChild(0),r=e.childForFieldName("value")??e.namedChild(1);return!n||!r||r.type!=="arrow_function"&&r.type!=="function_expression"?null:{name:n.text,definitionNode:e,functionNode:r}}return null}function Jm(e){let t=e.namedChildren.find(r=>r.type==="parameters"||r.type==="formal_parameters");if(!t)return 0;let n=0;for(let r of t.namedChildren)mi(r)||(n+=1);return n}function Ym(e,t){let n=e.namedChildren.find(d=>d.type==="block"||d.type==="statement_block");if(!n)return!1;let r=n.namedChildren.filter(d=>!mi(d));if(r.length!==1)return!1;let i=r[0],o=null;if(i.type==="return_statement"||i.type==="expression_statement"?o=i.namedChild(0)??null:t==="rust"&&(i.type==="call_expression"||i.type==="macro_invocation")&&(o=i),!o)return!1;let s=t==="python"?"call":"call_expression";if(o.type!==s)return!1;let a=o.namedChildren.find(d=>d.type==="arguments"||d.type==="argument_list");if(!a)return!1;let c=a.namedChildren.filter(d=>!mi(d)),l=e.namedChildren.find(d=>d.type==="parameters"||d.type==="formal_parameters");if(!l)return!1;let u=[];for(let d of l.namedChildren){if(d.type==="identifier"){u.push(d.text);continue}let f=d.namedChildren.find(m=>m.type==="identifier");f&&u.push(f.text)}if(c.length!==u.length)return!1;for(let d=0;d<u.length;d+=1){let f=c[d];if(f.type!=="identifier"||f.text!==u[d])return!1}return!0}var Ow=new Set(["identifier","type_identifier","field_identifier"]),jw=new Set(["identifier"]),$w=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]),Bw=new Set(["rust","python"]),Hw=/\{([^{}]*)\}/g,Uw=/\b([A-Za-z_][\w]*)\b/g;function Qm(e,t){return Ww(t).has(e.type)}function Zm(e,t){return Bw.has(t)&&e.type==="string_content"}function Qc(e){let t=0;for(let r of e.values()){let i=r[r.length-1];i!==void 0&&i>t&&(t=i)}let n=new Array(t+1);for(let r=0;r<=t;r+=1)n[r]=new Set;for(let[r,i]of e)for(let o of i)n[o].add(r);return n}function Ww(e){return e==="rust"?Ow:e==="python"?jw:$w}function ep(e,t){let n=e.startPosition.row;for(let r of e.text.matchAll(Hw)){let i=r[1]??"";for(let o of i.matchAll(Uw))o[1]&&t(o[1],n)}}var Gw=[/\bdefault\s*=\s*"([^"]+)"/g,/\bwith\s*=\s*"([^"]+)"/g,/\bserialize_with\s*=\s*"([^"]+)"/g,/\bdeserialize_with\s*=\s*"([^"]+)"/g,/\bskip_serializing_if\s*=\s*"([^"]+)"/g,/\bgetter\s*=\s*"([^"]+)"/g,/\brename_all_with\s*=\s*"([^"]+)"/g,/\bschema_with\s*=\s*"([^"]+)"/g],zw=/^#!?\[\s*serde\s*\(/,Vw=/^#!?\[\s*schemars\s*\(/,qw=/^#!?\[\s*validate\s*\(/,Kw=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function tp(e,t,n){if(t!=="typescript"&&t!=="tsx"&&t!=="javascript"||e.type!=="call_expression")return;let r=e.childForFieldName("function")??e.namedChild(0);if(!r)return;let i=Mn(r);if(!i||!Kw.has(i))return;let o=e.namedChildren.find(c=>c.type==="arguments");if(!o)return;let s=o.namedChild(0);if(!s||s.type!=="string")return;let a=s.namedChildren.find(c=>c.type==="string_fragment");a&&n.add(a.text)}function np(e,t){let n=zw.test(e),r=Vw.test(e),i=qw.test(e);if(!(!n&&!r&&!i))for(let o of Gw){o.lastIndex=0;let s;for(;(s=o.exec(e))!==null;){let a=s[1],c=a.split("::").pop()??a;c==="is_none"&&/\bOption\b/.test(a)||c==="is_empty"&&/\b(String|Vec|HashMap|BTreeMap|HashSet|BTreeSet)\b/.test(a)||c&&t.add(c)}}}function rp(e,t){let n=new Map,r=(s,a)=>{if(s===a)return;let c=n.get(s);c||(c=new Set,n.set(s,c)),c.add(a)},i=t==="python"?new Set(["identifier"]):new Set(["type_identifier"]),o=(s,a)=>{let c=l=>{i.has(l.type)&&l.text!==a&&r(l.text,a);for(let u of l.children)c(u)};for(let l of s.children)c(l)};if(t==="rust")for(let s of e.rootNode.descendantsOfType(["struct_item","enum_item","union_item","type_item"])){let a=s.namedChildren.find(l=>l.type==="type_identifier")?.text;if(!a)continue;let c=s.namedChildren.find(l=>l.type==="field_declaration_list"||l.type==="enum_variant_list"||l.type==="ordered_field_declaration_list");c&&o(c,a),s.type==="type_item"&&o(s,a)}else if(t==="python")for(let s of e.rootNode.descendantsOfType("class_definition")){let a=s.namedChildren.find(u=>u.type==="identifier")?.text;if(!a)continue;let c=s.childForFieldName("superclasses");c&&o(c,a);let l=s.namedChildren.find(u=>u.type==="block");if(l)for(let u of l.descendantsOfType("type"))for(let d of u.descendantsOfType("identifier"))d.text!==a&&r(d.text,a)}else for(let s of e.rootNode.descendantsOfType(["interface_declaration","type_alias_declaration","class_declaration"])){let a=s.namedChildren.find(c=>c.type==="type_identifier")?.text;a&&o(s,a)}return n}var Jw=new Map([["defn","function"],["defn-","function"],["defmacro","macro"],["defmacro-","macro"],["defmethod","method"]]),Zc=new Set(["catch","comment","def","defprotocol","defrecord","deftype","defmethod","defmacro","defmacro-","defn","defn-","do","doseq","dotimes","fn","for","if","let","loop","ns","quote","recur","throw","try","extend-protocol","extend-type","when","when-let","when-not"]);function ip(e){let t=[],n=[],r=[],i=new Map,o=[],s=0,a=0,c=(l,u)=>{let d=i.get(l);if(!d){i.set(l,[u]);return}d[d.length-1]!==u&&d.push(u)};for(;a<e.length;){let l=e[a];if(l===`
95
- `){s+=1,a+=1;continue}if(/\s|,/.test(l)){a+=1;continue}if(l===";"){a=Qo(e,a);continue}if(l==='"'){let p=gi(e,a,s);s=p.line,a=p.index;continue}if(l==="("||l==="["||l==="{"){o.push({kind:l,startLine:s,endLine:s,headTokens:[],tokens:[],children:[]}),a+=1;continue}if(l===")"||l==="]"||l==="}"){let p=o.pop();p&&(p.endLine=s,Yw(p,{callables:t,callSites:n,clojureMembers:r,recordIdentifier:c}),o[o.length-1]?.children.push(p)),a+=1;continue}if(el(l)){a+=1;continue}let u=s,d=a;for(;a<e.length&&!tl(e[a]);)a+=1;let f=e.slice(d,a);if(!f)continue;let m={text:f,line:u};Xw(o[o.length-1],m),c(it(f),u)}return{language:"clojure",callables:t,callSites:n,clojureMembers:r,typeContainerMap:new Map,identifierLineMap:i,identifiersByLine:nD(i),fileIdentifiers:new Set(i.keys()),rustAttrReferencedNames:new Set,crossLanguageDispatchNames:new Set}}function Yw(e,t){if(e.kind!=="("||e.headTokens.length===0)return;let n=e.headTokens[0],r=it(n.text),i=Jw.get(n.text);if(i){let s=e.headTokens[1];if(s){let a=it(s.text);t.recordIdentifier(a,s.line),t.callables.push({name:a,startLine:e.startLine,endLine:e.endLine,paramCount:0,params:[],paramsEndLine:s.line,isLiteralPassthrough:!1,clojureKind:i})}}if(Qw(e,t),!r||Zc.has(n.text)||Zc.has(r)||r.startsWith(":"))return;let o=tD(n.text);t.callSites.push({calleeLeaf:o.leaf,calleeQualifier:o.qualifier,calleeText:o.text,memberAccess:!1,line:n.line})}function Xw(e,t){e&&(e.headTokens.length<2&&e.headTokens.push(t),e.tokens.length<200&&e.tokens.push(t))}function Qw(e,t){let n=it(e.tokens[0]?.text??"");if(n==="defprotocol"){let r=it(e.tokens[1]?.text??"");if(!r)return;for(let i of Xo(e))pi(t,r,"protocol",i,"protocol-method");return}if(n==="defrecord"||n==="deftype"){let r=it(e.tokens[1]?.text??"");if(!r)return;let i=n==="defrecord"?"record":"type",o=n==="defrecord"?"record-method":"type-method";for(let s of Xo(e))pi(t,r,i,s,o);return}if(n==="extend-type"){let r=it(e.tokens[1]?.text??"");if(!r)return;for(let i of Xo(e))pi(t,r,"extension",i,"extension-method");return}if(n==="extend-protocol"){let r=it(e.tokens[1]?.text??"");for(let i of Xo(e)){r&&pi(t,r,"extension",i,"extension-method");let o=eD(e,i.startLine);o&&o!==r&&pi(t,o,"extension",i,"extension-method")}}}function Xo(e){return e.children.filter(Zw)}function Zw(e){if(e.kind!=="(")return!1;let t=it(e.tokens[0]?.text??"");return!!(t&&!Zc.has(t)&&!t.startsWith(":"))}function pi(e,t,n,r,i){let o=r.tokens[0],s=it(o?.text??"");!o||!s||(e.recordIdentifier(s,o.line),e.clojureMembers.push({ownerName:t,ownerKind:n,memberName:s,memberKind:i,startLine:r.startLine,endLine:r.endLine}))}function eD(e,t){let n=null;for(let r=2;r<e.tokens.length;r+=1){let i=e.tokens[r];if(i.line>t)break;let o=it(i.text);o&&!o.startsWith(":")&&(n=o)}return n}function it(e){return e.replace(/^#?['`~@]+/,"").split("/").pop()?.replace(/^\./,"")??""}function tD(e){let t=e.replace(/^#?['`~@]+/,""),n=t.lastIndexOf("/"),r=it(t);if(n<=0)return{leaf:r,text:t};let i=t.slice(0,n);return{leaf:r,qualifier:i,text:t}}function Qo(e,t){let n=t;for(;n<e.length&&e[n]!==`
96
- `;)n+=1;return n}function gi(e,t,n){let r=t+1,i=n;for(;r<e.length;){let o=e[r];if(o==="\\"){r+=2;continue}if(o===`
97
- `&&(i+=1),r+=1,o==='"')break}return{index:r,line:i}}function el(e){return e==="'"||e==="`"||e==="~"||e==="@"||e==="^"||e==="#"}function tl(e){return/\s|,/.test(e)||e==="("||e===")"||e==="["||e==="]"||e==="{"||e==="}"||e==='"'||e===";"}function nD(e){let t=[];for(let[n,r]of e)for(let i of r)t[i]??=new Set,t[i].add(n);return t}var op=3,rD=Ln("source-facts",{clearGroups:["whole-project","source-file"]}),nl=re({kind:"source-facts",invalidation:q("source-facts"),serialize:sD,deserialize:aD});function W(e,t){return rl(e,t).facts}function rl(e,t){let n=P(e,t);if(!n)return{facts:null};let r=iD(e,t,n);return r?rD.get(e,t,n,()=>oD(e,t,r,n)):{facts:null}}function iD(e,t,n){return Ot(t)?Ko(e,t,n)?.language??null:M(t)}function oD(e,t,n,r){let i=ae(e,t,r),o=nl.read(e,t,i);if(o&&o.language===n)return{facts:o};if(n==="clojure"){let c=ip(r);return nl.write(e,t,i,c),{facts:c}}let s=V(e,t);if(!s)return{facts:null,unavailable:{language:n,reason:"parser-unavailable"}};let a=lD(s,n);return nl.write(e,t,i,a),{facts:a}}function sD(e){let t={version:op,language:e.language,callables:e.callables,callSites:e.callSites,clojureMembers:e.clojureMembers,typeContainerMap:[...e.typeContainerMap.entries()].map(([n,r])=>[n,[...r]]),identifierLineMap:[...e.identifierLineMap.entries()],rustAttrReferencedNames:[...e.rustAttrReferencedNames],crossLanguageDispatchNames:[...e.crossLanguageDispatchNames]};return JSON.stringify(t)}function aD(e){try{let t=JSON.parse(e);if(t.version!==op||t.language==="clojure"&&(t.clojureMembers===void 0||t.callSites.some(r=>r.calleeText===void 0)))return null;let n=new Map(t.identifierLineMap);return{language:t.language,callables:t.callables,callSites:t.callSites,clojureMembers:t.clojureMembers??[],typeContainerMap:new Map(t.typeContainerMap.map(([r,i])=>[r,new Set(i)])),identifierLineMap:n,identifiersByLine:Qc(n),fileIdentifiers:new Set(n.keys()),rustAttrReferencedNames:new Set(t.rustAttrReferencedNames),crossLanguageDispatchNames:new Set(t.crossLanguageDispatchNames)}}catch{return null}}function il(e,t,n,r){let i=W(e,t);return i?cD(i,n,r)?.isLiteralPassthrough??!0:!0}function hi(e,t){return t.relativePath.includes(".clj-kondo/hooks/")?!0:W(e,t.relativePath)?.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine)?.clojureKind==="macro"}function cD(e,t,n){return e.callables.find(r=>r.startLine===t&&r.endLine===n)??null}function lD(e,t){let n=[],r=[],i=new Set,o=new Set,s=new Map,a=(l,u)=>{let d=s.get(l);if(!d){s.set(l,[u]);return}d[d.length-1]!==u&&d.push(u)},c=l=>{let u=Yo(l,t);u&&n.push(u);let d=yr(l,t);d&&r.push(d),tp(l,t,o),t==="rust"&&(l.type==="attribute_item"||l.type==="inner_attribute_item")&&np(l.text,i),Qm(l,t)&&a(l.text,l.startPosition.row),Zm(l,t)&&ep(l,a);for(let f of l.children)c(f)};return c(e.rootNode),{language:t,callables:n,callSites:r,clojureMembers:[],typeContainerMap:rp(e,t),identifierLineMap:s,identifiersByLine:Qc(s),fileIdentifiers:new Set(s.keys()),rustAttrReferencedNames:i,crossLanguageDispatchNames:o}}var sp=new Set(["rust","typescript","tsx","javascript","python","clojure"]);function ol(e,t){let n=W(e,t);return!n||!sp.has(n.language)?null:n.callables.map(r=>({name:r.name,startLine:r.startLine,endLine:r.endLine}))}function fn(e,t){let n=W(e,t);return!n||!sp.has(n.language)?null:n.callSites}function sl(e,t){return W(e,t)?.typeContainerMap??new Map}import{ElementTypes as dD,NodeTypes as al,parse as fD}from"@vue/compiler-dom";import{parse as VX}from"@vue/compiler-sfc";var uD=new Set(["children","className","data","e","err","error","ev","event","false","id","idx","index","item","key","null","props","res","result","state","style","true","undefined","val","value"]);function Zo(e){return e.length<=2||uD.has(e)}function es(e,t){return e.split(t).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}var mD=ln("vue-template-facts"),pD=new Set(["component","keep-alive","slot","suspense","teleport","template","transition","transition-group"]),gD=new Set(["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","label","legend","li","link","main","map","mark","menu","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","search","section","select","slot","small","source","span","strong","style","sub","summary","sup","svg","table","tbody","td","template","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr"]),hD=new Set(["div","span","template"]),yD=new Set(["as","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","false","finally","for","from","function","if","import","in","instanceof","let","new","null","of","return","super","switch","this","throw","true","try","typeof","undefined","var","void","while","with","yield"]);function ts(e,t){let n=t.replace(/\\/g,"/"),r=P(e,n);return mD.get(e,n,r,()=>bD(n,hr(e,n).template))}function bD(e,t){let n={relativePath:e,template:t?{startLine:t.startLine,endLine:t.endLine}:null,componentTags:[],nativeTags:[],builtinTags:[],props:[],events:[],directives:[],slots:[],expressionIdentifiers:[],structuralTokens:[]};if(!t)return n;let r;try{r=fD(t.body,{comments:!1})}catch{return n}let i=new Set,o=s=>{s.trim()&&i.add(s)};return cp(r.children,t.startLine,n,o),n.structuralTokens=[...i].sort(),n}function cp(e,t,n,r){for(let i of e)if(i.type===al.ELEMENT)SD(i,t,n,r),cp(i.children,t,n,r);else if(i.type===al.INTERPOLATION){r("interpolation");let o=cl(i.content);o&&lp(o,t,i.loc.start.line,n,r)}}function SD(e,t,n,r){let i=DD(e.tag),o={tag:e.tag,normalized:i,kind:wD(e),startLine:br(t,e.loc.start.line),endLine:br(t,e.loc.end.line)};o.kind==="component"?(n.componentTags.push(o),r(`component:${i}`)):o.kind==="builtin"?(n.builtinTags.push(o),r(`builtin:${i}`)):(n.nativeTags.push(o),hD.has(e.tag)||r(`native:${e.tag}`));for(let s of e.props)CD(s,t,n,r)}function CD(e,t,n,r){if(e.type===al.ATTRIBUTE){let a=e.value?.content??null,c=ap("prop",e.name,a,t,e.loc.start.line,e.loc.end.line);n.props.push(c),r(`prop:${e.name}`);return}let i=vD(e),o=cl(e.exp),s=ap(xD(e.name),i,o,t,e.loc.start.line,e.loc.end.line);switch(s.kind){case"prop":n.props.push(s),r(`prop:${i}`);break;case"event":n.events.push(s),r(`event:${i}`);break;case"slot":n.slots.push(s),r(`slot:${i}`);break;case"directive":n.directives.push(s),r(`directive:${i}`);break}o&&lp(o,t,e.loc.start.line,n,r)}function ap(e,t,n,r,i,o){return{kind:e,name:t,value:n,startLine:br(r,i),endLine:br(r,o)}}function xD(e){switch(e){case"bind":case"model":return"prop";case"on":return"event";case"slot":return"slot";default:return"directive"}}function vD(e){let t=cl(e.arg);return t||e.name}function cl(e){if(!e)return null;let t=("content"in e&&typeof e.content=="string"?e.content:e.loc.source).trim();return t||null}function lp(e,t,n,r,i){for(let o of RD(e)){let s={name:o,startLine:br(t,n),endLine:br(t,n)};r.expressionIdentifiers.push(s),i(`id:${o}`)}}function RD(e){let t=new Set,n=ID(e),r=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,i;for(;i=r.exec(n);){let o=i[0];yD.has(o)||Zo(o)||/^[A-Z_]+$/.test(o)||t.add(o)}return[...t].sort()}function ID(e){return e.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/.*$/gm," ").replace(/`(?:\\[\s\S]|\$\{([^}]*)\}|[^`\\])*`/g,(t,n)=>n??" ").replace(/'(?:\\[\s\S]|[^'\\])*'/g," ").replace(/"(?:\\[\s\S]|[^"\\])*"/g," ")}function wD(e){let t=e.tag;return e.tagType===dD.COMPONENT?"component":pD.has(t)?"builtin":gD.has(t)?"native":/^[A-Z]/.test(t)||t.includes("-")?"component":"native"}function DD(e){return es(e,/[-_:]/)}function br(e,t){return e+Math.max(0,t-1)}import{createRequire as jD}from"module";import{existsSync as Bn}from"fs";import{basename as up,dirname as Ye,extname as jt,join as ot,relative as jn,resolve as Ie,sep as $D}from"path";function N(e,t={}){let n=t.scope?"AND relative_path LIKE ?":"",r=t.like?"AND relative_path LIKE ?":"",i=[...t.scope?[`%${t.scope}%`]:[],...t.like?[t.like]:[]],o=e.all(`SELECT relative_path
98
- FROM documents
99
- WHERE 1 = 1
100
- ${e.pathExclusionsFor("documents")}
101
- ${n}
102
- ${r}
103
- ORDER BY relative_path`,...i).map(a=>a.relative_path),s=t.extensions?o.filter(a=>t.extensions.some(c=>a.toLowerCase().endsWith(c.toLowerCase()))):o;return t.includeIgnored===!1?s.filter(a=>!e.isIgnored(a)):s}import{isAbsolute as ED,relative as kD}from"path";function mn(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function ee(e){return e.replace(/\\/g,"/")}function Je(e,t){return mn(e)===mn(t)}function tQ(e,t){let n=kD(e,t);return n===""||!n.startsWith("..")&&!ED(n)}import{existsSync as ul,readFileSync as dl,readdirSync as PD,statSync as TD}from"fs";import{join as Sr,relative as _D}from"path";function Cr(e){let t=FD(e)??MD(e);if(!t||t.length===0)return[];let n=[],r=new Set;for(let i of t)for(let o of fl(e,i)){if(r.has(o))continue;r.add(o);let s=OD(e,o);s&&n.push(s)}return n}function FD(e){let t=Sr(e,"pnpm-workspace.yaml");if(!ul(t))return null;try{return LD(dl(t,"utf8"))}catch{return null}}function LD(e){let t=[],n=!1;for(let r of e.split(/\r?\n/)){let i=ND(r);if(!n){/^packages\s*:\s*$/.test(i.trim())&&(n=!0);continue}let o=/^\s+-\s*(.+)$/.exec(i);if(o){let s=AD(o[1].trim());s&&t.push(s);continue}if(i.trim()!=="")break}return t}function ND(e){let t=e.indexOf("#");return t===-1?e:e.slice(0,t)}function AD(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function MD(e){let t=Sr(e,"package.json");if(!ul(t))return null;try{let n=JSON.parse(dl(t,"utf8"));return n.workspaces?Array.isArray(n.workspaces)?n.workspaces:n.workspaces.packages??[]:null}catch{return null}}function fl(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=Sr(e,t);return ll(s)?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=Sr(e,r||".");return ll(o)?PD(o).map(s=>Sr(o,s,i)).filter(ll):[]}function ll(e){try{return TD(e).isDirectory()}catch{return!1}}function OD(e,t){let n=Sr(t,"package.json");if(!ul(n))return null;try{let r=JSON.parse(dl(n,"utf8"));return typeof r.name!="string"||r.name.length===0?null:{name:r.name,relativeDir:_D(e,t).replace(/\\/g,"/"),exports:r.exports}}catch{return null}}var BD=K("indexed-paths",{clearGroups:[]}),HD=K("indexed-path-digest",{clearGroups:[]}),UD=j("tsconfig-alias-config",{clearGroups:["whole-project"]}),WD=j("tsconfig-alias-config-for-dir",{clearGroups:["whole-project"]}),GD=jD(import.meta.url),yi;function zD(){if(yi!==void 0)return yi;try{yi=GD("typescript")}catch{yi=null}return yi}var VD=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"],qD=K("workspace-packages",{clearGroups:["whole-project"]}),$n=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],ns=[".py",".pyi"],Xe=[".java",".scala",".kt",".kts"],rs=[".rs"],is=[".rb"],os=[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],pn=[".cs",".vb"],ss=[".dart"],Hn=[".php"],xr=[".clj",".cljs",".cljc"],KD=new Set($n),ml=new Set(ns),dp=new Set(Xe),pl=new Set(rs),gl=new Set(is),fp=new Set(os),mp=new Set(pn),hl=new Set(ss),pp=new Set(Hn),gp=new Set(xr),JD=[{extensions:$n,lookup:KD},{extensions:ns,lookup:ml},{extensions:Xe,lookup:dp},{extensions:rs,lookup:pl},{extensions:is,lookup:gl},{extensions:os,lookup:fp},{extensions:pn,lookup:mp},{extensions:ss,lookup:hl},{extensions:Hn,lookup:pp},{extensions:xr,lookup:gp}];function $t(e,t){return t.has(jt(e).toLowerCase())}function YD(e){return $t(e,ml)}function XD(e){return $t(e,dp)}function QD(e){return $t(e,pl)}function ZD(e){return $t(e,gl)}function eE(e){return $t(e,fp)}function tE(e){return $t(e,mp)}function hp(e){return jt(e).toLowerCase()===".vb"}function nE(e){return $t(e,hl)}function rE(e){return $t(e,pp)}function iE(e){return $t(e,gp)}function yl(e){let t=jt(e).toLowerCase();for(let n of JD)if(n.lookup.has(t))return n.extensions;return $n}function oE(e){return XD(e)||tE(e)||rE(e)}function Qe(e,t,n){return YD(t)?vr(e,t,n):QD(t)?Bt(e,t,n):ZD(t)?as(e,t,n):eE(t)?cs(e,t,n):oE(t)?be(e,n.replace(/\\/g,"."),yl(t)):nE(t)?ls(e,t,n):iE(t)?bl(e,n):sE(e,t,n)}function sE(e,t,n){if(!n.startsWith(".")&&!n.startsWith("/"))return aE(e,t,n)??lE(e,n);let r=Ye(ot(e.config.projectRoot,t)),i=Ie(r,n),o=Ht(e);for(let s of Cl(i)){let a=ee(jn(e.config.projectRoot,s));if(o.has(a)||Bn(s))return a}return ee(jn(e.config.projectRoot,i))}function aE(e,t,n){let r=gE(e,t);if(!r)return null;let i=Ht(e);for(let o of cE(r,n)){let s=Ie(r.baseUrl,o);for(let a of Cl(s)){let c=ee(jn(e.config.projectRoot,a));if(i.has(c)||Bn(a))return c}}return null}function cE(e,t){let n=[];for(let[r,i]of Object.entries(e.paths)){let o=r.indexOf("*");if(o===-1){if(t!==r)continue;n.push(...i);continue}let s=r.slice(0,o),a=r.slice(o+1);if(!t.startsWith(s)||!t.endsWith(a)||t.length<s.length+a.length)continue;let c=t.slice(s.length,t.length-a.length);for(let l of i)n.push(l.includes("*")?l.replace("*",c):l)}return n}function lE(e,t){let n=dE(uE(e),t);if(!n)return null;let r=Ht(e);for(let i of fE(n)){let o=Ie(e.config.projectRoot,n.pkg.relativeDir,i);for(let s of Cl(o)){let a=ee(jn(e.config.projectRoot,s));if(r.has(a)||Bn(s))return a}}return null}function uE(e){return qD.get(e,()=>Cr(e.config.projectRoot))}function dE(e,t){let n=null;for(let r of e){let i=null;t===r.name?i="":t.startsWith(`${r.name}/`)&&(i=t.slice(r.name.length+1)),i!==null&&(!n||r.name.length>n.pkg.name.length)&&(n={pkg:r,subpath:i})}return n}function fE(e){let t=[],n=mE(e.pkg.exports,e.subpath);if(n){let r=pE(n);r&&t.push(r)}return t.push(e.subpath?`src/${e.subpath}`:"src/index"),t}function mE(e,t){if(!e||typeof e!="object")return null;let n=t===""?".":`./${t}`;return yp(e[n])}function yp(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return null;let t=e;for(let n of["types","import","default","require","node"]){let r=yp(t[n]);if(r)return r}return null}function pE(e){let t=e.replace(/^\.\//,"");return t.startsWith("dist/")?`src/${t.slice(5)}`:null}function gE(e,t){let n=ee(Ye(t));return WD.get(e,n,()=>hE(e,n))}function hE(e,t){let n=zD();if(!n)return null;let r=Ie(e.config.projectRoot),i=Ie(r,t);for(;i===r||i.startsWith(r+$D);){for(let s of VD){let a=ot(i,s);if(!Bn(a))continue;let c=UD.get(e,a,()=>yE(n,a));if(c)return c}let o=Ye(i);if(o===i)break;i=o}return null}function yE(e,t){try{let n=e.readConfigFile(t,e.sys.readFile);if(n.error||!n.config)return null;let r=e.parseJsonConfigFileContent(n.config,e.sys,Ye(t)),i=r.options.paths;return!i||Object.keys(i).length===0?null:{baseUrl:r.options.baseUrl?Ie(Ye(t),r.options.baseUrl):Ye(t),paths:i}}catch{return null}}function vr(e,t,n){let r=Ht(e),i;if(n.startsWith(".")){let o=n.match(/^(\.+)(.*)$/);if(!o)return null;let s=o[1].length,a=o[2].replace(/^\./,""),c=Ye(ot(e.config.projectRoot,t));for(let l=1;l<s;l++)c=Ye(c);i=a?Ie(c,a.replace(/\./g,"/")):c}else i=Ie(e.config.projectRoot,n.replace(/\./g,"/"));for(let o of bE(i)){let s=ee(jn(e.config.projectRoot,o));if(r.has(s)||Bn(o))return s}return null}function Bt(e,t,n){if(!n)return null;let r=n.replace(/\s+as\s+.+$/,"").trim();if(!r.startsWith("crate::")&&!r.startsWith("self::")&&!r.startsWith("super::"))return null;let i=Ye(ot(e.config.projectRoot,t)),o;return r.startsWith("crate::")?o=Ie(e.config.projectRoot,"src",r.slice(7).replace(/::/g,"/")):r.startsWith("self::")?o=Ie(i,r.slice(6).replace(/::/g,"/")):o=Ie(Ye(i),r.slice(7).replace(/::/g,"/")),Sl(e,SE(o))}function as(e,t,n){let r=Ye(ot(e.config.projectRoot,t)),i=Ie(r,n);return Sl(e,CE(i))}function cs(e,t,n){let r=Ye(ot(e.config.projectRoot,t)),i=[Ie(r,n),Ie(e.config.projectRoot,n),Ie(e.config.projectRoot,"include",n),Ie(e.config.projectRoot,"src",n)];return Sl(e,i)}function be(e,t,n){let r=Ht(e),i=t.replace(/\\/g,".").replace(/::/g,".").replace(/^global::/,""),o=i.replace(/\./g,"/"),s=i.split(".").pop()??i;for(let c of n){let l=`${o}${c}`,u=[...r].find(d=>d.endsWith(l));if(u)return u}for(let c of n){let l=[...r].find(u=>up(u)===`${s}${c}`);if(l)return l}let a=[...r].filter(c=>n.includes(jt(c).toLowerCase())).filter(c=>c.includes(`/${o}/`)||c.includes(`/${s}/`)).sort((c,l)=>c.localeCompare(l));return a.length===1?a[0]:null}function ls(e,t,n){let r=Ht(e);if(n.startsWith("package:")){let s=n.slice(8),a=s.indexOf("/");if(a<0)return null;let c=s.slice(a+1),l=ee(c.startsWith("lib/")?c:`lib/${c}`);return r.has(l)?l:null}let i=Ye(ot(e.config.projectRoot,t)),o=Ie(i,n);for(let s of xE(o)){let a=ee(jn(e.config.projectRoot,s));if(r.has(a)||Bn(s))return a}return null}function bl(e,t){let n=t.replace(/-/g,"_").replace(/\./g,"/"),r=Ht(e);for(let i of xr){let o=`${n}${i}`,s=[...r].find(a=>a.endsWith(o));if(s)return s}for(let i of xr){let o=[...r].find(s=>up(s)===`${n.split("/").pop()}${i}`);if(o)return o}return null}function bE(e){let t=jt(e);return ml.has(t)?[e]:[`${e}.py`,`${e}.pyi`,ot(e,"__init__.py"),ot(e,"__init__.pyi")]}function Sl(e,t){let n=Ht(e);for(let r of t){let i=ee(jn(e.config.projectRoot,r));if(n.has(i)||Bn(r))return i}return null}function SE(e){let t=jt(e);return pl.has(t)?[e]:[`${e}.rs`,ot(e,"mod.rs")]}function CE(e){let t=jt(e);return gl.has(t)?[e]:[`${e}.rb`,ot(e,"index.rb")]}function xE(e){let t=jt(e);return hl.has(t)?[e]:[`${e}.dart`,e]}function Cl(e){let t=jt(e),n=new Set;if(t){n.add(e);for(let r of $n)n.add(e.slice(0,-t.length)+r)}else for(let r of $n)n.add(`${e}${r}`),n.add(ot(e,`index${r}`));return[...n]}function Ht(e){return BD.get(e,()=>new Set(N(e,{includeIgnored:!1}).map(ee)))}function xl(e){return HD.get(e,()=>ge([...Ht(e)].sort().join(`
104
- `)))}import{readdirSync as vE}from"fs";import{execFileSync as RE}from"child_process";import{extname as us,join as IE}from"path";var wE=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".rs",".py",".pyi",".java",".kt",".kts",".scala",".sc",".clj",".cljs",".cljc",".rb",".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx",".cs",".vb",".php",".dart"],CQ=[".vue"],bp=[".tsx",".jsx"],Sp=[".vue"],DE=[...bp,...Sp],EE=new Set(bp),kE=new Set(Sp),Cp=new Set(wE.map(e=>e.toLowerCase())),PE=[...Cp].sort().join(","),xp=new Set(["node_modules",".git","target","dist","build",".next",".nuxt",".cache",".turbo",".nbb",".cpcache",".shadow-cljs","out","coverage",".scipquery-cache","__pycache__",".venv","venv",".idea",".vscode"]);function Ue(e,t={}){let n=t.includeIndexed??!0,r=t.includeAuxiliary??!0,i=t.extensions?.map(c=>c.toLowerCase()),o=i?new Set(i):Cp,s=i?[...o].sort().join(","):PE,a=`${n?"1":"0"}|${r?"1":"0"}|${s}`;return TE.get(e,a,()=>{let c=new Set;if(n)for(let l of N(e,{includeIgnored:!1}))o.has(us(l).toLowerCase())&&c.add(l);if(r)for(let l of _E(e.config.projectRoot,o))e.isIgnored(l)||n&&c.has(l)||c.add(l);return[...c].sort()})}function ds(e,t={}){let n=!1,r=!1;for(let i of Ue(e,{extensions:DE})){if(t.scope&&!i.includes(t.scope))continue;let o=us(i).toLowerCase();if(n||=EE.has(o),r||=kE.has(o),n&&r)break}return{react:n,vue:r}}var TE=j("source-files",{clearGroups:[]});function _E(e,t){return FE(e,t)??NE(e,t)}function FE(e,t){try{let n=RE("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e,encoding:"utf-8",timeout:1e4,stdio:["ignore","pipe","ignore"]}),r=new Set;for(let i of n.split(`
105
- `)){let o=i.trim();o&&(LE(o)||t.has(us(o).toLowerCase())&&r.add(o))}return r}catch{return null}}function LE(e){return e.split("/").some(t=>xp.has(t))}function NE(e,t){let n=new Set,r=i=>{let o=i?IE(e,i):e,s;try{s=vE(o,{withFileTypes:!0})}catch{return}for(let a of s)if(!xp.has(a.name)){if(a.isDirectory()){r(i?`${i}/${a.name}`:a.name);continue}t.has(us(a.name).toLowerCase())&&n.add(i?`${i}/${a.name}`:a.name)}};return r(""),n}var AE=new Set(["ref","shallowRef","reactive","computed","watch","watchEffect"]),ME=new Set(["onBeforeMount","onMounted","onBeforeUpdate","onUpdated","onBeforeUnmount","onUnmounted","onActivated","onDeactivated","onErrorCaptured"]),OE=new Set(["axios","fetch","runRequest","useAsyncData","useFetch","useResource"]),jE=new Set(["defineEmits","defineExpose","defineModel","defineOptions","defineProps","withDefaults"]),$E=new Set(["catch","for","function","if","return","switch","while"]);function ms(e){let t={imports:[],functions:[],calls:[],composables:[],stores:[],reactivity:[],lifecycle:[],requests:[],macros:[],lineCount:0,externalLineCount:0,externalScriptPaths:[],unresolvedScripts:[]};for(let n of e.scripts){t.lineCount+=An(n),n.external&&(t.externalLineCount+=An(n),t.externalScriptPaths.push(n.sourcePath));for(let i of n.errors)t.unresolvedScripts.push({sourcePath:n.sourcePath,reason:i});if(!n.body||!n.astLanguage){n.astLanguage||t.unresolvedScripts.push({sourcePath:n.sourcePath,reason:`Unsupported Vue script language: ${n.lang??"unknown"}`});continue}t.imports.push(...WE(n));let r=di(n.astLanguage,n.body);r?HE(n,r.rootNode,t):UE(n,t)}return BE(t),t.externalScriptPaths=Rp(t.externalScriptPaths),t}function BE(e){e.composables=Rr(e,"composable"),e.stores=Rr(e,"store"),e.reactivity=Rr(e,"reactivity"),e.lifecycle=Rr(e,"lifecycle"),e.requests=Rr(e,"request"),e.macros=Rr(e,"macro")}function Rr(e,t){return Rp(e.calls.filter(n=>n.categories.includes(t)).map(n=>n.name))}function HE(e,t,n){let r=new Set,i=new Set,o=s=>{let a=Yo(s,e.astLanguage);if(a){let l=`${a.name}:${a.startLine}:${a.endLine}`;i.has(l)||(i.add(l),n.functions.push({name:a.name,sourcePath:e.sourcePath,startLine:e.startLine+a.startLine,endLine:e.startLine+a.endLine,setup:e.setup}))}let c=yr(s,e.astLanguage);if(c){let l=`${c.calleeLeaf}:${c.line}`;r.has(l)||(r.add(l),n.calls.push({name:c.calleeLeaf,sourcePath:e.sourcePath,line:e.startLine+c.line,categories:vp(c.calleeLeaf),setup:e.setup}))}for(let l of s.children)o(l)};o(t)}function UE(e,t){for(let n of e.body.matchAll(/\b([A-Za-z_$][\w$]*)\s*\(/g)){let r=n[1];!r||$E.has(r)||t.calls.push({name:r,sourcePath:e.sourcePath,line:e.startLine+fs(e.body,n.index??0),categories:vp(r),setup:e.setup})}for(let n of e.body.matchAll(/\bfunction\s+([A-Za-z_$][\w$]*)\b/g)){let r=n[1];if(!r)continue;let i=e.startLine+fs(e.body,n.index??0);t.functions.push({name:r,sourcePath:e.sourcePath,startLine:i,endLine:i,setup:e.setup})}for(let n of e.body.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:function\b|\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)/g)){let r=n[1];if(!r)continue;let i=e.startLine+fs(e.body,n.index??0);t.functions.push({name:r,sourcePath:e.sourcePath,startLine:i,endLine:i,setup:e.setup})}}function WE(e){let t=[];for(let n of e.body.matchAll(/\bimport\s+(?:type\s+)?([^'";]+?)\s+from\s+['"]([^'"]+)['"]/g)){let r=n[1]?.trim(),i=n[2];if(!r||!i)continue;let o=e.startLine+fs(e.body,n.index??0);for(let s of GE(r))t.push({local:s,source:i,sourcePath:e.sourcePath,line:o,setup:e.setup})}return t}function GE(e){let t=[],r=e.split(",").map(s=>s.trim()).filter(Boolean)[0];r&&!r.startsWith("{")&&!r.startsWith("*")&&t.push(r);let i=/\{([^}]*)\}/.exec(e)?.[1];if(i)for(let s of i.split(",")){let a=s.trim();if(!a)continue;let c=/\bas\s+([A-Za-z_$][\w$]*)$/.exec(a)?.[1];t.push(c??a.replace(/^type\s+/,"").trim())}let o=/\*\s+as\s+([A-Za-z_$][\w$]*)/.exec(e)?.[1];return o&&t.push(o),t.filter(s=>/^[A-Za-z_$][\w$]*$/.test(s))}function vp(e){let t=["call"];return/^use[A-Z0-9_]/.test(e)&&t.push("composable"),/^use[A-Z0-9_].*Store$/.test(e)&&t.push("store"),AE.has(e)&&t.push("reactivity"),ME.has(e)&&t.push("lifecycle"),OE.has(e)&&t.push("request"),jE.has(e)&&t.push("macro"),t}function fs(e,t){let n=0;for(let r=0;r<t&&r<e.length;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}function Rp(e){return[...new Set(e)].sort()}var zE=new Set(["in","key","of"]),VE=new Set(["computed","defineEmits","defineProps","reactive","ref","watch","watchEffect"]),qE=ln("vue-component-behavior-profiles");function Ip(e,t={}){let n=Ue(e,{extensions:[".vue"]}).filter(i=>!t.scope||i.includes(t.scope)).sort();return(typeof t.scanLimit=="number"&&t.scanLimit>0?n.slice(0,t.scanLimit):n).map(i=>vl(e,i)).filter(i=>(t.minTemplateTokens===void 0||i.templateTokens.size>=t.minTemplateTokens)&&(t.minBehaviorTokens===void 0||i.behaviorTokens.size>=t.minBehaviorTokens))}function vl(e,t){let n=t.replace(/\\/g,"/"),r=P(e,n),i=qE.get(e,n,r,()=>KE(e,n,r));return YE(i)}function KE(e,t,n){let r=hr(e,t),i=ts(e,t),o=ms(r),s=ZE(i),a=i.expressionIdentifiers.map(h=>h.name).filter(h=>!s.includes(h)).filter((h,S,C)=>C.indexOf(h)===S).sort(),c=i.componentTags.map(h=>h.normalized).filter((h,S,C)=>C.indexOf(h)===S).sort(),l=n?n.split(`
106
- `).length:0,u=An(r.template),d=o.lineCount,f=r.styles.reduce((h,S)=>h+An(S),0),m=r.customBlocks.reduce((h,S)=>h+An(S),0),{lines:p,paths:g}=JE(e,t,o);return{file:t,sfc:r,templateFacts:i,scriptFacts:o,templateTokens:new Set(i.structuralTokens),behaviorTokens:QE(i,o,a),templateBindingNames:a,templateLocalNames:s,componentNames:c,sfcLines:l,totalLines:l+o.externalLineCount,templateLines:u,scriptLines:d,styleLines:f,externalScriptLines:o.externalLineCount,externalScriptPaths:o.externalScriptPaths,customBlockLines:m,delegatedComposableLines:p,delegatedComposablePaths:g}}function JE(e,t,n){let r=new Set;for(let s of n.composables){let a=n.imports.find(l=>l.local===s);if(!a)continue;let c=Qe(e,a.sourcePath,a.source);!c||c===t||r.add(c)}let i=[...r].sort();return{lines:i.reduce((s,a)=>{let c=P(e,a);return s+(c?c.split(`
107
- `).length:0)},0),paths:i}}function YE(e){let t=XE(e.scriptFacts);return{...e,scriptFacts:t,templateTokens:new Set(e.templateTokens),behaviorTokens:new Set(e.behaviorTokens),templateBindingNames:[...e.templateBindingNames],templateLocalNames:[...e.templateLocalNames],componentNames:[...e.componentNames],externalScriptPaths:t.externalScriptPaths,delegatedComposablePaths:[...e.delegatedComposablePaths]}}function XE(e){return{...e,imports:e.imports.map(t=>({...t})),functions:e.functions.map(t=>({...t})),calls:e.calls.map(t=>({...t,categories:[...t.categories]})),composables:[...e.composables],stores:[...e.stores],reactivity:[...e.reactivity],lifecycle:[...e.lifecycle],requests:[...e.requests],macros:[...e.macros],externalScriptPaths:[...e.externalScriptPaths],unresolvedScripts:e.unresolvedScripts.map(t=>({...t}))}}function QE(e,t,n){let r=new Set;for(let i of t.composables)r.add(`composable:${i}`);for(let i of t.stores)r.add(`store:${i}`);for(let i of t.reactivity)r.add(`reactivity:${i}`);for(let i of t.lifecycle)r.add(`lifecycle:${i}`);for(let i of t.requests)r.add(`request:${i}`);for(let i of t.macros)r.add(`macro:${i}`);for(let i of t.functions){if(VE.has(i.name))continue;r.add(`function:${i.name}`);let o=/^[a-z]+/.exec(i.name)?.[0]??null;o&&o.length>2&&o!==i.name&&r.add(`function-verb:${o}`)}for(let i of e.events)r.add(`template-event:${i.name}`);for(let i of n)r.add(`template-binding:${i}`);return r}function ZE(e){let t=new Set;for(let n of e.directives)if(n.name==="for"&&n.value)for(let r of ek(n.value))t.add(r);for(let n of e.slots)if(n.value)for(let r of wp(n.value))t.add(r);return[...t].sort()}function ek(e){let t=/^(.*?)\s+(?:in|of)\s+/.exec(e.trim());return t?wp(t[1]??""):[]}function wp(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let r=n[0];zE.has(r)||t.push(r)}return t}import{extname as tk}from"path";function Ze(e){return typeof e=="object"&&e!==null}function xe(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")?e:null}var nk=[".tsx",".jsx"],Dp=new Set(["useActionState","useCallback","useContext","useDebugValue","useDeferredValue","useEffect","useId","useImperativeHandle","useInsertionEffect","useLayoutEffect","useMemo","useOptimistic","useReducer","useRef","useState","useSyncExternalStore","useTransition"]),rk=new Set(["useEffect","useInsertionEffect","useLayoutEffect"]),ik=new Set(["useActionState","useOptimistic","useReducer","useRef","useState"]),ok=new Set(["useLocation","useNavigate","useParams","useSearchParams","useTranslation"]),sk=new Set(["axios","fetch","gql","graphql","mutate","query","request","useMutation","useQuery","useSuspenseQuery"]),ak=new Set(["add","apply","cancel","change","clear","close","create","delete","fetch","filter","handle","load","open","refresh","remove","render","reset","save","select","submit","toggle","update"]),ck=new Set(["aria-hidden","className","clipRule","d","fill","fillRule","height","role","stroke","strokeLinecap","strokeLinejoin","strokeWidth","style","viewBox","width","xmlns"]),lk=ln("react-component-behavior-profiles"),Ep=re({kind:"react-component-behavior-profiles",invalidation:q("react-component-behavior-profiles"),serialize:mk,deserialize:pk});function _p(e,t={}){let n=Ue(e,{extensions:nk}).filter(i=>!t.scope||i.includes(t.scope)).sort();return(typeof t.scanLimit=="number"&&t.scanLimit>0?n.slice(0,t.scanLimit):n).flatMap(i=>Il(e,i)).filter(i=>(t.minJsxTokens===void 0||i.jsxTokens.size>=t.minJsxTokens)&&(t.minBehaviorTokens===void 0||i.behaviorTokens.size>=t.minBehaviorTokens))}function Il(e,t){let n=t.replace(/\\/g,"/"),r=P(e,n);return lk.get(e,n,r,()=>uk(e,n,r)).map(fk)}function uk(e,t,n){let r=ae(e,t,n),i=Ep.read(e,t,r);if(i)return i;let o=dk(e,t);return Ep.write(e,t,r,o),o}function dk(e,t){let n=hk(t);if(!n)return[];let r=V(e,t);if(!r)return[];let i=Ce(e,t).length;return yk(r.rootNode,n).filter(s=>s.kind==="hook"||wl(s.bodyNode)).map(s=>{let a=Ik(s.bodyNode),c=Pk(s.bodyNode,n);return{file:t,name:s.name,kind:s.kind,startLine:s.node.startPosition.row,endLine:s.node.endPosition.row,loc:Math.max(1,s.node.endPosition.row-s.node.startPosition.row+1),fileLines:i,jsxTokens:a.tokens,behaviorTokens:c.tokens,componentNames:Ut(a.componentNames),nativeTags:Ut(a.nativeTags),propNames:Ut(a.propNames),eventNames:Ut(a.eventNames),hookNames:Ut(c.hookNames),requestNames:Ut(c.requestNames),stateNames:Ut(c.stateNames),effectNames:Ut(c.effectNames),handlerNames:Ut(c.handlerNames)}})}function fk(e){return{...e,jsxTokens:new Set(e.jsxTokens),behaviorTokens:new Set(e.behaviorTokens),componentNames:[...e.componentNames],nativeTags:[...e.nativeTags],propNames:[...e.propNames],eventNames:[...e.eventNames],hookNames:[...e.hookNames],requestNames:[...e.requestNames],stateNames:[...e.stateNames],effectNames:[...e.effectNames],handlerNames:[...e.handlerNames]}}function mk(e){return JSON.stringify(e.map(t=>({...t,jsxTokens:[...t.jsxTokens],behaviorTokens:[...t.behaviorTokens]})))}function pk(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=[];for(let r of t){let i=gk(r);if(!i)return null;n.push(i)}return n}catch{return null}}function gk(e){if(!Ze(e))return null;let{file:t,name:n,kind:r,startLine:i,endLine:o,loc:s,fileLines:a,jsxTokens:c,behaviorTokens:l,componentNames:u,nativeTags:d,propNames:f,eventNames:m,hookNames:p,requestNames:g,stateNames:h,effectNames:S,handlerNames:C}=e;if(typeof t!="string"||typeof n!="string"||r!=="component"&&r!=="hook"||!ps(i)||!ps(o)||!ps(s)||!ps(a))return null;let x={jsxTokens:xe(c),behaviorTokens:xe(l),componentNames:xe(u),nativeTags:xe(d),propNames:xe(f),eventNames:xe(m),hookNames:xe(p),requestNames:xe(g),stateNames:xe(h),effectNames:xe(S),handlerNames:xe(C)};return Object.values(x).some(b=>b===null)?null:{file:t,name:n,kind:r,startLine:i,endLine:o,loc:s,fileLines:a,jsxTokens:new Set(x.jsxTokens),behaviorTokens:new Set(x.behaviorTokens),componentNames:x.componentNames,nativeTags:x.nativeTags,propNames:x.propNames,eventNames:x.eventNames,hookNames:x.hookNames,requestNames:x.requestNames,stateNames:x.stateNames,effectNames:x.effectNames,handlerNames:x.handlerNames}}function ps(e){return typeof e=="number"&&Number.isFinite(e)}function hk(e){let t=tk(e).toLowerCase();return t!==".tsx"&&t!==".jsx"?null:M(e)}function yk(e,t){let n=[],r=new Set,i=o=>{let s=bk(o);if(s&&(!vk(o)||s.kind==="component")){let a=`${s.name}:${s.node.startIndex}:${s.node.endIndex}`;r.has(a)||(r.add(a),n.push(s))}for(let a of o.namedChildren)i(a)};return(t==="tsx"||t==="javascript")&&i(e),n}function bk(e){if(e.type==="class_declaration"){let o=Rl(e);if(!o||!/^[A-Z]/.test(o))return null;let s=Sk(e);return!s||!Ck(e)&&!wl(s)?null:{name:o,kind:"component",node:e,bodyNode:s}}if(e.type==="function_declaration"){let o=Rl(e);return!o||!kp(o)?null:{name:o,kind:Pp(o),node:e,bodyNode:e}}if(e.type!=="variable_declarator")return null;let t=e.childForFieldName("name")??e.namedChild(0),n=e.childForFieldName("value")??e.namedChild(1),r=bi(t);if(!r||!n||!kp(r))return null;let i=xk(n);return i?{name:r,kind:Pp(r),node:e,bodyNode:i}:null}function Sk(e){for(let t of e.namedChildren)if(t.type==="class_body")for(let n of t.namedChildren){if(n.type!=="method_definition")continue;if((n.childForFieldName("name")??n.namedChild(0))?.text==="render")return n}return null}function Ck(e){return/\b(?:React\.)?(?:Pure)?Component\b/.test(e.text)}function kp(e){return/^[A-Z]/.test(e)||/^use[A-Z0-9_]/.test(e)}function Pp(e){return/^use[A-Z0-9_]/.test(e)?"hook":"component"}function xk(e){if(e.type==="arrow_function"||e.type==="function_expression")return e;if(e.type!=="call_expression")return null;let t=Rk(e);return t!=="memo"&&t!=="forwardRef"?null:e.namedChildren.find(i=>i.type==="arguments")?.namedChildren.find(i=>i.type==="arrow_function"||i.type==="function_expression")??null}function vk(e){let t=e.parent;for(;t;){if(t.type==="function_declaration"||t.type==="function_expression"||t.type==="arrow_function"||t.type==="method_definition")return!0;t=t.parent}return!1}function Rl(e){return bi(e.childForFieldName("name")??e.namedChild(0))}function Rk(e){let t=e.childForFieldName("function")??e.namedChild(0);return t?t.text.split(".").pop()??t.text:null}function wl(e){return e.type.startsWith("jsx_")?!0:e.namedChildren.some(wl)}function Ik(e){let t={tokens:new Set,componentNames:new Set,nativeTags:new Set,propNames:new Set,eventNames:new Set},n=r=>{r.type==="jsx_opening_element"||r.type==="jsx_self_closing_element"?wk(r,t):r.type==="jsx_element"&&r.text.trimStart().startsWith("<>")?t.tokens.add("jsx:fragment"):r.type==="jsx_expression"?Dk(r,t):r.type==="jsx_fragment"&&t.tokens.add("jsx:fragment");for(let i of r.children)n(i)};return n(e),t}function wk(e,t){let n=Ek(e),r=!1;if(n){let i=Tp(n),o=i==="Fragment"||i==="React.Fragment";r=Nk(i)&&!o,o?t.tokens.add("jsx:fragment"):r?(t.componentNames.add(i),t.tokens.add(`component:${i}`)):(t.nativeTags.add(i),t.tokens.add(`native:${i}`))}for(let i of e.namedChildren)if(i.type==="jsx_attribute"){let o=kk(i);if(!o)continue;let s=Tp(o);if(s.startsWith("on")&&s.length>2){let a=s.slice(2).replace(/^[A-Z]/,c=>c.toLowerCase());t.eventNames.add(a),t.tokens.add(`event:${a}`)}else ck.has(s)||(t.propNames.add(s),t.tokens.add(`${r?"prop":"native-prop"}:${s}`))}else i.type==="jsx_spread_attribute"&&t.tokens.add(Fp(i))}function Dk(e,t){let n=e.text;/^\{\s*\.\.\./.test(n)&&t.tokens.add(Fp(e)),Lp(e)&&t.tokens.add("jsx:conditional"),(n.includes(".map(")||n.includes(".flatMap("))&&t.tokens.add("jsx:list");for(let r of Ak(n))Zo(r)||t.tokens.add(`binding:${r}`)}function Fp(e){let t=/^\{\s*\.\.\.\s*([^}]+)\s*\}$/.exec(e.text)?.[1],n=e.namedChildren.find(o=>o.type!=="comment"),r=t??n?.text??"",i=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.exec(r.trim())?.[0];return i?`prop:spread:${i}`:"prop:spread"}function Lp(e){return e.type==="ternary_expression"||e.type==="conditional_expression"?!0:e.namedChildren.some(Lp)}function Ek(e){for(let t of e.namedChildren)if(t.type==="identifier"||t.type==="jsx_identifier"||t.type==="property_identifier"||t.type==="member_expression"||t.type==="jsx_member_expression")return t.text;return/^<\s*([A-Za-z][\w$.]*)/.exec(e.text)?.[1]??null}function kk(e){for(let t of e.namedChildren)if(t.type==="property_identifier"||t.type==="identifier"||t.type==="jsx_identifier")return t.text;return/^([A-Za-z_$][\w$:-]*)/.exec(e.text)?.[1]??null}function Pk(e,t){let n={tokens:new Set,hookNames:new Set,requestNames:new Set,stateNames:new Set,effectNames:new Set,handlerNames:new Set},r=i=>{if(i.type==="call_expression"){let o=yr(i,t);o&&Tk(o.calleeLeaf,n)}else if(i.type==="variable_declarator")Fk(i,n);else if(i.type==="function_declaration"){let o=Rl(i);o&&Np(o,n)}for(let o of i.namedChildren)r(o)};return r(e),n}function Tk(e,t){/^use[A-Z0-9_]/.test(e)&&(t.hookNames.add(e),!Dp.has(e)&&!ok.has(e)&&t.tokens.add(`hook:${e}`)),Dp.has(e)&&t.tokens.add(`react-hook:${e}`),rk.has(e)&&(t.effectNames.add(e),t.tokens.add(`effect:${e}`)),ik.has(e)&&t.tokens.add(`state-hook:${e}`),_k(e)&&(t.requestNames.add(e),t.tokens.add(`request:${e}`))}function _k(e){if(sk.has(e))return!0;let t=/^use([A-Z0-9_].*)$/.exec(e)?.[1];return t?/(Query|Mutation|Fetch|Resource)$/.test(t):!1}function Fk(e,t){let n=e.childForFieldName("name")??e.namedChild(0),r=e.childForFieldName("value")??e.namedChild(1);if(n?.type==="array_pattern"&&r?.text.includes("useState")){let o=n.namedChildren.find(a=>bi(a)),s=bi(o);s&&(t.stateNames.add(s),t.tokens.add(`state:${s}`))}let i=bi(n);i&&Np(i,t)}function Np(e,t){let n=Lk(e);!n||!ak.has(n)||(t.handlerNames.add(e),t.tokens.add(`handler:${e}`),t.tokens.add(`handler-verb:${n}`))}function Lk(e){let t=e.startsWith("handle")&&e.length>6?e.slice(6).replace(/^[A-Z]/,n=>n.toLowerCase()):e;return/^[a-z]+/.exec(t)?.[0]??null}function Nk(e){return/^[A-Z]/.test(e)||e.includes(".")}function Tp(e){return e.replace(/^this\./,"").replace(/\$/g,".")}function bi(e){return e&&(e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"||/^[A-Za-z_$][\w$]*$/.test(e.text))?e.text:null}function Ak(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let r=n[0];t.includes(r)||t.push(r)}return t}function Ut(e){return[...e].sort()}function st(e){return{capability:(t,n)=>Mk(t,n),reactProfiles:(t={})=>_p(e,t),reactProfilesForFile:t=>Il(e,t),vueProfiles:(t={})=>Ip(e,t),vueProfileForFile:t=>vl(e,t),vueTemplateFacts:t=>ts(e,t),vueScriptFacts:t=>ms(hr(e,t))}}function Mk(e,t){let n=e.startsWith("react-")?"react":"vue";if(t===void 0)return{slot:e,available:!0,framework:n};let r=t.replace(/\\/g,"/").toLowerCase();return n==="react"&&!r.endsWith(".tsx")&&!r.endsWith(".jsx")?{slot:e,available:!1,framework:n,reason:"React behavior profiles are only available for .tsx and .jsx files"}:n==="vue"&&!r.endsWith(".vue")?{slot:e,available:!1,framework:n,reason:"Vue behavior facts are only available for .vue files"}:{slot:e,available:!0,framework:n}}function Un(e,t,n={}){let r=W(e,t);if(!r)return[];let i=[];if(n.includeCrossLanguageDispatchNames)for(let o of r.crossLanguageDispatchNames)i.push({name:o,kind:"cross-language-dispatch",occurrences:1});if(n.includeRustAttributeNames&&r.language==="rust")for(let o of r.rustAttrReferencedNames)i.push({name:o,kind:"rust-attribute",occurrences:1});return i}import{basename as Op}from"path";function B(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function at(e){return e.replace(/'''[\s\S]*?'''/g,gn).replace(/"""[\s\S]*?"""/g,gn).replace(/#.*$/gm,gn).replace(/\/\/.*$/gm,gn).replace(/\/\*[\s\S]*?\*\//g,gn).replace(/`(?:\\[\s\S]|[^`])*`/g,gn).replace(/'(?:\\.|[^'\\\r\n])*'/g,gn).replace(/"(?:\\.|[^"\\\r\n])*"/g,gn)}function Ci(e){return Mp(e,{maskStrings:!1})}function Ap(e){return Mp(e,{maskStrings:!0})}function Mp(e,t){let n="",r=0,i=e.length;for(;r<i;){if(e[r]==="/"&&e[r+1]==="/"){let s=e.indexOf(`
108
- `,r),a=s===-1?i:s;n+=Dl(e,r,a),r=a;continue}if(e[r]==="/"&&e[r+1]==="*"){let s=e.indexOf("*/",r+2),a=s===-1?i:s+2;n+=Dl(e,r,a),r=a;continue}let o=e[r];if(o==="`"||o==="'"||o==='"'){let s=o,a=r+1;for(;a<i;){if(e[a]==="\\"){a+=2;continue}if(e[a]===s){a+=1;break}if(s!=="`"&&e[a]===`
109
- `)break;a+=1}n+=t.maskStrings?Dl(e,r,a):e.slice(r,a),r=a;continue}n+=o,r+=1}return n}function Dl(e,t,n){let r="";for(let i=t;i<n;i+=1)r+=e[i]===`
110
- `?`
111
- `:" ";return r}function gn(e){return e.replace(/[^\r\n]/g," ")}var p4=Ln("stripped-lines",{clearGroups:["whole-project","source-file"]});cn({name:"stripped-source-singleton",groups:["whole-project","source-file"],clearAll:()=>{gs=null,Si=""},clearFile:()=>{gs=null,Si=""}});var gs=null,Si="";function Ok(e){return gs===e||(gs=e,Si=at(e)),Si}function hn(e,t,n){let r=Ok(e);return`${r.slice(0,t)}${" ".repeat(n-t)}${r.slice(n)}`}function We(e,t){return new RegExp(`\\b${B(t)}\\b`,"m").test(e)}function Ir(e,t){let n=new Set,r=new RegExp(`\\b${B(t)}\\s*\\.\\s*([A-Za-z_$][\\w$]*)`,"g");for(let i of e.matchAll(r)){let o=i[1];o&&n.add(o)}return[...n]}function xi(e){let t=0;for(let n of e)n==="("&&(t+=1),n===")"&&(t-=1);return t}var jk=new Set(["identifier","type_identifier","property_identifier","shorthand_property_identifier","field_identifier"]);function Ge(e){let t=[],n=0,r=0;for(let i=0;i<e.length;i++){let o=e[i];(o==="{"||o==="["||o==="(")&&n++,(o==="}"||o==="]"||o===")")&&n--,o===","&&n===0&&(t.push(e.slice(r,i)),r=i+1)}return t.push(e.slice(r)),t}function et(e,t){for(let n of e.namedChildren)if(n.type===t)return n;return null}function Se(e,t){let n=new Set,r=(i,o)=>{let s=o||t.has(i.type);!s&&jk.has(i.type)&&n.add(i.text);for(let a of i.children)r(a,s)};return r(e.rootNode,!1),n}function bt(e,t,n,r,i,o,s){return{importedName:i,localName:o,sourcePath:s??be(e,r,yl(t)),kind:"named",used:We(n,o),usedMembers:[]}}function me(e,t,n,r,i="named",o={}){return{importedName:e,localName:t,sourcePath:n,kind:i,used:r.has(t),usedMembers:[],isTypeOnly:o.isTypeOnly}}function Wt(e,t,n,r,i="named",o=[],s={}){return{importedName:e,localName:t,sourcePath:n,kind:i,used:r,usedMembers:o,isTypeOnly:s.isTypeOnly}}function Wn(e,t){return{importedName:e,localName:null,sourcePath:t,kind:"side-effect",used:!0,usedMembers:[]}}function Gn(e,t,n={}){return{importedName:e,localName:n.localName??null,sourcePath:t,kind:"namespace",used:n.used??!0,usedMembers:n.usedMembers??[],isTypeOnly:n.isTypeOnly}}function ct(e,t,n){let r=[];for(let i of e.matchAll(t)){let o=i[0];if(!o||typeof i.index!="number")continue;let s=hn(e,i.index,i.index+o.length);for(let a of n(i,s))r.push(a)}return r}function lt(e,t,n,r){let i=V(e,t);if(i){let o=n(i);if(o)return o}return r()}function hs(e,t,n,r){let i=V(e,t),o=M(t),s=o?n[o]:void 0;return i&&s?s(i):r()}function jp(e,t,n){return lt(e,t,r=>Bk(e,t,r),()=>$k(e,t,n))}function $k(e,t,n){return ct(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(r,i)=>{let o=r[1]?.trim();if(!o)return[];let s=Op(o).replace(/\.[^.]+$/,"");return[Wt(o,s,cs(e,t,o),We(i,s))]})}function Bk(e,t,n){let r=Se(n,new Set(["preproc_include"])),i=[];for(let o of n.rootNode.descendantsOfType("preproc_include")){let s=null;for(let c of o.namedChildren){if(c.type==="system_lib_string"){s=c.text.replace(/^<|>$/g,"");break}if(c.type==="string_literal"){s=c.namedChildren.find(u=>u.type==="string_content")?.text??c.text.replace(/^"|"$/g,"");break}}if(!s)continue;let a=Op(s).replace(/\.[^.]+$/,"");i.push(me(s,a,cs(e,t,s),r))}return i}var Hk=new Set([":require",":require-macros",":use"]),Pl=String.raw`A-Za-z0-9_$*+!?.<>=-`;function Bp(e,t,n){let r=Qk(n);if(!r)return[];let i=Xk(n,r.start,r.end),o=[];for(let s of r.children.slice(2)){if(s.type!=="list"||s.children.length===0)continue;let a=ut(s.children[0]);if(a){if(Hk.has(a)){for(let c of Gk(s.children.slice(1)))o.push(...Wk(e,c,i));continue}if(a===":import")for(let c of Vk(s.children.slice(1)))o.push(c)}}return o}function Uk(e){return e.type==="list"&&ut(e.children[0])==="ns"}function Wk(e,t,n){let r=bl(e,t.namespace),i=t.alias??t.namespace,o=Kk(n,i),s=[{importedName:t.namespace,localName:i,sourcePath:r,kind:"namespace",used:t.refers.length>0||t.referAll||o.length>0||Jk(n,t.namespace),usedMembers:o}];t.referAll&&s.push({importedName:"*",localName:null,sourcePath:r,kind:"side-effect",used:!0,usedMembers:[]});for(let a of t.refers)s.push({importedName:a,localName:a,sourcePath:r,kind:"named",used:Yk(n,a),usedMembers:[]});return s}function Gk(e){return e.flatMap(t=>ys(t,null))}function ys(e,t){if(e.type==="atom")return e.text.startsWith(":")?[]:[{namespace:kl(t,e.text),alias:null,refers:[],referAll:!1}];if(e.type==="vector")return e.children.length>0&&ut(e.children[0])===null?e.children.flatMap(n=>ys(n,t)):zk(e,t);if(e.type==="list"&&e.children.length>0){let n=ut(e.children[0]);return n?!n||n.startsWith(":")?[]:e.children.slice(1).flatMap(r=>ys(r,kl(t,n))):e.children.flatMap(r=>ys(r,t))}return[]}function zk(e,t){let n=ut(e.children[0]);if(!n||n.startsWith(":"))return[];let r={namespace:kl(t,n),alias:null,refers:[],referAll:!1};for(let i=1;i<e.children.length;i+=1){let o=ut(e.children[i]);if(!o?.startsWith(":"))continue;let s=e.children[i+1];if((o===":as"||o===":as-alias")&&s){r.alias=ut(s),i+=1;continue}o===":refer"&&s&&(ut(s)===":all"?r.referAll=!0:(s.type==="vector"||s.type==="list")&&r.refers.push(...s.children.map(ut).filter(qk)),i+=1)}return[r]}function Vk(e){let t=[];for(let n of e){if(n.type==="atom"){let i=n.text.split(".").pop()??n.text;t.push(Wt(i,i,null,!0));continue}if(n.type!=="vector")continue;let r=ut(n.children[0]);if(r)for(let i of n.children.slice(1)){let o=ut(i);o&&t.push(Wt(`${r}.${o}`,o,null,!0))}}return t}function kl(e,t){return e?`${e}.${t}`:t}function ut(e){return e?.type==="atom"?e.text:null}function qk(e){return!!(e&&!e.startsWith(":"))}function Kk(e,t){let n=new Set,r=new RegExp(`${Tl()}${B(t)}\\s*/\\s*([${Pl}]+)`,"g");for(let i of e.matchAll(r)){let o=i[1];o&&n.add(o)}return[...n]}function Jk(e,t){return new RegExp(`${Tl()}${B(t)}\\s*/`,"m").test(e)}function Yk(e,t){return new RegExp(`${Tl()}${B(t)}(?![${Pl}])`,"m").test(e)}function Tl(){return`(?<![${Pl}])`}function Xk(e,t,n){let r="",i=0;for(;i<e.length;){if(i>=t&&i<n){r+=e[i]===`
112
- `?`
113
- `:" ",i+=1;continue}let o=e[i];if(o===";"){let s=Qo(e,i);r+=$p(e.slice(i,s)),i=s;continue}if(o==='"'){let s=gi(e,i,0).index;r+=$p(e.slice(i,s)),i=s;continue}r+=o,i+=1}return r}function Qk(e){let t=0;for(;t<e.length&&(t=_l(e,t),!(t>=e.length));){let n=bs(e,t);if(!n){t+=1;continue}if(Uk(n.form))return n.form;t=n.index}return null}function bs(e,t){let n=_l(e,t);if(e.startsWith("#?@",n)||e.startsWith("#?",n))return Zk(e,n);if(e.startsWith("#_",n)){let i=bs(e,n+2);return i?{form:{type:"atom",text:"",start:n,end:i.index},index:i.index}:null}for(;el(e[n]);)n+=1;let r=e[n];return r?r==="("?El(e,n,"list",")"):r==="["?El(e,n,"vector","]"):r==="{"?El(e,n,"map","}"):r==='"'?{form:{type:"atom",text:"",start:n,end:gi(e,n,0).index},index:gi(e,n,0).index}:tP(e,n):null}function Zk(e,t){let n=e.startsWith("#?@",t)?3:2,r=bs(e,t+n);return r?{form:{type:"list",children:r.form.type==="list"||r.form.type==="vector"||r.form.type==="map"?eP(r.form.children):[],start:t,end:r.index},index:r.index}:null}function eP(e){let t=[];for(let n=0;n<e.length;n+=2){let r=ut(e[n]),i=e[n+1];r?.startsWith(":")&&i&&t.push(i)}return t}function El(e,t,n,r){let i=[],o=t+1;for(;o<e.length;){if(o=_l(e,o),e[o]===r)return{form:{type:n,children:i,start:t,end:o+1},index:o+1};let s=bs(e,o);if(!s){o+=1;continue}s.form.type==="atom"&&s.form.text===""||i.push(s.form),o=s.index}return{form:{type:n,children:i,start:t,end:e.length},index:e.length}}function tP(e,t){let n=t;for(;n<e.length&&!tl(e[n]);)n+=1;return{form:{type:"atom",text:e.slice(t,n),start:t,end:n},index:n}}function _l(e,t){let n=t;for(;n<e.length;){let r=e[n];if(/\s|,/.test(r)){n+=1;continue}if(r===";"){n=Qo(e,n);continue}break}return n}function $p(e){return e.replace(/[^\r\n]/g," ")}function Hp(e,t,n){let r=[];for(let i of n.matchAll(/^[ \t]*import\s+['"]([^'"]+)['"](?:\s+as\s+([A-Za-z_]\w*))?[\s\S]*?;$/gm)){let o=i[1]?.trim(),s=i[2]?.trim()??null,a=i[0];if(!o||!a||typeof i.index!="number")continue;let c=hn(n,i.index,i.index+a.length);r.push({importedName:o,localName:s,sourcePath:ls(e,t,o),kind:s?"namespace":"side-effect",used:s?We(c,s):!0,usedMembers:s?Ir(c,s):[]})}return r}function Up(e,t,n){let r=[];for(let i of n.matchAll(/^[ \t]*export\s+['"]([^'"]+)['"][\s\S]*?;$/gm)){let o=i[1]?.trim();o&&r.push({specifier:o,sourcePath:ls(e,t,o)})}return r}function Wp(e,t,n){return hs(e,t,{csharp:r=>rP(e,t,r),vb:r=>nP(e,t,r)},()=>{let r=hp(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return ct(n,r,(i,o)=>{let s=i[1]?.trim();if(!s)return[];let[a,c]=s.split(/\s*=\s*/),l=!!c,u=(l?c:a)?.trim()??s,d=u.split(".").pop()??u,f=l?a?.trim()??d:d;return[bt(e,t,o,u,d,f,be(e,u,pn))]})})}function nP(e,t,n){let r=Se(n,new Set(["imports_statement"])),i=[];for(let o of n.rootNode.descendantsOfType("imports_statement")){let s=o.namedChildren.filter(f=>f.type==="namespace_name");if(s.length===0)continue;let a=s[s.length-1],c=s.length>1?s[0]:null,l=a.text,u=l.split(".").pop()??l,d=c?.text??u;i.push(me(u,d,be(e,l,pn),r,c?"namespace":"named"))}return i}function rP(e,t,n){let r=Se(n,new Set(["using_directive"])),i=[];for(let o of n.rootNode.descendantsOfType("using_directive")){let s=o.namedChildren;if(s.length===0)continue;let a=null,c;s.length>=2&&s[0].type==="identifier"&&(s[1].type==="qualified_name"||s[1].type==="identifier")?(a=s[0],c=s[1]):c=s[s.length-1];let l=c.text,u=l.split(".").pop()??l,d=a?.text??u;i.push(me(u,d,be(e,l,pn),r,a?"namespace":"named"))}return i}var iP=j("vue-non-script-identifiers",{clearGroups:["whole-project","source-file"]});function Gp(e,t){return iP.get(e,t,()=>{let n=new Set,r=P(e,t);if(!r)return n;let o=r.replace(/<script\b[^>]*>[\s\S]*?<\/script>/g,s=>s.replace(/[^\r\n]/g," ")).replace(/<!--[\s\S]*?-->/g,s=>s.replace(/[^\r\n]/g," ")).replace(/\/\*[\s\S]*?\*\//g,s=>s.replace(/[^\r\n]/g," "));for(let s of o.matchAll(/[A-Za-z_$][\w$]*/g))n.add(s[0]);return n})}function Fl(e,t,n){return lt(e,t,r=>sP(e,t,r),()=>oP(e,t,n))}function oP(e,t,n){return yP(n).flatMap(r=>bP(e,t,r.clause,r.specifier,r.start,r.end,n))}function sP(e,t,n){let r=aP(e,t,n),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))i.push(...cP(e,t,n,o,r));return i}function aP(e,t,n){let r=Se(n,new Set(["import_statement"]));if(Ot(t))for(let i of Gp(e,t))r.add(i);return r}function cP(e,t,n,r,i){let o=mP(r);if(!o)return[];let s=Qe(e,t,o),a=et(r,"import_clause");return a?lP(n,a,s,i,pP(r.text)):[Wn("*",s)]}function lP(e,t,n,r,i){let o=[];for(let s of t.namedChildren)if(s.type==="identifier")o.push(uP(s.text,n,r,i));else if(s.type==="namespace_import"){let a=dP(e,s,n,r,i);a&&o.push(a)}else s.type==="named_imports"&&o.push(...fP(s,n,r,i));return o}function uP(e,t,n,r){return me("default",e,t,n,"default",{isTypeOnly:r})}function dP(e,t,n,r,i){let s=et(t,"identifier")?.text??"";if(!s)return null;let a=hP(e,s);return Gn("*",n,{localName:s,usedMembers:a,isTypeOnly:i,used:a.length>0||r.has(s)})}function fP(e,t,n,r){let i=[];for(let o of e.namedChildren){if(o.type!=="import_specifier")continue;let s=o.namedChild(0),a=o.namedChild(1);if(!s)continue;let c=s.text,l=a?.text??c;i.push(me(c,l,t,n,"named",{isTypeOnly:r||gP(o.text)}))}return i}function mP(e){let t=et(e,"string");if(!t)return null;let n=et(t,"string_fragment");return n?n.text:null}function pP(e){return/^\s*import\s+type\b/.test(e)}function gP(e){return/^\s*type\b/.test(e.trim())}function hP(e,t){let n=new Set;for(let r of e.rootNode.descendantsOfType("member_expression")){let i=r.namedChild(0),o=r.namedChild(1);!i||!o||i.type!=="identifier"||i.text!==t||(o.type==="property_identifier"||o.type==="identifier")&&n.add(o.text)}return[...n]}function yP(e){let t=[],n=/^[ \t]*import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let i of e.matchAll(n)){let o=i[0],s=i[1],a=i[2];!o||!a||typeof i.index!="number"||t.push({clause:s,specifier:a,start:i.index,end:i.index+o.length})}let r=/^[ \t]*import\s+['"]([^'"]+)['"]\s*;?/gm;for(let i of e.matchAll(r)){let o=i[0],s=i[1];!o||!s||typeof i.index!="number"||t.push({clause:null,specifier:s,start:i.index,end:i.index+o.length})}return t.sort((i,o)=>i.start-o.start)}function bP(e,t,n,r,i,o,s){let a=Qe(e,t,r),c=hn(s,i,o);return n?SP(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let d=Ir(c,u.localName);return Gn(u.importedName,u.sourcePath,{localName:u.localName,usedMembers:d,used:d.length>0||We(c,u.localName),isTypeOnly:u.isTypeOnly})}return u.kind==="side-effect"?Wn(u.importedName,u.sourcePath):Wt(u.importedName,u.localName??"",u.sourcePath,u.localName?We(c,u.localName):!1,u.kind,[],{isTypeOnly:u.isTypeOnly})}):[Wn("*",a)]}function SP(e){let t=e.trim(),n=/^type\b/.test(t),r=t.replace(/^type\s+/,""),[i,o]=CP(r),s=[];return i&&s.push(...zp(i,n)),o&&s.push(...zp(o,n)),s}function zp(e,t){let n=e.trim();if(!n)return[];if(n.startsWith("{")){let r=n.slice(1,-1).trim();return r?Ge(r).map(i=>{let o=i.trim(),s=t||/^type\b/.test(o),a=o.replace(/^type\s+/,""),[c,l]=a.split(/\s+as\s+/);return{importedName:c.trim(),localName:(l??c).trim(),kind:"named",isTypeOnly:s}}):[]}return n.startsWith("* as ")?[{importedName:"*",localName:n.slice(5).trim(),kind:"namespace",isTypeOnly:t}]:[{importedName:"default",localName:n,kind:"default",isTypeOnly:t}]}function CP(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r==="{"&&t++,r==="}"&&t--,r===","&&t===0)return[e.slice(0,n).trim(),e.slice(n+1).trim()]}return[e.trim(),null]}function Ll(e,t,n){let r=V(e,t);return r?DP(e,t,r):xP(e,t,n)}function xP(e,t,n){return[...vP(e,t,n),...RP(e,t,n),...IP(e,t,n)]}function vP(e,t,n){let r=[],i=/^[ \t]*export\s+(?:type\s+)?\{([\s\S]*?)\}\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(i)){if(typeof o.index!="number")continue;let s=o[1]??"",a=o[2]??"",c=Ge(s).map(d=>wP(d.trim())).filter(d=>!!d),l=wr(n,o.index),u=wr(n,o.index+o[0].length-1);r.push({kind:"named",sourcePath:Qe(e,t,a),names:c,startLine:l,endLine:u})}return r}function RP(e,t,n){let r=[],i=/^[ \t]*export\s+\*\s+as\s+(\w+)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(i)){if(typeof o.index!="number")continue;let s=o[2]??"",a=wr(n,o.index),c=wr(n,o.index+o[0].length-1);r.push({kind:"star-as",sourcePath:Qe(e,t,s),names:[],startLine:a,endLine:c})}return r}function IP(e,t,n){let r=[],i=/^[ \t]*export\s+\*\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(i)){if(typeof o.index!="number")continue;let s=o[1]??"",a=wr(n,o.index),c=wr(n,o.index+o[0].length-1);r.push({kind:"star",sourcePath:Qe(e,t,s),names:[],startLine:a,endLine:c})}return r}function wP(e){if(!e)return null;let t=e.replace(/^type\s+/,"").trim();if(!t)return null;let n=t.match(/^(\w+)\s+as\s+(\w+)$/);if(n)return n[2]??null;let r=t.match(/^(\w+)$/);return r?r[1]??null:null}function wr(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function DP(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("export_statement")){let o=EP(e,t,i);if(o===void 0)continue;let s=i.startPosition.row,a=i.endPosition.row,c=kP(i,o,s,a);r.push(c)}return r}function EP(e,t,n){let r=et(n,"string");if(!r)return;let i=et(r,"string_fragment");if(i)return Qe(e,t,i.text)}function kP(e,t,n,r){let i=et(e,"export_clause");if(i){let s=[];for(let a of i.namedChildren){if(a.type!=="export_specifier")continue;let c=a.namedChild(0),l=a.namedChild(1);c&&s.push((l??c).text)}return{kind:"named",sourcePath:t,names:s,startLine:n,endLine:r}}return et(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:r}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:r}}function Vp(e,t,n){return hs(e,t,{java:r=>PP(e,t,r),kotlin:r=>TP(e,t,r),scala:r=>_P(e,t,r)},()=>ct(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(r,i)=>{let o=r[1]?.trim();return o?FP(e,t,o,i):[]}))}function PP(e,t,n){let r=Se(n,new Set(["import_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.children.some(d=>d.type==="asterisk"),c=o.namedChildren.find(d=>d.type==="scoped_identifier")??o.namedChildren.find(d=>d.type==="identifier");if(!c)continue;let l=c.text;if(s){i.push(Gn("*",be(e,l,Xe)));continue}let u=l.split(".").pop()??l;i.push(me(u,u,be(e,l,Xe),r))}return i}function TP(e,t,n){let r=Se(n,new Set(["import_header","import_list"])),i=[];for(let o of n.rootNode.descendantsOfType("import_header")){let s=o.namedChildren.find(m=>m.type==="identifier");if(!s)continue;let a=o.namedChildren.some(m=>m.type==="wildcard_import"),c=o.namedChildren.find(m=>m.type==="import_alias");if(a){i.push(Gn("*",be(e,s.text,Xe)));continue}let l=s.text,u=l.split(".").pop()??l,f=c?.namedChild(0)?.text??u;i.push(me(u,f,be(e,l,Xe),r))}return i}function _P(e,t,n){let r=Se(n,new Set(["import_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.namedChildren.find(d=>d.type==="namespace_selectors"||d.type==="namespace_wildcard"),a=o.namedChildren.filter(d=>d!==s&&(d.type==="identifier"||d.type==="stable_identifier")),c=a.map(d=>d.text).join(".");if(!c)continue;if(s?.type==="namespace_wildcard"){i.push(Gn("*",be(e,c,Xe)));continue}if(s?.type==="namespace_selectors"){for(let d of s.namedChildren)if(d.type==="arrow_renamed_identifier"){let[f,m]=d.namedChildren;if(!f)continue;let p=f.text,g=m?.text??p;if(p==="_")continue;i.push(me(p,g,be(e,`${c}.${p}`,Xe),r))}else if(d.type==="identifier"){let f=d.text;i.push(me(f,f,be(e,`${c}.${f}`,Xe),r))}continue}let l=a[a.length-1]?.text??c,u=a.slice(0,-1).map(d=>d.text).join(".")||c;i.push(me(l,l,be(e,u&&a.length>1?`${u}.${l}`:c,Xe),r))}return i}function FP(e,t,n,r){if(n.includes("{")&&n.includes("}")){let i=n.slice(0,n.indexOf("{")).replace(/\.$/,"").trim(),o=n.slice(n.indexOf("{")+1,n.lastIndexOf("}")).trim();return Ge(o).flatMap(s=>{let a=s.trim();if(!a)return[];let[c,l]=a.includes("=>")?a.split(/\s*=>\s*/):a.split(/\s+as\s+/),u=c?.trim();if(!u||u==="_")return[];let d=(l??u.split(".").pop()??u).trim(),f=u==="_"?i:`${i}.${u}`.replace(/\.\./g,".");return[bt(e,t,r,f,u,d)]})}return[bt(e,t,r,n,n.split(".").pop()??n,n.split(".").pop()??n)]}function Kp(e,t,n){return lt(e,t,r=>LP(e,t,r),()=>ct(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?Ge(o).flatMap(s=>{let a=s.trim();if(!a)return[];let[c,l]=a.split(/\s+as\s+/i),u=c?.trim()??a,d=u.split("\\").pop()??u,f=(l??d).trim();return[bt(e,t,i,u,d,f,be(e,u.replace(/\\/g,"."),Hn))]}):[]}))}function LP(e,t,n){let r=Se(n,new Set(["namespace_use_declaration"])),i=[],o=(s,a,c)=>{i.push(me(a,c,be(e,s.replace(/\\/g,"."),Hn),r))};for(let s of n.rootNode.descendantsOfType("namespace_use_declaration")){let a=s.namedChildren.find(c=>c.type==="namespace_use_group");if(a){let c=s.namedChildren.find(l=>l.type==="namespace_name")?.text??"";for(let l of a.namedChildren){if(l.type!=="namespace_use_clause")continue;let{importedName:u,localName:d,qualified:f}=qp(l,c);u&&o(f,u,d)}continue}for(let c of s.namedChildren){if(c.type!=="namespace_use_clause")continue;let{importedName:l,localName:u,qualified:d}=qp(c,"");l&&o(d,l,u)}}return i}function qp(e,t){let n=e.namedChildren.find(l=>l.type==="qualified_name"),r=e.namedChildren.filter(l=>l.type==="name"),i="";n?i=n.text:r.length>=1&&(i=r[0].text);let o=n&&r.length>0?r[r.length-1]:null,s=i.split("\\").pop()??i,a=o?.text??s,c=t?`${t}\\${i}`:i;return{importedName:s,localName:a,qualified:c}}function Yp(e,t,n){return lt(e,t,r=>NP(e,t,r),()=>MP(n).flatMap(r=>jP(e,t,r,n)))}function NP(e,t,n){let r=Se(n,new Set(["import_statement","import_from_statement"])),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))for(let s of o.namedChildren){let a=Jp(s);if(!a)continue;let c=vr(e,t,a.qualifiedName);i.push({importedName:a.qualifiedName,localName:a.localName,sourcePath:c,kind:"namespace",used:r.has(a.localName),usedMembers:[]})}for(let o of n.rootNode.descendantsOfType("import_from_statement")){let s=o.namedChild(0);if(!s)continue;let a=AP(s);if(a===null)continue;let c=vr(e,t,a);for(let l=1;l<o.namedChildCount;l+=1){let u=o.namedChild(l);if(u.type==="wildcard_import"){i.push({importedName:"*",localName:null,sourcePath:c,kind:"side-effect",used:!0,usedMembers:[]});continue}let d=Jp(u);d&&i.push({importedName:d.qualifiedName,localName:d.localName,sourcePath:c,kind:"named",used:r.has(d.localName),usedMembers:[]})}}return i}function Jp(e){if(e.type==="aliased_import"){let t=e.namedChild(0),n=e.namedChild(1);return!t||!n?null:{qualifiedName:t.text,localName:n.text}}if(e.type==="dotted_name"){let t=e.text;return{qualifiedName:t,localName:t.split(".")[0]??t}}return e.type==="identifier"?{qualifiedName:e.text,localName:e.text}:null}function AP(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=et(e,"import_prefix")?.text??"",n=et(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function MP(e){let t=e.split(`
114
- `),n=[],r=0;for(let i=0;i<t.length;i++){let o=t[i],s=o.trimStart(),a=r;if(r+=o.length+1,!s.startsWith("import ")&&!s.startsWith("from "))continue;let c=o,l=a+o.length,u=xi(o);for(;i+1<t.length&&(u>0||c.trimEnd().endsWith("\\"));){i++;let f=t[i];c+=`
115
- ${f}`,l+=1+f.length,u+=xi(f),r+=f.length+1}let d=OP(c);d&&n.push({...d,start:a,end:l})}return n}function OP(e){let t=e.replace(/\\\s*\n/g," ").trim();if(t.startsWith("import "))return{kind:"import",module:null,clause:t.slice(7).trim()};let n=t.match(/^from\s+([.\w]+)\s+import\s+([\s\S]+)$/);if(!n)return null;let r=n[2].trim();return r.startsWith("(")&&r.endsWith(")")&&(r=r.slice(1,-1).trim()),{kind:"from",module:n[1],clause:r}}function jP(e,t,n,r){let i=hn(r,n.start,n.end),o=n.clause.replace(/\n/g," ").trim();if(n.kind==="import")return Ge(o).flatMap(c=>{let l=c.trim().replace(/,$/,"");if(!l)return[];let[u,d]=l.split(/\s+as\s+/),f=u.trim(),m=(d??f.split(".")[0]??f).trim(),p=vr(e,t,f),g=Ir(i,m);return[{importedName:f,localName:m,sourcePath:p,kind:"namespace",used:We(i,m)||g.length>0,usedMembers:g}]});let s=n.module?vr(e,t,n.module):null,a=[];for(let c of Ge(o)){let l=c.trim().replace(/,$/,"");if(!l)continue;if(l==="*"){a.push({importedName:"*",localName:null,sourcePath:s,kind:"side-effect",used:!0,usedMembers:[]});continue}let[u,d]=l.split(/\s+as\s+/),f=(d??u).trim();a.push({importedName:u.trim(),localName:f,sourcePath:s,kind:"named",used:We(i,f),usedMembers:[]})}return a}import{basename as $P}from"path";function Xp(e,t,n){return lt(e,t,r=>HP(e,t,r),()=>BP(e,t,n))}function BP(e,t,n){return ct(n,/^[ \t]*(require_relative|require)\s+["']([^"']+)["']\s*$/gm,(r,i)=>{let o=r[1],s=r[2];if(!o||!s)return[];let a=o==="require_relative"?as(e,t,s):null;if(a){let c=Qp(s);return[Wt(c,c,a,We(i,c))]}return[Wn(s,a)]})}function HP(e,t,n){let r=Se(n,new Set([])),i=[],o=new Set(["require","require_relative","load"]);for(let s of n.rootNode.descendantsOfType("call")){let a=s.namedChild(0);if(!a||a.type!=="identifier"||!o.has(a.text))continue;let l=s.namedChildren.find(m=>m.type==="argument_list")?.namedChild(0);if(!l||l.type!=="string")continue;let d=l.namedChildren.find(m=>m.type==="string_content")?.text;if(!d)continue;let f=a.text==="require_relative"?as(e,t,d):null;if(f){let m=Qp(d);i.push(me(m,m,f,r))}else i.push(Wn(d,f))}return i}function Qp(e){return es($P(e).replace(/\.[^.]+$/,""),/_/)}function Zp(e,t,n){return lt(e,t,r=>UP(e,t,r),()=>ct(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?WP(e,t,o,i):[]}))}function UP(e,t,n){let r=Se(n,new Set(["use_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("use_declaration")){let s=o.namedChild(0);if(s)for(let a of vi(s,"")){if(!a.importedName||a.importedName==="*")continue;let c=Bt(e,t,a.qualifiedName)??Bt(e,t,a.qualifiedName.split("::").slice(0,-1).join("::"));i.push(me(a.importedName,a.localName,c,r))}}return i}function vi(e,t){switch(e.type){case"identifier":case"super":case"crate":{let n=e.text;return[{qualifiedName:Dr(t,n),importedName:n,localName:n}]}case"self":{let n=t.split("::").filter(Boolean).pop()??"self";return[{qualifiedName:t||"self",importedName:n,localName:n}]}case"scoped_identifier":{let n=e.text,r=n.split("::").pop()??n;return[{qualifiedName:Dr(t,n),importedName:r,localName:r}]}case"scoped_use_list":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=Dr(t,n.text),o=[];for(let s of r.namedChildren)o.push(...vi(s,i));return o}case"use_list":{let n=[];for(let r of e.namedChildren)n.push(...vi(r,t));return n}case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=vi(n,t),o=r.text;return i.map(s=>({...s,localName:o}))}case"use_wildcard":{let n=e.namedChild(0),r=n?n.text:"";return[{qualifiedName:Dr(t,`${r}::*`),importedName:"*",localName:"*"}]}default:return[]}}function Dr(e,t){return e?t?`${e}::${t}`:e:t}function WP(e,t,n,r){let i=n.trim();if(i.includes("{")&&i.includes("}")){let u=i.slice(0,i.indexOf("{")).replace(/::$/,"").trim(),d=i.slice(i.indexOf("{")+1,i.lastIndexOf("}")).trim();return Ge(d).flatMap(f=>{let m=f.trim();if(!m)return[];if(m==="self"){let x=u.split("::").filter(Boolean).pop();return x?[bt(e,t,r,u,x,x)]:[]}let[p,g]=m.split(/\s+as\s+/),h=p?.trim();if(!h)return[];let S=(g??h.split("::").pop()??h).trim(),C=`${u}::${h}`.replace(/::::/g,"::");return[bt(e,t,r,C,h.split("::").pop()??h,S,Bt(e,t,u))]})}let[o,s]=i.split(/\s+as\s+/),a=o?.trim()??i,c=(s??a.split("::").pop()??a).trim(),l=Bt(e,t,a)??Bt(e,t,a.split("::").slice(0,-1).join("::"));return[bt(e,t,r,a,a.split("::").pop()??a,c,l)]}function eg(e,t,n){let r=V(e,t);if(r)return GP(e,t,r);let i=[];for(let o of n.matchAll(/^[ \t]*pub\s+use\s+(.+?)\s*;$/gm)){let s=o[1]?.trim();s&&i.push(...VP(e,t,s))}return i}function GP(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("use_declaration")){if(!zP(i))continue;let o=i.namedChildren.find(s=>s.type!=="visibility_modifier");if(o)for(let s of vi(o,""))s.importedName&&r.push(Nl(e,t,s.qualifiedName))}return r}function zP(e){for(let t of e.children)if(t.type==="visibility_modifier"&&t.text.startsWith("pub"))return!0;return!1}function VP(e,t,n){let r=n.trim();if(r.includes("{")&&r.includes("}")){let i=r.slice(0,r.indexOf("{")).replace(/::$/,"").trim(),o=r.slice(r.indexOf("{")+1,r.lastIndexOf("}")).trim();return Ge(o).flatMap(s=>{let a=s.trim();if(!a||a==="self")return[];let[c]=a.split(/\s+as\s+/),l=`${i}::${c?.trim()??a}`.replace(/::::/g,"::");return[Nl(e,t,l)]})}return[Nl(e,t,r)]}function Nl(e,t,n){return{specifier:n,sourcePath:Bt(e,t,n)??Bt(e,t,n.split("::").slice(0,-1).join("::"))}}function yn({language:e,extensions:t,imports:n,parseImports:r}){return{language:e,extensions:t,capabilities:{imports:n},parseImports:r}}function tg(e,t){let n=t.toLowerCase();for(let r of e)for(let i of r.extensions)if(n.endsWith(i))return r;return null}var qP={language:"javascript",extensions:$n,capabilities:{imports:"ast-with-regex-fallback",reExports:"ast-with-regex-fallback"},parseImports:Fl,parseReExports:Ll},KP=yn({language:"python",extensions:ns,imports:"ast-with-regex-fallback",parseImports:Yp}),JP=yn({language:"jvm",extensions:Xe,imports:"ast-dispatch-with-regex-fallback",parseImports:Vp}),YP={language:"rust",extensions:rs,capabilities:{imports:"ast-with-regex-fallback",exports:"ast-with-regex-fallback"},parseImports:Zp,parseExports:eg},XP=yn({language:"ruby",extensions:is,imports:"ast-with-regex-fallback",parseImports:Xp}),QP=yn({language:"c/cpp",extensions:os,imports:"ast-with-regex-fallback",parseImports:jp}),ZP=yn({language:"dotnet",extensions:pn,imports:"ast-dispatch-with-regex-fallback",parseImports:Wp}),eT={language:"dart",extensions:ss,capabilities:{imports:"regex-only",exports:"regex-only"},parseImports:Hp,parseExports:Up},tT=yn({language:"php",extensions:Hn,imports:"ast-with-regex-fallback",parseImports:Kp}),nT=yn({language:"clojure",extensions:xr,imports:"regex-only",parseImports:Bp}),ng=[qP,KP,JP,YP,XP,QP,ZP,eT,tT,nT];function Ss(e){return tg(ng,e)}function F8(e){return ng.find(n=>n.language===e)?.capabilities??null}var Al={clearGroups:["whole-project","source-file"]},rT=j("source-imports",Al),iT=j("source-exports",Al),oT=j("source-reexports",Al),rg=re({kind:"source-imports",invalidation:q("source-imports"),serialize:sT,deserialize:aT}),ig=re({kind:"source-reexports",invalidation:q("source-reexports"),serialize:cT,deserialize:lT});function zn(e,t){let n=ee(t);return oT.get(e,n,()=>{let r=Ss(n);if(!r?.parseReExports)return[];let i=P(e,n);if(!i)return[];let o=ae(e,n,i),s=xl(e),a=ig.read(e,n,o);if(a?.resolutionFingerprint===s)return a.reExports;let c=r.parseReExports(e,n,i);return ig.write(e,n,o,{resolutionFingerprint:s,reExports:c}),c})}function ne(e,t){let n=ee(t);return rT.get(e,n,()=>{let r=Ss(n);if(!r)return[];let i=P(e,n);if(!i)return[];let o=ae(e,n,i),s=xl(e),a=rg.read(e,n,o);if(a?.resolutionFingerprint===s)return a.imports;let c=r.parseImports(e,n,i);return rg.write(e,n,o,{resolutionFingerprint:s,imports:c}),c})}function Cs(e,t){let n=ee(t);return iT.get(e,n,()=>{let r=Ss(n);if(!r?.parseExports)return[];let i=P(e,n);return i?r.parseExports(e,n,i):[]})}function sT(e){return JSON.stringify(e)}function aT(e){try{let t=JSON.parse(e);return!Ze(t)||typeof t.resolutionFingerprint!="string"||!Array.isArray(t.imports)?null:{resolutionFingerprint:t.resolutionFingerprint,imports:t.imports}}catch{return null}}function cT(e){return JSON.stringify(e)}function lT(e){try{let t=JSON.parse(e);return!Ze(t)||typeof t.resolutionFingerprint!="string"||!Array.isArray(t.reExports)?null:{resolutionFingerprint:t.resolutionFingerprint,reExports:t.reExports}}catch{return null}}function dt(e){return{forFile(t,n){return og(e,t,n)},forFiles(t,n){let r=new Map;for(let i of t)r.set(i,og(e,i,n));return r}}}function og(e,t,n){let r={file:t},i=n.facts||n.identifiers;if(n.text&&(r.text=P(e,t)),n.lines&&(r.lines=Ce(e,t)),n.ast&&(r.ast=V(e,t)),n.imports&&(r.imports=ne(e,t)),n.reexports&&(r.reexports=zn(e,t)),i){let o=rl(e,t),s=o.facts;n.facts&&(r.facts=s),o.unavailable&&(r.sourceFactsUnavailable=o.unavailable),n.identifiers&&s&&(r.identifiers=s.fileIdentifiers,r.identifierLineMap=s.identifierLineMap)}return r}function Vn(e,t){return e.all(`SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.start_char, der.end_line, der.end_char, d.relative_path, gs.display_name, gs.documentation
116
- FROM global_symbols gs
117
- JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
118
- JOIN documents d ON der.document_id = d.id
119
- WHERE ${t.where}
120
- ${e.pathExclusionsFor("d")}
121
- ${ag(t.orderBy)}
122
- ${cg(t.limit)}`,...t.params??[])}function Er(e,t){return e.all(`SELECT
123
- gs.id,
124
- gs.symbol,
125
- c.document_id,
126
- MIN(c.start_line) AS start_line,
127
- 0 AS start_char,
128
- MAX(c.end_line) AS end_line,
129
- 0 AS end_char,
130
- d.relative_path,
131
- gs.display_name,
132
- gs.documentation
133
- FROM global_symbols gs
134
- JOIN mentions m ON m.symbol_id = gs.id
135
- JOIN chunks c ON m.chunk_id = c.id
136
- JOIN documents d ON c.document_id = d.id
137
- WHERE m.role = 1
138
- AND ${t.where}
139
- ${e.pathExclusionsFor("d")}
140
- GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name, gs.documentation
141
- ${ag(t.orderBy)}
142
- ${cg(t.limit)}`,...t.params??[])}function ag(e){return e?`ORDER BY ${e}`:""}function cg(e){return typeof e=="number"?`LIMIT ${e}`:""}function Gt(e){return!e||!e.trim()?null: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()||null}function zt(e){if(!e)return null;let t=sg(e);if(t)return t.replace(/\n/g," ");let n=e.indexOf("|");if(n===-1)return e.replace(/\n/g," ");let r=e.slice(n+1);return(sg(r)??r).replace(/\n/g," ")}function sg(e){return/^```(?:\w+)?\s*\n?([\s\S]*?)\n?```/.exec(e.trimStart())?.[1]?.trim()||null}function uT(e,t={}){if(Rt(e.symbol)!==null)return t.includeClassMemberFallbacks===!0;let i=(e.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(i)}function bn(e,t,n={}){let r=new Map;for(let o of t)e.length>0&&!uT(o,{includeClassMemberFallbacks:n.includeClassMemberFallbacks})||r.set(o.id,o);for(let o of e)r.set(o.id,o);let i=[...r.values()];return n.sort?i.sort((o,s)=>o.start_line-s.start_line||o.end_line-s.end_line||o.symbol.localeCompare(s.symbol)):i}var dT=j("file-definitions",{clearGroups:["definition-catalog"]}),fT=j("file-function-like-definitions",{clearGroups:["definition-catalog"]}),lg=new WeakMap;function X(e,t,n={}){return n.includeClassMemberFallbacks?Ml(e,t,void 0,{includeClassMemberFallbacks:!0}):dT.get(e,t,()=>{let r=mg(e,t);if(r)return r;let i=Ml(e,t),o=Te(e),s=dt(e).forFile(t,{text:!0}).text;return o&&s&&fg.write(e,t,ae(e,t,s),{projectFingerprint:o,definitions:i.map(a=>({...a}))}),i})}function mT(e,t){return fT.get(e,t,()=>{let n=mg(e,t);return n?n.filter(r=>r.isFunctionLike):Ml(e,t,r=>r.isFunctionLike)})}var fg=re({kind:"file-definitions",invalidation:q("file-definitions"),serialize:pT,deserialize:gT});function mg(e,t){let n=Te(e);if(!n)return null;let r=dt(e).forFile(t,{text:!0}).text;if(!r)return null;let i=fg.read(e,t,ae(e,t,r));return i?hT(i,n,t):null}function pT(e){return JSON.stringify(e)}function gT(e){try{let t=JSON.parse(e);return!Ze(t)||typeof t.projectFingerprint!="string"||!Array.isArray(t.definitions)?null:{projectFingerprint:t.projectFingerprint,definitions:t.definitions}}catch{return null}}function hT(e,t,n){if(e.projectFingerprint!==t)return null;let r=[];for(let i of e.definitions){let o=yT(i,n);if(!o)return null;r.push(o)}return r}function yT(e,t){return!Ze(e)||typeof e.symbolId!="number"||typeof e.symbol!="string"||typeof e.documentId!="number"||typeof e.startLine!="number"||typeof e.startChar!="number"&&e.startChar!==void 0||typeof e.endLine!="number"||typeof e.endChar!="number"&&e.endChar!==void 0||e.relativePath!==t||typeof e.leaf!="string"||typeof e.parentTypeName!="string"&&e.parentTypeName!==null||typeof e.isFunctionLike!="boolean"||typeof e.isTypeLike!="boolean"||typeof e.kind!="number"&&e.kind!==null||typeof e.documentation!="string"&&e.documentation!==null||typeof e.enclosingSymbol!="string"&&e.enclosingSymbol!==null?null:{symbolId:e.symbolId,symbol:e.symbol,documentId:e.documentId,startLine:e.startLine,startChar:e.startChar,endLine:e.endLine,endChar:e.endChar,relativePath:e.relativePath,leaf:e.leaf,parentTypeName:e.parentTypeName,isFunctionLike:e.isFunctionLike,isTypeLike:e.isTypeLike,kind:e.kind,documentation:e.documentation,enclosingSymbol:e.enclosingSymbol}}function Ml(e,t,n,r={}){let i=bn(bT(e,t),ST(e,t),{sort:!0,includeClassMemberFallbacks:r.includeClassMemberFallbacks}).map(pg);return n&&(i=i.filter(n)),yg(e,t,i)}function bT(e,t){return e.all(`SELECT
143
- gs.id,
144
- gs.symbol,
145
- der.document_id,
146
- der.start_line,
147
- der.start_char,
148
- der.end_line,
149
- der.end_char,
150
- d.relative_path,
151
- gs.display_name,
152
- gs.kind,
153
- gs.documentation,
154
- gs.enclosing_symbol
155
- FROM global_symbols gs
156
- JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
157
- JOIN documents d ON der.document_id = d.id
158
- WHERE d.relative_path = ?
159
- ${e.symbolNoiseFor("gs")}
160
- ORDER BY der.start_line, der.end_line`,t)}function ST(e,t){return e.all(`SELECT
161
- gs.id,
162
- gs.symbol,
163
- c.document_id,
164
- MIN(c.start_line) AS start_line,
165
- 0 AS start_char,
166
- MAX(c.end_line) AS end_line,
167
- 0 AS end_char,
168
- d.relative_path,
169
- gs.display_name,
170
- gs.kind,
171
- gs.documentation,
172
- gs.enclosing_symbol
173
- FROM global_symbols gs
174
- JOIN mentions m ON m.symbol_id = gs.id
175
- JOIN chunks c ON m.chunk_id = c.id
176
- JOIN documents d ON c.document_id = d.id
177
- WHERE d.relative_path = ?
178
- AND m.role = 1
179
- ${e.symbolNoiseFor("gs")}
180
- GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
181
- ORDER BY start_line, end_line`,t)}function pg(e){return{symbolId:e.id,symbol:e.symbol,documentId:e.document_id,startLine:e.start_line,startChar:e.start_char??0,endLine:e.end_line,endChar:e.end_char??0,relativePath:e.relative_path,leaf:T(e.symbol),parentTypeName:Rt(e.symbol),isFunctionLike:Z(e.symbol),isTypeLike:le(e.symbol)==="type",kind:e.kind??null,documentation:e.documentation??null,enclosingSymbol:e.enclosing_symbol??null}}function ve(e,t={}){return Ol(e,t.scope)}function Ol(e,t){return N(e,{scope:t,includeIgnored:!1}).flatMap(n=>X(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function gg(e,t){return N(e,{scope:t,includeIgnored:!1}).flatMap(n=>mT(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function Ri(e,t){let n=ug(CT(e,t.scope,t.sqlPrefilter)),r=ug(xT(e,t.scope,t.sqlPrefilter)),i=new Set([...n.keys(),...r.keys()]),o=[];for(let s of[...i].sort()){if(e.isIgnored(s))continue;let a=bn(n.get(s)??[],r.get(s)??[],{sort:!0}).filter(c=>t.symbolMatches(c.symbol));a.length!==0&&o.push(...yg(e,s,a.map(pg)))}return o}function CT(e,t,n){let r=t?"AND d.relative_path LIKE ?":"",i=n?`AND ${hg("gs",n)}`:"",o=t?[`%${t}%`]:[];return e.all(`SELECT
182
- gs.id,
183
- gs.symbol,
184
- der.document_id,
185
- der.start_line,
186
- der.start_char,
187
- der.end_line,
188
- der.end_char,
189
- d.relative_path,
190
- gs.display_name,
191
- gs.kind,
192
- gs.documentation,
193
- gs.enclosing_symbol
194
- FROM global_symbols gs
195
- JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
196
- JOIN documents d ON der.document_id = d.id
197
- WHERE 1 = 1
198
- ${e.pathExclusionsFor("d")}
199
- ${r}
200
- ${i}
201
- ${e.symbolNoiseFor("gs")}
202
- ORDER BY d.relative_path, der.start_line, der.end_line`,...o)}function xT(e,t,n){let r=t?"AND d.relative_path LIKE ?":"",i=n?`AND ${hg("gs",n)}`:"",o=t?[`%${t}%`]:[];return e.all(`SELECT
203
- gs.id,
204
- gs.symbol,
205
- c.document_id,
206
- MIN(c.start_line) AS start_line,
207
- 0 AS start_char,
208
- MAX(c.end_line) AS end_line,
209
- 0 AS end_char,
210
- d.relative_path,
211
- gs.display_name,
212
- gs.kind,
213
- gs.documentation,
214
- gs.enclosing_symbol
215
- FROM global_symbols gs
216
- JOIN mentions m ON m.symbol_id = gs.id
217
- JOIN chunks c ON m.chunk_id = c.id
218
- JOIN documents d ON c.document_id = d.id
219
- WHERE m.role = 1
220
- ${e.pathExclusionsFor("d")}
221
- ${r}
222
- ${i}
223
- ${e.symbolNoiseFor("gs")}
224
- GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
225
- ORDER BY d.relative_path, start_line, end_line`,...o)}function vT(e){return`(${e}.symbol LIKE '%().' OR ${e}.symbol LIKE '%()')`}function hg(e,t){return t==="callable"?vT(e):RT(e)}function RT(e){return`(${e}.symbol LIKE '%.' OR ${e}.symbol LIKE '%()')`}function ug(e){let t=new Map;for(let n of e){let r=t.get(n.relative_path);r?r.push(n):t.set(n.relative_path,[n])}return t}function xs(e,t,n={}){if(t.length===0)return[];let r=t.flatMap(i=>X(e,i)).filter(i=>!e.isIgnored(i.relativePath));return n.onlyDocumented&&(r=r.filter(i=>i.documentation!==null&&i.documentation!=="")),n.sort&&(r=r.sort((i,o)=>i.relativePath.localeCompare(o.relativePath)||i.startLine-o.startLine||i.endLine-o.endLine)),r.map(i=>({startLine:i.startLine,endLine:i.endLine,symbol:i.symbol,shortName:w(i.symbol),signature:Gt(zt(i.documentation)),relativePath:i.relativePath,enclosingSymbol:i.enclosingSymbol}))}function jl(e){let t=new Map,n=e.map((r,i)=>({definition:r,index:i,span:r.endLine-r.startLine})).sort((r,i)=>r.span-i.span||r.index-i.index);for(let{definition:r}of n)for(let i=r.startLine;i<=r.endLine;i+=1)t.has(i)||t.set(i,r);return t}function It(e,t){let n=lg.get(e);return n||(n=jl(e),lg.set(e,n)),n.get(t)??null}function vs(e,t){let n=X(e,t.relative_path).find(r=>r.symbolId===t.id);return n?{symbolId:n.symbolId,symbol:n.symbol,documentId:n.documentId,startLine:n.startLine,startChar:n.startChar,endLine:n.endLine,endChar:n.endChar,relativePath:n.relativePath}:{symbolId:t.id,symbol:t.symbol,documentId:t.document_id,startLine:t.start_line,startChar:t.start_char??0,endLine:t.end_line,endChar:t.end_char??0,relativePath:t.relative_path}}function yg(e,t,n){let r=dt(e).forFile(t,{text:!0}).text,i=ol(e,t);return i?PT(n,i,r):r?IT(n,r):n}function IT(e,t){let n=t.split(/\r?\n/),r=wT(e,n),i=DT(e,r),o=ET(i,n);return kT(e,o)}function wT(e,t){let n=e.some(i=>Rs(i.symbol))?MT(t):null,r=new Map;for(let i of e)r.set(i.symbolId,AT(t,n,i));return r}function DT(e,t){return e.filter(n=>Rs(n.symbol)).map(n=>({definition:n,startLine:t.get(n.symbolId)??n.startLine})).sort((n,r)=>n.startLine-r.startLine||n.definition.startLine-r.definition.startLine||n.definition.symbol.localeCompare(r.definition.symbol))}function ET(e,t){let n=new Map;for(let r=0;r<e.length;r+=1){let i=e[r],o=e[r+1],s=o?Math.max(i.startLine,o.startLine-1):t.length-1;n.set(i.definition.symbolId,{startLine:i.startLine,endLine:OT(t,i.definition,i.startLine,s)})}return n}function kT(e,t){return e.map(n=>{let r=t.get(n.symbolId);return r?{...n,startLine:r.startLine,endLine:r.endLine}:n})}function PT(e,t,n=null){let r=new Map;for(let i of t){let o=r.get(i.name);o?o.push(i):r.set(i.name,[i])}return e.map(i=>{if(!NT(i)||!i.leaf)return dg(i,n);let o=r.get(i.leaf);if(!o||o.length===0)return dg(i,n);let s=n?TT(i,o,n):null;if(s)return{...i,startLine:s.startLine,endLine:s.endLine};let a=o[0],c=Math.abs(a.startLine-i.startLine);for(let l=1;l<o.length;l+=1){let u=o[l],d=Math.abs(u.startLine-i.startLine);d<c&&(a=u,c=d)}return{...i,startLine:a.startLine,endLine:a.endLine}})}function TT(e,t,n){let r=_T(e.symbol);if(!r)return null;let i=n.split(/\r?\n/),o=new RegExp(`\\b${B(r)}\\b`);for(let s of t){let a=FT(i,s.startLine);if(a&&o.test(a))return s}return null}function _T(e){return e.match(/\/impl#\[([^\]]+)\]/)?.[1]??null}function FT(e,t){for(let n=t;n>=0;n-=1){let r=e[n]?.trim()??"";if(r){if(/^impl\b/.test(r))return LT(e,n,t);if(/^(?:struct|enum|trait|mod)\b/.test(r))return null}}return null}function LT(e,t,n){let r=[];for(let i=t;i<=n;i+=1){let o=e[i]??"";if(r.push(o),o.includes("{"))break}return r.join(" ")}function NT(e){return Rs(e.symbol)?!0:le(e.symbol)==="term"&&Rt(e.symbol)===null}function dg(e,t){if(!t||!e.leaf||le(e.symbol)!=="term"||Rt(e.symbol)!==null)return e;let n=B(e.leaf),r=new RegExp(`\\b(?:export\\s+)?(?:const|let|var)\\s+${n}\\b`),o=t.split(/\r?\n/).findIndex(s=>r.test(s));return o>=0?{...e,startLine:o,endLine:o}:e}function AT(e,t,n){if(!Rs(n.symbol))return n.startLine;let r=Math.max(0,Math.min(n.startLine,e.length-1));if(!t)return r;let i=t.get(n.leaf);if(!i||i.length===0)return r;let o=null;for(let s of i){let a=Math.abs(s-n.startLine);(!o||a<o.distance)&&(o={line:s,distance:a})}return o?.line??r}function MT(e){let t=/\b(?:function|def|fn)\s+([A-Za-z_$][\w$]*)/g,n=/\b([A-Za-z_$][\w$]*)\s*[:=]\s*(?:async\s*)?(?:function\b|\()/g,r=/^\s*(?:(?:export|public|private|protected|static|readonly|async|abstract|get|set)\s+)*([A-Za-z_$][\w$]*)\s*(?:<[^(]*>)?\s*\(/,i=/\b([A-Za-z_$][\w$]*)\s*\(/g,o=new Map,s=(a,c)=>{let l=o.get(a);if(!l){o.set(a,[c]);return}l[l.length-1]!==c&&l.push(c)};for(let a=0;a<e.length;a+=1){let c=e[a]??"";for(let u of c.matchAll(t))u[1]&&s(u[1],a);for(let u of c.matchAll(n))u[1]&&s(u[1],a);let l=c.match(r);l?.[1]&&s(l[1],a);for(let u of c.matchAll(i))u[1]&&s(u[1],a)}return o}function OT(e,t,n,r){let i=Math.max(n,Math.min(e.length-1,r)),o=Math.max(n,Math.min(i,t.endLine)),s=0,a=0,c=!1;for(let l=n;l<=i;l+=1){let u=jT(e[l]??"");for(let d of u)d==="{"?(s+=1,c=!0):d==="}"?s=Math.max(0,s-1):d==="("?a+=1:d===")"&&(a=Math.max(0,a-1));if(c&&s===0||!c&&a===0&&l>=o)return l}return o}function jT(e){let t="",n=null,r=!1;for(let i=0;i<e.length;i+=1){let o=e[i],s=e[i+1];if(!n&&o==="/"&&s==="/"){t+=" ".repeat(e.length-i);break}if(n){if(r){r=!1,t+=" ";continue}if(o==="\\"){r=!0,t+=" ";continue}o===n&&(n=null),t+=" ";continue}if(o==='"'||o==="'"||o==="`"){n=o,t+=" ";continue}t+=o}return t}function Rs(e){return e.includes("().")}function Is(e){let t=ye(e);if("kind"in t)return[];let n=[];for(let r=t.descriptors.length-2;r>=0;r-=1){let i=t.descriptors[r];i?.suffix==="type"&&i.name&&n.push(i.name)}return n}var $T=j("symbol-resolution",{clearGroups:[]});function $(e,t){return wi(e,t).match}function wi(e,t){return $T.get(e,t,()=>{let n=Sg(e,t.trim()).filter(o=>!e.isIgnored(o.relative_path));if(n.length>0)return Ii(e,n);let r=VT(e,t);if(r&&!e.isIgnored(r.relative_path))return Ii(e,[r]);let i=BT(e,t);return i.length>0?Ii(e,i):GT(e,t)})}function BT(e,t){let n=Ds(t),r=$l(n);if(!r)return[];let i=`%${r.path}%`,o=r.leaf;return HT(e,i,o,n)}function HT(e,t,n,r){let i=bn([],[...UT(e,t,n),...WT(e,t,n)]).filter(o=>!e.isIgnored(o.relative_path)).filter(o=>kr(o,r)>1);return i.sort((o,s)=>kr(s,r)-kr(o,r)||o.end_line-o.start_line-(s.end_line-s.start_line)||o.start_line-s.start_line||o.symbol.localeCompare(s.symbol)),i}function UT(e,t,n){return Vn(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function WT(e,t,n){return Er(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function GT(e,t){let n=Ds(t),r=QT(t),i=YT(e,r),o=ZT(i,t,n).filter(a=>!e.isIgnored(a.relative_path));if(o.length>0)return Ii(e,o);let s=[];for(let a of i){if(e.isIgnored(a.relative_path))continue;let c=XT(a,t,n,r);c<=0||s.push({row:a,score:c})}return s.sort((a,c)=>c.score-a.score||a.row.end_line-a.row.start_line-(c.row.end_line-c.row.start_line)||a.row.relative_path.localeCompare(c.row.relative_path)||a.row.symbol.localeCompare(c.row.symbol)),Ii(e,s.map(a=>a.row))}function Ii(e,t){let n=t.map(i=>vs(e,i)),r=n[0]??null;return{match:r,candidates:r?zT(n,r):[],total:n.length}}function zT(e,t){let n=new Set([`${t.symbolId}:${t.relativePath}:${t.startLine}`]),r=[];for(let i of e){let o=`${i.symbolId}:${i.relativePath}:${i.startLine}`;if(!n.has(o)&&(n.add(o),r.push({symbol:i.symbol,shortName:w(i.symbol),relativePath:i.relativePath,startLine:i.startLine}),r.length>=5))break}return r}function VT(e,t){let n=t.match(/^(.+):(\d+)-(\d+)$/);if(!n)return;let[,r,i,o]=n,s=Math.max(0,parseInt(i,10)-1),a=Math.max(s,parseInt(o,10)-1);return qT(e,r,s,a)??KT(e,r,s,a)}function qT(e,t,n,r){return Vn(e,{where:"d.relative_path LIKE ? AND der.start_line <= ? AND der.end_line >= ?",params:[`%${t}%`,n,r],orderBy:"(der.end_line - der.start_line) ASC",limit:1})[0]}function KT(e,t,n,r){return Er(e,{where:"d.relative_path LIKE ? AND c.start_line <= ? AND c.end_line >= ?",params:[`%${t}%`,n,r],orderBy:"(MAX(c.end_line) - MIN(c.start_line)) ASC",limit:1})[0]}function Di(e,t){let n=Sg(e,t).find(r=>!e.isIgnored(r.relative_path));return n?vs(e,n):null}function Sg(e,t){let n=Vn(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, der.start_line"}),r=n.length>0?[]:Er(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, start_line"});return bn(n,r)}function ws(e,t){if("symbol"in t&&"relativePath"in t)return t;let n=JT(e,t.symbolId)[0];return n?vs(e,n):null}function JT(e,t){let n=Vn(e,{where:"gs.id = ?",params:[t],orderBy:"der.start_line, der.end_line"}),r=Er(e,{where:"gs.id = ?",params:[t],orderBy:"start_line, end_line"});return bn(n,r)}function YT(e,t){let n=t.map(()=>"(gs.symbol LIKE ? OR d.relative_path LIKE ? OR COALESCE(gs.display_name, '') LIKE ?)"),r=t.flatMap(a=>{let c=`%${a}%`;return[c,c,c]}),i=n.join(`
226
- AND `),o=Vn(e,{where:i,params:r,limit:200}),s=Er(e,{where:i,params:r,limit:200});return bn(o,s)}function XT(e,t,n,r){let i=t.trim(),o=n,s=o.replace(/\(\)$/,""),a=t.toLowerCase(),c=n.toLowerCase(),l=c.replace(/\(\)$/,""),u=e.symbol,d=w(e.symbol),f=T(e.symbol),m=e.display_name??"",p=e.symbol.toLowerCase(),g=d.toLowerCase(),h=f.toLowerCase(),S=m.toLowerCase(),C=e.relative_path.toLowerCase(),x=/[/:.]/.test(n),b=$l(n),y=b?.leaf.toLowerCase(),R=0;return(u===i||u===o)&&(R+=1150),(d===i||d===o)&&(R+=1100),m===s&&(R+=1180),f===s&&(R+=1160),(`${f}()`===i||`${f}()`===o)&&(R+=955),(p===a||p===c)&&(R+=1e3),(g===a||g===c)&&(R+=950),(C===a||C===c)&&(R+=925),(C.endsWith(`/${c}`)||C.endsWith(`/${a}`))&&(R+=875),S===l&&(R+=850),h===l&&(R+=825),(`${h}()`===a||`${h}()`===c)&&(R+=820),(g.endsWith(`:${c}`)||g.endsWith(`:${l}`)||g.endsWith(`:${l}()`))&&(R+=800),p.includes(c)&&(R+=120),g.includes(c)&&(R+=140),C.includes(c)&&(R+=140),S.includes(c)&&(R+=110),r.every(v=>{let E=v.toLowerCase();return p.includes(E)||g.includes(E)||C.includes(E)||S.includes(E)})&&(R+=100+r.length*15),b&&C.includes(b.path.toLowerCase())&&(R+=360,y&&(h===y||`${h}()`===y||`${h}()`==`${y}()`)&&(R+=700),ce(e.symbol)&&(R+=180)),Z(e.symbol)&&h===l&&(R+=60),!x&&dn(e.symbol)&&(R-=160),R-=Math.min(50,Math.max(0,e.end_line-e.start_line)),R}function $l(e){let t=e.trim().replace(/\\/g,"/"),n=t.lastIndexOf("/");if(n<=0||n===t.length-1)return null;let r=t.slice(n+1).replace(/\(\)$/,"");return!r||r.includes(".")?null:{path:t.slice(0,n),leaf:r}}function Ds(e){return e.trim().replace(/\(\)$/,"").replace(/\(.*$/,"")}function QT(e){let t=Ds(e),n=t.split(/[^A-Za-z0-9_]+/).map(r=>r.trim()).filter(r=>r.length>0);return n.length>0?[...new Set(n)]:[t]}function ZT(e,t,n){let r=t.trim(),i=e.filter(o=>{let s=w(o.symbol),a=(o.display_name??"").trim();return o.symbol===r||s===r||s===n||a===r||a===n||`${a}()`===r||kr(o,n)>1||o.relative_path===r});return i.length===0?[]:(i.sort((o,s)=>kr(s,n)-kr(o,n)||o.end_line-o.start_line-(s.end_line-s.start_line)||o.relative_path.localeCompare(s.relative_path)||o.symbol.localeCompare(s.symbol)),i)}function kr(e,t){let n=$l(t);if(!n)return 0;let r=e.relative_path.toLowerCase(),i=T(e.symbol).toLowerCase(),o=n.path.toLowerCase(),s=n.leaf.toLowerCase();return r.includes(o)?i!==s?1:ce(e.symbol)?Rt(e.symbol)===null?5:4:Rt(e.symbol)===null?3:2:0}function pZ(e,t,n=5){let r=bg(t);if(!r)return[];let i=Vn(e,{where:"1 = 1",orderBy:"d.relative_path, der.start_line",limit:5e3}),o=new Map;for(let s of i){if(e.isIgnored(s.relative_path))continue;let a=w(s.symbol),c=T(s.symbol),l=s.display_name??c,u=[a,c,l].filter(m=>m.trim().length>0),d=Math.min(...u.map(m=>e_(bg(m),r))),f=o.get(a);(!f||d<f.distance)&&o.set(a,{shortName:a,distance:d})}return[...o.values()].sort((s,a)=>s.distance-a.distance||s.shortName.localeCompare(a.shortName)).slice(0,n).map(s=>s.shortName)}function bg(e){return Ds(e).toLowerCase().replace(/[^a-z0-9_]+/g,"")}function e_(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;let n=Array.from({length:t.length+1},(r,i)=>i);for(let r=0;r<e.length;r++){let i=[r+1];for(let o=0;o<t.length;o++){let s=e[r]===t[o]?0:1;i[o+1]=Math.min(i[o]+1,n[o+1]+1,n[o]+s)}n=i}return n[t.length]}function Es(e,t,n,r={}){if(!n)return[];let i=P(e,t);return i?i.indexOf(n)===-1?[]:(Vt(e,t).get(n)??[]).filter(s=>!t_(s,r)):[]}function t_(e,t){return typeof t.excludeStartLine=="number"&&typeof t.excludeEndLine=="number"&&e>=t.excludeStartLine&&e<=t.excludeEndLine}var n_=j("file-identifiers",{clearGroups:["whole-project","source-file"]});function Cg(e,t){let n=W(e,t);return n?n.fileIdentifiers:n_.get(e,t,()=>new Set(Vt(e,t).keys()))}var r_=j("file-ident-lines",{clearGroups:["whole-project","source-file"]});function Vt(e,t){let n=W(e,t);return n?n.identifierLineMap:r_.get(e,t,()=>o_(e,t))}var i_=j("file-idents-by-line",{clearGroups:["whole-project","source-file"]});function xg(e,t){let n=W(e,t);return n?n.identifiersByLine:i_.get(e,t,()=>{let r=Vt(e,t),i=0;for(let s of r.values()){let a=s[s.length-1];a!==void 0&&a>i&&(i=a)}let o=new Array(i+1);for(let s=0;s<=i;s+=1)o[s]=new Set;for(let[s,a]of r)for(let c of a)o[c].add(s);return o})}function o_(e,t){let n=new Map,r=(a,c)=>{let l=n.get(a);if(!l){n.set(a,[c]);return}l[l.length-1]!==c&&l.push(c)},i=P(e,t);if(!i)return n;let o=at(i).split(/\r?\n/),s=/\b([A-Za-z_$][\w$]*)\b/g;for(let a=0;a<o.length;a+=1){let c=o[a]??"";for(let l of c.matchAll(s))l[1]&&r(l[1],a)}return n}function vg(e,t){return ks(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT
227
- m.symbol_id,
228
- d.relative_path,
229
- COUNT(*) AS ref_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
- WHERE m.role != 1
234
- ${r}
235
- ${e.pathExclusionsFor("d")}
236
- GROUP BY m.symbol_id, d.relative_path`,...n??[])})}function Rg(e,t){return ks(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id, d.relative_path
237
- FROM mentions m
238
- JOIN chunks c ON m.chunk_id = c.id
239
- JOIN documents d ON c.document_id = d.id
240
- WHERE m.role != 1
241
- ${r}
242
- ${e.pathExclusionsFor("d")}`,...n??[])}).filter(n=>n.symbol_id!==null)}function Ig(e,t){return ks(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id
243
- FROM mentions m
244
- WHERE m.role != 1
245
- ${r}`,...n??[])}).filter(n=>n.symbol_id!==null)}function Pr(e,t){return ks(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id, d.relative_path, c.document_id,
246
- c.start_line AS chunk_start, c.end_line AS chunk_end
247
- FROM mentions m
248
- JOIN chunks c ON m.chunk_id = c.id
249
- JOIN documents d ON c.document_id = d.id
250
- WHERE m.role != 1
251
- ${r}
252
- ${e.pathExclusionsFor("d")}
253
- ORDER BY d.relative_path, c.start_line`,...n??[])})}function ks(e,t,n){if(!t)return n();if(t.length===0)return[];let r=[];for(let i=0;i<t.length;i+=750)r.push(...n(t.slice(i,i+750)));return r}function Ps(e,t){let n=wg(e);return n?t.filter(r=>wg(r.file)===n):t}function Ts(e,t,n,r){let i=n.find(o=>o.file===t);if(i)return i;if(r){let o=new Set(ne(e,t).map(s=>s.sourcePath).filter(s=>!!s));for(let s of n)for(let a of o)if(Je(a,s.file))return s;return null}return n.length===1?n[0]:null}function wg(e){let t=M(e);return t?t==="typescript"||t==="tsx"||t==="javascript"?"javascript-family":t:null}var s_=K("global-leaf-index",{clearGroups:["whole-project"]});function qt(e){return s_.get(e,()=>{let t=e.all(`SELECT gs.id, gs.symbol,
254
- COALESCE(der_doc.relative_path, mention_doc.relative_path) AS relative_path
255
- FROM global_symbols gs
256
- LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
257
- LEFT JOIN documents der_doc ON der_doc.id = der.document_id
258
- LEFT JOIN (
259
- SELECT m.symbol_id, MIN(d.relative_path) AS relative_path
260
- FROM mentions m
261
- JOIN chunks c ON m.chunk_id = c.id
262
- JOIN documents d ON c.document_id = d.id
263
- WHERE m.role = 1
264
- GROUP BY m.symbol_id
265
- ) mention_doc ON mention_doc.symbol_id = gs.id
266
- WHERE 1 = 1
267
- ${e.symbolNoiseFor("gs")}`),n=new Map;for(let r of t){if(!r.relative_path||e.isIgnored(r.relative_path))continue;let i=T(r.symbol);if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.some(s=>s.symbolId===r.id)||o.push({symbol:r.symbol,symbolId:r.id,file:r.relative_path})}return n})}var Dg=/[A-Za-z_$][A-Za-z0-9_$]*/g,Eg=/^[A-Za-z_$][A-Za-z0-9_$]*$/,a_=512;function Ei(e){let t=[],n=!1;for(let r of e)r&&(n=!0,Eg.test(r)||t.push(r));return{candidateNames:e,hasUsableCandidate:n,nonIdentifierNames:t}}function _s(e,t){let n=c_(t)?t:Ei(t);if(n.candidateNames.size===0||!n.hasUsableCandidate)return!0;if(n.candidateNames.size<=a_){for(let i of n.candidateNames)if(i){if(Eg.test(i)){if(l_(i).test(e))return!0;continue}if(e.includes(i))return!0}return!1}Dg.lastIndex=0;let r;for(;(r=Dg.exec(e))!==null;)if(n.candidateNames.has(r[0]))return!0;for(let i of n.nonIdentifierNames)if(e.includes(i))return!0;return!1}function c_(e){return"candidateNames"in e}function l_(e){return new RegExp(`(?<![A-Za-z_$0-9])${B(e)}(?![A-Za-z_$0-9])`)}function kg(e){let t=new Map,n=d_(e),r=new Map;return i=>{let o=u_(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=f_(X(e,i.file)),t.set(i.file,a));let c=m_(a,i);return r.set(o,c),c}}function u_(e){return`${e.file}\0${e.symbol}\0${e.line}`}function d_(e){return new Set(e.all("SELECT relative_path FROM documents").map(t=>t.relative_path))}function f_(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 m_(e,t){if(e.definitions.length===0)return t.symbol;let n=h_(t.symbol),r=p_(e.byLeaf,n),i=g_(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 p_(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 g_(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 h_(e){let t=new Set([e]),r=e.split(/::|\.|#/).filter(Boolean).at(-1);return r&&t.add(r),t}function Pg(e,t){let r=ne(e,t).map(i=>b_(t,i));return{usage:r,positions:S_(e,t,r)}}function Tg(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?y_(r.usage,i.sourcePaths):r.usage}}}function y_(e,t){return e.map((n,r)=>{let i=t.get(String(r));return i?{...n,sourcePath:i}:n})}function b_(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 S_(e,t,n){let r=V(e,t);if(!r)return[];let i=C_(r.rootNode),o=new Map;for(let a of i){let c=o.get(Hl(a.importedName,a.localName));c?c.push(a.position):o.set(Hl(a.importedName,a.localName),[a.position])}let s=[];return n.forEach((a,c)=>{let l=o.get(Hl(a.importedName,a.localName??a.importedName))?.shift();l&&s.push({...l,id:String(c),file:t})}),s}function C_(e){let t=[];for(let n of e.descendantsOfType("use_declaration")){let r=n.namedChildren.find(i=>i.type!=="visibility_modifier");r&&t.push(...Fs(r,""))}return t.filter(n=>n.importedName!=="*")}function Fs(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":return[{importedName:e.text,localName:e.text,position:Bl(e,e.text)}];case"scoped_identifier":{let n=e.text.split("::").pop()??e.text;return[{importedName:n,localName:n,position:Bl(e,n)}]}case"scoped_use_list":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=Dr(t,n.text);return r.namedChildren.flatMap(o=>Fs(o,i))}case"use_list":return e.namedChildren.flatMap(n=>Fs(n,t));case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);return!n||!r?[]:Fs(n,t).map(i=>({...i,localName:r.text}))}case"use_wildcard":{let n=e.namedChild(0),r="*";return[{importedName:r,localName:r,position:Bl(n??e,r)}]}default:return[]}}function Bl(e,t){let n=Math.max(0,e.text.lastIndexOf(t));return{id:"",file:"",line:e.startPosition.row,column:e.startPosition.column+n+x_(t)}}function x_(e){return Math.max(0,Math.min(e.length-1,1))}function Hl(e,t){return`${e}\0${t}`}import{spawnSync as iu}from"child_process";import{existsSync as ou}from"fs";import{fileURLToPath as BF}from"url";function Sn(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}import{existsSync as _g,readdirSync as v_}from"fs";import{isAbsolute as R_,join as Ul,resolve as I_}from"path";var w_={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:r})=>{let i=r?["index","--output",e,"--no-progress-bar",r]:["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&!r&&i.splice(1,0,"--pnpm-workspaces"),{binary:n,args:i}},markerFiles:["tsconfig.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--infer-tsconfig","--output",e,"--no-progress-bar"]}),markerFiles:["package.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},java:{language:"java",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["pom.xml","build.gradle"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.sbt"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.gradle.kts"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:"rust",indexerBinary:"rust-analyzer",checkCommand:"rust-analyzer --version",indexArgs:({outputPath:e})=>({binary:"rust-analyzer",args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[{label:"rustup",prerequisite:"rustup",binary:"rustup",args:["component","add","rust-analyzer"]}],installUrl:"https://github.com/rust-lang/rust-analyzer"},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:["pyproject.toml","setup.py"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","scip-python-plus"]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},clojure:{language:"clojure",indexerBinary:"scip-clojure",projectLocalBinaries:["node_modules/.bin/scip-clojure"],checkCommand:"scip-clojure -h",indexArgs:({projectRoot:e,outputPath:t,indexerBinary:n,configPath:r})=>{let i=["-root",e,"-output",t];return r&&i.push("-config",R_(r)?r:I_(e,r)),{binary:n,args:i}},markerFiles:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],installMethods:[],installUrl:"https://github.com/PlunderStruck/scip-clojure"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:["Gemfile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:["go.mod"],installMethods:[{label:"go install",prerequisite:"go",binary:"go",args:["install","github.com/sourcegraph/scip-go@latest"]}],installUrl:"https://github.com/sourcegraph/scip-go"},cpp:{language:"cpp",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Fg(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.csproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},vb:{language:"vb",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Fg(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.vbproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},dart:{language:"dart",indexerBinary:"scip-dart",checkCommand:"scip-dart --version",indexArgs:({indexerBinary:e,outputPath:t})=>({binary:e,args:["--output",t]}),markerFiles:["pubspec.yaml"],installMethods:[{label:"dart pub",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart"]}],installUrl:"https://github.com/Workiva/scip-dart/releases"},php:{language:"php",indexerBinary:"scip-php",projectLocalBinaries:["vendor/davidrjenni/scip-php/bin/scip-php","vendor/bin/scip-php"],checkCommand:"scip-php --version",indexArgs:({projectRoot:e,indexerBinary:t})=>{let n=Ul(e,"vendor","bin","scip-php"),r=Ul(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",_g(r)?r:_g(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function Lg(e){return w_[e]}function Fg(e,t){let n;try{n=v_(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return Ul(e,i);return null}import{execFileSync as Gl}from"child_process";import{existsSync as Wl,readFileSync as P_}from"fs";import{createRequire as T_}from"module";import{platform as __}from"os";import{dirname as Ng,join as Ns}from"path";import{execFileSync as D_}from"child_process";import{platform as E_}from"os";var k_=E_()==="win32";function Ls(e){let t=k_?"where":"which";try{return D_(t,[e],{stdio:"pipe"}),!0}catch{return!1}}var F_=T_(import.meta.url);function zl(e){return[e.indexerBinary,...e.binaryAliases??[]]}function Ag(e){let t=zl(e);return t.length===1?t[0]:t.join(" or ")}function As(e){for(let t of zl(e))if(Ls(t))return t;return N_(e)}function YZ(e){return As(e)!==null||L_(e)}function L_(e){return Mg(e)!==null}function N_(e){let t=Mg(e);if(!t)return null;let r=JSON.parse(P_(t,"utf8")).bin;if(!r)return null;if(typeof r=="string")return Ns(Ng(t),r);for(let i of zl(e)){let o=r[i];if(o)return Ns(Ng(t),o)}return null}function Mg(e){if(!e.bundledNpmPackage)return null;try{return F_.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function A_(e,t){for(let n of e.projectLocalBinaries??[]){let r=Ns(t,n);if(Wl(r))return r}return null}function M_(e,t){return A_(e,t)??As(e)}function XZ(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||Vl(n,t))return t;let r=jg(n,t);return r?{...t,DOTNET_ROOT:r}:t}function Og(e,t){let n=Ag(e),r=t?M_(e,t):As(e);if(!r)return{language:e.language,binaryLabel:n,installed:!1,runnable:!1,resolvedBinary:null,installUrl:e.installUrl};if(e.indexerBinary!=="scip-dotnet")return{language:e.language,binaryLabel:n,installed:!0,runnable:!0,resolvedBinary:r};let i=O_(r);return{language:e.language,binaryLabel:n,installed:!0,runnable:i.runnable,resolvedBinary:r,installUrl:e.installUrl,note:i.note}}function QZ(e,t){let n=e.installMethods,r=Ag(e);if(!n?.length)return t(`No auto-install method available for ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1;for(let i of n)if(Ls(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{Gl(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env});let o=As(e);if(o){let s=o===e.indexerBinary?"":` (using ${o})`;return t(`Successfully installed ${r} via ${i.label}${s}`),!0}t(`${i.label} command completed but ${r} was not found on PATH`)}catch(o){let s=o instanceof Error?o.message:String(o);t(`${i.label} install failed: ${s}`)}}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function O_(e){if(Vl(e,process.env))return{runnable:!0};let t=jg(e,process.env);if(t)return{runnable:!0,note:`using .NET 9 runtime from ${t}`};let n=$g(process.env);return{runnable:!1,note:n.length>0?`.NET 9 runtime still unavailable after checking ${n.join(", ")}`:"binary is present, but scip-dotnet still needs a .NET 9 runtime"}}function jg(e,t){for(let n of $g(t))if(Vl(e,{...t,DOTNET_ROOT:n}))return n;return null}function $g(e){let t=[],n=e.DOTNET_ROOT;if(n&&Wl(n)&&t.push(n),__()==="darwin"&&Ls("brew"))try{let r=Gl("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),i=Ns(r,"libexec");Wl(i)&&!t.includes(i)&&t.push(i)}catch{}return t}function Vl(e,t){try{return Gl(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}function Ms(e){let t=Og(Lg("rust"),e),n=t.runnable;return{available:n,dependencyAvailable:n,resolvedBinary:t.resolvedBinary??void 0,reason:n?"rust-analyzer semantic reference queries are enabled.":"rust-analyzer is not runnable; Rust semantic checks will use SCIP/source evidence only."}}import{existsSync as wF,mkdtempSync as dh,readFileSync as fh,rmSync as Ql}from"fs";import{tmpdir as tu}from"os";import{join as Zl}from"path";import{fileURLToPath as Li,pathToFileURL as DF}from"url";import{SHARE_ENV as EF,Worker as kF}from"worker_threads";function Cn(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 qn(e,t,n){let r=Sn(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 fF}from"child_process";import{createHash as mF,randomUUID as pF}from"crypto";import{existsSync as ih,mkdirSync as Zg,readFileSync as Us,realpathSync as gF,rmSync as Yl}from"fs";import{tmpdir as hF}from"os";import{resolve as wt}from"path";import{execFileSync as V_}from"child_process";import{existsSync as j_,readFileSync as $_}from"fs";import{deserializeSCIP as B_,SymbolRole as H_}from"@c4312/scip";import{existsSync as s3,readFileSync as a3}from"fs";import{relative as l3,resolve as u3,sep as d3}from"path";import{fileURLToPath as m3,pathToFileURL as p3}from"url";function Os(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 ql=new WeakMap,U_="SCIP_RUST_SCIP_OCCURRENCE_REFERENCE_MODE";function Bg(e,t){let n=new Map,r=js(),i=t.filter(s=>Wg(s,r));if(i.length===0)return n;let o=Gg(e);if(!o)return n;for(let s of i){let a=Ug(o,s);a!==null&&n.set(s.symbolId,a)}return n}function Hg(e,t){if(!Wg(t,js()))return null;let n=Gg(e);return n?Ug(n,t):null}function Ug(e,t){return e.referencesBySymbol.get(t.symbol)??[]}function Wg(e,t="safe"){if(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||Re(e.symbol)||/impl#\[[^\]]+\]\[Default\]default\(\)\.$/.test(e.symbol))return!1;if(t==="all")return!0;let n=le(e.symbol);if(n==="method")return!0;if(n!=="term")return!1;let r=ye(e.symbol);return"kind"in r?!1:!W_(r)}function W_(e){for(let t=0;t<e.descriptors.length-1;t+=1)if(e.descriptors[t]?.suffix==="type")return!0;return!1}function Gg(e){if(ql.has(e))return ql.get(e)??null;let t=G_(e);return ql.set(e,t),t}function G_(e){if(!j_(e.config.indexPath))return null;try{let t=B_($_(e.config.indexPath)),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&H_.Definition)!==0)continue;let s=z_(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,Os(i));return{referencesBySymbol:n}}catch{return null}}function z_(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 js(){return process.env[U_]==="all"?"all":"safe"}var zg=new Map;function Kl(e){let n=Ms(e).resolvedBinary??null;return{engine:"rust-analyzer",resolvedBinary:n,version:n?q_(e,n):"unavailable"}}function Kn(e){return{...Kl(e),scipOccurrenceReferenceMode:js()}}function q_(e,t){let n=`${e}\0${t}`,r=zg.get(n);if(r)return r;let i;try{i=V_(t,["--version"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim()}catch{i="unknown"}return zg.set(n,i),i}import{createHash as lF}from"crypto";import{execFileSync as K_}from"child_process";import{createHash as Vg}from"crypto";import{lstatSync as J_,readdirSync as Y_,readFileSync as X_,readlinkSync as Q_,realpathSync as qg}from"fs";import{isAbsolute as Z_,join as Kg,relative as eF,sep as tF}from"path";function $s(e,t){let n=e.split("/").at(-1)??e;if(Yg.has(n)||n===".scipquery.json"||/^tsconfig(?:\..+)?\.json$/.test(n))return"config";if(/\.d\.(?:ts|mts|cts)$/.test(e.toLowerCase()))return"ambient";let r=e.includes(".")?`.${e.split(".").at(-1).toLowerCase()}`:"";return t.some(i=>(Xg[i]??[]).includes(r))?"source":"other"}function nF(e){return[...new Set((e??[]).map(t=>t.trim()).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function rF(e){return(sF(e)??aF(e)).filter(t=>t&&!Jg(t)).sort()}function Jl(e,t={}){let n=rF(e).filter(i=>!t.language||oF(i,t.language,t.markerFiles)).filter(i=>!t.includePath||t.includePath(i)),r=qg(e);return n.map(i=>{let o=Kg(e,i);try{if(J_(o).isSymbolicLink()){let a=qg(o),c=eF(r,a);if(c===".."||c.startsWith(`..${tF}`)||Z_(c))throw new Error("external symlink");let l=Q_(o);return{path:i,size:Buffer.byteLength(l),hash:Vg("sha256").update("symlink\0").update(l).digest("hex")}}let s=X_(o);return{path:i,size:s.byteLength,hash:Vg("sha256").update(s).digest("hex")}}catch{return{path:i,size:-1,hash:"unreadable"}}})}function ki(e,t,n){return{version:2,languages:[...t].sort(),pnpmWorkspaces:n.typescriptProjectMode!=="workspace"&&n.pnpmWorkspaces===!0,typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:nF(n.typescriptProjects),clojureConfigPath:iF(n.clojureConfigPath),files:Jl(e)}}function iF(e){return e?.trim()||void 0}function oF(e,t,n){let r=e.split("/").at(-1)??e;if(n?.includes(e)||n?.includes(r)||Yg.has(r))return!0;let i=e.includes(".")?`.${e.split(".").at(-1).toLowerCase()}`:"";return(Xg[t]??[]).includes(i)}function sF(e){try{return K_("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:50*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
268
- `).filter(Boolean)}catch{return null}}function aF(e){let t=[],n=[""];for(;n.length>0;){let r=n.pop(),i=r?Kg(e,r):e,o;try{o=Y_(i,{withFileTypes:!0})}catch{continue}for(let s of o){let a=r?`${r}/${s.name}`:s.name;if(s.isDirectory()){Jg(a)||n.push(a);continue}t.push(a)}}return t}function Jg(e){let t=e.split("/");return e==="meta.json"||t.some(n=>cF.has(n))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var cF=new Set([".git","node_modules",".scipquery-cache",".scipquery-generations",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]),Yg=new Set(["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","bun.lockb","tsconfig.json","tsconfig.base.json","pyproject.toml","setup.py","setup.cfg","Cargo.toml","Cargo.lock","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","build.sbt","compile_commands.json","CMakeLists.txt","Makefile","Gemfile","Gemfile.lock","composer.json","composer.lock","pubspec.yaml","pubspec.lock","deps.edn","project.clj","bb.edn","shadow-cljs.edn"]),Xg={typescript:[".ts",".tsx",".mts",".cts"],javascript:[".js",".jsx",".mjs",".cjs"],java:[".java"],scala:[".scala"],kotlin:[".kt",".kts"],rust:[".rs"],python:[".py",".pyi"],ruby:[".rb"],go:[".go"],cpp:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"],c:[".c",".h"],csharp:[".cs"],vb:[".vb"],dart:[".dart"],php:[".php"],clojure:[".clj",".cljs",".cljc"]};var uF=new Set(["Cargo.lock","Cargo.toml","rust-project.json","rust-toolchain","rust-toolchain.toml"]);function Qg(e){let t=Jl(e,{includePath:dF});return lF("sha256").update(JSON.stringify(t)).digest("hex")}function dF(e){let t=e.replaceAll("\\","/"),n=t.split("/").at(-1)??t;return t.endsWith(".rs")||uF.has(n)?!0:t===".cargo/config"||t===".cargo/config.toml"||t.endsWith("/.cargo/config")||t.endsWith("/.cargo/config.toml")}var oh=2,yF=5e3,bF=5e3,sh=10,SF=3e4;function eh(e,t,n,r=uh){let i=r.engineIdentity(e),o={protocolVersion:oh,projectRoot:r.canonicalProjectRoot(e),projectFingerprint:r.projectFingerprint(e),engine:{engine:i.engine,resolvedBinary:i.resolvedBinary,version:i.version},workerFingerprint:r.fileFingerprint(t),environment:ah(r.environment())};return{key:Hs(Bs(o)),...o}}function Pi(e,t,n){return e.protocolVersion===oh&&(t-e.heartbeatAtMs<=yF||e.busyUntilMs!==void 0&&t<=e.busyUntilMs)&&n(e.pid)}function Xl(e,t,n){let r;try{r=Hs(Us(t))}catch{r="missing"}let i=Hs(Bs({projectRoot:wt(e),serverPath:wt(t),serverFingerprint:r})).slice(0,20);return wt(n,`scip-query-rust-session-${i}`)}function th(e){let t=e===void 0?Number.NaN:Number(e);return Number.isInteger(t)&&t>=0?t:0}function ah(e){return Object.fromEntries(Object.entries(e).filter(([t])=>lh(t)).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,n??null]))}function ch(e,t){let n=t.runtime??IF,r=t.identityRuntime??uh,i=Xl(e,t.serverPath,t.tempRoot??hF()),o=!1,s=(a,c)=>{if(o)throw new Error("Durable Rust semantic session was already disposed.");return xF(i,t.serverPath,t.semanticWorkerPath,a,c,n)};return{requestSemantic(a,c){let l=eh(e,t.semanticWorkerPath,a,r),u=n.now()+Math.max(1,c-1e3);return s({kind:"semantic",identityKey:l.key,workerEnvironment:rh(),request:{...a,readinessDeadlineMs:u,referenceRetryTimeoutMs:CF(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,a.referenceRetryTimeoutMs),settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:th(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},requestImportDefinitions(a,c){let l=eh(e,t.semanticWorkerPath,a,r),u=n.now()+Math.max(1,c-1e3);return s({kind:"import-definitions",identityKey:l.key,workerEnvironment:rh(),request:{...a,readinessDeadlineMs:u,settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:th(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},shutdown(){o=!0}}}function CF(e,t){return t!==void 0?t:e===void 0?SF:void 0}function xF(e,t,n,r,i,o){let s=o.randomId(),a=o.now(),c=wt(e,"requests"),l=wt(e,"responses"),u=wt(c,`${s}.json`),d=wt(l,`${s}.json`);Zg(c,{recursive:!0}),Zg(l,{recursive:!0}),he(u,{id:s,request:r});let f=o.now()+i;try{for(nh(e,t,n,f,o);o.now()<=f;){if(ih(d)){let p=vF(Us(d,"utf8"));if(!p.ok)throw new Error(p.error);return H()&&un({type:"span",name:"rust.semantic.durable-session.request",durationMs:o.now()-a,ok:!0,session:p.session,kind:r.kind}),p.response}let m=Ti(e);(!m||!Pi(m,o.now(),o.isProcessAlive))&&nh(e,t,n,f,o),o.sleep(sh)}throw new Error(`Durable Rust semantic session timed out after ${(i/1e3).toFixed(0)}s.`)}finally{Yl(u,{force:!0}),Yl(d,{force:!0})}}function nh(e,t,n,r,i){let o=Ti(e);if(o&&Pi(o,i.now(),i.isProcessAlive))return;Yl(wt(e,"server.json"),{force:!0}),i.spawnServer(t,e,n);let s=Math.min(r,i.now()+bF);for(;i.now()<=s;){let a=Ti(e);if(a&&Pi(a,i.now(),i.isProcessAlive))return;i.sleep(sh)}throw new Error("Durable Rust semantic session helper did not become ready within 5s.")}function Ti(e){try{let t=JSON.parse(Us(wt(e,"server.json"),"utf8"));return typeof t.protocolVersion!="number"||typeof t.pid!="number"||typeof t.heartbeatAtMs!="number"||t.busyUntilMs!==void 0&&typeof t.busyUntilMs!="number"?null:{protocolVersion:t.protocolVersion,pid:t.pid,heartbeatAtMs:t.heartbeatAtMs,...t.busyUntilMs===void 0?{}:{busyUntilMs:t.busyUntilMs}}}catch{return null}}function vF(e){try{let t=JSON.parse(e);return t.ok===!0&&(t.session==="created"||t.session==="reused"||t.session==="invalidated")&&t.response&&typeof t.response=="object"?{ok:!0,session:t.session,response:t.response}:{ok:!1,error:typeof t.error=="string"?t.error:"helper wrote an invalid response"}}catch(t){return{ok:!1,error:`helper wrote malformed JSON: ${t instanceof Error?t.message:String(t)}`}}}function rh(){return Object.fromEntries(Object.entries(process.env).filter(([e])=>RF(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t??null]))}function lh(e){return e==="HOME"||e==="PATH"||e.startsWith("CARGO_")||e.startsWith("RA_")||e.startsWith("RUST")}function RF(e){return lh(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 uh={canonicalProjectRoot(e){try{return gF(e)}catch{return wt(e)}},projectFingerprint(e){return Qg(e)},engineIdentity:Kl,fileFingerprint(e){return Hs(Us(e))},environment(){return ah(process.env)}},IF={now:Date.now,randomId:pF,isProcessAlive:Ae,spawnServer(e,t,n){if(!ih(e))throw new Error(`Durable Rust semantic session helper was not found at ${e}. Run npm run build first.`);fF(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 Bs(e){return Array.isArray(e)?`[${e.map(Bs).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Bs(n)}`).join(",")}}`:JSON.stringify(e)}function Hs(e){return mF("sha256").update(e).digest("hex")}var mh=15e3,ph=8,hh=5e3,PF=64,TF=96,nu=class{constructor(t,n,r={}){this.projectRoot=t;this.status=n;this.opts=r;this.requester=r.requester??LF(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:n.reason,references:_i(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!0});return{available:r.available,resolvedBinary:n.resolvedBinary,reason:r.reason,references:Cn(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:_i(t)}}}calleesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:n.reason,callees:Fi(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!0});return{available:r.available,resolvedBinary:n.resolvedBinary,reason:r.reason,callees:eu(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:Fi(t)}}}referencesAndCalleesForDefinitions(t,n){let r=this.status(this.projectRoot);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,references:_i(t),callees:Fi(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{available:o.available,resolvedBinary:r.resolvedBinary,reason:o.reason,references:Cn(t,new Map(o.references),new Set(o.incompleteReferenceSymbolIds??[])),callees:eu(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:n.reason,signatures:gh(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!1,includeSignatures:!0});return{available:r.available,resolvedBinary:n.resolvedBinary,reason:r.reason,signatures:jF(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:gh(t)}}}importDefinitionsForFile(t,n){let r=this.status(this.projectRoot);if(n.length===0)return{available:r.available,resolvedBinary:r.resolvedBinary,reason:r.reason,sourcePaths:new Map};if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,sourcePaths:new Map(n.map(i=>[i.id,null]))};try{let i=this.requestImportDefinitions(r.resolvedBinary,t,n);return{available:i.available,resolvedBinary:r.resolvedBinary,reason:i.reason,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=Ws(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,mh),o=Gs(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),s=Ws(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,ph),a=Gs(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),c=r.referenceDefinitions?[...r.referenceDefinitions]:void 0,l=r.calleeDefinitions?[...r.calleeDefinitions]:void 0,u=r.signatureDefinitions?[...r.signatureDefinitions]:void 0,d=Ni(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,...r}),f={projectRoot:this.projectRoot,rustAnalyzerBinary:t,definitions:[...n],...c?{referenceDefinitions:c}:{},...l?{calleeDefinitions:l}:{},...u?{signatureDefinitions:u}:{},requestTimeoutMs:i,...r.includeReferences!==!1&&o>0?{referenceRetryTimeoutMs:o}:{},diagnosticsTimeoutMs:a,settleDelayMs:d,concurrency:s,includeReferences:r.includeReferences,includeCallees:r.includeCallees,includeSignatures:r.includeSignatures},m=$F(f);return D("rust.semantic.session.request",()=>this.requester.requestSemantic(f,qn(m,ru(i,f.referenceRetryTimeoutMs),s)),()=>({definitions:n.length,operationDefinitions:m,referenceDefinitions:f.referenceDefinitions?.length,calleeDefinitions:f.calleeDefinitions?.length,signatureDefinitions:f.signatureDefinitions?.length,references:f.includeReferences!==!1,callees:f.includeCallees===!0,signatures:f.includeSignatures===!0,referenceRetryTimeoutMs:f.referenceRetryTimeoutMs}))}fallbackReferencesAndCallees(t,n,r,i){let o=n.length===0?{available:!0,references:_i(n)}:this.opts.fallbackReferenceResolver?.referencesForDefinitions(n),s=r.length===0?{available:!0,callees:Fi(r)}:this.opts.fallbackCalleeResolver?.calleesForDefinitions(r);return o&&s?{available:o.available&&s.available,resolvedBinary:o.resolvedBinary??s.resolvedBinary??t.resolvedBinary,reason:o.reason??s.reason,references:Cn(n,o.references),callees:eu(r,s.callees)}:{available:!1,resolvedBinary:t.resolvedBinary,reason:i instanceof Error?i.message:String(i),references:_i(n),callees:Fi(r)}}requestImportDefinitions(t,n,r){let i=Ws(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,mh),o=Ws(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,ph),s=Gs(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),a=Gs(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,hh),c={projectRoot:this.projectRoot,rustAnalyzerBinary:t,file:n,positions:[...r],requestTimeoutMs:i,diagnosticsTimeoutMs:s,settleDelayMs:a,concurrency:o};return D("rust.semantic.import-definitions.session.request",()=>this.requester.requestImportDefinitions(c,qn(r.length,i,o)),()=>({file:n,positions:r.length}))}};function yh(e,t,n={}){return new nu(e,t,n)}function Ni(e,t){let n=xh(e);if(n!==null)return n;let r=t.includeReferences!==!1;return r&&t.includeCallees!==!0&&t.includeSignatures!==!0&&t.definitionCount<=PF||r&&t.includeCallees===!0&&t.includeSignatures!==!0&&t.definitionCount<=TF?0:hh}function bh(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 _F(e){return bh(e).transport}function e6(e,t){let n=bh(t);if(n.transport==="worker")return{...n,state:"per-command"};let r=Li(Ch()),i=Xl(e,r,tu()),o=Ti(i);return o?{...n,state:Pi(o,Date.now(),Ae)?"live":"stale",pid:o.pid,heartbeatAtMs:o.heartbeatAtMs,...o.busyUntilMs===void 0?{}:{busyUntilMs:o.busyUntilMs}}:{...n,state:"stopped"}}function FF(e,t){let n=null,r=!1,i=!1,o=!1,s=()=>n??=t(),a=()=>{i||(e.shutdown(),i=!0)},c=(u,d,f)=>{let m=OF(u);r=!0;try{a()}catch{}H()&&un({type:"span",name:"rust.semantic.durable-session.request",durationMs:f,ok:!1,kind:d,session:"worker-fallback",reason:m})},l=(u,d,f)=>{if(o)throw new Error("Rust semantic failover session was already disposed.");if(r)return f(s());let m=Date.now();try{return d(e)}catch(p){c(p,u,Date.now()-m)}return f(s())};return{requestSemantic(u,d){return l("semantic",f=>f.requestSemantic(u,d),f=>f.requestSemantic(u,d))},requestImportDefinitions(u,d){return l("import-definitions",f=>f.requestImportDefinitions(u,d),f=>f.requestImportDefinitions(u,d))},shutdown(){if(o)return;o=!0;let u=[];try{a()}catch(d){u.push(d)}try{n?.shutdown()}catch(d){u.push(d)}if(u.length>0)throw u[0]}}}function LF(e,t,n={worker:()=>NF(),durable:()=>ch(e,{serverPath:Li(Ch()),semanticWorkerPath:Li(Sh())})}){return _F(t)==="durable"?FF(n.durable(),n.worker):n.worker()}function NF(e={}){let t=null,n=null,r=1,i=!1,o=()=>{n&&(Ql(n,{recursive:!0,force:!0}),n=null)},s=()=>{let l=t;t=null,l&&l.terminate(),o()},a=()=>{if(t)return t;let l=e.semanticWorkerPath?DF(e.semanticWorkerPath):Sh();if(!wF(Li(l)))throw new Error(`Rust semantic session worker was not found at ${Li(l)}. Run npm run build before using built semantic Rust queries.`);return n=dh(Zl(tu(),"scip-query-rust-session-")),t=new kF(l,e.shareEnvironment?{env:EF}:void 0),t.unref(),t},c=()=>{let l=n??dh(Zl(tu(),"scip-query-rust-session-"));return n=l,Zl(l,`${r++}.json`)};return{requestSemantic(l,u){if(i)throw new Error("Rust semantic session was already disposed.");let d=a(),f=c(),m=new SharedArrayBuffer(4),p=new Int32Array(m);if(d.postMessage({kind:"semantic",request:l,responsePath:f,sharedBuffer:m}),Atomics.wait(p,0,0,u)==="timed-out")throw s(),new Error(`Rust semantic session worker timed out after ${(u/1e3).toFixed(0)}s`);try{let h=AF(fh(f,"utf8"));if(!h.ok)throw new Error(h.error);return h.response}finally{Ql(f,{force:!0})}},requestImportDefinitions(l,u){if(i)throw new Error("Rust semantic session was already disposed.");let d=a(),f=c(),m=new SharedArrayBuffer(4),p=new Int32Array(m);if(d.postMessage({kind:"import-definitions",request:l,responsePath:f,sharedBuffer:m}),Atomics.wait(p,0,0,u)==="timed-out")throw s(),new Error(`Rust semantic import-definition session worker timed out after ${(u/1e3).toFixed(0)}s`);try{let h=MF(fh(f,"utf8"));if(!h.ok)throw new Error(h.error);return h.response}finally{Ql(f,{force:!0})}},shutdown(){if(i)return;if(i=!0,!t){o();return}let l=c(),u=new SharedArrayBuffer(4),d=new Int32Array(u);t.postMessage({kind:"shutdown",responsePath:l,sharedBuffer:u}),Atomics.wait(d,0,0,5e3),s()}}}function AF(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 MF(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 OF(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 _i(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Fi(e){return new Map(e.map(t=>[t.symbolId,[]]))}function gh(e){return new Map(e.map(t=>[t.symbolId,null]))}function eu(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??[]]))}function jF(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function $F(e){let t=0;return e.includeReferences!==!1&&(t+=(e.referenceDefinitions??e.definitions).length),e.includeCallees===!0&&(t+=(e.calleeDefinitions??e.definitions).length),e.includeSignatures===!0&&(t+=(e.signatureDefinitions??e.definitions).length),Math.max(1,t)}function ru(e,t){return t&&t>0?Math.max(e,t):e}function Sh(){return new URL("./rust-semantic-session-worker.js",import.meta.url)}function Ch(){return new URL("./rust-semantic-session-server.js",import.meta.url)}function Ws(e,t){return Sn(e)??t}function Gs(e,t){return xh(e)??t}function xh(e){if(!e)return null;let t=Number(e);return Number.isInteger(t)&&t>=0?t:null}var su=15e3,au=8;function wh(e,t={}){let n=t.status??Ms,r=WF(e,n),i=GF(e,n),o=zF(e,n),s=t.referenceResolver||t.calleeResolver||t.signatureResolver||!HF(t)?null:yh(e,n,{fallbackReferenceResolver:r,fallbackCalleeResolver:i,fallbackSignatureResolver:o}),a=t.referenceResolver??s??r,c=t.calleeResolver??s??i,l=t.signatureResolver??s??o,u=t.importUsageResolver??Tg(t.sourceImportUsageResolver??UF(),t.importDefinitionResolver??s),d=t.calleeSymbolResolver,f=t.sourceZeroCalleeOracle,m=t.scipOccurrenceCalleeOracle,p=new Map,g=new Map,h=null,S=null,C=()=>(h??=n(e),h),x=()=>{let E=C();return E.dependencyAvailable?S??E:E},b=E=>{if(E.length===0)return new Map;let I=Ai(E);try{let k=a.referencesForDefinitions(I),F=C();return S={...F,available:k.available,resolvedBinary:k.resolvedBinary??F.resolvedBinary,reason:k.reason??F.reason},k.available?new Map(k.references):Cn(I,k.references)}catch(k){return S={...C(),available:!1,reason:k instanceof Error?k.message:String(k)},Jn(I)}},y=E=>{if(E.length===0)return new Map;let I=Ai(E),k=I.filter(vh);if(k.length===0)return Yn(I);let F=new Map,te=Ih(k,m),Y=[];for(let L of k)g.has(L.symbolId)?F.set(L.symbolId,g.get(L.symbolId)??[]):te.has(L.symbolId)?F.set(L.symbolId,te.get(L.symbolId)??[]):Rh(L,f)?F.set(L.symbolId,[]):Y.push(L);if(Y.length===0)return Tr(I,F,void 0);try{let L=c.calleesForDefinitions(Y),oe=C();S={...oe,available:L.available,resolvedBinary:L.resolvedBinary??oe.resolvedBinary,reason:L.reason??oe.reason};let Q=Tr(Y,L.callees,d);for(let[an,wc]of Q)F.set(an,wc);return Tr(I,F,void 0)}catch(L){return S={...C(),available:!1,reason:L instanceof Error?L.message:String(L)},Yn(I)}},R=(E,I)=>{let k=Ai(E),F=Ai(I),te=F.filter(vh),Y=new Map,L=Ih(te,m),oe=[];for(let Q of te)L.has(Q.symbolId)?Y.set(Q.symbolId,L.get(Q.symbolId)??[]):Rh(Q,f)?Y.set(Q.symbolId,[]):oe.push(Q);if(k.length===0&&oe.length===0)return{references:Jn(k),callees:Tr(F,Y,void 0)};try{let Q=s?s.referencesAndCalleesForDefinitions(k,oe):JF(a,c,{referenceDefinitions:k,calleeDefinitions:oe}),an=C();S={...an,available:Q.available,resolvedBinary:Q.resolvedBinary??an.resolvedBinary,reason:Q.reason??an.reason};let wc=Q.available?new Map(Q.references):Cn(k,Q.references);for(let[Dc,Ec]of Q.callees)Y.set(Dc,Ec);let Zf=Tr(F,Y,d);for(let[Dc,Ec]of Zf)g.set(Dc,Ec);return{references:wc,callees:Zf}}catch(Q){return S={...C(),available:!1,reason:Q instanceof Error?Q.message:String(Q)},{references:Jn(k),callees:Yn(F)}}},v=E=>{if(E.length===0)return new Map;let I=Ai(E);try{let k=l.signaturesForDefinitions(I),F=C();return S={...F,available:k.available,resolvedBinary:k.resolvedBinary??F.resolvedBinary,reason:k.reason??F.reason},Dh(I,k.signatures)}catch(k){return S={...C(),available:!1,reason:k instanceof Error?k.message:String(k)},zs(I)}};return{language:"rust",availability:x,dispose:()=>{s?.dispose()},importUsage:E=>{let I=p.get(E);if(I)return I;try{let k=u.importUsage(E);return p.set(E,k),k}catch(k){return S={...C(),available:!1,reason:k instanceof Error?k.message:String(k)},[]}},referencesFor:E=>b([E]).get(E.symbolId)??[],referencesForDefinitions:b,referencesAndCalleesForDefinitions:R,calleesFor:E=>y([E]).get(E.symbolId)??[],calleesForDefinitions:y,signatureFor:E=>v([E]).get(E.symbolId)??null}}function HF(e){if(e.usePersistentSession!==void 0)return e.usePersistentSession;let t=process.env.SCIP_RUST_SEMANTIC_SESSION;return t!=="0"&&t!=="false"}function UF(){return{importUsageFacts:()=>({usage:[],positions:[]})}}function Ai(e){return e.map(t=>{let n=t;return{...t,leaf:typeof n.leaf=="string"?n.leaf:T(t.symbol),parentTypeName:n.parentTypeName??null,isFunctionLike:typeof n.isFunctionLike=="boolean"?n.isFunctionLike:Z(t.symbol),isTypeLike:n.isTypeLike??!1,kind:n.kind??null,documentation:n.documentation??null,enclosingSymbol:n.enclosingSymbol??null}})}function vh(e){return e.isFunctionLike}function Rh(e,t){if(!t)return!1;try{return t(e)}catch{return!1}}function Ih(e,t){if(!t||e.length===0)return new Map;try{return t(e)}catch{return new Map}}function WF(e,t){return{referencesForDefinitions:n=>VF(e,t,n)}}function GF(e,t){return{calleesForDefinitions:n=>qF(e,t,n)}}function zF(e,t){return{signaturesForDefinitions:n=>KF(e,t,n)}}function VF(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,references:Jn(n)};let i=cu();if(!ou(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:Jn(n)};let o=_r(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,su),s=Vs(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),a=_r(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,au),c=Vs(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),l=Ni(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!0}),u={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,...s>0?{referenceRetryTimeoutMs:s}:{},diagnosticsTimeoutMs:c,settleDelayMs:l,concurrency:a},d=iu(process.execPath,[i],{cwd:e,input:JSON.stringify(u),encoding:"utf8",maxBuffer:50*1024*1024,timeout:qn(n.length,ru(o,u.referenceRetryTimeoutMs),a)}),f=lu(d.stdout);if(f)return{available:f.available,resolvedBinary:r.resolvedBinary,reason:f.reason,references:Cn(n,new Map(f.references),new Set(f.incompleteReferenceSymbolIds??[]))};let m=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:m,references:Jn(n)}}function qF(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,callees:Yn(n)};let i=cu();if(!ou(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:Yn(n)};let o=_r(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,su),s=_r(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,au),a=Vs(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=Ni(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!0}),l={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:c,concurrency:s,includeReferences:!1,includeCallees:!0},u=iu(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:qn(n.length,o,s)}),d=lu(u.stdout);if(d)return{available:d.available,resolvedBinary:r.resolvedBinary,reason:d.reason,callees:Tr(n,new Map(d.callees??[]),void 0)};let f=u.error instanceof Error?u.error.message:u.stderr.trim()||`Rust semantic worker exited with status ${u.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:f,callees:Yn(n)}}function KF(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,signatures:zs(n)};let i=cu();if(!ou(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:zs(n)};let o=_r(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,su),s=_r(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,au),a=Vs(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=Ni(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!1,includeSignatures:!0}),l={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:c,concurrency:s,includeReferences:!1,includeCallees:!1,includeSignatures:!0},u=iu(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:qn(n.length,o,s)}),d=lu(u.stdout);if(d)return{available:d.available,resolvedBinary:r.resolvedBinary,reason:d.reason,signatures:Dh(n,new Map(d.signatures??[]))};let f=u.error instanceof Error?u.error.message:u.stderr.trim()||`Rust semantic worker exited with status ${u.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:f,signatures:zs(n)}}function JF(e,t,n){let r=n.referenceDefinitions.length>0?e.referencesForDefinitions(n.referenceDefinitions):{available:!0,references:Jn(n.referenceDefinitions)},i=n.calleeDefinitions.length>0?t.calleesForDefinitions(n.calleeDefinitions):{available:!0,callees:Yn(n.calleeDefinitions)};return{available:r.available&&i.available,resolvedBinary:r.resolvedBinary??i.resolvedBinary,reason:r.reason??i.reason,references:r.references,callees:i.callees}}function Jn(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Yn(e){return new Map(e.map(t=>[t.symbolId,[]]))}function zs(e){return new Map(e.map(t=>[t.symbolId,null]))}function Tr(e,t,n){let r=0,i=0;return D("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 Dh(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function cu(){return BF(new URL("./rust-semantic-worker.js",import.meta.url))}function lu(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return typeof n.available!="boolean"||!Array.isArray(n.references)?null:{available:n.available,reason:typeof n.reason=="string"?n.reason:void 0,references:n.references,incompleteReferenceSymbolIds:Array.isArray(n.incompleteReferenceSymbolIds)?n.incompleteReferenceSymbolIds.filter(r=>typeof r=="number"):void 0,callees:Array.isArray(n.callees)?n.callees:void 0,signatures:Array.isArray(n.signatures)?n.signatures:void 0}}catch{return null}}function _r(e,t){return Sn(e)??t}function Vs(e,t){if(!e)return t;let n=Number(e);return Number.isInteger(n)&&n>=0?n:t}import{existsSync as YF,readFileSync as XF}from"fs";import{deserializeSCIP as QF,SymbolRole as ZF}from"@c4312/scip";var uu=new WeakMap;function kh(e,t){let n=t.filter(eL);if(n.length===0)return new Map;let r=!1,i=0,o=0;return D("rust.scip-occurrence.callees",()=>{let s=rL(e);if(r=!!s,!s)return new Map;let a=new Map;for(let c of n){let l=tL(e,s,c);l!==null&&(a.set(c.symbolId,l),i+=1,o+=l.length)}return a},()=>({definitions:t.length,candidates:n.length,indexAvailable:r,resolvedDefinitions:i,resolvedCallees:o}))}function eL(e){return!(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||!e.isFunctionLike||e.leaf==="main"||Re(e.symbol))}function tL(e,t,n){let r=W(e,n.relativePath);if(!r||r.language!=="rust")return null;let i=r.callables.find(l=>l.startLine!==n.startLine||l.endLine!==n.endLine?!1:l.name===n.leaf||n.leaf.endsWith(l.name)||l.name.endsWith(n.leaf));if(!i)return null;let o=r.callSites.filter(l=>l.line>=i.startLine&&l.line<=i.endLine);if(o.length===0)return null;let s=(t.occurrencesByFile.get(n.relativePath)??[]).filter(l=>l.line>=i.startLine&&l.line<=i.endLine&&l.callee.symbol!==n.symbol);if(s.some(l=>l.traitImplMember)||!nL(o,s))return null;let a=[],c=new Set;for(let l of s){let u=`${l.callee.symbol}\0${l.callee.file}\0${l.callee.line}`;c.has(u)||(c.add(u),a.push(l.callee))}return a}function nL(e,t){let n=Eh(e),r=Eh(t);if(n.size!==r.size)return!1;for(let[i,o]of n)if(r.get(i)!==o)return!1;return!0}function Eh(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 rL(e){if(uu.has(e))return uu.get(e)??null;let t=iL(e);return uu.set(e,t),t}function iL(e){if(!YF(e.config.indexPath))return null;try{let t=ve(e).filter(o=>o.symbol.startsWith("rust-analyzer ")&&o.relativePath.endsWith(".rs")&&o.isFunctionLike),n=new Map(t.map(o=>[o.symbol,o])),r=QF(XF(e.config.indexPath)),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&ZF.Definition)!==0)continue;let l=n.get(c.symbol);if(!l)continue;let u=c.range?.[0];Number.isInteger(u)&&a.push({line:u,leaf:l.leaf,traitImplMember:Re(l.symbol),callee:{symbol:l.symbol,file:l.relativePath,line:l.startLine}})}i.set(s,a)}return{occurrencesByFile:i}}catch{return null}}var qs=class{sessions=new WeakMap;getOrCreate(t,n,r){let i=oL(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 oL(e,t){return`${e.config.projectRoot}:${t}-workspace`}import{randomUUID as AL}from"crypto";import{existsSync as ML,mkdirSync as ey,readFileSync as OL,rmSync as ty}from"fs";import{dirname as jL,resolve as ny}from"path";import{performance as U}from"perf_hooks";function ft(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}import Ph from"path";function sL(e,t){return e.getReferences().map(n=>{let r=n.getNode();return Ks(r,t)})}function aL(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function Th(e,t,n,r){let i=[];for(let o of aL(e))for(let s of sL(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 Fr(i)}function _h(e,t,n,r){let i=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();Lr(r,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||i.push({location:Ks(a,r),node:a}))}return i}function Ks(e,t){let n=e.getSourceFile(),r=n.getLineAndColumnAtPos(e.getStart());return{file:Lr(t,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function Fh(e,t,n){let r=e.getSourceFile(),i=fu(r,e),o=e.getText(),s=new RegExp(`\\b${B(o)}\\b`,"g"),a=r.getFullText().split(`
269
- `),c=[];for(let l=0;l<a.length;l++){if(l===i)continue;let u=a[l]??"";s.lastIndex=0;let d;for(;(d=s.exec(u))!==null;)c.push({file:t,line:l,column:d.index})}return Fr(c.filter(l=>Lr(n,Ph.join(n,l.file))===t))}function du(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 fu(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function Fr(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 Lr(e,t){let n=Ph.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function Lh(e,t,n,r){let i=cL(t,r);return i.size===0?new Map:lL(e,n,i)}function cL(e,t){let n=new Map;for(let r of X(e,t)){let i=T(r.symbol)??r.leaf;if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push(r)}return n}function lL(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of uL(e,o)){let a=n.get(s);if(!a)continue;let c=fu(t,o);for(let l of a){if(c<l.startLine-1||c>l.endLine+1)continue;let u=Math.abs(c-l.startLine),d=i.get(l.symbolId);d!==void 0&&d<=u||(i.set(l.symbolId,u),r.set(l.symbolId,o))}}}),r}function uL(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 dL=j("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function Nh(e,t,n,r){let i=gu(e,t),o=mu(i.get(r)??[],n);if(o)return o;let s=[];for(let a of i.values())for(let c of a)((c.leaf||T(c.symbol)||"").includes(r)||c.symbol.includes(r))&&s.push(c);return mu(s,n)}function pu(e,t,n,r){return mu(gu(e,t).get(r)??[],n)}function Ah(e,t){let n=new Map;for(let[r,i]of gu(e,t)){let o=i[0];o&&n.set(r,o)}return n}function gu(e,t){return dL.get(e,t,()=>{let n=new Map;for(let r of X(e,t)){let i=r.leaf||T(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 mu(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 hu from"path";var Mi=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];function Dt(e){let t=e.toLowerCase();return Mi.some(n=>t.endsWith(n))}function Mh(e,t){let n=new Map,r=null,i=null,o=()=>(i??=N(e,{extensions:Mi}),i),s=()=>(r??=D("typescript.source-file-index",()=>fL(e.config.projectRoot,t,o()),()=>({projects:t.length,indexedDocuments:o().length})),r),a=c=>Dt(c)?ft(n,c,()=>{let l=Oi(hu.resolve(e.config.projectRoot,c));for(let{project:u,sourceFiles:d}of s()){let f=d.get(l)??null;if(f||(f=u.addSourceFileAtPathIfExists(l)??null,f&&d.set(Oi(f.getFilePath()),f)),f)return{project:u,sourceFile:f}}return null}):null;return{sourceFile:c=>a(c)?.sourceFile??null,sourceFileMatch:a,indexedTypeScriptLikeDocuments:o}}function fL(e,t,n){let r=t.map(({project:i})=>({project:i,sourceFiles:new Map(i.getSourceFiles().map(o=>[Oi(o.getFilePath()),o]))}));for(let i of n){let o=Oi(hu.resolve(e,i));for(let s of r){if(s.sourceFiles.has(o))break;let a=s.project.addSourceFileAtPathIfExists(o)??null;if(a){s.sourceFiles.set(Oi(a.getFilePath()),a);break}}}return r}function Oi(e){return hu.resolve(e)}function yu(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function Oh(e){let t=`${e.relativeDir}/src`;return[`${t}/index.ts`,`${t}/index.tsx`,`${t}/index.mts`,`${t}/index.cts`]}import{existsSync as ji,readFileSync as mL}from"fs";import _e from"path";var bu=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Su(e,t){let r=t?_e.dirname(_e.join(e,t)):e,i=_e.resolve(e);for(;r.startsWith(i);){for(let s of bu){let a=_e.join(r,s);if(ji(a))return a}let o=_e.dirname(r);if(o===r)break;r=o}for(let o of bu){let s=_e.join(e,o);if(ji(s))return s}return null}function jh(e){let t=e.config.projectRoot,n=new Set(pL(t,e.config.semantic?.typescript?.tsconfigs)),r=N(e,{includeIgnored:!1,extensions:Mi});for(let i of r){let o=Su(t,i);o&&n.add(_e.resolve(o))}if(n.size===0){let i=Su(t);i&&n.add(_e.resolve(i))}return[...n].filter(i=>!$h(t,i)).sort((i,o)=>i.localeCompare(o))}function pL(e,t=[]){let n=new Set;for(let r of t){let i=_e.isAbsolute(r)?r:_e.join(e,r);ji(i)&&n.add(_e.resolve(i))}for(let r of gL(e))for(let i of bu){let o=_e.join(r,i);ji(o)&&n.add(_e.resolve(o))}if(n.size===0){let r=Su(e);r&&n.add(_e.resolve(r))}return[...n].filter(r=>!$h(e,r)).sort((r,i)=>r.localeCompare(i))}function gL(e){let t=_e.join(e,"package.json");if(!ji(t))return[];let n;try{n=JSON.parse(mL(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>fl(e,i))}function $h(e,t){let n=_e.relative(e,t).replace(/\\/g,"/");return n.startsWith("..")||n.includes("/node_modules/")||n.startsWith("node_modules/")||n.includes("/dist/")||n.startsWith("dist/")}import{createRequire as hL}from"module";var Bh=hL(import.meta.url),$i,Js;function Cu(){if($i!==void 0)return $i;try{$i=Bh("ts-morph")}catch{$i=null}return $i}function Ys(){if(Js)return Js;let e=Cu();if(!e)return"ts-morph:unavailable";let t="unknown";try{t=Bh("ts-morph/package.json").version??"unknown"}catch{}return Js=`ts-morph:${t}:typescript:${e.ts.version}`,Js}function Hh(e,t){return t.map(n=>({tsconfigPath:n,project:new e.Project({tsConfigFilePath:n,skipFileDependencyResolution:!0})}))}function Xs(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}function Qs(e,t){let n=new Map(e.map(i=>[i.symbol,i])),r=new Map(e.map(i=>[i.symbolId,[]]));for(let i of t.values())for(let o of i){let s=n.get(o.targetSymbol);s&&r.get(s.symbolId).push(o.location)}for(let[i,o]of r)r.set(i,yL(o));return r}function Gh(e,t,n){let r=Wh(e,t),i=Wh(e,n),o=[...r].filter(d=>!i.has(d)).sort(),s=[...i].filter(d=>!r.has(d)).sort(),a=Uh(e,t),c=Uh(e,n),l=[...a].filter(d=>!c.has(d)).sort(),u=[...c].filter(d=>!a.has(d)).sort();return{passed:o.length===0&&s.length===0,expectedCount:r.size,actualCount:i.size,missing:o,extra:s,callerFiles:{passed:l.length===0&&u.length===0,expectedCount:a.size,actualCount:c.size,missing:l,extra:u}}}function Uh(e,t){let n=new Set;for(let r of e)for(let i of t.get(r.symbolId)??[])i.file!==r.relativePath&&n.add(`${r.symbol}\0${i.file}`);return n}function zh(e,t,n){let r=new Set(n),i=new Map(n.map(o=>[o,[]]));for(let o of e)for(let s of t.get(o.symbolId)??[])r.has(s.file)&&i.get(s.file).push({targetSymbol:o.symbol,location:s});for(let[o,s]of i)i.set(o,bL(s));return i}function Wh(e,t){let n=new Set;for(let r of e)for(let i of t.get(r.symbolId)??[])n.add(`${r.symbol}\0${i.file}\0${i.line}\0${i.column}`);return n}function yL(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(Vh)}function bL(e){let t=new Map;for(let n of e){let{location:r}=n;t.set(`${n.targetSymbol}\0${r.file}\0${r.line}\0${r.column}`,n)}return[...t.values()].sort((n,r)=>n.targetSymbol.localeCompare(r.targetSymbol)||Vh(n.location,r.location))}function Vh(e,t){return e.file.localeCompare(t.file)||e.line-t.line||e.column-t.column}var SL=32;function Qh(e,t){let n=D("typescript.provider.load",()=>Cu());if(!n)return Xs("ts-morph is not installed");let r=D("typescript.provider.tsconfig-discovery",()=>jh(e));if(r.length===0)return Xs("no tsconfig found");try{let i=D("typescript.provider.project-bundles",()=>Hh(n,r),()=>({tsconfigs:r.length}));return CL(e,n,i)}catch(i){return Xs(i instanceof Error?i.message:String(i),r[0],r)}}function CL(e,t,n,r={}){return D("typescript.provider.construct",()=>new vu(e,t,n),()=>({tsconfigs:n.length,reusedProjects:r.reusedProjects===!0}))}var vu=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=Cr(t.config.projectRoot),this.sourceFiles=Mh(t,r)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;compilerCheckerCache=new WeakMap;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(t=>t.tsconfigPath)}}importUsage(t){return ft(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let r=vL();return D("typescript.import-usage.file",()=>this.importUsageForSourceFile(t,n,r),()=>({file:t,...r}))})}referencesFor(t){return ft(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);return this.referencesForDefinitionNode(t,n)})}referencesForDefinitions(t,n={}){let r=new Map,i=H(),o=[];for(let u of t){let d=this.referencesCache.get(u.symbolId);d?r.set(u.symbolId,d):o.push(u)}if(o.length===0)return r;let s=o,a=n.exact?[]:o.filter(u=>!Kh(u));if(a.length>=SL){let u=this.referencesForDefinitionsBySymbolScan(a);for(let d of a){let f=u.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,f),r.set(d.symbolId,f)}if(s=o.filter(d=>Kh(d)),s.length===0)return r}let c=new Map;for(let u of s){let d=c.get(u.relativePath);d?d.push(u):c.set(u.relativePath,[u])}let l=[];for(let[u,d]of c){let f=Jh();D("typescript.references-map.file",()=>{let m=this.definitionNodesForFile(u);for(let p of d){i&&(f.cacheMisses+=1);let g=m.get(p.symbolId)??null;i&&(g?f.nodeHits+=1:f.nodeMisses+=1);try{let h=this.referencesForDefinitionNode(p,g,i?f:void 0);this.referencesCache.set(p.symbolId,h),r.set(p.symbolId,h)}catch{f.preciseSearchFailures+=1,l.push(p)}}},()=>({relativePath:u,definitions:d.length,...Yh(f)}))}if(l.length>0){let u=this.referencesForDefinitionsBySymbolScan(l);for(let d of l){let f=u.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,f),r.set(d.symbolId,f)}}return r}referenceFragmentsForFiles(t){let n=ve(this.db).filter(o=>Dt(o.relativePath)),r=t.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(n,r);return zh(n,i,r)}referencesForDefinitionsBySymbolScan(t,n){let r=H(),i=Jh(),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 D("typescript.references-map.inverted-scan",()=>{let c=r?U.now():0,l=n?this.packageImportReferencesForFiles(n):this.packageImportReferences();for(let h of t){let S=l.get(h.symbolId)??[];if(S.length>0){let C=o.get(h.symbolId)??[];C.push(...S),o.set(h.symbolId,C)}r&&(i.packageReferenceCount+=S.length)}r&&(i.packageRefsMs+=U.now()-c);let u=new Map,d=new Map,f=this.hierarchyTargetsForDefinitions(t),m=new Set(t.map(h=>h.leaf).filter(Boolean)),p=r?U.now():0;for(let h of n??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(h))continue;let S=this.sourceFiles.sourceFile(h);S&&(r&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(S,h,s,a,f,m,u,d,o,r?i:void 0))}r&&(i.scanMs+=U.now()-p);let g=r?U.now():0;this.addHierarchyMemberReferences(t,o,r?i:void 0),r&&(i.hierarchyMs+=U.now()-g);for(let[h,S]of o){let C=Fr(S);o.set(h,C),r&&(i.referenceCount+=C.length)}},()=>({definitions:t.length,...Yh(i)})),o}addReferencesFromSourceFileScan(t,n,r,i,o,s,a,c,l,u){let d=this.compilerCheckerForSourceFile(t),f=t.compilerNode,m=wL(t),p=g=>{if(this.tsMorph.ts.isIdentifier(g)){if(u&&(u.identifiers+=1),!s.has(g.text)&&!m.has(g.text)){this.tsMorph.ts.forEachChild(g,p);return}let h=this.compilerReferenceSymbol(d,g,u);if(h){let S;a.has(h)?S=a.get(h)??null:(S=this.referenceDefinitionFromCompilerSymbol(h),a.set(h,S)),u&&(S?u.targetHits+=1:u.targetMisses+=1);let C=ft(c,h,()=>this.compilerSymbolKeys(h)),x=null,b=null,y=S&&r.has(S.symbolId)?i.get(S.symbolId):void 0;if(y&&(x=xu(f,g),!qh(y,n,x))){let R=f.getLineAndCharacterOfPosition(g.getStart(f));b={file:n,line:R.line,column:R.character};let v=l.get(y.symbolId)??[];v.push(b),l.set(y.symbolId,v),u&&(u.requestedHits+=1)}for(let R of C)for(let v of o.get(R)?.values()??[]){if(x??=xu(f,g),qh(v,n,x))continue;if(!b){let I=f.getLineAndCharacterOfPosition(g.getStart(f));b={file:n,line:I.line,column:I.character}}let E=l.get(v.symbolId)??[];E.push(b),l.set(v.symbolId,E),u&&(u.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(g,p)};p(f)}hierarchyTargetsForDefinitions(t){let n=new Map;for(let r of t){let i=this.nodeForDefinition(r),o=i?.compilerNode;if(!o||!this.isHierarchyMethod(o))continue;let s=o.parent;if(!this.isHierarchyContainer(s))continue;let a=this.compilerCheckerForSourceFile(i.getSourceFile()),c=a.getSymbolAtLocation(o.name);if(c)for(let l of this.hierarchyMemberSymbols(a,s,c))for(let u of this.compilerSymbolKeys(l)){let d=n.get(u)??new Map;d.set(r.symbolId,r),n.set(u,d)}}return n}hierarchyMemberSymbols(t,n,r){let i=new Set,o=new Set,s=(a,c,l)=>{if(!o.has(a)){o.add(a),i.add(c);for(let u of l){let d=u.getProperty(r.name);d&&s(u,d,this.hierarchyAncestorTypesForType(t,u))}}};return s(t.getTypeAtLocation(n),r,this.hierarchyAncestorTypes(t,n)),i}addHierarchyMemberReferences(t,n,r){let i=new Map;for(let o of t){let s=this.nodeForDefinition(o),a=s?.compilerNode;if(!a||!this.isHierarchyMethod(a))continue;let c=a.parent;if(!this.isHierarchyContainer(c))continue;let l=this.compilerCheckerForSourceFile(s.getSourceFile()),u=l.getSymbolAtLocation(a.name);if(!u)continue;let d=a.getSourceFile(),f=d.getLineAndCharacterOfPosition(a.name.getStart(d)),m={definition:o,location:{file:o.relativePath,line:f.line,column:f.character}},p=n.get(o.symbolId)??[];for(let h of this.hierarchyMemberSymbols(l,c,u))if(h!==u)for(let S of this.compilerSymbolLocations(h))p.push(S),r&&(r.hierarchyReferences+=1);n.set(o.symbolId,p);let g=this.hierarchyRootMemberSymbols(l,c,u);for(let h of g){let S=i.get(h)??new Map;S.set(o.symbolId,m),i.set(h,S)}r&&(r.hierarchyDefinitions+=1)}for(let o of i.values())if(!(o.size<2)){r&&(r.hierarchyFamilies+=1);for(let{definition:s}of o.values()){let a=n.get(s.symbolId)??[];for(let c of o.values())c.definition.symbolId!==s.symbolId&&(a.push(c.location),r&&(r.hierarchyReferences+=1));n.set(s.symbolId,a)}}}hierarchyRootMemberSymbols(t,n,r){let i=new Set,o=new Set,s=(a,c,l)=>{if(o.has(a))return;o.add(a);let u=!1;for(let d of l){let f=d.getProperty(r.name);f&&(u=!0,s(d,f,this.hierarchyAncestorTypesForType(t,d)))}if(!u)for(let d of this.compilerSymbolKeys(c))i.add(d)};return s(t.getTypeAtLocation(n),r,this.hierarchyAncestorTypes(t,n)),i}compilerSymbolKeys(t){return(t.declarations??[]).map(n=>{let r=n.getSourceFile();return`${r.fileName}\0${n.getStart(r)}\0${t.name}`})}compilerSymbolLocations(t){let n=[];for(let r of t.declarations??[]){let i=r.getSourceFile(),o=Lr(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 ft(this.calleesCache,t.symbolId,()=>ft(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}calleesForDefinitions(t){let n=new Map,r=new Map;for(let i of t){let o=r.get(i.relativePath);o?o.push(i):r.set(i.relativePath,[i])}for(let[i,o]of r){let s=this.fileCalleesCache.get(i),a=new Set(o.map(l=>l.symbolId)),c=s??this.calleeMapForFile(i,a);for(let l of o){let u=c.get(l.symbolId)??[];this.calleesCache.set(l.symbolId,u),n.set(l.symbolId,u)}}return n}referencesForDefinitionNode(t,n,r){let i=r?U.now():0,o=this.packageImportReferencesForDefinition(t);if(r&&(r.packageRefsMs+=U.now()-i,r.packageReferenceCount+=o.length),!n)return o;let s=r?U.now():0,a=Th(n,t,o,this.db.config.projectRoot);return r&&(r.semanticRefsMs+=U.now()-s,r.referenceCount+=a.length),a}signatureFor(t){return ft(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 Xh(c)}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${Xh(o)}`})}importUsageForSourceFile(t,n,r){let i=[],o=new Map;for(let s of n.getImportDeclarations()){r.declarations+=1;let a=Qe(this.db,t,s.getModuleSpecifierValue()),c=s.getImportClause()?.isTypeOnly()??!1;for(let l of Ru(s)){r.entries+=1;let u=c?null:l.identifier?.getSymbol()?.compilerSymbol??null;!c&&l.identifier&&(u?r.bindingSymbols+=1:r.missingBindingSymbols+=1);let d={sourcePath:a,entry:l,typeOnlyDeclaration:c,bindingSymbol:u,references:[]};if(i.push(d),c||!l.localName||!u)continue;let f=o.get(l.localName);f?f.push(d):o.set(l.localName,[d])}}return o.size>0&&n.forEachDescendant(s=>{if(s.getKindName()!=="Identifier")return;let a=o.get(s.getText());if(!a||RL(s))return;r.scannedIdentifiers+=1;let c=s.getSymbol()?.compilerSymbol;if(r.symbolLookups+=1,!!c){for(let l of a)if(l.bindingSymbol===c){l.references.push({location:Ks(s,this.db.config.projectRoot),node:s}),r.matchedReferences+=1;break}}}),i.map(s=>s.typeOnlyDeclaration?xL(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 _h(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=>!du(c.node)),s=i.some(c=>du(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=yu(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,Fr(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,Fr(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=yu(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of Ru(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=Fh(a.identifier,r,this.db.config.projectRoot);l.length>0&&PL(t,c,l)}}packageExports(){return this.packageExportIndex?this.packageExportIndex:(this.packageExportIndex=this.packageExportsForNames(new Set(this.workspacePackages.map(t=>t.name))),this.packageExportIndex)}packageExportsForNames(t){let n=new Map;for(let r of this.workspacePackages){if(!t.has(r.name))continue;let i=new Map;for(let o of Oh(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?Qe(this.db,n,a):n;if(!c||!c.startsWith(`${t.relativeDir}/src/`))continue;let l=s.getNamedExports();if(l.length===0){if(s.isNamespaceExport())continue;this.collectPackageExports(t,c,r,i);continue}for(let u of l){let d=u.getNameNode().getText(),f=u.getAliasNode()?.getText()??d,m=this.indexedDefinitionByLeaf(c,d);if(!m)continue;let p=r.get(f);p||(p=new Set,r.set(f,p)),p.add(m.symbolId)}}}indexedDefinitionByLeaf(t,n){return ft(this.indexedDefinitionLeafCache,t,()=>Ah(this.db,t)).get(n)??null}nodeForDefinition(t){return ft(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return ft(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?Lh(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?U.now():0,s=t.declarations??[];n&&(n.declarationsMs+=U.now()-o,n.declarationChecks+=s.length);for(let a of s){let c=n?U.now():0,l=a.getSourceFile(),u=Lr(this.db.config.projectRoot,l.fileName),d=l.getLineAndCharacterOfPosition(a.getStart(l)).line;if(n&&(n.declarationLocationMs+=U.now()-c),!u||this.db.isIgnored(u))continue;let f=n?U.now():0,m=this.compilerDeclarationName(a),p=r?pu(this.db,u,d,i)??(m&&m!==i?pu(this.db,u,d,m):null):Nh(this.db,u,d,i);if(n&&(n.indexedLookupMs+=U.now()-f),p)return{symbolId:p.symbolId,symbol:p.symbol,file:p.relativePath,line:p.startLine}}return null}compilerDeclarationName(t){let n=t.name;return n&&this.tsMorph.ts.isIdentifier(n)?n.text:null}calleeMapForFile(t,n){let r=H(),i=0,o=0,s=0,a=0,c=0,l=0,u=0,d=0,f=r?EL():void 0;return D("typescript.callee-map.file",()=>{let m=r?U.now():0,p=this.sourceFiles.sourceFile(t);if(r&&(c=Math.round(U.now()-m)),!p)return new Map;let g=r?U.now():0,h=X(this.db,t).sort((E,I)=>E.startLine-I.startLine||I.endLine-E.endLine);if(r&&(l=Math.round(U.now()-g)),i=h.length,h.length===0)return new Map;let S=new Map,C=r?U.now():0,x=this.compilerCheckerForSourceFile(p),b=p.compilerNode;r&&(u=Math.round(U.now()-C));let y=new Map,R=E=>{if(this.tsMorph.ts.isCallExpression(E)||this.tsMorph.ts.isNewExpression(E)){r&&(o+=1);let I=this.semanticCalleeForCallNode(x,b,h,E,y,n,f);I&&(r&&(s+=1),IL(S,I.callerId,I.target))}this.tsMorph.ts.forEachChild(E,R)},v=r?U.now():0;R(b),r&&(d=Math.round(U.now()-v));for(let[E,I]of S)S.set(E,TL(I));return a=S.size,S},()=>({relativePath:t,definitions:i,callNodes:o,resolvedCallees:s,outputRows:a,requestedDefinitions:n?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:u,traversalMs:d,...f?kL(f):{}}))}semanticCalleeForCallNode(t,n,r,i,o,s,a){let c=a?U.now():0,l=DL(r,xu(n,i));if(a&&(a.callerLookupMs+=U.now()-c),!l)return null;if(s&&!s.has(l.symbolId))return a&&(a.skippedUnrequestedCallers+=1),null;let u=i.expression,d=this.compilerSymbolForExpression(t,u,a),f=null;if(d)if(a&&(a.targetSymbolHits+=1),o.has(d))a&&(a.compilerSymbolCacheHits+=1),f=o.get(d)??null;else{a&&(a.compilerSymbolCacheMisses+=1);let m=a?U.now():0;f=this.definitionFromCompilerSymbol(d,a),a&&(a.targetLookupMs+=U.now()-m),o.set(d,f)}else a&&(a.targetMisses+=1);return f?{callerId:l.symbolId,target:{symbol:f.symbol,file:f.file,line:f.line}}:null}compilerSymbolForExpression(t,n,r){let i=r?U.now():0,o=t.getSymbolAtLocation(n);if(r&&(r.expressionSymbolMs+=U.now()-i),o)return o;r&&(r.typeFallbacks+=1);let s=r?U.now():0,a=t.getTypeAtLocation(n).getSymbol();return r&&(r.typeSymbolMs+=U.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 Ru(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 xL(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 vL(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function RL(e){for(let t=e;t;t=t.getParent())if(t.getKindName()==="ImportDeclaration")return!0;return!1}function IL(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function wL(e){let t=new Set;for(let n of e.getImportDeclarations())for(let r of Ru(n))r.localName&&t.add(r.localName);return t}function DL(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 xu(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line}function qh(e,t,n){return t===e.relativePath&&n>=e.startLine&&n<=e.endLine}function Kh(e){return e.symbol.includes("#")?le(e.symbol)==="type"&&e.relativePath.endsWith(".d.ts"):!1}function EL(){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 kL(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 Jh(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0,preciseSearchFailures:0,hierarchyDefinitions:0,hierarchyFamilies:0,hierarchyReferences:0,hierarchyMs:0}}function Yh(e){return{...e,scanMs:Math.round(e.scanMs),packageRefsMs:Math.round(e.packageRefsMs),semanticRefsMs:Math.round(e.semanticRefsMs),hierarchyMs:Math.round(e.hierarchyMs)}}function PL(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function TL(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}|${r.line}`;t.has(i)||(t.add(i),n.push(r))}return n}function Xh(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}import{createHash as _L}from"crypto";import{readFileSync as FL}from"fs";import{dirname as LL,join as Zs}from"path";var ea=2,NL="typescript-semantic";function Zh(e){let t=Zs(e,NL);return{rootDir:t,requestDir:Zs(t,"requests"),responseDir:Zs(t,"responses")}}function ta(e){try{let t=JSON.parse(FL(Zs(LL(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||typeof t.status!="string"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:_L("sha256").update(JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages})).digest("hex")}catch{return null}}var $L=12e4,BL=5;function oy(e,t,n={}){let r=new Iu(e,n),i=null,o=null,s=process.env.SCIP_QUERY_SKIP_WATCH_SERVICE==="1",a=()=>(i??=Qh(e,t),i),c=(d,f,m)=>{if(s)return m();try{return f(r.request(d))}catch{return s=!0,m()}},l=(d,f)=>c({kind:"references",definitions:[...d],...f?.exact?{exact:!0}:{}},m=>iy(m),()=>a().referencesForDefinitions?.(d,f)??new Map(d.map(m=>[m.symbolId,a().referencesFor(m)]))),u=d=>c({kind:"callees",definitions:[...d]},f=>iy(f),()=>a().calleesForDefinitions?.(d)??new Map(d.map(f=>[f.symbolId,a().calleesFor(f)])));return{language:"typescript",availability:()=>(o??=c({kind:"availability"},WL,()=>a().availability()),o),importUsage:d=>c({kind:"import-usage",file:d},f=>f,()=>a().importUsage(d)),referencesFor:d=>l([d]).get(d.symbolId)??[],referencesForDefinitions:l,referenceFragmentsForFiles:d=>c({kind:"reference-fragments",files:[...d]},f=>UL(f),()=>a().referenceFragmentsForFiles?.(d)??new Map),calleesFor:d=>u([d]).get(d.symbolId)??[],calleesForDefinitions:u,signatureFor:d=>c({kind:"signature",definition:d},GL,()=>a().signatureFor(d)),dispose:()=>i?.dispose?.()}}var Iu=class{constructor(t,n={}){this.db=t;this.runtime=n.runtime??VL,this.timeoutMs=n.timeoutMs??zL(),this.cacheDir=jL(t.config.dbPath),this.projectRoot=Ke(t.config.projectRoot)}db;runtime;timeoutMs;cacheDir;projectRoot;request(t){let n=zo(this.cacheDir),r=Zh(this.cacheDir),i=li(n.statePath);if(!ry(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript semantic service is not running.");let o=ta(this.db.config.dbPath);if(!o)throw new Error("Published TypeScript generation identity is unavailable.");let s=this.runtime.randomId(),a=ny(r.requestDir,`${s}.json`),c=ny(r.responseDir,`${s}.json`),l=this.runtime.now()+this.timeoutMs;ey(r.requestDir,{recursive:!0}),ey(r.responseDir,{recursive:!0}),he(a,{protocolVersion:ea,id:s,generation:o,deadlineAtMs:l,profileEnvironment:wm(),request:t});try{for(;this.runtime.now()<=l;){if(ML(c))return HL(OL(c,"utf8"),s,o);let u=li(n.statePath);if(!ry(u,this.projectRoot,this.runtime))throw new Error("TypeScript semantic service stopped while processing a request.");this.runtime.sleep(BL)}throw new Error(`TypeScript semantic service timed out after ${this.timeoutMs}ms.`)}finally{ty(a,{force:!0}),ty(c,{force:!0})}}};function ry(e,t,n){let r=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=zc,i=e?.typescriptSemantic?.busyUntil!==void 0&&n.now()<=Date.parse(e.typescriptSemantic.busyUntil);return e!==null&&e.projectRoot===t&&e.typescriptSemantic?.protocolVersion===ea&&n.isProcessAlive(e.pid)&&(r||i)}function HL(e,t,n){let r=JSON.parse(e);if(r.protocolVersion!==ea||r.id!==t||r.ok===!0&&r.generation!==n)throw new Error("TypeScript semantic service wrote an incompatible response.");if(r.ok===!0)return r.response;throw new Error(typeof r.error=="string"?r.error:"TypeScript semantic service request failed.")}function iy(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid numeric map.");return new Map(e)}function UL(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid string map.");return new Map(e)}function WL(e){if(!e||typeof e!="object"||typeof e.available!="boolean")throw new Error("TypeScript semantic service wrote invalid availability.");return e}function GL(e){if(e!==null&&typeof e!="string")throw new Error("TypeScript semantic service wrote an invalid signature.");return e}function zL(){let e=Number(process.env.SCIP_TYPESCRIPT_SEMANTIC_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:$L}var VL={now:Date.now,randomId:AL,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:Ae};var sy=new qs;cn({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>sy.clear(e)});function Nr(e,t){let n=we(t)??"typescript";return sy.getOrCreate(e,n,()=>n==="rust"?wh(e.config.projectRoot,{sourceImportUsageResolver:{importUsageFacts:r=>Pg(e,r)},calleeSymbolResolver:kg(e),sourceZeroCalleeOracle:r=>qL(e,r),scipOccurrenceCalleeOracle:r=>kh(e,r)}):oy(e,t))}function we(e){return e?M(e)==="rust"?"rust":Dt(e)?"typescript":null:"typescript"}function qL(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{existsSync as KL,readFileSync as JL}from"fs";import{resolve as YL}from"path";var XL=/^[A-Za-z_][A-Za-z0-9_]*$/,ay=/\bDefault::default\b/g,QL=/^\.\.\s*Default::default\b/;function cy(e,t){let n=new Map,r=new Map;for(let i of t){let o=wu(e,i,r);o!==null&&n.set(i.symbolId,o)}return n}function wu(e,t,n=new Map){let r=eN(t.symbol);if(!r)return null;let i=Pr(e,[t.symbolId]);if(i.length===0)return null;let o=new RegExp(`(^|[^A-Za-z0-9_])${B(r)}::default\\b`,"g"),s=new RegExp(`(^|[^A-Za-z0-9_])${B(r)}\\s*$`),a=ZL(e,t.symbolId),c=[];for(let l of i){let u=tN(e,l.relative_path,n);if(u===null)return null;let d=u.split(/\r?\n/),f=0,m=[],p=0;for(let g=l.chunk_start;g<=l.chunk_end&&g<d.length;g+=1){let S=d[g]??"",C=new Set;o.lastIndex=0;let x;for(;x=o.exec(S);)c.push({file:l.relative_path,line:g,column:x.index+x[1].length+r.length+2}),p+=1;for(let b=0;b<S.length;b+=1){let y=QL.exec(S.slice(b));if(y){if(a&&m.includes(f)){let v=b+y[0].lastIndexOf("default");c.push({file:l.relative_path,line:g,column:v}),C.add(v),p+=1}b+=y[0].length-1;continue}let R=S[b];if(R==="{"){let v=s.test(S.slice(0,b));f+=1,v&&m.push(f);continue}if(R==="}")for(f=Math.max(0,f-1);m.length>0&&m[m.length-1]>f;)m.pop()}for(ay.lastIndex=0;x=ay.exec(S);){let b=x.index+9;if(!C.has(b))return null}}if(p===0)return null}return Os(c)}function ZL(e,t){return e.get("SELECT 1 AS present FROM mentions WHERE symbol_id = ? AND role = 1 LIMIT 1",t)?.present===1}function eN(e){let t=/impl#\[([^\]]+)\]\[Default\]default\(\)\./.exec(e)?.[1]??null;return!t||!XL.test(t)?null:t}function tN(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:nN(e,t);return n.set(t,i),i}function nN(e,t){let n=YL(e.config.projectRoot,t);if(!KL(n))return null;try{return JL(n,"utf8")}catch{return null}}import{readFileSync as vN}from"fs";import{dirname as RN,join as IN}from"path";var ly=On({kind:"file-dependency-graph",invalidation:q("file-dependency-graph"),serialize:e=>JSON.stringify(e),deserialize:lN}),rN=j("file-dep-graph",{clearGroups:["whole-project"]});function se(e,t,n={}){let r=n.scipEdges??"all-references";return rN.get(e,`${r}:${t??""}`,()=>{let i=new Set(N(e,{includeIgnored:!1})),o=Te(e),s=sN(t,r),a=0,c=0,l=null,u=!1,d=0,f=0;return D("file-dep-graph.product",()=>{if(o){let h=ly.read(e,s,o);if(h){u=!0;let S=cN(h);return a=h.sourceFileCount,c=h.sourceEdgeCount,d=h.scipEdgeCount,f=S.size,l=h.sourceImportFingerprint,S}}let m=D("file-dep-graph.source-imports",()=>{let h=iN(e,i,t);return a=h.files.length,c=h.edges.length,l=h.fingerprint,h},()=>({scope:t??null,files:a,edges:c})),p=new Map,g=(h,S)=>mN(e,p,i,h,S);D("file-dep-graph.scip-edges",()=>{for(let h of fN(e,t,r))d+=1,g(h.from_file,h.to_file)},()=>({scope:t??null,edges:d}));for(let h of m.edges)g(h.fromFile,h.toFile);return f=p.size,o&&ly.write(e,s,o,{sourceImportFingerprint:m.fingerprint,sourceFileCount:m.files.length,sourceEdgeCount:m.edges.length,scipEdgeCount:d,graph:aN(p)}),p},()=>({scope:t??null,available:o!==null,hit:u,files:a,sourceEdges:c,scipEdges:d,graphFiles:f,sourceImportFingerprint:l}))})}function iN(e,t,n){let r=[],i=[];for(let o of t)if(!(n&&!o.includes(n))){r.push(o);for(let s of ne(e,o))s.sourcePath&&i.push({fromFile:o,toFile:s.sourcePath})}return{files:r,edges:i,fingerprint:oN(r,i)}}function oN(e,t){let n=t.map(r=>`${r.fromFile}\0${r.toFile}`).sort();return ge(JSON.stringify({files:e,edges:n}))}function sN(e,t){return`edge-mode-v2:${t}:${e??"<all>"}`}function aN(e){return[...e].map(([t,n])=>[t,[...n]])}function cN(e){return new Map(e.graph.map(([t,n])=>[t,new Set(n)]))}function lN(e){let t=JSON.parse(e);return uN(t)?t:null}function uN(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.sourceImportFingerprint=="string"&&typeof t.sourceFileCount=="number"&&typeof t.sourceEdgeCount=="number"&&typeof t.scipEdgeCount=="number"&&Array.isArray(t.graph)&&t.graph.every(dN)}function dN(e){return Array.isArray(e)&&e.length===2&&typeof e[0]=="string"&&Array.isArray(e[1])&&e[1].every(t=>typeof t=="string")}function fN(e,t,n){let r=t?"AND d1.relative_path LIKE ?":"",i=t?[`%${t}%`]:[],o=n==="imports-only"?"AND m.role = 2":"AND m.role != 1";return e.all(`SELECT DISTINCT
270
- d1.relative_path AS from_file,
271
- d2.relative_path AS to_file
272
- FROM mentions m
273
- JOIN chunks c ON m.chunk_id = c.id
274
- JOIN documents d1 ON c.document_id = d1.id
275
- JOIN global_symbols gs ON m.symbol_id = gs.id
276
- JOIN (
277
- SELECT m2.symbol_id, c2.document_id
278
- FROM mentions m2
279
- JOIN chunks c2 ON m2.chunk_id = c2.id
280
- WHERE m2.role = 1
281
- GROUP BY m2.symbol_id
282
- ) sym_def ON sym_def.symbol_id = gs.id
283
- JOIN documents d2 ON sym_def.document_id = d2.id
284
- WHERE d1.id != d2.id
285
- ${o}
286
- ${e.pathExclusionsFor("d1","d2")}
287
- ${r}`,...i)}function mN(e,t,n,r,i){if(r===i||e.isIgnored(r)||e.isIgnored(i)||!n.has(i))return;let o=t.get(r);o||(o=new Set,t.set(r,o)),o.add(i)}function my(e){return!Ze(e)||typeof e.version!="number"||xe(e.languages)===null||typeof e.pnpmWorkspaces!="boolean"||typeof e.typescriptProjectMode!="string"||xe(e.typescriptProjects)===null||e.clojureConfigPath!==void 0&&typeof e.clojureConfigPath!="string"||!Array.isArray(e.files)||!e.files.every(pN)?null:e}function e7(e,t){let n=new Map((e?.files??[]).map(a=>[a.path,a])),r=new Map(t.files.map(a=>[a.path,a])),i=new Set([...n.keys(),...r.keys()]),o=[];for(let a of[...i].sort()){let c=n.get(a),l=r.get(a),u=$s(a,t.languages);!c&&l?o.push({kind:"added",path:a,inputKind:u,after:l}):c&&!l?o.push({kind:"deleted",path:a,inputKind:u,before:c}):c&&l&&(c.hash!==l.hash||c.size!==l.size)&&o.push({kind:"modified",path:a,inputKind:u,before:c,after:l})}let s=new Set;return e||s.add("prior-snapshot-unavailable"),e&&e.version!==t.version&&s.add("snapshot-version-changed"),(uy(e?.files??[])||uy(t.files))&&s.add("duplicate-input-path"),[...e?.files??[],...t.files].some(gN)&&s.add("unreadable-input"),{version:1,changes:o,projectIdentityChanged:e?!bN(e,t):!0,uncertainty:[...s].sort()}}function uy(e){return new Set(e.map(t=>t.path)).size!==e.length}function pN(e){return Ze(e)&&typeof e.path=="string"&&typeof e.size=="number"&&typeof e.hash=="string"}function gN(e){return e.hash==="unreadable"||e.size<0}function hN(e){let t=new Set;for(let n of e.uncertainty)t.add(n);e.projectIdentityChanged&&t.add("project-identity-changed");for(let n of e.changes)n.kind==="added"&&t.add("file-added"),n.kind==="deleted"&&t.add("file-deleted"),n.inputKind==="config"&&t.add("configuration-changed"),n.inputKind==="ambient"&&t.add("ambient-declaration-changed"),n.inputKind==="other"&&t.add("unclassified-input");return{fullProject:t.size>0,reasons:[...t].sort()}}function t7(e,t,n){let r=e.changes.map(a=>a.path).sort();if(r.length===0&&!e.projectIdentityChanged&&e.uncertainty.length===0)return{mode:"none",changedFiles:r,affectedFiles:[],reasons:[]};let i=new Set(n),o=hN(e),s=new Set(o.reasons);return r.some(a=>!i.has(a))&&s.add("changed-file-outside-project"),t===null?(s.add("dependency-graph-unavailable"),dy(r,i,s)):s.size>0?dy(r,i,s):{mode:"closure",changedFiles:r,affectedFiles:yN(r,t,i),reasons:[]}}function dy(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function yN(e,t,n){let r=new Map;for(let[s,a]of t)if(n.has(s))for(let c of a){if(!n.has(c))continue;let l=r.get(c)??new Set;l.add(s),r.set(c,l)}let i=new Set(e),o=[...e];for(let s=0;s<o.length;s+=1){let a=o[s];if(a!==void 0)for(let c of r.get(a)??[])i.has(c)||(i.add(c),o.push(c))}return[...i].sort()}function bN(e,t){return fy(e.languages,t.languages)&&e.pnpmWorkspaces===t.pnpmWorkspaces&&e.typescriptProjectMode===t.typescriptProjectMode&&fy(e.typescriptProjects,t.typescriptProjects)&&e.clojureConfigPath===t.clojureConfigPath}function fy(e,t){if(e.length!==t.length)return!1;let n=[...e].sort(),r=[...t].sort();return n.every((i,o)=>i===r[o])}function ra(e){let t=na(e.projectFiles),n=new Set(t),r=new Map(e.snapshot.files.map(d=>[d.path,d])),i=e.snapshot.files.filter(d=>{let f=$s(d.path,["typescript"]);return f==="config"||f==="ambient"}).map(d=>d.path),o=na([...t,...i]),s=o.find(d=>!r.has(d)),a=new Set(e.snapshot.files.map(d=>d.path)).size!==e.snapshot.files.length,c=!s&&o.some(d=>py(r.get(d))),l=ge(JSON.stringify({pnpmWorkspaces:e.snapshot.pnpmWorkspaces,typescriptProjectMode:e.snapshot.typescriptProjectMode,typescriptProjects:na(e.snapshot.typescriptProjects),membership:t})),u=new Map;return{identityFor(d,f){if(!n.has(d))return Ar("target-outside-project");if(a)return Ar("duplicate-input-path");if(s)return Ar("missing-input-fingerprint");if(c)return Ar("unreadable-input");let m=[],p,g;if(e.graph===null)m.push("dependency-graph-unavailable"),g="whole-project",p=o;else{let C=CN(d,e.graph,u);if(C.find(b=>!r.has(b)))return Ar("missing-input-fingerprint");if(p=na([...C,...i]),p.some(b=>py(r.get(b))))return Ar("unreadable-input");g="dependency-closure"}let h=p.map(C=>xN(r.get(C)));return{version:1,key:ge(JSON.stringify({version:1,engineIdentity:e.engineIdentity,schemaVersion:f,projectIdentity:l,inputs:h})),mode:g,inputFiles:p,reasons:m}}}}function SN(e,t){let n=new Set,r=[e];for(let i=0;i<r.length;i+=1){let o=r[i];if(!(o===void 0||n.has(o))){n.add(o);for(let s of[...t.get(o)??[]].sort())n.has(s)||r.push(s)}}return[...n].sort()}function CN(e,t,n){let r=n.get(e);if(r)return r;let i=SN(e,t);return n.set(e,i),i}function xN(e){return{path:e.path,size:e.size,hash:e.hash}}function py(e){return e.size<0||e.hash==="unreadable"}function Ar(e){return{version:1,key:null,mode:"unkeyed",inputFiles:[],reasons:[e]}}function na(e){return[...new Set(e)].sort()}var wN=K("typescript-semantic-identity-context",{clearGroups:["whole-project"]});function xn(e,t,n){let r=wN.get(e,()=>DN(e));if(!r)return null;let i=`${n}\0${t}`,o=r.identities.get(i);if(o)return o;let s=r.builder.identityFor(t,n);return r.identities.set(i,s),s}function Bi(e){return N(e,{includeIgnored:!1}).filter(Dt).sort()}function DN(e){try{let t=JSON.parse(vN(IN(RN(e.config.dbPath),"meta.json"),"utf8")),n=my(t.fingerprint);return n?{builder:ra({projectFiles:Bi(e),snapshot:n,graph:se(e),engineIdentity:Ys()}),identities:new Map}:null}catch{return null}}var Du="typescript-reference-fragment-v2",oa=re({kind:"typescript-reference-fragments",invalidation:q("typescript-reference-fragments"),serialize:e=>JSON.stringify(e),deserialize:kN});function w7(e,t,n,r=e){let i=Bi(e),o=ra({projectFiles:i,snapshot:t,graph:se(e),engineIdentity:Ys()}),s=[...n].map(([a,c])=>({relativePath:a,contentHash:o.identityFor(a,Du).key,value:[...c]}));if(s.some(a=>a.contentHash===null))throw new Error("TypeScript reference fragment identity is unavailable for an affected document.");return oa.writeBatch(r,s.map(a=>({...a,contentHash:a.contentHash}))),s.length}function Eu(e,t,n){let r=t.filter(o=>Dt(o.relativePath));if(r.length===0)return ia("no TypeScript definitions");let i=ia("shadow did not run");return D("typescript.reference-fragments.shadow",()=>{try{let o=Nr(e,r[0].relativePath);if(!o.availability().available||!o.referenceFragmentsForFiles)return i=ia("TypeScript reference fragment provider is unavailable"),i;let s=Bi(e),a=new Set(s),c=o.referenceFragmentsForFiles(s),l=Qs(r,c),u=Gh(r,EN(n,a),l);if(!u.passed)return i={state:"failing",files:s.length,keyedFiles:0,writtenFiles:0,...u},i;let d=[];for(let f of s){let m=xn(e,f,Du);m?.key&&d.push({relativePath:f,contentHash:m.key,value:c.get(f)??[]})}return oa.writeBatch(e,d),i={state:"passing",files:s.length,keyedFiles:d.length,writtenFiles:d.length,...u},i}catch(o){return i=ia(o instanceof Error?o.message:String(o)),i}},()=>({...i}))}function EN(e,t){return new Map([...e].map(([n,r])=>[n,r.filter(i=>t.has(i.file))]))}function ku(e,t){if(t.length===0)return{references:new Map,files:0,cacheHits:0,cacheMisses:0,computedFiles:0};let n="fallback",r=0,i=0,o=0,s=0;return D("typescript.reference-fragments.materialize",()=>{try{let a=Bi(e);r=a.length;let c=new Map,l=new Map,u=[];for(let m of a){let p=xn(e,m,Du);if(!p?.key)return null;c.set(m,p.key);let g=oa.read(e,m,p.key);g===null?(o+=1,u.push(m)):(i+=1,l.set(m,g))}if(o===0)return n="hit",{references:Qs(t,l),files:r,cacheHits:i,cacheMisses:o,computedFiles:s};let d=Nr(e,t[0].relativePath);if(!d.availability().available||!d.referenceFragmentsForFiles)return null;let f=d.referenceFragmentsForFiles(u);if(u.some(m=>!f.has(m)))return null;s=f.size,oa.writeBatch(e,u.map(m=>({relativePath:m,contentHash:c.get(m),value:f.get(m)??[]})));for(let[m,p]of f)l.set(m,p);return n="computed",{references:Qs(t,l),files:r,cacheHits:i,cacheMisses:o,computedFiles:s}}catch{return null}},()=>({state:n,files:r,cacheHits:i,cacheMisses:o,computedFiles:s}))}function ia(e){return{state:"unavailable",files:0,keyedFiles:0,writtenFiles:0,expectedCount:0,actualCount:0,missing:[],extra:[],reason:e}}function kN(e){try{let t=JSON.parse(e);return!Array.isArray(t)||!t.every(PN)?null:t}catch{return null}}function PN(e){if(!e||typeof e!="object")return!1;let t=e,n=t.location;return typeof t.targetSymbol=="string"&&!!n&&typeof n.file=="string"&&typeof n.line=="number"&&typeof n.column=="number"}function sa(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}var TN="typescript-import-usage-v1",_N="typescript-signatures-v1",Pu=K("semantic-prefetched-callees",{clearGroups:["whole-project","source-file","semantic-provider"]}),gy=On({kind:"semantic-import-usage",invalidation:q("semantic-import-usage"),serialize:e=>JSON.stringify(e),deserialize:Dy}),hy=On({kind:"semantic-signatures",invalidation:q("semantic-signatures"),serialize:e=>JSON.stringify(e),deserialize:BN}),yy=re({kind:"typescript-import-usage",invalidation:q("typescript-import-usage"),serialize:e=>JSON.stringify(e),deserialize:Dy}),by=re({kind:"typescript-signatures",invalidation:q("typescript-signatures"),serialize:e=>JSON.stringify(e),deserialize:HN});function Oe(e){let t=new Map,n=new Set;return{capability:(r,i)=>Ey(e,r,i),importUsage:r=>LN(e,r),references:r=>xy(e,r),materializeReferences:(r,i)=>Ry(e,r,t,n,i),callerMap:r=>NN(e,r,t,n),calleeMap:r=>ON(e,r),signature:r=>jN(e,r)}}function FN(e,t){if(t.size===0)return;let n=Pu.get(e,()=>new Map);for(let[r,i]of t)n.set(r,[...i])}function Cy(e,t){if(!Pu.has(e))return{hits:[],misses:[...t]};let n=Pu.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 Ui(e,t){return Oe(e).importUsage(t)}function LN(e,t){if(we(t)==="typescript"){let o="fallback",s=0,a=0,c=0,l=0;return D("typescript.import-usage.materialize",()=>{let u=xn(e,t,TN);if(u?.key){s=1;let f=yy.read(e,t,u.key);if(f)return o="hit",a=1,f;c=1;let m=Et(e,t);if(!m)return o="unavailable",[];let p=m.importUsage(t);return yy.write(e,t,u.key,p),o="computed",p}l=1;let d=Et(e,t);return d?(o="direct-fallback",d.importUsage(t)):(o="unavailable",[])},()=>({state:o,eligible:s,cacheHits:a,cacheMisses:c,fallbacks:l}))}let n=wy(e,"semantic-import-usage",t);if(n){let o=gy.read(e,t,n);if(o)return o}let r=Et(e,t);if(!r)return[];let i=r.importUsage(t);return n&&gy.write(e,t,n,i),i}function aa(e,t){return Oe(e).references(t)}function xy(e,t){let n=wu(e,t);if(n)return n;let r=Hg(e,t);if(r)return r;let i=Et(e,t.relativePath);return i?i.referencesFor(t):[]}function vn(e,t){return Oe(e).callerMap(t)}function vy(e,t){let n=new Map,r=new Map;for(let i of t){if(we(i.relativePath)==="typescript"){let o=Et(e,i.relativePath);if(!o)continue;let s=r.get(o)??[];s.push(i),r.set(o,s);continue}Tu(e,n,i,xy(e,i))}for(let[i,o]of r){let s=ku(e,o),a=s?.references??(i.referencesForDefinitions?i.referencesForDefinitions(o,{exact:!0}):new Map(o.map(c=>[c.symbolId,i.referencesFor(c)])));!s&&H()&&Eu(e,o,a);for(let c of o)Tu(e,n,c,a.get(c.symbolId)??[])}return n}function NN(e,t,n=new Map,r=new Set){let i=new Map,o=Ry(e,t,n,r),s=0;return D("semantic.callers.from-references",()=>{for(let a of t)s+=Tu(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 Ry(e,t,n,r,i={}){let o=Te(e),s=[],a=[],c=[],l=0,u=0,d=0,f=0,m=0,p=0,g=0,h=0,S=0,C=0,x=0,b=0,y=[],R=new Map,v=t.filter(I=>we(I.relativePath)==="typescript"&&!n.has(I.symbolId)&&!r.has(I.symbolId)),E=ku(e,v);if(E){S=v.length,C=E.cacheHits,x=E.cacheMisses,b=E.computedFiles;for(let I of v)n.set(I.symbolId,E.references.get(I.symbolId)??[])}if(D("semantic.references.cache-scan",()=>{for(let[I,k]of sa(t)){let F=[];for(let L of k)n.has(L.symbolId)?u+=1:r.has(L.symbolId)?h+=1:F.push(L);if(F.length===0){g+=1;continue}let te=AN(e,o,I);if(!te){for(let L of F)we(L.relativePath)||(l+=1),c.push(L);continue}p+=1;let Y=lm(e,I,te);for(let L of F){let oe=Y.get(L.symbol)??null;if(oe!==null){let Q=MN(oe);if(Q){d+=1,n.set(L.symbolId,Q);continue}f+=1}a.push({definition:L,cacheFingerprint:te})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:l,cacheHits:d,parseFailures:f,misses:a.length,unkeyed:c.length,inMemoryHits:u,incompleteInMemoryHits:h,fullyInMemoryFiles:g,cacheReadFiles:p})),a.length>0||c.length>0){y=[...c,...a.map(I=>I.definition)],R=D("semantic.references.compute-misses",()=>{let I=_u(e,y,i);return m=I.size,I},()=>({definitions:y.length,misses:a.length,unkeyed:c.length,rows:m}));for(let I of y)R.has(I.symbolId)?(n.set(I.symbolId,R.get(I.symbolId)??[]),r.delete(I.symbolId)):r.add(I.symbolId);for(let{definition:I,cacheFingerprint:k}of a)R.has(I.symbolId)&&Ey(e,"semantic-references",I.relativePath).available&&s.push({relativePath:I.relativePath,symbol:I.symbol,projectFingerprint:k,payload:JSON.stringify(R.get(I.symbolId)??[])})}return s.length>0&&D("semantic.references.cache-write",()=>dm(e,s),()=>({entries:s.length})),R.size>0&&Eu(e,y,R),{definitions:t.length,inMemoryHits:u,incompleteInMemoryHits:h,cacheHits:d,misses:a.length,unkeyed:c.length,skippedUnsupportedLanguage:l,parseFailures:f,computed:m,incomplete:r.size,cacheWrites:s.length,fragmentDefinitions:S,fragmentCacheHits:C,fragmentCacheMisses:x,fragmentComputedFiles:b}}function AN(e,t,n){if(!t)return null;let r=we(n);return r==="typescript"?t:r==="rust"?ge(JSON.stringify({kind:"semantic-references",language:r,engine:Kn(e.config.projectRoot),projectFingerprint:t})):null}function _u(e,t,n={}){let r=H(),i=new Map,o=0,s=0,a=0,c=0,l=0,u=0,d=0,f=0,m=0;return D("semantic.references.provider-loop",()=>{let p=cy(e,t),g=Bg(e,t),h=new Map,S=n.prefetchCallees?new Map:null,C=[];for(let b of t){let y,R=()=>(y??=Et(e,b.relativePath),y);if(S){let k=R();if(k?.referencesAndCalleesForDefinitions){let F=S.get(k);F?F.push(b):S.set(k,[b]),m+=1}}let v=p.get(b.symbolId);if(v){a+=1,c+=v.length,Hi(i,b.symbolId,v,r,k=>{d+=1,f+=k});continue}let E=g.get(b.symbolId);if(E){l+=1,u+=E.length,Hi(i,b.symbolId,E,r,k=>{d+=1,f+=k});continue}let I=R();if(!I){r&&(s+=1);continue}if(r&&(o+=1),I.referencesForDefinitions){let k=h.get(I);k?k.push(b):h.set(I,[b])}else C.push({provider:I,definition:b})}let x=new Set;if(S)for(let[b,y]of S){if(!b.referencesAndCalleesForDefinitions)continue;let R=h.get(b)??[],v=b.referencesAndCalleesForDefinitions(R,y);x.add(b),FN(e,v.callees);for(let E of R){if(!v.references.has(E.symbolId))continue;let I=v.references.get(E.symbolId)??[];Hi(i,E.symbolId,I,r,k=>{d+=1,f+=k})}}for(let[b,y]of h){if(x.has(b))continue;let R=b.referencesForDefinitions(y);for(let v of y){if(!R.has(v.symbolId))continue;let E=R.get(v.symbolId)??[];Hi(i,v.symbolId,E,r,I=>{d+=1,f+=I})}}for(let{provider:b,definition:y}of C){let R=b.referencesFor(y);Hi(i,y.symbolId,R,r,v=>{d+=1,f+=v})}return i},()=>({definitions:t.length,providerHits:o,providerMisses:s,rustDefaultFastPathRows:a,rustDefaultFastPathReferences:c,rustScipOccurrenceFastPathRows:l,rustScipOccurrenceFastPathReferences:u,prefetchCalleeDefinitions:m,definitionsWithReferences:d,referenceCount:f,rows:i.size}))}function Hi(e,t,n,r,i){e.set(t,n),r&&n.length>0&&i(n.length)}function Tu(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 MN(e){try{return JSON.parse(e)}catch{return null}}function ca(e,t){return Oe(e).calleeMap(t)}function ON(e,t){let n=H(),r=new Map,i=0,o=0,s=0,a=0;return D("semantic.callees.provider-loop",()=>{let c=new Map,l=[];for(let u of t){let d=Et(e,u.relativePath);if(!d){n&&(o+=1);continue}n&&(i+=1);let f=u;if(d.calleesForDefinitions){let m=c.get(d);m?m.push(f):c.set(d,[f])}else l.push({provider:d,definition:f})}for(let[u,d]of c){let f=u.calleesForDefinitions(d);for(let m of d){let p=f.get(m.symbolId)??[];Sy(r,m.symbolId,p,n,g=>{s+=1,a+=g})}}for(let{provider:u,definition:d}of l){let f=u.calleesFor(d);Sy(r,d.symbolId,f,n,m=>{s+=1,a+=m})}return r},()=>({definitions:t.length,providerHits:i,providerMisses:o,definitionsWithCallees:s,calleeCount:a,rows:r.size}))}function Sy(e,t,n,r,i){n.length>0&&(e.set(t,n),r&&i(n.length))}function Iy(e,t){return Oe(e).signature(t)}function jN(e,t){if(we(t.relativePath)==="typescript"){let s="fallback",a=0,c=0,l=0,u=0;return D("typescript.signature.materialize",()=>{let d=xn(e,t.relativePath,_N);if(d?.key){a=1;let m=by.read(e,t.relativePath,d.key)??{};if(Object.prototype.hasOwnProperty.call(m,t.symbol))return s="hit",c=1,m[t.symbol]??null;l=1;let p=Et(e,t.relativePath);if(!p)return s="unavailable",null;let g=p.signatureFor(t);return by.write(e,t.relativePath,d.key,{...m,[t.symbol]:g}),s="computed",g}u=1;let f=Et(e,t.relativePath);return f?(s="direct-fallback",f.signatureFor(t)):(s="unavailable",null)},()=>({state:s,eligible:a,cacheHits:c,cacheMisses:l,fallbacks:u}))}let n=wy(e,"semantic-signatures",t.relativePath),r=$N(t);if(n){let s=hy.read(e,r,n);if(s)return s.signature}let i=Et(e,t.relativePath);if(!i)return null;let o=i.signatureFor(t);return n&&hy.write(e,r,n,{signature:o}),o}function wy(e,t,n){let r=Te(e);if(!r)return null;let i=we(n);return i!=="rust"?null:ge(JSON.stringify({kind:t,language:i,engine:Kn(e.config.projectRoot),projectFingerprint:r}))}function $N(e){return`${e.relativePath}\0${e.symbol}`}function Dy(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:null}catch{return null}}function BN(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 HN(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 Ey(e,t,n){let r=we(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,...Nr(e,n).availability()}}catch(i){return{slot:t,language:r,available:!1,reason:i instanceof Error?i.message:String(i)}}}function Et(e,t){if(!we(t))return null;let n=Nr(e,t);return n.availability().available?n:null}var UN=j("source-import-paths-by-local-name",{clearGroups:["whole-project","source-file"]});function la(e,t){let n=mn(t);return UN.get(e,n,()=>WN(e,n))}function WN(e,t){let n=new Map;for(let r of ne(e,t)){if(!r.sourcePath)continue;let i=r.localName??r.importedName;if(i&&ky(n,i,r.sourcePath),r.kind==="namespace")for(let o of r.usedMembers)ky(n,o,r.sourcePath)}return n}function ky(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function Mr(e,t,n){let r=qt(e).get(n);if(!r||r.length===0)return[];if(r.length===1)return[Wi(r[0])];let i=r.filter(c=>c.file===t);if(i.length>0)return i.map(Wi);let o=la(e,t),s=o.get(n);if(s)for(let c of s){let l=r.filter(u=>Je(c,u.file));if(l.length>0)return l.map(Wi)}let a=new Set;for(let c of o.values())for(let l of c)a.add(l);for(let c of a){let l=r.filter(u=>Je(c,u.file));if(l.length>0&&l.length===r.length)return l.map(Wi)}return[]}function Py(e,t,n){let r=Mr(e,t,n);if(r.length>0)return r;let i=qt(e).get(n);return!i||i.length===0?[]:i.map(Wi)}function Ty(e,t,n={}){let r=ws(e,t);if(!r)return[];let i=T(r.symbol);if(!i)return[];if(n.semantic!==!1){let s=aa(e,{...r,leaf:i,parentTypeName:null,isFunctionLike:!1,isTypeLike:!1,kind:null,documentation:null,enclosingSymbol:null});if(s.length>0){let a=new Map;for(let c of s){let l=a.get(c.file)??[];l.push(c.line),a.set(c.file,l)}return ua(e,a)}}let o=new Map;for(let s of Ue(e)){let a=P(e,s);if(!a||a.indexOf(i)===-1||s!==r.relativePath&&!Mr(e,s,i).some(u=>u.symbolId===r.symbolId))continue;let c=Es(e,s,i,s===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{});c.length>0&&o.set(s,c)}return ua(e,o)}function _y(e,t,n={}){let r=new Map;for(let c of t){if(!c.leaf)continue;let l=r.get(c.leaf)??[];l.push(c),r.set(c.leaf,l)}if(r.size===0)return new Map;let i=new Set(t.map(c=>c.symbolId)),o=new Set(r.keys()),s=Ei(o),a=new Map;for(let c of Ue(e)){if(n.skipPath?.(c)||!_s(P(e,c),s))continue;let l=Cg(e,c);if(l.size!==0){for(let u of l)if(r.has(u))for(let d of Mr(e,c,u)){if(!i.has(d.symbolId)||c===d.relativePath)continue;let f=a.get(d.symbolId);f||(f=new Set,a.set(d.symbolId,f)),f.add(c)}}}return a}function Wi(e){return{symbolId:e.symbolId,symbol:e.symbol,relativePath:e.file}}function ua(e,t){let n=[],r=new Set;for(let[i,o]of t){let s=X(e,i);for(let a of o){let c=It(s,a),l=`${i}|${a}|${c?.symbol??""}`;r.has(l)||(r.add(l),n.push({file:i,line:a,enclosingSymbol:c?.symbol??null}))}}return n}function Gi(e,t){let n=JN(e,t);return n?ua(e,zN(e,n.match,n.identifier)):[]}function kt(e,t,n={}){return GN(e,t,n).map(r=>({file:r.file,line:r.line,enclosingSymbol:r.enclosingSymbol}))}function GN(e,t,n={}){let r=Ty(e,t,{semantic:n.semantic}),i=r.length>0?Fy(r,"source-attribution"):Fy(Gi(e,t),"scip-reference-chunk");return n.includeIgnored===!0?i:i.filter(o=>!e.isIgnored(o.file))}function Fy(e,t){return e.map(n=>({...n,provenance:t}))}function zN(e,t,n){let r=new Map;for(let[i,o]of VN(e,t.symbolId))r.set(i,qN(e,i,o,t,n));return r}function VN(e,t){let n=new Map;for(let r of Pr(e,[t])){if(e.isIgnored(r.relative_path))continue;let i=n.get(r.relative_path);i||(i=[],n.set(r.relative_path,i)),i.push({start_line:r.chunk_start,end_line:r.chunk_end})}return n}function qN(e,t,n,r,i){let o=t===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{},s=i?Es(e,t,i,o):[];return n.flatMap(a=>KN(s,a))}function KN(e,t){let n=e.filter(r=>r>=t.start_line&&r<=t.end_line);return n.length>0?n:[t.start_line]}function JN(e,t){let n=ws(e,t);return n?{match:n,identifier:T(n.symbol)||null}:null}function mee(e,t,n={}){let r=$(e,t);if(!r)return[];let o=!Z(r.symbol)&&!e.isIgnored(r.relativePath)?[{relativePath:r.relativePath,line:r.startLine}]:[],s=kt(e,r,{semantic:n.semantic}).map(u=>({relativePath:u.file,line:u.line})),a=YN(e,r),c=new Set,l=[];for(let u of[...o,...s,...a]){let d=`${u.relativePath}:${u.line}`;c.has(d)||(c.add(d),l.push(u))}return l}function YN(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=XN(t.symbol);if(n.length===0)return[];let r=[];for(let i of N(e,{extensions:[".rb"],includeIgnored:!1})){let o=P(e,i);if(!o)continue;let s=o.split(`
288
- `);for(let a=0;a<s.length;a++){let c=s[a]??"";n.some(l=>new RegExp(`@${l}\\b|\\b${l}:`).test(c))&&r.push({relativePath:i,line:a})}}return r}function XN(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 QN}from"fs";import{basename as Ly,isAbsolute as ZN,join as eA}from"path";function je(e,t){let n=Ny(e,t,{allowMultiple:!1})[0]?.relativePath;return n||tA(e,t)}function Or(e,t){return Ny(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function tA(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=ZN(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,i=eA(e.config.projectRoot,r);return QN(i)?r:null}function Ny(e,t,n){let r=Ay(t);if(!r)return[];let i=N(e,{includeIgnored:!1}).map(a=>({relativePath:a,score:nA(a,r)})).filter(a=>a.score>0).sort((a,c)=>c.score-a.score||a.relativePath.localeCompare(c.relativePath));if(i.length===0){let a=$(e,t);return!a||e.isIgnored(a.relativePath)?[]:[{relativePath:a.relativePath,score:700}]}let o=i.filter(a=>a.score>=1100);if(o.length>0)return n.allowMultiple?o:[o[0]];let s=i.filter(a=>a.score>=800);return s.length>0?n.allowMultiple?s:[s[0]]:n.allowMultiple?i:[i[0]]}function nA(e,t){let n=Ay(e),r=Ly(n),i=Ly(t),o=0;return n===t&&(o+=1200),n.endsWith(`/${t}`)&&(o+=1100),r===i&&(o+=900),n.startsWith(`${t}/`)&&(o+=850),n.includes(t)&&(o+=250),o}function Ay(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}function Ree(e,t){let n=Or(e,t),r=xs(e,n,{sort:!0});if(r.length===0)return[];let i=r.map(a=>({symbol:a.symbol,shortName:a.shortName,startLine:a.startLine,endLine:a.endLine,signature:a.signature,children:[]})),o=new Map;for(let a of i)o.set(a.symbol,a);let s=[];for(let a=0;a<r.length;a++){let c=r[a],l=i[a];if(c.enclosingSymbol&&o.has(c.enclosingSymbol)){o.get(c.enclosingSymbol).children.push(l);continue}let u=null,d=1/0;for(let f of i)if(f!==l&&f.startLine<=l.startLine&&f.endLine>=l.endLine){if(f.startLine===l.startLine&&f.endLine===l.endLine&&!Om(f.symbol,l.symbol))continue;let p=f.endLine-f.startLine;p<d&&(d=p,u=f)}u?u.children.push(l):s.push(l)}return s}import{readFileSync as My}from"fs";import{extname as rA,join as Oy}from"path";function Tee(e,t,n={}){let{context:r=0}=n,i=iA(t);if(i)return sA(e,i.filePath,i.startLine,i.endLine,r);let o=$(e,t);return o?oA(e,o,r):null}function iA(e){let t=e.match(/^(.+\.\w+):(\d+)-(\d+)$/);return t?{filePath:t[1],startLine:parseInt(t[2],10),endLine:parseInt(t[3],10)}:null}function oA(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=Oy(e.config.projectRoot,t.relativePath),o;try{o=My(i,"utf-8")}catch{return null}let s=o.split(`
289
- `),a=Math.max(0,t.startLine-n),c=Math.min(s.length-1,t.endLine+n),l=s.slice(a,c+1).join(`
290
- `);return{symbol:t.symbol,shortName:w(t.symbol),relativePath:t.relativePath,startLine:a,endLine:c,language:r?.language??jy(t.relativePath),source:l}}function sA(e,t,n,r,i){let o=je(e,t);if(!o)return null;let s=e.get("SELECT relative_path, language FROM documents WHERE relative_path = ?",o);if(!s)return null;let a=Oy(e.config.projectRoot,s.relative_path),c;try{c=My(a,"utf-8")}catch{return null}let l=c.split(`
291
- `),u=Math.max(0,n-1-i),d=Math.min(l.length-1,r-1+i),f=l.slice(u,d+1).join(`
292
- `);return{symbol:`${s.relative_path}:${n}-${r}`,shortName:`${s.relative_path}:${n}-${r}`,relativePath:s.relative_path,startLine:u,endLine:d,language:s.language??jy(s.relative_path),source:f}}function jy(e){switch(rA(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}}import{createRequire as aA}from"module";var cA=aA(import.meta.url),Xn=lA().version;function lA(){for(let e of["../package.json","../../package.json"])try{return cA(e)}catch{}return{version:"0.0.0"}}import{existsSync as pd,statSync as S0}from"fs";import{join as C0}from"path";import uA from"better-sqlite3";var dA=["node_modules",".git","dist","build","out","coverage","target",".next",".nuxt",".cache",".turbo",".nbb",".cpcache",".shadow-cljs",".scipquery-cache","__pycache__",".venv","venv"],da=class{db;config;pathFilter;statementCache=new Map;constructor(t,n){this.config=t,this.pathFilter=n??null,this.db=new uA(t.dbPath,{readonly:!0}),this.db.pragma("busy_timeout = 5000"),this.db.pragma("query_only = ON"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("cache_size = -64000"),this.db.pragma("mmap_size = 268435456")}isIgnored(t){return this.pathFilter?.isIgnored(t)??!1}get localSymbolPredicate(){return`(
293
- EXISTS (
294
- SELECT 1
295
- FROM defn_enclosing_ranges local_der
296
- JOIN documents local_d ON local_der.document_id = local_d.id
297
- WHERE local_der.symbol_id = gs.id
298
- ${this.pathExclusionsFor("local_d").trimStart()}
299
- )
300
- OR EXISTS (
301
- SELECT 1
302
- FROM mentions local_m
303
- JOIN chunks local_c ON local_m.chunk_id = local_c.id
304
- JOIN documents local_d ON local_c.document_id = local_d.id
305
- WHERE local_m.symbol_id = gs.id
306
- AND local_m.role = 1
307
- ${this.pathExclusionsFor("local_d").trimStart()}
308
- )
309
- )`}get pathExclusions(){return this.pathExclusionsFor("d")}get symbolNoise(){return this.symbolNoiseFor("gs")}pathExclusionsFor(...t){return t.flatMap(n=>dA.flatMap(r=>[`AND ${n}.relative_path NOT LIKE '${r}/%'`,`AND ${n}.relative_path NOT LIKE '%/${r}/%'`])).join(`
310
- `)}symbolNoiseFor(t){return`AND ${t}.symbol NOT LIKE '%().(%' AND ${t}.symbol NOT LIKE '%typeLiteral%'`}all(t,...n){return this.statement(t).all(...n)}get(t,...n){return this.statement(t).get(...n)}close(){this.statementCache.clear(),this.db.close()}statement(t){let n=this.statementCache.get(t);return n||(n=this.db.prepare(t),this.statementCache.set(t,n)),n}};import fA from"ignore";import{readFileSync as mA,existsSync as $y,readdirSync as pA}from"fs";import{dirname as Fu,isAbsolute as By,join as fa,relative as gA,resolve as hA}from"path";function Hy(e){let t=fA();return yA(e,t)||t.add(CA),{isIgnored:r=>Lu(t,e,r),filter:r=>r.filter(i=>!Lu(t,e,i))}}function yA(e,t){let n=new Set,r=(s,a)=>{if(!(n.has(s)||!$y(s)))try{let c=mA(s,"utf-8");t.add(a?bA(c,a):c),n.add(s)}catch{}},i=Fu(e),o=0;for(;i!==Fu(i)&&o<5&&(r(fa(i,".gitignore"),""),!$y(fa(i,".git")));)i=Fu(i),o++;return Uy(e,"",t,r),n.size>0}function Uy(e,t,n,r){let i=t?fa(e,t):e;r(fa(i,".gitignore"),t);let o;try{o=pA(i,{withFileTypes:!0})}catch{return}for(let s of o){if(!s.isDirectory()||s.name===".git")continue;let a=t?`${t}/${s.name}`:s.name;Lu(n,e,`${a}/`)||Uy(e,a,n,r)}}function bA(e,t){let n=t.replaceAll("\\","/").replace(/\/+$/,"");return e.split(/\r?\n/).map(r=>SA(r,n)).join(`
311
- `)}function SA(e,t){let n=e.trimStart();if(!n||n.startsWith("#"))return e;let r=e.slice(0,e.length-n.length),i=n.startsWith("!"),o=i?n.slice(1):n;if(!o||o.startsWith("#"))return e;let s=o.startsWith("/"),a=s?o.slice(1):o,u=(a.endsWith("/")?a.slice(0,-1):a).includes("/")||s?`${t}/${a}`:`${t}/**/${a}`;return`${r}${i?"!":""}${u}`}var CA=`
312
- # Dependencies
313
- node_modules/
314
- vendor/
315
- .bundle/
316
-
317
- # Build output
318
- dist/
319
- build/
320
- out/
321
- target/
322
- bin/
323
- obj/
324
-
325
- # Python
326
- __pycache__/
327
- *.pyc
328
- *.pyo
329
- .venv/
330
- venv/
331
- .env/
332
- env/
333
- *.egg-info/
334
-
335
- # Rust
336
- target/
337
-
338
- # Java / Kotlin / Scala
339
- *.class
340
- .gradle/
341
- .mvn/
342
-
343
- # C# / .NET
344
- bin/
345
- obj/
346
- packages/
347
-
348
- # Go
349
- vendor/
350
-
351
- # Dart
352
- .dart_tool/
353
- build/
354
-
355
- # PHP
356
- vendor/
357
-
358
- # IDE / OS
359
- .idea/
360
- .vscode/
361
- *.swp
362
- *.swo
363
- .DS_Store
364
- Thumbs.db
365
-
366
- # Type definitions (often noise in queries)
367
- *.d.ts
368
- `;function Lu(e,t,n){let r=xA(t,n);if(!r)return!1;try{return e.ignores(r)}catch{return!1}}function xA(e,t){if(!t||t===".")return null;if(!By(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let n=By(t)?t:hA(e,t),r=gA(e,n).replaceAll("\\","/");return!r||r==="."||r.startsWith("..")?null:r}import{readFileSync as vA,writeFileSync as Au,existsSync as Kt,mkdirSync as RA,realpathSync as IA}from"fs";import{isAbsolute as Wy,join as ze,relative as Gy,resolve as ma}from"path";import{createHash as wA}from"crypto";import{homedir as DA}from"os";var jr=".scipquery.json",qy=250,Ky=0,Jy=10*6e4,EA={enabled:!1,debounceMs:qy,cooldownMs:Ky,gitPollMs:2e3,idleTimeoutMs:Jy,autoRefresh:!0,ignore:[]},Yy=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php","clojure"],kA=new Set(["languages","indexerConcurrency","watch","hooks","indexer","dbPath","entryRoots","semantic","suppressions","declaredCouplings","locality","coverageContracts","docs"]),PA=new Set(["enabled","debounceMs","cooldownMs","gitPollMs","idleTimeoutMs","autoRefresh","ignore"]),TA=new Set(["router"]),_A=new Set(["pathPrefixes","files","symbolPatterns","qualifiedVars"]),FA=new Set(["typescript","rust"]),LA=new Set(["tsconfigs"]),NA=new Set(["rustAnalyzerPath"]),zy=new Set(Yy),AA=new Set(["pnpmWorkspaces","projectMode","projects","configPath"]),MA=new Set(["architecturalBoundarySegments"]),OA=new Set(["snapshotPaths"]),jA=new Set(["name","files","reason"]),$A=new Set(["id","check","file","reason","expiresAt","createdAt"]),BA=new Set(["name","file","keys","mustEqual","allowExtra"]),HA=new Set(["type","identifier","marker"]),UA=new Set(["type","path","pattern"]),WA=new Set(["object-literal-keys","string-array","markdown-list"]),GA=new Set(["top-level-dirs","file-glob","registered-commands","builtin-skills"]);function Xy(e){let t=ze(e,jr);if(!Kt(t))return{};try{let n=vA(t,"utf-8");return JSON.parse(n)}catch(n){let r=n instanceof Error?n.message:String(n);throw n instanceof SyntaxError?new Error(`invalid ${jr} at ${t}: ${r}`,{cause:n}):new Error(`unable to read ${jr} at ${t}: ${r}`,{cause:n})}}function Gee(e,t={}){let n=[];KA(e,n);let r=new Set(Yy);for(let[c,l]of(e.languages??[]).entries())r.has(l)||n.push({level:"error",path:`languages[${c}]`,message:`Unsupported language: ${l}`});e.indexerConcurrency!==void 0&&(!Number.isInteger(e.indexerConcurrency)||e.indexerConcurrency<=0)&&n.push({level:"error",path:"indexerConcurrency",message:"Must be a positive integer."}),e.watch?.debounceMs!==void 0&&e.watch.debounceMs<=0&&n.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)&&n.push({level:"error",path:"watch.cooldownMs",message:"Must be a non-negative integer; 0 disables cooldown spacing."}),e.watch?.gitPollMs!==void 0&&e.watch.gitPollMs<=0&&n.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)&&n.push({level:"error",path:"watch.idleTimeoutMs",message:"Must be a non-negative integer; 0 disables idle shutdown."}),e.watch?.autoRefresh!==void 0&&typeof e.watch.autoRefresh!="boolean"&&n.push({level:"error",path:"watch.autoRefresh",message:"Must be a boolean."}),e.hooks?.router!==void 0&&e.hooks.router!=="off"&&e.hooks.router!=="single"&&n.push({level:"error",path:"hooks.router",message:'Must be "off" or "single".'});let i=e.indexer?.typescript;if(i?.projectMode!==void 0&&i.projectMode!=="single"&&i.projectMode!=="workspace"&&n.push({level:"error",path:"indexer.typescript.projectMode",message:'Must be "single" or "workspace".'}),i?.projects!==void 0)if(!Array.isArray(i.projects))n.push({level:"error",path:"indexer.typescript.projects",message:"Must be an array."});else for(let[c,l]of i.projects.entries()){let u=`indexer.typescript.projects[${c}]`;if(typeof l!="string"||l.trim()==="")n.push({level:"error",path:u,message:"Project path must be a non-empty string."});else if(t.projectRoot){let d=ma(t.projectRoot,l),f=Gy(t.projectRoot,d);f.startsWith("..")||Wy(f)?n.push({level:"error",path:u,message:"Project path must stay inside the project root."}):Kt(d)||n.push({level:"warning",path:u,message:`TypeScript project path does not exist: ${l}`})}}i?.projectMode==="workspace"&&i.pnpmWorkspaces===!0&&n.push({level:"warning",path:"indexer.typescript.pnpmWorkspaces",message:'Ignored when projectMode is "workspace"; explicit TypeScript projects are indexed directly.'});let o=e.semantic?.rust;o?.rustAnalyzerPath!==void 0&&(typeof o.rustAnalyzerPath!="string"||o.rustAnalyzerPath.trim()==="")&&n.push({level:"error",path:"semantic.rust.rustAnalyzerPath",message:"Rust analyzer path must be a non-empty string."});let s=e.indexer?.clojure;if(s?.configPath!==void 0){let c="indexer.clojure.configPath";if(typeof s.configPath!="string"||s.configPath.trim()==="")n.push({level:"error",path:c,message:"Config path must be a non-empty string."});else if(t.projectRoot){let l=ma(t.projectRoot,s.configPath),u=Gy(t.projectRoot,l);u.startsWith("..")||Wy(u)?n.push({level:"error",path:c,message:"Config path must stay inside the project root."}):Kt(l)||n.push({level:"warning",path:c,message:`Clojure indexer config path does not exist: ${s.configPath}`})}}if(e.locality!==void 0)if(!Rn(e.locality))n.push({level:"error",path:"locality",message:"Must be an object."});else{let c=e.locality.architecturalBoundarySegments;if(c!==void 0)if(!Array.isArray(c))n.push({level:"error",path:"locality.architecturalBoundarySegments",message:"Must be an array."});else for(let[l,u]of c.entries()){let d=`locality.architecturalBoundarySegments[${l}]`;typeof u!="string"||u.trim()===""?n.push({level:"error",path:d,message:"Boundary segment must be a non-empty string."}):(u.includes("/")||u.includes("\\"))&&n.push({level:"error",path:d,message:"Boundary segment must be a single folder name, not a path."})}}if(e.declaredCouplings!==void 0&&!Array.isArray(e.declaredCouplings))n.push({level:"error",path:"declaredCouplings",message:"Must be an array."});else for(let[c,l]of(e.declaredCouplings??[]).entries()){let u=`declaredCouplings[${c}]`;if((!l.name||l.name.trim()==="")&&n.push({level:"error",path:`${u}.name`,message:"Declared coupling name is required."}),!Array.isArray(l.files)||l.files.length<2)n.push({level:"error",path:`${u}.files`,message:"Declared coupling needs at least two files."});else for(let[d,f]of l.files.entries())!f||f.trim()===""?n.push({level:"error",path:`${u}.files[${d}]`,message:"Declared coupling file path is required."}):t.projectRoot&&!Kt(ze(t.projectRoot,f))&&n.push({level:"warning",path:`${u}.files[${d}]`,message:`Declared coupling file does not exist: ${f}`});l.reason!==void 0&&l.reason.trim()===""&&n.push({level:"error",path:`${u}.reason`,message:"Declared coupling reason cannot be blank."})}let a=t.now??new Date;e.suppressions!==void 0&&!Array.isArray(e.suppressions)&&n.push({level:"error",path:"suppressions",message:"Must be an array."});for(let[c,l]of(Array.isArray(e.suppressions)?e.suppressions:[]).entries()){let u=`suppressions[${c}]`;if(!Rn(l)){n.push({level:"error",path:u,message:"Suppression must be an object."});continue}if((!l.reason||l.reason.trim()==="")&&n.push({level:"error",path:`${u}.reason`,message:"Suppression reason is required."}),l.id!==void 0&&l.id.trim()===""&&n.push({level:"error",path:`${u}.id`,message:"Suppression id cannot be blank."}),l.check!==void 0&&l.check.trim()===""&&n.push({level:"error",path:`${u}.check`,message:"Suppression check cannot be blank."}),!l.id&&(!l.check||!l.file)?n.push({level:"error",path:u,message:"Suppression must include id or both check and file."}):!l.id&&l.check&&l.file&&n.push({level:"warning",path:u,message:"Check+file suppressions waive every matching finding in that file; prefer a stable id when available."}),l.file!==void 0&&(l.file.trim()===""?n.push({level:"error",path:`${u}.file`,message:"Suppression file path cannot be blank."}):t.projectRoot&&!Kt(ze(t.projectRoot,l.file))&&n.push({level:"warning",path:`${u}.file`,message:`Suppression file does not exist: ${l.file}`})),l.expiresAt){let d=Date.parse(l.expiresAt);Number.isNaN(d)?n.push({level:"error",path:`${u}.expiresAt`,message:"Must be an ISO date string."}):d<=a.getTime()&&n.push({level:"warning",path:`${u}.expiresAt`,message:"Suppression has expired."})}}return VA(e,n,t),zA(e,n),n}function zA(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(!Rn(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&&!Kt(ze(n.projectRoot,i.file))&&t.push({level:"warning",path:`${o}.file`,message:`Coverage contract file does not exist: ${i.file}`}),Vy(t,i.keys,`${o}.keys`,WA,"Unknown coverage-contract key extractor type."),Vy(t,i.mustEqual,`${o}.mustEqual`,GA,"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 Vy(e,t,n,r,i){if(!Rn(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 zee(e){return{...EA,...e.watch}}function qA(e,t){let n=process.env.SCIP_QUERY_CACHE_DIR;if(n)return Nu(n);if(t?.dbPath)return Nu(ma(e,t.dbPath));let r=pa(e);return Nu(r)}function Qy(){let e=process.env.XDG_CACHE_HOME;return ze(e||ze(DA(),".cache"),"scip-query")}function pa(e){let t=ma(e);try{t=IA(t)}catch{}let n=wA("sha256").update(t).digest("hex").slice(0,12);return ze(Qy(),"projects",n)}function zi(e){if(!/^[a-f0-9]{24}$/.test(e))throw new Error(`invalid repository cache identity: ${e}`);return ze(Qy(),"repositories",e)}function Mu(e){return process.env.SCIP_QUERY_SHARED_CACHE!=="0"&&!process.env.SCIP_QUERY_CACHE_DIR&&!process.env.SCIP_QUERY_INDEX_DB&&!e?.dbPath}function Zy(e,t){let n=qA(e,t);return{cacheDir:n,dbPath:ze(n,"index.db"),indexPath:ze(n,"index.scip"),metaPath:ze(n,"meta.json")}}function Vee(e,t){let n=ze(e,jr);return Kt(n)||Au(n,JSON.stringify({languages:t,watch:{enabled:!0,debounceMs:qy,cooldownMs:Ky,gitPollMs:2e3,idleTimeoutMs:Jy,autoRefresh:!0}},null,2)+`
369
- `),n}function qee(e,t,n){let r=ze(e,jr),i={...t,languages:[...n]},o=!Kt(r)||JSON.stringify(i)!==JSON.stringify(t);return o&&Au(r,JSON.stringify(i,null,2)+`
370
- `),{configPath:r,config:i,changed:o}}function Kee(e,t,n){let r=ze(e,jr),i={...t,watch:{...t.watch,enabled:n,...n&&t.watch?.autoRefresh===void 0?{autoRefresh:!0}:{}}},o=!Kt(r)||JSON.stringify(i)!==JSON.stringify(t);return o&&Au(r,JSON.stringify(i,null,2)+`
371
- `),{configPath:r,config:i,changed:o}}function Nu(e){return RA(e,{recursive:!0}),e}function KA(e,t){if(!Rn(e))return;let n=e;if(Fe(t,n,"",kA),Fe(t,n.watch,"watch",PA),Fe(t,n.hooks,"hooks",TA),Fe(t,n.entryRoots,"entryRoots",_A),Fe(t,n.semantic,"semantic",FA),Fe(t,n.semantic?.typescript,"semantic.typescript",LA),Fe(t,n.semantic?.rust,"semantic.rust",NA),Fe(t,n.locality,"locality",MA),Fe(t,n.docs,"docs",OA),Rn(n.indexer)){Fe(t,n.indexer,"indexer",zy);for(let[r,i]of Object.entries(n.indexer))zy.has(r)&&Fe(t,i,`indexer.${r}`,AA)}if(Array.isArray(n.declaredCouplings))for(let[r,i]of n.declaredCouplings.entries())Fe(t,i,`declaredCouplings[${r}]`,jA);if(Array.isArray(n.suppressions))for(let[r,i]of n.suppressions.entries())Fe(t,i,`suppressions[${r}]`,$A);if(Array.isArray(n.coverageContracts))for(let[r,i]of n.coverageContracts.entries()){let o=`coverageContracts[${r}]`;Fe(t,i,o,BA),Rn(i)&&(Fe(t,i.keys,`${o}.keys`,HA),Fe(t,i.mustEqual,`${o}.mustEqual`,UA))}}function Fe(e,t,n,r){if(Rn(t))for(let i of Object.keys(t))r.has(i)||e.push({level:"warning",path:n?`${n}.${i}`:i,message:"Unknown config key."})}function Rn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{existsSync as fb,readFileSync as mM}from"fs";import{execFileSync as JA}from"child_process";import{existsSync as YA,readdirSync as tb}from"fs";import{extname as nb,join as rb}from"path";var ib=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),XA=[{language:"typescript",files:["tsconfig.json","tsconfig.base.json"],extensions:[".ts",".tsx",".mts",".cts"]},{language:"rust",files:["Cargo.toml"],extensions:[".rs"]},{language:"go",files:["go.mod"],extensions:[".go"]},{language:"java",files:["pom.xml","build.gradle","build.gradle.kts"],extensions:[".java"]},{language:"kotlin",files:["build.gradle.kts"],extensions:[".kt",".kts"]},{language:"scala",files:["build.sbt"],extensions:[".scala"]},{language:"clojure",files:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],extensions:[".clj",".cljs",".cljc"]},{language:"python",files:["pyproject.toml","setup.py","setup.cfg","Pipfile"],extensions:[".py",".pyi"]},{language:"ruby",files:["Gemfile"],extensions:[".rb"]},{language:"cpp",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"]},{language:"c",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".c",".h"]},{language:"csharp",globs:["*.csproj","*.sln"],extensions:[".cs"]},{language:"vb",globs:["*.vbproj"],extensions:[".vb"]},{language:"dart",files:["pubspec.yaml"],extensions:[".dart"]},{language:"php",files:["composer.json"],extensions:[".php"]},{language:"javascript",files:["package.json"],extensions:[".js",".jsx",".mjs",".cjs"]}];function Vi(e){let t=[],n=QA(e),r=nM(e);for(let i of XA){if(ZA(e,i.files)){t.push(i.language);continue}if(eM(n,i.globs)){t.push(i.language);continue}iM(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&eb(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&eb(t,"c"),t}function QA(e){try{return tb(e)}catch{return[]}}function ZA(e,t){return t?.length?t.some(n=>YA(rb(e,n))):!1}function eM(e,t){return t?.length?e.some(n=>t.some(r=>tM(n,r))):!1}function tM(e,t){if(t==="*")return!0;if(!t.includes("*"))return e===t;let[n,r]=t.split("*");return e.startsWith(n??"")&&e.endsWith(r??"")}function nM(e){let t=rM(e);if(t)return t;let n=new Set,r=[e];for(;r.length>0;){let i=r.pop();if(!i)continue;let o;try{o=tb(i,{withFileTypes:!0})}catch{continue}for(let s of o){if(s.name.startsWith(".")&&!s.name.endsWith("proj")&&!s.name.endsWith("sln")&&s.isDirectory())continue;let a=rb(i,s.name);if(s.isDirectory()){ib.has(s.name)||r.push(a);continue}let c=nb(s.name).toLowerCase();c&&n.add(c)}}return n}function rM(e){try{let t=JA("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}),n=new Set;for(let r of t.split(`
372
- `)){if(!r||r.split("/").some(o=>ib.has(o)))continue;let i=nb(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function iM(e,t){return t?.length?t.some(n=>e.has(n)):!1}function eb(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{createHash as oM}from"crypto";import{copyFileSync as ob,existsSync as In,linkSync as sM,mkdirSync as sb,readFileSync as lb,readdirSync as ab,renameSync as ju,rmSync as ha,statSync as aM}from"fs";import{basename as ga,dirname as qi,join as Ve,relative as cb}from"path";var $r=1,ya=".scipquery-generations";function ub(e){let t=ba(e.outputDb),n=cM(e,t);e.onStage?.("after-recovery-retained"),e.preserveOutputScip||Ou(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),Ou(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),Ou(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let r=Sa(e.metaPath,e.outputDb),i={version:$r,currentGeneration:r,...n?{previousGeneration:n}:{},...e.publication?{publication:e.publication}:{},publishedAt:(e.now??(()=>new Date))().toISOString()};return he(Ve(t,"state.json"),i,{spacing:2,trailingNewline:!0}),{currentGeneration:r,...n?{previousGeneration:n}:{}}}function db(e){try{let t=JSON.parse(lb(Ve(ba(e),"state.json"),"utf8"));return t.version!==$r||typeof t.currentGeneration!="string"||!t.currentGeneration||typeof t.publishedAt!="string"||!Number.isFinite(Date.parse(t.publishedAt))||!dM(t.previousGeneration)||!fM(t.publication)?null:t}catch{return null}}function ite(e,t,n=()=>new Date){if(!In(e)||!In(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=db(e),i={version:$r,currentGeneration:Sa(t,e),...r?.previousGeneration?{previousGeneration:r.previousGeneration}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return he(Ve(ba(e),"state.json"),i,{spacing:2,trailingNewline:!0}),i}function Ki(e,t=Ve(qi(e),"meta.json")){let n=Ve(ba(e),"state.json");if(!In(n))return{state:"legacy",statePath:n};let r=db(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=Sa(t,e),o=r.currentGeneration===i,s=r.previousGeneration?In(Ve(qi(e),r.previousGeneration.databasePath)):!0;return!o||!s?{state:"drifted",statePath:n,currentMatches:o,recoveryExists:s,generation:r,reason:o?"retained recovery database is missing":"stable database or metadata no longer matches the published generation"}:{state:"current",statePath:n,currentMatches:o,recoveryExists:s,generation:r}}catch(i){return{state:"drifted",statePath:n,currentMatches:!1,recoveryExists:!1,generation:r,reason:i instanceof Error?i.message:String(i)}}}function ba(e){return Ve(qi(e),ya)}function cM(e,t){if(!In(e.outputDb))return;let n=Sa(e.metaPath,e.outputDb),r=Ve(t,n),i=Ve(r,ga(e.outputDb)),o=In(e.metaPath)?Ve(r,ga(e.metaPath)):void 0;if(!In(i)){let s=`${r}.${process.pid}.${Date.now()}.tmp`;ha(s,{recursive:!0,force:!0}),sb(s,{recursive:!0});let a=Ve(s,ga(e.outputDb));try{sM(e.outputDb,a)}catch{ob(e.outputDb,a)}o&&ob(e.metaPath,Ve(s,ga(e.metaPath))),sb(t,{recursive:!0}),ju(s,r)}return lM(t,n),{generationIdentity:n,databasePath:cb(qi(e.outputDb),i),...o?{metadataPath:cb(qi(e.outputDb),o)}:{}}}function lM(e,t){for(let n of ab(e,{withFileTypes:!0}))!n.isDirectory()||n.name===t||n.name.endsWith(".tmp")||ha(Ve(e,n.name),{recursive:!0,force:!0});for(let n of ab(e,{withFileTypes:!0}))n.isDirectory()&&n.name.endsWith(".tmp")&&ha(Ve(e,n.name),{recursive:!0,force:!0})}function Sa(e,t){let n=oM("sha256").update(`sqlite-generation-v${$r}\0`);In(e)&&n.update(uM(lb(e,"utf8")));let r=aM(t);return n.update(`\0${r.size}`),n.digest("hex")}function uM(e){try{let t=JSON.parse(e);if((t.version===2||t.version===3)&&t.status==="complete"&&typeof t.updatedAt=="string"&&t.fingerprint!==void 0)return JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages,scipCompanion:t.scipCompanion})}catch{}return e}function Ou(e,t){ha(`${t}.tmp-replace`,{force:!0}),ju(e,`${t}.tmp-replace`),ju(`${t}.tmp-replace`,t)}function dM(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e;return typeof t.generationIdentity=="string"&&!!t.generationIdentity&&typeof t.databasePath=="string"&&!!t.databasePath&&(t.metadataPath===void 0||typeof t.metadataPath=="string"&&!!t.metadataPath)}function fM(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e,n=[t.converterDurationMs,t.affectedDocumentCount,t.changedDocumentCount,t.producerDurationMs,t.materializationDurationMs,t.patchDurationMs].filter(r=>r!==void 0);return(t.mode==="incremental"||t.mode==="full")&&t.validation==="passed"&&t.converterDurationMs!==void 0&&n.every(r=>typeof r=="number"&&Number.isFinite(r)&&r>=0)&&(t.scipCompanion===void 0||t.scipCompanion==="current"||t.scipCompanion==="deferred")&&(t.typescriptOverlayGeneration===void 0||typeof t.typescriptOverlayGeneration=="string"&&!!t.typescriptOverlayGeneration)&&(t.scipCompanion!=="deferred"||!!t.typescriptOverlayGeneration)&&(t.fallbackReason===void 0||typeof t.fallbackReason=="string")}function mb(e,t,n){let r=new Date().toISOString();if(!fb(n.dbPath))return{state:"missing",checkedAt:r,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!fb(n.metaPath))return{state:"unknown",checkedAt:r,metaPath:n.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let i=JSON.parse(mM(n.metaPath,"utf-8")),o=t.languages??Vi(e),s=pM(e,o,t),a=Array.isArray(i.indexedLanguages)?[...i.indexedLanguages].sort():[],c=(i.version===2||i.version===3)&&i.status==="complete"&&JSON.stringify(i.fingerprint)===JSON.stringify(s)&&JSON.stringify(a)===JSON.stringify(s.languages),l=Ki(n.dbPath,n.metaPath),u=l.state==="invalid"||l.state==="drifted",d=c&&!u;return{state:d?"fresh":"stale",checkedAt:r,metaPath:n.metaPath,updatedAt:i.updatedAt,lastRefresh:i.lastRefresh,reason:u?`SQLite generation requires repair: ${l.reason}`:c?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:d?void 0:"Run: scip-query reindex"}}catch(i){return{state:"unknown",checkedAt:r,metaPath:n.metaPath,reason:`Could not read reindex metadata: ${i instanceof Error?i.message:String(i)}`,remedy:"Run: scip-query reindex"}}}function pM(e,t,n){return ki(e,t,{pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:n.indexer?.typescript?.projectMode,typescriptProjects:n.indexer?.typescript?.projects,clojureConfigPath:n.indexer?.clojure?.configPath})}import{createHash as Qb,randomUUID as sd}from"crypto";import{closeSync as Zb,constants as r0,copyFileSync as Kb,existsSync as Dn,lstatSync as i0,mkdirSync as Jt,mkdtempSync as eS,openSync as tS,readdirSync as o0,readFileSync as tt,realpathSync as s0,renameSync as er,rmSync as wn,statSync as a0,unlinkSync as nd,writeFileSync as nS}from"fs";import{dirname as rS,join as A,resolve as Ct}from"path";import{setTimeout as c0}from"timers/promises";import{pathToFileURL as Jb}from"url";import{deserializeSCIP as iS}from"@c4312/scip";import l0 from"better-sqlite3";import{randomUUID as pb}from"crypto";import{closeSync as gb,mkdirSync as gM,openSync as hb,readFileSync as yb,unlinkSync as bb,writeFileSync as Sb}from"fs";import{dirname as hM,join as yM}from"path";function $u(e,t={}){return Bu(yM(e,"gc.lock"),t)}function Bu(e,t={}){let n=t.waitMs??0,r=t.pollMs??10,i=t.now??Date.now,o=Date.now()+n;gM(hM(e),{recursive:!0});do{let s=pb();try{let a=hb(e,"wx");try{let c={version:1,pid:process.pid,token:s,startedAt:new Date(i()).toISOString()};Sb(a,`${JSON.stringify(c)}
373
- `)}finally{gb(a)}return{release:()=>xb(e,s)}}catch(a){if(a.code!=="EEXIST")return null;let c=Cb(e);if(c&&(c.pid===void 0||!Ae(c.pid))){bM(e,c);continue}if(Date.now()>=o)return null;SM(Math.min(r,Math.max(1,o-Date.now())))}}while(Date.now()<=o);return null}function Cb(e){try{let t=yb(e,"utf8"),n=JSON.parse(t),r=typeof n.pid=="number"&&Number.isSafeInteger(n.pid)&&n.pid>0?n.pid:void 0;return{raw:t,...r===void 0?{}:{pid:r}}}catch{return null}}function bM(e,t){let n=`${e}.reclaim`,r=pb(),i;try{i=hb(n,"wx")}catch{return!1}try{Sb(i,`${JSON.stringify({version:1,pid:process.pid,token:r,startedAt:new Date().toISOString()})}
374
- `)}finally{gb(i)}try{let o=Cb(e);return!o||o.raw!==t.raw||o.pid!==void 0&&Ae(o.pid)?!1:(bb(e),!0)}catch{return!1}finally{xb(n,r)}}function xb(e,t){try{let n=JSON.parse(yb(e,"utf8"));n.pid===process.pid&&n.token===t&&bb(e)}catch{}}function SM(e){let t=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));Atomics.wait(t,0,0,e)}import{lstatSync as NM,readdirSync as AM}from"fs";import{join as MM,relative as OM,resolve as Ju,sep as jM}from"path";import{createHash as CM}from"crypto";import{existsSync as Uu,mkdirSync as xM,readFileSync as Ca,readdirSync as bte,renameSync as vM,rmSync as Ste,writeFileSync as RM}from"fs";import{join as Br}from"path";import{create as Rb,fromBinary as Ib,toBinary as IM}from"@bufbuild/protobuf";import{deserializeSCIP as xa,DocumentSchema as Wu,IndexSchema as wb,serializeSCIP as Db}from"@c4312/scip";var va=1,Ji="typescript-scip-fragments";function Ite(e){if(e.length===0)throw new Error("affected TypeScript mini index requires documents");let t=new Set,n=[];for(let o of e){let s=Qn(o.relativePath);if(t.has(s))throw new Error(`duplicate TypeScript fragment replacement: ${s}`);if(t.add(s),o.bytes===null)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${s}`);let a=Ib(Wu,o.bytes);if(a.relativePath!==s)throw new Error(`TypeScript fragment path mismatch: expected ${s}, got ${a.relativePath}`);n.push(a)}let r=Db(Rb(wb,{documents:n,externalSymbols:[]})),i=xa(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function Ra(e){let t=Br(e,Ji);return{rootDir:t,blobDir:Br(t,"blobs"),generationDir:Br(t,"generations")}}function wM(e){let t=xa(e.indexBytes);Ab(t.metadata,Mb(e)),Nb(t.externalSymbols);let n=new Set,r=[];for(let o of t.documents){let s=Qn(o.relativePath);if(n.has(s))throw new Error(`duplicate TypeScript SCIP document path: ${s}`);n.add(s);let a=IM(Wu,o),c=e.documentIdentities.get(s)??(e.allowUntrackedDocuments?Zn(JSON.stringify({version:1,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,untrackedDocument:s,contentHash:Zn(a)})):null);if(!c)throw new Error(`missing TypeScript document identity: ${s}`);r.push(Tb(e.cacheDir,{relativePath:s,bytes:a,occurrences:o.occurrences.length,symbols:o.symbols.length,referenceFragments:[]},c))}let i=_b(e,r);return Fb(e.cacheDir,i),i}function wte(e){let t=Ra(e.cacheDir);if(!Uu(Gu(t,e.generationIdentity)))return wM(e);let n=Eb({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity});if(!e.allowUntrackedDocuments&&n.manifest.documents.length!==e.documentIdentities.size)throw new Error("TypeScript fragment generation document identities changed");for(let r of n.manifest.documents){let i=e.documentIdentities.get(r.relativePath);if(!(i===void 0&&e.allowUntrackedDocuments)&&i!==r.documentIdentity)throw new Error(`TypeScript fragment generation document identity changed: ${r.relativePath}`)}return n.manifest}function Dte(e){let t=Eb({cacheDir:e.cacheDir,generationIdentity:e.previousGenerationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity}).manifest,n=new Map(t.documents.map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let s=Qn(o.relativePath);if(r.has(s))throw new Error(`duplicate TypeScript fragment replacement: ${s}`);if(r.add(s),!n.has(s))throw new Error(`TypeScript fragment replacement has no prior document: ${s}`);let a=e.documentIdentities.get(s);if(!a)throw new Error(`missing TypeScript document identity: ${s}`);o.bytes===null?n.delete(s):n.set(s,Tb(e.cacheDir,o,a))}if(r.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=_b(e,[...n.values()]);return Fb(e.cacheDir,i),i}function Eb(e){let t=Ra(e.cacheDir),n=Gu(t,e.generationIdentity),r;try{r=Lb(Ca(n,"utf8"))}catch(o){throw new Error(`TypeScript fragment generation is unavailable: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(r.generationIdentity!==e.generationIdentity)throw new Error("TypeScript fragment generation identity does not match its manifest path");if(e.producerIdentity&&r.producerIdentity!==e.producerIdentity)throw new Error("TypeScript fragment producer identity changed");if(e.projectIdentity&&r.projectIdentity!==e.projectIdentity)throw new Error("TypeScript fragment project identity changed");let i=new Map;for(let o of r.documents){let s=Br(t.blobDir,`${o.blobHash}.scipdoc`),a=Ca(s);if(a.byteLength!==o.byteLength||Zn(a)!==o.blobHash)throw new Error(`TypeScript fragment blob is corrupt: ${o.relativePath}`);i.set(o.relativePath,a)}return{manifest:r,fragments:i}}function kb(e){let t=Pb(e);return Hu(t.baseIndex,t.completeDocuments,"assembled")}function Ete(e){let t=Pb(e);return DM(t.deletedAffectedPaths),{completeIndexBytes:Hu(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:Hu(t.baseIndex,t.affectedDocuments,"affected")}}function Pb(e){let t=xa(e.baseIndexBytes);Ab(t.metadata,Mb(e)),Nb(t.externalSymbols);let n=new Map;for(let a of e.fragments){let c=Qn(a.relativePath);if(n.has(c))throw new Error(`duplicate TypeScript fragment replacement: ${c}`);n.set(c,a)}if(n.size===0)throw new Error("TypeScript index assembly requires at least one replacement");let r=new Set,i=[],o=[],s=[];for(let a of t.documents){let c=Qn(a.relativePath);if(r.has(c))throw new Error(`duplicate TypeScript SCIP document path: ${c}`);r.add(c);let l=n.get(c);if(!l){i.push(a);continue}if(n.delete(c),l.bytes===null){s.push(c);continue}let u=Ib(Wu,l.bytes);if(u.relativePath!==c)throw new Error(`TypeScript fragment path mismatch: expected ${c}, got ${u.relativePath}`);i.push(u),o.push(u)}if(n.size>0)throw new Error(`TypeScript fragment replacement has no prior document: ${[...n.keys()].sort()[0]}`);return{baseIndex:t,completeDocuments:i,affectedDocuments:o,deletedAffectedPaths:s}}function Hu(e,t,n){let r=Db(Rb(wb,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=xa(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function DM(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function Tb(e,t,n){if(t.bytes===null)throw new Error(`cannot persist an empty TypeScript fragment: ${t.relativePath}`);let r=Qn(t.relativePath),i=Buffer.from(t.bytes),o=Zn(i),s=Ra(e);xM(s.blobDir,{recursive:!0});let a=Br(s.blobDir,`${o}.scipdoc`);if(Uu(a)){let c=Ca(a);if(c.byteLength!==i.byteLength||Zn(c)!==o)throw new Error(`existing TypeScript fragment blob is corrupt: ${r}`)}else{let c=`${a}.${process.pid}.${Date.now()}.tmp`;RM(c,i),vM(c,a)}return{relativePath:r,blobHash:o,byteLength:i.byteLength,documentIdentity:n}}function _b(e,t){if(!e.producerIdentity||!e.projectIdentity||!e.generationIdentity)throw new Error("TypeScript fragment generation identities must be non-empty");let n=[...t].sort((r,i)=>r.relativePath.localeCompare(i.relativePath));if(new Set(n.map(r=>r.relativePath)).size!==n.length)throw new Error("TypeScript fragment generation contains duplicate document paths");return{version:va,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:n}}function Fb(e,t){let n=Ra(e),r=Gu(n,t.generationIdentity);if(Uu(r)){let i=Lb(Ca(r,"utf8"));if(vb(i)!==vb(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}he(r,t,{spacing:2,trailingNewline:!0})}function vb(e){return Zn(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function Lb(e){let t=JSON.parse(e);if(t.version!==va||typeof t.producerIdentity!="string"||typeof t.projectIdentity!="string"||typeof t.generationIdentity!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.documents))throw new Error("invalid TypeScript fragment generation manifest");let n=new Set;for(let r of t.documents){if(!r||typeof r.relativePath!="string"||typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash)||typeof r.byteLength!="number"||!Number.isInteger(r.byteLength)||r.byteLength<0||typeof r.documentIdentity!="string"||!r.documentIdentity)throw new Error("invalid TypeScript fragment record");if(Qn(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function Gu(e,t){return Br(e.generationDir,EM(t))}function EM(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${Zn(e)}.json`}function Nb(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function Ab(e,t){if(!e||typeof e!="object")throw new Error("TypeScript SCIP shard has no producer metadata");let n=e,r=n.toolInfo??n.tool_info;if(!r||typeof r!="object")throw new Error("TypeScript SCIP shard has no producer tool identity");let i=r;if(i.name!=="scip-typescript"||i.version!==t)throw new Error("TypeScript SCIP shard producer identity changed")}function Mb(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function Qn(e){if(!e||e.startsWith("/")||e.startsWith("\\")||e.includes("\\"))throw new Error(`invalid TypeScript SCIP document path: ${e}`);let t=e.split("/");if(t.includes("")||t.includes(".")||t.includes(".."))throw new Error(`invalid TypeScript SCIP document path: ${e}`);return e}function Zn(e){return CM("sha256").update(e).digest("hex")}import{createHash as kM}from"crypto";import{existsSync as Yi,mkdirSync as PM,readFileSync as Qi,readdirSync as zu,renameSync as TM,rmSync as Ob,writeFileSync as _M}from"fs";import{join as St}from"path";var Ia=1,Nte=64*1024*1024,Zi="typescript-scip-overlays";function Ate(e){let t=$b(e.cacheDir,e.previousGenerationIdentity);if(!t&&!e.baseShardCurrent)throw new Error("deferred TypeScript SCIP base has no matching overlay generation");if(t&&(t.producerIdentity!==e.producerIdentity||t.projectIdentity!==e.projectIdentity))throw new Error("TypeScript overlay producer or project identity changed");let n=new Map((t?.overlays??[]).map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let s=Ku(o.relativePath);if(r.has(s))throw new Error(`duplicate TypeScript overlay: ${s}`);r.add(s),n.set(s,FM(e.cacheDir,o))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:Ia,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:t?.baseGenerationIdentity??e.previousGenerationIdentity,generationIdentity:e.nextGenerationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),overlays:[...n.values()].sort((o,s)=>o.relativePath.localeCompare(s.relativePath))};return LM(e.cacheDir,i),i}function Mte(e){let t=$b(e.cacheDir,e.generationIdentity);if(!t)throw new Error("TypeScript overlay generation is unavailable");let n=t.overlays.map(r=>{if(r.blobHash===null)return{relativePath:r.relativePath,bytes:null,occurrences:0,symbols:0,referenceFragments:[]};let i=Qi(St(eo(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`));if(i.byteLength!==r.byteLength||Xi(i)!==r.blobHash)throw new Error(`TypeScript overlay blob is corrupt: ${r.relativePath}`);return{relativePath:r.relativePath,bytes:i,occurrences:0,symbols:0,referenceFragments:[]}});return kb({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function Ote(e,t){let n=eo(e),r=St(n,"generations");if(!Yi(r))return;let i=new Set(t.map(qu)),o=new Set;for(let a of zu(r).filter(c=>i.has(c))){let c=Vu(Qi(St(r,a),"utf8"));for(let l of c.overlays)l.blobHash&&o.add(`${l.blobHash}.scipdoc`)}for(let a of zu(r))i.has(a)||Ob(St(r,a),{force:!0});let s=St(n,"blobs");if(Yi(s))for(let a of zu(s))o.has(a)||Ob(St(s,a),{force:!0})}function $b(e,t){let n=St(eo(e),"generations",qu(t));if(!Yi(n))return null;let r=Vu(Qi(n,"utf8"));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function FM(e,t){let n=Ku(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=Xi(r),o=St(eo(e),"blobs");PM(o,{recursive:!0});let s=St(o,`${i}.scipdoc`);if(Yi(s)){let a=Qi(s);if(a.byteLength!==r.byteLength||Xi(a)!==i)throw new Error(`existing TypeScript overlay blob is corrupt: ${n}`)}else{let a=`${s}.${process.pid}.${Date.now()}.tmp`;_M(a,r),TM(a,s)}return{relativePath:n,blobHash:i,byteLength:r.byteLength}}function LM(e,t){let n=St(eo(e),"generations",qu(t.generationIdentity));if(Yi(n)){let r=Vu(Qi(n,"utf8"));if(jb(r)!==jb(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}he(n,t,{spacing:2,trailingNewline:!0})}function Vu(e){let t=JSON.parse(e);if(t.version!==Ia||typeof t.producerIdentity!="string"||!t.producerIdentity||typeof t.projectIdentity!="string"||!t.projectIdentity||typeof t.baseGenerationIdentity!="string"||!t.baseGenerationIdentity||typeof t.generationIdentity!="string"||!t.generationIdentity||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.overlays))throw new Error("invalid TypeScript overlay manifest");let n=new Set;for(let r of t.overlays){if(!r||typeof r.relativePath!="string"||r.blobHash!==null&&(typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash))||!Number.isInteger(r.byteLength)||r.byteLength<0||r.blobHash===null&&r.byteLength!==0)throw new Error("invalid TypeScript overlay record");if(Ku(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function eo(e){return St(e,Zi)}function qu(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${Xi(e)}.json`}function jb(e){return Xi(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function Ku(e){if(!e||e.startsWith("/")||e.includes("\\")||e.split("/").some(t=>!t||t==="."))throw new Error(`invalid TypeScript overlay path: ${e}`);if(e.split("/").includes(".."))throw new Error(`invalid TypeScript overlay path: ${e}`);return e}function Xi(e){return kM("sha256").update(e).digest("hex")}var to=1,Yu="language-indexes",Bb=["index.db","index.scip","meta.json"],Hb=[Yu,Ji,Zi];function wa(e){let t=[];for(let n of Bb)$M(e,n),t.push(n);for(let n of Hb)Ub(e,n,t);return{version:to,files:t.sort()}}function Da(e){if(!e||e.includes("\0")||e.startsWith("/")||e.includes("\\"))throw new Error(`invalid index artifact path: ${e||"<empty>"}`);let t=e.split("/");if(t.some(r=>!r||r==="."||r===".."))throw new Error(`invalid index artifact path: ${e}`);let n=t[0];if(!Bb.includes(e)&&!Hb.includes(n))throw new Error(`index artifact path is not shareable: ${e}`);return e}function Pt(e,t){let n=Da(t),r=Ju(e),i=Ju(r,...n.split("/"));if(i!==r&&!i.startsWith(`${r}${jM}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function Ub(e,t,n){let r=MM(e,t),i;try{i=AM(r,{withFileTypes:!0,encoding:"utf8"})}catch{return}for(let o of i){let s=`${t}/${o.name}`;if(o.isSymbolicLink())throw new Error(`index artifact cannot be a symlink: ${s}`);o.isDirectory()?Ub(e,s,n):o.isFile()&&n.push(Da(s))}}function $M(e,t){let n=Pt(e,t),r;try{r=NM(n)}catch{throw new Error(`required index artifact is missing: ${t}`)}if(!r.isFile()||r.isSymbolicLink())throw new Error(`required index artifact is not a regular file: ${t}`);if(OM(Ju(e),n).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{readFileSync as Qu,writeFileSync as Zu}from"fs";import{create as no}from"@bufbuild/protobuf";import{deserializeSCIP as ed,serializeSCIP as td,DocumentSchema as qM,IndexSchema as Gb,MetadataSchema as KM,SymbolInformationSchema as JM}from"@c4312/scip";import{readFileSync as BM,writeFileSync as HM}from"fs";import{create as Wb}from"@bufbuild/protobuf";import{deserializeSCIP as UM,DocumentSchema as WM,IndexSchema as GM,serializeSCIP as zM,SymbolRole as VM}from"@c4312/scip";function qte(e){let t;try{t=UM(BM(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=Xu(t);return n.removedDefinitionOccurrences>0&&HM(e,Buffer.from(zM(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function Xu(e){let t=new Set;for(let o of e.documents)for(let s of o.symbols)s.symbol&&t.add(s.symbol);for(let o of e.externalSymbols)o.symbol&&t.add(o.symbol);let n=0,r=0,i=[];for(let o of e.documents){let s=o.occurrences.filter(a=>(a.symbolRoles&VM.Definition)===0||t.has(a.symbol)?!0:(n+=1,!1));if(s.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(Wb(WM,{language:o.language,relativePath:o.relativePath,occurrences:s,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:Wb(GM,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function zb(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=XM(e),n=QM(e.flatMap(i=>i.documents??[])),r=qb(e.flatMap(i=>i.externalSymbols??[]));return no(Gb,{metadata:t,documents:n,externalSymbols:r})}function Zte(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>ed(Qu(i))),r=zb(n);return Zu(t,Buffer.from(td(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function ene(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>ed(Qu(i))),r=Xu(zb(n));return Zu(t,Buffer.from(td(r.index))),{documentCount:r.index.documents.length,externalSymbolCount:r.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:r.removedDefinitionOccurrences,touchedDocuments:r.touchedDocuments}}function YM(e,t,n){let r=e.metadata;if(!r)throw new Error("Cannot rebase a SCIP index without metadata");if(r.projectRoot!==t)throw new Error(`Cannot rebase SCIP project root: expected ${t}, got ${r.projectRoot}`);return no(Gb,{metadata:no(KM,{...r,projectRoot:n}),documents:e.documents,externalSymbols:e.externalSymbols})}function Vb(e,t,n){let r=ed(Qu(e)),i=YM(r,t,n);Zu(e,Buffer.from(td(i)))}function XM(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let r of e.slice(1)){let i=r.metadata?.projectRoot;if(n&&i&&i!==n)throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${i}`)}return t}function QM(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);if(!r){t.set(n.relativePath,n);continue}t.set(n.relativePath,no(qM,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:ZM([...r.occurrences,...n.occurrences]),symbols:qb([...r.symbols,...n.symbols]),text:t0(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function ZM(e){let t=new Set,n=[];for(let r of e){let i=JSON.stringify(r);t.has(i)||(t.add(i),n.push(r))}return n}function qb(e){let t=new Map;for(let n of e){let r=t.get(n.symbol);if(!r){t.set(n.symbol,n);continue}t.set(n.symbol,no(JM,{symbol:r.symbol,documentation:n0([...r.documentation,...n.documentation]),relationships:e0([...r.relationships,...n.relationships]),kind:r.kind||n.kind,displayName:r.displayName||n.displayName,enclosingSymbol:r.enclosingSymbol||n.enclosingSymbol,signatureDocumentation:r.signatureDocumentation??n.signatureDocumentation}))}return[...t.values()]}function e0(e){let t=new Set,n=[];for(let r of e){let i=[r.symbol,r.isReference?"1":"0",r.isImplementation?"1":"0",r.isTypeDefinition?"1":"0",r.isDefinition?"1":"0"].join("|");t.has(i)||(t.add(i),n.push(r))}return n}function t0(e,t){return e?t?e.length>=t.length?e:t:e:t}function n0(e){return[...new Set(e)]}var ad=1,Yb="SCIP_QUERY_SHARED_CACHE",rd=JSON.stringify({cliVersion:Xn,artifactCatalogVersion:to,sqliteGenerationStoreVersion:$r,typescriptFragmentStoreVersion:va,typescriptOverlayStoreVersion:Ia}),oS="manifest.json",sS="shared-cache.json",cd=[Yu,Ji,Zi];function Ea(e,t){if(!e.clean||!e.treeOid)return;let n=oo(JSON.stringify({version:ad,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:t,producerIdentity:rd}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:rd,generationId:n,repositoryCacheDir:zi(e.repositoryId)}}function aS(e,t,n){if(process.env[Yb]==="0")return`${Yb}=0`;if(!Mu(n))return"explicit cache or database override";if(Ct(t)!==Ct(A(pa(e),"index.db")))return"index database is outside the managed worktree cache"}function cS(e,t,n){if(!Mu(t))return;let r=n??fr(e);return r?A(zi(r.repositoryId),"evidence.db"):void 0}function tr(e,t=!0){let n=dd(e),r;try{r=u0(tt(A(n,oS),"utf8"))}catch{return null}if(r.generationId!==e.generationId||r.repositoryId!==e.repositoryId||r.treeOid!==e.treeOid||r.producerIdentity!==e.producerIdentity||JSON.stringify(r.fingerprint)!==JSON.stringify(e.fingerprint))return null;if(!t)return r;try{for(let i of r.artifacts){let o=Pt(n,i.path),s=a0(o);if(!s.isFile()||s.size!==i.size||oo(tt(o))!==i.sha256)return null}}catch{return null}return r}function lS(e){let t=tr(e.snapshot);if(t)return t;if(!Hr(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let n=Xb(e.sourceCacheDir);if(!n)throw new Error("source index artifacts are incomplete");let r=wa(e.sourceCacheDir),i=A(e.snapshot.repositoryCacheDir,"generations");Jt(i,{recursive:!0});let o=eS(A(i,`.tmp-${process.pid}-`));try{let s=[];for(let d of r.files){let f=Pt(e.sourceCacheDir,d),m=Pt(o,d);io(f,m);let p=tt(m);s.push({path:d,size:p.byteLength,sha256:oo(p)})}let a=iS(tt(A(o,"index.scip"))).metadata?.projectRoot;if(!a)throw new Error("shared SCIP generation has no project root metadata");let c=fd(e.sourceProjectRoot);if(a!==c)throw new Error("shared SCIP generation root does not match its source worktree");if(Xb(e.sourceCacheDir)!==n||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let l={version:ad,artifactCatalogVersion:to,generationId:e.snapshot.generationId,repositoryId:e.snapshot.repositoryId,treeOid:e.snapshot.treeOid,fingerprint:e.snapshot.fingerprint,producerIdentity:e.snapshot.producerIdentity,sourceProjectRoot:e.sourceProjectRoot,scipProjectRoot:a,createdAt:(e.now??(()=>new Date))().toISOString(),artifacts:s.sort((d,f)=>d.path.localeCompare(f.path))};he(A(o,oS),l,{spacing:2,trailingNewline:!0});let u=dd(e.snapshot);try{if(Dn(u)&&!tr(e.snapshot)){let d=`${u}.corrupt-${process.pid}-${Date.now()}`;er(u,d),wn(d,{recursive:!0,force:!0})}er(o,u)}catch(d){let f=tr(e.snapshot);if(f)return f;throw d}return l}finally{wn(o,{recursive:!0,force:!0})}}function id(e){let t=dd(e.snapshot);Jt(e.targetCacheDir,{recursive:!0});let n=Bu(A(e.targetCacheDir,"cache-lifecycle.lock"),{waitMs:3e4});if(!n)throw new Error("timed out waiting for another cache hydration");let r,i,o=!1;try{r=eS(A(e.targetCacheDir,".shared-hydrate-")),y0(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let l=Pt(t,c.path),u=Pt(r,c.path);io(l,u);let d=tt(u);if(d.byteLength!==c.size||oo(d)!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let s=fd(e.targetProjectRoot);if(s!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&Vb(Pt(r,c.path),e.manifest.scipProjectRoot,s);if(!Hr(r,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=p0(e.targetCacheDir,r),o=!0,g0(r,e.targetCacheDir,i),ub({tempOutputScip:A(r,"index.scip"),tempOutputDb:A(r,"index.db"),tempMetaPath:A(r,"meta.json"),outputScip:A(e.targetCacheDir,"index.scip"),outputDb:A(e.targetCacheDir,"index.db"),metaPath:A(e.targetCacheDir,"meta.json"),now:e.now});let a=Ki(A(e.targetCacheDir,"index.db"),A(e.targetCacheDir,"meta.json"));if(a.state==="invalid"||a.state==="drifted")throw new Error(`hydrated SQLite generation failed validation: ${a.reason}`);od(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(s){throw o&&i&&h0(e.targetCacheDir,i),s}finally{r&&wn(r,{recursive:!0,force:!0}),n.release()}}function uS(e,t,n,r){let i=aS(e,n.dbPath,t);if(i)return{kind:"bypassed",reason:i};try{let o=r??fr(e);if(!o)return{kind:"missed",reason:"Git worktree identity is unavailable"};if(!o.clean)return ka(o,n.cacheDir,"missed",void 0,"worktree has uncommitted changes"),{kind:"missed",reason:"worktree has uncommitted changes"};let s=t.languages??Vi(e),a=ki(e,s,fS(t)),c=Ea(o,a);if(!c)return{kind:"missed",reason:"clean committed snapshot is unavailable"};let l=tr(c);if(l)return id({snapshot:c,manifest:l,targetCacheDir:n.cacheDir,targetProjectRoot:e}),{kind:"attached",generationId:c.generationId};let u=d0(c,e);return u?(l=u.manifest,id({snapshot:c,manifest:l,targetCacheDir:n.cacheDir,targetProjectRoot:e,action:"peer-imported"}),{kind:"peer-imported",generationId:c.generationId,sourceProjectRoot:u.sourceProjectRoot}):(ka(o,n.cacheDir,"missed",void 0,"no exact shared or peer generation exists"),{kind:"missed",reason:"no exact shared or peer generation exists"})}catch(o){return{kind:"failed",reason:o instanceof Error?o.message:String(o)}}}function ld(e,t,n,r){let i=aS(e,n.dbPath,t);if(i)return{kind:"bypassed",reason:i};try{let o=r??fr(e);if(!o)return{kind:"missed",reason:"Git worktree identity is unavailable"};if(!o.clean)return ka(o,n.cacheDir,"missed",void 0,"worktree is not a clean committed snapshot"),{kind:"missed",reason:"worktree is not a clean committed snapshot"};let s=t.languages??Vi(e),a=ki(e,s,fS(t)),c=Ea(o,a);if(!c)return ka(o,n.cacheDir,"missed",void 0,"worktree is not a clean committed snapshot"),{kind:"missed",reason:"worktree is not a clean committed snapshot"};let l=tr(c);if(l)return Hr(n.cacheDir,e,a)?(od(c,n.cacheDir,"local-fresh"),{kind:"local-fresh"}):(id({snapshot:c,manifest:l,targetCacheDir:n.cacheDir,targetProjectRoot:e}),{kind:"attached",generationId:c.generationId});let u=Pa(n.cacheDir);return u?.status!=="complete"||JSON.stringify(u.fingerprint)!==JSON.stringify(a)||JSON.stringify([...u.indexedLanguages??[]].sort())!==JSON.stringify([...s].sort())?{kind:"missed",reason:"local metadata does not match the clean worktree snapshot"}:Hr(n.cacheDir,e,a)?(lS({snapshot:c,sourceCacheDir:n.cacheDir,sourceProjectRoot:e,sourceStillValid:()=>{let d=fr(e);return(d?Ea(d,a):void 0)?.generationId===c.generationId}}),od(c,n.cacheDir,"built"),{kind:"built",generationId:c.generationId}):{kind:"missed",reason:"local index artifacts are incomplete or incompatible"}}catch(o){return{kind:"failed",reason:o instanceof Error?o.message:String(o)}}}async function vne(e,t={}){let n=t.timeoutMs??3e4,r=t.pollMs??100,i=t.now??Date.now,o=i()+n,s=A(e.repositoryCacheDir,"locks"),a=A(s,`${e.generationId}.lock`);for(Jt(s,{recursive:!0});i()<=o;){if(tr(e))return{kind:"generation-ready"};let c=sd();try{let l=tS(a,"wx");try{nS(l,`${JSON.stringify({version:1,pid:process.pid,token:c,generationId:e.generationId,startedAt:new Date(i()).toISOString()})}
375
- `)}finally{Zb(l)}return{kind:"owner",release:()=>{try{let u=JSON.parse(tt(a,"utf8"));u.pid===process.pid&&u.token===c&&nd(a)}catch{}}}}catch(l){if(l.code!=="EEXIST")return{kind:"timeout"};let u=mS(a);if(u&&(u.pid===void 0||!Ae(u.pid))){m0(a,u);continue}await c0(r)}}return tr(e)?{kind:"generation-ready"}:{kind:"timeout"}}function od(e,t,n,r=void 0){let i={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,baseGenerationId:e.generationId,activeGenerationId:e.generationId,lastAction:n,lastSeenAt:(r??(()=>new Date))().toISOString()},o={...i,ownershipChecksum:ud(i)};return pS(e.repositoryCacheDir,o,!0),o}function ka(e,t,n,r=void 0,i=void 0){let o={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,lastAction:n,...i?{lastReason:i}:{},lastSeenAt:(r??(()=>new Date))().toISOString()},s={...o,ownershipChecksum:ud(o)};return pS(zi(e.repositoryId),s,!1),s}function ud(e){return oo(JSON.stringify({version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:Ct(e.projectRoot),localCacheDir:Ct(e.localCacheDir)}))}function dS(e,t,n=void 0,r){try{let i=JSON.parse(tt(A(t,sS),"utf8"));if(i.version!==1||typeof i.repositoryId!="string"||!/^[a-f0-9]{24}$/.test(i.repositoryId)||typeof i.worktreeId!="string"||!/^[a-f0-9]{24}$/.test(i.worktreeId))return null;let o=A(zi(i.repositoryId),"worktrees",`${i.worktreeId}.json`),s=JSON.parse(tt(o,"utf8")),a=r??fr(e);if(!a?.clean||!a.treeOid||s.version!==1||s.repositoryId!==i.repositoryId||s.worktreeId!==i.worktreeId||s.repositoryId!==a.repositoryId||s.worktreeId!==a.worktreeId||Ct(s.projectRoot)!==Ct(a.projectRoot)||s.treeOid!==a.treeOid||Ct(s.localCacheDir)!==Ct(t)||s.ownershipChecksum!==ud(s))return null;let c=Pa(t);if(!b0(c?.fingerprint))return null;let l=Ea(a,c.fingerprint);if(!l||s.baseGenerationId!==l.generationId||s.activeGenerationId!==l.generationId||!Hr(t,e,l.fingerprint,!0,!1))return null;let u=(n??(()=>new Date))();if(Number.isFinite(Date.parse(s.lastSeenAt))&&u.getTime()-Date.parse(s.lastSeenAt)<6e4)return s;let d=$u(l.repositoryCacheDir,{waitMs:5e3});if(!d)return null;try{s.lastSeenAt=u.toISOString(),he(o,s,{spacing:2,trailingNewline:!0})}finally{d.release()}return s}catch{return null}}function u0(e){let t=JSON.parse(e);if(t.version!==ad||t.artifactCatalogVersion!==to||typeof t.generationId!="string"||!/^[a-f0-9]{64}$/.test(t.generationId)||typeof t.repositoryId!="string"||!/^[a-f0-9]{24}$/.test(t.repositoryId)||typeof t.treeOid!="string"||!t.treeOid||typeof t.producerIdentity!="string"||t.producerIdentity!==rd||typeof t.sourceProjectRoot!="string"||typeof t.scipProjectRoot!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!t.fingerprint||!Array.isArray(t.artifacts))throw new Error("invalid shared generation manifest");let n=new Set;for(let r of t.artifacts){if(!r||typeof r.path!="string"||typeof r.size!="number"||r.size<0||typeof r.sha256!="string"||!/^[a-f0-9]{64}$/.test(r.sha256))throw new Error("invalid shared generation artifact");if(Da(r.path),n.has(r.path))throw new Error(`duplicate shared generation artifact: ${r.path}`);n.add(r.path)}for(let r of["index.db","index.scip","meta.json"])if(!n.has(r))throw new Error(`shared generation is missing ${r}`);return t}function io(e,t){Jt(rS(t),{recursive:!0});try{Kb(e,t,r0.COPYFILE_FICLONE)}catch{Kb(e,t)}}function d0(e,t){for(let n of Pm(t)){if(Ct(n.path)===Ct(t))continue;let r=pa(n.path),i=Pa(r);if(!(i?.status!=="complete"||JSON.stringify(i.fingerprint)!==JSON.stringify(e.fingerprint)||JSON.stringify([...i.indexedLanguages??[]].sort())!==JSON.stringify([...e.fingerprint.languages].sort()))&&Hr(r,n.path,e.fingerprint))try{return{manifest:lS({snapshot:e,sourceCacheDir:r,sourceProjectRoot:n.path}),sourceProjectRoot:n.path}}catch{continue}}return null}function f0(e,t,n){Jt(e,{recursive:!0}),he(A(e,sS),{version:1,repositoryId:t,worktreeId:n},{spacing:2,trailingNewline:!0})}function Xb(e){try{let t=wa(e),n=Qb("sha256");for(let r of t.files){let i=tt(Pt(e,r));n.update(r).update("\0").update(String(i.byteLength)).update("\0").update(i).update("\0")}return n.digest("hex")}catch{return null}}function Pa(e){try{return JSON.parse(tt(A(e,"meta.json"),"utf8"))}catch{return}}function fS(e){return{pnpmWorkspaces:e.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:e.indexer?.typescript?.projectMode,typescriptProjects:e.indexer?.typescript?.projects,clojureConfigPath:e.indexer?.clojure?.configPath}}function dd(e){return A(e.repositoryCacheDir,"generations",e.generationId)}function mS(e){try{let t=tt(e,"utf8"),n=JSON.parse(t),r=typeof n.pid=="number"&&Number.isSafeInteger(n.pid)&&n.pid>0?n.pid:void 0;return{raw:t,...r===void 0?{}:{pid:r}}}catch{return null}}function m0(e,t){let n=`${e}.reclaim`,r=sd(),i;try{i=tS(n,"wx")}catch{return!1}try{nS(i,`${JSON.stringify({version:1,pid:process.pid,token:r,startedAt:new Date().toISOString()})}
376
- `)}finally{Zb(i)}try{let o=mS(e);return!o||o.raw!==t.raw||o.pid!==void 0&&Ae(o.pid)?!1:(nd(e),!0)}catch{return!1}finally{try{let o=JSON.parse(tt(n,"utf8"));o.pid===process.pid&&o.token===r&&nd(n)}catch{}}}function pS(e,t,n){let r=$u(e,{waitMs:5e3});if(!r)throw new Error("repository cache cleanup is busy");try{if(n){let o=t.activeGenerationId;if(!o||!Dn(A(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=A(e,"worktrees");Jt(i,{recursive:!0}),he(A(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),f0(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{r.release()}}function p0(e,t){let n=A(t,".rollback"),r=new Map,i=new Map;Jt(n,{recursive:!0});for(let a of["index.scip","index.db","meta.json"]){let c=A(e,a),l=Dn(c);r.set(a,l),l&&io(c,A(n,"stable",a))}for(let a of cd){let c=A(e,a),l=Dn(c);if(l){let u=i0(c);if(!u.isDirectory()||u.isSymbolicLink())throw new Error(`managed artifact path is not a directory: ${a}`)}i.set(a,l)}let o=A(e,ya),s=Dn(o);return s&&gS(o,A(n,"sqlite-generations")),{root:n,stableFiles:r,managedDirectories:i,generationStoreExisted:s}}function g0(e,t,n){for(let r of cd){let i=A(t,r);if(n.managedDirectories.get(r)){let s=A(n.root,"managed",r);Jt(rS(s),{recursive:!0}),er(i,s)}let o=A(e,r);Dn(o)&&er(o,i)}}function h0(e,t){for(let i of cd){let o=A(e,i),s=A(t.root,"managed",i);t.managedDirectories.get(i)?Dn(s)&&(wn(o,{recursive:!0,force:!0}),er(s,o)):wn(o,{recursive:!0,force:!0})}for(let[i,o]of t.stableFiles){let s=A(e,i);if(!o){wn(s,{force:!0});continue}let a=`${s}.shared-restore-${sd()}`;io(A(t.root,"stable",i),a),wn(s,{force:!0}),er(a,s)}let n=A(e,ya);wn(n,{recursive:!0,force:!0});let r=A(t.root,"sqlite-generations");t.generationStoreExisted&&Dn(r)&&er(r,n)}function gS(e,t){Jt(t,{recursive:!0});for(let n of o0(e,{withFileTypes:!0})){let r=A(e,n.name),i=A(t,n.name);if(n.isSymbolicLink())throw new Error(`managed cache backup cannot contain a symlink: ${r}`);n.isDirectory()?gS(r,i):n.isFile()&&io(r,i)}}function y0(e,t){if(e.generationId!==t.generationId||e.repositoryId!==t.repositoryId||e.treeOid!==t.treeOid||e.producerIdentity!==t.producerIdentity||JSON.stringify(e.fingerprint)!==JSON.stringify(t.fingerprint))throw new Error("shared generation manifest does not match the requested snapshot")}function Hr(e,t,n,r=!0,i=!0){try{let o=Pa(e);if(o?.status!=="complete"||JSON.stringify(o.fingerprint)!==JSON.stringify(n)||JSON.stringify([...o.indexedLanguages??[]].sort())!==JSON.stringify([...n.languages].sort()))return ro("source validation rejected metadata"),!1;let s=wa(e),a=Ki(A(e,"index.db"),A(e,"meta.json"));if(r?a.state!=="current":a.state==="invalid"||a.state==="drifted")return ro(`source validation rejected SQLite generation state ${a.state}`),!1;let c=new l0(A(e,"index.db"),{readonly:!0,fileMustExist:!0});try{if(i){if(c.pragma("quick_check(1)",{simple:!0})!=="ok")return!1}else c.pragma("schema_version",{simple:!0})}finally{c.close()}let l=fd(t),d=(i?s.files.filter(f=>f.endsWith(".scip")):["index.scip"]).every(f=>{let m=iS(tt(Pt(e,f))).metadata?.projectRoot;return m!==l&&ro(`source validation rejected SCIP root for ${f}: ${String(m)}`),m===l});return d||ro("source validation rejected SCIP project roots"),d}catch(o){return ro(`source validation failed: ${o instanceof Error?o.message:String(o)}`),!1}}function ro(e){process.env.SCIP_QUERY_DEBUG&&console.error(`shared-cache: ${e}`)}function fd(e){try{return Jb(s0(e)).href}catch{return Jb(Ct(e)).href}}function b0(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===2&&Array.isArray(t.languages)&&typeof t.pnpmWorkspaces=="boolean"&&(t.typescriptProjectMode==="single"||t.typescriptProjectMode==="workspace")&&Array.isArray(t.typescriptProjects)&&Array.isArray(t.files)&&t.files.every(n=>n!==null&&typeof n=="object"&&typeof n.path=="string"&&typeof n.size=="number"&&typeof n.hash=="string")}function oo(e){return Qb("sha256").update(e).digest("hex")}function hS(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var md;function Fne(e){md=e}function yS(e=hS(),t=void 0){if(t===void 0&&md?.projectRoot===e)return md;let n=Xy(e),r=Zy(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(pd(r.dbPath))return{projectRoot:e,config:n,paths:r,dbPath:r.dbPath,dbPathSource:"configured",gitContext:t};let o=C0(e,"index.db");return{projectRoot:e,config:n,paths:r,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:I0(o,r.dbPath),gitContext:t}}function Lne(e){return yS(e).dbPath}function Nne(e,t,n,r={}){return pd(n.dbPath)&&dS(e,n.cacheDir,void 0,r.gitContext)?{kind:"local-fresh"}:r.gitContext?.clean===!1&&r.watcherGeneration!==void 0&&ta(n.dbPath)===r.watcherGeneration?ld(e,t,n,r.gitContext):mb(e,t,n).state==="fresh"?ld(e,t,n,r.gitContext):uS(e,t,n,r.gitContext)}function Ane(e){return!e.startsWith("__")&&!x0.has(e)}var x0=new Set(["bench","config-validate","hook-context","hook-stop","init","setup","setup-agent","setup-ci","setup-hooks","uninstall","work-audit"]);function v0(){try{return R0(hS(),{warnOnRootFallback:!0})}catch(e){console.error(`error: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}function R0(e,t={}){let{config:n,paths:r,dbPath:i,dbPathSource:o,rootFallbackWarning:s,gitContext:a}=yS(e);if(!pd(i))throw new Error("No index.db found. Run: scip-query reindex");t.warnOnRootFallback&&o==="root-fallback"&&s&&console.error(s);let c={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??r.indexPath,projectRoot:e,sharedEvidenceDbPath:cS(e,n,a),entryRoots:n.entryRoots,semantic:n.semantic,suppressions:n.suppressions,declaredCouplings:n.declaredCouplings,locality:n.locality,coverageContracts:n.coverageContracts,docs:n.docs},l=Hy(e);return new da(c,l)}function I0(e,t){let n="unknown time";try{n=S0(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 Yt(e){let t=v0();try{return e(t)}finally{t.close()}}function Mne(e,t){return t.concat([e])}function bS(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 One(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":""}`;default:return w0(e)}}function w0(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}function SS(e){return e+1}function D0(e,t){return`${SS(e)}-${SS(t)}`}function $ne(e,t,n){return`${e}:${D0(t,n)}`}function Bne(e,t=180){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var Tt={empty(e){console.log(e)},list(e,t){for(let n of e)console.log(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(o),r=o),console.log(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 ${n.title} \u2550\u2550\u2550`),n.explanation!==void 0&&console.log(n.explanation);for(let r of n.rows)console.log(r)}},table(e,t,n){console.log(` ${e.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(i)}};import{availableParallelism as mY}from"os";import{fileURLToPath as Xf}from"url";import{existsSync as Ta,readFileSync as E0,readdirSync as xS}from"fs";import{join as so}from"path";var k0={files:new Set,pathPrefixes:[]},gd=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,P0=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,vS=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],T0=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),_0=4,F0=K("package-surface",{clearGroups:["whole-project"]});function L0(e){return F0.get(e,()=>N0(e.config.projectRoot))}function nr(e,t){let n=L0(e);return n.files.has(t)?!0:n.pathPrefixes.some(r=>t.startsWith(r))}function N0(e){let t=new Set,n=[];for(let{manifest:r,packageRoot:i}of A0(e))for(let o of M0(r))O0(e,i,o,t,n);return t.size===0&&n.length===0?k0:{files:t,pathPrefixes:n}}function A0(e){let t=[],n=IS(e,"");return n&&t.push({manifest:n,packageRoot:""}),RS(e,"",t,0),t}function RS(e,t,n,r){if(r>=_0)return;let i=so(e,t);if(Ta(i))for(let o of xS(i,{withFileTypes:!0})){if(!o.isDirectory()||T0.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=IS(e,s);a&&n.push({manifest:a,packageRoot:s}),RS(e,s,n,r+1)}}function IS(e,t){try{let n=E0(so(e,t,"package.json"),"utf-8"),r=JSON.parse(n);return r&&typeof r=="object"?r:null}catch{return null}}function M0(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 wS(e.exports,t),t}function wS(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))wS(n,t)}function O0(e,t,n,r,i){let o=n.replace(/\\/g,"/").replace(/^\.\//,"");if(o===""||o.startsWith(".."))return;let s=o.indexOf("*");if(s>=0){let c=o.slice(0,s);for(let l of CS(c))l!==""&&i.push(Xt(t,l));return}let a=o.replace(P0,"");for(let c of CS(a)){c===a&&c===o&&r.add(Xt(t,o));for(let l of vS)j0(e,r,t,c+l)}r.add(Xt(t,o))}function CS(e){let t=[e];return gd.test(e)&&(t.push(e.replace(gd,"src/")),t.push(e.replace(gd,""))),t}function j0(e,t,n,r){let i=Xt(n,r);if(t.add(i),!r.startsWith("src/")||Ta(so(e,i)))return;let o=vS.find(u=>r.endsWith(u));if(!o)return;let s=r.slice(0,-o.length);$0(e,t,n,s,o);let a=s.lastIndexOf("/");if(a<=4)return;let c=s.slice(0,a),l=s.slice(a+1);for(let u of DS(e,n,c,`${l}${o}`))t.add(u)}function $0(e,t,n,r,i){let o=Xt(n,`${r}/index${i}`);Ta(so(e,o))&&t.add(o)}function DS(e,t,n,r){let i=so(e,t,n);if(!Ta(i))return[];let o=[];for(let s of xS(i,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...DS(e,t,a,r)):s.isFile()&&s.name===r&&o.push(Xt(t,a))}return o}function Xt(e,t){return e?`${e}/${t}`:t}import{existsSync as _a,readFileSync as B0,readdirSync as H0}from"fs";import{dirname as U0,join as Fa}from"path";var W0={rootFiles:new Set,sourcePrefixes:[]},G0=new Set([".git",".scipquery","node_modules","target"]),z0=6,V0=K("rust-library-surface",{clearGroups:["whole-project"]});function ES(e,t,n){if(!n.endsWith(".rs")||!J0(q0(e),n))return!1;let r=X(e,n).find(i=>i.symbol===t);return r?Y0(Ce(e,n)[r.startLine]??""):!1}function q0(e){return V0.get(e,()=>K0(e.config.projectRoot))}function K0(e){let t=new Set,n=new Set;for(let r of X0(e)){let i=Fa(e,r,"Cargo.toml"),o=B0(i,"utf8"),s=Q0(o),a=Xt(r,"src/lib.rs"),c=s?Xt(r,s):!Z0(o)&&_a(Fa(e,a))?a:null;if(!c)continue;t.add(c);let l=U0(c).replaceAll("\\","/");n.add(l==="."?"":`${l}/`)}return t.size===0?W0:{rootFiles:t,sourcePrefixes:[...n].sort()}}function J0(e,t){return t.endsWith(".rs")?e.rootFiles.has(t)?!0:eO(t)?!1:e.sourcePrefixes.some(n=>t.startsWith(n)):!1}function Y0(e){return/^\s*pub\s+(?!\()/.test(e)}function X0(e){if(!_a(e))return[];let t=[];return kS(e,"",t,0),t}function kS(e,t,n,r){let i=Fa(e,t);if(_a(i)&&(_a(Fa(i,"Cargo.toml"))&&n.push(t),!(r>=z0)))for(let o of H0(i,{withFileTypes:!0})){if(!o.isDirectory()||G0.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name;kS(e,s,n,r+1)}}function Q0(e){let t=!1;for(let n of e.split(`
377
- `)){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 Z0(e){let t=!1;for(let n of e.split(`
378
- `)){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 eO(e){return/(?:^|\/)src\/main\.rs$/.test(e)||/(?:^|\/)src\/bin\//.test(e)||/(?:^|\/)(?:examples|tests|benches)\//.test(e)}function J(e){let t=ee(e);return yO(t)?"test":bO(t)?"worker":SO(t)?"entry":CO(t)?"barrel":"source"}function Ur(e){return J(e)==="barrel"}function TS(e){return tO.get(e,()=>{let n=N(e,{includeIgnored:!1}).filter(s=>{let a=J(s);return a==="entry"||a==="worker"});if(n.length===0)return new Set;let r=se(e),i=new Set,o=new Set;for(;n.length>0;){let s=n.shift();if(!i.has(s)){i.add(s),J(s)==="barrel"&&o.add(s);for(let a of r.get(s)??[])i.has(a)||n.push(a)}}return o})}var tO=K("live-barrels",{clearGroups:["whole-project"]});function hd(e,t){return TS(e).has(ee(t))}function _S(e){let t=TS(e);return N(e,{includeIgnored:!1}).filter(n=>Ur(n)&&!t.has(n)&&!nO(e,n))}function nO(e,t){let n=ee(t),r=dt(e).forFile(n,{facts:!0}).facts?.callables;return r&&r.length>0?!0:(e.get(`SELECT COUNT(*) AS n
379
- FROM defn_enclosing_ranges der
380
- JOIN documents d ON d.id = der.document_id
381
- WHERE d.relative_path = ?
382
- AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function De(e,t){let n=ee(t),r=J(t);return r==="entry"||r==="worker"||pO(n)||hd(e,n)}function ue(e,t,n){let r=ee(n);if(nr(e,r)||iO(e,t,r)||ES(e,t,r)||mO(t,r))return!0;let i=e.config.entryRoots;return i?!!(i.files?.some(o=>ee(o)===r)||i.pathPrefixes?.some(o=>r.startsWith(ee(o)))||i.qualifiedVars?.some(o=>xO(t,o))||i.symbolPatterns?.some(o=>{try{return new RegExp(o).test(t)}catch{return!1}})):!1}var rO=K("package-surface-reachability",{clearGroups:["whole-project"]});function iO(e,t,n){let r=oO(e).get(n);return r===void 0?!1:r===null||r.has(T(t))}function oO(e){return rO.get(e,()=>{let t=new Map,n=[];for(let r of N(e,{includeIgnored:!1}))nr(e,r)&&(t.set(r,null),n.push(r));for(;n.length>0;){let r=n.shift(),i=t.get(r);if(i!==void 0)for(let o of zn(e,r)){if(!o.sourcePath||e.isIgnored(o.sourcePath))continue;let s=sO(i,o);s!==void 0&&aO(t,o.sourcePath,s)&&n.push(o.sourcePath)}}return t})}function sO(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;let n=t.names.filter(r=>e.has(r));return n.length>0?new Set(n):void 0}function aO(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 FS=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),cO=new Set(["default","generateMetadata","generateStaticParams"]),lO=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),uO=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),dO=new Set(["load","actions","entries",...FS]),fO=new Set(["default"]);function mO(e,t){let n=T(e);return n===""?!1:LS(t)?FS.has(n):NS(t)?cO.has(n):AS(t)?lO.has(n):MS(t)?uO.has(n):OS(t)?dO.has(n):hO(t)?fO.has(n):!1}function pO(e){return LS(e)||NS(e)||AS(e)||gO(e)||MS(e)||OS(e)}function LS(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function NS(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function AS(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function gO(e){let t="(?:middleware|proxy|instrumentation)\\.(?:ts|js|mts|mjs)";return new RegExp(`^(?:src/)?${t}$`).test(e)||new RegExp(`(?:^|/)src/${t}$`).test(e)||new RegExp(`(?:^|/)(?:apps|services|packages)/[^/]+/(?:src/)?${t}$`).test(e)}function MS(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function OS(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function hO(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function yO(e){return!!(/\.(?:test|spec)\.[a-z0-9]+$/i.test(e)||/(?:^|\/)(?:_)?test_[^/]+$/i.test(e)||/(?:^|\/)spec_[^/]+$/i.test(e)||/(?:^|\/)[^/]+_test\.[a-z0-9]+$/i.test(e)||/(?:^|\/)[^/]+_tests\.rs$/i.test(e)||/(?:^|\/)tests\.rs$/i.test(e)||/(?:^|\/)[^/]+_spec\.[a-z0-9]+$/i.test(e)||/(?:^|\/)__tests__\//i.test(e)||/(?:^|\/)test\//i.test(e)||/(?:^|\/)tests\//i.test(e)||/(?:^|\/)__fixtures__\//i.test(e)||/(?:^|\/)__mocks__\//i.test(e)||/(?:^|\/)test-support\//i.test(e)||/(?:^|\/)test-utils\//i.test(e)||/(?:^|\/)testing\//i.test(e))}function bO(e){return/(?:^|\/)[^/]*worker\.(?:ts|tsx|js|mjs|cjs|rs|py|go)$/.test(e)}function SO(e){let t=e.split("/"),n=t[t.length-1]??e;return n==="cli.ts"||n==="cli.js"||n==="postinstall.ts"||n==="postinstall.js"||n==="main.ts"||n==="main.js"||n==="main.rs"||n==="main.go"||n==="main.py"||n==="build.rs"||n==="lib.rs"||/\bsrc\/bin\/[^/]+\.rs$/.test(e)||/(?:^|\/)examples\/[^/]+\.rs$/.test(e)||/(?:^|\/)tests\/[^/]+\.rs$/.test(e)||/(?:^|\/)benches\/[^/]+\.rs$/.test(e)?!0:n==="index.ts"||n==="index.js"?/(?:^|\/)(?:apps|services)\/[^/]+\/src\/index\.(?:ts|js)$/.test(e)?!0:t.length<=2:!1}function CO(e){return e==="index.ts"||e==="index.js"||e.endsWith("/index.ts")||e.endsWith("/index.js")||e.endsWith("/mod.rs")||e.endsWith("/__init__.py")}function xO(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(PS(r)+"/")&&e.includes(PS(i)+".")}function PS(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}import{SymbolInformation_Kind as G}from"@c4312/scip";var La=new Map(Object.entries(G).filter(([e,t])=>Number.isInteger(Number(e))&&typeof t=="string").map(([e,t])=>[Number(e),t])),jS=new Map([...La.entries()].map(([e,t])=>[t.toLowerCase(),e]));function ao(e){return La.get(e)??"Unknown"}function _t(){return[G.Function,G.Method,G.Macro,G.Constructor,G.Getter,G.Setter,G.StaticMethod,G.SingletonMethod,G.AbstractMethod,G.ProtocolMethod,G.TraitMethod]}function $S(){return[G.Class,G.Interface,G.Struct,G.Trait,G.Type,G.TypeAlias,G.Enum,G.Union,G.Protocol]}function ure(){return[G.Constant,G.Variable,G.Value,G.Field,G.Property,G.StaticDataMember,G.StaticField,G.StaticProperty,G.StaticVariable,G.EnumMember]}function mt(e,t,n={}){let r=Na(e,[t],{additive:n.additive,semantic:n.semantic}),i=n.callableOnly?(r.get(t.symbolId)??[]).filter(o=>ce(o.symbol)||o.source==="ast-callsite"):r.get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}function HS(e,t,n={}){return bd(e,[t],n).get(t.symbolId)??[]}function bd(e,t,n={}){let r=IO(e)?DO(e,t,{semantic:n.semantic!==!1}):wO(e);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 vO=K("caller-rows",{clearGroups:["whole-project"]}),RO=2e4;function IO(e){return(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>RO}function wO(e){return vO.get(e,()=>{let t=ve(e),n=Na(e,t),r=new Map;for(let s of t)r.set(s.symbol,s.symbolId);let i=new Map,o=new Map;for(let s of t){let a=n.get(s.symbolId);if(!(!a||a.length===0))for(let c of a){let l=r.get(c.symbol);if(l===void 0||l===s.symbolId)continue;let u=i.get(l);u||(u=[],i.set(l,u),o.set(l,new Set));let d=`${s.symbol}|${s.relativePath}`;o.get(l).has(d)||(o.get(l).add(d),u.push({symbol:s.symbol,file:s.relativePath,source:"caller-map-inversion"}))}}return i})}function DO(e,t,n){let r=n.semantic?t.flatMap(a=>{let c=EO(e,a);return c?[c]:[]}):[],i=new Map(r.map(a=>[a.symbolId,a])),o=_u(e,r),s=new Map;for(let a of t){let c=[],l=new Set,u=f=>{if(f.symbol===a.symbol)return;let m=`${f.symbol}|${f.file}`;l.has(m)||(l.add(m),c.push(f))};for(let f of Gi(e,a))f.file!==a.relativePath&&u({symbol:f.enclosingSymbol??f.file,file:f.file,source:"resolved-reference"});let d=i.get(a.symbolId);if(d)for(let f of o.get(d.symbolId)??[]){if(f.file===a.relativePath||e.isIgnored(f.file))continue;let m=It(X(e,f.file),f.line);u({symbol:m?.symbol??f.file,file:f.file,source:"semantic-reference"})}s.set(a.symbolId,c)}return s}function EO(e,t){let n=_t().join(", "),r=$S().join(", ");return e.get(`SELECT
383
- d.id AS documentId,
384
- gs.id AS symbolId,
385
- gs.symbol,
386
- d.relative_path AS relativePath,
387
- COALESCE(der.start_line, c.start_line) AS startLine,
388
- COALESCE(der.end_line, c.end_line) AS endLine,
389
- COALESCE(gs.display_name, '') AS leaf,
390
- NULL AS parentTypeName,
391
- CASE WHEN gs.kind IN (${n}) OR gs.symbol LIKE '%().' THEN 1 ELSE 0 END AS isFunctionLike,
392
- CASE WHEN gs.kind IN (${r}) THEN 1 ELSE 0 END AS isTypeLike,
393
- gs.kind AS kind,
394
- gs.documentation AS documentation,
395
- gs.enclosing_symbol AS enclosingSymbol
396
- FROM global_symbols gs
397
- LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
398
- LEFT JOIN chunks c ON c.document_id = der.document_id
399
- JOIN documents d ON d.id = COALESCE(der.document_id, c.document_id)
400
- WHERE gs.id = ?
401
- LIMIT 1`,t.symbolId)??null}function Na(e,t,n={}){if(t.length===0)return new Map;let r=n.additive??!1,i=[],o=[];for(let u of t)M(u.relativePath)&&fn(e,u.relativePath)!==null?i.push(u):o.push(u);let s=new Map,a=new Map,c=u=>{for(let[d,f]of u){let m=s.get(d);m||(m=[],s.set(d,m));let p=a.get(d);p||(p=new Set,a.set(d,p));for(let g of f){let h=`${g.symbol}|${g.chunkId}`;p.has(h)||(p.add(h),m.push(g))}}};i.length>0&&c(LO(e,i)),n.semantic!==!1&&c($O(US(e,t)));let l=r?t:o;return l.length>0&&c(OO(e,l)),s}function US(e,t){let n=H(),r=new Map,i=Cy(e,t),o=[],s=[],a=0,c=0,l=0,u=0,d=0,f=0,m=0;for(let{definition:x,callees:b}of i.hits)d+=1,b.length>0&&(f+=1,m+=b.length,r.set(x.symbolId,b));let p=kO(e,i.hits);if(p.entries.length>0&&D("semantic.callees.prefetch-cache-write",()=>Lc(e,p.entries),()=>({entries:p.entries.length,sourceMissing:p.sourceMissing,skippedUnsupportedLanguage:p.skippedUnsupportedLanguage})),D("semantic.callees.cache-scan",()=>{for(let[x,b]of sa(i.misses)){if(!we(x)){n&&(a+=b.length);continue}let y=P(e,x);if(!y){n&&(c+=b.length),s.push(...b);continue}let R=ae(e,x,y),v=GS(e,x);if(!v){s.push(...b);continue}let E=cm(e,x,R,v);for(let I of b){let k=E.get(I.symbol)??null;if(k!==null){let F=TO(k);if(F){n&&(l+=1),F.length>0&&r.set(I.symbolId,F);continue}n&&(u+=1)}o.push({def:I,contentHash:R,depsDigest:v})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:a,sourceMissing:c,cacheHits:l,parseFailures:u,misses:o.length,unkeyed:s.length,inMemoryHits:d,inMemoryRows:f,inMemoryCalleeCount:m,resultRows:r.size})),o.length===0&&s.length===0)return r;let g=[...s,...o.map(x=>x.def)],h=0,S=D("semantic.callees.compute-misses",()=>{let x=ca(e,g);return h=x.size,x},()=>({definitions:g.length,misses:o.length,unkeyed:s.length,rows:h}));for(let[x,b]of S)r.set(x,b);let C=o.filter(x=>Oe(e).capability("semantic-callees",x.def.relativePath).available).map(x=>({relativePath:x.def.relativePath,symbol:x.def.symbol,contentHash:x.contentHash,depsDigest:x.depsDigest,payload:JSON.stringify(S.get(x.def.symbolId)??[])}));return C.length>0?D("semantic.callees.cache-write",()=>Lc(e,C),()=>({entries:C.length})):D("semantic.callees.cache-write-skip",()=>{},()=>({reason:"provider-unavailable",misses:o.length})),r}function kO(e,t){let n=[],r=new Map,i=0,o=0;for(let{definition:s,callees:a}of t){if(!we(s.relativePath)){o+=1;continue}if(!r.has(s.relativePath)){let l=P(e,s.relativePath),u=l?GS(e,s.relativePath):null;r.set(s.relativePath,l&&u?{contentHash:ae(e,s.relativePath,l),depsDigest:u}:null)}let c=r.get(s.relativePath);if(!c){i+=1;continue}n.push({relativePath:s.relativePath,symbol:s.symbol,contentHash:c.contentHash,depsDigest:c.depsDigest,payload:JSON.stringify(a)})}return{entries:n,sourceMissing:i,skippedUnsupportedLanguage:o}}function WS(e,t){return US(e,t)}var PO="typescript-callees-v1";function GS(e,t){let n=we(t);if(n==="typescript")return xn(e,t,PO)?.key??null;let r=FO(e,t);return n==="rust"?ge(JSON.stringify({kind:"semantic-callees",language:n,engine:Kn(e.config.projectRoot),positionMapping:"nearby-leaf-v1",depsDigest:r})):r}function TO(e){try{return JSON.parse(e)}catch{return null}}var _O=j("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function FO(e,t){return _O.get(e,t,()=>{let r=[...se(e).get(t)??[]].sort().map(i=>`${i}:${ae(e,i,P(e,i))}`);return ge(r.join("|"))})}function LO(e,t){let n=new Map,r=NO(t,n),i=qt(e);for(let[o,s]of r){let a=fn(e,o);if(!a)continue;let c=jl(s);for(let l of a){let u=c.get(l.line);if(!u)continue;let d=AO(e,o,i,l);d&&d.symbol!==u.symbol&&n.get(u.symbolId).push({symbol:d.symbol,file:d.file,chunkId:l.line,source:"ast-callsite"})}}return n}function NO(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 AO(e,t,n,r){let i=Ps(t,n.get(r.calleeLeaf)??[]);if(i.length===0)return null;let o=MO(e,t,i,r.calleeQualifier);return o||Ts(e,t,i,r.memberAccess)}function MO(e,t,n,r){if(!r||M(t)!=="clojure")return null;let o=ne(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=>Je(s,c.file));if(a)return a}return n.find(s=>/`([^`]+)`\//.exec(s.symbol)?.[1]===r)??null}function OO(e,t){if(t.length===0)return new Map;let r=yd(t.map(m=>m.documentId)).flatMap(m=>e.all(`SELECT c.document_id, c.id AS chunk_id, c.start_line, c.end_line, m.symbol_id
402
- FROM mentions m
403
- JOIN chunks c ON m.chunk_id = c.id
404
- WHERE m.role != 1
405
- AND c.document_id IN (${m.map(()=>"?").join(",")})`,...m)),i=new Map;for(let m of r)i.has(m.document_id)||i.set(m.document_id,[]),i.get(m.document_id).push(m);let s=yd(r.map(m=>m.symbol_id)).flatMap(m=>e.all(`SELECT gs.id AS symbol_id, gs.symbol,
406
- COALESCE(der.document_id, def_chunk.document_id) AS document_id
407
- FROM global_symbols gs
408
- LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
409
- LEFT JOIN (
410
- SELECT m.symbol_id, MIN(c.document_id) AS document_id
411
- FROM mentions m
412
- JOIN chunks c ON m.chunk_id = c.id
413
- WHERE m.role = 1
414
- AND m.symbol_id IN (${m.map(()=>"?").join(",")})
415
- GROUP BY m.symbol_id
416
- ) def_chunk ON def_chunk.symbol_id = gs.id
417
- WHERE gs.id IN (${m.map(()=>"?").join(",")})`,...m,...m)),a=yd([...t.map(m=>m.documentId),...s.flatMap(m=>m.document_id===null?[]:[m.document_id])]),c=new Map(a.flatMap(m=>e.all(`SELECT id, relative_path FROM documents
418
- WHERE id IN (${m.map(()=>"?").join(",")})`,...m).map(p=>[p.id,p.relative_path]))),l=new Map;for(let m of s)l.has(m.symbol_id)||l.set(m.symbol_id,{symbol:m.symbol,file:m.document_id!==null?c.get(m.document_id)??"":""});let u=new Map,d=c,f=jO(t);for(let[m,p]of f){let h=[...i.get(m)??[]].sort((b,y)=>b.start_line-y.start_line||b.end_line-y.end_line),S=[...p].sort((b,y)=>b.startLine-y.startLine||b.endLine-y.endLine),C=new Set,x=0;for(let b of S){for(;x<h.length&&h[x].start_line<=b.endLine;)C.add(h[x]),x+=1;for(let I of C)I.end_line<b.startLine&&C.delete(I);let y=new Set,R=[],v=null,E=()=>{if(v)return v;let I=d.get(b.documentId)??"",k=new Set;if(I){let F=xg(e,I),te=Math.max(0,b.startLine),Y=Math.min(F.length-1,b.endLine);for(let L=te;L<=Y;L+=1)for(let oe of F[L])k.add(oe)}return v=k,k};for(let I of C){if(I.symbol_id===b.symbolId)continue;let k=l.get(I.symbol_id);if(!k)continue;if(!(I.start_line>=b.startLine&&I.end_line<=b.endLine)){if(!(I.start_line<=b.endLine&&I.end_line>=b.startLine))continue;let L=T(k.symbol);if(!L||!E().has(L))continue}let te=`${k.symbol}|${I.chunk_id}`;y.has(te)||(y.add(te),R.push({...k,chunkId:I.chunk_id,source:"scip-chunk"}))}u.set(b.symbolId,R)}}return u}var BS=500;function yd(e){let t=[...new Set(e)],n=[];for(let r=0;r<t.length;r+=BS)n.push(t.slice(r,r+BS));return n}function jO(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 $O(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"});t.set(n,i)}return t}function zS(e,t,n={}){let r=new Map;if(t&&t.length===0)return r;let i=N(e,{includeIgnored:!1}),o=qt(e),s=t??ve(e),a=new Set(s.map(l=>l.symbolId)),c=VO(s);if(BO(e,r,i,o,a,c),HO(e,r,s,a),zO(e,r,i,o,a,c),n.semantic!==!1){let l=Oe(e);KO(r,l.callerMap(qO(s)))}return r}function BO(e,t,n,r,i,o){for(let s of n){if(!M(s))continue;let a=fn(e,s);if(a)for(let c of a){if(o&&!o.has(c.calleeLeaf))continue;let l=Ps(s,r.get(c.calleeLeaf)??[]);if(!l||l.length===0)continue;let u=Ts(e,s,l,c.memberAccess);u&&i.has(u.symbolId)&&u.file!==s&&Sd(t,u.symbolId,s)}}}function HO(e,t,n,r){let i=WO(n);for(let o of UO(e,r))e.isIgnored(o.relative_path)||GO(o,i.get(o.symbol_id))||Sd(t,o.symbol_id,o.relative_path)}function UO(e,t){return Pr(e,t?[...t]:void 0)}function WO(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 GO(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function zO(e,t,n,r,i,o){for(let s of n){if(M(s)!=="rust")continue;let a=Un(e,s,{includeRustAttributeNames:!0});if(a.length!==0)for(let{name:c}of a){if(o&&!o.has(c))continue;let l=r.get(c);if(l)for(let u of l)i.has(u.symbolId)&&u.file!==s&&Sd(t,u.symbolId,s)}}}function Sd(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function VO(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"?T(n.symbol):"";r&&t.add(r)}return t.size>0?t:null}function qO(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function KO(e,t){for(let[n,r]of t){let i=e.get(n);i||(i=new Set,e.set(n,i));for(let o of r)i.add(o)}}function xt(e,t,n={}){return HS(e,t,n)}function VS(e,t,n={}){return bd(e,t,n)}function Cd(e,t,n={}){return zS(e,t,n)}function co(e,t,n={}){return _y(e,t,n)}function qS(e,t,n={}){let r=Cd(e,t,{semantic:n.semantic});return n.sourceFallback===!1?r:Qt(r,co(e,t))}function Qt(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 KS(e,t,n){let r=t.identifierResolution==="strict"?Mr:Py,i=t.candidateNames?Ei(t.candidateNames):null,o=0,s=0,a=0,c=0,l="";for(let u of t.paths)if(o+=1,l=u,!(!M(u)&&!(t.includeVueSfc&&Ot(u)))&&!e.isIgnored(u)&&!t.skipPath?.(u))try{if(i&&!_s(P(e,u),i))continue;s+=1;let f=(p,g,h,S)=>{if(t.candidateNames&&!t.candidateNames.has(p))return;a+=1;let C=t.resolveTargets?t.resolveTargets({sourceFile:u,name:p,kind:g,defaultTargets:S}):S();for(let x of C)c+=1,n({sourceFile:u,name:p,target:x,occurrences:h,kind:g})},m=Vt(e,u);for(let[p,g]of m)f(p,"identifier",g.length,()=>r(e,u,p));for(let p of Un(e,u,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let g=p.kind==="cross-language-dispatch"?()=>Mr(e,u,p.name):()=>r(e,u,p.name);f(p.name,p.kind,p.occurrences,g)}}finally{t.afterPath?.(u),o%10===0&&D("source-reference-scan.progress",()=>{},()=>({scannedPaths:o,currentPath:l,candidateMatchedPaths:s,visitedNames:a,visitedHits:c}))}}function O(e){return e.endLine-e.startLine+1}function JS(e,t={}){let{scope:n,files:r,minLoc:i=1,maxLoc:o=Number.POSITIVE_INFINITY,excludeSymbol:s,excludeEntrySurfaces:a=!1,excludeTypesFiles:c=!1,excludeRootedSymbols:l=!1,requireFunctionLikeSymbol:u=!1,requireCallableSymbol:d=!1,excludeRustTraitImplMembers:f=!1,includeSuppressed:m=!1,sortByLocDesc:p=!1}=t,g=[],h=JO(e,{scope:n,files:r,requireFunctionLikeSymbol:u,requireCallableSymbol:d}),S=new Map,C=new Map,x=y=>{let R=S.get(y);if(R!==void 0)return R;let v=De(e,y);return S.set(y,v),v},b=y=>{let R=C.get(y);if(R!==void 0)return R;let v=J(y);return C.set(y,v),v};for(let y of h){let R=y.relativePath;if(e.isIgnored(R)||a&&x(R)||!YO(y,{requireFunctionLikeSymbol:u,requireCallableSymbol:d})||s!==void 0&&y.symbol===s)continue;let v=O(y);v<i||v>o||c&&XO(R)||l&&ue(e,y.symbol,R)||f&&Re(y.symbol)||b(R)!=="test"&&(pr(y.symbol)||!m&&Vo(e,R,y.startLine)||g.push(y))}return p?g.sort((y,R)=>O(R)-O(y)):g}function JO(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=>X(e,r)):t.requireCallableSymbol?Ri(e,{scope:t.scope,symbolMatches:ce,sqlPrefilter:"callable"}):t.requireFunctionLikeSymbol?Ri(e,{scope:t.scope,symbolMatches:Z,sqlPrefilter:"function-like"}):gg(e,t.scope)}function YO(e,t){return t.requireCallableSymbol?ce(e.symbol):t.requireFunctionLikeSymbol?Z(e.symbol):e.isFunctionLike}function XO(e){return(e.split("/").pop()??"").includes("types")}var _=class{constructor(t){this.db=t}db;scopedDefinitions(t){return Ol(this.db,t)}definitionsForFile(t){return X(this.db,t)}productionCallableDefinitions(t={}){return JS(this.db,t)}calleeMap(t,n={}){return Na(this.db,t,n)}crossFileCallerMap(t,n={}){return Cd(this.db,t,n)}sourceFallbackCallerFiles(t,n={}){return co(this.db,t,n)}callerFileMap(t,n={}){return qS(this.db,t,n)}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 N(this.db,{includeIgnored:!1}))if(M(i)==="rust")for(let{name:o}of Un(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 se(this.db,t)}fileKind(t){return J(t)}hasSuppressionComment(t){return Vo(this.db,t.relativePath,t.startLine)}sourceFiles(){return Ue(this.db)}scanSourceReferences(t,n){KS(this.db,t,n)}callableSignature(t){let n=dt(this.db).forFile(t.relativePath,{facts:!0}).facts?.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};import{statSync as QO}from"fs";function rr(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,...ZO(e.config.dbPath)}}function ZO(e){try{let t=QO(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function ej(e){return/[*?]/.test(e)?e.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_"):`%${e}%`}function tj(e,t){let n=ej(t);return N(e,{like:n,includeIgnored:!1}).filter(r=>nj(t,r)).map(r=>({relativePath:r}))}function nj(e,t){if(!/[*?]/.test(e))return t.includes(e);let n=e.includes("/")?e:`**/${e}`;return Aa(n.split("/"),t.split("/"))}function Aa(e,t){if(e.length===0)return t.length===0;let[n,...r]=e;return n==="**"?Aa(r,t)||t.length>0&&Aa(e,t.slice(1)):t.length===0||!rj(n??"",t[0]??"")?!1:Aa(r,t.slice(1))}function rj(e,t){let n="^";for(let r of e)r==="*"?n+="[^/]*":r==="?"?n+="[^/]":n+=ij(r);return n+="$",new RegExp(n).test(t)}function ij(e){return/[\\^$.*+?()[\]{}|]/.test(e)?`\\${e}`:e}import{basename as oj}from"path";function sj(e,t){let n=$(e,t);if(!n)return[];let r=T(n.symbol),o=new _(e).definitionsForFile(n.relativePath).filter(l=>ce(l.symbol)),s=o.filter(l=>l.parentTypeName===r||l.symbol.includes(r)),c=(s.length>0?s:aj(oj(n.relativePath))===r?o.filter(l=>l.symbol.includes("<invalid-global-code>")):[]).map(l=>({startLine:l.startLine,endLine:l.endLine,name:T(l.symbol)}));return M(n.relativePath)!=="clojure"?c:lj(c,cj(e,n))}function aj(e){return e.replace(/\.[^.]+$/,"")}function cj(e,t){let n=T(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 lj(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)}function xd(e,t,n={}){let r=$(e,t);if(!r)return{definitions:[],referencedBy:[]};let i=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",r.symbolId),o=zt(i?.documentation??null),s=e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,signature:dj(o,i?.display_name??null,r.symbol),source:uj(e,r.relativePath,r.startLine,r.endLine)}],a=kt(e,r,{semantic:n.semantic}).map(c=>({relativePath:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol,enclosingShort:c.enclosingSymbol?w(c.enclosingSymbol):"(top-level)"}));return{definitions:s,referencedBy:a}}function uj(e,t,n,r){let i=P(e,t);if(!i)return null;let s=i.split(`
419
- `).slice(n,r+1).join(`
420
- `).trimEnd();return s.length>0?s:null}function dj(e,t,n){let r=Gt(e);if(r&&!fj(r))return r;let i=(t??"").trim();return i?Z(n)&&!i.endsWith("()")?`${i}()`:i:w(n)}function fj(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function vd(e,t){let n=je(e,t);return n?e.all(`SELECT DISTINCT d2.relative_path
421
- FROM mentions m
422
- JOIN chunks c ON m.chunk_id = c.id
423
- JOIN documents d1 ON c.document_id = d1.id
424
- JOIN global_symbols gs ON m.symbol_id = gs.id
425
- JOIN (
426
- SELECT m2.symbol_id, c2.document_id
427
- FROM mentions m2
428
- JOIN chunks c2 ON m2.chunk_id = c2.id
429
- WHERE m2.role = 1
430
- GROUP BY m2.symbol_id
431
- ) sym_def ON sym_def.symbol_id = gs.id
432
- JOIN documents d2 ON sym_def.document_id = d2.id
433
- WHERE d1.relative_path = ?
434
- AND d2.relative_path <> d1.relative_path
435
- AND ${e.localSymbolPredicate}
436
- ORDER BY d2.relative_path`,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function Rd(e,t){let n=je(e,t);return n?e.all(`SELECT DISTINCT d1.relative_path
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 d2.relative_path = ?
450
- AND d1.relative_path != ?
451
- ORDER BY d1.relative_path`,n,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function Id(e,t){let n=Or(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let r=n.map(()=>"?").join(", "),o=e.all(`SELECT relative_path FROM documents
452
- WHERE relative_path IN (${r})
453
- ORDER BY relative_path`,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d)),s=xs(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:d,...f})=>f),c=e.all(`SELECT DISTINCT d2.relative_path
454
- FROM mentions m
455
- JOIN chunks c ON m.chunk_id = c.id
456
- JOIN documents d1 ON c.document_id = d1.id
457
- JOIN global_symbols gs ON m.symbol_id = gs.id
458
- JOIN (
459
- SELECT m2.symbol_id, c2.document_id
460
- FROM mentions m2
461
- JOIN chunks c2 ON m2.chunk_id = c2.id
462
- WHERE m2.role = 1
463
- GROUP BY m2.symbol_id
464
- ) sym_def ON sym_def.symbol_id = gs.id
465
- JOIN documents d2 ON sym_def.document_id = d2.id
466
- WHERE d1.relative_path IN (${r})
467
- AND d2.relative_path NOT IN (${r})
468
- AND ${e.localSymbolPredicate}
469
- ORDER BY d2.relative_path`,...n,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d)),u=e.all(`SELECT DISTINCT d1.relative_path
470
- FROM mentions m
471
- JOIN chunks c ON m.chunk_id = c.id
472
- JOIN documents d1 ON c.document_id = d1.id
473
- JOIN global_symbols gs ON m.symbol_id = gs.id
474
- JOIN (
475
- SELECT m2.symbol_id, c2.document_id
476
- FROM mentions m2
477
- JOIN chunks c2 ON m2.chunk_id = c2.id
478
- WHERE m2.role = 1
479
- GROUP BY m2.symbol_id
480
- ) sym_def ON sym_def.symbol_id = gs.id
481
- JOIN documents d2 ON sym_def.document_id = d2.id
482
- WHERE d2.relative_path IN (${r})
483
- AND d1.relative_path NOT IN (${r})
484
- ORDER BY d1.relative_path`,...n,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d));return{files:o,symbols:s,dependsOn:c,dependedOnBy:u}}function wd(e,t){let n=Or(e,t);return n.length===0?[]:gj([...mj(e,n),...pj(e,n)]).filter(r=>!e.isIgnored(r.relative_path)).map(hj)}function mj(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
485
- FROM mentions m
486
- JOIN chunks c ON m.chunk_id = c.id
487
- JOIN documents d1 ON c.document_id = d1.id
488
- JOIN global_symbols gs ON m.symbol_id = gs.id
489
- WHERE d1.relative_path NOT IN (${n})
490
- AND (
491
- EXISTS (
492
- SELECT 1
493
- FROM defn_enclosing_ranges der
494
- JOIN documents d2 ON der.document_id = d2.id
495
- WHERE der.symbol_id = gs.id
496
- AND d2.relative_path IN (${n})
497
- )
498
- OR EXISTS (
499
- SELECT 1
500
- FROM mentions def_m
501
- JOIN chunks def_c ON def_m.chunk_id = def_c.id
502
- JOIN documents d2 ON def_c.document_id = d2.id
503
- WHERE def_m.symbol_id = gs.id
504
- AND def_m.role = 1
505
- AND d2.relative_path IN (${n})
506
- )
507
- )
508
- AND m.role != 1
509
- AND ${e.localSymbolPredicate}
510
- ${e.pathExclusionsFor("d1")}
511
- ORDER BY d1.relative_path`,...t,...t,...t)}function pj(e,t){let n=new _(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>ce(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function gj(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 hj(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:w(e.symbol)}}var lo=new WeakMap,YS=re({kind:"definition-exclusions",invalidation:q("definition-exclusions"),serialize:e=>JSON.stringify(e),deserialize:yj});function QS(e,t){let n=M(t);if(!(n==="rust"||n==="typescript"||n==="tsx"||n==="javascript"))return[];let i=P(e,t);if(!i)return[];let o=ae(e,t,i),s=YS.read(e,t,o);if(s)return s;let a=n==="rust"?wj(e,t):xj(e,t);return YS.write(e,t,o,a),a}function yj(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=t.map(bj);return n.some(r=>r===null)?null:n}catch{return null}}function bj(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?Oj(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 ZS=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]),Sj=/\b(?:describe|it|test|fdescribe|fit|xdescribe|xit|beforeEach|afterEach|beforeAll|afterAll|before|after|suite|bench|benchmark)\s*\(/,Cj=/\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 xj(e,t){let n=P(e,t);if(!n||!vj(n))return[];let r=V(e,t);if(!r)return[];let i=lo.get(r);if(i)return i;let o=!1,s=r.rootNode;for(let c of s.namedChildren){if(c.type!=="expression_statement")continue;let l=c.namedChild(0);if(!l||l.type!=="call_expression")continue;let u=l.namedChild(0);if(!u)continue;let d=u.type==="member_expression"?u.namedChild(u.namedChildCount-1)?.text:u.text;if(d&&ZS.has(d)){o=!0;break}}let a=[];o&&a.push({startLine:0,endLine:s.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)",disposition:"exclude"});for(let c of s.namedChildren){let l=null,u=null;if(c.type==="function_declaration")l=c.namedChild(0)?.text??null,u=c;else if(c.type==="export_statement"){let d=c.namedChild(0);d?.type==="function_declaration"&&(l=d.namedChild(0)?.text??null,u=d)}else if(c.type==="lexical_declaration"){let d=c.namedChild(0);if(d?.type==="variable_declarator"){let f=d.namedChild(0)?.text,m=d.namedChild(1);f&&(m?.type==="arrow_function"||m?.type==="function_expression")&&(l=f,u=d)}}l&&/^use[A-Z]/.test(l)&&u&&a.push({startLine:u.startPosition.row,endLine:u.endPosition.row,reason:"React custom hook (use*)",disposition:"exclude"})}return a.push(...eC(r,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),lo.set(r,a),a}function vj(e){if(e.includes("scip-query"))return!0;let t=!1;for(let n of ZS)if(e.includes(n)){t=!0;break}return t&&Sj.test(e)?!0:e.includes("use")&&Cj.test(e)}var Rj=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function Ij(e){return Rj.test(e)}function eC(e,t,n){let r=[],i=o=>{if(t.has(o.type)&&o.parent){let a=o.parent.children,c=-1;for(let l=0;l<a.length;l+=1)if(a[l].startIndex===o.startIndex&&a[l].type===o.type){c=l;break}if(c>0)for(let l=c-1;l>=0;l-=1){let u=a[l];if(n.has(u.type)){if(Ij(u.text)){r.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"scip-query suppression comment",disposition:"exclude"});break}continue}if(!(u.type==="attribute_item"||u.type==="inner_attribute_item"))break}}for(let s of o.namedChildren)i(s)};return i(e.rootNode),r}function wj(e,t){let n=V(e,t);if(!n)return[];let r=lo.get(n);if(r)return r;let i=[],o=Dj(n);return o?(lo.set(n,o),o):(tC(n.rootNode,i,!1,!1),i.push(...eC(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(...Aj(n.rootNode)),lo.set(n,i),i)}function Dj(e){return jj(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)",disposition:"exclude"}]:null}function tC(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"?Ej(e,t,n,r):r&&Nj(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"?kj(e,t,n):e.type==="mod_item"&&Dd(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(i=!0);for(let s of e.namedChildren)tC(s,t,i,o)}function Ej(e,t,n,r){let i=Dd(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(nC(s)){o={reason:"#[allow(dead_code)]",disposition:"exclude"};break}let a=Fj(s);if(a){o=a;break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o.reason,disposition:o.disposition})}function kj(e,t,n){let r=Dd(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(Lj)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(...)] - generated impl may access fields",disposition:"implicit-usage",containerName:i}),r.some(nC)&&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 Dd(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 Pj=new Set(["test","bench","tokio::test","async_std::test"]),Tj=new Set(["no_mangle","export_name","link_name","used","macro_export","proc_macro","proc_macro_derive","proc_macro_attribute"]),_j=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 Fj(e){if(/#\[\s*cfg\s*\(\s*test\s*\)/.test(e))return{reason:"#[cfg(test)]",disposition:"exclude"};let t=Mj(e);return t?Pj.has(t)?{reason:`#[${t}]`,disposition:"exclude"}:Tj.has(t)?{reason:`Rust ABI/export attribute #[${t}]`,disposition:"implicit-usage"}:_j.has(t)?null:{reason:`Rust attribute macro #[${t}]`,disposition:"implicit-usage"}:null}function Lj(e){return/#\[\s*derive\s*\(/.test(e)}function nC(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function Nj(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function Aj(e){let t=$j(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 Mj(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 Oj(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 jj(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 XS=/\bwith\s*=\s*"([^"]+)"/g;function $j(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){XS.lastIndex=0;let r;for(;(r=XS.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}function rC(e){let t=Ed(e);return(n,r,i,o)=>t(n,r,i,o)?.disposition==="exclude"}function Ed(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=QS(e,r),s=new Map;for(let a of o){if(!a.containerName)continue;let c=s.get(a.containerName)??[];c.push(a),s.set(a.containerName,c)}return i={ranges:o,containers:s},t.set(r,i),i};return(r,i,o,s)=>{let a=n(r),c=[];for(let u of a.ranges)i>=u.startLine&&i<=u.endLine&&c.push(u);let l=new Set;s&&l.add(s);for(let u of Is(o))l.add(u);for(let u of l){let d=a.containers.get(u);d&&c.push(...d)}return Bj(c)}}function Bj(e){if(e.length===0)return null;let n=e.find(r=>r.disposition==="exclude")??e[0];return{disposition:n.disposition,reason:n.reason}}function kd(e,t={}){kc(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function iC(e,t,n={}){kc(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function oC(e,t){if(t.isIgnoredPath(e.relativePath))return $e("ignored-file");if(dn(e.symbol))return $e("module-like-symbol");if(!Ma(e.symbol))return $e("non-value-symbol");if(!e.isFunctionLike&&e.enclosingSymbol&&Ma(e.enclosingSymbol))return $e("nested-non-callable-value");if(!t.includeTests&&!Hj(e.relativePath))return $e("test-file");if(!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName))return $e("excluded-file-region");let n=T(e.symbol);if(n==="<constructor>")return $e("implicit-constructor");if(e.symbol.startsWith("scip-python ")){if(n==="__all__")return $e("python-runtime-metadata");if(/^__[^_].*__$/.test(n))return $e("python-protocol-member")}return t.isDeclarationOnlyCallable()?$e("declaration-only-callable"):t.isFrameworkContractCallable()?$e("framework-contract-member"):Re(e.symbol)?$e("rust-trait-impl-member"):pr(e.symbol)?$e("rust-test-module"):!t.includeMembers&&!Uj(e)?$e("member"):e.endLine-e.startLine+1<t.minLoc?$e("below-min-loc"):{accepted:!0}}function Hj(e){return J(e)!=="test"}function $e(e){return{accepted:!1,rejectionReason:e}}function Ma(e){return Z(e)||e.endsWith("().")||e.endsWith(".")}function Uj(e){return ce(e.symbol)||Is(e.symbol).length===0}function Oa(e,t){return O(e)-O(t)||e.relativePath.localeCompare(t.relativePath)}function ie(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function Wr(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 sC(){return new Map}function aC(e,t,n){let r=new Map;for(let i of vg(e,n))e.isIgnored(i.relative_path)||t.has(i.relative_path)||$a(r,i.symbol_id,i.relative_path,i.ref_count,"scip-mention");return r}function cC(e,t,n,r={}){let i=new Set;if(r.conservative||n.size===0){for(let o of Ig(e,t))i.add(o.symbol_id);return i}for(let o of Rg(e,t))e.isIgnored(o.relative_path)||n.has(o.relative_path)||i.add(o.symbol_id);return i}function Pd(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 ja(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 lC(e){return e?.occurrences??0}function $a(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=dC(e,t,n);o.occurrences+=r,o.sources.add(i)}function uC(e,t,n,r,i){if(r<=0)return;let o=dC(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function dC(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 Wj=new Set(["componentDidCatch","componentDidMount","componentDidUpdate","componentWillUnmount","getDerivedStateFromError","getDerivedStateFromProps","getSnapshotBeforeUpdate","render","shouldComponentUpdate","UNSAFE_componentWillMount","UNSAFE_componentWillReceiveProps","UNSAFE_componentWillUpdate"]);function Gr(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=V(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:Wj.has(t.leaf)&&/\bextends\s+(?:React\.)?(?:Component|PureComponent)\b/.test(o)}var Gj=1e3,zj=300;function ir(e,t={}){let{scope:n,minLoc:r=1,includeTests:i=!1,skipBarrels:o=!1,includeMembers:s=!1,deadCodeOnly:a=!1,scanLimit:c,semantic:l=!0}=t,u=0,d=D("dead.candidates",()=>{let y=ie(Vj(e,{scope:n,minLoc:r,includeTests:i,includeMembers:s}),c);return u=y.length,y},()=>({definitions:u})),f=0,m=o?D("dead.inactive-barrels",()=>{let y=new Set(_S(e));return f=y.size,y},()=>({paths:f})):new Set,p=0,g=a?sC():D("dead.mention-reference-counts",()=>{let y=aC(e,m,d.map(R=>R.symbolId));return p=y.size,y},()=>({definitions:d.length,symbolsWithReferences:p})),h=0,S=a?D("dead.mentioned-symbol-ids",()=>{let y=cC(e,d.map(R=>R.symbolId),m,{conservative:m.size===0});return h=y.size,y},()=>({definitions:d.length,referencedSymbols:h})):new Set,C=a?d.filter(y=>!S.has(y.symbolId)):d.filter(y=>!ja(g,y.symbolId,y.relativePath));a?D("dead.source-fallback.dead-code-only",()=>Zj(e,C,g,{inactiveBarrelPaths:m}),()=>({definitions:C.length,testReferencesIncluded:!0})):D("dead.source-fallback.ast",()=>Qj(e,C,g,{inactiveBarrelPaths:m}),()=>({definitions:C.length,testReferencesIncluded:!0}));let x=a?C.filter(y=>!Pd(g,y.symbolId)):C.filter(y=>!ja(g,y.symbolId,y.relativePath));D("dead.caller-map-supplement",()=>i$(e,x,g,{inactiveBarrelPaths:m,includeSemantic:!a&&l}),()=>({definitions:x.length,semantic:!a&&l}));let b=a?C.filter(y=>!Pd(g,y.symbolId)):d;return Xj(e,Jj(b,g))}function Vj(e,t){let n=rC(e),r=[];for(let i of Ri(e,{scope:t.scope,symbolMatches:Ma,sqlPrefilter:"function-like"}))oC(i,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:s=>e.isIgnored(s),isExcludedRegion:n,isDeclarationOnlyCallable:()=>Kj(e,i),isFrameworkContractCallable:()=>Gr(e,i)}).accepted&&r.push(i);return r}var qj=["method_signature","abstract_method_signature","call_signature","construct_signature"];function Kj(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=V(e,t.relativePath);if(n)return n.rootNode.descendantsOfType([...qj]).some(i=>i.startPosition.row<=t.startLine&&i.endPosition.row>=t.endLine);let r=Ce(e,t.relativePath).slice(t.startLine,t.endLine+1).join(`
512
- `).trim();return r.endsWith(";")&&!r.includes("=>")&&!r.includes("{")}function Jj(e,t){return e.map(n=>Yj(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 Yj(e,t){let n=t.get(e.symbolId)??new Map,r=lC(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 Xj(e,t){let n=Ed(e),r=[],i=0,o=0,s=0,a=0,c=0,l=0;for(let u of t){if(e.isIgnored(u.relative_path))continue;if(De(e,u.relative_path)){a++;continue}if(ue(e,u.symbol,u.relative_path)){c++;continue}let d=n(u.relative_path,u.start_line,u.symbol,u.parent_type_name),f=d?.disposition==="implicit-usage"?d.reason:void 0,m=f?"implicit-usage":u.same_file_refs===0?"dead-code":"file-internal";m==="dead-code"?i++:m==="file-internal"?o++:s++,l+=u.loc,r.push({relativePath:u.relative_path,startLine:u.start_line,endLine:u.end_line,loc:u.loc,symbol:u.symbol,shortName:w(u.symbol),sameFileRefs:u.same_file_refs,kind:m,...f?{implicitUsageReason:f}:{}})}return{symbols:r,counts:{total:r.length,deadCode:i,fileInternal:o,implicitUsage:s,loc:l},applicability:{entrySurfaceExcluded:a,externalRootExcluded:c,implicitUsageSignals:s},totalCount:r.length,deadCodeCount:i,fileInternalCount:o,implicitUsageCount:s,totalLoc:l}}function Qj(e,t,n,r){if(t.length===0)return;let i=new _(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 N(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)&&(n$(e,c)||$a(n,c.target.symbolId,c.sourceFile,r$(c),"source-fallback"))})}function Zj(e,t,n,r){if(t.length===0)return;let i=new _(e),o=e$(t),s=new Set(i.sourceFiles());for(let u of N(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let d=c.get(u);return d||(d=la(e,u),c.set(u,d)),d};i.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:u=>r.inactiveBarrelPaths.has(u),resolveTargets:({sourceFile:u,name:d,kind:f})=>{let m=o.get(d);return m?t$(u,d,m,()=>l(u),{permissive:f!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),iC(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&fC(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||$a(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function e$(e){let t=new Map;for(let n of e){if(!n.leaf)continue;let r=t.get(n.leaf)??[];r.push(n),t.set(n.leaf,r)}return t}function t$(e,t,n,r,i){let o=n.filter(l=>l.relativePath===e);if(o.length>0)return o;if(!i.permissive&&n.length===1)return[...n];let s=r(),a=s.get(t);if(a)for(let l of a){let u=n.filter(d=>Je(l,d.relativePath));if(u.length>0)return u}let c=new Set;for(let l of s.values())for(let u of l)c.add(u);for(let l of c){let u=n.filter(d=>Je(l,d.relativePath));if(u.length>0&&u.length===n.length)return u}return i.permissive?[...n]:[]}function n$(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&fC(e,t)}function r$(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function fC(e,t){return t.occurrences>1?!1:ne(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function i$(e,t,n,r){let i=r.includeSemantic!==!1,o=i&&t.length>=Gj&&N(e).length>=zj,s=(u,d)=>{d===u.relativePath||e.isIgnored(d)||r.inactiveBarrelPaths.has(d)||uC(n,u.symbolId,d,1,"caller-map")};if(o?D("dead.caller-map.per-symbol-non-semantic",()=>{for(let u of t){let d=xt(e,u,{semantic:!1});for(let f of d)s(u,f.file)}},()=>({definitions:t.length,semantic:!1})):D("dead.caller-map.per-symbol",()=>{for(let u of t){let d=xt(e,u,{semantic:i});if(d.length!==0)for(let f of d)s(u,f.file)}},()=>({definitions:t.length,semantic:i})),!o)return;let a=0,c=D("dead.caller-map.semantic-candidates",()=>{let u=t.filter(d=>!ja(n,d.symbolId,d.relativePath));return a=u.length,u},()=>({definitions:t.length,semanticCandidates:a}));if(c.length===0)return;let l=vy(e,c);for(let u of c){let d=l.get(u.symbolId);if(d)for(let f of d)s(u,f)}}function o$(e,t={}){let{limit:n=30,scope:r}=t,i=r?"AND def_d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[],a=e.all(`SELECT
513
- gs.symbol,
514
- COUNT(*) AS ref_count,
515
- COUNT(DISTINCT ref_d.id) AS file_count,
516
- def_d.relative_path AS defined_in
517
- FROM mentions m
518
- JOIN chunks c ON m.chunk_id = c.id
519
- JOIN documents ref_d ON c.document_id = ref_d.id
520
- JOIN global_symbols gs ON m.symbol_id = gs.id
521
- JOIN (
522
- SELECT m2.symbol_id, c2.document_id
523
- FROM mentions m2
524
- JOIN chunks c2 ON m2.chunk_id = c2.id
525
- WHERE m2.role = 1
526
- GROUP BY m2.symbol_id
527
- ) sym_def ON sym_def.symbol_id = gs.id
528
- JOIN documents def_d ON sym_def.document_id = def_d.id
529
- WHERE m.role != 1
530
- AND def_d.id != ref_d.id
531
- ${e.pathExclusionsFor("def_d")}
532
- ${e.symbolNoiseFor("gs")}
533
- ${i}
534
- GROUP BY gs.id
535
- ORDER BY ref_count DESC
536
- LIMIT ?`,...o,n).filter(c=>!e.isIgnored(c.defined_in)).map(c=>({symbol:c.symbol,shortName:w(c.symbol),refCount:c.ref_count,fileCount:c.file_count,definedIn:c.defined_in}));return a.length>0?a:s$(e,r,n)}function s$(e,t,n){return ve(e,{scope:t}).filter(r=>!e.isIgnored(r.relativePath)).map(r=>a$(e,r)).filter(r=>r.refCount>0).sort((r,i)=>i.refCount-r.refCount||i.fileCount-r.fileCount).slice(0,n)}function a$(e,t){let r=xt(e,t,{limit:500}).filter(i=>i.file!==t.relativePath);return{symbol:t.symbol,shortName:w(t.symbol),refCount:r.length,fileCount:new Set(r.map(i=>i.file)).size,definedIn:t.relativePath}}function c$(e,t,n={}){return b$(e,t,n)?.map(r=>({symbol:r.symbol,shortName:r.shortName,fromFile:r.fromFile}))??[]}function l$(e,t){let n=$(e,t),r=f$(e,t);if(r.length>0&&!p$(n))return r;let i=m$(e,t,n);return Td(t)&&i.length>0?i:g$([...r,...i])}function u$(e,t,n={}){let r=je(e,t);if(!r)return[];let i=pC(e,r),o=n.semantic===!1?null:mC(e,r);return(o?d$(o,i):i).filter(a=>!a.used).map(a=>({symbol:a.symbol,shortName:a.shortName,importedIn:a.importer}))}function d$(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 f$(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
537
- FROM mentions m
538
- JOIN chunks c ON m.chunk_id = c.id
539
- JOIN documents d ON c.document_id = d.id
540
- JOIN global_symbols gs ON m.symbol_id = gs.id
541
- WHERE gs.symbol LIKE ?
542
- AND m.role = 2
543
- ORDER BY d.relative_path`,`%${t}%`).filter(r=>!e.isIgnored(r.importer)).map(r=>({symbol:r.symbol,shortName:w(r.symbol),fromFile:r.importer}))}function m$(e,t,n=$(e,t)){let r=n?.relativePath??null,i=n?T(n.symbol):t.replace(/\(\)$/,""),o=n?dn(n.symbol):!1,s=new Set;for(let c of N(e,{includeIgnored:!1}))for(let l of ne(e,c))h$(l,c,{targetFile:r,targetLeaf:i,targetIsModule:o,targetPattern:t})&&s.add(c);let a=Td(t)?t.trim():null;return[...s].sort().map(c=>({symbol:a??n?.symbol??i,shortName:a??(n?w(n.symbol):i),fromFile:c}))}function p$(e){return!!(e&&(e.symbol.startsWith("scip-clojure ")||M(e.relativePath)==="clojure"))}function g$(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 h$(e,t,n){return!e.sourcePath||n.targetFile&&ee(e.sourcePath)!==ee(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&v$(t)||e.kind==="namespace"&&y$(e,n.targetPattern)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function y$(e,t){let n=t.trim().replace(/\(\)$/,"");return Td(n)?e.importedName===n||e.localName===n:!1}function Td(e){let t=e.trim().replace(/\(\)$/,"");return t.includes(".")&&!t.includes("/")&&!t.includes(":")}function b$(e,t,n={}){let r=je(e,t);return r?S$(e,r,n)??(n.semantic===!1?null:mC(e,r))??pC(e,r):null}function S$(e,t,n){let i=e.all(`SELECT DISTINCT
544
- gs.symbol,
545
- def_d.relative_path AS from_file,
546
- imp_d.relative_path AS importer,
547
- EXISTS (
548
- SELECT 1
549
- FROM mentions ref_m
550
- JOIN chunks ref_c ON ref_m.chunk_id = ref_c.id
551
- WHERE ref_m.symbol_id = gs.id
552
- AND ref_m.role != 1
553
- AND ref_c.document_id = imp_d.id
554
- ) AS used
555
- FROM mentions m
556
- JOIN chunks c ON m.chunk_id = c.id
557
- JOIN documents imp_d ON c.document_id = imp_d.id
558
- JOIN global_symbols gs ON m.symbol_id = gs.id
559
- LEFT JOIN (
560
- SELECT m2.symbol_id, c2.document_id
561
- FROM mentions m2
562
- JOIN chunks c2 ON m2.chunk_id = c2.id
563
- WHERE m2.role = 1
564
- GROUP BY m2.symbol_id
565
- ) sym_def ON sym_def.symbol_id = gs.id
566
- LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
567
- WHERE imp_d.relative_path = ?
568
- AND m.role = 2
569
- ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(i.length>0){let o=n.semantic===!1?[]:Ui(e,t);return i.map(s=>({symbol:s.symbol,shortName:w(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 mC(e,t){let n=Ui(e,t);return n.length>0?n.map(r=>{let i=gC(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 pC(e,t){let n=C$(t,P(e,t));return ne(e,t).map(r=>{let i=gC(r.importedName,r.localName,r.kind),o=r.kind==="side-effect"||x$(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 C$(e,t){let n=new Set;if(M(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 x$(e,t){if(M(e)!=="rust"||t.used||t.kind==="side-effect")return!1;let n=t.localName??t.importedName;return n==="_"||/^[A-Z]/.test(n)}function gC(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 v$(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function R$(e,t){let n=$(e,t);if(!n)return[];let i=new _(e).definitionsForFile(n.relativePath).filter(o=>o.symbol!==n.symbol).filter(o=>Mm(n.symbol,o.symbol)).sort((o,s)=>o.startLine-s.startLine||o.endLine-s.endLine).map(o=>({symbol:o.symbol,shortName:w(o.symbol),startLine:o.startLine,endLine:o.endLine,kind:le(o.symbol)??"unknown"}));return M(n.relativePath)!=="clojure"?i:w$(i,I$(e,n))}function I$(e,t){let n=T(t.symbol);if(!n)return[];let r=w(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 w$(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 D$(e,t){let n=$(e,t);if(!n)return[];let r=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
570
- FROM mentions m
571
- JOIN chunks c ON m.chunk_id = c.id
572
- JOIN (
573
- SELECT m2.symbol_id, c2.document_id
574
- FROM mentions m2
575
- JOIN chunks c2 ON m2.chunk_id = c2.id
576
- WHERE m2.role = 1
577
- GROUP BY m2.symbol_id
578
- ) sym_def ON sym_def.symbol_id = m.symbol_id
579
- WHERE m.symbol_id = ?
580
- AND m.role != 1
581
- AND sym_def.document_id != c.document_id`,n.symbolId);return[{name:w(n.symbol),count:r?.file_count??0,symbol:n.symbol,definedIn:n.relativePath}]}function E$(e,t){let n=je(e,t);if(!n)return[];let i=e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
582
- FROM mentions m
583
- JOIN chunks c ON m.chunk_id = c.id
584
- JOIN documents d ON c.document_id = d.id
585
- JOIN global_symbols gs ON m.symbol_id = gs.id
586
- JOIN (
587
- SELECT m2.symbol_id, c2.document_id
588
- FROM mentions m2
589
- JOIN chunks c2 ON m2.chunk_id = c2.id
590
- WHERE m2.role = 1
591
- GROUP BY m2.symbol_id
592
- ) sym_def ON sym_def.symbol_id = gs.id
593
- JOIN documents def_d ON sym_def.document_id = def_d.id
594
- WHERE d.relative_path = ?
595
- AND m.role != 1
596
- AND def_d.id != d.id
597
- GROUP BY d.id
598
- ORDER BY symbol_count DESC`,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}));if(i.length>0)return i;let s=se(e).get(n);return!s||s.size===0?[]:[{name:n,count:s.size}]}function k$(e,t={}){return P$(e,t).map(n=>({name:w(n.symbol),count:n.file_count,symbol:n.symbol,definedIn:n.defined_in}))}function P$(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,
599
- COUNT(DISTINCT c.document_id) AS file_count,
600
- def_d.relative_path AS defined_in
601
- FROM mentions m
602
- JOIN chunks c ON m.chunk_id = c.id
603
- JOIN global_symbols gs ON m.symbol_id = gs.id
604
- JOIN (
605
- SELECT m2.symbol_id, c2.document_id
606
- FROM mentions m2
607
- JOIN chunks c2 ON m2.chunk_id = c2.id
608
- WHERE m2.role = 1
609
- GROUP BY m2.symbol_id
610
- ) sym_def ON sym_def.symbol_id = gs.id
611
- JOIN documents def_d ON sym_def.document_id = def_d.id
612
- WHERE m.role != 1
613
- AND def_d.id != c.document_id
614
- ${e.pathExclusionsFor("def_d")}
615
- ${e.symbolNoiseFor("gs")}
616
- ${i}
617
- GROUP BY gs.id
618
- HAVING file_count > 1
619
- ORDER BY file_count DESC
620
- LIMIT ?`,...o,n)}function T$(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
621
- FROM mentions m
622
- JOIN chunks c ON m.chunk_id = c.id
623
- JOIN documents d ON c.document_id = d.id
624
- JOIN global_symbols gs ON m.symbol_id = gs.id
625
- JOIN (
626
- SELECT m2.symbol_id, c2.document_id
627
- FROM mentions m2
628
- JOIN chunks c2 ON m2.chunk_id = c2.id
629
- WHERE m2.role = 1
630
- GROUP BY m2.symbol_id
631
- ) sym_def ON sym_def.symbol_id = gs.id
632
- JOIN documents def_d ON sym_def.document_id = def_d.id
633
- WHERE m.role != 1
634
- AND def_d.id != d.id
635
- ${e.pathExclusionsFor("d")}
636
- ${e.symbolNoiseFor("gs")}
637
- ${i}
638
- GROUP BY d.id
639
- ORDER BY symbol_count DESC
640
- LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}))}function _$(e,t,n){let r=je(e,t)??t,i=je(e,n)??n,o=e.get(`SELECT COUNT(DISTINCT gs.id) AS shared
641
- FROM global_symbols gs
642
- WHERE (
643
- -- Defined in file1, referenced in file2
644
- EXISTS (
645
- SELECT 1
646
- FROM mentions def_m
647
- JOIN chunks def_c ON def_m.chunk_id = def_c.id
648
- JOIN documents d ON def_c.document_id = d.id
649
- WHERE def_m.symbol_id = gs.id AND def_m.role = 1 AND d.relative_path = ?
650
- )
651
- AND EXISTS (
652
- SELECT 1 FROM mentions m
653
- JOIN chunks c ON m.chunk_id = c.id
654
- JOIN documents d ON c.document_id = d.id
655
- WHERE m.symbol_id = gs.id AND m.role != 1 AND d.relative_path = ?
656
- )
657
- ) OR (
658
- -- Defined in file2, referenced in file1
659
- EXISTS (
660
- SELECT 1
661
- FROM mentions def_m
662
- JOIN chunks def_c ON def_m.chunk_id = def_c.id
663
- JOIN documents d ON def_c.document_id = d.id
664
- WHERE def_m.symbol_id = gs.id AND def_m.role = 1 AND d.relative_path = ?
665
- )
666
- AND EXISTS (
667
- SELECT 1 FROM mentions m
668
- JOIN chunks c ON m.chunk_id = c.id
669
- JOIN documents d ON c.document_id = d.id
670
- WHERE m.symbol_id = gs.id AND m.role != 1 AND d.relative_path = ?
671
- )
672
- )`,r,i,i,r);return{...hC(r,i,o?.shared??0)}}function F$(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
673
- def_d.relative_path AS file1,
674
- ref_d.relative_path AS file2,
675
- COUNT(DISTINCT gs.id) AS shared
676
- FROM mentions m
677
- JOIN chunks c ON m.chunk_id = c.id
678
- JOIN documents ref_d ON c.document_id = ref_d.id
679
- JOIN global_symbols gs ON m.symbol_id = gs.id
680
- JOIN (
681
- SELECT m2.symbol_id, c2.document_id
682
- FROM mentions m2
683
- JOIN chunks c2 ON m2.chunk_id = c2.id
684
- WHERE m2.role = 1
685
- GROUP BY m2.symbol_id
686
- ) sym_def ON sym_def.symbol_id = gs.id
687
- JOIN documents def_d ON sym_def.document_id = def_d.id
688
- WHERE m.role != 1
689
- AND def_d.id != ref_d.id
690
- ${e.pathExclusionsFor("def_d","ref_d")}
691
- ${i}
692
- GROUP BY def_d.id, ref_d.id
693
- ORDER BY shared DESC
694
- LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.file1)&&!e.isIgnored(a.file2)).map(a=>hC(a.file1,a.file2,a.shared))}function hC(e,t,n){return{file1:e,file2:t,sharedSymbols:n,actionTier:"signal",couplingKind:"shared-symbol-coupling",evidenceReasons:[`${n} symbol(s) are defined in one file and referenced by the other`],recommendation:"Review whether the shared symbol surface is an intentional boundary or hidden coordination pressure before moving code."}}function uo(e,t={}){return SC(e,t).cycles}function SC(e,t={}){let{scope:n,maxDepth:r=10}=t,i=se(e,n,{scipEdges:"imports-only"}),o=[],s=new Set,a=new Set,c=[],l=!1;function u(f,m){if(m>r){l=!0;return}if(a.has(f)){let g=c.indexOf(f);if(g!==-1){let h=c.slice(g).concat(f),S=h.indexOf(h.reduce((b,y)=>b<y?b:y)),C=[...h.slice(S,-1),...h.slice(0,S),h[S]],x=C.join(" -> ");d.has(x)||(d.add(x),o.push({path:C,kind:L$(C)}))}return}if(s.has(f))return;s.add(f),a.add(f),c.push(f);let p=i.get(f);if(p)for(let g of p)u(g,m+1);c.pop(),a.delete(f)}let d=new Set;for(let f of i.keys())s.has(f)||u(f,0);return o.sort((f,m)=>f.kind!==m.kind?f.kind==="real"?-1:1:f.path.length-m.path.length),{cycles:o,truncated:l,maxDepth:r}}function L$(e){for(let r of e){let i=J(r);if(i==="test"||i==="barrel"||i==="entry")return"module-hierarchy"}if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":Ur(t)||Ur(n)||yC(t,n)||yC(n,t)||bC(t,n)||bC(n,t)||J(t)==="entry"||J(n)==="entry"?"module-hierarchy":"real"}function yC(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=t.replace(/\.rs$/,"/");return e.startsWith(n)?!e.slice(n.length).includes("/"):!1}function bC(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=e.replace(/\.rs$/,""),r=t.replace(/\.rs$/,"");if(n===r+"_tests"||n===r+"/tests")return!0;let i=e.split("/"),o=t.split("/");if(i.length===o.length&&i.includes("tests")&&o.includes("src")){let s=i[i.length-1],a=o[o.length-1];if(s&&s===a)return!0}return!1}function N$(e,t={}){let{limit:n=20,scope:r,minFanIn:i=2,minFanOut:o=2,scanLimit:s}=t,a=new _(e);return ie(a.productionCallableDefinitions({scope:r,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s).map(u=>A$(e,u,t.semantic!==!1)).filter(u=>u.fanIn>=i&&u.fanOut>=o).sort((u,d)=>d.score-u.score||d.fanIn-u.fanIn).slice(0,n)}function A$(e,t,n){let r=[...new Set(xt(e,t,{limit:500,semantic:n}).map(l=>l.file))].sort(),i=new Map;for(let l of mt(e,t,{limit:500,semantic:n})){if(l.file===t.relativePath)continue;let u=`${l.symbol}|${l.file}`;i.has(u)||i.set(u,{symbol:l.symbol,shortName:w(l.symbol),file:l.file})}let o=[...i.values()].sort((l,u)=>l.file.localeCompare(u.file)||l.symbol.localeCompare(u.symbol)),s=r.length,a=o.length,c=s*a;return{symbol:t.symbol,shortName:w(t.symbol),fanIn:s,fanOut:a,callerFiles:r,externalCallees:o,score:c,definedIn:t.relativePath,actionTier:"signal",riskKind:"coordination-hotspot",evidenceReasons:[`${s} incoming file(s) reference this symbol`,`${a} distinct cross-file callee symbol(s) are reached from it`,`centrality score is ${c} (fan-in * fan-out)`],recommendation:"Review ownership, API stability, and caller groups before changing this central symbol; do not refactor solely from graph centrality."}}function fo(e,t={}){let{scope:n,minLoc:r=3,scanLimit:i}=t,o=new _(e),s=t.semantic!==!1,a=0,c=D("isolated.candidates",()=>{let R=ie(o.productionCallableDefinitions({scope:n,minLoc:r,excludeEntrySurfaces:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:typeof i=="number"&&i>0}),i).filter(v=>!Gr(e,v));return a=R.length,R},()=>({definitions:a})),l=0,u=D("isolated.strict-callees",()=>{let y=o.symbolsWithNonSelfCallees(c,{additive:!1,semantic:!1});return l=y.size,y},()=>({definitions:c.length,symbols:l})),d=c.filter(y=>!u.has(y.symbolId)),f=0,m=D("isolated.scip-callers",()=>{let y=o.crossFileCallerMap(d,{semantic:!1});return f=y.size,y},()=>({definitions:d.length,symbols:f})),p=new Set(m.keys());for(let y of o.frameworkReferencedSymbolIds(d))p.add(y);let g=d.filter(y=>!p.has(y.symbolId));if(s&&g.length>0){for(let y of vn(e,g).keys())p.add(y);for(let y of o.symbolsWithNonSelfCallees(g,{additive:!1,semantic:!0}))u.add(y);g=g.filter(y=>!p.has(y.symbolId)).filter(y=>!u.has(y.symbolId))}let h=0,S=D("isolated.source-fallback-callers",()=>{let y=o.sourceFallbackCallerFiles(g,{skipPath:R=>J(R)==="test"});return h=y.size,y},()=>({definitions:g.length,symbols:h}));for(let y of S.keys())p.add(y);let C=g.filter(y=>!p.has(y.symbolId)),x=0,b=D("isolated.additive-callees",()=>{let y=o.symbolsWithNonSelfCallees(C,{additive:!0,semantic:s});return x=y.size,y},()=>({definitions:C.length,symbols:x}));for(let y of b)u.add(y);return C.filter(y=>!u.has(y.symbolId)).sort((y,R)=>O(R)-O(y)||y.relativePath.localeCompare(R.relativePath)||y.startLine-R.startLine).map(y=>({symbol:y.symbol,shortName:w(y.symbol),relativePath:y.relativePath,startLine:y.startLine,endLine:y.endLine,loc:O(y)}))}import{SymbolInformation_Kind as Ee}from"@c4312/scip";var CC=500;function M$(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),r=jS.get(n);if(r!==void 0)return r;for(let[i,o]of La)if(o.toLowerCase().includes(n))return i;return null}function O$(e,t,n={}){let{scope:r,limit:i=100}=n,o=M$(t);return o===null?[]:$$(e,r).map(a=>({row:a,resolvedKind:vC(a)})).filter(a=>a.resolvedKind===o).slice(0,i).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:w(a.symbol),kind:c,kindName:ao(c),relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function j$(e,t={}){let n=B$(e,t.scope);for(let r of H$(e,t.scope)){let i=vC(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:ao(r),count:i}))}function $$(e,t){return ve(e,{scope:t}).map(U$)}function B$(e,t){let n=new Map;for(let r of xC(N(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", "),o=e.all(`SELECT gs.kind AS kind, COUNT(*) AS count
695
- FROM defn_enclosing_ranges der
696
- JOIN global_symbols gs ON der.symbol_id = gs.id
697
- JOIN documents d ON der.document_id = d.id
698
- WHERE gs.kind IS NOT NULL
699
- AND gs.kind != 0
700
- AND gs.symbol NOT LIKE '%#'
701
- AND d.relative_path IN (${i})
702
- GROUP BY gs.kind`,...r);for(let s of o)n.set(s.kind,(n.get(s.kind)??0)+s.count)}return n}function H$(e,t){let n=[];for(let r of xC(N(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", ");n.push(...e.all(`SELECT gs.symbol,
703
- gs.kind,
704
- gs.documentation,
705
- gs.enclosing_symbol,
706
- d.relative_path,
707
- der.start_line,
708
- der.end_line
709
- FROM defn_enclosing_ranges der
710
- JOIN global_symbols gs ON der.symbol_id = gs.id
711
- JOIN documents d ON der.document_id = d.id
712
- WHERE (gs.kind IS NULL OR gs.kind = 0 OR gs.symbol LIKE '%#')
713
- ${e.symbolNoiseFor("gs")}
714
- AND d.relative_path IN (${i})
715
- ORDER BY d.relative_path, der.start_line, der.end_line, gs.symbol`,...r))}return n}function xC(e){let t=[];for(let n=0;n<e.length;n+=CC)t.push(e.slice(n,n+CC));return t}function U$(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 vC(e){return e.kind!==null&&e.kind!==0?W$(e.kind,e.symbol,e.documentation):G$(e.symbol,e.documentation,e.enclosing_symbol)}function W$(e,t,n){let r=(n??"").toLowerCase();if(le(t)==="type"){if(r.includes("type "))return Ee.TypeAlias;if(r.includes("interface "))return Ee.Interface;if(r.includes("struct "))return Ee.Struct;if(r.includes("trait "))return Ee.Trait;if(r.includes("class "))return Ee.Class}return e}function G$(e,t,n){let r=ye(e);if("kind"in r)return null;let i=r.descriptors,o=i[i.length-2]??null,s=le(e),a=(t??"").toLowerCase();return s==="type"?a.includes("type ")?Ee.TypeAlias:a.includes("interface ")?Ee.Interface:a.includes("struct ")?Ee.Struct:a.includes("trait ")?Ee.Trait:a.includes("class ")?Ee.Class:Ee.Class:s==="method"?o?.suffix==="type"?Ee.Method:Ee.Function:s==="namespace"?Ee.Module:s!=="term"?null:a.includes("async def ")||a.includes("def ")?Ee.Function:(n?le(n):o?.suffix??null)==="type"?Ee.Field:Ee.Variable}function z$(e,t={}){let{limit:n=10,scope:r,minDepth:i=3}=t,o=se(e,r),s=new Map,a=[],c=new Map,l=new Map,u=new Set,d=[],f=0;for(let b of o.keys()){if(c.has(b))continue;let y=[],R=(o.get(b)??new Set).values();for(c.set(b,f),l.set(b,f),f+=1,d.push(b),u.add(b),y.push({node:b,iter:R,pendingChild:null});y.length>0;){let v=y[y.length-1];if(v.pendingChild!==null){let k=v.pendingChild;v.pendingChild=null,l.set(v.node,Math.min(l.get(v.node),l.get(k)))}let E=v.iter.next();if(E.done){if(l.get(v.node)===c.get(v.node)){let k=[];for(;;){let F=d.pop();if(u.delete(F),k.push(F),s.set(F,a.length),F===v.node)break}a.push(k)}y.pop();continue}let I=E.value;if(c.has(I))u.has(I)&&l.set(v.node,Math.min(l.get(v.node),c.get(I)));else{c.set(I,f),l.set(I,f),f+=1,d.push(I),u.add(I);let k=(o.get(I)??new Set).values();v.pendingChild=I,y.push({node:I,iter:k,pendingChild:null})}}}let m=new Map;for(let b=0;b<a.length;b++)m.set(b,new Set);for(let[b,y]of o){let R=s.get(b);for(let v of y){let E=s.get(v);E!==R&&m.get(R).add(E)}}let p=new Array(a.length),g=new Array(a.length);for(let b=0;b<a.length;b++){let y=[],R=0;for(let v of m.get(b)){let E=g[v];E>R&&(R=E,y=p[v])}p[b]=[b,...y],g[b]=1+R}function h(b){return p[b]}let S=a.map(b=>[...b].sort()),C=new Set,x=[];for(let b=0;b<a.length;b++){let R=h(b).map(I=>S[I]),v=R.map(I=>I[0]);if(R.length<i)continue;let E=v.join(" ");C.has(E)||(C.add(E),x.push(V$(v,R)))}return x.sort((b,y)=>y.depth-b.depth),q$(x).slice(0,n)}function V$(e,t){let n=t.reduce((i,o)=>i+o.length,0),r=t.filter(i=>i.length>1).length;return{chain:e,components:t,depth:t.length,fileCount:n,actionTier:"signal",chainKind:"transitive-dependency-depth",evidenceReasons:[`${t.length} condensed dependency component(s) form the representative transitive path`,`${n} file(s) are represented; ${r} component(s) contain a dependency cycle`,"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 q$(e){let t=[];for(let n of e)t.some(r=>K$(n.chain,r.chain))||t.push(n);return t}function K$(e,t){if(e.length>=t.length)return!1;let n=t.length-e.length;for(let r=0;r<e.length;r++)if(e[r]!==t[n+r])return!1;return!0}function J$(e,t){let n=$(e,t);if(!n)return[];let r=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
716
- WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:w(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:w(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(i.length>1)return i;let c=ye(r.symbol);if("kind"in c)return i;let l=c.descriptors;if(l.length<=1)return i;let u=[i[0]];for(let d=l.length-2,f=1;d>=0;d--,f++){let p=l.slice(0,d+1).map(g=>g.suffix==="method"?`${g.name}()`:g.name.replace(/\.(ts|tsx|js|jsx|mjs|cjs|py|pyi|rs|java|scala|kt|kts|rb|go|cs|vb|dart|php|c|cc|cpp|cxx|h|hpp)$/,"")).join(":");u.push({symbol:p,shortName:p,depth:f})}return u}function _d(e,t,n={}){let r=$(e,t);if(!r)return null;let i=n.semantic!==!1,o=xt(e,r,{semantic:i}).filter(a=>Z(a.symbol)).slice(0,50),s=Wr(mt(e,r,{limit:50,additive:!0,callableOnly:!0,semantic:i}));return{symbol:r.symbol,shortName:w(r.symbol),callers:o.map(a=>({symbol:a.symbol,shortName:w(a.symbol),file:a.file})),callees:s.map(a=>({symbol:a.symbol,shortName:w(a.symbol),file:a.file}))}}function pt(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function ke(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function En(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 RC(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 Fd(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 zr(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 Vr(e,t){let n=0;for(let r of e){let i=t.get(r)??0;n+=i*i}return Math.sqrt(n)}function IC(e,t,n,r={}){let i=0,o=0,s=0,a=r.medianIdf??zr(n),c=[],l=[];for(let f of e){let m=n.get(f)??0;o+=m*m,t.has(f)&&(i+=m*m,m>=a?c.push(f):l.push(f))}if(c.length===0&&l.length===0)return{similarity:0,significantShared:[],trivialShared:[]};for(let f of t){let m=n.get(f)??0;s+=m*m}let u=Math.sqrt(o)*Math.sqrt(s),d=u>0?i/u:0;return c.sort((f,m)=>(n.get(m)??0)-(n.get(f)??0)),{similarity:d,significantShared:c,trivialShared:l}}function wC(e,t,n,r){let i=0,o=r.medianIdf??zr(n),s=[],a=[];for(let u of e){if(!t.has(u))continue;let d=n.get(u)??0;i+=d*d,d>=o?s.push(u):a.push(u)}if(s.length===0&&a.length===0)return{similarity:0,significantShared:[],trivialShared:[]};let c=r.magnitudeA*r.magnitudeB,l=c>0?i/c:0;return s.sort((u,d)=>(n.get(d)??0)-(n.get(u)??0)),{similarity:l,significantShared:s,trivialShared:a}}function Ba(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=iB(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!Z(o.symbol))return[];if(o.callees.size===0)return DC(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"});let s=X$(e,o,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,i):DC(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"})}function Md(e,t,n,r={}){let i=$(e,t),o=$(e,n);if(!i||!o)return null;let s=Ba(e,i.symbol,{minSimilarity:0,limit:Number.POSITIVE_INFINITY,semantic:r.semantic,scanLimit:r.scanLimit}).find(l=>l.symbolB===o.symbol||l.symbolA===o.symbol);if(!s)return null;let a=i.endLine-i.startLine+1,c=o.endLine-o.startLine+1;return{symbolA:{symbol:i.symbol,shortName:w(i.symbol),file:i.relativePath,loc:a},symbolB:{symbol:o.symbol,shortName:w(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:Y$(s)}}function Y$(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 X$(e,t,n,r){let i=qr(e).calleeIndex({minCallees:3,scanLimit:r.scanLimit,semantic:r.semantic}),o=fB(t,i.corpus),s=lB(o,i),a=Q$(o,i),c=zr(a),l=Vr(o.callees,a),u=[];for(let d of s){if(d.callees.size<3)continue;let f=Vr(d.callees,a),m=TC(o,d,a,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0,medianIdf:c,magnitudeA:l,magnitudeB:f});m&&u.push(m)}return u.sort((d,f)=>f.similarity-d.similarity),u}function Q$(e,t){let n=new Map(t.docFreq);for(let r of e.callees)n.set(r,(n.get(r)??0)+1);return Fd(n,t.corpus.length+1)}function TC(e,t,n,r){let i=eB(e,t,n,r);if(!tB(i,r))return null;let{similarity:o,significantShared:s,trivialShared:a}=i,c=s.length>0?s:a,l=AC(c,"callees");return{symbolA:e.symbol,shortNameA:w(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:w(t.symbol),fileB:t.file,similarity:o,similarityBasis:"callees",sharedCallees:c.map(w),uniqueToA:[...ke(e.callees,t.callees)].map(w),uniqueToB:[...ke(t.callees,e.callees)].map(w),...l}}function Z$(e,t,n,r){let i=r.magnitudeA??Vr(e.callees,n),o=r.magnitudeB??Vr(t.callees,n),s=0,a=0,c=0,l=r.medianIdf??zr(n);for(let f of e.callees){if(!t.callees.has(f))continue;let m=n.get(f)??0;s+=m*m,c+=1,m>=l&&(a+=1)}if(c===0)return!1;let u=i*o;return(u>0?s/u:0)<r.minSimilarity?!1:a>=r.requireSignificantShared||c>=r.requireSharedCount}function eB(e,t,n,r){return r.magnitudeA===void 0||r.magnitudeB===void 0?IC(e.callees,t.callees,n,{medianIdf:r.medianIdf}):wC(e.callees,t.callees,n,{medianIdf:r.medianIdf,magnitudeA:r.magnitudeA,magnitudeB:r.magnitudeB})}function tB(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 mo(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=t.semantic!==!1,l=H(),u=0,d=0,f=0,m=0,p=0,g=0,h=0;return D("similar.all",()=>{let C=qr(e).calleeIndex({minCallees:o,scope:i,scanLimit:a,semantic:c}),x=C.corpus;u=x.length;let b=t.focusFiles,y=[],R=0;return D("similar.all.pair-scan",()=>{for(let v=0;v<x.length;v+=1){let E=x[v],I=b?.has(E.file)??!1,k=C.weightedMagnitudes[v],F=new Set;for(let te of E.callees){let Y=C.candidateIndexesByCallee.get(te);if(Y)for(let L of Y)L<=v||b&&!I&&!b.has(x[L].file)||F.add(L)}l&&(f+=F.size,F.size>0&&(d+=1));for(let te of F){let Y=x[te];if(s&&E.file===Y.file){l&&(p+=1);continue}if(_C(E,Y)){l&&(g+=1);continue}l&&(m+=1);let L=TC(E,Y,C.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:C.medianIdf,magnitudeA:k,magnitudeB:C.weightedMagnitudes[te]});L&&(nB(y,L,r,R),l&&(h+=1),R+=1)}}},()=>({corpusSize:u,candidateSets:d,candidatePairs:f,comparedPairs:m,crossFileSkips:p,signatureSkips:g,insertedResults:h,topResults:y.length})),D("similar.all.sort-project",()=>(y.sort((v,E)=>E.result.similarity-v.result.similarity||v.order-E.order),y.map(v=>v.result)),()=>({topResults:y.length}))},()=>({minSimilarity:n,limit:r,scope:i,minCallees:o,crossFileOnly:s,scanLimit:a,semantic:c,corpusSize:u,candidateSets:d,candidatePairs:f,comparedPairs:m,crossFileSkips:p,signatureSkips:g,insertedResults:h}))}function Od(e,t={}){let{minSimilarity:n=.5,scope:r,minCallees:i=4,crossFileOnly:o=!1,scanLimit:s}=t,a=t.semantic!==!1,c=H(),l=0,u=0,d=0,f=0,m=0,p=0,g=0;return D("similar.all-count",()=>{let S=qr(e).calleeIndex({minCallees:i,scope:r,scanLimit:s,semantic:a}),C=S.corpus;l=C.length;let x=t.focusFiles;return D("similar.all-count.pair-scan",()=>{for(let b=0;b<C.length;b+=1){let y=C[b],R=x?.has(y.file)??!1,v=S.weightedMagnitudes[b],E=new Set;for(let I of y.callees){let k=S.candidateIndexesByCallee.get(I);if(k)for(let F of k)F<=b||x&&!R&&!x.has(C[F].file)||E.add(F)}c&&(d+=E.size,E.size>0&&(u+=1));for(let I of E){let k=C[I];if(o&&y.file===k.file){c&&(m+=1);continue}if(_C(y,k)){c&&(p+=1);continue}c&&(f+=1),Z$(y,k,S.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:S.medianIdf,magnitudeA:v,magnitudeB:S.weightedMagnitudes[I]})&&(g+=1)}}},()=>({corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:f,crossFileSkips:m,signatureSkips:p,insertedResults:g})),g},()=>({minSimilarity:n,scope:r,minCallees:i,crossFileOnly:o,scanLimit:s,semantic:a,corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:f,crossFileSkips:m,signatureSkips:p,insertedResults:g}))}function _C(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 FC=re({kind:"source-fingerprints",invalidation:q("source-fingerprints"),serialize:FB,deserialize:_B});function nB(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 rB=["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 iB(e,t,n){let r=$(e,t);if(!r||!Z(r.symbol))return null;let i=new _(e),o=mt(e,r,{semantic:n.semantic});return{symbol:r.symbol,file:r.relativePath,callees:Ha(o.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}var oB=K("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),sB=K("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function LC(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:o}=t,s=t.semantic!==!1,a=oB.get(e,()=>new Map),c=`${n}|${r??""}|${o??""}|${s}`,l=!0,u=0,d=0;return D("similar.callee-fingerprints.resolve",()=>{let f=a.get(c);if(l=f!==void 0,f||(f=uB(e,{minCallees:n,scope:r,scanLimit:o,semantic:s}),a.set(c,f)),u=f.length,i===void 0)return f;let m=f.filter(p=>p.symbol!==i);return d=f.length-m.length,m},()=>({minCallees:n,scope:r,scanLimit:o,semantic:s,cacheHit:l,corpusSize:u,excludeSymbol:i!==void 0,excludedSymbols:d}))}function aB(e,t){let{minCallees:n,scope:r,scanLimit:i}=t,o=t.semantic!==!1,s=sB.get(e,()=>new Map),a=`${n}|${r??""}|${i??""}|${o}`,c=!0,l=0,u=0,d=0;return D("similar.callee-index.resolve",()=>{let f=s.get(a);return c=f!==void 0,f||(f=cB(LC(e,{minCallees:n,scope:r,scanLimit:i,semantic:o})),s.set(a,f)),l=f.corpus.length,u=f.docFreq.size,d=f.candidateIndexesByCallee.size,f},()=>({minCallees:n,scope:r,scanLimit:i,semantic:o,cacheHit:c,corpusSize:l,indexedCallees:u,candidateBuckets:d}))}function qr(e){return{calleeCorpus:t=>LC(e,t),calleeIndex:t=>aB(e,t),sourceCorpus:(t={})=>BC(e,t),sourceIndex:(t={})=>PC(e,t),sourceCandidates:(t,n)=>(n.candidateMode??"full")==="target-pruned"?RB(e,t,{minSimilarity:n.minSimilarity,scanLimit:n.scanLimit}):vB(t,PC(e,{scanLimit:n.scanLimit}))}}function cB(e){let t=H(),n=0,r=D("similar.callee-index.doc-frequency",()=>{let f=new Map;for(let m of e)for(let p of m.callees)f.set(p,(f.get(p)??0)+1);return n=f.size,f},()=>({corpusSize:e.length,uniqueCallees:n})),i=Math.max(8,Math.ceil(Math.sqrt(e.length))),o=D("similar.callee-index.idf-weights",()=>Fd(r,e.length),()=>({corpusSize:e.length,uniqueCallees:r.size})),s=D("similar.callee-index.weighted-magnitudes",()=>e.map(f=>Vr(f.callees,o)),()=>({corpusSize:e.length})),a=0,c=0,l=0,u=D("similar.callee-index.candidate-buckets",()=>{let f=new Map;for(let m=0;m<e.length;m+=1){let p=e[m];for(let g of p.callees){if((r.get(g)??0)>i){t&&(c+=1);continue}let h=f.get(g);h||(h=[],f.set(g,h)),h.push(m),t&&(a+=1)}}return t&&(l=f.size),f},()=>({corpusSize:e.length,buckets:l,candidateRefs:a,ubiquitousSkips:c,ubiquityThreshold:i})),d=D("similar.callee-index.median-idf",()=>zr(o),()=>({uniqueCallees:o.size}));return{corpus:e,candidateIndexesByCallee:u,docFreq:r,idfWeights:o,weightedMagnitudes:s,medianIdf:d,ubiquityThreshold:i}}function lB(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 uB(e,t){let{minCallees:n,scope:r,scanLimit:i,semantic:o}=t,s=H(),a=new _(e),c=0,l=D("similar.callee-fingerprints.candidates",()=>{let g=ie(a.productionCallableDefinitions({scope:r,minLoc:5,sortByLocDesc:typeof i=="number"&&i>0}),i);return c=g.length,g},()=>({scope:r,scanLimit:i,candidateCount:c})),u=0,d=D("similar.callee-fingerprints.callee-map",()=>{let g=a.calleeMap(l,{semantic:o});if(s)for(let h of g.values())u+=h.length;return g},()=>({candidateCount:c,semantic:o,calleeEdges:u})),f=0,m=0,p=0;return D("similar.callee-fingerprints.shape",()=>{let g=l.map(C=>({symbol:C.symbol,file:C.relativePath,callees:Ha((d.get(C.symbolId)??[]).map(x=>x.symbol)),paramCount:a.callableSignature(C)?.paramCount??-1})),h=dB(g);s&&(p=h.filter((C,x)=>C.callees.size!==g[x].callees.size).length);let S=h.filter(C=>C.callees.size>=n);return f=S.length,s&&(m=S.reduce((C,x)=>C+x.callees.size,0)),S},()=>({candidateCount:c,fingerprintCount:f,retainedCalleeCount:m,minCallees:n,siblingSaturatedFingerprints:p}))}var NC=5;function dB(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)>=NC);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 fB(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>=NC);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 Ha(e){return new Set([...e].filter(t=>!mB(t)))}function mB(e){return rB.some(t=>e.includes(t))}function DC(e,t,n){let r=yB(e,t);if(!r||r.tokens.size<3)return[];let i=n.minSimilarity>=.5?n.minSimilarity:.3,o=[],s=n.candidateMode??"full",a=0,c=0,l=0,u=0;return D("similar.source-shape",()=>{let f=qr(e).sourceCandidates(r,{minSimilarity:i,scanLimit:n.scanLimit,candidateMode:s});a=f.length;for(let m of f){if(m.symbol===r.symbol||m.tokens.size<3)continue;c+=1;let p=pt(r.tokens,m.tokens);if(p.size<2){l+=1;continue}let g=new Set([...r.tokens,...m.tokens]),h=g.size>0?p.size/g.size:0;if(h<i){u+=1;continue}o.push({symbolA:r.symbol,shortNameA:w(r.symbol),fileA:r.file,symbolB:m.symbol,shortNameB:w(m.symbol),fileB:m.file,similarity:h,similarityBasis:"source-tokens",sharedCallees:[...p].sort(),uniqueToA:[...ke(r.tokens,m.tokens)].sort(),uniqueToB:[...ke(m.tokens,r.tokens)].sort(),...AC([...p],"source-tokens")})}return o.sort((m,p)=>p.similarity-m.similarity||m.shortNameB.localeCompare(p.shortNameB)),o.slice(0,n.limit)},()=>({symbol:r.symbol,file:r.file,targetTokens:r.tokens.size,candidateMode:s,candidates:a,comparedPairs:c,sharedSkips:l,similaritySkips:u,results:o.length}))}function AC(e,t){let n=e.flatMap(Nd),r=e.flatMap(h=>EC(h,t)),i=Ld(n,MC),o=Ld(n,OC),s=Ld(r,Ad),a=[...new Set(r.filter(kC))],c=e.filter(h=>{let S=EC(h,t);return S.some(C=>Ad.has(C))&&S.some(kC)}).length,l=[];i.length>0&&l.push(`access/query scaffolding: ${i.slice(0,5).join(", ")}`),o.length>0&&l.push(`framework/generic scaffolding: ${o.slice(0,5).join(", ")}`),s.length>0&&l.push(`domain behavior verbs: ${s.slice(0,5).join(", ")}`),s.length>0&&a.length>0&&l.push(`domain-specific terms: ${a.slice(0,5).join(", ")}`);let u=t==="source-tokens"&&n.length>0&&n.every(h=>jC.has(h));u&&l.push("shared source tokens are generic scaffolding");let d=s.length>0&&a.length>0,f=i.length+o.length>0,m=t==="callees"&&d&&e.length>=4&&a.length>=4&&c>=2,p=m?"domain-behavior":d?f?"mixed":"domain-behavior":i.length>0?"access-query-scaffolding":o.length>0||u?"framework-scaffolding":"structural-overlap";p==="structural-overlap"&&e.length>0&&l.push(`shared ${t} overlap has no recognized domain or scaffolding category`);let g=p==="domain-behavior"&&(e.length>=3||m)?"direct":"signal";return{evidenceClass:p,actionTier:g,evidenceClassReasons:l,recommendation:pB(p,g)}}function pB(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 Ld(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function Nd(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function EC(e,t){if(t==="source-tokens")return Nd(e);let n=T(e);return Nd(n.length>0?n:gB(e))}function gB(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 kC(e){return e.length>3&&!Ad.has(e)&&!MC.has(e)&&!OC.has(e)&&!jC.has(e)&&!hB.has(e)}var Ad=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),MC=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),OC=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"]),jC=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),hB=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 yB(e,t){let n=$(e,t);if(!n||!Z(n.symbol))return null;let r=bB(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function bB(e,t){let n=T(t.symbol),r=kB(e,t.relativePath,t.startLine,t.endLine,n),i=WC(r,n);return i.size>0?i:null}var SB=K("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),CB=K("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function $C(e){return`${e.scanLimit??""}`}function BC(e,t={}){let n=SB.get(e,()=>new Map),r=$C(t),i=n.get(r);return i||(i=EB(e,t),n.set(r,i)),i}function PC(e,t={}){let n=CB.get(e,()=>new Map),r=$C(t),i=n.get(r);return i||(i=xB(BC(e,t)),n.set(r,i)),i}function xB(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 vB(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 RB(e,t,n){let r=H(),i=new _(e),o=IB(t.tokens.size,n.minSimilarity),s=0,a=0,c=0,l=D("similar.source-shape.target-files",()=>{let p=[...t.tokens],g=[];for(let h of N(e,{includeIgnored:!1})){s+=1;let S=P(e,h);S&&(a+=1,wB(S,p,o)&&g.push(h))}return c=g.length,g},()=>({symbol:t.symbol,targetTokens:t.tokens.size,requiredSharedTokens:o,scannedFiles:s,readableFiles:a,candidateFiles:c})),u=0,d=D("similar.source-shape.target-definitions",()=>{let p=ie(i.productionCallableDefinitions({files:l,sortByLocDesc:typeof n.scanLimit=="number"&&n.scanLimit>0}),n.scanLimit);return u=p.length,p},()=>({symbol:t.symbol,candidateFiles:c,scanLimit:n.scanLimit,definitionCount:u})),f=0;return D("similar.source-shape.target-fingerprints",()=>{let p=HC(e,d);return r&&(f=p.length),p},()=>({symbol:t.symbol,definitionCount:u,fingerprintCount:f})).filter(p=>p.symbol!==t.symbol)}function IB(e,t){return Math.max(2,Math.ceil(e*t))}function wB(e,t,n){if(t.length<n)return!1;let r=e.toLowerCase(),i=0;for(let o of t)if(DB(r,o)&&(i+=1,i>=n))return!0;return!1}function DB(e,t){return t==="num"?/\b\d+\b/.test(e):e.includes(t)}function EB(e,t={}){let n=new _(e),{scanLimit:r}=t,i=ie(n.productionCallableDefinitions({sortByLocDesc:typeof r=="number"&&r>0}),r);return HC(e,i)}function HC(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=P(e,i);if(!s)continue;let a=ae(e,i,s),c=TB(e,i,a),l=!1,u=null;for(let d of o){let f=PB(d),m=c.get(f),p=m?new Set(m.tokens):null;p||(u??=Ce(e,i),p=WC(UC(u,d.startLine,d.endLine,d.leaf),d.leaf),c.set(f,{key:f,symbol:d.symbol,startLine:d.startLine,endLine:d.endLine,leaf:d.leaf,tokens:[...p].sort()}),l=!0),p.size>0&&r.set(d.symbol,{symbol:d.symbol,file:d.relativePath,tokens:p})}l&&LB(e,i,a,c)}return t.map(i=>r.get(i.symbol)).filter(i=>!!i)}function kB(e,t,n,r,i){let o=Ce(e,t);return o.length===0?"":UC(o,n,r,i)}function UC(e,t,n,r){if(n>=t&&n-t<=12)return e.slice(t,n+1).join(`
717
- `);let i=[new RegExp(`\\bdef\\s+${B(r)}\\b`),new RegExp(`\\bfun\\s+${B(r)}\\b`),new RegExp(`\\bfn\\s+${B(r)}\\b`),new RegExp(`\\bfunction\\s+${B(r)}\\b`),new RegExp(`\\b${B(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&&AB(c)||(s=a,c.trim()===""&&a>o+1))break}return e.slice(o,s+1).join(`
718
- `)}return e.slice(t,Math.min(e.length,t+8)).join(`
719
- `)}function PB(e){return`${e.symbol}\0${e.startLine}\0${e.endLine}\0${e.leaf}`}function TB(e,t,n){return FC.read(e,t,n)??new Map}function _B(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 FB(e){let t={entries:[...e.values()].sort((n,r)=>n.key.localeCompare(r.key))};return JSON.stringify(t)}function LB(e,t,n,r){FC.write(e,t,n,new Map(r))}function WC(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=NB(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 NB(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 AB(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function Ft(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 Lt(e){let t=GC(e.profile?.name),n=()=>{let r=[];t=GC(e.profile?.name,e);let i=(s,a)=>{let c=e.profiles[s],l=e.profiles[a];t.candidatePairs+=1,t.comparedPairs+=1;let u=e.compare(c,l);u&&r.push(u)};if(e.filePattern){let s=e.profiles.findIndex(a=>a.file.includes(e.filePattern));if(s>=0){let a=e.profiles[s];for(let c of MB(e,s)){let l=e.profiles[c];e.focusFiles&&!e.focusFiles.has(a.file)&&!e.focusFiles.has(l.file)||i(s,c)}}}else if(e.focusFiles?.size!==0){let s=typeof e.overrunFactor=="number"&&Number.isFinite(e.limit)?e.limit*e.overrunFactor:Number.POSITIVE_INFINITY;for(let a=0;a<e.profiles.length;a+=1){let c=e.profiles[a],l=e.focusFiles?.has(c.file)??!1;for(let u of OB(e,a))e.focusFiles&&!l&&!e.focusFiles.has(e.profiles[u].file)||i(a,u);if(r.length>s){t.overrunApplied=!0;break}}}r.sort(e.sort??((s,a)=>a.similarity-s.similarity)),t.matchedResults=r.length;let o=r.slice(0,e.limit);return t.emittedResults=o.length,e.onProfile?.({...t}),o};return e.profile?D(`pairwise-profile:${e.profile.name}`,n,()=>({...jB(e.profile?.metadata),...t})):n()}function MB(e,t){if(e.candidateIndex)return zC(e,t,-1);let n=[];for(let r=0;r<e.profiles.length;r+=1)r!==t&&n.push(r);return n}function OB(e,t){if(e.candidateIndex)return zC(e,t,t);let n=[];for(let r=t+1;r<e.profiles.length;r+=1)n.push(r);return n}function zC(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 GC(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 jB(e){return typeof e=="function"?e():e??{}}function $B(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=BB(e,{scope:i,minDeps:s}),l=Ft(a,u=>u.deps);return Lt({profiles:a,limit:r,filePattern:o,overrunFactor:5,candidateIndex:l,profile:{name:"similar-files"},compare:(u,d)=>UB(u,d,n,c)})}function BB(e,t){let{scope:n,minDeps:r}=t,i=se(e,n),{universalDeps:o,distinctiveDeps:s}=HB(i),a=[];for(let[c,l]of i)l.size>=r&&a.push({file:c,deps:new Set([...l].filter(u=>!o.has(u)))});return{profiles:a,distinctiveDeps:s}}function HB(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 UB(e,t,n,r){let i=new Set;for(let l of e.deps)t.deps.has(l)&&i.add(l);if(i.size<3||e.deps.size<4||t.deps.size<4)return null;let o=0;for(let l of i)r.has(l)&&o++;if(o<2)return null;let s=En(e.deps,t.deps);if(s<n)return null;let a=[];for(let l of e.deps)t.deps.has(l)||a.push(l);let c=[];for(let l of t.deps)e.deps.has(l)||c.push(l);return{fileA:e.file,fileB:t.file,similarity:s,sharedDeps:[...i],uniqueToA:a,uniqueToB:c}}function kn(e){let t=[],n=[],r=[];for(let l of e.primitiveGroups)l.values.length!==0&&VC(l.bucket,n,r).push(`${l.reasonPrefix}: ${l.values.join(", ")}`);for(let l of e.nameGroups)WB(l.names,l.label,e.genericWords,e.stripPrefixes??[],t,VC(l.fallbackBucket,n,r));let i=t.length>0,o=n.length>0,s=r.length>0,a=i?o||s?"mixed":"domain-behavior":s?"shared-abstraction":"generic-workflow-scaffolding";return{actionTier:a==="domain-behavior"||a==="mixed"?"signal":"support",evidenceClass:a,reasons:[...t,...r,...n].slice(0,6),recommendation:e.recommendation(a)}}function Ua(e,t){if(e.size===0||t.size===0)return 0;let i=pt(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(En(e,t),i)}function Pn(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 Wa(e,t,n){let r=t.map(c=>{let l=c.value(e),u=c.weightedValue?c.weightedValue(e,l):l;return{axis:c,value:l,weighted:u,qualifies:c.qualifies?c.qualifies(e,l):l>0}}),i=r.filter(c=>c.qualifies&&c.axis.reason).map(c=>c.axis.reason(e,c.value)),o=r.filter(c=>c.qualifies&&c.axis.dominantEligible!==!1).sort((c,l)=>l.weighted-c.weighted)[0],s=o&&o.weighted>0?o.axis.axis:n,a=[...new Set(r.filter(c=>c.qualifies).map(c=>c.axis.axis).concat(i.length>0?[]:[s]))];return{dominantPressure:s,pressureKinds:a,reasons:i}}function z(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function Le(e){return[...e].sort()}function WB(e,t,n,r,i,o){let s=[],a=[];for(let c of e)GB(c,r).filter(u=>!n.has(u)).length>0?s.push(c):a.push(c);s.length&&i.push(`${t} has domain term(s): ${s.slice(0,6).join(", ")}`),a.length&&o.push(`${t} is generic workflow: ${a.slice(0,6).join(", ")}`)}function GB(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 VC(e,t,n){return e==="generic"?t:n}function po(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=st(e).reactProfiles({scope:o,minJsxTokens:r,scanLimit:s}).filter(d=>d.kind==="component").map(d=>({file:d.file,component:d.name,tokens:d.jsxTokens,profile:d})),u=Ft(l,d=>d.tokens);return Lt({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-component-duplicates"},compare:(d,f)=>zB(d,f,n),sort:(d,f)=>f.similarity-d.similarity||d.fileA.localeCompare(f.fileA)||d.componentA.localeCompare(f.componentA)||d.fileB.localeCompare(f.fileB)||d.componentB.localeCompare(f.componentB)})}function zB(e,t,n){let r=pt(e.tokens,t.tokens);if(r.size<6||!VB(r))return null;let i=En(e.tokens,t.tokens);if(i<n)return null;let o=z(r,"component:"),s=z(r,"native:"),a=z(r,"prop:"),c=z(r,"event:"),l=z(r,"binding:"),u=qB({sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:c,sharedBindings:l});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:i,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:Le(r),sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:c,sharedBindings:l,evidenceClass:u.evidenceClass,actionTier:u.actionTier,evidenceClassReasons:u.reasons,recommendation:u.recommendation,uniqueToA:Le(ke(e.tokens,t.tokens)).slice(0,25),uniqueToB:Le(ke(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function VB(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 Pn([{name:"component",count:t},{name:"shape",count:n}],[{min:{component:1},reason:"shared custom component"},{min:{shape:4},reason:"shared JSX structure"}]).pass}function qB(e){return kn({genericWords:JB,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:KB})}function KB(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 JB=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 go(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=st(e).reactProfiles({scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(d=>({file:d.file,component:d.name,tokens:d.behaviorTokens,profile:d})),u=Ft(l,d=>d.tokens);return Lt({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-hook-candidates"},compare:(d,f)=>YB(d,f,n,r),sort:(d,f)=>f.similarity-d.similarity||d.fileA.localeCompare(f.fileA)||d.componentA.localeCompare(f.componentA)||d.fileB.localeCompare(f.fileB)||d.componentB.localeCompare(f.componentB)})}function YB(e,t,n,r){let i=pt(e.tokens,t.tokens);if(i.size<r||!ZB(i))return null;let o=Ua(e.tokens,t.tokens);if(o<n)return null;let s=z(i,"hook:"),a=z(i,"react-hook:"),c=z(i,"effect:"),l=z(i,"state:"),u=z(i,"request:"),d=z(i,"handler:"),f=z(i,"handler-verb:"),m=XB({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:f});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:o,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:Le(i),sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:f,evidenceClass:m.evidenceClass,actionTier:m.actionTier,evidenceClassReasons:m.reasons,recommendation:m.recommendation,uniqueToA:Le(ke(e.tokens,t.tokens)).slice(0,25),uniqueToB:Le(ke(t.tokens,e.tokens)).slice(0,25),reason:e1({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:f}),locA:e.profile.loc,locB:t.profile.loc}}function XB(e){return kn({genericWords:t1,stripPrefixes:n1,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:QB})}function QB(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 ZB(e){let t=0,n=0,r=0,i=0,o=0,s=0,a=0;for(let u of e)u.startsWith("hook:")?t+=1:u.startsWith("react-hook:")?n+=1:u.startsWith("effect:")?r+=1:u.startsWith("request:")?i+=1:u.startsWith("handler:")||u.startsWith("handler-verb:")?o+=1:u.startsWith("state:")?s+=1:u.startsWith("state-hook:")&&(a+=1);let c=s+a,l=t+n+r+i+o+c;return Pn([{name:"requests",count:i},{name:"customHooks",count:t},{name:"namedStates",count:s},{name:"handlers",count:o},{name:"effects",count:r},{name:"reactHooks",count:n},{name:"namedBehavior",count:l}],[{min:{requests:1,namedBehavior:4},reason:"shared request workflow"},{min:{customHooks:1,requests:1,namedBehavior:5},reason:"shared custom hook and request workflow"},{min:{customHooks:1,namedStates:1,namedBehavior:5},reason:"shared custom hook and state"},{min:{customHooks:1,handlers:2,namedBehavior:5},reason:"shared custom hook and handlers"},{min:{namedStates:1,handlers:2,effects:1,namedBehavior:5},reason:"shared stateful effects"},{min:{namedStates:1,handlers:2,reactHooks:2,namedBehavior:5},reason:"shared stateful React primitives"}]).pass}function e1(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 t1=new Set(["add","apply","async","callback","cancel","change","clear","close","create","data","delete","draft","edit","effect","error","fetch","filter","form","handle","has","is","item","items","load","loader","loading","memo","name","open","reducer","refresh","ref","remove","request","reset","resource","row","rows","save","saving","search","select","selected","state","store","submit","toggle","update","use","value"]),n1=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function jd(e,t={}){let{minComponentLines:n=300,minFileLines:r=800,minJsxTokens:i=80,minBehaviorTokens:o=40,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return st(e).reactProfiles({scope:a,scanLimit:c}).filter(d=>d.kind==="component").filter(d=>!l||d.file.includes(l)||d.name.includes(l)).map(d=>r1(d,{minComponentLines:n,minFileLines:r,minJsxTokens:i,minBehaviorTokens:o})).filter(d=>d!==null).sort((d,f)=>f.componentLines-d.componentLines||f.fileLines-d.fileLines||d.file.localeCompare(f.file)).slice(0,s)}function r1(e,t){let n=Math.max(80,Math.floor(t.minComponentLines/2)),r=Wa(e,i1({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=o1(e),c=s1(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:a1(c,a),reasons:i,loc:e.loc}}function i1(e){return[{axis:"component",value:t=>t.loc,qualifies:(t,n)=>n>=e.minComponentLines,reason:(t,n)=>`${n} component line(s)`},{axis:"file",value:t=>t.fileLines,qualifies:(t,n)=>n>=e.minFileLines&&t.loc>=e.substantialComponentLines,reason:(t,n)=>`${n} file line(s)`},{axis:"jsx-structure",value:t=>t.jsxTokens.size,weightedValue:(t,n)=>n*3,qualifies:(t,n)=>n>=e.minJsxTokens,reason:(t,n)=>`${n} JSX structure token(s)`},{axis:"hook-behavior",value:t=>t.behaviorTokens.size,weightedValue:(t,n)=>n*4,qualifies:(t,n)=>n>=e.minBehaviorTokens,reason:(t,n)=>`${n} behavior token(s)`}]}function o1(e){let t=e.file.split(/[\\/]+/).filter(Boolean),n=t.slice(0,-1).map(f=>f.toLowerCase()),r=(t.at(-1)??e.name).replace(/\.[^.]+$/,""),o=n.findIndex(f=>l1.has(f))>=0,s=n.some(f=>c1.has(f));if(qC(r)||qC(e.name))return"component";let c=u1.has(r.toLowerCase()),l=/(?:Page|Route|Screen)$/.test(e.name),u=o&&/View$/.test(e.name),d=!s&&r.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()===e.name.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()&&/(?:Page|Route|Screen|View)$/.test(r);return c||l||u||d?"route-page":"component"}function qC(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&KC.has(t.at(-1))?!0:[...KC].some(n=>e.endsWith(d1(n)))}function s1(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 a1(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 c1=new Set(["component","components","panel","panels","partial","partials"]),KC=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"]),l1=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),u1=new Set(["page","route","screen"]);function d1(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ho(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=f1(e,{scope:o,minTokens:r,scanLimit:s}),u=Ft(l,d=>d.tokens);return Lt({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-component-duplicates"},compare:(d,f)=>p1(d,f,n),sort:(d,f)=>f.similarity-d.similarity||d.fileA.localeCompare(f.fileA)||d.fileB.localeCompare(f.fileB)})}function f1(e,t){return st(e).vueProfiles({scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:m1(n)}))}function m1(e){return e.totalLines}function p1(e,t,n){let r=pt(e.tokens,t.tokens);if(r.size<6||!g1(r))return null;let i=En(e.tokens,t.tokens);if(i<n)return null;let o=z(r,"component:"),s=z(r,"prop:"),a=z(r,"event:"),c=z(r,"directive:"),l=z(r,"slot:"),u=z(r,"id:"),d=h1({sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:c,sharedSlots:l,sharedIdentifiers:u});return{fileA:e.file,fileB:t.file,similarity:i,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:Le(r),sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:c,sharedSlots:l,sharedIdentifiers:u,evidenceClass:d.evidenceClass,actionTier:d.actionTier,evidenceClassReasons:d.reasons,recommendation:d.recommendation,uniqueToA:Le(ke(e.tokens,t.tokens)).slice(0,25),uniqueToB:Le(ke(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function g1(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 Pn([{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 h1(e){return kn({genericWords:b1,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:y1})}function y1(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 b1=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 yo(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=st(e).vueProfiles({scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(d=>({file:d.file,tokens:d.behaviorTokens,profile:d})),u=Ft(l,d=>d.tokens);return Lt({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-composable-candidates"},compare:(d,f)=>S1(d,f,n,r),sort:(d,f)=>f.similarity-d.similarity||d.fileA.localeCompare(f.fileA)||d.fileB.localeCompare(f.fileB)})}function S1(e,t,n,r){let i=pt(e.tokens,t.tokens);if(i.size<r||!v1(i))return null;let o=Ua(e.tokens,t.tokens);if(o<n)return null;let s=z(i,"composable:"),a=z(i,"store:"),c=z(i,"reactivity:"),l=z(i,"lifecycle:"),u=z(i,"request:"),d=z(i,"function:"),f=z(i,"function-verb:"),m=z(i,"template-binding:"),p=z(i,"template-event:"),g=C1({sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:f,sharedBindings:m,sharedTemplateEvents:p});return{fileA:e.file,fileB:t.file,similarity:o,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:Le(i),sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:f,sharedBindings:m,sharedTemplateEvents:p,evidenceClass:g.evidenceClass,actionTier:g.actionTier,evidenceClassReasons:g.reasons,recommendation:g.recommendation,uniqueToA:Le(ke(e.tokens,t.tokens)).slice(0,25),uniqueToB:Le(ke(t.tokens,e.tokens)).slice(0,25),reason:R1({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:l,sharedFunctions:d,sharedFunctionVerbs:f,sharedBindings:m}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function C1(e){return kn({genericWords:I1,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:x1})}function x1(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 v1(e){let t=0,n=0,r=0,i=0,o=0,s=0,a=0;for(let u of e)u.startsWith("composable:")?t+=1:u.startsWith("store:")?n+=1:u.startsWith("request:")?r+=1:u.startsWith("lifecycle:")?i+=1:u.startsWith("function:")?o+=1:u.startsWith("reactivity:")?s+=1:(u.startsWith("function-verb:")||u.startsWith("template-binding:")||u.startsWith("template-event:"))&&(a+=1);let c=t+n,l=c+r+i+o+a;return Pn([{name:"requests",count:r},{name:"lifecycle",count:i},{name:"functions",count:o},{name:"reusableHooks",count:c},{name:"reactivity",count:s},{name:"namedBehavior",count:l}],[{min:{requests:1,namedBehavior:4},reason:"shared request workflow"},{min:{lifecycle:1,functions:2,namedBehavior:4},reason:"shared lifecycle workflow"},{min:{reusableHooks:2,requests:1,namedBehavior:5},reason:"shared reusable Vue hooks and requests"},{min:{reusableHooks:2,functions:2,namedBehavior:5},reason:"shared reusable Vue hooks and functions"},{min:{functions:2,reactivity:1,namedBehavior:4},reason:"shared reactive functions"}]).pass}function R1(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 I1=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 $d(e,t={}){let{minTotalLines:n=800,minTemplateLines:r=300,minScriptLines:i=300,minStyleLines:o=500,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return st(e).vueProfiles({scope:a,scanLimit:c}).filter(d=>!l||d.file.includes(l)).map(d=>w1(d,{minTotalLines:n,minTemplateLines:r,minScriptLines:i,minStyleLines:o})).filter(d=>d!==null).sort((d,f)=>f.totalLines-d.totalLines||d.file.localeCompare(f.file)).slice(0,s)}function w1(e,t){let n=Wa(e,D1(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=E1(e.file),a=k1(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:P1(a,s),reasons:r,loc:c}}function D1(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 E1(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(r=>T1.has(r))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function k1(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 P1(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 T1=new Set(["landing","page","pages","route","routes","view","views"]);function _1(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:o=3,maxChainLength:s=8}=t,a=se(e,i),c=$1(a,o,s);if(c.length===0)return[];let l=F1(c);return l.length<2?[]:j1(A1(l,n,r),r)}function F1(e){let t=L1(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 L1(e){let{nodeFreq:t,tailFreq:n}=N1(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 N1(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 A1(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let o=i+1;o<e.length;o++){let s=M1(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 M1(e,t,n){if(!O1(e.filtered,t.filtered))return null;let{distance:r,ops:i}=B1(e.filtered,t.filtered),o=Math.max(e.filtered.length,t.filtered.length);if(o===0)return null;let s=1-r/o;if(s<n||r===0)return null;let a=i.filter(l=>l.type==="substitute").map(l=>({index:l.indexA,nodeA:e.filtered[l.indexA],nodeB:t.filtered[l.indexB]}));return a.length===0||i.filter(l=>l.type==="match").length<2?null:{chainA:e.original,chainB:t.original,similarity:s,editDistance:r,divergencePoints:a,commonPrefix:H1(e.original,t.original),commonSuffix:U1(e.original,t.original)}}function O1(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function j1(e,t){let n=[];for(let r of e)if(n.some(o=>JC(r.chainA,o.chainA)&&JC(r.chainB,o.chainB))||n.push(r),n.length>=t)break;return n}function $1(e,t,n){let r=[];for(let o of e.keys()){if(r.length>=500)break;YC(e,o,[o],new Set([o]),t,n,r,500)}return r}function YC(e,t,n,r,i,o,s,a){if(s.length>=a)return;if(n.length>=o){n.length>=i&&s.push([...n]);return}let c=e.get(t);if(!c||c.size===0){n.length>=i&&s.push([...n]);return}let l=!1;for(let u of c)if(!r.has(u)&&(r.add(u),n.push(u),YC(e,u,n,r,i,o,s,a),n.pop(),r.delete(u),l=!0,s.length>=a))return;!l&&n.length>=i&&s.push([...n])}function B1(e,t){let n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let c=0;c<=n;c++)i[c][0]=c;for(let c=0;c<=r;c++)i[0][c]=c;for(let c=1;c<=n;c++)for(let l=1;l<=r;l++)e[c-1]===t[l-1]?i[c][l]=i[c-1][l-1]:i[c][l]=1+Math.min(i[c-1][l],i[c][l-1],i[c-1][l-1]);let o=[],s=n,a=r;for(;s>0||a>0;)s>0&&a>0&&e[s-1]===t[a-1]?(o.unshift({type:"match",indexA:s-1,indexB:a-1}),s--,a--):s>0&&a>0&&i[s][a]===i[s-1][a-1]+1?(o.unshift({type:"substitute",indexA:s-1,indexB:a-1}),s--,a--):a>0&&i[s][a]===i[s][a-1]+1?(o.unshift({type:"insert",indexA:s,indexB:a-1}),a--):(o.unshift({type:"delete",indexA:s-1,indexB:a}),s--);return{distance:i[n][r],ops:o}}function H1(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 U1(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 JC(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),r=e.join("\u2192");return n.includes(r)}function gt(e){let t=W1(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=ie(o,e.scanLimit);t={pipeline:e.profile?.name,loadedCandidates:r.length,filteredCandidates:i.length,scannedCandidates:s.length,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:s.length<i.length,resultLimitApplied:!1};let a=e.prepare?.(s)??void 0,c=[];for(let u of s){t.evaluatedCandidates+=1;let d=e.evaluate(u,a);d&&c.push(d)}t.matchedResults=c.length,e.orderResults&&c.sort(e.orderResults);let l=typeof e.limit=="number"?c.slice(0,e.limit):c;return t.emittedResults=l.length,t.resultLimitApplied=l.length<c.length,e.onProfile?.({...t}),l};return e.profile?D(`candidate-pipeline:${e.profile.name}`,n,()=>({...G1(e.profile?.metadata),...t})):n()}function W1(e){return{pipeline:e,loadedCandidates:0,filteredCandidates:0,scannedCandidates:0,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:!1,resultLimitApplied:!1}}function G1(e){return typeof e=="function"?e():e??{}}function bo(e,t={}){let{scope:n,minLoc:r=10,minCallees:i=6,limit:o=20,scanLimit:s}=t,a=new _(e);return gt({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:r,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:s,profile:{name:"extract-candidates"},prepare:c=>a.calleeMap(c,{semantic:t.semantic!==!1}),evaluate:(c,l)=>z1(c,l.get(c.symbolId)??[],i),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function z1(e,t,n){let r=new Set(t.map(l=>l.symbol));if(r.size<n)return null;let i=Y1(r,t),o=X1(r,i);if(o.length<2)return null;let s=Q1(o,i);if(s.length===0)return null;let a=w(e.symbol),c=V1(a,r.size,o.length,s);return{symbol:e.symbol,shortName:a,relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:O(e),totalCallees:r.size,extractionKind:c.extractionKind,actionTier:"signal",evidenceReasons:c.evidenceReasons,recommendation:c.recommendation,clusters:s}}function V1(e,t,n,r){let i=Math.max(...r.map(c=>c.callees.length)),o=Math.max(...r.map(c=>c.isolation)),s=[`${t} distinct callees across ${n} co-occurrence cluster(s)`,`${r.length} extractable cluster(s) passed size and isolation thresholds`,`largest extractable cluster has ${i} callees at ${Math.round(o*100)}% isolation`],a=q1(e,t,n);return a!==null?{extractionKind:"workflow-orchestration",evidenceReasons:[...s,a],recommendation:"Review the isolated helper group as a possible private or feature-local helper, but keep the orchestration sequence together when it preserves the workflow."}:i>=6?{extractionKind:"broad-helper-cluster",evidenceReasons:[...s,"one isolated helper group is broad enough to deserve a named review"],recommendation:"Review whether the broad helper cluster has a stable concept name before extracting it; avoid creating a bag-of-helpers abstraction."}:{extractionKind:"cohesive-helper-cluster",evidenceReasons:s,recommendation:"Review the isolated callee group as a possible same-file or feature-local helper; extract only if the new name preserves the current behavior."}}function q1(e,t,n){if(t>=10)return`callee breadth suggests orchestration: ${t} callees`;if(n>=4)return`multiple disconnected callee groups suggest orchestration: ${n} groups`;let r=K1(e);return J1.has(r)?`caller verb suggests orchestration: ${r}`:null}function K1(e){return e.split(":").pop()?.replace(/\(\)$/,"").replace(/[^A-Za-z0-9_]/g,"").replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\s-]+/).filter(Boolean)[0]?.toLowerCase()??""}var J1=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function Y1(e,t){let n=new Map;for(let i of e)n.set(i,new Set);let r=new Map;for(let i of t){let o=r.get(i.chunkId);o||(o=new Set,r.set(i.chunkId,o)),o.add(i.symbol)}for(let i of r.values()){let o=[...i];for(let s=0;s<o.length;s++)for(let a=s+1;a<o.length;a++)n.get(o[s]).add(o[a]),n.get(o[a]).add(o[s])}return n}function X1(e,t){let n=new Set,r=[];for(let i of e){if(n.has(i))continue;let o=new Set,s=[i];for(;s.length>0;){let a=s.pop();if(!n.has(a)){n.add(a),o.add(a);for(let c of t.get(a)??[])n.has(c)||s.push(c)}}r.push(o)}return r}function Q1(e,t){return e.filter(n=>n.size>=3).map(n=>Z1(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function Z1(e,t,n){let r=new Set;for(let a of t)if(a!==e)for(let c of a)r.add(c);let i=0;for(let a of e)for(let c of n.get(a)??[])r.has(c)&&i++;let o=e.size*r.size,s=o>0?1-i/o:1;return{callees:[...e].map(w),isolation:s}}import{posix as Kr}from"path";import{spawnSync as eH}from"child_process";import{createHash as tH}from"crypto";import{existsSync as nH}from"fs";import{dirname as XC,join as rH}from"path";import{fileURLToPath as iH}from"url";var ex=j("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]}),QC=re({kind:"consumer-file-usage",invalidation:q("consumer-file-usage"),serialize:pH,deserialize:gH});function Zt(e,t){return{forDefinitions(n,r){return oH(e,t,n,r)}}}function en(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 za(e,t,n){return nx(e,t,n).partition}function oH(e,t,n,r){let i=tx(n.length),o=H()?Te(e):null,s=o?sH(n,r,o):void 0,a=s?{workIdentity:s,workOutcome:"computed"}:{};return D("consumer-evidence.product",()=>{let c=D("consumer-evidence.provenance",()=>aH(e,t,n,r),()=>({...a,definitions:n.length,semantic:r.semantic,sourceFallback:r.sourceFallback!==!1})),l=new Map;i={...i,...c.counters};let u=cH(n,c.sources);return D("consumer-evidence.classify",()=>{let d=lH(e,n,c.sources,u);for(let f of n){let m=d.get(f.symbolId)??dH();i.realFiles+=m.partition.realConsumers.length,i.reexportOnlyFiles+=m.partition.barrelConsumers,i.importOnlyFiles+=m.partition.importOnlyConsumers,l.set(f.symbolId,{definition:f,files:m.files,...m.partition})}},()=>({...a,...u,realFiles:i.realFiles,reexportOnlyFiles:i.reexportOnlyFiles,importOnlyFiles:i.importOnlyFiles})),l},()=>({...a,...i}))}function sH(e,t,n){let r=tH("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 tx(e){return{definitions:e,indexedFiles:0,semanticFiles:0,fallbackFiles:0,totalFiles:0,realFiles:0,reexportOnlyFiles:0,importOnlyFiles:0}}function aH(e,t,n,r){let i=tx(n.length),o=new Map;return Bd(o,i,"indexed",t.crossFileCallerMap(n,{semantic:!1})),r.semantic&&Bd(o,i,"semantic",vn(e,n)),r.sourceFallback!==!1&&Bd(o,i,"source-fallback",t.sourceFallbackCallerFiles(n)),i.totalFiles=[...o.values()].reduce((s,a)=>s+a.size,0),{sources:o,counters:i}}function cH(e,t){return{definitions:e.length,consumerFiles:[...t.values()].reduce((n,r)=>n+r.size,0),nativeAttempted:!1,nativeUsed:!1,nativeReason:"not-attempted"}}function Bd(e,t,n,r){let i=0;for(let[o,s]of r){let a=e.get(o);a||(a=new Map,e.set(o,a));for(let c of s){i++;let l=a.get(c)??new Set;l.add(n),a.set(c,l)}}n==="indexed"?t.indexedFiles+=i:n==="semantic"?t.semanticFiles+=i:t.fallbackFiles+=i}function lH(e,t,n,r){let i=vH(e,t,n,r);return i||uH(e,t,n)}function uH(e,t,n){let r=new Map;for(let i of t){let o=n.get(i.symbolId)??new Map;r.set(i.symbolId,nx(e,i,[...o.keys()],o))}return r}function nx(e,t,n,r=new Map){let i=[],o=0,s=0,a=T(t.symbol),c=[];for(let l of n){let u;hH(e,l,t.relativePath,a)?(o++,u="reexport-only"):Hd(e,l,a)?(s++,u="import-only"):(i.push(l),u="real"),c.push({file:l,sources:[...r.get(l)??[]],classification:u})}return{partition:{realConsumers:i,barrelConsumers:o,importOnlyConsumers:s},files:c}}function dH(){return{partition:{realConsumers:[],barrelConsumers:0,importOnlyConsumers:0},files:[]}}function Hd(e,t,n){if(!n)return!1;let r=M(t);if(!r)return!1;let i=ex.get(e,t,()=>rx(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function rx(e,t,n){let r=dt(e).forFile(t,{text:!0,ast:!0}),i=r.text;if(!i)return mH();let o=ae(e,t,i),s=QC.read(e,t,o);if(s)return s;let a=fH(r.ast,n);return QC.write(e,t,o,a),a}function fH(e,t){let n=new Set,r=new Set;if(!e)return{importedLeaves:n,usedLeaves:r};let i=t==="rust"?new Set(["use_declaration"]):t==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),o=(s,a)=>{let c=a||i.has(s.type);(s.type==="identifier"||s.type==="type_identifier"||s.type==="property_identifier"||s.type==="field_identifier")&&(c?n.add(s.text):r.add(s.text));for(let l of s.children)o(l,c)};return o(e.rootNode,!1),{importedLeaves:n,usedLeaves:r}}function mH(){return{importedLeaves:new Set,usedLeaves:new Set}}function pH(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function gH(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 hH(e,t,n,r){if(!r)return!1;let i=dt(e).forFile(t,{lines:!0,reexports:!0}),o=i.lines??[];if(o.length===0)return!1;let s=i.reexports??[];return ix(o,s,r)}function ix(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 yH="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY",bH="SCIP_QUERY_NATIVE_KERNELS_BIN",SH="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY_MIN_FILES",ZC=1e3,CH=5e3,xH=64*1024*1024,Ga;function vH(e,t,n,r){let i=process.env[yH]?.toLowerCase();if(i!=="1"&&i!=="true")return r.nativeReason=i==="0"||i==="false"?"disabled":"opt-in-required",null;if(r.consumerFiles<PH())return r.nativeReason="below-threshold",null;let o=TH();if(!o)return r.nativeReason="binary-missing",null;r.nativeAttempted=!0;let s=RH(e,t,n),a=eH(o,["consumer-classify"],{input:JSON.stringify(s),encoding:"utf8",timeout:CH,maxBuffer:xH});if(a.status!==0||a.error)return r.nativeReason=a.error?`spawn-error:${a.error.message}`:`exit-${a.status??"null"}`,null;try{let c=JSON.parse(a.stdout),l=wH(c,t);return l?(r.nativeUsed=!0,r.nativeReason="used",l):(r.nativeReason="invalid-response",null)}catch{return r.nativeReason="invalid-json",null}}function RH(e,t,n){let r=new Map,i=[];for(let a of t){let c=T(a.symbol),u=[...(n.get(a.symbolId)??new Map).entries()].map(([d,f])=>{let m=r.get(d)??new Set;return c&&m.add(c),r.set(d,m),{file:d,sources:[...f]}});i.push({symbol_id:a.symbolId,leaf:c,consumer_files:u})}let o={},s={};for(let[a,c]of r){let l=M(a);if(l){let d=ex.get(e,a,()=>rx(e,a,l));o[a]={imported_leaves:[...d.importedLeaves],used_leaves:[...d.usedLeaves]}}let u=IH(e,a,c);u.length>0&&(s[a]=u)}return{definitions:i,file_usages:o,reexport_only_leaves:s}}function IH(e,t,n){if(n.size===0)return[];let r=dt(e).forFile(t,{lines:!0,reexports:!0}),i=r.lines??[],o=r.reexports??[];return i.length===0||o.length===0?[]:[...n].filter(s=>ix(i,o,s))}function wH(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=DH(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 DH(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(EH)||!kH(i.classification))return null;n.push({file:i.file,sources:i.sources,classification:i.classification})}return{symbol_id:t.symbol_id,real_consumers:t.real_consumers,barrel_consumers:t.barrel_consumers,import_only_consumers:t.import_only_consumers,files:n}}function EH(e){return e==="indexed"||e==="semantic"||e==="source-fallback"}function kH(e){return e==="real"||e==="reexport-only"||e==="import-only"}function PH(){let e=process.env[SH];if(!e)return ZC;let t=Number(e);return Number.isFinite(t)&&t>=0?t:ZC}function TH(){if(Ga!==void 0)return Ga;let e=process.env[bH],t=process.platform==="win32"?"scip-query-kernels.exe":"scip-query-kernels";return Ga=[...e?[e]:[],..._H().map(r=>rH(r,"target","release",t))].find(r=>nH(r))??null,Ga}function _H(){let e=new Set,t=XC(iH(import.meta.url));for(let n=0;n<5;n++)e.add(t),t=XC(t);return[...e]}var FH=20,LH=1,NH=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"]]),AH=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),MH=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 OH(e,t={}){let n=Gd(t.limit,FH),r=Gd(t.minConsumers,LH),i=new _(e),o=i.fileDependencyGraph(t.scope),s=rU(N(e,{includeIgnored:!1})),a=sU(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?jH(e,i,t.target):$H(e,t.scope,t.scanLimit)).map(u=>BH(e,i,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=r||t.target).sort(nU).slice(0,n)}function jH(e,t,n){let r=WH(e,n);if(r)return[lx(r)];let i=$(e,n);if(!i)return[];let o=t.definitionsForFile(i.relativePath).find(s=>s.symbolId===i.symbolId);return o?[GH(o)]:[{unit:{kind:"symbol",file:i.relativePath,shortName:w(i.symbol),symbol:i.symbol,startLine:i.startLine,endLine:i.endLine}}]}function $H(e,t,n){let r=N(e,{scope:t,includeIgnored:!1}),i=Gd(n,r.length);return r.slice(0,i).map(o=>lx(o))}function BH(e,t,n,r,i,o,s){let a=r.definition?HH(e,t,r.definition,i.semantic):UH(n,r.unit.file),c=r.definition?a.length>0?"exact":"none":a.length>0?"file-level":"none",l=r.unit.file,u=vt(Kr.dirname(l)),d=VH(a),f=zH(u),m=Vd([...ox(u),...d?ox(d):[]]),p=qH(r.unit,u,d,a),g=KH(p,r.unit,u,d,a,o,s),h=ZH(r.unit,c,d,a,u,g.whyNoSuggestedHome),S=eU(r.unit,u,d,a,g.suggestedHome,g.whyNoSuggestedHome);return{actionTier:"signal",sourceUnit:r.unit,candidatePath:l,currentDirectory:u,directoryAncestry:f,consumerFiles:a,consumerCoverage:c,nearestCommonOwner:d,boundaryMarkers:m,recommendedTier:p,suggestedHome:g.suggestedHome,destinationConfidence:g.confidence,whyNoSuggestedHome:g.whyNoSuggestedHome,counterevidence:h,reasons:S,recommendation:tU(p,g.suggestedHome,c)}}function HH(e,t,n,r){let i=en(Zt(e,t).forDefinitions([n],{semantic:r!==!1,sourceFallback:!0}));return px(i.get(n.symbolId)??[])}function UH(e,t){let n=[];for(let[r,i]of e.entries())r!==t&&i.has(t)&&n.push(r);return px(n)}function WH(e,t){let n=mn(t),r=N(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 GH(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:w(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function lx(e){return{unit:{kind:"file",file:e,shortName:Kr.basename(e)}}}function zH(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:zd(i)})}return t}function ox(e){return e==="."?[]:ux(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function zd(e){return Vd(ux(e).map(({marker:t})=>t))}function ux(e){let t=e.split("/").filter(Boolean),n=[];for(let r=0;r<t.length;r+=1){let i=NH.get(t[r]);i&&n.push({marker:i,prefix:t.slice(0,r+1).join("/")})}return n}function VH(e){if(e.length===0)return null;let t=e.map(r=>vt(Kr.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 qH(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":ax(n,"package")?"package-level-shared":ax(n,"app")?"app-level-shared":cx(n,["feature","domain","module"])||cx(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function KH(e,t,n,r,i,o,s){let a=JH(e,r);if(a)return Tn(a);let c=iU(t.file),l=YH(e,n,c,i,s);if(l)return l;let u=r;if(vt(n)===vt(u))return Tn(`${n} is already the nearest common owner for its consumers.`);let d=XH(u,n,c,s);return d||QH(u,n,c,o,s)}function JH(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 YH(e,t,n,r,i){if(e==="same-file"){let o=r[0]??null;return o?Ud(o):Tn("No same-file consumer path was available.")}if(e==="sibling-folder"&&r.length===1){let o=vt(Kr.dirname(r[0])),s=mx(t,n,o,i);return s?Tn(s):Ud(o)}return null}function XH(e,t,n,r){return cU(e)?dx(e,t,n,r,`Nearest shared owner ${e} is outside source root ${n}.`):null}function QH(e,t,n,r,i){if(e===".")return Tn("The nearest common owner is the repository root.");let o=`${e}/shared`,s=dx(o,t,n,i,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||r.has(o)?s:Tn(`${o} does not exist in the indexed project.`)}function dx(e,t,n,r,i){if(!fx(e,n))return Tn(i);let o=mx(t,n,e,r);return o?Tn(o):Ud(e)}function Ud(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function Tn(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function ZH(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 eU(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 tU(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 nU(e,t){return sx(t)-sx(e)||e.candidatePath.localeCompare(t.candidatePath)}function sx(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 rU(e){let t=new Set(["."]);for(let n of e){let r=vt(Kr.dirname(n));for(;!t.has(r)&&(t.add(r),r!==".");)r=vt(Kr.dirname(r))}return t}function iU(e){let t=Wd(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function fx(e,t){let n=vt(e),r=vt(t);return r==="."||n===r||n.startsWith(`${r}/`)}function oU(e,t,n){let r=Wd(e),i=Wd(t);return(fx(e,t)?r.slice(i.length):r).some(s=>n.has(s.toLowerCase()))}function mx(e,t,n,r){return vt(e)===vt(n)||!oU(e,t,r)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function sU(...e){let t=new Set(MH);for(let n of e)for(let r of n??[]){let i=aU(r);i&&t.add(i)}return t}function aU(e){let t=e.trim().toLowerCase();return t===""?null:t}function ax(e,t){return zd(e).includes(t)}function cx(e,t){let n=zd(e);return t.some(r=>n.includes(r))}function cU(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?AH.has(n):!1}function vt(e){let t=mn(e);return t===""?".":t}function Wd(e){let t=mn(e);return t==="."?[]:t.split("/").filter(Boolean)}function Gd(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function px(e){return Vd([...e]).sort((t,n)=>t.localeCompare(n))}function Vd(e){return[...new Set(e)]}function qd(e,t,n={}){let{maxDepth:r=5,scope:i}=n,o=$(e,t);if(!o)return[];let s=[],a=new Set([o.symbolId]),c=new Set,l=[o];for(let u=1;u<=r&&l.length!==0;u++){let d=[],f=VS(e,l,{limit:500});for(let m of l)for(let p of lU(e,m,i,f.get(m.symbolId)??[])){let g=`${p.file}|${p.shortName}`;if(p.symbolId!==null){if(a.has(p.symbolId))continue;a.add(p.symbolId)}else if(c.has(g))continue;c.add(g),s.push({symbol:p.symbol,shortName:p.shortName,file:p.file,depth:u}),p.symbolId!==null&&p.symbolMatch&&d.push(p.symbolMatch)}l=d}return s.sort((u,d)=>u.depth-d.depth||u.file.localeCompare(d.file)),s}function lU(e,t,n,r){let i=r.filter(u=>!e.isIgnored(u.file)).filter(u=>!n||u.file.includes(n)),o=new Set(i.map(u=>u.file)),s=[];for(let u of uU(e,t,n)){if(o.has(u))continue;let d=X(e,u),f=d.length>0?It(d,d[0].startLine):null;s.push({symbol:f?.symbol??u,file:u})}let a=[...i,...s],c=[],l=new Set;for(let u of a){let d=Di(e,u.symbol);if(!d){let m=`${u.file}|${u.symbol}`;if(l.has(m))continue;l.add(m),c.push({symbolId:null,symbol:u.symbol,shortName:w(u.symbol),file:u.file,symbolMatch:null});continue}if(d.symbolId===t.symbolId||e.isIgnored(d.relativePath)||!dU(d))continue;let f=`${d.symbolId}|${d.relativePath}`;l.has(f)||(l.add(f),c.push({symbolId:d.symbolId,symbol:d.symbol,shortName:w(d.symbol),file:d.relativePath,symbolMatch:d}))}return c}function uU(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
720
- FROM mentions m
721
- JOIN chunks c ON m.chunk_id = c.id
722
- JOIN documents consumer_d ON consumer_d.id = c.document_id
723
- WHERE m.symbol_id = ?
724
- AND m.role != 1
725
- AND c.document_id != ?
726
- ${e.pathExclusionsFor("consumer_d")}
727
- ${r}`,...i).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function dU(e){if(e.symbol.startsWith("scip-clojure ")||M(e.relativePath)==="clojure")return!0;let t=le(e.symbol);return t==="method"||t==="type"||e.symbol.endsWith("().")}function Kd(e,t,n={}){let r=je(e,t);if(!r)return null;let i=fU(e,r);if(!i||e.isIgnored(i.relative_path))return null;let o=[],s=0,a=mU(e,i.relative_path),c=n.semantic===!1?new Map:vn(e,a);for(let l of a){let u=pU(e,i,l,c.get(l.symbolId)??new Set);s+=u,o.push({symbol:l.symbol,shortName:w(l.symbol),startLine:l.startLine,endLine:l.endLine,externalConsumers:u,riskLevel:gU(u)})}return{file:i.relative_path,symbols:o,totalExternalConsumers:s}}function fU(e,t){return e.get(`SELECT id, relative_path FROM documents
728
- WHERE relative_path = ?
729
- ${e.pathExclusionsFor("documents")}
730
- LIMIT 1`,t)??null}function mU(e,t){return new _(e).definitionsForFile(t).sort((n,r)=>n.startLine-r.startLine||n.endLine-r.endLine)}function pU(e,t,n,r){let i=e.all(`SELECT DISTINCT consumer_d.relative_path
731
- FROM mentions m
732
- JOIN chunks c ON m.chunk_id = c.id
733
- JOIN documents consumer_d ON consumer_d.id = c.document_id
734
- WHERE m.symbol_id = ?
735
- AND m.role != 1
736
- 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 gU(e){return e>10?"high":e>0?"medium":"low"}function hU(e,t={}){let{scope:n,minLoc:r=1,maxDepth:i=5,scanLimit:o}=t,s=new _(e),a=yU(e,n,r,o),c=new Jd;for(let g of a)c.add(g);let l=[],u=[];a.length>0&&l.push(gx(e,0,a,c));let d=a.map(g=>g.definition).filter(g=>g!==null),f=new Set(a.map(g=>g.symbol));for(let g=1;g<=i&&d.length>0;g++){let h=s.calleeMap(d,{semantic:!1}),S=new Set;for(let x of d)for(let b of h.get(x.symbolId)??[])f.has(b.symbol)||S.add(b.symbol);let C=[];for(let x of S){f.add(x);let b=hx(e,x);if(!b||e.isIgnored(b.relativePath)||De(e,b.relativePath)||ue(e,b.symbol,b.relativePath)||s.fileKind(b.relativePath)==="test"||s.hasSuppressionComment(b))continue;let y=SU(e,b,c);y.removable?C.push(bU(b,"cascade")):y.blockingFiles.length>0&&u.push({shortName:w(b.symbol),file:b.relativePath,blockingFiles:y.blockingFiles.slice(0,3)})}if(C.length===0)break;for(let x of C)c.add(x);l.push(gx(e,g,C,c)),d=C.map(x=>x.definition).filter(x=>x!==null)}let m=l.reduce((g,h)=>g+h.loc,0),p=l.reduce((g,h)=>g+h.entries.length,0);return{batches:l,totalSymbols:p,totalLoc:m,blocked:u}}function yU(e,t,n,r){let i=ir(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:r,semantic:!1}),o=[];for(let s of i.symbols)s.kind==="dead-code"&&(De(e,s.relativePath)||ue(e,s.symbol,s.relativePath)||o.push({symbol:s.symbol,shortName:s.shortName,file:s.relativePath,startLine:s.startLine,endLine:s.endLine,loc:s.loc,evidence:"graph-fact",definition:hx(e,s.symbol)}));return o}function bU(e,t){return{symbol:e.symbol,shortName:w(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function hx(e,t){let n=e.get(`SELECT d.relative_path
737
- FROM global_symbols gs
738
- JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
739
- JOIN documents d ON d.id = der.document_id
740
- WHERE gs.symbol = ?
741
- LIMIT 1`,t);return n?X(e,n.relative_path).find(r=>r.symbol===t)??null:null}function SU(e,t,n){let r=Gi(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 gx(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=X(e,a);c.length>0&&c.every(l=>r.contains(a,l.startLine))&&s.push(a)}return{depth:t,entries:i.map(({definition:a,...c})=>c),loc:i.reduce((a,c)=>a+c.loc,0),filesEmptied:s.sort()}}var Jd=class{ranges=new Map;add(t){let n=this.ranges.get(t.file)??[];n.push({start:t.startLine,end:t.endLine}),this.ranges.set(t.file,n)}contains(t,n){let r=this.ranges.get(t);return r?r.some(i=>n>=i.start&&n<=i.end):!1}};import{createHash as sq}from"crypto";import{existsSync as Tf}from"fs";import{execFileSync as CU}from"child_process";var xx=2e3,Va=50,xU=64,vU=8,RU=3,IU=2160*60*60,wU=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,DU=3,EU=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,kU=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function PU(e){let t=K(e,{clearGroups:["whole-project"]});return(n,r,i)=>{let o=i??Yd(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 qa(e){let t=K(e,{clearGroups:["whole-project"]});return(n,r,i,o)=>{let s=o??Yd(n.config.projectRoot);if(!s)return null;let a=t.has(n)?t.get(n,()=>({head:"",values:new Map})):null;(!a||a.head!==s)&&t.invalidate(n);let c=t.get(n,()=>({head:s,values:new Map}));if(c.values.has(r))return c.values.get(r)??null;let l=i(n.config.projectRoot,s);return c.values.set(r,l),l}}var TU=qa("git-commit-history");function qe(e,t={}){let n=t.historyMode??"bounded",r=t.head;return{capability:i=>_U(e,i,r),commitHistory:()=>So(e,n,r),fileChurn:()=>NU(e,n,r),changeAmplification:()=>AU(e,n,r),trackedFiles:()=>OU(e,r),fileAddRecords:()=>$U(e,n,r),coChangePairs:(i={})=>VU(e,i,n,r),coChangePairsForFiles:(i,o={})=>Rx(e,i,o,n,r),directionalCoChangePairsForFiles:(i,o={})=>qU(e,i,o,n,r)}}function So(e,t="bounded",n){return TU(e,Jr(t),(r,i)=>FU(r,i,t),n)}function _U(e,t,n){let r=n??Yd(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 Yd(e){try{return Nt(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function Nt(e,t){return CU("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]})}function FU(e,t,n){let r;try{r=Nt(e,["log","--no-merges","--name-only",...Ka(n),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}return{head:t,...ef(r,Va)}}function LU(e){return wU.test(e.subject)}function NU(e,t,n){let r=So(e,t,n);if(!r)return null;let i=new Map;for(let o of r.commits){let s=LU(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 AU(e,t,n){let r=So(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:yx(i,.5),p90FilesPerCommit:yx(i,.9),commitsAnalyzed:i.length}}function yx(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var MU=PU("git-tracked-files");function OU(e,t){return MU(e,n=>{try{let r=Nt(n,["ls-files"]);return new Set(r.split(`
742
- `).map(i=>i.trim()).filter(i=>i!==""))}catch{return null}},t)}var jU=qa("git-file-adds"),bx="__git__/file-adds",Sx=re({kind:"git-file-adds",invalidation:q("git-file-adds"),serialize:HU,deserialize:UU});function Xd(e){return qe(e).fileAddRecords()}function $U(e,t,n){let r=Jr(t);return jU(e,r,(i,o)=>BU(e,i,o,t),n)}function BU(e,t,n,r){let i=Sx.read(e,Cx(r),n);if(i)return i;let o=WU(t,r);return o&&Sx.write(e,Cx(r),n,o),o}function HU(e){return JSON.stringify([...e.entries()])}function UU(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 WU(e,t){let n;try{n=Nt(e,["log","--no-merges","--find-renames","--name-status",...Ka(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(`
743
- `),c=a>=0?s.slice(0,a):s,[,l]=c.split("\0"),u=Number(l)||0;if(!(a<0))for(let d of s.slice(a+1).split(`
744
- `)){let f=GU(d);if(!f)continue;if(f.status==="R"&&f.from&&f.to){let p=i.get(f.to)??new Set([f.to]);i.set(f.from,p);continue}if(f.status!=="A"||!f.to)continue;let m={commitsAgo:o,addedAt:u};r.set(f.to,m);for(let p of i.get(f.to)??[])r.set(p,m)}}return r}function GU(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 vx=qa("git-co-change-pairs"),zU=qa("git-directional-co-change-pairs");function VU(e,t,n,r){let i=`all\0${Jr(n)}\0${Qd(t)}`,o=vx(e,i,()=>{let s=So(e,n,r);return s?Zd(s,t):null},r);return o&&[...o]}function Rx(e,t,n,r,i){if(t.size===0)return[];let o=`files\0${Jr(r)}\0${Ix(t)}\0${Qd(n)}`,s=vx(e,o,()=>{let a=So(e,r,i);return a?Zd(a,n,t):null},i);return s&&[...s]}function qU(e,t,n,r,i){if(t.size===0)return[];let o=n.maxFilesPerCommit??Va;if(t.size>xU)return Rx(e,t,n,r,i);let s=`directional\0${Jr(r)}\0${Ix(t)}\0${Qd({...n,maxFilesPerCommit:o})}`,a=zU(e,s,(c,l)=>{let u=KU(c,l,t,o,r);return u?Zd(u,n,t):null},i);return a&&[...a]}function Qd(e){let t=e.minTogether??4,n=e.minConfidence??.6,r=e.maxFilesPerCommit??Va;return`${t}\0${n}\0${r}`}function Ix(e){return[...e].sort().join("\0")}function Zd(e,t,n){let{minTogether:r=4,minConfidence:i=.6,maxFilesPerCommit:o=Va}=t,s=new Map,a=new Map,c=e.newestAnalyzedAt??0;for(let d of e.commits){let f=[...new Set(d.files)].sort();if(f.length>o)continue;e.newestAnalyzedAt===void 0&&d.timestamp>c&&(c=d.timestamp);let m=XU(f),p=n===void 0||f.some(g=>n.has(g));for(let g of f)s.set(g,(s.get(g)??0)+1);if(p)for(let g=0;g<f.length;g++)for(let h=g+1;h<f.length;h++){if(n&&!n.has(f[g])&&!n.has(f[h]))continue;let S=`${f[g]}\0${f[h]}`,C=a.get(S)??{together:0,focusedTogether:0,broadTogether:0,lastTogetherAt:0,timestamps:[],subjects:[]};C.together+=1,m?C.broadTogether+=1:C.focusedTogether+=1,d.timestamp>C.lastTogetherAt&&(C.lastTogetherAt=d.timestamp),C.timestamps.push(d.timestamp),C.subjects.push(d.subject),a.set(S,C)}}let l=[],u=c-IU;for(let[d,f]of a){let m=f.together;if(m<r)continue;let[p,g]=d.split("\0"),h=s.get(p)??m,S=s.get(g)??m,C=Math.max(m/h,m/S);if(C<i)continue;let x=f.broadTogether/m,b=f.timestamps.filter(y=>y>=u).length;l.push({fileA:p,fileB:g,together:m,confidence:C,changesA:h,changesB:S,focusedTogether:f.focusedTogether,broadTogether:f.broadTogether,broadCommitRatio:x,lastTogetherAt:f.lastTogetherAt,recentTogether:b,commitScope:ZU(f.broadTogether,m),recency:b>0?"recent":"stale",subjectContext:eW(f.subjects)})}return l.sort((d,f)=>f.together-d.together||f.confidence-d.confidence||d.fileA.localeCompare(f.fileA)),l}function KU(e,t,n,r,i){let o;try{o=JU(e,i)}catch{return null}if(o.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:0};let s;try{s=Nt(e,["log","--no-merges","--format=%H",...Ka(i),"--",...[...n].sort()])}catch{return null}let a=new Set(o.map(f=>f.hash)),c=s.split(`
745
- `).map(f=>f.trim()).filter(f=>f!==""&&a.has(f)),l=YU(e,o,r);if(c.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:l};let u;try{u=Nt(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...c])}catch{return null}let d=ef(u,r);return{head:t,...d,newestAnalyzedAt:l}}function JU(e,t){return Nt(e,["log","--no-merges","--format=%H%x00%ct",...Ka(t)]).split(`
746
- `).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 Ka(e){return e==="full"?[]:["-n",String(wx())]}function wx(){return Sn(process.env.SCIP_QUERY_GIT_HISTORY_MAX_COMMITS)??xx}function Jr(e){return e==="full"?"full":`bounded:${wx()}`}function Cx(e){let t=Jr(e);return t===`bounded:${xx}`?bx:`${bx}:${t}`}function YU(e,t,n){for(let i=0;i<t.length;i+=20){let o=t.slice(i,i+20),s;try{s=Nt(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=ef(s,n);if(a.commits.length>0)return a.commits[0].timestamp}return 0}function ef(e,t){let n=[],r=0;for(let i of e.split("")){if(i.trim()==="")continue;let o=i.indexOf(`
747
- `),s=o>=0?i.slice(0,o):i,[a,c,l]=s.split("\0");if(!a||!c)continue;let u=o>=0?i.slice(o+1).split(`
748
- `).map(d=>d.trim()).filter(d=>d!==""):[];if(u.length>t){r+=1;continue}n.push({hash:a,timestamp:Number(c)||0,subject:l??"",files:u})}return{commits:n,skippedBulkCommits:r}}function XU(e){return e.length>=vU?!0:QU(e).size>=RU}function QU(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 ZU(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function eW(e){let t=new Set,n=[],r=[];for(let i of e){!r.includes(i)&&r.length<DU&&r.push(i);for(let o of tW(i))t.add(o);for(let o of i.match(EU)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:r,externalIssueLabelStatus:"unavailable"}}function tW(e){let t=new Set,n=kU.exec(e)?.[1]?.toLowerCase();return n&&t.add(nW(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 nW(e){return e==="feat"?"feature":e}import{existsSync as rW}from"fs";import{join as iW}from"path";function nf(e){return tf.test(e)}var tf=/(?:^|\/)(?: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 Co(e,t,n={}){let{minTogether:r=4,minConfidence:i=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=qe(e,{historyMode:n.historyMode,...n.head?{head:n.head}:{}}),c=a.commitHistory(),l=t!==void 0,u=a.coChangePairs({minTogether:l?Math.min(r,2):r,minConfidence:l?0:i,maxFilesPerCommit:s});if(!c||!u)return{available:!1,commitsAnalyzed:0,findings:[]};let d=typeof n.scanLimit=="number"?u.slice(0,n.scanLimit):u,f=se(e),m=Tx(e),p=sf(e,f,m),g=n.includeLinked===!0||l,h=[];for(let S of d){if(tf.test(S.fileA)||tf.test(S.fileB)||!Dx(e,S.fileA)||!Dx(e,S.fileB)||l&&!S.fileA.includes(t)&&!S.fileB.includes(t)||!l&&(J(S.fileA)==="test"||J(S.fileB)==="test"||cW(S.fileA,S.fileB)||sW(S.fileA,S.fileB)))continue;let C=p(S.fileA,S.fileB);if(!g&&C)continue;let x=rf(S.fileA,S.fileB),b=of(S,x,C);if(h.push({...S,structurallyLinked:C,partnerClass:x.partnerClass,partnerClassReasons:x.reasons,...b?{declaredCouplingSuggestion:b}:{}}),h.length>=o)break}return{available:!0,commitsAnalyzed:c.commits.length,findings:h}}function Dx(e,t){return rW(iW(e.config.projectRoot,t))}function rf(e,t){let n=kx(e),r=kx(t),i=[],o=c=>{i.includes(c)||i.push(c)},s=(c,l)=>n.tags.has(c)&&r.tags.has(l)||n.tags.has(l)&&r.tags.has(c);if(s("doc","code"))return o("one side is documentation and the other is executable source"),{partnerClass:"doc-code",reasons:i};if(n.tags.has("test")||r.tags.has("test"))return o("one side is classified as a test file"),{partnerClass:"test-code",reasons:i};if(s("schema","script"))return o("schema or contract file changes with a script or generated-code path"),{partnerClass:"schema-script",reasons:i};if(s("model","view"))return o("model or state path changes with a view or component path"),{partnerClass:"model-view",reasons:i};if(s("config","code"))return o("configuration file changes with executable source"),{partnerClass:"config-code",reasons:i};let a=SW(n.tokens,r.tokens).filter(c=>!yW.has(c));return Px(e,t)||a.length>=2?(o(Px(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 of(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!hW.has(t.partnerClass))return;let r=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${CW(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 sf(e,t=se(e),n=Tx(e)){return(r,i)=>lW(t,n,r,i)}var oW=/(?:^|\/)(?:locales|i18n)\//i;function Ex(e){return oW.test(e)}function sW(e,t){return Ex(e)&&Ex(t)?!0:aW(e,t)}function aW(e,t){if(!e.endsWith(".json")||!t.endsWith(".json"))return!1;let n=e.lastIndexOf("/"),r=t.lastIndexOf("/");if(n<0||r<0)return!1;let i=e.slice(0,n),o=t.slice(0,r);if(i===o)return!1;let s=e.slice(n+1),a=t.slice(r+1);if(s!==a)return!1;let c=i.lastIndexOf("/"),l=o.lastIndexOf("/"),u=c>=0?i.slice(0,c):"",d=l>=0?o.slice(0,l):"";return u===d}function cW(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 Tx(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function lW(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 uW=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,dW=/(?:^|\/)(?:\.[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,fW=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,mW=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,pW=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,gW=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,hW=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),yW=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 kx(e){let t=e.replace(/\\/g,"/"),n=new Set;return uW.test(t)&&n.add("doc"),dW.test(t)&&n.add("config"),fW.test(t)&&n.add("schema"),mW.test(t)&&n.add("script"),pW.test(t)&&n.add("model"),gW.test(t)&&n.add("view"),J(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:bW(t)}}function Px(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 bW(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 SW(e,t){let n=new Set(t);return[...new Set(e.filter(r=>n.has(r)))].sort()}function CW(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}import{execFileSync as or}from"child_process";import{existsSync as xW,readFileSync as vW}from"fs";import{basename as _x}from"path";function Ja(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 xo="Unable to compute git diff.";function Yr(e,t={}){let n=t.plan??_n(e,t);return n.note?RW(n.note,n.changedFileLines):n.changedFiles.length===0?IW(n.changedFileLines):Ya(n.changedFiles,[Ax(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function _n(e,t={}){let{base:n="HEAD"}=t;try{let r=wW(e.config.projectRoot,n),i=r.changedFileLines,o=_W(e,i),s=FW(e,r.changedRanges);return{changedFileLines:i,changedFiles:o,changedRanges:s,renamedFiles:kW(e.config.projectRoot,n,o,r),note:i.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:xo}}}function Ax(e,t,n,r=[]){let i=new _(e),o=new Set(n),s=Ja(r),a=[],c=new Map,l=t.flatMap(b=>i.definitionsForFile(b)).filter(VW),u=l.filter(b=>NW(b,s)),d=MW(e,l,u,s),f=$W([...u,...d.definitions]).sort((b,y)=>b.relativePath.localeCompare(y.relativePath)||b.startLine-y.startLine),m=f.map(b=>b.symbolId),p=WW(e,m),g=GW(e,m,n),h=f.filter(b=>(p.get(b.symbolId)??0)===0),S=Nx(()=>vn(e,h)),C=h.filter(b=>(S.get(b.symbolId)?.size??0)===0),x=Nx(()=>co(e,C));for(let b of f)UW(e,b,o,a,c,S.get(b.symbolId)??new Set,x.get(b.symbolId)??new Set,p.get(b.symbolId)??0,g.get(b.symbolId)??new Set);return{changedSymbols:a,consumerEntries:[...c.entries()].map(([b,y])=>({file:b,symbols:[...y].sort()})),attributionNotes:d.notes}}function Ya(e,t){let n=new Map,r=t.flatMap(s=>s.changedSymbols),i=t.flatMap(s=>s.attributionNotes??[]);for(let s of t)for(let a of s.consumerEntries){let c=n.get(a.file);c||(c=new Set,n.set(a.file,c));for(let l of a.symbols)c.add(l)}let o=zW(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:o,attributionNotes:i,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:o.length}}}function RW(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],attributionNotes:[],summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function IW(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],attributionNotes:[],summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function wW(e,t){let n=or("git",["diff","--name-status","--find-renames",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864}),r=or("git",["diff","--name-status","--find-renames","--cached",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),i=or("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),o=or("git",["diff","--unified=0",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),s=or("git",["diff","--unified=0","--cached",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),a=PW([n,r]);return{changedFileLines:[...new Set([...a.changedFiles,...Mx(i)])],changedRanges:jx([...Lx(o),...Lx(s)]),renamedFiles:a.renamedFiles,deletedFiles:a.deletedFiles}}function lf(e,t,n){try{return or("git",["show",`${t}:./${n}`],{encoding:"utf-8",cwd:e,timeout:1e4,stdio:["ignore","pipe","ignore"]})}catch{return null}}function vo(e,t,n=[]){let r=DW(e,t,n);return i=>(r.has(i)||r.set(i,lf(e,t,i)),r.get(i)??null)}function Ro(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 DW(e,t,n){let r=[...new Set(n)],i=new Map;if(r.length===0)return i;try{let o=r.map(a=>`${t}:./${a}
749
- `).join(""),s=or("git",["cat-file","--batch"],{cwd:e,input:o,maxBuffer:256*1024*1024,timeout:1e4,stdio:["pipe","pipe","ignore"]});return EW(s,r)}catch{for(let o of r)i.set(o,lf(e,t,o));return i}}function EW(e,t){let n=new Map,r=0;for(let i of t){let o=e.indexOf(10,r);if(o<0)throw new Error("git cat-file batch output ended before object header");let s=e.subarray(r,o).toString("utf-8");if(r=o+1,s.endsWith(" missing")){n.set(i,null);continue}let a=/^[0-9a-f]+ ([^ ]+) (\d+)$/.exec(s);if(!a)throw new Error(`unexpected git cat-file batch header: ${s}`);let[,c,l]=a,u=Number(l);if(!Number.isFinite(u)||u<0)throw new Error(`unexpected git cat-file batch size: ${s}`);if(r+u>e.length)throw new Error("git cat-file batch output ended before blob payload");let d=e.subarray(r,r+u);n.set(i,c==="blob"?d.toString("utf-8"):null),r+=u,e[r]===10&&(r+=1)}return n}function kW(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)||!xW(`${e}/${a}`))continue;let c=s.filter(d=>!o.has(d)).filter(d=>_x(d)===_x(a));if(c.length===0)continue;let l=vW(`${e}/${a}`,"utf-8"),u=c.map(d=>({from:d,to:a,similarity:TW(lf(e,t,d)??"",l)})).sort((d,f)=>f.similarity-d.similarity)[0];u&&u.similarity>=.45&&(i.set(a,u),o.add(u.from))}return[...i.values()].sort((a,c)=>a.to.localeCompare(c.to))}function PW(e){let t=new Set,n=new Map,r=new Set;for(let i of e.flatMap(o=>Mx(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 TW(e,t){let n=new Set(Fx(e)),r=new Set(Fx(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 Fx(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function Mx(e){return e.split(`
750
- `).map(t=>t.trim()).filter(t=>t.length>0)}function _W(e,t){let n=Ox(e),r=[];for(let i of t){let o=n(i);o&&!e.isIgnored(o)&&r.push(o)}return r}function FW(e,t){let n=Ox(e),r=[];for(let i of t){let o=n(i.file);o&&!e.isIgnored(o)&&r.push({...i,file:o})}return jx(r)}function Ox(e){let t=e.all(`SELECT relative_path FROM documents
751
- 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 Lx(e){let t=[],n=null;for(let r of e.split(`
752
- `)){if(r.startsWith("+++ ")){n=LW(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 LW(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function jx(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 NW(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(r=>uf(e.startLine,e.endLine,r.startLine,r.endLine))}function AW(e,t,n){let r=new Map,i=[],o=$x(e),s=BW(n);for(let a of t){let c=o.get(a.file)??[];if(c.some(d=>uf(d.startLine,d.endLine,a.startLine,a.endLine)))continue;let l=s.get(a.file)??[],u=HW(l,a);if(u){let d=c.find(f=>f.startLine>=u.startLine&&f.startLine<=u.endLine);if(d){r.set(d.symbolId,d),i.push(af(a,"ast-widened"));continue}}if(l.length===0){let d=[...c].filter(f=>f.startLine<=a.startLine).sort((f,m)=>m.startLine-f.startLine||f.endLine-m.endLine)[0];if(d){r.set(d.symbolId,d),i.push(af(a,"nearest-preceding"));continue}}i.push(af(a,"unattributed"))}return{definitions:[...r.values()],notes:i}}function MW(e,t,n,r){let i=$x(n),o=[],s=[],a=[...new Set(t.map(c=>c.relativePath))];for(let c of a){let l=r.get(c)??[];if(l.length===0)continue;let u=i.get(c)??[];for(let d of l)u.some(f=>uf(f.startLine,f.endLine,d.startLine,d.endLine))||o.push(d);o.some(d=>d.file===c)&&s.push(...OW(e,c))}return AW(t,o,s)}function OW(e,t){let n=V(e,t);return n?n.rootNode.namedChildren.filter(jW).map(r=>({file:t,startLine:r.startPosition.row,endLine:r.endPosition.row})).filter(r=>r.endLine>=r.startLine):[]}function jW(e){return e.endPosition.row<e.startPosition.row?!1:!new Set(["import_statement","comment"]).has(e.type)}function $W(e){let t=new Map;for(let n of e)t.set(n.symbolId,n);return[...t.values()]}function $x(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 BW(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 HW(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 af(e,t){return{file:e.file,startLine:e.startLine,endLine:e.endLine,method:t}}function uf(e,t,n,r){return e<=r&&n<=t}function UW(e,t,n,r,i,o,s,a,c){let l=Math.max(a,o.size,s.size);if(!qW(t,l))return;let u=w(t.symbol);r.push({symbol:t.symbol,shortName:u,file:t.relativePath,startLine:t.startLine,endLine:t.endLine,fanIn:l});for(let d of c)cf(e,n,i,d,u);for(let d of o)cf(e,n,i,d,u);for(let d of s)cf(e,n,i,d,u)}function Nx(e){try{return e()}catch(t){return console.error(`warning: diff-impact enrichment scan failed, continuing without it: ${t instanceof Error?t.message:t}`),new Map}}function WW(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
753
- FROM mentions m
754
- JOIN chunks c ON m.chunk_id = c.id
755
- WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
756
- AND m.role != 1
757
- GROUP BY m.symbol_id`,...t);return new Map(n.map(r=>[r.symbol_id,r.fan_in]))}function GW(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
758
- FROM mentions m
759
- JOIN chunks c ON m.chunk_id = c.id
760
- JOIN documents ref_d ON c.document_id = ref_d.id
761
- WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
762
- AND m.role != 1
763
- AND ref_d.relative_path NOT IN (${n.map(()=>"?").join(",")})
764
- ${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 cf(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 zW(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function VW(e){return!(dn(e.symbol)||e.parentTypeName!==null&&!ce(e.symbol))}function qW(e,t){return ce(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}function Bx(e){let[t,n]=Xa(e,":"),r=t||"unknown",i=(o={})=>{let s=o.actionTier??KW(r);return{sourceAnalyzer:r,actionTier:s,rootCauseKey:o.rootCauseKey??(n||e),label:o.label??`${r} finding`,relatedFiles:o.relatedFiles??[],why:o.why??[],remediation:o.remediation??JW(s,r),file:o.file}};if(!n)return i({rootCauseKey:e,why:["Baseline identity did not include analyzer payload."]});if(["dead","isolated","extract","wrapper","passthrough","stale"].includes(r)){let[o,s]=Xa(n,":");return i({file:o,relatedFiles:o?[o]:[],rootCauseKey:s?`${o}:${s}`:n,label:`${r} finding`,why:s?[`Baseline subject: ${s}.`]:[]})}if(r==="cycle"){let o=n.split(">").filter(Boolean);return i({relatedFiles:o,rootCauseKey:n,label:"cycle finding",why:o.length>0?[`Cycle path: ${o.join(" > ")}.`]:[]})}if(r==="similar"){let o=n.split("|").filter(Boolean);return i({relatedFiles:[],rootCauseKey:n,label:"similarity finding",why:o.length>0?[`Similar symbols: ${o.join(" | ")}.`]:[]})}if(r==="drift"){let[o,s]=Xa(n,":"),[a,c]=Xa(s,":");return i({actionTier:o==="unused-import"?"direct":"signal",file:a,relatedFiles:[...new Set([a,c].filter(Boolean))],rootCauseKey:n,label:`${o||"drift"} finding`,why:[...o?[`Drift kind: ${o}.`]:[],...c?[`Related dependency: ${c}.`]:[]]})}return i({why:["Baseline analyzer prefix is not recognized by this diff-gate version."]})}function KW(e){switch(e){case"dead":case"isolated":case"cycle":case"passthrough":return"direct";case"similar":case"extract":case"wrapper":case"stale":return"signal";default:return"signal"}}function JW(e,t){return e==="direct"?`Fix the new ${t} baseline finding, or knowingly accept it via health --write-baseline.`:`Review the new ${t} baseline signal; fix it if it reflects real debt, or knowingly accept it via health --write-baseline.`}function Xa(e,t){let n=e.indexOf(t);return n<0?[e,""]:[e.slice(0,n),e.slice(n+t.length)]}import{existsSync as rG,readFileSync as zx}from"fs";function ec(e,t){let n=YW(e,t)??XW(e,t)??QW(e,t)??ZW(e,t);return eG(e,n,t)}function YW(e,t){let n=-1,r=null;for(let i=0;i<=t;i+=1){let o=df(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(df(e[i]??"")===r)return{start:n,end:i+1};return{start:n,end:e.length}}function df(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function XW(e,t){if(!Qa(e[t]??""))return null;let n=t;for(;n>0&&Qa(e[n-1]??"");)n-=1;let r=t+1;for(;r<e.length&&Qa(e[r]??"");)r+=1;return{start:n,end:r}}function Qa(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function QW(e,t){let n=t;for(;n>=0;){let o=e[n]??"";if(Za(o)!==null)break;if(ff(o)!==null)return null;n-=1}if(n<0)return null;let r=Za(e[n]??"");if(r===null)return null;let i=n+1;for(;i<e.length;){let o=e[i]??"",s=Za(o);if(s!==null){if(s<=r)break;i+=1;continue}if(ff(o)!==null)break;i+=1}return{start:n,end:i}}function Za(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function ZW(e,t){let n=e[t]??"";if(Ux(n)||n.trim().length===0)return{start:t,end:t+1};let r=t;for(;r>0&&Hx(e[r-1]??"");)r-=1;let i=t+1;for(;i<e.length&&Hx(e[i]??"");)i+=1;return{start:r,end:i}}function Hx(e){return ff(e)===null}function ff(e){return e.trim().length===0?"blank":Ux(e)?"heading":df(e)?"fence":Qa(e)?"table":Za(e)!==null?"list":null}function Ux(e){return/^#{1,6}\s+/.test(e.trim())}function eG(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(`
765
- `).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}function sr(e,t){return t.filter(n=>e.includes(n))}import{readdirSync as tG}from"fs";import{join as Wx}from"path";function Io(e,t){let n=tc(e),r=tc(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 nG(e){return tc(e).replace(/\/\*\*?$/,"")}function Gx(e,t){let n=tc(t),r=nG(n),i=n.endsWith("/**"),o=[],s=(a,c)=>{let l;try{l=tG(a,{withFileTypes:!0})}catch{return}for(let u of l){if(u.name.startsWith("."))continue;let d=c?`${c}/${u.name}`:u.name;Io(n,d)&&o.push(d),i&&u.isDirectory()&&s(Wx(a,u.name),d)}};return s(Wx(e,r),r),o.sort()}function tc(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}var iG=/<!--\s*scip-query:\s*snapshot\s*-->/i;function nc(e,t){if((e.config.docs?.snapshotPaths??[]).some(i=>Io(i,t)))return!0;let r=P(e,t);return r.length>0&&iG.test(r)}var tn={classifyCitation:sG,citationContexts:aG,citationKindLabel:lG,citationRemediation:uG,referenceTargets:dG,hasLineAnchoredCitation:oG};function oG(e){return e.some(t=>(t.lineReferences?.length??0)>0)}function sG(e){let t=e.join(`
766
- `).toLowerCase(),n=[],r=sr(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=sr(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=sr(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 aG(e,t,n){let r;try{r=zx(`${e.config.projectRoot}/${t}`,"utf-8").split(/\r?\n/)}catch{return[]}let i=n.flatMap(cG),o=[];for(let s=0;s<r.length;s+=1){let a=r[s]??"";i.some(c=>a.includes(c))&&o.push(ec(r,s))}return o}function cG(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 lG(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 uG(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 dG(e,t,n){let r=Ja(n),i=new Set;for(let o of t)fG(e,o,r.get(o)??[])&&i.add(o);return i}function fG(e,t,n){if(!mG.test(t))return!0;let r=`${e.config.projectRoot}/${t}`;if(!rG(r))return!0;if(n.length===0)return!1;let i=zx(r,"utf-8").split(/\r?\n/),o=pG(i);for(let s of n)for(let a=s.startLine;a<=s.endLine;a+=1)if((i[a]??"").trim()!==""&&!o.has(a))return!0;return!1}var mG=/\.(?:[cm]?[jt]sx?)$/i;function pG(e){let t=new Set,n=!1;for(let r=0;r<e.length;r+=1){let i=e[r].trim();!n&&gG(i)&&(n=!0),n&&(t.add(r),i.endsWith(";")&&(n=!1))}return t}function gG(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}import{existsSync as qx,readFileSync as pf,statSync as hG}from"fs";import{join as Xr}from"path";var Vx=re({kind:"doc-path-evidence",invalidation:q("doc-path-evidence"),serialize:_G,deserialize:FG}),wo=/\.(?:md|mdx|rst|txt)$/i;function yG(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var bG=3,SG=/([A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6})(?::([1-9][0-9]*))?\b/g;function CG(e,t={}){let{doc:n,limit:r=20,minCoupling:i=bG,includeSnapshotExcluded:o=!1}=t,s=IG(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&&!Jx(e,c)||n!==void 0&&!qx(Xr(e.config.projectRoot,c)))continue;let l=nc(e,c);if(l&&!o)continue;let{value:u,estimated:d}=xG(e,c,s.changeTimes.get(c)),f=vG(e,c),m=new Map,{resolved:p,broken:g,citations:h}=EG(e,c,s.tracked,s.trackedBySuffix,s.everSeenInHistory),S=new Map(h.map(x=>[x.file,x]));for(let x of p){if(x===c||wo.test(x))continue;let b=(s.changeTimes.get(x)??[]).filter(R=>R>u).length;if(b===0)continue;let y=S.get(x);m.set(x,{file:x,evidence:"reference",coChanges:0,changesSinceDocUpdate:b,...mf("reference",f,y?.contexts),citationContexts:y?.contexts,citedLines:y?.lineReferences})}for(let[x,b]of s.coupling.get(c)??[]){if(b<i||!s.tracked.has(x))continue;let y=(s.changeTimes.get(x)??[]).filter(v=>v>u).length;if(y===0)continue;let R=m.get(x);R?(R.evidence="both",R.coChanges=b,Object.assign(R,mf("both",f,R.citationContexts))):m.set(x,{file:x,evidence:"co-change",coChanges:b,changesSinceDocUpdate:y,...mf("co-change",f)})}if(m.size===0&&g.length===0)continue;let C=[...m.values()].sort((x,b)=>b.changesSinceDocUpdate-x.changesSinceDocUpdate);a.push({doc:c,docLastChangedAt:u,staleness:C.reduce((x,b)=>x+b.changesSinceDocUpdate,0)+g.length*10,subjects:C.slice(0,8),brokenReferences:g,...l?{snapshotExcluded:!0}:{},...d?{docLastChangedAtEstimated:!0}:{}})}return a.sort((c,l)=>l.staleness-c.staleness),{available:!0,commitsAnalyzed:s.historyCommitCount,docsScanned:s.docFiles.length,findings:a.slice(0,r)}}function xG(e,t,n){if(n&&n.length>0)return{value:Math.max(...n),estimated:!1};try{return{value:Math.floor(hG(Xr(e.config.projectRoot,t)).mtimeMs/1e3),estimated:!0}}catch{return{value:0,estimated:!1}}}function vG(e,t){let n;try{n=pf(Xr(e.config.projectRoot,t),"utf8").slice(0,6e3)}catch{return{docIntent:"unknown",reasons:["doc text unavailable"]}}let r=`${t}
767
- ${n}`.toLowerCase(),i=sr(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=sr(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 mf(e,t,n=[]){let r=e==="co-change"||n.length===0?null:tn.classifyCitation(n);return{actionTier:RG(e,t.docIntent,r?.actionTier),docIntent:t.docIntent,docIntentReasons:t.reasons,...r?{citationKind:r.citationKind,citationKindReasons:r.reasons}:{}}}function RG(e,t,n){return t==="historical-note"?"support":n||(e==="co-change"?"signal":"direct")}function IG(e,t){let n=qe(e,{historyMode:t}),r=n.commitHistory();if(!r)return null;let i=n.trackedFiles()??new Set,o=new Map,s=new Map,a=new Set;for(let c of r.commits){let l=[...new Set(c.files)],u=l.filter(f=>wo.test(f)),d=l.filter(f=>!wo.test(f));for(let f of l){a.add(f);let m=o.get(f)??[];m.push(c.timestamp),o.set(f,m)}for(let f of u){let m=s.get(f);m||(m=new Map,s.set(f,m));for(let p of d)m.set(p,(m.get(p)??0)+1)}}return{changeTimes:o,coupling:s,docFiles:[...i].filter(c=>wo.test(c)),everSeenInHistory:a,historyCommitCount:r.commits.length,tracked:i,trackedBySuffix:Yx(i)}}function Kx(e,t){if(t.size===0)return[];let n=H(),r=0,i=0,o=0,s=0,a=0,c=0;return D("doc-reference.docs-citing-files",()=>{let l=qe(e).trackedFiles()??new Set;r=l.size;let u=Yx(l),d=wG(t,u),f=[];for(let m of l){if(!Jx(e,m))continue;n&&(i+=1);let p;try{p=pf(Xr(e.config.projectRoot,m),"utf-8")}catch{n&&(o+=1);continue}if(!PG(p,d)){n&&(s+=1);continue}let g=Xx(e,m,p);if(!g)continue;n&&(a+=1);let h=DG(g.candidates,t,d,l,u);if(h.size===0)continue;let S=[...new Set([...h.values()].flatMap(y=>[...y]))],C=kG(g.contextsByCandidate,S),x=[...h].map(([y,R])=>({file:y,contexts:rc([...R].flatMap(v=>C.get(v)??[])).slice(0,3),lineReferences:ic([...R].flatMap(v=>g.lineReferencesByCandidate.get(v)??[]))})).filter(y=>y.contexts.length>0),b=[...h.keys()];if(b.length>0){n&&(c+=1);let y=b.sort();f.push({doc:m,cited:y,citations:x,citedClaims:rc(x.flatMap(R=>R.contexts)).slice(0,3)})}}return f},()=>({targets:t.size,trackedFiles:r,livingDocs:i,unreadableDocs:o,candidateMisses:s,evidenceDocs:a,citedDocs:c}))}function Jx(e,t){return wo.test(t)&&!yG(t)&&qx(Xr(e.config.projectRoot,t))}function Yx(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 wG(e,t){let n=new Set(e);for(let r of e){let i=r.split("/");for(let o of[2,3]){if(i.length<o)continue;let s=i.slice(-o).join("/"),a=t.get(s);a?.length===1&&a[0]===r&&n.add(s)}}return n}function DG(e,t,n,r,i){let o=new Map;for(let s of e){if(!n.has(s))continue;let a;if(t.has(s))a=s;else if(r.has(s))a=s;else{let l=i.get(s);l?.length===1&&(a=l[0])}if(!a||!t.has(a))continue;let c=o.get(a)??new Set;c.add(s),o.set(a,c)}return o}function EG(e,t,n,r,i){let o=new Set,s=new Set,a=Xx(e,t);if(!a)return{resolved:o,broken:[],citations:[]};let c=a.candidates,l=a.contextsByCandidate,u=a.lineReferencesByCandidate,d=new Map,f=new Map,m=(p,g)=>{let h=l.get(g);if(h&&h.length>0){let C=d.get(p)??[];C.push(...h),d.set(p,rc(C).slice(0,3))}let S=u.get(g);S&&S.length>0&&f.set(p,ic([...f.get(p)??[],...S]))};for(let p of c){if(n.has(p)){o.add(p),m(p,p);continue}let g=r.get(p);if(g&&g.length===1){o.add(g[0]),m(g[0],p);continue}g&&g.length>1||i.has(p)&&s.add(p)}return{resolved:o,broken:[...s],citations:[...d].map(([p,g])=>({file:p,contexts:g,lineReferences:f.get(p)}))}}function kG(e,t){let n=new Map;for(let r of t){let i=e.get(r);i&&i.length>0&&n.set(r,[...i])}return n}function Xx(e,t,n){let r=n;if(r===void 0)try{r=pf(Xr(e.config.projectRoot,t),"utf-8")}catch{return null}let i=ae(e,t,r),o=Vx.read(e,t,i);if(o)return o;let s=TG(r);return Vx.write(e,t,i,s),s}function PG(e,t){for(let n of t)if(e.includes(n))return!0;return!1}function TG(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(SG)){let c=(a[1]??"").replace(/^\.?\//,"");if(c.length===0)continue;n.add(c);let l=a[2]?Number(a[2]):null;l!==null&&Number.isSafeInteger(l)&&i.set(c,ic([...i.get(c)??[],l]));let u=ec(t,o);if(u.length===0)continue;let d=r.get(c)??[];d.push(u),r.set(c,rc(d).slice(0,3))}}return{candidates:[...n],contextsByCandidate:r,lineReferencesByCandidate:i}}function _G(e){let t={candidates:e.candidates,contextsByCandidate:[...e.contextsByCandidate.entries()],lineReferencesByCandidate:[...e.lineReferencesByCandidate.entries()]};return JSON.stringify(t)}function FG(e){try{let t=JSON.parse(e);if(!Ze(t))return null;let n=xe(t.candidates),r=NG(t.contextsByCandidate),i=LG(t.lineReferencesByCandidate);return!n||!r?null:{candidates:n,contextsByCandidate:new Map(r),lineReferencesByCandidate:new Map(i??[])}}catch{return null}}function LG(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],ic(r)])}return t}function NG(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=xe(n[1]);if(!r)return null;t.push([n[0],r])}return t}function rc(e){let t=[];for(let n of new Set(e))t.some(r=>AG(r,n))||t.push(n);return t}function ic(e){return[...new Set(e)].sort((t,n)=>t-n)}function AG(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 MG}from"crypto";var Zx=3;function Do(e,t={}){let{scope:n,maxLoc:r=15,minLoc:i=Zx,limit:o,scanLimit:s}=t,a=Xd(e),c=nv(e,{scope:n,maxLoc:r,scanLimit:s}).map(u=>rv(e,u,a,i)).filter(u=>u!==null),l=tv(c);return o?l.slice(0,o):l}function gf(e,t,n={}){let{scope:r,maxLoc:i=15,minLoc:o=Zx,scanLimit:s}=n,a=Xd(e),c=nv(e,{scope:r,maxLoc:i,scanLimit:s}).map(u=>rv(e,u,a,o)).filter(u=>u!==null),l=c.find(u=>u.symbol===t);return l?c.filter(u=>u.symbol!==l.symbol&&u.normalizedBody===l.normalizedBody&&u.file!==l.file).sort(iv).map(({normalizedBody:u,...d})=>d):[]}function ev(e){let t=At(e);return at(t).replace(/\s+/g,"")}function tv(e){let t=new Map;for(let r of e){if(r.normalizedBody.length<8)continue;let i=jG(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(iv).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=Qx(i)-Qx(r);return s!==0?s:r.canonical.file.localeCompare(i.canonical.file)}),n}function nv(e,t){let n=ve(e,{scope:t.scope}).filter(r=>r.isFunctionLike&&!e.isIgnored(r.relativePath)).filter(r=>O(r)<=t.maxLoc);return n.sort((r,i)=>O(i)-O(r)||r.relativePath.localeCompare(i.relativePath)),ie(n,t.scanLimit)}function rv(e,t,n,r){let i=nn(e,t);if(!i||OG(i)<r)return null;let o=hf(e,t);return o?{symbol:t.symbol,shortName:w(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:O(t),ageCommits:n?.get(t.relativePath)?.commitsAgo??null,normalizedBody:o}:null}function hf(e,t){let n=nn(e,t);return n&&ev(n)||null}function nn(e,t){let n=Ce(e,t.relativePath);return n.length===0?null:n.slice(t.startLine,t.endLine+1).join(`
768
- `)}function At(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(t>=0&&n>t)return e.slice(t+1,n);let r=e.indexOf("=>");return r>=0?e.slice(r+2).replace(/;+\s*$/,""):e}function OG(e){return At(e).split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0).length}function jG(e){return MG("sha256").update(e).digest("hex").slice(0,16)}function iv(e,t){let n=e.ageCommits??-1;return(t.ageCommits??-1)-n||e.file.localeCompare(t.file)||e.startLine-t.startLine}function Qx(e){return e.functions.reduce((t,n)=>t+n.loc,0)}var $G=new Set(_t());function BG(e,t={}){let{includeHomonyms:n=!1,limit:r}=t,i=Qr(e,t).filter(o=>o.relationship==="divergent"||n&&o.relationship==="homonym");return r?i.slice(0,r):i}function Qr(e,t={}){let{scope:n,minSimilarity:r=.3,scanLimit:i}=t,o=WG(e,{scope:n,scanLimit:i});return av(o,{minSimilarity:r,isDelegatePair:dz(e)}).filter(s=>!s.members.some(a=>Hm(e,a.file,a.startLine,"twin")))}function av(e,t={}){let n=t.minSimilarity??.3,r=t.isDelegatePair,i=e.filter(l=>!pv(l.leaf)&&!ez(l.leaf)&&J(l.file)!=="test"&&!Re(l.symbol)&&!lv(l.symbol)&&!uv(l.symbol,l.leaf)),{recordsByLeaf:o,recordOrder:s}=D("twin-drift.group-by-leaf",()=>HG(i),()=>({records:i.length})),a=D("twin-drift.cluster-leaf-names",()=>cv([...o.keys()]),()=>({leaves:o.size}));return D("twin-drift.compare-clusters",()=>{let l=[];for(let u of a){let d=UG(u,o,s);if(d.length<2||new Set(d.map(C=>C.file)).size<2)continue;let f=null,m=!1,p=!1,g=new Set;for(let C=0;C<d.length;C+=1)for(let x=C+1;x<d.length;x+=1){let b=d[C],y=d[x];if(b.file===y.file||!iz(b,y)||r?.(b,y,d)||r?.(y,b,d))continue;if(m=!0,g.add(b.symbol),g.add(y.symbol),b.normalizedBody===y.normalizedBody){p=!0;continue}let R=YG(b.tokens,y.tokens);(!f||R>f.similarity)&&(f={a:b,b:y,similarity:R})}if(!m)continue;let h=d.filter(C=>g.has(C.symbol)).sort((C,x)=>C.file.localeCompare(x.file)||C.startLine-x.startLine).map(JG);if(!f){l.push({leaf:sv(u),relationship:p?"identical":"homonym",maxDivergence:0,members:h});continue}let S=f.similarity>=n?"divergent":"homonym";l.push({leaf:sv(u),relationship:S,maxDivergence:Math.round((1-f.similarity)*1e3)/1e3,members:h,...S==="divergent"?{firstDivergentTokens:XG(f.a.tokens,f.b.tokens)}:{}})}return l},()=>({clusters:a.length,records:i.length})).sort((l,u)=>u.members.length-l.members.length||u.maxDivergence-l.maxDivergence||l.leaf.localeCompare(u.leaf))}function HG(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 UG(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 WG(e,t){let n=D("twin-drift.load-definitions",()=>ve(e,{scope:t.scope}).filter(o=>GG(o)&&!e.isIgnored(o.relativePath)).filter(o=>!Ur(o.relativePath)));D("twin-drift.sort-definitions",()=>n.sort((o,s)=>o.relativePath.localeCompare(s.relativePath)||o.startLine-s.startLine),()=>({definitions:n.length}));let r=ie(n,t.scanLimit),i=D("twin-drift.select-candidates",()=>zG(r),()=>({scanned:r.length}));return D("twin-drift.build-records",()=>{let o=[];for(let s of i){let a=VG(e,s);a&&o.push(a)}return o},()=>({candidates:i.length,scanned:r.length}))}function GG(e){return e.isFunctionLike?e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&$G.has(e.kind):!0:!1}function zG(e){let t=e.filter(o=>o.leaf&&!pv(o.leaf)&&!Re(o.symbol)&&!lv(o.symbol)&&!uv(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=cv([...n.keys()]),i=new Set;for(let o of r){let s=[...o].flatMap(a=>n.get(a)??[]);if(!(s.length<2)&&!(new Set(s.map(a=>a.relativePath)).size<2)&&!s.every(a=>J(a.relativePath)==="test"))for(let a of s)i.add(a)}return e.filter(o=>i.has(o))}function VG(e,t){if(!t.leaf)return null;let n=nn(e,t);if(!n||!ce(t.symbol)&&!qG(n,t.leaf))return null;let r=at(At(n)),i=r.replace(/\s+/g,"");if(!i||i.length<8)return null;let o=r.match(KG)??[];return o.length===0?null:{leaf:t.leaf,symbol:t.symbol,shortName:w(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:O(t),normalizedBody:i,tokens:o,isThinForwarder:fv(r)}}function qG(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 KG=/[A-Za-z_$][A-Za-z0-9_$]*|\d+(?:\.\d+)?|[^\sA-Za-z0-9_$]/g;function JG(e){return{symbol:e.symbol,shortName:e.shortName,file:e.file,startLine:e.startLine,endLine:e.endLine,loc:e.loc}}function YG(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 XG(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 cv(e){let t=new Map;for(let s of e)t.set(s,s);let n=s=>{let a=s;for(;t.get(a)!==a;)a=t.get(a);let c=s;for(;t.get(c)!==a;){let l=t.get(c);t.set(c,a),c=l}return a},r=(s,a)=>{let c=n(s),l=n(a);c!==l&&t.set(c,l)},i=new Map;for(let s of e){let a=s.slice(0,2).toLowerCase(),c=i.get(a)??[];c.push(s),i.set(a,c)}for(let s of i.values())for(let a=0;a<s.length;a+=1)for(let c=a+1;c<s.length;c+=1)QG(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 QG(e,t){return e===t||e.toLowerCase()===t.toLowerCase()?!0:e.length<8||t.length<8||Math.abs(e.length-t.length)>2||ZG(e.toLowerCase(),t.toLowerCase())/Math.max(e.length,t.length)<.8?!1:oz(e.toLowerCase(),t.toLowerCase(),2)}function ZG(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;return r}function ez(e){return/^[A-Z][A-Z0-9_]*$/.test(e)||/^__[^_].*__$/.test(e)||tz.has(e.toLowerCase())}var tz=new Set(["main","row"]),nz=new Set(["app","component","components","feature","features","impl","index","lib","route","routes","shared","src","tsx","typescript","ui"]);function lv(e){return e.startsWith("rust-analyzer ")&&/\/(?:tests?|benches?)\//.test(e)}var rz=new Set(["default","new","reset"]);function uv(e,t){return e.startsWith("rust-analyzer ")&&rz.has(t.toLowerCase())}function iz(e,t){if(e.leaf.toLowerCase()!==t.leaf.toLowerCase()||e.leaf.length>4)return!0;let n=ov(e);return[...ov(t)].some(r=>n.has(r))}function ov(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&&!nz.has(n)))}function oz(e,t,n){if(Math.abs(e.length-t.length)>n)return!1;let r=Array.from({length:t.length+1},(i,o)=>o);for(let i=1;i<=e.length;i+=1){let o=[i],s=o[0];for(let a=1;a<=t.length;a+=1){let c=e[i-1]===t[a-1]?0:1,l=Math.min(r[a]+1,o[a-1]+1,r[a-1]+c);o.push(l),s=Math.min(s,l)}if(s>n)return!1;r=o}return r[t.length]<=n}function dv(e){return fv(at(At(e)))}function fv(e){let t=e.trim();if(!t||sz.test(t))return!1;let n=lz(t);return n.length===0||n.length>2?!1:cz(n[n.length-1])}var sz=/\b(?:if|else|for|while|switch|try|catch|do)\b/,az=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^[\]]*\])*\((?:[^()]|\([^()]*\))*\)$/;function cz(e){let t=e.trim().replace(/^return\s+/,"").replace(/^await\s+/,"").replace(/;\s*$/,"").trim();return az.test(t)}function lz(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 uz=3;function dz(e){let t=new Map;return(n,r,i)=>{if(!n.isThinForwarder)return!1;let o=`${n.symbol}\0${r.symbol}`,s=t.get(o);if(s!==void 0)return s;let a=mv(e,n,r,i,uz,new Set);return t.set(o,a),a}}function mv(e,t,n,r,i,o){if(i<=0||o.has(t.symbol)||(o.add(t.symbol),(fn(e,t.file)??[]).filter(c=>c.line>=t.startLine&&c.line<=t.endLine&&c.calleeLeaf===n.leaf).length===0))return!1;let a=new Set(ne(e,t.file).filter(c=>c.sourcePath&&(c.kind!=="namespace"||c.usedMembers.includes(n.leaf))).map(c=>c.sourcePath));if([...a].some(c=>Je(c,n.file)))return!0;for(let c of r)if(!(c.symbol===t.symbol||c.symbol===n.symbol||!c.isThinForwarder)&&[...a].some(l=>Je(l,c.file))&&mv(e,c,n,r,i-1,o))return!0;return!1}function pv(e){return e.startsWith("<")&&e.endsWith(">")}function sv(e){return[...e].sort()[0]}import{readFileSync as fz,readdirSync as mz}from"fs";import{basename as pz,join as yf}from"path";function gz(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 bf(e,t){let n=hz(e,t.file,t.keys);if(!n.ok)return{name:t.name,file:t.file,status:"unavailable",missing:[],extra:[],unavailableReason:n.reason};let r=vz(e.config.projectRoot,t.mustEqual),i=gz(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 hv(e,t){return t.map(n=>bf(e,n))}function yv(e,t){if(t.has(e.file))return!0;let n=e.mustEqual;switch(n.type){case"top-level-dirs":return[...t].some(r=>r===n.path||r.startsWith(`${n.path}/`));case"file-glob":return[...t].some(r=>Io(n.pattern,r));case"registered-commands":return t.has("docs/COMMAND_REFERENCE.md");case"builtin-skills":return[...t].some(r=>r.startsWith("skills/"))}}function bv(e){if(e.status==="unavailable")return`[coverage-contract] ${e.name}: DISCLOSED \u2014 could not evaluate (${e.unavailableReason})`;let t=[];return e.missing.length>0&&t.push(`missing ${e.missing.join(", ")}`),e.extra.length>0&&t.push(`extra ${e.extra.join(", ")}`),`[coverage-contract] ${e.name}: ${t.join("; ")}`}function hz(e,t,n){return n.type==="markdown-list"?xz(e,t,n.marker):yz(e,t,n)}function yz(e,t,n){if(!P(e,t))return{ok:!1,reason:`file not found: ${t}`};let i=M(t);if(!i)return{ok:!1,reason:`unsupported file type for ${n.type} extraction: ${t}`};let o=V(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"?bz(o,n.identifier):Cz(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 Sv(e){let t=e.childForFieldName("value");return t?t.type==="as_expression"||t.type==="satisfies_expression"?t.namedChild(0):t:null}function bz(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=Sv(n);if(i?.type==="object")return Sz(i)}return null}function Sz(e){let t=new Set;for(let n of e.namedChildren)if(n.type==="pair"){let r=n.childForFieldName("key");r&&t.add(Cv(r.text))}else n.type==="shorthand_property_identifier"&&t.add(n.text);return[...t].sort()}function Cz(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=Sv(n);if(i?.type!=="array")continue;let o=new Set;for(let s of i.namedChildren)s.type==="string"&&o.add(Cv(s.text));return[...o].sort()}return null}function Cv(e){return e.length>=2&&(e[0]==="'"&&e.endsWith("'")||e[0]==='"'&&e.endsWith('"'))?e.slice(1,-1):e}function xz(e,t,n){let r=P(e,t);if(!r)return{ok:!1,reason:`file not found: ${t}`};let i=xv(r,n);return i===null?{ok:!1,reason:`no <!-- BEGIN GENERATED ${n} --> ... <!-- END GENERATED ${n} --> block in ${t}`}:{ok:!0,keys:vv(i)}}function xv(e,t){let n=B(t),i=new RegExp(`<!--\\s*BEGIN GENERATED ${n}\\s*-->([\\s\\S]*?)<!--\\s*END GENERATED ${n}\\s*-->`).exec(e);return i?i[1]:null}function vv(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 vz(e,t){switch(t.type){case"top-level-dirs":return gv(yf(e,t.path));case"file-glob":return[...new Set(Gx(e,t.pattern).map(n=>pz(n)))].sort();case"registered-commands":return Rz(e);case"builtin-skills":return gv(yf(e,"skills"))}}function gv(e){let t;try{t=mz(e,{withFileTypes:!0})}catch{return[]}return t.filter(n=>n.isDirectory()&&!n.name.startsWith(".")).map(n=>n.name).sort()}function Rz(e){let t;try{t=fz(yf(e,"docs/COMMAND_REFERENCE.md"),"utf-8")}catch{return[]}let n=xv(t,"COMMAND REFERENCE");return n?vv(n):[]}import{existsSync as _V,readFileSync as FV,writeFileSync as LV}from"fs";import{isAbsolute as NV,join as AV}from"path";var de={dead:{minLoc:3,skipBarrels:!0,deadCodeOnly:!0},isolated:{minLoc:3},similar:{minSimilarity:.6,limit:50,minCallees:4},duplicateBodies:{maxLoc:15,limit:50},extract:{minLoc:15,minCallees:5,limit:50},wrappers:{maxLoc:15,limit:50},passthroughs:{maxLoc:15,limit:50},stale:{minLoc:3,limit:50},drift:{},twinDrift:{minSimilarity:.3}};import Eo from"path";var Rv={analysis:new Set(["domain","source","storage","symbols"]),core:new Set(["analysis","domain","resolution","source","storage","symbols"]),domain:new Set([]),instrumentation:new Set([]),"language-parsers":new Set(["core","domain","resolution","source","storage"]),queries:new Set(["analysis","core","domain","language-parsers","resolution","semantic","source","storage","symbols"]),reindex:new Set(["domain","language-parsers","resolution","runtime","semantic","source","storage","symbols"]),resolution:new Set(["domain","source","storage","symbols"]),runtime:new Set(["core","domain","language-parsers","queries","reindex","resolution","semantic","source","storage","symbols","tla"]),semantic:new Set(["core","domain","language-parsers","reindex","resolution","runtime","source","storage","symbols"]),source:new Set(["core","domain","resolution","storage"]),storage:new Set(["analysis","domain","queries","source"]),symbols:new Set(["analysis","core","domain","language-parsers","resolution","semantic","source","storage"]),tla:new Set(["core","domain","queries","source","storage","symbols"])};function ar(e){let n=e.replace(/\\/g,"/").split("/").filter(Boolean);return n.length<=1?"(root)":n.length>=3&&["src","lib","app","server","client"].includes(n[0])?`${n[0]}/${n[1]}`:n[0]}function Sf(e,t){if(e===t)return"ok";let n=Zr(e),r=Zr(t);return n&&r?!ei(n)||!ei(r)?null:Iz(n,r)?"ok":"violation":wz(e,t)}function Iv(e,t){let n=Zr(ar(e)),r=Zr(ar(t));return!!n&&!!r&&ei(n)&&ei(r)}function wv(e,t){let n=Zr(e),r=Zr(t);return!!n&&!!r&&(!ei(n)||!ei(r))}function Zr(e){return/^src\/([^/]+)$/.exec(e)?.[1]??null}function Iz(e,t){return t==="instrumentation"||t==="domain"?!0:e==="domain"?!1:Rv[e]?.has(t)??!1}function ei(e){return Object.hasOwn(Rv,e)}function wz(e,t){if(t==="shared")return"ok";let n={app:new Set(["core","shared","ui"]),core:new Set(["shared"]),infra:new Set(["core","shared"]),ui:new Set(["core","shared"])};return n[e]?n[e].has(t)?"ok":"violation":null}function ko(e,t){let{scope:n,minDeviation:r=5,limit:i=50}=t??{},o=t?.semantic!==!1,s=t?.includePatternDeviations===!0,c=new _(e).fileDependencyGraph(n),l=_z([...Dz(e,c,{scope:n,semantic:o}),...kz(c),...s?Tz(c,r):[]]);return i<=0||l.results.length<=i?l:{...l,results:l.results.slice(0,i),totalResults:l.results.length}}function Dz(e,t,n){let r=Nz(e,n.scope),i=[],o=new Set;for(let[a,c]of t){if(rn(a))continue;let l=r.get(a)??new Set;for(let u of c)rn(u)||l.has(u)||Ez(e,a,u,n)||(i.push({file:a,dep:u}),o.add(a))}o.size>0&&Oz(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 Ez(e,t,n,r){return Hz(e,t,n)||Uz(e,t,n)||$z(n)||Gz(e,t,n)||Wz(n)?!0:r.semantic&&Bz(e,t,n)}function kz(e){let t=[],n=jz(e);for(let[r,i]of e){if(rn(r))continue;let o=ar(r);for(let s of i){if(rn(s))continue;let a=ar(s);if(o===a)continue;let c=Sf(o,a),l=c===null&&wv(o,a),u=c?"explicit":l?"unknown-layer":"inferred";if((l?"violation":c??n.get(`${o}->${a}`))==="violation"){let f=u==="explicit"?"direct":"signal";t.push({file:r,kind:"layer-violation",description:`Imports from ${a}/ (${s}) \u2014 may cross architectural boundary`,dep:s,detail:`${o}/ should not depend on ${a}/`,actionTier:f,policyBasis:u,evidenceReasons:[`dependency edge exists from ${r} to ${s}`,Pz(u,o,a)],recommendation:u==="explicit"?"Move the dependency behind an allowed layer boundary or document a policy change.":u==="unknown-layer"?"Add a layer policy entry before treating this as a boundary violation.":"Review whether this is a real boundary break or an intentional exception before moving code."})}}}return t}function Pz(e,t,n){return e==="explicit"?`explicit layer policy rejects ${t}/ -> ${n}/`:e==="unknown-layer"?`source layer policy has no entry for ${t}/ -> ${n}/`:`rare cross-layer edge ${t}/ -> ${n}/ is inferred as a violation`}function Tz(e,t){let n=[];for(let[r,i]of Fz(e)){let o=i.filter(a=>!rn(a));if(o.length<t)continue;let s=Lz(e,o);for(let a of o)for(let c of e.get(a)??[])rn(c)||(s.get(c)??0)===1&&Eo.dirname(c)!==r&&Eo.dirname(c)!==Eo.dirname(r)&&(Iv(a,c)||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 _z(e){return{results:e,unusedImports:e.filter(t=>t.kind==="unused-import").length,layerViolations:e.filter(t=>t.kind==="layer-violation").length,patternDeviations:e.filter(t=>t.kind==="pattern-deviation").length}}function Fz(e){let t=new Map;for(let n of e.keys()){let r=Eo.dirname(n),i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function Lz(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])rn(i)||n.set(i,(n.get(i)??0)+1);return n}function Nz(e,t){let n=new Map;return Az(e,n,t),n}function Az(e,t,n){for(let r of Mz(e,n))Dv(e,t,r.from_file,r.to_file)}function Mz(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
769
- FROM mentions m
770
- JOIN chunks c ON m.chunk_id = c.id
771
- JOIN documents d1 ON c.document_id = d1.id
772
- JOIN global_symbols gs ON m.symbol_id = gs.id
773
- JOIN (
774
- SELECT m2.symbol_id, c2.document_id
775
- FROM mentions m2
776
- JOIN chunks c2 ON m2.chunk_id = c2.id
777
- WHERE m2.role = 1
778
- GROUP BY m2.symbol_id
779
- ) sym_def ON sym_def.symbol_id = gs.id
780
- JOIN documents d2 ON sym_def.document_id = d2.id
781
- WHERE d1.id != d2.id
782
- AND m.role != 1
783
- ${e.pathExclusionsFor("d1","d2")}
784
- ${n}`,...r)}function Oz(e,t,n={}){new _(e).scanSourceReferences({paths:n.paths??N(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},i=>{i.target.relativePath!==i.sourceFile&&(e.isIgnored(i.target.relativePath)||Dv(e,t,i.sourceFile,i.target.relativePath))})}function Dv(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 jz(e){let t=new Map;for(let[r,i]of e){if(rn(r))continue;let o=ar(r);for(let s of i){if(rn(s))continue;let a=ar(s);if(o===a||Sf(o,a))continue;let c=`${o}->${a}`;t.set(c,(t.get(c)??0)+1)}}let n=new Map;for(let[r,i]of t)n.set(r,i<=2?"violation":"ok");return n}function $z(e){return e.includes("types")||e.endsWith(".d.ts")}function Bz(e,t,n){let r=Ui(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.isUsed)}function Hz(e,t,n){let r=ne(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.used)}function Uz(e,t,n){let r=ne(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.every(i=>i.isTypeOnly===!0)}function Wz(e){return e.endsWith(".vue")}function Gz(e,t,n){let r=ne(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 rn(e){let t=J(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||zz(Eo.basename(e)))}function zz(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")}import{basename as Ev,extname as kv}from"path";function oc(e,t,n,r,i,o){let s=new Set;qz(e,t,n,r)&&s.add(i);for(let a of o)a.value&&Vz(s,a.label,a.value);return[...s].slice(0,6)}function Vz(e,t,n){let r=Kz(n);t.endsWith("name")&&Jz(r)&&e.add(`${t} has type-guard boundary shape`);for(let i of r){let o=Yz.get(i);o&&e.add(`${t} has ${o} term: ${i}`)}}function qz(e,t,n,r){if(n<=0)return!1;let i=Ce(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(fi(s)===r)return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function Kz(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 Jz(e){return e.some(t=>Xz.has(t))&&e.some(t=>Qz.has(t))}var Yz=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"]]),Xz=new Set(["can","has","is","should"]),Qz=new Set(["access","api","auth","collision","expired","input","keyboard","overlap","permission","permissions","policy","projectile","response","route","routes","scope"]);function Po(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new _(e);return gt({candidates:()=>sV(e,s,n,r),orderCandidates:Oa,scanLimit:o,profile:{name:"passthrough-candidates"},prepare:a=>s.calleeMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,c)=>Zz(e,a,c.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:i})}function Zz(e,t,n){let r=oV(n);if(r.size!==1||!il(e,t.relativePath,t.startLine,t.endLine))return null;let[,i]=[...r.entries()][0],o=eV(e,t,i),s=nV(e,t),a=o.length>0||s.length>0?"signal":"direct";return{symbol:t.symbol,shortName:w(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:O(t),forwardsTo:i.symbol,forwardsToShort:w(i.symbol),forwardsToFile:i.file,actionTier:a,boundaryEvidence:o,publicFacadeEvidence:s,recommendation:tV(a,o,s)}}function eV(e,t,n){return oc(e,t.relativePath,t.startLine,"passthrough","explicit ignore-passthrough comment",[{label:"passthrough name",value:w(t.symbol)},{label:"callee name",value:w(n.symbol)},{label:"passthrough module",value:Ev(t.relativePath,kv(t.relativePath))},{label:"callee module",value:Ev(n.file,kv(n.file))}])}function tV(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(iV);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 nV(e,t){return To(e,t)?nr(e,t.relativePath)?["exported passthrough is declared on the package public surface"]:ue(e,t.symbol,t.relativePath)?["exported passthrough matches configured or framework public entry surface"]:[]:[]}function To(e,t){let n=Ce(e,t.relativePath);if(n.length===0)return!1;let r=T(t.symbol);if(!r)return!1;let i=n.slice(Math.max(0,t.startLine-2),t.startLine+1).join(`
785
- `),o=B(r);return new RegExp(`^\\s*export\\s+(?:default\\s+)?(?:(?:async\\s+)?function\\s+${o}\\b|(?:const|let|var)\\s+${o}\\b)`,"m").test(i)?!0:rV(n,r)}function rV(e,t){if(!t)return!1;let n=new RegExp(`^\\s*export\\s*\\{[^}\\n]*\\b${B(t)}\\b`);return e.some(r=>n.test(r))}function iV(e){return e.includes("public surface")}function oV(e){let t=e.some(r=>Z(r.symbol))?e.filter(r=>Z(r.symbol)):e,n=new Map;for(let r of t)n.has(r.symbol)||n.set(r.symbol,r);return n}function sV(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:3,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0}).filter(i=>!hi(e,i))}function _o(e,t){let{scope:n,minLoc:r=3,maxLoc:i=80,limit:o=30,includeLowConfidence:s=!1,scanLimit:a}=t??{},c=t?.semantic!==!1,l=new _(e),u=l.scopedDefinitions(n),d=bV(l,n),f={high:0,medium:1,low:2};return gt({candidates:()=>aV(e,l,u,{minLoc:r,maxLoc:i}),orderCandidates:(m,p)=>O(p)-O(m)||m.relativePath.localeCompare(p.relativePath),scanLimit:a,profile:{name:"stale-abstractions"},prepare:m=>{let p=lV(m),g=cV(e,l,m,p,{semantic:c}),h=m.filter(S=>{let C=sc(e,S,g,p);return C.realConsumers.length<=1&&!C.transitivelyReachable&&Pv(S,C.realConsumers.length,d)});return{consumerFileMap:g,singletonBackedClassIds:fV(e,l,u,h,{semantic:c}),candidateIndex:p}},evaluate:(m,p)=>{if(p.singletonBackedClassIds.has(m.symbolId))return null;let g=sc(e,m,p.consumerFileMap,p.candidateIndex);if(g.transitivelyReachable||g.realConsumers.length>1||g.realConsumers.length===0&&g.barrelConsumers>0||!Pv(g.definition,g.realConsumers.length,d))return null;let h=uV(e,g);return!s&&h.confidence==="low"?null:h},orderResults:(m,p)=>f[m.confidence]-f[p.confidence]||p.loc-m.loc||m.file.localeCompare(p.file)||m.startLine-p.startLine,limit:o})}function aV(e,t,n,r){return n.filter(i=>i.isTypeLike&&O(i)>=r.minLoc).filter(i=>O(i)<=r.maxLoc).filter(i=>!e.isIgnored(i.relativePath)).filter(i=>!i.relativePath.endsWith(".d.ts")).filter(i=>J(i.relativePath)!=="test").filter(i=>!ue(e,i.symbol,i.relativePath)).filter(i=>!SV(i.symbol)).filter(i=>!t.hasSuppressionComment(i))}function Cf(e,t,n,r){return en(Zt(e,t).forDefinitions(n,{semantic:r.semantic,sourceFallback:r.sourceFallback}))}function cV(e,t,n,r,i){let o=Cf(e,t,n,{semantic:!1,sourceFallback:!1}),s=n.filter(l=>{let u=sc(e,l,o,r);return u.realConsumers.length<=1&&!(u.realConsumers.length>0&&xf(l.relativePath))}),a=i.semantic&&s.length>0?Qt(o,Cf(e,t,s,{semantic:!0,sourceFallback:!1})):o,c=s.filter(l=>sc(e,l,a,r).realConsumers.length<=1);return Qt(a,Cf(e,t,c,{semantic:!1,sourceFallback:!0}))}function lV(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=T(n.symbol);i&&r.set(i,n)}return t}function sc(e,t,n,r){let o=[...n.get(t.symbolId)??new Set].filter(u=>u!==t.relativePath&&!e.isIgnored(u)),{realConsumers:s,barrelConsumers:a,importOnlyConsumers:c}=za(e,t,o),l=CV(e,t,n,r);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:l}}function uV(e,t){let n=_v(e,t.definition.relativePath,t.definition.startLine),r=xf(t.definition.relativePath)?!0:xV(e,t.definition),{confidence:i,reason:o}=vV(t.realConsumers.length,n,r),s=dV(t.realConsumers.length,n,r);return{symbol:t.definition.symbol,shortName:w(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:O(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 dV(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 fV(e,t,n,r,i){let o=pV(e,mV(n),r),s=o.map(l=>l.singleton);if(o.length===0)return new Set;let a=en(Zt(e,t).forDefinitions(s,{semantic:i.semantic,sourceFallback:!0})),c=new Set;for(let{singleton:l,classId:u}of o)hV(e,l,a)&&c.add(u);return c}function mV(e){let t=new Map;for(let n of e){let r=T(n.symbol);r&&t.set(Tv(n.relativePath,r),n)}return t}function pV(e,t,n){let r=[];for(let i of n){let o=gV(e,t,i);o&&r.push({singleton:o,classId:i.symbolId})}return r}function gV(e,t,n){if(_v(e,n.relativePath,n.startLine)!=="class")return null;let r=T(n.symbol);if(!r)return null;let i=yV(e,n.relativePath,r);return i?t.get(Tv(n.relativePath,i))??null:null}function hV(e,t,n){let r=T(t.symbol),i=n.get(t.symbolId);return!r||!i?!1:[...i].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!Hd(e,o,r))}function Tv(e,t){return`${e}\0${t}`}function yV(e,t,n){let r=P(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 bV(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function SV(e){let t=ye(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 xf(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 Pv(e,t,n){return!(xf(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function CV(e,t,n,r){let i=sl(e,t.relativePath),o=T(t.symbol);if(!o)return!1;let s=r.get(t.relativePath);if(!s)return!1;let a=[...i.get(o)??[]],c=new Set;for(;a.length>0;){let l=a.pop();if(c.has(l))continue;c.add(l);let u=s.get(l);if(!u)continue;let d=n.get(u.symbolId);if(d){for(let f of d)if(f!==t.relativePath&&!e.isIgnored(f))return!0}for(let f of i.get(l)??[])a.push(f)}return!1}function _v(e,t,n){let r=P(e,t);if(!r)return"other";let i=r.split(`
786
- `),o=Math.max(0,n-2),s=Math.min(i.length-1,n+2);for(let a=o;a<=s;a++){let l=(i[a]??"").replace(/^\s*\/\/.*$/g,"");if(/\b(?:export\s+)?(?:abstract\s+)?class\s+\w/.test(l))return"class";if(/\b(?:export\s+)?interface\s+\w/.test(l))return"interface";if(/\b(?:export\s+)?type\s+\w/.test(l))return"type";if(/\b(?:export\s+)?(?:const\s+)?enum\s+\w/.test(l))return"enum"}return"other"}function xV(e,t){let n=P(e,t.relativePath);if(!n)return!1;let r=T(t.symbol);if(!r)return!1;let i=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${i}\\b`),s=n.split(`
787
- `);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function vV(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 ti,extname as ac}from"path";function Fo(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new _(e),a=kV(s.fileDependencyGraph(n));return gt({candidates:()=>wV(e,s,n,r),orderCandidates:Oa,scanLimit:o,profile:{name:"wrapper-candidates"},prepare:c=>({callerFileMap:RV(e,s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>IV(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:i})}function RV(e,t,n,r){let i=Zt(e,t),o=en(i.forDefinitions(n,{semantic:!1,sourceFallback:!1})),s=[];r.semantic&&D("wrapper.semantic-candidates",()=>{s=n.filter(f=>vf(e,t,f,o).length<=1)},()=>({symbols:n.length,semanticCandidates:s.length}));let a=s.length===0?new Map:en(i.forDefinitions(s,{semantic:!0,sourceFallback:!1})),c=a.size===0?o:Qt(o,a),l=new Map(n.map(f=>[f.symbolId,f])),u=new Map;for(let f of n){let m=vf(e,t,f,c);if(m.length>1||(u.set(f.symbolId,f),m.length!==1))continue;let p=m[0],g=Fv(e,f.symbolId,p);if(!g)continue;let h=Lv(t,e,p,f.symbol,g);h?.isFunctionLike&&l.has(h.symbolId)&&u.set(h.symbolId,l.get(h.symbolId))}let d=[...u.values()];return d.length===0?c:Qt(c,en(i.forDefinitions(d,{semantic:!1,sourceFallback:!0})))}function IV(e,t,n,r){let i=vf(e,t,n,r.callerFileMap);if(i.length!==1)return null;let o=i[0],s=Fv(e,n.symbolId,o);if(!s)return null;let a=Lv(t,e,o,n.symbol,s);if(a&&pr(a.symbol))return null;let{fanIn:c,source:l}=DV(r.callerFileMap,r.reverseFanIn,o,a);if(l==="function"?c<=3:c<=5)return null;let u=TV(e,n,o,a);return{symbol:n.symbol,shortName:w(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:O(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?w(a.symbol):ti(o),callerFanIn:c,actionTier:u.length>0?"signal":"direct",boundaryEvidence:u}}function wV(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:2,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0}).filter(i=>!hi(e,i))}function vf(e,t,n,r){let i=ti(n.relativePath,ac(n.relativePath)),o=[...r.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>ti(s,ac(s))!==i).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return za(e,n,o).realConsumers}function Fv(e,t,n){return e.get(`SELECT c.start_line, c.end_line
788
- FROM mentions m
789
- JOIN chunks c ON m.chunk_id = c.id
790
- JOIN documents d ON c.document_id = d.id
791
- WHERE m.symbol_id = ? AND m.role != 1 AND d.relative_path = ?
792
- LIMIT 1`,t,n)}function Lv(e,t,n,r,i){let o=e.definitionsForFile(n),s=EV(t,n,r,i.start_line,i.end_line);return It(o,s)}function DV(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:PV(t,n),source:"file"}}function EV(e,t,n,r,i){let o=T(n);if(!o)return r;let s=Vt(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 kV(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 PV(e,t){let n=e.get(t)??0;if(n>0)return n;let r=ti(t,ac(t)),i=0;for(let[o,s]of e)o!==t&&ti(o,ac(o))===r&&s>i&&(i=s);return i}function TV(e,t,n,r){return oc(e,t.relativePath,t.startLine,"wrapper","explicit ignore-wrapper comment",[{label:"wrapper name",value:w(t.symbol)},{label:"caller name",value:r?.symbol?w(r.symbol):ti(n)},{label:"wrapper path",value:t.relativePath},{label:"caller path",value:n}])}var MV=25e3,OV=2500,jV=2500;function $V(e){let t=rr(e);return t.symbols>=MV||t.documents>=OV?jV:void 0}var BV=".scipquery-baseline.json";function cc(e,t){return t&&NV(t)?t:AV(e.config.projectRoot,t??BV)}function Rf(e,t={}){let{scope:n}=t,r=$V(e),i=[],o=ir(e,{scope:n,...de.dead,scanLimit:r});for(let s of o.symbols)De(e,s.relativePath)||ue(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&i.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of fo(e,{scope:n,...de.isolated,scanLimit:r}))De(e,s.relativePath)||ue(e,s.symbol,s.relativePath)||i.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of uo(e,{scope:n}))s.kind==="real"&&i.push(`cycle:${HV(s.path)}`);for(let s of mo(e,{scope:n,...de.similar,scanLimit:r}))i.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of Do(e,{scope:n,...de.duplicateBodies,scanLimit:r}))i.push(`duplicate-bodies:${s.hash}:${s.functions.map(a=>a.symbol).sort().join("|")}`);for(let s of bo(e,{scope:n,...de.extract,scanLimit:r}))i.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of Fo(e,{scope:n,...de.wrappers,scanLimit:r}))i.push(`wrapper:${s.file}:${s.shortName}`);for(let s of Po(e,{scope:n,...de.passthroughs,scanLimit:r}))i.push(`passthrough:${s.file}:${s.shortName}`);for(let s of _o(e,{scope:n,...de.stale,scanLimit:r}))i.push(`stale:${s.file}:${s.shortName}`);for(let s of ko(e,{scope:n,...de.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY}).results)i.push(`drift:${s.kind}:${s.file}:${s.dep}`);return[...new Set(i)].sort()}function HV(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 UV(e,t={}){let n=Rf(e,{scope:t.scope}),r=cc(e,t.path);return LV(r,JSON.stringify({version:1,findings:n},null,2)+`
793
- `),{path:r,findingCount:n.length}}function If(e,t={}){let n=cc(e,t.path);if(!_V(n))throw new Error(`No baseline found at ${n}. Create one with: scip-query health --write-baseline`);let r=JSON.parse(FV(n,"utf-8")),i=new Set(r.findings??[]),o=Rf(e,{scope:t.scope}),s=new Set(o);return{baselinePath:n,baselineCount:i.size,current:o,newFindings:o.filter(a=>!i.has(a)),fixedFindings:[...i].filter(a=>!s.has(a))}}var WV=5;function Df(e,t={}){let{base:n="HEAD",minContainment:r=.7,minCallees:i=3,minSiteCoverage:o=.4,maxHelpers:s=Number.POSITIVE_INFINITY,limit:a=20,scanLimit:c}=t,l=t.semantic!==!1,u=t.diffPlan??_n(e,{base:n}),d={available:u.note!==xo,base:n,changedFiles:u.changedFiles,helpersChecked:0,skipped:[],findings:[]};if(!d.available||u.changedFiles.length===0)return d;let f=new _(e),m=new Set(u.changedFiles),p=new Map(u.renamedFiles.map(v=>[v.to,v.from])),g=t.baseContentAt??vo(e.config.projectRoot,n,Ro(u)),h=JV(f,m,p,g);if(h.length===0)return d;let S=h.slice(0,s);h.length>s&&(d.note=`helper scoring capped at ${s} of ${h.length} new symbols`);let C=f.calleeMap(S,{semantic:l}),x=S.map(v=>({def:v,callees:Ha((C.get(v.symbolId)??[]).map(E=>E.symbol))})),b=qr(e),y,R=()=>(y??=b.calleeIndex({minCallees:Math.min(3,i),scanLimit:c,semantic:l}),y);for(let{def:v,callees:E}of x){let I=w(v.symbol);if(E.size<i){d.skipped.push({helperShortName:I,helperFile:v.relativePath,reason:`fewer than ${i} meaningful callees \u2014 too small to score`});continue}let k=R(),F=KV(E,k);if(F===0){d.skipped.push({helperShortName:I,helperFile:v.relativePath,reason:"helper callee pattern is all project-wide infrastructure \u2014 too generic to score"});continue}let te=YV(e,v.symbolId);if(te.length===0){d.skipped.push({helperShortName:I,helperFile:v.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}d.helpersChecked+=1;let Y=GV({candidateIndex:k,changed:m,helperCallees:E,helperFile:v.relativePath,helperSymbol:v.symbol,minContainment:r,minSiteCoverage:o,migratedFiles:te});Y.length!==0&&(Y.sort((L,oe)=>Nv(oe.migrationScope)-Nv(L.migrationScope)||oe.containment-L.containment||oe.siteCoverage-L.siteCoverage||L.file.localeCompare(oe.file)),d.findings.push({helperSymbol:v.symbol,helperShortName:I,helperFile:v.relativePath,helperShape:"specific-callee-cluster",helperCalleeCount:E.size,specificHelperCalleeCount:F,migratedFiles:te.sort(),leftovers:Y.slice(0,WV)}))}return d.findings.sort((v,E)=>(E.leftovers[0]?.containment??0)-(v.leftovers[0]?.containment??0)||v.helperFile.localeCompare(E.helperFile)),d.findings=d.findings.slice(0,a),d}function GV(e){let t=[],n=zV(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=RC(e.helperCallees,o.callees);if(s<e.minContainment)continue;let a=[...e.helperCallees].filter(u=>o.callees.has(u)),c=o.callees.size===0?0:a.length/o.callees.size;if(c<e.minSiteCoverage||!a.some(u=>(e.candidateIndex.docFreq.get(u)??0)<=e.candidateIndex.ubiquityThreshold))continue;let l=VV(n,o.symbol,o.file);t.push({symbol:o.symbol,shortName:w(o.symbol),file:o.file,...l,containment:s,siteCoverage:c,uniqueSiteCalleeCount:Math.max(0,o.callees.size-a.length),sharedCallees:a.map(w).sort()})}return t}function Nv(e){return e==="same-scope"?2:e==="unknown"?1:0}function zV(e,t,n){let r=new Set([...wf(t),...Ef(T(e))]);for(let i of n)for(let o of wf(i))r.add(o);return r}function VV(e,t,n){let r=new Set([...wf(n),...Ef(T(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 qV=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 wf(e){return Ef(e.replace(/\.[^.]+$/,""))}function Ef(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!qV.has(t))}function KV(e,t){let n=0;for(let r of e)(t.docFreq.get(r)??0)<=t.ubiquityThreshold&&(n+=1);return n}function JV(e,t,n,r){return e.productionCallableDefinitions({files:[...t],requireFunctionLikeSymbol:!0}).filter(i=>{if(!t.has(i.relativePath))return!1;let o=n.get(i.relativePath)??i.relativePath,s=r(o);return s===null||!new RegExp(`\\b${B(i.leaf)}\\b`).test(s)})}function YV(e,t){return e.all(`SELECT DISTINCT ref_d.relative_path
794
- FROM mentions m
795
- JOIN chunks c ON m.chunk_id = c.id
796
- JOIN documents ref_d ON c.document_id = ref_d.id
797
- WHERE m.symbol_id = ?
798
- AND m.role != 1
799
- ${e.pathExclusionsFor("ref_d")}`,t).map(r=>r.relative_path)}function kf(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new _(e);return gt({candidates:()=>o.productionCallableDefinitions({scope:n,files:t.files,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}),filterCandidate:s=>XV(s.relativePath),scanLimit:i,profile:{name:"unused-params"},evaluate:s=>{let a=W(e,s.relativePath)?.callables.find(u=>u.startLine===s.startLine&&u.endLine===s.endLine);if(!a||a.params.length===0||a.params.some(u=>!u.simple)||a.paramsEndLine>=a.endLine)return null;let c=Vt(e,s.relativePath),l=[];for(let u=a.params.length-1;u>=0;u--){let d=a.params[u];if(d.name===""||d.name.startsWith("_")||QV(c.get(d.name),a.paramsEndLine,a.endLine))break;l.unshift(d.name)}return l.length===0?null:{symbol:s.symbol,shortName:w(s.symbol),file:s.relativePath,startLine:s.startLine,endLine:s.endLine,paramCount:a.paramCount,unusedTrailing:l}},orderResults:(s,a)=>a.unusedTrailing.length-s.unusedTrailing.length||s.file.localeCompare(a.file)||s.startLine-a.startLine,limit:r})}function XV(e){let t=M(e);return t==="typescript"||t==="tsx"||t==="javascript"}function QV(e,t,n){return e?e.some(r=>r>t&&r<=n):!1}import{existsSync as ZV,mkdirSync as eq,readdirSync as tq,readFileSync as nq,writeFileSync as rq}from"fs";import{createHash as iq}from"crypto";import{join as lc}from"path";var Lo=lc(".scipquery","suppressions");function Av(e){return lc(e,Lo)}function oq(e){if(e.id&&e.id.trim()!=="")return`${e.id.trim()}.json`;let t=`${e.check??""}\0${e.file??""}`;return`CHECK-${iq("sha256").update(t).digest("hex").slice(0,12).toUpperCase()}.json`}function yde(e,t,n=new Date){if(!t.reason||t.reason.trim()==="")throw new Error("suppression requires a non-empty reason");if(!t.id&&!t.check)throw new Error("suppression requires an id or a check");let r=Av(e);eq(r,{recursive:!0});let i=lc(r,oq(t)),o={...t,createdAt:t.createdAt??n.toISOString()};return rq(i,JSON.stringify(o,null,2)+`
800
- `),{path:i}}function Mv(e){let t=Av(e);if(!ZV(t))return{suppressions:[],warnings:[]};let n=[],r=[];for(let i of tq(t).sort()){if(!i.endsWith(".json"))continue;let o=lc(t,i),s;try{s=JSON.parse(nq(o,"utf-8"))}catch{r.push(`${Lo}/${i}: malformed JSON \u2014 ignored`);continue}if(typeof s!="object"||s===null||Array.isArray(s)){r.push(`${Lo}/${i}: not a suppression object \u2014 ignored`);continue}let a=s;if(typeof a.reason!="string"||a.reason.trim()===""){r.push(`${Lo}/${i}: missing reason \u2014 ignored`);continue}if(!a.id&&!a.check){r.push(`${Lo}/${i}: needs an id or a check \u2014 ignored`);continue}n.push(a)}return{suppressions:n,warnings:r}}var aq=["echo","incomplete-migration","co-change-partner","twin-partner","coverage-contract","doc-reference","unused-params","new-dead","baseline"];function cq(e,t={}){let n=t.base??"HEAD",{minTogether:r=6,minConfidence:i=.6,maxEchoChecks:o=Number.POSITIVE_INFINITY,maxHelpers:s=Number.POSITIVE_INFINITY,minSimilarity:a=.8,includeBaseline:c=!1,scanLimit:l}=t,u=t.semantic!==!1,d=t.historyMode??"bounded",f=new Set(t.skip??[]),m=_n(e,{base:n}),p=Yr(e,{base:n,plan:m}),g=p.changedFiles,h=new Set(g),S=new Set(m.changedFileLines),C=new Set([...h,...S]),x=vo(e.config.projectRoot,n,Ro(m,g)),b=Oq(e.config.projectRoot,n,m,x),y={base:n,changedFiles:g,changedSymbols:p.changedSymbols.length,checksRun:[],skipped:[],suppressed:[],findings:[],attributionNotes:p.attributionNotes,rootCauseGroups:[],note:p.summary.note};if(g.length===0)return y;let R=(v,E)=>{if(f.has(v)){y.skipped.push({check:v,reason:"skipped via --skip"});return}let I=y.findings.length,k=y.skipped.length,F=y.checksRun.length;D(`diff-gate.check.${v}`,E,()=>({check:v,changedFiles:g.length,changedSymbols:p.changedSymbols.length,findingsAdded:y.findings.length-I,skippedAdded:y.skipped.length-k,checksRunAdded:y.checksRun.length-F}))};return R("echo",()=>pq(e,p.changedSymbols,h,b,o,a,l,u,y)),R("incomplete-migration",()=>Cq(e,n,m,s,l,u,x,y)),R("co-change-partner",()=>xq(e,C,r,i,d,y)),R("twin-partner",()=>vq(e,p.changedSymbols,h,l,y)),R("coverage-contract",()=>Rq(e,C,y)),R("doc-reference",()=>kq(e,h,S,m.changedRanges,m.renamedFiles,y)),R("unused-params",()=>Fq(e,g,y)),R("new-dead",()=>Lq(e,p.changedSymbols,b,y)),c&&R("baseline",()=>$q(e,y)),fq(y,[...e.config.suppressions??[],...Mv(e.config.projectRoot).suppressions]),y.rootCauseGroups=dq(y.findings),y}function lq(e){return e.checksRun.length===0&&e.note===xo}function uq(e){return e.filter(t=>!t.advisory)}function dq(e){let t=new Map;for(let n of e){let r=n.groupKey??`${n.check}:${n.id}`,i=t.get(r);i||(i={groupKey:r,check:n.check,severity:n.severity,actionTier:n.actionTier,sourceAnalyzer:n.sourceAnalyzer,rootCauseKey:n.rootCauseKey,count:0,findingIds:[],files:new Set,relatedFiles:new Set,message:n.message,remediation:n.remediation},t.set(r,i)),i.count+=1,i.findingIds.push(n.id),i.severity=Uv(i.severity,n.severity),i.actionTier=Wv(i.actionTier,n.actionTier),n.file&&i.files.add(n.file);for(let o of n.relatedFiles??[])i.relatedFiles.add(o)}return[...t.values()].map(n=>({...n,files:[...n.files].sort(),relatedFiles:[...n.relatedFiles].sort()})).sort((n,r)=>r.count-n.count||uc(r.severity)-uc(n.severity)||n.groupKey.localeCompare(r.groupKey))}function Uv(e,t){return uc(t)>uc(e)?t:e}function uc(e){return e==="error"?2:e==="warning"?1:0}function Wv(e,t){return e?t&&Ov(t)>Ov(e)?t:e:t}function Ov(e){return e==="direct"?2:e==="signal"?1:0}function fq(e,t){if(t.length===0||e.findings.length===0)return;let n=[];for(let r of e.findings){let i=t.find(o=>mq(o,r));i?e.suppressed.push({finding:r,suppression:i}):n.push(r)}e.findings=n}function mq(e,t){return!e.reason||e.reason.trim()===""||e.expiresAt&&Date.parse(e.expiresAt)<=Date.now()||e.id&&e.id!==t.id&&!t.legacySuppressionIds?.includes(e.id)||e.check&&e.check!==t.check||e.file&&e.file!==t.file?!1:!!(e.id||e.check)}function on(e,t){e.findings.push({...t,suppressionHint:`scip-query: ignore ${t.check} ${t.id} -- <reason>`})}function pq(e,t,n,r,i,o,s,a,c){c.checksRun.push("echo");for(let l of t.slice(0,i)){if(!ce(l.symbol)||r(l))continue;let u=gf(e,l.symbol,{maxLoc:15,scanLimit:s}).filter(S=>!n.has(S.file)).slice(0,5).map(S=>({otherFile:S.file,otherShort:S.shortName,otherSymbol:S.symbol,similarity:1,similarityBasis:"exact-body",sharedEvidence:[`exact normalized body (${S.loc} LOC)`]}));if(u.length>0){let S=Pe("echo",l.symbol,l.file),C=Pe("echo",l.symbol,l.file,...u.map(b=>`${b.otherSymbol}|${b.otherFile}`).sort()),x=u[0];on(c,{id:S,legacySuppressionIds:C===S?void 0:[C],groupKey:S,actionTier:"direct",check:"echo",severity:"warning",evidence:"heuristic",confidence:1,file:l.file,symbol:l.symbol,relatedFiles:[...new Set(u.map(b=>b.otherFile))].sort(),sourceAnalyzer:"duplicate-bodies",rootCauseKey:`${l.symbol}:${x.otherSymbol}`,message:$v(l,u),why:Bv(l,u),remediation:Hv("direct",l.shortName,x.otherShort)});continue}let d=Ba(e,l.symbol,{minSimilarity:o,limit:5,scanLimit:s,semantic:a,sourceCandidateMode:"target-pruned"}),f=[];for(let S of d){let C=S.fileA===l.file?S.fileB:S.fileA,x=S.fileA===l.file?S.shortNameB:S.shortNameA,b=S.fileA===l.file?S.symbolB:S.symbolA;n.has(C)||f.push({otherFile:C,otherShort:x,otherSymbol:b,similarity:S.similarity,similarityBasis:S.similarityBasis??"callees",sharedEvidence:S.sharedCallees})}if(f.length===0)continue;let m=f[0],p=Pe("echo",l.symbol,l.file,...f.map(S=>`${S.otherSymbol}|${S.otherFile}`).sort()),g=Pe("echo",l.symbol,l.file),h=gq(l,f);on(c,{id:g,legacySuppressionIds:p===g?void 0:[p],groupKey:g,actionTier:h,check:"echo",severity:"warning",evidence:"heuristic",confidence:m.similarity,file:l.file,symbol:l.symbol,relatedFiles:[...new Set(f.map(S=>S.otherFile))].sort(),message:$v(l,f),why:Bv(l,f),remediation:Hv(h,l.shortName,m.otherShort)})}t.length>i&&c.skipped.push({check:"echo",reason:`echo check capped at ${i} of ${t.length} changed symbols`})}function gq(e,t){return t.some(r=>hq(e.symbol,r))?"direct":"signal"}function hq(e,t){if(t.similarityBasis==="exact-body")return!0;if(t.similarityBasis!=="source-tokens"||t.similarity<.98||t.sharedEvidence.length>8)return!1;let n=T(e),r=T(t.otherSymbol);return!n||!r?!1:n===r?!0:Sq(t.sharedEvidence)?!1:yq(n,r)}function yq(e,t){let n=jv(e),r=jv(t);if(n.length===0||r.length===0)return!1;let i=new Set(r),o=n.filter(s=>i.has(s)).length;return o>=2&&o/Math.min(n.length,r.length)>=.5}function jv(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)}var bq=new Set(["bytes","crypto","hex","num","random","secret","to","token"]);function Sq(e){return e.length>=3&&e.every(t=>bq.has(t.toLowerCase()))}function $v(e,t){let n=t[0],r=Math.round(n.similarity*100);return t.length===1?`${e.shortName} (${e.file}) is ${r}% similar to established ${n.otherShort} (${n.otherFile})`:`${e.shortName} (${e.file}) resembles ${t.length} established symbol(s); strongest is ${r}% similar to ${n.otherShort} (${n.otherFile})`}function Bv(e,t){let n=[`${e.shortName} was changed in this diff.`];for(let r of t.slice(0,3))n.push(`${r.otherShort} is outside this diff and scored ${Math.round(r.similarity*100)}% similar by ${r.similarityBasis} evidence.`),n.push(`Shared evidence: ${r.sharedEvidence.slice(0,5).join(", ")||"(none listed)"}.`);return t.length>3&&n.push(`${t.length-3} additional similar match(es) grouped into this finding.`),n}function Hv(e,t,n){return e==="direct"?`Extract or reuse the shared behavior with ${n}, or keep the duplicate with a suppression reason.`:`Review whether ${t} is intentionally parallel to the established implementation(s); extract shared behavior only if the product semantics match.`}function Cq(e,t,n,r,i,o,s,a){let c=Df(e,{base:t,maxHelpers:r,diffPlan:n,scanLimit:i,semantic:o,baseContentAt:s});if(!c.available){a.skipped.push({check:"incomplete-migration",reason:"no git history"});return}a.checksRun.push("incomplete-migration"),c.note&&a.skipped.push({check:"incomplete-migration",reason:c.note});for(let l of c.findings){let u=l.leftovers.map(S=>`${S.shortName} (${S.file}, ${Math.round(S.containment*100)}% helper / ${Math.round(S.siteCoverage*100)}% site, ${S.migrationScope})`).join(", "),d=l.leftovers.map(S=>`${S.shortName}: ${S.migrationScope} (${S.migrationScopeReasons[0]})`).join("; "),f=[...l.migratedFiles,...l.leftovers.map(S=>S.file)],m=l.leftovers.length===0?void 0:Math.max(...l.leftovers.map(S=>Math.min(S.containment,S.siteCoverage))),p=l.leftovers.some(S=>S.migrationScope==="possible-subtype"),g=Pe("incomplete-migration",l.helperSymbol,l.helperFile,f.join("|")),h=Pe("incomplete-migration",l.helperSymbol,l.helperFile);on(a,{id:h,legacySuppressionIds:g===h?void 0:[g],check:"incomplete-migration",severity:"warning",evidence:"heuristic",confidence:m,file:l.helperFile,symbol:l.helperSymbol,relatedFiles:f,message:`new helper ${l.helperShortName} (${l.helperFile}) is wired into ${l.migratedFiles.length} file(s), but ${l.leftovers.length} similar un-migrated site(s) remain: ${u}`,why:[`${l.helperShortName} is new in this diff and already referenced by ${l.migratedFiles.join(", ")}.`,`Helper shape: ${l.helperShape}; ${l.specificHelperCalleeCount}/${l.helperCalleeCount} helper callees are specific enough to score.`,`Unchanged site(s) still contain the helper's callee pattern: ${u}.`,`Migration scope hints: ${d}.`],remediation:p?`Migrate same-scope sites to ${l.helperShortName}; review possible subtype/variant sites before applying the helper.`:`Migrate the remaining sites to ${l.helperShortName}, or confirm they are intentionally different.`})}}function xq(e,t,n,r,i,o){let s=qe(e,{historyMode:i}).directionalCoChangePairsForFiles(t,{minTogether:n,minConfidence:0,maxFilesPerCommit:20});if(!s){o.skipped.push({check:"co-change-partner",reason:"no git history"});return}o.checksRun.push("co-change-partner");let a=new Set,c;for(let l of s){let u=t.has(l.fileA),d=t.has(l.fileB);if(u===d)continue;let f=u?l.fileA:l.fileB,m=u?l.fileB:l.fileA,p=u?l.changesA:l.changesB,g=p>0?l.together/p:0;if(g<r||nf(m)||nf(f)||!Tf(`${e.config.projectRoot}/${m}`))continue;let h=`${f}|${m}`;if(a.has(h))continue;a.add(h);let S=Pe("co-change-partner",f,m,String(l.together)),C=Pe("co-change-partner",f,m),x=rf(f,m),b=of({fileA:f,fileB:m,together:l.together,confidence:g,commitScope:l.commitScope,recency:l.recency,subjectContext:l.subjectContext},x,(c??=sf(e))(f,m)),y=[f,m].sort().join("|");o.findings.push({id:C,legacySuppressionIds:S===C?void 0:[S],check:"co-change-partner",severity:"warning",evidence:"change-graph",actionTier:"signal",groupKey:`co-change-partner:${y}`,confidence:g,file:f,relatedFiles:[m],sourceAnalyzer:"co-change",rootCauseKey:y,partnerClass:x.partnerClass,partnerClassReasons:x.reasons,commitScope:l.commitScope,recency:l.recency,focusedTogether:l.focusedTogether,broadTogether:l.broadTogether,broadCommitRatio:l.broadCommitRatio,lastTogetherAt:l.lastTogetherAt,recentTogether:l.recentTogether,subjectContext:l.subjectContext,...b?{declaredCouplingSuggestion:b}:{},message:`${f} changed, but ${m} did not \u2014 they change together ${l.together}x (${Math.round(g*100)}% of the time)`,why:[`${f} is in this diff and ${m} is not.`,`Git history shows ${l.together} co-change(s), which is ${Math.round(g*100)}% of changes to the edited side.`,`History context: ${Iq(l)}.`,`Subject context: ${wq(l.subjectContext)}.`,...Dq(l),`Partner class: ${x.partnerClass} (${x.reasons.join("; ")}).`],remediation:b?`Update ${m} alongside this change, declare the coupling "${b.name}", or confirm the coupling no longer holds.`:`Update ${m} alongside this change, or confirm the coupling no longer holds.`})}}function vq(e,t,n,r,i){i.checksRun.push("twin-partner");let o=Qr(e,{scanLimit:r}).filter(c=>c.relationship==="divergent"||c.relationship==="identical");if(o.length===0)return;let s=new Map;for(let c of o)for(let l of c.members)s.set(l.symbol,c);let a=new Set;for(let c of t){if(!ce(c.symbol))continue;let l=s.get(c.symbol);if(!l)continue;let u=l.members.filter(p=>p.symbol!==c.symbol&&!n.has(p.file));if(u.length===0)continue;let d=[c.symbol,...u.map(p=>p.symbol)].sort().join("|");if(a.has(d))continue;a.add(d);let f=u[0],m=Pe("twin-partner",c.symbol,c.file,f.symbol);on(i,{id:m,groupKey:`twin-partner:${d}`,check:"twin-partner",severity:"warning",evidence:"heuristic",actionTier:"signal",advisory:!0,confidence:l.relationship==="identical"?1:Math.max(0,1-l.maxDivergence),file:c.file,symbol:c.symbol,relatedFiles:u.map(p=>p.file).sort(),sourceAnalyzer:"twin-drift",rootCauseKey:d,message:`${c.shortName} (${c.file}) changed but its same-name twin ${f.shortName} (${f.file}) did not \u2014 verify the change shouldn't apply to both, or consolidate them.`,why:[`${c.symbol} is in this diff.`,`${f.symbol} shares its (near-)name and is classified '${l.relationship}' with it, but ${f.file} is not in this diff.`,l.relationship==="divergent"?`The two bodies already diverge (~${Math.round(l.maxDivergence*100)}% token difference) \u2014 this diff may widen or narrow that drift.`:"The two bodies were byte-identical before this diff.","Advisory: twin-partner never fails the gate by itself \u2014 see the twin-partner entry in the diff-gate checks table."],remediation:`Update ${f.file} alongside this change, consolidate ${c.shortName}/${f.shortName} into one helper, or confirm the twin should diverge on purpose.`})}}function Rq(e,t,n){n.checksRun.push("coverage-contract");let r=e.config.coverageContracts??[];for(let i of r){if(!yv(i,t))continue;let o=bf(e,i);if(o.status==="ok")continue;let s=Pe("coverage-contract",i.name,i.file);on(n,{id:s,groupKey:`coverage-contract:${i.name}`,check:"coverage-contract",severity:o.status==="unavailable"?"warning":"error",evidence:"graph-fact",actionTier:"direct",file:i.file,sourceAnalyzer:"coverage-contracts",rootCauseKey:i.name,message:bv(o),why:[`Contract "${i.name}" declares that ${i.file} (${i.keys.type}) must track ${i.mustEqual.type}.`,o.status==="unavailable"?`The declared side could not be evaluated: ${o.unavailableReason}.`:`Missing: ${o.missing.join(", ")||"none"}. Extra: ${o.extra.join(", ")||"none"}.`,"Either side of this contract changed in this diff."],remediation:o.status==="unavailable"?"Investigate why the declared key set could not be parsed (see the reason above) \u2014 do not treat this as a pass.":`Update ${i.file} so its ${i.keys.type==="object-literal-keys"||i.keys.type==="string-array"?i.keys.identifier:i.keys.marker} matches ${i.mustEqual.type}, or fix the ground-truth source if the declared set is right.`})}}function Iq(e){return`${e.commitScope}/${e.recency}; ${e.focusedTogether} focused, ${e.broadTogether} broad-sweep (${Math.round(e.broadCommitRatio*100)}% broad), ${e.recentTogether} recent, last ${Eq(e.lastTogetherAt)}`}function wq(e){let t=e.subjectLabels.length>0?e.subjectLabels.slice(0,5).join(", "):"none inferred",n=e.issueRefs.length>0?e.issueRefs.slice(0,5).join(", "):"none",r=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(i=>`"${i}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${r}; external issue/PR labels ${e.externalIssueLabelStatus}`}function Dq(e){let t=[];return e.commitScope==="broad-sweep"&&t.push("Broad-sweep history is weaker than focused co-edits; confirm this is a real coordination contract."),e.recency==="stale"&&t.push("The pair has no co-change in the recent history window; confirm the coupling still holds."),t}function Eq(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}var Pf=3;function kq(e,t,n,r,i,o){o.checksRun.push("doc-reference");let s=tn.referenceTargets(e,t,r);if(s.size===0)return;let a=new Set(i.map(l=>l.from)),c=[];for(let l of Kx(e,s))n.has(l.doc)||nc(e,l.doc)||c.push(Pq(e,l,a));for(let l of Tq(c))on(o,l)}function Pq(e,t,n){let r=t.citedClaims.length>0?t.citedClaims:tn.citationContexts(e,t.doc,t.cited),i=tn.classifyCitation(r),o=tn.hasLineAnchoredCitation(t.citations),s=t.cited.some(d=>n.has(d)||!Tf(`${e.config.projectRoot}/${d}`)),a=!(o||s),c=t.cited[0]??"",l=Pe("doc-reference",t.doc,t.cited.join("|")),u=Pe("doc-reference",t.doc,c);return{id:u,legacySuppressionIds:l===u?void 0:[l],check:"doc-reference",severity:"warning",evidence:"change-graph",actionTier:i.actionTier,groupKey:`doc-reference:${c}`,rootCauseKey:c,confidence:1,file:t.doc,relatedFiles:t.cited,citationKind:i.citationKind,citationKindReasons:i.reasons,citedClaims:r,...a?{advisory:!0}:{},message:`${t.doc} cites ${t.cited.join(", ")} as ${tn.citationKindLabel(i.citationKind)} \u2014 changed in this diff, doc untouched`,why:[`${t.cited.join(", ")} changed in this diff.`,`${t.doc} cites the changed file(s) but was not updated in the same diff.`,...i.reasons.map(d=>`Citation kind evidence: ${d}`),a?"Advisory: bare file-mention citation (no line anchor, cited file still present under the same path) \u2014 21.2 calibration found this citation shape low-precision; verify at your leisure.":o?"Blocking: citation includes a line anchor that may now point at the wrong lines.":"Blocking: the cited file was deleted or renamed in this diff \u2014 the citation almost certainly needs an update."],remediation:tn.citationRemediation(i.citationKind,t.doc)}}function Tq(e){let t=new Map;for(let r of e){let i=r.rootCauseKey??"",o=t.get(i);o?o.push(r):t.set(i,[r])}let n=[];for(let[r,i]of t)i.length<=Pf?n.push(...i):n.push(_q(r,i));return n}function _q(e,t){let n=[...t].sort((u,d)=>(u.file??"").localeCompare(d.file??"")),r=n.slice(0,Pf).map(u=>({doc:u.file??"",citedClaims:u.citedClaims??[]})),i=n.length-r.length,o=n.every(u=>u.advisory===!0),s=n.reduce((u,d)=>Uv(u,d.severity),"info"),a=n.reduce((u,d)=>Wv(u,d.actionTier),void 0),c=n.map(u=>u.file??"").filter(u=>u.length>0),l=[...new Set(n.flatMap(u=>[u.id,...u.legacySuppressionIds??[]]))];return{id:Pe("doc-reference","hub-cluster",e),memberFindingIds:l,check:"doc-reference",severity:s,evidence:"change-graph",actionTier:a,groupKey:`doc-reference:${e}`,rootCauseKey:e,confidence:1,file:r[0]?.doc,relatedFiles:[e],citationCount:n.length,citationExemplars:r,suppressedCount:i,...o?{advisory:!0}:{},message:`${e} is cited by ${n.length} doc(s) changed in this diff, doc(s) untouched \u2014 showing ${r.length} example(s), ${i} more damped`,why:[`${e} changed in this diff.`,`${n.length} doc(s) cite it but were not updated in the same diff: ${c.join(", ")}.`,...r.map(u=>`Example \u2014 ${u.doc}: ${u.citedClaims[0]??"(no captured citation text)"}`),`${i} additional doc(s) also cite this file, past the per-hub-file cascade cap (${Pf}) \u2014 not silently dropped: counted in citationCount/suppressedCount and individually addressable via memberFindingIds.`,o?"Advisory: every citation in this cluster is a bare file-mention (no line anchor, cited file still present).":"Blocking: at least one citation in this cluster is line-anchored or cites a deleted/renamed file."],remediation:`Review the ${r.length} example doc(s) above; ${n.length} total doc(s) cite ${e} the same way \u2014 see citationExemplars and memberFindingIds in --json for the complete list.`}}function Fq(e,t,n){n.checksRun.push("unused-params");for(let r of kf(e,{files:t,limit:50})){let i=Pe("unused-params",r.symbol,r.file,r.unusedTrailing.join("|")),o=Pe("unused-params",r.symbol,r.file);on(n,{id:o,legacySuppressionIds:i===o?void 0:[i],check:"unused-params",severity:"warning",evidence:"heuristic",confidence:.85,file:r.file,startLine:r.startLine,endLine:r.endLine,symbol:r.symbol,message:`${r.shortName} (${r.file}) has trailing unused parameter(s): ${r.unusedTrailing.join(", ")}`,why:[`${r.shortName} is in a changed file.`,`The trailing parameter(s) ${r.unusedTrailing.join(", ")} are not referenced in the function body.`],remediation:"Drop the unused trailing parameters and their call-site arguments."})}}function Lq(e,t,n,r){r.checksRun.push("new-dead");let i=new _(e),o=Cr(e.config.projectRoot),s=o.length>1;for(let a of t){if(n(a)||a.fanIn>0||i.fileKind(a.file)==="test"||De(e,a.file)||ue(e,a.symbol,a.file)||Mq(a.symbol))continue;let c=Pe("new-dead",a.symbol,a.file),l=s&&Nq(o,a.file)&&Aq(e,a.symbol);on(r,{id:c,check:"new-dead",severity:"warning",evidence:l?"heuristic":"graph-fact",confidence:l?.4:.9,file:a.file,symbol:a.symbol,message:l?`${a.shortName} (${a.file}) unconfirmed (cross-package ambiguous-name resolution gap): zero indexed consumers found, but this name is ambiguous project-wide and lives in a workspace package \u2014 verify manually before treating as dead`:`${a.shortName} (${a.file}) was changed but has zero indexed consumers`,why:l?[`${a.shortName} is a changed production symbol in a workspace package.`,"The index, semantic, and source-fallback layers all report zero consumers for this symbol.","Its leaf name is ambiguous project-wide (a same-named definition exists elsewhere), and cross-package consumers reached only through a re-exporting barrel are a known unresolvable shape for this tool \u2014 see docs/plans/2026-07-02-followups.md item 2."]:[`${a.shortName} is a changed production symbol.`,"The index reports zero consumers for this symbol.","The symbol is not in a detected entry surface or configured live root."],remediation:l?"Verify with a direct code search before deleting; this tool cannot confidently resolve this symbol.":"Wire it up, or remove it before it becomes permanent dead code."})}}function Nq(e,t){return e.some(n=>t===n.relativeDir||t.startsWith(`${n.relativeDir}/`))}function Aq(e,t){let n=T(t);return n?(qt(e).get(n)?.length??0)>1:!1}function Mq(e){if(le(e)!=="type")return!1;let t=T(e);return t.startsWith("_Assert")||t.startsWith("Assert")}function Oq(e,t,n,r){let i=new Map(n.renamedFiles.map(s=>[s.to,s.from])),o=r??vo(e,t,Ro(n));return s=>{let a=i.get(s.file)??s.file,c=T(s.symbol);if(!c)return!1;let l=o(a);return l!==null&&jq(l,c)}}function jq(e,t){return new RegExp(`\\b${B(t)}\\b`).test(e)}function $q(e,t){if(!Tf(cc(e))){t.skipped.push({check:"baseline",reason:"no .scipquery-baseline.json \u2014 run health --write-baseline to enable"});return}t.checksRun.push("baseline");let n=If(e);for(let r of n.newFindings){let i=Bx(r),o=Pe("baseline",r);on(t,{id:o,groupKey:`baseline:${i.sourceAnalyzer}:${i.rootCauseKey}`,check:"baseline",severity:"error",evidence:"baseline",actionTier:i.actionTier,confidence:1,file:i.file,relatedFiles:i.relatedFiles.length>0?i.relatedFiles:void 0,sourceAnalyzer:i.sourceAnalyzer,rootCauseKey:i.rootCauseKey,message:`new ${i.label} vs committed baseline: ${r}`,why:["A committed health baseline exists.","The current health result contains a finding not present in that baseline.",`Underlying analyzer: ${i.sourceAnalyzer}.`,`Inherited action tier: ${i.actionTier}.`,`Root cause key: ${i.rootCauseKey}.`,...i.why],remediation:i.remediation})}}function Pe(e,...t){return`SQ${sq("sha256").update([e,...t].join("\0")).digest("hex").slice(0,12).toUpperCase()}`}import{dirname as Bq,relative as Hq,resolve as Uq}from"path";var Wq=new Set(_t());function Gq(e,t){return`tests/generated/twin-ab/${Gv(e)}-vs-${Gv(t)}.test.ts`}function Gv(e){return(e.split(/[/#]/).pop()||e).replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"symbol"}function zq(e,t,n,r){let i=zv(e,t);if(!i.ok)return i;let o=zv(e,n);if(!o.ok)return o;let s=i.symbol.paramCount===null||o.symbol.paramCount===null?null:i.symbol.paramCount===o.symbol.paramCount,a=qq(i.symbol,o.symbol,e.config.projectRoot,r,s);return{ok:!0,a:i.symbol,b:o.symbol,signatureCompatible:s,testSource:a}}function zv(e,t){let r=wi(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?Wq.has(o):Z(r.symbol)))return{ok:!1,reason:`${t} resolves to ${w(r.symbol)}${o!==null?` with SCIP kind ${ao(o)}`:""} \u2014 twin-ab compares call outputs, so both referents must be functions or methods.`};if(!To(e,r))return{ok:!1,reason:`${t} (${w(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=Gt(zt(a?.documentation??null));return{ok:!0,symbol:{ref:t,symbol:r.symbol,shortName:T(r.symbol)||w(r.symbol),file:r.relativePath,startLine:r.startLine,signature:c,paramCount:c?Vq(c):null}}}function Vq(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 Vv(e,t,n){let r=Bq(t),i=Uq(e,n),s=Hq(r,i).replace(/\\/g,"/").replace(/\.tsx?$/,".js");return s.startsWith(".")?s:`./${s}`}function qq(e,t,n,r,i){let o=Vv(n,r,e.file),s=Vv(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`/**
801
- * Generated by 'scip-query twin-ab'. scip-integrity-audit drill 5
802
- * ("cross-examine same-concept twins"): where one concept is computed in
803
- * more than one place, feed both the same input and require the same
804
- * answer. Disagreement between twins means at least one is wrong \u2014
805
- * determine which before consolidating.
806
- *
807
- * Twin A: ${e.shortName} (${e.file}:${e.startLine+1})
808
- * ${e.signature??"(signature unavailable)"}
809
- * Twin B: ${t.shortName} (${t.file}:${t.startLine+1})
810
- * ${t.signature??"(signature unavailable)"}
811
- * ${a}
812
- *
813
- * Fill in the TODO input table below with inputs both twins should agree
814
- * on, then run this file with vitest.
815
- */
816
- import { describe, expect, it } from 'vitest';
817
- import { ${e.shortName} as twinA } from '${o}';
818
- import { ${t.shortName} as twinB } from '${s}';
819
-
820
- // TODO: fill in shared inputs both twins should agree on \u2014 one arg array per call.
821
- const inputs: any[][] = [
822
- // [/* arg1, arg2, ... */],
823
- ];
824
-
825
- // Cast to a variadic signature so the input table can hold any arg shape \u2014
826
- // the real twins have fixed, non-rest parameter lists, and TS rejects
827
- // spreading a generic args array into those (TS2556) even when the array
828
- // itself is 'any'; casting the callee's signature, not the args, satisfies
829
- // the checker without weakening the twins' real exported types elsewhere.
830
- const callA = twinA as (...callArgs: any[]) => any;
831
- const callB = twinB as (...callArgs: any[]) => any;
832
-
833
- describe.skipIf(inputs.length === 0)('twin-ab: ${e.shortName} vs ${t.shortName}', () => {
834
- it.each(inputs)('agrees on input %#', (...args) => {
835
- expect(callA(...args)).toEqual(callB(...args));
836
- });
837
- });
838
- `}var qv={caller:3,"entry-surface":2,rooted:1},Kq=/not\s*yet\s*implement|not\s*implement|unimplement|\bnyi\b|\btodo\b|\bstub\b|not\s*supported|coming\s*soon/i,Jq=/^throw\s+new\s+[\w.]*Error\s*\(([\s\S]*)\)\s*;?$/,Yq=/^return(\s+(null|undefined|false|0|''|""|``|\[\]|\{\}))?\s*;?$/,Xq=/\/\/\s*TODO\b|\/\*\s*TODO\b/i,Qq=/(?:=>|\))\s*(?::\s*[^{;=]+)?\s*\{\s*\}\s*;?\s*$/;function Zq(e,t={}){let{scope:n,limit:r=30,scanLimit:i,semantic:o=!0}=t,s=new _(e),a=ie(s.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),c=[];for(let m of a){let p=tK(e,m);p&&c.push(p)}if(c.length===0)return[];let l=oK(e,c,a),u=c.filter(m=>!l.has(m.def.symbol));if(u.length===0)return[];let d=Zt(e,s).forDefinitions(u.map(m=>m.def),{semantic:o}),f=[];for(let m of u){let g=d.get(m.def.symbolId)?.realConsumers.length??0,h=eK(e,m.def,g);h&&f.push({symbol:m.def.symbol,shortName:w(m.def.symbol),file:m.def.relativePath,startLine:m.def.startLine,endLine:m.def.endLine,loc:O(m.def),stubKind:m.stubKind,reachability:h,callerFanIn:g,stubText:m.stubText})}return f.sort((m,p)=>qv[p.reachability]-qv[m.reachability]||p.callerFanIn-m.callerFanIn||m.file.localeCompare(p.file)||m.startLine-p.startLine),r?f.slice(0,r):f}function eK(e,t,n){return n>0?"caller":ue(e,t.symbol,t.relativePath)?"rooted":De(e,t.relativePath)?"entry-surface":null}function tK(e,t){let n=nn(e,t);if(!n)return null;let r=At(n),i=r.trim();if(i==="")return!iK(n)||!To(e,t)?null:{def:t,stubKind:"empty-body",stubText:"(empty body)"};let o=Ci(r),s=at(r),a=nK(o,s);if(a.length!==1)return null;let c=a[0];return rK(c)?{def:t,stubKind:"throw-stub",stubText:c.trim()}:Xq.test(r)&&Yq.test(c.trim())?{def:t,stubKind:"todo-return-default",stubText:i}:null}function nK(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 rK(e){let t=Jq.exec(e.trim());return t?Kq.test(t[1]??""):!1}function iK(e){return Qq.test(e.trimEnd())}function oK(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=aK(e,i),s=new Map;for(let a of n){if(!a.parentTypeName)continue;let c=s.get(a.leaf)??new Set;c.add(a.parentTypeName),s.set(a.leaf,c)}for(let a of t){let c=a.def.parentTypeName;if(!c)continue;let l=o.get(c);if(!l||l.size===0)continue;let u=s.get(a.def.leaf)??new Set;[...l].every(f=>u.has(f))&&r.add(a.def.symbol)}return r}var sK=/\bclass\s+([A-Za-z_$][\w$]*)\s+extends\s+([A-Za-z_$][\w$]*)/g;function aK(e,t){let n=new Map;for(let r of N(e,{includeIgnored:!1})){let i=P(e,r);if(i)for(let o of i.matchAll(sK)){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 cK=/^(?:validate|verify|check|assert)(?:[A-Z].*)?$/,lK=/^(?:is|has)(?:[A-Z].*)?$/,uK=/[{,]\s*(?:ok|success|valid|isValid)\s*:\s*false\b/,_f=/\breturn\b/g,dK=/\bfunction\b|=>|\)\s*(?::\s*[^{;=]+)?\s*\{/,fK=/\.(?:addIssue|push)\s*\(/;function mK(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new _(e),s=ie(o.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),a=[];for(let c of s){let l=gK(e,c);l&&a.push({symbol:c.symbol,shortName:w(c.symbol),file:c.relativePath,startLine:c.startLine,endLine:c.endLine,loc:O(c),...l})}return a.sort((c,l)=>c.file.localeCompare(l.file)||c.startLine-l.startLine||c.loc-l.loc),r?a.slice(0,r):a}function pK(e){return cK.test(e)?"imperative":lK.test(e)?"predicate":null}function gK(e,t){let n=pK(t.leaf);if(!n||Gr(e,t))return null;let r=nn(e,t);if(!r||!dK.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(dv(r)){let s=bK(e,t);return!s||Yv(s.body,Jv(s.snippet))||Kv(s.body)?null:{nameKind:n,resolvedVia:"one-hop-delegate",delegateTarget:s.shortName}}let o=At(r);return Yv(o,Jv(r))||Kv(o)?null:{nameKind:n,resolvedVia:"direct"}}var hK=new Set(["if","for","while","switch","catch","function"]);function Kv(e){let t=Ci(e);for(let n of t.matchAll(/\b([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(/g))if(!hK.has(n[1]))return!0;return!1}function Jv(e){let t=e.indexOf("=>");return t===-1?!1:!/^\s*\{/.test(e.slice(t+2))}function Yv(e,t){let n=Ci(e);if(/\bthrow\b/.test(n)||/\.reject\s*\(/.test(n)||uK.test(n)||fK.test(n))return!0;let r=yK(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 yK(e){let t=[];_f.lastIndex=0;let n;for(;n=_f.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()),_f.lastIndex=o}return t}function bK(e,t){let n=mt(e,t,{callableOnly:!0,limit:3}),r=[...new Set(n.map(c=>c.symbol))].filter(c=>c!==t.symbol);if(r.length!==1)return null;let o=wi(e,r[0]).match;if(!o)return null;let s=X(e,o.relativePath).find(c=>c.symbolId===o.symbolId);if(!s)return null;let a=nn(e,s);return a?{body:At(a),snippet:a,shortName:w(s.symbol)}:null}var SK=60;function CK(e,t={}){let{scope:n,limit:r=30,scanLimit:i,rotDays:o=SK}=t,s=ie(Ue(e,{extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs"]}).filter(u=>J(u)==="test").filter(u=>!n||u.includes(n)).filter(u=>!e.isIgnored(u)).sort(),i),a=[],c=[],l=[];for(let u of s){let d=P(e,u);if(!d)continue;let f=Ap(d),m=RK(d);for(let g of EK(f,m))m.add(g);let p=xK(f);for(let g of p){if(g.skip){c.push(NK(e,u,g,o));continue}if(g.kind==="describe")continue;let h=Qv(d,g.argsStart),S=f.slice(g.argsStart,g.callEnd),C=d.slice(g.argsStart,g.callEnd);Zv(S,m)||a.push({file:u,startLine:No(d,g.callStart),endLine:No(d,g.callEnd),title:h,severity:/\bawait\b/.test(S)?"low":"high"});let x=_K(S,C);x&&l.push({file:u,startLine:No(d,g.callStart),endLine:No(d,g.callEnd),title:h,echoedValue:x})}}return{assertionFree:r?a.slice(0,r):a,skipped:r?c.slice(0,r):c,mockEcho:r?l.slice(0,r):l}}var Ff=/(?<!\.)\b(?:x(it|test|describe)|(it|test|describe)(?:\.\s*(skip|only|todo|each\s*\([^)]*\)))?)\s*\(/g;function xK(e){let t=[];Ff.lastIndex=0;let n;for(;n=Ff.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=Ao(e,a);Ff.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 Ao(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 No(e,t){let n=0;for(let r=0;r<t&&r<e.length;r+=1)e[r]===`
839
- `&&(n+=1);return n}function Qv(e,t){let n=e.slice(t,t+400),r=/^\s*(['"`])((?:\\.|(?!\1)[\s\S])*)\1/.exec(n);return r?r[2]:"(anonymous)"}var vK=new Set(["vitest","chai","jest","@jest/globals","assert","node:assert","node:assert/strict","assert/strict","uvu/assert","expect","chai-as-promised"]),Xv=/import\s+(?:\*\s+as\s+(\w+)|\{([^}]*)\}|(\w+))\s+from\s+['"]([^'"]+)['"]/g;function RK(e){let t=new Set(["expect","assert"]);Xv.lastIndex=0;let n;for(;n=Xv.exec(e);){let[,r,i,o,s]=n;if(!(!s||!vK.has(s))&&(r&&t.add(r),o&&t.add(o),i))for(let a of i.split(",")){let c=a.trim().replace(/^type\s+/,"");if(!c)continue;let l=/^(\w+)\s+as\s+(\w+)$/.exec(c);t.add(l?l[2]:c)}}return t}function Zv(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 IK=/\bfunction\s+(\w+)\s*\(/g,wK=/\b(?:const|let)\s+(\w+)\s*=\s*(?:async\s*)?\(/g,DK=60;function EK(e,t){let n=new Set;for(let r of[IK,wK]){r.lastIndex=0;let i;for(;i=r.exec(e);){let o=i[1],s=i.index+i[0].length-1,a=Ao(e,s),c=e.indexOf("{",a+1);if(c===-1||c-a>DK)continue;let l=kK(e,c),u=e.slice(c+1,l);Zv(u,t)&&n.add(o)}}return n}function kK(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 PK=/\bmock(?:ReturnValue|ResolvedValue)(?:Once)?\s*\(/g,Lf=/\bexpect\s*\(/g,TK=/^\s*\.\s*(?:toBe|toEqual|toStrictEqual)\s*\(/,eR=/^(?:-?\d+(?:\.\d+)?|(['"`]).+\1)$/;function _K(e,t){let n=FK(e,t,PK);if(n.length===0)return null;let r=LK(e,t);for(let i of r)if(n.includes(i))return i;return null}function FK(e,t,n){let r=[];n.lastIndex=0;let i;for(;i=n.exec(e);){let o=i.index+i[0].length-1,s=Ao(e,o),a=t.slice(o+1,s).trim();eR.test(a)&&r.push(a),n.lastIndex=s+1}return r}function LK(e,t){let n=[];Lf.lastIndex=0;let r;for(;r=Lf.exec(e);){let i=r.index+r[0].length-1,o=Ao(e,i),s=e.slice(o+1),a=TK.exec(s);if(Lf.lastIndex=o+1,!a)continue;let c=o+1+a[0].length-1,l=Ao(e,c),u=t.slice(c+1,l).trim();eR.test(u)&&n.push(u)}return n}function NK(e,t,n,r){let i=P(e,t),o=Qv(i,n.argsStart),s=No(i,n.callStart),a=AK(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 AK(e,t,n){let r=n+1;try{let i=Nt(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 MK=.7,tR=.62,nR=.45;function OK(e,t={}){let{windowCommits:n=100,limit:r=30,scope:i,scanLimit:o}=t,s=qe(e,{historyMode:t.historyMode}).fileAddRecords();if(!s)return{available:!1,windowCommits:n,findings:[]};if(r<=0)return{available:!0,windowCommits:n,findings:[]};let a=VK(s,n);if(a.size===0)return{available:!0,windowCommits:n,findings:[]};let l=jK(e,{limit:r,minSimilarity:t.minSimilarity,scanLimit:o,scope:i,semantic:t.semantic,focusFiles:Number.isFinite(r)?void 0:a}).map(d=>qK(d,s,n)).filter(d=>d!==null);l.sort((d,f)=>(d.kind===f.kind?0:d.kind==="echo"?-1:1)||f.similarity-d.similarity||d.echoFile.localeCompare(f.echoFile)||d.echoSymbol.localeCompare(f.echoSymbol)||d.domain.localeCompare(f.domain));let u=l.slice(0,r).map(KK);return{available:!0,windowCommits:n,findings:u,rootCauseGroups:JK(u)}}function jK(e,t){let n=XK(t.limit),r=[...$K(e,{scope:t.scope,minSimilarity:t.minSimilarity??MK,limit:n,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles})],i=ds(e,{scope:t.scope});return i.react&&r.push(...BK(e,{scope:t.scope,minSimilarity:t.minSimilarity??tR,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...HK(e,{scope:t.scope,minSimilarity:t.minSimilarity??nR,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),i.vue&&r.push(...GK(e,{scope:t.scope,minSimilarity:t.minSimilarity??tR,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...zK(e,{scope:t.scope,minSimilarity:t.minSimilarity??nR,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),r}function $K(e,t){return mo(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles}).filter(n=>!Re(n.symbolA)&&!Re(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 BK(e,t){return fc(e,t,{query:po,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 fc(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:QK(...n.evidenceBuckets(r)),sharedCallees:[]}))}function HK(e,t){return fc(e,t,{query:go,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,acceptPair:WK,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 UK=new Set(["useCallback","useEffect","useLayoutEffect","useMemo","useMutation","useQueries","useQuery","useQueryClient","useReducer","useRef","useState"]);function WK(e){return e.sharedHooks.some(t=>!UK.has(t))||e.sharedState.length>0||e.sharedHandlers.length>0||e.sharedHandlerVerbs.length>=2}function GK(e,t){return fc(e,t,{query:ho,domain:"vue-component",basis:"vue-template",symbolA:n=>dc(n.fileA),symbolB:n=>dc(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function zK(e,t){return fc(e,t,{query:yo,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>dc(n.fileA),symbolB:n=>dc(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 VK(e,t){let n=new Set;for(let[r,i]of e)i.commitsAgo<=t&&n.add(r);return n}function qK(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 KK(e){let t=rR(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function rR(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 JK(e){let t=new Map;for(let[n,r]of e.entries()){let i=r.rootCauseKey??rR(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:YK(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 YK(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 XK(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function QK(...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 dc(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var ZK=K("suppression-inventory",{clearGroups:["whole-project"]});function mc(e){return ZK.get(e,()=>e2(e))}function e2(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 Ue(e)){let o=P(e,i);if(!(!o||!o.includes("scip-query")))for(let s of o.split(/\r?\n/)){let a=fi(s);if(a===null)continue;r+=1,n.set(i,(n.get(i)??0)+1);let c=t2(a);t[c]+=1}}return{total:r,byCategory:t,byFile:n}}function t2(e){if(!e)return"uncategorized";let t=e.toLowerCase();return t==="dead-code"?"dead":t}import{readFileSync as n2}from"fs";import{join as r2}from"path";function Nf(e,t,n={}){let r=$(e,t);if(!r)return null;let i=new _(e),o=i2(e,r),s=r.endLine-r.startLine+1,c=i.calleeMap([r],{additive:!0,semantic:n.semantic}).get(r.symbolId)??[],l=new Set(c.map(u=>u.symbol));return{symbol:r.symbol,shortName:w(r.symbol),relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,loc:s,branches:o.branches,estimateBasis:o.estimateBasis,cyclomaticEstimate:o.branches+1,calleeCount:l.size,fanIn:s2(e,r.symbolId),fanOut:a2(c,r.relativePath)}}function i2(e,t){let n=V(e,t.relativePath);if(n){let r=aR(n.rootNode,t.startLine,t.endLine);if(r)return{branches:c2(r),estimateBasis:"ast"}}return{branches:lR(sR(e,t.relativePath,t.startLine,t.endLine),oR(e,t.relativePath)),estimateBasis:"regex-fallback"}}function iR(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=V(e,i),a=s===null?[]:o.filter(l=>s.rootNode.startPosition.row<=l.startLine&&s.rootNode.endPosition.row>=l.endLine),c=new Set(a.map(l=>l.symbolId));if(s&&a.length>0){for(let l of a)n.set(l.symbolId,{branches:0,estimateBasis:"ast"});l2(s.rootNode,a,n)}for(let l of o)c.has(l.symbolId)||n.set(l.symbolId,o2(e,l))}return n}function o2(e,t){return{branches:lR(sR(e,t.relativePath,t.startLine,t.endLine),oR(e,t.relativePath)),estimateBasis:"regex-fallback"}}function oR(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function sR(e,t,n,r){try{return n2(r2(e.config.projectRoot,t),"utf-8").split(`
840
- `).slice(n,r+1).join(`
841
- `)}catch{return""}}function s2(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
842
- FROM mentions m
843
- JOIN chunks c ON m.chunk_id = c.id
844
- JOIN (
845
- SELECT m2.symbol_id, c2.document_id
846
- FROM mentions m2
847
- JOIN chunks c2 ON m2.chunk_id = c2.id
848
- WHERE m2.role = 1
849
- GROUP BY m2.symbol_id
850
- ) sym_def ON sym_def.symbol_id = m.symbol_id
851
- WHERE m.symbol_id = ?
852
- AND m.role != 1
853
- AND sym_def.document_id != c.document_id`,t)?.c??0}function a2(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function c2(e){let t=0;return Af(e,n=>{t+=cR(n)}),t}function l2(e,t,n){let r=[...t].sort((i,o)=>i.startLine-o.startLine||o.endLine-i.endLine);Af(e,i=>{let o=cR(i);if(o===0)return;let s=i.startPosition.row,a=i.endPosition.row;for(let c of r){if(c.startLine>s)break;if(c.endLine<a)continue;let l=n.get(c.symbolId);l&&(l.branches+=o)}})}function Af(e,t){t(e);for(let n of e.namedChildren)Af(n,t)}function aR(e,t,n){if(e.startPosition.row>t||e.endPosition.row<n)return null;for(let r of e.namedChildren){let i=aR(r,t,n);if(i)return i}return e}var u2=new Set(["if_statement","conditional_expression","ternary_expression","for_statement","for_in_statement","for_of_statement","while_statement","do_statement","switch_case","case_statement","catch_clause","except_clause","elif_clause","match_arm"]);function cR(e){return u2.has(e.type)?1:e.type==="binary_expression"&&e.parent?.type!=="binary_expression"&&(e.text.includes("&&")||e.text.includes("||"))?d2(e.text):0}function d2(e){return(e.match(/&&|\|\|/g)??[]).length}function lR(e,t){let n=at(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 Mf(e,t,n={}){let r=$(e,t);if(!r)return null;let i=[{file:r.relativePath,line:r.startLine}],o=kt(e,r,{semantic:n.semantic}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?w(c.enclosingSymbol):"(top-level)"})),{producers:s,consumers:a}=f2(e,r,o,{semantic:n.semantic!==!1});return{symbol:r.symbol,shortName:w(r.symbol),relativePath:r.relativePath,definitionSites:i.filter(c=>!e.isIgnored(c.file)),usageSites:o,producers:s.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:w(c.symbol),file:c.file})),consumers:a.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:c.symbol===c.file?"(top-level)":w(c.symbol),file:c.file}))}}function f2(e,t,n,r){let i=Wr(mt(e,t,{limit:30,semantic:r.semantic}).map(a=>({symbol:a.symbol,file:a.file}))),o=Wr(xt(e,t,{limit:30,semantic:r.semantic})),s=o.length>0?o:Wr(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{producers:i,consumers:s}}function pc(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,o=$(e,t);return o?r==="backward"?m2(e,o,i,{semantic:n.semantic!==!1}):p2(e,o,{semantic:n.semantic!==!1}):null}function m2(e,t,n,r){let i=[],o=new Set([t.symbol]),s=[t];for(let a=1;a<=n&&s.length!==0;a++){let c=[];for(let l of s){let u=mt(e,l,{semantic:r.semantic});for(let d of u){if(o.has(d.symbol))continue;o.add(d.symbol),i.push({symbol:d.symbol,shortName:w(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let f=Di(e,d.symbol);f&&!e.isIgnored(f.relativePath)&&c.push(f)}}s=c}return{symbol:t.symbol,shortName:w(t.symbol),direction:"backward",connectedSymbols:i}}function p2(e,t,n){let r=new Set,i=[],o=new _(e);for(let s of kt(e,t,{semantic:n.semantic})){if(i.length>=30)break;let a=s.enclosingSymbol??It(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=Di(e,a);!c||e.isIgnored(c.relativePath)||r.has(c.symbol)||(r.add(c.symbol),i.push({symbol:c.symbol,shortName:w(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:w(t.symbol),direction:"forward",connectedSymbols:i}}function g2(e,t,n={}){let r=n.impactDepth??3,i=n.sliceDepth??3,o=n.semantic,s=!y2(t),a=s?Ne("trace",t,()=>xd(e,t,{semantic:o}),v=>({definitions:v.definitions.length,references:v.referencedBy.length})):{definitions:[],referencedBy:[]},c=s?Ne("call-graph",t,()=>_d(e,t,{semantic:o}),v=>({callers:v?.callers.length??0,callees:v?.callees.length??0})):null,l=s?Ne("complexity",t,()=>Nf(e,t,{semantic:o}),v=>({callees:v?.calleeCount??0})):null,u=s?Ne("dataflow",t,()=>Mf(e,t,{semantic:o}),v=>({references:v?.usageSites.length??0,producers:v?.producers.length??0,consumers:v?.consumers.length??0})):null,d=s?Ne("backward-slice",t,()=>pc(e,t,{direction:"backward",maxDepth:i,semantic:o}),v=>({maxDepth:i,connectedSymbols:v?.connectedSymbols.length??0})):null,f=s?Ne("forward-slice",t,()=>pc(e,t,{direction:"forward",maxDepth:i,semantic:o}),v=>({maxDepth:i,connectedSymbols:v?.connectedSymbols.length??0})):null,m=s?Ne("affected",t,()=>qd(e,t,{maxDepth:r,scope:n.scope}),v=>({maxDepth:r,affectedSymbols:v.length})):[],p=Ne("change-surface",t,()=>Kd(e,t,{semantic:o}),v=>({symbols:v?.symbols.length??0,externalConsumers:v?.totalExternalConsumers??0})),g=Ne("system",t,()=>Id(e,t),v=>({files:v.files.length,symbols:v.symbols.length})),h=g.files.length===1,S=Ne("deps",t,()=>h?g.dependsOn.map(v=>({relativePath:v})):vd(e,t),v=>({files:v.length,reusedSystem:h})),C=Ne("rdeps",t,()=>h?g.dependedOnBy.map(v=>({relativePath:v})):Rd(e,t),v=>({files:v.length,reusedSystem:h})),x=Ne("surface",t,()=>wd(e,t),v=>({consumers:v.length})),b={symbol:a.definitions.length>0||a.referencedBy.length>0||c!==null||l!==null||u!==null||d!==null||f!==null||m.length>0,file:p!==null||S.length>0||C.length>0,module:g.files.length>0||g.symbols.length>0||x.length>0},y=[];!b.symbol&&!b.file&&!b.module&&y.push("No symbol, file, or module matched target.");let R=p?.file??a.definitions[0]?.relativePath??null;return{target:t,matched:b,history:Ne("history",R??t,()=>h2(e,R,n.gitHead)),trace:a,callGraph:c,complexity:l,dataflow:u,backwardSlice:d,forwardSlice:f,affected:m,changeSurface:p,deps:S,rdeps:C,system:g,surface:x,warnings:y}}function Ne(e,t,n,r=()=>({})){let i;return D(`plan-context.${e}`,()=>(i=n(),i),()=>({target:t,...r(i)}))}function h2(e,t,n){let r={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return r;let i=qe(e,n?{head:n}:{}),o=Ne("history.churn",t,()=>i.fileChurn(),c=>({files:c?.size??0}));if(!o)return r;let s=Ne("history.co-change",t,()=>Co(e,t,{limit:5,...n?{head:n}:{}}),c=>({commits:c.commitsAnalyzed,partners:c.findings.length})),a=Ne("history.suppressions",t,()=>mc(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 y2(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}var b2=new Set(_t());function Of(e,t){let{scope:n,minLoc:r=10,limit:i=30,scanLimit:o}=t??{},s=new _(e);return gt({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:r,requireFunctionLikeSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,filterCandidate:S2,profile:{name:"complexity-hotspots"},prepare:a=>{let c=x2(e,a),l=t?.semantic!==!1,u=l?Oe(e):null;u?.materializeReferences(a,{prefetchCallees:!0});let d=s.crossFileCallerMap(a,{semantic:!1});return{callerMap:u?Qt(d,u.callerMap(a)):d,calleeMap:s.calleeMap(a,{semantic:l}),languageByFile:c,clojureCallableIds:v2(e,a,c),branchEstimates:iR(e,a)}},evaluate:(a,c)=>C2(a,c,r),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:i})}function S2(e){return e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&b2.has(e.kind):!0}function C2(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 f of o){let m=`${f.symbol}|${f.file}`;s.add(m),f.file!==e.relativePath&&a.add(m)}let c=a.size,l=s.size,u=t.branchEstimates.get(e.symbolId)??{branches:0,estimateBasis:"regex-fallback"},d=u.branches+1;return{symbol:e.symbol,shortName:w(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:r,fanIn:i,fanOut:c,calleeCount:l,branches:u.branches,estimateBasis:u.estimateBasis,score:Math.round(r/50*(i/5)*Math.max(c/5,1)*Math.max(d/5,1)*100)/100}}function x2(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
854
- FROM documents
855
- WHERE relative_path IN (${r})`,...n);return new Map(i.map(o=>[o.relative_path,o.language?.toLowerCase()??null]))}function v2(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 R2(e,t,n,r,i=new Set){let o=new Map(e.map(c=>[ni(c.check,c.findingId),c])),s=new Set(t.map(c=>ni(c.check,c.findingId))),a=new Set(n);for(let c of t){let l=ni(c.check,c.findingId),u=o.get(l),d=c.suppressed?"suppressed":"still-open";u?o.set(l,{...u,lastSeen:r,timesShown:u.timesShown+1,outcome:d}):o.set(l,{check:c.check,findingId:c.findingId,firstSeen:r,lastSeen:r,timesShown:1,outcome:d})}for(let c of e){if(!a.has(c.check))continue;let l=ni(c.check,c.findingId);s.has(l)||i.has(l)||c.outcome!=="resolved"&&o.set(l,{...c,outcome:"resolved"})}return[...o.values()]}function jf(e,t){let n=new Map;for(let i of e){let o=n.get(i.check)??[];o.push(i),n.set(i.check,o)}let r=[];for(let[i,o]of n){let s=o.filter(d=>d.outcome==="resolved").length,a=o.filter(d=>d.outcome==="suppressed").length,c=o.filter(d=>d.outcome==="still-open").length,l=o.length,u=o.filter(d=>d.outcome==="still-open").sort((d,f)=>d.firstSeen-f.firstSeen)[0];r.push({check:i,seen:l,resolved:s,suppressed:a,stillOpen:c,resolutionRate:l>0?s/l:0,suppressionRate:l>0?a/l:0,oldestOpenAgeDays:u?Math.floor((t-u.firstSeen)/uR):null})}return r.sort((i,o)=>i.check.localeCompare(o.check))}var uR=864e5,I2=50,w2=.1,D2=10;function E2(e,t,n){return e.filter(r=>r.check===t).sort((r,i)=>i.firstSeen-r.firstSeen).slice(0,n)}function Fme(e,t,n){if(t.length===0)return null;let r=new Map(e.map(s=>[ni(s.check,s.findingId),s])),i=t.map(s=>r.get(ni(s.check,s.findingId))).filter(s=>s!==void 0&&s.timesShown>1);if(i.length===0)return null;let o=Math.max(...i.map(s=>Math.floor((n-s.firstSeen)/uR)));return`${t.length} finding(s), ${i.length} shown before and unresolved (oldest: ${o} day(s))`}function Lme(e,t){let n=[];for(let r of[...new Set(t)].sort()){let i=E2(e,r,I2);i.length<D2||i.filter(a=>a.outcome==="resolved").length/i.length>=w2||n.push(`(the ${r} check's findings are rarely acted on in this repo \u2014 consider suppressing with reasons or tuning its config)`)}return n}function ni(e,t){return`${e}\0${t}`}function gc(e){return fm(e).map(t=>({check:t.check,findingId:t.findingId,firstSeen:t.firstSeen,lastSeen:t.lastSeen,timesShown:t.timesShown,outcome:t.outcome}))}function Nme(e,t,n,r=Date.now(),i=new Set){let o=gc(e),s=R2(o,t,n,r,i);return mm(e,s),s}function sn(e){return e.scoreCount??e.count}function mR(e){let t=_2(e),{breakdown:n,pressure:r}=F2(e),i=fR(n,"risk"),o=fR(n,"hygiene");return{score:Math.min(i,o),riskScore:i,hygieneScore:o,scoreBreakdown:n,overview:{documents:e.statsResult.documents,symbols:e.statsResult.symbols,indexSizeBytes:e.statsResult.indexSizeBytes},findings:{deadSymbols:e.dead.count,deadLoc:e.dead.loc,isolatedSymbols:e.isolated.count,isolatedLoc:e.isolated.loc,cycles:e.realCycleCount,similarPairs:e.similarCount,duplicateBodyGroups:e.duplicateBodies.count,duplicateBodyLoc:e.duplicateBodies.loc,twinDriftGroups:e.twinDrift.count,twinDriftLoc:e.twinDrift.loc,reactComponentDuplicatePairs:e.reactComponentDuplicates.count,reactHookCandidatePairs:e.reactHookCandidates.count,reactHookCandidateScoreCount:sn(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:sn(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:sn(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:k2(e),validation:T2(e),suppressions:e.suppressions,actions:t,pressure:r,topComplexity:e.complexity.top,warnings:e.warnings.length>0?e.warnings:void 0,detectorPrecision:[]}}function k2(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:P2(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 P2(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:Mt(n.score*Math.log2(1+r))}}).sort((n,r)=>r.weighted-n.weighted):null}function T2(e){let t=e.gitEvidence?.fileStats;if(!t)return null;let n={dead:e.dead.files??[],isolated:e.isolated.files??[],twinDrift:e.twinDrift.files??[],wrappers:e.wrappers.files??[],passthroughs:e.passthroughs.files??[],stale:e.stale.files??[],reactComponents:e.reactComponentDuplicates.files??[],reactHooks:e.reactHookCandidates.files??[],reactLargeComponents:e.reactLargeComponentPressure.files??[],vueComponents:e.vueComponentDuplicates.files??[],vueComposables:e.vueComposableCandidates.files??[],vueLargeViews:e.vueLargeViewPressure.files??[]},r=new Set(Object.values(n).flat()),i=0,o=0,s=0;for(let[u,d]of Object.entries(t))r.has(u)?i+=d.fixChanges:(o+=d.fixChanges,s+=1);let a=r.size>0?Mt(i/r.size):0,c=s>0?Mt(o/s):0,l={};for(let[u,d]of Object.entries(n)){let f=new Set(d);if(f.size===0)continue;let m=0;for(let g of f)m+=t[g]?.fixChanges??0;let p=Mt(m/f.size);l[u]={flaggedFiles:f.size,fixDensity:p,lift:c>0?Mt(p/c):null}}return{flaggedFiles:r.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:r.size>0&&c>0?Mt(a/c):null,byCategory:l,validationBasis:{method:"subject-regex",commitsScanned:e.gitEvidence?.commitsScanned??0}}}function Mt(e){return Math.round(e*100)/100}function pR(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function hc(e,t="existing shared infrastructure discount"){let n=sn(e);return Math.abs(n-e.count)<.01?"":` (${pR(n)} score-weighted after ${t})`}function Mo(e,t){let n=sn(e),r=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?r:`${r} (${pR(n)} score-weighted)`}function _2(e){let t=[];if(e.dead.count>0&&t.push({category:"Dead code",evidence:"graph-fact",description:`${e.dead.count} indexed symbols with no visible repository references \u2014 review runtime/framework roots and the capability disclosure, then verify any deletion with cleanup-plan --verify`,effort:"low",impact:"high",count:e.dead.count,locRecoverable:e.dead.loc}),e.isolated.count>0&&t.push({category:"Isolated symbols",evidence:"graph-fact",description:`${e.isolated.count} symbols completely disconnected from the codebase graph`,effort:"low",impact:"medium",count:e.isolated.count,locRecoverable:e.isolated.loc}),e.realCycleCount>0&&t.push({category:"Circular dependencies",evidence:"graph-fact",description:`${e.realCycleCount} indexed dependency cycle(s) \u2014 inspect ownership and runtime order before choosing whether or how to break them`,effort:"medium",impact:"high",count:e.realCycleCount,locRecoverable:0}),e.similarCount>0&&t.push({category:"Similar functions",evidence:"heuristic",description:`${e.similarCount} pairs share disclosed call or source-token evidence beyond imports \u2014 review domain identity before considering consolidation`,effort:"medium",impact:"medium",count:e.similarCount,locRecoverable:0}),e.duplicateBodies.count>0&&t.push({category:"Duplicate function bodies",evidence:"heuristic",description:`${e.duplicateBodies.count} exact small-body group(s) across files \u2014 consolidate only when the domain concept matches`,effort:"low",impact:"medium",count:e.duplicateBodies.count,locRecoverable:e.duplicateBodies.loc}),e.twinDrift.count>0&&t.push({category:"Drifted twin implementations",evidence:"heuristic",description:`${e.twinDrift.count} same-name (or near-name) function group(s) across files with diverged or identical bodies \u2014 determine whether they represent the same concept before acting`,effort:"medium",impact:"medium",count:e.twinDrift.count,locRecoverable:0}),e.reactComponentDuplicates.count>0&&t.push({category:"Duplicated React components",evidence:"heuristic",description:`${e.reactComponentDuplicates.count} React component pair(s) share JSX structure \u2014 review whether local product intent justifies reuse`,effort:"medium",impact:"medium",count:e.reactComponentDuplicates.count,locRecoverable:e.reactComponentDuplicates.loc}),e.reactHookCandidates.count>0&&t.push({category:"Duplicated React hook behavior",evidence:"heuristic",description:`${e.reactHookCandidates.count} React component pair(s) share state/effect/request behavior${hc(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${hc(e.vueComposableCandidates)} \u2014 review whether a common composable would preserve ownership and lifecycle semantics`,effort:"medium",impact:"medium",count:e.vueComposableCandidates.count,locRecoverable:e.vueComposableCandidates.loc}),e.vueLargeViewPressure.count>0&&t.push({category:"Large Vue views",evidence:"heuristic",description:`${e.vueLargeViewPressure.count} Vue file(s) concentrate template/script/style pressure \u2014 split by reason to change`,effort:"medium",impact:"medium",count:e.vueLargeViewPressure.count,locRecoverable:0}),e.extractCount>0&&t.push({category:"Extraction candidates",evidence:"heuristic",description:`${e.extractCount} large functions with isolated callee clusters \u2014 review same-file or feature-local extraction seams`,effort:"medium",impact:"medium",count:e.extractCount,locRecoverable:0}),e.wrappers.count>0&&t.push({category:"Wrapper functions",evidence:"heuristic",description:`${e.wrappers.count} single-consumer symbols${hc(e.wrappers,"boundary-evidence discount")} \u2014 inspect whether each is indirection or an intentional API, framework, or ownership boundary`,effort:"low",impact:"low",count:e.wrappers.count,locRecoverable:e.wrappers.loc}),e.passthroughs.count>0&&t.push({category:"Passthrough functions",evidence:"heuristic",description:`${e.passthroughs.count} functions that literally forward to one callee \u2014 inspect whether each is unnecessary indirection or an intentional boundary`,effort:"low",impact:"low",count:e.passthroughs.count,locRecoverable:e.passthroughs.loc}),e.stale.count>0){let i=[];e.stale.unused>0&&i.push(`${e.stale.unused} unused`),e.stale.singleUse>0&&i.push(`${e.stale.singleUse} single-consumer (not in types file)`),t.push({category:"Stale abstractions",evidence:"heuristic",description:`${i.join(", ")} \u2014 review public, runtime-registration, and ownership evidence before removing, moving, or inlining`,effort:"low",impact:"medium",count:e.stale.count,locRecoverable:e.stale.loc})}if(e.drift.count>0){let i=[];e.drift.unusedImports>0&&i.push(`${e.drift.unusedImports} unused imports`),e.drift.layerViolations>0&&i.push(`${e.drift.layerViolations} layer violations`),t.push({category:"Structural drift",evidence:"heuristic",description:`${i.join(", ")} \u2014 verify direct rows and review inferred layer signals against declared ownership`,effort:e.drift.layerViolations>0?"medium":"low",impact:e.drift.layerViolations>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 diff-gate\` or \`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`+hc({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 dR={"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 fR(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 F2(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),r=[],i=[],o=(v,E,I)=>{E>0&&r.push({axis:v,points:E,detail:I,kind:dR[v]??"hygiene"})},s=(v,E,I,k,F,te,Y)=>{let L=Math.max(k,1);if(I<=L)return;let oe=I/L,Q=Math.min(F,Math.ceil(Math.log2(oe)*te));if(Q<=0)return;let an=dR[v]??"hygiene";i.push({axis:v,category:E,kind:an,count:I,threshold:Mt(L),ratio:Mt(oe),extraPenalty:Q}),o(v,Q,`${I} ${Y} exceed pressure threshold ${Mt(L)} (${Mt(oe)}x)`)},a=e.dead.count/n;o("dead-code",Math.min(20,Math.round(a*200)),`${e.dead.count} dead symbols (${e.dead.loc} LOC deletable)`);let c=e.isolated.count/n;o("isolated",Math.min(10,Math.round(c*200)),`${e.isolated.count} isolated symbols (${e.isolated.loc} LOC deletable)`),o("cycles",Math.min(15,e.realCycleCount*5),`${e.realCycleCount} real dependency cycle(s)`);let l=e.similarCount/n*1e3;o("similar",Math.min(10,Math.round(l)),`${e.similarCount} similar function pair(s)`);let u=e.duplicateBodies.count/n*1e3;o("duplicate-bodies",Math.min(10,Math.round(u*2)),`${e.duplicateBodies.count} exact duplicate small-body group(s) (${e.duplicateBodies.loc} duplicate LOC)`);let d=e.twinDrift.count/n*1e3;o("twin-drift",Math.min(10,Math.round(d*2)),`${e.twinDrift.count} drifted twin implementation group(s) (same or near-same name, diverged or identical bodies)`);let f=e.reactComponentDuplicates.count/t*1e3;o("react-component-duplicates",Math.min(10,Math.round(f)),`${e.reactComponentDuplicates.count} duplicated React component pair(s)`);let m=sn(e.reactHookCandidates),p=m/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(p)),Mo(e.reactHookCandidates,"duplicated React behavior pair(s)"));let g=e.reactLargeComponentPressure.count/t*1e3;o("react-large-component-pressure",Math.min(5,Math.round(g/2)),`${e.reactLargeComponentPressure.count} large React component pressure file(s)`);let h=e.vueComponentDuplicates.count/t*1e3;o("vue-component-duplicates",Math.min(10,Math.round(h)),`${e.vueComponentDuplicates.count} duplicated Vue component pair(s)`);let S=sn(e.vueComposableCandidates),C=S/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(C)),Mo(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 b=sn(e.wrappers);o("wrappers",Math.min(3,b),Mo(e.wrappers,"wrapper candidate(s)"));let y=sn(e.passthroughs);o("passthroughs",Math.min(3,y),Mo(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 v=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(v/10)),Mo({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:v},"co-changing pair(s) without a structural link"))}if(s("cycles-pressure","Circular dependencies",e.realCycleCount,3,10,3,"cycle(s)"),s("complexity-pressure","Extreme complexity",e.complexity.extremeCount,3,5,2,"extreme complexity hotspot(s)"),e.gitEvidence){let v=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",v,50,10,4,"score-weighted co-changing pair(s)")}return s("similar-pressure","Similar functions",e.similarCount,Math.max(50,n*.01),8,4,"similar function pair(s)"),s("duplicate-bodies-pressure","Duplicate function bodies",e.duplicateBodies.count,Math.max(20,n*.005),8,4,"exact duplicate small-body group(s)"),s("twin-drift-pressure","Drifted twin implementations",e.twinDrift.count,Math.max(20,n*.005),8,4,"drifted twin implementation group(s)"),s("react-component-duplicates-pressure","Duplicated React components",e.reactComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated React component pair(s)"),s("react-hook-candidates-pressure","Duplicated React hook behavior",m,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",b,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",y,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 L2}from"v8";var N2=64*1024*1024;function $f(){let e=globalThis.gc;if(!e)return;let t=L2();t.heap_size_limit-t.used_heap_size<N2||e()}var A2=50,M2=25e3,O2=2500,gR=2500,hR=50,j2=10,yc=["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"],$2={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:W2(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:G2(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:z2(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:V2(e,t,n)}),"duplicate-bodies":(e,t,n)=>({phase:"duplicate-bodies",duplicateBodies:K2(e,t,n)}),"twin-drift":(e,t,n)=>({phase:"twin-drift",twinDrift:J2(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:Y2(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:X2(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:Q2(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:Z2(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:eJ(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:tJ(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:q2(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:nJ(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:rJ(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:iJ(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:cJ(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:lJ(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:oJ(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:sJ(e,n)}),"coverage-contracts":(e,t,n)=>({phase:"coverage-contracts",coverageContracts:aJ(e,n)})};function Bf(e,t,n={}){return B2(e,[t],n)[0]}function B2(e,t,n={}){return H2(e,n.full!==!1,(r,i)=>{let o={...i,releaseCachesBetweenPhases:!1};return t.map(s=>$2[s](e,n.scope,o,r))})}function H2(e,t,n){let r=rr(e),i=uJ(r,t);try{return n(r,i)}finally{kd(e,{semanticProvider:!0}),$f()}}function Hf(e){return mR(U2(e))}function U2(e){let t=pe(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,dead:pe(e,"dead").dead,isolated:pe(e,"isolated").isolated,realCycleCount:pe(e,"cycles").realCycleCount,similarCount:pe(e,"similar").similarCount,duplicateBodies:pe(e,"duplicate-bodies").duplicateBodies,twinDrift:pe(e,"twin-drift").twinDrift,reactComponentDuplicates:pe(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:pe(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:pe(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:pe(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:pe(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:pe(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:pe(e,"extract-candidates").extractCount,wrappers:pe(e,"wrapper-candidates").wrappers,passthroughs:pe(e,"passthrough-candidates").passthroughs,stale:pe(e,"stale-abstractions").stale,drift:pe(e,"drift").drift,complexity:pe(e,"complexity-hotspots").complexity,gitEvidence:yR(e,"git-evidence")?.gitEvidence??null,suppressions:yR(e,"suppressions")?.suppressions??null,coverageContracts:pe(e,"coverage-contracts").coverageContracts}}function yR(e,t){return e.find(n=>n.phase===t)}function pe(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function W2(e,t,n){return fe(e,n,"dead",()=>{let r=ir(e,{scope:t,...de.dead,scanLimit:n.candidateScanLimit,semantic:n.semantic});return bc(mJ(e,r.symbols))})}function G2(e,t,n){return fe(e,n,"isolated",()=>{let r=fo(e,{scope:t,...de.isolated,scanLimit:n.candidateScanLimit,semantic:n.semantic});return bc(pJ(e,r))})}function z2(e,t,n){return fe(e,n,"cycles",()=>uo(e,{scope:t}).filter(i=>i.kind==="real").length)}function V2(e,t,n){let r=fe(e,n,"similar",()=>Od(e,{scope:t,...de.similar,scanLimit:n.candidateScanLimit,semantic:n.semantic}));return Math.min(r,n.candidateResultLimit)}function q2(e,t,n){return fe(e,n,"extract-candidates",()=>bo(e,{scope:t,...de.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}).length)}function K2(e,t,n){return fe(e,n,"duplicate-bodies",()=>{let r=Do(e,{scope:t,...de.duplicateBodies,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),i=new Set,o=0;for(let s of r)for(let a of s.functions.slice(1))i.add(a.file),o+=a.loc;return{count:r.length,loc:o,files:[...i]}})}function J2(e,t,n){return fe(e,n,"twin-drift",()=>{let r=Qr(e,{scope:t,...de.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 Y2(e,t,n){return fe(e,n,"react-component-duplicates",()=>{let r=po(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Uf(r)})}function X2(e,t,n){return fe(e,n,"react-hook-candidates",()=>{let r=go(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return CR(r,hJ)})}function Q2(e,t,n){return fe(e,n,"react-large-component-pressure",()=>{let r=jd(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return gJ(r)})}function Z2(e,t,n){return fe(e,n,"vue-component-duplicates",()=>{let r=ho(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Uf(r)})}function eJ(e,t,n){return fe(e,n,"vue-composable-candidates",()=>{let r=yo(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return CR(r,yJ)})}function tJ(e,t,n){return fe(e,n,"vue-large-view-pressure",()=>{let r=$d(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return bc(r)})}function nJ(e,t,n){return fe(e,n,"wrapper-candidates",()=>{let r=Fo(e,{scope:t,...de.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return SR(r,bJ)})}function rJ(e,t,n){return fe(e,n,"passthrough-candidates",()=>{let r=Po(e,{scope:t,...de.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return SR(r,SJ)})}function iJ(e,t,n){return fe(e,n,"stale-abstractions",()=>{let r=_o(e,{scope:t,...de.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 oJ(e,t){return fe(e,t,"git-evidence",()=>{let n=qe(e,{historyMode:t.gitHistoryMode}),r=n.fileChurn();if(!r)return null;let i=n.commitHistory(),o=Co(e,void 0,{limit:t.candidateResultLimit,historyMode:t.gitHistoryMode}),s={};for(let[a,c]of r)s[a]={changes:c.changes,fixChanges:c.fixChanges};return{amplification:n.changeAmplification(),hiddenCoupling:{pairCount:o.findings.length,scoreCount:Wf(o.findings.reduce((a,c)=>a+bR(c),0)),top:o.findings.slice(0,5).map(a=>({fileA:a.fileA,fileB:a.fileB,together:a.together,confidence:a.confidence,focusedTogether:a.focusedTogether,broadTogether:a.broadTogether,broadCommitRatio:a.broadCommitRatio,lastTogetherAt:a.lastTogetherAt,recentTogether:a.recentTogether,commitScope:a.commitScope,recency:a.recency,scoreWeight:bR(a),subjectContext:a.subjectContext}))},fileStats:s,commitsScanned:i?.commits.length??0}})}function sJ(e,t){return fe(e,t,"suppressions",()=>{let n=mc(e);return{total:n.total,byCategory:{...n.byCategory}}})}function aJ(e,t){return fe(e,t,"coverage-contracts",()=>{let n=e.config.coverageContracts??[],i=hv(e,n).filter(o=>o.status!=="ok");return{count:i.length,loc:0,files:[...new Set(i.map(o=>o.file))].sort()}})}function cJ(e,t,n){return fe(e,n,"drift",()=>{let r=ko(e,{scope:t,...de.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,layerViolations:r.layerViolations,direct:o,signal:s}})}function lJ(e,t,n){return fe(e,n,"complexity-hotspots",()=>{let r=Of(e,{scope:t,minLoc:10,limit:n.complexityResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return{top:r.slice(0,5).map(i=>({symbol:i.shortName,score:i.score,file:i.file})),extremeCount:r.filter(i=>i.score>A2).length}})}function uJ(e,t){let n=e.symbols>=M2||e.documents>=O2,r=t?Number.POSITIVE_INFINITY:hR,i=t?Number.POSITIVE_INFINITY:j2;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:gR,candidateResultLimit:r,complexityResultLimit:i,semantic:!1,gitHistoryMode:"bounded",releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${gR} symbols and reported their top ${hR} findings. Enable full mode for unbounded candidate counts.`]}}function dJ(e,t){t.releaseCachesBetweenPhases&&(kd(e),$f())}function fe(e,t,n,r){fJ(n);try{return r()}finally{dJ(e,t)}}function fJ(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function mJ(e,t){return t.filter(n=>!De(e,n.relativePath)&&!ue(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function pJ(e,t){return t.filter(n=>!De(e,n.relativePath)&&!ue(e,n.symbol,n.relativePath))}function bc(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 SR(e,t){return{...bc(e),scoreCount:Wf(e.reduce((r,i)=>r+t(i),0))}}function gJ(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 Uf(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 CR(e,t){return{...Uf(e),scoreCount:Wf(e.reduce((r,i)=>r+t(i),0))}}function hJ(e){let t=e.sharedHooks.length>0,n=xR({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:vR(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function yJ(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=xR({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:vR(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function xR(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!IR.has(RR(t))).length+Math.min(e.functions.length,3)}function vR(e,t,n){let r=[...e,...t,...n].map(RR);return r.length>0&&r.every(i=>IR.has(i))}function RR(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function bJ(e){return e.actionTier==="signal"?.25:1}function SJ(e){return e.actionTier==="signal"?.25:1}function bR(e){return e.commitScope==="broad-sweep"?e.recency==="recent"?.25:0:e.commitScope==="mixed"?e.recency==="recent"?.5:.25:e.recency==="recent"?1:.5}function Wf(e){return Math.round(e*100)/100}var IR=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 CJ(e,t,n,r={}){let i=Md(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 xJ(e,t={}){let{scope:n,limit:r}=t,i=new _(e),o=PJ([...vJ(e,n),...wJ(e,i,n)]);return TJ(o),r?o.slice(0,r):o}function vJ(e,t){let n=[];for(let r of RJ(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||hd(e,r.barrel_path)||P(e,r.barrel_path)&&Cs(e,r.barrel_path).length===0)continue;let i=IJ(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:w(r.symbol),originalFile:r.original_path,barrelConsumers:o,directConsumers:s,...DR(e,r.barrel_path)})}return n}function RJ(e,t){let n=t?"AND barrel_d.relative_path LIKE ?":"",r=t?[`%${t}%`]:[];return e.all(`SELECT DISTINCT
856
- barrel_d.id AS barrel_doc_id,
857
- barrel_d.relative_path AS barrel_path,
858
- gs.id AS symbol_id,
859
- gs.symbol AS symbol,
860
- orig_d.id AS original_doc_id,
861
- orig_d.relative_path AS original_path
862
- FROM mentions m
863
- JOIN chunks c ON m.chunk_id = c.id
864
- JOIN documents barrel_d ON c.document_id = barrel_d.id
865
- JOIN global_symbols gs ON m.symbol_id = gs.id
866
- JOIN (
867
- SELECT m2.symbol_id, c2.document_id
868
- FROM mentions m2
869
- JOIN chunks c2 ON m2.chunk_id = c2.id
870
- WHERE m2.role = 1
871
- GROUP BY m2.symbol_id
872
- ) sym_def ON sym_def.symbol_id = gs.id
873
- JOIN documents orig_d ON sym_def.document_id = orig_d.id
874
- WHERE m.role != 1
875
- AND (barrel_d.relative_path LIKE '%/index.ts'
876
- OR barrel_d.relative_path LIKE '%/index.js'
877
- OR barrel_d.relative_path = 'index.ts'
878
- OR barrel_d.relative_path = 'index.js')
879
- AND orig_d.id != barrel_d.id
880
- ${e.pathExclusionsFor("barrel_d","orig_d")}
881
- ${e.symbolNoiseFor("gs")}
882
- -- Only function-level symbols (ending with ().), not module-level
883
- AND gs.symbol LIKE '%().'
884
- ${n}
885
- ORDER BY barrel_d.relative_path, gs.symbol`,...r)}function IJ(e,t){return e.get(`SELECT
886
- SUM(CASE WHEN uses_barrel = 1 THEN 1 ELSE 0 END) AS barrel_consumers,
887
- SUM(CASE WHEN uses_barrel = 0 THEN 1 ELSE 0 END) AS direct_consumers
888
- FROM (
889
- SELECT
890
- consumer_d.id AS consumer_doc_id,
891
- MAX(CASE WHEN EXISTS (
892
- SELECT 1
893
- FROM mentions barrel_m
894
- JOIN chunks barrel_c ON barrel_m.chunk_id = barrel_c.id
895
- WHERE barrel_c.document_id = consumer_d.id
896
- AND barrel_m.role != 1
897
- AND barrel_m.symbol_id IN (
898
- SELECT m2.symbol_id
899
- FROM mentions m2
900
- JOIN chunks c2 ON m2.chunk_id = c2.id
901
- WHERE c2.document_id = ?
902
- AND m2.role != 1
903
- )
904
- ) THEN 1 ELSE 0 END) AS uses_barrel
905
- FROM mentions ref_m
906
- JOIN chunks ref_c ON ref_m.chunk_id = ref_c.id
907
- JOIN documents consumer_d ON ref_c.document_id = consumer_d.id
908
- WHERE ref_m.symbol_id = ?
909
- AND ref_m.role != 1
910
- AND consumer_d.id != ?
911
- AND consumer_d.id != ?
912
- ${e.pathExclusionsFor("consumer_d")}
913
- GROUP BY consumer_d.id
914
- )`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function wJ(e,t,n){let r=[];for(let i of DJ(e,n))ER(e,i,i)>0||r.push(...EJ(e,t,i));return r}function DJ(e,t){return N(e,{scope:t,includeIgnored:!1}).filter(n=>Cs(e,n).length>0||zn(e,n).length>0)}function EJ(e,t,n){let r=Cs(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>wR(e,t,n,o.sourcePath,[kJ(o.specifier)])),i=zn(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>wR(e,t,n,o.sourcePath,o.kind==="named"&&o.names.length>0?o.names:[o.kind==="star"?`* from ${o.sourcePath}`:`* namespace from ${o.sourcePath}`]));return[...r,...i]}function wR(e,t,n,r,i){let o=t.definitionsForFile(r);return i.map(s=>{let a=o.find(c=>c.leaf===s);return{barrelFile:n,symbol:a?.symbol??`source-reexport:${n}:${s}`,shortName:a?w(a.symbol):s,originalFile:r,barrelConsumers:0,directConsumers:ER(e,r,n),...DR(e,n)}})}function kJ(e){return e.split("::").at(-1)?.split("/").at(-1)?.replace(/\.[^.]+$/,"")??e}function DR(e,t){return nr(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 ER(e,t,n){let r=new Set;for(let i of N(e,{includeIgnored:!1}))if(i!==n)for(let o of ne(e,i))o.sourcePath===t&&r.add(i);return r.size}function PJ(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 TJ(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function _J(e,t={}){let{samples:n=50,scope:r,maxDisagreements:i=5}=t,o=new _(e),s=FJ(o.productionCallableDefinitions({scope:r,minLoc:2,requireFunctionLikeSymbol:!0}),n),a=LJ(e,s);if(s.length===0||!a)return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let c={references:kR(),callees:kR()},l=[],u=0,d=a==="semantic"?ca(e,s):new Map,f=a==="source"?MJ(e,o,s):null;for(let m of s){let p=Sc(m,a==="semantic"?aa(e,m).map(b=>b.file):[...f?.referencesBySymbolId.get(m.symbolId)??[]]),g=Sc(m,a==="semantic"?(d.get(m.symbolId)??[]).map(b=>b.file):[...f?.calleesBySymbolId.get(m.symbolId)??[]]);u+=1;let h=Sc(m,kt(e,m).map(b=>b.file)),S=Sc(m,(o.calleeMap([m],{semantic:!1}).get(m.symbolId)??[]).map(b=>b.file)),C=Gf(a,"references"),x=Gf(a,"callees");PR(c.references,m,"references",h,p,C,l),PR(c.callees,m,"callees",S,g,x,l)}return l.sort((m,p)=>p.cheapOnly.length+p.oracleOnly.length-(m.cheapOnly.length+m.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?Vf(u/s.length):0,oracleKind:a,scores:["references","callees"].map(m=>AJ(m,c[m],a)),topDisagreements:l.slice(0,i)}}function kR(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0,skippedOraclePartial:0}}function FJ(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 LJ(e,t){let n=t[0];if(!n)return null;if(zf(e,n))return"source";try{if(Oe(e).capability("semantic-references",n.relativePath).available)return"semantic"}catch{}return t.some(r=>zf(e,r))?"source":null}function Sc(e,t){let n=new Set;for(let r of t)r!==e.relativePath&&n.add(r);return n}function PR(e,t,n,r,i,o,s){if(!o&&i.size===0){e.skippedOraclePartial+=1;return}e.comparedSymbols+=1,e.cheapTotal+=r.size,e.oracleTotal+=i.size;let a=[],c=[];for(let l of r)i.has(l)?e.agreed+=1:a.push(l);for(let l of i)r.has(l)||c.push(l);(a.length>0||c.length>0)&&s.push({symbol:w(t.symbol),question:n,cheapOnly:a,oracleOnly:c})}var NJ={references:!0,callees:!1};function AJ(e,t,n){let r=t.oracleTotal>0?t.agreed/t.oracleTotal:1,i=t.cheapTotal-t.agreed,o=Gf(n,e);return{question:e,comparedSymbols:t.comparedSymbols,precision:o&&t.cheapTotal>0?Vf(t.agreed/t.cheapTotal):null,recall:Vf(r),unverified:i,skippedOraclePartial:t.skippedOraclePartial}}function Gf(e,t){return e==="semantic"?NJ[t]:!1}function zf(e,t){return M(t.relativePath)==="clojure"&&W(e,t.relativePath)!==null}function MJ(e,t,n){let r=new Map,i=new Map,o=n.filter(c=>zf(e,c)),s=new Map;for(let c of o){let l=s.get(c.leaf)??[];l.push(c),s.set(c.leaf,l)}for(let c of t.sourceFiles()){if(M(c)!=="clojure")continue;let l=W(e,c);if(l)for(let u of l.fileIdentifiers)for(let d of s.get(u)??[])TR(r,d.symbolId,c)}let a=new Map;for(let c of t.scopedDefinitions()){if(M(c.relativePath)!=="clojure")continue;let l=a.get(c.leaf)??[];l.push(c),a.set(c.leaf,l)}for(let c of o){let l=W(e,c.relativePath);if(l){for(let u of l.callSites)if(!(u.line<c.startLine||u.line>c.endLine))for(let d of a.get(u.calleeLeaf)??[])TR(i,c.symbolId,d.relativePath)}}return{referencesBySymbolId:r,calleesBySymbolId:i}}function TR(e,t,n){let r=e.get(t);if(r){r.add(n);return}e.set(t,new Set([n]))}function Vf(e){return Math.round(e*1e3)/1e3}var OJ=new Set(_t());function jJ(e,t={}){let{scope:n,minLoc:r=1,limit:i,scanLimit:o,maxShapeFrequency:s=12}=t,a=t.semantic!==!1,c=HJ(e,$J(e,{scope:n,minLoc:r,scanLimit:o}),{semantic:a,maxShapeFrequency:s}),l=WJ(c);return i?l.slice(0,i):l}function $J(e,t){let n=ve(e,{scope:t.scope}).filter(r=>BJ(r)&&!e.isIgnored(r.relativePath)).filter(r=>O(r)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((r,i)=>O(i)-O(r)||r.relativePath.localeCompare(i.relativePath)),ie(n,t.scanLimit)}function BJ(e){return!e.isFunctionLike||Re(e.symbol)?!1:e.kind===null||OJ.has(e.kind)}function HJ(e,t,n){let r=[];for(let s of t){let a=zJ(e,s,n);a&&r.push({signature:a,definition:s,fn:UJ(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=GJ(s.fn.loc),c=(i.get(s.signature)??0)>n.maxShapeFrequency,l=c?hf(e,s.definition):null;if(c&&!l)continue;let u=c?`${s.signature}\0body\0${l}`:`${s.signature}\0band\0${a}`,d=o.get(u)??{signature:s.signature,locBand:a,exactBody:c,functions:[]};d.functions.push(s.fn),o.set(u,d)}return[...o.values()]}function UJ(e){return{symbol:e.symbol,shortName:w(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:O(e)}}function WJ(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 GJ(e){return e<=5?"<=5":e<=20?"6-20":">20"}function zJ(e,t,n){if(n.semantic){let o=Iy(e,t);if(o)return o}let r=VJ(t.documentation),i=r?JJ(r):null;return i||YJ(qJ(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function VJ(e){return Gt(zt(e))}function qJ(e,t,n,r,i){let o=P(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=QJ(s,n,r,i);for(let c of a){let l=Math.min(s.length-1,Math.max(c,c+4)),u="";for(let d=c;d<=l;d+=1){let f=s[d]?.trim();if(f&&(u=u?`${u} ${f}`:f,KJ(u)))return u}if(u&&u.includes("("))return u}return null}function KJ(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||xi(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function JJ(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 YJ(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${B(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=XJ(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 XJ(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 QJ(e,t,n,r){let i=B(r),o=new RegExp(`\\b${i}\\b\\s*\\(`,"i"),s=new RegExp(`\\bdef\\s+${i}\\b`,"i"),a=[],c=new Set,l=Math.max(0,Math.min(t,e.length-1)),u=Math.max(l,Math.min(e.length-1,Math.max(n,t+4)));for(let d=l;d<=u;d+=1){let f=e[d]??"";(o.test(f)||s.test(f))&&!c.has(d)&&(c.add(d),a.push(d))}for(let d=0;d<e.length;d+=1){let f=e[d]??"";(o.test(f)||s.test(f))&&!c.has(d)&&(c.add(d),a.push(d))}return a}import{spawn as eY,spawnSync as Xge}from"child_process";var ri=class extends Error{constructor(n,r){super(`${n} timed out after ${r}ms.`);this.label=n;this.timeoutMs=r}label;timeoutMs;timedOut=!0};function _R(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Cc(e){return new Promise((t,n)=>{let r=e.maxBuffer??10485760,i=eY(process.execPath,[...process.execArgv,e.cliPath,e.command,...e.args??[]],{cwd:process.cwd(),env:e.env??process.env,stdio:["ignore","pipe","pipe"]}),o=[],s=[],a=0,c=0,l=!1,u=e.timeoutMs&&e.timeoutMs>0?setTimeout(()=>d(new ri(e.label,e.timeoutMs)),e.timeoutMs):null,d=f=>{l||(l=!0,u&&clearTimeout(u),i.kill(),n(f))};i.stdout.on("data",f=>{if(a+=f.length,a>r){d(new Error(`${e.label} exceeded stdout buffer limit (${r} bytes).`));return}o.push(f)}),i.stderr.on("data",f=>{if(c+=f.length,c>r){d(new Error(`${e.label} exceeded stderr buffer limit (${r} bytes).`));return}s.push(f)}),i.on("error",d),i.on("close",f=>{if(l)return;l=!0,u&&clearTimeout(u);let m=Buffer.concat(s).toString("utf8").trim();if(f!==0){n(new Error(`${e.label} failed${m?`:
915
- ${m}`:""}`));return}try{t(JSON.parse(Buffer.concat(o).toString("utf8")))}catch(p){n(new Error(`${e.label} returned invalid JSON: ${p instanceof Error?p.message:p}`))}})})}async function qf(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 FR(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 tY}from"child_process";import{existsSync as nY,mkdirSync as rY,readFileSync as iY,renameSync as oY,writeFileSync as sY}from"fs";import{dirname as LR,join as aY}from"path";var xc=3,cY="health-report-cache.json";function Kf(e,t,n,r=fY()){let i=Te(e);return i?{version:xc,projectFingerprint:i,cliVersion:n,scope:t.scope??null,full:t.full===!0,phaseTimeoutMs:t.phaseTimeoutMs??null,gitHead:r.gitHead(e.config.projectRoot)}:null}function NR(e,t,n=jR()){let r=MR(e),i=OR(t),o=!1;return D("health.report-cache.read",()=>{if(!n.existsSync(r))return null;try{let s=JSON.parse(n.readFileSync(r,"utf8"));return!lY(s)||s.keyHash!==i?null:(o=!0,s.report)}catch{return null}},()=>({available:!0,hit:o,keyHash:i}))}function AR(e,t,n,r=jR()){let i=MR(e),o={version:xc,keyHash:OR(t),key:t,writtenAt:r.nowIso(),report:n};r.mkdirSync(LR(i),{recursive:!0});let s=`${i}.${process.pid}.${Date.now()}.tmp`;r.writeFileSync(s,JSON.stringify(o)),r.renameSync(s,i)}function MR(e){return aY(LR(e.config.dbPath),cY)}function OR(e){return ge(JSON.stringify(e))}function lY(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===xc&&typeof t.keyHash=="string"&&uY(t.key)&&typeof t.writtenAt=="string"&&dY(t.report)}function uY(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===xc&&typeof t.projectFingerprint=="string"&&typeof t.cliVersion=="string"&&(t.scope===null||typeof t.scope=="string")&&typeof t.full=="boolean"&&(t.phaseTimeoutMs===null||typeof t.phaseTimeoutMs=="number")&&(t.gitHead===null||typeof t.gitHead=="string")}function dY(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.detectorPrecision)}function fY(){return{gitHead(e){let t=tY("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"});return t.status===0?t.stdout.trim():null}}}function jR(){return{existsSync:nY,mkdirSync:rY,readFileSync:iY,renameSync:oY,writeFileSync:sY,nowIso:()=>new Date().toISOString()}}var HR="__health-phase",pY="__diff-impact-batch",gY=10,hY=4,yY=8,bY=25e3,SY=2500,Jf=2500,CY=4,xY=12,$R=3e4,UR=new Set(["react-component-duplicates","react-hook-candidates","react-large-component-pressure"]),WR=new Set(["vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure"]),vY=new Set([...WR,"suppressions"]),RY=new Set(["similar","extract-candidates"]),vc=2,BR=On({kind:"health-semantic-prewarm",invalidation:q("health-semantic-prewarm"),serialize:e=>JSON.stringify(e),deserialize:IY});function IY(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return n.version!==vc||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:vc,definitions:n.definitions,referenceCacheWrites:n.referenceCacheWrites,referenceIncomplete:n.referenceIncomplete,calleeRows:n.calleeRows,warmedAt:n.warmedAt}}catch{return null}}function GR(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
916
- `)}function wY(e){let t=rr(e);return t.symbols>=bY||t.documents>=SY}function zR(e,t,n,r={}){return wY(e)?n?(r.quiet||console.error(`Large index detected; ${t} is running the unbounded semantic pass because --full was supplied.`),{semantic:!0}):(r.quiet||console.error(`Large index detected; ${t} will scan the highest-priority ${Jf} candidates with semantic enrichment disabled. Run "scip-query ${t} --full" for the unbounded semantic pass.`),{scanLimit:Jf,semantic:!1,analysisBudget:{scanLimit:Jf,semanticEnrichment:!1,reason:"large index default budget; pass --full for unbounded semantic analysis"}}):{semantic:!0}}function vhe(e){return e?`analysis budget: scanning up to ${e.scanLimit} candidate(s); semantic enrichment=${e.semanticEnrichment}; ${e.reason}`:null}var DY={env:process.env,projectFingerprint:Te,semanticEngineFingerprint:TY,readMarker:(e,t,n)=>BR.read(e,t,n),writeMarker:(e,t,n,r)=>BR.write(e,t,n,r),candidateDefinitions:(e,t)=>new _(e).scopedDefinitions(t.scope).filter(n=>we(n.relativePath)!==null),materializeReferences:(e,t,n)=>Oe(e).materializeReferences(t,n),materializeCallees:WS};function EY(e,t,n=DY){if(t.full!==!0)return Fn("default-mode");if((n.env??process.env).SCIP_QUERY_HEALTH_SEMANTIC_PREWARM==="0")return Fn("disabled");let r=Fn("error");return D("health.semantic-prewarm",()=>{try{r=kY(e,t,n)}catch(i){r=Fn("error",{error:i instanceof Error?i.message:String(i)})}return r},()=>_Y(r))}function kY(e,t,n){let r=n.projectFingerprint(e);if(!r)return Fn("missing-project-fingerprint");let i=PY(t,n.semanticEngineFingerprint(e)),o=n.readMarker(e,i,r);if(o&&o.referenceIncomplete===0)return Fn("cache-hit");let s=[];if(s=D("health.semantic-prewarm.candidate-definitions",()=>(s=n.candidateDefinitions(e,t),s),()=>({definitions:s.length})),s.length===0)return Fn("no-semantic-definitions");let a=0,c=D("health.semantic-prewarm.references",()=>{let f=n.materializeReferences(e,s,{prefetchCallees:!0});return a=f.cacheHits+f.cacheWrites+f.inMemoryHits,f},()=>({definitions:s.length,rows:a}));if(c.cacheHits+c.cacheWrites+c.inMemoryHits===0&&c.misses+c.unkeyed>0)return Fn("provider-unavailable",{definitions:s.length,referenceMisses:c.misses});let u=0,d=D("health.semantic-prewarm.callees",()=>{let f=n.materializeCallees(e,s);return u=f.size,f},()=>({definitions:s.length,rows:u}));return c.incomplete>0?{status:"partial",reason:"incomplete-references",definitions:s.length,referenceCacheHits:c.cacheHits,referenceCacheWrites:c.cacheWrites,referenceMisses:c.misses,referenceIncomplete:c.incomplete,calleeRows:d.size}:(D("health.semantic-prewarm.marker-write",()=>n.writeMarker(e,i,r,{version:vc,definitions:s.length,referenceCacheWrites:c.cacheWrites,referenceIncomplete:c.incomplete,calleeRows:d.size,warmedAt:Date.now()})),{status:"warmed",reason:"cache-miss",definitions:s.length,referenceCacheHits:c.cacheHits,referenceCacheWrites:c.cacheWrites,referenceMisses:c.misses,referenceIncomplete:c.incomplete,calleeRows:d.size})}function PY(e,t){return JSON.stringify({version:vc,cliVersion:Xn,semanticEngineFingerprint:t,scope:e.scope??null})}function TY(e){return ge(JSON.stringify({kind:"health-semantic-prewarm-engine",rust:Kn(e.config.projectRoot)}))}function Fn(e,t={}){return{status:"skipped",reason:e,definitions:0,referenceCacheHits:0,referenceCacheWrites:0,referenceMisses:0,referenceIncomplete:0,calleeRows:0,...t}}function _Y(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}}async function Rhe(e){let t=OY(e),n={...e,phaseTimeoutMs:t??null},r=Yt(f=>{let m=Kf(f,n,Xn);if(!m)return null;let p=NR(f,m);return p?(p.detectorPrecision=jf(gc(f),Date.now()),p):null});if(r)return r;let{applicability:i,overview:o}=Yt(f=>({applicability:FY(f,e),overview:Bf(f,"overview",e)})),s=new Map;s.set("overview",o);let a=yc.filter(f=>f==="overview"?!1:LY(f,i)?!0:(s.set(f,cr(f)),!1)),c=NY(a);e.full&&Yt(f=>EY(f,e));let l=await qf(c,jY(c.length),f=>AY(f,e,t)),u=[];if(l.flat().forEach(f=>{f.healthPhaseMeta&&u.push(`Health phase "${f.phase}" deferred: ${f.healthPhaseMeta.reason}. Run health --full for exhaustive analysis.`),s.set(f.phase,f)}),u.length>0){let f=s.get("overview");s.set("overview",{...f,warnings:[...f.warnings,...u]})}let d=Hf(yc.map(f=>s.get(f)));return d.detectorPrecision=Yt(f=>jf(gc(f),Date.now())),Yt(f=>{let m=Kf(f,n,Xn);m&&AR(f,m,d)}),d}function FY(e,t){return ds(e,{scope:t.scope})}function LY(e,t){return UR.has(e)?t.react:WR.has(e)?t.vue:!0}function NY(e){return FR(e,[UR,vY,RY])}function cr(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 AY(e,t,n){if(e.length===1)return MY(e[0],t,n).then(s=>[s]);let r=e.join(","),i=process.argv[1]??Xf(import.meta.url),o=[r];return t.scope&&o.push("--scope",t.scope),t.full&&o.push("--full"),Cc({cliPath:i,command:HR,args:o,label:`Health phases "${r}"`,timeoutMs:n}).catch(s=>{if(t.full||!(s instanceof ri))throw s;return e.map(a=>VR(a,s.timeoutMs,`timed out after ${s.timeoutMs}ms`))})}function MY(e,t,n){let r=process.argv[1]??Xf(import.meta.url),i=[e];return t.scope&&i.push("--scope",t.scope),t.full&&i.push("--full"),Cc({cliPath:r,command:HR,args:i,label:`Health phase "${e}"`,timeoutMs:n}).catch(o=>{if(t.full||!(o instanceof ri))throw o;return VR(e,o.timeoutMs,`timed out after ${o.timeoutMs}ms`)})}function OY(e,t=process.env){if(e.full)return;let n=t.SCIP_QUERY_HEALTH_PHASE_TIMEOUT_MS;if(!n)return $R;let r=parseInt(n,10);return!Number.isFinite(r)||r<0?$R:r===0?void 0:r}function VR(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{...cr(e),...r};case"react-hook-candidates":return{...cr(e),...r};case"react-large-component-pressure":return{...cr(e),...r};case"vue-component-duplicates":return{...cr(e),...r};case"vue-composable-candidates":return{...cr(e),...r};case"vue-large-view-pressure":return{...cr(e),...r};case"extract-candidates":return{phase:e,extractCount:0,...r};case"wrapper-candidates":return{phase:e,wrappers:{count:0,loc:0,files:[]},...r};case"passthrough-candidates":return{phase:e,passthroughs:{count:0,loc:0,files:[]},...r};case"stale-abstractions":return{phase:e,stale:{count:0,loc:0,files:[],unused:0,singleUse:0},...r};case"drift":return{phase:e,drift:{count:0,unusedImports:0,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 jY=qR({envKey:"SCIP_QUERY_HEALTH_CONCURRENCY",defaultMinimum:CY,defaultMaximum:xY});function Ihe(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(console.log(`
917
- 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)
918
- `),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${bS(e.overview.indexSizeBytes)}
919
- `),e.warnings&&e.warnings.length>0){console.log(" Warnings:");for(let r of e.warnings)console.log(` ${r}`);console.log("")}console.log(" Findings:");let n=e.findings;if(n.deadSymbols>0&&console.log(` Dead code: ${n.deadSymbols} symbols (${n.deadLoc} LOC)`),n.isolatedSymbols>0&&console.log(` Isolated symbols: ${n.isolatedSymbols} (${n.isolatedLoc} LOC)`),n.cycles>0&&console.log(` Circular deps: ${n.cycles}`),n.similarPairs>0&&console.log(` Similar pairs: ${n.similarPairs}`),n.twinDriftGroups>0&&console.log(` Drifted twins: ${n.twinDriftGroups} group(s)`),n.reactComponentDuplicatePairs>0&&console.log(` React components: ${n.reactComponentDuplicatePairs} duplicate pair(s)`),n.reactHookCandidatePairs>0&&console.log(` React hook reuse: ${Yf(n.reactHookCandidatePairs,n.reactHookCandidateScoreCount)} candidate pair(s)`),n.reactLargeComponentPressureFiles>0&&console.log(` React large comps: ${n.reactLargeComponentPressureFiles} component(s)`),n.vueComponentDuplicatePairs>0&&console.log(` Vue components: ${n.vueComponentDuplicatePairs} duplicate pair(s)`),n.vueComposableCandidatePairs>0&&console.log(` Vue composables: ${Yf(n.vueComposableCandidatePairs,n.vueComposableCandidateScoreCount)} candidate pair(s)`),n.vueLargeViewPressureFiles>0&&console.log(` Vue large views: ${n.vueLargeViewPressureFiles} file(s)`),n.extractionCandidates>0&&console.log(` Extract candidates: ${n.extractionCandidates}`),n.wrappers>0&&console.log(` Wrapper functions: ${Yf(n.wrappers,n.wrapperScoreCount)}`),n.passthroughs>0&&console.log(` Passthroughs: ${n.passthroughs}`),n.staleTypes>0&&console.log(` Stale abstractions: ${n.staleTypes}`),n.driftedFiles>0&&console.log(` Pattern drift: ${n.driftedFiles} files`),n.complexityHotspotCount>0&&console.log(` Complexity hotspots: ${n.complexityHotspotCount}`),e.actions.length>0){console.log(`
920
- 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(`
921
- Top Complexity Hotspots:`);for(let r of e.topComplexity)console.log(` ${r.score.toFixed(1).padStart(6)} ${r.symbol}`)}if(HY(e),BY(e),e.scoreBreakdown.length>0){console.log(`
922
- 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?`
923
- No findings from completed analyses. Review warnings before interpreting this result as clean.`:`
924
- No issues found. Codebase is clean.`)}function Yf(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${$Y(t)} score-weighted)`}function $Y(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function BY(e){if(e.pressure.length!==0){console.log(`
925
- 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 HY(e){let t=e.axes;if(console.log(`
926
- 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 whe(e){let t=Yt(i=>{let o=_n(i,{base:e.base});return o.note?{kind:"complete",result:Yr(i,{base:e.base})}:o.changedFiles.length===0?{kind:"complete",result:Yr(i,{base:e.base})}:{kind:"batched",plan:o}});if(t.kind==="complete")return t.result;let n=_R(t.plan.changedFiles,gY),r=await qf(n,UY(n.length),i=>zY(i,e));return Ya(t.plan.changedFiles,r)}var UY=qR({envKey:"SCIP_QUERY_DIFF_IMPACT_CONCURRENCY",defaultMinimum:hY,defaultMaximum:yY});function qR(e){return(t,n=process.env,r=mY)=>WY(t,n,r,e)}function WY(e,t,n,r){let i=t[r.envKey],o=GY(n,r),s=i?parseInt(i,10):o;return!Number.isFinite(s)||s<1?Math.min(o,e):Math.min(s,e)}function GY(e,t){let n=e(),r=Number.isFinite(n)?Math.max(t.defaultMinimum,n-1):0;return Math.min(t.defaultMaximum,Math.max(t.defaultMinimum,r))}function zY(e,t){let n=process.argv[1]??Xf(import.meta.url),r=[];return t.base&&r.push("--base",t.base),Cc({cliPath:n,command:pY,args:r,env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch"})}function Dhe(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}`);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:"),Tt.list(e.changedSymbols,n=>` ${n.file} ${n.shortName} (fan-in: ${n.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
927
- Affected consumer files:`),Tt.list(e.affectedConsumers,n=>` ${n.file} (${n.consumedSymbols} symbol(s))`))}var KR=Symbol("option-value-source"),JR=new Map;function Fhe(e){JR=new Map(e)}function Oo(e){return(...t)=>{let{args:n,opts:r}=QY(t);Yt(i=>e({db:i,args:n,opts:r}))}}function Ic(e,t){return Oo(n=>{let r=zR(n.db,e,Rc(n.opts,"full"),{quiet:Rc(n.opts,"json")});t({...n,budget:r})})}function Lhe(e){return Oo(t=>ii(t,e,{kind:"list"}))}function Nhe(e){return Oo(t=>ii(t,e,{kind:"table",headers:e.headers,dashWidths:e.dashWidths}))}function Ahe(e){return Oo(t=>ii(t,e,{kind:"grouped",key:e.key}))}function VY(e){return Oo(t=>Qf(t,e))}function Mhe(e){return VY({commandName:e.commandName,query:e.query,emptyMessage:e.emptyMessage,heuristicLabel:e.heuristicLabel,before:e.before,render:(t,n)=>Tt.sectionedReport(e.sections(t,n)),toJson:e.toJson,after:e.after})}function qY(e,t){return Ic(e,n=>Qf(n,{...t,commandName:t.commandName??e}))}function Ohe(e,t){return qY(e,{commandName:t.commandName??e,query:t.query,emptyMessage:t.emptyMessage,heuristicLabel:t.heuristicLabel,before:t.before,render:(n,r)=>Tt.sectionedReport(t.sections(n,r)),toJson:t.toJson,after:t.after})}function jhe(e,t){return Ic(e,n=>ii(n,{...t,commandName:e},{kind:"list"}))}function $he(e,t){return Ic(e,n=>ii(n,{...t,commandName:e},{kind:"table",headers:t.headers,dashWidths:t.dashWidths}))}function Bhe(e,t){return Ic(e,n=>ii(n,{...t,commandName:e},{kind:"grouped",key:t.key}))}function Hhe(e,t){return String(e[t])}function Uhe(e,t){let n=e[t];return typeof n=="string"?n:void 0}function Whe(e,t){let n=e[t];return typeof n=="string"?n:void 0}function YR(e,t){let n=e[t];return typeof n=="number"?n:void 0}function Rc(e,t){return!!e[t]}function Ghe(e,t){let n=e[t];return Array.isArray(n)&&n.every(r=>typeof r=="string")?n:[]}function zhe(e,t,n){return YR(e,t)??n}function Vhe(e,t,n){let r=YR(e,t),i=r!==void 0&&KY(e,t)!=="default";if(Rc(e,"full")){if(i)throw new Error("--full cannot be combined with --limit. Use --full for all findings, or --limit N for a capped report.");return Number.MAX_SAFE_INTEGER}return r??n}function KY(e,t){return e[KR]?.(t)}function ii(e,t,n){Qf(e,{commandName:t.commandName,query:t.query,emptyMessage:(r,i)=>r.length===0&&t.emptyMessage?t.emptyMessage(i):void 0,heuristicLabel:t.heuristicLabel,render:(r,i)=>{n.kind==="list"?Tt.list(r,o=>t.format(o,i)):n.kind==="table"?Tt.table(n.headers,r.map(o=>t.format(o,i)),n.dashWidths):Tt.groupedByFile(r,o=>t.format(o,i),n.key?o=>n.key(o,i):void 0)},toJson:t.toJson,before:t.before,after:t.after})}function Qf(e,t){let n=t.query(e);if(Rc(e.opts,"json")){YY(t.commandName,e.args,e.opts,t.toJson?t.toJson(n,e):n,{analysisBudget:JY(e)});return}let r=t.emptyMessage?.(n,e);if(r){Tt.empty(r);return}t.heuristicLabel&&GR(t.heuristicLabel),t.before?.(n,e),t.render(n,e),t.after?.(n,e)}function JY(e){return e.budget?.analysisBudget}function YY(e,t,n,r,i={}){let o=e?JR.get(e):void 0;console.log(JSON.stringify({command:e,...o?{evidence:o}:{},...i.analysisBudget?{analysisBudget:i.analysisBudget}:{},args:XY(t),options:n,result:r},null,2))}function XY(e){return e.filter(t=>typeof t=="string"||typeof t=="number"||typeof t=="boolean")}function QY(e){if(e.length===0)return{args:[],opts:{}};let t=e[e.length-1];return{args:e.slice(0,-1),opts:ZY(t)}}function ZY(e){if(!e||typeof e!="object")return{};let t=e;if(typeof t.opts=="function"){let n=t.opts();return!n||typeof n!="object"?{}:(typeof t.getOptionValueSource=="function"&&Object.defineProperty(n,KR,{value:r=>t.getOptionValueSource(r),enumerable:!1}),n)}return e}export{Te as a,c5 as b,N as c,tQ as d,xr as e,Ze as f,xe as g,H as h,vm as i,Rm as j,Im as k,yI as l,D as m,g5 as n,un as o,B as p,at as q,V5 as r,q5 as s,V as t,wE as u,CQ as v,xp as w,F8 as x,se as y,w as z,T as A,X as B,ve as C,$ as D,wi as E,pZ as F,Lg as G,Ls as H,Ag as I,As as J,YZ as K,A_ as L,XZ as M,Og as N,QZ as O,Ms as P,Ae as Q,he as R,$s as S,nF as T,Jl as U,ki as V,e6 as W,x5 as X,fr as Y,Pm as Z,v5 as _,Bo as $,Ke as aa,zc as ba,VI as ca,A5 as da,XI as ea,M5 as fa,zo as ga,O5 as ha,QI as ia,j5 as ja,li as ka,$5 as la,B5 as ma,Fr as na,Lr as oa,Dt as pa,jh as qa,pL as ra,Xs as sa,Qh as ta,my as ua,e7 as va,hN as wa,t7 as xa,ra as ya,w7 as za,ao as Aa,_t as Ba,$S as Ca,ure as Da,rr as Ea,tj as Fa,sj as Ga,mee as Ha,xd as Ia,vd as Ja,Rd as Ka,Id as La,wd as Ma,ir as Na,o$ as Oa,c$ as Pa,l$ as Qa,u$ as Ra,Ree as Sa,R$ as Ta,D$ as Ua,E$ as Va,k$ as Wa,T$ as Xa,_$ as Ya,F$ as Za,SC as _a,N$ as $a,fo as ab,O$ as bb,j$ as cb,z$ as db,J$ as eb,_d as fb,Ba as gb,Md as hb,mo as ib,$B as jb,po as kb,go as lb,jd as mb,ho as nb,yo as ob,$d as pb,_1 as qb,bo as rb,OH as sb,qd as tb,Kd as ub,hU as vb,Nt as wb,Co as xb,_n as yb,Ax as zb,CG as Ab,Do as Bb,BG as Cb,ko as Db,Po as Eb,_o as Fb,Fo as Gb,UV as Hb,If as Ib,Df as Jb,kf as Kb,yde as Lb,aq as Mb,cq as Nb,lq as Ob,uq as Pb,Gq as Qb,zq as Rb,Zq as Sb,mK as Tb,CK as Ub,OK as Vb,Nf as Wb,Mf as Xb,pc as Yb,g2 as Zb,Of as _b,Fme as $b,Lme as ac,ni as bc,gc as cc,Nme as dc,yc as ec,Bf as fc,B2 as gc,CJ as hc,Tee as ic,xJ as jc,_J as kc,jJ as lc,da as mc,Hy as nc,Yy as oc,Xy as pc,Gee as qc,zee as rc,Qy as sc,pa as tc,Mu as uc,Zy as vc,Vee as wc,qee as xc,Kee as yc,Vi as zc,ub as Ac,ite as Bc,Ki as Cc,mb as Dc,Xn as Ec,$u as Fc,Bu as Gc,Ite as Hc,wte as Ic,Dte as Jc,Ete as Kc,Nte as Lc,Ate as Mc,Mte as Nc,Ote as Oc,qte as Pc,Zte as Qc,ene as Rc,Ea as Sc,aS as Tc,cS as Uc,tr as Vc,lS as Wc,id as Xc,vne as Yc,od as Zc,ud as _c,hS as $c,Fne as ad,yS as bd,Lne as cd,Nne as dd,Ane as ed,Yt as fd,Mne as gd,bS as hd,One as id,SS as jd,D0 as kd,$ne as ld,Bne as md,Tt as nd,HR as od,pY as pd,GR as qd,zR as rd,vhe as sd,Rhe as td,Ihe as ud,whe as vd,Dhe as wd,Fhe as xd,Oo as yd,Ic as zd,Lhe as Ad,Nhe as Bd,Ahe as Cd,VY as Dd,Mhe as Ed,qY as Fd,Ohe as Gd,jhe as Hd,$he as Id,Bhe as Jd,Hhe as Kd,Uhe as Ld,Whe as Md,YR as Nd,Rc as Od,Ghe as Pd,zhe as Qd,Vhe as Rd,KY as Sd,YY as Td,QY as Ud,ZY as Vd};
928
- //# sourceMappingURL=chunk-6AITNECC.js.map