scip-query 0.10.10 → 0.10.12

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 (279) hide show
  1. package/README.md +56 -35
  2. package/dist/augment-vue-worker.js +1 -1
  3. package/dist/chunk-2DOW7QCA.js +71 -0
  4. package/dist/chunk-2FMFF4RI.js +2 -0
  5. package/dist/{chunk-J7RWXLUL.js → chunk-2GLNBCHB.js} +2 -2
  6. package/dist/chunk-2UVCH7CQ.js +2 -0
  7. package/dist/{chunk-LM5SHAN4.js → chunk-3XSNW5XB.js} +2 -2
  8. package/dist/chunk-4ISHQ7UW.js +35 -0
  9. package/dist/{chunk-XXZXDXTD.js → chunk-5GXTUANY.js} +2 -2
  10. package/dist/{chunk-TL6QPNF5.js → chunk-5JHEN5VN.js} +2 -2
  11. package/dist/chunk-62ULXMQ7.js +18 -0
  12. package/dist/chunk-63CI3IXR.js +102 -0
  13. package/dist/{chunk-Z4I7BVIU.js → chunk-6BN3EHQE.js} +2 -2
  14. package/dist/chunk-7C6JBBE4.js +23 -0
  15. package/dist/chunk-7EK7OSWS.js +2 -0
  16. package/dist/chunk-7IWIMNHI.js +2 -0
  17. package/dist/chunk-7XTO4YXB.js +8 -0
  18. package/dist/{chunk-5NVUWIAN.js → chunk-A4UTLKHU.js} +2 -2
  19. package/dist/{chunk-FDEQIPPK.js → chunk-ANUEY5WV.js} +2 -2
  20. package/dist/chunk-AOWFUGDL.js +2 -0
  21. package/dist/chunk-AREANYIA.js +3 -0
  22. package/dist/{chunk-7UQWUVRG.js → chunk-AZBELWZQ.js} +2 -2
  23. package/dist/{chunk-WG6KRH5F.js → chunk-CXWCLVYL.js} +2 -2
  24. package/dist/chunk-CYHIKTJN.js +3 -0
  25. package/dist/{chunk-BVRS7RKQ.js → chunk-DDQONX6B.js} +2 -2
  26. package/dist/{chunk-736BLPHR.js → chunk-DFSEARAU.js} +2 -2
  27. package/dist/{chunk-UFX7EPBA.js → chunk-DQ6433ZG.js} +2 -2
  28. package/dist/chunk-DVFP6PZI.js +2 -0
  29. package/dist/chunk-E3ADDB43.js +2 -0
  30. package/dist/{chunk-YWOOQ4FF.js → chunk-ELC77ZDE.js} +1 -1
  31. package/dist/chunk-EOLGSSDR.js +2 -0
  32. package/dist/chunk-F6IXELII.js +20 -0
  33. package/dist/{chunk-QYB5P7GL.js → chunk-FMGVZBS2.js} +2 -2
  34. package/dist/{chunk-VOYOYC5T.js → chunk-FX6ULETZ.js} +2 -2
  35. package/dist/chunk-GG5LHT27.js +2 -0
  36. package/dist/chunk-GKB4JJDU.js +2 -0
  37. package/dist/chunk-H7JF2CKK.js +2 -0
  38. package/dist/chunk-HHOMJCP5.js +4 -0
  39. package/dist/chunk-HRDSU5FN.js +9 -0
  40. package/dist/{chunk-BZ53S4ZN.js → chunk-HWVYTJOV.js} +2 -2
  41. package/dist/chunk-JJ5SAWBT.js +2 -0
  42. package/dist/chunk-JNMLBL36.js +2 -0
  43. package/dist/chunk-JS6B76AQ.js +2 -0
  44. package/dist/{chunk-ZQO43G2T.js → chunk-KZ4MG5NY.js} +2 -2
  45. package/dist/{chunk-UQLFQLAF.js → chunk-L446VQYQ.js} +2 -2
  46. package/dist/{chunk-NZ4UDB5N.js → chunk-LDJUB7XW.js} +2 -2
  47. package/dist/{chunk-MMLZEGMS.js → chunk-LEHVP4DY.js} +2 -2
  48. package/dist/chunk-MNCQPMCH.js +2 -0
  49. package/dist/chunk-MYTUWXHK.js +4 -0
  50. package/dist/chunk-N25HPUOK.js +2 -0
  51. package/dist/chunk-NABVR6B7.js +2 -0
  52. package/dist/{chunk-PTQVNJ4Q.js → chunk-NBNEVLRC.js} +2 -2
  53. package/dist/chunk-NTSR6SRP.js +2 -0
  54. package/dist/{chunk-RYXW3KRC.js → chunk-OFXN2BCT.js} +2 -2
  55. package/dist/chunk-PWAK75BU.js +2 -0
  56. package/dist/chunk-Q5P7NOVM.js +2 -0
  57. package/dist/chunk-RGKRYO22.js +4 -0
  58. package/dist/chunk-RM2WQ75T.js +2 -0
  59. package/dist/chunk-ROGZXWN2.js +2 -0
  60. package/dist/chunk-RSSXKJ6J.js +38 -0
  61. package/dist/chunk-RUV5IY25.js +7 -0
  62. package/dist/chunk-RVGEZYMQ.js +2 -0
  63. package/dist/{chunk-IPQTC36U.js → chunk-RXINFVBN.js} +2 -2
  64. package/dist/{chunk-RXRLZFUL.js → chunk-S2MRVIJ5.js} +2 -2
  65. package/dist/chunk-SA3DPTHT.js +7 -0
  66. package/dist/chunk-SGTKURU6.js +52 -0
  67. package/dist/chunk-SQNHOOJ5.js +3 -0
  68. package/dist/chunk-T3AEVJBG.js +4 -0
  69. package/dist/{chunk-DQVKIG3D.js → chunk-T4N2ZRVY.js} +2 -2
  70. package/dist/{chunk-5VG7RKEF.js → chunk-TBCHRDAC.js} +2 -2
  71. package/dist/chunk-THB6AM3V.js +11 -0
  72. package/dist/chunk-ULHLDOD6.js +4 -0
  73. package/dist/chunk-UQ73QF5D.js +43 -0
  74. package/dist/chunk-UVPY3RUZ.js +2 -0
  75. package/dist/chunk-V5FGK3DZ.js +2 -0
  76. package/dist/{chunk-3DGD6NKW.js → chunk-VB2EZZPA.js} +2 -2
  77. package/dist/{chunk-56P7PDST.js → chunk-WTY5FERW.js} +2 -2
  78. package/dist/chunk-WUOB4DHH.js +6 -0
  79. package/dist/chunk-XHMVZFA6.js +2 -0
  80. package/dist/chunk-XRUGSM76.js +10 -0
  81. package/dist/{chunk-UYD7FJ3K.js → chunk-XUCZ3RQ5.js} +2 -2
  82. package/dist/chunk-YFQIKYOP.js +2 -0
  83. package/dist/chunk-Z2LDWIJV.js +5 -0
  84. package/dist/chunk-ZNWWVYQL.js +3 -0
  85. package/dist/{chunk-UDGXK2WA.js → chunk-ZUUNREKS.js} +2 -2
  86. package/dist/cli.js +277 -252
  87. package/dist/{config-types-BDIWAYzr.d.ts → config-types-dvHOz0zU.d.ts} +4 -1
  88. package/dist/{db-Djj3Nqrb.d.ts → db-rMZO5JFK.d.ts} +1 -1
  89. package/dist/{health-D5J42g4D.d.ts → health-CtTIGh6H.d.ts} +1 -1
  90. package/dist/index.d.ts +9 -5
  91. package/dist/index.js +2 -2
  92. package/dist/queries/affected.d.ts +2 -2
  93. package/dist/queries/affected.js +1 -1
  94. package/dist/queries/bottlenecks.d.ts +2 -2
  95. package/dist/queries/bottlenecks.js +1 -1
  96. package/dist/queries/by-kind.d.ts +2 -2
  97. package/dist/queries/by-kind.js +1 -1
  98. package/dist/queries/call-graph.d.ts +2 -2
  99. package/dist/queries/call-graph.js +1 -1
  100. package/dist/queries/change-surface.d.ts +2 -2
  101. package/dist/queries/change-surface.js +1 -1
  102. package/dist/queries/cleanup-plan.d.ts +2 -2
  103. package/dist/queries/cleanup-plan.js +1 -1
  104. package/dist/queries/co-change.d.ts +2 -2
  105. package/dist/queries/co-change.js +1 -1
  106. package/dist/queries/code.d.ts +2 -2
  107. package/dist/queries/code.js +1 -1
  108. package/dist/queries/complexity-hotspots.d.ts +2 -2
  109. package/dist/queries/complexity-hotspots.js +1 -1
  110. package/dist/queries/complexity.d.ts +2 -2
  111. package/dist/queries/complexity.js +1 -1
  112. package/dist/queries/convergence.d.ts +2 -2
  113. package/dist/queries/convergence.js +1 -1
  114. package/dist/queries/coupling.d.ts +2 -2
  115. package/dist/queries/coupling.js +1 -1
  116. package/dist/queries/cycles.d.ts +2 -2
  117. package/dist/queries/cycles.js +1 -1
  118. package/dist/queries/dataflow.d.ts +2 -2
  119. package/dist/queries/dataflow.js +1 -1
  120. package/dist/queries/dead.d.ts +2 -2
  121. package/dist/queries/dead.js +1 -1
  122. package/dist/queries/deep-chains.d.ts +2 -2
  123. package/dist/queries/deep-chains.js +1 -1
  124. package/dist/queries/deps.d.ts +2 -2
  125. package/dist/queries/deps.js +1 -1
  126. package/dist/queries/diff-gate.d.ts +2 -2
  127. package/dist/queries/diff-gate.js +1 -1
  128. package/dist/queries/diff-impact.d.ts +2 -2
  129. package/dist/queries/diff-impact.js +1 -1
  130. package/dist/queries/doc-drift.d.ts +2 -2
  131. package/dist/queries/doc-drift.js +1 -1
  132. package/dist/queries/drift.d.ts +2 -2
  133. package/dist/queries/drift.js +1 -1
  134. package/dist/queries/extract-candidates.d.ts +2 -2
  135. package/dist/queries/extract-candidates.js +1 -1
  136. package/dist/queries/fan.d.ts +2 -2
  137. package/dist/queries/fan.js +1 -1
  138. package/dist/queries/files.d.ts +2 -2
  139. package/dist/queries/health.d.ts +3 -3
  140. package/dist/queries/health.js +1 -1
  141. package/dist/queries/hierarchy.d.ts +2 -2
  142. package/dist/queries/hierarchy.js +1 -1
  143. package/dist/queries/hotspots.d.ts +2 -2
  144. package/dist/queries/hotspots.js +1 -1
  145. package/dist/queries/imports.d.ts +2 -2
  146. package/dist/queries/imports.js +1 -1
  147. package/dist/queries/incomplete-migration.d.ts +2 -2
  148. package/dist/queries/incomplete-migration.js +1 -1
  149. package/dist/queries/index.d.ts +4 -4
  150. package/dist/queries/index.js +1 -1
  151. package/dist/queries/isolated.d.ts +2 -2
  152. package/dist/queries/isolated.js +1 -1
  153. package/dist/queries/locality-candidates.d.ts +2 -2
  154. package/dist/queries/locality-candidates.js +1 -1
  155. package/dist/queries/members.d.ts +2 -2
  156. package/dist/queries/members.js +1 -1
  157. package/dist/queries/methods.d.ts +2 -2
  158. package/dist/queries/methods.js +1 -1
  159. package/dist/queries/outline.d.ts +2 -2
  160. package/dist/queries/outline.js +1 -1
  161. package/dist/queries/passthrough-candidates.d.ts +2 -2
  162. package/dist/queries/passthrough-candidates.js +1 -1
  163. package/dist/queries/plan-context.d.ts +2 -2
  164. package/dist/queries/plan-context.js +1 -1
  165. package/dist/queries/react-component-duplicates.d.ts +2 -2
  166. package/dist/queries/react-component-duplicates.js +1 -1
  167. package/dist/queries/react-hook-candidates.d.ts +2 -2
  168. package/dist/queries/react-hook-candidates.js +1 -1
  169. package/dist/queries/react-large-component-pressure.d.ts +2 -2
  170. package/dist/queries/react-large-component-pressure.js +1 -1
  171. package/dist/queries/recent-duplicates.d.ts +2 -2
  172. package/dist/queries/recent-duplicates.js +1 -1
  173. package/dist/queries/redundant-reexports.d.ts +2 -2
  174. package/dist/queries/redundant-reexports.js +1 -1
  175. package/dist/queries/refs.d.ts +2 -2
  176. package/dist/queries/refs.js +1 -1
  177. package/dist/queries/self-audit.d.ts +7 -4
  178. package/dist/queries/self-audit.js +1 -1
  179. package/dist/queries/similar-chains.d.ts +2 -2
  180. package/dist/queries/similar-chains.js +1 -1
  181. package/dist/queries/similar-files.d.ts +2 -2
  182. package/dist/queries/similar-files.js +1 -1
  183. package/dist/queries/similar-signatures.d.ts +2 -2
  184. package/dist/queries/similar-signatures.js +1 -1
  185. package/dist/queries/similar.d.ts +55 -16
  186. package/dist/queries/similar.js +1 -1
  187. package/dist/queries/slice.d.ts +2 -2
  188. package/dist/queries/slice.js +1 -1
  189. package/dist/queries/stale-abstractions.d.ts +2 -2
  190. package/dist/queries/stale-abstractions.js +1 -1
  191. package/dist/queries/stats.d.ts +2 -2
  192. package/dist/queries/surface.d.ts +2 -2
  193. package/dist/queries/surface.js +1 -1
  194. package/dist/queries/symbols.d.ts +2 -2
  195. package/dist/queries/symbols.js +1 -1
  196. package/dist/queries/system.d.ts +2 -2
  197. package/dist/queries/system.js +1 -1
  198. package/dist/queries/trace.d.ts +2 -2
  199. package/dist/queries/trace.js +1 -1
  200. package/dist/queries/unused-imports.d.ts +2 -2
  201. package/dist/queries/unused-imports.js +1 -1
  202. package/dist/queries/unused-params.d.ts +2 -2
  203. package/dist/queries/unused-params.js +1 -1
  204. package/dist/queries/vue-component-duplicates.d.ts +2 -2
  205. package/dist/queries/vue-component-duplicates.js +1 -1
  206. package/dist/queries/vue-composable-candidates.d.ts +2 -2
  207. package/dist/queries/vue-composable-candidates.js +1 -1
  208. package/dist/queries/vue-large-view-pressure.d.ts +2 -2
  209. package/dist/queries/vue-large-view-pressure.js +1 -1
  210. package/dist/queries/wrapper-candidates.d.ts +2 -2
  211. package/dist/queries/wrapper-candidates.js +1 -1
  212. package/dist/reindex-worker.js +9 -9
  213. package/dist/reindex.d.ts +30 -4
  214. package/dist/reindex.js +19 -19
  215. package/dist/runtime.d.ts +4 -3
  216. package/dist/runtime.js +2 -2
  217. package/dist/{scip-cli-CnK9Va4O.d.ts → scip-cli-trnNvymv.d.ts} +1 -1
  218. package/docs/COMMAND_REFERENCE.md +2 -2
  219. package/docs/analyzer-inventory.md +8 -0
  220. package/docs/analyzer-validation-ledger.md +7 -0
  221. package/package.json +3 -1
  222. package/scripts/evidence-product-contract.mjs +197 -0
  223. package/skills/scip-hyper-optimization/SKILL.md +153 -24
  224. package/skills/scip-hyper-optimization/agents/openai.yaml +3 -3
  225. package/dist/chunk-2UYQLFVC.js +0 -2
  226. package/dist/chunk-2VM46FC5.js +0 -8
  227. package/dist/chunk-3Q77KKEY.js +0 -2
  228. package/dist/chunk-3VD3JMK2.js +0 -2
  229. package/dist/chunk-4KTOV4QN.js +0 -3
  230. package/dist/chunk-4N4WONI4.js +0 -102
  231. package/dist/chunk-65AU3HFZ.js +0 -2
  232. package/dist/chunk-6LNQOOTB.js +0 -2
  233. package/dist/chunk-72KY2ZFO.js +0 -2
  234. package/dist/chunk-7JRRXGVZ.js +0 -2
  235. package/dist/chunk-A536TEU4.js +0 -3
  236. package/dist/chunk-A6IDHNMC.js +0 -4
  237. package/dist/chunk-A6TANQNV.js +0 -2
  238. package/dist/chunk-AW2QHPLL.js +0 -4
  239. package/dist/chunk-BSN22NRK.js +0 -9
  240. package/dist/chunk-C5CTSJ6X.js +0 -6
  241. package/dist/chunk-CCKPYPDI.js +0 -35
  242. package/dist/chunk-CZ425R2B.js +0 -18
  243. package/dist/chunk-DS6QEB3G.js +0 -5
  244. package/dist/chunk-F6ICF7HL.js +0 -40
  245. package/dist/chunk-FAYI6KZ5.js +0 -2
  246. package/dist/chunk-FG4NT6VY.js +0 -2
  247. package/dist/chunk-FRPEPTYJ.js +0 -5
  248. package/dist/chunk-GBEYTDY5.js +0 -2
  249. package/dist/chunk-GRJY65YT.js +0 -2
  250. package/dist/chunk-HF25DFSC.js +0 -3
  251. package/dist/chunk-HHN2B5KA.js +0 -2
  252. package/dist/chunk-I46WR7MT.js +0 -10
  253. package/dist/chunk-JM72FNGA.js +0 -2
  254. package/dist/chunk-KX5PLFZ5.js +0 -3
  255. package/dist/chunk-LPL4MA6R.js +0 -2
  256. package/dist/chunk-LZHUWKGD.js +0 -2
  257. package/dist/chunk-OBGRLXWF.js +0 -3
  258. package/dist/chunk-P5RYBRIO.js +0 -4
  259. package/dist/chunk-PFOCOG57.js +0 -2
  260. package/dist/chunk-PKMZCDQD.js +0 -4
  261. package/dist/chunk-QPU7EXAW.js +0 -2
  262. package/dist/chunk-QVI3NR7E.js +0 -7
  263. package/dist/chunk-QX7LLCGB.js +0 -23
  264. package/dist/chunk-RVWSAMTT.js +0 -2
  265. package/dist/chunk-SGLLBSCV.js +0 -2
  266. package/dist/chunk-SULEXAHO.js +0 -38
  267. package/dist/chunk-TH2N6QHW.js +0 -2
  268. package/dist/chunk-UWYJDBDW.js +0 -2
  269. package/dist/chunk-VUKC6F77.js +0 -20
  270. package/dist/chunk-W2CBNBEL.js +0 -71
  271. package/dist/chunk-XIVO4SDZ.js +0 -2
  272. package/dist/chunk-XSNRACLV.js +0 -3
  273. package/dist/chunk-XUGQU7PM.js +0 -41
  274. package/dist/chunk-Y6E3JHC4.js +0 -2
  275. package/dist/chunk-YBEEVDJQ.js +0 -2
  276. package/dist/chunk-YGHUVQLR.js +0 -2
  277. package/dist/chunk-YWDVDAD7.js +0 -2
  278. package/dist/chunk-YZA6PPZL.js +0 -3
  279. package/dist/chunk-ZU6PROUY.js +0 -2
package/dist/cli.js CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
- import{program as ra}from"commander";import{realpathSync as jb}from"fs";import{fileURLToPath as J1}from"url";import{spawn as FF}from"child_process";import{createRequire as AF}from"module";import{availableParallelism as $F}from"os";import{fileURLToPath as xl}from"url";import{statSync as Hb}from"fs";function Oe(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,...Vb(e.config.dbPath)}}function Vb(e){try{let t=Hb(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function O(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 Aa}from"commander";import{realpathSync as Fx}from"fs";import{fileURLToPath as AU}from"url";import{createRequire as hj}from"module";import{availableParallelism as yj}from"os";import{fileURLToPath as yu}from"url";import{statSync as Tx}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,i=e.get("SELECT COUNT(*) as c FROM mentions WHERE role = 1").c,r=e.get("SELECT COUNT(*) as c FROM mentions WHERE role != 1").c;return{documents:t,symbols:n,definitions:i,references:r,..._x(e.config.dbPath)}}function _x(e){try{let t=Tx(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function O(e,t={}){let n=t.scope?"AND relative_path LIKE ?":"",i=t.like?"AND relative_path LIKE ?":"",r=[...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
- ${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 qb(e){return/[*?]/.test(e)?e.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_"):`%${e}%`}function ia(e,t){let n=qb(t);return O(e,{like:n,includeIgnored:!1}).map(r=>({relativePath:r}))}import{extname as du}from"path";var Ub={".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 W(e){return Ub[du(e).toLowerCase()]??null}function Lt(e){return du(e).toLowerCase()===".vue"}var mu=[];function Bt(e){e.groups.length>0&&mu.push(e)}function oa(e,t){let n=new Set(t.groups);for(let r of mu)r.groups.some(i=>n.has(i))&&(t.file!==void 0&&r.clearFile?r.clearFile(e,t.file):r.clearAll(e))}function pu(){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 q(e,t){let{cache:n,ensure:r}=pu(),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 Bt({name:e,groups:t.clearGroups,clearAll:o=>i.invalidateAll(o),clearFile:(o,s)=>i.invalidate(o,s)}),i}function Z(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 Bt({name:e,groups:t.clearGroups,clearAll:i=>r.invalidate(i)}),r}var Wb={clearGroups:["whole-project","source-file"]};function Ht(e){return cn(e,Wb)}function cn(e,t){let{cache:n,ensure:r}=pu(),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 Bt({name:e,groups:t.clearGroups,clearAll:o=>i.invalidateAll(o),clearFile:(o,s)=>i.invalidate(o,s)}),i}import{createRequire as Gb}from"module";var Pe=Gb(import.meta.url),eo=null,fu=!1;function zb(){if(fu)return null;if(eo)return eo;try{return eo=Pe("tree-sitter"),eo}catch{return fu=!0,null}}var gu=new Map,sa=new Set;function Jb(e){if(sa.has(e))return null;let t=gu.get(e);if(t)return t;let n;try{switch(e){case"rust":n=Pe("tree-sitter-rust");break;case"typescript":n=Pe("tree-sitter-typescript").typescript;break;case"tsx":n=Pe("tree-sitter-typescript").tsx;break;case"javascript":n=Pe("tree-sitter-javascript");break;case"python":n=Pe("tree-sitter-python");break;case"java":n=Pe("tree-sitter-java");break;case"kotlin":n=Pe("tree-sitter-kotlin");break;case"scala":n=Pe("tree-sitter-scala");break;case"ruby":n=Pe("tree-sitter-ruby");break;case"c":n=Pe("tree-sitter-c");break;case"cpp":n=Pe("tree-sitter-cpp");break;case"csharp":n=Pe("tree-sitter-c-sharp");break;case"php":n=Pe("tree-sitter-php").php;break;case"vb":{let r=Pe("tree-sitter-vb-dotnet");n=r.language??r;break}}}catch{return sa.add(e),null}return gu.set(e,n),n}var hu=new Map;function Kb(e){let t=hu.get(e);if(t)return t;let n=Jb(e);if(!n)return null;let r=zb();if(!r)return null;let i=new r;try{i.setLanguage(n)}catch{return sa.add(e),null}return hu.set(e,i),i}function Xb(e,t){return e.parse(r=>r>=t.length?null:t.slice(r,Math.min(t.length,r+16384)))}function zr(e,t){let n=Kb(e);if(!n)return null;try{return Xb(n,t)}catch{return null}}import{readFileSync as Qb}from"fs";import{join as Yb}from"path";var Zb=q("source-text",{clearGroups:["whole-project","source-file"]}),eS=q("source-lines",{clearGroups:["whole-project","source-file"]});function T(e,t){let n=t.replace(/\\/g,"/");return Zb.get(e,n,()=>{let r=Yb(e.config.projectRoot,n);try{return Qb(r,"utf-8")}catch(i){if(tS(i))return"";throw i}})}function tS(e){return typeof e=="object"&&e!==null&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function We(e,t){let n=t.replace(/\\/g,"/");return eS.get(e,n,()=>{let r=T(e,n);return r?r.split(`
9
- `):[]})}var nS=/^\s*(?:\/\/|#|\/\*+|\*)\s*scip-query[\s:-]*ignore(?:[\s:-]+(dead(?:-code)?|stale|wrapper|passthrough|drift|extract|similar))?\b/i;function Jr(e){let t=nS.exec(e);return t?t[1]??"":null}function to(e,t,n){if(n<=0)return!1;let r=We(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(Jr(o)!==null)return!0;if(!o.startsWith("//")&&!o.startsWith("*")&&!o.startsWith("/*")&&!o.startsWith("@")&&!o.startsWith("#"))return!1}}return!1}import{parse as cS}from"@vue/compiler-sfc";import{posix as aa}from"path";import{parse as rS}from"@vue/compiler-sfc";var iS=Ht("vue-sfc-units");function ro(e,t){let n=Su(t),r=T(e,n);return iS.get(e,n,r,()=>oS(e,n,r))}function Su(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function ca(e){let t=e?.toLowerCase();return!t||t==="js"||t==="javascript"||t==="jsx"?"javascript":t==="ts"||t==="typescript"?"typescript":t==="tsx"?"tsx":null}function ln(e){return!e||e.body.length===0?0:e.body.split(`
10
- `).length}function oS(e,t,n){let r={relativePath:t,template:null,scripts:[],styles:[],customBlocks:[],errors:[]};if(!n)return r;let i;try{i=rS(n,{filename:t})}catch(s){return r.errors.push(bu(s)),r}r.errors.push(...i.errors.map(bu));let{descriptor:o}=i;return o.template&&(r.template=no(e,t,"template",o.template)),o.script&&r.scripts.push(yu(e,t,o.script,!1)),o.scriptSetup&&r.scripts.push(yu(e,t,o.scriptSetup,!0)),r.styles=o.styles.map(s=>no(e,t,"style",s)),r.customBlocks=o.customBlocks.map(s=>no(e,t,"custom",s)),r.errors.push(...[r.template,...r.scripts,...r.styles,...r.customBlocks].flatMap(s=>s?.errors??[])),r}function yu(e,t,n,r){let i=no(e,t,"script",n);return{...i,kind:"script",setup:r,astLanguage:ca(i.lang)}}function no(e,t,n,r){let i=aS(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=sS(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=T(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 sS(e,t){let n=t.split(/[?#]/,1)[0];if(!n||n.startsWith("/")||n.includes("://"))return null;let r=Su(aa.normalize(aa.join(aa.dirname(e),n)));return r===".."||r.startsWith("../")?null:r}function aS(e){return{...e}}function bu(e){return e instanceof Error?e.message:String(e)}function io(e){let t=cS(e),n=t.descriptor.scriptSetup??t.descriptor.script;if(!n||n.src)return null;let r=ca(n.lang??null);return r?{body:n.content,startLine:Math.max(0,n.loc.start.line-1),language:r}:null}var xu=cn("ast-trees",{clearGroups:["whole-project","source-file"]});function be(e,t){if(Lt(t))return lS(e,t);let n=W(t);if(!n)return null;let r=T(e,t);return r?xu.get(e,t,r,()=>zr(n,r)):null}function lS(e,t){let n=T(e,t);return n?xu.get(e,t,n,()=>{let r=io(n);if(!r)return null;let i=`
12
- `.repeat(r.startLine)+r.body;return zr(r.language,i)}):null}function Yn(e,t){let n=uS(e,t);if(!n)return null;let r=Qn(n);return r?{calleeLeaf:r,memberAccess:dS(n),line:e.startPosition.row}:null}function uS(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 dS(e){switch(e.type){case"field_expression":case"member_expression":case"attribute":return!0;default:return!1}}function Qn(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?Qn(t):null}case"scoped_identifier":{let t=e.childForFieldName("name")??e.namedChild(e.namedChildCount-1);return t?Qn(t):null}case"super":case"self":case"this":return null;default:return null}}import{createHash as mS}from"crypto";import{readFileSync as pS}from"fs";import{dirname as Cu,join as vu}from"path";import fS from"better-sqlite3";var gS="evidence.db",oo=new WeakMap,hS=q("evidence-content-hash",{clearGroups:["whole-project","source-file"]}),yS=q("evidence-project-fingerprint",{clearGroups:["whole-project"]}),Zn="evidence-v1",la="version NOT LIKE 'evidence-%'";function er(e){return mS("sha256").update(e).digest("hex")}function X(e,t,n){return hS.get(e,t,()=>er(n))}function Kr(e){return yS.get(e,"current",()=>{try{let t=JSON.parse(pS(vu(Cu(e.config.dbPath),"meta.json"),"utf-8"));if(t.version!==2&&t.version!==3||t.status!=="complete"||t.fingerprint===void 0)return null;let n=Array.isArray(t.indexedLanguages)?[...t.indexedLanguages].sort():[];return er(JSON.stringify({fingerprint:t.fingerprint,indexedLanguages:n}))}catch(t){return ua("project fingerprint unavailable",t),null}})}function ua(e,t){process.env.SCIP_QUERY_DEBUG&&console.error(`evidence-cache: ${e}: ${t instanceof Error?t.message:String(t)}`)}function tr(e){if(oo.has(e))return oo.get(e)??null;let t=null;try{let n=new fS(vu(Cu(e.config.dbPath),gS));n.pragma("journal_mode = WAL"),n.pragma("busy_timeout = 5000"),n.pragma("synchronous = NORMAL"),n.exec(`
7
+ ${i}
8
+ ORDER BY relative_path`,...r).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 Ax(e){return/[*?]/.test(e)?e.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_"):`%${e}%`}function Ma(e,t){let n=Ax(t);return O(e,{like:n,includeIgnored:!1}).map(i=>({relativePath:i}))}import{extname as cd}from"path";var Mx={".rs":"rust",".ts":"typescript",".mts":"typescript",".cts":"typescript",".tsx":"tsx",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".pyi":"python",".java":"java",".kt":"kotlin",".kts":"kotlin",".scala":"scala",".sc":"scala",".rb":"ruby",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".hxx":"cpp",".cs":"csharp",".php":"php",".vb":"vb",".clj":"clojure",".cljs":"clojure",".cljc":"clojure"};function H(e){return Mx[cd(e).toLowerCase()]??null}function Ht(e){return cd(e).toLowerCase()===".vue"}var ld=[];function on(e){e.groups.length>0&&ld.push(e)}function $a(e,t){let n=new Set(t.groups);for(let i of ld)i.groups.some(r=>n.has(r))&&(t.file!==void 0&&i.clearFile?i.clearFile(e,t.file):i.clearAll(e))}function ud(){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:i}=ud(),r={get(o,s,a){let c=i(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 on({name:e,groups:t.clearGroups,clearAll:o=>r.invalidateAll(o),clearFile:(o,s)=>r.invalidate(o,s)}),r}function ie(e,t){let n=new WeakMap,i={get(r,o){let s=n.get(r);if(s)return s.value;let a=o();return n.set(r,{value:a}),a},invalidate(r){n.delete(r)},has(r){return n.has(r)}};return on({name:e,groups:t.clearGroups,clearAll:r=>i.invalidate(r)}),i}var $x={clearGroups:["whole-project","source-file"]};function sn(e){return wn(e,$x)}function wn(e,t){let{cache:n,ensure:i}=ud(),r={get(o,s,a,c){let l=i(o),d=l.get(s);if(d&&d.source===a)return d.value;let u=c();return l.set(s,{source:a,value:u}),u},invalidate(o,s){n.get(o)?.delete(s)},invalidateAll(o){n.delete(o)}};return on({name:e,groups:t.clearGroups,clearAll:o=>r.invalidateAll(o),clearFile:(o,s)=>r.invalidate(o,s)}),r}import{createRequire as jx}from"module";var $e=jx(import.meta.url),ko=null,dd=!1;function Ox(){if(dd)return null;if(ko)return ko;try{return ko=$e("tree-sitter"),ko}catch{return dd=!0,null}}var md=new Map,wo=new Set;function Bx(e){if(wo.has(e))return null;let t=md.get(e);if(t)return t;let n;try{switch(e){case"rust":n=$e("tree-sitter-rust");break;case"typescript":n=$e("tree-sitter-typescript").typescript;break;case"tsx":n=$e("tree-sitter-typescript").tsx;break;case"javascript":n=$e("tree-sitter-javascript");break;case"python":n=$e("tree-sitter-python");break;case"java":n=$e("tree-sitter-java");break;case"kotlin":n=$e("tree-sitter-kotlin");break;case"scala":n=$e("tree-sitter-scala");break;case"ruby":n=$e("tree-sitter-ruby");break;case"c":n=$e("tree-sitter-c");break;case"cpp":n=$e("tree-sitter-cpp");break;case"csharp":n=$e("tree-sitter-c-sharp");break;case"php":n=$e("tree-sitter-php").php;break;case"vb":{let i=$e("tree-sitter-vb-dotnet");n=i.language??i;break}case"clojure":return wo.add(e),null}}catch{return wo.add(e),null}return md.set(e,n),n}var pd=new Map;function Hx(e){let t=pd.get(e);if(t)return t;let n=Bx(e);if(!n)return null;let i=Ox();if(!i)return null;let r=new i;try{r.setLanguage(n)}catch{return wo.add(e),null}return pd.set(e,r),r}function Vx(e,t){return e.parse(i=>i>=t.length?null:t.slice(i,Math.min(t.length,i+16384)))}function dr(e,t){let n=Hx(e);if(!n)return null;try{return Vx(n,t)}catch{return null}}import{readFileSync as qx}from"fs";import{join as Ux}from"path";var zx=W("source-text",{clearGroups:["whole-project","source-file"]}),Wx=W("source-lines",{clearGroups:["whole-project","source-file"]});function M(e,t){let n=t.replace(/\\/g,"/");return zx.get(e,n,()=>{let i=Ux(e.config.projectRoot,n);try{return qx(i,"utf-8")}catch(r){if(Gx(r))return"";throw r}})}function Gx(e){return typeof e=="object"&&e!==null&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function Ye(e,t){let n=t.replace(/\\/g,"/");return Wx.get(e,n,()=>{let i=M(e,n);return i?i.split(`
9
+ `):[]})}var Kx=/^\s*(?:\/\/|#|\/\*+|\*)\s*scip-query[\s:-]*ignore(?:[\s:-]+(dead(?:-code)?|stale|wrapper|passthrough|drift|extract|similar))?\b/i;function mr(e){let t=Kx.exec(e);return t?t[1]??"":null}function Po(e,t,n){if(n<=0)return!1;let i=Ye(e,t);if(i.length===0)return!1;for(let r=n-1;r>=0&&r>=n-5;r-=1){let o=(i[r]??"").trim();if(o!==""){if(mr(o)!==null)return!0;if(!o.startsWith("//")&&!o.startsWith("*")&&!o.startsWith("/*")&&!o.startsWith("@")&&!o.startsWith("#"))return!1}}return!1}import{parse as eC}from"@vue/compiler-sfc";import{posix as ja}from"path";import{parse as Jx}from"@vue/compiler-sfc";var Xx=sn("vue-sfc-units");function yi(e,t){let n=hd(t),i=M(e,n);return Xx.get(e,n,i,()=>Qx(e,n,i))}function hd(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Oa(e){let t=e?.toLowerCase();return!t||t==="js"||t==="javascript"||t==="jsx"?"javascript":t==="ts"||t==="typescript"?"typescript":t==="tsx"?"tsx":null}function Pn(e){return!e||e.body.length===0?0:e.body.split(`
10
+ `).length}function Qx(e,t,n){let i={relativePath:t,template:null,scripts:[],styles:[],customBlocks:[],errors:[]};if(!n)return i;let r;try{r=Jx(n,{filename:t})}catch(s){return i.errors.push(gd(s)),i}i.errors.push(...r.errors.map(gd));let{descriptor:o}=r;return o.template&&(i.template=Io(e,t,"template",o.template)),o.script&&i.scripts.push(fd(e,t,o.script,!1)),o.scriptSetup&&i.scripts.push(fd(e,t,o.scriptSetup,!0)),i.styles=o.styles.map(s=>Io(e,t,"style",s)),i.customBlocks=o.customBlocks.map(s=>Io(e,t,"custom",s)),i.errors.push(...[i.template,...i.scripts,...i.styles,...i.customBlocks].flatMap(s=>s?.errors??[])),i}function fd(e,t,n,i){let r=Io(e,t,"script",n);return{...r,kind:"script",setup:i,astLanguage:Oa(r.lang)}}function Io(e,t,n,i){let r=Zx(i.attrs),o=typeof r.lang=="string"?r.lang:null,s=typeof r.src=="string"?r.src:typeof i.src=="string"?i.src:void 0;if(s){let c=Yx(t,s);if(!c)return{kind:n,ownerPath:t,sourcePath:t,external:!0,src:s,attrs:r,lang:o,body:"",startLine:0,endLine:0,errors:[`Could not resolve Vue ${n} block source: ${s}`]};let l=M(e,c),d=l?Math.max(0,l.split(`
11
+ `).length-1):0;return{kind:n,ownerPath:t,sourcePath:c,external:!0,src:s,attrs:r,lang:o,body:l,startLine:0,endLine:d,errors:l?[]:[`Vue ${n} block source not found: ${c}`]}}let a=Math.max(0,i.loc.start.line-1);return{kind:n,ownerPath:t,sourcePath:t,external:!1,attrs:r,lang:o,body:i.content,startLine:a,endLine:Math.max(a,i.loc.end.line-1),errors:[]}}function Yx(e,t){let n=t.split(/[?#]/,1)[0];if(!n||n.startsWith("/")||n.includes("://"))return null;let i=hd(ja.normalize(ja.join(ja.dirname(e),n)));return i===".."||i.startsWith("../")?null:i}function Zx(e){return{...e}}function gd(e){return e instanceof Error?e.message:String(e)}function Lo(e){let t=eC(e),n=t.descriptor.scriptSetup??t.descriptor.script;if(!n||n.src)return null;let i=Oa(n.lang??null);return i?{body:n.content,startLine:Math.max(0,n.loc.start.line-1),language:i}:null}var yd=wn("ast-trees",{clearGroups:["whole-project","source-file"]});function Pe(e,t){if(Ht(t))return tC(e,t);let n=H(t);if(!n)return null;let i=M(e,t);return i?yd.get(e,t,i,()=>dr(n,i)):null}function tC(e,t){let n=M(e,t);return n?yd.get(e,t,n,()=>{let i=Lo(n);if(!i)return null;let r=`
12
+ `.repeat(i.startLine)+i.body;return dr(i.language,r)}):null}function Si(e,t){let n=nC(e,t);if(!n)return null;let i=bi(n);return i?{calleeLeaf:i,memberAccess:iC(n),line:e.startPosition.row}:null}function nC(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 iC(e){switch(e.type){case"field_expression":case"member_expression":case"attribute":return!0;default:return!1}}function bi(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?bi(t):null}case"scoped_identifier":{let t=e.childForFieldName("name")??e.namedChild(e.namedChildCount-1);return t?bi(t):null}case"super":case"self":case"this":return null;default:return null}}import{createHash as rC}from"crypto";import{readFileSync as oC}from"fs";import{dirname as bd,join as Sd}from"path";import sC from"better-sqlite3";var aC="evidence.db",Eo=new WeakMap,cC=W("evidence-content-hash",{clearGroups:["whole-project","source-file"]}),lC=W("evidence-project-fingerprint",{clearGroups:["whole-project"]}),an="evidence-v1",Do="version NOT LIKE 'evidence-%'";function Vt(e){return rC("sha256").update(e).digest("hex")}function re(e,t,n){return cC.get(e,t,()=>Vt(n))}function In(e){return lC.get(e,"current",()=>{try{let t=JSON.parse(oC(Sd(bd(e.config.dbPath),"meta.json"),"utf-8"));if(t.version!==2&&t.version!==3||t.status!=="complete"||t.fingerprint===void 0)return null;let n=Array.isArray(t.indexedLanguages)?[...t.indexedLanguages].sort():[];return Vt(JSON.stringify({fingerprint:t.fingerprint,indexedLanguages:n}))}catch(t){return Ba("project fingerprint unavailable",t),null}})}function Ba(e,t){process.env.SCIP_QUERY_DEBUG&&console.error(`evidence-cache: ${e}: ${t instanceof Error?t.message:String(t)}`)}function cn(e){if(Eo.has(e))return Eo.get(e)??null;let t=null;try{let n=new sC(Sd(bd(e.config.dbPath),aC));n.pragma("journal_mode = WAL"),n.pragma("busy_timeout = 5000"),n.pragma("synchronous = NORMAL"),n.exec(`
13
13
  CREATE TABLE IF NOT EXISTS file_evidence (
14
14
  kind TEXT NOT NULL,
15
15
  relative_path TEXT NOT NULL,
@@ -18,6 +18,14 @@ import{program as ra}from"commander";import{realpathSync as jb}from"fs";import{f
18
18
  payload TEXT NOT NULL,
19
19
  PRIMARY KEY (kind, relative_path)
20
20
  );
21
+ CREATE TABLE IF NOT EXISTS project_evidence (
22
+ kind TEXT NOT NULL,
23
+ cache_key TEXT NOT NULL,
24
+ project_fingerprint TEXT NOT NULL,
25
+ version TEXT NOT NULL,
26
+ payload TEXT NOT NULL,
27
+ PRIMARY KEY (kind, cache_key)
28
+ );
21
29
  CREATE TABLE IF NOT EXISTS semantic_callees (
22
30
  relative_path TEXT NOT NULL,
23
31
  symbol TEXT NOT NULL,
@@ -36,28 +44,40 @@ import{program as ra}from"commander";import{realpathSync as jb}from"fs";import{f
36
44
  PRIMARY KEY (relative_path, symbol)
37
45
  );
38
46
  `),t={evidence:n,readFileEvidence:n.prepare("SELECT payload FROM file_evidence WHERE kind = ? AND relative_path = ? AND content_hash = ? AND version = ?"),readLegacyFileEvidence:n.prepare(`SELECT payload FROM file_evidence
39
- WHERE kind = ? AND relative_path = ? AND content_hash = ? AND ${la}
47
+ WHERE kind = ? AND relative_path = ? AND content_hash = ? AND ${Do}
48
+ ORDER BY version DESC
49
+ LIMIT 1`),writeFileEvidence:n.prepare("INSERT OR REPLACE INTO file_evidence (kind, relative_path, content_hash, version, payload) VALUES (?, ?, ?, ?, ?)"),readProjectEvidence:n.prepare("SELECT payload FROM project_evidence WHERE kind = ? AND cache_key = ? AND project_fingerprint = ? AND version = ?"),readLegacyProjectEvidence:n.prepare(`SELECT payload FROM project_evidence
50
+ WHERE kind = ? AND cache_key = ? AND project_fingerprint = ? AND ${Do}
40
51
  ORDER BY version DESC
41
- LIMIT 1`),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
52
+ LIMIT 1`),writeProjectEvidence:n.prepare("INSERT OR REPLACE INTO project_evidence (kind, cache_key, project_fingerprint, version, payload) VALUES (?, ?, ?, ?, ?)"),readCallees:n.prepare(`SELECT payload FROM semantic_callees
42
53
  WHERE relative_path = ? AND symbol = ? AND content_hash = ? AND deps_digest = ? AND version = ?`),readLegacyCallees:n.prepare(`SELECT payload FROM semantic_callees
43
- WHERE relative_path = ? AND symbol = ? AND content_hash = ? AND deps_digest = ? AND ${la}
54
+ WHERE relative_path = ? AND symbol = ? AND content_hash = ? AND deps_digest = ? AND ${Do}
44
55
  ORDER BY version DESC
45
56
  LIMIT 1`),writeCallees:n.prepare(`INSERT OR REPLACE INTO semantic_callees
46
57
  (relative_path, symbol, content_hash, deps_digest, version, payload) VALUES (?, ?, ?, ?, ?, ?)`),dropStaleCallees:n.prepare("DELETE FROM semantic_callees WHERE relative_path = ? AND content_hash != ?"),readReferences:n.prepare(`SELECT payload FROM semantic_references
47
58
  WHERE relative_path = ? AND symbol = ? AND project_fingerprint = ? AND version = ?`),readLegacyReferences:n.prepare(`SELECT payload FROM semantic_references
48
- WHERE relative_path = ? AND symbol = ? AND project_fingerprint = ? AND ${la}
59
+ WHERE relative_path = ? AND symbol = ? AND project_fingerprint = ? AND ${Do}
49
60
  ORDER BY version DESC
50
61
  LIMIT 1`),writeReferences:n.prepare(`INSERT OR REPLACE INTO semantic_references
51
- (relative_path, symbol, project_fingerprint, version, payload) VALUES (?, ?, ?, ?, ?)`),dropStaleReferences:n.prepare("DELETE FROM semantic_references WHERE project_fingerprint != ?")}}catch(n){ua("disabled (open failed)",n)}return oo.set(e,t),t}function nr(e,t,n){ua(`disabled (${t})`,n),oo.set(e,null)}function te(e,t,n,r){let i=tr(e);if(!i)return null;try{return(i.readFileEvidence.get(t,n,r,Zn)??i.readLegacyFileEvidence.get(t,n,r))?.payload??null}catch(o){return nr(e,"file_evidence read",o),null}}function ne(e,t,n,r,i){let o=tr(e);if(o)try{o.writeFileEvidence.run(t,n,r,Zn,i)}catch(s){nr(e,"file_evidence write",s)}}function Ru(e,t,n,r,i){let o=tr(e);if(!o)return null;try{return(o.readCallees.get(t,n,r,i,Zn)??o.readLegacyCallees.get(t,n,r,i))?.payload??null}catch(s){return nr(e,"semantic_callees read",s),null}}function ku(e,t,n,r){let i=tr(e);if(!i)return null;try{return(i.readReferences.get(t,n,r,Zn)??i.readLegacyReferences.get(t,n,r))?.payload??null}catch(o){return nr(e,"semantic_references read",o),null}}function wu(e,t){if(t.length===0)return;let n=tr(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,Zn,i.payload)}})()}catch(r){nr(e,"semantic_callees write",r)}}function Lu(e,t){if(t.length===0)return;let n=tr(e);if(n)try{n.evidence.transaction(()=>{let r=new Set;for(let i of t)r.has(i.projectFingerprint)||(r.add(i.projectFingerprint),n.dropStaleReferences.run(i.projectFingerprint)),n.writeReferences.run(i.relativePath,i.symbol,i.projectFingerprint,Zn,i.payload)})()}catch(r){nr(e,"semantic_references write",r)}}function Xr(e){return e.type==="comment"||e.type==="line_comment"||e.type==="block_comment"}var bS=new Set(["function_declaration","method_definition","method_signature","function_signature"]);function so(e,t){let n=xS(e,t);if(n)return{name:n.name,startLine:n.definitionNode.startPosition.row,endLine:n.definitionNode.endPosition.row,paramCount:Pu(n.functionNode),params:Iu(n.functionNode),paramsEndLine:Du(n.functionNode),isLiteralPassthrough:Nu(n.functionNode,t)};if(!SS(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:Pu(e),params:Iu(e),paramsEndLine:Du(e),isLiteralPassthrough:Nu(e,t)}:null}function Eu(e){return e.namedChildren.find(t=>t.type==="parameters"||t.type==="formal_parameters")}function Iu(e){let t=Eu(e);if(!t)return[];let n=[];for(let r of t.namedChildren){if(Xr(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 Du(e){let t=Eu(e);return t?t.endPosition.row:e.startPosition.row}function SS(e,t){return t==="rust"?e==="function_item"||e==="function_signature_item":t==="python"?e==="function_definition":t==="typescript"||t==="tsx"||t==="javascript"?bS.has(e):!1}function xS(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 Pu(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)Xr(r)||(n+=1);return n}function Nu(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=>!Xr(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=>!Xr(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(p=>p.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 CS=new Set(["identifier","type_identifier","field_identifier"]),vS=new Set(["identifier"]),RS=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]),kS=new Set(["rust","python"]),wS=/\{([^{}]*)\}/g,LS=/\b([A-Za-z_][\w]*)\b/g;function Tu(e,t){return IS(t).has(e.type)}function _u(e,t){return kS.has(t)&&e.type==="string_content"}function da(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 IS(e){return e==="rust"?CS:e==="python"?vS:RS}function Fu(e,t){let n=e.startPosition.row;for(let r of e.text.matchAll(wS)){let i=r[1]??"";for(let o of i.matchAll(LS))o[1]&&t(o[1],n)}}var DS=[/\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],PS=/^#!?\[\s*serde\s*\(/,NS=/^#!?\[\s*schemars\s*\(/,ES=/^#!?\[\s*validate\s*\(/,TS=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function Au(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=Qn(r);if(!i||!TS.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 $u(e,t){let n=PS.test(e),r=NS.test(e),i=ES.test(e);if(!(!n&&!r&&!i))for(let o of DS){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 Mu(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 _S=cn("source-facts",{clearGroups:["whole-project","source-file"]});function me(e,t){let n=T(e,t);if(!n)return null;let r=FS(t,n);return r?_S.get(e,t,n,()=>AS(e,t,r,n)):null}function FS(e,t){return Lt(e)?io(t)?.language??null:W(e)}function AS(e,t,n,r){let i=X(e,t,r),o=te(e,"source-facts",t,i);if(o){let c=MS(o);if(c&&c.language===n)return c}let s=be(e,t);if(!s)return null;let a=jS(s,n);return ne(e,"source-facts",t,i,$S(a)),a}function $S(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 MS(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:da(n),fileIdentifiers:new Set(n.keys()),rustAttrReferencedNames:new Set(t.rustAttrReferencedNames),crossLanguageDispatchNames:new Set(t.crossLanguageDispatchNames)}}catch{return null}}function ma(e,t,n,r){let i=me(e,t);return i?OS(i,n,r)?.isLiteralPassthrough??!0:!0}function OS(e,t,n){return e.callables.find(r=>r.startLine===t&&r.endLine===n)??null}function jS(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=so(l,t);u&&n.push(u);let d=Yn(l,t);d&&r.push(d),Au(l,t,o),t==="rust"&&(l.type==="attribute_item"||l.type==="inner_attribute_item")&&$u(l.text,i),Tu(l,t)&&a(l.text,l.startPosition.row),_u(l,t)&&Fu(l,a);for(let m of l.children)c(m)};return c(e.rootNode),{language:t,callables:n,callSites:r,typeContainerMap:Mu(e,t),identifierLineMap:s,identifiersByLine:da(s),fileIdentifiers:new Set(s.keys()),rustAttrReferencedNames:i,crossLanguageDispatchNames:o}}var Ou=new Set(["rust","typescript","tsx","javascript","python"]);function pa(e,t){let n=me(e,t);return!n||!Ou.has(n.language)?null:n.callables.map(r=>({name:r.name,startLine:r.startLine,endLine:r.endLine}))}function rr(e,t){let n=me(e,t);return!n||!Ou.has(n.language)?null:n.callSites}function fa(e,t){return me(e,t)?.typeContainerMap??new Map}import{ElementTypes as BS,NodeTypes as Bu,parse as HS}from"@vue/compiler-dom";import{parse as rV}from"@vue/compiler-sfc";function ao(e,t){return e.split(t).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}var VS=Ht("vue-template-facts"),qS=new Set(["component","keep-alive","slot","suspense","teleport","template","transition","transition-group"]),US=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"]),WS=new Set(["div","span","template"]),GS=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 Hu(e,t){let n=t.replace(/\\/g,"/"),r=T(e,n);return VS.get(e,n,r,()=>zS(n,ro(e,n).template))}function zS(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=HS(t.body,{comments:!1})}catch{return n}let i=new Set,o=s=>{s.trim()&&i.add(s)};return Vu(r.children,t.startLine,n,o),n.structuralTokens=[...i].sort(),n}function Vu(e,t,n,r){for(let i of e)i.type===Bu.ELEMENT&&(JS(i,t,n,r),Vu(i.children,t,n,r))}function JS(e,t,n,r){let i=nx(e.tag),o={tag:e.tag,normalized:i,kind:tx(e),startLine:ir(t,e.loc.start.line),endLine:ir(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),WS.has(e.tag)||r(`native:${e.tag}`));for(let s of e.props)KS(s,t,n,r)}function KS(e,t,n,r){if(e.type===Bu.ATTRIBUTE){let a=e.value?.content??null,c=ju("prop",e.name,a,t,e.loc.start.line,e.loc.end.line);n.props.push(c),r(`prop:${e.name}`);return}let i=QS(e),o=qu(e.exp),s=ju(XS(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&&YS(o,t,e.loc.start.line,n,r)}function ju(e,t,n,r,i,o){return{kind:e,name:t,value:n,startLine:ir(r,i),endLine:ir(r,o)}}function XS(e){switch(e){case"bind":case"model":return"prop";case"on":return"event";case"slot":return"slot";default:return"directive"}}function QS(e){let t=qu(e.arg);return t||e.name}function qu(e){if(!e)return null;let t=("content"in e&&typeof e.content=="string"?e.content:e.loc.source).trim();return t||null}function YS(e,t,n,r,i){for(let o of ZS(e)){let s={name:o,startLine:ir(t,n),endLine:ir(t,n)};r.expressionIdentifiers.push(s),i(`id:${o}`)}}function ZS(e){let t=new Set,n=ex(e),r=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,i;for(;i=r.exec(n);){let o=i[0];GS.has(o)||/^[A-Z_]+$/.test(o)||t.add(o)}return[...t].sort()}function ex(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 tx(e){let t=e.tag;return e.tagType===BS.COMPONENT?"component":qS.has(t)?"builtin":US.has(t)?"native":/^[A-Z]/.test(t)||t.includes("-")?"component":"native"}function nx(e){return ao(e,/[-_:]/)}function ir(e,t){return e+Math.max(0,t-1)}import{readdirSync as rx}from"fs";import{execFileSync as ix}from"child_process";import{extname as co,join as ox}from"path";var ga=[".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"],Uu=[".vue"],Wu=[".tsx",".jsx"],Gu=[".vue"],sx=[...Wu,...Gu],ax=new Set(Wu),cx=new Set(Gu),zu=new Set(ga.map(e=>e.toLowerCase())),lx=[...zu].sort().join(","),ha=new Set(["node_modules",".git","target","dist","build",".next",".nuxt",".cache",".turbo","out","coverage",".scipquery-cache","__pycache__",".venv","venv",".idea",".vscode"]);function Ne(e,t={}){let n=t.includeIndexed??!0,r=t.includeAuxiliary??!0,i=t.extensions?.map(c=>c.toLowerCase()),o=i?new Set(i):zu,s=i?[...o].sort().join(","):lx,a=`${n?"1":"0"}|${r?"1":"0"}|${s}`;return ux.get(e,a,()=>{let c=new Set;if(n)for(let l of O(e,{includeIgnored:!1}))o.has(co(l).toLowerCase())&&c.add(l);if(r)for(let l of dx(e.config.projectRoot,o))e.isIgnored(l)||n&&c.has(l)||c.add(l);return[...c].sort()})}function lo(e,t={}){let n=!1,r=!1;for(let i of Ne(e,{extensions:sx})){if(t.scope&&!i.includes(t.scope))continue;let o=co(i).toLowerCase();if(n||=ax.has(o),r||=cx.has(o),n&&r)break}return{react:n,vue:r}}var ux=q("source-files",{clearGroups:[]});function dx(e,t){return mx(e,t)??px(e,t)}function mx(e,t){try{let n=ix("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(`
52
- `)){let o=i.trim();o&&t.has(co(o).toLowerCase())&&r.add(o)}return r}catch{return null}}function px(e,t){let n=new Set,r=i=>{let o=i?ox(e,i):e,s;try{s=rx(o,{withFileTypes:!0})}catch{return}for(let a of s)if(!ha.has(a.name)){if(a.isDirectory()){r(i?`${i}/${a.name}`:a.name);continue}t.has(co(a.name).toLowerCase())&&n.add(i?`${i}/${a.name}`:a.name)}};return r(""),n}var fx=new Set(["ref","shallowRef","reactive","computed","watch","watchEffect"]),gx=new Set(["onBeforeMount","onMounted","onBeforeUpdate","onUpdated","onBeforeUnmount","onUnmounted","onActivated","onDeactivated","onErrorCaptured"]),hx=new Set(["axios","fetch","runRequest","useAsyncData","useFetch","useResource"]),yx=new Set(["defineEmits","defineExpose","defineModel","defineOptions","defineProps","withDefaults"]),bx=new Set(["catch","for","function","if","return","switch","while"]);function Ju(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+=ln(n),n.external&&(t.externalLineCount+=ln(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(...vx(n));let r=zr(n.astLanguage,n.body);r?xx(n,r.rootNode,t):Cx(n,t)}return Sx(t),t.externalScriptPaths=Xu(t.externalScriptPaths),t}function Sx(e){e.composables=or(e,"composable"),e.stores=or(e,"store"),e.reactivity=or(e,"reactivity"),e.lifecycle=or(e,"lifecycle"),e.requests=or(e,"request"),e.macros=or(e,"macro")}function or(e,t){return Xu(e.calls.filter(n=>n.categories.includes(t)).map(n=>n.name))}function xx(e,t,n){let r=new Set,i=new Set,o=s=>{let a=so(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=Yn(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:Ku(c.calleeLeaf),setup:e.setup}))}for(let l of s.children)o(l)};o(t)}function Cx(e,t){for(let n of e.body.matchAll(/\b([A-Za-z_$][\w$]*)\s*\(/g)){let r=n[1];!r||bx.has(r)||t.calls.push({name:r,sourcePath:e.sourcePath,line:e.startLine+uo(e.body,n.index??0),categories:Ku(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+uo(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+uo(e.body,n.index??0);t.functions.push({name:r,sourcePath:e.sourcePath,startLine:i,endLine:i,setup:e.setup})}}function vx(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+uo(e.body,n.index??0);for(let s of Rx(r))t.push({local:s,source:i,sourcePath:e.sourcePath,line:o,setup:e.setup})}return t}function Rx(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 Ku(e){let t=["call"];return/^use[A-Z0-9_]/.test(e)&&t.push("composable"),/^use[A-Z0-9_].*Store$/.test(e)&&t.push("store"),fx.has(e)&&t.push("reactivity"),gx.has(e)&&t.push("lifecycle"),hx.has(e)&&t.push("request"),yx.has(e)&&t.push("macro"),t}function uo(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 Xu(e){return[...new Set(e)].sort()}var kx=new Set(["in","key","of"]),wx=new Set(["computed","defineEmits","defineProps","reactive","ref","watch","watchEffect"]),Lx=Ht("vue-component-behavior-profiles");function sr(e,t={}){let n=Ne(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=>Ix(e,i)).filter(i=>(t.minTemplateTokens===void 0||i.templateTokens.size>=t.minTemplateTokens)&&(t.minBehaviorTokens===void 0||i.behaviorTokens.size>=t.minBehaviorTokens))}function Ix(e,t){let n=t.replace(/\\/g,"/"),r=T(e,n),i=Lx.get(e,n,r,()=>Dx(e,n,r));return Px(i)}function Dx(e,t,n){let r=ro(e,t),i=Hu(e,t),o=Ju(r),s=Tx(i),a=i.expressionIdentifiers.map(g=>g.name).filter(g=>!s.includes(g)).filter((g,y,h)=>h.indexOf(g)===y).sort(),c=i.componentTags.map(g=>g.normalized).filter((g,y,h)=>h.indexOf(g)===y).sort(),l=n?n.split(`
53
- `).length:0,u=ln(r.template),d=o.lineCount,m=r.styles.reduce((g,y)=>g+ln(y),0),p=r.customBlocks.reduce((g,y)=>g+ln(y),0);return{file:t,sfc:r,templateFacts:i,scriptFacts:o,templateTokens:new Set(i.structuralTokens),behaviorTokens:Ex(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:p}}function Px(e){let t=Nx(e.scriptFacts);return{...e,scriptFacts:t,templateTokens:new Set(e.templateTokens),behaviorTokens:new Set(e.behaviorTokens),templateBindingNames:[...e.templateBindingNames],templateLocalNames:[...e.templateLocalNames],componentNames:[...e.componentNames],externalScriptPaths:t.externalScriptPaths}}function Nx(e){return{...e,imports:e.imports.map(t=>({...t})),functions:e.functions.map(t=>({...t})),calls:e.calls.map(t=>({...t,categories:[...t.categories]})),composables:[...e.composables],stores:[...e.stores],reactivity:[...e.reactivity],lifecycle:[...e.lifecycle],requests:[...e.requests],macros:[...e.macros],externalScriptPaths:[...e.externalScriptPaths],unresolvedScripts:e.unresolvedScripts.map(t=>({...t}))}}function Ex(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(wx.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 Tx(e){let t=new Set;for(let n of e.directives)if(n.name==="for"&&n.value)for(let r of _x(n.value))t.add(r);for(let n of e.slots)if(n.value)for(let r of Qu(n.value))t.add(r);return[...t].sort()}function _x(e){let t=/^(.*?)\s+(?:in|of)\s+/.exec(e.trim());return t?Qu(t[1]??""):[]}function Qu(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let r=n[0];kx.has(r)||t.push(r)}return t}import{extname as Fx}from"path";function un(e){return typeof e=="object"&&e!==null}function Ee(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")?e:null}var Ax=[".tsx",".jsx"],Yu=new Set(["useActionState","useCallback","useContext","useDebugValue","useDeferredValue","useEffect","useId","useImperativeHandle","useInsertionEffect","useLayoutEffect","useMemo","useOptimistic","useReducer","useRef","useState","useSyncExternalStore","useTransition"]),$x=new Set(["useEffect","useInsertionEffect","useLayoutEffect"]),Mx=new Set(["useActionState","useOptimistic","useReducer","useRef","useState"]),Ox=new Set(["useLocation","useNavigate","useParams","useSearchParams","useTranslation"]),jx=new Set(["axios","fetch","gql","graphql","mutate","query","request","useMutation","useQuery","useSuspenseQuery"]),Bx=new Set(["add","apply","cancel","change","clear","close","create","delete","fetch","filter","handle","load","open","refresh","remove","render","reset","save","select","submit","toggle","update"]),Hx=new Set(["children","className","false","key","null","style","true","undefined"]),Vx=new Set(["aria-hidden","className","clipRule","d","fill","fillRule","height","role","stroke","strokeLinecap","strokeLinejoin","strokeWidth","style","viewBox","width","xmlns"]),qx=Ht("react-component-behavior-profiles");function ar(e,t={}){let n=Ne(e,{extensions:Ax}).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=>Ux(e,i)).filter(i=>(t.minJsxTokens===void 0||i.jsxTokens.size>=t.minJsxTokens)&&(t.minBehaviorTokens===void 0||i.behaviorTokens.size>=t.minBehaviorTokens))}function Ux(e,t){let n=t.replace(/\\/g,"/"),r=T(e,n);return qx.get(e,n,r,()=>Wx(e,n,r)).map(zx)}function Wx(e,t,n){let r=X(e,t,n),i=te(e,"react-component-behavior-profiles",t,r);if(i){let s=Kx(i);if(s)return s}let o=Gx(e,t);return ne(e,"react-component-behavior-profiles",t,r,Jx(o)),o}function Gx(e,t){let n=Qx(t);if(!n)return[];let r=be(e,t);if(!r)return[];let i=We(e,t).length;return Yx(r.rootNode,n).filter(s=>s.kind==="hook"||rd(s.bodyNode)).map(s=>{let a=rC(s.bodyNode),c=cC(s.bodyNode,n);return{file:t,name:s.name,kind:s.kind,startLine:s.node.startPosition.row,endLine:s.node.endPosition.row,loc:Math.max(1,s.node.endPosition.row-s.node.startPosition.row+1),fileLines:i,jsxTokens:a.tokens,behaviorTokens:c.tokens,componentNames:It(a.componentNames),nativeTags:It(a.nativeTags),propNames:It(a.propNames),eventNames:It(a.eventNames),hookNames:It(c.hookNames),requestNames:It(c.requestNames),stateNames:It(c.stateNames),effectNames:It(c.effectNames),handlerNames:It(c.handlerNames)}})}function zx(e){return{...e,jsxTokens:new Set(e.jsxTokens),behaviorTokens:new Set(e.behaviorTokens),componentNames:[...e.componentNames],nativeTags:[...e.nativeTags],propNames:[...e.propNames],eventNames:[...e.eventNames],hookNames:[...e.hookNames],requestNames:[...e.requestNames],stateNames:[...e.stateNames],effectNames:[...e.effectNames],handlerNames:[...e.handlerNames]}}function Jx(e){return JSON.stringify(e.map(t=>({...t,jsxTokens:[...t.jsxTokens],behaviorTokens:[...t.behaviorTokens]})))}function Kx(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=[];for(let r of t){let i=Xx(r);if(!i)return null;n.push(i)}return n}catch{return null}}function Xx(e){if(!un(e))return null;let{file:t,name:n,kind:r,startLine:i,endLine:o,loc:s,fileLines:a,jsxTokens:c,behaviorTokens:l,componentNames:u,nativeTags:d,propNames:m,eventNames:p,hookNames:g,requestNames:y,stateNames:h,effectNames:x,handlerNames:v}=e;if(typeof t!="string"||typeof n!="string"||r!=="component"&&r!=="hook"||!mo(i)||!mo(o)||!mo(s)||!mo(a))return null;let R={jsxTokens:Ee(c),behaviorTokens:Ee(l),componentNames:Ee(u),nativeTags:Ee(d),propNames:Ee(m),eventNames:Ee(p),hookNames:Ee(g),requestNames:Ee(y),stateNames:Ee(h),effectNames:Ee(x),handlerNames:Ee(v)};return Object.values(R).some(L=>L===null)?null:{file:t,name:n,kind:r,startLine:i,endLine:o,loc:s,fileLines:a,jsxTokens:new Set(R.jsxTokens),behaviorTokens:new Set(R.behaviorTokens),componentNames:R.componentNames,nativeTags:R.nativeTags,propNames:R.propNames,eventNames:R.eventNames,hookNames:R.hookNames,requestNames:R.requestNames,stateNames:R.stateNames,effectNames:R.effectNames,handlerNames:R.handlerNames}}function mo(e){return typeof e=="number"&&Number.isFinite(e)}function Qx(e){let t=Fx(e).toLowerCase();return t!==".tsx"&&t!==".jsx"?null:W(e)}function Yx(e,t){let n=[],r=new Set,i=o=>{let s=Zx(o);if(s&&!tC(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 Zx(e){if(e.type==="function_declaration"){let o=nd(e);return!o||!Zu(o)?null:{name:o,kind:ed(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=Qr(t);if(!r||!n||!Zu(r))return null;let i=eC(n);return i?{name:r,kind:ed(r),node:e,bodyNode:i}:null}function Zu(e){return/^[A-Z]/.test(e)||/^use[A-Z0-9_]/.test(e)}function ed(e){return/^use[A-Z0-9_]/.test(e)?"hook":"component"}function eC(e){if(e.type==="arrow_function"||e.type==="function_expression")return e;if(e.type!=="call_expression")return null;let t=nC(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 tC(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 nd(e){return Qr(e.childForFieldName("name")??e.namedChild(0))}function nC(e){let t=e.childForFieldName("function")??e.namedChild(0);return t?t.text.split(".").pop()??t.text:null}function rd(e){return e.type.startsWith("jsx_")?!0:e.namedChildren.some(rd)}function rC(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"?iC(r,t):r.type==="jsx_expression"?oC(r,t):r.type==="jsx_fragment"&&t.tokens.add("jsx:fragment");for(let i of r.namedChildren)n(i)};return n(e),t}function iC(e,t){let n=sC(e),r=!1;if(n){let i=td(n);r=pC(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=aC(i);if(!o)continue;let s=td(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 Vx.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 oC(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 fC(n))Hx.has(r)||t.tokens.add(`binding:${r}`)}function sC(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 aC(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 cC(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=Yn(i,t);o&&lC(o.calleeLeaf,n)}else if(i.type==="variable_declarator")dC(i,n);else if(i.type==="function_declaration"){let o=nd(i);o&&id(o,n)}for(let o of i.namedChildren)r(o)};return r(e),n}function lC(e,t){/^use[A-Z0-9_]/.test(e)&&(t.hookNames.add(e),!Yu.has(e)&&!Ox.has(e)&&t.tokens.add(`hook:${e}`)),Yu.has(e)&&t.tokens.add(`react-hook:${e}`),$x.has(e)&&(t.effectNames.add(e),t.tokens.add(`effect:${e}`)),Mx.has(e)&&t.tokens.add(`state-hook:${e}`),uC(e)&&(t.requestNames.add(e),t.tokens.add(`request:${e}`))}function uC(e){if(jx.has(e))return!0;let t=/^use([A-Z0-9_].*)$/.exec(e)?.[1];return t?/(Query|Mutation|Fetch|Resource)$/.test(t):!1}function dC(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=>Qr(a)),s=Qr(o);s&&(t.stateNames.add(s),t.tokens.add(`state:${s}`))}let i=Qr(n);i&&id(i,t)}function id(e,t){let n=mC(e);!n||!Bx.has(n)||(t.handlerNames.add(e),t.tokens.add(`handler:${e}`),t.tokens.add(`handler-verb:${n}`))}function mC(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 pC(e){return/^[A-Z]/.test(e)||e.includes(".")}function td(e){return e.replace(/^this\./,"").replace(/\$/g,".")}function Qr(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 fC(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 It(e){return[...e].sort()}function dn(e,t,n={}){let r=me(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 gC={"/":"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=hC(i);return{scheme:n,manager:r,packageName:o,version:s,descriptors:c,raw:e}}function pt(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 hC(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||od(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&&!od(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=gC[i];o&&t.push({name:r,suffix:o}),n+=1}}return t}function od(e){return e==="/"||e==="#"||e==="."||e==="("||e==="["||e===":"||e==="!"}function b(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=yC(i);o&&r.push(o)}return r.join(":")}function yC(e){let t=e.suffix==="namespace"?bC(e.name):e.name;return t?e.suffix==="method"?`${t}()`:t:""}function bC(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 re(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 ie(e){return e.endsWith("().")||re(e)==="method"}function oe(e){let t=re(e);return t==="method"||t==="term"}function Vt(e){return re(e)==="namespace"}var SC=/^rust-analyzer\b.*[\s/]impl#\[[^\]]+\]\[[^\]]+\]/;function po(e){return SC.test(e)}var xC=new Set(["test","tests","_tests"]);function cr(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&&xC.has(r.name))return!0}return!1}function sd(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 ad(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 lr(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
62
+ (relative_path, symbol, project_fingerprint, version, payload) VALUES (?, ?, ?, ?, ?)`),dropStaleReferences:n.prepare("DELETE FROM semantic_references WHERE project_fingerprint != ?")}}catch(n){Ba("disabled (open failed)",n)}return Eo.set(e,t),t}function ln(e,t,n){Ba(`disabled (${t})`,n),Eo.set(e,null)}function xd(e,t,n,i){let r=cn(e);if(!r)return null;try{return(r.readFileEvidence.get(t,n,i,an)??r.readLegacyFileEvidence.get(t,n,i))?.payload??null}catch(o){return ln(e,"file_evidence read",o),null}}function Cd(e,t,n,i,r){let o=cn(e);if(o)try{o.writeFileEvidence.run(t,n,i,an,r)}catch(s){ln(e,"file_evidence write",s)}}function vd(e,t,n,i){let r=cn(e);if(!r)return null;try{return(r.readProjectEvidence.get(t,n,i,an)??r.readLegacyProjectEvidence.get(t,n,i))?.payload??null}catch(o){return ln(e,"project_evidence read",o),null}}function Rd(e,t,n,i,r){let o=cn(e);if(o)try{o.writeProjectEvidence.run(t,n,i,an,r)}catch(s){ln(e,"project_evidence write",s)}}function kd(e,t,n,i,r){let o=cn(e);if(!o)return null;try{return(o.readCallees.get(t,n,i,r,an)??o.readLegacyCallees.get(t,n,i,r))?.payload??null}catch(s){return ln(e,"semantic_callees read",s),null}}function wd(e,t,n,i){let r=cn(e);if(!r)return null;try{return(r.readReferences.get(t,n,i,an)??r.readLegacyReferences.get(t,n,i))?.payload??null}catch(o){return ln(e,"semantic_references read",o),null}}function Pd(e,t){if(t.length===0)return;let n=cn(e);if(n)try{n.evidence.transaction(()=>{let i=new Set;for(let r of t){let o=`${r.relativePath}\0${r.contentHash}`;i.has(o)||(i.add(o),n.dropStaleCallees.run(r.relativePath,r.contentHash)),n.writeCallees.run(r.relativePath,r.symbol,r.contentHash,r.depsDigest,an,r.payload)}})()}catch(i){ln(e,"semantic_callees write",i)}}function Id(e,t){if(t.length===0)return;let n=cn(e);if(n)try{n.evidence.transaction(()=>{let i=new Set;for(let r of t)i.has(r.projectFingerprint)||(i.add(r.projectFingerprint),n.dropStaleReferences.run(r.projectFingerprint)),n.writeReferences.run(r.relativePath,r.symbol,r.projectFingerprint,an,r.payload)})()}catch(i){ln(e,"semantic_references write",i)}}function pe(e){return{kind:e.kind,read(t,n,i){let r=xd(t,e.kind,n,i);if(r===null)return null;try{return e.deserialize(r)}catch{return null}},write(t,n,i,r){Cd(t,e.kind,n,i,e.serialize(r))}}}function Ld(e){return{kind:e.kind,read(t,n,i){let r=vd(t,e.kind,n,i);if(r===null)return null;try{return e.deserialize(r)}catch{return null}},write(t,n,i,r){Rd(t,e.kind,n,i,e.serialize(r))}}}function pr(e){return e.type==="comment"||e.type==="line_comment"||e.type==="block_comment"}var uC=new Set(["function_declaration","method_definition","method_signature","function_signature"]);function No(e,t){let n=mC(e,t);if(n)return{name:n.name,startLine:n.definitionNode.startPosition.row,endLine:n.definitionNode.endPosition.row,paramCount:Nd(n.functionNode),params:Dd(n.functionNode),paramsEndLine:Ed(n.functionNode),isLiteralPassthrough:Fd(n.functionNode,t)};if(!dC(e.type,t))return null;let i=e.childForFieldName("name")??e.namedChildren.find(r=>r.type==="identifier"||r.type==="property_identifier");return i?{name:i.text,startLine:e.startPosition.row,endLine:e.endPosition.row,paramCount:Nd(e),params:Dd(e),paramsEndLine:Ed(e),isLiteralPassthrough:Fd(e,t)}:null}function Td(e){return e.namedChildren.find(t=>t.type==="parameters"||t.type==="formal_parameters")}function Dd(e){let t=Td(e);if(!t)return[];let n=[];for(let i of t.namedChildren){if(pr(i))continue;if(i.type==="identifier"){n.push({name:i.text,simple:!0});continue}let r=i.namedChildren.some(a=>a.type.endsWith("_modifier"))||/^\s*(?:public|private|protected|readonly|override)\b/.test(i.text),o=i.childForFieldName("pattern");if(!r&&o&&o.type==="identifier"){n.push({name:o.text,simple:!0});continue}let s=i.namedChildren.find(a=>a.type==="identifier");n.push({name:o?.type==="identifier"?o.text:s?.text??"",simple:!1})}return n}function Ed(e){let t=Td(e);return t?t.endPosition.row:e.startPosition.row}function dC(e,t){return t==="rust"?e==="function_item"||e==="function_signature_item":t==="python"?e==="function_definition":t==="typescript"||t==="tsx"||t==="javascript"?uC.has(e):!1}function mC(e,t){if(t!=="typescript"&&t!=="tsx"&&t!=="javascript")return null;if(e.type==="variable_declarator"){let n=e.childForFieldName("name")??e.namedChild(0),i=e.childForFieldName("value")??e.namedChild(1);return!n||!i||i.type!=="arrow_function"&&i.type!=="function_expression"?null:{name:n.text,definitionNode:e,functionNode:i}}if(e.type==="public_field_definition"){let n=e.childForFieldName("name")??e.namedChild(0),i=e.childForFieldName("value")??e.namedChild(1);return!n||!i||i.type!=="arrow_function"&&i.type!=="function_expression"?null:{name:n.text,definitionNode:e,functionNode:i}}return null}function Nd(e){let t=e.namedChildren.find(i=>i.type==="parameters"||i.type==="formal_parameters");if(!t)return 0;let n=0;for(let i of t.namedChildren)pr(i)||(n+=1);return n}function Fd(e,t){let n=e.namedChildren.find(u=>u.type==="block"||u.type==="statement_block");if(!n)return!1;let i=n.namedChildren.filter(u=>!pr(u));if(i.length!==1)return!1;let r=i[0],o=null;if(r.type==="return_statement"||r.type==="expression_statement"?o=r.namedChild(0)??null:t==="rust"&&(r.type==="call_expression"||r.type==="macro_invocation")&&(o=r),!o)return!1;let s=t==="python"?"call":"call_expression";if(o.type!==s)return!1;let a=o.namedChildren.find(u=>u.type==="arguments"||u.type==="argument_list");if(!a)return!1;let c=a.namedChildren.filter(u=>!pr(u)),l=e.namedChildren.find(u=>u.type==="parameters"||u.type==="formal_parameters");if(!l)return!1;let d=[];for(let u of l.namedChildren){if(u.type==="identifier"){d.push(u.text);continue}let m=u.namedChildren.find(p=>p.type==="identifier");m&&d.push(m.text)}if(c.length!==d.length)return!1;for(let u=0;u<d.length;u+=1){let m=c[u];if(m.type!=="identifier"||m.text!==d[u])return!1}return!0}var pC=new Set(["identifier","type_identifier","field_identifier"]),fC=new Set(["identifier"]),gC=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]),hC=new Set(["rust","python"]),yC=/\{([^{}]*)\}/g,bC=/\b([A-Za-z_][\w]*)\b/g;function _d(e,t){return SC(t).has(e.type)}function Ad(e,t){return hC.has(t)&&e.type==="string_content"}function Ha(e){let t=0;for(let i of e.values()){let r=i[i.length-1];r!==void 0&&r>t&&(t=r)}let n=new Array(t+1);for(let i=0;i<=t;i+=1)n[i]=new Set;for(let[i,r]of e)for(let o of r)n[o].add(i);return n}function SC(e){return e==="rust"?pC:e==="python"?fC:gC}function Md(e,t){let n=e.startPosition.row;for(let i of e.text.matchAll(yC)){let r=i[1]??"";for(let o of r.matchAll(bC))o[1]&&t(o[1],n)}}var xC=[/\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],CC=/^#!?\[\s*serde\s*\(/,vC=/^#!?\[\s*schemars\s*\(/,RC=/^#!?\[\s*validate\s*\(/,kC=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function $d(e,t,n){if(t!=="typescript"&&t!=="tsx"&&t!=="javascript"||e.type!=="call_expression")return;let i=e.childForFieldName("function")??e.namedChild(0);if(!i)return;let r=bi(i);if(!r||!kC.has(r))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 jd(e,t){let n=CC.test(e),i=vC.test(e),r=RC.test(e);if(!(!n&&!i&&!r))for(let o of xC){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 Od(e,t){let n=new Map,i=(s,a)=>{if(s===a)return;let c=n.get(s);c||(c=new Set,n.set(s,c)),c.add(a)},r=t==="python"?new Set(["identifier"]):new Set(["type_identifier"]),o=(s,a)=>{let c=l=>{r.has(l.type)&&l.text!==a&&i(l.text,a);for(let d of l.children)c(d)};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 d of l.descendantsOfType("identifier"))d.text!==a&&i(d.text,a)}else for(let s of e.rootNode.descendantsOfType(["interface_declaration","type_alias_declaration","class_declaration"])){let a=s.namedChildren.find(c=>c.type==="type_identifier")?.text;a&&o(s,a)}return n}var wC=new Map([["defn","function"],["defn-","function"],["defmacro","macro"],["defmacro-","macro"],["defmethod","method"]]),Va=new Set(["catch","comment","def","defprotocol","defrecord","deftype","defmethod","defmacro","defmacro-","defn","defn-","do","doseq","dotimes","fn","for","if","let","loop","ns","quote","recur","throw","try","extend-protocol","extend-type","when","when-let","when-not"]);function Bd(e){let t=[],n=[],i=[],r=new Map,o=[],s=0,a=0,c=(l,d)=>{let u=r.get(l);if(!u){r.set(l,[d]);return}u[u.length-1]!==d&&u.push(d)};for(;a<e.length;){let l=e[a];if(l===`
63
+ `){s+=1,a+=1;continue}if(/\s|,/.test(l)){a+=1;continue}if(l===";"){a=FC(e,a);continue}if(l==='"'){let f=TC(e,a,s);s=f.line,a=f.index;continue}if(l==="("||l==="["||l==="{"){o.push({kind:l,startLine:s,endLine:s,headTokens:[],tokens:[],children:[]}),a+=1;continue}if(l===")"||l==="]"||l==="}"){let f=o.pop();f&&(f.endLine=s,PC(f,{callables:t,callSites:n,clojureMembers:i,recordIdentifier:c}),o[o.length-1]?.children.push(f)),a+=1;continue}if(_C(l)){a+=1;continue}let d=s,u=a;for(;a<e.length&&!AC(e[a]);)a+=1;let m=e.slice(u,a);if(!m)continue;let p={text:m,line:d};IC(o[o.length-1],p),c(Ze(m),d)}return{language:"clojure",callables:t,callSites:n,clojureMembers:i,typeContainerMap:new Map,identifierLineMap:r,identifiersByLine:MC(r),fileIdentifiers:new Set(r.keys()),rustAttrReferencedNames:new Set,crossLanguageDispatchNames:new Set}}function PC(e,t){if(e.kind!=="("||e.headTokens.length===0)return;let n=e.headTokens[0],i=Ze(n.text),r=wC.get(n.text);if(r){let s=e.headTokens[1];if(s){let a=Ze(s.text);t.recordIdentifier(a,s.line),t.callables.push({name:a,startLine:e.startLine,endLine:e.endLine,paramCount:0,params:[],paramsEndLine:s.line,isLiteralPassthrough:!1,clojureKind:r})}}if(LC(e,t),!i||Va.has(n.text)||Va.has(i)||i.startsWith(":"))return;let o=NC(n.text);t.callSites.push({calleeLeaf:o.leaf,calleeQualifier:o.qualifier,calleeText:o.text,memberAccess:!1,line:n.line})}function IC(e,t){e&&(e.headTokens.length<2&&e.headTokens.push(t),e.tokens.length<200&&e.tokens.push(t))}function LC(e,t){let n=Ze(e.tokens[0]?.text??"");if(n==="defprotocol"){let i=Ze(e.tokens[1]?.text??"");if(!i)return;for(let r of Fo(e))fr(t,i,"protocol",r,"protocol-method");return}if(n==="defrecord"||n==="deftype"){let i=Ze(e.tokens[1]?.text??"");if(!i)return;let r=n==="defrecord"?"record":"type",o=n==="defrecord"?"record-method":"type-method";for(let s of Fo(e))fr(t,i,r,s,o);return}if(n==="extend-type"){let i=Ze(e.tokens[1]?.text??"");if(!i)return;for(let r of Fo(e))fr(t,i,"extension",r,"extension-method");return}if(n==="extend-protocol"){let i=Ze(e.tokens[1]?.text??"");for(let r of Fo(e)){i&&fr(t,i,"extension",r,"extension-method");let o=EC(e,r.startLine);o&&o!==i&&fr(t,o,"extension",r,"extension-method")}}}function Fo(e){return e.children.filter(DC)}function DC(e){if(e.kind!=="(")return!1;let t=Ze(e.tokens[0]?.text??"");return!!(t&&!Va.has(t)&&!t.startsWith(":"))}function fr(e,t,n,i,r){let o=i.tokens[0],s=Ze(o?.text??"");!o||!s||(e.recordIdentifier(s,o.line),e.clojureMembers.push({ownerName:t,ownerKind:n,memberName:s,memberKind:r,startLine:i.startLine,endLine:i.endLine}))}function EC(e,t){let n=null;for(let i=2;i<e.tokens.length;i+=1){let r=e.tokens[i];if(r.line>t)break;let o=Ze(r.text);o&&!o.startsWith(":")&&(n=o)}return n}function Ze(e){return e.replace(/^#?['`~@]+/,"").split("/").pop()?.replace(/^\./,"")??""}function NC(e){let t=e.replace(/^#?['`~@]+/,""),n=t.lastIndexOf("/"),i=Ze(t);if(n<=0)return{leaf:i,text:t};let r=t.slice(0,n);return{leaf:i,qualifier:r,text:t}}function FC(e,t){let n=t;for(;n<e.length&&e[n]!==`
64
+ `;)n+=1;return n}function TC(e,t,n){let i=t+1,r=n;for(;i<e.length;){let o=e[i];if(o==="\\"){i+=2;continue}if(o===`
65
+ `&&(r+=1),i+=1,o==='"')break}return{index:i,line:r}}function _C(e){return e==="'"||e==="`"||e==="~"||e==="@"||e==="^"||e==="#"}function AC(e){return/\s|,/.test(e)||e==="("||e===")"||e==="["||e==="]"||e==="{"||e==="}"}function MC(e){let t=[];for(let[n,i]of e)for(let r of i)t[r]??=new Set,t[r].add(n);return t}var $C=wn("source-facts",{clearGroups:["whole-project","source-file"]}),qa=pe({kind:"source-facts",serialize:BC,deserialize:HC});function X(e,t){let n=M(e,t);if(!n)return null;let i=jC(t,n);return i?$C.get(e,t,n,()=>OC(e,t,i,n)):null}function jC(e,t){return Ht(e)?Lo(t)?.language??null:H(e)}function OC(e,t,n,i){let r=re(e,t,i),o=qa.read(e,t,r);if(o&&o.language===n)return o;if(n==="clojure"){let c=Bd(i);return qa.write(e,t,r,c),c}let s=Pe(e,t);if(!s)return null;let a=qC(s,n);return qa.write(e,t,r,a),a}function BC(e){let t={language:e.language,callables:e.callables,callSites:e.callSites,clojureMembers:e.clojureMembers,typeContainerMap:[...e.typeContainerMap.entries()].map(([n,i])=>[n,[...i]]),identifierLineMap:[...e.identifierLineMap.entries()],rustAttrReferencedNames:[...e.rustAttrReferencedNames],crossLanguageDispatchNames:[...e.crossLanguageDispatchNames]};return JSON.stringify(t)}function HC(e){try{let t=JSON.parse(e);if(t.language==="clojure"&&(t.clojureMembers===void 0||t.callSites.some(i=>i.calleeText===void 0)))return null;let n=new Map(t.identifierLineMap);return{language:t.language,callables:t.callables,callSites:t.callSites,clojureMembers:t.clojureMembers??[],typeContainerMap:new Map(t.typeContainerMap.map(([i,r])=>[i,new Set(r)])),identifierLineMap:n,identifiersByLine:Ha(n),fileIdentifiers:new Set(n.keys()),rustAttrReferencedNames:new Set(t.rustAttrReferencedNames),crossLanguageDispatchNames:new Set(t.crossLanguageDispatchNames)}}catch{return null}}function Ua(e,t,n,i){let r=X(e,t);return r?VC(r,n,i)?.isLiteralPassthrough??!0:!0}function Ln(e,t){return t.relativePath.includes(".clj-kondo/hooks/")?!0:X(e,t.relativePath)?.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine)?.clojureKind==="macro"}function VC(e,t,n){return e.callables.find(i=>i.startLine===t&&i.endLine===n)??null}function qC(e,t){let n=[],i=[],r=new Set,o=new Set,s=new Map,a=(l,d)=>{let u=s.get(l);if(!u){s.set(l,[d]);return}u[u.length-1]!==d&&u.push(d)},c=l=>{let d=No(l,t);d&&n.push(d);let u=Si(l,t);u&&i.push(u),$d(l,t,o),t==="rust"&&(l.type==="attribute_item"||l.type==="inner_attribute_item")&&jd(l.text,r),_d(l,t)&&a(l.text,l.startPosition.row),Ad(l,t)&&Md(l,a);for(let m of l.children)c(m)};return c(e.rootNode),{language:t,callables:n,callSites:i,clojureMembers:[],typeContainerMap:Od(e,t),identifierLineMap:s,identifiersByLine:Ha(s),fileIdentifiers:new Set(s.keys()),rustAttrReferencedNames:r,crossLanguageDispatchNames:o}}var Hd=new Set(["rust","typescript","tsx","javascript","python","clojure"]);function za(e,t){let n=X(e,t);return!n||!Hd.has(n.language)?null:n.callables.map(i=>({name:i.name,startLine:i.startLine,endLine:i.endLine}))}function xi(e,t){let n=X(e,t);return!n||!Hd.has(n.language)?null:n.callSites}function Wa(e,t){return X(e,t)?.typeContainerMap??new Map}import{ElementTypes as UC,NodeTypes as qd,parse as zC}from"@vue/compiler-dom";import{parse as Jz}from"@vue/compiler-sfc";function To(e,t){return e.split(t).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}var WC=sn("vue-template-facts"),GC=new Set(["component","keep-alive","slot","suspense","teleport","template","transition","transition-group"]),KC=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"]),JC=new Set(["div","span","template"]),XC=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 _o(e,t){let n=t.replace(/\\/g,"/"),i=M(e,n);return WC.get(e,n,i,()=>QC(n,yi(e,n).template))}function QC(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 i;try{i=zC(t.body,{comments:!1})}catch{return n}let r=new Set,o=s=>{s.trim()&&r.add(s)};return Ud(i.children,t.startLine,n,o),n.structuralTokens=[...r].sort(),n}function Ud(e,t,n,i){for(let r of e)r.type===qd.ELEMENT&&(YC(r,t,n,i),Ud(r.children,t,n,i))}function YC(e,t,n,i){let r=sv(e.tag),o={tag:e.tag,normalized:r,kind:ov(e),startLine:Ci(t,e.loc.start.line),endLine:Ci(t,e.loc.end.line)};o.kind==="component"?(n.componentTags.push(o),i(`component:${r}`)):o.kind==="builtin"?(n.builtinTags.push(o),i(`builtin:${r}`)):(n.nativeTags.push(o),JC.has(e.tag)||i(`native:${e.tag}`));for(let s of e.props)ZC(s,t,n,i)}function ZC(e,t,n,i){if(e.type===qd.ATTRIBUTE){let a=e.value?.content??null,c=Vd("prop",e.name,a,t,e.loc.start.line,e.loc.end.line);n.props.push(c),i(`prop:${e.name}`);return}let r=tv(e),o=zd(e.exp),s=Vd(ev(e.name),r,o,t,e.loc.start.line,e.loc.end.line);switch(s.kind){case"prop":n.props.push(s),i(`prop:${r}`);break;case"event":n.events.push(s),i(`event:${r}`);break;case"slot":n.slots.push(s),i(`slot:${r}`);break;case"directive":n.directives.push(s),i(`directive:${r}`);break}o&&nv(o,t,e.loc.start.line,n,i)}function Vd(e,t,n,i,r,o){return{kind:e,name:t,value:n,startLine:Ci(i,r),endLine:Ci(i,o)}}function ev(e){switch(e){case"bind":case"model":return"prop";case"on":return"event";case"slot":return"slot";default:return"directive"}}function tv(e){let t=zd(e.arg);return t||e.name}function zd(e){if(!e)return null;let t=("content"in e&&typeof e.content=="string"?e.content:e.loc.source).trim();return t||null}function nv(e,t,n,i,r){for(let o of iv(e)){let s={name:o,startLine:Ci(t,n),endLine:Ci(t,n)};i.expressionIdentifiers.push(s),r(`id:${o}`)}}function iv(e){let t=new Set,n=rv(e),i=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,r;for(;r=i.exec(n);){let o=r[0];XC.has(o)||/^[A-Z_]+$/.test(o)||t.add(o)}return[...t].sort()}function rv(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 ov(e){let t=e.tag;return e.tagType===UC.COMPONENT?"component":GC.has(t)?"builtin":KC.has(t)?"native":/^[A-Z]/.test(t)||t.includes("-")?"component":"native"}function sv(e){return To(e,/[-_:]/)}function Ci(e,t){return e+Math.max(0,t-1)}import{readdirSync as av}from"fs";import{execFileSync as cv}from"child_process";import{extname as Ao,join as lv}from"path";var Ga=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".rs",".py",".pyi",".java",".kt",".kts",".scala",".sc",".clj",".cljs",".cljc",".rb",".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx",".cs",".vb",".php",".dart"],Wd=[".vue"],Gd=[".tsx",".jsx"],Kd=[".vue"],uv=[...Gd,...Kd],dv=new Set(Gd),mv=new Set(Kd),Jd=new Set(Ga.map(e=>e.toLowerCase())),pv=[...Jd].sort().join(","),Mo=new Set(["node_modules",".git","target","dist","build",".next",".nuxt",".cache",".turbo",".nbb",".cpcache",".shadow-cljs","out","coverage",".scipquery-cache","__pycache__",".venv","venv",".idea",".vscode"]);function et(e,t={}){let n=t.includeIndexed??!0,i=t.includeAuxiliary??!0,r=t.extensions?.map(c=>c.toLowerCase()),o=r?new Set(r):Jd,s=r?[...o].sort().join(","):pv,a=`${n?"1":"0"}|${i?"1":"0"}|${s}`;return fv.get(e,a,()=>{let c=new Set;if(n)for(let l of O(e,{includeIgnored:!1}))o.has(Ao(l).toLowerCase())&&c.add(l);if(i)for(let l of gv(e.config.projectRoot,o))e.isIgnored(l)||n&&c.has(l)||c.add(l);return[...c].sort()})}function $o(e,t={}){let n=!1,i=!1;for(let r of et(e,{extensions:uv})){if(t.scope&&!r.includes(t.scope))continue;let o=Ao(r).toLowerCase();if(n||=dv.has(o),i||=mv.has(o),n&&i)break}return{react:n,vue:i}}var fv=W("source-files",{clearGroups:[]});function gv(e,t){return hv(e,t)??bv(e,t)}function hv(e,t){try{let n=cv("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e,encoding:"utf-8",timeout:1e4,stdio:["ignore","pipe","ignore"]}),i=new Set;for(let r of n.split(`
66
+ `)){let o=r.trim();o&&(yv(o)||t.has(Ao(o).toLowerCase())&&i.add(o))}return i}catch{return null}}function yv(e){return e.split("/").some(t=>Mo.has(t))}function bv(e,t){let n=new Set,i=r=>{let o=r?lv(e,r):e,s;try{s=av(o,{withFileTypes:!0})}catch{return}for(let a of s)if(!Mo.has(a.name)){if(a.isDirectory()){i(r?`${r}/${a.name}`:a.name);continue}t.has(Ao(a.name).toLowerCase())&&n.add(r?`${r}/${a.name}`:a.name)}};return i(""),n}var Sv=new Set(["ref","shallowRef","reactive","computed","watch","watchEffect"]),xv=new Set(["onBeforeMount","onMounted","onBeforeUpdate","onUpdated","onBeforeUnmount","onUnmounted","onActivated","onDeactivated","onErrorCaptured"]),Cv=new Set(["axios","fetch","runRequest","useAsyncData","useFetch","useResource"]),vv=new Set(["defineEmits","defineExpose","defineModel","defineOptions","defineProps","withDefaults"]),Rv=new Set(["catch","for","function","if","return","switch","while"]);function Oo(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+=Pn(n),n.external&&(t.externalLineCount+=Pn(n),t.externalScriptPaths.push(n.sourcePath));for(let r of n.errors)t.unresolvedScripts.push({sourcePath:n.sourcePath,reason:r});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(...Iv(n));let i=dr(n.astLanguage,n.body);i?wv(n,i.rootNode,t):Pv(n,t)}return kv(t),t.externalScriptPaths=Qd(t.externalScriptPaths),t}function kv(e){e.composables=vi(e,"composable"),e.stores=vi(e,"store"),e.reactivity=vi(e,"reactivity"),e.lifecycle=vi(e,"lifecycle"),e.requests=vi(e,"request"),e.macros=vi(e,"macro")}function vi(e,t){return Qd(e.calls.filter(n=>n.categories.includes(t)).map(n=>n.name))}function wv(e,t,n){let i=new Set,r=new Set,o=s=>{let a=No(s,e.astLanguage);if(a){let l=`${a.name}:${a.startLine}:${a.endLine}`;r.has(l)||(r.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=Si(s,e.astLanguage);if(c){let l=`${c.calleeLeaf}:${c.line}`;i.has(l)||(i.add(l),n.calls.push({name:c.calleeLeaf,sourcePath:e.sourcePath,line:e.startLine+c.line,categories:Xd(c.calleeLeaf),setup:e.setup}))}for(let l of s.children)o(l)};o(t)}function Pv(e,t){for(let n of e.body.matchAll(/\b([A-Za-z_$][\w$]*)\s*\(/g)){let i=n[1];!i||Rv.has(i)||t.calls.push({name:i,sourcePath:e.sourcePath,line:e.startLine+jo(e.body,n.index??0),categories:Xd(i),setup:e.setup})}for(let n of e.body.matchAll(/\bfunction\s+([A-Za-z_$][\w$]*)\b/g)){let i=n[1];if(!i)continue;let r=e.startLine+jo(e.body,n.index??0);t.functions.push({name:i,sourcePath:e.sourcePath,startLine:r,endLine:r,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 i=n[1];if(!i)continue;let r=e.startLine+jo(e.body,n.index??0);t.functions.push({name:i,sourcePath:e.sourcePath,startLine:r,endLine:r,setup:e.setup})}}function Iv(e){let t=[];for(let n of e.body.matchAll(/\bimport\s+(?:type\s+)?([^'";]+?)\s+from\s+['"]([^'"]+)['"]/g)){let i=n[1]?.trim(),r=n[2];if(!i||!r)continue;let o=e.startLine+jo(e.body,n.index??0);for(let s of Lv(i))t.push({local:s,source:r,sourcePath:e.sourcePath,line:o,setup:e.setup})}return t}function Lv(e){let t=[],i=e.split(",").map(s=>s.trim()).filter(Boolean)[0];i&&!i.startsWith("{")&&!i.startsWith("*")&&t.push(i);let r=/\{([^}]*)\}/.exec(e)?.[1];if(r)for(let s of r.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 Xd(e){let t=["call"];return/^use[A-Z0-9_]/.test(e)&&t.push("composable"),/^use[A-Z0-9_].*Store$/.test(e)&&t.push("store"),Sv.has(e)&&t.push("reactivity"),xv.has(e)&&t.push("lifecycle"),Cv.has(e)&&t.push("request"),vv.has(e)&&t.push("macro"),t}function jo(e,t){let n=0;for(let i=0;i<t&&i<e.length;i+=1)e.charCodeAt(i)===10&&(n+=1);return n}function Qd(e){return[...new Set(e)].sort()}var Dv=new Set(["in","key","of"]),Ev=new Set(["computed","defineEmits","defineProps","reactive","ref","watch","watchEffect"]),Nv=sn("vue-component-behavior-profiles");function Yd(e,t={}){let n=et(e,{extensions:[".vue"]}).filter(r=>!t.scope||r.includes(t.scope)).sort();return(typeof t.scanLimit=="number"&&t.scanLimit>0?n.slice(0,t.scanLimit):n).map(r=>Ka(e,r)).filter(r=>(t.minTemplateTokens===void 0||r.templateTokens.size>=t.minTemplateTokens)&&(t.minBehaviorTokens===void 0||r.behaviorTokens.size>=t.minBehaviorTokens))}function Ka(e,t){let n=t.replace(/\\/g,"/"),i=M(e,n),r=Nv.get(e,n,i,()=>Fv(e,n,i));return Tv(r)}function Fv(e,t,n){let i=yi(e,t),r=_o(e,t),o=Oo(i),s=Mv(r),a=r.expressionIdentifiers.map(f=>f.name).filter(f=>!s.includes(f)).filter((f,g,b)=>b.indexOf(f)===g).sort(),c=r.componentTags.map(f=>f.normalized).filter((f,g,b)=>b.indexOf(f)===g).sort(),l=n?n.split(`
67
+ `).length:0,d=Pn(i.template),u=o.lineCount,m=i.styles.reduce((f,g)=>f+Pn(g),0),p=i.customBlocks.reduce((f,g)=>f+Pn(g),0);return{file:t,sfc:i,templateFacts:r,scriptFacts:o,templateTokens:new Set(r.structuralTokens),behaviorTokens:Av(r,o,a),templateBindingNames:a,templateLocalNames:s,componentNames:c,sfcLines:l,totalLines:l+o.externalLineCount,templateLines:d,scriptLines:u,styleLines:m,externalScriptLines:o.externalLineCount,externalScriptPaths:o.externalScriptPaths,customBlockLines:p}}function Tv(e){let t=_v(e.scriptFacts);return{...e,scriptFacts:t,templateTokens:new Set(e.templateTokens),behaviorTokens:new Set(e.behaviorTokens),templateBindingNames:[...e.templateBindingNames],templateLocalNames:[...e.templateLocalNames],componentNames:[...e.componentNames],externalScriptPaths:t.externalScriptPaths}}function _v(e){return{...e,imports:e.imports.map(t=>({...t})),functions:e.functions.map(t=>({...t})),calls:e.calls.map(t=>({...t,categories:[...t.categories]})),composables:[...e.composables],stores:[...e.stores],reactivity:[...e.reactivity],lifecycle:[...e.lifecycle],requests:[...e.requests],macros:[...e.macros],externalScriptPaths:[...e.externalScriptPaths],unresolvedScripts:e.unresolvedScripts.map(t=>({...t}))}}function Av(e,t,n){let i=new Set;for(let r of t.composables)i.add(`composable:${r}`);for(let r of t.stores)i.add(`store:${r}`);for(let r of t.reactivity)i.add(`reactivity:${r}`);for(let r of t.lifecycle)i.add(`lifecycle:${r}`);for(let r of t.requests)i.add(`request:${r}`);for(let r of t.macros)i.add(`macro:${r}`);for(let r of t.functions){if(Ev.has(r.name))continue;i.add(`function:${r.name}`);let o=/^[a-z]+/.exec(r.name)?.[0]??null;o&&o.length>2&&o!==r.name&&i.add(`function-verb:${o}`)}for(let r of e.events)i.add(`template-event:${r.name}`);for(let r of n)i.add(`template-binding:${r}`);return i}function Mv(e){let t=new Set;for(let n of e.directives)if(n.name==="for"&&n.value)for(let i of $v(n.value))t.add(i);for(let n of e.slots)if(n.value)for(let i of Zd(n.value))t.add(i);return[...t].sort()}function $v(e){let t=/^(.*?)\s+(?:in|of)\s+/.exec(e.trim());return t?Zd(t[1]??""):[]}function Zd(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let i=n[0];Dv.has(i)||t.push(i)}return t}import{extname as jv}from"path";function kt(e){return typeof e=="object"&&e!==null}function je(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")?e:null}var Ov=[".tsx",".jsx"],em=new Set(["useActionState","useCallback","useContext","useDebugValue","useDeferredValue","useEffect","useId","useImperativeHandle","useInsertionEffect","useLayoutEffect","useMemo","useOptimistic","useReducer","useRef","useState","useSyncExternalStore","useTransition"]),Bv=new Set(["useEffect","useInsertionEffect","useLayoutEffect"]),Hv=new Set(["useActionState","useOptimistic","useReducer","useRef","useState"]),Vv=new Set(["useLocation","useNavigate","useParams","useSearchParams","useTranslation"]),qv=new Set(["axios","fetch","gql","graphql","mutate","query","request","useMutation","useQuery","useSuspenseQuery"]),Uv=new Set(["add","apply","cancel","change","clear","close","create","delete","fetch","filter","handle","load","open","refresh","remove","render","reset","save","select","submit","toggle","update"]),zv=new Set(["children","className","false","key","null","style","true","undefined"]),Wv=new Set(["aria-hidden","className","clipRule","d","fill","fillRule","height","role","stroke","strokeLinecap","strokeLinejoin","strokeWidth","style","viewBox","width","xmlns"]),Gv=sn("react-component-behavior-profiles"),tm=pe({kind:"react-component-behavior-profiles",serialize:Qv,deserialize:Yv});function om(e,t={}){let n=et(e,{extensions:Ov}).filter(r=>!t.scope||r.includes(t.scope)).sort();return(typeof t.scanLimit=="number"&&t.scanLimit>0?n.slice(0,t.scanLimit):n).flatMap(r=>Ja(e,r)).filter(r=>(t.minJsxTokens===void 0||r.jsxTokens.size>=t.minJsxTokens)&&(t.minBehaviorTokens===void 0||r.behaviorTokens.size>=t.minBehaviorTokens))}function Ja(e,t){let n=t.replace(/\\/g,"/"),i=M(e,n);return Gv.get(e,n,i,()=>Kv(e,n,i)).map(Xv)}function Kv(e,t,n){let i=re(e,t,n),r=tm.read(e,t,i);if(r)return r;let o=Jv(e,t);return tm.write(e,t,i,o),o}function Jv(e,t){let n=eR(t);if(!n)return[];let i=Pe(e,t);if(!i)return[];let r=Ye(e,t).length;return tR(i.rootNode,n).filter(s=>s.kind==="hook"||am(s.bodyNode)).map(s=>{let a=sR(s.bodyNode),c=dR(s.bodyNode,n);return{file:t,name:s.name,kind:s.kind,startLine:s.node.startPosition.row,endLine:s.node.endPosition.row,loc:Math.max(1,s.node.endPosition.row-s.node.startPosition.row+1),fileLines:r,jsxTokens:a.tokens,behaviorTokens:c.tokens,componentNames:qt(a.componentNames),nativeTags:qt(a.nativeTags),propNames:qt(a.propNames),eventNames:qt(a.eventNames),hookNames:qt(c.hookNames),requestNames:qt(c.requestNames),stateNames:qt(c.stateNames),effectNames:qt(c.effectNames),handlerNames:qt(c.handlerNames)}})}function Xv(e){return{...e,jsxTokens:new Set(e.jsxTokens),behaviorTokens:new Set(e.behaviorTokens),componentNames:[...e.componentNames],nativeTags:[...e.nativeTags],propNames:[...e.propNames],eventNames:[...e.eventNames],hookNames:[...e.hookNames],requestNames:[...e.requestNames],stateNames:[...e.stateNames],effectNames:[...e.effectNames],handlerNames:[...e.handlerNames]}}function Qv(e){return JSON.stringify(e.map(t=>({...t,jsxTokens:[...t.jsxTokens],behaviorTokens:[...t.behaviorTokens]})))}function Yv(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=[];for(let i of t){let r=Zv(i);if(!r)return null;n.push(r)}return n}catch{return null}}function Zv(e){if(!kt(e))return null;let{file:t,name:n,kind:i,startLine:r,endLine:o,loc:s,fileLines:a,jsxTokens:c,behaviorTokens:l,componentNames:d,nativeTags:u,propNames:m,eventNames:p,hookNames:f,requestNames:g,stateNames:b,effectNames:x,handlerNames:S}=e;if(typeof t!="string"||typeof n!="string"||i!=="component"&&i!=="hook"||!Bo(r)||!Bo(o)||!Bo(s)||!Bo(a))return null;let R={jsxTokens:je(c),behaviorTokens:je(l),componentNames:je(d),nativeTags:je(u),propNames:je(m),eventNames:je(p),hookNames:je(f),requestNames:je(g),stateNames:je(b),effectNames:je(x),handlerNames:je(S)};return Object.values(R).some(C=>C===null)?null:{file:t,name:n,kind:i,startLine:r,endLine:o,loc:s,fileLines:a,jsxTokens:new Set(R.jsxTokens),behaviorTokens:new Set(R.behaviorTokens),componentNames:R.componentNames,nativeTags:R.nativeTags,propNames:R.propNames,eventNames:R.eventNames,hookNames:R.hookNames,requestNames:R.requestNames,stateNames:R.stateNames,effectNames:R.effectNames,handlerNames:R.handlerNames}}function Bo(e){return typeof e=="number"&&Number.isFinite(e)}function eR(e){let t=jv(e).toLowerCase();return t!==".tsx"&&t!==".jsx"?null:H(e)}function tR(e,t){let n=[],i=new Set,r=o=>{let s=nR(o);if(s&&!rR(o)){let a=`${s.name}:${s.node.startIndex}:${s.node.endIndex}`;i.has(a)||(i.add(a),n.push(s));return}for(let a of o.namedChildren)r(a)};return(t==="tsx"||t==="javascript")&&r(e),n}function nR(e){if(e.type==="function_declaration"){let o=sm(e);return!o||!nm(o)?null:{name:o,kind:im(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),i=gr(t);if(!i||!n||!nm(i))return null;let r=iR(n);return r?{name:i,kind:im(i),node:e,bodyNode:r}:null}function nm(e){return/^[A-Z]/.test(e)||/^use[A-Z0-9_]/.test(e)}function im(e){return/^use[A-Z0-9_]/.test(e)?"hook":"component"}function iR(e){if(e.type==="arrow_function"||e.type==="function_expression")return e;if(e.type!=="call_expression")return null;let t=oR(e);return t!=="memo"&&t!=="forwardRef"?null:e.namedChildren.find(r=>r.type==="arguments")?.namedChildren.find(r=>r.type==="arrow_function"||r.type==="function_expression")??null}function rR(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 sm(e){return gr(e.childForFieldName("name")??e.namedChild(0))}function oR(e){let t=e.childForFieldName("function")??e.namedChild(0);return t?t.text.split(".").pop()??t.text:null}function am(e){return e.type.startsWith("jsx_")?!0:e.namedChildren.some(am)}function sR(e){let t={tokens:new Set,componentNames:new Set,nativeTags:new Set,propNames:new Set,eventNames:new Set},n=i=>{i.type==="jsx_opening_element"||i.type==="jsx_self_closing_element"?aR(i,t):i.type==="jsx_expression"?cR(i,t):i.type==="jsx_fragment"&&t.tokens.add("jsx:fragment");for(let r of i.namedChildren)n(r)};return n(e),t}function aR(e,t){let n=lR(e),i=!1;if(n){let r=rm(n);i=hR(r),i?(t.componentNames.add(r),t.tokens.add(`component:${r}`)):(t.nativeTags.add(r),t.tokens.add(`native:${r}`))}for(let r of e.namedChildren)if(r.type==="jsx_attribute"){let o=uR(r);if(!o)continue;let s=rm(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 Wv.has(s)||(t.propNames.add(s),t.tokens.add(`${i?"prop":"native-prop"}:${s}`))}else r.type==="jsx_spread_attribute"&&t.tokens.add("prop:spread")}function cR(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 i of yR(n))zv.has(i)||t.tokens.add(`binding:${i}`)}function lR(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 uR(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 dR(e,t){let n={tokens:new Set,hookNames:new Set,requestNames:new Set,stateNames:new Set,effectNames:new Set,handlerNames:new Set},i=r=>{if(r.type==="call_expression"){let o=Si(r,t);o&&mR(o.calleeLeaf,n)}else if(r.type==="variable_declarator")fR(r,n);else if(r.type==="function_declaration"){let o=sm(r);o&&cm(o,n)}for(let o of r.namedChildren)i(o)};return i(e),n}function mR(e,t){/^use[A-Z0-9_]/.test(e)&&(t.hookNames.add(e),!em.has(e)&&!Vv.has(e)&&t.tokens.add(`hook:${e}`)),em.has(e)&&t.tokens.add(`react-hook:${e}`),Bv.has(e)&&(t.effectNames.add(e),t.tokens.add(`effect:${e}`)),Hv.has(e)&&t.tokens.add(`state-hook:${e}`),pR(e)&&(t.requestNames.add(e),t.tokens.add(`request:${e}`))}function pR(e){if(qv.has(e))return!0;let t=/^use([A-Z0-9_].*)$/.exec(e)?.[1];return t?/(Query|Mutation|Fetch|Resource)$/.test(t):!1}function fR(e,t){let n=e.childForFieldName("name")??e.namedChild(0),i=e.childForFieldName("value")??e.namedChild(1);if(n?.type==="array_pattern"&&i?.text.includes("useState")){let o=n.namedChildren.find(a=>gr(a)),s=gr(o);s&&(t.stateNames.add(s),t.tokens.add(`state:${s}`))}let r=gr(n);r&&cm(r,t)}function cm(e,t){let n=gR(e);!n||!Uv.has(n)||(t.handlerNames.add(e),t.tokens.add(`handler:${e}`),t.tokens.add(`handler-verb:${n}`))}function gR(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 hR(e){return/^[A-Z]/.test(e)||e.includes(".")}function rm(e){return e.replace(/^this\./,"").replace(/\$/g,".")}function gr(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 yR(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let i=n[0];t.includes(i)||t.push(i)}return t}function qt(e){return[...e].sort()}function tt(e){return{capability:(t,n)=>bR(t,n),reactProfiles:(t={})=>om(e,t),reactProfilesForFile:t=>Ja(e,t),vueProfiles:(t={})=>Yd(e,t),vueProfileForFile:t=>Ka(e,t),vueTemplateFacts:t=>_o(e,t),vueScriptFacts:t=>Oo(yi(e,t))}}function bR(e,t){let n=e.startsWith("react-")?"react":"vue";if(t===void 0)return{slot:e,available:!0,framework:n};let i=t.replace(/\\/g,"/").toLowerCase();return n==="react"&&!i.endsWith(".tsx")&&!i.endsWith(".jsx")?{slot:e,available:!1,framework:n,reason:"React behavior profiles are only available for .tsx and .jsx files"}:n==="vue"&&!i.endsWith(".vue")?{slot:e,available:!1,framework:n,reason:"Vue behavior facts are only available for .vue files"}:{slot:e,available:!0,framework:n}}function Dn(e,t,n={}){let i=X(e,t);if(!i)return[];let r=[];if(n.includeCrossLanguageDispatchNames)for(let o of i.crossLanguageDispatchNames)r.push({name:o,kind:"cross-language-dispatch",occurrences:1});if(n.includeRustAttributeNames&&i.language==="rust")for(let o of i.rustAttrReferencedNames)r.push({name:o,kind:"rust-attribute",occurrences:1});return r}import{existsSync as Ho}from"fs";import{basename as lm,dirname as un,extname as Ut,join as mt,relative as hr,resolve as nt}from"path";var SR=ie("indexed-paths",{clearGroups:[]}),xR=ie("indexed-path-digest",{clearGroups:[]}),En=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],Vo=[".py",".pyi"],Ge=[".java",".scala",".kt",".kts"],qo=[".rs"],Uo=[".rb"],zo=[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],dn=[".cs",".vb"],Wo=[".dart"],Nn=[".php"],Ri=[".clj",".cljs",".cljc"],CR=new Set(En),Xa=new Set(Vo),um=new Set(Ge),Qa=new Set(qo),Ya=new Set(Uo),dm=new Set(zo),mm=new Set(dn),Za=new Set(Wo),pm=new Set(Nn),fm=new Set(Ri),vR=[{extensions:En,lookup:CR},{extensions:Vo,lookup:Xa},{extensions:Ge,lookup:um},{extensions:qo,lookup:Qa},{extensions:Uo,lookup:Ya},{extensions:zo,lookup:dm},{extensions:dn,lookup:mm},{extensions:Wo,lookup:Za},{extensions:Nn,lookup:pm},{extensions:Ri,lookup:fm}];function zt(e,t){return t.has(Ut(e).toLowerCase())}function RR(e){return zt(e,Xa)}function kR(e){return zt(e,um)}function wR(e){return zt(e,Qa)}function PR(e){return zt(e,Ya)}function IR(e){return zt(e,dm)}function LR(e){return zt(e,mm)}function gm(e){return Ut(e).toLowerCase()===".vb"}function DR(e){return zt(e,Za)}function ER(e){return zt(e,pm)}function NR(e){return zt(e,fm)}function ec(e){let t=Ut(e).toLowerCase();for(let n of vR)if(n.lookup.has(t))return n.extensions;return En}function FR(e){return kR(e)||LR(e)||ER(e)}function ft(e,t,n){return RR(t)?ki(e,t,n):wR(t)?Wt(e,t,n):PR(t)?Go(e,t,n):IR(t)?Ko(e,t,n):FR(t)?fe(e,n.replace(/\\/g,"."),ec(t)):DR(t)?Jo(e,t,n):NR(t)?tc(e,n):TR(e,t,n)}function TR(e,t,n){if(!n.startsWith(".")&&!n.startsWith("/"))return null;let i=un(mt(e.config.projectRoot,t)),r=nt(i,n),o=Fn(e);for(let s of jR(r)){let a=pt(hr(e.config.projectRoot,s));if(o.has(a)||Ho(s))return a}return pt(hr(e.config.projectRoot,r))}function ki(e,t,n){let i=Fn(e),r;if(n.startsWith(".")){let o=n.match(/^(\.+)(.*)$/);if(!o)return null;let s=o[1].length,a=o[2].replace(/^\./,""),c=un(mt(e.config.projectRoot,t));for(let l=1;l<s;l++)c=un(c);r=a?nt(c,a.replace(/\./g,"/")):c}else r=nt(e.config.projectRoot,n.replace(/\./g,"/"));for(let o of _R(r)){let s=pt(hr(e.config.projectRoot,o));if(i.has(s)||Ho(o))return s}return null}function Wt(e,t,n){if(!n)return null;let i=n.replace(/\s+as\s+.+$/,"").trim();if(!i.startsWith("crate::")&&!i.startsWith("self::")&&!i.startsWith("super::"))return null;let r=un(mt(e.config.projectRoot,t)),o;return i.startsWith("crate::")?o=nt(e.config.projectRoot,"src",i.slice(7).replace(/::/g,"/")):i.startsWith("self::")?o=nt(r,i.slice(6).replace(/::/g,"/")):o=nt(un(r),i.slice(7).replace(/::/g,"/")),nc(e,AR(o))}function Go(e,t,n){let i=un(mt(e.config.projectRoot,t)),r=nt(i,n);return nc(e,MR(r))}function Ko(e,t,n){let i=un(mt(e.config.projectRoot,t)),r=[nt(i,n),nt(e.config.projectRoot,n),nt(e.config.projectRoot,"include",n),nt(e.config.projectRoot,"src",n)];return nc(e,r)}function fe(e,t,n){let i=Fn(e),r=t.replace(/\\/g,".").replace(/::/g,".").replace(/^global::/,""),o=r.replace(/\./g,"/"),s=r.split(".").pop()??r;for(let c of n){let l=`${o}${c}`,d=[...i].find(u=>u.endsWith(l));if(d)return d}for(let c of n){let l=[...i].find(d=>lm(d)===`${s}${c}`);if(l)return l}let a=[...i].filter(c=>n.includes(Ut(c).toLowerCase())).filter(c=>c.includes(`/${o}/`)||c.includes(`/${s}/`)).sort((c,l)=>c.localeCompare(l));return a.length===1?a[0]:null}function Jo(e,t,n){let i=Fn(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=pt(c.startsWith("lib/")?c:`lib/${c}`);return i.has(l)?l:null}let r=un(mt(e.config.projectRoot,t)),o=nt(r,n);for(let s of $R(o)){let a=pt(hr(e.config.projectRoot,s));if(i.has(a)||Ho(s))return a}return null}function tc(e,t){let n=t.replace(/-/g,"_").replace(/\./g,"/"),i=Fn(e);for(let r of Ri){let o=`${n}${r}`,s=[...i].find(a=>a.endsWith(o));if(s)return s}for(let r of Ri){let o=[...i].find(s=>lm(s)===`${n.split("/").pop()}${r}`);if(o)return o}return null}function _R(e){let t=Ut(e);return Xa.has(t)?[e]:[`${e}.py`,`${e}.pyi`,mt(e,"__init__.py"),mt(e,"__init__.pyi")]}function nc(e,t){let n=Fn(e);for(let i of t){let r=pt(hr(e.config.projectRoot,i));if(n.has(r)||Ho(i))return r}return null}function AR(e){let t=Ut(e);return Qa.has(t)?[e]:[`${e}.rs`,mt(e,"mod.rs")]}function MR(e){let t=Ut(e);return Ya.has(t)?[e]:[`${e}.rb`,mt(e,"index.rb")]}function $R(e){let t=Ut(e);return Za.has(t)?[e]:[`${e}.dart`,e]}function jR(e){let t=Ut(e),n=new Set;if(t){n.add(e);for(let i of En)n.add(e.slice(0,-t.length)+i)}else for(let i of En)n.add(`${e}${i}`),n.add(mt(e,`index${i}`));return[...n]}function Fn(e){return SR.get(e,()=>new Set(O(e,{includeIgnored:!1}).map(pt)))}function ic(e){return xR.get(e,()=>Vt([...Fn(e)].sort().join(`
68
+ `)))}function pt(e){return e.replace(/\\/g,"/")}import{basename as ym}from"path";function Tn(e){return e.replace(/'''[\s\S]*?'''/g,mn).replace(/"""[\s\S]*?"""/g,mn).replace(/#.*$/gm,mn).replace(/\/\/.*$/gm,mn).replace(/\/\*[\s\S]*?\*\//g,mn).replace(/`(?:\\[\s\S]|[^`])*`/g,mn).replace(/'(?:\\.|[^'\\\r\n])*'/g,mn).replace(/"(?:\\.|[^"\\\r\n])*"/g,mn)}function mn(e){return e.replace(/[^\r\n]/g," ")}var tG=wn("stripped-lines",{clearGroups:["whole-project","source-file"]});on({name:"stripped-source-singleton",groups:["whole-project","source-file"],clearAll:()=>{Xo=null,yr=""},clearFile:()=>{Xo=null,yr=""}});var Xo=null,yr="";function OR(e){return Xo===e||(Xo=e,yr=Tn(e)),yr}function pn(e,t,n){let i=OR(e);return`${i.slice(0,t)}${" ".repeat(n-t)}${i.slice(n)}`}function Be(e,t){return new RegExp(`\\b${hm(t)}\\b`,"m").test(e)}function wi(e,t){let n=new Set,i=new RegExp(`\\b${hm(t)}\\s*\\.\\s*([A-Za-z_$][\\w$]*)`,"g");for(let r of e.matchAll(i)){let o=r[1];o&&n.add(o)}return[...n]}function hm(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function br(e){let t=0;for(let n of e)n==="("&&(t+=1),n===")"&&(t-=1);return t}var BR=new Set(["identifier","type_identifier","property_identifier","shorthand_property_identifier","field_identifier"]);function He(e){let t=[],n=0,i=0;for(let r=0;r<e.length;r++){let o=e[r];(o==="{"||o==="["||o==="(")&&n++,(o==="}"||o==="]"||o===")")&&n--,o===","&&n===0&&(t.push(e.slice(i,r)),i=r+1)}return t.push(e.slice(i)),t}function Ke(e,t){for(let n of e.namedChildren)if(n.type===t)return n;return null}function ge(e,t){let n=new Set,i=(r,o)=>{let s=o||t.has(r.type);!s&&BR.has(r.type)&&n.add(r.text);for(let a of r.children)i(a,s)};return i(e.rootNode,!1),n}function wt(e,t,n,i,r,o,s){return{importedName:r,localName:o,sourcePath:s??fe(e,i,ec(t)),kind:"named",used:Be(n,o),usedMembers:[]}}function ue(e,t,n,i,r="named",o={}){return{importedName:e,localName:t,sourcePath:n,kind:r,used:i.has(t),usedMembers:[],isTypeOnly:o.isTypeOnly}}function Gt(e,t,n,i,r="named",o=[],s={}){return{importedName:e,localName:t,sourcePath:n,kind:r,used:i,usedMembers:o,isTypeOnly:s.isTypeOnly}}function _n(e,t){return{importedName:e,localName:null,sourcePath:t,kind:"side-effect",used:!0,usedMembers:[]}}function An(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 it(e,t,n){let i=[];for(let r of e.matchAll(t)){let o=r[0];if(!o||typeof r.index!="number")continue;let s=pn(e,r.index,r.index+o.length);for(let a of n(r,s))i.push(a)}return i}function rt(e,t,n,i){let r=Pe(e,t);if(r){let o=n(r);if(o)return o}return i()}function Qo(e,t,n,i){let r=Pe(e,t),o=H(t),s=o?n[o]:void 0;return r&&s?s(r):i()}function bm(e,t,n){return rt(e,t,i=>VR(e,t,i),()=>HR(e,t,n))}function HR(e,t,n){return it(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(i,r)=>{let o=i[1]?.trim();if(!o)return[];let s=ym(o).replace(/\.[^.]+$/,"");return[Gt(o,s,Ko(e,t,o),Be(r,s))]})}function VR(e,t,n){let i=ge(n,new Set(["preproc_include"])),r=[];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(d=>d.type==="string_content")?.text??c.text.replace(/^"|"$/g,"");break}}if(!s)continue;let a=ym(s).replace(/\.[^.]+$/,"");r.push(ue(s,a,Ko(e,t,s),i))}return r}var qR=new Set([":require",":require-macros",":use"]),ac=String.raw`A-Za-z0-9_$*+!?.<>=-`;function xm(e,t,n){let i=ek(n);if(!i)return[];let r=ZR(n,i.start,i.end),o=[];for(let s of i.children.slice(2)){if(s.type!=="list"||s.children.length===0)continue;let a=Pt(s.children[0]);if(a){if(qR.has(a)){for(let c of WR(s.children.slice(1)))o.push(...zR(e,c,r));continue}if(a===":import")for(let c of KR(s.children.slice(1)))o.push(c)}}return o}function UR(e){return e.type==="list"&&Pt(e.children[0])==="ns"}function zR(e,t,n){let i=tc(e,t.namespace),r=t.alias??t.namespace,o=XR(n,r),s=[{importedName:t.namespace,localName:r,sourcePath:i,kind:"namespace",used:t.refers.length>0||t.referAll||o.length>0||QR(n,t.namespace),usedMembers:o}];t.referAll&&s.push({importedName:"*",localName:null,sourcePath:i,kind:"side-effect",used:!0,usedMembers:[]});for(let a of t.refers)s.push({importedName:a,localName:a,sourcePath:i,kind:"named",used:YR(n,a),usedMembers:[]});return s}function WR(e){return e.flatMap(t=>Cm(t,null))}function Cm(e,t){if(e.type==="atom")return e.text.startsWith(":")?[]:[{namespace:oc(t,e.text),alias:null,refers:[],referAll:!1}];if(e.type==="vector")return GR(e,t);if(e.type==="list"&&e.children.length>0){let n=Pt(e.children[0]);return!n||n.startsWith(":")?[]:e.children.slice(1).flatMap(i=>Cm(i,oc(t,n)))}return[]}function GR(e,t){let n=Pt(e.children[0]);if(!n||n.startsWith(":"))return[];let i={namespace:oc(t,n),alias:null,refers:[],referAll:!1};for(let r=1;r<e.children.length;r+=1){let o=Pt(e.children[r]);if(!o?.startsWith(":"))continue;let s=e.children[r+1];if((o===":as"||o===":as-alias")&&s){i.alias=Pt(s),r+=1;continue}o===":refer"&&s&&(Pt(s)===":all"?i.referAll=!0:(s.type==="vector"||s.type==="list")&&i.refers.push(...s.children.map(Pt).filter(JR)),r+=1)}return[i]}function KR(e){let t=[];for(let n of e){if(n.type==="atom"){let r=n.text.split(".").pop()??n.text;t.push(Gt(r,r,null,!0));continue}if(n.type!=="vector")continue;let i=Pt(n.children[0]);if(i)for(let r of n.children.slice(1)){let o=Pt(r);o&&t.push(Gt(`${i}.${o}`,o,null,!0))}}return t}function oc(e,t){return e?`${e}.${t}`:t}function Pt(e){return e?.type==="atom"?e.text:null}function JR(e){return!!(e&&!e.startsWith(":"))}function XR(e,t){let n=new Set,i=new RegExp(`${cc()}${lc(t)}\\s*/\\s*([${ac}]+)`,"g");for(let r of e.matchAll(i)){let o=r[1];o&&n.add(o)}return[...n]}function QR(e,t){return new RegExp(`${cc()}${lc(t)}\\s*/`,"m").test(e)}function YR(e,t){return new RegExp(`${cc()}${lc(t)}(?![${ac}])`,"m").test(e)}function cc(){return`(?<![${ac}])`}function lc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ZR(e,t,n){let i="",r=0;for(;r<e.length;){if(r>=t&&r<n){i+=e[r]===`
69
+ `?`
70
+ `:" ",r+=1;continue}let o=e[r];if(o===";"){let s=vm(e,r);i+=Sm(e.slice(r,s)),r=s;continue}if(o==='"'){let s=sc(e,r);i+=Sm(e.slice(r,s)),r=s;continue}i+=o,r+=1}return i}function ek(e){let t=0;for(;t<e.length&&(t=dc(e,t),!(t>=e.length));){let n=uc(e,t);if(!n){t+=1;continue}if(UR(n.form))return n.form;t=n.index}return null}function uc(e,t){let n=dc(e,t);if(e.startsWith("#_",n)){let r=uc(e,n+2);return r?{form:{type:"atom",text:"",start:n,end:r.index},index:r.index}:null}for(;nk(e[n]);)n+=1;let i=e[n];return i?i==="("?rc(e,n,"list",")"):i==="["?rc(e,n,"vector","]"):i==="{"?rc(e,n,"map","}"):i==='"'?{form:{type:"atom",text:"",start:n,end:sc(e,n)},index:sc(e,n)}:tk(e,n):null}function rc(e,t,n,i){let r=[],o=t+1;for(;o<e.length;){if(o=dc(e,o),e[o]===i)return{form:{type:n,children:r,start:t,end:o+1},index:o+1};let s=uc(e,o);if(!s){o+=1;continue}s.form.type==="atom"&&s.form.text===""||r.push(s.form),o=s.index}return{form:{type:n,children:r,start:t,end:e.length},index:e.length}}function tk(e,t){let n=t;for(;n<e.length&&!ik(e[n]);)n+=1;return{form:{type:"atom",text:e.slice(t,n),start:t,end:n},index:n}}function dc(e,t){let n=t;for(;n<e.length;){let i=e[n];if(/\s|,/.test(i)){n+=1;continue}if(i===";"){n=vm(e,n);continue}break}return n}function vm(e,t){let n=t;for(;n<e.length&&e[n]!==`
71
+ `;)n+=1;return n}function sc(e,t){let n=t+1;for(;n<e.length;){let i=e[n];if(i==="\\"){n+=2;continue}if(n+=1,i==='"')break}return n}function nk(e){return e==="'"||e==="`"||e==="~"||e==="@"||e==="^"}function ik(e){return/\s|,/.test(e)||e==="("||e===")"||e==="["||e==="]"||e==="{"||e==="}"||e==='"'||e===";"}function Sm(e){return e.replace(/[^\r\n]/g," ")}function Rm(e,t,n){let i=[];for(let r of n.matchAll(/^[ \t]*import\s+['"]([^'"]+)['"](?:\s+as\s+([A-Za-z_]\w*))?[\s\S]*?;$/gm)){let o=r[1]?.trim(),s=r[2]?.trim()??null,a=r[0];if(!o||!a||typeof r.index!="number")continue;let c=pn(n,r.index,r.index+a.length);i.push({importedName:o,localName:s,sourcePath:Jo(e,t,o),kind:s?"namespace":"side-effect",used:s?Be(c,s):!0,usedMembers:s?wi(c,s):[]})}return i}function km(e,t,n){let i=[];for(let r of n.matchAll(/^[ \t]*export\s+['"]([^'"]+)['"][\s\S]*?;$/gm)){let o=r[1]?.trim();o&&i.push({specifier:o,sourcePath:Jo(e,t,o)})}return i}function wm(e,t,n){return Qo(e,t,{csharp:i=>ok(e,t,i),vb:i=>rk(e,t,i)},()=>{let i=gm(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return it(n,i,(r,o)=>{let s=r[1]?.trim();if(!s)return[];let[a,c]=s.split(/\s*=\s*/),l=!!c,d=(l?c:a)?.trim()??s,u=d.split(".").pop()??d,m=l?a?.trim()??u:u;return[wt(e,t,o,d,u,m,fe(e,d,dn))]})})}function rk(e,t,n){let i=ge(n,new Set(["imports_statement"])),r=[];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,d=l.split(".").pop()??l,u=c?.text??d;r.push(ue(d,u,fe(e,l,dn),i,c?"namespace":"named"))}return r}function ok(e,t,n){let i=ge(n,new Set(["using_directive"])),r=[];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,d=l.split(".").pop()??l,u=a?.text??d;r.push(ue(d,u,fe(e,l,dn),i,a?"namespace":"named"))}return r}var sk=W("vue-non-script-identifiers",{clearGroups:["whole-project","source-file"]});function Pm(e,t){return sk.get(e,t,()=>{let n=new Set,i=M(e,t);if(!i)return n;let o=i.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 mc(e,t,n){return rt(e,t,i=>ck(e,t,i),()=>ak(e,t,n))}function ak(e,t,n){return Sk(n).flatMap(i=>xk(e,t,i.clause,i.specifier,i.start,i.end,n))}function ck(e,t,n){let i=lk(e,t,n),r=[];for(let o of n.rootNode.descendantsOfType("import_statement"))r.push(...uk(e,t,n,o,i));return r}function lk(e,t,n){let i=ge(n,new Set(["import_statement"]));if(Ht(t))for(let r of Pm(e,t))i.add(r);return i}function uk(e,t,n,i,r){let o=gk(i);if(!o)return[];let s=ft(e,t,o),a=Ke(i,"import_clause");return a?dk(n,a,s,r,hk(i.text)):[_n("*",s)]}function dk(e,t,n,i,r){let o=[];for(let s of t.namedChildren)if(s.type==="identifier")o.push(mk(s.text,n,i,r));else if(s.type==="namespace_import"){let a=pk(e,s,n,i,r);a&&o.push(a)}else s.type==="named_imports"&&o.push(...fk(s,n,i,r));return o}function mk(e,t,n,i){return ue("default",e,t,n,"default",{isTypeOnly:i})}function pk(e,t,n,i,r){let s=Ke(t,"identifier")?.text??"";if(!s)return null;let a=bk(e,s);return An("*",n,{localName:s,usedMembers:a,isTypeOnly:r,used:a.length>0||i.has(s)})}function fk(e,t,n,i){let r=[];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;r.push(ue(c,l,t,n,"named",{isTypeOnly:i||yk(o.text)}))}return r}function gk(e){let t=Ke(e,"string");if(!t)return null;let n=Ke(t,"string_fragment");return n?n.text:null}function hk(e){return/^\s*import\s+type\b/.test(e)}function yk(e){return/^\s*type\b/.test(e.trim())}function bk(e,t){let n=new Set;for(let i of e.rootNode.descendantsOfType("member_expression")){let r=i.namedChild(0),o=i.namedChild(1);!r||!o||r.type!=="identifier"||r.text!==t||(o.type==="property_identifier"||o.type==="identifier")&&n.add(o.text)}return[...n]}function Sk(e){let t=[],n=/^[ \t]*import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let r of e.matchAll(n)){let o=r[0],s=r[1],a=r[2];!o||!a||typeof r.index!="number"||t.push({clause:s,specifier:a,start:r.index,end:r.index+o.length})}let i=/^[ \t]*import\s+['"]([^'"]+)['"]\s*;?/gm;for(let r of e.matchAll(i)){let o=r[0],s=r[1];!o||!s||typeof r.index!="number"||t.push({clause:null,specifier:s,start:r.index,end:r.index+o.length})}return t.sort((r,o)=>r.start-o.start)}function xk(e,t,n,i,r,o,s){let a=ft(e,t,i),c=pn(s,r,o);return n?Ck(n).map(d=>({...d,sourcePath:a})).map(d=>{if(d.kind==="namespace"){let u=wi(c,d.localName);return An(d.importedName,d.sourcePath,{localName:d.localName,usedMembers:u,used:u.length>0||Be(c,d.localName),isTypeOnly:d.isTypeOnly})}return d.kind==="side-effect"?_n(d.importedName,d.sourcePath):Gt(d.importedName,d.localName??"",d.sourcePath,d.localName?Be(c,d.localName):!1,d.kind,[],{isTypeOnly:d.isTypeOnly})}):[_n("*",a)]}function Ck(e){let t=e.trim(),n=/^type\b/.test(t),i=t.replace(/^type\s+/,""),[r,o]=vk(i),s=[];return r&&s.push(...Im(r,n)),o&&s.push(...Im(o,n)),s}function Im(e,t){let n=e.trim();if(!n)return[];if(n.startsWith("{")){let i=n.slice(1,-1).trim();return i?He(i).map(r=>{let o=r.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 vk(e){let t=0;for(let n=0;n<e.length;n++){let i=e[n];if(i==="{"&&t++,i==="}"&&t--,i===","&&t===0)return[e.slice(0,n).trim(),e.slice(n+1).trim()]}return[e.trim(),null]}function pc(e,t,n){let i=Pe(e,t);return i?Lk(e,t,i):Rk(e,t,n)}function Rk(e,t,n){return[...kk(e,t,n),...wk(e,t,n),...Pk(e,t,n)]}function kk(e,t,n){let i=[],r=/^[ \t]*export\s+(?:type\s+)?\{([\s\S]*?)\}\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(r)){if(typeof o.index!="number")continue;let s=o[1]??"",a=o[2]??"",c=He(s).map(u=>Ik(u.trim())).filter(u=>!!u),l=Pi(n,o.index),d=Pi(n,o.index+o[0].length-1);i.push({kind:"named",sourcePath:ft(e,t,a),names:c,startLine:l,endLine:d})}return i}function wk(e,t,n){let i=[],r=/^[ \t]*export\s+\*\s+as\s+(\w+)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(r)){if(typeof o.index!="number")continue;let s=o[2]??"",a=Pi(n,o.index),c=Pi(n,o.index+o[0].length-1);i.push({kind:"star-as",sourcePath:ft(e,t,s),names:[],startLine:a,endLine:c})}return i}function Pk(e,t,n){let i=[],r=/^[ \t]*export\s+\*\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(r)){if(typeof o.index!="number")continue;let s=o[1]??"",a=Pi(n,o.index),c=Pi(n,o.index+o[0].length-1);i.push({kind:"star",sourcePath:ft(e,t,s),names:[],startLine:a,endLine:c})}return i}function Ik(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 i=t.match(/^(\w+)$/);return i?i[1]??null:null}function Pi(e,t){let n=0;for(let i=0;i<t&&i<e.length;i++)e.charCodeAt(i)===10&&n++;return n}function Lk(e,t,n){let i=[];for(let r of n.rootNode.descendantsOfType("export_statement")){let o=Dk(e,t,r);if(o===void 0)continue;let s=r.startPosition.row,a=r.endPosition.row,c=Ek(r,o,s,a);i.push(c)}return i}function Dk(e,t,n){let i=Ke(n,"string");if(!i)return;let r=Ke(i,"string_fragment");if(r)return ft(e,t,r.text)}function Ek(e,t,n,i){let r=Ke(e,"export_clause");if(r){let s=[];for(let a of r.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:i}}return Ke(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:i}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:i}}function Lm(e,t,n){return Qo(e,t,{java:i=>Nk(e,t,i),kotlin:i=>Fk(e,t,i),scala:i=>Tk(e,t,i)},()=>it(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(i,r)=>{let o=i[1]?.trim();return o?_k(e,t,o,r):[]}))}function Nk(e,t,n){let i=ge(n,new Set(["import_declaration"])),r=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.children.some(u=>u.type==="asterisk"),c=o.namedChildren.find(u=>u.type==="scoped_identifier")??o.namedChildren.find(u=>u.type==="identifier");if(!c)continue;let l=c.text;if(s){r.push(An("*",fe(e,l,Ge)));continue}let d=l.split(".").pop()??l;r.push(ue(d,d,fe(e,l,Ge),i))}return r}function Fk(e,t,n){let i=ge(n,new Set(["import_header","import_list"])),r=[];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){r.push(An("*",fe(e,s.text,Ge)));continue}let l=s.text,d=l.split(".").pop()??l,m=c?.namedChild(0)?.text??d;r.push(ue(d,m,fe(e,l,Ge),i))}return r}function Tk(e,t,n){let i=ge(n,new Set(["import_declaration"])),r=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.namedChildren.find(u=>u.type==="namespace_selectors"||u.type==="namespace_wildcard"),a=o.namedChildren.filter(u=>u!==s&&(u.type==="identifier"||u.type==="stable_identifier")),c=a.map(u=>u.text).join(".");if(!c)continue;if(s?.type==="namespace_wildcard"){r.push(An("*",fe(e,c,Ge)));continue}if(s?.type==="namespace_selectors"){for(let u of s.namedChildren)if(u.type==="arrow_renamed_identifier"){let[m,p]=u.namedChildren;if(!m)continue;let f=m.text,g=p?.text??f;if(f==="_")continue;r.push(ue(f,g,fe(e,`${c}.${f}`,Ge),i))}else if(u.type==="identifier"){let m=u.text;r.push(ue(m,m,fe(e,`${c}.${m}`,Ge),i))}continue}let l=a[a.length-1]?.text??c,d=a.slice(0,-1).map(u=>u.text).join(".")||c;r.push(ue(l,l,fe(e,d&&a.length>1?`${d}.${l}`:c,Ge),i))}return r}function _k(e,t,n,i){if(n.includes("{")&&n.includes("}")){let r=n.slice(0,n.indexOf("{")).replace(/\.$/,"").trim(),o=n.slice(n.indexOf("{")+1,n.lastIndexOf("}")).trim();return He(o).flatMap(s=>{let a=s.trim();if(!a)return[];let[c,l]=a.includes("=>")?a.split(/\s*=>\s*/):a.split(/\s+as\s+/),d=c?.trim();if(!d||d==="_")return[];let u=(l??d.split(".").pop()??d).trim(),m=d==="_"?r:`${r}.${d}`.replace(/\.\./g,".");return[wt(e,t,i,m,d,u)]})}return[wt(e,t,i,n,n.split(".").pop()??n,n.split(".").pop()??n)]}function Em(e,t,n){return rt(e,t,i=>Ak(e,t,i),()=>it(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(i,r)=>{let o=i[1]?.trim();return o?He(o).flatMap(s=>{let a=s.trim();if(!a)return[];let[c,l]=a.split(/\s+as\s+/i),d=c?.trim()??a,u=d.split("\\").pop()??d,m=(l??u).trim();return[wt(e,t,r,d,u,m,fe(e,d.replace(/\\/g,"."),Nn))]}):[]}))}function Ak(e,t,n){let i=ge(n,new Set(["namespace_use_declaration"])),r=[],o=(s,a,c)=>{r.push(ue(a,c,fe(e,s.replace(/\\/g,"."),Nn),i))};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:d,localName:u,qualified:m}=Dm(l,c);d&&o(m,d,u)}continue}for(let c of s.namedChildren){if(c.type!=="namespace_use_clause")continue;let{importedName:l,localName:d,qualified:u}=Dm(c,"");l&&o(u,l,d)}}return r}function Dm(e,t){let n=e.namedChildren.find(l=>l.type==="qualified_name"),i=e.namedChildren.filter(l=>l.type==="name"),r="";n?r=n.text:i.length>=1&&(r=i[0].text);let o=n&&i.length>0?i[i.length-1]:null,s=r.split("\\").pop()??r,a=o?.text??s,c=t?`${t}\\${r}`:r;return{importedName:s,localName:a,qualified:c}}function Fm(e,t,n){return rt(e,t,i=>Mk(e,t,i),()=>jk(n).flatMap(i=>Bk(e,t,i,n)))}function Mk(e,t,n){let i=ge(n,new Set(["import_statement","import_from_statement"])),r=[];for(let o of n.rootNode.descendantsOfType("import_statement"))for(let s of o.namedChildren){let a=Nm(s);if(!a)continue;let c=ki(e,t,a.qualifiedName);r.push({importedName:a.qualifiedName,localName:a.localName,sourcePath:c,kind:"namespace",used:i.has(a.localName),usedMembers:[]})}for(let o of n.rootNode.descendantsOfType("import_from_statement")){let s=o.namedChild(0);if(!s)continue;let a=$k(s);if(a===null)continue;let c=ki(e,t,a);for(let l=1;l<o.namedChildCount;l+=1){let d=o.namedChild(l);if(d.type==="wildcard_import"){r.push({importedName:"*",localName:null,sourcePath:c,kind:"side-effect",used:!0,usedMembers:[]});continue}let u=Nm(d);u&&r.push({importedName:u.qualifiedName,localName:u.localName,sourcePath:c,kind:"named",used:i.has(u.localName),usedMembers:[]})}}return r}function Nm(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 $k(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=Ke(e,"import_prefix")?.text??"",n=Ke(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function jk(e){let t=e.split(`
72
+ `),n=[],i=0;for(let r=0;r<t.length;r++){let o=t[r],s=o.trimStart(),a=i;if(i+=o.length+1,!s.startsWith("import ")&&!s.startsWith("from "))continue;let c=o,l=a+o.length,d=br(o);for(;r+1<t.length&&(d>0||c.trimEnd().endsWith("\\"));){r++;let m=t[r];c+=`
73
+ ${m}`,l+=1+m.length,d+=br(m),i+=m.length+1}let u=Ok(c);u&&n.push({...u,start:a,end:l})}return n}function Ok(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 i=n[2].trim();return i.startsWith("(")&&i.endsWith(")")&&(i=i.slice(1,-1).trim()),{kind:"from",module:n[1],clause:i}}function Bk(e,t,n,i){let r=pn(i,n.start,n.end),o=n.clause.replace(/\n/g," ").trim();if(n.kind==="import")return He(o).flatMap(c=>{let l=c.trim().replace(/,$/,"");if(!l)return[];let[d,u]=l.split(/\s+as\s+/),m=d.trim(),p=(u??m.split(".")[0]??m).trim(),f=ki(e,t,m),g=wi(r,p);return[{importedName:m,localName:p,sourcePath:f,kind:"namespace",used:Be(r,p)||g.length>0,usedMembers:g}]});let s=n.module?ki(e,t,n.module):null,a=[];for(let c of He(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[d,u]=l.split(/\s+as\s+/),m=(u??d).trim();a.push({importedName:d.trim(),localName:m,sourcePath:s,kind:"named",used:Be(r,m),usedMembers:[]})}return a}import{basename as Hk}from"path";function Tm(e,t,n){return rt(e,t,i=>qk(e,t,i),()=>Vk(e,t,n))}function Vk(e,t,n){return it(n,/^[ \t]*(require_relative|require)\s+["']([^"']+)["']\s*$/gm,(i,r)=>{let o=i[1],s=i[2];if(!o||!s)return[];let a=o==="require_relative"?Go(e,t,s):null;if(a){let c=_m(s);return[Gt(c,c,a,Be(r,c))]}return[_n(s,a)]})}function qk(e,t,n){let i=ge(n,new Set([])),r=[],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 u=l.namedChildren.find(p=>p.type==="string_content")?.text;if(!u)continue;let m=a.text==="require_relative"?Go(e,t,u):null;if(m){let p=_m(u);r.push(ue(p,p,m,i))}else r.push(_n(u,m))}return r}function _m(e){return To(Hk(e).replace(/\.[^.]+$/,""),/_/)}function Am(e,t,n){return rt(e,t,i=>Uk(e,t,i),()=>it(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(i,r)=>{let o=i[1]?.trim();return o?zk(e,t,o,r):[]}))}function Uk(e,t,n){let i=ge(n,new Set(["use_declaration"])),r=[];for(let o of n.rootNode.descendantsOfType("use_declaration")){let s=o.namedChild(0);if(s)for(let a of Sr(s,"")){if(!a.importedName||a.importedName==="*")continue;let c=Wt(e,t,a.qualifiedName)??Wt(e,t,a.qualifiedName.split("::").slice(0,-1).join("::"));r.push(ue(a.importedName,a.localName,c,i))}}return r}function Sr(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":{let n=e.text;return[{qualifiedName:Yo(t,n),importedName:n,localName:n}]}case"scoped_identifier":{let n=e.text,i=n.split("::").pop()??n;return[{qualifiedName:Yo(t,n),importedName:i,localName:i}]}case"scoped_use_list":{let n=e.namedChild(0),i=e.namedChild(1);if(!n||!i)return[];let r=Yo(t,n.text),o=[];for(let s of i.namedChildren)o.push(...Sr(s,r));return o}case"use_list":{let n=[];for(let i of e.namedChildren)n.push(...Sr(i,t));return n}case"use_as_clause":{let n=e.namedChild(0),i=e.namedChild(1);if(!n||!i)return[];let r=Sr(n,t),o=i.text;return r.map(s=>({...s,localName:o}))}case"use_wildcard":{let n=e.namedChild(0),i=n?n.text:"";return[{qualifiedName:Yo(t,`${i}::*`),importedName:"*",localName:"*"}]}default:return[]}}function Yo(e,t){return e?t?`${e}::${t}`:e:t}function zk(e,t,n,i){let r=n.trim();if(r.includes("{")&&r.includes("}")){let d=r.slice(0,r.indexOf("{")).replace(/::$/,"").trim(),u=r.slice(r.indexOf("{")+1,r.lastIndexOf("}")).trim();return He(u).flatMap(m=>{let p=m.trim();if(!p||p==="self")return[];let[f,g]=p.split(/\s+as\s+/),b=f?.trim();if(!b)return[];let x=(g??b.split("::").pop()??b).trim(),S=`${d}::${b}`.replace(/::::/g,"::");return[wt(e,t,i,S,b.split("::").pop()??b,x,Wt(e,t,d))]})}let[o,s]=r.split(/\s+as\s+/),a=o?.trim()??r,c=(s??a.split("::").pop()??a).trim(),l=Wt(e,t,a)??Wt(e,t,a.split("::").slice(0,-1).join("::"));return[wt(e,t,i,a,a.split("::").pop()??a,c,l)]}function Mm(e,t,n){let i=Pe(e,t);if(i)return Wk(e,t,i);let r=[];for(let o of n.matchAll(/^[ \t]*pub\s+use\s+(.+?)\s*;$/gm)){let s=o[1]?.trim();s&&r.push(...Kk(e,t,s))}return r}function Wk(e,t,n){let i=[];for(let r of n.rootNode.descendantsOfType("use_declaration")){if(!Gk(r))continue;let o=r.namedChildren.find(s=>s.type!=="visibility_modifier");if(o)for(let s of Sr(o,""))s.importedName&&i.push(fc(e,t,s.qualifiedName))}return i}function Gk(e){for(let t of e.children)if(t.type==="visibility_modifier"&&t.text.startsWith("pub"))return!0;return!1}function Kk(e,t,n){let i=n.trim();if(i.includes("{")&&i.includes("}")){let r=i.slice(0,i.indexOf("{")).replace(/::$/,"").trim(),o=i.slice(i.indexOf("{")+1,i.lastIndexOf("}")).trim();return He(o).flatMap(s=>{let a=s.trim();if(!a||a==="self")return[];let[c]=a.split(/\s+as\s+/),l=`${r}::${c?.trim()??a}`.replace(/::::/g,"::");return[fc(e,t,l)]})}return[fc(e,t,i)]}function fc(e,t,n){return{specifier:n,sourcePath:Wt(e,t,n)??Wt(e,t,n.split("::").slice(0,-1).join("::"))}}function fn({language:e,extensions:t,imports:n,parseImports:i}){return{language:e,extensions:t,capabilities:{imports:n},parseImports:i}}function $m(e,t){let n=t.toLowerCase();for(let i of e)for(let r of i.extensions)if(n.endsWith(r))return i;return null}var Jk={language:"javascript",extensions:En,capabilities:{imports:"ast-with-regex-fallback",reExports:"ast-with-regex-fallback"},parseImports:mc,parseReExports:pc},Xk=fn({language:"python",extensions:Vo,imports:"ast-with-regex-fallback",parseImports:Fm}),Qk=fn({language:"jvm",extensions:Ge,imports:"ast-dispatch-with-regex-fallback",parseImports:Lm}),Yk={language:"rust",extensions:qo,capabilities:{imports:"ast-with-regex-fallback",exports:"ast-with-regex-fallback"},parseImports:Am,parseExports:Mm},Zk=fn({language:"ruby",extensions:Uo,imports:"ast-with-regex-fallback",parseImports:Tm}),ew=fn({language:"c/cpp",extensions:zo,imports:"ast-with-regex-fallback",parseImports:bm}),tw=fn({language:"dotnet",extensions:dn,imports:"ast-dispatch-with-regex-fallback",parseImports:wm}),nw={language:"dart",extensions:Wo,capabilities:{imports:"regex-only",exports:"regex-only"},parseImports:Rm,parseExports:km},iw=fn({language:"php",extensions:Nn,imports:"ast-with-regex-fallback",parseImports:Em}),rw=fn({language:"clojure",extensions:Ri,imports:"regex-only",parseImports:xm}),ow=[Jk,Xk,Qk,Yk,Zk,ew,tw,nw,iw,rw];function Zo(e){return $m(ow,e)}var gc={clearGroups:["whole-project","source-file"]},sw=W("source-imports",gc),aw=W("source-exports",gc),cw=W("source-reexports",gc),jm=pe({kind:"source-imports",serialize:lw,deserialize:uw}),Om=pe({kind:"source-reexports",serialize:dw,deserialize:mw});function xr(e,t){let n=pt(t);return cw.get(e,n,()=>{let i=Zo(n);if(!i?.parseReExports)return[];let r=M(e,n);if(!r)return[];let o=re(e,n,r),s=ic(e),a=Om.read(e,n,o);if(a?.resolutionFingerprint===s)return a.reExports;let c=i.parseReExports(e,n,r);return Om.write(e,n,o,{resolutionFingerprint:s,reExports:c}),c})}function oe(e,t){let n=pt(t);return sw.get(e,n,()=>{let i=Zo(n);if(!i)return[];let r=M(e,n);if(!r)return[];let o=re(e,n,r),s=ic(e),a=jm.read(e,n,o);if(a?.resolutionFingerprint===s)return a.imports;let c=i.parseImports(e,n,r);return jm.write(e,n,o,{resolutionFingerprint:s,imports:c}),c})}function es(e,t){let n=pt(t);return aw.get(e,n,()=>{let i=Zo(n);if(!i?.parseExports)return[];let r=M(e,n);return r?i.parseExports(e,n,r):[]})}function lw(e){return JSON.stringify(e)}function uw(e){try{let t=JSON.parse(e);return!kt(t)||typeof t.resolutionFingerprint!="string"||!Array.isArray(t.imports)?null:{resolutionFingerprint:t.resolutionFingerprint,imports:t.imports}}catch{return null}}function dw(e){return JSON.stringify(e)}function mw(e){try{let t=JSON.parse(e);return!kt(t)||typeof t.resolutionFingerprint!="string"||!Array.isArray(t.reExports)?null:{resolutionFingerprint:t.resolutionFingerprint,reExports:t.reExports}}catch{return null}}function gt(e){return{forFile(t,n){return Bm(e,t,n)},forFiles(t,n){let i=new Map;for(let r of t)i.set(r,Bm(e,r,n));return i}}}function Bm(e,t,n){let i={file:t},r=n.facts||n.identifiers;if(n.text&&(i.text=M(e,t)),n.lines&&(i.lines=Ye(e,t)),n.ast&&(i.ast=Pe(e,t)),n.imports&&(i.imports=oe(e,t)),n.reexports&&(i.reexports=xr(e,t)),r){let o=X(e,t);n.facts&&(i.facts=o),n.identifiers&&o&&(i.identifiers=o.fileIdentifiers,i.identifierLineMap=o.identifierLineMap)}return i}var pw={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function Ie(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],i=t[1],r=e.slice(n.length+1+i.length+1),o;if(r.startsWith("`")){let l=r.indexOf("`",1);l===-1?(o=r.slice(1),r=""):(o=r.slice(1,l),r=r.slice(l+2))}else{let l=r.indexOf(" ");l===-1?(o=r,r=""):(o=r.slice(0,l),r=r.slice(l+1))}let s,a=r.indexOf(" ");a===-1?(s=r,r=""):(s=r.slice(0,a),r=r.slice(a+1));let c=fw(r);return{scheme:n,manager:i,packageName:o,version:s,descriptors:c,raw:e}}function It(e){let t=Ie(e);if("kind"in t)return null;for(let n=t.descriptors.length-2;n>=0;n--){let i=t.descriptors[n];if(i?.suffix==="type")return i.name}return null}function fw(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||Hm(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 i;if(e[n]==="`"){let o=e.indexOf("`",n+1);if(o===-1){i=e.slice(n+1),t.push({name:i,suffix:"term"});break}i=e.slice(n+1,o),n=o+1}else{let o=n;for(;n<e.length&&!Hm(e[n]);)n++;i=e.slice(o,n)}if(n>=e.length){i&&t.push({name:i,suffix:"term"});break}let r=e[n];if(r==="("){let o=e.indexOf(")",n+1);o!==-1&&e[o+1]==="."?(t.push({name:i,suffix:"method"}),n=o+2):o!==-1?(t.push({name:i,suffix:"method"}),n=o+1):(t.push({name:i,suffix:"term"}),n++)}else{let o=pw[r];o&&t.push({name:i,suffix:o}),n+=1}}return t}function Hm(e){return e==="/"||e==="#"||e==="."||e==="("||e==="["||e===":"||e==="!"}function v(e){let t=Ie(e);if("kind"in t&&t.kind==="local")return`local:${t.id}`;let n=t;if(n.descriptors.length===0)return n.raw;let i=[];for(let r of n.descriptors){let o=gw(r);o&&i.push(o)}return i.join(":")}function gw(e){let t=e.suffix==="namespace"?hw(e.name):e.name;return t?e.suffix==="method"?`${t}()`:t:""}function hw(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=Ie(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 se(e){let t=Ie(e);if("kind"in t&&t.kind==="local")return null;let n=t;return n.descriptors[n.descriptors.length-1]?.suffix??null}function he(e){return e.endsWith("().")||se(e)==="method"}function de(e){let t=se(e);return t==="method"||t==="term"}function gn(e){return se(e)==="namespace"}var yw=/^rust-analyzer\b.*[\s/]impl#\[[^\]]+\]\[[^\]]+\]/;function ts(e){return yw.test(e)}var bw=new Set(["test","tests","_tests"]);function Ii(e){let t=Ie(e);if("kind"in t)return!1;for(let n=0;n<t.descriptors.length-1;n+=1){let i=t.descriptors[n];if(i?.suffix==="namespace"&&i.name&&bw.has(i.name))return!0}return!1}function Vm(e,t){let n=Ie(e),i=Ie(t);if("kind"in n||"kind"in i)return!1;let r=n.descriptors,o=i.descriptors;if(o.length!==r.length+1)return!1;for(let s=0;s<r.length;s++){let a=r[s],c=o[s];if(a.name!==c.name||a.suffix!==c.suffix)return!1}return!0}function qm(e,t){let n=Ie(e),i=Ie(t);if("kind"in n||"kind"in i)return!1;let r=n.descriptors,o=i.descriptors;if(o.length<=r.length)return!1;for(let s=0;s<r.length;s++){let a=r[s],c=o[s];if(a.name!==c.name||a.suffix!==c.suffix)return!1}return!0}function Li(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
54
74
  FROM global_symbols gs
55
75
  JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
56
76
  JOIN documents d ON der.document_id = d.id
57
77
  WHERE ${t.where}
58
78
  ${e.pathExclusionsFor("d")}
59
- ${ld(t.orderBy)}
60
- ${ud(t.limit)}`,...t.params??[])}function ur(e,t){return e.all(`SELECT
79
+ ${zm(t.orderBy)}
80
+ ${Wm(t.limit)}`,...t.params??[])}function Di(e,t){return e.all(`SELECT
61
81
  gs.id,
62
82
  gs.symbol,
63
83
  c.document_id,
@@ -74,8 +94,8 @@ import{program as ra}from"commander";import{realpathSync as jb}from"fs";import{f
74
94
  AND ${t.where}
75
95
  ${e.pathExclusionsFor("d")}
76
96
  GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name, gs.documentation
77
- ${ld(t.orderBy)}
78
- ${ud(t.limit)}`,...t.params??[])}function ld(e){return e?`ORDER BY ${e}`:""}function ud(e){return typeof e=="number"?`LIMIT ${e}`:""}function mn(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 pn(e){if(!e)return null;let t=cd(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(cd(r)??r).replace(/\n/g," ")}function cd(e){return/^```(?:\w+)?\s*\n?([\s\S]*?)\n?```/.exec(e.trimStart())?.[1]?.trim()||null}function CC(e){if(pt(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 fn(e,t,n={}){let r=new Map;for(let o of t)e.length>0&&!CC(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 vC=q("file-definitions",{clearGroups:["definition-catalog"]}),dd=new WeakMap;function G(e,t){return vC.get(e,t,()=>{let n=RC(e,t);if(n)return n;let r=fn(LC(e,t),IC(e,t),{sort:!0}),i=yd(e,t,r.map(fd)),o=Kr(e),s=T(e,t);return o&&s&&ne(e,"file-definitions",t,X(e,t,s),JSON.stringify({projectFingerprint:o,definitions:i.map(a=>({...a}))})),i})}function RC(e,t){let n=Kr(e);if(!n)return null;let r=T(e,t);if(!r)return null;let i=te(e,"file-definitions",t,X(e,t,r));return i?kC(i,n,t):null}function kC(e,t,n){try{let r=JSON.parse(e);if(!un(r)||r.projectFingerprint!==t||!Array.isArray(r.definitions))return null;let i=[];for(let o of r.definitions){let s=wC(o,n);if(!s)return null;i.push(s)}return i}catch{return null}}function wC(e,t){return!un(e)||typeof e.symbolId!="number"||typeof e.symbol!="string"||typeof e.documentId!="number"||typeof e.startLine!="number"||typeof e.endLine!="number"||e.relativePath!==t||typeof e.leaf!="string"||typeof e.parentTypeName!="string"&&e.parentTypeName!==null||typeof e.isFunctionLike!="boolean"||typeof e.isTypeLike!="boolean"||typeof e.kind!="number"&&e.kind!==null||typeof e.documentation!="string"&&e.documentation!==null||typeof e.enclosingSymbol!="string"&&e.enclosingSymbol!==null?null:{symbolId:e.symbolId,symbol:e.symbol,documentId:e.documentId,startLine:e.startLine,endLine:e.endLine,relativePath:e.relativePath,leaf:e.leaf,parentTypeName:e.parentTypeName,isFunctionLike:e.isFunctionLike,isTypeLike:e.isTypeLike,kind:e.kind,documentation:e.documentation,enclosingSymbol:e.enclosingSymbol}}function LC(e,t){return e.all(`SELECT
97
+ ${zm(t.orderBy)}
98
+ ${Wm(t.limit)}`,...t.params??[])}function zm(e){return e?`ORDER BY ${e}`:""}function Wm(e){return typeof e=="number"?`LIMIT ${e}`:""}function Mn(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 $n(e){if(!e)return null;let t=Um(e);if(t)return t.replace(/\n/g," ");let n=e.indexOf("|");if(n===-1)return e.replace(/\n/g," ");let i=e.slice(n+1);return(Um(i)??i).replace(/\n/g," ")}function Um(e){return/^```(?:\w+)?\s*\n?([\s\S]*?)\n?```/.exec(e.trimStart())?.[1]?.trim()||null}function Sw(e){if(It(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 jn(e,t,n={}){let i=new Map;for(let o of t)e.length>0&&!Sw(o)||i.set(o.id,o);for(let o of e)i.set(o.id,o);let r=[...i.values()];return n.sort?r.sort((o,s)=>o.start_line-s.start_line||o.end_line-s.end_line||o.symbol.localeCompare(s.symbol)):r}var xw=W("file-definitions",{clearGroups:["definition-catalog"]}),Cw=W("file-function-like-definitions",{clearGroups:["definition-catalog"]}),Gm=new WeakMap;function Q(e,t){return xw.get(e,t,()=>{let n=Qm(e,t);if(n)return n;let i=Ym(e,t),r=In(e),o=gt(e).forFile(t,{text:!0}).text;return r&&o&&Xm.write(e,t,re(e,t,o),{projectFingerprint:r,definitions:i.map(s=>({...s}))}),i})}function vw(e,t){return Cw.get(e,t,()=>{let n=Qm(e,t);return n?n.filter(i=>i.isFunctionLike):Ym(e,t,i=>i.isFunctionLike)})}var Xm=pe({kind:"file-definitions",serialize:Rw,deserialize:kw});function Qm(e,t){let n=In(e);if(!n)return null;let i=gt(e).forFile(t,{text:!0}).text;if(!i)return null;let r=Xm.read(e,t,re(e,t,i));return r?ww(r,n,t):null}function Rw(e){return JSON.stringify(e)}function kw(e){try{let t=JSON.parse(e);return!kt(t)||typeof t.projectFingerprint!="string"||!Array.isArray(t.definitions)?null:{projectFingerprint:t.projectFingerprint,definitions:t.definitions}}catch{return null}}function ww(e,t,n){if(e.projectFingerprint!==t)return null;let i=[];for(let r of e.definitions){let o=Pw(r,n);if(!o)return null;i.push(o)}return i}function Pw(e,t){return!kt(e)||typeof e.symbolId!="number"||typeof e.symbol!="string"||typeof e.documentId!="number"||typeof e.startLine!="number"||typeof e.endLine!="number"||e.relativePath!==t||typeof e.leaf!="string"||typeof e.parentTypeName!="string"&&e.parentTypeName!==null||typeof e.isFunctionLike!="boolean"||typeof e.isTypeLike!="boolean"||typeof e.kind!="number"&&e.kind!==null||typeof e.documentation!="string"&&e.documentation!==null||typeof e.enclosingSymbol!="string"&&e.enclosingSymbol!==null?null:{symbolId:e.symbolId,symbol:e.symbol,documentId:e.documentId,startLine:e.startLine,endLine:e.endLine,relativePath:e.relativePath,leaf:e.leaf,parentTypeName:e.parentTypeName,isFunctionLike:e.isFunctionLike,isTypeLike:e.isTypeLike,kind:e.kind,documentation:e.documentation,enclosingSymbol:e.enclosingSymbol}}function Ym(e,t,n){let i=jn(Iw(e,t),Lw(e,t),{sort:!0}).map(Zm);return n&&(i=i.filter(n)),np(e,t,i)}function Iw(e,t){return e.all(`SELECT
79
99
  gs.id,
80
100
  gs.symbol,
81
101
  der.document_id,
@@ -91,7 +111,7 @@ import{program as ra}from"commander";import{realpathSync as jb}from"fs";import{f
91
111
  JOIN documents d ON der.document_id = d.id
92
112
  WHERE d.relative_path = ?
93
113
  ${e.symbolNoiseFor("gs")}
94
- ORDER BY der.start_line, der.end_line`,t)}function IC(e,t){return e.all(`SELECT
114
+ ORDER BY der.start_line, der.end_line`,t)}function Lw(e,t){return e.all(`SELECT
95
115
  gs.id,
96
116
  gs.symbol,
97
117
  c.document_id,
@@ -110,7 +130,7 @@ import{program as ra}from"commander";import{realpathSync as jb}from"fs";import{f
110
130
  AND m.role = 1
111
131
  ${e.symbolNoiseFor("gs")}
112
132
  GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
113
- ORDER BY start_line, end_line`,t)}function fd(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:pt(e.symbol),isFunctionLike:oe(e.symbol),isTypeLike:re(e.symbol)==="type",kind:e.kind??null,documentation:e.documentation??null,enclosingSymbol:e.enclosing_symbol??null}}function ft(e,t={}){return gn(e,t.scope)}function gn(e,t){return O(e,{scope:t,includeIgnored:!1}).flatMap(n=>G(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function gd(e,t){let n=md(DC(e,t.scope,t.sqlPrefilter)),r=md(PC(e,t.scope,t.sqlPrefilter)),i=new Set([...n.keys(),...r.keys()]),o=[];for(let s of[...i].sort()){if(e.isIgnored(s))continue;let a=fn(n.get(s)??[],r.get(s)??[],{sort:!0}).filter(c=>t.symbolMatches(c.symbol));a.length!==0&&o.push(...yd(e,s,a.map(fd)))}return o}function DC(e,t,n){let r=t?"AND d.relative_path LIKE ?":"",i=n==="callable"?`AND ${hd("gs")}`:"",o=t?[`%${t}%`]:[];return e.all(`SELECT
133
+ ORDER BY start_line, end_line`,t)}function Zm(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:It(e.symbol),isFunctionLike:de(e.symbol),isTypeLike:se(e.symbol)==="type",kind:e.kind??null,documentation:e.documentation??null,enclosingSymbol:e.enclosing_symbol??null}}function Lt(e,t={}){return hc(e,t.scope)}function hc(e,t){return O(e,{scope:t,includeIgnored:!1}).flatMap(n=>Q(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function ep(e,t){return O(e,{scope:t,includeIgnored:!1}).flatMap(n=>vw(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function Cr(e,t){let n=Km(Dw(e,t.scope,t.sqlPrefilter)),i=Km(Ew(e,t.scope,t.sqlPrefilter)),r=new Set([...n.keys(),...i.keys()]),o=[];for(let s of[...r].sort()){if(e.isIgnored(s))continue;let a=jn(n.get(s)??[],i.get(s)??[],{sort:!0}).filter(c=>t.symbolMatches(c.symbol));a.length!==0&&o.push(...np(e,s,a.map(Zm)))}return o}function Dw(e,t,n){let i=t?"AND d.relative_path LIKE ?":"",r=n?`AND ${tp("gs",n)}`:"",o=t?[`%${t}%`]:[];return e.all(`SELECT
114
134
  gs.id,
115
135
  gs.symbol,
116
136
  der.document_id,
@@ -126,10 +146,10 @@ import{program as ra}from"commander";import{realpathSync as jb}from"fs";import{f
126
146
  JOIN documents d ON der.document_id = d.id
127
147
  WHERE 1 = 1
128
148
  ${e.pathExclusionsFor("d")}
129
- ${r}
130
149
  ${i}
150
+ ${r}
131
151
  ${e.symbolNoiseFor("gs")}
132
- ORDER BY d.relative_path, der.start_line, der.end_line`,...o)}function PC(e,t,n){let r=t?"AND d.relative_path LIKE ?":"",i=n==="callable"?`AND ${hd("gs")}`:"",o=t?[`%${t}%`]:[];return e.all(`SELECT
152
+ ORDER BY d.relative_path, der.start_line, der.end_line`,...o)}function Ew(e,t,n){let i=t?"AND d.relative_path LIKE ?":"",r=n?`AND ${tp("gs",n)}`:"",o=t?[`%${t}%`]:[];return e.all(`SELECT
133
153
  gs.id,
134
154
  gs.symbol,
135
155
  c.document_id,
@@ -146,15 +166,14 @@ import{program as ra}from"commander";import{realpathSync as jb}from"fs";import{f
146
166
  JOIN documents d ON c.document_id = d.id
147
167
  WHERE m.role = 1
148
168
  ${e.pathExclusionsFor("d")}
149
- ${r}
150
169
  ${i}
170
+ ${r}
151
171
  ${e.symbolNoiseFor("gs")}
152
172
  GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
153
- ORDER BY d.relative_path, start_line, end_line`,...o)}function hd(e){return`(${e}.symbol LIKE '%().' OR ${e}.symbol LIKE '%()')`}function md(e){let t=new Map;for(let n of e){let r=t.get(n.relative_path);r?r.push(n):t.set(n.relative_path,[n])}return t}function fo(e,t,n={}){if(t.length===0)return[];let r=t.flatMap(i=>G(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:mn(pn(i.documentation)),relativePath:i.relativePath,enclosingSymbol:i.enclosingSymbol}))}function ya(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 Ge(e,t){let n=dd.get(e);return n||(n=ya(e),dd.set(e,n)),n.get(t)??null}function hn(e,t){let n=G(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 yd(e,t,n){let r=T(e,t),i=pa(e,t);return i?AC(n,i,r):r?NC(n,r):n}function NC(e,t){let n=t.split(/\r?\n/),r=EC(e,n),i=TC(e,r),o=_C(i,n);return FC(e,o)}function EC(e,t){let n=e.some(i=>go(i.symbol))?OC(t):null,r=new Map;for(let i of e)r.set(i.symbolId,MC(t,n,i));return r}function TC(e,t){return e.filter(n=>go(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 _C(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:jC(t,i.definition,i.startLine,s)})}return n}function FC(e,t){return e.map(n=>{let r=t.get(n.symbolId);return r?{...n,startLine:r.startLine,endLine:r.endLine}:n})}function AC(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(!$C(i)||!i.leaf)return pd(i,n);let o=r.get(i.leaf);if(!o||o.length===0)return pd(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 $C(e){return go(e.symbol)?!0:re(e.symbol)==="term"&&pt(e.symbol)===null}function pd(e,t){if(!t||!e.leaf||re(e.symbol)!=="term"||pt(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 MC(e,t,n){if(!go(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 OC(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 jC(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=BC(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 BC(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 go(e){return e.includes("().")}function ho(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 ev}from"fs";import{basename as bd,isAbsolute as tv,join as nv}from"path";function B(e,t){let n=mr(e,t.trim());if(n)return n;let r=GC(e,t);if(r)return r;let i=HC(e,t);return i||WC(e,t)}function HC(e,t){let n=Sa(t),r=ba(n);if(!r)return null;let i=`%${r.path}%`,o=r.leaf,a=VC(e,i,o,n)[0];return a?hn(e,a):null}function VC(e,t,n,r){let i=fn([],[...qC(e,t,n),...UC(e,t,n)]).filter(o=>!e.isIgnored(o.relative_path)).filter(o=>dr(o,r)>1);return i.sort((o,s)=>dr(s,r)-dr(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 qC(e,t,n){return lr(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function UC(e,t,n){return ur(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function WC(e,t){let n=Sa(t),r=YC(t),i=XC(e,r),o=ZC(i,t,n);if(o&&!e.isIgnored(o.relative_path))return hn(e,o);let s=null;for(let a of i){if(e.isIgnored(a.relative_path))continue;let c=QC(a,t,n,r);c<=0||(!s||c>s.score)&&(s={row:a,score:c})}return s?hn(e,s.row):null}function GC(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=zC(e,r,s,a)??JC(e,r,s,a);return c&&!e.isIgnored(c.relative_path)?hn(e,c):null}function zC(e,t,n,r){return lr(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 JC(e,t,n,r){return ur(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 mr(e,t){let r=lr(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, der.start_line",limit:1})[0]??ur(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, start_line",limit:1})[0];return!r||e.isIgnored(r.relative_path)?null:hn(e,r)}function yo(e,t){if("symbol"in t&&"relativePath"in t)return t;let n=KC(e,t.symbolId)[0];return n?hn(e,n):null}function KC(e,t){let n=lr(e,{where:"gs.id = ?",params:[t],orderBy:"der.start_line, der.end_line"}),r=ur(e,{where:"gs.id = ?",params:[t],orderBy:"start_line, end_line"});return fn(n,r)}function XC(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(`
154
- AND `),o=lr(e,{where:i,params:r,limit:200}),s=ur(e,{where:i,params:r,limit:200});return fn(o,s)}function QC(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=b(e.symbol),m=$(e.symbol),p=e.display_name??"",g=e.symbol.toLowerCase(),y=d.toLowerCase(),h=m.toLowerCase(),x=p.toLowerCase(),v=e.relative_path.toLowerCase(),R=/[/:.]/.test(n),L=ba(n),S=L?.leaf.toLowerCase(),C=0;return(u===i||u===o)&&(C+=1150),(d===i||d===o)&&(C+=1100),p===s&&(C+=1180),m===s&&(C+=1160),(`${m}()`===i||`${m}()`===o)&&(C+=955),(g===a||g===c)&&(C+=1e3),(y===a||y===c)&&(C+=950),(v===a||v===c)&&(C+=925),(v.endsWith(`/${c}`)||v.endsWith(`/${a}`))&&(C+=875),x===l&&(C+=850),h===l&&(C+=825),(`${h}()`===a||`${h}()`===c)&&(C+=820),(y.endsWith(`:${c}`)||y.endsWith(`:${l}`)||y.endsWith(`:${l}()`))&&(C+=800),g.includes(c)&&(C+=120),y.includes(c)&&(C+=140),v.includes(c)&&(C+=140),x.includes(c)&&(C+=110),r.every(P=>{let D=P.toLowerCase();return g.includes(D)||y.includes(D)||v.includes(D)||x.includes(D)})&&(C+=100+r.length*15),L&&v.includes(L.path.toLowerCase())&&(C+=360,S&&(h===S||`${h}()`===S||`${h}()`==`${S}()`)&&(C+=700),ie(e.symbol)&&(C+=180)),oe(e.symbol)&&h===l&&(C+=60),!R&&Vt(e.symbol)&&(C-=160),C-=Math.min(50,Math.max(0,e.end_line-e.start_line)),C}function ba(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 Sa(e){return e.trim().replace(/\(\)$/,"").replace(/\(.*$/,"")}function YC(e){let t=Sa(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 ZC(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||dr(o,n)>1||o.relative_path===r});return i.length===0?null:(i.sort((o,s)=>dr(s,n)-dr(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 dr(e,t){let n=ba(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:ie(e.symbol)?pt(e.symbol)===null?5:4:pt(e.symbol)===null?3:2:0}function Fe(e,t){let n=Sd(e,t,{allowMultiple:!1})[0]?.relativePath;return n||rv(e,t)}function pr(e,t){return Sd(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function rv(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=tv(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,i=nv(e.config.projectRoot,r);return ev(i)?r:null}function Sd(e,t,n){let r=xd(t);if(!r)return[];let i=O(e,{includeIgnored:!1}).map(a=>({relativePath:a,score:iv(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 iv(e,t){let n=xd(e),r=bd(n),i=bd(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 xd(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}import{basename as Pw}from"path";import{existsSync as bo}from"fs";import{basename as ov,dirname as qt,extname as Dt,join as rt,relative as Yr,resolve as ze}from"path";var sv=Z("indexed-paths",{clearGroups:[]}),av=Z("indexed-path-digest",{clearGroups:[]}),yn=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],So=[".py",".pyi"],je=[".java",".scala",".kt",".kts"],xo=[".rs"],Co=[".rb"],vo=[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],Ut=[".cs",".vb"],Ro=[".dart"],bn=[".php"],cv=new Set(yn),xa=new Set(So),Cd=new Set(je),Ca=new Set(xo),va=new Set(Co),vd=new Set(vo),Rd=new Set(Ut),Ra=new Set(Ro),kd=new Set(bn),lv=[{extensions:yn,lookup:cv},{extensions:So,lookup:xa},{extensions:je,lookup:Cd},{extensions:xo,lookup:Ca},{extensions:Co,lookup:va},{extensions:vo,lookup:vd},{extensions:Ut,lookup:Rd},{extensions:Ro,lookup:Ra},{extensions:bn,lookup:kd}];function Wt(e,t){return t.has(Dt(e).toLowerCase())}function uv(e){return Wt(e,xa)}function dv(e){return Wt(e,Cd)}function mv(e){return Wt(e,Ca)}function pv(e){return Wt(e,va)}function fv(e){return Wt(e,vd)}function gv(e){return Wt(e,Rd)}function wd(e){return Dt(e).toLowerCase()===".vb"}function hv(e){return Wt(e,Ra)}function yv(e){return Wt(e,kd)}function ka(e){let t=Dt(e).toLowerCase();for(let n of lv)if(n.lookup.has(t))return n.extensions;return yn}function bv(e){return dv(e)||gv(e)||yv(e)}function ot(e,t,n){return uv(t)?fr(e,t,n):mv(t)?Pt(e,t,n):pv(t)?ko(e,t,n):fv(t)?wo(e,t,n):bv(t)?se(e,n.replace(/\\/g,"."),ka(t)):hv(t)?Lo(e,t,n):Sv(e,t,n)}function Sv(e,t,n){if(!n.startsWith(".")&&!n.startsWith("/"))return null;let r=qt(rt(e.config.projectRoot,t)),i=ze(r,n),o=gr(e);for(let s of kv(i)){let a=it(Yr(e.config.projectRoot,s));if(o.has(a)||bo(s))return a}return it(Yr(e.config.projectRoot,i))}function fr(e,t,n){let r=gr(e),i;if(n.startsWith(".")){let o=n.match(/^(\.+)(.*)$/);if(!o)return null;let s=o[1].length,a=o[2].replace(/^\./,""),c=qt(rt(e.config.projectRoot,t));for(let l=1;l<s;l++)c=qt(c);i=a?ze(c,a.replace(/\./g,"/")):c}else i=ze(e.config.projectRoot,n.replace(/\./g,"/"));for(let o of xv(i)){let s=it(Yr(e.config.projectRoot,o));if(r.has(s)||bo(o))return s}return null}function Pt(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=qt(rt(e.config.projectRoot,t)),o;return r.startsWith("crate::")?o=ze(e.config.projectRoot,"src",r.slice(7).replace(/::/g,"/")):r.startsWith("self::")?o=ze(i,r.slice(6).replace(/::/g,"/")):o=ze(qt(i),r.slice(7).replace(/::/g,"/")),wa(e,Cv(o))}function ko(e,t,n){let r=qt(rt(e.config.projectRoot,t)),i=ze(r,n);return wa(e,vv(i))}function wo(e,t,n){let r=qt(rt(e.config.projectRoot,t)),i=[ze(r,n),ze(e.config.projectRoot,n),ze(e.config.projectRoot,"include",n),ze(e.config.projectRoot,"src",n)];return wa(e,i)}function se(e,t,n){let r=gr(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=>ov(u)===`${s}${c}`);if(l)return l}let a=[...r].filter(c=>n.includes(Dt(c).toLowerCase())).filter(c=>c.includes(`/${o}/`)||c.includes(`/${s}/`)).sort((c,l)=>c.localeCompare(l));return a.length===1?a[0]:null}function Lo(e,t,n){let r=gr(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=it(c.startsWith("lib/")?c:`lib/${c}`);return r.has(l)?l:null}let i=qt(rt(e.config.projectRoot,t)),o=ze(i,n);for(let s of Rv(o)){let a=it(Yr(e.config.projectRoot,s));if(r.has(a)||bo(s))return a}return null}function xv(e){let t=Dt(e);return xa.has(t)?[e]:[`${e}.py`,`${e}.pyi`,rt(e,"__init__.py"),rt(e,"__init__.pyi")]}function wa(e,t){let n=gr(e);for(let r of t){let i=it(Yr(e.config.projectRoot,r));if(n.has(i)||bo(r))return i}return null}function Cv(e){let t=Dt(e);return Ca.has(t)?[e]:[`${e}.rs`,rt(e,"mod.rs")]}function vv(e){let t=Dt(e);return va.has(t)?[e]:[`${e}.rb`,rt(e,"index.rb")]}function Rv(e){let t=Dt(e);return Ra.has(t)?[e]:[`${e}.dart`,e]}function kv(e){let t=Dt(e),n=new Set;if(t){n.add(e);for(let r of yn)n.add(e.slice(0,-t.length)+r)}else for(let r of yn)n.add(`${e}${r}`),n.add(rt(e,`index${r}`));return[...n]}function gr(e){return sv.get(e,()=>new Set(O(e,{includeIgnored:!1}).map(it)))}function La(e){return av.get(e,()=>er([...gr(e)].sort().join(`
155
- `)))}function it(e){return e.replace(/\\/g,"/")}import{basename as Id}from"path";function Sn(e){return e.replace(/'''[\s\S]*?'''/g,Gt).replace(/"""[\s\S]*?"""/g,Gt).replace(/#.*$/gm,Gt).replace(/\/\/.*$/gm,Gt).replace(/\/\*[\s\S]*?\*\//g,Gt).replace(/`(?:\\[\s\S]|[^`])*`/g,Gt).replace(/'(?:\\.|[^'\\\r\n])*'/g,Gt).replace(/"(?:\\.|[^"\\\r\n])*"/g,Gt)}function Gt(e){return e.replace(/[^\r\n]/g," ")}var Dq=cn("stripped-lines",{clearGroups:["whole-project","source-file"]});Bt({name:"stripped-source-singleton",groups:["whole-project","source-file"],clearAll:()=>{Io=null,Zr=""},clearFile:()=>{Io=null,Zr=""}});var Io=null,Zr="";function wv(e){return Io===e||(Io=e,Zr=Sn(e)),Zr}function zt(e,t,n){let r=wv(e);return`${r.slice(0,t)}${" ".repeat(n-t)}${r.slice(n)}`}function Ae(e,t){return new RegExp(`\\b${Ld(t)}\\b`,"m").test(e)}function hr(e,t){let n=new Set,r=new RegExp(`\\b${Ld(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 Ld(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ei(e){let t=0;for(let n of e)n==="("&&(t+=1),n===")"&&(t-=1);return t}var Lv=new Set(["identifier","type_identifier","property_identifier","shorthand_property_identifier","field_identifier"]);function $e(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 ae(e,t){let n=new Set,r=(i,o)=>{let s=o||t.has(i.type);!s&&Lv.has(i.type)&&n.add(i.text);for(let a of i.children)r(a,s)};return r(e.rootNode,!1),n}function gt(e,t,n,r,i,o,s){return{importedName:i,localName:o,sourcePath:s??se(e,r,ka(t)),kind:"named",used:Ae(n,o),usedMembers:[]}}function ee(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 yr(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 xn(e,t){return{importedName:e,localName:null,sourcePath:t,kind:"side-effect",used:!0,usedMembers:[]}}function Cn(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 Je(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=zt(e,i.index,i.index+o.length);for(let a of n(i,s))r.push(a)}return r}function Ke(e,t,n,r){let i=be(e,t);if(i){let o=n(i);if(o)return o}return r()}function Do(e,t,n,r){let i=be(e,t),o=W(t),s=o?n[o]:void 0;return i&&s?s(i):r()}function Dd(e,t,n){return Ke(e,t,r=>Dv(e,t,r),()=>Iv(e,t,n))}function Iv(e,t,n){return Je(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(r,i)=>{let o=r[1]?.trim();if(!o)return[];let s=Id(o).replace(/\.[^.]+$/,"");return[yr(o,s,wo(e,t,o),Ae(i,s))]})}function Dv(e,t,n){let r=ae(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=Id(s).replace(/\.[^.]+$/,"");i.push(ee(s,a,wo(e,t,s),r))}return i}function Pd(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=zt(n,i.index,i.index+a.length);r.push({importedName:o,localName:s,sourcePath:Lo(e,t,o),kind:s?"namespace":"side-effect",used:s?Ae(c,s):!0,usedMembers:s?hr(c,s):[]})}return r}function Nd(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:Lo(e,t,o)})}return r}function Ed(e,t,n){return Do(e,t,{csharp:r=>Nv(e,t,r),vb:r=>Pv(e,t,r)},()=>{let r=wd(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return Je(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[gt(e,t,o,u,d,m,se(e,u,Ut))]})})}function Pv(e,t,n){let r=ae(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(ee(u,d,se(e,l,Ut),r,c?"namespace":"named"))}return i}function Nv(e,t,n){let r=ae(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(ee(u,d,se(e,l,Ut),r,a?"namespace":"named"))}return i}var Ev=q("vue-non-script-identifiers",{clearGroups:["whole-project","source-file"]});function Td(e,t){return Ev.get(e,t,()=>{let n=new Set,r=T(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 Ia(e,t,n){return Ke(e,t,r=>_v(e,t,r),()=>Tv(e,t,n))}function Tv(e,t,n){return Uv(n).flatMap(r=>Wv(e,t,r.clause,r.specifier,r.start,r.end,n))}function _v(e,t,n){let r=Fv(e,t,n),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))i.push(...Av(e,t,n,o,r));return i}function Fv(e,t,n){let r=ae(n,new Set(["import_statement"]));if(Lt(t))for(let i of Td(e,t))r.add(i);return r}function Av(e,t,n,r,i){let o=Bv(r);if(!o)return[];let s=ot(e,t,o),a=Be(r,"import_clause");return a?$v(n,a,s,i,Hv(r.text)):[xn("*",s)]}function $v(e,t,n,r,i){let o=[];for(let s of t.namedChildren)if(s.type==="identifier")o.push(Mv(s.text,n,r,i));else if(s.type==="namespace_import"){let a=Ov(e,s,n,r,i);a&&o.push(a)}else s.type==="named_imports"&&o.push(...jv(s,n,r,i));return o}function Mv(e,t,n,r){return ee("default",e,t,n,"default",{isTypeOnly:r})}function Ov(e,t,n,r,i){let s=Be(t,"identifier")?.text??"";if(!s)return null;let a=qv(e,s);return Cn("*",n,{localName:s,usedMembers:a,isTypeOnly:i,used:a.length>0||r.has(s)})}function jv(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(ee(c,l,t,n,"named",{isTypeOnly:r||Vv(o.text)}))}return i}function Bv(e){let t=Be(e,"string");if(!t)return null;let n=Be(t,"string_fragment");return n?n.text:null}function Hv(e){return/^\s*import\s+type\b/.test(e)}function Vv(e){return/^\s*type\b/.test(e.trim())}function qv(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 Uv(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 Wv(e,t,n,r,i,o,s){let a=ot(e,t,r),c=zt(s,i,o);return n?Gv(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let d=hr(c,u.localName);return Cn(u.importedName,u.sourcePath,{localName:u.localName,usedMembers:d,used:d.length>0||Ae(c,u.localName),isTypeOnly:u.isTypeOnly})}return u.kind==="side-effect"?xn(u.importedName,u.sourcePath):yr(u.importedName,u.localName??"",u.sourcePath,u.localName?Ae(c,u.localName):!1,u.kind,[],{isTypeOnly:u.isTypeOnly})}):[xn("*",a)]}function Gv(e){let t=e.trim(),n=/^type\b/.test(t),r=t.replace(/^type\s+/,""),[i,o]=zv(r),s=[];return i&&s.push(..._d(i,n)),o&&s.push(..._d(o,n)),s}function _d(e,t){let n=e.trim();if(!n)return[];if(n.startsWith("{")){let r=n.slice(1,-1).trim();return r?$e(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 zv(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 Da(e,t,n){let r=be(e,t);return r?Zv(e,t,r):Jv(e,t,n)}function Jv(e,t,n){return[...Kv(e,t,n),...Xv(e,t,n),...Qv(e,t,n)]}function Kv(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=$e(s).map(d=>Yv(d.trim())).filter(d=>!!d),l=br(n,o.index),u=br(n,o.index+o[0].length-1);r.push({kind:"named",sourcePath:ot(e,t,a),names:c,startLine:l,endLine:u})}return r}function Xv(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=br(n,o.index),c=br(n,o.index+o[0].length-1);r.push({kind:"star-as",sourcePath:ot(e,t,s),names:[],startLine:a,endLine:c})}return r}function Qv(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=br(n,o.index),c=br(n,o.index+o[0].length-1);r.push({kind:"star",sourcePath:ot(e,t,s),names:[],startLine:a,endLine:c})}return r}function Yv(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 br(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function Zv(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("export_statement")){let o=eR(e,t,i);if(o===void 0)continue;let s=i.startPosition.row,a=i.endPosition.row,c=tR(i,o,s,a);r.push(c)}return r}function eR(e,t,n){let r=Be(n,"string");if(!r)return;let i=Be(r,"string_fragment");if(i)return ot(e,t,i.text)}function tR(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 Fd(e,t,n){return Do(e,t,{java:r=>nR(e,t,r),kotlin:r=>rR(e,t,r),scala:r=>iR(e,t,r)},()=>Je(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(r,i)=>{let o=r[1]?.trim();return o?oR(e,t,o,i):[]}))}function nR(e,t,n){let r=ae(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(Cn("*",se(e,l,je)));continue}let u=l.split(".").pop()??l;i.push(ee(u,u,se(e,l,je),r))}return i}function rR(e,t,n){let r=ae(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(Cn("*",se(e,s.text,je)));continue}let l=s.text,u=l.split(".").pop()??l,m=c?.namedChild(0)?.text??u;i.push(ee(u,m,se(e,l,je),r))}return i}function iR(e,t,n){let r=ae(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(Cn("*",se(e,c,je)));continue}if(s?.type==="namespace_selectors"){for(let d of s.namedChildren)if(d.type==="arrow_renamed_identifier"){let[m,p]=d.namedChildren;if(!m)continue;let g=m.text,y=p?.text??g;if(g==="_")continue;i.push(ee(g,y,se(e,`${c}.${g}`,je),r))}else if(d.type==="identifier"){let m=d.text;i.push(ee(m,m,se(e,`${c}.${m}`,je),r))}continue}let l=a[a.length-1]?.text??c,u=a.slice(0,-1).map(d=>d.text).join(".")||c;i.push(ee(l,l,se(e,u&&a.length>1?`${u}.${l}`:c,je),r))}return i}function oR(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 $e(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[gt(e,t,r,m,u,d)]})}return[gt(e,t,r,n,n.split(".").pop()??n,n.split(".").pop()??n)]}function $d(e,t,n){return Ke(e,t,r=>sR(e,t,r),()=>Je(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?$e(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[gt(e,t,i,u,d,m,se(e,u.replace(/\\/g,"."),bn))]}):[]}))}function sR(e,t,n){let r=ae(n,new Set(["namespace_use_declaration"])),i=[],o=(s,a,c)=>{i.push(ee(a,c,se(e,s.replace(/\\/g,"."),bn),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}=Ad(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}=Ad(c,"");l&&o(d,l,u)}}return i}function Ad(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 Od(e,t,n){return Ke(e,t,r=>aR(e,t,r),()=>lR(n).flatMap(r=>dR(e,t,r,n)))}function aR(e,t,n){let r=ae(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=Md(s);if(!a)continue;let c=fr(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=cR(s);if(a===null)continue;let c=fr(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=Md(u);d&&i.push({importedName:d.qualifiedName,localName:d.localName,sourcePath:c,kind:"named",used:r.has(d.localName),usedMembers:[]})}}return i}function Md(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 cR(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 lR(e){let t=e.split(`
156
- `),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=ei(o);for(;i+1<t.length&&(u>0||c.trimEnd().endsWith("\\"));){i++;let m=t[i];c+=`
157
- ${m}`,l+=1+m.length,u+=ei(m),r+=m.length+1}let d=uR(c);d&&n.push({...d,start:a,end:l})}return n}function uR(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 dR(e,t,n,r){let i=zt(r,n.start,n.end),o=n.clause.replace(/\n/g," ").trim();if(n.kind==="import")return $e(o).flatMap(c=>{let l=c.trim().replace(/,$/,"");if(!l)return[];let[u,d]=l.split(/\s+as\s+/),m=u.trim(),p=(d??m.split(".")[0]??m).trim(),g=fr(e,t,m),y=hr(i,p);return[{importedName:m,localName:p,sourcePath:g,kind:"namespace",used:Ae(i,p)||y.length>0,usedMembers:y}]});let s=n.module?fr(e,t,n.module):null,a=[];for(let c of $e(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:Ae(i,m),usedMembers:[]})}return a}import{basename as mR}from"path";function jd(e,t,n){return Ke(e,t,r=>fR(e,t,r),()=>pR(e,t,n))}function pR(e,t,n){return Je(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"?ko(e,t,s):null;if(a){let c=Bd(s);return[yr(c,c,a,Ae(i,c))]}return[xn(s,a)]})}function fR(e,t,n){let r=ae(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 d=l.namedChildren.find(p=>p.type==="string_content")?.text;if(!d)continue;let m=a.text==="require_relative"?ko(e,t,d):null;if(m){let p=Bd(d);i.push(ee(p,p,m,r))}else i.push(xn(d,m))}return i}function Bd(e){return ao(mR(e).replace(/\.[^.]+$/,""),/_/)}function Hd(e,t,n){return Ke(e,t,r=>gR(e,t,r),()=>Je(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?hR(e,t,o,i):[]}))}function gR(e,t,n){let r=ae(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 ti(s,"")){if(!a.importedName||a.importedName==="*")continue;let c=Pt(e,t,a.qualifiedName)??Pt(e,t,a.qualifiedName.split("::").slice(0,-1).join("::"));i.push(ee(a.importedName,a.localName,c,r))}}return i}function ti(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":{let n=e.text;return[{qualifiedName:Po(t,n),importedName:n,localName:n}]}case"scoped_identifier":{let n=e.text,r=n.split("::").pop()??n;return[{qualifiedName:Po(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=Po(t,n.text),o=[];for(let s of r.namedChildren)o.push(...ti(s,i));return o}case"use_list":{let n=[];for(let r of e.namedChildren)n.push(...ti(r,t));return n}case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=ti(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:Po(t,`${r}::*`),importedName:"*",localName:"*"}]}default:return[]}}function Po(e,t){return e?t?`${e}::${t}`:e:t}function hR(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 $e(d).flatMap(m=>{let p=m.trim();if(!p||p==="self")return[];let[g,y]=p.split(/\s+as\s+/),h=g?.trim();if(!h)return[];let x=(y??h.split("::").pop()??h).trim(),v=`${u}::${h}`.replace(/::::/g,"::");return[gt(e,t,r,v,h.split("::").pop()??h,x,Pt(e,t,u))]})}let[o,s]=i.split(/\s+as\s+/),a=o?.trim()??i,c=(s??a.split("::").pop()??a).trim(),l=Pt(e,t,a)??Pt(e,t,a.split("::").slice(0,-1).join("::"));return[gt(e,t,r,a,a.split("::").pop()??a,c,l)]}function Vd(e,t,n){let r=be(e,t);if(r)return yR(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(...SR(e,t,s))}return i}function yR(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("use_declaration")){if(!bR(i))continue;let o=i.namedChildren.find(s=>s.type!=="visibility_modifier");if(o)for(let s of ti(o,""))s.importedName&&r.push(Pa(e,t,s.qualifiedName))}return r}function bR(e){for(let t of e.children)if(t.type==="visibility_modifier"&&t.text.startsWith("pub"))return!0;return!1}function SR(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 $e(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[Pa(e,t,l)]})}return[Pa(e,t,r)]}function Pa(e,t,n){return{specifier:n,sourcePath:Pt(e,t,n)??Pt(e,t,n.split("::").slice(0,-1).join("::"))}}function vn({language:e,extensions:t,imports:n,parseImports:r}){return{language:e,extensions:t,capabilities:{imports:n},parseImports:r}}function qd(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 xR={language:"javascript",extensions:yn,capabilities:{imports:"ast-with-regex-fallback",reExports:"ast-with-regex-fallback"},parseImports:Ia,parseReExports:Da},CR=vn({language:"python",extensions:So,imports:"ast-with-regex-fallback",parseImports:Od}),vR=vn({language:"jvm",extensions:je,imports:"ast-dispatch-with-regex-fallback",parseImports:Fd}),RR={language:"rust",extensions:xo,capabilities:{imports:"ast-with-regex-fallback",exports:"ast-with-regex-fallback"},parseImports:Hd,parseExports:Vd},kR=vn({language:"ruby",extensions:Co,imports:"ast-with-regex-fallback",parseImports:jd}),wR=vn({language:"c/cpp",extensions:vo,imports:"ast-with-regex-fallback",parseImports:Dd}),LR=vn({language:"dotnet",extensions:Ut,imports:"ast-dispatch-with-regex-fallback",parseImports:Ed}),IR={language:"dart",extensions:Ro,capabilities:{imports:"regex-only",exports:"regex-only"},parseImports:Pd,parseExports:Nd},DR=vn({language:"php",extensions:bn,imports:"ast-with-regex-fallback",parseImports:$d}),PR=[xR,CR,vR,RR,kR,wR,LR,IR,DR];function No(e){return qd(PR,e)}var Na={clearGroups:["whole-project","source-file"]},NR=q("source-imports",Na),ER=q("source-exports",Na),TR=q("source-reexports",Na);function ni(e,t){let n=it(t);return TR.get(e,n,()=>{let r=No(n);if(!r?.parseReExports)return[];let i=T(e,n);if(!i)return[];let o=X(e,n,i),s=La(e),a=te(e,"source-reexports",n,o);if(a!==null)try{let l=JSON.parse(a);if(l.resolutionFingerprint===s&&Array.isArray(l.reExports))return l.reExports}catch{}let c=r.parseReExports(e,n,i);return ne(e,"source-reexports",n,o,JSON.stringify({resolutionFingerprint:s,reExports:c})),c})}function xe(e,t){let n=it(t);return NR.get(e,n,()=>{let r=No(n);if(!r)return[];let i=T(e,n);if(!i)return[];let o=X(e,n,i),s=La(e),a=te(e,"source-imports",n,o);if(a!==null)try{let l=JSON.parse(a);if(l.resolutionFingerprint===s&&Array.isArray(l.imports))return l.imports}catch{}let c=r.parseImports(e,n,i);return ne(e,"source-imports",n,o,JSON.stringify({resolutionFingerprint:s,imports:c})),c})}function Eo(e,t){let n=it(t);return ER.get(e,n,()=>{let r=No(n);if(!r?.parseExports)return[];let i=T(e,n);return i?r.parseExports(e,n,i):[]})}var _R=q("file-dep-graph",{clearGroups:["whole-project"]});function ce(e,t){return _R.get(e,t??"",()=>{let n=new Map,r=new Set(O(e,{includeIgnored:!1})),i=(o,s)=>AR(e,n,r,o,s);for(let o of FR(e,t))i(o.from_file,o.to_file);for(let o of r)if(!(t&&!o.includes(t)))for(let s of xe(e,o))s.sourcePath&&i(o,s.sourcePath);return n})}function FR(e,t){let n=t?`AND d1.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
173
+ ORDER BY d.relative_path, start_line, end_line`,...o)}function Nw(e){return`(${e}.symbol LIKE '%().' OR ${e}.symbol LIKE '%()')`}function tp(e,t){return t==="callable"?Nw(e):Fw(e)}function Fw(e){return`(${e}.symbol LIKE '%.' OR ${e}.symbol LIKE '%()')`}function Km(e){let t=new Map;for(let n of e){let i=t.get(n.relative_path);i?i.push(n):t.set(n.relative_path,[n])}return t}function ns(e,t,n={}){if(t.length===0)return[];let i=t.flatMap(r=>Q(e,r)).filter(r=>!e.isIgnored(r.relativePath));return n.onlyDocumented&&(i=i.filter(r=>r.documentation!==null&&r.documentation!=="")),n.sort&&(i=i.sort((r,o)=>r.relativePath.localeCompare(o.relativePath)||r.startLine-o.startLine||r.endLine-o.endLine)),i.map(r=>({startLine:r.startLine,endLine:r.endLine,symbol:r.symbol,shortName:v(r.symbol),signature:Mn($n(r.documentation)),relativePath:r.relativePath,enclosingSymbol:r.enclosingSymbol}))}function yc(e){let t=new Map,n=e.map((i,r)=>({definition:i,index:r,span:i.endLine-i.startLine})).sort((i,r)=>i.span-r.span||i.index-r.index);for(let{definition:i}of n)for(let r=i.startLine;r<=i.endLine;r+=1)t.has(r)||t.set(r,i);return t}function ot(e,t){let n=Gm.get(e);return n||(n=yc(e),Gm.set(e,n)),n.get(t)??null}function On(e,t){let n=Q(e,t.relative_path).find(i=>i.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 np(e,t,n){let i=gt(e).forFile(t,{text:!0}).text,r=za(e,t);return r?jw(n,r,i):i?Tw(n,i):n}function Tw(e,t){let n=t.split(/\r?\n/),i=_w(e,n),r=Aw(e,i),o=Mw(r,n);return $w(e,o)}function _w(e,t){let n=e.some(r=>is(r.symbol))?Hw(t):null,i=new Map;for(let r of e)i.set(r.symbolId,Bw(t,n,r));return i}function Aw(e,t){return e.filter(n=>is(n.symbol)).map(n=>({definition:n,startLine:t.get(n.symbolId)??n.startLine})).sort((n,i)=>n.startLine-i.startLine||n.definition.startLine-i.definition.startLine||n.definition.symbol.localeCompare(i.definition.symbol))}function Mw(e,t){let n=new Map;for(let i=0;i<e.length;i+=1){let r=e[i],o=e[i+1],s=o?Math.max(r.startLine,o.startLine-1):t.length-1;n.set(r.definition.symbolId,{startLine:r.startLine,endLine:Vw(t,r.definition,r.startLine,s)})}return n}function $w(e,t){return e.map(n=>{let i=t.get(n.symbolId);return i?{...n,startLine:i.startLine,endLine:i.endLine}:n})}function jw(e,t,n=null){let i=new Map;for(let r of t){let o=i.get(r.name);o?o.push(r):i.set(r.name,[r])}return e.map(r=>{if(!Ow(r)||!r.leaf)return Jm(r,n);let o=i.get(r.leaf);if(!o||o.length===0)return Jm(r,n);let s=o[0],a=Math.abs(s.startLine-r.startLine);for(let c=1;c<o.length;c+=1){let l=o[c],d=Math.abs(l.startLine-r.startLine);d<a&&(s=l,a=d)}return{...r,startLine:s.startLine,endLine:s.endLine}})}function Ow(e){return is(e.symbol)?!0:se(e.symbol)==="term"&&It(e.symbol)===null}function Jm(e,t){if(!t||!e.leaf||se(e.symbol)!=="term"||It(e.symbol)!==null)return e;let n=e.leaf.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\b(?:export\\s+)?(?:const|let|var)\\s+${n}\\b`),o=t.split(/\r?\n/).findIndex(s=>i.test(s));return o>=0?{...e,startLine:o,endLine:o}:e}function Bw(e,t,n){if(!is(n.symbol))return n.startLine;let i=Math.max(0,Math.min(n.startLine,e.length-1));if(!t)return i;let r=t.get(n.leaf);if(!r||r.length===0)return i;let o=null;for(let s of r){let a=Math.abs(s-n.startLine);(!o||a<o.distance)&&(o={line:s,distance:a})}return o?.line??i}function Hw(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,i=/^\s*(?:(?:export|public|private|protected|static|readonly|async|abstract|get|set)\s+)*([A-Za-z_$][\w$]*)\s*(?:<[^(]*>)?\s*\(/,r=/\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 d of c.matchAll(t))d[1]&&s(d[1],a);for(let d of c.matchAll(n))d[1]&&s(d[1],a);let l=c.match(i);l?.[1]&&s(l[1],a);for(let d of c.matchAll(r))d[1]&&s(d[1],a)}return o}function Vw(e,t,n,i){let r=Math.max(n,Math.min(e.length-1,i)),o=Math.max(n,Math.min(r,t.endLine)),s=0,a=0,c=!1;for(let l=n;l<=r;l+=1){let d=qw(e[l]??"");for(let u of d)u==="{"?(s+=1,c=!0):u==="}"?s=Math.max(0,s-1):u==="("?a+=1:u===")"&&(a=Math.max(0,a-1));if(c&&s===0||!c&&a===0&&l>=o)return l}return o}function qw(e){let t="",n=null,i=!1;for(let r=0;r<e.length;r+=1){let o=e[r],s=e[r+1];if(!n&&o==="/"&&s==="/"){t+=" ".repeat(e.length-r);break}if(n){if(i){i=!1,t+=" ";continue}if(o==="\\"){i=!0,t+=" ";continue}o===n&&(n=null),t+=" ";continue}if(o==='"'||o==="'"||o==="`"){n=o,t+=" ";continue}t+=o}return t}function is(e){return e.includes("().")}function rs(e){let t=Ie(e);if("kind"in t)return[];let n=[];for(let i=t.descriptors.length-2;i>=0;i-=1){let r=t.descriptors[i];r?.suffix==="type"&&r.name&&n.push(r.name)}return n}import{existsSync as iP}from"fs";import{basename as ip,isAbsolute as rP,join as oP}from"path";function q(e,t){let n=Ni(e,t.trim());if(n)return n;let i=Jw(e,t);if(i)return i;let r=Uw(e,t);return r||Kw(e,t)}function Uw(e,t){let n=Sc(t),i=bc(n);if(!i)return null;let r=`%${i.path}%`,o=i.leaf,a=zw(e,r,o,n)[0];return a?On(e,a):null}function zw(e,t,n,i){let r=jn([],[...Ww(e,t,n),...Gw(e,t,n)]).filter(o=>!e.isIgnored(o.relative_path)).filter(o=>Ei(o,i)>1);return r.sort((o,s)=>Ei(s,i)-Ei(o,i)||o.end_line-o.start_line-(s.end_line-s.start_line)||o.start_line-s.start_line||o.symbol.localeCompare(s.symbol)),r}function Ww(e,t,n){return Li(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function Gw(e,t,n){return Di(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function Kw(e,t){let n=Sc(t),i=tP(t),r=Zw(e,i),o=nP(r,t,n);if(o&&!e.isIgnored(o.relative_path))return On(e,o);let s=null;for(let a of r){if(e.isIgnored(a.relative_path))continue;let c=eP(a,t,n,i);c<=0||(!s||c>s.score)&&(s={row:a,score:c})}return s?On(e,s.row):null}function Jw(e,t){let n=t.match(/^(.+):(\d+)-(\d+)$/);if(!n)return null;let[,i,r,o]=n,s=Math.max(0,parseInt(r,10)-1),a=Math.max(s,parseInt(o,10)-1),c=Xw(e,i,s,a)??Qw(e,i,s,a);return c&&!e.isIgnored(c.relative_path)?On(e,c):null}function Xw(e,t,n,i){return Li(e,{where:"d.relative_path LIKE ? AND der.start_line <= ? AND der.end_line >= ?",params:[`%${t}%`,n,i],orderBy:"(der.end_line - der.start_line) ASC",limit:1})[0]}function Qw(e,t,n,i){return Di(e,{where:"d.relative_path LIKE ? AND c.start_line <= ? AND c.end_line >= ?",params:[`%${t}%`,n,i],orderBy:"(MAX(c.end_line) - MIN(c.start_line)) ASC",limit:1})[0]}function Ni(e,t){let i=Li(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, der.start_line",limit:1})[0]??Di(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, start_line",limit:1})[0];return!i||e.isIgnored(i.relative_path)?null:On(e,i)}function os(e,t){if("symbol"in t&&"relativePath"in t)return t;let n=Yw(e,t.symbolId)[0];return n?On(e,n):null}function Yw(e,t){let n=Li(e,{where:"gs.id = ?",params:[t],orderBy:"der.start_line, der.end_line"}),i=Di(e,{where:"gs.id = ?",params:[t],orderBy:"start_line, end_line"});return jn(n,i)}function Zw(e,t){let n=t.map(()=>"(gs.symbol LIKE ? OR d.relative_path LIKE ? OR COALESCE(gs.display_name, '') LIKE ?)"),i=t.flatMap(a=>{let c=`%${a}%`;return[c,c,c]}),r=n.join(`
174
+ AND `),o=Li(e,{where:r,params:i,limit:200}),s=Di(e,{where:r,params:i,limit:200});return jn(o,s)}function eP(e,t,n,i){let r=t.trim(),o=n,s=o.replace(/\(\)$/,""),a=t.toLowerCase(),c=n.toLowerCase(),l=c.replace(/\(\)$/,""),d=e.symbol,u=v(e.symbol),m=$(e.symbol),p=e.display_name??"",f=e.symbol.toLowerCase(),g=u.toLowerCase(),b=m.toLowerCase(),x=p.toLowerCase(),S=e.relative_path.toLowerCase(),R=/[/:.]/.test(n),C=bc(n),y=C?.leaf.toLowerCase(),w=0;return(d===r||d===o)&&(w+=1150),(u===r||u===o)&&(w+=1100),p===s&&(w+=1180),m===s&&(w+=1160),(`${m}()`===r||`${m}()`===o)&&(w+=955),(f===a||f===c)&&(w+=1e3),(g===a||g===c)&&(w+=950),(S===a||S===c)&&(w+=925),(S.endsWith(`/${c}`)||S.endsWith(`/${a}`))&&(w+=875),x===l&&(w+=850),b===l&&(w+=825),(`${b}()`===a||`${b}()`===c)&&(w+=820),(g.endsWith(`:${c}`)||g.endsWith(`:${l}`)||g.endsWith(`:${l}()`))&&(w+=800),f.includes(c)&&(w+=120),g.includes(c)&&(w+=140),S.includes(c)&&(w+=140),x.includes(c)&&(w+=110),i.every(L=>{let k=L.toLowerCase();return f.includes(k)||g.includes(k)||S.includes(k)||x.includes(k)})&&(w+=100+i.length*15),C&&S.includes(C.path.toLowerCase())&&(w+=360,y&&(b===y||`${b}()`===y||`${b}()`==`${y}()`)&&(w+=700),he(e.symbol)&&(w+=180)),de(e.symbol)&&b===l&&(w+=60),!R&&gn(e.symbol)&&(w-=160),w-=Math.min(50,Math.max(0,e.end_line-e.start_line)),w}function bc(e){let t=e.trim().replace(/\\/g,"/"),n=t.lastIndexOf("/");if(n<=0||n===t.length-1)return null;let i=t.slice(n+1).replace(/\(\)$/,"");return!i||i.includes(".")?null:{path:t.slice(0,n),leaf:i}}function Sc(e){return e.trim().replace(/\(\)$/,"").replace(/\(.*$/,"")}function tP(e){let t=Sc(e),n=t.split(/[^A-Za-z0-9_]+/).map(i=>i.trim()).filter(i=>i.length>0);return n.length>0?[...new Set(n)]:[t]}function nP(e,t,n){let i=t.trim(),r=e.filter(o=>{let s=v(o.symbol),a=(o.display_name??"").trim();return o.symbol===i||s===i||s===n||a===i||a===n||`${a}()`===i||Ei(o,n)>1||o.relative_path===i});return r.length===0?null:(r.sort((o,s)=>Ei(s,n)-Ei(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)),r[0]??null)}function Ei(e,t){let n=bc(t);if(!n)return 0;let i=e.relative_path.toLowerCase(),r=$(e.symbol).toLowerCase(),o=n.path.toLowerCase(),s=n.leaf.toLowerCase();return i.includes(o)?r!==s?1:he(e.symbol)?It(e.symbol)===null?5:4:It(e.symbol)===null?3:2:0}function Ve(e,t){let n=rp(e,t,{allowMultiple:!1})[0]?.relativePath;return n||sP(e,t)}function Fi(e,t){return rp(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function sP(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),i=rP(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,r=oP(e.config.projectRoot,i);return iP(r)?i:null}function rp(e,t,n){let i=op(t);if(!i)return[];let r=O(e,{includeIgnored:!1}).map(a=>({relativePath:a,score:aP(a,i)})).filter(a=>a.score>0).sort((a,c)=>c.score-a.score||a.relativePath.localeCompare(c.relativePath));if(r.length===0){let a=q(e,t);return!a||e.isIgnored(a.relativePath)?[]:[{relativePath:a.relativePath,score:700}]}let o=r.filter(a=>a.score>=1100);if(o.length>0)return n.allowMultiple?o:[o[0]];let s=r.filter(a=>a.score>=800);return s.length>0?n.allowMultiple?s:[s[0]]:n.allowMultiple?r:[r[0]]}function aP(e,t){let n=op(e),i=ip(n),r=ip(t),o=0;return n===t&&(o+=1200),n.endsWith(`/${t}`)&&(o+=1100),i===r&&(o+=900),n.startsWith(`${t}/`)&&(o+=850),n.includes(t)&&(o+=250),o}function op(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}import{basename as ML}from"path";import{appendFileSync as cP,mkdirSync as lP}from"fs";import{dirname as uP}from"path";import{performance as xc}from"perf_hooks";var dP="SCIP_QUERY_PROFILE",mP="SCIP_QUERY_PROFILE_OUT",pP="SCIP_QUERY_PROFILE_COMMAND",sp=new Set,ap=!1;function me(){let e=process.env[dP];return e==="1"||e==="true"}function fP(){return process.env[mP]}function gP(){return process.env[pP]}function D(e,t,n){if(!me())return t();let i=xc.now();try{let r=t();return Bn({type:"span",name:e,durationMs:Math.round(xc.now()-i),ok:!0,...cp(n)??{}}),r}catch(r){throw Bn({type:"span",name:e,durationMs:Math.round(xc.now()-i),ok:!1,error:r instanceof Error?r.message:String(r),...cp(n)??{}}),r}}function Bn(e,t=fP()){let n={timestamp:new Date().toISOString(),pid:process.pid,command:gP(),...e},i=`${JSON.stringify(n)}
175
+ `;if(t)try{let r=uP(t);sp.has(r)||(lP(r,{recursive:!0}),sp.add(r)),cP(t,i);return}catch(r){ap||(ap=!0,process.stderr.write(`[profile] failed to write ${t}: ${r instanceof Error?r.message:String(r)}
176
+ `));return}me()&&process.stderr.write(i)}function cp(e){return typeof e=="function"?e():e}var lp=Ld({kind:"file-dependency-graph",serialize:e=>JSON.stringify(e),deserialize:RP}),hP=W("file-dep-graph",{clearGroups:["whole-project"]});function ye(e,t){return hP.get(e,t??"",()=>{let n=new Set(O(e,{includeIgnored:!1})),i=0,r=0,o=D("file-dep-graph.source-imports",()=>{let u=yP(e,n,t);return i=u.files.length,r=u.edges.length,u},()=>({scope:t??null,files:i,edges:r})),s=In(e),a=s?xP(s,o.fingerprint):null,c=!1,l=0,d=0;return D("file-dep-graph.product",()=>{let u=SP(t);if(a){let f=lp.read(e,u,a);if(f?.sourceImportFingerprint===o.fingerprint){c=!0;let g=vP(f);return d=g.size,g}}let m=new Map,p=(f,g)=>IP(e,m,n,f,g);D("file-dep-graph.scip-edges",()=>{for(let f of PP(e,t))l+=1,p(f.from_file,f.to_file)},()=>({scope:t??null,edges:l}));for(let f of o.edges)p(f.fromFile,f.toFile);return d=m.size,a&&lp.write(e,u,a,{sourceImportFingerprint:o.fingerprint,sourceFileCount:o.files.length,sourceEdgeCount:o.edges.length,scipEdgeCount:l,graph:CP(m)}),m},()=>({scope:t??null,available:a!==null,hit:c,files:o.files.length,sourceEdges:o.edges.length,scipEdges:l,graphFiles:d,sourceImportFingerprint:o.fingerprint}))})}function yP(e,t,n){let i=[],r=[];for(let o of t)if(!(n&&!o.includes(n))){i.push(o);for(let s of oe(e,o))s.sourcePath&&r.push({fromFile:o,toFile:s.sourcePath})}return{files:i,edges:r,fingerprint:bP(i,r)}}function bP(e,t){let n=t.map(i=>`${i.fromFile}\0${i.toFile}`).sort();return Vt(JSON.stringify({files:e,edges:n}))}function SP(e){return e??"<all>"}function xP(e,t){return Vt(JSON.stringify({projectFingerprint:e,sourceImportFingerprint:t}))}function CP(e){return[...e].map(([t,n])=>[t,[...n]])}function vP(e){return new Map(e.graph.map(([t,n])=>[t,new Set(n)]))}function RP(e){let t=JSON.parse(e);return kP(t)?t:null}function kP(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.sourceImportFingerprint=="string"&&typeof t.sourceFileCount=="number"&&typeof t.sourceEdgeCount=="number"&&typeof t.scipEdgeCount=="number"&&Array.isArray(t.graph)&&t.graph.every(wP)}function wP(e){return Array.isArray(e)&&e.length===2&&typeof e[0]=="string"&&Array.isArray(e[1])&&e[1].every(t=>typeof t=="string")}function PP(e,t){let n=t?`AND d1.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
158
177
  d1.relative_path AS from_file,
159
178
  d2.relative_path AS to_file
160
179
  FROM mentions m
@@ -172,11 +191,11 @@ ${m}`,l+=1+m.length,u+=ei(m),r+=m.length+1}let d=uR(c);d&&n.push({...d,start:a,e
172
191
  WHERE d1.id != d2.id
173
192
  AND m.role != 1
174
193
  ${e.pathExclusionsFor("d1","d2")}
175
- ${n}`)}function AR(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 To,readFileSync as $R,readdirSync as Wd}from"fs";import{join as ri}from"path";var MR={files:new Set,pathPrefixes:[]},Ea=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,OR=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,Gd=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],jR=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),BR=4,HR=Z("package-surface",{clearGroups:["whole-project"]});function VR(e){return HR.get(e,()=>qR(e.config.projectRoot))}function xr(e,t){let n=VR(e);return n.files.has(t)?!0:n.pathPrefixes.some(r=>t.startsWith(r))}function qR(e){let t=new Set,n=[];for(let{manifest:r,packageRoot:i}of UR(e))for(let o of WR(r))GR(e,i,o,t,n);return t.size===0&&n.length===0?MR:{files:t,pathPrefixes:n}}function UR(e){let t=[],n=Jd(e,"");return n&&t.push({manifest:n,packageRoot:""}),zd(e,"",t,0),t}function zd(e,t,n,r){if(r>=BR)return;let i=ri(e,t);if(To(i))for(let o of Wd(i,{withFileTypes:!0})){if(!o.isDirectory()||jR.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=Jd(e,s);a&&n.push({manifest:a,packageRoot:s}),zd(e,s,n,r+1)}}function Jd(e,t){try{let n=$R(ri(e,t,"package.json"),"utf-8"),r=JSON.parse(n);return r&&typeof r=="object"?r:null}catch{return null}}function WR(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 Kd(e.exports,t),t}function Kd(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))Kd(n,t)}function GR(e,t,n,r,i){let o=n.replace(/\\/g,"/").replace(/^\.\//,"");if(o===""||o.startsWith(".."))return;let s=o.indexOf("*");if(s>=0){let c=o.slice(0,s);for(let l of Ud(c))l!==""&&i.push(Sr(t,l));return}let a=o.replace(OR,"");for(let c of Ud(a)){c===a&&c===o&&r.add(Sr(t,o));for(let l of Gd)zR(e,r,t,c+l)}r.add(Sr(t,o))}function Ud(e){let t=[e];return Ea.test(e)&&(t.push(e.replace(Ea,"src/")),t.push(e.replace(Ea,""))),t}function zR(e,t,n,r){let i=Sr(n,r);if(t.add(i),!r.startsWith("src/")||To(ri(e,i)))return;let o=Gd.find(u=>r.endsWith(u));if(!o)return;let s=r.slice(0,-o.length);JR(e,t,n,s,o);let a=s.lastIndexOf("/");if(a<=4)return;let c=s.slice(0,a),l=s.slice(a+1);for(let u of Xd(e,n,c,`${l}${o}`))t.add(u)}function JR(e,t,n,r,i){let o=Sr(n,`${r}/index${i}`);To(ri(e,o))&&t.add(o)}function Xd(e,t,n,r){let i=ri(e,t,n);if(!To(i))return[];let o=[];for(let s of Wd(i,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...Xd(e,t,a,r)):s.isFile()&&s.name===r&&o.push(Sr(t,a))}return o}function Sr(e,t){return e?`${e}/${t}`:t}function J(e){let t=Cr(e);return lk(t)?"test":uk(t)?"worker":dk(t)?"entry":mk(t)?"barrel":"source"}function _o(e){return J(e)==="barrel"}function Yd(e){return KR.get(e,()=>{let t=ce(e),n=Ne(e).filter(o=>{let s=J(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),J(o)==="barrel"&&i.add(o);for(let s of t.get(o)??[])r.has(s)||n.push(s)}}return i})}var KR=Z("live-barrels",{clearGroups:["whole-project"]});function Ta(e,t){return Yd(e).has(Cr(t))}function Zd(e){let t=Yd(e);return Ne(e).filter(n=>_o(n)&&!t.has(n)&&!XR(e,n))}function XR(e,t){let n=Cr(t),r=me(e,n)?.callables;return r&&r.length>0?!0:(e.get(`SELECT COUNT(*) AS n
194
+ ${n}`)}function IP(e,t,n,i,r){if(i===r||e.isIgnored(i)||e.isIgnored(r)||!n.has(r))return;let o=t.get(i);o||(o=new Set,t.set(i,o)),o.add(r)}import{existsSync as ss,readFileSync as LP,readdirSync as dp}from"fs";import{join as vr}from"path";var DP={files:new Set,pathPrefixes:[]},Cc=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,EP=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,mp=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],NP=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),FP=4,TP=ie("package-surface",{clearGroups:["whole-project"]});function _P(e){return TP.get(e,()=>AP(e.config.projectRoot))}function _i(e,t){let n=_P(e);return n.files.has(t)?!0:n.pathPrefixes.some(i=>t.startsWith(i))}function AP(e){let t=new Set,n=[];for(let{manifest:i,packageRoot:r}of MP(e))for(let o of $P(i))jP(e,r,o,t,n);return t.size===0&&n.length===0?DP:{files:t,pathPrefixes:n}}function MP(e){let t=[],n=fp(e,"");return n&&t.push({manifest:n,packageRoot:""}),pp(e,"",t,0),t}function pp(e,t,n,i){if(i>=FP)return;let r=vr(e,t);if(ss(r))for(let o of dp(r,{withFileTypes:!0})){if(!o.isDirectory()||NP.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=fp(e,s);a&&n.push({manifest:a,packageRoot:s}),pp(e,s,n,i+1)}}function fp(e,t){try{let n=LP(vr(e,t,"package.json"),"utf-8"),i=JSON.parse(n);return i&&typeof i=="object"?i:null}catch{return null}}function $P(e){let t=[];for(let i of["main","module","types","browser"])typeof e[i]=="string"&&t.push(e[i]);let n=e.bin;if(typeof n=="string")t.push(n);else if(n&&typeof n=="object")for(let i of Object.values(n))typeof i=="string"&&t.push(i);return gp(e.exports,t),t}function gp(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))gp(n,t)}function jP(e,t,n,i,r){let o=n.replace(/\\/g,"/").replace(/^\.\//,"");if(o===""||o.startsWith(".."))return;let s=o.indexOf("*");if(s>=0){let c=o.slice(0,s);for(let l of up(c))l!==""&&r.push(Ti(t,l));return}let a=o.replace(EP,"");for(let c of up(a)){c===a&&c===o&&i.add(Ti(t,o));for(let l of mp)OP(e,i,t,c+l)}i.add(Ti(t,o))}function up(e){let t=[e];return Cc.test(e)&&(t.push(e.replace(Cc,"src/")),t.push(e.replace(Cc,""))),t}function OP(e,t,n,i){let r=Ti(n,i);if(t.add(r),!i.startsWith("src/")||ss(vr(e,r)))return;let o=mp.find(d=>i.endsWith(d));if(!o)return;let s=i.slice(0,-o.length);BP(e,t,n,s,o);let a=s.lastIndexOf("/");if(a<=4)return;let c=s.slice(0,a),l=s.slice(a+1);for(let d of hp(e,n,c,`${l}${o}`))t.add(d)}function BP(e,t,n,i,r){let o=Ti(n,`${i}/index${r}`);ss(vr(e,o))&&t.add(o)}function hp(e,t,n,i){let r=vr(e,t,n);if(!ss(r))return[];let o=[];for(let s of dp(r,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...hp(e,t,a,i)):s.isFile()&&s.name===i&&o.push(Ti(t,a))}return o}function Ti(e,t){return e?`${e}/${t}`:t}function Z(e){let t=Ai(e);return tI(t)?"test":nI(t)?"worker":iI(t)?"entry":rI(t)?"barrel":"source"}function as(e){return Z(e)==="barrel"}function bp(e){return HP.get(e,()=>{let n=O(e,{includeIgnored:!1}).filter(s=>{let a=Z(s);return a==="entry"||a==="worker"});if(n.length===0)return new Set;let i=ye(e),r=new Set,o=new Set;for(;n.length>0;){let s=n.shift();if(!r.has(s)){r.add(s),Z(s)==="barrel"&&o.add(s);for(let a of i.get(s)??[])r.has(a)||n.push(a)}}return o})}var HP=ie("live-barrels",{clearGroups:["whole-project"]});function vc(e,t){return bp(e).has(Ai(t))}function Sp(e){let t=bp(e);return O(e,{includeIgnored:!1}).filter(n=>as(n)&&!t.has(n)&&!VP(e,n))}function VP(e,t){let n=Ai(t),i=gt(e).forFile(n,{facts:!0}).facts?.callables;return i&&i.length>0?!0:(e.get(`SELECT COUNT(*) AS n
176
195
  FROM defn_enclosing_ranges der
177
196
  JOIN documents d ON d.id = der.document_id
178
197
  WHERE d.relative_path = ?
179
- AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function Te(e,t){let n=J(t);return n==="entry"||n==="worker"||Ta(e,t)}function le(e,t,n){let r=Cr(n);if(xr(e,r)||nk(t,r))return!0;let i=e.config.entryRoots;return i?!!(i.files?.some(o=>Cr(o)===r)||i.pathPrefixes?.some(o=>r.startsWith(Cr(o)))||i.qualifiedVars?.some(o=>pk(t,o))||i.symbolPatterns?.some(o=>{try{return new RegExp(o).test(t)}catch{return!1}})):!1}var em=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),QR=new Set(["default","generateMetadata","generateStaticParams"]),YR=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),ZR=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),ek=new Set(["load","actions","entries",...em]),tk=new Set(["default"]);function nk(e,t){let n=$(e);return n===""?!1:rk(t)?em.has(n):ik(t)?QR.has(n):ok(t)?YR.has(n):sk(t)?ZR.has(n):ak(t)?ek.has(n):ck(t)?tk.has(n):!1}function rk(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function ik(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function ok(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function sk(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function ak(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function ck(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function lk(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 uk(e){return/(?:^|\/)[^/]*worker\.(?:ts|tsx|js|mjs|cjs|rs|py|go)$/.test(e)}function dk(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 mk(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 Cr(e){return e.replace(/\\/g,"/")}function pk(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(Qd(r)+"/")&&e.includes(Qd(i)+".")}function Qd(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function Fo(e,t,n,r={}){if(!n)return[];let i=T(e,t);return i?i.indexOf(n)===-1?[]:(Nt(e,t).get(n)??[]).filter(s=>!fk(s,r)):[]}function fk(e,t){return typeof t.excludeStartLine=="number"&&typeof t.excludeEndLine=="number"&&e>=t.excludeStartLine&&e<=t.excludeEndLine}var gk=q("file-identifiers",{clearGroups:["whole-project","source-file"]});function tm(e,t){let n=me(e,t);return n?n.fileIdentifiers:gk.get(e,t,()=>new Set(Nt(e,t).keys()))}var hk=q("file-ident-lines",{clearGroups:["whole-project","source-file"]});function Nt(e,t){let n=me(e,t);return n?n.identifierLineMap:hk.get(e,t,()=>bk(e,t))}var yk=q("file-idents-by-line",{clearGroups:["whole-project","source-file"]});function nm(e,t){let n=me(e,t);return n?n.identifiersByLine:yk.get(e,t,()=>{let r=Nt(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 bk(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=T(e,t);if(!i)return n;let o=Sn(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 rm(e,t){return _a(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT
198
+ AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function Oe(e,t){let n=Z(t);return n==="entry"||n==="worker"||vc(e,t)}function be(e,t,n){let i=Ai(n);if(_i(e,i)||KP(t,i))return!0;let r=e.config.entryRoots;return r?!!(r.files?.some(o=>Ai(o)===i)||r.pathPrefixes?.some(o=>i.startsWith(Ai(o)))||r.qualifiedVars?.some(o=>oI(t,o))||r.symbolPatterns?.some(o=>{try{return new RegExp(o).test(t)}catch{return!1}})):!1}var xp=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),qP=new Set(["default","generateMetadata","generateStaticParams"]),UP=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),zP=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),WP=new Set(["load","actions","entries",...xp]),GP=new Set(["default"]);function KP(e,t){let n=$(e);return n===""?!1:JP(t)?xp.has(n):XP(t)?qP.has(n):QP(t)?UP.has(n):YP(t)?zP.has(n):ZP(t)?WP.has(n):eI(t)?GP.has(n):!1}function JP(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function XP(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function QP(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function YP(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function ZP(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function eI(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function tI(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 nI(e){return/(?:^|\/)[^/]*worker\.(?:ts|tsx|js|mjs|cjs|rs|py|go)$/.test(e)}function iI(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 rI(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 Ai(e){return e.replace(/\\/g,"/")}function oI(e,t){let n=t.lastIndexOf("/");if(n<0)return!1;let i=t.slice(0,n),r=t.slice(n+1);return e.includes(yp(i)+"/")&&e.includes(yp(r)+".")}function yp(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function cs(e,t,n,i={}){if(!n)return[];let r=M(e,t);return r?r.indexOf(n)===-1?[]:(Kt(e,t).get(n)??[]).filter(s=>!sI(s,i)):[]}function sI(e,t){return typeof t.excludeStartLine=="number"&&typeof t.excludeEndLine=="number"&&e>=t.excludeStartLine&&e<=t.excludeEndLine}var aI=W("file-identifiers",{clearGroups:["whole-project","source-file"]});function Cp(e,t){let n=X(e,t);return n?n.fileIdentifiers:aI.get(e,t,()=>new Set(Kt(e,t).keys()))}var cI=W("file-ident-lines",{clearGroups:["whole-project","source-file"]});function Kt(e,t){let n=X(e,t);return n?n.identifierLineMap:cI.get(e,t,()=>uI(e,t))}var lI=W("file-idents-by-line",{clearGroups:["whole-project","source-file"]});function vp(e,t){let n=X(e,t);return n?n.identifiersByLine:lI.get(e,t,()=>{let i=Kt(e,t),r=0;for(let s of i.values()){let a=s[s.length-1];a!==void 0&&a>r&&(r=a)}let o=new Array(r+1);for(let s=0;s<=r;s+=1)o[s]=new Set;for(let[s,a]of i)for(let c of a)o[c].add(s);return o})}function uI(e,t){let n=new Map,i=(a,c)=>{let l=n.get(a);if(!l){n.set(a,[c]);return}l[l.length-1]!==c&&l.push(c)},r=M(e,t);if(!r)return n;let o=Tn(r).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]&&i(l[1],a)}return n}function Rp(e,t){return ls(e,t,n=>{let i=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT
180
199
  m.symbol_id,
181
200
  d.relative_path,
182
201
  COUNT(*) AS ref_count
@@ -184,23 +203,26 @@ ${m}`,l+=1+m.length,u+=ei(m),r+=m.length+1}let d=uR(c);d&&n.push({...d,start:a,e
184
203
  JOIN chunks c ON m.chunk_id = c.id
185
204
  JOIN documents d ON c.document_id = d.id
186
205
  WHERE m.role != 1
187
- ${r}
206
+ ${i}
188
207
  ${e.pathExclusionsFor("d")}
189
- GROUP BY m.symbol_id, d.relative_path`,...n??[])})}function im(e,t){return _a(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
208
+ GROUP BY m.symbol_id, d.relative_path`,...n??[])})}function kp(e,t){return ls(e,t,n=>{let i=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id, d.relative_path
190
209
  FROM mentions m
191
210
  JOIN chunks c ON m.chunk_id = c.id
192
211
  JOIN documents d ON c.document_id = d.id
193
212
  WHERE m.role != 1
194
- ${r}
195
- ${e.pathExclusionsFor("d")}`,...n??[])}).filter(n=>n.symbol_id!==null)}function vr(e,t){return _a(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,
213
+ ${i}
214
+ ${e.pathExclusionsFor("d")}`,...n??[])}).filter(n=>n.symbol_id!==null)}function wp(e,t){return ls(e,t,n=>{let i=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id
215
+ FROM mentions m
216
+ WHERE m.role != 1
217
+ ${i}`,...n??[])}).filter(n=>n.symbol_id!==null)}function Mi(e,t){return ls(e,t,n=>{let i=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id, d.relative_path, c.document_id,
196
218
  c.start_line AS chunk_start, c.end_line AS chunk_end
197
219
  FROM mentions m
198
220
  JOIN chunks c ON m.chunk_id = c.id
199
221
  JOIN documents d ON c.document_id = d.id
200
222
  WHERE m.role != 1
201
- ${r}
223
+ ${i}
202
224
  ${e.pathExclusionsFor("d")}
203
- ORDER BY d.relative_path, c.start_line`,...n??[])})}function _a(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 Ao(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Jt(e,t){return Ao(e)===Ao(t)}function $o(e,t){let n=om(e);return n?t.filter(r=>om(r.file)===n):t}function Mo(e,t,n,r){let i=n.find(o=>o.file===t);if(i)return i;if(r){let o=new Set(xe(e,t).map(s=>s.sourcePath).filter(s=>!!s));for(let s of n)for(let a of o)if(Jt(a,s.file))return s;return null}return n.length===1?n[0]:null}function om(e){let t=W(e);return t?t==="typescript"||t==="tsx"||t==="javascript"?"javascript-family":t:null}var Sk=Z("global-leaf-index",{clearGroups:["whole-project"]});function Rn(e){return Sk.get(e,()=>{let t=e.all(`SELECT gs.id, gs.symbol,
225
+ ORDER BY d.relative_path, c.start_line`,...n??[])})}function ls(e,t,n){if(!t)return n();if(t.length===0)return[];let i=[];for(let r=0;r<t.length;r+=750)i.push(...n(t.slice(r,r+750)));return i}function us(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Dt(e,t){return us(e)===us(t)}function ds(e,t){let n=Pp(e);return n?t.filter(i=>Pp(i.file)===n):t}function ms(e,t,n,i){let r=n.find(o=>o.file===t);if(r)return r;if(i){let o=new Set(oe(e,t).map(s=>s.sourcePath).filter(s=>!!s));for(let s of n)for(let a of o)if(Dt(a,s.file))return s;return null}return n.length===1?n[0]:null}function Pp(e){let t=H(e);return t?t==="typescript"||t==="tsx"||t==="javascript"?"javascript-family":t:null}var dI=ie("global-leaf-index",{clearGroups:["whole-project"]});function Hn(e){return dI.get(e,()=>{let t=e.all(`SELECT gs.id, gs.symbol,
204
226
  COALESCE(der_doc.relative_path, mention_doc.relative_path) AS relative_path
205
227
  FROM global_symbols gs
206
228
  LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
@@ -214,8 +236,8 @@ ${m}`,l+=1+m.length,u+=ei(m),r+=m.length+1}let d=uR(c);d&&n.push({...d,start:a,e
214
236
  GROUP BY m.symbol_id
215
237
  ) mention_doc ON mention_doc.symbol_id = gs.id
216
238
  WHERE 1 = 1
217
- ${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})}var sm=/[A-Za-z_$][A-Za-z0-9_$]*/g,xk=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function ii(e){let t=[],n=!1;for(let r of e)r&&(n=!0,xk.test(r)||t.push(r));return{candidateNames:e,hasUsableCandidate:n,nonIdentifierNames:t}}function Oo(e,t){let n=Ck(t)?t:ii(t);if(n.candidateNames.size===0||!n.hasUsableCandidate)return!0;sm.lastIndex=0;let r;for(;(r=sm.exec(e))!==null;)if(n.candidateNames.has(r[0]))return!0;for(let i of n.nonIdentifierNames)if(e.includes(i))return!0;return!1}function Ck(e){return"candidateNames"in e}function st(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}import am from"path";function vk(e,t){return e.getReferences().map(n=>{let r=n.getNode();return um(r,t)})}function Rk(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function cm(e,t,n,r){let i=[];for(let o of Rk(e))for(let s of vk(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 jo(i)}function lm(e,t,n,r){let i=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();oi(r,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||i.push({location:um(a,r),node:a}))}return i}function um(e,t){let n=e.getSourceFile(),r=n.getLineAndColumnAtPos(e.getStart());return{file:oi(t,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function dm(e,t,n){let r=e.getSourceFile(),i=Rr(r,e),o=e.getText(),s=new RegExp(`\\b${kk(o)}\\b`,"g"),a=r.getFullText().split(`
218
- `),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 jo(c.filter(l=>oi(n,am.join(n,l.file))===t))}function Fa(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 Rr(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function jo(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 oi(e,t){let n=am.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function kk(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mm(e,t,n,r){let i=wk(t,r);return i.size===0?new Map:Lk(e,n,i)}function wk(e,t){let n=new Map;for(let r of G(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 Lk(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of Ik(e,o)){let a=n.get(s);if(!a)continue;let c=Rr(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 Ik(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 Dk=q("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function fm(e,t,n,r){let i=hm(e,t),o=pm(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 pm(s,n)}function gm(e,t){let n=new Map;for(let[r,i]of hm(e,t)){let o=i[0];o&&n.set(r,o)}return n}function hm(e,t){return Dk.get(e,t,()=>{let n=new Map;for(let r of G(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 pm(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 Pk from"path";var si=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];function kn(e){let t=e.toLowerCase();return si.some(n=>t.endsWith(n))}function ym(e,t){let n=new Map,r=i=>kn(i)?st(n,i,()=>{let o=Pk.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:()=>O(e,{extensions:si})}}import Kt from"path";import{existsSync as Bo,readdirSync as Nk,readFileSync as bm}from"fs";function Sm(e){let t=Kt.join(e,"package.json");if(!Bo(t))return[];let n;try{n=JSON.parse(bm(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>Ek(e,i)).flatMap(i=>Tk(e,i))}function Ek(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=Kt.join(e,t);return Bo(Kt.join(s,"package.json"))?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=Kt.join(e,r||".");if(!Bo(o))return[];try{return Nk(o).map(s=>Kt.join(o,s,i)).filter(s=>Bo(Kt.join(s,"package.json")))}catch{return[]}}function Tk(e,t){try{let n=JSON.parse(bm(Kt.join(t,"package.json"),"utf8"));if(!n.name)return[];let r=Kt.relative(e,t).replace(/\\/g,"/");return[{name:n.name,rootRelative:r,sourceRootRelative:`${r}/src`}]}catch{return[]}}function xm(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function Cm(e){return[`${e.sourceRootRelative}/index.ts`,`${e.sourceRootRelative}/index.tsx`,`${e.sourceRootRelative}/index.mts`,`${e.sourceRootRelative}/index.cts`]}import{existsSync as ai,readFileSync as _k,readdirSync as Fk,statSync as Ak}from"fs";import ue from"path";var $a=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Ma(e,t){let r=t?ue.dirname(ue.join(e,t)):e,i=ue.resolve(e);for(;r.startsWith(i);){for(let s of $a){let a=ue.join(r,s);if(ai(a))return a}let o=ue.dirname(r);if(o===r)break;r=o}for(let o of $a){let s=ue.join(e,o);if(ai(s))return s}return null}function vm(e){let t=e.config.projectRoot,n=new Set(Oa(t,e.config.semantic?.typescript?.tsconfigs)),r=O(e,{includeIgnored:!1,extensions:si});for(let i of r){let o=Ma(t,i);o&&n.add(ue.resolve(o))}if(n.size===0){let i=Ma(t);i&&n.add(ue.resolve(i))}return[...n].filter(i=>!Rm(t,i)).sort((i,o)=>i.localeCompare(o))}function Oa(e,t=[]){let n=new Set;for(let r of t){let i=ue.isAbsolute(r)?r:ue.join(e,r);ai(i)&&n.add(ue.resolve(i))}for(let r of $k(e))for(let i of $a){let o=ue.join(r,i);ai(o)&&n.add(ue.resolve(o))}if(n.size===0){let r=Ma(e);r&&n.add(ue.resolve(r))}return[...n].filter(r=>!Rm(e,r)).sort((r,i)=>r.localeCompare(i))}function $k(e){let t=ue.join(e,"package.json");if(!ai(t))return[];let n;try{n=JSON.parse(_k(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>Mk(e,i))}function Mk(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=ue.join(e,t);return Aa(s)?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=ue.join(e,r||".");return Aa(o)?Fk(o).map(s=>ue.join(o,s,i)).filter(Aa):[]}function Aa(e){try{return Ak(e).isDirectory()}catch{return!1}}function Rm(e,t){let n=ue.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 Ok}from"module";var jk=Ok(import.meta.url),ci;function km(){if(ci!==void 0)return ci;try{ci=jk("ts-morph")}catch{ci=null}return ci}function wm(e,t){return t.map(n=>({tsconfigPath:n,project:new e.Project({tsConfigFilePath:n,skipFileDependencyResolution:!1})}))}function Ho(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}function Dm(e,t){let n=km();if(!n)return Ho("ts-morph is not installed");let r=vm(e);if(r.length===0)return Ho("no tsconfig found");try{let i=wm(n,r);return new ja(e,n,i)}catch(i){return Ho(i instanceof Error?i.message:String(i),r[0],r)}}var ja=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=Sm(t.config.projectRoot),this.sourceFiles=ym(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 st(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 st(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t),r=this.packageImportReferencesForDefinition(t);return n?cm(n,t,r,this.db.config.projectRoot):r})}calleesFor(t){return st(this.calleesCache,t.symbolId,()=>st(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}signatureFor(t){return st(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 Im(c)}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${Im(o)}`})}importUsageForDeclaration(t,n){let r=ot(this.db,t,n.getModuleSpecifierValue()),i=Lm(n);return n.getImportClause()?.isTypeOnly()?i.map(o=>Bk(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 lm(l,t,r.identifier,this.db.config.projectRoot))o.push(u);let s=o.some(l=>!Fa(l.node)),a=o.some(l=>Fa(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,jo(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=xm(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of Lm(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=dm(a.identifier,r,this.db.config.projectRoot);l.length>0&&qk(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 Cm(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?ot(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,p=this.indexedDefinitionByLeaf(c,d);if(!p)continue;let g=r.get(m);g||(g=new Set,r.set(m,g)),g.add(p.symbolId)}}}indexedDefinitionByLeaf(t,n){return st(this.indexedDefinitionLeafCache,t,()=>gm(this.db,t)).get(n)??null}nodeForDefinition(t){return st(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return st(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?mm(this.tsMorph,this.db,n,t):new Map})}definitionFromSymbol(t){let n=t.getDeclarations();for(let r of n){let i=r.getSourceFile(),o=oi(this.db.config.projectRoot,i.getFilePath());if(!o||this.db.isIgnored(o))continue;let s=Rr(i,r),a=fm(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=G(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&&Hk(i,s.callerId,s.target)});for(let[o,s]of i)i.set(o,Uk(s));return i}semanticCalleeForCallNode(t,n,r){let i=Vk(n,Rr(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 Lm(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 Bk(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 Hk(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function Vk(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 qk(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function Uk(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 Im(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var Ba=new WeakMap;Bt({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>Ba.delete(e)});function Xt(e,t){let n=`${e.config.projectRoot}:typescript-workspace`,r=Ba.get(e);r||(r=new Map,Ba.set(e,r));let i=r.get(n);if(i)return i;let o=Dm(e,t);return r.set(n,o),o}function li(e,t){let n=qo(e,t);return n?n.importUsage(t):[]}function Qt(e,t){let n=qo(e,t.relativePath);return n?n.referencesFor(t):[]}function Xe(e,t){let n=new Map,r=Kr(e),i=[];for(let o of t){let s=Wk(e,o,r,i);for(let a of s){if(a.file===o.relativePath||e.isIgnored(a.file))continue;let c=n.get(o.symbolId);c||(c=new Set,n.set(o.symbolId,c)),c.add(a.file)}}return i.length>0&&Xt(e).availability().available&&Lu(e,i),n}function Wk(e,t,n,r){if(!n||!kn(t.relativePath))return Qt(e,t);let i=ku(e,t.relativePath,t.symbol,n);if(i!==null){let s=Gk(i);if(s)return s}let o=Qt(e,t);return r.push({relativePath:t.relativePath,symbol:t.symbol,projectFingerprint:n,payload:JSON.stringify(o)}),o}function Gk(e){try{return JSON.parse(e)}catch{return null}}function Vo(e,t){let n=new Map;for(let r of t){let i=qo(e,r.relativePath);if(!i)continue;let o=i.calleesFor(r);o.length>0&&n.set(r.symbolId,o)}return n}function Pm(e,t){let n=qo(e,t.relativePath);return n?n.signatureFor(t):null}function qo(e,t){if(!kn(t))return null;let n=Xt(e,t);return n.availability().available?n:null}var zk=q("source-import-paths-by-local-name",{clearGroups:["whole-project","source-file"]});function Uo(e,t){let n=Ao(t);return zk.get(e,n,()=>Jk(e,n))}function Jk(e,t){let n=new Map;for(let r of xe(e,t)){if(!r.sourcePath)continue;let i=r.localName??r.importedName;if(i&&Nm(n,i,r.sourcePath),r.kind==="namespace")for(let o of r.usedMembers)Nm(n,o,r.sourcePath)}return n}function Nm(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function kr(e,t,n){let r=Rn(e).get(n);if(!r||r.length===0)return[];if(r.length===1)return[ui(r[0])];let i=r.filter(c=>c.file===t);if(i.length>0)return i.map(ui);let o=Uo(e,t),s=o.get(n);if(s)for(let c of s){let l=r.filter(u=>Jt(c,u.file));if(l.length>0)return l.map(ui)}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=>Jt(c,u.file));if(l.length>0&&l.length===r.length)return l.map(ui)}return[]}function Tm(e,t,n){let r=kr(e,t,n);if(r.length>0)return r;let i=Rn(e).get(n);return!i||i.length===0?[]:i.map(ui)}function _m(e,t,n={}){let r=yo(e,t);if(!r)return[];let i=$(r.symbol);if(!i)return[];if(n.semantic!==!1){let s=Qt(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 Em(e,a)}}let o=new Map;for(let s of Ne(e)){let a=T(e,s);if(!a||a.indexOf(i)===-1||s!==r.relativePath&&!kr(e,s,i).some(u=>u.symbolId===r.symbolId))continue;let c=Fo(e,s,i,s===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{});c.length>0&&o.set(s,c)}return Em(e,o)}function Fm(e,t){let n=new Map;for(let a of t){if(!a.leaf)continue;let c=n.get(a.leaf)??[];c.push(a),n.set(a.leaf,c)}if(n.size===0)return new Map;let r=new Set(t.map(a=>a.symbolId)),i=new Set(n.keys()),o=ii(i),s=new Map;for(let a of Ne(e)){if(!Oo(T(e,a),o))continue;let c=tm(e,a);if(c.size!==0){for(let l of c)if(n.has(l))for(let u of kr(e,a,l)){if(!r.has(u.symbolId)||a===u.relativePath)continue;let d=s.get(u.symbolId);d||(d=new Set,s.set(u.symbolId,d)),d.add(a)}}}return s}function ui(e){return{symbolId:e.symbolId,symbol:e.symbol,relativePath:e.file}}function Em(e,t){let n=[],r=new Set;for(let[i,o]of t){let s=G(e,i);for(let a of o){let c=Ge(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 wn(e,t){let n=ew(e,t);return n?tw(e,Xk(e,n.match,n.identifier)):[]}function Yt(e,t,n={}){return Kk(e,t,n).map(r=>({file:r.file,line:r.line,enclosingSymbol:r.enclosingSymbol}))}function Kk(e,t,n={}){let r=_m(e,t,{semantic:n.semantic}),i=r.length>0?Am(r,"source-attribution"):Am(wn(e,t),"scip-reference-chunk");return n.includeIgnored===!0?i:i.filter(o=>!e.isIgnored(o.file))}function Am(e,t){return e.map(n=>({...n,provenance:t}))}function Xk(e,t,n){let r=new Map;for(let[i,o]of Qk(e,t.symbolId))r.set(i,Yk(e,i,o,t,n));return r}function Qk(e,t){let n=new Map;for(let r of vr(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 Yk(e,t,n,r,i){let o=t===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{},s=i?Fo(e,t,i,o):[];return n.flatMap(a=>Zk(s,a))}function Zk(e,t){let n=e.filter(r=>r>=t.start_line&&r<=t.end_line);return n.length>0?n:[t.start_line]}function ew(e,t){let n=yo(e,t);return n?{match:n,identifier:$(n.symbol)||null}:null}function tw(e,t){let n=[],r=new Set;for(let[i,o]of t){let s=G(e,i);for(let a of o){let c=Ge(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 He(e,t,n={}){let r=Wo(e,[t],{additive:n.additive,semantic:n.semantic}),i=n.callableOnly?(r.get(t.symbolId)??[]).filter(o=>ie(o.symbol)):r.get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}function Mm(e,t,n={}){let r=iw(e)?sw(e,t,{semantic:n.semantic!==!1}):ow(e).get(t.symbolId)??[];return typeof n.limit=="number"?r.slice(0,n.limit):r}var nw=Z("caller-rows",{clearGroups:["whole-project"]}),rw=2e4;function iw(e){return(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>rw}function ow(e){return nw.get(e,()=>{let t=ft(e),n=Wo(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 sw(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 wn(e,t))a.file!==t.relativePath&&o({symbol:a.enclosingSymbol??a.file,file:a.file,source:"resolved-reference"});let s=n.semantic?aw(e,t):null;if(s)for(let a of Qt(e,s)){if(a.file===t.relativePath||e.isIgnored(a.file))continue;let c=Ge(G(e,a.file),a.line);o({symbol:c?.symbol??a.file,file:a.file,source:"semantic-reference"})}return r}function aw(e,t){return e.get(`SELECT
239
+ ${e.symbolNoiseFor("gs")}`),n=new Map;for(let i of t){if(!i.relative_path||e.isIgnored(i.relative_path))continue;let r=$(i.symbol);if(!r)continue;let o=n.get(r);o||(o=[],n.set(r,o)),o.some(s=>s.symbolId===i.id)||o.push({symbol:i.symbol,symbolId:i.id,file:i.relative_path})}return n})}var Ip=/[A-Za-z_$][A-Za-z0-9_$]*/g,Lp=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function Rr(e){let t=[],n=!1;for(let i of e)i&&(n=!0,Lp.test(i)||t.push(i));return{candidateNames:e,hasUsableCandidate:n,nonIdentifierNames:t}}function ps(e,t){let n=mI(t)?t:Rr(t);if(n.candidateNames.size===0||!n.hasUsableCandidate)return!0;if(n.candidateNames.size<=512){for(let r of n.candidateNames)if(r){if(Lp.test(r)){if(pI(r).test(e))return!0;continue}if(e.includes(r))return!0}return!1}Ip.lastIndex=0;let i;for(;(i=Ip.exec(e))!==null;)if(n.candidateNames.has(i[0]))return!0;for(let r of n.nonIdentifierNames)if(e.includes(r))return!0;return!1}function mI(e){return"candidateNames"in e}function pI(e){return new RegExp(`(?<![A-Za-z_$0-9])${fI(e)}(?![A-Za-z_$0-9])`)}function fI(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}import{performance as K}from"perf_hooks";function ht(e,t,n){if(e.has(t))return e.get(t);let i=n();return e.set(t,i),i}import Dp from"path";function gI(e,t){return e.getReferences().map(n=>{let i=n.getNode();return fs(i,t)})}function hI(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function Ep(e,t,n,i){let r=[];for(let o of hI(e))for(let s of gI(o,i))s.file===t.relativePath&&s.line>=t.startLine&&s.line<=t.endLine||r.push(s);for(let o of n)r.push(o);return kr(r)}function Np(e,t,n,i){let r=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();wr(i,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||r.push({location:fs(a,i),node:a}))}return r}function fs(e,t){let n=e.getSourceFile(),i=n.getLineAndColumnAtPos(e.getStart());return{file:wr(t,n.getFilePath())??n.getBaseName(),line:i.line-1,column:i.column-1}}function Fp(e,t,n){let i=e.getSourceFile(),r=kc(i,e),o=e.getText(),s=new RegExp(`\\b${yI(o)}\\b`,"g"),a=i.getFullText().split(`
240
+ `),c=[];for(let l=0;l<a.length;l++){if(l===r)continue;let d=a[l]??"";s.lastIndex=0;let u;for(;(u=s.exec(d))!==null;)c.push({file:t,line:l,column:u.index})}return kr(c.filter(l=>wr(n,Dp.join(n,l.file))===t))}function Rc(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 kc(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function kr(e){let t=new Set,n=[];for(let i of e){let r=`${i.file}:${i.line}:${i.column}`;t.has(r)||(t.add(r),n.push(i))}return n}function wr(e,t){let n=Dp.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function yI(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Tp(e,t,n,i){let r=bI(t,i);return r.size===0?new Map:SI(e,n,r)}function bI(e,t){let n=new Map;for(let i of Q(e,t)){let r=$(i.symbol)??i.leaf;if(!r)continue;let o=n.get(r);o||(o=[],n.set(r,o)),o.push(i)}return n}function SI(e,t,n){let i=new Map,r=new Map;return t.forEachDescendant(o=>{for(let s of xI(e,o)){let a=n.get(s);if(!a)continue;let c=kc(t,o);for(let l of a){if(c<l.startLine-1||c>l.endLine+1)continue;let d=Math.abs(c-l.startLine),u=r.get(l.symbolId);u!==void 0&&u<=d||(r.set(l.symbolId,d),i.set(l.symbolId,o))}}}),i}function xI(e,t){let n=[],i=r=>{r&&!n.includes(r)&&n.push(r)};if("getNameNode"in t&&typeof t.getNameNode=="function"){let r=t.getNameNode();i(r?.getText())}if("getName"in t&&typeof t.getName=="function"){let r=t.getName();i(r)}return e.Node.isIdentifier(t)&&i(t.getText()),n}var CI=W("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function Ap(e,t,n,i){let r=$p(e,t),o=_p(r.get(i)??[],n);if(o)return o;let s=[];for(let a of r.values())for(let c of a)((c.leaf||$(c.symbol)||"").includes(i)||c.symbol.includes(i))&&s.push(c);return _p(s,n)}function Mp(e,t){let n=new Map;for(let[i,r]of $p(e,t)){let o=r[0];o&&n.set(i,o)}return n}function $p(e,t){return CI.get(e,t,()=>{let n=new Map;for(let i of Q(e,t)){let r=i.leaf||$(i.symbol);if(!r)continue;let o=n.get(r);o||(o=[],n.set(r,o)),o.push({...i,leaf:r})}for(let i of n.values())i.sort((r,o)=>r.startLine-o.startLine||r.endLine-o.endLine||r.symbolId-o.symbolId);return n})}function _p(e,t){let n=null,i=Number.POSITIVE_INFINITY;for(let r of e){let o=Math.abs(r.startLine-t);(o<i||o===i&&n&&r.startLine<n.startLine)&&(n=r,i=o)}return n}import wc from"path";var Pr=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];function Jt(e){let t=e.toLowerCase();return Pr.some(n=>t.endsWith(n))}function jp(e,t){let n=new Map,i=null,r=null,o=()=>(r??=O(e,{extensions:Pr}),r),s=()=>(i??=D("typescript.source-file-index",()=>vI(e.config.projectRoot,t,o()),()=>({projects:t.length,indexedDocuments:o().length})),i),a=c=>Jt(c)?ht(n,c,()=>{let l=Ir(wc.resolve(e.config.projectRoot,c));for(let{project:d,sourceFiles:u}of s()){let m=u.get(l)??null;if(m||(m=d.addSourceFileAtPathIfExists(l)??null,m&&u.set(Ir(m.getFilePath()),m)),m)return{project:d,sourceFile:m}}return null}):null;return{sourceFile:c=>a(c)?.sourceFile??null,sourceFileMatch:a,indexedTypeScriptLikeDocuments:o}}function vI(e,t,n){let i=t.map(({project:r})=>({project:r,sourceFiles:new Map(r.getSourceFiles().map(o=>[Ir(o.getFilePath()),o]))}));for(let r of n){let o=Ir(wc.resolve(e,r));for(let s of i){if(s.sourceFiles.has(o))break;let a=s.project.addSourceFileAtPathIfExists(o)??null;if(a){s.sourceFiles.set(Ir(a.getFilePath()),a);break}}}return i}function Ir(e){return wc.resolve(e)}import hn from"path";import{existsSync as gs,readdirSync as RI,readFileSync as Op}from"fs";function Bp(e){let t=hn.join(e,"package.json");if(!gs(t))return[];let n;try{n=JSON.parse(Op(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(r=>kI(e,r)).flatMap(r=>wI(e,r))}function kI(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=hn.join(e,t);return gs(hn.join(s,"package.json"))?[s]:[]}let n=t.indexOf("*"),i=t.slice(0,n).replace(/\/$/,""),r=t.slice(n+1).replace(/^\//,""),o=hn.join(e,i||".");if(!gs(o))return[];try{return RI(o).map(s=>hn.join(o,s,r)).filter(s=>gs(hn.join(s,"package.json")))}catch{return[]}}function wI(e,t){try{let n=JSON.parse(Op(hn.join(t,"package.json"),"utf8"));if(!n.name)return[];let i=hn.relative(e,t).replace(/\\/g,"/");return[{name:n.name,rootRelative:i,sourceRootRelative:`${i}/src`}]}catch{return[]}}function Hp(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function Vp(e){return[`${e.sourceRootRelative}/index.ts`,`${e.sourceRootRelative}/index.tsx`,`${e.sourceRootRelative}/index.mts`,`${e.sourceRootRelative}/index.cts`]}import{existsSync as Lr,readFileSync as PI,readdirSync as II,statSync as LI}from"fs";import Se from"path";var Ic=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Lc(e,t){let i=t?Se.dirname(Se.join(e,t)):e,r=Se.resolve(e);for(;i.startsWith(r);){for(let s of Ic){let a=Se.join(i,s);if(Lr(a))return a}let o=Se.dirname(i);if(o===i)break;i=o}for(let o of Ic){let s=Se.join(e,o);if(Lr(s))return s}return null}function qp(e){let t=e.config.projectRoot,n=new Set(Dc(t,e.config.semantic?.typescript?.tsconfigs)),i=O(e,{includeIgnored:!1,extensions:Pr});for(let r of i){let o=Lc(t,r);o&&n.add(Se.resolve(o))}if(n.size===0){let r=Lc(t);r&&n.add(Se.resolve(r))}return[...n].filter(r=>!Up(t,r)).sort((r,o)=>r.localeCompare(o))}function Dc(e,t=[]){let n=new Set;for(let i of t){let r=Se.isAbsolute(i)?i:Se.join(e,i);Lr(r)&&n.add(Se.resolve(r))}for(let i of DI(e))for(let r of Ic){let o=Se.join(i,r);Lr(o)&&n.add(Se.resolve(o))}if(n.size===0){let i=Lc(e);i&&n.add(Se.resolve(i))}return[...n].filter(i=>!Up(e,i)).sort((i,r)=>i.localeCompare(r))}function DI(e){let t=Se.join(e,"package.json");if(!Lr(t))return[];let n;try{n=JSON.parse(PI(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(r=>EI(e,r))}function EI(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=Se.join(e,t);return Pc(s)?[s]:[]}let n=t.indexOf("*"),i=t.slice(0,n).replace(/\/$/,""),r=t.slice(n+1).replace(/^\//,""),o=Se.join(e,i||".");return Pc(o)?II(o).map(s=>Se.join(o,s,r)).filter(Pc):[]}function Pc(e){try{return LI(e).isDirectory()}catch{return!1}}function Up(e,t){let n=Se.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 NI}from"module";var FI=NI(import.meta.url),Dr;function zp(){if(Dr!==void 0)return Dr;try{Dr=FI("ts-morph")}catch{Dr=null}return Dr}function Wp(e,t){return t.map(n=>({tsconfigPath:n,project:new e.Project({tsConfigFilePath:n,skipFileDependencyResolution:!0})}))}function hs(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}var TI=32;function Yp(e,t){let n=D("typescript.provider.load",()=>zp());if(!n)return hs("ts-morph is not installed");let i=D("typescript.provider.tsconfig-discovery",()=>qp(e));if(i.length===0)return hs("no tsconfig found");try{let r=D("typescript.provider.project-bundles",()=>Wp(n,i),()=>({tsconfigs:i.length}));return D("typescript.provider.construct",()=>new Ec(e,n,r),()=>({tsconfigs:i.length}))}catch(r){return hs(r instanceof Error?r.message:String(r),i[0],i)}}var Ec=class{constructor(t,n,i){this.db=t;this.tsMorph=n;this.projects=i;this.workspacePackages=Bp(t.config.projectRoot),this.sourceFiles=jp(t,i)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;compilerCheckerCache=new WeakMap;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(t=>t.tsconfigPath)}}importUsage(t){return ht(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let i=AI();return D("typescript.import-usage.file",()=>this.importUsageForSourceFile(t,n,i),()=>({file:t,...i}))})}referencesFor(t){return ht(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);return this.referencesForDefinitionNode(t,n)})}referencesForDefinitions(t){let n=new Map,i=me(),r=[];for(let c of t){let l=this.referencesCache.get(c.symbolId);l?n.set(c.symbolId,l):r.push(c)}if(r.length===0)return n;let o=r,s=r.filter(c=>!Kp(c));if(s.length>=TI){let c=this.referencesForDefinitionsBySymbolScan(s);for(let l of s){let d=c.get(l.symbolId)??[];this.referencesCache.set(l.symbolId,d),n.set(l.symbolId,d)}if(o=r.filter(l=>Kp(l)),o.length===0)return n}let a=new Map;for(let c of o){let l=a.get(c.relativePath);l?l.push(c):a.set(c.relativePath,[c])}for(let[c,l]of a){let d=Jp();D("typescript.references-map.file",()=>{let u=this.definitionNodesForFile(c);for(let m of l){i&&(d.cacheMisses+=1);let p=u.get(m.symbolId)??null;i&&(p?d.nodeHits+=1:d.nodeMisses+=1);let f=this.referencesForDefinitionNode(m,p,i?d:void 0);this.referencesCache.set(m.symbolId,f),n.set(m.symbolId,f)}},()=>({relativePath:c,definitions:l.length,...Xp(d)}))}return n}referencesForDefinitionsBySymbolScan(t){let n=me(),i=Jp(),r=new Map,o=new Set(t.map(a=>a.symbolId)),s=new Map(t.map(a=>[a.symbolId,a]));for(let a of t)r.set(a.symbolId,[]);return D("typescript.references-map.inverted-scan",()=>{let a=n?K.now():0;for(let u of t){let m=this.packageImportReferencesForDefinition(u);if(m.length>0){let p=r.get(u.symbolId)??[];p.push(...m),r.set(u.symbolId,p)}n&&(i.packageReferenceCount+=m.length)}n&&(i.packageRefsMs+=K.now()-a);let c=new Map,l=new Set(t.map(u=>u.leaf).filter(Boolean)),d=n?K.now():0;for(let u of this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(u))continue;let m=this.sourceFiles.sourceFile(u);m&&(n&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(m,u,o,s,l,c,r,n?i:void 0))}n&&(i.scanMs+=K.now()-d);for(let[u,m]of r){let p=kr(m);r.set(u,p),n&&(i.referenceCount+=p.length)}},()=>({definitions:t.length,...Xp(i)})),r}addReferencesFromSourceFileScan(t,n,i,r,o,s,a,c){let l=this.compilerCheckerForSourceFile(t),d=t.compilerNode,u=jI(t),m=p=>{if(this.tsMorph.ts.isIdentifier(p)){if(c&&(c.identifiers+=1),!o.has(p.text)&&!u.has(p.text)){this.tsMorph.ts.forEachChild(p,m);return}let f=this.compilerReferenceSymbol(l,p,c);if(f){let g;if(s.has(f)?g=s.get(f)??null:(g=this.definitionFromCompilerSymbol(f),s.set(f,g)),c&&(g?c.targetHits+=1:c.targetMisses+=1),g&&i.has(g.symbolId)){c&&(c.requestedHits+=1);let b=r.get(g.symbolId);if(b&&!BI(b,n,Gp(d,p))){let x=a.get(g.symbolId)??[],S=d.getLineAndCharacterOfPosition(p.getStart(d));x.push({file:n,line:S.line,column:S.character}),a.set(g.symbolId,x)}}}}this.tsMorph.ts.forEachChild(p,m)};m(d)}compilerReferenceSymbol(t,n,i){i&&(i.symbolLookups+=1);let r=t.getSymbolAtLocation(n);if(r){if((r.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return r;try{return i&&(i.aliasResolutions+=1),t.getAliasedSymbol(r)}catch{return r}}}calleesFor(t){return ht(this.calleesCache,t.symbolId,()=>ht(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}calleesForDefinitions(t){let n=new Map,i=new Map;for(let r of t){let o=i.get(r.relativePath);o?o.push(r):i.set(r.relativePath,[r])}for(let[r,o]of i){let s=this.fileCalleesCache.get(r),a=new Set(o.map(l=>l.symbolId)),c=s??this.calleeMapForFile(r,a);for(let l of o){let d=c.get(l.symbolId)??[];this.calleesCache.set(l.symbolId,d),n.set(l.symbolId,d)}}return n}referencesForDefinitionNode(t,n,i){let r=i?K.now():0,o=this.packageImportReferencesForDefinition(t);if(i&&(i.packageRefsMs+=K.now()-r,i.packageReferenceCount+=o.length),!n)return o;let s=i?K.now():0,a=Ep(n,t,o,this.db.config.projectRoot);return i&&(i.semanticRefsMs+=K.now()-s,i.referenceCount+=a.length),a}signatureFor(t){return ht(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 i=n.getType().getCallSignatures()[0];if(!i)return null;let r=i.getParameters().map(s=>{let a=s.getDeclarations()[0],c=a?s.getTypeAtLocation(a).getText(a):s.getValueDeclaration()?.getType().getText()??"unknown";return Qp(c)}),o=i.getReturnType().getText(n);return`(${r.join(",")})=>${Qp(o)}`})}importUsageForSourceFile(t,n,i){let r=[],o=new Map;for(let s of n.getImportDeclarations()){i.declarations+=1;let a=ft(this.db,t,s.getModuleSpecifierValue()),c=s.getImportClause()?.isTypeOnly()??!1;for(let l of Nc(s)){i.entries+=1;let d=c?null:l.identifier?.getSymbol()?.compilerSymbol??null;!c&&l.identifier&&(d?i.bindingSymbols+=1:i.missingBindingSymbols+=1);let u={sourcePath:a,entry:l,typeOnlyDeclaration:c,bindingSymbol:d,references:[]};if(r.push(u),c||!l.localName||!d)continue;let m=o.get(l.localName);m?m.push(u):o.set(l.localName,[u])}}return o.size>0&&n.forEachDescendant(s=>{if(s.getKindName()!=="Identifier")return;let a=o.get(s.getText());if(!a||MI(s))return;i.scannedIdentifiers+=1;let c=s.getSymbol()?.compilerSymbol;if(i.symbolLookups+=1,!!c){for(let l of a)if(l.bindingSymbol===c){l.references.push({location:fs(s,this.db.config.projectRoot),node:s}),i.matchedReferences+=1;break}}}),r.map(s=>s.typeOnlyDeclaration?_I(t,s.sourcePath,s.entry):s.entry.identifier&&!s.bindingSymbol?(i.fallbackEntries+=1,this.valueImportUsageForEntry(t,s.sourcePath,s.entry)):this.valueImportUsageFromLocations(t,s.sourcePath,s.entry,s.references))}valueImportUsageForEntry(t,n,i){let r=i.identifier?i.identifier.findReferences():[],o=[];for(let s of r)for(let a of Np(s,t,i.identifier,this.db.config.projectRoot))o.push(a);return this.valueImportUsageFromLocations(t,n,i,o)}valueImportUsageFromLocations(t,n,i,r){let o=r.some(c=>!Rc(c.node)),s=r.some(c=>Rc(c.node)),a=i.isTypeOnly;return{importer:t,sourcePath:n,importedName:i.importedName,localName:i.localName,kind:i.kind,isTypeOnly:a,isUsed:a||r.length>0,isTypeUsed:a||s,isValueUsed:o,references:r.map(c=>c.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 i of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(t,n,i);for(let[i,r]of t)t.set(i,kr(r));return this.packageImportReferenceIndex=t,t}addPackageImportReferencesForDocument(t,n,i){if(this.db.isIgnored(i))return;let r=this.sourceFiles.sourceFileMatch(i);if(r)for(let o of r.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(t,n,i,o)}addPackageImportReferencesForDeclaration(t,n,i,r){let o=Hp(this.workspacePackages,r.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of Nc(r)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=Fp(a.identifier,i,this.db.config.projectRoot);l.length>0&&qI(t,c,l)}}packageExports(){if(this.packageExportIndex)return this.packageExportIndex;let t=new Map;for(let n of this.workspacePackages){let i=new Map;for(let r of Vp(n))this.collectPackageExports(n,r,i,new Set);i.size>0&&t.set(n.name,i)}return this.packageExportIndex=t,t}collectPackageExports(t,n,i,r){if(r.has(n))return;r.add(n);let o=this.sourceFiles.sourceFile(n);if(o)for(let s of o.getExportDeclarations()){let a=s.getModuleSpecifierValue(),c=a?ft(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,i,r);continue}for(let d of l){let u=d.getNameNode().getText(),m=d.getAliasNode()?.getText()??u,p=this.indexedDefinitionByLeaf(c,u);if(!p)continue;let f=i.get(m);f||(f=new Set,i.set(m,f)),f.add(p.symbolId)}}}indexedDefinitionByLeaf(t,n){return ht(this.indexedDefinitionLeafCache,t,()=>Mp(this.db,t)).get(n)??null}nodeForDefinition(t){return ht(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return ht(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?Tp(this.tsMorph,this.db,n,t):new Map})}definitionFromCompilerSymbol(t,n){let i=t.name,r=n?K.now():0,o=t.declarations??[];n&&(n.declarationsMs+=K.now()-r,n.declarationChecks+=o.length);for(let s of o){let a=n?K.now():0,c=s.getSourceFile(),l=wr(this.db.config.projectRoot,c.fileName),d=c.getLineAndCharacterOfPosition(s.getStart(c)).line;if(n&&(n.declarationLocationMs+=K.now()-a),!l||this.db.isIgnored(l))continue;let u=n?K.now():0,m=Ap(this.db,l,d,i);if(n&&(n.indexedLookupMs+=K.now()-u),m)return{symbolId:m.symbolId,symbol:m.symbol,file:m.relativePath,line:m.startLine}}return null}calleeMapForFile(t,n){let i=me(),r=0,o=0,s=0,a=0,c=0,l=0,d=0,u=0,m=i?HI():void 0;return D("typescript.callee-map.file",()=>{let p=i?K.now():0,f=this.sourceFiles.sourceFile(t);if(i&&(c=Math.round(K.now()-p)),!f)return new Map;let g=i?K.now():0,b=Q(this.db,t).sort((k,T)=>k.startLine-T.startLine||T.endLine-k.endLine);if(i&&(l=Math.round(K.now()-g)),r=b.length,b.length===0)return new Map;let x=new Map,S=i?K.now():0,R=this.compilerCheckerForSourceFile(f),C=f.compilerNode;i&&(d=Math.round(K.now()-S));let y=new Map,w=k=>{if(this.tsMorph.ts.isCallExpression(k)||this.tsMorph.ts.isNewExpression(k)){i&&(o+=1);let T=this.semanticCalleeForCallNode(R,C,b,k,y,n,m);T&&(i&&(s+=1),$I(x,T.callerId,T.target))}this.tsMorph.ts.forEachChild(k,w)},L=i?K.now():0;w(C),i&&(u=Math.round(K.now()-L));for(let[k,T]of x)x.set(k,UI(T));return a=x.size,x},()=>({relativePath:t,definitions:r,callNodes:o,resolvedCallees:s,outputRows:a,requestedDefinitions:n?.size??r,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:d,traversalMs:u,...m?VI(m):{}}))}semanticCalleeForCallNode(t,n,i,r,o,s,a){let c=a?K.now():0,l=OI(i,Gp(n,r));if(a&&(a.callerLookupMs+=K.now()-c),!l)return null;if(s&&!s.has(l.symbolId))return a&&(a.skippedUnrequestedCallers+=1),null;let d=r.expression,u=this.compilerSymbolForExpression(t,d,a),m=null;if(u)if(a&&(a.targetSymbolHits+=1),o.has(u))a&&(a.compilerSymbolCacheHits+=1),m=o.get(u)??null;else{a&&(a.compilerSymbolCacheMisses+=1);let p=a?K.now():0;m=this.definitionFromCompilerSymbol(u,a),a&&(a.targetLookupMs+=K.now()-p),o.set(u,m)}else a&&(a.targetMisses+=1);return m?{callerId:l.symbolId,target:{symbol:m.symbol,file:m.file,line:m.line}}:null}compilerSymbolForExpression(t,n,i){let r=i?K.now():0,o=t.getSymbolAtLocation(n);if(i&&(i.expressionSymbolMs+=K.now()-r),o)return o;i&&(i.typeFallbacks+=1);let s=i?K.now():0,a=t.getTypeAtLocation(n).getSymbol();return i&&(i.typeSymbolMs+=K.now()-s),a}compilerCheckerForSourceFile(t){let n=t.getProject(),i=this.compilerCheckerCache.get(n);return i||(i=n.getTypeChecker().compilerObject,this.compilerCheckerCache.set(n,i)),i}};function Nc(e){let t=[],n=e.getDefaultImport();n&&t.push({identifier:n,importedName:"default",localName:n.getText(),kind:"default",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});let i=e.getNamespaceImport();i&&t.push({identifier:i,importedName:"*",localName:i.getText(),kind:"namespace",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});for(let r of e.getNamedImports()){let o=r.getNameNode(),a=r.getAliasNode()??(o.getKindName()==="Identifier"?o:null);t.push({identifier:a,importedName:o.getText(),localName:a?.getText()??o.getText(),kind:"named",isTypeOnly:r.isTypeOnly()||(e.getImportClause()?.isTypeOnly()??!1)})}return t.length===0&&t.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),t}function _I(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 AI(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function MI(e){for(let t=e;t;t=t.getParent())if(t.getKindName()==="ImportDeclaration")return!0;return!1}function $I(e,t,n){let i=e.get(t);i||(i=[],e.set(t,i)),i.push(n)}function jI(e){let t=new Set;for(let n of e.getImportDeclarations())for(let i of Nc(n))i.localName&&t.add(i.localName);return t}function OI(e,t){let n=null;for(let i of e)t<i.startLine||t>i.endLine||(!n||i.startLine>=n.startLine)&&(n=i);return n}function Gp(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line}function BI(e,t,n){return t===e.relativePath&&n>=e.startLine&&n<=e.endLine}function Kp(e){return e.symbol.includes("#")?se(e.symbol)==="type"&&e.relativePath.endsWith(".d.ts"):!1}function HI(){return{callerLookupMs:0,expressionSymbolMs:0,typeSymbolMs:0,targetLookupMs:0,declarationsMs:0,declarationLocationMs:0,indexedLookupMs:0,compilerSymbolCacheHits:0,compilerSymbolCacheMisses:0,targetSymbolHits:0,targetMisses:0,typeFallbacks:0,declarationChecks:0,skippedUnrequestedCallers:0}}function VI(e){return{...e,callerLookupMs:Math.round(e.callerLookupMs),expressionSymbolMs:Math.round(e.expressionSymbolMs),typeSymbolMs:Math.round(e.typeSymbolMs),targetLookupMs:Math.round(e.targetLookupMs),declarationsMs:Math.round(e.declarationsMs),declarationLocationMs:Math.round(e.declarationLocationMs),indexedLookupMs:Math.round(e.indexedLookupMs)}}function Jp(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0}}function Xp(e){return{...e,scanMs:Math.round(e.scanMs),packageRefsMs:Math.round(e.packageRefsMs),semanticRefsMs:Math.round(e.semanticRefsMs)}}function qI(e,t,n){for(let i of t){let r=e.get(i)??[];r.push(...n),e.set(i,r)}}function UI(e){let t=new Set,n=[];for(let i of e){let r=`${i.symbol}|${i.file}|${i.line}`;t.has(r)||(t.add(r),n.push(i))}return n}function Qp(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var Fc=new WeakMap;on({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>Fc.delete(e)});function Tc(e,t){let n=`${e.config.projectRoot}:typescript-workspace`,i=Fc.get(e);i||(i=new Map,Fc.set(e,i));let r=i.get(n);if(r)return r;let o=Yp(e,t);return i.set(n,o),o}function Xt(e){return{capability:(t,n)=>rf(e,t,n),importUsage:t=>zI(e,t),references:t=>WI(e,t),callerMap:t=>GI(e,t),calleeMap:t=>XI(e,t),signature:t=>QI(e,t)}}function Er(e,t){return Xt(e).importUsage(t)}function zI(e,t){let n=Nr(e,t);return n?n.importUsage(t):[]}function $i(e,t){return Xt(e).references(t)}function WI(e,t){let n=Nr(e,t.relativePath);return n?n.referencesFor(t):[]}function st(e,t){return Xt(e).callerMap(t)}function GI(e,t){let n=me(),i=new Map,r=In(e),o=[],s=[],a=[],c=0,l=0,d=0,u=0;if(D("semantic.references.cache-scan",()=>{for(let m of t){if(!r||!Jt(m.relativePath)){n&&!Jt(m.relativePath)&&(c+=1),a.push(m);continue}let p=wd(e,m.relativePath,m.symbol,r);if(p!==null){let f=JI(p);if(f){n&&(l+=1),u+=ef(e,i,m,f);continue}n&&(d+=1)}s.push(m)}},()=>({definitions:t.length,skippedNonTs:c,cacheHits:l,parseFailures:d,misses:s.length,unkeyed:a.length,resultRows:i.size,callerFiles:u})),s.length>0||a.length>0){let m=[...a,...s],p=0,f=D("semantic.references.compute-misses",()=>{let g=KI(e,m);return p=g.size,g},()=>({definitions:m.length,misses:s.length,unkeyed:a.length,rows:p}));for(let g of m)u+=ef(e,i,g,f.get(g.symbolId)??[]);if(r)for(let g of s)o.push({relativePath:g.relativePath,symbol:g.symbol,projectFingerprint:r,payload:JSON.stringify(f.get(g.symbolId)??[])})}return o.length>0&&(rf(e,"semantic-references").available?D("semantic.references.cache-write",()=>Id(e,o),()=>({entries:o.length})):D("semantic.references.cache-write-skip",()=>{},()=>({reason:"provider-unavailable",entries:o.length}))),i}function KI(e,t){let n=me(),i=new Map,r=0,o=0,s=0,a=0;return D("semantic.references.provider-loop",()=>{let c=new Map,l=[];for(let d of t){let u=Nr(e,d.relativePath);if(!u){n&&(o+=1);continue}if(n&&(r+=1),u.referencesForDefinitions){let m=c.get(u);m?m.push(d):c.set(u,[d])}else l.push({provider:u,definition:d})}for(let[d,u]of c){let m=d.referencesForDefinitions(u);for(let p of u){let f=m.get(p.symbolId)??[];Zp(i,p.symbolId,f,n,g=>{s+=1,a+=g})}}for(let{provider:d,definition:u}of l){let m=d.referencesFor(u);Zp(i,u.symbolId,m,n,p=>{s+=1,a+=p})}return i},()=>({definitions:t.length,providerHits:r,providerMisses:o,definitionsWithReferences:s,referenceCount:a,rows:i.size}))}function Zp(e,t,n,i,r){e.set(t,n),i&&n.length>0&&r(n.length)}function ef(e,t,n,i){let r=0;for(let o of i){if(o.file===n.relativePath||e.isIgnored(o.file))continue;let s=t.get(n.symbolId);s||(s=new Set,t.set(n.symbolId,s));let a=s.size;s.add(o.file),s.size!==a&&(r+=1)}return r}function JI(e){try{return JSON.parse(e)}catch{return null}}function ys(e,t){return Xt(e).calleeMap(t)}function XI(e,t){let n=me(),i=new Map,r=0,o=0,s=0,a=0;return D("semantic.callees.provider-loop",()=>{let c=new Map,l=[];for(let d of t){let u=Nr(e,d.relativePath);if(!u){n&&(o+=1);continue}n&&(r+=1);let m=d;if(u.calleesForDefinitions){let p=c.get(u);p?p.push(m):c.set(u,[m])}else l.push({provider:u,definition:m})}for(let[d,u]of c){let m=d.calleesForDefinitions(u);for(let p of u){let f=m.get(p.symbolId)??[];tf(i,p.symbolId,f,n,g=>{s+=1,a+=g})}}for(let{provider:d,definition:u}of l){let m=d.calleesFor(u);tf(i,u.symbolId,m,n,p=>{s+=1,a+=p})}return i},()=>({definitions:t.length,providerHits:r,providerMisses:o,definitionsWithCallees:s,calleeCount:a,rows:i.size}))}function tf(e,t,n,i,r){n.length>0&&(e.set(t,n),i&&r(n.length))}function nf(e,t){return Xt(e).signature(t)}function QI(e,t){let n=Nr(e,t.relativePath);return n?n.signatureFor(t):null}function rf(e,t,n){if(n!==void 0&&!Jt(n))return{slot:t,language:"typescript",available:!1,reason:"semantic evidence is only available for TypeScript files"};try{return{slot:t,language:"typescript",...Tc(e,n).availability()}}catch(i){return{slot:t,language:"typescript",available:!1,reason:i instanceof Error?i.message:String(i)}}}function Nr(e,t){if(!Jt(t))return null;let n=Tc(e,t);return n.availability().available?n:null}var YI=W("source-import-paths-by-local-name",{clearGroups:["whole-project","source-file"]});function bs(e,t){let n=us(t);return YI.get(e,n,()=>ZI(e,n))}function ZI(e,t){let n=new Map;for(let i of oe(e,t)){if(!i.sourcePath)continue;let r=i.localName??i.importedName;if(r&&of(n,r,i.sourcePath),i.kind==="namespace")for(let o of i.usedMembers)of(n,o,i.sourcePath)}return n}function of(e,t,n){let i=e.get(t);i||(i=new Set,e.set(t,i)),i.add(n)}function ji(e,t,n){let i=Hn(e).get(n);if(!i||i.length===0)return[];if(i.length===1)return[Fr(i[0])];let r=i.filter(c=>c.file===t);if(r.length>0)return r.map(Fr);let o=bs(e,t),s=o.get(n);if(s)for(let c of s){let l=i.filter(d=>Dt(c,d.file));if(l.length>0)return l.map(Fr)}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=i.filter(d=>Dt(c,d.file));if(l.length>0&&l.length===i.length)return l.map(Fr)}return[]}function af(e,t,n){let i=ji(e,t,n);if(i.length>0)return i;let r=Hn(e).get(n);return!r||r.length===0?[]:r.map(Fr)}function cf(e,t,n={}){let i=os(e,t);if(!i)return[];let r=$(i.symbol);if(!r)return[];if(n.semantic!==!1){let s=$i(e,{...i,leaf:r,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 sf(e,a)}}let o=new Map;for(let s of et(e)){let a=M(e,s);if(!a||a.indexOf(r)===-1||s!==i.relativePath&&!ji(e,s,r).some(d=>d.symbolId===i.symbolId))continue;let c=cs(e,s,r,s===i.relativePath?{excludeStartLine:i.startLine,excludeEndLine:i.endLine}:{});c.length>0&&o.set(s,c)}return sf(e,o)}function lf(e,t,n={}){let i=new Map;for(let c of t){if(!c.leaf)continue;let l=i.get(c.leaf)??[];l.push(c),i.set(c.leaf,l)}if(i.size===0)return new Map;let r=new Set(t.map(c=>c.symbolId)),o=new Set(i.keys()),s=Rr(o),a=new Map;for(let c of et(e)){if(n.skipPath?.(c)||!ps(M(e,c),s))continue;let l=Cp(e,c);if(l.size!==0){for(let d of l)if(i.has(d))for(let u of ji(e,c,d)){if(!r.has(u.symbolId)||c===u.relativePath)continue;let m=a.get(u.symbolId);m||(m=new Set,a.set(u.symbolId,m)),m.add(c)}}}return a}function Fr(e){return{symbolId:e.symbolId,symbol:e.symbol,relativePath:e.file}}function sf(e,t){let n=[],i=new Set;for(let[r,o]of t){let s=Q(e,r);for(let a of o){let c=ot(s,a),l=`${r}|${a}|${c?.symbol??""}`;i.has(l)||(i.add(l),n.push({file:r,line:a,enclosingSymbol:c?.symbol??null}))}}return n}function Vn(e,t){let n=oL(e,t);return n?sL(e,tL(e,n.match,n.identifier)):[]}function yn(e,t,n={}){return eL(e,t,n).map(i=>({file:i.file,line:i.line,enclosingSymbol:i.enclosingSymbol}))}function eL(e,t,n={}){let i=cf(e,t,{semantic:n.semantic}),r=i.length>0?uf(i,"source-attribution"):uf(Vn(e,t),"scip-reference-chunk");return n.includeIgnored===!0?r:r.filter(o=>!e.isIgnored(o.file))}function uf(e,t){return e.map(n=>({...n,provenance:t}))}function tL(e,t,n){let i=new Map;for(let[r,o]of nL(e,t.symbolId))i.set(r,iL(e,r,o,t,n));return i}function nL(e,t){let n=new Map;for(let i of Mi(e,[t])){if(e.isIgnored(i.relative_path))continue;let r=n.get(i.relative_path);r||(r=[],n.set(i.relative_path,r)),r.push({start_line:i.chunk_start,end_line:i.chunk_end})}return n}function iL(e,t,n,i,r){let o=t===i.relativePath?{excludeStartLine:i.startLine,excludeEndLine:i.endLine}:{},s=r?cs(e,t,r,o):[];return n.flatMap(a=>rL(s,a))}function rL(e,t){let n=e.filter(i=>i>=t.start_line&&i<=t.end_line);return n.length>0?n:[t.start_line]}function oL(e,t){let n=os(e,t);return n?{match:n,identifier:$(n.symbol)||null}:null}function sL(e,t){let n=[],i=new Set;for(let[r,o]of t){let s=Q(e,r);for(let a of o){let c=ot(s,a),l=`${r}|${a}|${c?.symbol??""}`;i.has(l)||(i.add(l),n.push({file:r,line:a,enclosingSymbol:c?.symbol??null}))}}return n}import{SymbolInformation_Kind as ae}from"@c4312/scip";var Ss=new Map(Object.entries(ae).filter(([e,t])=>Number.isInteger(Number(e))&&typeof t=="string").map(([e,t])=>[Number(e),t])),df=new Map([...Ss.entries()].map(([e,t])=>[t.toLowerCase(),e]));function _c(e){return Ss.get(e)??"Unknown"}function mf(){return[ae.Function,ae.Method,ae.Macro,ae.Constructor,ae.Getter,ae.Setter,ae.StaticMethod,ae.SingletonMethod,ae.AbstractMethod,ae.ProtocolMethod,ae.TraitMethod]}function pf(){return[ae.Class,ae.Interface,ae.Struct,ae.Trait,ae.Type,ae.TypeAlias,ae.Enum,ae.Union,ae.Protocol]}function Je(e,t,n={}){let i=xs(e,[t],{additive:n.additive,semantic:n.semantic}),r=n.callableOnly?(i.get(t.symbolId)??[]).filter(o=>he(o.symbol)||o.source==="ast-callsite"):i.get(t.symbolId)??[];return typeof n.limit=="number"?r.slice(0,n.limit):r}function gf(e,t,n={}){let i=lL(e)?dL(e,t,{semantic:n.semantic!==!1}):uL(e).get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}var aL=ie("caller-rows",{clearGroups:["whole-project"]}),cL=2e4;function lL(e){return(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>cL}function uL(e){return aL.get(e,()=>{let t=Lt(e),n=xs(e,t),i=new Map;for(let s of t)i.set(s.symbol,s.symbolId);let r=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=i.get(c.symbol);if(l===void 0||l===s.symbolId)continue;let d=r.get(l);d||(d=[],r.set(l,d),o.set(l,new Set));let u=`${s.symbol}|${s.relativePath}`;o.get(l).has(u)||(o.get(l).add(u),d.push({symbol:s.symbol,file:s.relativePath,source:"caller-map-inversion"}))}}return r})}function dL(e,t,n){let i=[],r=new Set,o=a=>{if(a.symbol===t.symbol)return;let c=`${a.symbol}|${a.file}`;r.has(c)||(r.add(c),i.push(a))};for(let a of Vn(e,t))a.file!==t.relativePath&&o({symbol:a.enclosingSymbol??a.file,file:a.file,source:"resolved-reference"});let s=n.semantic?mL(e,t):null;if(s)for(let a of $i(e,s)){if(a.file===t.relativePath||e.isIgnored(a.file))continue;let c=ot(Q(e,a.file),a.line);o({symbol:c?.symbol??a.file,file:a.file,source:"semantic-reference"})}return i}function mL(e,t){let n=mf().join(", "),i=pf().join(", ");return e.get(`SELECT
219
241
  d.id AS documentId,
220
242
  gs.id AS symbolId,
221
243
  gs.symbol,
@@ -224,8 +246,8 @@ ${m}`,l+=1+m.length,u+=ei(m),r+=m.length+1}let d=uR(c);d&&n.push({...d,start:a,e
224
246
  COALESCE(der.end_line, c.end_line) AS endLine,
225
247
  COALESCE(gs.display_name, '') AS leaf,
226
248
  NULL AS parentTypeName,
227
- CASE WHEN gs.kind IN (6, 12, 13) OR gs.symbol LIKE '%().' THEN 1 ELSE 0 END AS isFunctionLike,
228
- CASE WHEN gs.kind IN (5, 8, 11) THEN 1 ELSE 0 END AS isTypeLike,
249
+ CASE WHEN gs.kind IN (${n}) OR gs.symbol LIKE '%().' THEN 1 ELSE 0 END AS isFunctionLike,
250
+ CASE WHEN gs.kind IN (${i}) THEN 1 ELSE 0 END AS isTypeLike,
229
251
  gs.kind AS kind,
230
252
  gs.documentation AS documentation,
231
253
  gs.enclosing_symbol AS enclosingSymbol
@@ -234,11 +256,11 @@ ${m}`,l+=1+m.length,u+=ei(m),r+=m.length+1}let d=uR(c);d&&n.push({...d,start:a,e
234
256
  LEFT JOIN chunks c ON c.document_id = der.document_id
235
257
  JOIN documents d ON d.id = COALESCE(der.document_id, c.document_id)
236
258
  WHERE gs.id = ?
237
- LIMIT 1`,t.symbolId)??null}function Wo(e,t,n={}){if(t.length===0)return new Map;let r=n.additive??!1,i=[],o=[];for(let u of t)W(u.relativePath)&&rr(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 p=s.get(d);p||(p=[],s.set(d,p));let g=a.get(d);g||(g=new Set,a.set(d,g));for(let y of m){let h=`${y.symbol}|${y.chunkId}`;g.has(h)||(g.add(h),p.push(y))}}};i.length>0&&c(mw(e,i)),n.semantic!==!1&&c(hw(cw(e,t)));let l=r?t:o;return l.length>0&&c(gw(e,l)),s}function cw(e,t){let n=new Map,r=[],i=[];for(let s of t){if(!kn(s.relativePath))continue;let a=T(e,s.relativePath);if(!a){i.push(s);continue}let c=X(e,s.relativePath,a),l=dw(e,s.relativePath),u=Ru(e,s.relativePath,s.symbol,c,l);if(u!==null){let d=lw(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=Vo(e,[...i,...r.map(s=>s.def)]);for(let[s,a]of o)n.set(s,a);return Xt(e).availability().available&&wu(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 lw(e){try{return JSON.parse(e)}catch{return null}}var uw=q("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function dw(e,t){return uw.get(e,t,()=>{let r=[...ce(e).get(t)??[]].sort().map(i=>`${i}:${X(e,i,T(e,i))}`);return er(r.join("|"))})}function mw(e,t){let n=new Map,r=pw(t,n),i=Rn(e);for(let[o,s]of r){let a=rr(e,o);if(!a)continue;let c=ya(s);for(let l of a){let u=c.get(l.line);if(!u)continue;let d=fw(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 pw(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 fw(e,t,n,r,i){let o=$o(t,n.get(r)??[]);return o.length===0?null:Mo(e,t,o,i)}function gw(e,t){if(t.length===0)return new Map;let r=Ha(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
259
+ LIMIT 1`,t.symbolId)??null}function xs(e,t,n={}){if(t.length===0)return new Map;let i=n.additive??!1,r=[],o=[];for(let d of t)H(d.relativePath)&&xi(e,d.relativePath)!==null?r.push(d):o.push(d);let s=new Map,a=new Map,c=d=>{for(let[u,m]of d){let p=s.get(u);p||(p=[],s.set(u,p));let f=a.get(u);f||(f=new Set,a.set(u,f));for(let g of m){let b=`${g.symbol}|${g.chunkId}`;f.has(b)||(f.add(b),p.push(g))}}};r.length>0&&c(yL(e,r)),n.semantic!==!1&&c(RL(pL(e,t)));let l=i?t:o;return l.length>0&&c(CL(e,l)),s}function pL(e,t){let n=me(),i=new Map,r=[],o=[],s=0,a=0,c=0,l=0;if(D("semantic.callees.cache-scan",()=>{for(let f of t){if(!Jt(f.relativePath)){n&&(s+=1);continue}let g=M(e,f.relativePath);if(!g){n&&(a+=1),o.push(f);continue}let b=re(e,f.relativePath,g),x=hL(e,f.relativePath),S=kd(e,f.relativePath,f.symbol,b,x);if(S!==null){let R=fL(S);if(R){n&&(c+=1),R.length>0&&i.set(f.symbolId,R);continue}n&&(l+=1)}r.push({def:f,contentHash:b,depsDigest:x})}},()=>({definitions:t.length,skippedNonTs:s,sourceMissing:a,cacheHits:c,parseFailures:l,misses:r.length,unkeyed:o.length,resultRows:i.size})),r.length===0&&o.length===0)return i;let d=[...o,...r.map(f=>f.def)],u=0,m=D("semantic.callees.compute-misses",()=>{let f=ys(e,d);return u=f.size,f},()=>({definitions:d.length,misses:r.length,unkeyed:o.length,rows:u}));for(let[f,g]of m)i.set(f,g);if(Xt(e).capability("semantic-callees").available){let f=r.map(g=>({relativePath:g.def.relativePath,symbol:g.def.symbol,contentHash:g.contentHash,depsDigest:g.depsDigest,payload:JSON.stringify(m.get(g.def.symbolId)??[])}));D("semantic.callees.cache-write",()=>Pd(e,f),()=>({entries:f.length}))}else D("semantic.callees.cache-write-skip",()=>{},()=>({reason:"provider-unavailable",misses:r.length}));return i}function fL(e){try{return JSON.parse(e)}catch{return null}}var gL=W("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function hL(e,t){return gL.get(e,t,()=>{let i=[...ye(e).get(t)??[]].sort().map(r=>`${r}:${re(e,r,M(e,r))}`);return Vt(i.join("|"))})}function yL(e,t){let n=new Map,i=bL(t,n),r=Hn(e);for(let[o,s]of i){let a=xi(e,o);if(!a)continue;let c=yc(s);for(let l of a){let d=c.get(l.line);if(!d)continue;let u=SL(e,o,r,l);u&&u.symbol!==d.symbol&&n.get(d.symbolId).push({symbol:u.symbol,file:u.file,chunkId:l.line,source:"ast-callsite"})}}return n}function bL(e,t){let n=new Map;for(let i of e){let r=n.get(i.relativePath);r?r.push(i):n.set(i.relativePath,[i]),t.set(i.symbolId,[])}for(let i of n.values())i.sort((r,o)=>r.endLine-r.startLine-(o.endLine-o.startLine));return n}function SL(e,t,n,i){let r=ds(t,n.get(i.calleeLeaf)??[]);if(r.length===0)return null;let o=xL(e,t,r,i.calleeQualifier);return o||ms(e,t,r,i.memberAccess)}function xL(e,t,n,i){if(!i||H(t)!=="clojure")return null;let o=oe(e,t).filter(s=>s.kind==="namespace"&&s.localName===i&&s.sourcePath).map(s=>s.sourcePath);for(let s of o){let a=n.find(c=>Dt(s,c.file));if(a)return a}return n.find(s=>/`([^`]+)`\//.exec(s.symbol)?.[1]===i)??null}function CL(e,t){if(t.length===0)return new Map;let i=Ac(t.map(p=>p.documentId)).flatMap(p=>e.all(`SELECT c.document_id, c.id AS chunk_id, c.start_line, c.end_line, m.symbol_id
238
260
  FROM mentions m
239
261
  JOIN chunks c ON m.chunk_id = c.id
240
262
  WHERE m.role != 1
241
- 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=Ha(r.map(m=>m.symbol_id)).flatMap(m=>e.all(`SELECT gs.id AS symbol_id, gs.symbol,
263
+ AND c.document_id IN (${p.map(()=>"?").join(",")})`,...p)),r=new Map;for(let p of i)r.has(p.document_id)||r.set(p.document_id,[]),r.get(p.document_id).push(p);let s=Ac(i.map(p=>p.symbol_id)).flatMap(p=>e.all(`SELECT gs.id AS symbol_id, gs.symbol,
242
264
  COALESCE(der.document_id, def_chunk.document_id) AS document_id
243
265
  FROM global_symbols gs
244
266
  LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
@@ -247,14 +269,14 @@ ${m}`,l+=1+m.length,u+=ei(m),r+=m.length+1}let d=uR(c);d&&n.push({...d,start:a,e
247
269
  FROM mentions m
248
270
  JOIN chunks c ON m.chunk_id = c.id
249
271
  WHERE m.role = 1
250
- AND m.symbol_id IN (${m.map(()=>"?").join(",")})
272
+ AND m.symbol_id IN (${p.map(()=>"?").join(",")})
251
273
  GROUP BY m.symbol_id
252
274
  ) def_chunk ON def_chunk.symbol_id = gs.id
253
- WHERE gs.id IN (${m.map(()=>"?").join(",")})`,...m,...m)),a=Ha([...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
254
- WHERE id IN (${m.map(()=>"?").join(",")})`,...m).map(p=>[p.id,p.relative_path]))),l=new Map;for(let m of s)l.has(m.symbol_id)||l.set(m.symbol_id,{symbol:m.symbol,file:m.document_id!==null?c.get(m.document_id)??"":""});let u=new Map,d=c;for(let m of t){let p=i.get(m.documentId)??[],g=new Set,y=[],h=null,x=()=>{if(h)return h;let v=d.get(m.documentId)??"",R=new Set;if(v){let L=nm(e,v),S=Math.max(0,m.startLine),C=Math.min(L.length-1,m.endLine);for(let P=S;P<=C;P+=1)for(let D of L[P])R.add(D)}return h=R,R};for(let v of p){if(v.symbol_id===m.symbolId)continue;let R=l.get(v.symbol_id);if(!R)continue;if(!(v.start_line>=m.startLine&&v.end_line<=m.endLine)){if(!(v.start_line<=m.endLine&&v.end_line>=m.startLine))continue;let P=$(R.symbol);if(!P||!x().has(P))continue}let S=`${R.symbol}|${v.chunk_id}`;g.has(S)||(g.add(S),y.push({...R,chunkId:v.chunk_id,source:"scip-chunk"}))}u.set(m.symbolId,y)}return u}var $m=500;function Ha(e){let t=[...new Set(e)],n=[];for(let r=0;r<t.length;r+=$m)n.push(t.slice(r,r+$m));return n}function hw(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 Om(e,t,n={}){let r=new Map;if(t&&t.length===0)return r;let i=O(e,{includeIgnored:!1}),o=Rn(e),s=t??ft(e),a=new Set(s.map(l=>l.symbolId)),c=Rw(s);return yw(e,r,i,o,a,c),bw(e,r,s,a),vw(e,r,i,o,a,c),n.semantic!==!1&&ww(r,Xe(e,kw(s))),r}function yw(e,t,n,r,i,o){for(let s of n){if(!W(s))continue;let a=rr(e,s);if(a)for(let c of a){if(o&&!o.has(c.calleeLeaf))continue;let l=$o(s,r.get(c.calleeLeaf)??[]);if(!l||l.length===0)continue;let u=Mo(e,s,l,c.memberAccess);u&&i.has(u.symbolId)&&u.file!==s&&Va(t,u.symbolId,s)}}}function bw(e,t,n,r){let i=xw(n);for(let o of Sw(e,r))e.isIgnored(o.relative_path)||Cw(o,i.get(o.symbol_id))||Va(t,o.symbol_id,o.relative_path)}function Sw(e,t){return vr(e,t?[...t]:void 0)}function xw(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 Cw(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function vw(e,t,n,r,i,o){for(let s of n){if(W(s)!=="rust")continue;let a=dn(e,s,{includeRustAttributeNames:!0});if(a.length!==0)for(let{name:c}of a){if(o&&!o.has(c))continue;let l=r.get(c);if(l)for(let u of l)i.has(u.symbolId)&&u.file!==s&&Va(t,u.symbolId,s)}}}function Va(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function Rw(e){let t=new Set;for(let n of e){let r="leaf"in n&&typeof n.leaf=="string"?n.leaf:"symbol"in n&&typeof n.symbol=="string"?$(n.symbol):"";r&&t.add(r)}return t.size>0?t:null}function kw(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function ww(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 Qe(e,t,n={}){return Mm(e,t,n)}function qa(e,t,n={}){return Om(e,t,n)}function Ua(e,t){return Fm(e,t)}function jm(e,t,n={}){let r=qa(e,t,{semantic:n.semantic});return n.sourceFallback===!1?r:wr(r,Ua(e,t))}function wr(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 Bm(e,t,n){let r=t.identifierResolution==="strict"?kr:Tm,i=t.candidateNames?ii(t.candidateNames):null;for(let o of t.paths)if(!(!W(o)&&!(t.includeVueSfc&&Lt(o)))&&!e.isIgnored(o)&&!t.skipPath?.(o))try{if(i&&!Oo(T(e,o),i))continue;let a=(l,u,d,m)=>{if(t.candidateNames&&!t.candidateNames.has(l))return;let p=t.resolveTargets?t.resolveTargets({sourceFile:o,name:l,kind:u,defaultTargets:m}):m();for(let g of p)n({sourceFile:o,name:l,target:g,occurrences:d,kind:u})},c=Nt(e,o);for(let[l,u]of c)a(l,"identifier",u.length,()=>r(e,o,l));for(let l of dn(e,o,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let u=l.kind==="cross-language-dispatch"?()=>kr(e,o,l.name):()=>r(e,o,l.name);a(l.name,l.kind,l.occurrences,u)}}finally{t.afterPath?.(o)}}function U(e){return e.endLine-e.startLine+1}function Hm(e,t={}){let{scope:n,files:r,minLoc:i=1,maxLoc:o=Number.POSITIVE_INFINITY,excludeSymbol:s,excludeEntrySurfaces:a=!1,excludeTypesFiles:c=!1,excludeRootedSymbols:l=!1,requireFunctionLikeSymbol:u=!1,requireCallableSymbol:d=!1,excludeRustTraitImplMembers:m=!1,includeSuppressed:p=!1,sortByLocDesc:g=!1}=t,y=[],h=Lw(e,{scope:n,files:r,requireCallableSymbol:d}),x=new Map,v=new Map,R=S=>{let C=x.get(S);if(C!==void 0)return C;let P=Te(e,S);return x.set(S,P),P},L=S=>{let C=v.get(S);if(C!==void 0)return C;let P=J(S);return v.set(S,P),P};for(let S of h){let C=S.relativePath;if(e.isIgnored(C)||a&&R(C)||!Iw(S,{requireFunctionLikeSymbol:u,requireCallableSymbol:d})||s!==void 0&&S.symbol===s)continue;let P=U(S);P<i||P>o||c&&Dw(C)||l&&le(e,S.symbol,C)||m&&po(S.symbol)||L(C)!=="test"&&(cr(S.symbol)||!p&&to(e,C,S.startLine)||y.push(S))}return g?y.sort((S,C)=>U(C)-U(S)):y}function Lw(e,t){return t.files!==void 0?[...new Set(t.files.map(r=>r.replace(/\\/g,"/")))].sort().filter(r=>!t.scope||r.includes(t.scope)).flatMap(r=>G(e,r)):t.requireCallableSymbol?gd(e,{scope:t.scope,symbolMatches:ie,sqlPrefilter:"callable"}):gn(e,t.scope)}function Iw(e,t){return t.requireCallableSymbol?ie(e.symbol):t.requireFunctionLikeSymbol?oe(e.symbol):e.isFunctionLike}function Dw(e){return(e.split("/").pop()??"").includes("types")}var F=class{constructor(t){this.db=t}db;scopedDefinitions(t){return gn(this.db,t)}definitionsForFile(t){return G(this.db,t)}productionCallableDefinitions(t={}){return Hm(this.db,t)}calleeMap(t,n={}){return Wo(this.db,t,n)}crossFileCallerMap(t,n={}){return qa(this.db,t,n)}sourceFallbackCallerFiles(t){return Ua(this.db,t)}callerFileMap(t,n={}){return jm(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 O(this.db,{includeIgnored:!1}))if(W(i)==="rust")for(let{name:o}of dn(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 ce(this.db,t)}fileKind(t){return J(t)}hasSuppressionComment(t){return to(this.db,t.relativePath,t.startLine)}sourceFiles(){return Ne(this.db)}scanSourceReferences(t,n){Bm(this.db,t,n)}callableSignature(t){let n=me(this.db,t.relativePath)?.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};function Wa(e,t){let n=B(e,t);if(!n)return[];let r=$(n.symbol),o=new F(e).definitionsForFile(n.relativePath).filter(c=>ie(c.symbol)),s=o.filter(c=>c.parentTypeName===r||c.symbol.includes(r));return(s.length>0?s:Nw(Pw(n.relativePath))===r?o.filter(c=>c.symbol.includes("<invalid-global-code>")):[]).map(c=>({startLine:c.startLine,endLine:c.endLine,name:$(c.symbol)}))}function Nw(e){return e.replace(/\.[^.]+$/,"")}function Ga(e,t,n={}){let r=B(e,t);if(!r)return[];let o=!oe(r.symbol)&&!e.isIgnored(r.relativePath)?[{relativePath:r.relativePath,line:r.startLine}]:[],s=Yt(e,r,{semantic:n.semantic}).map(u=>({relativePath:u.file,line:u.line})),a=Ew(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 Ew(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=Tw(t.symbol);if(n.length===0)return[];let r=[];for(let i of O(e,{extensions:[".rb"],includeIgnored:!1})){let o=T(e,i);if(!o)continue;let s=o.split(`
255
- `);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 Tw(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 di(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=pn(i?.documentation??null),s=e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,signature:Fw(o,i?.display_name??null,r.symbol),source:_w(e,r.relativePath,r.startLine,r.endLine)}],a=Yt(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 _w(e,t,n,r){let i=T(e,t);if(!i)return null;let s=i.split(`
256
- `).slice(n,r+1).join(`
257
- `).trimEnd();return s.length>0?s:null}function Fw(e,t,n){let r=mn(e);if(r&&!Aw(r))return r;let i=(t??"").trim();return i?oe(n)&&!i.endsWith("()")?`${i}()`:i:b(n)}function Aw(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function mi(e,t){let n=Fe(e,t);return n?e.all(`SELECT DISTINCT d2.relative_path
275
+ WHERE gs.id IN (${p.map(()=>"?").join(",")})`,...p,...p)),a=Ac([...t.map(p=>p.documentId),...s.flatMap(p=>p.document_id===null?[]:[p.document_id])]),c=new Map(a.flatMap(p=>e.all(`SELECT id, relative_path FROM documents
276
+ WHERE id IN (${p.map(()=>"?").join(",")})`,...p).map(f=>[f.id,f.relative_path]))),l=new Map;for(let p of s)l.has(p.symbol_id)||l.set(p.symbol_id,{symbol:p.symbol,file:p.document_id!==null?c.get(p.document_id)??"":""});let d=new Map,u=c,m=vL(t);for(let[p,f]of m){let b=[...r.get(p)??[]].sort((C,y)=>C.start_line-y.start_line||C.end_line-y.end_line),x=[...f].sort((C,y)=>C.startLine-y.startLine||C.endLine-y.endLine),S=new Set,R=0;for(let C of x){for(;R<b.length&&b[R].start_line<=C.endLine;)S.add(b[R]),R+=1;for(let T of S)T.end_line<C.startLine&&S.delete(T);let y=new Set,w=[],L=null,k=()=>{if(L)return L;let T=u.get(C.documentId)??"",U=new Set;if(T){let Y=vp(e,T),ee=Math.max(0,C.startLine),we=Math.min(Y.length-1,C.endLine);for(let te=ee;te<=we;te+=1)for(let rn of Y[te])U.add(rn)}return L=U,U};for(let T of S){if(T.symbol_id===C.symbolId)continue;let U=l.get(T.symbol_id);if(!U)continue;if(!(T.start_line>=C.startLine&&T.end_line<=C.endLine)){if(!(T.start_line<=C.endLine&&T.end_line>=C.startLine))continue;let te=$(U.symbol);if(!te||!k().has(te))continue}let ee=`${U.symbol}|${T.chunk_id}`;y.has(ee)||(y.add(ee),w.push({...U,chunkId:T.chunk_id,source:"scip-chunk"}))}d.set(C.symbolId,w)}}return d}var ff=500;function Ac(e){let t=[...new Set(e)],n=[];for(let i=0;i<t.length;i+=ff)n.push(t.slice(i,i+ff));return n}function vL(e){let t=new Map;for(let n of e){let i=t.get(n.documentId);i?i.push(n):t.set(n.documentId,[n])}return t}function RL(e){let t=new Map;for(let[n,i]of e){let r=[];for(let o of i)r.push({symbol:o.symbol,file:o.file,chunkId:-1,source:"semantic-callee"});t.set(n,r)}return t}function hf(e,t,n={}){let i=new Map;if(t&&t.length===0)return i;let r=O(e,{includeIgnored:!1}),o=Hn(e),s=t??Lt(e),a=new Set(s.map(l=>l.symbolId)),c=EL(s);return kL(e,i,r,o,a,c),wL(e,i,s,a),DL(e,i,r,o,a,c),n.semantic!==!1&&FL(i,st(e,NL(s))),i}function kL(e,t,n,i,r,o){for(let s of n){if(!H(s))continue;let a=xi(e,s);if(a)for(let c of a){if(o&&!o.has(c.calleeLeaf))continue;let l=ds(s,i.get(c.calleeLeaf)??[]);if(!l||l.length===0)continue;let d=ms(e,s,l,c.memberAccess);d&&r.has(d.symbolId)&&d.file!==s&&Mc(t,d.symbolId,s)}}}function wL(e,t,n,i){let r=IL(n);for(let o of PL(e,i))e.isIgnored(o.relative_path)||LL(o,r.get(o.symbol_id))||Mc(t,o.symbol_id,o.relative_path)}function PL(e,t){return Mi(e,t?[...t]:void 0)}function IL(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 LL(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function DL(e,t,n,i,r,o){for(let s of n){if(H(s)!=="rust")continue;let a=Dn(e,s,{includeRustAttributeNames:!0});if(a.length!==0)for(let{name:c}of a){if(o&&!o.has(c))continue;let l=i.get(c);if(l)for(let d of l)r.has(d.symbolId)&&d.file!==s&&Mc(t,d.symbolId,s)}}}function Mc(e,t,n){let i=e.get(t);i||(i=new Set,e.set(t,i)),i.add(n)}function EL(e){let t=new Set;for(let n of e){let i="leaf"in n&&typeof n.leaf=="string"?n.leaf:"symbol"in n&&typeof n.symbol=="string"?$(n.symbol):"";i&&t.add(i)}return t.size>0?t:null}function NL(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function FL(e,t){for(let[n,i]of t){let r=e.get(n);r||(r=new Set,e.set(n,r));for(let o of i)r.add(o)}}function at(e,t,n={}){return gf(e,t,n)}function $c(e,t,n={}){return hf(e,t,n)}function jc(e,t,n={}){return lf(e,t,n)}function yf(e,t,n={}){let i=$c(e,t,{semantic:n.semantic});return n.sourceFallback===!1?i:qn(i,jc(e,t))}function qn(e,t){let n=new Map;for(let[i,r]of e)n.set(i,new Set(r));for(let[i,r]of t){let o=n.get(i)??new Set;for(let s of r)o.add(s);n.set(i,o)}return n}function bf(e,t,n){let i=t.identifierResolution==="strict"?ji:af,r=t.candidateNames?Rr(t.candidateNames):null,o=0,s=0,a=0,c=0,l="";for(let d of t.paths)if(o+=1,l=d,!(!H(d)&&!(t.includeVueSfc&&Ht(d)))&&!e.isIgnored(d)&&!t.skipPath?.(d))try{if(r&&!ps(M(e,d),r))continue;s+=1;let m=(f,g,b,x)=>{if(t.candidateNames&&!t.candidateNames.has(f))return;a+=1;let S=t.resolveTargets?t.resolveTargets({sourceFile:d,name:f,kind:g,defaultTargets:x}):x();for(let R of S)c+=1,n({sourceFile:d,name:f,target:R,occurrences:b,kind:g})},p=Kt(e,d);for(let[f,g]of p)m(f,"identifier",g.length,()=>i(e,d,f));for(let f of Dn(e,d,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let g=f.kind==="cross-language-dispatch"?()=>ji(e,d,f.name):()=>i(e,d,f.name);m(f.name,f.kind,f.occurrences,g)}}finally{t.afterPath?.(d),o%10===0&&D("source-reference-scan.progress",()=>{},()=>({scannedPaths:o,currentPath:l,candidateMatchedPaths:s,visitedNames:a,visitedHits:c}))}}function J(e){return e.endLine-e.startLine+1}function Sf(e,t={}){let{scope:n,files:i,minLoc:r=1,maxLoc:o=Number.POSITIVE_INFINITY,excludeSymbol:s,excludeEntrySurfaces:a=!1,excludeTypesFiles:c=!1,excludeRootedSymbols:l=!1,requireFunctionLikeSymbol:d=!1,requireCallableSymbol:u=!1,excludeRustTraitImplMembers:m=!1,includeSuppressed:p=!1,sortByLocDesc:f=!1}=t,g=[],b=TL(e,{scope:n,files:i,requireFunctionLikeSymbol:d,requireCallableSymbol:u}),x=new Map,S=new Map,R=y=>{let w=x.get(y);if(w!==void 0)return w;let L=Oe(e,y);return x.set(y,L),L},C=y=>{let w=S.get(y);if(w!==void 0)return w;let L=Z(y);return S.set(y,L),L};for(let y of b){let w=y.relativePath;if(e.isIgnored(w)||a&&R(w)||!_L(y,{requireFunctionLikeSymbol:d,requireCallableSymbol:u})||s!==void 0&&y.symbol===s)continue;let L=J(y);L<r||L>o||c&&AL(w)||l&&be(e,y.symbol,w)||m&&ts(y.symbol)||C(w)!=="test"&&(Ii(y.symbol)||!p&&Po(e,w,y.startLine)||g.push(y))}return f?g.sort((y,w)=>J(w)-J(y)):g}function TL(e,t){return t.files!==void 0?[...new Set(t.files.map(i=>i.replace(/\\/g,"/")))].sort().filter(i=>!t.scope||i.includes(t.scope)).flatMap(i=>Q(e,i)):t.requireCallableSymbol?Cr(e,{scope:t.scope,symbolMatches:he,sqlPrefilter:"callable"}):t.requireFunctionLikeSymbol?Cr(e,{scope:t.scope,symbolMatches:de,sqlPrefilter:"function-like"}):ep(e,t.scope)}function _L(e,t){return t.requireCallableSymbol?he(e.symbol):t.requireFunctionLikeSymbol?de(e.symbol):e.isFunctionLike}function AL(e){return(e.split("/").pop()??"").includes("types")}var A=class{constructor(t){this.db=t}db;scopedDefinitions(t){return hc(this.db,t)}definitionsForFile(t){return Q(this.db,t)}productionCallableDefinitions(t={}){return Sf(this.db,t)}calleeMap(t,n={}){return xs(this.db,t,n)}crossFileCallerMap(t,n={}){return $c(this.db,t,n)}sourceFallbackCallerFiles(t,n={}){return jc(this.db,t,n)}callerFileMap(t,n={}){return yf(this.db,t,n)}frameworkReferencedSymbolIds(t){let n=new Map;for(let r of t){if(!r.leaf)continue;let o=n.get(r.leaf)??[];o.push(r.symbolId),n.set(r.leaf,o)}let i=new Set;for(let r of O(this.db,{includeIgnored:!1}))if(H(r)==="rust")for(let{name:o}of Dn(this.db,r,{includeRustAttributeNames:!0}))for(let s of n.get(o)??[])i.add(s);return i}symbolsWithNonSelfCallees(t,n={}){if(t.length===0)return new Set;let i=new Map(t.map(o=>[o.symbolId,o.symbol])),r=this.calleeMap(t,n);return new Set([...r.entries()].filter(([o,s])=>{let a=i.get(o);return s.some(c=>c.symbol!==a)}).map(([o])=>o))}fileDependencyGraph(t){return ye(this.db,t)}fileKind(t){return Z(t)}hasSuppressionComment(t){return Po(this.db,t.relativePath,t.startLine)}sourceFiles(){return et(this.db)}scanSourceReferences(t,n){bf(this.db,t,n)}callableSignature(t){let n=gt(this.db).forFile(t.relativePath,{facts:!0}).facts?.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};function Oc(e,t){let n=q(e,t);if(!n)return[];let i=$(n.symbol),o=new A(e).definitionsForFile(n.relativePath).filter(l=>he(l.symbol)),s=o.filter(l=>l.parentTypeName===i||l.symbol.includes(i)),c=(s.length>0?s:$L(ML(n.relativePath))===i?o.filter(l=>l.symbol.includes("<invalid-global-code>")):[]).map(l=>({startLine:l.startLine,endLine:l.endLine,name:$(l.symbol)}));return H(n.relativePath)!=="clojure"?c:OL(c,jL(e,n))}function $L(e){return e.replace(/\.[^.]+$/,"")}function jL(e,t){let n=$(t.symbol);return n?(X(e,t.relativePath)?.clojureMembers??[]).filter(i=>i.ownerName===n).map(i=>({startLine:i.startLine,endLine:i.endLine,name:i.memberName})):[]}function OL(e,t){let n=new Map;for(let i of[...e,...t])n.set(`${i.name}:${i.startLine}:${i.endLine}`,i);return[...n.values()].sort((i,r)=>i.startLine-r.startLine||i.endLine-r.endLine)}function Bc(e,t,n={}){let i=q(e,t);if(!i)return[];let o=!de(i.symbol)&&!e.isIgnored(i.relativePath)?[{relativePath:i.relativePath,line:i.startLine}]:[],s=yn(e,i,{semantic:n.semantic}).map(d=>({relativePath:d.file,line:d.line})),a=BL(e,i),c=new Set,l=[];for(let d of[...o,...s,...a]){let u=`${d.relativePath}:${d.line}`;c.has(u)||(c.add(u),l.push(d))}return l}function BL(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=HL(t.symbol);if(n.length===0)return[];let i=[];for(let r of O(e,{extensions:[".rb"],includeIgnored:!1})){let o=M(e,r);if(!o)continue;let s=o.split(`
277
+ `);for(let a=0;a<s.length;a++){let c=s[a]??"";n.some(l=>new RegExp(`@${l}\\b|\\b${l}:`).test(c))&&i.push({relativePath:r,line:a})}}return i}function HL(e){let n=(e.split(":").pop()??e).replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),i=n.split("_").filter(Boolean),r=new Set;return n&&r.add(n),i.length>=1&&r.add(i[i.length-1]),i.length>=2&&r.add(i.slice(-2).join("_")),[...r]}function Tr(e,t,n={}){let i=q(e,t);if(!i)return{definitions:[],referencedBy:[]};let r=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",i.symbolId),o=$n(r?.documentation??null),s=e.isIgnored(i.relativePath)?[]:[{relativePath:i.relativePath,startLine:i.startLine,endLine:i.endLine,signature:qL(o,r?.display_name??null,i.symbol),source:VL(e,i.relativePath,i.startLine,i.endLine)}],a=yn(e,i,{semantic:n.semantic}).map(c=>({relativePath:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol,enclosingShort:c.enclosingSymbol?v(c.enclosingSymbol):"(top-level)"}));return{definitions:s,referencedBy:a}}function VL(e,t,n,i){let r=M(e,t);if(!r)return null;let s=r.split(`
278
+ `).slice(n,i+1).join(`
279
+ `).trimEnd();return s.length>0?s:null}function qL(e,t,n){let i=Mn(e);if(i&&!UL(i))return i;let r=(t??"").trim();return r?de(n)&&!r.endsWith("()")?`${r}()`:r:v(n)}function UL(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function _r(e,t){let n=Ve(e,t);return n?e.all(`SELECT DISTINCT d2.relative_path
258
280
  FROM mentions m
259
281
  JOIN chunks c ON m.chunk_id = c.id
260
282
  JOIN documents d1 ON c.document_id = d1.id
@@ -270,7 +292,7 @@ ${m}`,l+=1+m.length,u+=ei(m),r+=m.length+1}let d=uR(c);d&&n.push({...d,start:a,e
270
292
  WHERE d1.relative_path = ?
271
293
  AND d2.relative_path <> d1.relative_path
272
294
  AND ${e.localSymbolPredicate}
273
- ORDER BY d2.relative_path`,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function pi(e,t){let n=Fe(e,t);return n?e.all(`SELECT DISTINCT d1.relative_path
295
+ ORDER BY d2.relative_path`,n).filter(r=>!e.isIgnored(r.relative_path)).map(r=>({relativePath:r.relative_path})):[]}function Ar(e,t){let n=Ve(e,t);return n?e.all(`SELECT DISTINCT d1.relative_path
274
296
  FROM mentions m
275
297
  JOIN chunks c ON m.chunk_id = c.id
276
298
  JOIN documents d1 ON c.document_id = d1.id
@@ -285,9 +307,9 @@ ${m}`,l+=1+m.length,u+=ei(m),r+=m.length+1}let d=uR(c);d&&n.push({...d,start:a,e
285
307
  JOIN documents d2 ON sym_def.document_id = d2.id
286
308
  WHERE d2.relative_path = ?
287
309
  AND d1.relative_path != ?
288
- ORDER BY d1.relative_path`,n,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function fi(e,t){let n=pr(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let r=n.map(()=>"?").join(", "),o=e.all(`SELECT relative_path FROM documents
289
- WHERE relative_path IN (${r})
290
- ORDER BY relative_path`,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d)),s=fo(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:d,...m})=>m),c=e.all(`SELECT DISTINCT d2.relative_path
310
+ ORDER BY d1.relative_path`,n,n).filter(r=>!e.isIgnored(r.relative_path)).map(r=>({relativePath:r.relative_path})):[]}function Mr(e,t){let n=Fi(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let i=n.map(()=>"?").join(", "),o=e.all(`SELECT relative_path FROM documents
311
+ WHERE relative_path IN (${i})
312
+ ORDER BY relative_path`,...n).map(u=>u.relative_path).filter(u=>!e.isIgnored(u)),s=ns(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:u,...m})=>m),c=e.all(`SELECT DISTINCT d2.relative_path
291
313
  FROM mentions m
292
314
  JOIN chunks c ON m.chunk_id = c.id
293
315
  JOIN documents d1 ON c.document_id = d1.id
@@ -300,10 +322,10 @@ ${m}`,l+=1+m.length,u+=ei(m),r+=m.length+1}let d=uR(c);d&&n.push({...d,start:a,e
300
322
  GROUP BY m2.symbol_id
301
323
  ) sym_def ON sym_def.symbol_id = gs.id
302
324
  JOIN documents d2 ON sym_def.document_id = d2.id
303
- WHERE d1.relative_path IN (${r})
304
- AND d2.relative_path NOT IN (${r})
325
+ WHERE d1.relative_path IN (${i})
326
+ AND d2.relative_path NOT IN (${i})
305
327
  AND ${e.localSymbolPredicate}
306
- 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
328
+ ORDER BY d2.relative_path`,...n,...n).map(u=>u.relative_path).filter(u=>!e.isIgnored(u)),d=e.all(`SELECT DISTINCT d1.relative_path
307
329
  FROM mentions m
308
330
  JOIN chunks c ON m.chunk_id = c.id
309
331
  JOIN documents d1 ON c.document_id = d1.id
@@ -316,9 +338,9 @@ ${m}`,l+=1+m.length,u+=ei(m),r+=m.length+1}let d=uR(c);d&&n.push({...d,start:a,e
316
338
  GROUP BY m2.symbol_id
317
339
  ) sym_def ON sym_def.symbol_id = gs.id
318
340
  JOIN documents d2 ON sym_def.document_id = d2.id
319
- WHERE d2.relative_path IN (${r})
320
- AND d1.relative_path NOT IN (${r})
321
- 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 gi(e,t){let n=pr(e,t);return n.length===0?[]:Ow([...$w(e,n),...Mw(e,n)]).filter(r=>!e.isIgnored(r.relative_path)).map(jw)}function $w(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
341
+ WHERE d2.relative_path IN (${i})
342
+ AND d1.relative_path NOT IN (${i})
343
+ ORDER BY d1.relative_path`,...n,...n).map(u=>u.relative_path).filter(u=>!e.isIgnored(u));return{files:o,symbols:s,dependsOn:c,dependedOnBy:d}}function $r(e,t){let n=Fi(e,t);return n.length===0?[]:GL([...zL(e,n),...WL(e,n)]).filter(i=>!e.isIgnored(i.relative_path)).map(KL)}function zL(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
322
344
  FROM mentions m
323
345
  JOIN chunks c ON m.chunk_id = c.id
324
346
  JOIN documents d1 ON c.document_id = d1.id
@@ -345,7 +367,7 @@ ${m}`,l+=1+m.length,u+=ei(m),r+=m.length+1}let d=uR(c);d&&n.push({...d,start:a,e
345
367
  AND m.role != 1
346
368
  AND ${e.localSymbolPredicate}
347
369
  ${e.pathExclusionsFor("d1")}
348
- ORDER BY d1.relative_path`,...t,...t,...t)}function Mw(e,t){let n=new F(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>ie(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function Ow(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 jw(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:b(e.symbol)}}var hi=new WeakMap;function qm(e,t){let n=W(t);if(!(n==="rust"||n==="typescript"||n==="tsx"||n==="javascript"))return[];let i=T(e,t);if(!i)return[];let o=X(e,t,i),s=te(e,"definition-exclusions",t,o);if(s){let c=Bw(s);if(c)return c}let a=n==="rust"?Jw(e,t):Uw(e,t);return ne(e,"definition-exclusions",t,o,JSON.stringify(a)),a}function Bw(e){try{let t=JSON.parse(e);return!Array.isArray(t)||!t.every(Hw)?null:t}catch{return null}}function Hw(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.startLine!="number"||!Number.isFinite(t.startLine)||typeof t.endLine!="number"||!Number.isFinite(t.endLine)||typeof t.reason!="string"?!1:t.containerName===void 0||typeof t.containerName=="string"}var Um=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]),Vw=/\b(?:describe|it|test|fdescribe|fit|xdescribe|xit|beforeEach|afterEach|beforeAll|afterAll|before|after|suite|bench|benchmark)\s*\(/,qw=/\b(?:export\s+)?(?:async\s+)?function\s+use[A-Z][A-Za-z0-9_$]*\b|\b(?:const|let|var)\s+use[A-Z][A-Za-z0-9_$]*\s*(?::[^=;]+)?=\s*(?:async\s*)?(?:function\b|(?:<[^=;{]+>\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>)/;function Uw(e,t){let n=T(e,t);if(!n||!Ww(n))return[];let r=be(e,t);if(!r)return[];let i=hi.get(r);if(i)return i;let o=!1,s=r.rootNode;for(let c of s.namedChildren){if(c.type!=="expression_statement")continue;let l=c.namedChild(0);if(!l||l.type!=="call_expression")continue;let u=l.namedChild(0);if(!u)continue;let d=u.type==="member_expression"?u.namedChild(u.namedChildCount-1)?.text:u.text;if(d&&Um.has(d)){o=!0;break}}let a=[];o&&a.push({startLine:0,endLine:s.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)"});for(let c of s.namedChildren){let l=null,u=null;if(c.type==="function_declaration")l=c.namedChild(0)?.text??null,u=c;else if(c.type==="export_statement"){let d=c.namedChild(0);d?.type==="function_declaration"&&(l=d.namedChild(0)?.text??null,u=d)}else if(c.type==="lexical_declaration"){let d=c.namedChild(0);if(d?.type==="variable_declarator"){let m=d.namedChild(0)?.text,p=d.namedChild(1);m&&(p?.type==="arrow_function"||p?.type==="function_expression")&&(l=m,u=d)}}l&&/^use[A-Z]/.test(l)&&u&&a.push({startLine:u.startPosition.row,endLine:u.endPosition.row,reason:"React custom hook (use*)"})}return a.push(...Wm(r,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),hi.set(r,a),a}function Ww(e){if(e.includes("scip-query"))return!0;let t=!1;for(let n of Um)if(e.includes(n)){t=!0;break}return t&&Vw.test(e)?!0:e.includes("use")&&qw.test(e)}var Gw=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function zw(e){return Gw.test(e)}function Wm(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(zw(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 Jw(e,t){let n=be(e,t);if(!n)return[];let r=hi.get(n);if(r)return r;let i=[],o=Kw(n);return o?(hi.set(n,o),o):(Gm(n.rootNode,i,!1,!1),i.push(...Wm(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(...rL(n.rootNode)),hi.set(n,i),i)}function Kw(e){return iL(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)"}]:null}function Gm(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"?Xw(e,t,n,r):r&&nL(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"?Qw(e,t,n):e.type==="mod_item"&&za(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(i=!0);for(let s of e.namedChildren)Gm(s,t,i,o)}function Xw(e,t,n,r){let i=za(e),o=null;r?o="trait impl method (dynamic dispatch)":n&&(o="inside #[cfg(test)] mod");for(let s of i){let a=Zw(s);if(a){o=a;break}if(zm(s)){o="#[allow(dead_code)]";break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o})}function Qw(e,t,n){let r=za(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(tL)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(<reflective>)] \u2014 fields accessed via macro/reflection",containerName:i}),r.some(zm)&&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 za(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 Yw=[{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 Zw(e){return Yw.find(({re:t})=>t.test(e))?.reason??null}var eL=[/\bSerialize\b/,/\bDeserialize\b/,/\bFromRow\b/,/\bsqlx::FromRow\b/,/\bDeriveEntityModel\b/,/\bIntoSchema\b/,/\bToSchema\b/,/\bDeriveValueType\b/,/\bError\b/,/\bthiserror::Error\b/];function tL(e){return/#\[\s*derive\s*\(/.test(e)?eL.some(t=>t.test(e)):!1}function zm(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function nL(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function rL(e){let t=sL(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 iL(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 oL=/^#!?\[\s*serde\s*\(/,Vm=/\bwith\s*=\s*"([^"]+)"/g;function sL(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){if(!oL.test(n.text))continue;Vm.lastIndex=0;let r;for(;(r=Vm.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}function Jm(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=qm(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 ho(o))if(a.containers.has(c))return!0;return!1}}function Ja(e,t={}){oa(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function Km(e,t,n={}){oa(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function Qm(e,t){return t.isIgnoredPath(e.relativePath)?ht("ignored-file"):Vt(e.symbol)?ht("module-like-symbol"):Xm(e.symbol)?!e.isFunctionLike&&e.enclosingSymbol&&Xm(e.enclosingSymbol)?ht("nested-non-callable-value"):!t.includeTests&&!Ka(e.relativePath)?ht("test-file"):!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName)?ht("excluded-file-region"):po(e.symbol)?ht("rust-trait-impl-member"):cr(e.symbol)?ht("rust-test-module"):!t.includeMembers&&!aL(e)?ht("member"):e.endLine-e.startLine+1<t.minLoc?ht("below-min-loc"):{accepted:!0}:ht("non-value-symbol")}function Ka(e){return J(e)!=="test"}function ht(e){return{accepted:!1,rejectionReason:e}}function Xm(e){return oe(e)||e.endsWith("().")||e.endsWith(".")}function aL(e){return ie(e.symbol)||ho(e.symbol).length===0}function Go(e,t){return U(e)-U(t)||e.relativePath.localeCompare(t.relativePath)}function Ve(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function Lr(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 Ym(){return new Map}function Zm(e,t,n){let r=new Map;for(let i of rm(e,n))e.isIgnored(i.relative_path)||t.has(i.relative_path)||zo(r,i.symbol_id,i.relative_path,i.ref_count,"scip-mention");return r}function ep(e,t,n){let r=new Set;for(let i of im(e,t))e.isIgnored(i.relative_path)||n.has(i.relative_path)||r.add(i.symbol_id);return r}function Xa(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 Qa(e,t,n){let r=e.get(t);if(!r)return!1;for(let[i,o]of r)if(i!==n&&o.occurrences>0)return!0;return!1}function tp(e){return e?.occurrences??0}function zo(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=rp(e,t,n);o.occurrences+=r,o.sources.add(i)}function np(e,t,n,r,i){if(r<=0)return;let o=rp(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function rp(e,t,n){let r=e.get(t);r||(r=new Map,e.set(t,r));let i=r.get(n);return i||(i={occurrences:0,sources:new Set},r.set(n,i)),i}var cL=3e3,lL=1e3;function Et(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=Ve(uL(e,{scope:n,minLoc:r,includeTests:i,includeMembers:s}),c),d=o?new Set(Zd(e)):new Set,m=a?Ym():Zm(e,d,u.map(x=>x.symbolId)),p=a?ep(e,u.map(x=>x.symbolId),d):new Set,g=a?u.filter(x=>!p.has(x.symbolId)):u.filter(x=>!Qa(m,x.symbolId,x.relativePath));a?gL(e,g,m,d):fL(e,g,m,d);let y=a?g.filter(x=>!Xa(m,x.symbolId)):g.filter(x=>!Qa(m,x.symbolId,x.relativePath));xL(e,y,m,{includeTests:i,inactiveBarrelPaths:d,includeSemantic:!a&&l});let h=a?g.filter(x=>!Xa(m,x.symbolId)):u;return pL(e,dL(h,m))}function uL(e,t){let n=Jm(e),r=[];for(let i of gn(e,t.scope))Qm(i,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:s=>e.isIgnored(s),isExcludedRegion:n}).accepted&&r.push(i);return r}function dL(e,t){return e.map(n=>mL(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 mL(e,t){let n=t.get(e.symbolId)??new Map,r=tp(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 pL(e,t){let n=[],r=0,i=0,o=0;for(let s of t){if(e.isIgnored(s.relative_path)||Te(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:b(s.symbol),sameFileRefs:s.same_file_refs,kind:a})}return{symbols:n,counts:{total:n.length,deadCode:r,fileInternal:i,loc:o},totalCount:n.length,deadCodeCount:r,fileInternalCount:i,totalLoc:o}}function fL(e,t,n,r){if(t.length===0)return;let i=new F(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 O(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)&&(bL(e,c)||zo(n,c.target.symbolId,c.sourceFile,SL(c),"source-fallback"))})}function gL(e,t,n,r){if(t.length===0)return;let i=new F(e),o=hL(t),s=new Set(i.sourceFiles());for(let u of O(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let d=c.get(u);return d||(d=Uo(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 p=o.get(d);return p?yL(u,d,p,l(u),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),Km(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&ip(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||zo(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function hL(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 yL(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=>Jt(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=>Jt(c,u.relativePath));if(l.length>0&&l.length===n.length)return l}return i.permissive?[...n]:[]}function bL(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&ip(e,t)}function SL(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function ip(e,t){return t.occurrences>1?!1:xe(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function xL(e,t,n,r){let i=r.includeSemantic!==!1,o=i&&t.length>=cL&&O(e).length>=lL,s=(c,l)=>{l===c.relativePath||e.isIgnored(l)||r.inactiveBarrelPaths.has(l)||!r.includeTests&&!Ka(l)||np(n,c.symbolId,l,1,"caller-map")};if(o)CL(e,t,s);else for(let c of t){let l=Qe(e,c,{semantic:i});if(l.length!==0)for(let u of l)s(c,u.file)}if(!o)return;let a=Xe(e,t);for(let c of t){let l=a.get(c.symbolId);if(l)for(let u of l)s(c,u)}}function CL(e,t,n){let r=new Map(t.map(i=>[i.symbolId,i]));for(let i of vr(e,[...r.keys()])){let o=r.get(i.symbol_id);o&&n(o,i.relative_path)}}function Ya(e,t={}){let{limit:n=30,scope:r}=t,i=r?`AND def_d.relative_path LIKE '%${r}%'`:"",s=e.all(`SELECT
370
+ ORDER BY d1.relative_path`,...t,...t,...t)}function WL(e,t){let n=new A(e);return t.flatMap(i=>n.definitionsForFile(i).filter(r=>he(r.symbol)).map(r=>({relative_path:i,symbol:r.symbol})))}function GL(e){let t=new Set;return e.filter(n=>{let i=`${n.relative_path}|${n.symbol}`;return t.has(i)?!1:(t.add(i),!0)})}function KL(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:v(e.symbol)}}var jr=new WeakMap,xf=pe({kind:"definition-exclusions",serialize:e=>JSON.stringify(e),deserialize:JL});function vf(e,t){let n=H(t);if(!(n==="rust"||n==="typescript"||n==="tsx"||n==="javascript"))return[];let r=M(e,t);if(!r)return[];let o=re(e,t,r),s=xf.read(e,t,o);if(s)return s;let a=n==="rust"?iD(e,t):ZL(e,t);return xf.write(e,t,o,a),a}function JL(e){try{let t=JSON.parse(e);return!Array.isArray(t)||!t.every(XL)?null:t}catch{return null}}function XL(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.startLine!="number"||!Number.isFinite(t.startLine)||typeof t.endLine!="number"||!Number.isFinite(t.endLine)||typeof t.reason!="string"?!1:t.containerName===void 0||typeof t.containerName=="string"}var Rf=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]),QL=/\b(?:describe|it|test|fdescribe|fit|xdescribe|xit|beforeEach|afterEach|beforeAll|afterAll|before|after|suite|bench|benchmark)\s*\(/,YL=/\b(?:export\s+)?(?:async\s+)?function\s+use[A-Z][A-Za-z0-9_$]*\b|\b(?:const|let|var)\s+use[A-Z][A-Za-z0-9_$]*\s*(?::[^=;]+)?=\s*(?:async\s*)?(?:function\b|(?:<[^=;{]+>\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>)/;function ZL(e,t){let n=M(e,t);if(!n||!eD(n))return[];let i=Pe(e,t);if(!i)return[];let r=jr.get(i);if(r)return r;let o=!1,s=i.rootNode;for(let c of s.namedChildren){if(c.type!=="expression_statement")continue;let l=c.namedChild(0);if(!l||l.type!=="call_expression")continue;let d=l.namedChild(0);if(!d)continue;let u=d.type==="member_expression"?d.namedChild(d.namedChildCount-1)?.text:d.text;if(u&&Rf.has(u)){o=!0;break}}let a=[];o&&a.push({startLine:0,endLine:s.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)"});for(let c of s.namedChildren){let l=null,d=null;if(c.type==="function_declaration")l=c.namedChild(0)?.text??null,d=c;else if(c.type==="export_statement"){let u=c.namedChild(0);u?.type==="function_declaration"&&(l=u.namedChild(0)?.text??null,d=u)}else if(c.type==="lexical_declaration"){let u=c.namedChild(0);if(u?.type==="variable_declarator"){let m=u.namedChild(0)?.text,p=u.namedChild(1);m&&(p?.type==="arrow_function"||p?.type==="function_expression")&&(l=m,d=u)}}l&&/^use[A-Z]/.test(l)&&d&&a.push({startLine:d.startPosition.row,endLine:d.endPosition.row,reason:"React custom hook (use*)"})}return a.push(...kf(i,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),jr.set(i,a),a}function eD(e){if(e.includes("scip-query"))return!0;let t=!1;for(let n of Rf)if(e.includes(n)){t=!0;break}return t&&QL.test(e)?!0:e.includes("use")&&YL.test(e)}var tD=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function nD(e){return tD.test(e)}function kf(e,t,n){let i=[],r=o=>{if(t.has(o.type)&&o.parent){let a=o.parent.children,c=-1;for(let l=0;l<a.length;l+=1)if(a[l].startIndex===o.startIndex&&a[l].type===o.type){c=l;break}if(c>0)for(let l=c-1;l>=0;l-=1){let d=a[l];if(n.has(d.type)){if(nD(d.text)){i.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"scip-query suppression comment"});break}continue}if(!(d.type==="attribute_item"||d.type==="inner_attribute_item"))break}}for(let s of o.namedChildren)r(s)};return r(e.rootNode),i}function iD(e,t){let n=Pe(e,t);if(!n)return[];let i=jr.get(n);if(i)return i;let r=[],o=rD(n);return o?(jr.set(n,o),o):(wf(n.rootNode,r,!1,!1),r.push(...kf(n,new Set(["function_item","function_signature_item","struct_item","enum_item","union_item","impl_item","mod_item","static_item","const_item"]),new Set(["line_comment","block_comment"]))),r.push(...mD(n.rootNode)),jr.set(n,r),r)}function rD(e){return pD(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)"}]:null}function wf(e,t,n,i){let r=n,o=i;e.type==="trait_item"&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait declaration body (dynamic dispatch)"}),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"?oD(e,t,n,i):i&&dD(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"?sD(e,t,n):e.type==="mod_item"&&Hc(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(r=!0);for(let s of e.namedChildren)wf(s,t,r,o)}function oD(e,t,n,i){let r=Hc(e),o=null;i?o="trait impl method (dynamic dispatch)":n&&(o="inside #[cfg(test)] mod");for(let s of r){let a=cD(s);if(a){o=a;break}if(Pf(s)){o="#[allow(dead_code)]";break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o})}function sD(e,t,n){let i=Hc(e),r=e.namedChildren.find(o=>o.type==="type_identifier")?.text;i.some(uD)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(<reflective>)] \u2014 fields accessed via macro/reflection",containerName:r}),i.some(Pf)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",containerName:r}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",containerName:r})}function Hc(e){let t=e.parent;if(!t)return[];let n=t.children,i=-1;for(let o=0;o<n.length;o+=1)if(n[o].startIndex===e.startIndex&&n[o].type===e.type){i=o;break}if(i<=0)return[];let r=[];for(let o=i-1;o>=0;o-=1){let s=n[o];if(s.type==="attribute_item"||s.type==="inner_attribute_item")r.push(s.text);else{if(s.type==="line_comment"||s.type==="block_comment")continue;break}}return r}var aD=[{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 cD(e){return aD.find(({re:t})=>t.test(e))?.reason??null}var lD=[/\bSerialize\b/,/\bDeserialize\b/,/\bFromRow\b/,/\bsqlx::FromRow\b/,/\bDeriveEntityModel\b/,/\bIntoSchema\b/,/\bToSchema\b/,/\bDeriveValueType\b/,/\bError\b/,/\bthiserror::Error\b/];function uD(e){return/#\[\s*derive\s*\(/.test(e)?lD.some(t=>t.test(e)):!1}function Pf(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function dD(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function mD(e){let t=gD(e);if(t.size===0)return[];let n=[];for(let i of e.descendantsOfType("mod_item")){let r=i.childForFieldName("name")?.text;r&&t.has(r)&&n.push({startLine:i.startPosition.row,endLine:i.endPosition.row,reason:'serde `with = "..."` module \u2014 body invoked via reflection',containerName:r})}return n}function pD(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 fD=/^#!?\[\s*serde\s*\(/,Cf=/\bwith\s*=\s*"([^"]+)"/g;function gD(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){if(!fD.test(n.text))continue;Cf.lastIndex=0;let i;for(;(i=Cf.exec(n.text))!==null;){let r=i[1],o=r.split("::").pop()??r;o&&t.add(o)}}return t}function If(e){let t=new Map,n=i=>{let r=t.get(i);if(r)return r;let o=vf(e,i);return r={ranges:o.map(s=>({startLine:s.startLine,endLine:s.endLine})),containers:new Set(o.map(s=>s.containerName).filter(s=>!!s))},t.set(i,r),r};return(i,r,o,s)=>{let a=n(i);for(let c of a.ranges)if(r>=c.startLine&&r<=c.endLine)return!0;if(s&&a.containers.has(s))return!0;for(let c of rs(o))if(a.containers.has(c))return!0;return!1}}function Vc(e,t={}){$a(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function Lf(e,t,n={}){$a(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function Df(e,t){return t.isIgnoredPath(e.relativePath)?Et("ignored-file"):gn(e.symbol)?Et("module-like-symbol"):Cs(e.symbol)?!e.isFunctionLike&&e.enclosingSymbol&&Cs(e.enclosingSymbol)?Et("nested-non-callable-value"):!t.includeTests&&!Or(e.relativePath)?Et("test-file"):!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName)?Et("excluded-file-region"):ts(e.symbol)?Et("rust-trait-impl-member"):Ii(e.symbol)?Et("rust-test-module"):!t.includeMembers&&!hD(e)?Et("member"):e.endLine-e.startLine+1<t.minLoc?Et("below-min-loc"):{accepted:!0}:Et("non-value-symbol")}function Or(e){return Z(e)!=="test"}function Et(e){return{accepted:!1,rejectionReason:e}}function Cs(e){return de(e)||e.endsWith("().")||e.endsWith(".")}function hD(e){return he(e.symbol)||rs(e.symbol).length===0}function vs(e,t){return J(e)-J(t)||e.relativePath.localeCompare(t.relativePath)}function qe(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function Oi(e){let t=new Set,n=[];for(let i of e){let r=`${i.symbol}|${i.file}`;t.has(r)||(t.add(r),n.push(i))}return n}function Ef(){return new Map}function Nf(e,t,n){let i=new Map;for(let r of Rp(e,n))e.isIgnored(r.relative_path)||t.has(r.relative_path)||ks(i,r.symbol_id,r.relative_path,r.ref_count,"scip-mention");return i}function Ff(e,t,n,i={}){let r=new Set;if(i.conservative||n.size===0){for(let o of wp(e,t))r.add(o.symbol_id);return r}for(let o of kp(e,t))e.isIgnored(o.relative_path)||n.has(o.relative_path)||r.add(o.symbol_id);return r}function qc(e,t){let n=e.get(t);if(!n)return!1;for(let i of n.values())if(i.occurrences>0)return!0;return!1}function Rs(e,t,n){let i=e.get(t);if(!i)return!1;for(let[r,o]of i)if(r!==n&&o.occurrences>0)return!0;return!1}function Tf(e){return e?.occurrences??0}function ks(e,t,n,i,r="source-fallback"){if(i<=0)return;let o=Af(e,t,n);o.occurrences+=i,o.sources.add(r)}function _f(e,t,n,i,r){if(i<=0)return;let o=Af(e,t,n);o.occurrences=Math.max(i,o.occurrences),o.sources.add(r)}function Af(e,t,n){let i=e.get(t);i||(i=new Map,e.set(t,i));let r=i.get(n);return r||(r={occurrences:0,sources:new Set},i.set(n,r)),r}var yD=3e3,bD=1e3;function Qt(e,t={}){let{scope:n,minLoc:i=1,includeTests:r=!1,skipBarrels:o=!1,includeMembers:s=!1,deadCodeOnly:a=!1,scanLimit:c,semantic:l=!0}=t,d=0,u=D("dead.candidates",()=>{let y=qe(SD(e,{scope:n,minLoc:i,includeTests:r,includeMembers:s}),c);return d=y.length,y},()=>({definitions:d})),m=0,p=o?D("dead.inactive-barrels",()=>{let y=new Set(Sp(e));return m=y.size,y},()=>({paths:m})):new Set,f=0,g=a?Ef():D("dead.mention-reference-counts",()=>{let y=Nf(e,p,u.map(w=>w.symbolId));return f=y.size,y},()=>({definitions:u.length,symbolsWithReferences:f})),b=0,x=a?D("dead.mentioned-symbol-ids",()=>{let y=Ff(e,u.map(w=>w.symbolId),p,{conservative:p.size===0});return b=y.size,y},()=>({definitions:u.length,referencedSymbols:b})):new Set,S=a?u.filter(y=>!x.has(y.symbolId)):u.filter(y=>!Rs(g,y.symbolId,y.relativePath));a?D("dead.source-fallback.dead-code-only",()=>kD(e,S,g,{includeTests:r,inactiveBarrelPaths:p}),()=>({definitions:S.length,includeTests:r})):D("dead.source-fallback.ast",()=>RD(e,S,g,{includeTests:r,inactiveBarrelPaths:p}),()=>({definitions:S.length,includeTests:r}));let R=a?S.filter(y=>!qc(g,y.symbolId)):S.filter(y=>!Rs(g,y.symbolId,y.relativePath));D("dead.caller-map-supplement",()=>DD(e,R,g,{includeTests:r,inactiveBarrelPaths:p,includeSemantic:!a&&l}),()=>({definitions:R.length,semantic:!a&&l}));let C=a?S.filter(y=>!qc(g,y.symbolId)):u;return vD(e,xD(C,g))}function SD(e,t){let n=If(e),i=[];for(let r of Cr(e,{scope:t.scope,symbolMatches:Cs,sqlPrefilter:"function-like"}))Df(r,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:s=>e.isIgnored(s),isExcludedRegion:n}).accepted&&i.push(r);return i}function xD(e,t){return e.map(n=>CD(n,t)).filter(n=>n.cross_file_refs===0).sort((n,i)=>i.loc-n.loc||n.relative_path.localeCompare(i.relative_path)||n.start_line-i.start_line)}function CD(e,t){let n=t.get(e.symbolId)??new Map,i=Tf(n.get(e.relativePath)),r=0;for(let[o,s]of n)o!==e.relativePath&&(r+=s.occurrences);return{relative_path:e.relativePath,start_line:e.startLine,end_line:e.endLine,loc:e.endLine-e.startLine+1,symbol:e.symbol,same_file_refs:i,cross_file_refs:r}}function vD(e,t){let n=[],i=0,r=0,o=0;for(let s of t){if(e.isIgnored(s.relative_path)||Oe(e,s.relative_path)||be(e,s.symbol,s.relative_path))continue;let a=s.same_file_refs===0?"dead-code":"file-internal";a==="dead-code"?i++:r++,o+=s.loc,n.push({relativePath:s.relative_path,startLine:s.start_line,endLine:s.end_line,loc:s.loc,symbol:s.symbol,shortName:v(s.symbol),sameFileRefs:s.same_file_refs,kind:a})}return{symbols:n,counts:{total:n.length,deadCode:i,fileInternal:r,loc:o},totalCount:n.length,deadCodeCount:i,fileInternalCount:r,totalLoc:o}}function RD(e,t,n,i){if(t.length===0)return;let r=new A(e),o=new Set(t.map(c=>c.symbolId)),s=new Set(t.map(c=>c.leaf).filter(Boolean)),a=new Set(r.sourceFiles());for(let c of O(e))a.add(c);r.scanSourceReferences({paths:a,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:s,skipPath:c=>i.inactiveBarrelPaths.has(c)||!i.includeTests&&!Or(c)},c=>{o.has(c.target.symbolId)&&(ID(e,c)||ks(n,c.target.symbolId,c.sourceFile,LD(c),"source-fallback"))})}function kD(e,t,n,i){if(t.length===0)return;let r=new A(e),o=wD(t),s=new Set(r.sourceFiles());for(let d of O(e))s.add(d);let a=new Set(o.keys()),c=new Map,l=d=>{let u=c.get(d);return u||(u=bs(e,d),c.set(d,u)),u};r.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:d=>i.inactiveBarrelPaths.has(d)||!i.includeTests&&!Or(d),resolveTargets:({sourceFile:d,name:u,kind:m})=>{let p=o.get(u);return p?PD(d,u,p,()=>l(d),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:d=>{c.delete(d),Lf(e,d)}},d=>{let u=d.kind==="identifier"&&d.sourceFile===d.target.relativePath?Math.max(0,d.occurrences-1):d.occurrences;d.kind==="identifier"&&Mf(e,{sourceFile:d.sourceFile,name:d.name,target:d.target,occurrences:u})||ks(n,d.target.symbolId,d.sourceFile,u,"source-fallback")})}function wD(e){let t=new Map;for(let n of e){if(!n.leaf)continue;let i=t.get(n.leaf)??[];i.push(n),t.set(n.leaf,i)}return t}function PD(e,t,n,i,r){let o=n.filter(l=>l.relativePath===e);if(o.length>0)return o;if(!r.permissive&&n.length===1)return[...n];let s=i(),a=s.get(t);if(a)for(let l of a){let d=n.filter(u=>Dt(l,u.relativePath));if(d.length>0)return d}let c=new Set;for(let l of s.values())for(let d of l)c.add(d);for(let l of c){let d=n.filter(u=>Dt(l,u.relativePath));if(d.length>0&&d.length===n.length)return d}return r.permissive?[...n]:[]}function ID(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&Mf(e,t)}function LD(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function Mf(e,t){return t.occurrences>1?!1:oe(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function DD(e,t,n,i){let r=i.includeSemantic!==!1,o=r&&t.length>=yD&&O(e).length>=bD,s=(d,u)=>{u===d.relativePath||e.isIgnored(u)||i.inactiveBarrelPaths.has(u)||!i.includeTests&&!Or(u)||_f(n,d.symbolId,u,1,"caller-map")};if(o?D("dead.caller-map.mention-chunks",()=>ED(e,t,s),()=>({definitions:t.length})):D("dead.caller-map.per-symbol",()=>{for(let d of t){let u=at(e,d,{semantic:r});if(u.length!==0)for(let m of u)s(d,m.file)}},()=>({definitions:t.length,semantic:r})),!o)return;let a=0,c=D("dead.caller-map.semantic-candidates",()=>{let d=t.filter(u=>!Rs(n,u.symbolId,u.relativePath));return a=d.length,d},()=>({definitions:t.length,semanticCandidates:a}));if(c.length===0)return;let l=st(e,c);for(let d of c){let u=l.get(d.symbolId);if(u)for(let m of u)s(d,m)}}function ED(e,t,n){let i=new Map(t.map(r=>[r.symbolId,r]));for(let r of Mi(e,[...i.keys()])){let o=i.get(r.symbol_id);o&&n(o,r.relative_path)}}function Uc(e,t={}){let{limit:n=30,scope:i}=t,r=i?`AND def_d.relative_path LIKE '%${i}%'`:"",s=e.all(`SELECT
349
371
  gs.symbol,
350
372
  COUNT(*) AS ref_count,
351
373
  COUNT(DISTINCT ref_d.id) AS file_count,
@@ -365,17 +387,17 @@ ${m}`,l+=1+m.length,u+=ei(m),r+=m.length+1}let d=uR(c);d&&n.push({...d,start:a,e
365
387
  WHERE m.role != 1
366
388
  ${e.pathExclusionsFor("def_d")}
367
389
  ${e.symbolNoiseFor("gs")}
368
- ${i}
390
+ ${r}
369
391
  GROUP BY gs.id
370
392
  ORDER BY ref_count DESC
371
- 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:vL(e,r,n)}function vL(e,t,n){return ft(e,{scope:t}).filter(r=>!e.isIgnored(r.relativePath)).map(r=>RL(e,r)).filter(r=>r.refCount>0).sort((r,i)=>i.refCount-r.refCount||i.fileCount-r.fileCount).slice(0,n)}function RL(e,t){let n=Qe(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 Za(e,t,n={}){return sp(e,t,n)?.map(r=>({symbol:r.symbol,shortName:r.shortName,fromFile:r.fromFile}))??[]}function ec(e,t){let n=kL(e,t);return n.length>0?n:wL(e,t)}function tc(e,t,n={}){return sp(e,t,n)?.filter(r=>!r.used).map(r=>({symbol:r.symbol,shortName:r.shortName,importedIn:r.importer}))??[]}function kL(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
393
+ LIMIT ?`,n).filter(a=>!e.isIgnored(a.defined_in)).map(a=>({symbol:a.symbol,shortName:v(a.symbol),refCount:a.ref_count,fileCount:a.file_count,definedIn:a.defined_in}));return s.length>0?s:ND(e,i,n)}function ND(e,t,n){return Lt(e,{scope:t}).filter(i=>!e.isIgnored(i.relativePath)).map(i=>FD(e,i)).filter(i=>i.refCount>0).sort((i,r)=>r.refCount-i.refCount||r.fileCount-i.fileCount).slice(0,n)}function FD(e,t){let n=at(e,t,{limit:500});return{symbol:t.symbol,shortName:v(t.symbol),refCount:n.length,fileCount:new Set(n.map(i=>i.file)).size,definedIn:t.relativePath}}function zc(e,t,n={}){return jf(e,t,n)?.map(i=>({symbol:i.symbol,shortName:i.shortName,fromFile:i.fromFile}))??[]}function Wc(e,t){let n=q(e,t),i=TD(e,t);if(i.length>0&&!AD(n))return i;let r=_D(e,t,n);return Kc(t)&&r.length>0?r:MD([...i,...r])}function Gc(e,t,n={}){return jf(e,t,n)?.filter(i=>!i.used).map(i=>({symbol:i.symbol,shortName:i.shortName,importedIn:i.importer}))??[]}function TD(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
372
394
  FROM mentions m
373
395
  JOIN chunks c ON m.chunk_id = c.id
374
396
  JOIN documents d ON c.document_id = d.id
375
397
  JOIN global_symbols gs ON m.symbol_id = gs.id
376
398
  WHERE gs.symbol LIKE ?
377
399
  AND m.role = 2
378
- 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 wL(e,t){let n=B(e,t),r=n?.relativePath??null,i=n?$(n.symbol):t.replace(/\(\)$/,""),o=n?Vt(n.symbol):!1,s=new Set;for(let a of O(e,{includeIgnored:!1}))for(let c of xe(e,a))LL(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 LL(e,t,n){return!e.sourcePath||n.targetFile&&op(e.sourcePath)!==op(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&NL(t)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function sp(e,t,n={}){let r=Fe(e,t);return r?IL(e,r,n)??(n.semantic===!1?null:DL(e,r))??PL(e,r):null}function IL(e,t,n){let i=e.all(`SELECT DISTINCT
400
+ ORDER BY d.relative_path`,`%${t}%`).filter(i=>!e.isIgnored(i.importer)).map(i=>({symbol:i.symbol,shortName:v(i.symbol),fromFile:i.importer}))}function _D(e,t,n=q(e,t)){let i=n?.relativePath??null,r=n?$(n.symbol):t.replace(/\(\)$/,""),o=n?gn(n.symbol):!1,s=new Set;for(let c of O(e,{includeIgnored:!1}))for(let l of oe(e,c))$D(l,c,{targetFile:i,targetLeaf:r,targetIsModule:o,targetPattern:t})&&s.add(c);let a=Kc(t)?t.trim():null;return[...s].sort().map(c=>({symbol:a??n?.symbol??r,shortName:a??(n?v(n.symbol):r),fromFile:c}))}function AD(e){return!!(e&&(e.symbol.startsWith("scip-clojure ")||H(e.relativePath)==="clojure"))}function MD(e){let t=new Set,n=[];for(let i of e){let r=`${i.symbol}|${i.fromFile}`;t.has(r)||(t.add(r),n.push(i))}return n.sort((i,r)=>i.fromFile.localeCompare(r.fromFile)||i.shortName.localeCompare(r.shortName))}function $D(e,t,n){return!e.sourcePath||n.targetFile&&$f(e.sourcePath)!==$f(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&VD(t)||e.kind==="namespace"&&jD(e,n.targetPattern)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function jD(e,t){let n=t.trim().replace(/\(\)$/,"");return Kc(n)?e.importedName===n||e.localName===n:!1}function Kc(e){let t=e.trim().replace(/\(\)$/,"");return t.includes(".")&&!t.includes("/")&&!t.includes(":")}function jf(e,t,n={}){let i=Ve(e,t);return i?OD(e,i,n)??(n.semantic===!1?null:BD(e,i))??HD(e,i):null}function OD(e,t,n){let r=e.all(`SELECT DISTINCT
379
401
  gs.symbol,
380
402
  def_d.relative_path AS from_file,
381
403
  imp_d.relative_path AS importer,
@@ -401,11 +423,11 @@ ${m}`,l+=1+m.length,u+=ei(m),r+=m.length+1}let d=uR(c);d&&n.push({...d,start:a,e
401
423
  LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
402
424
  WHERE imp_d.relative_path = ?
403
425
  AND m.role = 2
404
- ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(i.length>0){let o=n.semantic===!1?[]:li(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 DL(e,t){let n=li(e,t);return n.length>0?n.map(r=>{let i=ap(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 PL(e,t){return xe(e,t).map(n=>{let r=ap(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 ap(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 op(e){return e.replace(/\\/g,"/")}function NL(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function nc(e,t){let n=pr(e,t),r=fo(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&&!ad(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 rc(e,t){let n=B(e,t);return n?new F(e).definitionsForFile(n.relativePath).filter(i=>i.symbol!==n.symbol).filter(i=>sd(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:re(i.symbol)??"unknown"})):[]}function ic(e,t){let n=B(e,t);if(!n)return[];let r=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
426
+ ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(r.length>0){let o=n.semantic===!1?[]:Er(e,t);return r.map(s=>({symbol:s.symbol,shortName:v(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 BD(e,t){let n=Er(e,t);return n.length>0?n.map(i=>{let r=Of(i.importedName,i.localName,i.kind);return{symbol:r,shortName:r,fromFile:i.sourcePath??"(external)",importer:t,used:i.kind==="side-effect"?!0:i.isUsed}}):null}function HD(e,t){return oe(e,t).map(n=>{let i=Of(n.importedName,n.localName,n.kind),r=n.kind==="side-effect"?!0:n.used;return{symbol:i,shortName:i,fromFile:n.sourcePath??"(external)",importer:t,used:r}})}function Of(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 $f(e){return e.replace(/\\/g,"/")}function VD(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function Jc(e,t){let n=Fi(e,t),i=ns(e,n,{sort:!0});if(i.length===0)return[];let r=i.map(a=>({symbol:a.symbol,shortName:a.shortName,startLine:a.startLine,endLine:a.endLine,signature:a.signature,children:[]})),o=new Map;for(let a of r)o.set(a.symbol,a);let s=[];for(let a=0;a<i.length;a++){let c=i[a],l=r[a];if(c.enclosingSymbol&&o.has(c.enclosingSymbol)){o.get(c.enclosingSymbol).children.push(l);continue}let d=null,u=1/0;for(let m of r)if(m!==l&&m.startLine<=l.startLine&&m.endLine>=l.endLine){if(m.startLine===l.startLine&&m.endLine===l.endLine&&!qm(m.symbol,l.symbol))continue;let f=m.endLine-m.startLine;f<u&&(u=f,d=m)}d?d.children.push(l):s.push(l)}return s}function Xc(e,t){let n=q(e,t);if(!n)return[];let r=new A(e).definitionsForFile(n.relativePath).filter(o=>o.symbol!==n.symbol).filter(o=>Vm(n.symbol,o.symbol)).sort((o,s)=>o.startLine-s.startLine||o.endLine-s.endLine).map(o=>({symbol:o.symbol,shortName:v(o.symbol),startLine:o.startLine,endLine:o.endLine,kind:se(o.symbol)??"unknown"}));return H(n.relativePath)!=="clojure"?r:UD(r,qD(e,n))}function qD(e,t){let n=$(t.symbol);if(!n)return[];let i=v(t.symbol);return(X(e,t.relativePath)?.clojureMembers??[]).filter(r=>r.ownerName===n).map(r=>({symbol:`${t.symbol}${r.memberName}().`,shortName:`${i}:${r.memberName}()`,startLine:r.startLine,endLine:r.endLine,kind:r.memberKind}))}function UD(e,t){let n=new Map;for(let i of[...e,...t])n.set(`${i.shortName}:${i.startLine}:${i.endLine}`,i);return[...n.values()].sort((i,r)=>i.startLine-r.startLine||i.endLine-r.endLine)}function Qc(e,t){let n=q(e,t);if(!n)return[];let i=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
405
427
  FROM mentions m
406
428
  JOIN chunks c ON m.chunk_id = c.id
407
429
  WHERE m.symbol_id = ?
408
- AND m.role != 1`,n.symbolId);return[{name:b(n.symbol),count:r?.file_count??0}]}function oc(e,t){let n=Fe(e,t);if(!n)return[];let i=e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
430
+ AND m.role != 1`,n.symbolId);return[{name:v(n.symbol),count:i?.file_count??0}]}function Yc(e,t){let n=Ve(e,t);if(!n)return[];let r=e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
409
431
  FROM mentions m
410
432
  JOIN chunks c ON m.chunk_id = c.id
411
433
  JOIN documents d ON c.document_id = d.id
@@ -422,7 +444,7 @@ ${m}`,l+=1+m.length,u+=ei(m),r+=m.length+1}let d=uR(c);d&&n.push({...d,start:a,e
422
444
  AND m.role != 1
423
445
  AND def_d.id != d.id
424
446
  GROUP BY d.id
425
- 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=ce(e).get(n);return!s||s.size===0?[]:[{name:n,count:s.size}]}function sc(e,t={}){return EL(e,t).map(n=>({name:b(n.symbol),count:n.file_count}))}function EL(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
447
+ ORDER BY symbol_count DESC`,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}));if(r.length>0)return r;let s=ye(e).get(n);return!s||s.size===0?[]:[{name:n,count:s.size}]}function Zc(e,t={}){return zD(e,t).map(n=>({name:v(n.symbol),count:n.file_count}))}function zD(e,t){let{limit:n=30,scope:i}=t,r=i?`AND def_d.relative_path LIKE '%${i}%'`:"";return e.all(`SELECT gs.symbol, COUNT(DISTINCT c.document_id) AS file_count
426
448
  FROM mentions m
427
449
  JOIN chunks c ON m.chunk_id = c.id
428
450
  JOIN global_symbols gs ON m.symbol_id = gs.id
@@ -437,11 +459,11 @@ ${m}`,l+=1+m.length,u+=ei(m),r+=m.length+1}let d=uR(c);d&&n.push({...d,start:a,e
437
459
  WHERE m.role != 1
438
460
  ${e.pathExclusionsFor("def_d")}
439
461
  ${e.symbolNoiseFor("gs")}
440
- ${i}
462
+ ${r}
441
463
  GROUP BY gs.id
442
464
  HAVING file_count > 1
443
465
  ORDER BY file_count DESC
444
- LIMIT ?`,n)}function ac(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
466
+ LIMIT ?`,n)}function el(e,t={}){let{limit:n=30,scope:i}=t,r=i?`AND d.relative_path LIKE '%${i}%'`:"";return e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
445
467
  FROM mentions m
446
468
  JOIN chunks c ON m.chunk_id = c.id
447
469
  JOIN documents d ON c.document_id = d.id
@@ -458,10 +480,10 @@ ${m}`,l+=1+m.length,u+=ei(m),r+=m.length+1}let d=uR(c);d&&n.push({...d,start:a,e
458
480
  AND def_d.id != d.id
459
481
  ${e.pathExclusionsFor("d")}
460
482
  ${e.symbolNoiseFor("gs")}
461
- ${i}
483
+ ${r}
462
484
  GROUP BY d.id
463
485
  ORDER BY symbol_count DESC
464
- LIMIT ?`,n).filter(s=>!e.isIgnored(s.relative_path)).map(s=>({name:s.relative_path,count:s.symbol_count}))}function cc(e,t,n){let r=Fe(e,t)??t,i=Fe(e,n)??n,o=e.get(`SELECT COUNT(DISTINCT gs.id) AS shared
486
+ LIMIT ?`,n).filter(s=>!e.isIgnored(s.relative_path)).map(s=>({name:s.relative_path,count:s.symbol_count}))}function tl(e,t,n){let i=Ve(e,t)??t,r=Ve(e,n)??n,o=e.get(`SELECT COUNT(DISTINCT gs.id) AS shared
465
487
  FROM global_symbols gs
466
488
  WHERE (
467
489
  -- Defined in file1, referenced in file2
@@ -493,7 +515,7 @@ ${m}`,l+=1+m.length,u+=ei(m),r+=m.length+1}let d=uR(c);d&&n.push({...d,start:a,e
493
515
  JOIN documents d ON c.document_id = d.id
494
516
  WHERE m.symbol_id = gs.id AND m.role != 1 AND d.relative_path = ?
495
517
  )
496
- )`,r,i,i,r);return{...cp(r,i,o?.shared??0)}}function lc(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
518
+ )`,i,r,r,i);return{...Bf(i,r,o?.shared??0)}}function nl(e,t={}){let{limit:n=20,scope:i}=t,r=i?`AND d1.relative_path LIKE '%${i}%' AND d2.relative_path LIKE '%${i}%'`:"";return e.all(`SELECT
497
519
  def_d.relative_path AS file1,
498
520
  ref_d.relative_path AS file2,
499
521
  COUNT(DISTINCT gs.id) AS shared
@@ -512,18 +534,18 @@ ${m}`,l+=1+m.length,u+=ei(m),r+=m.length+1}let d=uR(c);d&&n.push({...d,start:a,e
512
534
  WHERE m.role != 1
513
535
  AND def_d.id != ref_d.id
514
536
  ${e.pathExclusionsFor("def_d","ref_d")}
515
- ${i}
537
+ ${r}
516
538
  GROUP BY def_d.id, ref_d.id
517
539
  ORDER BY shared DESC
518
- LIMIT ?`,n).filter(s=>!e.isIgnored(s.file1)&&!e.isIgnored(s.file2)).map(s=>cp(s.file1,s.file2,s.shared))}function cp(e,t,n){return{file1:e,file2:t,sharedSymbols:n,actionTier:"signal",couplingKind:"shared-symbol-coupling",evidenceReasons:[`${n} symbol(s) are defined in one file and referenced by the other`],recommendation:"Review whether the shared symbol surface is an intentional boundary or hidden coordination pressure before moving code."}}function Ln(e,t={}){let{scope:n,maxDepth:r=10}=t,i=ce(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 y=c.slice(g).concat(d),h=y.indexOf(y.reduce((R,L)=>R<L?R:L)),x=[...y.slice(h,-1),...y.slice(0,h),y[h]],v=x.join(" -> ");u.has(v)||(u.add(v),o.push({path:x,kind:TL(x)}))}return}if(s.has(d))return;s.add(d),a.add(d),c.push(d);let p=i.get(d);if(p)for(let g of p)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 TL(e){for(let r of e){let i=J(r);if(i==="test"||i==="barrel"||i==="entry")return"module-hierarchy"}if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":_o(t)||_o(n)||lp(t,n)||lp(n,t)||up(t,n)||up(n,t)||J(t)==="entry"||J(n)==="entry"?"module-hierarchy":"real"}function lp(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 up(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 uc(e,t={}){let{limit:n=20,scope:r,minFanIn:i=2,minFanOut:o=2,scanLimit:s}=t,a=new F(e);return Ve(a.productionCallableDefinitions({scope:r,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s).map(u=>_L(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 _L(e,t,n){let r=new Set(Qe(e,t,{limit:500,semantic:n}).map(s=>s.file)).size,i=new Set(He(e,t,{limit:500,semantic:n}).filter(s=>s.file!==t.relativePath).map(s=>`${s.symbol}|${s.file}`)).size,o=r*i;return{symbol:t.symbol,shortName:b(t.symbol),fanIn:r,fanOut:i,score:o,definedIn:t.relativePath,actionTier:"signal",riskKind:"coordination-hotspot",evidenceReasons:[`${r} incoming file(s) reference this symbol`,`${i} distinct cross-file callee symbol(s) are reached from it`,`centrality score is ${o} (fan-in * fan-out)`],recommendation:"Review ownership, API stability, and caller groups before changing this central symbol; do not refactor solely from graph centrality."}}function In(e,t={}){let{scope:n,minLoc:r=3,scanLimit:i}=t,o=new F(e),s=t.semantic!==!1,a=Ve(o.productionCallableDefinitions({scope:n,minLoc:r,excludeEntrySurfaces:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,sortByLocDesc:typeof i=="number"&&i>0}),i),c=o.symbolsWithNonSelfCallees(a,{additive:!1,semantic:!1}),l=a.filter(h=>!c.has(h.symbolId)),u=o.crossFileCallerMap(l,{semantic:!1}),d=new Set(u.keys());for(let h of o.frameworkReferencedSymbolIds(l))d.add(h);let m=l.filter(h=>!d.has(h.symbolId));if(s&&m.length>0){for(let h of Xe(e,m).keys())d.add(h);for(let h of o.symbolsWithNonSelfCallees(m,{additive:!1,semantic:!0}))c.add(h);m=m.filter(h=>!d.has(h.symbolId)).filter(h=>!c.has(h.symbolId))}let p=o.sourceFallbackCallerFiles(m);for(let h of p.keys())d.add(h);let g=m.filter(h=>!d.has(h.symbolId)),y=o.symbolsWithNonSelfCallees(g,{additive:!0,semantic:s});for(let h of y)c.add(h);return g.filter(h=>!c.has(h.symbolId)).sort((h,x)=>U(x)-U(h)||h.relativePath.localeCompare(x.relativePath)||h.startLine-x.startLine).map(h=>({symbol:h.symbol,shortName:b(h.symbol),relativePath:h.relativePath,startLine:h.startLine,endLine:h.endLine,loc:U(h)}))}var mc={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"},dc=new Map;for(let[e,t]of Object.entries(mc))dc.set(t.toLowerCase(),Number(e));var dp=500;function FL(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),r=dc.get(n);if(r!==void 0)return r;for(let[i,o]of dc)if(i.includes(n))return o;return null}function pc(e,t,n={}){let{scope:r,limit:i=100}=n,o=FL(t);return o===null?[]:AL(e,r).map(a=>({row:a,resolvedKind:pp(a)})).filter(a=>a.resolvedKind===o).slice(0,i).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:b(a.symbol),kind:c,kindName:mc[c]??"Unknown",relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function fc(e,t={}){let n=$L(e,t.scope);for(let r of ML(e,t.scope)){let i=pp(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:mc[r]??"Unknown",count:i}))}function AL(e,t){return ft(e,{scope:t}).map(OL)}function $L(e,t){let n=new Map;for(let r of mp(O(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", "),o=e.all(`SELECT gs.kind AS kind, COUNT(*) AS count
540
+ LIMIT ?`,n).filter(s=>!e.isIgnored(s.file1)&&!e.isIgnored(s.file2)).map(s=>Bf(s.file1,s.file2,s.shared))}function Bf(e,t,n){return{file1:e,file2:t,sharedSymbols:n,actionTier:"signal",couplingKind:"shared-symbol-coupling",evidenceReasons:[`${n} symbol(s) are defined in one file and referenced by the other`],recommendation:"Review whether the shared symbol surface is an intentional boundary or hidden coordination pressure before moving code."}}function Un(e,t={}){let{scope:n,maxDepth:i=10}=t,r=ye(e,n),o=[],s=new Set,a=new Set,c=[];function l(u,m){if(m>i)return;if(a.has(u)){let f=c.indexOf(u);if(f!==-1){let g=c.slice(f).concat(u),b=g.indexOf(g.reduce((R,C)=>R<C?R:C)),x=[...g.slice(b,-1),...g.slice(0,b),g[b]],S=x.join(" -> ");d.has(S)||(d.add(S),o.push({path:x,kind:WD(x)}))}return}if(s.has(u))return;s.add(u),a.add(u),c.push(u);let p=r.get(u);if(p)for(let f of p)l(f,m+1);c.pop(),a.delete(u)}let d=new Set;for(let u of r.keys())s.has(u)||l(u,0);return o.sort((u,m)=>u.kind!==m.kind?u.kind==="real"?-1:1:u.path.length-m.path.length),o}function WD(e){for(let i of e){let r=Z(i);if(r==="test"||r==="barrel"||r==="entry")return"module-hierarchy"}if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":as(t)||as(n)||Hf(t,n)||Hf(n,t)||Vf(t,n)||Vf(n,t)||Z(t)==="entry"||Z(n)==="entry"?"module-hierarchy":"real"}function Hf(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 Vf(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=e.replace(/\.rs$/,""),i=t.replace(/\.rs$/,"");if(n===i+"_tests"||n===i+"/tests")return!0;let r=e.split("/"),o=t.split("/");if(r.length===o.length&&r.includes("tests")&&o.includes("src")){let s=r[r.length-1],a=o[o.length-1];if(s&&s===a)return!0}return!1}function il(e,t={}){let{limit:n=20,scope:i,minFanIn:r=2,minFanOut:o=2,scanLimit:s}=t,a=new A(e);return qe(a.productionCallableDefinitions({scope:i,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s).map(d=>GD(e,d,t.semantic!==!1)).filter(d=>d.fanIn>=r&&d.fanOut>=o).sort((d,u)=>u.score-d.score||u.fanIn-d.fanIn).slice(0,n)}function GD(e,t,n){let i=new Set(at(e,t,{limit:500,semantic:n}).map(s=>s.file)).size,r=new Set(Je(e,t,{limit:500,semantic:n}).filter(s=>s.file!==t.relativePath).map(s=>`${s.symbol}|${s.file}`)).size,o=i*r;return{symbol:t.symbol,shortName:v(t.symbol),fanIn:i,fanOut:r,score:o,definedIn:t.relativePath,actionTier:"signal",riskKind:"coordination-hotspot",evidenceReasons:[`${i} incoming file(s) reference this symbol`,`${r} distinct cross-file callee symbol(s) are reached from it`,`centrality score is ${o} (fan-in * fan-out)`],recommendation:"Review ownership, API stability, and caller groups before changing this central symbol; do not refactor solely from graph centrality."}}function zn(e,t={}){let{scope:n,minLoc:i=3,scanLimit:r}=t,o=new A(e),s=t.semantic!==!1,a=0,c=D("isolated.candidates",()=>{let y=qe(o.productionCallableDefinitions({scope:n,minLoc:i,excludeEntrySurfaces:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:typeof r=="number"&&r>0}),r);return a=y.length,y},()=>({definitions:a})),l=0,d=D("isolated.strict-callees",()=>{let y=o.symbolsWithNonSelfCallees(c,{additive:!1,semantic:!1});return l=y.size,y},()=>({definitions:c.length,symbols:l})),u=c.filter(y=>!d.has(y.symbolId)),m=0,p=D("isolated.scip-callers",()=>{let y=o.crossFileCallerMap(u,{semantic:!1});return m=y.size,y},()=>({definitions:u.length,symbols:m})),f=new Set(p.keys());for(let y of o.frameworkReferencedSymbolIds(u))f.add(y);let g=u.filter(y=>!f.has(y.symbolId));if(s&&g.length>0){for(let y of st(e,g).keys())f.add(y);for(let y of o.symbolsWithNonSelfCallees(g,{additive:!1,semantic:!0}))d.add(y);g=g.filter(y=>!f.has(y.symbolId)).filter(y=>!d.has(y.symbolId))}let b=0,x=D("isolated.source-fallback-callers",()=>{let y=o.sourceFallbackCallerFiles(g,{skipPath:w=>Z(w)==="test"});return b=y.size,y},()=>({definitions:g.length,symbols:b}));for(let y of x.keys())f.add(y);let S=g.filter(y=>!f.has(y.symbolId)),R=0,C=D("isolated.additive-callees",()=>{let y=o.symbolsWithNonSelfCallees(S,{additive:!0,semantic:s});return R=y.size,y},()=>({definitions:S.length,symbols:R}));for(let y of C)d.add(y);return S.filter(y=>!d.has(y.symbolId)).sort((y,w)=>J(w)-J(y)||y.relativePath.localeCompare(w.relativePath)||y.startLine-w.startLine).map(y=>({symbol:y.symbol,shortName:v(y.symbol),relativePath:y.relativePath,startLine:y.startLine,endLine:y.endLine,loc:J(y)}))}import{SymbolInformation_Kind as Le}from"@c4312/scip";var qf=500;function KD(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),i=df.get(n);if(i!==void 0)return i;for(let[r,o]of Ss)if(o.toLowerCase().includes(n))return r;return null}function rl(e,t,n={}){let{scope:i,limit:r=100}=n,o=KD(t);return o===null?[]:JD(e,i).map(a=>({row:a,resolvedKind:zf(a)})).filter(a=>a.resolvedKind===o).slice(0,r).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:v(a.symbol),kind:c,kindName:_c(c),relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function ol(e,t={}){let n=XD(e,t.scope);for(let i of QD(e,t.scope)){let r=zf(i);r===null||r===0||n.set(r,(n.get(r)??0)+1)}return[...n.entries()].sort((i,r)=>r[1]-i[1]||i[0]-r[0]).map(([i,r])=>({kind:i,kindName:_c(i),count:r}))}function JD(e,t){return Lt(e,{scope:t}).map(YD)}function XD(e,t){let n=new Map;for(let i of Uf(O(e,{scope:t,includeIgnored:!1}))){let r=i.map(()=>"?").join(", "),o=e.all(`SELECT gs.kind AS kind, COUNT(*) AS count
519
541
  FROM defn_enclosing_ranges der
520
542
  JOIN global_symbols gs ON der.symbol_id = gs.id
521
543
  JOIN documents d ON der.document_id = d.id
522
544
  WHERE gs.kind IS NOT NULL
523
545
  AND gs.kind != 0
524
546
  AND gs.symbol NOT LIKE '%#'
525
- AND d.relative_path IN (${i})
526
- GROUP BY gs.kind`,...r);for(let s of o)n.set(s.kind,(n.get(s.kind)??0)+s.count)}return n}function ML(e,t){let n=[];for(let r of mp(O(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", ");n.push(...e.all(`SELECT gs.symbol,
547
+ AND d.relative_path IN (${r})
548
+ GROUP BY gs.kind`,...i);for(let s of o)n.set(s.kind,(n.get(s.kind)??0)+s.count)}return n}function QD(e,t){let n=[];for(let i of Uf(O(e,{scope:t,includeIgnored:!1}))){let r=i.map(()=>"?").join(", ");n.push(...e.all(`SELECT gs.symbol,
527
549
  gs.kind,
528
550
  gs.documentation,
529
551
  gs.enclosing_symbol,
@@ -535,12 +557,12 @@ ${m}`,l+=1+m.length,u+=ei(m),r+=m.length+1}let d=uR(c);d&&n.push({...d,start:a,e
535
557
  JOIN documents d ON der.document_id = d.id
536
558
  WHERE (gs.kind IS NULL OR gs.kind = 0 OR gs.symbol LIKE '%#')
537
559
  ${e.symbolNoiseFor("gs")}
538
- AND d.relative_path IN (${i})
539
- ORDER BY d.relative_path, der.start_line, der.end_line, gs.symbol`,...r))}return n}function mp(e){let t=[];for(let n=0;n<e.length;n+=dp)t.push(e.slice(n,n+dp));return t}function OL(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 pp(e){return e.kind!==null&&e.kind!==0?jL(e.kind,e.symbol,e.documentation):BL(e.symbol,e.documentation,e.enclosing_symbol)}function jL(e,t,n){let r=(n??"").toLowerCase();if(re(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 BL(e,t,n){let r=Se(e);if("kind"in r)return null;let i=r.descriptors,o=i[i.length-2]??null,s=re(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?re(n):o?.suffix??null)==="type"?21:83}function gc(e,t={}){let{limit:n=10,scope:r,minDepth:i=3}=t,o=ce(e,r),s=new Map,a=[],c=new Map,l=new Map,u=new Set,d=[],m=0;for(let S of o.keys()){if(c.has(S))continue;let C=[],P=(o.get(S)??new Set).values();for(c.set(S,m),l.set(S,m),m+=1,d.push(S),u.add(S),C.push({node:S,iter:P,pendingChild:null});C.length>0;){let D=C[C.length-1];if(D.pendingChild!==null){let Ue=D.pendingChild;D.pendingChild=null,l.set(D.node,Math.min(l.get(D.node),l.get(Ue)))}let z=D.iter.next();if(z.done){if(l.get(D.node)===c.get(D.node)){let Ue=[];for(;;){let Me=d.pop();if(u.delete(Me),Ue.push(Me),s.set(Me,a.length),Me===D.node)break}a.push(Ue)}C.pop();continue}let De=z.value;if(c.has(De))u.has(De)&&l.set(D.node,Math.min(l.get(D.node),c.get(De)));else{c.set(De,m),l.set(De,m),m+=1,d.push(De),u.add(De);let Ue=(o.get(De)??new Set).values();D.pendingChild=De,C.push({node:De,iter:Ue,pendingChild:null})}}}let p=new Map,g=new Array(a.length);for(let S=0;S<a.length;S++)g[S]=a[S].length,p.set(S,new Set);for(let[S,C]of o){let P=s.get(S);for(let D of C){let z=s.get(D);z!==P&&p.get(P).add(z)}}let y=new Array(a.length),h=new Array(a.length);for(let S=0;S<a.length;S++){let C=[],P=0;for(let D of p.get(S)){let z=h[D];z>P&&(P=z,C=y[D])}y[S]=[S,...C],h[S]=g[S]+P}function x(S){return y[S]}let v=a.map(S=>[...S].sort()),R=new Set,L=[];for(let S=0;S<a.length;S++){let C=x(S),P=[];for(let z of C)P.push(...v[z]);if(P.length<i)continue;let D=P.join(" ");R.has(D)||(R.add(D),L.push(HL(P)))}return L.sort((S,C)=>C.depth-S.depth),VL(L).slice(0,n)}function HL(e){return{chain:e,depth:e.length,actionTier:"signal",chainKind:"transitive-dependency-depth",evidenceReasons:[`${e.length} file(s) form the representative transitive dependency path`,"cycles are condensed before longest-path calculation"],recommendation:"Review whether the chain crosses ownership or layer boundaries; shorten it only when the dependency direction is accidental."}}function VL(e){let t=[];for(let n of e)t.some(r=>qL(n.chain,r.chain))||t.push(n);return t}function qL(e,t){if(e.length>=t.length)return!1;let n=t.length-e.length;for(let r=0;r<e.length;r++)if(e[r]!==t[n+r])return!1;return!0}function hc(e,t){let n=B(e,t);if(!n)return[];let r=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
540
- 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 d=e.get("SELECT symbol, enclosing_symbol FROM global_symbols WHERE symbol = ?",o);if(!d)break;i.push({symbol:d.symbol,shortName:b(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(y=>y.suffix==="method"?`${y.name}()`:y.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 yi(e,t,n={}){let r=B(e,t);if(!r)return null;let i=n.semantic!==!1,o=Qe(e,r,{limit:50,semantic:i}),s=Lr(He(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 Ye(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function Ce(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function Zt(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 fp(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 yc(e,t){if(t<=0)return new Map;let n=new Map;for(let[r,i]of e)i>0&&n.set(r,Math.log(t/i));return n}function bi(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 Jo(e,t){let n=0;for(let r of e){let i=t.get(r)??0;n+=i*i}return Math.sqrt(n)}function gp(e,t,n,r={}){let i=0,o=0,s=0,a=r.medianIdf??bi(n),c=[],l=[];for(let m of e){let p=n.get(m)??0;o+=p*p,t.has(m)&&(i+=p*p,p>=a?c.push(m):l.push(m))}if(c.length===0&&l.length===0)return{similarity:0,significantShared:[],trivialShared:[]};for(let m of t){let p=n.get(m)??0;s+=p*p}let u=Math.sqrt(o)*Math.sqrt(s),d=u>0?i/u:0;return c.sort((m,p)=>(n.get(p)??0)-(n.get(m)??0)),{similarity:d,significantShared:c,trivialShared:l}}function hp(e,t,n,r){let i=0,o=r.medianIdf??bi(n),s=[],a=[];for(let u of e){if(!t.has(u))continue;let d=n.get(u)??0;i+=d*d,d>=o?s.push(u):a.push(u)}if(s.length===0&&a.length===0)return{similarity:0,significantShared:[],trivialShared:[]};let c=r.magnitudeA*r.magnitudeB,l=c>0?i/c:0;return s.sort((u,d)=>(n.get(d)??0)-(n.get(u)??0)),{similarity:l,significantShared:s,trivialShared:a}}function xi(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=JL(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!oe(o.symbol))return[];if(o.callees.size===0)return yp(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit});let s=UL(e,o,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,i):yp(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit})}function UL(e,t,n,r){let i=Ko(e,{minCallees:3,scanLimit:r.scanLimit,semantic:r.semantic}),o=ZL(t,i),s=WL(t,i),a=bi(s),c=Jo(t.callees,s),l=[];for(let u of o){if(u.callees.size<3)continue;let d=Jo(u.callees,s),m=xp(t,u,s,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0,medianIdf:a,magnitudeA:c,magnitudeB:d});m&&l.push(m)}return l.sort((u,d)=>d.similarity-u.similarity),l}function WL(e,t){let n=new Map(t.docFreq);for(let r of e.callees)n.set(r,(n.get(r)??0)+1);return yc(n,t.corpus.length+1)}function xp(e,t,n,r){let i=r.magnitudeA===void 0||r.magnitudeB===void 0?gp(e.callees,t.callees,n,{medianIdf:r.medianIdf}):hp(e.callees,t.callees,n,{medianIdf:r.medianIdf,magnitudeA:r.magnitudeA,magnitudeB:r.magnitudeB}),{similarity:o,significantShared:s,trivialShared:a}=i;if(o<r.minSimilarity)return null;let c=s.length+a.length;if(s.length<r.requireSignificantShared&&c<r.requireSharedCount)return null;let l=s.length>0?s:a,u=Cp(l,"callees");return{symbolA:e.symbol,shortNameA:b(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:b(t.symbol),fileB:t.file,similarity:o,similarityBasis:"callees",sharedCallees:l.map(b),uniqueToA:[...Ce(e.callees,t.callees)].map(b),uniqueToB:[...Ce(t.callees,e.callees)].map(b),...u}}function Tt(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=Ko(e,{minCallees:o,scope:i,scanLimit:a,semantic:t.semantic!==!1}),l=c.corpus,u=t.focusFiles,d=[],m=0;for(let p=0;p<l.length;p+=1){let g=l[p],y=u?.has(g.file)??!1,h=c.weightedMagnitudes[p],x=new Set;for(let v of g.callees){let R=c.candidateIndexesByCallee.get(v);if(R)for(let L of R)L<=p||u&&!y&&!u.has(l[L].file)||x.add(L)}for(let v of x){let R=l[v];if(s&&g.file===R.file)continue;if(g.paramCount>=0&&R.paramCount>=0){let S=Math.abs(g.paramCount-R.paramCount),C=Math.max(2,Math.ceil(Math.max(g.paramCount,R.paramCount)*.5));if(S>C)continue}let L=xp(g,R,c.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:c.medianIdf,magnitudeA:h,magnitudeB:c.weightedMagnitudes[v]});L&&(GL(d,L,r,m),m+=1)}}return d.sort((p,g)=>g.result.similarity-p.result.similarity||p.order-g.order),d.map(p=>p.result)}function GL(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 zL=["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 JL(e,t,n){let r=B(e,t);if(!r||!oe(r.symbol))return null;let i=new F(e),o=He(e,r,{semantic:n.semantic});return{symbol:r.symbol,file:r.relativePath,callees:Xo(o.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}var KL=Z("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),XL=Z("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function QL(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:o}=t,s=t.semantic!==!1,a=KL.get(e,()=>new Map),c=`${n}|${r??""}|${o??""}|${s}`,l=a.get(c);return l||(l=eI(e,{minCallees:n,scope:r,scanLimit:o,semantic:s}),a.set(c,l)),i===void 0?l:l.filter(u=>u.symbol!==i)}function Ko(e,t){let{minCallees:n,scope:r,scanLimit:i}=t,o=t.semantic!==!1,s=XL.get(e,()=>new Map),a=`${n}|${r??""}|${i??""}|${o}`,c=s.get(a);return c||(c=YL(QL(e,{minCallees:n,scope:r,scanLimit:i,semantic:o})),s.set(a,c)),c}function YL(e){let t=new Map;for(let s of e)for(let a of s.callees)t.set(a,(t.get(a)??0)+1);let n=Math.max(8,Math.ceil(Math.sqrt(e.length))),r=yc(t,e.length),i=e.map(s=>Jo(s.callees,r)),o=new Map;for(let s=0;s<e.length;s+=1){let a=e[s];for(let c of a.callees){if((t.get(c)??0)>n)continue;let l=o.get(c);l||(l=[],o.set(c,l)),l.push(s)}}return{corpus:e,candidateIndexesByCallee:o,docFreq:t,idfWeights:r,weightedMagnitudes:i,medianIdf:bi(r),ubiquityThreshold:n}}function ZL(e,t){let n=new Map;for(let r of e.callees)for(let i of t.candidateIndexesByCallee.get(r)??[]){let o=t.corpus[i];o.symbol!==e.symbol&&n.set(o.symbol,o)}return n.size>0?[...n.values()]:t.corpus.filter(r=>r.symbol!==e.symbol)}function eI(e,t){let{minCallees:n,scope:r,scanLimit:i,semantic:o}=t,s=new F(e),a=Ve(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:Xo((c.get(l.symbolId)??[]).map(u=>u.symbol)),paramCount:s.callableSignature(l)?.paramCount??-1})).filter(l=>l.callees.size>=n)}function Xo(e){return new Set([...e].filter(t=>!tI(t)))}function tI(e){return zL.some(t=>e.includes(t))}function yp(e,t,n){let r=oI(e,t);if(!r||r.tokens.size<3)return[];let i=n.minSimilarity>=.5?n.minSimilarity:.3,o=[],s=mI(r,uI(e,{scanLimit:n.scanLimit}));for(let a of s){if(a.symbol===r.symbol||a.tokens.size<3)continue;let c=Ye(r.tokens,a.tokens);if(c.size<2)continue;let l=new Set([...r.tokens,...a.tokens]),u=l.size>0?c.size/l.size:0;u<i||o.push({symbolA:r.symbol,shortNameA:b(r.symbol),fileA:r.file,symbolB:a.symbol,shortNameB:b(a.symbol),fileB:a.file,similarity:u,similarityBasis:"source-tokens",sharedCallees:[...c].sort(),uniqueToA:[...Ce(r.tokens,a.tokens)].sort(),uniqueToB:[...Ce(a.tokens,r.tokens)].sort(),...Cp([...c],"source-tokens")})}return o.sort((a,c)=>c.similarity-a.similarity||a.shortNameB.localeCompare(c.shortNameB)),o.slice(0,n.limit)}function Cp(e,t){let n=e.flatMap(Sc),r=e.flatMap(h=>bp(h,t)),i=bc(n,vp),o=bc(n,Rp),s=bc(r,xc),a=[...new Set(r.filter(Sp))],c=e.filter(h=>{let x=bp(h,t);return x.some(v=>xc.has(v))&&x.some(Sp)}).length,l=[];i.length>0&&l.push(`access/query scaffolding: ${i.slice(0,5).join(", ")}`),o.length>0&&l.push(`framework/generic scaffolding: ${o.slice(0,5).join(", ")}`),s.length>0&&l.push(`domain behavior verbs: ${s.slice(0,5).join(", ")}`),s.length>0&&a.length>0&&l.push(`domain-specific terms: ${a.slice(0,5).join(", ")}`);let u=t==="source-tokens"&&n.length>0&&n.every(h=>kp.has(h));u&&l.push("shared source tokens are generic scaffolding");let d=s.length>0&&a.length>0,m=i.length+o.length>0,p=t==="callees"&&d&&e.length>=4&&a.length>=4&&c>=2,g=p?"domain-behavior":d?m?"mixed":"domain-behavior":i.length>0?"access-query-scaffolding":o.length>0||u?"framework-scaffolding":"structural-overlap";g==="structural-overlap"&&e.length>0&&l.push(`shared ${t} overlap has no recognized domain or scaffolding category`);let y=g==="domain-behavior"&&(e.length>=3||p)?"direct":"signal";return{evidenceClass:g,actionTier:y,evidenceClassReasons:l,recommendation:nI(g,y)}}function nI(e,t){return t==="direct"?"Shared domain behavior looks concrete; review for an extract/reuse opportunity.":e==="mixed"?"Shared evidence mixes domain behavior with scaffolding; review semantics before extracting anything.":e==="access-query-scaffolding"?"Shared evidence is mostly access/query scaffolding; compare product semantics before reusing code.":e==="structural-overlap"?"Shared structure has no domain or scaffolding classification; inspect names and behavior before reusing code.":"Shared evidence is mostly framework or generic scaffolding; treat as a contextual signal."}function bc(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function Sc(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function bp(e,t){if(t==="source-tokens")return Sc(e);let n=$(e);return Sc(n.length>0?n:rI(e))}function rI(e){return e.replace(/[()`]/g," ").replace(/\.[a-z][a-z0-9]+(?=\s|$)/gi," ").split(/[:/\\\s]+/).map(r=>r.trim()).filter(r=>/[A-Za-z]/.test(r)).at(-1)?.replace(/\.$/,"")??e}function Sp(e){return e.length>3&&!xc.has(e)&&!vp.has(e)&&!Rp.has(e)&&!kp.has(e)&&!iI.has(e)}var xc=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),vp=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),Rp=new Set(["bytes","computed","crypto","describe","effect","expect","fetch","filter","hex","hook","json","map","mounted","on","promise","random","react","reduce","ref","render","state","test","token","trim","uuid","vue","watch"]),kp=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),iI=new Set(["best","backend","conflict","database","effect","effects","error","errors","frontend","found","helpers","javascript","module","modules","scip","shared","source","typescript","utils","with","workflow","workflows"]);function oI(e,t){let n=B(e,t);if(!n||!oe(n.symbol))return null;let r=sI(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function sI(e,t){let n=$(t.symbol),r=gI(e,t.relativePath,t.startLine,t.endLine,n),i=Ip(r,n);return i.size>0?i:null}var aI=Z("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),cI=Z("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function wp(e){return`${e.scanLimit??""}`}function lI(e,t={}){let n=aI.get(e,()=>new Map),r=wp(t),i=n.get(r);return i||(i=pI(e,t),n.set(r,i)),i}function uI(e,t={}){let n=cI.get(e,()=>new Map),r=wp(t),i=n.get(r);return i||(i=dI(lI(e,t)),n.set(r,i)),i}function dI(e){let t=new Map;for(let i of e)for(let o of i.tokens)t.set(o,(t.get(o)??0)+1);let n=Math.max(8,Math.ceil(Math.sqrt(e.length))),r=new Map;for(let i of e)for(let o of i.tokens){if((t.get(o)??0)>n)continue;let s=r.get(o);s||(s=[],r.set(o,s)),s.push(i)}return{corpus:e,candidateByToken:r,docFreq:t,ubiquityThreshold:n}}function mI(e,t){let n=new Map;for(let r of e.tokens)for(let i of t.candidateByToken.get(r)??[])i.symbol!==e.symbol&&n.set(i.symbol,i);return n.size>0?[...n.values()]:t.corpus.filter(r=>r.symbol!==e.symbol)}function pI(e,t={}){let n=new F(e),{scanLimit:r}=t,i=Ve(n.productionCallableDefinitions({sortByLocDesc:typeof r=="number"&&r>0}),r);return fI(e,i)}function fI(e,t){let n=new Map;for(let i of t){let o=n.get(i.relativePath)??[];o.push(i),n.set(i.relativePath,o)}let r=new Map;for(let[i,o]of n){let s=T(e,i);if(!s)continue;let a=X(e,i,s),c=yI(e,i,a),l=!1,u=null;for(let d of o){let m=hI(d),p=c.get(m),g=p?new Set(p.tokens):null;g||(u??=We(e,i),g=Ip(Lp(u,d.startLine,d.endLine,d.leaf),d.leaf),c.set(m,{key:m,symbol:d.symbol,startLine:d.startLine,endLine:d.endLine,leaf:d.leaf,tokens:[...g].sort()}),l=!0),g.size>0&&r.set(d.symbol,{symbol:d.symbol,file:d.relativePath,tokens:g})}l&&bI(e,i,a,c)}return t.map(i=>r.get(i.symbol)).filter(i=>!!i)}function gI(e,t,n,r,i){let o=We(e,t);return o.length===0?"":Lp(o,n,r,i)}function Lp(e,t,n,r){if(n>=t&&n-t<=12)return e.slice(t,n+1).join(`
541
- `);let i=[new RegExp(`\\bdef\\s+${Si(r)}\\b`),new RegExp(`\\bfun\\s+${Si(r)}\\b`),new RegExp(`\\bfn\\s+${Si(r)}\\b`),new RegExp(`\\bfunction\\s+${Si(r)}\\b`),new RegExp(`\\b${Si(r)}\\s*\\(`)],o=e.findIndex(s=>i.some(a=>a.test(s)));if(o>=0){let s=o;for(let a=o+1;a<e.length&&a<=o+8;a++){let c=e[a]??"";if(a>o&&xI(c)||(s=a,c.trim()===""&&a>o+1))break}return e.slice(o,s+1).join(`
560
+ AND d.relative_path IN (${r})
561
+ ORDER BY d.relative_path, der.start_line, der.end_line, gs.symbol`,...i))}return n}function Uf(e){let t=[];for(let n=0;n<e.length;n+=qf)t.push(e.slice(n,n+qf));return t}function YD(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 zf(e){return e.kind!==null&&e.kind!==0?ZD(e.kind,e.symbol,e.documentation):eE(e.symbol,e.documentation,e.enclosing_symbol)}function ZD(e,t,n){let i=(n??"").toLowerCase();if(se(t)==="type"){if(i.includes("type "))return Le.TypeAlias;if(i.includes("interface "))return Le.Interface;if(i.includes("struct "))return Le.Struct;if(i.includes("trait "))return Le.Trait;if(i.includes("class "))return Le.Class}return e}function eE(e,t,n){let i=Ie(e);if("kind"in i)return null;let r=i.descriptors,o=r[r.length-2]??null,s=se(e),a=(t??"").toLowerCase();return s==="type"?a.includes("type ")?Le.TypeAlias:a.includes("interface ")?Le.Interface:a.includes("struct ")?Le.Struct:a.includes("trait ")?Le.Trait:a.includes("class ")?Le.Class:Le.Class:s==="method"?o?.suffix==="type"?Le.Method:Le.Function:s==="namespace"?Le.Module:s!=="term"?null:a.includes("async def ")||a.includes("def ")?Le.Function:(n?se(n):o?.suffix??null)==="type"?Le.Field:Le.Variable}function sl(e,t={}){let{limit:n=10,scope:i,minDepth:r=3}=t,o=ye(e,i),s=new Map,a=[],c=new Map,l=new Map,d=new Set,u=[],m=0;for(let y of o.keys()){if(c.has(y))continue;let w=[],L=(o.get(y)??new Set).values();for(c.set(y,m),l.set(y,m),m+=1,u.push(y),d.add(y),w.push({node:y,iter:L,pendingChild:null});w.length>0;){let k=w[w.length-1];if(k.pendingChild!==null){let Y=k.pendingChild;k.pendingChild=null,l.set(k.node,Math.min(l.get(k.node),l.get(Y)))}let T=k.iter.next();if(T.done){if(l.get(k.node)===c.get(k.node)){let Y=[];for(;;){let ee=u.pop();if(d.delete(ee),Y.push(ee),s.set(ee,a.length),ee===k.node)break}a.push(Y)}w.pop();continue}let U=T.value;if(c.has(U))d.has(U)&&l.set(k.node,Math.min(l.get(k.node),c.get(U)));else{c.set(U,m),l.set(U,m),m+=1,u.push(U),d.add(U);let Y=(o.get(U)??new Set).values();k.pendingChild=U,w.push({node:U,iter:Y,pendingChild:null})}}}let p=new Map,f=new Array(a.length);for(let y=0;y<a.length;y++)f[y]=a[y].length,p.set(y,new Set);for(let[y,w]of o){let L=s.get(y);for(let k of w){let T=s.get(k);T!==L&&p.get(L).add(T)}}let g=new Array(a.length),b=new Array(a.length);for(let y=0;y<a.length;y++){let w=[],L=0;for(let k of p.get(y)){let T=b[k];T>L&&(L=T,w=g[k])}g[y]=[y,...w],b[y]=f[y]+L}function x(y){return g[y]}let S=a.map(y=>[...y].sort()),R=new Set,C=[];for(let y=0;y<a.length;y++){let w=x(y),L=[];for(let T of w)L.push(...S[T]);if(L.length<r)continue;let k=L.join(" ");R.has(k)||(R.add(k),C.push(tE(L)))}return C.sort((y,w)=>w.depth-y.depth),nE(C).slice(0,n)}function tE(e){return{chain:e,depth:e.length,actionTier:"signal",chainKind:"transitive-dependency-depth",evidenceReasons:[`${e.length} file(s) form the representative transitive dependency path`,"cycles are condensed before longest-path calculation"],recommendation:"Review whether the chain crosses ownership or layer boundaries; shorten it only when the dependency direction is accidental."}}function nE(e){let t=[];for(let n of e)t.some(i=>iE(n.chain,i.chain))||t.push(n);return t}function iE(e,t){if(e.length>=t.length)return!1;let n=t.length-e.length;for(let i=0;i<e.length;i++)if(e[i]!==t[n+i])return!1;return!0}function al(e,t){let n=q(e,t);if(!n)return[];let i=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
562
+ WHERE id = ? LIMIT 1`,n.symbolId);if(!i)return[];let r=[{symbol:i.symbol,shortName:v(i.symbol),depth:0}],o=i.enclosing_symbol,s=1,a=new Set([i.symbol]);for(;o&&!a.has(o)&&s<20;){a.add(o);let u=e.get("SELECT symbol, enclosing_symbol FROM global_symbols WHERE symbol = ?",o);if(!u)break;r.push({symbol:u.symbol,shortName:v(u.symbol),depth:s}),o=u.enclosing_symbol,s++}if(r.length>1)return r;let c=Ie(i.symbol);if("kind"in c)return r;let l=c.descriptors;if(l.length<=1)return r;let d=[r[0]];for(let u=l.length-2,m=1;u>=0;u--,m++){let f=l.slice(0,u+1).map(g=>g.suffix==="method"?`${g.name}()`:g.name.replace(/\.(ts|tsx|js|jsx|mjs|cjs|py|pyi|rs|java|scala|kt|kts|rb|go|cs|vb|dart|php|c|cc|cpp|cxx|h|hpp)$/,"")).join(":");d.push({symbol:f,shortName:f,depth:m})}return d}function Br(e,t,n={}){let i=q(e,t);if(!i)return null;let r=n.semantic!==!1,o=at(e,i,{limit:50,semantic:r}),s=Oi(Je(e,i,{limit:50,additive:!0,callableOnly:!0,semantic:r}));return{symbol:i.symbol,shortName:v(i.symbol),callers:o.map(a=>({symbol:a.symbol,shortName:v(a.symbol),file:a.file})),callees:s.map(a=>({symbol:a.symbol,shortName:v(a.symbol),file:a.file}))}}function ct(e,t){let n=new Set;for(let i of e)t.has(i)&&n.add(i);return n}function De(e,t){let n=new Set;for(let i of e)t.has(i)||n.add(i);return n}function bn(e,t){if(e.size===0&&t.size===0)return 0;let n=0;for(let r of e)t.has(r)&&(n+=1);let i=e.size+t.size-n;return i===0?0:n/i}function Wf(e,t){if(e.size===0)return 0;let n=0;for(let i of e)t.has(i)&&(n+=1);return n/e.size}function cl(e,t){if(t<=0)return new Map;let n=new Map;for(let[i,r]of e)r>0&&n.set(i,Math.log(t/r));return n}function Bi(e){let t=[...e.values()].sort((i,r)=>i-r);if(t.length===0)return 0;let n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function Hi(e,t){let n=0;for(let i of e){let r=t.get(i)??0;n+=r*r}return Math.sqrt(n)}function Gf(e,t,n,i={}){let r=0,o=0,s=0,a=i.medianIdf??Bi(n),c=[],l=[];for(let m of e){let p=n.get(m)??0;o+=p*p,t.has(m)&&(r+=p*p,p>=a?c.push(m):l.push(m))}if(c.length===0&&l.length===0)return{similarity:0,significantShared:[],trivialShared:[]};for(let m of t){let p=n.get(m)??0;s+=p*p}let d=Math.sqrt(o)*Math.sqrt(s),u=d>0?r/d:0;return c.sort((m,p)=>(n.get(p)??0)-(n.get(m)??0)),{similarity:u,significantShared:c,trivialShared:l}}function Kf(e,t,n,i){let r=0,o=i.medianIdf??Bi(n),s=[],a=[];for(let d of e){if(!t.has(d))continue;let u=n.get(d)??0;r+=u*u,u>=o?s.push(d):a.push(d)}if(s.length===0&&a.length===0)return{similarity:0,significantShared:[],trivialShared:[]};let c=i.magnitudeA*i.magnitudeB,l=c>0?r/c:0;return s.sort((d,u)=>(n.get(u)??0)-(n.get(d)??0)),{similarity:l,significantShared:s,trivialShared:a}}function Vr(e,t,n={}){let{minSimilarity:i=.4,limit:r=20}=n,o=dE(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!de(o.symbol))return[];if(o.callees.size===0)return Jf(e,t,{minSimilarity:i,limit:r,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"});let s=rE(e,o,i,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,r):Jf(e,t,{minSimilarity:i,limit:r,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"})}function rE(e,t,n,i){let r=Vi(e).calleeIndex({minCallees:3,scanLimit:i.scanLimit,semantic:i.semantic}),o=hE(t,r),s=oE(t,r),a=Bi(s),c=Hi(t.callees,s),l=[];for(let d of o){if(d.callees.size<3)continue;let u=Hi(d.callees,s),m=Zf(t,d,s,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0,medianIdf:a,magnitudeA:c,magnitudeB:u});m&&l.push(m)}return l.sort((d,u)=>u.similarity-d.similarity),l}function oE(e,t){let n=new Map(t.docFreq);for(let i of e.callees)n.set(i,(n.get(i)??0)+1);return cl(n,t.corpus.length+1)}function Zf(e,t,n,i){let r=aE(e,t,n,i);if(!cE(r,i))return null;let{similarity:o,significantShared:s,trivialShared:a}=r,c=s.length>0?s:a,l=ig(c,"callees");return{symbolA:e.symbol,shortNameA:v(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:v(t.symbol),fileB:t.file,similarity:o,similarityBasis:"callees",sharedCallees:c.map(v),uniqueToA:[...De(e.callees,t.callees)].map(v),uniqueToB:[...De(t.callees,e.callees)].map(v),...l}}function sE(e,t,n,i){let r=i.magnitudeA??Hi(e.callees,n),o=i.magnitudeB??Hi(t.callees,n),s=0,a=0,c=0,l=i.medianIdf??Bi(n);for(let m of e.callees){if(!t.callees.has(m))continue;let p=n.get(m)??0;s+=p*p,c+=1,p>=l&&(a+=1)}if(c===0)return!1;let d=r*o;return(d>0?s/d:0)<i.minSimilarity?!1:a>=i.requireSignificantShared||c>=i.requireSharedCount}function aE(e,t,n,i){return i.magnitudeA===void 0||i.magnitudeB===void 0?Gf(e.callees,t.callees,n,{medianIdf:i.medianIdf}):Kf(e.callees,t.callees,n,{medianIdf:i.medianIdf,magnitudeA:i.magnitudeA,magnitudeB:i.magnitudeB})}function cE(e,t){if(e.similarity<t.minSimilarity)return!1;let n=e.significantShared.length+e.trivialShared.length;return e.significantShared.length>=t.requireSignificantShared||n>=t.requireSharedCount}function Wn(e,t={}){let{minSimilarity:n=.5,limit:i=20,scope:r,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=t.semantic!==!1,l=me(),d=0,u=0,m=0,p=0,f=0,g=0,b=0;return D("similar.all",()=>{let S=Vi(e).calleeIndex({minCallees:o,scope:r,scanLimit:a,semantic:c}),R=S.corpus;d=R.length;let C=t.focusFiles,y=[],w=0;return D("similar.all.pair-scan",()=>{for(let L=0;L<R.length;L+=1){let k=R[L],T=C?.has(k.file)??!1,U=S.weightedMagnitudes[L],Y=new Set;for(let ee of k.callees){let we=S.candidateIndexesByCallee.get(ee);if(we)for(let te of we)te<=L||C&&!T&&!C.has(R[te].file)||Y.add(te)}l&&(m+=Y.size,Y.size>0&&(u+=1));for(let ee of Y){let we=R[ee];if(s&&k.file===we.file){l&&(f+=1);continue}if(eg(k,we)){l&&(g+=1);continue}l&&(p+=1);let te=Zf(k,we,S.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:S.medianIdf,magnitudeA:U,magnitudeB:S.weightedMagnitudes[ee]});te&&(lE(y,te,i,w),l&&(b+=1),w+=1)}}},()=>({corpusSize:d,candidateSets:u,candidatePairs:m,comparedPairs:p,crossFileSkips:f,signatureSkips:g,insertedResults:b,topResults:y.length})),D("similar.all.sort-project",()=>(y.sort((L,k)=>k.result.similarity-L.result.similarity||L.order-k.order),y.map(L=>L.result)),()=>({topResults:y.length}))},()=>({minSimilarity:n,limit:i,scope:r,minCallees:o,crossFileOnly:s,scanLimit:a,semantic:c,corpusSize:d,candidateSets:u,candidatePairs:m,comparedPairs:p,crossFileSkips:f,signatureSkips:g,insertedResults:b}))}function ml(e,t={}){let{minSimilarity:n=.5,scope:i,minCallees:r=4,crossFileOnly:o=!1,scanLimit:s}=t,a=t.semantic!==!1,c=me(),l=0,d=0,u=0,m=0,p=0,f=0,g=0;return D("similar.all-count",()=>{let x=Vi(e).calleeIndex({minCallees:r,scope:i,scanLimit:s,semantic:a}),S=x.corpus;l=S.length;let R=t.focusFiles;return D("similar.all-count.pair-scan",()=>{for(let C=0;C<S.length;C+=1){let y=S[C],w=R?.has(y.file)??!1,L=x.weightedMagnitudes[C],k=new Set;for(let T of y.callees){let U=x.candidateIndexesByCallee.get(T);if(U)for(let Y of U)Y<=C||R&&!w&&!R.has(S[Y].file)||k.add(Y)}c&&(u+=k.size,k.size>0&&(d+=1));for(let T of k){let U=S[T];if(o&&y.file===U.file){c&&(p+=1);continue}if(eg(y,U)){c&&(f+=1);continue}c&&(m+=1),sE(y,U,x.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:x.medianIdf,magnitudeA:L,magnitudeB:x.weightedMagnitudes[T]})&&(g+=1)}}},()=>({corpusSize:l,candidateSets:d,candidatePairs:u,comparedPairs:m,crossFileSkips:p,signatureSkips:f,insertedResults:g})),g},()=>({minSimilarity:n,scope:i,minCallees:r,crossFileOnly:o,scanLimit:s,semantic:a,corpusSize:l,candidateSets:d,candidatePairs:u,comparedPairs:m,crossFileSkips:p,signatureSkips:f,insertedResults:g}))}function eg(e,t){if(e.paramCount<0||t.paramCount<0)return!1;let n=Math.abs(e.paramCount-t.paramCount),i=Math.max(2,Math.ceil(Math.max(e.paramCount,t.paramCount)*.5));return n>i}var tg=pe({kind:"source-fingerprints",serialize:$E,deserialize:ME});function lE(e,t,n,i){if(n<=0)return;if(e.length<n){e.push({result:t,order:i});return}let r=0;for(let s=1;s<e.length;s+=1){let a=e[s],c=e[r];(a.result.similarity<c.result.similarity||a.result.similarity===c.result.similarity&&a.order>c.order)&&(r=s)}let o=e[r];t.similarity<=o.result.similarity||(e[r]={result:t,order:i})}var uE=["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 dE(e,t,n){let i=q(e,t);if(!i||!de(i.symbol))return null;let r=new A(e),o=Je(e,i,{semantic:n.semantic});return{symbol:i.symbol,file:i.relativePath,callees:ws(o.map(s=>s.symbol)),paramCount:r.callableSignature(i)?.paramCount??-1}}var mE=ie("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),pE=ie("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function ng(e,t){let{minCallees:n,scope:i,excludeSymbol:r,scanLimit:o}=t,s=t.semantic!==!1,a=mE.get(e,()=>new Map),c=`${n}|${i??""}|${o??""}|${s}`,l=!0,d=0,u=0;return D("similar.callee-fingerprints.resolve",()=>{let m=a.get(c);if(l=m!==void 0,m||(m=yE(e,{minCallees:n,scope:i,scanLimit:o,semantic:s}),a.set(c,m)),d=m.length,r===void 0)return m;let p=m.filter(f=>f.symbol!==r);return u=m.length-p.length,p},()=>({minCallees:n,scope:i,scanLimit:o,semantic:s,cacheHit:l,corpusSize:d,excludeSymbol:r!==void 0,excludedSymbols:u}))}function fE(e,t){let{minCallees:n,scope:i,scanLimit:r}=t,o=t.semantic!==!1,s=pE.get(e,()=>new Map),a=`${n}|${i??""}|${r??""}|${o}`,c=!0,l=0,d=0,u=0;return D("similar.callee-index.resolve",()=>{let m=s.get(a);return c=m!==void 0,m||(m=gE(ng(e,{minCallees:n,scope:i,scanLimit:r,semantic:o})),s.set(a,m)),l=m.corpus.length,d=m.docFreq.size,u=m.candidateIndexesByCallee.size,m},()=>({minCallees:n,scope:i,scanLimit:r,semantic:o,cacheHit:c,corpusSize:l,indexedCallees:d,candidateBuckets:u}))}function Vi(e){return{calleeCorpus:t=>ng(e,t),calleeIndex:t=>fE(e,t),sourceCorpus:(t={})=>cg(e,t),sourceIndex:(t={})=>Yf(e,t),sourceCandidates:(t,n)=>(n.candidateMode??"full")==="target-pruned"?LE(e,t,{minSimilarity:n.minSimilarity,scanLimit:n.scanLimit}):IE(t,Yf(e,{scanLimit:n.scanLimit}))}}function gE(e){let t=me(),n=0,i=D("similar.callee-index.doc-frequency",()=>{let m=new Map;for(let p of e)for(let f of p.callees)m.set(f,(m.get(f)??0)+1);return n=m.size,m},()=>({corpusSize:e.length,uniqueCallees:n})),r=Math.max(8,Math.ceil(Math.sqrt(e.length))),o=D("similar.callee-index.idf-weights",()=>cl(i,e.length),()=>({corpusSize:e.length,uniqueCallees:i.size})),s=D("similar.callee-index.weighted-magnitudes",()=>e.map(m=>Hi(m.callees,o)),()=>({corpusSize:e.length})),a=0,c=0,l=0,d=D("similar.callee-index.candidate-buckets",()=>{let m=new Map;for(let p=0;p<e.length;p+=1){let f=e[p];for(let g of f.callees){if((i.get(g)??0)>r){t&&(c+=1);continue}let b=m.get(g);b||(b=[],m.set(g,b)),b.push(p),t&&(a+=1)}}return t&&(l=m.size),m},()=>({corpusSize:e.length,buckets:l,candidateRefs:a,ubiquitousSkips:c,ubiquityThreshold:r})),u=D("similar.callee-index.median-idf",()=>Bi(o),()=>({uniqueCallees:o.size}));return{corpus:e,candidateIndexesByCallee:d,docFreq:i,idfWeights:o,weightedMagnitudes:s,medianIdf:u,ubiquityThreshold:r}}function hE(e,t){let n=new Map;for(let i of e.callees)for(let r of t.candidateIndexesByCallee.get(i)??[]){let o=t.corpus[r];o.symbol!==e.symbol&&n.set(o.symbol,o)}return n.size>0?[...n.values()]:t.corpus.filter(i=>i.symbol!==e.symbol)}function yE(e,t){let{minCallees:n,scope:i,scanLimit:r,semantic:o}=t,s=me(),a=new A(e),c=0,l=D("similar.callee-fingerprints.candidates",()=>{let f=qe(a.productionCallableDefinitions({scope:i,minLoc:5,sortByLocDesc:typeof r=="number"&&r>0}),r);return c=f.length,f},()=>({scope:i,scanLimit:r,candidateCount:c})),d=0,u=D("similar.callee-fingerprints.callee-map",()=>{let f=a.calleeMap(l,{semantic:o});if(s)for(let g of f.values())d+=g.length;return f},()=>({candidateCount:c,semantic:o,calleeEdges:d})),m=0,p=0;return D("similar.callee-fingerprints.shape",()=>{let f=l.map(g=>({symbol:g.symbol,file:g.relativePath,callees:ws((u.get(g.symbolId)??[]).map(b=>b.symbol)),paramCount:a.callableSignature(g)?.paramCount??-1})).filter(g=>g.callees.size>=n);return m=f.length,s&&(p=f.reduce((g,b)=>g+b.callees.size,0)),f},()=>({candidateCount:c,fingerprintCount:m,retainedCalleeCount:p,minCallees:n}))}function ws(e){return new Set([...e].filter(t=>!bE(t)))}function bE(e){return uE.some(t=>e.includes(t))}function Jf(e,t,n){let i=vE(e,t);if(!i||i.tokens.size<3)return[];let r=n.minSimilarity>=.5?n.minSimilarity:.3,o=[],s=n.candidateMode??"full",a=0,c=0,l=0,d=0;return D("similar.source-shape",()=>{let m=Vi(e).sourceCandidates(i,{minSimilarity:r,scanLimit:n.scanLimit,candidateMode:s});a=m.length;for(let p of m){if(p.symbol===i.symbol||p.tokens.size<3)continue;c+=1;let f=ct(i.tokens,p.tokens);if(f.size<2){l+=1;continue}let g=new Set([...i.tokens,...p.tokens]),b=g.size>0?f.size/g.size:0;if(b<r){d+=1;continue}o.push({symbolA:i.symbol,shortNameA:v(i.symbol),fileA:i.file,symbolB:p.symbol,shortNameB:v(p.symbol),fileB:p.file,similarity:b,similarityBasis:"source-tokens",sharedCallees:[...f].sort(),uniqueToA:[...De(i.tokens,p.tokens)].sort(),uniqueToB:[...De(p.tokens,i.tokens)].sort(),...ig([...f],"source-tokens")})}return o.sort((p,f)=>f.similarity-p.similarity||p.shortNameB.localeCompare(f.shortNameB)),o.slice(0,n.limit)},()=>({symbol:i.symbol,file:i.file,targetTokens:i.tokens.size,candidateMode:s,candidates:a,comparedPairs:c,sharedSkips:l,similaritySkips:d,results:o.length}))}function ig(e,t){let n=e.flatMap(ul),i=e.flatMap(b=>Xf(b,t)),r=ll(n,rg),o=ll(n,og),s=ll(i,dl),a=[...new Set(i.filter(Qf))],c=e.filter(b=>{let x=Xf(b,t);return x.some(S=>dl.has(S))&&x.some(Qf)}).length,l=[];r.length>0&&l.push(`access/query scaffolding: ${r.slice(0,5).join(", ")}`),o.length>0&&l.push(`framework/generic scaffolding: ${o.slice(0,5).join(", ")}`),s.length>0&&l.push(`domain behavior verbs: ${s.slice(0,5).join(", ")}`),s.length>0&&a.length>0&&l.push(`domain-specific terms: ${a.slice(0,5).join(", ")}`);let d=t==="source-tokens"&&n.length>0&&n.every(b=>sg.has(b));d&&l.push("shared source tokens are generic scaffolding");let u=s.length>0&&a.length>0,m=r.length+o.length>0,p=t==="callees"&&u&&e.length>=4&&a.length>=4&&c>=2,f=p?"domain-behavior":u?m?"mixed":"domain-behavior":r.length>0?"access-query-scaffolding":o.length>0||d?"framework-scaffolding":"structural-overlap";f==="structural-overlap"&&e.length>0&&l.push(`shared ${t} overlap has no recognized domain or scaffolding category`);let g=f==="domain-behavior"&&(e.length>=3||p)?"direct":"signal";return{evidenceClass:f,actionTier:g,evidenceClassReasons:l,recommendation:SE(f,g)}}function SE(e,t){return t==="direct"?"Shared domain behavior looks concrete; review for an extract/reuse opportunity.":e==="mixed"?"Shared evidence mixes domain behavior with scaffolding; review semantics before extracting anything.":e==="access-query-scaffolding"?"Shared evidence is mostly access/query scaffolding; compare product semantics before reusing code.":e==="structural-overlap"?"Shared structure has no domain or scaffolding classification; inspect names and behavior before reusing code.":"Shared evidence is mostly framework or generic scaffolding; treat as a contextual signal."}function ll(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function ul(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function Xf(e,t){if(t==="source-tokens")return ul(e);let n=$(e);return ul(n.length>0?n:xE(e))}function xE(e){return e.replace(/[()`]/g," ").replace(/\.[a-z][a-z0-9]+(?=\s|$)/gi," ").split(/[:/\\\s]+/).map(i=>i.trim()).filter(i=>/[A-Za-z]/.test(i)).at(-1)?.replace(/\.$/,"")??e}function Qf(e){return e.length>3&&!dl.has(e)&&!rg.has(e)&&!og.has(e)&&!sg.has(e)&&!CE.has(e)}var dl=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),rg=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),og=new Set(["bytes","computed","crypto","describe","effect","expect","fetch","filter","hex","hook","json","map","mounted","on","promise","random","react","reduce","ref","render","state","test","token","trim","uuid","vue","watch"]),sg=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),CE=new Set(["best","backend","conflict","database","effect","effects","error","errors","frontend","found","helpers","javascript","module","modules","scip","shared","source","typescript","utils","with","workflow","workflows"]);function vE(e,t){let n=q(e,t);if(!n||!de(n.symbol))return null;let i=RE(e,n);return i?{symbol:n.symbol,file:n.relativePath,tokens:i}:null}function RE(e,t){let n=$(t.symbol),i=TE(e,t.relativePath,t.startLine,t.endLine,n),r=dg(i,n);return r.size>0?r:null}var kE=ie("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),wE=ie("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function ag(e){return`${e.scanLimit??""}`}function cg(e,t={}){let n=kE.get(e,()=>new Map),i=ag(t),r=n.get(i);return r||(r=FE(e,t),n.set(i,r)),r}function Yf(e,t={}){let n=wE.get(e,()=>new Map),i=ag(t),r=n.get(i);return r||(r=PE(cg(e,t)),n.set(i,r)),r}function PE(e){let t=new Map;for(let r of e)for(let o of r.tokens)t.set(o,(t.get(o)??0)+1);let n=Math.max(8,Math.ceil(Math.sqrt(e.length))),i=new Map;for(let r of e)for(let o of r.tokens){if((t.get(o)??0)>n)continue;let s=i.get(o);s||(s=[],i.set(o,s)),s.push(r)}return{corpus:e,candidateByToken:i,docFreq:t,ubiquityThreshold:n}}function IE(e,t){let n=new Map;for(let i of e.tokens)for(let r of t.candidateByToken.get(i)??[])r.symbol!==e.symbol&&n.set(r.symbol,r);return n.size>0?[...n.values()]:t.corpus.filter(i=>i.symbol!==e.symbol)}function LE(e,t,n){let i=me(),r=new A(e),o=DE(t.tokens.size,n.minSimilarity),s=0,a=0,c=0,l=D("similar.source-shape.target-files",()=>{let f=[...t.tokens],g=[];for(let b of O(e,{includeIgnored:!1})){s+=1;let x=M(e,b);x&&(a+=1,EE(x,f,o)&&g.push(b))}return c=g.length,g},()=>({symbol:t.symbol,targetTokens:t.tokens.size,requiredSharedTokens:o,scannedFiles:s,readableFiles:a,candidateFiles:c})),d=0,u=D("similar.source-shape.target-definitions",()=>{let f=qe(r.productionCallableDefinitions({files:l,sortByLocDesc:typeof n.scanLimit=="number"&&n.scanLimit>0}),n.scanLimit);return d=f.length,f},()=>({symbol:t.symbol,candidateFiles:c,scanLimit:n.scanLimit,definitionCount:d})),m=0;return D("similar.source-shape.target-fingerprints",()=>{let f=lg(e,u);return i&&(m=f.length),f},()=>({symbol:t.symbol,definitionCount:d,fingerprintCount:m})).filter(f=>f.symbol!==t.symbol)}function DE(e,t){return Math.max(2,Math.ceil(e*t))}function EE(e,t,n){if(t.length<n)return!1;let i=e.toLowerCase(),r=0;for(let o of t)if(NE(i,o)&&(r+=1,r>=n))return!0;return!1}function NE(e,t){return t==="num"?/\b\d+\b/.test(e):e.includes(t)}function FE(e,t={}){let n=new A(e),{scanLimit:i}=t,r=qe(n.productionCallableDefinitions({sortByLocDesc:typeof i=="number"&&i>0}),i);return lg(e,r)}function lg(e,t){let n=new Map;for(let r of t){let o=n.get(r.relativePath)??[];o.push(r),n.set(r.relativePath,o)}let i=new Map;for(let[r,o]of n){let s=M(e,r);if(!s)continue;let a=re(e,r,s),c=AE(e,r,a),l=!1,d=null;for(let u of o){let m=_E(u),p=c.get(m),f=p?new Set(p.tokens):null;f||(d??=Ye(e,r),f=dg(ug(d,u.startLine,u.endLine,u.leaf),u.leaf),c.set(m,{key:m,symbol:u.symbol,startLine:u.startLine,endLine:u.endLine,leaf:u.leaf,tokens:[...f].sort()}),l=!0),f.size>0&&i.set(u.symbol,{symbol:u.symbol,file:u.relativePath,tokens:f})}l&&jE(e,r,a,c)}return t.map(r=>i.get(r.symbol)).filter(r=>!!r)}function TE(e,t,n,i,r){let o=Ye(e,t);return o.length===0?"":ug(o,n,i,r)}function ug(e,t,n,i){if(n>=t&&n-t<=12)return e.slice(t,n+1).join(`
563
+ `);let r=[new RegExp(`\\bdef\\s+${Hr(i)}\\b`),new RegExp(`\\bfun\\s+${Hr(i)}\\b`),new RegExp(`\\bfn\\s+${Hr(i)}\\b`),new RegExp(`\\bfunction\\s+${Hr(i)}\\b`),new RegExp(`\\b${Hr(i)}\\s*\\(`)],o=e.findIndex(s=>r.some(a=>a.test(s)));if(o>=0){let s=o;for(let a=o+1;a<e.length&&a<=o+8;a++){let c=e[a]??"";if(a>o&&BE(c)||(s=a,c.trim()===""&&a>o+1))break}return e.slice(o,s+1).join(`
542
564
  `)}return e.slice(t,Math.min(e.length,t+8)).join(`
543
- `)}function hI(e){return`${e.symbol}\0${e.startLine}\0${e.endLine}\0${e.leaf}`}function yI(e,t,n){let r=te(e,"source-fingerprints",t,n);if(!r)return new Map;try{let i=JSON.parse(r);if(!Array.isArray(i.entries))return new Map;let o=new Map;for(let s of i.entries){if(!s||typeof s.key!="string"||typeof s.symbol!="string"||typeof s.startLine!="number"||typeof s.endLine!="number"||typeof s.leaf!="string"||!Array.isArray(s.tokens)||!s.tokens.every(a=>typeof a=="string"))return new Map;o.set(s.key,s)}return o}catch{return new Map}}function bI(e,t,n,r){let i={entries:[...r.values()].sort((o,s)=>o.key.localeCompare(s.key))};ne(e,"source-fingerprints",t,n,JSON.stringify(i))}function Ip(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=SI(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 SI(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 xI(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function Si(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yt(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||e.focusFiles&&!e.focusFiles.has(n.file)&&!e.focusFiles.has(r.file))continue;let i=e.compare(n,r);i&&t.push(i)}}else{if(e.focusFiles?.size===0)return[];let n=e.focusFiles?e.profiles.map((i,o)=>e.focusFiles.has(i.file)?o:-1).filter(i=>i>=0):[],r=typeof e.overrunFactor=="number"&&Number.isFinite(e.limit)?e.limit*e.overrunFactor:Number.POSITIVE_INFINITY;for(let i=0;i<e.profiles.length;i+=1){let o=e.profiles[i];if(e.focusFiles&&!e.focusFiles.has(o.file))for(let s of n){if(s<=i)continue;let a=e.compare(o,e.profiles[s]);a&&t.push(a)}else for(let s=i+1;s<e.profiles.length;s+=1){let a=e.compare(o,e.profiles[s]);a&&t.push(a)}if(t.length>r)break}}return t.sort(e.sort??((n,r)=>r.similarity-n.similarity)),t.slice(0,e.limit)}function Cc(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=CI(e,{scope:i,minDeps:s});return yt({profiles:a,limit:r,filePattern:o,overrunFactor:5,compare:(l,u)=>RI(l,u,n,c)})}function CI(e,t){let{scope:n,minDeps:r}=t,i=ce(e,n),{universalDeps:o,distinctiveDeps:s}=vI(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 vI(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 RI(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=Zt(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 Qo(e){let t=[],n=[],r=[];for(let l of e.primitiveGroups)l.values.length!==0&&Dp(l.bucket,n,r).push(`${l.reasonPrefix}: ${l.values.join(", ")}`);for(let l of e.nameGroups)kI(l.names,l.label,e.genericWords,e.stripPrefixes??[],t,Dp(l.fallbackBucket,n,r));let i=t.length>0,o=n.length>0,s=r.length>0,a=i?o||s?"mixed":"domain-behavior":s?"shared-abstraction":"generic-workflow-scaffolding";return{actionTier:a==="domain-behavior"||a==="mixed"?"signal":"support",evidenceClass:a,reasons:[...t,...r,...n].slice(0,6),recommendation:e.recommendation(a)}}function Yo(e,t){if(e.size===0||t.size===0)return 0;let r=Ye(e,t).size/Math.min(e.size,t.size);return Math.max(Zt(e,t),r)}function V(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function ke(e){return[...e].sort()}function kI(e,t,n,r,i,o){let s=[],a=[];for(let c of e)wI(c,r).filter(u=>!n.has(u)).length>0?s.push(c):a.push(c);s.length&&i.push(`${t} has domain term(s): ${s.slice(0,6).join(", ")}`),a.length&&o.push(`${t} is generic workflow: ${a.slice(0,6).join(", ")}`)}function wI(e,t){let n=e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2");for(let r of t)n=n.replace(r,"");return n.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function Dp(e,t,n){return e==="generic"?t:n}function Dn(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=ar(e,{scope:o,minJsxTokens:r,scanLimit:s}).filter(u=>u.kind==="component").map(u=>({file:u.file,component:u.name,tokens:u.jsxTokens,profile:u}));return yt({profiles:l,limit:i,filePattern:a,focusFiles:c,compare:(u,d)=>LI(u,d,n),sort:(u,d)=>d.similarity-u.similarity||u.fileA.localeCompare(d.fileA)||u.componentA.localeCompare(d.componentA)||u.fileB.localeCompare(d.fileB)||u.componentB.localeCompare(d.componentB)})}function LI(e,t,n){let r=Ye(e.tokens,t.tokens);if(r.size<6||!II(r))return null;let i=Zt(e.tokens,t.tokens);return i<n?null:{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:i,sharedTokens:ke(r),sharedComponents:V(r,"component:"),sharedNativeTags:V(r,"native:"),sharedProps:V(r,"prop:"),sharedEvents:V(r,"event:"),sharedBindings:V(r,"binding:"),uniqueToA:ke(Ce(e.tokens,t.tokens)).slice(0,25),uniqueToB:ke(Ce(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function II(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 Pn(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=ar(e,{scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(u=>({file:u.file,component:u.name,tokens:u.behaviorTokens,profile:u}));return yt({profiles:l,limit:i,filePattern:a,focusFiles:c,compare:(u,d)=>DI(u,d,n,r),sort:(u,d)=>d.similarity-u.similarity||u.fileA.localeCompare(d.fileA)||u.componentA.localeCompare(d.componentA)||u.fileB.localeCompare(d.fileB)||u.componentB.localeCompare(d.componentB)})}function DI(e,t,n,r){let i=Ye(e.tokens,t.tokens);if(i.size<r||!EI(i))return null;let o=Yo(e.tokens,t.tokens);if(o<n)return null;let s=V(i,"hook:"),a=V(i,"react-hook:"),c=V(i,"effect:"),l=V(i,"state:"),u=V(i,"request:"),d=V(i,"handler:"),m=V(i,"handler-verb:"),p=PI({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:o,sharedTokens:ke(i),sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m,evidenceClass:p.evidenceClass,actionTier:p.actionTier,evidenceClassReasons:p.reasons,recommendation:p.recommendation,uniqueToA:ke(Ce(e.tokens,t.tokens)).slice(0,25),uniqueToB:ke(Ce(t.tokens,e.tokens)).slice(0,25),reason:TI({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m}),locA:e.profile.loc,locB:t.profile.loc}}function PI(e){return Qo({genericWords:_I,stripPrefixes:FI,primitiveGroups:[{values:e.sharedReactHooks,reasonPrefix:"shared React primitives",bucket:"generic"},{values:e.sharedEffects,reasonPrefix:"shared lifecycle primitive",bucket:"generic"}],nameGroups:[{names:e.sharedHooks,label:"shared hook",fallbackBucket:"shared-abstraction"},{names:e.sharedRequests,label:"shared request",fallbackBucket:"generic"},{names:e.sharedState,label:"shared state",fallbackBucket:"generic"},{names:e.sharedHandlers,label:"shared handler",fallbackBucket:"generic"},{names:e.sharedHandlerVerbs,label:"shared action verb",fallbackBucket:"generic"}],recommendation:NI})}function NI(e){switch(e){case"domain-behavior":return"Review for a shared hook, controller, or feature module around the named domain behavior.";case"mixed":return"Separate generic React mechanics from domain-specific behavior before extracting a shared hook.";case"shared-abstraction":return"Review the existing shared hook usage first; extract only if duplicated behavior remains outside it.";case"generic-workflow-scaffolding":return"Treat as support evidence for a repeated workflow shape, not direct hook-extraction evidence."}}function EI(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 TI(e){let t=[];return e.sharedHooks.length&&t.push(`shared hooks: ${e.sharedHooks.join(", ")}`),e.sharedReactHooks.length&&t.push(`shared React hooks: ${e.sharedReactHooks.join(", ")}`),e.sharedEffects.length&&t.push(`shared effects: ${e.sharedEffects.join(", ")}`),e.sharedState.length&&t.push(`shared state: ${e.sharedState.join(", ")}`),e.sharedRequests.length&&t.push(`shared requests: ${e.sharedRequests.join(", ")}`),e.sharedHandlers.length&&t.push(`shared handlers: ${e.sharedHandlers.slice(0,6).join(", ")}`),e.sharedHandlerVerbs.length&&t.push(`shared action verbs: ${e.sharedHandlerVerbs.slice(0,6).join(", ")}`),t.join("; ")||"shared React behavior profile"}var _I=new Set(["add","apply","async","callback","cancel","change","clear","close","create","data","delete","draft","edit","effect","error","fetch","filter","form","handle","has","is","item","items","load","loader","loading","memo","name","open","reducer","refresh","ref","remove","request","reset","resource","row","rows","save","saving","search","select","selected","state","store","submit","toggle","update","use","value"]),FI=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function Ci(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 ar(e,{scope:a,scanLimit:c}).filter(d=>d.kind==="component").filter(d=>!l||d.file.includes(l)||d.name.includes(l)).map(d=>AI(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 AI(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));if(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)return null;let i=$I(e),o=MI(e,t,i),s=OI(e),a=jI(i,o,s);return{file:e.file,component:e.name,componentLines:e.loc,fileLines:e.fileLines,jsxTokens:e.jsxTokens.size,behaviorTokens:e.behaviorTokens.size,dominantPressure:i,pressureKinds:o,contextKind:s,recommendationKind:a,recommendation:BI(a,s),reasons:n,loc:e.loc}}function $I(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 MI(e,t,n){let r=[];e.loc>=t.minComponentLines&&r.push("component");let i=Math.max(80,Math.floor(t.minComponentLines/2));return e.fileLines>=t.minFileLines&&e.loc>=i&&r.push("file"),e.jsxTokens.size>=t.minJsxTokens&&r.push("jsx-structure"),e.behaviorTokens.size>=t.minBehaviorTokens&&r.push("hook-behavior"),[...new Set(r.length>0?r:[n])]}function OI(e){let t=e.file.split(/[\\/]+/).filter(Boolean),n=t.slice(0,-1).map(l=>l.toLowerCase()),r=(t.at(-1)??e.name).replace(/\.[^.]+$/,""),i=`${r} ${e.name}`.split(/[^A-Za-z0-9]+/).filter(Boolean).map(l=>l.toLowerCase()),o=n.findIndex(l=>VI.has(l)),s=o>=0&&n.slice(o+1).some(l=>HI.has(l)),a=Pp(r)||Pp(e.name);return/(?:Page|Route|Screen|View)$/.test(r)||/(?:Page|Route|Screen|View)$/.test(e.name)||i.some(l=>qI.has(l))||o>=0&&!s&&!a?"route-page":"component"}function Pp(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&Np.has(t.at(-1))?!0:[...Np].some(n=>e.endsWith(UI(n)))}function jI(e,t,n){return e==="hook-behavior"?"behavior-extraction":n==="route-page"?"route-page-decomposition":t.includes("hook-behavior")?"behavior-extraction":t.includes("jsx-structure")?"jsx-decomposition":t.includes("file")?"file-decomposition":e==="jsx-structure"?"jsx-decomposition":e==="file"&&!t.includes("component")?"file-decomposition":"component-decomposition"}function BI(e,t){switch(e){case"behavior-extraction":return"Extract independent state, effects, requests, or handlers into hooks, controllers, or feature modules.";case"route-page-decomposition":return"Split route/page orchestration from reusable panels and feature controllers.";case"jsx-decomposition":return t==="route-page"?"Split page JSX into named layout sections before extracting behavior.":"Split repeated JSX sections into named presentational components.";case"file-decomposition":return"Review file-level decomposition; split colocated panels or helpers before changing behavior.";case"component-decomposition":return"Review component boundaries around props, state ownership, and independently changing UI sections."}}var HI=new Set(["component","components","panel","panels","partial","partials"]),Np=new Set(["banner","button","card","dialog","drawer","filter","form","grid","header","item","list","menu","modal","nav","panel","picker","rail","row","section","selector","shell","sidebar","table","toolbar"]),VI=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),qI=new Set(["landing","page","route","screen","view"]);function UI(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Nn(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=WI(e,{scope:o,minTokens:r,scanLimit:s});return yt({profiles:l,limit:i,filePattern:a,focusFiles:c,compare:(u,d)=>zI(u,d,n),sort:(u,d)=>d.similarity-u.similarity||u.fileA.localeCompare(d.fileA)||u.fileB.localeCompare(d.fileB)})}function WI(e,t){return sr(e,{scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:GI(n)}))}function GI(e){return e.totalLines}function zI(e,t,n){let r=Ye(e.tokens,t.tokens);if(r.size<6||!JI(r))return null;let i=Zt(e.tokens,t.tokens);return i<n?null:{fileA:e.file,fileB:t.file,similarity:i,sharedTokens:ke(r),sharedComponents:V(r,"component:"),sharedProps:V(r,"prop:"),sharedEvents:V(r,"event:"),sharedDirectives:V(r,"directive:"),sharedSlots:V(r,"slot:"),sharedIdentifiers:V(r,"id:"),uniqueToA:ke(Ce(e.tokens,t.tokens)).slice(0,25),uniqueToB:ke(Ce(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function JI(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 En(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=sr(e,{scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(u=>({file:u.file,tokens:u.behaviorTokens,profile:u}));return yt({profiles:l,limit:i,filePattern:a,focusFiles:c,compare:(u,d)=>KI(u,d,n,r),sort:(u,d)=>d.similarity-u.similarity||u.fileA.localeCompare(d.fileA)||u.fileB.localeCompare(d.fileB)})}function KI(e,t,n,r){let i=Ye(e.tokens,t.tokens);if(i.size<r||!YI(i))return null;let o=Yo(e.tokens,t.tokens);if(o<n)return null;let s=V(i,"composable:"),a=V(i,"store:"),c=V(i,"reactivity:"),l=V(i,"lifecycle:"),u=V(i,"request:"),d=V(i,"function:"),m=V(i,"function-verb:"),p=V(i,"template-binding:"),g=V(i,"template-event:"),y=XI({sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p,sharedTemplateEvents:g});return{fileA:e.file,fileB:t.file,similarity:o,sharedTokens:ke(i),sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p,sharedTemplateEvents:g,evidenceClass:y.evidenceClass,actionTier:y.actionTier,evidenceClassReasons:y.reasons,recommendation:y.recommendation,uniqueToA:ke(Ce(e.tokens,t.tokens)).slice(0,25),uniqueToB:ke(Ce(t.tokens,e.tokens)).slice(0,25),reason:ZI({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:l,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function XI(e){return Qo({genericWords:eD,primitiveGroups:[{values:e.sharedReactivity,reasonPrefix:"shared reactivity primitive",bucket:"generic"},{values:e.sharedLifecycle,reasonPrefix:"shared lifecycle primitive",bucket:"generic"}],nameGroups:[{names:e.sharedComposables,label:"shared composable",fallbackBucket:"shared-abstraction"},{names:e.sharedStores,label:"shared store",fallbackBucket:"shared-abstraction"},{names:e.sharedRequests,label:"shared request",fallbackBucket:"generic"},{names:e.sharedFunctions,label:"shared function",fallbackBucket:"generic"},{names:e.sharedFunctionVerbs,label:"shared action verb",fallbackBucket:"generic"},{names:e.sharedBindings,label:"shared binding",fallbackBucket:"generic"},{names:e.sharedTemplateEvents,label:"shared template event",fallbackBucket:"generic"}],recommendation:QI})}function QI(e){switch(e){case"domain-behavior":return"Review for a shared composable, store, or feature module around the named domain behavior.";case"mixed":return"Separate generic Vue mechanics from domain-specific behavior before extracting a composable.";case"shared-abstraction":return"Review the existing composable/store usage first; extract only if duplicated behavior remains outside it.";case"generic-workflow-scaffolding":return"Treat as support evidence for a repeated workflow shape, not direct composable-extraction evidence."}}function YI(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 ZI(e){let t=[];return e.sharedComposables.length&&t.push(`shared composables: ${e.sharedComposables.join(", ")}`),e.sharedStores.length&&t.push(`shared stores: ${e.sharedStores.join(", ")}`),e.sharedRequests.length&&t.push(`shared request helpers: ${e.sharedRequests.join(", ")}`),e.sharedLifecycle.length&&t.push(`shared lifecycle: ${e.sharedLifecycle.join(", ")}`),e.sharedFunctions.length&&t.push(`shared functions: ${e.sharedFunctions.slice(0,6).join(", ")}`),e.sharedFunctionVerbs.length&&t.push(`shared action verbs: ${e.sharedFunctionVerbs.slice(0,6).join(", ")}`),e.sharedBindings.length&&t.push(`shared template bindings: ${e.sharedBindings.slice(0,6).join(", ")}`),t.join("; ")||"shared Vue behavior profile"}var eD=new Set(["add","apply","cancel","change","clear","close","composable","create","data","delete","draft","edit","error","fetch","filter","form","item","items","load","loading","name","open","reactive","ref","refresh","remove","request","reset","resource","row","rows","save","saving","search","select","selected","store","submit","toggle","update","use","value","watch"]);function vi(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 sr(e,{scope:a,scanLimit:c}).filter(d=>!l||d.file.includes(l)).map(d=>tD(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 tD(e,t){let n=[];if(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)return null;let r=nD(e),i=rD(e,t,r),o=iD(e.file),s=oD(r,o);return{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:r,pressureKinds:i,contextKind:o,recommendationKind:s,recommendation:sD(s,o),reasons:n,loc:e.totalLines}}function nD(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 rD(e,t,n){let r=[];return e.totalLines>=t.minTotalLines&&(r.push("total"),n!=="total"&&r.push(n)),e.templateLines>=t.minTemplateLines&&r.push("template"),e.scriptLines>=t.minScriptLines&&r.push("script"),e.styleLines>=t.minStyleLines&&r.push("style"),(e.externalScriptLines>=t.minScriptLines||n==="external-script")&&r.push("external-script"),e.customBlockLines>0&&n==="custom-block"&&r.push("custom-block"),[...new Set(r.length>0?r:[n])]}function iD(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(r=>aD.has(r))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function oD(e,t){return e==="style"?"style-decomposition":e==="template"?"template-decomposition":e==="external-script"?"external-script-boundary":e==="custom-block"?"custom-block-review":t==="route-page"?"route-page-decomposition":e==="script"?"script-behavior-extraction":"total-size-review"}function sD(e,t){switch(e){case"template-decomposition":return t==="route-page"?"Split route template sections into named panels before extracting script behavior.":"Split repeated template sections into named presentational components.";case"script-behavior-extraction":return"Extract independent script behavior into composables, controllers, or feature modules.";case"style-decomposition":return"Review UI/style decomposition; move repeated styling to component or style primitives, not composables.";case"external-script-boundary":return"Review the external script boundary and split controller/composable modules by workflow.";case"custom-block-review":return"Review custom block ownership before splitting template or script code.";case"route-page-decomposition":return"Split route/page orchestration from reusable panels and feature controllers.";case"total-size-review":return"Review the largest block first, then split by the dominant reason to change."}}var aD=new Set(["landing","page","pages","route","routes","view","views"]);function vc(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:o=3,maxChainLength:s=8}=t,a=ce(e,i),c=gD(a,o,s);if(c.length===0)return[];let l=cD(c);return l.length<2?[]:fD(dD(l,n,r),r)}function cD(e){let t=lD(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 lD(e){let{nodeFreq:t,tailFreq:n}=uD(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 uD(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 dD(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let o=i+1;o<e.length;o++){let s=mD(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 mD(e,t,n){if(!pD(e.filtered,t.filtered))return null;let{distance:r,ops:i}=hD(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:yD(e.original,t.original),commonSuffix:bD(e.original,t.original)}}function pD(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function fD(e,t){let n=[];for(let r of e)if(n.some(o=>Ep(r.chainA,o.chainA)&&Ep(r.chainB,o.chainB))||n.push(r),n.length>=t)break;return n}function gD(e,t,n){let r=[];for(let o of e.keys()){if(r.length>=500)break;Tp(e,o,[o],new Set([o]),t,n,r,500)}return r}function Tp(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),Tp(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 hD(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 yD(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 bD(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 Ep(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),r=e.join("\u2192");return n.includes(r)}function Ze(e){let t=e.orderCandidates?[...e.candidates()].sort(e.orderCandidates):e.candidates(),n=Ve(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 Tn(e,t={}){let{scope:n,minLoc:r=10,minCallees:i=6,limit:o=20,scanLimit:s}=t,a=new F(e);return Ze({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)=>SD(c,l.get(c.symbolId)??[],i),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function SD(e,t,n){let r=new Set(t.map(l=>l.symbol));if(r.size<n)return null;let i=kD(r,t),o=wD(r,i);if(o.length<2)return null;let s=LD(o,i);if(s.length===0)return null;let a=b(e.symbol),c=xD(a,r.size,o.length,s);return{symbol:e.symbol,shortName:a,relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:U(e),totalCallees:r.size,extractionKind:c.extractionKind,actionTier:"signal",evidenceReasons:c.evidenceReasons,recommendation:c.recommendation,clusters:s}}function xD(e,t,n,r){let i=Math.max(...r.map(c=>c.callees.length)),o=Math.max(...r.map(c=>c.isolation)),s=[`${t} distinct callees across ${n} co-occurrence cluster(s)`,`${r.length} extractable cluster(s) passed size and isolation thresholds`,`largest extractable cluster has ${i} callees at ${Math.round(o*100)}% isolation`],a=CD(e,t,n);return a!==null?{extractionKind:"workflow-orchestration",evidenceReasons:[...s,a],recommendation:"Review the isolated helper group as a possible private or feature-local helper, but keep the orchestration sequence together when it preserves the workflow."}:i>=6?{extractionKind:"broad-helper-cluster",evidenceReasons:[...s,"one isolated helper group is broad enough to deserve a named review"],recommendation:"Review whether the broad helper cluster has a stable concept name before extracting it; avoid creating a bag-of-helpers abstraction."}:{extractionKind:"cohesive-helper-cluster",evidenceReasons:s,recommendation:"Review the isolated callee group as a possible same-file or feature-local helper; extract only if the new name preserves the current behavior."}}function CD(e,t,n){if(t>=10)return`callee breadth suggests orchestration: ${t} callees`;if(n>=4)return`multiple disconnected callee groups suggest orchestration: ${n} groups`;let r=vD(e);return RD.has(r)?`caller verb suggests orchestration: ${r}`:null}function vD(e){return e.split(":").pop()?.replace(/\(\)$/,"").replace(/[^A-Za-z0-9_]/g,"").replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\s-]+/).filter(Boolean)[0]?.toLowerCase()??""}var RD=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function kD(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 wD(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 LD(e,t){return e.filter(n=>n.size>=3).map(n=>ID(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function ID(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}}import{posix as Ir}from"path";var DD=q("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]});function _n(e,t,n){return e.callerFileMap(t,{semantic:n.semantic,sourceFallback:n.sourceFallback})}function Zo(e,t,n){let r=[],i=0,o=0,s=$(t.symbol);for(let a of n)FD(e,a,t.relativePath,s)?i++:Rc(e,a,s)?o++:r.push(a);return{realConsumers:r,barrelConsumers:i,importOnlyConsumers:o}}function Rc(e,t,n){if(!n)return!1;let r=W(t);if(!r)return!1;let i=DD.get(e,t,()=>PD(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function PD(e,t,n){let r=T(e,t);if(!r)return ED();let i=X(e,t,r),o=te(e,"consumer-file-usage",t,i);if(o){let a=_D(o);if(a)return a}let s=ND(e,t,n);return ne(e,"consumer-file-usage",t,i,TD(s)),s}function ND(e,t,n){let r=new Set,i=new Set,o=be(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 ED(){return{importedLeaves:new Set,usedLeaves:new Set}}function TD(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function _D(e){try{let t=JSON.parse(e);return!Array.isArray(t.importedLeaves)||!Array.isArray(t.usedLeaves)?null:{importedLeaves:new Set(t.importedLeaves.filter(n=>typeof n=="string")),usedLeaves:new Set(t.usedLeaves.filter(n=>typeof n=="string"))}}catch{return null}}function FD(e,t,n,r){if(!r)return!1;let i=We(e,t);if(i.length===0)return!1;let o=ni(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}var AD=20,$D=1,MD=new Map([["app","app"],["apps","app"],["component","component"],["components","component"],["composable","composable"],["composables","composable"],["contract","contract"],["contracts","contract"],["domain","domain"],["domains","domain"],["feature","feature"],["features","feature"],["hook","hook"],["hooks","hook"],["lib","library"],["module","module"],["modules","module"],["package","package"],["packages","package"],["page","page"],["pages","page"],["route","route"],["routes","route"],["screen","screen"],["screens","screen"],["service","service"],["services","service"],["shared","shared"],["src","source-root"],["store","state"],["stores","state"],["test","test"],["tests","test"],["util","utility"],["utils","utility"],["view","view"],["views","view"]]),OD=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),jD=new Set(["access","api","auth","config","db","effect","errors","hooks","lib","middleware","permissions","routes","schemas","servicetasks","services","startup","store","stores","test-utils","repository","repositories","tests","types","ui","utils","workflow","workflows"]);function Ic(e,t={}){let n=Lc(t.limit,AD),r=Lc(t.minConsumers,$D),i=new F(e),o=i.fileDependencyGraph(t.scope),s=oP(O(e,{includeIgnored:!1})),a=cP(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?BD(e,i,t.target):HD(e,t.scope,t.scanLimit)).map(u=>VD(i,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=r||t.target).sort(iP).slice(0,n)}function BD(e,t,n){let r=WD(e,n);if(r)return[Mp(r)];let i=B(e,n);if(!i)return[];let o=t.definitionsForFile(i.relativePath).find(s=>s.symbolId===i.symbolId);return o?[GD(o)]:[{unit:{kind:"symbol",file:i.relativePath,shortName:b(i.symbol),symbol:i.symbol,startLine:i.startLine,endLine:i.endLine}}]}function HD(e,t,n){let r=O(e,{scope:t,includeIgnored:!1}),i=Lc(n,r.length);return r.slice(0,i).map(o=>Mp(o))}function VD(e,t,n,r,i,o){let s=n.definition?qD(e,n.definition,r.semantic):UD(t,n.unit.file),a=n.definition?s.length>0?"exact":"none":s.length>0?"file-level":"none",c=n.unit.file,l=at(Ir.dirname(c)),u=JD(s),d=zD(l),m=Nc([..._p(l),...u?_p(u):[]]),p=KD(n.unit,l,u,s),g=XD(p,n.unit,l,u,s,i,o),y=tP(n.unit,a,u,s,l,g.whyNoSuggestedHome),h=nP(n.unit,l,u,s,g.suggestedHome,g.whyNoSuggestedHome);return{actionTier:"signal",sourceUnit:n.unit,candidatePath:c,currentDirectory:l,directoryAncestry:d,consumerFiles:s,consumerCoverage:a,nearestCommonOwner:u,boundaryMarkers:m,recommendedTier:p,suggestedHome:g.suggestedHome,destinationConfidence:g.confidence,whyNoSuggestedHome:g.whyNoSuggestedHome,counterevidence:y,reasons:h,recommendation:rP(p,g.suggestedHome,a)}}function qD(e,t,n){let r=_n(e,[t],{semantic:n!==!1,sourceFallback:!0});return Vp(r.get(t.symbolId)??[])}function UD(e,t){let n=[];for(let[r,i]of e.entries())r!==t&&i.has(t)&&n.push(r);return Vp(n)}function WD(e,t){let n=Pc(t),r=O(e,{includeIgnored:!1}),i=r.find(s=>s===n);if(i)return i;let o=r.find(s=>s.endsWith(`/${n}`));return o||(r.find(s=>s.includes(n))??null)}function GD(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:b(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function Mp(e){return{unit:{kind:"file",file:e,shortName:Ir.basename(e)}}}function zD(e){if(e===".")return[{path:".",depth:0,markers:[]}];let t=[],n=e.split("/").filter(Boolean);for(let r=0;r<n.length;r+=1){let i=n.slice(0,r+1).join("/");t.push({path:i,depth:r,markers:Dc(i)})}return t}function _p(e){return e==="."?[]:Op(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function Dc(e){return Nc(Op(e).map(({marker:t})=>t))}function Op(e){let t=e.split("/").filter(Boolean),n=[];for(let r=0;r<t.length;r+=1){let i=MD.get(t[r]);i&&n.push({marker:i,prefix:t.slice(0,r+1).join("/")})}return n}function JD(e){if(e.length===0)return null;let t=e.map(r=>at(Ir.dirname(r))),n=t[0].split("/").filter(Boolean);for(let r of t.slice(1)){let i=r.split("/").filter(Boolean),o=[],s=Math.min(n.length,i.length);for(let a=0;a<s&&n[a]===i[a];a+=1)o.push(n[a]);n=o}return n.length===0?".":n.join("/")}function KD(e,t,n,r){return n?e.kind==="symbol"&&r.length===1?r[0]===e.file?"same-file":"sibling-folder":n==="."||n==="src"?"repository-level-review":Ap(n,"package")?"package-level-shared":Ap(n,"app")?"app-level-shared":$p(n,["feature","domain","module"])||$p(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function XD(e,t,n,r,i,o,s){let a=QD(e,r);if(a)return en(a);let c=sP(t.file),l=YD(e,n,c,i,s);if(l)return l;let u=r;if(at(n)===at(u))return en(`${n} is already the nearest common owner for its consumers.`);let d=ZD(u,n,c,s);return d||eP(u,n,c,o,s)}function QD(e,t){return t?e==="no-exact-consumers"||e==="repository-level-review"?"The inferred owner is too broad or unsupported for an exact destination.":null:"No consumer owner could be inferred from the current index."}function YD(e,t,n,r,i){if(e==="same-file"){let o=r[0]??null;return o?kc(o):en("No same-file consumer path was available.")}if(e==="sibling-folder"&&r.length===1){let o=at(Ir.dirname(r[0])),s=Hp(t,n,o,i);return s?en(s):kc(o)}return null}function ZD(e,t,n,r){return uP(e)?jp(e,t,n,r,`Nearest shared owner ${e} is outside source root ${n}.`):null}function eP(e,t,n,r,i){if(e===".")return en("The nearest common owner is the repository root.");let o=`${e}/shared`,s=jp(o,t,n,i,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||r.has(o)?s:en(`${o} does not exist in the indexed project.`)}function jp(e,t,n,r,i){if(!Bp(e,n))return en(i);let o=Hp(t,n,e,r);return o?en(o):kc(e)}function kc(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function en(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function tP(e,t,n,r,i,o){let s=["Report-only signal; review ownership before moving files."];return t==="none"&&s.push("No consumers were found in the current index."),t==="file-level"&&s.push("File-level import evidence can hide which exported unit is actually used."),(n==="."||n==="src")&&s.push("Nearest common owner is broad, so this is not enough evidence for automatic placement."),r.length===1&&s.push("Only one consumer was found; inlining or same-folder placement may be better than shared extraction."),e.kind==="file"&&s.push("File targets describe module locality, not symbol-level usage."),n&&i.startsWith(`${n}/`)&&s.push("Candidate already lives under the nearest common owner."),o&&s.push(`No exact suggested home: ${o}`),s}function nP(e,t,n,r,i,o){let s=[];return s.push(`${e.shortName} currently lives in ${t}.`),n?s.push(`${r.length} consumer file(s) share ${n} as their nearest common owner.`):s.push("No consumer owner could be inferred from the current index."),i?s.push(`Suggested home is ${i}.`):o&&s.push(`No exact suggested home: ${o}`),s}function rP(e,t,n){return e==="no-exact-consumers"?"Review references before moving; no consumers were found.":e==="repository-level-review"?"Keep this as a broad locality signal; the inferred owner is too general for automatic relocation.":t?`Review whether ${n==="exact"?"symbol usage":"module import"} supports moving or extracting toward ${t}.`:"Review ownership manually before changing structure."}function iP(e,t){return Fp(t)-Fp(e)||e.candidatePath.localeCompare(t.candidatePath)}function Fp(e){let t=e.consumerFiles.length*10;return e.consumerCoverage==="exact"&&(t+=5),e.suggestedHome&&(t+=3),e.recommendedTier==="repository-level-review"&&(t-=8),e.recommendedTier==="no-exact-consumers"&&(t-=12),t}function oP(e){let t=new Set(["."]);for(let n of e){let r=at(Ir.dirname(n));for(;!t.has(r)&&(t.add(r),r!==".");)r=at(Ir.dirname(r))}return t}function sP(e){let t=wc(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function Bp(e,t){let n=at(e),r=at(t);return r==="."||n===r||n.startsWith(`${r}/`)}function aP(e,t,n){let r=wc(e),i=wc(t);return(Bp(e,t)?r.slice(i.length):r).some(s=>n.has(s.toLowerCase()))}function Hp(e,t,n,r){return at(e)===at(n)||!aP(e,t,r)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function cP(...e){let t=new Set(jD);for(let n of e)for(let r of n??[]){let i=lP(r);i&&t.add(i)}return t}function lP(e){let t=e.trim().toLowerCase();return t===""?null:t}function Ap(e,t){return Dc(e).includes(t)}function $p(e,t){let n=Dc(e);return t.some(r=>n.includes(r))}function uP(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?OD.has(n):!1}function Pc(e){return e.replaceAll("\\","/").replace(/^\.\//,"")}function at(e){let t=Pc(e);return t===""?".":t}function wc(e){let t=Pc(e);return t==="."?[]:t.split("/").filter(Boolean)}function Lc(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function Vp(e){return Nc([...e]).sort((t,n)=>t.localeCompare(n))}function Nc(e){return[...new Set(e)]}function Ri(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 p of dP(e,m,i)){let g=`${p.file}|${p.shortName}`;if(p.symbolId!==null){if(a.has(p.symbolId))continue;a.add(p.symbolId)}else if(c.has(g))continue;c.add(g),s.push({symbol:p.symbol,shortName:p.shortName,file:p.file,depth:u}),p.symbolId!==null&&p.symbolMatch&&d.push(p.symbolMatch)}l=d}return s.sort((u,d)=>u.depth-d.depth||u.file.localeCompare(d.file)),s}function dP(e,t,n){let r=Qe(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 mP(e,t,n)){if(i.has(l))continue;let u=G(e,l),d=u.length>0?Ge(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=mr(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:b(l.symbol),file:l.file,symbolMatch:null});continue}if(u.symbolId===t.symbolId||e.isIgnored(u.relativePath)||!pP(u.symbol))continue;let d=`${u.symbolId}|${u.relativePath}`;c.has(d)||(c.add(d),a.push({symbolId:u.symbolId,symbol:u.symbol,shortName:b(u.symbol),file:u.relativePath,symbolMatch:u}))}return a}function mP(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
565
+ `)}function _E(e){return`${e.symbol}\0${e.startLine}\0${e.endLine}\0${e.leaf}`}function AE(e,t,n){return tg.read(e,t,n)??new Map}function ME(e){try{let t=JSON.parse(e);if(!Array.isArray(t.entries))return null;let n=new Map;for(let i of t.entries){if(!i||typeof i.key!="string"||typeof i.symbol!="string"||typeof i.startLine!="number"||typeof i.endLine!="number"||typeof i.leaf!="string"||!Array.isArray(i.tokens)||!i.tokens.every(r=>typeof r=="string"))return null;n.set(i.key,i)}return n}catch{return null}}function $E(e){let t={entries:[...e.values()].sort((n,i)=>n.key.localeCompare(i.key))};return JSON.stringify(t)}function jE(e,t,n,i){tg.write(e,t,n,new Map(i))}function dg(e,t){if(!e)return new Set;let n=new Set(["public","private","protected","final","static","class","def","fun","fn","function","return","string","bool","boolean","void","unit","self","this","new","const","let","var","end","pub"]),i=OE(t),o=e.replace(/["'`]/g," ").replace(/\b\d+\b/g," NUM ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[^A-Za-z0-9_]+/g," ").replace(/_/g," ").toLowerCase().split(/\s+/).map(s=>s.trim()).filter(s=>s.length>1).filter(s=>!n.has(s)).filter(s=>!i.has(s));return new Set(o)}function OE(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 BE(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function Hr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Nt(e,t){let n=new Map;return e.forEach((i,r)=>{let o=new Set;for(let s of t(i)){if(o.has(s))continue;o.add(s);let a=n.get(s);a?a.push(r):n.set(s,[r])}}),{candidatesFor:(i,r)=>{let o=new Set;for(let s of t(i)){let a=n.get(s);if(a)for(let c of a)c!==r&&o.add(c)}return[...o].sort((s,a)=>s-a)}}}function Ft(e){let t=mg(e.profile?.name),n=()=>{let i=[];t=mg(e.profile?.name,e);let r=(s,a)=>{let c=e.profiles[s],l=e.profiles[a];t.candidatePairs+=1,t.comparedPairs+=1;let d=e.compare(c,l);d&&i.push(d)};if(e.filePattern){let s=e.profiles.findIndex(a=>a.file.includes(e.filePattern));if(s>=0){let a=e.profiles[s];for(let c of HE(e,s)){let l=e.profiles[c];e.focusFiles&&!e.focusFiles.has(a.file)&&!e.focusFiles.has(l.file)||r(s,c)}}}else if(e.focusFiles?.size!==0){let s=typeof e.overrunFactor=="number"&&Number.isFinite(e.limit)?e.limit*e.overrunFactor:Number.POSITIVE_INFINITY;for(let a=0;a<e.profiles.length;a+=1){let c=e.profiles[a],l=e.focusFiles?.has(c.file)??!1;for(let d of VE(e,a))e.focusFiles&&!l&&!e.focusFiles.has(e.profiles[d].file)||r(a,d);if(i.length>s){t.overrunApplied=!0;break}}}i.sort(e.sort??((s,a)=>a.similarity-s.similarity)),t.matchedResults=i.length;let o=i.slice(0,e.limit);return t.emittedResults=o.length,e.onProfile?.({...t}),o};return e.profile?D(`pairwise-profile:${e.profile.name}`,n,()=>({...qE(e.profile?.metadata),...t})):n()}function HE(e,t){if(e.candidateIndex)return pg(e,t,-1);let n=[];for(let i=0;i<e.profiles.length;i+=1)i!==t&&n.push(i);return n}function VE(e,t){if(e.candidateIndex)return pg(e,t,t);let n=[];for(let i=t+1;i<e.profiles.length;i+=1)n.push(i);return n}function pg(e,t,n){let i=e.profiles[t],r=new Set;for(let o of e.candidateIndex?.candidatesFor(i,t,e.profiles)??[])o<=n||o!==t&&(o<0||o>=e.profiles.length||r.add(o));return[...r].sort((o,s)=>o-s)}function mg(e,t){return{pipeline:e,profileCount:t?.profiles.length??0,focusedProfileCount:t?.focusFiles?t.profiles.filter(n=>t.focusFiles.has(n.file)).length:0,candidatePairs:0,comparedPairs:0,matchedResults:0,emittedResults:0,candidateIndexApplied:t?.candidateIndex!==void 0,focusApplied:t?.focusFiles!==void 0,filePatternApplied:t?.filePattern!==void 0,overrunApplied:!1}}function qE(e){return typeof e=="function"?e():e??{}}function pl(e,t={}){let{minSimilarity:n=.5,limit:i=20,scope:r,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=UE(e,{scope:r,minDeps:s}),l=Nt(a,d=>d.deps);return Ft({profiles:a,limit:i,filePattern:o,overrunFactor:5,candidateIndex:l,profile:{name:"similar-files"},compare:(d,u)=>WE(d,u,n,c)})}function UE(e,t){let{scope:n,minDeps:i}=t,r=ye(e,n),{universalDeps:o,distinctiveDeps:s}=zE(r),a=[];for(let[c,l]of r)l.size>=i&&a.push({file:c,deps:new Set([...l].filter(d=>!o.has(d)))});return{profiles:a,distinctiveDeps:s}}function zE(e){let t=new Set,n=new Set,i=e.size;if(i===0)return{universalDeps:t,distinctiveDeps:n};let r=new Map;for(let s of e.values())for(let a of s)r.set(a,(r.get(a)??0)+1);let o=Math.max(3,Math.ceil(i*.03));for(let[s,a]of r)a>=5&&a/i>.3?t.add(s):a<=o&&n.add(s);return{universalDeps:t,distinctiveDeps:n}}function WE(e,t,n,i){let r=new Set;for(let l of e.deps)t.deps.has(l)&&r.add(l);if(r.size<3||e.deps.size<4||t.deps.size<4)return null;let o=0;for(let l of r)i.has(l)&&o++;if(o<2)return null;let s=bn(e.deps,t.deps);if(s<n)return null;let a=[];for(let l of e.deps)t.deps.has(l)||a.push(l);let c=[];for(let l of t.deps)e.deps.has(l)||c.push(l);return{fileA:e.file,fileB:t.file,similarity:s,sharedDeps:[...r],uniqueToA:a,uniqueToB:c}}function Ps(e){let t=[],n=[],i=[];for(let l of e.primitiveGroups)l.values.length!==0&&fg(l.bucket,n,i).push(`${l.reasonPrefix}: ${l.values.join(", ")}`);for(let l of e.nameGroups)GE(l.names,l.label,e.genericWords,e.stripPrefixes??[],t,fg(l.fallbackBucket,n,i));let r=t.length>0,o=n.length>0,s=i.length>0,a=r?o||s?"mixed":"domain-behavior":s?"shared-abstraction":"generic-workflow-scaffolding";return{actionTier:a==="domain-behavior"||a==="mixed"?"signal":"support",evidenceClass:a,reasons:[...t,...i,...n].slice(0,6),recommendation:e.recommendation(a)}}function Is(e,t){if(e.size===0||t.size===0)return 0;let i=ct(e,t).size/Math.min(e.size,t.size);return Math.max(bn(e,t),i)}function G(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function Te(e){return[...e].sort()}function GE(e,t,n,i,r,o){let s=[],a=[];for(let c of e)KE(c,i).filter(d=>!n.has(d)).length>0?s.push(c):a.push(c);s.length&&r.push(`${t} has domain term(s): ${s.slice(0,6).join(", ")}`),a.length&&o.push(`${t} is generic workflow: ${a.slice(0,6).join(", ")}`)}function KE(e,t){let n=e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2");for(let i of t)n=n.replace(i,"");return n.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function fg(e,t,n){return e==="generic"?t:n}function Gn(e,t={}){let{minSimilarity:n=.62,minTokens:i=8,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=tt(e).reactProfiles({scope:o,minJsxTokens:i,scanLimit:s}).filter(u=>u.kind==="component").map(u=>({file:u.file,component:u.name,tokens:u.jsxTokens,profile:u})),d=Nt(l,u=>u.tokens);return Ft({profiles:l,limit:r,filePattern:a,focusFiles:c,candidateIndex:d,profile:{name:"react-component-duplicates"},compare:(u,m)=>JE(u,m,n),sort:(u,m)=>m.similarity-u.similarity||u.fileA.localeCompare(m.fileA)||u.componentA.localeCompare(m.componentA)||u.fileB.localeCompare(m.fileB)||u.componentB.localeCompare(m.componentB)})}function JE(e,t,n){let i=ct(e.tokens,t.tokens);if(i.size<6||!XE(i))return null;let r=bn(e.tokens,t.tokens);return r<n?null:{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:r,sharedTokens:Te(i),sharedComponents:G(i,"component:"),sharedNativeTags:G(i,"native:"),sharedProps:G(i,"prop:"),sharedEvents:G(i,"event:"),sharedBindings:G(i,"binding:"),uniqueToA:Te(De(e.tokens,t.tokens)).slice(0,25),uniqueToB:Te(De(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function XE(e){let t=0,n=0;for(let i of e)i.startsWith("component:")&&(t+=1),(i.startsWith("prop:")||i.startsWith("event:")||i.startsWith("native:")||i.startsWith("jsx:"))&&(n+=1);return t>=1||n>=4}function Kn(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:i=6,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=tt(e).reactProfiles({scope:o,minBehaviorTokens:Math.max(3,i),scanLimit:s}).map(u=>({file:u.file,component:u.name,tokens:u.behaviorTokens,profile:u})),d=Nt(l,u=>u.tokens);return Ft({profiles:l,limit:r,filePattern:a,focusFiles:c,candidateIndex:d,profile:{name:"react-hook-candidates"},compare:(u,m)=>QE(u,m,n,i),sort:(u,m)=>m.similarity-u.similarity||u.fileA.localeCompare(m.fileA)||u.componentA.localeCompare(m.componentA)||u.fileB.localeCompare(m.fileB)||u.componentB.localeCompare(m.componentB)})}function QE(e,t,n,i){let r=ct(e.tokens,t.tokens);if(r.size<i||!eN(r))return null;let o=Is(e.tokens,t.tokens);if(o<n)return null;let s=G(r,"hook:"),a=G(r,"react-hook:"),c=G(r,"effect:"),l=G(r,"state:"),d=G(r,"request:"),u=G(r,"handler:"),m=G(r,"handler-verb:"),p=YE({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:d,sharedHandlers:u,sharedHandlerVerbs:m});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:o,sharedTokens:Te(r),sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:d,sharedHandlers:u,sharedHandlerVerbs:m,evidenceClass:p.evidenceClass,actionTier:p.actionTier,evidenceClassReasons:p.reasons,recommendation:p.recommendation,uniqueToA:Te(De(e.tokens,t.tokens)).slice(0,25),uniqueToB:Te(De(t.tokens,e.tokens)).slice(0,25),reason:tN({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:d,sharedHandlers:u,sharedHandlerVerbs:m}),locA:e.profile.loc,locB:t.profile.loc}}function YE(e){return Ps({genericWords:nN,stripPrefixes:iN,primitiveGroups:[{values:e.sharedReactHooks,reasonPrefix:"shared React primitives",bucket:"generic"},{values:e.sharedEffects,reasonPrefix:"shared lifecycle primitive",bucket:"generic"}],nameGroups:[{names:e.sharedHooks,label:"shared hook",fallbackBucket:"shared-abstraction"},{names:e.sharedRequests,label:"shared request",fallbackBucket:"generic"},{names:e.sharedState,label:"shared state",fallbackBucket:"generic"},{names:e.sharedHandlers,label:"shared handler",fallbackBucket:"generic"},{names:e.sharedHandlerVerbs,label:"shared action verb",fallbackBucket:"generic"}],recommendation:ZE})}function ZE(e){switch(e){case"domain-behavior":return"Review for a shared hook, controller, or feature module around the named domain behavior.";case"mixed":return"Separate generic React mechanics from domain-specific behavior before extracting a shared hook.";case"shared-abstraction":return"Review the existing shared hook usage first; extract only if duplicated behavior remains outside it.";case"generic-workflow-scaffolding":return"Treat as support evidence for a repeated workflow shape, not direct hook-extraction evidence."}}function eN(e){let t=0,n=0,i=0,r=0,o=0,s=0,a=0;for(let d of e)d.startsWith("hook:")?t+=1:d.startsWith("react-hook:")?n+=1:d.startsWith("effect:")?i+=1:d.startsWith("request:")?r+=1:d.startsWith("handler:")||d.startsWith("handler-verb:")?o+=1:d.startsWith("state:")?s+=1:d.startsWith("state-hook:")&&(a+=1);let c=s+a,l=t+n+i+r+o+c;return r>=1&&l>=4||t>=1&&(r>=1||s>=1||o>=2)&&l>=5||s>=1&&o>=2&&(i>=1||n>=2)&&l>=5}function tN(e){let t=[];return e.sharedHooks.length&&t.push(`shared hooks: ${e.sharedHooks.join(", ")}`),e.sharedReactHooks.length&&t.push(`shared React hooks: ${e.sharedReactHooks.join(", ")}`),e.sharedEffects.length&&t.push(`shared effects: ${e.sharedEffects.join(", ")}`),e.sharedState.length&&t.push(`shared state: ${e.sharedState.join(", ")}`),e.sharedRequests.length&&t.push(`shared requests: ${e.sharedRequests.join(", ")}`),e.sharedHandlers.length&&t.push(`shared handlers: ${e.sharedHandlers.slice(0,6).join(", ")}`),e.sharedHandlerVerbs.length&&t.push(`shared action verbs: ${e.sharedHandlerVerbs.slice(0,6).join(", ")}`),t.join("; ")||"shared React behavior profile"}var nN=new Set(["add","apply","async","callback","cancel","change","clear","close","create","data","delete","draft","edit","effect","error","fetch","filter","form","handle","has","is","item","items","load","loader","loading","memo","name","open","reducer","refresh","ref","remove","request","reset","resource","row","rows","save","saving","search","select","selected","state","store","submit","toggle","update","use","value"]),iN=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function qr(e,t={}){let{minComponentLines:n=300,minFileLines:i=800,minJsxTokens:r=80,minBehaviorTokens:o=40,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return tt(e).reactProfiles({scope:a,scanLimit:c}).filter(u=>u.kind==="component").filter(u=>!l||u.file.includes(l)||u.name.includes(l)).map(u=>rN(u,{minComponentLines:n,minFileLines:i,minJsxTokens:r,minBehaviorTokens:o})).filter(u=>u!==null).sort((u,m)=>m.componentLines-u.componentLines||m.fileLines-u.fileLines||u.file.localeCompare(m.file)).slice(0,s)}function rN(e,t){let n=[];e.loc>=t.minComponentLines&&n.push(`${e.loc} component line(s)`);let i=Math.max(80,Math.floor(t.minComponentLines/2));if(e.fileLines>=t.minFileLines&&e.loc>=i&&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)return null;let r=oN(e),o=sN(e,t,r),s=aN(e),a=cN(r,o,s);return{file:e.file,component:e.name,componentLines:e.loc,fileLines:e.fileLines,jsxTokens:e.jsxTokens.size,behaviorTokens:e.behaviorTokens.size,dominantPressure:r,pressureKinds:o,contextKind:s,recommendationKind:a,recommendation:lN(a,s),reasons:n,loc:e.loc}}function oN(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,i)=>i.value-n.value),t[0]?.axis??"component"}function sN(e,t,n){let i=[];e.loc>=t.minComponentLines&&i.push("component");let r=Math.max(80,Math.floor(t.minComponentLines/2));return e.fileLines>=t.minFileLines&&e.loc>=r&&i.push("file"),e.jsxTokens.size>=t.minJsxTokens&&i.push("jsx-structure"),e.behaviorTokens.size>=t.minBehaviorTokens&&i.push("hook-behavior"),[...new Set(i.length>0?i:[n])]}function aN(e){let t=e.file.split(/[\\/]+/).filter(Boolean),n=t.slice(0,-1).map(l=>l.toLowerCase()),i=(t.at(-1)??e.name).replace(/\.[^.]+$/,""),r=`${i} ${e.name}`.split(/[^A-Za-z0-9]+/).filter(Boolean).map(l=>l.toLowerCase()),o=n.findIndex(l=>dN.has(l)),s=o>=0&&n.slice(o+1).some(l=>uN.has(l)),a=gg(i)||gg(e.name);return/(?:Page|Route|Screen|View)$/.test(i)||/(?:Page|Route|Screen|View)$/.test(e.name)||r.some(l=>mN.has(l))||o>=0&&!s&&!a?"route-page":"component"}function gg(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&hg.has(t.at(-1))?!0:[...hg].some(n=>e.endsWith(pN(n)))}function cN(e,t,n){return e==="hook-behavior"?"behavior-extraction":n==="route-page"?"route-page-decomposition":t.includes("hook-behavior")?"behavior-extraction":t.includes("jsx-structure")?"jsx-decomposition":t.includes("file")?"file-decomposition":e==="jsx-structure"?"jsx-decomposition":e==="file"&&!t.includes("component")?"file-decomposition":"component-decomposition"}function lN(e,t){switch(e){case"behavior-extraction":return"Extract independent state, effects, requests, or handlers into hooks, controllers, or feature modules.";case"route-page-decomposition":return"Split route/page orchestration from reusable panels and feature controllers.";case"jsx-decomposition":return t==="route-page"?"Split page JSX into named layout sections before extracting behavior.":"Split repeated JSX sections into named presentational components.";case"file-decomposition":return"Review file-level decomposition; split colocated panels or helpers before changing behavior.";case"component-decomposition":return"Review component boundaries around props, state ownership, and independently changing UI sections."}}var uN=new Set(["component","components","panel","panels","partial","partials"]),hg=new Set(["banner","button","card","dialog","drawer","filter","form","grid","header","item","list","menu","modal","nav","panel","picker","rail","row","section","selector","shell","sidebar","table","toolbar"]),dN=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),mN=new Set(["landing","page","route","screen","view"]);function pN(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Jn(e,t={}){let{minSimilarity:n=.62,minTokens:i=8,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=fN(e,{scope:o,minTokens:i,scanLimit:s}),d=Nt(l,u=>u.tokens);return Ft({profiles:l,limit:r,filePattern:a,focusFiles:c,candidateIndex:d,profile:{name:"vue-component-duplicates"},compare:(u,m)=>hN(u,m,n),sort:(u,m)=>m.similarity-u.similarity||u.fileA.localeCompare(m.fileA)||u.fileB.localeCompare(m.fileB)})}function fN(e,t){return tt(e).vueProfiles({scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:gN(n)}))}function gN(e){return e.totalLines}function hN(e,t,n){let i=ct(e.tokens,t.tokens);if(i.size<6||!yN(i))return null;let r=bn(e.tokens,t.tokens);return r<n?null:{fileA:e.file,fileB:t.file,similarity:r,sharedTokens:Te(i),sharedComponents:G(i,"component:"),sharedProps:G(i,"prop:"),sharedEvents:G(i,"event:"),sharedDirectives:G(i,"directive:"),sharedSlots:G(i,"slot:"),sharedIdentifiers:G(i,"id:"),uniqueToA:Te(De(e.tokens,t.tokens)).slice(0,25),uniqueToB:Te(De(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function yN(e){let t=0,n=0;for(let i of e)i.startsWith("component:")&&(t+=1),(i.startsWith("prop:")||i.startsWith("event:")||i.startsWith("directive:")||i.startsWith("slot:"))&&(n+=1);return t>=1||n>=3}function Xn(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:i=6,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=tt(e).vueProfiles({scope:o,minBehaviorTokens:Math.max(3,i),scanLimit:s}).map(u=>({file:u.file,tokens:u.behaviorTokens,profile:u})),d=Nt(l,u=>u.tokens);return Ft({profiles:l,limit:r,filePattern:a,focusFiles:c,candidateIndex:d,profile:{name:"vue-composable-candidates"},compare:(u,m)=>bN(u,m,n,i),sort:(u,m)=>m.similarity-u.similarity||u.fileA.localeCompare(m.fileA)||u.fileB.localeCompare(m.fileB)})}function bN(e,t,n,i){let r=ct(e.tokens,t.tokens);if(r.size<i||!CN(r))return null;let o=Is(e.tokens,t.tokens);if(o<n)return null;let s=G(r,"composable:"),a=G(r,"store:"),c=G(r,"reactivity:"),l=G(r,"lifecycle:"),d=G(r,"request:"),u=G(r,"function:"),m=G(r,"function-verb:"),p=G(r,"template-binding:"),f=G(r,"template-event:"),g=SN({sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:d,sharedFunctions:u,sharedFunctionVerbs:m,sharedBindings:p,sharedTemplateEvents:f});return{fileA:e.file,fileB:t.file,similarity:o,sharedTokens:Te(r),sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:d,sharedFunctions:u,sharedFunctionVerbs:m,sharedBindings:p,sharedTemplateEvents:f,evidenceClass:g.evidenceClass,actionTier:g.actionTier,evidenceClassReasons:g.reasons,recommendation:g.recommendation,uniqueToA:Te(De(e.tokens,t.tokens)).slice(0,25),uniqueToB:Te(De(t.tokens,e.tokens)).slice(0,25),reason:vN({sharedComposables:s,sharedStores:a,sharedRequests:d,sharedLifecycle:l,sharedFunctions:u,sharedFunctionVerbs:m,sharedBindings:p}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function SN(e){return Ps({genericWords:RN,primitiveGroups:[{values:e.sharedReactivity,reasonPrefix:"shared reactivity primitive",bucket:"generic"},{values:e.sharedLifecycle,reasonPrefix:"shared lifecycle primitive",bucket:"generic"}],nameGroups:[{names:e.sharedComposables,label:"shared composable",fallbackBucket:"shared-abstraction"},{names:e.sharedStores,label:"shared store",fallbackBucket:"shared-abstraction"},{names:e.sharedRequests,label:"shared request",fallbackBucket:"generic"},{names:e.sharedFunctions,label:"shared function",fallbackBucket:"generic"},{names:e.sharedFunctionVerbs,label:"shared action verb",fallbackBucket:"generic"},{names:e.sharedBindings,label:"shared binding",fallbackBucket:"generic"},{names:e.sharedTemplateEvents,label:"shared template event",fallbackBucket:"generic"}],recommendation:xN})}function xN(e){switch(e){case"domain-behavior":return"Review for a shared composable, store, or feature module around the named domain behavior.";case"mixed":return"Separate generic Vue mechanics from domain-specific behavior before extracting a composable.";case"shared-abstraction":return"Review the existing composable/store usage first; extract only if duplicated behavior remains outside it.";case"generic-workflow-scaffolding":return"Treat as support evidence for a repeated workflow shape, not direct composable-extraction evidence."}}function CN(e){let t=0,n=0,i=0,r=0,o=0,s=0,a=0;for(let d of e)d.startsWith("composable:")?t+=1:d.startsWith("store:")?n+=1:d.startsWith("request:")?i+=1:d.startsWith("lifecycle:")?r+=1:d.startsWith("function:")?o+=1:d.startsWith("reactivity:")?s+=1:(d.startsWith("function-verb:")||d.startsWith("template-binding:")||d.startsWith("template-event:"))&&(a+=1);let c=t+n,l=c+i+r+o+a;return i>=1&&l>=4||r>=1&&o>=2&&l>=4||c>=2&&(i>=1||o>=2)&&l>=5||o>=2&&s>=1&&l>=4}function vN(e){let t=[];return e.sharedComposables.length&&t.push(`shared composables: ${e.sharedComposables.join(", ")}`),e.sharedStores.length&&t.push(`shared stores: ${e.sharedStores.join(", ")}`),e.sharedRequests.length&&t.push(`shared request helpers: ${e.sharedRequests.join(", ")}`),e.sharedLifecycle.length&&t.push(`shared lifecycle: ${e.sharedLifecycle.join(", ")}`),e.sharedFunctions.length&&t.push(`shared functions: ${e.sharedFunctions.slice(0,6).join(", ")}`),e.sharedFunctionVerbs.length&&t.push(`shared action verbs: ${e.sharedFunctionVerbs.slice(0,6).join(", ")}`),e.sharedBindings.length&&t.push(`shared template bindings: ${e.sharedBindings.slice(0,6).join(", ")}`),t.join("; ")||"shared Vue behavior profile"}var RN=new Set(["add","apply","cancel","change","clear","close","composable","create","data","delete","draft","edit","error","fetch","filter","form","item","items","load","loading","name","open","reactive","ref","refresh","remove","request","reset","resource","row","rows","save","saving","search","select","selected","store","submit","toggle","update","use","value","watch"]);function Ur(e,t={}){let{minTotalLines:n=800,minTemplateLines:i=300,minScriptLines:r=300,minStyleLines:o=500,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return tt(e).vueProfiles({scope:a,scanLimit:c}).filter(u=>!l||u.file.includes(l)).map(u=>kN(u,{minTotalLines:n,minTemplateLines:i,minScriptLines:r,minStyleLines:o})).filter(u=>u!==null).sort((u,m)=>m.totalLines-u.totalLines||u.file.localeCompare(m.file)).slice(0,s)}function kN(e,t){let n=[];if(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)return null;let i=wN(e),r=PN(e,t,i),o=IN(e.file),s=LN(i,o);return{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:i,pressureKinds:r,contextKind:o,recommendationKind:s,recommendation:DN(s,o),reasons:n,loc:e.totalLines}}function wN(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,i)=>i.lines-n.lines),t[0]?.lines?t[0].axis:"total"}function PN(e,t,n){let i=[];return e.totalLines>=t.minTotalLines&&(i.push("total"),n!=="total"&&i.push(n)),e.templateLines>=t.minTemplateLines&&i.push("template"),e.scriptLines>=t.minScriptLines&&i.push("script"),e.styleLines>=t.minStyleLines&&i.push("style"),(e.externalScriptLines>=t.minScriptLines||n==="external-script")&&i.push("external-script"),e.customBlockLines>0&&n==="custom-block"&&i.push("custom-block"),[...new Set(i.length>0?i:[n])]}function IN(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(i=>EN.has(i))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function LN(e,t){return e==="style"?"style-decomposition":e==="template"?"template-decomposition":e==="external-script"?"external-script-boundary":e==="custom-block"?"custom-block-review":t==="route-page"?"route-page-decomposition":e==="script"?"script-behavior-extraction":"total-size-review"}function DN(e,t){switch(e){case"template-decomposition":return t==="route-page"?"Split route template sections into named panels before extracting script behavior.":"Split repeated template sections into named presentational components.";case"script-behavior-extraction":return"Extract independent script behavior into composables, controllers, or feature modules.";case"style-decomposition":return"Review UI/style decomposition; move repeated styling to component or style primitives, not composables.";case"external-script-boundary":return"Review the external script boundary and split controller/composable modules by workflow.";case"custom-block-review":return"Review custom block ownership before splitting template or script code.";case"route-page-decomposition":return"Split route/page orchestration from reusable panels and feature controllers.";case"total-size-review":return"Review the largest block first, then split by the dominant reason to change."}}var EN=new Set(["landing","page","pages","route","routes","view","views"]);function fl(e,t={}){let{minSimilarity:n=.5,limit:i=15,scope:r,minChainLength:o=3,maxChainLength:s=8}=t,a=ye(e,r),c=jN(a,o,s);if(c.length===0)return[];let l=NN(c);return l.length<2?[]:$N(_N(l,n,i),i)}function NN(e){let t=FN(e),n=[];for(let i of e){let r=i.filter(o=>!t.has(o));r.length>=2&&n.push({original:i,filtered:r})}return n}function FN(e){let{nodeFreq:t,tailFreq:n}=TN(e),i=e.length*.9,r=e.length*.8,o=new Set;for(let[a,c]of t)c>i&&o.add(a);for(let[a,c]of n)c>r&&o.add(a);let s=["index.ts","index.js","cli.ts","main.ts","health.ts","health.js"];for(let a of t.keys()){let c=a.split("/").pop()??"";s.includes(c)&&o.add(a)}return o}function TN(e){let t=new Map,n=new Map;for(let i of e){let r=new Set;for(let o of i)r.has(o)||(t.set(o,(t.get(o)??0)+1),r.add(o));for(let o=Math.max(0,i.length-2);o<i.length;o++)n.set(i[o],(n.get(i[o])??0)+1)}return{nodeFreq:t,tailFreq:n}}function _N(e,t,n){let i=[];for(let r=0;r<e.length;r++){for(let o=r+1;o<e.length;o++){let s=AN(e[r],e[o],t);s&&i.push(s)}if(i.length>n*10)break}return i.sort((r,o)=>Math.abs(o.similarity-r.similarity)>.01?o.similarity-r.similarity:r.divergencePoints.length-o.divergencePoints.length),i}function AN(e,t,n){if(!MN(e.filtered,t.filtered))return null;let{distance:i,ops:r}=ON(e.filtered,t.filtered),o=Math.max(e.filtered.length,t.filtered.length);if(o===0)return null;let s=1-i/o;if(s<n||i===0)return null;let a=r.filter(l=>l.type==="substitute").map(l=>({index:l.indexA,nodeA:e.filtered[l.indexA],nodeB:t.filtered[l.indexB]}));return a.length===0||r.filter(l=>l.type==="match").length<2?null:{chainA:e.original,chainB:t.original,similarity:s,editDistance:i,divergencePoints:a,commonPrefix:BN(e.original,t.original),commonSuffix:HN(e.original,t.original)}}function MN(e,t){let n=new Set(e);return t.some(i=>n.has(i))}function $N(e,t){let n=[];for(let i of e)if(n.some(o=>yg(i.chainA,o.chainA)&&yg(i.chainB,o.chainB))||n.push(i),n.length>=t)break;return n}function jN(e,t,n){let i=[];for(let o of e.keys()){if(i.length>=500)break;bg(e,o,[o],new Set([o]),t,n,i,500)}return i}function bg(e,t,n,i,r,o,s,a){if(s.length>=a)return;if(n.length>=o){n.length>=r&&s.push([...n]);return}let c=e.get(t);if(!c||c.size===0){n.length>=r&&s.push([...n]);return}let l=!1;for(let d of c)if(!i.has(d)&&(i.add(d),n.push(d),bg(e,d,n,i,r,o,s,a),n.pop(),i.delete(d),l=!0,s.length>=a))return;!l&&n.length>=r&&s.push([...n])}function ON(e,t){let n=e.length,i=t.length,r=Array.from({length:n+1},()=>Array(i+1).fill(0));for(let c=0;c<=n;c++)r[c][0]=c;for(let c=0;c<=i;c++)r[0][c]=c;for(let c=1;c<=n;c++)for(let l=1;l<=i;l++)e[c-1]===t[l-1]?r[c][l]=r[c-1][l-1]:r[c][l]=1+Math.min(r[c-1][l],r[c][l-1],r[c-1][l-1]);let o=[],s=n,a=i;for(;s>0||a>0;)s>0&&a>0&&e[s-1]===t[a-1]?(o.unshift({type:"match",indexA:s-1,indexB:a-1}),s--,a--):s>0&&a>0&&r[s][a]===r[s-1][a-1]+1?(o.unshift({type:"substitute",indexA:s-1,indexB:a-1}),s--,a--):a>0&&r[s][a]===r[s][a-1]+1?(o.unshift({type:"insert",indexA:s,indexB:a-1}),a--):(o.unshift({type:"delete",indexA:s-1,indexB:a}),s--);return{distance:r[n][i],ops:o}}function BN(e,t){let n=[];for(let i=0;i<Math.min(e.length,t.length)&&e[i]===t[i];i++)n.push(e[i]);return n}function HN(e,t){let n=[],i=e.length-1,r=t.length-1;for(;i>=0&&r>=0&&e[i]===t[r];)n.unshift(e[i]),i--,r--;return n}function yg(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),i=e.join("\u2192");return n.includes(i)}function lt(e){let t=VN(e.profile?.name),n=()=>{let i=e.candidates(),r=e.filterCandidate?i.filter(e.filterCandidate):i,o=e.orderCandidates?[...r].sort(e.orderCandidates):r,s=qe(o,e.scanLimit);t={pipeline:e.profile?.name,loadedCandidates:i.length,filteredCandidates:r.length,scannedCandidates:s.length,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:s.length<r.length,resultLimitApplied:!1};let a=e.prepare?.(s)??void 0,c=[];for(let d of s){t.evaluatedCandidates+=1;let u=e.evaluate(d,a);u&&c.push(u)}t.matchedResults=c.length,e.orderResults&&c.sort(e.orderResults);let l=typeof e.limit=="number"?c.slice(0,e.limit):c;return t.emittedResults=l.length,t.resultLimitApplied=l.length<c.length,e.onProfile?.({...t}),l};return e.profile?D(`candidate-pipeline:${e.profile.name}`,n,()=>({...qN(e.profile?.metadata),...t})):n()}function VN(e){return{pipeline:e,loadedCandidates:0,filteredCandidates:0,scannedCandidates:0,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:!1,resultLimitApplied:!1}}function qN(e){return typeof e=="function"?e():e??{}}function Qn(e,t={}){let{scope:n,minLoc:i=10,minCallees:r=6,limit:o=20,scanLimit:s}=t,a=new A(e);return lt({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:i,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:s,profile:{name:"extract-candidates"},prepare:c=>a.calleeMap(c,{semantic:t.semantic!==!1}),evaluate:(c,l)=>UN(c,l.get(c.symbolId)??[],r),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function UN(e,t,n){let i=new Set(t.map(l=>l.symbol));if(i.size<n)return null;let r=JN(i,t),o=XN(i,r);if(o.length<2)return null;let s=QN(o,r);if(s.length===0)return null;let a=v(e.symbol),c=zN(a,i.size,o.length,s);return{symbol:e.symbol,shortName:a,relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:J(e),totalCallees:i.size,extractionKind:c.extractionKind,actionTier:"signal",evidenceReasons:c.evidenceReasons,recommendation:c.recommendation,clusters:s}}function zN(e,t,n,i){let r=Math.max(...i.map(c=>c.callees.length)),o=Math.max(...i.map(c=>c.isolation)),s=[`${t} distinct callees across ${n} co-occurrence cluster(s)`,`${i.length} extractable cluster(s) passed size and isolation thresholds`,`largest extractable cluster has ${r} callees at ${Math.round(o*100)}% isolation`],a=WN(e,t,n);return a!==null?{extractionKind:"workflow-orchestration",evidenceReasons:[...s,a],recommendation:"Review the isolated helper group as a possible private or feature-local helper, but keep the orchestration sequence together when it preserves the workflow."}:r>=6?{extractionKind:"broad-helper-cluster",evidenceReasons:[...s,"one isolated helper group is broad enough to deserve a named review"],recommendation:"Review whether the broad helper cluster has a stable concept name before extracting it; avoid creating a bag-of-helpers abstraction."}:{extractionKind:"cohesive-helper-cluster",evidenceReasons:s,recommendation:"Review the isolated callee group as a possible same-file or feature-local helper; extract only if the new name preserves the current behavior."}}function WN(e,t,n){if(t>=10)return`callee breadth suggests orchestration: ${t} callees`;if(n>=4)return`multiple disconnected callee groups suggest orchestration: ${n} groups`;let i=GN(e);return KN.has(i)?`caller verb suggests orchestration: ${i}`:null}function GN(e){return e.split(":").pop()?.replace(/\(\)$/,"").replace(/[^A-Za-z0-9_]/g,"").replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\s-]+/).filter(Boolean)[0]?.toLowerCase()??""}var KN=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function JN(e,t){let n=new Map;for(let r of e)n.set(r,new Set);let i=new Map;for(let r of t){let o=i.get(r.chunkId);o||(o=new Set,i.set(r.chunkId,o)),o.add(r.symbol)}for(let r of i.values()){let o=[...r];for(let s=0;s<o.length;s++)for(let a=s+1;a<o.length;a++)n.get(o[s]).add(o[a]),n.get(o[a]).add(o[s])}return n}function XN(e,t){let n=new Set,i=[];for(let r of e){if(n.has(r))continue;let o=new Set,s=[r];for(;s.length>0;){let a=s.pop();if(!n.has(a)){n.add(a),o.add(a);for(let c of t.get(a)??[])n.has(c)||s.push(c)}}i.push(o)}return i}function QN(e,t){return e.filter(n=>n.size>=3).map(n=>YN(n,e,t)).filter(n=>n.isolation>.5).sort((n,i)=>i.isolation-n.isolation)}function YN(e,t,n){let i=new Set;for(let a of t)if(a!==e)for(let c of a)i.add(c);let r=0;for(let a of e)for(let c of n.get(a)??[])i.has(c)&&r++;let o=e.size*i.size,s=o>0?1-r/o:1;return{callees:[...e].map(v),isolation:s}}import{posix as qi}from"path";var ZN=W("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]}),Sg=pe({kind:"consumer-file-usage",serialize:oF,deserialize:sF});function Yn(e,t){return{forDefinitions(n,i){return eF(e,t,n,i)}}}function Yt(e){let t=new Map;for(let[n,i]of e)t.set(n,new Set(i.files.map(r=>r.file)));return t}function Ls(e,t,n){return Cg(e,t,n).partition}function eF(e,t,n,i){let r=xg(n.length);return D("consumer-evidence.product",()=>{let o=tF(e,t,n,i),s=new Map;r={...r,...o.counters};for(let a of n){let c=o.sources.get(a.symbolId)??new Map,l=Cg(e,a,[...c.keys()],c);r.realFiles+=l.partition.realConsumers.length,r.reexportOnlyFiles+=l.partition.barrelConsumers,r.importOnlyFiles+=l.partition.importOnlyConsumers,s.set(a.symbolId,{definition:a,files:l.files,...l.partition})}return s},()=>({...r}))}function xg(e){return{definitions:e,indexedFiles:0,semanticFiles:0,fallbackFiles:0,totalFiles:0,realFiles:0,reexportOnlyFiles:0,importOnlyFiles:0}}function tF(e,t,n,i){let r=xg(n.length),o=new Map;return gl(o,r,"indexed",t.crossFileCallerMap(n,{semantic:!1})),i.semantic&&gl(o,r,"semantic",st(e,n)),i.sourceFallback!==!1&&gl(o,r,"source-fallback",t.sourceFallbackCallerFiles(n)),r.totalFiles=[...o.values()].reduce((s,a)=>s+a.size,0),{sources:o,counters:r}}function gl(e,t,n,i){let r=0;for(let[o,s]of i){let a=e.get(o);a||(a=new Map,e.set(o,a));for(let c of s){r++;let l=a.get(c)??new Set;l.add(n),a.set(c,l)}}n==="indexed"?t.indexedFiles+=r:n==="semantic"?t.semanticFiles+=r:t.fallbackFiles+=r}function Cg(e,t,n,i=new Map){let r=[],o=0,s=0,a=$(t.symbol),c=[];for(let l of n){let d;aF(e,l,t.relativePath,a)?(o++,d="reexport-only"):hl(e,l,a)?(s++,d="import-only"):(r.push(l),d="real"),c.push({file:l,sources:[...i.get(l)??[]],classification:d})}return{partition:{realConsumers:r,barrelConsumers:o,importOnlyConsumers:s},files:c}}function hl(e,t,n){if(!n)return!1;let i=H(t);if(!i)return!1;let r=ZN.get(e,t,()=>nF(e,t,i));return r.importedLeaves.has(n)&&!r.usedLeaves.has(n)}function nF(e,t,n){let i=gt(e).forFile(t,{text:!0,ast:!0}),r=i.text;if(!r)return rF();let o=re(e,t,r),s=Sg.read(e,t,o);if(s)return s;let a=iF(i.ast,n);return Sg.write(e,t,o,a),a}function iF(e,t){let n=new Set,i=new Set;if(!e)return{importedLeaves:n,usedLeaves:i};let r=t==="rust"?new Set(["use_declaration"]):t==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),o=(s,a)=>{let c=a||r.has(s.type);(s.type==="identifier"||s.type==="type_identifier"||s.type==="property_identifier"||s.type==="field_identifier")&&(c?n.add(s.text):i.add(s.text));for(let l of s.children)o(l,c)};return o(e.rootNode,!1),{importedLeaves:n,usedLeaves:i}}function rF(){return{importedLeaves:new Set,usedLeaves:new Set}}function oF(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function sF(e){try{let t=JSON.parse(e);return!Array.isArray(t.importedLeaves)||!Array.isArray(t.usedLeaves)?null:{importedLeaves:new Set(t.importedLeaves.filter(n=>typeof n=="string")),usedLeaves:new Set(t.usedLeaves.filter(n=>typeof n=="string"))}}catch{return null}}function aF(e,t,n,i){if(!i)return!1;let r=gt(e).forFile(t,{lines:!0,reexports:!0}),o=r.lines??[];if(o.length===0)return!1;let s=r.reexports??[];if(s.length===0)return!1;let a=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`\\b${a}\\b`),l=0;for(let d=0;d<o.length;d++){if(!c.test(o[d]??""))continue;if(l++,!s.find(m=>m.startLine<=d&&d<=m.endLine))return!1}return l>0}var cF=20,lF=1,uF=new Map([["app","app"],["apps","app"],["component","component"],["components","component"],["composable","composable"],["composables","composable"],["contract","contract"],["contracts","contract"],["domain","domain"],["domains","domain"],["feature","feature"],["features","feature"],["hook","hook"],["hooks","hook"],["lib","library"],["module","module"],["modules","module"],["package","package"],["packages","package"],["page","page"],["pages","page"],["route","route"],["routes","route"],["screen","screen"],["screens","screen"],["service","service"],["services","service"],["shared","shared"],["src","source-root"],["store","state"],["stores","state"],["test","test"],["tests","test"],["util","utility"],["utils","utility"],["view","view"],["views","view"]]),dF=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),mF=new Set(["access","api","auth","config","db","effect","errors","hooks","lib","middleware","permissions","routes","schemas","servicetasks","services","startup","store","stores","test-utils","repository","repositories","tests","types","ui","utils","workflow","workflows"]);function xl(e,t={}){let n=Sl(t.limit,cF),i=Sl(t.minConsumers,lF),r=new A(e),o=r.fileDependencyGraph(t.scope),s=FF(O(e,{includeIgnored:!1})),a=AF(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?pF(e,r,t.target):fF(e,t.scope,t.scanLimit)).map(d=>gF(e,r,o,d,t,s,a)).filter(d=>d.consumerFiles.length>=i||t.target).sort(NF).slice(0,n)}function pF(e,t,n){let i=bF(e,n);if(i)return[Pg(i)];let r=q(e,n);if(!r)return[];let o=t.definitionsForFile(r.relativePath).find(s=>s.symbolId===r.symbolId);return o?[SF(o)]:[{unit:{kind:"symbol",file:r.relativePath,shortName:v(r.symbol),symbol:r.symbol,startLine:r.startLine,endLine:r.endLine}}]}function fF(e,t,n){let i=O(e,{scope:t,includeIgnored:!1}),r=Sl(n,i.length);return i.slice(0,r).map(o=>Pg(o))}function gF(e,t,n,i,r,o,s){let a=i.definition?hF(e,t,i.definition,r.semantic):yF(n,i.unit.file),c=i.definition?a.length>0?"exact":"none":a.length>0?"file-level":"none",l=i.unit.file,d=yt(qi.dirname(l)),u=CF(a),m=xF(d),p=Rl([...vg(d),...u?vg(u):[]]),f=vF(i.unit,d,u,a),g=RF(f,i.unit,d,u,a,o,s),b=LF(i.unit,c,u,a,d,g.whyNoSuggestedHome),x=DF(i.unit,d,u,a,g.suggestedHome,g.whyNoSuggestedHome);return{actionTier:"signal",sourceUnit:i.unit,candidatePath:l,currentDirectory:d,directoryAncestry:m,consumerFiles:a,consumerCoverage:c,nearestCommonOwner:u,boundaryMarkers:p,recommendedTier:f,suggestedHome:g.suggestedHome,destinationConfidence:g.confidence,whyNoSuggestedHome:g.whyNoSuggestedHome,counterevidence:b,reasons:x,recommendation:EF(f,g.suggestedHome,c)}}function hF(e,t,n,i){let r=Yt(Yn(e,t).forDefinitions([n],{semantic:i!==!1,sourceFallback:!0}));return Ng(r.get(n.symbolId)??[])}function yF(e,t){let n=[];for(let[i,r]of e.entries())i!==t&&r.has(t)&&n.push(i);return Ng(n)}function bF(e,t){let n=vl(t),i=O(e,{includeIgnored:!1}),r=i.find(s=>s===n);if(r)return r;let o=i.find(s=>s.endsWith(`/${n}`));return o||(i.find(s=>s.includes(n))??null)}function SF(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:v(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function Pg(e){return{unit:{kind:"file",file:e,shortName:qi.basename(e)}}}function xF(e){if(e===".")return[{path:".",depth:0,markers:[]}];let t=[],n=e.split("/").filter(Boolean);for(let i=0;i<n.length;i+=1){let r=n.slice(0,i+1).join("/");t.push({path:r,depth:i,markers:Cl(r)})}return t}function vg(e){return e==="."?[]:Ig(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function Cl(e){return Rl(Ig(e).map(({marker:t})=>t))}function Ig(e){let t=e.split("/").filter(Boolean),n=[];for(let i=0;i<t.length;i+=1){let r=uF.get(t[i]);r&&n.push({marker:r,prefix:t.slice(0,i+1).join("/")})}return n}function CF(e){if(e.length===0)return null;let t=e.map(i=>yt(qi.dirname(i))),n=t[0].split("/").filter(Boolean);for(let i of t.slice(1)){let r=i.split("/").filter(Boolean),o=[],s=Math.min(n.length,r.length);for(let a=0;a<s&&n[a]===r[a];a+=1)o.push(n[a]);n=o}return n.length===0?".":n.join("/")}function vF(e,t,n,i){return n?e.kind==="symbol"&&i.length===1?i[0]===e.file?"same-file":"sibling-folder":n==="."||n==="src"?"repository-level-review":kg(n,"package")?"package-level-shared":kg(n,"app")?"app-level-shared":wg(n,["feature","domain","module"])||wg(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function RF(e,t,n,i,r,o,s){let a=kF(e,i);if(a)return Sn(a);let c=TF(t.file),l=wF(e,n,c,r,s);if(l)return l;let d=i;if(yt(n)===yt(d))return Sn(`${n} is already the nearest common owner for its consumers.`);let u=PF(d,n,c,s);return u||IF(d,n,c,o,s)}function kF(e,t){return t?e==="no-exact-consumers"||e==="repository-level-review"?"The inferred owner is too broad or unsupported for an exact destination.":null:"No consumer owner could be inferred from the current index."}function wF(e,t,n,i,r){if(e==="same-file"){let o=i[0]??null;return o?yl(o):Sn("No same-file consumer path was available.")}if(e==="sibling-folder"&&i.length===1){let o=yt(qi.dirname(i[0])),s=Eg(t,n,o,r);return s?Sn(s):yl(o)}return null}function PF(e,t,n,i){return $F(e)?Lg(e,t,n,i,`Nearest shared owner ${e} is outside source root ${n}.`):null}function IF(e,t,n,i,r){if(e===".")return Sn("The nearest common owner is the repository root.");let o=`${e}/shared`,s=Lg(o,t,n,r,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||i.has(o)?s:Sn(`${o} does not exist in the indexed project.`)}function Lg(e,t,n,i,r){if(!Dg(e,n))return Sn(r);let o=Eg(t,n,e,i);return o?Sn(o):yl(e)}function yl(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function Sn(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function LF(e,t,n,i,r,o){let s=["Report-only signal; review ownership before moving files."];return t==="none"&&s.push("No consumers were found in the current index."),t==="file-level"&&s.push("File-level import evidence can hide which exported unit is actually used."),(n==="."||n==="src")&&s.push("Nearest common owner is broad, so this is not enough evidence for automatic placement."),i.length===1&&s.push("Only one consumer was found; inlining or same-folder placement may be better than shared extraction."),e.kind==="file"&&s.push("File targets describe module locality, not symbol-level usage."),n&&r.startsWith(`${n}/`)&&s.push("Candidate already lives under the nearest common owner."),o&&s.push(`No exact suggested home: ${o}`),s}function DF(e,t,n,i,r,o){let s=[];return s.push(`${e.shortName} currently lives in ${t}.`),n?s.push(`${i.length} consumer file(s) share ${n} as their nearest common owner.`):s.push("No consumer owner could be inferred from the current index."),r?s.push(`Suggested home is ${r}.`):o&&s.push(`No exact suggested home: ${o}`),s}function EF(e,t,n){return e==="no-exact-consumers"?"Review references before moving; no consumers were found.":e==="repository-level-review"?"Keep this as a broad locality signal; the inferred owner is too general for automatic relocation.":t?`Review whether ${n==="exact"?"symbol usage":"module import"} supports moving or extracting toward ${t}.`:"Review ownership manually before changing structure."}function NF(e,t){return Rg(t)-Rg(e)||e.candidatePath.localeCompare(t.candidatePath)}function Rg(e){let t=e.consumerFiles.length*10;return e.consumerCoverage==="exact"&&(t+=5),e.suggestedHome&&(t+=3),e.recommendedTier==="repository-level-review"&&(t-=8),e.recommendedTier==="no-exact-consumers"&&(t-=12),t}function FF(e){let t=new Set(["."]);for(let n of e){let i=yt(qi.dirname(n));for(;!t.has(i)&&(t.add(i),i!==".");)i=yt(qi.dirname(i))}return t}function TF(e){let t=bl(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function Dg(e,t){let n=yt(e),i=yt(t);return i==="."||n===i||n.startsWith(`${i}/`)}function _F(e,t,n){let i=bl(e),r=bl(t);return(Dg(e,t)?i.slice(r.length):i).some(s=>n.has(s.toLowerCase()))}function Eg(e,t,n,i){return yt(e)===yt(n)||!_F(e,t,i)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function AF(...e){let t=new Set(mF);for(let n of e)for(let i of n??[]){let r=MF(i);r&&t.add(r)}return t}function MF(e){let t=e.trim().toLowerCase();return t===""?null:t}function kg(e,t){return Cl(e).includes(t)}function wg(e,t){let n=Cl(e);return t.some(i=>n.includes(i))}function $F(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?dF.has(n):!1}function vl(e){return e.replaceAll("\\","/").replace(/^\.\//,"")}function yt(e){let t=vl(e);return t===""?".":t}function bl(e){let t=vl(e);return t==="."?[]:t.split("/").filter(Boolean)}function Sl(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function Ng(e){return Rl([...e]).sort((t,n)=>t.localeCompare(n))}function Rl(e){return[...new Set(e)]}function zr(e,t,n={}){let{maxDepth:i=5,scope:r}=n,o=q(e,t);if(!o)return[];let s=[],a=new Set([o.symbolId]),c=new Set,l=[o];for(let d=1;d<=i&&l.length!==0;d++){let u=[];for(let m of l)for(let p of jF(e,m,r)){let f=`${p.file}|${p.shortName}`;if(p.symbolId!==null){if(a.has(p.symbolId))continue;a.add(p.symbolId)}else if(c.has(f))continue;c.add(f),s.push({symbol:p.symbol,shortName:p.shortName,file:p.file,depth:d}),p.symbolId!==null&&p.symbolMatch&&u.push(p.symbolMatch)}l=u}return s.sort((d,u)=>d.depth-u.depth||d.file.localeCompare(u.file)),s}function jF(e,t,n){let i=at(e,t,{limit:500}).filter(l=>!e.isIgnored(l.file)).filter(l=>!n||l.file.includes(n)),r=new Set(i.map(l=>l.file)),o=[];for(let l of OF(e,t,n)){if(r.has(l))continue;let d=Q(e,l),u=d.length>0?ot(d,d[0].startLine):null;o.push({symbol:u?.symbol??l,file:l})}let s=[...i,...o],a=[],c=new Set;for(let l of s){let d=Ni(e,l.symbol);if(!d){let m=`${l.file}|${l.symbol}`;if(c.has(m))continue;c.add(m),a.push({symbolId:null,symbol:l.symbol,shortName:v(l.symbol),file:l.file,symbolMatch:null});continue}if(d.symbolId===t.symbolId||e.isIgnored(d.relativePath)||!BF(d))continue;let u=`${d.symbolId}|${d.relativePath}`;c.has(u)||(c.add(u),a.push({symbolId:d.symbolId,symbol:d.symbol,shortName:v(d.symbol),file:d.relativePath,symbolMatch:d}))}return a}function OF(e,t,n){let i=n?"AND consumer_d.relative_path LIKE ?":"",r=[t.symbolId,t.documentId];return n&&r.push(`%${n}%`),new Set(e.all(`SELECT DISTINCT consumer_d.relative_path
544
566
  FROM mentions m
545
567
  JOIN chunks c ON m.chunk_id = c.id
546
568
  JOIN documents consumer_d ON consumer_d.id = c.document_id
@@ -548,50 +570,50 @@ ${m}`,l+=1+m.length,u+=ei(m),r+=m.length+1}let d=uR(c);d&&n.push({...d,start:a,e
548
570
  AND m.role != 1
549
571
  AND c.document_id != ?
550
572
  ${e.pathExclusionsFor("consumer_d")}
551
- ${r}`,...i).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function pP(e){let t=re(e);return t==="method"||t==="type"||e.endsWith("().")}function ki(e,t,n={}){let r=Fe(e,t);if(!r)return null;let i=fP(e,r);if(!i||e.isIgnored(i.relative_path))return null;let o=[],s=0,a=gP(e,i.relative_path),c=n.semantic===!1?new Map:Xe(e,a);for(let l of a){let u=hP(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:yP(u)})}return{file:i.relative_path,symbols:o,totalExternalConsumers:s}}function fP(e,t){return e.get(`SELECT id, relative_path FROM documents
573
+ ${i}`,...r).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function BF(e){if(e.symbol.startsWith("scip-clojure ")||H(e.relativePath)==="clojure")return!0;let t=se(e.symbol);return t==="method"||t==="type"||e.symbol.endsWith("().")}function Wr(e,t,n={}){let i=Ve(e,t);if(!i)return null;let r=HF(e,i);if(!r||e.isIgnored(r.relative_path))return null;let o=[],s=0,a=VF(e,r.relative_path),c=n.semantic===!1?new Map:st(e,a);for(let l of a){let d=qF(e,r,l,c.get(l.symbolId)??new Set);s+=d,o.push({symbol:l.symbol,shortName:v(l.symbol),startLine:l.startLine,endLine:l.endLine,externalConsumers:d,riskLevel:UF(d)})}return{file:r.relative_path,symbols:o,totalExternalConsumers:s}}function HF(e,t){return e.get(`SELECT id, relative_path FROM documents
552
574
  WHERE relative_path = ?
553
575
  ${e.pathExclusionsFor("documents")}
554
- LIMIT 1`,t)??null}function gP(e,t){return new F(e).definitionsForFile(t).sort((n,r)=>n.startLine-r.startLine||n.endLine-r.endLine)}function hP(e,t,n,r){let i=e.all(`SELECT DISTINCT consumer_d.relative_path
576
+ LIMIT 1`,t)??null}function VF(e,t){return new A(e).definitionsForFile(t).sort((n,i)=>n.startLine-i.startLine||n.endLine-i.endLine)}function qF(e,t,n,i){let r=e.all(`SELECT DISTINCT consumer_d.relative_path
555
577
  FROM mentions m
556
578
  JOIN chunks c ON m.chunk_id = c.id
557
579
  JOIN documents consumer_d ON consumer_d.id = c.document_id
558
580
  WHERE m.symbol_id = ?
559
581
  AND m.role != 1
560
- 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 yP(e){return e>10?"high":e>0?"medium":"low"}function es(e,t={}){let{scope:n,minLoc:r=1,maxDepth:i=5,scanLimit:o}=t,s=new F(e),a=bP(e,n,r,o),c=new Ec;for(let y of a)c.add(y);let l=[],u=[];a.length>0&&l.push(qp(e,0,a,c));let d=a.map(y=>y.definition).filter(y=>y!==null),m=new Set(a.map(y=>y.symbol));for(let y=1;y<=i&&d.length>0;y++){let h=s.calleeMap(d,{semantic:!1}),x=new Set;for(let R of d)for(let L of h.get(R.symbolId)??[])m.has(L.symbol)||x.add(L.symbol);let v=[];for(let R of x){m.add(R);let L=Up(e,R);if(!L||e.isIgnored(L.relativePath)||Te(e,L.relativePath)||le(e,L.symbol,L.relativePath)||s.fileKind(L.relativePath)==="test"||s.hasSuppressionComment(L))continue;let S=xP(e,L,c);S.removable?v.push(SP(L,"cascade")):S.blockingFiles.length>0&&u.push({shortName:b(L.symbol),file:L.relativePath,blockingFiles:S.blockingFiles.slice(0,3)})}if(v.length===0)break;for(let R of v)c.add(R);l.push(qp(e,y,v,c)),d=v.map(R=>R.definition).filter(R=>R!==null)}let p=l.reduce((y,h)=>y+h.loc,0),g=l.reduce((y,h)=>y+h.entries.length,0);return{batches:l,totalSymbols:g,totalLoc:p,blocked:u}}function bP(e,t,n,r){let i=Et(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:r,semantic:!1}),o=[];for(let s of i.symbols)s.kind==="dead-code"&&(Te(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:Up(e,s.symbol)}));return o}function SP(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 Up(e,t){let n=e.get(`SELECT d.relative_path
582
+ AND c.document_id != ?`,n.symbolId,t.id);return new Set([...r.map(o=>o.relative_path),...[...i].filter(o=>o!==t.relative_path)]).size}function UF(e){return e>10?"high":e>0?"medium":"low"}function Ds(e,t={}){let{scope:n,minLoc:i=1,maxDepth:r=5,scanLimit:o}=t,s=new A(e),a=zF(e,n,i,o),c=new kl;for(let g of a)c.add(g);let l=[],d=[];a.length>0&&l.push(Fg(e,0,a,c));let u=a.map(g=>g.definition).filter(g=>g!==null),m=new Set(a.map(g=>g.symbol));for(let g=1;g<=r&&u.length>0;g++){let b=s.calleeMap(u,{semantic:!1}),x=new Set;for(let R of u)for(let C of b.get(R.symbolId)??[])m.has(C.symbol)||x.add(C.symbol);let S=[];for(let R of x){m.add(R);let C=Tg(e,R);if(!C||e.isIgnored(C.relativePath)||Oe(e,C.relativePath)||be(e,C.symbol,C.relativePath)||s.fileKind(C.relativePath)==="test"||s.hasSuppressionComment(C))continue;let y=GF(e,C,c);y.removable?S.push(WF(C,"cascade")):y.blockingFiles.length>0&&d.push({shortName:v(C.symbol),file:C.relativePath,blockingFiles:y.blockingFiles.slice(0,3)})}if(S.length===0)break;for(let R of S)c.add(R);l.push(Fg(e,g,S,c)),u=S.map(R=>R.definition).filter(R=>R!==null)}let p=l.reduce((g,b)=>g+b.loc,0),f=l.reduce((g,b)=>g+b.entries.length,0);return{batches:l,totalSymbols:f,totalLoc:p,blocked:d}}function zF(e,t,n,i){let r=Qt(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:i,semantic:!1}),o=[];for(let s of r.symbols)s.kind==="dead-code"&&(Oe(e,s.relativePath)||be(e,s.symbol,s.relativePath)||o.push({symbol:s.symbol,shortName:s.shortName,file:s.relativePath,startLine:s.startLine,endLine:s.endLine,loc:s.loc,evidence:"graph-fact",definition:Tg(e,s.symbol)}));return o}function WF(e,t){return{symbol:e.symbol,shortName:v(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function Tg(e,t){let n=e.get(`SELECT d.relative_path
561
583
  FROM global_symbols gs
562
584
  JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
563
585
  JOIN documents d ON d.id = der.document_id
564
586
  WHERE gs.symbol = ?
565
- LIMIT 1`,t);return n?G(e,n.relative_path).find(r=>r.symbol===t)??null:null}function xP(e,t,n){let r=wn(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 qp(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=G(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 Ec=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 UT}from"crypto";import{existsSync as _f}from"fs";import{execFileSync as CP}from"child_process";var ts=2e3,Tc=50,vP=64,RP=8,kP=3,wP=2160*60*60,LP=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,IP=3,DP=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,PP=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function _c(e){let t=Z(e,{clearGroups:["whole-project"]});return(n,r)=>{let i=zp(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 NP=_c("git-commit-history");function nn(e){return NP(e,EP)}function zp(e){try{return tn(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function tn(e,t){return CP("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]})}function EP(e,t){let n;try{n=tn(e,["log","--no-merges","--name-only","-n",String(ts),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}return{head:t,...$c(n,Tc)}}function TP(e){return LP.test(e.subject)}function ns(e){let t=nn(e);if(!t)return null;let n=new Map;for(let r of t.commits){let i=TP(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 Jp(e){let t=nn(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:Wp(n,.5),p90FilesPerCommit:Wp(n,.9),commitsAnalyzed:n.length}}function Wp(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var _P=_c("git-tracked-files");function Fc(e){return _P(e,t=>{try{let n=tn(t,["ls-files"]);return new Set(n.split(`
566
- `).map(r=>r.trim()).filter(r=>r!==""))}catch{return null}})}var FP=_c("git-file-adds"),Gp="__git__/file-adds";function Kp(e){return FP(e,(t,n)=>AP(e,t,n))}function AP(e,t,n){let r=MP(te(e,"git-file-adds",Gp,n));if(r)return r;let i=OP(t);return i&&ne(e,"git-file-adds",Gp,n,$P(i)),i}function $P(e){return JSON.stringify([...e.entries()])}function MP(e){if(!e)return null;try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=new Map;for(let r of t){if(!Array.isArray(r)||r.length!==2||typeof r[0]!="string")return null;let i=r[1];if(!i||typeof i.commitsAgo!="number"||!Number.isFinite(i.commitsAgo)||typeof i.addedAt!="number"||!Number.isFinite(i.addedAt))return null;n.set(r[0],{commitsAgo:i.commitsAgo,addedAt:i.addedAt})}return n}catch{return null}}function OP(e){let t;try{t=tn(e,["log","--no-merges","--diff-filter=A","--name-only","-n",String(ts),"--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(`
567
- `),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(`
568
- `)){let u=l.trim();u!==""&&n.set(u,{commitsAgo:r,addedAt:c})}}return n}function Xp(e,t={}){let n=nn(e);return n?Ac(n,t):null}function jP(e,t,n={}){let r=nn(e);return r?t.size===0?[]:Ac(r,n,t):null}function Qp(e,t,n={}){if(t.size===0)return[];let r=zp(e.config.projectRoot);if(!r)return null;let i=n.maxFilesPerCommit??Tc;if(t.size>vP)return jP(e,t,n);let o=BP(e.config.projectRoot,r,t,i);return o?Ac(o,n,t):null}function Ac(e,t,n){let{minTogether:r=4,minConfidence:i=.6,maxFilesPerCommit:o=Tc}=t,s=new Map,a=new Map,c=e.newestAnalyzedAt??0;for(let d of e.commits){let m=[...new Set(d.files)].sort();if(m.length>o)continue;e.newestAnalyzedAt===void 0&&d.timestamp>c&&(c=d.timestamp);let p=qP(m),g=n===void 0||m.some(y=>n.has(y));for(let y of m)s.set(y,(s.get(y)??0)+1);if(g)for(let y=0;y<m.length;y++)for(let h=y+1;h<m.length;h++){if(n&&!n.has(m[y])&&!n.has(m[h]))continue;let x=`${m[y]}\0${m[h]}`,v=a.get(x)??{together:0,focusedTogether:0,broadTogether:0,lastTogetherAt:0,timestamps:[],subjects:[]};v.together+=1,p?v.broadTogether+=1:v.focusedTogether+=1,d.timestamp>v.lastTogetherAt&&(v.lastTogetherAt=d.timestamp),v.timestamps.push(d.timestamp),v.subjects.push(d.subject),a.set(x,v)}}let l=[],u=c-wP;for(let[d,m]of a){let p=m.together;if(p<r)continue;let[g,y]=d.split("\0"),h=s.get(g)??p,x=s.get(y)??p,v=Math.max(p/h,p/x);if(v<i)continue;let R=m.broadTogether/p,L=m.timestamps.filter(S=>S>=u).length;l.push({fileA:g,fileB:y,together:p,confidence:v,changesA:h,changesB:x,focusedTogether:m.focusedTogether,broadTogether:m.broadTogether,broadCommitRatio:R,lastTogetherAt:m.lastTogetherAt,recentTogether:L,commitScope:WP(m.broadTogether,p),recency:L>0?"recent":"stale",subjectContext:GP(m.subjects)})}return l.sort((d,m)=>m.together-d.together||m.confidence-d.confidence||d.fileA.localeCompare(m.fileA)),l}function BP(e,t,n,r){let i;try{i=HP(e)}catch{return null}if(i.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:0};let o;try{o=tn(e,["log","--no-merges","--format=%H","-n",String(ts),"--",...[...n].sort()])}catch{return null}let s=new Set(i.map(d=>d.hash)),a=o.split(`
569
- `).map(d=>d.trim()).filter(d=>d!==""&&s.has(d)),c=VP(e,i,r);if(a.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:c};let l;try{l=tn(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...a])}catch{return null}let u=$c(l,r);return{head:t,...u,newestAnalyzedAt:c}}function HP(e){return tn(e,["log","--no-merges","--format=%H%x00%ct","-n",String(ts)]).split(`
570
- `).map(n=>n.trim()).filter(n=>n!=="").map(n=>{let[r,i]=n.split("\0");return{hash:r??"",timestamp:Number(i)||0}}).filter(n=>n.hash!=="")}function VP(e,t,n){for(let i=0;i<t.length;i+=20){let o=t.slice(i,i+20),s;try{s=tn(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...o.map(c=>c.hash)])}catch{return t[0]?.timestamp??0}let a=$c(s,n);if(a.commits.length>0)return a.commits[0].timestamp}return 0}function $c(e,t){let n=[],r=0;for(let i of e.split("")){if(i.trim()==="")continue;let o=i.indexOf(`
571
- `),s=o>=0?i.slice(0,o):i,[a,c,l]=s.split("\0");if(!a||!c)continue;let u=o>=0?i.slice(o+1).split(`
572
- `).map(d=>d.trim()).filter(d=>d!==""):[];if(u.length>t){r+=1;continue}n.push({hash:a,timestamp:Number(c)||0,subject:l??"",files:u})}return{commits:n,skippedBulkCommits:r}}function qP(e){return e.length>=RP?!0:UP(e).size>=kP}function UP(e){let t=new Set;for(let n of e){let r=n.indexOf("/");t.add(r>=0?n.slice(0,r):".")}return t}function WP(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function GP(e){let t=new Set,n=[],r=[];for(let i of e){!r.includes(i)&&r.length<IP&&r.push(i);for(let o of zP(i))t.add(o);for(let o of i.match(DP)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:r,externalIssueLabelStatus:"unavailable"}}function zP(e){let t=new Set,n=PP.exec(e)?.[1]?.toLowerCase();return n&&t.add(JP(n)),/\b(?:feat|feature)\b/i.test(e)&&t.add("feature"),/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i.test(e)&&t.add("fix"),/\b(?:docs?|documentation|guide|readme)\b/i.test(e)&&t.add("docs"),/\brefactor(?:ing|ed)?\b/i.test(e)&&t.add("refactor"),/\btests?\b/i.test(e)&&t.add("test"),/\b(?:release|version|v\d+\.\d+)\b/i.test(e)&&t.add("release"),/\bchore\b/i.test(e)&&t.add("chore"),/\bbuild\b/i.test(e)&&t.add("build"),/\bci\b/i.test(e)&&t.add("ci"),/\bperf(?:ormance)?\b/i.test(e)&&t.add("perf"),[...t]}function JP(e){return e==="feat"?"feature":e}import{existsSync as KP}from"fs";import{join as XP}from"path";function Oc(e){return Mc.test(e)}var Mc=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|CHANGELOG(?:\.[a-z]+)?|.*\.map)$|(?:^|\/)(?:dist|build|out|node_modules|docs\/plans)\//i;function Fn(e,t,n={}){let{minTogether:r=4,minConfidence:i=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=nn(e),c=t!==void 0,l=Xp(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=ce(e),d=tf(e),m=Hc(e,u,d),p=n.includeLinked===!0||c,g=[];for(let y of l){if(Mc.test(y.fileA)||Mc.test(y.fileB)||!Yp(e,y.fileA)||!Yp(e,y.fileB)||c&&!y.fileA.includes(t)&&!y.fileB.includes(t)||!c&&(J(y.fileA)==="test"||J(y.fileB)==="test"||QP(y.fileA,y.fileB)))continue;let h=m(y.fileA,y.fileB);if(!p&&h)continue;let x=jc(y.fileA,y.fileB),v=Bc(y,x,h);if(g.push({...y,structurallyLinked:h,partnerClass:x.partnerClass,partnerClassReasons:x.reasons,...v?{declaredCouplingSuggestion:v}:{}}),g.length>=o)break}return{available:!0,commitsAnalyzed:a.commits.length,findings:g}}function Yp(e,t){return KP(XP(e.config.projectRoot,t))}function jc(e,t){let n=Zp(e),r=Zp(t),i=[],o=c=>{i.includes(c)||i.push(c)},s=(c,l)=>n.tags.has(c)&&r.tags.has(l)||n.tags.has(l)&&r.tags.has(c);if(s("doc","code"))return o("one side is documentation and the other is executable source"),{partnerClass:"doc-code",reasons:i};if(n.tags.has("test")||r.tags.has("test"))return o("one side is classified as a test file"),{partnerClass:"test-code",reasons:i};if(s("schema","script"))return o("schema or contract file changes with a script or generated-code path"),{partnerClass:"schema-script",reasons:i};if(s("model","view"))return o("model or state path changes with a view or component path"),{partnerClass:"model-view",reasons:i};if(s("config","code"))return o("configuration file changes with executable source"),{partnerClass:"config-code",reasons:i};let a=cN(n.tokens,r.tokens).filter(c=>!sN.has(c));return ef(e,t)||a.length>=2?(o(ef(e,t)?"both files live in the same directory":`files share feature tokens: ${a.slice(0,4).join(", ")}`),{partnerClass:"same-feature",reasons:i}):(o("no specific relationship pattern matched"),{partnerClass:"unknown",reasons:i})}function Bc(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!oN.has(t.partnerClass))return;let r=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${lN(r)}`,files:r,reason:`${t.partnerClass} pair changed together ${e.together}x with ${Math.round(e.confidence*100)}% confidence; declare it if future edits should require both sides.`}}function Hc(e,t=ce(e),n=tf(e)){return(r,i)=>YP(t,n,r,i)}function QP(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 tf(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function YP(e,t,n,r){return e.get(n)?.has(r)===!0||e.get(r)?.has(n)===!0?!0:t.some(i=>i.has(n)&&i.has(r))}var ZP=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,eN=/(?:^|\/)(?:\.[a-z0-9-]+rc|config|configs|settings|\.github)(?:\/|$)|(?:^|\/)(?:package\.json|tsconfig(?:\.[^.]+)?\.json|vite\.config\.[cm]?[jt]s|rollup\.config\.[cm]?[jt]s|eslint\.config\.[cm]?[jt]s)$|\.(?:json|ya?ml|toml|ini|env)$/i,tN=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,nN=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,rN=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,iN=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,oN=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),sN=new Set(["src","lib","app","test","tests","spec","index","main","utils","util","types","type","config","docs","doc"]);function Zp(e){let t=e.replace(/\\/g,"/"),n=new Set;return ZP.test(t)&&n.add("doc"),eN.test(t)&&n.add("config"),tN.test(t)&&n.add("schema"),nN.test(t)&&n.add("script"),rN.test(t)&&n.add("model"),iN.test(t)&&n.add("view"),J(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:aN(t)}}function ef(e,t){let n=e.lastIndexOf("/"),r=t.lastIndexOf("/"),i=n>=0?e.slice(0,n):"",o=r>=0?t.slice(0,r):"";return i!==""&&i===o}function aN(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).map(t=>t.toLowerCase()).filter(t=>t.length>=2)}function cN(e,t){let n=new Set(t);return[...new Set(e.filter(r=>n.has(r)))].sort()}function lN(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}import{execFileSync as ct}from"child_process";import{existsSync as uN,readFileSync as dN}from"fs";import{basename as nf}from"path";function rs(e){let t=new Map;for(let n of e){let r=t.get(n.file);r||(r=[],t.set(n.file,r)),r.push(n)}return t}var Vc="Unable to compute git diff.";function Dr(e,t={}){let n=t.plan??bt(e,t);return n.note?mN(n.note,n.changedFileLines):n.changedFiles.length===0?pN(n.changedFileLines):os(n.changedFiles,[is(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function bt(e,t={}){let{base:n="HEAD"}=t;try{let r=fN(e.config.projectRoot,n),i=vN(e,r),o=RN(e,gN(e.config.projectRoot,n));return{changedFileLines:r,changedFiles:i,changedRanges:o,renamedFiles:bN(e.config.projectRoot,n,i),note:r.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:Vc}}}function is(e,t,n,r=[]){let i=new F(e),o=new Set(n),s=rs(r),a=[],c=new Map,l=t.flatMap(g=>i.definitionsForFile(g)).filter(EN).filter(g=>wN(g,s)).sort((g,y)=>g.relativePath.localeCompare(y.relativePath)||g.startLine-y.startLine),u=l.map(g=>g.symbolId),d=DN(e,u),m=PN(e,u,n),p=Xe(e,l.filter(g=>d.get(g.symbolId)===0));for(let g of l)IN(e,g,o,a,c,p.get(g.symbolId)??new Set,d.get(g.symbolId)??0,m.get(g.symbolId)??new Set);return{changedSymbols:a,consumerEntries:[...c.entries()].map(([g,y])=>({file:g,symbols:[...y].sort()}))}}function os(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=NN(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:i,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:i.length}}}function mN(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function pN(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 fN(e,t){let n=ct("git",["diff","--name-only",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=ct("git",["diff","--name-only","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=ct("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([n,r,i].flatMap(o=>o.split(`
573
- `)).map(o=>o.trim()).filter(o=>o.length>0))]}function gN(e,t){let n=ct("git",["diff","--unified=0",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=ct("git",["diff","--unified=0","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return lf([...sf(n),...sf(r)])}function qc(e,t,n){try{return ct("git",["show",`${t}:./${n}`],{encoding:"utf-8",cwd:e,timeout:1e4,stdio:["ignore","pipe","ignore"]})}catch{return null}}function wi(e,t,n=[]){let r=hN(e,t,n);return i=>(r.has(i)||r.set(i,qc(e,t,i)),r.get(i)??null)}function Li(e,t=e.changedFiles){let n=new Map(e.renamedFiles.map(r=>[r.to,r.from]));return[...new Set(t.map(r=>n.get(r)??r))]}function hN(e,t,n){let r=[...new Set(n)],i=new Map;if(r.length===0)return i;try{let o=r.map(a=>`${t}:./${a}
574
- `).join(""),s=ct("git",["cat-file","--batch"],{cwd:e,input:o,maxBuffer:256*1024*1024,timeout:1e4,stdio:["pipe","pipe","ignore"]});return yN(s,r)}catch{for(let o of r)i.set(o,qc(e,t,o));return i}}function yN(e,t){let n=new Map,r=0;for(let i of t){let o=e.indexOf(10,r);if(o<0)throw new Error("git cat-file batch output ended before object header");let s=e.subarray(r,o).toString("utf-8");if(r=o+1,s.endsWith(" missing")){n.set(i,null);continue}let a=/^[0-9a-f]+ ([^ ]+) (\d+)$/.exec(s);if(!a)throw new Error(`unexpected git cat-file batch header: ${s}`);let[,c,l]=a,u=Number(l);if(!Number.isFinite(u)||u<0)throw new Error(`unexpected git cat-file batch size: ${s}`);if(r+u>e.length)throw new Error("git cat-file batch output ended before blob payload");let d=e.subarray(r,r+u);n.set(i,c==="blob"?d.toString("utf-8"):null),r+=u,e[r]===10&&(r+=1)}return n}function bN(e,t,n){if(n.length===0)return[];let r=new Map,i=new Set;for(let s of xN(e,t))n.includes(s.to)&&(r.set(s.to,s),i.add(s.from));let o=SN(e,t);if(o.length===0)return[...r.values()].sort((s,a)=>s.to.localeCompare(a.to));for(let s of n){if(r.has(s)||!uN(`${e}/${s}`))continue;let a=o.filter(u=>!i.has(u)).filter(u=>nf(u)===nf(s));if(a.length===0)continue;let c=dN(`${e}/${s}`,"utf-8"),l=a.map(u=>({from:u,to:s,similarity:CN(qc(e,t,u)??"",c)})).sort((u,d)=>d.similarity-u.similarity)[0];l&&l.similarity>=.45&&(r.set(s,l),i.add(l.from))}return[...r.values()].sort((s,a)=>s.to.localeCompare(a.to))}function SN(e,t){let n=ct("git",["diff","--name-only","--diff-filter=D",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=ct("git",["diff","--name-only","--diff-filter=D","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([...of(n),...of(r)])]}function xN(e,t){let n=ct("git",["diff","--name-status","--find-renames",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=ct("git",["diff","--name-status","--find-renames","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return[...n.split(`
575
- `),...r.split(`
576
- `)].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 CN(e,t){let n=new Set(rf(e)),r=new Set(rf(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 rf(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function of(e){return e.split(`
577
- `).map(t=>t.trim()).filter(t=>t.length>0)}function vN(e,t){let n=cf(e),r=[];for(let i of t){let o=n(i);o&&!e.isIgnored(o)&&r.push(o)}return r}function RN(e,t){let n=cf(e),r=[];for(let i of t){let o=n(i.file);o&&!e.isIgnored(o)&&r.push({...i,file:o})}return lf(r)}function cf(e){let t=e.all(`SELECT relative_path FROM documents
578
- 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 sf(e){let t=[],n=null;for(let r of e.split(`
579
- `)){if(r.startsWith("+++ ")){n=kN(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 kN(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function lf(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 wN(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(r=>LN(e.startLine,e.endLine,r.startLine,r.endLine))}function LN(e,t,n,r){return e<=r&&n<=t}function IN(e,t,n,r,i,o,s,a){let c=Math.max(s,o.size);if(!TN(t,c))return;let l=b(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)af(e,n,i,u,l);for(let u of o)af(e,n,i,u,l)}function DN(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
587
+ LIMIT 1`,t);return n?Q(e,n.relative_path).find(i=>i.symbol===t)??null:null}function GF(e,t,n){let i=Vn(e,t);if(i.length===0)return{removable:!1,blockingFiles:[]};let r=new Set;for(let o of i)o.file===t.relativePath&&o.line>=t.startLine&&o.line<=t.endLine||n.contains(o.file,o.line)||r.add(o.file);return{removable:r.size===0,blockingFiles:[...r]}}function Fg(e,t,n,i){let r=[...n].sort((a,c)=>a.file.localeCompare(c.file)||a.startLine-c.startLine),o=new Set(r.map(a=>a.file)),s=[];for(let a of o){let c=Q(e,a);c.length>0&&c.every(l=>i.contains(a,l.startLine))&&s.push(a)}return{depth:t,entries:r.map(({definition:a,...c})=>c),loc:r.reduce((a,c)=>a+c.loc,0),filesEmptied:s.sort()}}var kl=class{ranges=new Map;add(t){let n=this.ranges.get(t.file)??[];n.push({start:t.startLine,end:t.endLine}),this.ranges.set(t.file,n)}contains(t,n){let i=this.ranges.get(t);return i?i.some(r=>n>=r.start&&n<=r.end):!1}};import{createHash as kA}from"crypto";import{existsSync as xh}from"fs";import{execFileSync as KF}from"child_process";var Es=2e3,Ns=50,JF=64,XF=8,QF=3,YF=2160*60*60,ZF=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,eT=3,tT=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,nT=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function wl(e){let t=ie(e,{clearGroups:["whole-project"]});return(n,i)=>{let r=Pl(n.config.projectRoot);if(!r)return null;let o=t.has(n)?t.get(n,()=>({head:"",value:null})):null;return o&&o.head===r?o.value:(t.invalidate(n),t.get(n,()=>({head:r,value:i(n.config.projectRoot,r)})).value)}}function $g(e){let t=ie(e,{clearGroups:["whole-project"]});return(n,i,r)=>{let o=Pl(n.config.projectRoot);if(!o)return null;let s=t.has(n)?t.get(n,()=>({head:"",values:new Map})):null;(!s||s.head!==o)&&t.invalidate(n);let a=t.get(n,()=>({head:o,values:new Map}));if(a.values.has(i))return a.values.get(i)??null;let c=r(n.config.projectRoot,o);return a.values.set(i,c),c}}var iT=wl("git-commit-history");function Xe(e){return{capability:t=>rT(e,t),commitHistory:()=>Gr(e),fileChurn:()=>aT(e),changeAmplification:()=>cT(e),trackedFiles:()=>uT(e),fileAddRecords:()=>mT(e),coChangePairs:(t={})=>bT(e,t),coChangePairsForFiles:(t,n={})=>Og(e,t,n),directionalCoChangePairsForFiles:(t,n={})=>ST(e,t,n)}}function Gr(e){return iT(e,oT)}function rT(e,t){let n=Pl(e.config.projectRoot);return n?{slot:t,available:!0,head:n}:{slot:t,available:!1,head:null,reason:"git history is unavailable for this project"}}function Pl(e){try{return xn(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function xn(e,t){return KF("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]})}function oT(e,t){let n;try{n=xn(e,["log","--no-merges","--name-only","-n",String(Es),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}return{head:t,...Dl(n,Ns)}}function sT(e){return ZF.test(e.subject)}function aT(e){let t=Gr(e);if(!t)return null;let n=new Map;for(let i of t.commits){let r=sT(i);for(let o of i.files){let s=n.get(o)??{changes:0,fixChanges:0,lastChangedAt:0};s.changes+=1,r&&(s.fixChanges+=1),i.timestamp>s.lastChangedAt&&(s.lastChangedAt=i.timestamp),n.set(o,s)}}return n}function cT(e){let t=Gr(e);if(!t||t.commits.length===0)return null;let n=t.commits.map(i=>i.files.length).filter(i=>i>0).sort((i,r)=>i-r);return n.length===0?null:{medianFilesPerCommit:_g(n,.5),p90FilesPerCommit:_g(n,.9),commitsAnalyzed:n.length}}function _g(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var lT=wl("git-tracked-files");function uT(e){return lT(e,t=>{try{let n=xn(t,["ls-files"]);return new Set(n.split(`
588
+ `).map(i=>i.trim()).filter(i=>i!==""))}catch{return null}})}var dT=wl("git-file-adds"),Ag="__git__/file-adds",Mg=pe({kind:"git-file-adds",serialize:fT,deserialize:gT});function mT(e){return dT(e,(t,n)=>pT(e,t,n))}function pT(e,t,n){let i=Mg.read(e,Ag,n);if(i)return i;let r=hT(t);return r&&Mg.write(e,Ag,n,r),r}function fT(e){return JSON.stringify([...e.entries()])}function gT(e){if(!e)return null;try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=new Map;for(let i of t){if(!Array.isArray(i)||i.length!==2||typeof i[0]!="string")return null;let r=i[1];if(!r||typeof r.commitsAgo!="number"||!Number.isFinite(r.commitsAgo)||typeof r.addedAt!="number"||!Number.isFinite(r.addedAt))return null;n.set(i[0],{commitsAgo:r.commitsAgo,addedAt:r.addedAt})}return n}catch{return null}}function hT(e){let t;try{t=xn(e,["log","--no-merges","--diff-filter=A","--name-only","-n",String(Es),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let n=new Map,i=-1;for(let r of t.split("")){if(r.trim()==="")continue;i+=1;let o=r.indexOf(`
589
+ `),s=o>=0?r.slice(0,o):r,[,a]=s.split("\0"),c=Number(a)||0;if(!(o<0))for(let l of r.slice(o+1).split(`
590
+ `)){let d=l.trim();d!==""&&n.set(d,{commitsAgo:i,addedAt:c})}}return n}var jg=$g("git-co-change-pairs"),yT=$g("git-directional-co-change-pairs");function bT(e,t){let n=`all\0${Il(t)}`,i=jg(e,n,()=>{let r=Gr(e);return r?Ll(r,t):null});return i&&[...i]}function Og(e,t,n){if(t.size===0)return[];let i=`files\0${Bg(t)}\0${Il(n)}`,r=jg(e,i,()=>{let o=Gr(e);return o?Ll(o,n,t):null});return r&&[...r]}function ST(e,t,n){if(t.size===0)return[];let i=n.maxFilesPerCommit??Ns;if(t.size>JF)return Og(e,t,n);let r=`directional\0${Bg(t)}\0${Il({...n,maxFilesPerCommit:i})}`,o=yT(e,r,(s,a)=>{let c=xT(s,a,t,i);return c?Ll(c,n,t):null});return o&&[...o]}function Il(e){let t=e.minTogether??4,n=e.minConfidence??.6,i=e.maxFilesPerCommit??Ns;return`${t}\0${n}\0${i}`}function Bg(e){return[...e].sort().join("\0")}function Ll(e,t,n){let{minTogether:i=4,minConfidence:r=.6,maxFilesPerCommit:o=Ns}=t,s=new Map,a=new Map,c=e.newestAnalyzedAt??0;for(let u of e.commits){let m=[...new Set(u.files)].sort();if(m.length>o)continue;e.newestAnalyzedAt===void 0&&u.timestamp>c&&(c=u.timestamp);let p=RT(m),f=n===void 0||m.some(g=>n.has(g));for(let g of m)s.set(g,(s.get(g)??0)+1);if(f)for(let g=0;g<m.length;g++)for(let b=g+1;b<m.length;b++){if(n&&!n.has(m[g])&&!n.has(m[b]))continue;let x=`${m[g]}\0${m[b]}`,S=a.get(x)??{together:0,focusedTogether:0,broadTogether:0,lastTogetherAt:0,timestamps:[],subjects:[]};S.together+=1,p?S.broadTogether+=1:S.focusedTogether+=1,u.timestamp>S.lastTogetherAt&&(S.lastTogetherAt=u.timestamp),S.timestamps.push(u.timestamp),S.subjects.push(u.subject),a.set(x,S)}}let l=[],d=c-YF;for(let[u,m]of a){let p=m.together;if(p<i)continue;let[f,g]=u.split("\0"),b=s.get(f)??p,x=s.get(g)??p,S=Math.max(p/b,p/x);if(S<r)continue;let R=m.broadTogether/p,C=m.timestamps.filter(y=>y>=d).length;l.push({fileA:f,fileB:g,together:p,confidence:S,changesA:b,changesB:x,focusedTogether:m.focusedTogether,broadTogether:m.broadTogether,broadCommitRatio:R,lastTogetherAt:m.lastTogetherAt,recentTogether:C,commitScope:wT(m.broadTogether,p),recency:C>0?"recent":"stale",subjectContext:PT(m.subjects)})}return l.sort((u,m)=>m.together-u.together||m.confidence-u.confidence||u.fileA.localeCompare(m.fileA)),l}function xT(e,t,n,i){let r;try{r=CT(e)}catch{return null}if(r.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:0};let o;try{o=xn(e,["log","--no-merges","--format=%H","-n",String(Es),"--",...[...n].sort()])}catch{return null}let s=new Set(r.map(u=>u.hash)),a=o.split(`
591
+ `).map(u=>u.trim()).filter(u=>u!==""&&s.has(u)),c=vT(e,r,i);if(a.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:c};let l;try{l=xn(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...a])}catch{return null}let d=Dl(l,i);return{head:t,...d,newestAnalyzedAt:c}}function CT(e){return xn(e,["log","--no-merges","--format=%H%x00%ct","-n",String(Es)]).split(`
592
+ `).map(n=>n.trim()).filter(n=>n!=="").map(n=>{let[i,r]=n.split("\0");return{hash:i??"",timestamp:Number(r)||0}}).filter(n=>n.hash!=="")}function vT(e,t,n){for(let r=0;r<t.length;r+=20){let o=t.slice(r,r+20),s;try{s=xn(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...o.map(c=>c.hash)])}catch{return t[0]?.timestamp??0}let a=Dl(s,n);if(a.commits.length>0)return a.commits[0].timestamp}return 0}function Dl(e,t){let n=[],i=0;for(let r of e.split("")){if(r.trim()==="")continue;let o=r.indexOf(`
593
+ `),s=o>=0?r.slice(0,o):r,[a,c,l]=s.split("\0");if(!a||!c)continue;let d=o>=0?r.slice(o+1).split(`
594
+ `).map(u=>u.trim()).filter(u=>u!==""):[];if(d.length>t){i+=1;continue}n.push({hash:a,timestamp:Number(c)||0,subject:l??"",files:d})}return{commits:n,skippedBulkCommits:i}}function RT(e){return e.length>=XF?!0:kT(e).size>=QF}function kT(e){let t=new Set;for(let n of e){let i=n.indexOf("/");t.add(i>=0?n.slice(0,i):".")}return t}function wT(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function PT(e){let t=new Set,n=[],i=[];for(let r of e){!i.includes(r)&&i.length<eT&&i.push(r);for(let o of IT(r))t.add(o);for(let o of r.match(tT)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:i,externalIssueLabelStatus:"unavailable"}}function IT(e){let t=new Set,n=nT.exec(e)?.[1]?.toLowerCase();return n&&t.add(LT(n)),/\b(?:feat|feature)\b/i.test(e)&&t.add("feature"),/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i.test(e)&&t.add("fix"),/\b(?:docs?|documentation|guide|readme)\b/i.test(e)&&t.add("docs"),/\brefactor(?:ing|ed)?\b/i.test(e)&&t.add("refactor"),/\btests?\b/i.test(e)&&t.add("test"),/\b(?:release|version|v\d+\.\d+)\b/i.test(e)&&t.add("release"),/\bchore\b/i.test(e)&&t.add("chore"),/\bbuild\b/i.test(e)&&t.add("build"),/\bci\b/i.test(e)&&t.add("ci"),/\bperf(?:ormance)?\b/i.test(e)&&t.add("perf"),[...t]}function LT(e){return e==="feat"?"feature":e}import{existsSync as DT}from"fs";import{join as ET}from"path";function Nl(e){return El.test(e)}var El=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|CHANGELOG(?:\.[a-z]+)?|.*\.map)$|(?:^|\/)(?:dist|build|out|node_modules|docs\/plans)\//i;function Zn(e,t,n={}){let{minTogether:i=4,minConfidence:r=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=Xe(e),c=a.commitHistory(),l=t!==void 0,d=a.coChangePairs({minTogether:l?Math.min(i,2):i,minConfidence:l?0:r,maxFilesPerCommit:s});if(!c||!d)return{available:!1,commitsAnalyzed:0,findings:[]};let u=ye(e),m=Ug(e),p=_l(e,u,m),f=n.includeLinked===!0||l,g=[];for(let b of d){if(El.test(b.fileA)||El.test(b.fileB)||!Hg(e,b.fileA)||!Hg(e,b.fileB)||l&&!b.fileA.includes(t)&&!b.fileB.includes(t)||!l&&(Z(b.fileA)==="test"||Z(b.fileB)==="test"||NT(b.fileA,b.fileB)))continue;let x=p(b.fileA,b.fileB);if(!f&&x)continue;let S=Fl(b.fileA,b.fileB),R=Tl(b,S,x);if(g.push({...b,structurallyLinked:x,partnerClass:S.partnerClass,partnerClassReasons:S.reasons,...R?{declaredCouplingSuggestion:R}:{}}),g.length>=o)break}return{available:!0,commitsAnalyzed:c.commits.length,findings:g}}function Hg(e,t){return DT(ET(e.config.projectRoot,t))}function Fl(e,t){let n=Vg(e),i=Vg(t),r=[],o=c=>{r.includes(c)||r.push(c)},s=(c,l)=>n.tags.has(c)&&i.tags.has(l)||n.tags.has(l)&&i.tags.has(c);if(s("doc","code"))return o("one side is documentation and the other is executable source"),{partnerClass:"doc-code",reasons:r};if(n.tags.has("test")||i.tags.has("test"))return o("one side is classified as a test file"),{partnerClass:"test-code",reasons:r};if(s("schema","script"))return o("schema or contract file changes with a script or generated-code path"),{partnerClass:"schema-script",reasons:r};if(s("model","view"))return o("model or state path changes with a view or component path"),{partnerClass:"model-view",reasons:r};if(s("config","code"))return o("configuration file changes with executable source"),{partnerClass:"config-code",reasons:r};let a=VT(n.tokens,i.tokens).filter(c=>!BT.has(c));return qg(e,t)||a.length>=2?(o(qg(e,t)?"both files live in the same directory":`files share feature tokens: ${a.slice(0,4).join(", ")}`),{partnerClass:"same-feature",reasons:r}):(o("no specific relationship pattern matched"),{partnerClass:"unknown",reasons:r})}function Tl(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!OT.has(t.partnerClass))return;let i=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${qT(i)}`,files:i,reason:`${t.partnerClass} pair changed together ${e.together}x with ${Math.round(e.confidence*100)}% confidence; declare it if future edits should require both sides.`}}function _l(e,t=ye(e),n=Ug(e)){return(i,r)=>FT(t,n,i,r)}function NT(e,t){let n=e.lastIndexOf("/"),i=t.lastIndexOf("/");if(e.slice(0,n)!==t.slice(0,i))return!1;let r=e.slice(n+1).split(".")[0],o=t.slice(i+1).split(".")[0];return r!==""&&r===o}function Ug(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function FT(e,t,n,i){return e.get(n)?.has(i)===!0||e.get(i)?.has(n)===!0?!0:t.some(r=>r.has(n)&&r.has(i))}var TT=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,_T=/(?:^|\/)(?:\.[a-z0-9-]+rc|config|configs|settings|\.github)(?:\/|$)|(?:^|\/)(?:package\.json|tsconfig(?:\.[^.]+)?\.json|vite\.config\.[cm]?[jt]s|rollup\.config\.[cm]?[jt]s|eslint\.config\.[cm]?[jt]s)$|\.(?:json|ya?ml|toml|ini|env)$/i,AT=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,MT=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,$T=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,jT=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,OT=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),BT=new Set(["src","lib","app","test","tests","spec","index","main","utils","util","types","type","config","docs","doc"]);function Vg(e){let t=e.replace(/\\/g,"/"),n=new Set;return TT.test(t)&&n.add("doc"),_T.test(t)&&n.add("config"),AT.test(t)&&n.add("schema"),MT.test(t)&&n.add("script"),$T.test(t)&&n.add("model"),jT.test(t)&&n.add("view"),Z(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:HT(t)}}function qg(e,t){let n=e.lastIndexOf("/"),i=t.lastIndexOf("/"),r=n>=0?e.slice(0,n):"",o=i>=0?t.slice(0,i):"";return r!==""&&r===o}function HT(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).map(t=>t.toLowerCase()).filter(t=>t.length>=2)}function VT(e,t){let n=new Set(t);return[...new Set(e.filter(i=>n.has(i)))].sort()}function qT(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}import{execFileSync as bt}from"child_process";import{existsSync as UT,readFileSync as zT}from"fs";import{basename as zg}from"path";function Fs(e){let t=new Map;for(let n of e){let i=t.get(n.file);i||(i=[],t.set(n.file,i)),i.push(n)}return t}var Al="Unable to compute git diff.";function Ui(e,t={}){let n=t.plan??Tt(e,t);return n.note?WT(n.note,n.changedFileLines):n.changedFiles.length===0?GT(n.changedFileLines):_s(n.changedFiles,[Ts(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function Tt(e,t={}){let{base:n="HEAD"}=t;try{let i=KT(e.config.projectRoot,n),r=n0(e,i),o=i0(e,JT(e.config.projectRoot,n));return{changedFileLines:i,changedFiles:r,changedRanges:o,renamedFiles:YT(e.config.projectRoot,n,r),note:i.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:Al}}}function Ts(e,t,n,i=[]){let r=new A(e),o=new Set(n),s=Fs(i),a=[],c=new Map,l=t.flatMap(f=>r.definitionsForFile(f)).filter(d0).filter(f=>o0(f,s)).sort((f,g)=>f.relativePath.localeCompare(g.relativePath)||f.startLine-g.startLine),d=l.map(f=>f.symbolId),u=c0(e,d),m=l0(e,d,n),p=st(e,l.filter(f=>u.get(f.symbolId)===0));for(let f of l)a0(e,f,o,a,c,p.get(f.symbolId)??new Set,u.get(f.symbolId)??0,m.get(f.symbolId)??new Set);return{changedSymbols:a,consumerEntries:[...c.entries()].map(([f,g])=>({file:f,symbols:[...g].sort()}))}}function _s(e,t){let n=new Map,i=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 r=u0(n);return{changedFiles:[...e],changedSymbols:i,affectedConsumers:r,summary:{totalChangedFiles:e.length,totalChangedSymbols:i.length,totalAffectedFiles:r.length}}}function WT(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function GT(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 KT(e,t){let n=bt("git",["diff","--name-only",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=bt("git",["diff","--name-only","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=bt("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([n,i,r].flatMap(o=>o.split(`
595
+ `)).map(o=>o.trim()).filter(o=>o.length>0))]}function JT(e,t){let n=bt("git",["diff","--unified=0",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=bt("git",["diff","--unified=0","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return Qg([...Kg(n),...Kg(i)])}function Ml(e,t,n){try{return bt("git",["show",`${t}:./${n}`],{encoding:"utf-8",cwd:e,timeout:1e4,stdio:["ignore","pipe","ignore"]})}catch{return null}}function Kr(e,t,n=[]){let i=XT(e,t,n);return r=>(i.has(r)||i.set(r,Ml(e,t,r)),i.get(r)??null)}function Jr(e,t=e.changedFiles){let n=new Map(e.renamedFiles.map(i=>[i.to,i.from]));return[...new Set(t.map(i=>n.get(i)??i))]}function XT(e,t,n){let i=[...new Set(n)],r=new Map;if(i.length===0)return r;try{let o=i.map(a=>`${t}:./${a}
596
+ `).join(""),s=bt("git",["cat-file","--batch"],{cwd:e,input:o,maxBuffer:256*1024*1024,timeout:1e4,stdio:["pipe","pipe","ignore"]});return QT(s,i)}catch{for(let o of i)r.set(o,Ml(e,t,o));return r}}function QT(e,t){let n=new Map,i=0;for(let r of t){let o=e.indexOf(10,i);if(o<0)throw new Error("git cat-file batch output ended before object header");let s=e.subarray(i,o).toString("utf-8");if(i=o+1,s.endsWith(" missing")){n.set(r,null);continue}let a=/^[0-9a-f]+ ([^ ]+) (\d+)$/.exec(s);if(!a)throw new Error(`unexpected git cat-file batch header: ${s}`);let[,c,l]=a,d=Number(l);if(!Number.isFinite(d)||d<0)throw new Error(`unexpected git cat-file batch size: ${s}`);if(i+d>e.length)throw new Error("git cat-file batch output ended before blob payload");let u=e.subarray(i,i+d);n.set(r,c==="blob"?u.toString("utf-8"):null),i+=d,e[i]===10&&(i+=1)}return n}function YT(e,t,n){if(n.length===0)return[];let i=new Map,r=new Set;for(let s of e0(e,t))n.includes(s.to)&&(i.set(s.to,s),r.add(s.from));let o=ZT(e,t);if(o.length===0)return[...i.values()].sort((s,a)=>s.to.localeCompare(a.to));for(let s of n){if(i.has(s)||!UT(`${e}/${s}`))continue;let a=o.filter(d=>!r.has(d)).filter(d=>zg(d)===zg(s));if(a.length===0)continue;let c=zT(`${e}/${s}`,"utf-8"),l=a.map(d=>({from:d,to:s,similarity:t0(Ml(e,t,d)??"",c)})).sort((d,u)=>u.similarity-d.similarity)[0];l&&l.similarity>=.45&&(i.set(s,l),r.add(l.from))}return[...i.values()].sort((s,a)=>s.to.localeCompare(a.to))}function ZT(e,t){let n=bt("git",["diff","--name-only","--diff-filter=D",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=bt("git",["diff","--name-only","--diff-filter=D","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([...Gg(n),...Gg(i)])]}function e0(e,t){let n=bt("git",["diff","--name-status","--find-renames",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=bt("git",["diff","--name-status","--find-renames","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return[...n.split(`
597
+ `),...i.split(`
598
+ `)].map(r=>r.trim()).filter(r=>r.startsWith("R")).map(r=>r.split(" ")).filter(r=>r.length>=3).map(([r,o,s])=>({from:o,to:s,similarity:Number(r.slice(1))/100}))}function t0(e,t){let n=new Set(Wg(e)),i=new Set(Wg(t));if(n.size===0&&i.size===0)return 1;if(n.size===0||i.size===0)return 0;let r=0;for(let o of n)i.has(o)&&(r+=1);return 2*r/(n.size+i.size)}function Wg(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function Gg(e){return e.split(`
599
+ `).map(t=>t.trim()).filter(t=>t.length>0)}function n0(e,t){let n=Xg(e),i=[];for(let r of t){let o=n(r);o&&!e.isIgnored(o)&&i.push(o)}return i}function i0(e,t){let n=Xg(e),i=[];for(let r of t){let o=n(r.file);o&&!e.isIgnored(o)&&i.push({...r,file:o})}return Qg(i)}function Xg(e){let t=e.all(`SELECT relative_path FROM documents
600
+ ORDER BY id`).map(i=>i.relative_path),n=new Map(t.map(i=>[i,i]));return i=>{let r=i.replace(/\\/g,"/"),o=n.get(r);return o||(t.find(s=>s.endsWith(r))??null)}}function Kg(e){let t=[],n=null;for(let i of e.split(`
601
+ `)){if(i.startsWith("+++ ")){n=r0(i.slice(4).trim());continue}if(!n||!i.startsWith("@@ "))continue;let r=/@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(i);if(!r)continue;let o=Math.max(0,Number(r[1])-1),s=r[2]===void 0?1:Number(r[2]);t.push({file:n,startLine:o,endLine:Math.max(o,o+Math.max(s,1)-1)})}return t}function r0(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function Qg(e){let t=new Set,n=[];for(let i of e){let r=`${i.file}:${i.startLine}:${i.endLine}`;t.has(r)||(t.add(r),n.push(i))}return n}function o0(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(i=>s0(e.startLine,e.endLine,i.startLine,i.endLine))}function s0(e,t,n,i){return e<=i&&n<=t}function a0(e,t,n,i,r,o,s,a){let c=Math.max(s,o.size);if(!m0(t,c))return;let l=v(t.symbol);i.push({symbol:t.symbol,shortName:l,file:t.relativePath,startLine:t.startLine,endLine:t.endLine,fanIn:c});for(let d of a)Jg(e,n,r,d,l);for(let d of o)Jg(e,n,r,d,l)}function c0(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
580
602
  FROM mentions m
581
603
  JOIN chunks c ON m.chunk_id = c.id
582
604
  WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
583
605
  AND m.role != 1
584
- GROUP BY m.symbol_id`,...t);return new Map(n.map(r=>[r.symbol_id,r.fan_in]))}function PN(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
606
+ GROUP BY m.symbol_id`,...t);return new Map(n.map(i=>[i.symbol_id,i.fan_in]))}function l0(e,t,n){if(t.length===0||n.length===0)return new Map;let i=e.all(`SELECT DISTINCT m.symbol_id, ref_d.relative_path
585
607
  FROM mentions m
586
608
  JOIN chunks c ON m.chunk_id = c.id
587
609
  JOIN documents ref_d ON c.document_id = ref_d.id
588
610
  WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
589
611
  AND m.role != 1
590
612
  AND ref_d.relative_path NOT IN (${n.map(()=>"?").join(",")})
591
- ${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 af(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 NN(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function EN(e){return!(Vt(e.symbol)||e.parentTypeName!==null&&!ie(e.symbol))}function TN(e,t){return ie(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}function uf(e){let[t,n]=ss(e,":"),r=t||"unknown",i=(o={})=>{let s=o.actionTier??_N(r);return{sourceAnalyzer:r,actionTier:s,rootCauseKey:o.rootCauseKey??(n||e),label:o.label??`${r} finding`,relatedFiles:o.relatedFiles??[],why:o.why??[],remediation:o.remediation??FN(s,r),file:o.file}};if(!n)return i({rootCauseKey:e,why:["Baseline identity did not include analyzer payload."]});if(["dead","isolated","extract","wrapper","passthrough","stale"].includes(r)){let[o,s]=ss(n,":");return i({file:o,relatedFiles:o?[o]:[],rootCauseKey:s?`${o}:${s}`:n,label:`${r} finding`,why:s?[`Baseline subject: ${s}.`]:[]})}if(r==="cycle"){let o=n.split(">").filter(Boolean);return i({relatedFiles:o,rootCauseKey:n,label:"cycle finding",why:o.length>0?[`Cycle path: ${o.join(" > ")}.`]:[]})}if(r==="similar"){let o=n.split("|").filter(Boolean);return i({relatedFiles:[],rootCauseKey:n,label:"similarity finding",why:o.length>0?[`Similar symbols: ${o.join(" | ")}.`]:[]})}if(r==="drift"){let[o,s]=ss(n,":"),[a,c]=ss(s,":");return i({actionTier:o==="unused-import"?"direct":"signal",file:a,relatedFiles:[...new Set([a,c].filter(Boolean))],rootCauseKey:n,label:`${o||"drift"} finding`,why:[...o?[`Drift kind: ${o}.`]:[],...c?[`Related dependency: ${c}.`]:[]]})}return i({why:["Baseline analyzer prefix is not recognized by this diff-gate version."]})}function _N(e){switch(e){case"dead":case"isolated":case"cycle":case"passthrough":return"direct";case"similar":case"extract":case"wrapper":case"stale":return"signal";default:return"signal"}}function FN(e,t){return e==="direct"?`Fix the new ${t} baseline finding, or knowingly accept it via health --write-baseline.`:`Review the new ${t} baseline signal; fix it if it reflects real debt, or knowingly accept it via health --write-baseline.`}function ss(e,t){let n=e.indexOf(t);return n<0?[e,""]:[e.slice(0,n),e.slice(n+t.length)]}import{existsSync as BN,readFileSync as pf}from"fs";function ls(e,t){let n=AN(e,t)??$N(e,t)??MN(e,t)??ON(e,t);return jN(e,n,t)}function AN(e,t){let n=-1,r=null;for(let i=0;i<=t;i+=1){let o=Uc(e[i]??"");o&&(r===null?(r=o,n=i):o===r&&(r=null,n=-1))}if(r===null||n<0)return null;for(let i=t+1;i<e.length;i+=1)if(Uc(e[i]??"")===r)return{start:n,end:i+1};return{start:n,end:e.length}}function Uc(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function $N(e,t){if(!as(e[t]??""))return null;let n=t;for(;n>0&&as(e[n-1]??"");)n-=1;let r=t+1;for(;r<e.length&&as(e[r]??"");)r+=1;return{start:n,end:r}}function as(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function MN(e,t){let n=t;for(;n>=0;){let o=e[n]??"";if(cs(o)!==null)break;if(Wc(o)!==null)return null;n-=1}if(n<0)return null;let r=cs(e[n]??"");if(r===null)return null;let i=n+1;for(;i<e.length;){let o=e[i]??"",s=cs(o);if(s!==null){if(s<=r)break;i+=1;continue}if(Wc(o)!==null)break;i+=1}return{start:n,end:i}}function cs(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function ON(e,t){let n=e[t]??"";if(mf(n)||n.trim().length===0)return{start:t,end:t+1};let r=t;for(;r>0&&df(e[r-1]??"");)r-=1;let i=t+1;for(;i<e.length&&df(e[i]??"");)i+=1;return{start:r,end:i}}function df(e){return Wc(e)===null}function Wc(e){return e.trim().length===0?"blank":mf(e)?"heading":Uc(e)?"fence":as(e)?"table":cs(e)!==null?"list":null}function mf(e){return/^#{1,6}\s+/.test(e.trim())}function jN(e,t,n){let{start:r,end:i}=t;if(i-r>40){let s=Math.floor(20);r=Math.max(r,n-s),i=Math.min(i,r+40),r=Math.max(t.start,i-40)}let o=e.slice(r,i).join(`
592
- `).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}function An(e,t){return t.filter(n=>e.includes(n))}var Pr={classifyCitation:HN,citationContexts:VN,citationKindLabel:UN,citationRemediation:WN,referenceTargets:GN};function HN(e){let t=e.join(`
593
- `).toLowerCase(),n=[],r=An(t,[".scipquery","declaredcouplings","suppression","suppressions","config","configuration","json"]);if(r.length>0)return n.push(`configuration/example terms near citation: ${r.join(", ")}`),{citationKind:"configuration-example",actionTier:"support",reasons:n};let i=An(t,["accepted","intentional","intentionally","retained","historical"]);if(i.length>0)return n.push(`intentional-record terms near citation: ${i.join(", ")}`),{citationKind:"intentional-record",actionTier:"support",reasons:n};let o=An(t,["command","cli","usage","example","run","workflow"]);return o.length>0?(n.push(`guide/reference terms near citation: ${o.join(", ")}`),{citationKind:"guide-reference",actionTier:"signal",reasons:n}):(n.push(e.length>0?"citation appears in prose without config or guide markers":"citation context unavailable"),{citationKind:"behavioral-claim",actionTier:"direct",reasons:n})}function VN(e,t,n){let r;try{r=pf(`${e.config.projectRoot}/${t}`,"utf-8").split(/\r?\n/)}catch{return[]}let i=n.flatMap(qN),o=[];for(let s=0;s<r.length;s+=1){let a=r[s]??"";i.some(c=>a.includes(c))&&o.push(ls(r,s))}return o}function qN(e){let t=e.split("/");return[e,`./${e}`,t.slice(-3).join("/"),t.slice(-2).join("/")].filter((n,r,i)=>n.length>0&&i.indexOf(n)===r)}function UN(e){switch(e){case"behavioral-claim":return"a behavioral doc claim";case"configuration-example":return"a configuration example";case"guide-reference":return"a guide reference";case"intentional-record":return"an intentional record"}}function WN(e,t){switch(e){case"behavioral-claim":return`Re-read ${t} and update the behavioral claim or citation.`;case"configuration-example":return`Verify the configuration example in ${t} still points at the intended file; update only if the example target changed.`;case"guide-reference":return`Verify the guide reference in ${t} still sends readers to the right implementation or command surface.`;case"intentional-record":return`Verify the intentional citation in ${t} is still meant to name this file.`}}function GN(e,t,n){let r=rs(n),i=new Set;for(let o of t)zN(e,o,r.get(o)??[])&&i.add(o);return i}function zN(e,t,n){if(n.length===0)return!1;if(!JN.test(t))return!0;let r=`${e.config.projectRoot}/${t}`;if(!BN(r))return!0;let i=pf(r,"utf-8").split(/\r?\n/),o=KN(i);for(let s of n)for(let a=s.startLine;a<=s.endLine;a+=1)if((i[a]??"").trim()!==""&&!o.has(a))return!0;return!1}var JN=/\.(?:[cm]?[jt]sx?)$/i;function KN(e){let t=new Set,n=!1;for(let r=0;r<e.length;r+=1){let i=e[r].trim();!n&&XN(i)&&(n=!0),n&&(t.add(r),i.endsWith(";")&&(n=!1))}return t}function XN(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}import{existsSync as ff,readFileSync as gf}from"fs";import{join as ds}from"path";var Ii=/\.(?:md|mdx|rst|txt)$/i;function QN(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var YN=3,ZN=/[A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6}\b/g;function zc(e,t={}){let{doc:n,limit:r=20,minCoupling:i=YN}=t,o=nE(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&&!yf(e,a)||n!==void 0&&!ff(ds(e.config.projectRoot,a)))continue;let c=Math.max(0,...o.changeTimes.get(a)??[]),l=eE(e,a),u=new Map,{resolved:d,broken:m,citations:p}=oE(e,a,o.tracked,o.trackedBySuffix,o.everSeenInHistory),g=new Map(p.map(h=>[h.file,h.contexts]));for(let h of d){if(h===a||Ii.test(h))continue;let x=(o.changeTimes.get(h)??[]).filter(v=>v>c).length;x!==0&&u.set(h,{file:h,evidence:"reference",coChanges:0,changesSinceDocUpdate:x,...Gc("reference",l),citationContexts:g.get(h)})}for(let[h,x]of o.coupling.get(a)??[]){if(x<i||!o.tracked.has(h))continue;let v=(o.changeTimes.get(h)??[]).filter(L=>L>c).length;if(v===0)continue;let R=u.get(h);R?(R.evidence="both",R.coChanges=x,Object.assign(R,Gc("both",l))):u.set(h,{file:h,evidence:"co-change",coChanges:x,changesSinceDocUpdate:v,...Gc("co-change",l)})}if(u.size===0&&m.length===0)continue;let y=[...u.values()].sort((h,x)=>x.changesSinceDocUpdate-h.changesSinceDocUpdate);s.push({doc:a,docLastChangedAt:c,staleness:y.reduce((h,x)=>h+x.changesSinceDocUpdate,0)+m.length*10,subjects:y.slice(0,8),brokenReferences:m})}return s.sort((a,c)=>c.staleness-a.staleness),{available:!0,commitsAnalyzed:o.historyCommitCount,docsScanned:o.docFiles.length,findings:s.slice(0,r)}}function eE(e,t){let n;try{n=gf(ds(e.config.projectRoot,t),"utf8").slice(0,6e3)}catch{return{docIntent:"unknown",reasons:["doc text unavailable"]}}let r=`${t}
594
- ${n}`.toLowerCase(),i=An(r,["historical note","historical record","history note","retrospective","postmortem","post-mortem","archived","archive","previously","legacy","recorded","record of","snapshot","as of","migration note","decision record"]);if(i.length>0)return{docIntent:"historical-note",reasons:[`historical-note terms: ${i.join(", ")}`]};let o=An(r,["current","standard","standards","must","should","policy","guide","guidance","workflow","contract","invariant","source of truth"]);return o.length>0?{docIntent:"current-guidance",reasons:[`current-guidance terms: ${o.join(", ")}`]}:{docIntent:"unknown",reasons:["no current-guidance or historical-note markers found"]}}function Gc(e,t){return{actionTier:tE(e,t.docIntent),docIntent:t.docIntent,docIntentReasons:t.reasons}}function tE(e,t){return t==="historical-note"?"support":e==="co-change"?"signal":"direct"}function nE(e){let t=nn(e);if(!t)return null;let n=Fc(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=>Ii.test(u)),l=a.filter(u=>!Ii.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=>Ii.test(s)),everSeenInHistory:o,historyCommitCount:t.commits.length,tracked:n,trackedBySuffix:bf(n)}}function hf(e,t){if(t.size===0)return[];let n=Fc(e)??new Set,r=bf(n),i=rE(t,r),o=[];for(let s of n){if(!yf(e,s))continue;let a=Sf(e,s);if(!a)continue;let c=iE(a.candidates,t,i,n,r);if(c.size===0)continue;let l=[...new Set([...c.values()].flatMap(p=>[...p]))],u=sE(a.contextsByCandidate,l),d=[...c].map(([p,g])=>({file:p,contexts:us([...g].flatMap(y=>u.get(y)??[])).slice(0,3)})).filter(p=>p.contexts.length>0),m=[...c.keys()];if(m.length>0){let p=m.sort();o.push({doc:s,cited:p,citations:d,citedClaims:us(d.flatMap(g=>g.contexts)).slice(0,3)})}}return o}function yf(e,t){return Ii.test(t)&&!QN(t)&&ff(ds(e.config.projectRoot,t))}function bf(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 rE(e,t){let n=new Set(e);for(let r of e){let i=r.split("/");for(let o of[2,3]){if(i.length<o)continue;let s=i.slice(-o).join("/"),a=t.get(s);a?.length===1&&a[0]===r&&n.add(s)}}return n}function iE(e,t,n,r,i){let o=new Map;for(let s of e){if(!n.has(s))continue;let a;if(r.has(s))a=s;else{let l=i.get(s);l?.length===1&&(a=l[0])}if(!a||!t.has(a))continue;let c=o.get(a)??new Set;c.add(s),o.set(a,c)}return o}function oE(e,t,n,r,i){let o=new Set,s=new Set,a=Sf(e,t);if(!a)return{resolved:o,broken:[],citations:[]};let c=a.candidates,l=a.contextsByCandidate,u=new Map,d=(m,p)=>{let g=l.get(p);if(!g||g.length===0)return;let y=u.get(m)??[];y.push(...g),u.set(m,us(y).slice(0,3))};for(let m of c){if(n.has(m)){o.add(m),d(m,m);continue}let p=r.get(m);if(p&&p.length===1){o.add(p[0]),d(p[0],m);continue}p&&p.length>1||i.has(m)&&s.add(m)}return{resolved:o,broken:[...s],citations:[...u].map(([m,p])=>({file:m,contexts:p}))}}function sE(e,t){let n=new Map;for(let r of t){let i=e.get(r);i&&i.length>0&&n.set(r,[...i])}return n}function Sf(e,t){let n;try{n=gf(ds(e.config.projectRoot,t),"utf-8")}catch{return null}let r=X(e,t,n),i=te(e,"doc-path-evidence",t,r);if(i!==null){let s=lE(i);if(s)return s}let o=aE(n);return ne(e,"doc-path-evidence",t,r,cE(o)),o}function aE(e){let t=e.split(/\r?\n/),n=new Set,r=new Map;for(let i=0;i<t.length;i+=1){let o=t[i]??"";for(let s of o.matchAll(ZN)){let a=s[0].replace(/^\.?\//,"");n.add(a);let c=ls(t,i);if(c.length===0)continue;let l=r.get(a)??[];l.push(c),r.set(a,us(l).slice(0,3))}}return{candidates:[...n],contextsByCandidate:r}}function cE(e){let t={candidates:e.candidates,contextsByCandidate:[...e.contextsByCandidate.entries()]};return JSON.stringify(t)}function lE(e){try{let t=JSON.parse(e);if(!un(t))return null;let n=Ee(t.candidates),r=uE(t.contextsByCandidate);return!n||!r?null:{candidates:n,contextsByCandidate:new Map(r)}}catch{return null}}function uE(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string")return null;let r=Ee(n[1]);if(!r)return null;t.push([n[0],r])}return t}function us(e){let t=[];for(let n of new Set(e))t.some(r=>dE(r,n))||t.push(n);return t}function dE(e,t){if(e===t)return!0;let n=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),r=t.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),i=Math.min(n.length,r.length);if(i===0)return!1;if(i<3)return e.includes(t)||t.includes(e);let o=new Set(r),s=n.filter(a=>o.has(a)).length;return s>=3&&s/i>=.6}import{existsSync as vT,readFileSync as RT,writeFileSync as kT}from"fs";import{isAbsolute as wT,join as LT}from"path";var pe={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 Di from"path";function $n(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 Jc(e,t){if(e===t)return"ok";let n=ms(e),r=ms(t);return n&&r?mE(n,r)?"ok":"violation":pE(e,t)}function xf(e,t){let n=ms($n(e)),r=ms($n(t));return!!n&&!!r}function ms(e){return/^src\/([^/]+)$/.exec(e)?.[1]??null}function mE(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 pE(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 Mn(e,t){let{scope:n,minDeviation:r=5}=t??{},i=t?.semantic!==!1,o=t?.includePatternDeviations!==!1,a=new F(e).fileDependencyGraph(n);return bE([...fE(e,a,{scope:n,semantic:i}),...hE(a),...o?yE(a,r):[]])}function fE(e,t,n){let r=CE(e,n.scope),i=[],o=new Set;for(let[a,c]of t){if(_t(a))continue;let l=r.get(a)??new Set;for(let u of c)_t(u)||l.has(u)||gE(e,a,u,n)||(i.push({file:a,dep:u}),o.add(a))}o.size>0&&kE(e,r,{paths:[...o]});let s=[];for(let{file:a,dep:c}of i)(r.get(a)??new Set).has(c)||s.push({file:a,kind:"unused-import",description:`Depends on ${c} but references none of its symbols`,dep:c,actionTier:"direct",evidenceReasons:[`dependency edge exists from ${a} to ${c}`,"no semantic, source, type-only, side-effect, or Vue-template usage survived the conservative skip gates"],recommendation:"Remove the unused import or dependency edge after running the project checks."});return s}function gE(e,t,n,r){return r.semantic&&IE(e,t,n)||DE(e,t,n)||PE(e,t,n)||LE(n)||EE(e,t,n)?!0:NE(n)}function hE(e){let t=[],n=wE(e);for(let[r,i]of e){if(_t(r))continue;let o=$n(r);for(let s of i){if(_t(s))continue;let a=$n(s);if(o===a)continue;let c=Jc(o,a),l=c?"explicit":"inferred";if((c??n.get(`${o}->${a}`))==="violation"){let d=l==="explicit"?"direct":"signal";t.push({file:r,kind:"layer-violation",description:`Imports from ${a}/ (${s}) \u2014 may cross architectural boundary`,dep:s,detail:`${o}/ should not depend on ${a}/`,actionTier:d,policyBasis:l,evidenceReasons:[`dependency edge exists from ${r} to ${s}`,l==="explicit"?`explicit layer policy rejects ${o}/ -> ${a}/`:`rare cross-layer edge ${o}/ -> ${a}/ is inferred as a violation`],recommendation:l==="explicit"?"Move the dependency behind an allowed layer boundary or document a policy change.":"Review whether this is a real boundary break or an intentional exception before moving code."})}}}return t}function yE(e,t){let n=[];for(let[r,i]of SE(e)){let o=i.filter(a=>!_t(a));if(o.length<t)continue;let s=xE(e,o);for(let a of o)for(let c of e.get(a)??[])_t(c)||(s.get(c)??0)===1&&Di.dirname(c)!==r&&Di.dirname(c)!==Di.dirname(r)&&(xf(a,c)||n.push({file:a,kind:"pattern-deviation",description:`Only file in ${r}/ that depends on ${c}`,dep:c,actionTier:"signal",evidenceReasons:[`${o.length} sibling file(s) in ${r}/ were compared`,`${a} is the only non-skipped sibling depending on ${c}`],recommendation:"Review sibling ownership before changing this import; unique dependency shape can be intentional specialization."}))}return n}function bE(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 SE(e){let t=new Map;for(let n of e.keys()){let r=Di.dirname(n),i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function xE(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])_t(i)||n.set(i,(n.get(i)??0)+1);return n}function CE(e,t){let n=new Map;return vE(e,n,t),n}function vE(e,t,n){for(let r of RE(e,n))Cf(e,t,r.from_file,r.to_file)}function RE(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
613
+ ${e.pathExclusionsFor("ref_d")}`,...t,...n),r=new Map;for(let o of i){let s=r.get(o.symbol_id);s||(s=new Set,r.set(o.symbol_id,s)),s.add(o.relative_path)}return r}function Jg(e,t,n,i,r){if(e.isIgnored(i)||t.has(i))return;let o=n.get(i);o||(o=new Set,n.set(i,o)),o.add(r)}function u0(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function d0(e){return!(gn(e.symbol)||e.parentTypeName!==null&&!he(e.symbol))}function m0(e,t){return he(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}function Yg(e){let[t,n]=As(e,":"),i=t||"unknown",r=(o={})=>{let s=o.actionTier??p0(i);return{sourceAnalyzer:i,actionTier:s,rootCauseKey:o.rootCauseKey??(n||e),label:o.label??`${i} finding`,relatedFiles:o.relatedFiles??[],why:o.why??[],remediation:o.remediation??f0(s,i),file:o.file}};if(!n)return r({rootCauseKey:e,why:["Baseline identity did not include analyzer payload."]});if(["dead","isolated","extract","wrapper","passthrough","stale"].includes(i)){let[o,s]=As(n,":");return r({file:o,relatedFiles:o?[o]:[],rootCauseKey:s?`${o}:${s}`:n,label:`${i} finding`,why:s?[`Baseline subject: ${s}.`]:[]})}if(i==="cycle"){let o=n.split(">").filter(Boolean);return r({relatedFiles:o,rootCauseKey:n,label:"cycle finding",why:o.length>0?[`Cycle path: ${o.join(" > ")}.`]:[]})}if(i==="similar"){let o=n.split("|").filter(Boolean);return r({relatedFiles:[],rootCauseKey:n,label:"similarity finding",why:o.length>0?[`Similar symbols: ${o.join(" | ")}.`]:[]})}if(i==="drift"){let[o,s]=As(n,":"),[a,c]=As(s,":");return r({actionTier:o==="unused-import"?"direct":"signal",file:a,relatedFiles:[...new Set([a,c].filter(Boolean))],rootCauseKey:n,label:`${o||"drift"} finding`,why:[...o?[`Drift kind: ${o}.`]:[],...c?[`Related dependency: ${c}.`]:[]]})}return r({why:["Baseline analyzer prefix is not recognized by this diff-gate version."]})}function p0(e){switch(e){case"dead":case"isolated":case"cycle":case"passthrough":return"direct";case"similar":case"extract":case"wrapper":case"stale":return"signal";default:return"signal"}}function f0(e,t){return e==="direct"?`Fix the new ${t} baseline finding, or knowingly accept it via health --write-baseline.`:`Review the new ${t} baseline signal; fix it if it reflects real debt, or knowingly accept it via health --write-baseline.`}function As(e,t){let n=e.indexOf(t);return n<0?[e,""]:[e.slice(0,n),e.slice(n+t.length)]}import{existsSync as x0,readFileSync as th}from"fs";function js(e,t){let n=g0(e,t)??h0(e,t)??y0(e,t)??b0(e,t);return S0(e,n,t)}function g0(e,t){let n=-1,i=null;for(let r=0;r<=t;r+=1){let o=$l(e[r]??"");o&&(i===null?(i=o,n=r):o===i&&(i=null,n=-1))}if(i===null||n<0)return null;for(let r=t+1;r<e.length;r+=1)if($l(e[r]??"")===i)return{start:n,end:r+1};return{start:n,end:e.length}}function $l(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function h0(e,t){if(!Ms(e[t]??""))return null;let n=t;for(;n>0&&Ms(e[n-1]??"");)n-=1;let i=t+1;for(;i<e.length&&Ms(e[i]??"");)i+=1;return{start:n,end:i}}function Ms(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function y0(e,t){let n=t;for(;n>=0;){let o=e[n]??"";if($s(o)!==null)break;if(jl(o)!==null)return null;n-=1}if(n<0)return null;let i=$s(e[n]??"");if(i===null)return null;let r=n+1;for(;r<e.length;){let o=e[r]??"",s=$s(o);if(s!==null){if(s<=i)break;r+=1;continue}if(jl(o)!==null)break;r+=1}return{start:n,end:r}}function $s(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function b0(e,t){let n=e[t]??"";if(eh(n)||n.trim().length===0)return{start:t,end:t+1};let i=t;for(;i>0&&Zg(e[i-1]??"");)i-=1;let r=t+1;for(;r<e.length&&Zg(e[r]??"");)r+=1;return{start:i,end:r}}function Zg(e){return jl(e)===null}function jl(e){return e.trim().length===0?"blank":eh(e)?"heading":$l(e)?"fence":Ms(e)?"table":$s(e)!==null?"list":null}function eh(e){return/^#{1,6}\s+/.test(e.trim())}function S0(e,t,n){let{start:i,end:r}=t;if(r-i>40){let s=Math.floor(20);i=Math.max(i,n-s),r=Math.min(r,i+40),i=Math.max(t.start,r-40)}let o=e.slice(i,r).join(`
614
+ `).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}function ei(e,t){return t.filter(n=>e.includes(n))}var zi={classifyCitation:C0,citationContexts:v0,citationKindLabel:k0,citationRemediation:w0,referenceTargets:P0};function C0(e){let t=e.join(`
615
+ `).toLowerCase(),n=[],i=ei(t,[".scipquery","declaredcouplings","suppression","suppressions","config","configuration","json"]);if(i.length>0)return n.push(`configuration/example terms near citation: ${i.join(", ")}`),{citationKind:"configuration-example",actionTier:"support",reasons:n};let r=ei(t,["accepted","intentional","intentionally","retained","historical"]);if(r.length>0)return n.push(`intentional-record terms near citation: ${r.join(", ")}`),{citationKind:"intentional-record",actionTier:"support",reasons:n};let o=ei(t,["command","cli","usage","example","run","workflow"]);return o.length>0?(n.push(`guide/reference terms near citation: ${o.join(", ")}`),{citationKind:"guide-reference",actionTier:"signal",reasons:n}):(n.push(e.length>0?"citation appears in prose without config or guide markers":"citation context unavailable"),{citationKind:"behavioral-claim",actionTier:"direct",reasons:n})}function v0(e,t,n){let i;try{i=th(`${e.config.projectRoot}/${t}`,"utf-8").split(/\r?\n/)}catch{return[]}let r=n.flatMap(R0),o=[];for(let s=0;s<i.length;s+=1){let a=i[s]??"";r.some(c=>a.includes(c))&&o.push(js(i,s))}return o}function R0(e){let t=e.split("/");return[e,`./${e}`,t.slice(-3).join("/"),t.slice(-2).join("/")].filter((n,i,r)=>n.length>0&&r.indexOf(n)===i)}function k0(e){switch(e){case"behavioral-claim":return"a behavioral doc claim";case"configuration-example":return"a configuration example";case"guide-reference":return"a guide reference";case"intentional-record":return"an intentional record"}}function w0(e,t){switch(e){case"behavioral-claim":return`Re-read ${t} and update the behavioral claim or citation.`;case"configuration-example":return`Verify the configuration example in ${t} still points at the intended file; update only if the example target changed.`;case"guide-reference":return`Verify the guide reference in ${t} still sends readers to the right implementation or command surface.`;case"intentional-record":return`Verify the intentional citation in ${t} is still meant to name this file.`}}function P0(e,t,n){let i=Fs(n),r=new Set;for(let o of t)I0(e,o,i.get(o)??[])&&r.add(o);return r}function I0(e,t,n){if(n.length===0)return!1;if(!L0.test(t))return!0;let i=`${e.config.projectRoot}/${t}`;if(!x0(i))return!0;let r=th(i,"utf-8").split(/\r?\n/),o=D0(r);for(let s of n)for(let a=s.startLine;a<=s.endLine;a+=1)if((r[a]??"").trim()!==""&&!o.has(a))return!0;return!1}var L0=/\.(?:[cm]?[jt]sx?)$/i;function D0(e){let t=new Set,n=!1;for(let i=0;i<e.length;i+=1){let r=e[i].trim();!n&&E0(r)&&(n=!0),n&&(t.add(i),r.endsWith(";")&&(n=!1))}return t}function E0(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}import{existsSync as ih,readFileSync as Bl}from"fs";import{join as Qr}from"path";var nh=pe({kind:"doc-path-evidence",serialize:q0,deserialize:U0}),Xr=/\.(?:md|mdx|rst|txt)$/i;function N0(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var F0=3,T0=/[A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6}\b/g;function Hl(e,t={}){let{doc:n,limit:i=20,minCoupling:r=F0}=t,o=M0(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&&!oh(e,a)||n!==void 0&&!ih(Qr(e.config.projectRoot,a)))continue;let c=Math.max(0,...o.changeTimes.get(a)??[]),l=_0(e,a),d=new Map,{resolved:u,broken:m,citations:p}=O0(e,a,o.tracked,o.trackedBySuffix,o.everSeenInHistory),f=new Map(p.map(b=>[b.file,b.contexts]));for(let b of u){if(b===a||Xr.test(b))continue;let x=(o.changeTimes.get(b)??[]).filter(S=>S>c).length;x!==0&&d.set(b,{file:b,evidence:"reference",coChanges:0,changesSinceDocUpdate:x,...Ol("reference",l),citationContexts:f.get(b)})}for(let[b,x]of o.coupling.get(a)??[]){if(x<r||!o.tracked.has(b))continue;let S=(o.changeTimes.get(b)??[]).filter(C=>C>c).length;if(S===0)continue;let R=d.get(b);R?(R.evidence="both",R.coChanges=x,Object.assign(R,Ol("both",l))):d.set(b,{file:b,evidence:"co-change",coChanges:x,changesSinceDocUpdate:S,...Ol("co-change",l)})}if(d.size===0&&m.length===0)continue;let g=[...d.values()].sort((b,x)=>x.changesSinceDocUpdate-b.changesSinceDocUpdate);s.push({doc:a,docLastChangedAt:c,staleness:g.reduce((b,x)=>b+x.changesSinceDocUpdate,0)+m.length*10,subjects:g.slice(0,8),brokenReferences:m})}return s.sort((a,c)=>c.staleness-a.staleness),{available:!0,commitsAnalyzed:o.historyCommitCount,docsScanned:o.docFiles.length,findings:s.slice(0,i)}}function _0(e,t){let n;try{n=Bl(Qr(e.config.projectRoot,t),"utf8").slice(0,6e3)}catch{return{docIntent:"unknown",reasons:["doc text unavailable"]}}let i=`${t}
616
+ ${n}`.toLowerCase(),r=ei(i,["historical note","historical record","history note","retrospective","postmortem","post-mortem","archived","archive","previously","legacy","recorded","record of","snapshot","as of","migration note","decision record"]);if(r.length>0)return{docIntent:"historical-note",reasons:[`historical-note terms: ${r.join(", ")}`]};let o=ei(i,["current","standard","standards","must","should","policy","guide","guidance","workflow","contract","invariant","source of truth"]);return o.length>0?{docIntent:"current-guidance",reasons:[`current-guidance terms: ${o.join(", ")}`]}:{docIntent:"unknown",reasons:["no current-guidance or historical-note markers found"]}}function Ol(e,t){return{actionTier:A0(e,t.docIntent),docIntent:t.docIntent,docIntentReasons:t.reasons}}function A0(e,t){return t==="historical-note"?"support":e==="co-change"?"signal":"direct"}function M0(e){let t=Xe(e),n=t.commitHistory();if(!n)return null;let i=t.trackedFiles()??new Set,r=new Map,o=new Map,s=new Set;for(let a of n.commits){let c=[...new Set(a.files)],l=c.filter(u=>Xr.test(u)),d=c.filter(u=>!Xr.test(u));for(let u of c){s.add(u);let m=r.get(u)??[];m.push(a.timestamp),r.set(u,m)}for(let u of l){let m=o.get(u);m||(m=new Map,o.set(u,m));for(let p of d)m.set(p,(m.get(p)??0)+1)}}return{changeTimes:r,coupling:o,docFiles:[...i].filter(a=>Xr.test(a)),everSeenInHistory:s,historyCommitCount:n.commits.length,tracked:i,trackedBySuffix:sh(i)}}function rh(e,t){if(t.size===0)return[];let n=me(),i=0,r=0,o=0,s=0,a=0,c=0;return D("doc-reference.docs-citing-files",()=>{let l=Xe(e).trackedFiles()??new Set;i=l.size;let d=sh(l),u=$0(t,d),m=[];for(let p of l){if(!oh(e,p))continue;n&&(r+=1);let f;try{f=Bl(Qr(e.config.projectRoot,p),"utf-8")}catch{n&&(o+=1);continue}if(!H0(f,u)){n&&(s+=1);continue}let g=ah(e,p,f);if(!g)continue;n&&(a+=1);let b=j0(g.candidates,t,u,l,d);if(b.size===0)continue;let x=[...new Set([...b.values()].flatMap(y=>[...y]))],S=B0(g.contextsByCandidate,x),R=[...b].map(([y,w])=>({file:y,contexts:Os([...w].flatMap(L=>S.get(L)??[])).slice(0,3)})).filter(y=>y.contexts.length>0),C=[...b.keys()];if(C.length>0){n&&(c+=1);let y=C.sort();m.push({doc:p,cited:y,citations:R,citedClaims:Os(R.flatMap(w=>w.contexts)).slice(0,3)})}}return m},()=>({targets:t.size,trackedFiles:i,livingDocs:r,unreadableDocs:o,candidateMisses:s,evidenceDocs:a,citedDocs:c}))}function oh(e,t){return Xr.test(t)&&!N0(t)&&ih(Qr(e.config.projectRoot,t))}function sh(e){let t=new Map;for(let n of e){let i=n.split("/");for(let r of[2,3]){if(i.length<r)continue;let o=i.slice(-r).join("/"),s=t.get(o)??[];s.push(n),t.set(o,s)}}return t}function $0(e,t){let n=new Set(e);for(let i of e){let r=i.split("/");for(let o of[2,3]){if(r.length<o)continue;let s=r.slice(-o).join("/"),a=t.get(s);a?.length===1&&a[0]===i&&n.add(s)}}return n}function j0(e,t,n,i,r){let o=new Map;for(let s of e){if(!n.has(s))continue;let a;if(i.has(s))a=s;else{let l=r.get(s);l?.length===1&&(a=l[0])}if(!a||!t.has(a))continue;let c=o.get(a)??new Set;c.add(s),o.set(a,c)}return o}function O0(e,t,n,i,r){let o=new Set,s=new Set,a=ah(e,t);if(!a)return{resolved:o,broken:[],citations:[]};let c=a.candidates,l=a.contextsByCandidate,d=new Map,u=(m,p)=>{let f=l.get(p);if(!f||f.length===0)return;let g=d.get(m)??[];g.push(...f),d.set(m,Os(g).slice(0,3))};for(let m of c){if(n.has(m)){o.add(m),u(m,m);continue}let p=i.get(m);if(p&&p.length===1){o.add(p[0]),u(p[0],m);continue}p&&p.length>1||r.has(m)&&s.add(m)}return{resolved:o,broken:[...s],citations:[...d].map(([m,p])=>({file:m,contexts:p}))}}function B0(e,t){let n=new Map;for(let i of t){let r=e.get(i);r&&r.length>0&&n.set(i,[...r])}return n}function ah(e,t,n){let i=n;if(i===void 0)try{i=Bl(Qr(e.config.projectRoot,t),"utf-8")}catch{return null}let r=re(e,t,i),o=nh.read(e,t,r);if(o)return o;let s=V0(i);return nh.write(e,t,r,s),s}function H0(e,t){for(let n of t)if(e.includes(n))return!0;return!1}function V0(e){let t=e.split(/\r?\n/),n=new Set,i=new Map;for(let r=0;r<t.length;r+=1){let o=t[r]??"";for(let s of o.matchAll(T0)){let a=s[0].replace(/^\.?\//,"");n.add(a);let c=js(t,r);if(c.length===0)continue;let l=i.get(a)??[];l.push(c),i.set(a,Os(l).slice(0,3))}}return{candidates:[...n],contextsByCandidate:i}}function q0(e){let t={candidates:e.candidates,contextsByCandidate:[...e.contextsByCandidate.entries()]};return JSON.stringify(t)}function U0(e){try{let t=JSON.parse(e);if(!kt(t))return null;let n=je(t.candidates),i=z0(t.contextsByCandidate);return!n||!i?null:{candidates:n,contextsByCandidate:new Map(i)}}catch{return null}}function z0(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string")return null;let i=je(n[1]);if(!i)return null;t.push([n[0],i])}return t}function Os(e){let t=[];for(let n of new Set(e))t.some(i=>W0(i,n))||t.push(n);return t}function W0(e,t){if(e===t)return!0;let n=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),i=t.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),r=Math.min(n.length,i.length);if(r===0)return!1;if(r<3)return e.includes(t)||t.includes(e);let o=new Set(i),s=n.filter(a=>o.has(a)).length;return s>=3&&s/r>=.6}import{existsSync as nA,readFileSync as iA,writeFileSync as rA}from"fs";import{isAbsolute as oA,join as sA}from"path";var Ce={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 Yr from"path";function ti(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 Vl(e,t){if(e===t)return"ok";let n=Bs(e),i=Bs(t);return n&&i?G0(n,i)?"ok":"violation":K0(e,t)}function ch(e,t){let n=Bs(ti(e)),i=Bs(ti(t));return!!n&&!!i}function Bs(e){return/^src\/([^/]+)$/.exec(e)?.[1]??null}function G0(e,t){return t==="instrumentation"||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 K0(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 ni(e,t){let{scope:n,minDeviation:i=5}=t??{},r=t?.semantic!==!1,o=t?.includePatternDeviations!==!1,a=new A(e).fileDependencyGraph(n);return Z0([...J0(e,a,{scope:n,semantic:r}),...Q0(a),...o?Y0(a,i):[]])}function J0(e,t,n){let i=n_(e,n.scope),r=[],o=new Set;for(let[a,c]of t){if(Zt(a))continue;let l=i.get(a)??new Set;for(let d of c)Zt(d)||l.has(d)||X0(e,a,d,n)||(r.push({file:a,dep:d}),o.add(a))}o.size>0&&o_(e,i,{paths:[...o]});let s=[];for(let{file:a,dep:c}of r)(i.get(a)??new Set).has(c)||s.push({file:a,kind:"unused-import",description:`Depends on ${c} but references none of its symbols`,dep:c,actionTier:"direct",evidenceReasons:[`dependency edge exists from ${a} to ${c}`,"no semantic, source, type-only, side-effect, or Vue-template usage survived the conservative skip gates"],recommendation:"Remove the unused import or dependency edge after running the project checks."});return s}function X0(e,t,n,i){return l_(e,t,n)||u_(e,t,n)||a_(n)||m_(e,t,n)||d_(n)?!0:i.semantic&&c_(e,t,n)}function Q0(e){let t=[],n=s_(e);for(let[i,r]of e){if(Zt(i))continue;let o=ti(i);for(let s of r){if(Zt(s))continue;let a=ti(s);if(o===a)continue;let c=Vl(o,a),l=c?"explicit":"inferred";if((c??n.get(`${o}->${a}`))==="violation"){let u=l==="explicit"?"direct":"signal";t.push({file:i,kind:"layer-violation",description:`Imports from ${a}/ (${s}) \u2014 may cross architectural boundary`,dep:s,detail:`${o}/ should not depend on ${a}/`,actionTier:u,policyBasis:l,evidenceReasons:[`dependency edge exists from ${i} to ${s}`,l==="explicit"?`explicit layer policy rejects ${o}/ -> ${a}/`:`rare cross-layer edge ${o}/ -> ${a}/ is inferred as a violation`],recommendation:l==="explicit"?"Move the dependency behind an allowed layer boundary or document a policy change.":"Review whether this is a real boundary break or an intentional exception before moving code."})}}}return t}function Y0(e,t){let n=[];for(let[i,r]of e_(e)){let o=r.filter(a=>!Zt(a));if(o.length<t)continue;let s=t_(e,o);for(let a of o)for(let c of e.get(a)??[])Zt(c)||(s.get(c)??0)===1&&Yr.dirname(c)!==i&&Yr.dirname(c)!==Yr.dirname(i)&&(ch(a,c)||n.push({file:a,kind:"pattern-deviation",description:`Only file in ${i}/ that depends on ${c}`,dep:c,actionTier:"signal",evidenceReasons:[`${o.length} sibling file(s) in ${i}/ were compared`,`${a} is the only non-skipped sibling depending on ${c}`],recommendation:"Review sibling ownership before changing this import; unique dependency shape can be intentional specialization."}))}return n}function Z0(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 e_(e){let t=new Map;for(let n of e.keys()){let i=Yr.dirname(n),r=t.get(i);r||(r=[],t.set(i,r)),r.push(n)}return t}function t_(e,t){let n=new Map;for(let i of t)for(let r of e.get(i)??[])Zt(r)||n.set(r,(n.get(r)??0)+1);return n}function n_(e,t){let n=new Map;return i_(e,n,t),n}function i_(e,t,n){for(let i of r_(e,n))lh(e,t,i.from_file,i.to_file)}function r_(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
595
617
  FROM mentions m
596
618
  JOIN chunks c ON m.chunk_id = c.id
597
619
  JOIN documents d1 ON c.document_id = d1.id
@@ -607,31 +629,33 @@ ${n}`.toLowerCase(),i=An(r,["historical note","historical record","history note"
607
629
  WHERE d1.id != d2.id
608
630
  AND m.role != 1
609
631
  ${e.pathExclusionsFor("d1","d2")}
610
- ${n}`)}function kE(e,t,n={}){new F(e).scanSourceReferences({paths:n.paths??O(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},i=>{i.target.relativePath!==i.sourceFile&&(e.isIgnored(i.target.relativePath)||Cf(e,t,i.sourceFile,i.target.relativePath))})}function Cf(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 wE(e){let t=new Map;for(let[r,i]of e){if(_t(r))continue;let o=$n(r);for(let s of i){if(_t(s))continue;let a=$n(s);if(o===a||Jc(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 LE(e){return e.includes("types")||e.endsWith(".d.ts")}function IE(e,t,n){let r=li(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.isUsed)}function DE(e,t,n){let r=xe(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.used)}function PE(e,t,n){let r=xe(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.every(i=>i.isTypeOnly===!0)}function NE(e){return e.endsWith(".vue")}function EE(e,t,n){let r=xe(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 _t(e){let t=J(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||TE(Di.basename(e)))}function TE(e){return!!(e==="index.ts"||e==="index.js"||e==="cli.ts"||e==="main.ts"||e==="main.rs"||e.includes("worker.")||e.includes("postinstall.")||e==="health.ts"||e==="health.js")}import{basename as vf,extname as Rf}from"path";function ps(e,t,n,r,i,o){let s=new Set;FE(e,t,n,r)&&s.add(i);for(let a of o)a.value&&_E(s,a.label,a.value);return[...s].slice(0,6)}function _E(e,t,n){let r=AE(n);t.endsWith("name")&&$E(r)&&e.add(`${t} has type-guard boundary shape`);for(let i of r){let o=ME.get(i);o&&e.add(`${t} has ${o} term: ${i}`)}}function FE(e,t,n,r){if(n<=0)return!1;let i=We(e,t);if(i.length===0)return!1;for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(i[o]??"").trim();if(s!==""){if(Jr(s)===r)return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function AE(e){return e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function $E(e){return e.some(t=>OE.has(t))&&e.some(t=>jE.has(t))}var ME=new Map([["access","access policy"],["accessible","access policy"],["adapter","adapter"],["adapters","adapter"],["allow","access policy"],["allowed","access policy"],["animation","animation calculation"],["api","api surface"],["apply","settings/application"],["audit","side-effect boundary"],["auth","authorization"],["authorize","authorization"],["audio","audio side-effect"],["can","access policy"],["capabilities","capability boundary"],["capability","capability boundary"],["boundary","boundary"],["begin","lifecycle"],["bridge","bridge"],["bridges","bridge"],["cache","state cache"],["chase","gameplay action"],["command","command boundary"],["context","context policy"],["cooldown","temporal state"],["cooldowns","temporal state"],["controller","controller"],["controllers","controller"],["diagnostic","diagnostics"],["diagnostics","diagnostics"],["effect","side-effect boundary"],["effects","side-effect boundary"],["energy","gameplay calculation"],["expired","temporal state"],["facade","facade"],["facades","facade"],["fire","gameplay action"],["gateway","gateway"],["gateways","gateway"],["guard","guard"],["guards","guard"],["haptic","haptic side-effect"],["haptics","haptic side-effect"],["head","sequence boundary"],["history","state history"],["input","input boundary"],["jump","gameplay action"],["keyboard","input boundary"],["log","side-effect boundary"],["logger","side-effect boundary"],["lock","coordination boundary"],["middleware","middleware"],["multiplier","gameplay calculation"],["mute","audio side-effect"],["normalize","normalization"],["normalise","normalization"],["normalizer","normalization"],["oscillate","animation calculation"],["oscillation","animation calculation"],["overlap","collision predicate"],["performance","diagnostics"],["permission","access policy"],["permissions","access policy"],["policy","policy"],["pool","state pool"],["pooled","state pool"],["pools","state pool"],["predict","prediction"],["presenter","presenter"],["presenters","presenter"],["projectile","gameplay entity"],["provider","provider boundary"],["providers","provider boundary"],["public","public surface"],["quality","settings/application"],["rate","calculation"],["register","registry"],["registry","registry"],["relay","relay"],["relays","relay"],["reseed","state lifecycle"],["reset","state lifecycle"],["respond","response boundary"],["response","response boundary"],["resolve","resolution"],["resolver","resolution"],["route","route boundary"],["routes","route boundary"],["run","lifecycle"],["sample","diagnostics"],["score","gameplay calculation"],["scope","scope policy"],["scroll","position state"],["scrolled","position state"],["seed","state lifecycle"],["seeded","state lifecycle"],["segment","segment boundary"],["segments","segment boundary"],["setting","settings/application"],["settings","settings/application"],["spawn","gameplay lifecycle"],["spawning","gameplay lifecycle"],["speed","gameplay calculation"],["surface","public surface"],["tail","sequence boundary"],["tick","temporal state"],["transaction","transaction"],["transactional","transaction"],["transform","transformation"],["transformer","transformation"],["translate","translation"],["translator","translation"],["try","fallible action"],["validate","validation"],["validation","validation"],["validator","validation"],["visual","diagnostics"],["window","settings/application"],["socket","transport boundary"],["websocket","transport boundary"]]),OE=new Set(["can","has","is","should"]),jE=new Set(["access","api","auth","collision","expired","input","keyboard","overlap","permission","permissions","policy","projectile","response","route","routes","scope"]);function On(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new F(e);return Ze({candidates:()=>KE(s,n,r),orderCandidates:Go,scanLimit:o,prepare:a=>s.calleeMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,c)=>BE(e,a,c.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:i})}function BE(e,t,n){let r=JE(n);if(r.size!==1||!ma(e,t.relativePath,t.startLine,t.endLine))return null;let[,i]=[...r.entries()][0],o=HE(e,t,i),s=qE(e,t),a=o.length>0||s.length>0?"signal":"direct";return{symbol:t.symbol,shortName:b(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:U(t),forwardsTo:i.symbol,forwardsToShort:b(i.symbol),forwardsToFile:i.file,actionTier:a,boundaryEvidence:o,publicFacadeEvidence:s,recommendation:VE(a,o,s)}}function HE(e,t,n){return ps(e,t.relativePath,t.startLine,"passthrough","explicit ignore-passthrough comment",[{label:"passthrough name",value:b(t.symbol)},{label:"callee name",value:b(n.symbol)},{label:"passthrough module",value:vf(t.relativePath,Rf(t.relativePath))},{label:"callee module",value:vf(n.file,Rf(n.file))}])}function VE(e,t,n){if(e==="signal"){if(n.length>0)return`Review the public API before inlining; public-facade evidence: ${n.slice(0,2).join("; ")}.`;let r=t.filter(GE);return r.length>0?`Review the public API before inlining; public-surface evidence: ${r.slice(0,2).join("; ")}.`:`Review the boundary before inlining; boundary evidence: ${t.slice(0,2).join("; ")}.`}return"Inline or remove this passthrough unless an external API or runtime registration depends on the forwarding name."}function qE(e,t){return UE(e,t)?xr(e,t.relativePath)?["exported passthrough is declared on the package public surface"]:le(e,t.symbol,t.relativePath)?["exported passthrough matches configured or framework public entry surface"]:[]:[]}function UE(e,t){let n=We(e,t.relativePath);if(n.length===0)return!1;let r=n.slice(Math.max(0,t.startLine-2),t.startLine+1).join(`
611
- `);return XE.test(r)?!0:WE(n,$(t.symbol))}function WE(e,t){if(!t)return!1;let n=new RegExp(`^\\s*export\\s*\\{[^}\\n]*\\b${zE(t)}\\b`);return e.some(r=>n.test(r))}function GE(e){return e.includes("public surface")}function zE(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function JE(e){let t=e.some(r=>oe(r.symbol))?e.filter(r=>oe(r.symbol)):e,n=new Map;for(let r of t)n.has(r.symbol)||n.set(r.symbol,r);return n}function KE(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:3,maxLoc:n,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0})}var XE=/^\s*export\s+(?:default\s+)?(?:(?:async\s+)?function\b|(?:const|let|var)\b)/m;function jn(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 F(e),u=l.scopedDefinitions(n),d=lT(l,n),m={high:0,medium:1,low:2};return Ze({candidates:()=>QE(e,l,u,{minLoc:r,maxLoc:i}),orderCandidates:(p,g)=>U(g)-U(p)||p.relativePath.localeCompare(g.relativePath),scanLimit:a,prepare:p=>{let g=eT(p),y=ZE(e,l,p,g,{semantic:c}),h=p.filter(x=>{let v=fs(e,x,y,g);return v.realConsumers.length<=1&&!v.transitivelyReachable&&kf(x,v.realConsumers.length,d)});return{consumerFileMap:y,singletonBackedClassIds:rT(e,l,u,h,{semantic:c}),candidateIndex:g}},evaluate:(p,g)=>{if(g.singletonBackedClassIds.has(p.symbolId))return null;let y=fs(e,p,g.consumerFileMap,g.candidateIndex);if(y.transitivelyReachable||y.realConsumers.length>1||y.realConsumers.length===0&&y.barrelConsumers>0||!kf(y.definition,y.realConsumers.length,d))return null;let h=tT(e,y);return!s&&h.confidence==="low"?null:h},orderResults:(p,g)=>m[p.confidence]-m[g.confidence]||g.loc-p.loc||p.file.localeCompare(g.file)||p.startLine-g.startLine,limit:o})}function QE(e,t,n,r){return n.filter(i=>i.isTypeLike&&U(i)>=r.minLoc).filter(i=>U(i)<=r.maxLoc).filter(i=>!e.isIgnored(i.relativePath)).filter(i=>J(i.relativePath)!=="test").filter(i=>!le(e,i.symbol,i.relativePath)).filter(i=>!uT(i.symbol)).filter(i=>!t.hasSuppressionComment(i))}function YE(e,t,n){return _n(e,t,{semantic:n.semantic,sourceFallback:n.sourceFallback})}function ZE(e,t,n,r,i){let o=YE(t,n,{semantic:!1,sourceFallback:!1}),s=n.filter(l=>{let u=fs(e,l,o,r);return u.realConsumers.length<=1&&!(u.realConsumers.length>0&&Kc(l.relativePath))}),a=i.semantic&&s.length>0?wr(o,Xe(e,s)):o,c=s.filter(l=>fs(e,l,a,r).realConsumers.length<=1);return wr(a,t.sourceFallbackCallerFiles(c))}function eT(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 fs(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}=Zo(e,t,o),l=dT(e,t,n,r);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:l}}function tT(e,t){let n=Lf(e,t.definition.relativePath,t.definition.startLine),r=Kc(t.definition.relativePath)?!0:mT(e,t.definition),{confidence:i,reason:o}=pT(t.realConsumers.length,n,r),s=nT(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:U(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:r,confidence:i,reason:o,actionTier:s.actionTier,stalenessKind:s.stalenessKind,recommendation:s.recommendation}}function nT(e,t,n){return e===0?{actionTier:"direct",stalenessKind:"unused-abstraction",recommendation:"Delete the abstraction or wire the missing consumer after checking public/package surfaces."}:t==="class"?{actionTier:"signal",stalenessKind:"one-to-one-class-encapsulation",recommendation:"Treat as weak signal: a one-consumer class may be intentional encapsulation, so inline only after reviewing ownership and state boundaries."}:n?{actionTier:"signal",stalenessKind:"single-consumer-abstraction",recommendation:"Review whether this single-consumer abstraction earns its name or should be folded into the owning feature."}:{actionTier:"signal",stalenessKind:"misplaced-single-consumer-type",recommendation:"Review moving or co-locating the type with its only real consumer; keep it here only if this file owns the public contract."}}function rT(e,t,n,r,i){let o=oT(e,iT(n),r),s=o.map(l=>l.singleton);if(o.length===0)return new Set;let a=_n(t,s,{semantic:i.semantic}),c=new Set;for(let{singleton:l,classId:u}of o)aT(e,l,a)&&c.add(u);return c}function iT(e){let t=new Map;for(let n of e){let r=$(n.symbol);r&&t.set(wf(n.relativePath,r),n)}return t}function oT(e,t,n){let r=[];for(let i of n){let o=sT(e,t,i);o&&r.push({singleton:o,classId:i.symbolId})}return r}function sT(e,t,n){if(Lf(e,n.relativePath,n.startLine)!=="class")return null;let r=$(n.symbol);if(!r)return null;let i=cT(e,n.relativePath,r);return i?t.get(wf(n.relativePath,i))??null:null}function aT(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)&&!Rc(e,o,r))}function wf(e,t){return`${e}\0${t}`}function cT(e,t,n){let r=T(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 lT(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function uT(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 Kc(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 kf(e,t,n){return!(Kc(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function dT(e,t,n,r){let i=fa(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 Lf(e,t,n){let r=T(e,t);if(!r)return"other";let i=r.split(`
612
- `),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 mT(e,t){let n=T(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(`
613
- `);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function pT(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 Nr,extname as gs}from"path";function Bn(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new F(e),a=ST(s.fileDependencyGraph(n));return Ze({candidates:()=>hT(s,n,r),orderCandidates:Go,scanLimit:o,prepare:c=>({callerFileMap:fT(e,s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>gT(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:i})}function fT(e,t,n,r){let i=_n(t,n,{semantic:r.semantic,sourceFallback:!1}),o=new Map(n.map(c=>[c.symbolId,c])),s=new Map;for(let c of n){let l=If(e,t,c,i);if(l.length>1||(s.set(c.symbolId,c),l.length!==1))continue;let u=l[0],d=Df(e,c.symbolId,u);if(!d)continue;let m=Pf(t,e,u,c.symbol,d);m?.isFunctionLike&&o.has(m.symbolId)&&s.set(m.symbolId,o.get(m.symbolId))}let a=[...s.values()];return a.length===0?i:wr(i,t.sourceFallbackCallerFiles(a))}function gT(e,t,n,r){let i=If(e,t,n,r.callerFileMap);if(i.length!==1)return null;let o=i[0],s=Df(e,n.symbolId,o);if(!s)return null;let a=Pf(t,e,o,n.symbol,s);if(a&&cr(a.symbol))return null;let{fanIn:c,source:l}=yT(r.callerFileMap,r.reverseFanIn,o,a);if(l==="function"?c<=3:c<=5)return null;let u=CT(e,n,o,a);return{symbol:n.symbol,shortName:b(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:U(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?b(a.symbol):Nr(o),callerFanIn:c,actionTier:u.length>0?"signal":"direct",boundaryEvidence:u}}function hT(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:2,maxLoc:n,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0})}function If(e,t,n,r){let i=Nr(n.relativePath,gs(n.relativePath)),o=[...r.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>Nr(s,gs(s))!==i).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return Zo(e,n,o).realConsumers}function Df(e,t,n){return e.get(`SELECT c.start_line, c.end_line
632
+ ${n}`)}function o_(e,t,n={}){new A(e).scanSourceReferences({paths:n.paths??O(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},r=>{r.target.relativePath!==r.sourceFile&&(e.isIgnored(r.target.relativePath)||lh(e,t,r.sourceFile,r.target.relativePath))})}function lh(e,t,n,i){if(e.isIgnored(n)||e.isIgnored(i))return;let r=t.get(n);r||(r=new Set,t.set(n,r)),r.add(i)}function s_(e){let t=new Map;for(let[i,r]of e){if(Zt(i))continue;let o=ti(i);for(let s of r){if(Zt(s))continue;let a=ti(s);if(o===a||Vl(o,a))continue;let c=`${o}->${a}`;t.set(c,(t.get(c)??0)+1)}}let n=new Map;for(let[i,r]of t)n.set(i,r<=2?"violation":"ok");return n}function a_(e){return e.includes("types")||e.endsWith(".d.ts")}function c_(e,t,n){let i=Er(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.some(r=>r.isUsed)}function l_(e,t,n){let i=oe(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.some(r=>r.used)}function u_(e,t,n){let i=oe(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.every(r=>r.isTypeOnly===!0)}function d_(e){return e.endsWith(".vue")}function m_(e,t,n){let i=oe(e,t).filter(r=>r.sourcePath===n);return i.length===0?!1:i.every(r=>r.kind==="side-effect"||r.kind==="namespace"&&r.usedMembers.length===0&&!r.used)}function Zt(e){let t=Z(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||p_(Yr.basename(e)))}function p_(e){return!!(e==="index.ts"||e==="index.js"||e==="cli.ts"||e==="main.ts"||e==="main.rs"||e.includes("worker.")||e.includes("postinstall.")||e==="health.ts"||e==="health.js")}import{basename as uh,extname as dh}from"path";function Hs(e,t,n,i,r,o){let s=new Set;g_(e,t,n,i)&&s.add(r);for(let a of o)a.value&&f_(s,a.label,a.value);return[...s].slice(0,6)}function f_(e,t,n){let i=h_(n);t.endsWith("name")&&y_(i)&&e.add(`${t} has type-guard boundary shape`);for(let r of i){let o=b_.get(r);o&&e.add(`${t} has ${o} term: ${r}`)}}function g_(e,t,n,i){if(n<=0)return!1;let r=Ye(e,t);if(r.length===0)return!1;for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(r[o]??"").trim();if(s!==""){if(mr(s)===i)return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function h_(e){return e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function y_(e){return e.some(t=>S_.has(t))&&e.some(t=>x_.has(t))}var b_=new Map([["access","access policy"],["accessible","access policy"],["adapter","adapter"],["adapters","adapter"],["allow","access policy"],["allowed","access policy"],["animation","animation calculation"],["api","api surface"],["apply","settings/application"],["audit","side-effect boundary"],["auth","authorization"],["authorize","authorization"],["audio","audio side-effect"],["can","access policy"],["capabilities","capability boundary"],["capability","capability boundary"],["boundary","boundary"],["begin","lifecycle"],["bridge","bridge"],["bridges","bridge"],["cache","state cache"],["chase","gameplay action"],["command","command boundary"],["context","context policy"],["cooldown","temporal state"],["cooldowns","temporal state"],["controller","controller"],["controllers","controller"],["diagnostic","diagnostics"],["diagnostics","diagnostics"],["effect","side-effect boundary"],["effects","side-effect boundary"],["energy","gameplay calculation"],["expired","temporal state"],["facade","facade"],["facades","facade"],["fire","gameplay action"],["gateway","gateway"],["gateways","gateway"],["guard","guard"],["guards","guard"],["haptic","haptic side-effect"],["haptics","haptic side-effect"],["head","sequence boundary"],["history","state history"],["input","input boundary"],["jump","gameplay action"],["keyboard","input boundary"],["log","side-effect boundary"],["logger","side-effect boundary"],["lock","coordination boundary"],["middleware","middleware"],["multiplier","gameplay calculation"],["mute","audio side-effect"],["normalize","normalization"],["normalise","normalization"],["normalizer","normalization"],["oscillate","animation calculation"],["oscillation","animation calculation"],["overlap","collision predicate"],["performance","diagnostics"],["permission","access policy"],["permissions","access policy"],["policy","policy"],["pool","state pool"],["pooled","state pool"],["pools","state pool"],["predict","prediction"],["presenter","presenter"],["presenters","presenter"],["projectile","gameplay entity"],["provider","provider boundary"],["providers","provider boundary"],["public","public surface"],["quality","settings/application"],["rate","calculation"],["register","registry"],["registry","registry"],["relay","relay"],["relays","relay"],["reseed","state lifecycle"],["reset","state lifecycle"],["respond","response boundary"],["response","response boundary"],["resolve","resolution"],["resolver","resolution"],["route","route boundary"],["routes","route boundary"],["run","lifecycle"],["sample","diagnostics"],["score","gameplay calculation"],["scope","scope policy"],["scroll","position state"],["scrolled","position state"],["seed","state lifecycle"],["seeded","state lifecycle"],["segment","segment boundary"],["segments","segment boundary"],["setting","settings/application"],["settings","settings/application"],["spawn","gameplay lifecycle"],["spawning","gameplay lifecycle"],["speed","gameplay calculation"],["surface","public surface"],["tail","sequence boundary"],["tick","temporal state"],["transaction","transaction"],["transactional","transaction"],["transform","transformation"],["transformer","transformation"],["translate","translation"],["translator","translation"],["try","fallible action"],["validate","validation"],["validation","validation"],["validator","validation"],["visual","diagnostics"],["window","settings/application"],["socket","transport boundary"],["websocket","transport boundary"]]),S_=new Set(["can","has","is","should"]),x_=new Set(["access","api","auth","collision","expired","input","keyboard","overlap","permission","permissions","policy","projectile","response","route","routes","scope"]);function ii(e,t){let{scope:n,maxLoc:i=15,limit:r=30,scanLimit:o}=t??{},s=new A(e);return lt({candidates:()=>E_(e,s,n,i),orderCandidates:vs,scanLimit:o,profile:{name:"passthrough-candidates"},prepare:a=>s.calleeMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,c)=>C_(e,a,c.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:r})}function C_(e,t,n){let i=D_(n);if(i.size!==1||!Ua(e,t.relativePath,t.startLine,t.endLine))return null;let[,r]=[...i.entries()][0],o=v_(e,t,r),s=k_(e,t),a=o.length>0||s.length>0?"signal":"direct";return{symbol:t.symbol,shortName:v(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:J(t),forwardsTo:r.symbol,forwardsToShort:v(r.symbol),forwardsToFile:r.file,actionTier:a,boundaryEvidence:o,publicFacadeEvidence:s,recommendation:R_(a,o,s)}}function v_(e,t,n){return Hs(e,t.relativePath,t.startLine,"passthrough","explicit ignore-passthrough comment",[{label:"passthrough name",value:v(t.symbol)},{label:"callee name",value:v(n.symbol)},{label:"passthrough module",value:uh(t.relativePath,dh(t.relativePath))},{label:"callee module",value:uh(n.file,dh(n.file))}])}function R_(e,t,n){if(e==="signal"){if(n.length>0)return`Review the public API before inlining; public-facade evidence: ${n.slice(0,2).join("; ")}.`;let i=t.filter(I_);return i.length>0?`Review the public API before inlining; public-surface evidence: ${i.slice(0,2).join("; ")}.`:`Review the boundary before inlining; boundary evidence: ${t.slice(0,2).join("; ")}.`}return"Inline or remove this passthrough unless an external API or runtime registration depends on the forwarding name."}function k_(e,t){return w_(e,t)?_i(e,t.relativePath)?["exported passthrough is declared on the package public surface"]:be(e,t.symbol,t.relativePath)?["exported passthrough matches configured or framework public entry surface"]:[]:[]}function w_(e,t){let n=Ye(e,t.relativePath);if(n.length===0)return!1;let i=n.slice(Math.max(0,t.startLine-2),t.startLine+1).join(`
633
+ `);return N_.test(i)?!0:P_(n,$(t.symbol))}function P_(e,t){if(!t)return!1;let n=new RegExp(`^\\s*export\\s*\\{[^}\\n]*\\b${L_(t)}\\b`);return e.some(i=>n.test(i))}function I_(e){return e.includes("public surface")}function L_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function D_(e){let t=e.some(i=>de(i.symbol))?e.filter(i=>de(i.symbol)):e,n=new Map;for(let i of t)n.has(i.symbol)||n.set(i.symbol,i);return n}function E_(e,t,n,i){return t.productionCallableDefinitions({scope:n,minLoc:3,maxLoc:i,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0}).filter(r=>!Ln(e,r))}var N_=/^\s*export\s+(?:default\s+)?(?:(?:async\s+)?function\b|(?:const|let|var)\b)/m;function ri(e,t){let{scope:n,minLoc:i=3,maxLoc:r=80,limit:o=30,includeLowConfidence:s=!1,scanLimit:a}=t??{},c=t?.semantic!==!1,l=new A(e),d=l.scopedDefinitions(n),u=q_(l,n),m={high:0,medium:1,low:2};return lt({candidates:()=>F_(e,l,d,{minLoc:i,maxLoc:r}),orderCandidates:(p,f)=>J(f)-J(p)||p.relativePath.localeCompare(f.relativePath),scanLimit:a,profile:{name:"stale-abstractions"},prepare:p=>{let f=__(p),g=T_(e,l,p,f,{semantic:c}),b=p.filter(x=>{let S=Vs(e,x,g,f);return S.realConsumers.length<=1&&!S.transitivelyReachable&&mh(x,S.realConsumers.length,u)});return{consumerFileMap:g,singletonBackedClassIds:$_(e,l,d,b,{semantic:c}),candidateIndex:f}},evaluate:(p,f)=>{if(f.singletonBackedClassIds.has(p.symbolId))return null;let g=Vs(e,p,f.consumerFileMap,f.candidateIndex);if(g.transitivelyReachable||g.realConsumers.length>1||g.realConsumers.length===0&&g.barrelConsumers>0||!mh(g.definition,g.realConsumers.length,u))return null;let b=A_(e,g);return!s&&b.confidence==="low"?null:b},orderResults:(p,f)=>m[p.confidence]-m[f.confidence]||f.loc-p.loc||p.file.localeCompare(f.file)||p.startLine-f.startLine,limit:o})}function F_(e,t,n,i){return n.filter(r=>r.isTypeLike&&J(r)>=i.minLoc).filter(r=>J(r)<=i.maxLoc).filter(r=>!e.isIgnored(r.relativePath)).filter(r=>Z(r.relativePath)!=="test").filter(r=>!be(e,r.symbol,r.relativePath)).filter(r=>!U_(r.symbol)).filter(r=>!t.hasSuppressionComment(r))}function ql(e,t,n,i){return Yt(Yn(e,t).forDefinitions(n,{semantic:i.semantic,sourceFallback:i.sourceFallback}))}function T_(e,t,n,i,r){let o=ql(e,t,n,{semantic:!1,sourceFallback:!1}),s=n.filter(l=>{let d=Vs(e,l,o,i);return d.realConsumers.length<=1&&!(d.realConsumers.length>0&&Ul(l.relativePath))}),a=r.semantic&&s.length>0?qn(o,ql(e,t,s,{semantic:!0,sourceFallback:!1})):o,c=s.filter(l=>Vs(e,l,a,i).realConsumers.length<=1);return qn(a,ql(e,t,c,{semantic:!1,sourceFallback:!0}))}function __(e){let t=new Map;for(let n of e){let i=t.get(n.relativePath);i||(i=new Map,t.set(n.relativePath,i));let r=$(n.symbol);r&&i.set(r,n)}return t}function Vs(e,t,n,i){let o=[...n.get(t.symbolId)??new Set].filter(d=>d!==t.relativePath&&!e.isIgnored(d)),{realConsumers:s,barrelConsumers:a,importOnlyConsumers:c}=Ls(e,t,o),l=z_(e,t,n,i);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:l}}function A_(e,t){let n=fh(e,t.definition.relativePath,t.definition.startLine),i=Ul(t.definition.relativePath)?!0:W_(e,t.definition),{confidence:r,reason:o}=G_(t.realConsumers.length,n,i),s=M_(t.realConsumers.length,n,i);return{symbol:t.definition.symbol,shortName:v(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:J(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:i,confidence:r,reason:o,actionTier:s.actionTier,stalenessKind:s.stalenessKind,recommendation:s.recommendation}}function M_(e,t,n){return e===0?{actionTier:"direct",stalenessKind:"unused-abstraction",recommendation:"Delete the abstraction or wire the missing consumer after checking public/package surfaces."}:t==="class"?{actionTier:"signal",stalenessKind:"one-to-one-class-encapsulation",recommendation:"Treat as weak signal: a one-consumer class may be intentional encapsulation, so inline only after reviewing ownership and state boundaries."}:n?{actionTier:"signal",stalenessKind:"single-consumer-abstraction",recommendation:"Review whether this single-consumer abstraction earns its name or should be folded into the owning feature."}:{actionTier:"signal",stalenessKind:"misplaced-single-consumer-type",recommendation:"Review moving or co-locating the type with its only real consumer; keep it here only if this file owns the public contract."}}function $_(e,t,n,i,r){let o=O_(e,j_(n),i),s=o.map(l=>l.singleton);if(o.length===0)return new Set;let a=Yt(Yn(e,t).forDefinitions(s,{semantic:r.semantic,sourceFallback:!0})),c=new Set;for(let{singleton:l,classId:d}of o)H_(e,l,a)&&c.add(d);return c}function j_(e){let t=new Map;for(let n of e){let i=$(n.symbol);i&&t.set(ph(n.relativePath,i),n)}return t}function O_(e,t,n){let i=[];for(let r of n){let o=B_(e,t,r);o&&i.push({singleton:o,classId:r.symbolId})}return i}function B_(e,t,n){if(fh(e,n.relativePath,n.startLine)!=="class")return null;let i=$(n.symbol);if(!i)return null;let r=V_(e,n.relativePath,i);return r?t.get(ph(n.relativePath,r))??null:null}function H_(e,t,n){let i=$(t.symbol),r=n.get(t.symbolId);return!i||!r?!1:[...r].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!hl(e,o,i))}function ph(e,t){return`${e}\0${t}`}function V_(e,t,n){let i=M(e,t);if(!i)return null;let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\bexport\\s+const\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*new\\s+${r}\\s*\\(`);return i.match(o)?.[1]??null}function q_(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function U_(e){let t=Ie(e);if("kind"in t)return!1;let n=t.descriptors;if(n.length<2)return!1;let i=n[n.length-1],r=n[n.length-2];return i?.suffix==="type"&&r?.suffix==="type"}function 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 mh(e,t,n){return!(Ul(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function z_(e,t,n,i){let r=Wa(e,t.relativePath),o=$(t.symbol);if(!o)return!1;let s=r.get(o);if(!s||s.size===0)return!1;let a=i.get(t.relativePath);if(!a)return!1;for(let c of s){let l=a.get(c);if(!l)continue;let d=n.get(l.symbolId);if(d){for(let u of d)if(u!==t.relativePath&&!e.isIgnored(u))return!0}}return!1}function fh(e,t,n){let i=M(e,t);if(!i)return"other";let r=i.split(`
634
+ `),o=Math.max(0,n-2),s=Math.min(r.length-1,n+2);for(let a=o;a<=s;a++){let l=(r[a]??"").replace(/^\s*\/\/.*$/g,"");if(/\b(?:export\s+)?(?:abstract\s+)?class\s+\w/.test(l))return"class";if(/\b(?:export\s+)?interface\s+\w/.test(l))return"interface";if(/\b(?:export\s+)?type\s+\w/.test(l))return"type";if(/\b(?:export\s+)?(?:const\s+)?enum\s+\w/.test(l))return"enum"}return"other"}function W_(e,t){let n=M(e,t.relativePath);if(!n)return!1;let i=$(t.symbol);if(!i)return!1;let r=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${r}\\b`),s=n.split(`
635
+ `);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function G_(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 Wi,extname as qs}from"path";function oi(e,t){let{scope:n,maxLoc:i=15,limit:r=30,scanLimit:o}=t??{},s=new A(e),a=Z_(s.fileDependencyGraph(n));return lt({candidates:()=>X_(e,s,n,i),orderCandidates:vs,scanLimit:o,profile:{name:"wrapper-candidates"},prepare:c=>({callerFileMap:K_(e,s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>J_(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:r})}function K_(e,t,n,i){let r=Yn(e,t),o=Yt(r.forDefinitions(n,{semantic:!1,sourceFallback:!1})),s=[];i.semantic&&D("wrapper.semantic-candidates",()=>{s=n.filter(m=>zl(e,t,m,o).length<=1)},()=>({symbols:n.length,semanticCandidates:s.length}));let a=s.length===0?new Map:Yt(r.forDefinitions(s,{semantic:!0,sourceFallback:!1})),c=a.size===0?o:qn(o,a),l=new Map(n.map(m=>[m.symbolId,m])),d=new Map;for(let m of n){let p=zl(e,t,m,c);if(p.length>1||(d.set(m.symbolId,m),p.length!==1))continue;let f=p[0],g=gh(e,m.symbolId,f);if(!g)continue;let b=hh(t,e,f,m.symbol,g);b?.isFunctionLike&&l.has(b.symbolId)&&d.set(b.symbolId,l.get(b.symbolId))}let u=[...d.values()];return u.length===0?c:qn(c,Yt(r.forDefinitions(u,{semantic:!1,sourceFallback:!0})))}function J_(e,t,n,i){let r=zl(e,t,n,i.callerFileMap);if(r.length!==1)return null;let o=r[0],s=gh(e,n.symbolId,o);if(!s)return null;let a=hh(t,e,o,n.symbol,s);if(a&&Ii(a.symbol))return null;let{fanIn:c,source:l}=Q_(i.callerFileMap,i.reverseFanIn,o,a);if(l==="function"?c<=3:c<=5)return null;let d=tA(e,n,o,a);return{symbol:n.symbol,shortName:v(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:J(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?v(a.symbol):Wi(o),callerFanIn:c,actionTier:d.length>0?"signal":"direct",boundaryEvidence:d}}function X_(e,t,n,i){return t.productionCallableDefinitions({scope:n,minLoc:2,maxLoc:i,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0}).filter(r=>!Ln(e,r))}function zl(e,t,n,i){let r=Wi(n.relativePath,qs(n.relativePath)),o=[...i.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>Wi(s,qs(s))!==r).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return Ls(e,n,o).realConsumers}function gh(e,t,n){return e.get(`SELECT c.start_line, c.end_line
614
636
  FROM mentions m
615
637
  JOIN chunks c ON m.chunk_id = c.id
616
638
  JOIN documents d ON c.document_id = d.id
617
639
  WHERE m.symbol_id = ? AND m.role != 1 AND d.relative_path = ?
618
- LIMIT 1`,t,n)}function Pf(e,t,n,r,i){let o=e.definitionsForFile(n),s=bT(t,n,r,i.start_line,i.end_line);return Ge(o,s)}function yT(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:xT(t,n),source:"file"}}function bT(e,t,n,r,i){let o=$(n);if(!o)return r;let s=Nt(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 ST(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 xT(e,t){let n=e.get(t)??0;if(n>0)return n;let r=Nr(t,gs(t)),i=0;for(let[o,s]of e)o!==t&&Nr(o,gs(o))===r&&s>i&&(i=s);return i}function CT(e,t,n,r){return ps(e,t.relativePath,t.startLine,"wrapper","explicit ignore-wrapper comment",[{label:"wrapper name",value:b(t.symbol)},{label:"caller name",value:r?.symbol?b(r.symbol):Nr(n)},{label:"wrapper path",value:t.relativePath},{label:"caller path",value:n}])}var IT=75e3,DT=5e3,PT=2500;function NT(e){let t=Oe(e);return t.symbols>=IT||t.documents>=DT?PT:void 0}var ET=".scipquery-baseline.json";function hs(e,t){return t&&wT(t)?t:LT(e.config.projectRoot,t??ET)}function Xc(e,t={}){let{scope:n}=t,r=NT(e),i=[],o=Et(e,{scope:n,...pe.dead,scanLimit:r});for(let s of o.symbols)Te(e,s.relativePath)||le(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&i.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of In(e,{scope:n,...pe.isolated,scanLimit:r}))Te(e,s.relativePath)||le(e,s.symbol,s.relativePath)||i.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of Ln(e,{scope:n}))s.kind==="real"&&i.push(`cycle:${TT(s.path)}`);for(let s of Tt(e,{scope:n,...pe.similar,scanLimit:r}))i.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of Tn(e,{scope:n,...pe.extract,scanLimit:r}))i.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of Bn(e,{scope:n,...pe.wrappers,scanLimit:r}))i.push(`wrapper:${s.file}:${s.shortName}`);for(let s of On(e,{scope:n,...pe.passthroughs,scanLimit:r}))i.push(`passthrough:${s.file}:${s.shortName}`);for(let s of jn(e,{scope:n,...pe.stale,scanLimit:r}))i.push(`stale:${s.file}:${s.shortName}`);for(let s of Mn(e,{scope:n,...pe.drift,includePatternDeviations:!1}).results)i.push(`drift:${s.kind}:${s.file}:${s.dep}`);return[...new Set(i)].sort()}function TT(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 Qc(e,t={}){let n=Xc(e,{scope:t.scope}),r=hs(e,t.path);return kT(r,JSON.stringify({version:1,findings:n},null,2)+`
619
- `),{path:r,findingCount:n.length}}function Pi(e,t={}){let n=hs(e,t.path);if(!vT(n))throw new Error(`No baseline found at ${n}. Create one with: scip-query health --write-baseline`);let r=JSON.parse(RT(n,"utf-8")),i=new Set(r.findings??[]),o=Xc(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 _T=5;function Ni(e,t={}){let{base:n="HEAD",minContainment:r=.7,minCallees:i=3,minSiteCoverage:o=.4,maxHelpers:s=Number.POSITIVE_INFINITY,limit:a=20,scanLimit:c}=t,l=t.semantic!==!1,u=t.diffPlan??bt(e,{base:n}),d={available:u.note!==Vc,base:n,changedFiles:u.changedFiles,helpersChecked:0,skipped:[],findings:[]};if(!d.available||u.changedFiles.length===0)return d;let m=new F(e),p=new Set(u.changedFiles),g=new Map(u.renamedFiles.map(C=>[C.to,C.from])),y=t.baseContentAt??wi(e.config.projectRoot,n,Li(u)),h=jT(m,p,g,y);if(h.length===0)return d;let x=h.slice(0,s);h.length>s&&(d.note=`helper scoring capped at ${s} of ${h.length} new symbols`);let v=m.calleeMap(x,{semantic:l}),R=x.map(C=>({def:C,callees:Xo((v.get(C.symbolId)??[]).map(P=>P.symbol))})),L,S=()=>(L??=Ko(e,{minCallees:Math.min(3,i),scanLimit:c,semantic:l}),L);for(let{def:C,callees:P}of R){let D=b(C.symbol);if(P.size<i){d.skipped.push({helperShortName:D,helperFile:C.relativePath,reason:`fewer than ${i} meaningful callees \u2014 too small to score`});continue}let z=S(),De=OT(P,z);if(De===0){d.skipped.push({helperShortName:D,helperFile:C.relativePath,reason:"helper callee pattern is all project-wide infrastructure \u2014 too generic to score"});continue}let Ue=BT(e,C.symbolId);if(Ue.length===0){d.skipped.push({helperShortName:D,helperFile:C.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}d.helpersChecked+=1;let Me=FT({candidateIndex:z,changed:p,helperCallees:P,helperFile:C.relativePath,helperSymbol:C.symbol,minContainment:r,minSiteCoverage:o,migratedFiles:Ue});Me.length!==0&&(Me.sort((Ot,jt)=>Nf(jt.migrationScope)-Nf(Ot.migrationScope)||jt.containment-Ot.containment||jt.siteCoverage-Ot.siteCoverage||Ot.file.localeCompare(jt.file)),d.findings.push({helperSymbol:C.symbol,helperShortName:D,helperFile:C.relativePath,helperShape:"specific-callee-cluster",helperCalleeCount:P.size,specificHelperCalleeCount:De,migratedFiles:Ue.sort(),leftovers:Me.slice(0,_T)}))}return d.findings.sort((C,P)=>(P.leftovers[0]?.containment??0)-(C.leftovers[0]?.containment??0)||C.helperFile.localeCompare(P.helperFile)),d.findings=d.findings.slice(0,a),d}function FT(e){let t=[],n=AT(e.helperSymbol,e.helperFile,e.migratedFiles),r=new Set;for(let i of e.helperCallees)for(let o of e.candidateIndex.candidateIndexesByCallee.get(i)??[])r.add(o);for(let i of r){let o=e.candidateIndex.corpus[i];if(o.symbol===e.helperSymbol||e.changed.has(o.file)||o.callees.has(e.helperSymbol))continue;let s=fp(e.helperCallees,o.callees);if(s<e.minContainment)continue;let a=[...e.helperCallees].filter(u=>o.callees.has(u)),c=o.callees.size===0?0:a.length/o.callees.size;if(c<e.minSiteCoverage||!a.some(u=>(e.candidateIndex.docFreq.get(u)??0)<=e.candidateIndex.ubiquityThreshold))continue;let l=$T(n,o.symbol,o.file);t.push({symbol:o.symbol,shortName:b(o.symbol),file:o.file,...l,containment:s,siteCoverage:c,uniqueSiteCalleeCount:Math.max(0,o.callees.size-a.length),sharedCallees:a.map(b).sort()})}return t}function Nf(e){return e==="same-scope"?2:e==="unknown"?1:0}function AT(e,t,n){let r=new Set([...Yc(t),...Zc($(e))]);for(let i of n)for(let o of Yc(i))r.add(o);return r}function $T(e,t,n){let r=new Set([...Yc(n),...Zc($(t))]);if(e.size===0||r.size===0)return{migrationScope:"unknown",migrationScopeReasons:["insufficient path/name tokens to infer migration scope"]};let i=[...r].filter(o=>e.has(o)).sort();return i.length>0?{migrationScope:"same-scope",migrationScopeReasons:[`shares migration-scope token(s): ${i.slice(0,5).join(", ")}`]}:{migrationScope:"possible-subtype",migrationScopeReasons:["no path/name tokens shared with the helper or already migrated files"]}}var MT=new Set(["app","apps","common","component","components","helper","helpers","index","lib","package","packages","page","pages","route","routes","service","services","shared","spec","src","test","tests","util","utils"]);function Yc(e){return Zc(e.replace(/\.[^.]+$/,""))}function Zc(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!MT.has(t))}function OT(e,t){let n=0;for(let r of e)(t.docFreq.get(r)??0)<=t.ubiquityThreshold&&(n+=1);return n}function jT(e,t,n,r){return e.productionCallableDefinitions({requireFunctionLikeSymbol:!0}).filter(i=>{if(!t.has(i.relativePath))return!1;let o=n.get(i.relativePath)??i.relativePath,s=r(o);return s===null||!new RegExp(`\\b${HT(i.leaf)}\\b`).test(s)})}function BT(e,t){return e.all(`SELECT DISTINCT ref_d.relative_path
640
+ LIMIT 1`,t,n)}function hh(e,t,n,i,r){let o=e.definitionsForFile(n),s=Y_(t,n,i,r.start_line,r.end_line);return ot(o,s)}function Q_(e,t,n,i){if(i?.isFunctionLike){let r=[...e.get(i.symbolId)??[]].filter(o=>o!==i.relativePath);if(r.length>0)return{fanIn:r.length,source:"function"}}return{fanIn:eA(t,n),source:"file"}}function Y_(e,t,n,i,r){let o=$(n);if(!o)return i;let s=Kt(e,t).get(o);if(!s||s.length===0)return i;for(let a of s)if(a>=i&&a<=r)return a;return i}function Z_(e){let t=new Map;for(let[n,i]of e){t.has(n)||t.set(n,t.get(n)??0);for(let r of i)t.set(r,(t.get(r)??0)+1)}return t}function eA(e,t){let n=e.get(t)??0;if(n>0)return n;let i=Wi(t,qs(t)),r=0;for(let[o,s]of e)o!==t&&Wi(o,qs(o))===i&&s>r&&(r=s);return r}function tA(e,t,n,i){return Hs(e,t.relativePath,t.startLine,"wrapper","explicit ignore-wrapper comment",[{label:"wrapper name",value:v(t.symbol)},{label:"caller name",value:i?.symbol?v(i.symbol):Wi(n)},{label:"wrapper path",value:t.relativePath},{label:"caller path",value:n}])}var aA=25e3,cA=2500,lA=2500;function uA(e){let t=We(e);return t.symbols>=aA||t.documents>=cA?lA:void 0}var dA=".scipquery-baseline.json";function Us(e,t){return t&&oA(t)?t:sA(e.config.projectRoot,t??dA)}function Wl(e,t={}){let{scope:n}=t,i=uA(e),r=[],o=Qt(e,{scope:n,...Ce.dead,scanLimit:i});for(let s of o.symbols)Oe(e,s.relativePath)||be(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&r.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of zn(e,{scope:n,...Ce.isolated,scanLimit:i}))Oe(e,s.relativePath)||be(e,s.symbol,s.relativePath)||r.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of Un(e,{scope:n}))s.kind==="real"&&r.push(`cycle:${mA(s.path)}`);for(let s of Wn(e,{scope:n,...Ce.similar,scanLimit:i}))r.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of Qn(e,{scope:n,...Ce.extract,scanLimit:i}))r.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of oi(e,{scope:n,...Ce.wrappers,scanLimit:i}))r.push(`wrapper:${s.file}:${s.shortName}`);for(let s of ii(e,{scope:n,...Ce.passthroughs,scanLimit:i}))r.push(`passthrough:${s.file}:${s.shortName}`);for(let s of ri(e,{scope:n,...Ce.stale,scanLimit:i}))r.push(`stale:${s.file}:${s.shortName}`);for(let s of ni(e,{scope:n,...Ce.drift,includePatternDeviations:!1}).results)r.push(`drift:${s.kind}:${s.file}:${s.dep}`);return[...new Set(r)].sort()}function mA(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 Gl(e,t={}){let n=Wl(e,{scope:t.scope}),i=Us(e,t.path);return rA(i,JSON.stringify({version:1,findings:n},null,2)+`
641
+ `),{path:i,findingCount:n.length}}function Zr(e,t={}){let n=Us(e,t.path);if(!nA(n))throw new Error(`No baseline found at ${n}. Create one with: scip-query health --write-baseline`);let i=JSON.parse(iA(n,"utf-8")),r=new Set(i.findings??[]),o=Wl(e,{scope:t.scope}),s=new Set(o);return{baselinePath:n,baselineCount:r.size,current:o,newFindings:o.filter(a=>!r.has(a)),fixedFindings:[...r].filter(a=>!s.has(a))}}var pA=5;function eo(e,t={}){let{base:n="HEAD",minContainment:i=.7,minCallees:r=3,minSiteCoverage:o=.4,maxHelpers:s=Number.POSITIVE_INFINITY,limit:a=20,scanLimit:c}=t,l=t.semantic!==!1,d=t.diffPlan??Tt(e,{base:n}),u={available:d.note!==Al,base:n,changedFiles:d.changedFiles,helpersChecked:0,skipped:[],findings:[]};if(!u.available||d.changedFiles.length===0)return u;let m=new A(e),p=new Set(d.changedFiles),f=new Map(d.renamedFiles.map(L=>[L.to,L.from])),g=t.baseContentAt??Kr(e.config.projectRoot,n,Jr(d)),b=SA(m,p,f,g);if(b.length===0)return u;let x=b.slice(0,s);b.length>s&&(u.note=`helper scoring capped at ${s} of ${b.length} new symbols`);let S=m.calleeMap(x,{semantic:l}),R=x.map(L=>({def:L,callees:ws((S.get(L.symbolId)??[]).map(k=>k.symbol))})),C=Vi(e),y,w=()=>(y??=C.calleeIndex({minCallees:Math.min(3,r),scanLimit:c,semantic:l}),y);for(let{def:L,callees:k}of R){let T=v(L.symbol);if(k.size<r){u.skipped.push({helperShortName:T,helperFile:L.relativePath,reason:`fewer than ${r} meaningful callees \u2014 too small to score`});continue}let U=w(),Y=bA(k,U);if(Y===0){u.skipped.push({helperShortName:T,helperFile:L.relativePath,reason:"helper callee pattern is all project-wide infrastructure \u2014 too generic to score"});continue}let ee=xA(e,L.symbolId);if(ee.length===0){u.skipped.push({helperShortName:T,helperFile:L.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}u.helpersChecked+=1;let we=fA({candidateIndex:U,changed:p,helperCallees:k,helperFile:L.relativePath,helperSymbol:L.symbol,minContainment:i,minSiteCoverage:o,migratedFiles:ee});we.length!==0&&(we.sort((te,rn)=>yh(rn.migrationScope)-yh(te.migrationScope)||rn.containment-te.containment||rn.siteCoverage-te.siteCoverage||te.file.localeCompare(rn.file)),u.findings.push({helperSymbol:L.symbol,helperShortName:T,helperFile:L.relativePath,helperShape:"specific-callee-cluster",helperCalleeCount:k.size,specificHelperCalleeCount:Y,migratedFiles:ee.sort(),leftovers:we.slice(0,pA)}))}return u.findings.sort((L,k)=>(k.leftovers[0]?.containment??0)-(L.leftovers[0]?.containment??0)||L.helperFile.localeCompare(k.helperFile)),u.findings=u.findings.slice(0,a),u}function fA(e){let t=[],n=gA(e.helperSymbol,e.helperFile,e.migratedFiles),i=new Set;for(let r of e.helperCallees)for(let o of e.candidateIndex.candidateIndexesByCallee.get(r)??[])i.add(o);for(let r of i){let o=e.candidateIndex.corpus[r];if(o.symbol===e.helperSymbol||e.changed.has(o.file)||o.callees.has(e.helperSymbol))continue;let s=Wf(e.helperCallees,o.callees);if(s<e.minContainment)continue;let a=[...e.helperCallees].filter(d=>o.callees.has(d)),c=o.callees.size===0?0:a.length/o.callees.size;if(c<e.minSiteCoverage||!a.some(d=>(e.candidateIndex.docFreq.get(d)??0)<=e.candidateIndex.ubiquityThreshold))continue;let l=hA(n,o.symbol,o.file);t.push({symbol:o.symbol,shortName:v(o.symbol),file:o.file,...l,containment:s,siteCoverage:c,uniqueSiteCalleeCount:Math.max(0,o.callees.size-a.length),sharedCallees:a.map(v).sort()})}return t}function yh(e){return e==="same-scope"?2:e==="unknown"?1:0}function gA(e,t,n){let i=new Set([...Kl(t),...Jl($(e))]);for(let r of n)for(let o of Kl(r))i.add(o);return i}function hA(e,t,n){let i=new Set([...Kl(n),...Jl($(t))]);if(e.size===0||i.size===0)return{migrationScope:"unknown",migrationScopeReasons:["insufficient path/name tokens to infer migration scope"]};let r=[...i].filter(o=>e.has(o)).sort();return r.length>0?{migrationScope:"same-scope",migrationScopeReasons:[`shares migration-scope token(s): ${r.slice(0,5).join(", ")}`]}:{migrationScope:"possible-subtype",migrationScopeReasons:["no path/name tokens shared with the helper or already migrated files"]}}var yA=new Set(["app","apps","common","component","components","helper","helpers","index","lib","package","packages","page","pages","route","routes","service","services","shared","spec","src","test","tests","util","utils"]);function Kl(e){return Jl(e.replace(/\.[^.]+$/,""))}function Jl(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!yA.has(t))}function bA(e,t){let n=0;for(let i of e)(t.docFreq.get(i)??0)<=t.ubiquityThreshold&&(n+=1);return n}function SA(e,t,n,i){return e.productionCallableDefinitions({files:[...t],requireFunctionLikeSymbol:!0}).filter(r=>{if(!t.has(r.relativePath))return!1;let o=n.get(r.relativePath)??r.relativePath,s=i(o);return s===null||!new RegExp(`\\b${CA(r.leaf)}\\b`).test(s)})}function xA(e,t){return e.all(`SELECT DISTINCT ref_d.relative_path
620
642
  FROM mentions m
621
643
  JOIN chunks c ON m.chunk_id = c.id
622
644
  JOIN documents ref_d ON c.document_id = ref_d.id
623
645
  WHERE m.symbol_id = ?
624
646
  AND m.role != 1
625
- ${e.pathExclusionsFor("ref_d")}`,t).map(r=>r.relative_path)}function HT(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ei(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new F(e);return Ze({candidates:()=>o.productionCallableDefinitions({scope:n,files:t.files,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}).filter(s=>VT(s.relativePath)),scanLimit:i,evaluate:s=>{let a=me(e,s.relativePath)?.callables.find(u=>u.startLine===s.startLine&&u.endLine===s.endLine);if(!a||a.params.length===0||a.params.some(u=>!u.simple)||a.paramsEndLine>=a.endLine)return null;let c=Nt(e,s.relativePath),l=[];for(let u=a.params.length-1;u>=0;u--){let d=a.params[u];if(d.name===""||d.name.startsWith("_")||qT(c.get(d.name),a.paramsEndLine,a.endLine))break;l.unshift(d.name)}return l.length===0?null:{symbol:s.symbol,shortName:b(s.symbol),file:s.relativePath,startLine:s.startLine,endLine:s.endLine,paramCount:a.paramCount,unusedTrailing:l}},orderResults:(s,a)=>a.unusedTrailing.length-s.unusedTrailing.length||s.file.localeCompare(a.file)||s.startLine-a.startLine,limit:r})}function VT(e){let t=W(e);return t==="typescript"||t==="tsx"||t==="javascript"}function qT(e,t,n){return e?e.some(r=>r>t&&r<=n):!1}var bs=["echo","incomplete-migration","co-change-partner","doc-reference","unused-params","new-dead","baseline"];function Ti(e,t={}){let n=t.base??"HEAD",{minTogether:r=6,minConfidence:i=.6,maxEchoChecks:o=Number.POSITIVE_INFINITY,maxHelpers:s=Number.POSITIVE_INFINITY,minSimilarity:a=.8,includeBaseline:c=!1,scanLimit:l}=t,u=t.semantic!==!1,d=new Set(t.skip??[]),m=bt(e,{base:n}),p=Dr(e,{base:n,plan:m}),g=p.changedFiles,y=new Set(g),h=new Set(m.changedFileLines),x=new Set([...y,...h]),v=wi(e.config.projectRoot,n,Li(m,g)),R=g_(e.config.projectRoot,n,m,v),L={base:n,changedFiles:g,changedSymbols:p.changedSymbols.length,checksRun:[],skipped:[],suppressed:[],findings:[],rootCauseGroups:[],note:p.summary.note};if(g.length===0)return L;let S=(C,P)=>{if(d.has(C)){L.skipped.push({check:C,reason:"skipped via --skip"});return}P()};return S("echo",()=>XT(e,p.changedSymbols,y,R,o,a,l,u,L)),S("incomplete-migration",()=>o_(e,n,m,s,l,u,v,L)),S("co-change-partner",()=>s_(e,x,r,i,L)),S("doc-reference",()=>d_(e,y,h,m.changedRanges,L)),S("unused-params",()=>m_(e,g,L)),S("new-dead",()=>p_(e,p.changedSymbols,R,L)),c&&S("baseline",()=>b_(e,L)),JT(L,e.config.suppressions??[]),L.rootCauseGroups=WT(L.findings),L}function WT(e){let t=new Map;for(let n of e){let r=n.groupKey??`${n.check}:${n.id}`,i=t.get(r);i||(i={groupKey:r,check:n.check,severity:n.severity,actionTier:n.actionTier,sourceAnalyzer:n.sourceAnalyzer,rootCauseKey:n.rootCauseKey,count:0,findingIds:[],files:new Set,relatedFiles:new Set,message:n.message,remediation:n.remediation},t.set(r,i)),i.count+=1,i.findingIds.push(n.id),i.severity=GT(i.severity,n.severity),i.actionTier=zT(i.actionTier,n.actionTier),n.file&&i.files.add(n.file);for(let o of n.relatedFiles??[])i.relatedFiles.add(o)}return[...t.values()].map(n=>({...n,files:[...n.files].sort(),relatedFiles:[...n.relatedFiles].sort()})).sort((n,r)=>r.count-n.count||ys(r.severity)-ys(n.severity)||n.groupKey.localeCompare(r.groupKey))}function GT(e,t){return ys(t)>ys(e)?t:e}function ys(e){return e==="error"?2:e==="warning"?1:0}function zT(e,t){return e?t&&Ef(t)>Ef(e)?t:e:t}function Ef(e){return e==="direct"?2:e==="signal"?1:0}function JT(e,t){if(t.length===0||e.findings.length===0)return;let n=[];for(let r of e.findings){let i=t.find(o=>KT(o,r));i?e.suppressed.push({finding:r,suppression:i}):n.push(r)}e.findings=n}function KT(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 Er(e,t){e.findings.push({...t,suppressionHint:`scip-query: ignore ${t.check} ${t.id} -- <reason>`})}function XT(e,t,n,r,i,o,s,a,c){c.checksRun.push("echo");for(let l of t.slice(0,i)){if(!ie(l.symbol)||r(l))continue;let u=xi(e,l.symbol,{minSimilarity:o,limit:5,scanLimit:s,semantic:a}),d=[];for(let y of u){let h=y.fileA===l.file?y.fileB:y.fileA,x=y.fileA===l.file?y.shortNameB:y.shortNameA,v=y.fileA===l.file?y.symbolB:y.symbolA;n.has(h)||d.push({otherFile:h,otherShort:x,otherSymbol:v,similarity:y.similarity,similarityBasis:y.similarityBasis??"callees",sharedEvidence:y.sharedCallees})}if(d.length===0)continue;let m=d[0],p=Hn("echo",l.symbol,l.file,...d.map(y=>`${y.otherSymbol}|${y.otherFile}`).sort()),g=QT(l,d);Er(c,{id:p,groupKey:p,actionTier:g,check:"echo",severity:"warning",evidence:"heuristic",confidence:m.similarity,file:l.file,symbol:l.symbol,relatedFiles:[...new Set(d.map(y=>y.otherFile))].sort(),message:n_(l,d),why:r_(l,d),remediation:i_(g,l.shortName,m.otherShort)})}t.length>i&&c.skipped.push({check:"echo",reason:`echo check capped at ${i} of ${t.length} changed symbols`})}function QT(e,t){return t.some(r=>YT(e.symbol,r))?"direct":"signal"}function YT(e,t){if(t.similarityBasis!=="source-tokens"||t.similarity<.98||t.sharedEvidence.length>8)return!1;let n=$(e),r=$(t.otherSymbol);return!n||!r?!1:n===r?!0:t_(t.sharedEvidence)?!1:ZT(n,r)}function ZT(e,t){let n=Tf(e),r=Tf(t);if(n.length===0||r.length===0)return!1;let i=new Set(r),o=n.filter(s=>i.has(s)).length;return o>=2&&o/Math.min(n.length,r.length)>=.5}function Tf(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).map(t=>t.toLowerCase()).filter(t=>t.length>=2)}var e_=new Set(["bytes","crypto","hex","num","random","secret","to","token"]);function t_(e){return e.length>=3&&e.every(t=>e_.has(t.toLowerCase()))}function n_(e,t){let n=t[0],r=Math.round(n.similarity*100);return t.length===1?`${e.shortName} (${e.file}) is ${r}% similar to established ${n.otherShort} (${n.otherFile})`:`${e.shortName} (${e.file}) resembles ${t.length} established symbol(s); strongest is ${r}% similar to ${n.otherShort} (${n.otherFile})`}function r_(e,t){let n=[`${e.shortName} was changed in this diff.`];for(let r of t.slice(0,3))n.push(`${r.otherShort} is outside this diff and scored ${Math.round(r.similarity*100)}% similar by ${r.similarityBasis} evidence.`),n.push(`Shared evidence: ${r.sharedEvidence.slice(0,5).join(", ")||"(none listed)"}.`);return t.length>3&&n.push(`${t.length-3} additional similar match(es) grouped into this finding.`),n}function i_(e,t,n){return e==="direct"?`Extract or reuse the shared behavior with ${n}, or keep the duplicate with a suppression reason.`:`Review whether ${t} is intentionally parallel to the established implementation(s); extract shared behavior only if the product semantics match.`}function o_(e,t,n,r,i,o,s,a){let c=Ni(e,{base:t,maxHelpers:r,diffPlan:n,scanLimit:i,semantic:o,baseContentAt:s});if(!c.available){a.skipped.push({check:"incomplete-migration",reason:"no git history"});return}a.checksRun.push("incomplete-migration"),c.note&&a.skipped.push({check:"incomplete-migration",reason:c.note});for(let l of c.findings){let u=l.leftovers.map(h=>`${h.shortName} (${h.file}, ${Math.round(h.containment*100)}% helper / ${Math.round(h.siteCoverage*100)}% site, ${h.migrationScope})`).join(", "),d=l.leftovers.map(h=>`${h.shortName}: ${h.migrationScope} (${h.migrationScopeReasons[0]})`).join("; "),m=[...l.migratedFiles,...l.leftovers.map(h=>h.file)],p=l.leftovers.length===0?void 0:Math.max(...l.leftovers.map(h=>Math.min(h.containment,h.siteCoverage))),g=l.leftovers.some(h=>h.migrationScope==="possible-subtype"),y=Hn("incomplete-migration",l.helperSymbol,l.helperFile,m.join("|"));Er(a,{id:y,check:"incomplete-migration",severity:"warning",evidence:"heuristic",confidence:p,file:l.helperFile,symbol:l.helperSymbol,relatedFiles:m,message:`new helper ${l.helperShortName} (${l.helperFile}) is wired into ${l.migratedFiles.length} file(s), but ${l.leftovers.length} similar un-migrated site(s) remain: ${u}`,why:[`${l.helperShortName} is new in this diff and already referenced by ${l.migratedFiles.join(", ")}.`,`Helper shape: ${l.helperShape}; ${l.specificHelperCalleeCount}/${l.helperCalleeCount} helper callees are specific enough to score.`,`Unchanged site(s) still contain the helper's callee pattern: ${u}.`,`Migration scope hints: ${d}.`],remediation:g?`Migrate same-scope sites to ${l.helperShortName}; review possible subtype/variant sites before applying the helper.`:`Migrate the remaining sites to ${l.helperShortName}, or confirm they are intentionally different.`})}}function s_(e,t,n,r,i){let o=Qp(e,t,{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,a;for(let c of o){let l=t.has(c.fileA),u=t.has(c.fileB);if(l===u)continue;let d=l?c.fileA:c.fileB,m=l?c.fileB:c.fileA,p=l?c.changesA:c.changesB,g=p>0?c.together/p:0;if(g<r||Oc(m)||Oc(d)||!_f(`${e.config.projectRoot}/${m}`))continue;let y=`${d}|${m}`;if(s.has(y))continue;s.add(y);let h=Hn("co-change-partner",d,m,String(c.together)),x=jc(d,m),v=Bc({fileA:d,fileB:m,together:c.together,confidence:g,commitScope:c.commitScope,recency:c.recency,subjectContext:c.subjectContext},x,(a??=Hc(e))(d,m)),R=[d,m].sort().join("|");i.findings.push({id:h,check:"co-change-partner",severity:"warning",evidence:"change-graph",actionTier:"signal",groupKey:`co-change-partner:${R}`,confidence:g,file:d,relatedFiles:[m],sourceAnalyzer:"co-change",rootCauseKey:R,partnerClass:x.partnerClass,partnerClassReasons:x.reasons,commitScope:c.commitScope,recency:c.recency,focusedTogether:c.focusedTogether,broadTogether:c.broadTogether,broadCommitRatio:c.broadCommitRatio,lastTogetherAt:c.lastTogetherAt,recentTogether:c.recentTogether,subjectContext:c.subjectContext,...v?{declaredCouplingSuggestion:v}:{},message:`${d} changed, but ${m} did not \u2014 they change together ${c.together}x (${Math.round(g*100)}% of the time)`,why:[`${d} is in this diff and ${m} is not.`,`Git history shows ${c.together} co-change(s), which is ${Math.round(g*100)}% of changes to the edited side.`,`History context: ${a_(c)}.`,`Subject context: ${c_(c.subjectContext)}.`,...l_(c),`Partner class: ${x.partnerClass} (${x.reasons.join("; ")}).`],remediation:v?`Update ${m} alongside this change, declare the coupling "${v.name}", or confirm the coupling no longer holds.`:`Update ${m} alongside this change, or confirm the coupling no longer holds.`})}}function a_(e){return`${e.commitScope}/${e.recency}; ${e.focusedTogether} focused, ${e.broadTogether} broad-sweep (${Math.round(e.broadCommitRatio*100)}% broad), ${e.recentTogether} recent, last ${u_(e.lastTogetherAt)}`}function c_(e){let t=e.subjectLabels.length>0?e.subjectLabels.slice(0,5).join(", "):"none inferred",n=e.issueRefs.length>0?e.issueRefs.slice(0,5).join(", "):"none",r=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(i=>`"${i}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${r}; external issue/PR labels ${e.externalIssueLabelStatus}`}function l_(e){let t=[];return e.commitScope==="broad-sweep"&&t.push("Broad-sweep history is weaker than focused co-edits; confirm this is a real coordination contract."),e.recency==="stale"&&t.push("The pair has no co-change in the recent history window; confirm the coupling still holds."),t}function u_(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function d_(e,t,n,r,i){i.checksRun.push("doc-reference");let o=Pr.referenceTargets(e,t,r);if(o.size!==0)for(let s of hf(e,o)){if(n.has(s.doc))continue;let a=s.citedClaims.length>0?s.citedClaims:Pr.citationContexts(e,s.doc,s.cited),c=Pr.classifyCitation(a),l=Hn("doc-reference",s.doc,s.cited.join("|"));Er(i,{id:l,check:"doc-reference",severity:"warning",evidence:"change-graph",actionTier:c.actionTier,confidence:1,file:s.doc,relatedFiles:s.cited,citationKind:c.citationKind,citationKindReasons:c.reasons,citedClaims:a,message:`${s.doc} cites ${s.cited.join(", ")} as ${Pr.citationKindLabel(c.citationKind)} \u2014 changed in this diff, doc untouched`,why:[`${s.cited.join(", ")} changed in this diff.`,`${s.doc} cites the changed file(s) but was not updated in the same diff.`,...c.reasons.map(u=>`Citation kind evidence: ${u}`)],remediation:Pr.citationRemediation(c.citationKind,s.doc)})}}function m_(e,t,n){n.checksRun.push("unused-params");for(let r of Ei(e,{files:t,limit:50})){let i=Hn("unused-params",r.symbol,r.file,r.unusedTrailing.join("|"));Er(n,{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."})}}function p_(e,t,n,r){r.checksRun.push("new-dead");let i=new F(e);for(let o of t){if(n(o)||o.fanIn>0||i.fileKind(o.file)==="test"||Te(e,o.file)||le(e,o.symbol,o.file)||f_(o.symbol))continue;let s=Hn("new-dead",o.symbol,o.file);Er(r,{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."})}}function f_(e){if(re(e)!=="type")return!1;let t=$(e);return t.startsWith("_Assert")||t.startsWith("Assert")}function g_(e,t,n,r){let i=new Map(n.renamedFiles.map(s=>[s.to,s.from])),o=r??wi(e,t,Li(n));return s=>{let a=i.get(s.file)??s.file,c=$(s.symbol);if(!c)return!1;let l=o(a);return l!==null&&h_(l,c)}}function h_(e,t){return new RegExp(`\\b${y_(t)}\\b`).test(e)}function y_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function b_(e,t){if(!_f(hs(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=Pi(e);for(let r of n.newFindings){let i=uf(r),o=Hn("baseline",r);Er(t,{id:o,groupKey:`baseline:${i.sourceAnalyzer}:${i.rootCauseKey}`,check:"baseline",severity:"error",evidence:"baseline",actionTier:i.actionTier,confidence:1,file:i.file,relatedFiles:i.relatedFiles.length>0?i.relatedFiles:void 0,sourceAnalyzer:i.sourceAnalyzer,rootCauseKey:i.rootCauseKey,message:`new ${i.label} vs committed baseline: ${r}`,why:["A committed health baseline exists.","The current health result contains a finding not present in that baseline.",`Underlying analyzer: ${i.sourceAnalyzer}.`,`Inherited action tier: ${i.actionTier}.`,`Root cause key: ${i.rootCauseKey}.`,...i.why],remediation:i.remediation})}}function Hn(e,...t){return`SQ${UT("sha256").update([e,...t].join("\0")).digest("hex").slice(0,12).toUpperCase()}`}var S_=.7,Ff=.62,Af=.45;function el(e,t={}){let{windowCommits:n=100,limit:r=30,scope:i,scanLimit:o}=t,s=Kp(e);if(!s)return{available:!1,windowCommits:n,findings:[]};if(r<=0)return{available:!0,windowCommits:n,findings:[]};let a=L_(s,n);if(a.size===0)return{available:!0,windowCommits:n,findings:[]};let l=x_(e,{limit:r,minSimilarity:t.minSimilarity,scanLimit:o,scope:i,semantic:t.semantic,focusFiles:Number.isFinite(r)?void 0:a}).map(d=>I_(d,s,n)).filter(d=>d!==null);l.sort((d,m)=>(d.kind===m.kind?0:d.kind==="echo"?-1:1)||m.similarity-d.similarity||d.echoFile.localeCompare(m.echoFile)||d.echoSymbol.localeCompare(m.echoSymbol)||d.domain.localeCompare(m.domain));let u=l.slice(0,r).map(D_);return{available:!0,windowCommits:n,findings:u,rootCauseGroups:P_(u)}}function x_(e,t){let n=E_(t.limit),r=[...C_(e,{scope:t.scope,minSimilarity:t.minSimilarity??S_,limit:n,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles})],i=lo(e,{scope:t.scope});return i.react&&r.push(...v_(e,{scope:t.scope,minSimilarity:t.minSimilarity??Ff,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...R_(e,{scope:t.scope,minSimilarity:t.minSimilarity??Af,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),i.vue&&r.push(...k_(e,{scope:t.scope,minSimilarity:t.minSimilarity??Ff,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...w_(e,{scope:t.scope,minSimilarity:t.minSimilarity??Af,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),r}function C_(e,t){return Tt(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles}).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 v_(e,t){return xs(e,t,{query:Dn,domain:"react-component",basis:"jsx-structure",symbolA:n=>n.componentA,symbolB:n=>n.componentB,evidenceBuckets:n=>[["component",n.sharedComponents],["tag",n.sharedNativeTags],["prop",n.sharedProps],["event",n.sharedEvents],["binding",n.sharedBindings]]})}function xs(e,t,n){return n.query(e,t).filter(r=>r.fileA!==r.fileB).map(r=>({domain:n.domain,basis:n.basis,symbolA:n.symbolA(r),fileA:r.fileA,symbolB:n.symbolB(r),fileB:r.fileB,similarity:r.similarity,sharedEvidence:T_(...n.evidenceBuckets(r)),sharedCallees:[]}))}function R_(e,t){return xs(e,t,{query:Pn,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,evidenceBuckets:n=>[["hook",n.sharedHooks],["react-hook",n.sharedReactHooks],["effect",n.sharedEffects],["state",n.sharedState],["request",n.sharedRequests],["handler",n.sharedHandlers],["action",n.sharedHandlerVerbs]]})}function k_(e,t){return xs(e,t,{query:Nn,domain:"vue-component",basis:"vue-template",symbolA:n=>Ss(n.fileA),symbolB:n=>Ss(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function w_(e,t){return xs(e,t,{query:En,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>Ss(n.fileA),symbolB:n=>Ss(n.fileB),evidenceBuckets:n=>[["composable",n.sharedComposables],["store",n.sharedStores],["reactivity",n.sharedReactivity],["lifecycle",n.sharedLifecycle],["request",n.sharedRequests],["function",n.sharedFunctions],["action",n.sharedFunctionVerbs],["binding",n.sharedBindings],["template-event",n.sharedTemplateEvents]]})}function L_(e,t){let n=new Set;for(let[r,i]of e)i.commitsAgo<=t&&n.add(r);return n}function I_(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 D_(e){let t=$f(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function $f(e){if(e.kind==="echo")return["echo",e.domain,e.basis,e.establishedSymbol].join(":");let t=e.sharedEvidence.slice().sort().join("|"),n=[e.echoSymbol,e.establishedSymbol].sort().join("|");return["twin",e.domain,e.basis,t||n].join(":")}function P_(e){let t=new Map;for(let[n,r]of e.entries()){let i=r.rootCauseKey??$f(r),o=r.groupKey??`recent-duplicate:${i}`,s=t.get(o);s||(s={groupKey:o,rootCauseKey:i,kind:r.kind,domain:r.domain,basis:r.basis,count:0,maxSimilarity:r.similarity,findingIndexes:[],echoFiles:new Set,establishedFile:r.kind==="echo"?r.establishedFile:void 0,establishedSymbol:r.kind==="echo"?r.establishedSymbol:void 0,relatedFiles:new Set,sharedEvidence:new Set,recommendation:N_(r)},t.set(o,s)),s.count+=1,s.maxSimilarity=Math.max(s.maxSimilarity,r.similarity),s.findingIndexes.push(n),s.echoFiles.add(r.echoFile),s.relatedFiles.add(r.echoFile),s.relatedFiles.add(r.establishedFile);for(let a of r.sharedEvidence)s.sharedEvidence.add(a)}return[...t.values()].map(n=>({...n,echoFiles:[...n.echoFiles].sort(),relatedFiles:[...n.relatedFiles].sort(),sharedEvidence:[...n.sharedEvidence].sort().slice(0,16)})).sort((n,r)=>r.count-n.count||r.maxSimilarity-n.maxSimilarity||n.groupKey.localeCompare(r.groupKey))}function N_(e){return e.kind==="echo"?"Review the established side once, then migrate or delete every echo in this group.":"Pick one owner for the new twins and consolidate the group before the copies diverge."}function E_(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function T_(...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 Ss(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var __=Z("suppression-inventory",{clearGroups:["whole-project"]});function Cs(e){return __.get(e,()=>F_(e))}function F_(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 Ne(e)){let o=T(e,i);if(!(!o||!o.includes("scip-query")))for(let s of o.split(/\r?\n/)){let a=Jr(s);if(a===null)continue;r+=1,n.set(i,(n.get(i)??0)+1);let c=A_(a);t[c]+=1}}return{total:r,byCategory:t,byFile:n}}function A_(e){if(!e)return"uncategorized";let t=e.toLowerCase();return t==="dead-code"?"dead":t}import{readFileSync as $_}from"fs";import{join as M_}from"path";function _i(e,t,n={}){let r=B(e,t);if(!r)return null;let i=new F(e),o=V_(j_(e,r.relativePath,r.startLine,r.endLine),O_(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:B_(e,r.symbolId),fanOut:H_(c,r.relativePath)}}function O_(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function j_(e,t,n,r){try{return $_(M_(e.config.projectRoot,t),"utf-8").split(`
626
- `).slice(n,r+1).join(`
627
- `)}catch{return""}}function B_(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
647
+ ${e.pathExclusionsFor("ref_d")}`,t).map(i=>i.relative_path)}function CA(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function to(e,t={}){let{scope:n,limit:i=30,scanLimit:r}=t,o=new A(e);return lt({candidates:()=>o.productionCallableDefinitions({scope:n,files:t.files,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}),filterCandidate:s=>vA(s.relativePath),scanLimit:r,profile:{name:"unused-params"},evaluate:s=>{let a=X(e,s.relativePath)?.callables.find(d=>d.startLine===s.startLine&&d.endLine===s.endLine);if(!a||a.params.length===0||a.params.some(d=>!d.simple)||a.paramsEndLine>=a.endLine)return null;let c=Kt(e,s.relativePath),l=[];for(let d=a.params.length-1;d>=0;d--){let u=a.params[d];if(u.name===""||u.name.startsWith("_")||RA(c.get(u.name),a.paramsEndLine,a.endLine))break;l.unshift(u.name)}return l.length===0?null:{symbol:s.symbol,shortName:v(s.symbol),file:s.relativePath,startLine:s.startLine,endLine:s.endLine,paramCount:a.paramCount,unusedTrailing:l}},orderResults:(s,a)=>a.unusedTrailing.length-s.unusedTrailing.length||s.file.localeCompare(a.file)||s.startLine-a.startLine,limit:i})}function vA(e){let t=H(e);return t==="typescript"||t==="tsx"||t==="javascript"}function RA(e,t,n){return e?e.some(i=>i>t&&i<=n):!1}var Ws=["echo","incomplete-migration","co-change-partner","doc-reference","unused-params","new-dead","baseline"];function no(e,t={}){let n=t.base??"HEAD",{minTogether:i=6,minConfidence:r=.6,maxEchoChecks:o=Number.POSITIVE_INFINITY,maxHelpers:s=Number.POSITIVE_INFINITY,minSimilarity:a=.8,includeBaseline:c=!1,scanLimit:l}=t,d=t.semantic!==!1,u=new Set(t.skip??[]),m=Tt(e,{base:n}),p=Ui(e,{base:n,plan:m}),f=p.changedFiles,g=new Set(f),b=new Set(m.changedFileLines),x=new Set([...g,...b]),S=Kr(e.config.projectRoot,n,Jr(m,f)),R=JA(e.config.projectRoot,n,m,S),C={base:n,changedFiles:f,changedSymbols:p.changedSymbols.length,checksRun:[],skipped:[],suppressed:[],findings:[],rootCauseGroups:[],note:p.summary.note};if(f.length===0)return C;let y=(w,L)=>{if(u.has(w)){C.skipped.push({check:w,reason:"skipped via --skip"});return}let k=C.findings.length,T=C.skipped.length,U=C.checksRun.length;D(`diff-gate.check.${w}`,L,()=>({check:w,changedFiles:f.length,changedSymbols:p.changedSymbols.length,findingsAdded:C.findings.length-k,skippedAdded:C.skipped.length-T,checksRunAdded:C.checksRun.length-U}))};return y("echo",()=>EA(e,p.changedSymbols,g,R,o,a,l,d,C)),y("incomplete-migration",()=>OA(e,n,m,s,l,d,S,C)),y("co-change-partner",()=>BA(e,x,i,r,C)),y("doc-reference",()=>zA(e,g,b,m.changedRanges,C)),y("unused-params",()=>WA(e,f,C)),y("new-dead",()=>GA(e,p.changedSymbols,R,C)),c&&y("baseline",()=>YA(e,C)),LA(C,e.config.suppressions??[]),C.rootCauseGroups=wA(C.findings),C}function wA(e){let t=new Map;for(let n of e){let i=n.groupKey??`${n.check}:${n.id}`,r=t.get(i);r||(r={groupKey:i,check:n.check,severity:n.severity,actionTier:n.actionTier,sourceAnalyzer:n.sourceAnalyzer,rootCauseKey:n.rootCauseKey,count:0,findingIds:[],files:new Set,relatedFiles:new Set,message:n.message,remediation:n.remediation},t.set(i,r)),r.count+=1,r.findingIds.push(n.id),r.severity=PA(r.severity,n.severity),r.actionTier=IA(r.actionTier,n.actionTier),n.file&&r.files.add(n.file);for(let o of n.relatedFiles??[])r.relatedFiles.add(o)}return[...t.values()].map(n=>({...n,files:[...n.files].sort(),relatedFiles:[...n.relatedFiles].sort()})).sort((n,i)=>i.count-n.count||zs(i.severity)-zs(n.severity)||n.groupKey.localeCompare(i.groupKey))}function PA(e,t){return zs(t)>zs(e)?t:e}function zs(e){return e==="error"?2:e==="warning"?1:0}function IA(e,t){return e?t&&bh(t)>bh(e)?t:e:t}function bh(e){return e==="direct"?2:e==="signal"?1:0}function LA(e,t){if(t.length===0||e.findings.length===0)return;let n=[];for(let i of e.findings){let r=t.find(o=>DA(o,i));r?e.suppressed.push({finding:i,suppression:r}):n.push(i)}e.findings=n}function DA(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 Gi(e,t){e.findings.push({...t,suppressionHint:`scip-query: ignore ${t.check} ${t.id} -- <reason>`})}function EA(e,t,n,i,r,o,s,a,c){c.checksRun.push("echo");for(let l of t.slice(0,r)){if(!he(l.symbol)||i(l))continue;let d=Vr(e,l.symbol,{minSimilarity:o,limit:5,scanLimit:s,semantic:a,sourceCandidateMode:"target-pruned"}),u=[];for(let g of d){let b=g.fileA===l.file?g.fileB:g.fileA,x=g.fileA===l.file?g.shortNameB:g.shortNameA,S=g.fileA===l.file?g.symbolB:g.symbolA;n.has(b)||u.push({otherFile:b,otherShort:x,otherSymbol:S,similarity:g.similarity,similarityBasis:g.similarityBasis??"callees",sharedEvidence:g.sharedCallees})}if(u.length===0)continue;let m=u[0],p=si("echo",l.symbol,l.file,...u.map(g=>`${g.otherSymbol}|${g.otherFile}`).sort()),f=NA(l,u);Gi(c,{id:p,groupKey:p,actionTier:f,check:"echo",severity:"warning",evidence:"heuristic",confidence:m.similarity,file:l.file,symbol:l.symbol,relatedFiles:[...new Set(u.map(g=>g.otherFile))].sort(),message:MA(l,u),why:$A(l,u),remediation:jA(f,l.shortName,m.otherShort)})}t.length>r&&c.skipped.push({check:"echo",reason:`echo check capped at ${r} of ${t.length} changed symbols`})}function NA(e,t){return t.some(i=>FA(e.symbol,i))?"direct":"signal"}function FA(e,t){if(t.similarityBasis!=="source-tokens"||t.similarity<.98||t.sharedEvidence.length>8)return!1;let n=$(e),i=$(t.otherSymbol);return!n||!i?!1:n===i?!0:AA(t.sharedEvidence)?!1:TA(n,i)}function TA(e,t){let n=Sh(e),i=Sh(t);if(n.length===0||i.length===0)return!1;let r=new Set(i),o=n.filter(s=>r.has(s)).length;return o>=2&&o/Math.min(n.length,i.length)>=.5}function Sh(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).map(t=>t.toLowerCase()).filter(t=>t.length>=2)}var _A=new Set(["bytes","crypto","hex","num","random","secret","to","token"]);function AA(e){return e.length>=3&&e.every(t=>_A.has(t.toLowerCase()))}function MA(e,t){let n=t[0],i=Math.round(n.similarity*100);return t.length===1?`${e.shortName} (${e.file}) is ${i}% similar to established ${n.otherShort} (${n.otherFile})`:`${e.shortName} (${e.file}) resembles ${t.length} established symbol(s); strongest is ${i}% similar to ${n.otherShort} (${n.otherFile})`}function $A(e,t){let n=[`${e.shortName} was changed in this diff.`];for(let i of t.slice(0,3))n.push(`${i.otherShort} is outside this diff and scored ${Math.round(i.similarity*100)}% similar by ${i.similarityBasis} evidence.`),n.push(`Shared evidence: ${i.sharedEvidence.slice(0,5).join(", ")||"(none listed)"}.`);return t.length>3&&n.push(`${t.length-3} additional similar match(es) grouped into this finding.`),n}function jA(e,t,n){return e==="direct"?`Extract or reuse the shared behavior with ${n}, or keep the duplicate with a suppression reason.`:`Review whether ${t} is intentionally parallel to the established implementation(s); extract shared behavior only if the product semantics match.`}function OA(e,t,n,i,r,o,s,a){let c=eo(e,{base:t,maxHelpers:i,diffPlan:n,scanLimit:r,semantic:o,baseContentAt:s});if(!c.available){a.skipped.push({check:"incomplete-migration",reason:"no git history"});return}a.checksRun.push("incomplete-migration"),c.note&&a.skipped.push({check:"incomplete-migration",reason:c.note});for(let l of c.findings){let d=l.leftovers.map(b=>`${b.shortName} (${b.file}, ${Math.round(b.containment*100)}% helper / ${Math.round(b.siteCoverage*100)}% site, ${b.migrationScope})`).join(", "),u=l.leftovers.map(b=>`${b.shortName}: ${b.migrationScope} (${b.migrationScopeReasons[0]})`).join("; "),m=[...l.migratedFiles,...l.leftovers.map(b=>b.file)],p=l.leftovers.length===0?void 0:Math.max(...l.leftovers.map(b=>Math.min(b.containment,b.siteCoverage))),f=l.leftovers.some(b=>b.migrationScope==="possible-subtype"),g=si("incomplete-migration",l.helperSymbol,l.helperFile,m.join("|"));Gi(a,{id:g,check:"incomplete-migration",severity:"warning",evidence:"heuristic",confidence:p,file:l.helperFile,symbol:l.helperSymbol,relatedFiles:m,message:`new helper ${l.helperShortName} (${l.helperFile}) is wired into ${l.migratedFiles.length} file(s), but ${l.leftovers.length} similar un-migrated site(s) remain: ${d}`,why:[`${l.helperShortName} is new in this diff and already referenced by ${l.migratedFiles.join(", ")}.`,`Helper shape: ${l.helperShape}; ${l.specificHelperCalleeCount}/${l.helperCalleeCount} helper callees are specific enough to score.`,`Unchanged site(s) still contain the helper's callee pattern: ${d}.`,`Migration scope hints: ${u}.`],remediation:f?`Migrate same-scope sites to ${l.helperShortName}; review possible subtype/variant sites before applying the helper.`:`Migrate the remaining sites to ${l.helperShortName}, or confirm they are intentionally different.`})}}function BA(e,t,n,i,r){let o=Xe(e).directionalCoChangePairsForFiles(t,{minTogether:n,minConfidence:0,maxFilesPerCommit:20});if(!o){r.skipped.push({check:"co-change-partner",reason:"no git history"});return}r.checksRun.push("co-change-partner");let s=new Set,a;for(let c of o){let l=t.has(c.fileA),d=t.has(c.fileB);if(l===d)continue;let u=l?c.fileA:c.fileB,m=l?c.fileB:c.fileA,p=l?c.changesA:c.changesB,f=p>0?c.together/p:0;if(f<i||Nl(m)||Nl(u)||!xh(`${e.config.projectRoot}/${m}`))continue;let g=`${u}|${m}`;if(s.has(g))continue;s.add(g);let b=si("co-change-partner",u,m,String(c.together)),x=Fl(u,m),S=Tl({fileA:u,fileB:m,together:c.together,confidence:f,commitScope:c.commitScope,recency:c.recency,subjectContext:c.subjectContext},x,(a??=_l(e))(u,m)),R=[u,m].sort().join("|");r.findings.push({id:b,check:"co-change-partner",severity:"warning",evidence:"change-graph",actionTier:"signal",groupKey:`co-change-partner:${R}`,confidence:f,file:u,relatedFiles:[m],sourceAnalyzer:"co-change",rootCauseKey:R,partnerClass:x.partnerClass,partnerClassReasons:x.reasons,commitScope:c.commitScope,recency:c.recency,focusedTogether:c.focusedTogether,broadTogether:c.broadTogether,broadCommitRatio:c.broadCommitRatio,lastTogetherAt:c.lastTogetherAt,recentTogether:c.recentTogether,subjectContext:c.subjectContext,...S?{declaredCouplingSuggestion:S}:{},message:`${u} changed, but ${m} did not \u2014 they change together ${c.together}x (${Math.round(f*100)}% of the time)`,why:[`${u} is in this diff and ${m} is not.`,`Git history shows ${c.together} co-change(s), which is ${Math.round(f*100)}% of changes to the edited side.`,`History context: ${HA(c)}.`,`Subject context: ${VA(c.subjectContext)}.`,...qA(c),`Partner class: ${x.partnerClass} (${x.reasons.join("; ")}).`],remediation:S?`Update ${m} alongside this change, declare the coupling "${S.name}", or confirm the coupling no longer holds.`:`Update ${m} alongside this change, or confirm the coupling no longer holds.`})}}function HA(e){return`${e.commitScope}/${e.recency}; ${e.focusedTogether} focused, ${e.broadTogether} broad-sweep (${Math.round(e.broadCommitRatio*100)}% broad), ${e.recentTogether} recent, last ${UA(e.lastTogetherAt)}`}function VA(e){let t=e.subjectLabels.length>0?e.subjectLabels.slice(0,5).join(", "):"none inferred",n=e.issueRefs.length>0?e.issueRefs.slice(0,5).join(", "):"none",i=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(r=>`"${r}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${i}; external issue/PR labels ${e.externalIssueLabelStatus}`}function qA(e){let t=[];return e.commitScope==="broad-sweep"&&t.push("Broad-sweep history is weaker than focused co-edits; confirm this is a real coordination contract."),e.recency==="stale"&&t.push("The pair has no co-change in the recent history window; confirm the coupling still holds."),t}function UA(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function zA(e,t,n,i,r){r.checksRun.push("doc-reference");let o=zi.referenceTargets(e,t,i);if(o.size!==0)for(let s of rh(e,o)){if(n.has(s.doc))continue;let a=s.citedClaims.length>0?s.citedClaims:zi.citationContexts(e,s.doc,s.cited),c=zi.classifyCitation(a),l=si("doc-reference",s.doc,s.cited.join("|"));Gi(r,{id:l,check:"doc-reference",severity:"warning",evidence:"change-graph",actionTier:c.actionTier,confidence:1,file:s.doc,relatedFiles:s.cited,citationKind:c.citationKind,citationKindReasons:c.reasons,citedClaims:a,message:`${s.doc} cites ${s.cited.join(", ")} as ${zi.citationKindLabel(c.citationKind)} \u2014 changed in this diff, doc untouched`,why:[`${s.cited.join(", ")} changed in this diff.`,`${s.doc} cites the changed file(s) but was not updated in the same diff.`,...c.reasons.map(d=>`Citation kind evidence: ${d}`)],remediation:zi.citationRemediation(c.citationKind,s.doc)})}}function WA(e,t,n){n.checksRun.push("unused-params");for(let i of to(e,{files:t,limit:50})){let r=si("unused-params",i.symbol,i.file,i.unusedTrailing.join("|"));Gi(n,{id:r,check:"unused-params",severity:"warning",evidence:"heuristic",confidence:.85,file:i.file,startLine:i.startLine,endLine:i.endLine,symbol:i.symbol,message:`${i.shortName} (${i.file}) has trailing unused parameter(s): ${i.unusedTrailing.join(", ")}`,why:[`${i.shortName} is in a changed file.`,`The trailing parameter(s) ${i.unusedTrailing.join(", ")} are not referenced in the function body.`],remediation:"Drop the unused trailing parameters and their call-site arguments."})}}function GA(e,t,n,i){i.checksRun.push("new-dead");let r=new A(e);for(let o of t){if(n(o)||o.fanIn>0||r.fileKind(o.file)==="test"||Oe(e,o.file)||be(e,o.symbol,o.file)||KA(o.symbol))continue;let s=si("new-dead",o.symbol,o.file);Gi(i,{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."})}}function KA(e){if(se(e)!=="type")return!1;let t=$(e);return t.startsWith("_Assert")||t.startsWith("Assert")}function JA(e,t,n,i){let r=new Map(n.renamedFiles.map(s=>[s.to,s.from])),o=i??Kr(e,t,Jr(n));return s=>{let a=r.get(s.file)??s.file,c=$(s.symbol);if(!c)return!1;let l=o(a);return l!==null&&XA(l,c)}}function XA(e,t){return new RegExp(`\\b${QA(t)}\\b`).test(e)}function QA(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function YA(e,t){if(!xh(Us(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=Zr(e);for(let i of n.newFindings){let r=Yg(i),o=si("baseline",i);Gi(t,{id:o,groupKey:`baseline:${r.sourceAnalyzer}:${r.rootCauseKey}`,check:"baseline",severity:"error",evidence:"baseline",actionTier:r.actionTier,confidence:1,file:r.file,relatedFiles:r.relatedFiles.length>0?r.relatedFiles:void 0,sourceAnalyzer:r.sourceAnalyzer,rootCauseKey:r.rootCauseKey,message:`new ${r.label} vs committed baseline: ${i}`,why:["A committed health baseline exists.","The current health result contains a finding not present in that baseline.",`Underlying analyzer: ${r.sourceAnalyzer}.`,`Inherited action tier: ${r.actionTier}.`,`Root cause key: ${r.rootCauseKey}.`,...r.why],remediation:r.remediation})}}function si(e,...t){return`SQ${kA("sha256").update([e,...t].join("\0")).digest("hex").slice(0,12).toUpperCase()}`}var ZA=.7,Ch=.62,vh=.45;function Xl(e,t={}){let{windowCommits:n=100,limit:i=30,scope:r,scanLimit:o}=t,s=Xe(e).fileAddRecords();if(!s)return{available:!1,windowCommits:n,findings:[]};if(i<=0)return{available:!0,windowCommits:n,findings:[]};let a=sM(s,n);if(a.size===0)return{available:!0,windowCommits:n,findings:[]};let l=eM(e,{limit:i,minSimilarity:t.minSimilarity,scanLimit:o,scope:r,semantic:t.semantic,focusFiles:Number.isFinite(i)?void 0:a}).map(u=>aM(u,s,n)).filter(u=>u!==null);l.sort((u,m)=>(u.kind===m.kind?0:u.kind==="echo"?-1:1)||m.similarity-u.similarity||u.echoFile.localeCompare(m.echoFile)||u.echoSymbol.localeCompare(m.echoSymbol)||u.domain.localeCompare(m.domain));let d=l.slice(0,i).map(cM);return{available:!0,windowCommits:n,findings:d,rootCauseGroups:lM(d)}}function eM(e,t){let n=dM(t.limit),i=[...tM(e,{scope:t.scope,minSimilarity:t.minSimilarity??ZA,limit:n,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles})],r=$o(e,{scope:t.scope});return r.react&&i.push(...nM(e,{scope:t.scope,minSimilarity:t.minSimilarity??Ch,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...iM(e,{scope:t.scope,minSimilarity:t.minSimilarity??vh,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),r.vue&&i.push(...rM(e,{scope:t.scope,minSimilarity:t.minSimilarity??Ch,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...oM(e,{scope:t.scope,minSimilarity:t.minSimilarity??vh,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),i}function tM(e,t){return Wn(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles}).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 nM(e,t){return Ks(e,t,{query:Gn,domain:"react-component",basis:"jsx-structure",symbolA:n=>n.componentA,symbolB:n=>n.componentB,evidenceBuckets:n=>[["component",n.sharedComponents],["tag",n.sharedNativeTags],["prop",n.sharedProps],["event",n.sharedEvents],["binding",n.sharedBindings]]})}function Ks(e,t,n){return n.query(e,t).filter(i=>i.fileA!==i.fileB).map(i=>({domain:n.domain,basis:n.basis,symbolA:n.symbolA(i),fileA:i.fileA,symbolB:n.symbolB(i),fileB:i.fileB,similarity:i.similarity,sharedEvidence:mM(...n.evidenceBuckets(i)),sharedCallees:[]}))}function iM(e,t){return Ks(e,t,{query:Kn,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,evidenceBuckets:n=>[["hook",n.sharedHooks],["react-hook",n.sharedReactHooks],["effect",n.sharedEffects],["state",n.sharedState],["request",n.sharedRequests],["handler",n.sharedHandlers],["action",n.sharedHandlerVerbs]]})}function rM(e,t){return Ks(e,t,{query:Jn,domain:"vue-component",basis:"vue-template",symbolA:n=>Gs(n.fileA),symbolB:n=>Gs(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function oM(e,t){return Ks(e,t,{query:Xn,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>Gs(n.fileA),symbolB:n=>Gs(n.fileB),evidenceBuckets:n=>[["composable",n.sharedComposables],["store",n.sharedStores],["reactivity",n.sharedReactivity],["lifecycle",n.sharedLifecycle],["request",n.sharedRequests],["function",n.sharedFunctions],["action",n.sharedFunctionVerbs],["binding",n.sharedBindings],["template-event",n.sharedTemplateEvents]]})}function sM(e,t){let n=new Set;for(let[i,r]of e)r.commitsAgo<=t&&n.add(i);return n}function aM(e,t,n){let i=t.get(e.fileA)?.commitsAgo??null,r=t.get(e.fileB)?.commitsAgo??null,o=i!==null&&i<=n,s=r!==null&&r<=n;if(!o&&!s)return null;if(o&&s){let a=(i??0)<=(r??0);return{kind:"twin",domain:e.domain,basis:e.basis,echoSymbol:a?e.symbolA:e.symbolB,echoFile:a?e.fileA:e.fileB,echoAgeCommits:(a?i:r)??0,establishedSymbol:a?e.symbolB:e.symbolA,establishedFile:a?e.fileB:e.fileA,establishedAgeCommits:a?r:i,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}return{kind:"echo",domain:e.domain,basis:e.basis,echoSymbol:o?e.symbolA:e.symbolB,echoFile:o?e.fileA:e.fileB,echoAgeCommits:(o?i:r)??0,establishedSymbol:o?e.symbolB:e.symbolA,establishedFile:o?e.fileB:e.fileA,establishedAgeCommits:o?r:i,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}function cM(e){let t=Rh(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function Rh(e){if(e.kind==="echo")return["echo",e.domain,e.basis,e.establishedSymbol].join(":");let t=e.sharedEvidence.slice().sort().join("|"),n=[e.echoSymbol,e.establishedSymbol].sort().join("|");return["twin",e.domain,e.basis,t||n].join(":")}function lM(e){let t=new Map;for(let[n,i]of e.entries()){let r=i.rootCauseKey??Rh(i),o=i.groupKey??`recent-duplicate:${r}`,s=t.get(o);s||(s={groupKey:o,rootCauseKey:r,kind:i.kind,domain:i.domain,basis:i.basis,count:0,maxSimilarity:i.similarity,findingIndexes:[],echoFiles:new Set,establishedFile:i.kind==="echo"?i.establishedFile:void 0,establishedSymbol:i.kind==="echo"?i.establishedSymbol:void 0,relatedFiles:new Set,sharedEvidence:new Set,recommendation:uM(i)},t.set(o,s)),s.count+=1,s.maxSimilarity=Math.max(s.maxSimilarity,i.similarity),s.findingIndexes.push(n),s.echoFiles.add(i.echoFile),s.relatedFiles.add(i.echoFile),s.relatedFiles.add(i.establishedFile);for(let a of i.sharedEvidence)s.sharedEvidence.add(a)}return[...t.values()].map(n=>({...n,echoFiles:[...n.echoFiles].sort(),relatedFiles:[...n.relatedFiles].sort(),sharedEvidence:[...n.sharedEvidence].sort().slice(0,16)})).sort((n,i)=>i.count-n.count||i.maxSimilarity-n.maxSimilarity||n.groupKey.localeCompare(i.groupKey))}function uM(e){return e.kind==="echo"?"Review the established side once, then migrate or delete every echo in this group.":"Pick one owner for the new twins and consolidate the group before the copies diverge."}function dM(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function mM(...e){let t=[],n=new Set;for(let[i,r]of e)for(let o of r){let s=`${i}:${o}`;n.has(s)||(n.add(s),t.push(s))}return t}function Gs(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var pM=ie("suppression-inventory",{clearGroups:["whole-project"]});function Js(e){return pM.get(e,()=>fM(e))}function fM(e){let t={dead:0,stale:0,wrapper:0,passthrough:0,drift:0,extract:0,similar:0,uncategorized:0},n=new Map,i=0;for(let r of et(e)){let o=M(e,r);if(!(!o||!o.includes("scip-query")))for(let s of o.split(/\r?\n/)){let a=mr(s);if(a===null)continue;i+=1,n.set(r,(n.get(r)??0)+1);let c=gM(a);t[c]+=1}}return{total:i,byCategory:t,byFile:n}}function gM(e){if(!e)return"uncategorized";let t=e.toLowerCase();return t==="dead-code"?"dead":t}import{readFileSync as hM}from"fs";import{join as yM}from"path";function io(e,t,n={}){let i=q(e,t);if(!i)return null;let r=new A(e),o=vM(SM(e,i.relativePath,i.startLine,i.endLine),bM(e,i.relativePath)),s=i.endLine-i.startLine+1,c=r.calleeMap([i],{additive:!0,semantic:n.semantic}).get(i.symbolId)??[],l=new Set(c.map(d=>d.symbol));return{symbol:i.symbol,shortName:v(i.symbol),relativePath:i.relativePath,startLine:i.startLine,endLine:i.endLine,loc:s,branches:o,cyclomaticEstimate:o+1,calleeCount:l.size,fanIn:xM(e,i.symbolId),fanOut:CM(c,i.relativePath)}}function bM(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function SM(e,t,n,i){try{return hM(yM(e.config.projectRoot,t),"utf-8").split(`
648
+ `).slice(n,i+1).join(`
649
+ `)}catch{return""}}function xM(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
628
650
  FROM mentions m
629
651
  JOIN chunks c ON m.chunk_id = c.id
630
- WHERE m.symbol_id = ? AND m.role != 1`,t)?.c??0}function H_(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function V_(e,t){let n=Sn(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 Fi(e,t,n={}){let r=B(e,t);if(!r)return null;let i=[{file:r.relativePath,line:r.startLine}],o=Yt(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}=q_(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 q_(e,t,n,r){let i=Lr(He(e,t,{limit:30,semantic:r.semantic}).map(a=>({symbol:a.symbol,file:a.file}))),o=Lr(Qe(e,t,{limit:30,semantic:r.semantic})),s=o.length>0?o:Lr(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{producers:i,consumers:s}}function Tr(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,o=B(e,t);return o?r==="backward"?U_(e,o,i,{semantic:n.semantic!==!1}):W_(e,o,{semantic:n.semantic!==!1}):null}function U_(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=He(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:b(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let m=mr(e,d.symbol);m&&!e.isIgnored(m.relativePath)&&c.push(m)}}s=c}return{symbol:t.symbol,shortName:b(t.symbol),direction:"backward",connectedSymbols:i}}function W_(e,t,n){let r=new Set,i=[],o=new F(e);for(let s of Yt(e,t,{semantic:n.semantic})){if(i.length>=30)break;let a=s.enclosingSymbol??Ge(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=mr(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 tl(e,t,n={}){let r=n.impactDepth??3,i=n.sliceDepth??3,o=n.semantic,s=!z_(t),a=s?di(e,t,{semantic:o}):{definitions:[],referencedBy:[]},c=s?yi(e,t,{semantic:o}):null,l=s?_i(e,t,{semantic:o}):null,u=s?Fi(e,t,{semantic:o}):null,d=s?Tr(e,t,{direction:"backward",maxDepth:i,semantic:o}):null,m=s?Tr(e,t,{direction:"forward",maxDepth:i,semantic:o}):null,p=s?Ri(e,t,{maxDepth:r,scope:n.scope}):[],g=ki(e,t,{semantic:o}),y=mi(e,t),h=pi(e,t),x=fi(e,t),v=gi(e,t),R={symbol:a.definitions.length>0||a.referencedBy.length>0||c!==null||l!==null||u!==null||d!==null||m!==null||p.length>0,file:g!==null||y.length>0||h.length>0,module:x.files.length>0||x.symbols.length>0||v.length>0},L=[];!R.symbol&&!R.file&&!R.module&&L.push("No symbol, file, or module matched target.");let S=g?.file??a.definitions[0]?.relativePath??null;return{target:t,matched:R,history:G_(e,S),trace:a,callGraph:c,complexity:l,dataflow:u,backwardSlice:d,forwardSlice:m,affected:p,changeSurface:g,deps:y,rdeps:h,system:x,surface:v,warnings:L}}function G_(e,t){let n={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return n;let r=ns(e);if(!r)return n;let i=Fn(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,subjectContext:o.subjectContext})),suppressionsInFile:Cs(e).byFile.get(t)??0}}function z_(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}function Ai(e,t){let{scope:n,minLoc:r=10,limit:i=30,scanLimit:o}=t??{},s=new F(e);return Ze({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:r,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)=>J_(a,c,r),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:i})}function J_(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=new Set,a=new Set;for(let u of o){let d=`${u.symbol}|${u.file}`;s.add(d),u.file!==e.relativePath&&a.add(d)}let c=a.size,l=s.size;return{symbol:e.symbol,shortName:b(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:r,fanIn:i,fanOut:c,calleeCount:l,score:Math.round(r/50*(i/5)*Math.max(c/5,1)*100)/100}}function Ft(e){return e.scoreCount??e.count}function jf(e){let t=Y_(e),{breakdown:n,pressure:r}=Z_(e),i=Of(n,"risk"),o=Of(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:Ft(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:Ft(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:Ft(e.wrappers),passthroughs:e.passthroughs.count,staleTypes:e.stale.count,driftedFiles:e.drift.count,complexityHotspotCount:e.complexity.extremeCount,hiddenCouplingPairs:e.gitEvidence?.hiddenCoupling.pairCount??null,hiddenCouplingScoreCount:e.gitEvidence?.hiddenCoupling.scoreCount??null},axes:K_(e),validation:Q_(e),suppressions:e.suppressions,actions:t,pressure:r,topComplexity:e.complexity.top,warnings:e.warnings.length>0?e.warnings:void 0}}function K_(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:X_(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 X_(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:St(n.score*Math.log2(1+r))}}).sort((n,r)=>r.weighted-n.weighted):null}function Q_(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?St(i/r.size):0,c=s>0?St(o/s):0,l={};for(let[u,d]of Object.entries(n)){let m=new Set(d);if(m.size===0)continue;let p=0;for(let y of m)p+=t[y]?.fixChanges??0;let g=St(p/m.size);l[u]={flaggedFiles:m.size,fixDensity:g,lift:c>0?St(g/c):null}}return{flaggedFiles:r.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:r.size>0&&c>0?St(a/c):null,byCategory:l}}function St(e){return Math.round(e*100)/100}function Bf(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function vs(e,t="existing shared infrastructure discount"){let n=Ft(e);return Math.abs(n-e.count)<.01?"":` (${Bf(n)} score-weighted after ${t})`}function $i(e,t){let n=Ft(e),r=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?r:`${r} (${Bf(n)} score-weighted)`}function Y_(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${vs(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${vs(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 review same-file or feature-local extraction seams`,effort:"medium",impact:"medium",count:e.extractCount,locRecoverable:0}),e.wrappers.count>0&&t.push({category:"Wrapper functions",evidence:"heuristic",description:`${e.wrappers.count} single-consumer symbols${vs(e.wrappers,"boundary-evidence discount")} \u2014 inline direct wrappers or review boundary signals`,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 remove unused abstractions; review single-consumer ownership before moving or inlining`,effort:"low",impact:"medium",count:e.stale.count,locRecoverable:e.stale.loc})}if(e.drift.count>0){let i=[];e.drift.unusedImports>0&&i.push(`${e.drift.unusedImports} unused imports`),e.drift.layerViolations>0&&i.push(`${e.drift.layerViolations} layer violations`),t.push({category:"Structural drift",evidence:"heuristic",description:`${i.join(", ")} \u2014 remove direct drift; review signal drift against layer ownership`,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`+vs({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:e.gitEvidence.hiddenCoupling.scoreCount},"broad/stale-history discount")+(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 Mf={"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 Of(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 Z_(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),r=[],i=[],o=(S,C,P)=>{C>0&&r.push({axis:S,points:C,detail:P,kind:Mf[S]??"hygiene"})},s=(S,C,P,D,z,De,Ue)=>{let Me=Math.max(D,1);if(P<=Me)return;let Ot=P/Me,jt=Math.min(z,Math.ceil(Math.log2(Ot)*De));if(jt<=0)return;let Bb=Mf[S]??"hygiene";i.push({axis:S,category:C,kind:Bb,count:P,threshold:St(Me),ratio:St(Ot),extraPenalty:jt}),o(S,jt,`${P} ${Ue} exceed pressure threshold ${St(Me)} (${St(Ot)}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=Ft(e.reactHookCandidates),m=d/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(m)),$i(e.reactHookCandidates,"duplicated React behavior pair(s)"));let p=e.reactLargeComponentPressure.count/t*1e3;o("react-large-component-pressure",Math.min(5,Math.round(p/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 y=Ft(e.vueComposableCandidates),h=y/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(h)),$i(e.vueComposableCandidates,"duplicated Vue behavior pair(s)"));let x=e.vueLargeViewPressure.count/t*1e3;o("vue-large-view-pressure",Math.min(5,Math.round(x/2)),`${e.vueLargeViewPressure.count} large Vue view pressure file(s)`);let v=Ft(e.wrappers);o("wrappers",Math.min(3,v),$i(e.wrappers,"wrapper candidate(s)"));let R=Ft(e.passthroughs);o("passthroughs",Math.min(3,R),$i(e.passthroughs,"passthrough candidate(s)")),o("stale-abstractions",Math.min(8,e.stale.unused),`${e.stale.unused} unused stale abstraction(s); ${e.stale.singleUse} single-consumer signal(s)`);let L=e.drift.direct/t;if(o("drift",Math.min(5,Math.round(L*50)),`${e.drift.direct} direct drift finding(s); ${e.drift.signal} signal drift finding(s)`),o("complexity",Math.min(5,e.complexity.extremeCount*2),`${e.complexity.extremeCount} extreme complexity hotspot(s)`),e.gitEvidence){let S=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(S/10)),$i({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:S},"co-changing pair(s) without a structural link"))}if(s("cycles-pressure","Circular dependencies",e.realCycleCount,3,10,3,"cycle(s)"),s("complexity-pressure","Extreme complexity",e.complexity.extremeCount,3,5,2,"extreme complexity hotspot(s)"),e.gitEvidence){let S=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",S,50,10,4,"score-weighted co-changing pair(s)")}return s("similar-pressure","Similar functions",e.similarCount,Math.max(50,n*.01),8,4,"similar function pair(s)"),s("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",y,Math.max(10,t*.01),8,4,"duplicated Vue behavior pair(s)"),s("vue-large-view-pressure-pressure","Large Vue views",e.vueLargeViewPressure.count,Math.max(10,t*.01),4,2,"large Vue view pressure file(s)"),s("extract-pressure","Extraction candidates",e.extractCount,Math.max(50,n*.01),4,2,"extraction candidate(s)"),s("wrappers-pressure","Wrapper functions",v,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",R,50,4,2,"passthrough candidate(s)"),s("stale-abstractions-pressure","Single-consumer stale abstraction signals",e.stale.singleUse,Math.max(50,n*.02),4,2,"single-consumer stale abstraction signal(s)"),s("drift-pressure","Structural drift signals",e.drift.signal,Math.max(10,t*.1),4,2,"signal drift finding(s)"),{breakdown:r,pressure:i}}import{getHeapStatistics as e0}from"v8";var t0=64*1024*1024;function nl(){let e=globalThis.gc;if(!e)return;let t=e0();t.heap_size_limit-t.used_heap_size<t0||e()}var n0=50,r0=75e3,i0=5e3,Hf=2500,Vf=50,o0=10,_r=["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"],s0={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:l0(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:u0(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:d0(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:m0(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:f0(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:g0(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:h0(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:y0(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:b0(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:S0(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:p0(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:x0(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:C0(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:v0(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:w0(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:L0(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:R0(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:k0(e,n)})};function Mi(e,t,n={}){return rl(e,[t],n)[0]}function rl(e,t,n={}){return a0(e,n.full!==!1,(r,i)=>{let o={...i,releaseCachesBetweenPhases:!1};return t.map(s=>s0[s](e,n.scope,o,r))})}function a0(e,t,n){let r=Oe(e),i=I0(r,t);try{return n(r,i)}finally{Ja(e,{semanticProvider:!0}),nl()}}function il(e){return jf(c0(e))}function c0(e){let t=ve(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,dead:ve(e,"dead").dead,isolated:ve(e,"isolated").isolated,realCycleCount:ve(e,"cycles").realCycleCount,similarCount:ve(e,"similar").similarCount,reactComponentDuplicates:ve(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:ve(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:ve(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:ve(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:ve(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:ve(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:ve(e,"extract-candidates").extractCount,wrappers:ve(e,"wrapper-candidates").wrappers,passthroughs:ve(e,"passthrough-candidates").passthroughs,stale:ve(e,"stale-abstractions").stale,drift:ve(e,"drift").drift,complexity:ve(e,"complexity-hotspots").complexity,gitEvidence:qf(e,"git-evidence")?.gitEvidence??null,suppressions:qf(e,"suppressions")?.suppressions??null}}function qf(e,t){return e.find(n=>n.phase===t)}function ve(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function l0(e,t,n){return fe(e,n,"dead",()=>{let r=Et(e,{scope:t,...pe.dead,scanLimit:n.candidateScanLimit});return Rs(N0(e,r.symbols))})}function u0(e,t,n){return fe(e,n,"isolated",()=>{let r=In(e,{scope:t,...pe.isolated,scanLimit:n.candidateScanLimit});return Rs(E0(e,r))})}function d0(e,t,n){return fe(e,n,"cycles",()=>Ln(e,{scope:t}).filter(i=>i.kind==="real").length)}function m0(e,t,n){return fe(e,n,"similar",()=>Tt(e,{scope:t,...pe.similar,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}).length)}function p0(e,t,n){return fe(e,n,"extract-candidates",()=>Tn(e,{scope:t,...pe.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}).length)}function f0(e,t,n){return fe(e,n,"react-component-duplicates",()=>{let r=Dn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return ol(r)})}function g0(e,t,n){return fe(e,n,"react-hook-candidates",()=>{let r=Pn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Gf(r,_0)})}function h0(e,t,n){return fe(e,n,"react-large-component-pressure",()=>{let r=Ci(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return T0(r)})}function y0(e,t,n){return fe(e,n,"vue-component-duplicates",()=>{let r=Nn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return ol(r)})}function b0(e,t,n){return fe(e,n,"vue-composable-candidates",()=>{let r=En(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Gf(r,F0)})}function S0(e,t,n){return fe(e,n,"vue-large-view-pressure",()=>{let r=vi(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Rs(r)})}function x0(e,t,n){return fe(e,n,"wrapper-candidates",()=>{let r=Bn(e,{scope:t,...pe.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Wf(r,A0)})}function C0(e,t,n){return fe(e,n,"passthrough-candidates",()=>{let r=On(e,{scope:t,...pe.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Wf(r,$0)})}function v0(e,t,n){return fe(e,n,"stale-abstractions",()=>{let r=jn(e,{scope:t,...pe.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 R0(e,t){return fe(e,t,"git-evidence",()=>{let n=ns(e);if(!n)return null;let r=Fn(e,void 0,{limit:t.candidateResultLimit}),i={};for(let[o,s]of n)i[o]={changes:s.changes,fixChanges:s.fixChanges};return{amplification:Jp(e),hiddenCoupling:{pairCount:r.findings.length,scoreCount:sl(r.findings.reduce((o,s)=>o+Uf(s),0)),top:r.findings.slice(0,5).map(o=>({fileA:o.fileA,fileB:o.fileB,together:o.together,confidence:o.confidence,focusedTogether:o.focusedTogether,broadTogether:o.broadTogether,broadCommitRatio:o.broadCommitRatio,lastTogetherAt:o.lastTogetherAt,recentTogether:o.recentTogether,commitScope:o.commitScope,recency:o.recency,scoreWeight:Uf(o),subjectContext:o.subjectContext}))},fileStats:i}})}function k0(e,t){return fe(e,t,"suppressions",()=>{let n=Cs(e);return{total:n.total,byCategory:{...n.byCategory}}})}function w0(e,t,n){return fe(e,n,"drift",()=>{let r=Mn(e,{scope:t,...pe.drift,includePatternDeviations:!1}),i=r.results.filter(a=>a.kind!=="pattern-deviation"),o=i.filter(a=>a.actionTier==="direct").length,s=i.length-o;return{count:i.length,unusedImports:r.unusedImports,layerViolations:r.layerViolations,direct:o,signal:s}})}function L0(e,t,n){return fe(e,n,"complexity-hotspots",()=>{let r=Ai(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>n0).length}})}function I0(e,t){let n=e.symbols>=r0||e.documents>=i0,r=t?Number.POSITIVE_INFINITY:Vf,i=t?Number.POSITIVE_INFINITY:o0;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 mode is enabled."]:[]}:{candidateScanLimit:Hf,candidateResultLimit:r,complexityResultLimit:i,releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${Hf} symbols and reported their top ${Vf} findings. Enable full mode for unbounded candidate counts.`]}}function D0(e,t){t.releaseCachesBetweenPhases&&(Ja(e),nl())}function fe(e,t,n,r){P0(n);try{return r()}finally{D0(e,t)}}function P0(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function N0(e,t){return t.filter(n=>!Te(e,n.relativePath)&&!le(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function E0(e,t){return t.filter(n=>!Te(e,n.relativePath)&&!le(e,n.symbol,n.relativePath))}function Rs(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 Wf(e,t){return{...Rs(e),scoreCount:sl(e.reduce((r,i)=>r+t(i),0))}}function T0(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 ol(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 Gf(e,t){return{...ol(e),scoreCount:sl(e.reduce((r,i)=>r+t(i),0))}}function _0(e){let t=e.sharedHooks.length>0,n=zf({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:Jf(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function F0(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=zf({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:Jf(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function zf(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!Xf.has(Kf(t))).length+Math.min(e.functions.length,3)}function Jf(e,t,n){let r=[...e,...t,...n].map(Kf);return r.length>0&&r.every(i=>Xf.has(i))}function Kf(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function A0(e){return e.actionTier==="signal"?.25:1}function $0(e){return e.actionTier==="signal"?.25:1}function Uf(e){return e.commitScope==="broad-sweep"?e.recency==="recent"?.25:0:e.commitScope==="mixed"?e.recency==="recent"?.5:.25:e.recency==="recent"?1:.5}function sl(e){return Math.round(e*100)/100}var Xf=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 al(e,t,n,r={}){let i=B(e,t),o=B(e,n);if(!i||!o)return null;let s=new Set(He(e,i,{semantic:r.semantic}).map(h=>h.symbol)),a=new Set(He(e,o,{semantic:r.semantic}).map(h=>h.symbol)),c=[];for(let h of s)a.has(h)&&c.push(h);let l=[];for(let h of s)a.has(h)||l.push(h);let u=[];for(let h of a)s.has(h)||u.push(h);let d=new Set([...s,...a]),m=d.size>0?c.length/d.size:0,p;d.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 g=i.endLine-i.startLine+1,y=o.endLine-o.startLine+1;return{symbolA:{symbol:i.symbol,shortName:b(i.symbol),file:i.relativePath,loc:g},symbolB:{symbol:o.symbol,shortName:b(o.symbol),file:o.relativePath,loc:y},similarity:m,sharedCallees:c.map(b),uniqueToA:l.map(b),uniqueToB:u.map(b),consolidationStrategy:p}}import{readFileSync as Qf}from"fs";import{extname as M0,join as Yf}from"path";function cl(e,t,n={}){let{context:r=0}=n,i=O0(t);if(i)return B0(e,i.filePath,i.startLine,i.endLine,r);let o=B(e,t);return o?j0(e,o,r):null}function O0(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 j0(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=Yf(e.config.projectRoot,t.relativePath),o;try{o=Qf(i,"utf-8")}catch{return null}let s=o.split(`
652
+ WHERE m.symbol_id = ? AND m.role != 1`,t)?.c??0}function CM(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function vM(e,t){let n=Tn(e),i=0,r=[/\bif\b/g,/\belse\s+if\b/g,/\belse\b/g,/\bfor\b/g,/\bwhile\b/g,/\bswitch\b/g,/\bcase\b/g,/\bcatch\b/g,/\?\s*[^?]/g,/&&/g,/\|\|/g];for(let o of r){let s=n.match(o);s&&(i+=s.length)}if(t==="python"){let o=[/\belif\b/g,/\bexcept\b/g,/\bfinally\b/g];for(let s of o){let a=n.match(s);a&&(i+=a.length)}}else if(t==="rust"){let o=[/\bmatch\b/g,/=>/g,/\bloop\b/g];for(let s of o){let a=n.match(s);a&&(i+=a.length)}}else if(t==="ruby"){let o=[/\belsif\b/g,/\bunless\b/g,/\brescue\b/g,/\bwhen\b/g];for(let s of o){let a=n.match(s);a&&(i+=a.length)}}else if(t==="go"){let o=[/\bselect\b/g,/\bdefer\b/g];for(let s of o){let a=n.match(s);a&&(i+=a.length)}}return i}function ro(e,t,n={}){let i=q(e,t);if(!i)return null;let r=[{file:i.relativePath,line:i.startLine}],o=yn(e,i,{semantic:n.semantic}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?v(c.enclosingSymbol):"(top-level)"})),{producers:s,consumers:a}=RM(e,i,o,{semantic:n.semantic!==!1});return{symbol:i.symbol,shortName:v(i.symbol),relativePath:i.relativePath,definitionSites:r.filter(c=>!e.isIgnored(c.file)),usageSites:o,producers:s.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:v(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)":v(c.symbol),file:c.file}))}}function RM(e,t,n,i){let r=Oi(Je(e,t,{limit:30,semantic:i.semantic}).map(a=>({symbol:a.symbol,file:a.file}))),o=Oi(at(e,t,{limit:30,semantic:i.semantic})),s=o.length>0?o:Oi(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{producers:r,consumers:s}}function Ki(e,t,n={}){let{direction:i="backward",maxDepth:r=3}=n,o=q(e,t);return o?i==="backward"?kM(e,o,r,{semantic:n.semantic!==!1}):wM(e,o,{semantic:n.semantic!==!1}):null}function kM(e,t,n,i){let r=[],o=new Set([t.symbol]),s=[t];for(let a=1;a<=n&&s.length!==0;a++){let c=[];for(let l of s){let d=Je(e,l,{semantic:i.semantic});for(let u of d){if(o.has(u.symbol))continue;o.add(u.symbol),r.push({symbol:u.symbol,shortName:v(u.symbol),file:u.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let m=Ni(e,u.symbol);m&&!e.isIgnored(m.relativePath)&&c.push(m)}}s=c}return{symbol:t.symbol,shortName:v(t.symbol),direction:"backward",connectedSymbols:r}}function wM(e,t,n){let i=new Set,r=[],o=new A(e);for(let s of yn(e,t,{semantic:n.semantic})){if(r.length>=30)break;let a=s.enclosingSymbol??ot(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=Ni(e,a);!c||e.isIgnored(c.relativePath)||i.has(c.symbol)||(i.add(c.symbol),r.push({symbol:c.symbol,shortName:v(c.symbol),file:c.relativePath,relationship:`references target at ${s.file}:${s.line+1}`}))}return r.sort((s,a)=>s.file.localeCompare(a.file)),{symbol:t.symbol,shortName:v(t.symbol),direction:"forward",connectedSymbols:r}}function Ql(e,t,n={}){let i=n.impactDepth??3,r=n.sliceDepth??3,o=n.semantic,s=!IM(t),a=s?Tr(e,t,{semantic:o}):{definitions:[],referencedBy:[]},c=s?Br(e,t,{semantic:o}):null,l=s?io(e,t,{semantic:o}):null,d=s?ro(e,t,{semantic:o}):null,u=s?Ki(e,t,{direction:"backward",maxDepth:r,semantic:o}):null,m=s?Ki(e,t,{direction:"forward",maxDepth:r,semantic:o}):null,p=s?zr(e,t,{maxDepth:i,scope:n.scope}):[],f=Wr(e,t,{semantic:o}),g=_r(e,t),b=Ar(e,t),x=Mr(e,t),S=$r(e,t),R={symbol:a.definitions.length>0||a.referencedBy.length>0||c!==null||l!==null||d!==null||u!==null||m!==null||p.length>0,file:f!==null||g.length>0||b.length>0,module:x.files.length>0||x.symbols.length>0||S.length>0},C=[];!R.symbol&&!R.file&&!R.module&&C.push("No symbol, file, or module matched target.");let y=f?.file??a.definitions[0]?.relativePath??null;return{target:t,matched:R,history:PM(e,y),trace:a,callGraph:c,complexity:l,dataflow:d,backwardSlice:u,forwardSlice:m,affected:p,changeSurface:f,deps:g,rdeps:b,system:x,surface:S,warnings:C}}function PM(e,t){let n={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return n;let i=Xe(e).fileChurn();if(!i)return n;let r=Zn(e,t,{limit:5});return{available:!0,file:t,churn:i.get(t)??{changes:0,fixChanges:0,lastChangedAt:0},coChangePartners:r.findings.map(o=>({file:o.fileA===t?o.fileB:o.fileA,together:o.together,confidence:o.confidence,subjectContext:o.subjectContext})),suppressionsInFile:Js(e).byFile.get(t)??0}}function IM(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}function oo(e,t){let{scope:n,minLoc:i=10,limit:r=30,scanLimit:o}=t??{},s=new A(e);return lt({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:i,requireFunctionLikeSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,profile:{name:"complexity-hotspots"},prepare:a=>{let c=DM(e,a);return{callerMap:s.crossFileCallerMap(a,{semantic:t?.semantic!==!1}),calleeMap:s.calleeMap(a,{semantic:t?.semantic!==!1}),languageByFile:c,clojureCallableIds:EM(e,a,c)}},evaluate:(a,c)=>LM(a,c,i),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:r})}function LM(e,t,n){if(t.languageByFile.get(e.relativePath)==="clojure"&&!t.clojureCallableIds.has(e.symbolId))return null;let i=e.endLine-e.startLine+1;if(i<n)return null;let r=t.callerMap.get(e.symbolId)?.size??0,o=t.calleeMap.get(e.symbolId)??[],s=new Set,a=new Set;for(let d of o){let u=`${d.symbol}|${d.file}`;s.add(u),d.file!==e.relativePath&&a.add(u)}let c=a.size,l=s.size;return{symbol:e.symbol,shortName:v(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:i,fanIn:r,fanOut:c,calleeCount:l,score:Math.round(i/50*(r/5)*Math.max(c/5,1)*100)/100}}function DM(e,t){let n=[...new Set(t.map(o=>o.relativePath))];if(n.length===0)return new Map;let i=n.map(()=>"?").join(", "),r=e.all(`SELECT relative_path, language
653
+ FROM documents
654
+ WHERE relative_path IN (${i})`,...n);return new Map(r.map(o=>[o.relative_path,o.language?.toLowerCase()??null]))}function EM(e,t,n){let i=new Set,r=new Map;for(let o of t){if(n.get(o.relativePath)!=="clojure")continue;let s=r.get(o.relativePath);s||(s=new Set((X(e,o.relativePath)?.callables??[]).map(a=>`${a.name}:${a.startLine}`)),r.set(o.relativePath,s)),s.has(`${o.leaf}:${o.startLine}`)&&i.add(o.symbolId)}return i}function en(e){return e.scoreCount??e.count}function Ph(e){let t=_M(e),{breakdown:n,pressure:i}=AM(e),r=wh(n,"risk"),o=wh(n,"hygiene");return{score:Math.min(r,o),riskScore:r,hygieneScore:o,scoreBreakdown:n,overview:{documents:e.statsResult.documents,symbols:e.statsResult.symbols,indexSizeBytes:e.statsResult.indexSizeBytes},findings:{deadSymbols:e.dead.count,deadLoc:e.dead.loc,isolatedSymbols:e.isolated.count,isolatedLoc:e.isolated.loc,cycles:e.realCycleCount,similarPairs:e.similarCount,reactComponentDuplicatePairs:e.reactComponentDuplicates.count,reactHookCandidatePairs:e.reactHookCandidates.count,reactHookCandidateScoreCount:en(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:en(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:en(e.wrappers),passthroughs:e.passthroughs.count,staleTypes:e.stale.count,driftedFiles:e.drift.count,complexityHotspotCount:e.complexity.extremeCount,hiddenCouplingPairs:e.gitEvidence?.hiddenCoupling.pairCount??null,hiddenCouplingScoreCount:e.gitEvidence?.hiddenCoupling.scoreCount??null},axes:NM(e),validation:TM(e),suppressions:e.suppressions,actions:t,pressure:i,topComplexity:e.complexity.top,warnings:e.warnings.length>0?e.warnings:void 0}}function NM(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:FM(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 FM(e){let t=e.gitEvidence?.fileStats;return t?e.complexity.top.map(n=>{let i=n.file?t[n.file]?.changes??0:0;return{...n,changes:i,weighted:_t(n.score*Math.log2(1+i))}}).sort((n,i)=>i.weighted-n.weighted):null}function TM(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??[]},i=new Set(Object.values(n).flat()),r=0,o=0,s=0;for(let[d,u]of Object.entries(t))i.has(d)?r+=u.fixChanges:(o+=u.fixChanges,s+=1);let a=i.size>0?_t(r/i.size):0,c=s>0?_t(o/s):0,l={};for(let[d,u]of Object.entries(n)){let m=new Set(u);if(m.size===0)continue;let p=0;for(let g of m)p+=t[g]?.fixChanges??0;let f=_t(p/m.size);l[d]={flaggedFiles:m.size,fixDensity:f,lift:c>0?_t(f/c):null}}return{flaggedFiles:i.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:i.size>0&&c>0?_t(a/c):null,byCategory:l}}function _t(e){return Math.round(e*100)/100}function Ih(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function Xs(e,t="existing shared infrastructure discount"){let n=en(e);return Math.abs(n-e.count)<.01?"":` (${Ih(n)} score-weighted after ${t})`}function so(e,t){let n=en(e),i=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?i:`${i} (${Ih(n)} score-weighted)`}function _M(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${Xs(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${Xs(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 review same-file or feature-local extraction seams`,effort:"medium",impact:"medium",count:e.extractCount,locRecoverable:0}),e.wrappers.count>0&&t.push({category:"Wrapper functions",evidence:"heuristic",description:`${e.wrappers.count} single-consumer symbols${Xs(e.wrappers,"boundary-evidence discount")} \u2014 inline direct wrappers or review boundary signals`,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 r=[];e.stale.unused>0&&r.push(`${e.stale.unused} unused`),e.stale.singleUse>0&&r.push(`${e.stale.singleUse} single-consumer (not in types file)`),t.push({category:"Stale abstractions",evidence:"heuristic",description:`${r.join(", ")} \u2014 remove unused abstractions; review single-consumer ownership before moving or inlining`,effort:"low",impact:"medium",count:e.stale.count,locRecoverable:e.stale.loc})}if(e.drift.count>0){let r=[];e.drift.unusedImports>0&&r.push(`${e.drift.unusedImports} unused imports`),e.drift.layerViolations>0&&r.push(`${e.drift.layerViolations} layer violations`),t.push({category:"Structural drift",evidence:"heuristic",description:`${r.join(", ")} \u2014 remove direct drift; review signal drift against layer ownership`,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 r=e.gitEvidence.hiddenCoupling.top[0];t.push({category:"Hidden coupling",evidence:"change-graph",description:`${e.gitEvidence.hiddenCoupling.pairCount} file pair(s) co-change without a structural link`+Xs({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:e.gitEvidence.hiddenCoupling.scoreCount},"broad/stale-history discount")+(r?` (e.g. ${r.fileA} \u2194 ${r.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},i={low:3,medium:2,high:1};return t.sort((r,o)=>{let s=n[r.impact]*i[r.effort];return n[o.impact]*i[o.effort]-s}),t}var kh={"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 wh(e,t){let n=e.filter(i=>i.kind===t).reduce((i,r)=>i+r.points,0);return Math.max(0,Math.min(100,100-n))}function AM(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),i=[],r=[],o=(y,w,L)=>{w>0&&i.push({axis:y,points:w,detail:L,kind:kh[y]??"hygiene"})},s=(y,w,L,k,T,U,Y)=>{let ee=Math.max(k,1);if(L<=ee)return;let we=L/ee,te=Math.min(T,Math.ceil(Math.log2(we)*U));if(te<=0)return;let rn=kh[y]??"hygiene";r.push({axis:y,category:w,kind:rn,count:L,threshold:_t(ee),ratio:_t(we),extraPenalty:te}),o(y,te,`${L} ${Y} exceed pressure threshold ${_t(ee)} (${_t(we)}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 d=e.reactComponentDuplicates.count/t*1e3;o("react-component-duplicates",Math.min(10,Math.round(d)),`${e.reactComponentDuplicates.count} duplicated React component pair(s)`);let u=en(e.reactHookCandidates),m=u/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(m)),so(e.reactHookCandidates,"duplicated React behavior pair(s)"));let p=e.reactLargeComponentPressure.count/t*1e3;o("react-large-component-pressure",Math.min(5,Math.round(p/2)),`${e.reactLargeComponentPressure.count} large React component pressure file(s)`);let f=e.vueComponentDuplicates.count/t*1e3;o("vue-component-duplicates",Math.min(10,Math.round(f)),`${e.vueComponentDuplicates.count} duplicated Vue component pair(s)`);let g=en(e.vueComposableCandidates),b=g/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(b)),so(e.vueComposableCandidates,"duplicated Vue behavior pair(s)"));let x=e.vueLargeViewPressure.count/t*1e3;o("vue-large-view-pressure",Math.min(5,Math.round(x/2)),`${e.vueLargeViewPressure.count} large Vue view pressure file(s)`);let S=en(e.wrappers);o("wrappers",Math.min(3,S),so(e.wrappers,"wrapper candidate(s)"));let R=en(e.passthroughs);o("passthroughs",Math.min(3,R),so(e.passthroughs,"passthrough candidate(s)")),o("stale-abstractions",Math.min(8,e.stale.unused),`${e.stale.unused} unused stale abstraction(s); ${e.stale.singleUse} single-consumer signal(s)`);let C=e.drift.direct/t;if(o("drift",Math.min(5,Math.round(C*50)),`${e.drift.direct} direct drift finding(s); ${e.drift.signal} signal drift finding(s)`),o("complexity",Math.min(5,e.complexity.extremeCount*2),`${e.complexity.extremeCount} extreme complexity hotspot(s)`),e.gitEvidence){let y=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(y/10)),so({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:y},"co-changing pair(s) without a structural link"))}if(s("cycles-pressure","Circular dependencies",e.realCycleCount,3,10,3,"cycle(s)"),s("complexity-pressure","Extreme complexity",e.complexity.extremeCount,3,5,2,"extreme complexity hotspot(s)"),e.gitEvidence){let y=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",y,50,10,4,"score-weighted co-changing pair(s)")}return s("similar-pressure","Similar functions",e.similarCount,Math.max(50,n*.01),8,4,"similar function pair(s)"),s("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",u,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",g,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",S,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",R,50,4,2,"passthrough candidate(s)"),s("stale-abstractions-pressure","Single-consumer stale abstraction signals",e.stale.singleUse,Math.max(50,n*.02),4,2,"single-consumer stale abstraction signal(s)"),s("drift-pressure","Structural drift signals",e.drift.signal,Math.max(10,t*.1),4,2,"signal drift finding(s)"),{breakdown:i,pressure:r}}import{getHeapStatistics as MM}from"v8";var $M=64*1024*1024;function Yl(){let e=globalThis.gc;if(!e)return;let t=MM();t.heap_size_limit-t.used_heap_size<$M||e()}var jM=50,OM=25e3,BM=2500,Lh=2500,Dh=50,HM=10,Ji=["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"],VM={overview:(e,t,n,i)=>({phase:"overview",statsResult:i,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:zM(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:WM(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:GM(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:KM(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:XM(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:QM(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:YM(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:ZM(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:e$(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:t$(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:JM(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:n$(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:i$(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:r$(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:a$(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:c$(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:o$(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:s$(e,n)})};function ao(e,t,n={}){return Zl(e,[t],n)[0]}function Zl(e,t,n={}){return qM(e,n.full!==!1,(i,r)=>{let o={...r,releaseCachesBetweenPhases:!1};return t.map(s=>VM[s](e,n.scope,o,i))})}function qM(e,t,n){let i=We(e),r=l$(i,t);try{return n(i,r)}finally{Vc(e,{semanticProvider:!0}),Yl()}}function eu(e){return Ph(UM(e))}function UM(e){let t=Ee(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,dead:Ee(e,"dead").dead,isolated:Ee(e,"isolated").isolated,realCycleCount:Ee(e,"cycles").realCycleCount,similarCount:Ee(e,"similar").similarCount,reactComponentDuplicates:Ee(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:Ee(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:Ee(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:Ee(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:Ee(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:Ee(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:Ee(e,"extract-candidates").extractCount,wrappers:Ee(e,"wrapper-candidates").wrappers,passthroughs:Ee(e,"passthrough-candidates").passthroughs,stale:Ee(e,"stale-abstractions").stale,drift:Ee(e,"drift").drift,complexity:Ee(e,"complexity-hotspots").complexity,gitEvidence:Eh(e,"git-evidence")?.gitEvidence??null,suppressions:Eh(e,"suppressions")?.suppressions??null}}function Eh(e,t){return e.find(n=>n.phase===t)}function Ee(e,t){let n=e.find(i=>i.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function zM(e,t,n){return ve(e,n,"dead",()=>{let i=Qt(e,{scope:t,...Ce.dead,scanLimit:n.candidateScanLimit});return Qs(m$(e,i.symbols))})}function WM(e,t,n){return ve(e,n,"isolated",()=>{let i=zn(e,{scope:t,...Ce.isolated,scanLimit:n.candidateScanLimit});return Qs(p$(e,i))})}function GM(e,t,n){return ve(e,n,"cycles",()=>Un(e,{scope:t}).filter(r=>r.kind==="real").length)}function KM(e,t,n){let i=ve(e,n,"similar",()=>ml(e,{scope:t,...Ce.similar,scanLimit:n.candidateScanLimit}));return Math.min(i,n.candidateResultLimit)}function JM(e,t,n){return ve(e,n,"extract-candidates",()=>Qn(e,{scope:t,...Ce.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}).length)}function XM(e,t,n){return ve(e,n,"react-component-duplicates",()=>{let i=Gn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return tu(i)})}function QM(e,t,n){return ve(e,n,"react-hook-candidates",()=>{let i=Kn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Th(i,g$)})}function YM(e,t,n){return ve(e,n,"react-large-component-pressure",()=>{let i=qr(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return f$(i)})}function ZM(e,t,n){return ve(e,n,"vue-component-duplicates",()=>{let i=Jn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return tu(i)})}function e$(e,t,n){return ve(e,n,"vue-composable-candidates",()=>{let i=Xn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Th(i,h$)})}function t$(e,t,n){return ve(e,n,"vue-large-view-pressure",()=>{let i=Ur(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Qs(i)})}function n$(e,t,n){return ve(e,n,"wrapper-candidates",()=>{let i=oi(e,{scope:t,...Ce.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Fh(i,y$)})}function i$(e,t,n){return ve(e,n,"passthrough-candidates",()=>{let i=ii(e,{scope:t,...Ce.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Fh(i,b$)})}function r$(e,t,n){return ve(e,n,"stale-abstractions",()=>{let i=ri(e,{scope:t,...Ce.stale,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),r=i.filter(o=>o.consumers===0).length;return{count:i.length,loc:i.reduce((o,s)=>o+s.loc,0),files:[...new Set(i.map(o=>o.file))],unused:r,singleUse:i.length-r}})}function o$(e,t){return ve(e,t,"git-evidence",()=>{let n=Xe(e),i=n.fileChurn();if(!i)return null;let r=Zn(e,void 0,{limit:t.candidateResultLimit}),o={};for(let[s,a]of i)o[s]={changes:a.changes,fixChanges:a.fixChanges};return{amplification:n.changeAmplification(),hiddenCoupling:{pairCount:r.findings.length,scoreCount:nu(r.findings.reduce((s,a)=>s+Nh(a),0)),top:r.findings.slice(0,5).map(s=>({fileA:s.fileA,fileB:s.fileB,together:s.together,confidence:s.confidence,focusedTogether:s.focusedTogether,broadTogether:s.broadTogether,broadCommitRatio:s.broadCommitRatio,lastTogetherAt:s.lastTogetherAt,recentTogether:s.recentTogether,commitScope:s.commitScope,recency:s.recency,scoreWeight:Nh(s),subjectContext:s.subjectContext}))},fileStats:o}})}function s$(e,t){return ve(e,t,"suppressions",()=>{let n=Js(e);return{total:n.total,byCategory:{...n.byCategory}}})}function a$(e,t,n){return ve(e,n,"drift",()=>{let i=ni(e,{scope:t,...Ce.drift,includePatternDeviations:!1}),r=i.results.filter(a=>a.kind!=="pattern-deviation"),o=r.filter(a=>a.actionTier==="direct").length,s=r.length-o;return{count:r.length,unusedImports:i.unusedImports,layerViolations:i.layerViolations,direct:o,signal:s}})}function c$(e,t,n){return ve(e,n,"complexity-hotspots",()=>{let i=oo(e,{scope:t,minLoc:10,limit:n.complexityResultLimit,scanLimit:n.candidateScanLimit,semantic:!1});return{top:i.slice(0,5).map(r=>({symbol:r.shortName,score:r.score,file:r.file})),extremeCount:i.filter(r=>r.score>jM).length}})}function l$(e,t){let n=e.symbols>=OM||e.documents>=BM,i=t?Number.POSITIVE_INFINITY:Dh,r=t?Number.POSITIVE_INFINITY:HM;return!n||t?{candidateScanLimit:void 0,candidateResultLimit:i,complexityResultLimit:r,releaseCachesBetweenPhases:!0,warnings:t&&n?["Large index detected; running health without candidate scan or result caps because full mode is enabled."]:[]}:{candidateScanLimit:Lh,candidateResultLimit:i,complexityResultLimit:r,releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${Lh} symbols and reported their top ${Dh} findings. Enable full mode for unbounded candidate counts.`]}}function u$(e,t){t.releaseCachesBetweenPhases&&(Vc(e),Yl())}function ve(e,t,n,i){d$(n);try{return i()}finally{u$(e,t)}}function d$(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function m$(e,t){return t.filter(n=>!Oe(e,n.relativePath)&&!be(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function p$(e,t){return t.filter(n=>!Oe(e,n.relativePath)&&!be(e,n.symbol,n.relativePath))}function Qs(e){let t=new Set;for(let n of e){let i=n.relativePath??n.file;i&&t.add(i)}return{count:e.length,loc:e.reduce((n,i)=>n+i.loc,0),files:[...t]}}function Fh(e,t){return{...Qs(e),scoreCount:nu(e.reduce((i,r)=>i+t(r),0))}}function f$(e){let t=new Map;for(let n of e)t.set(n.file,Math.max(t.get(n.file)??0,n.loc));return{count:t.size,loc:[...t.values()].reduce((n,i)=>n+i,0),files:[...t.keys()]}}function tu(e){let t=new Map;for(let n of e)t.set(n.fileA,Math.max(t.get(n.fileA)??0,n.locA)),t.set(n.fileB,Math.max(t.get(n.fileB)??0,n.locB));return{count:e.length,loc:[...t.values()].reduce((n,i)=>n+i,0),files:[...t.keys()]}}function Th(e,t){return{...tu(e),scoreCount:nu(e.reduce((i,r)=>i+t(r),0))}}function g$(e){let t=e.sharedHooks.length>0,n=_h({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:Ah(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function h$(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=_h({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:Ah(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function _h(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!$h.has(Mh(t))).length+Math.min(e.functions.length,3)}function Ah(e,t,n){let i=[...e,...t,...n].map(Mh);return i.length>0&&i.every(r=>$h.has(r))}function Mh(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function y$(e){return e.actionTier==="signal"?.25:1}function b$(e){return e.actionTier==="signal"?.25:1}function Nh(e){return e.commitScope==="broad-sweep"?e.recency==="recent"?.25:0:e.commitScope==="mixed"?e.recency==="recent"?.5:.25:e.recency==="recent"?1:.5}function nu(e){return Math.round(e*100)/100}var $h=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 iu(e,t,n,i={}){let r=q(e,t),o=q(e,n);if(!r||!o)return null;let s=Je(e,r,{semantic:i.semantic}),a=Je(e,o,{semantic:i.semantic}),c=s.filter(y=>!jh(e,y)),l=a.filter(y=>!jh(e,y)),d=c.length!==s.length||l.length!==a.length,u=new Set(c.map(y=>y.symbol)),m=new Set(l.map(y=>y.symbol)),p=[];for(let y of u)m.has(y)&&p.push(y);let f=[];for(let y of u)m.has(y)||f.push(y);let g=[];for(let y of m)u.has(y)||g.push(y);let b=new Set([...u,...m]),x=b.size>0?p.length/b.size:0,S;b.size===0?S="Neither function calls other tracked symbols. There is no callee-pattern evidence for consolidation; inspect the source bodies directly.":p.length===0?S="These functions do not share any callees. They are not a callee-based consolidation candidate.":f.length===0&&g.length===0?S="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.":f.length===0?S="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.":g.length===0?S="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.":f.length<=2&&g.length<=2?S=`Create a shared function with the ${p.length} common callees. Pass the ${f.length+g.length} divergent callees as parameters or strategy callbacks.`:S=`Extract the ${p.length} shared callees into a common helper. Each function calls the helper plus its own unique logic (${f.length} callees in A, ${g.length} in B).`,d&&(S=`Ignored Clojure macro scaffolding while comparing tracked callees. ${S}`);let R=r.endLine-r.startLine+1,C=o.endLine-o.startLine+1;return{symbolA:{symbol:r.symbol,shortName:v(r.symbol),file:r.relativePath,loc:R},symbolB:{symbol:o.symbol,shortName:v(o.symbol),file:o.relativePath,loc:C},similarity:x,sharedCallees:p.map(v),uniqueToA:f.map(v),uniqueToB:g.map(v),consolidationStrategy:S}}function jh(e,t){return Q(e,t.file).some(n=>n.symbol===t.symbol&&Ln(e,n))}import{readFileSync as Oh}from"fs";import{extname as S$,join as Bh}from"path";function ru(e,t,n={}){let{context:i=0}=n,r=x$(t);if(r)return v$(e,r.filePath,r.startLine,r.endLine,i);let o=q(e,t);return o?C$(e,o,i):null}function x$(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 C$(e,t,n){let i=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),r=Bh(e.config.projectRoot,t.relativePath),o;try{o=Oh(r,"utf-8")}catch{return null}let s=o.split(`
631
655
  `),a=Math.max(0,t.startLine-n),c=Math.min(s.length-1,t.endLine+n),l=s.slice(a,c+1).join(`
632
- `);return{symbol:t.symbol,shortName:b(t.symbol),relativePath:t.relativePath,startLine:a,endLine:c,language:r?.language??Zf(t.relativePath),source:l}}function B0(e,t,n,r,i){let o=Fe(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=Yf(e.config.projectRoot,s.relative_path),c;try{c=Qf(a,"utf-8")}catch{return null}let l=c.split(`
633
- `),u=Math.max(0,n-1-i),d=Math.min(l.length-1,r-1+i),m=l.slice(u,d+1).join(`
634
- `);return{symbol:`${s.relative_path}:${n}-${r}`,shortName:`${s.relative_path}:${n}-${r}`,relativePath:s.relative_path,startLine:u,endLine:d,language:s.language??Zf(s.relative_path),source:m}}function Zf(e){switch(M0(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 ll(e,t={}){let{scope:n,limit:r}=t,i=new F(e),o=J0([...H0(e,n),...U0(e,i,n)]);return K0(o),r?o.slice(0,r):o}function H0(e,t){let n=[];for(let r of V0(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||Ta(e,r.barrel_path)||T(e,r.barrel_path)&&Eo(e,r.barrel_path).length===0)continue;let i=q0(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,...tg(e,r.barrel_path)})}return n}function V0(e,t){let n=t?`AND barrel_d.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
656
+ `);return{symbol:t.symbol,shortName:v(t.symbol),relativePath:t.relativePath,startLine:a,endLine:c,language:i?.language??Hh(t.relativePath),source:l}}function v$(e,t,n,i,r){let o=Ve(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=Bh(e.config.projectRoot,s.relative_path),c;try{c=Oh(a,"utf-8")}catch{return null}let l=c.split(`
657
+ `),d=Math.max(0,n-1-r),u=Math.min(l.length-1,i-1+r),m=l.slice(d,u+1).join(`
658
+ `);return{symbol:`${s.relative_path}:${n}-${i}`,shortName:`${s.relative_path}:${n}-${i}`,relativePath:s.relative_path,startLine:d,endLine:u,language:s.language??Hh(s.relative_path),source:m}}function Hh(e){switch(S$(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 ou(e,t={}){let{scope:n,limit:i}=t,r=new A(e),o=E$([...R$(e,n),...P$(e,r,n)]);return N$(o),i?o.slice(0,i):o}function R$(e,t){let n=[];for(let i of k$(e,t)){if(e.isIgnored(i.barrel_path)||e.isIgnored(i.original_path)||vc(e,i.barrel_path)||M(e,i.barrel_path)&&es(e,i.barrel_path).length===0)continue;let r=w$(e,i),o=r?.barrel_consumers??0,s=r?.direct_consumers??0;o!==0||s!==0||n.push({barrelFile:i.barrel_path,symbol:i.symbol,shortName:v(i.symbol),originalFile:i.original_path,barrelConsumers:o,directConsumers:s,...qh(e,i.barrel_path)})}return n}function k$(e,t){let n=t?`AND barrel_d.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
635
659
  barrel_d.id AS barrel_doc_id,
636
660
  barrel_d.relative_path AS barrel_path,
637
661
  gs.id AS symbol_id,
@@ -661,7 +685,7 @@ ${n}`.toLowerCase(),i=An(r,["historical note","historical record","history note"
661
685
  -- Only function-level symbols (ending with ().), not module-level
662
686
  AND gs.symbol LIKE '%().'
663
687
  ${n}
664
- ORDER BY barrel_d.relative_path, gs.symbol`)}function q0(e,t){return e.get(`SELECT
688
+ ORDER BY barrel_d.relative_path, gs.symbol`)}function w$(e,t){return e.get(`SELECT
665
689
  SUM(CASE WHEN uses_barrel = 1 THEN 1 ELSE 0 END) AS barrel_consumers,
666
690
  SUM(CASE WHEN uses_barrel = 0 THEN 1 ELSE 0 END) AS direct_consumers
667
691
  FROM (
@@ -690,7 +714,7 @@ ${n}`.toLowerCase(),i=An(r,["historical note","historical record","history note"
690
714
  AND consumer_d.id != ?
691
715
  ${e.pathExclusionsFor("consumer_d")}
692
716
  GROUP BY consumer_d.id
693
- )`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function U0(e,t,n){let r=[];for(let i of W0(e,n))ng(e,i,i)>0||r.push(...G0(e,t,i));return r}function W0(e,t){return O(e,{scope:t,includeIgnored:!1}).filter(n=>Eo(e,n).length>0||ni(e,n).length>0)}function G0(e,t,n){let r=Eo(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>eg(e,t,n,o.sourcePath)),i=ni(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>eg(e,t,n,o.sourcePath));return[...r,...i]}function eg(e,t,n,r){let i=z0(t,r);return i?[{barrelFile:n,symbol:i.symbol,shortName:b(i.symbol),originalFile:r,barrelConsumers:0,directConsumers:ng(e,r,n),...tg(e,n)}]:[]}function tg(e,t){return xr(e,t)?{actionTier:"signal",surfaceEvidence:["barrel file is declared on the package public surface"],recommendation:"Review the package API before removing this re-export; local consumers are zero, but external consumers may import through the public barrel."}:{actionTier:"direct",surfaceEvidence:[],recommendation:"Remove this unused re-export when the barrel is not part of an external API surface."}}function ng(e,t,n){let r=new Set;for(let i of O(e,{includeIgnored:!1}))if(i!==n)for(let o of xe(e,i))o.sourcePath===t&&r.add(i);return r.size}function z0(e,t){let n=e.definitionsForFile(t);return n.find(r=>re(r.symbol)==="method")??n[0]??null}function J0(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 K0(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function dl(e,t={}){let{samples:n=50,scope:r,maxDisagreements:i=5}=t,o=new F(e),s=X0(o.productionCallableDefinitions({scope:r,minLoc:2,requireFunctionLikeSymbol:!0}),n);if(s.length===0||!Q0(e,s))return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let a={references:rg(),callees:rg()},c=[],l=0,u=Vo(e,s);for(let d of s){let m=ks(d,Qt(e,d).map(h=>h.file)),p=ks(d,(u.get(d.symbolId)??[]).map(h=>h.file));if(m.size===0&&p.size===0)continue;l+=1;let g=ks(d,wn(e,d).map(h=>h.file)),y=ks(d,(o.calleeMap([d],{semantic:!1}).get(d.symbolId)??[]).map(h=>h.file));ig(a.references,d,"references",g,m,c),ig(a.callees,d,"callees",y,p,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?ul(l/s.length):0,scores:["references","callees"].map(d=>Z0(d,a[d])),topDisagreements:c.slice(0,i)}}function rg(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0}}function X0(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 Q0(e,t){let n=t[0];if(!n)return!1;try{return Xt(e,n.relativePath).availability().available}catch{return!1}}function ks(e,t){let n=new Set;for(let r of t)r!==e.relativePath&&n.add(r);return n}function ig(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 Y0={references:!0,callees:!1};function Z0(e,t){let n=t.oracleTotal>0?t.agreed/t.oracleTotal:1,r=t.cheapTotal-t.agreed;return{question:e,comparedSymbols:t.comparedSymbols,precision:Y0[e]&&t.cheapTotal>0?ul(t.agreed/t.cheapTotal):null,recall:ul(n),unverified:r}}function ul(e){return Math.round(e*1e3)/1e3}function ml(e,t={}){let{scope:n,minLoc:r=1,limit:i,scanLimit:o}=t,s=t.semantic!==!1,a=tF(e,eF(e,{scope:n,minLoc:r,scanLimit:o}),{semantic:s}),c=rF(a);return i?c.slice(0,i):c}function eF(e,t){let n=ft(e,{scope:t.scope}).filter(r=>r.isFunctionLike&&!e.isIgnored(r.relativePath)).filter(r=>U(r)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((r,i)=>U(i)-U(r)||r.relativePath.localeCompare(i.relativePath)),Ve(n,t.scanLimit)}function tF(e,t,n){let r=new Map;for(let i of t){let o=iF(e,i,n);if(!o)continue;let s=r.get(o)??[];s.push(nF(i)),r.set(o,s)}return r}function nF(e){return{symbol:e.symbol,shortName:b(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:U(e)}}function rF(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 iF(e,t,n){if(n.semantic){let o=Pm(e,t);if(o)return o}let r=oF(t.documentation),i=r?cF(r):null;return i||lF(sF(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function oF(e){return mn(pn(e))}function sF(e,t,n,r,i){let o=T(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=dF(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,aF(u)))return u}if(u&&u.includes("("))return u}return null}function aF(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||ei(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function cF(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 lF(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${og(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=uF(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 uF(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 dF(e,t,n,r){let i=og(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 og(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}import{existsSync as dg}from"fs";import{join as EF}from"path";import mF from"better-sqlite3";var pF=["node_modules",".git","dist","build","out","coverage","target",".next",".nuxt",".cache",".turbo",".scipquery-cache","__pycache__",".venv","venv"],Fr=class{db;config;pathFilter;statementCache=new Map;constructor(t,n){this.config=t,this.pathFilter=n??null,this.db=new mF(t.dbPath,{readonly:!0}),this.db.pragma("busy_timeout = 5000"),this.db.pragma("query_only = ON"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("cache_size = -64000"),this.db.pragma("mmap_size = 268435456")}isIgnored(t){return this.pathFilter?.isIgnored(t)??!1}get localSymbolPredicate(){return`(
717
+ )`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function P$(e,t,n){let i=[];for(let r of I$(e,n))Uh(e,r,r)>0||i.push(...L$(e,t,r));return i}function I$(e,t){return O(e,{scope:t,includeIgnored:!1}).filter(n=>es(e,n).length>0||xr(e,n).length>0)}function L$(e,t,n){let i=es(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>Vh(e,t,n,o.sourcePath)),r=xr(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>Vh(e,t,n,o.sourcePath));return[...i,...r]}function Vh(e,t,n,i){let r=D$(t,i);return r?[{barrelFile:n,symbol:r.symbol,shortName:v(r.symbol),originalFile:i,barrelConsumers:0,directConsumers:Uh(e,i,n),...qh(e,n)}]:[]}function qh(e,t){return _i(e,t)?{actionTier:"signal",surfaceEvidence:["barrel file is declared on the package public surface"],recommendation:"Review the package API before removing this re-export; local consumers are zero, but external consumers may import through the public barrel."}:{actionTier:"direct",surfaceEvidence:[],recommendation:"Remove this unused re-export when the barrel is not part of an external API surface."}}function Uh(e,t,n){let i=new Set;for(let r of O(e,{includeIgnored:!1}))if(r!==n)for(let o of oe(e,r))o.sourcePath===t&&i.add(r);return i.size}function D$(e,t){let n=e.definitionsForFile(t);return n.find(i=>se(i.symbol)==="method")??n[0]??null}function E$(e){let t=new Set,n=[];for(let i of e){let r=`${i.barrelFile}|${i.symbol}|${i.originalFile}`;t.has(r)||(t.add(r),n.push(i))}return n}function N$(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function cu(e,t={}){let{samples:n=50,scope:i,maxDisagreements:r=5}=t,o=new A(e),s=F$(o.productionCallableDefinitions({scope:i,minLoc:2,requireFunctionLikeSymbol:!0}),n),a=T$(e,s);if(s.length===0||!a)return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let c={references:zh(),callees:zh()},l=[],d=0,u=a==="semantic"?ys(e,s):new Map,m=a==="source"?M$(e,o,s):null;for(let p of s){let f=Ys(p,a==="semantic"?$i(e,p).map(S=>S.file):[...m?.referencesBySymbolId.get(p.symbolId)??[]]),g=Ys(p,a==="semantic"?(u.get(p.symbolId)??[]).map(S=>S.file):[...m?.calleesBySymbolId.get(p.symbolId)??[]]);if(f.size===0&&g.size===0)continue;d+=1;let b=Ys(p,Vn(e,p).map(S=>S.file)),x=Ys(p,(o.calleeMap([p],{semantic:!1}).get(p.symbolId)??[]).map(S=>S.file));Wh(c.references,p,"references",b,f,l),Wh(c.callees,p,"callees",x,g,l)}return l.sort((p,f)=>f.cheapOnly.length+f.oracleOnly.length-(p.cheapOnly.length+p.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?au(d/s.length):0,oracleKind:a,scores:["references","callees"].map(p=>A$(p,c[p],a)),topDisagreements:l.slice(0,r)}}function zh(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0}}function F$(e,t){let n=[...e].sort((o,s)=>o.symbolId-s.symbolId);if(n.length<=t)return n;let i=n.length/t,r=[];for(let o=0;o<t;o++)r.push(n[Math.floor(o*i)]);return r}function T$(e,t){let n=t[0];if(!n)return null;if(su(e,n))return"source";try{if(Xt(e).capability("semantic-references",n.relativePath).available)return"semantic"}catch{}return t.some(i=>su(e,i))?"source":null}function Ys(e,t){let n=new Set;for(let i of t)i!==e.relativePath&&n.add(i);return n}function Wh(e,t,n,i,r,o){if(i.size===0&&r.size===0)return;e.comparedSymbols+=1,e.cheapTotal+=i.size,e.oracleTotal+=r.size;let s=[],a=[];for(let c of i)r.has(c)?e.agreed+=1:s.push(c);for(let c of r)i.has(c)||a.push(c);(s.length>0||a.length>0)&&o.push({symbol:v(t.symbol),question:n,cheapOnly:s,oracleOnly:a})}var _$={references:!0,callees:!1};function A$(e,t,n){let i=t.oracleTotal>0?t.agreed/t.oracleTotal:1,r=t.cheapTotal-t.agreed,o=n==="semantic"?_$[e]:!1;return{question:e,comparedSymbols:t.comparedSymbols,precision:o&&t.cheapTotal>0?au(t.agreed/t.cheapTotal):null,recall:au(i),unverified:r}}function su(e,t){return H(t.relativePath)==="clojure"&&X(e,t.relativePath)!==null}function M$(e,t,n){let i=new Map,r=new Map,o=n.filter(c=>su(e,c)),s=new Map;for(let c of o){let l=s.get(c.leaf)??[];l.push(c),s.set(c.leaf,l)}for(let c of t.sourceFiles()){if(H(c)!=="clojure")continue;let l=X(e,c);if(l)for(let d of l.fileIdentifiers)for(let u of s.get(d)??[])Gh(i,u.symbolId,c)}let a=new Map;for(let c of t.scopedDefinitions()){if(H(c.relativePath)!=="clojure")continue;let l=a.get(c.leaf)??[];l.push(c),a.set(c.leaf,l)}for(let c of o){let l=X(e,c.relativePath);if(l){for(let d of l.callSites)if(!(d.line<c.startLine||d.line>c.endLine))for(let u of a.get(d.calleeLeaf)??[])Gh(r,c.symbolId,u.relativePath)}}return{referencesBySymbolId:i,calleesBySymbolId:r}}function Gh(e,t,n){let i=e.get(t);if(i){i.add(n);return}e.set(t,new Set([n]))}function au(e){return Math.round(e*1e3)/1e3}function lu(e,t={}){let{scope:n,minLoc:i=1,limit:r,scanLimit:o}=t,s=t.semantic!==!1,a=j$(e,$$(e,{scope:n,minLoc:i,scanLimit:o}),{semantic:s}),c=B$(a);return r?c.slice(0,r):c}function $$(e,t){let n=Lt(e,{scope:t.scope}).filter(i=>i.isFunctionLike&&!e.isIgnored(i.relativePath)).filter(i=>J(i)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((i,r)=>J(r)-J(i)||i.relativePath.localeCompare(r.relativePath)),qe(n,t.scanLimit)}function j$(e,t,n){let i=new Map;for(let r of t){let o=H$(e,r,n);if(!o)continue;let s=i.get(o)??[];s.push(O$(r)),i.set(o,s)}return i}function O$(e){return{symbol:e.symbol,shortName:v(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:J(e)}}function B$(e){let t=[];for(let[n,i]of e)i.length>=2&&t.push({signature:n,functions:i});return t.sort((n,i)=>{let r=i.functions.length-n.functions.length;if(r!==0)return r;let o=n.functions.reduce((a,c)=>a+c.loc,0);return i.functions.reduce((a,c)=>a+c.loc,0)-o}),t}function H$(e,t,n){if(n.semantic){let o=nf(e,t);if(o)return o}let i=V$(t.documentation),r=i?z$(i):null;return r||W$(q$(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function V$(e){return Mn($n(e))}function q$(e,t,n,i,r){let o=M(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=K$(s,n,i,r);for(let c of a){let l=Math.min(s.length-1,Math.max(c,c+4)),d="";for(let u=c;u<=l;u+=1){let m=s[u]?.trim();if(m&&(d=d?`${d} ${m}`:m,U$(d)))return d}if(d&&d.includes("("))return d}return null}function U$(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||br(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function z$(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 W$(e,t){if(!e||!e.trim())return null;let n=e.replace(/\s+/g," ").trim(),i=n.indexOf("(");if(i===-1)return null;let r=n.slice(0,i),s=new RegExp(`\\b${Kh(t)}\\b`,"i").exec(r);s&&typeof s.index=="number"&&(r=r.slice(0,s.index)),r=r.replace(/\b(public|private|protected|internal|final|static|abstract|sealed|virtual|override|async|suspend|inline|constexpr|consteval|constinit|const|pub|fn|function|def|sub|friend|shared|readonly|new|open|partial|export)\b/gi," ").replace(/\s+/g," ").trim();let a=G$(n.slice(i)).replace(/\)\s*=\s*[\s\S]*$/,")").replace(/\s+throws\s+[^={]+$/i,"").replace(/\s+where\s+.+$/i,"").replace(/\s+/g," ").trim();if(!a.startsWith("("))return null;let c=`${r?`${r} `:""}${a}`.replace(/\s+/g,"").toLowerCase();return c.length>=3?c:null}function G$(e){let t=0,n=0,i=0,r=0,o=null,s=!1;for(let a=0;a<e.length;a+=1){let c=e[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c===o&&(o=null);continue}if(c==='"'||c==="'"||c==="`"){o=c;continue}if(c==="(")t+=1;else if(c===")")t=Math.max(0,t-1);else if(c==="[")i+=1;else if(c==="]")i=Math.max(0,i-1);else if(c==="<")r+=1;else if(c===">")r=Math.max(0,r-1);else if(c==="{"){if(t===0&&i===0&&r===0)return e.slice(0,a);n+=1}else if(c==="}")n=Math.max(0,n-1);else if(c==="="&&e[a+1]===">"&&t===0&&n===0&&i===0&&r===0)return e.slice(0,a)}return e}function K$(e,t,n,i){let r=Kh(i),o=new RegExp(`\\b${r}\\b\\s*\\(`,"i"),s=new RegExp(`\\bdef\\s+${r}\\b`,"i"),a=[],c=new Set,l=Math.max(0,Math.min(t,e.length-1)),d=Math.max(l,Math.min(e.length-1,Math.max(n,t+4)));for(let u=l;u<=d;u+=1){let m=e[u]??"";(o.test(m)||s.test(m))&&!c.has(u)&&(c.add(u),a.push(u))}for(let u=0;u<e.length;u+=1){let m=e[u]??"";(o.test(m)||s.test(m))&&!c.has(u)&&(c.add(u),a.push(u))}return a}function Kh(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}import{existsSync as ny}from"fs";import{join as mj}from"path";import J$ from"better-sqlite3";var X$=["node_modules",".git","dist","build","out","coverage","target",".next",".nuxt",".cache",".turbo",".nbb",".cpcache",".shadow-cljs",".scipquery-cache","__pycache__",".venv","venv"],Xi=class{db;config;pathFilter;statementCache=new Map;constructor(t,n){this.config=t,this.pathFilter=n??null,this.db=new J$(t.dbPath,{readonly:!0}),this.db.pragma("busy_timeout = 5000"),this.db.pragma("query_only = ON"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("cache_size = -64000"),this.db.pragma("mmap_size = 268435456")}isIgnored(t){return this.pathFilter?.isIgnored(t)??!1}get localSymbolPredicate(){return`(
694
718
  EXISTS (
695
719
  SELECT 1
696
720
  FROM defn_enclosing_ranges local_der
@@ -707,8 +731,8 @@ ${n}`.toLowerCase(),i=An(r,["historical note","historical record","history note"
707
731
  AND local_m.role = 1
708
732
  ${this.pathExclusionsFor("local_d").trimStart()}
709
733
  )
710
- )`}get pathExclusions(){return this.pathExclusionsFor("d")}get symbolNoise(){return this.symbolNoiseFor("gs")}pathExclusionsFor(...t){return t.flatMap(n=>pF.flatMap(r=>[`AND ${n}.relative_path NOT LIKE '${r}/%'`,`AND ${n}.relative_path NOT LIKE '%/${r}/%'`])).join(`
711
- `)}symbolNoiseFor(t){return`AND ${t}.symbol NOT LIKE '%().(%' AND ${t}.symbol NOT LIKE '%typeLiteral%'`}all(t,...n){return this.statement(t).all(...n)}get(t,...n){return this.statement(t).get(...n)}close(){this.statementCache.clear(),this.db.close()}statement(t){let n=this.statementCache.get(t);return n||(n=this.db.prepare(t),this.statementCache.set(t,n)),n}};import fF from"ignore";import{readFileSync as gF,existsSync as pl}from"fs";import{dirname as fl,isAbsolute as sg,join as gl,relative as hF,resolve as yF}from"path";function rn(e){let t=fF(),n=!1,r=bF(e);for(let i of r)try{let o=gF(i,"utf-8");t.add(o),n=!0}catch{}return n||t.add(SF),{isIgnored:i=>ag(t,e,i),filter:i=>i.filter(o=>!ag(t,e,o))}}function bF(e){let t=[],n=gl(e,".gitignore");pl(n)&&t.push(n);let r=fl(e),i=0;for(;r!==fl(r)&&i<5;){let o=gl(r,".gitignore");if(pl(o)&&t.push(o),pl(gl(r,".git")))break;r=fl(r),i++}return t}var SF=`
734
+ )`}get pathExclusions(){return this.pathExclusionsFor("d")}get symbolNoise(){return this.symbolNoiseFor("gs")}pathExclusionsFor(...t){return t.flatMap(n=>X$.flatMap(i=>[`AND ${n}.relative_path NOT LIKE '${i}/%'`,`AND ${n}.relative_path NOT LIKE '%/${i}/%'`])).join(`
735
+ `)}symbolNoiseFor(t){return`AND ${t}.symbol NOT LIKE '%().(%' AND ${t}.symbol NOT LIKE '%typeLiteral%'`}all(t,...n){return this.statement(t).all(...n)}get(t,...n){return this.statement(t).get(...n)}close(){this.statementCache.clear(),this.db.close()}statement(t){let n=this.statementCache.get(t);return n||(n=this.db.prepare(t),this.statementCache.set(t,n)),n}};import Q$ from"ignore";import{readFileSync as Y$,existsSync as uu}from"fs";import{dirname as du,isAbsolute as Jh,join as mu,relative as Z$,resolve as ej}from"path";function Cn(e){let t=Q$(),n=!1,i=tj(e);for(let r of i)try{let o=Y$(r,"utf-8");t.add(o),n=!0}catch{}return n||t.add(nj),{isIgnored:r=>Xh(t,e,r),filter:r=>r.filter(o=>!Xh(t,e,o))}}function tj(e){let t=[],n=mu(e,".gitignore");uu(n)&&t.push(n);let i=du(e),r=0;for(;i!==du(i)&&r<5;){let o=mu(i,".gitignore");if(uu(o)&&t.push(o),uu(mu(i,".git")))break;i=du(i),r++}return t}var nj=`
712
736
  # Dependencies
713
737
  node_modules/
714
738
  vendor/
@@ -765,30 +789,31 @@ Thumbs.db
765
789
 
766
790
  # Type definitions (often noise in queries)
767
791
  *.d.ts
768
- `;function ag(e,t,n){let r=xF(t,n);if(!r)return!1;try{return e.ignores(r)}catch{return!1}}function xF(e,t){if(!t||t===".")return null;if(!sg(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let n=sg(t)?t:yF(e,t),r=hF(e,n).replaceAll("\\","/");return!r||r==="."||r.startsWith("..")?null:r}import{readFileSync as CF,writeFileSync as cg,existsSync as Oi,mkdirSync as vF}from"fs";import{isAbsolute as RF,join as xt,relative as kF,resolve as yl}from"path";import{createHash as wF}from"crypto";import{homedir as LF}from"os";var ji=".scipquery.json",IF={enabled:!1,debounceMs:3e4,cooldownMs:6e4,gitPollMs:2e3,autoRefresh:!0,ignore:[]},DF=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php"];function _e(e){let t=xt(e,ji);if(!Oi(t))return{};try{let n=CF(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 ${ji} at ${t}: ${r}`,{cause:n}):new Error(`unable to read ${ji} at ${t}: ${r}`,{cause:n})}}function Ar(e,t={}){let n=[],r=new Set(DF);for(let[s,a]of(e.languages??[]).entries())r.has(a)||n.push({level:"error",path:`languages[${s}]`,message:`Unsupported language: ${a}`});e.indexerConcurrency!==void 0&&(!Number.isInteger(e.indexerConcurrency)||e.indexerConcurrency<=0)&&n.push({level:"error",path:"indexerConcurrency",message:"Must be a positive integer."}),e.watch?.debounceMs!==void 0&&e.watch.debounceMs<=0&&n.push({level:"error",path:"watch.debounceMs",message:"Must be greater than 0."}),e.watch?.cooldownMs!==void 0&&e.watch.cooldownMs<=0&&n.push({level:"error",path:"watch.cooldownMs",message:"Must be greater than 0."}),e.watch?.gitPollMs!==void 0&&e.watch.gitPollMs<=0&&n.push({level:"error",path:"watch.gitPollMs",message:"Must be greater than 0."}),e.watch?.autoRefresh!==void 0&&typeof e.watch.autoRefresh!="boolean"&&n.push({level:"error",path:"watch.autoRefresh",message:"Must be a boolean."});let i=e.indexer?.typescript;if(i?.projectMode!==void 0&&i.projectMode!=="single"&&i.projectMode!=="workspace"&&n.push({level:"error",path:"indexer.typescript.projectMode",message:'Must be "single" or "workspace".'}),i?.projects!==void 0)if(!Array.isArray(i.projects))n.push({level:"error",path:"indexer.typescript.projects",message:"Must be an array."});else for(let[s,a]of i.projects.entries()){let c=`indexer.typescript.projects[${s}]`;if(typeof a!="string"||a.trim()==="")n.push({level:"error",path:c,message:"Project path must be a non-empty string."});else if(t.projectRoot){let l=yl(t.projectRoot,a),u=kF(t.projectRoot,l);u.startsWith("..")||RF(u)?n.push({level:"error",path:c,message:"Project path must stay inside the project root."}):Oi(l)||n.push({level:"warning",path:c,message:`TypeScript project path does not exist: ${a}`})}}if(i?.projectMode==="workspace"&&i.pnpmWorkspaces===!0&&n.push({level:"warning",path:"indexer.typescript.pnpmWorkspaces",message:'Ignored when projectMode is "workspace"; explicit TypeScript projects are indexed directly.'}),e.locality!==void 0)if(!NF(e.locality))n.push({level:"error",path:"locality",message:"Must be an object."});else{let s=e.locality.architecturalBoundarySegments;if(s!==void 0)if(!Array.isArray(s))n.push({level:"error",path:"locality.architecturalBoundarySegments",message:"Must be an array."});else for(let[a,c]of s.entries()){let l=`locality.architecturalBoundarySegments[${a}]`;typeof c!="string"||c.trim()===""?n.push({level:"error",path:l,message:"Boundary segment must be a non-empty string."}):(c.includes("/")||c.includes("\\"))&&n.push({level:"error",path:l,message:"Boundary segment must be a single folder name, not a path."})}}if(e.declaredCouplings!==void 0&&!Array.isArray(e.declaredCouplings))n.push({level:"error",path:"declaredCouplings",message:"Must be an array."});else for(let[s,a]of(e.declaredCouplings??[]).entries()){let c=`declaredCouplings[${s}]`;if((!a.name||a.name.trim()==="")&&n.push({level:"error",path:`${c}.name`,message:"Declared coupling name is required."}),!Array.isArray(a.files)||a.files.length<2)n.push({level:"error",path:`${c}.files`,message:"Declared coupling needs at least two files."});else for(let[l,u]of a.files.entries())!u||u.trim()===""?n.push({level:"error",path:`${c}.files[${l}]`,message:"Declared coupling file path is required."}):t.projectRoot&&!Oi(xt(t.projectRoot,u))&&n.push({level:"warning",path:`${c}.files[${l}]`,message:`Declared coupling file does not exist: ${u}`});a.reason!==void 0&&a.reason.trim()===""&&n.push({level:"error",path:`${c}.reason`,message:"Declared coupling reason cannot be blank."})}let o=t.now??new Date;for(let[s,a]of(e.suppressions??[]).entries()){let c=`suppressions[${s}]`;if((!a.reason||a.reason.trim()==="")&&n.push({level:"error",path:`${c}.reason`,message:"Suppression reason is required."}),!a.id&&!a.check&&n.push({level:"error",path:c,message:"Suppression must include id or check."}),a.file!==void 0&&(a.file.trim()===""?n.push({level:"error",path:`${c}.file`,message:"Suppression file path cannot be blank."}):t.projectRoot&&!Oi(xt(t.projectRoot,a.file))&&n.push({level:"warning",path:`${c}.file`,message:`Suppression file does not exist: ${a.file}`})),a.expiresAt){let l=Date.parse(a.expiresAt);Number.isNaN(l)?n.push({level:"error",path:`${c}.expiresAt`,message:"Must be an ISO date string."}):l<=o.getTime()&&n.push({level:"warning",path:`${c}.expiresAt`,message:"Suppression has expired."})}}return n}function $r(e){return{...IF,...e.watch}}function PF(e,t){let n=process.env.SCIP_QUERY_CACHE_DIR;if(n)return hl(n);if(t?.dbPath)return hl(yl(e,t.dbPath));let i=process.env.XDG_CACHE_HOME||xt(LF(),".cache"),o=wF("sha256").update(yl(e)).digest("hex").slice(0,12),s=xt(i,"scip-query","projects",o);return hl(s)}function Ct(e,t){let n=PF(e,t);return{cacheDir:n,dbPath:xt(n,"index.db"),indexPath:xt(n,"index.scip"),metaPath:xt(n,"meta.json")}}function lg(e,t){let n=xt(e,ji);return Oi(n)||cg(n,JSON.stringify({languages:t,watch:{enabled:!1,debounceMs:3e4,cooldownMs:6e4,gitPollMs:2e3,autoRefresh:!0}},null,2)+`
769
- `),n}function ug(e,t){let n=xt(e,ji),r=_e(e),i={...r,suppressions:[...r.suppressions??[],t]},o=Ar(i,{projectRoot:e}).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 cg(n,JSON.stringify(i,null,2)+`
770
- `),{path:n,suppressionCount:i.suppressions?.length??0}}function hl(e){return vF(e,{recursive:!0}),e}function NF(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ge(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}function Mr(e=ge()){let t=_e(e),n=Ct(e,t),r=process.env.SCIP_QUERY_INDEX_DB??(dg(n.dbPath)?n.dbPath:EF(e,"index.db"));return{projectRoot:e,config:t,paths:n,dbPath:r}}function Or(e){return Mr(e).dbPath}function TF(){let{projectRoot:e,config:t,paths:n,dbPath:r}=Mr();dg(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,locality:t.locality},o=rn(e);return new Fr(i,o)}function et(e){let t=TF();try{return e(t)}finally{t.close()}}function bl(e,t){return t.concat([e])}function Vn(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 mg(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 _F(e)}}function _F(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}import{spawnSync as s8}from"child_process";function pg(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function qe(e){return e+1}function we(e,t){return`${qe(e)}-${qe(t)}`}function Re(e,t,n){return`${e}:${we(t,n)}`}function ws(e,t=180){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var N={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 MF=AF(import.meta.url),{version:Ls}=JF(),Bi="__health-phase",Is="__diff-impact-batch",OF=10,jF=4,BF=8,HF=75e3,VF=5e3,fg=2500,qF=4,UF=12,WF=10*1024*1024,gg=new Set(["react-component-duplicates","react-hook-candidates","react-large-component-pressure"]),hg=new Set(["vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure"]),GF=new Set([...hg,"suppressions"]),zF=new Set(["similar","extract-candidates"]);function JF(){for(let e of["../package.json","../../package.json"])try{return MF(e)}catch{}return{version:"0.0.0"}}function jr(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
771
- `)}function KF(e){let t=Oe(e);return t.symbols>=HF||t.documents>=VF}function Ds(e,t,n,r={}){return KF(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 ${fg} candidates with semantic enrichment disabled. Run "scip-query ${t} --full" for the unbounded semantic pass.`),{scanLimit:fg,semantic:!1}):{semantic:!0}}async function Ps(e){let{applicability:t,overview:n}=et(a=>({applicability:XF(a,e),overview:Mi(a,"overview",e)})),r=new Map;r.set("overview",n);let i=_r.filter(a=>a==="overview"?!1:QF(a,t)?!0:(r.set(a,ZF(a)),!1)),o=YF(i);return(await yg(o,nA(o.length),a=>eA(a,e))).flat().forEach(a=>r.set(a.phase,a)),il(_r.map(a=>r.get(a)))}function XF(e,t){return lo(e,{scope:t.scope})}function QF(e,t){return gg.has(e)?t.react:hg.has(e)?t.vue:!0}function YF(e){let t=[gg,GF,zF],n=new Set,r=[];for(let i of e){if(n.has(i))continue;let o=t.find(a=>a.has(i));if(!o){n.add(i),r.push([i]);continue}let s=e.filter(a=>o.has(a));s.forEach(a=>n.add(a)),r.push(s)}return r}function ZF(e){switch(e){case"react-component-duplicates":return{phase:e,reactComponentDuplicates:{count:0,loc:0,files:[]}};case"react-hook-candidates":return{phase:e,reactHookCandidates:{count:0,loc:0,files:[]}};case"react-large-component-pressure":return{phase:e,reactLargeComponentPressure:{count:0,loc:0,files:[]}};case"vue-component-duplicates":return{phase:e,vueComponentDuplicates:{count:0,loc:0,files:[]}};case"vue-composable-candidates":return{phase:e,vueComposableCandidates:{count:0,loc:0,files:[]}};case"vue-large-view-pressure":return{phase:e,vueLargeViewPressure:{count:0,loc:0,files:[]}};default:throw new Error(`Health phase "${e}" cannot be synthesized.`)}}function eA(e,t){if(e.length===1)return tA(e[0],t).then(o=>[o]);let n=e.join(","),r=process.argv[1]??xl(import.meta.url),i=[n];return t.scope&&i.push("--scope",t.scope),t.full&&i.push("--full"),Cl({cliPath:r,command:Bi,args:i,label:`Health phases "${n}"`})}function tA(e,t){let n=process.argv[1]??xl(import.meta.url),r=[e];return t.scope&&r.push("--scope",t.scope),t.full&&r.push("--full"),Cl({cliPath:n,command:Bi,args:r,label:`Health phase "${e}"`})}function Cl(e){return new Promise((t,n)=>{let r=e.maxBuffer??WF,i=FF(process.execPath,[...process.execArgv,e.cliPath,e.command,...e.args??[]],{cwd:process.cwd(),env:e.env??process.env,stdio:["ignore","pipe","pipe"]}),o=[],s=[],a=0,c=0,l=!1,u=d=>{l||(l=!0,i.kill(),n(d))};i.stdout.on("data",d=>{if(a+=d.length,a>r){u(new Error(`${e.label} exceeded stdout buffer limit (${r} bytes).`));return}o.push(d)}),i.stderr.on("data",d=>{if(c+=d.length,c>r){u(new Error(`${e.label} exceeded stderr buffer limit (${r} bytes).`));return}s.push(d)}),i.on("error",u),i.on("close",d=>{if(l)return;l=!0;let m=Buffer.concat(s).toString("utf8").trim();if(d!==0){n(new Error(`${e.label} failed${m?`:
772
- ${m}`:""}`));return}try{t(JSON.parse(Buffer.concat(o).toString("utf8")))}catch(p){n(new Error(`${e.label} returned invalid JSON: ${p instanceof Error?p.message:p}`))}})})}async function yg(e,t,n){let r=new Array(e.length),i=0;async function o(){for(;i<e.length;){let s=i++;r[s]=await n(e[s])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),r}var nA=xg({envKey:"SCIP_QUERY_HEALTH_CONCURRENCY",defaultMinimum:qF,defaultMaximum:UF});function bg(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(console.log(`
792
+ `;function Xh(e,t,n){let i=ij(t,n);if(!i)return!1;try{return e.ignores(i)}catch{return!1}}function ij(e,t){if(!t||t===".")return null;if(!Jh(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let n=Jh(t)?t:ej(e,t),i=Z$(e,n).replaceAll("\\","/");return!i||i==="."||i.startsWith("..")?null:i}import{readFileSync as rj,writeFileSync as Zh,existsSync as Qi,mkdirSync as oj}from"fs";import{isAbsolute as Qh,join as At,relative as Yh,resolve as Zs}from"path";import{createHash as sj}from"crypto";import{homedir as aj}from"os";var co=".scipquery.json",cj={enabled:!1,debounceMs:3e4,cooldownMs:6e4,gitPollMs:2e3,autoRefresh:!0,ignore:[]},lj=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php","clojure"];function Ue(e){let t=At(e,co);if(!Qi(t))return{};try{let n=rj(t,"utf-8");return JSON.parse(n)}catch(n){let i=n instanceof Error?n.message:String(n);throw n instanceof SyntaxError?new Error(`invalid ${co} at ${t}: ${i}`,{cause:n}):new Error(`unable to read ${co} at ${t}: ${i}`,{cause:n})}}function Yi(e,t={}){let n=[],i=new Set(lj);for(let[a,c]of(e.languages??[]).entries())i.has(c)||n.push({level:"error",path:`languages[${a}]`,message:`Unsupported language: ${c}`});e.indexerConcurrency!==void 0&&(!Number.isInteger(e.indexerConcurrency)||e.indexerConcurrency<=0)&&n.push({level:"error",path:"indexerConcurrency",message:"Must be a positive integer."}),e.watch?.debounceMs!==void 0&&e.watch.debounceMs<=0&&n.push({level:"error",path:"watch.debounceMs",message:"Must be greater than 0."}),e.watch?.cooldownMs!==void 0&&e.watch.cooldownMs<=0&&n.push({level:"error",path:"watch.cooldownMs",message:"Must be greater than 0."}),e.watch?.gitPollMs!==void 0&&e.watch.gitPollMs<=0&&n.push({level:"error",path:"watch.gitPollMs",message:"Must be greater than 0."}),e.watch?.autoRefresh!==void 0&&typeof e.watch.autoRefresh!="boolean"&&n.push({level:"error",path:"watch.autoRefresh",message:"Must be a boolean."});let r=e.indexer?.typescript;if(r?.projectMode!==void 0&&r.projectMode!=="single"&&r.projectMode!=="workspace"&&n.push({level:"error",path:"indexer.typescript.projectMode",message:'Must be "single" or "workspace".'}),r?.projects!==void 0)if(!Array.isArray(r.projects))n.push({level:"error",path:"indexer.typescript.projects",message:"Must be an array."});else for(let[a,c]of r.projects.entries()){let l=`indexer.typescript.projects[${a}]`;if(typeof c!="string"||c.trim()==="")n.push({level:"error",path:l,message:"Project path must be a non-empty string."});else if(t.projectRoot){let d=Zs(t.projectRoot,c),u=Yh(t.projectRoot,d);u.startsWith("..")||Qh(u)?n.push({level:"error",path:l,message:"Project path must stay inside the project root."}):Qi(d)||n.push({level:"warning",path:l,message:`TypeScript project path does not exist: ${c}`})}}r?.projectMode==="workspace"&&r.pnpmWorkspaces===!0&&n.push({level:"warning",path:"indexer.typescript.pnpmWorkspaces",message:'Ignored when projectMode is "workspace"; explicit TypeScript projects are indexed directly.'});let o=e.indexer?.clojure;if(o?.configPath!==void 0){let a="indexer.clojure.configPath";if(typeof o.configPath!="string"||o.configPath.trim()==="")n.push({level:"error",path:a,message:"Config path must be a non-empty string."});else if(t.projectRoot){let c=Zs(t.projectRoot,o.configPath),l=Yh(t.projectRoot,c);l.startsWith("..")||Qh(l)?n.push({level:"error",path:a,message:"Config path must stay inside the project root."}):Qi(c)||n.push({level:"warning",path:a,message:`Clojure indexer config path does not exist: ${o.configPath}`})}}if(e.locality!==void 0)if(!dj(e.locality))n.push({level:"error",path:"locality",message:"Must be an object."});else{let a=e.locality.architecturalBoundarySegments;if(a!==void 0)if(!Array.isArray(a))n.push({level:"error",path:"locality.architecturalBoundarySegments",message:"Must be an array."});else for(let[c,l]of a.entries()){let d=`locality.architecturalBoundarySegments[${c}]`;typeof l!="string"||l.trim()===""?n.push({level:"error",path:d,message:"Boundary segment must be a non-empty string."}):(l.includes("/")||l.includes("\\"))&&n.push({level:"error",path:d,message:"Boundary segment must be a single folder name, not a path."})}}if(e.declaredCouplings!==void 0&&!Array.isArray(e.declaredCouplings))n.push({level:"error",path:"declaredCouplings",message:"Must be an array."});else for(let[a,c]of(e.declaredCouplings??[]).entries()){let l=`declaredCouplings[${a}]`;if((!c.name||c.name.trim()==="")&&n.push({level:"error",path:`${l}.name`,message:"Declared coupling name is required."}),!Array.isArray(c.files)||c.files.length<2)n.push({level:"error",path:`${l}.files`,message:"Declared coupling needs at least two files."});else for(let[d,u]of c.files.entries())!u||u.trim()===""?n.push({level:"error",path:`${l}.files[${d}]`,message:"Declared coupling file path is required."}):t.projectRoot&&!Qi(At(t.projectRoot,u))&&n.push({level:"warning",path:`${l}.files[${d}]`,message:`Declared coupling file does not exist: ${u}`});c.reason!==void 0&&c.reason.trim()===""&&n.push({level:"error",path:`${l}.reason`,message:"Declared coupling reason cannot be blank."})}let s=t.now??new Date;for(let[a,c]of(e.suppressions??[]).entries()){let l=`suppressions[${a}]`;if((!c.reason||c.reason.trim()==="")&&n.push({level:"error",path:`${l}.reason`,message:"Suppression reason is required."}),!c.id&&!c.check&&n.push({level:"error",path:l,message:"Suppression must include id or check."}),c.file!==void 0&&(c.file.trim()===""?n.push({level:"error",path:`${l}.file`,message:"Suppression file path cannot be blank."}):t.projectRoot&&!Qi(At(t.projectRoot,c.file))&&n.push({level:"warning",path:`${l}.file`,message:`Suppression file does not exist: ${c.file}`})),c.expiresAt){let d=Date.parse(c.expiresAt);Number.isNaN(d)?n.push({level:"error",path:`${l}.expiresAt`,message:"Must be an ISO date string."}):d<=s.getTime()&&n.push({level:"warning",path:`${l}.expiresAt`,message:"Suppression has expired."})}}return n}function Zi(e){return{...cj,...e.watch}}function uj(e,t){let n=process.env.SCIP_QUERY_CACHE_DIR;if(n)return pu(n);if(t?.dbPath)return pu(Zs(e,t.dbPath));let r=process.env.XDG_CACHE_HOME||At(aj(),".cache"),o=sj("sha256").update(Zs(e)).digest("hex").slice(0,12),s=At(r,"scip-query","projects",o);return pu(s)}function Mt(e,t){let n=uj(e,t);return{cacheDir:n,dbPath:At(n,"index.db"),indexPath:At(n,"index.scip"),metaPath:At(n,"meta.json")}}function ey(e,t){let n=At(e,co);return Qi(n)||Zh(n,JSON.stringify({languages:t,watch:{enabled:!1,debounceMs:3e4,cooldownMs:6e4,gitPollMs:2e3,autoRefresh:!0}},null,2)+`
793
+ `),n}function ty(e,t){let n=At(e,co),i=Ue(e),r={...i,suppressions:[...i.suppressions??[],t]},o=Yi(r,{projectRoot:e}).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 Zh(n,JSON.stringify(r,null,2)+`
794
+ `),{path:n,suppressionCount:r.suppressions?.length??0}}function pu(e){return oj(e,{recursive:!0}),e}function dj(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ne(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}function ai(e=Ne()){let t=Ue(e),n=Mt(e,t),i=process.env.SCIP_QUERY_INDEX_DB??(ny(n.dbPath)?n.dbPath:mj(e,"index.db"));return{projectRoot:e,config:t,paths:n,dbPath:i}}function er(e){return ai(e).dbPath}function pj(){let{projectRoot:e,config:t,paths:n,dbPath:i}=ai();ny(i)||(console.error("error: No index.db found. Run: scip-query reindex"),process.exit(1));let r={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??n.indexPath,projectRoot:e,entryRoots:t.entryRoots,semantic:t.semantic,suppressions:t.suppressions,declaredCouplings:t.declaredCouplings,locality:t.locality},o=Cn(e);return new Xi(r,o)}function ut(e){let t=pj();try{return e(t)}finally{t.close()}}function fu(e,t){return t.concat([e])}function ci(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 iy(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 fj(e)}}function fj(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}import{spawn as gj,spawnSync as oee}from"child_process";function ry(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}function ea(e){return new Promise((t,n)=>{let i=e.maxBuffer??10485760,r=gj(process.execPath,[...process.execArgv,e.cliPath,e.command,...e.args??[]],{cwd:process.cwd(),env:e.env??process.env,stdio:["ignore","pipe","pipe"]}),o=[],s=[],a=0,c=0,l=!1,d=u=>{l||(l=!0,r.kill(),n(u))};r.stdout.on("data",u=>{if(a+=u.length,a>i){d(new Error(`${e.label} exceeded stdout buffer limit (${i} bytes).`));return}o.push(u)}),r.stderr.on("data",u=>{if(c+=u.length,c>i){d(new Error(`${e.label} exceeded stderr buffer limit (${i} bytes).`));return}s.push(u)}),r.on("error",d),r.on("close",u=>{if(l)return;l=!0;let m=Buffer.concat(s).toString("utf8").trim();if(u!==0){n(new Error(`${e.label} failed${m?`:
795
+ ${m}`:""}`));return}try{t(JSON.parse(Buffer.concat(o).toString("utf8")))}catch(p){n(new Error(`${e.label} returned invalid JSON: ${p instanceof Error?p.message:p}`))}})})}async function gu(e,t,n){let i=new Array(e.length),r=0;async function o(){for(;r<e.length;){let s=r++;i[s]=await n(e[s])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),i}function oy(e,t){let n=new Set,i=[];for(let r of e){if(n.has(r))continue;let o=t.find(a=>a.has(r));if(!o){n.add(r),i.push([r]);continue}let s=e.filter(a=>o.has(a));s.forEach(a=>n.add(a)),i.push(s)}return i}function Qe(e){return e+1}function _e(e,t){return`${Qe(e)}-${Qe(t)}`}function Fe(e,t,n){return`${e}:${_e(t,n)}`}function ta(e,t=180){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var N={empty(e){console.log(e)},list(e,t){for(let n of e)console.log(t(n))},groupedByFile(e,t,n=i=>i.relativePath){let i="";for(let r of e){let o=n(r);o!==i&&(i&&console.log(""),console.log(o),i=o),console.log(t(r))}},sectionedReport(e){let t=!0;for(let n of e)if(!(n.skipIfEmpty&&n.rows.length===0)){t||console.log(""),t=!1,n.title!==void 0&&console.log(`\u2550\u2550\u2550 ${n.title} \u2550\u2550\u2550`),n.explanation!==void 0&&console.log(n.explanation);for(let i of n.rows)console.log(i)}},table(e,t,n){console.log(` ${e.join(" ")}`);let i=n??e.map(r=>r.length);console.log(` ${i.map(r=>"\u2500".repeat(r)).join(" ")}`);for(let r of t)console.log(r)}};var bj=hj(import.meta.url),{version:na}=Lj(),lo="__health-phase",ia="__diff-impact-batch",Sj=10,xj=4,Cj=8,vj=25e3,Rj=2500,sy=2500,kj=4,wj=12,ay=new Set(["react-component-duplicates","react-hook-candidates","react-large-component-pressure"]),cy=new Set(["vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure"]),Pj=new Set([...cy,"suppressions"]),Ij=new Set(["similar","extract-candidates"]);function Lj(){for(let e of["../package.json","../../package.json"])try{return bj(e)}catch{}return{version:"0.0.0"}}function tr(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
796
+ `)}function Dj(e){let t=We(e);return t.symbols>=vj||t.documents>=Rj}function ra(e,t,n,i={}){return Dj(e)?n?(i.quiet||console.error(`Large index detected; ${t} is running the unbounded semantic pass because --full was supplied.`),{semantic:!0}):(i.quiet||console.error(`Large index detected; ${t} will scan the highest-priority ${sy} candidates with semantic enrichment disabled. Run "scip-query ${t} --full" for the unbounded semantic pass.`),{scanLimit:sy,semantic:!1}):{semantic:!0}}async function oa(e){let{applicability:t,overview:n}=ut(a=>({applicability:Ej(a,e),overview:ao(a,"overview",e)})),i=new Map;i.set("overview",n);let r=Ji.filter(a=>a==="overview"?!1:Nj(a,t)?!0:(i.set(a,Tj(a)),!1)),o=Fj(r);return(await gu(o,Mj(o.length),a=>_j(a,e))).flat().forEach(a=>i.set(a.phase,a)),eu(Ji.map(a=>i.get(a)))}function Ej(e,t){return $o(e,{scope:t.scope})}function Nj(e,t){return ay.has(e)?t.react:cy.has(e)?t.vue:!0}function Fj(e){return oy(e,[ay,Pj,Ij])}function Tj(e){switch(e){case"react-component-duplicates":return{phase:e,reactComponentDuplicates:{count:0,loc:0,files:[]}};case"react-hook-candidates":return{phase:e,reactHookCandidates:{count:0,loc:0,files:[]}};case"react-large-component-pressure":return{phase:e,reactLargeComponentPressure:{count:0,loc:0,files:[]}};case"vue-component-duplicates":return{phase:e,vueComponentDuplicates:{count:0,loc:0,files:[]}};case"vue-composable-candidates":return{phase:e,vueComposableCandidates:{count:0,loc:0,files:[]}};case"vue-large-view-pressure":return{phase:e,vueLargeViewPressure:{count:0,loc:0,files:[]}};default:throw new Error(`Health phase "${e}" cannot be synthesized.`)}}function _j(e,t){if(e.length===1)return Aj(e[0],t).then(o=>[o]);let n=e.join(","),i=process.argv[1]??yu(import.meta.url),r=[n];return t.scope&&r.push("--scope",t.scope),t.full&&r.push("--full"),ea({cliPath:i,command:lo,args:r,label:`Health phases "${n}"`})}function Aj(e,t){let n=process.argv[1]??yu(import.meta.url),i=[e];return t.scope&&i.push("--scope",t.scope),t.full&&i.push("--full"),ea({cliPath:n,command:lo,args:i,label:`Health phase "${e}"`})}var Mj=dy({envKey:"SCIP_QUERY_HEALTH_CONCURRENCY",defaultMinimum:kj,defaultMaximum:wj});function ly(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(console.log(`
773
797
  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)
774
- `),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${Vn(e.overview.indexSizeBytes)}
775
- `),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: ${Sl(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: ${Sl(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: ${Sl(n.wrappers,n.wrapperScoreCount)}`),n.passthroughs>0&&console.log(` Passthroughs: ${n.passthroughs}`),n.staleTypes>0&&console.log(` Stale abstractions: ${n.staleTypes}`),n.driftedFiles>0&&console.log(` Pattern drift: ${n.driftedFiles} files`),n.complexityHotspotCount>0&&console.log(` Complexity hotspots: ${n.complexityHotspotCount}`),e.actions.length>0){console.log(`
776
- 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(`
777
- Top Complexity Hotspots:`);for(let r of e.topComplexity)console.log(` ${r.score.toFixed(1).padStart(6)} ${r.symbol}`)}if(oA(e),iA(e),e.scoreBreakdown.length>0){console.log(`
778
- 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(`
779
- No issues found. Codebase is clean.`)}function Sl(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${rA(t)} score-weighted)`}function rA(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function iA(e){if(e.pressure.length!==0){console.log(`
780
- 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 oA(e){let t=e.axes;if(console.log(`
781
- 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})`)}}async function Sg(e){let t=et(i=>{let o=bt(i,{base:e.base});return o.note?{kind:"complete",result:Dr(i,{base:e.base})}:o.changedFiles.length===0?{kind:"complete",result:Dr(i,{base:e.base})}:{kind:"batched",plan:o}});if(t.kind==="complete")return t.result;let n=pg(t.plan.changedFiles,OF),r=await yg(n,sA(n.length),i=>lA(i,e));return os(t.plan.changedFiles,r)}var sA=xg({envKey:"SCIP_QUERY_DIFF_IMPACT_CONCURRENCY",defaultMinimum:jF,defaultMaximum:BF});function xg(e){return(t,n=process.env,r=$F)=>aA(t,n,r,e)}function aA(e,t,n,r){let i=t[r.envKey],o=cA(n,r),s=i?parseInt(i,10):o;return!Number.isFinite(s)||s<1?Math.min(o,e):Math.min(s,e)}function cA(e,t){let n=e(),r=Number.isFinite(n)?Math.max(t.defaultMinimum,n-1):0;return Math.min(t.defaultMaximum,Math.max(t.defaultMinimum,r))}function lA(e,t){let n=process.argv[1]??xl(import.meta.url),r=[];return t.base&&r.push("--base",t.base),Cl({cliPath:n,command:Is,args:r,env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch"})}function Cg(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:"),N.list(e.changedSymbols,t=>` ${t.file} ${t.shortName} (fan-in: ${t.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
782
- Affected consumer files:`),N.list(e.affectedConsumers,t=>` ${t.file} (${t.consumedSymbols} symbol(s))`))}var Hi=bl,k=(e=>parseInt(e,10)),Vi=(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,Ns=parseInt;function f(e,t,n,...r){return r.length>0?{flags:e,description:t,parser:n,defaultValue:r[0]}:{flags:e,description:t,parser:n}}function vl(){return f("--json","Output as JSON for programmatic consumption")}function A(e=[]){return e.some(t=>t.flags==="--json")?e:[...e,vl()]}function I(e,t=[]){return{category:e,examples:t}}import{execFileSync as tj}from"child_process";import{existsSync as Qi,mkdirSync as nj,readFileSync as rj,writeFileSync as Kh}from"fs";import{homedir as ij}from"os";import{dirname as oj,join as qr}from"path";import{execFileSync as zM}from"child_process";import{closeSync as JM,copyFileSync as KM,existsSync as Bs,mkdirSync as ql,mkdtempSync as XM,openSync as QM,readFileSync as Hs,renameSync as Wi,rmSync as Gi,writeFileSync as vh}from"fs";import{basename as js,dirname as dt,extname as YM,join as Rt}from"path";import{execFileSync as vg}from"child_process";import{existsSync as kg,readFileSync as pA}from"fs";import{platform as qi,arch as wg}from"os";import{dirname as Rg,join as Es}from"path";import{fileURLToPath as fA}from"url";import{execFileSync as uA}from"child_process";import{platform as dA}from"os";var mA=dA()==="win32";function vt(e){let t=mA?"where":"which";try{return uA(t,[e],{stdio:"pipe"}),!0}catch{return!1}}var Lg="v0.8.1",Rl="https://github.com/scip-code/scip",gA={win32:{x64:Es("vendor","scip","win32-x64","scip.exe"),arm64:Es("vendor","scip","win32-arm64","scip.exe")}};function hA(){let e=Rg(fA(import.meta.url));for(;;){let t=Es(e,"package.json");if(kg(t))try{if(JSON.parse(pA(t,"utf-8")).name==="scip-query")return e}catch{}let n=Rg(e);if(n===e)return null;e=n}}function Ig(){let e=gA[qi()]?.[wg()];if(!e)return null;let t=hA();if(!t)return null;let n=Es(t,e);return kg(n)?n:null}function Ts(){return vt("scip")?"scip":Ig()}function Ui(){return Ts()!==null}function yA(){let e=qi(),t=wg(),n,r,i;switch(e){case"darwin":n="darwin",i="tar.gz";break;case"linux":n="linux",i="tar.gz";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:`${Rl}/releases/download/${Lg}/${o}`,filename:o}}function kl(){let e=yA();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),qi()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
783
- `),console.log("Or download manually:")):qi()==="win32"?(console.log("Windows installs should include a managed scip.exe in the scip-query package."),console.log("Reinstall scip-query, or build the managed binary from source with:"),console.log(` npm run build:scip-windows
798
+ `),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${ci(e.overview.indexSizeBytes)}
799
+ `),e.warnings&&e.warnings.length>0){console.log(" Warnings:");for(let i of e.warnings)console.log(` ${i}`);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: ${hu(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: ${hu(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: ${hu(n.wrappers,n.wrapperScoreCount)}`),n.passthroughs>0&&console.log(` Passthroughs: ${n.passthroughs}`),n.staleTypes>0&&console.log(` Stale abstractions: ${n.staleTypes}`),n.driftedFiles>0&&console.log(` Pattern drift: ${n.driftedFiles} files`),n.complexityHotspotCount>0&&console.log(` Complexity hotspots: ${n.complexityHotspotCount}`),e.actions.length>0){console.log(`
800
+ Prioritized Actions (highest impact + lowest effort first):`);for(let i=0;i<e.actions.length;i++){let r=e.actions[i],o=r.locRecoverable>0?` (~${r.locRecoverable} LOC recoverable)`:"";console.log(` ${i+1}. [${r.effort} effort / ${r.impact} impact] ${r.description}${o}`)}}if(e.topComplexity.length>0){console.log(`
801
+ Top Complexity Hotspots:`);for(let i of e.topComplexity)console.log(` ${i.score.toFixed(1).padStart(6)} ${i.symbol}`)}if(Oj(e),jj(e),e.scoreBreakdown.length>0){console.log(`
802
+ Score Breakdown (100 minus the following):`);for(let i of e.scoreBreakdown)console.log(` -${String(i.points).padStart(2)} ${i.axis}: ${i.detail}`)}e.actions.length===0&&console.log(`
803
+ No issues found. Codebase is clean.`)}function hu(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${$j(t)} score-weighted)`}function $j(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function jj(e){if(e.pressure.length!==0){console.log(`
804
+ 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 Oj(e){let t=e.axes;if(console.log(`
805
+ Axes:`),console.log(` Deletable: ${t.deletable.loc} LOC across ${t.deletable.symbols} symbols`),t.changeAmplification){let i=t.changeAmplification;console.log(` Change amplification: ${i.medianFilesPerCommit} files/commit median, ${i.p90FilesPerCommit} p90 (${i.commitsAnalyzed} commits)`)}if(t.hiddenCoupling&&t.hiddenCoupling.pairCount>0){console.log(` Hidden coupling: ${t.hiddenCoupling.pairCount} co-changing pair(s) without a dependency edge`);for(let i of t.hiddenCoupling.top.slice(0,3))console.log(` ${i.fileA} <-> ${i.fileB} (${i.together}x together, ${Math.round(i.confidence*100)}%)`)}if(t.churnWeightedComplexity&&t.churnWeightedComplexity.length>0){let i=t.churnWeightedComplexity[0];i.weighted>0&&console.log(` Churn x complexity: hottest is ${i.symbol} (${i.changes} changes, weighted ${i.weighted})`)}let n=t.evidenceQuality;if(console.log(` Evidence quality: ${n.graphFindings} graph-fact finding(s), ${n.heuristicFindings} heuristic finding(s), ${n.userSuppressed} user-suppressed`),e.validation&&e.validation.flaggedFiles>0){let i=e.validation,r=i.ratio===null?"n/a":`${i.ratio}x`;console.log(` Validation: flagged files fix-density ${i.flaggedFixDensity} vs baseline ${i.baselineFixDensity} (${r})`)}}async function uy(e){let t=ut(r=>{let o=Tt(r,{base:e.base});return o.note?{kind:"complete",result:Ui(r,{base:e.base})}:o.changedFiles.length===0?{kind:"complete",result:Ui(r,{base:e.base})}:{kind:"batched",plan:o}});if(t.kind==="complete")return t.result;let n=ry(t.plan.changedFiles,Sj),i=await gu(n,Bj(n.length),r=>qj(r,e));return _s(t.plan.changedFiles,i)}var Bj=dy({envKey:"SCIP_QUERY_DIFF_IMPACT_CONCURRENCY",defaultMinimum:xj,defaultMaximum:Cj});function dy(e){return(t,n=process.env,i=yj)=>Hj(t,n,i,e)}function Hj(e,t,n,i){let r=t[i.envKey],o=Vj(n,i),s=r?parseInt(r,10):o;return!Number.isFinite(s)||s<1?Math.min(o,e):Math.min(s,e)}function Vj(e,t){let n=e(),i=Number.isFinite(n)?Math.max(t.defaultMinimum,n-1):0;return Math.min(t.defaultMaximum,Math.max(t.defaultMinimum,i))}function qj(e,t){let n=process.argv[1]??yu(import.meta.url),i=[];return t.base&&i.push("--base",t.base),ea({cliPath:n,command:ia,args:i,env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch"})}function my(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:"),N.list(e.changedSymbols,t=>` ${t.file} ${t.shortName} (fan-in: ${t.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
806
+ Affected consumer files:`),N.list(e.affectedConsumers,t=>` ${t.file} (${t.consumedSymbols} symbol(s))`))}var uo=fu,I=(e=>parseInt(e,10)),mo=(e=>{let t=parseInt(e,10);if(!Number.isFinite(t)||t<1)throw new Error(`Expected a positive integer, got ${e}`);return t}),xt=parseFloat,sa=parseInt;function h(e,t,n,...i){return i.length>0?{flags:e,description:t,parser:n,defaultValue:i[0]}:{flags:e,description:t,parser:n}}function bu(){return h("--json","Output as JSON for programmatic consumption")}function j(e=[]){return e.some(t=>t.flags==="--json")?e:[...e,bu()]}function E(e,t=[]){return{category:e,examples:t}}import{execFileSync as HH}from"child_process";import{existsSync as Co,mkdirSync as VH,readFileSync as qH,writeFileSync as Vb}from"fs";import{homedir as UH}from"os";import{dirname as zH,join as ar}from"path";import{execFileSync as E1}from"child_process";import{closeSync as N1,copyFileSync as F1,existsSync as ya,mkdirSync as Ou,mkdtempSync as T1,openSync as _1,readFileSync as ba,renameSync as go,rmSync as ho,writeFileSync as gb}from"fs";import{basename as ha,dirname as Ct,extname as A1,join as jt}from"path";import{execFileSync as py}from"child_process";import{existsSync as gy,readFileSync as Gj}from"fs";import{platform as po,arch as hy}from"os";import{dirname as fy,join as aa}from"path";import{fileURLToPath as Kj}from"url";import{execFileSync as Uj}from"child_process";import{platform as zj}from"os";var Wj=zj()==="win32";function $t(e){let t=Wj?"where":"which";try{return Uj(t,[e],{stdio:"pipe"}),!0}catch{return!1}}var yy="v0.8.1",Su="https://github.com/scip-code/scip",Jj={win32:{x64:aa("vendor","scip","win32-x64","scip.exe"),arm64:aa("vendor","scip","win32-arm64","scip.exe")}};function Xj(){let e=fy(Kj(import.meta.url));for(;;){let t=aa(e,"package.json");if(gy(t))try{if(JSON.parse(Gj(t,"utf-8")).name==="scip-query")return e}catch{}let n=fy(e);if(n===e)return null;e=n}}function by(){let e=Jj[po()]?.[hy()];if(!e)return null;let t=Xj();if(!t)return null;let n=aa(t,e);return gy(n)?n:null}function ca(){return $t("scip")?"scip":by()}function fo(){return ca()!==null}function Qj(){let e=po(),t=hy(),n,i,r;switch(e){case"darwin":n="darwin",r="tar.gz";break;case"linux":n="linux",r="tar.gz";break;default:return null}switch(t){case"arm64":i="arm64";break;case"x64":i="amd64";break;default:return null}let o=`scip-${n}-${i}.${r}`;return{url:`${Su}/releases/download/${yy}/${o}`,filename:o}}function xu(){let e=Qj();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),po()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
807
+ `),console.log("Or download manually:")):po()==="win32"?(console.log("Windows installs should include a managed scip.exe in the scip-query package."),console.log("Reinstall scip-query, or build the managed binary from source with:"),console.log(` npm run build:scip-windows
784
808
  `),console.log("Upstream release page:")):console.log("Download from:"),console.log(e?` ${e.url}
785
- `:` ${Rl}/releases/tag/${Lg}
786
- `),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function Dg(e){let t=Ig();if(t)return e(`Using bundled scip CLI at ${t}`),!0;if(qi()==="darwin"&&vt("brew")){e("Installing scip CLI via Homebrew...");try{if(vg("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),vt("scip"))return e("Successfully installed scip CLI via Homebrew"),!0}catch(n){let r=n instanceof Error?n.message:String(n);e(`Homebrew install failed: ${r}`)}}if(vt("go")){e("Installing scip CLI via go install...");try{if(vg("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),vt("scip"))return e("Successfully installed scip CLI via go install"),!0}catch(n){let r=n instanceof Error?n.message:String(n);e(`go install failed: ${r}`)}}return e("Could not auto-install scip CLI."),e(`Install manually from: ${Rl}/releases`),!1}import bA from"better-sqlite3";import{execFileSync as SA}from"child_process";import{existsSync as xA,readdirSync as CA,readFileSync as vA}from"fs";import{extname as _s,join as Pg}from"path";function on(e){let t=new Set((e.extensions??Uu).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!xA(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=rn(e.projectRoot),r=RA(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new bA(e.dbPath);try{let o=wA(i,r),s=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
787
- VALUES (?, ?, NULL, ?)`),c=i.transaction(u=>{let d=0;for(let m of u){if(o.has(m))continue;let p=vA(Pg(e.projectRoot,m),"utf-8"),g=s.run(LA(m),m,p);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 RA(e,t){let n=kA(e,t);if(n)return n;let r=[],i=o=>{let s=o?Pg(e,o):e,a;try{a=CA(s,{withFileTypes:!0})}catch{return}for(let c of a){if(ha.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(l);continue}t.has(_s(c.name).toLowerCase())&&r.push(l)}};return i(""),r.sort()}function kA(e,t){try{return SA("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
788
- `).filter(r=>r&&t.has(_s(r).toLowerCase())).sort()}catch{return null}}function wA(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 LA(e){return _s(e).toLowerCase()===".vue"?"vue":_s(e).replace(/^\./,"").toLowerCase()||"source"}import{execFileSync as IA}from"child_process";import{existsSync as DA,readdirSync as Eg}from"fs";import{extname as Tg,join as _g}from"path";var PA=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),NA=[{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 At(e){let t=[],n=EA(e),r=AA(e);for(let i of NA){if(TA(e,i.files)){t.push(i.language);continue}if(_A(n,i.globs)){t.push(i.language);continue}MA(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&Ng(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&Ng(t,"c"),t}function EA(e){try{return Eg(e)}catch{return[]}}function TA(e,t){return t?.length?t.some(n=>DA(_g(e,n))):!1}function _A(e,t){return t?.length?e.some(n=>t.some(r=>FA(n,r))):!1}function FA(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 AA(e){let t=$A(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=Eg(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=_g(i,s.name);if(s.isDirectory()){PA.has(s.name)||r.push(a);continue}let c=Tg(s.name).toLowerCase();c&&n.add(c)}}return n}function $A(e){try{let t=IA("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(`
789
- `)){if(!r)continue;let i=Tg(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function MA(e,t){return t?.length?t.some(n=>e.has(n)):!1}function Ng(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{existsSync as Fg,readdirSync as OA}from"fs";import{join as wl}from"path";var jA={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:r})=>{let i=r?["index","--output",e,"--no-progress-bar",r]:["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&!r&&i.splice(1,0,"--pnpm-workspaces"),{binary:n,args:i}},markerFiles:["tsconfig.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--infer-tsconfig","--output",e,"--no-progress-bar"]}),markerFiles:["package.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},java:{language:"java",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["pom.xml","build.gradle"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.sbt"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.gradle.kts"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:"rust",indexerBinary:"rust-analyzer",checkCommand:"rust-analyzer --version",indexArgs:({outputPath:e})=>({binary:"rust-analyzer",args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[{label:"rustup",prerequisite:"rustup",binary:"rustup",args:["component","add","rust-analyzer"]}],installUrl:"https://github.com/rust-lang/rust-analyzer"},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:["pyproject.toml","setup.py"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","scip-python-plus"]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},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",Ag(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",Ag(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=wl(e,"vendor","bin","scip-php"),r=wl(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",Fg(r)?r:Fg(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function qn(e){return jA[e]}function Ag(e,t){let n;try{n=OA(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return wl(e,i);return null}import{readFileSync as BA,writeFileSync as HA}from"fs";import{create as Ll}from"@bufbuild/protobuf";import{deserializeSCIP as VA,serializeSCIP as qA,DocumentSchema as UA,IndexSchema as WA,SymbolInformationSchema as GA}from"@c4312/scip";function zA(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=JA(e),n=KA(e.flatMap(i=>i.documents??[])),r=$g(e.flatMap(i=>i.externalSymbols??[]));return Ll(WA,{metadata:t,documents:n,externalSymbols:r})}function Il(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>VA(BA(i))),r=zA(n);return HA(t,Buffer.from(qA(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function JA(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 KA(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,Ll(UA,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:XA([...r.occurrences,...n.occurrences]),symbols:$g([...r.symbols,...n.symbols]),text:YA(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function XA(e){let t=new Set,n=[];for(let r of e){let i=JSON.stringify(r);t.has(i)||(t.add(i),n.push(r))}return n}function $g(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,Ll(GA,{symbol:r.symbol,documentation:ZA([...r.documentation,...n.documentation]),relationships:QA([...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 QA(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 YA(e,t){return e?t?e.length>=t.length?e:t:e:t}function ZA(e){return[...new Set(e)]}import{execFileSync as e$}from"child_process";import{createHash as t$}from"crypto";import{readdirSync as n$,readFileSync as r$}from"fs";import{join as Og}from"path";function Mg(e){return(o$(e)??s$(e)).filter(t=>t&&!jg(t)).sort()}function Un(e,t={}){return(t.language?Mg(e).filter(r=>i$(r,t.language,t.markerFiles)):Mg(e)).map(r=>{let i=Og(e,r);try{let o=r$(i);return{path:r,size:o.byteLength,hash:t$("sha256").update(o).digest("hex")}}catch{return{path:r,size:-1,hash:"unreadable"}}})}function i$(e,t,n){let r=e.split("/").at(-1)??e;if(n?.includes(e)||n?.includes(r)||c$.has(r))return!0;let i=e.includes(".")?`.${e.split(".").at(-1).toLowerCase()}`:"";return(l$[t]??[]).includes(i)}function o$(e){try{return e$("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:50*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
790
- `).filter(Boolean)}catch{return null}}function s$(e){let t=[],n=[""];for(;n.length>0;){let r=n.pop(),i=r?Og(e,r):e,o;try{o=n$(i,{withFileTypes:!0})}catch{continue}for(let s of o){let a=r?`${r}/${s.name}`:s.name;if(s.isDirectory()){jg(a)||n.push(a);continue}t.push(a)}}return t}function jg(e){return e.split("/").some(n=>a$.has(n))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var a$=new Set([".git","node_modules",".scipquery-cache",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]),c$=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"]),l$={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 u$,writeFileSync as d$}from"fs";import{create as Bg}from"@bufbuild/protobuf";import{deserializeSCIP as m$,DocumentSchema as p$,IndexSchema as f$,serializeSCIP as g$,SymbolRole as h$}from"@c4312/scip";function Hg(e){let t;try{t=m$(u$(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=y$(t);return n.removedDefinitionOccurrences>0&&d$(e,Buffer.from(g$(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function y$(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&h$.Definition)===0||t.has(a.symbol)?!0:(n+=1,!1));if(s.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(Bg(p$,{language:o.language,relativePath:o.relativePath,occurrences:s,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:Bg(f$,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}import{existsSync as b$,readFileSync as S$,readdirSync as x$,statSync as C$}from"fs";import he from"path";var v$=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function Vg(e,t=[]){let n=he.resolve(e),r=R$(n),i=t.flatMap(c=>k$(n,c)),o=L$([...r,...i]),s=I$(n,o)?[n,...o]:o,a=s.length>0?s:[n];return[...new Set(a.map(c=>P$(n,c)))].sort((c,l)=>c.localeCompare(l))}function R$(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=x$(r,{withFileTypes:!0})}catch{continue}for(let o of i){let s=he.join(r,o.name);if(o.isDirectory()){!v$.has(o.name)&&!o.name.startsWith(".")&&n.push(s);continue}o.isFile()&&w$(s)&&t.push(he.dirname(s))}}return t}function k$(e,t){let n=t.trim();if(!n)return[];let r=he.resolve(e,n);if(!E$(e,r))return[];try{let i=C$(r);if(i.isDirectory())return[r];if(i.isFile()&&qg(he.basename(r)))return[he.dirname(r)]}catch{return[]}return[]}function w$(e){if(!qg(he.basename(e)))return!1;let t=Ug(e);return t?he.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function qg(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function L$(e){let t=[...new Set(e.map(n=>he.resolve(n)))].sort((n,r)=>n.localeCompare(r));return t.length<=1?t:t.filter(n=>!t.some(r=>r!==n&&N$(n,r)))}function I$(e,t){if(t.length===0||t.some(r=>he.resolve(r)===e))return!1;let n=he.join(e,"tsconfig.json");return b$(n)&&D$(n)}function D$(e){let n=Ug(e)?.include;return Array.isArray(n)?n.some(r=>typeof r=="string"&&r.trim()!==""&&!r.startsWith("!")&&(r.includes("/")||r.includes("**")||!he.extname(r))):!1}function Ug(e){try{let t=JSON.parse(S$(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function P$(e,t){let n=he.relative(e,t);return n?n.split(he.sep).join("/"):"."}function N$(e,t){let n=he.relative(e,t);return!!n&&!n.startsWith("..")&&!he.isAbsolute(n)}function E$(e,t){let n=he.relative(e,t);return!n.startsWith("..")&&!he.isAbsolute(n)}import{execFile as T$}from"child_process";import{existsSync as Fs,renameSync as Pl,rmSync as Nl}from"fs";import{cpus as _$}from"os";import{join as Wg}from"path";function F$(e,t,n){if(!e.defaultOutputPath)return;let r=Wg(t,e.defaultOutputPath);n!==r&&Fs(r)&&Pl(r,n)}function A$(e,t,n){if(!e.defaultOutputPath)return null;let r=Wg(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Nl(i,{force:!0}),Fs(r)?(Pl(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function $$(e){e&&(Nl(e.defaultOutputPath,{force:!0}),e.backupPath&&Fs(e.backupPath)&&Pl(e.backupPath,e.defaultOutputPath))}function M$(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(8,Math.max(1,_$().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function Gg(e,t,n,r){let i=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=M$(o.length,r),c=await j$(o,a,l=>Dl(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.id===u.id);d&&(n(`Retrying ${d.label} indexer serially after parallel failure...`),l.set(d.id,await Dl(d,t,n)))}s.push(...c.map(u=>l.get(u.id)??u))}else s.push(...c);for(let l of i)s.push(await Dl(l,t,n));return s.sort((l,u)=>e.findIndex(d=>d.id===l.id)-e.findIndex(d=>d.id===u.id))}async function Dl(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Nl(e.scipPath,{force:!0});let r=A$(e.config,t,e.scipPath);try{await O$(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),F$(e.config,t,e.scipPath)}catch(i){let o=i instanceof Error?i.message:String(i),s=`${e.resolvedBinary} indexer failed: ${o.split(`
791
- `)[0]}`,a=e.label===e.language?s:`${e.label}: ${s}`;return n(`Skipping ${e.label}: ${s}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,skipped:{language:e.language,reason:a}}}finally{$$(r)}if(!Fs(e.scipPath)){let i=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,o=e.label===e.language?i:`${e.label}: ${i}`;return n(`Skipping ${e.label}: ${i}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,skipped:{language:e.language,reason:o}}}return{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath}}function O$(e,t,n){return new Promise((r,i)=>{T$(e,[...t],n,o=>{o?i(o):r()})})}async function j$(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 Tl}from"child_process";import{existsSync as El,readFileSync as B$}from"fs";import{createRequire as H$}from"module";import{platform as V$}from"os";import{dirname as zg,join as As}from"path";var q$=H$(import.meta.url);function _l(e){return[e.indexerBinary,...e.binaryAliases??[]]}function $s(e){let t=_l(e);return t.length===1?t[0]:t.join(" or ")}function Br(e){for(let t of _l(e))if(vt(t))return t;return W$(e)}function Jg(e){return Br(e)!==null||U$(e)}function U$(e){return Kg(e)!==null}function W$(e){let t=Kg(e);if(!t)return null;let r=JSON.parse(B$(t,"utf8")).bin;if(!r)return null;if(typeof r=="string")return As(zg(t),r);for(let i of _l(e)){let o=r[i];if(o)return As(zg(t),o)}return null}function Kg(e){if(!e.bundledNpmPackage)return null;try{return q$.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function Fl(e,t){for(let n of e.projectLocalBinaries??[]){let r=As(t,n);if(El(r))return r}return null}function G$(e,t){return Fl(e,t)??Br(e)}function Xg(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||Al(n,t))return t;let r=Qg(n,t);return r?{...t,DOTNET_ROOT:r}:t}function Ms(e,t){let n=$s(e),r=t?G$(e,t):Br(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=z$(r);return{language:e.language,binaryLabel:n,installed:!0,runnable:i.runnable,resolvedBinary:r,installUrl:e.installUrl,note:i.note}}function Os(e,t){let n=e.installMethods,r=$s(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(vt(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{Tl(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env});let o=Br(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 z$(e){if(Al(e,process.env))return{runnable:!0};let t=Qg(e,process.env);if(t)return{runnable:!0,note:`using .NET 9 runtime from ${t}`};let n=Yg(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 Qg(e,t){for(let n of Yg(t))if(Al(e,{...t,DOTNET_ROOT:n}))return n;return null}function Yg(e){let t=[],n=e.DOTNET_ROOT;if(n&&El(n)&&t.push(n),V$()==="darwin"&&vt("brew"))try{let r=Tl("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),i=As(r,"libexec");El(i)&&!t.includes(i)&&t.push(i)}catch{}return t}function Al(e,t){try{return Tl(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}import IM from"better-sqlite3";import{existsSync as DM,readFileSync as PM,writeFileSync as NM}from"fs";import{dirname as EM,join as TM,resolve as _M}from"path";import{readFileSync as J$,rmSync as K$,statSync as X$,mkdtempSync as Q$}from"fs";import{cpus as Y$,tmpdir as Z$}from"os";import{join as $l}from"path";import{Worker as eM}from"worker_threads";function Zg(e){return e.length>=8&&th(e.length)>1}function eh(e){let t=th(e.vueFiles.length),n=nM(e.vueFiles),r=iM(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=Q$($l(Z$(),"scip-query-vue-workers-")),s=new SharedArrayBuffer(4),a=new Int32Array(s),c=tM(),l=Date.now();try{for(let d=0;d<r.length;d++)new eM(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[d],resultPath:$l(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 p=JSON.parse(J$($l(o,`${m}.json`),"utf-8"));if(!p.ok)throw new Error(`Vue reference worker failed: ${p.error}`);return p.result});return{occurrences:u.flatMap(d=>d.occurrences),skippedReferences:u.reduce((d,m)=>d+m.skippedReferences,0)}}finally{K$(o,{recursive:!0,force:!0})}}function th(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,Y$().length-1));return Math.max(1,Math.min(e,n))}function tM(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function nM(e){let t=rM(),n=[];for(let r of e){let i=nh(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 rM(){return Number.POSITIVE_INFINITY}function iM(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:oM(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 oM(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,nh(e.fileName)-e.startOffset)}function nh(e){try{return X$(e).size}catch{return 1}}import{createRequire as sM}from"module";import{existsSync as aM,readFileSync as Ol}from"fs";import{dirname as rh,extname as cM,join as ih,relative as lM,resolve as uM}from"path";import{pathToFileURL as dM}from"url";function mM(e){e.transaction(()=>{e.prepare(`
809
+ `:` ${Su}/releases/tag/${yy}
810
+ `),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function Sy(e){let t=by();if(t)return e(`Using bundled scip CLI at ${t}`),!0;if(po()==="darwin"&&$t("brew")){e("Installing scip CLI via Homebrew...");try{if(py("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),$t("scip"))return e("Successfully installed scip CLI via Homebrew"),!0}catch(n){let i=n instanceof Error?n.message:String(n);e(`Homebrew install failed: ${i}`)}}if($t("go")){e("Installing scip CLI via go install...");try{if(py("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),$t("scip"))return e("Successfully installed scip CLI via go install"),!0}catch(n){let i=n instanceof Error?n.message:String(n);e(`go install failed: ${i}`)}}return e("Could not auto-install scip CLI."),e(`Install manually from: ${Su}/releases`),!1}import Yj from"better-sqlite3";import{execFileSync as Zj}from"child_process";import{existsSync as eO,readdirSync as tO,readFileSync as nO}from"fs";import{extname as la,join as xy}from"path";function nr(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>ua({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function ua(e){let t=new Set((e.extensions??Wd).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!eO(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Cn(e.projectRoot),i=iO(e.projectRoot,t).filter(o=>!n.isIgnored(o)),r=new Yj(e.dbPath);try{let o=oO(r,i),s=r.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
811
+ VALUES (?, ?, NULL, ?)`),c=r.transaction(d=>{let u=0;for(let m of d){if(o.has(m))continue;let p=nO(xy(e.projectRoot,m),"utf-8"),f=s.run(sO(m),m,p);u+=Number(f.changes)}return u})(i),l={scanned:i.length,inserted:c,existing:i.length-c};return e.onStatus?.(`Augmented SQLite documents with ${c} auxiliary source file${c===1?"":"s"} (${l.existing} already present).`),l}finally{r.close()}}function iO(e,t){let n=rO(e,t);if(n)return n;let i=[],r=o=>{let s=o?xy(e,o):e,a;try{a=tO(s,{withFileTypes:!0})}catch{return}for(let c of a){if(Mo.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){r(l);continue}t.has(la(c.name).toLowerCase())&&i.push(l)}};return r(""),i.sort()}function rO(e,t){try{return Zj("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
812
+ `).filter(i=>i&&t.has(la(i).toLowerCase())).sort()}catch{return null}}function oO(e,t){let n=new Set,i=500;for(let r=0;r<t.length;r+=i){let o=t.slice(r,r+i),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 sO(e){return la(e).toLowerCase()===".vue"?"vue":la(e).replace(/^\./,"").toLowerCase()||"source"}import{execFileSync as aO}from"child_process";import{existsSync as cO,readdirSync as vy}from"fs";import{extname as Ry,join as ky}from"path";var lO=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),uO=[{language:"typescript",files:["tsconfig.json","tsconfig.base.json"],extensions:[".ts",".tsx",".mts",".cts"]},{language:"rust",files:["Cargo.toml"],extensions:[".rs"]},{language:"go",files:["go.mod"],extensions:[".go"]},{language:"java",files:["pom.xml","build.gradle","build.gradle.kts"],extensions:[".java"]},{language:"kotlin",files:["build.gradle.kts"],extensions:[".kt",".kts"]},{language:"scala",files:["build.sbt"],extensions:[".scala"]},{language:"clojure",files:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],extensions:[".clj",".cljs",".cljc"]},{language:"python",files:["pyproject.toml","setup.py","setup.cfg","Pipfile"],extensions:[".py",".pyi"]},{language:"ruby",files:["Gemfile"],extensions:[".rb"]},{language:"cpp",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"]},{language:"c",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".c",".h"]},{language:"csharp",globs:["*.csproj","*.sln"],extensions:[".cs"]},{language:"vb",globs:["*.vbproj"],extensions:[".vb"]},{language:"dart",files:["pubspec.yaml"],extensions:[".dart"]},{language:"php",files:["composer.json"],extensions:[".php"]},{language:"javascript",files:["package.json"],extensions:[".js",".jsx",".mjs",".cjs"]}];function tn(e){let t=[],n=dO(e),i=gO(e);for(let r of uO){if(mO(e,r.files)){t.push(r.language);continue}if(pO(n,r.globs)){t.push(r.language);continue}yO(i,r.extensions)&&t.push(r.language)}return t.includes("typescript")&&Cy(t,"javascript"),t.includes("cpp")&&!i.has(".c")&&Cy(t,"c"),t}function dO(e){try{return vy(e)}catch{return[]}}function mO(e,t){return t?.length?t.some(n=>cO(ky(e,n))):!1}function pO(e,t){return t?.length?e.some(n=>t.some(i=>fO(n,i))):!1}function fO(e,t){if(t==="*")return!0;if(!t.includes("*"))return e===t;let[n,i]=t.split("*");return e.startsWith(n??"")&&e.endsWith(i??"")}function gO(e){let t=hO(e);if(t)return t;let n=new Set,i=[e];for(;i.length>0;){let r=i.pop();if(!r)continue;let o;try{o=vy(r,{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=ky(r,s.name);if(s.isDirectory()){lO.has(s.name)||i.push(a);continue}let c=Ry(s.name).toLowerCase();c&&n.add(c)}}return n}function hO(e){try{let t=aO("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}),n=new Set;for(let i of t.split(`
813
+ `)){if(!i)continue;let r=Ry(i).toLowerCase();r&&n.add(r)}return n}catch{return null}}function yO(e,t){return t?.length?t.some(n=>e.has(n)):!1}function Cy(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{existsSync as wy,readdirSync as bO}from"fs";import{isAbsolute as SO,join as Cu,resolve as xO}from"path";var CO={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:i})=>{let r=i?["index","--output",e,"--no-progress-bar",i]:["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&!i&&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"},clojure:{language:"clojure",indexerBinary:"scip-clojure",projectLocalBinaries:["node_modules/.bin/scip-clojure"],checkCommand:"scip-clojure -h",indexArgs:({projectRoot:e,outputPath:t,indexerBinary:n,configPath:i})=>{let r=["-root",e,"-output",t];return i&&r.push("-config",SO(i)?i:xO(e,i)),{binary:n,args:r}},markerFiles:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","scip-clojure"]}],installUrl:"https://github.com/PlunderStruck/scip-clojure"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:["Gemfile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:["go.mod"],installMethods:[{label:"go install",prerequisite:"go",binary:"go",args:["install","github.com/sourcegraph/scip-go@latest"]}],installUrl:"https://github.com/sourcegraph/scip-go"},cpp:{language:"cpp",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Py(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",Py(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=Cu(e,"vendor","bin","scip-php"),i=Cu(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",wy(i)?i:wy(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function li(e){return CO[e]}function Py(e,t){let n;try{n=bO(e)}catch{return null}for(let i of t)for(let r of n)if(r.endsWith(i))return Cu(e,r);return null}import{readFileSync as vO,writeFileSync as RO}from"fs";import{create as vu}from"@bufbuild/protobuf";import{deserializeSCIP as kO,serializeSCIP as wO,DocumentSchema as PO,IndexSchema as IO,SymbolInformationSchema as LO}from"@c4312/scip";function DO(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=EO(e),n=NO(e.flatMap(r=>r.documents??[])),i=Iy(e.flatMap(r=>r.externalSymbols??[]));return vu(IO,{metadata:t,documents:n,externalSymbols:i})}function Ru(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(r=>kO(vO(r))),i=DO(n);return RO(t,Buffer.from(wO(i))),{documentCount:i.documents.length,externalSymbolCount:i.externalSymbols.length,inputCount:e.length}}function EO(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let i of e.slice(1)){let r=i.metadata?.projectRoot;if(n&&r&&r!==n)throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${r}`)}return t}function NO(e){let t=new Map;for(let n of e){let i=t.get(n.relativePath);if(!i){t.set(n.relativePath,n);continue}t.set(n.relativePath,vu(PO,{language:i.language||n.language,relativePath:i.relativePath||n.relativePath,occurrences:FO([...i.occurrences,...n.occurrences]),symbols:Iy([...i.symbols,...n.symbols]),text:_O(i.text,n.text),positionEncoding:i.positionEncoding||n.positionEncoding}))}return[...t.values()]}function FO(e){let t=new Set,n=[];for(let i of e){let r=JSON.stringify(i);t.has(r)||(t.add(r),n.push(i))}return n}function Iy(e){let t=new Map;for(let n of e){let i=t.get(n.symbol);if(!i){t.set(n.symbol,n);continue}t.set(n.symbol,vu(LO,{symbol:i.symbol,documentation:AO([...i.documentation,...n.documentation]),relationships:TO([...i.relationships,...n.relationships]),kind:i.kind||n.kind,displayName:i.displayName||n.displayName,enclosingSymbol:i.enclosingSymbol||n.enclosingSymbol,signatureDocumentation:i.signatureDocumentation??n.signatureDocumentation}))}return[...t.values()]}function TO(e){let t=new Set,n=[];for(let i of e){let r=[i.symbol,i.isReference?"1":"0",i.isImplementation?"1":"0",i.isTypeDefinition?"1":"0",i.isDefinition?"1":"0"].join("|");t.has(r)||(t.add(r),n.push(i))}return n}function _O(e,t){return e?t?e.length>=t.length?e:t:e:t}function AO(e){return[...new Set(e)]}import{readFileSync as MO,writeFileSync as $O}from"fs";function ir(e,t){let n=Date.now(),i=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:Date.now()-n,result:i}}function Dy(e){let t=e.readFingerprint(),n=jO(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let i=e.compute();return OO(e.cachePath,e.readFingerprint(),i),i}function jO(e,t){try{let n=JSON.parse(MO(e,"utf-8"));return Ly(n.fingerprint)===Ly(t)?{result:n.result}:null}catch{return null}}function OO(e,t,n){$O(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
814
+ `)}function Ly(e){return JSON.stringify(e)}import{execFileSync as BO}from"child_process";import{createHash as HO}from"crypto";import{readdirSync as VO,readFileSync as qO}from"fs";import{join as Ny}from"path";function Ey(e){return(zO(e)??WO(e)).filter(t=>t&&!Fy(t)).sort()}function ui(e,t={}){return(t.language?Ey(e).filter(i=>UO(i,t.language,t.markerFiles)):Ey(e)).map(i=>{let r=Ny(e,i);try{let o=qO(r);return{path:i,size:o.byteLength,hash:HO("sha256").update(o).digest("hex")}}catch{return{path:i,size:-1,hash:"unreadable"}}})}function UO(e,t,n){let i=e.split("/").at(-1)??e;if(n?.includes(e)||n?.includes(i)||KO.has(i))return!0;let r=e.includes(".")?`.${e.split(".").at(-1).toLowerCase()}`:"";return(JO[t]??[]).includes(r)}function zO(e){try{return BO("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:50*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
815
+ `).filter(Boolean)}catch{return null}}function WO(e){let t=[],n=[""];for(;n.length>0;){let i=n.pop(),r=i?Ny(e,i):e,o;try{o=VO(r,{withFileTypes:!0})}catch{continue}for(let s of o){let a=i?`${i}/${s.name}`:s.name;if(s.isDirectory()){Fy(a)||n.push(a);continue}t.push(a)}}return t}function Fy(e){let t=e.split("/");return e==="meta.json"||t.some(n=>GO.has(n))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var GO=new Set([".git","node_modules",".scipquery-cache",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]),KO=new Set(["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","bun.lockb","tsconfig.json","tsconfig.base.json","pyproject.toml","setup.py","setup.cfg","Cargo.toml","Cargo.lock","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","build.sbt","compile_commands.json","CMakeLists.txt","Makefile","Gemfile","Gemfile.lock","composer.json","composer.lock","pubspec.yaml","pubspec.lock","deps.edn","project.clj","bb.edn","shadow-cljs.edn"]),JO={typescript:[".ts",".tsx",".mts",".cts"],javascript:[".js",".jsx",".mjs",".cjs"],java:[".java"],scala:[".scala"],kotlin:[".kt",".kts"],rust:[".rs"],python:[".py",".pyi"],ruby:[".rb"],go:[".go"],cpp:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"],c:[".c",".h"],csharp:[".cs"],vb:[".vb"],dart:[".dart"],php:[".php"],clojure:[".clj",".cljs",".cljc"]};import{readFileSync as XO,writeFileSync as QO}from"fs";import{create as Ty}from"@bufbuild/protobuf";import{deserializeSCIP as YO,DocumentSchema as ZO,IndexSchema as eB,serializeSCIP as tB,SymbolRole as nB}from"@c4312/scip";function _y(e){let t;try{t=YO(XO(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=iB(t);return n.removedDefinitionOccurrences>0&&QO(e,Buffer.from(tB(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function iB(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,i=0,r=[];for(let o of e.documents){let s=o.occurrences.filter(a=>(a.symbolRoles&nB.Definition)===0||t.has(a.symbol)?!0:(n+=1,!1));if(s.length===o.occurrences.length){r.push(o);continue}i+=1,r.push(Ty(ZO,{language:o.language,relativePath:o.relativePath,occurrences:s,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:Ty(eB,{metadata:e.metadata,documents:r,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:i}}import{existsSync as rB,readFileSync as oB,readdirSync as sB,statSync as aB}from"fs";import Re from"path";var cB=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function Ay(e,t=[]){let n=Re.resolve(e),i=lB(n),r=t.flatMap(c=>uB(n,c)),o=mB([...i,...r]),s=pB(n,o)?[n,...o]:o,a=s.length>0?s:[n];return[...new Set(a.map(c=>gB(n,c)))].sort((c,l)=>c.localeCompare(l))}function lB(e){let t=[],n=[e];for(;n.length>0;){let i=n.pop(),r;try{r=sB(i,{withFileTypes:!0})}catch{continue}for(let o of r){let s=Re.join(i,o.name);if(o.isDirectory()){!cB.has(o.name)&&!o.name.startsWith(".")&&n.push(s);continue}o.isFile()&&dB(s)&&t.push(Re.dirname(s))}}return t}function uB(e,t){let n=t.trim();if(!n)return[];let i=Re.resolve(e,n);if(!yB(e,i))return[];try{let r=aB(i);if(r.isDirectory())return[i];if(r.isFile()&&My(Re.basename(i)))return[Re.dirname(i)]}catch{return[]}return[]}function dB(e){if(!My(Re.basename(e)))return!1;let t=$y(e);return t?Re.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function My(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function mB(e){let t=[...new Set(e.map(n=>Re.resolve(n)))].sort((n,i)=>n.localeCompare(i));return t.length<=1?t:t.filter(n=>!t.some(i=>i!==n&&hB(n,i)))}function pB(e,t){if(t.length===0||t.some(i=>Re.resolve(i)===e))return!1;let n=Re.join(e,"tsconfig.json");return rB(n)&&fB(n)}function fB(e){let n=$y(e)?.include;return Array.isArray(n)?n.some(i=>typeof i=="string"&&i.trim()!==""&&!i.startsWith("!")&&(i.includes("/")||i.includes("**")||!Re.extname(i))):!1}function $y(e){try{let t=JSON.parse(oB(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function gB(e,t){let n=Re.relative(e,t);return n?n.split(Re.sep).join("/"):"."}function hB(e,t){let n=Re.relative(e,t);return!!n&&!n.startsWith("..")&&!Re.isAbsolute(n)}function yB(e,t){let n=Re.relative(e,t);return!n.startsWith("..")&&!Re.isAbsolute(n)}import{execFile as bB}from"child_process";import{existsSync as da,renameSync as wu,rmSync as Pu}from"fs";import{cpus as SB}from"os";import{join as jy}from"path";function xB(e,t,n){if(!e.defaultOutputPath)return;let i=jy(t,e.defaultOutputPath);n!==i&&da(i)&&wu(i,n)}function CB(e,t,n){if(!e.defaultOutputPath)return null;let i=jy(t,e.defaultOutputPath);if(i===n)return null;let r=`${n}.default-output-backup`;return Pu(r,{force:!0}),da(i)?(wu(i,r),{defaultOutputPath:i,backupPath:r}):{defaultOutputPath:i,backupPath:null}}function vB(e){e&&(Pu(e.defaultOutputPath,{force:!0}),e.backupPath&&da(e.backupPath)&&wu(e.backupPath,e.defaultOutputPath))}function RB(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),i=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(8,Math.max(1,SB().length));return Math.max(1,Math.min(e,Math.floor(i)))}async function Oy(e,t,n,i){let r=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=RB(o.length,i),c=await wB(o,a,l=>ku(l,t,n));if(a>1){let l=new Map;for(let d of c.filter(u=>u.skipped)){let u=o.find(m=>m.id===d.id);u&&(n(`Retrying ${u.label} indexer serially after parallel failure...`),l.set(u.id,await ku(u,t,n)))}s.push(...c.map(d=>l.get(d.id)??d))}else s.push(...c);for(let l of r)s.push(await ku(l,t,n));return s.sort((l,d)=>e.findIndex(u=>u.id===l.id)-e.findIndex(u=>u.id===d.id))}async function ku(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Pu(e.scipPath,{force:!0});let i=CB(e.config,t,e.scipPath);try{await kB(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),xB(e.config,t,e.scipPath)}catch(r){let o=r instanceof Error?r.message:String(r),s=`${e.resolvedBinary} indexer failed: ${o.split(`
816
+ `)[0]}`,a=e.label===e.language?s:`${e.label}: ${s}`;return n(`Skipping ${e.label}: ${s}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,skipped:{language:e.language,reason:a}}}finally{vB(i)}if(!da(e.scipPath)){let r=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,o=e.label===e.language?r:`${e.label}: ${r}`;return n(`Skipping ${e.label}: ${r}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,skipped:{language:e.language,reason:o}}}return{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath}}function kB(e,t,n){return new Promise((i,r)=>{bB(e,[...t],n,o=>{o?r(o):i()})})}async function wB(e,t,n){if(e.length===0)return[];let i=new Array(e.length),r=0,o=Math.max(1,Math.min(e.length,t)),s=Array.from({length:o},async()=>{for(;r<e.length;){let a=r++;i[a]=await n(e[a])}});return await Promise.all(s),i}import{execFileSync as Lu}from"child_process";import{existsSync as Iu,readFileSync as PB}from"fs";import{createRequire as IB}from"module";import{platform as LB}from"os";import{dirname as By,join as ma}from"path";var DB=IB(import.meta.url);function Du(e){return[e.indexerBinary,...e.binaryAliases??[]]}function pa(e){let t=Du(e);return t.length===1?t[0]:t.join(" or ")}function rr(e){for(let t of Du(e))if($t(t))return t;return NB(e)}function Hy(e){return rr(e)!==null||EB(e)}function EB(e){return Vy(e)!==null}function NB(e){let t=Vy(e);if(!t)return null;let i=JSON.parse(PB(t,"utf8")).bin;if(!i)return null;if(typeof i=="string")return ma(By(t),i);for(let r of Du(e)){let o=i[r];if(o)return ma(By(t),o)}return null}function Vy(e){if(!e.bundledNpmPackage)return null;try{return DB.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function Eu(e,t){for(let n of e.projectLocalBinaries??[]){let i=ma(t,n);if(Iu(i))return i}return null}function FB(e,t){return Eu(e,t)??rr(e)}function qy(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||Nu(n,t))return t;let i=Uy(n,t);return i?{...t,DOTNET_ROOT:i}:t}function fa(e,t){let n=pa(e),i=t?FB(e,t):rr(e);if(!i)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:i};let r=TB(i);return{language:e.language,binaryLabel:n,installed:!0,runnable:r.runnable,resolvedBinary:i,installUrl:e.installUrl,note:r.note}}function ga(e,t){let n=e.installMethods,i=pa(e);if(!n?.length)return t(`No auto-install method available for ${i}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1;for(let r of n)if($t(r.prerequisite)){t(`Installing ${i} via ${r.label}...`);try{Lu(r.binary,r.args,{stdio:"inherit",timeout:3e5,env:process.env});let o=rr(e);if(o){let s=o===e.indexerBinary?"":` (using ${o})`;return t(`Successfully installed ${i} via ${r.label}${s}`),!0}t(`${r.label} command completed but ${i} was not found on PATH`)}catch(o){let s=o instanceof Error?o.message:String(o);t(`${r.label} install failed: ${s}`)}}return t(`Could not auto-install ${i}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function TB(e){if(Nu(e,process.env))return{runnable:!0};let t=Uy(e,process.env);if(t)return{runnable:!0,note:`using .NET 9 runtime from ${t}`};let n=zy(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 Uy(e,t){for(let n of zy(t))if(Nu(e,{...t,DOTNET_ROOT:n}))return n;return null}function zy(e){let t=[],n=e.DOTNET_ROOT;if(n&&Iu(n)&&t.push(n),LB()==="darwin"&&$t("brew"))try{let i=Lu("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),r=ma(i,"libexec");Iu(r)&&!t.includes(r)&&t.push(r)}catch{}return t}function Nu(e,t){try{return Lu(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}import p1 from"better-sqlite3";import{existsSync as f1}from"fs";import{dirname as g1,join as h1,resolve as y1}from"path";import{readFileSync as _B,rmSync as AB,statSync as MB,mkdtempSync as $B}from"fs";import{cpus as jB,tmpdir as OB}from"os";import{join as Fu}from"path";import{Worker as BB}from"worker_threads";function Wy(e){return e.length>=8&&Ky(e.length)>1}function Gy(e){let t=Ky(e.vueFiles.length),n=VB(e.vueFiles),i=UB(n,t),r=new URL("./augment-vue-worker.js",import.meta.url),o=$B(Fu(OB(),"scip-query-vue-workers-")),s=new SharedArrayBuffer(4),a=new Int32Array(s),c=HB(),l=Date.now();try{for(let u=0;u<i.length;u++)new BB(r,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:i[u],resultPath:Fu(o,`${u}.json`),sharedBuffer:s}});for(;Atomics.load(a,0)<i.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 d=i.map((u,m)=>{let p=JSON.parse(_B(Fu(o,`${m}.json`),"utf-8"));if(!p.ok)throw new Error(`Vue reference worker failed: ${p.error}`);return p.result});return{occurrences:d.flatMap(u=>u.occurrences),skippedReferences:d.reduce((u,m)=>u+m.skippedReferences,0)}}finally{AB(o,{recursive:!0,force:!0})}}function Ky(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,jB().length-1));return Math.max(1,Math.min(e,n))}function HB(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function VB(e){let t=qB(),n=[];for(let i of e){let r=Jy(i),o=Math.max(1,Math.ceil(r/t));for(let s=0;s<o;s++)n.push({fileName:i,startOffset:Math.floor(r*s/o),endOffset:s===o-1?Number.POSITIVE_INFINITY:Math.floor(r*(s+1)/o),countFileSkip:s===0})}return n}function qB(){return Number.POSITIVE_INFINITY}function UB(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),i=e.map(r=>({task:r,weight:zB(r)})).sort((r,o)=>o.weight-r.weight);for(let r of i){let o=n.reduce((s,a)=>a.weight<s.weight?a:s);o.tasks.push(r.task),o.weight+=r.weight}return n.map(r=>r.tasks).filter(r=>r.length>0)}function zB(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Jy(e.fileName)-e.startOffset)}function Jy(e){try{return MB(e).size}catch{return 1}}import{createRequire as WB}from"module";import{existsSync as GB,readFileSync as _u}from"fs";import{dirname as Xy,extname as KB,join as Qy,relative as JB,resolve as XB}from"path";import{pathToFileURL as QB}from"url";function YB(e){e.transaction(()=>{e.prepare(`
792
817
  DELETE FROM mentions
793
818
  WHERE chunk_id IN (
794
819
  SELECT c.id
@@ -803,12 +828,12 @@ Affected consumer files:`),N.list(e.affectedConsumers,t=>` ${t.file} (${t.cons
803
828
  FROM documents
804
829
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
805
830
  )
806
- `).run()})()}function oh(e,t){return e.prepare(`
831
+ `).run()})()}function Yy(e,t){return e.prepare(`
807
832
  SELECT relative_path AS relativePath
808
833
  FROM documents
809
834
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
810
835
  ORDER BY relative_path
811
- `).all().map(r=>uM(t,r.relativePath))}function sh(e,t){let{vueCore:n,ts:r,volarTs:i}=pM(e),{parsed:o,vueOptions:s}=fM(n,r,t),a=rh(t),c=n.createVueLanguagePlugin(r,o.options,s,p=>p),l=gM(n,r,c),u=hM(a,o),{languageServiceHost:d}=i.createLanguageServiceHost(r,r.sys,l,p=>p,u),m=r.createLanguageService(d);return{ts:r,language:l,languageService:m,fileNames:o.fileNames,configDir:a}}function pM(e){let t=sM(dM(ih(e,"package.json")).href);return{vueCore:Ml(t,"@vue/language-core",e),ts:Ml(t,"typescript",e),volarTs:Ml(t,"@volar/typescript",e)}}function fM(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,rh(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function gM(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!aM(o))return;let s=Ol(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??vM(o))});return r.current=i,i}function hM(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Ml(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 ah(e,t,n){let r=yM(e);return i=>{let o=Wn(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:bM(c.starts,a.line,2)}}function yM(e){let t=e.prepare(`
836
+ `).all().map(i=>XB(t,i.relativePath))}function Zy(e,t){let{vueCore:n,ts:i,volarTs:r}=ZB(e),{parsed:o,vueOptions:s}=e1(n,i,t),a=Xy(t),c=n.createVueLanguagePlugin(i,o.options,s,p=>p),l=t1(n,i,c),d=n1(a,o),{languageServiceHost:u}=r.createLanguageServiceHost(i,i.sys,l,p=>p,d),m=i.createLanguageService(u);return{ts:i,language:l,languageService:m,fileNames:o.fileNames,configDir:a}}function ZB(e){let t=WB(QB(Qy(e,"package.json")).href);return{vueCore:Tu(t,"@vue/language-core",e),ts:Tu(t,"typescript",e),volarTs:Tu(t,"@volar/typescript",e)}}function e1(e,t,n){let i=t.readConfigFile(n,t.sys.readFile);if(i.error||!i.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(i.config,t.sys,Xy(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function t1(e,t,n){let i={},r=e.createLanguage([n],new Map,o=>{if(!GB(o))return;let s=_u(o,"utf-8");i.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??c1(o))});return i.current=r,r}function n1(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Tu(e,t,n){try{return e(t)}catch(i){throw(typeof i=="object"&&i!==null&&"code"in i?i.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:i}):i}}function eb(e,t,n){let i=i1(e);return r=>{let o=di(t,r.fileName),s=n.get(r.fileName);if(!s)return null;let a=n.positionAt(s,r.textSpan.start),c=i.get(o);if(!c)return null;let l=c.containingByLine.get(a.line);return l!==void 0?l:r1(c.starts,a.line,2)}}function i1(e){let t=e.prepare(`
812
837
  SELECT
813
838
  d.relative_path AS relativePath,
814
839
  der.start_line AS startLine,
@@ -817,23 +842,22 @@ Affected consumer files:`),N.list(e.affectedConsumers,t=>` ${t.file} (${t.cons
817
842
  FROM defn_enclosing_ranges der
818
843
  JOIN documents d ON d.id = der.document_id
819
844
  ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
820
- `).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 bM(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 ch(e,t,n){let r=wM(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
845
+ `).all(),n=new Map;for(let i of t){let r=n.get(i.relativePath);r||(r={containingByLine:new Map,starts:[]},n.set(i.relativePath,r)),r.starts.push({line:i.startLine,symbolId:i.symbolId});for(let o=i.startLine;o<=i.endLine;o++)r.containingByLine.set(o,i.symbolId)}for(let i of n.values())i.starts.sort((r,o)=>r.line-o.line);return n}function r1(e,t,n){let i=0,r=e.length-1;for(;i<=r;){let s=Math.floor((i+r)/2);e[s].line<t?i=s+1:r=s-1}let o=null;for(let s of[r,i]){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 tb(e,t,n){let i=d1(t),r=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
821
846
  INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
822
847
  VALUES (?, ?, ?, ?)
823
- `),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let u=Wn(t,l),d=yh(r.name,r.version,u);o.run(d,"default",7,`Vue component|${u}`);let m=LM(i,r,t,l);m&&(s++,a.set(l,m))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function lh(e,t,n,r,i){return e.transaction(()=>(mM(e),SM(e,t,n,r),xM(e,i)))()}function SM(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
848
+ `),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let d=di(t,l),u=ub(i.name,i.version,d);o.run(u,"default",7,`Vue component|${d}`);let m=m1(r,i,t,l);m&&(s++,a.set(l,m))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function nb(e,t,n,i,r){return e.transaction(()=>(YB(e),o1(e,t,n,i),s1(e,r)))()}function o1(e,t,n,i){let r=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
824
849
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
825
850
  VALUES (?, ?, ?, ?, X'00')
826
851
  `),s=e.prepare(`
827
852
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
828
853
  VALUES (?, ?, 1)
829
- `);for(let a of n){let c=r.get(a);if(!c)continue;let l=Wn(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 uh(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(jl(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function dh(e){let t=new Set,n=[];for(let r of e){let i=mh(r);t.has(i)||(t.add(i),n.push(r))}return n}function mh(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function xM(e,t){let n=kM(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
854
+ `);for(let a of n){let c=i.get(a);if(!c)continue;let l=di(t,a),d=r.get(l);if(!d)continue;let u=o.run(d.id,-1,0,0);s.run(Number(u.lastInsertRowid),c)}}function ib(e,t,n,i,r){if(e.fileName.endsWith(".vue")){let o=i.language.scripts.get(e.fileName),s=o?.generated?.languagePlugin.typescript?.getServiceScript(o.generated.root)?.code;if(o&&s){let a=i.language.maps.get(s,o);if(Au(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(r)?n.get(e.fileName):null}return t(e)}function rb(e){let t=new Set,n=[];for(let i of e){let r=ob(i);t.has(r)||(t.add(r),n.push(i))}return n}function ob(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function s1(e,t){let n=u1(e,[...new Set(t.map(c=>c.sourceFile))]),i=e.prepare(`
830
855
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
831
856
  VALUES (?, ?, ?, ?, X'00')
832
- `),i=e.prepare(`
857
+ `),r=e.prepare(`
833
858
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
834
859
  VALUES (?, ?, 0)
835
- `),o=new Set,s=0,a=0;for(let c of t){let l=mh(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*ph(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 fh(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function jl(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function CM(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 gh(e,t){return Wn(e,t).startsWith("node_modules/")}function Wn(e,t){return lM(e,t).replaceAll("\\","/")}function vM(e){switch(cM(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 hh(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=Ol(t,"utf-8"),r={text:n,lineStarts:RM(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:CM}}function RM(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function kM(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 wM(e){try{let t=JSON.parse(Ol(ih(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 LM(e,t,n,r){let i=Wn(n,r),o=yh(t.name,t.version,i);return e.get(o)?.id??null}function yh(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function Bl(e){on({projectRoot:e.projectRoot,dbPath:e.dbPath});let t=_M(e.projectRoot,e.tsconfig);if(!DM(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new IM(e.dbPath);try{let r=oh(n,e.projectRoot),i=TM(EM(e.dbPath),"augment-vue-meta.json"),o=bh(n,e.projectRoot,e.tsconfig),s=FM(i,o,e.onStatus);if(s)return s;let a=AM({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus});return OM(i,bh(n,e.projectRoot,e.tsconfig),a),a}finally{n.close()}}function FM(e,t,n){let r=MM(e,t);return r&&n?.(`Vue references unchanged; reused ${r.resolvedReferences} cached resolved references.`),r}function AM(e){let t=ch(e.db,e.projectRoot,e.vueFiles),n=$M(e,t),r=dh(n.occurrences),i=lh(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 $M(e,t){if(Zg(e.vueFiles))return eh({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=jM({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return BM({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function MM(e,t){try{let n=JSON.parse(PM(e,"utf-8"));return JSON.stringify(n.fingerprint)===JSON.stringify(t)?n.result:null}catch{return null}}function OM(e,t,n){NM(e,JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)+`
836
- `)}function bh(e,t,n){let r=e.prepare(`
860
+ `),o=new Set,s=0,a=0;for(let c of t){let l=ob(c);if(o.has(l))continue;o.add(l);let d=n.get(c.sourceFile);if(!d)continue;let u=i.run(d,a++,c.sourceLine,c.sourceLine),m=r.run(Number(u.lastInsertRowid),c.symbolId);s+=Number(m.changes)}return s}function*sb(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"]),i;for(;i=t.exec(e);){let r=i[0];n.has(r)||(yield{text:r,start:i.index,end:i.index+r.length})}}function ab(e,t){for(let[n]of e.toGeneratedLocation(t,i=>!!i.navigation))return n;return null}function Au(e,t){let n=e;for(let[i]of n.toSourceLocation(t,r=>!!r.navigation))return i;return null}function a1(e,t){let n=0,i=e.lineStarts.length-1;for(;n<=i;){let o=Math.floor((n+i)/2);e.lineStarts[o]<=t?n=o+1:i=o-1}let r=Math.max(0,i);return{line:r,character:t-e.lineStarts[r]}}function cb(e,t){return di(e,t).startsWith("node_modules/")}function di(e,t){return JB(e,t).replaceAll("\\","/")}function c1(e){switch(KB(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 lb(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=_u(t,"utf-8"),i={text:n,lineStarts:l1(n)};return e.set(t,i),i}catch{return e.set(t,null),null}},positionAt:a1}}function l1(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function u1(e,t){let n=new Map,i=500;for(let r=0;r<t.length;r+=i){let o=t.slice(r,r+i),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 d1(e){try{let t=JSON.parse(_u(Qy(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 m1(e,t,n,i){let r=di(n,i),o=ub(t.name,t.version,r);return e.get(o)?.id??null}function ub(e,t,n){let i=n.split("/").map(r=>`\`${r.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${i}/default.`}function db(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>b1({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function Mu(e){return ir(nr(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),ir(db({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}function b1(e){let t=y1(e.projectRoot,e.tsconfig);if(!f1(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new p1(e.dbPath);try{let i=Yy(n,e.projectRoot),r=h1(g1(e.dbPath),"augment-vue-meta.json");return Dy({cachePath:r,readFingerprint:()=>C1(n,e.projectRoot,e.tsconfig),compute:()=>S1({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:i,onStatus:e.onStatus}),onCacheHit:o=>e.onStatus?.(`Vue references unchanged; reused ${o.resolvedReferences} cached resolved references.`)})}finally{n.close()}}function S1(e){let t=tb(e.db,e.projectRoot,e.vueFiles),n=x1(e,t),i=rb(n.occurrences),r=nb(e.db,e.projectRoot,e.vueFiles,t,i),o={vueFiles:e.vueFiles.length,resolvedReferences:i.length,insertedMentions:r,skippedReferences:n.skippedReferences,syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function x1(e,t){if(Wy(e.vueFiles))return Gy({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=v1({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return R1({...n,vueFiles:n.context.fileNames.filter(i=>i.endsWith(".vue"))})}function C1(e,t,n){let i=e.prepare(`
837
861
  SELECT
838
862
  (SELECT COUNT(*) FROM documents) AS documents,
839
863
  (SELECT COUNT(*) FROM global_symbols) AS symbols,
@@ -842,40 +866,40 @@ Affected consumer files:`),N.list(e.affectedConsumers,t=>` ${t.file} (${t.cons
842
866
  (SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
843
867
  (SELECT MAX(id) FROM chunks) AS maxChunkId,
844
868
  (SELECT MAX(id) FROM global_symbols) AS maxSymbolId
845
- `).get();return{version:2,tsconfig:n,files:Un(t),db:r}}function jM(e){let t=hh();return{projectRoot:e.projectRoot,context:sh(e.projectRoot,e.configPath),symbolLookup:ah(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function BM(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=HM(e,i);t.push(...o.occurrences),n+=o.skippedReferences}return{occurrences:t,skippedReferences:n}}function HM(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=Wn(e.projectRoot,t.fileName),a=[...ph(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:UM(a),processedStarts:new Set};return VM({...e,fileName:t.fileName,sourceInfo:i,sourceFile:s,map:o,tokenContext:c})}function VM(e){let t=[],n=0;for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start))continue;let i=fh(e.map,r.start);if(i===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(c=>!gh(e.projectRoot,c.fileName));if(!s){n++;continue}let a=uh(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(a===null){n++;continue}Sh(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,a),e.tokenContext.processedStarts.add(r.start),qM(t,e,r,i,a)}return{occurrences:t,skippedReferences:n}}function qM(e,t,n,r,i){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let o of WM(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&&(Sh(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i),t.tokenContext.processedStarts.add(o))}}function Sh(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 UM(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function WM(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=GM(r,l.textSpan.start,o,i.text);u!==null&&a.push(u)}return a}function GM(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=jl(e,t);if(o===null)return null;let s=n.get(o);return s?.text===r?s.start:null}async function sn(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=ZM(e),s=Date.now();ql(dt(o.outputScip),{recursive:!0}),ql(dt(o.outputDb),{recursive:!0});let a=e.languages??At(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=vO(t,a,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects}),l=await fO(Rt(dt(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),u=null;try{let d=eO({opts:e,paths:o,languages:a,fingerprint:c,start:s,onStatus:r});if(d)return d;aO(i,r);let m=tO(o);return u=m.runDir,await nO({opts:e,languages:a,projectRoot:t,paths:o,tempPaths:m,fingerprint:c,start:s,maxHeapMb:n,skipAutoInstall:i,onStatus:r})}catch(d){throw Nh(o.metaPath,Wl({trigger:e.trigger,result:"failed",start:s,error:d instanceof Error?d.message:String(d)})),d}finally{u&&Gi(u,{recursive:!0,force:!0}),l()}}function ZM(e){let t=e.outputScip??Rt(e.projectRoot,"index.scip"),n=e.outputDb??Rt(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:Rt(dt(n),"meta.json")}}function eO(e){if(e.opts.skipIfUnchanged===!1||!Bs(e.paths.outputScip)||!Bs(e.paths.outputDb)||!RO(e.paths.metaPath,e.fingerprint))return null;on({projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let t=Date.now()-e.start,n=Wl({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return Nh(e.paths.metaPath,n),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:[],lastRefresh:n}}function tO(e){let t=XM(Rt(dt(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:Rt(t,js(e.outputScip)),tempOutputDb:Rt(t,js(e.outputDb)),tempMetaPath:Rt(t,js(e.metaPath))}}async function nO(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},{indexedOutputs:n,skippedLanguages:r,reusedLanguages:i}=await rO(e,t);i.length>0&&e.onStatus(`Reused ${i.length} cached language shard(s): ${i.join(", ")}`);let o=iO(e,t,n,r),s=o.durationMs;return e.onStatus(`Done in ${(s/1e3).toFixed(1)}s`),{languages:n.map(a=>a.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:s,reused:!1,skipped:r,lastRefresh:o}}async function rO(e,t){let n=oO(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}=cO({languages:e.languages.filter(l=>!r.has(l)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,onStatus:e.onStatus}),s=await Gg(i,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),{indexedOutputs:a}=uO(s,o),c=[...n,...a];return dO(c,o,e.languages,e.opts.allowPartial,e.onStatus),{indexedOutputs:c,skippedLanguages:o,reusedLanguages:[...r]}}function iO(e,t,n,r){sO(e.paths.outputDb,n),mO(n,e.tempPaths.tempOutputScip,e.onStatus),pO(e.tempPaths.tempOutputScip,e.tempPaths.tempOutputDb,t,e.onStatus),on({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus});let i=Wl({trigger:e.opts.trigger,result:"rebuilt",start:e.start,languages:n.map(o=>o.language),skipped:[...r]});return Ph(e.tempPaths.tempMetaPath,{version:3,status:r.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.fingerprint,languageFingerprints:wh(e.projectRoot,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects}),requestedLanguages:e.languages,indexedLanguages:n.map(o=>o.language),skipped:[...r],lastRefresh:i}),CO({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath}),i}function oO(e){let t;try{t=JSON.parse(Hs(e.paths.metaPath,"utf-8"))}catch{return[]}if(t.version!==3||!t.languageFingerprints)return[];let n=[],r=wh(e.projectRoot,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects});for(let i of e.languages){let o=Dh(e.paths.outputDb,i);Bs(o)&&Hr(t.languageFingerprints[i])===Hr(r[i])&&n.push({language:i,scipPath:o})}return n}function sO(e,t){for(let n of t){let r=Dh(e,n.language);ql(dt(r),{recursive:!0}),n.scipPath!==r&&KM(n.scipPath,r)}}function aO(e,t){if(!Ts()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
846
- Install from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!Dg(t))throw new Error(`The scip CLI is required but could not be installed.
847
- Install manually from: https://github.com/sourcegraph/scip/releases`)}}function cO(e){let t=[],n=[],r=e.languages.map((i,o)=>({language:i,scipPath:e.languages.length>1?kh(e.tempOutputScip,i,o):e.tempOutputScip}));for(let{language:i,scipPath:o}of r){let s=lO({...e,language:i,scipPath:o});for(let a of s)"skipped"in a?Rh(n,a.skipped):t.push(a.prepared)}return{preparedRuns:t,skippedLanguages:n}}function lO(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[Hl({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=Vg(e.projectRoot,e.typescriptProjects);return t.length===0?[Hl({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})]:(e.onStatus(`Indexing TypeScript workspace as ${t.length} project shard(s).`),t.map((n,r)=>Hl({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:kh(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function Hl(e){let t=qn(e.language),n=$s(t),r=Fl(t,e.projectRoot);if(!r&&!Jg(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...`),!Os(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??Br(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,projectPath:e.projectPath});return{prepared:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,config:t,resolvedBinary:i,binary:o,args:s,env:Xg(t,e.env,i)}}}function uO(e,t){let n=new Map;for(let i of e)if(i.skipped)Rh(t,i.skipped);else{let o=`${i.language}\0${i.outputScipPath}`,s=n.get(o)??{language:i.language,outputScipPath:i.outputScipPath,scipPaths:[]};s.scipPaths.push(i.scipPath),n.set(o,s)}let r=[];for(let i of n.values())if(i.scipPaths.length>1)Il(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&Wi(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function Rh(e,t){let n=e.find(r=>r.language===t.language);if(!n){e.push(t);return}n.reason.includes(t.reason)||(n.reason=`${n.reason}; ${t.reason}`)}function dO(e,t,n,r,i){if(e.length===0){let o=t.map(s=>` - ${s.language}: ${s.reason}`).join(`
869
+ `).get();return{version:2,tsconfig:n,files:ui(t),db:i}}function v1(e){let t=lb();return{projectRoot:e.projectRoot,context:Zy(e.projectRoot,e.configPath),symbolLookup:eb(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function R1(e){let t=[],n=0,i=e.tasks??e.vueFiles.map(r=>({fileName:r,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let r of i){let o=k1(e,r);t.push(...o.occurrences),n+=o.skippedReferences}return{occurrences:t,skippedReferences:n}}function k1(e,t){let n=e.context.language.scripts.get(t.fileName),i=n?.generated?.languagePlugin.typescript?.getServiceScript(n.generated.root)?.code;if(!n||!i)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let r=e.sourceReader.get(t.fileName);if(!r)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let o=e.context.language.maps.get(i,n),s=di(e.projectRoot,t.fileName),a=[...sb(r.text)],c={tokens:a.filter(l=>l.start>=t.startOffset&&l.start<t.endOffset),tokenByStart:new Map(a.map(l=>[l.start,l])),tokenTextCounts:I1(a),processedStarts:new Set};return w1({...e,fileName:t.fileName,sourceInfo:r,sourceFile:s,map:o,tokenContext:c})}function w1(e){let t=[],n=0;for(let i of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(i.start))continue;let r=ab(e.map,i.start);if(r===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,r+1)??[]).find(c=>!cb(e.projectRoot,c.fileName));if(!s){n++;continue}let a=ib(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(a===null){n++;continue}mb(t,e.sourceReader,e.sourceInfo,e.sourceFile,i,a),e.tokenContext.processedStarts.add(i.start),P1(t,e,i,r,a)}return{occurrences:t,skippedReferences:n}}function P1(e,t,n,i,r){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let o of L1(t.context.languageService,t.fileName,i+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(o))continue;let s=t.tokenContext.tokenByStart.get(o);s&&(mb(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,r),t.tokenContext.processedStarts.add(o))}}function mb(e,t,n,i,r,o){let s=t.positionAt(n,r.start);e.push({sourceFile:i,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+r.text.length,symbolId:o})}function I1(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function L1(e,t,n,i,r,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 d=D1(i,l.textSpan.start,o,r.text);d!==null&&a.push(d)}return a}function D1(e,t,n,i){let r=n.get(t);if(r?.text===i)return r.start;let o=Au(e,t);if(o===null)return null;let s=n.get(o);return s?.text===i?s.start:null}async function vn(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:i=console.log,skipAutoInstall:r=!1}=e,o=M1(e),s=Date.now();Ou(Ct(o.outputScip),{recursive:!0}),Ou(Ct(o.outputDb),{recursive:!0});let a=e.languages??tn(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.");i(`Detected languages: ${a.join(", ")}`);let c=oH(t,a,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),l=await Q1(jt(Ct(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:i}),d=null;try{let u=$1({opts:e,paths:o,languages:a,fingerprint:c,start:s,onStatus:i});if(u)return u;U1(r,i);let m=j1(o);return d=m.runDir,await O1({opts:e,languages:a,projectRoot:t,paths:o,tempPaths:m,fingerprint:c,start:s,maxHeapMb:n,skipAutoInstall:r,onStatus:i})}catch(u){throw kb(o.metaPath,Hu({trigger:e.trigger,result:"failed",start:s,error:u instanceof Error?u.message:String(u)})),u}finally{d&&ho(d,{recursive:!0,force:!0}),l()}}function M1(e){let t=e.outputScip??jt(e.projectRoot,"index.scip"),n=e.outputDb??jt(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:jt(Ct(n),"meta.json")}}function $1(e){if(e.opts.skipIfUnchanged===!1||!ya(e.paths.outputScip)||!ya(e.paths.outputDb)||!sH(e.paths.metaPath,e.fingerprint))return null;ir(nr(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let t=Date.now()-e.start,n=Hu({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return kb(e.paths.metaPath,n),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:[],lastRefresh:n}}function j1(e){let t=T1(jt(Ct(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:jt(t,ha(e.outputScip)),tempOutputDb:jt(t,ha(e.outputDb)),tempMetaPath:jt(t,ha(e.metaPath))}}async function O1(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},{indexedOutputs:n,skippedLanguages:i,reusedLanguages:r}=await B1(e,t);r.length>0&&e.onStatus(`Reused ${r.length} cached language shard(s): ${r.join(", ")}`);let o=H1(e,t,n,i),s=o.durationMs;return e.onStatus(`Done in ${(s/1e3).toFixed(1)}s`),{languages:n.map(a=>a.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:s,reused:!1,skipped:i,lastRefresh:o}}async function B1(e,t){let n=V1(e),i=new Set(n.map(l=>l.language));for(let l of i)e.onStatus(`Reusing cached ${l} SCIP shard (language inputs unchanged).`);let{preparedRuns:r,skippedLanguages:o}=z1({languages:e.languages.filter(l=>!i.has(l)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),s=await Oy(r,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),{indexedOutputs:a}=G1(s,o),c=[...n,...a];return K1(c,o,e.languages,e.opts.allowPartial,e.onStatus),{indexedOutputs:c,skippedLanguages:o,reusedLanguages:[...i]}}function H1(e,t,n,i){q1(e.paths.outputDb,n),J1(n,e.tempPaths.tempOutputScip,e.onStatus),X1(e.tempPaths.tempOutputScip,e.tempPaths.tempOutputDb,t,e.onStatus),ir(nr(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus});let r=Hu({trigger:e.opts.trigger,result:"rebuilt",start:e.start,languages:n.map(o=>o.language),skipped:[...i]});return Rb(e.tempPaths.tempMetaPath,{version:3,status:i.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.fingerprint,languageFingerprints:bb(e.projectRoot,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath}),requestedLanguages:e.languages,indexedLanguages:n.map(o=>o.language),skipped:[...i],lastRefresh:r}),rH({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath}),r}function V1(e){let t;try{t=JSON.parse(ba(e.paths.metaPath,"utf-8"))}catch{return[]}if(t.version!==3||!t.languageFingerprints)return[];let n=[],i=bb(e.projectRoot,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath});for(let r of e.languages){let o=vb(e.paths.outputDb,r);ya(o)&&or(t.languageFingerprints[r])===or(i[r])&&n.push({language:r,scipPath:o})}return n}function q1(e,t){for(let n of t){let i=vb(e,n.language);Ou(Ct(i),{recursive:!0}),n.scipPath!==i&&F1(n.scipPath,i)}}function U1(e,t){if(!ca()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
870
+ Install from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!Sy(t))throw new Error(`The scip CLI is required but could not be installed.
871
+ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function z1(e){let t=[],n=[],i=e.languages.map((r,o)=>({language:r,scipPath:e.languages.length>1?yb(e.tempOutputScip,r,o):e.tempOutputScip}));for(let{language:r,scipPath:o}of i){let s=W1({...e,language:r,scipPath:o});for(let a of s)"skipped"in a?hb(n,a.skipped):t.push(a.prepared)}return{preparedRuns:t,skippedLanguages:n}}function W1(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[$u({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=Ay(e.projectRoot,e.typescriptProjects);return t.length===0?[$u({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})]:(e.onStatus(`Indexing TypeScript workspace as ${t.length} project shard(s).`),t.map((n,i)=>$u({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:yb(e.tempOutputScip,"typescript-project",i),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function $u(e){let t=li(e.language),n=pa(t),i=Eu(t,e.projectRoot);if(!i&&!Hy(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...`),!ga(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 r=i??rr(t);if(!r){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:r,projectPath:e.projectPath,configPath:e.language==="clojure"?e.clojureConfigPath:void 0});return{prepared:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,config:t,resolvedBinary:r,binary:o,args:s,env:qy(t,e.env,r)}}}function G1(e,t){let n=new Map;for(let r of e)if(r.skipped)hb(t,r.skipped);else{let o=`${r.language}\0${r.outputScipPath}`,s=n.get(o)??{language:r.language,outputScipPath:r.outputScipPath,scipPaths:[]};s.scipPaths.push(r.scipPath),n.set(o,s)}let i=[];for(let r of n.values())if(r.scipPaths.length>1)Ru(r.scipPaths,r.outputScipPath),i.push({language:r.language,scipPath:r.outputScipPath});else{let o=r.scipPaths[0];o!==r.outputScipPath&&go(o,r.outputScipPath),i.push({language:r.language,scipPath:r.outputScipPath})}return{indexedOutputs:i}}function hb(e,t){let n=e.find(i=>i.language===t.language);if(!n){e.push(t);return}n.reason.includes(t.reason)||(n.reason=`${n.reason}; ${t.reason}`)}function K1(e,t,n,i,r){if(e.length===0){let o=t.map(s=>` - ${s.language}: ${s.reason}`).join(`
848
872
  `);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
849
- `+o)}if(t.length!==0&&(i(`Indexed ${e.length} language output(s); skipped or incomplete: ${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.
873
+ `+o)}if(t.length!==0&&(r(`Indexed ${e.length} language output(s); skipped or incomplete: ${t.map(o=>o.language).join(", ")}.`),!i))throw new Error(`Failed to index all required languages; preserving the previous index. Pass --allow-partial to intentionally write an incomplete index.
850
874
  `+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
851
- `))}function mO(e,t,n){e.length>1?(n(`Merging ${e.length} language indexes...`),Il(e.map(r=>r.scipPath),t)):e[0].scipPath!==t&&Wi(e[0].scipPath,t)}function pO(e,t,n,r){if(r("Converting to SQLite..."),!Bs(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{let i=Hg(e);i.removedDefinitionOccurrences>0&&r(`Sanitized ${i.removedDefinitionOccurrences} invalid definition occurrences across ${i.touchedDocuments} documents before SQLite conversion.`);let o=Ts();if(!o)throw new Error("scip CLI is not available");zM(o,["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 kh(e,t,n){let r=YM(e)||".scip",i=js(e,r);return Rt(dt(e),`${i}.${n+1}.${t}${r}`)}async function fO(e,t){for(let n=0;n<2;n++){let r=gO(e,t);if(r)return r;let i=hO(e);if(i&&yO(t.trigger,i)){t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`),await SO(i.pid),Gi(e,{force:!0});continue}if(i&&!Ul(i.pid)){Gi(e,{force:!0});continue}throw new Error(`Another scip-query reindex is already running for ${dt(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${dt(e)}.`)}function gO(e,t){let n;try{n=QM(e,"wx")}catch(i){if((typeof i=="object"&&i&&"code"in i?i.code:void 0)==="EEXIST")return null;throw i}let r={version:1,pid:process.pid,projectRoot:t.projectRoot,startedAt:new Date().toISOString(),trigger:t.trigger};return vh(n,JSON.stringify(r)+`
852
- `),()=>{try{JM(n)}finally{Gi(e,{force:!0})}}}function hO(e){try{let t=JSON.parse(Hs(e,"utf-8"));return typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0?null:{version:1,pid:t.pid,projectRoot:typeof t.projectRoot=="string"?t.projectRoot:dt(e),startedAt:typeof t.startedAt=="string"?t.startedAt:"unknown",trigger:t.trigger}}catch{return null}}function yO(e,t){return e?.kind==="manual-cli"&&bO(t?.trigger)}function bO(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function SO(e){xh(e,"SIGTERM"),!await Ch(e,2e3)&&(xh(e,"SIGKILL"),await Ch(e,1e3))}function xh(e,t){try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}async function Ch(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!Ul(e))return!0;await xO(50)}return!Ul(e)}function Ul(e){try{return process.kill(e,0),!0}catch{return!1}}function xO(e){return new Promise(t=>setTimeout(t,e))}function CO(e){Vl(e.tempOutputScip,e.outputScip),Vl(e.tempOutputDb,e.outputDb),Vl(e.tempMetaPath,e.metaPath)}function Vl(e,t){Gi(`${t}.tmp-replace`,{force:!0}),Wi(e,`${t}.tmp-replace`),Wi(`${t}.tmp-replace`,t)}function vO(e,t,n){return{version:2,languages:[...t].sort(),pnpmWorkspaces:Ih(n),typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:Lh(n.typescriptProjects),files:Un(e)}}function wh(e,t,n){return Object.fromEntries(t.map(r=>{let i=qn(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:Lh(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]};return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&Ih(n),...o,files:Un(e,{language:r,markerFiles:i})}]}))}function Lh(e){return[...new Set((e??[]).map(t=>t.trim()).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function Ih(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Dh(e,t){return Rt(dt(e),"language-indexes",`${t}.scip`)}function RO(e,t){try{let n=JSON.parse(Hs(e,"utf-8"));return(n.version===2||n.version===3)&&n.status==="complete"&&Hr(n.fingerprint)===Hr(t)&&Hr([...n.indexedLanguages??[]].sort())===Hr(t.languages)}catch{return!1}}function Ph(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;vh(n,`${JSON.stringify(t,null,2)}
853
- `),Wi(n,e)}function Nh(e,t){try{let n=JSON.parse(Hs(e,"utf-8"));if(n.version!==2&&n.version!==3)return;Ph(e,{...n,lastRefresh:t})}catch{}}function Wl(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:Date.now()-e.start,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function Hr(e){return JSON.stringify(e)}import{existsSync as Eh,readFileSync as kO}from"fs";function Gn(e,t,n){let r=new Date().toISOString();if(!Eh(n.dbPath))return{state:"missing",checkedAt:r,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!Eh(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(kO(n.metaPath,"utf-8")),o=t.languages??At(e),s=wO(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,lastRefresh:i.lastRefresh,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 wO(e,t,n){return{version:2,languages:[...t].sort(),pnpmWorkspaces:n.indexer?.typescript?.projectMode!=="workspace"&&n.indexer?.typescript?.pnpmWorkspaces===!0,typescriptProjectMode:n.indexer?.typescript?.projectMode??"single",typescriptProjects:LO(n.indexer?.typescript?.projects),files:Un(e)}}function LO(e){return[...new Set((e??[]).map(t=>t.trim()).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}import{execFileSync as GO}from"child_process";import{createRequire as IO}from"module";var DO=IO(import.meta.url);function Th(e,t=[]){let n=PO(),r=Oa(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 PO(){try{return DO.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as Vr,spawnSync as $h}from"child_process";import{existsSync as $t,mkdtempSync as Mh,readFileSync as NO,readdirSync as EO,rmSync as Oh,symlinkSync as TO,writeFileSync as _O}from"fs";import{tmpdir as jh}from"os";import{join as tt}from"path";var FO=3e5,AO=12;function Gl(e,t,n={}){let r=zl(e);if(r.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,dirtyOverlap:[],batches:[]};let i=$O(t,r),o=n.timeoutMs??FO,s=jO(e,t),a=Mh(tt(jh(),"scip-cleanup-verify-")),c=[],l=new Set;try{Vr("git",["-C",e,"worktree","add","--detach","--force",a,"HEAD"],{stdio:"ignore"}),BO(e,a);for(let u of r)for(let d of Ah(u,a,o).errorKeys)l.add(d);for(let u of t.batches){Hh(a,u);let d=[];for(let m of r){let p=Ah(m,a,o);d.push(...p.rawErrors.filter(g=>!l.has(Bh(g))))}if(d.length===0)c.push({depth:u.depth,status:"verified"});else{c.push({depth:u.depth,status:"failed",errors:d.slice(0,AO)});break}}}finally{try{Vr("git",["-C",e,"worktree","remove","--force",a],{stdio:"ignore"})}catch{Oh(a,{recursive:!0,force:!0})}}return{checkers:r.map(u=>u.label),uncoveredFiles:i,baselineErrors:l.size,dirtyOverlap:s,batches:c}}function $O(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 Bh(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var _h=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"];function zl(e){let t=[];if($t(tt(e,"tsconfig.json"))){let n=tt(e,"node_modules",".bin","tsc");t.push($t(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:_h}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:_h})}if($t(tt(e,"go.mod"))&&t.push({label:"go build ./...",binary:"go",args:["build","./..."],coversExtensions:[".go"]}),["pyproject.toml","setup.py","requirements.txt"].some(n=>$t(tt(e,n)))){let n=MO();n&&t.push(n)}for(let n of OO(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:tt(e,n,"..","target")}});return t}function MO(){return Fh("ruff")?{label:"ruff check --select E9,F821,F822",binary:"ruff",args:["check","--quiet","--select","E9,F821,F822","."],coversExtensions:[".py"]}:Fh("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"]}:null}function Fh(e){try{return $h(e,["--version"],{stdio:"ignore",timeout:1e4}).status===0}catch{return!1}}function OO(e){let t=[];if($t(tt(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=EO(e)}catch{return t}for(let r of n)r==="node_modules"||r.startsWith(".")||$t(tt(e,r,"Cargo.toml"))&&t.push(`${r}/Cargo.toml`);return t}function jO(e,t){let n;try{n=Vr("git",["-C",e,"status","--porcelain"],{encoding:"utf-8"})}catch{return[]}let r=new Set(n.split(`
854
- `).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 BO(e,t){for(let n of["node_modules"]){let r=tt(e,n),i=tt(t,n);if($t(r)&&!$t(i))try{TO(r,i,"junction")}catch{}}}function Hh(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=tt(e,r);$t(o)&&_O(o,HO(NO(o,"utf-8"),i,{rust:r.endsWith(".rs")}))}}function Jl(e,t){for(let n of t)Hh(e,n)}function Vh(e,t){let n=Mh(tt(jh(),"scip-cleanup-patch-"));try{return Vr("git",["-C",e,"worktree","add","--detach","--force",n,"HEAD"],{stdio:"ignore"}),Jl(n,t),Vr("git",["-C",n,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024})}finally{try{Vr("git",["-C",e,"worktree","remove","--force",n],{stdio:"ignore"})}catch{Oh(n,{recursive:!0,force:!0})}}}function Kl(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 Xl(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 HO(e,t,n={}){let r=e.split(`
855
- `),i=(n.rust===!0?VO(e):Sn(e)).split(`
856
- `),o=new Set;for(let s of t){let a=qO(r,s.start),c=WO(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(`
857
- `)}function VO(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 qO(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 UO=200;function WO(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>UO)break}return n}function Ah(e,t,n){let r=$h(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??""}
858
- ${r.stderr??""}`.split(`
859
- `).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(Bh))}}var qh={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"]},zO={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 kt(e,t){let n=t.languages??At(e),r=n.map(s=>{let a=Ms(qn(s),e);return{...a,language:s,resolvedBinary:a.resolvedBinary??void 0}}),i=n.includes("typescript")?{language:"typescript",...Th(e,t.semantic?.typescript?.tsconfigs)}:void 0,o=zl(e).map(s=>({label:s.label,coversExtensions:s.coversExtensions}));return{languages:n,indexers:r,semantic:i,checkers:o,gitAvailable:QO(e)}}function zn(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=>JO(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 JO(e,t){let n=e.indexers.find(a=>a.language===t),r=n?.runnable?"available":"unavailable",i=zO[t],o=t==="typescript"?KO(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=XO(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 ${qh[t].join(", ")} files.`}}}function KO(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 XO(e,t){let n=new Set(qh[t]);return e.checkers.filter(r=>r.coversExtensions.some(i=>n.has(i)))}function QO(e){try{return GO("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import{chmodSync as YO,existsSync as Vs,readFileSync as qs,writeFileSync as Gh}from"fs";import{join as Ji}from"path";var zi="<!-- scip-query:agent-setup:begin -->",Ql="<!-- scip-query:agent-setup:end -->",Uh="# scip-query:agent-setup";function Ki(){if(process.stdin.isTTY)return"";try{return qs(0,"utf-8")}catch{return""}}function Us(e){if(!e.trim())return!1;try{return JSON.parse(e).stop_hook_active===!0}catch{return!1}}function Xi(e){let t=e.rootCauseGroups?.length??e.findings.length,n=[`scip-query diff-gate found ${e.findings.length} issue(s) in ${t} root-cause group(s) in this diff \u2014 fix or knowingly accept them before finishing:`],r=e.rootCauseGroups?.filter(i=>i.count>1)??[];for(let i of r)n.push(`- group [${i.check}] ${i.count} finding(s): ${i.message}`),n.push(` -> ${i.remediation}`);for(let i of e.findings)n.push(`- [${i.check}] ${i.message}`),n.push(` -> ${i.remediation}`);return n.join(`
860
- `)}function Ws(e,t={}){let n={written:[],unchanged:[],skipped:[]};return ZO(e,n),t.gitHook&&ej(e,n),n}function ZO(e,t){let n=[zi,"## 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.",Ql].join(`
861
- `);Wh(e,"AGENTS.md",n,t);let r=Vs(Ji(e,"CLAUDE.md"))?qs(Ji(e,"CLAUDE.md"),"utf-8"):"";if(r.includes("@AGENTS.md")&&!r.includes(zi)){t.unchanged.push("CLAUDE.md");return}let i=[zi,"@AGENTS.md",Ql].join(`
862
- `);Wh(e,"CLAUDE.md",i,t)}function Wh(e,t,n,r){let i=Ji(e,t),o=Vs(i)?qs(i,"utf-8"):"",s;if(o.includes(zi)){let a=new RegExp(`${zi}[\\s\\S]*?${Ql}`);s=o.replace(a,n)}else s=o.length>0?`${o.replace(/\n*$/,`
875
+ `))}function J1(e,t,n){e.length>1?(n(`Merging ${e.length} language indexes...`),Ru(e.map(i=>i.scipPath),t)):e[0].scipPath!==t&&go(e[0].scipPath,t)}function X1(e,t,n,i){if(i("Converting to SQLite..."),!ya(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{let r=_y(e);r.removedDefinitionOccurrences>0&&i(`Sanitized ${r.removedDefinitionOccurrences} invalid definition occurrences across ${r.touchedDocuments} documents before SQLite conversion.`);let o=ca();if(!o)throw new Error("scip CLI is not available");E1(o,["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024})}catch(r){let o=r instanceof Error?r.message:String(r);throw new Error(`Failed to convert SCIP index to SQLite: ${o}`,{cause:r})}}function yb(e,t,n){let i=A1(e)||".scip",r=ha(e,i);return jt(Ct(e),`${r}.${n+1}.${t}${i}`)}async function Q1(e,t){for(let n=0;n<2;n++){let i=Y1(e,t);if(i)return i;let r=Z1(e);if(r&&eH(t.trigger,r)){t.onStatus(`Manual reindex preempting watcher refresh started at ${r.startedAt}.`),await nH(r.pid),ho(e,{force:!0});continue}if(r&&!Bu(r.pid)){ho(e,{force:!0});continue}throw new Error(`Another scip-query reindex is already running for ${Ct(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${Ct(e)}.`)}function Y1(e,t){let n;try{n=_1(e,"wx")}catch(r){if((typeof r=="object"&&r&&"code"in r?r.code:void 0)==="EEXIST")return null;throw r}let i={version:1,pid:process.pid,projectRoot:t.projectRoot,startedAt:new Date().toISOString(),trigger:t.trigger};return gb(n,JSON.stringify(i)+`
876
+ `),()=>{try{N1(n)}finally{ho(e,{force:!0})}}}function Z1(e){try{let t=JSON.parse(ba(e,"utf-8"));return typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0?null:{version:1,pid:t.pid,projectRoot:typeof t.projectRoot=="string"?t.projectRoot:Ct(e),startedAt:typeof t.startedAt=="string"?t.startedAt:"unknown",trigger:t.trigger}}catch{return null}}function eH(e,t){return e?.kind==="manual-cli"&&tH(t?.trigger)}function tH(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function nH(e){pb(e,"SIGTERM"),!await fb(e,2e3)&&(pb(e,"SIGKILL"),await fb(e,1e3))}function pb(e,t){try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}async function fb(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!Bu(e))return!0;await iH(50)}return!Bu(e)}function Bu(e){try{return process.kill(e,0),!0}catch{return!1}}function iH(e){return new Promise(t=>setTimeout(t,e))}function rH(e){ju(e.tempOutputScip,e.outputScip),ju(e.tempOutputDb,e.outputDb),ju(e.tempMetaPath,e.metaPath)}function ju(e,t){ho(`${t}.tmp-replace`,{force:!0}),go(e,`${t}.tmp-replace`),go(`${t}.tmp-replace`,t)}function oH(e,t,n){return{version:2,languages:[...t].sort(),pnpmWorkspaces:Cb(n),typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:Sb(n.typescriptProjects),clojureConfigPath:xb(n.clojureConfigPath),files:ui(e)}}function bb(e,t,n){return Object.fromEntries(t.map(i=>{let r=li(i).markerFiles,o=i==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:Sb(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},s=i==="clojure"?xb(n.clojureConfigPath):void 0;return[i,{version:2,languages:[i],pnpmWorkspaces:i==="typescript"&&Cb(n),...o,clojureConfigPath:s,files:ui(e,{language:i,markerFiles:r})}]}))}function Sb(e){return[...new Set((e??[]).map(t=>t.trim()).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function xb(e){return e?.trim()||void 0}function Cb(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function vb(e,t){return jt(Ct(e),"language-indexes",`${t}.scip`)}function sH(e,t){try{let n=JSON.parse(ba(e,"utf-8"));return(n.version===2||n.version===3)&&n.status==="complete"&&or(n.fingerprint)===or(t)&&or([...n.indexedLanguages??[]].sort())===or(t.languages)}catch{return!1}}function Rb(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;gb(n,`${JSON.stringify(t,null,2)}
877
+ `),go(n,e)}function kb(e,t){try{let n=JSON.parse(ba(e,"utf-8"));if(n.version!==2&&n.version!==3)return;Rb(e,{...n,lastRefresh:t})}catch{}}function Hu(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:Date.now()-e.start,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function or(e){return JSON.stringify(e)}import{existsSync as wb,readFileSync as aH}from"fs";function Rn(e,t,n){let i=new Date().toISOString();if(!wb(n.dbPath))return{state:"missing",checkedAt:i,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!wb(n.metaPath))return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let r=JSON.parse(aH(n.metaPath,"utf-8")),o=t.languages??tn(e),s=cH(e,o,t),a=Array.isArray(r.indexedLanguages)?[...r.indexedLanguages].sort():[],c=(r.version===2||r.version===3)&&r.status==="complete"&&JSON.stringify(r.fingerprint)===JSON.stringify(s)&&JSON.stringify(a)===JSON.stringify(s.languages);return{state:c?"fresh":"stale",checkedAt:i,metaPath:n.metaPath,updatedAt:r.updatedAt,lastRefresh:r.lastRefresh,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(r){return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Could not read reindex metadata: ${r instanceof Error?r.message:String(r)}`,remedy:"Run: scip-query reindex"}}}function cH(e,t,n){return{version:2,languages:[...t].sort(),pnpmWorkspaces:n.indexer?.typescript?.projectMode!=="workspace"&&n.indexer?.typescript?.pnpmWorkspaces===!0,typescriptProjectMode:n.indexer?.typescript?.projectMode??"single",typescriptProjects:lH(n.indexer?.typescript?.projects),clojureConfigPath:uH(n.indexer?.clojure?.configPath),files:ui(e)}}function lH(e){return[...new Set((e??[]).map(t=>t.trim()).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function uH(e){return e?.trim()||void 0}import{execFileSync as FH}from"child_process";import{createRequire as dH}from"module";var mH=dH(import.meta.url);function Pb(e,t=[]){let n=pH(),i=Dc(e,t),r=i[0];return n?i.length===0?{available:!1,dependencyAvailable:n,reason:"no tsconfig found"}:{available:!0,dependencyAvailable:n,tsconfigPath:r,tsconfigPaths:i}:{available:!1,dependencyAvailable:n,tsconfigPath:r,tsconfigPaths:i,reason:"ts-morph is not installed"}}function pH(){try{return mH.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as sr,spawnSync as Db}from"child_process";import{existsSync as vt,mkdtempSync as Eb,readFileSync as fH,readdirSync as gH,rmSync as Nb,symlinkSync as hH,writeFileSync as yH}from"fs";import{tmpdir as Fb}from"os";import{join as ze}from"path";var bH=3e5,SH=12;function qu(e,t,n={}){let i=Uu(e);if(i.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,dirtyOverlap:[],batches:[]};let r=xH(t,i),o=n.timeoutMs??bH,s=wH(e,t),a=Eb(ze(Fb(),"scip-cleanup-verify-")),c=[],l=new Set;try{sr("git",["-C",e,"worktree","add","--detach","--force",a,"HEAD"],{stdio:"ignore"}),PH(e,a);for(let d of i)for(let u of Lb(d,a,o).errorKeys)l.add(u);for(let d of t.batches){_b(a,d);let u=[];for(let m of i){let p=Lb(m,a,o);u.push(...p.rawErrors.filter(f=>!l.has(Tb(f))))}if(u.length===0)c.push({depth:d.depth,status:"verified"});else{c.push({depth:d.depth,status:"failed",errors:u.slice(0,SH)});break}}}finally{try{sr("git",["-C",e,"worktree","remove","--force",a],{stdio:"ignore"})}catch{Nb(a,{recursive:!0,force:!0})}}return{checkers:i.map(d=>d.label),uncoveredFiles:r,baselineErrors:l.size,dirtyOverlap:s,batches:c}}function xH(e,t){let n=new Set(t.flatMap(r=>r.coversExtensions));return[...new Set(e.batches.flatMap(r=>r.entries.map(o=>o.file)))].filter(r=>{let o=r.slice(r.lastIndexOf("."));return!n.has(o)}).sort()}function Tb(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var Ib=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"],Vu=[".clj",".cljs",".cljc"],CH=["deps.edn","project.clj","bb.edn","shadow-cljs.edn"];function Uu(e){let t=[];if(vt(ze(e,"tsconfig.json"))){let n=ze(e,"node_modules",".bin","tsc");t.push(vt(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:Ib}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:Ib})}if(vt(ze(e,"go.mod"))&&t.push({label:"go build ./...",binary:"go",args:["build","./..."],coversExtensions:[".go"]}),["pyproject.toml","setup.py","requirements.txt"].some(n=>vt(ze(e,n)))){let n=vH();n&&t.push(n)}if(CH.some(n=>vt(ze(e,n)))){let n=RH(e);n&&t.push(n)}for(let n of kH(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:ze(e,n,"..","target")}});return t}function vH(){return Sa("ruff")?{label:"ruff check --select E9,F821,F822",binary:"ruff",args:["check","--quiet","--select","E9,F821,F822","."],coversExtensions:[".py"]}:Sa("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"]}:null}function RH(e){let t=ze(e,"node_modules",".bin","clj-kondo");return vt(t)?{label:"clj-kondo --lint .",binary:t,args:["--lint","."],coversExtensions:Vu}:Sa("clj-kondo")?{label:"clj-kondo --lint .",binary:"clj-kondo",args:["--lint","."],coversExtensions:Vu}:Sa("npx")?{label:"npx clj-kondo --lint .",binary:"npx",args:["--yes","clj-kondo","--lint","."],coversExtensions:Vu}:null}function Sa(e){try{return Db(e,["--version"],{stdio:"ignore",timeout:1e4}).status===0}catch{return!1}}function kH(e){let t=[];if(vt(ze(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=gH(e)}catch{return t}for(let i of n)i==="node_modules"||i.startsWith(".")||vt(ze(e,i,"Cargo.toml"))&&t.push(`${i}/Cargo.toml`);return t}function wH(e,t){let n;try{n=sr("git",["-C",e,"status","--porcelain"],{encoding:"utf-8"})}catch{return[]}let i=new Set(n.split(`
878
+ `).map(o=>o.slice(3).trim()).filter(o=>o!==""));return[...new Set(t.batches.flatMap(o=>o.entries.map(s=>s.file)))].filter(o=>i.has(o)).sort()}function PH(e,t){for(let n of["node_modules"]){let i=ze(e,n),r=ze(t,n);if(vt(i)&&!vt(r))try{hH(i,r,"junction")}catch{}}}function _b(e,t){let n=new Map;for(let i of t.entries){let r=n.get(i.file)??[];r.push({start:i.startLine,end:i.endLine}),n.set(i.file,r)}for(let[i,r]of n){let o=ze(e,i);vt(o)&&yH(o,IH(fH(o,"utf-8"),r,{rust:i.endsWith(".rs")}))}}function zu(e,t){for(let n of t)_b(e,n)}function Ab(e,t){let n=Eb(ze(Fb(),"scip-cleanup-patch-"));try{return sr("git",["-C",e,"worktree","add","--detach","--force",n,"HEAD"],{stdio:"ignore"}),zu(n,t),sr("git",["-C",n,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024})}finally{try{sr("git",["-C",e,"worktree","remove","--force",n],{stdio:"ignore"})}catch{Nb(n,{recursive:!0,force:!0})}}}function Wu(e,t={}){if(t.all)return[...e.batches];if(t.batch!==void 0){let n=e.batches.find(i=>i.depth===t.batch);return n?[n]:[]}return[...e.batches]}function Gu(e,t,n={}){let i=[];e.checkers.length===0&&i.push("No project checker was detected, so no deletion patch is compiler-verified."),e.uncoveredFiles.length>0&&i.push(`No detected checker covers: ${e.uncoveredFiles.join(", ")}.`),!n.allowDirty&&e.dirtyOverlap.length>0&&i.push(`Plan files are dirty in the working tree: ${e.dirtyOverlap.join(", ")}.`);let r=new Set(e.batches.filter(o=>o.status==="verified").map(o=>o.depth));for(let o of t)r.has(o.depth)||i.push(`Batch ${o.depth} is not compiler-verified.`);return i}function IH(e,t,n={}){let i=e.split(`
879
+ `),r=(n.rust===!0?LH(e):Tn(e)).split(`
880
+ `),o=new Set;for(let s of t){let a=DH(i,s.start),c=NH(r,a,Math.min(s.end,i.length-1));for(let l=a;l<=c&&l<i.length;l++)o.add(l)}return i.filter((s,a)=>!o.has(a)).join(`
881
+ `)}function LH(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 DH(e,t){let n=t;for(;n>0;){let i=(e[n-1]??"").trim();if(/^(?:\/\/\/|\/\/!|#\[|#!\[|\/\*\*|\*|\*\/|@\w)/.test(i))n-=1;else break}return n}var EH=200;function NH(e,t,n){let i=0;for(let r=t;r<e.length;r++){for(let o of e[r]??"")o==="("||o==="["||o==="{"?i+=1:(o===")"||o==="]"||o==="}")&&(i-=1);if(r>=n&&i<=0)return r;if(r-n>EH)break}return n}function Lb(e,t,n){let i=Db(e.binary,e.args,{cwd:t,encoding:"utf-8",timeout:n,env:e.env??process.env,maxBuffer:33554432});if(i.status===0)return{ok:!0,rawErrors:[],errorKeys:new Set};let o=`${i.stdout??""}
882
+ ${i.stderr??""}`.split(`
883
+ `).map(s=>s.trim()).filter(s=>/\berror\b/i.test(s));return i.error&&o.length===0&&o.push(String(i.error)),{ok:!1,rawErrors:o,errorKeys:new Set(o.map(Tb))}}var Mb={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"],clojure:[".clj",".cljs",".cljc"]},TH={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."},clojure:{status:"available",reason:"Source fallback covers Clojure namespace imports plus callable, callsite, and protocol/record member evidence for .clj, .cljs, and .cljc files."}};function Ot(e,t){let n=t.languages??tn(e),i=n.map(s=>{let a=fa(li(s),e);return{...a,language:s,resolvedBinary:a.resolvedBinary??void 0}}),r=n.includes("typescript")?{language:"typescript",...Pb(e,t.semantic?.typescript?.tsconfigs)}:void 0,o=Uu(e).map(s=>({label:s.label,coversExtensions:s.coversExtensions}));return{languages:n,indexers:i,semantic:r,checkers:o,gitAvailable:$H(e)}}function mi(e,t={}){let n=e.indexers.filter(s=>s.runnable).length,i=e.languages.length===0||n===0&&!t.hasIndexedGraph?"unavailable":n===e.indexers.length&&e.indexers.length>0?"available":"partial",r=i!=="unavailable",o=e.semantic?e.semantic.available?"available":"partial":"unavailable";return{languages:e.languages,matrix:e.languages.map(s=>_H(e,s,{hasIndexedGraph:t.hasIndexedGraph===!0})),capabilities:[{id:"indexing",label:"SCIP indexing",status:i,evidence:"graph-fact",reason:i==="available"?"All detected/configured language indexers are runnable.":t.hasIndexedGraph?`An indexed graph is present; ${n}/${e.indexers.length} detected/configured language indexers are runnable for refresh.`:`${n}/${e.indexers.length} detected/configured language indexers are runnable.`},{id:"semantic-typescript",label:"TypeScript semantic provider",status:o,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:r?"available":"unavailable",evidence:"heuristic",reason:r?"Similarity, migration, wrapper, stale-abstraction, and doc-drift detectors can run over the index.":"Heuristic detectors need an indexed code graph."},{id:"cleanup-verification",label:"Compiler cleanup verification",status:e.checkers.length>0?"available":"unavailable",evidence:"compiler",reason:e.checkers.length>0?e.checkers.map(s=>s.label).join(", "):"No project checker was detected for cleanup-plan --verify."},{id:"diff-gate",label:"Git diff gate",status:e.gitAvailable&&r?"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 _H(e,t,n){let i=e.indexers.find(l=>l.language===t),r=i?.runnable?"available":n.hasIndexedGraph?"partial":"unavailable",o=r!=="unavailable",s=TH[t],a=t==="typescript"?AH(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.`},c=MH(e,t);return{language:t,indexing:{id:"indexing",label:"SCIP indexing",status:r,evidence:"graph-fact",reason:r==="available"?`${i?.binaryLabel??t} is runnable${i?.resolvedBinary?` at ${i.resolvedBinary}`:""}.`:r==="partial"?`An indexed ${t} graph is present, but ${i?.binaryLabel??t} is not currently runnable for refresh.`:i?.note??`${t} indexing is not runnable in this project.`},sourceFacts:{id:"source-facts",label:"Source fallback",status:o?s.status:"unavailable",evidence:"heuristic",reason:o?s.reason:"Source fallback needs indexed documents before it can attach evidence."},semantic:a,detectors:{id:"detectors",label:"Cleanup detectors",status:o?"available":"unavailable",evidence:"heuristic",reason:o?"Graph-backed cleanup detectors can analyze this language; source and semantic precision depends on the rows above.":"Cleanup detectors need an indexed graph for this language."},cleanupVerification:{id:"cleanup-verification",label:"Cleanup verification",status:c.length>0?"available":"unavailable",evidence:"compiler",reason:c.length>0?c.map(l=>l.label).join(", "):`No detected checker covers ${Mb[t].join(", ")} files.`}}}function AH(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 MH(e,t){let n=new Set(Mb[t]);return e.checkers.filter(i=>i.coversExtensions.some(r=>n.has(r)))}function $H(e){try{return FH("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import{chmodSync as jH,existsSync as xa,readFileSync as Ca,writeFileSync as Ob}from"fs";import{join as bo}from"path";var yo="<!-- scip-query:agent-setup:begin -->",Ku="<!-- scip-query:agent-setup:end -->",$b="# scip-query:agent-setup";function So(){if(process.stdin.isTTY)return"";try{return Ca(0,"utf-8")}catch{return""}}function va(e){if(!e.trim())return!1;try{return JSON.parse(e).stop_hook_active===!0}catch{return!1}}function xo(e){let t=e.rootCauseGroups?.length??e.findings.length,n=[`scip-query diff-gate found ${e.findings.length} issue(s) in ${t} root-cause group(s) in this diff \u2014 fix or knowingly accept them before finishing:`],i=e.rootCauseGroups?.filter(r=>r.count>1)??[];for(let r of i)n.push(`- group [${r.check}] ${r.count} finding(s): ${r.message}`),n.push(` -> ${r.remediation}`);for(let r of e.findings)n.push(`- [${r.check}] ${r.message}`),n.push(` -> ${r.remediation}`);return n.join(`
884
+ `)}function Ra(e,t={}){let n={written:[],unchanged:[],skipped:[]};return OH(e,n),t.gitHook&&BH(e,n),n}function OH(e,t){let n=[yo,"## 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.",Ku].join(`
885
+ `);jb(e,"AGENTS.md",n,t);let i=xa(bo(e,"CLAUDE.md"))?Ca(bo(e,"CLAUDE.md"),"utf-8"):"";if(i.includes("@AGENTS.md")&&!i.includes(yo)){t.unchanged.push("CLAUDE.md");return}let r=[yo,"@AGENTS.md",Ku].join(`
886
+ `);jb(e,"CLAUDE.md",r,t)}function jb(e,t,n,i){let r=bo(e,t),o=xa(r)?Ca(r,"utf-8"):"",s;if(o.includes(yo)){let a=new RegExp(`${yo}[\\s\\S]*?${Ku}`);s=o.replace(a,n)}else s=o.length>0?`${o.replace(/\n*$/,`
863
887
 
864
888
  `)}${n}
865
889
  `:`${n}
866
- `;s===o?r.unchanged.push(t):(Gh(i,s),r.written.push(t))}function ej(e,t){let n=Ji(e,".git","hooks");if(!Vs(n)){t.skipped.push({target:".git/hooks/pre-commit",reason:"no .git/hooks directory (not a git repository?)"});return}let r=Ji(n,"pre-commit"),i=["#!/bin/sh",Uh,"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(`
867
- `);if(Vs(r)){let o=qs(r,"utf-8");if(o.includes(Uh)){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}}Gh(r,i),YO(r,493),t.written.push(".git/hooks/pre-commit")}var Xh="SCIP_QUERY_SKIP_HOOK_INSTALL",Yl="SCIP_QUERY_STOP_HOOK_MODE",sj="scip-query hook-",aj="scip-query diff-gate --hook";function Gs(e,t={}){let n=Qh(),r=t.env??process.env;return lj(r)?(n.skipped.push({target:"project agent hooks",reason:`${Xh}=1`}),n):(zh({provider:"codex",rootDir:qr(e,".codex"),configPath:qr(e,".codex","hooks.json"),label:".codex/hooks.json",createRoot:!0,result:n}),zh({provider:"claude",rootDir:qr(e,".claude"),configPath:qr(e,".claude","settings.json"),label:".claude/settings.json",createRoot:!0,result:n}),t.removeLegacyUserHooks!==!1&&cj({homeDir:t.homeDir,result:n}),n)}function cj(e={}){let t=e.result??Qh(),n=e.homeDir??ij();return Jh({configPath:qr(n,".codex","hooks.json"),label:"Codex/hooks.json",result:t}),Jh({configPath:qr(n,".claude","settings.json"),label:"Claude/settings.json",result:t}),t}function Qh(){return{installed:[],updated:[],unchanged:[],removed:[],skipped:[]}}function lj(e=process.env){let t=e[Xh];return t==="1"||t?.toLowerCase()==="true"||t?.toLowerCase()==="yes"}function uj(e=process.env){let t=e[Yl]?.toLowerCase();return t==="block"||t==="blocking"||t==="1"||t==="true"||t==="yes"?"block":t==="feedback"||t==="continue"?"feedback":"warn"}function zh(e){if(!e.createRoot&&!Qi(e.rootDir))return;let t=Yh(e.configPath,e.label,e.result);if(!t)return;let n=dj(t,e.provider);if(JSON.stringify(n)===JSON.stringify(t)){e.result.unchanged.push(e.label);return}let r=Qi(e.configPath);nj(oj(e.configPath),{recursive:!0}),Kh(e.configPath,`${JSON.stringify(n,null,2)}
868
- `),e.result[r?"updated":"installed"].push(e.label)}function Jh(e){if(!Qi(e.configPath))return;let t=Yh(e.configPath,e.label,e.result);if(!t)return;let n=t.hooks&&typeof t.hooks=="object"&&!Array.isArray(t.hooks)?t.hooks:{},r={...n},i=!1;for(let s of["SessionStart","UserPromptSubmit","Stop"]){let a=Array.isArray(n[s])?n[s]:[],c=Zh(a);(c.length!==a.length||JSON.stringify(c)!==JSON.stringify(a))&&(i=!0,c.length>0?r[s]=c:delete r[s])}if(!i)return;let o={...t};Object.keys(r).length>0?o.hooks=r:delete o.hooks,Kh(e.configPath,`${JSON.stringify(o,null,2)}
869
- `),e.result.removed.push(e.label)}function Yh(e,t,n){if(!Qi(e))return{};try{let r=JSON.parse(rj(e,"utf-8"));if(!r||typeof r!="object"||Array.isArray(r)){n.skipped.push({target:t,reason:"existing hook config is not a JSON object"});return}return r}catch(r){n.skipped.push({target:t,reason:`could not parse existing hook config: ${r instanceof Error?r.message:String(r)}`});return}}function dj(e,t){let n=e.hooks&&typeof e.hooks=="object"&&!Array.isArray(e.hooks)?e.hooks:{},r={...e,hooks:{...n}};for(let i of["SessionStart","UserPromptSubmit","Stop"]){let o=Array.isArray(n[i])?n[i]:[];r.hooks[i]=[...Zh(o),pj(t,i)]}return r}function Zh(e){return e.map(t=>({...t,hooks:Array.isArray(t.hooks)?t.hooks.filter(n=>!mj(n)):[]})).filter(t=>t.hooks.length>0)}function mj(e){if(!e||typeof e!="object")return!1;let t=e.command;return typeof t=="string"&&(t.startsWith(sj)||t===aj)}function pj(e,t){return t==="SessionStart"?{matcher:"startup|resume|clear|compact",hooks:[{type:"command",command:"scip-query hook-context",timeout:60,statusMessage:"Refreshing scip-query context"}]}:t==="UserPromptSubmit"?{hooks:[{type:"command",command:"scip-query hook-context",timeout:60,statusMessage:"Checking scip-query freshness"}]}:{hooks:[{type:"command",command:"scip-query hook-stop",timeout:30,statusMessage:"Running scip-query diff gate"}]}}async function ey(){let e=await hj(Ki());e&&console.log(JSON.stringify(e))}function ty(){let e=Ki();if(Us(e))return;let t=ny(e),n=ry(t);!n||!Qi(n.paths.dbPath)||vj(n,r=>{let i=Ti(r,{minTogether:6,skip:[]});i.findings.length!==0&&console.log(JSON.stringify(fj(i,uj())))})}function fj(e,t="warn"){let n=Xi(e),r=gj(e);return t==="block"?{decision:"block",reason:n}:t==="feedback"?{hookSpecificOutput:{hookEventName:"Stop",additionalContext:`${r}
890
+ `;s===o?i.unchanged.push(t):(Ob(r,s),i.written.push(t))}function BH(e,t){let n=bo(e,".git","hooks");if(!xa(n)){t.skipped.push({target:".git/hooks/pre-commit",reason:"no .git/hooks directory (not a git repository?)"});return}let i=bo(n,"pre-commit"),r=["#!/bin/sh",$b,"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(`
891
+ `);if(xa(i)){let o=Ca(i,"utf-8");if(o.includes($b)){if(o===r){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}}Ob(i,r),jH(i,493),t.written.push(".git/hooks/pre-commit")}var qb="SCIP_QUERY_SKIP_HOOK_INSTALL",Ju="SCIP_QUERY_STOP_HOOK_MODE",WH="scip-query hook-",GH="scip-query diff-gate --hook";function ka(e,t={}){let n=Ub(),i=t.env??process.env;return JH(i)?(n.skipped.push({target:"project agent hooks",reason:`${qb}=1`}),n):(Bb({provider:"codex",rootDir:ar(e,".codex"),configPath:ar(e,".codex","hooks.json"),label:".codex/hooks.json",createRoot:!0,result:n}),Bb({provider:"claude",rootDir:ar(e,".claude"),configPath:ar(e,".claude","settings.json"),label:".claude/settings.json",createRoot:!0,result:n}),t.removeLegacyUserHooks!==!1&&KH({homeDir:t.homeDir,result:n}),n)}function KH(e={}){let t=e.result??Ub(),n=e.homeDir??UH();return Hb({configPath:ar(n,".codex","hooks.json"),label:"Codex/hooks.json",result:t}),Hb({configPath:ar(n,".claude","settings.json"),label:"Claude/settings.json",result:t}),t}function Ub(){return{installed:[],updated:[],unchanged:[],removed:[],skipped:[]}}function JH(e=process.env){let t=e[qb];return t==="1"||t?.toLowerCase()==="true"||t?.toLowerCase()==="yes"}function XH(e=process.env){let t=e[Ju]?.toLowerCase();return t==="block"||t==="blocking"||t==="1"||t==="true"||t==="yes"?"block":t==="feedback"||t==="continue"?"feedback":"warn"}function Bb(e){if(!e.createRoot&&!Co(e.rootDir))return;let t=zb(e.configPath,e.label,e.result);if(!t)return;let n=QH(t,e.provider);if(JSON.stringify(n)===JSON.stringify(t)){e.result.unchanged.push(e.label);return}let i=Co(e.configPath);VH(zH(e.configPath),{recursive:!0}),Vb(e.configPath,`${JSON.stringify(n,null,2)}
892
+ `),e.result[i?"updated":"installed"].push(e.label)}function Hb(e){if(!Co(e.configPath))return;let t=zb(e.configPath,e.label,e.result);if(!t)return;let n=t.hooks&&typeof t.hooks=="object"&&!Array.isArray(t.hooks)?t.hooks:{},i={...n},r=!1;for(let s of["SessionStart","UserPromptSubmit","Stop"]){let a=Array.isArray(n[s])?n[s]:[],c=Wb(a);(c.length!==a.length||JSON.stringify(c)!==JSON.stringify(a))&&(r=!0,c.length>0?i[s]=c:delete i[s])}if(!r)return;let o={...t};Object.keys(i).length>0?o.hooks=i:delete o.hooks,Vb(e.configPath,`${JSON.stringify(o,null,2)}
893
+ `),e.result.removed.push(e.label)}function zb(e,t,n){if(!Co(e))return{};try{let i=JSON.parse(qH(e,"utf-8"));if(!i||typeof i!="object"||Array.isArray(i)){n.skipped.push({target:t,reason:"existing hook config is not a JSON object"});return}return i}catch(i){n.skipped.push({target:t,reason:`could not parse existing hook config: ${i instanceof Error?i.message:String(i)}`});return}}function QH(e,t){let n=e.hooks&&typeof e.hooks=="object"&&!Array.isArray(e.hooks)?e.hooks:{},i={...e,hooks:{...n}};for(let r of["SessionStart","UserPromptSubmit","Stop"]){let o=Array.isArray(n[r])?n[r]:[];i.hooks[r]=[...Wb(o),ZH(t,r)]}return i}function Wb(e){return e.map(t=>({...t,hooks:Array.isArray(t.hooks)?t.hooks.filter(n=>!YH(n)):[]})).filter(t=>t.hooks.length>0)}function YH(e){if(!e||typeof e!="object")return!1;let t=e.command;return typeof t=="string"&&(t.startsWith(WH)||t===GH)}function ZH(e,t){return t==="SessionStart"?{matcher:"startup|resume|clear|compact",hooks:[{type:"command",command:"scip-query hook-context",timeout:60,statusMessage:"Refreshing scip-query context"}]}:t==="UserPromptSubmit"?{hooks:[{type:"command",command:"scip-query hook-context",timeout:60,statusMessage:"Checking scip-query freshness"}]}:{hooks:[{type:"command",command:"scip-query hook-stop",timeout:30,statusMessage:"Running scip-query diff gate"}]}}async function Gb(){let e=await nV(So());e&&console.log(JSON.stringify(e))}function Kb(){let e=So();if(va(e))return;let t=Jb(e),n=Xb(t);!n||!Co(n.paths.dbPath)||cV(n,i=>{let r=no(i,{minTogether:6,skip:[]});r.findings.length!==0&&console.log(JSON.stringify(eV(r,XH())))})}function eV(e,t="warn"){let n=xo(e),i=tV(e);return t==="block"?{decision:"block",reason:n}:t==="feedback"?{hookSpecificOutput:{hookEventName:"Stop",additionalContext:`${i}
870
894
 
871
- This is non-error Stop hook feedback. Fix true findings, or explain why a finding is intentionally accepted before finishing.`}}:{systemMessage:`${r}
895
+ This is non-error Stop hook feedback. Fix true findings, or explain why a finding is intentionally accepted before finishing.`}}:{systemMessage:`${i}
872
896
 
873
- Stop hook allowed this turn to finish. Review these findings when relevant. Set ${Yl}=feedback to ask the agent to continue without a hook error, or ${Yl}=block to enforce the gate.`}}function gj(e){return Xi(e).replace(" \u2014 fix or knowingly accept them before finishing:"," \u2014 review these findings when relevant:")}async function hj(e){let t=ny(e),n=xj(t);if(n!=="SessionStart"&&n!=="UserPromptSubmit")return;let r=ry(t);if(!r)return;let i=await yj(r),o=n==="SessionStart"?bj(r.projectRoot,r.config,r.paths):Sj(String(t.prompt??"")),s=[i,o].filter(a=>!!a?.trim()).join(`
874
- `);if(s.trim())return{hookSpecificOutput:{hookEventName:n,additionalContext:s}}}async function yj(e){if($r(e.config).autoRefresh===!1)return;let n=Gn(e.projectRoot,e.config,e.paths);if(n.state!=="fresh")try{let r=await sn({projectRoot:e.projectRoot,languages:e.config.languages,outputScip:e.paths.indexPath,outputDb:e.paths.dbPath,pnpmWorkspaces:e.config.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:e.config.indexer?.typescript?.projectMode,typescriptProjects:e.config.indexer?.typescript?.projects,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:e.config.indexerConcurrency,trigger:{kind:"manual-cli",detail:"agent hook auto-refresh"},onStatus:()=>{}});return`scip-query auto-refresh: ${r.reused?"reused":"indexed"} ${r.languages.join(", ")} because the index was ${n.state}.`}catch(r){let i=r instanceof Error?r.message:String(r);return`scip-query auto-refresh skipped: index is ${n.state}, but refresh failed: ${i}`}}function bj(e,t,n){let r=Gn(e,t,n),i=kt(e,t),s=zn(i).capabilities.filter(c=>c.status!=="available").map(c=>c.label),a=i.languages.length>0?i.languages.join(", "):"none detected";return[`scip-query is available in this repository. Index state: ${r.state} (${r.reason})`,r.lastRefresh?`Last refresh: ${r.lastRefresh.result} by ${r.lastRefresh.trigger.kind} at ${r.lastRefresh.completedAt}.`:void 0,`Detected languages: ${a}.`,s.length>0?`Unavailable or partial capabilities: ${s.join(", ")}.`:"Core capabilities are available.","Use the scip-query router skill when exploring, planning, verifying, debugging, diagramming, or cleaning up code.","For non-trivial edits, plan with concrete-plan anchored by `scip-query plan-context <target>`, then verify with scip-verify."].filter(c=>c!==void 0).join(`
875
- `)}function Sj(e){let t=e.toLowerCase(),n=[];return Jn(t,["debug","bug","regression","failing","fails","error","wrong"])&&n.push("Debug or bug request: use scip-debug. For issue-quality triage, use scip-triage-issue."),Jn(t,["explain","how does","walk me through","trace","understand"])&&n.push("Exploration request: use scip-explore before answering behavioral questions."),Jn(t,["diagram","visualize","visualise","flow map","architecture map"])&&n.push("Diagram request: use scip-diagram and back every node and edge with scip-query evidence."),Jn(t,["implement","build","change","refactor","fix","add ","update "])&&n.push("Implementation request: plan first with concrete-plan and `scip-query plan-context <target>`, then verify with scip-verify."),Jn(t,["review","maintainability","architecture","boundary"])&&n.push("Review request: use scip-maintainability, scip-api-impact, or scip-verify depending on whether this is architecture, API impact, or post-change verification."),Jn(t,["setup","adopt","install","bootstrap"])&&n.push("Setup request: use scip-adoption or scip-query-setup; keep CI setup out of the default path."),Jn(t,["health","score","dossier","cleanup","dead code","duplicate","debloat","perfect code","as high as","maximize","maximise"])&&n.push("Health or cleanup request: use scip-health-audit before editing; use scip-health-improve when the user wants the score raised as high as reasonably possible."),n.length===0?"":["scip-query routing reminder:",...n].join(`
876
- `)}function Jn(e,t){return t.some(n=>e.includes(n))}function ny(e){if(!e.trim())return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function xj(e){let t=e.hook_event_name??e.hookEventName;return typeof t=="string"?t:void 0}function ry(e){let t=typeof e.cwd=="string"?e.cwd:process.cwd(),n=Cj(t);if(n)try{let r=_e(n),i=Ct(n,r);return{projectRoot:n,config:r,paths:i}}catch{return}}function Cj(e){try{return tj("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return}}function vj(e,t){let n={dbPath:e.paths.dbPath,indexPath:e.paths.indexPath,projectRoot:e.projectRoot,entryRoots:e.config.entryRoots,semantic:e.config.semantic,suppressions:e.config.suppressions,declaredCouplings:e.config.declaredCouplings,locality:e.config.locality},r=new Fr(n,rn(e.projectRoot));try{return t(r)}finally{r.close()}}import{existsSync as Zl,mkdirSync as Rj,symlinkSync as kj,readlinkSync as wj,unlinkSync as Lj}from"fs";import{join as Yi,dirname as iy,resolve as eu}from"path";import{homedir as tu,platform as Ij}from"os";import{fileURLToPath as Dj}from"url";var Pj=Ij()==="win32",nu=["scip-query","scip-query-setup","scip-adoption","scip-health-audit","scip-health-improve","scip-hyper-optimization","scip-api-impact","concrete-plan","scip-ai-cleanup","scip-debug","scip-explore","scip-triage-issue","scip-diagram","scip-debloat","scip-doc-reconcile","scip-directory-architecture","scip-maintainability","scip-react-maintainability","scip-vue-maintainability","scip-verify","scip-language-playbook"];function zs(e={}){let t=e.quiet?()=>{}:console.log,n=Dj(import.meta.url),r=eu(iy(n),"..","skills"),i=[Yi(tu(),".claude","skills"),Yi(tu(),".codex","skills"),Yi(tu(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[]};for(let s of i){let a=iy(s);if(!Zl(a))continue;Rj(s,{recursive:!0});let c=Nj(s);for(let l of nu){let u=Yi(r,l),d=Yi(s,l);if(!Zl(u)){o.skipped.push(`${c}/${l}`);continue}if(Zl(d)){try{let m=wj(d);if(eu(m)===eu(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}Lj(d)}kj(u,d,Pj?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function Nj(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{spawnSync as ky}from"child_process";import{existsSync as Wr,renameSync as vy,rmSync as CB}from"fs";import{dirname as vB,extname as RB}from"path";import{execFileSync as Ej,fork as Tj}from"child_process";import{statSync as _j,watch as Fj}from"fs";import{join as Aj,relative as $j}from"path";import Mj from"ignore";var Js=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;indexerConcurrency;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=$r(t.config),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=t.config.indexer?.typescript?.projectMode,this.typescriptProjects=t.config.indexer?.typescript?.projects,this.indexerConcurrency=t.config.indexerConcurrency,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onError=t.onError??(n=>console.error(n.message)),this.gitignoreFilter=rn(t.projectRoot),this.extraIgnore=Mj(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{let t=Fj(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.clearGitPollTimer(),this.setStatus({state:"idle"})}handleFileChange(t){let n=$j(this.projectRoot,Aj(this.projectRoot,t));n===".git"||n.startsWith(".git/")||this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||this.scheduleReindex({kind:"watch-source",detail:n})}scheduleReindex(t){if(this.pendingTrigger=Oj(this.pendingTrigger,t),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 n=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:n}),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 i=this.watchConfig.cooldownMs-t;this.dirty=!0;let o=Date.now()+i;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},i);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let n=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let r=Date.now();this.setStatus({state:"indexing",startedAt:r}),this.runReindex(n).then(i=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(i),this.dirty&&!this.stopped){let o=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:o,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(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(i instanceof Error?i:new Error(String(i))),this.setStatus({state:"idle"})})}runReindex(t){return new Promise((n,r)=>{let i=Date.now(),o=_e(this.projectRoot),s=Object.keys(o).length>0?o:this.config,a=Ct(this.projectRoot,s),c=s.indexer?.typescript,l=Tj(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:a.indexPath,SCIP_REINDEX_OUTPUT_DB:a.dbPath,SCIP_REINDEX_LANGUAGES:(s.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(s.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:c?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:c?.projectMode??this.typescriptProjectMode,projects:c?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_TRIGGER_KIND:t.kind,SCIP_REINDEX_TRIGGER_DETAIL:t.detail??""},stdio:"pipe"});l.on("exit",u=>{u===0?n(Date.now()-i):r(new Error(`Reindex worker exited with code ${u}`))}),l.on("error",r)})}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)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let t=this.lastGitState,n=this.readGitState();if(!t||!n||this.stopped){this.lastGitState=n;return}this.lastGitState=n;let r=t.head!==n.head,i=t.indexPath!==n.indexPath||t.indexMtimeMs!==n.indexMtimeMs||t.indexSize!==n.indexSize;r&&i?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):r?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):i&&this.scheduleReindex({kind:"watch-git-index",detail:n.indexPath??"index changed"})}readGitState(){let t=oy(this.projectRoot,["rev-parse","--git-path","index"]);if(!t)return null;let n={head:oy(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:t};try{let r=_j(t);n.indexMtimeMs=r.mtimeMs,n.indexSize=r.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function oy(e,t){try{return Ej("git",["-C",e,...t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return}}function Oj(e,t){return e?e.kind===t.kind?e.detail===t.detail?e:{kind:e.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${e.kind}, ${t.kind}`}:t}import{existsSync as Xj}from"fs";import{existsSync as jj,mkdirSync as Bj,readFileSync as Hj,writeFileSync as Vj}from"fs";import{dirname as qj,join as sy}from"path";function cy(e){let t={markdownPath:sy(e.projectRoot,"docs","scip-query","health-dossier.md"),jsonPath:sy(e.projectRoot,"docs","scip-query","health-dossier.json"),status:"written",written:[],unchanged:[]},n={...e,healthDossier:t};try{return ay(t.markdownPath,Uj(n),t),ay(t.jsonPath,`${JSON.stringify(n,null,2)}
877
- `,t),t}catch(r){return{...t,status:"failed",error:r instanceof Error?r.message:String(r)}}}function Uj(e){return`${["# scip-query Health Dossier","",`Generated: ${new Date().toISOString()}`,`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${Jj(e)}`,"","## Items That Need Attention","",...Wj(e),"","## Blocked Or Unavailable Checks","",...Gj(e),"","## Setup Smoke Tests","",...e.smokeTests.map(n=>`- ${n.status.toUpperCase()} \`${n.command}\`: ${n.evidence}`),"","## Setup Steps","",...e.steps.map(n=>`- ${n.status.toUpperCase()} ${n.label}${n.message?`: ${n.message}`:""}`),"","## Indexer Remediation","",...zj(e),"","## JSON","",`Machine-readable report: \`${Kj(e)}\``,""].join(`
878
- `)}`}function Wj(e){return e.health.issuesNeedAttention.length===0?["No prioritized health actions were reported."]:e.health.issuesNeedAttention.map(t=>`- ${t.category}: ${t.description} (${t.count}; impact ${t.impact}, effort ${t.effort}, evidence ${t.evidence}; confirmation ${t.confirmationStatus}; safe to start ${t.safeForAgentToStart?"yes":"no"}). ${t.recommendedNextStep}`)}function Gj(e){let t=[...e.smokeTests.filter(n=>n.status!=="pass").map(n=>`- ${n.status.toUpperCase()} \`${n.command}\`: ${n.evidence}`),...e.indexerRemediation.filter(n=>!n.after.runnable).map(n=>`- BLOCKED ${n.language}: ${n.recovery??`Install ${n.binaryLabel}.`}`)];return t.length>0?t:["No blocked or unavailable setup checks were reported."]}function zj(e){return e.indexerRemediation.length===0?["All detected indexers were already runnable."]:e.indexerRemediation.map(t=>{let n=t.after.runnable?"READY":"BLOCKED",r=t.attempted?"install attempted":"no automatic install attempted";return`- ${n} ${t.language}: ${t.binaryLabel} (${r})`})}function Jj(e){return e.health.score===null?`unavailable (${e.health.unavailableReason??"not checked"})`:`${e.health.score} (risk ${e.health.riskScore}, hygiene ${e.health.hygieneScore})`}function Kj(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function ay(e,t,n){if(Bj(qj(e),{recursive:!0}),(jj(e)?Hj(e,"utf-8"):null)===t){n.unchanged.push(e);return}Vj(e,t),n.written.push(e)}async function py(e={}){let t=[],{projectRoot:n,config:r,paths:i,dbPath:o}=Mr(),s=Ui();Q(t,{id:"scip-cli",label:"scip CLI",status:s?"ok":"warn",message:s?"scip CLI is available.":"scip CLI is not available; reindex may attempt install."});let a=zs({quiet:!0});Q(t,{id:"skills",label:"Agent skills",status:a.skipped.length>0?"warn":"ok",message:`${a.installed.length} installed, ${a.alreadyLinked.length} already linked, ${a.skipped.length} skipped.`,details:a.skipped.map(D=>`Skipped ${D}`)});let c=Ar(r,{projectRoot:n}),l=c.filter(D=>D.level==="error");Q(t,{id:"config",label:"Project config",status:l.length>0?"failed":c.length>0?"warn":"ok",message:c.length===0?"Config OK.":`${c.length} diagnostic(s), ${l.length} error(s).`,details:c.map(D=>`${D.level.toUpperCase()} ${D.path}: ${D.message}`)});let u=$r(r);Q(t,{id:"watch-refresh",label:"Watch refresh policy",status:u.autoRefresh===!1?"skipped":"ok",message:u.autoRefresh===!1?"Project hooks report freshness but do not auto-refresh stale indexes.":`Project hooks auto-refresh stale indexes; live watch defaults are ${u.debounceMs}ms debounce, ${u.cooldownMs}ms cooldown, and ${u.gitPollMs}ms Git polling.`});let d=kt(n,r);Q(t,{id:"readiness",label:"Indexer readiness",status:d.languages.length===0?"failed":d.indexers.some(D=>!D.runnable)?"warn":"ok",message:d.languages.length===0?"No supported project languages detected.":`Detected languages: ${d.languages.join(", ")}`,details:d.indexers.map(D=>`${D.runnable?"OK":D.installed?"WARN":"MISSING"} ${D.language}: ${D.binaryLabel}${D.note?` - ${D.note}`:""}`)});let m=oB(n,d,t),p=kt(n,r),g=null;if(p.languages.length===0||l.length>0)Q(t,{id:"reindex",label:"Index refresh",status:"skipped",message:p.languages.length===0?"Skipped because no supported languages were detected.":"Skipped because config validation has errors."});else{let D=[];try{g=await sn({projectRoot:n,languages:p.languages,outputScip:i.indexPath,outputDb:i.dbPath,pnpmWorkspaces:r.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:r.indexer?.typescript?.projectMode,typescriptProjects:r.indexer?.typescript?.projects,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:r.indexerConcurrency,trigger:{kind:"setup",detail:"scip-query setup"},onStatus:z=>D.push(z)}),Q(t,{id:"reindex",label:"Index refresh",status:g.skipped.length>0?"warn":"ok",message:`${g.reused?"Reused":"Indexed"} ${g.languages.join(", ")} in ${(g.durationMs/1e3).toFixed(1)}s.`,details:[...D,...g.skipped.map(z=>`Skipped ${z.language}: ${z.reason}`)]})}catch(z){Q(t,{id:"reindex",label:"Index refresh",status:"failed",message:Ks(z),details:D})}}let y=kt(n,r),h=zn(y),x=Gn(n,r,i);Q(t,{id:"capabilities",label:"Capability matrix",status:uB(h),message:dB(h)});let v=await aB(i.dbPath,t),R=null;try{R=Gs(n),Q(t,{id:"project-hooks",label:"Project agent hooks",status:R.skipped.length>0?"warn":"ok",message:`${R.installed.length} installed, ${R.updated.length} updated, ${R.unchanged.length} already configured, ${R.removed.length} legacy user hook config(s) cleaned up, ${R.skipped.length} skipped.`,details:[...R.removed.map(D=>`Removed legacy user-level ${D}`),...R.skipped.map(D=>`Skipped ${D.target}: ${D.reason}`)]})}catch(D){Q(t,{id:"project-hooks",label:"Project agent hooks",status:"failed",message:Ks(D)})}let L=null;try{L=Ws(n,{gitHook:e.gitHook}),Q(t,{id:"agent-guidance",label:"Project agent guidance",status:L.skipped.length>0?"warn":"ok",message:`${L.written.length} written, ${L.unchanged.length} already wired, ${L.skipped.length} skipped.`,details:L.skipped.map(D=>`Skipped ${D.target}: ${D.reason}`)})}catch(D){Q(t,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:Ks(D)})}let S=Qj({reindexResult:g,readiness:y,capabilities:h,freshness:x,health:v,hooksResult:R,agentResult:L,steps:t});Q(t,{id:"smoke-tests",label:"Setup smoke tests",status:Yj(S),message:Zj(S),details:S.map(D=>`${D.command}: ${D.status} - ${D.evidence}`)});let C={projectRoot:n,dbPath:o,configuredDbPath:i.dbPath,scipCliInstalled:s,languages:y.languages,steps:t,skills:a,initialReadiness:d,indexerRemediation:m,readiness:y,capabilities:h,freshness:x,reindex:g,health:v,smokeTests:S,healthDossier:null,hooks:R,setupAgent:L,filesWritten:L?.written??[],verdict:my(t,y)},P=cy(C);return C.healthDossier=P,C.filesWritten=[...C.filesWritten,...P.written],Q(t,{id:"health-dossier",label:"Health dossier",status:P.status==="failed"?"failed":"ok",message:P.status==="failed"?P.error:`${P.written.length} written, ${P.unchanged.length} unchanged.`,details:[P.markdownPath,P.jsonPath]}),C.verdict=my(t,y),C}function fy(e){if(console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${mB(e.health)}`),console.log(""),e.health.issuesNeedAttention.length===0)console.log("Items that need attention: none reported by the health pass.");else{console.log("Items that need attention:");for(let t of e.health.issuesNeedAttention)console.log(` - ${t.category}: ${t.description} (${t.count}; impact ${t.impact}, effort ${t.effort})`)}if(e.health.unavailableReason&&console.log(`Health pass: ${e.health.unavailableReason}`),e.health.warnings.length>0){console.log("Health warnings:");for(let t of e.health.warnings)console.log(` - ${t}`)}e.healthDossier&&console.log(`Health dossier: ${e.healthDossier.markdownPath}`),console.log(""),console.log("Setup steps:");for(let t of e.steps)console.log(` ${t.status.toUpperCase()} ${t.label}${t.message?` - ${t.message}`:""}`);console.log(""),console.log("Smoke tests:");for(let t of e.smokeTests)console.log(` ${t.status.toUpperCase()} ${t.command} - ${t.evidence}`);if(e.indexerRemediation.length>0){console.log(""),console.log("Indexer remediation:");for(let t of e.indexerRemediation){let n=t.after.runnable?"ready":"blocked",r=t.attempted?"attempted install":"manual action required";console.log(` - ${t.language}: ${n} (${r})`),t.recovery&&console.log(` ${t.recovery}`)}}}function Qj(e){let t=e.steps.find(o=>o.id==="reindex"),n=e.steps.find(o=>o.id==="project-hooks"),r=e.steps.find(o=>o.id==="agent-guidance"),i=e.steps.find(o=>o.id==="watch-refresh");return[{id:"reindex",command:"scip-query reindex",status:e.reindexResult?"pass":t?.status==="failed"?"fail":"unavailable",evidence:e.reindexResult?`${e.reindexResult.languages.join(", ")} indexed${e.reindexResult.reused?" from cache":""}.`:t?.message??"No reindex result was produced."},{id:"status",command:"scip-query status",status:e.freshness.state==="missing"?"fail":"pass",evidence:`Index freshness is ${e.freshness.state}: ${e.freshness.reason}`},{id:"config-validate",command:"scip-query config-validate",status:eB(e.steps),evidence:tB(e.steps)},{id:"capabilities",command:"scip-query capabilities",status:e.capabilities.matrix.length>0?"pass":"unavailable",evidence:e.capabilities.matrix.length>0?`${e.capabilities.matrix.length} language capability row(s) available.`:"No detected languages produced capability rows."},{id:"capability-matrix",command:"scip-query capability-matrix --json",status:e.capabilities.matrix.length>0?"pass":"unavailable",evidence:e.capabilities.matrix.length>0?nB(e.capabilities):"No detected languages produced capability rows."},{id:"health",command:"scip-query health",status:e.health.score===null?"unavailable":"pass",evidence:e.health.score===null?e.health.unavailableReason??"Health report was not available.":`Health score ${e.health.score}.`},{id:"diff-impact",command:"scip-query diff-impact --json",status:ly(e.readiness,e.freshness),evidence:uy(e.readiness,e.freshness)},{id:"diff-gate",command:"scip-query diff-gate --json",status:ly(e.readiness,e.freshness),evidence:uy(e.readiness,e.freshness)},{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:rB(e.capabilities),evidence:iB(e.capabilities)},{id:"setup-hooks",command:"scip-query setup-hooks",status:e.hooksResult?"pass":n?.status==="failed"?"fail":"unavailable",evidence:e.hooksResult?`${e.hooksResult.installed.length} installed, ${e.hooksResult.updated.length} updated, ${e.hooksResult.unchanged.length} already configured.`:n?.message??"Project agent hooks were not configured."},{id:"watch-refresh",command:`printf %s '{"hook_event_name":"SessionStart"}' | scip-query hook-context`,status:i?.status==="ok"?"pass":"unavailable",evidence:i?.message??"Watch refresh policy was not evaluated."},{id:"setup-agent",command:"scip-query setup-agent",status:e.agentResult?"pass":r?.status==="failed"?"fail":"unavailable",evidence:e.agentResult?`${e.agentResult.written.length} written, ${e.agentResult.unchanged.length} already wired, ${e.agentResult.skipped.length} skipped.`:r?.message??"Project agent guidance was not written."}]}function Yj(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable")?"warn":"ok"}function Zj(e){let t=e.filter(i=>i.status==="pass").length,n=e.filter(i=>i.status==="unavailable").length,r=e.filter(i=>i.status==="fail").length;return`${t} passed, ${n} unavailable, ${r} failed.`}function eB(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function tB(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function nB(e){let t=e.matrix.filter(n=>[n.indexing,n.sourceFacts,n.semantic,n.cleanupVerification].some(r=>r.status==="unavailable")).length;return`${e.matrix.length} language row(s), ${t} with unavailable capability cells.`}function ly(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function uy(e,t){if(!e.gitAvailable)return"Git is not available for this project.";let n=t.lastRefresh?` Last refresh: ${t.lastRefresh.result} by ${t.lastRefresh.trigger.kind} at ${t.lastRefresh.completedAt}.`:"";return`Git is available and index freshness is ${t.state}: ${t.reason}${n}`}function rB(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function iB(e){if(e.matrix.length===0)return"No detected languages produced capability rows.";let t=e.matrix.filter(i=>i.cleanupVerification.status==="available").length,n=e.matrix.filter(i=>i.cleanupVerification.status==="partial").length,r=e.matrix.filter(i=>i.cleanupVerification.status==="unavailable").length;return`${t} available, ${n} partial, ${r} unavailable cleanup-verification row(s).`}function oB(e,t,n){let r=[];if(t.languages.length===0)return Q(n,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped because no supported languages were detected."}),r;for(let s of t.indexers){if(s.runnable)continue;let a=qn(s.language),c=[],l=!s.installed&&!!a.installMethods?.length,u=!1;l?u=Os(a,m=>c.push(m)):s.installed?c.push(s.note??`${s.binaryLabel} is installed but is not runnable.`):a.installMethods?.length||c.push(`No auto-install method is configured for ${s.binaryLabel}.`);let d=sB(Ms(a,e));r.push({language:s.language,binaryLabel:s.binaryLabel,attempted:l,installed:u,before:s,after:d,messages:c,recovery:d.runnable?void 0:d.note??d.installUrl??`Install ${s.binaryLabel} and put it on PATH.`})}if(r.length===0)return Q(n,{id:"indexer-remediation",label:"Indexer remediation",status:"ok",message:"All detected indexers are runnable."}),r;let i=r.filter(s=>!s.after.runnable),o=r.filter(s=>s.attempted);return Q(n,{id:"indexer-remediation",label:"Indexer remediation",status:i.length>0?"warn":"ok",message:i.length===0?`${o.length} install attempt(s); all detected indexers are runnable.`:`${o.length} install attempt(s); ${i.length} indexer(s) still blocked.`,details:r.flatMap(s=>[`${s.language}: ${s.after.runnable?"ready":"blocked"}`,...s.messages])}),r}function sB(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function aB(e,t){if(!Xj(e)){let n="Skipped because no SQLite index database exists yet.";return Q(t,{id:"health",label:"Health audit",status:"skipped",message:n}),dy(n)}try{let n=await Ps({full:!0,json:!0});return Q(t,{id:"health",label:"Health audit",status:"ok",message:`Health score ${n.score}. ${n.actions.length} prioritized action(s).`}),cB(n)}catch(n){let r=Ks(n);return Q(t,{id:"health",label:"Health audit",status:"failed",message:r}),dy(r)}}function cB(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(lB),warnings:e.warnings??[]}}function lB(e){return{category:e.category,description:e.description,count:e.count,impact:e.impact,effort:e.effort,evidence:e.evidence,locRecoverable:e.locRecoverable,confirmationStatus:"unconfirmed",safeForAgentToStart:!1,recommendedNextStep:"Run scip-health-audit to confirm this signal; use scip-health-improve when the user wants confirmed issues fixed autonomously."}}function dy(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function my(e,t){return e.some(n=>n.status==="failed")?"blocked":t.indexers.some(n=>!n.runnable)||e.some(n=>n.status==="warn"||n.status==="skipped")?"partial":"ready"}function uB(e){let t=e.matrix.flatMap(n=>[n.indexing.status,n.sourceFacts.status,n.semantic.status,n.cleanupVerification.status]);return t.some(n=>n==="unavailable")||t.some(n=>n==="partial")?"warn":"ok"}function dB(e){return e.matrix.length===0?"No language capability rows.":`${e.matrix.filter(n=>n.indexing.status==="available").length}/${e.matrix.length} language(s) have available indexing.`}function mB(e){return e.score===null?`unavailable (${e.unavailableReason??"not checked"})`:`${e.score} (risk ${e.riskScore}, hygiene ${e.hygieneScore})`}function Q(e,t){e.push({...t,details:t.details?.filter(n=>n.trim()!=="")})}function Ks(e){return e instanceof Error?e.message:String(e)}import{existsSync as pB,mkdirSync as fB,writeFileSync as gB}from"fs";import{dirname as hB,join as yB}from"path";function gy(e,t={}){let n=yB(e,".github","workflows","scip-query.yml"),r=bB();return pB(n)&&!t.force?{path:n,written:!1,skipped:!0,content:r,reason:"Workflow already exists. Re-run with --force to overwrite."}:(t.dryRun||(fB(hB(n),{recursive:!0}),gB(n,r)),{path:n,written:!t.dryRun,skipped:!1,content:r})}function bB(){return`name: scip-query
897
+ Stop hook allowed this turn to finish. Review these findings when relevant. Set ${Ju}=feedback to ask the agent to continue without a hook error, or ${Ju}=block to enforce the gate.`}}function tV(e){return xo(e).replace(" \u2014 fix or knowingly accept them before finishing:"," \u2014 review these findings when relevant:")}async function nV(e){let t=Jb(e),n=sV(t);if(n!=="SessionStart"&&n!=="UserPromptSubmit")return;let i=Xb(t);if(!i)return;let r=await iV(i),o=n==="SessionStart"?rV(i.projectRoot,i.config,i.paths):oV(String(t.prompt??"")),s=[r,o].filter(a=>!!a?.trim()).join(`
898
+ `);if(s.trim())return{hookSpecificOutput:{hookEventName:n,additionalContext:s}}}async function iV(e){if(Zi(e.config).autoRefresh===!1)return;let n=Rn(e.projectRoot,e.config,e.paths);if(n.state!=="fresh")try{let i=await vn({projectRoot:e.projectRoot,languages:e.config.languages,outputScip:e.paths.indexPath,outputDb:e.paths.dbPath,pnpmWorkspaces:e.config.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:e.config.indexer?.typescript?.projectMode,typescriptProjects:e.config.indexer?.typescript?.projects,clojureConfigPath:e.config.indexer?.clojure?.configPath,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:e.config.indexerConcurrency,trigger:{kind:"manual-cli",detail:"agent hook auto-refresh"},onStatus:()=>{}});return`scip-query auto-refresh: ${i.reused?"reused":"indexed"} ${i.languages.join(", ")} because the index was ${n.state}.`}catch(i){let r=i instanceof Error?i.message:String(i);return`scip-query auto-refresh skipped: index is ${n.state}, but refresh failed: ${r}`}}function rV(e,t,n){let i=Rn(e,t,n),r=Ot(e,t),s=mi(r).capabilities.filter(c=>c.status!=="available").map(c=>c.label),a=r.languages.length>0?r.languages.join(", "):"none detected";return[`scip-query is available in this repository. Index state: ${i.state} (${i.reason})`,i.lastRefresh?`Last refresh: ${i.lastRefresh.result} by ${i.lastRefresh.trigger.kind} at ${i.lastRefresh.completedAt}.`:void 0,`Detected languages: ${a}.`,s.length>0?`Unavailable or partial capabilities: ${s.join(", ")}.`:"Core capabilities are available.","Use the scip-query router skill when exploring, planning, verifying, debugging, diagramming, or cleaning up code.","For non-trivial edits, plan with concrete-plan anchored by `scip-query plan-context <target>`, then verify with scip-verify."].filter(c=>c!==void 0).join(`
899
+ `)}function oV(e){let t=e.toLowerCase(),n=[];return pi(t,["debug","bug","regression","failing","fails","error","wrong"])&&n.push("Debug or bug request: use scip-debug. For issue-quality triage, use scip-triage-issue."),pi(t,["explain","how does","walk me through","trace","understand"])&&n.push("Exploration request: use scip-explore before answering behavioral questions."),pi(t,["diagram","visualize","visualise","flow map","architecture map"])&&n.push("Diagram request: use scip-diagram and back every node and edge with scip-query evidence."),pi(t,["implement","build","change","refactor","fix","add ","update "])&&n.push("Implementation request: plan first with concrete-plan and `scip-query plan-context <target>`, then verify with scip-verify."),pi(t,["review","maintainability","architecture","boundary"])&&n.push("Review request: use scip-maintainability, scip-api-impact, or scip-verify depending on whether this is architecture, API impact, or post-change verification."),pi(t,["setup","adopt","install","bootstrap"])&&n.push("Setup request: use scip-adoption or scip-query-setup; keep CI setup out of the default path."),pi(t,["health","score","dossier","cleanup","dead code","duplicate","debloat","perfect code","as high as","maximize","maximise"])&&n.push("Health or cleanup request: use scip-health-audit before editing; use scip-health-improve when the user wants the score raised as high as reasonably possible."),n.length===0?"":["scip-query routing reminder:",...n].join(`
900
+ `)}function pi(e,t){return t.some(n=>e.includes(n))}function Jb(e){if(!e.trim())return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function sV(e){let t=e.hook_event_name??e.hookEventName;return typeof t=="string"?t:void 0}function Xb(e){let t=typeof e.cwd=="string"?e.cwd:process.cwd(),n=aV(t);if(n)try{let i=Ue(n),r=Mt(n,i);return{projectRoot:n,config:i,paths:r}}catch{return}}function aV(e){try{return HH("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return}}function cV(e,t){let n={dbPath:e.paths.dbPath,indexPath:e.paths.indexPath,projectRoot:e.projectRoot,entryRoots:e.config.entryRoots,semantic:e.config.semantic,suppressions:e.config.suppressions,declaredCouplings:e.config.declaredCouplings,locality:e.config.locality},i=new Xi(n,Cn(e.projectRoot));try{return t(i)}finally{i.close()}}import{existsSync as Xu,mkdirSync as lV,symlinkSync as uV,readlinkSync as dV,unlinkSync as mV}from"fs";import{join as vo,dirname as Qb,resolve as Qu}from"path";import{homedir as Yu,platform as pV}from"os";import{fileURLToPath as fV}from"url";var gV=pV()==="win32",Zu=["scip-query","scip-query-setup","scip-adoption","scip-health-audit","scip-health-improve","scip-hyper-optimization","scip-api-impact","concrete-plan","scip-ai-cleanup","scip-debug","scip-explore","scip-triage-issue","scip-diagram","scip-debloat","scip-doc-reconcile","scip-directory-architecture","scip-maintainability","scip-react-maintainability","scip-vue-maintainability","scip-verify","scip-language-playbook"];function wa(e={}){let t=e.quiet?()=>{}:console.log,n=fV(import.meta.url),i=Qu(Qb(n),"..","skills"),r=[vo(Yu(),".claude","skills"),vo(Yu(),".codex","skills"),vo(Yu(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[]};for(let s of r){let a=Qb(s);if(!Xu(a))continue;lV(s,{recursive:!0});let c=hV(s);for(let l of Zu){let d=vo(i,l),u=vo(s,l);if(!Xu(d)){o.skipped.push(`${c}/${l}`);continue}if(Xu(u)){try{let m=dV(u);if(Qu(m)===Qu(d)){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}mV(u)}uV(d,u,gV?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function hV(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{spawnSync as yS}from"child_process";import{existsSync as gi,renameSync as gS,rmSync as aq}from"fs";import{dirname as cq,extname as lq}from"path";import{execFileSync as yV,fork as bV}from"child_process";import{statSync as SV,watch as xV}from"fs";import{join as CV,relative as vV}from"path";import RV from"ignore";var Pa=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=Zi(t.config),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=t.config.indexer?.typescript?.projectMode,this.typescriptProjects=t.config.indexer?.typescript?.projects,this.clojureConfigPath=t.config.indexer?.clojure?.configPath,this.indexerConcurrency=t.config.indexerConcurrency,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onError=t.onError??(n=>console.error(n.message)),this.gitignoreFilter=Cn(t.projectRoot),this.extraIgnore=RV(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{let t=xV(this.projectRoot,{recursive:!0},(n,i)=>{i&&!this.stopped&&this.handleFileChange(i)});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.clearGitPollTimer(),this.setStatus({state:"idle"})}handleFileChange(t){let n=vV(this.projectRoot,CV(this.projectRoot,t));n===".git"||n.startsWith(".git/")||this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||this.scheduleReindex({kind:"watch-source",detail:n})}scheduleReindex(t){if(this.pendingTrigger=kV(this.pendingTrigger,t),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 n=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:n}),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 o=Date.now()+r;this.setStatus({state:"cooldown",until:o,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=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let i=Date.now();this.setStatus({state:"indexing",startedAt:i}),this.runReindex(n).then(r=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(r),this.dirty&&!this.stopped){let o=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:o,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(t){return new Promise((n,i)=>{let r=Date.now(),o=Ue(this.projectRoot),s=Object.keys(o).length>0?o:this.config,a=Mt(this.projectRoot,s),c=s.indexer?.typescript,l=s.indexer?.clojure,d=bV(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:a.indexPath,SCIP_REINDEX_OUTPUT_DB:a.dbPath,SCIP_REINDEX_LANGUAGES:(s.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(s.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:c?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:c?.projectMode??this.typescriptProjectMode,projects:c?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:t.kind,SCIP_REINDEX_TRIGGER_DETAIL:t.detail??""},stdio:"pipe"});d.on("exit",u=>{u===0?n(Date.now()-r):i(new Error(`Reindex worker exited with code ${u}`))}),d.on("error",i)})}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)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let t=this.lastGitState,n=this.readGitState();if(!t||!n||this.stopped){this.lastGitState=n;return}this.lastGitState=n;let i=t.head!==n.head,r=t.indexPath!==n.indexPath||t.indexMtimeMs!==n.indexMtimeMs||t.indexSize!==n.indexSize;i&&r?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):i?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):r&&this.scheduleReindex({kind:"watch-git-index",detail:n.indexPath??"index changed"})}readGitState(){let t=Yb(this.projectRoot,["rev-parse","--git-path","index"]);if(!t)return null;let n={head:Yb(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:t};try{let i=SV(t);n.indexMtimeMs=i.mtimeMs,n.indexSize=i.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function Yb(e,t){try{return yV("git",["-C",e,...t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return}}function kV(e,t){return e?e.kind===t.kind?e.detail===t.detail?e:{kind:e.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${e.kind}, ${t.kind}`}:t}import{existsSync as MV}from"fs";import{existsSync as wV,mkdirSync as PV,readFileSync as IV,writeFileSync as LV}from"fs";import{dirname as DV,join as Zb}from"path";function tS(e){let t={markdownPath:Zb(e.projectRoot,"docs","scip-query","health-dossier.md"),jsonPath:Zb(e.projectRoot,"docs","scip-query","health-dossier.json"),status:"written",written:[],unchanged:[]},n={...e,healthDossier:t};try{return eS(t.markdownPath,EV(n),t),eS(t.jsonPath,`${JSON.stringify(n,null,2)}
901
+ `,t),t}catch(i){return{...t,status:"failed",error:i instanceof Error?i.message:String(i)}}}function EV(e){return`${["# scip-query Health Dossier","",`Generated: ${new Date().toISOString()}`,`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${_V(e)}`,"","## Items That Need Attention","",...NV(e),"","## Blocked Or Unavailable Checks","",...FV(e),"","## Setup Smoke Tests","",...e.smokeTests.map(n=>`- ${n.status.toUpperCase()} \`${n.command}\`: ${n.evidence}`),"","## Setup Steps","",...e.steps.map(n=>`- ${n.status.toUpperCase()} ${n.label}${n.message?`: ${n.message}`:""}`),"","## Indexer Remediation","",...TV(e),"","## JSON","",`Machine-readable report: \`${AV(e)}\``,""].join(`
902
+ `)}`}function NV(e){return e.health.issuesNeedAttention.length===0?["No prioritized health actions were reported."]:e.health.issuesNeedAttention.map(t=>`- ${t.category}: ${t.description} (${t.count}; impact ${t.impact}, effort ${t.effort}, evidence ${t.evidence}; confirmation ${t.confirmationStatus}; safe to start ${t.safeForAgentToStart?"yes":"no"}). ${t.recommendedNextStep}`)}function FV(e){let t=[...e.smokeTests.filter(n=>n.status!=="pass").map(n=>`- ${n.status.toUpperCase()} \`${n.command}\`: ${n.evidence}`),...e.indexerRemediation.filter(n=>!n.after.runnable).map(n=>`- BLOCKED ${n.language}: ${n.recovery??`Install ${n.binaryLabel}.`}`)];return t.length>0?t:["No blocked or unavailable setup checks were reported."]}function TV(e){return e.indexerRemediation.length===0?["All detected indexers were already runnable."]:e.indexerRemediation.map(t=>{let n=t.after.runnable?"READY":"BLOCKED",i=t.attempted?"install attempted":"no automatic install attempted";return`- ${n} ${t.language}: ${t.binaryLabel} (${i})`})}function _V(e){return e.health.score===null?`unavailable (${e.health.unavailableReason??"not checked"})`:`${e.health.score} (risk ${e.health.riskScore}, hygiene ${e.health.hygieneScore})`}function AV(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function eS(e,t,n){if(PV(DV(e),{recursive:!0}),(wV(e)?IV(e,"utf-8"):null)===t){n.unchanged.push(e);return}LV(e,t),n.written.push(e)}async function sS(e={}){let t=[],{projectRoot:n,config:i,paths:r,dbPath:o}=ai(),s=fo();ce(t,{id:"scip-cli",label:"scip CLI",status:s?"ok":"warn",message:s?"scip CLI is available.":"scip CLI is not available; reindex may attempt install."});let a=wa({quiet:!0});ce(t,{id:"skills",label:"Agent skills",status:a.skipped.length>0?"warn":"ok",message:`${a.installed.length} installed, ${a.alreadyLinked.length} already linked, ${a.skipped.length} skipped.`,details:a.skipped.map(k=>`Skipped ${k}`)});let c=Yi(i,{projectRoot:n}),l=c.filter(k=>k.level==="error");ce(t,{id:"config",label:"Project config",status:l.length>0?"failed":c.length>0?"warn":"ok",message:c.length===0?"Config OK.":`${c.length} diagnostic(s), ${l.length} error(s).`,details:c.map(k=>`${k.level.toUpperCase()} ${k.path}: ${k.message}`)});let d=Zi(i);ce(t,{id:"watch-refresh",label:"Watch refresh policy",status:d.autoRefresh===!1?"skipped":"ok",message:d.autoRefresh===!1?"Project hooks report freshness but do not auto-refresh stale indexes.":`Project hooks auto-refresh stale indexes; live watch defaults are ${d.debounceMs}ms debounce, ${d.cooldownMs}ms cooldown, and ${d.gitPollMs}ms Git polling.`});let u=Ot(n,i);ce(t,{id:"readiness",label:"Indexer readiness",status:u.languages.length===0?"failed":u.indexers.some(k=>!k.runnable)?"warn":"ok",message:u.languages.length===0?"No supported project languages detected.":`Detected languages: ${u.languages.join(", ")}`,details:u.indexers.map(k=>`${k.runnable?"OK":k.installed?"WARN":"MISSING"} ${k.language}: ${k.binaryLabel}${k.note?` - ${k.note}`:""}`)});let m=zV(n,u,t),p=Ot(n,i),f=null;if(p.languages.length===0||l.length>0)ce(t,{id:"reindex",label:"Index refresh",status:"skipped",message:p.languages.length===0?"Skipped because no supported languages were detected.":"Skipped because config validation has errors."});else{let k=[];try{f=await vn({projectRoot:n,languages:p.languages,outputScip:r.indexPath,outputDb:r.dbPath,pnpmWorkspaces:i.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:i.indexer?.typescript?.projectMode,typescriptProjects:i.indexer?.typescript?.projects,clojureConfigPath:i.indexer?.clojure?.configPath,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:i.indexerConcurrency,trigger:{kind:"setup",detail:"scip-query setup"},onStatus:T=>k.push(T)}),ce(t,{id:"reindex",label:"Index refresh",status:f.skipped.length>0?"warn":"ok",message:`${f.reused?"Reused":"Indexed"} ${f.languages.join(", ")} in ${(f.durationMs/1e3).toFixed(1)}s.`,details:[...k,...f.skipped.map(T=>`Skipped ${T.language}: ${T.reason}`)]})}catch(T){ce(t,{id:"reindex",label:"Index refresh",status:"failed",message:Ia(T),details:k})}}let g=Ot(n,i),b=mi(g),x=Rn(n,i,r);ce(t,{id:"capabilities",label:"Capability matrix",status:XV(b),message:QV(b)});let S=await GV(r.dbPath,t),R=null;try{R=ka(n),ce(t,{id:"project-hooks",label:"Project agent hooks",status:R.skipped.length>0?"warn":"ok",message:`${R.installed.length} installed, ${R.updated.length} updated, ${R.unchanged.length} already configured, ${R.removed.length} legacy user hook config(s) cleaned up, ${R.skipped.length} skipped.`,details:[...R.removed.map(k=>`Removed legacy user-level ${k}`),...R.skipped.map(k=>`Skipped ${k.target}: ${k.reason}`)]})}catch(k){ce(t,{id:"project-hooks",label:"Project agent hooks",status:"failed",message:Ia(k)})}let C=null;try{C=Ra(n,{gitHook:e.gitHook}),ce(t,{id:"agent-guidance",label:"Project agent guidance",status:C.skipped.length>0?"warn":"ok",message:`${C.written.length} written, ${C.unchanged.length} already wired, ${C.skipped.length} skipped.`,details:C.skipped.map(k=>`Skipped ${k.target}: ${k.reason}`)})}catch(k){ce(t,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:Ia(k)})}let y=$V({reindexResult:f,readiness:g,capabilities:b,freshness:x,health:S,hooksResult:R,agentResult:C,steps:t});ce(t,{id:"smoke-tests",label:"Setup smoke tests",status:jV(y),message:OV(y),details:y.map(k=>`${k.command}: ${k.status} - ${k.evidence}`)});let w={projectRoot:n,dbPath:o,configuredDbPath:r.dbPath,scipCliInstalled:s,languages:g.languages,steps:t,skills:a,initialReadiness:u,indexerRemediation:m,readiness:g,capabilities:b,freshness:x,reindex:f,health:S,smokeTests:y,healthDossier:null,hooks:R,setupAgent:C,filesWritten:C?.written??[],verdict:oS(t,g)},L=tS(w);return w.healthDossier=L,w.filesWritten=[...w.filesWritten,...L.written],ce(t,{id:"health-dossier",label:"Health dossier",status:L.status==="failed"?"failed":"ok",message:L.status==="failed"?L.error:`${L.written.length} written, ${L.unchanged.length} unchanged.`,details:[L.markdownPath,L.jsonPath]}),w.verdict=oS(t,g),w}function aS(e){if(console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${YV(e.health)}`),console.log(""),e.health.issuesNeedAttention.length===0)console.log("Items that need attention: none reported by the health pass.");else{console.log("Items that need attention:");for(let t of e.health.issuesNeedAttention)console.log(` - ${t.category}: ${t.description} (${t.count}; impact ${t.impact}, effort ${t.effort})`)}if(e.health.unavailableReason&&console.log(`Health pass: ${e.health.unavailableReason}`),e.health.warnings.length>0){console.log("Health warnings:");for(let t of e.health.warnings)console.log(` - ${t}`)}e.healthDossier&&console.log(`Health dossier: ${e.healthDossier.markdownPath}`),console.log(""),console.log("Setup steps:");for(let t of e.steps)console.log(` ${t.status.toUpperCase()} ${t.label}${t.message?` - ${t.message}`:""}`);console.log(""),console.log("Smoke tests:");for(let t of e.smokeTests)console.log(` ${t.status.toUpperCase()} ${t.command} - ${t.evidence}`);if(e.indexerRemediation.length>0){console.log(""),console.log("Indexer remediation:");for(let t of e.indexerRemediation){let n=t.after.runnable?"ready":"blocked",i=t.attempted?"attempted install":"manual action required";console.log(` - ${t.language}: ${n} (${i})`),t.recovery&&console.log(` ${t.recovery}`)}}}function $V(e){let t=e.steps.find(o=>o.id==="reindex"),n=e.steps.find(o=>o.id==="project-hooks"),i=e.steps.find(o=>o.id==="agent-guidance"),r=e.steps.find(o=>o.id==="watch-refresh");return[{id:"reindex",command:"scip-query reindex",status:e.reindexResult?"pass":t?.status==="failed"?"fail":"unavailable",evidence:e.reindexResult?`${e.reindexResult.languages.join(", ")} indexed${e.reindexResult.reused?" from cache":""}.`:t?.message??"No reindex result was produced."},{id:"status",command:"scip-query status",status:e.freshness.state==="missing"?"fail":"pass",evidence:`Index freshness is ${e.freshness.state}: ${e.freshness.reason}`},{id:"config-validate",command:"scip-query config-validate",status:BV(e.steps),evidence:HV(e.steps)},{id:"capabilities",command:"scip-query capabilities",status:e.capabilities.matrix.length>0?"pass":"unavailable",evidence:e.capabilities.matrix.length>0?`${e.capabilities.matrix.length} language capability row(s) available.`:"No detected languages produced capability rows."},{id:"capability-matrix",command:"scip-query capability-matrix --json",status:e.capabilities.matrix.length>0?"pass":"unavailable",evidence:e.capabilities.matrix.length>0?VV(e.capabilities):"No detected languages produced capability rows."},{id:"health",command:"scip-query health",status:e.health.score===null?"unavailable":"pass",evidence:e.health.score===null?e.health.unavailableReason??"Health report was not available.":`Health score ${e.health.score}.`},{id:"diff-impact",command:"scip-query diff-impact --json",status:nS(e.readiness,e.freshness),evidence:iS(e.readiness,e.freshness)},{id:"diff-gate",command:"scip-query diff-gate --json",status:nS(e.readiness,e.freshness),evidence:iS(e.readiness,e.freshness)},{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:qV(e.capabilities),evidence:UV(e.capabilities)},{id:"setup-hooks",command:"scip-query setup-hooks",status:e.hooksResult?"pass":n?.status==="failed"?"fail":"unavailable",evidence:e.hooksResult?`${e.hooksResult.installed.length} installed, ${e.hooksResult.updated.length} updated, ${e.hooksResult.unchanged.length} already configured.`:n?.message??"Project agent hooks were not configured."},{id:"watch-refresh",command:`printf %s '{"hook_event_name":"SessionStart"}' | scip-query hook-context`,status:r?.status==="ok"?"pass":"unavailable",evidence:r?.message??"Watch refresh policy was not evaluated."},{id:"setup-agent",command:"scip-query setup-agent",status:e.agentResult?"pass":i?.status==="failed"?"fail":"unavailable",evidence:e.agentResult?`${e.agentResult.written.length} written, ${e.agentResult.unchanged.length} already wired, ${e.agentResult.skipped.length} skipped.`:i?.message??"Project agent guidance was not written."}]}function jV(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable")?"warn":"ok"}function OV(e){let t=e.filter(r=>r.status==="pass").length,n=e.filter(r=>r.status==="unavailable").length,i=e.filter(r=>r.status==="fail").length;return`${t} passed, ${n} unavailable, ${i} failed.`}function BV(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function HV(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function VV(e){let t=e.matrix.filter(n=>[n.indexing,n.sourceFacts,n.semantic,n.cleanupVerification].some(i=>i.status==="unavailable")).length;return`${e.matrix.length} language row(s), ${t} with unavailable capability cells.`}function nS(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function iS(e,t){if(!e.gitAvailable)return"Git is not available for this project.";let n=t.lastRefresh?` Last refresh: ${t.lastRefresh.result} by ${t.lastRefresh.trigger.kind} at ${t.lastRefresh.completedAt}.`:"";return`Git is available and index freshness is ${t.state}: ${t.reason}${n}`}function qV(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function UV(e){if(e.matrix.length===0)return"No detected languages produced capability rows.";let t=e.matrix.filter(r=>r.cleanupVerification.status==="available").length,n=e.matrix.filter(r=>r.cleanupVerification.status==="partial").length,i=e.matrix.filter(r=>r.cleanupVerification.status==="unavailable").length;return`${t} available, ${n} partial, ${i} unavailable cleanup-verification row(s).`}function zV(e,t,n){let i=[];if(t.languages.length===0)return ce(n,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped because no supported languages were detected."}),i;for(let s of t.indexers){if(s.runnable)continue;let a=li(s.language),c=[],l=!s.installed&&!!a.installMethods?.length,d=!1;l?d=ga(a,m=>c.push(m)):s.installed?c.push(s.note??`${s.binaryLabel} is installed but is not runnable.`):a.installMethods?.length||c.push(`No auto-install method is configured for ${s.binaryLabel}.`);let u=WV(fa(a,e));i.push({language:s.language,binaryLabel:s.binaryLabel,attempted:l,installed:d,before:s,after:u,messages:c,recovery:u.runnable?void 0:u.note??u.installUrl??`Install ${s.binaryLabel} and put it on PATH.`})}if(i.length===0)return ce(n,{id:"indexer-remediation",label:"Indexer remediation",status:"ok",message:"All detected indexers are runnable."}),i;let r=i.filter(s=>!s.after.runnable),o=i.filter(s=>s.attempted);return ce(n,{id:"indexer-remediation",label:"Indexer remediation",status:r.length>0?"warn":"ok",message:r.length===0?`${o.length} install attempt(s); all detected indexers are runnable.`:`${o.length} install attempt(s); ${r.length} indexer(s) still blocked.`,details:i.flatMap(s=>[`${s.language}: ${s.after.runnable?"ready":"blocked"}`,...s.messages])}),i}function WV(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function GV(e,t){if(!MV(e)){let n="Skipped because no SQLite index database exists yet.";return ce(t,{id:"health",label:"Health audit",status:"skipped",message:n}),rS(n)}try{let n=await oa({full:!0,json:!0});return ce(t,{id:"health",label:"Health audit",status:"ok",message:`Health score ${n.score}. ${n.actions.length} prioritized action(s).`}),KV(n)}catch(n){let i=Ia(n);return ce(t,{id:"health",label:"Health audit",status:"failed",message:i}),rS(i)}}function KV(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(JV),warnings:e.warnings??[]}}function JV(e){return{category:e.category,description:e.description,count:e.count,impact:e.impact,effort:e.effort,evidence:e.evidence,locRecoverable:e.locRecoverable,confirmationStatus:"unconfirmed",safeForAgentToStart:!1,recommendedNextStep:"Run scip-health-audit to confirm this signal; use scip-health-improve when the user wants confirmed issues fixed autonomously."}}function rS(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function oS(e,t){return e.some(n=>n.status==="failed")?"blocked":t.indexers.some(n=>!n.runnable)||e.some(n=>n.status==="warn"||n.status==="skipped")?"partial":"ready"}function XV(e){let t=e.matrix.flatMap(n=>[n.indexing.status,n.sourceFacts.status,n.semantic.status,n.cleanupVerification.status]);return t.some(n=>n==="unavailable")||t.some(n=>n==="partial")?"warn":"ok"}function QV(e){return e.matrix.length===0?"No language capability rows.":`${e.matrix.filter(n=>n.indexing.status==="available").length}/${e.matrix.length} language(s) have available indexing.`}function YV(e){return e.score===null?`unavailable (${e.unavailableReason??"not checked"})`:`${e.score} (risk ${e.riskScore}, hygiene ${e.hygieneScore})`}function ce(e,t){e.push({...t,details:t.details?.filter(n=>n.trim()!=="")})}function Ia(e){return e instanceof Error?e.message:String(e)}import{existsSync as ZV,mkdirSync as eq,writeFileSync as tq}from"fs";import{dirname as nq,join as iq}from"path";function cS(e,t={}){let n=iq(e,".github","workflows","scip-query.yml"),i=rq();return ZV(n)&&!t.force?{path:n,written:!1,skipped:!0,content:i,reason:"Workflow already exists. Re-run with --force to overwrite."}:(t.dryRun||(eq(nq(n),{recursive:!0}),tq(n,i)),{path:n,written:!t.dryRun,skipped:!1,content:i})}function rq(){return`name: scip-query
879
903
 
880
904
  on:
881
905
  pull_request:
@@ -893,47 +917,48 @@ jobs:
893
917
  - run: npm ci
894
918
  - run: npx scip-query reindex
895
919
  - run: npx scip-query diff-gate --base "origin/\${{ github.base_ref }}"
896
- `}var hy=Symbol("option-value-source");function K(e){return(...t)=>{let{args:n,opts:r}=xB(t);et(i=>e({db:i,args:n,opts:r}))}}function Y(e,t){return K(n=>{let r=Ds(n.db,e,w(n.opts,"full"),{quiet:w(n.opts,"json")});t({...n,budget:r})})}function yy(e){return K(t=>Ur(t,e,{kind:"list"}))}function by(e){return K(t=>Ur(t,e,{kind:"table",headers:e.headers,dashWidths:e.dashWidths}))}function Sy(e){return K(t=>Ur(t,e,{kind:"grouped",key:e.key}))}function Kn(e){return K(t=>ou(t,e))}function xy(e){return Kn({commandName:e.commandName,query:e.query,emptyMessage:e.emptyMessage,heuristicLabel:e.heuristicLabel,before:e.before,render:(t,n)=>N.sectionedReport(e.sections(t,n)),toJson:e.toJson,after:e.after})}function nt(e,t){return Y(e,n=>ou(n,{...t,commandName:t.commandName??e}))}function Cy(e,t){return nt(e,{commandName:t.commandName??e,query:t.query,emptyMessage:t.emptyMessage,heuristicLabel:t.heuristicLabel,before:t.before,render:(n,r)=>N.sectionedReport(t.sections(n,r)),toJson:t.toJson,after:t.after})}function Mt(e,t){return Y(e,n=>Ur(n,{...t,commandName:e},{kind:"list"}))}function Xs(e,t){return Y(e,n=>Ur(n,{...t,commandName:e},{kind:"table",headers:t.headers,dashWidths:t.dashWidths}))}function Qs(e,t){return Y(e,n=>Ur(n,{...t,commandName:e},{kind:"grouped",key:t.key}))}function H(e,t){return String(e[t])}function ye(e,t){let n=e[t];return typeof n=="string"?n:void 0}function _(e,t){let n=e[t];return typeof n=="string"?n:void 0}function Le(e,t){let n=e[t];return typeof n=="number"?n:void 0}function w(e,t){return!!e[t]}function ru(e,t){let n=e[t];return Array.isArray(n)&&n.every(r=>typeof r=="string")?n:[]}function E(e,t,n){return Le(e,t)??n}function j(e,t,n){let r=Le(e,t),i=r!==void 0&&iu(e,t)!=="default";if(w(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 iu(e,t){return e[hy]?.(t)}function Ur(e,t,n){ou(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"?N.list(r,o=>t.format(o,i)):n.kind==="table"?N.table(n.headers,r.map(o=>t.format(o,i)),n.dashWidths):N.groupedByFile(r,o=>t.format(o,i),n.key?o=>n.key(o,i):void 0)},toJson:t.toJson,after:t.after})}function ou(e,t){let n=t.query(e);if(w(e.opts,"json")){M(t.commandName,e.args,e.opts,t.toJson?t.toJson(n,e):n);return}let r=t.emptyMessage?.(n,e);if(r){N.empty(r);return}t.heuristicLabel&&jr(t.heuristicLabel),t.before?.(n,e),t.render(n,e),t.after?.(n,e)}function M(e,t,n,r){console.log(JSON.stringify({command:e,args:SB(t),options:n,result:r},null,2))}function SB(e){return e.filter(t=>typeof t=="string"||typeof t=="number"||typeof t=="boolean")}function xB(e){if(e.length===0)return{args:[],opts:{}};let t=e[e.length-1];return{args:e.slice(0,-1),opts:de(t)}}function de(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,hy,{value:r=>t.getOptionValueSource(r),enumerable:!1}),n)}return e}var kB=new Set(["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php"]),wB=18e4,wy=100*1024*1024,LB=new Set(ga),IB=[["status","--json"],["status","--capabilities"],["capabilities","--json"],["capability-matrix","--json"],["stats"],["kind-counts"],["diff-impact","--json"],["diff-gate","--json"]],DB=[["health","--json"],["dead","--json","--full"],["isolated","--json","--full"],["similar","--json","--full"],["similar-files","--json","--full"],["recent-duplicates","--json","--full"],["doc-drift","--json","--full"],["unused-params","--json","--full"],["wrapper-candidates","--json","--full"],["passthrough-candidates","--json","--full"],["stale-abstractions","--json","--full"],["incomplete-migration","--json","--full"],["cleanup-plan","--verify","--json"],["complexity-hotspots","--json","--full"]];function PB(e){return e.filter(t=>kB.has(t))}async function Ly(e){let t=de(e),n=ge(),r=_e(n),i=Ct(n,r);try{let o=PB(ru(t,"language")),s=await sn({projectRoot:n,languages:o.length>0?o:r.languages,outputScip:i.indexPath,outputDb:i.dbPath,pnpmWorkspaces:w(t,"pnpmWorkspaces")||r.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:r.indexer?.typescript?.projectMode,typescriptProjects:r.indexer?.typescript?.projects,skipIfUnchanged:!w(t,"force"),allowPartial:w(t,"allowPartial"),indexerConcurrency:Le(t,"indexerConcurrency")??r.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query reindex"}});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 Iy(){let e=ge(),t=Or(e);try{let n=on({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 Dy(e){let t=de(e),n=ge(),r=Or(n);try{let i=Bl({projectRoot:n,dbPath:r,tsconfig:_(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 Py(e){let t=de(e);et(n=>{let r=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),i=bt(n,{base:_(t,"base")}),o=is(n,r,i.changedFiles,i.changedRanges);console.log(JSON.stringify(o))})}async function Ny(e){let t=de(e);try{let n=await Sg({base:_(t,"base")});if(w(t,"json")){M("diff-impact",[],t,n);return}Cg(n)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function Ey(e,t){let n=de(t),r=String(e).split(",").filter(i=>i.length>0);et(i=>{let o=[];for(let c of r)_r.includes(c)||(console.error(`error: Unknown health phase: ${c}`),process.exit(1)),o.push(c);let s={scope:_(n,"scope"),full:w(n,"full")},a=o.length===1?Mi(i,o[0],s):rl(i,o,s);console.log(JSON.stringify(a))})}async function Ty(e){let t=de(e);if(w(t,"writeBaseline")||w(t,"baseline")){MB(t);return}try{let n=await Ps({scope:_(t,"scope"),full:!0,json:w(t,"json")});if(w(t,"json")){M("health",[],t,n);return}bg(n,!1)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function _y(e){let t=de(e),n=ge(),r=Le(t,"timeoutMs")??wB,i={projectRoot:n,...AB(n),index:su(Wr(Or(n))),commands:[]};w(t,"coldIndex")&&(i.coldIndex=await NB(n),i.warmIndex=await EB(n),i.index=su(Wr(Or(n))));for(let o of TB(t))i.commands.push(FB(n,o,r));if(w(t,"json")){M("bench",[],t,i);return}$B(i)}async function NB(e){let t=_e(e),n=Ct(e,t),r=vB(n.dbPath),i=`${r}.bench-backup-${Date.now()}`,o=!1;Wr(r)&&(vy(r,i),o=!0);try{let s=await Fy(()=>sn({projectRoot:e,languages:t.languages,outputScip:n.indexPath,outputDb:n.dbPath,pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:t.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query bench --cold-index"},onStatus:()=>{}}));return o&&CB(i,{recursive:!0,force:!0}),{durationMs:s.durationMs,result:s.value.reused?"reused":"rebuilt",languages:s.value.languages,...Ay(e)}}catch(s){throw o&&!Wr(r)&&vy(i,r),s}}async function EB(e){let t=_e(e),n=Ct(e,t),r=await Fy(()=>sn({projectRoot:e,languages:t.languages,outputScip:n.indexPath,outputDb:n.dbPath,pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:t.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query bench warm index"},onStatus:()=>{}}));return{durationMs:r.durationMs,result:r.value.reused?"reused":"rebuilt",languages:r.value.languages,...Ay(e)}}async function Fy(e){let t=performance.now(),n=await e();return{durationMs:Math.round(performance.now()-t),value:n}}function Ay(e){return Wr(Or(e))?et(t=>{let n=Oe(t);return{files:n.documents,symbols:n.symbols}}):{}}function TB(e){let t=ru(e,"command");return t.length>0?t.map(_B).filter(n=>n.length>0):[...IB.map(n=>[...n]),...w(e,"includeHeavy")?DB.map(n=>[...n]):[]]}function _B(e){return e.trim().split(/\s+/).filter(Boolean).filter((t,n)=>!(n===0&&t==="scip-query"))}function FB(e,t,n){let r=performance.now(),i=ky(process.execPath,[...process.execArgv,process.argv[1]??"",...t],{cwd:e,encoding:"buffer",maxBuffer:wy,timeout:n}),o=Math.round(performance.now()-r);return{command:`scip-query ${t.join(" ")}`,durationMs:o,exitCode:i.status,signal:i.signal,timedOut:i.error?.name==="ETIMEDOUT",stdoutBytes:i.stdout?.length??0,stderrBytes:i.stderr?.length??0}}function AB(e){let t=ky("git",["-C",e,"ls-files","-co","--exclude-standard"],{encoding:"utf8",maxBuffer:wy});if(t.status!==0)return{repoFiles:null,sourceFiles:null};let n=t.stdout.split(`
897
- `).filter(Boolean);return{repoFiles:n.length,sourceFiles:n.filter(r=>LB.has(RB(r).toLowerCase())).length}}function $B(e){console.log("scip-query bench"),console.log(`Project: ${e.projectRoot}`),console.log(`Repo files: ${e.repoFiles??"unknown"}; source-like files: ${e.sourceFiles??"unknown"}`),e.index&&console.log(`Index: ${e.index.files} files, ${e.index.symbols} symbols, ${Vn(e.index.indexSizeBytes)}`),e.coldIndex&&Ry("Cold index",e.coldIndex),e.warmIndex&&Ry("Warm index",e.warmIndex),console.log(`
898
- Commands:`);for(let t of[...e.commands].sort((n,r)=>r.durationMs-n.durationMs)){let n=t.timedOut?"timeout":t.exitCode===0?"ok":`exit ${t.exitCode??t.signal??"unknown"}`;console.log(` ${String(t.durationMs).padStart(7)}ms ${n.padEnd(10)} ${String(t.stdoutBytes).padStart(8)}B out ${t.command}`)}}function Ry(e,t){console.log(`${e}: ${t.durationMs}ms, ${t.result}, ${t.languages.join(", ")}${t.files?`, ${t.files} files`:""}${t.symbols?`, ${t.symbols} symbols`:""}`)}function MB(e){let t=_(e,"scope");et(n=>{if(w(e,"writeBaseline")){let i=Qc(n,{scope:t});console.log(`Baseline written to ${i.path} (${i.findingCount} finding(s)).`);return}let r=Pi(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 $y(){let e=zs(),t=e.installed.length+e.alreadyLinked.length;console.log(`
899
- ${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 My(e){let t=de(e),n=ge(),r=Gs(n);if(w(t,"json")){M("setup-hooks",[],t,r);return}for(let o of r.installed)console.log(` done: ${o}`);for(let o of r.updated)console.log(` update: ${o}`);for(let o of r.unchanged)console.log(` ok: ${o} (already configured)`);for(let o of r.removed)console.log(` remove: legacy user-level ${o}`);for(let o of r.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);r.installed.length+r.updated.length+r.unchanged.length>0?(console.log(`
920
+ `}var lS=Symbol("option-value-source");function ne(e){return(...t)=>{let{args:n,opts:i}=sq(t);ut(r=>e({db:r,args:n,opts:i}))}}function le(e,t){return ne(n=>{let i=ra(n.db,e,P(n.opts,"full"),{quiet:P(n.opts,"json")});t({...n,budget:i})})}function uS(e){return ne(t=>cr(t,e,{kind:"list"}))}function dS(e){return ne(t=>cr(t,e,{kind:"table",headers:e.headers,dashWidths:e.dashWidths}))}function mS(e){return ne(t=>cr(t,e,{kind:"grouped",key:e.key}))}function fi(e){return ne(t=>nd(t,e))}function pS(e){return fi({commandName:e.commandName,query:e.query,emptyMessage:e.emptyMessage,heuristicLabel:e.heuristicLabel,before:e.before,render:(t,n)=>N.sectionedReport(e.sections(t,n)),toJson:e.toJson,after:e.after})}function dt(e,t){return le(e,n=>nd(n,{...t,commandName:t.commandName??e}))}function fS(e,t){return dt(e,{commandName:t.commandName??e,query:t.query,emptyMessage:t.emptyMessage,heuristicLabel:t.heuristicLabel,before:t.before,render:(n,i)=>N.sectionedReport(t.sections(n,i)),toJson:t.toJson,after:t.after})}function nn(e,t){return le(e,n=>cr(n,{...t,commandName:e},{kind:"list"}))}function La(e,t){return le(e,n=>cr(n,{...t,commandName:e},{kind:"table",headers:t.headers,dashWidths:t.dashWidths}))}function Da(e,t){return le(e,n=>cr(n,{...t,commandName:e},{kind:"grouped",key:t.key}))}function z(e,t){return String(e[t])}function ke(e,t){let n=e[t];return typeof n=="string"?n:void 0}function _(e,t){let n=e[t];return typeof n=="string"?n:void 0}function Ae(e,t){let n=e[t];return typeof n=="number"?n:void 0}function P(e,t){return!!e[t]}function ed(e,t){let n=e[t];return Array.isArray(n)&&n.every(i=>typeof i=="string")?n:[]}function F(e,t,n){return Ae(e,t)??n}function V(e,t,n){let i=Ae(e,t),r=i!==void 0&&td(e,t)!=="default";if(P(e,"full")){if(r)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 i??n}function td(e,t){return e[lS]?.(t)}function cr(e,t,n){nd(e,{commandName:t.commandName,query:t.query,emptyMessage:(i,r)=>i.length===0&&t.emptyMessage?t.emptyMessage(r):void 0,heuristicLabel:t.heuristicLabel,render:(i,r)=>{n.kind==="list"?N.list(i,o=>t.format(o,r)):n.kind==="table"?N.table(n.headers,i.map(o=>t.format(o,r)),n.dashWidths):N.groupedByFile(i,o=>t.format(o,r),n.key?o=>n.key(o,r):void 0)},toJson:t.toJson,after:t.after})}function nd(e,t){let n=t.query(e);if(P(e.opts,"json")){B(t.commandName,e.args,e.opts,t.toJson?t.toJson(n,e):n);return}let i=t.emptyMessage?.(n,e);if(i){N.empty(i);return}t.heuristicLabel&&tr(t.heuristicLabel),t.before?.(n,e),t.render(n,e),t.after?.(n,e)}function B(e,t,n,i){console.log(JSON.stringify({command:e,args:oq(t),options:n,result:i},null,2))}function oq(e){return e.filter(t=>typeof t=="string"||typeof t=="number"||typeof t=="boolean")}function sq(e){if(e.length===0)return{args:[],opts:{}};let t=e[e.length-1];return{args:e.slice(0,-1),opts:xe(t)}}function xe(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,lS,{value:i=>t.getOptionValueSource(i),enumerable:!1}),n)}return e}var uq=new Set(["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php","clojure"]),dq=18e4,bS=100*1024*1024,mq=new Set(Ga),pq=[["status","--json"],["status","--capabilities"],["capabilities","--json"],["capability-matrix","--json"],["stats"],["kind-counts"],["diff-impact","--json"],["diff-gate","--json"]],fq=[["health","--json"],["dead","--json","--full"],["isolated","--json","--full"],["similar","--json","--full"],["similar-files","--json","--full"],["recent-duplicates","--json","--full"],["doc-drift","--json","--full"],["unused-params","--json","--full"],["wrapper-candidates","--json","--full"],["passthrough-candidates","--json","--full"],["stale-abstractions","--json","--full"],["incomplete-migration","--json","--full"],["cleanup-plan","--verify","--json"],["complexity-hotspots","--json","--full"]];function gq(e){return e.filter(t=>uq.has(t))}async function SS(e){let t=xe(e),n=Ne(),i=Ue(n),r=Mt(n,i);try{let o=gq(ed(t,"language")),s=await vn({projectRoot:n,languages:o.length>0?o:i.languages,outputScip:r.indexPath,outputDb:r.dbPath,pnpmWorkspaces:P(t,"pnpmWorkspaces")||i.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:i.indexer?.typescript?.projectMode,typescriptProjects:i.indexer?.typescript?.projects,clojureConfigPath:i.indexer?.clojure?.configPath,skipIfUnchanged:!P(t,"force"),allowPartial:P(t,"allowPartial"),indexerConcurrency:Ae(t,"indexerConcurrency")??i.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query reindex"}});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 xS(){let e=Ne(),t=er(e);try{let n=ua({projectRoot:e,dbPath:t,onStatus:i=>console.log(i)});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 CS(e){let t=xe(e),n=Ne(),i=er(n);try{let r=Mu({projectRoot:n,dbPath:i,tsconfig:_(t,"project")??"frontend/tsconfig.scip.json",onStatus:o=>console.log(o)});console.log(`Vue files: ${r.vueFiles}; resolved references: ${r.resolvedReferences}; inserted mentions: ${r.insertedMentions}.`)}catch(r){console.error(`error: ${r instanceof Error?r.message:r}`),process.exit(1)}}function vS(e){let t=xe(e);ut(n=>{let i=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),r=Tt(n,{base:_(t,"base")}),o=Ts(n,i,r.changedFiles,r.changedRanges);console.log(JSON.stringify(o))})}async function RS(e){let t=xe(e);try{let n=await uy({base:_(t,"base")});if(P(t,"json")){B("diff-impact",[],t,n);return}my(n)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function kS(e,t){let n=xe(t),i=String(e).split(",").filter(r=>r.length>0);ut(r=>{let o=[];for(let c of i)Ji.includes(c)||(console.error(`error: Unknown health phase: ${c}`),process.exit(1)),o.push(c);let s={scope:_(n,"scope"),full:P(n,"full")},a=o.length===1?ao(r,o[0],s):Zl(r,o,s);console.log(JSON.stringify(a))})}async function wS(e){let t=xe(e);if(P(t,"writeBaseline")||P(t,"baseline")){kq(t);return}try{let n=await oa({scope:_(t,"scope"),full:!0,json:P(t,"json")});if(P(t,"json")){B("health",[],t,n);return}ly(n,!1)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function PS(e){let t=xe(e),n=Ne(),i=Ae(t,"timeoutMs")??dq,r=P(t,"progress"),o=P(t,"profile"),s=_(t,"profileOut"),a={projectRoot:n,...vq(n),index:id(gi(er(n))),commands:[]};P(t,"coldIndex")&&(lr(r,"cold index started"),a.coldIndex=await hq(n),lr(r,`cold index finished ${a.coldIndex.durationMs}ms`),Bn({type:"bench-index",phase:"cold-index",projectRoot:n,durationMs:a.coldIndex.durationMs,result:a.coldIndex.result,files:a.coldIndex.files,symbols:a.coldIndex.symbols},s),lr(r,"warm index started"),a.warmIndex=await yq(n),lr(r,`warm index finished ${a.warmIndex.durationMs}ms`),Bn({type:"bench-index",phase:"warm-index",projectRoot:n,durationMs:a.warmIndex.durationMs,result:a.warmIndex.result,files:a.warmIndex.files,symbols:a.warmIndex.symbols},s),a.index=id(gi(er(n))));for(let c of bq(t))a.commands.push(xq(n,c,i,{progress:r,profile:o,profileOut:s}));if(P(t,"json")){B("bench",[],t,a);return}Rq(a)}async function hq(e){let t=Ue(e),n=Mt(e,t),i=cq(n.dbPath),r=`${i}.bench-backup-${Date.now()}`,o=!1;gi(i)&&(gS(i,r),o=!0);try{let s=await IS(()=>vn({projectRoot:e,languages:t.languages,outputScip:n.indexPath,outputDb:n.dbPath,pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:t.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query bench --cold-index"},onStatus:()=>{}}));return o&&aq(r,{recursive:!0,force:!0}),{durationMs:s.durationMs,result:s.value.reused?"reused":"rebuilt",languages:s.value.languages,...LS(e)}}catch(s){throw o&&!gi(i)&&gS(r,i),s}}async function yq(e){let t=Ue(e),n=Mt(e,t),i=await IS(()=>vn({projectRoot:e,languages:t.languages,outputScip:n.indexPath,outputDb:n.dbPath,pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:t.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query bench warm index"},onStatus:()=>{}}));return{durationMs:i.durationMs,result:i.value.reused?"reused":"rebuilt",languages:i.value.languages,...LS(e)}}async function IS(e){let t=performance.now(),n=await e();return{durationMs:Math.round(performance.now()-t),value:n}}function LS(e){return gi(er(e))?ut(t=>{let n=We(t);return{files:n.documents,symbols:n.symbols}}):{}}function bq(e){let t=ed(e,"command");return t.length>0?t.map(Sq).filter(n=>n.length>0):[...pq.map(n=>[...n]),...P(e,"includeHeavy")?fq.map(n=>[...n]):[]]}function Sq(e){return e.trim().split(/\s+/).filter(Boolean).filter((t,n)=>!(n===0&&t==="scip-query"))}function xq(e,t,n,i={}){let r=`scip-query ${t.join(" ")}`;lr(i.progress,`${r} started`),Bn({type:"bench-command-start",command:r,projectRoot:e},i.profileOut);let o=performance.now(),s=i.profile?Cq(r,i.profileOut):process.env,a=yS(process.execPath,[...process.execArgv,process.argv[1]??"",...t],{cwd:e,env:s,encoding:"buffer",maxBuffer:bS,timeout:n}),c=Math.round(performance.now()-o),l={command:r,durationMs:c,exitCode:a.status,signal:a.signal,timedOut:a.error?.name==="ETIMEDOUT",stdoutBytes:a.stdout?.length??0,stderrBytes:a.stderr?.length??0,...i.profileOut?{profilePath:i.profileOut}:{}};return lr(i.progress,`${r} finished ${c}ms exit=${l.exitCode??l.signal??"unknown"}${l.timedOut?" timed-out":""}`),Bn({type:"bench-command-finish",command:r,projectRoot:e,durationMs:c,exitCode:l.exitCode,signal:l.signal,timedOut:l.timedOut,stdoutBytes:l.stdoutBytes,stderrBytes:l.stderrBytes},i.profileOut),l}function lr(e,t){e&&process.stderr.write(`[bench] ${t}
921
+ `)}function Cq(e,t){return{...process.env,SCIP_QUERY_PROFILE:"1",SCIP_QUERY_PROFILE_COMMAND:e,...t?{SCIP_QUERY_PROFILE_OUT:t}:{}}}function vq(e){let t=yS("git",["-C",e,"ls-files","-co","--exclude-standard"],{encoding:"utf8",maxBuffer:bS});if(t.status!==0)return{repoFiles:null,sourceFiles:null};let n=t.stdout.split(`
922
+ `).filter(Boolean);return{repoFiles:n.length,sourceFiles:n.filter(i=>mq.has(lq(i).toLowerCase())).length}}function Rq(e){console.log("scip-query bench"),console.log(`Project: ${e.projectRoot}`),console.log(`Repo files: ${e.repoFiles??"unknown"}; source-like files: ${e.sourceFiles??"unknown"}`),e.index&&console.log(`Index: ${e.index.files} files, ${e.index.symbols} symbols, ${ci(e.index.indexSizeBytes)}`),e.coldIndex&&hS("Cold index",e.coldIndex),e.warmIndex&&hS("Warm index",e.warmIndex),console.log(`
923
+ Commands:`);for(let t of[...e.commands].sort((n,i)=>i.durationMs-n.durationMs)){let n=t.timedOut?"timeout":t.exitCode===0?"ok":`exit ${t.exitCode??t.signal??"unknown"}`;console.log(` ${String(t.durationMs).padStart(7)}ms ${n.padEnd(10)} ${String(t.stdoutBytes).padStart(8)}B out ${t.command}`)}}function hS(e,t){console.log(`${e}: ${t.durationMs}ms, ${t.result}, ${t.languages.join(", ")}${t.files?`, ${t.files} files`:""}${t.symbols?`, ${t.symbols} symbols`:""}`)}function kq(e){let t=_(e,"scope");ut(n=>{if(P(e,"writeBaseline")){let r=Gl(n,{scope:t});console.log(`Baseline written to ${r.path} (${r.findingCount} finding(s)).`);return}let i=Zr(n,{scope:t});if(i.fixedFindings.length>0&&console.log(`${i.fixedFindings.length} finding(s) fixed since baseline. Re-run --write-baseline to ratchet down.`),i.newFindings.length===0){console.log(`OK: no new findings vs baseline (${i.baselineCount} baselined, ${i.current.length} current).`);return}console.log(`FAIL: ${i.newFindings.length} new finding(s) vs ${i.baselinePath}:`);for(let r of i.newFindings)console.log(` + ${r}`);process.exitCode=1})}function DS(){let e=wa(),t=e.installed.length+e.alreadyLinked.length;console.log(`
924
+ ${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 ES(e){let t=xe(e),n=Ne(),i=ka(n);if(P(t,"json")){B("setup-hooks",[],t,i);return}for(let o of i.installed)console.log(` done: ${o}`);for(let o of i.updated)console.log(` update: ${o}`);for(let o of i.unchanged)console.log(` ok: ${o} (already configured)`);for(let o of i.removed)console.log(` remove: legacy user-level ${o}`);for(let o of i.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);i.installed.length+i.updated.length+i.unchanged.length>0?(console.log(`
900
925
  Project-local scip-query hooks are configured for this repository.`),console.log("Review new or changed hooks in Codex/Claude Code with /hooks before they run.")):console.log(`
901
- No project-local hook config was written.`)}function Oy(){let e=!1;Ui()?console.log("scip CLI: installed"):(kl(),e=!0);let t=ge(),n=_e(t),r=kt(t,n);if(r.languages.length===0){console.log(`
926
+ No project-local hook config was written.`)}function NS(){let e=!1;fo()?console.log("scip CLI: installed"):(xu(),e=!0);let t=Ne(),n=Ue(t),i=Ot(t,n);if(i.languages.length===0){console.log(`
902
927
  No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
903
- Detected languages: ${r.languages.join(", ")}`),console.log(`
904
- 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(`
905
- 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 jy(e){Hy(e,"capabilities")}function By(e){Hy(e,"capability-matrix")}function Hy(e,t){let n=de(e),r=ge(),i=_e(r),o=kt(r,i),s=zn(o);if(w(n,"json")){M(t,[],n,s);return}au(s)}function Vy(){let e=ge(),t=At(e),n=lg(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function qy(e){let t=de(e),n=ge(),r=_e(n),i=Ar(r,{projectRoot:n});if(w(t,"json"))M("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 Uy(e,t){let n=de(t),r=_(n,"reason");if(!r||r.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}try{let i=ug(ge(),{id:String(e),check:_(n,"check"),file:_(n,"file"),reason:r,expiresAt:_(n,"expiresAt")});if(w(n,"json")){M("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 Wy(e){let t=de(e),{report:n,hasIndexerProblems:r,hasErrors:i}=Gy("doctor");w(t,"json")?M("doctor",[],t,n):OB(n,r),process.exitCode=i?1:0}function Gy(e){let{projectRoot:t,config:n,paths:r,dbPath:i}=Mr(),o=Ar(n,{projectRoot:t}),s=kt(t,n),a=zn(s),c=Gn(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:Wr(i),configDiagnostics:o,readiness:s,freshness:c,capabilities:a,ok:!u},hasIndexerProblems:l,hasErrors:u}}function zy(e){let t=de(e),n=ge(),r=Ws(n,{gitHook:w(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(`
906
- 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.")}async function Jy(e){let t=de(e);try{let n=await py({gitHook:w(t,"gitHook")});w(t,"json")?M("setup",[],t,n):fy(n),process.exitCode=n.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function Ky(e){let t=de(e),n=ge(),r=gy(n,{force:w(t,"force"),dryRun:w(t,"dryRun")});if(w(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 Xy(e){let t=de(e),n=ge(),r=_e(n),i=Le(t,"debounce"),o=Le(t,"cooldown"),s=Le(t,"gitPoll");i&&((r.watch??={}).debounceMs=i),o&&((r.watch??={}).cooldownMs=o),s&&((r.watch??={}).gitPollMs=s);let a=new Js({projectRoot:n,config:r,languages:r.languages,onStatus:c=>{process.stdout.write(`\r\x1B[K${mg(c)}`)},onReindexComplete:c=>{console.log(`
928
+ Detected languages: ${i.languages.join(", ")}`),console.log(`
929
+ Indexer readiness:`);for(let r of i.indexers){let o=r.runnable?" OK":r.installed?" WARN":" MISSING",s=r.resolvedBinary?` (${r.resolvedBinary})`:"";console.log(`${o} ${r.language}: ${r.binaryLabel}${s}`),r.note&&console.log(` ${r.note}`),!r.installed&&r.installUrl&&console.log(` install: ${r.installUrl}`),r.runnable||(e=!0)}if(i.semantic){let r=i.semantic,o=r.available?" OK":r.dependencyAvailable?" WARN":" MISSING",s=r.tsconfigPaths&&r.tsconfigPaths.length>1?` (${r.tsconfigPaths.length} tsconfigs)`:r.tsconfigPath?` (${r.tsconfigPath})`:"";console.log(`
930
+ Semantic provider readiness:`),console.log(`${o} typescript: ts-morph${s}`),r.reason&&console.log(` ${r.reason}; semantic checks will fall back to SCIP/source evidence`)}process.exitCode=e?1:0}function FS(e){_S(e,"capabilities")}function TS(e){_S(e,"capability-matrix")}function _S(e,t){let n=xe(e),{projectRoot:i,config:r,paths:o,dbPath:s}=ai(),a=Ot(i,r),c=Rn(i,r,o),l=mi(a,{hasIndexedGraph:gi(s)&&c.state!=="missing"});if(P(n,"json")){B(t,[],n,l);return}rd(l)}function AS(){let e=Ne(),t=tn(e),n=ey(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function MS(e){let t=xe(e),n=Ne(),i=Ue(n),r=Yi(i,{projectRoot:n});if(P(t,"json"))B("config-validate",[],t,{diagnostics:r});else if(r.length===0)console.log("Config OK.");else for(let o of r)console.log(`${o.level.toUpperCase()} ${o.path}: ${o.message}`);r.some(o=>o.level==="error")&&(process.exitCode=1)}function $S(e,t){let n=xe(t),i=_(n,"reason");if(!i||i.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}try{let r=ty(Ne(),{id:String(e),check:_(n,"check"),file:_(n,"file"),reason:i,expiresAt:_(n,"expiresAt")});if(P(n,"json")){B("suppress",[String(e)],n,r);return}console.log(`Suppression added to ${r.path} (${r.suppressionCount} total).`)}catch(r){console.error(`error: ${r instanceof Error?r.message:r}`),process.exitCode=1}}function jS(e){let t=xe(e),{report:n,hasIndexerProblems:i,hasErrors:r}=OS("doctor");P(t,"json")?B("doctor",[],t,n):wq(n,i),process.exitCode=r?1:0}function OS(e){let{projectRoot:t,config:n,paths:i,dbPath:r}=ai(),o=Yi(n,{projectRoot:t}),s=Ot(t,n),a=Rn(t,n,i),c=gi(r),l=mi(s,{hasIndexedGraph:c&&a.state!=="missing"}),d=s.indexers.some(m=>!m.runnable),u=o.some(m=>m.level==="error")||d||a.state==="missing"||a.state==="stale";return{report:{command:e,projectRoot:t,dbPath:r,configuredDbPath:i.dbPath,exists:c,configDiagnostics:o,readiness:s,freshness:a,capabilities:l,ok:!u},hasIndexerProblems:d,hasErrors:u}}function BS(e){let t=xe(e),n=Ne(),i=Ra(n,{gitHook:P(t,"gitHook")});for(let r of i.written)console.log(` done: ${r}`);for(let r of i.unchanged)console.log(` ok: ${r} (already wired)`);for(let r of i.skipped)console.log(` skip: ${r.target} \u2014 ${r.reason}`);console.log(`
931
+ 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.")}async function HS(e){let t=xe(e);try{let n=await sS({gitHook:P(t,"gitHook")});P(t,"json")?B("setup",[],t,n):aS(n),process.exitCode=n.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function VS(e){let t=xe(e),n=Ne(),i=cS(n,{force:P(t,"force"),dryRun:P(t,"dryRun")});if(P(t,"dryRun")){console.log(i.content);return}if(i.skipped){console.log(`skip: ${i.path} \u2014 ${i.reason}`);return}console.log(`done: ${i.path}`)}function qS(e){let t=xe(e),n=Ne(),i=Ue(n),r=Ae(t,"debounce"),o=Ae(t,"cooldown"),s=Ae(t,"gitPoll");r&&((i.watch??={}).debounceMs=r),o&&((i.watch??={}).cooldownMs=o),s&&((i.watch??={}).gitPollMs=s);let a=new Pa({projectRoot:n,config:i,languages:i.languages,onStatus:c=>{process.stdout.write(`\r\x1B[K${iy(c)}`)},onReindexComplete:c=>{console.log(`
907
932
  Reindex complete in ${(c/1e3).toFixed(1)}s`)},onError:c=>{console.error(`
908
- Watch error: ${c.message}`)}});console.log(`Watching ${n}`),console.log(`Debounce: ${r.watch?.debounceMs??3e4}ms | Cooldown: ${r.watch?.cooldownMs??6e4}ms | Git poll: ${r.watch?.gitPollMs??2e3}ms`),console.log(`Press Ctrl+C to stop.
933
+ Watch error: ${c.message}`)}});console.log(`Watching ${n}`),console.log(`Debounce: ${i.watch?.debounceMs??3e4}ms | Cooldown: ${i.watch?.cooldownMs??6e4}ms | Git poll: ${i.watch?.gitPollMs??2e3}ms`),console.log(`Press Ctrl+C to stop.
909
934
  `),a.start(),process.on("SIGINT",()=>{a.stop(),console.log(`
910
- Stopped.`),process.exit(0)})}function Qy(e){let t=de(e),{report:n}=Gy("status");if(w(t,"json")){M("status",[],t,{...n,stats:su(n.exists)});return}jB(n,{capabilities:w(t,"capabilities")})}function OB(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})`:""}`),au(e.capabilities)}function jB(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})`:""}`),e.freshness.lastRefresh&&console.log(`Refresh: ${BB(e.freshness.lastRefresh)}`),HB(e.exists),t.capabilities&&(console.log(""),au(e.capabilities))}function BB(e){let t=(e.durationMs/1e3).toFixed(1),n=e.trigger.detail?` (${e.trigger.detail})`:"",r=e.error?`: ${e.error}`:"";return`${e.result} by ${e.trigger.kind}${n} in ${t}s at ${e.completedAt}${r}`}function su(e){if(e)return et(t=>{let n=Oe(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function HB(e){e&&et(t=>{let n=Oe(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${Vn(n.indexSizeBytes)}`),n.lastBuilt){let r=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${r}s ago`)}})}function au(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(`
911
- 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 Zi(e){return{...e,options:A(e.options)}}function wt({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,...o}){let s=Zi(o);return{...s,renderShape:"list",handler:yy({commandName:s.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i})}}function Ys({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,headers:o,dashWidths:s,...a}){let c=Zi(a);return{...c,renderShape:"table",handler:by({commandName:c.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,headers:o,dashWidths:s})}}function Yy({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,key:o,...s}){let a=Zi(s);return{...a,renderShape:"grouped-by-file",handler:Sy({commandName:a.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,key:o})}}function Zy({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,after:o,...s}){let a=Zi(s);return{...a,renderShape:"sectioned-report",handler:xy({commandName:a.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,after:o})}}function Zs({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,after:o,...s}){let a=Zi(s);return{...a,budget:a.budget??"semantic",renderShape:"sectioned-report",handler:Cy(a.id,{commandName:a.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,after:o})}}function cu(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(` ${we(l.startLine,l.endLine)} (${l.loc} LOC) ${l.shortName}`)}}var eb=Y("dead",({db:e,args:t,opts:n,budget:r})=>{let i={scope:ye(t,0)||void 0,minLoc:E(n,"minLoc",1),includeTests:w(n,"includeTests"),skipBarrels:w(n,"skipBarrels"),includeMembers:w(n,"includeMembers"),scanLimit:r.scanLimit,semantic:r.semantic},o=Et(e,i),s=o.symbols.filter(h=>h.kind==="dead-code"),a=o.symbols.filter(h=>h.kind!=="dead-code"),c=!w(n,"onlyInternal"),l=!w(n,"onlyDead"),u=c?s:[],d=l?a:[],m=u.reduce((h,x)=>h+x.loc,0),p=d.reduce((h,x)=>h+x.loc,0),g={total:u.length+d.length,deadCode:u.length,fileInternal:d.length,loc:m+p};if(w(n,"json")){M("dead",t,n,{...o,shown:{deadCode:u,fileInternal:d},shownCounts:g,totals:{total:o.counts.total,deadCode:o.counts.deadCode,fileInternal:o.counts.fileInternal,loc:o.counts.loc}});return}if(u.length===0&&d.length===0){N.empty("No matching dead-code symbols found.");return}u.length>0&&cu(u,"DEAD CODE",` Zero references anywhere \u2014 no cross-file callers AND no same-file uses.
912
- Safe to delete.`,m),d.length>0&&(u.length>0&&console.log(""),cu(d,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
935
+ Stopped.`),process.exit(0)})}function US(e){let t=xe(e),{report:n}=OS("status");if(P(t,"json")){B("status",[],t,{...n,stats:id(n.exists)});return}Pq(n,{capabilities:P(t,"capabilities")})}function wq(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(i=>!i.runnable))console.log(` MISSING ${n.language}: ${n.note??n.binaryLabel}`);console.log(` Freshness: ${e.freshness.state}${e.freshness.remedy?` (${e.freshness.remedy})`:""}`),rd(e.capabilities)}function Pq(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",i=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}${i}`),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})`:""}`),e.freshness.lastRefresh&&console.log(`Refresh: ${Iq(e.freshness.lastRefresh)}`),Lq(e.exists),t.capabilities&&(console.log(""),rd(e.capabilities))}function Iq(e){let t=(e.durationMs/1e3).toFixed(1),n=e.trigger.detail?` (${e.trigger.detail})`:"",i=e.error?`: ${e.error}`:"";return`${e.result} by ${e.trigger.kind}${n} in ${t}s at ${e.completedAt}${i}`}function id(e){if(e)return ut(t=>{let n=We(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function Lq(e){e&&ut(t=>{let n=We(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${ci(n.indexSizeBytes)}`),n.lastBuilt){let i=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${i}s ago`)}})}function rd(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(`
936
+ 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 Ro(e){return{...e,options:j(e.options)}}function Bt({query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,...o}){let s=Ro(o);return{...s,renderShape:"list",handler:uS({commandName:s.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r})}}function Ea({query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,headers:o,dashWidths:s,...a}){let c=Ro(a);return{...c,renderShape:"table",handler:dS({commandName:c.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,headers:o,dashWidths:s})}}function zS({query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,key:o,...s}){let a=Ro(s);return{...a,renderShape:"grouped-by-file",handler:mS({commandName:a.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,key:o})}}function WS({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:r,after:o,...s}){let a=Ro(s);return{...a,renderShape:"sectioned-report",handler:pS({commandName:a.id,query:e,emptyMessage:t,heuristicLabel:n,before:r,sections:i,after:o})}}function Na({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:r,after:o,...s}){let a=Ro(s);return{...a,budget:a.budget??"semantic",renderShape:"sectioned-report",handler:fS(a.id,{commandName:a.id,query:e,emptyMessage:t,heuristicLabel:n,before:r,sections:i,after:o})}}function od(e,t,n,i){console.log(`\u2550\u2550\u2550 ${t} (${e.length}, ${i} LOC) \u2550\u2550\u2550`),console.log(n),console.log("");let r=new Map;for(let a of e){let c=r.get(a.relativePath)??[];c.push(a),r.set(a.relativePath,c)}let o=[...r.entries()].map(([a,c])=>({file:a,bucket:c,totalLoc:c.reduce((l,d)=>l+d.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,d)=>l.startLine-d.startLine);for(let l of c)console.log(` ${_e(l.startLine,l.endLine)} (${l.loc} LOC) ${l.shortName}`)}}var GS=le("dead",({db:e,args:t,opts:n,budget:i})=>{let r={scope:ke(t,0)||void 0,minLoc:F(n,"minLoc",1),includeTests:P(n,"includeTests"),skipBarrels:P(n,"skipBarrels"),includeMembers:P(n,"includeMembers"),scanLimit:i.scanLimit,semantic:i.semantic},o=Qt(e,r),s=o.symbols.filter(b=>b.kind==="dead-code"),a=o.symbols.filter(b=>b.kind!=="dead-code"),c=!P(n,"onlyInternal"),l=!P(n,"onlyDead"),d=c?s:[],u=l?a:[],m=d.reduce((b,x)=>b+x.loc,0),p=u.reduce((b,x)=>b+x.loc,0),f={total:d.length+u.length,deadCode:d.length,fileInternal:u.length,loc:m+p};if(P(n,"json")){B("dead",t,n,{...o,shown:{deadCode:d,fileInternal:u},shownCounts:f,totals:{total:o.counts.total,deadCode:o.counts.deadCode,fileInternal:o.counts.fileInternal,loc:o.counts.loc}});return}if(d.length===0&&u.length===0){N.empty("No matching dead-code symbols found.");return}d.length>0&&od(d,"DEAD CODE",` Zero references anywhere \u2014 no cross-file callers AND no same-file uses.
937
+ Safe to delete.`,m),u.length>0&&(d.length>0&&console.log(""),od(u,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
913
938
  single-use helper, an abstraction-in-progress, or a callback registered
914
939
  through a framework path that static analysis cannot trace (signal
915
940
  handlers, event listeners, dependency injection). NOT necessarily dead \u2014
916
- review case by case.`,p));let y=[];c&&y.push(`${u.length} dead code (${m} LOC)`),l&&y.push(`${d.length} file-internal (${p} LOC)`),console.log(`
917
- \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 ${y.join(" + ")}`)}),tb=Mt("unused-imports",{query:({db:e,args:t,budget:n})=>tc(e,H(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
918
- ${e.length} unused import(s)`)}),nb=Qs("isolated",{query:({db:e,opts:t,budget:n})=>In(e,{scope:_(t,"scope"),minLoc:E(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${we(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
919
- ${e.length} isolated symbol(s)`)}),rb=Y("extract-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=Tn(e,{scope:_(n,"scope"),minLoc:E(n,"minLoc",10),minCallees:E(n,"minCallees",6),limit:j(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic});if(w(n,"json")){M("extract-candidates",t,n,i);return}if(i.length===0)return N.empty("No extraction candidates found.");jr("extraction candidates");for(let o of i){console.log(`
920
- ${Re(o.relativePath,o.startLine,o.endLine)} ${o.shortName} (${o.loc} LOC, ${o.totalCallees} callees)`),console.log(` Kind: ${o.extractionKind}; tier: ${o.actionTier}`),console.log(` Recommendation: ${o.recommendation}`);for(let s of o.evidenceReasons)console.log(` - ${s}`);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(`
921
- ${i.length} extraction candidate(s) found.`)}),ib=Y("locality-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=Ic(e,{target:ye(t,0)||void 0,scope:_(n,"scope"),minConsumers:E(n,"minConsumers",1),limit:j(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic,architecturalBoundarySegments:e.config.locality?.architecturalBoundarySegments});if(w(n,"json")){M("locality-candidates",t,n,i);return}if(i.length===0)return N.empty("No locality candidates found.");jr("locality candidates");for(let o of i){let s=o.sourceUnit.kind==="symbol"&&o.sourceUnit.startLine!==void 0&&o.sourceUnit.endLine!==void 0?Re(o.sourceUnit.file,o.sourceUnit.startLine,o.sourceUnit.endLine):o.sourceUnit.file;if(console.log(`
941
+ review case by case.`,p));let g=[];c&&g.push(`${d.length} dead code (${m} LOC)`),l&&g.push(`${u.length} file-internal (${p} LOC)`),console.log(`
942
+ \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: ${d.length+u.length} symbols \u2014 ${g.join(" + ")}`)}),KS=nn("unused-imports",{query:({db:e,args:t,budget:n})=>Gc(e,z(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
943
+ ${e.length} unused import(s)`)}),JS=Da("isolated",{query:({db:e,opts:t,budget:n})=>zn(e,{scope:_(t,"scope"),minLoc:F(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${_e(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
944
+ ${e.length} isolated symbol(s)`)}),XS=le("extract-candidates",({db:e,args:t,opts:n,budget:i})=>{let r=Qn(e,{scope:_(n,"scope"),minLoc:F(n,"minLoc",10),minCallees:F(n,"minCallees",6),limit:V(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic});if(P(n,"json")){B("extract-candidates",t,n,r);return}if(r.length===0)return N.empty("No extraction candidates found.");tr("extraction candidates");for(let o of r){console.log(`
945
+ ${Fe(o.relativePath,o.startLine,o.endLine)} ${o.shortName} (${o.loc} LOC, ${o.totalCallees} callees)`),console.log(` Kind: ${o.extractionKind}; tier: ${o.actionTier}`),console.log(` Recommendation: ${o.recommendation}`);for(let s of o.evidenceReasons)console.log(` - ${s}`);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(`
946
+ ${r.length} extraction candidate(s) found.`)}),QS=le("locality-candidates",({db:e,args:t,opts:n,budget:i})=>{let r=xl(e,{target:ke(t,0)||void 0,scope:_(n,"scope"),minConsumers:F(n,"minConsumers",1),limit:V(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic,architecturalBoundarySegments:e.config.locality?.architecturalBoundarySegments});if(P(n,"json")){B("locality-candidates",t,n,r);return}if(r.length===0)return N.empty("No locality candidates found.");tr("locality candidates");for(let o of r){let s=o.sourceUnit.kind==="symbol"&&o.sourceUnit.startLine!==void 0&&o.sourceUnit.endLine!==void 0?Fe(o.sourceUnit.file,o.sourceUnit.startLine,o.sourceUnit.endLine):o.sourceUnit.file;if(console.log(`
922
947
  ${s} ${o.sourceUnit.shortName}`),console.log(` Current directory: ${o.currentDirectory}; tier: ${o.recommendedTier}; action: ${o.actionTier}`),console.log(` Consumer coverage: ${o.consumerCoverage}; consumers: ${o.consumerFiles.length}`),o.nearestCommonOwner&&console.log(` Nearest common owner: ${o.nearestCommonOwner}`),o.suggestedHome&&console.log(` Suggested home: ${o.suggestedHome}`),o.whyNoSuggestedHome&&console.log(` Suggested home withheld: ${o.whyNoSuggestedHome}`),o.boundaryMarkers.length>0&&console.log(` Boundary markers: ${o.boundaryMarkers.join("; ")}`),console.log(` Recommendation: ${o.recommendation}`),o.consumerFiles.length>0){for(let a of o.consumerFiles.slice(0,8))console.log(` - consumer: ${a}`);o.consumerFiles.length>8&&console.log(` - ... ${o.consumerFiles.length-8} more consumer(s)`)}for(let a of o.counterevidence)console.log(` - counterevidence: ${a}`)}console.log(`
923
- ${i.length} locality candidate(s) found.`)}),ob=Mt("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>Bn(e,{scope:_(t,"scope"),maxLoc:E(t,"maxLoc",15),limit:j(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${Re(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
948
+ ${r.length} locality candidate(s) found.`)}),YS=nn("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>oi(e,{scope:_(t,"scope"),maxLoc:F(t,"maxLoc",15),limit:V(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${Fe(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
924
949
  Only called by: ${e.singleCallerShort} (fan-in: ${e.callerFanIn}, tier: ${e.actionTier})`+(e.boundaryEvidence.length>0?`
925
950
  Boundary evidence: ${e.boundaryEvidence.join("; ")}`:""),emptyMessage:()=>"No wrapper candidates found.",heuristicLabel:"wrapper candidates",after:e=>console.log(`
926
- ${e.length} wrapper candidate(s).`)}),sb=Mt("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>On(e,{scope:_(t,"scope"),maxLoc:E(t,"maxLoc",15),limit:j(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${Re(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
951
+ ${e.length} wrapper candidate(s).`)}),ZS=nn("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>ii(e,{scope:_(t,"scope"),maxLoc:F(t,"maxLoc",15),limit:V(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${Fe(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
927
952
  Forwards to: ${e.forwardsToShort} (${e.forwardsToFile}, tier: ${e.actionTier})
928
953
  Recommendation: ${e.recommendation}`+(e.boundaryEvidence.length>0?`
929
954
  Boundary evidence: ${e.boundaryEvidence.join("; ")}`:"")+(e.publicFacadeEvidence.length>0?`
930
955
  Public facade evidence: ${e.publicFacadeEvidence.join("; ")}`:""),emptyMessage:()=>"No passthrough candidates found.",heuristicLabel:"passthrough candidates",after:e=>console.log(`
931
- ${e.length} passthrough candidate(s).`)}),ab=Mt("stale-abstractions",{query:({db:e,opts:t,budget:n})=>jn(e,{scope:_(t,"scope"),minLoc:E(t,"minLoc",3),limit:j(t,"limit",30),includeLowConfidence:w(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}] ${Re(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
956
+ ${e.length} passthrough candidate(s).`)}),ex=nn("stale-abstractions",{query:({db:e,opts:t,budget:n})=>ri(e,{scope:_(t,"scope"),minLoc:F(t,"minLoc",3),limit:V(t,"limit",30),includeLowConfidence:P(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}] ${Fe(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
932
957
  ${e.reason}
933
958
  Kind: ${e.stalenessKind}; tier: ${e.actionTier}
934
959
  Recommendation: ${e.recommendation}`},emptyMessage:()=>"No stale abstractions found.",heuristicLabel:"stale abstraction candidates",after:e=>console.log(`
935
- ${e.length} stale abstraction(s).`)}),cb=Xs("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>Ai(e,{scope:_(t,"scope"),minLoc:E(t,"minLoc",10),limit:j(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]}),lb=nt("similar",{query:({db:e,args:t,opts:n,budget:r})=>{let i=ye(t,0);return i?{mode:"target",rows:xi(e,i,{minSimilarity:E(n,"minSimilarity",.4),limit:j(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic})}:{mode:"all",rows:Tt(e,{minSimilarity:E(n,"minSimilarity",.4),limit:j(n,"limit",20),scope:_(n,"scope"),minCallees:E(n,"minCallees",4),crossFileOnly:w(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"){N.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=[`
936
- ${Math.round(t.similarity*100)}% similar:`,` A: ${t.shortNameA} (${t.fileA})`,` B: ${t.shortNameB} (${t.fileB})`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`,` ${r}: ${t.sharedCallees.join(", ")}`];return t.evidenceClassReasons.length&&o.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.uniqueToA.length&&o.push(` ${i} A: ${t.uniqueToA.join(", ")}`),t.uniqueToB.length&&o.push(` ${i} B: ${t.uniqueToB.join(", ")}`),o.join(`
960
+ ${e.length} stale abstraction(s).`)}),tx=La("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>oo(e,{scope:_(t,"scope"),minLoc:F(t,"minLoc",10),limit:V(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]}),nx=dt("similar",{query:({db:e,args:t,opts:n,budget:i})=>{let r=ke(t,0);return r?{mode:"target",rows:Vr(e,r,{minSimilarity:F(n,"minSimilarity",.4),limit:V(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic})}:{mode:"all",rows:Wn(e,{minSimilarity:F(n,"minSimilarity",.4),limit:V(n,"limit",20),scope:_(n,"scope"),minCallees:F(n,"minCallees",4),crossFileOnly:P(n,"crossFileOnly"),scanLimit:i.scanLimit,semantic:i.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"){N.list(e.rows,t=>{let n=t.similarityBasis??"callees",i=n==="source-tokens"?"Shared source tokens":"Shared callees",r=n==="source-tokens"?"Only tokens in":"Only in",o=[`
961
+ ${Math.round(t.similarity*100)}% similar:`,` A: ${t.shortNameA} (${t.fileA})`,` B: ${t.shortNameB} (${t.fileB})`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`,` ${i}: ${t.sharedCallees.join(", ")}`];return t.evidenceClassReasons.length&&o.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.uniqueToA.length&&o.push(` ${r} A: ${t.uniqueToA.join(", ")}`),t.uniqueToB.length&&o.push(` ${r} B: ${t.uniqueToB.join(", ")}`),o.join(`
937
962
  `)});return}N.list(e.rows,t=>`
938
963
  ${Math.round(t.similarity*100)}% similar:
939
964
  A: ${t.shortNameA} (${t.fileA})
@@ -942,85 +967,85 @@ ${Math.round(t.similarity*100)}% similar:
942
967
  Recommendation: ${t.recommendation}
943
968
  `+(t.evidenceClassReasons.length?` Evidence reasons: ${t.evidenceClassReasons.join("; ")}
944
969
  `:"")+` Shared ${t.similarityBasis==="source-tokens"?"source tokens":"callees"}: ${t.sharedCallees.join(", ")}`),console.log(`
945
- ${e.rows.length} similar pair(s) found.`)}}),ub=Kn({commandName:"similar-files",query:({db:e,args:t,opts:n})=>Cc(e,{minSimilarity:E(n,"minSimilarity",.5),limit:j(n,"limit",20),scope:_(n,"scope"),minDeps:Le(n,"minDeps"),filePattern:ye(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{N.list(e,t=>{let n=[`
970
+ ${e.rows.length} similar pair(s) found.`)}}),ix=fi({commandName:"similar-files",query:({db:e,args:t,opts:n})=>pl(e,{minSimilarity:F(n,"minSimilarity",.5),limit:V(n,"limit",20),scope:_(n,"scope"),minDeps:Ae(n,"minDeps"),filePattern:ke(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{N.list(e,t=>{let n=[`
946
971
  ${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(`
947
972
  `)}),console.log(`
948
- ${e.length} similar pair(s) found.`)}}),db=Kn({commandName:"similar-chains",query:({db:e,opts:t})=>vc(e,{minSimilarity:E(t,"minSimilarity",.5),limit:j(t,"limit",15),scope:_(t,"scope"),minChainLength:E(t,"minLength",3),maxChainLength:E(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(`
949
- \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(`
950
- ${e.length} similar chain pair(s) found.`)}}),mb=nt("drift",{query:({db:e,args:t,opts:n,budget:r})=>Mn(e,{scope:ye(t,0),minDeviation:E(n,"minDeviation",5),semantic:r.semantic}),emptyMessage:e=>e.results.length===0?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{console.log(""),N.groupedByFile(e.results,t=>{let n=t.kind==="unused-import"?"UNUSED":t.kind==="layer-violation"?"LAYER":"UNIQUE",r=t.policyBasis?`, policy: ${t.policyBasis}`:"",i=[` [${n}] ${t.description}`,` Tier: ${t.actionTier}${r}`,` Recommendation: ${t.recommendation}`,` Evidence: ${t.evidenceReasons.join("; ")}`];return t.detail&&i.push(` ${t.detail}`),i.join(`
973
+ ${e.length} similar pair(s) found.`)}}),rx=fi({commandName:"similar-chains",query:({db:e,opts:t})=>fl(e,{minSimilarity:F(t,"minSimilarity",.5),limit:V(t,"limit",15),scope:_(t,"scope"),minChainLength:F(t,"minLength",3),maxChainLength:F(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(`
974
+ \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 i of n.divergencePoints)console.log(` [${i.index}] ${i.nodeA} \u2194 ${i.nodeB}`)}console.log(`
975
+ ${e.length} similar chain pair(s) found.`)}}),ox=dt("drift",{query:({db:e,args:t,opts:n,budget:i})=>ni(e,{scope:ke(t,0),minDeviation:F(n,"minDeviation",5),semantic:i.semantic}),emptyMessage:e=>e.results.length===0?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{console.log(""),N.groupedByFile(e.results,t=>{let n=t.kind==="unused-import"?"UNUSED":t.kind==="layer-violation"?"LAYER":"UNIQUE",i=t.policyBasis?`, policy: ${t.policyBasis}`:"",r=[` [${n}] ${t.description}`,` Tier: ${t.actionTier}${i}`,` Recommendation: ${t.recommendation}`,` Evidence: ${t.evidenceReasons.join("; ")}`];return t.detail&&r.push(` ${t.detail}`),r.join(`
951
976
  `)},t=>t.file),console.log(`
952
- ${e.unusedImports} unused import(s), ${e.layerViolations} layer violation(s), ${e.patternDeviations} pattern deviation(s)`)}}),pb=nt("convergence",{query:({db:e,args:t,budget:n})=>al(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(`
977
+ ${e.unusedImports} unused import(s), ${e.layerViolations} layer violation(s), ${e.patternDeviations} pattern deviation(s)`)}}),sx=dt("convergence",{query:({db:e,args:t,budget:n})=>iu(e,z(t,0),z(t,1),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"One or both symbols not found.",render:e=>{if(e){console.log(`
953
978
  ${Math.round(e.similarity*100)}% callee overlap
954
979
  `),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)
955
980
  `),console.log(` Shared callees (${e.sharedCallees.length}):`);for(let t of e.sharedCallees)console.log(` ${t}`);if(e.uniqueToA.length>0){console.log(`
956
981
  Unique to A (${e.uniqueToA.length}):`);for(let t of e.uniqueToA)console.log(` ${t}`)}if(e.uniqueToB.length>0){console.log(`
957
982
  Unique to B (${e.uniqueToB.length}):`);for(let t of e.uniqueToB)console.log(` ${t}`)}console.log(`
958
- Strategy: ${e.consolidationStrategy}`)}}}),fb=Mt("similar-signatures",{query:({db:e,opts:t,budget:n})=>ml(e,{scope:_(t,"scope"),minLoc:E(t,"minLoc",3),limit:j(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=`
959
- Signature: ${e.signature} (${e.functions.length} functions)`,n=e.functions.map(r=>` ${Re(r.file,r.startLine,r.endLine)} ${r.shortName} (${r.loc} LOC)`).join(`
983
+ Strategy: ${e.consolidationStrategy}`)}}}),ax=nn("similar-signatures",{query:({db:e,opts:t,budget:n})=>lu(e,{scope:_(t,"scope"),minLoc:F(t,"minLoc",3),limit:V(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=`
984
+ Signature: ${e.signature} (${e.functions.length} functions)`,n=e.functions.map(i=>` ${Fe(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
960
985
  `);return`${t}
961
986
  ${n}`},emptyMessage:()=>"No same-shape function groups found.",after:e=>console.log(`
962
- ${e.length} group(s) found.`)}),gb=Y("cleanup-plan",({db:e,args:t,opts:n,budget:r})=>{let i=es(e,{scope:_(n,"scope"),minLoc:E(n,"minLoc",1),maxDepth:E(n,"maxDepth",5),scanLimit:r.scanLimit}),o=ge(),s=w(n,"patch"),a=w(n,"json"),c=w(n,"verify")||s;if(s&&!w(n,"verify")){console.error("error: cleanup-plan --patch requires --verify."),process.exitCode=1;return}if(i.batches.length===0){if(a){M("cleanup-plan",t,n,i);return}return N.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.")}let l=Kl(i),u=c?Gl(o,i):void 0;if(a){M("cleanup-plan",t,n,{result:i,verification:u});return}if(s){let d=Xl(u,l);if(d.length>0){for(let p of d)console.error(`error: ${p}`);process.exitCode=1;return}let m=Vh(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.
963
- `);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 p of d.entries)console.log(` ${p.file}:${p.startLine+1}-${p.endLine+1} ${p.shortName} (${p.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(`
964
- 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}`)}}}),hb=Y("cleanup-apply",({db:e,opts:t,budget:n})=>{if(!w(t,"verified")){console.error("error: cleanup-apply requires --verified so deletions are checked before mutating files."),process.exitCode=1;return}let r=w(t,"all"),i=Le(t,"batch");if(r===(i!==void 0)){console.error("error: choose exactly one of --all or --batch <n>."),process.exitCode=1;return}let o=es(e,{scope:_(t,"scope"),minLoc:E(t,"minLoc",1),maxDepth:E(t,"maxDepth",5),scanLimit:n.scanLimit});if(o.batches.length===0){N.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.");return}let s=Kl(o,{all:r,batch:i});if(s.length===0){console.error(`error: No cleanup batch ${i} exists.`),process.exitCode=1;return}let a=ge(),c=Gl(a,o),l=Xl(c,s,{allowDirty:w(t,"forceDirty")});if(l.length>0){for(let m of l)console.error(`error: ${m}`);process.exitCode=1;return}Jl(a,s);let u=s.reduce((m,p)=>m+p.entries.length,0),d=s.reduce((m,p)=>m+p.loc,0);console.log(`Applied ${s.length} compiler-verified cleanup batch(es): ${u} symbol(s), ${d} LOC.`)}),yb=Y("recent-duplicates",({db:e,args:t,opts:n,budget:r})=>{let i=el(e,{windowCommits:E(n,"window",100),minSimilarity:Le(n,"minSimilarity"),limit:j(n,"limit",30),scope:_(n,"scope"),scanLimit:r.scanLimit,semantic:r.semantic});if(w(n,"json")){M("recent-duplicates",t,n,i);return}if(!i.available)return N.empty("No git history available (not a repository, or git missing).");if(i.findings.length===0)return N.empty(`No recent re-implementations found (window: last ${i.windowCommits} commits).`);console.log(`Recent re-implementations (window: last ${i.windowCommits} commits):
965
- `);let o=i.rootCauseGroups?.filter(s=>s.count>1)??[];if(o.length>0){console.log(`Root-cause groups (${o.length}):`);for(let s of o)console.log(` ${s.count} pair(s) ${s.kind.toUpperCase()} ${s.domain} ${Math.round(s.maxSimilarity*100)}% max`),s.establishedFile&&s.establishedSymbol&&console.log(` established: ${s.establishedFile} ${s.establishedSymbol}`),console.log(` files: ${s.relatedFiles.slice(0,6).join(", ")}`),console.log(` -> ${s.recommendation}`);console.log("")}for(let s of i.findings){let a=s.sharedEvidence.slice(0,16).join(", ");s.kind==="echo"?(console.log(` ${Math.round(s.similarity*100)}% ECHO ${s.domain} ${s.echoFile} ${s.echoSymbol} (added ${s.echoAgeCommits} commits ago)`),console.log(` duplicates established ${s.establishedFile} ${s.establishedSymbol}`)):(console.log(` ${Math.round(s.similarity*100)}% TWIN ${s.domain} ${s.echoFile} ${s.echoSymbol}`),console.log(` and ${s.establishedFile} ${s.establishedSymbol} (both new \u2014 consolidate before they diverge)`)),console.log(` basis: ${s.basis}`),a.length>0&&console.log(` shared: ${a}`)}console.log(`
966
- ${i.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),bb=K(({db:e,args:t,opts:n})=>{let r=zc(e,{doc:t[0]===void 0?void 0:H(t,0),limit:j(n,"limit",20),minCoupling:E(n,"minCoupling",3)});if(w(n,"json")){M("doc-drift",t,n,r);return}if(!r.available)return N.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return N.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):
967
- `);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}; ${o.actionTier}/${o.docIntent})`);let a=o.docIntentReasons[0];a&&console.log(` intent: ${a}`);let c=o.citationContexts?.[0];c&&console.log(` cited claim: ${ws(c)}`)}}console.log(`
968
- Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),Sb=Mt("unused-params",{query:({db:e,opts:t,budget:n})=>Ei(e,{scope:_(t,"scope"),limit:j(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${Re(e.file,e.startLine,e.endLine)} ${e.shortName}
987
+ ${e.length} group(s) found.`)}),cx=le("cleanup-plan",({db:e,args:t,opts:n,budget:i})=>{let r=Ds(e,{scope:_(n,"scope"),minLoc:F(n,"minLoc",1),maxDepth:F(n,"maxDepth",5),scanLimit:i.scanLimit}),o=Ne(),s=P(n,"patch"),a=P(n,"json"),c=P(n,"verify")||s;if(s&&!P(n,"verify")){console.error("error: cleanup-plan --patch requires --verify."),process.exitCode=1;return}if(r.batches.length===0){if(a){B("cleanup-plan",t,n,r);return}return N.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.")}let l=Wu(r),d=c?qu(o,r):void 0;if(a){B("cleanup-plan",t,n,{result:r,verification:d});return}if(s){let u=Gu(d,l);if(u.length>0){for(let p of u)console.error(`error: ${p}`);process.exitCode=1;return}let m=Ab(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), ${r.totalLoc} LOC.`),console.log(m);return}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.
988
+ `);for(let u of r.batches){let m=u.depth===0?`\u2500\u2500 Batch 0: deletable now (graph-fact, ${u.loc} LOC) \u2500\u2500`:`\u2500\u2500 Batch ${u.depth}: dead once batch ${u.depth-1} lands (cascade, ${u.loc} LOC) \u2500\u2500`;console.log(m);for(let p of u.entries)console.log(` ${p.file}:${p.startLine+1}-${p.endLine+1} ${p.shortName} (${p.loc} LOC)`);u.filesEmptied.length>0&&console.log(` -> empties: ${u.filesEmptied.join(", ")}`),console.log("")}if(r.blocked.length>0){console.log("Cascade blocked (references outside the removal set):");for(let u of r.blocked)console.log(` ${u.shortName} (${u.file}) blocked by ${u.blockingFiles.join(", ")}`)}if(d){if(console.log(`
989
+ Verifying batches against the project checker (throwaway worktree at HEAD)...`),d.checkers.length===0){console.log(" No checker detected (need tsconfig.json or a Cargo.toml) \u2014 skipped.");return}for(let u of d.checkers)console.log(` Checker: ${u}`);d.uncoveredFiles.length>0&&console.log(` WARNING: no checker covers these plan files (entries there are NOT verified): ${d.uncoveredFiles.join(", ")}`),d.baselineErrors>0&&console.log(` Baseline has ${d.baselineErrors} pre-existing error(s) \u2014 verifying differentially (no NEW errors).`),d.dirtyOverlap.length>0&&console.log(` WARNING: plan files dirty in working tree (verification runs at HEAD): ${d.dirtyOverlap.join(", ")}`);for(let u of d.batches)if(u.status==="verified")console.log(` Batch ${u.depth}: COMPILER-VERIFIED`);else{console.log(` Batch ${u.depth}: FAILED \u2014 the errors below name references the static evidence missed:`);for(let m of u.errors??[])console.log(` ${m}`)}}}),lx=le("cleanup-apply",({db:e,opts:t,budget:n})=>{if(!P(t,"verified")){console.error("error: cleanup-apply requires --verified so deletions are checked before mutating files."),process.exitCode=1;return}let i=P(t,"all"),r=Ae(t,"batch");if(i===(r!==void 0)){console.error("error: choose exactly one of --all or --batch <n>."),process.exitCode=1;return}let o=Ds(e,{scope:_(t,"scope"),minLoc:F(t,"minLoc",1),maxDepth:F(t,"maxDepth",5),scanLimit:n.scanLimit});if(o.batches.length===0){N.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.");return}let s=Wu(o,{all:i,batch:r});if(s.length===0){console.error(`error: No cleanup batch ${r} exists.`),process.exitCode=1;return}let a=Ne(),c=qu(a,o),l=Gu(c,s,{allowDirty:P(t,"forceDirty")});if(l.length>0){for(let m of l)console.error(`error: ${m}`);process.exitCode=1;return}zu(a,s);let d=s.reduce((m,p)=>m+p.entries.length,0),u=s.reduce((m,p)=>m+p.loc,0);console.log(`Applied ${s.length} compiler-verified cleanup batch(es): ${d} symbol(s), ${u} LOC.`)}),ux=le("recent-duplicates",({db:e,args:t,opts:n,budget:i})=>{let r=Xl(e,{windowCommits:F(n,"window",100),minSimilarity:Ae(n,"minSimilarity"),limit:V(n,"limit",30),scope:_(n,"scope"),scanLimit:i.scanLimit,semantic:i.semantic});if(P(n,"json")){B("recent-duplicates",t,n,r);return}if(!r.available)return N.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return N.empty(`No recent re-implementations found (window: last ${r.windowCommits} commits).`);console.log(`Recent re-implementations (window: last ${r.windowCommits} commits):
990
+ `);let o=r.rootCauseGroups?.filter(s=>s.count>1)??[];if(o.length>0){console.log(`Root-cause groups (${o.length}):`);for(let s of o)console.log(` ${s.count} pair(s) ${s.kind.toUpperCase()} ${s.domain} ${Math.round(s.maxSimilarity*100)}% max`),s.establishedFile&&s.establishedSymbol&&console.log(` established: ${s.establishedFile} ${s.establishedSymbol}`),console.log(` files: ${s.relatedFiles.slice(0,6).join(", ")}`),console.log(` -> ${s.recommendation}`);console.log("")}for(let s of r.findings){let a=s.sharedEvidence.slice(0,16).join(", ");s.kind==="echo"?(console.log(` ${Math.round(s.similarity*100)}% ECHO ${s.domain} ${s.echoFile} ${s.echoSymbol} (added ${s.echoAgeCommits} commits ago)`),console.log(` duplicates established ${s.establishedFile} ${s.establishedSymbol}`)):(console.log(` ${Math.round(s.similarity*100)}% TWIN ${s.domain} ${s.echoFile} ${s.echoSymbol}`),console.log(` and ${s.establishedFile} ${s.establishedSymbol} (both new \u2014 consolidate before they diverge)`)),console.log(` basis: ${s.basis}`),a.length>0&&console.log(` shared: ${a}`)}console.log(`
991
+ ${r.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),dx=ne(({db:e,args:t,opts:n})=>{let i=Hl(e,{doc:t[0]===void 0?void 0:z(t,0),limit:V(n,"limit",20),minCoupling:F(n,"minCoupling",3)});if(P(n,"json")){B("doc-drift",t,n,i);return}if(!i.available)return N.empty("No git history available (not a repository, or git missing).");if(i.findings.length===0)return N.empty(`No drifting docs found across ${i.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 (${i.docsScanned} docs scanned, ${i.commitsAnalyzed} commits analyzed):
992
+ `);for(let r of i.findings){console.log(` staleness ${r.staleness} ${r.doc}`);for(let o of r.brokenReferences.slice(0,4))console.log(` BROKEN REFERENCE: cites ${o} \u2014 that file no longer exists`);for(let o of r.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}; ${o.actionTier}/${o.docIntent})`);let a=o.docIntentReasons[0];a&&console.log(` intent: ${a}`);let c=o.citationContexts?.[0];c&&console.log(` cited claim: ${ta(c)}`)}}console.log(`
993
+ Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),mx=nn("unused-params",{query:({db:e,opts:t,budget:n})=>to(e,{scope:_(t,"scope"),limit:V(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${Fe(e.file,e.startLine,e.endLine)} ${e.shortName}
969
994
  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(`
970
- ${e.length} function(s) with trailing unused parameters.`)});var xb=nt("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>Dn(e,{minSimilarity:E(n,"minSimilarity",.62),minTokens:E(n,"minTokens",8),limit:j(n,"limit",20),scope:_(n,"scope"),scanLimit:r.scanLimit,filePattern:ye(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React component structures found.":void 0,heuristicLabel:"React component duplicate candidates",render:e=>{N.list(e,t=>{let n=[`
995
+ ${e.length} function(s) with trailing unused parameters.`)});var px=dt("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:i})=>Gn(e,{minSimilarity:F(n,"minSimilarity",.62),minTokens:F(n,"minTokens",8),limit:V(n,"limit",20),scope:_(n,"scope"),scanLimit:i.scanLimit,filePattern:ke(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React component structures found.":void 0,heuristicLabel:"React component duplicate candidates",render:e=>{N.list(e,t=>{let n=[`
971
996
  ${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(`
972
997
  `)}),console.log(`
973
- ${e.length} duplicated React component pair(s) found.`)}}),Cb=nt("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:r})=>Pn(e,{minSimilarity:E(n,"minSimilarity",.45),minSharedBehaviors:E(n,"minSharedBehaviors",6),limit:j(n,"limit",20),scope:_(n,"scope"),scanLimit:r.scanLimit,filePattern:ye(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React hook behavior candidates found.":void 0,heuristicLabel:"React hook extraction candidates",render:e=>{N.list(e,t=>{let n=[`
998
+ ${e.length} duplicated React component pair(s) found.`)}}),fx=dt("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:i})=>Kn(e,{minSimilarity:F(n,"minSimilarity",.45),minSharedBehaviors:F(n,"minSharedBehaviors",6),limit:V(n,"limit",20),scope:_(n,"scope"),scanLimit:i.scanLimit,filePattern:ke(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React hook behavior candidates found.":void 0,heuristicLabel:"React hook extraction candidates",render:e=>{N.list(e,t=>{let n=[`
974
999
  ${Math.round(t.similarity*100)}% similar React behavior:`,` ${t.componentA} (${t.fileA})`,` ${t.componentB} (${t.fileB})`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`,` ${t.reason}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),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(`
975
1000
  `)}),console.log(`
976
- ${e.length} React hook candidate pair(s) found.`)}}),vb=nt("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:r})=>Ci(e,{minComponentLines:E(n,"minComponentLines",300),minFileLines:E(n,"minFileLines",800),minJsxTokens:E(n,"minJsxTokens",80),minBehaviorTokens:E(n,"minBehaviorTokens",40),limit:j(n,"limit",20),scope:_(n,"scope"),scanLimit:r.scanLimit,filePattern:ye(t,0)}),emptyMessage:e=>e.length===0?"No large React component pressure found.":void 0,heuristicLabel:"large React component pressure candidates",render:e=>{N.list(e,t=>[`
1001
+ ${e.length} React hook candidate pair(s) found.`)}}),gx=dt("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:i})=>qr(e,{minComponentLines:F(n,"minComponentLines",300),minFileLines:F(n,"minFileLines",800),minJsxTokens:F(n,"minJsxTokens",80),minBehaviorTokens:F(n,"minBehaviorTokens",40),limit:V(n,"limit",20),scope:_(n,"scope"),scanLimit:i.scanLimit,filePattern:ke(t,0)}),emptyMessage:e=>e.length===0?"No large React component pressure found.":void 0,heuristicLabel:"large React component pressure candidates",render:e=>{N.list(e,t=>[`
977
1002
  ${t.componentLines} component line(s): ${t.component} (${t.file})`,` Dominant pressure: ${t.dominantPressure} (context: ${t.contextKind})`,` Pressure kinds: ${t.pressureKinds.join(", ")}`,` File lines: ${t.fileLines}; JSX tokens: ${t.jsxTokens}; behavior tokens: ${t.behaviorTokens}`,` Recommendation: ${t.recommendationKind} - ${t.recommendation}`,` Reasons: ${t.reasons.join("; ")}`].join(`
978
1003
  `)),console.log(`
979
- ${e.length} large React component(s) found.`)}}),Rb=nt("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>Nn(e,{minSimilarity:E(n,"minSimilarity",.62),minTokens:E(n,"minTokens",8),limit:j(n,"limit",20),scope:_(n,"scope"),scanLimit:r.scanLimit,filePattern:ye(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue component structures found.":void 0,heuristicLabel:"Vue component duplicate candidates",render:e=>{N.list(e,t=>{let n=[`
1004
+ ${e.length} large React component(s) found.`)}}),hx=dt("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:i})=>Jn(e,{minSimilarity:F(n,"minSimilarity",.62),minTokens:F(n,"minTokens",8),limit:V(n,"limit",20),scope:_(n,"scope"),scanLimit:i.scanLimit,filePattern:ke(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue component structures found.":void 0,heuristicLabel:"Vue component duplicate candidates",render:e=>{N.list(e,t=>{let n=[`
980
1005
  ${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(`
981
1006
  `)}),console.log(`
982
- ${e.length} duplicated Vue component pair(s) found.`)}}),kb=nt("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:r})=>En(e,{minSimilarity:E(n,"minSimilarity",.45),minSharedBehaviors:E(n,"minSharedBehaviors",6),limit:j(n,"limit",20),scope:_(n,"scope"),scanLimit:r.scanLimit,filePattern:ye(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue behavior candidates found.":void 0,heuristicLabel:"Vue composable extraction candidates",render:e=>{N.list(e,t=>{let n=[`
1007
+ ${e.length} duplicated Vue component pair(s) found.`)}}),yx=dt("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:i})=>Xn(e,{minSimilarity:F(n,"minSimilarity",.45),minSharedBehaviors:F(n,"minSharedBehaviors",6),limit:V(n,"limit",20),scope:_(n,"scope"),scanLimit:i.scanLimit,filePattern:ke(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue behavior candidates found.":void 0,heuristicLabel:"Vue composable extraction candidates",render:e=>{N.list(e,t=>{let n=[`
983
1008
  ${Math.round(t.similarity*100)}% similar Vue behavior:`,` ${t.fileA}`,` ${t.fileB}`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`,` ${t.reason}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),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(`
984
1009
  `)}),console.log(`
985
- ${e.length} Vue composable candidate pair(s) found.`)}}),wb=nt("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:r})=>vi(e,{minTotalLines:w(n,"reviewThresholds")&&iu(n,"minTotalLines")==="default"?300:E(n,"minTotalLines",800),minTemplateLines:E(n,"minTemplateLines",300),minScriptLines:E(n,"minScriptLines",300),minStyleLines:E(n,"minStyleLines",500),limit:j(n,"limit",20),scope:_(n,"scope"),scanLimit:r.scanLimit,filePattern:ye(t,0)}),emptyMessage:e=>e.length===0?"No large Vue view pressure found.":void 0,heuristicLabel:"large Vue view pressure candidates",render:e=>{N.list(e,t=>{let n=[`
1010
+ ${e.length} Vue composable candidate pair(s) found.`)}}),bx=dt("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:i})=>Ur(e,{minTotalLines:P(n,"reviewThresholds")&&td(n,"minTotalLines")==="default"?300:F(n,"minTotalLines",800),minTemplateLines:F(n,"minTemplateLines",300),minScriptLines:F(n,"minScriptLines",300),minStyleLines:F(n,"minStyleLines",500),limit:V(n,"limit",20),scope:_(n,"scope"),scanLimit:i.scanLimit,filePattern:ke(t,0)}),emptyMessage:e=>e.length===0?"No large Vue view pressure found.":void 0,heuristicLabel:"large Vue view pressure candidates",render:e=>{N.list(e,t=>{let n=[`
986
1011
  ${t.totalLines} total line(s): ${t.file}`,` Dominant pressure: ${t.dominantPressure} (context: ${t.contextKind})`,` Pressure kinds: ${t.pressureKinds.join(", ")}`,` Blocks: template ${t.templateLines}, script ${t.scriptLines}, style ${t.styleLines}, external script ${t.externalScriptLines}, custom ${t.customBlockLines}`,` Recommendation: ${t.recommendationKind} - ${t.recommendation}`];return t.externalScriptPaths.length&&n.push(` External scripts: ${t.externalScriptPaths.join(", ")}`),n.push(` Reasons: ${t.reasons.join("; ")}`),n.join(`
987
1012
  `)}),console.log(`
988
- ${e.length} large Vue view pressure file(s) found.`)}});function mt(e){return{docs:I("Cleanup"),...e}}function Ie({heuristicLabel:e,...t}){return mt({...t,heuristic:{label:e}})}var ea=[mt({id:"unused-params",command:"unused-params",description:"Speculative-generality candidates: trailing parameters no body ever uses (TS/JS)",options:A([f("-s, --scope <path>","Limit to files matching path"),f("-n, --limit <n>","Maximum findings",k,30),f("--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:Sb}),mt({id:"cleanup-plan",command:"cleanup-plan",description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:[f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Only include symbols >= N lines",k,1),f("--max-depth <n>","Maximum cascade depth",k,5),f("--verify","Apply batches in a throwaway worktree and run the project checker (tsc / cargo check)"),f("--patch","With --verify, print the compiler-verified deletion patch to stdout"),f("--json","Output as JSON for programmatic consumption"),f("--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:gb}),mt({id:"cleanup-apply",command:"cleanup-apply",description:"Apply a compiler-verified cleanup-plan batch to the working tree",options:[f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Only include symbols >= N lines",k,1),f("--max-depth <n>","Maximum cascade depth",k,5),f("--verified","Required: verify the selected cleanup batch before applying it"),f("--batch <n>","Apply one batch depth",k),f("--all","Apply every compiler-verified batch in the plan"),f("--force-dirty","Allow applying when plan files already have working-tree edits"),f("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:I("Cleanup",["scip-query cleanup-apply --verified --batch 0"]),handler:hb}),mt({id:"recent-duplicates",command:"recent-duplicates",description:"Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code",options:A([f("--window <n>",'How many commits back counts as "recent"',k,100),f("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",ut),f("-n, --limit <n>","Maximum findings",k,30),f("-s, --scope <path>","Limit to files matching path"),f("--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:yb}),mt({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:A([f("-n, --limit <n>","Maximum docs to report",k,20),f("--min-coupling <n>","Minimum historical co-changes to track a subject",k,3),f("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:I("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:bb}),mt({id:"dead",command:"dead [scope]",description:"Find dead code and file-internal symbols (no cross-file consumers)",options:A([f("--min-loc <n>","Only show symbols >= N lines",k,1),f("--include-tests","Include test files"),f("--skip-barrels","Ignore refs from barrel re-export files"),f("--include-members","Include class members"),f("--only-dead","Show only [dead code] symbols (skip [file-internal only])"),f("--only-internal","Show only [file-internal only] symbols (skip [dead code])"),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:I("Cleanup",["scip-query dead --min-loc 10"]),handler:eb}),mt({id:"unused-imports",command:"unused-imports <file>",description:"Find imports not referenced in the same file",options:A([f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:tb}),mt({id:"isolated",command:"isolated",description:"Find completely orphaned symbols (no references at all)",options:A([f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Minimum lines of code",k,3),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:nb}),Ie({id:"similar",command:"similar [symbol]",description:"Find heuristic function similarity candidates from callee fingerprints",options:A([f("--min-similarity <n>","Minimum Jaccard similarity (0-1)",ut,.4),f("-n, --limit <n>","Number of results",k,20),f("-s, --scope <path>","Limit to files matching path"),f("--min-callees <n>","Minimum callees to consider",k,4),f("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:lb}),Ie({id:"similar-files",command:"similar-files [file]",description:"Find heuristic similar-file candidates from dependency profiles",options:A([f("--min-similarity <n>","Minimum Jaccard similarity (0-1)",ut,.5),f("-n, --limit <n>","Number of results",k,20),f("-s, --scope <path>","Limit to files matching path"),f("--min-deps <n>","Minimum dependencies to consider",k),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:ub}),Ie({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:A([f("--min-similarity <n>","Minimum JSX structure similarity (0-1)",ut,.62),f("--min-tokens <n>","Minimum structural tokens to consider",k,8),f("-n, --limit <n>","Number of results",k,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:xb}),Ie({id:"react-hook-candidates",command:"react-hook-candidates [file]",description:"Find heuristic React hook extraction candidates from shared state, effects, requests, and handlers",options:A([f("--min-similarity <n>","Minimum behavior similarity (0-1)",ut,.45),f("--min-shared-behaviors <n>","Minimum shared behavior tokens",k,6),f("-n, --limit <n>","Number of results",k,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Cb}),Ie({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:A([f("--min-component-lines <n>","Minimum component lines",k,300),f("--min-file-lines <n>","Minimum file lines",k,800),f("--min-jsx-tokens <n>","Minimum JSX structure tokens",k,80),f("--min-behavior-tokens <n>","Minimum behavior tokens",k,40),f("-n, --limit <n>","Number of results",k,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:vb}),Ie({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:A([f("--min-similarity <n>","Minimum template similarity (0-1)",ut,.62),f("--min-tokens <n>","Minimum structural tokens to consider",k,8),f("-n, --limit <n>","Number of results",k,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:Rb}),Ie({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:A([f("--min-similarity <n>","Minimum behavior similarity (0-1)",ut,.45),f("--min-shared-behaviors <n>","Minimum shared behavior tokens",k,6),f("-n, --limit <n>","Number of results",k,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:kb}),Ie({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:A([f("--min-total-lines <n>","Minimum total component lines",k,800),f("--min-template-lines <n>","Minimum template lines",k,300),f("--min-script-lines <n>","Minimum script lines",k,300),f("--min-style-lines <n>","Minimum style lines",k,500),f("--review-thresholds","Use lower review thresholds without changing health scoring"),f("-n, --limit <n>","Number of results",k,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:wb}),Ie({id:"similar-chains",command:"similar-chains",description:"Find heuristic similar-chain candidates from dependency flows",options:A([f("--min-similarity <n>","Minimum chain similarity (0-1)",ut,.5),f("-n, --limit <n>","Number of results",k,15),f("-s, --scope <path>","Limit to files matching path"),f("--min-length <n>","Minimum chain length",k,3),f("--max-length <n>","Maximum chain length",k,8),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:db}),Ie({id:"extract-candidates",command:"extract-candidates",description:"Find heuristic extraction candidates from isolated callee clusters",options:A([f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Minimum function LOC",k,10),f("--min-callees <n>","Minimum callees to analyze",k,6),f("-n, --limit <n>","Number of results",k,20),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:rb}),Ie({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",description:"Find directory-locality and ancestry candidates from consumer ownership",options:A([f("-s, --scope <path>","Limit scan mode to files matching path"),f("--min-consumers <n>","Minimum consumers in scan mode",k,1),f("-n, --limit <n>","Number of results",k,20),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"locality candidates",budget:"candidate-scan",renderShape:"custom",docs:I("Cleanup",["scip-query locality-candidates","scip-query locality-candidates formatName --json","scip-query locality-candidates src/shared/date.ts"]),handler:ib}),Ie({id:"drift",command:"drift [module]",description:"Detect heuristic drift candidates: unused imports, layer violations, and pattern deviations",options:A([f("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",Vi,5),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:mb}),Ie({id:"wrapper-candidates",command:"wrapper-candidates",description:"Find heuristic wrapper candidates only called by one consumer",options:A([f("-s, --scope <path>","Limit to files matching path"),f("--max-loc <n>","Maximum LOC for candidates",k,15),f("-n, --limit <n>","Number of results",k,30),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:ob}),Ie({id:"passthrough-candidates",command:"passthrough-candidates",description:"Find heuristic passthrough candidates that forward to one callee",options:A([f("-s, --scope <path>","Limit to files matching path"),f("--max-loc <n>","Maximum LOC for candidates",k,15),f("-n, --limit <n>","Number of results",k,30),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:sb}),Ie({id:"stale-abstractions",command:"stale-abstractions",description:"Find heuristic stale abstraction candidates with 0-1 consumers",options:A([f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Minimum LOC",k,3),f("-n, --limit <n>","Number of results",k,30),f("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:ab}),Ie({id:"complexity-hotspots",command:"complexity-hotspots",description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:A([f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Minimum LOC",k,10),f("-n, --limit <n>","Number of results",k,20),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:cb}),mt({id:"convergence",command:"convergence <symbol1> <symbol2>",description:"Show what a consolidated version of two similar functions would look like",options:A([f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:pb}),Yy({id:"redundant-reexports",command:"redundant-reexports",description:"Find barrel re-exports that nobody imports through",options:[f("-s, --scope <path>","Limit to files matching path"),f("-n, --limit <n>","Number of results",k,30),f("--full","Run unbounded analysis on large indexes")],docs:I("Cleanup"),query:({db:e,opts:t})=>ll(e,{scope:_(t,"scope"),limit:j(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
1013
+ ${e.length} large Vue view pressure file(s) found.`)}});function Rt(e){return{docs:E("Cleanup"),...e}}function Me({heuristicLabel:e,...t}){return Rt({...t,heuristic:{label:e}})}var Fa=[Rt({id:"unused-params",command:"unused-params",description:"Speculative-generality candidates: trailing parameters no body ever uses (TS/JS)",options:j([h("-s, --scope <path>","Limit to files matching path"),h("-n, --limit <n>","Maximum findings",I,30),h("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:E("Cleanup",["scip-query unused-params -s src/services"]),handler:mx}),Rt({id:"cleanup-plan",command:"cleanup-plan",description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:[h("-s, --scope <path>","Limit to files matching path"),h("--min-loc <n>","Only include symbols >= N lines",I,1),h("--max-depth <n>","Maximum cascade depth",I,5),h("--verify","Apply batches in a throwaway worktree and run the project checker (tsc / cargo check)"),h("--patch","With --verify, print the compiler-verified deletion patch to stdout"),h("--json","Output as JSON for programmatic consumption"),h("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:E("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:cx}),Rt({id:"cleanup-apply",command:"cleanup-apply",description:"Apply a compiler-verified cleanup-plan batch to the working tree",options:[h("-s, --scope <path>","Limit to files matching path"),h("--min-loc <n>","Only include symbols >= N lines",I,1),h("--max-depth <n>","Maximum cascade depth",I,5),h("--verified","Required: verify the selected cleanup batch before applying it"),h("--batch <n>","Apply one batch depth",I),h("--all","Apply every compiler-verified batch in the plan"),h("--force-dirty","Allow applying when plan files already have working-tree edits"),h("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:E("Cleanup",["scip-query cleanup-apply --verified --batch 0"]),handler:lx}),Rt({id:"recent-duplicates",command:"recent-duplicates",description:"Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code",options:j([h("--window <n>",'How many commits back counts as "recent"',I,100),h("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",xt),h("-n, --limit <n>","Maximum findings",I,30),h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:E("Cleanup",["scip-query recent-duplicates --window 50"]),handler:ux}),Rt({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:j([h("-n, --limit <n>","Maximum docs to report",I,20),h("--min-coupling <n>","Minimum historical co-changes to track a subject",I,3),h("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:E("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:dx}),Rt({id:"dead",command:"dead [scope]",description:"Find dead code and file-internal symbols (no cross-file consumers)",options:j([h("--min-loc <n>","Only show symbols >= N lines",I,1),h("--include-tests","Include test files"),h("--skip-barrels","Ignore refs from barrel re-export files"),h("--include-members","Include class members"),h("--only-dead","Show only [dead code] symbols (skip [file-internal only])"),h("--only-internal","Show only [file-internal only] symbols (skip [dead code])"),h("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:E("Cleanup",["scip-query dead --min-loc 10"]),handler:GS}),Rt({id:"unused-imports",command:"unused-imports <file>",description:"Find imports not referenced in the same file",options:j([h("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:KS}),Rt({id:"isolated",command:"isolated",description:"Find completely orphaned symbols (no references at all)",options:j([h("-s, --scope <path>","Limit to files matching path"),h("--min-loc <n>","Minimum lines of code",I,3),h("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:JS}),Me({id:"similar",command:"similar [symbol]",description:"Find heuristic function similarity candidates from callee fingerprints",options:j([h("--min-similarity <n>","Minimum Jaccard similarity (0-1)",xt,.4),h("-n, --limit <n>","Number of results",I,20),h("-s, --scope <path>","Limit to files matching path"),h("--min-callees <n>","Minimum callees to consider",I,4),h("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),h("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:nx}),Me({id:"similar-files",command:"similar-files [file]",description:"Find heuristic similar-file candidates from dependency profiles",options:j([h("--min-similarity <n>","Minimum Jaccard similarity (0-1)",xt,.5),h("-n, --limit <n>","Number of results",I,20),h("-s, --scope <path>","Limit to files matching path"),h("--min-deps <n>","Minimum dependencies to consider",I),h("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:ix}),Me({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:j([h("--min-similarity <n>","Minimum JSX structure similarity (0-1)",xt,.62),h("--min-tokens <n>","Minimum structural tokens to consider",I,8),h("-n, --limit <n>","Number of results",I,20),h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:px}),Me({id:"react-hook-candidates",command:"react-hook-candidates [file]",description:"Find heuristic React hook extraction candidates from shared state, effects, requests, and handlers",options:j([h("--min-similarity <n>","Minimum behavior similarity (0-1)",xt,.45),h("--min-shared-behaviors <n>","Minimum shared behavior tokens",I,6),h("-n, --limit <n>","Number of results",I,20),h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:fx}),Me({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:j([h("--min-component-lines <n>","Minimum component lines",I,300),h("--min-file-lines <n>","Minimum file lines",I,800),h("--min-jsx-tokens <n>","Minimum JSX structure tokens",I,80),h("--min-behavior-tokens <n>","Minimum behavior tokens",I,40),h("-n, --limit <n>","Number of results",I,20),h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:gx}),Me({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:j([h("--min-similarity <n>","Minimum template similarity (0-1)",xt,.62),h("--min-tokens <n>","Minimum structural tokens to consider",I,8),h("-n, --limit <n>","Number of results",I,20),h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:hx}),Me({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:j([h("--min-similarity <n>","Minimum behavior similarity (0-1)",xt,.45),h("--min-shared-behaviors <n>","Minimum shared behavior tokens",I,6),h("-n, --limit <n>","Number of results",I,20),h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:yx}),Me({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:j([h("--min-total-lines <n>","Minimum total component lines",I,800),h("--min-template-lines <n>","Minimum template lines",I,300),h("--min-script-lines <n>","Minimum script lines",I,300),h("--min-style-lines <n>","Minimum style lines",I,500),h("--review-thresholds","Use lower review thresholds without changing health scoring"),h("-n, --limit <n>","Number of results",I,20),h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:bx}),Me({id:"similar-chains",command:"similar-chains",description:"Find heuristic similar-chain candidates from dependency flows",options:j([h("--min-similarity <n>","Minimum chain similarity (0-1)",xt,.5),h("-n, --limit <n>","Number of results",I,15),h("-s, --scope <path>","Limit to files matching path"),h("--min-length <n>","Minimum chain length",I,3),h("--max-length <n>","Maximum chain length",I,8),h("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:rx}),Me({id:"extract-candidates",command:"extract-candidates",description:"Find heuristic extraction candidates from isolated callee clusters",options:j([h("-s, --scope <path>","Limit to files matching path"),h("--min-loc <n>","Minimum function LOC",I,10),h("--min-callees <n>","Minimum callees to analyze",I,6),h("-n, --limit <n>","Number of results",I,20),h("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:XS}),Me({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",description:"Find directory-locality and ancestry candidates from consumer ownership",options:j([h("-s, --scope <path>","Limit scan mode to files matching path"),h("--min-consumers <n>","Minimum consumers in scan mode",I,1),h("-n, --limit <n>","Number of results",I,20),h("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"locality candidates",budget:"candidate-scan",renderShape:"custom",docs:E("Cleanup",["scip-query locality-candidates","scip-query locality-candidates formatName --json","scip-query locality-candidates src/shared/date.ts"]),handler:QS}),Me({id:"drift",command:"drift [module]",description:"Detect heuristic drift candidates: unused imports, layer violations, and pattern deviations",options:j([h("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",mo,5),h("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:ox}),Me({id:"wrapper-candidates",command:"wrapper-candidates",description:"Find heuristic wrapper candidates only called by one consumer",options:j([h("-s, --scope <path>","Limit to files matching path"),h("--max-loc <n>","Maximum LOC for candidates",I,15),h("-n, --limit <n>","Number of results",I,30),h("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:YS}),Me({id:"passthrough-candidates",command:"passthrough-candidates",description:"Find heuristic passthrough candidates that forward to one callee",options:j([h("-s, --scope <path>","Limit to files matching path"),h("--max-loc <n>","Maximum LOC for candidates",I,15),h("-n, --limit <n>","Number of results",I,30),h("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:ZS}),Me({id:"stale-abstractions",command:"stale-abstractions",description:"Find heuristic stale abstraction candidates with 0-1 consumers",options:j([h("-s, --scope <path>","Limit to files matching path"),h("--min-loc <n>","Minimum LOC",I,3),h("-n, --limit <n>","Number of results",I,30),h("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),h("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:ex}),Me({id:"complexity-hotspots",command:"complexity-hotspots",description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:j([h("-s, --scope <path>","Limit to files matching path"),h("--min-loc <n>","Minimum LOC",I,10),h("-n, --limit <n>","Number of results",I,20),h("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:tx}),Rt({id:"convergence",command:"convergence <symbol1> <symbol2>",description:"Show what a consolidated version of two similar functions would look like",options:j([h("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:sx}),zS({id:"redundant-reexports",command:"redundant-reexports",description:"Find barrel re-exports that nobody imports through",options:[h("-s, --scope <path>","Limit to files matching path"),h("-n, --limit <n>","Number of results",I,30),h("--full","Run unbounded analysis on large indexes")],docs:E("Cleanup"),query:({db:e,opts:t})=>ou(e,{scope:_(t,"scope"),limit:V(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
989
1014
  barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s) | tier: ${e.actionTier}
990
1015
  Recommendation: ${e.recommendation}`+(e.surfaceEvidence.length>0?`
991
1016
  Surface evidence: ${e.surfaceEvidence.join("; ")}`:""),key:e=>e.barrelFile,emptyMessage:()=>"No redundant re-exports found.",after:e=>console.log(`
992
- ${e.length} redundant re-export(s).`)}),mt({id:"similar-signatures",command:"similar-signatures",description:"Find functions with near-identical type signatures (same shape)",options:A([f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Minimum LOC per function",k,3),f("-n, --limit <n>","Number of groups",k,20),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:fb})];var qB=K(({db:e,args:t,opts:n})=>{let r=Oe(e);if(w(n,"json")){M("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: ${Vn(r.indexSizeBytes)}`),r.lastBuilt&&console.log(`Last built: ${r.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),Lb=[{id:"stats",command:"stats",description:"Show index statistics",options:[vl()],renderShape:"custom",docs:I("Core"),handler:qB}];var UB=Xs("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>uc(e,{limit:j(t,"limit",20),scope:_(t,"scope"),minFanIn:E(t,"minFanIn",2),minFanOut:E(t,"minFanOut",2),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${e.actionTier.padEnd(6)} ${e.riskKind.padEnd(20)} ${String(e.score).padStart(5)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No bottlenecks found."}),WB=K(({db:e,args:t,opts:n})=>{let r=ye(t,0),i=j(n,"limit",30);if(r){let s=ic(e,r);if(w(n,"json")){M("fan-in",t,n,{mode:"symbol",symbol:r,rows:s});return}if(s.length===0)return N.empty(`No fan-in for ${r}.`);N.list(s,a=>` ${String(a.count).padStart(4)} files ${a.name}`);return}let o=sc(e,{limit:i,scope:_(n,"scope")});if(w(n,"json")){M("fan-in",t,n,{mode:"top",rows:o});return}N.table(["files","symbol"],o.map(s=>` ${String(s.count).padStart(5)} ${s.name}`))}),GB=K(({db:e,args:t,opts:n})=>{let r=ye(t,0),i=j(n,"limit",30);if(r){let s=oc(e,r);if(w(n,"json")){M("fan-out",t,n,{mode:"file",file:r,rows:s});return}if(s.length===0)return N.empty(`No fan-out for ${r}.`);N.list(s,a=>` ${String(a.count).padStart(4)} symbols ${a.name}`);return}let o=ac(e,{limit:i,scope:_(n,"scope")});if(w(n,"json")){M("fan-out",t,n,{mode:"top",rows:o});return}N.table(["symbols","file"],o.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),zB=K(({db:e,args:t,opts:n})=>{let r=ye(t,0),i=ye(t,1),o=j(n,"limit",20);if(r&&i){let a=cc(e,r,i);if(w(n,"json")){M("coupling",t,n,{mode:"pair",result:a});return}console.log(`${a.file1} \u2194 ${a.file2}: ${a.sharedSymbols} shared symbols (${a.actionTier})`),console.log(` Risk: ${a.couplingKind}`),console.log(` Recommendation: ${a.recommendation}`);return}let s=lc(e,{limit:o,scope:_(n,"scope")});if(w(n,"json")){M("coupling",t,n,{mode:"top",rows:s});return}N.table(["tier","risk","shared","file1 \u2192 file2"],s.map(a=>` ${a.actionTier.padEnd(6)} ${a.couplingKind.padEnd(22)} ${String(a.sharedSymbols).padStart(6)} ${a.file1} \u2192 ${a.file2}`))}),JB=Kn({commandName:"cycles",query:({db:e,opts:t})=>Ln(e,{scope:_(t,"scope"),maxDepth:E(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(`
993
- 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(`
994
- ${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.)`)}}),KB=Kn({commandName:"deep-chains",query:({db:e,opts:t})=>gc(e,{limit:j(t,"limit",10),scope:_(t,"scope"),minDepth:E(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(`
995
- Chain ${t+1} (depth ${e[t].depth}):`);for(let n of e[t].chain)console.log(` \u2192 ${n}`);console.log(` Tier: ${e[t].actionTier} Risk: ${e[t].chainKind}`),console.log(` Recommendation: ${e[t].recommendation}`),console.log(` Evidence: ${e[t].evidenceReasons.join("; ")}`)}}}),Ib=[Ys({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",options:[f("-n, --limit <n>","Number of results",k,30),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")],docs:I("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>Ya(e,{limit:j(t,"limit",30),scope:_(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:A([f("-n, --limit <n>","Number of results for top mode",k,30),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:I("Graph"),handler:WB},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",options:A([f("-n, --limit <n>","Number of results for top mode",k,30),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:I("Graph"),handler:GB},{id:"coupling",command:"coupling [file1] [file2]",description:"Coupling between two files, or top coupled pairs in codebase",options:A([f("-n, --limit <n>","Number of results for top mode",k,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:I("Graph"),handler:zB},{id:"cycles",command:"cycles",description:"Detect circular dependency chains between files",options:A([f("-s, --scope <path>","Limit to files matching path"),f("--max-depth <n>","Maximum cycle depth",k,10)]),renderShape:"custom",docs:I("Graph"),handler:JB},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",options:A([f("-n, --limit <n>","Number of results",k,20),f("-s, --scope <path>","Limit to files matching path"),f("--min-fan-in <n>","Minimum fan-in",k,2),f("--min-fan-out <n>","Minimum fan-out",k,2),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:I("Graph"),handler:UB},{id:"deep-chains",command:"deep-chains",description:"Find the longest transitive dependency chains",options:A([f("-n, --limit <n>","Number of chains to show",k,10),f("-s, --scope <path>","Limit to files matching path"),f("--min-depth <n>","Minimum chain depth",k,3),f("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:I("Graph"),handler:KB},Zs({id:"call-graph",command:"call-graph <symbol>",description:"Show incoming callers and outgoing callees for a symbol",options:[f("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:I("Graph"),query:({db:e,args:t,budget:n})=>yi(e,String(t[0]),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"Symbol not found.",before:e=>{e&&console.log(`Symbol: ${e.shortName}
996
- `)},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 XB=Y("complexity",({db:e,args:t,opts:n,budget:r})=>{let i=_i(e,H(t,0),{semantic:r.semantic});if(w(n,"json")){M("complexity",t,n,i);return}if(!i)return N.empty("Symbol not found.");console.log(`${Re(i.relativePath,i.startLine,i.endLine)} ${i.shortName}
997
- `),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}`)}),QB=K(({db:e,args:t,opts:n})=>{let r=dl(e,{samples:E(n,"samples",50),scope:_(n,"scope")});if(w(n,"json")){M("self-audit",t,n,r);return}if(!r.available)return N.empty("No semantic provider available to audit against (TypeScript projects only).");console.log(`Sampled ${r.sampleSize} symbols; oracle answered ${Math.round(r.oracleCoverage*100)}%.
998
- `),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(`
999
- 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(", ")}`)}}),Db=[{id:"self-audit",command:"self-audit",description:"Score the cheap evidence paths against the TypeScript compiler oracle on sampled symbols",options:A([f("--samples <n>","Number of symbols to sample",k,50),f("-s, --scope <path>","Limit sampling to files matching path")]),renderShape:"custom",docs:I("Health",["scip-query self-audit --samples 100"]),handler:QB},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",options:A([f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:I("Health"),handler:XB}];var YB=K(({db:e,args:t,opts:n})=>{let r=Ri(e,H(t,0),{maxDepth:E(n,"maxDepth",5),scope:_(n,"scope")});if(w(n,"json")){M("affected",t,n,r);return}if(r.length===0)return N.empty("No affected symbols found.");let i=-1;for(let o of r)o.depth!==i&&(console.log(`
1000
- \u2500\u2500 Depth ${o.depth} \u2500\u2500`),i=o.depth),console.log(` ${o.file} ${o.shortName}`);console.log(`
1001
- ${r.length} affected symbol(s) across ${new Set(r.map(o=>o.file)).size} files.`)}),ZB=K(({db:e,args:t,opts:n})=>{let r=t[0]===void 0?void 0:H(t,0),i=Fn(e,r,{minTogether:E(n,"minTogether",4),limit:j(n,"limit",30),includeLinked:n.all===!0});if(w(n,"json")){M("co-change",t,n,i);return}if(!i.available)return N.empty("No git history available (not a repository, or git missing).");if(i.findings.length===0)return N.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):
1002
- `:`Hidden coupling \u2014 pairs that co-change with no dependency edge (${i.commitsAnalyzed} commits analyzed):
1003
- `);for(let o of i.findings){let s=o.structurallyLinked?" [dep edge]":"",a=` [${o.partnerClass}]`,c=` [${o.commitScope}/${o.recency}]`;console.log(` ${o.together}x (${Math.round(o.confidence*100)}%) ${o.fileA} <-> ${o.fileB}${a}${c}${s}`),console.log(` history: ${o.focusedTogether} focused, ${o.broadTogether} broad-sweep (${Math.round(o.broadCommitRatio*100)}% broad), ${o.recentTogether} recent; last ${e1(o.lastTogetherAt)}`),console.log(` subjects: ${t1(o.subjectContext)}`),o.declaredCouplingSuggestion&&console.log(` declare coupling: ${o.declaredCouplingSuggestion.name} (${o.declaredCouplingSuggestion.reason})`)}console.log(`
1004
- ${i.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function e1(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function t1(e){let t=e.subjectLabels.length>0?e.subjectLabels.slice(0,5).join(", "):"none inferred",n=e.issueRefs.length>0?e.issueRefs.slice(0,5).join(", "):"none",r=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(i=>`"${i}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${r}; external issue/PR labels ${e.externalIssueLabelStatus}`}var n1=Y("change-surface",({db:e,args:t,opts:n,budget:r})=>{let i=ki(e,H(t,0),{semantic:r.semantic});if(w(n,"json")){M("change-surface",t,n,i);return}if(!i)return N.empty("File not found in index.");console.log(`File: ${i.file}`),console.log(`External consumers: ${i.totalExternalConsumers}
1005
- `),N.list(i.symbols,o=>{let s=o.riskLevel==="high"?" *** HIGH RISK ***":o.riskLevel==="medium"?" * medium risk *":"";return` ${we(o.startLine,o.endLine)} ${o.shortName} [${o.externalConsumers} consumers]${s}`})}),r1=Y("incomplete-migration",({db:e,args:t,opts:n,budget:r})=>{let i=Ni(e,{base:_(n,"base"),minContainment:E(n,"minContainment",.7),maxHelpers:Le(n,"maxHelpers"),limit:j(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic});if(w(n,"json")){M("incomplete-migration",t,n,i),i.available&&i.findings.length>0&&(process.exitCode=1);return}if(!i.available)return N.empty("No git history available (not a repository, or git missing).");if(i.changedFiles.length===0)return N.empty(`No changes vs ${i.base}.`);console.log(`Incomplete migrations vs ${i.base}: ${i.changedFiles.length} changed file(s), ${i.helpersChecked} new helper(s) scored.`),i.note&&console.log(` note: ${i.note}`);for(let o of i.skipped)console.log(` skipped ${o.helperShortName} (${o.helperFile}): ${o.reason}`);if(i.findings.length===0){console.log(`
1006
- No incomplete migrations detected.`);return}for(let o of i.findings){console.log(`
1017
+ ${e.length} redundant re-export(s).`)}),Rt({id:"similar-signatures",command:"similar-signatures",description:"Find functions with near-identical type signatures (same shape)",options:j([h("-s, --scope <path>","Limit to files matching path"),h("--min-loc <n>","Minimum LOC per function",I,3),h("-n, --limit <n>","Number of groups",I,20),h("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:ax})];var Eq=ne(({db:e,args:t,opts:n})=>{let i=We(e);if(P(n,"json")){B("stats",t,n,i);return}console.log(`Documents: ${i.documents}`),console.log(`Symbols: ${i.symbols}`),console.log(`Definitions: ${i.definitions}`),console.log(`References: ${i.references}`),console.log(`Index size: ${ci(i.indexSizeBytes)}`),i.lastBuilt&&console.log(`Last built: ${i.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),Sx=[{id:"stats",command:"stats",description:"Show index statistics",options:[bu()],renderShape:"custom",docs:E("Core"),handler:Eq}];var Nq=La("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>il(e,{limit:V(t,"limit",20),scope:_(t,"scope"),minFanIn:F(t,"minFanIn",2),minFanOut:F(t,"minFanOut",2),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${e.actionTier.padEnd(6)} ${e.riskKind.padEnd(20)} ${String(e.score).padStart(5)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No bottlenecks found."}),Fq=ne(({db:e,args:t,opts:n})=>{let i=ke(t,0),r=V(n,"limit",30);if(i){let s=Qc(e,i);if(P(n,"json")){B("fan-in",t,n,{mode:"symbol",symbol:i,rows:s});return}if(s.length===0)return N.empty(`No fan-in for ${i}.`);N.list(s,a=>` ${String(a.count).padStart(4)} files ${a.name}`);return}let o=Zc(e,{limit:r,scope:_(n,"scope")});if(P(n,"json")){B("fan-in",t,n,{mode:"top",rows:o});return}N.table(["files","symbol"],o.map(s=>` ${String(s.count).padStart(5)} ${s.name}`))}),Tq=ne(({db:e,args:t,opts:n})=>{let i=ke(t,0),r=V(n,"limit",30);if(i){let s=Yc(e,i);if(P(n,"json")){B("fan-out",t,n,{mode:"file",file:i,rows:s});return}if(s.length===0)return N.empty(`No fan-out for ${i}.`);N.list(s,a=>` ${String(a.count).padStart(4)} symbols ${a.name}`);return}let o=el(e,{limit:r,scope:_(n,"scope")});if(P(n,"json")){B("fan-out",t,n,{mode:"top",rows:o});return}N.table(["symbols","file"],o.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),_q=ne(({db:e,args:t,opts:n})=>{let i=ke(t,0),r=ke(t,1),o=V(n,"limit",20);if(i&&r){let a=tl(e,i,r);if(P(n,"json")){B("coupling",t,n,{mode:"pair",result:a});return}console.log(`${a.file1} \u2194 ${a.file2}: ${a.sharedSymbols} shared symbols (${a.actionTier})`),console.log(` Risk: ${a.couplingKind}`),console.log(` Recommendation: ${a.recommendation}`);return}let s=nl(e,{limit:o,scope:_(n,"scope")});if(P(n,"json")){B("coupling",t,n,{mode:"top",rows:s});return}N.table(["tier","risk","shared","file1 \u2192 file2"],s.map(a=>` ${a.actionTier.padEnd(6)} ${a.couplingKind.padEnd(22)} ${String(a.sharedSymbols).padStart(6)} ${a.file1} \u2192 ${a.file2}`))}),Aq=fi({commandName:"cycles",query:({db:e,opts:t})=>Un(e,{scope:_(t,"scope"),maxDepth:F(t,"maxDepth",10)}),emptyMessage:e=>e.length===0?"No circular dependencies found.":void 0,render:e=>{let t=e.filter(i=>i.kind==="real"),n=e.filter(i=>i.kind==="module-hierarchy");for(let i=0;i<t.length;i++){console.log(`
1018
+ Cycle ${i+1} (${t[i].path.length-1} files):`);for(let r=0;r<t[i].path.length;r++){let o=r<t[i].path.length-1?" \u2192":" (cycle)";console.log(` ${t[i].path[r]}${o}`)}}t.length===0?console.log("No real circular dependencies found."):console.log(`
1019
+ ${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.)`)}}),Mq=fi({commandName:"deep-chains",query:({db:e,opts:t})=>sl(e,{limit:V(t,"limit",10),scope:_(t,"scope"),minDepth:F(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(`
1020
+ Chain ${t+1} (depth ${e[t].depth}):`);for(let n of e[t].chain)console.log(` \u2192 ${n}`);console.log(` Tier: ${e[t].actionTier} Risk: ${e[t].chainKind}`),console.log(` Recommendation: ${e[t].recommendation}`),console.log(` Evidence: ${e[t].evidenceReasons.join("; ")}`)}}}),xx=[Ea({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",options:[h("-n, --limit <n>","Number of results",I,30),h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded analysis on large indexes")],docs:E("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>Uc(e,{limit:V(t,"limit",30),scope:_(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:j([h("-n, --limit <n>","Number of results for top mode",I,30),h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:E("Graph"),handler:Fq},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",options:j([h("-n, --limit <n>","Number of results for top mode",I,30),h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:E("Graph"),handler:Tq},{id:"coupling",command:"coupling [file1] [file2]",description:"Coupling between two files, or top coupled pairs in codebase",options:j([h("-n, --limit <n>","Number of results for top mode",I,20),h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:E("Graph"),handler:_q},{id:"cycles",command:"cycles",description:"Detect circular dependency chains between files",options:j([h("-s, --scope <path>","Limit to files matching path"),h("--max-depth <n>","Maximum cycle depth",I,10)]),renderShape:"custom",docs:E("Graph"),handler:Aq},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",options:j([h("-n, --limit <n>","Number of results",I,20),h("-s, --scope <path>","Limit to files matching path"),h("--min-fan-in <n>","Minimum fan-in",I,2),h("--min-fan-out <n>","Minimum fan-out",I,2),h("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:E("Graph"),handler:Nq},{id:"deep-chains",command:"deep-chains",description:"Find the longest transitive dependency chains",options:j([h("-n, --limit <n>","Number of chains to show",I,10),h("-s, --scope <path>","Limit to files matching path"),h("--min-depth <n>","Minimum chain depth",I,3),h("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:E("Graph"),handler:Mq},Na({id:"call-graph",command:"call-graph <symbol>",description:"Show incoming callers and outgoing callees for a symbol",options:[h("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:E("Graph"),query:({db:e,args:t,budget:n})=>Br(e,String(t[0]),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"Symbol not found.",before:e=>{e&&console.log(`Symbol: ${e.shortName}
1021
+ `)},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 $q=le("complexity",({db:e,args:t,opts:n,budget:i})=>{let r=io(e,z(t,0),{semantic:i.semantic});if(P(n,"json")){B("complexity",t,n,r);return}if(!r)return N.empty("Symbol not found.");console.log(`${Fe(r.relativePath,r.startLine,r.endLine)} ${r.shortName}
1022
+ `),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}`)}),jq=ne(({db:e,args:t,opts:n})=>{let i=cu(e,{samples:F(n,"samples",50),scope:_(n,"scope")});if(P(n,"json")){B("self-audit",t,n,i);return}if(!i.available)return N.empty("No semantic or source-backed oracle available to audit against.");let r=i.oracleKind==="source"?"source facts":"compiler semantics";console.log(`Sampled ${i.sampleSize} symbols; ${r} oracle answered ${Math.round(i.oracleCoverage*100)}%.
1023
+ `),console.log(`Agreement with ${r} (file-level):`);for(let o of i.scores){let s=o.precision===null?`unverified ${o.unverified} (oracle partial \u2014 no precision claim)`:`precision ${o.precision}`;console.log(` ${o.question.padEnd(11)} ${s} recall ${o.recall} (${o.comparedSymbols} symbols)`)}if(i.topDisagreements.length>0){console.log(`
1024
+ Top disagreements (debugging targets):`);for(let o of i.topDisagreements)console.log(` ${o.symbol} [${o.question}]`),o.cheapOnly.length>0&&console.log(` cheap-only: ${o.cheapOnly.join(", ")}`),o.oracleOnly.length>0&&console.log(` oracle-only: ${o.oracleOnly.join(", ")}`)}}),Cx=[{id:"self-audit",command:"self-audit",description:"Score cheap evidence paths against the best available semantic/source oracle on sampled symbols",options:j([h("--samples <n>","Number of symbols to sample",I,50),h("-s, --scope <path>","Limit sampling to files matching path")]),renderShape:"custom",docs:E("Health",["scip-query self-audit --samples 100"]),handler:jq},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",options:j([h("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:E("Health"),handler:$q}];var Oq=ne(({db:e,args:t,opts:n})=>{let i=zr(e,z(t,0),{maxDepth:F(n,"maxDepth",5),scope:_(n,"scope")});if(P(n,"json")){B("affected",t,n,i);return}if(i.length===0)return N.empty("No affected symbols found.");let r=-1;for(let o of i)o.depth!==r&&(console.log(`
1025
+ \u2500\u2500 Depth ${o.depth} \u2500\u2500`),r=o.depth),console.log(` ${o.file} ${o.shortName}`);console.log(`
1026
+ ${i.length} affected symbol(s) across ${new Set(i.map(o=>o.file)).size} files.`)}),Bq=ne(({db:e,args:t,opts:n})=>{let i=t[0]===void 0?void 0:z(t,0),r=Zn(e,i,{minTogether:F(n,"minTogether",4),limit:V(n,"limit",30),includeLinked:n.all===!0});if(P(n,"json")){B("co-change",t,n,r);return}if(!r.available)return N.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return N.empty(i?`No co-change partners found for ${i} in ${r.commitsAnalyzed} commits.`:`No hidden coupling found in ${r.commitsAnalyzed} commits.`);console.log(i?`Co-change partners (${r.commitsAnalyzed} commits analyzed):
1027
+ `:`Hidden coupling \u2014 pairs that co-change with no dependency edge (${r.commitsAnalyzed} commits analyzed):
1028
+ `);for(let o of r.findings){let s=o.structurallyLinked?" [dep edge]":"",a=` [${o.partnerClass}]`,c=` [${o.commitScope}/${o.recency}]`;console.log(` ${o.together}x (${Math.round(o.confidence*100)}%) ${o.fileA} <-> ${o.fileB}${a}${c}${s}`),console.log(` history: ${o.focusedTogether} focused, ${o.broadTogether} broad-sweep (${Math.round(o.broadCommitRatio*100)}% broad), ${o.recentTogether} recent; last ${Hq(o.lastTogetherAt)}`),console.log(` subjects: ${Vq(o.subjectContext)}`),o.declaredCouplingSuggestion&&console.log(` declare coupling: ${o.declaredCouplingSuggestion.name} (${o.declaredCouplingSuggestion.reason})`)}console.log(`
1029
+ ${r.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function Hq(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function Vq(e){let t=e.subjectLabels.length>0?e.subjectLabels.slice(0,5).join(", "):"none inferred",n=e.issueRefs.length>0?e.issueRefs.slice(0,5).join(", "):"none",i=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(r=>`"${r}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${i}; external issue/PR labels ${e.externalIssueLabelStatus}`}var qq=le("change-surface",({db:e,args:t,opts:n,budget:i})=>{let r=Wr(e,z(t,0),{semantic:i.semantic});if(P(n,"json")){B("change-surface",t,n,r);return}if(!r)return N.empty("File not found in index.");console.log(`File: ${r.file}`),console.log(`External consumers: ${r.totalExternalConsumers}
1030
+ `),N.list(r.symbols,o=>{let s=o.riskLevel==="high"?" *** HIGH RISK ***":o.riskLevel==="medium"?" * medium risk *":"";return` ${_e(o.startLine,o.endLine)} ${o.shortName} [${o.externalConsumers} consumers]${s}`})}),Uq=le("incomplete-migration",({db:e,args:t,opts:n,budget:i})=>{let r=eo(e,{base:_(n,"base"),minContainment:F(n,"minContainment",.7),maxHelpers:Ae(n,"maxHelpers"),limit:V(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic});if(P(n,"json")){B("incomplete-migration",t,n,r),r.available&&r.findings.length>0&&(process.exitCode=1);return}if(!r.available)return N.empty("No git history available (not a repository, or git missing).");if(r.changedFiles.length===0)return N.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 o of r.skipped)console.log(` skipped ${o.helperShortName} (${o.helperFile}): ${o.reason}`);if(r.findings.length===0){console.log(`
1031
+ No incomplete migrations detected.`);return}for(let o of r.findings){console.log(`
1007
1032
  ${o.helperShortName} (${o.helperFile})`),console.log(` helper shape: ${o.helperShape} (${o.specificHelperCalleeCount}/${o.helperCalleeCount} specific callees)`),console.log(` wired into: ${o.migratedFiles.join(", ")}`);for(let s of o.leftovers)console.log(` un-migrated: ${Math.round(s.containment*100)}% helper / ${Math.round(s.siteCoverage*100)}% site [${s.migrationScope}] ${s.shortName} (${s.file})`),console.log(` scope: ${s.migrationScopeReasons.join("; ")}`),s.uniqueSiteCalleeCount>0&&console.log(` extra site callees: ${s.uniqueSiteCalleeCount}`),console.log(` shared: ${s.sharedCallees.join(", ")}`)}console.log(`
1008
- ${i.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)});function i1(e){let t=Array.isArray(e)?e:[],n=t.filter(r=>!bs.includes(r));return n.length>0&&(console.error(`error: unknown --skip check(s): ${n.join(", ")}. Valid checks: ${bs.join(", ")}`),process.exit(1)),t}var o1=K(({db:e,opts:t})=>{let n=t.hook===!0;if(n&&Us(Ki()))return;let r=Ds(e,"diff-gate",w(t,"full"),{quiet:n||w(t,"json")}),i=Ti(e,{base:_(t,"base"),minTogether:E(t,"minTogether",6),maxEchoChecks:Le(t,"maxEchoChecks"),maxHelpers:Le(t,"maxHelpers"),includeBaseline:w(t,"baseline"),scanLimit:r.scanLimit,semantic:r.semantic,skip:i1(t.skip)});if(!n&&w(t,"json")){M("diff-gate",[],t,{exitCode:i.findings.length>0?1:0,...i}),i.findings.length>0&&(process.exitCode=1);return}if(n){if(i.findings.length===0)return;console.error(Xi(i)),process.exitCode=2;return}if(i.changedFiles.length===0)return N.empty(i.note??`No changes vs ${i.base}.`);console.log(`Diff gate vs ${i.base}: ${i.changedFiles.length} file(s), ${i.changedSymbols} symbol(s) changed.`),console.log(`Checks: ${i.checksRun.join(", ")}
1009
- `);for(let s of i.skipped)console.log(` skipped ${s.check}: ${s.reason}`);if(i.findings.length===0){console.log("PASS: this change introduces no gate findings.");return}let o=i.rootCauseGroups?.filter(s=>s.count>1)??[];if(o.length>0){console.log(`Root-cause groups (${o.length}):`);for(let s of o){console.log(` [${s.check}] ${s.count} finding(s), ${s.severity}${s.actionTier?`, tier: ${s.actionTier}`:""}`),(s.sourceAnalyzer||s.rootCauseKey)&&console.log(` source: ${s.sourceAnalyzer??s.check}${s.rootCauseKey?` root cause: ${s.rootCauseKey}`:""}`);let a=[...new Set([...s.files,...s.relatedFiles])].slice(0,6);a.length>0&&console.log(` files: ${a.join(", ")}`),console.log(` -> ${s.remediation}`)}console.log("")}for(let s of i.findings){if(console.log(` [${s.check}] ${s.message}`),s.partnerClass){console.log(` partner class: ${s.partnerClass}`);for(let a of s.partnerClassReasons??[])console.log(` reason: ${a}`)}s.citationKind&&console.log(` citation kind: ${s.citationKind}${s.actionTier?` (tier: ${s.actionTier})`:""}`);for(let a of s.citedClaims?.slice(0,2)??[])console.log(` cited claim: ${ws(a)}`);s.declaredCouplingSuggestion&&console.log(` declare coupling: ${s.declaredCouplingSuggestion.name} (${s.declaredCouplingSuggestion.reason})`),console.log(` -> ${s.remediation}`)}console.log(`
1010
- FAIL: ${i.findings.length} finding(s), ${i.rootCauseGroups?.length??i.findings.length} root-cause group(s). Fix or knowingly accept before merging.`),process.exitCode=1}),Pb=[{id:"affected",command:"affected <symbol>",description:"Transitive closure of symbols that could break if this symbol changes",options:A([f("--max-depth <n>","Maximum traversal depth",k,5),f("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:I("Impact"),handler:YB},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: exports, consumers, and blast-radius risk",options:A([f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:I("Impact"),handler:n1},{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:[f("--base <ref>","Git ref to diff against (default: HEAD)"),f("--min-together <n>","Minimum historical co-changes for the partner check",k,6),f("--max-echo-checks <n>","Maximum changed symbols to test for echoes (default: all)",k),f("--max-helpers <n>","Maximum new helpers to score for incomplete-migration (default: all)",k),f("--baseline","Also run the full health-baseline ratchet"),f("--full","Run unbounded semantic analysis on large indexes"),f("--skip <check>","Skip a check (repeatable): echo, incomplete-migration, co-change-partner, doc-reference, unused-params, new-dead, baseline",Hi,[]),f("--hook","Agent Stop-hook mode: silent on pass, exit 2 with findings on stderr to block the stop"),f("--json","Output as JSON for programmatic consumption")],heuristic:{label:"diff gate candidates"},renderShape:"custom",docs:I("Impact",["scip-query diff-gate","scip-query diff-gate --base origin/main"]),handler:o1},{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:A([f("--base <ref>","Git ref to diff against (default: HEAD)"),f("--min-containment <n>","Minimum share of helper callees a site must contain (0-1)",ut,.7),f("--max-helpers <n>","Maximum new helpers to score (default: all)",k),f("-n, --limit <n>","Maximum findings to report",k,20),f("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"incomplete migration candidates"},renderShape:"custom",docs:I("Impact",["scip-query incomplete-migration","scip-query incomplete-migration --base origin/main"]),handler:r1},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",options:A([f("--min-together <n>","Minimum commits where both files changed",k,4),f("-n, --limit <n>","Maximum pairs to report",k,30),f("--all","Include pairs that already have a dependency edge"),f("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"co-change candidates"},renderShape:"custom",docs:I("Impact",["scip-query co-change","scip-query co-change src/runtime/config.ts"]),handler:ZB}];function s1(e){let t=[];for(let i of e.definitions){let o=i.signature?` \u2014 ${i.signature}`:"";t.push(` ${Re(i.relativePath,i.startLine,i.endLine)}${o}`),i.source&&t.push(i.source.split(`
1011
- `).map((s,a)=>` ${qe(i.startLine+a)} ${s}`).join(`
1012
- `))}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 ${qe(i.line)} in ${i.enclosingShort}`);return[{title:"DEFINITION",rows:t},{title:"REFERENCED BY",rows:n}]}var a1=K(({db:e,args:t,opts:n})=>{let r=H(t,0),i=w(n,"signatures"),o=nc(e,r);if(w(n,"json")){M("outline",t,n,o);return}if(o.length===0)return N.empty(`No symbols found for "${r}".`);function s(a,c){for(let l of a){let u=" ".repeat(c),d=i&&l.signature?` - ${c1(l.signature)}`:"";console.log(`${u}${we(l.startLine,l.endLine)} ${l.shortName}${d}`),s(l.children,c+1)}}s(o,0)});function c1(e){return e.length>120?`${e.slice(0,117)}...`:e}var l1=Mt("imports",{query:({db:e,args:t,budget:n})=>Za(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)."}),u1=Qs("refs",{query:({db:e,args:t,budget:n})=>Ga(e,H(t,0),{semantic:n.semantic}),format:e=>` line ${qe(e.line)}`}),d1=K(({db:e,args:t,opts:n})=>{let r=cl(e,H(t,0),{context:E(n,"context",0)});if(w(n,"json")){M("code",t,n,r);return}if(!r)return N.empty("Symbol not found or file unreadable.");console.log(`${Re(r.relativePath,r.startLine,r.endLine)} ${r.shortName} [${r.language??"unknown"}]
1013
- `);let i=r.source.split(`
1014
- `);for(let o=0;o<i.length;o++)console.log(` ${String(qe(r.startLine+o)).padStart(4)} ${i[o]}`)}),m1=Y("dataflow",({db:e,args:t,opts:n,budget:r})=>{let i=Fi(e,H(t,0),{semantic:r.semantic});if(w(n,"json")){M("dataflow",t,n,i);return}if(!i)return N.empty("Symbol not found.");if(console.log(`${i.shortName} (${i.relativePath})
1015
- `),i.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let o of i.definitionSites)console.log(` ${o.file}:${qe(o.line)}`)}if(i.usageSites.length>0){console.log(`
1016
- \u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let o of i.usageSites)console.log(` ${o.file}:${qe(o.line)} in ${o.enclosingShort}`)}if(i.producers.length>0){console.log(`
1017
- \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(`
1018
- \u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let o of i.consumers)console.log(` ${o.file} ${o.shortName}`)}}),p1=Y("slice",({db:e,args:t,opts:n,budget:r})=>{let i=w(n,"forward")?"forward":"backward",o=Tr(e,H(t,0),{direction:i,maxDepth:E(n,"depth",3),semantic:r.semantic});if(w(n,"json")){M("slice",t,n,o);return}if(!o)return N.empty("Symbol not found.");if(console.log(`${o.direction} slice of ${o.shortName}
1033
+ ${r.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)});function zq(e){let t=Array.isArray(e)?e:[],n=t.filter(i=>!Ws.includes(i));return n.length>0&&(console.error(`error: unknown --skip check(s): ${n.join(", ")}. Valid checks: ${Ws.join(", ")}`),process.exit(1)),t}var Wq=ne(({db:e,opts:t})=>{let n=t.hook===!0;if(n&&va(So()))return;let i=ra(e,"diff-gate",P(t,"full"),{quiet:n||P(t,"json")}),r=no(e,{base:_(t,"base"),minTogether:F(t,"minTogether",6),maxEchoChecks:Ae(t,"maxEchoChecks"),maxHelpers:Ae(t,"maxHelpers"),includeBaseline:P(t,"baseline"),scanLimit:i.scanLimit,semantic:i.semantic,skip:zq(t.skip)});if(!n&&P(t,"json")){B("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(xo(r)),process.exitCode=2;return}if(r.changedFiles.length===0)return N.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(", ")}
1034
+ `);for(let s of r.skipped)console.log(` skipped ${s.check}: ${s.reason}`);if(r.findings.length===0){console.log("PASS: this change introduces no gate findings.");return}let o=r.rootCauseGroups?.filter(s=>s.count>1)??[];if(o.length>0){console.log(`Root-cause groups (${o.length}):`);for(let s of o){console.log(` [${s.check}] ${s.count} finding(s), ${s.severity}${s.actionTier?`, tier: ${s.actionTier}`:""}`),(s.sourceAnalyzer||s.rootCauseKey)&&console.log(` source: ${s.sourceAnalyzer??s.check}${s.rootCauseKey?` root cause: ${s.rootCauseKey}`:""}`);let a=[...new Set([...s.files,...s.relatedFiles])].slice(0,6);a.length>0&&console.log(` files: ${a.join(", ")}`),console.log(` -> ${s.remediation}`)}console.log("")}for(let s of r.findings){if(console.log(` [${s.check}] ${s.message}`),s.partnerClass){console.log(` partner class: ${s.partnerClass}`);for(let a of s.partnerClassReasons??[])console.log(` reason: ${a}`)}s.citationKind&&console.log(` citation kind: ${s.citationKind}${s.actionTier?` (tier: ${s.actionTier})`:""}`);for(let a of s.citedClaims?.slice(0,2)??[])console.log(` cited claim: ${ta(a)}`);s.declaredCouplingSuggestion&&console.log(` declare coupling: ${s.declaredCouplingSuggestion.name} (${s.declaredCouplingSuggestion.reason})`),console.log(` -> ${s.remediation}`)}console.log(`
1035
+ FAIL: ${r.findings.length} finding(s), ${r.rootCauseGroups?.length??r.findings.length} root-cause group(s). Fix or knowingly accept before merging.`),process.exitCode=1}),vx=[{id:"affected",command:"affected <symbol>",description:"Transitive closure of symbols that could break if this symbol changes",options:j([h("--max-depth <n>","Maximum traversal depth",I,5),h("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:E("Impact"),handler:Oq},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: exports, consumers, and blast-radius risk",options:j([h("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:E("Impact"),handler:qq},{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:[h("--base <ref>","Git ref to diff against (default: HEAD)"),h("--min-together <n>","Minimum historical co-changes for the partner check",I,6),h("--max-echo-checks <n>","Maximum changed symbols to test for echoes (default: all)",I),h("--max-helpers <n>","Maximum new helpers to score for incomplete-migration (default: all)",I),h("--baseline","Also run the full health-baseline ratchet"),h("--full","Run unbounded semantic analysis on large indexes"),h("--skip <check>","Skip a check (repeatable): echo, incomplete-migration, co-change-partner, doc-reference, unused-params, new-dead, baseline",uo,[]),h("--hook","Agent Stop-hook mode: silent on pass, exit 2 with findings on stderr to block the stop"),h("--json","Output as JSON for programmatic consumption")],heuristic:{label:"diff gate candidates"},renderShape:"custom",docs:E("Impact",["scip-query diff-gate","scip-query diff-gate --base origin/main"]),handler:Wq},{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:j([h("--base <ref>","Git ref to diff against (default: HEAD)"),h("--min-containment <n>","Minimum share of helper callees a site must contain (0-1)",xt,.7),h("--max-helpers <n>","Maximum new helpers to score (default: all)",I),h("-n, --limit <n>","Maximum findings to report",I,20),h("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"incomplete migration candidates"},renderShape:"custom",docs:E("Impact",["scip-query incomplete-migration","scip-query incomplete-migration --base origin/main"]),handler:Uq},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",options:j([h("--min-together <n>","Minimum commits where both files changed",I,4),h("-n, --limit <n>","Maximum pairs to report",I,30),h("--all","Include pairs that already have a dependency edge"),h("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"co-change candidates"},renderShape:"custom",docs:E("Impact",["scip-query co-change","scip-query co-change src/runtime/config.ts"]),handler:Bq}];function Gq(e){let t=[];for(let r of e.definitions){let o=r.signature?` \u2014 ${r.signature}`:"";t.push(` ${Fe(r.relativePath,r.startLine,r.endLine)}${o}`),r.source&&t.push(r.source.split(`
1036
+ `).map((s,a)=>` ${Qe(r.startLine+a)} ${s}`).join(`
1037
+ `))}let n=[],i="";for(let r of e.referencedBy)r.relativePath!==i&&(i&&n.push(""),n.push(` ${r.relativePath}`),i=r.relativePath),n.push(` line ${Qe(r.line)} in ${r.enclosingShort}`);return[{title:"DEFINITION",rows:t},{title:"REFERENCED BY",rows:n}]}var Kq=ne(({db:e,args:t,opts:n})=>{let i=z(t,0),r=P(n,"signatures"),o=Jc(e,i);if(P(n,"json")){B("outline",t,n,o);return}if(o.length===0)return N.empty(`No symbols found for "${i}".`);function s(a,c){for(let l of a){let d=" ".repeat(c),u=r&&l.signature?` - ${Jq(l.signature)}`:"";console.log(`${d}${_e(l.startLine,l.endLine)} ${l.shortName}${u}`),s(l.children,c+1)}}s(o,0)});function Jq(e){return e.length>120?`${e.slice(0,117)}...`:e}var Xq=nn("imports",{query:({db:e,args:t,budget:n})=>zc(e,z(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)."}),Qq=Da("refs",{query:({db:e,args:t,budget:n})=>Bc(e,z(t,0),{semantic:n.semantic}),format:e=>` line ${Qe(e.line)}`}),Yq=ne(({db:e,args:t,opts:n})=>{let i=ru(e,z(t,0),{context:F(n,"context",0)});if(P(n,"json")){B("code",t,n,i);return}if(!i)return N.empty("Symbol not found or file unreadable.");console.log(`${Fe(i.relativePath,i.startLine,i.endLine)} ${i.shortName} [${i.language??"unknown"}]
1038
+ `);let r=i.source.split(`
1039
+ `);for(let o=0;o<r.length;o++)console.log(` ${String(Qe(i.startLine+o)).padStart(4)} ${r[o]}`)}),Zq=le("dataflow",({db:e,args:t,opts:n,budget:i})=>{let r=ro(e,z(t,0),{semantic:i.semantic});if(P(n,"json")){B("dataflow",t,n,r);return}if(!r)return N.empty("Symbol not found.");if(console.log(`${r.shortName} (${r.relativePath})
1040
+ `),r.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let o of r.definitionSites)console.log(` ${o.file}:${Qe(o.line)}`)}if(r.usageSites.length>0){console.log(`
1041
+ \u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let o of r.usageSites)console.log(` ${o.file}:${Qe(o.line)} in ${o.enclosingShort}`)}if(r.producers.length>0){console.log(`
1042
+ \u2550\u2550\u2550 PRODUCERS (feeds into this) \u2550\u2550\u2550`);for(let o of r.producers)console.log(` ${o.file} ${o.shortName}`)}if(r.consumers.length>0){console.log(`
1043
+ \u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let o of r.consumers)console.log(` ${o.file} ${o.shortName}`)}}),eU=le("slice",({db:e,args:t,opts:n,budget:i})=>{let r=P(n,"forward")?"forward":"backward",o=Ki(e,z(t,0),{direction:r,maxDepth:F(n,"depth",3),semantic:i.semantic});if(P(n,"json")){B("slice",t,n,o);return}if(!o)return N.empty("Symbol not found.");if(console.log(`${o.direction} slice of ${o.shortName}
1019
1044
  `),o.connectedSymbols.length===0){console.log(" No connected symbols found.");return}N.list(o.connectedSymbols,s=>` ${s.file} ${s.shortName}
1020
1045
  ${s.relationship}`),console.log(`
1021
- ${o.connectedSymbols.length} connected symbol(s).`)}),Nb=[wt({id:"files",command:"files <pattern>",description:"Find files matching a pattern",docs:I("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>ia(e,H(t,0)),format:e=>e.relativePath}),wt({id:"methods",command:"methods <className>",description:"List methods of a class (with line ranges)",docs:I("Navigation"),query:({db:e,args:t})=>Wa(e,H(t,0)),format:e=>` ${we(e.startLine,e.endLine)} ${e.name}`}),{id:"refs",command:"refs <symbol>",description:"Find all files referencing a symbol",options:[f("--full","Run unbounded semantic analysis on large indexes"),f("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"grouped-by-file",docs:I("Navigation",["scip-query refs login"]),handler:u1},Zs({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[f("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:I("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>di(e,H(t,0),{semantic:n.semantic}),sections:s1}),wt({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",docs:I("Navigation"),query:({db:e,args:t})=>mi(e,H(t,0)),format:e=>e.relativePath}),wt({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",docs:I("Navigation"),query:({db:e,args:t})=>pi(e,H(t,0)),format:e=>e.relativePath}),Zy({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})=>fi(e,H(t,0)),sections:e=>[{title:"FILES",rows:e.files},{title:"EXPORTED SYMBOLS",rows:e.symbols.map(t=>` ${we(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}`)}]}),wt({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",docs:I("Navigation"),query:({db:e,args:t})=>gi(e,H(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",options:[f("--full","Run unbounded semantic analysis on large indexes"),f("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"list",docs:I("Navigation"),handler:l1},wt({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",docs:I("Navigation"),query:({db:e,args:t})=>ec(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:A([f("--signatures","Show trimmed symbol signatures")]),renderShape:"custom",docs:I("Navigation"),handler:a1},wt({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",docs:I("Navigation"),query:({db:e,args:t})=>rc(e,H(t,0)),format:e=>` ${we(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`}),wt({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",options:[f("-s, --scope <path>","Limit to files matching path"),f("-n, --limit <n>","Number of results",k,100),f("--full","Run unbounded analysis on large indexes")],docs:I("Navigation"),query:({db:e,args:t,opts:n})=>pc(e,H(t,0),{scope:_(n,"scope"),limit:j(n,"limit",100)}),format:e=>` ${Re(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(`
1022
- ${e.length} symbol(s)`)}),Ys({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",options:[f("-s, --scope <path>","Limit to files matching path")],docs:I("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>fc(e,{scope:_(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),wt({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})=>hc(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:A([f("-C, --context <n>","Extra lines of context above/below",k,0)]),renderShape:"custom",docs:I("Navigation"),handler:d1},{id:"dataflow",command:"dataflow <symbol>",description:"Reference-level dataflow: definition sites, usage sites, producers, consumers",options:A([f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:I("Navigation"),handler:m1},{id:"slice",command:"slice <symbol>",description:"Reference-level program slice: what affects this (backward) or what this affects (forward)",options:A([f("--forward","Forward slice (what does this affect). Default is backward."),f("--depth <n>","Max transitive depth for backward slice",k,3),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:I("Navigation"),handler:p1}];var f1=Y("plan-context",({db:e,args:t,opts:n,budget:r})=>{let i=j(n,"limit",20),o=tl(e,H(t,0),{semantic:r.semantic,impactDepth:E(n,"impactDepth",3),sliceDepth:E(n,"sliceDepth",3),scope:_(n,"scope")});if(o.warnings.length===1&&o.warnings[0]==="No symbol, file, or module matched target."){if(w(n,"json")){M("plan-context",t,n,o);return}return N.empty(o.warnings[0])}if(w(n,"json")){M("plan-context",t,n,o);return}let s=[{title:"TARGET",rows:g1(o)},{title:"DEFINITIONS",rows:h1(o,i),skipIfEmpty:!0},{title:"REFERENCES",rows:y1(o,i),skipIfEmpty:!0},{title:"CALL GRAPH",rows:b1(o,i),skipIfEmpty:!0},{title:"DATAFLOW",rows:S1(o,i),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:x1(o,i),skipIfEmpty:!0},{title:"SURFACE",rows:C1(o,i),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:v1(o,i),skipIfEmpty:!0},{title:"CHANGE RISK",rows:R1(o,i),skipIfEmpty:!0},{title:"HISTORY",rows:k1(o),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:w1(o),skipIfEmpty:!0}];N.sectionedReport(s)}),Eb=[{id:"plan-context",command:"plan-context <target>",description:"Pre-edit planning context for a symbol, file, or module",options:A([f("--impact-depth <n>","Maximum affected traversal depth",k,3),f("--slice-depth <n>","Maximum backward slice depth",k,3),f("-s, --scope <path>","Limit downstream impact to files matching path"),f("-n, --limit <n>","Rows per section",k,20),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:I("Planning",["scip-query plan-context parseSymbol"]),handler:f1}];function g1(e){return[`Target: ${e.target}`,`Matched: symbol=${lu(e.matched.symbol)} file=${lu(e.matched.file)} module=${lu(e.matched.module)}`]}function h1(e,t){let n=[];for(let r of e.trace.definitions){let i=r.signature?` -- ${r.signature}`:"";n.push(` ${Re(r.relativePath,r.startLine,r.endLine)}${i}`),r.source&&n.push(...r.source.split(`
1023
- `).map((o,s)=>` ${String(qe(r.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(r=>` ${we(r.startLine,r.endLine)} ${r.shortName}`)),an(n,t).rows}function y1(e,t){let n=e.trace.referencedBy.map(r=>` ${r.relativePath}:${qe(r.line)} in ${r.enclosingShort}`);return Xn(an(n,t))}function b1(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 Xn(an([...n,...r],t))}function S1(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}:${qe(o.line)} in ${o.enclosingShort}`);return Xn(an([...n,...r,...i],t))}function x1(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 Xn(an(n,t))}function C1(e,t){let n=[...e.system.files.map(r=>` file ${r}`),...e.system.symbols.map(r=>` export ${we(r.startLine,r.endLine)} ${r.shortName}`),...e.surface.map(r=>` use ${r.consumer} -> ${r.shortName}`)];return Xn(an(n,t))}function v1(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 Xn(an(n,t))}function R1(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` ${we(r.startLine,r.endLine)} ${r.shortName} [${r.externalConsumers} consumers]${i}`}))),e.complexity&&(n.push(` Complexity: ${Re(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}`)),Xn(an(n,t))}function k1(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 w1(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 an(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function Xn(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function lu(e){return e?"yes":"no"}var Tb=["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","locality-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"],L1=[Lb,Nb,Ib,ea,Pb,Eb,Db],_b=L1.flat(),I1=new Map(_b.map(e=>[e.id,e]));for(let e of _b)if(!Tb.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var Gr=Tb.map(e=>D1(e));function D1(e){let t=I1.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var P1=Gr.slice(0,uu("plan-context")),N1=Gr.slice(ta("drift"),uu("self-audit")),E1=Gr.slice(ta("convergence"),uu("slice")),T1=Gr.slice(ta("redundant-reexports")),Fb=[{id:"reindex",command:"reindex",description:"Index the codebase and convert to SQLite",options:[f("-l, --language <lang>","Index only this language (can be repeated)",Hi,[]),f("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),f("--force","Rebuild even if source inputs are unchanged"),f("--allow-partial","Write an incomplete index when one or more detected languages fail"),f("--indexer-concurrency <n>","Number of language indexers to run at once",Vi)],renderShape:"custom",docs:I("Indexing",["scip-query reindex"]),handler:Ly},{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:Iy},{id:"augment-vue",command:"augment-vue",description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[f("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:I("Indexing"),handler:Dy},...P1,{id:Is,command:Is,description:"Internal diff-impact batch worker",hidden:!0,options:[f("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:Py},{id:"diff-impact",command:"diff-impact",description:"Compute changed symbols and downstream consumers from current git diff",options:A([f("--base <ref>","Git ref to diff against (default: HEAD)")]),renderShape:"custom",docs:I("Impact"),handler:Ny},...N1,{id:Bi,command:Bi,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:Ey},{id:"health",command:"health",description:"Composite codebase health report with prioritized action list",options:[f("-s, --scope <path>","Limit to files matching path"),f("--full","Compatibility flag; health already runs unbounded candidate analyses by default"),f("--json","Output as JSON for programmatic consumption"),f("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),f("--write-baseline","Snapshot current finding identities to the baseline file")],renderShape:"custom",docs:I("Health",["scip-query health --json","scip-query health --baseline"]),handler:Ty},{id:"bench",command:"bench",description:"Benchmark indexing and command runtimes for this repository",options:[f("--json","Output as JSON for programmatic consumption"),f("--cold-index","Temporarily clear this project index cache and measure a cold rebuild"),f("--include-heavy","Include expensive full-detector commands in the command matrix"),f("--command <cmd>","Benchmark a specific scip-query command (can be repeated)",Hi,[]),f("--timeout-ms <n>","Per-command timeout in milliseconds",Vi,18e4)],renderShape:"custom",docs:I("Maintenance",["scip-query bench","scip-query bench --json --cold-index"]),handler:_y},...E1,{id:"install-skills",command:"install-skills",description:`Install skills (${nu.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:I("Maintenance"),handler:$y},{id:"setup-hooks",command:"setup-hooks",description:"Install or refresh project-local Codex and Claude Code lifecycle hooks",options:[f("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:I("Maintenance",["scip-query setup-hooks","scip-query setup-hooks --json"]),handler:My},{id:"hook-context",command:"hook-context",description:"Internal agent lifecycle hook context renderer",hidden:!0,renderShape:"custom",handler:ey},{id:"hook-stop",command:"hook-stop",description:"Internal agent Stop hook wrapper for diff-gate",hidden:!0,renderShape:"custom",handler:ty},{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:Oy},{id:"capabilities",command:"capabilities",description:"Report which evidence and verification capabilities are available in this project",options:[f("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:I("Maintenance"),handler:jy},{id:"capability-matrix",command:"capability-matrix",description:"Report the evidence and verification capability matrix by language",options:[f("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:I("Maintenance"),handler:By},...T1,{id:"init",command:"init",description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:I("Maintenance"),handler:Vy},{id:"config-validate",command:"config-validate",description:"Validate .scipquery.json, including structured suppressions and declared coupling groups",options:[f("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:I("Maintenance",["scip-query config-validate"]),handler:qy},{id:"suppress",command:"suppress <id>",description:"Record an accepted finding in .scipquery.json with a required reason",options:A([f("--reason <text>","Required human reason for accepting the finding"),f("--check <check>","Optional detector/check name to narrow the suppression"),f("--file <path>","Optional file path to narrow the suppression"),f("--expires-at <iso>","Optional ISO date after which the suppression expires")]),renderShape:"custom",docs:I("Maintenance",['scip-query suppress SQABC123DEF456 --reason "intentional boundary"']),handler:Uy},{id:"doctor",command:"doctor",description:"Diagnose config, index freshness, dependency readiness, and project capabilities",options:[f("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:I("Maintenance"),handler:Wy},{id:"setup",command:"setup",description:"Bootstrap this project: install agent skills, refresh the index, verify capabilities, and report health",options:A([f("--git-hook","Also install a git pre-commit hook that runs diff-gate")]),renderShape:"custom",docs:I("Maintenance",["scip-query setup","scip-query setup --json"]),handler:Jy},{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:[f("--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:zy},{id:"setup-ci",command:"setup-ci",description:"Write a GitHub Actions workflow that runs scip-query reindex and diff-gate on pull requests",options:[f("--force","Overwrite an existing workflow"),f("--dry-run","Print the workflow without writing it")],renderShape:"custom",docs:I("Maintenance",["scip-query setup-ci"]),handler:Ky},{id:"watch",command:"watch",description:"Watch for file changes and reindex automatically",options:[f("--debounce <ms>","Ms to wait after last change (default: 30000)",Ns),f("--cooldown <ms>","Min ms between reindexes (default: 60000)",Ns),f("--git-poll <ms>","Ms between Git HEAD/index checks (default: 2000)",Ns)],renderShape:"custom",docs:I("Maintenance"),handler:Xy},{id:"status",command:"status",description:"Show index status for this project",options:[f("--json","Output as JSON for programmatic consumption"),f("--capabilities","Include the project capability matrix")],renderShape:"custom",docs:I("Maintenance"),handler:Qy}];function ta(e){let t=Gr.findIndex(n=>n.id===e);if(t<0)throw new Error(`Ordered query command descriptor is missing: ${e}`);return t}function uu(e){return ta(e)+1}function Ab(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){_1(o)}}),{descriptor:n,command:r}})}function _1(e){let t=e instanceof Error?e.message:String(e);console.error(`error: ${t}`),process.exitCode=1}import{existsSync as F1,mkdirSync as A1,readFileSync as $1,writeFileSync as M1}from"fs";import{homedir as O1}from"os";import{join as na}from"path";var j1=1440*60*1e3,Mb="update-check.json",B1="https://registry.npmjs.org/scip-query/latest";async function Ob(e={}){let t=e.env??process.env;if(t.SCIP_QUERY_UPDATE_CHECK==="0"||t.NO_UPDATE_NOTIFIER)return;let n=e.cacheDir??q1(t),r=e.now??Date.now(),i=e.currentVersion??Ls,o=U1(n),s=o&&r-o.checkedAt<j1?o.latestVersion:await W1(n,e.fetchLatestVersion??z1,r);if(!s||!V1(s,i))return;(e.writeNotice??(c=>console.error(c)))(H1(i,s))}function H1(e,t){return[`scip-query update available: ${e} -> ${t}.`,"Agent: tell your human to update with: npm install -g scip-query@latest",""].join(`
1024
- `)}function V1(e,t){let n=$b(e),r=$b(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 q1(e){let t=e.XDG_CACHE_HOME||na(O1(),".cache");return na(t,"scip-query")}function U1(e){let t=na(e,Mb);if(!F1(t))return null;try{let n=JSON.parse($1(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 W1(e,t,n){let r;try{r=await t()}catch{r=null}return G1(e,{checkedAt:n,latestVersion:r}),r}function G1(e,t){try{A1(e,{recursive:!0}),M1(na(e,Mb),`${JSON.stringify(t,null,2)}
1025
- `)}catch{}}async function z1(){let e=await fetch(B1,{signal:AbortSignal.timeout(1e3)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}function $b(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}ra.name("scip-query").description("Language-agnostic code intelligence CLI powered by SCIP indexes").version(Ls);Ab(ra,Fb);ra.hook("preAction",async()=>{await Ob()});K1()&&await ra.parseAsync();function K1(){if(!process.argv[1])return!1;let e=J1(import.meta.url);try{return jb(e)===jb(process.argv[1])}catch{return e===process.argv[1]}}export{ra as program,jr as renderHeuristicNotice};
1046
+ ${o.connectedSymbols.length} connected symbol(s).`)}),Rx=[Bt({id:"files",command:"files <pattern>",description:"Find files matching a pattern",docs:E("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>Ma(e,z(t,0)),format:e=>e.relativePath}),Bt({id:"methods",command:"methods <className>",description:"List methods of a class (with line ranges)",docs:E("Navigation"),query:({db:e,args:t})=>Oc(e,z(t,0)),format:e=>` ${_e(e.startLine,e.endLine)} ${e.name}`}),{id:"refs",command:"refs <symbol>",description:"Find all files referencing a symbol",options:[h("--full","Run unbounded semantic analysis on large indexes"),h("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"grouped-by-file",docs:E("Navigation",["scip-query refs login"]),handler:Qq},Na({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[h("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:E("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>Tr(e,z(t,0),{semantic:n.semantic}),sections:Gq}),Bt({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",docs:E("Navigation"),query:({db:e,args:t})=>_r(e,z(t,0)),format:e=>e.relativePath}),Bt({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",docs:E("Navigation"),query:({db:e,args:t})=>Ar(e,z(t,0)),format:e=>e.relativePath}),WS({id:"system",command:"system <module>",description:"Full module map: files, symbols, deps in/out",docs:E("Navigation",["scip-query system queries"]),query:({db:e,args:t})=>Mr(e,z(t,0)),sections:e=>[{title:"FILES",rows:e.files},{title:"EXPORTED SYMBOLS",rows:e.symbols.map(t=>` ${_e(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}`)}]}),Bt({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",docs:E("Navigation"),query:({db:e,args:t})=>$r(e,z(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",options:[h("--full","Run unbounded semantic analysis on large indexes"),h("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"list",docs:E("Navigation"),handler:Xq},Bt({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",docs:E("Navigation"),query:({db:e,args:t})=>Wc(e,z(t,0)),format:e=>` ${e.fromFile}`}),{id:"outline",command:"outline <file>",description:"Tree view of symbols in a file, with line ranges",options:j([h("--signatures","Show trimmed symbol signatures")]),renderShape:"custom",docs:E("Navigation"),handler:Kq},Bt({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",docs:E("Navigation"),query:({db:e,args:t})=>Xc(e,z(t,0)),format:e=>` ${_e(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`}),Bt({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",options:[h("-s, --scope <path>","Limit to files matching path"),h("-n, --limit <n>","Number of results",I,100),h("--full","Run unbounded analysis on large indexes")],docs:E("Navigation"),query:({db:e,args:t,opts:n})=>rl(e,z(t,0),{scope:_(n,"scope"),limit:V(n,"limit",100)}),format:e=>` ${Fe(e.relativePath,e.startLine,e.endLine)} [${e.kindName}] ${e.shortName}`,emptyMessage:({args:e})=>`No symbols found for kind "${z(e,0)}". Use "kind-counts" to see available kinds.`,after:e=>console.log(`
1047
+ ${e.length} symbol(s)`)}),Ea({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",options:[h("-s, --scope <path>","Limit to files matching path")],docs:E("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>ol(e,{scope:_(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),Bt({id:"hierarchy",command:"hierarchy <symbol>",description:"Show a symbol's ancestry chain (method \u2192 class \u2192 module)",docs:E("Navigation"),query:({db:e,args:t})=>al(e,z(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:j([h("-C, --context <n>","Extra lines of context above/below",I,0)]),renderShape:"custom",docs:E("Navigation"),handler:Yq},{id:"dataflow",command:"dataflow <symbol>",description:"Reference-level dataflow: definition sites, usage sites, producers, consumers",options:j([h("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:E("Navigation"),handler:Zq},{id:"slice",command:"slice <symbol>",description:"Reference-level program slice: what affects this (backward) or what this affects (forward)",options:j([h("--forward","Forward slice (what does this affect). Default is backward."),h("--depth <n>","Max transitive depth for backward slice",I,3),h("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:E("Navigation"),handler:eU}];var tU=le("plan-context",({db:e,args:t,opts:n,budget:i})=>{let r=V(n,"limit",20),o=Ql(e,z(t,0),{semantic:i.semantic,impactDepth:F(n,"impactDepth",3),sliceDepth:F(n,"sliceDepth",3),scope:_(n,"scope")});if(o.warnings.length===1&&o.warnings[0]==="No symbol, file, or module matched target."){if(P(n,"json")){B("plan-context",t,n,o);return}return N.empty(o.warnings[0])}if(P(n,"json")){B("plan-context",t,n,o);return}let s=[{title:"TARGET",rows:nU(o)},{title:"DEFINITIONS",rows:iU(o,r),skipIfEmpty:!0},{title:"REFERENCES",rows:rU(o,r),skipIfEmpty:!0},{title:"CALL GRAPH",rows:oU(o,r),skipIfEmpty:!0},{title:"DATAFLOW",rows:sU(o,r),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:aU(o,r),skipIfEmpty:!0},{title:"SURFACE",rows:cU(o,r),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:lU(o,r),skipIfEmpty:!0},{title:"CHANGE RISK",rows:uU(o,r),skipIfEmpty:!0},{title:"HISTORY",rows:dU(o),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:mU(o),skipIfEmpty:!0}];N.sectionedReport(s)}),kx=[{id:"plan-context",command:"plan-context <target>",description:"Pre-edit planning context for a symbol, file, or module",options:j([h("--impact-depth <n>","Maximum affected traversal depth",I,3),h("--slice-depth <n>","Maximum backward slice depth",I,3),h("-s, --scope <path>","Limit downstream impact to files matching path"),h("-n, --limit <n>","Rows per section",I,20),h("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:E("Planning",["scip-query plan-context parseSymbol"]),handler:tU}];function nU(e){return[`Target: ${e.target}`,`Matched: symbol=${sd(e.matched.symbol)} file=${sd(e.matched.file)} module=${sd(e.matched.module)}`]}function iU(e,t){let n=[];for(let i of e.trace.definitions){let r=i.signature?` -- ${i.signature}`:"";n.push(` ${Fe(i.relativePath,i.startLine,i.endLine)}${r}`),i.source&&n.push(...i.source.split(`
1048
+ `).map((o,s)=>` ${String(Qe(i.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(i=>` ${_e(i.startLine,i.endLine)} ${i.shortName}`)),kn(n,t).rows}function rU(e,t){let n=e.trace.referencedBy.map(i=>` ${i.relativePath}:${Qe(i.line)} in ${i.enclosingShort}`);return hi(kn(n,t))}function oU(e,t){if(!e.callGraph)return[];let n=e.callGraph.callers.map(r=>` caller ${r.file} ${r.shortName}`),i=e.callGraph.callees.map(r=>` callee ${r.file} ${r.shortName}`);return hi(kn([...n,...i],t))}function sU(e,t){if(!e.dataflow)return[];let n=e.dataflow.producers.map(o=>` producer ${o.file} ${o.shortName}`),i=e.dataflow.consumers.map(o=>` consumer ${o.file} ${o.shortName}`),r=e.dataflow.usageSites.map(o=>` usage ${o.file}:${Qe(o.line)} in ${o.enclosingShort}`);return hi(kn([...n,...i,...r],t))}function aU(e,t){let n=[...e.deps.map(i=>` file depends on ${i.relativePath}`),...e.rdeps.map(i=>` file depended on by ${i.relativePath}`),...e.system.dependsOn.map(i=>` module depends on ${i}`),...e.system.dependedOnBy.map(i=>` module used by ${i}`)];return hi(kn(n,t))}function cU(e,t){let n=[...e.system.files.map(i=>` file ${i}`),...e.system.symbols.map(i=>` export ${_e(i.startLine,i.endLine)} ${i.shortName}`),...e.surface.map(i=>` use ${i.consumer} -> ${i.shortName}`)];return hi(kn(n,t))}function lU(e,t){let n=[],i=-1;for(let r of e.affected)r.depth!==i&&(n.push(` -- Depth ${r.depth} --`),i=r.depth),n.push(` ${r.file} ${r.shortName}`);return hi(kn(n,t))}function uU(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(i=>{let r=i.riskLevel==="high"?" *** HIGH RISK ***":i.riskLevel==="medium"?" * medium risk *":"";return` ${_e(i.startLine,i.endLine)} ${i.shortName} [${i.externalConsumers} consumers]${r}`}))),e.complexity&&(n.push(` Complexity: ${Fe(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}`)),hi(kn(n,t))}function dU(e){let t=e.history;if(!t.available||!t.file)return[];let n=[];if(t.churn){let i=t.churn.fixChanges>0?`, ${t.churn.fixChanges} in fix commits`:"";n.push(` Churn: ${t.churn.changes} change(s) in recent history${i}`)}for(let i of t.coChangePartners)n.push(` Usually changes with: ${i.file} (${i.together}x, ${Math.round(i.confidence*100)}%)`);return t.suppressionsInFile>0&&n.push(` Detector suppressions in file: ${t.suppressionsInFile} (accepted findings \u2014 read the reasons before refactoring)`),n}function mU(e){let t=e.warnings.map(i=>` ${i}`);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(i=>i.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 kn(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function hi(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function sd(e){return e?"yes":"no"}var wx=["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","locality-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"],pU=[Sx,Rx,xx,Fa,vx,kx,Cx],Px=pU.flat(),fU=new Map(Px.map(e=>[e.id,e]));for(let e of Px)if(!wx.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var ur=wx.map(e=>gU(e));function gU(e){let t=fU.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var hU=ur.slice(0,ad("plan-context")),yU=ur.slice(Ta("drift"),ad("self-audit")),bU=ur.slice(Ta("convergence"),ad("slice")),SU=ur.slice(Ta("redundant-reexports")),Ix=[{id:"reindex",command:"reindex",description:"Index the codebase and convert to SQLite",options:[h("-l, --language <lang>","Index only this language (can be repeated)",uo,[]),h("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),h("--force","Rebuild even if source inputs are unchanged"),h("--allow-partial","Write an incomplete index when one or more detected languages fail"),h("--indexer-concurrency <n>","Number of language indexers to run at once",mo)],renderShape:"custom",docs:E("Indexing",["scip-query reindex"]),handler:SS},{id:"augment-sources",command:"augment-sources",description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:E("Indexing"),handler:xS},{id:"augment-vue",command:"augment-vue",description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[h("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:E("Indexing"),handler:CS},...hU,{id:ia,command:ia,description:"Internal diff-impact batch worker",hidden:!0,options:[h("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:vS},{id:"diff-impact",command:"diff-impact",description:"Compute changed symbols and downstream consumers from current git diff",options:j([h("--base <ref>","Git ref to diff against (default: HEAD)")]),renderShape:"custom",docs:E("Impact"),handler:RS},...yU,{id:lo,command:lo,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:kS},{id:"health",command:"health",description:"Composite codebase health report with prioritized action list",options:[h("-s, --scope <path>","Limit to files matching path"),h("--full","Compatibility flag; health already runs unbounded candidate analyses by default"),h("--json","Output as JSON for programmatic consumption"),h("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),h("--write-baseline","Snapshot current finding identities to the baseline file")],renderShape:"custom",docs:E("Health",["scip-query health --json","scip-query health --baseline"]),handler:wS},{id:"bench",command:"bench",description:"Benchmark indexing and command runtimes for this repository",options:[h("--json","Output as JSON for programmatic consumption"),h("--cold-index","Temporarily clear this project index cache and measure a cold rebuild"),h("--include-heavy","Include expensive full-detector commands in the command matrix"),h("--command <cmd>","Benchmark a specific scip-query command (can be repeated)",uo,[]),h("--timeout-ms <n>","Per-command timeout in milliseconds",mo,18e4),h("--progress","Print benchmark command start/finish progress to stderr"),h("--profile","Enable low-overhead phase profiling in benchmarked commands"),h("--profile-out <path>","Append benchmark and phase profile events as JSONL")],renderShape:"custom",docs:E("Maintenance",["scip-query bench","scip-query bench --json --cold-index"]),handler:PS},...bU,{id:"install-skills",command:"install-skills",description:`Install skills (${Zu.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:E("Maintenance"),handler:DS},{id:"setup-hooks",command:"setup-hooks",description:"Install or refresh project-local Codex and Claude Code lifecycle hooks",options:[h("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:E("Maintenance",["scip-query setup-hooks","scip-query setup-hooks --json"]),handler:ES},{id:"hook-context",command:"hook-context",description:"Internal agent lifecycle hook context renderer",hidden:!0,renderShape:"custom",handler:Gb},{id:"hook-stop",command:"hook-stop",description:"Internal agent Stop hook wrapper for diff-gate",hidden:!0,renderShape:"custom",handler:Kb},{id:"check-deps",command:"check-deps",description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:E("Maintenance"),handler:NS},{id:"capabilities",command:"capabilities",description:"Report which evidence and verification capabilities are available in this project",options:[h("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:E("Maintenance"),handler:FS},{id:"capability-matrix",command:"capability-matrix",description:"Report the evidence and verification capability matrix by language",options:[h("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:E("Maintenance"),handler:TS},...SU,{id:"init",command:"init",description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:E("Maintenance"),handler:AS},{id:"config-validate",command:"config-validate",description:"Validate .scipquery.json, including structured suppressions and declared coupling groups",options:[h("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:E("Maintenance",["scip-query config-validate"]),handler:MS},{id:"suppress",command:"suppress <id>",description:"Record an accepted finding in .scipquery.json with a required reason",options:j([h("--reason <text>","Required human reason for accepting the finding"),h("--check <check>","Optional detector/check name to narrow the suppression"),h("--file <path>","Optional file path to narrow the suppression"),h("--expires-at <iso>","Optional ISO date after which the suppression expires")]),renderShape:"custom",docs:E("Maintenance",['scip-query suppress SQABC123DEF456 --reason "intentional boundary"']),handler:$S},{id:"doctor",command:"doctor",description:"Diagnose config, index freshness, dependency readiness, and project capabilities",options:[h("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:E("Maintenance"),handler:jS},{id:"setup",command:"setup",description:"Bootstrap this project: install agent skills, refresh the index, verify capabilities, and report health",options:j([h("--git-hook","Also install a git pre-commit hook that runs diff-gate")]),renderShape:"custom",docs:E("Maintenance",["scip-query setup","scip-query setup --json"]),handler:HS},{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:[h("--git-hook","Also install a git pre-commit hook that runs diff-gate")],renderShape:"custom",docs:E("Maintenance",["scip-query setup-agent","scip-query setup-agent --git-hook"]),handler:BS},{id:"setup-ci",command:"setup-ci",description:"Write a GitHub Actions workflow that runs scip-query reindex and diff-gate on pull requests",options:[h("--force","Overwrite an existing workflow"),h("--dry-run","Print the workflow without writing it")],renderShape:"custom",docs:E("Maintenance",["scip-query setup-ci"]),handler:VS},{id:"watch",command:"watch",description:"Watch for file changes and reindex automatically",options:[h("--debounce <ms>","Ms to wait after last change (default: 30000)",sa),h("--cooldown <ms>","Min ms between reindexes (default: 60000)",sa),h("--git-poll <ms>","Ms between Git HEAD/index checks (default: 2000)",sa)],renderShape:"custom",docs:E("Maintenance"),handler:qS},{id:"status",command:"status",description:"Show index status for this project",options:[h("--json","Output as JSON for programmatic consumption"),h("--capabilities","Include the project capability matrix")],renderShape:"custom",docs:E("Maintenance"),handler:US}];function Ta(e){let t=ur.findIndex(n=>n.id===e);if(t<0)throw new Error(`Ordered query command descriptor is missing: ${e}`);return t}function ad(e){return Ta(e)+1}function Lx(e,t){return t.map(n=>{let i=n.hidden?e.command(n.command,{hidden:!0}):e.command(n.command);i.description(n.description);for(let r of n.arguments??[])i.argument(r.name);for(let r of n.options??[])r.parser&&Object.hasOwn(r,"defaultValue")?i.option(r.flags,r.description,r.parser,r.defaultValue):r.parser?i.option(r.flags,r.description,r.parser):Object.hasOwn(r,"defaultValue")?i.option(r.flags,r.description,r.defaultValue):i.option(r.flags,r.description);return i.action(async(...r)=>{try{await n.handler(...r)}catch(o){xU(o)}}),{descriptor:n,command:i}})}function xU(e){let t=e instanceof Error?e.message:String(e);console.error(`error: ${t}`),process.exitCode=1}import{existsSync as CU,mkdirSync as vU,readFileSync as RU,writeFileSync as kU}from"fs";import{homedir as wU}from"os";import{join as _a}from"path";var PU=1440*60*1e3,Ex="update-check.json",IU="https://registry.npmjs.org/scip-query/latest";async function Nx(e={}){let t=e.env??process.env;if(t.SCIP_QUERY_UPDATE_CHECK==="0"||t.NO_UPDATE_NOTIFIER)return;let n=e.cacheDir??EU(t),i=e.now??Date.now(),r=e.currentVersion??na,o=NU(n),s=o&&i-o.checkedAt<PU?o.latestVersion:await FU(n,e.fetchLatestVersion??_U,i);if(!s||!DU(s,r))return;(e.writeNotice??(c=>console.error(c)))(LU(r,s))}function LU(e,t){return[`scip-query update available: ${e} -> ${t}.`,"Agent: tell your human to update with: npm install -g scip-query@latest",""].join(`
1049
+ `)}function DU(e,t){let n=Dx(e),i=Dx(t);if(!n||!i)return e!==t;for(let r=0;r<n.length;r++){let o=n[r]-i[r];if(o>0)return!0;if(o<0)return!1}return!1}function EU(e){let t=e.XDG_CACHE_HOME||_a(wU(),".cache");return _a(t,"scip-query")}function NU(e){let t=_a(e,Ex);if(!CU(t))return null;try{let n=JSON.parse(RU(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 FU(e,t,n){let i;try{i=await t()}catch{i=null}return TU(e,{checkedAt:n,latestVersion:i}),i}function TU(e,t){try{vU(e,{recursive:!0}),kU(_a(e,Ex),`${JSON.stringify(t,null,2)}
1050
+ `)}catch{}}async function _U(){let e=await fetch(IU,{signal:AbortSignal.timeout(1e3)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}function Dx(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}Aa.name("scip-query").description("Language-agnostic code intelligence CLI powered by SCIP indexes").version(na);Lx(Aa,Ix);Aa.hook("preAction",async()=>{await Nx()});MU()&&await Aa.parseAsync();function MU(){if(!process.argv[1])return!1;let e=AU(import.meta.url);try{return Fx(e)===Fx(process.argv[1])}catch{return e===process.argv[1]}}export{Aa as program,tr as renderHeuristicNotice};
1026
1051
  //# sourceMappingURL=cli.js.map