scip-query 0.9.0 → 0.10.1

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 (263) hide show
  1. package/README.md +115 -58
  2. package/dist/augment-vue-worker.js +1 -1
  3. package/dist/chunk-23FVN4Y5.js +2 -0
  4. package/dist/chunk-24PFLKFK.js +2 -0
  5. package/dist/{chunk-VTF5EH22.js → chunk-27KPKLRJ.js} +2 -2
  6. package/dist/chunk-2NLK4INB.js +2 -0
  7. package/dist/{chunk-TA4DDU7J.js → chunk-2XKAMW6B.js} +2 -2
  8. package/dist/{chunk-PE4EJOLN.js → chunk-332L7SRO.js} +2 -2
  9. package/dist/chunk-44JOJLMO.js +38 -0
  10. package/dist/{chunk-U254PV4S.js → chunk-4EAANIWC.js} +2 -2
  11. package/dist/{chunk-ITUU3VE3.js → chunk-4N7LFYSD.js} +2 -2
  12. package/dist/{chunk-7I6KNKE3.js → chunk-5ALI77D7.js} +2 -2
  13. package/dist/{chunk-V76FCF5F.js → chunk-5BZOSICN.js} +2 -2
  14. package/dist/{chunk-RIXOMSOR.js → chunk-5D3BT4B4.js} +2 -2
  15. package/dist/{chunk-YSSTUCNS.js → chunk-5HDYAOSF.js} +2 -2
  16. package/dist/{chunk-NK7TQQG4.js → chunk-5IDEQEM4.js} +2 -2
  17. package/dist/{chunk-AGW2MVIO.js → chunk-5VB3WU7K.js} +2 -2
  18. package/dist/chunk-623UQCVG.js +2 -0
  19. package/dist/chunk-62NMBOA5.js +2 -0
  20. package/dist/chunk-64LH2QUP.js +62 -0
  21. package/dist/{chunk-PG3ZI5IH.js → chunk-65UWNXEH.js} +1 -1
  22. package/dist/{chunk-NGLRXEWN.js → chunk-6TWFT4Y5.js} +2 -2
  23. package/dist/chunk-6U4EODW3.js +2 -0
  24. package/dist/{chunk-SDGCKEB7.js → chunk-6YKJSETN.js} +2 -2
  25. package/dist/chunk-A2GVUCZR.js +8 -0
  26. package/dist/{chunk-WEJYUS5O.js → chunk-ADKQX2OY.js} +2 -2
  27. package/dist/{chunk-I7OTKWNY.js → chunk-ADTG377O.js} +2 -2
  28. package/dist/chunk-ATGRITZP.js +20 -0
  29. package/dist/chunk-B3HMRQDA.js +2 -0
  30. package/dist/chunk-B75HZHUP.js +2 -0
  31. package/dist/chunk-BGBBVSH4.js +2 -0
  32. package/dist/chunk-BJ7OHKB5.js +2 -0
  33. package/dist/{chunk-VN6B6HFB.js → chunk-CCB45WDY.js} +2 -2
  34. package/dist/chunk-CFLYMEUS.js +2 -0
  35. package/dist/chunk-CMGOXDVP.js +22 -0
  36. package/dist/chunk-DBIG4QAJ.js +2 -0
  37. package/dist/{chunk-RCRK4E7E.js → chunk-DMLPJ75B.js} +2 -2
  38. package/dist/chunk-DRU74YUM.js +71 -0
  39. package/dist/chunk-DTERBKUE.js +7 -0
  40. package/dist/{chunk-EKP7XJ6L.js → chunk-E55WCTLH.js} +2 -2
  41. package/dist/{chunk-ZJ737ZMD.js → chunk-F4PKYBQB.js} +2 -2
  42. package/dist/{chunk-HDA2V5DC.js → chunk-FVX4GEAC.js} +2 -2
  43. package/dist/{chunk-TR5AU6A5.js → chunk-GTNPPGZJ.js} +2 -2
  44. package/dist/{chunk-TFO4OMJZ.js → chunk-GZXXBDJA.js} +2 -2
  45. package/dist/chunk-HCQ7J2N5.js +3 -0
  46. package/dist/chunk-HQHFMPLJ.js +2 -0
  47. package/dist/{chunk-D43L5PQF.js → chunk-I6PTB2CM.js} +2 -2
  48. package/dist/{chunk-VHENVDS2.js → chunk-IJYWCB57.js} +2 -2
  49. package/dist/chunk-JTRY2YRJ.js +2 -0
  50. package/dist/chunk-L77GXANO.js +6 -0
  51. package/dist/{chunk-UUDYI3FF.js → chunk-LT6GJ27X.js} +2 -2
  52. package/dist/chunk-LUBKUISI.js +2 -0
  53. package/dist/{chunk-VQGQHIAT.js → chunk-LVYXX7ZW.js} +2 -2
  54. package/dist/{chunk-3YQO3S5D.js → chunk-LWPEZ4FP.js} +2 -2
  55. package/dist/chunk-LWWZBABT.js +2 -0
  56. package/dist/chunk-LXM7AHQG.js +4 -0
  57. package/dist/chunk-LY6NRJPJ.js +2 -0
  58. package/dist/chunk-LYS4SMAQ.js +2 -0
  59. package/dist/{chunk-7TYJD45F.js → chunk-MESUJJVQ.js} +2 -2
  60. package/dist/{chunk-6HP3BKIP.js → chunk-MHAQXOZY.js} +2 -2
  61. package/dist/chunk-N2T2GPYQ.js +2 -0
  62. package/dist/chunk-OB6PEVI3.js +2 -0
  63. package/dist/chunk-PNN3D4BE.js +2 -0
  64. package/dist/{chunk-46ILZVMX.js → chunk-PV4CEDIL.js} +2 -2
  65. package/dist/chunk-QH5GTVVB.js +3 -0
  66. package/dist/{chunk-WC43FMAB.js → chunk-QOFKVNFE.js} +2 -2
  67. package/dist/chunk-QUKZ77A6.js +4 -0
  68. package/dist/chunk-R42LZMLX.js +2 -0
  69. package/dist/{chunk-GD7XRHSV.js → chunk-R7S3UCDR.js} +2 -2
  70. package/dist/chunk-RGDUIMNE.js +3 -0
  71. package/dist/{chunk-TCCUWKH4.js → chunk-RNLUCQJB.js} +2 -2
  72. package/dist/chunk-RYBMW2EN.js +2 -0
  73. package/dist/{chunk-6ZFKI5EP.js → chunk-SA6B3EGD.js} +2 -2
  74. package/dist/chunk-T67R7V5I.js +2 -0
  75. package/dist/chunk-TMS4JPWY.js +3 -0
  76. package/dist/chunk-TTGWDUJ4.js +5 -0
  77. package/dist/chunk-TUAPDKBI.js +2 -0
  78. package/dist/chunk-UVK3SL4Z.js +2 -0
  79. package/dist/chunk-W3PQRAI4.js +2 -0
  80. package/dist/{chunk-LBAMALDV.js → chunk-WWFBDM5Y.js} +2 -2
  81. package/dist/{chunk-AQYBOORI.js → chunk-WZVTADY7.js} +1 -1
  82. package/dist/chunk-XGGTESMN.js +2 -0
  83. package/dist/{chunk-2DVVHNC3.js → chunk-Y33GRQK6.js} +2 -2
  84. package/dist/{chunk-BCFED24F.js → chunk-YIE5FZAF.js} +2 -2
  85. package/dist/chunk-YISMWW66.js +7 -0
  86. package/dist/chunk-YVQUQIBM.js +5 -0
  87. package/dist/{chunk-Z2AJQ7VA.js → chunk-YYCQQBMG.js} +2 -2
  88. package/dist/cli.js +240 -232
  89. package/dist/{config-types-CGIeLEpY.d.ts → config-types-Bok4jrO3.d.ts} +29 -1
  90. package/dist/{db-DdTPetj5.d.ts → db-BkFlkzI3.d.ts} +1 -1
  91. package/dist/{health-C6r2VgpA.d.ts → health-CbGMdRPg.d.ts} +42 -3
  92. package/dist/index.d.ts +7 -6
  93. package/dist/index.js +1 -1
  94. package/dist/postinstall.js +2 -2
  95. package/dist/queries/affected.d.ts +2 -2
  96. package/dist/queries/affected.js +1 -1
  97. package/dist/queries/bottlenecks.d.ts +2 -2
  98. package/dist/queries/bottlenecks.js +1 -1
  99. package/dist/queries/by-kind.d.ts +2 -2
  100. package/dist/queries/by-kind.js +1 -1
  101. package/dist/queries/call-graph.d.ts +2 -2
  102. package/dist/queries/call-graph.js +1 -1
  103. package/dist/queries/change-surface.d.ts +2 -2
  104. package/dist/queries/change-surface.js +1 -1
  105. package/dist/queries/cleanup-plan.d.ts +2 -2
  106. package/dist/queries/cleanup-plan.js +1 -1
  107. package/dist/queries/co-change.d.ts +5 -4
  108. package/dist/queries/co-change.js +1 -1
  109. package/dist/queries/code.d.ts +2 -2
  110. package/dist/queries/code.js +1 -1
  111. package/dist/queries/complexity-hotspots.d.ts +2 -2
  112. package/dist/queries/complexity-hotspots.js +1 -1
  113. package/dist/queries/complexity.d.ts +2 -2
  114. package/dist/queries/complexity.js +1 -1
  115. package/dist/queries/convergence.d.ts +2 -2
  116. package/dist/queries/convergence.js +1 -1
  117. package/dist/queries/coupling.d.ts +2 -2
  118. package/dist/queries/coupling.js +1 -1
  119. package/dist/queries/cycles.d.ts +2 -2
  120. package/dist/queries/cycles.js +1 -1
  121. package/dist/queries/dataflow.d.ts +2 -2
  122. package/dist/queries/dataflow.js +1 -1
  123. package/dist/queries/dead.d.ts +2 -2
  124. package/dist/queries/dead.js +1 -1
  125. package/dist/queries/deep-chains.d.ts +2 -2
  126. package/dist/queries/deep-chains.js +1 -1
  127. package/dist/queries/deps.d.ts +2 -2
  128. package/dist/queries/deps.js +1 -1
  129. package/dist/queries/diff-gate.d.ts +25 -3
  130. package/dist/queries/diff-gate.js +1 -1
  131. package/dist/queries/diff-impact.d.ts +20 -4
  132. package/dist/queries/diff-impact.js +1 -1
  133. package/dist/queries/doc-drift.d.ts +2 -2
  134. package/dist/queries/doc-drift.js +1 -1
  135. package/dist/queries/drift.d.ts +2 -2
  136. package/dist/queries/drift.js +1 -1
  137. package/dist/queries/extract-candidates.d.ts +2 -2
  138. package/dist/queries/extract-candidates.js +1 -1
  139. package/dist/queries/fan.d.ts +2 -2
  140. package/dist/queries/fan.js +1 -1
  141. package/dist/queries/files.d.ts +2 -2
  142. package/dist/queries/files.js +1 -1
  143. package/dist/queries/health.d.ts +3 -3
  144. package/dist/queries/health.js +1 -1
  145. package/dist/queries/hierarchy.d.ts +2 -2
  146. package/dist/queries/hierarchy.js +1 -1
  147. package/dist/queries/hotspots.d.ts +2 -2
  148. package/dist/queries/hotspots.js +1 -1
  149. package/dist/queries/imports.d.ts +2 -2
  150. package/dist/queries/imports.js +1 -1
  151. package/dist/queries/incomplete-migration.d.ts +4 -2
  152. package/dist/queries/incomplete-migration.js +1 -1
  153. package/dist/queries/index.d.ts +11 -5
  154. package/dist/queries/index.js +1 -1
  155. package/dist/queries/isolated.d.ts +2 -2
  156. package/dist/queries/isolated.js +1 -1
  157. package/dist/queries/members.d.ts +2 -2
  158. package/dist/queries/members.js +1 -1
  159. package/dist/queries/methods.d.ts +2 -2
  160. package/dist/queries/methods.js +1 -1
  161. package/dist/queries/outline.d.ts +2 -2
  162. package/dist/queries/outline.js +1 -1
  163. package/dist/queries/passthrough-candidates.d.ts +2 -2
  164. package/dist/queries/passthrough-candidates.js +1 -1
  165. package/dist/queries/plan-context.d.ts +2 -2
  166. package/dist/queries/plan-context.js +1 -1
  167. package/dist/queries/react-component-duplicates.d.ts +31 -0
  168. package/dist/queries/react-component-duplicates.js +2 -0
  169. package/dist/queries/react-hook-candidates.d.ts +34 -0
  170. package/dist/queries/react-hook-candidates.js +2 -0
  171. package/dist/queries/react-large-component-pressure.d.ts +28 -0
  172. package/dist/queries/react-large-component-pressure.js +2 -0
  173. package/dist/queries/recent-duplicates.d.ts +10 -3
  174. package/dist/queries/recent-duplicates.js +1 -1
  175. package/dist/queries/redundant-reexports.d.ts +2 -2
  176. package/dist/queries/redundant-reexports.js +1 -1
  177. package/dist/queries/refs.d.ts +2 -2
  178. package/dist/queries/refs.js +1 -1
  179. package/dist/queries/self-audit.d.ts +2 -2
  180. package/dist/queries/self-audit.js +1 -1
  181. package/dist/queries/similar-chains.d.ts +2 -2
  182. package/dist/queries/similar-chains.js +1 -1
  183. package/dist/queries/similar-files.d.ts +2 -2
  184. package/dist/queries/similar-files.js +1 -1
  185. package/dist/queries/similar-signatures.d.ts +2 -2
  186. package/dist/queries/similar-signatures.js +1 -1
  187. package/dist/queries/similar.d.ts +8 -3
  188. package/dist/queries/similar.js +1 -1
  189. package/dist/queries/slice.d.ts +2 -2
  190. package/dist/queries/slice.js +1 -1
  191. package/dist/queries/stale-abstractions.d.ts +2 -2
  192. package/dist/queries/stale-abstractions.js +1 -1
  193. package/dist/queries/stats.d.ts +2 -2
  194. package/dist/queries/stats.js +1 -1
  195. package/dist/queries/surface.d.ts +2 -2
  196. package/dist/queries/surface.js +1 -1
  197. package/dist/queries/symbols.d.ts +2 -2
  198. package/dist/queries/symbols.js +1 -1
  199. package/dist/queries/system.d.ts +2 -2
  200. package/dist/queries/system.js +1 -1
  201. package/dist/queries/trace.d.ts +2 -2
  202. package/dist/queries/trace.js +1 -1
  203. package/dist/queries/unused-params.d.ts +2 -2
  204. package/dist/queries/unused-params.js +1 -1
  205. package/dist/queries/vue-component-duplicates.d.ts +35 -0
  206. package/dist/queries/vue-component-duplicates.js +2 -0
  207. package/dist/queries/vue-composable-candidates.d.ts +34 -0
  208. package/dist/queries/vue-composable-candidates.js +2 -0
  209. package/dist/queries/vue-large-view-pressure.d.ts +31 -0
  210. package/dist/queries/vue-large-view-pressure.js +2 -0
  211. package/dist/queries/wrapper-candidates.d.ts +2 -2
  212. package/dist/queries/wrapper-candidates.js +1 -1
  213. package/dist/reindex-worker.js +10 -10
  214. package/dist/reindex.d.ts +1 -1
  215. package/dist/reindex.js +22 -22
  216. package/dist/runtime.d.ts +1 -1
  217. package/dist/runtime.js +2 -2
  218. package/docs/AGENT_GUIDE.md +353 -0
  219. package/docs/AI_FAILURE_MODES.md +278 -0
  220. package/docs/API.md +40 -0
  221. package/docs/COMMAND_REFERENCE.md +130 -0
  222. package/docs/DETECTOR_GUIDE.md +119 -0
  223. package/docs/accuracy-hardening-goal.md +54 -0
  224. package/docs/assets/scip-query-logo-dark.svg +21 -0
  225. package/docs/assets/scip-query-logo.svg +24 -0
  226. package/package.json +31 -3
  227. package/skills/scip-maintainability/SKILL.md +24 -3
  228. package/skills/scip-query/SKILL.md +2 -1
  229. package/skills/scip-react-maintainability/SKILL.md +114 -0
  230. package/skills/scip-vue-maintainability/SKILL.md +130 -0
  231. package/dist/chunk-2Y2WIJI4.js +0 -2
  232. package/dist/chunk-44G4P3GJ.js +0 -2
  233. package/dist/chunk-64UY7VTR.js +0 -63
  234. package/dist/chunk-6G76D2YM.js +0 -2
  235. package/dist/chunk-APLCSDXL.js +0 -4
  236. package/dist/chunk-CVRXOP6M.js +0 -3
  237. package/dist/chunk-EAU4RDFG.js +0 -2
  238. package/dist/chunk-FYT2PE7C.js +0 -2
  239. package/dist/chunk-I66MQD5U.js +0 -2
  240. package/dist/chunk-IBM6FXOQ.js +0 -3
  241. package/dist/chunk-JTCEWV7Q.js +0 -2
  242. package/dist/chunk-K3V6XUTL.js +0 -2
  243. package/dist/chunk-L6TOEQ2M.js +0 -2
  244. package/dist/chunk-LR7E2ATW.js +0 -8
  245. package/dist/chunk-MX6F756F.js +0 -2
  246. package/dist/chunk-NM3BZXHA.js +0 -2
  247. package/dist/chunk-NO2TPMCQ.js +0 -2
  248. package/dist/chunk-OMNT7E2T.js +0 -4
  249. package/dist/chunk-PBGTMPJ7.js +0 -2
  250. package/dist/chunk-PCMVXWDC.js +0 -34
  251. package/dist/chunk-PLFYFZX3.js +0 -2
  252. package/dist/chunk-R3G6ERW7.js +0 -7
  253. package/dist/chunk-SEZZ24IG.js +0 -2
  254. package/dist/chunk-SLX5XBCD.js +0 -7
  255. package/dist/chunk-SOGLYIJ4.js +0 -62
  256. package/dist/chunk-SQ6VENQY.js +0 -6
  257. package/dist/chunk-T4AK46CM.js +0 -16
  258. package/dist/chunk-TH4JVC34.js +0 -71
  259. package/dist/chunk-TQTVM27C.js +0 -6
  260. package/dist/chunk-VDZL45XI.js +0 -2
  261. package/dist/chunk-WQFOZIID.js +0 -4
  262. package/dist/chunk-Y3RUPPIU.js +0 -2
  263. package/dist/chunk-YO6DU7QZ.js +0 -2
package/dist/cli.js CHANGED
@@ -1,20 +1,43 @@
1
1
  #!/usr/bin/env node
2
- import{program as ki}from"commander";import{realpathSync as xd}from"fs";import{fileURLToPath as __}from"url";import{createRequire as IR}from"module";import{fileURLToPath as yu}from"url";import{statSync as Cd}from"fs";function we(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,...Rd(e.config.dbPath)}}function Rd(e){try{let t=Cd(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function T(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
2
+ import{program as To}from"commander";import{realpathSync as zf}from"fs";import{fileURLToPath as v0}from"url";import{createRequire as Vk}from"module";import{fileURLToPath as Dm}from"url";import{statSync as Qf}from"fs";function Te(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,...Xf(e.config.dbPath)}}function Xf(e){try{let t=Qf(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function V(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
3
3
  FROM documents
4
4
  WHERE 1 = 1
5
5
  ${e.pathExclusionsFor("documents")}
6
6
  ${n}
7
7
  ${r}
8
- 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}function Id(e){return/[*?]/.test(e)?e.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_"):`%${e}%`}function Ei(e,t){let n=Id(t);return T(e,{like:n,includeIgnored:!1}).map(r=>({relativePath:r}))}import{extname as na}from"path";var vd={".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"};function B(e){return vd[na(e).toLowerCase()]??null}function xt(e){return na(e).toLowerCase()===".vue"}var ra=[];function st(e){e.groups.length>0&&ra.push(e)}function Pi(e,t){let n=new Set(t.groups);for(let r of ra)r.groups.some(i=>n.has(i))&&(t.file!==void 0&&r.clearFile?r.clearFile(e,t.file):r.clearAll(e))}function ia(){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 W(e,t){let{cache:n,ensure:r}=ia(),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 st({name:e,groups:t.clearGroups,clearAll:o=>i.invalidateAll(o),clearFile:(o,s)=>i.invalidate(o,s)}),i}function de(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 st({name:e,groups:t.clearGroups,clearAll:i=>r.invalidate(i)}),r}function fr(e,t){let{cache:n,ensure:r}=ia(),i={get(o,s,a,c){let l=r(o),u=l.get(s);if(u&&u.source===a)return u.value;let m=c();return l.set(s,{source:a,value:m}),m},invalidate(o,s){n.get(o)?.delete(s)},invalidateAll(o){n.delete(o)}};return st({name:e,groups:t.clearGroups,clearAll:o=>i.invalidateAll(o),clearFile:(o,s)=>i.invalidate(o,s)}),i}import{createRequire as Dd}from"module";var ce=Dd(import.meta.url),gr=null,oa=!1;function Nd(){if(oa)return null;if(gr)return gr;try{return gr=ce("tree-sitter"),gr}catch{return oa=!0,null}}var sa=new Map,Fi=new Set;function _d(e){if(Fi.has(e))return null;let t=sa.get(e);if(t)return t;let n;try{switch(e){case"rust":n=ce("tree-sitter-rust");break;case"typescript":n=ce("tree-sitter-typescript").typescript;break;case"tsx":n=ce("tree-sitter-typescript").tsx;break;case"javascript":n=ce("tree-sitter-javascript");break;case"python":n=ce("tree-sitter-python");break;case"java":n=ce("tree-sitter-java");break;case"kotlin":n=ce("tree-sitter-kotlin");break;case"scala":n=ce("tree-sitter-scala");break;case"ruby":n=ce("tree-sitter-ruby");break;case"c":n=ce("tree-sitter-c");break;case"cpp":n=ce("tree-sitter-cpp");break;case"csharp":n=ce("tree-sitter-c-sharp");break;case"php":n=ce("tree-sitter-php").php;break;case"vb":{let r=ce("tree-sitter-vb-dotnet");n=r.language??r;break}}}catch{return Fi.add(e),null}return sa.set(e,n),n}var aa=new Map;function Ld(e){let t=aa.get(e);if(t)return t;let n=_d(e);if(!n)return null;let r=Nd();if(!r)return null;let i=new r;try{i.setLanguage(n)}catch{return Fi.add(e),null}return aa.set(e,i),i}function wd(e,t){return e.parse(r=>r>=t.length?null:t.slice(r,Math.min(t.length,r+16384)))}function Ai(e,t){let n=Ld(e);if(!n)return null;try{return wd(n,t)}catch{return null}}import{existsSync as kd,readFileSync as Ed}from"fs";import{join as Pd}from"path";var Fd=W("source-text",{clearGroups:["whole-project","source-file"]});function M(e,t){let n=t.replace(/\\/g,"/");return Fd.get(e,n,()=>{let r=Pd(e.config.projectRoot,n);return kd(r)?Ed(r,"utf-8"):""})}var Ad=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale|wrapper|passthrough|drift|extract)?/i;function Ti(e,t,n){if(n<=0)return!1;let r=M(e,t);if(!r)return!1;let i=r.split(`
9
- `);for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(i[o]??"").trim();if(s!==""){if(Ad.test(s))return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function ca(e){let t=[],n=/<script\b([^>]*)>([\s\S]*?)<\/script>/g;for(let a of e.matchAll(n))typeof a.index=="number"&&t.push({tagOpen:a[1]??"",body:a[2]??"",openIdx:a.index+(a[0].length-(a[2]?.length??0)-9)});if(t.length===0)return null;let r=t.find(a=>/\bsetup\b/.test(a.tagOpen))??t[0],o=r.tagOpen.match(/\blang\s*=\s*["']?([\w-]+)/)?.[1]?.toLowerCase(),s=o==="ts"||o==="typescript"?"typescript":o==="tsx"?"tsx":"javascript";return{body:r.body,startLine:Td(e,r.openIdx),language:s}}function Td(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}var la=fr("ast-trees",{clearGroups:["whole-project","source-file"]});function le(e,t){if(xt(t))return Md(e,t);let n=B(t);if(!n)return null;let r=M(e,t);return r?la.get(e,t,r,()=>Ai(n,r)):null}function Md(e,t){let n=M(e,t);return n?la.get(e,t,n,()=>{let r=ca(n);if(!r)return null;let i=`
10
- `.repeat(r.startLine)+r.body;return Ai(r.language,i)}):null}function ua(e,t){let n=Od(e,t);if(!n)return null;let r=Yt(n);return r?{calleeLeaf:r,memberAccess:$d(n),line:e.startPosition.row}:null}function Od(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 $d(e){switch(e.type){case"field_expression":case"member_expression":case"attribute":return!0;default:return!1}}function Yt(e){switch(e.type){case"identifier":case"type_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?Yt(t):null}case"scoped_identifier":{let t=e.childForFieldName("name")??e.namedChild(e.namedChildCount-1);return t?Yt(t):null}case"super":case"self":case"this":return null;default:return null}}function Dn(e){return e.type==="comment"||e.type==="line_comment"||e.type==="block_comment"}var jd=new Set(["function_declaration","method_definition","method_signature","function_signature"]);function ga(e,t){let n=Hd(e,t);if(n)return{name:n.name,startLine:n.definitionNode.startPosition.row,endLine:n.definitionNode.endPosition.row,paramCount:pa(n.functionNode),params:ma(n.functionNode),paramsEndLine:da(n.functionNode),isLiteralPassthrough:fa(n.functionNode,t)};if(!Bd(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:pa(e),params:ma(e),paramsEndLine:da(e),isLiteralPassthrough:fa(e,t)}:null}function ha(e){return e.namedChildren.find(t=>t.type==="parameters"||t.type==="formal_parameters")}function ma(e){let t=ha(e);if(!t)return[];let n=[];for(let r of t.namedChildren){if(Dn(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 da(e){let t=ha(e);return t?t.endPosition.row:e.startPosition.row}function Bd(e,t){return t==="rust"?e==="function_item"||e==="function_signature_item":t==="python"?e==="function_definition":t==="typescript"||t==="tsx"||t==="javascript"?jd.has(e):!1}function Hd(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 pa(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)Dn(r)||(n+=1);return n}function fa(e,t){let n=e.namedChildren.find(m=>m.type==="block"||m.type==="statement_block");if(!n)return!1;let r=n.namedChildren.filter(m=>!Dn(m));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(m=>m.type==="arguments"||m.type==="argument_list");if(!a)return!1;let c=a.namedChildren.filter(m=>!Dn(m)),l=e.namedChildren.find(m=>m.type==="parameters"||m.type==="formal_parameters");if(!l)return!1;let u=[];for(let m of l.namedChildren){if(m.type==="identifier"){u.push(m.text);continue}let d=m.namedChildren.find(p=>p.type==="identifier");d&&u.push(d.text)}if(c.length!==u.length)return!1;for(let m=0;m<u.length;m+=1){let d=c[m];if(d.type!=="identifier"||d.text!==u[m])return!1}return!0}var qd=new Set(["identifier","type_identifier","field_identifier"]),Vd=new Set(["identifier"]),Wd=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]),Ud=new Set(["rust","python"]),Gd=/\{([^{}]*)\}/g,Jd=/\b([A-Za-z_][\w]*)\b/g;function ya(e,t){return zd(t).has(e.type)}function ba(e,t){return Ud.has(t)&&e.type==="string_content"}function Sa(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 zd(e){return e==="rust"?qd:e==="python"?Vd:Wd}function xa(e,t){let n=e.startPosition.row;for(let r of e.text.matchAll(Gd)){let i=r[1]??"";for(let o of i.matchAll(Jd))o[1]&&t(o[1],n)}}var Kd=[/\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],Qd=/^#!?\[\s*serde\s*\(/,Yd=/^#!?\[\s*schemars\s*\(/,Xd=/^#!?\[\s*validate\s*\(/,Zd=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function Ca(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=Yt(r);if(!i||!Zd.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 Ra(e,t){let n=Qd.test(e),r=Yd.test(e),i=Xd.test(e);if(!(!n&&!r&&!i))for(let o of Kd){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 Ia(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(l=>l.type==="identifier")?.text;if(!a)continue;let c=s.namedChildren.find(l=>l.type==="block");if(c)for(let l of c.descendantsOfType("type"))for(let u of l.descendantsOfType("identifier"))u.text!==a&&r(u.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 va=new WeakMap;function Q(e,t){let n=B(t);if(!n)return null;let r=le(e,t);if(!r)return null;let i=va.get(r);if(i)return i;let o=tp(r,n);return va.set(r,o),o}function Mi(e,t,n,r){let i=Q(e,t);return i?ep(i,n,r)?.isLiteralPassthrough??!0:!0}function ep(e,t,n){return e.callables.find(r=>r.startLine===t&&r.endLine===n)??null}function tp(e,t){let n=[],r=[],i=new Set,o=new Set,s=new Map,a=(l,u)=>{let m=s.get(l);if(!m){s.set(l,[u]);return}m[m.length-1]!==u&&m.push(u)},c=l=>{let u=ga(l,t);u&&n.push(u);let m=ua(l,t);m&&r.push(m),Ca(l,t,o),t==="rust"&&(l.type==="attribute_item"||l.type==="inner_attribute_item")&&Ra(l.text,i),ya(l,t)&&a(l.text,l.startPosition.row),ba(l,t)&&xa(l,a);for(let d of l.children)c(d)};return c(e.rootNode),{language:t,callables:n,callSites:r,typeContainerMap:Ia(e,t),identifierLineMap:s,identifiersByLine:Sa(s),fileIdentifiers:new Set(s.keys()),rustAttrReferencedNames:i,crossLanguageDispatchNames:o}}var Da=new Set(["rust","typescript","tsx","javascript","python"]);function Oi(e,t){let n=Q(e,t);return!n||!Da.has(n.language)?null:n.callables.map(r=>({name:r.name,startLine:r.startLine,endLine:r.endLine}))}function Xt(e,t){let n=Q(e,t);return!n||!Da.has(n.language)?null:n.callSites}function $i(e,t){return Q(e,t)?.typeContainerMap??new Map}function Ct(e,t,n={}){let r=Q(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}var np={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function ee(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=rp(i);return{scheme:n,manager:r,packageName:o,version:s,descriptors:c,raw:e}}function je(e){let t=ee(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 rp(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||Na(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&&!Na(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=np[i];o&&t.push({name:r,suffix:o}),n+=1}}return t}function Na(e){return e==="/"||e==="#"||e==="."||e==="("||e==="["||e===":"||e==="!"}function b(e){let t=ee(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=ip(i);o&&r.push(o)}return r.join(":")}function ip(e){let t=e.suffix==="namespace"?op(e.name):e.name;return t?e.suffix==="method"?`${t}()`:t:""}function op(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 F(e){let t=ee(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 te(e){let t=ee(e);if("kind"in t&&t.kind==="local")return null;let n=t;return n.descriptors[n.descriptors.length-1]?.suffix??null}function oe(e){return e.endsWith("().")||te(e)==="method"}function Y(e){let t=te(e);return t==="method"||t==="term"}function at(e){return te(e)==="namespace"}var sp=/^rust-analyzer\b.*[\s/]impl#\[[^\]]+\]\[[^\]]+\]/;function hr(e){return sp.test(e)}var ap=new Set(["test","tests","_tests"]);function Zt(e){let t=ee(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&&ap.has(r.name))return!0}return!1}function _a(e,t){let n=ee(e),r=ee(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 La(e,t){let n=ee(e),r=ee(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}function en(e,t){return e.all(`SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path, gs.display_name, gs.documentation
8
+ 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}function Yf(e){return/[*?]/.test(e)?e.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_"):`%${e}%`}function Mo(e,t){let n=Yf(t);return V(e,{like:n,includeIgnored:!1}).map(r=>({relativePath:r}))}import{extname as Cc}from"path";var Zf={".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"};function U(e){return Zf[Cc(e).toLowerCase()]??null}function ut(e){return Cc(e).toLowerCase()===".vue"}var vc=[];function kt(e){e.groups.length>0&&vc.push(e)}function Oo(e,t){let n=new Set(t.groups);for(let r of vc)r.groups.some(i=>n.has(i))&&(t.file!==void 0&&r.clearFile?r.clearFile(e,t.file):r.clearAll(e))}function Rc(){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 W(e,t){let{cache:n,ensure:r}=Rc(),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 kt({name:e,groups:t.clearGroups,clearAll:o=>i.invalidateAll(o),clearFile:(o,s)=>i.invalidate(o,s)}),i}function ie(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 kt({name:e,groups:t.clearGroups,clearAll:i=>r.invalidate(i)}),r}var eg={clearGroups:["whole-project","source-file"]};function ti(e){return Bt(e,eg)}function Bt(e,t){let{cache:n,ensure:r}=Rc(),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 kt({name:e,groups:t.clearGroups,clearAll:o=>i.invalidateAll(o),clearFile:(o,s)=>i.invalidate(o,s)}),i}import{createRequire as tg}from"module";var Se=tg(import.meta.url),ni=null,Lc=!1;function ng(){if(Lc)return null;if(ni)return ni;try{return ni=Se("tree-sitter"),ni}catch{return Lc=!0,null}}var Ic=new Map,jo=new Set;function rg(e){if(jo.has(e))return null;let t=Ic.get(e);if(t)return t;let n;try{switch(e){case"rust":n=Se("tree-sitter-rust");break;case"typescript":n=Se("tree-sitter-typescript").typescript;break;case"tsx":n=Se("tree-sitter-typescript").tsx;break;case"javascript":n=Se("tree-sitter-javascript");break;case"python":n=Se("tree-sitter-python");break;case"java":n=Se("tree-sitter-java");break;case"kotlin":n=Se("tree-sitter-kotlin");break;case"scala":n=Se("tree-sitter-scala");break;case"ruby":n=Se("tree-sitter-ruby");break;case"c":n=Se("tree-sitter-c");break;case"cpp":n=Se("tree-sitter-cpp");break;case"csharp":n=Se("tree-sitter-c-sharp");break;case"php":n=Se("tree-sitter-php").php;break;case"vb":{let r=Se("tree-sitter-vb-dotnet");n=r.language??r;break}}}catch{return jo.add(e),null}return Ic.set(e,n),n}var Dc=new Map;function ig(e){let t=Dc.get(e);if(t)return t;let n=rg(e);if(!n)return null;let r=ng();if(!r)return null;let i=new r;try{i.setLanguage(n)}catch{return jo.add(e),null}return Dc.set(e,i),i}function og(e,t){return e.parse(r=>r>=t.length?null:t.slice(r,Math.min(t.length,r+16384)))}function or(e,t){let n=ig(e);if(!n)return null;try{return og(n,t)}catch{return null}}import{existsSync as sg,readFileSync as ag}from"fs";import{join as cg}from"path";var lg=W("source-text",{clearGroups:["whole-project","source-file"]}),ug=W("source-lines",{clearGroups:["whole-project","source-file"]});function A(e,t){let n=t.replace(/\\/g,"/");return lg.get(e,n,()=>{let r=cg(e.config.projectRoot,n);return sg(r)?ag(r,"utf-8"):""})}function dt(e,t){let n=t.replace(/\\/g,"/");return ug.get(e,n,()=>{let r=A(e,n);return r?r.split(`
9
+ `):[]})}var dg=/^\s*(?:\/\/|#|\/\*+|\*)\s*scip-query[\s:-]*ignore(?:[\s:-]+(dead(?:-code)?|stale|wrapper|passthrough|drift|extract|similar))?\b/i;function Bo(e){let t=dg.exec(e);return t?t[1]??"":null}function ri(e,t,n){if(n<=0)return!1;let r=dt(e,t);if(r.length===0)return!1;for(let i=n-1;i>=0&&i>=n-5;i-=1){let o=(r[i]??"").trim();if(o!==""){if(Bo(o)!==null)return!0;if(!o.startsWith("//")&&!o.startsWith("*")&&!o.startsWith("/*")&&!o.startsWith("@")&&!o.startsWith("#"))return!1}}return!1}import{parse as bg}from"@vue/compiler-sfc";import{posix as Vo}from"path";import{parse as mg}from"@vue/compiler-sfc";var pg=ti("vue-sfc-units");function oi(e,t){let n=Nc(t),r=A(e,n);return pg.get(e,n,r,()=>fg(e,n,r))}function Nc(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Ho(e){let t=e?.toLowerCase();return!t||t==="js"||t==="javascript"||t==="jsx"?"javascript":t==="ts"||t==="typescript"?"typescript":t==="tsx"?"tsx":null}function Vt(e){return!e||e.body.length===0?0:e.body.split(`
10
+ `).length}function fg(e,t,n){let r={relativePath:t,template:null,scripts:[],styles:[],customBlocks:[],errors:[]};if(!n)return r;let i;try{i=mg(n,{filename:t})}catch(s){return r.errors.push(wc(s)),r}r.errors.push(...i.errors.map(wc));let{descriptor:o}=i;return o.template&&(r.template=ii(e,t,"template",o.template)),o.script&&r.scripts.push(kc(e,t,o.script,!1)),o.scriptSetup&&r.scripts.push(kc(e,t,o.scriptSetup,!0)),r.styles=o.styles.map(s=>ii(e,t,"style",s)),r.customBlocks=o.customBlocks.map(s=>ii(e,t,"custom",s)),r.errors.push(...[r.template,...r.scripts,...r.styles,...r.customBlocks].flatMap(s=>s?.errors??[])),r}function kc(e,t,n,r){let i=ii(e,t,"script",n);return{...i,kind:"script",setup:r,astLanguage:Ho(i.lang)}}function ii(e,t,n,r){let i=hg(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=gg(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=A(e,c),u=l?Math.max(0,l.split(`
11
+ `).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 gg(e,t){let n=t.split(/[?#]/,1)[0];if(!n||n.startsWith("/")||n.includes("://"))return null;let r=Nc(Vo.normalize(Vo.join(Vo.dirname(e),n)));return r===".."||r.startsWith("../")?null:r}function hg(e){return{...e}}function wc(e){return e instanceof Error?e.message:String(e)}function si(e){let t=bg(e),n=t.descriptor.scriptSetup??t.descriptor.script;if(!n||n.src)return null;let r=Ho(n.lang??null);return r?{body:n.content,startLine:Math.max(0,n.loc.start.line-1),language:r}:null}var Pc=Bt("ast-trees",{clearGroups:["whole-project","source-file"]});function oe(e,t){if(ut(t))return yg(e,t);let n=U(t);if(!n)return null;let r=A(e,t);return r?Pc.get(e,t,r,()=>or(n,r)):null}function yg(e,t){let n=A(e,t);return n?Pc.get(e,t,n,()=>{let r=si(n);if(!r)return null;let i=`
12
+ `.repeat(r.startLine)+r.body;return or(r.language,i)}):null}function In(e,t){let n=Sg(e,t);if(!n)return null;let r=Ln(n);return r?{calleeLeaf:r,memberAccess:xg(n),line:e.startPosition.row}:null}function Sg(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 xg(e){switch(e.type){case"field_expression":case"member_expression":case"attribute":return!0;default:return!1}}function Ln(e){switch(e.type){case"identifier":case"type_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?Ln(t):null}case"scoped_identifier":{let t=e.childForFieldName("name")??e.namedChild(e.namedChildCount-1);return t?Ln(t):null}case"super":case"self":case"this":return null;default:return null}}import{createHash as Cg}from"crypto";import{createRequire as vg}from"module";import{dirname as Rg,join as Lg}from"path";import Ig from"better-sqlite3";var Dg=vg(import.meta.url),kg="evidence.db",ai=new WeakMap,wg=W("evidence-content-hash",{clearGroups:["whole-project","source-file"]});function Ng(){for(let e of["../package.json","../../package.json"])try{return Dg(e).version}catch{}return"0.0.0"}var ci=Ng();function qo(e){return Cg("sha256").update(e).digest("hex")}function Ht(e,t,n){return wg.get(e,t,()=>qo(n))}function _c(e,t){process.env.SCIP_QUERY_DEBUG&&console.error(`evidence-cache: ${e}: ${t instanceof Error?t.message:String(t)}`)}function sr(e){if(ai.has(e))return ai.get(e)??null;let t=null;try{let n=new Ig(Lg(Rg(e.config.dbPath),kg));n.pragma("journal_mode = WAL"),n.pragma("busy_timeout = 5000"),n.pragma("synchronous = NORMAL"),n.exec(`
13
+ CREATE TABLE IF NOT EXISTS file_evidence (
14
+ kind TEXT NOT NULL,
15
+ relative_path TEXT NOT NULL,
16
+ content_hash TEXT NOT NULL,
17
+ version TEXT NOT NULL,
18
+ payload TEXT NOT NULL,
19
+ PRIMARY KEY (kind, relative_path)
20
+ );
21
+ CREATE TABLE IF NOT EXISTS semantic_callees (
22
+ relative_path TEXT NOT NULL,
23
+ symbol TEXT NOT NULL,
24
+ content_hash TEXT NOT NULL,
25
+ deps_digest TEXT NOT NULL,
26
+ version TEXT NOT NULL,
27
+ payload TEXT NOT NULL,
28
+ PRIMARY KEY (relative_path, symbol)
29
+ );
30
+ `),t={evidence:n,readFileEvidence:n.prepare("SELECT payload FROM file_evidence WHERE kind = ? AND relative_path = ? AND content_hash = ? AND version = ?"),writeFileEvidence:n.prepare("INSERT OR REPLACE INTO file_evidence (kind, relative_path, content_hash, version, payload) VALUES (?, ?, ?, ?, ?)"),readCallees:n.prepare(`SELECT payload FROM semantic_callees
31
+ WHERE relative_path = ? AND symbol = ? AND content_hash = ? AND deps_digest = ? AND version = ?`),writeCallees:n.prepare(`INSERT OR REPLACE INTO semantic_callees
32
+ (relative_path, symbol, content_hash, deps_digest, version, payload) VALUES (?, ?, ?, ?, ?, ?)`),dropStaleCallees:n.prepare("DELETE FROM semantic_callees WHERE relative_path = ? AND content_hash != ?")}}catch(n){_c("disabled (open failed)",n)}return ai.set(e,t),t}function ar(e,t,n){_c(`disabled (${t})`,n),ai.set(e,null)}function li(e,t,n,r){let i=sr(e);if(!i)return null;try{return i.readFileEvidence.get(t,n,r,ci)?.payload??null}catch(o){return ar(e,"file_evidence read",o),null}}function ui(e,t,n,r,i){let o=sr(e);if(o)try{o.writeFileEvidence.run(t,n,r,ci,i)}catch(s){ar(e,"file_evidence write",s)}}function Ec(e){let t=sr(e);if(!t)return 0;try{return t.evidence.prepare("SELECT COUNT(*) AS count FROM semantic_callees").get()?.count??0}catch(n){return ar(e,"semantic_callees count",n),0}}function Fc(e,t,n,r,i){let o=sr(e);if(!o)return null;try{return o.readCallees.get(t,n,r,i,ci)?.payload??null}catch(s){return ar(e,"semantic_callees read",s),null}}function Tc(e,t){if(t.length===0)return;let n=sr(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,ci,i.payload)}})()}catch(r){ar(e,"semantic_callees write",r)}}function cr(e){return e.type==="comment"||e.type==="line_comment"||e.type==="block_comment"}var Pg=new Set(["function_declaration","method_definition","method_signature","function_signature"]);function di(e,t){let n=Eg(e,t);if(n)return{name:n.name,startLine:n.definitionNode.startPosition.row,endLine:n.definitionNode.endPosition.row,paramCount:Mc(n.functionNode),params:Ac(n.functionNode),paramsEndLine:$c(n.functionNode),isLiteralPassthrough:Oc(n.functionNode,t)};if(!_g(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:Mc(e),params:Ac(e),paramsEndLine:$c(e),isLiteralPassthrough:Oc(e,t)}:null}function jc(e){return e.namedChildren.find(t=>t.type==="parameters"||t.type==="formal_parameters")}function Ac(e){let t=jc(e);if(!t)return[];let n=[];for(let r of t.namedChildren){if(cr(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 $c(e){let t=jc(e);return t?t.endPosition.row:e.startPosition.row}function _g(e,t){return t==="rust"?e==="function_item"||e==="function_signature_item":t==="python"?e==="function_definition":t==="typescript"||t==="tsx"||t==="javascript"?Pg.has(e):!1}function Eg(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 Mc(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)cr(r)||(n+=1);return n}function Oc(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=>!cr(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=>!cr(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 m=d.namedChildren.find(f=>f.type==="identifier");m&&u.push(m.text)}if(c.length!==u.length)return!1;for(let d=0;d<u.length;d+=1){let m=c[d];if(m.type!=="identifier"||m.text!==u[d])return!1}return!0}var Fg=new Set(["identifier","type_identifier","field_identifier"]),Tg=new Set(["identifier"]),Ag=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]),$g=new Set(["rust","python"]),Mg=/\{([^{}]*)\}/g,Og=/\b([A-Za-z_][\w]*)\b/g;function Bc(e,t){return jg(t).has(e.type)}function Vc(e,t){return $g.has(t)&&e.type==="string_content"}function Wo(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 jg(e){return e==="rust"?Fg:e==="python"?Tg:Ag}function Hc(e,t){let n=e.startPosition.row;for(let r of e.text.matchAll(Mg)){let i=r[1]??"";for(let o of i.matchAll(Og))o[1]&&t(o[1],n)}}var Bg=[/\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],Vg=/^#!?\[\s*serde\s*\(/,Hg=/^#!?\[\s*schemars\s*\(/,qg=/^#!?\[\s*validate\s*\(/,Wg=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function qc(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=Ln(r);if(!i||!Wg.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 Wc(e,t){let n=Vg.test(e),r=Hg.test(e),i=qg.test(e);if(!(!n&&!r&&!i))for(let o of Bg){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 Uc(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(l=>l.type==="identifier")?.text;if(!a)continue;let c=s.namedChildren.find(l=>l.type==="block");if(c)for(let l of c.descendantsOfType("type"))for(let u of l.descendantsOfType("identifier"))u.text!==a&&r(u.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 Ug=Bt("source-facts",{clearGroups:["whole-project","source-file"]});function ee(e,t){let n=A(e,t);if(!n)return null;let r=Jg(t,n);return r?Ug.get(e,t,n,()=>Gg(e,t,r,n)):null}function Jg(e,t){return ut(e)?si(t)?.language??null:U(e)}function Gg(e,t,n,r){let i=Ht(e,t,r),o=li(e,"source-facts",t,i);if(o){let c=Kg(o);if(c&&c.language===n)return c}let s=oe(e,t);if(!s)return null;let a=Xg(s,n);return ui(e,"source-facts",t,i,zg(a)),a}function zg(e){let t={language:e.language,callables:e.callables,callSites:e.callSites,typeContainerMap:[...e.typeContainerMap.entries()].map(([n,r])=>[n,[...r]]),identifierLineMap:[...e.identifierLineMap.entries()],rustAttrReferencedNames:[...e.rustAttrReferencedNames],crossLanguageDispatchNames:[...e.crossLanguageDispatchNames]};return JSON.stringify(t)}function Kg(e){try{let t=JSON.parse(e),n=new Map(t.identifierLineMap);return{language:t.language,callables:t.callables,callSites:t.callSites,typeContainerMap:new Map(t.typeContainerMap.map(([r,i])=>[r,new Set(i)])),identifierLineMap:n,identifiersByLine:Wo(n),fileIdentifiers:new Set(n.keys()),rustAttrReferencedNames:new Set(t.rustAttrReferencedNames),crossLanguageDispatchNames:new Set(t.crossLanguageDispatchNames)}}catch{return null}}function Uo(e,t,n,r){let i=ee(e,t);return i?Qg(i,n,r)?.isLiteralPassthrough??!0:!0}function Qg(e,t,n){return e.callables.find(r=>r.startLine===t&&r.endLine===n)??null}function Xg(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=di(l,t);u&&n.push(u);let d=In(l,t);d&&r.push(d),qc(l,t,o),t==="rust"&&(l.type==="attribute_item"||l.type==="inner_attribute_item")&&Wc(l.text,i),Bc(l,t)&&a(l.text,l.startPosition.row),Vc(l,t)&&Hc(l,a);for(let m of l.children)c(m)};return c(e.rootNode),{language:t,callables:n,callSites:r,typeContainerMap:Uc(e,t),identifierLineMap:s,identifiersByLine:Wo(s),fileIdentifiers:new Set(s.keys()),rustAttrReferencedNames:i,crossLanguageDispatchNames:o}}var Jc=new Set(["rust","typescript","tsx","javascript","python"]);function Jo(e,t){let n=ee(e,t);return!n||!Jc.has(n.language)?null:n.callables.map(r=>({name:r.name,startLine:r.startLine,endLine:r.endLine}))}function Dn(e,t){let n=ee(e,t);return!n||!Jc.has(n.language)?null:n.callSites}function Go(e,t){return ee(e,t)?.typeContainerMap??new Map}import{ElementTypes as Yg,NodeTypes as zc,parse as Zg}from"@vue/compiler-dom";import{parse as _F}from"@vue/compiler-sfc";function mi(e,t){return e.split(t).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}var eh=ti("vue-template-facts"),th=new Set(["component","keep-alive","slot","suspense","teleport","template","transition","transition-group"]),nh=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"]),rh=new Set(["div","span","template"]),ih=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 Kc(e,t){let n=t.replace(/\\/g,"/"),r=A(e,n);return eh.get(e,n,r,()=>oh(n,oi(e,n).template))}function oh(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=Zg(t.body,{comments:!1})}catch{return n}let i=new Set,o=s=>{s.trim()&&i.add(s)};return Qc(r.children,t.startLine,n,o),n.structuralTokens=[...i].sort(),n}function Qc(e,t,n,r){for(let i of e)i.type===zc.ELEMENT&&(sh(i,t,n,r),Qc(i.children,t,n,r))}function sh(e,t,n,r){let i=fh(e.tag),o={tag:e.tag,normalized:i,kind:ph(e),startLine:kn(t,e.loc.start.line),endLine:kn(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),rh.has(e.tag)||r(`native:${e.tag}`));for(let s of e.props)ah(s,t,n,r)}function ah(e,t,n,r){if(e.type===zc.ATTRIBUTE){let a=e.value?.content??null,c=Gc("prop",e.name,a,t,e.loc.start.line,e.loc.end.line);n.props.push(c),r(`prop:${e.name}`);return}let i=lh(e),o=Xc(e.exp),s=Gc(ch(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&&uh(o,t,e.loc.start.line,n,r)}function Gc(e,t,n,r,i,o){return{kind:e,name:t,value:n,startLine:kn(r,i),endLine:kn(r,o)}}function ch(e){switch(e){case"bind":case"model":return"prop";case"on":return"event";case"slot":return"slot";default:return"directive"}}function lh(e){let t=Xc(e.arg);return t||e.name}function Xc(e){if(!e)return null;let t=("content"in e&&typeof e.content=="string"?e.content:e.loc.source).trim();return t||null}function uh(e,t,n,r,i){for(let o of dh(e)){let s={name:o,startLine:kn(t,n),endLine:kn(t,n)};r.expressionIdentifiers.push(s),i(`id:${o}`)}}function dh(e){let t=new Set,n=mh(e),r=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,i;for(;i=r.exec(n);){let o=i[0];ih.has(o)||/^[A-Z_]+$/.test(o)||t.add(o)}return[...t].sort()}function mh(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 ph(e){let t=e.tag;return e.tagType===Yg.COMPONENT?"component":th.has(t)?"builtin":nh.has(t)?"native":/^[A-Z]/.test(t)||t.includes("-")?"component":"native"}function fh(e){return mi(e,/[-_:]/)}function kn(e,t){return e+Math.max(0,t-1)}import{readdirSync as gh}from"fs";import{execFileSync as hh}from"child_process";import{extname as zo,join as bh}from"path";var yh=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".rs",".py",".pyi",".java",".kt",".kts",".scala",".sc",".rb",".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx",".cs",".vb",".php",".dart"],Yc=[".vue"],Zc=new Set(yh.map(e=>e.toLowerCase())),Sh=[...Zc].sort().join(","),Ko=new Set(["node_modules",".git","target","dist","build",".next",".nuxt",".cache",".turbo","out","coverage",".scipquery-cache","__pycache__",".venv","venv",".idea",".vscode"]);function Le(e,t={}){let n=t.includeIndexed??!0,r=t.includeAuxiliary??!0,i=t.extensions?.map(c=>c.toLowerCase()),o=i?new Set(i):Zc,s=i?[...o].sort().join(","):Sh,a=`${n?"1":"0"}|${r?"1":"0"}|${s}`;return xh.get(e,a,()=>{let c=new Set;if(n)for(let l of V(e,{includeIgnored:!1}))o.has(zo(l).toLowerCase())&&c.add(l);if(r)for(let l of Ch(e.config.projectRoot,o))e.isIgnored(l)||n&&c.has(l)||c.add(l);return[...c].sort()})}var xh=W("source-files",{clearGroups:[]});function Ch(e,t){return vh(e,t)??Rh(e,t)}function vh(e,t){try{let n=hh("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(`
33
+ `)){let o=i.trim();o&&t.has(zo(o).toLowerCase())&&r.add(o)}return r}catch{return null}}function Rh(e,t){let n=new Set,r=i=>{let o=i?bh(e,i):e,s;try{s=gh(o,{withFileTypes:!0})}catch{return}for(let a of s)if(!Ko.has(a.name)){if(a.isDirectory()){r(i?`${i}/${a.name}`:a.name);continue}t.has(zo(a.name).toLowerCase())&&n.add(i?`${i}/${a.name}`:a.name)}};return r(""),n}var Lh=new Set(["ref","shallowRef","reactive","computed","watch","watchEffect"]),Ih=new Set(["onBeforeMount","onMounted","onBeforeUpdate","onUpdated","onBeforeUnmount","onUnmounted","onActivated","onDeactivated","onErrorCaptured"]),Dh=new Set(["axios","fetch","runRequest","useAsyncData","useFetch","useResource"]),kh=new Set(["defineEmits","defineExpose","defineModel","defineOptions","defineProps","withDefaults"]),wh=new Set(["catch","for","function","if","return","switch","while"]);function el(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+=Vt(n),n.external&&(t.externalLineCount+=Vt(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(...Eh(n));let r=or(n.astLanguage,n.body);r?Ph(n,r.rootNode,t):_h(n,t)}return Nh(t),t.externalScriptPaths=nl(t.externalScriptPaths),t}function Nh(e){e.composables=wn(e,"composable"),e.stores=wn(e,"store"),e.reactivity=wn(e,"reactivity"),e.lifecycle=wn(e,"lifecycle"),e.requests=wn(e,"request"),e.macros=wn(e,"macro")}function wn(e,t){return nl(e.calls.filter(n=>n.categories.includes(t)).map(n=>n.name))}function Ph(e,t,n){let r=new Set,i=new Set,o=s=>{let a=di(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=In(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:tl(c.calleeLeaf),setup:e.setup}))}for(let l of s.children)o(l)};o(t)}function _h(e,t){for(let n of e.body.matchAll(/\b([A-Za-z_$][\w$]*)\s*\(/g)){let r=n[1];!r||wh.has(r)||t.calls.push({name:r,sourcePath:e.sourcePath,line:e.startLine+pi(e.body,n.index??0),categories:tl(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+pi(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+pi(e.body,n.index??0);t.functions.push({name:r,sourcePath:e.sourcePath,startLine:i,endLine:i,setup:e.setup})}}function Eh(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+pi(e.body,n.index??0);for(let s of Fh(r))t.push({local:s,source:i,sourcePath:e.sourcePath,line:o,setup:e.setup})}return t}function Fh(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 tl(e){let t=["call"];return/^use[A-Z0-9_]/.test(e)&&t.push("composable"),/^use[A-Z0-9_].*Store$/.test(e)&&t.push("store"),Lh.has(e)&&t.push("reactivity"),Ih.has(e)&&t.push("lifecycle"),Dh.has(e)&&t.push("request"),kh.has(e)&&t.push("macro"),t}function pi(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 nl(e){return[...new Set(e)].sort()}var Th=new Set(["in","key","of"]),Ah=new Set(["computed","defineEmits","defineProps","reactive","ref","watch","watchEffect"]);function Nn(e,t={}){let n=Le(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=>$h(e,i)).filter(i=>(t.minTemplateTokens===void 0||i.templateTokens.size>=t.minTemplateTokens)&&(t.minBehaviorTokens===void 0||i.behaviorTokens.size>=t.minBehaviorTokens))}function $h(e,t){let n=t.replace(/\\/g,"/"),r=oi(e,n),i=Kc(e,n),o=el(r),s=Oh(i),a=i.expressionIdentifiers.map(g=>g.name).filter(g=>!s.includes(g)).filter((g,h,b)=>b.indexOf(g)===h).sort(),c=i.componentTags.map(g=>g.normalized).filter((g,h,b)=>b.indexOf(g)===h).sort(),l=dt(e,n).length,u=Vt(r.template),d=o.lineCount,m=r.styles.reduce((g,h)=>g+Vt(h),0),f=r.customBlocks.reduce((g,h)=>g+Vt(h),0);return{file:n,sfc:r,templateFacts:i,scriptFacts:o,templateTokens:new Set(i.structuralTokens),behaviorTokens:Mh(i,o,a),templateBindingNames:a,templateLocalNames:s,componentNames:c,sfcLines:l,totalLines:l+o.externalLineCount,templateLines:u,scriptLines:d,styleLines:m,externalScriptLines:o.externalLineCount,externalScriptPaths:o.externalScriptPaths,customBlockLines:f}}function Mh(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(Ah.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 Oh(e){let t=new Set;for(let n of e.directives)if(n.name==="for"&&n.value)for(let r of jh(n.value))t.add(r);for(let n of e.slots)if(n.value)for(let r of rl(n.value))t.add(r);return[...t].sort()}function jh(e){let t=/^(.*?)\s+(?:in|of)\s+/.exec(e.trim());return t?rl(t[1]??""):[]}function rl(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let r=n[0];Th.has(r)||t.push(r)}return t}import{extname as Bh}from"path";var Vh=[".tsx",".jsx"],il=new Set(["useActionState","useCallback","useContext","useDebugValue","useDeferredValue","useEffect","useId","useImperativeHandle","useInsertionEffect","useLayoutEffect","useMemo","useOptimistic","useReducer","useRef","useState","useSyncExternalStore","useTransition"]),Hh=new Set(["useEffect","useInsertionEffect","useLayoutEffect"]),qh=new Set(["useActionState","useOptimistic","useReducer","useRef","useState"]),Wh=new Set(["useLocation","useNavigate","useParams","useSearchParams","useTranslation"]),Uh=new Set(["axios","fetch","gql","graphql","mutate","query","request","useMutation","useQuery","useSuspenseQuery"]),Jh=new Set(["add","apply","cancel","change","clear","close","create","delete","fetch","filter","handle","load","open","refresh","remove","render","reset","save","select","submit","toggle","update"]),Gh=new Set(["children","className","false","key","null","style","true","undefined"]),zh=new Set(["aria-hidden","className","clipRule","d","fill","fillRule","height","role","stroke","strokeLinecap","strokeLinejoin","strokeWidth","style","viewBox","width","xmlns"]);function Pn(e,t={}){let n=Le(e,{extensions:Vh}).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=>Kh(e,i)).filter(i=>(t.minJsxTokens===void 0||i.jsxTokens.size>=t.minJsxTokens)&&(t.minBehaviorTokens===void 0||i.behaviorTokens.size>=t.minBehaviorTokens))}function Kh(e,t){let n=t.replace(/\\/g,"/"),r=Qh(n);if(!r)return[];let i=oe(e,n);if(!i)return[];let o=dt(e,n).length;return Xh(i.rootNode,r).filter(a=>a.kind==="hook"||ll(a.bodyNode)).map(a=>{let c=nb(a.bodyNode),l=ab(a.bodyNode,r);return{file:n,name:a.name,kind:a.kind,startLine:a.node.startPosition.row,endLine:a.node.endPosition.row,loc:Math.max(1,a.node.endPosition.row-a.node.startPosition.row+1),fileLines:o,jsxTokens:c.tokens,behaviorTokens:l.tokens,componentNames:mt(c.componentNames),nativeTags:mt(c.nativeTags),propNames:mt(c.propNames),eventNames:mt(c.eventNames),hookNames:mt(l.hookNames),requestNames:mt(l.requestNames),stateNames:mt(l.stateNames),effectNames:mt(l.effectNames),handlerNames:mt(l.handlerNames)}})}function Qh(e){let t=Bh(e).toLowerCase();return t!==".tsx"&&t!==".jsx"?null:U(e)}function Xh(e,t){let n=[],r=new Set,i=o=>{let s=Yh(o);if(s&&!eb(o)){let a=`${s.name}:${s.node.startIndex}:${s.node.endIndex}`;r.has(a)||(r.add(a),n.push(s));return}for(let a of o.namedChildren)i(a)};return(t==="tsx"||t==="javascript")&&i(e),n}function Yh(e){if(e.type==="function_declaration"){let o=cl(e);return!o||!ol(o)?null:{name:o,kind:sl(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=lr(t);if(!r||!n||!ol(r))return null;let i=Zh(n);return i?{name:r,kind:sl(r),node:e,bodyNode:i}:null}function ol(e){return/^[A-Z]/.test(e)||/^use[A-Z0-9_]/.test(e)}function sl(e){return/^use[A-Z0-9_]/.test(e)?"hook":"component"}function Zh(e){if(e.type==="arrow_function"||e.type==="function_expression")return e;if(e.type!=="call_expression")return null;let t=tb(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 eb(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 cl(e){return lr(e.childForFieldName("name")??e.namedChild(0))}function tb(e){let t=e.childForFieldName("function")??e.namedChild(0);return t?t.text.split(".").pop()??t.text:null}function ll(e){return e.type.startsWith("jsx_")?!0:e.namedChildren.some(ll)}function nb(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"?rb(r,t):r.type==="jsx_expression"?ib(r,t):r.type==="jsx_fragment"&&t.tokens.add("jsx:fragment");for(let i of r.namedChildren)n(i)};return n(e),t}function rb(e,t){let n=ob(e),r=!1;if(n){let i=al(n);r=mb(i),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=sb(i);if(!o)continue;let s=al(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 zh.has(s)||(t.propNames.add(s),t.tokens.add(`${r?"prop":"native-prop"}:${s}`))}else i.type==="jsx_spread_attribute"&&t.tokens.add("prop:spread")}function ib(e,t){let n=e.text;(n.includes("&&")||n.includes("?"))&&t.tokens.add("jsx:conditional"),(n.includes(".map(")||n.includes(".flatMap("))&&t.tokens.add("jsx:list");for(let r of pb(n))Gh.has(r)||t.tokens.add(`binding:${r}`)}function ob(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 sb(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 ab(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=In(i,t);o&&cb(o.calleeLeaf,n)}else if(i.type==="variable_declarator")ub(i,n);else if(i.type==="function_declaration"){let o=cl(i);o&&ul(o,n)}for(let o of i.namedChildren)r(o)};return r(e),n}function cb(e,t){/^use[A-Z0-9_]/.test(e)&&(t.hookNames.add(e),!il.has(e)&&!Wh.has(e)&&t.tokens.add(`hook:${e}`)),il.has(e)&&t.tokens.add(`react-hook:${e}`),Hh.has(e)&&(t.effectNames.add(e),t.tokens.add(`effect:${e}`)),qh.has(e)&&t.tokens.add(`state-hook:${e}`),lb(e)&&(t.requestNames.add(e),t.tokens.add(`request:${e}`))}function lb(e){if(Uh.has(e))return!0;let t=/^use([A-Z0-9_].*)$/.exec(e)?.[1];return t?/(Query|Mutation|Fetch|Resource)$/.test(t):!1}function ub(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=>lr(a)),s=lr(o);s&&(t.stateNames.add(s),t.tokens.add(`state:${s}`))}let i=lr(n);i&&ul(i,t)}function ul(e,t){let n=db(e);!n||!Jh.has(n)||(t.handlerNames.add(e),t.tokens.add(`handler:${e}`),t.tokens.add(`handler-verb:${n}`))}function db(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 mb(e){return/^[A-Z]/.test(e)||e.includes(".")}function al(e){return e.replace(/^this\./,"").replace(/\$/g,".")}function lr(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 pb(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 mt(e){return[...e].sort()}function qt(e,t,n={}){let r=ee(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}var fb={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function se(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=gb(i);return{scheme:n,manager:r,packageName:o,version:s,descriptors:c,raw:e}}function Xe(e){let t=se(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 gb(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||dl(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&&!dl(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=fb[i];o&&t.push({name:r,suffix:o}),n+=1}}return t}function dl(e){return e==="/"||e==="#"||e==="."||e==="("||e==="["||e===":"||e==="!"}function y(e){let t=se(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=hb(i);o&&r.push(o)}return r.join(":")}function hb(e){let t=e.suffix==="namespace"?bb(e.name):e.name;return t?e.suffix==="method"?`${t}()`:t:""}function bb(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 $(e){let t=se(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 ae(e){let t=se(e);if("kind"in t&&t.kind==="local")return null;let n=t;return n.descriptors[n.descriptors.length-1]?.suffix??null}function pe(e){return e.endsWith("().")||ae(e)==="method"}function te(e){let t=ae(e);return t==="method"||t==="term"}function wt(e){return ae(e)==="namespace"}var yb=/^rust-analyzer\b.*[\s/]impl#\[[^\]]+\]\[[^\]]+\]/;function fi(e){return yb.test(e)}var Sb=new Set(["test","tests","_tests"]);function _n(e){let t=se(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&&Sb.has(r.name))return!0}return!1}function ml(e,t){let n=se(e),r=se(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 pl(e,t){let n=se(e),r=se(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}function En(e,t){return e.all(`SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path, gs.display_name, gs.documentation
11
34
  FROM global_symbols gs
12
35
  JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
13
36
  JOIN documents d ON der.document_id = d.id
14
37
  WHERE ${t.where}
15
38
  ${e.pathExclusionsFor("d")}
16
- ${ka(t.orderBy)}
17
- ${Ea(t.limit)}`,...t.params??[])}function tn(e,t){return e.all(`SELECT
39
+ ${gl(t.orderBy)}
40
+ ${hl(t.limit)}`,...t.params??[])}function Fn(e,t){return e.all(`SELECT
18
41
  gs.id,
19
42
  gs.symbol,
20
43
  c.document_id,
@@ -31,8 +54,8 @@ import{program as ki}from"commander";import{realpathSync as xd}from"fs";import{f
31
54
  AND ${t.where}
32
55
  ${e.pathExclusionsFor("d")}
33
56
  GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name, gs.documentation
34
- ${ka(t.orderBy)}
35
- ${Ea(t.limit)}`,...t.params??[])}function ka(e){return e?`ORDER BY ${e}`:""}function Ea(e){return typeof e=="number"?`LIMIT ${e}`:""}function Rt(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 It(e){if(!e)return null;let t=wa(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(wa(r)??r).replace(/\n/g," ")}function wa(e){return/^```(?:\w+)?\s*\n?([\s\S]*?)\n?```/.exec(e.trimStart())?.[1]?.trim()||null}function cp(e){if(je(e.symbol)!==null)return!1;let n=(e.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(n)}function nn(e,t,n={}){let r=new Map;for(let o of t)e.length>0&&!cp(o)||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 lp=W("file-definitions",{clearGroups:["definition-catalog"]});function V(e,t){return lp.get(e,t,()=>{let n=nn(up(e,t),mp(e,t),{sort:!0});return pp(e,t,n.map(dp))})}function up(e,t){return e.all(`SELECT
57
+ ${gl(t.orderBy)}
58
+ ${hl(t.limit)}`,...t.params??[])}function gl(e){return e?`ORDER BY ${e}`:""}function hl(e){return typeof e=="number"?`LIMIT ${e}`:""}function Wt(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 Ut(e){if(!e)return null;let t=fl(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(fl(r)??r).replace(/\n/g," ")}function fl(e){return/^```(?:\w+)?\s*\n?([\s\S]*?)\n?```/.exec(e.trimStart())?.[1]?.trim()||null}function xb(e){if(Xe(e.symbol)!==null)return!1;let n=(e.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(n)}function Tn(e,t,n={}){let r=new Map;for(let o of t)e.length>0&&!xb(o)||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 Cb=W("file-definitions",{clearGroups:["definition-catalog"]}),bl=new WeakMap;function J(e,t){return Cb.get(e,t,()=>{let n=Tn(vb(e,t),Rb(e,t),{sort:!0});return Ib(e,t,n.map(Lb))})}function vb(e,t){return e.all(`SELECT
36
59
  gs.id,
37
60
  gs.symbol,
38
61
  der.document_id,
@@ -48,7 +71,7 @@ import{program as ki}from"commander";import{realpathSync as xd}from"fs";import{f
48
71
  JOIN documents d ON der.document_id = d.id
49
72
  WHERE d.relative_path = ?
50
73
  ${e.symbolNoiseFor("gs")}
51
- ORDER BY der.start_line, der.end_line`,t)}function mp(e,t){return e.all(`SELECT
74
+ ORDER BY der.start_line, der.end_line`,t)}function Rb(e,t){return e.all(`SELECT
52
75
  gs.id,
53
76
  gs.symbol,
54
77
  c.document_id,
@@ -67,10 +90,10 @@ import{program as ki}from"commander";import{realpathSync as xd}from"fs";import{f
67
90
  AND m.role = 1
68
91
  ${e.symbolNoiseFor("gs")}
69
92
  GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
70
- ORDER BY start_line, end_line`,t)}function dp(e){return{symbolId:e.id,symbol:e.symbol,documentId:e.document_id,startLine:e.start_line,endLine:e.end_line,relativePath:e.relative_path,leaf:F(e.symbol),parentTypeName:je(e.symbol),isFunctionLike:Y(e.symbol),isTypeLike:te(e.symbol)==="type",kind:e.kind??null,documentation:e.documentation??null,enclosingSymbol:e.enclosing_symbol??null}}function Be(e,t={}){return ji(e,t.scope)}function ji(e,t){return T(e,{scope:t,includeIgnored:!1}).flatMap(n=>V(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function yr(e,t,n={}){if(t.length===0)return[];let r=t.flatMap(i=>V(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:b(i.symbol),signature:Rt(It(i.documentation)),relativePath:i.relativePath,enclosingSymbol:i.enclosingSymbol}))}function Ce(e,t){let n=null;for(let r of e)r.startLine>t||r.endLine<t||(!n||r.endLine-r.startLine<n.endLine-n.startLine)&&(n=r);return n}function vt(e,t){let n=V(e,t.relative_path).find(r=>r.symbolId===t.id);return n?{symbolId:n.symbolId,symbol:n.symbol,documentId:n.documentId,startLine:n.startLine,endLine:n.endLine,relativePath:n.relativePath}:{symbolId:t.id,symbol:t.symbol,documentId:t.document_id,startLine:t.start_line,endLine:t.end_line,relativePath:t.relative_path}}function pp(e,t,n){let r=M(e,t),i=Oi(e,t);return i?Sp(n,i,r):r?fp(n,r):n}function fp(e,t){let n=t.split(/\r?\n/),r=gp(e,n),i=hp(e,r),o=yp(i,n);return bp(e,o)}function gp(e,t){let n=e.some(i=>br(i.symbol))?Rp(t):null,r=new Map;for(let i of e)r.set(i.symbolId,Cp(t,n,i));return r}function hp(e,t){return e.filter(n=>br(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 yp(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:Ip(t,i.definition,i.startLine,s)})}return n}function bp(e,t){return e.map(n=>{let r=t.get(n.symbolId);return r?{...n,startLine:r.startLine,endLine:r.endLine}:n})}function Sp(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(!xp(i)||!i.leaf)return Pa(i,n);let o=r.get(i.leaf);if(!o||o.length===0)return Pa(i,n);let s=o[0],a=Math.abs(s.startLine-i.startLine);for(let c=1;c<o.length;c+=1){let l=o[c],u=Math.abs(l.startLine-i.startLine);u<a&&(s=l,a=u)}return{...i,startLine:s.startLine,endLine:s.endLine}})}function xp(e){return br(e.symbol)?!0:te(e.symbol)==="term"&&je(e.symbol)===null}function Pa(e,t){if(!t||!e.leaf||te(e.symbol)!=="term"||je(e.symbol)!==null)return e;let n=e.leaf.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),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 Cp(e,t,n){if(!br(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 Rp(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 Ip(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=vp(e[l]??"");for(let m of u)m==="{"?(s+=1,c=!0):m==="}"?s=Math.max(0,s-1):m==="("?a+=1:m===")"&&(a=Math.max(0,a-1));if(c&&s===0||!c&&a===0&&l>=o)return l}return o}function vp(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 br(e){return e.includes("().")}function Sr(e){let t=ee(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}import{existsSync as $p}from"fs";import{basename as Fa,isAbsolute as jp,join as Bp}from"path";function A(e,t){let n=on(e,t.trim());if(n)return n;let r=kp(e,t);if(r)return r;let i=Dp(e,t);return i||wp(e,t)}function Dp(e,t){let n=Hi(t),r=Bi(n);if(!r)return null;let i=`%${r.path}%`,o=r.leaf,a=Np(e,i,o,n)[0];return a?vt(e,a):null}function Np(e,t,n,r){let i=nn([],[..._p(e,t,n),...Lp(e,t,n)]).filter(o=>!e.isIgnored(o.relative_path)).filter(o=>rn(o,r)>1);return i.sort((o,s)=>rn(s,r)-rn(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 _p(e,t,n){return en(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function Lp(e,t,n){return tn(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function wp(e,t){let n=Hi(t),r=Mp(t),i=Ap(e,r),o=Op(i,t,n);if(o&&!e.isIgnored(o.relative_path))return vt(e,o);let s=null;for(let a of i){if(e.isIgnored(a.relative_path))continue;let c=Tp(a,t,n,r);c<=0||(!s||c>s.score)&&(s={row:a,score:c})}return s?vt(e,s.row):null}function kp(e,t){let n=t.match(/^(.+):(\d+)-(\d+)$/);if(!n)return null;let[,r,i,o]=n,s=Math.max(0,parseInt(i,10)-1),a=Math.max(s,parseInt(o,10)-1),c=Ep(e,r,s,a)??Pp(e,r,s,a);return c&&!e.isIgnored(c.relative_path)?vt(e,c):null}function Ep(e,t,n,r){return en(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 Pp(e,t,n,r){return tn(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 on(e,t){let r=en(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, der.start_line",limit:1})[0]??tn(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, start_line",limit:1})[0];return!r||e.isIgnored(r.relative_path)?null:vt(e,r)}function xr(e,t){if("symbol"in t&&"relativePath"in t)return t;let n=Fp(e,t.symbolId)[0];return n?vt(e,n):null}function Fp(e,t){let n=en(e,{where:"gs.id = ?",params:[t],orderBy:"der.start_line, der.end_line"}),r=tn(e,{where:"gs.id = ?",params:[t],orderBy:"start_line, end_line"});return nn(n,r)}function Ap(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(`
71
- AND `),o=en(e,{where:i,params:r,limit:200}),s=tn(e,{where:i,params:r,limit:200});return nn(o,s)}function Tp(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,m=b(e.symbol),d=F(e.symbol),p=e.display_name??"",h=e.symbol.toLowerCase(),f=m.toLowerCase(),y=d.toLowerCase(),R=p.toLowerCase(),k=e.relative_path.toLowerCase(),S=/[/:.]/.test(n),x=Bi(n),D=x?.leaf.toLowerCase(),w=0;return(u===i||u===o)&&(w+=1150),(m===i||m===o)&&(w+=1100),p===s&&(w+=1180),d===s&&(w+=1160),(`${d}()`===i||`${d}()`===o)&&(w+=955),(h===a||h===c)&&(w+=1e3),(f===a||f===c)&&(w+=950),(k===a||k===c)&&(w+=925),(k.endsWith(`/${c}`)||k.endsWith(`/${a}`))&&(w+=875),R===l&&(w+=850),y===l&&(w+=825),(`${y}()`===a||`${y}()`===c)&&(w+=820),(f.endsWith(`:${c}`)||f.endsWith(`:${l}`)||f.endsWith(`:${l}()`))&&(w+=800),h.includes(c)&&(w+=120),f.includes(c)&&(w+=140),k.includes(c)&&(w+=140),R.includes(c)&&(w+=110),r.every($=>{let P=$.toLowerCase();return h.includes(P)||f.includes(P)||k.includes(P)||R.includes(P)})&&(w+=100+r.length*15),x&&k.includes(x.path.toLowerCase())&&(w+=360,D&&(y===D||`${y}()`===D||`${y}()`==`${D}()`)&&(w+=700),oe(e.symbol)&&(w+=180)),Y(e.symbol)&&y===l&&(w+=60),!S&&at(e.symbol)&&(w-=160),w-=Math.min(50,Math.max(0,e.end_line-e.start_line)),w}function Bi(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 Hi(e){return e.trim().replace(/\(\)$/,"").replace(/\(.*$/,"")}function Mp(e){let t=Hi(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 Op(e,t,n){let r=t.trim(),i=e.filter(o=>{let s=b(o.symbol),a=(o.display_name??"").trim();return o.symbol===r||s===r||s===n||a===r||a===n||`${a}()`===r||rn(o,n)>1||o.relative_path===r});return i.length===0?null:(i.sort((o,s)=>rn(s,n)-rn(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[0]??null)}function rn(e,t){let n=Bi(t);if(!n)return 0;let r=e.relative_path.toLowerCase(),i=F(e.symbol).toLowerCase(),o=n.path.toLowerCase(),s=n.leaf.toLowerCase();return r.includes(o)?i!==s?1:oe(e.symbol)?je(e.symbol)===null?5:4:je(e.symbol)===null?3:2:0}function pe(e,t){let n=Aa(e,t,{allowMultiple:!1})[0]?.relativePath;return n||Hp(e,t)}function sn(e,t){return Aa(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function Hp(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=jp(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,i=Bp(e.config.projectRoot,r);return $p(i)?r:null}function Aa(e,t,n){let r=Ta(t);if(!r)return[];let i=T(e,{includeIgnored:!1}).map(a=>({relativePath:a,score:qp(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=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 qp(e,t){let n=Ta(e),r=Fa(n),i=Fa(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 Ta(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}import{basename as zh}from"path";import{existsSync as Cr}from"fs";import{basename as Vp,dirname as ct,extname as ze,join as ke,relative as Nn,resolve as Re}from"path";var Wp=de("indexed-paths",{clearGroups:[]}),Dt=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],Rr=[".py",".pyi"],ye=[".java",".scala",".kt",".kts"],Ir=[".rs"],vr=[".rb"],Dr=[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],lt=[".cs",".vb"],Nr=[".dart"],Nt=[".php"],Up=new Set(Dt),qi=new Set(Rr),Ma=new Set(ye),Vi=new Set(Ir),Wi=new Set(vr),Oa=new Set(Dr),$a=new Set(lt),Ui=new Set(Nr),ja=new Set(Nt),Gp=[{extensions:Dt,lookup:Up},{extensions:Rr,lookup:qi},{extensions:ye,lookup:Ma},{extensions:Ir,lookup:Vi},{extensions:vr,lookup:Wi},{extensions:Dr,lookup:Oa},{extensions:lt,lookup:$a},{extensions:Nr,lookup:Ui},{extensions:Nt,lookup:ja}];function ut(e,t){return t.has(ze(e).toLowerCase())}function Jp(e){return ut(e,qi)}function zp(e){return ut(e,Ma)}function Kp(e){return ut(e,Vi)}function Qp(e){return ut(e,Wi)}function Yp(e){return ut(e,Oa)}function Xp(e){return ut(e,$a)}function Ba(e){return ze(e).toLowerCase()===".vb"}function Zp(e){return ut(e,Ui)}function ef(e){return ut(e,ja)}function Gi(e){let t=ze(e).toLowerCase();for(let n of Gp)if(n.lookup.has(t))return n.extensions;return Dt}function tf(e){return zp(e)||Xp(e)||ef(e)}function Pe(e,t,n){return Jp(t)?an(e,t,n):Kp(t)?Ke(e,t,n):Qp(t)?_r(e,t,n):Yp(t)?Lr(e,t,n):tf(t)?J(e,n.replace(/\\/g,"."),Gi(t)):Zp(t)?wr(e,t,n):nf(e,t,n)}function nf(e,t,n){if(!n.startsWith(".")&&!n.startsWith("/"))return null;let r=ct(ke(e.config.projectRoot,t)),i=Re(r,n),o=_n(e);for(let s of cf(i)){let a=Ee(Nn(e.config.projectRoot,s));if(o.has(a)||Cr(s))return a}return Ee(Nn(e.config.projectRoot,i))}function an(e,t,n){let r=_n(e),i;if(n.startsWith(".")){let o=n.match(/^(\.+)(.*)$/);if(!o)return null;let s=o[1].length,a=o[2].replace(/^\./,""),c=ct(ke(e.config.projectRoot,t));for(let l=1;l<s;l++)c=ct(c);i=a?Re(c,a.replace(/\./g,"/")):c}else i=Re(e.config.projectRoot,n.replace(/\./g,"/"));for(let o of rf(i)){let s=Ee(Nn(e.config.projectRoot,o));if(r.has(s)||Cr(o))return s}return null}function Ke(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=ct(ke(e.config.projectRoot,t)),o;return r.startsWith("crate::")?o=Re(e.config.projectRoot,"src",r.slice(7).replace(/::/g,"/")):r.startsWith("self::")?o=Re(i,r.slice(6).replace(/::/g,"/")):o=Re(ct(i),r.slice(7).replace(/::/g,"/")),Ji(e,of(o))}function _r(e,t,n){let r=ct(ke(e.config.projectRoot,t)),i=Re(r,n);return Ji(e,sf(i))}function Lr(e,t,n){let r=ct(ke(e.config.projectRoot,t)),i=[Re(r,n),Re(e.config.projectRoot,n),Re(e.config.projectRoot,"include",n),Re(e.config.projectRoot,"src",n)];return Ji(e,i)}function J(e,t,n){let r=_n(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(m=>m.endsWith(l));if(u)return u}for(let c of n){let l=[...r].find(u=>Vp(u)===`${s}${c}`);if(l)return l}let a=[...r].filter(c=>n.includes(ze(c).toLowerCase())).filter(c=>c.includes(`/${o}/`)||c.includes(`/${s}/`)).sort((c,l)=>c.localeCompare(l));return a.length===1?a[0]:null}function wr(e,t,n){let r=_n(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=ct(ke(e.config.projectRoot,t)),o=Re(i,n);for(let s of af(o)){let a=Ee(Nn(e.config.projectRoot,s));if(r.has(a)||Cr(s))return a}return null}function rf(e){let t=ze(e);return qi.has(t)?[e]:[`${e}.py`,`${e}.pyi`,ke(e,"__init__.py"),ke(e,"__init__.pyi")]}function Ji(e,t){let n=_n(e);for(let r of t){let i=Ee(Nn(e.config.projectRoot,r));if(n.has(i)||Cr(r))return i}return null}function of(e){let t=ze(e);return Vi.has(t)?[e]:[`${e}.rs`,ke(e,"mod.rs")]}function sf(e){let t=ze(e);return Wi.has(t)?[e]:[`${e}.rb`,ke(e,"index.rb")]}function af(e){let t=ze(e);return Ui.has(t)?[e]:[`${e}.dart`,e]}function cf(e){let t=ze(e),n=new Set;if(t){n.add(e);for(let r of Dt)n.add(e.slice(0,-t.length)+r)}else for(let r of Dt)n.add(`${e}${r}`),n.add(ke(e,`index${r}`));return[...n]}function _n(e){return Wp.get(e,()=>new Set(T(e,{includeIgnored:!1}).map(Ee)))}function Ee(e){return e.replace(/\\/g,"/")}import{basename as qa}from"path";function _t(e){return e.replace(/'''[\s\S]*?'''/g,mt).replace(/"""[\s\S]*?"""/g,mt).replace(/#.*$/gm,mt).replace(/\/\/.*$/gm,mt).replace(/\/\*[\s\S]*?\*\//g,mt).replace(/`(?:\\[\s\S]|[^`])*`/g,mt).replace(/'(?:\\.|[^'\\\r\n])*'/g,mt).replace(/"(?:\\.|[^"\\\r\n])*"/g,mt)}function mt(e){return e.replace(/[^\r\n]/g," ")}var rw=fr("stripped-lines",{clearGroups:["whole-project","source-file"]});st({name:"stripped-source-singleton",groups:["whole-project","source-file"],clearAll:()=>{kr=null,Ln=""},clearFile:()=>{kr=null,Ln=""}});var kr=null,Ln="";function lf(e){return kr===e||(kr=e,Ln=_t(e)),Ln}function dt(e,t,n){let r=lf(e);return`${r.slice(0,t)}${" ".repeat(n-t)}${r.slice(n)}`}function fe(e,t){return new RegExp(`\\b${Ha(t)}\\b`,"m").test(e)}function cn(e,t){let n=new Set,r=new RegExp(`\\b${Ha(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 Ha(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wn(e){let t=0;for(let n of e)n==="("&&(t+=1),n===")"&&(t-=1);return t}var uf=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 be(e,t){for(let n of e.namedChildren)if(n.type===t)return n;return null}function z(e,t){let n=new Set,r=(i,o)=>{let s=o||t.has(i.type);!s&&uf.has(i.type)&&n.add(i.text);for(let a of i.children)r(a,s)};return r(e.rootNode,!1),n}function He(e,t,n,r,i,o,s){return{importedName:i,localName:o,sourcePath:s??J(e,r,Gi(t)),kind:"named",used:fe(n,o),usedMembers:[]}}function U(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 ln(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 Lt(e,t){return{importedName:e,localName:null,sourcePath:t,kind:"side-effect",used:!0,usedMembers:[]}}function wt(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 Ie(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=dt(e,i.index,i.index+o.length);for(let a of n(i,s))r.push(a)}return r}function ve(e,t,n,r){let i=le(e,t);if(i){let o=n(i);if(o)return o}return r()}function Er(e,t,n,r){let i=le(e,t),o=B(t),s=o?n[o]:void 0;return i&&s?s(i):r()}function Va(e,t,n){return ve(e,t,r=>df(e,t,r),()=>mf(e,t,n))}function mf(e,t,n){return Ie(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(r,i)=>{let o=r[1]?.trim();if(!o)return[];let s=qa(o).replace(/\.[^.]+$/,"");return[ln(o,s,Lr(e,t,o),fe(i,s))]})}function df(e,t,n){let r=z(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=qa(s).replace(/\.[^.]+$/,"");i.push(U(s,a,Lr(e,t,s),r))}return i}function Wa(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=dt(n,i.index,i.index+a.length);r.push({importedName:o,localName:s,sourcePath:wr(e,t,o),kind:s?"namespace":"side-effect",used:s?fe(c,s):!0,usedMembers:s?cn(c,s):[]})}return r}function Ua(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:wr(e,t,o)})}return r}function Ga(e,t,n){return Er(e,t,{csharp:r=>ff(e,t,r),vb:r=>pf(e,t,r)},()=>{let r=Ba(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return Ie(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,m=u.split(".").pop()??u,d=l?a?.trim()??m:m;return[He(e,t,o,u,m,d,J(e,u,lt))]})})}function pf(e,t,n){let r=z(n,new Set(["imports_statement"])),i=[];for(let o of n.rootNode.descendantsOfType("imports_statement")){let s=o.namedChildren.filter(d=>d.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,m=c?.text??u;i.push(U(u,m,J(e,l,lt),r,c?"namespace":"named"))}return i}function ff(e,t,n){let r=z(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,m=a?.text??u;i.push(U(u,m,J(e,l,lt),r,a?"namespace":"named"))}return i}var gf=W("vue-non-script-identifiers",{clearGroups:["whole-project","source-file"]});function Ja(e,t){return gf.get(e,t,()=>{let n=new Set,r=M(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 zi(e,t,n){return ve(e,t,r=>yf(e,t,r),()=>hf(e,t,n))}function hf(e,t,n){return Lf(n).flatMap(r=>wf(e,t,r.clause,r.specifier,r.start,r.end,n))}function yf(e,t,n){let r=bf(e,t,n),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))i.push(...Sf(e,t,n,o,r));return i}function bf(e,t,n){let r=z(n,new Set(["import_statement"]));if(xt(t))for(let i of Ja(e,t))r.add(i);return r}function Sf(e,t,n,r,i){let o=vf(r);if(!o)return[];let s=Pe(e,t,o),a=be(r,"import_clause");return a?xf(n,a,s,i,Df(r.text)):[Lt("*",s)]}function xf(e,t,n,r,i){let o=[];for(let s of t.namedChildren)if(s.type==="identifier")o.push(Cf(s.text,n,r,i));else if(s.type==="namespace_import"){let a=Rf(e,s,n,r,i);a&&o.push(a)}else s.type==="named_imports"&&o.push(...If(s,n,r,i));return o}function Cf(e,t,n,r){return U("default",e,t,n,"default",{isTypeOnly:r})}function Rf(e,t,n,r,i){let s=be(t,"identifier")?.text??"";if(!s)return null;let a=_f(e,s);return wt("*",n,{localName:s,usedMembers:a,isTypeOnly:i,used:a.length>0||r.has(s)})}function If(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(U(c,l,t,n,"named",{isTypeOnly:r||Nf(o.text)}))}return i}function vf(e){let t=be(e,"string");if(!t)return null;let n=be(t,"string_fragment");return n?n.text:null}function Df(e){return/^\s*import\s+type\b/.test(e)}function Nf(e){return/^\s*type\b/.test(e.trim())}function _f(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 Lf(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 wf(e,t,n,r,i,o,s){let a=Pe(e,t,r),c=dt(s,i,o);return n?kf(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let m=cn(c,u.localName);return wt(u.importedName,u.sourcePath,{localName:u.localName,usedMembers:m,used:m.length>0||fe(c,u.localName),isTypeOnly:u.isTypeOnly})}return u.kind==="side-effect"?Lt(u.importedName,u.sourcePath):ln(u.importedName,u.localName??"",u.sourcePath,u.localName?fe(c,u.localName):!1,u.kind,[],{isTypeOnly:u.isTypeOnly})}):[Lt("*",a)]}function kf(e){let t=e.trim(),n=/^type\b/.test(t),r=t.replace(/^type\s+/,""),[i,o]=Ef(r),s=[];return i&&s.push(...za(i,n)),o&&s.push(...za(o,n)),s}function za(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 Ef(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 Ki(e,t,n){let r=le(e,t);return r?Of(e,t,r):Pf(e,t,n)}function Pf(e,t,n){return[...Ff(e,t,n),...Af(e,t,n),...Tf(e,t,n)]}function Ff(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(m=>Mf(m.trim())).filter(m=>!!m),l=un(n,o.index),u=un(n,o.index+o[0].length-1);r.push({kind:"named",sourcePath:Pe(e,t,a),names:c,startLine:l,endLine:u})}return r}function Af(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=un(n,o.index),c=un(n,o.index+o[0].length-1);r.push({kind:"star-as",sourcePath:Pe(e,t,s),names:[],startLine:a,endLine:c})}return r}function Tf(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=un(n,o.index),c=un(n,o.index+o[0].length-1);r.push({kind:"star",sourcePath:Pe(e,t,s),names:[],startLine:a,endLine:c})}return r}function Mf(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 un(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function Of(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("export_statement")){let o=$f(e,t,i);if(o===void 0)continue;let s=i.startPosition.row,a=i.endPosition.row,c=jf(i,o,s,a);r.push(c)}return r}function $f(e,t,n){let r=be(n,"string");if(!r)return;let i=be(r,"string_fragment");if(i)return Pe(e,t,i.text)}function jf(e,t,n,r){let i=be(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 be(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:r}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:r}}function Ka(e,t,n){return Er(e,t,{java:r=>Bf(e,t,r),kotlin:r=>Hf(e,t,r),scala:r=>qf(e,t,r)},()=>Ie(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(r,i)=>{let o=r[1]?.trim();return o?Vf(e,t,o,i):[]}))}function Bf(e,t,n){let r=z(n,new Set(["import_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.children.some(m=>m.type==="asterisk"),c=o.namedChildren.find(m=>m.type==="scoped_identifier")??o.namedChildren.find(m=>m.type==="identifier");if(!c)continue;let l=c.text;if(s){i.push(wt("*",J(e,l,ye)));continue}let u=l.split(".").pop()??l;i.push(U(u,u,J(e,l,ye),r))}return i}function Hf(e,t,n){let r=z(n,new Set(["import_header","import_list"])),i=[];for(let o of n.rootNode.descendantsOfType("import_header")){let s=o.namedChildren.find(p=>p.type==="identifier");if(!s)continue;let a=o.namedChildren.some(p=>p.type==="wildcard_import"),c=o.namedChildren.find(p=>p.type==="import_alias");if(a){i.push(wt("*",J(e,s.text,ye)));continue}let l=s.text,u=l.split(".").pop()??l,d=c?.namedChild(0)?.text??u;i.push(U(u,d,J(e,l,ye),r))}return i}function qf(e,t,n){let r=z(n,new Set(["import_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.namedChildren.find(m=>m.type==="namespace_selectors"||m.type==="namespace_wildcard"),a=o.namedChildren.filter(m=>m!==s&&(m.type==="identifier"||m.type==="stable_identifier")),c=a.map(m=>m.text).join(".");if(!c)continue;if(s?.type==="namespace_wildcard"){i.push(wt("*",J(e,c,ye)));continue}if(s?.type==="namespace_selectors"){for(let m of s.namedChildren)if(m.type==="arrow_renamed_identifier"){let[d,p]=m.namedChildren;if(!d)continue;let h=d.text,f=p?.text??h;if(h==="_")continue;i.push(U(h,f,J(e,`${c}.${h}`,ye),r))}else if(m.type==="identifier"){let d=m.text;i.push(U(d,d,J(e,`${c}.${d}`,ye),r))}continue}let l=a[a.length-1]?.text??c,u=a.slice(0,-1).map(m=>m.text).join(".")||c;i.push(U(l,l,J(e,u&&a.length>1?`${u}.${l}`:c,ye),r))}return i}function Vf(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 m=(l??u.split(".").pop()??u).trim(),d=u==="_"?i:`${i}.${u}`.replace(/\.\./g,".");return[He(e,t,r,d,u,m)]})}return[He(e,t,r,n,n.split(".").pop()??n,n.split(".").pop()??n)]}function Ya(e,t,n){return ve(e,t,r=>Wf(e,t,r),()=>Ie(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,m=u.split("\\").pop()??u,d=(l??m).trim();return[He(e,t,i,u,m,d,J(e,u.replace(/\\/g,"."),Nt))]}):[]}))}function Wf(e,t,n){let r=z(n,new Set(["namespace_use_declaration"])),i=[],o=(s,a,c)=>{i.push(U(a,c,J(e,s.replace(/\\/g,"."),Nt),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:m,qualified:d}=Qa(l,c);u&&o(d,u,m)}continue}for(let c of s.namedChildren){if(c.type!=="namespace_use_clause")continue;let{importedName:l,localName:u,qualified:m}=Qa(c,"");l&&o(m,l,u)}}return i}function Qa(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 Za(e,t,n){return ve(e,t,r=>Uf(e,t,r),()=>Jf(n).flatMap(r=>Kf(e,t,r,n)))}function Uf(e,t,n){let r=z(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=Xa(s);if(!a)continue;let c=an(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=Gf(s);if(a===null)continue;let c=an(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 m=Xa(u);m&&i.push({importedName:m.qualifiedName,localName:m.localName,sourcePath:c,kind:"named",used:r.has(m.localName),usedMembers:[]})}}return i}function Xa(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 Gf(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=be(e,"import_prefix")?.text??"",n=be(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function Jf(e){let t=e.split(`
72
- `),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=wn(o);for(;i+1<t.length&&(u>0||c.trimEnd().endsWith("\\"));){i++;let d=t[i];c+=`
73
- ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,end:l})}return n}function zf(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 Kf(e,t,n,r){let i=dt(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,m]=l.split(/\s+as\s+/),d=u.trim(),p=(m??d.split(".")[0]??d).trim(),h=an(e,t,d),f=cn(i,p);return[{importedName:d,localName:p,sourcePath:h,kind:"namespace",used:fe(i,p)||f.length>0,usedMembers:f}]});let s=n.module?an(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,m]=l.split(/\s+as\s+/),d=(m??u).trim();a.push({importedName:u.trim(),localName:d,sourcePath:s,kind:"named",used:fe(i,d),usedMembers:[]})}return a}import{basename as Qf}from"path";function ec(e,t,n){return ve(e,t,r=>Xf(e,t,r),()=>Yf(e,t,n))}function Yf(e,t,n){return Ie(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"?_r(e,t,s):null;if(a){let c=tc(s);return[ln(c,c,a,fe(i,c))]}return[Lt(s,a)]})}function Xf(e,t,n){let r=z(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(p=>p.type==="argument_list")?.namedChild(0);if(!l||l.type!=="string")continue;let m=l.namedChildren.find(p=>p.type==="string_content")?.text;if(!m)continue;let d=a.text==="require_relative"?_r(e,t,m):null;if(d){let p=tc(m);i.push(U(p,p,d,r))}else i.push(Lt(m,d))}return i}function tc(e){return Qf(e).replace(/\.[^.]+$/,"").split("_").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function nc(e,t,n){return ve(e,t,r=>Zf(e,t,r),()=>Ie(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?eg(e,t,o,i):[]}))}function Zf(e,t,n){let r=z(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 kn(s,"")){if(!a.importedName||a.importedName==="*")continue;let c=Ke(e,t,a.qualifiedName)??Ke(e,t,a.qualifiedName.split("::").slice(0,-1).join("::"));i.push(U(a.importedName,a.localName,c,r))}}return i}function kn(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":{let n=e.text;return[{qualifiedName:Pr(t,n),importedName:n,localName:n}]}case"scoped_identifier":{let n=e.text,r=n.split("::").pop()??n;return[{qualifiedName:Pr(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=Pr(t,n.text),o=[];for(let s of r.namedChildren)o.push(...kn(s,i));return o}case"use_list":{let n=[];for(let r of e.namedChildren)n.push(...kn(r,t));return n}case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=kn(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:Pr(t,`${r}::*`),importedName:"*",localName:"*"}]}default:return[]}}function Pr(e,t){return e?t?`${e}::${t}`:e:t}function eg(e,t,n,r){let i=n.trim();if(i.includes("{")&&i.includes("}")){let u=i.slice(0,i.indexOf("{")).replace(/::$/,"").trim(),m=i.slice(i.indexOf("{")+1,i.lastIndexOf("}")).trim();return ge(m).flatMap(d=>{let p=d.trim();if(!p||p==="self")return[];let[h,f]=p.split(/\s+as\s+/),y=h?.trim();if(!y)return[];let R=(f??y.split("::").pop()??y).trim(),k=`${u}::${y}`.replace(/::::/g,"::");return[He(e,t,r,k,y.split("::").pop()??y,R,Ke(e,t,u))]})}let[o,s]=i.split(/\s+as\s+/),a=o?.trim()??i,c=(s??a.split("::").pop()??a).trim(),l=Ke(e,t,a)??Ke(e,t,a.split("::").slice(0,-1).join("::"));return[He(e,t,r,a,a.split("::").pop()??a,c,l)]}function rc(e,t,n){let r=le(e,t);if(r)return tg(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(...rg(e,t,s))}return i}function tg(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("use_declaration")){if(!ng(i))continue;let o=i.namedChildren.find(s=>s.type!=="visibility_modifier");if(o)for(let s of kn(o,""))s.importedName&&r.push(Qi(e,t,s.qualifiedName))}return r}function ng(e){for(let t of e.children)if(t.type==="visibility_modifier"&&t.text.startsWith("pub"))return!0;return!1}function rg(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[Qi(e,t,l)]})}return[Qi(e,t,r)]}function Qi(e,t,n){return{specifier:n,sourcePath:Ke(e,t,n)??Ke(e,t,n.split("::").slice(0,-1).join("::"))}}function kt({language:e,extensions:t,imports:n,parseImports:r}){return{language:e,extensions:t,capabilities:{imports:n},parseImports:r}}function ic(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 ig={language:"javascript",extensions:Dt,capabilities:{imports:"ast-with-regex-fallback",reExports:"ast-with-regex-fallback"},parseImports:zi,parseReExports:Ki},og=kt({language:"python",extensions:Rr,imports:"ast-with-regex-fallback",parseImports:Za}),sg=kt({language:"jvm",extensions:ye,imports:"ast-dispatch-with-regex-fallback",parseImports:Ka}),ag={language:"rust",extensions:Ir,capabilities:{imports:"ast-with-regex-fallback",exports:"ast-with-regex-fallback"},parseImports:nc,parseExports:rc},cg=kt({language:"ruby",extensions:vr,imports:"ast-with-regex-fallback",parseImports:ec}),lg=kt({language:"c/cpp",extensions:Dr,imports:"ast-with-regex-fallback",parseImports:Va}),ug=kt({language:"dotnet",extensions:lt,imports:"ast-dispatch-with-regex-fallback",parseImports:Ga}),mg={language:"dart",extensions:Nr,capabilities:{imports:"regex-only",exports:"regex-only"},parseImports:Wa,parseExports:Ua},dg=kt({language:"php",extensions:Nt,imports:"ast-with-regex-fallback",parseImports:Ya}),pg=[ig,og,sg,ag,cg,lg,ug,mg,dg];function Fr(e){return ic(pg,e)}var Yi={clearGroups:["whole-project","source-file"]},fg=W("source-imports",Yi),gg=W("source-exports",Yi),hg=W("source-reexports",Yi);function oc(e,t){let n=Ee(t);return hg.get(e,n,()=>{let r=Fr(n);if(!r?.parseReExports)return[];let i=M(e,n);return i?r.parseReExports(e,n,i):[]})}function ne(e,t){let n=Ee(t);return fg.get(e,n,()=>{let r=Fr(n);if(!r)return[];let i=M(e,n);return i?r.parseImports(e,n,i):[]})}function Xi(e,t){let n=Ee(t);return gg.get(e,n,()=>{let r=Fr(n);if(!r?.parseExports)return[];let i=M(e,n);return i?r.parseExports(e,n,i):[]})}var yg=W("file-dep-graph",{clearGroups:["whole-project"]});function se(e,t){return yg.get(e,t??"",()=>{let n=new Map,r=new Set(T(e,{includeIgnored:!1})),i=(o,s)=>Sg(e,n,r,o,s);for(let o of bg(e,t))i(o.from_file,o.to_file);for(let o of r)if(!(t&&!o.includes(t)))for(let s of ne(e,o))s.sourcePath&&i(o,s.sourcePath);return n})}function bg(e,t){let n=t?`AND d1.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
93
+ ORDER BY start_line, end_line`,t)}function Lb(e){return{symbolId:e.id,symbol:e.symbol,documentId:e.document_id,startLine:e.start_line,endLine:e.end_line,relativePath:e.relative_path,leaf:$(e.symbol),parentTypeName:Xe(e.symbol),isFunctionLike:te(e.symbol),isTypeLike:ae(e.symbol)==="type",kind:e.kind??null,documentation:e.documentation??null,enclosingSymbol:e.enclosing_symbol??null}}function Ye(e,t={}){return ur(e,t.scope)}function ur(e,t){return V(e,{scope:t,includeIgnored:!1}).flatMap(n=>J(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function gi(e,t,n={}){if(t.length===0)return[];let r=t.flatMap(i=>J(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:y(i.symbol),signature:Wt(Ut(i.documentation)),relativePath:i.relativePath,enclosingSymbol:i.enclosingSymbol}))}function Qo(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 Ae(e,t){let n=bl.get(e);return n||(n=Qo(e),bl.set(e,n)),n.get(t)??null}function Jt(e,t){let n=J(e,t.relative_path).find(r=>r.symbolId===t.id);return n?{symbolId:n.symbolId,symbol:n.symbol,documentId:n.documentId,startLine:n.startLine,endLine:n.endLine,relativePath:n.relativePath}:{symbolId:t.id,symbol:t.symbol,documentId:t.document_id,startLine:t.start_line,endLine:t.end_line,relativePath:t.relative_path}}function Ib(e,t,n){let r=A(e,t),i=Jo(e,t);return i?_b(n,i,r):r?Db(n,r):n}function Db(e,t){let n=t.split(/\r?\n/),r=kb(e,n),i=wb(e,r),o=Nb(i,n);return Pb(e,o)}function kb(e,t){let n=e.some(i=>hi(i.symbol))?Tb(t):null,r=new Map;for(let i of e)r.set(i.symbolId,Fb(t,n,i));return r}function wb(e,t){return e.filter(n=>hi(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 Nb(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:Ab(t,i.definition,i.startLine,s)})}return n}function Pb(e,t){return e.map(n=>{let r=t.get(n.symbolId);return r?{...n,startLine:r.startLine,endLine:r.endLine}:n})}function _b(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(!Eb(i)||!i.leaf)return yl(i,n);let o=r.get(i.leaf);if(!o||o.length===0)return yl(i,n);let s=o[0],a=Math.abs(s.startLine-i.startLine);for(let c=1;c<o.length;c+=1){let l=o[c],u=Math.abs(l.startLine-i.startLine);u<a&&(s=l,a=u)}return{...i,startLine:s.startLine,endLine:s.endLine}})}function Eb(e){return hi(e.symbol)?!0:ae(e.symbol)==="term"&&Xe(e.symbol)===null}function yl(e,t){if(!t||!e.leaf||ae(e.symbol)!=="term"||Xe(e.symbol)!==null)return e;let n=e.leaf.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),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 Fb(e,t,n){if(!hi(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 Tb(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 Ab(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=$b(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 $b(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 hi(e){return e.includes("().")}function bi(e){let t=se(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}import{existsSync as Qb}from"fs";import{basename as Sl,isAbsolute as Xb,join as Yb}from"path";function B(e,t){let n=$n(e,t.trim());if(n)return n;let r=Hb(e,t);if(r)return r;let i=Mb(e,t);return i||Vb(e,t)}function Mb(e,t){let n=Yo(t),r=Xo(n);if(!r)return null;let i=`%${r.path}%`,o=r.leaf,a=Ob(e,i,o,n)[0];return a?Jt(e,a):null}function Ob(e,t,n,r){let i=Tn([],[...jb(e,t,n),...Bb(e,t,n)]).filter(o=>!e.isIgnored(o.relative_path)).filter(o=>An(o,r)>1);return i.sort((o,s)=>An(s,r)-An(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 jb(e,t,n){return En(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function Bb(e,t,n){return Fn(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function Vb(e,t){let n=Yo(t),r=zb(t),i=Jb(e,r),o=Kb(i,t,n);if(o&&!e.isIgnored(o.relative_path))return Jt(e,o);let s=null;for(let a of i){if(e.isIgnored(a.relative_path))continue;let c=Gb(a,t,n,r);c<=0||(!s||c>s.score)&&(s={row:a,score:c})}return s?Jt(e,s.row):null}function Hb(e,t){let n=t.match(/^(.+):(\d+)-(\d+)$/);if(!n)return null;let[,r,i,o]=n,s=Math.max(0,parseInt(i,10)-1),a=Math.max(s,parseInt(o,10)-1),c=qb(e,r,s,a)??Wb(e,r,s,a);return c&&!e.isIgnored(c.relative_path)?Jt(e,c):null}function qb(e,t,n,r){return En(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 Wb(e,t,n,r){return Fn(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 $n(e,t){let r=En(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, der.start_line",limit:1})[0]??Fn(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, start_line",limit:1})[0];return!r||e.isIgnored(r.relative_path)?null:Jt(e,r)}function yi(e,t){if("symbol"in t&&"relativePath"in t)return t;let n=Ub(e,t.symbolId)[0];return n?Jt(e,n):null}function Ub(e,t){let n=En(e,{where:"gs.id = ?",params:[t],orderBy:"der.start_line, der.end_line"}),r=Fn(e,{where:"gs.id = ?",params:[t],orderBy:"start_line, end_line"});return Tn(n,r)}function Jb(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(`
94
+ AND `),o=En(e,{where:i,params:r,limit:200}),s=Fn(e,{where:i,params:r,limit:200});return Tn(o,s)}function Gb(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=y(e.symbol),m=$(e.symbol),f=e.display_name??"",g=e.symbol.toLowerCase(),h=d.toLowerCase(),b=m.toLowerCase(),L=f.toLowerCase(),F=e.relative_path.toLowerCase(),k=/[/:.]/.test(n),E=Xo(n),C=E?.leaf.toLowerCase(),w=0;return(u===i||u===o)&&(w+=1150),(d===i||d===o)&&(w+=1100),f===s&&(w+=1180),m===s&&(w+=1160),(`${m}()`===i||`${m}()`===o)&&(w+=955),(g===a||g===c)&&(w+=1e3),(h===a||h===c)&&(w+=950),(F===a||F===c)&&(w+=925),(F.endsWith(`/${c}`)||F.endsWith(`/${a}`))&&(w+=875),L===l&&(w+=850),b===l&&(w+=825),(`${b}()`===a||`${b}()`===c)&&(w+=820),(h.endsWith(`:${c}`)||h.endsWith(`:${l}`)||h.endsWith(`:${l}()`))&&(w+=800),g.includes(c)&&(w+=120),h.includes(c)&&(w+=140),F.includes(c)&&(w+=140),L.includes(c)&&(w+=110),r.every(M=>{let j=M.toLowerCase();return g.includes(j)||h.includes(j)||F.includes(j)||L.includes(j)})&&(w+=100+r.length*15),E&&F.includes(E.path.toLowerCase())&&(w+=360,C&&(b===C||`${b}()`===C||`${b}()`==`${C}()`)&&(w+=700),pe(e.symbol)&&(w+=180)),te(e.symbol)&&b===l&&(w+=60),!k&&wt(e.symbol)&&(w-=160),w-=Math.min(50,Math.max(0,e.end_line-e.start_line)),w}function Xo(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 Yo(e){return e.trim().replace(/\(\)$/,"").replace(/\(.*$/,"")}function zb(e){let t=Yo(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 Kb(e,t,n){let r=t.trim(),i=e.filter(o=>{let s=y(o.symbol),a=(o.display_name??"").trim();return o.symbol===r||s===r||s===n||a===r||a===n||`${a}()`===r||An(o,n)>1||o.relative_path===r});return i.length===0?null:(i.sort((o,s)=>An(s,n)-An(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[0]??null)}function An(e,t){let n=Xo(t);if(!n)return 0;let r=e.relative_path.toLowerCase(),i=$(e.symbol).toLowerCase(),o=n.path.toLowerCase(),s=n.leaf.toLowerCase();return r.includes(o)?i!==s?1:pe(e.symbol)?Xe(e.symbol)===null?5:4:Xe(e.symbol)===null?3:2:0}function Ie(e,t){let n=xl(e,t,{allowMultiple:!1})[0]?.relativePath;return n||Zb(e,t)}function Mn(e,t){return xl(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function Zb(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=Xb(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,i=Yb(e.config.projectRoot,r);return Qb(i)?r:null}function xl(e,t,n){let r=Cl(t);if(!r)return[];let i=V(e,{includeIgnored:!1}).map(a=>({relativePath:a,score:ey(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=B(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 ey(e,t){let n=Cl(e),r=Sl(n),i=Sl(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 Cl(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}import{basename as rC}from"path";import{existsSync as Si}from"fs";import{basename as ty,dirname as Nt,extname as pt,join as We,relative as dr,resolve as $e}from"path";var ny=ie("indexed-paths",{clearGroups:[]}),Gt=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],xi=[".py",".pyi"],Ne=[".java",".scala",".kt",".kts"],Ci=[".rs"],vi=[".rb"],Ri=[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],Pt=[".cs",".vb"],Li=[".dart"],zt=[".php"],ry=new Set(Gt),Zo=new Set(xi),vl=new Set(Ne),es=new Set(Ci),ts=new Set(vi),Rl=new Set(Ri),Ll=new Set(Pt),ns=new Set(Li),Il=new Set(zt),iy=[{extensions:Gt,lookup:ry},{extensions:xi,lookup:Zo},{extensions:Ne,lookup:vl},{extensions:Ci,lookup:es},{extensions:vi,lookup:ts},{extensions:Ri,lookup:Rl},{extensions:Pt,lookup:Ll},{extensions:Li,lookup:ns},{extensions:zt,lookup:Il}];function _t(e,t){return t.has(pt(e).toLowerCase())}function oy(e){return _t(e,Zo)}function sy(e){return _t(e,vl)}function ay(e){return _t(e,es)}function cy(e){return _t(e,ts)}function ly(e){return _t(e,Rl)}function uy(e){return _t(e,Ll)}function Dl(e){return pt(e).toLowerCase()===".vb"}function dy(e){return _t(e,ns)}function my(e){return _t(e,Il)}function rs(e){let t=pt(e).toLowerCase();for(let n of iy)if(n.lookup.has(t))return n.extensions;return Gt}function py(e){return sy(e)||uy(e)||my(e)}function Je(e,t,n){return oy(t)?On(e,t,n):ay(t)?ft(e,t,n):cy(t)?Ii(e,t,n):ly(t)?Di(e,t,n):py(t)?Q(e,n.replace(/\\/g,"."),rs(t)):dy(t)?ki(e,t,n):fy(e,t,n)}function fy(e,t,n){if(!n.startsWith(".")&&!n.startsWith("/"))return null;let r=Nt(We(e.config.projectRoot,t)),i=$e(r,n),o=mr(e);for(let s of Sy(i)){let a=Ue(dr(e.config.projectRoot,s));if(o.has(a)||Si(s))return a}return Ue(dr(e.config.projectRoot,i))}function On(e,t,n){let r=mr(e),i;if(n.startsWith(".")){let o=n.match(/^(\.+)(.*)$/);if(!o)return null;let s=o[1].length,a=o[2].replace(/^\./,""),c=Nt(We(e.config.projectRoot,t));for(let l=1;l<s;l++)c=Nt(c);i=a?$e(c,a.replace(/\./g,"/")):c}else i=$e(e.config.projectRoot,n.replace(/\./g,"/"));for(let o of gy(i)){let s=Ue(dr(e.config.projectRoot,o));if(r.has(s)||Si(o))return s}return null}function ft(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=Nt(We(e.config.projectRoot,t)),o;return r.startsWith("crate::")?o=$e(e.config.projectRoot,"src",r.slice(7).replace(/::/g,"/")):r.startsWith("self::")?o=$e(i,r.slice(6).replace(/::/g,"/")):o=$e(Nt(i),r.slice(7).replace(/::/g,"/")),is(e,hy(o))}function Ii(e,t,n){let r=Nt(We(e.config.projectRoot,t)),i=$e(r,n);return is(e,by(i))}function Di(e,t,n){let r=Nt(We(e.config.projectRoot,t)),i=[$e(r,n),$e(e.config.projectRoot,n),$e(e.config.projectRoot,"include",n),$e(e.config.projectRoot,"src",n)];return is(e,i)}function Q(e,t,n){let r=mr(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=>ty(u)===`${s}${c}`);if(l)return l}let a=[...r].filter(c=>n.includes(pt(c).toLowerCase())).filter(c=>c.includes(`/${o}/`)||c.includes(`/${s}/`)).sort((c,l)=>c.localeCompare(l));return a.length===1?a[0]:null}function ki(e,t,n){let r=mr(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=Ue(c.startsWith("lib/")?c:`lib/${c}`);return r.has(l)?l:null}let i=Nt(We(e.config.projectRoot,t)),o=$e(i,n);for(let s of yy(o)){let a=Ue(dr(e.config.projectRoot,s));if(r.has(a)||Si(s))return a}return null}function gy(e){let t=pt(e);return Zo.has(t)?[e]:[`${e}.py`,`${e}.pyi`,We(e,"__init__.py"),We(e,"__init__.pyi")]}function is(e,t){let n=mr(e);for(let r of t){let i=Ue(dr(e.config.projectRoot,r));if(n.has(i)||Si(r))return i}return null}function hy(e){let t=pt(e);return es.has(t)?[e]:[`${e}.rs`,We(e,"mod.rs")]}function by(e){let t=pt(e);return ts.has(t)?[e]:[`${e}.rb`,We(e,"index.rb")]}function yy(e){let t=pt(e);return ns.has(t)?[e]:[`${e}.dart`,e]}function Sy(e){let t=pt(e),n=new Set;if(t){n.add(e);for(let r of Gt)n.add(e.slice(0,-t.length)+r)}else for(let r of Gt)n.add(`${e}${r}`),n.add(We(e,`index${r}`));return[...n]}function mr(e){return ny.get(e,()=>new Set(V(e,{includeIgnored:!1}).map(Ue)))}function Ue(e){return e.replace(/\\/g,"/")}import{basename as wl}from"path";function Kt(e){return e.replace(/'''[\s\S]*?'''/g,Et).replace(/"""[\s\S]*?"""/g,Et).replace(/#.*$/gm,Et).replace(/\/\/.*$/gm,Et).replace(/\/\*[\s\S]*?\*\//g,Et).replace(/`(?:\\[\s\S]|[^`])*`/g,Et).replace(/'(?:\\.|[^'\\\r\n])*'/g,Et).replace(/"(?:\\.|[^"\\\r\n])*"/g,Et)}function Et(e){return e.replace(/[^\r\n]/g," ")}var zT=Bt("stripped-lines",{clearGroups:["whole-project","source-file"]});kt({name:"stripped-source-singleton",groups:["whole-project","source-file"],clearAll:()=>{wi=null,pr=""},clearFile:()=>{wi=null,pr=""}});var wi=null,pr="";function xy(e){return wi===e||(wi=e,pr=Kt(e)),pr}function Ft(e,t,n){let r=xy(e);return`${r.slice(0,t)}${" ".repeat(n-t)}${r.slice(n)}`}function De(e,t){return new RegExp(`\\b${kl(t)}\\b`,"m").test(e)}function jn(e,t){let n=new Set,r=new RegExp(`\\b${kl(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 kl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fr(e){let t=0;for(let n of e)n==="("&&(t+=1),n===")"&&(t-=1);return t}var Cy=new Set(["identifier","type_identifier","property_identifier","shorthand_property_identifier","field_identifier"]);function ke(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 Pe(e,t){for(let n of e.namedChildren)if(n.type===t)return n;return null}function X(e,t){let n=new Set,r=(i,o)=>{let s=o||t.has(i.type);!s&&Cy.has(i.type)&&n.add(i.text);for(let a of i.children)r(a,s)};return r(e.rootNode,!1),n}function Ze(e,t,n,r,i,o,s){return{importedName:i,localName:o,sourcePath:s??Q(e,r,rs(t)),kind:"named",used:De(n,o),usedMembers:[]}}function K(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 Bn(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 Qt(e,t){return{importedName:e,localName:null,sourcePath:t,kind:"side-effect",used:!0,usedMembers:[]}}function Xt(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 Me(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=Ft(e,i.index,i.index+o.length);for(let a of n(i,s))r.push(a)}return r}function Oe(e,t,n,r){let i=oe(e,t);if(i){let o=n(i);if(o)return o}return r()}function Ni(e,t,n,r){let i=oe(e,t),o=U(t),s=o?n[o]:void 0;return i&&s?s(i):r()}function Nl(e,t,n){return Oe(e,t,r=>Ry(e,t,r),()=>vy(e,t,n))}function vy(e,t,n){return Me(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(r,i)=>{let o=r[1]?.trim();if(!o)return[];let s=wl(o).replace(/\.[^.]+$/,"");return[Bn(o,s,Di(e,t,o),De(i,s))]})}function Ry(e,t,n){let r=X(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=wl(s).replace(/\.[^.]+$/,"");i.push(K(s,a,Di(e,t,s),r))}return i}function Pl(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=Ft(n,i.index,i.index+a.length);r.push({importedName:o,localName:s,sourcePath:ki(e,t,o),kind:s?"namespace":"side-effect",used:s?De(c,s):!0,usedMembers:s?jn(c,s):[]})}return r}function _l(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:ki(e,t,o)})}return r}function El(e,t,n){return Ni(e,t,{csharp:r=>Iy(e,t,r),vb:r=>Ly(e,t,r)},()=>{let r=Dl(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return Me(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,m=l?a?.trim()??d:d;return[Ze(e,t,o,u,d,m,Q(e,u,Pt))]})})}function Ly(e,t,n){let r=X(n,new Set(["imports_statement"])),i=[];for(let o of n.rootNode.descendantsOfType("imports_statement")){let s=o.namedChildren.filter(m=>m.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(K(u,d,Q(e,l,Pt),r,c?"namespace":"named"))}return i}function Iy(e,t,n){let r=X(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(K(u,d,Q(e,l,Pt),r,a?"namespace":"named"))}return i}var Dy=W("vue-non-script-identifiers",{clearGroups:["whole-project","source-file"]});function Fl(e,t){return Dy.get(e,t,()=>{let n=new Set,r=A(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 os(e,t,n){return Oe(e,t,r=>wy(e,t,r),()=>ky(e,t,n))}function ky(e,t,n){return jy(n).flatMap(r=>By(e,t,r.clause,r.specifier,r.start,r.end,n))}function wy(e,t,n){let r=Ny(e,t,n),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))i.push(...Py(e,t,n,o,r));return i}function Ny(e,t,n){let r=X(n,new Set(["import_statement"]));if(ut(t))for(let i of Fl(e,t))r.add(i);return r}function Py(e,t,n,r,i){let o=Ay(r);if(!o)return[];let s=Je(e,t,o),a=Pe(r,"import_clause");return a?_y(n,a,s,i,$y(r.text)):[Qt("*",s)]}function _y(e,t,n,r,i){let o=[];for(let s of t.namedChildren)if(s.type==="identifier")o.push(Ey(s.text,n,r,i));else if(s.type==="namespace_import"){let a=Fy(e,s,n,r,i);a&&o.push(a)}else s.type==="named_imports"&&o.push(...Ty(s,n,r,i));return o}function Ey(e,t,n,r){return K("default",e,t,n,"default",{isTypeOnly:r})}function Fy(e,t,n,r,i){let s=Pe(t,"identifier")?.text??"";if(!s)return null;let a=Oy(e,s);return Xt("*",n,{localName:s,usedMembers:a,isTypeOnly:i,used:a.length>0||r.has(s)})}function Ty(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(K(c,l,t,n,"named",{isTypeOnly:r||My(o.text)}))}return i}function Ay(e){let t=Pe(e,"string");if(!t)return null;let n=Pe(t,"string_fragment");return n?n.text:null}function $y(e){return/^\s*import\s+type\b/.test(e)}function My(e){return/^\s*type\b/.test(e.trim())}function Oy(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 jy(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 By(e,t,n,r,i,o,s){let a=Je(e,t,r),c=Ft(s,i,o);return n?Vy(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let d=jn(c,u.localName);return Xt(u.importedName,u.sourcePath,{localName:u.localName,usedMembers:d,used:d.length>0||De(c,u.localName),isTypeOnly:u.isTypeOnly})}return u.kind==="side-effect"?Qt(u.importedName,u.sourcePath):Bn(u.importedName,u.localName??"",u.sourcePath,u.localName?De(c,u.localName):!1,u.kind,[],{isTypeOnly:u.isTypeOnly})}):[Qt("*",a)]}function Vy(e){let t=e.trim(),n=/^type\b/.test(t),r=t.replace(/^type\s+/,""),[i,o]=Hy(r),s=[];return i&&s.push(...Tl(i,n)),o&&s.push(...Tl(o,n)),s}function Tl(e,t){let n=e.trim();if(!n)return[];if(n.startsWith("{")){let r=n.slice(1,-1).trim();return r?ke(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 Hy(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 ss(e,t,n){let r=oe(e,t);return r?zy(e,t,r):qy(e,t,n)}function qy(e,t,n){return[...Wy(e,t,n),...Uy(e,t,n),...Jy(e,t,n)]}function Wy(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=ke(s).map(d=>Gy(d.trim())).filter(d=>!!d),l=Vn(n,o.index),u=Vn(n,o.index+o[0].length-1);r.push({kind:"named",sourcePath:Je(e,t,a),names:c,startLine:l,endLine:u})}return r}function Uy(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=Vn(n,o.index),c=Vn(n,o.index+o[0].length-1);r.push({kind:"star-as",sourcePath:Je(e,t,s),names:[],startLine:a,endLine:c})}return r}function Jy(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=Vn(n,o.index),c=Vn(n,o.index+o[0].length-1);r.push({kind:"star",sourcePath:Je(e,t,s),names:[],startLine:a,endLine:c})}return r}function Gy(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 Vn(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function zy(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("export_statement")){let o=Ky(e,t,i);if(o===void 0)continue;let s=i.startPosition.row,a=i.endPosition.row,c=Qy(i,o,s,a);r.push(c)}return r}function Ky(e,t,n){let r=Pe(n,"string");if(!r)return;let i=Pe(r,"string_fragment");if(i)return Je(e,t,i.text)}function Qy(e,t,n,r){let i=Pe(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 Pe(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:r}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:r}}function Al(e,t,n){return Ni(e,t,{java:r=>Xy(e,t,r),kotlin:r=>Yy(e,t,r),scala:r=>Zy(e,t,r)},()=>Me(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(r,i)=>{let o=r[1]?.trim();return o?eS(e,t,o,i):[]}))}function Xy(e,t,n){let r=X(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(Xt("*",Q(e,l,Ne)));continue}let u=l.split(".").pop()??l;i.push(K(u,u,Q(e,l,Ne),r))}return i}function Yy(e,t,n){let r=X(n,new Set(["import_header","import_list"])),i=[];for(let o of n.rootNode.descendantsOfType("import_header")){let s=o.namedChildren.find(f=>f.type==="identifier");if(!s)continue;let a=o.namedChildren.some(f=>f.type==="wildcard_import"),c=o.namedChildren.find(f=>f.type==="import_alias");if(a){i.push(Xt("*",Q(e,s.text,Ne)));continue}let l=s.text,u=l.split(".").pop()??l,m=c?.namedChild(0)?.text??u;i.push(K(u,m,Q(e,l,Ne),r))}return i}function Zy(e,t,n){let r=X(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(Xt("*",Q(e,c,Ne)));continue}if(s?.type==="namespace_selectors"){for(let d of s.namedChildren)if(d.type==="arrow_renamed_identifier"){let[m,f]=d.namedChildren;if(!m)continue;let g=m.text,h=f?.text??g;if(g==="_")continue;i.push(K(g,h,Q(e,`${c}.${g}`,Ne),r))}else if(d.type==="identifier"){let m=d.text;i.push(K(m,m,Q(e,`${c}.${m}`,Ne),r))}continue}let l=a[a.length-1]?.text??c,u=a.slice(0,-1).map(d=>d.text).join(".")||c;i.push(K(l,l,Q(e,u&&a.length>1?`${u}.${l}`:c,Ne),r))}return i}function eS(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 ke(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(),m=u==="_"?i:`${i}.${u}`.replace(/\.\./g,".");return[Ze(e,t,r,m,u,d)]})}return[Ze(e,t,r,n,n.split(".").pop()??n,n.split(".").pop()??n)]}function Ml(e,t,n){return Oe(e,t,r=>tS(e,t,r),()=>Me(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?ke(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,m=(l??d).trim();return[Ze(e,t,i,u,d,m,Q(e,u.replace(/\\/g,"."),zt))]}):[]}))}function tS(e,t,n){let r=X(n,new Set(["namespace_use_declaration"])),i=[],o=(s,a,c)=>{i.push(K(a,c,Q(e,s.replace(/\\/g,"."),zt),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:m}=$l(l,c);u&&o(m,u,d)}continue}for(let c of s.namedChildren){if(c.type!=="namespace_use_clause")continue;let{importedName:l,localName:u,qualified:d}=$l(c,"");l&&o(d,l,u)}}return i}function $l(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 jl(e,t,n){return Oe(e,t,r=>nS(e,t,r),()=>iS(n).flatMap(r=>sS(e,t,r,n)))}function nS(e,t,n){let r=X(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=Ol(s);if(!a)continue;let c=On(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=rS(s);if(a===null)continue;let c=On(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=Ol(u);d&&i.push({importedName:d.qualifiedName,localName:d.localName,sourcePath:c,kind:"named",used:r.has(d.localName),usedMembers:[]})}}return i}function Ol(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 rS(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=Pe(e,"import_prefix")?.text??"",n=Pe(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function iS(e){let t=e.split(`
95
+ `),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=fr(o);for(;i+1<t.length&&(u>0||c.trimEnd().endsWith("\\"));){i++;let m=t[i];c+=`
96
+ ${m}`,l+=1+m.length,u+=fr(m),r+=m.length+1}let d=oS(c);d&&n.push({...d,start:a,end:l})}return n}function oS(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 sS(e,t,n,r){let i=Ft(r,n.start,n.end),o=n.clause.replace(/\n/g," ").trim();if(n.kind==="import")return ke(o).flatMap(c=>{let l=c.trim().replace(/,$/,"");if(!l)return[];let[u,d]=l.split(/\s+as\s+/),m=u.trim(),f=(d??m.split(".")[0]??m).trim(),g=On(e,t,m),h=jn(i,f);return[{importedName:m,localName:f,sourcePath:g,kind:"namespace",used:De(i,f)||h.length>0,usedMembers:h}]});let s=n.module?On(e,t,n.module):null,a=[];for(let c of ke(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+/),m=(d??u).trim();a.push({importedName:u.trim(),localName:m,sourcePath:s,kind:"named",used:De(i,m),usedMembers:[]})}return a}import{basename as aS}from"path";function Bl(e,t,n){return Oe(e,t,r=>lS(e,t,r),()=>cS(e,t,n))}function cS(e,t,n){return Me(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"?Ii(e,t,s):null;if(a){let c=Vl(s);return[Bn(c,c,a,De(i,c))]}return[Qt(s,a)]})}function lS(e,t,n){let r=X(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(f=>f.type==="argument_list")?.namedChild(0);if(!l||l.type!=="string")continue;let d=l.namedChildren.find(f=>f.type==="string_content")?.text;if(!d)continue;let m=a.text==="require_relative"?Ii(e,t,d):null;if(m){let f=Vl(d);i.push(K(f,f,m,r))}else i.push(Qt(d,m))}return i}function Vl(e){return mi(aS(e).replace(/\.[^.]+$/,""),/_/)}function Hl(e,t,n){return Oe(e,t,r=>uS(e,t,r),()=>Me(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?dS(e,t,o,i):[]}))}function uS(e,t,n){let r=X(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 gr(s,"")){if(!a.importedName||a.importedName==="*")continue;let c=ft(e,t,a.qualifiedName)??ft(e,t,a.qualifiedName.split("::").slice(0,-1).join("::"));i.push(K(a.importedName,a.localName,c,r))}}return i}function gr(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":{let n=e.text;return[{qualifiedName:Pi(t,n),importedName:n,localName:n}]}case"scoped_identifier":{let n=e.text,r=n.split("::").pop()??n;return[{qualifiedName:Pi(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=Pi(t,n.text),o=[];for(let s of r.namedChildren)o.push(...gr(s,i));return o}case"use_list":{let n=[];for(let r of e.namedChildren)n.push(...gr(r,t));return n}case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=gr(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:Pi(t,`${r}::*`),importedName:"*",localName:"*"}]}default:return[]}}function Pi(e,t){return e?t?`${e}::${t}`:e:t}function dS(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 ke(d).flatMap(m=>{let f=m.trim();if(!f||f==="self")return[];let[g,h]=f.split(/\s+as\s+/),b=g?.trim();if(!b)return[];let L=(h??b.split("::").pop()??b).trim(),F=`${u}::${b}`.replace(/::::/g,"::");return[Ze(e,t,r,F,b.split("::").pop()??b,L,ft(e,t,u))]})}let[o,s]=i.split(/\s+as\s+/),a=o?.trim()??i,c=(s??a.split("::").pop()??a).trim(),l=ft(e,t,a)??ft(e,t,a.split("::").slice(0,-1).join("::"));return[Ze(e,t,r,a,a.split("::").pop()??a,c,l)]}function ql(e,t,n){let r=oe(e,t);if(r)return mS(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(...fS(e,t,s))}return i}function mS(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("use_declaration")){if(!pS(i))continue;let o=i.namedChildren.find(s=>s.type!=="visibility_modifier");if(o)for(let s of gr(o,""))s.importedName&&r.push(as(e,t,s.qualifiedName))}return r}function pS(e){for(let t of e.children)if(t.type==="visibility_modifier"&&t.text.startsWith("pub"))return!0;return!1}function fS(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 ke(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[as(e,t,l)]})}return[as(e,t,r)]}function as(e,t,n){return{specifier:n,sourcePath:ft(e,t,n)??ft(e,t,n.split("::").slice(0,-1).join("::"))}}function Yt({language:e,extensions:t,imports:n,parseImports:r}){return{language:e,extensions:t,capabilities:{imports:n},parseImports:r}}function Wl(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 gS={language:"javascript",extensions:Gt,capabilities:{imports:"ast-with-regex-fallback",reExports:"ast-with-regex-fallback"},parseImports:os,parseReExports:ss},hS=Yt({language:"python",extensions:xi,imports:"ast-with-regex-fallback",parseImports:jl}),bS=Yt({language:"jvm",extensions:Ne,imports:"ast-dispatch-with-regex-fallback",parseImports:Al}),yS={language:"rust",extensions:Ci,capabilities:{imports:"ast-with-regex-fallback",exports:"ast-with-regex-fallback"},parseImports:Hl,parseExports:ql},SS=Yt({language:"ruby",extensions:vi,imports:"ast-with-regex-fallback",parseImports:Bl}),xS=Yt({language:"c/cpp",extensions:Ri,imports:"ast-with-regex-fallback",parseImports:Nl}),CS=Yt({language:"dotnet",extensions:Pt,imports:"ast-dispatch-with-regex-fallback",parseImports:El}),vS={language:"dart",extensions:Li,capabilities:{imports:"regex-only",exports:"regex-only"},parseImports:Pl,parseExports:_l},RS=Yt({language:"php",extensions:zt,imports:"ast-with-regex-fallback",parseImports:Ml}),LS=[gS,hS,bS,yS,SS,xS,CS,vS,RS];function _i(e){return Wl(LS,e)}var cs={clearGroups:["whole-project","source-file"]},IS=W("source-imports",cs),DS=W("source-exports",cs),kS=W("source-reexports",cs);function Ul(e,t){let n=Ue(t);return kS.get(e,n,()=>{let r=_i(n);if(!r?.parseReExports)return[];let i=A(e,n);return i?r.parseReExports(e,n,i):[]})}function ce(e,t){let n=Ue(t);return IS.get(e,n,()=>{let r=_i(n);if(!r)return[];let i=A(e,n);return i?r.parseImports(e,n,i):[]})}function ls(e,t){let n=Ue(t);return DS.get(e,n,()=>{let r=_i(n);if(!r?.parseExports)return[];let i=A(e,n);return i?r.parseExports(e,n,i):[]})}var wS=W("file-dep-graph",{clearGroups:["whole-project"]});function ne(e,t){return wS.get(e,t??"",()=>{let n=new Map,r=new Set(V(e,{includeIgnored:!1})),i=(o,s)=>PS(e,n,r,o,s);for(let o of NS(e,t))i(o.from_file,o.to_file);for(let o of r)if(!(t&&!o.includes(t)))for(let s of ce(e,o))s.sourcePath&&i(o,s.sourcePath);return n})}function NS(e,t){let n=t?`AND d1.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
74
97
  d1.relative_path AS from_file,
75
98
  d2.relative_path AS to_file
76
99
  FROM mentions m
@@ -88,11 +111,11 @@ ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,e
88
111
  WHERE d1.id != d2.id
89
112
  AND m.role != 1
90
113
  ${e.pathExclusionsFor("d1","d2")}
91
- ${n}`)}function Sg(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)}import{readdirSync as xg}from"fs";import{extname as sc,join as Cg}from"path";var Rg=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".rs",".py",".pyi",".java",".kt",".kts",".scala",".sc",".rb",".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx",".cs",".vb",".php",".dart"],ac=[".vue"],cc=new Set(Rg.map(e=>e.toLowerCase())),Ig=[...cc].sort().join(","),Zi=new Set(["node_modules",".git","target","dist","build",".next",".nuxt",".cache",".turbo","out","coverage",".scipquery-cache","__pycache__",".venv","venv",".idea",".vscode"]);function qe(e,t={}){let n=t.includeIndexed??!0,r=t.includeAuxiliary??!0,i=t.extensions?.map(c=>c.toLowerCase()),o=i?new Set(i):cc,s=i?[...o].sort().join(","):Ig,a=`${n?"1":"0"}|${r?"1":"0"}|${s}`;return vg.get(e,a,()=>{let c=new Set;if(n)for(let l of T(e,{includeIgnored:!1}))o.has(sc(l).toLowerCase())&&c.add(l);if(r)for(let l of Dg(e.config.projectRoot,o))e.isIgnored(l)||c.add(l);return[...c].sort()})}var vg=W("source-files",{clearGroups:[]});function Dg(e,t){let n=new Set,r=i=>{let o=i?Cg(e,i):e,s;try{s=xg(o,{withFileTypes:!0})}catch{return}for(let a of s)if(!Zi.has(a.name)){if(a.isDirectory()){r(i?`${i}/${a.name}`:a.name);continue}t.has(sc(a.name).toLowerCase())&&n.add(i?`${i}/${a.name}`:a.name)}};return r(""),n}import{readFileSync as Ng}from"fs";import{join as _g}from"path";var Lg={files:new Set,pathPrefixes:[]},eo=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,wg=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,kg=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Eg=de("package-surface",{clearGroups:["whole-project"]});function Pg(e){return Eg.get(e,()=>Fg(e.config.projectRoot))}function uc(e,t){let n=Pg(e);return n.files.has(t)?!0:n.pathPrefixes.some(r=>t.startsWith(r))}function Fg(e){let t=Ag(e);if(!t)return Lg;let n=new Set,r=[];for(let i of Tg(t))Mg(i,n,r);return{files:n,pathPrefixes:r}}function Ag(e){try{let t=Ng(_g(e,"package.json"),"utf-8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Tg(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 mc(e.exports,t),t}function mc(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))mc(n,t)}function Mg(e,t,n){let r=e.replace(/\\/g,"/").replace(/^\.\//,"");if(r===""||r.startsWith(".."))return;let i=r.indexOf("*");if(i>=0){let s=r.slice(0,i);for(let a of lc(s))a!==""&&n.push(a);return}let o=r.replace(wg,"");for(let s of lc(o)){s===o&&s===r&&t.add(r);for(let a of kg)t.add(s+a)}t.add(r)}function lc(e){let t=[e];return eo.test(e)&&(t.push(e.replace(eo,"src/")),t.push(e.replace(eo,""))),t}function G(e){let t=mn(e);return jg(t)?"test":Bg(t)?"worker":Hg(t)?"entry":qg(t)?"barrel":"source"}function Ar(e){return G(e)==="barrel"}function pc(e){return Og.get(e,()=>{let t=se(e),n=qe(e).filter(o=>{let s=G(o);return s==="entry"||s==="worker"}),r=new Set,i=new Set;for(;n.length>0;){let o=n.shift();if(!r.has(o)){r.add(o),G(o)==="barrel"&&i.add(o);for(let s of t.get(o)??[])r.has(s)||n.push(s)}}return i})}var Og=de("live-barrels",{clearGroups:["whole-project"]});function to(e,t){return pc(e).has(mn(t))}function fc(e){let t=pc(e);return qe(e).filter(n=>Ar(n)&&!t.has(n)&&!$g(e,n))}function $g(e,t){let n=mn(t),r=Q(e,n)?.callables;return r&&r.length>0?!0:(e.get(`SELECT COUNT(*) AS n
114
+ ${n}`)}function PS(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)}import{existsSync as Gl,readFileSync as _S,readdirSync as ES}from"fs";import{join as ds}from"path";var FS={files:new Set,pathPrefixes:[]},us=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,TS=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,zl=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],AS=ie("package-surface",{clearGroups:["whole-project"]});function $S(e){return AS.get(e,()=>MS(e.config.projectRoot))}function Kl(e,t){let n=$S(e);return n.files.has(t)?!0:n.pathPrefixes.some(r=>t.startsWith(r))}function MS(e){let t=OS(e);if(!t)return FS;let n=new Set,r=[];for(let i of jS(t))BS(e,i,n,r);return{files:n,pathPrefixes:r}}function OS(e){try{let t=_S(ds(e,"package.json"),"utf-8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function jS(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 Ql(e.exports,t),t}function Ql(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))Ql(n,t)}function BS(e,t,n,r){let i=t.replace(/\\/g,"/").replace(/^\.\//,"");if(i===""||i.startsWith(".."))return;let o=i.indexOf("*");if(o>=0){let a=i.slice(0,o);for(let c of Jl(a))c!==""&&r.push(c);return}let s=i.replace(TS,"");for(let a of Jl(s)){a===s&&a===i&&n.add(i);for(let c of zl)VS(e,n,a+c)}n.add(i)}function Jl(e){let t=[e];return us.test(e)&&(t.push(e.replace(us,"src/")),t.push(e.replace(us,""))),t}function VS(e,t,n){if(t.add(n),!n.startsWith("src/")||Gl(ds(e,n)))return;let r=zl.find(c=>n.endsWith(c));if(!r)return;let i=n.slice(0,-r.length),o=i.lastIndexOf("/");if(o<=4)return;let s=i.slice(0,o),a=i.slice(o+1);for(let c of Xl(e,s,`${a}${r}`))t.add(c)}function Xl(e,t,n){let r=ds(e,t);if(!Gl(r))return[];let i=[];for(let o of ES(r,{withFileTypes:!0})){let s=`${t}/${o.name}`;o.isDirectory()?i.push(...Xl(e,s,n)):o.isFile()&&o.name===n&&i.push(s)}return i}function z(e){let t=Hn(e);return WS(t)?"test":US(t)?"worker":JS(t)?"entry":GS(t)?"barrel":"source"}function Ei(e){return z(e)==="barrel"}function Zl(e){return HS.get(e,()=>{let t=ne(e),n=Le(e).filter(o=>{let s=z(o);return s==="entry"||s==="worker"}),r=new Set,i=new Set;for(;n.length>0;){let o=n.shift();if(!r.has(o)){r.add(o),z(o)==="barrel"&&i.add(o);for(let s of t.get(o)??[])r.has(s)||n.push(s)}}return i})}var HS=ie("live-barrels",{clearGroups:["whole-project"]});function ms(e,t){return Zl(e).has(Hn(t))}function eu(e){let t=Zl(e);return Le(e).filter(n=>Ei(n)&&!t.has(n)&&!qS(e,n))}function qS(e,t){let n=Hn(t),r=ee(e,n)?.callables;return r&&r.length>0?!0:(e.get(`SELECT COUNT(*) AS n
92
115
  FROM defn_enclosing_ranges der
93
116
  JOIN documents d ON d.id = der.document_id
94
117
  WHERE d.relative_path = ?
95
- AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function ue(e,t){let n=G(t);return n==="entry"||n==="worker"||to(e,t)}function re(e,t,n){let r=mn(n);if(uc(e,r))return!0;let i=e.config.entryRoots;return i?!!(i.files?.some(o=>mn(o)===r)||i.pathPrefixes?.some(o=>r.startsWith(mn(o)))||i.qualifiedVars?.some(o=>Vg(t,o))||i.symbolPatterns?.some(o=>{try{return new RegExp(o).test(t)}catch{return!1}})):!1}function jg(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 Bg(e){return/(?:^|\/)[^/]*worker\.(?:ts|tsx|js|mjs|cjs|rs|py|go)$/.test(e)}function Hg(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 qg(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 mn(e){return e.replace(/\\/g,"/")}function Vg(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(dc(r)+"/")&&e.includes(dc(i)+".")}function dc(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function Tr(e,t,n,r={}){if(!n)return[];let i=M(e,t);return i?i.indexOf(n)===-1?[]:(Qe(e,t).get(n)??[]).filter(s=>!Wg(s,r)):[]}function Wg(e,t){return typeof t.excludeStartLine=="number"&&typeof t.excludeEndLine=="number"&&e>=t.excludeStartLine&&e<=t.excludeEndLine}var Ug=W("file-identifiers",{clearGroups:["whole-project","source-file"]});function gc(e,t){let n=Q(e,t);return n?n.fileIdentifiers:Ug.get(e,t,()=>new Set(Qe(e,t).keys()))}var Gg=W("file-ident-lines",{clearGroups:["whole-project","source-file"]});function Qe(e,t){let n=Q(e,t);return n?n.identifierLineMap:Gg.get(e,t,()=>zg(e,t))}var Jg=W("file-idents-by-line",{clearGroups:["whole-project","source-file"]});function hc(e,t){let n=Q(e,t);return n?n.identifiersByLine:Jg.get(e,t,()=>{let r=Qe(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 zg(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=M(e,t);if(!i)return n;let o=_t(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 yc(e,t){return no(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT
118
+ AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function xe(e,t){let n=z(t);return n==="entry"||n==="worker"||ms(e,t)}function le(e,t,n){let r=Hn(n);if(Kl(e,r))return!0;let i=e.config.entryRoots;return i?!!(i.files?.some(o=>Hn(o)===r)||i.pathPrefixes?.some(o=>r.startsWith(Hn(o)))||i.qualifiedVars?.some(o=>zS(t,o))||i.symbolPatterns?.some(o=>{try{return new RegExp(o).test(t)}catch{return!1}})):!1}function WS(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 US(e){return/(?:^|\/)[^/]*worker\.(?:ts|tsx|js|mjs|cjs|rs|py|go)$/.test(e)}function JS(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 GS(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 Hn(e){return e.replace(/\\/g,"/")}function zS(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(Yl(r)+"/")&&e.includes(Yl(i)+".")}function Yl(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function Fi(e,t,n,r={}){if(!n)return[];let i=A(e,t);return i?i.indexOf(n)===-1?[]:(gt(e,t).get(n)??[]).filter(s=>!KS(s,r)):[]}function KS(e,t){return typeof t.excludeStartLine=="number"&&typeof t.excludeEndLine=="number"&&e>=t.excludeStartLine&&e<=t.excludeEndLine}var QS=W("file-identifiers",{clearGroups:["whole-project","source-file"]});function tu(e,t){let n=ee(e,t);return n?n.fileIdentifiers:QS.get(e,t,()=>new Set(gt(e,t).keys()))}var XS=W("file-ident-lines",{clearGroups:["whole-project","source-file"]});function gt(e,t){let n=ee(e,t);return n?n.identifierLineMap:XS.get(e,t,()=>ZS(e,t))}var YS=W("file-idents-by-line",{clearGroups:["whole-project","source-file"]});function nu(e,t){let n=ee(e,t);return n?n.identifiersByLine:YS.get(e,t,()=>{let r=gt(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 ZS(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=A(e,t);if(!i)return n;let o=Kt(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 ru(e,t){return ps(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT
96
119
  m.symbol_id,
97
120
  d.relative_path,
98
121
  COUNT(*) AS ref_count
@@ -102,13 +125,13 @@ ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,e
102
125
  WHERE m.role != 1
103
126
  ${r}
104
127
  ${e.pathExclusionsFor("d")}
105
- GROUP BY m.symbol_id, d.relative_path`,...n??[])})}function bc(e,t){return no(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
128
+ GROUP BY m.symbol_id, d.relative_path`,...n??[])})}function iu(e,t){return ps(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
106
129
  FROM mentions m
107
130
  JOIN chunks c ON m.chunk_id = c.id
108
131
  JOIN documents d ON c.document_id = d.id
109
132
  WHERE m.role != 1
110
133
  ${r}
111
- ${e.pathExclusionsFor("d")}`,...n??[])}).filter(n=>n.symbol_id!==null)}function Mr(e,t){return no(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,
134
+ ${e.pathExclusionsFor("d")}`,...n??[])}).filter(n=>n.symbol_id!==null)}function Ti(e,t){return ps(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,
112
135
  c.start_line AS chunk_start, c.end_line AS chunk_end
113
136
  FROM mentions m
114
137
  JOIN chunks c ON m.chunk_id = c.id
@@ -116,7 +139,7 @@ ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,e
116
139
  WHERE m.role != 1
117
140
  ${r}
118
141
  ${e.pathExclusionsFor("d")}
119
- ORDER BY d.relative_path, c.start_line`,...n??[])})}function no(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 Sc(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function pt(e,t){return Sc(e)===Sc(t)}function Or(e,t){let n=xc(e);return n?t.filter(r=>xc(r.file)===n):t}function $r(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(pt(a,s.file))return s;return null}return n.length===1?n[0]:null}function xc(e){let t=B(e);return t?t==="typescript"||t==="tsx"||t==="javascript"?"javascript-family":t:null}var Kg=de("global-leaf-index",{clearGroups:["whole-project"]});function Et(e){return Kg.get(e,()=>{let t=e.all(`SELECT gs.id, gs.symbol,
142
+ ORDER BY d.relative_path, c.start_line`,...n??[])})}function ps(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 ou(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Tt(e,t){return ou(e)===ou(t)}function Ai(e,t){let n=su(e);return n?t.filter(r=>su(r.file)===n):t}function $i(e,t,n,r){let i=n.find(o=>o.file===t);if(i)return i;if(r){let o=new Set(ce(e,t).map(s=>s.sourcePath).filter(s=>!!s));for(let s of n)for(let a of o)if(Tt(a,s.file))return s;return null}return n.length===1?n[0]:null}function su(e){let t=U(e);return t?t==="typescript"||t==="tsx"||t==="javascript"?"javascript-family":t:null}var ex=ie("global-leaf-index",{clearGroups:["whole-project"]});function Zt(e){return ex.get(e,()=>{let t=e.all(`SELECT gs.id, gs.symbol,
120
143
  COALESCE(der_doc.relative_path, mention_doc.relative_path) AS relative_path
121
144
  FROM global_symbols gs
122
145
  LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
@@ -130,68 +153,8 @@ ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,e
130
153
  GROUP BY m.symbol_id
131
154
  ) mention_doc ON mention_doc.symbol_id = gs.id
132
155
  WHERE 1 = 1
133
- ${e.symbolNoiseFor("gs")}`),n=new Map;for(let r of t){if(!r.relative_path||e.isIgnored(r.relative_path))continue;let i=F(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})}function Fe(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}import Cc from"path";function Qg(e,t){return e.getReferences().map(n=>{let r=n.getNode();return vc(r,t)})}function Yg(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function Rc(e,t,n,r){let i=[];for(let o of Yg(e))for(let s of Qg(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 jr(i)}function Ic(e,t,n,r){let i=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();En(r,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||i.push({location:vc(a,r),node:a}))}return i}function vc(e,t){let n=e.getSourceFile(),r=n.getLineAndColumnAtPos(e.getStart());return{file:En(t,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function Dc(e,t,n){let r=e.getSourceFile(),i=dn(r,e),o=e.getText(),s=new RegExp(`\\b${Xg(o)}\\b`,"g"),a=r.getFullText().split(`
134
- `),c=[];for(let l=0;l<a.length;l++){if(l===i)continue;let u=a[l]??"";s.lastIndex=0;let m;for(;(m=s.exec(u))!==null;)c.push({file:t,line:l,column:m.index})}return jr(c.filter(l=>En(n,Cc.join(n,l.file))===t))}function ro(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 dn(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function jr(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 En(e,t){let n=Cc.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function Xg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Nc(e,t,n,r){let i=Zg(t,r);return i.size===0?new Map:eh(e,n,i)}function Zg(e,t){let n=new Map;for(let r of V(e,t)){let i=F(r.symbol)??r.leaf;if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push(r)}return n}function eh(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of th(e,o)){let a=n.get(s);if(!a)continue;let c=dn(t,o);for(let l of a){if(c<l.startLine-1||c>l.endLine+1)continue;let u=Math.abs(c-l.startLine),m=i.get(l.symbolId);m!==void 0&&m<=u||(i.set(l.symbolId,u),r.set(l.symbolId,o))}}}),r}function th(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}function _c(e,t,n,r){return e.all(`SELECT
135
- gs.id AS symbolId,
136
- gs.symbol,
137
- d.relative_path AS relativePath,
138
- COALESCE(der.start_line, c.start_line) AS startLine,
139
- COALESCE(der.end_line, c.end_line) AS endLine,
140
- COALESCE(gs.display_name, '') AS leaf,
141
- NULL AS parentTypeName,
142
- CASE WHEN gs.kind IN (6, 12, 13) OR gs.symbol LIKE '%().' THEN 1 ELSE 0 END AS isFunctionLike,
143
- CASE WHEN gs.kind IN (5, 8, 11) THEN 1 ELSE 0 END AS isTypeLike,
144
- gs.kind AS kind,
145
- gs.documentation AS documentation,
146
- gs.enclosing_symbol AS enclosingSymbol
147
- FROM global_symbols gs
148
- LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
149
- LEFT JOIN chunks c ON c.document_id = der.document_id
150
- JOIN documents d ON d.id = der.document_id
151
- WHERE d.relative_path = ?
152
- AND COALESCE(gs.display_name, gs.symbol) LIKE ?
153
- ORDER BY ABS(COALESCE(der.start_line, c.start_line) - ?)
154
- LIMIT 5`,t,`%${r}%`,n)[0]??null}function Lc(e,t){let n=e.all(`SELECT
155
- d.id AS documentId,
156
- gs.id AS symbolId,
157
- gs.symbol,
158
- d.relative_path AS relativePath,
159
- der.start_line AS startLine,
160
- der.end_line AS endLine,
161
- COALESCE(gs.display_name, '') AS leaf,
162
- NULL AS parentTypeName,
163
- CASE WHEN gs.kind IN (6, 12, 13) OR gs.symbol LIKE '%().' THEN 1 ELSE 0 END AS isFunctionLike,
164
- CASE WHEN gs.kind IN (5, 8, 11) THEN 1 ELSE 0 END AS isTypeLike,
165
- gs.kind AS kind,
166
- gs.documentation AS documentation,
167
- gs.enclosing_symbol AS enclosingSymbol
168
- FROM global_symbols gs
169
- JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
170
- JOIN documents d ON d.id = der.document_id
171
- WHERE d.relative_path = ?
172
- UNION ALL
173
- SELECT
174
- d.id AS documentId,
175
- gs.id AS symbolId,
176
- gs.symbol,
177
- d.relative_path AS relativePath,
178
- MIN(c.start_line) AS startLine,
179
- MAX(c.end_line) AS endLine,
180
- COALESCE(gs.display_name, '') AS leaf,
181
- NULL AS parentTypeName,
182
- CASE WHEN gs.kind IN (6, 12, 13) OR gs.symbol LIKE '%().' THEN 1 ELSE 0 END AS isFunctionLike,
183
- CASE WHEN gs.kind IN (5, 8, 11) THEN 1 ELSE 0 END AS isTypeLike,
184
- gs.kind AS kind,
185
- gs.documentation AS documentation,
186
- gs.enclosing_symbol AS enclosingSymbol
187
- FROM global_symbols gs
188
- JOIN mentions m ON m.symbol_id = gs.id
189
- JOIN chunks c ON c.id = m.chunk_id
190
- JOIN documents d ON d.id = c.document_id
191
- WHERE d.relative_path = ?
192
- AND m.role = 1
193
- GROUP BY gs.id, gs.symbol, d.id, d.relative_path, gs.display_name, gs.kind, gs.documentation, gs.enclosing_symbol
194
- ORDER BY startLine, endLine`,t,t),r=new Set,i=new Map;for(let o of n){if(r.has(o.symbolId))continue;r.add(o.symbolId);let s=o.leaf||F(o.symbol);!s||i.has(s)||i.set(s,{...o,leaf:s})}return i}import nh from"path";var Pn=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];function Br(e){let t=e.toLowerCase();return Pn.some(n=>t.endsWith(n))}function wc(e,t){let n=new Map,r=i=>Br(i)?Fe(n,i,()=>{let o=nh.join(e.config.projectRoot,i);for(let{project:s}of t){let a=s.getSourceFile(o)??s.addSourceFileAtPathIfExists(o)??null;if(a)return{project:s,sourceFile:a}}return null}):null;return{sourceFile:i=>r(i)?.sourceFile??null,sourceFileMatch:r,indexedTypeScriptLikeDocuments:()=>T(e,{extensions:Pn})}}import ft from"path";import{existsSync as Hr,readdirSync as rh,readFileSync as kc}from"fs";function Ec(e){let t=ft.join(e,"package.json");if(!Hr(t))return[];let n;try{n=JSON.parse(kc(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>ih(e,i)).flatMap(i=>oh(e,i))}function ih(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=ft.join(e,t);return Hr(ft.join(s,"package.json"))?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=ft.join(e,r||".");if(!Hr(o))return[];try{return rh(o).map(s=>ft.join(o,s,i)).filter(s=>Hr(ft.join(s,"package.json")))}catch{return[]}}function oh(e,t){try{let n=JSON.parse(kc(ft.join(t,"package.json"),"utf8"));if(!n.name)return[];let r=ft.relative(e,t).replace(/\\/g,"/");return[{name:n.name,rootRelative:r,sourceRootRelative:`${r}/src`}]}catch{return[]}}function Pc(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function Fc(e){return[`${e.sourceRootRelative}/index.ts`,`${e.sourceRootRelative}/index.tsx`,`${e.sourceRootRelative}/index.mts`,`${e.sourceRootRelative}/index.cts`]}import{existsSync as Fn,readFileSync as sh,readdirSync as ah,statSync as ch}from"fs";import K from"path";var oo=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function so(e,t){let r=t?K.dirname(K.join(e,t)):e,i=K.resolve(e);for(;r.startsWith(i);){for(let s of oo){let a=K.join(r,s);if(Fn(a))return a}let o=K.dirname(r);if(o===r)break;r=o}for(let o of oo){let s=K.join(e,o);if(Fn(s))return s}return null}function Ac(e){let t=e.config.projectRoot,n=new Set(ao(t,e.config.semantic?.typescript?.tsconfigs)),r=T(e,{includeIgnored:!1,extensions:Pn});for(let i of r){let o=so(t,i);o&&n.add(K.resolve(o))}if(n.size===0){let i=so(t);i&&n.add(K.resolve(i))}return[...n].filter(i=>!Tc(t,i)).sort((i,o)=>i.localeCompare(o))}function ao(e,t=[]){let n=new Set;for(let r of t){let i=K.isAbsolute(r)?r:K.join(e,r);Fn(i)&&n.add(K.resolve(i))}for(let r of lh(e))for(let i of oo){let o=K.join(r,i);Fn(o)&&n.add(K.resolve(o))}if(n.size===0){let r=so(e);r&&n.add(K.resolve(r))}return[...n].filter(r=>!Tc(e,r)).sort((r,i)=>r.localeCompare(i))}function lh(e){let t=K.join(e,"package.json");if(!Fn(t))return[];let n;try{n=JSON.parse(sh(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>uh(e,i))}function uh(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=K.join(e,t);return io(s)?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=K.join(e,r||".");return io(o)?ah(o).map(s=>K.join(o,s,i)).filter(io):[]}function io(e){try{return ch(e).isDirectory()}catch{return!1}}function Tc(e,t){let n=K.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 mh}from"module";var dh=mh(import.meta.url),An;function Mc(){if(An!==void 0)return An;try{An=dh("ts-morph")}catch{An=null}return An}function Oc(e,t){return t.map(n=>({tsconfigPath:n,project:new e.Project({tsConfigFilePath:n,skipFileDependencyResolution:!1})}))}function qr(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}function Bc(e,t){let n=Mc();if(!n)return qr("ts-morph is not installed");let r=Ac(e);if(r.length===0)return qr("no tsconfig found");try{let i=Oc(n,r);return new co(e,n,i)}catch(i){return qr(i instanceof Error?i.message:String(i),r[0],r)}}var co=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=Ec(t.config.projectRoot),this.sourceFiles=wc(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;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 Fe(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let r=[];for(let i of n.getImportDeclarations())for(let o of this.importUsageForDeclaration(t,i))r.push(o);return r})}referencesFor(t){return Fe(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t),r=this.packageImportReferencesForDefinition(t);return n?Rc(n,t,r,this.db.config.projectRoot):r})}calleesFor(t){return Fe(this.calleesCache,t.symbolId,()=>Fe(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}signatureFor(t){return Fe(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 jc(c)}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${jc(o)}`})}importUsageForDeclaration(t,n){let r=Pe(this.db,t,n.getModuleSpecifierValue()),i=$c(n);return n.getImportClause()?.isTypeOnly()?i.map(o=>ph(t,r,o)):i.map(o=>this.valueImportUsageForEntry(t,r,o))}valueImportUsageForEntry(t,n,r){let i=r.identifier?r.identifier.findReferences():[],o=[];for(let l of i)for(let u of Ic(l,t,r.identifier,this.db.config.projectRoot))o.push(u);let s=o.some(l=>!ro(l.node)),a=o.some(l=>ro(l.node)),c=r.isTypeOnly;return{importer:t,sourcePath:n,importedName:r.importedName,localName:r.localName,kind:r.kind,isTypeOnly:c,isUsed:c||o.length>0,isTypeUsed:c||a,isValueUsed:s,references:o.map(l=>l.location)}}packageImportReferencesForDefinition(t){return this.packageImportReferences().get(t.symbolId)??[]}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,jr(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=Pc(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of $c(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=Dc(a.identifier,r,this.db.config.projectRoot);l.length>0&&hh(t,c,l)}}packageExports(){if(this.packageExportIndex)return this.packageExportIndex;let t=new Map;for(let n of this.workspacePackages){let r=new Map;for(let i of Fc(n))this.collectPackageExports(n,i,r,new Set);r.size>0&&t.set(n.name,r)}return this.packageExportIndex=t,t}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?Pe(this.db,n,a):n;if(!c||!c.startsWith(`${t.sourceRootRelative}/`))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 m=u.getNameNode().getText(),d=u.getAliasNode()?.getText()??m,p=this.indexedDefinitionByLeaf(c,m);if(!p)continue;let h=r.get(d);h||(h=new Set,r.set(d,h)),h.add(p.symbolId)}}}indexedDefinitionByLeaf(t,n){return Fe(this.indexedDefinitionLeafCache,t,()=>Lc(this.db,t)).get(n)??null}nodeForDefinition(t){return Fe(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return Fe(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?Nc(this.tsMorph,this.db,n,t):new Map})}definitionFromSymbol(t){let n=t.getDeclarations();for(let r of n){let i=r.getSourceFile(),o=En(this.db.config.projectRoot,i.getFilePath());if(!o||this.db.isIgnored(o))continue;let s=dn(i,r),a=_c(this.db,o,s,t.getName());if(a)return{symbol:a.symbol,file:a.relativePath,line:a.startLine}}return null}calleeMapForFile(t){let n=this.sourceFiles.sourceFile(t);if(!n)return new Map;let r=V(this.db,t).sort((o,s)=>o.startLine-s.startLine||s.endLine-o.endLine);if(r.length===0)return new Map;let i=new Map;n.forEachDescendant(o=>{if(!this.tsMorph.Node.isCallExpression(o)&&!this.tsMorph.Node.isNewExpression(o))return;let s=this.semanticCalleeForCallNode(n,r,o);s&&fh(i,s.callerId,s.target)});for(let[o,s]of i)i.set(o,yh(s));return i}semanticCalleeForCallNode(t,n,r){let i=gh(n,dn(t,r));if(!i)return null;let o=r.getExpression(),s=o.getSymbol()??o.getType().getSymbol(),a=s?this.definitionFromSymbol(s):null;return a?{callerId:i.symbolId,target:{symbol:a.symbol,file:a.file,line:a.line}}:null}};function $c(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 ph(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 fh(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function gh(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 hh(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function yh(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 jc(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var lo=new WeakMap;st({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>lo.delete(e)});function Tn(e,t){let n=`${e.config.projectRoot}:typescript-workspace`,r=lo.get(e);r||(r=new Map,lo.set(e,r));let i=r.get(n);if(i)return i;let o=Bc(e,t);return r.set(n,o),o}function Mn(e,t){let n=Wr(e,t);return n?n.importUsage(t):[]}function Pt(e,t){let n=Wr(e,t.relativePath);return n?n.referencesFor(t):[]}function pn(e,t){let n=new Map;for(let r of t)for(let i of Pt(e,r)){if(i.file===r.relativePath||e.isIgnored(i.file))continue;let o=n.get(r.symbolId);o||(o=new Set,n.set(r.symbolId,o)),o.add(i.file)}return n}function Vr(e,t){let n=new Map;for(let r of t){let i=Wr(e,r.relativePath);if(!i)continue;let o=i.calleesFor(r);o.length>0&&n.set(r.symbolId,o)}return n}function Hc(e,t){let n=Wr(e,t.relativePath);return n?n.signatureFor(t):null}function Wr(e,t){if(!Br(t))return null;let n=Tn(e,t);return n.availability().available?n:null}function Ur(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&&qc(n,i,r.sourcePath),r.kind==="namespace")for(let o of r.usedMembers)qc(n,o,r.sourcePath)}return n}function qc(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function fn(e,t,n){let r=Et(e).get(n);if(!r||r.length===0)return[];if(r.length===1)return[On(r[0])];let i=r.filter(c=>c.file===t);if(i.length>0)return i.map(On);let o=Ur(e,t),s=o.get(n);if(s)for(let c of s){let l=r.filter(u=>pt(c,u.file));if(l.length>0)return l.map(On)}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=>pt(c,u.file));if(l.length>0&&l.length===r.length)return l.map(On)}return[]}function Wc(e,t,n){let r=fn(e,t,n);if(r.length>0)return r;let i=Et(e).get(n);return!i||i.length===0?[]:i.map(On)}function Uc(e,t,n={}){let r=xr(e,t);if(!r)return[];let i=F(r.symbol);if(!i)return[];if(n.semantic!==!1){let s=Pt(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 Vc(e,a)}}let o=new Map;for(let s of qe(e)){let a=M(e,s);if(!a||a.indexOf(i)===-1||s!==r.relativePath&&!fn(e,s,i).some(u=>u.symbolId===r.symbolId))continue;let c=Tr(e,s,i,s===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{});c.length>0&&o.set(s,c)}return Vc(e,o)}function Gc(e,t){let n=new Map;for(let o of t){if(!o.leaf)continue;let s=n.get(o.leaf)??[];s.push(o),n.set(o.leaf,s)}if(n.size===0)return new Map;let r=new Set(t.map(o=>o.symbolId)),i=new Map;for(let o of qe(e)){let s=gc(e,o);if(s.size!==0){for(let a of s)if(n.has(a))for(let c of fn(e,o,a)){if(!r.has(c.symbolId)||o===c.relativePath)continue;let l=i.get(c.symbolId);l||(l=new Set,i.set(c.symbolId,l)),l.add(o)}}}return i}function On(e){return{symbolId:e.symbolId,symbol:e.symbol,relativePath:e.file}}function Vc(e,t){let n=[],r=new Set;for(let[i,o]of t){let s=V(e,i);for(let a of o){let c=Ce(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 Ft(e,t){let n=Ih(e,t);return n?vh(e,Sh(e,n.match,n.identifier)):[]}function gt(e,t,n={}){return bh(e,t,n).map(r=>({file:r.file,line:r.line,enclosingSymbol:r.enclosingSymbol}))}function bh(e,t,n={}){let r=Uc(e,t,{semantic:n.semantic}),i=r.length>0?Jc(r,"source-attribution"):Jc(Ft(e,t),"scip-reference-chunk");return n.includeIgnored===!0?i:i.filter(o=>!e.isIgnored(o.file))}function Jc(e,t){return e.map(n=>({...n,provenance:t}))}function Sh(e,t,n){let r=new Map;for(let[i,o]of xh(e,t.symbolId))r.set(i,Ch(e,i,o,t,n));return r}function xh(e,t){let n=new Map;for(let r of Mr(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 Ch(e,t,n,r,i){let o=t===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{},s=i?Tr(e,t,i,o):[];return n.flatMap(a=>Rh(s,a))}function Rh(e,t){let n=e.filter(r=>r>=t.start_line&&r<=t.end_line);return n.length>0?n:[t.start_line]}function Ih(e,t){let n=xr(e,t);return n?{match:n,identifier:F(n.symbol)||null}:null}function vh(e,t){let n=[],r=new Set;for(let[i,o]of t){let s=V(e,i);for(let a of o){let c=Ce(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 Se(e,t,n={}){let r=Gr(e,[t],{additive:n.additive,semantic:n.semantic}),i=n.callableOnly?(r.get(t.symbolId)??[]).filter(o=>oe(o.symbol)):r.get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}function zc(e,t,n={}){let r=_h(e)?wh(e,t,{semantic:n.semantic!==!1}):Lh(e).get(t.symbolId)??[];return typeof n.limit=="number"?r.slice(0,n.limit):r}var Dh=de("caller-rows",{clearGroups:["whole-project"]}),Nh=2e4;function _h(e){return(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>Nh}function Lh(e){return Dh.get(e,()=>{let t=Be(e),n=Gr(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 m=`${s.symbol}|${s.relativePath}`;o.get(l).has(m)||(o.get(l).add(m),u.push({symbol:s.symbol,file:s.relativePath,source:"caller-map-inversion"}))}}return i})}function wh(e,t,n){let r=[],i=new Set,o=a=>{if(a.symbol===t.symbol)return;let c=`${a.symbol}|${a.file}`;i.has(c)||(i.add(c),r.push(a))};for(let a of Ft(e,t))a.file!==t.relativePath&&o({symbol:a.enclosingSymbol??a.file,file:a.file,source:"resolved-reference"});let s=n.semantic?kh(e,t):null;if(s)for(let a of Pt(e,s)){if(a.file===t.relativePath||e.isIgnored(a.file))continue;let c=Ce(V(e,a.file),a.line);o({symbol:c?.symbol??a.file,file:a.file,source:"semantic-reference"})}return r}function kh(e,t){return e.get(`SELECT
156
+ ${e.symbolNoiseFor("gs")}`),n=new Map;for(let r of t){if(!r.relative_path||e.isIgnored(r.relative_path))continue;let i=$(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})}function Ge(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}import au from"path";function tx(e,t){return e.getReferences().map(n=>{let r=n.getNode();return uu(r,t)})}function nx(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function cu(e,t,n,r){let i=[];for(let o of nx(e))for(let s of tx(o,r))s.file===t.relativePath&&s.line>=t.startLine&&s.line<=t.endLine||i.push(s);for(let o of n)i.push(o);return Mi(i)}function lu(e,t,n,r){let i=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();hr(r,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||i.push({location:uu(a,r),node:a}))}return i}function uu(e,t){let n=e.getSourceFile(),r=n.getLineAndColumnAtPos(e.getStart());return{file:hr(t,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function du(e,t,n){let r=e.getSourceFile(),i=qn(r,e),o=e.getText(),s=new RegExp(`\\b${rx(o)}\\b`,"g"),a=r.getFullText().split(`
157
+ `),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 Mi(c.filter(l=>hr(n,au.join(n,l.file))===t))}function fs(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 qn(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function Mi(e){let t=new Set,n=[];for(let r of e){let i=`${r.file}:${r.line}:${r.column}`;t.has(i)||(t.add(i),n.push(r))}return n}function hr(e,t){let n=au.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function rx(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mu(e,t,n,r){let i=ix(t,r);return i.size===0?new Map:ox(e,n,i)}function ix(e,t){let n=new Map;for(let r of J(e,t)){let i=$(r.symbol)??r.leaf;if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push(r)}return n}function ox(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of sx(e,o)){let a=n.get(s);if(!a)continue;let c=qn(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 sx(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 ax=W("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function fu(e,t,n,r){let i=hu(e,t),o=pu(i.get(r)??[],n);if(o)return o;let s=[];for(let a of i.values())for(let c of a)((c.leaf||$(c.symbol)||"").includes(r)||c.symbol.includes(r))&&s.push(c);return pu(s,n)}function gu(e,t){let n=new Map;for(let[r,i]of hu(e,t)){let o=i[0];o&&n.set(r,o)}return n}function hu(e,t){return ax.get(e,t,()=>{let n=new Map;for(let r of J(e,t)){let i=r.leaf||$(r.symbol);if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push({...r,leaf:i})}for(let r of n.values())r.sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine||i.symbolId-o.symbolId);return n})}function pu(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let i of e){let o=Math.abs(i.startLine-t);(o<r||o===r&&n&&i.startLine<n.startLine)&&(n=i,r=o)}return n}import cx from"path";var br=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];function Wn(e){let t=e.toLowerCase();return br.some(n=>t.endsWith(n))}function bu(e,t){let n=new Map,r=i=>Wn(i)?Ge(n,i,()=>{let o=cx.join(e.config.projectRoot,i);for(let{project:s}of t){let a=s.getSourceFile(o)??s.addSourceFileAtPathIfExists(o)??null;if(a)return{project:s,sourceFile:a}}return null}):null;return{sourceFile:i=>r(i)?.sourceFile??null,sourceFileMatch:r,indexedTypeScriptLikeDocuments:()=>V(e,{extensions:br})}}import At from"path";import{existsSync as Oi,readdirSync as lx,readFileSync as yu}from"fs";function Su(e){let t=At.join(e,"package.json");if(!Oi(t))return[];let n;try{n=JSON.parse(yu(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>ux(e,i)).flatMap(i=>dx(e,i))}function ux(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=At.join(e,t);return Oi(At.join(s,"package.json"))?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=At.join(e,r||".");if(!Oi(o))return[];try{return lx(o).map(s=>At.join(o,s,i)).filter(s=>Oi(At.join(s,"package.json")))}catch{return[]}}function dx(e,t){try{let n=JSON.parse(yu(At.join(t,"package.json"),"utf8"));if(!n.name)return[];let r=At.relative(e,t).replace(/\\/g,"/");return[{name:n.name,rootRelative:r,sourceRootRelative:`${r}/src`}]}catch{return[]}}function xu(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function Cu(e){return[`${e.sourceRootRelative}/index.ts`,`${e.sourceRootRelative}/index.tsx`,`${e.sourceRootRelative}/index.mts`,`${e.sourceRootRelative}/index.cts`]}import{existsSync as yr,readFileSync as mx,readdirSync as px,statSync as fx}from"fs";import Y from"path";var hs=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function bs(e,t){let r=t?Y.dirname(Y.join(e,t)):e,i=Y.resolve(e);for(;r.startsWith(i);){for(let s of hs){let a=Y.join(r,s);if(yr(a))return a}let o=Y.dirname(r);if(o===r)break;r=o}for(let o of hs){let s=Y.join(e,o);if(yr(s))return s}return null}function vu(e){let t=e.config.projectRoot,n=new Set(ys(t,e.config.semantic?.typescript?.tsconfigs)),r=V(e,{includeIgnored:!1,extensions:br});for(let i of r){let o=bs(t,i);o&&n.add(Y.resolve(o))}if(n.size===0){let i=bs(t);i&&n.add(Y.resolve(i))}return[...n].filter(i=>!Ru(t,i)).sort((i,o)=>i.localeCompare(o))}function ys(e,t=[]){let n=new Set;for(let r of t){let i=Y.isAbsolute(r)?r:Y.join(e,r);yr(i)&&n.add(Y.resolve(i))}for(let r of gx(e))for(let i of hs){let o=Y.join(r,i);yr(o)&&n.add(Y.resolve(o))}if(n.size===0){let r=bs(e);r&&n.add(Y.resolve(r))}return[...n].filter(r=>!Ru(e,r)).sort((r,i)=>r.localeCompare(i))}function gx(e){let t=Y.join(e,"package.json");if(!yr(t))return[];let n;try{n=JSON.parse(mx(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>hx(e,i))}function hx(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=Y.join(e,t);return gs(s)?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=Y.join(e,r||".");return gs(o)?px(o).map(s=>Y.join(o,s,i)).filter(gs):[]}function gs(e){try{return fx(e).isDirectory()}catch{return!1}}function Ru(e,t){let n=Y.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 bx}from"module";var yx=bx(import.meta.url),Sr;function Lu(){if(Sr!==void 0)return Sr;try{Sr=yx("ts-morph")}catch{Sr=null}return Sr}function Iu(e,t){return t.map(n=>({tsconfigPath:n,project:new e.Project({tsConfigFilePath:n,skipFileDependencyResolution:!1})}))}function ji(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}function wu(e,t){let n=Lu();if(!n)return ji("ts-morph is not installed");let r=vu(e);if(r.length===0)return ji("no tsconfig found");try{let i=Iu(n,r);return new Ss(e,n,i)}catch(i){return ji(i instanceof Error?i.message:String(i),r[0],r)}}var Ss=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=Su(t.config.projectRoot),this.sourceFiles=bu(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;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 Ge(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let r=[];for(let i of n.getImportDeclarations())for(let o of this.importUsageForDeclaration(t,i))r.push(o);return r})}referencesFor(t){return Ge(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t),r=this.packageImportReferencesForDefinition(t);return n?cu(n,t,r,this.db.config.projectRoot):r})}calleesFor(t){return Ge(this.calleesCache,t.symbolId,()=>Ge(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}signatureFor(t){return Ge(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 ku(c)}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${ku(o)}`})}importUsageForDeclaration(t,n){let r=Je(this.db,t,n.getModuleSpecifierValue()),i=Du(n);return n.getImportClause()?.isTypeOnly()?i.map(o=>Sx(t,r,o)):i.map(o=>this.valueImportUsageForEntry(t,r,o))}valueImportUsageForEntry(t,n,r){let i=r.identifier?r.identifier.findReferences():[],o=[];for(let l of i)for(let u of lu(l,t,r.identifier,this.db.config.projectRoot))o.push(u);let s=o.some(l=>!fs(l.node)),a=o.some(l=>fs(l.node)),c=r.isTypeOnly;return{importer:t,sourcePath:n,importedName:r.importedName,localName:r.localName,kind:r.kind,isTypeOnly:c,isUsed:c||o.length>0,isTypeUsed:c||a,isValueUsed:s,references:o.map(l=>l.location)}}packageImportReferencesForDefinition(t){return this.packageImportReferences().get(t.symbolId)??[]}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let t=new Map,n=this.packageExports();for(let r of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(t,n,r);for(let[r,i]of t)t.set(r,Mi(i));return this.packageImportReferenceIndex=t,t}addPackageImportReferencesForDocument(t,n,r){if(this.db.isIgnored(r))return;let i=this.sourceFiles.sourceFileMatch(r);if(i)for(let o of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(t,n,r,o)}addPackageImportReferencesForDeclaration(t,n,r,i){let o=xu(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of Du(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=du(a.identifier,r,this.db.config.projectRoot);l.length>0&&vx(t,c,l)}}packageExports(){if(this.packageExportIndex)return this.packageExportIndex;let t=new Map;for(let n of this.workspacePackages){let r=new Map;for(let i of Cu(n))this.collectPackageExports(n,i,r,new Set);r.size>0&&t.set(n.name,r)}return this.packageExportIndex=t,t}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?Je(this.db,n,a):n;if(!c||!c.startsWith(`${t.sourceRootRelative}/`))continue;let l=s.getNamedExports();if(l.length===0){if(s.isNamespaceExport())continue;this.collectPackageExports(t,c,r,i);continue}for(let u of l){let d=u.getNameNode().getText(),m=u.getAliasNode()?.getText()??d,f=this.indexedDefinitionByLeaf(c,d);if(!f)continue;let g=r.get(m);g||(g=new Set,r.set(m,g)),g.add(f.symbolId)}}}indexedDefinitionByLeaf(t,n){return Ge(this.indexedDefinitionLeafCache,t,()=>gu(this.db,t)).get(n)??null}nodeForDefinition(t){return Ge(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return Ge(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?mu(this.tsMorph,this.db,n,t):new Map})}definitionFromSymbol(t){let n=t.getDeclarations();for(let r of n){let i=r.getSourceFile(),o=hr(this.db.config.projectRoot,i.getFilePath());if(!o||this.db.isIgnored(o))continue;let s=qn(i,r),a=fu(this.db,o,s,t.getName());if(a)return{symbol:a.symbol,file:a.relativePath,line:a.startLine}}return null}calleeMapForFile(t){let n=this.sourceFiles.sourceFile(t);if(!n)return new Map;let r=J(this.db,t).sort((o,s)=>o.startLine-s.startLine||s.endLine-o.endLine);if(r.length===0)return new Map;let i=new Map;n.forEachDescendant(o=>{if(!this.tsMorph.Node.isCallExpression(o)&&!this.tsMorph.Node.isNewExpression(o))return;let s=this.semanticCalleeForCallNode(n,r,o);s&&xx(i,s.callerId,s.target)});for(let[o,s]of i)i.set(o,Rx(s));return i}semanticCalleeForCallNode(t,n,r){let i=Cx(n,qn(t,r));if(!i)return null;let o=r.getExpression(),s=o.getSymbol()??o.getType().getSymbol(),a=s?this.definitionFromSymbol(s):null;return a?{callerId:i.symbolId,target:{symbol:a.symbol,file:a.file,line:a.line}}:null}};function Du(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 Sx(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 xx(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function Cx(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 vx(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function Rx(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 ku(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var xs=new WeakMap;kt({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>xs.delete(e)});function en(e,t){let n=`${e.config.projectRoot}:typescript-workspace`,r=xs.get(e);r||(r=new Map,xs.set(e,r));let i=r.get(n);if(i)return i;let o=wu(e,t);return r.set(n,o),o}function xr(e,t){let n=Vi(e,t);return n?n.importUsage(t):[]}function tn(e,t){let n=Vi(e,t.relativePath);return n?n.referencesFor(t):[]}function Un(e,t){let n=new Map;for(let r of t)for(let i of tn(e,r)){if(i.file===r.relativePath||e.isIgnored(i.file))continue;let o=n.get(r.symbolId);o||(o=new Set,n.set(r.symbolId,o)),o.add(i.file)}return n}function Bi(e,t){let n=new Map;for(let r of t){let i=Vi(e,r.relativePath);if(!i)continue;let o=i.calleesFor(r);o.length>0&&n.set(r.symbolId,o)}return n}function Nu(e,t){let n=Vi(e,t.relativePath);return n?n.signatureFor(t):null}function Vi(e,t){if(!Wn(t))return null;let n=en(e,t);return n.availability().available?n:null}function Hi(e,t){let n=new Map;for(let r of ce(e,t)){if(!r.sourcePath)continue;let i=r.localName??r.importedName;if(i&&Pu(n,i,r.sourcePath),r.kind==="namespace")for(let o of r.usedMembers)Pu(n,o,r.sourcePath)}return n}function Pu(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function Jn(e,t,n){let r=Zt(e).get(n);if(!r||r.length===0)return[];if(r.length===1)return[Cr(r[0])];let i=r.filter(c=>c.file===t);if(i.length>0)return i.map(Cr);let o=Hi(e,t),s=o.get(n);if(s)for(let c of s){let l=r.filter(u=>Tt(c,u.file));if(l.length>0)return l.map(Cr)}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=>Tt(c,u.file));if(l.length>0&&l.length===r.length)return l.map(Cr)}return[]}function Eu(e,t,n){let r=Jn(e,t,n);if(r.length>0)return r;let i=Zt(e).get(n);return!i||i.length===0?[]:i.map(Cr)}function Fu(e,t,n={}){let r=yi(e,t);if(!r)return[];let i=$(r.symbol);if(!i)return[];if(n.semantic!==!1){let s=tn(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 _u(e,a)}}let o=new Map;for(let s of Le(e)){let a=A(e,s);if(!a||a.indexOf(i)===-1||s!==r.relativePath&&!Jn(e,s,i).some(u=>u.symbolId===r.symbolId))continue;let c=Fi(e,s,i,s===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{});c.length>0&&o.set(s,c)}return _u(e,o)}function Tu(e,t){let n=new Map;for(let o of t){if(!o.leaf)continue;let s=n.get(o.leaf)??[];s.push(o),n.set(o.leaf,s)}if(n.size===0)return new Map;let r=new Set(t.map(o=>o.symbolId)),i=new Map;for(let o of Le(e)){let s=tu(e,o);if(s.size!==0){for(let a of s)if(n.has(a))for(let c of Jn(e,o,a)){if(!r.has(c.symbolId)||o===c.relativePath)continue;let l=i.get(c.symbolId);l||(l=new Set,i.set(c.symbolId,l)),l.add(o)}}}return i}function Cr(e){return{symbolId:e.symbolId,symbol:e.symbol,relativePath:e.file}}function _u(e,t){let n=[],r=new Set;for(let[i,o]of t){let s=J(e,i);for(let a of o){let c=Ae(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 nn(e,t){let n=Nx(e,t);return n?Px(e,Ix(e,n.match,n.identifier)):[]}function $t(e,t,n={}){return Lx(e,t,n).map(r=>({file:r.file,line:r.line,enclosingSymbol:r.enclosingSymbol}))}function Lx(e,t,n={}){let r=Fu(e,t,{semantic:n.semantic}),i=r.length>0?Au(r,"source-attribution"):Au(nn(e,t),"scip-reference-chunk");return n.includeIgnored===!0?i:i.filter(o=>!e.isIgnored(o.file))}function Au(e,t){return e.map(n=>({...n,provenance:t}))}function Ix(e,t,n){let r=new Map;for(let[i,o]of Dx(e,t.symbolId))r.set(i,kx(e,i,o,t,n));return r}function Dx(e,t){let n=new Map;for(let r of Ti(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 kx(e,t,n,r,i){let o=t===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{},s=i?Fi(e,t,i,o):[];return n.flatMap(a=>wx(s,a))}function wx(e,t){let n=e.filter(r=>r>=t.start_line&&r<=t.end_line);return n.length>0?n:[t.start_line]}function Nx(e,t){let n=yi(e,t);return n?{match:n,identifier:$(n.symbol)||null}:null}function Px(e,t){let n=[],r=new Set;for(let[i,o]of t){let s=J(e,i);for(let a of o){let c=Ae(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 _e(e,t,n={}){let r=qi(e,[t],{additive:n.additive,semantic:n.semantic}),i=n.callableOnly?(r.get(t.symbolId)??[]).filter(o=>pe(o.symbol)):r.get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}function Mu(e,t,n={}){let r=Fx(e)?Ax(e,t,{semantic:n.semantic!==!1}):Tx(e).get(t.symbolId)??[];return typeof n.limit=="number"?r.slice(0,n.limit):r}var _x=ie("caller-rows",{clearGroups:["whole-project"]}),Ex=2e4;function Fx(e){return(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>Ex}function Tx(e){return _x.get(e,()=>{let t=Ye(e),n=qi(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 Ax(e,t,n){let r=[],i=new Set,o=a=>{if(a.symbol===t.symbol)return;let c=`${a.symbol}|${a.file}`;i.has(c)||(i.add(c),r.push(a))};for(let a of nn(e,t))a.file!==t.relativePath&&o({symbol:a.enclosingSymbol??a.file,file:a.file,source:"resolved-reference"});let s=n.semantic?$x(e,t):null;if(s)for(let a of tn(e,s)){if(a.file===t.relativePath||e.isIgnored(a.file))continue;let c=Ae(J(e,a.file),a.line);o({symbol:c?.symbol??a.file,file:a.file,source:"semantic-reference"})}return r}function $x(e,t){return e.get(`SELECT
195
158
  d.id AS documentId,
196
159
  gs.id AS symbolId,
197
160
  gs.symbol,
@@ -210,10 +173,11 @@ ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,e
210
173
  LEFT JOIN chunks c ON c.document_id = der.document_id
211
174
  JOIN documents d ON d.id = COALESCE(der.document_id, c.document_id)
212
175
  WHERE gs.id = ?
213
- LIMIT 1`,t.symbolId)??null}function Gr(e,t,n={}){if(t.length===0)return new Map;let r=n.additive??!1,i=[],o=[];for(let u of t)B(u.relativePath)&&Xt(e,u.relativePath)!==null?i.push(u):o.push(u);let s=new Map,a=new Map,c=u=>{for(let[m,d]of u){let p=s.get(m);p||(p=[],s.set(m,p));let h=a.get(m);h||(h=new Set,a.set(m,h));for(let f of d){let y=`${f.symbol}|${f.chunkId}`;h.has(y)||(h.add(y),p.push(f))}}};i.length>0&&c(Eh(e,i)),n.semantic!==!1&&c(Mh(Vr(e,t)));let l=r?t:o;return l.length>0&&c(Th(e,l)),s}function Eh(e,t){let n=new Map,r=Ph(t,n),i=Et(e);for(let[o,s]of r){let a=Xt(e,o);if(a)for(let c of a){let l=Fh(s,c.line);if(!l)continue;let u=Ah(e,o,i,c.calleeLeaf,c.memberAccess);u&&u.symbol!==l.symbol&&n.get(l.symbolId).push({symbol:u.symbol,file:u.file,chunkId:c.line,source:"ast-callsite"})}}return n}function Ph(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 Fh(e,t){return e.find(n=>t>=n.startLine&&t<=n.endLine)??null}function Ah(e,t,n,r,i){let o=Or(t,n.get(r)??[]);return o.length===0?null:$r(e,t,o,i)}function Th(e,t){if(t.length===0)return new Map;let n=e.all(`SELECT c.document_id, c.id AS chunk_id, c.start_line, c.end_line, m.symbol_id
176
+ LIMIT 1`,t.symbolId)??null}function qi(e,t,n={}){if(t.length===0)return new Map;let r=n.additive??!1,i=[],o=[];for(let u of t)U(u.relativePath)&&Dn(e,u.relativePath)!==null?i.push(u):o.push(u);let s=new Map,a=new Map,c=u=>{for(let[d,m]of u){let f=s.get(d);f||(f=[],s.set(d,f));let g=a.get(d);g||(g=new Set,a.set(d,g));for(let h of m){let b=`${h.symbol}|${h.chunkId}`;g.has(b)||(g.add(b),f.push(h))}}};i.length>0&&c(Vx(e,i)),n.semantic!==!1&&c(Ux(Mx(e,t)));let l=r?t:o;return l.length>0&&c(Wx(e,l)),s}function Mx(e,t){let n=new Map,r=[],i=[];for(let s of t){if(!Wn(s.relativePath))continue;let a=A(e,s.relativePath);if(!a){i.push(s);continue}let c=Ht(e,s.relativePath,a),l=Bx(e,s.relativePath),u=Fc(e,s.relativePath,s.symbol,c,l);if(u!==null){let d=Ox(u);if(d){d.length>0&&n.set(s.symbolId,d);continue}}r.push({def:s,contentHash:c,depsDigest:l})}if(r.length===0&&i.length===0)return n;let o=Bi(e,[...i,...r.map(s=>s.def)]);for(let[s,a]of o)n.set(s,a);return en(e).availability().available&&Tc(e,r.map(s=>({relativePath:s.def.relativePath,symbol:s.def.symbol,contentHash:s.contentHash,depsDigest:s.depsDigest,payload:JSON.stringify(o.get(s.def.symbolId)??[])}))),n}function Ox(e){try{return JSON.parse(e)}catch{return null}}var jx=W("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function Bx(e,t){return jx.get(e,t,()=>{let r=[...ne(e).get(t)??[]].sort().map(i=>`${i}:${Ht(e,i,A(e,i))}`);return qo(r.join("|"))})}function Vx(e,t){let n=new Map,r=Hx(t,n),i=Zt(e);for(let[o,s]of r){let a=Dn(e,o);if(!a)continue;let c=Qo(s);for(let l of a){let u=c.get(l.line);if(!u)continue;let d=qx(e,o,i,l.calleeLeaf,l.memberAccess);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 Hx(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 qx(e,t,n,r,i){let o=Ai(t,n.get(r)??[]);return o.length===0?null:$i(e,t,o,i)}function Wx(e,t){if(t.length===0)return new Map;let r=Cs(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
214
177
  FROM mentions m
215
178
  JOIN chunks c ON m.chunk_id = c.id
216
- WHERE m.role != 1`),r=new Map;for(let l of n)r.has(l.document_id)||r.set(l.document_id,[]),r.get(l.document_id).push(l);let i=new Map(e.all("SELECT id, relative_path FROM documents").map(l=>[l.id,l.relative_path])),o=new Map,s=e.all(`SELECT gs.id AS symbol_id, gs.symbol,
179
+ WHERE m.role != 1
180
+ 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=Cs(r.map(m=>m.symbol_id)).flatMap(m=>e.all(`SELECT gs.id AS symbol_id, gs.symbol,
217
181
  COALESCE(der.document_id, def_chunk.document_id) AS document_id
218
182
  FROM global_symbols gs
219
183
  LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
@@ -222,11 +186,14 @@ ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,e
222
186
  FROM mentions m
223
187
  JOIN chunks c ON m.chunk_id = c.id
224
188
  WHERE m.role = 1
189
+ AND m.symbol_id IN (${m.map(()=>"?").join(",")})
225
190
  GROUP BY m.symbol_id
226
- ) def_chunk ON def_chunk.symbol_id = gs.id`);for(let l of s)o.has(l.symbol_id)||o.set(l.symbol_id,{symbol:l.symbol,file:l.document_id!==null?i.get(l.document_id)??"":""});let a=new Map,c=i;for(let l of t){let u=r.get(l.documentId)??[],m=new Set,d=[],p=null,h=()=>{if(p)return p;let f=c.get(l.documentId)??"",y=new Set;if(f){let R=hc(e,f),k=Math.max(0,l.startLine),S=Math.min(R.length-1,l.endLine);for(let x=k;x<=S;x+=1)for(let D of R[x])y.add(D)}return p=y,y};for(let f of u){if(f.symbol_id===l.symbolId)continue;let y=o.get(f.symbol_id);if(!y)continue;if(!(f.start_line>=l.startLine&&f.end_line<=l.endLine)){if(!(f.start_line<=l.endLine&&f.end_line>=l.startLine))continue;let x=F(y.symbol);if(!x||!h().has(x))continue}let k=`${y.symbol}|${f.chunk_id}`;m.has(k)||(m.add(k),d.push({...y,chunkId:f.chunk_id,source:"scip-chunk"}))}a.set(l.symbolId,d)}return a}function Mh(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 Kc(e,t,n={}){let r=new Map;if(t&&t.length===0)return r;let i=T(e,{includeIgnored:!1}),o=Et(e),s=t??Be(e),a=new Set(s.map(c=>c.symbolId));return Oh(e,r,i,o,a),$h(e,r,s,a),qh(e,r,i,o,a),n.semantic!==!1&&Wh(r,pn(e,Vh(s))),r}function Oh(e,t,n,r,i){for(let o of n){if(!B(o))continue;let s=Xt(e,o);if(s)for(let a of s){let c=Or(o,r.get(a.calleeLeaf)??[]);if(!c||c.length===0)continue;let l=$r(e,o,c,a.memberAccess);l&&i.has(l.symbolId)&&l.file!==o&&uo(t,l.symbolId,o)}}}function $h(e,t,n,r){let i=Bh(n);for(let o of jh(e,r))e.isIgnored(o.relative_path)||Hh(o,i.get(o.symbol_id))||uo(t,o.symbol_id,o.relative_path)}function jh(e,t){return Mr(e,t?[...t]:void 0)}function Bh(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 Hh(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function qh(e,t,n,r,i){for(let o of n){if(B(o)!=="rust")continue;let s=Ct(e,o,{includeRustAttributeNames:!0});if(s.length!==0)for(let{name:a}of s){let c=r.get(a);if(c)for(let l of c)i.has(l.symbolId)&&l.file!==o&&uo(t,l.symbolId,o)}}}function uo(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function Vh(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function Wh(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 De(e,t,n={}){return zc(e,t,n)}function mo(e,t,n={}){return Kc(e,t,n)}function po(e,t){return Gc(e,t)}function Qc(e,t,n={}){let r=mo(e,t,{semantic:n.semantic});return n.sourceFallback===!1?r:Uh(r,po(e,t))}function Uh(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 Yc(e,t,n){let r=t.identifierResolution==="strict"?fn:Wc;for(let i of t.paths)if(!(!B(i)&&!(t.includeVueSfc&&xt(i)))&&!e.isIgnored(i)&&!t.skipPath?.(i))try{let s=(c,l,u,m)=>{if(t.candidateNames&&!t.candidateNames.has(c))return;let d=t.resolveTargets?t.resolveTargets({sourceFile:i,name:c,kind:l,defaultTargets:m}):m();for(let p of d)n({sourceFile:i,name:c,target:p,occurrences:u,kind:l})},a=Qe(e,i);for(let[c,l]of a)s(c,"identifier",l.length,()=>r(e,i,c));for(let c of Ct(e,i,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let l=c.kind==="cross-language-dispatch"?()=>fn(e,i,c.name):()=>r(e,i,c.name);s(c.name,c.kind,c.occurrences,l)}}finally{t.afterPath?.(i)}}var _=class{constructor(t){this.db=t}db;scopedDefinitions(t){return ji(this.db,t)}definitionsForFile(t){return V(this.db,t)}productionCallableDefinitions(t={}){let{scope:n,minLoc:r=1,maxLoc:i=Number.POSITIVE_INFINITY,excludeSymbol:o,excludeEntrySurfaces:s=!1,excludeTypesFiles:a=!1,excludeRootedSymbols:c=!1,requireFunctionLikeSymbol:l=!1,requireCallableSymbol:u=!1,excludeRustTraitImplMembers:m=!1,includeSuppressed:d=!1,sortByLocDesc:p=!1}=t,h=[];for(let f of this.scopedDefinitions(n)){let y=f.relativePath;if(this.db.isIgnored(y)||s&&ue(this.db,y)||!Gh(f,{requireFunctionLikeSymbol:l,requireCallableSymbol:u})||o!==void 0&&f.symbol===o)continue;let R=fo(f);R<r||R>i||a&&Jh(y)||c&&re(this.db,f.symbol,y)||m&&hr(f.symbol)||G(y)!=="test"&&(Zt(f.symbol)||!d&&Ti(this.db,y,f.startLine)||h.push(f))}return p?h.sort((f,y)=>fo(y)-fo(f)):h}calleeMap(t,n={}){return Gr(this.db,t,n)}crossFileCallerMap(t,n={}){return mo(this.db,t,n)}sourceFallbackCallerFiles(t){return po(this.db,t)}callerFileMap(t,n={}){return Qc(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 T(this.db,{includeIgnored:!1}))if(B(i)==="rust")for(let{name:o}of Ct(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 G(t)}hasSuppressionComment(t){return Ti(this.db,t.relativePath,t.startLine)}sourceFiles(){return qe(this.db)}scanSourceReferences(t,n){Yc(this.db,t,n)}callableSignature(t){let n=Q(this.db,t.relativePath)?.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};function Gh(e,t){return t.requireCallableSymbol?oe(e.symbol):t.requireFunctionLikeSymbol?Y(e.symbol):e.isFunctionLike}function fo(e){return e.endLine-e.startLine+1}function Jh(e){return(e.split("/").pop()??"").includes("types")}function go(e,t){let n=A(e,t);if(!n)return[];let r=F(n.symbol),o=new _(e).definitionsForFile(n.relativePath).filter(c=>oe(c.symbol)),s=o.filter(c=>c.parentTypeName===r||c.symbol.includes(r));return(s.length>0?s:Kh(zh(n.relativePath))===r?o.filter(c=>c.symbol.includes("<invalid-global-code>")):[]).map(c=>({startLine:c.startLine,endLine:c.endLine,name:F(c.symbol)}))}function Kh(e){return e.replace(/\.[^.]+$/,"")}function ho(e,t,n={}){let r=A(e,t);if(!r)return[];let o=!Y(r.symbol)&&!e.isIgnored(r.relativePath)?[{relativePath:r.relativePath,line:r.startLine}]:[],s=gt(e,r,{semantic:n.semantic}).map(u=>({relativePath:u.file,line:u.line})),a=Qh(e,r),c=new Set,l=[];for(let u of[...o,...s,...a]){let m=`${u.relativePath}:${u.line}`;c.has(m)||(c.add(m),l.push(u))}return l}function Qh(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=Yh(t.symbol);if(n.length===0)return[];let r=[];for(let i of T(e,{extensions:[".rb"],includeIgnored:!1})){let o=M(e,i);if(!o)continue;let s=o.split(`
227
- `);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 Yh(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]}function $n(e,t,n={}){let r=A(e,t);if(!r)return{definitions:[],referencedBy:[]};let i=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",r.symbolId),o=It(i?.documentation??null),s=e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,signature:Zh(o,i?.display_name??null,r.symbol),source:Xh(e,r.relativePath,r.startLine,r.endLine)}],a=gt(e,r,{semantic:n.semantic}).map(c=>({relativePath:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol,enclosingShort:c.enclosingSymbol?b(c.enclosingSymbol):"(top-level)"}));return{definitions:s,referencedBy:a}}function Xh(e,t,n,r){let i=M(e,t);if(!i)return null;let s=i.split(`
191
+ ) def_chunk ON def_chunk.symbol_id = gs.id
192
+ WHERE gs.id IN (${m.map(()=>"?").join(",")})`,...m,...m)),a=Cs([...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
193
+ WHERE id IN (${m.map(()=>"?").join(",")})`,...m).map(f=>[f.id,f.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;for(let m of t){let f=i.get(m.documentId)??[],g=new Set,h=[],b=null,L=()=>{if(b)return b;let F=d.get(m.documentId)??"",k=new Set;if(F){let E=nu(e,F),C=Math.max(0,m.startLine),w=Math.min(E.length-1,m.endLine);for(let M=C;M<=w;M+=1)for(let j of E[M])k.add(j)}return b=k,k};for(let F of f){if(F.symbol_id===m.symbolId)continue;let k=l.get(F.symbol_id);if(!k)continue;if(!(F.start_line>=m.startLine&&F.end_line<=m.endLine)){if(!(F.start_line<=m.endLine&&F.end_line>=m.startLine))continue;let M=$(k.symbol);if(!M||!L().has(M))continue}let C=`${k.symbol}|${F.chunk_id}`;g.has(C)||(g.add(C),h.push({...k,chunkId:F.chunk_id,source:"scip-chunk"}))}u.set(m.symbolId,h)}return u}var $u=500;function Cs(e){let t=[...new Set(e)],n=[];for(let r=0;r<t.length;r+=$u)n.push(t.slice(r,r+$u));return n}function Ux(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 Ou(e,t,n={}){let r=new Map;if(t&&t.length===0)return r;let i=V(e,{includeIgnored:!1}),o=Zt(e),s=t??Ye(e),a=new Set(s.map(c=>c.symbolId));return Jx(e,r,i,o,a),Gx(e,r,s,a),Xx(e,r,i,o,a),n.semantic!==!1&&Zx(r,Un(e,Yx(s))),r}function Jx(e,t,n,r,i){for(let o of n){if(!U(o))continue;let s=Dn(e,o);if(s)for(let a of s){let c=Ai(o,r.get(a.calleeLeaf)??[]);if(!c||c.length===0)continue;let l=$i(e,o,c,a.memberAccess);l&&i.has(l.symbolId)&&l.file!==o&&vs(t,l.symbolId,o)}}}function Gx(e,t,n,r){let i=Kx(n);for(let o of zx(e,r))e.isIgnored(o.relative_path)||Qx(o,i.get(o.symbol_id))||vs(t,o.symbol_id,o.relative_path)}function zx(e,t){return Ti(e,t?[...t]:void 0)}function Kx(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 Qx(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function Xx(e,t,n,r,i){for(let o of n){if(U(o)!=="rust")continue;let s=qt(e,o,{includeRustAttributeNames:!0});if(s.length!==0)for(let{name:a}of s){let c=r.get(a);if(c)for(let l of c)i.has(l.symbolId)&&l.file!==o&&vs(t,l.symbolId,o)}}}function vs(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function Yx(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function Zx(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 je(e,t,n={}){return Mu(e,t,n)}function Rs(e,t,n={}){return Ou(e,t,n)}function Ls(e,t){return Tu(e,t)}function ju(e,t,n={}){let r=Rs(e,t,{semantic:n.semantic});return n.sourceFallback===!1?r:eC(r,Ls(e,t))}function eC(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 Bu(e,t,n){let r=t.identifierResolution==="strict"?Jn:Eu;for(let i of t.paths)if(!(!U(i)&&!(t.includeVueSfc&&ut(i)))&&!e.isIgnored(i)&&!t.skipPath?.(i))try{let s=(c,l,u,d)=>{if(t.candidateNames&&!t.candidateNames.has(c))return;let m=t.resolveTargets?t.resolveTargets({sourceFile:i,name:c,kind:l,defaultTargets:d}):d();for(let f of m)n({sourceFile:i,name:c,target:f,occurrences:u,kind:l})},a=gt(e,i);for(let[c,l]of a)s(c,"identifier",l.length,()=>r(e,i,c));for(let c of qt(e,i,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let l=c.kind==="cross-language-dispatch"?()=>Jn(e,i,c.name):()=>r(e,i,c.name);s(c.name,c.kind,c.occurrences,l)}}finally{t.afterPath?.(i)}}function q(e){return e.endLine-e.startLine+1}function Vu(e,t={}){let{scope:n,minLoc:r=1,maxLoc:i=Number.POSITIVE_INFINITY,excludeSymbol:o,excludeEntrySurfaces:s=!1,excludeTypesFiles:a=!1,excludeRootedSymbols:c=!1,requireFunctionLikeSymbol:l=!1,requireCallableSymbol:u=!1,excludeRustTraitImplMembers:d=!1,includeSuppressed:m=!1,sortByLocDesc:f=!1}=t,g=[];for(let h of ur(e,n)){let b=h.relativePath;if(e.isIgnored(b)||s&&xe(e,b)||!tC(h,{requireFunctionLikeSymbol:l,requireCallableSymbol:u})||o!==void 0&&h.symbol===o)continue;let L=q(h);L<r||L>i||a&&nC(b)||c&&le(e,h.symbol,b)||d&&fi(h.symbol)||z(b)!=="test"&&(_n(h.symbol)||!m&&ri(e,b,h.startLine)||g.push(h))}return f?g.sort((h,b)=>q(b)-q(h)):g}function tC(e,t){return t.requireCallableSymbol?pe(e.symbol):t.requireFunctionLikeSymbol?te(e.symbol):e.isFunctionLike}function nC(e){return(e.split("/").pop()??"").includes("types")}var N=class{constructor(t){this.db=t}db;scopedDefinitions(t){return ur(this.db,t)}definitionsForFile(t){return J(this.db,t)}productionCallableDefinitions(t={}){return Vu(this.db,t)}calleeMap(t,n={}){return qi(this.db,t,n)}crossFileCallerMap(t,n={}){return Rs(this.db,t,n)}sourceFallbackCallerFiles(t){return Ls(this.db,t)}callerFileMap(t,n={}){return ju(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 V(this.db,{includeIgnored:!1}))if(U(i)==="rust")for(let{name:o}of qt(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 ne(this.db,t)}fileKind(t){return z(t)}hasSuppressionComment(t){return ri(this.db,t.relativePath,t.startLine)}sourceFiles(){return Le(this.db)}scanSourceReferences(t,n){Bu(this.db,t,n)}callableSignature(t){let n=ee(this.db,t.relativePath)?.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};function Is(e,t){let n=B(e,t);if(!n)return[];let r=$(n.symbol),o=new N(e).definitionsForFile(n.relativePath).filter(c=>pe(c.symbol)),s=o.filter(c=>c.parentTypeName===r||c.symbol.includes(r));return(s.length>0?s:iC(rC(n.relativePath))===r?o.filter(c=>c.symbol.includes("<invalid-global-code>")):[]).map(c=>({startLine:c.startLine,endLine:c.endLine,name:$(c.symbol)}))}function iC(e){return e.replace(/\.[^.]+$/,"")}function Ds(e,t,n={}){let r=B(e,t);if(!r)return[];let o=!te(r.symbol)&&!e.isIgnored(r.relativePath)?[{relativePath:r.relativePath,line:r.startLine}]:[],s=$t(e,r,{semantic:n.semantic}).map(u=>({relativePath:u.file,line:u.line})),a=oC(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 oC(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=sC(t.symbol);if(n.length===0)return[];let r=[];for(let i of V(e,{extensions:[".rb"],includeIgnored:!1})){let o=A(e,i);if(!o)continue;let s=o.split(`
194
+ `);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 sC(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]}function vr(e,t,n={}){let r=B(e,t);if(!r)return{definitions:[],referencedBy:[]};let i=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",r.symbolId),o=Ut(i?.documentation??null),s=e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,signature:cC(o,i?.display_name??null,r.symbol),source:aC(e,r.relativePath,r.startLine,r.endLine)}],a=$t(e,r,{semantic:n.semantic}).map(c=>({relativePath:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol,enclosingShort:c.enclosingSymbol?y(c.enclosingSymbol):"(top-level)"}));return{definitions:s,referencedBy:a}}function aC(e,t,n,r){let i=A(e,t);if(!i)return null;let s=i.split(`
228
195
  `).slice(n,r+1).join(`
229
- `).trimEnd();return s.length>0?s:null}function Zh(e,t,n){let r=Rt(e);if(r&&!ey(r))return r;let i=(t??"").trim();return i?Y(n)&&!i.endsWith("()")?`${i}()`:i:b(n)}function ey(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function jn(e,t){let n=pe(e,t);return n?e.all(`SELECT DISTINCT d2.relative_path
196
+ `).trimEnd();return s.length>0?s:null}function cC(e,t,n){let r=Wt(e);if(r&&!lC(r))return r;let i=(t??"").trim();return i?te(n)&&!i.endsWith("()")?`${i}()`:i:y(n)}function lC(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function Rr(e,t){let n=Ie(e,t);return n?e.all(`SELECT DISTINCT d2.relative_path
230
197
  FROM mentions m
231
198
  JOIN chunks c ON m.chunk_id = c.id
232
199
  JOIN documents d1 ON c.document_id = d1.id
@@ -242,7 +209,7 @@ ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,e
242
209
  WHERE d1.relative_path = ?
243
210
  AND d2.relative_path <> d1.relative_path
244
211
  AND ${e.localSymbolPredicate}
245
- ORDER BY d2.relative_path`,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function Bn(e,t){let n=pe(e,t);return n?e.all(`SELECT DISTINCT d1.relative_path
212
+ ORDER BY d2.relative_path`,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function Lr(e,t){let n=Ie(e,t);return n?e.all(`SELECT DISTINCT d1.relative_path
246
213
  FROM mentions m
247
214
  JOIN chunks c ON m.chunk_id = c.id
248
215
  JOIN documents d1 ON c.document_id = d1.id
@@ -257,9 +224,9 @@ ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,e
257
224
  JOIN documents d2 ON sym_def.document_id = d2.id
258
225
  WHERE d2.relative_path = ?
259
226
  AND d1.relative_path != ?
260
- ORDER BY d1.relative_path`,n,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function Hn(e,t){let n=sn(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let r=n.map(()=>"?").join(", "),o=e.all(`SELECT relative_path FROM documents
227
+ ORDER BY d1.relative_path`,n,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function Ir(e,t){let n=Mn(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let r=n.map(()=>"?").join(", "),o=e.all(`SELECT relative_path FROM documents
261
228
  WHERE relative_path IN (${r})
262
- ORDER BY relative_path`,...n).map(m=>m.relative_path).filter(m=>!e.isIgnored(m)),s=yr(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:m,...d})=>d),c=e.all(`SELECT DISTINCT d2.relative_path
229
+ ORDER BY relative_path`,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d)),s=gi(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:d,...m})=>m),c=e.all(`SELECT DISTINCT d2.relative_path
263
230
  FROM mentions m
264
231
  JOIN chunks c ON m.chunk_id = c.id
265
232
  JOIN documents d1 ON c.document_id = d1.id
@@ -275,7 +242,7 @@ ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,e
275
242
  WHERE d1.relative_path IN (${r})
276
243
  AND d2.relative_path NOT IN (${r})
277
244
  AND ${e.localSymbolPredicate}
278
- ORDER BY d2.relative_path`,...n,...n).map(m=>m.relative_path).filter(m=>!e.isIgnored(m)),u=e.all(`SELECT DISTINCT d1.relative_path
245
+ 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
279
246
  FROM mentions m
280
247
  JOIN chunks c ON m.chunk_id = c.id
281
248
  JOIN documents d1 ON c.document_id = d1.id
@@ -290,7 +257,7 @@ ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,e
290
257
  JOIN documents d2 ON sym_def.document_id = d2.id
291
258
  WHERE d2.relative_path IN (${r})
292
259
  AND d1.relative_path NOT IN (${r})
293
- ORDER BY d1.relative_path`,...n,...n).map(m=>m.relative_path).filter(m=>!e.isIgnored(m));return{files:o,symbols:s,dependsOn:c,dependedOnBy:u}}function qn(e,t){let n=sn(e,t);return n.length===0?[]:ry([...ty(e,n),...ny(e,n)]).filter(r=>!e.isIgnored(r.relative_path)).map(iy)}function ty(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
260
+ 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 Dr(e,t){let n=Mn(e,t);return n.length===0?[]:mC([...uC(e,n),...dC(e,n)]).filter(r=>!e.isIgnored(r.relative_path)).map(pC)}function uC(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
294
261
  FROM mentions m
295
262
  JOIN chunks c ON m.chunk_id = c.id
296
263
  JOIN documents d1 ON c.document_id = d1.id
@@ -317,7 +284,7 @@ ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,e
317
284
  AND m.role != 1
318
285
  AND ${e.localSymbolPredicate}
319
286
  ${e.pathExclusionsFor("d1")}
320
- ORDER BY d1.relative_path`,...t,...t,...t)}function ny(e,t){let n=new _(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>oe(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function ry(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 iy(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:b(e.symbol)}}var Vn=new WeakMap;function Zc(e,t){let n=B(t);return n==="rust"?ly(e,t):n==="typescript"||n==="tsx"||n==="javascript"?sy(e,t):[]}var oy=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]);function sy(e,t){let n=le(e,t);if(!n)return[];let r=Vn.get(n);if(r)return r;let i=/(^|\/)(pages|app)\/.+\.(tsx?|jsx?)$/.test(t)||/(^|\/)(layout|page|loading|error|not-found|head|template|default)\.(tsx?|jsx?)$/.test(t),o=/(^|\/)src\/(pages|views|routes)\/.+\.(tsx?|jsx?|vue)$/.test(t),s=!1,a=n.rootNode;for(let l of a.namedChildren){if(l.type!=="expression_statement")continue;let u=l.namedChild(0);if(!u||u.type!=="call_expression")continue;let m=u.namedChild(0);if(!m)continue;let d=m.type==="member_expression"?m.namedChild(m.namedChildCount-1)?.text:m.text;if(d&&oy.has(d)){s=!0;break}}let c=[];s&&c.push({startLine:0,endLine:a.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)"}),(i||o)&&c.push({startLine:0,endLine:a.endPosition.row,reason:i?"Next.js / Remix route file":"Vite/Vue route component"});for(let l of a.namedChildren){let u=null,m=null;if(l.type==="function_declaration")u=l.namedChild(0)?.text??null,m=l;else if(l.type==="export_statement"){let d=l.namedChild(0);d?.type==="function_declaration"&&(u=d.namedChild(0)?.text??null,m=d)}else if(l.type==="lexical_declaration"){let d=l.namedChild(0);if(d?.type==="variable_declarator"){let p=d.namedChild(0)?.text,h=d.namedChild(1);p&&(h?.type==="arrow_function"||h?.type==="function_expression")&&(u=p,m=d)}}u&&/^use[A-Z]/.test(u)&&m&&c.push({startLine:m.startPosition.row,endLine:m.endPosition.row,reason:"React custom hook (use*)"})}return c.push(...el(n,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),Vn.set(n,c),c}var ay=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function cy(e){return ay.test(e)}function el(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(cy(u.text)){r.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"scip-query suppression comment"});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 ly(e,t){let n=le(e,t);if(!n)return[];let r=Vn.get(n);if(r)return r;let i=[],o=uy(n);return o?(Vn.set(n,o),o):(tl(n.rootNode,i,!1,!1),i.push(...el(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(...by(n.rootNode)),Vn.set(n,i),i)}function uy(e){return Sy(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)"}]:null}function tl(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)"}),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)"})),e.type==="function_item"||e.type==="function_signature_item"?my(e,t,n,r):r&&yy(e)?t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl associated item (dynamic dispatch)"}):e.type==="struct_item"||e.type==="enum_item"||e.type==="union_item"?dy(e,t,n):e.type==="mod_item"&&yo(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(i=!0);for(let s of e.namedChildren)tl(s,t,i,o)}function my(e,t,n,r){let i=yo(e),o=null;r?o="trait impl method (dynamic dispatch)":n&&(o="inside #[cfg(test)] mod");for(let s of i){let a=fy(s);if(a){o=a;break}if(nl(s)){o="#[allow(dead_code)]";break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o})}function dy(e,t,n){let r=yo(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(hy)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(<reflective>)] \u2014 fields accessed via macro/reflection",containerName:i}),r.some(nl)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",containerName:i}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",containerName:i})}function yo(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 py=[{re:/#\[\s*tauri::command\b/,reason:"#[tauri::command]"},{re:/#\[\s*command\b/,reason:"#[command]"},{re:/#\[\s*test\b/,reason:"#[test]"},{re:/#\[\s*bench\b/,reason:"#[bench]"},{re:/#\[\s*tokio::test\b/,reason:"#[tokio::test]"},{re:/#\[\s*async_std::test\b/,reason:"#[async_std::test]"},{re:/#\[\s*wasm_bindgen\b/,reason:"#[wasm_bindgen]"},{re:/#\[\s*no_mangle\b/,reason:"#[no_mangle]"},{re:/#\[\s*napi\b/,reason:"#[napi]"},{re:/#\[\s*pyfunction\b/,reason:"#[pyfunction]"},{re:/#\[\s*pymethod\b/,reason:"#[pymethod]"},{re:/#\[\s*pyo3\b/,reason:"#[pyo3]"},{re:/#\[\s*cfg\s*\(\s*test\s*\)/,reason:"#[cfg(test)]"},{re:/#\[\s*doc\s*\(\s*hidden\s*\)/,reason:"#[doc(hidden)]"}];function fy(e){return py.find(({re:t})=>t.test(e))?.reason??null}var gy=[/\bSerialize\b/,/\bDeserialize\b/,/\bFromRow\b/,/\bsqlx::FromRow\b/,/\bDeriveEntityModel\b/,/\bIntoSchema\b/,/\bToSchema\b/,/\bDeriveValueType\b/,/\bError\b/,/\bthiserror::Error\b/];function hy(e){return/#\[\s*derive\s*\(/.test(e)?gy.some(t=>t.test(e)):!1}function nl(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function yy(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function by(e){let t=Cy(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:'serde `with = "..."` module \u2014 body invoked via reflection',containerName:i})}return n}function Sy(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 xy=/^#!?\[\s*serde\s*\(/,Xc=/\bwith\s*=\s*"([^"]+)"/g;function Cy(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){if(!xy.test(n.text))continue;Xc.lastIndex=0;let r;for(;(r=Xc.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}function rl(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=Zc(e,r);return i={ranges:o.map(s=>({startLine:s.startLine,endLine:s.endLine})),containers:new Set(o.map(s=>s.containerName).filter(s=>!!s))},t.set(r,i),i};return(r,i,o,s)=>{let a=n(r);for(let c of a.ranges)if(i>=c.startLine&&i<=c.endLine)return!0;if(s&&a.containers.has(s))return!0;for(let c of Sr(o))if(a.containers.has(c))return!0;return!1}}function bo(e,t={}){Pi(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function So(e,t,n={}){Pi(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function ol(e,t){return t.isIgnoredPath(e.relativePath)?Ve("ignored-file"):at(e.symbol)?Ve("module-like-symbol"):il(e.symbol)?!e.isFunctionLike&&e.enclosingSymbol&&il(e.enclosingSymbol)?Ve("nested-non-callable-value"):!t.includeTests&&!xo(e.relativePath)?Ve("test-file"):!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName)?Ve("excluded-file-region"):hr(e.symbol)?Ve("rust-trait-impl-member"):Zt(e.symbol)?Ve("rust-test-module"):!t.includeMembers&&!Ry(e)?Ve("member"):e.endLine-e.startLine+1<t.minLoc?Ve("below-min-loc"):{accepted:!0}:Ve("non-value-symbol")}function xo(e){return G(e)!=="test"}function Ve(e){return{accepted:!1,rejectionReason:e}}function il(e){return Y(e)||e.endsWith("().")||e.endsWith(".")}function Ry(e){return oe(e.symbol)||Sr(e.symbol).length===0}function H(e){return e.endLine-e.startLine+1}function Jr(e,t){return H(e)-H(t)||e.relativePath.localeCompare(t.relativePath)}function Ne(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function gn(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 sl(){return new Map}function al(e,t,n){let r=new Map;for(let i of yc(e,n))e.isIgnored(i.relative_path)||t.has(i.relative_path)||zr(r,i.symbol_id,i.relative_path,i.ref_count,"scip-mention");return r}function cl(e,t,n){let r=new Set;for(let i of bc(e,t))e.isIgnored(i.relative_path)||n.has(i.relative_path)||r.add(i.symbol_id);return r}function Co(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 ll(e){return e?.occurrences??0}function zr(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=ml(e,t,n);o.occurrences+=r,o.sources.add(i)}function ul(e,t,n,r,i){if(r<=0)return;let o=ml(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function ml(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}function Ye(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=Ne(Iy(e,{scope:n,minLoc:r,includeTests:i,includeMembers:s}),c),m=o?new Set(fc(e)):new Set,d=a?sl():al(e,m,u.map(R=>R.symbolId)),p=a?cl(e,u.map(R=>R.symbolId),m):new Set,h=a?u.filter(R=>!p.has(R.symbolId)):u;a?Ly(e,h,d,m):_y(e,h,d,m);let f=a?h.filter(R=>!Co(d,R.symbolId)):u;Fy(e,f,d,{includeTests:i,inactiveBarrelPaths:m,includeSemantic:!a&&l});let y=a?h.filter(R=>!Co(d,R.symbolId)):u;return Ny(e,vy(y,d))}function Iy(e,t){let n=rl(e),r=[];for(let i of T(e,{scope:t.scope}))try{for(let o of V(e,i))ol(o,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:a=>e.isIgnored(a),isExcludedRegion:n}).accepted&&r.push(o)}finally{So(e,i,{definitions:!0})}return r}function vy(e,t){return e.map(n=>Dy(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 Dy(e,t){let n=t.get(e.symbolId)??new Map,r=ll(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,same_file_refs:r,cross_file_refs:i}}function Ny(e,t){let n=[],r=0,i=0,o=0;for(let s of t){if(e.isIgnored(s.relative_path)||ue(e,s.relative_path)||re(e,s.symbol,s.relative_path))continue;let a=s.same_file_refs===0?"dead-code":"file-internal";a==="dead-code"?r++:i++,o+=s.loc,n.push({relativePath:s.relative_path,startLine:s.start_line,endLine:s.end_line,loc:s.loc,symbol:s.symbol,shortName:b(s.symbol),sameFileRefs:s.same_file_refs,kind:a})}return{symbols:n,totalCount:n.length,deadCodeCount:r,fileInternalCount:i,totalLoc:o}}function _y(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 T(e))a.add(c);i.scanSourceReferences({paths:a,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:s,skipPath:c=>r.has(c)},c=>{o.has(c.target.symbolId)&&(Ey(e,c)||zr(n,c.target.symbolId,c.sourceFile,Py(c),"source-fallback"))})}function Ly(e,t,n,r){if(t.length===0)return;let i=new _(e),o=wy(t),s=new Set(i.sourceFiles());for(let u of T(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let m=c.get(u);return m||(m=Ur(e,u),c.set(u,m)),m};i.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:u=>r.has(u),resolveTargets:({sourceFile:u,name:m,kind:d})=>{let p=o.get(m);return p?ky(u,m,p,l(u),{permissive:d!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),So(e,u)}},u=>{let m=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&dl(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:m})||zr(n,u.target.symbolId,u.sourceFile,m,"source-fallback")})}function wy(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 ky(e,t,n,r,i){let o=n.filter(c=>c.relativePath===e);if(o.length>0)return o;if(!i.permissive&&n.length===1)return[...n];let s=r.get(t);if(s)for(let c of s){let l=n.filter(u=>pt(c,u.relativePath));if(l.length>0)return l}let a=new Set;for(let c of r.values())for(let l of c)a.add(l);for(let c of a){let l=n.filter(u=>pt(c,u.relativePath));if(l.length>0&&l.length===n.length)return l}return i.permissive?[...n]:[]}function Ey(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&dl(e,t)}function Py(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function dl(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 Fy(e,t,n,r){for(let i of t){let o=De(e,i,{semantic:r.includeSemantic!==!1});if(o.length!==0)for(let s of o){let a=s.file;a===i.relativePath||e.isIgnored(a)||r.inactiveBarrelPaths.has(a)||!r.includeTests&&!xo(a)||ul(n,i.symbolId,a,1,"caller-map")}}}function Ro(e,t={}){let{limit:n=30,scope:r}=t,i=r?`AND def_d.relative_path LIKE '%${r}%'`:"",s=e.all(`SELECT
287
+ ORDER BY d1.relative_path`,...t,...t,...t)}function dC(e,t){let n=new N(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>pe(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function mC(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 pC(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:y(e.symbol)}}var kr=new WeakMap;function qu(e,t){let n=U(t);return n==="rust"?yC(e,t):n==="typescript"||n==="tsx"||n==="javascript"?gC(e,t):[]}var fC=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]);function gC(e,t){let n=oe(e,t);if(!n)return[];let r=kr.get(n);if(r)return r;let i=/(^|\/)(pages|app)\/.+\.(tsx?|jsx?)$/.test(t)||/(^|\/)(layout|page|loading|error|not-found|head|template|default)\.(tsx?|jsx?)$/.test(t),o=/(^|\/)src\/(pages|views|routes)\/.+\.(tsx?|jsx?|vue)$/.test(t),s=!1,a=n.rootNode;for(let l of a.namedChildren){if(l.type!=="expression_statement")continue;let u=l.namedChild(0);if(!u||u.type!=="call_expression")continue;let d=u.namedChild(0);if(!d)continue;let m=d.type==="member_expression"?d.namedChild(d.namedChildCount-1)?.text:d.text;if(m&&fC.has(m)){s=!0;break}}let c=[];s&&c.push({startLine:0,endLine:a.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)"}),(i||o)&&c.push({startLine:0,endLine:a.endPosition.row,reason:i?"Next.js / Remix route file":"Vite/Vue route component"});for(let l of a.namedChildren){let u=null,d=null;if(l.type==="function_declaration")u=l.namedChild(0)?.text??null,d=l;else if(l.type==="export_statement"){let m=l.namedChild(0);m?.type==="function_declaration"&&(u=m.namedChild(0)?.text??null,d=m)}else if(l.type==="lexical_declaration"){let m=l.namedChild(0);if(m?.type==="variable_declarator"){let f=m.namedChild(0)?.text,g=m.namedChild(1);f&&(g?.type==="arrow_function"||g?.type==="function_expression")&&(u=f,d=m)}}u&&/^use[A-Z]/.test(u)&&d&&c.push({startLine:d.startPosition.row,endLine:d.endPosition.row,reason:"React custom hook (use*)"})}return c.push(...Wu(n,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),kr.set(n,c),c}var hC=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function bC(e){return hC.test(e)}function Wu(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(bC(u.text)){r.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"scip-query suppression comment"});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 yC(e,t){let n=oe(e,t);if(!n)return[];let r=kr.get(n);if(r)return r;let i=[],o=SC(n);return o?(kr.set(n,o),o):(Uu(n.rootNode,i,!1,!1),i.push(...Wu(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(...kC(n.rootNode)),kr.set(n,i),i)}function SC(e){return wC(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)"}]:null}function Uu(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)"}),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)"})),e.type==="function_item"||e.type==="function_signature_item"?xC(e,t,n,r):r&&DC(e)?t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl associated item (dynamic dispatch)"}):e.type==="struct_item"||e.type==="enum_item"||e.type==="union_item"?CC(e,t,n):e.type==="mod_item"&&ks(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(i=!0);for(let s of e.namedChildren)Uu(s,t,i,o)}function xC(e,t,n,r){let i=ks(e),o=null;r?o="trait impl method (dynamic dispatch)":n&&(o="inside #[cfg(test)] mod");for(let s of i){let a=RC(s);if(a){o=a;break}if(Ju(s)){o="#[allow(dead_code)]";break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o})}function CC(e,t,n){let r=ks(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(IC)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(<reflective>)] \u2014 fields accessed via macro/reflection",containerName:i}),r.some(Ju)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",containerName:i}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",containerName:i})}function ks(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 vC=[{re:/#\[\s*tauri::command\b/,reason:"#[tauri::command]"},{re:/#\[\s*command\b/,reason:"#[command]"},{re:/#\[\s*test\b/,reason:"#[test]"},{re:/#\[\s*bench\b/,reason:"#[bench]"},{re:/#\[\s*tokio::test\b/,reason:"#[tokio::test]"},{re:/#\[\s*async_std::test\b/,reason:"#[async_std::test]"},{re:/#\[\s*wasm_bindgen\b/,reason:"#[wasm_bindgen]"},{re:/#\[\s*no_mangle\b/,reason:"#[no_mangle]"},{re:/#\[\s*napi\b/,reason:"#[napi]"},{re:/#\[\s*pyfunction\b/,reason:"#[pyfunction]"},{re:/#\[\s*pymethod\b/,reason:"#[pymethod]"},{re:/#\[\s*pyo3\b/,reason:"#[pyo3]"},{re:/#\[\s*cfg\s*\(\s*test\s*\)/,reason:"#[cfg(test)]"},{re:/#\[\s*doc\s*\(\s*hidden\s*\)/,reason:"#[doc(hidden)]"}];function RC(e){return vC.find(({re:t})=>t.test(e))?.reason??null}var LC=[/\bSerialize\b/,/\bDeserialize\b/,/\bFromRow\b/,/\bsqlx::FromRow\b/,/\bDeriveEntityModel\b/,/\bIntoSchema\b/,/\bToSchema\b/,/\bDeriveValueType\b/,/\bError\b/,/\bthiserror::Error\b/];function IC(e){return/#\[\s*derive\s*\(/.test(e)?LC.some(t=>t.test(e)):!1}function Ju(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function DC(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function kC(e){let t=PC(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:'serde `with = "..."` module \u2014 body invoked via reflection',containerName:i})}return n}function wC(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 NC=/^#!?\[\s*serde\s*\(/,Hu=/\bwith\s*=\s*"([^"]+)"/g;function PC(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){if(!NC.test(n.text))continue;Hu.lastIndex=0;let r;for(;(r=Hu.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}function Gu(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=qu(e,r);return i={ranges:o.map(s=>({startLine:s.startLine,endLine:s.endLine})),containers:new Set(o.map(s=>s.containerName).filter(s=>!!s))},t.set(r,i),i};return(r,i,o,s)=>{let a=n(r);for(let c of a.ranges)if(i>=c.startLine&&i<=c.endLine)return!0;if(s&&a.containers.has(s))return!0;for(let c of bi(o))if(a.containers.has(c))return!0;return!1}}function ws(e,t={}){Oo(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function Ns(e,t,n={}){Oo(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function Ku(e,t){return t.isIgnoredPath(e.relativePath)?et("ignored-file"):wt(e.symbol)?et("module-like-symbol"):zu(e.symbol)?!e.isFunctionLike&&e.enclosingSymbol&&zu(e.enclosingSymbol)?et("nested-non-callable-value"):!t.includeTests&&!Ps(e.relativePath)?et("test-file"):!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName)?et("excluded-file-region"):fi(e.symbol)?et("rust-trait-impl-member"):_n(e.symbol)?et("rust-test-module"):!t.includeMembers&&!_C(e)?et("member"):e.endLine-e.startLine+1<t.minLoc?et("below-min-loc"):{accepted:!0}:et("non-value-symbol")}function Ps(e){return z(e)!=="test"}function et(e){return{accepted:!1,rejectionReason:e}}function zu(e){return te(e)||e.endsWith("().")||e.endsWith(".")}function _C(e){return pe(e.symbol)||bi(e.symbol).length===0}function Wi(e,t){return q(e)-q(t)||e.relativePath.localeCompare(t.relativePath)}function Be(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function Gn(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 Qu(){return new Map}function Xu(e,t,n){let r=new Map;for(let i of ru(e,n))e.isIgnored(i.relative_path)||t.has(i.relative_path)||Ui(r,i.symbol_id,i.relative_path,i.ref_count,"scip-mention");return r}function Yu(e,t,n){let r=new Set;for(let i of iu(e,t))e.isIgnored(i.relative_path)||n.has(i.relative_path)||r.add(i.symbol_id);return r}function _s(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 Zu(e){return e?.occurrences??0}function Ui(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=td(e,t,n);o.occurrences+=r,o.sources.add(i)}function ed(e,t,n,r,i){if(r<=0)return;let o=td(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function td(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}function ht(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=Be(EC(e,{scope:n,minLoc:r,includeTests:i,includeMembers:s}),c),d=o?new Set(eu(e)):new Set,m=a?Qu():Xu(e,d,u.map(L=>L.symbolId)),f=a?Yu(e,u.map(L=>L.symbolId),d):new Set,g=a?u.filter(L=>!f.has(L.symbolId)):u;a?MC(e,g,m,d):$C(e,g,m,d);let h=a?g.filter(L=>!_s(m,L.symbolId)):u;HC(e,h,m,{includeTests:i,inactiveBarrelPaths:d,includeSemantic:!a&&l});let b=a?g.filter(L=>!_s(m,L.symbolId)):u;return AC(e,FC(b,m))}function EC(e,t){let n=Gu(e),r=[];for(let i of V(e,{scope:t.scope}))try{for(let o of J(e,i))Ku(o,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:a=>e.isIgnored(a),isExcludedRegion:n}).accepted&&r.push(o)}finally{Ns(e,i,{definitions:!0})}return r}function FC(e,t){return e.map(n=>TC(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 TC(e,t){let n=t.get(e.symbolId)??new Map,r=Zu(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,same_file_refs:r,cross_file_refs:i}}function AC(e,t){let n=[],r=0,i=0,o=0;for(let s of t){if(e.isIgnored(s.relative_path)||xe(e,s.relative_path)||le(e,s.symbol,s.relative_path))continue;let a=s.same_file_refs===0?"dead-code":"file-internal";a==="dead-code"?r++:i++,o+=s.loc,n.push({relativePath:s.relative_path,startLine:s.start_line,endLine:s.end_line,loc:s.loc,symbol:s.symbol,shortName:y(s.symbol),sameFileRefs:s.same_file_refs,kind:a})}return{symbols:n,totalCount:n.length,deadCodeCount:r,fileInternalCount:i,totalLoc:o}}function $C(e,t,n,r){if(t.length===0)return;let i=new N(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 V(e))a.add(c);i.scanSourceReferences({paths:a,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:s,skipPath:c=>r.has(c)},c=>{o.has(c.target.symbolId)&&(BC(e,c)||Ui(n,c.target.symbolId,c.sourceFile,VC(c),"source-fallback"))})}function MC(e,t,n,r){if(t.length===0)return;let i=new N(e),o=OC(t),s=new Set(i.sourceFiles());for(let u of V(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let d=c.get(u);return d||(d=Hi(e,u),c.set(u,d)),d};i.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:u=>r.has(u),resolveTargets:({sourceFile:u,name:d,kind:m})=>{let f=o.get(d);return f?jC(u,d,f,l(u),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),Ns(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&nd(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||Ui(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function OC(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 jC(e,t,n,r,i){let o=n.filter(c=>c.relativePath===e);if(o.length>0)return o;if(!i.permissive&&n.length===1)return[...n];let s=r.get(t);if(s)for(let c of s){let l=n.filter(u=>Tt(c,u.relativePath));if(l.length>0)return l}let a=new Set;for(let c of r.values())for(let l of c)a.add(l);for(let c of a){let l=n.filter(u=>Tt(c,u.relativePath));if(l.length>0&&l.length===n.length)return l}return i.permissive?[...n]:[]}function BC(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&nd(e,t)}function VC(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function nd(e,t){return t.occurrences>1?!1:ce(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function HC(e,t,n,r){for(let i of t){let o=je(e,i,{semantic:r.includeSemantic!==!1});if(o.length!==0)for(let s of o){let a=s.file;a===i.relativePath||e.isIgnored(a)||r.inactiveBarrelPaths.has(a)||!r.includeTests&&!Ps(a)||ed(n,i.symbolId,a,1,"caller-map")}}}function Es(e,t={}){let{limit:n=30,scope:r}=t,i=r?`AND def_d.relative_path LIKE '%${r}%'`:"",s=e.all(`SELECT
321
288
  gs.symbol,
322
289
  COUNT(*) AS ref_count,
323
290
  COUNT(DISTINCT ref_d.id) AS file_count,
@@ -340,14 +307,14 @@ ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,e
340
307
  ${i}
341
308
  GROUP BY gs.id
342
309
  ORDER BY ref_count DESC
343
- LIMIT ?`,n).filter(a=>!e.isIgnored(a.defined_in)).map(a=>({symbol:a.symbol,shortName:b(a.symbol),refCount:a.ref_count,fileCount:a.file_count,definedIn:a.defined_in}));return s.length>0?s:Ay(e,r,n)}function Ay(e,t,n){return Be(e,{scope:t}).filter(r=>!e.isIgnored(r.relativePath)).map(r=>Ty(e,r)).filter(r=>r.refCount>0).sort((r,i)=>i.refCount-r.refCount||i.fileCount-r.fileCount).slice(0,n)}function Ty(e,t){let n=De(e,t,{limit:500});return{symbol:t.symbol,shortName:b(t.symbol),refCount:n.length,fileCount:new Set(n.map(r=>r.file)).size,definedIn:t.relativePath}}function Io(e,t,n={}){return fl(e,t,n)?.map(r=>({symbol:r.symbol,shortName:r.shortName,fromFile:r.fromFile}))??[]}function vo(e,t){let n=My(e,t);return n.length>0?n:Oy(e,t)}function Do(e,t,n={}){return fl(e,t,n)?.filter(r=>!r.used).map(r=>({symbol:r.symbol,shortName:r.shortName,importedIn:r.importer}))??[]}function My(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
310
+ LIMIT ?`,n).filter(a=>!e.isIgnored(a.defined_in)).map(a=>({symbol:a.symbol,shortName:y(a.symbol),refCount:a.ref_count,fileCount:a.file_count,definedIn:a.defined_in}));return s.length>0?s:qC(e,r,n)}function qC(e,t,n){return Ye(e,{scope:t}).filter(r=>!e.isIgnored(r.relativePath)).map(r=>WC(e,r)).filter(r=>r.refCount>0).sort((r,i)=>i.refCount-r.refCount||i.fileCount-r.fileCount).slice(0,n)}function WC(e,t){let n=je(e,t,{limit:500});return{symbol:t.symbol,shortName:y(t.symbol),refCount:n.length,fileCount:new Set(n.map(r=>r.file)).size,definedIn:t.relativePath}}function Fs(e,t,n={}){return id(e,t,n)?.map(r=>({symbol:r.symbol,shortName:r.shortName,fromFile:r.fromFile}))??[]}function Ts(e,t){let n=UC(e,t);return n.length>0?n:JC(e,t)}function As(e,t,n={}){return id(e,t,n)?.filter(r=>!r.used).map(r=>({symbol:r.symbol,shortName:r.shortName,importedIn:r.importer}))??[]}function UC(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
344
311
  FROM mentions m
345
312
  JOIN chunks c ON m.chunk_id = c.id
346
313
  JOIN documents d ON c.document_id = d.id
347
314
  JOIN global_symbols gs ON m.symbol_id = gs.id
348
315
  WHERE gs.symbol LIKE ?
349
316
  AND m.role = 2
350
- ORDER BY d.relative_path`,`%${t}%`).filter(r=>!e.isIgnored(r.importer)).map(r=>({symbol:r.symbol,shortName:b(r.symbol),fromFile:r.importer}))}function Oy(e,t){let n=A(e,t),r=n?.relativePath??null,i=n?F(n.symbol):t.replace(/\(\)$/,""),o=n?at(n.symbol):!1,s=new Set;for(let a of T(e,{includeIgnored:!1}))for(let c of ne(e,a))$y(c,a,{targetFile:r,targetLeaf:i,targetIsModule:o})&&s.add(a);return[...s].sort().map(a=>({symbol:n?.symbol??i,shortName:n?b(n.symbol):i,fromFile:a}))}function $y(e,t,n){return!e.sourcePath||n.targetFile&&pl(e.sourcePath)!==pl(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&qy(t)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function fl(e,t,n={}){let r=pe(e,t);return r?jy(e,r,n)??(n.semantic===!1?null:By(e,r))??Hy(e,r):null}function jy(e,t,n){let i=e.all(`SELECT DISTINCT
317
+ ORDER BY d.relative_path`,`%${t}%`).filter(r=>!e.isIgnored(r.importer)).map(r=>({symbol:r.symbol,shortName:y(r.symbol),fromFile:r.importer}))}function JC(e,t){let n=B(e,t),r=n?.relativePath??null,i=n?$(n.symbol):t.replace(/\(\)$/,""),o=n?wt(n.symbol):!1,s=new Set;for(let a of V(e,{includeIgnored:!1}))for(let c of ce(e,a))GC(c,a,{targetFile:r,targetLeaf:i,targetIsModule:o})&&s.add(a);return[...s].sort().map(a=>({symbol:n?.symbol??i,shortName:n?y(n.symbol):i,fromFile:a}))}function GC(e,t,n){return!e.sourcePath||n.targetFile&&rd(e.sourcePath)!==rd(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&XC(t)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function id(e,t,n={}){let r=Ie(e,t);return r?zC(e,r,n)??(n.semantic===!1?null:KC(e,r))??QC(e,r):null}function zC(e,t,n){let i=e.all(`SELECT DISTINCT
351
318
  gs.symbol,
352
319
  def_d.relative_path AS from_file,
353
320
  imp_d.relative_path AS importer,
@@ -373,11 +340,11 @@ ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,e
373
340
  LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
374
341
  WHERE imp_d.relative_path = ?
375
342
  AND m.role = 2
376
- ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(i.length>0){let o=n.semantic===!1?[]:Mn(e,t);return i.map(s=>({symbol:s.symbol,shortName:b(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 By(e,t){let n=Mn(e,t);return n.length>0?n.map(r=>{let i=gl(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 Hy(e,t){return ne(e,t).map(n=>{let r=gl(n.importedName,n.localName,n.kind),i=n.kind==="side-effect"?!0:n.used;return{symbol:r,shortName:r,fromFile:n.sourcePath??"(external)",importer:t,used:i}})}function gl(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 pl(e){return e.replace(/\\/g,"/")}function qy(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function No(e,t){let n=sn(e,t),r=yr(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,m=1/0;for(let d of i)if(d!==l&&d.startLine<=l.startLine&&d.endLine>=l.endLine){if(d.startLine===l.startLine&&d.endLine===l.endLine&&!La(d.symbol,l.symbol))continue;let h=d.endLine-d.startLine;h<m&&(m=h,u=d)}u?u.children.push(l):s.push(l)}return s}function _o(e,t){let n=A(e,t);return n?new _(e).definitionsForFile(n.relativePath).filter(i=>i.symbol!==n.symbol).filter(i=>_a(n.symbol,i.symbol)).sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine).map(i=>({symbol:i.symbol,shortName:b(i.symbol),startLine:i.startLine,endLine:i.endLine,kind:te(i.symbol)??"unknown"})):[]}function Lo(e,t){let n=A(e,t);if(!n)return[];let r=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
343
+ ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(i.length>0){let o=n.semantic===!1?[]:xr(e,t);return i.map(s=>({symbol:s.symbol,shortName:y(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 KC(e,t){let n=xr(e,t);return n.length>0?n.map(r=>{let i=od(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 QC(e,t){return ce(e,t).map(n=>{let r=od(n.importedName,n.localName,n.kind),i=n.kind==="side-effect"?!0:n.used;return{symbol:r,shortName:r,fromFile:n.sourcePath??"(external)",importer:t,used:i}})}function od(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 rd(e){return e.replace(/\\/g,"/")}function XC(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function $s(e,t){let n=Mn(e,t),r=gi(e,n,{sort:!0});if(r.length===0)return[];let i=r.map(a=>({symbol:a.symbol,shortName:a.shortName,startLine:a.startLine,endLine:a.endLine,signature:a.signature,children:[]})),o=new Map;for(let a of i)o.set(a.symbol,a);let s=[];for(let a=0;a<r.length;a++){let c=r[a],l=i[a];if(c.enclosingSymbol&&o.has(c.enclosingSymbol)){o.get(c.enclosingSymbol).children.push(l);continue}let u=null,d=1/0;for(let m of i)if(m!==l&&m.startLine<=l.startLine&&m.endLine>=l.endLine){if(m.startLine===l.startLine&&m.endLine===l.endLine&&!pl(m.symbol,l.symbol))continue;let g=m.endLine-m.startLine;g<d&&(d=g,u=m)}u?u.children.push(l):s.push(l)}return s}function Ms(e,t){let n=B(e,t);return n?new N(e).definitionsForFile(n.relativePath).filter(i=>i.symbol!==n.symbol).filter(i=>ml(n.symbol,i.symbol)).sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine).map(i=>({symbol:i.symbol,shortName:y(i.symbol),startLine:i.startLine,endLine:i.endLine,kind:ae(i.symbol)??"unknown"})):[]}function Os(e,t){let n=B(e,t);if(!n)return[];let r=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
377
344
  FROM mentions m
378
345
  JOIN chunks c ON m.chunk_id = c.id
379
346
  WHERE m.symbol_id = ?
380
- AND m.role != 1`,n.symbolId);return[{name:b(n.symbol),count:r?.file_count??0}]}function wo(e,t){let n=pe(e,t);if(!n)return[];let i=e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
347
+ AND m.role != 1`,n.symbolId);return[{name:y(n.symbol),count:r?.file_count??0}]}function js(e,t){let n=Ie(e,t);if(!n)return[];let i=e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
381
348
  FROM mentions m
382
349
  JOIN chunks c ON m.chunk_id = c.id
383
350
  JOIN documents d ON c.document_id = d.id
@@ -394,7 +361,7 @@ ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,e
394
361
  AND m.role != 1
395
362
  AND def_d.id != d.id
396
363
  GROUP BY d.id
397
- 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 ko(e,t={}){return Vy(e,t).map(n=>({name:b(n.symbol),count:n.file_count}))}function Vy(e,t){let{limit:n=30,scope:r}=t,i=r?`AND def_d.relative_path LIKE '%${r}%'`:"";return e.all(`SELECT gs.symbol, COUNT(DISTINCT c.document_id) AS file_count
364
+ 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=ne(e).get(n);return!s||s.size===0?[]:[{name:n,count:s.size}]}function Bs(e,t={}){return YC(e,t).map(n=>({name:y(n.symbol),count:n.file_count}))}function YC(e,t){let{limit:n=30,scope:r}=t,i=r?`AND def_d.relative_path LIKE '%${r}%'`:"";return e.all(`SELECT gs.symbol, COUNT(DISTINCT c.document_id) AS file_count
398
365
  FROM mentions m
399
366
  JOIN chunks c ON m.chunk_id = c.id
400
367
  JOIN global_symbols gs ON m.symbol_id = gs.id
@@ -413,7 +380,7 @@ ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,e
413
380
  GROUP BY gs.id
414
381
  HAVING file_count > 1
415
382
  ORDER BY file_count DESC
416
- LIMIT ?`,n)}function Eo(e,t={}){let{limit:n=30,scope:r}=t,i=r?`AND d.relative_path LIKE '%${r}%'`:"";return e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
383
+ LIMIT ?`,n)}function Vs(e,t={}){let{limit:n=30,scope:r}=t,i=r?`AND d.relative_path LIKE '%${r}%'`:"";return e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
417
384
  FROM mentions m
418
385
  JOIN chunks c ON m.chunk_id = c.id
419
386
  JOIN documents d ON c.document_id = d.id
@@ -433,7 +400,7 @@ ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,e
433
400
  ${i}
434
401
  GROUP BY d.id
435
402
  ORDER BY symbol_count DESC
436
- LIMIT ?`,n).filter(s=>!e.isIgnored(s.relative_path)).map(s=>({name:s.relative_path,count:s.symbol_count}))}function Po(e,t,n){let r=pe(e,t)??t,i=pe(e,n)??n,o=e.get(`SELECT COUNT(DISTINCT gs.id) AS shared
403
+ LIMIT ?`,n).filter(s=>!e.isIgnored(s.relative_path)).map(s=>({name:s.relative_path,count:s.symbol_count}))}function Hs(e,t,n){let r=Ie(e,t)??t,i=Ie(e,n)??n,o=e.get(`SELECT COUNT(DISTINCT gs.id) AS shared
437
404
  FROM global_symbols gs
438
405
  WHERE (
439
406
  -- Defined in file1, referenced in file2
@@ -465,7 +432,7 @@ ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,e
465
432
  JOIN documents d ON c.document_id = d.id
466
433
  WHERE m.symbol_id = gs.id AND m.role != 1 AND d.relative_path = ?
467
434
  )
468
- )`,r,i,i,r);return{file1:r,file2:i,sharedSymbols:o?.shared??0}}function Fo(e,t={}){let{limit:n=20,scope:r}=t,i=r?`AND d1.relative_path LIKE '%${r}%' AND d2.relative_path LIKE '%${r}%'`:"";return e.all(`SELECT
435
+ )`,r,i,i,r);return{file1:r,file2:i,sharedSymbols:o?.shared??0}}function qs(e,t={}){let{limit:n=20,scope:r}=t,i=r?`AND d1.relative_path LIKE '%${r}%' AND d2.relative_path LIKE '%${r}%'`:"";return e.all(`SELECT
469
436
  def_d.relative_path AS file1,
470
437
  ref_d.relative_path AS file2,
471
438
  COUNT(DISTINCT gs.id) AS shared
@@ -487,12 +454,11 @@ ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,e
487
454
  ${i}
488
455
  GROUP BY def_d.id, ref_d.id
489
456
  ORDER BY shared DESC
490
- LIMIT ?`,n).filter(s=>!e.isIgnored(s.file1)&&!e.isIgnored(s.file2)).map(s=>({file1:s.file1,file2:s.file2,sharedSymbols:s.shared}))}function At(e,t={}){let{scope:n,maxDepth:r=10}=t,i=se(e,n),o=[],s=new Set,a=new Set,c=[];function l(m,d){if(d>r)return;if(a.has(m)){let h=c.indexOf(m);if(h!==-1){let f=c.slice(h).concat(m),y=f.indexOf(f.reduce((S,x)=>S<x?S:x)),R=[...f.slice(y,-1),...f.slice(0,y),f[y]],k=R.join(" -> ");u.has(k)||(u.add(k),o.push({path:R,kind:Wy(R)}))}return}if(s.has(m))return;s.add(m),a.add(m),c.push(m);let p=i.get(m);if(p)for(let h of p)l(h,d+1);c.pop(),a.delete(m)}let u=new Set;for(let m of i.keys())s.has(m)||l(m,0);return o.sort((m,d)=>m.kind!==d.kind?m.kind==="real"?-1:1:m.path.length-d.path.length),o}function Wy(e){for(let r of e){let i=G(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":Ar(t)||Ar(n)||hl(t,n)||hl(n,t)||yl(t,n)||yl(n,t)||G(t)==="entry"||G(n)==="entry"?"module-hierarchy":"real"}function hl(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 yl(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 Ao(e,t={}){let{limit:n=20,scope:r,minFanIn:i=2,minFanOut:o=2,scanLimit:s}=t,a=new _(e);return Ne(a.productionCallableDefinitions({scope:r,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s).map(u=>Uy(e,u,t.semantic!==!1)).filter(u=>u.fanIn>=i&&u.fanOut>=o).sort((u,m)=>m.score-u.score||m.fanIn-u.fanIn).slice(0,n)}function Uy(e,t,n){let r=new Set(De(e,t,{limit:500,semantic:n}).map(o=>o.file)).size,i=new Set(Se(e,t,{limit:500,semantic:n}).filter(o=>o.file!==t.relativePath).map(o=>`${o.symbol}|${o.file}`)).size;return{symbol:t.symbol,shortName:b(t.symbol),fanIn:r,fanOut:i,score:r*i,definedIn:t.relativePath}}function Tt(e,t={}){let{scope:n,minLoc:r=3,scanLimit:i}=t,o=new _(e),s=t.semantic!==!1,a=Ne(o.productionCallableDefinitions({scope:n,minLoc:r,excludeEntrySurfaces:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,sortByLocDesc:typeof i=="number"&&i>0}),i),c=o.crossFileCallerMap(a,{semantic:s}),l=new Set(c.keys());for(let f of o.frameworkReferencedSymbolIds(a))l.add(f);let u=o.symbolsWithNonSelfCallees(a,{additive:!1,semantic:s}),m=a.filter(f=>!l.has(f.symbolId)).filter(f=>!u.has(f.symbolId)),d=o.sourceFallbackCallerFiles(m);for(let f of d.keys())l.add(f);let p=m.filter(f=>!l.has(f.symbolId)),h=o.symbolsWithNonSelfCallees(p,{additive:!0,semantic:s});for(let f of h)u.add(f);return p.filter(f=>!u.has(f.symbolId)).sort((f,y)=>H(y)-H(f)||f.relativePath.localeCompare(y.relativePath)||f.startLine-y.startLine).map(f=>({symbol:f.symbol,shortName:b(f.symbol),relativePath:f.relativePath,startLine:f.startLine,endLine:f.endLine,loc:H(f)}))}var Mo={0:"UnspecifiedKind",1:"AbstractMethod",2:"Accessor",3:"Array",4:"Assertion",5:"AssociatedType",6:"Attribute",7:"Axiom",8:"Boolean",9:"Class",10:"Constant",11:"Constructor",12:"Contract",13:"DataFamily",14:"DefinitionMacro",15:"Delegate",16:"Enum",17:"EnumMember",18:"Error",19:"Event",20:"Fact",21:"Field",22:"File",23:"Function",24:"Getter",25:"Grammar",26:"Instance",27:"Interface",28:"Key",29:"Lang",30:"Lemma",31:"Library",32:"Macro",33:"Method",34:"MethodAlias",35:"MethodReceiver",36:"MethodSpecification",37:"Message",38:"Modifier",39:"Module",40:"Namespace",41:"Null",42:"Number",43:"Object",44:"Operator",45:"Package",46:"PackageObject",47:"Parameter",48:"ParameterLabel",49:"Pattern",50:"Predicate",51:"Property",52:"Protocol",53:"ProtocolMethod",54:"PureVirtualMethod",55:"Quasiquoter",56:"SelfParameter",57:"Setter",58:"Signature",59:"SingletonClass",60:"SingletonMethod",61:"StaticDataMember",62:"StaticEvent",63:"StaticField",64:"StaticMethod",65:"StaticProperty",66:"StaticVariable",67:"String",68:"Struct",69:"Subscript",70:"Tactic",71:"Theorem",72:"ThisParameter",73:"Trait",74:"TraitMethod",75:"Type",76:"TypeAlias",77:"TypeClass",78:"TypeClassMethod",79:"TypeFamily",80:"TypeParameter",81:"Union",82:"Value",83:"Variable"},To=new Map;for(let[e,t]of Object.entries(Mo))To.set(t.toLowerCase(),Number(e));function Gy(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),r=To.get(n);if(r!==void 0)return r;for(let[i,o]of To)if(i.includes(n))return o;return null}function Oo(e,t,n={}){let{scope:r,limit:i=100}=n,o=Gy(t);return o===null?[]:bl(e,r).map(a=>({row:a,resolvedKind:Sl(a)})).filter(a=>a.resolvedKind===o).slice(0,i).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:b(a.symbol),kind:c,kindName:Mo[c]??"Unknown",relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function $o(e,t={}){let n=new Map;for(let r of bl(e,t.scope)){let i=Sl(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:Mo[r]??"Unknown",count:i}))}function bl(e,t){return Be(e,{scope:t}).map(Jy)}function Jy(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 Sl(e){return e.kind!==null&&e.kind!==0?zy(e.kind,e.symbol,e.documentation):Ky(e.symbol,e.documentation,e.enclosing_symbol)}function zy(e,t,n){let r=(n??"").toLowerCase();if(te(t)==="type"){if(r.includes("type "))return 76;if(r.includes("interface "))return 27;if(r.includes("struct "))return 68;if(r.includes("trait "))return 73;if(r.includes("class "))return 9}return e}function Ky(e,t,n){let r=ee(e);if("kind"in r)return null;let i=r.descriptors,o=i[i.length-2]??null,s=te(e),a=(t??"").toLowerCase();return s==="type"?a.includes("type ")?76:a.includes("interface ")?27:a.includes("struct ")?68:a.includes("trait ")?73:(a.includes("class "),9):s==="method"?o?.suffix==="type"?33:23:s==="namespace"?39:s!=="term"?null:a.includes("async def ")||a.includes("def ")?23:(n?te(n):o?.suffix??null)==="type"?21:83}function jo(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,m=[],d=0;for(let D of o.keys()){if(c.has(D))continue;let w=[],$=(o.get(D)??new Set).values();for(c.set(D,d),l.set(D,d),d+=1,m.push(D),u.add(D),w.push({node:D,iter:$,pendingChild:null});w.length>0;){let P=w[w.length-1];if(P.pendingChild!==null){let $e=P.pendingChild;P.pendingChild=null,l.set(P.node,Math.min(l.get(P.node),l.get($e)))}let ie=P.iter.next();if(ie.done){if(l.get(P.node)===c.get(P.node)){let $e=[];for(;;){let pr=m.pop();if(u.delete(pr),$e.push(pr),s.set(pr,a.length),pr===P.node)break}a.push($e)}w.pop();continue}let he=ie.value;if(c.has(he))u.has(he)&&l.set(P.node,Math.min(l.get(P.node),c.get(he)));else{c.set(he,d),l.set(he,d),d+=1,m.push(he),u.add(he);let $e=(o.get(he)??new Set).values();P.pendingChild=he,w.push({node:he,iter:$e,pendingChild:null})}}}let p=new Map,h=new Array(a.length);for(let D=0;D<a.length;D++)h[D]=a[D].length,p.set(D,new Set);for(let[D,w]of o){let $=s.get(D);for(let P of w){let ie=s.get(P);ie!==$&&p.get($).add(ie)}}let f=new Array(a.length),y=new Array(a.length);for(let D=0;D<a.length;D++){let w=[],$=0;for(let P of p.get(D)){let ie=y[P];ie>$&&($=ie,w=f[P])}f[D]=[D,...w],y[D]=h[D]+$}function R(D){return f[D]}let k=a.map(D=>[...D].sort()),S=new Set,x=[];for(let D=0;D<a.length;D++){let w=R(D),$=[];for(let ie of w)$.push(...k[ie]);if($.length<i)continue;let P=$.join(" ");S.has(P)||(S.add(P),x.push({chain:$,depth:$.length}))}return x.sort((D,w)=>w.depth-D.depth),x.slice(0,n)}function Bo(e,t){let n=A(e,t);if(!n)return[];let r=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
491
- WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:b(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 m=e.get("SELECT symbol, enclosing_symbol FROM global_symbols WHERE symbol = ?",o);if(!m)break;i.push({symbol:m.symbol,shortName:b(m.symbol),depth:s}),o=m.enclosing_symbol,s++}if(i.length>1)return i;let c=ee(r.symbol);if("kind"in c)return i;let l=c.descriptors;if(l.length<=1)return i;let u=[i[0]];for(let m=l.length-2,d=1;m>=0;m--,d++){let h=l.slice(0,m+1).map(f=>f.suffix==="method"?`${f.name}()`:f.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:h,shortName:h,depth:d})}return u}function Wn(e,t,n={}){let r=A(e,t);if(!r)return null;let i=n.semantic!==!1,o=De(e,r,{limit:50,semantic:i}),s=gn(Se(e,r,{limit:50,additive:!0,callableOnly:!0,semantic:i}));return{symbol:r.symbol,shortName:b(r.symbol),callers:o.map(a=>({symbol:a.symbol,shortName:b(a.symbol),file:a.file})),callees:s.map(a=>({symbol:a.symbol,shortName:b(a.symbol),file:a.file}))}}function Un(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function Gn(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function xl(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 Cl(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 Ho(e){let t=e.length;if(t===0)return new Map;let n=new Map;for(let i of e)for(let o of i)n.set(o,(n.get(o)??0)+1);let r=new Map;for(let[i,o]of n)r.set(i,Math.log(t/o));return r}function Qy(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 Rl(e,t,n){let r=Un(e,t);if(r.size===0)return{similarity:0,significantShared:[],trivialShared:[]};let i=0,o=0,s=0,a=new Set([...e,...t]);for(let p of a){let h=n.get(p)??0,f=e.has(p)?h:0,y=t.has(p)?h:0;i+=f*y,o+=f*f,s+=y*y}let c=Math.sqrt(o)*Math.sqrt(s),l=c>0?i/c:0,u=Qy(n),m=[],d=[];for(let p of r)(n.get(p)??0)>=u?m.push(p):d.push(p);return m.sort((p,h)=>(n.get(h)??0)-(n.get(p)??0)),{similarity:l,significantShared:m,trivialShared:d}}function zn(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=Zy(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!Y(o.symbol))return[];let s=Yy(e,o,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,i):tb(e,t,{minSimilarity:r,limit:i})}function Yy(e,t,n,r){let i=Kr(e,{minCallees:3,excludeSymbol:t.symbol,scanLimit:r.scanLimit,semantic:r.semantic}),o=Ho([t,...i].map(a=>a.callees)),s=[];for(let a of i){if(a.callees.size<3)continue;let c=Il(t,a,o,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0});c&&s.push(c)}return s.sort((a,c)=>c.similarity-a.similarity),s}function Il(e,t,n,r){let{similarity:i,significantShared:o}=Rl(e.callees,t.callees,n);if(i<r.minSimilarity)return null;let s=Un(e.callees,t.callees).size;if(o.length<r.requireSignificantShared&&s<r.requireSharedCount)return null;let a=o.length>0?o:[...Un(e.callees,t.callees)];return{symbolA:e.symbol,shortNameA:b(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:b(t.symbol),fileB:t.file,similarity:i,similarityBasis:"callees",sharedCallees:a.map(b),uniqueToA:[...Gn(e.callees,t.callees)].map(b),uniqueToB:[...Gn(t.callees,e.callees)].map(b)}}function Xe(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=Kr(e,{minCallees:o,scope:i,scanLimit:a,semantic:t.semantic!==!1}),l=Ho(c.map(f=>f.callees)),u=new Map;for(let f of c)for(let y of f.callees)u.set(y,(u.get(y)??0)+1);let m=Math.max(8,Math.ceil(Math.sqrt(c.length))),d=new Map;for(let f=0;f<c.length;f+=1)for(let y of c[f].callees){if((u.get(y)??0)>m)continue;let R=d.get(y);R||(R=[],d.set(y,R)),R.push(f)}let p=[],h=new Set;e:for(let f=0;f<c.length;f+=1){let y=c[f],R=new Set;for(let k of y.callees){let S=d.get(k);if(S)for(let x of S)x>f&&R.add(x)}for(let k of R){let S=`${f}|${k}`;if(h.has(S))continue;h.add(S);let x=c[k];if(s&&y.file===x.file)continue;if(y.paramCount>=0&&x.paramCount>=0){let w=Math.abs(y.paramCount-x.paramCount),$=Math.max(2,Math.ceil(Math.max(y.paramCount,x.paramCount)*.5));if(w>$)continue}let D=Il(y,x,l,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4});if(D&&(p.push(D),p.length>r*5))break e}}return p.sort((f,y)=>y.similarity-f.similarity),p.slice(0,r)}var Xy=["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 Zy(e,t,n){let r=A(e,t),i=new _(e);if(!r)return null;let o=Se(e,r,{semantic:n.semantic});return{symbol:r.symbol,file:r.relativePath,callees:Qr(o.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}function Kr(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:o}=t,s=new _(e),a=Ne(s.productionCallableDefinitions({scope:r,minLoc:5,excludeSymbol:i,sortByLocDesc:typeof o=="number"&&o>0}),o),c=s.calleeMap(a,{semantic:t.semantic!==!1});return a.map(l=>({symbol:l.symbol,file:l.relativePath,callees:Qr((c.get(l.symbolId)??[]).map(u=>u.symbol)),paramCount:s.callableSignature(l)?.paramCount??-1})).filter(l=>l.callees.size>=n)}function Qr(e){return new Set([...e].filter(t=>!eb(t)))}function eb(e){return Xy.some(t=>e.includes(t))}function tb(e,t,n){let r=nb(e,t);if(!r||r.tokens.size<3)return[];let i=n.minSimilarity>=.5?n.minSimilarity:.3,o=[];for(let s of ib(e)){if(s.symbol===r.symbol||s.tokens.size<3)continue;let a=Un(r.tokens,s.tokens);if(a.size<2)continue;let c=new Set([...r.tokens,...s.tokens]),l=c.size>0?a.size/c.size:0;l<i||o.push({symbolA:r.symbol,shortNameA:b(r.symbol),fileA:r.file,symbolB:s.symbol,shortNameB:b(s.symbol),fileB:s.file,similarity:l,similarityBasis:"source-tokens",sharedCallees:[...a].sort(),uniqueToA:[...Gn(r.tokens,s.tokens)].sort(),uniqueToB:[...Gn(s.tokens,r.tokens)].sort()})}return o.sort((s,a)=>a.similarity-s.similarity||s.shortNameB.localeCompare(a.shortNameB)),o.slice(0,n.limit)}function nb(e,t){let n=A(e,t);if(!n||!Y(n.symbol))return null;let r=rb(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function rb(e,t){let n=F(t.symbol),r=vl(e,t.relativePath,t.startLine,t.endLine,n),i=Dl(r,n);return i.size>0?i:null}function ib(e){return new _(e).productionCallableDefinitions().map(n=>({symbol:n.symbol,file:n.relativePath,tokens:Dl(vl(e,n.relativePath,n.startLine,n.endLine,n.leaf),n.leaf)})).filter(n=>n.tokens.size>0)}function vl(e,t,n,r,i){let o=M(e,t);if(!o)return"";let s=o.split(`
492
- `);if(r>=n&&r-n<=12)return s.slice(n,r+1).join(`
493
- `);let a=[new RegExp(`\\bdef\\s+${Jn(i)}\\b`),new RegExp(`\\bfun\\s+${Jn(i)}\\b`),new RegExp(`\\bfn\\s+${Jn(i)}\\b`),new RegExp(`\\bfunction\\s+${Jn(i)}\\b`),new RegExp(`\\b${Jn(i)}\\s*\\(`)],c=s.findIndex(l=>a.some(u=>u.test(l)));if(c>=0){let l=c;for(let u=c+1;u<s.length&&u<=c+8;u++){let m=s[u]??"";if(u>c&&sb(m)||(l=u,m.trim()===""&&u>c+1))break}return s.slice(c,l+1).join(`
494
- `)}return s.slice(n,Math.min(s.length,n+8)).join(`
495
- `)}function Dl(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=ob(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 ob(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 sb(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function Jn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qo(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=ab(e,{scope:i,minDeps:s}),l=[];if(o){let u=a.find(m=>m.file.includes(o));if(!u)return[];for(let m of a){if(m.file===u.file)continue;let d=Nl(u,m,n,c);d&&l.push(d)}}else for(let u=0;u<a.length;u++){for(let m=u+1;m<a.length;m++){let d=Nl(a[u],a[m],n,c);d&&l.push(d)}if(l.length>r*5)break}return l.sort((u,m)=>m.similarity-u.similarity),l.slice(0,r)}function ab(e,t){let{scope:n,minDeps:r}=t,i=se(e,n),{universalDeps:o,distinctiveDeps:s}=cb(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 cb(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 Nl(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=xl(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 Vo(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:o=3,maxChainLength:s=8}=t,a=se(e,i),c=hb(a,o,s);if(c.length===0)return[];let l=lb(c);return l.length<2?[]:gb(db(l,n,r),r)}function lb(e){let t=ub(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 ub(e){let{nodeFreq:t,tailFreq:n}=mb(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 mb(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 db(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let o=i+1;o<e.length;o++){let s=pb(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 pb(e,t,n){if(!fb(e.filtered,t.filtered))return null;let{distance:r,ops:i}=yb(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:bb(e.original,t.original),commonSuffix:Sb(e.original,t.original)}}function fb(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function gb(e,t){let n=[];for(let r of e)if(n.some(o=>_l(r.chainA,o.chainA)&&_l(r.chainB,o.chainB))||n.push(r),n.length>=t)break;return n}function hb(e,t,n){let r=[];for(let o of e.keys()){if(r.length>=500)break;Ll(e,o,[o],new Set([o]),t,n,r,500)}return r}function Ll(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),Ll(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 yb(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 bb(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 Sb(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 _l(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),r=e.join("\u2192");return n.includes(r)}function _e(e){let t=e.orderCandidates?[...e.candidates()].sort(e.orderCandidates):e.candidates(),n=Ne(t,e.scanLimit),r=e.prepare?.(n)??void 0,i=[];for(let o of n){let s=e.evaluate(o,r);s&&i.push(s)}return e.orderResults&&i.sort(e.orderResults),typeof e.limit=="number"?i.slice(0,e.limit):i}function Mt(e,t={}){let{scope:n,minLoc:r=10,minCallees:i=6,limit:o=20,scanLimit:s}=t,a=new _(e);return _e({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:r,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:s,prepare:c=>a.calleeMap(c,{semantic:t.semantic!==!1}),evaluate:(c,l)=>xb(c,l.get(c.symbolId)??[],i),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function xb(e,t,n){let r=new Set(t.map(a=>a.symbol));if(r.size<n)return null;let i=Cb(r,t),o=Rb(r,i);if(o.length<2)return null;let s=Ib(o,i);return s.length===0?null:{symbol:e.symbol,shortName:b(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:H(e),totalCallees:r.size,clusters:s}}function Cb(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 Rb(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 Ib(e,t){return e.filter(n=>n.size>=3).map(n=>vb(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function vb(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(b),isolation:s}}function Kn(e,t,n={}){let{maxDepth:r=5,scope:i}=n,o=A(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 m=[];for(let d of l)for(let p of Db(e,d,i)){let h=`${p.file}|${p.shortName}`;if(p.symbolId!==null){if(a.has(p.symbolId))continue;a.add(p.symbolId)}else if(c.has(h))continue;c.add(h),s.push({symbol:p.symbol,shortName:p.shortName,file:p.file,depth:u}),p.symbolId!==null&&p.symbolMatch&&m.push(p.symbolMatch)}l=m}return s.sort((u,m)=>u.depth-m.depth||u.file.localeCompare(m.file)),s}function Db(e,t,n){let r=De(e,t,{limit:500}).filter(l=>!e.isIgnored(l.file)).filter(l=>!n||l.file.includes(n)),i=new Set(r.map(l=>l.file)),o=[];for(let l of Nb(e,t,n)){if(i.has(l))continue;let u=V(e,l),m=u.length>0?Ce(u,u[0].startLine):null;o.push({symbol:m?.symbol??l,file:l})}let s=[...r,...o],a=[],c=new Set;for(let l of s){let u=on(e,l.symbol);if(!u){let d=`${l.file}|${l.symbol}`;if(c.has(d))continue;c.add(d),a.push({symbolId:null,symbol:l.symbol,shortName:b(l.symbol),file:l.file,symbolMatch:null});continue}if(u.symbolId===t.symbolId||e.isIgnored(u.relativePath)||!_b(u.symbol))continue;let m=`${u.symbolId}|${u.relativePath}`;c.has(m)||(c.add(m),a.push({symbolId:u.symbolId,symbol:u.symbol,shortName:b(u.symbol),file:u.relativePath,symbolMatch:u}))}return a}function Nb(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
457
+ LIMIT ?`,n).filter(s=>!e.isIgnored(s.file1)&&!e.isIgnored(s.file2)).map(s=>({file1:s.file1,file2:s.file2,sharedSymbols:s.shared}))}function rn(e,t={}){let{scope:n,maxDepth:r=10}=t,i=ne(e,n),o=[],s=new Set,a=new Set,c=[];function l(d,m){if(m>r)return;if(a.has(d)){let g=c.indexOf(d);if(g!==-1){let h=c.slice(g).concat(d),b=h.indexOf(h.reduce((k,E)=>k<E?k:E)),L=[...h.slice(b,-1),...h.slice(0,b),h[b]],F=L.join(" -> ");u.has(F)||(u.add(F),o.push({path:L,kind:ZC(L)}))}return}if(s.has(d))return;s.add(d),a.add(d),c.push(d);let f=i.get(d);if(f)for(let g of f)l(g,m+1);c.pop(),a.delete(d)}let u=new Set;for(let d of i.keys())s.has(d)||l(d,0);return o.sort((d,m)=>d.kind!==m.kind?d.kind==="real"?-1:1:d.path.length-m.path.length),o}function ZC(e){for(let r of e){let i=z(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":Ei(t)||Ei(n)||sd(t,n)||sd(n,t)||ad(t,n)||ad(n,t)||z(t)==="entry"||z(n)==="entry"?"module-hierarchy":"real"}function sd(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 ad(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 Ws(e,t={}){let{limit:n=20,scope:r,minFanIn:i=2,minFanOut:o=2,scanLimit:s}=t,a=new N(e);return Be(a.productionCallableDefinitions({scope:r,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s).map(u=>ev(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 ev(e,t,n){let r=new Set(je(e,t,{limit:500,semantic:n}).map(o=>o.file)).size,i=new Set(_e(e,t,{limit:500,semantic:n}).filter(o=>o.file!==t.relativePath).map(o=>`${o.symbol}|${o.file}`)).size;return{symbol:t.symbol,shortName:y(t.symbol),fanIn:r,fanOut:i,score:r*i,definedIn:t.relativePath}}function on(e,t={}){let{scope:n,minLoc:r=3,scanLimit:i}=t,o=new N(e),s=t.semantic!==!1,a=Be(o.productionCallableDefinitions({scope:n,minLoc:r,excludeEntrySurfaces:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,sortByLocDesc:typeof i=="number"&&i>0}),i),c=o.crossFileCallerMap(a,{semantic:s}),l=new Set(c.keys());for(let h of o.frameworkReferencedSymbolIds(a))l.add(h);let u=o.symbolsWithNonSelfCallees(a,{additive:!1,semantic:s}),d=a.filter(h=>!l.has(h.symbolId)).filter(h=>!u.has(h.symbolId)),m=o.sourceFallbackCallerFiles(d);for(let h of m.keys())l.add(h);let f=d.filter(h=>!l.has(h.symbolId)),g=o.symbolsWithNonSelfCallees(f,{additive:!0,semantic:s});for(let h of g)u.add(h);return f.filter(h=>!u.has(h.symbolId)).sort((h,b)=>q(b)-q(h)||h.relativePath.localeCompare(b.relativePath)||h.startLine-b.startLine).map(h=>({symbol:h.symbol,shortName:y(h.symbol),relativePath:h.relativePath,startLine:h.startLine,endLine:h.endLine,loc:q(h)}))}var Js={0:"UnspecifiedKind",1:"AbstractMethod",2:"Accessor",3:"Array",4:"Assertion",5:"AssociatedType",6:"Attribute",7:"Axiom",8:"Boolean",9:"Class",10:"Constant",11:"Constructor",12:"Contract",13:"DataFamily",14:"DefinitionMacro",15:"Delegate",16:"Enum",17:"EnumMember",18:"Error",19:"Event",20:"Fact",21:"Field",22:"File",23:"Function",24:"Getter",25:"Grammar",26:"Instance",27:"Interface",28:"Key",29:"Lang",30:"Lemma",31:"Library",32:"Macro",33:"Method",34:"MethodAlias",35:"MethodReceiver",36:"MethodSpecification",37:"Message",38:"Modifier",39:"Module",40:"Namespace",41:"Null",42:"Number",43:"Object",44:"Operator",45:"Package",46:"PackageObject",47:"Parameter",48:"ParameterLabel",49:"Pattern",50:"Predicate",51:"Property",52:"Protocol",53:"ProtocolMethod",54:"PureVirtualMethod",55:"Quasiquoter",56:"SelfParameter",57:"Setter",58:"Signature",59:"SingletonClass",60:"SingletonMethod",61:"StaticDataMember",62:"StaticEvent",63:"StaticField",64:"StaticMethod",65:"StaticProperty",66:"StaticVariable",67:"String",68:"Struct",69:"Subscript",70:"Tactic",71:"Theorem",72:"ThisParameter",73:"Trait",74:"TraitMethod",75:"Type",76:"TypeAlias",77:"TypeClass",78:"TypeClassMethod",79:"TypeFamily",80:"TypeParameter",81:"Union",82:"Value",83:"Variable"},Us=new Map;for(let[e,t]of Object.entries(Js))Us.set(t.toLowerCase(),Number(e));function tv(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),r=Us.get(n);if(r!==void 0)return r;for(let[i,o]of Us)if(i.includes(n))return o;return null}function Gs(e,t,n={}){let{scope:r,limit:i=100}=n,o=tv(t);return o===null?[]:cd(e,r).map(a=>({row:a,resolvedKind:ld(a)})).filter(a=>a.resolvedKind===o).slice(0,i).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:y(a.symbol),kind:c,kindName:Js[c]??"Unknown",relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function zs(e,t={}){let n=new Map;for(let r of cd(e,t.scope)){let i=ld(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:Js[r]??"Unknown",count:i}))}function cd(e,t){return Ye(e,{scope:t}).map(nv)}function nv(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 ld(e){return e.kind!==null&&e.kind!==0?rv(e.kind,e.symbol,e.documentation):iv(e.symbol,e.documentation,e.enclosing_symbol)}function rv(e,t,n){let r=(n??"").toLowerCase();if(ae(t)==="type"){if(r.includes("type "))return 76;if(r.includes("interface "))return 27;if(r.includes("struct "))return 68;if(r.includes("trait "))return 73;if(r.includes("class "))return 9}return e}function iv(e,t,n){let r=se(e);if("kind"in r)return null;let i=r.descriptors,o=i[i.length-2]??null,s=ae(e),a=(t??"").toLowerCase();return s==="type"?a.includes("type ")?76:a.includes("interface ")?27:a.includes("struct ")?68:a.includes("trait ")?73:(a.includes("class "),9):s==="method"?o?.suffix==="type"?33:23:s==="namespace"?39:s!=="term"?null:a.includes("async def ")||a.includes("def ")?23:(n?ae(n):o?.suffix??null)==="type"?21:83}function Ks(e,t={}){let{limit:n=10,scope:r,minDepth:i=3}=t,o=ne(e,r),s=new Map,a=[],c=new Map,l=new Map,u=new Set,d=[],m=0;for(let C of o.keys()){if(c.has(C))continue;let w=[],M=(o.get(C)??new Set).values();for(c.set(C,m),l.set(C,m),m+=1,d.push(C),u.add(C),w.push({node:C,iter:M,pendingChild:null});w.length>0;){let j=w[w.length-1];if(j.pendingChild!==null){let Dt=j.pendingChild;j.pendingChild=null,l.set(j.node,Math.min(l.get(j.node),l.get(Dt)))}let ye=j.iter.next();if(ye.done){if(l.get(j.node)===c.get(j.node)){let Dt=[];for(;;){let lt=d.pop();if(u.delete(lt),Dt.push(lt),s.set(lt,a.length),lt===j.node)break}a.push(Dt)}w.pop();continue}let Fe=ye.value;if(c.has(Fe))u.has(Fe)&&l.set(j.node,Math.min(l.get(j.node),c.get(Fe)));else{c.set(Fe,m),l.set(Fe,m),m+=1,d.push(Fe),u.add(Fe);let Dt=(o.get(Fe)??new Set).values();j.pendingChild=Fe,w.push({node:Fe,iter:Dt,pendingChild:null})}}}let f=new Map,g=new Array(a.length);for(let C=0;C<a.length;C++)g[C]=a[C].length,f.set(C,new Set);for(let[C,w]of o){let M=s.get(C);for(let j of w){let ye=s.get(j);ye!==M&&f.get(M).add(ye)}}let h=new Array(a.length),b=new Array(a.length);for(let C=0;C<a.length;C++){let w=[],M=0;for(let j of f.get(C)){let ye=b[j];ye>M&&(M=ye,w=h[j])}h[C]=[C,...w],b[C]=g[C]+M}function L(C){return h[C]}let F=a.map(C=>[...C].sort()),k=new Set,E=[];for(let C=0;C<a.length;C++){let w=L(C),M=[];for(let ye of w)M.push(...F[ye]);if(M.length<i)continue;let j=M.join(" ");k.has(j)||(k.add(j),E.push({chain:M,depth:M.length}))}return E.sort((C,w)=>w.depth-C.depth),E.slice(0,n)}function Qs(e,t){let n=B(e,t);if(!n)return[];let r=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
458
+ WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:y(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:y(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(i.length>1)return i;let c=se(r.symbol);if("kind"in c)return i;let l=c.descriptors;if(l.length<=1)return i;let u=[i[0]];for(let d=l.length-2,m=1;d>=0;d--,m++){let g=l.slice(0,d+1).map(h=>h.suffix==="method"?`${h.name}()`:h.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:g,shortName:g,depth:m})}return u}function wr(e,t,n={}){let r=B(e,t);if(!r)return null;let i=n.semantic!==!1,o=je(e,r,{limit:50,semantic:i}),s=Gn(_e(e,r,{limit:50,additive:!0,callableOnly:!0,semantic:i}));return{symbol:r.symbol,shortName:y(r.symbol),callers:o.map(a=>({symbol:a.symbol,shortName:y(a.symbol),file:a.file})),callees:s.map(a=>({symbol:a.symbol,shortName:y(a.symbol),file:a.file}))}}function Ce(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function ue(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function tt(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 ud(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 Xs(e){let t=e.length;if(t===0)return new Map;let n=new Map;for(let i of e)for(let o of i)n.set(o,(n.get(o)??0)+1);let r=new Map;for(let[i,o]of n)r.set(i,Math.log(t/o));return r}function ov(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 dd(e,t,n){let r=Ce(e,t);if(r.size===0)return{similarity:0,significantShared:[],trivialShared:[]};let i=0,o=0,s=0,a=new Set([...e,...t]);for(let f of a){let g=n.get(f)??0,h=e.has(f)?g:0,b=t.has(f)?g:0;i+=h*b,o+=h*h,s+=b*b}let c=Math.sqrt(o)*Math.sqrt(s),l=c>0?i/c:0,u=ov(n),d=[],m=[];for(let f of r)(n.get(f)??0)>=u?d.push(f):m.push(f);return d.sort((f,g)=>(n.get(g)??0)-(n.get(f)??0)),{similarity:l,significantShared:d,trivialShared:m}}function Pr(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=lv(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!te(o.symbol))return[];let s=sv(e,o,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,i):pv(e,t,{minSimilarity:r,limit:i})}function sv(e,t,n,r){let i=Ji(e,{minCallees:3,excludeSymbol:t.symbol,scanLimit:r.scanLimit,semantic:r.semantic}),o=Xs([t,...i].map(a=>a.callees)),s=[];for(let a of i){if(a.callees.size<3)continue;let c=md(t,a,o,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0});c&&s.push(c)}return s.sort((a,c)=>c.similarity-a.similarity),s}function md(e,t,n,r){let{similarity:i,significantShared:o}=dd(e.callees,t.callees,n);if(i<r.minSimilarity)return null;let s=Ce(e.callees,t.callees).size;if(o.length<r.requireSignificantShared&&s<r.requireSharedCount)return null;let a=o.length>0?o:[...Ce(e.callees,t.callees)];return{symbolA:e.symbol,shortNameA:y(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:y(t.symbol),fileB:t.file,similarity:i,similarityBasis:"callees",sharedCallees:a.map(y),uniqueToA:[...ue(e.callees,t.callees)].map(y),uniqueToB:[...ue(t.callees,e.callees)].map(y)}}function bt(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=Ji(e,{minCallees:o,scope:i,scanLimit:a,semantic:t.semantic!==!1}),l=Xs(c.map(b=>b.callees)),u=new Map;for(let b of c)for(let L of b.callees)u.set(L,(u.get(L)??0)+1);let d=Math.max(8,Math.ceil(Math.sqrt(c.length))),m=new Map;for(let b=0;b<c.length;b+=1)for(let L of c[b].callees){if((u.get(L)??0)>d)continue;let F=m.get(L);F||(F=[],m.set(L,F)),F.push(b)}let f=[],g=0,h=new Set;for(let b=0;b<c.length;b+=1){let L=c[b],F=new Set;for(let k of L.callees){let E=m.get(k);if(E)for(let C of E)C>b&&F.add(C)}for(let k of F){let E=`${b}|${k}`;if(h.has(E))continue;h.add(E);let C=c[k];if(s&&L.file===C.file)continue;if(L.paramCount>=0&&C.paramCount>=0){let M=Math.abs(L.paramCount-C.paramCount),j=Math.max(2,Math.ceil(Math.max(L.paramCount,C.paramCount)*.5));if(M>j)continue}let w=md(L,C,l,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4});w&&(av(f,w,r,g),g+=1)}}return f.sort((b,L)=>L.result.similarity-b.result.similarity||b.order-L.order),f.map(b=>b.result)}function av(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 cv=["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 lv(e,t,n){let r=B(e,t),i=new N(e);if(!r)return null;let o=_e(e,r,{semantic:n.semantic});return{symbol:r.symbol,file:r.relativePath,callees:Gi(o.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}var uv=ie("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]});function Ji(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:o}=t,s=t.semantic!==!1,a=uv.get(e,()=>new Map),c=`${n}|${r??""}|${o??""}|${s}`,l=a.get(c);return l||(l=dv(e,{minCallees:n,scope:r,scanLimit:o,semantic:s}),a.set(c,l)),i===void 0?l:l.filter(u=>u.symbol!==i)}function dv(e,t){let{minCallees:n,scope:r,scanLimit:i,semantic:o}=t,s=new N(e),a=Be(s.productionCallableDefinitions({scope:r,minLoc:5,sortByLocDesc:typeof i=="number"&&i>0}),i),c=s.calleeMap(a,{semantic:o});return a.map(l=>({symbol:l.symbol,file:l.relativePath,callees:Gi((c.get(l.symbolId)??[]).map(u=>u.symbol)),paramCount:s.callableSignature(l)?.paramCount??-1})).filter(l=>l.callees.size>=n)}function Gi(e){return new Set([...e].filter(t=>!mv(t)))}function mv(e){return cv.some(t=>e.includes(t))}function pv(e,t,n){let r=fv(e,t);if(!r||r.tokens.size<3)return[];let i=n.minSimilarity>=.5?n.minSimilarity:.3,o=[],s=new Set,a=yv(bv(e));for(let c of r.tokens)for(let l of a.get(c)??[])s.add(l);for(let c of s){if(c.symbol===r.symbol||c.tokens.size<3)continue;let l=Ce(r.tokens,c.tokens);if(l.size<2)continue;let u=new Set([...r.tokens,...c.tokens]),d=u.size>0?l.size/u.size:0;d<i||o.push({symbolA:r.symbol,shortNameA:y(r.symbol),fileA:r.file,symbolB:c.symbol,shortNameB:y(c.symbol),fileB:c.file,similarity:d,similarityBasis:"source-tokens",sharedCallees:[...l].sort(),uniqueToA:[...ue(r.tokens,c.tokens)].sort(),uniqueToB:[...ue(c.tokens,r.tokens)].sort()})}return o.sort((c,l)=>l.similarity-c.similarity||c.shortNameB.localeCompare(l.shortNameB)),o.slice(0,n.limit)}function fv(e,t){let n=B(e,t);if(!n||!te(n.symbol))return null;let r=gv(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function gv(e,t){let n=$(t.symbol),r=pd(e,t.relativePath,t.startLine,t.endLine,n),i=fd(r,n);return i.size>0?i:null}var hv=ie("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]});function bv(e){return hv.get(e,()=>Sv(e))}function yv(e){let t=new Map;for(let n of e)for(let r of n.tokens){let i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function Sv(e){return new N(e).productionCallableDefinitions().map(n=>({symbol:n.symbol,file:n.relativePath,tokens:fd(pd(e,n.relativePath,n.startLine,n.endLine,n.leaf),n.leaf)})).filter(n=>n.tokens.size>0)}function pd(e,t,n,r,i){let o=dt(e,t);if(o.length===0)return"";if(r>=n&&r-n<=12)return o.slice(n,r+1).join(`
459
+ `);let s=[new RegExp(`\\bdef\\s+${Nr(i)}\\b`),new RegExp(`\\bfun\\s+${Nr(i)}\\b`),new RegExp(`\\bfn\\s+${Nr(i)}\\b`),new RegExp(`\\bfunction\\s+${Nr(i)}\\b`),new RegExp(`\\b${Nr(i)}\\s*\\(`)],a=o.findIndex(c=>s.some(l=>l.test(c)));if(a>=0){let c=a;for(let l=a+1;l<o.length&&l<=a+8;l++){let u=o[l]??"";if(l>a&&Cv(u)||(c=l,u.trim()===""&&l>a+1))break}return o.slice(a,c+1).join(`
460
+ `)}return o.slice(n,Math.min(o.length,n+8)).join(`
461
+ `)}function fd(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=xv(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 xv(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 Cv(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function Nr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function nt(e){let t=[];if(e.filePattern){let n=e.profiles.find(r=>r.file.includes(e.filePattern));if(!n)return[];for(let r of e.profiles){if(r.file===n.file)continue;let i=e.compare(n,r);i&&t.push(i)}}else{let n=typeof e.overrunFactor=="number"&&Number.isFinite(e.limit)?e.limit*e.overrunFactor:Number.POSITIVE_INFINITY;for(let r=0;r<e.profiles.length;r+=1){for(let i=r+1;i<e.profiles.length;i+=1){let o=e.compare(e.profiles[r],e.profiles[i]);o&&t.push(o)}if(t.length>n)break}}return t.sort(e.sort??((n,r)=>r.similarity-n.similarity)),t.slice(0,e.limit)}function Ys(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=vv(e,{scope:i,minDeps:s});return nt({profiles:a,limit:r,filePattern:o,overrunFactor:5,compare:(l,u)=>Lv(l,u,n,c)})}function vv(e,t){let{scope:n,minDeps:r}=t,i=ne(e,n),{universalDeps:o,distinctiveDeps:s}=Rv(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 Rv(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 Lv(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=tt(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 sn(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a}=t,c=Pn(e,{scope:o,minJsxTokens:r,scanLimit:s}).filter(l=>l.kind==="component").map(l=>({file:l.file,component:l.name,tokens:l.jsxTokens,profile:l}));return nt({profiles:c,limit:i,filePattern:a,compare:(l,u)=>Iv(l,u,n),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.componentA.localeCompare(u.componentA)||l.fileB.localeCompare(u.fileB)||l.componentB.localeCompare(u.componentB)})}function Iv(e,t,n){let r=Ce(e.tokens,t.tokens);if(r.size<6||!Dv(r))return null;let i=tt(e.tokens,t.tokens);return i<n?null:{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:i,sharedTokens:Zs(r),sharedComponents:_r(r,"component:"),sharedNativeTags:_r(r,"native:"),sharedProps:_r(r,"prop:"),sharedEvents:_r(r,"event:"),sharedBindings:_r(r,"binding:"),uniqueToA:Zs(ue(e.tokens,t.tokens)).slice(0,25),uniqueToB:Zs(ue(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function Dv(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 t>=1||n>=4}function _r(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function Zs(e){return[...e].sort()}function cn(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a}=t,c=Pn(e,{scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(l=>({file:l.file,component:l.name,tokens:l.behaviorTokens,profile:l}));return nt({profiles:c,limit:i,filePattern:a,compare:(l,u)=>kv(l,u,n,r),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.componentA.localeCompare(u.componentA)||l.fileB.localeCompare(u.fileB)||l.componentB.localeCompare(u.componentB)})}function kv(e,t,n,r){let i=Ce(e.tokens,t.tokens);if(i.size<r||!Nv(i))return null;let o=wv(e.tokens,t.tokens);if(o<n)return null;let s=an(i,"hook:"),a=an(i,"react-hook:"),c=an(i,"effect:"),l=an(i,"state:"),u=an(i,"request:"),d=an(i,"handler:"),m=an(i,"handler-verb:");return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:o,sharedTokens:ea(i),sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m,uniqueToA:ea(ue(e.tokens,t.tokens)).slice(0,25),uniqueToB:ea(ue(t.tokens,e.tokens)).slice(0,25),reason:Pv({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m}),locA:e.profile.loc,locB:t.profile.loc}}function wv(e,t){if(e.size===0||t.size===0)return 0;let r=Ce(e,t).size/Math.min(e.size,t.size);return Math.max(tt(e,t),r)}function Nv(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 i>=1&&l>=4||t>=1&&(i>=1||s>=1||o>=2)&&l>=5||s>=1&&o>=2&&(r>=1||n>=2)&&l>=5}function Pv(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"}function an(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function ea(e){return[...e].sort()}function Er(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 Pn(e,{scope:a,scanLimit:c}).filter(d=>d.kind==="component").filter(d=>!l||d.file.includes(l)||d.name.includes(l)).map(d=>_v(d,{minComponentLines:n,minFileLines:r,minJsxTokens:i,minBehaviorTokens:o})).filter(d=>d!==null).sort((d,m)=>m.componentLines-d.componentLines||m.fileLines-d.fileLines||d.file.localeCompare(m.file)).slice(0,s)}function _v(e,t){let n=[];e.loc>=t.minComponentLines&&n.push(`${e.loc} component line(s)`);let r=Math.max(80,Math.floor(t.minComponentLines/2));return e.fileLines>=t.minFileLines&&e.loc>=r&&n.push(`${e.fileLines} file line(s)`),e.jsxTokens.size>=t.minJsxTokens&&n.push(`${e.jsxTokens.size} JSX structure token(s)`),e.behaviorTokens.size>=t.minBehaviorTokens&&n.push(`${e.behaviorTokens.size} behavior token(s)`),n.length===0?null:{file:e.file,component:e.name,componentLines:e.loc,fileLines:e.fileLines,jsxTokens:e.jsxTokens.size,behaviorTokens:e.behaviorTokens.size,dominantPressure:Ev(e),reasons:n,loc:e.loc}}function Ev(e){let t=[{axis:"component",value:e.loc},{axis:"file",value:e.fileLines},{axis:"jsx-structure",value:e.jsxTokens.size*3},{axis:"hook-behavior",value:e.behaviorTokens.size*4}];return t.sort((n,r)=>r.value-n.value),t[0]?.axis??"component"}function ln(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a}=t,c=Fv(e,{scope:o,minTokens:r,scanLimit:s});return nt({profiles:c,limit:i,filePattern:a,compare:(l,u)=>Av(l,u,n),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.fileB.localeCompare(u.fileB)})}function Fv(e,t){return Nn(e,{scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:Tv(n)}))}function Tv(e){return e.totalLines}function Av(e,t,n){let r=Ce(e.tokens,t.tokens);if(r.size<6||!$v(r))return null;let i=tt(e.tokens,t.tokens);return i<n?null:{fileA:e.file,fileB:t.file,similarity:i,sharedTokens:ta(r),sharedComponents:zn(r,"component:"),sharedProps:zn(r,"prop:"),sharedEvents:zn(r,"event:"),sharedDirectives:zn(r,"directive:"),sharedSlots:zn(r,"slot:"),sharedIdentifiers:zn(r,"id:"),uniqueToA:ta(ue(e.tokens,t.tokens)).slice(0,25),uniqueToB:ta(ue(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function $v(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 t>=1||n>=3}function zn(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function ta(e){return[...e].sort()}function un(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a}=t,c=Nn(e,{scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(l=>({file:l.file,tokens:l.behaviorTokens,profile:l}));return nt({profiles:c,limit:i,filePattern:a,compare:(l,u)=>Mv(l,u,n,r),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.fileB.localeCompare(u.fileB)})}function Mv(e,t,n,r){let i=Ce(e.tokens,t.tokens);if(i.size<r||!jv(i))return null;let o=Ov(e.tokens,t.tokens);if(o<n)return null;let s=yt(i,"composable:"),a=yt(i,"store:"),c=yt(i,"reactivity:"),l=yt(i,"lifecycle:"),u=yt(i,"request:"),d=yt(i,"function:"),m=yt(i,"function-verb:"),f=yt(i,"template-binding:"),g=yt(i,"template-event:");return{fileA:e.file,fileB:t.file,similarity:o,sharedTokens:na(i),sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f,sharedTemplateEvents:g,uniqueToA:na(ue(e.tokens,t.tokens)).slice(0,25),uniqueToB:na(ue(t.tokens,e.tokens)).slice(0,25),reason:Bv({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:l,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function Ov(e,t){if(e.size===0||t.size===0)return 0;let r=Ce(e,t).size/Math.min(e.size,t.size);return Math.max(tt(e,t),r)}function jv(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 r>=1&&l>=4||i>=1&&o>=2&&l>=4||c>=2&&(r>=1||o>=2)&&l>=5||o>=2&&s>=1&&l>=4}function Bv(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"}function yt(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function na(e){return[...e].sort()}function Fr(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 Nn(e,{scope:a,scanLimit:c}).filter(d=>!l||d.file.includes(l)).map(d=>Vv(d,{minTotalLines:n,minTemplateLines:r,minScriptLines:i,minStyleLines:o})).filter(d=>d!==null).sort((d,m)=>m.totalLines-d.totalLines||d.file.localeCompare(m.file)).slice(0,s)}function Vv(e,t){let n=[];return e.totalLines>=t.minTotalLines&&n.push(`${e.totalLines} total component line(s)`),e.templateLines>=t.minTemplateLines&&n.push(`${e.templateLines} template line(s)`),e.scriptLines>=t.minScriptLines&&n.push(`${e.scriptLines} script line(s)`),e.styleLines>=t.minStyleLines&&n.push(`${e.styleLines} style line(s)`),n.length===0?null:{file:e.file,totalLines:e.totalLines,sfcLines:e.sfcLines,templateLines:e.templateLines,scriptLines:e.scriptLines,styleLines:e.styleLines,externalScriptLines:e.externalScriptLines,externalScriptPaths:e.externalScriptPaths,customBlockLines:e.customBlockLines,dominantPressure:Hv(e),reasons:n,loc:e.totalLines}}function Hv(e){let t=[{axis:"template",lines:e.templateLines},{axis:"script",lines:e.scriptLines-e.externalScriptLines},{axis:"style",lines:e.styleLines},{axis:"external-script",lines:e.externalScriptLines},{axis:"custom-block",lines:e.customBlockLines}];return t.sort((n,r)=>r.lines-n.lines),t[0]?.lines?t[0].axis:"total"}function ra(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:o=3,maxChainLength:s=8}=t,a=ne(e,i),c=Qv(a,o,s);if(c.length===0)return[];let l=qv(c);return l.length<2?[]:Kv(Jv(l,n,r),r)}function qv(e){let t=Wv(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 Wv(e){let{nodeFreq:t,tailFreq:n}=Uv(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 Uv(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 Jv(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let o=i+1;o<e.length;o++){let s=Gv(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 Gv(e,t,n){if(!zv(e.filtered,t.filtered))return null;let{distance:r,ops:i}=Xv(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:Yv(e.original,t.original),commonSuffix:Zv(e.original,t.original)}}function zv(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function Kv(e,t){let n=[];for(let r of e)if(n.some(o=>gd(r.chainA,o.chainA)&&gd(r.chainB,o.chainB))||n.push(r),n.length>=t)break;return n}function Qv(e,t,n){let r=[];for(let o of e.keys()){if(r.length>=500)break;hd(e,o,[o],new Set([o]),t,n,r,500)}return r}function hd(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),hd(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 Xv(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 Yv(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 Zv(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 gd(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),r=e.join("\u2192");return n.includes(r)}function Ve(e){let t=e.orderCandidates?[...e.candidates()].sort(e.orderCandidates):e.candidates(),n=Be(t,e.scanLimit),r=e.prepare?.(n)??void 0,i=[];for(let o of n){let s=e.evaluate(o,r);s&&i.push(s)}return e.orderResults&&i.sort(e.orderResults),typeof e.limit=="number"?i.slice(0,e.limit):i}function dn(e,t={}){let{scope:n,minLoc:r=10,minCallees:i=6,limit:o=20,scanLimit:s}=t,a=new N(e);return Ve({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:r,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:s,prepare:c=>a.calleeMap(c,{semantic:t.semantic!==!1}),evaluate:(c,l)=>eR(c,l.get(c.symbolId)??[],i),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function eR(e,t,n){let r=new Set(t.map(a=>a.symbol));if(r.size<n)return null;let i=tR(r,t),o=nR(r,i);if(o.length<2)return null;let s=rR(o,i);return s.length===0?null:{symbol:e.symbol,shortName:y(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:q(e),totalCallees:r.size,clusters:s}}function tR(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 nR(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 rR(e,t){return e.filter(n=>n.size>=3).map(n=>iR(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function iR(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(y),isolation:s}}function Tr(e,t,n={}){let{maxDepth:r=5,scope:i}=n,o=B(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=[];for(let m of l)for(let f of oR(e,m,i)){let g=`${f.file}|${f.shortName}`;if(f.symbolId!==null){if(a.has(f.symbolId))continue;a.add(f.symbolId)}else if(c.has(g))continue;c.add(g),s.push({symbol:f.symbol,shortName:f.shortName,file:f.file,depth:u}),f.symbolId!==null&&f.symbolMatch&&d.push(f.symbolMatch)}l=d}return s.sort((u,d)=>u.depth-d.depth||u.file.localeCompare(d.file)),s}function oR(e,t,n){let r=je(e,t,{limit:500}).filter(l=>!e.isIgnored(l.file)).filter(l=>!n||l.file.includes(n)),i=new Set(r.map(l=>l.file)),o=[];for(let l of sR(e,t,n)){if(i.has(l))continue;let u=J(e,l),d=u.length>0?Ae(u,u[0].startLine):null;o.push({symbol:d?.symbol??l,file:l})}let s=[...r,...o],a=[],c=new Set;for(let l of s){let u=$n(e,l.symbol);if(!u){let m=`${l.file}|${l.symbol}`;if(c.has(m))continue;c.add(m),a.push({symbolId:null,symbol:l.symbol,shortName:y(l.symbol),file:l.file,symbolMatch:null});continue}if(u.symbolId===t.symbolId||e.isIgnored(u.relativePath)||!aR(u.symbol))continue;let d=`${u.symbolId}|${u.relativePath}`;c.has(d)||(c.add(d),a.push({symbolId:u.symbolId,symbol:u.symbol,shortName:y(u.symbol),file:u.relativePath,symbolMatch:u}))}return a}function sR(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
496
462
  FROM mentions m
497
463
  JOIN chunks c ON m.chunk_id = c.id
498
464
  JOIN documents consumer_d ON consumer_d.id = c.document_id
@@ -500,40 +466,44 @@ ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,e
500
466
  AND m.role != 1
501
467
  AND c.document_id != ?
502
468
  ${e.pathExclusionsFor("consumer_d")}
503
- ${r}`,...i).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function _b(e){let t=te(e);return t==="method"||t==="type"||e.endsWith("().")}function Qn(e,t,n={}){let r=pe(e,t);if(!r)return null;let i=Lb(e,r);if(!i||e.isIgnored(i.relative_path))return null;let o=[],s=0,a=wb(e,i.relative_path),c=n.semantic===!1?new Map:pn(e,a);for(let l of a){let u=kb(e,i,l,c.get(l.symbolId)??new Set);s+=u,o.push({symbol:l.symbol,shortName:b(l.symbol),startLine:l.startLine,endLine:l.endLine,externalConsumers:u,riskLevel:Eb(u)})}return{file:i.relative_path,symbols:o,totalExternalConsumers:s}}function Lb(e,t){return e.get(`SELECT id, relative_path FROM documents
469
+ ${r}`,...i).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function aR(e){let t=ae(e);return t==="method"||t==="type"||e.endsWith("().")}function Ar(e,t,n={}){let r=Ie(e,t);if(!r)return null;let i=cR(e,r);if(!i||e.isIgnored(i.relative_path))return null;let o=[],s=0,a=lR(e,i.relative_path),c=n.semantic===!1?new Map:Un(e,a);for(let l of a){let u=uR(e,i,l,c.get(l.symbolId)??new Set);s+=u,o.push({symbol:l.symbol,shortName:y(l.symbol),startLine:l.startLine,endLine:l.endLine,externalConsumers:u,riskLevel:dR(u)})}return{file:i.relative_path,symbols:o,totalExternalConsumers:s}}function cR(e,t){return e.get(`SELECT id, relative_path FROM documents
504
470
  WHERE relative_path = ?
505
471
  ${e.pathExclusionsFor("documents")}
506
- LIMIT 1`,t)??null}function wb(e,t){return new _(e).definitionsForFile(t).sort((n,r)=>n.startLine-r.startLine||n.endLine-r.endLine)}function kb(e,t,n,r){let i=e.all(`SELECT DISTINCT consumer_d.relative_path
472
+ LIMIT 1`,t)??null}function lR(e,t){return new N(e).definitionsForFile(t).sort((n,r)=>n.startLine-r.startLine||n.endLine-r.endLine)}function uR(e,t,n,r){let i=e.all(`SELECT DISTINCT consumer_d.relative_path
507
473
  FROM mentions m
508
474
  JOIN chunks c ON m.chunk_id = c.id
509
475
  JOIN documents consumer_d ON consumer_d.id = c.document_id
510
476
  WHERE m.symbol_id = ?
511
477
  AND m.role != 1
512
- 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 Eb(e){return e>10?"high":e>0?"medium":"low"}function Uo(e,t={}){let{scope:n,minLoc:r=1,maxDepth:i=5,scanLimit:o}=t,s=new _(e),a=Pb(e,n,r,o),c=new Wo;for(let f of a)c.add(f);let l=[],u=[];a.length>0&&l.push(wl(e,0,a,c));let m=a.map(f=>f.definition).filter(f=>f!==null),d=new Set(a.map(f=>f.symbol));for(let f=1;f<=i&&m.length>0;f++){let y=s.calleeMap(m,{semantic:!1}),R=new Set;for(let S of m)for(let x of y.get(S.symbolId)??[])d.has(x.symbol)||R.add(x.symbol);let k=[];for(let S of R){d.add(S);let x=kl(e,S);if(!x||e.isIgnored(x.relativePath)||ue(e,x.relativePath)||re(e,x.symbol,x.relativePath)||s.fileKind(x.relativePath)==="test"||s.hasSuppressionComment(x))continue;let D=Ab(e,x,c);D.removable?k.push(Fb(x,"cascade")):D.blockingFiles.length>0&&u.push({shortName:b(x.symbol),file:x.relativePath,blockingFiles:D.blockingFiles.slice(0,3)})}if(k.length===0)break;for(let S of k)c.add(S);l.push(wl(e,f,k,c)),m=k.map(S=>S.definition).filter(S=>S!==null)}let p=l.reduce((f,y)=>f+y.loc,0),h=l.reduce((f,y)=>f+y.entries.length,0);return{batches:l,totalSymbols:h,totalLoc:p,blocked:u}}function Pb(e,t,n,r){let i=Ye(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:r,semantic:!1}),o=[];for(let s of i.symbols)s.kind==="dead-code"&&(ue(e,s.relativePath)||re(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:kl(e,s.symbol)}));return o}function Fb(e,t){return{symbol:e.symbol,shortName:b(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function kl(e,t){let n=e.get(`SELECT d.relative_path
478
+ 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 dR(e){return e>10?"high":e>0?"medium":"low"}function zi(e,t={}){let{scope:n,minLoc:r=1,maxDepth:i=5,scanLimit:o}=t,s=new N(e),a=mR(e,n,r,o),c=new ia;for(let h of a)c.add(h);let l=[],u=[];a.length>0&&l.push(bd(e,0,a,c));let d=a.map(h=>h.definition).filter(h=>h!==null),m=new Set(a.map(h=>h.symbol));for(let h=1;h<=i&&d.length>0;h++){let b=s.calleeMap(d,{semantic:!1}),L=new Set;for(let k of d)for(let E of b.get(k.symbolId)??[])m.has(E.symbol)||L.add(E.symbol);let F=[];for(let k of L){m.add(k);let E=yd(e,k);if(!E||e.isIgnored(E.relativePath)||xe(e,E.relativePath)||le(e,E.symbol,E.relativePath)||s.fileKind(E.relativePath)==="test"||s.hasSuppressionComment(E))continue;let C=fR(e,E,c);C.removable?F.push(pR(E,"cascade")):C.blockingFiles.length>0&&u.push({shortName:y(E.symbol),file:E.relativePath,blockingFiles:C.blockingFiles.slice(0,3)})}if(F.length===0)break;for(let k of F)c.add(k);l.push(bd(e,h,F,c)),d=F.map(k=>k.definition).filter(k=>k!==null)}let f=l.reduce((h,b)=>h+b.loc,0),g=l.reduce((h,b)=>h+b.entries.length,0);return{batches:l,totalSymbols:g,totalLoc:f,blocked:u}}function mR(e,t,n,r){let i=ht(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:r,semantic:!1}),o=[];for(let s of i.symbols)s.kind==="dead-code"&&(xe(e,s.relativePath)||le(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:yd(e,s.symbol)}));return o}function pR(e,t){return{symbol:e.symbol,shortName:y(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function yd(e,t){let n=e.get(`SELECT d.relative_path
513
479
  FROM global_symbols gs
514
480
  JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
515
481
  JOIN documents d ON d.id = der.document_id
516
482
  WHERE gs.symbol = ?
517
- LIMIT 1`,t);return n?V(e,n.relative_path).find(r=>r.symbol===t)??null:null}function Ab(e,t,n){let r=Ft(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 wl(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=V(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 Wo=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{existsSync as Jl}from"fs";import{execFileSync as Tb}from"child_process";var Pl=2e3,Mb=50,Ob=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i;function Go(e){let t=de(e,{clearGroups:["whole-project"]});return(n,r)=>{let i=jb(n.config.projectRoot);if(!i)return null;let o=t.has(n)?t.get(n,()=>({head:"",value:null})):null;return o&&o.head===i?o.value:(t.invalidate(n),t.get(n,()=>({head:i,value:r(n.config.projectRoot,i)})).value)}}var $b=Go("git-commit-history");function Ot(e){return $b(e,Bb)}function jb(e){try{return Yr(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function Yr(e,t){return Tb("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]})}function Bb(e,t){let n;try{n=Yr(e,["log","--no-merges","--name-only","-n",String(Pl),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let r=[],i=0;for(let o of n.split("")){if(o.trim()==="")continue;let s=o.indexOf(`
518
- `),a=s>=0?o.slice(0,s):o,[c,l,u]=a.split("\0");if(!c||!l)continue;let m=s>=0?o.slice(s+1).split(`
519
- `).map(d=>d.trim()).filter(d=>d!==""):[];if(m.length>Mb){i+=1;continue}r.push({hash:c,timestamp:Number(l)||0,subject:u??"",files:m})}return{head:t,commits:r,skippedBulkCommits:i}}function Hb(e){return Ob.test(e.subject)}function Xr(e){let t=Ot(e);if(!t)return null;let n=new Map;for(let r of t.commits){let i=Hb(r);for(let o of r.files){let s=n.get(o)??{changes:0,fixChanges:0,lastChangedAt:0};s.changes+=1,i&&(s.fixChanges+=1),r.timestamp>s.lastChangedAt&&(s.lastChangedAt=r.timestamp),n.set(o,s)}}return n}function Fl(e){let t=Ot(e);if(!t||t.commits.length===0)return null;let n=t.commits.map(r=>r.files.length).filter(r=>r>0).sort((r,i)=>r-i);return n.length===0?null:{medianFilesPerCommit:El(n,.5),p90FilesPerCommit:El(n,.9),commitsAnalyzed:n.length}}function El(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var qb=Go("git-tracked-files");function Jo(e){return qb(e,t=>{try{let n=Yr(t,["ls-files"]);return new Set(n.split(`
520
- `).map(r=>r.trim()).filter(r=>r!==""))}catch{return null}})}var Vb=Go("git-file-adds");function Al(e){return Vb(e,t=>Wb(t))}function Wb(e){let t;try{t=Yr(e,["log","--no-merges","--diff-filter=A","--name-only","-n",String(Pl),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let n=new Map,r=-1;for(let i of t.split("")){if(i.trim()==="")continue;r+=1;let o=i.indexOf(`
483
+ LIMIT 1`,t);return n?J(e,n.relative_path).find(r=>r.symbol===t)??null:null}function fR(e,t,n){let r=nn(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 bd(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=J(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 ia=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 xI}from"crypto";import{existsSync as Hd}from"fs";import{execFileSync as gR}from"child_process";var xd=2e3,Cd=50,hR=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i;function oa(e){let t=ie(e,{clearGroups:["whole-project"]});return(n,r)=>{let i=yR(n.config.projectRoot);if(!i)return null;let o=t.has(n)?t.get(n,()=>({head:"",value:null})):null;return o&&o.head===i?o.value:(t.invalidate(n),t.get(n,()=>({head:i,value:r(n.config.projectRoot,i)})).value)}}var bR=oa("git-commit-history");function mn(e){return bR(e,SR)}function yR(e){try{return Ki(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function Ki(e,t){return gR("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]})}function SR(e,t){let n;try{n=Ki(e,["log","--no-merges","--name-only","-n",String(xd),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let r=[],i=0;for(let o of n.split("")){if(o.trim()==="")continue;let s=o.indexOf(`
484
+ `),a=s>=0?o.slice(0,s):o,[c,l,u]=a.split("\0");if(!c||!l)continue;let d=s>=0?o.slice(s+1).split(`
485
+ `).map(m=>m.trim()).filter(m=>m!==""):[];if(d.length>Cd){i+=1;continue}r.push({hash:c,timestamp:Number(l)||0,subject:u??"",files:d})}return{head:t,commits:r,skippedBulkCommits:i}}function xR(e){return hR.test(e.subject)}function Qi(e){let t=mn(e);if(!t)return null;let n=new Map;for(let r of t.commits){let i=xR(r);for(let o of r.files){let s=n.get(o)??{changes:0,fixChanges:0,lastChangedAt:0};s.changes+=1,i&&(s.fixChanges+=1),r.timestamp>s.lastChangedAt&&(s.lastChangedAt=r.timestamp),n.set(o,s)}}return n}function vd(e){let t=mn(e);if(!t||t.commits.length===0)return null;let n=t.commits.map(r=>r.files.length).filter(r=>r>0).sort((r,i)=>r-i);return n.length===0?null:{medianFilesPerCommit:Sd(n,.5),p90FilesPerCommit:Sd(n,.9),commitsAnalyzed:n.length}}function Sd(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var CR=oa("git-tracked-files");function sa(e){return CR(e,t=>{try{let n=Ki(t,["ls-files"]);return new Set(n.split(`
486
+ `).map(r=>r.trim()).filter(r=>r!==""))}catch{return null}})}var vR=oa("git-file-adds");function Rd(e){return vR(e,t=>RR(t))}function RR(e){let t;try{t=Ki(e,["log","--no-merges","--diff-filter=A","--name-only","-n",String(xd),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let n=new Map,r=-1;for(let i of t.split("")){if(i.trim()==="")continue;r+=1;let o=i.indexOf(`
521
487
  `),s=o>=0?i.slice(0,o):i,[,a]=s.split("\0"),c=Number(a)||0;if(!(o<0))for(let l of i.slice(o+1).split(`
522
- `)){let u=l.trim();u!==""&&n.set(u,{commitsAgo:r,addedAt:c})}}return n}function Zr(e,t={}){let{minTogether:n=4,minConfidence:r=.6}=t,i=Ot(e);if(!i)return null;let o=new Map,s=new Map;for(let c of i.commits){let l=[...new Set(c.files)].sort();for(let u of l)o.set(u,(o.get(u)??0)+1);for(let u=0;u<l.length;u++)for(let m=u+1;m<l.length;m++){let d=`${l[u]}\0${l[m]}`;s.set(d,(s.get(d)??0)+1)}}let a=[];for(let[c,l]of s){if(l<n)continue;let[u,m]=c.split("\0"),d=o.get(u)??l,p=o.get(m)??l,h=Math.max(l/d,l/p);h<r||a.push({fileA:u,fileB:m,together:l,confidence:h,changesA:d,changesB:p})}return a.sort((c,l)=>l.together-c.together||l.confidence-c.confidence||c.fileA.localeCompare(l.fileA)),a}import{existsSync as Ub}from"fs";import{join as Gb}from"path";function Ko(e){return zo.test(e)}var zo=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|CHANGELOG(?:\.[a-z]+)?|.*\.map)$|(?:^|\/)(?:dist|build|out|node_modules)\//i;function $t(e,t,n={}){let{minTogether:r=4,minConfidence:i=.6,limit:o=30}=n,s=Ot(e),a=t!==void 0,c=Zr(e,{minTogether:a?Math.min(r,2):r,minConfidence:a?0:i});if(!s||!c)return{available:!1,commitsAnalyzed:0,findings:[]};let l=se(e),u=n.includeLinked===!0||a,m=[];for(let d of c){if(zo.test(d.fileA)||zo.test(d.fileB)||!Tl(e,d.fileA)||!Tl(e,d.fileB)||a&&!d.fileA.includes(t)&&!d.fileB.includes(t)||!a&&(G(d.fileA)==="test"||G(d.fileB)==="test"||Jb(d.fileA,d.fileB)))continue;let p=zb(l,d.fileA,d.fileB);if(!(!u&&p)&&(m.push({...d,structurallyLinked:p}),m.length>=o))break}return{available:!0,commitsAnalyzed:s.commits.length,findings:m}}function Tl(e,t){return Ub(Gb(e.config.projectRoot,t))}function Jb(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 zb(e,t,n){return e.get(t)?.has(n)===!0||e.get(n)?.has(t)===!0}import{execFileSync as Qo}from"child_process";var Yo="Unable to compute git diff.";function hn(e,t={}){let n=ht(e,t);return n.note?Kb(n.note,n.changedFileLines):n.changedFiles.length===0?Qb(n.changedFileLines):ti(n.changedFiles,[ei(e,n.changedFiles,n.changedFiles)])}function ht(e,t={}){let{base:n="HEAD"}=t;try{let r=Yb(e.config.projectRoot,n);return{changedFileLines:r,changedFiles:Xb(e,r),note:r.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],note:Yo}}}function ei(e,t,n){let r=new _(e),i=new Set(n),o=[],s=new Map,a=t.flatMap(l=>r.definitionsForFile(l)).filter(rS).sort((l,u)=>l.relativePath.localeCompare(u.relativePath)||l.startLine-u.startLine),c=pn(e,a);for(let l of a)Zb(e,l,n,i,o,s,c.get(l.symbolId)??new Set);return{changedSymbols:o,consumerEntries:[...s.entries()].map(([l,u])=>({file:l,symbols:[...u].sort()}))}}function ti(e,t){let n=new Map,r=t.flatMap(o=>o.changedSymbols);for(let o of t)for(let s of o.consumerEntries){let a=n.get(s.file);a||(a=new Set,n.set(s.file,a));for(let c of s.symbols)a.add(c)}let i=nS(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:i,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:i.length}}}function Kb(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function Qb(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function Yb(e,t){let n=Qo("git",["diff","--name-only",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=Qo("git",["diff","--name-only","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=Qo("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([n,r,i].flatMap(o=>o.split(`
523
- `)).map(o=>o.trim()).filter(o=>o.length>0))]}function Xb(e,t){let n=[];for(let r of t){let i=e.get(`SELECT relative_path FROM documents
524
- WHERE relative_path LIKE ?
525
- LIMIT 1`,`%${r}`);i&&!e.isIgnored(i.relative_path)&&n.push(i.relative_path)}return n}function Zb(e,t,n,r,i,o,s){let a=Math.max(eS(e,t.symbolId),s.size);if(!iS(t,a))return;let c=b(t.symbol);i.push({symbol:t.symbol,shortName:c,file:t.relativePath,fanIn:a});for(let l of tS(e,t.symbolId,n))Ml(e,r,o,l,c);for(let l of s)Ml(e,r,o,l,c)}function eS(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS fan_in
488
+ `)){let u=l.trim();u!==""&&n.set(u,{commitsAgo:r,addedAt:c})}}return n}function Xi(e,t={}){let{minTogether:n=4,minConfidence:r=.6,maxFilesPerCommit:i=Cd}=t,o=mn(e);if(!o)return null;let s=new Map,a=new Map;for(let l of o.commits){let u=[...new Set(l.files)].sort();if(!(u.length>i)){for(let d of u)s.set(d,(s.get(d)??0)+1);for(let d=0;d<u.length;d++)for(let m=d+1;m<u.length;m++){let f=`${u[d]}\0${u[m]}`;a.set(f,(a.get(f)??0)+1)}}}let c=[];for(let[l,u]of a){if(u<n)continue;let[d,m]=l.split("\0"),f=s.get(d)??u,g=s.get(m)??u,h=Math.max(u/f,u/g);h<r||c.push({fileA:d,fileB:m,together:u,confidence:h,changesA:f,changesB:g})}return c.sort((l,u)=>u.together-l.together||u.confidence-l.confidence||l.fileA.localeCompare(u.fileA)),c}import{existsSync as LR}from"fs";import{join as IR}from"path";function ca(e){return aa.test(e)}var aa=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|CHANGELOG(?:\.[a-z]+)?|.*\.map)$|(?:^|\/)(?:dist|build|out|node_modules|docs\/plans)\//i;function pn(e,t,n={}){let{minTogether:r=4,minConfidence:i=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=mn(e),c=t!==void 0,l=Xi(e,{minTogether:c?Math.min(r,2):r,minConfidence:c?0:i,maxFilesPerCommit:s});if(!a||!l)return{available:!1,commitsAnalyzed:0,findings:[]};let u=ne(e),d=kR(e),m=n.includeLinked===!0||c,f=[];for(let g of l){if(aa.test(g.fileA)||aa.test(g.fileB)||!Ld(e,g.fileA)||!Ld(e,g.fileB)||c&&!g.fileA.includes(t)&&!g.fileB.includes(t)||!c&&(z(g.fileA)==="test"||z(g.fileB)==="test"||DR(g.fileA,g.fileB)))continue;let h=wR(u,d,g.fileA,g.fileB);if(!(!m&&h)&&(f.push({...g,structurallyLinked:h}),f.length>=o))break}return{available:!0,commitsAnalyzed:a.commits.length,findings:f}}function Ld(e,t){return LR(IR(e.config.projectRoot,t))}function DR(e,t){let n=e.lastIndexOf("/"),r=t.lastIndexOf("/");if(e.slice(0,n)!==t.slice(0,r))return!1;let i=e.slice(n+1).split(".")[0],o=t.slice(r+1).split(".")[0];return i!==""&&i===o}function kR(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function wR(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))}import{execFileSync as rt}from"child_process";import{existsSync as NR,readFileSync as PR}from"fs";import{basename as Id}from"path";var la="Unable to compute git diff.";function Kn(e,t={}){let n=t.plan??it(e,t);return n.note?_R(n.note,n.changedFileLines):n.changedFiles.length===0?ER(n.changedFileLines):Zi(n.changedFiles,[Yi(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function it(e,t={}){let{base:n="HEAD"}=t;try{let r=FR(e.config.projectRoot,n),i=jR(e,r),o=BR(e,TR(e.config.projectRoot,n));return{changedFileLines:r,changedFiles:i,changedRanges:o,renamedFiles:AR(e.config.projectRoot,n,i),note:r.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:la}}}function Yi(e,t,n,r=[]){let i=new N(e),o=new Set(n),s=HR(r),a=[],c=new Map,l=t.flatMap(g=>i.definitionsForFile(g)).filter(KR).filter(g=>qR(g,s)).sort((g,h)=>g.relativePath.localeCompare(h.relativePath)||g.startLine-h.startLine),u=l.map(g=>g.symbolId),d=JR(e,u),m=GR(e,u,n),f=Un(e,l.filter(g=>d.get(g.symbolId)===0));for(let g of l)UR(e,g,o,a,c,f.get(g.symbolId)??new Set,d.get(g.symbolId)??0,m.get(g.symbolId)??new Set);return{changedSymbols:a,consumerEntries:[...c.entries()].map(([g,h])=>({file:g,symbols:[...h].sort()}))}}function Zi(e,t){let n=new Map,r=t.flatMap(o=>o.changedSymbols);for(let o of t)for(let s of o.consumerEntries){let a=n.get(s.file);a||(a=new Set,n.set(s.file,a));for(let c of s.symbols)a.add(c)}let i=zR(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:i,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:i.length}}}function _R(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function ER(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function FR(e,t){let n=rt("git",["diff","--name-only",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=rt("git",["diff","--name-only","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=rt("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([n,r,i].flatMap(o=>o.split(`
489
+ `)).map(o=>o.trim()).filter(o=>o.length>0))]}function TR(e,t){let n=rt("git",["diff","--unified=0",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=rt("git",["diff","--unified=0","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return _d([...wd(n),...wd(r)])}function $r(e,t,n){try{return rt("git",["show",`${t}:./${n}`],{encoding:"utf-8",cwd:e,timeout:1e4,stdio:["ignore","pipe","ignore"]})}catch{return null}}function AR(e,t,n){let r=$R(e,t);if(r.length===0||n.length===0)return[];let i=new Map,o=new Set;for(let s of MR(e,t))n.includes(s.to)&&(i.set(s.to,s),o.add(s.from));for(let s of n){if(i.has(s)||!NR(`${e}/${s}`))continue;let a=r.filter(u=>!o.has(u)).filter(u=>Id(u)===Id(s));if(a.length===0)continue;let c=PR(`${e}/${s}`,"utf-8"),l=a.map(u=>({from:u,to:s,similarity:OR($r(e,t,u)??"",c)})).sort((u,d)=>d.similarity-u.similarity)[0];l&&l.similarity>=.45&&(i.set(s,l),o.add(l.from))}return[...i.values()].sort((s,a)=>s.to.localeCompare(a.to))}function $R(e,t){let n=rt("git",["diff","--name-only","--diff-filter=D",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=rt("git",["diff","--name-only","--diff-filter=D","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([...kd(n),...kd(r)])]}function MR(e,t){let n=rt("git",["diff","--name-status","--find-renames",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=rt("git",["diff","--name-status","--find-renames","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return[...n.split(`
490
+ `),...r.split(`
491
+ `)].map(i=>i.trim()).filter(i=>i.startsWith("R")).map(i=>i.split(" ")).filter(i=>i.length>=3).map(([i,o,s])=>({from:o,to:s,similarity:Number(i.slice(1))/100}))}function OR(e,t){let n=new Set(Dd(e)),r=new Set(Dd(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 Dd(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function kd(e){return e.split(`
492
+ `).map(t=>t.trim()).filter(t=>t.length>0)}function jR(e,t){let n=Pd(e),r=[];for(let i of t){let o=n(i);o&&!e.isIgnored(o)&&r.push(o)}return r}function BR(e,t){let n=Pd(e),r=[];for(let i of t){let o=n(i.file);o&&!e.isIgnored(o)&&r.push({...i,file:o})}return _d(r)}function Pd(e){let t=e.all(`SELECT relative_path FROM documents
493
+ 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 wd(e){let t=[],n=null;for(let r of e.split(`
494
+ `)){if(r.startsWith("+++ ")){n=VR(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 VR(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function _d(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 HR(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}function qR(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(r=>WR(e.startLine,e.endLine,r.startLine,r.endLine))}function WR(e,t,n,r){return e<=r&&n<=t}function UR(e,t,n,r,i,o,s,a){let c=Math.max(s,o.size);if(!QR(t,c))return;let l=y(t.symbol);r.push({symbol:t.symbol,shortName:l,file:t.relativePath,startLine:t.startLine,endLine:t.endLine,fanIn:c});for(let u of a)Nd(e,n,i,u,l);for(let u of o)Nd(e,n,i,u,l)}function JR(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
526
495
  FROM mentions m
527
496
  JOIN chunks c ON m.chunk_id = c.id
528
- WHERE m.symbol_id = ?
529
- AND m.role != 1`,t)?.fan_in??0}function tS(e,t,n){return n.length===0?[]:e.all(`SELECT DISTINCT ref_d.relative_path
497
+ WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
498
+ AND m.role != 1
499
+ GROUP BY m.symbol_id`,...t);return new Map(n.map(r=>[r.symbol_id,r.fan_in]))}function GR(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
530
500
  FROM mentions m
531
501
  JOIN chunks c ON m.chunk_id = c.id
532
502
  JOIN documents ref_d ON c.document_id = ref_d.id
533
- WHERE m.symbol_id = ?
503
+ WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
534
504
  AND m.role != 1
535
505
  AND ref_d.relative_path NOT IN (${n.map(()=>"?").join(",")})
536
- ${e.pathExclusionsFor("ref_d")}`,t,...n).map(i=>i.relative_path)}function Ml(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 nS(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function rS(e){return!(at(e.symbol)||e.parentTypeName!==null&&!oe(e.symbol))}function iS(e,t){return oe(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}import{existsSync as Ol,readFileSync as oS}from"fs";import{join as Xo}from"path";var Yn=/\.(?:md|mdx|rst|txt)$/i;function sS(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var aS=3,cS=/[A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6}\b/g;function Zo(e,t={}){let{doc:n,limit:r=20,minCoupling:i=aS}=t,o=Ot(e);if(!o)return{available:!1,commitsAnalyzed:0,docsScanned:0,findings:[]};let s=Jo(e)??new Set,a=new Map,c=new Map,l=new Set;for(let p of o.commits){let h=[...new Set(p.files)],f=h.filter(R=>Yn.test(R)),y=h.filter(R=>!Yn.test(R));for(let R of h){l.add(R);let k=a.get(R)??[];k.push(p.timestamp),a.set(R,k)}for(let R of f){let k=c.get(R);k||(k=new Map,c.set(R,k));for(let S of y)k.set(S,(k.get(S)??0)+1)}}let u=[...s].filter(p=>Yn.test(p)),m=Bl(s),d=[];for(let p of u){if(n!==void 0&&!p.includes(n)||n===void 0&&!jl(e,p)||n!==void 0&&!Ol(Xo(e.config.projectRoot,p)))continue;let h=Math.max(0,...a.get(p)??[]),f=new Map,{resolved:y,broken:R}=Hl(e,p,s,m,l);for(let S of y){if(S===p||Yn.test(S))continue;let x=(a.get(S)??[]).filter(D=>D>h).length;x!==0&&f.set(S,{file:S,evidence:"reference",coChanges:0,changesSinceDocUpdate:x})}for(let[S,x]of c.get(p)??[]){if(x<i||!s.has(S))continue;let D=(a.get(S)??[]).filter($=>$>h).length;if(D===0)continue;let w=f.get(S);w?(w.evidence="both",w.coChanges=x):f.set(S,{file:S,evidence:"co-change",coChanges:x,changesSinceDocUpdate:D})}if(f.size===0&&R.length===0)continue;let k=[...f.values()].sort((S,x)=>x.changesSinceDocUpdate-S.changesSinceDocUpdate);d.push({doc:p,docLastChangedAt:h,staleness:k.reduce((S,x)=>S+x.changesSinceDocUpdate,0)+R.length*10,subjects:k.slice(0,8),brokenReferences:R})}return d.sort((p,h)=>h.staleness-p.staleness),{available:!0,commitsAnalyzed:o.commits.length,docsScanned:u.length,findings:d.slice(0,r)}}function $l(e,t){let n=Jo(e)??new Set,r=Bl(n),i=[];for(let o of n){if(!jl(e,o))continue;let{resolved:s}=Hl(e,o,n,r,new Set),a=[...s].filter(c=>t.has(c));a.length>0&&i.push({doc:o,cited:a.sort()})}return i}function jl(e,t){return Yn.test(t)&&!sS(t)&&Ol(Xo(e.config.projectRoot,t))}function Bl(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 Hl(e,t,n,r,i){let o=new Set,s=new Set,a;try{a=oS(Xo(e.config.projectRoot,t),"utf-8")}catch{return{resolved:o,broken:[]}}for(let c of a.matchAll(cS)){let l=c[0].replace(/^\.?\//,"");if(n.has(l)){o.add(l);continue}let u=r.get(l);if(u&&u.length===1){o.add(u[0]);continue}u&&u.length>1||i.has(l)&&s.add(l)}return{resolved:o,broken:[...s]}}import{existsSync as ax,readFileSync as cx,writeFileSync as lx}from"fs";import{isAbsolute as ux,join as mx}from"path";var X={dead:{minLoc:3,skipBarrels:!0,deadCodeOnly:!0,semantic:!1},isolated:{minLoc:3,semantic:!1},similar:{minSimilarity:.6,limit:50,minCallees:4,semantic:!1},extract:{minLoc:15,minCallees:5,limit:50,semantic:!1},wrappers:{maxLoc:15,limit:50,semantic:!1},passthroughs:{maxLoc:15,limit:50,semantic:!1},stale:{minLoc:3,limit:50,semantic:!1},drift:{semantic:!1}};import Xn from"path";function jt(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 es(e,t){if(e===t)return"ok";let n=ni(e),r=ni(t);return n&&r?lS(n,r)?"ok":"violation":uS(e,t)}function ql(e,t){let n=ni(jt(e)),r=ni(jt(t));return!!n&&!!r}function ni(e){return/^src\/([^/]+)$/.exec(e)?.[1]??null}function lS(e,t){return t==="domain"?!0:e==="domain"?!1:{analysis:new Set(["domain","source","storage","symbols"]),core:new Set(["analysis","domain","resolution","source","storage","symbols"]),"language-parsers":new Set(["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(["domain","queries","reindex","resolution","semantic","source","storage","symbols"]),semantic:new Set(["domain","resolution","storage","symbols"]),source:new Set(["domain","storage"]),storage:new Set(["domain","source"]),symbols:new Set(["analysis","domain","language-parsers","resolution","semantic","source","storage"])}[e]?.has(t)??!1}function uS(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 Bt(e,t){let{scope:n,minDeviation:r=5}=t??{},i=t?.semantic!==!1,s=new _(e).fileDependencyGraph(n),a=yS(e,n);return fS([...mS(e,s,a,{semantic:i}),...dS(s),...pS(s,r)])}function mS(e,t,n,r){let i=[];for(let[o,s]of t){if(Ze(o))continue;let a=n.get(o)??new Set;for(let c of s)if(!Ze(c)&&!a.has(c)){if(r.semantic&&IS(e,o,c)||vS(e,o,c)||DS(e,o,c)||RS(c)||_S(e,o,c)||NS(c))continue;i.push({file:o,kind:"unused-import",description:`Depends on ${c} but references none of its symbols`,dep:c})}}return i}function dS(e){let t=[],n=CS(e);for(let[r,i]of e){if(Ze(r))continue;let o=jt(r);for(let s of i){if(Ze(s))continue;let a=jt(s);if(o===a)continue;(es(o,a)??n.get(`${o}->${a}`))==="violation"&&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}/`})}}return t}function pS(e,t){let n=[];for(let[r,i]of gS(e)){let o=i.filter(a=>!Ze(a));if(o.length<t)continue;let s=hS(e,o);for(let a of o)for(let c of e.get(a)??[])Ze(c)||(s.get(c)??0)===1&&Xn.dirname(c)!==r&&Xn.dirname(c)!==Xn.dirname(r)&&(ql(a,c)||n.push({file:a,kind:"pattern-deviation",description:`Only file in ${r}/ that depends on ${c}`,dep:c}))}return n}function fS(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 gS(e){let t=new Map;for(let n of e.keys()){let r=Xn.dirname(n),i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function hS(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])Ze(i)||n.set(i,(n.get(i)??0)+1);return n}function yS(e,t){let n=new Map;return bS(e,n,t),xS(e,n),n}function bS(e,t,n){for(let r of SS(e,n))Vl(e,t,r.from_file,r.to_file)}function SS(e,t){let n=t?`AND d1.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT d1.relative_path AS from_file, d2.relative_path AS to_file
506
+ ${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 Nd(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 zR(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function KR(e){return!(wt(e.symbol)||e.parentTypeName!==null&&!pe(e.symbol))}function QR(e,t){return pe(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}import{existsSync as Ed,readFileSync as XR}from"fs";import{join as ua}from"path";var Mr=/\.(?:md|mdx|rst|txt)$/i;function YR(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var ZR=3,eL=/[A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6}\b/g;function da(e,t={}){let{doc:n,limit:r=20,minCoupling:i=ZR}=t,o=tL(e);if(!o)return{available:!1,commitsAnalyzed:0,docsScanned:0,findings:[]};let s=[];for(let a of o.docFiles){if(n!==void 0&&!a.includes(n)||n===void 0&&!Td(e,a)||n!==void 0&&!Ed(ua(e.config.projectRoot,a)))continue;let c=Math.max(0,...o.changeTimes.get(a)??[]),l=new Map,{resolved:u,broken:d}=$d(e,a,o.tracked,o.trackedBySuffix,o.everSeenInHistory);for(let f of u){if(f===a||Mr.test(f))continue;let g=(o.changeTimes.get(f)??[]).filter(h=>h>c).length;g!==0&&l.set(f,{file:f,evidence:"reference",coChanges:0,changesSinceDocUpdate:g})}for(let[f,g]of o.coupling.get(a)??[]){if(g<i||!o.tracked.has(f))continue;let h=(o.changeTimes.get(f)??[]).filter(L=>L>c).length;if(h===0)continue;let b=l.get(f);b?(b.evidence="both",b.coChanges=g):l.set(f,{file:f,evidence:"co-change",coChanges:g,changesSinceDocUpdate:h})}if(l.size===0&&d.length===0)continue;let m=[...l.values()].sort((f,g)=>g.changesSinceDocUpdate-f.changesSinceDocUpdate);s.push({doc:a,docLastChangedAt:c,staleness:m.reduce((f,g)=>f+g.changesSinceDocUpdate,0)+d.length*10,subjects:m.slice(0,8),brokenReferences:d})}return s.sort((a,c)=>c.staleness-a.staleness),{available:!0,commitsAnalyzed:o.historyCommitCount,docsScanned:o.docFiles.length,findings:s.slice(0,r)}}function tL(e){let t=mn(e);if(!t)return null;let n=sa(e)??new Set,r=new Map,i=new Map,o=new Set;for(let s of t.commits){let a=[...new Set(s.files)],c=a.filter(u=>Mr.test(u)),l=a.filter(u=>!Mr.test(u));for(let u of a){o.add(u);let d=r.get(u)??[];d.push(s.timestamp),r.set(u,d)}for(let u of c){let d=i.get(u);d||(d=new Map,i.set(u,d));for(let m of l)d.set(m,(d.get(m)??0)+1)}}return{changeTimes:r,coupling:i,docFiles:[...n].filter(s=>Mr.test(s)),everSeenInHistory:o,historyCommitCount:t.commits.length,tracked:n,trackedBySuffix:Ad(n)}}function Fd(e,t){let n=sa(e)??new Set,r=Ad(n),i=[];for(let o of n){if(!Td(e,o))continue;let{resolved:s}=$d(e,o,n,r,new Set),a=[...s].filter(c=>t.has(c));a.length>0&&i.push({doc:o,cited:a.sort()})}return i}function Td(e,t){return Mr.test(t)&&!YR(t)&&Ed(ua(e.config.projectRoot,t))}function Ad(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 $d(e,t,n,r,i){let o=new Set,s=new Set,a=nL(e,t);if(!a)return{resolved:o,broken:[]};for(let c of a){if(n.has(c)){o.add(c);continue}let l=r.get(c);if(l&&l.length===1){o.add(l[0]);continue}l&&l.length>1||i.has(c)&&s.add(c)}return{resolved:o,broken:[...s]}}function nL(e,t){let n;try{n=XR(ua(e.config.projectRoot,t),"utf-8")}catch{return null}let r=Ht(e,t,n),i=li(e,"doc-path-tokens",t,r);if(i!==null)try{return JSON.parse(i)}catch{}let o=[...new Set([...n.matchAll(eL)].map(s=>s[0].replace(/^\.?\//,"")))];return ui(e,"doc-path-tokens",t,r,JSON.stringify(o)),o}import{existsSync as tI,readFileSync as nI,writeFileSync as rI}from"fs";import{isAbsolute as iI,join as oI}from"path";var re={dead:{minLoc:3,skipBarrels:!0,deadCodeOnly:!0,semantic:!1},isolated:{minLoc:3,semantic:!1},similar:{minSimilarity:.6,limit:50,minCallees:4,semantic:!1},extract:{minLoc:15,minCallees:5,limit:50,semantic:!1},wrappers:{maxLoc:15,limit:50,semantic:!1},passthroughs:{maxLoc:15,limit:50,semantic:!1},stale:{minLoc:3,limit:50,semantic:!1},drift:{semantic:!1}};import Or from"path";function fn(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 ma(e,t){if(e===t)return"ok";let n=eo(e),r=eo(t);return n&&r?rL(n,r)?"ok":"violation":iL(e,t)}function Md(e,t){let n=eo(fn(e)),r=eo(fn(t));return!!n&&!!r}function eo(e){return/^src\/([^/]+)$/.exec(e)?.[1]??null}function rL(e,t){return t==="domain"?!0:e==="domain"?!1:{analysis:new Set(["domain","source","storage","symbols"]),core:new Set(["analysis","domain","resolution","source","storage","symbols"]),"language-parsers":new Set(["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(["domain","queries","reindex","resolution","semantic","source","storage","symbols"]),semantic:new Set(["domain","resolution","storage","symbols"]),source:new Set(["domain","storage"]),storage:new Set(["domain","source"]),symbols:new Set(["analysis","domain","language-parsers","resolution","semantic","source","storage"])}[e]?.has(t)??!1}function iL(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 gn(e,t){let{scope:n,minDeviation:r=5}=t??{},i=t?.semantic!==!1,s=new N(e).fileDependencyGraph(n),a=dL(e,n);return cL([...oL(e,s,a,{semantic:i}),...sL(s),...aL(s,r)])}function oL(e,t,n,r){let i=[];for(let[o,s]of t){if(St(o))continue;let a=n.get(o)??new Set;for(let c of s)if(!St(c)&&!a.has(c)){if(r.semantic&&bL(e,o,c)||yL(e,o,c)||SL(e,o,c)||hL(c)||CL(e,o,c)||xL(c))continue;i.push({file:o,kind:"unused-import",description:`Depends on ${c} but references none of its symbols`,dep:c})}}return i}function sL(e){let t=[],n=gL(e);for(let[r,i]of e){if(St(r))continue;let o=fn(r);for(let s of i){if(St(s))continue;let a=fn(s);if(o===a)continue;(ma(o,a)??n.get(`${o}->${a}`))==="violation"&&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}/`})}}return t}function aL(e,t){let n=[];for(let[r,i]of lL(e)){let o=i.filter(a=>!St(a));if(o.length<t)continue;let s=uL(e,o);for(let a of o)for(let c of e.get(a)??[])St(c)||(s.get(c)??0)===1&&Or.dirname(c)!==r&&Or.dirname(c)!==Or.dirname(r)&&(Md(a,c)||n.push({file:a,kind:"pattern-deviation",description:`Only file in ${r}/ that depends on ${c}`,dep:c}))}return n}function cL(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 lL(e){let t=new Map;for(let n of e.keys()){let r=Or.dirname(n),i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function uL(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])St(i)||n.set(i,(n.get(i)??0)+1);return n}function dL(e,t){let n=new Map;return mL(e,n,t),fL(e,n),n}function mL(e,t,n){for(let r of pL(e,n))Od(e,t,r.from_file,r.to_file)}function pL(e,t){let n=t?`AND d1.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT d1.relative_path AS from_file, d2.relative_path AS to_file
537
507
  FROM mentions m
538
508
  JOIN chunks c ON m.chunk_id = c.id
539
509
  JOIN documents d1 ON c.document_id = d1.id
@@ -549,31 +519,30 @@ ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,e
549
519
  WHERE d1.id != d2.id
550
520
  AND m.role != 1
551
521
  ${e.pathExclusionsFor("d1","d2")}
552
- ${n}`)}function xS(e,t){new _(e).scanSourceReferences({paths:T(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},r=>{r.target.relativePath!==r.sourceFile&&(e.isIgnored(r.target.relativePath)||Vl(e,t,r.sourceFile,r.target.relativePath))})}function Vl(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 CS(e){let t=new Map;for(let[r,i]of e){if(Ze(r))continue;let o=jt(r);for(let s of i){if(Ze(s))continue;let a=jt(s);if(o===a||es(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 RS(e){return e.includes("types")||e.endsWith(".d.ts")}function IS(e,t,n){let r=Mn(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.isUsed)}function vS(e,t,n){let r=ne(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.used)}function DS(e,t,n){let r=ne(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.every(i=>i.isTypeOnly===!0)}function NS(e){return e.endsWith(".vue")}function _S(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 Ze(e){let t=G(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||LS(Xn.basename(e)))}function LS(e){return!!(e==="index.ts"||e==="index.js"||e==="cli.ts"||e==="main.ts"||e==="main.rs"||e.includes("worker.")||e.includes("postinstall.")||e==="health.ts"||e==="health.js")}function Ht(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new _(e);return _e({candidates:()=>ES(s,n,r),orderCandidates:Jr,scanLimit:o,prepare:a=>s.calleeMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,c)=>wS(e,a,c.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:i})}function wS(e,t,n){let r=kS(n);if(r.size!==1||!Mi(e,t.relativePath,t.startLine,t.endLine))return null;let[,i]=[...r.entries()][0];return{symbol:t.symbol,shortName:b(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:H(t),forwardsTo:i.symbol,forwardsToShort:b(i.symbol),forwardsToFile:i.file}}function kS(e){let t=e.some(r=>Y(r.symbol))?e.filter(r=>Y(r.symbol)):e,n=new Map;for(let r of t)n.has(r.symbol)||n.set(r.symbol,r);return n}function ES(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:3,maxLoc:n,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0})}var PS=W("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]});function Zn(e,t,n){return e.callerFileMap(t,{semantic:n.semantic,sourceFallback:n.sourceFallback})}function ri(e,t,n){let r=[],i=0,o=0,s=F(t.symbol);for(let a of n)AS(e,a,t.relativePath,s)?i++:ts(e,a,s)?o++:r.push(a);return{realConsumers:r,barrelConsumers:i,importOnlyConsumers:o}}function ts(e,t,n){if(!n)return!1;let r=B(t);if(!r)return!1;let i=PS.get(e,t,()=>FS(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function FS(e,t,n){let r=new Set,i=new Set,o=le(e,t);if(!o)return{importedLeaves:r,usedLeaves:i};let s=n==="rust"?new Set(["use_declaration"]):n==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),a=(c,l)=>{let u=l||s.has(c.type);(c.type==="identifier"||c.type==="type_identifier"||c.type==="property_identifier"||c.type==="field_identifier")&&(u?r.add(c.text):i.add(c.text));for(let m of c.children)a(m,u)};return a(o.rootNode,!1),{importedLeaves:r,usedLeaves:i}}function AS(e,t,n,r){if(!r)return!1;let i=M(e,t);if(!i)return!1;let o=oc(e,t);if(o.length===0)return!1;let s=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`\\b${s}\\b`),c=i.split(`
553
- `),l=0;for(let u=0;u<c.length;u++){if(!a.test(c[u]??""))continue;if(l++,!o.find(d=>d.startLine<=u&&u<=d.endLine))return!1}return l>0}function qt(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),m=GS(l,n),d={high:0,medium:1,low:2};return _e({candidates:()=>TS(e,l,u,{minLoc:r,maxLoc:i}),orderCandidates:(p,h)=>H(h)-H(p)||p.relativePath.localeCompare(h.relativePath),scanLimit:a,prepare:p=>({consumerFileMap:MS(l,p,{semantic:c}),singletonBackedClassIds:BS(e,l,u,p,{semantic:c}),candidateIndex:OS(p)}),evaluate:(p,h)=>{if(h.singletonBackedClassIds.has(p.symbolId))return null;let f=$S(e,p,h.consumerFileMap,h.candidateIndex);if(f.transitivelyReachable||f.realConsumers.length>1||f.realConsumers.length===0&&f.barrelConsumers>0||!zS(f.definition,f.realConsumers.length,m))return null;let y=jS(e,f);return!s&&y.confidence==="low"?null:y},orderResults:(p,h)=>d[p.confidence]-d[h.confidence]||h.loc-p.loc||p.file.localeCompare(h.file)||p.startLine-h.startLine,limit:o})}function TS(e,t,n,r){return n.filter(i=>i.isTypeLike&&H(i)>=r.minLoc).filter(i=>H(i)<=r.maxLoc).filter(i=>!e.isIgnored(i.relativePath)).filter(i=>G(i.relativePath)!=="test").filter(i=>!re(e,i.symbol,i.relativePath)).filter(i=>!JS(i.symbol)).filter(i=>!t.hasSuppressionComment(i))}function MS(e,t,n){return Zn(e,t,{semantic:n.semantic})}function OS(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=F(n.symbol);i&&r.set(i,n)}return t}function $S(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}=ri(e,t,o),l=KS(e,t,n,r);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:l}}function jS(e,t){let n=Gl(e,t.definition.relativePath,t.definition.startLine),r=Ul(t.definition.relativePath)?!0:QS(e,t.definition),{confidence:i,reason:o}=YS(t.realConsumers.length,n,r);return{symbol:t.definition.symbol,shortName:b(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:H(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:r,confidence:i,reason:o}}function BS(e,t,n,r,i){let o=qS(e,HS(n),r),s=o.map(l=>l.singleton);if(o.length===0)return new Set;let a=Zn(t,s,{semantic:i.semantic}),c=new Set;for(let{singleton:l,classId:u}of o)WS(e,l,a)&&c.add(u);return c}function HS(e){let t=new Map;for(let n of e){let r=F(n.symbol);r&&t.set(Wl(n.relativePath,r),n)}return t}function qS(e,t,n){let r=[];for(let i of n){let o=VS(e,t,i);o&&r.push({singleton:o,classId:i.symbolId})}return r}function VS(e,t,n){if(Gl(e,n.relativePath,n.startLine)!=="class")return null;let r=F(n.symbol);if(!r)return null;let i=US(e,n.relativePath,r);return i?t.get(Wl(n.relativePath,i))??null:null}function WS(e,t,n){let r=F(t.symbol),i=n.get(t.symbolId);return!r||!i?!1:[...i].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!ts(e,o,r))}function Wl(e,t){return`${e}\0${t}`}function US(e,t,n){let r=M(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 GS(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function JS(e){let t=ee(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 Ul(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 zS(e,t,n){return!(Ul(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function KS(e,t,n,r){let i=$i(e,t.relativePath),o=F(t.symbol);if(!o)return!1;let s=i.get(o);if(!s||s.size===0)return!1;let a=r.get(t.relativePath);if(!a)return!1;for(let c of s){let l=a.get(c);if(!l)continue;let u=n.get(l.symbolId);if(u){for(let m of u)if(m!==t.relativePath&&!e.isIgnored(m))return!0}}return!1}function Gl(e,t,n){let r=M(e,t);if(!r)return"other";let i=r.split(`
554
- `),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 QS(e,t){let n=M(e,t.relativePath);if(!n)return!1;let r=F(t.symbol);if(!r)return!1;let i=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${i}\\b`),s=n.split(`
555
- `);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function YS(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 er,extname as ii}from"path";function Vt(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new _(e),a=ox(s.fileDependencyGraph(n));return _e({candidates:()=>ZS(s,n,r),orderCandidates:Jr,scanLimit:o,prepare:c=>({callerFileMap:Zn(s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>XS(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:i})}function XS(e,t,n,r){let i=ex(e,t,n,r.callerFileMap);if(i.length!==1)return null;let o=i[0],s=tx(e,n.symbolId,o);if(!s)return null;let a=nx(t,e,o,n.symbol,s);if(a&&Zt(a.symbol))return null;let{fanIn:c,source:l}=rx(r.callerFileMap,r.reverseFanIn,o,a);return(l==="function"?c<=3:c<=5)?null:{symbol:n.symbol,shortName:b(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:H(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?b(a.symbol):er(o),callerFanIn:c}}function ZS(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:2,maxLoc:n,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0})}function ex(e,t,n,r){let i=er(n.relativePath,ii(n.relativePath)),o=[...r.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>er(s,ii(s))!==i).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return ri(e,n,o).realConsumers}function tx(e,t,n){return e.get(`SELECT c.start_line, c.end_line
522
+ ${n}`)}function fL(e,t){new N(e).scanSourceReferences({paths:V(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},r=>{r.target.relativePath!==r.sourceFile&&(e.isIgnored(r.target.relativePath)||Od(e,t,r.sourceFile,r.target.relativePath))})}function Od(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 gL(e){let t=new Map;for(let[r,i]of e){if(St(r))continue;let o=fn(r);for(let s of i){if(St(s))continue;let a=fn(s);if(o===a||ma(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 hL(e){return e.includes("types")||e.endsWith(".d.ts")}function bL(e,t,n){let r=xr(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.isUsed)}function yL(e,t,n){let r=ce(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.used)}function SL(e,t,n){let r=ce(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.every(i=>i.isTypeOnly===!0)}function xL(e){return e.endsWith(".vue")}function CL(e,t,n){let r=ce(e,t).filter(i=>i.sourcePath===n);return r.length===0?!1:r.every(i=>i.kind==="side-effect"||i.kind==="namespace"&&i.usedMembers.length===0&&!i.used)}function St(e){let t=z(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||vL(Or.basename(e)))}function vL(e){return!!(e==="index.ts"||e==="index.js"||e==="cli.ts"||e==="main.ts"||e==="main.rs"||e.includes("worker.")||e.includes("postinstall.")||e==="health.ts"||e==="health.js")}function hn(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new N(e);return Ve({candidates:()=>IL(s,n,r),orderCandidates:Wi,scanLimit:o,prepare:a=>s.calleeMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,c)=>RL(e,a,c.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:i})}function RL(e,t,n){let r=LL(n);if(r.size!==1||!Uo(e,t.relativePath,t.startLine,t.endLine))return null;let[,i]=[...r.entries()][0];return{symbol:t.symbol,shortName:y(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:q(t),forwardsTo:i.symbol,forwardsToShort:y(i.symbol),forwardsToFile:i.file}}function LL(e){let t=e.some(r=>te(r.symbol))?e.filter(r=>te(r.symbol)):e,n=new Map;for(let r of t)n.has(r.symbol)||n.set(r.symbol,r);return n}function IL(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:3,maxLoc:n,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0})}var DL=W("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]});function jr(e,t,n){return e.callerFileMap(t,{semantic:n.semantic,sourceFallback:n.sourceFallback})}function to(e,t,n){let r=[],i=0,o=0,s=$(t.symbol);for(let a of n)wL(e,a,t.relativePath,s)?i++:pa(e,a,s)?o++:r.push(a);return{realConsumers:r,barrelConsumers:i,importOnlyConsumers:o}}function pa(e,t,n){if(!n)return!1;let r=U(t);if(!r)return!1;let i=DL.get(e,t,()=>kL(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function kL(e,t,n){let r=new Set,i=new Set,o=oe(e,t);if(!o)return{importedLeaves:r,usedLeaves:i};let s=n==="rust"?new Set(["use_declaration"]):n==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),a=(c,l)=>{let u=l||s.has(c.type);(c.type==="identifier"||c.type==="type_identifier"||c.type==="property_identifier"||c.type==="field_identifier")&&(u?r.add(c.text):i.add(c.text));for(let d of c.children)a(d,u)};return a(o.rootNode,!1),{importedLeaves:r,usedLeaves:i}}function wL(e,t,n,r){if(!r)return!1;let i=dt(e,t);if(i.length===0)return!1;let o=Ul(e,t);if(o.length===0)return!1;let s=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`\\b${s}\\b`),c=0;for(let l=0;l<i.length;l++){if(!a.test(i[l]??""))continue;if(c++,!o.find(d=>d.startLine<=l&&l<=d.endLine))return!1}return c>0}function bn(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 N(e),u=l.scopedDefinitions(n),d=BL(l,n),m={high:0,medium:1,low:2};return Ve({candidates:()=>NL(e,l,u,{minLoc:r,maxLoc:i}),orderCandidates:(f,g)=>q(g)-q(f)||f.relativePath.localeCompare(g.relativePath),scanLimit:a,prepare:f=>({consumerFileMap:PL(l,f,{semantic:c}),singletonBackedClassIds:TL(e,l,u,f,{semantic:c}),candidateIndex:_L(f)}),evaluate:(f,g)=>{if(g.singletonBackedClassIds.has(f.symbolId))return null;let h=EL(e,f,g.consumerFileMap,g.candidateIndex);if(h.transitivelyReachable||h.realConsumers.length>1||h.realConsumers.length===0&&h.barrelConsumers>0||!HL(h.definition,h.realConsumers.length,d))return null;let b=FL(e,h);return!s&&b.confidence==="low"?null:b},orderResults:(f,g)=>m[f.confidence]-m[g.confidence]||g.loc-f.loc||f.file.localeCompare(g.file)||f.startLine-g.startLine,limit:o})}function NL(e,t,n,r){return n.filter(i=>i.isTypeLike&&q(i)>=r.minLoc).filter(i=>q(i)<=r.maxLoc).filter(i=>!e.isIgnored(i.relativePath)).filter(i=>z(i.relativePath)!=="test").filter(i=>!le(e,i.symbol,i.relativePath)).filter(i=>!VL(i.symbol)).filter(i=>!t.hasSuppressionComment(i))}function PL(e,t,n){return jr(e,t,{semantic:n.semantic})}function _L(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=$(n.symbol);i&&r.set(i,n)}return t}function EL(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}=to(e,t,o),l=qL(e,t,n,r);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:l}}function FL(e,t){let n=Vd(e,t.definition.relativePath,t.definition.startLine),r=Bd(t.definition.relativePath)?!0:WL(e,t.definition),{confidence:i,reason:o}=UL(t.realConsumers.length,n,r);return{symbol:t.definition.symbol,shortName:y(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:q(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:r,confidence:i,reason:o}}function TL(e,t,n,r,i){let o=$L(e,AL(n),r),s=o.map(l=>l.singleton);if(o.length===0)return new Set;let a=jr(t,s,{semantic:i.semantic}),c=new Set;for(let{singleton:l,classId:u}of o)OL(e,l,a)&&c.add(u);return c}function AL(e){let t=new Map;for(let n of e){let r=$(n.symbol);r&&t.set(jd(n.relativePath,r),n)}return t}function $L(e,t,n){let r=[];for(let i of n){let o=ML(e,t,i);o&&r.push({singleton:o,classId:i.symbolId})}return r}function ML(e,t,n){if(Vd(e,n.relativePath,n.startLine)!=="class")return null;let r=$(n.symbol);if(!r)return null;let i=jL(e,n.relativePath,r);return i?t.get(jd(n.relativePath,i))??null:null}function OL(e,t,n){let r=$(t.symbol),i=n.get(t.symbolId);return!r||!i?!1:[...i].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!pa(e,o,r))}function jd(e,t){return`${e}\0${t}`}function jL(e,t,n){let r=A(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 BL(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function VL(e){let t=se(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 Bd(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 HL(e,t,n){return!(Bd(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function qL(e,t,n,r){let i=Go(e,t.relativePath),o=$(t.symbol);if(!o)return!1;let s=i.get(o);if(!s||s.size===0)return!1;let a=r.get(t.relativePath);if(!a)return!1;for(let c of s){let l=a.get(c);if(!l)continue;let u=n.get(l.symbolId);if(u){for(let d of u)if(d!==t.relativePath&&!e.isIgnored(d))return!0}}return!1}function Vd(e,t,n){let r=A(e,t);if(!r)return"other";let i=r.split(`
523
+ `),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 WL(e,t){let n=A(e,t.relativePath);if(!n)return!1;let r=$(t.symbol);if(!r)return!1;let i=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${i}\\b`),s=n.split(`
524
+ `);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function UL(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 Br,extname as no}from"path";function yn(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new N(e),a=ZL(s.fileDependencyGraph(n));return Ve({candidates:()=>GL(s,n,r),orderCandidates:Wi,scanLimit:o,prepare:c=>({callerFileMap:jr(s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>JL(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:i})}function JL(e,t,n,r){let i=zL(e,t,n,r.callerFileMap);if(i.length!==1)return null;let o=i[0],s=KL(e,n.symbolId,o);if(!s)return null;let a=QL(t,e,o,n.symbol,s);if(a&&_n(a.symbol))return null;let{fanIn:c,source:l}=XL(r.callerFileMap,r.reverseFanIn,o,a);return(l==="function"?c<=3:c<=5)?null:{symbol:n.symbol,shortName:y(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:q(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?y(a.symbol):Br(o),callerFanIn:c}}function GL(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:2,maxLoc:n,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0})}function zL(e,t,n,r){let i=Br(n.relativePath,no(n.relativePath)),o=[...r.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>Br(s,no(s))!==i).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return to(e,n,o).realConsumers}function KL(e,t,n){return e.get(`SELECT c.start_line, c.end_line
556
525
  FROM mentions m
557
526
  JOIN chunks c ON m.chunk_id = c.id
558
527
  JOIN documents d ON c.document_id = d.id
559
528
  WHERE m.symbol_id = ? AND m.role != 1 AND d.relative_path = ?
560
- LIMIT 1`,t,n)}function nx(e,t,n,r,i){let o=e.definitionsForFile(n),s=ix(t,n,r,i.start_line,i.end_line);return Ce(o,s)}function rx(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:sx(t,n),source:"file"}}function ix(e,t,n,r,i){let o=F(n);if(!o)return r;let s=Qe(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 ox(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 sx(e,t){let n=e.get(t)??0;if(n>0)return n;let r=er(t,ii(t)),i=0;for(let[o,s]of e)o!==t&&er(o,ii(o))===r&&s>i&&(i=s);return i}var dx=75e3,px=5e3,fx=2500;function gx(e){let t=we(e);return t.symbols>=dx||t.documents>=px?fx:void 0}var hx=".scipquery-baseline.json";function oi(e,t){return t&&ux(t)?t:mx(e.config.projectRoot,t??hx)}function ns(e,t={}){let{scope:n}=t,r=gx(e),i=[],o=Ye(e,{scope:n,...X.dead,scanLimit:r});for(let s of o.symbols)ue(e,s.relativePath)||re(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&i.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of Tt(e,{scope:n,...X.isolated,scanLimit:r}))ue(e,s.relativePath)||re(e,s.symbol,s.relativePath)||i.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of At(e,{scope:n}))s.kind==="real"&&i.push(`cycle:${yx(s.path)}`);for(let s of Xe(e,{scope:n,...X.similar,scanLimit:r}))i.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of Mt(e,{scope:n,...X.extract,scanLimit:r}))i.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of Vt(e,{scope:n,...X.wrappers,scanLimit:r}))i.push(`wrapper:${s.file}:${s.shortName}`);for(let s of Ht(e,{scope:n,...X.passthroughs,scanLimit:r}))i.push(`passthrough:${s.file}:${s.shortName}`);for(let s of qt(e,{scope:n,...X.stale,scanLimit:r}))i.push(`stale:${s.file}:${s.shortName}`);for(let s of Bt(e,{scope:n,...X.drift}).results)s.kind!=="pattern-deviation"&&i.push(`drift:${s.kind}:${s.file}:${s.dep}`);return[...new Set(i)].sort()}function yx(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 rs(e,t={}){let n=ns(e,{scope:t.scope}),r=oi(e,t.path);return lx(r,JSON.stringify({version:1,findings:n},null,2)+`
561
- `),{path:r,findingCount:n.length}}function tr(e,t={}){let n=oi(e,t.path);if(!ax(n))throw new Error(`No baseline found at ${n}. Create one with: scip-query health --write-baseline`);let r=JSON.parse(cx(n,"utf-8")),i=new Set(r.findings??[]),o=ns(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))}}import{execFileSync as bx}from"child_process";var Sx=5;function nr(e,t={}){let{base:n="HEAD",minContainment:r=.7,minCallees:i=3,maxHelpers:o=10,limit:s=20}=t,a=t.semantic!==!1,c=ht(e,{base:n}),l={available:c.note!==Yo,base:n,changedFiles:c.changedFiles,helpersChecked:0,skipped:[],findings:[]};if(!l.available||c.changedFiles.length===0)return l;let u=new _(e),m=new Set(c.changedFiles),d=xx(e,u,m,n);if(d.length===0)return l;let p=d.slice(0,o);d.length>o&&(l.note=`helper scoring capped at ${o} of ${d.length} new symbols`);let h=Kr(e,{minCallees:Math.min(3,i),semantic:a}),f=u.calleeMap(p,{semantic:a}),y=p.map(S=>({def:S,callees:Qr((f.get(S.symbolId)??[]).map(x=>x.symbol))})),R=new Map;for(let S of h)for(let x of S.callees)R.set(x,(R.get(x)??0)+1);let k=Math.max(8,Math.ceil(Math.sqrt(h.length)));for(let{def:S,callees:x}of y){let D=b(S.symbol);if(x.size<i){l.skipped.push({helperShortName:D,helperFile:S.relativePath,reason:`fewer than ${i} meaningful callees \u2014 too small to score`});continue}let w=Rx(e,S.symbolId);if(w.length===0){l.skipped.push({helperShortName:D,helperFile:S.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}l.helpersChecked+=1;let $=[];for(let P of h){if(P.symbol===S.symbol||m.has(P.file)||P.callees.has(S.symbol))continue;let ie=Cl(x,P.callees);if(ie<r)continue;let he=[...x].filter($e=>P.callees.has($e));he.some($e=>(R.get($e)??0)<=k)&&$.push({symbol:P.symbol,shortName:b(P.symbol),file:P.file,containment:ie,sharedCallees:he.map(b).sort()})}$.length!==0&&($.sort((P,ie)=>ie.containment-P.containment||P.file.localeCompare(ie.file)),l.findings.push({helperSymbol:S.symbol,helperShortName:D,helperFile:S.relativePath,migratedFiles:w.sort(),leftovers:$.slice(0,Sx)}))}return l.findings.sort((S,x)=>(x.leftovers[0]?.containment??0)-(S.leftovers[0]?.containment??0)||S.helperFile.localeCompare(x.helperFile)),l.findings=l.findings.slice(0,s),l}function xx(e,t,n,r){let i=new Map;return t.productionCallableDefinitions({requireFunctionLikeSymbol:!0}).filter(o=>{if(!n.has(o.relativePath))return!1;let s=i.get(o.relativePath);return s===void 0&&(s=Cx(e.config.projectRoot,r,o.relativePath),i.set(o.relativePath,s)),s===null||!new RegExp(`\\b${Ix(o.leaf)}\\b`).test(s)})}function Cx(e,t,n){try{return bx("git",["show",`${t}:./${n}`],{encoding:"utf-8",cwd:e,timeout:1e4,stdio:["ignore","pipe","ignore"]})}catch{return null}}function Rx(e,t){return e.all(`SELECT DISTINCT ref_d.relative_path
529
+ LIMIT 1`,t,n)}function QL(e,t,n,r,i){let o=e.definitionsForFile(n),s=YL(t,n,r,i.start_line,i.end_line);return Ae(o,s)}function XL(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:eI(t,n),source:"file"}}function YL(e,t,n,r,i){let o=$(n);if(!o)return r;let s=gt(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 ZL(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 eI(e,t){let n=e.get(t)??0;if(n>0)return n;let r=Br(t,no(t)),i=0;for(let[o,s]of e)o!==t&&Br(o,no(o))===r&&s>i&&(i=s);return i}var sI=75e3,aI=5e3,cI=2500;function lI(e){let t=Te(e);return t.symbols>=sI||t.documents>=aI?cI:void 0}var uI=".scipquery-baseline.json";function ro(e,t){return t&&iI(t)?t:oI(e.config.projectRoot,t??uI)}function fa(e,t={}){let{scope:n}=t,r=lI(e),i=[],o=ht(e,{scope:n,...re.dead,scanLimit:r});for(let s of o.symbols)xe(e,s.relativePath)||le(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&i.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of on(e,{scope:n,...re.isolated,scanLimit:r}))xe(e,s.relativePath)||le(e,s.symbol,s.relativePath)||i.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of rn(e,{scope:n}))s.kind==="real"&&i.push(`cycle:${dI(s.path)}`);for(let s of bt(e,{scope:n,...re.similar,scanLimit:r}))i.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of dn(e,{scope:n,...re.extract,scanLimit:r}))i.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of yn(e,{scope:n,...re.wrappers,scanLimit:r}))i.push(`wrapper:${s.file}:${s.shortName}`);for(let s of hn(e,{scope:n,...re.passthroughs,scanLimit:r}))i.push(`passthrough:${s.file}:${s.shortName}`);for(let s of bn(e,{scope:n,...re.stale,scanLimit:r}))i.push(`stale:${s.file}:${s.shortName}`);for(let s of gn(e,{scope:n,...re.drift}).results)s.kind!=="pattern-deviation"&&i.push(`drift:${s.kind}:${s.file}:${s.dep}`);return[...new Set(i)].sort()}function dI(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 ga(e,t={}){let n=fa(e,{scope:t.scope}),r=ro(e,t.path);return rI(r,JSON.stringify({version:1,findings:n},null,2)+`
530
+ `),{path:r,findingCount:n.length}}function Vr(e,t={}){let n=ro(e,t.path);if(!tI(n))throw new Error(`No baseline found at ${n}. Create one with: scip-query health --write-baseline`);let r=JSON.parse(nI(n,"utf-8")),i=new Set(r.findings??[]),o=fa(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 mI=5;function Hr(e,t={}){let{base:n="HEAD",minContainment:r=.7,minCallees:i=3,maxHelpers:o=Number.POSITIVE_INFINITY,limit:s=20}=t,a=t.semantic!==!1,c=t.diffPlan??it(e,{base:n}),l={available:c.note!==la,base:n,changedFiles:c.changedFiles,helpersChecked:0,skipped:[],findings:[]};if(!l.available||c.changedFiles.length===0)return l;let u=new N(e),d=new Set(c.changedFiles),m=new Map(c.renamedFiles.map(k=>[k.to,k.from])),f=gI(e,u,d,n,m);if(f.length===0)return l;let g=f.slice(0,o);f.length>o&&(l.note=`helper scoring capped at ${o} of ${f.length} new symbols`);let h=Ji(e,{minCallees:Math.min(3,i),semantic:a}),b=pI(h),L=u.calleeMap(g,{semantic:a}),F=g.map(k=>({def:k,callees:Gi((L.get(k.symbolId)??[]).map(E=>E.symbol))}));for(let{def:k,callees:E}of F){let C=y(k.symbol);if(E.size<i){l.skipped.push({helperShortName:C,helperFile:k.relativePath,reason:`fewer than ${i} meaningful callees \u2014 too small to score`});continue}let w=hI(e,k.symbolId);if(w.length===0){l.skipped.push({helperShortName:C,helperFile:k.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}l.helpersChecked+=1;let M=fI({candidateIndex:b,changed:d,helperCallees:E,helperSymbol:k.symbol,minContainment:r});M.length!==0&&(M.sort((j,ye)=>ye.containment-j.containment||j.file.localeCompare(ye.file)),l.findings.push({helperSymbol:k.symbol,helperShortName:C,helperFile:k.relativePath,migratedFiles:w.sort(),leftovers:M.slice(0,mI)}))}return l.findings.sort((k,E)=>(E.leftovers[0]?.containment??0)-(k.leftovers[0]?.containment??0)||k.helperFile.localeCompare(E.helperFile)),l.findings=l.findings.slice(0,s),l}function pI(e){let t=new Map,n=new Map;for(let r of e)for(let i of r.callees){t.set(i,(t.get(i)??0)+1);let o=n.get(i);o||(o=[],n.set(i,o)),o.push(r)}return{candidatesByCallee:n,docFreq:t,ubiquityThreshold:Math.max(8,Math.ceil(Math.sqrt(e.length)))}}function fI(e){let t=[],n=new Set;for(let r of e.helperCallees)for(let i of e.candidateIndex.candidatesByCallee.get(r)??[])n.add(i);for(let r of n){if(r.symbol===e.helperSymbol||e.changed.has(r.file)||r.callees.has(e.helperSymbol))continue;let i=ud(e.helperCallees,r.callees);if(i<e.minContainment)continue;let o=[...e.helperCallees].filter(s=>r.callees.has(s));o.some(s=>(e.candidateIndex.docFreq.get(s)??0)<=e.candidateIndex.ubiquityThreshold)&&t.push({symbol:r.symbol,shortName:y(r.symbol),file:r.file,containment:i,sharedCallees:o.map(y).sort()})}return t}function gI(e,t,n,r,i){let o=new Map;return t.productionCallableDefinitions({requireFunctionLikeSymbol:!0}).filter(s=>{if(!n.has(s.relativePath))return!1;let a=i.get(s.relativePath)??s.relativePath,c=o.get(a);return c===void 0&&(c=$r(e.config.projectRoot,r,a),o.set(a,c)),c===null||!new RegExp(`\\b${bI(s.leaf)}\\b`).test(c)})}function hI(e,t){return e.all(`SELECT DISTINCT ref_d.relative_path
562
531
  FROM mentions m
563
532
  JOIN chunks c ON m.chunk_id = c.id
564
533
  JOIN documents ref_d ON c.document_id = ref_d.id
565
534
  WHERE m.symbol_id = ?
566
535
  AND m.role != 1
567
- ${e.pathExclusionsFor("ref_d")}`,t).map(r=>r.relative_path)}function Ix(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rr(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=t.files===void 0?null:new Set(t.files),s=new _(e);return _e({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}).filter(a=>vx(a.relativePath)&&(o===null||o.has(a.relativePath))),scanLimit:i,evaluate:a=>{let c=Q(e,a.relativePath)?.callables.find(m=>m.startLine===a.startLine&&m.endLine===a.endLine);if(!c||c.params.length===0||c.params.some(m=>!m.simple)||c.paramsEndLine>=c.endLine)return null;let l=Qe(e,a.relativePath),u=[];for(let m=c.params.length-1;m>=0;m--){let d=c.params[m];if(d.name===""||d.name.startsWith("_")||Dx(l.get(d.name),c.paramsEndLine,c.endLine))break;u.unshift(d.name)}return u.length===0?null:{symbol:a.symbol,shortName:b(a.symbol),file:a.relativePath,startLine:a.startLine,endLine:a.endLine,paramCount:c.paramCount,unusedTrailing:u}},orderResults:(a,c)=>c.unusedTrailing.length-a.unusedTrailing.length||a.file.localeCompare(c.file)||a.startLine-c.startLine,limit:r})}function vx(e){let t=B(e);return t==="typescript"||t==="tsx"||t==="javascript"}function Dx(e,t,n){return e?e.some(r=>r>t&&r<=n):!1}function is(e,t={}){let n=t.base??"HEAD",{minTogether:r=6,minConfidence:i=.6,maxEchoChecks:o=10,minSimilarity:s=.8}=t,a=hn(e,{base:n}),c=a.changedFiles,l=new Set(c),u={base:n,changedFiles:c,changedSymbols:a.changedSymbols.length,checksRun:[],skipped:[],findings:[],note:a.summary.note};return c.length===0||(Nx(e,a.changedSymbols,l,o,s,u),_x(e,n,u),Lx(e,l,r,i,u),wx(e,l,u),kx(e,c,u),Ex(e,a.changedSymbols,u),Px(e,u)),u}function Nx(e,t,n,r,i,o){o.checksRun.push("echo");for(let s of t.slice(0,r)){let a=zn(e,s.symbol,{minSimilarity:i,limit:3});for(let c of a){let l=c.fileA===s.file?c.fileB:c.fileA,u=c.fileA===s.file?c.shortNameB:c.shortNameA;n.has(l)||o.findings.push({check:"echo",message:`${s.shortName} (${s.file}) is ${Math.round(c.similarity*100)}% similar to established ${u} (${l})`,remediation:`Extend or reuse ${u} instead of keeping the re-implementation.`})}}t.length>r&&o.skipped.push({check:"echo",reason:`echo check capped at ${r} of ${t.length} changed symbols`})}function _x(e,t,n){let r=nr(e,{base:t});if(!r.available){n.skipped.push({check:"incomplete-migration",reason:"no git history"});return}n.checksRun.push("incomplete-migration"),r.note&&n.skipped.push({check:"incomplete-migration",reason:r.note});for(let i of r.findings){let o=i.leftovers.map(s=>`${s.shortName} (${s.file}, ${Math.round(s.containment*100)}%)`).join(", ");n.findings.push({check:"incomplete-migration",message:`new helper ${i.helperShortName} (${i.helperFile}) is wired into ${i.migratedFiles.length} file(s), but ${i.leftovers.length} similar un-migrated site(s) remain: ${o}`,remediation:`Migrate the remaining sites to ${i.helperShortName}, or confirm they are intentionally different.`})}}function Lx(e,t,n,r,i){let o=Zr(e,{minTogether:n,minConfidence:0});if(!o){i.skipped.push({check:"co-change-partner",reason:"no git history"});return}i.checksRun.push("co-change-partner");let s=new Set;for(let a of o){let c=t.has(a.fileA),l=t.has(a.fileB);if(c===l)continue;let u=c?a.fileA:a.fileB,m=c?a.fileB:a.fileA,d=c?a.changesA:a.changesB,p=d>0?a.together/d:0;if(p<r||Ko(m)||Ko(u)||!Jl(`${e.config.projectRoot}/${m}`))continue;let h=`${u}|${m}`;s.has(h)||(s.add(h),i.findings.push({check:"co-change-partner",message:`${u} changed, but ${m} did not \u2014 they change together ${a.together}x (${Math.round(p*100)}% of the time)`,remediation:`Update ${m} alongside this change, or confirm the coupling no longer holds.`}))}}function wx(e,t,n){n.checksRun.push("doc-reference");for(let r of $l(e,t))t.has(r.doc)||n.findings.push({check:"doc-reference",message:`${r.doc} cites ${r.cited.join(", ")} \u2014 changed in this diff, doc untouched`,remediation:`Re-read ${r.doc} and update its claims, or update its citations.`})}function kx(e,t,n){n.checksRun.push("unused-params");for(let r of rr(e,{files:t,limit:50}))n.findings.push({check:"unused-params",message:`${r.shortName} (${r.file}) has trailing unused parameter(s): ${r.unusedTrailing.join(", ")}`,remediation:"Drop the unused trailing parameters and their call-site arguments."})}function Ex(e,t,n){n.checksRun.push("new-dead");let r=new _(e);for(let i of t)i.fanIn>0||r.fileKind(i.file)!=="test"&&(ue(e,i.file)||re(e,i.symbol,i.file)||n.findings.push({check:"new-dead",message:`${i.shortName} (${i.file}) was changed but has zero indexed consumers`,remediation:"Wire it up, or remove it before it becomes permanent dead code."}))}function Px(e,t){if(!Jl(oi(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=tr(e);for(let r of n.newFindings)t.findings.push({check:"baseline",message:`new finding vs committed baseline: ${r}`,remediation:"Fix the finding, or knowingly accept it via health --write-baseline."})}function os(e,t={}){let{windowCommits:n=100,minSimilarity:r=.7,limit:i=30,scope:o,scanLimit:s}=t,a=Al(e);if(!a)return{available:!1,windowCommits:n,findings:[]};let c=Xe(e,{scope:o,minSimilarity:r,limit:i*5,crossFileOnly:!0,scanLimit:s,semantic:t.semantic}),l=[];for(let u of c){let m=a.get(u.fileA)?.commitsAgo??null,d=a.get(u.fileB)?.commitsAgo??null,p=m!==null&&m<=n,h=d!==null&&d<=n;if(!(!p&&!h)){if(p&&h){let f=(m??0)<=(d??0);l.push({kind:"twin",echoSymbol:f?u.shortNameA:u.shortNameB,echoFile:f?u.fileA:u.fileB,echoAgeCommits:(f?m:d)??0,establishedSymbol:f?u.shortNameB:u.shortNameA,establishedFile:f?u.fileB:u.fileA,establishedAgeCommits:f?d:m,similarity:u.similarity,sharedCallees:u.sharedCallees})}else l.push({kind:"echo",echoSymbol:p?u.shortNameA:u.shortNameB,echoFile:p?u.fileA:u.fileB,echoAgeCommits:(p?m:d)??0,establishedSymbol:p?u.shortNameB:u.shortNameA,establishedFile:p?u.fileB:u.fileA,establishedAgeCommits:p?d:m,similarity:u.similarity,sharedCallees:u.sharedCallees});if(l.length>=i)break}}return l.sort((u,m)=>(u.kind===m.kind?0:u.kind==="echo"?-1:1)||m.similarity-u.similarity),{available:!0,windowCommits:n,findings:l}}var Fx=/scip-query[\s:-]*ignore[\s:-]*(dead(?:-code)?|stale|wrapper|passthrough|drift|extract|similar)?/gi,Ax=de("suppression-inventory",{clearGroups:["whole-project"]});function si(e){return Ax.get(e,()=>Tx(e))}function Tx(e){let t={dead:0,stale:0,wrapper:0,passthrough:0,drift:0,extract:0,similar:0,uncategorized:0},n=new Map,r=0;for(let i of qe(e)){let o=M(e,i);if(!(!o||!o.includes("scip-query")))for(let s of o.matchAll(Fx)){r+=1,n.set(i,(n.get(i)??0)+1);let a=Mx(s[1]);t[a]+=1}}return{total:r,byCategory:t,byFile:n}}function Mx(e){if(!e)return"uncategorized";let t=e.toLowerCase();return t==="dead-code"?"dead":t}import{readFileSync as Ox}from"fs";import{join as $x}from"path";function ir(e,t,n={}){let r=A(e,t);if(!r)return null;let i=new _(e),o=Vx(Bx(e,r.relativePath,r.startLine,r.endLine),jx(e,r.relativePath)),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:b(r.symbol),relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,loc:s,branches:o,cyclomaticEstimate:o+1,calleeCount:l.size,fanIn:Hx(e,r.symbolId),fanOut:qx(c,r.relativePath)}}function jx(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function Bx(e,t,n,r){try{return Ox($x(e.config.projectRoot,t),"utf-8").split(`
536
+ ${e.pathExclusionsFor("ref_d")}`,t).map(r=>r.relative_path)}function bI(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qr(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=t.files===void 0?null:new Set(t.files),s=new N(e);return Ve({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}).filter(a=>yI(a.relativePath)&&(o===null||o.has(a.relativePath))),scanLimit:i,evaluate:a=>{let c=ee(e,a.relativePath)?.callables.find(d=>d.startLine===a.startLine&&d.endLine===a.endLine);if(!c||c.params.length===0||c.params.some(d=>!d.simple)||c.paramsEndLine>=c.endLine)return null;let l=gt(e,a.relativePath),u=[];for(let d=c.params.length-1;d>=0;d--){let m=c.params[d];if(m.name===""||m.name.startsWith("_")||SI(l.get(m.name),c.paramsEndLine,c.endLine))break;u.unshift(m.name)}return u.length===0?null:{symbol:a.symbol,shortName:y(a.symbol),file:a.relativePath,startLine:a.startLine,endLine:a.endLine,paramCount:c.paramCount,unusedTrailing:u}},orderResults:(a,c)=>c.unusedTrailing.length-a.unusedTrailing.length||a.file.localeCompare(c.file)||a.startLine-c.startLine,limit:r})}function yI(e){let t=U(e);return t==="typescript"||t==="tsx"||t==="javascript"}function SI(e,t,n){return e?e.some(r=>r>t&&r<=n):!1}var io=["echo","incomplete-migration","co-change-partner","doc-reference","unused-params","new-dead","baseline"];function ha(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}=t,c=new Set(t.skip??[]),l=it(e,{base:n}),u=Kn(e,{base:n,plan:l}),d=u.changedFiles,m=new Set(d),f=NI(e.config.projectRoot,n,l),g={base:n,changedFiles:d,changedSymbols:u.changedSymbols.length,checksRun:[],skipped:[],suppressed:[],findings:[],note:u.summary.note};if(d.length===0)return g;let h=(b,L)=>{if(c.has(b)){g.skipped.push({check:b,reason:"skipped via --skip"});return}L()};return h("echo",()=>RI(e,u.changedSymbols,m,f,o,a,g)),h("incomplete-migration",()=>LI(e,n,l,s,g)),h("co-change-partner",()=>II(e,m,r,i,g)),h("doc-reference",()=>DI(e,m,g)),h("unused-params",()=>kI(e,d,g)),h("new-dead",()=>wI(e,u.changedSymbols,f,g)),h("baseline",()=>EI(e,g)),CI(g,e.config.suppressions??[]),g}function CI(e,t){if(t.length===0||e.findings.length===0)return;let n=[];for(let r of e.findings){let i=t.find(o=>vI(o,r));i?e.suppressed.push({finding:r,suppression:i}):n.push(r)}e.findings=n}function vI(e,t){return!e.reason||e.reason.trim()===""||e.expiresAt&&Date.parse(e.expiresAt)<=Date.now()||e.id&&e.id!==t.id||e.check&&e.check!==t.check||e.file&&e.file!==t.file?!1:!!(e.id||e.check)}function RI(e,t,n,r,i,o,s){s.checksRun.push("echo");for(let a of t.slice(0,i)){if(r(a))continue;let c=Pr(e,a.symbol,{minSimilarity:o,limit:3});for(let l of c){let u=l.fileA===a.file?l.fileB:l.fileA,d=l.fileA===a.file?l.shortNameB:l.shortNameA,m=l.fileA===a.file?l.symbolB:l.symbolA;if(n.has(u))continue;let f=Sn("echo",a.symbol,a.file,m,u);s.findings.push({id:f,check:"echo",severity:"warning",evidence:"heuristic",confidence:l.similarity,file:a.file,symbol:a.symbol,relatedFiles:[u],message:`${a.shortName} (${a.file}) is ${Math.round(l.similarity*100)}% similar to established ${d} (${u})`,why:[`${a.shortName} was changed in this diff.`,`${d} is outside this diff and scored ${Math.round(l.similarity*100)}% similar by ${l.similarityBasis??"callee"} evidence.`,`Shared evidence: ${l.sharedCallees.slice(0,5).join(", ")||"(none listed)"}.`],remediation:`Extend or reuse ${d} instead of keeping the re-implementation.`,suppressionHint:`scip-query: ignore echo ${f} -- <reason>`})}}t.length>i&&s.skipped.push({check:"echo",reason:`echo check capped at ${i} of ${t.length} changed symbols`})}function LI(e,t,n,r,i){let o=Hr(e,{base:t,maxHelpers:r,diffPlan:n});if(!o.available){i.skipped.push({check:"incomplete-migration",reason:"no git history"});return}i.checksRun.push("incomplete-migration"),o.note&&i.skipped.push({check:"incomplete-migration",reason:o.note});for(let s of o.findings){let a=s.leftovers.map(d=>`${d.shortName} (${d.file}, ${Math.round(d.containment*100)}%)`).join(", "),c=[...s.migratedFiles,...s.leftovers.map(d=>d.file)],l=s.leftovers.length===0?void 0:Math.max(...s.leftovers.map(d=>d.containment)),u=Sn("incomplete-migration",s.helperSymbol,s.helperFile,c.join("|"));i.findings.push({id:u,check:"incomplete-migration",severity:"warning",evidence:"heuristic",confidence:l,file:s.helperFile,symbol:s.helperSymbol,relatedFiles:c,message:`new helper ${s.helperShortName} (${s.helperFile}) is wired into ${s.migratedFiles.length} file(s), but ${s.leftovers.length} similar un-migrated site(s) remain: ${a}`,why:[`${s.helperShortName} is new in this diff and already referenced by ${s.migratedFiles.join(", ")}.`,`Unchanged site(s) still contain the helper's callee pattern: ${a}.`],remediation:`Migrate the remaining sites to ${s.helperShortName}, or confirm they are intentionally different.`,suppressionHint:`scip-query: ignore incomplete-migration ${u} -- <reason>`})}}function II(e,t,n,r,i){let o=Xi(e,{minTogether:n,minConfidence:0,maxFilesPerCommit:20});if(!o){i.skipped.push({check:"co-change-partner",reason:"no git history"});return}i.checksRun.push("co-change-partner");let s=new Set;for(let a of o){let c=t.has(a.fileA),l=t.has(a.fileB);if(c===l)continue;let u=c?a.fileA:a.fileB,d=c?a.fileB:a.fileA,m=c?a.changesA:a.changesB,f=m>0?a.together/m:0;if(f<r||ca(d)||ca(u)||!Hd(`${e.config.projectRoot}/${d}`))continue;let g=`${u}|${d}`;if(s.has(g))continue;s.add(g);let h=Sn("co-change-partner",u,d,String(a.together));i.findings.push({id:h,check:"co-change-partner",severity:"warning",evidence:"change-graph",confidence:f,file:u,relatedFiles:[d],message:`${u} changed, but ${d} did not \u2014 they change together ${a.together}x (${Math.round(f*100)}% of the time)`,why:[`${u} is in this diff and ${d} is not.`,`Git history shows ${a.together} co-change(s), which is ${Math.round(f*100)}% of changes to the edited side.`],remediation:`Update ${d} alongside this change, or confirm the coupling no longer holds.`,suppressionHint:`scip-query: ignore co-change-partner ${h} -- <reason>`})}}function DI(e,t,n){n.checksRun.push("doc-reference");for(let r of Fd(e,t)){if(t.has(r.doc))continue;let i=Sn("doc-reference",r.doc,r.cited.join("|"));n.findings.push({id:i,check:"doc-reference",severity:"warning",evidence:"change-graph",confidence:1,file:r.doc,relatedFiles:r.cited,message:`${r.doc} cites ${r.cited.join(", ")} \u2014 changed in this diff, doc untouched`,why:[`${r.cited.join(", ")} changed in this diff.`,`${r.doc} cites the changed file(s) but was not updated in the same diff.`],remediation:`Re-read ${r.doc} and update its claims, or update its citations.`,suppressionHint:`scip-query: ignore doc-reference ${i} -- <reason>`})}}function kI(e,t,n){n.checksRun.push("unused-params");for(let r of qr(e,{files:t,limit:50})){let i=Sn("unused-params",r.symbol,r.file,r.unusedTrailing.join("|"));n.findings.push({id: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.",suppressionHint:`scip-query: ignore unused-params ${i} -- <reason>`})}}function wI(e,t,n,r){r.checksRun.push("new-dead");let i=new N(e);for(let o of t){if(n(o)||o.fanIn>0||i.fileKind(o.file)==="test"||xe(e,o.file)||le(e,o.symbol,o.file))continue;let s=Sn("new-dead",o.symbol,o.file);r.findings.push({id:s,check:"new-dead",severity:"warning",evidence:"graph-fact",confidence:.9,file:o.file,symbol:o.symbol,message:`${o.shortName} (${o.file}) was changed but has zero indexed consumers`,why:[`${o.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:"Wire it up, or remove it before it becomes permanent dead code.",suppressionHint:`scip-query: ignore new-dead ${s} -- <reason>`})}}function NI(e,t,n){let r=new Map(n.renamedFiles.map(o=>[o.to,o.from])),i=new Map;return o=>{let s=r.get(o.file);if(!s)return!1;let a=$(o.symbol);if(!a)return!1;let c=i.get(s);return c===void 0&&(c=$r(e,t,s),i.set(s,c)),c!==null&&PI(c,a)}}function PI(e,t){return new RegExp(`\\b${_I(t)}\\b`).test(e)}function _I(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function EI(e,t){if(!Hd(ro(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=Vr(e);for(let r of n.newFindings){let i=Sn("baseline",r);t.findings.push({id:i,check:"baseline",severity:"error",evidence:"baseline",confidence:1,message:`new finding vs committed baseline: ${r}`,why:["A committed health baseline exists.","The current health result contains a finding not present in that baseline."],remediation:"Fix the finding, or knowingly accept it via health --write-baseline.",suppressionHint:`scip-query: ignore baseline ${i} -- <reason>`})}}function Sn(e,...t){return`SQ${xI("sha256").update([e,...t].join("\0")).digest("hex").slice(0,12).toUpperCase()}`}var FI=.7,qd=.62,Wd=.45;function ba(e,t={}){let{windowCommits:n=100,limit:r=30,scope:i,scanLimit:o}=t,s=Rd(e);if(!s)return{available:!1,windowCommits:n,findings:[]};if(r<=0)return{available:!0,windowCommits:n,findings:[]};let c=TI(e,{limit:r,minSimilarity:t.minSimilarity,scanLimit:o,scope:i,semantic:t.semantic}).map(l=>BI(l,s,n)).filter(l=>l!==null);return c.sort((l,u)=>(l.kind===u.kind?0:l.kind==="echo"?-1:1)||u.similarity-l.similarity||l.echoFile.localeCompare(u.echoFile)||l.echoSymbol.localeCompare(u.echoSymbol)||l.domain.localeCompare(u.domain)),{available:!0,windowCommits:n,findings:c.slice(0,r)}}function TI(e,t){let n=VI(t.limit);return[...AI(e,{scope:t.scope,minSimilarity:t.minSimilarity??FI,limit:n,scanLimit:t.scanLimit,semantic:t.semantic}),...$I(e,{scope:t.scope,minSimilarity:t.minSimilarity??qd,limit:n,scanLimit:t.scanLimit}),...MI(e,{scope:t.scope,minSimilarity:t.minSimilarity??Wd,limit:n,scanLimit:t.scanLimit}),...OI(e,{scope:t.scope,minSimilarity:t.minSimilarity??qd,limit:n,scanLimit:t.scanLimit}),...jI(e,{scope:t.scope,minSimilarity:t.minSimilarity??Wd,limit:n,scanLimit:t.scanLimit})]}function AI(e,t){return bt(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic}).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 $I(e,t){return sn(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,scanLimit:t.scanLimit}).filter(n=>n.fileA!==n.fileB).map(n=>({domain:"react-component",basis:"jsx-structure",symbolA:n.componentA,fileA:n.fileA,symbolB:n.componentB,fileB:n.fileB,similarity:n.similarity,sharedEvidence:so(["component",n.sharedComponents],["tag",n.sharedNativeTags],["prop",n.sharedProps],["event",n.sharedEvents],["binding",n.sharedBindings]),sharedCallees:[]}))}function MI(e,t){return cn(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,scanLimit:t.scanLimit}).filter(n=>n.fileA!==n.fileB).map(n=>({domain:"react-hook",basis:"react-behavior",symbolA:n.componentA,fileA:n.fileA,symbolB:n.componentB,fileB:n.fileB,similarity:n.similarity,sharedEvidence:so(["hook",n.sharedHooks],["react-hook",n.sharedReactHooks],["effect",n.sharedEffects],["state",n.sharedState],["request",n.sharedRequests],["handler",n.sharedHandlers],["action",n.sharedHandlerVerbs]),sharedCallees:[]}))}function OI(e,t){return ln(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,scanLimit:t.scanLimit}).filter(n=>n.fileA!==n.fileB).map(n=>({domain:"vue-component",basis:"vue-template",symbolA:oo(n.fileA),fileA:n.fileA,symbolB:oo(n.fileB),fileB:n.fileB,similarity:n.similarity,sharedEvidence:so(["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]),sharedCallees:[]}))}function jI(e,t){return un(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,scanLimit:t.scanLimit}).filter(n=>n.fileA!==n.fileB).map(n=>({domain:"vue-composable",basis:"vue-behavior",symbolA:oo(n.fileA),fileA:n.fileA,symbolB:oo(n.fileB),fileB:n.fileB,similarity:n.similarity,sharedEvidence:so(["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]),sharedCallees:[]}))}function BI(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 VI(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function so(...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 oo(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var HI=ie("suppression-inventory",{clearGroups:["whole-project"]});function ao(e){return HI.get(e,()=>qI(e))}function qI(e){let t={dead:0,stale:0,wrapper:0,passthrough:0,drift:0,extract:0,similar:0,uncategorized:0},n=new Map,r=0;for(let i of Le(e)){let o=A(e,i);if(!(!o||!o.includes("scip-query")))for(let s of o.split(/\r?\n/)){let a=Bo(s);if(a===null)continue;r+=1,n.set(i,(n.get(i)??0)+1);let c=WI(a);t[c]+=1}}return{total:r,byCategory:t,byFile:n}}function WI(e){if(!e)return"uncategorized";let t=e.toLowerCase();return t==="dead-code"?"dead":t}import{readFileSync as UI}from"fs";import{join as JI}from"path";function Wr(e,t,n={}){let r=B(e,t);if(!r)return null;let i=new N(e),o=XI(zI(e,r.relativePath,r.startLine,r.endLine),GI(e,r.relativePath)),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:y(r.symbol),relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,loc:s,branches:o,cyclomaticEstimate:o+1,calleeCount:l.size,fanIn:KI(e,r.symbolId),fanOut:QI(c,r.relativePath)}}function GI(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function zI(e,t,n,r){try{return UI(JI(e.config.projectRoot,t),"utf-8").split(`
568
537
  `).slice(n,r+1).join(`
569
- `)}catch{return""}}function Hx(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
538
+ `)}catch{return""}}function KI(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
570
539
  FROM mentions m
571
540
  JOIN chunks c ON m.chunk_id = c.id
572
- WHERE m.symbol_id = ? AND m.role != 1`,t)?.c??0}function qx(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function Vx(e,t){let n=_t(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 or(e,t,n={}){let r=A(e,t);if(!r)return null;let i=[{file:r.relativePath,line:r.startLine}],o=gt(e,r,{semantic:n.semantic}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?b(c.enclosingSymbol):"(top-level)"})),{producers:s,consumers:a}=Wx(e,r,o,{semantic:n.semantic!==!1});return{symbol:r.symbol,shortName:b(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:b(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)":b(c.symbol),file:c.file}))}}function Wx(e,t,n,r){let i=gn(Se(e,t,{limit:30,semantic:r.semantic}).map(a=>({symbol:a.symbol,file:a.file}))),o=gn(De(e,t,{limit:30,semantic:r.semantic})),s=o.length>0?o:gn(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{producers:i,consumers:s}}function yn(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,o=A(e,t);return o?r==="backward"?Ux(e,o,i,{semantic:n.semantic!==!1}):Gx(e,o,{semantic:n.semantic!==!1}):null}function Ux(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=Se(e,l,{semantic:r.semantic});for(let m of u){if(o.has(m.symbol))continue;o.add(m.symbol),i.push({symbol:m.symbol,shortName:b(m.symbol),file:m.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let d=on(e,m.symbol);d&&!e.isIgnored(d.relativePath)&&c.push(d)}}s=c}return{symbol:t.symbol,shortName:b(t.symbol),direction:"backward",connectedSymbols:i}}function Gx(e,t,n){let r=new Set,i=[],o=new _(e);for(let s of gt(e,t,{semantic:n.semantic})){if(i.length>=30)break;let a=s.enclosingSymbol??Ce(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=on(e,a);!c||e.isIgnored(c.relativePath)||r.has(c.symbol)||(r.add(c.symbol),i.push({symbol:c.symbol,shortName:b(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:b(t.symbol),direction:"forward",connectedSymbols:i}}function ss(e,t,n={}){let r=n.impactDepth??3,i=n.sliceDepth??3,o=n.semantic,s=!zx(t),a=s?$n(e,t,{semantic:o}):{definitions:[],referencedBy:[]},c=s?Wn(e,t,{semantic:o}):null,l=s?ir(e,t,{semantic:o}):null,u=s?or(e,t,{semantic:o}):null,m=s?yn(e,t,{direction:"backward",maxDepth:i,semantic:o}):null,d=s?yn(e,t,{direction:"forward",maxDepth:i,semantic:o}):null,p=s?Kn(e,t,{maxDepth:r,scope:n.scope}):[],h=Qn(e,t,{semantic:o}),f=jn(e,t),y=Bn(e,t),R=Hn(e,t),k=qn(e,t),S={symbol:a.definitions.length>0||a.referencedBy.length>0||c!==null||l!==null||u!==null||m!==null||d!==null||p.length>0,file:h!==null||f.length>0||y.length>0,module:R.files.length>0||R.symbols.length>0||k.length>0},x=[];!S.symbol&&!S.file&&!S.module&&x.push("No symbol, file, or module matched target.");let D=h?.file??a.definitions[0]?.relativePath??null;return{target:t,matched:S,history:Jx(e,D),trace:a,callGraph:c,complexity:l,dataflow:u,backwardSlice:m,forwardSlice:d,affected:p,changeSurface:h,deps:f,rdeps:y,system:R,surface:k,warnings:x}}function Jx(e,t){let n={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return n;let r=Xr(e);if(!r)return n;let i=$t(e,t,{limit:5});return{available:!0,file:t,churn:r.get(t)??{changes:0,fixChanges:0,lastChangedAt:0},coChangePartners:i.findings.map(o=>({file:o.fileA===t?o.fileB:o.fileA,together:o.together,confidence:o.confidence})),suppressionsInFile:si(e).byFile.get(t)??0}}function zx(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}function sr(e,t){let{scope:n,minLoc:r=10,limit:i=30,scanLimit:o}=t??{},s=new _(e);return _e({candidates:()=>s.productionCallableDefinitions({scope:n,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,prepare:a=>({callerMap:s.crossFileCallerMap(a,{semantic:t?.semantic!==!1}),calleeMap:s.calleeMap(a,{semantic:t?.semantic!==!1})}),evaluate:(a,c)=>Kx(a,c,r),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:i})}function Kx(e,t,n){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=o.filter(l=>l.file!==e.relativePath),a=new Set(s.map(l=>`${l.symbol}|${l.file}`)).size,c=new Set(o.map(l=>`${l.symbol}|${l.file}`)).size;return{symbol:e.symbol,shortName:b(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:r,fanIn:i,fanOut:a,calleeCount:c,score:Math.round(r/50*(i/5)*Math.max(a/5,1)*100)/100}}function Kl(e){let t=Zx(e),{breakdown:n}=tC(e),r=zl(n,"risk"),i=zl(n,"hygiene");return{score:Math.min(r,i),riskScore:r,hygieneScore:i,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,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,passthroughs:e.passthroughs.count,staleTypes:e.stale.count,driftedFiles:e.drift.count,complexityHotspotCount:e.complexity.extremeCount,hiddenCouplingPairs:e.gitEvidence?.hiddenCoupling.pairCount??null},axes:Qx(e),validation:Xx(e),suppressions:e.suppressions,actions:t,topComplexity:e.complexity.top,warnings:e.warnings.length>0?e.warnings:void 0}}function Qx(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:Yx(e),evidenceQuality:{graphFindings:e.dead.count+e.isolated.count+e.realCycleCount,heuristicFindings:e.similarCount+e.extractCount+e.wrappers.count+e.passthroughs.count+e.stale.count+e.drift.count,userSuppressed:e.suppressions?.total??0}}}function Yx(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:bn(n.score*Math.log2(1+r))}}).sort((n,r)=>r.weighted-n.weighted):null}function Xx(e){let t=e.gitEvidence?.fileStats;if(!t)return null;let n={dead:e.dead.files??[],isolated:e.isolated.files??[],wrappers:e.wrappers.files??[],passthroughs:e.passthroughs.files??[],stale:e.stale.files??[]},r=new Set(Object.values(n).flat()),i=0,o=0,s=0;for(let[u,m]of Object.entries(t))r.has(u)?i+=m.fixChanges:(o+=m.fixChanges,s+=1);let a=r.size>0?bn(i/r.size):0,c=s>0?bn(o/s):0,l={};for(let[u,m]of Object.entries(n)){let d=new Set(m);if(d.size===0)continue;let p=0;for(let f of d)p+=t[f]?.fixChanges??0;let h=bn(p/d.size);l[u]={flaggedFiles:d.size,fixDensity:h,lift:c>0?bn(h/c):null}}return{flaggedFiles:r.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:r.size>0&&c>0?bn(a/c):null,byCategory:l}}function bn(e){return Math.round(e*100)/100}function Zx(e){let t=[];if(e.dead.count>0&&t.push({category:"Dead code",evidence:"graph-fact",description:`${e.dead.count} symbols with zero references anywhere \u2014 safe to delete`,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} cycle(s) \u2014 break with dependency inversion or module restructuring`,effort:"medium",impact:"high",count:e.realCycleCount,locRecoverable:0}),e.similarCount>0&&t.push({category:"Similar functions",evidence:"heuristic",description:`${e.similarCount} pairs with real logic overlap (beyond shared imports) \u2014 consolidation candidates`,effort:"medium",impact:"medium",count:e.similarCount,locRecoverable:0}),e.extractCount>0&&t.push({category:"Extraction candidates",evidence:"heuristic",description:`${e.extractCount} large functions with isolated callee clusters \u2014 extract method opportunities`,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 that could be inlined`,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 just forward to one callee \u2014 unnecessary indirection`,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 premature abstraction`,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(", "),effort:e.drift.layerViolations>0?"medium":"low",impact:e.drift.layerViolations>0?"medium":"low",count:e.drift.count,locRecoverable:0})}if(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 dependency edge`+(i?` (e.g. ${i.fileA} \u2194 ${i.fileB})`:"")+" \u2014 name the shared concept or enforce the sync",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 eC={"dead-code":"risk",isolated:"risk",cycles:"risk",complexity:"risk","hidden-coupling":"risk",similar:"hygiene",extract:"hygiene",wrappers:"hygiene",passthroughs:"hygiene","stale-abstractions":"hygiene",drift:"hygiene"};function zl(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 tC(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),r=[],i=(m,d,p)=>{d>0&&r.push({axis:m,points:d,detail:p,kind:eC[m]??"hygiene"})},o=e.dead.count/n;i("dead-code",Math.min(20,Math.round(o*200)),`${e.dead.count} dead symbols (${e.dead.loc} LOC deletable)`);let s=e.isolated.count/n;i("isolated",Math.min(10,Math.round(s*200)),`${e.isolated.count} isolated symbols (${e.isolated.loc} LOC deletable)`),i("cycles",Math.min(15,e.realCycleCount*5),`${e.realCycleCount} real dependency cycle(s)`);let a=e.similarCount/n*1e3;i("similar",Math.min(10,Math.round(a)),`${e.similarCount} similar function pair(s)`);let c=e.extractCount/n*1e3;i("extract",Math.min(5,Math.round(c/2)),`${e.extractCount} extraction candidate(s)`),i("wrappers",Math.min(3,e.wrappers.count),`${e.wrappers.count} wrapper candidate(s)`),i("passthroughs",Math.min(3,e.passthroughs.count),`${e.passthroughs.count} passthrough candidate(s)`);let l=e.stale.count/Math.max(n*.1,1);i("stale-abstractions",Math.min(8,Math.round(l*10)),`${e.stale.count} stale abstraction(s)`);let u=e.drift.count/t;return i("drift",Math.min(5,Math.round(u*50)),`${e.drift.count} drift finding(s)`),i("complexity",Math.min(5,e.complexity.extremeCount*2),`${e.complexity.extremeCount} extreme complexity hotspot(s)`),e.gitEvidence&&i("hidden-coupling",Math.min(5,e.gitEvidence.hiddenCoupling.pairCount),`${e.gitEvidence.hiddenCoupling.pairCount} co-changing pair(s) without a dependency edge`),{breakdown:r}}import{getHeapStatistics as nC}from"v8";var rC=64*1024*1024;function as(){let e=globalThis.gc;if(!e)return;let t=nC();t.heap_size_limit-t.used_heap_size<rC||e()}var iC=50,oC=75e3,sC=5e3,Ql=2500,ar=["overview","dead","isolated","cycles","similar","extract-candidates","wrapper-candidates","passthrough-candidates","stale-abstractions","drift","complexity-hotspots","git-evidence","suppressions"],aC={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:uC(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:mC(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:dC(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:pC(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:fC(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:gC(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:hC(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:yC(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:xC(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:CC(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:bC(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:SC(e,n)})};function cs(e,t,n={}){return cC(e,n.full===!0,(r,i)=>aC[t](e,n.scope,i,r))}function cC(e,t,n){let r=we(e),i=RC(r,t);try{return n(r,i)}finally{bo(e,{semanticProvider:!0}),as()}}function ls(e){return Kl(lC(e))}function lC(e){let t=Ae(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,dead:Ae(e,"dead").dead,isolated:Ae(e,"isolated").isolated,realCycleCount:Ae(e,"cycles").realCycleCount,similarCount:Ae(e,"similar").similarCount,extractCount:Ae(e,"extract-candidates").extractCount,wrappers:Ae(e,"wrapper-candidates").wrappers,passthroughs:Ae(e,"passthrough-candidates").passthroughs,stale:Ae(e,"stale-abstractions").stale,drift:Ae(e,"drift").drift,complexity:Ae(e,"complexity-hotspots").complexity,gitEvidence:Yl(e,"git-evidence")?.gitEvidence??null,suppressions:Yl(e,"suppressions")?.suppressions??null}}function Yl(e,t){return e.find(n=>n.phase===t)}function Ae(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function uC(e,t,n){return Te(e,n,"dead",()=>{let r=Ye(e,{scope:t,...X.dead,scanLimit:n.candidateScanLimit});return us(DC(e,r.symbols))})}function mC(e,t,n){return Te(e,n,"isolated",()=>{let r=Tt(e,{scope:t,...X.isolated,scanLimit:n.candidateScanLimit});return us(NC(e,r))})}function dC(e,t,n){return Te(e,n,"cycles",()=>At(e,{scope:t}).filter(i=>i.kind==="real").length)}function pC(e,t,n){return Te(e,n,"similar",()=>Xe(e,{scope:t,...X.similar,scanLimit:n.candidateScanLimit}).length)}function fC(e,t,n){return Te(e,n,"extract-candidates",()=>Mt(e,{scope:t,...X.extract,scanLimit:n.candidateScanLimit}).length)}function gC(e,t,n){return Xl(e,n,"wrapper-candidates",()=>Vt(e,{scope:t,...X.wrappers,scanLimit:n.candidateScanLimit}))}function hC(e,t,n){return Xl(e,n,"passthrough-candidates",()=>Ht(e,{scope:t,...X.passthroughs,scanLimit:n.candidateScanLimit}))}function yC(e,t,n){return Te(e,n,"stale-abstractions",()=>{let r=qt(e,{scope:t,...X.stale,scanLimit:n.candidateScanLimit}),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 bC(e,t){return Te(e,t,"git-evidence",()=>{let n=Xr(e);if(!n)return null;let r=$t(e,void 0,{limit:50}),i={};for(let[o,s]of n)i[o]={changes:s.changes,fixChanges:s.fixChanges};return{amplification:Fl(e),hiddenCoupling:{pairCount:r.findings.length,top:r.findings.slice(0,5).map(o=>({fileA:o.fileA,fileB:o.fileB,together:o.together,confidence:o.confidence}))},fileStats:i}})}function SC(e,t){return Te(e,t,"suppressions",()=>{let n=si(e);return{total:n.total,byCategory:{...n.byCategory}}})}function xC(e,t,n){return Te(e,n,"drift",()=>{let r=Bt(e,{scope:t,...X.drift});return{count:r.unusedImports+r.layerViolations,unusedImports:r.unusedImports,layerViolations:r.layerViolations}})}function CC(e,t,n){return Te(e,n,"complexity-hotspots",()=>{let r=sr(e,{scope:t,minLoc:10,limit:10,scanLimit:n.candidateScanLimit,semantic:!1});return{top:r.slice(0,5).map(i=>({symbol:i.shortName,score:i.score,file:i.file})),extremeCount:r.filter(i=>i.score>iC).length}})}function RC(e,t){return e.symbols>=oC||e.documents>=sC?t?{candidateScanLimit:void 0,releaseCachesBetweenPhases:!0,warnings:["Large index detected; running unbounded health analyses because --full was supplied."]}:{candidateScanLimit:Ql,releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${Ql} symbols. Run "scip-query health --full" for unbounded candidate counts.`]}:{candidateScanLimit:void 0,releaseCachesBetweenPhases:!0,warnings:[]}}function IC(e,t){t.releaseCachesBetweenPhases&&(bo(e),as())}function Te(e,t,n,r){vC(n);try{return r()}finally{IC(e,t)}}function Xl(e,t,n,r){return Te(e,t,n,()=>us(r()))}function vC(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function DC(e,t){return t.filter(n=>!ue(e,n.relativePath)&&!re(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function NC(e,t){return t.filter(n=>!ue(e,n.relativePath)&&!re(e,n.symbol,n.relativePath))}function us(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 ms(e,t,n,r={}){let i=A(e,t),o=A(e,n);if(!i||!o)return null;let s=new Set(Se(e,i,{semantic:r.semantic}).map(y=>y.symbol)),a=new Set(Se(e,o,{semantic:r.semantic}).map(y=>y.symbol)),c=[];for(let y of s)a.has(y)&&c.push(y);let l=[];for(let y of s)a.has(y)||l.push(y);let u=[];for(let y of a)s.has(y)||u.push(y);let m=new Set([...s,...a]),d=m.size>0?c.length/m.size:0,p;m.size===0?p="Neither function calls other tracked symbols. There is no callee-pattern evidence for consolidation; inspect the source bodies directly.":c.length===0?p="These functions do not share any callees. They are not a callee-based consolidation candidate.":l.length===0&&u.length===0?p="These functions have identical tracked callee sets. They are a strong structural match, but identical callees do not prove interchangeable semantics; inspect signatures, control flow, and return values before consolidating.":l.length===0?p="A's tracked callees are a subset of B's. B may subsume part of A's structure, but verify signatures, guards, and non-call logic before replacing A with B.":u.length===0?p="B's tracked callees are a subset of A's. A may subsume part of B's structure, but verify signatures, guards, and non-call logic before replacing B with A.":l.length<=2&&u.length<=2?p=`Create a shared function with the ${c.length} common callees. Pass the ${l.length+u.length} divergent callees as parameters or strategy callbacks.`:p=`Extract the ${c.length} shared callees into a common helper. Each function calls the helper plus its own unique logic (${l.length} callees in A, ${u.length} in B).`;let h=i.endLine-i.startLine+1,f=o.endLine-o.startLine+1;return{symbolA:{symbol:i.symbol,shortName:b(i.symbol),file:i.relativePath,loc:h},symbolB:{symbol:o.symbol,shortName:b(o.symbol),file:o.relativePath,loc:f},similarity:d,sharedCallees:c.map(b),uniqueToA:l.map(b),uniqueToB:u.map(b),consolidationStrategy:p}}import{readFileSync as Zl}from"fs";import{extname as _C,join as eu}from"path";function ds(e,t,n={}){let{context:r=0}=n,i=LC(t);if(i)return kC(e,i.filePath,i.startLine,i.endLine,r);let o=A(e,t);return o?wC(e,o,r):null}function LC(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 wC(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=eu(e.config.projectRoot,t.relativePath),o;try{o=Zl(i,"utf-8")}catch{return null}let s=o.split(`
541
+ WHERE m.symbol_id = ? AND m.role != 1`,t)?.c??0}function QI(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function XI(e,t){let n=Kt(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 Ur(e,t,n={}){let r=B(e,t);if(!r)return null;let i=[{file:r.relativePath,line:r.startLine}],o=$t(e,r,{semantic:n.semantic}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?y(c.enclosingSymbol):"(top-level)"})),{producers:s,consumers:a}=YI(e,r,o,{semantic:n.semantic!==!1});return{symbol:r.symbol,shortName:y(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:y(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)":y(c.symbol),file:c.file}))}}function YI(e,t,n,r){let i=Gn(_e(e,t,{limit:30,semantic:r.semantic}).map(a=>({symbol:a.symbol,file:a.file}))),o=Gn(je(e,t,{limit:30,semantic:r.semantic})),s=o.length>0?o:Gn(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{producers:i,consumers:s}}function Qn(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,o=B(e,t);return o?r==="backward"?ZI(e,o,i,{semantic:n.semantic!==!1}):eD(e,o,{semantic:n.semantic!==!1}):null}function ZI(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=_e(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:y(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let m=$n(e,d.symbol);m&&!e.isIgnored(m.relativePath)&&c.push(m)}}s=c}return{symbol:t.symbol,shortName:y(t.symbol),direction:"backward",connectedSymbols:i}}function eD(e,t,n){let r=new Set,i=[],o=new N(e);for(let s of $t(e,t,{semantic:n.semantic})){if(i.length>=30)break;let a=s.enclosingSymbol??Ae(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=$n(e,a);!c||e.isIgnored(c.relativePath)||r.has(c.symbol)||(r.add(c.symbol),i.push({symbol:c.symbol,shortName:y(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:y(t.symbol),direction:"forward",connectedSymbols:i}}function ya(e,t,n={}){let r=n.impactDepth??3,i=n.sliceDepth??3,o=n.semantic,s=!nD(t),a=s?vr(e,t,{semantic:o}):{definitions:[],referencedBy:[]},c=s?wr(e,t,{semantic:o}):null,l=s?Wr(e,t,{semantic:o}):null,u=s?Ur(e,t,{semantic:o}):null,d=s?Qn(e,t,{direction:"backward",maxDepth:i,semantic:o}):null,m=s?Qn(e,t,{direction:"forward",maxDepth:i,semantic:o}):null,f=s?Tr(e,t,{maxDepth:r,scope:n.scope}):[],g=Ar(e,t,{semantic:o}),h=Rr(e,t),b=Lr(e,t),L=Ir(e,t),F=Dr(e,t),k={symbol:a.definitions.length>0||a.referencedBy.length>0||c!==null||l!==null||u!==null||d!==null||m!==null||f.length>0,file:g!==null||h.length>0||b.length>0,module:L.files.length>0||L.symbols.length>0||F.length>0},E=[];!k.symbol&&!k.file&&!k.module&&E.push("No symbol, file, or module matched target.");let C=g?.file??a.definitions[0]?.relativePath??null;return{target:t,matched:k,history:tD(e,C),trace:a,callGraph:c,complexity:l,dataflow:u,backwardSlice:d,forwardSlice:m,affected:f,changeSurface:g,deps:h,rdeps:b,system:L,surface:F,warnings:E}}function tD(e,t){let n={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return n;let r=Qi(e);if(!r)return n;let i=pn(e,t,{limit:5});return{available:!0,file:t,churn:r.get(t)??{changes:0,fixChanges:0,lastChangedAt:0},coChangePartners:i.findings.map(o=>({file:o.fileA===t?o.fileB:o.fileA,together:o.together,confidence:o.confidence})),suppressionsInFile:ao(e).byFile.get(t)??0}}function nD(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}function Jr(e,t){let{scope:n,minLoc:r=10,limit:i=30,scanLimit:o}=t??{},s=new N(e);return Ve({candidates:()=>s.productionCallableDefinitions({scope:n,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,prepare:a=>({callerMap:s.crossFileCallerMap(a,{semantic:t?.semantic!==!1}),calleeMap:s.calleeMap(a,{semantic:t?.semantic!==!1})}),evaluate:(a,c)=>rD(a,c,r),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:i})}function rD(e,t,n){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=o.filter(l=>l.file!==e.relativePath),a=new Set(s.map(l=>`${l.symbol}|${l.file}`)).size,c=new Set(o.map(l=>`${l.symbol}|${l.file}`)).size;return{symbol:e.symbol,shortName:y(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:r,fanIn:i,fanOut:a,calleeCount:c,score:Math.round(r/50*(i/5)*Math.max(a/5,1)*100)/100}}function Xn(e){return e.scoreCount??e.count}function Kd(e){let t=aD(e),{breakdown:n,pressure:r}=cD(e),i=zd(n,"risk"),o=zd(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,reactComponentDuplicatePairs:e.reactComponentDuplicates.count,reactHookCandidatePairs:e.reactHookCandidates.count,reactHookCandidateScoreCount:Xn(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:Xn(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,passthroughs:e.passthroughs.count,staleTypes:e.stale.count,driftedFiles:e.drift.count,complexityHotspotCount:e.complexity.extremeCount,hiddenCouplingPairs:e.gitEvidence?.hiddenCoupling.pairCount??null},axes:iD(e),validation:sD(e),suppressions:e.suppressions,actions:t,pressure:r,topComplexity:e.complexity.top,warnings:e.warnings.length>0?e.warnings:void 0}}function iD(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:oD(e),evidenceQuality:{graphFindings:e.dead.count+e.isolated.count+e.realCycleCount,heuristicFindings:e.similarCount+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 oD(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:ot(n.score*Math.log2(1+r))}}).sort((n,r)=>r.weighted-n.weighted):null}function sD(e){let t=e.gitEvidence?.fileStats;if(!t)return null;let n={dead:e.dead.files??[],isolated:e.isolated.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?ot(i/r.size):0,c=s>0?ot(o/s):0,l={};for(let[u,d]of Object.entries(n)){let m=new Set(d);if(m.size===0)continue;let f=0;for(let h of m)f+=t[h]?.fixChanges??0;let g=ot(f/m.size);l[u]={flaggedFiles:m.size,fixDensity:g,lift:c>0?ot(g/c):null}}return{flaggedFiles:r.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:r.size>0&&c>0?ot(a/c):null,byCategory:l}}function ot(e){return Math.round(e*100)/100}function Qd(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function Ud(e){let t=Xn(e);return Math.abs(t-e.count)<.01?"":` (${Qd(t)} score-weighted after existing shared infrastructure discount)`}function Jd(e,t){let n=Xn(e),r=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?r:`${r} (${Qd(n)} score-weighted)`}function aD(e){let t=[];if(e.dead.count>0&&t.push({category:"Dead code",evidence:"graph-fact",description:`${e.dead.count} symbols with zero references anywhere \u2014 safe to delete`,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} cycle(s) \u2014 break with dependency inversion or module restructuring`,effort:"medium",impact:"high",count:e.realCycleCount,locRecoverable:0}),e.similarCount>0&&t.push({category:"Similar functions",evidence:"heuristic",description:`${e.similarCount} pairs with real logic overlap (beyond shared imports) \u2014 consolidation candidates`,effort:"medium",impact:"medium",count:e.similarCount,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 extract or reuse the shared UI concept`,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${Ud(e.reactHookCandidates)} \u2014 extract or reuse a hook`,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 extract or reuse the shared UI concept`,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${Ud(e.vueComposableCandidates)} \u2014 extract or reuse a composable`,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 extract method opportunities`,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 that could be inlined`,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 just forward to one callee \u2014 unnecessary indirection`,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 premature abstraction`,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(", "),effort:e.drift.layerViolations>0?"medium":"low",impact:e.drift.layerViolations>0?"medium":"low",count:e.drift.count,locRecoverable:0})}if(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`+(i?` (e.g. ${i.fileA} \u2194 ${i.fileB})`:"")+" \u2014 name the shared concept or enforce the sync",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 Gd={"dead-code":"risk",isolated:"risk",cycles:"risk",complexity:"risk","hidden-coupling":"risk","cycles-pressure":"risk","complexity-pressure":"risk","hidden-coupling-pressure":"risk",similar:"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","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 zd(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 cD(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),r=[],i=[],o=(C,w,M)=>{w>0&&r.push({axis:C,points:w,detail:M,kind:Gd[C]??"hygiene"})},s=(C,w,M,j,ye,Fe,Dt)=>{let lt=Math.max(j,1);if(M<=lt)return;let Ao=M/lt,$o=Math.min(ye,Math.ceil(Math.log2(Ao)*Fe));if($o<=0)return;let Kf=Gd[C]??"hygiene";i.push({axis:C,category:w,kind:Kf,count:M,threshold:ot(lt),ratio:ot(Ao),extraPenalty:$o}),o(C,$o,`${M} ${Dt} exceed pressure threshold ${ot(lt)} (${ot(Ao)}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.reactComponentDuplicates.count/t*1e3;o("react-component-duplicates",Math.min(10,Math.round(u)),`${e.reactComponentDuplicates.count} duplicated React component pair(s)`);let d=Xn(e.reactHookCandidates),m=d/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(m)),Jd(e.reactHookCandidates,"duplicated React behavior pair(s)"));let f=e.reactLargeComponentPressure.count/t*1e3;o("react-large-component-pressure",Math.min(5,Math.round(f/2)),`${e.reactLargeComponentPressure.count} large React component pressure file(s)`);let g=e.vueComponentDuplicates.count/t*1e3;o("vue-component-duplicates",Math.min(10,Math.round(g)),`${e.vueComponentDuplicates.count} duplicated Vue component pair(s)`);let h=Xn(e.vueComposableCandidates),b=h/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(b)),Jd(e.vueComposableCandidates,"duplicated Vue behavior pair(s)"));let L=e.vueLargeViewPressure.count/t*1e3;o("vue-large-view-pressure",Math.min(5,Math.round(L/2)),`${e.vueLargeViewPressure.count} large Vue view pressure file(s)`);let F=e.extractCount/n*1e3;o("extract",Math.min(5,Math.round(F/2)),`${e.extractCount} extraction candidate(s)`),o("wrappers",Math.min(3,e.wrappers.count),`${e.wrappers.count} wrapper candidate(s)`),o("passthroughs",Math.min(3,e.passthroughs.count),`${e.passthroughs.count} passthrough candidate(s)`);let k=e.stale.count/Math.max(n*.1,1);o("stale-abstractions",Math.min(8,Math.round(k*10)),`${e.stale.count} stale abstraction(s)`);let E=e.drift.count/t;return o("drift",Math.min(5,Math.round(E*50)),`${e.drift.count} drift finding(s)`),o("complexity",Math.min(5,e.complexity.extremeCount*2),`${e.complexity.extremeCount} extreme complexity hotspot(s)`),e.gitEvidence&&o("hidden-coupling",Math.min(5,e.gitEvidence.hiddenCoupling.pairCount),`${e.gitEvidence.hiddenCoupling.pairCount} co-changing pair(s) without a structural link`),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&&s("hidden-coupling-pressure","Hidden coupling",e.gitEvidence.hiddenCoupling.pairCount,50,10,4,"co-changing pair(s)"),s("similar-pressure","Similar functions",e.similarCount,Math.max(50,n*.01),8,4,"similar function pair(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",d,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",h,Math.max(10,t*.01),8,4,"duplicated Vue behavior pair(s)"),s("vue-large-view-pressure-pressure","Large Vue views",e.vueLargeViewPressure.count,Math.max(10,t*.01),4,2,"large Vue view pressure file(s)"),s("extract-pressure","Extraction candidates",e.extractCount,Math.max(50,n*.01),4,2,"extraction candidate(s)"),s("wrappers-pressure","Wrapper functions",e.wrappers.count,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",e.passthroughs.count,50,4,2,"passthrough candidate(s)"),s("stale-abstractions-pressure","Stale abstractions",e.stale.count,Math.max(50,n*.02),4,2,"stale abstraction(s)"),s("drift-pressure","Structural drift",e.drift.count,Math.max(10,t*.1),4,2,"drift finding(s)"),{breakdown:r,pressure:i}}import{getHeapStatistics as lD}from"v8";var uD=64*1024*1024;function Sa(){let e=globalThis.gc;if(!e)return;let t=lD();t.heap_size_limit-t.used_heap_size<uD||e()}var dD=50,mD=75e3,pD=5e3,Xd=2500,Yd=50,fD=10,Gr=["overview","dead","isolated","cycles","similar","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"],gD={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:yD(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:SD(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:xD(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:CD(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:RD(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:LD(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:ID(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:DD(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:kD(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:wD(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:vD(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:ND(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:PD(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:_D(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:TD(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:AD(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:ED(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:FD(e,n)})};function xa(e,t,n={}){return hD(e,n.full===!0,(r,i)=>gD[t](e,n.scope,i,r))}function hD(e,t,n){let r=Te(e),i=$D(r,t);try{return n(r,i)}finally{ws(e,{semanticProvider:!0}),Sa()}}function Ca(e){return Kd(bD(e))}function bD(e){let t=de(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,dead:de(e,"dead").dead,isolated:de(e,"isolated").isolated,realCycleCount:de(e,"cycles").realCycleCount,similarCount:de(e,"similar").similarCount,reactComponentDuplicates:de(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:de(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:de(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:de(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:de(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:de(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:de(e,"extract-candidates").extractCount,wrappers:de(e,"wrapper-candidates").wrappers,passthroughs:de(e,"passthrough-candidates").passthroughs,stale:de(e,"stale-abstractions").stale,drift:de(e,"drift").drift,complexity:de(e,"complexity-hotspots").complexity,gitEvidence:Zd(e,"git-evidence")?.gitEvidence??null,suppressions:Zd(e,"suppressions")?.suppressions??null}}function Zd(e,t){return e.find(n=>n.phase===t)}function de(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function yD(e,t,n){return me(e,n,"dead",()=>{let r=ht(e,{scope:t,...re.dead,scanLimit:n.candidateScanLimit});return co(jD(e,r.symbols))})}function SD(e,t,n){return me(e,n,"isolated",()=>{let r=on(e,{scope:t,...re.isolated,scanLimit:n.candidateScanLimit});return co(BD(e,r))})}function xD(e,t,n){return me(e,n,"cycles",()=>rn(e,{scope:t}).filter(i=>i.kind==="real").length)}function CD(e,t,n){return me(e,n,"similar",()=>bt(e,{scope:t,...re.similar,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}).length)}function vD(e,t,n){return me(e,n,"extract-candidates",()=>dn(e,{scope:t,...re.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}).length)}function RD(e,t,n){return me(e,n,"react-component-duplicates",()=>{let r=sn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return va(r)})}function LD(e,t,n){return me(e,n,"react-hook-candidates",()=>{let r=cn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return tm(r,HD)})}function ID(e,t,n){return me(e,n,"react-large-component-pressure",()=>{let r=Er(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return VD(r)})}function DD(e,t,n){return me(e,n,"vue-component-duplicates",()=>{let r=ln(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return va(r)})}function kD(e,t,n){return me(e,n,"vue-composable-candidates",()=>{let r=un(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return tm(r,qD)})}function wD(e,t,n){return me(e,n,"vue-large-view-pressure",()=>{let r=Fr(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return co(r)})}function ND(e,t,n){return em(e,n,"wrapper-candidates",()=>yn(e,{scope:t,...re.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}))}function PD(e,t,n){return em(e,n,"passthrough-candidates",()=>hn(e,{scope:t,...re.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}))}function _D(e,t,n){return me(e,n,"stale-abstractions",()=>{let r=bn(e,{scope:t,...re.stale,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),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 ED(e,t){return me(e,t,"git-evidence",()=>{let n=Qi(e);if(!n)return null;let r=pn(e,void 0,{limit:t.candidateResultLimit}),i={};for(let[o,s]of n)i[o]={changes:s.changes,fixChanges:s.fixChanges};return{amplification:vd(e),hiddenCoupling:{pairCount:r.findings.length,top:r.findings.slice(0,5).map(o=>({fileA:o.fileA,fileB:o.fileB,together:o.together,confidence:o.confidence}))},fileStats:i}})}function FD(e,t){return me(e,t,"suppressions",()=>{let n=ao(e);return{total:n.total,byCategory:{...n.byCategory}}})}function TD(e,t,n){return me(e,n,"drift",()=>{let r=gn(e,{scope:t,...re.drift});return{count:r.unusedImports+r.layerViolations,unusedImports:r.unusedImports,layerViolations:r.layerViolations}})}function AD(e,t,n){return me(e,n,"complexity-hotspots",()=>{let r=Jr(e,{scope:t,minLoc:10,limit:n.complexityResultLimit,scanLimit:n.candidateScanLimit,semantic:!1});return{top:r.slice(0,5).map(i=>({symbol:i.shortName,score:i.score,file:i.file})),extremeCount:r.filter(i=>i.score>dD).length}})}function $D(e,t){let n=e.symbols>=mD||e.documents>=pD,r=t?Number.POSITIVE_INFINITY:Yd,i=t?Number.POSITIVE_INFINITY:fD;return!n||t?{candidateScanLimit:void 0,candidateResultLimit:r,complexityResultLimit:i,releaseCachesBetweenPhases:!0,warnings:t&&n?["Large index detected; running health without candidate scan or result caps because --full was supplied."]:[]}:{candidateScanLimit:Xd,candidateResultLimit:r,complexityResultLimit:i,releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${Xd} symbols and reported their top ${Yd} findings. Run "scip-query health --full" for unbounded candidate counts.`]}}function MD(e,t){t.releaseCachesBetweenPhases&&(ws(e),Sa())}function me(e,t,n,r){OD(n);try{return r()}finally{MD(e,t)}}function em(e,t,n,r){return me(e,t,n,()=>co(r()))}function OD(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function jD(e,t){return t.filter(n=>!xe(e,n.relativePath)&&!le(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function BD(e,t){return t.filter(n=>!xe(e,n.relativePath)&&!le(e,n.symbol,n.relativePath))}function co(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 VD(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 va(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 tm(e,t){return{...va(e),scoreCount:WD(e.reduce((r,i)=>r+t(i),0))}}function HD(e){let t=e.sharedHooks.length>0,n=nm({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:rm(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function qD(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=nm({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:rm(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function nm(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!om.has(im(t))).length+Math.min(e.functions.length,3)}function rm(e,t,n){let r=[...e,...t,...n].map(im);return r.length>0&&r.every(i=>om.has(i))}function im(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function WD(e){return Math.round(e*100)/100}var om=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 Ra(e,t,n,r={}){let i=B(e,t),o=B(e,n);if(!i||!o)return null;let s=new Set(_e(e,i,{semantic:r.semantic}).map(b=>b.symbol)),a=new Set(_e(e,o,{semantic:r.semantic}).map(b=>b.symbol)),c=[];for(let b of s)a.has(b)&&c.push(b);let l=[];for(let b of s)a.has(b)||l.push(b);let u=[];for(let b of a)s.has(b)||u.push(b);let d=new Set([...s,...a]),m=d.size>0?c.length/d.size:0,f;d.size===0?f="Neither function calls other tracked symbols. There is no callee-pattern evidence for consolidation; inspect the source bodies directly.":c.length===0?f="These functions do not share any callees. They are not a callee-based consolidation candidate.":l.length===0&&u.length===0?f="These functions have identical tracked callee sets. They are a strong structural match, but identical callees do not prove interchangeable semantics; inspect signatures, control flow, and return values before consolidating.":l.length===0?f="A's tracked callees are a subset of B's. B may subsume part of A's structure, but verify signatures, guards, and non-call logic before replacing A with B.":u.length===0?f="B's tracked callees are a subset of A's. A may subsume part of B's structure, but verify signatures, guards, and non-call logic before replacing B with A.":l.length<=2&&u.length<=2?f=`Create a shared function with the ${c.length} common callees. Pass the ${l.length+u.length} divergent callees as parameters or strategy callbacks.`:f=`Extract the ${c.length} shared callees into a common helper. Each function calls the helper plus its own unique logic (${l.length} callees in A, ${u.length} in B).`;let g=i.endLine-i.startLine+1,h=o.endLine-o.startLine+1;return{symbolA:{symbol:i.symbol,shortName:y(i.symbol),file:i.relativePath,loc:g},symbolB:{symbol:o.symbol,shortName:y(o.symbol),file:o.relativePath,loc:h},similarity:m,sharedCallees:c.map(y),uniqueToA:l.map(y),uniqueToB:u.map(y),consolidationStrategy:f}}import{readFileSync as sm}from"fs";import{extname as UD,join as am}from"path";function La(e,t,n={}){let{context:r=0}=n,i=JD(t);if(i)return zD(e,i.filePath,i.startLine,i.endLine,r);let o=B(e,t);return o?GD(e,o,r):null}function JD(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 GD(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=am(e.config.projectRoot,t.relativePath),o;try{o=sm(i,"utf-8")}catch{return null}let s=o.split(`
573
542
  `),a=Math.max(0,t.startLine-n),c=Math.min(s.length-1,t.endLine+n),l=s.slice(a,c+1).join(`
574
- `);return{symbol:t.symbol,shortName:b(t.symbol),relativePath:t.relativePath,startLine:a,endLine:c,language:r?.language??tu(t.relativePath),source:l}}function kC(e,t,n,r,i){let o=pe(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=eu(e.config.projectRoot,s.relative_path),c;try{c=Zl(a,"utf-8")}catch{return null}let l=c.split(`
575
- `),u=Math.max(0,n-1-i),m=Math.min(l.length-1,r-1+i),d=l.slice(u,m+1).join(`
576
- `);return{symbol:`${s.relative_path}:${n}-${r}`,shortName:`${s.relative_path}:${n}-${r}`,relativePath:s.relative_path,startLine:u,endLine:m,language:s.language??tu(s.relative_path),source:d}}function tu(e){switch(_C(e).toLowerCase()){case".ts":case".tsx":case".mts":case".cts":return"typescript";case".js":case".jsx":case".mjs":case".cjs":return"javascript";case".py":case".pyi":return"python";case".rs":return"rust";case".go":return"go";case".java":return"java";case".kt":case".kts":return"kotlin";case".scala":return"scala";case".rb":return"ruby";case".php":return"php";case".cs":return"csharp";case".vb":return"vb";case".dart":return"dart";case".c":case".h":return"c";case".cc":case".cpp":case".cxx":case".hpp":case".hh":case".hxx":return"cpp";case".vue":return"vue";default:return null}}function ps(e,t={}){let{scope:n,limit:r}=t,i=new _(e),o=jC([...EC(e,n),...AC(e,i,n)]);return BC(o),r?o.slice(0,r):o}function EC(e,t){let n=[];for(let r of PC(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||to(e,r.barrel_path))continue;let i=FC(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:b(r.symbol),originalFile:r.original_path,barrelConsumers:o,directConsumers:s})}return n}function PC(e,t){let n=t?`AND barrel_d.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
543
+ `);return{symbol:t.symbol,shortName:y(t.symbol),relativePath:t.relativePath,startLine:a,endLine:c,language:r?.language??cm(t.relativePath),source:l}}function zD(e,t,n,r,i){let o=Ie(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=am(e.config.projectRoot,s.relative_path),c;try{c=sm(a,"utf-8")}catch{return null}let l=c.split(`
544
+ `),u=Math.max(0,n-1-i),d=Math.min(l.length-1,r-1+i),m=l.slice(u,d+1).join(`
545
+ `);return{symbol:`${s.relative_path}:${n}-${r}`,shortName:`${s.relative_path}:${n}-${r}`,relativePath:s.relative_path,startLine:u,endLine:d,language:s.language??cm(s.relative_path),source:m}}function cm(e){switch(UD(e).toLowerCase()){case".ts":case".tsx":case".mts":case".cts":return"typescript";case".js":case".jsx":case".mjs":case".cjs":return"javascript";case".py":case".pyi":return"python";case".rs":return"rust";case".go":return"go";case".java":return"java";case".kt":case".kts":return"kotlin";case".scala":return"scala";case".rb":return"ruby";case".php":return"php";case".cs":return"csharp";case".vb":return"vb";case".dart":return"dart";case".c":case".h":return"c";case".cc":case".cpp":case".cxx":case".hpp":case".hh":case".hxx":return"cpp";case".vue":return"vue";default:return null}}function Ia(e,t={}){let{scope:n,limit:r}=t,i=new N(e),o=rk([...KD(e,n),...YD(e,i,n)]);return ik(o),r?o.slice(0,r):o}function KD(e,t){let n=[];for(let r of QD(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||ms(e,r.barrel_path))continue;let i=XD(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:y(r.symbol),originalFile:r.original_path,barrelConsumers:o,directConsumers:s})}return n}function QD(e,t){let n=t?`AND barrel_d.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
577
546
  barrel_d.id AS barrel_doc_id,
578
547
  barrel_d.relative_path AS barrel_path,
579
548
  gs.id AS symbol_id,
@@ -603,7 +572,7 @@ ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,e
603
572
  -- Only function-level symbols (ending with ().), not module-level
604
573
  AND gs.symbol LIKE '%().'
605
574
  ${n}
606
- ORDER BY barrel_d.relative_path, gs.symbol`)}function FC(e,t){return e.get(`SELECT
575
+ ORDER BY barrel_d.relative_path, gs.symbol`)}function XD(e,t){return e.get(`SELECT
607
576
  SUM(CASE WHEN uses_barrel = 1 THEN 1 ELSE 0 END) AS barrel_consumers,
608
577
  SUM(CASE WHEN uses_barrel = 0 THEN 1 ELSE 0 END) AS direct_consumers
609
578
  FROM (
@@ -632,7 +601,7 @@ ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,e
632
601
  AND consumer_d.id != ?
633
602
  ${e.pathExclusionsFor("consumer_d")}
634
603
  GROUP BY consumer_d.id
635
- )`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function AC(e,t,n){let r=[];for(let i of TC(e,n))nu(e,i,i)>0||r.push(...MC(e,t,i));return r}function TC(e,t){return T(e,{scope:t,includeIgnored:!1}).filter(n=>Xi(e,n).length>0)}function MC(e,t,n){return Xi(e,n).filter(r=>r.sourcePath&&!e.isIgnored(r.sourcePath)).flatMap(r=>OC(e,t,n,r.sourcePath))}function OC(e,t,n,r){let i=$C(t,r);return i?[{barrelFile:n,symbol:i.symbol,shortName:b(i.symbol),originalFile:r,barrelConsumers:0,directConsumers:nu(e,r,n)}]:[]}function nu(e,t,n){let r=new Set;for(let i of T(e,{includeIgnored:!1}))if(i!==n)for(let o of ne(e,i))o.sourcePath===t&&r.add(i);return r.size}function $C(e,t){let n=e.definitionsForFile(t);return n.find(r=>te(r.symbol)==="method")??n[0]??null}function jC(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 BC(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function gs(e,t={}){let{samples:n=50,scope:r,maxDisagreements:i=5}=t,o=new _(e),s=HC(o.productionCallableDefinitions({scope:r,minLoc:2,requireFunctionLikeSymbol:!0}),n);if(s.length===0||!qC(e,s))return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let a={references:ru(),callees:ru()},c=[],l=0,u=Vr(e,s);for(let m of s){let d=ai(m,Pt(e,m).map(y=>y.file)),p=ai(m,(u.get(m.symbolId)??[]).map(y=>y.file));if(d.size===0&&p.size===0)continue;l+=1;let h=ai(m,Ft(e,m).map(y=>y.file)),f=ai(m,(o.calleeMap([m],{semantic:!1}).get(m.symbolId)??[]).map(y=>y.file));iu(a.references,m,"references",h,d,c),iu(a.callees,m,"callees",f,p,c)}return c.sort((m,d)=>d.cheapOnly.length+d.oracleOnly.length-(m.cheapOnly.length+m.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?fs(l/s.length):0,scores:["references","callees"].map(m=>WC(m,a[m])),topDisagreements:c.slice(0,i)}}function ru(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0}}function HC(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 qC(e,t){let n=t[0];if(!n)return!1;try{return Tn(e,n.relativePath).availability().available}catch{return!1}}function ai(e,t){let n=new Set;for(let r of t)r!==e.relativePath&&n.add(r);return n}function iu(e,t,n,r,i,o){if(r.size===0&&i.size===0)return;e.comparedSymbols+=1,e.cheapTotal+=r.size,e.oracleTotal+=i.size;let s=[],a=[];for(let c of r)i.has(c)?e.agreed+=1:s.push(c);for(let c of i)r.has(c)||a.push(c);(s.length>0||a.length>0)&&o.push({symbol:b(t.symbol),question:n,cheapOnly:s,oracleOnly:a})}var VC={references:!0,callees:!1};function WC(e,t){let n=t.oracleTotal>0?t.agreed/t.oracleTotal:1,r=t.cheapTotal-t.agreed;return{question:e,comparedSymbols:t.comparedSymbols,precision:VC[e]&&t.cheapTotal>0?fs(t.agreed/t.cheapTotal):null,recall:fs(n),unverified:r}}function fs(e){return Math.round(e*1e3)/1e3}function hs(e,t={}){let{scope:n,minLoc:r=1,limit:i,scanLimit:o}=t,s=t.semantic!==!1,a=GC(e,UC(e,{scope:n,minLoc:r,scanLimit:o}),{semantic:s}),c=zC(a);return i?c.slice(0,i):c}function UC(e,t){let n=Be(e,{scope:t.scope}).filter(r=>r.isFunctionLike&&!e.isIgnored(r.relativePath)).filter(r=>H(r)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((r,i)=>H(i)-H(r)||r.relativePath.localeCompare(i.relativePath)),Ne(n,t.scanLimit)}function GC(e,t,n){let r=new Map;for(let i of t){let o=KC(e,i,n);if(!o)continue;let s=r.get(o)??[];s.push(JC(i)),r.set(o,s)}return r}function JC(e){return{symbol:e.symbol,shortName:b(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:H(e)}}function zC(e){let t=[];for(let[n,r]of e)r.length>=2&&t.push({signature:n,functions:r});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 KC(e,t,n){if(n.semantic){let o=Hc(e,t);if(o)return o}let r=QC(t.documentation),i=r?ZC(r):null;return i||eR(YC(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function QC(e){return Rt(It(e))}function YC(e,t,n,r,i){let o=M(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=nR(s,n,r,i);for(let c of a){let l=Math.min(s.length-1,Math.max(c,c+4)),u="";for(let m=c;m<=l;m+=1){let d=s[m]?.trim();if(d&&(u=u?`${u} ${d}`:d,XC(u)))return u}if(u&&u.includes("("))return u}return null}function XC(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||wn(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function ZC(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 eR(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${ou(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=tR(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 tR(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 nR(e,t,n,r){let i=ou(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 m=l;m<=u;m+=1){let d=e[m]??"";(o.test(d)||s.test(d))&&!c.has(m)&&(c.add(m),a.push(m))}for(let m=0;m<e.length;m+=1){let d=e[m]??"";(o.test(d)||s.test(d))&&!c.has(m)&&(c.add(m),a.push(m))}return a}function ou(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}import{existsSync as pu}from"fs";import{join as SR}from"path";import rR from"better-sqlite3";var iR=["node_modules",".git","dist","build","out","coverage","target",".next",".nuxt",".cache",".turbo",".scipquery-cache","__pycache__",".venv","venv"],ci=class{db;config;pathFilter;constructor(t,n){this.config=t,this.pathFilter=n??null,this.db=new rR(t.dbPath,{readonly:!0}),this.db.pragma("busy_timeout = 5000")}isIgnored(t){return this.pathFilter?.isIgnored(t)??!1}get localSymbolPredicate(){return`(
604
+ )`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function YD(e,t,n){let r=[];for(let i of ZD(e,n))lm(e,i,i)>0||r.push(...ek(e,t,i));return r}function ZD(e,t){return V(e,{scope:t,includeIgnored:!1}).filter(n=>ls(e,n).length>0)}function ek(e,t,n){return ls(e,n).filter(r=>r.sourcePath&&!e.isIgnored(r.sourcePath)).flatMap(r=>tk(e,t,n,r.sourcePath))}function tk(e,t,n,r){let i=nk(t,r);return i?[{barrelFile:n,symbol:i.symbol,shortName:y(i.symbol),originalFile:r,barrelConsumers:0,directConsumers:lm(e,r,n)}]:[]}function lm(e,t,n){let r=new Set;for(let i of V(e,{includeIgnored:!1}))if(i!==n)for(let o of ce(e,i))o.sourcePath===t&&r.add(i);return r.size}function nk(e,t){let n=e.definitionsForFile(t);return n.find(r=>ae(r.symbol)==="method")??n[0]??null}function rk(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 ik(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function ka(e,t={}){let{samples:n=50,scope:r,maxDisagreements:i=5}=t,o=new N(e),s=ok(o.productionCallableDefinitions({scope:r,minLoc:2,requireFunctionLikeSymbol:!0}),n);if(s.length===0||!sk(e,s))return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let a={references:um(),callees:um()},c=[],l=0,u=Bi(e,s);for(let d of s){let m=lo(d,tn(e,d).map(b=>b.file)),f=lo(d,(u.get(d.symbolId)??[]).map(b=>b.file));if(m.size===0&&f.size===0)continue;l+=1;let g=lo(d,nn(e,d).map(b=>b.file)),h=lo(d,(o.calleeMap([d],{semantic:!1}).get(d.symbolId)??[]).map(b=>b.file));dm(a.references,d,"references",g,m,c),dm(a.callees,d,"callees",h,f,c)}return c.sort((d,m)=>m.cheapOnly.length+m.oracleOnly.length-(d.cheapOnly.length+d.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?Da(l/s.length):0,scores:["references","callees"].map(d=>ck(d,a[d])),topDisagreements:c.slice(0,i)}}function um(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0}}function ok(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 sk(e,t){let n=t[0];if(!n)return!1;try{return en(e,n.relativePath).availability().available}catch{return!1}}function lo(e,t){let n=new Set;for(let r of t)r!==e.relativePath&&n.add(r);return n}function dm(e,t,n,r,i,o){if(r.size===0&&i.size===0)return;e.comparedSymbols+=1,e.cheapTotal+=r.size,e.oracleTotal+=i.size;let s=[],a=[];for(let c of r)i.has(c)?e.agreed+=1:s.push(c);for(let c of i)r.has(c)||a.push(c);(s.length>0||a.length>0)&&o.push({symbol:y(t.symbol),question:n,cheapOnly:s,oracleOnly:a})}var ak={references:!0,callees:!1};function ck(e,t){let n=t.oracleTotal>0?t.agreed/t.oracleTotal:1,r=t.cheapTotal-t.agreed;return{question:e,comparedSymbols:t.comparedSymbols,precision:ak[e]&&t.cheapTotal>0?Da(t.agreed/t.cheapTotal):null,recall:Da(n),unverified:r}}function Da(e){return Math.round(e*1e3)/1e3}function wa(e,t={}){let{scope:n,minLoc:r=1,limit:i,scanLimit:o}=t,s=t.semantic!==!1,a=uk(e,lk(e,{scope:n,minLoc:r,scanLimit:o}),{semantic:s}),c=mk(a);return i?c.slice(0,i):c}function lk(e,t){let n=Ye(e,{scope:t.scope}).filter(r=>r.isFunctionLike&&!e.isIgnored(r.relativePath)).filter(r=>q(r)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((r,i)=>q(i)-q(r)||r.relativePath.localeCompare(i.relativePath)),Be(n,t.scanLimit)}function uk(e,t,n){let r=new Map;for(let i of t){let o=pk(e,i,n);if(!o)continue;let s=r.get(o)??[];s.push(dk(i)),r.set(o,s)}return r}function dk(e){return{symbol:e.symbol,shortName:y(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:q(e)}}function mk(e){let t=[];for(let[n,r]of e)r.length>=2&&t.push({signature:n,functions:r});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 pk(e,t,n){if(n.semantic){let o=Nu(e,t);if(o)return o}let r=fk(t.documentation),i=r?bk(r):null;return i||yk(gk(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function fk(e){return Wt(Ut(e))}function gk(e,t,n,r,i){let o=A(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=xk(s,n,r,i);for(let c of a){let l=Math.min(s.length-1,Math.max(c,c+4)),u="";for(let d=c;d<=l;d+=1){let m=s[d]?.trim();if(m&&(u=u?`${u} ${m}`:m,hk(u)))return u}if(u&&u.includes("("))return u}return null}function hk(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||fr(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function bk(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 yk(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${mm(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=Sk(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 Sk(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 xk(e,t,n,r){let i=mm(r),o=new RegExp(`\\b${i}\\b\\s*\\(`,"i"),s=new RegExp(`\\bdef\\s+${i}\\b`,"i"),a=[],c=new Set,l=Math.max(0,Math.min(t,e.length-1)),u=Math.max(l,Math.min(e.length-1,Math.max(n,t+4)));for(let d=l;d<=u;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!c.has(d)&&(c.add(d),a.push(d))}for(let d=0;d<e.length;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!c.has(d)&&(c.add(d),a.push(d))}return a}function mm(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}import{existsSync as Cm}from"fs";import{join as Mk}from"path";import Ck from"better-sqlite3";var vk=["node_modules",".git","dist","build","out","coverage","target",".next",".nuxt",".cache",".turbo",".scipquery-cache","__pycache__",".venv","venv"],uo=class{db;config;pathFilter;constructor(t,n){this.config=t,this.pathFilter=n??null,this.db=new Ck(t.dbPath,{readonly:!0}),this.db.pragma("busy_timeout = 5000")}isIgnored(t){return this.pathFilter?.isIgnored(t)??!1}get localSymbolPredicate(){return`(
636
605
  EXISTS (
637
606
  SELECT 1
638
607
  FROM defn_enclosing_ranges local_der
@@ -649,8 +618,8 @@ ${d}`,l+=1+d.length,u+=wn(d),r+=d.length+1}let m=zf(c);m&&n.push({...m,start:a,e
649
618
  AND local_m.role = 1
650
619
  ${this.pathExclusionsFor("local_d").trimStart()}
651
620
  )
652
- )`}get pathExclusions(){return this.pathExclusionsFor("d")}get symbolNoise(){return this.symbolNoiseFor("gs")}pathExclusionsFor(...t){return t.flatMap(n=>iR.flatMap(r=>[`AND ${n}.relative_path NOT LIKE '${r}/%'`,`AND ${n}.relative_path NOT LIKE '%/${r}/%'`])).join(`
653
- `)}symbolNoiseFor(t){return`AND ${t}.symbol NOT LIKE '%().(%' AND ${t}.symbol NOT LIKE '%typeLiteral%'`}all(t,...n){return this.db.prepare(t).all(...n)}get(t,...n){return this.db.prepare(t).get(...n)}close(){this.db.close()}};import oR from"ignore";import{readFileSync as sR,existsSync as ys}from"fs";import{dirname as bs,isAbsolute as su,join as Ss,relative as aR,resolve as cR}from"path";function Sn(e){let t=oR(),n=!1,r=lR(e);for(let i of r)try{let o=sR(i,"utf-8");t.add(o),n=!0}catch{}return n||t.add(uR),{isIgnored:i=>au(t,e,i),filter:i=>i.filter(o=>!au(t,e,o))}}function lR(e){let t=[],n=Ss(e,".gitignore");ys(n)&&t.push(n);let r=bs(e),i=0;for(;r!==bs(r)&&i<5;){let o=Ss(r,".gitignore");if(ys(o)&&t.push(o),ys(Ss(r,".git")))break;r=bs(r),i++}return t}var uR=`
621
+ )`}get pathExclusions(){return this.pathExclusionsFor("d")}get symbolNoise(){return this.symbolNoiseFor("gs")}pathExclusionsFor(...t){return t.flatMap(n=>vk.flatMap(r=>[`AND ${n}.relative_path NOT LIKE '${r}/%'`,`AND ${n}.relative_path NOT LIKE '%/${r}/%'`])).join(`
622
+ `)}symbolNoiseFor(t){return`AND ${t}.symbol NOT LIKE '%().(%' AND ${t}.symbol NOT LIKE '%typeLiteral%'`}all(t,...n){return this.db.prepare(t).all(...n)}get(t,...n){return this.db.prepare(t).get(...n)}close(){this.db.close()}};import Rk from"ignore";import{readFileSync as Lk,existsSync as Na}from"fs";import{dirname as Pa,isAbsolute as pm,join as _a,relative as Ik,resolve as Dk}from"path";function Yn(e){let t=Rk(),n=!1,r=kk(e);for(let i of r)try{let o=Lk(i,"utf-8");t.add(o),n=!0}catch{}return n||t.add(wk),{isIgnored:i=>fm(t,e,i),filter:i=>i.filter(o=>!fm(t,e,o))}}function kk(e){let t=[],n=_a(e,".gitignore");Na(n)&&t.push(n);let r=Pa(e),i=0;for(;r!==Pa(r)&&i<5;){let o=_a(r,".gitignore");if(Na(o)&&t.push(o),Na(_a(r,".git")))break;r=Pa(r),i++}return t}var wk=`
654
623
  # Dependencies
655
624
  node_modules/
656
625
  vendor/
@@ -707,27 +676,29 @@ Thumbs.db
707
676
 
708
677
  # Type definitions (often noise in queries)
709
678
  *.d.ts
710
- `;function au(e,t,n){let r=mR(t,n);if(!r)return!1;try{return e.ignores(r)}catch{return!1}}function mR(e,t){if(!t||t===".")return null;if(!su(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let n=su(t)?t:cR(e,t),r=aR(e,n).replaceAll("\\","/");return!r||r==="."||r.startsWith("..")?null:r}import{readFileSync as dR,writeFileSync as pR,existsSync as lu,mkdirSync as fR}from"fs";import{join as Wt,resolve as cu}from"path";import{createHash as gR}from"crypto";import{homedir as hR}from"os";var uu=".scipquery.json",yR={enabled:!1,debounceMs:3e4,cooldownMs:6e4,ignore:[]};function xn(e){let t=Wt(e,uu);if(!lu(t))return{};try{let n=dR(t,"utf-8");return JSON.parse(n)}catch{return{}}}function mu(e){return{...yR,...e.watch}}function bR(e,t){let n=process.env.SCIP_QUERY_CACHE_DIR;if(n)return xs(n);if(t?.dbPath)return xs(cu(e,t.dbPath));let i=process.env.XDG_CACHE_HOME||Wt(hR(),".cache"),o=gR("sha256").update(cu(e)).digest("hex").slice(0,12),s=Wt(i,"scip-query","projects",o);return xs(s)}function Cn(e,t){let n=bR(e,t);return{cacheDir:n,dbPath:Wt(n,"index.db"),indexPath:Wt(n,"index.scip"),metaPath:Wt(n,"meta.json")}}function du(e,t){let n=Wt(e,uu);return lu(n)||pR(n,JSON.stringify({languages:t,watch:{enabled:!1,debounceMs:3e4,cooldownMs:6e4}},null,2)+`
711
- `),n}function xs(e){return fR(e,{recursive:!0}),e}function Me(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}function li(e=Me()){let t=xn(e),n=Cn(e,t),r=process.env.SCIP_QUERY_INDEX_DB??(pu(n.dbPath)?n.dbPath:SR(e,"index.db"));return{projectRoot:e,config:t,paths:n,dbPath:r}}function Cs(e){return li(e).dbPath}function xR(){let{projectRoot:e,config:t,paths:n,dbPath:r}=li();pu(r)||(console.error("error: No index.db found. Run: scip-query reindex"),process.exit(1));let i={dbPath:r,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??n.indexPath,projectRoot:e,entryRoots:t.entryRoots,semantic:t.semantic},o=Sn(e);return new ci(i,o)}function tt(e){let t=xR();try{return e(t)}finally{t.close()}}function Rs(e,t){return t.concat([e])}function Rn(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 fu(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 CR(e)}}function CR(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}import{spawnSync as RR}from"child_process";function Is(e){let t=RR(process.execPath,[...process.execArgv,e.cliPath,e.command,...e.args??[]],{cwd:process.cwd(),env:e.env??process.env,encoding:"utf8",maxBuffer:e.maxBuffer??10485760});if(t.status!==0){let n=t.stderr.trim();throw new Error(`${e.label} failed${n?`:
712
- ${n}`:""}`)}return JSON.parse(t.stdout)}function gu(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function xe(e){return e+1}function me(e,t){return`${xe(e)}-${xe(t)}`}function ae(e,t,n){return`${e}:${me(t,n)}`}var L={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)}};var vR=IR(import.meta.url),{version:ui}=LR(),mi="__health-phase",di="__diff-impact-batch",DR=10,NR=75e3,_R=5e3,hu=2500;function LR(){for(let e of["../package.json","../../package.json"])try{return vR(e)}catch{}return{version:"0.0.0"}}function cr(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
713
- `)}function bu(e,t,n){let r=we(e);return r.symbols>=NR||r.documents>=_R?n?(console.error(`Large index detected; ${t} is running the unbounded semantic pass because --full was supplied.`),{semantic:!0}):(console.error(`Large index detected; ${t} will scan the highest-priority ${hu} candidates with semantic enrichment disabled. Run "scip-query ${t} --full" for the unbounded semantic pass.`),{scanLimit:hu,semantic:!1}):{semantic:!0}}function Su(e){let t=ar.map(n=>wR(n,e));return ls(t)}function wR(e,t){let n=process.argv[1]??yu(import.meta.url),r=[e];return t.scope&&r.push("--scope",t.scope),t.full&&r.push("--full"),Is({cliPath:n,command:mi,args:r,label:`Health phase "${e}"`})}function xu(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(console.log(`
679
+ `;function fm(e,t,n){let r=Nk(t,n);if(!r)return!1;try{return e.ignores(r)}catch{return!1}}function Nk(e,t){if(!t||t===".")return null;if(!pm(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let n=pm(t)?t:Dk(e,t),r=Ik(e,n).replaceAll("\\","/");return!r||r==="."||r.startsWith("..")?null:r}import{readFileSync as Pk,writeFileSync as hm,existsSync as bm,mkdirSync as _k}from"fs";import{join as Mt,resolve as gm}from"path";import{createHash as Ek}from"crypto";import{homedir as Fk}from"os";var zr=".scipquery.json",Tk={enabled:!1,debounceMs:3e4,cooldownMs:6e4,ignore:[]},Ak=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php"];function Ct(e){let t=Mt(e,zr);if(!bm(t))return{};try{let n=Pk(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 ${zr} at ${t}: ${r}`,{cause:n}):new Error(`unable to read ${zr} at ${t}: ${r}`,{cause:n})}}function mo(e,t={}){let n=[],r=new Set(Ak);for(let[o,s]of(e.languages??[]).entries())r.has(s)||n.push({level:"error",path:`languages[${o}]`,message:`Unsupported language: ${s}`});if(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&&e.watch.cooldownMs<=0&&n.push({level:"error",path:"watch.cooldownMs",message:"Must be greater than 0."}),e.declaredCouplings!==void 0&&!Array.isArray(e.declaredCouplings))n.push({level:"error",path:"declaredCouplings",message:"Must be an array."});else for(let[o,s]of(e.declaredCouplings??[]).entries()){let a=`declaredCouplings[${o}]`;if((!s.name||s.name.trim()==="")&&n.push({level:"error",path:`${a}.name`,message:"Declared coupling name is required."}),!Array.isArray(s.files)||s.files.length<2)n.push({level:"error",path:`${a}.files`,message:"Declared coupling needs at least two files."});else for(let[c,l]of s.files.entries())(!l||l.trim()==="")&&n.push({level:"error",path:`${a}.files[${c}]`,message:"Declared coupling file path is required."});s.reason!==void 0&&s.reason.trim()===""&&n.push({level:"error",path:`${a}.reason`,message:"Declared coupling reason cannot be blank."})}let i=t.now??new Date;for(let[o,s]of(e.suppressions??[]).entries()){let a=`suppressions[${o}]`;if((!s.reason||s.reason.trim()==="")&&n.push({level:"error",path:`${a}.reason`,message:"Suppression reason is required."}),!s.id&&!s.check&&n.push({level:"error",path:a,message:"Suppression must include id or check."}),s.expiresAt){let c=Date.parse(s.expiresAt);Number.isNaN(c)?n.push({level:"error",path:`${a}.expiresAt`,message:"Must be an ISO date string."}):c<=i.getTime()&&n.push({level:"warning",path:`${a}.expiresAt`,message:"Suppression has expired."})}}return n}function ym(e){return{...Tk,...e.watch}}function $k(e,t){let n=process.env.SCIP_QUERY_CACHE_DIR;if(n)return Ea(n);if(t?.dbPath)return Ea(gm(e,t.dbPath));let i=process.env.XDG_CACHE_HOME||Mt(Fk(),".cache"),o=Ek("sha256").update(gm(e)).digest("hex").slice(0,12),s=Mt(i,"scip-query","projects",o);return Ea(s)}function Zn(e,t){let n=$k(e,t);return{cacheDir:n,dbPath:Mt(n,"index.db"),indexPath:Mt(n,"index.scip"),metaPath:Mt(n,"meta.json")}}function Sm(e,t){let n=Mt(e,zr);return bm(n)||hm(n,JSON.stringify({languages:t,watch:{enabled:!1,debounceMs:3e4,cooldownMs:6e4}},null,2)+`
680
+ `),n}function xm(e,t){let n=Mt(e,zr),r=Ct(e),i={...r,suppressions:[...r.suppressions??[],t]},o=mo(i).filter(s=>s.level==="error");if(o.length>0){let s=o.map(a=>`${a.path}: ${a.message}`).join("; ");throw new Error(`invalid suppression: ${s}`)}return hm(n,JSON.stringify(i,null,2)+`
681
+ `),{path:n,suppressionCount:i.suppressions?.length??0}}function Ea(e){return _k(e,{recursive:!0}),e}function fe(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}function po(e=fe()){let t=Ct(e),n=Zn(e,t),r=process.env.SCIP_QUERY_INDEX_DB??(Cm(n.dbPath)?n.dbPath:Mk(e,"index.db"));return{projectRoot:e,config:t,paths:n,dbPath:r}}function Fa(e){return po(e).dbPath}function Ok(){let{projectRoot:e,config:t,paths:n,dbPath:r}=po();Cm(r)||(console.error("error: No index.db found. Run: scip-query reindex"),process.exit(1));let i={dbPath:r,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??n.indexPath,projectRoot:e,entryRoots:t.entryRoots,semantic:t.semantic,suppressions:t.suppressions,declaredCouplings:t.declaredCouplings},o=Yn(e);return new uo(i,o)}function st(e){let t=Ok();try{return e(t)}finally{t.close()}}function Ta(e,t){return t.concat([e])}function er(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 vm(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 jk(e)}}function jk(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}import{spawnSync as Bk}from"child_process";function Aa(e){let t=Bk(process.execPath,[...process.execArgv,e.cliPath,e.command,...e.args??[]],{cwd:process.cwd(),env:e.env??process.env,encoding:"utf8",maxBuffer:e.maxBuffer??10485760});if(t.status!==0){let n=t.stderr.trim();throw new Error(`${e.label} failed${n?`:
682
+ ${n}`:""}`)}return JSON.parse(t.stdout)}function Rm(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Ee(e){return e+1}function ve(e,t){return`${Ee(e)}-${Ee(t)}`}function ge(e,t,n){return`${e}:${ve(t,n)}`}var I={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)}};var Hk=Vk(import.meta.url),{version:fo}=Jk(),go="__health-phase",ho="__diff-impact-batch",qk=10,Wk=75e3,Uk=5e3,Lm=2500;function Jk(){for(let e of["../package.json","../../package.json"])try{return Hk(e)}catch{}return{version:"0.0.0"}}function Kr(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
683
+ `)}function $a(e){let t=Te(e);return t.symbols>=Wk||t.documents>=Uk}function km(e,t,n,r={}){return $a(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 ${Lm} candidates with semantic enrichment disabled. Run "scip-query ${t} --full" for the unbounded semantic pass.`),{scanLimit:Lm,semantic:!1}):{semantic:!0}}function wm(e){let t=Gr.map(n=>Gk(n,e));return Ca(t)}function Gk(e,t){let n=process.argv[1]??Dm(import.meta.url),r=[e];return t.scope&&r.push("--scope",t.scope),t.full&&r.push("--full"),Aa({cliPath:n,command:go,args:r,label:`Health phase "${e}"`})}function Nm(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(console.log(`
714
684
  Codebase Health Score: ${e.score}/100`),console.log(` Risk: ${e.riskScore}/100 (validated predictors: graph facts + change graph)`),console.log(` Hygiene: ${e.hygieneScore}/100 (tidiness candidates)
715
- `),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${Rn(e.overview.indexSizeBytes)}
716
- `),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.extractionCandidates>0&&console.log(` Extract candidates: ${n.extractionCandidates}`),n.wrappers>0&&console.log(` Wrapper functions: ${n.wrappers}`),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(`
685
+ `),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${er(e.overview.indexSizeBytes)}
686
+ `),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.reactComponentDuplicatePairs>0&&console.log(` React components: ${n.reactComponentDuplicatePairs} duplicate pair(s)`),n.reactHookCandidatePairs>0&&console.log(` React hook reuse: ${Im(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: ${Im(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: ${n.wrappers}`),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(`
717
687
  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 recoverable)`:"";console.log(` ${r+1}. [${i.effort} effort / ${i.impact} impact] ${i.description}${o}`)}}if(e.topComplexity.length>0){console.log(`
718
- Top Complexity Hotspots:`);for(let r of e.topComplexity)console.log(` ${r.score.toFixed(1).padStart(6)} ${r.symbol}`)}if(kR(e),e.scoreBreakdown.length>0){console.log(`
688
+ Top Complexity Hotspots:`);for(let r of e.topComplexity)console.log(` ${r.score.toFixed(1).padStart(6)} ${r.symbol}`)}if(Qk(e),Kk(e),e.scoreBreakdown.length>0){console.log(`
719
689
  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(`
720
- No issues found. Codebase is clean.`)}function kR(e){let t=e.axes;if(console.log(`
721
- Axes:`),console.log(` Deletable: ${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})`)}}function Cu(e){return tt(t=>{let n=ht(t,{base:e.base});if(n.note)return hn(t,{base:e.base});if(n.changedFiles.length===0)return hn(t,{base:e.base});let r=[];for(let i of gu(n.changedFiles,DR))r.push(ER(i,e));return ti(n.changedFiles,r)})}function ER(e,t){let n=process.argv[1]??yu(import.meta.url),r=[];return t.base&&r.push("--base",t.base),Is({cliPath:n,command:di,args:r,env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch"})}function Ru(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}`),console.log(""),e.changedSymbols.length>0&&(console.log("Changed symbols:"),L.list(e.changedSymbols,t=>` ${t.file} ${t.shortName} (fan-in: ${t.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
722
- Affected consumer files:`),L.list(e.affectedConsumers,t=>` ${t.file} (${t.consumedSymbols} symbol(s))`))}var Iu=Rs,v=(e=>parseInt(e,10)),pi=(e=>{let t=parseInt(e,10);if(!Number.isFinite(t)||t<1)throw new Error(`Expected a positive integer, got ${e}`);return t}),Ut=parseFloat,vs=parseInt;function g(e,t,n,...r){return r.length>0?{flags:e,description:t,parser:n,defaultValue:r[0]}:{flags:e,description:t,parser:n}}function I(e,t=[]){return{category:e,examples:t}}import{existsSync as Ls,mkdirSync as OR,symlinkSync as $R,readlinkSync as jR,unlinkSync as BR}from"fs";import{join as lr,dirname as _u,resolve as ws}from"path";import{homedir as ks,platform as HR}from"os";import{fileURLToPath as qR}from"url";import{execFileSync as vu}from"child_process";import{platform as Ds,arch as TR}from"os";import{execFileSync as PR}from"child_process";import{platform as FR}from"os";var AR=FR()==="win32";function Le(e){let t=AR?"where":"which";try{return PR(t,[e],{stdio:"pipe"}),!0}catch{return!1}}var Du="v0.7.0";function Ns(){return Le("scip")}function MR(){let e=Ds(),t=TR(),n,r,i;switch(e){case"darwin":n="darwin",i="tar.gz";break;case"linux":n="linux",i="tar.gz";break;case"win32":n="windows",i="zip";break;default:return null}switch(t){case"arm64":r="arm64";break;case"x64":r="amd64";break;default:return null}let o=`scip-${n}-${r}.${i}`;return{url:`https://github.com/sourcegraph/scip/releases/download/${Du}/${o}`,filename:o}}function _s(){let e=MR();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),Ds()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
690
+ No issues found. Codebase is clean.`)}function Im(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${zk(t)} score-weighted)`}function zk(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function Kk(e){if(e.pressure.length!==0){console.log(`
691
+ 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 Qk(e){let t=e.axes;if(console.log(`
692
+ Axes:`),console.log(` Deletable: ${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})`)}}function Pm(e){return st(t=>{let n=it(t,{base:e.base});if(n.note)return Kn(t,{base:e.base});if(n.changedFiles.length===0)return Kn(t,{base:e.base});let r=[];for(let i of Rm(n.changedFiles,qk))r.push(Xk(i,e));return Zi(n.changedFiles,r)})}function Xk(e,t){let n=process.argv[1]??Dm(import.meta.url),r=[];return t.base&&r.push("--base",t.base),Aa({cliPath:n,command:ho,args:r,env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch"})}function _m(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}`),console.log(""),e.changedSymbols.length>0&&(console.log("Changed symbols:"),I.list(e.changedSymbols,t=>` ${t.file} ${t.shortName} (fan-in: ${t.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
693
+ Affected consumer files:`),I.list(e.affectedConsumers,t=>` ${t.file} (${t.consumedSymbols} symbol(s))`))}var bo=Ta,S=(e=>parseInt(e,10)),yo=(e=>{let t=parseInt(e,10);if(!Number.isFinite(t)||t<1)throw new Error(`Expected a positive integer, got ${e}`);return t}),ze=parseFloat,Ma=parseInt;function p(e,t,n,...r){return r.length>0?{flags:e,description:t,parser:n,defaultValue:r[0]}:{flags:e,description:t,parser:n}}function Oa(){return p("--json","Output as JSON for programmatic consumption")}function _(e=[]){return e.some(t=>t.flags==="--json")?e:[...e,Oa()]}function v(e,t=[]){return{category:e,examples:t}}import{existsSync as Ha,mkdirSync as rw,symlinkSync as iw,readlinkSync as ow,unlinkSync as sw}from"fs";import{join as Qr,dirname as Am,resolve as qa}from"path";import{homedir as Wa,platform as aw}from"os";import{fileURLToPath as cw}from"url";import{execFileSync as Em}from"child_process";import{platform as ja,arch as tw}from"os";import{execFileSync as Yk}from"child_process";import{platform as Zk}from"os";var ew=Zk()==="win32";function He(e){let t=ew?"where":"which";try{return Yk(t,[e],{stdio:"pipe"}),!0}catch{return!1}}var Fm="v0.7.0";function Ba(){return He("scip")}function nw(){let e=ja(),t=tw(),n,r,i;switch(e){case"darwin":n="darwin",i="tar.gz";break;case"linux":n="linux",i="tar.gz";break;case"win32":n="windows",i="zip";break;default:return null}switch(t){case"arm64":r="arm64";break;case"x64":r="amd64";break;default:return null}let o=`scip-${n}-${r}.${i}`;return{url:`https://github.com/sourcegraph/scip/releases/download/${Fm}/${o}`,filename:o}}function Va(){let e=nw();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),ja()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
723
694
  `),console.log("Or download manually:")):console.log("Download from:"),console.log(e?` ${e.url}
724
- `:` https://github.com/sourcegraph/scip/releases/tag/${Du}
725
- `),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function Nu(e){if(Ds()==="darwin"&&Le("brew")){e("Installing scip CLI via Homebrew...");try{if(vu("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),Le("scip"))return e("Successfully installed scip CLI via Homebrew"),!0}catch(t){let n=t instanceof Error?t.message:String(t);e(`Homebrew install failed: ${n}`)}}if(Le("go")){e("Installing scip CLI via go install...");try{if(vu("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),Le("scip"))return e("Successfully installed scip CLI via go install"),!0}catch(t){let n=t instanceof Error?t.message:String(t);e(`go install failed: ${n}`)}}return e("Could not auto-install scip CLI."),e("Install manually from: https://github.com/sourcegraph/scip/releases"),!1}var VR=HR()==="win32",Es=["scip-query","concrete-plan","scip-ai-cleanup","scip-explore","scip-debloat","scip-doc-reconcile","scip-maintainability","scip-verify","scip-language-playbook"];function Lu(e={}){let t=e.quiet?()=>{}:console.log,n=qR(import.meta.url),r=ws(_u(n),"..","skills"),i=[lr(ks(),".claude","skills"),lr(ks(),".codex","skills"),lr(ks(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[]};for(let s of i){let a=_u(s);if(!Ls(a))continue;OR(s,{recursive:!0});let c=WR(s);for(let l of Es){let u=lr(r,l),m=lr(s,l);if(!Ls(u)){o.skipped.push(`${c}/${l}`);continue}if(Ls(m)){try{let d=jR(m);if(ws(d)===ws(u)){o.alreadyLinked.push(`${c}/${l}`),t(` ok: ${l} \u2192 ${c} (already linked)`);continue}}catch{o.skipped.push(`${c}/${l}`),t(` skip: ${l} \u2192 ${c} (exists, not a symlink)`);continue}BR(m)}$R(u,m,VR?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function WR(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{existsSync as $m}from"fs";import{execFileSync as rD}from"child_process";import{closeSync as iD,existsSync as zs,mkdirSync as Sm,mkdtempSync as oD,openSync as sD,readFileSync as aD,renameSync as Ks,rmSync as Qs,writeFileSync as xm}from"fs";import{basename as Ci,dirname as zt,extname as cD,join as nt}from"path";import UR from"better-sqlite3";import{execFileSync as GR}from"child_process";import{existsSync as JR,readdirSync as zR,readFileSync as KR}from"fs";import{extname as fi,join as wu}from"path";function yt(e){let t=new Set((e.extensions??ac).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!JR(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Sn(e.projectRoot),r=QR(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new UR(e.dbPath);try{let o=XR(i,r),s=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
726
- VALUES (?, ?, NULL, ?)`),c=i.transaction(u=>{let m=0;for(let d of u){if(o.has(d))continue;let p=KR(wu(e.projectRoot,d),"utf-8"),h=s.run(ZR(d),d,p);m+=Number(h.changes)}return m})(r),l={scanned:r.length,inserted:c,existing:r.length-c};return e.onStatus?.(`Augmented SQLite documents with ${c} auxiliary source file${c===1?"":"s"} (${l.existing} already present).`),l}finally{i.close()}}function QR(e,t){let n=YR(e,t);if(n)return n;let r=[],i=o=>{let s=o?wu(e,o):e,a;try{a=zR(s,{withFileTypes:!0})}catch{return}for(let c of a){if(Zi.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(l);continue}t.has(fi(c.name).toLowerCase())&&r.push(l)}};return i(""),r.sort()}function YR(e,t){try{return GR("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
727
- `).filter(r=>r&&t.has(fi(r).toLowerCase())).sort()}catch{return null}}function XR(e,t){let n=new Set,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),s=e.prepare(`SELECT relative_path FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let a of s)n.add(a.relative_path)}return n}function ZR(e){return fi(e).toLowerCase()===".vue"?"vue":fi(e).replace(/^\./,"").toLowerCase()||"source"}import{execFileSync as eI}from"child_process";import{existsSync as tI,readdirSync as Eu}from"fs";import{extname as Pu,join as Fu}from"path";var nI=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),rI=[{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:"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 Gt(e){let t=[],n=iI(e),r=cI(e);for(let i of rI){if(oI(e,i.files)){t.push(i.language);continue}if(sI(n,i.globs)){t.push(i.language);continue}uI(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&ku(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&ku(t,"c"),t}function iI(e){try{return Eu(e)}catch{return[]}}function oI(e,t){return t?.length?t.some(n=>tI(Fu(e,n))):!1}function sI(e,t){return t?.length?e.some(n=>t.some(r=>aI(n,r))):!1}function aI(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 cI(e){let t=lI(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=Eu(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=Fu(i,s.name);if(s.isDirectory()){nI.has(s.name)||r.push(a);continue}let c=Pu(s.name).toLowerCase();c&&n.add(c)}}return n}function lI(e){try{let t=eI("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(`
728
- `)){if(!r)continue;let i=Pu(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function uI(e,t){return t?.length?t.some(n=>e.has(n)):!1}function ku(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{existsSync as Au,readdirSync as mI}from"fs";import{join as Ps}from"path";var dI={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n})=>{let r=["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&r.splice(1,0,"--pnpm-workspaces"),{binary:n,args:r}},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"},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",Tu(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",Tu(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=Ps(e,"vendor","bin","scip-php"),r=Ps(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",Au(r)?r:Au(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function gi(e){return dI[e]}function Tu(e,t){let n;try{n=mI(e)}catch{return null}for(let r of n)if(t.some(i=>r.endsWith(i)))return Ps(e,r);return null}import{readFileSync as pI,writeFileSync as fI}from"fs";import{create as Fs}from"@bufbuild/protobuf";import{deserializeSCIP as gI,serializeSCIP as hI,DocumentSchema as yI,IndexSchema as bI,SymbolInformationSchema as SI}from"@c4312/scip";function xI(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=CI(e),n=RI(e.flatMap(i=>i.documents??[])),r=Ou(e.flatMap(i=>i.externalSymbols??[]));return Fs(bI,{metadata:t,documents:n,externalSymbols:r})}function Mu(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>gI(pI(i))),r=xI(n);return fI(t,Buffer.from(hI(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function CI(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 RI(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,Fs(yI,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:[...r.occurrences,...n.occurrences],symbols:Ou([...r.symbols,...n.symbols]),text:vI(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function Ou(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,Fs(SI,{symbol:r.symbol,documentation:DI([...r.documentation,...n.documentation]),relationships:II([...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 II(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 vI(e,t){return e?t?e.length>=t.length?e:t:e:t}function DI(e){return[...new Set(e)]}import{execFileSync as NI}from"child_process";import{createHash as _I}from"crypto";import{readdirSync as LI,readFileSync as wI}from"fs";import{join as $u}from"path";function kI(e){return(EI(e)??PI(e)).filter(t=>t&&!ju(t)).sort()}function hi(e){return kI(e).map(t=>{let n=$u(e,t);try{let r=wI(n);return{path:t,size:r.byteLength,hash:_I("sha256").update(r).digest("hex")}}catch{return{path:t,size:-1,hash:"unreadable"}}})}function EI(e){try{return NI("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:50*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
729
- `).filter(Boolean)}catch{return null}}function PI(e){let t=[],n=[""];for(;n.length>0;){let r=n.pop(),i=r?$u(e,r):e,o;try{o=LI(i,{withFileTypes:!0})}catch{continue}for(let s of o){let a=r?`${r}/${s.name}`:s.name;if(s.isDirectory()){ju(a)||n.push(a);continue}t.push(a)}}return t}function ju(e){return e.split("/").some(n=>FI.has(n))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var FI=new Set([".git","node_modules",".scipquery-cache",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]);import{readFileSync as AI,writeFileSync as TI}from"fs";import{create as Bu}from"@bufbuild/protobuf";import{deserializeSCIP as MI,DocumentSchema as OI,IndexSchema as $I,serializeSCIP as jI,SymbolRole as BI}from"@c4312/scip";function Hu(e){let t;try{t=MI(AI(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=HI(t);return n.removedDefinitionOccurrences>0&&TI(e,Buffer.from(jI(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function HI(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&BI.Definition)===0||t.has(a.symbol)?!0:(n+=1,!1));if(s.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(Bu(OI,{language:o.language,relativePath:o.relativePath,occurrences:s,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:Bu($I,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}import{execFile as qI}from"child_process";import{existsSync as yi,renameSync as Ts,rmSync as Ms}from"fs";import{cpus as VI}from"os";import{join as qu}from"path";function WI(e,t,n){if(!e.defaultOutputPath)return;let r=qu(t,e.defaultOutputPath);n!==r&&yi(r)&&Ts(r,n)}function UI(e,t,n){if(!e.defaultOutputPath)return null;let r=qu(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Ms(i,{force:!0}),yi(r)?(Ts(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function GI(e){e&&(Ms(e.defaultOutputPath,{force:!0}),e.backupPath&&yi(e.backupPath)&&Ts(e.backupPath,e.defaultOutputPath))}function JI(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),r=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(2,Math.max(1,VI().length-1));return Math.max(1,Math.min(e,Math.floor(r)))}async function Vu(e,t,n,r){let i=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=JI(o.length,r),c=await KI(o,a,l=>As(l,t,n));if(a>1){let l=new Map;for(let u of c.filter(m=>m.skipped)){let m=o.find(d=>d.language===u.language);m&&(n(`Retrying ${m.language} indexer serially after parallel failure...`),l.set(m.language,await As(m,t,n)))}s.push(...c.map(u=>l.get(u.language)??u))}else s.push(...c);for(let l of i)s.push(await As(l,t,n));return s.sort((l,u)=>e.findIndex(m=>m.language===l.language)-e.findIndex(m=>m.language===u.language))}async function As(e,t,n){n(`Indexing ${e.language} with ${e.resolvedBinary}...`),Ms(e.scipPath,{force:!0});let r=UI(e.config,t,e.scipPath);try{await zI(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),WI(e.config,t,e.scipPath)}catch(i){let o=i instanceof Error?i.message:String(i),s=`${e.resolvedBinary} indexer failed: ${o.split(`
730
- `)[0]}`;return n(`Skipping ${e.language}: ${s}`),{language:e.language,scipPath:e.scipPath,skipped:{language:e.language,reason:s}}}finally{GI(r)}if(!yi(e.scipPath)){let i=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`;return n(`Skipping ${e.language}: ${i}`),{language:e.language,scipPath:e.scipPath,skipped:{language:e.language,reason:i}}}return{language:e.language,scipPath:e.scipPath}}function zI(e,t,n){return new Promise((r,i)=>{qI(e,[...t],n,o=>{o?i(o):r()})})}async function KI(e,t,n){if(e.length===0)return[];let r=new Array(e.length),i=0,o=Math.max(1,Math.min(e.length,t)),s=Array.from({length:o},async()=>{for(;i<e.length;){let a=i++;r[a]=await n(e[a])}});return await Promise.all(s),r}import{execFileSync as $s}from"child_process";import{existsSync as Os,readFileSync as QI}from"fs";import{createRequire as YI}from"module";import{platform as XI}from"os";import{dirname as Wu,join as bi}from"path";var ZI=YI(import.meta.url);function js(e){return[e.indexerBinary,...e.binaryAliases??[]]}function Si(e){let t=js(e);return t.length===1?t[0]:t.join(" or ")}function In(e){for(let t of js(e))if(Le(t))return t;return tv(e)}function Uu(e){return In(e)!==null||ev(e)}function ev(e){return Gu(e)!==null}function tv(e){let t=Gu(e);if(!t)return null;let r=JSON.parse(QI(t,"utf8")).bin;if(!r)return null;if(typeof r=="string")return bi(Wu(t),r);for(let i of js(e)){let o=r[i];if(o)return bi(Wu(t),o)}return null}function Gu(e){if(!e.bundledNpmPackage)return null;try{return ZI.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function Bs(e,t){for(let n of e.projectLocalBinaries??[]){let r=bi(t,n);if(Os(r))return r}return null}function nv(e,t){return Bs(e,t)??In(e)}function Ju(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||Hs(n,t))return t;let r=Qu(n,t);return r?{...t,DOTNET_ROOT:r}:t}function zu(e,t){let n=Si(e),r=t?nv(e,t):In(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=rv(r);return{language:e.language,binaryLabel:n,installed:!0,runnable:i.runnable,resolvedBinary:r,installUrl:e.installUrl,note:i.note}}function Ku(e,t){let n=e.installMethods,r=Si(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(Le(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{$s(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env});let o=In(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 rv(e){if(Hs(e,process.env))return{runnable:!0};let t=Qu(e,process.env);if(t)return{runnable:!0,note:`using .NET 9 runtime from ${t}`};let n=Yu(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 Qu(e,t){for(let n of Yu(t))if(Hs(e,{...t,DOTNET_ROOT:n}))return n;return null}function Yu(e){let t=[],n=e.DOTNET_ROOT;if(n&&Os(n)&&t.push(n),XI()==="darwin"&&Le("brew"))try{let r=$s("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),i=bi(r,"libexec");Os(i)&&!t.includes(i)&&t.push(i)}catch{}return t}function Hs(e,t){try{return $s(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}import Ov from"better-sqlite3";import{existsSync as $v,readFileSync as jv,writeFileSync as Bv}from"fs";import{dirname as Hv,join as qv,resolve as Vv}from"path";import{readFileSync as iv,rmSync as ov,statSync as sv,mkdtempSync as av}from"fs";import{cpus as cv,tmpdir as lv}from"os";import{join as qs}from"path";import{Worker as uv}from"worker_threads";function Xu(e){return e.length>=8&&em(e.length)>1}function Zu(e){let t=em(e.vueFiles.length),n=dv(e.vueFiles),r=fv(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=av(qs(lv(),"scip-query-vue-workers-")),s=new SharedArrayBuffer(4),a=new Int32Array(s),c=mv(),l=Date.now();try{for(let m=0;m<r.length;m++)new uv(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[m],resultPath:qs(o,`${m}.json`),sharedBuffer:s}});for(;Atomics.load(a,0)<r.length;){if(Date.now()-l>c)throw new Error(`Vue reference workers timed out after ${(c/1e3).toFixed(0)}s`);Atomics.wait(a,0,Atomics.load(a,0),100)}let u=r.map((m,d)=>{let p=JSON.parse(iv(qs(o,`${d}.json`),"utf-8"));if(!p.ok)throw new Error(`Vue reference worker failed: ${p.error}`);return p.result});return{occurrences:u.flatMap(m=>m.occurrences),skippedReferences:u.reduce((m,d)=>m+d.skippedReferences,0)}}finally{ov(o,{recursive:!0,force:!0})}}function em(e){let t=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKERS??0),n=Number.isFinite(t)&&t>0?t:Math.min(8,Math.max(1,cv().length-1));return Math.max(1,Math.min(e,n))}function mv(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function dv(e){let t=pv(),n=[];for(let r of e){let i=tm(r),o=Math.max(1,Math.ceil(i/t));for(let s=0;s<o;s++)n.push({fileName:r,startOffset:Math.floor(i*s/o),endOffset:s===o-1?Number.POSITIVE_INFINITY:Math.floor(i*(s+1)/o),countFileSkip:s===0})}return n}function pv(){return Number.POSITIVE_INFINITY}function fv(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:gv(i)})).sort((i,o)=>o.weight-i.weight);for(let i of r){let o=n.reduce((s,a)=>a.weight<s.weight?a:s);o.tasks.push(i.task),o.weight+=i.weight}return n.map(i=>i.tasks).filter(i=>i.length>0)}function gv(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,tm(e.fileName)-e.startOffset)}function tm(e){try{return sv(e).size}catch{return 1}}import{createRequire as hv}from"module";import{existsSync as yv,readFileSync as Ws}from"fs";import{dirname as nm,extname as bv,join as rm,relative as Sv,resolve as xv}from"path";import{pathToFileURL as Cv}from"url";function Rv(e){e.transaction(()=>{e.prepare(`
695
+ `:` https://github.com/sourcegraph/scip/releases/tag/${Fm}
696
+ `),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function Tm(e){if(ja()==="darwin"&&He("brew")){e("Installing scip CLI via Homebrew...");try{if(Em("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),He("scip"))return e("Successfully installed scip CLI via Homebrew"),!0}catch(t){let n=t instanceof Error?t.message:String(t);e(`Homebrew install failed: ${n}`)}}if(He("go")){e("Installing scip CLI via go install...");try{if(Em("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),He("scip"))return e("Successfully installed scip CLI via go install"),!0}catch(t){let n=t instanceof Error?t.message:String(t);e(`go install failed: ${n}`)}}return e("Could not auto-install scip CLI."),e("Install manually from: https://github.com/sourcegraph/scip/releases"),!1}var lw=aw()==="win32",Ua=["scip-query","concrete-plan","scip-ai-cleanup","scip-explore","scip-debloat","scip-doc-reconcile","scip-maintainability","scip-react-maintainability","scip-vue-maintainability","scip-verify","scip-language-playbook"];function $m(e={}){let t=e.quiet?()=>{}:console.log,n=cw(import.meta.url),r=qa(Am(n),"..","skills"),i=[Qr(Wa(),".claude","skills"),Qr(Wa(),".codex","skills"),Qr(Wa(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[]};for(let s of i){let a=Am(s);if(!Ha(a))continue;rw(s,{recursive:!0});let c=uw(s);for(let l of Ua){let u=Qr(r,l),d=Qr(s,l);if(!Ha(u)){o.skipped.push(`${c}/${l}`);continue}if(Ha(d)){try{let m=ow(d);if(qa(m)===qa(u)){o.alreadyLinked.push(`${c}/${l}`),t(` ok: ${l} \u2192 ${c} (already linked)`);continue}}catch{o.skipped.push(`${c}/${l}`),t(` skip: ${l} \u2192 ${c} (exists, not a symlink)`);continue}sw(d)}iw(u,d,lw?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function uw(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{existsSync as q_}from"fs";import{execFileSync as IP}from"child_process";import{closeSync as DP,copyFileSync as kP,existsSync as Lo,mkdirSync as cc,mkdtempSync as wP,openSync as NP,readFileSync as wp,renameSync as lc,rmSync as uc,writeFileSync as Np}from"fs";import{basename as Ro,dirname as Rt,extname as PP,join as at}from"path";import dw from"better-sqlite3";import{execFileSync as mw}from"child_process";import{existsSync as pw,readdirSync as fw,readFileSync as gw}from"fs";import{extname as So,join as Mm}from"path";function Ot(e){let t=new Set((e.extensions??Yc).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!pw(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Yn(e.projectRoot),r=hw(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new dw(e.dbPath);try{let o=yw(i,r),s=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
697
+ VALUES (?, ?, NULL, ?)`),c=i.transaction(u=>{let d=0;for(let m of u){if(o.has(m))continue;let f=gw(Mm(e.projectRoot,m),"utf-8"),g=s.run(Sw(m),m,f);d+=Number(g.changes)}return d})(r),l={scanned:r.length,inserted:c,existing:r.length-c};return e.onStatus?.(`Augmented SQLite documents with ${c} auxiliary source file${c===1?"":"s"} (${l.existing} already present).`),l}finally{i.close()}}function hw(e,t){let n=bw(e,t);if(n)return n;let r=[],i=o=>{let s=o?Mm(e,o):e,a;try{a=fw(s,{withFileTypes:!0})}catch{return}for(let c of a){if(Ko.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(l);continue}t.has(So(c.name).toLowerCase())&&r.push(l)}};return i(""),r.sort()}function bw(e,t){try{return mw("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
698
+ `).filter(r=>r&&t.has(So(r).toLowerCase())).sort()}catch{return null}}function yw(e,t){let n=new Set,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),s=e.prepare(`SELECT relative_path FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let a of s)n.add(a.relative_path)}return n}function Sw(e){return So(e).toLowerCase()===".vue"?"vue":So(e).replace(/^\./,"").toLowerCase()||"source"}import{execFileSync as xw}from"child_process";import{existsSync as Cw,readdirSync as jm}from"fs";import{extname as Bm,join as Vm}from"path";var vw=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),Rw=[{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:"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 vt(e){let t=[],n=Lw(e),r=ww(e);for(let i of Rw){if(Iw(e,i.files)){t.push(i.language);continue}if(Dw(n,i.globs)){t.push(i.language);continue}Pw(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&Om(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&Om(t,"c"),t}function Lw(e){try{return jm(e)}catch{return[]}}function Iw(e,t){return t?.length?t.some(n=>Cw(Vm(e,n))):!1}function Dw(e,t){return t?.length?e.some(n=>t.some(r=>kw(n,r))):!1}function kw(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 ww(e){let t=Nw(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=jm(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=Vm(i,s.name);if(s.isDirectory()){vw.has(s.name)||r.push(a);continue}let c=Bm(s.name).toLowerCase();c&&n.add(c)}}return n}function Nw(e){try{let t=xw("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(`
699
+ `)){if(!r)continue;let i=Bm(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function Pw(e,t){return t?.length?t.some(n=>e.has(n)):!1}function Om(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{existsSync as Hm,readdirSync as _w}from"fs";import{join as Ja}from"path";var Ew={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n})=>{let r=["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&r.splice(1,0,"--pnpm-workspaces"),{binary:n,args:r}},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"},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",qm(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",qm(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=Ja(e,"vendor","bin","scip-php"),r=Ja(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",Hm(r)?r:Hm(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function Xr(e){return Ew[e]}function qm(e,t){let n;try{n=_w(e)}catch{return null}for(let r of n)if(t.some(i=>r.endsWith(i)))return Ja(e,r);return null}import{readFileSync as Fw,writeFileSync as Tw}from"fs";import{create as Ga}from"@bufbuild/protobuf";import{deserializeSCIP as Aw,serializeSCIP as $w,DocumentSchema as Mw,IndexSchema as Ow,SymbolInformationSchema as jw}from"@c4312/scip";function Bw(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=Vw(e),n=Hw(e.flatMap(i=>i.documents??[])),r=Um(e.flatMap(i=>i.externalSymbols??[]));return Ga(Ow,{metadata:t,documents:n,externalSymbols:r})}function Wm(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>Aw(Fw(i))),r=Bw(n);return Tw(t,Buffer.from($w(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function Vw(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 Hw(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,Ga(Mw,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:[...r.occurrences,...n.occurrences],symbols:Um([...r.symbols,...n.symbols]),text:Ww(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function Um(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,Ga(jw,{symbol:r.symbol,documentation:Uw([...r.documentation,...n.documentation]),relationships:qw([...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 qw(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 Ww(e,t){return e?t?e.length>=t.length?e:t:e:t}function Uw(e){return[...new Set(e)]}import{execFileSync as Jw}from"child_process";import{createHash as Gw}from"crypto";import{readdirSync as zw,readFileSync as Kw}from"fs";import{join as Gm}from"path";function Jm(e){return(Xw(e)??Yw(e)).filter(t=>t&&!zm(t)).sort()}function xn(e,t={}){return(t.language?Jm(e).filter(r=>Qw(r,t.language,t.markerFiles)):Jm(e)).map(r=>{let i=Gm(e,r);try{let o=Kw(i);return{path:r,size:o.byteLength,hash:Gw("sha256").update(o).digest("hex")}}catch{return{path:r,size:-1,hash:"unreadable"}}})}function Qw(e,t,n){let r=e.split("/").at(-1)??e;if(n?.includes(e)||n?.includes(r)||eN.has(r))return!0;let i=e.includes(".")?`.${e.split(".").at(-1).toLowerCase()}`:"";return(tN[t]??[]).includes(i)}function Xw(e){try{return Jw("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:50*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
700
+ `).filter(Boolean)}catch{return null}}function Yw(e){let t=[],n=[""];for(;n.length>0;){let r=n.pop(),i=r?Gm(e,r):e,o;try{o=zw(i,{withFileTypes:!0})}catch{continue}for(let s of o){let a=r?`${r}/${s.name}`:s.name;if(s.isDirectory()){zm(a)||n.push(a);continue}t.push(a)}}return t}function zm(e){return e.split("/").some(n=>Zw.has(n))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var Zw=new Set([".git","node_modules",".scipquery-cache",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]),eN=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"]),tN={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"]};import{readFileSync as nN,writeFileSync as rN}from"fs";import{create as Km}from"@bufbuild/protobuf";import{deserializeSCIP as iN,DocumentSchema as oN,IndexSchema as sN,serializeSCIP as aN,SymbolRole as cN}from"@c4312/scip";function Qm(e){let t;try{t=iN(nN(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=lN(t);return n.removedDefinitionOccurrences>0&&rN(e,Buffer.from(aN(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function lN(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&cN.Definition)===0||t.has(a.symbol)?!0:(n+=1,!1));if(s.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(Km(oN,{language:o.language,relativePath:o.relativePath,occurrences:s,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:Km(sN,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}import{execFile as uN}from"child_process";import{existsSync as xo,renameSync as Ka,rmSync as Qa}from"fs";import{cpus as dN}from"os";import{join as Xm}from"path";function mN(e,t,n){if(!e.defaultOutputPath)return;let r=Xm(t,e.defaultOutputPath);n!==r&&xo(r)&&Ka(r,n)}function pN(e,t,n){if(!e.defaultOutputPath)return null;let r=Xm(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Qa(i,{force:!0}),xo(r)?(Ka(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function fN(e){e&&(Qa(e.defaultOutputPath,{force:!0}),e.backupPath&&xo(e.backupPath)&&Ka(e.backupPath,e.defaultOutputPath))}function gN(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),r=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(2,Math.max(1,dN().length-1));return Math.max(1,Math.min(e,Math.floor(r)))}async function Ym(e,t,n,r){let i=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=gN(o.length,r),c=await bN(o,a,l=>za(l,t,n));if(a>1){let l=new Map;for(let u of c.filter(d=>d.skipped)){let d=o.find(m=>m.language===u.language);d&&(n(`Retrying ${d.language} indexer serially after parallel failure...`),l.set(d.language,await za(d,t,n)))}s.push(...c.map(u=>l.get(u.language)??u))}else s.push(...c);for(let l of i)s.push(await za(l,t,n));return s.sort((l,u)=>e.findIndex(d=>d.language===l.language)-e.findIndex(d=>d.language===u.language))}async function za(e,t,n){n(`Indexing ${e.language} with ${e.resolvedBinary}...`),Qa(e.scipPath,{force:!0});let r=pN(e.config,t,e.scipPath);try{await hN(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),mN(e.config,t,e.scipPath)}catch(i){let o=i instanceof Error?i.message:String(i),s=`${e.resolvedBinary} indexer failed: ${o.split(`
701
+ `)[0]}`;return n(`Skipping ${e.language}: ${s}`),{language:e.language,scipPath:e.scipPath,skipped:{language:e.language,reason:s}}}finally{fN(r)}if(!xo(e.scipPath)){let i=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`;return n(`Skipping ${e.language}: ${i}`),{language:e.language,scipPath:e.scipPath,skipped:{language:e.language,reason:i}}}return{language:e.language,scipPath:e.scipPath}}function hN(e,t,n){return new Promise((r,i)=>{uN(e,[...t],n,o=>{o?i(o):r()})})}async function bN(e,t,n){if(e.length===0)return[];let r=new Array(e.length),i=0,o=Math.max(1,Math.min(e.length,t)),s=Array.from({length:o},async()=>{for(;i<e.length;){let a=i++;r[a]=await n(e[a])}});return await Promise.all(s),r}import{execFileSync as Ya}from"child_process";import{existsSync as Xa,readFileSync as yN}from"fs";import{createRequire as SN}from"module";import{platform as xN}from"os";import{dirname as Zm,join as Co}from"path";var CN=SN(import.meta.url);function Za(e){return[e.indexerBinary,...e.binaryAliases??[]]}function vo(e){let t=Za(e);return t.length===1?t[0]:t.join(" or ")}function tr(e){for(let t of Za(e))if(He(t))return t;return RN(e)}function ep(e){return tr(e)!==null||vN(e)}function vN(e){return tp(e)!==null}function RN(e){let t=tp(e);if(!t)return null;let r=JSON.parse(yN(t,"utf8")).bin;if(!r)return null;if(typeof r=="string")return Co(Zm(t),r);for(let i of Za(e)){let o=r[i];if(o)return Co(Zm(t),o)}return null}function tp(e){if(!e.bundledNpmPackage)return null;try{return CN.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function ec(e,t){for(let n of e.projectLocalBinaries??[]){let r=Co(t,n);if(Xa(r))return r}return null}function LN(e,t){return ec(e,t)??tr(e)}function np(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||tc(n,t))return t;let r=op(n,t);return r?{...t,DOTNET_ROOT:r}:t}function rp(e,t){let n=vo(e),r=t?LN(e,t):tr(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=IN(r);return{language:e.language,binaryLabel:n,installed:!0,runnable:i.runnable,resolvedBinary:r,installUrl:e.installUrl,note:i.note}}function ip(e,t){let n=e.installMethods,r=vo(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(He(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{Ya(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env});let o=tr(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 IN(e){if(tc(e,process.env))return{runnable:!0};let t=op(e,process.env);if(t)return{runnable:!0,note:`using .NET 9 runtime from ${t}`};let n=sp(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 op(e,t){for(let n of sp(t))if(tc(e,{...t,DOTNET_ROOT:n}))return n;return null}function sp(e){let t=[],n=e.DOTNET_ROOT;if(n&&Xa(n)&&t.push(n),xN()==="darwin"&&He("brew"))try{let r=Ya("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),i=Co(r,"libexec");Xa(i)&&!t.includes(i)&&t.push(i)}catch{}return t}function tc(e,t){try{return Ya(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}import oP from"better-sqlite3";import{existsSync as sP,readFileSync as aP,writeFileSync as cP}from"fs";import{dirname as lP,join as uP,resolve as dP}from"path";import{readFileSync as DN,rmSync as kN,statSync as wN,mkdtempSync as NN}from"fs";import{cpus as PN,tmpdir as _N}from"os";import{join as nc}from"path";import{Worker as EN}from"worker_threads";function ap(e){return e.length>=8&&lp(e.length)>1}function cp(e){let t=lp(e.vueFiles.length),n=TN(e.vueFiles),r=$N(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=NN(nc(_N(),"scip-query-vue-workers-")),s=new SharedArrayBuffer(4),a=new Int32Array(s),c=FN(),l=Date.now();try{for(let d=0;d<r.length;d++)new EN(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[d],resultPath:nc(o,`${d}.json`),sharedBuffer:s}});for(;Atomics.load(a,0)<r.length;){if(Date.now()-l>c)throw new Error(`Vue reference workers timed out after ${(c/1e3).toFixed(0)}s`);Atomics.wait(a,0,Atomics.load(a,0),100)}let u=r.map((d,m)=>{let f=JSON.parse(DN(nc(o,`${m}.json`),"utf-8"));if(!f.ok)throw new Error(`Vue reference worker failed: ${f.error}`);return f.result});return{occurrences:u.flatMap(d=>d.occurrences),skippedReferences:u.reduce((d,m)=>d+m.skippedReferences,0)}}finally{kN(o,{recursive:!0,force:!0})}}function lp(e){let t=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKERS??0),n=Number.isFinite(t)&&t>0?t:Math.min(8,Math.max(1,PN().length-1));return Math.max(1,Math.min(e,n))}function FN(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function TN(e){let t=AN(),n=[];for(let r of e){let i=up(r),o=Math.max(1,Math.ceil(i/t));for(let s=0;s<o;s++)n.push({fileName:r,startOffset:Math.floor(i*s/o),endOffset:s===o-1?Number.POSITIVE_INFINITY:Math.floor(i*(s+1)/o),countFileSkip:s===0})}return n}function AN(){return Number.POSITIVE_INFINITY}function $N(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:MN(i)})).sort((i,o)=>o.weight-i.weight);for(let i of r){let o=n.reduce((s,a)=>a.weight<s.weight?a:s);o.tasks.push(i.task),o.weight+=i.weight}return n.map(i=>i.tasks).filter(i=>i.length>0)}function MN(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,up(e.fileName)-e.startOffset)}function up(e){try{return wN(e).size}catch{return 1}}import{createRequire as ON}from"module";import{existsSync as jN,readFileSync as ic}from"fs";import{dirname as dp,extname as BN,join as mp,relative as VN,resolve as HN}from"path";import{pathToFileURL as qN}from"url";function WN(e){e.transaction(()=>{e.prepare(`
731
702
  DELETE FROM mentions
732
703
  WHERE chunk_id IN (
733
704
  SELECT c.id
@@ -742,12 +713,12 @@ Affected consumer files:`),L.list(e.affectedConsumers,t=>` ${t.file} (${t.cons
742
713
  FROM documents
743
714
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
744
715
  )
745
- `).run()})()}function im(e,t){return e.prepare(`
716
+ `).run()})()}function pp(e,t){return e.prepare(`
746
717
  SELECT relative_path AS relativePath
747
718
  FROM documents
748
719
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
749
720
  ORDER BY relative_path
750
- `).all().map(r=>xv(t,r.relativePath))}function om(e,t){let{vueCore:n,ts:r,volarTs:i}=Iv(e),{parsed:o,vueOptions:s}=vv(n,r,t),a=nm(t),c=n.createVueLanguagePlugin(r,o.options,s,p=>p),l=Dv(n,r,c),u=Nv(a,o),{languageServiceHost:m}=i.createLanguageServiceHost(r,r.sys,l,p=>p,u),d=r.createLanguageService(m);return{ts:r,language:l,languageService:d,fileNames:o.fileNames,configDir:a}}function Iv(e){let t=hv(Cv(rm(e,"package.json")).href);return{vueCore:Vs(t,"@vue/language-core",e),ts:Vs(t,"typescript",e),volarTs:Vs(t,"@volar/typescript",e)}}function vv(e,t,n){let r=t.readConfigFile(n,t.sys.readFile);if(r.error||!r.config)throw new Error(`Failed to read ${n}`);let o=e.createParsedCommandLine(t,t.sys,n).vueOptions;return typeof e.createGlobalTypesWriter=="function"&&(o.globalTypesPath=e.createGlobalTypesWriter(o,t.sys.writeFile)),{parsed:t.parseJsonConfigFileContent(r.config,t.sys,nm(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function Dv(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!yv(o))return;let s=Ws(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??Pv(o))});return r.current=i,i}function Nv(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Vs(e,t,n){try{return e(t)}catch(r){throw(typeof r=="object"&&r!==null&&"code"in r?r.code:null)==="MODULE_NOT_FOUND"?new Error(`Vue augmentation requires ${t} to be installed in ${n}. Install Vue/Volar dependencies for that project, then rerun augment-vue.`,{cause:r}):r}}function sm(e,t,n){let r=_v(e);return i=>{let o=Jt(t,i.fileName),s=n.get(i.fileName);if(!s)return null;let a=n.positionAt(s,i.textSpan.start),c=r.get(o);if(!c)return null;let l=c.containingByLine.get(a.line);return l!==void 0?l:Lv(c.starts,a.line,2)}}function _v(e){let t=e.prepare(`
721
+ `).all().map(r=>HN(t,r.relativePath))}function fp(e,t){let{vueCore:n,ts:r,volarTs:i}=UN(e),{parsed:o,vueOptions:s}=JN(n,r,t),a=dp(t),c=n.createVueLanguagePlugin(r,o.options,s,f=>f),l=GN(n,r,c),u=zN(a,o),{languageServiceHost:d}=i.createLanguageServiceHost(r,r.sys,l,f=>f,u),m=r.createLanguageService(d);return{ts:r,language:l,languageService:m,fileNames:o.fileNames,configDir:a}}function UN(e){let t=ON(qN(mp(e,"package.json")).href);return{vueCore:rc(t,"@vue/language-core",e),ts:rc(t,"typescript",e),volarTs:rc(t,"@volar/typescript",e)}}function JN(e,t,n){let r=t.readConfigFile(n,t.sys.readFile);if(r.error||!r.config)throw new Error(`Failed to read ${n}`);let o=e.createParsedCommandLine(t,t.sys,n).vueOptions;return typeof e.createGlobalTypesWriter=="function"&&(o.globalTypesPath=e.createGlobalTypesWriter(o,t.sys.writeFile)),{parsed:t.parseJsonConfigFileContent(r.config,t.sys,dp(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function GN(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!jN(o))return;let s=ic(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??eP(o))});return r.current=i,i}function zN(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function rc(e,t,n){try{return e(t)}catch(r){throw(typeof r=="object"&&r!==null&&"code"in r?r.code:null)==="MODULE_NOT_FOUND"?new Error(`Vue augmentation requires ${t} to be installed in ${n}. Install Vue/Volar dependencies for that project, then rerun augment-vue.`,{cause:r}):r}}function gp(e,t,n){let r=KN(e);return i=>{let o=Cn(t,i.fileName),s=n.get(i.fileName);if(!s)return null;let a=n.positionAt(s,i.textSpan.start),c=r.get(o);if(!c)return null;let l=c.containingByLine.get(a.line);return l!==void 0?l:QN(c.starts,a.line,2)}}function KN(e){let t=e.prepare(`
751
722
  SELECT
752
723
  d.relative_path AS relativePath,
753
724
  der.start_line AS startLine,
@@ -756,23 +727,23 @@ Affected consumer files:`),L.list(e.affectedConsumers,t=>` ${t.file} (${t.cons
756
727
  FROM defn_enclosing_ranges der
757
728
  JOIN documents d ON d.id = der.document_id
758
729
  ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
759
- `).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,r.symbolId)}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function Lv(e,t,n){let r=0,i=e.length-1;for(;r<=i;){let s=Math.floor((r+i)/2);e[s].line<t?r=s+1:i=s-1}let o=null;for(let s of[i,r]){let a=e[s];if(!a)continue;let c=Math.abs(a.line-t);c>n||(!o||c<o.distance)&&(o={distance:c,symbolId:a.symbolId})}return o?.symbolId??null}function am(e,t,n){let r=Tv(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
730
+ `).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,r.symbolId)}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function QN(e,t,n){let r=0,i=e.length-1;for(;r<=i;){let s=Math.floor((r+i)/2);e[s].line<t?r=s+1:i=s-1}let o=null;for(let s of[i,r]){let a=e[s];if(!a)continue;let c=Math.abs(a.line-t);c>n||(!o||c<o.distance)&&(o={distance:c,symbolId:a.symbolId})}return o?.symbolId??null}function hp(e,t,n){let r=rP(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
760
731
  INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
761
732
  VALUES (?, ?, ?, ?)
762
- `),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let u=Jt(t,l),m=hm(r.name,r.version,u);o.run(m,"default",7,`Vue component|${u}`);let d=Mv(i,r,t,l);d&&(s++,a.set(l,d))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function cm(e,t,n,r,i){return e.transaction(()=>(Rv(e),wv(e,t,n,r),kv(e,i)))()}function wv(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
733
+ `),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let u=Cn(t,l),d=Ip(r.name,r.version,u);o.run(d,"default",7,`Vue component|${u}`);let m=iP(i,r,t,l);m&&(s++,a.set(l,m))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function bp(e,t,n,r,i){return e.transaction(()=>(WN(e),XN(e,t,n,r),YN(e,i)))()}function XN(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
763
734
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
764
735
  VALUES (?, ?, ?, ?, X'00')
765
736
  `),s=e.prepare(`
766
737
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
767
738
  VALUES (?, ?, 1)
768
- `);for(let a of n){let c=r.get(a);if(!c)continue;let l=Jt(t,a),u=i.get(l);if(!u)continue;let m=o.run(u.id,-1,0,0);s.run(Number(m.lastInsertRowid),c)}}function lm(e,t,n,r,i){if(e.fileName.endsWith(".vue")){let o=r.language.scripts.get(e.fileName),s=o?.generated?.languagePlugin.typescript?.getServiceScript(o.generated.root)?.code;if(o&&s){let a=r.language.maps.get(s,o);if(Us(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function um(e){let t=new Set,n=[];for(let r of e){let i=mm(r);t.has(i)||(t.add(i),n.push(r))}return n}function mm(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function kv(e,t){let n=Av(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
739
+ `);for(let a of n){let c=r.get(a);if(!c)continue;let l=Cn(t,a),u=i.get(l);if(!u)continue;let d=o.run(u.id,-1,0,0);s.run(Number(d.lastInsertRowid),c)}}function yp(e,t,n,r,i){if(e.fileName.endsWith(".vue")){let o=r.language.scripts.get(e.fileName),s=o?.generated?.languagePlugin.typescript?.getServiceScript(o.generated.root)?.code;if(o&&s){let a=r.language.maps.get(s,o);if(oc(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function Sp(e){let t=new Set,n=[];for(let r of e){let i=xp(r);t.has(i)||(t.add(i),n.push(r))}return n}function xp(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function YN(e,t){let n=nP(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
769
740
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
770
741
  VALUES (?, ?, ?, ?, X'00')
771
742
  `),i=e.prepare(`
772
743
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
773
744
  VALUES (?, ?, 0)
774
- `),o=new Set,s=0,a=0;for(let c of t){let l=mm(c);if(o.has(l))continue;o.add(l);let u=n.get(c.sourceFile);if(!u)continue;let m=r.run(u,a++,c.sourceLine,c.sourceLine),d=i.run(Number(m.lastInsertRowid),c.symbolId);s+=Number(d.changes)}return s}function*dm(e){let t=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,n=new Set(["script","setup","template","style","lang","scoped","true","false","null","undefined","const","let","var","import","from","export","return","if","else","for","while","function","class","type","interface","as","await","async"]),r;for(;r=t.exec(e);){let i=r[0];n.has(i)||(yield{text:i,start:r.index,end:r.index+i.length})}}function pm(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function Us(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function Ev(e,t){let n=0,r=e.lineStarts.length-1;for(;n<=r;){let o=Math.floor((n+r)/2);e.lineStarts[o]<=t?n=o+1:r=o-1}let i=Math.max(0,r);return{line:i,character:t-e.lineStarts[i]}}function fm(e,t){return Jt(e,t).startsWith("node_modules/")}function Jt(e,t){return Sv(e,t).replaceAll("\\","/")}function Pv(e){switch(bv(e)){case".vue":return"vue";case".tsx":return"typescriptreact";case".ts":case".mts":case".cts":return"typescript";case".jsx":return"javascriptreact";case".js":case".mjs":case".cjs":return"javascript";case".json":return"json";default:return"typescript"}}function gm(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=Ws(t,"utf-8"),r={text:n,lineStarts:Fv(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:Ev}}function Fv(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function Av(e,t){let n=new Map,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),s=e.prepare(`SELECT id, relative_path AS relativePath FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let a of s)n.set(a.relativePath,a.id)}return n}function Tv(e){try{let t=JSON.parse(Ws(rm(e,"package.json"),"utf-8"));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function Mv(e,t,n,r){let i=Jt(n,r),o=hm(t.name,t.version,i);return e.get(o)?.id??null}function hm(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function Gs(e){yt({projectRoot:e.projectRoot,dbPath:e.dbPath});let t=Vv(e.projectRoot,e.tsconfig);if(!$v(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new Ov(e.dbPath);try{let r=im(n,e.projectRoot),i=qv(Hv(e.dbPath),"augment-vue-meta.json"),o=ym(n,e.projectRoot,e.tsconfig),s=Wv(i,o,e.onStatus);if(s)return s;let a=Uv({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus});return zv(i,ym(n,e.projectRoot,e.tsconfig),a),a}finally{n.close()}}function Wv(e,t,n){let r=Jv(e,t);return r&&n?.(`Vue references unchanged; reused ${r.resolvedReferences} cached resolved references.`),r}function Uv(e){let t=am(e.db,e.projectRoot,e.vueFiles),n=Gv(e,t),r=um(n.occurrences),i=cm(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,insertedMentions:i,skippedReferences:n.skippedReferences,syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function Gv(e,t){if(Xu(e.vueFiles))return Zu({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=Kv({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return Qv({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function Jv(e,t){try{let n=JSON.parse(jv(e,"utf-8"));return JSON.stringify(n.fingerprint)===JSON.stringify(t)?n.result:null}catch{return null}}function zv(e,t,n){Bv(e,JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)+`
775
- `)}function ym(e,t,n){let r=e.prepare(`
745
+ `),o=new Set,s=0,a=0;for(let c of t){let l=xp(c);if(o.has(l))continue;o.add(l);let u=n.get(c.sourceFile);if(!u)continue;let d=r.run(u,a++,c.sourceLine,c.sourceLine),m=i.run(Number(d.lastInsertRowid),c.symbolId);s+=Number(m.changes)}return s}function*Cp(e){let t=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,n=new Set(["script","setup","template","style","lang","scoped","true","false","null","undefined","const","let","var","import","from","export","return","if","else","for","while","function","class","type","interface","as","await","async"]),r;for(;r=t.exec(e);){let i=r[0];n.has(i)||(yield{text:i,start:r.index,end:r.index+i.length})}}function vp(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function oc(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function ZN(e,t){let n=0,r=e.lineStarts.length-1;for(;n<=r;){let o=Math.floor((n+r)/2);e.lineStarts[o]<=t?n=o+1:r=o-1}let i=Math.max(0,r);return{line:i,character:t-e.lineStarts[i]}}function Rp(e,t){return Cn(e,t).startsWith("node_modules/")}function Cn(e,t){return VN(e,t).replaceAll("\\","/")}function eP(e){switch(BN(e)){case".vue":return"vue";case".tsx":return"typescriptreact";case".ts":case".mts":case".cts":return"typescript";case".jsx":return"javascriptreact";case".js":case".mjs":case".cjs":return"javascript";case".json":return"json";default:return"typescript"}}function Lp(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=ic(t,"utf-8"),r={text:n,lineStarts:tP(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:ZN}}function tP(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function nP(e,t){let n=new Map,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),s=e.prepare(`SELECT id, relative_path AS relativePath FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let a of s)n.set(a.relativePath,a.id)}return n}function rP(e){try{let t=JSON.parse(ic(mp(e,"package.json"),"utf-8"));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function iP(e,t,n,r){let i=Cn(n,r),o=Ip(t.name,t.version,i);return e.get(o)?.id??null}function Ip(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function sc(e){Ot({projectRoot:e.projectRoot,dbPath:e.dbPath});let t=dP(e.projectRoot,e.tsconfig);if(!sP(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new oP(e.dbPath);try{let r=pp(n,e.projectRoot),i=uP(lP(e.dbPath),"augment-vue-meta.json"),o=Dp(n,e.projectRoot,e.tsconfig),s=mP(i,o,e.onStatus);if(s)return s;let a=pP({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus});return hP(i,Dp(n,e.projectRoot,e.tsconfig),a),a}finally{n.close()}}function mP(e,t,n){let r=gP(e,t);return r&&n?.(`Vue references unchanged; reused ${r.resolvedReferences} cached resolved references.`),r}function pP(e){let t=hp(e.db,e.projectRoot,e.vueFiles),n=fP(e,t),r=Sp(n.occurrences),i=bp(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,insertedMentions:i,skippedReferences:n.skippedReferences,syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function fP(e,t){if(ap(e.vueFiles))return cp({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=bP({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return yP({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function gP(e,t){try{let n=JSON.parse(aP(e,"utf-8"));return JSON.stringify(n.fingerprint)===JSON.stringify(t)?n.result:null}catch{return null}}function hP(e,t,n){cP(e,JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)+`
746
+ `)}function Dp(e,t,n){let r=e.prepare(`
776
747
  SELECT
777
748
  (SELECT COUNT(*) FROM documents) AS documents,
778
749
  (SELECT COUNT(*) FROM global_symbols) AS symbols,
@@ -781,120 +752,157 @@ Affected consumer files:`),L.list(e.affectedConsumers,t=>` ${t.file} (${t.cons
781
752
  (SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
782
753
  (SELECT MAX(id) FROM chunks) AS maxChunkId,
783
754
  (SELECT MAX(id) FROM global_symbols) AS maxSymbolId
784
- `).get();return{version:2,tsconfig:n,files:hi(t),db:r}}function Kv(e){let t=gm();return{projectRoot:e.projectRoot,context:om(e.projectRoot,e.configPath),symbolLookup:sm(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function Qv(e){let t=[],n=0,r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=Yv(e,i);t.push(...o.occurrences),n+=o.skippedReferences}return{occurrences:t,skippedReferences:n}}function Yv(e,t){let n=e.context.language.scripts.get(t.fileName),r=n?.generated?.languagePlugin.typescript?.getServiceScript(n.generated.root)?.code;if(!n||!r)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let i=e.sourceReader.get(t.fileName);if(!i)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let o=e.context.language.maps.get(r,n),s=Jt(e.projectRoot,t.fileName),a=[...dm(i.text)],c={tokens:a.filter(l=>l.start>=t.startOffset&&l.start<t.endOffset),tokenByStart:new Map(a.map(l=>[l.start,l])),tokenTextCounts:eD(a),processedStarts:new Set};return Xv({...e,fileName:t.fileName,sourceInfo:i,sourceFile:s,map:o,tokenContext:c})}function Xv(e){let t=[],n=0;for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start))continue;let i=pm(e.map,r.start);if(i===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(c=>!fm(e.projectRoot,c.fileName));if(!s){n++;continue}let a=lm(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(a===null){n++;continue}bm(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,a),e.tokenContext.processedStarts.add(r.start),Zv(t,e,r,i,a)}return{occurrences:t,skippedReferences:n}}function Zv(e,t,n,r,i){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let o of tD(t.context.languageService,t.fileName,r+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(o))continue;let s=t.tokenContext.tokenByStart.get(o);s&&(bm(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i),t.tokenContext.processedStarts.add(o))}}function bm(e,t,n,r,i,o){let s=t.positionAt(n,i.start);e.push({sourceFile:r,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+i.text.length,symbolId:o})}function eD(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function tD(e,t,n,r,i,o){let s=e.getDocumentHighlights?.(t,n,[t])??[],a=[];for(let c of s)if(c.fileName===t)for(let l of c.highlightSpans){let u=nD(r,l.textSpan.start,o,i.text);u!==null&&a.push(u)}return a}function nD(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=Us(e,t);if(o===null)return null;let s=n.get(o);return s?.text===r?s.start:null}async function Cm(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=lD(e),s=Date.now();Sm(zt(o.outputScip),{recursive:!0}),Sm(zt(o.outputDb),{recursive:!0});let a=e.languages??Gt(t);if(a.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");r(`Detected languages: ${a.join(", ")}`);let c=DD(t,a,{pnpmWorkspaces:e.pnpmWorkspaces}),l=ID(nt(zt(o.outputDb),"index.lock")),u=null;try{let m=uD({opts:e,paths:o,languages:a,fingerprint:c,start:s,onStatus:r});if(m)return m;gD(i,r);let d=mD(o);return u=d.runDir,await dD({opts:e,languages:a,projectRoot:t,paths:o,tempPaths:d,fingerprint:c,start:s,maxHeapMb:n,skipAutoInstall:i,onStatus:r})}finally{u&&Qs(u,{recursive:!0,force:!0}),l()}}function lD(e){let t=e.outputScip??nt(e.projectRoot,"index.scip"),n=e.outputDb??nt(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:nt(zt(n),"meta.json")}}function uD(e){if(e.opts.skipIfUnchanged===!1||!zs(e.paths.outputScip)||!zs(e.paths.outputDb)||!ND(e.paths.metaPath,e.fingerprint))return null;yt({projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let t=Date.now()-e.start;return e.onStatus(`Index unchanged; reused existing SQLite index in ${(t/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:t,reused:!0,skipped:[]}}function mD(e){let t=oD(nt(zt(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:nt(t,Ci(e.outputScip)),tempOutputDb:nt(t,Ci(e.outputDb)),tempMetaPath:nt(t,Ci(e.metaPath))}}async function dD(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},{indexedOutputs:n,skippedLanguages:r}=await pD(e,t);fD(e,t,n,r);let i=Date.now()-e.start;return e.onStatus(`Done in ${(i/1e3).toFixed(1)}s`),{languages:n.map(o=>o.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:i,reused:!1,skipped:r}}async function pD(e,t){let{preparedRuns:n,skippedLanguages:r}=hD({languages:e.languages,tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,onStatus:e.onStatus}),i=await Vu(n,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),{indexedOutputs:o}=bD(i,r);return SD(o,r,e.languages,e.opts.allowPartial,e.onStatus),{indexedOutputs:o,skippedLanguages:r}}function fD(e,t,n,r){xD(n,e.tempPaths.tempOutputScip,e.onStatus),CD(e.tempPaths.tempOutputScip,e.tempPaths.tempOutputDb,t,e.onStatus),yt({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),_D(e.tempPaths.tempMetaPath,{version:2,status:r.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.fingerprint,requestedLanguages:e.languages,indexedLanguages:n.map(i=>i.language),skipped:[...r]}),vD({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath})}function gD(e,t){if(!Le("scip")){if(e)throw new Error(`The scip CLI is required but not found on PATH.
785
- Install from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!Nu(t))throw new Error(`The scip CLI is required but could not be installed.
786
- Install manually from: https://github.com/sourcegraph/scip/releases`)}}function hD(e){let t=[],n=[],r=e.languages.map((i,o)=>({language:i,scipPath:e.languages.length>1?RD(e.tempOutputScip,i,o):e.tempOutputScip}));for(let{language:i,scipPath:o}of r){let s=yD({...e,language:i,scipPath:o});"skipped"in s?n.push(s.skipped):t.push(s.prepared)}return{preparedRuns:t,skippedLanguages:n}}function yD(e){let t=gi(e.language),n=Si(t),r=Bs(t,e.projectRoot);if(!r&&!Uu(t)){if(e.skipAutoInstall){let a=`${n} not found on PATH (auto-install disabled). ${t.installUrl??""}`.trim();return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!Ku(t,e.onStatus)){let a=`${n} could not be auto-installed. ${t.installUrl?`Install manually from ${t.installUrl}`:`Install ${n} and put it on PATH.`}`;return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}}let i=r??In(t);if(!i){let a=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}let{binary:o,args:s}=t.indexArgs({projectRoot:e.projectRoot,outputPath:e.scipPath,pnpmWorkspaces:e.pnpmWorkspaces,indexerBinary:i});return{prepared:{language:e.language,scipPath:e.scipPath,config:t,resolvedBinary:i,binary:o,args:s,env:Ju(t,e.env,i)}}}function bD(e,t){let n=[];for(let r of e)r.skipped?t.push(r.skipped):n.push({language:r.language,scipPath:r.scipPath});return{indexedOutputs:n}}function SD(e,t,n,r,i){if(e.length===0){let o=t.map(s=>` - ${s.language}: ${s.reason}`).join(`
755
+ `).get();return{version:2,tsconfig:n,files:xn(t),db:r}}function bP(e){let t=Lp();return{projectRoot:e.projectRoot,context:fp(e.projectRoot,e.configPath),symbolLookup:gp(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function yP(e){let t=[],n=0,r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=SP(e,i);t.push(...o.occurrences),n+=o.skippedReferences}return{occurrences:t,skippedReferences:n}}function SP(e,t){let n=e.context.language.scripts.get(t.fileName),r=n?.generated?.languagePlugin.typescript?.getServiceScript(n.generated.root)?.code;if(!n||!r)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let i=e.sourceReader.get(t.fileName);if(!i)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let o=e.context.language.maps.get(r,n),s=Cn(e.projectRoot,t.fileName),a=[...Cp(i.text)],c={tokens:a.filter(l=>l.start>=t.startOffset&&l.start<t.endOffset),tokenByStart:new Map(a.map(l=>[l.start,l])),tokenTextCounts:vP(a),processedStarts:new Set};return xP({...e,fileName:t.fileName,sourceInfo:i,sourceFile:s,map:o,tokenContext:c})}function xP(e){let t=[],n=0;for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start))continue;let i=vp(e.map,r.start);if(i===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(c=>!Rp(e.projectRoot,c.fileName));if(!s){n++;continue}let a=yp(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(a===null){n++;continue}kp(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,a),e.tokenContext.processedStarts.add(r.start),CP(t,e,r,i,a)}return{occurrences:t,skippedReferences:n}}function CP(e,t,n,r,i){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let o of RP(t.context.languageService,t.fileName,r+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(o))continue;let s=t.tokenContext.tokenByStart.get(o);s&&(kp(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i),t.tokenContext.processedStarts.add(o))}}function kp(e,t,n,r,i,o){let s=t.positionAt(n,i.start);e.push({sourceFile:r,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+i.text.length,symbolId:o})}function vP(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function RP(e,t,n,r,i,o){let s=e.getDocumentHighlights?.(t,n,[t])??[],a=[];for(let c of s)if(c.fileName===t)for(let l of c.highlightSpans){let u=LP(r,l.textSpan.start,o,i.text);u!==null&&a.push(u)}return a}function LP(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=oc(e,t);if(o===null)return null;let s=n.get(o);return s?.text===r?s.start:null}async function Pp(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=_P(e),s=Date.now();cc(Rt(o.outputScip),{recursive:!0}),cc(Rt(o.outputDb),{recursive:!0});let a=e.languages??vt(t);if(a.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");r(`Detected languages: ${a.join(", ")}`);let c=KP(t,a,{pnpmWorkspaces:e.pnpmWorkspaces}),l=GP(at(Rt(o.outputDb),"index.lock")),u=null;try{let d=EP({opts:e,paths:o,languages:a,fingerprint:c,start:s,onStatus:r});if(d)return d;jP(i,r);let m=FP(o);return u=m.runDir,await TP({opts:e,languages:a,projectRoot:t,paths:o,tempPaths:m,fingerprint:c,start:s,maxHeapMb:n,skipAutoInstall:i,onStatus:r})}finally{u&&uc(u,{recursive:!0,force:!0}),l()}}function _P(e){let t=e.outputScip??at(e.projectRoot,"index.scip"),n=e.outputDb??at(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:at(Rt(n),"meta.json")}}function EP(e){if(e.opts.skipIfUnchanged===!1||!Lo(e.paths.outputScip)||!Lo(e.paths.outputDb)||!QP(e.paths.metaPath,e.fingerprint))return null;Ot({projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let t=Date.now()-e.start;return e.onStatus(`Index unchanged; reused existing SQLite index in ${(t/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:t,reused:!0,skipped:[]}}function FP(e){let t=wP(at(Rt(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:at(t,Ro(e.outputScip)),tempOutputDb:at(t,Ro(e.outputDb)),tempMetaPath:at(t,Ro(e.metaPath))}}async function TP(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},{indexedOutputs:n,skippedLanguages:r,reusedLanguages:i}=await AP(e,t);i.length>0&&e.onStatus(`Reused ${i.length} cached language shard(s): ${i.join(", ")}`),$P(e,t,n,r);let o=Date.now()-e.start;return e.onStatus(`Done in ${(o/1e3).toFixed(1)}s`),{languages:n.map(s=>s.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:o,reused:!1,skipped:r}}async function AP(e,t){let n=MP(e),r=new Set(n.map(l=>l.language));for(let l of r)e.onStatus(`Reusing cached ${l} SCIP shard (language inputs unchanged).`);let{preparedRuns:i,skippedLanguages:o}=BP({languages:e.languages.filter(l=>!r.has(l)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,onStatus:e.onStatus}),s=await Ym(i,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),{indexedOutputs:a}=HP(s,o),c=[...n,...a];return qP(c,o,e.languages,e.opts.allowPartial,e.onStatus),{indexedOutputs:c,skippedLanguages:o,reusedLanguages:[...r]}}function $P(e,t,n,r){OP(e.paths.outputDb,n),WP(n,e.tempPaths.tempOutputScip,e.onStatus),UP(e.tempPaths.tempOutputScip,e.tempPaths.tempOutputDb,t,e.onStatus),Ot({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),XP(e.tempPaths.tempMetaPath,{version:3,status:r.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.fingerprint,languageFingerprints:_p(e.projectRoot,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces}),requestedLanguages:e.languages,indexedLanguages:n.map(i=>i.language),skipped:[...r]}),zP({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath})}function MP(e){let t;try{t=JSON.parse(wp(e.paths.metaPath,"utf-8"))}catch{return[]}if(t.version!==3||!t.languageFingerprints)return[];let n=[],r=_p(e.projectRoot,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces});for(let i of e.languages){let o=Ep(e.paths.outputDb,i);Lo(o)&&nr(t.languageFingerprints[i])===nr(r[i])&&n.push({language:i,scipPath:o})}return n}function OP(e,t){for(let n of t){let r=Ep(e,n.language);cc(Rt(r),{recursive:!0}),n.scipPath!==r&&kP(n.scipPath,r)}}function jP(e,t){if(!He("scip")){if(e)throw new Error(`The scip CLI is required but not found on PATH.
756
+ Install from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!Tm(t))throw new Error(`The scip CLI is required but could not be installed.
757
+ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function BP(e){let t=[],n=[],r=e.languages.map((i,o)=>({language:i,scipPath:e.languages.length>1?JP(e.tempOutputScip,i,o):e.tempOutputScip}));for(let{language:i,scipPath:o}of r){let s=VP({...e,language:i,scipPath:o});"skipped"in s?n.push(s.skipped):t.push(s.prepared)}return{preparedRuns:t,skippedLanguages:n}}function VP(e){let t=Xr(e.language),n=vo(t),r=ec(t,e.projectRoot);if(!r&&!ep(t)){if(e.skipAutoInstall){let a=`${n} not found on PATH (auto-install disabled). ${t.installUrl??""}`.trim();return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!ip(t,e.onStatus)){let a=`${n} could not be auto-installed. ${t.installUrl?`Install manually from ${t.installUrl}`:`Install ${n} and put it on PATH.`}`;return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}}let i=r??tr(t);if(!i){let a=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}let{binary:o,args:s}=t.indexArgs({projectRoot:e.projectRoot,outputPath:e.scipPath,pnpmWorkspaces:e.pnpmWorkspaces,indexerBinary:i});return{prepared:{language:e.language,scipPath:e.scipPath,config:t,resolvedBinary:i,binary:o,args:s,env:np(t,e.env,i)}}}function HP(e,t){let n=[];for(let r of e)r.skipped?t.push(r.skipped):n.push({language:r.language,scipPath:r.scipPath});return{indexedOutputs:n}}function qP(e,t,n,r,i){if(e.length===0){let o=t.map(s=>` - ${s.language}: ${s.reason}`).join(`
787
758
  `);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
788
759
  `+o)}if(t.length!==0&&(i(`Indexed ${e.length} of ${n.length} languages; skipped ${t.map(o=>o.language).join(", ")}.`),!r))throw new Error(`Failed to index all required languages; preserving the previous index. Pass --allow-partial to intentionally write an incomplete index.
789
760
  `+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
790
- `))}function xD(e,t,n){e.length>1?(n(`Merging ${e.length} language indexes...`),Mu(e.map(r=>r.scipPath),t)):e[0].scipPath!==t&&Ks(e[0].scipPath,t)}function CD(e,t,n,r){if(r("Converting to SQLite..."),!zs(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{let i=Hu(e);i.removedDefinitionOccurrences>0&&r(`Sanitized ${i.removedDefinitionOccurrences} invalid definition occurrences across ${i.touchedDocuments} documents before SQLite conversion.`),rD("scip",["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024})}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`Failed to convert SCIP index to SQLite: ${o}`,{cause:i})}}function RD(e,t,n){let r=cD(e)||".scip",i=Ci(e,r);return nt(zt(e),`${i}.${n+1}.${t}${r}`)}function ID(e){let t;try{t=sD(e,"wx")}catch(n){throw(typeof n=="object"&&n&&"code"in n?n.code:void 0)==="EEXIST"?new Error(`Another scip-query reindex is already running for ${zt(e)}.`,{cause:n}):n}return xm(t,JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()})+`
791
- `),()=>{try{iD(t)}finally{Qs(e,{force:!0})}}}function vD(e){Js(e.tempOutputScip,e.outputScip),Js(e.tempOutputDb,e.outputDb),Js(e.tempMetaPath,e.metaPath)}function Js(e,t){Qs(`${t}.tmp-replace`,{force:!0}),Ks(e,`${t}.tmp-replace`),Ks(`${t}.tmp-replace`,t)}function DD(e,t,n){return{version:1,languages:[...t].sort(),pnpmWorkspaces:n.pnpmWorkspaces===!0,files:hi(e)}}function ND(e,t){try{let n=JSON.parse(aD(e,"utf-8"));return n.version===2&&n.status==="complete"&&xi(n.fingerprint)===xi(t)&&xi([...n.indexedLanguages??[]].sort())===xi(t.languages)}catch{return!1}}function _D(e,t){xm(e,`${JSON.stringify(t,null,2)}
792
- `)}function xi(e){return JSON.stringify(e)}import{createRequire as LD}from"module";var wD=LD(import.meta.url);function Rm(e,t=[]){let n=kD(),r=ao(e,t),i=r[0];return n?r.length===0?{available:!1,dependencyAvailable:n,reason:"no tsconfig found"}:{available:!0,dependencyAvailable:n,tsconfigPath:i,tsconfigPaths:r}:{available:!1,dependencyAvailable:n,tsconfigPath:i,tsconfigPaths:r,reason:"ts-morph is not installed"}}function kD(){try{return wD.resolve("ts-morph"),!0}catch{return!1}}function Ys(e,t){let n=t.languages??Gt(e),r=n.map(o=>{let s=zu(gi(o),e);return{...s,language:o,resolvedBinary:s.resolvedBinary??void 0}}),i=n.includes("typescript")?{language:"typescript",...Rm(e,t.semantic?.typescript?.tsconfigs)}:void 0;return{languages:n,indexers:r,semantic:i}}import{watch as ED}from"fs";import{existsSync as Im,renameSync as vm}from"fs";import{join as PD,relative as FD}from"path";import{fork as AD}from"child_process";import TD from"ignore";var Ri=class{projectRoot;watchConfig;indexPaths;languages;pnpmWorkspaces;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.watchConfig=mu(t.config),this.indexPaths=Cn(t.projectRoot,t.config),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onError=t.onError??(n=>console.error(n.message)),this.gitignoreFilter=Sn(t.projectRoot),this.extraIgnore=TD(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"});try{let t=ED(this.projectRoot,{recursive:!0},(n,r)=>{r&&!this.stopped&&this.handleFileChange(r)});this.fsWatchers.push(t)}catch{this.onError(new Error("Failed to start file watcher. On Linux, you may need to increase inotify limits: sysctl -w fs.inotify.max_user_watches=524288"))}}stop(){this.stopped=!0;for(let t of this.fsWatchers)t.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.setStatus({state:"idle"})}handleFileChange(t){let n=FD(this.projectRoot,PD(this.projectRoot,t));if(this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||t.endsWith(".scipquery.json"))return;if(this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}this.clearDebounceTimer();let r=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:r}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let t=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&t<this.watchConfig.cooldownMs){let r=this.watchConfig.cooldownMs-t;this.dirty=!0;let i=Date.now()+r;this.setStatus({state:"cooldown",until:i,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},r);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let n=Date.now();this.setStatus({state:"indexing",startedAt:n}),this.runReindex().then(r=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(r),this.dirty&&!this.stopped){let i=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:i,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(r=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(r instanceof Error?r:new Error(String(r))),this.setStatus({state:"idle"})})}runReindex(){return new Promise((t,n)=>{let r=Date.now(),i=this.indexPaths.dbPath+".tmp",o=MD(this.indexPaths.indexPath),s=AD(new URL("./reindex-worker.js",import.meta.url).pathname,[],{env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:o,SCIP_REINDEX_OUTPUT_DB:i,SCIP_REINDEX_LANGUAGES:this.languages?.join(",")??"",SCIP_REINDEX_PNPM_WORKSPACES:this.pnpmWorkspaces?"1":""},stdio:"pipe"});s.on("exit",a=>{if(a===0)try{Im(i)&&vm(i,this.indexPaths.dbPath),Im(o)&&vm(o,this.indexPaths.indexPath),t(Date.now()-r)}catch(c){n(new Error(`Atomic swap failed: ${c}`))}else n(new Error(`Reindex worker exited with code ${a}`))}),s.on("error",n)})}setStatus(t){this.status=t,this.onStatus(t)}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}};function MD(e){return e.endsWith(".scip")?e.slice(0,-5)+".tmp.scip":e+".tmp.scip"}import{chmodSync as OD,existsSync as Ii,readFileSync as vi,writeFileSync as _m}from"fs";import{join as mr}from"path";var ur="<!-- scip-query:agent-setup:begin -->",Xs="<!-- scip-query:agent-setup:end -->",Dm="# scip-query:agent-setup";function Lm(){if(process.stdin.isTTY)return"";try{return vi(0,"utf-8")}catch{return""}}function wm(e){if(!e.trim())return!1;try{return JSON.parse(e).stop_hook_active===!0}catch{return!1}}function km(e){let t=[`scip-query diff-gate found ${e.findings.length} issue(s) in this diff \u2014 fix or knowingly accept them before finishing:`];for(let n of e.findings)t.push(`- [${n.check}] ${n.message}`),t.push(` -> ${n.remediation}`);return t.join(`
793
- `)}function Em(e,t={}){let n={written:[],unchanged:[],skipped:[]};return $D(e,n),t.gitHook&&jD(e,n),n}function $D(e,t){let n=[ur,"## scip-query","","This repo is indexed by scip-query (compiler-resolved code intelligence).","","- Unsure how to explore, plan, verify, or clean up here: invoke the `scip-query` skill \u2014 it routes to the right specialist skill.","- For non-trivial implementation requests: plan first (`concrete-plan` skill, anchored by `scip-query plan-context <target>`), then implement.","- After the change, run the check matching what you did: extracted a helper -> `scip-query incomplete-migration`; new helper -> `scip-query recent-duplicates`; new params -> `scip-query unused-params`; new wrapper -> `scip-query wrapper-candidates`; schema/config change -> `scip-query co-change <file>`; deleted code -> `scip-query cleanup-plan --verify`.","- Before declaring the work done: `scip-query reindex && scip-query diff-gate` \u2014 fix findings or state why each is accepted.",Xs].join(`
794
- `);Nm(e,"AGENTS.md",n,t);let r=Ii(mr(e,"CLAUDE.md"))?vi(mr(e,"CLAUDE.md"),"utf-8"):"";if(r.includes("@AGENTS.md")&&!r.includes(ur)){t.unchanged.push("CLAUDE.md");return}let i=[ur,"@AGENTS.md",Xs].join(`
795
- `);Nm(e,"CLAUDE.md",i,t)}function Nm(e,t,n,r){let i=mr(e,t),o=Ii(i)?vi(i,"utf-8"):"",s;if(o.includes(ur)){let a=new RegExp(`${ur}[\\s\\S]*?${Xs}`);s=o.replace(a,n)}else s=o.length>0?`${o.replace(/\n*$/,`
761
+ `))}function WP(e,t,n){e.length>1?(n(`Merging ${e.length} language indexes...`),Wm(e.map(r=>r.scipPath),t)):e[0].scipPath!==t&&lc(e[0].scipPath,t)}function UP(e,t,n,r){if(r("Converting to SQLite..."),!Lo(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{let i=Qm(e);i.removedDefinitionOccurrences>0&&r(`Sanitized ${i.removedDefinitionOccurrences} invalid definition occurrences across ${i.touchedDocuments} documents before SQLite conversion.`),IP("scip",["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024})}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`Failed to convert SCIP index to SQLite: ${o}`,{cause:i})}}function JP(e,t,n){let r=PP(e)||".scip",i=Ro(e,r);return at(Rt(e),`${i}.${n+1}.${t}${r}`)}function GP(e){let t;try{t=NP(e,"wx")}catch(n){throw(typeof n=="object"&&n&&"code"in n?n.code:void 0)==="EEXIST"?new Error(`Another scip-query reindex is already running for ${Rt(e)}.`,{cause:n}):n}return Np(t,JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()})+`
762
+ `),()=>{try{DP(t)}finally{uc(e,{force:!0})}}}function zP(e){ac(e.tempOutputScip,e.outputScip),ac(e.tempOutputDb,e.outputDb),ac(e.tempMetaPath,e.metaPath)}function ac(e,t){uc(`${t}.tmp-replace`,{force:!0}),lc(e,`${t}.tmp-replace`),lc(`${t}.tmp-replace`,t)}function KP(e,t,n){return{version:1,languages:[...t].sort(),pnpmWorkspaces:n.pnpmWorkspaces===!0,files:xn(e)}}function _p(e,t,n){return Object.fromEntries(t.map(r=>{let i=Xr(r).markerFiles;return[r,{version:1,languages:[r],pnpmWorkspaces:r==="typescript"&&n.pnpmWorkspaces===!0,files:xn(e,{language:r,markerFiles:i})}]}))}function Ep(e,t){return at(Rt(e),"language-indexes",`${t}.scip`)}function QP(e,t){try{let n=JSON.parse(wp(e,"utf-8"));return(n.version===2||n.version===3)&&n.status==="complete"&&nr(n.fingerprint)===nr(t)&&nr([...n.indexedLanguages??[]].sort())===nr(t.languages)}catch{return!1}}function XP(e,t){Np(e,`${JSON.stringify(t,null,2)}
763
+ `)}function nr(e){return JSON.stringify(e)}import{existsSync as Fp,readFileSync as YP}from"fs";function Tp(e,t,n){let r=new Date().toISOString();if(!Fp(n.dbPath))return{state:"missing",checkedAt:r,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!Fp(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(YP(n.metaPath,"utf-8")),o=t.languages??vt(e),s=ZP(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);return{state:c?"fresh":"stale",checkedAt:r,metaPath:n.metaPath,updatedAt:i.updatedAt,reason:c?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:c?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 ZP(e,t,n){return{version:1,languages:[...t].sort(),pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces===!0,files:xn(e)}}import{execFileSync as S_}from"child_process";import{createRequire as e_}from"module";var t_=e_(import.meta.url);function Ap(e,t=[]){let n=n_(),r=ys(e,t),i=r[0];return n?r.length===0?{available:!1,dependencyAvailable:n,reason:"no tsconfig found"}:{available:!0,dependencyAvailable:n,tsconfigPath:i,tsconfigPaths:r}:{available:!1,dependencyAvailable:n,tsconfigPath:i,tsconfigPaths:r,reason:"ts-morph is not installed"}}function n_(){try{return t_.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as rr,spawnSync as jp}from"child_process";import{existsSync as Lt,mkdtempSync as Bp,readFileSync as r_,readdirSync as i_,rmSync as Vp,symlinkSync as o_,writeFileSync as s_}from"fs";import{tmpdir as Hp}from"os";import{join as qe}from"path";var a_=3e5,c_=12;function dc(e,t,n={}){let r=mc(e);if(r.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,dirtyOverlap:[],batches:[]};let i=l_(t,r),o=n.timeoutMs??a_,s=m_(e,t),a=Bp(qe(Hp(),"scip-cleanup-verify-")),c=[],l=new Set;try{rr("git",["-C",e,"worktree","add","--detach","--force",a,"HEAD"],{stdio:"ignore"}),p_(e,a);for(let u of r)for(let d of Op(u,a,o).errorKeys)l.add(d);for(let u of t.batches){Wp(a,u);let d=[];for(let m of r){let f=Op(m,a,o);d.push(...f.rawErrors.filter(g=>!l.has(qp(g))))}if(d.length===0)c.push({depth:u.depth,status:"verified"});else{c.push({depth:u.depth,status:"failed",errors:d.slice(0,c_)});break}}}finally{try{rr("git",["-C",e,"worktree","remove","--force",a],{stdio:"ignore"})}catch{Vp(a,{recursive:!0,force:!0})}}return{checkers:r.map(u=>u.label),uncoveredFiles:i,baselineErrors:l.size,dirtyOverlap:s,batches:c}}function l_(e,t){let n=new Set(t.flatMap(i=>i.coversExtensions));return[...new Set(e.batches.flatMap(i=>i.entries.map(o=>o.file)))].filter(i=>{let o=i.slice(i.lastIndexOf("."));return!n.has(o)}).sort()}function qp(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var $p=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"];function mc(e){let t=[];if(Lt(qe(e,"tsconfig.json"))){let n=qe(e,"node_modules",".bin","tsc");t.push(Lt(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:$p}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:$p})}if(Lt(qe(e,"go.mod"))&&t.push({label:"go build ./...",binary:"go",args:["build","./..."],coversExtensions:[".go"]}),["pyproject.toml","setup.py","requirements.txt"].some(n=>Lt(qe(e,n)))){let n=u_();n&&t.push(n)}for(let n of d_(e))t.push({label:`cargo check --quiet --manifest-path ${n}`,binary:"cargo",args:["check","--quiet","--manifest-path",n],coversExtensions:[".rs"],env:{...process.env,CARGO_TARGET_DIR:qe(e,n,"..","target")}});return t}function u_(){return Mp("ruff")?{label:"ruff check --select E9,F821,F822",binary:"ruff",args:["check","--quiet","--select","E9,F821,F822","."],coversExtensions:[".py"]}:Mp("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"]}:null}function Mp(e){try{return jp(e,["--version"],{stdio:"ignore",timeout:1e4}).status===0}catch{return!1}}function d_(e){let t=[];if(Lt(qe(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=i_(e)}catch{return t}for(let r of n)r==="node_modules"||r.startsWith(".")||Lt(qe(e,r,"Cargo.toml"))&&t.push(`${r}/Cargo.toml`);return t}function m_(e,t){let n;try{n=rr("git",["-C",e,"status","--porcelain"],{encoding:"utf-8"})}catch{return[]}let r=new Set(n.split(`
764
+ `).map(o=>o.slice(3).trim()).filter(o=>o!==""));return[...new Set(t.batches.flatMap(o=>o.entries.map(s=>s.file)))].filter(o=>r.has(o)).sort()}function p_(e,t){for(let n of["node_modules"]){let r=qe(e,n),i=qe(t,n);if(Lt(r)&&!Lt(i))try{o_(r,i,"junction")}catch{}}}function Wp(e,t){let n=new Map;for(let r of t.entries){let i=n.get(r.file)??[];i.push({start:r.startLine,end:r.endLine}),n.set(r.file,i)}for(let[r,i]of n){let o=qe(e,r);Lt(o)&&s_(o,f_(r_(o,"utf-8"),i,{rust:r.endsWith(".rs")}))}}function pc(e,t){for(let n of t)Wp(e,n)}function Up(e,t){let n=Bp(qe(Hp(),"scip-cleanup-patch-"));try{return rr("git",["-C",e,"worktree","add","--detach","--force",n,"HEAD"],{stdio:"ignore"}),pc(n,t),rr("git",["-C",n,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024})}finally{try{rr("git",["-C",e,"worktree","remove","--force",n],{stdio:"ignore"})}catch{Vp(n,{recursive:!0,force:!0})}}}function fc(e,t={}){if(t.all)return[...e.batches];if(t.batch!==void 0){let n=e.batches.find(r=>r.depth===t.batch);return n?[n]:[]}return[...e.batches]}function gc(e,t,n={}){let r=[];e.checkers.length===0&&r.push("No project checker was detected, so no deletion patch is compiler-verified."),e.uncoveredFiles.length>0&&r.push(`No detected checker covers: ${e.uncoveredFiles.join(", ")}.`),!n.allowDirty&&e.dirtyOverlap.length>0&&r.push(`Plan files are dirty in the working tree: ${e.dirtyOverlap.join(", ")}.`);let i=new Set(e.batches.filter(o=>o.status==="verified").map(o=>o.depth));for(let o of t)i.has(o.depth)||r.push(`Batch ${o.depth} is not compiler-verified.`);return r}function f_(e,t,n={}){let r=e.split(`
765
+ `),i=(n.rust===!0?g_(e):Kt(e)).split(`
766
+ `),o=new Set;for(let s of t){let a=h_(r,s.start),c=y_(i,a,Math.min(s.end,r.length-1));for(let l=a;l<=c&&l<r.length;l++)o.add(l)}return r.filter((s,a)=>!o.has(a)).join(`
767
+ `)}function g_(e){return e.replace(/\/\/.*$/gm,t=>t.replace(/[^\r\n]/g," ")).replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\r\n]/g," ")).replace(/"(?:\\.|[^"\\\r\n])*"/g,t=>t.replace(/[^\r\n]/g," "))}function h_(e,t){let n=t;for(;n>0;){let r=(e[n-1]??"").trim();if(/^(?:\/\/\/|\/\/!|#\[|#!\[|\/\*\*|\*|\*\/|@\w)/.test(r))n-=1;else break}return n}var b_=200;function y_(e,t,n){let r=0;for(let i=t;i<e.length;i++){for(let o of e[i]??"")o==="("||o==="["||o==="{"?r+=1:(o===")"||o==="]"||o==="}")&&(r-=1);if(i>=n&&r<=0)return i;if(i-n>b_)break}return n}function Op(e,t,n){let r=jp(e.binary,e.args,{cwd:t,encoding:"utf-8",timeout:n,env:e.env??process.env,maxBuffer:33554432});if(r.status===0)return{ok:!0,rawErrors:[],errorKeys:new Set};let o=`${r.stdout??""}
768
+ ${r.stderr??""}`.split(`
769
+ `).map(s=>s.trim()).filter(s=>/\berror\b/i.test(s));return r.error&&o.length===0&&o.push(String(r.error)),{ok:!1,rawErrors:o,errorKeys:new Set(o.map(qp))}}var Jp={typescript:[".ts",".tsx",".mts",".cts"],javascript:[".js",".jsx",".vue"],java:[".java"],scala:[".scala"],kotlin:[".kt",".kts"],rust:[".rs"],python:[".py",".pyi"],ruby:[".rb"],go:[".go"],cpp:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],c:[".c",".h"],csharp:[".cs"],vb:[".vb"],dart:[".dart"],php:[".php"]},x_={typescript:{status:"available",reason:"AST/source fallback covers TypeScript imports, references, and source-backed evidence."},javascript:{status:"available",reason:"AST/source fallback covers JavaScript, JSX, and Vue script evidence."},java:{status:"available",reason:"AST-dispatched source fallback covers Java imports."},scala:{status:"available",reason:"AST-dispatched source fallback covers Scala imports."},kotlin:{status:"available",reason:"AST-dispatched source fallback covers Kotlin imports."},rust:{status:"available",reason:"AST/source fallback covers Rust imports and exports."},python:{status:"available",reason:"AST/source fallback covers Python imports."},ruby:{status:"available",reason:"AST/source fallback covers Ruby imports."},go:{status:"unavailable",reason:"No Go source-fallback adapter is registered; Go relies on SCIP graph facts."},cpp:{status:"available",reason:"AST/source fallback covers C++ includes."},c:{status:"available",reason:"AST/source fallback covers C includes."},csharp:{status:"available",reason:"AST-dispatched source fallback covers C# imports."},vb:{status:"available",reason:"AST-dispatched source fallback covers Visual Basic imports."},dart:{status:"partial",reason:"Dart source fallback is regex-only for imports and exports."},php:{status:"available",reason:"AST/source fallback covers PHP imports."}};function Io(e,t){let n=t.languages??vt(e),r=n.map(s=>{let a=rp(Xr(s),e);return{...a,language:s,resolvedBinary:a.resolvedBinary??void 0}}),i=n.includes("typescript")?{language:"typescript",...Ap(e,t.semantic?.typescript?.tsconfigs)}:void 0,o=mc(e).map(s=>({label:s.label,coversExtensions:s.coversExtensions}));return{languages:n,indexers:r,semantic:i,checkers:o,gitAvailable:L_(e)}}function hc(e){let t=e.indexers.filter(i=>i.runnable).length,n=e.languages.length===0||t===0?"unavailable":t===e.indexers.length?"available":"partial",r=e.semantic?e.semantic.available?"available":"partial":"unavailable";return{languages:e.languages,matrix:e.languages.map(i=>C_(e,i)),capabilities:[{id:"indexing",label:"SCIP indexing",status:n,evidence:"graph-fact",reason:n==="available"?"All detected/configured language indexers are runnable.":`${t}/${e.indexers.length} detected/configured language indexers are runnable.`},{id:"semantic-typescript",label:"TypeScript semantic provider",status:r,evidence:"semantic",reason:e.semantic?e.semantic.available?"ts-morph can load the configured TypeScript project.":e.semantic.reason??"TypeScript semantic checks will fall back to SCIP/source evidence.":"TypeScript is not detected/configured for this project."},{id:"heuristic-detectors",label:"Heuristic cleanup detectors",status:n==="unavailable"?"unavailable":"available",evidence:"heuristic",reason:n==="unavailable"?"Heuristic detectors need an indexed code graph.":"Similarity, migration, wrapper, stale-abstraction, and doc-drift detectors can run over the index."},{id:"cleanup-verification",label:"Compiler cleanup verification",status:e.checkers.length>0?"available":"unavailable",evidence:"compiler",reason:e.checkers.length>0?e.checkers.map(i=>i.label).join(", "):"No project checker was detected for cleanup-plan --verify."},{id:"diff-gate",label:"Git diff gate",status:e.gitAvailable&&n!=="unavailable"?"available":"unavailable",evidence:"git",reason:e.gitAvailable?"Git diff data is available for changed-file gates.":"Git is unavailable or the project root is not a git worktree."}]}}function C_(e,t){let n=e.indexers.find(a=>a.language===t),r=n?.runnable?"available":"unavailable",i=x_[t],o=t==="typescript"?v_(e):{id:"semantic",label:"Semantic provider",status:"unavailable",evidence:"semantic",reason:`No semantic provider is registered for ${t}; commands use graph and source evidence instead.`},s=R_(e,t);return{language:t,indexing:{id:"indexing",label:"SCIP indexing",status:r,evidence:"graph-fact",reason:n?.runnable?`${n.binaryLabel} is runnable${n.resolvedBinary?` at ${n.resolvedBinary}`:""}.`:n?.note??`${t} indexing is not runnable in this project.`},sourceFacts:{id:"source-facts",label:"Source fallback",status:r==="unavailable"?"unavailable":i.status,evidence:"heuristic",reason:r==="unavailable"?"Source fallback needs indexed documents before it can attach evidence.":i.reason},semantic:o,detectors:{id:"detectors",label:"Cleanup detectors",status:r==="unavailable"?"unavailable":"available",evidence:"heuristic",reason:r==="unavailable"?"Cleanup detectors need an indexed graph for this language.":"Graph-backed cleanup detectors can analyze this language; source and semantic precision depends on the rows above."},cleanupVerification:{id:"cleanup-verification",label:"Cleanup verification",status:s.length>0?"available":"unavailable",evidence:"compiler",reason:s.length>0?s.map(a=>a.label).join(", "):`No detected checker covers ${Jp[t].join(", ")} files.`}}}function v_(e){return e.semantic?{id:"semantic",label:"Semantic provider",status:e.semantic.available?"available":"partial",evidence:"semantic",reason:e.semantic.available?"ts-morph can load the configured TypeScript project.":e.semantic.reason??"TypeScript semantic checks fall back to SCIP/source evidence."}:{id:"semantic",label:"Semantic provider",status:"unavailable",evidence:"semantic",reason:"TypeScript is not detected/configured for this project."}}function R_(e,t){let n=new Set(Jp[t]);return e.checkers.filter(r=>r.coversExtensions.some(i=>n.has(i)))}function L_(e){try{return S_("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import{watch as I_}from"fs";import{existsSync as Gp,renameSync as zp}from"fs";import{join as D_,relative as k_}from"path";import{fork as w_}from"child_process";import N_ from"ignore";var Do=class{projectRoot;watchConfig;indexPaths;languages;pnpmWorkspaces;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.watchConfig=ym(t.config),this.indexPaths=Zn(t.projectRoot,t.config),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onError=t.onError??(n=>console.error(n.message)),this.gitignoreFilter=Yn(t.projectRoot),this.extraIgnore=N_(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"});try{let t=I_(this.projectRoot,{recursive:!0},(n,r)=>{r&&!this.stopped&&this.handleFileChange(r)});this.fsWatchers.push(t)}catch{this.onError(new Error("Failed to start file watcher. On Linux, you may need to increase inotify limits: sysctl -w fs.inotify.max_user_watches=524288"))}}stop(){this.stopped=!0;for(let t of this.fsWatchers)t.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.setStatus({state:"idle"})}handleFileChange(t){let n=k_(this.projectRoot,D_(this.projectRoot,t));if(this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||t.endsWith(".scipquery.json"))return;if(this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}this.clearDebounceTimer();let r=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:r}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let t=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&t<this.watchConfig.cooldownMs){let r=this.watchConfig.cooldownMs-t;this.dirty=!0;let i=Date.now()+r;this.setStatus({state:"cooldown",until:i,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},r);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let n=Date.now();this.setStatus({state:"indexing",startedAt:n}),this.runReindex().then(r=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(r),this.dirty&&!this.stopped){let i=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:i,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(r=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(r instanceof Error?r:new Error(String(r))),this.setStatus({state:"idle"})})}runReindex(){return new Promise((t,n)=>{let r=Date.now(),i=this.indexPaths.dbPath+".tmp",o=P_(this.indexPaths.indexPath),s=w_(new URL("./reindex-worker.js",import.meta.url).pathname,[],{env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:o,SCIP_REINDEX_OUTPUT_DB:i,SCIP_REINDEX_LANGUAGES:this.languages?.join(",")??"",SCIP_REINDEX_PNPM_WORKSPACES:this.pnpmWorkspaces?"1":""},stdio:"pipe"});s.on("exit",a=>{if(a===0)try{Gp(i)&&zp(i,this.indexPaths.dbPath),Gp(o)&&zp(o,this.indexPaths.indexPath),t(Date.now()-r)}catch(c){n(new Error(`Atomic swap failed: ${c}`))}else n(new Error(`Reindex worker exited with code ${a}`))}),s.on("error",n)})}setStatus(t){this.status=t,this.onStatus(t)}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}};function P_(e){return e.endsWith(".scip")?e.slice(0,-5)+".tmp.scip":e+".tmp.scip"}import{chmodSync as __,existsSync as ko,readFileSync as wo,writeFileSync as Xp}from"fs";import{join as Zr}from"path";var Yr="<!-- scip-query:agent-setup:begin -->",bc="<!-- scip-query:agent-setup:end -->",Kp="# scip-query:agent-setup";function Yp(){if(process.stdin.isTTY)return"";try{return wo(0,"utf-8")}catch{return""}}function Zp(e){if(!e.trim())return!1;try{return JSON.parse(e).stop_hook_active===!0}catch{return!1}}function ef(e){let t=[`scip-query diff-gate found ${e.findings.length} issue(s) in this diff \u2014 fix or knowingly accept them before finishing:`];for(let n of e.findings)t.push(`- [${n.check}] ${n.message}`),t.push(` -> ${n.remediation}`);return t.join(`
770
+ `)}function tf(e,t={}){let n={written:[],unchanged:[],skipped:[]};return E_(e,n),t.gitHook&&F_(e,n),n}function E_(e,t){let n=[Yr,"## scip-query","","This repo is indexed by scip-query (compiler-resolved code intelligence).","","- Unsure how to explore, plan, verify, or clean up here: invoke the `scip-query` skill \u2014 it routes to the right specialist skill.","- For non-trivial implementation requests: plan first (`concrete-plan` skill, anchored by `scip-query plan-context <target>`), then implement.","- After the change, run the check matching what you did: extracted a helper -> `scip-query incomplete-migration`; new helper -> `scip-query recent-duplicates`; new params -> `scip-query unused-params`; new wrapper -> `scip-query wrapper-candidates`; schema/config change -> `scip-query co-change <file>`; deleted code -> `scip-query cleanup-plan --verify`.","- Before declaring the work done: `scip-query reindex && scip-query diff-gate` \u2014 fix findings or state why each is accepted.",bc].join(`
771
+ `);Qp(e,"AGENTS.md",n,t);let r=ko(Zr(e,"CLAUDE.md"))?wo(Zr(e,"CLAUDE.md"),"utf-8"):"";if(r.includes("@AGENTS.md")&&!r.includes(Yr)){t.unchanged.push("CLAUDE.md");return}let i=[Yr,"@AGENTS.md",bc].join(`
772
+ `);Qp(e,"CLAUDE.md",i,t)}function Qp(e,t,n,r){let i=Zr(e,t),o=ko(i)?wo(i,"utf-8"):"",s;if(o.includes(Yr)){let a=new RegExp(`${Yr}[\\s\\S]*?${bc}`);s=o.replace(a,n)}else s=o.length>0?`${o.replace(/\n*$/,`
796
773
 
797
774
  `)}${n}
798
775
  `:`${n}
799
- `;s===o?r.unchanged.push(t):(_m(i,s),r.written.push(t))}function jD(e,t){let n=mr(e,".git","hooks");if(!Ii(n)){t.skipped.push({target:".git/hooks/pre-commit",reason:"no .git/hooks directory (not a git repository?)"});return}let r=mr(n,"pre-commit"),i=["#!/bin/sh",Dm,"scip-query diff-gate || {",' echo "scip-query diff-gate failed \u2014 fix findings or commit with --no-verify to knowingly accept." >&2'," exit 1","}",""].join(`
800
- `);if(Ii(r)){let o=vi(r,"utf-8");if(o.includes(Dm)){if(o===i){t.unchanged.push(".git/hooks/pre-commit");return}}else{t.skipped.push({target:".git/hooks/pre-commit",reason:"a pre-commit hook already exists \u2014 add `scip-query diff-gate` to it manually"});return}}_m(r,i),OD(r,493),t.written.push(".git/hooks/pre-commit")}function q(e){return(...t)=>{let{args:n,opts:r}=BD(t);tt(i=>e({db:i,args:n,opts:r}))}}function Z(e,t){return q(n=>{let r=bu(n.db,e,j(n.opts,"full"));t({...n,budget:r})})}function Pm(e){return q(t=>vn(t,e,{kind:"list"}))}function Fm(e){return q(t=>vn(t,e,{kind:"table",headers:e.headers,dashWidths:e.dashWidths}))}function Am(e){return q(t=>vn(t,e,{kind:"grouped",key:e.key}))}function Kt(e){return q(t=>Zs(t,e))}function Tm(e){return Kt({query:e.query,emptyMessage:e.emptyMessage,heuristicLabel:e.heuristicLabel,before:e.before,render:(t,n)=>L.sectionedReport(e.sections(t,n)),after:e.after})}function dr(e,t){return Z(e,n=>Zs(n,t))}function Mm(e,t){return dr(e,{query:t.query,emptyMessage:t.emptyMessage,heuristicLabel:t.heuristicLabel,before:t.before,render:(n,r)=>L.sectionedReport(t.sections(n,r)),after:t.after})}function rt(e,t){return Z(e,n=>vn(n,t,{kind:"list"}))}function Di(e,t){return Z(e,n=>vn(n,t,{kind:"table",headers:t.headers,dashWidths:t.dashWidths}))}function Ni(e,t){return Z(e,n=>vn(n,t,{kind:"grouped",key:t.key}))}function O(e,t){return String(e[t])}function We(e,t){let n=e[t];return typeof n=="string"?n:void 0}function E(e,t){let n=e[t];return typeof n=="string"?n:void 0}function bt(e,t){let n=e[t];return typeof n=="number"?n:void 0}function j(e,t){return!!e[t]}function Om(e,t){let n=e[t];return Array.isArray(n)&&n.every(r=>typeof r=="string")?n:[]}function C(e,t,n){return bt(e,t)??n}function vn(e,t,n){Zs(e,{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"?L.list(r,o=>t.format(o,i)):n.kind==="table"?L.table(n.headers,r.map(o=>t.format(o,i)),n.dashWidths):L.groupedByFile(r,o=>t.format(o,i),n.key?o=>n.key(o,i):void 0)},after:t.after})}function Zs(e,t){let n=t.query(e),r=t.emptyMessage?.(n,e);if(r){L.empty(r);return}t.heuristicLabel&&cr(t.heuristicLabel),t.before?.(n,e),t.render(n,e),t.after?.(n,e)}function BD(e){if(e.length===0)return{args:[],opts:{}};let t=e[e.length-1];return{args:e.slice(0,-1),opts:Ue(t)}}function Ue(e){if(!e||typeof e!="object")return{};let t=e;if(typeof t.opts=="function"){let n=t.opts();return n&&typeof n=="object"?n:{}}return e}var HD=new Set(["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php"]);function qD(e){return e.filter(t=>HD.has(t))}async function jm(e){let t=Ue(e),n=Me(),r=xn(n),i=Cn(n,r);try{let o=qD(Om(t,"language")),s=await Cm({projectRoot:n,languages:o.length>0?o:r.languages,outputScip:i.indexPath,outputDb:i.dbPath,pnpmWorkspaces:j(t,"pnpmWorkspaces")||r.indexer?.typescript?.pnpmWorkspaces,skipIfUnchanged:!j(t,"force"),allowPartial:j(t,"allowPartial"),indexerConcurrency:bt(t,"indexerConcurrency")});console.log(`${s.reused?"Reused":"Indexed"} ${s.languages.join(", ")} in ${(s.durationMs/1e3).toFixed(1)}s`)}catch(o){console.error(`error: ${o instanceof Error?o.message:o}`),process.exit(1)}}function Bm(){let e=Me(),t=Cs(e);try{let n=yt({projectRoot:e,dbPath:t,onStatus:r=>console.log(r)});console.log(`Scanned ${n.scanned} auxiliary source files; inserted ${n.inserted}.`)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function Hm(e){let t=Ue(e),n=Me(),r=Cs(n);try{let i=Gs({projectRoot:n,dbPath:r,tsconfig:E(t,"project")??"frontend/tsconfig.scip.json",onStatus:o=>console.log(o)});console.log(`Vue files: ${i.vueFiles}; resolved references: ${i.resolvedReferences}; inserted mentions: ${i.insertedMentions}.`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exit(1)}}function qm(e){let t=Ue(e);tt(n=>{let r=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),i=ht(n,{base:E(t,"base")}),o=ei(n,r,i.changedFiles);console.log(JSON.stringify(o))})}function Vm(e){let t=Ue(e);try{Ru(Cu({base:E(t,"base")}))}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function Wm(e,t){let n=Ue(t);tt(r=>{ar.includes(e)||(console.error(`error: Unknown health phase: ${e}`),process.exit(1));let i=cs(r,e,{scope:E(n,"scope"),full:j(n,"full")});console.log(JSON.stringify(i))})}function Um(e){let t=Ue(e);if(j(t,"writeBaseline")||j(t,"baseline")){VD(t);return}try{let n=Su({scope:E(t,"scope"),full:j(t,"full"),json:j(t,"json")});xu(n,j(t,"json"))}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function VD(e){let t=E(e,"scope");tt(n=>{if(j(e,"writeBaseline")){let i=rs(n,{scope:t});console.log(`Baseline written to ${i.path} (${i.findingCount} finding(s)).`);return}let r=tr(n,{scope:t});if(r.fixedFindings.length>0&&console.log(`${r.fixedFindings.length} finding(s) fixed since baseline. Re-run --write-baseline to ratchet down.`),r.newFindings.length===0){console.log(`OK: no new findings vs baseline (${r.baselineCount} baselined, ${r.current.length} current).`);return}console.log(`FAIL: ${r.newFindings.length} new finding(s) vs ${r.baselinePath}:`);for(let i of r.newFindings)console.log(` + ${i}`);process.exitCode=1})}function Gm(){let e=Lu(),t=e.installed.length+e.alreadyLinked.length;console.log(`
801
- ${e.installed.length} installed, ${e.alreadyLinked.length} already linked, ${e.skipped.length} skipped.`),t>0&&console.log("Skills will be available in your next Claude Code / Codex session.")}function Jm(){let e=!1;Ns()?console.log("scip CLI: installed"):(_s(),e=!0);let t=Me(),n=xn(t),r=Ys(t,n);if(r.languages.length===0){console.log(`
776
+ `;s===o?r.unchanged.push(t):(Xp(i,s),r.written.push(t))}function F_(e,t){let n=Zr(e,".git","hooks");if(!ko(n)){t.skipped.push({target:".git/hooks/pre-commit",reason:"no .git/hooks directory (not a git repository?)"});return}let r=Zr(n,"pre-commit"),i=["#!/bin/sh",Kp,"scip-query diff-gate || {",' echo "scip-query diff-gate failed \u2014 fix findings or commit with --no-verify to knowingly accept." >&2'," exit 1","}",""].join(`
777
+ `);if(ko(r)){let o=wo(r,"utf-8");if(o.includes(Kp)){if(o===i){t.unchanged.push(".git/hooks/pre-commit");return}}else{t.skipped.push({target:".git/hooks/pre-commit",reason:"a pre-commit hook already exists \u2014 add `scip-query diff-gate` to it manually"});return}}Xp(r,i),__(r,493),t.written.push(".git/hooks/pre-commit")}import{existsSync as T_,mkdirSync as A_,writeFileSync as $_}from"fs";import{dirname as M_,join as O_}from"path";function nf(e,t={}){let n=O_(e,".github","workflows","scip-query.yml"),r=j_();return T_(n)&&!t.force?{path:n,written:!1,skipped:!0,content:r,reason:"Workflow already exists. Re-run with --force to overwrite."}:(t.dryRun||(A_(M_(n),{recursive:!0}),$_(n,r)),{path:n,written:!t.dryRun,skipped:!1,content:r})}function j_(){return`name: scip-query
778
+
779
+ on:
780
+ pull_request:
781
+
782
+ jobs:
783
+ diff-gate:
784
+ runs-on: ubuntu-latest
785
+ steps:
786
+ - uses: actions/checkout@v4
787
+ with:
788
+ fetch-depth: 0
789
+ - uses: actions/setup-node@v4
790
+ with:
791
+ node-version: 22
792
+ - run: npm ci
793
+ - run: npx scip-query reindex
794
+ - run: npx scip-query diff-gate --base "origin/\${{ github.base_ref }}"
795
+ `}var rf=Symbol("option-value-source");function G(e){return(...t)=>{let{args:n,opts:r}=H_(t);st(i=>e({db:i,args:n,opts:r}))}}function Z(e,t){return G(n=>{let r=km(n.db,e,x(n.opts,"full"),{quiet:x(n.opts,"json")});t({...n,budget:r})})}function of(e){return G(t=>ir(t,e,{kind:"list"}))}function sf(e){return G(t=>ir(t,e,{kind:"table",headers:e.headers,dashWidths:e.dashWidths}))}function af(e){return G(t=>ir(t,e,{kind:"grouped",key:e.key}))}function vn(e){return G(t=>yc(t,e))}function cf(e){return vn({commandName:e.commandName,query:e.query,emptyMessage:e.emptyMessage,heuristicLabel:e.heuristicLabel,before:e.before,render:(t,n)=>I.sectionedReport(e.sections(t,n)),toJson:e.toJson,after:e.after})}function Ke(e,t){return Z(e,n=>yc(n,{...t,commandName:t.commandName??e}))}function lf(e,t){return Ke(e,{commandName:t.commandName??e,query:t.query,emptyMessage:t.emptyMessage,heuristicLabel:t.heuristicLabel,before:t.before,render:(n,r)=>I.sectionedReport(t.sections(n,r)),toJson:t.toJson,after:t.after})}function It(e,t){return Z(e,n=>ir(n,{...t,commandName:e},{kind:"list"}))}function No(e,t){return Z(e,n=>ir(n,{...t,commandName:e},{kind:"table",headers:t.headers,dashWidths:t.dashWidths}))}function Po(e,t){return Z(e,n=>ir(n,{...t,commandName:e},{kind:"grouped",key:t.key}))}function H(e,t){return String(e[t])}function he(e,t){let n=e[t];return typeof n=="string"?n:void 0}function P(e,t){let n=e[t];return typeof n=="string"?n:void 0}function we(e,t){let n=e[t];return typeof n=="number"?n:void 0}function x(e,t){return!!e[t]}function uf(e,t){let n=e[t];return Array.isArray(n)&&n.every(r=>typeof r=="string")?n:[]}function D(e,t,n){return we(e,t)??n}function O(e,t,n){let r=we(e,t),i=r!==void 0&&B_(e,t)!=="default";if(x(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.POSITIVE_INFINITY}return r??n}function B_(e,t){return e[rf]?.(t)}function ir(e,t,n){yc(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"?I.list(r,o=>t.format(o,i)):n.kind==="table"?I.table(n.headers,r.map(o=>t.format(o,i)),n.dashWidths):I.groupedByFile(r,o=>t.format(o,i),n.key?o=>n.key(o,i):void 0)},toJson:t.toJson,after:t.after})}function yc(e,t){let n=t.query(e);if(x(e.opts,"json")){T(t.commandName,e.args,e.opts,t.toJson?t.toJson(n,e):n);return}let r=t.emptyMessage?.(n,e);if(r){I.empty(r);return}t.heuristicLabel&&Kr(t.heuristicLabel),t.before?.(n,e),t.render(n,e),t.after?.(n,e)}function T(e,t,n,r){console.log(JSON.stringify({command:e,args:V_(t),options:n,result:r},null,2))}function V_(e){return e.filter(t=>typeof t=="string"||typeof t=="number"||typeof t=="boolean")}function H_(e){if(e.length===0)return{args:[],opts:{}};let t=e[e.length-1];return{args:e.slice(0,-1),opts:be(t)}}function be(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,rf,{value:r=>t.getOptionValueSource(r),enumerable:!1}),n)}return e}var W_=new Set(["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php"]);function U_(e){return e.filter(t=>W_.has(t))}async function df(e){let t=be(e),n=fe(),r=Ct(n),i=Zn(n,r);try{let o=U_(uf(t,"language")),s=await Pp({projectRoot:n,languages:o.length>0?o:r.languages,outputScip:i.indexPath,outputDb:i.dbPath,pnpmWorkspaces:x(t,"pnpmWorkspaces")||r.indexer?.typescript?.pnpmWorkspaces,skipIfUnchanged:!x(t,"force"),allowPartial:x(t,"allowPartial"),indexerConcurrency:we(t,"indexerConcurrency")});console.log(`${s.reused?"Reused":"Indexed"} ${s.languages.join(", ")} in ${(s.durationMs/1e3).toFixed(1)}s`)}catch(o){console.error(`error: ${o instanceof Error?o.message:o}`),process.exit(1)}}function mf(){let e=fe(),t=Fa(e);try{let n=Ot({projectRoot:e,dbPath:t,onStatus:r=>console.log(r)});console.log(`Scanned ${n.scanned} auxiliary source files; inserted ${n.inserted}.`)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function pf(e){let t=be(e),n=fe(),r=Fa(n);try{let i=sc({projectRoot:n,dbPath:r,tsconfig:P(t,"project")??"frontend/tsconfig.scip.json",onStatus:o=>console.log(o)});console.log(`Vue files: ${i.vueFiles}; resolved references: ${i.resolvedReferences}; inserted mentions: ${i.insertedMentions}.`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exit(1)}}function ff(e){let t=be(e);st(n=>{let r=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),i=it(n,{base:P(t,"base")}),o=Yi(n,r,i.changedFiles,i.changedRanges);console.log(JSON.stringify(o))})}function gf(e){let t=be(e);try{_m(Pm({base:P(t,"base")}))}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function hf(e,t){let n=be(t);st(r=>{Gr.includes(e)||(console.error(`error: Unknown health phase: ${e}`),process.exit(1));let i=xa(r,e,{scope:P(n,"scope"),full:x(n,"full")});console.log(JSON.stringify(i))})}function bf(e){let t=be(e);if(x(t,"writeBaseline")||x(t,"baseline")){J_(t);return}try{let n=wm({scope:P(t,"scope"),full:x(t,"full"),json:x(t,"json")});if(x(t,"json")){T("health",[],t,n);return}Nm(n,!1)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function J_(e){let t=P(e,"scope");st(n=>{if(x(e,"writeBaseline")){let i=ga(n,{scope:t});console.log(`Baseline written to ${i.path} (${i.findingCount} finding(s)).`);return}let r=Vr(n,{scope:t});if(r.fixedFindings.length>0&&console.log(`${r.fixedFindings.length} finding(s) fixed since baseline. Re-run --write-baseline to ratchet down.`),r.newFindings.length===0){console.log(`OK: no new findings vs baseline (${r.baselineCount} baselined, ${r.current.length} current).`);return}console.log(`FAIL: ${r.newFindings.length} new finding(s) vs ${r.baselinePath}:`);for(let i of r.newFindings)console.log(` + ${i}`);process.exitCode=1})}function yf(){let e=$m(),t=e.installed.length+e.alreadyLinked.length;console.log(`
796
+ ${e.installed.length} installed, ${e.alreadyLinked.length} already linked, ${e.skipped.length} skipped.`),t>0&&console.log("Skills will be available in your next Claude Code / Codex session.")}function Sf(){let e=!1;Ba()?console.log("scip CLI: installed"):(Va(),e=!0);let t=fe(),n=Ct(t),r=Io(t,n);if(r.languages.length===0){console.log(`
802
797
  No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
803
798
  Detected languages: ${r.languages.join(", ")}`),console.log(`
804
799
  Indexer readiness:`);for(let i of r.indexers){let o=i.runnable?" OK":i.installed?" WARN":" MISSING",s=i.resolvedBinary?` (${i.resolvedBinary})`:"";console.log(`${o} ${i.language}: ${i.binaryLabel}${s}`),i.note&&console.log(` ${i.note}`),!i.installed&&i.installUrl&&console.log(` install: ${i.installUrl}`),i.runnable||(e=!0)}if(r.semantic){let i=r.semantic,o=i.available?" OK":i.dependencyAvailable?" WARN":" MISSING",s=i.tsconfigPaths&&i.tsconfigPaths.length>1?` (${i.tsconfigPaths.length} tsconfigs)`:i.tsconfigPath?` (${i.tsconfigPath})`:"";console.log(`
805
- Semantic provider readiness:`),console.log(`${o} typescript: ts-morph${s}`),i.reason&&console.log(` ${i.reason}; semantic checks will fall back to SCIP/source evidence`)}process.exitCode=e?1:0}function zm(){let e=Me(),t=Gt(e),n=du(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function Km(e){let t=Ue(e),n=Me(),r=Em(n,{gitHook:j(t,"gitHook")});for(let i of r.written)console.log(` done: ${i}`);for(let i of r.unchanged)console.log(` ok: ${i} (already wired)`);for(let i of r.skipped)console.log(` skip: ${i.target} \u2014 ${i.reason}`);console.log(`
806
- Agents reading this project now know to route through the scip-query skills and gate their diffs.`),console.log("Keep the index fresh (`scip-query reindex` or `scip-query watch`) so the gate sees current code.")}function Qm(e){let t=Ue(e),n=Me(),r=xn(n),i=bt(t,"debounce"),o=bt(t,"cooldown");i&&((r.watch??={}).debounceMs=i),o&&((r.watch??={}).cooldownMs=o);let s=new Ri({projectRoot:n,config:r,languages:r.languages,onStatus:a=>{process.stdout.write(`\r\x1B[K${fu(a)}`)},onReindexComplete:a=>{console.log(`
800
+ Semantic provider readiness:`),console.log(`${o} typescript: ts-morph${s}`),i.reason&&console.log(` ${i.reason}; semantic checks will fall back to SCIP/source evidence`)}process.exitCode=e?1:0}function xf(e){vf(e,"capabilities")}function Cf(e){vf(e,"capability-matrix")}function vf(e,t){let n=be(e),r=fe(),i=Ct(r),o=Io(r,i),s=hc(o);if(x(n,"json")){T(t,[],n,s);return}Sc(s)}function Rf(){let e=fe(),t=vt(e),n=Sm(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function Lf(e){let t=be(e),n=fe(),r=Ct(n),i=mo(r);if(x(t,"json"))T("config-validate",[],t,{diagnostics:i});else if(i.length===0)console.log("Config OK.");else for(let o of i)console.log(`${o.level.toUpperCase()} ${o.path}: ${o.message}`);i.some(o=>o.level==="error")&&(process.exitCode=1)}function If(e,t){let n=be(t),r=P(n,"reason");if(!r||r.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}try{let i=xm(fe(),{id:String(e),check:P(n,"check"),file:P(n,"file"),reason:r,expiresAt:P(n,"expiresAt")});if(x(n,"json")){T("suppress",[String(e)],n,i);return}console.log(`Suppression added to ${i.path} (${i.suppressionCount} total).`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exitCode=1}}function Df(e){let t=be(e),{report:n,hasIndexerProblems:r,hasErrors:i}=kf("doctor");x(t,"json")?T("doctor",[],t,n):G_(n,r),process.exitCode=i?1:0}function kf(e){let{projectRoot:t,config:n,paths:r,dbPath:i}=po(),o=mo(n),s=Io(t,n),a=hc(s),c=Tp(t,n,r),l=s.indexers.some(d=>!d.runnable),u=o.some(d=>d.level==="error")||l||c.state==="missing"||c.state==="stale";return{report:{command:e,projectRoot:t,dbPath:i,configuredDbPath:r.dbPath,exists:q_(i),configDiagnostics:o,readiness:s,freshness:c,capabilities:a,ok:!u},hasIndexerProblems:l,hasErrors:u}}function wf(e){let t=be(e),n=fe(),r=tf(n,{gitHook:x(t,"gitHook")});for(let i of r.written)console.log(` done: ${i}`);for(let i of r.unchanged)console.log(` ok: ${i} (already wired)`);for(let i of r.skipped)console.log(` skip: ${i.target} \u2014 ${i.reason}`);console.log(`
801
+ Agents reading this project now know to route through the scip-query skills and gate their diffs.`),console.log("Keep the index fresh (`scip-query reindex` or `scip-query watch`) so the gate sees current code.")}function Nf(e){let t=be(e),n=fe(),r=nf(n,{force:x(t,"force"),dryRun:x(t,"dryRun")});if(x(t,"dryRun")){console.log(r.content);return}if(r.skipped){console.log(`skip: ${r.path} \u2014 ${r.reason}`);return}console.log(`done: ${r.path}`)}function Pf(e){let t=be(e),n=fe(),r=Ct(n),i=we(t,"debounce"),o=we(t,"cooldown");i&&((r.watch??={}).debounceMs=i),o&&((r.watch??={}).cooldownMs=o);let s=new Do({projectRoot:n,config:r,languages:r.languages,onStatus:a=>{process.stdout.write(`\r\x1B[K${vm(a)}`)},onReindexComplete:a=>{console.log(`
807
802
  Reindex complete in ${(a/1e3).toFixed(1)}s`)},onError:a=>{console.error(`
808
803
  Watch error: ${a.message}`)}});console.log(`Watching ${n}`),console.log(`Debounce: ${r.watch?.debounceMs??3e4}ms | Cooldown: ${r.watch?.cooldownMs??6e4}ms`),console.log(`Press Ctrl+C to stop.
809
804
  `),s.start(),process.on("SIGINT",()=>{s.stop(),console.log(`
810
- Stopped.`),process.exit(0)})}function Ym(){let{projectRoot:e,config:t,paths:n,dbPath:r}=li(),i=Ys(e,t);if(console.log(`Project: ${e}`),console.log(`DB path: ${r}`),r!==n.dbPath&&console.log(`Config: ${n.dbPath} (fallback to project root index.db)`),i.semantic){let o=i.semantic.available?"available":"fallback",s=i.semantic.tsconfigPaths&&i.semantic.tsconfigPaths.length>1?` (${i.semantic.tsconfigPaths.length} tsconfigs)`:i.semantic.tsconfigPath?` (${i.semantic.tsconfigPath})`:"";console.log(`TS sem: ${o}${s}`),i.semantic.reason&&console.log(`TS note: ${i.semantic.reason}`)}console.log(`Exists: ${$m(r)?"yes":"no"}`),$m(r)&&tt(o=>{let s=we(o);if(console.log(`Symbols: ${s.symbols}`),console.log(`Files: ${s.documents}`),console.log(`Size: ${Rn(s.indexSizeBytes)}`),s.lastBuilt){let a=Math.round((Date.now()-s.lastBuilt.getTime())/1e3);console.log(`Built: ${a}s ago`)}})}import{execFileSync as ea,spawnSync as td}from"child_process";import{existsSync as it,mkdtempSync as UD,readFileSync as GD,readdirSync as JD,rmSync as zD,symlinkSync as KD,writeFileSync as QD}from"fs";import{tmpdir as YD}from"os";import{join as Oe}from"path";var XD=3e5,ZD=12;function nd(e,t,n={}){let r=tN(e);if(r.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,dirtyOverlap:[],batches:[]};let i=eN(t,r),o=n.timeoutMs??XD,s=iN(e,t),a=UD(Oe(YD(),"scip-cleanup-verify-")),c=[],l=0;try{ea("git",["-C",e,"worktree","add","--detach","--force",a,"HEAD"],{stdio:"ignore"}),oN(e,a);let u=new Set;for(let m of r)for(let d of ed(m,a,o).errorKeys)u.add(d);l=u.size;for(let m of t.batches){sN(a,m);let d=[];for(let p of r){let h=ed(p,a,o);d.push(...h.rawErrors.filter(f=>!u.has(rd(f))))}if(d.length===0)c.push({depth:m.depth,status:"verified"});else{c.push({depth:m.depth,status:"failed",errors:d.slice(0,ZD)});break}}}finally{try{ea("git",["-C",e,"worktree","remove","--force",a],{stdio:"ignore"})}catch{zD(a,{recursive:!0,force:!0})}}return{checkers:r.map(u=>u.label),uncoveredFiles:i,baselineErrors:l,dirtyOverlap:s,batches:c}}function eN(e,t){let n=new Set(t.flatMap(i=>i.coversExtensions));return[...new Set(e.batches.flatMap(i=>i.entries.map(o=>o.file)))].filter(i=>{let o=i.slice(i.lastIndexOf("."));return!n.has(o)}).sort()}function rd(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var Xm=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"];function tN(e){let t=[];if(it(Oe(e,"tsconfig.json"))){let n=Oe(e,"node_modules",".bin","tsc");t.push(it(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:Xm}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:Xm})}if(it(Oe(e,"go.mod"))&&t.push({label:"go build ./...",binary:"go",args:["build","./..."],coversExtensions:[".go"]}),["pyproject.toml","setup.py","requirements.txt"].some(n=>it(Oe(e,n)))){let n=nN();n&&t.push(n)}for(let n of rN(e))t.push({label:`cargo check --quiet --manifest-path ${n}`,binary:"cargo",args:["check","--quiet","--manifest-path",n],coversExtensions:[".rs"],env:{...process.env,CARGO_TARGET_DIR:Oe(e,n,"..","target")}});return t}function nN(){return Zm("ruff")?{label:"ruff check --select E9,F821,F822",binary:"ruff",args:["check","--quiet","--select","E9,F821,F822","."],coversExtensions:[".py"]}:Zm("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"]}:null}function Zm(e){try{return td(e,["--version"],{stdio:"ignore",timeout:1e4}).status===0}catch{return!1}}function rN(e){let t=[];if(it(Oe(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n=[];try{n=JD(e)}catch{return t}for(let r of n)r==="node_modules"||r.startsWith(".")||it(Oe(e,r,"Cargo.toml"))&&t.push(`${r}/Cargo.toml`);return t}function iN(e,t){let n;try{n=ea("git",["-C",e,"status","--porcelain"],{encoding:"utf-8"})}catch{return[]}let r=new Set(n.split(`
811
- `).map(o=>o.slice(3).trim()).filter(o=>o!==""));return[...new Set(t.batches.flatMap(o=>o.entries.map(s=>s.file)))].filter(o=>r.has(o)).sort()}function oN(e,t){for(let n of["node_modules"]){let r=Oe(e,n),i=Oe(t,n);if(it(r)&&!it(i))try{KD(r,i,"junction")}catch{}}}function sN(e,t){let n=new Map;for(let r of t.entries){let i=n.get(r.file)??[];i.push({start:r.startLine,end:r.endLine}),n.set(r.file,i)}for(let[r,i]of n){let o=Oe(e,r);it(o)&&QD(o,aN(GD(o,"utf-8"),i,{rust:r.endsWith(".rs")}))}}function aN(e,t,n={}){let r=e.split(`
812
- `),i=(n.rust===!0?cN(e):_t(e)).split(`
813
- `),o=new Set;for(let s of t){let a=lN(r,s.start),c=mN(i,a,Math.min(s.end,r.length-1));for(let l=a;l<=c&&l<r.length;l++)o.add(l)}return r.filter((s,a)=>!o.has(a)).join(`
814
- `)}function cN(e){return e.replace(/\/\/.*$/gm,t=>t.replace(/[^\r\n]/g," ")).replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\r\n]/g," ")).replace(/"(?:\\.|[^"\\\r\n])*"/g,t=>t.replace(/[^\r\n]/g," "))}function lN(e,t){let n=t;for(;n>0;){let r=(e[n-1]??"").trim();if(/^(?:\/\/\/|\/\/!|#\[|#!\[|\/\*\*|\*|\*\/|@\w)/.test(r))n-=1;else break}return n}var uN=200;function mN(e,t,n){let r=0;for(let i=t;i<e.length;i++){for(let o of e[i]??"")o==="("||o==="["||o==="{"?r+=1:(o===")"||o==="]"||o==="}")&&(r-=1);if(i>=n&&r<=0)return i;if(i-n>uN)break}return n}function ed(e,t,n){let r=td(e.binary,e.args,{cwd:t,encoding:"utf-8",timeout:n,env:e.env??process.env,maxBuffer:33554432});if(r.status===0)return{ok:!0,rawErrors:[],errorKeys:new Set};let o=`${r.stdout??""}
815
- ${r.stderr??""}`.split(`
816
- `).map(s=>s.trim()).filter(s=>/\berror\b/i.test(s));return r.error&&o.length===0&&o.push(String(r.error)),{ok:!1,rawErrors:o,errorKeys:new Set(o.map(rd))}}function Ge({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,...o}){return{...o,renderShape:"list",handler:Pm({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i})}}function _i({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,headers:o,dashWidths:s,...a}){return{...a,renderShape:"table",handler:Fm({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,headers:o,dashWidths:s})}}function id({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,key:o,...s}){return{...s,renderShape:"grouped-by-file",handler:Am({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,key:o})}}function od({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,after:o,...s}){return{...s,renderShape:"sectioned-report",handler:Tm({query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,after:o})}}function Li({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,after:o,...s}){return{...s,budget:s.budget??"semantic",renderShape:"sectioned-report",handler:Mm(s.id,{query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,after:o})}}var dN=Z("dead",({db:e,args:t,opts:n,budget:r})=>{let i={scope:We(t,0)||void 0,minLoc:C(n,"minLoc",1),includeTests:j(n,"includeTests"),skipBarrels:j(n,"skipBarrels"),includeMembers:j(n,"includeMembers"),scanLimit:r.scanLimit,semantic:r.semantic},o=Ye(e,i),s=o.symbols.filter(f=>f.kind==="dead-code"),a=o.symbols.filter(f=>f.kind!=="dead-code"),c=!j(n,"onlyInternal"),l=!j(n,"onlyDead"),u=c?s:[],m=l?a:[];if(u.length===0&&m.length===0){L.empty("No matching dead-code symbols found.");return}let d=u.reduce((f,y)=>f+y.loc,0),p=m.reduce((f,y)=>f+y.loc,0);u.length>0&&sd(u,"DEAD CODE",` Zero references anywhere \u2014 no cross-file callers AND no same-file uses.
817
- Safe to delete.`,d),m.length>0&&(u.length>0&&console.log(""),sd(m,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
805
+ Stopped.`),process.exit(0)})}function _f(e){let t=be(e),{report:n}=kf("status");if(x(t,"json")){T("status",[],t,{...n,stats:K_(n.exists)});return}z_(n,{capabilities:x(t,"capabilities")})}function G_(e,t){console.log(`Doctor: ${e.ok?"OK":"needs attention"}`);for(let n of e.configDiagnostics)console.log(` ${n.level.toUpperCase()} ${n.path}: ${n.message}`);if(t)for(let n of e.readiness.indexers.filter(r=>!r.runnable))console.log(` MISSING ${n.language}: ${n.note??n.binaryLabel}`);console.log(` Freshness: ${e.freshness.state}${e.freshness.remedy?` (${e.freshness.remedy})`:""}`),Sc(e.capabilities)}function z_(e,t){if(console.log(`Project: ${e.projectRoot}`),console.log(`DB path: ${e.dbPath}`),e.dbPath!==e.configuredDbPath&&console.log(`Config: ${e.configuredDbPath} (fallback to project root index.db)`),e.readiness.semantic){let n=e.readiness.semantic.available?"available":"fallback",r=e.readiness.semantic.tsconfigPaths&&e.readiness.semantic.tsconfigPaths.length>1?` (${e.readiness.semantic.tsconfigPaths.length} tsconfigs)`:e.readiness.semantic.tsconfigPath?` (${e.readiness.semantic.tsconfigPath})`:"";console.log(`TS sem: ${n}${r}`),e.readiness.semantic.reason&&console.log(`TS note: ${e.readiness.semantic.reason}`)}console.log(`Exists: ${e.exists?"yes":"no"}`),console.log(`Fresh: ${e.freshness.state}${e.freshness.remedy?` (${e.freshness.remedy})`:""}`),Q_(e.exists),t.capabilities&&(console.log(""),Sc(e.capabilities))}function K_(e){if(e)return st(t=>{let n=Te(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function Q_(e){e&&st(t=>{let n=Te(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${er(n.indexSizeBytes)}`),n.lastBuilt){let r=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${r}s ago`)}})}function Sc(e){console.log(`Capabilities for: ${e.languages.join(", ")||"(no detected languages)"}`);for(let t of e.capabilities)console.log(` ${t.status.toUpperCase().padEnd(11)} ${t.label} [${t.evidence}]`),console.log(` ${t.reason}`);if(e.matrix.length!==0){console.log(`
806
+ Language matrix:`);for(let t of e.matrix){console.log(` ${t.language}`);for(let n of[t.indexing,t.sourceFacts,t.semantic,t.detectors,t.cleanupVerification])console.log(` ${n.status.toUpperCase().padEnd(11)} ${n.label}`),console.log(` ${n.reason}`)}}}function ei(e){return{...e,options:_(e.options)}}function ct({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,...o}){let s=ei(o);return{...s,renderShape:"list",handler:of({commandName:s.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i})}}function _o({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,headers:o,dashWidths:s,...a}){let c=ei(a);return{...c,renderShape:"table",handler:sf({commandName:c.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,headers:o,dashWidths:s})}}function Ef({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,key:o,...s}){let a=ei(s);return{...a,renderShape:"grouped-by-file",handler:af({commandName:a.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,key:o})}}function Ff({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,after:o,...s}){let a=ei(s);return{...a,renderShape:"sectioned-report",handler:cf({commandName:a.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,after:o})}}function Eo({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,after:o,...s}){let a=ei(s);return{...a,budget:a.budget??"semantic",renderShape:"sectioned-report",handler:lf(a.id,{commandName:a.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,after:o})}}var Y_=Z("dead",({db:e,args:t,opts:n,budget:r})=>{let i={scope:he(t,0)||void 0,minLoc:D(n,"minLoc",1),includeTests:x(n,"includeTests"),skipBarrels:x(n,"skipBarrels"),includeMembers:x(n,"includeMembers"),scanLimit:r.scanLimit,semantic:r.semantic},o=ht(e,i),s=o.symbols.filter(h=>h.kind==="dead-code"),a=o.symbols.filter(h=>h.kind!=="dead-code"),c=!x(n,"onlyInternal"),l=!x(n,"onlyDead"),u=c?s:[],d=l?a:[];if(x(n,"json")){T("dead",t,n,{...o,shown:{deadCode:u,fileInternal:d},totals:{deadCode:s.length,fileInternal:a.length}});return}if(u.length===0&&d.length===0){I.empty("No matching dead-code symbols found.");return}let m=u.reduce((h,b)=>h+b.loc,0),f=d.reduce((h,b)=>h+b.loc,0);u.length>0&&Tf(u,"DEAD CODE",` Zero references anywhere \u2014 no cross-file callers AND no same-file uses.
807
+ Safe to delete.`,m),d.length>0&&(u.length>0&&console.log(""),Tf(d,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
818
808
  single-use helper, an abstraction-in-progress, or a callback registered
819
809
  through a framework path that static analysis cannot trace (signal
820
810
  handlers, event listeners, dependency injection). NOT necessarily dead \u2014
821
- review case by case.`,p));let h=[];c&&h.push(`${u.length} dead code (${d} LOC)`),l&&h.push(`${m.length} file-internal (${p} LOC)`),console.log(`
822
- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`),console.log(`Total: ${u.length+m.length} symbols \u2014 ${h.join(" + ")}`)});function sd(e,t,n,r){console.log(`\u2550\u2550\u2550 ${t} (${e.length}, ${r} LOC) \u2550\u2550\u2550`),console.log(n),console.log("");let i=new Map;for(let a of e){let c=i.get(a.relativePath)??[];c.push(a),i.set(a.relativePath,c)}let o=[...i.entries()].map(([a,c])=>({file:a,bucket:c,totalLoc:c.reduce((l,u)=>l+u.loc,0)})).sort((a,c)=>c.totalLoc-a.totalLoc||a.file.localeCompare(c.file)),s=!0;for(let{file:a,bucket:c}of o){s||console.log(""),s=!1,console.log(` ${a}`),c.sort((l,u)=>l.startLine-u.startLine);for(let l of c)console.log(` ${me(l.startLine,l.endLine)} (${l.loc} LOC) ${l.shortName}`)}}var pN=rt("unused-imports",{query:({db:e,args:t,budget:n})=>Do(e,O(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
823
- ${e.length} unused import(s)`)}),fN=Ni("isolated",{query:({db:e,opts:t,budget:n})=>Tt(e,{scope:E(t,"scope"),minLoc:C(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${me(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
824
- ${e.length} isolated symbol(s)`)}),gN=Z("extract-candidates",({db:e,opts:t,budget:n})=>{let r=Mt(e,{scope:E(t,"scope"),minLoc:C(t,"minLoc",10),minCallees:C(t,"minCallees",6),limit:C(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic});if(r.length===0)return L.empty("No extraction candidates found.");cr("extraction candidates");for(let i of r){console.log(`
825
- ${ae(i.relativePath,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC, ${i.totalCallees} callees)`);for(let o=0;o<i.clusters.length;o++){let s=i.clusters[o];console.log(` Cluster ${o+1} (${Math.round(s.isolation*100)}% isolated, ${s.callees.length} callees):`);for(let a of s.callees)console.log(` ${a}`)}}console.log(`
826
- ${r.length} extraction candidate(s) found.`)}),hN=rt("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>Vt(e,{scope:E(t,"scope"),maxLoc:C(t,"maxLoc",15),limit:C(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${ae(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
811
+ review case by case.`,f));let g=[];c&&g.push(`${u.length} dead code (${m} LOC)`),l&&g.push(`${d.length} file-internal (${f} LOC)`),console.log(`
812
+ \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`),console.log(`Total: ${u.length+d.length} symbols \u2014 ${g.join(" + ")}`)});function Tf(e,t,n,r){console.log(`\u2550\u2550\u2550 ${t} (${e.length}, ${r} LOC) \u2550\u2550\u2550`),console.log(n),console.log("");let i=new Map;for(let a of e){let c=i.get(a.relativePath)??[];c.push(a),i.set(a.relativePath,c)}let o=[...i.entries()].map(([a,c])=>({file:a,bucket:c,totalLoc:c.reduce((l,u)=>l+u.loc,0)})).sort((a,c)=>c.totalLoc-a.totalLoc||a.file.localeCompare(c.file)),s=!0;for(let{file:a,bucket:c}of o){s||console.log(""),s=!1,console.log(` ${a}`),c.sort((l,u)=>l.startLine-u.startLine);for(let l of c)console.log(` ${ve(l.startLine,l.endLine)} (${l.loc} LOC) ${l.shortName}`)}}var Z_=It("unused-imports",{query:({db:e,args:t,budget:n})=>As(e,H(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
813
+ ${e.length} unused import(s)`)}),eE=Po("isolated",{query:({db:e,opts:t,budget:n})=>on(e,{scope:P(t,"scope"),minLoc:D(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${ve(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
814
+ ${e.length} isolated symbol(s)`)}),tE=Z("extract-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=dn(e,{scope:P(n,"scope"),minLoc:D(n,"minLoc",10),minCallees:D(n,"minCallees",6),limit:O(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic});if(x(n,"json")){T("extract-candidates",t,n,i);return}if(i.length===0)return I.empty("No extraction candidates found.");Kr("extraction candidates");for(let o of i){console.log(`
815
+ ${ge(o.relativePath,o.startLine,o.endLine)} ${o.shortName} (${o.loc} LOC, ${o.totalCallees} callees)`);for(let s=0;s<o.clusters.length;s++){let a=o.clusters[s];console.log(` Cluster ${s+1} (${Math.round(a.isolation*100)}% isolated, ${a.callees.length} callees):`);for(let c of a.callees)console.log(` ${c}`)}}console.log(`
816
+ ${i.length} extraction candidate(s) found.`)}),nE=It("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>yn(e,{scope:P(t,"scope"),maxLoc:D(t,"maxLoc",15),limit:O(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${ge(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
827
817
  Only called by: ${e.singleCallerShort} (fan-in: ${e.callerFanIn})`,emptyMessage:()=>"No wrapper candidates found.",heuristicLabel:"wrapper candidates",after:e=>console.log(`
828
- ${e.length} wrapper candidate(s).`)}),yN=rt("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>Ht(e,{scope:E(t,"scope"),maxLoc:C(t,"maxLoc",15),limit:C(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${ae(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
818
+ ${e.length} wrapper candidate(s).`)}),rE=It("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>hn(e,{scope:P(t,"scope"),maxLoc:D(t,"maxLoc",15),limit:O(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${ge(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
829
819
  Forwards to: ${e.forwardsToShort} (${e.forwardsToFile})`,emptyMessage:()=>"No passthrough candidates found.",heuristicLabel:"passthrough candidates",after:e=>console.log(`
830
- ${e.length} passthrough candidate(s).`)}),bN=rt("stale-abstractions",{query:({db:e,opts:t,budget:n})=>qt(e,{scope:E(t,"scope"),minLoc:C(t,"minLoc",3),limit:C(t,"limit",30),includeLowConfidence:j(t,"includeLowConfidence"),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.consumers===0?"unused":`${e.consumers} consumer`,n=e.barrelConsumers>0?`, +${e.barrelConsumers} barrel`:"";return` [${e.confidence}] ${ae(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
820
+ ${e.length} passthrough candidate(s).`)}),iE=It("stale-abstractions",{query:({db:e,opts:t,budget:n})=>bn(e,{scope:P(t,"scope"),minLoc:D(t,"minLoc",3),limit:O(t,"limit",30),includeLowConfidence:x(t,"includeLowConfidence"),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.consumers===0?"unused":`${e.consumers} consumer`,n=e.barrelConsumers>0?`, +${e.barrelConsumers} barrel`:"";return` [${e.confidence}] ${ge(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
831
821
  ${e.reason}`},emptyMessage:()=>"No stale abstractions found.",heuristicLabel:"stale abstraction candidates",after:e=>console.log(`
832
- ${e.length} stale abstraction(s).`)}),SN=Di("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>sr(e,{scope:E(t,"scope"),minLoc:C(t,"minLoc",10),limit:C(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${e.score.toFixed(1).padStart(5)} ${String(e.loc).padStart(4)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${String(e.calleeCount).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No complexity hotspots found.",heuristicLabel:"complexity hotspot candidates",dashWidths:[5,4,6,7,7,6]}),xN=dr("similar",{query:({db:e,args:t,opts:n,budget:r})=>{let i=We(t,0);return i?{mode:"target",rows:zn(e,i,{minSimilarity:C(n,"minSimilarity",.4),limit:C(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic})}:{mode:"all",rows:Xe(e,{minSimilarity:C(n,"minSimilarity",.4),limit:C(n,"limit",20),scope:E(n,"scope"),minCallees:C(n,"minCallees",4),crossFileOnly:j(n,"crossFileOnly"),scanLimit:r.scanLimit,semantic:r.semantic})}},emptyMessage:e=>{if(!(e.rows.length>0))return e.mode==="target"?"No similar symbols found.":"No similar symbol pairs found."},heuristicLabel:"similarity candidates",render:e=>{if(e.mode==="target"){L.list(e.rows,t=>{let n=t.similarityBasis??"callees",r=n==="source-tokens"?"Shared source tokens":"Shared callees",i=n==="source-tokens"?"Only tokens in":"Only in",o=[`
822
+ ${e.length} stale abstraction(s).`)}),oE=No("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>Jr(e,{scope:P(t,"scope"),minLoc:D(t,"minLoc",10),limit:O(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${e.score.toFixed(1).padStart(5)} ${String(e.loc).padStart(4)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${String(e.calleeCount).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No complexity hotspots found.",heuristicLabel:"complexity hotspot candidates",dashWidths:[5,4,6,7,7,6]}),sE=Ke("similar",{query:({db:e,args:t,opts:n,budget:r})=>{let i=he(t,0);return i?{mode:"target",rows:Pr(e,i,{minSimilarity:D(n,"minSimilarity",.4),limit:O(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic})}:{mode:"all",rows:bt(e,{minSimilarity:D(n,"minSimilarity",.4),limit:O(n,"limit",20),scope:P(n,"scope"),minCallees:D(n,"minCallees",4),crossFileOnly:x(n,"crossFileOnly"),scanLimit:r.scanLimit,semantic:r.semantic})}},emptyMessage:e=>{if(!(e.rows.length>0))return e.mode==="target"?"No similar symbols found.":"No similar symbol pairs found."},heuristicLabel:"similarity candidates",render:e=>{if(e.mode==="target"){I.list(e.rows,t=>{let n=t.similarityBasis??"callees",r=n==="source-tokens"?"Shared source tokens":"Shared callees",i=n==="source-tokens"?"Only tokens in":"Only in",o=[`
833
823
  ${Math.round(t.similarity*100)}% similar:`,` A: ${t.shortNameA} (${t.fileA})`,` B: ${t.shortNameB} (${t.fileB})`,` ${r}: ${t.sharedCallees.join(", ")}`];return t.uniqueToA.length&&o.push(` ${i} A: ${t.uniqueToA.join(", ")}`),t.uniqueToB.length&&o.push(` ${i} B: ${t.uniqueToB.join(", ")}`),o.join(`
834
- `)});return}L.list(e.rows,t=>`
824
+ `)});return}I.list(e.rows,t=>`
835
825
  ${Math.round(t.similarity*100)}% similar:
836
826
  A: ${t.shortNameA} (${t.fileA})
837
827
  B: ${t.shortNameB} (${t.fileB})
838
828
  Shared ${t.similarityBasis==="source-tokens"?"source tokens":"callees"}: ${t.sharedCallees.join(", ")}`),console.log(`
839
- ${e.rows.length} similar pair(s) found.`)}}),CN=Kt({query:({db:e,args:t,opts:n})=>qo(e,{minSimilarity:C(n,"minSimilarity",.5),limit:C(n,"limit",20),scope:E(n,"scope"),minDeps:bt(n,"minDeps"),filePattern:We(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{L.list(e,t=>{let n=[`
829
+ ${e.rows.length} similar pair(s) found.`)}}),aE=vn({commandName:"similar-files",query:({db:e,args:t,opts:n})=>Ys(e,{minSimilarity:D(n,"minSimilarity",.5),limit:O(n,"limit",20),scope:P(n,"scope"),minDeps:we(n,"minDeps"),filePattern:he(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{I.list(e,t=>{let n=[`
840
830
  ${Math.round(t.similarity*100)}% similar:`,` ${t.fileA}`,` ${t.fileB}`,` Shared deps (${t.sharedDeps.length}): ${t.sharedDeps.join(", ")}`];return t.uniqueToA.length&&n.push(` Only in first: ${t.uniqueToA.join(", ")}`),t.uniqueToB.length&&n.push(` Only in second: ${t.uniqueToB.join(", ")}`),n.join(`
841
831
  `)}),console.log(`
842
- ${e.length} similar pair(s) found.`)}}),RN=Kt({query:({db:e,opts:t})=>Vo(e,{minSimilarity:C(t,"minSimilarity",.5),limit:C(t,"limit",15),scope:E(t,"scope"),minChainLength:C(t,"minLength",3),maxChainLength:C(t,"maxLength",8)}),emptyMessage:e=>e.length===0?"No similar chains found.":void 0,heuristicLabel:"similar chain candidates",render:e=>{for(let t=0;t<e.length;t++){let n=e[t];console.log(`
832
+ ${e.length} similar pair(s) found.`)}}),cE=Ke("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>sn(e,{minSimilarity:D(n,"minSimilarity",.62),minTokens:D(n,"minTokens",8),limit:O(n,"limit",20),scope:P(n,"scope"),scanLimit:r.scanLimit,filePattern:he(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React component structures found.":void 0,heuristicLabel:"React component duplicate candidates",render:e=>{I.list(e,t=>{let n=[`
833
+ ${Math.round(t.similarity*100)}% similar React structure:`,` ${t.componentA} (${t.fileA})`,` ${t.componentB} (${t.fileB})`];return t.sharedComponents.length&&n.push(` Shared components: ${t.sharedComponents.join(", ")}`),t.sharedNativeTags.length&&n.push(` Shared native tags: ${t.sharedNativeTags.join(", ")}`),t.sharedProps.length&&n.push(` Shared props: ${t.sharedProps.join(", ")}`),t.sharedEvents.length&&n.push(` Shared events: ${t.sharedEvents.join(", ")}`),t.sharedBindings.length&&n.push(` Shared bindings: ${t.sharedBindings.slice(0,20).join(", ")}`),n.join(`
834
+ `)}),console.log(`
835
+ ${e.length} duplicated React component pair(s) found.`)}}),lE=Ke("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:r})=>cn(e,{minSimilarity:D(n,"minSimilarity",.45),minSharedBehaviors:D(n,"minSharedBehaviors",6),limit:O(n,"limit",20),scope:P(n,"scope"),scanLimit:r.scanLimit,filePattern:he(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React hook behavior candidates found.":void 0,heuristicLabel:"React hook extraction candidates",render:e=>{I.list(e,t=>{let n=[`
836
+ ${Math.round(t.similarity*100)}% similar React behavior:`,` ${t.componentA} (${t.fileA})`,` ${t.componentB} (${t.fileB})`,` ${t.reason}`];return t.sharedHooks.length&&n.push(` Shared hooks: ${t.sharedHooks.join(", ")}`),t.sharedReactHooks.length&&n.push(` Shared React hooks: ${t.sharedReactHooks.join(", ")}`),t.sharedEffects.length&&n.push(` Shared effects: ${t.sharedEffects.join(", ")}`),t.sharedState.length&&n.push(` Shared state: ${t.sharedState.join(", ")}`),t.sharedRequests.length&&n.push(` Shared requests: ${t.sharedRequests.join(", ")}`),t.sharedHandlers.length&&n.push(` Shared handlers: ${t.sharedHandlers.slice(0,12).join(", ")}`),t.sharedHandlerVerbs.length&&n.push(` Shared action verbs: ${t.sharedHandlerVerbs.slice(0,12).join(", ")}`),n.join(`
837
+ `)}),console.log(`
838
+ ${e.length} React hook candidate pair(s) found.`)}}),uE=Ke("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:r})=>Er(e,{minComponentLines:D(n,"minComponentLines",300),minFileLines:D(n,"minFileLines",800),minJsxTokens:D(n,"minJsxTokens",80),minBehaviorTokens:D(n,"minBehaviorTokens",40),limit:O(n,"limit",20),scope:P(n,"scope"),scanLimit:r.scanLimit,filePattern:he(t,0)}),emptyMessage:e=>e.length===0?"No large React component pressure found.":void 0,heuristicLabel:"large React component pressure candidates",render:e=>{I.list(e,t=>[`
839
+ ${t.componentLines} component line(s): ${t.component} (${t.file})`,` Dominant pressure: ${t.dominantPressure}`,` File lines: ${t.fileLines}; JSX tokens: ${t.jsxTokens}; behavior tokens: ${t.behaviorTokens}`,` Reasons: ${t.reasons.join("; ")}`].join(`
840
+ `)),console.log(`
841
+ ${e.length} large React component(s) found.`)}}),dE=Ke("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>ln(e,{minSimilarity:D(n,"minSimilarity",.62),minTokens:D(n,"minTokens",8),limit:O(n,"limit",20),scope:P(n,"scope"),scanLimit:r.scanLimit,filePattern:he(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue component structures found.":void 0,heuristicLabel:"Vue component duplicate candidates",render:e=>{I.list(e,t=>{let n=[`
842
+ ${Math.round(t.similarity*100)}% similar Vue structure:`,` ${t.fileA}`,` ${t.fileB}`];return t.sharedComponents.length&&n.push(` Shared components: ${t.sharedComponents.join(", ")}`),t.sharedProps.length&&n.push(` Shared props: ${t.sharedProps.join(", ")}`),t.sharedEvents.length&&n.push(` Shared events: ${t.sharedEvents.join(", ")}`),t.sharedDirectives.length&&n.push(` Shared directives: ${t.sharedDirectives.join(", ")}`),t.sharedSlots.length&&n.push(` Shared slots: ${t.sharedSlots.join(", ")}`),t.sharedIdentifiers.length&&n.push(` Shared identifiers: ${t.sharedIdentifiers.slice(0,20).join(", ")}`),n.join(`
843
+ `)}),console.log(`
844
+ ${e.length} duplicated Vue component pair(s) found.`)}}),mE=Ke("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:r})=>un(e,{minSimilarity:D(n,"minSimilarity",.45),minSharedBehaviors:D(n,"minSharedBehaviors",6),limit:O(n,"limit",20),scope:P(n,"scope"),scanLimit:r.scanLimit,filePattern:he(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue behavior candidates found.":void 0,heuristicLabel:"Vue composable extraction candidates",render:e=>{I.list(e,t=>{let n=[`
845
+ ${Math.round(t.similarity*100)}% similar Vue behavior:`,` ${t.fileA}`,` ${t.fileB}`,` ${t.reason}`];return t.sharedComposables.length&&n.push(` Shared composables: ${t.sharedComposables.join(", ")}`),t.sharedStores.length&&n.push(` Shared stores: ${t.sharedStores.join(", ")}`),t.sharedRequests.length&&n.push(` Shared requests: ${t.sharedRequests.join(", ")}`),t.sharedLifecycle.length&&n.push(` Shared lifecycle: ${t.sharedLifecycle.join(", ")}`),t.sharedFunctions.length&&n.push(` Shared functions: ${t.sharedFunctions.slice(0,12).join(", ")}`),t.sharedFunctionVerbs.length&&n.push(` Shared action verbs: ${t.sharedFunctionVerbs.slice(0,12).join(", ")}`),t.sharedBindings.length&&n.push(` Shared bindings: ${t.sharedBindings.slice(0,20).join(", ")}`),t.sharedTemplateEvents.length&&n.push(` Shared template events: ${t.sharedTemplateEvents.slice(0,20).join(", ")}`),n.join(`
846
+ `)}),console.log(`
847
+ ${e.length} Vue composable candidate pair(s) found.`)}}),pE=Ke("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:r})=>Fr(e,{minTotalLines:D(n,"minTotalLines",800),minTemplateLines:D(n,"minTemplateLines",300),minScriptLines:D(n,"minScriptLines",300),minStyleLines:D(n,"minStyleLines",500),limit:O(n,"limit",20),scope:P(n,"scope"),scanLimit:r.scanLimit,filePattern:he(t,0)}),emptyMessage:e=>e.length===0?"No large Vue view pressure found.":void 0,heuristicLabel:"large Vue view pressure candidates",render:e=>{I.list(e,t=>{let n=[`
848
+ ${t.totalLines} total line(s): ${t.file}`,` Dominant pressure: ${t.dominantPressure}`,` Blocks: template ${t.templateLines}, script ${t.scriptLines}, style ${t.styleLines}, external script ${t.externalScriptLines}, custom ${t.customBlockLines}`];return t.externalScriptPaths.length&&n.push(` External scripts: ${t.externalScriptPaths.join(", ")}`),n.push(` Reasons: ${t.reasons.join("; ")}`),n.join(`
849
+ `)}),console.log(`
850
+ ${e.length} large Vue view pressure file(s) found.`)}}),fE=vn({commandName:"similar-chains",query:({db:e,opts:t})=>ra(e,{minSimilarity:D(t,"minSimilarity",.5),limit:O(t,"limit",15),scope:P(t,"scope"),minChainLength:D(t,"minLength",3),maxChainLength:D(t,"maxLength",8)}),emptyMessage:e=>e.length===0?"No similar chains found.":void 0,heuristicLabel:"similar chain candidates",render:e=>{for(let t=0;t<e.length;t++){let n=e[t];console.log(`
843
851
  \u2500\u2500 Chain pair ${t+1} (${Math.round(n.similarity*100)}% similar, ${n.divergencePoints.length} divergence point(s)) \u2500\u2500`),console.log(` Chain A: ${n.chainA.join(" \u2192 ")}`),console.log(` Chain B: ${n.chainB.join(" \u2192 ")}`),n.commonPrefix.length&&console.log(` Common prefix: ${n.commonPrefix.join(" \u2192 ")}`),n.commonSuffix.length&&console.log(` Common suffix: ${n.commonSuffix.join(" \u2192 ")}`),console.log(" Divergence points (consolidation targets):");for(let r of n.divergencePoints)console.log(` [${r.index}] ${r.nodeA} \u2194 ${r.nodeB}`)}console.log(`
844
- ${e.length} similar chain pair(s) found.`)}}),IN=dr("drift",{query:({db:e,args:t,opts:n,budget:r})=>Bt(e,{scope:We(t,0),minDeviation:C(n,"minDeviation",5),semantic:r.semantic}),emptyMessage:e=>e.results.length===0?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{console.log(""),L.groupedByFile(e.results,t=>{let r=` [${t.kind==="unused-import"?"UNUSED":t.kind==="layer-violation"?"LAYER":"UNIQUE"}] ${t.description}`;return t.detail?`${r}
852
+ ${e.length} similar chain pair(s) found.`)}}),gE=Ke("drift",{query:({db:e,args:t,opts:n,budget:r})=>gn(e,{scope:he(t,0),minDeviation:D(n,"minDeviation",5),semantic:r.semantic}),emptyMessage:e=>e.results.length===0?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{console.log(""),I.groupedByFile(e.results,t=>{let r=` [${t.kind==="unused-import"?"UNUSED":t.kind==="layer-violation"?"LAYER":"UNIQUE"}] ${t.description}`;return t.detail?`${r}
845
853
  ${t.detail}`:r},t=>t.file),console.log(`
846
- ${e.unusedImports} unused import(s), ${e.layerViolations} layer violation(s), ${e.patternDeviations} pattern deviation(s)`)}}),vN=dr("convergence",{query:({db:e,args:t,budget:n})=>ms(e,O(t,0),O(t,1),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"One or both symbols not found.",render:e=>{if(e){console.log(`
854
+ ${e.unusedImports} unused import(s), ${e.layerViolations} layer violation(s), ${e.patternDeviations} pattern deviation(s)`)}}),hE=Ke("convergence",{query:({db:e,args:t,budget:n})=>Ra(e,H(t,0),H(t,1),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"One or both symbols not found.",render:e=>{if(e){console.log(`
847
855
  ${Math.round(e.similarity*100)}% callee overlap
848
856
  `),console.log(` A: ${e.symbolA.shortName} (${e.symbolA.file}, ${e.symbolA.loc} LOC)`),console.log(` B: ${e.symbolB.shortName} (${e.symbolB.file}, ${e.symbolB.loc} LOC)
849
857
  `),console.log(` Shared callees (${e.sharedCallees.length}):`);for(let t of e.sharedCallees)console.log(` ${t}`);if(e.uniqueToA.length>0){console.log(`
850
858
  Unique to A (${e.uniqueToA.length}):`);for(let t of e.uniqueToA)console.log(` ${t}`)}if(e.uniqueToB.length>0){console.log(`
851
859
  Unique to B (${e.uniqueToB.length}):`);for(let t of e.uniqueToB)console.log(` ${t}`)}console.log(`
852
- Strategy: ${e.consolidationStrategy}`)}}}),DN=rt("similar-signatures",{query:({db:e,opts:t,budget:n})=>hs(e,{scope:E(t,"scope"),minLoc:C(t,"minLoc",3),limit:C(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=`
853
- Signature: ${e.signature} (${e.functions.length} functions)`,n=e.functions.map(r=>` ${ae(r.file,r.startLine,r.endLine)} ${r.shortName} (${r.loc} LOC)`).join(`
860
+ Strategy: ${e.consolidationStrategy}`)}}}),bE=It("similar-signatures",{query:({db:e,opts:t,budget:n})=>wa(e,{scope:P(t,"scope"),minLoc:D(t,"minLoc",3),limit:O(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=`
861
+ Signature: ${e.signature} (${e.functions.length} functions)`,n=e.functions.map(r=>` ${ge(r.file,r.startLine,r.endLine)} ${r.shortName} (${r.loc} LOC)`).join(`
854
862
  `);return`${t}
855
863
  ${n}`},emptyMessage:()=>"No same-shape function groups found.",after:e=>console.log(`
856
- ${e.length} group(s) found.`)});function Je(e){return{docs:I("Cleanup"),...e}}function ot({heuristicLabel:e,...t}){return Je({...t,heuristic:{label:e}})}var NN=Z("cleanup-plan",({db:e,opts:t,budget:n})=>{let r=Uo(e,{scope:E(t,"scope"),minLoc:C(t,"minLoc",1),maxDepth:C(t,"maxDepth",5),scanLimit:n.scanLimit});if(r.batches.length===0)return L.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.");console.log(`Cleanup plan: ${r.totalSymbols} symbol(s), ${r.totalLoc} LOC across ${r.batches.length} batch(es).`),console.log(`Apply one batch at a time; run your typecheck between batches.
857
- `);for(let i of r.batches){let o=i.depth===0?`\u2500\u2500 Batch 0: deletable now (graph-fact, ${i.loc} LOC) \u2500\u2500`:`\u2500\u2500 Batch ${i.depth}: dead once batch ${i.depth-1} lands (cascade, ${i.loc} LOC) \u2500\u2500`;console.log(o);for(let s of i.entries)console.log(` ${s.file}:${s.startLine+1}-${s.endLine+1} ${s.shortName} (${s.loc} LOC)`);i.filesEmptied.length>0&&console.log(` -> empties: ${i.filesEmptied.join(", ")}`),console.log("")}if(r.blocked.length>0){console.log("Cascade blocked (references outside the removal set):");for(let i of r.blocked)console.log(` ${i.shortName} (${i.file}) blocked by ${i.blockingFiles.join(", ")}`)}if(j(t,"verify")){console.log(`
858
- Verifying batches against the project checker (throwaway worktree at HEAD)...`);let i=nd(Me(),r);if(i.checkers.length===0){console.log(" No checker detected (need tsconfig.json or a Cargo.toml) \u2014 skipped.");return}for(let o of i.checkers)console.log(` Checker: ${o}`);i.uncoveredFiles.length>0&&console.log(` WARNING: no checker covers these plan files (entries there are NOT verified): ${i.uncoveredFiles.join(", ")}`),i.baselineErrors>0&&console.log(` Baseline has ${i.baselineErrors} pre-existing error(s) \u2014 verifying differentially (no NEW errors).`),i.dirtyOverlap.length>0&&console.log(` WARNING: plan files dirty in working tree (verification runs at HEAD): ${i.dirtyOverlap.join(", ")}`);for(let o of i.batches)if(o.status==="verified")console.log(` Batch ${o.depth}: COMPILER-VERIFIED`);else{console.log(` Batch ${o.depth}: FAILED \u2014 the errors below name references the static evidence missed:`);for(let s of o.errors??[])console.log(` ${s}`)}}}),_N=Z("recent-duplicates",({db:e,opts:t,budget:n})=>{let r=os(e,{windowCommits:C(t,"window",100),minSimilarity:bt(t,"minSimilarity")??.7,limit:C(t,"limit",30),scope:E(t,"scope"),scanLimit:n.scanLimit,semantic:n.semantic});if(!r.available)return L.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return L.empty(`No recent re-implementations found (window: last ${r.windowCommits} commits).`);console.log(`Recent re-implementations (window: last ${r.windowCommits} commits):
859
- `);for(let i of r.findings)i.kind==="echo"?(console.log(` ${Math.round(i.similarity*100)}% ECHO ${i.echoFile} ${i.echoSymbol} (added ${i.echoAgeCommits} commits ago)`),console.log(` duplicates established ${i.establishedFile} ${i.establishedSymbol}`)):(console.log(` ${Math.round(i.similarity*100)}% TWIN ${i.echoFile} ${i.echoSymbol}`),console.log(` and ${i.establishedFile} ${i.establishedSymbol} (both new \u2014 consolidate before they diverge)`));console.log(`
860
- ${r.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),LN=q(({db:e,args:t,opts:n})=>{let r=Zo(e,{doc:t[0]===void 0?void 0:O(t,0),limit:C(n,"limit",20),minCoupling:C(n,"minCoupling",3)});if(!r.available)return L.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return L.empty(`No drifting docs found across ${r.docsScanned} doc(s) \u2014 referenced and co-changed code has not moved since each doc last changed.`);console.log(`Docs whose referenced or co-changed code moved on without them (${r.docsScanned} docs scanned, ${r.commitsAnalyzed} commits analyzed):
864
+ ${e.length} group(s) found.`)});function Qe(e){return{docs:v("Cleanup"),...e}}function Re({heuristicLabel:e,...t}){return Qe({...t,heuristic:{label:e}})}var yE=Z("cleanup-plan",({db:e,args:t,opts:n,budget:r})=>{let i=zi(e,{scope:P(n,"scope"),minLoc:D(n,"minLoc",1),maxDepth:D(n,"maxDepth",5),scanLimit:r.scanLimit}),o=fe(),s=x(n,"patch"),a=x(n,"json"),c=x(n,"verify")||s;if(s&&!x(n,"verify")){console.error("error: cleanup-plan --patch requires --verify."),process.exitCode=1;return}if(i.batches.length===0){if(a){T("cleanup-plan",t,n,i);return}return I.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.")}let l=fc(i),u=c?dc(o,i):void 0;if(a){T("cleanup-plan",t,n,{result:i,verification:u});return}if(s){let d=gc(u,l);if(d.length>0){for(let f of d)console.error(`error: ${f}`);process.exitCode=1;return}let m=Up(o,l);if(m.trim()===""){console.error("error: verified cleanup plan produced an empty patch."),process.exitCode=1;return}console.error(`cleanup-plan --patch: ${l.length} compiler-verified batch(es), ${i.totalLoc} LOC.`),console.log(m);return}console.log(`Cleanup plan: ${i.totalSymbols} symbol(s), ${i.totalLoc} LOC across ${i.batches.length} batch(es).`),console.log(`Apply one batch at a time; run your typecheck between batches.
865
+ `);for(let d of i.batches){let m=d.depth===0?`\u2500\u2500 Batch 0: deletable now (graph-fact, ${d.loc} LOC) \u2500\u2500`:`\u2500\u2500 Batch ${d.depth}: dead once batch ${d.depth-1} lands (cascade, ${d.loc} LOC) \u2500\u2500`;console.log(m);for(let f of d.entries)console.log(` ${f.file}:${f.startLine+1}-${f.endLine+1} ${f.shortName} (${f.loc} LOC)`);d.filesEmptied.length>0&&console.log(` -> empties: ${d.filesEmptied.join(", ")}`),console.log("")}if(i.blocked.length>0){console.log("Cascade blocked (references outside the removal set):");for(let d of i.blocked)console.log(` ${d.shortName} (${d.file}) blocked by ${d.blockingFiles.join(", ")}`)}if(u){if(console.log(`
866
+ Verifying batches against the project checker (throwaway worktree at HEAD)...`),u.checkers.length===0){console.log(" No checker detected (need tsconfig.json or a Cargo.toml) \u2014 skipped.");return}for(let d of u.checkers)console.log(` Checker: ${d}`);u.uncoveredFiles.length>0&&console.log(` WARNING: no checker covers these plan files (entries there are NOT verified): ${u.uncoveredFiles.join(", ")}`),u.baselineErrors>0&&console.log(` Baseline has ${u.baselineErrors} pre-existing error(s) \u2014 verifying differentially (no NEW errors).`),u.dirtyOverlap.length>0&&console.log(` WARNING: plan files dirty in working tree (verification runs at HEAD): ${u.dirtyOverlap.join(", ")}`);for(let d of u.batches)if(d.status==="verified")console.log(` Batch ${d.depth}: COMPILER-VERIFIED`);else{console.log(` Batch ${d.depth}: FAILED \u2014 the errors below name references the static evidence missed:`);for(let m of d.errors??[])console.log(` ${m}`)}}}),SE=Z("cleanup-apply",({db:e,opts:t,budget:n})=>{if(!x(t,"verified")){console.error("error: cleanup-apply requires --verified so deletions are checked before mutating files."),process.exitCode=1;return}let r=x(t,"all"),i=we(t,"batch");if(r===(i!==void 0)){console.error("error: choose exactly one of --all or --batch <n>."),process.exitCode=1;return}let o=zi(e,{scope:P(t,"scope"),minLoc:D(t,"minLoc",1),maxDepth:D(t,"maxDepth",5),scanLimit:n.scanLimit});if(o.batches.length===0){I.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.");return}let s=fc(o,{all:r,batch:i});if(s.length===0){console.error(`error: No cleanup batch ${i} exists.`),process.exitCode=1;return}let a=fe(),c=dc(a,o),l=gc(c,s,{allowDirty:x(t,"forceDirty")});if(l.length>0){for(let m of l)console.error(`error: ${m}`);process.exitCode=1;return}pc(a,s);let u=s.reduce((m,f)=>m+f.entries.length,0),d=s.reduce((m,f)=>m+f.loc,0);console.log(`Applied ${s.length} compiler-verified cleanup batch(es): ${u} symbol(s), ${d} LOC.`)}),xE=Z("recent-duplicates",({db:e,args:t,opts:n,budget:r})=>{let i=ba(e,{windowCommits:D(n,"window",100),minSimilarity:we(n,"minSimilarity"),limit:O(n,"limit",30),scope:P(n,"scope"),scanLimit:r.scanLimit,semantic:r.semantic});if(x(n,"json")){T("recent-duplicates",t,n,i);return}if(!i.available)return I.empty("No git history available (not a repository, or git missing).");if(i.findings.length===0)return I.empty(`No recent re-implementations found (window: last ${i.windowCommits} commits).`);console.log(`Recent re-implementations (window: last ${i.windowCommits} commits):
867
+ `);for(let o of i.findings){let s=o.sharedEvidence.slice(0,16).join(", ");o.kind==="echo"?(console.log(` ${Math.round(o.similarity*100)}% ECHO ${o.domain} ${o.echoFile} ${o.echoSymbol} (added ${o.echoAgeCommits} commits ago)`),console.log(` duplicates established ${o.establishedFile} ${o.establishedSymbol}`)):(console.log(` ${Math.round(o.similarity*100)}% TWIN ${o.domain} ${o.echoFile} ${o.echoSymbol}`),console.log(` and ${o.establishedFile} ${o.establishedSymbol} (both new \u2014 consolidate before they diverge)`)),console.log(` basis: ${o.basis}`),s.length>0&&console.log(` shared: ${s}`)}console.log(`
868
+ ${i.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),CE=G(({db:e,args:t,opts:n})=>{let r=da(e,{doc:t[0]===void 0?void 0:H(t,0),limit:O(n,"limit",20),minCoupling:D(n,"minCoupling",3)});if(x(n,"json")){T("doc-drift",t,n,r);return}if(!r.available)return I.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return I.empty(`No drifting docs found across ${r.docsScanned} doc(s) \u2014 referenced and co-changed code has not moved since each doc last changed.`);console.log(`Docs whose referenced or co-changed code moved on without them (${r.docsScanned} docs scanned, ${r.commitsAnalyzed} commits analyzed):
861
869
  `);for(let i of r.findings){console.log(` staleness ${i.staleness} ${i.doc}`);for(let o of i.brokenReferences.slice(0,4))console.log(` BROKEN REFERENCE: cites ${o} \u2014 that file no longer exists`);for(let o of i.subjects.slice(0,4)){let s=o.evidence==="both"?`referenced by doc + coupled ${o.coChanges}x`:o.evidence==="reference"?"referenced by doc":`coupled ${o.coChanges}x historically`;console.log(` ${o.changesSinceDocUpdate} change(s) since doc update ${o.file} (${s})`)}}console.log(`
862
- Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),wN=rt("unused-params",{query:({db:e,opts:t,budget:n})=>rr(e,{scope:E(t,"scope"),limit:C(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${ae(e.file,e.startLine,e.endLine)} ${e.shortName}
870
+ Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),vE=It("unused-params",{query:({db:e,opts:t,budget:n})=>qr(e,{scope:P(t,"scope"),limit:O(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${ge(e.file,e.startLine,e.endLine)} ${e.shortName}
863
871
  trailing unused: ${e.unusedTrailing.join(", ")} (${e.unusedTrailing.length} of ${e.paramCount} params \u2014 safe to drop)`,emptyMessage:()=>"No trailing unused parameters found.",heuristicLabel:"unused trailing parameter candidates",after:e=>console.log(`
864
- ${e.length} function(s) with trailing unused parameters.`)}),ad=[Je({id:"unused-params",command:"unused-params",description:"Speculative-generality candidates: trailing parameters no body ever uses (TS/JS)",options:[g("-s, --scope <path>","Limit to files matching path"),g("-n, --limit <n>","Maximum findings",v,30),g("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:I("Cleanup",["scip-query unused-params -s src/services"]),handler:wN}),Je({id:"cleanup-plan",command:"cleanup-plan",description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:[g("-s, --scope <path>","Limit to files matching path"),g("--min-loc <n>","Only include symbols >= N lines",v,1),g("--max-depth <n>","Maximum cascade depth",v,5),g("--verify","Apply batches in a throwaway worktree and run the project checker (tsc / cargo check)"),g("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:I("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:NN}),Je({id:"recent-duplicates",command:"recent-duplicates",description:"Directional duplicate candidates: recent code that re-implements established code",options:[g("--window <n>",'How many commits back counts as "recent"',v,100),g("--min-similarity <n>","Minimum similarity (0-1)",Ut,.7),g("-n, --limit <n>","Maximum findings",v,30),g("-s, --scope <path>","Limit to files matching path"),g("--full","Run unbounded semantic analysis on large indexes")],budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:I("Cleanup",["scip-query recent-duplicates --window 50"]),handler:_N}),Je({id:"doc-drift",command:"doc-drift [doc]",description:"Stale-doc candidates: code the doc references or co-changed with kept changing after the doc stopped",options:[g("-n, --limit <n>","Maximum docs to report",v,20),g("--min-coupling <n>","Minimum historical co-changes to track a subject",v,3)],heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:I("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:LN}),Je({id:"dead",command:"dead [scope]",description:"Find dead code and file-internal symbols (no cross-file consumers)",options:[g("--min-loc <n>","Only show symbols >= N lines",v,1),g("--include-tests","Include test files"),g("--skip-barrels","Ignore refs from barrel re-export files"),g("--include-members","Include class members"),g("--only-dead","Show only [dead code] symbols (skip [file-internal only])"),g("--only-internal","Show only [file-internal only] symbols (skip [dead code])"),g("--full","Run unbounded semantic analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:I("Cleanup",["scip-query dead --min-loc 10"]),handler:dN}),Je({id:"unused-imports",command:"unused-imports <file>",description:"Find imports not referenced in the same file",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"list",handler:pN}),Je({id:"isolated",command:"isolated",description:"Find completely orphaned symbols (no references at all)",options:[g("-s, --scope <path>","Limit to files matching path"),g("--min-loc <n>","Minimum lines of code",v,3),g("--full","Run unbounded semantic analysis on large indexes")],budget:"candidate-scan",renderShape:"grouped-by-file",handler:fN}),ot({id:"similar",command:"similar [symbol]",description:"Find heuristic function similarity candidates from callee fingerprints",options:[g("--min-similarity <n>","Minimum Jaccard similarity (0-1)",Ut,.4),g("-n, --limit <n>","Number of results",v,20),g("-s, --scope <path>","Limit to files matching path"),g("--min-callees <n>","Minimum callees to consider",v,4),g("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:xN}),ot({id:"similar-files",command:"similar-files [file]",description:"Find heuristic similar-file candidates from dependency profiles",options:[g("--min-similarity <n>","Minimum Jaccard similarity (0-1)",Ut,.5),g("-n, --limit <n>","Number of results",v,20),g("-s, --scope <path>","Limit to files matching path"),g("--min-deps <n>","Minimum dependencies to consider",v)],heuristicLabel:"similar file candidates",renderShape:"custom",handler:CN}),ot({id:"similar-chains",command:"similar-chains",description:"Find heuristic similar-chain candidates from dependency flows",options:[g("--min-similarity <n>","Minimum chain similarity (0-1)",Ut,.5),g("-n, --limit <n>","Number of results",v,15),g("-s, --scope <path>","Limit to files matching path"),g("--min-length <n>","Minimum chain length",v,3),g("--max-length <n>","Maximum chain length",v,8)],heuristicLabel:"similar chain candidates",renderShape:"custom",handler:RN}),ot({id:"extract-candidates",command:"extract-candidates",description:"Find heuristic extraction candidates from isolated callee clusters",options:[g("-s, --scope <path>","Limit to files matching path"),g("--min-loc <n>","Minimum function LOC",v,10),g("--min-callees <n>","Minimum callees to analyze",v,6),g("-n, --limit <n>","Number of results",v,20),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:gN}),ot({id:"drift",command:"drift [module]",description:"Detect heuristic drift candidates: unused imports, layer violations, and pattern deviations",options:[g("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",pi,5),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:IN}),ot({id:"wrapper-candidates",command:"wrapper-candidates",description:"Find heuristic wrapper candidates only called by one consumer",options:[g("-s, --scope <path>","Limit to files matching path"),g("--max-loc <n>","Maximum LOC for candidates",v,15),g("-n, --limit <n>","Number of results",v,30),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:hN}),ot({id:"passthrough-candidates",command:"passthrough-candidates",description:"Find heuristic passthrough candidates that forward to one callee",options:[g("-s, --scope <path>","Limit to files matching path"),g("--max-loc <n>","Maximum LOC for candidates",v,15),g("-n, --limit <n>","Number of results",v,30),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:yN}),ot({id:"stale-abstractions",command:"stale-abstractions",description:"Find heuristic stale abstraction candidates with 0-1 consumers",options:[g("-s, --scope <path>","Limit to files matching path"),g("--min-loc <n>","Minimum LOC",v,3),g("-n, --limit <n>","Number of results",v,30),g("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:bN}),ot({id:"complexity-hotspots",command:"complexity-hotspots",description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:[g("-s, --scope <path>","Limit to files matching path"),g("--min-loc <n>","Minimum LOC",v,10),g("-n, --limit <n>","Number of results",v,20),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:SN}),Je({id:"convergence",command:"convergence <symbol1> <symbol2>",description:"Show what a consolidated version of two similar functions would look like",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"custom",handler:vN}),id({id:"redundant-reexports",command:"redundant-reexports",description:"Find barrel re-exports that nobody imports through",options:[g("-s, --scope <path>","Limit to files matching path"),g("-n, --limit <n>","Number of results",v,30)],docs:I("Cleanup"),query:({db:e,opts:t})=>ps(e,{scope:E(t,"scope"),limit:C(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
872
+ ${e.length} function(s) with trailing unused parameters.`)}),Af=[Qe({id:"unused-params",command:"unused-params",description:"Speculative-generality candidates: trailing parameters no body ever uses (TS/JS)",options:_([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Maximum findings",S,30),p("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:v("Cleanup",["scip-query unused-params -s src/services"]),handler:vE}),Qe({id:"cleanup-plan",command:"cleanup-plan",description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:[p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Only include symbols >= N lines",S,1),p("--max-depth <n>","Maximum cascade depth",S,5),p("--verify","Apply batches in a throwaway worktree and run the project checker (tsc / cargo check)"),p("--patch","With --verify, print the compiler-verified deletion patch to stdout"),p("--json","Output as JSON for programmatic consumption"),p("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:v("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:yE}),Qe({id:"cleanup-apply",command:"cleanup-apply",description:"Apply a compiler-verified cleanup-plan batch to the working tree",options:[p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Only include symbols >= N lines",S,1),p("--max-depth <n>","Maximum cascade depth",S,5),p("--verified","Required: verify the selected cleanup batch before applying it"),p("--batch <n>","Apply one batch depth",S),p("--all","Apply every compiler-verified batch in the plan"),p("--force-dirty","Allow applying when plan files already have working-tree edits"),p("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:v("Cleanup",["scip-query cleanup-apply --verified --batch 0"]),handler:SE}),Qe({id:"recent-duplicates",command:"recent-duplicates",description:"Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code",options:_([p("--window <n>",'How many commits back counts as "recent"',S,100),p("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",ze),p("-n, --limit <n>","Maximum findings",S,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:v("Cleanup",["scip-query recent-duplicates --window 50"]),handler:xE}),Qe({id:"doc-drift",command:"doc-drift [doc]",description:"Stale-doc candidates: code the doc references or co-changed with kept changing after the doc stopped",options:_([p("-n, --limit <n>","Maximum docs to report",S,20),p("--min-coupling <n>","Minimum historical co-changes to track a subject",S,3),p("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:v("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:CE}),Qe({id:"dead",command:"dead [scope]",description:"Find dead code and file-internal symbols (no cross-file consumers)",options:_([p("--min-loc <n>","Only show symbols >= N lines",S,1),p("--include-tests","Include test files"),p("--skip-barrels","Ignore refs from barrel re-export files"),p("--include-members","Include class members"),p("--only-dead","Show only [dead code] symbols (skip [file-internal only])"),p("--only-internal","Show only [file-internal only] symbols (skip [dead code])"),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:v("Cleanup",["scip-query dead --min-loc 10"]),handler:Y_}),Qe({id:"unused-imports",command:"unused-imports <file>",description:"Find imports not referenced in the same file",options:_([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:Z_}),Qe({id:"isolated",command:"isolated",description:"Find completely orphaned symbols (no references at all)",options:_([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum lines of code",S,3),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:eE}),Re({id:"similar",command:"similar [symbol]",description:"Find heuristic function similarity candidates from callee fingerprints",options:_([p("--min-similarity <n>","Minimum Jaccard similarity (0-1)",ze,.4),p("-n, --limit <n>","Number of results",S,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-callees <n>","Minimum callees to consider",S,4),p("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:sE}),Re({id:"similar-files",command:"similar-files [file]",description:"Find heuristic similar-file candidates from dependency profiles",options:_([p("--min-similarity <n>","Minimum Jaccard similarity (0-1)",ze,.5),p("-n, --limit <n>","Number of results",S,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-deps <n>","Minimum dependencies to consider",S),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:aE}),Re({id:"react-component-duplicates",command:"react-component-duplicates [file]",description:"Find heuristic duplicated React component structure candidates from JSX tags, props, events, and bindings",options:_([p("--min-similarity <n>","Minimum JSX structure similarity (0-1)",ze,.62),p("--min-tokens <n>","Minimum structural tokens to consider",S,8),p("-n, --limit <n>","Number of results",S,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:cE}),Re({id:"react-hook-candidates",command:"react-hook-candidates [file]",description:"Find heuristic React hook extraction candidates from shared state, effects, requests, and handlers",options:_([p("--min-similarity <n>","Minimum behavior similarity (0-1)",ze,.45),p("--min-shared-behaviors <n>","Minimum shared behavior tokens",S,6),p("-n, --limit <n>","Number of results",S,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:lE}),Re({id:"react-large-component-pressure",command:"react-large-component-pressure [file]",description:"Find heuristic large React component pressure candidates from component lines, JSX structure, and hook behavior",options:_([p("--min-component-lines <n>","Minimum component lines",S,300),p("--min-file-lines <n>","Minimum file lines",S,800),p("--min-jsx-tokens <n>","Minimum JSX structure tokens",S,80),p("--min-behavior-tokens <n>","Minimum behavior tokens",S,40),p("-n, --limit <n>","Number of results",S,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:uE}),Re({id:"vue-component-duplicates",command:"vue-component-duplicates [file]",description:"Find heuristic duplicated Vue component structure candidates from template tags, bindings, slots, and directives",options:_([p("--min-similarity <n>","Minimum template similarity (0-1)",ze,.62),p("--min-tokens <n>","Minimum structural tokens to consider",S,8),p("-n, --limit <n>","Number of results",S,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:dE}),Re({id:"vue-composable-candidates",command:"vue-composable-candidates [file]",description:"Find heuristic Vue composable extraction candidates from shared state, effects, requests, and template bindings",options:_([p("--min-similarity <n>","Minimum behavior similarity (0-1)",ze,.45),p("--min-shared-behaviors <n>","Minimum shared behavior tokens",S,6),p("-n, --limit <n>","Number of results",S,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:mE}),Re({id:"vue-large-view-pressure",command:"vue-large-view-pressure [file]",description:"Find heuristic large Vue view pressure candidates from template, script, style, and external script line counts",options:_([p("--min-total-lines <n>","Minimum total component lines",S,800),p("--min-template-lines <n>","Minimum template lines",S,300),p("--min-script-lines <n>","Minimum script lines",S,300),p("--min-style-lines <n>","Minimum style lines",S,500),p("-n, --limit <n>","Number of results",S,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:pE}),Re({id:"similar-chains",command:"similar-chains",description:"Find heuristic similar-chain candidates from dependency flows",options:_([p("--min-similarity <n>","Minimum chain similarity (0-1)",ze,.5),p("-n, --limit <n>","Number of results",S,15),p("-s, --scope <path>","Limit to files matching path"),p("--min-length <n>","Minimum chain length",S,3),p("--max-length <n>","Maximum chain length",S,8),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:fE}),Re({id:"extract-candidates",command:"extract-candidates",description:"Find heuristic extraction candidates from isolated callee clusters",options:_([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum function LOC",S,10),p("--min-callees <n>","Minimum callees to analyze",S,6),p("-n, --limit <n>","Number of results",S,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:tE}),Re({id:"drift",command:"drift [module]",description:"Detect heuristic drift candidates: unused imports, layer violations, and pattern deviations",options:_([p("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",yo,5),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:gE}),Re({id:"wrapper-candidates",command:"wrapper-candidates",description:"Find heuristic wrapper candidates only called by one consumer",options:_([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC for candidates",S,15),p("-n, --limit <n>","Number of results",S,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:nE}),Re({id:"passthrough-candidates",command:"passthrough-candidates",description:"Find heuristic passthrough candidates that forward to one callee",options:_([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC for candidates",S,15),p("-n, --limit <n>","Number of results",S,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:rE}),Re({id:"stale-abstractions",command:"stale-abstractions",description:"Find heuristic stale abstraction candidates with 0-1 consumers",options:_([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC",S,3),p("-n, --limit <n>","Number of results",S,30),p("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:iE}),Re({id:"complexity-hotspots",command:"complexity-hotspots",description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:_([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC",S,10),p("-n, --limit <n>","Number of results",S,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:oE}),Qe({id:"convergence",command:"convergence <symbol1> <symbol2>",description:"Show what a consolidated version of two similar functions would look like",options:_([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:hE}),Ef({id:"redundant-reexports",command:"redundant-reexports",description:"Find barrel re-exports that nobody imports through",options:[p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",S,30),p("--full","Run unbounded analysis on large indexes")],docs:v("Cleanup"),query:({db:e,opts:t})=>Ia(e,{scope:P(t,"scope"),limit:O(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
865
873
  barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s)`,key:e=>e.barrelFile,emptyMessage:()=>"No redundant re-exports found.",after:e=>console.log(`
866
- ${e.length} redundant re-export(s).`)}),Je({id:"similar-signatures",command:"similar-signatures",description:"Find functions with near-identical type signatures (same shape)",options:[g("-s, --scope <path>","Limit to files matching path"),g("--min-loc <n>","Minimum LOC per function",v,3),g("-n, --limit <n>","Number of groups",v,20),g("--full","Run unbounded semantic analysis on large indexes")],budget:"candidate-scan",renderShape:"list",handler:DN})];var kN=q(({db:e})=>{let t=we(e);console.log(`Documents: ${t.documents}`),console.log(`Symbols: ${t.symbols}`),console.log(`Definitions: ${t.definitions}`),console.log(`References: ${t.references}`),console.log(`Index size: ${Rn(t.indexSizeBytes)}`),t.lastBuilt&&console.log(`Last built: ${t.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),cd=[{id:"stats",command:"stats",description:"Show index statistics",renderShape:"custom",docs:I("Core"),handler:kN}];var EN=Di("bottlenecks",{headers:["score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>Ao(e,{limit:C(t,"limit",20),scope:E(t,"scope"),minFanIn:C(t,"minFanIn",2),minFanOut:C(t,"minFanOut",2),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${String(e.score).padStart(5)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No bottlenecks found."}),PN=q(({db:e,args:t,opts:n})=>{let r=We(t,0);if(r){let i=Lo(e,r);if(i.length===0)return L.empty(`No fan-in for ${r}.`);L.list(i,o=>` ${String(o.count).padStart(4)} files ${o.name}`);return}L.table(["files","symbol"],ko(e,{limit:C(n,"limit",30),scope:E(n,"scope")}).map(i=>` ${String(i.count).padStart(5)} ${i.name}`))}),FN=q(({db:e,args:t,opts:n})=>{let r=We(t,0);if(r){let i=wo(e,r);if(i.length===0)return L.empty(`No fan-out for ${r}.`);L.list(i,o=>` ${String(o.count).padStart(4)} symbols ${o.name}`);return}L.table(["symbols","file"],Eo(e,{limit:C(n,"limit",30),scope:E(n,"scope")}).map(i=>` ${String(i.count).padStart(7)} ${i.name}`))}),AN=q(({db:e,args:t,opts:n})=>{let r=We(t,0),i=We(t,1);if(r&&i){let o=Po(e,r,i);console.log(`${o.file1} \u2194 ${o.file2}: ${o.sharedSymbols} shared symbols`);return}L.table(["shared","file1 \u2192 file2"],Fo(e,{limit:C(n,"limit",20),scope:E(n,"scope")}).map(o=>` ${String(o.sharedSymbols).padStart(6)} ${o.file1} \u2192 ${o.file2}`))}),TN=Kt({query:({db:e,opts:t})=>At(e,{scope:E(t,"scope"),maxDepth:C(t,"maxDepth",10)}),emptyMessage:e=>e.length===0?"No circular dependencies found.":void 0,render:e=>{let t=e.filter(r=>r.kind==="real"),n=e.filter(r=>r.kind==="module-hierarchy");for(let r=0;r<t.length;r++){console.log(`
874
+ ${e.length} redundant re-export(s).`)}),Qe({id:"similar-signatures",command:"similar-signatures",description:"Find functions with near-identical type signatures (same shape)",options:_([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC per function",S,3),p("-n, --limit <n>","Number of groups",S,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:bE})];var RE=G(({db:e,args:t,opts:n})=>{let r=Te(e);if(x(n,"json")){T("stats",t,n,r);return}console.log(`Documents: ${r.documents}`),console.log(`Symbols: ${r.symbols}`),console.log(`Definitions: ${r.definitions}`),console.log(`References: ${r.references}`),console.log(`Index size: ${er(r.indexSizeBytes)}`),r.lastBuilt&&console.log(`Last built: ${r.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),$f=[{id:"stats",command:"stats",description:"Show index statistics",options:[Oa()],renderShape:"custom",docs:v("Core"),handler:RE}];var LE=No("bottlenecks",{headers:["score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>Ws(e,{limit:O(t,"limit",20),scope:P(t,"scope"),minFanIn:D(t,"minFanIn",2),minFanOut:D(t,"minFanOut",2),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${String(e.score).padStart(5)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No bottlenecks found."}),IE=G(({db:e,args:t,opts:n})=>{let r=he(t,0),i=O(n,"limit",30);if(r){let s=Os(e,r);if(x(n,"json")){T("fan-in",t,n,{mode:"symbol",symbol:r,rows:s});return}if(s.length===0)return I.empty(`No fan-in for ${r}.`);I.list(s,a=>` ${String(a.count).padStart(4)} files ${a.name}`);return}let o=Bs(e,{limit:i,scope:P(n,"scope")});if(x(n,"json")){T("fan-in",t,n,{mode:"top",rows:o});return}I.table(["files","symbol"],o.map(s=>` ${String(s.count).padStart(5)} ${s.name}`))}),DE=G(({db:e,args:t,opts:n})=>{let r=he(t,0),i=O(n,"limit",30);if(r){let s=js(e,r);if(x(n,"json")){T("fan-out",t,n,{mode:"file",file:r,rows:s});return}if(s.length===0)return I.empty(`No fan-out for ${r}.`);I.list(s,a=>` ${String(a.count).padStart(4)} symbols ${a.name}`);return}let o=Vs(e,{limit:i,scope:P(n,"scope")});if(x(n,"json")){T("fan-out",t,n,{mode:"top",rows:o});return}I.table(["symbols","file"],o.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),kE=G(({db:e,args:t,opts:n})=>{let r=he(t,0),i=he(t,1),o=O(n,"limit",20);if(r&&i){let a=Hs(e,r,i);if(x(n,"json")){T("coupling",t,n,{mode:"pair",result:a});return}console.log(`${a.file1} \u2194 ${a.file2}: ${a.sharedSymbols} shared symbols`);return}let s=qs(e,{limit:o,scope:P(n,"scope")});if(x(n,"json")){T("coupling",t,n,{mode:"top",rows:s});return}I.table(["shared","file1 \u2192 file2"],s.map(a=>` ${String(a.sharedSymbols).padStart(6)} ${a.file1} \u2192 ${a.file2}`))}),wE=vn({commandName:"cycles",query:({db:e,opts:t})=>rn(e,{scope:P(t,"scope"),maxDepth:D(t,"maxDepth",10)}),emptyMessage:e=>e.length===0?"No circular dependencies found.":void 0,render:e=>{let t=e.filter(r=>r.kind==="real"),n=e.filter(r=>r.kind==="module-hierarchy");for(let r=0;r<t.length;r++){console.log(`
867
875
  Cycle ${r+1} (${t[r].path.length-1} files):`);for(let i=0;i<t[r].path.length;i++){let o=i<t[r].path.length-1?" \u2192":" (cycle)";console.log(` ${t[r].path[i]}${o}`)}}t.length===0?console.log("No real circular dependencies found."):console.log(`
868
- ${t.length} real cycle(s) found.`),n.length>0&&console.log(`(${n.length} module-hierarchy cycle(s) hidden \u2014 barrel files participating in normal parent/child re-export patterns. Pass --include-module-hierarchy to see them.)`)}}),MN=Kt({query:({db:e,opts:t})=>jo(e,{limit:C(t,"limit",10),scope:E(t,"scope"),minDepth:C(t,"minDepth",3)}),emptyMessage:e=>e.length===0?"No deep chains found.":void 0,render:e=>{for(let t=0;t<e.length;t++){console.log(`
869
- Chain ${t+1} (depth ${e[t].depth}):`);for(let n of e[t].chain)console.log(` \u2192 ${n}`)}}}),ld=[_i({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",options:[g("-n, --limit <n>","Number of results",v,30),g("-s, --scope <path>","Limit to files matching path")],docs:I("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>Ro(e,{limit:C(t,"limit",30),scope:E(t,"scope")}),format:e=>` ${String(e.refCount).padStart(4)} ${String(e.fileCount).padStart(5)} ${e.shortName}`}),{id:"fan-in",command:"fan-in [symbol]",description:"How many files reference a symbol (or top fan-in across codebase)",options:[g("-n, --limit <n>","Number of results for top mode",v,30),g("-s, --scope <path>","Limit to files matching path")],renderShape:"custom",docs:I("Graph"),handler:PN},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",options:[g("-n, --limit <n>","Number of results for top mode",v,30),g("-s, --scope <path>","Limit to files matching path")],renderShape:"custom",docs:I("Graph"),handler:FN},{id:"coupling",command:"coupling [file1] [file2]",description:"Coupling between two files, or top coupled pairs in codebase",options:[g("-n, --limit <n>","Number of results for top mode",v,20),g("-s, --scope <path>","Limit to files matching path")],renderShape:"custom",docs:I("Graph"),handler:AN},{id:"cycles",command:"cycles",description:"Detect circular dependency chains between files",options:[g("-s, --scope <path>","Limit to files matching path"),g("--max-depth <n>","Maximum cycle depth",v,10)],renderShape:"custom",docs:I("Graph"),handler:TN},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",options:[g("-n, --limit <n>","Number of results",v,20),g("-s, --scope <path>","Limit to files matching path"),g("--min-fan-in <n>","Minimum fan-in",v,2),g("--min-fan-out <n>","Minimum fan-out",v,2),g("--full","Run unbounded semantic analysis on large indexes")],budget:"candidate-scan",renderShape:"table",docs:I("Graph"),handler:EN},{id:"deep-chains",command:"deep-chains",description:"Find the longest transitive dependency chains",options:[g("-n, --limit <n>","Number of chains to show",v,10),g("-s, --scope <path>","Limit to files matching path"),g("--min-depth <n>","Minimum chain depth",v,3)],renderShape:"custom",docs:I("Graph"),handler:MN},Li({id:"call-graph",command:"call-graph <symbol>",description:"Show incoming callers and outgoing callees for a symbol",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:I("Graph"),query:({db:e,args:t,budget:n})=>Wn(e,String(t[0]),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"Symbol not found.",before:e=>{e&&console.log(`Symbol: ${e.shortName}
870
- `)},sections:e=>e?[{title:`CALLERS (${e.callers.length})`,rows:e.callers.map(t=>` ${t.file} ${t.shortName}`)},{title:`CALLEES (${e.callees.length})`,rows:e.callees.map(t=>` ${t.file} ${t.shortName}`)}]:[]})];var ON=Z("complexity",({db:e,args:t,budget:n})=>{let r=ir(e,O(t,0),{semantic:n.semantic});if(!r)return L.empty("Symbol not found.");console.log(`${ae(r.relativePath,r.startLine,r.endLine)} ${r.shortName}
871
- `),console.log(` LOC: ${r.loc}`),console.log(` Branches: ${r.branches}`),console.log(` Cyclomatic estimate: ${r.cyclomaticEstimate}`),console.log(` Callees: ${r.calleeCount}`),console.log(` Fan-in: ${r.fanIn}`),console.log(` Fan-out: ${r.fanOut}`)}),$N=q(({db:e,opts:t})=>{let n=gs(e,{samples:C(t,"samples",50),scope:E(t,"scope")});if(!n.available)return L.empty("No semantic provider available to audit against (TypeScript projects only).");console.log(`Sampled ${n.sampleSize} symbols; oracle answered ${Math.round(n.oracleCoverage*100)}%.
872
- `),console.log("Agreement with compiler semantics (file-level):");for(let r of n.scores){let i=r.precision===null?`unverified ${r.unverified} (oracle partial \u2014 no precision claim)`:`precision ${r.precision}`;console.log(` ${r.question.padEnd(11)} ${i} recall ${r.recall} (${r.comparedSymbols} symbols)`)}if(n.topDisagreements.length>0){console.log(`
873
- Top disagreements (debugging targets):`);for(let r of n.topDisagreements)console.log(` ${r.symbol} [${r.question}]`),r.cheapOnly.length>0&&console.log(` cheap-only: ${r.cheapOnly.join(", ")}`),r.oracleOnly.length>0&&console.log(` oracle-only: ${r.oracleOnly.join(", ")}`)}}),ud=[{id:"self-audit",command:"self-audit",description:"Score the cheap evidence paths against the TypeScript compiler oracle on sampled symbols",options:[g("--samples <n>","Number of symbols to sample",v,50),g("-s, --scope <path>","Limit sampling to files matching path")],renderShape:"custom",docs:I("Health",["scip-query self-audit --samples 100"]),handler:$N},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"custom",docs:I("Health"),handler:ON}];var jN=q(({db:e,args:t,opts:n})=>{let r=Kn(e,O(t,0),{maxDepth:C(n,"maxDepth",5),scope:E(n,"scope")});if(r.length===0)return L.empty("No affected symbols found.");let i=-1;for(let o of r)o.depth!==i&&(console.log(`
876
+ ${t.length} real cycle(s) found.`),n.length>0&&console.log(`(${n.length} module-hierarchy cycle(s) hidden \u2014 barrel files participating in normal parent/child re-export patterns. Pass --include-module-hierarchy to see them.)`)}}),NE=vn({commandName:"deep-chains",query:({db:e,opts:t})=>Ks(e,{limit:O(t,"limit",10),scope:P(t,"scope"),minDepth:D(t,"minDepth",3)}),emptyMessage:e=>e.length===0?"No deep chains found.":void 0,render:e=>{for(let t=0;t<e.length;t++){console.log(`
877
+ Chain ${t+1} (depth ${e[t].depth}):`);for(let n of e[t].chain)console.log(` \u2192 ${n}`)}}}),Mf=[_o({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",options:[p("-n, --limit <n>","Number of results",S,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")],docs:v("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>Es(e,{limit:O(t,"limit",30),scope:P(t,"scope")}),format:e=>` ${String(e.refCount).padStart(4)} ${String(e.fileCount).padStart(5)} ${e.shortName}`}),{id:"fan-in",command:"fan-in [symbol]",description:"How many files reference a symbol (or top fan-in across codebase)",options:_([p("-n, --limit <n>","Number of results for top mode",S,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:v("Graph"),handler:IE},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",options:_([p("-n, --limit <n>","Number of results for top mode",S,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:v("Graph"),handler:DE},{id:"coupling",command:"coupling [file1] [file2]",description:"Coupling between two files, or top coupled pairs in codebase",options:_([p("-n, --limit <n>","Number of results for top mode",S,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:v("Graph"),handler:kE},{id:"cycles",command:"cycles",description:"Detect circular dependency chains between files",options:_([p("-s, --scope <path>","Limit to files matching path"),p("--max-depth <n>","Maximum cycle depth",S,10)]),renderShape:"custom",docs:v("Graph"),handler:wE},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",options:_([p("-n, --limit <n>","Number of results",S,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-fan-in <n>","Minimum fan-in",S,2),p("--min-fan-out <n>","Minimum fan-out",S,2),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:v("Graph"),handler:LE},{id:"deep-chains",command:"deep-chains",description:"Find the longest transitive dependency chains",options:_([p("-n, --limit <n>","Number of chains to show",S,10),p("-s, --scope <path>","Limit to files matching path"),p("--min-depth <n>","Minimum chain depth",S,3),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:v("Graph"),handler:NE},Eo({id:"call-graph",command:"call-graph <symbol>",description:"Show incoming callers and outgoing callees for a symbol",options:[p("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:v("Graph"),query:({db:e,args:t,budget:n})=>wr(e,String(t[0]),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"Symbol not found.",before:e=>{e&&console.log(`Symbol: ${e.shortName}
878
+ `)},sections:e=>e?[{title:`CALLERS (${e.callers.length})`,rows:e.callers.map(t=>` ${t.file} ${t.shortName}`)},{title:`CALLEES (${e.callees.length})`,rows:e.callees.map(t=>` ${t.file} ${t.shortName}`)}]:[]})];var PE=Z("complexity",({db:e,args:t,opts:n,budget:r})=>{let i=Wr(e,H(t,0),{semantic:r.semantic});if(x(n,"json")){T("complexity",t,n,i);return}if(!i)return I.empty("Symbol not found.");console.log(`${ge(i.relativePath,i.startLine,i.endLine)} ${i.shortName}
879
+ `),console.log(` LOC: ${i.loc}`),console.log(` Branches: ${i.branches}`),console.log(` Cyclomatic estimate: ${i.cyclomaticEstimate}`),console.log(` Callees: ${i.calleeCount}`),console.log(` Fan-in: ${i.fanIn}`),console.log(` Fan-out: ${i.fanOut}`)}),_E=G(({db:e,args:t,opts:n})=>{let r=ka(e,{samples:D(n,"samples",50),scope:P(n,"scope")});if(x(n,"json")){T("self-audit",t,n,r);return}if(!r.available)return I.empty("No semantic provider available to audit against (TypeScript projects only).");console.log(`Sampled ${r.sampleSize} symbols; oracle answered ${Math.round(r.oracleCoverage*100)}%.
880
+ `),console.log("Agreement with compiler semantics (file-level):");for(let i of r.scores){let o=i.precision===null?`unverified ${i.unverified} (oracle partial \u2014 no precision claim)`:`precision ${i.precision}`;console.log(` ${i.question.padEnd(11)} ${o} recall ${i.recall} (${i.comparedSymbols} symbols)`)}if(r.topDisagreements.length>0){console.log(`
881
+ Top disagreements (debugging targets):`);for(let i of r.topDisagreements)console.log(` ${i.symbol} [${i.question}]`),i.cheapOnly.length>0&&console.log(` cheap-only: ${i.cheapOnly.join(", ")}`),i.oracleOnly.length>0&&console.log(` oracle-only: ${i.oracleOnly.join(", ")}`)}}),Of=[{id:"self-audit",command:"self-audit",description:"Score the cheap evidence paths against the TypeScript compiler oracle on sampled symbols",options:_([p("--samples <n>","Number of symbols to sample",S,50),p("-s, --scope <path>","Limit sampling to files matching path")]),renderShape:"custom",docs:v("Health",["scip-query self-audit --samples 100"]),handler:_E},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",options:_([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:v("Health"),handler:PE}];var EE=G(({db:e,args:t,opts:n})=>{let r=Tr(e,H(t,0),{maxDepth:D(n,"maxDepth",5),scope:P(n,"scope")});if(x(n,"json")){T("affected",t,n,r);return}if(r.length===0)return I.empty("No affected symbols found.");let i=-1;for(let o of r)o.depth!==i&&(console.log(`
874
882
  \u2500\u2500 Depth ${o.depth} \u2500\u2500`),i=o.depth),console.log(` ${o.file} ${o.shortName}`);console.log(`
875
- ${r.length} affected symbol(s) across ${new Set(r.map(o=>o.file)).size} files.`)}),BN=q(({db:e,args:t,opts:n})=>{let r=t[0]===void 0?void 0:O(t,0),i=$t(e,r,{minTogether:C(n,"minTogether",4),limit:C(n,"limit",30),includeLinked:n.all===!0});if(!i.available)return L.empty("No git history available (not a repository, or git missing).");if(i.findings.length===0)return L.empty(r?`No co-change partners found for ${r} in ${i.commitsAnalyzed} commits.`:`No hidden coupling found in ${i.commitsAnalyzed} commits.`);console.log(r?`Co-change partners (${i.commitsAnalyzed} commits analyzed):
883
+ ${r.length} affected symbol(s) across ${new Set(r.map(o=>o.file)).size} files.`)}),FE=G(({db:e,args:t,opts:n})=>{let r=t[0]===void 0?void 0:H(t,0),i=pn(e,r,{minTogether:D(n,"minTogether",4),limit:O(n,"limit",30),includeLinked:n.all===!0});if(x(n,"json")){T("co-change",t,n,i);return}if(!i.available)return I.empty("No git history available (not a repository, or git missing).");if(i.findings.length===0)return I.empty(r?`No co-change partners found for ${r} in ${i.commitsAnalyzed} commits.`:`No hidden coupling found in ${i.commitsAnalyzed} commits.`);console.log(r?`Co-change partners (${i.commitsAnalyzed} commits analyzed):
876
884
  `:`Hidden coupling \u2014 pairs that co-change with no dependency edge (${i.commitsAnalyzed} commits analyzed):
877
885
  `);for(let o of i.findings){let s=o.structurallyLinked?" [dep edge]":"";console.log(` ${o.together}x (${Math.round(o.confidence*100)}%) ${o.fileA} <-> ${o.fileB}${s}`)}console.log(`
878
- ${i.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)}),HN=Z("change-surface",({db:e,args:t,budget:n})=>{let r=Qn(e,O(t,0),{semantic:n.semantic});if(!r)return L.empty("File not found in index.");console.log(`File: ${r.file}`),console.log(`External consumers: ${r.totalExternalConsumers}
879
- `),L.list(r.symbols,i=>{let o=i.riskLevel==="high"?" *** HIGH RISK ***":i.riskLevel==="medium"?" * medium risk *":"";return` ${me(i.startLine,i.endLine)} ${i.shortName} [${i.externalConsumers} consumers]${o}`})}),qN=q(({db:e,opts:t})=>{let n=nr(e,{base:E(t,"base"),minContainment:C(t,"minContainment",.7),maxHelpers:C(t,"maxHelpers",10),limit:C(t,"limit",20)});if(!n.available)return L.empty("No git history available (not a repository, or git missing).");if(n.changedFiles.length===0)return L.empty(`No changes vs ${n.base}.`);console.log(`Incomplete migrations vs ${n.base}: ${n.changedFiles.length} changed file(s), ${n.helpersChecked} new helper(s) scored.`),n.note&&console.log(` note: ${n.note}`);for(let r of n.skipped)console.log(` skipped ${r.helperShortName} (${r.helperFile}): ${r.reason}`);if(n.findings.length===0){console.log(`
880
- No incomplete migrations detected.`);return}for(let r of n.findings){console.log(`
881
- ${r.helperShortName} (${r.helperFile})`),console.log(` wired into: ${r.migratedFiles.join(", ")}`);for(let i of r.leftovers)console.log(` un-migrated: ${Math.round(i.containment*100)}% ${i.shortName} (${i.file})`),console.log(` shared: ${i.sharedCallees.join(", ")}`)}console.log(`
882
- ${n.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)}),VN=q(({db:e,opts:t})=>{let n=t.hook===!0;if(n&&wm(Lm()))return;let r=is(e,{base:E(t,"base"),minTogether:C(t,"minTogether",6),maxEchoChecks:C(t,"maxEchoChecks",10)});if(n){if(r.findings.length===0)return;console.error(km(r)),process.exitCode=2;return}if(r.changedFiles.length===0)return L.empty(r.note??`No changes vs ${r.base}.`);console.log(`Diff gate vs ${r.base}: ${r.changedFiles.length} file(s), ${r.changedSymbols} symbol(s) changed.`),console.log(`Checks: ${r.checksRun.join(", ")}
886
+ ${i.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)}),TE=Z("change-surface",({db:e,args:t,opts:n,budget:r})=>{let i=Ar(e,H(t,0),{semantic:r.semantic});if(x(n,"json")){T("change-surface",t,n,i);return}if(!i)return I.empty("File not found in index.");console.log(`File: ${i.file}`),console.log(`External consumers: ${i.totalExternalConsumers}
887
+ `),I.list(i.symbols,o=>{let s=o.riskLevel==="high"?" *** HIGH RISK ***":o.riskLevel==="medium"?" * medium risk *":"";return` ${ve(o.startLine,o.endLine)} ${o.shortName} [${o.externalConsumers} consumers]${s}`})}),AE=G(({db:e,args:t,opts:n})=>{let r=Hr(e,{base:P(n,"base"),minContainment:D(n,"minContainment",.7),maxHelpers:we(n,"maxHelpers"),limit:O(n,"limit",20)});if(x(n,"json")){T("incomplete-migration",t,n,r),r.available&&r.findings.length>0&&(process.exitCode=1);return}if(!r.available)return I.empty("No git history available (not a repository, or git missing).");if(r.changedFiles.length===0)return I.empty(`No changes vs ${r.base}.`);console.log(`Incomplete migrations vs ${r.base}: ${r.changedFiles.length} changed file(s), ${r.helpersChecked} new helper(s) scored.`),r.note&&console.log(` note: ${r.note}`);for(let i of r.skipped)console.log(` skipped ${i.helperShortName} (${i.helperFile}): ${i.reason}`);if(r.findings.length===0){console.log(`
888
+ No incomplete migrations detected.`);return}for(let i of r.findings){console.log(`
889
+ ${i.helperShortName} (${i.helperFile})`),console.log(` wired into: ${i.migratedFiles.join(", ")}`);for(let o of i.leftovers)console.log(` un-migrated: ${Math.round(o.containment*100)}% ${o.shortName} (${o.file})`),console.log(` shared: ${o.sharedCallees.join(", ")}`)}console.log(`
890
+ ${r.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)});function $E(e){let t=Array.isArray(e)?e:[],n=t.filter(r=>!io.includes(r));return n.length>0&&(console.error(`error: unknown --skip check(s): ${n.join(", ")}. Valid checks: ${io.join(", ")}`),process.exit(1)),t}var ME=G(({db:e,opts:t})=>{let n=t.hook===!0;if(n&&Zp(Yp()))return;!n&&$a(e)&&Ec(e)===0&&console.error("Large index with a cold evidence cache: this first run computes semantic callee evidence for every production callable and can take minutes. Re-runs are incremental (evidence.db).");let r=ha(e,{base:P(t,"base"),minTogether:D(t,"minTogether",6),maxEchoChecks:we(t,"maxEchoChecks"),maxHelpers:we(t,"maxHelpers"),skip:$E(t.skip)});if(!n&&x(t,"json")){T("diff-gate",[],t,{exitCode:r.findings.length>0?1:0,...r}),r.findings.length>0&&(process.exitCode=1);return}if(n){if(r.findings.length===0)return;console.error(ef(r)),process.exitCode=2;return}if(r.changedFiles.length===0)return I.empty(r.note??`No changes vs ${r.base}.`);console.log(`Diff gate vs ${r.base}: ${r.changedFiles.length} file(s), ${r.changedSymbols} symbol(s) changed.`),console.log(`Checks: ${r.checksRun.join(", ")}
883
891
  `);for(let i of r.skipped)console.log(` skipped ${i.check}: ${i.reason}`);if(r.findings.length===0){console.log("PASS: this change introduces no gate findings.");return}for(let i of r.findings)console.log(` [${i.check}] ${i.message}`),console.log(` -> ${i.remediation}`);console.log(`
884
- FAIL: ${r.findings.length} finding(s). Fix or knowingly accept before merging.`),process.exitCode=1}),md=[{id:"affected",command:"affected <symbol>",description:"Transitive closure of symbols that could break if this symbol changes",options:[g("--max-depth <n>","Maximum traversal depth",v,5),g("-s, --scope <path>","Limit to files matching path")],renderShape:"custom",docs:I("Impact"),handler:jN},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: exports, consumers, and blast-radius risk",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"list",docs:I("Impact"),handler:HN},{id:"diff-gate",command:"diff-gate",description:"Gate the current diff: echo candidates, incomplete migrations, missing co-change partners, uncited doc updates, unused params, new dead symbols; exit 1 on findings",options:[g("--base <ref>","Git ref to diff against (default: HEAD)"),g("--min-together <n>","Minimum historical co-changes for the partner check",v,6),g("--max-echo-checks <n>","Maximum changed symbols to test for echoes",v,10),g("--hook","Agent Stop-hook mode: silent on pass, exit 2 with findings on stderr to block the stop")],heuristic:{label:"diff gate candidates"},renderShape:"custom",docs:I("Impact",["scip-query diff-gate","scip-query diff-gate --base origin/main"]),handler:VN},{id:"incomplete-migration",command:"incomplete-migration",description:"Partially-completed extraction candidates: new helpers in the diff wired into some sites while similar un-migrated sites remain",options:[g("--base <ref>","Git ref to diff against (default: HEAD)"),g("--min-containment <n>","Minimum share of helper callees a site must contain (0-1)",Ut,.7),g("--max-helpers <n>","Maximum new helpers to score",v,10),g("-n, --limit <n>","Maximum findings to report",v,20)],heuristic:{label:"incomplete migration candidates"},renderShape:"custom",docs:I("Impact",["scip-query incomplete-migration","scip-query incomplete-migration --base origin/main"]),handler:qN},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",options:[g("--min-together <n>","Minimum commits where both files changed",v,4),g("-n, --limit <n>","Maximum pairs to report",v,30),g("--all","Include pairs that already have a dependency edge")],heuristic:{label:"co-change candidates"},renderShape:"custom",docs:I("Impact",["scip-query co-change","scip-query co-change src/runtime/config.ts"]),handler:BN}];function WN(e){let t=[];for(let i of e.definitions){let o=i.signature?` \u2014 ${i.signature}`:"";t.push(` ${ae(i.relativePath,i.startLine,i.endLine)}${o}`),i.source&&t.push(i.source.split(`
885
- `).map((s,a)=>` ${xe(i.startLine+a)} ${s}`).join(`
886
- `))}let n=[],r="";for(let i of e.referencedBy)i.relativePath!==r&&(r&&n.push(""),n.push(` ${i.relativePath}`),r=i.relativePath),n.push(` line ${xe(i.line)} in ${i.enclosingShort}`);return[{title:"DEFINITION",rows:t},{title:"REFERENCED BY",rows:n}]}var UN=q(({db:e,args:t,opts:n})=>{let r=O(t,0),i=j(n,"signatures"),o=No(e,r);if(o.length===0)return L.empty(`No symbols found for "${r}".`);function s(a,c){for(let l of a){let u=" ".repeat(c),m=i&&l.signature?` - ${GN(l.signature)}`:"";console.log(`${u}${me(l.startLine,l.endLine)} ${l.shortName}${m}`),s(l.children,c+1)}}s(o,0)});function GN(e){return e.length>120?`${e.slice(0,117)}...`:e}var JN=rt("imports",{query:({db:e,args:t,budget:n})=>Io(e,O(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} \u2190 ${e.fromFile}`,emptyMessage:()=>"No imports found (indexer may not emit role=2 for this language)."}),zN=Ni("refs",{query:({db:e,args:t,budget:n})=>ho(e,O(t,0),{semantic:n.semantic}),format:e=>` line ${xe(e.line)}`}),KN=q(({db:e,args:t,opts:n})=>{let r=ds(e,O(t,0),{context:C(n,"context",0)});if(!r)return L.empty("Symbol not found or file unreadable.");console.log(`${ae(r.relativePath,r.startLine,r.endLine)} ${r.shortName} [${r.language??"unknown"}]
892
+ FAIL: ${r.findings.length} finding(s). Fix or knowingly accept before merging.`),process.exitCode=1}),jf=[{id:"affected",command:"affected <symbol>",description:"Transitive closure of symbols that could break if this symbol changes",options:_([p("--max-depth <n>","Maximum traversal depth",S,5),p("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:v("Impact"),handler:EE},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: exports, consumers, and blast-radius risk",options:_([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:v("Impact"),handler:TE},{id:"diff-gate",command:"diff-gate",description:"Gate the current diff: echo candidates, incomplete migrations, missing co-change partners, uncited doc updates, unused params, new dead symbols; exit 1 on findings",options:[p("--base <ref>","Git ref to diff against (default: HEAD)"),p("--min-together <n>","Minimum historical co-changes for the partner check",S,6),p("--max-echo-checks <n>","Maximum changed symbols to test for echoes (default: all)",S),p("--max-helpers <n>","Maximum new helpers to score for incomplete-migration (default: all)",S),p("--skip <check>","Skip a check (repeatable): echo, incomplete-migration, co-change-partner, doc-reference, unused-params, new-dead, baseline",bo,[]),p("--hook","Agent Stop-hook mode: silent on pass, exit 2 with findings on stderr to block the stop"),p("--json","Output as JSON for programmatic consumption")],heuristic:{label:"diff gate candidates"},renderShape:"custom",docs:v("Impact",["scip-query diff-gate","scip-query diff-gate --base origin/main"]),handler:ME},{id:"incomplete-migration",command:"incomplete-migration",description:"Partially-completed extraction candidates: new helpers in the diff wired into some sites while similar un-migrated sites remain",options:_([p("--base <ref>","Git ref to diff against (default: HEAD)"),p("--min-containment <n>","Minimum share of helper callees a site must contain (0-1)",ze,.7),p("--max-helpers <n>","Maximum new helpers to score (default: all)",S),p("-n, --limit <n>","Maximum findings to report",S,20),p("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"incomplete migration candidates"},renderShape:"custom",docs:v("Impact",["scip-query incomplete-migration","scip-query incomplete-migration --base origin/main"]),handler:AE},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",options:_([p("--min-together <n>","Minimum commits where both files changed",S,4),p("-n, --limit <n>","Maximum pairs to report",S,30),p("--all","Include pairs that already have a dependency edge"),p("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"co-change candidates"},renderShape:"custom",docs:v("Impact",["scip-query co-change","scip-query co-change src/runtime/config.ts"]),handler:FE}];function OE(e){let t=[];for(let i of e.definitions){let o=i.signature?` \u2014 ${i.signature}`:"";t.push(` ${ge(i.relativePath,i.startLine,i.endLine)}${o}`),i.source&&t.push(i.source.split(`
893
+ `).map((s,a)=>` ${Ee(i.startLine+a)} ${s}`).join(`
894
+ `))}let n=[],r="";for(let i of e.referencedBy)i.relativePath!==r&&(r&&n.push(""),n.push(` ${i.relativePath}`),r=i.relativePath),n.push(` line ${Ee(i.line)} in ${i.enclosingShort}`);return[{title:"DEFINITION",rows:t},{title:"REFERENCED BY",rows:n}]}var jE=G(({db:e,args:t,opts:n})=>{let r=H(t,0),i=x(n,"signatures"),o=$s(e,r);if(x(n,"json")){T("outline",t,n,o);return}if(o.length===0)return I.empty(`No symbols found for "${r}".`);function s(a,c){for(let l of a){let u=" ".repeat(c),d=i&&l.signature?` - ${BE(l.signature)}`:"";console.log(`${u}${ve(l.startLine,l.endLine)} ${l.shortName}${d}`),s(l.children,c+1)}}s(o,0)});function BE(e){return e.length>120?`${e.slice(0,117)}...`:e}var VE=It("imports",{query:({db:e,args:t,budget:n})=>Fs(e,H(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} \u2190 ${e.fromFile}`,emptyMessage:()=>"No imports found (indexer may not emit role=2 for this language)."}),HE=Po("refs",{query:({db:e,args:t,budget:n})=>Ds(e,H(t,0),{semantic:n.semantic}),format:e=>` line ${Ee(e.line)}`}),qE=G(({db:e,args:t,opts:n})=>{let r=La(e,H(t,0),{context:D(n,"context",0)});if(x(n,"json")){T("code",t,n,r);return}if(!r)return I.empty("Symbol not found or file unreadable.");console.log(`${ge(r.relativePath,r.startLine,r.endLine)} ${r.shortName} [${r.language??"unknown"}]
887
895
  `);let i=r.source.split(`
888
- `);for(let o=0;o<i.length;o++)console.log(` ${String(xe(r.startLine+o)).padStart(4)} ${i[o]}`)}),QN=Z("dataflow",({db:e,args:t,budget:n})=>{let r=or(e,O(t,0),{semantic:n.semantic});if(!r)return L.empty("Symbol not found.");if(console.log(`${r.shortName} (${r.relativePath})
889
- `),r.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let i of r.definitionSites)console.log(` ${i.file}:${xe(i.line)}`)}if(r.usageSites.length>0){console.log(`
890
- \u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let i of r.usageSites)console.log(` ${i.file}:${xe(i.line)} in ${i.enclosingShort}`)}if(r.producers.length>0){console.log(`
891
- \u2550\u2550\u2550 PRODUCERS (feeds into this) \u2550\u2550\u2550`);for(let i of r.producers)console.log(` ${i.file} ${i.shortName}`)}if(r.consumers.length>0){console.log(`
892
- \u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let i of r.consumers)console.log(` ${i.file} ${i.shortName}`)}}),YN=Z("slice",({db:e,args:t,opts:n,budget:r})=>{let i=j(n,"forward")?"forward":"backward",o=yn(e,O(t,0),{direction:i,maxDepth:C(n,"depth",3),semantic:r.semantic});if(!o)return L.empty("Symbol not found.");if(console.log(`${o.direction} slice of ${o.shortName}
893
- `),o.connectedSymbols.length===0){console.log(" No connected symbols found.");return}L.list(o.connectedSymbols,s=>` ${s.file} ${s.shortName}
896
+ `);for(let o=0;o<i.length;o++)console.log(` ${String(Ee(r.startLine+o)).padStart(4)} ${i[o]}`)}),WE=Z("dataflow",({db:e,args:t,opts:n,budget:r})=>{let i=Ur(e,H(t,0),{semantic:r.semantic});if(x(n,"json")){T("dataflow",t,n,i);return}if(!i)return I.empty("Symbol not found.");if(console.log(`${i.shortName} (${i.relativePath})
897
+ `),i.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let o of i.definitionSites)console.log(` ${o.file}:${Ee(o.line)}`)}if(i.usageSites.length>0){console.log(`
898
+ \u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let o of i.usageSites)console.log(` ${o.file}:${Ee(o.line)} in ${o.enclosingShort}`)}if(i.producers.length>0){console.log(`
899
+ \u2550\u2550\u2550 PRODUCERS (feeds into this) \u2550\u2550\u2550`);for(let o of i.producers)console.log(` ${o.file} ${o.shortName}`)}if(i.consumers.length>0){console.log(`
900
+ \u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let o of i.consumers)console.log(` ${o.file} ${o.shortName}`)}}),UE=Z("slice",({db:e,args:t,opts:n,budget:r})=>{let i=x(n,"forward")?"forward":"backward",o=Qn(e,H(t,0),{direction:i,maxDepth:D(n,"depth",3),semantic:r.semantic});if(x(n,"json")){T("slice",t,n,o);return}if(!o)return I.empty("Symbol not found.");if(console.log(`${o.direction} slice of ${o.shortName}
901
+ `),o.connectedSymbols.length===0){console.log(" No connected symbols found.");return}I.list(o.connectedSymbols,s=>` ${s.file} ${s.shortName}
894
902
  ${s.relationship}`),console.log(`
895
- ${o.connectedSymbols.length} connected symbol(s).`)}),dd=[Ge({id:"files",command:"files <pattern>",description:"Find files matching a pattern",docs:I("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>Ei(e,O(t,0)),format:e=>e.relativePath}),Ge({id:"methods",command:"methods <className>",description:"List methods of a class (with line ranges)",docs:I("Navigation"),query:({db:e,args:t})=>go(e,O(t,0)),format:e=>` ${me(e.startLine,e.endLine)} ${e.name}`}),{id:"refs",command:"refs <symbol>",description:"Find all files referencing a symbol",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"grouped-by-file",docs:I("Navigation",["scip-query refs login"]),handler:zN},Li({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:I("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>$n(e,O(t,0),{semantic:n.semantic}),sections:WN}),Ge({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",docs:I("Navigation"),query:({db:e,args:t})=>jn(e,O(t,0)),format:e=>e.relativePath}),Ge({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",docs:I("Navigation"),query:({db:e,args:t})=>Bn(e,O(t,0)),format:e=>e.relativePath}),od({id:"system",command:"system <module>",description:"Full module map: files, symbols, deps in/out",docs:I("Navigation",["scip-query system queries"]),query:({db:e,args:t})=>Hn(e,O(t,0)),sections:e=>[{title:"FILES",rows:e.files},{title:"EXPORTED SYMBOLS",rows:e.symbols.map(t=>` ${me(t.startLine,t.endLine)} ${t.shortName}`)},{title:"DEPENDS ON (internal)",rows:e.dependsOn.map(t=>` ${t}`)},{title:"DEPENDED ON BY",rows:e.dependedOnBy.map(t=>` ${t}`)}]}),Ge({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",docs:I("Navigation"),query:({db:e,args:t})=>qn(e,O(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"list",docs:I("Navigation"),handler:JN},Ge({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",docs:I("Navigation"),query:({db:e,args:t})=>vo(e,O(t,0)),format:e=>` ${e.fromFile}`}),{id:"outline",command:"outline <file>",description:"Tree view of symbols in a file, with line ranges",options:[g("--signatures","Show trimmed symbol signatures")],renderShape:"custom",docs:I("Navigation"),handler:UN},Ge({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",docs:I("Navigation"),query:({db:e,args:t})=>_o(e,O(t,0)),format:e=>` ${me(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`}),Ge({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",options:[g("-s, --scope <path>","Limit to files matching path"),g("-n, --limit <n>","Number of results",v,100)],docs:I("Navigation"),query:({db:e,args:t,opts:n})=>Oo(e,O(t,0),{scope:E(n,"scope"),limit:C(n,"limit",100)}),format:e=>` ${ae(e.relativePath,e.startLine,e.endLine)} [${e.kindName}] ${e.shortName}`,emptyMessage:({args:e})=>`No symbols found for kind "${O(e,0)}". Use "kind-counts" to see available kinds.`,after:e=>console.log(`
896
- ${e.length} symbol(s)`)}),_i({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",options:[g("-s, --scope <path>","Limit to files matching path")],docs:I("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>$o(e,{scope:E(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),Ge({id:"hierarchy",command:"hierarchy <symbol>",description:"Show a symbol's ancestry chain (method \u2192 class \u2192 module)",docs:I("Navigation"),query:({db:e,args:t})=>Bo(e,O(t,0)),format:e=>`${" ".repeat(e.depth)}${e.shortName}`,emptyMessage:()=>"Symbol not found."}),{id:"code",command:"code <symbol>",description:"Read the source code for a symbol (bounded to its definition range)",options:[g("-C, --context <n>","Extra lines of context above/below",v,0)],renderShape:"custom",docs:I("Navigation"),handler:KN},{id:"dataflow",command:"dataflow <symbol>",description:"Reference-level dataflow: definition sites, usage sites, producers, consumers",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"custom",docs:I("Navigation"),handler:QN},{id:"slice",command:"slice <symbol>",description:"Reference-level program slice: what affects this (backward) or what this affects (forward)",options:[g("--forward","Forward slice (what does this affect). Default is backward."),g("--depth <n>","Max transitive depth for backward slice",v,3),g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"custom",docs:I("Navigation"),handler:YN}];var XN=Z("plan-context",({db:e,args:t,opts:n,budget:r})=>{let i=C(n,"limit",20),o=ss(e,O(t,0),{semantic:r.semantic,impactDepth:C(n,"impactDepth",3),sliceDepth:C(n,"sliceDepth",3),scope:E(n,"scope")});if(o.warnings.length===1&&o.warnings[0]==="No symbol, file, or module matched target.")return L.empty(o.warnings[0]);let s=[{title:"TARGET",rows:ZN(o)},{title:"DEFINITIONS",rows:e_(o,i),skipIfEmpty:!0},{title:"REFERENCES",rows:t_(o,i),skipIfEmpty:!0},{title:"CALL GRAPH",rows:n_(o,i),skipIfEmpty:!0},{title:"DATAFLOW",rows:r_(o,i),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:i_(o,i),skipIfEmpty:!0},{title:"SURFACE",rows:o_(o,i),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:s_(o,i),skipIfEmpty:!0},{title:"CHANGE RISK",rows:a_(o,i),skipIfEmpty:!0},{title:"HISTORY",rows:c_(o),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:l_(o),skipIfEmpty:!0}];L.sectionedReport(s)}),pd=[{id:"plan-context",command:"plan-context <target>",description:"Pre-edit planning context for a symbol, file, or module",options:[g("--impact-depth <n>","Maximum affected traversal depth",v,3),g("--slice-depth <n>","Maximum backward slice depth",v,3),g("-s, --scope <path>","Limit downstream impact to files matching path"),g("-n, --limit <n>","Rows per section",v,20),g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"custom",docs:I("Planning",["scip-query plan-context parseSymbol"]),handler:XN}];function ZN(e){return[`Target: ${e.target}`,`Matched: symbol=${ta(e.matched.symbol)} file=${ta(e.matched.file)} module=${ta(e.matched.module)}`]}function e_(e,t){let n=[];for(let r of e.trace.definitions){let i=r.signature?` -- ${r.signature}`:"";n.push(` ${ae(r.relativePath,r.startLine,r.endLine)}${i}`),r.source&&n.push(...r.source.split(`
897
- `).map((o,s)=>` ${String(xe(r.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(r=>` ${me(r.startLine,r.endLine)} ${r.shortName}`)),St(n,t).rows}function t_(e,t){let n=e.trace.referencedBy.map(r=>` ${r.relativePath}:${xe(r.line)} in ${r.enclosingShort}`);return Qt(St(n,t))}function n_(e,t){if(!e.callGraph)return[];let n=e.callGraph.callers.map(i=>` caller ${i.file} ${i.shortName}`),r=e.callGraph.callees.map(i=>` callee ${i.file} ${i.shortName}`);return Qt(St([...n,...r],t))}function r_(e,t){if(!e.dataflow)return[];let n=e.dataflow.producers.map(o=>` producer ${o.file} ${o.shortName}`),r=e.dataflow.consumers.map(o=>` consumer ${o.file} ${o.shortName}`),i=e.dataflow.usageSites.map(o=>` usage ${o.file}:${xe(o.line)} in ${o.enclosingShort}`);return Qt(St([...n,...r,...i],t))}function i_(e,t){let n=[...e.deps.map(r=>` file depends on ${r.relativePath}`),...e.rdeps.map(r=>` file depended on by ${r.relativePath}`),...e.system.dependsOn.map(r=>` module depends on ${r}`),...e.system.dependedOnBy.map(r=>` module used by ${r}`)];return Qt(St(n,t))}function o_(e,t){let n=[...e.system.files.map(r=>` file ${r}`),...e.system.symbols.map(r=>` export ${me(r.startLine,r.endLine)} ${r.shortName}`),...e.surface.map(r=>` use ${r.consumer} -> ${r.shortName}`)];return Qt(St(n,t))}function s_(e,t){let n=[],r=-1;for(let i of e.affected)i.depth!==r&&(n.push(` -- Depth ${i.depth} --`),r=i.depth),n.push(` ${i.file} ${i.shortName}`);return Qt(St(n,t))}function a_(e,t){let n=[];return e.changeSurface&&(n.push(` File: ${e.changeSurface.file}`),n.push(` External consumers: ${e.changeSurface.totalExternalConsumers}`),n.push(...e.changeSurface.symbols.map(r=>{let i=r.riskLevel==="high"?" *** HIGH RISK ***":r.riskLevel==="medium"?" * medium risk *":"";return` ${me(r.startLine,r.endLine)} ${r.shortName} [${r.externalConsumers} consumers]${i}`}))),e.complexity&&(n.push(` Complexity: ${ae(e.complexity.relativePath,e.complexity.startLine,e.complexity.endLine)} ${e.complexity.shortName}`),n.push(` LOC: ${e.complexity.loc}`),n.push(` Branches: ${e.complexity.branches}`),n.push(` Cyclomatic estimate: ${e.complexity.cyclomaticEstimate}`),n.push(` Callees: ${e.complexity.calleeCount}`),n.push(` Fan-in: ${e.complexity.fanIn}`),n.push(` Fan-out: ${e.complexity.fanOut}`)),Qt(St(n,t))}function c_(e){let t=e.history;if(!t.available||!t.file)return[];let n=[];if(t.churn){let r=t.churn.fixChanges>0?`, ${t.churn.fixChanges} in fix commits`:"";n.push(` Churn: ${t.churn.changes} change(s) in recent history${r}`)}for(let r of t.coChangePartners)n.push(` Usually changes with: ${r.file} (${r.together}x, ${Math.round(r.confidence*100)}%)`);return t.suppressionsInFile>0&&n.push(` Detector suppressions in file: ${t.suppressionsInFile} (accepted findings \u2014 read the reasons before refactoring)`),n}function l_(e){let t=e.warnings.map(r=>` ${r}`);return e.history.coChangePartners.length>0&&t.push(" Check the HISTORY co-change partners \u2014 editing this file usually means editing them too."),(e.changeSurface?.symbols.filter(r=>r.riskLevel==="high")??[]).length>0&&t.push(" Inspect high-risk consumers before editing public behavior."),e.affected.length>0&&t.push(" Validate downstream consumers at the shallowest affected depths first."),t}function St(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function Qt(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function ta(e){return e?"yes":"no"}var u_=["stats","files","methods","refs","trace","deps","rdeps","system","surface","dead","hotspots","imports","imported-by","unused-imports","outline","members","fan-in","fan-out","coupling","cycles","bottlenecks","isolated","by-kind","kind-counts","deep-chains","hierarchy","call-graph","similar","similar-files","similar-chains","extract-candidates","affected","change-surface","cleanup-plan","co-change","recent-duplicates","doc-drift","unused-params","diff-gate","incomplete-migration","plan-context","drift","wrapper-candidates","passthrough-candidates","stale-abstractions","complexity-hotspots","self-audit","convergence","code","complexity","dataflow","slice","redundant-reexports","similar-signatures"],m_=[cd,dd,ld,ad,md,pd,ud],fd=m_.flat(),d_=new Map(fd.map(e=>[e.id,e]));for(let e of fd)if(!u_.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);function N(e){let t=d_.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var gd=[{id:"reindex",command:"reindex",description:"Index the codebase and convert to SQLite",options:[g("-l, --language <lang>","Index only this language (can be repeated)",Iu,[]),g("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),g("--force","Rebuild even if source inputs are unchanged"),g("--allow-partial","Write an incomplete index when one or more detected languages fail"),g("--indexer-concurrency <n>","Number of language indexers to run at once",pi)],renderShape:"custom",docs:I("Indexing",["scip-query reindex"]),handler:jm},{id:"augment-sources",command:"augment-sources",description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:I("Indexing"),handler:Bm},{id:"augment-vue",command:"augment-vue",description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[g("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:I("Indexing"),handler:Hm},N("stats"),N("files"),N("methods"),N("refs"),N("trace"),N("deps"),N("rdeps"),N("system"),N("surface"),N("dead"),N("hotspots"),N("imports"),N("imported-by"),N("unused-imports"),N("outline"),N("members"),N("fan-in"),N("fan-out"),N("coupling"),N("cycles"),N("bottlenecks"),N("isolated"),N("by-kind"),N("kind-counts"),N("deep-chains"),N("hierarchy"),N("call-graph"),N("similar"),N("similar-files"),N("similar-chains"),N("extract-candidates"),N("affected"),N("change-surface"),N("cleanup-plan"),N("co-change"),N("recent-duplicates"),N("doc-drift"),N("unused-params"),N("diff-gate"),N("incomplete-migration"),N("plan-context"),{id:di,command:di,description:"Internal diff-impact batch worker",hidden:!0,options:[g("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:qm},{id:"diff-impact",command:"diff-impact",description:"Compute changed symbols and downstream consumers from current git diff",options:[g("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",docs:I("Impact"),handler:Vm},N("drift"),N("wrapper-candidates"),N("passthrough-candidates"),N("stale-abstractions"),N("complexity-hotspots"),N("self-audit"),{id:mi,command:mi,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[g("-s, --scope <path>","Limit to files matching path"),g("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:Wm},{id:"health",command:"health",description:"Composite codebase health report with prioritized action list",options:[g("-s, --scope <path>","Limit to files matching path"),g("--full","Run unbounded candidate analyses on large indexes"),g("--json","Output as JSON for programmatic consumption"),g("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),g("--write-baseline","Snapshot current finding identities to the baseline file")],renderShape:"custom",docs:I("Health",["scip-query health --json","scip-query health --baseline"]),handler:Um},N("convergence"),N("code"),N("complexity"),N("dataflow"),N("slice"),{id:"install-skills",command:"install-skills",description:`Install skills (${Es.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:I("Maintenance"),handler:Gm},{id:"check-deps",command:"check-deps",description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:I("Maintenance"),handler:Jm},N("redundant-reexports"),N("similar-signatures"),{id:"init",command:"init",description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:I("Maintenance"),handler:zm},{id:"setup-agent",command:"setup-agent",description:"Seed agent guidance for this project: AGENTS.md/CLAUDE.md block pointing agents at the scip-query skills and diff gate, plus an optional git pre-commit backstop",options:[g("--git-hook","Also install a git pre-commit hook that runs diff-gate")],renderShape:"custom",docs:I("Maintenance",["scip-query setup-agent","scip-query setup-agent --git-hook"]),handler:Km},{id:"watch",command:"watch",description:"Watch for file changes and reindex automatically",options:[g("--debounce <ms>","Ms to wait after last change (default: 30000)",vs),g("--cooldown <ms>","Min ms between reindexes (default: 60000)",vs)],renderShape:"custom",docs:I("Maintenance"),handler:Qm},{id:"status",command:"status",description:"Show index status for this project",renderShape:"custom",docs:I("Maintenance"),handler:Ym}];function hd(e,t){return t.map(n=>{let r=n.hidden?e.command(n.command,{hidden:!0}):e.command(n.command);r.description(n.description);for(let i of n.arguments??[])r.argument(i.name);for(let i of n.options??[])i.parser&&Object.hasOwn(i,"defaultValue")?r.option(i.flags,i.description,i.parser,i.defaultValue):i.parser?r.option(i.flags,i.description,i.parser):Object.hasOwn(i,"defaultValue")?r.option(i.flags,i.description,i.defaultValue):r.option(i.flags,i.description);return r.action((...i)=>n.handler(...i)),{descriptor:n,command:r}})}import{existsSync as p_,mkdirSync as f_,readFileSync as g_,writeFileSync as h_}from"fs";import{homedir as y_}from"os";import{join as wi}from"path";var b_=1440*60*1e3,bd="update-check.json",S_="https://registry.npmjs.org/scip-query/latest";async function Sd(e={}){let t=e.env??process.env;if(t.SCIP_QUERY_UPDATE_CHECK==="0"||t.NO_UPDATE_NOTIFIER)return;let n=e.cacheDir??R_(t),r=e.now??Date.now(),i=e.currentVersion??ui,o=I_(n),s=o&&r-o.checkedAt<b_?o.latestVersion:await v_(n,e.fetchLatestVersion??N_,r);if(!s||!C_(s,i))return;(e.writeNotice??(c=>console.error(c)))(x_(i,s))}function x_(e,t){return[`scip-query update available: ${e} -> ${t}.`,"Agent: tell your human to update with: npm install -g scip-query@latest",""].join(`
898
- `)}function C_(e,t){let n=yd(e),r=yd(t);if(!n||!r)return e!==t;for(let i=0;i<n.length;i++){let o=n[i]-r[i];if(o>0)return!0;if(o<0)return!1}return!1}function R_(e){let t=e.XDG_CACHE_HOME||wi(y_(),".cache");return wi(t,"scip-query")}function I_(e){let t=wi(e,bd);if(!p_(t))return null;try{let n=JSON.parse(g_(t,"utf8"));return typeof n.checkedAt=="number"&&(typeof n.latestVersion=="string"||n.latestVersion===null)?{checkedAt:n.checkedAt,latestVersion:n.latestVersion}:null}catch{return null}}async function v_(e,t,n){let r;try{r=await t()}catch{r=null}return D_(e,{checkedAt:n,latestVersion:r}),r}function D_(e,t){try{f_(e,{recursive:!0}),h_(wi(e,bd),`${JSON.stringify(t,null,2)}
899
- `)}catch{}}async function N_(){let e=await fetch(S_,{signal:AbortSignal.timeout(1e3)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}function yd(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}ki.name("scip-query").description("Language-agnostic code intelligence CLI powered by SCIP indexes").version(ui);hd(ki,gd);ki.hook("preAction",async()=>{await Sd()});L_()&&await ki.parseAsync();function L_(){if(!process.argv[1])return!1;let e=__(import.meta.url);try{return xd(e)===xd(process.argv[1])}catch{return e===process.argv[1]}}export{ki as program,cr as renderHeuristicNotice};
903
+ ${o.connectedSymbols.length} connected symbol(s).`)}),Bf=[ct({id:"files",command:"files <pattern>",description:"Find files matching a pattern",docs:v("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>Mo(e,H(t,0)),format:e=>e.relativePath}),ct({id:"methods",command:"methods <className>",description:"List methods of a class (with line ranges)",docs:v("Navigation"),query:({db:e,args:t})=>Is(e,H(t,0)),format:e=>` ${ve(e.startLine,e.endLine)} ${e.name}`}),{id:"refs",command:"refs <symbol>",description:"Find all files referencing a symbol",options:[p("--full","Run unbounded semantic analysis on large indexes"),p("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"grouped-by-file",docs:v("Navigation",["scip-query refs login"]),handler:HE},Eo({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[p("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:v("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>vr(e,H(t,0),{semantic:n.semantic}),sections:OE}),ct({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",docs:v("Navigation"),query:({db:e,args:t})=>Rr(e,H(t,0)),format:e=>e.relativePath}),ct({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",docs:v("Navigation"),query:({db:e,args:t})=>Lr(e,H(t,0)),format:e=>e.relativePath}),Ff({id:"system",command:"system <module>",description:"Full module map: files, symbols, deps in/out",docs:v("Navigation",["scip-query system queries"]),query:({db:e,args:t})=>Ir(e,H(t,0)),sections:e=>[{title:"FILES",rows:e.files},{title:"EXPORTED SYMBOLS",rows:e.symbols.map(t=>` ${ve(t.startLine,t.endLine)} ${t.shortName}`)},{title:"DEPENDS ON (internal)",rows:e.dependsOn.map(t=>` ${t}`)},{title:"DEPENDED ON BY",rows:e.dependedOnBy.map(t=>` ${t}`)}]}),ct({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",docs:v("Navigation"),query:({db:e,args:t})=>Dr(e,H(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",options:[p("--full","Run unbounded semantic analysis on large indexes"),p("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"list",docs:v("Navigation"),handler:VE},ct({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",docs:v("Navigation"),query:({db:e,args:t})=>Ts(e,H(t,0)),format:e=>` ${e.fromFile}`}),{id:"outline",command:"outline <file>",description:"Tree view of symbols in a file, with line ranges",options:_([p("--signatures","Show trimmed symbol signatures")]),renderShape:"custom",docs:v("Navigation"),handler:jE},ct({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",docs:v("Navigation"),query:({db:e,args:t})=>Ms(e,H(t,0)),format:e=>` ${ve(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`}),ct({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",options:[p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",S,100),p("--full","Run unbounded analysis on large indexes")],docs:v("Navigation"),query:({db:e,args:t,opts:n})=>Gs(e,H(t,0),{scope:P(n,"scope"),limit:O(n,"limit",100)}),format:e=>` ${ge(e.relativePath,e.startLine,e.endLine)} [${e.kindName}] ${e.shortName}`,emptyMessage:({args:e})=>`No symbols found for kind "${H(e,0)}". Use "kind-counts" to see available kinds.`,after:e=>console.log(`
904
+ ${e.length} symbol(s)`)}),_o({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",options:[p("-s, --scope <path>","Limit to files matching path")],docs:v("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>zs(e,{scope:P(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),ct({id:"hierarchy",command:"hierarchy <symbol>",description:"Show a symbol's ancestry chain (method \u2192 class \u2192 module)",docs:v("Navigation"),query:({db:e,args:t})=>Qs(e,H(t,0)),format:e=>`${" ".repeat(e.depth)}${e.shortName}`,emptyMessage:()=>"Symbol not found."}),{id:"code",command:"code <symbol>",description:"Read the source code for a symbol (bounded to its definition range)",options:_([p("-C, --context <n>","Extra lines of context above/below",S,0)]),renderShape:"custom",docs:v("Navigation"),handler:qE},{id:"dataflow",command:"dataflow <symbol>",description:"Reference-level dataflow: definition sites, usage sites, producers, consumers",options:_([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:v("Navigation"),handler:WE},{id:"slice",command:"slice <symbol>",description:"Reference-level program slice: what affects this (backward) or what this affects (forward)",options:_([p("--forward","Forward slice (what does this affect). Default is backward."),p("--depth <n>","Max transitive depth for backward slice",S,3),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:v("Navigation"),handler:UE}];var JE=Z("plan-context",({db:e,args:t,opts:n,budget:r})=>{let i=O(n,"limit",20),o=ya(e,H(t,0),{semantic:r.semantic,impactDepth:D(n,"impactDepth",3),sliceDepth:D(n,"sliceDepth",3),scope:P(n,"scope")});if(o.warnings.length===1&&o.warnings[0]==="No symbol, file, or module matched target."){if(x(n,"json")){T("plan-context",t,n,o);return}return I.empty(o.warnings[0])}if(x(n,"json")){T("plan-context",t,n,o);return}let s=[{title:"TARGET",rows:GE(o)},{title:"DEFINITIONS",rows:zE(o,i),skipIfEmpty:!0},{title:"REFERENCES",rows:KE(o,i),skipIfEmpty:!0},{title:"CALL GRAPH",rows:QE(o,i),skipIfEmpty:!0},{title:"DATAFLOW",rows:XE(o,i),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:YE(o,i),skipIfEmpty:!0},{title:"SURFACE",rows:ZE(o,i),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:e0(o,i),skipIfEmpty:!0},{title:"CHANGE RISK",rows:t0(o,i),skipIfEmpty:!0},{title:"HISTORY",rows:n0(o),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:r0(o),skipIfEmpty:!0}];I.sectionedReport(s)}),Vf=[{id:"plan-context",command:"plan-context <target>",description:"Pre-edit planning context for a symbol, file, or module",options:_([p("--impact-depth <n>","Maximum affected traversal depth",S,3),p("--slice-depth <n>","Maximum backward slice depth",S,3),p("-s, --scope <path>","Limit downstream impact to files matching path"),p("-n, --limit <n>","Rows per section",S,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:v("Planning",["scip-query plan-context parseSymbol"]),handler:JE}];function GE(e){return[`Target: ${e.target}`,`Matched: symbol=${xc(e.matched.symbol)} file=${xc(e.matched.file)} module=${xc(e.matched.module)}`]}function zE(e,t){let n=[];for(let r of e.trace.definitions){let i=r.signature?` -- ${r.signature}`:"";n.push(` ${ge(r.relativePath,r.startLine,r.endLine)}${i}`),r.source&&n.push(...r.source.split(`
905
+ `).map((o,s)=>` ${String(Ee(r.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(r=>` ${ve(r.startLine,r.endLine)} ${r.shortName}`)),jt(n,t).rows}function KE(e,t){let n=e.trace.referencedBy.map(r=>` ${r.relativePath}:${Ee(r.line)} in ${r.enclosingShort}`);return Rn(jt(n,t))}function QE(e,t){if(!e.callGraph)return[];let n=e.callGraph.callers.map(i=>` caller ${i.file} ${i.shortName}`),r=e.callGraph.callees.map(i=>` callee ${i.file} ${i.shortName}`);return Rn(jt([...n,...r],t))}function XE(e,t){if(!e.dataflow)return[];let n=e.dataflow.producers.map(o=>` producer ${o.file} ${o.shortName}`),r=e.dataflow.consumers.map(o=>` consumer ${o.file} ${o.shortName}`),i=e.dataflow.usageSites.map(o=>` usage ${o.file}:${Ee(o.line)} in ${o.enclosingShort}`);return Rn(jt([...n,...r,...i],t))}function YE(e,t){let n=[...e.deps.map(r=>` file depends on ${r.relativePath}`),...e.rdeps.map(r=>` file depended on by ${r.relativePath}`),...e.system.dependsOn.map(r=>` module depends on ${r}`),...e.system.dependedOnBy.map(r=>` module used by ${r}`)];return Rn(jt(n,t))}function ZE(e,t){let n=[...e.system.files.map(r=>` file ${r}`),...e.system.symbols.map(r=>` export ${ve(r.startLine,r.endLine)} ${r.shortName}`),...e.surface.map(r=>` use ${r.consumer} -> ${r.shortName}`)];return Rn(jt(n,t))}function e0(e,t){let n=[],r=-1;for(let i of e.affected)i.depth!==r&&(n.push(` -- Depth ${i.depth} --`),r=i.depth),n.push(` ${i.file} ${i.shortName}`);return Rn(jt(n,t))}function t0(e,t){let n=[];return e.changeSurface&&(n.push(` File: ${e.changeSurface.file}`),n.push(` External consumers: ${e.changeSurface.totalExternalConsumers}`),n.push(...e.changeSurface.symbols.map(r=>{let i=r.riskLevel==="high"?" *** HIGH RISK ***":r.riskLevel==="medium"?" * medium risk *":"";return` ${ve(r.startLine,r.endLine)} ${r.shortName} [${r.externalConsumers} consumers]${i}`}))),e.complexity&&(n.push(` Complexity: ${ge(e.complexity.relativePath,e.complexity.startLine,e.complexity.endLine)} ${e.complexity.shortName}`),n.push(` LOC: ${e.complexity.loc}`),n.push(` Branches: ${e.complexity.branches}`),n.push(` Cyclomatic estimate: ${e.complexity.cyclomaticEstimate}`),n.push(` Callees: ${e.complexity.calleeCount}`),n.push(` Fan-in: ${e.complexity.fanIn}`),n.push(` Fan-out: ${e.complexity.fanOut}`)),Rn(jt(n,t))}function n0(e){let t=e.history;if(!t.available||!t.file)return[];let n=[];if(t.churn){let r=t.churn.fixChanges>0?`, ${t.churn.fixChanges} in fix commits`:"";n.push(` Churn: ${t.churn.changes} change(s) in recent history${r}`)}for(let r of t.coChangePartners)n.push(` Usually changes with: ${r.file} (${r.together}x, ${Math.round(r.confidence*100)}%)`);return t.suppressionsInFile>0&&n.push(` Detector suppressions in file: ${t.suppressionsInFile} (accepted findings \u2014 read the reasons before refactoring)`),n}function r0(e){let t=e.warnings.map(r=>` ${r}`);return e.history.coChangePartners.length>0&&t.push(" Check the HISTORY co-change partners \u2014 editing this file usually means editing them too."),(e.changeSurface?.symbols.filter(r=>r.riskLevel==="high")??[]).length>0&&t.push(" Inspect high-risk consumers before editing public behavior."),e.affected.length>0&&t.push(" Validate downstream consumers at the shallowest affected depths first."),t}function jt(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function Rn(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function xc(e){return e?"yes":"no"}var i0=["stats","files","methods","refs","trace","deps","rdeps","system","surface","dead","hotspots","imports","imported-by","unused-imports","outline","members","fan-in","fan-out","coupling","cycles","bottlenecks","isolated","by-kind","kind-counts","deep-chains","hierarchy","call-graph","similar","similar-files","react-component-duplicates","react-hook-candidates","react-large-component-pressure","vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure","similar-chains","extract-candidates","affected","change-surface","cleanup-plan","cleanup-apply","co-change","recent-duplicates","doc-drift","unused-params","diff-gate","incomplete-migration","plan-context","drift","wrapper-candidates","passthrough-candidates","stale-abstractions","complexity-hotspots","self-audit","convergence","code","complexity","dataflow","slice","redundant-reexports","similar-signatures"],o0=[$f,Bf,Mf,Af,jf,Vf,Of],Hf=o0.flat(),s0=new Map(Hf.map(e=>[e.id,e]));for(let e of Hf)if(!i0.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);function R(e){let t=s0.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var qf=[{id:"reindex",command:"reindex",description:"Index the codebase and convert to SQLite",options:[p("-l, --language <lang>","Index only this language (can be repeated)",bo,[]),p("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),p("--force","Rebuild even if source inputs are unchanged"),p("--allow-partial","Write an incomplete index when one or more detected languages fail"),p("--indexer-concurrency <n>","Number of language indexers to run at once",yo)],renderShape:"custom",docs:v("Indexing",["scip-query reindex"]),handler:df},{id:"augment-sources",command:"augment-sources",description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:v("Indexing"),handler:mf},{id:"augment-vue",command:"augment-vue",description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[p("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:v("Indexing"),handler:pf},R("stats"),R("files"),R("methods"),R("refs"),R("trace"),R("deps"),R("rdeps"),R("system"),R("surface"),R("dead"),R("hotspots"),R("imports"),R("imported-by"),R("unused-imports"),R("outline"),R("members"),R("fan-in"),R("fan-out"),R("coupling"),R("cycles"),R("bottlenecks"),R("isolated"),R("by-kind"),R("kind-counts"),R("deep-chains"),R("hierarchy"),R("call-graph"),R("similar"),R("similar-files"),R("react-component-duplicates"),R("react-hook-candidates"),R("react-large-component-pressure"),R("vue-component-duplicates"),R("vue-composable-candidates"),R("vue-large-view-pressure"),R("similar-chains"),R("extract-candidates"),R("affected"),R("change-surface"),R("cleanup-plan"),R("cleanup-apply"),R("co-change"),R("recent-duplicates"),R("doc-drift"),R("unused-params"),R("diff-gate"),R("incomplete-migration"),R("plan-context"),{id:ho,command:ho,description:"Internal diff-impact batch worker",hidden:!0,options:[p("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:ff},{id:"diff-impact",command:"diff-impact",description:"Compute changed symbols and downstream consumers from current git diff",options:[p("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",docs:v("Impact"),handler:gf},R("drift"),R("wrapper-candidates"),R("passthrough-candidates"),R("stale-abstractions"),R("complexity-hotspots"),R("self-audit"),{id:go,command:go,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:hf},{id:"health",command:"health",description:"Composite codebase health report with prioritized action list",options:[p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded candidate analyses on large indexes"),p("--json","Output as JSON for programmatic consumption"),p("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),p("--write-baseline","Snapshot current finding identities to the baseline file")],renderShape:"custom",docs:v("Health",["scip-query health --json","scip-query health --baseline"]),handler:bf},R("convergence"),R("code"),R("complexity"),R("dataflow"),R("slice"),{id:"install-skills",command:"install-skills",description:`Install skills (${Ua.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:v("Maintenance"),handler:yf},{id:"check-deps",command:"check-deps",description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:v("Maintenance"),handler:Sf},{id:"capabilities",command:"capabilities",description:"Report which evidence and verification capabilities are available in this project",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:v("Maintenance"),handler:xf},{id:"capability-matrix",command:"capability-matrix",description:"Report the evidence and verification capability matrix by language",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:v("Maintenance"),handler:Cf},R("redundant-reexports"),R("similar-signatures"),{id:"init",command:"init",description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:v("Maintenance"),handler:Rf},{id:"config-validate",command:"config-validate",description:"Validate .scipquery.json, including structured suppressions and declared coupling groups",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:v("Maintenance",["scip-query config-validate"]),handler:Lf},{id:"suppress",command:"suppress <id>",description:"Record an accepted finding in .scipquery.json with a required reason",options:_([p("--reason <text>","Required human reason for accepting the finding"),p("--check <check>","Optional detector/check name to narrow the suppression"),p("--file <path>","Optional file path to narrow the suppression"),p("--expires-at <iso>","Optional ISO date after which the suppression expires")]),renderShape:"custom",docs:v("Maintenance",['scip-query suppress SQABC123DEF456 --reason "intentional boundary"']),handler:If},{id:"doctor",command:"doctor",description:"Diagnose config, index freshness, dependency readiness, and project capabilities",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:v("Maintenance"),handler:Df},{id:"setup-agent",command:"setup-agent",description:"Seed agent guidance for this project: AGENTS.md/CLAUDE.md block pointing agents at the scip-query skills and diff gate, plus an optional git pre-commit backstop",options:[p("--git-hook","Also install a git pre-commit hook that runs diff-gate")],renderShape:"custom",docs:v("Maintenance",["scip-query setup-agent","scip-query setup-agent --git-hook"]),handler:wf},{id:"setup-ci",command:"setup-ci",description:"Write a GitHub Actions workflow that runs scip-query reindex and diff-gate on pull requests",options:[p("--force","Overwrite an existing workflow"),p("--dry-run","Print the workflow without writing it")],renderShape:"custom",docs:v("Maintenance",["scip-query setup-ci"]),handler:Nf},{id:"watch",command:"watch",description:"Watch for file changes and reindex automatically",options:[p("--debounce <ms>","Ms to wait after last change (default: 30000)",Ma),p("--cooldown <ms>","Min ms between reindexes (default: 60000)",Ma)],renderShape:"custom",docs:v("Maintenance"),handler:Pf},{id:"status",command:"status",description:"Show index status for this project",options:[p("--json","Output as JSON for programmatic consumption"),p("--capabilities","Include the project capability matrix")],renderShape:"custom",docs:v("Maintenance"),handler:_f}];function Wf(e,t){return t.map(n=>{let r=n.hidden?e.command(n.command,{hidden:!0}):e.command(n.command);r.description(n.description);for(let i of n.arguments??[])r.argument(i.name);for(let i of n.options??[])i.parser&&Object.hasOwn(i,"defaultValue")?r.option(i.flags,i.description,i.parser,i.defaultValue):i.parser?r.option(i.flags,i.description,i.parser):Object.hasOwn(i,"defaultValue")?r.option(i.flags,i.description,i.defaultValue):r.option(i.flags,i.description);return r.action(async(...i)=>{try{await n.handler(...i)}catch(o){a0(o)}}),{descriptor:n,command:r}})}function a0(e){let t=e instanceof Error?e.message:String(e);console.error(`error: ${t}`),process.exitCode=1}import{existsSync as c0,mkdirSync as l0,readFileSync as u0,writeFileSync as d0}from"fs";import{homedir as m0}from"os";import{join as Fo}from"path";var p0=1440*60*1e3,Jf="update-check.json",f0="https://registry.npmjs.org/scip-query/latest";async function Gf(e={}){let t=e.env??process.env;if(t.SCIP_QUERY_UPDATE_CHECK==="0"||t.NO_UPDATE_NOTIFIER)return;let n=e.cacheDir??b0(t),r=e.now??Date.now(),i=e.currentVersion??fo,o=y0(n),s=o&&r-o.checkedAt<p0?o.latestVersion:await S0(n,e.fetchLatestVersion??C0,r);if(!s||!h0(s,i))return;(e.writeNotice??(c=>console.error(c)))(g0(i,s))}function g0(e,t){return[`scip-query update available: ${e} -> ${t}.`,"Agent: tell your human to update with: npm install -g scip-query@latest",""].join(`
906
+ `)}function h0(e,t){let n=Uf(e),r=Uf(t);if(!n||!r)return e!==t;for(let i=0;i<n.length;i++){let o=n[i]-r[i];if(o>0)return!0;if(o<0)return!1}return!1}function b0(e){let t=e.XDG_CACHE_HOME||Fo(m0(),".cache");return Fo(t,"scip-query")}function y0(e){let t=Fo(e,Jf);if(!c0(t))return null;try{let n=JSON.parse(u0(t,"utf8"));return typeof n.checkedAt=="number"&&(typeof n.latestVersion=="string"||n.latestVersion===null)?{checkedAt:n.checkedAt,latestVersion:n.latestVersion}:null}catch{return null}}async function S0(e,t,n){let r;try{r=await t()}catch{r=null}return x0(e,{checkedAt:n,latestVersion:r}),r}function x0(e,t){try{l0(e,{recursive:!0}),d0(Fo(e,Jf),`${JSON.stringify(t,null,2)}
907
+ `)}catch{}}async function C0(){let e=await fetch(f0,{signal:AbortSignal.timeout(1e3)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}function Uf(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}To.name("scip-query").description("Language-agnostic code intelligence CLI powered by SCIP indexes").version(fo);Wf(To,qf);To.hook("preAction",async()=>{await Gf()});R0()&&await To.parseAsync();function R0(){if(!process.argv[1])return!1;let e=v0(import.meta.url);try{return zf(e)===zf(process.argv[1])}catch{return e===process.argv[1]}}export{To as program,Kr as renderHeuristicNotice};
900
908
  //# sourceMappingURL=cli.js.map